@cosmicdrift/kumiko-server-runtime 0.159.1 → 0.160.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-server-runtime",
3
- "version": "0.159.1",
3
+ "version": "0.160.0",
4
4
  "description": "Production server-boot runtime for Kumiko apps: connections, schema-drift-gate, seeds, lifecycle, graceful shutdown. Symmetric to kumiko-dev-server's runDevApp, without dev/scaffold/codegen tooling.",
5
5
  "license": "BUSL-1.1",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -72,8 +72,8 @@
72
72
  }
73
73
  },
74
74
  "dependencies": {
75
- "@cosmicdrift/kumiko-bundled-features": "0.159.1",
76
- "@cosmicdrift/kumiko-framework": "0.159.1",
75
+ "@cosmicdrift/kumiko-bundled-features": "0.160.0",
76
+ "@cosmicdrift/kumiko-framework": "0.160.0",
77
77
  "temporal-polyfill": "^0.3.2"
78
78
  },
79
79
  "publishConfig": {
@@ -0,0 +1,166 @@
1
+ // In-process buildProdBundle — covers Bun.build + HTML render + build-info
2
+ // in the same process (CLI subprocess tests do not contribute to lcov).
3
+
4
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
5
+ import { existsSync } from "node:fs";
6
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
7
+ import { tmpdir } from "node:os";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { buildProdBundle } from "../build-prod-bundle";
11
+
12
+ const __dirname = dirname(fileURLToPath(import.meta.url));
13
+ const REPO_ROOT = resolve(__dirname, "../../../..");
14
+
15
+ describe("buildProdBundle in-process (Bun.build)", () => {
16
+ let tmp = "";
17
+
18
+ beforeEach(async () => {
19
+ tmp = await mkdtemp(join(tmpdir(), "kumiko-build-inproc-"));
20
+ });
21
+
22
+ afterEach(async () => {
23
+ await rm(tmp, { recursive: true, force: true });
24
+ });
25
+
26
+ async function writeMinimalClientApp(opts?: { html?: string; client?: string }) {
27
+ await mkdir(join(tmp, "src"), { recursive: true });
28
+ await writeFile(
29
+ join(tmp, "src/client.ts"),
30
+ opts?.client ??
31
+ `const root = document.getElementById("root"); if (root) root.textContent = "hi";`,
32
+ );
33
+ await mkdir(join(tmp, "public"), { recursive: true });
34
+ await writeFile(
35
+ join(tmp, "public/index.html"),
36
+ opts?.html ??
37
+ `<!doctype html><html><head></head><body><div id="root"></div><script type="module" src="/client.js"></script></body></html>`,
38
+ );
39
+ await writeFile(join(tmp, "package.json"), `{"name":"inproc-fixture","private":true}`);
40
+ }
41
+
42
+ test("client.ts → hashed bundle, manifest, build-info, injected script", async () => {
43
+ await writeMinimalClientApp();
44
+
45
+ const result = await buildProdBundle({ cwd: tmp, stylesheet: false });
46
+
47
+ expect(result.manifest["client.js"]).toMatch(/^\/assets\/client-[a-z0-9]+\.js$/);
48
+ expect(result.buildInfo?.id).toMatch(/^[0-9a-f]{12}$/);
49
+ expect(existsSync(join(tmp, "dist/build-info.json"))).toBe(true);
50
+
51
+ const html = await readFile(join(tmp, "dist/index.html"), "utf8");
52
+ expect(html).toContain(`src="${result.manifest["client.js"]}"`);
53
+ expect(html).toContain("__KUMIKO_BUILD__");
54
+
55
+ const assetPath = join(tmp, "dist", result.manifest["client.js"] ?? "");
56
+ expect(existsSync(assetPath)).toBe(true);
57
+ expect(await readFile(assetPath, "utf8")).toContain('"hi"');
58
+ });
59
+
60
+ test("missing index.html → error with template snippet", async () => {
61
+ await mkdir(join(tmp, "src"), { recursive: true });
62
+ await writeFile(join(tmp, "src/client.ts"), `console.log("hi");`);
63
+ await writeFile(join(tmp, "package.json"), `{"name":"no-html","private":true}`);
64
+
65
+ await expect(buildProdBundle({ cwd: tmp, stylesheet: false })).rejects.toThrow(
66
+ /kein index\.html gefunden/,
67
+ );
68
+ });
69
+
70
+ test("index.html without /client.js placeholder → error with snippet", async () => {
71
+ await writeMinimalClientApp({
72
+ html: `<!doctype html><html><body>no script</body></html>`,
73
+ });
74
+
75
+ await expect(buildProdBundle({ cwd: tmp, stylesheet: false })).rejects.toThrow(
76
+ /keinen Entry-Tag für \/client\.js/,
77
+ );
78
+ });
79
+
80
+ test("syntax-broken client → Bun.build rejects", async () => {
81
+ await writeMinimalClientApp({ client: `const x = {{{` });
82
+
83
+ // Bun may throw "Bundle failed" before returning `{ success: false }`.
84
+ await expect(buildProdBundle({ cwd: tmp, stylesheet: false })).rejects.toThrow(
85
+ /Bundle failed|Bun\.build failed/,
86
+ );
87
+ });
88
+
89
+ test("stylesheet override src/styles.css → hashed styles.css in manifest", async () => {
90
+ // Temp under REPO_ROOT so @tailwindcss/cli + tailwindcss peer resolve
91
+ // (same constraint as renderer-web-css-relocation.integration.test.ts).
92
+ const dir = await mkdtemp(join(REPO_ROOT, ".inproc-styles-"));
93
+ const cwd = join(dir, "app");
94
+ try {
95
+ await mkdir(join(cwd, "src"), { recursive: true });
96
+ await writeFile(
97
+ join(cwd, "src/client.ts"),
98
+ `const root = document.getElementById("root"); if (root) root.textContent = "hi";`,
99
+ );
100
+ await writeFile(join(cwd, "src/styles.css"), "body { margin: 0; }\n");
101
+ await mkdir(join(cwd, "public"), { recursive: true });
102
+ await writeFile(
103
+ join(cwd, "public/index.html"),
104
+ `<!doctype html><html><head><link rel="stylesheet" href="/styles.css" /></head><body><div id="root"></div><script type="module" src="/client.js"></script></body></html>`,
105
+ );
106
+ await writeFile(join(cwd, "package.json"), `{"name":"inproc-styles","private":true}`);
107
+
108
+ const result = await buildProdBundle({ cwd, stylesheet: "src/styles.css" });
109
+
110
+ expect(result.manifest["styles.css"]).toMatch(/^\/assets\/styles-[a-z0-9]+\.css$/);
111
+ const cssPath = join(cwd, "dist", result.manifest["styles.css"] ?? "");
112
+ expect(existsSync(cssPath)).toBe(true);
113
+ expect(await readFile(cssPath, "utf8")).toMatch(/margin:\s*0/);
114
+
115
+ const html = await readFile(join(cwd, "dist/index.html"), "utf8");
116
+ expect(html).toContain(`href="${result.manifest["styles.css"]}"`);
117
+ expect(html).not.toContain('href="/styles.css"');
118
+ } finally {
119
+ await rm(dir, { recursive: true, force: true });
120
+ }
121
+ });
122
+
123
+ test("missing stylesheet override → tailwind rejects", async () => {
124
+ const dir = await mkdtemp(join(REPO_ROOT, ".inproc-styles-miss-"));
125
+ const cwd = join(dir, "app");
126
+ try {
127
+ await mkdir(join(cwd, "src"), { recursive: true });
128
+ await writeFile(join(cwd, "src/client.ts"), `console.log("hi");`);
129
+ await mkdir(join(cwd, "public"), { recursive: true });
130
+ await writeFile(
131
+ join(cwd, "public/index.html"),
132
+ `<!doctype html><html><body><div id="root"></div><script type="module" src="/client.js"></script></body></html>`,
133
+ );
134
+ await writeFile(join(cwd, "package.json"), `{"name":"inproc-styles-miss","private":true}`);
135
+
136
+ await expect(buildProdBundle({ cwd, stylesheet: "src/missing-theme.css" })).rejects.toThrow(
137
+ /tailwind|Bundle failed|tailwindcss/i,
138
+ );
139
+ } finally {
140
+ await rm(dir, { recursive: true, force: true });
141
+ }
142
+ });
143
+
144
+ test("multi-entry client-admin + client-public → two hashed bundles", async () => {
145
+ await mkdir(join(tmp, "src"), { recursive: true });
146
+ await writeFile(join(tmp, "src/client-admin.ts"), `console.log("admin");`);
147
+ await writeFile(join(tmp, "src/client-public.ts"), `console.log("public");`);
148
+ await mkdir(join(tmp, "public"), { recursive: true });
149
+ await writeFile(
150
+ join(tmp, "public/index.html"),
151
+ `<!doctype html><html><body><script type="module" src="/client-public.js"></script></body></html>`,
152
+ );
153
+ await writeFile(
154
+ join(tmp, "admin.html"),
155
+ `<!doctype html><html><body><script type="module" src="/client-admin.js"></script></body></html>`,
156
+ );
157
+ await writeFile(join(tmp, "package.json"), `{"name":"multi-inproc","private":true}`);
158
+
159
+ const result = await buildProdBundle({ cwd: tmp, stylesheet: false });
160
+
161
+ expect(result.manifest["client-admin.js"]).toMatch(/^\/assets\/client-admin-/);
162
+ expect(result.manifest["client-public.js"]).toMatch(/^\/assets\/client-public-/);
163
+ expect(existsSync(join(tmp, "dist/admin.html"))).toBe(true);
164
+ expect(existsSync(join(tmp, "dist/index.html"))).toBe(true);
165
+ });
166
+ });
@@ -0,0 +1,158 @@
1
+ // Dry-run + bootErrorReporter paths — no DB/Redis. envSource avoids process.exit(0).
2
+
3
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
4
+ import {
5
+ createBooleanField,
6
+ createEntity,
7
+ createTextField,
8
+ defineFeature,
9
+ } from "@cosmicdrift/kumiko-framework/engine";
10
+ import { composeEnvSchema, KumikoBootError } from "@cosmicdrift/kumiko-framework/env";
11
+ import { z } from "zod";
12
+ import { runProdApp } from "../run-prod-app";
13
+
14
+ const probeEntity = createEntity({
15
+ fields: {
16
+ name: createTextField({ required: true }),
17
+ active: createBooleanField({ default: true }),
18
+ },
19
+ table: "dry_run_probe",
20
+ });
21
+
22
+ const probeFeature = defineFeature("dry-run-probe", (r) => {
23
+ r.entity("widget", probeEntity);
24
+ r.envSchema(z.object({ DRY_RUN_PROBE: z.string().optional().describe("probe var") }));
25
+ r.queryHandler({
26
+ name: "ping",
27
+ schema: z.object({}),
28
+ access: { roles: ["anonymous"] },
29
+ handler: async () => ({ pong: true }),
30
+ });
31
+ });
32
+
33
+ const CLEARED = ["DATABASE_URL", "REDIS_URL", "JWT_SECRET", "PORT"] as const;
34
+
35
+ describe("runProdApp dry-run / bootErrorReporter", () => {
36
+ const saved: Record<string, string | undefined> = {};
37
+
38
+ beforeEach(() => {
39
+ for (const k of CLEARED) {
40
+ saved[k] = process.env[k];
41
+ delete process.env[k];
42
+ }
43
+ });
44
+
45
+ afterEach(() => {
46
+ for (const k of CLEARED) {
47
+ if (saved[k] === undefined) delete process.env[k];
48
+ else process.env[k] = saved[k];
49
+ }
50
+ });
51
+
52
+ test("KUMIKO_DRY_RUN_ENV=human + envSource → render + dry-run handle (no exit)", async () => {
53
+ const logs: string[] = [];
54
+ const originalLog = console.log;
55
+ console.log = (...args: unknown[]) => {
56
+ logs.push(args.map(String).join(" "));
57
+ };
58
+ const envSchema = composeEnvSchema({ features: [probeFeature] });
59
+ let handle: Awaited<ReturnType<typeof runProdApp>>;
60
+ try {
61
+ handle = await runProdApp({
62
+ features: [probeFeature],
63
+ envSchema,
64
+ autoListen: false,
65
+ migrations: false,
66
+ envSource: { KUMIKO_DRY_RUN_ENV: "human" },
67
+ });
68
+ } finally {
69
+ console.log = originalLog;
70
+ }
71
+
72
+ expect(logs.some((l) => l.includes("DRY_RUN_PROBE") || l.includes("Optional"))).toBe(true);
73
+ const res = await handle!.fetch(new Request("http://test/"));
74
+ expect(res.status).toBe(503);
75
+ expect(await res.text()).toBe("dry-run");
76
+ await handle!.stop();
77
+ });
78
+
79
+ test("KUMIKO_DRY_RUN_ENV=json → structured dry-run output", async () => {
80
+ const logs: string[] = [];
81
+ const originalLog = console.log;
82
+ console.log = (...args: unknown[]) => {
83
+ logs.push(args.map(String).join(" "));
84
+ };
85
+ const envSchema = composeEnvSchema({ features: [probeFeature] });
86
+ try {
87
+ const handle = await runProdApp({
88
+ features: [probeFeature],
89
+ envSchema,
90
+ autoListen: false,
91
+ migrations: false,
92
+ envSource: { KUMIKO_DRY_RUN_ENV: "json" },
93
+ });
94
+ await handle.stop();
95
+ } finally {
96
+ console.log = originalLog;
97
+ }
98
+ const joined = logs.join("\n");
99
+ expect(joined).toContain("required");
100
+ expect(joined).toContain("optional");
101
+ });
102
+
103
+ test("unrecognized KUMIKO_DRY_RUN_ENV warns then hits envSchema parse", async () => {
104
+ const warnings: string[] = [];
105
+ const originalWarn = console.warn;
106
+ console.warn = (...args: unknown[]) => {
107
+ warnings.push(args.map(String).join(" "));
108
+ };
109
+ const envSchema = composeEnvSchema({
110
+ features: [],
111
+ extend: z.object({ MUST_HAVE: z.string().describe("required for test") }),
112
+ });
113
+ try {
114
+ await expect(
115
+ runProdApp({
116
+ features: [probeFeature],
117
+ envSchema,
118
+ autoListen: false,
119
+ migrations: false,
120
+ envSource: { KUMIKO_DRY_RUN_ENV: "not-a-real-mode" },
121
+ bootErrorReporter: (err) => {
122
+ throw err;
123
+ },
124
+ }),
125
+ ).rejects.toBeInstanceOf(KumikoBootError);
126
+ } finally {
127
+ console.warn = originalWarn;
128
+ }
129
+ expect(warnings.some((w) => w.includes("unrecognized"))).toBe(true);
130
+ });
131
+
132
+ test("bootErrorReporter receives KumikoBootError instead of process.exit", async () => {
133
+ const envSchema = composeEnvSchema({
134
+ features: [],
135
+ extend: z.object({ MUST_HAVE: z.string().describe("required for test") }),
136
+ });
137
+ let reported: KumikoBootError | undefined;
138
+ await expect(
139
+ runProdApp({
140
+ features: [probeFeature],
141
+ envSchema,
142
+ autoListen: false,
143
+ migrations: false,
144
+ envSource: {
145
+ // no MUST_HAVE → parseEnv throws KumikoBootError
146
+ DATABASE_URL: "postgres://x",
147
+ REDIS_URL: "redis://x",
148
+ },
149
+ bootErrorReporter: (err) => {
150
+ reported = err;
151
+ throw err;
152
+ },
153
+ }),
154
+ ).rejects.toBeInstanceOf(KumikoBootError);
155
+ expect(reported).toBeInstanceOf(KumikoBootError);
156
+ expect(reported!.errors.some((e) => e.name === "MUST_HAVE")).toBe(true);
157
+ });
158
+ });
@@ -0,0 +1,148 @@
1
+ // Unit coverage for mimeTypeFor + hostDispatch edge in buildStaticFallback.
2
+
3
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
4
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import {
8
+ buildStaticFallback,
9
+ mimeTypeFor,
10
+ readStaticFile,
11
+ serveDiskFile,
12
+ } from "../run-prod-app-static-files";
13
+
14
+ describe("mimeTypeFor", () => {
15
+ const cases: ReadonlyArray<readonly [string, string]> = [
16
+ ["x.html", "text/html; charset=utf-8"],
17
+ ["x.js", "text/javascript; charset=utf-8"],
18
+ ["x.mjs", "text/javascript; charset=utf-8"],
19
+ ["x.css", "text/css; charset=utf-8"],
20
+ ["x.json", "application/json; charset=utf-8"],
21
+ ["x.svg", "image/svg+xml"],
22
+ ["x.png", "image/png"],
23
+ ["x.jpg", "image/jpeg"],
24
+ ["x.jpeg", "image/jpeg"],
25
+ ["x.ico", "image/x-icon"],
26
+ ["x.txt", "text/plain; charset=utf-8"],
27
+ ["x.xml", "application/xml; charset=utf-8"],
28
+ ["x.webmanifest", "application/manifest+json"],
29
+ ["x.bin", "application/octet-stream"],
30
+ ["noext", "application/octet-stream"],
31
+ ];
32
+
33
+ for (const [path, mime] of cases) {
34
+ test(`${path} → ${mime}`, () => {
35
+ expect(mimeTypeFor(path)).toBe(mime);
36
+ });
37
+ }
38
+ });
39
+
40
+ describe("readStaticFile / serveDiskFile", () => {
41
+ let tmp = "";
42
+
43
+ beforeEach(async () => {
44
+ tmp = await mkdtemp(join(tmpdir(), "kumiko-static-"));
45
+ });
46
+
47
+ afterEach(async () => {
48
+ await rm(tmp, { recursive: true, force: true });
49
+ });
50
+
51
+ test("readStaticFile returns bytes+mime; ENOENT → undefined", async () => {
52
+ const path = join(tmp, "a.css");
53
+ await writeFile(path, "body{}");
54
+ const file = await readStaticFile(path);
55
+ expect(file?.mime).toBe("text/css; charset=utf-8");
56
+ expect(new TextDecoder().decode(file!.bytes)).toBe("body{}");
57
+ expect(await readStaticFile(join(tmp, "missing.css"))).toBeUndefined();
58
+ });
59
+
60
+ test("serveDiskFile sets content-type from mime", async () => {
61
+ const path = join(tmp, "a.svg");
62
+ await writeFile(path, "<svg/>");
63
+ const file = await readStaticFile(path);
64
+ const res = serveDiskFile(new Request("http://t/a.svg"), "/a.svg", file!);
65
+ expect(res.headers.get("content-type")).toBe("image/svg+xml");
66
+ expect(await res.text()).toBe("<svg/>");
67
+ });
68
+ });
69
+
70
+ describe("buildStaticFallback hostDispatch", () => {
71
+ let tmp = "";
72
+
73
+ beforeEach(async () => {
74
+ tmp = await mkdtemp(join(tmpdir(), "kumiko-fallback-"));
75
+ });
76
+
77
+ afterEach(async () => {
78
+ await rm(tmp, { recursive: true, force: true });
79
+ });
80
+
81
+ test("hostDispatch html pointing at missing file → 500", async () => {
82
+ const handler = buildStaticFallback(
83
+ () => new Response("api-404", { status: 404 }),
84
+ tmp,
85
+ "{}",
86
+ () => ({ kind: "html", file: "gone.html" }),
87
+ );
88
+ const res = await handler(new Request("http://t/"));
89
+ expect(res.status).toBe(500);
90
+ expect(await res.text()).toContain("hostDispatch: file not found: gone.html");
91
+ });
92
+
93
+ test("hostDispatch not-found → 404; redirect → 302", async () => {
94
+ const notFound = buildStaticFallback(
95
+ () => new Response("x", { status: 404 }),
96
+ tmp,
97
+ "{}",
98
+ () => ({ kind: "not-found" }),
99
+ );
100
+ expect((await notFound(new Request("http://t/"))).status).toBe(404);
101
+
102
+ const redirect = buildStaticFallback(
103
+ () => new Response("x", { status: 404 }),
104
+ tmp,
105
+ "{}",
106
+ () => ({ kind: "redirect", to: "https://example.com/", status: 301 }),
107
+ );
108
+ const res = await redirect(new Request("http://t/"));
109
+ expect(res.status).toBe(301);
110
+ expect(res.headers.get("location")).toBe("https://example.com/");
111
+ });
112
+
113
+ test("/api/* always hits apiHandler", async () => {
114
+ const handler = buildStaticFallback(() => new Response("from-api", { status: 200 }), tmp, "{}");
115
+ const res = await handler(new Request("http://t/api/query", { method: "POST" }));
116
+ expect(res.status).toBe(200);
117
+ expect(await res.text()).toBe("from-api");
118
+ });
119
+
120
+ test("serves disk asset under staticDir", async () => {
121
+ await writeFile(join(tmp, "logo.png"), "PNGDATA");
122
+ const handler = buildStaticFallback(() => new Response("404", { status: 404 }), tmp, "{}");
123
+ const res = await handler(new Request("http://t/logo.png"));
124
+ expect(res.status).toBe(200);
125
+ expect(res.headers.get("content-type")).toBe("image/png");
126
+ expect(await res.text()).toBe("PNGDATA");
127
+ });
128
+
129
+ test("hostDispatch html with CSP + Vary: Host", async () => {
130
+ await writeFile(join(tmp, "tenant.html"), "<!doctype html><html><body>ok</body></html>");
131
+ const handler = buildStaticFallback(
132
+ () => new Response("404", { status: 404 }),
133
+ tmp,
134
+ '{"screens":[]}',
135
+ () => ({
136
+ kind: "html",
137
+ file: "tenant.html",
138
+ injectSchema: false,
139
+ csp: "default-src 'self'",
140
+ }),
141
+ );
142
+ const res = await handler(new Request("http://t/", { headers: { host: "a.example" } }));
143
+ expect(res.status).toBe(200);
144
+ expect(res.headers.get("vary")).toBe("Host");
145
+ expect(res.headers.get("content-security-policy")).toBe("default-src 'self'");
146
+ expect(await res.text()).toContain("ok");
147
+ });
148
+ });