Files
WRNexusJS/packages/csr/test/api-call.test.ts
T
ClintchizandClaude Opus 5 b5029889a5 fix: address all seven final-gate findings for typed api blocks
B1: qualify each generated __wrn_api_check_* assertion name with a short
hash of the page's path (relative to app/, for reproducibility across
checkouts) so two pages declaring a same-named block no longer collide
with an identical type alias (TS2300).

B2: skip assertion emission for any block that is not client-mode, or
that has zero declared request fields. ssr sectioned blocks can never
declare a request and always fell back to Record<string, never>, whose
keyof is `string` -- making the key-exactness arm of AssertAssignable
evaluate to false unconditionally (TS2344) on every ssr sectioned block
regardless of correctness. Chose to skip both non-client blocks and
zero-field client blocks, since neither has anything meaningful to
assert type-safety about.

B3: only resolve the endpoint's input (query params / ctx.req.json())
when the endpoint declares an input schema. Previously the router-set
fix accidentally read the request body unconditionally, so a handler
with no input schema that parses the request itself hit
ERR_BODY_ALREADY_USED.

B4: run response/error bodies in client-mode api blocks through
eraseFunctionTypes, matching every other browser-bound body in
client-codegen.ts, so a TypeScript-only construct inside one (e.g. an
annotated locally-declared function) doesn't reach the .mjs artifact.

B5: only exclude "api" from state/prop destructuring in the generated
browser module when the page actually has client-mode api blocks (i.e.
there is a real `api` binding to shadow). Previously "api" was always
excluded, so a page with `state api` and no api blocks got an
undeclared `api` reference (ReferenceError) in client code.

B6: prefix each emitted assertion with `export`, so it isn't flagged as
an unused local under a downstream project's noUnusedLocals (TS6196).

B7: wrnexusCallApi now resolves with undefined for an ok 204/205
response, or an ok response with an empty/unparseable body, instead of
rejecting with "Response was not valid JSON" -- matching the spec's
failure table (error path only for non-2xx, network failure, or an
actually unparseable body on a non-empty response).

Regenerated examples/basic-app's generated types and editor bundles to
match. Confirmed the example's type gate still fails when an
unaccepted field is added to a request body, and passes cleanly
otherwise.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 20:38:22 +05:30

129 lines
4.7 KiB
TypeScript

import { expect, test, beforeEach } from "bun:test";
import { Window } from "happy-dom";
import { REACTIVE_RUNTIME } from "../src/reactive-runtime.ts";
import { restoreGlobalsAfterAll } from "./global-restore.ts";
const REPLACED_GLOBALS = ["window", "document", "location", "fetch", "NodeFilter"];
restoreGlobalsAfterAll(REPLACED_GLOBALS);
beforeEach(() => {
for (const name of REPLACED_GLOBALS) delete (globalThis as Record<string, unknown>)[name];
});
interface Call {
url: string;
init: RequestInit;
}
/** Mount the runtime with a recording fetch and return its callApi plus the calls made. */
function harness(response: { status: number; payload: unknown }) {
const win = new Window() as unknown as Window & Record<string, unknown>;
win.document.body.innerHTML = `<div data-scope="x: 1"></div>`;
const calls: Call[] = [];
(globalThis as Record<string, unknown>).window = win;
(globalThis as Record<string, unknown>).document = win.document;
(globalThis as Record<string, unknown>).location = win.location;
(globalThis as Record<string, unknown>).NodeFilter = (
win as unknown as { NodeFilter: unknown }
).NodeFilter;
(globalThis as Record<string, unknown>).fetch = (url: string, init: RequestInit) => {
calls.push({ url, init });
return Promise.resolve({
ok: response.status >= 200 && response.status < 300,
status: response.status,
json: () => Promise.resolve(response.payload),
});
};
(0, eval)(REACTIVE_RUNTIME);
const callApi = (win as unknown as { __wrnexusCallApi: (...args: any[]) => Promise<any> })
.__wrnexusCallApi;
return { callApi, calls, win };
}
test("GET builds a query string and omits undefined fields", async () => {
const { callApi, calls } = harness({ status: 200, payload: { users: [] } });
await callApi("/api/users", "GET", { name: "Ajay", age: undefined });
expect(calls[0]!.url).toBe("/api/users?name=Ajay");
expect(calls[0]!.init.method).toBe("GET");
expect(calls[0]!.init.body).toBeUndefined();
});
test("POST sends a JSON body", async () => {
const { callApi, calls } = harness({ status: 200, payload: { ok: true } });
await callApi("/api/users", "POST", { name: "Ajay" });
expect(calls[0]!.url).toBe("/api/users");
expect(calls[0]!.init.body).toBe(JSON.stringify({ name: "Ajay" }));
expect((calls[0]!.init.headers as Record<string, string>)["content-type"]).toBe(
"application/json",
);
});
test("a non-GET request carries the CSRF token from the cookie", async () => {
const { callApi, calls, win } = harness({ status: 200, payload: {} });
win.document.cookie = "wrn-csrf=token-123";
await callApi("/api/users", "POST", {});
expect((calls[0]!.init.headers as Record<string, string>)["x-csrf-token"]).toBe("token-123");
});
test("a 2xx resolves to the parsed payload", async () => {
const { callApi } = harness({ status: 200, payload: { users: [{ name: "Ajay" }] } });
expect(await callApi("/api/users", "GET", {})).toEqual({ users: [{ name: "Ajay" }] });
});
test("a 204 with no body resolves to undefined instead of rejecting", async () => {
const win = new Window() as unknown as Window & Record<string, unknown>;
win.document.body.innerHTML = `<div data-scope="x: 1"></div>`;
(globalThis as Record<string, unknown>).window = win;
(globalThis as Record<string, unknown>).document = win.document;
(globalThis as Record<string, unknown>).location = win.location;
(globalThis as Record<string, unknown>).NodeFilter = (
win as unknown as { NodeFilter: unknown }
).NodeFilter;
(globalThis as Record<string, unknown>).fetch = () =>
Promise.resolve({
ok: true,
status: 204,
json: () => Promise.reject(new SyntaxError("Unexpected end of JSON input")),
});
(0, eval)(REACTIVE_RUNTIME);
const callApi = (win as unknown as { __wrnexusCallApi: (...args: any[]) => Promise<any> })
.__wrnexusCallApi;
await expect(callApi("/api/users", "DELETE", {})).resolves.toBeUndefined();
});
test("a 2xx with an empty/unparseable body resolves to undefined", async () => {
const { callApi } = harness({ status: 200, payload: undefined });
(globalThis as Record<string, unknown>).fetch = () =>
Promise.resolve({
ok: true,
status: 200,
json: () => Promise.reject(new SyntaxError("Unexpected end of JSON input")),
});
await expect(callApi("/api/users", "GET", {})).resolves.toBeUndefined();
});
test("a non-2xx rejects with status, message and data", async () => {
const { callApi } = harness({ status: 400, payload: { error: "Bad filter" } });
const failure = await callApi("/api/users", "GET", {}).catch(
(error: Error & { status?: number; data?: unknown }) => error,
);
expect(failure.status).toBe(400);
expect(failure.message).toContain("Bad filter");
expect(failure.data).toEqual({ error: "Bad filter" });
});