209 lines · 8.0 KB
/** Shared helpers for the sites e2e scripts. */
import { request as httpRequest } from "node:http";
import { gzipSync } from "node:zlib";

export const HTTP_OK = 200;
const HTTP_CREATED = 201;

/** Prints a progress line; e2e scripts report on stdout. */
export function log(line: string): void {
  process.stdout.write(`${line}\n`);
}

export const FORGE = new URL(process.env.SITES_E2E_URL ?? "http://localhost:3000");
export const DOMAIN = process.env.SITES_DOMAIN ?? "gitforstatic.localhost";

export type Reply = { status: number; headers: Record<string, string | string[] | undefined>; body: string };

export function send(
  host: string,
  path: string,
  init: { method?: string; headers?: Record<string, string>; body?: Uint8Array } = {},
): Promise<Reply> {
  return new Promise((resolve, reject) => {
    const req = httpRequest(
      {
        host: FORGE.hostname,
        port: FORGE.port || 80,
        path,
        method: init.method ?? "GET",
        headers: { host: `${host}:${FORGE.port}`, ...init.headers },
      },
      (res) => {
        const chunks: Buffer[] = [];
        res.on("data", (chunk: Buffer) => chunks.push(chunk));
        res.on("end", () =>
          resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(chunks).toString() }),
        );
      },
    );
    req.on("error", reject);