test: restore executed and real-tsc coverage lost when the old api-block tests were deleted

Fix round 1: the deleted api-block-*.test.ts files were not fully superseded
by the apis-* siblings as claimed. Ports back, using apis {} fixtures:
- brace-inside-a-string-literal response-section scanner regression test
- type erasure of response/error bodies before browser emission
- client-side response-error-not-swallowed / transport-failure-fallback,
  executed via dynamic import of a generated browser module
- the full SSR execution suite: response payload binding, error section
  status/message/data binding, {#each} failure propagation, all executed
  via dynamic import + a real load/api call chain (not string checks)
- the four real-tsc enforcement tests (matching/wrong-type/extra-field/
  missing-field), plus the B1 cross-page collision guard and the B6
  export-for-noUnusedLocals guard

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-20 08:14:16 +05:30
co-authored by Claude Opus 5
parent 890d6106b3
commit 0ed8351828
4 changed files with 737 additions and 2 deletions
+240
View File
@@ -46,3 +46,243 @@ test("a block with no declared fields gets no assertion", () => {
expect(generated).not.toContain("listAll");
});
test("emits the ApiInput, ApiOutput and AssertAssignable helpers", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string; age?: number } }
response { return data.users }
}`);
generateApplicationTypes(root);
const generated = readFileSync(join(root, "app/types/wrnexus.generated.d.ts"), "utf8");
expect(generated).toContain("type AssertAssignable<");
expect(generated).toContain('type ApiInput<P extends ApiRoute, M> = ApiContracts[P][M]["input"]');
expect(generated).toContain(
'type ApiOutput<P extends ApiRoute, M> = ApiContracts[P][M]["output"]',
);
});
// The per-block assertions live in a plain .ts file, not the .d.ts: `skipLibCheck: true`
// (set repo-wide) exempts .d.ts *contents* from being checked at all, so a `.d.ts` can
// never actually enforce anything here. A real .ts file under app/ is compiled and
// checked normally.
test("emits one assertion per sectioned block, naming its route and method", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string; age?: number } }
response { return data.users }
}`);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
expect(checks).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
expect(checks).toContain('WRNexusGenerated.ApiInput<"/api/users", "POST">');
expect(checks).toContain("name?: string");
expect(checks).toContain("age?: number");
});
test("the api-checks file has no runtime code and is a module", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string } }
response { return data.users }
}`);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
expect(checks).toContain("AUTO-GENERATED");
expect(checks.trim().endsWith("export {};")).toBe(true);
});
test("B1: two pages each declaring a block with the same name do not collide", () => {
const root = mkdtempSync(join(tmpdir(), "wrnexus-apis-types-collide-"));
roots.push(root);
mkdirSync(join(root, "app/pages"), { recursive: true });
mkdirSync(join(root, "app/api"), { recursive: true });
writeFileSync(
join(root, "app/api/users.ts"),
`export const POST = async () => Response.json({ users: [] });\n`,
);
const block = ` searchUsers POST /api/users {
request { body { name?: string } }
response { return data.users }
}`;
writeFileSync(
join(root, "app/pages/one.wrn"),
`page One {\n apis {\n${block}\n }\n\n view { <main>x</main> }\n}\n`,
);
writeFileSync(
join(root, "app/pages/two.wrn"),
`page Two {\n apis {\n${block}\n }\n\n view { <main>x</main> }\n}\n`,
);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const names = [...checks.matchAll(/__wrn_api_check_\S+(?=\s*=)/g)].map((m) => m[0]);
expect(names.length).toBe(2);
expect(new Set(names).size).toBe(2);
});
test("B6: each emitted assertion is exported, so noUnusedLocals cannot flag it", () => {
const root = fixture(` searchUsers POST /api/users {
request { body { name?: string } }
response { return data.users }
}`);
generateApplicationTypes(root);
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const assertionLine = checks
.split(/\r?\n/)
.find((line) => line.includes("__wrn_api_check_") && line.includes("="));
expect(assertionLine).toBeDefined();
expect(assertionLine).toMatch(/^export type __wrn_api_check_/);
});
// --- Real-compiler enforcement tests ---------------------------------------------
//
// Everything above only asserts on the emitted *text*. That proves nothing about
// whether the assertions actually make `tsc` fail — a build that reverted to the
// original inert `never`-based design, or one where `AssertAssignable` is merely
// one-directional (so it misses an *extra* declared field), would pass every test
// above unchanged. These tests instead run the real TypeScript compiler over the
// generated output and assert on its diagnostics.
//
// The fixture endpoint takes a second (body) parameter so `ApiContract`'s fallback
// branch infers a real input type (`{ name: string; email: string }`) instead of
// `unknown` — with `unknown`, `AssertAssignable`'s untyped-route bypass means nothing
// could ever fail, which would make these tests meaningless.
function typedFixture(block: string): string {
const root = mkdtempSync(join(tmpdir(), "wrnexus-apis-types-tsc-"));
roots.push(root);
mkdirSync(join(root, "app/pages"), { recursive: true });
mkdirSync(join(root, "app/api"), { recursive: true });
writeFileSync(
join(root, "app/api/users.ts"),
`export const POST = async (ctx: unknown, body: { name: string; email: string }) => Response.json(body);\n`,
);
writeFileSync(
join(root, "app/pages/search.wrn"),
`page Search {\n apis {\n${block}\n }\n\n view { <main>x</main> }\n}\n`,
);
return root;
}
/**
* Compiles the two generated files (and whatever they reference on disk) with the
* real TypeScript compiler and returns its stdout plus whether it reported any
* diagnostics.
*/
function typecheckGenerated(root: string): { ok: boolean; output: string } {
const dts = join(root, "app/types/wrnexus.generated.d.ts");
const checks = join(root, "app/types/wrnexus.generated.api-checks.ts");
const result = Bun.spawnSync(
[
"bunx",
"tsc",
"--noEmit",
"--strict",
"--skipLibCheck",
"--moduleResolution",
"bundler",
"--target",
"ES2022",
"--module",
"ESNext",
dts,
checks,
],
{ cwd: root, stdout: "pipe", stderr: "pipe" },
);
const output = `${result.stdout?.toString() ?? ""}${result.stderr?.toString() ?? ""}`;
return { ok: result.exitCode === 0, output };
}
const MATCHING_BLOCK = ` searchUsers POST /api/users {
request {
body {
name: string
email: string
}
}
response {
return data
}
}`;
test("tsc: a block whose fields match the contract has no diagnostics", () => {
const root = typedFixture(MATCHING_BLOCK);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(output.trim()).toBe("");
expect(ok).toBe(true);
});
test("tsc: a field with the wrong type fails, naming the block's assertion", () => {
const root = typedFixture(` searchUsers POST /api/users {
request {
body {
name: number
email: string
}
}
response {
return data
}
}`);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(ok).toBe(false);
expect(output).toContain("wrnexus.generated.api-checks.ts");
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const failingLine = Number(output.match(/api-checks\.ts\((\d+),\d+\)/)?.[1]);
expect(checks.split(/\r?\n/)[failingLine - 1]).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
});
test("tsc: an extra field the contract does not accept fails (Finding A regression guard)", () => {
const root = typedFixture(` searchUsers POST /api/users {
request {
body {
name: string
email: string
extra: string
}
}
response {
return data
}
}`);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(ok).toBe(false);
expect(output).toContain("wrnexus.generated.api-checks.ts");
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const failingLine = Number(output.match(/api-checks\.ts\((\d+),\d+\)/)?.[1]);
expect(checks.split(/\r?\n/)[failingLine - 1]).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
});
test("tsc: a missing required field fails", () => {
const root = typedFixture(` searchUsers POST /api/users {
request {
body {
name: string
}
}
response {
return data
}
}`);
generateApplicationTypes(root);
const { ok, output } = typecheckGenerated(root);
expect(ok).toBe(false);
expect(output).toContain("wrnexus.generated.api-checks.ts");
const checks = readFileSync(join(root, "app/types/wrnexus.generated.api-checks.ts"), "utf8");
const failingLine = Number(output.match(/api-checks\.ts\((\d+),\d+\)/)?.[1]);
expect(checks.split(/\r?\n/)[failingLine - 1]).toMatch(/__wrn_api_check_[\w$]*_searchUsers\b/);
});