pi-mono/packages/chord/test/examples/53-app/client.ts
Mario Zechner e9c0ff4d84 feat(chord): Chord v2 is the package's root
src/next is src (the main export), src/next-node is src/node with short subpaths (/http, /workers, /plugins,
/plugins/runtime, /app, /surfaces, /web, /react, /tui, /tui/launcher); the foundations get /json and /watch;
Chord v1 moves to src/old (/old, /old/node) until p2 runs on v2; tests and docs move likewise (test/, docs/,
test/old, docs/old). Durable and env import the foundations from their subpaths.
2026-11-02 22:36:55 +00:00

44 lines
1.4 KiB
TypeScript

// A small HTTP client for examples 53 to 55, standing in for a browser and a command-line client: a request to the
// app on loopback, its status, `Set-Cookie` and JSON body.
import { request } from "node:http";
/** An answer: status, the cookie it set (name=value), JSON body (or text). */
export type Answer = { readonly status: number; readonly cookie: string | undefined; readonly body: unknown };
/** `method path` on the app at `port`, with `headers` and a JSON `body`. */
export function call(
port: number,
method: string,
path: string,
headers: Readonly<Record<string, string>> = {},
body?: unknown,
): Promise<Answer> {
return new Promise((resolve, reject) => {
const sent = request(
{
host: "127.0.0.1",
port,
method,
path,
headers: { ...headers, ...(body === undefined ? {} : { "content-type": "application/json" }) },
},
(response) => {
const chunks: Buffer[] = [];
response.on("data", (chunk: Buffer) => chunks.push(chunk));
response.on("end", () => {
const text = Buffer.concat(chunks).toString();
const type = response.headers["content-type"] ?? "";
const cookie = response.headers["set-cookie"]?.[0]?.split(";")[0];
resolve({
status: response.statusCode ?? 0,
cookie,
body: type.includes("json") ? JSON.parse(text) : text,
});
});
},
);
sent.on("error", reject);
sent.end(body === undefined ? undefined : JSON.stringify(body));
});
}