@kiln-js/cli 0.1.5 → 0.2.0-hotfix

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/dist/index.js CHANGED
@@ -1,16 +1,17 @@
1
- #!/usr/bin/env bun
2
- // @bun
1
+ #!/usr/bin/env node
3
2
 
4
- // src/index.ts
3
+ // packages/cli/src/index.ts
5
4
  import { cac } from "cac";
6
5
 
7
- // src/dev.ts
8
- import http from "http";
6
+ // packages/cli/src/dev.ts
7
+ import fs5 from "node:fs";
8
+ import path8 from "node:path";
9
+ import http from "node:http";
9
10
  import { createServer as createViteServer } from "vite";
10
- import { kiln } from "@kiln-js/vite-plugin";
11
+ import { kiln, buildCacheStats } from "@kiln-js/vite-plugin";
11
12
 
12
- // src/paths.ts
13
- import path from "path";
13
+ // packages/cli/src/paths.ts
14
+ import path from "node:path";
14
15
  var root = process.cwd();
15
16
  var paths = {
16
17
  root,
@@ -21,9 +22,9 @@ var paths = {
21
22
  serverOut: path.resolve(root, "dist/server")
22
23
  };
23
24
 
24
- // src/entries.ts
25
- import fs from "fs";
26
- import path2 from "path";
25
+ // packages/cli/src/entries.ts
26
+ import fs from "node:fs";
27
+ import path2 from "node:path";
27
28
  var EXTENSIONS = ["tsx", "ts", "jsx", "js"];
28
29
  var ENV_TYPES = `// Generated by Kiln. Do not edit.
29
30
  export {};
@@ -51,16 +52,16 @@ function ensureKilnDir() {
51
52
  }
52
53
  function findUserEntry(name) {
53
54
  for (const ext of EXTENSIONS) {
54
- const file = path2.join(paths.root, "app", `${name}.${ext}`);
55
- if (fs.existsSync(file))
56
- return file;
55
+ const file2 = path2.join(paths.root, "app", `${name}.${ext}`);
56
+ if (fs.existsSync(file2)) return file2;
57
57
  }
58
58
  return null;
59
59
  }
60
60
  function writeGenerated(name, source) {
61
61
  ensureKilnDir();
62
62
  const target = path2.join(paths.kilnDir, name);
63
- fs.writeFileSync(target, source);
63
+ const current = fs.existsSync(target) ? fs.readFileSync(target, "utf8") : null;
64
+ if (current !== source) fs.writeFileSync(target, source);
64
65
  return target;
65
66
  }
66
67
  function resolveEntries() {
@@ -74,18 +75,17 @@ function resolveEntries() {
74
75
  };
75
76
  }
76
77
 
77
- // src/env.ts
78
+ // packages/cli/src/env.ts
78
79
  import { loadEnv } from "vite";
79
80
  function loadEnvFiles(mode) {
80
81
  const env = loadEnv(mode, paths.root, "");
81
82
  for (const [key, value] of Object.entries(env)) {
82
- if (process.env[key] === undefined)
83
- process.env[key] = value;
83
+ if (process.env[key] === void 0) process.env[key] = value;
84
84
  }
85
85
  return env;
86
86
  }
87
87
 
88
- // src/log.ts
88
+ // packages/cli/src/log.ts
89
89
  var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
90
90
  var sgr = (open, close) => (s) => useColor ? `\x1B[${open}m${s}\x1B[${close}m` : s;
91
91
  var fg = (r, g, b) => sgr(`38;2;${r};${g};${b}`, "39");
@@ -95,6 +95,7 @@ var colors = {
95
95
  red: sgr("31", "39"),
96
96
  yellow: sgr("33", "39"),
97
97
  cyan: sgr("36", "39"),
98
+ // Kiln palette
98
99
  fire: fg(255, 122, 69),
99
100
  ember: fg(255, 92, 122),
100
101
  mint: fg(94, 234, 212),
@@ -115,8 +116,7 @@ var METHOD_COLORS = {
115
116
  var methodColor = (m) => METHOD_COLORS[m] ?? colors.bold;
116
117
  var statusColor = (s) => s >= 500 ? colors.ember : s >= 400 ? colors.yellow : s >= 300 ? colors.violet : colors.mint;
117
118
  function gradient(text, from, to) {
118
- if (!useColor)
119
- return text;
119
+ if (!useColor) return text;
120
120
  const chars = [...text];
121
121
  const painted = chars.map((ch, i) => {
122
122
  const t = chars.length < 2 ? 0 : i / (chars.length - 1);
@@ -126,15 +126,12 @@ function gradient(text, from, to) {
126
126
  return `${painted}\x1B[39m`;
127
127
  }
128
128
  function formatDuration(ms) {
129
- if (ms < 1000)
130
- return `${Math.round(ms)}ms`;
131
- return `${(ms / 1000).toFixed(2)}s`;
129
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
130
+ return `${(ms / 1e3).toFixed(2)}s`;
132
131
  }
133
132
  function formatBytes(bytes) {
134
- if (bytes < 1024)
135
- return `${bytes} B`;
136
- if (bytes < 1024 ** 2)
137
- return `${(bytes / 1024).toFixed(1)} kB`;
133
+ if (bytes < 1024) return `${bytes} B`;
134
+ if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} kB`;
138
135
  return `${(bytes / 1024 ** 2).toFixed(2)} MB`;
139
136
  }
140
137
  var log = {
@@ -143,10 +140,12 @@ var log = {
143
140
  success: (msg) => console.log(` ${colors.mint("\u2714")} ${msg}`),
144
141
  warn: (msg) => console.log(` ${colors.yellow("\u26A0")} ${colors.yellow(msg)}`),
145
142
  error: (msg) => console.error(` ${colors.ember("\u2716")} ${colors.ember(msg)}`),
146
- change: (file) => console.log(` ${colors.violet("\u21BB")} ${colors.dim("changed")} ${file}`),
147
- request(method, pathname, status, time) {
143
+ change: (file2) => console.log(` ${colors.violet("\u21BB")} ${colors.dim("changed")} ${file2}`),
144
+ request(method, pathname, status, time2) {
148
145
  const verb = methodColor(method)(method.padEnd(6));
149
- console.log(` ${colors.gray("\u203A")} ${verb}${colors.bold(pathname)} ${statusColor(status)(String(status))} ${colors.gray(time)}`);
146
+ console.log(
147
+ ` ${colors.gray("\u203A")} ${verb}${colors.bold(pathname)} ${statusColor(status)(String(status))} ${colors.gray(time2)}`
148
+ );
150
149
  }
151
150
  };
152
151
  function spinner(label) {
@@ -169,8 +168,8 @@ function spinner(label) {
169
168
  clearInterval(timer);
170
169
  const icon = ok ? colors.mint("\u2714") : colors.ember("\u2716");
171
170
  const text = ok ? label : colors.ember(label);
172
- const time = colors.gray(formatDuration(performance.now() - start));
173
- process.stdout.write(`\r\x1B[2K ${icon} ${text} ${time}${note ? ` ${note}` : ""}
171
+ const time2 = colors.gray(formatDuration(performance.now() - start));
172
+ process.stdout.write(`\r\x1B[2K ${icon} ${text} ${time2}${note ? ` ${note}` : ""}
174
173
  `);
175
174
  }
176
175
  };
@@ -190,9 +189,10 @@ function box(lines, paint = colors.fire) {
190
189
  const width = Math.max(...lines.map(visible)) + 4;
191
190
  const top = paint(`\u256D${"\u2500".repeat(width)}\u256E`);
192
191
  const bottom = paint(`\u2570${"\u2500".repeat(width)}\u256F`);
193
- const body = lines.map((l) => `${paint("\u2502")} ${l}${" ".repeat(width - visible(l) - 2)}${paint("\u2502")}`);
194
- console.log([top, ...body, bottom].map((l) => ` ${l}`).join(`
195
- `));
192
+ const body = lines.map(
193
+ (l) => `${paint("\u2502")} ${l}${" ".repeat(width - visible(l) - 2)}${paint("\u2502")}`
194
+ );
195
+ console.log([top, ...body, bottom].map((l) => ` ${l}`).join("\n"));
196
196
  }
197
197
  function table(rows, headers) {
198
198
  const all = [headers, ...rows];
@@ -211,152 +211,331 @@ function banner(version) {
211
211
  `);
212
212
  }
213
213
 
214
- // src/errors.ts
215
- import fs2 from "fs";
216
- import path3 from "path";
214
+ // packages/cli/src/errors.ts
215
+ import fs2 from "node:fs";
216
+ import path4 from "node:path";
217
+
218
+ // packages/cli/src/hints.ts
219
+ import path3 from "node:path";
217
220
  var norm = (p) => p.replace(/\\/g, "/");
218
- var rootNorm = norm(paths.root);
221
+ var rel = (file2) => norm(path3.relative(paths.root, file2));
222
+ var BROWSER_GLOBAL = /^(window|document|localStorage|sessionStorage|navigator|matchMedia|IntersectionObserver|ResizeObserver|location|history)$/;
223
+ function diagnose(error, frames) {
224
+ const hints = [];
225
+ const msg = error.message;
226
+ const layout = frames.find((f) => /_layout\.[jt]sx?$/.test(norm(f.file)));
227
+ const browserName = msg.match(/^(\w+) is not defined/)?.[1];
228
+ if (error.name === "ReferenceError" && browserName && BROWSER_GLOBAL.test(browserName)) {
229
+ hints.push({
230
+ title: `"${browserName}" is a browser API, but it ran while the server rendered the page`,
231
+ steps: [
232
+ layout ? `The code is in a layout: ${rel(layout.file)}. Layouts render on the server for server and universal pages.` : "The code runs during server rendering. Server and universal pages render on the server.",
233
+ "Move the code into useEffect, which runs only in the browser.",
234
+ "Or wrap the browser-only part in <ClientOnly fallback={...}> from @kiln-js/core.",
235
+ "If the whole page needs the browser, use the .client suffix for that page."
236
+ ]
237
+ });
238
+ }
239
+ if (/Cannot find module|Failed to resolve import|Could not resolve|Cannot find package/.test(msg)) {
240
+ hints.push({
241
+ title: "An import could not be resolved",
242
+ steps: [
243
+ "Check the path: relative paths start with ./ or ../, and file names are case-sensitive.",
244
+ "For packages, run bun install in the project root.",
245
+ "After adding a dependency, restart kiln dev."
246
+ ]
247
+ });
248
+ }
249
+ if (/must export "createHandler/.test(msg)) {
250
+ hints.push({
251
+ title: "The server entry does not export createHandler",
252
+ steps: [
253
+ "app/server.ts must export: export function createHandler(assets) { ... }",
254
+ "Use createAppHandler from @kiln-js/server inside it."
255
+ ]
256
+ });
257
+ }
258
+ if (/server-only and cannot be imported/.test(msg)) {
259
+ hints.push({
260
+ title: "A .server module is imported by browser code",
261
+ steps: [
262
+ "Move the import into a loader or action, which the build removes from the browser bundle.",
263
+ "Or move the helper that uses it into a .server module."
264
+ ]
265
+ });
266
+ }
267
+ if (/DATABASE_URL is not set/.test(msg)) {
268
+ hints.push({
269
+ title: "A required environment variable is missing",
270
+ steps: [
271
+ "Add DATABASE_URL to .env.local for local development.",
272
+ "On Vercel, add it under Settings \u2192 Environment Variables."
273
+ ]
274
+ });
275
+ }
276
+ if (/Invalid environment/.test(msg)) {
277
+ hints.push({
278
+ title: "Environment validation failed",
279
+ steps: ["Each line under the message names a variable. Add it to .env.local or fix its value."]
280
+ });
281
+ }
282
+ if (error.name === "SyntaxError" && frames.some((f) => norm(f.file).endsWith(".md"))) {
283
+ hints.push({
284
+ title: "A Markdown file reached the JavaScript parser",
285
+ steps: [
286
+ "Add md() from @kiln-js/md to the plugins in vite.config.ts.",
287
+ "Restart kiln dev after changing the config."
288
+ ]
289
+ });
290
+ }
291
+ if (/Hydration failed|did not match|Text content does not match|#418|#423|#425/.test(msg)) {
292
+ hints.push({
293
+ title: "The server and the browser rendered different HTML",
294
+ steps: [
295
+ "Common causes: Date.now(), Math.random(), toLocaleString(), and window checks during render.",
296
+ "Move those values into useEffect, or wrap them in <ClientOnly>."
297
+ ]
298
+ });
299
+ }
300
+ if (/conflict: .* both map to/.test(msg)) {
301
+ hints.push({
302
+ title: "Two files map to the same URL",
303
+ steps: [
304
+ "Rename one of the files, or move it into a (group) folder if it should share a layout without changing the URL."
305
+ ]
306
+ });
307
+ }
308
+ return hints;
309
+ }
310
+
311
+ // packages/cli/src/errors.ts
312
+ var norm2 = (p) => p.replace(/\\/g, "/");
313
+ var rootNorm = norm2(paths.root);
219
314
  var toError = (err) => err instanceof Error ? err : new Error(String(err));
220
- var rel = (file) => norm(path3.relative(paths.root, file));
315
+ var rel2 = (file2) => norm2(path4.relative(paths.root, file2));
221
316
  var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
222
- var editorLink = (f) => `vscode://file/${encodeURI(norm(f.file))}:${f.line}:${f.column}`;
317
+ var editorLink = (f) => `vscode://file/${encodeURI(norm2(f.file))}:${f.line}:${f.column}`;
223
318
  function parseFrames(stack) {
224
319
  const frames = [];
225
- for (const raw of stack.split(`
226
- `)) {
320
+ for (const raw of stack.split("\n")) {
227
321
  const m = raw.trim().match(/^at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/);
228
- if (!m)
229
- continue;
322
+ if (!m) continue;
230
323
  frames.push({
231
324
  fn: m[1] ?? "<anonymous>",
232
- file: m[2].replace(/^file:\/\/\/?/, ""),
325
+ // Dev URLs carry a ?t=timestamp suffix, which is not part of the path.
326
+ file: m[2].replace(/^file:\/\/\/?/, "").split("?")[0],
233
327
  line: Number(m[3]),
234
328
  column: Number(m[4])
235
329
  });
236
330
  }
237
331
  return frames;
238
332
  }
239
- var isUserFile = (file) => {
240
- const n = norm(file);
333
+ function isAppFrame(f) {
334
+ const n = norm2(f.file);
241
335
  return n.startsWith(rootNorm) && !n.includes("/node_modules/");
242
- };
336
+ }
243
337
  function findOrigin(frames) {
244
- return frames.find((f) => isUserFile(f.file) && fs2.existsSync(f.file));
338
+ return frames.find((f) => isAppFrame(f) && fs2.existsSync(f.file));
245
339
  }
246
- function codeLines(f, radius = 2) {
340
+ function codeLines(f, radius = 3) {
247
341
  try {
248
342
  const lines = fs2.readFileSync(f.file, "utf8").split(/\r?\n/);
249
343
  const from = Math.max(1, f.line - radius);
250
344
  const to = Math.min(lines.length, f.line + radius);
251
345
  const out = [];
252
- for (let n = from;n <= to; n++) {
253
- out.push({ n, text: lines[n - 1] ?? "", hot: n === f.line });
254
- }
346
+ for (let n = from; n <= to; n++) out.push({ n, text: lines[n - 1] ?? "", hot: n === f.line });
255
347
  return out;
256
348
  } catch {
257
349
  return [];
258
350
  }
259
351
  }
352
+ function terminalCode(f) {
353
+ const lines = codeLines(f, 3);
354
+ const width = String(lines[lines.length - 1]?.n ?? 0).length;
355
+ const rows = [];
356
+ for (const l of lines) {
357
+ const num = String(l.n).padStart(width);
358
+ if (l.hot) {
359
+ rows.push(`${colors.red("\u25B8")} ${colors.red(num)} ${colors.gray("\u2502")} ${l.text}`);
360
+ rows.push(` ${" ".repeat(width)} ${colors.gray("\u2502")} ${" ".repeat(Math.max(0, f.column - 1))}${colors.red("^")}`);
361
+ } else {
362
+ rows.push(` ${colors.gray(num)} ${colors.gray("\u2502")} ${colors.gray(l.text)}`);
363
+ }
364
+ }
365
+ return rows;
366
+ }
260
367
  function printError(err, context) {
261
368
  const error = toError(err);
262
- const origin = findOrigin(parseFrames(error.stack ?? ""));
263
- console.error("");
264
- console.error(colors.red(colors.bold(` ${error.name}: ${error.message}`)));
265
- console.error(colors.dim(` ${context}`));
369
+ const frames = parseFrames(error.stack ?? "");
370
+ const origin = findOrigin(frames);
371
+ const hints = diagnose(error, frames);
372
+ const appFrames = frames.filter(isAppFrame);
373
+ const hidden = frames.length - appFrames.length;
374
+ const c = colors;
375
+ const lines = [""];
376
+ lines.push(` ${c.red("\u2716")} ${c.bold(c.red(error.name))} ${c.bold(error.message)}`);
377
+ lines.push(` ${c.gray(context)}`);
266
378
  if (origin) {
267
- console.error(`
268
- ${colors.cyan(`${rel(origin.file)}:${origin.line}:${origin.column}`)}`);
269
- for (const l of codeLines(origin)) {
270
- const mark = l.hot ? colors.red(">") : " ";
271
- const num = colors.dim(String(l.n).padStart(4));
272
- console.error(` ${mark} ${num} ${colors.dim("\u2502")} ${l.hot ? l.text : colors.dim(l.text)}`);
273
- if (l.hot) {
274
- console.error(` ${colors.dim("\u2502")} ${" ".repeat(origin.column - 1)}${colors.red("^")}`);
275
- }
379
+ lines.push("");
380
+ lines.push(` ${c.gray("at")} ${c.cyan(`${rel2(origin.file)}:${origin.line}:${origin.column}`)}`);
381
+ lines.push("");
382
+ for (const row of terminalCode(origin)) lines.push(` ${row}`);
383
+ }
384
+ for (const hint of hints) {
385
+ lines.push("");
386
+ lines.push(` ${c.yellow("hint")} ${c.bold(hint.title)}`);
387
+ for (const step of hint.steps) lines.push(` ${c.gray("\u203A")} ${step}`);
388
+ }
389
+ if (appFrames.length > 0) {
390
+ lines.push("");
391
+ lines.push(` ${c.gray("stack")}`);
392
+ for (const f of appFrames.slice(0, 6)) {
393
+ lines.push(` ${c.dim(f.fn.padEnd(28))} ${c.gray(`${rel2(f.file)}:${f.line}`)}`);
276
394
  }
277
395
  }
278
- console.error("");
396
+ if (hidden > 0) lines.push(` ${c.gray(`+ ${hidden} internal frames`)}`);
397
+ lines.push("");
398
+ console.error(lines.join("\n"));
399
+ }
400
+ var OVERLAY_CSS = `
401
+ :root {
402
+ --bg: #0e1116; --panel: #161b22; --line: #262d38; --text: #e6edf3; --muted: #8b949e;
403
+ --accent: #f85149; --link: #79c0ff; --warn: #e3b341; --hot: rgba(248, 81, 73, 0.14);
404
+ color-scheme: dark;
405
+ }
406
+ @media (prefers-color-scheme: light) {
407
+ :root {
408
+ --bg: #f6f8fa; --panel: #ffffff; --line: #d0d7de; --text: #1f2328; --muted: #656d76;
409
+ --accent: #cf222e; --link: #0550ae; --warn: #9a6700; --hot: rgba(207, 34, 46, 0.1);
410
+ color-scheme: light;
411
+ }
412
+ }
413
+ * { box-sizing: border-box; }
414
+ body { margin: 0; background: var(--bg); color: var(--text);
415
+ font: 14px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
416
+ .overlay[hidden] { display: none; }
417
+ .bar { position: sticky; top: 0; z-index: 1; display: flex; align-items: center; gap: 16px;
418
+ padding: 10px 24px; background: var(--panel); border-bottom: 1px solid var(--line); flex-wrap: wrap; }
419
+ .brand { font-weight: 700; }
420
+ .route { display: flex; gap: 8px; align-items: center; color: var(--muted);
421
+ font: 13px ui-monospace, SFMono-Regular, Consolas, monospace; }
422
+ .method { color: var(--text); font-weight: 600; }
423
+ .actions { margin-left: auto; display: flex; gap: 8px; }
424
+ button { font: inherit; font-size: 13px; padding: 5px 10px; border-radius: 6px; cursor: pointer;
425
+ border: 1px solid var(--line); background: transparent; color: var(--text); }
426
+ main { max-width: 1040px; margin: 0 auto; padding: 28px 24px 64px; display: grid; gap: 16px; }
427
+ .kind { margin: 0; color: var(--accent); font: 600 12px ui-monospace, monospace;
428
+ text-transform: uppercase; letter-spacing: 0.08em; }
429
+ .hero h1 { margin: 6px 0 10px; font-size: 22px; line-height: 1.35; word-break: break-word; }
430
+ .where { color: var(--link); text-decoration: none; font: 13px ui-monospace, monospace; }
431
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
432
+ .card h2 { margin: 0; font-size: 14px; padding: 12px 16px; border-bottom: 1px solid var(--line); }
433
+ .hint { border-color: color-mix(in srgb, var(--warn) 45%, var(--line)); }
434
+ .hint h2 { color: var(--warn); }
435
+ .hint ul { margin: 0; padding: 12px 16px 14px 36px; }
436
+ .card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px;
437
+ padding: 10px 16px; border-bottom: 1px solid var(--line); color: var(--muted); font-size: 13px; }
438
+ .open { color: var(--link); text-decoration: none; }
439
+ .code { overflow: auto; padding: 8px 0; font: 13px/1.7 ui-monospace, SFMono-Regular, Consolas, monospace; }
440
+ .ln { display: flex; white-space: pre; padding: 0 16px; }
441
+ .num { width: 48px; flex: none; color: var(--muted); user-select: none; }
442
+ .ln.hot { background: var(--hot); }
443
+ .ln.hot .txt { font-weight: 600; }
444
+ .caret-row .txt { color: var(--accent); }
445
+ .frames { margin: 0; padding: 8px 16px 12px 44px; }
446
+ .frames li { padding: 4px 0; }
447
+ .frames a { color: var(--link); text-decoration: none; font: 13px ui-monospace, monospace; word-break: break-all; }
448
+ .fn { color: var(--muted); margin-right: 10px; font: 13px ui-monospace, monospace; }
449
+ .none { color: var(--muted); list-style: none; margin-left: -28px; }
450
+ details.internal { border-top: 1px solid var(--line); }
451
+ details.internal summary { cursor: pointer; color: var(--muted); padding: 10px 16px; }
452
+ details.internal .frames { padding-top: 0; }
453
+ footer { text-align: center; color: var(--muted); font-size: 13px; }
454
+ `;
455
+ var OVERLAY_JS = `
456
+ (function () {
457
+ var raw = document.getElementById("raw").content.textContent;
458
+ var copy = document.getElementById("copy");
459
+ copy.onclick = function () {
460
+ if (!navigator.clipboard) return;
461
+ navigator.clipboard.writeText(raw).then(function () {
462
+ copy.textContent = "Copied";
463
+ setTimeout(function () { copy.textContent = "Copy stack"; }, 1500);
464
+ });
465
+ };
466
+ function hide() { document.querySelector(".overlay").hidden = true; }
467
+ document.getElementById("dismiss").onclick = hide;
468
+ document.addEventListener("keydown", function (e) { if (e.key === "Escape") hide(); });
469
+ })();
470
+ `;
471
+ function frameItem(f) {
472
+ return `<li><span class="fn">${esc(f.fn)}</span><a href="${editorLink(f)}">${esc(rel2(f.file))}:${f.line}:${f.column}</a></li>`;
473
+ }
474
+ function hintCard(h) {
475
+ return `<section class="card hint"><h2>${esc(h.title)}</h2><ul>${h.steps.map((s) => `<li>${esc(s)}</li>`).join("")}</ul></section>`;
476
+ }
477
+ function sourceCard(f) {
478
+ const rows = codeLines(f, 4).map((l) => {
479
+ const row = `<div class="ln${l.hot ? " hot" : ""}"><span class="num">${l.n}</span><span class="txt">${esc(l.text) || " "}</span></div>`;
480
+ if (!l.hot) return row;
481
+ const caret = `<div class="ln caret-row"><span class="num"></span><span class="txt" style="white-space:pre">${" ".repeat(
482
+ Math.max(0, f.column - 1)
483
+ )}<span>^</span></span></div>`;
484
+ return row + caret;
485
+ }).join("");
486
+ return `<section class="card">
487
+ <div class="card-head"><span>Source</span><a class="open" href="${editorLink(f)}">Open in editor \u2192</a></div>
488
+ <div class="code">${rows}</div>
489
+ </section>`;
279
490
  }
280
491
  function renderDevError(err, meta) {
281
492
  const error = toError(err);
282
493
  const frames = parseFrames(error.stack ?? "");
283
494
  const origin = findOrigin(frames);
284
- const source = origin ? `<section class="card">
285
- <div class="card-head">
286
- <span>Source</span>
287
- <a href="${editorLink(origin)}">${esc(rel(origin.file))}:${origin.line}:${origin.column}</a>
288
- </div>
289
- <pre class="code">${codeLines(origin, 5).map((l) => `<div class="ln${l.hot ? " hot" : ""}"><span class="num">${l.n}</span><span class="txt">${esc(l.text) || " "}</span></div>`).join("")}</pre>
290
- </section>` : "";
291
- const stack = frames.map((f) => {
292
- const internal = !isUserFile(f.file);
293
- return `<li class="${internal ? "internal" : ""}">
294
- <span class="fn">${esc(f.fn)}</span>
295
- <a href="${editorLink(f)}">${esc(rel(f.file))}:${f.line}:${f.column}</a>
296
- </li>`;
297
- }).join("");
495
+ const hints = diagnose(error, frames);
496
+ const appFrames = frames.filter(isAppFrame);
497
+ const internal = frames.filter((f) => !isAppFrame(f));
498
+ const time2 = (/* @__PURE__ */ new Date()).toLocaleTimeString();
499
+ const where = origin ? `<a class="where" href="${editorLink(origin)}">${esc(rel2(origin.file))}:${origin.line}:${origin.column}</a>` : "";
500
+ const internalBlock = internal.length ? `<details class="internal"><summary>${internal.length} internal frames</summary><ol class="frames">${internal.map(frameItem).join("")}</ol></details>` : "";
501
+ const appList = appFrames.length ? appFrames.map(frameItem).join("") : `<li class="none">No frames from your code</li>`;
298
502
  return `<!doctype html>
299
503
  <html lang="en">
300
504
  <head>
301
- <meta charset="utf-8" />
302
- <title>${esc(error.name)}: ${esc(error.message)}</title>
303
- <style>
304
- :root { color-scheme: dark; --bg:#0f1115; --panel:#171a21; --line:#262b36; --text:#e5e7eb; --muted:#8b93a7; --accent:#67e8f9; }
305
- * { box-sizing: border-box; }
306
- body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.6 ui-sans-serif, system-ui, sans-serif; }
307
- header { padding: 28px 32px; background: linear-gradient(135deg, #7f1d1d, #1e1b4b); border-bottom: 1px solid var(--line); }
308
- .badge { display: inline-block; font: 12px ui-monospace, monospace; padding: 2px 10px; border-radius: 999px; background: rgba(255,255,255,.12); margin-bottom: 10px; }
309
- .kind { color: #fecaca; font: 13px ui-monospace, monospace; }
310
- h1 { margin: 4px 0 0; font-size: 20px; color: #fff; word-break: break-word; }
311
- main { padding: 24px 32px; display: grid; gap: 20px; max-width: 1100px; }
312
- .card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
313
- .card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 10px 14px; border-bottom: 1px solid var(--line); font-weight: 600; }
314
- a { color: var(--accent); text-decoration: none; font: 13px ui-monospace, monospace; }
315
- a:hover { text-decoration: underline; }
316
- .code { margin: 0; padding: 8px 0; overflow: auto; font: 13px/1.7 ui-monospace, Consolas, monospace; }
317
- .ln { display: flex; white-space: pre; padding: 0 14px; }
318
- .ln .num { width: 48px; color: var(--muted); user-select: none; flex-shrink: 0; }
319
- .ln.hot { background: rgba(248,113,113,.18); }
320
- .ln.hot .num, .ln.hot .txt { color: #fff; }
321
- .stack { margin: 0; padding: 10px 14px; list-style: none; }
322
- .stack li { padding: 5px 0; border-bottom: 1px dashed var(--line); }
323
- .stack li:last-child { border-bottom: 0; }
324
- .stack li.internal { opacity: .45; }
325
- .fn { color: #c4b5fd; font: 13px ui-monospace, monospace; margin-right: 8px; }
326
- button { background: var(--line); color: var(--text); border: 1px solid #343a48; border-radius: 6px; padding: 4px 10px; cursor: pointer; font: inherit; }
327
- .hint { color: var(--muted); font-size: 12px; }
328
- </style>
505
+ <meta charset="utf-8" />
506
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
507
+ <title>${esc(error.name)}: ${esc(error.message)}</title>
508
+ <style>${OVERLAY_CSS}</style>
329
509
  </head>
330
510
  <body>
331
- <div class="overlay">
332
- <header>
333
- <span class="badge">${esc(meta.method)} ${esc(meta.pathname)}</span>
334
- <div class="kind">${esc(error.name)}</div>
511
+ <div class="overlay">
512
+ <header class="bar">
513
+ <span class="brand">Kiln</span>
514
+ <span class="route"><span class="method">${esc(meta.method)}</span>${esc(meta.pathname)}</span>
515
+ <span class="route">${esc(time2)}</span>
516
+ <div class="actions">
517
+ <button id="copy" type="button">Copy stack</button>
518
+ <button id="dismiss" type="button">Dismiss</button>
519
+ </div>
520
+ </header>
521
+ <main>
522
+ <section class="hero">
523
+ <p class="kind">${esc(error.name)}</p>
335
524
  <h1>${esc(error.message)}</h1>
336
- </header>
337
- <main>
338
- ${source}
339
- <section class="card">
340
- <div class="card-head">
341
- <span>Call stack</span>
342
- <button id="copy">Copy</button>
343
- </div>
344
- <ol class="stack">${stack}</ol>
345
- </section>
346
- <p class="hint">Fix the file and save. The page reloads automatically. Press Esc to hide this overlay.</p>
347
- </main>
348
- </div>
349
- <template id="raw">${esc(error.stack ?? error.message)}</template>
350
- <script>
351
- document.getElementById("copy").onclick = async (e) => {
352
- const text = document.getElementById("raw").content.textContent;
353
- await navigator.clipboard.writeText(text);
354
- e.target.textContent = "Copied";
355
- };
356
- document.addEventListener("keydown", (e) => {
357
- if (e.key === "Escape") document.querySelector(".overlay").style.display = "none";
358
- });
359
- </script>
525
+ ${where}
526
+ </section>
527
+ ${hints.map(hintCard).join("")}
528
+ ${origin ? sourceCard(origin) : ""}
529
+ <section class="card">
530
+ <div class="card-head"><span>Call stack</span><span>${appFrames.length} in your code</span></div>
531
+ <ol class="frames">${appList}</ol>
532
+ ${internalBlock}
533
+ </section>
534
+ <footer>Save a file to reload. Press Esc to dismiss.</footer>
535
+ </main>
536
+ </div>
537
+ <template id="raw">${esc(error.stack ?? error.message)}</template>
538
+ <script>${OVERLAY_JS}</script>
360
539
  </body>
361
540
  </html>`;
362
541
  }
@@ -364,94 +543,398 @@ function renderProdError(requestId) {
364
543
  return `<!doctype html>
365
544
  <html lang="en">
366
545
  <head>
367
- <meta charset="utf-8" />
368
- <meta name="viewport" content="width=device-width, initial-scale=1" />
369
- <title>500 \xB7 Server error</title>
370
- <style>
371
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f8fafc; color: #0f172a; font: 16px/1.6 system-ui, sans-serif; }
372
- main { text-align: center; padding: 2rem; }
373
- h1 { font-size: 4rem; margin: 0; color: #dc2626; }
374
- code { background: #e2e8f0; padding: 2px 8px; border-radius: 6px; }
375
- a { color: #2563eb; }
376
- </style>
546
+ <meta charset="utf-8" />
547
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
548
+ <title>Server error</title>
549
+ <style>
550
+ :root { color-scheme: light dark; }
551
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #fafafa; color: #111;
552
+ font: 16px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif; }
553
+ @media (prefers-color-scheme: dark) { body { background: #0e1116; color: #e6edf3; } }
554
+ main { max-width: 420px; padding: 32px; text-align: center; }
555
+ .status { margin: 0; font-size: 56px; font-weight: 700; color: #dc2626; }
556
+ .ref { font: 13px ui-monospace, monospace; opacity: 0.7; }
557
+ a { color: inherit; }
558
+ </style>
377
559
  </head>
378
560
  <body>
379
- <main>
380
- <h1>500</h1>
381
- <p>Something went wrong on our side.</p>
382
- <p>Reference: <code>${esc(requestId)}</code></p>
383
- <p><a href="/">Back to home</a></p>
384
- </main>
561
+ <main>
562
+ <p class="status">500</p>
563
+ <h1 style="font-size: 22px; margin: 8px 0;">Something went wrong</h1>
564
+ <p>The error was logged on the server.</p>
565
+ <p class="ref">Reference ${esc(requestId)}</p>
566
+ <p><a href="/">Back to home</a></p>
567
+ </main>
568
+ </body>
569
+ </html>`;
570
+ }
571
+
572
+ // packages/cli/src/versions.ts
573
+ import fs3 from "node:fs";
574
+ import path5 from "node:path";
575
+ var KILN_PACKAGES = [
576
+ "@kiln-js/core",
577
+ "@kiln-js/server",
578
+ "@kiln-js/client",
579
+ "@kiln-js/vite-plugin",
580
+ "@kiln-js/md",
581
+ "@kiln-js/adapter-vercel",
582
+ "@kiln-js/auth"
583
+ ];
584
+ function cliVersion() {
585
+ const file2 = new URL("../package.json", import.meta.url);
586
+ return JSON.parse(fs3.readFileSync(file2, "utf8")).version;
587
+ }
588
+ function findPackageDir(name) {
589
+ let dir = paths.root;
590
+ for (; ; ) {
591
+ const candidate = path5.join(dir, "node_modules", ...name.split("/"));
592
+ if (fs3.existsSync(path5.join(candidate, "package.json"))) return candidate;
593
+ const parent = path5.dirname(dir);
594
+ if (parent === dir) return null;
595
+ dir = parent;
596
+ }
597
+ }
598
+ function inspectPackages() {
599
+ return KILN_PACKAGES.map((name) => {
600
+ const dir = findPackageDir(name);
601
+ if (!dir) return { name, version: null, location: null, linked: false };
602
+ const real = fs3.realpathSync(dir);
603
+ const version = JSON.parse(fs3.readFileSync(path5.join(real, "package.json"), "utf8")).version;
604
+ const location = path5.relative(paths.root, real).replace(/\\/g, "/") || ".";
605
+ return { name, version, location, linked: real.includes(`${path5.sep}packages${path5.sep}`) };
606
+ });
607
+ }
608
+ function findVersionProblems() {
609
+ const expected = cliVersion();
610
+ return inspectPackages().filter((p) => p.version !== null && p.version !== expected);
611
+ }
612
+ function assertVersionsMatch() {
613
+ const problems = findVersionProblems();
614
+ if (problems.length === 0) return;
615
+ const expected = cliVersion();
616
+ const list = problems.map((p) => ` ${p.name} ${p.version} at ${p.location}`).join("\n");
617
+ throw new Error(
618
+ `The Kiln packages in this app do not match the CLI (${expected}):
619
+ ${list}
620
+
621
+ Mixed versions cause "does not provide an export named" errors.
622
+ Run kiln doctor for the full list.`
623
+ );
624
+ }
625
+
626
+ // packages/cli/src/preflight.ts
627
+ import fs4 from "node:fs";
628
+ import path6 from "node:path";
629
+ import { pathToFileURL } from "node:url";
630
+ var ENTRY_PACKAGES = ["@kiln-js/core", "@kiln-js/server", "@kiln-js/client", "@kiln-js/md"];
631
+ function resolvePackage(name) {
632
+ let dir = paths.root;
633
+ for (; ; ) {
634
+ const pkgDir = path6.join(dir, "node_modules", ...name.split("/"));
635
+ const pkgJson = path6.join(pkgDir, "package.json");
636
+ if (fs4.existsSync(pkgJson)) {
637
+ const json = JSON.parse(fs4.readFileSync(pkgJson, "utf8"));
638
+ const dot = json.exports?.["."];
639
+ const rel5 = (typeof dot === "string" ? dot : dot?.import) ?? json.module ?? json.main ?? "index.js";
640
+ return { file: path6.join(pkgDir, rel5) };
641
+ }
642
+ const parent = path6.dirname(dir);
643
+ if (parent === dir) return null;
644
+ dir = parent;
645
+ }
646
+ }
647
+ async function preflightImports() {
648
+ const failures = [];
649
+ for (const name of ENTRY_PACKAGES) {
650
+ const resolved = resolvePackage(name);
651
+ if (!resolved) continue;
652
+ try {
653
+ await import(pathToFileURL(resolved.file).href);
654
+ } catch (err) {
655
+ failures.push({
656
+ name,
657
+ file: path6.relative(paths.root, resolved.file).replace(/\\/g, "/"),
658
+ message: err instanceof Error ? err.message : String(err)
659
+ });
660
+ }
661
+ }
662
+ if (failures.length === 0) return;
663
+ const lines = failures.map((f) => ` ${f.name} (${f.file})
664
+ ${f.message}`).join("\n");
665
+ throw new Error(
666
+ `Kiln cannot load its own packages in this folder:
667
+ ${lines}
668
+
669
+ The packages in use do not export what the app needs. This usually means an
670
+ old published copy is installed under this folder or a parent folder.
671
+
672
+ Fix:
673
+ 1. Run Get-Command kiln -All and remove any global install:
674
+ npm uninstall -g @kiln-js/cli
675
+ bun remove -g @kiln-js/cli
676
+ 2. Delete the stray folders reported above (node_modules and .kiln under examples\\).
677
+ 3. From the monorepo root, run bun install and node scripts/build.mjs
678
+ 4. From the app folder, run bun run dev`
679
+ );
680
+ }
681
+
682
+ // packages/cli/src/dashboard.ts
683
+ import path7 from "node:path";
684
+ import { scanApi, scanRoutes } from "@kiln-js/core/scan";
685
+ var DevStats = class {
686
+ startedAt = Date.now();
687
+ requests = [];
688
+ errors = [];
689
+ total = 0;
690
+ failed = 0;
691
+ recordRequest(entry) {
692
+ this.total++;
693
+ if (entry.status >= 500) this.failed++;
694
+ this.requests.unshift({ ...entry, at: Date.now() });
695
+ if (this.requests.length > 100) this.requests.length = 100;
696
+ }
697
+ recordError(entry) {
698
+ this.errors.unshift({ ...entry, at: Date.now() });
699
+ if (this.errors.length > 20) this.errors.length = 20;
700
+ }
701
+ snapshot() {
702
+ return {
703
+ startedAt: this.startedAt,
704
+ total: this.total,
705
+ failed: this.failed,
706
+ requests: this.requests,
707
+ errors: this.errors
708
+ };
709
+ }
710
+ };
711
+ var esc2 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
712
+ var time = (ms) => new Date(ms).toLocaleTimeString();
713
+ var rel3 = (file2) => path7.relative(paths.root, file2).replace(/\\/g, "/");
714
+ function routeRows() {
715
+ try {
716
+ const pages = scanRoutes(paths.pagesDir).map(
717
+ (r) => `<tr><td><code>${esc2(r.pattern)}</code></td><td>${esc2(r.mode)}</td><td>${esc2(rel3(r.file))}</td></tr>`
718
+ );
719
+ const apis = scanApi(paths.apiDir).map(
720
+ (r) => `<tr><td><code>${esc2(r.pattern)}</code></td><td>api</td><td>${esc2(rel3(r.file))}</td></tr>`
721
+ );
722
+ return [...pages, ...apis].join("") || `<tr><td colspan="3">No routes</td></tr>`;
723
+ } catch (err) {
724
+ const message = err instanceof Error ? err.message : String(err);
725
+ return `<tr><td colspan="3">${esc2(message)}</td></tr>`;
726
+ }
727
+ }
728
+ var CSS = `
729
+ :root { color-scheme: dark; --bg:#0e1116; --panel:#161b22; --line:#262d38; --text:#e6edf3; --muted:#8b949e; --ok:#3fb950; --warn:#d29922; --bad:#f85149; --link:#79c0ff; }
730
+ * { box-sizing: border-box; }
731
+ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.5 ui-sans-serif, system-ui, sans-serif; }
732
+ header { display: flex; gap: 16px; align-items: baseline; padding: 16px 24px; border-bottom: 1px solid var(--line); background: var(--panel); }
733
+ header h1 { margin: 0; font-size: 16px; }
734
+ header span { color: var(--muted); font-size: 13px; }
735
+ main { padding: 20px 24px 48px; display: grid; gap: 16px; max-width: 1200px; margin: 0 auto; }
736
+ .grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
737
+ .stat { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; }
738
+ .stat b { display: block; font-size: 22px; margin-top: 4px; }
739
+ section { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
740
+ section h2 { margin: 0; font-size: 13px; padding: 10px 14px; border-bottom: 1px solid var(--line); color: var(--muted); text-transform: uppercase; letter-spacing: .06em; }
741
+ table { width: 100%; border-collapse: collapse; font-size: 13px; }
742
+ th, td { text-align: left; padding: 7px 14px; border-bottom: 1px solid var(--line); }
743
+ th { color: var(--muted); font-weight: 500; }
744
+ code { font: 13px ui-monospace, Consolas, monospace; color: var(--link); }
745
+ .s2 { color: var(--ok); } .s3 { color: var(--link); } .s4 { color: var(--warn); } .s5 { color: var(--bad); }
746
+ .err { padding: 10px 14px; border-bottom: 1px solid var(--line); }
747
+ .err pre { margin: 6px 0 0; white-space: pre-wrap; color: var(--bad); font: 12px ui-monospace, Consolas, monospace; }
748
+ .empty { padding: 14px; color: var(--muted); }
749
+ @media (max-width: 800px) { .grid { grid-template-columns: repeat(2, 1fr); } }
750
+ `;
751
+ function renderDashboard(stats, cache, pathname) {
752
+ const snap = stats.snapshot();
753
+ const uptime = Math.floor((Date.now() - snap.startedAt) / 1e3);
754
+ const lookups = cache.hits + cache.misses;
755
+ const hitRate = lookups === 0 ? 0 : Math.round(cache.hits / lookups * 100);
756
+ const requests = snap.requests.length ? snap.requests.map(
757
+ (r) => `<tr>
758
+ <td>${time(r.at)}</td><td>${esc2(r.method)}</td><td><code>${esc2(r.path)}</code></td>
759
+ <td class="s${Math.floor(r.status / 100)}">${r.status}</td><td>${r.ms.toFixed(0)} ms</td>
760
+ </tr>`
761
+ ).join("") : `<tr><td colspan="5" class="empty">No requests yet. Open a page in the browser.</td></tr>`;
762
+ const errors = snap.errors.length ? snap.errors.map(
763
+ (e) => `<div class="err">
764
+ <div>${time(e.at)} \xB7 ${esc2(e.method)} <code>${esc2(e.path)}</code></div>
765
+ <pre>${esc2(e.message)}</pre>
766
+ </div>`
767
+ ).join("") : `<div class="empty">No errors</div>`;
768
+ return `<!doctype html>
769
+ <html lang="en">
770
+ <head>
771
+ <meta charset="utf-8" />
772
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
773
+ <meta http-equiv="refresh" content="2" />
774
+ <title>Kiln dashboard</title>
775
+ <style>${CSS}</style>
776
+ </head>
777
+ <body>
778
+ <header>
779
+ <h1>Kiln dashboard</h1>
780
+ <span>development only \xB7 ${esc2(pathname)} \xB7 up ${uptime}s</span>
781
+ </header>
782
+ <main>
783
+ <div class="grid">
784
+ <div class="stat">Requests<b>${snap.total}</b></div>
785
+ <div class="stat">Failed (5xx)<b>${snap.failed}</b></div>
786
+ <div class="stat">Cache hit rate<b>${hitRate}%</b></div>
787
+ <div class="stat">Cache invalidations<b>${cache.invalidations}</b></div>
788
+ </div>
789
+
790
+ <section>
791
+ <h2>Routes</h2>
792
+ <table><thead><tr><th>Pattern</th><th>Mode</th><th>File</th></tr></thead><tbody>${routeRows()}</tbody></table>
793
+ </section>
794
+
795
+ <section>
796
+ <h2>Recent requests</h2>
797
+ <table><thead><tr><th>Time</th><th>Method</th><th>Path</th><th>Status</th><th>Duration</th></tr></thead><tbody>${requests}</tbody></table>
798
+ </section>
799
+
800
+ <section>
801
+ <h2>Recent errors</h2>
802
+ ${errors}
803
+ </section>
804
+ </main>
385
805
  </body>
386
806
  </html>`;
387
807
  }
388
808
 
389
- // src/dev.ts
390
- var toError2 = (err) => err instanceof Error ? err : new Error(String(err));
391
- function getHandlerFactory(mod, file) {
809
+ // packages/cli/src/dev.ts
810
+ function findAppFolders(base) {
811
+ try {
812
+ return fs5.readdirSync(base, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules").map((e) => path8.join(base, e.name)).filter((dir) => fs5.existsSync(path8.join(dir, "app", "pages")));
813
+ } catch {
814
+ return [];
815
+ }
816
+ }
817
+ function assertAppFolder() {
818
+ const pkgPath = path8.join(paths.root, "package.json");
819
+ if (!fs5.existsSync(pkgPath)) {
820
+ throw new Error(`No package.json in ${paths.root}. Run kiln dev inside an app folder.`);
821
+ }
822
+ const pkg2 = JSON.parse(fs5.readFileSync(pkgPath, "utf8"));
823
+ if (pkg2.workspaces) {
824
+ throw new Error(
825
+ `${paths.root} is a monorepo root, not an app. Run kiln dev inside an app, for example:
826
+ cd examples\\kiln-docs && bun run dev`
827
+ );
828
+ }
829
+ if (!fs5.existsSync(paths.pagesDir)) {
830
+ const found = findAppFolders(paths.root);
831
+ const hint = found.length > 0 ? `Found app folder(s) below this one:
832
+ ` + found.map((d) => ` cd ${path8.relative(process.cwd(), d)} && bun run dev`).join("\n") : "Create app/pages in this folder, or run kiln dev in your app folder.";
833
+ throw new Error(`No app/pages folder in ${paths.root}.
834
+ ${hint}`);
835
+ }
836
+ }
837
+ function toError2(err) {
838
+ if (err instanceof Error) return err;
839
+ if (typeof err === "object" && err !== null) {
840
+ const { message, name } = err;
841
+ const error = new Error(String(message ?? "Unknown error"));
842
+ if (typeof name === "string") error.name = name;
843
+ return error;
844
+ }
845
+ return new Error(String(err));
846
+ }
847
+ function fixStack(vite, error) {
848
+ try {
849
+ vite.ssrFixStacktrace(error);
850
+ } catch {
851
+ }
852
+ }
853
+ function getHandlerFactory(mod, file2) {
392
854
  const factory = mod.createHandler;
393
855
  if (typeof factory !== "function") {
394
856
  const exports = Object.keys(mod).join(", ") || "(none)";
395
- throw new Error(`${file} must export "createHandler(assets)". Found exports: ${exports}`);
857
+ throw new Error(`${file2} must export "createHandler(assets)". Found exports: ${exports}`);
396
858
  }
397
859
  return factory;
398
860
  }
399
861
  async function toWebRequest(req, origin) {
400
- const headers = new Headers;
862
+ const headers = new Headers();
401
863
  for (const [key, value] of Object.entries(req.headers)) {
402
- if (value === undefined)
403
- continue;
404
- for (const v of Array.isArray(value) ? value : [value])
405
- headers.append(key, v);
864
+ if (value === void 0) continue;
865
+ for (const v of Array.isArray(value) ? value : [value]) headers.append(key, v);
406
866
  }
407
867
  const init = { method: req.method, headers };
408
868
  if (req.method !== "GET" && req.method !== "HEAD") {
409
869
  const chunks = [];
410
- for await (const chunk of req)
411
- chunks.push(chunk);
870
+ for await (const chunk of req) chunks.push(chunk);
412
871
  init.body = Buffer.concat(chunks);
413
872
  }
414
873
  return new Request(new URL(req.url ?? "/", origin), init);
415
874
  }
416
875
  async function startDev(port) {
876
+ assertAppFolder();
877
+ await preflightImports();
878
+ assertVersionsMatch();
417
879
  const startedAt = performance.now();
880
+ globalThis.__KILN_DEV__ = true;
418
881
  loadEnvFiles("development");
419
882
  const entries = resolveEntries();
420
883
  const origin = `http://localhost:${port}`;
884
+ const stats = new DevStats();
421
885
  let vite;
422
886
  let lastRenderFailed = false;
887
+ let handler = null;
888
+ async function currentHandler() {
889
+ if (handler) return handler;
890
+ const mod = await vite.ssrLoadModule(entries.server);
891
+ const createHandler = getHandlerFactory(mod, entries.server);
892
+ handler = createHandler({ head: "", entry: `/${entries.clientRel}` });
893
+ return handler;
894
+ }
423
895
  async function handleSsr(req, res) {
424
896
  const url = req.url ?? "/";
425
897
  const pathname = new URL(url, origin).pathname;
898
+ const method = req.method ?? "GET";
426
899
  const start = performance.now();
900
+ if (pathname === "/__kiln" || pathname === "/__kiln/") {
901
+ res.statusCode = 200;
902
+ res.setHeader("content-type", "text/html; charset=utf-8");
903
+ res.end(renderDashboard(stats, buildCacheStats(), pathname));
904
+ return;
905
+ }
427
906
  try {
428
- const mod = await vite.ssrLoadModule(entries.server);
429
- const createHandler = getHandlerFactory(mod, entries.server);
430
- const handler = createHandler({ head: "", entry: `/${entries.clientRel}` });
431
- const response = await handler(await toWebRequest(req, origin));
907
+ const current = await currentHandler();
908
+ const response = await current(await toWebRequest(req, origin));
432
909
  const isHtml = (response.headers.get("content-type") ?? "").includes("text/html");
433
910
  const body = isHtml ? await vite.transformIndexHtml(url, await response.text()) : Buffer.from(await response.arrayBuffer());
434
911
  res.statusCode = response.status;
435
912
  response.headers.forEach((value, key) => {
436
- if (key !== "content-length")
437
- res.setHeader(key, value);
913
+ if (key !== "content-length" && key !== "set-cookie") res.setHeader(key, value);
438
914
  });
915
+ const cookies = response.headers.getSetCookie();
916
+ if (cookies.length) res.setHeader("set-cookie", cookies);
439
917
  res.end(body);
440
918
  lastRenderFailed = false;
441
- log.request(req.method ?? "GET", pathname, response.status, formatDuration(performance.now() - start));
919
+ const ms = performance.now() - start;
920
+ stats.recordRequest({ method, path: pathname, status: response.status, ms });
921
+ log.request(method, pathname, response.status, formatDuration(ms));
442
922
  } catch (err) {
443
923
  const error = toError2(err);
444
- vite.ssrFixStacktrace(error);
924
+ fixStack(vite, error);
445
925
  lastRenderFailed = true;
446
- log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - start)}`);
447
- printError(error, `${req.method} ${pathname}`);
926
+ const ms = performance.now() - start;
927
+ stats.recordRequest({ method, path: pathname, status: 500, ms });
928
+ stats.recordError({ method, path: pathname, message: `${error.name}: ${error.message}` });
929
+ log.error(`${method} ${pathname} 500 ${formatDuration(ms)}`);
930
+ printError(error, `${method} ${pathname}`);
448
931
  if (pathname.startsWith("/api/")) {
449
932
  res.statusCode = 500;
450
933
  res.setHeader("content-type", "application/json");
451
934
  res.end(JSON.stringify({ error: error.message }));
452
935
  return;
453
936
  }
454
- const page = renderDevError(error, { method: req.method ?? "GET", pathname });
937
+ const page = renderDevError(error, { method, pathname });
455
938
  const html = await vite.transformIndexHtml(url, page).catch(() => page);
456
939
  res.statusCode = 500;
457
940
  res.setHeader("content-type", "text/html; charset=utf-8");
@@ -460,18 +943,26 @@ async function startDev(port) {
460
943
  }
461
944
  const server = http.createServer((req, res) => {
462
945
  vite.middlewares(req, res, () => {
463
- handleSsr(req, res);
946
+ void handleSsr(req, res);
464
947
  });
465
948
  });
466
949
  vite = await createViteServer({
467
950
  root: paths.root,
468
951
  appType: "custom",
469
- plugins: kiln({ pagesDir: paths.pagesDir, apiDir: paths.apiDir }),
952
+ plugins: kiln({
953
+ pagesDir: paths.pagesDir,
954
+ apiDir: paths.apiDir,
955
+ appDir: path8.join(paths.root, "app")
956
+ }),
470
957
  logLevel: "warn",
471
958
  server: { middlewareMode: true, hmr: { server } }
472
959
  });
473
- vite.watcher.on("change", (file) => {
474
- const shown = file.replace(paths.root, "").replace(/\\/g, "/");
960
+ vite.watcher.on("all", (_event, file2) => {
961
+ const f = file2.replace(/\\/g, "/");
962
+ if (f.includes("/app/") || f.includes("/packages/")) handler = null;
963
+ });
964
+ vite.watcher.on("change", (file2) => {
965
+ const shown = file2.replace(paths.root, "").replace(/\\/g, "/");
475
966
  log.change(shown);
476
967
  if (lastRenderFailed) {
477
968
  lastRenderFailed = false;
@@ -479,11 +970,15 @@ async function startDev(port) {
479
970
  }
480
971
  });
481
972
  server.listen(port, () => {
482
- box([
483
- colors.bold("Kiln dev server"),
484
- `${colors.sky(origin)} ${colors.gray(`ready in ${formatDuration(performance.now() - startedAt)}`)}`,
485
- colors.dim("press Ctrl+C to stop")
486
- ], colors.fire);
973
+ box(
974
+ [
975
+ colors.bold("Kiln dev server"),
976
+ `${colors.sky(origin)} ${colors.gray(`ready in ${formatDuration(performance.now() - startedAt)}`)}`,
977
+ `${colors.sky(`${origin}/__kiln`)} ${colors.gray("dashboard (dev only)")}`,
978
+ colors.dim("press Ctrl+C to stop")
979
+ ],
980
+ colors.fire
981
+ );
487
982
  });
488
983
  process.once("SIGINT", async () => {
489
984
  log.info("Shutting down");
@@ -493,19 +988,34 @@ async function startDev(port) {
493
988
  });
494
989
  }
495
990
 
496
- // src/build.ts
497
- import fs3 from "fs";
498
- import path4 from "path";
991
+ // packages/cli/src/build.ts
992
+ import fs6 from "node:fs";
993
+ import path9 from "node:path";
499
994
  import { build } from "vite";
500
- import { adaptVercel } from "@kiln-js/adapter-vercel";
501
995
  import { kiln as kiln2 } from "@kiln-js/vite-plugin";
996
+ import { adaptVercel } from "@kiln-js/adapter-vercel";
997
+
998
+ // packages/cli/src/engine.ts
999
+ function detectEngine() {
1000
+ const bun = globalThis.Bun;
1001
+ if (bun) {
1002
+ return { runtime: "bun", version: bun.version, bundler: "bun", label: `bun ${bun.version} \xB7 Bun.build` };
1003
+ }
1004
+ return {
1005
+ runtime: "node",
1006
+ version: process.versions.node,
1007
+ bundler: "esbuild",
1008
+ label: `node ${process.versions.node} \xB7 esbuild`
1009
+ };
1010
+ }
1011
+
1012
+ // packages/cli/src/build.ts
502
1013
  var TARGETS = ["none", "vercel"];
503
1014
  function dirSize(dir) {
504
- if (!fs3.existsSync(dir))
505
- return 0;
506
- return fs3.readdirSync(dir, { withFileTypes: true }).reduce((sum, entry) => {
507
- const full = path4.join(dir, entry.name);
508
- return sum + (entry.isDirectory() ? dirSize(full) : fs3.statSync(full).size);
1015
+ if (!fs6.existsSync(dir)) return 0;
1016
+ return fs6.readdirSync(dir, { withFileTypes: true }).reduce((sum, entry) => {
1017
+ const full = path9.join(dir, entry.name);
1018
+ return sum + (entry.isDirectory() ? dirSize(full) : fs6.statSync(full).size);
509
1019
  }, 0);
510
1020
  }
511
1021
  async function runBuild(target = "none") {
@@ -514,43 +1024,59 @@ async function runBuild(target = "none") {
514
1024
  }
515
1025
  const total = performance.now();
516
1026
  loadEnvFiles("production");
1027
+ const engine = detectEngine();
517
1028
  const entries = resolveEntries();
518
- const plugins = kiln2({ pagesDir: paths.pagesDir, apiDir: paths.apiDir });
519
- log.info(`Building for production ${colors.gray(`\xB7 target ${target}`)}`);
520
- await task("client bundle", () => build({
521
- root: paths.root,
522
- plugins,
523
- logLevel: "warn",
524
- build: {
525
- outDir: paths.clientOut,
526
- emptyOutDir: true,
527
- manifest: true,
528
- rollupOptions: { input: entries.client }
529
- }
530
- }));
531
- await task("server bundle", () => build({
532
- root: paths.root,
533
- plugins,
534
- logLevel: "warn",
535
- build: {
536
- ssr: entries.server,
537
- outDir: paths.serverOut,
538
- emptyOutDir: true,
539
- rollupOptions: { output: { entryFileNames: "server.js" } }
540
- }
541
- }));
542
- if (target === "vercel") {
543
- await task("vercel output", () => adaptVercel({
1029
+ const plugins = kiln2({
1030
+ pagesDir: paths.pagesDir,
1031
+ apiDir: paths.apiDir,
1032
+ appDir: path9.join(paths.root, "app")
1033
+ });
1034
+ log.info(`Building for production ${colors.gray(`\xB7 target ${target} \xB7 ${engine.label}`)}`);
1035
+ await task(
1036
+ "client bundle",
1037
+ () => build({
544
1038
  root: paths.root,
545
- clientOut: paths.clientOut,
546
- serverOut: paths.serverOut,
547
- clientRel: entries.clientRel
548
- }));
1039
+ plugins,
1040
+ logLevel: "warn",
1041
+ build: {
1042
+ outDir: paths.clientOut,
1043
+ emptyOutDir: true,
1044
+ manifest: true,
1045
+ rollupOptions: { input: entries.client }
1046
+ }
1047
+ })
1048
+ );
1049
+ await task(
1050
+ "server bundle",
1051
+ () => build({
1052
+ root: paths.root,
1053
+ plugins,
1054
+ logLevel: "warn",
1055
+ build: {
1056
+ ssr: entries.server,
1057
+ outDir: paths.serverOut,
1058
+ emptyOutDir: true,
1059
+ rollupOptions: { output: { entryFileNames: "server.js" } }
1060
+ }
1061
+ })
1062
+ );
1063
+ if (target === "vercel") {
1064
+ await task(
1065
+ `vercel output (${engine.bundler})`,
1066
+ () => adaptVercel({
1067
+ root: paths.root,
1068
+ clientOut: paths.clientOut,
1069
+ serverOut: paths.serverOut,
1070
+ clientRel: entries.clientRel,
1071
+ bundler: engine.bundler
1072
+ })
1073
+ );
549
1074
  }
550
1075
  const lines = [
551
1076
  `${colors.bold("Build complete")} ${colors.gray(formatDuration(performance.now() - total))}`,
552
1077
  `${colors.sky("client")} ${formatBytes(dirSize(paths.clientOut))}`,
553
- `${colors.violet("server")} ${formatBytes(dirSize(paths.serverOut))}`
1078
+ `${colors.violet("server")} ${formatBytes(dirSize(paths.serverOut))}`,
1079
+ `${colors.gray("engine")} ${engine.label}`
554
1080
  ];
555
1081
  if (target === "vercel") {
556
1082
  lines.push(`${colors.fire("vercel")} .vercel/output ${colors.dim("\u2192 vercel deploy --prebuilt")}`);
@@ -558,30 +1084,47 @@ async function runBuild(target = "none") {
558
1084
  box(lines, colors.mint);
559
1085
  }
560
1086
 
561
- // src/start.ts
562
- import path5 from "path";
563
- import { pathToFileURL } from "url";
1087
+ // packages/cli/src/start.ts
1088
+ import fs8 from "node:fs";
1089
+ import path11 from "node:path";
1090
+ import { randomUUID } from "node:crypto";
1091
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
564
1092
 
565
- // src/compress.ts
566
- import { brotliCompressSync, gzipSync, constants } from "zlib";
1093
+ // packages/cli/src/compress.ts
1094
+ import fs7 from "node:fs";
1095
+ import path10 from "node:path";
1096
+ import { brotliCompressSync, gzipSync, constants } from "node:zlib";
567
1097
  var COMPRESSIBLE = /^(text\/|application\/(javascript|json|xml|xhtml\+xml|wasm)|image\/svg\+xml)/;
568
1098
  var MIN_SIZE = 1024;
569
1099
  var MAX_CACHE = 64;
570
- var staticCache = new Map;
1100
+ var MIME = {
1101
+ ".html": "text/html; charset=utf-8",
1102
+ ".js": "text/javascript; charset=utf-8",
1103
+ ".mjs": "text/javascript; charset=utf-8",
1104
+ ".css": "text/css; charset=utf-8",
1105
+ ".json": "application/json; charset=utf-8",
1106
+ ".map": "application/json; charset=utf-8",
1107
+ ".txt": "text/plain; charset=utf-8",
1108
+ ".svg": "image/svg+xml",
1109
+ ".png": "image/png",
1110
+ ".jpg": "image/jpeg",
1111
+ ".jpeg": "image/jpeg",
1112
+ ".gif": "image/gif",
1113
+ ".webp": "image/webp",
1114
+ ".ico": "image/x-icon",
1115
+ ".woff": "font/woff",
1116
+ ".woff2": "font/woff2"
1117
+ };
1118
+ var staticCache = /* @__PURE__ */ new Map();
571
1119
  function cacheSet(key, value) {
572
- if (staticCache.size >= MAX_CACHE) {
573
- staticCache.delete(staticCache.keys().next().value);
574
- }
1120
+ if (staticCache.size >= MAX_CACHE) staticCache.delete(staticCache.keys().next().value);
575
1121
  staticCache.set(key, value);
576
1122
  }
577
1123
  function pickEncoding(header) {
578
- if (!header)
579
- return null;
1124
+ if (!header) return null;
580
1125
  const accepts = header.toLowerCase();
581
- if (/\bbr\b/.test(accepts))
582
- return "br";
583
- if (/\bgzip\b/.test(accepts))
584
- return "gzip";
1126
+ if (/\bbr\b/.test(accepts)) return "br";
1127
+ if (/\bgzip\b/.test(accepts)) return "gzip";
585
1128
  return null;
586
1129
  }
587
1130
  function encode(body, encoding) {
@@ -591,27 +1134,31 @@ function encode(body, encoding) {
591
1134
  async function compressResponse(req, res) {
592
1135
  const headers = new Headers(res.headers);
593
1136
  headers.append("vary", "Accept-Encoding");
594
- const encoding = pickEncoding(req.headers.get("accept-encoding"));
1137
+ const accept = req.headers.get("accept-encoding");
595
1138
  const type = headers.get("content-type") ?? "";
596
- if (!encoding || !COMPRESSIBLE.test(type) || headers.has("content-encoding") || !res.body) {
1139
+ const skip = !res.body || req.method === "HEAD" || headers.has("content-encoding") || !COMPRESSIBLE.test(type) || !pickEncoding(accept);
1140
+ if (skip || !res.body) return new Response(res.body, { status: res.status, headers });
1141
+ if (!(accept ?? "").toLowerCase().includes("gzip")) {
597
1142
  return new Response(res.body, { status: res.status, headers });
598
1143
  }
599
- const raw = new Uint8Array(await res.arrayBuffer());
600
- if (raw.byteLength < MIN_SIZE)
601
- return new Response(raw, { status: res.status, headers });
602
- const out = encode(raw, encoding);
603
- headers.set("content-encoding", encoding);
604
- headers.set("content-length", String(out.byteLength));
605
- return new Response(out, { status: res.status, headers });
1144
+ headers.delete("content-length");
1145
+ headers.set("content-encoding", "gzip");
1146
+ const gzipped = res.body.pipeThrough(new CompressionStream("gzip"));
1147
+ return new Response(gzipped, { status: res.status, headers });
606
1148
  }
607
1149
  async function serveStatic(req, filePath) {
608
- const file = Bun.file(filePath);
609
- if (!await file.exists())
1150
+ let stat;
1151
+ try {
1152
+ stat = await fs7.promises.stat(filePath);
1153
+ } catch {
610
1154
  return null;
611
- const etag = `W/"${file.size}-${file.lastModified}"`;
1155
+ }
1156
+ if (!stat.isFile()) return null;
1157
+ const type = MIME[path10.extname(filePath).toLowerCase()] ?? "application/octet-stream";
1158
+ const etag = `W/"${stat.size}-${stat.mtimeMs}"`;
612
1159
  const isHashed = /[\\/]assets[\\/]/.test(filePath);
613
1160
  const headers = new Headers({
614
- "content-type": file.type,
1161
+ "content-type": type,
615
1162
  etag,
616
1163
  "cache-control": isHashed ? "public, max-age=31536000, immutable" : "no-cache",
617
1164
  vary: "Accept-Encoding"
@@ -619,14 +1166,16 @@ async function serveStatic(req, filePath) {
619
1166
  if (req.headers.get("if-none-match") === etag) {
620
1167
  return new Response(null, { status: 304, headers });
621
1168
  }
1169
+ const raw = new Uint8Array(await fs7.promises.readFile(filePath));
622
1170
  const encoding = pickEncoding(req.headers.get("accept-encoding"));
623
- if (!encoding || !COMPRESSIBLE.test(file.type) || file.size < MIN_SIZE) {
624
- return new Response(file, { headers });
1171
+ if (!encoding || !COMPRESSIBLE.test(type) || raw.byteLength < MIN_SIZE) {
1172
+ headers.set("content-length", String(raw.byteLength));
1173
+ return new Response(raw, { headers });
625
1174
  }
626
1175
  const key = `${filePath}|${etag}|${encoding}`;
627
1176
  let body = staticCache.get(key);
628
1177
  if (!body) {
629
- body = encode(new Uint8Array(await file.arrayBuffer()), encoding);
1178
+ body = encode(raw, encoding);
630
1179
  cacheSet(key, body);
631
1180
  }
632
1181
  headers.set("content-encoding", encoding);
@@ -634,51 +1183,111 @@ async function serveStatic(req, filePath) {
634
1183
  return new Response(body, { headers });
635
1184
  }
636
1185
 
637
- // src/start.ts
1186
+ // packages/cli/src/runtime.ts
1187
+ import http2 from "node:http";
1188
+ var runtime = globalThis.Bun ? "bun" : "node";
1189
+ var nodeVersion = process.versions.node;
1190
+ function serve(port, fetch) {
1191
+ if (runtime === "bun") {
1192
+ const bun = globalThis.Bun;
1193
+ const server2 = bun.serve({ port, fetch });
1194
+ return { port, stop: () => server2.stop() };
1195
+ }
1196
+ const server = http2.createServer(async (req, res) => {
1197
+ try {
1198
+ await writeResponse(res, await fetch(await toRequest(req, port)));
1199
+ } catch (err) {
1200
+ console.error("[kiln] request failed", err);
1201
+ if (!res.headersSent) res.statusCode = 500;
1202
+ res.end("Internal Server Error");
1203
+ }
1204
+ });
1205
+ server.listen(port);
1206
+ return { port, stop: () => server.close() };
1207
+ }
1208
+ async function toRequest(req, port) {
1209
+ const headers = new Headers();
1210
+ for (const [key, value] of Object.entries(req.headers)) {
1211
+ if (value === void 0) continue;
1212
+ for (const v of Array.isArray(value) ? value : [value]) headers.append(key, v);
1213
+ }
1214
+ const method = req.method ?? "GET";
1215
+ const init = { method, headers };
1216
+ if (method !== "GET" && method !== "HEAD") {
1217
+ const chunks = [];
1218
+ for await (const chunk of req) chunks.push(chunk);
1219
+ init.body = Buffer.concat(chunks);
1220
+ }
1221
+ return new Request(new URL(req.url ?? "/", `http://localhost:${port}`), init);
1222
+ }
1223
+ async function writeResponse(res, response) {
1224
+ res.statusCode = response.status;
1225
+ response.headers.forEach((value, key) => {
1226
+ if (key !== "set-cookie") res.setHeader(key, value);
1227
+ });
1228
+ const cookies = response.headers.getSetCookie?.() ?? [];
1229
+ if (cookies.length) res.setHeader("set-cookie", cookies);
1230
+ if (!response.body) {
1231
+ res.end();
1232
+ return;
1233
+ }
1234
+ const reader = response.body.getReader();
1235
+ for (; ; ) {
1236
+ const { done, value } = await reader.read();
1237
+ if (done) break;
1238
+ res.write(value);
1239
+ }
1240
+ res.end();
1241
+ }
1242
+
1243
+ // packages/cli/src/start.ts
1244
+ function safeDecode(p) {
1245
+ try {
1246
+ return decodeURIComponent(p);
1247
+ } catch {
1248
+ return null;
1249
+ }
1250
+ }
638
1251
  async function runStart(port) {
639
1252
  const startedAt = performance.now();
640
1253
  loadEnvFiles("production");
641
1254
  const { clientRel } = resolveEntries();
642
- const manifest = JSON.parse(await Bun.file(path5.join(paths.clientOut, ".vite/manifest.json")).text());
1255
+ const manifest = JSON.parse(fs8.readFileSync(path11.join(paths.clientOut, ".vite", "manifest.json"), "utf8"));
643
1256
  const entry = manifest[clientRel];
644
- if (!entry)
645
- throw new Error(`No manifest entry for ${clientRel}. Run "kiln build" first.`);
1257
+ if (!entry) throw new Error(`No manifest entry for ${clientRel}. Run "kiln build" first.`);
646
1258
  const assets = {
647
- head: (entry.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}">`).join(`
648
- `),
1259
+ head: (entry.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}">`).join("\n"),
649
1260
  entry: `/${entry.file}`
650
1261
  };
651
- const serverEntry = await import(pathToFileURL(path5.join(paths.serverOut, "server.js")).href);
1262
+ const serverEntry = await import(pathToFileURL2(path11.join(paths.serverOut, "server.js")).href);
652
1263
  const handler = serverEntry.createHandler(assets);
653
- const server = Bun.serve({
654
- port,
655
- async fetch(req) {
656
- const started = performance.now();
657
- const { pathname } = new URL(req.url);
658
- const requestId = crypto.randomUUID().slice(0, 8);
659
- try {
660
- if (pathname !== "/") {
661
- const filePath = path5.join(paths.clientOut, decodeURIComponent(pathname));
662
- if (filePath.startsWith(paths.clientOut + path5.sep)) {
663
- const asset = await serveStatic(req, filePath);
664
- if (asset)
665
- return asset;
666
- }
667
- }
668
- const res = await compressResponse(req, await handler(req));
669
- log.request(req.method, pathname, res.status, formatDuration(performance.now() - started));
670
- return res;
671
- } catch (err) {
672
- log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - started)} [${requestId}]`);
673
- printError(err, `${req.method} ${pathname} [${requestId}]`);
674
- if (pathname.startsWith("/api/")) {
675
- return Response.json({ error: "Internal Server Error", requestId }, { status: 500 });
1264
+ const server = serve(port, async (req) => {
1265
+ const started = performance.now();
1266
+ const { pathname } = new URL(req.url);
1267
+ const requestId = randomUUID().slice(0, 8);
1268
+ try {
1269
+ if (pathname !== "/") {
1270
+ const decoded = safeDecode(pathname);
1271
+ if (decoded === null) return new Response("Bad Request", { status: 400 });
1272
+ const filePath = path11.join(paths.clientOut, decoded);
1273
+ if (filePath.startsWith(paths.clientOut + path11.sep)) {
1274
+ const asset = await serveStatic(req, filePath);
1275
+ if (asset) return asset;
676
1276
  }
677
- return new Response(renderProdError(requestId), {
678
- status: 500,
679
- headers: { "content-type": "text/html; charset=utf-8" }
680
- });
681
1277
  }
1278
+ const res = await compressResponse(req, await handler(req));
1279
+ log.request(req.method, pathname, res.status, formatDuration(performance.now() - started));
1280
+ return res;
1281
+ } catch (err) {
1282
+ log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - started)} [${requestId}]`);
1283
+ printError(err, `${req.method} ${pathname} [${requestId}]`);
1284
+ if (pathname.startsWith("/api/")) {
1285
+ return Response.json({ error: "Internal Server Error", requestId }, { status: 500 });
1286
+ }
1287
+ return new Response(renderProdError(requestId), {
1288
+ status: 500,
1289
+ headers: { "content-type": "text/html; charset=utf-8" }
1290
+ });
682
1291
  }
683
1292
  });
684
1293
  const shutdown = () => {
@@ -688,36 +1297,39 @@ async function runStart(port) {
688
1297
  };
689
1298
  process.once("SIGINT", shutdown);
690
1299
  process.once("SIGTERM", shutdown);
691
- box([
692
- colors.bold("Kiln production server"),
693
- `${colors.sky(`http://localhost:${port}`)} ${colors.gray(`ready in ${formatDuration(performance.now() - startedAt)}`)}`
694
- ], colors.mint);
1300
+ box(
1301
+ [
1302
+ colors.bold("Kiln production server"),
1303
+ `${colors.sky(`http://localhost:${port}`)} ${colors.gray(`${runtime} \xB7 ready in ${formatDuration(performance.now() - startedAt)}`)}`
1304
+ ],
1305
+ colors.mint
1306
+ );
695
1307
  }
696
1308
 
697
- // src/routes.ts
698
- import fs4 from "fs";
699
- import path6 from "path";
700
- import { scanRoutes, scanApi } from "@kiln-js/core/scan";
1309
+ // packages/cli/src/routes.ts
1310
+ import fs9 from "node:fs";
1311
+ import path12 from "node:path";
1312
+ import { scanRoutes as scanRoutes2, scanApi as scanApi2 } from "@kiln-js/core/scan";
701
1313
  var METHOD_RE = /export\s+(?:async\s+)?(?:function|const)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
702
1314
  var MODE_COLORS = {
703
1315
  universal: colors.mint,
704
1316
  server: colors.sky,
705
1317
  client: colors.violet
706
1318
  };
707
- var rel2 = (file) => path6.relative(paths.root, file).split(path6.sep).join("/");
708
- function methodsOf(file) {
709
- const src = fs4.readFileSync(file, "utf8");
1319
+ var rel4 = (file2) => path12.relative(paths.root, file2).split(path12.sep).join("/");
1320
+ function methodsOf(file2) {
1321
+ const src = fs9.readFileSync(file2, "utf8");
710
1322
  return [...src.matchAll(METHOD_RE)].map((m) => m[1]);
711
1323
  }
712
1324
  function printRoutes() {
713
- const pages = scanRoutes(paths.pagesDir);
714
- const apis = scanApi(paths.apiDir);
1325
+ const pages = scanRoutes2(paths.pagesDir);
1326
+ const apis = scanApi2(paths.apiDir);
715
1327
  const rows = [
716
1328
  ...pages.map((r) => [
717
1329
  colors.bold(r.pattern),
718
1330
  colors.gray("page"),
719
1331
  MODE_COLORS[r.mode](r.mode),
720
- colors.dim(rel2(r.file))
1332
+ colors.dim(rel4(r.file))
721
1333
  ]),
722
1334
  ...apis.map((r) => {
723
1335
  const methods = methodsOf(r.file);
@@ -725,7 +1337,7 @@ function printRoutes() {
725
1337
  colors.bold(r.pattern),
726
1338
  colors.fire("api"),
727
1339
  methods.map((m) => methodColor(m)(m)).join(" ") || colors.gray("none"),
728
- colors.dim(rel2(r.file))
1340
+ colors.dim(rel4(r.file))
729
1341
  ];
730
1342
  })
731
1343
  ];
@@ -733,12 +1345,12 @@ function printRoutes() {
733
1345
  table(rows, ["PATTERN", "KIND", "MODE / METHODS", "FILE"]);
734
1346
  }
735
1347
 
736
- // src/create.ts
737
- import fs5 from "fs";
738
- import path7 from "path";
1348
+ // packages/cli/src/create.ts
1349
+ import fs10 from "node:fs";
1350
+ import path13 from "node:path";
739
1351
  import inquirer from "inquirer";
740
1352
 
741
- // src/templates.ts
1353
+ // packages/cli/src/templates.ts
742
1354
  var SCOPE = "@kiln-js";
743
1355
  var CLI_PACKAGE = "kiln";
744
1356
  var KILN_VERSION = "0.1.3";
@@ -748,11 +1360,8 @@ var kilnDep = (linked) => linked ? "*" : `^${KILN_VERSION}`;
748
1360
  var SUFFIX = { universal: "", server: ".server", client: ".client" };
749
1361
  function homePage(name, mode) {
750
1362
  const stateful = mode !== "server";
751
- return `${stateful ? `import { useState } from "react";
752
-
753
- ` : ""}export default function Home() {
754
- ${stateful ? ` const [count, setCount] = useState(0);
755
- ` : ""} return (
1363
+ return `${stateful ? 'import { useState } from "react";\n\n' : ""}export default function Home() {
1364
+ ${stateful ? " const [count, setCount] = useState(0);\n" : ""} return (
756
1365
  <section>
757
1366
  <kiln:title>Home \xB7 ${name}</kiln:title>
758
1367
  <h1>Welcome to ${name}</h1>
@@ -781,8 +1390,7 @@ export default function Layout({ children }: { children: ReactNode }) {
781
1390
  <nav>
782
1391
  <Link href="/">Home</Link>{" "}
783
1392
  <Link href="/about">About</Link>{" "}
784
- ${withBlog ? `<Link href="/blog">Blog</Link>{" "}
785
- <Link href="/pricing">Pricing</Link>` : ""}
1393
+ ${withBlog ? '<Link href="/blog">Blog</Link>{" "}\n <Link href="/pricing">Pricing</Link>' : ""}
786
1394
  </nav>
787
1395
  <main>{children}</main>
788
1396
  </>
@@ -836,7 +1444,7 @@ export function GET(_ctx: ApiContext) {
836
1444
  return Response.json({ ok: true, time: new Date().toISOString() });
837
1445
  }
838
1446
  `;
839
- var CSS = `body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
1447
+ var CSS2 = `body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
840
1448
  nav a { margin-right: 1rem; }
841
1449
  `;
842
1450
  var TSCONFIG = `{
@@ -886,16 +1494,10 @@ function projectFiles(o) {
886
1494
  vite: VITE_VERSION
887
1495
  }
888
1496
  };
889
- files["package.json"] = JSON.stringify(pkgJson, null, 2) + `
890
- `;
1497
+ files["package.json"] = JSON.stringify(pkgJson, null, 2) + "\n";
891
1498
  files["tsconfig.json"] = TSCONFIG;
892
- files[".gitignore"] = `node_modules
893
- dist
894
- .kiln
895
- .env.local
896
- .vercel
897
- `;
898
- files["app/index.css"] = CSS;
1499
+ files[".gitignore"] = "node_modules\ndist\n.kiln\n.env.local\n.vercel\n";
1500
+ files["app/index.css"] = CSS2;
899
1501
  files["app/pages/_layout.tsx"] = LAYOUT(withBlog);
900
1502
  files[`app/pages/index${SUFFIX[o.defaultMode]}.tsx`] = homePage(o.name, o.defaultMode);
901
1503
  if (o.template !== "minimal") {
@@ -906,8 +1508,7 @@ dist
906
1508
  files["app/pages/blog/[slug].tsx"] = BLOG_POST;
907
1509
  files["app/pages/(marketing)/pricing.tsx"] = PRICING;
908
1510
  }
909
- if (o.api)
910
- files["app/api/health.ts"] = HEALTH;
1511
+ if (o.api) files["app/api/health.ts"] = HEALTH;
911
1512
  if (o.env) {
912
1513
  files[".env"] = `# Exposed to the browser through import.meta.env
913
1514
  KILN_PUBLIC_SITE_NAME=${o.name}
@@ -929,7 +1530,8 @@ export function createHandler(assets: KilnAssets) {
929
1530
  return files;
930
1531
  }
931
1532
 
932
- // src/create.ts
1533
+ // packages/cli/src/create.ts
1534
+ import { spawn } from "node:child_process";
933
1535
  async function runCreate(nameArg) {
934
1536
  const answers = await inquirer.prompt([
935
1537
  {
@@ -995,8 +1597,8 @@ async function runCreate(nameArg) {
995
1597
  customEntries: extras.includes("entries"),
996
1598
  linked: answers.linked
997
1599
  };
998
- const dir = path7.resolve(process.cwd(), options.name);
999
- if (fs5.existsSync(dir) && fs5.readdirSync(dir).length > 0) {
1600
+ const dir = path13.resolve(process.cwd(), options.name);
1601
+ if (fs10.existsSync(dir) && fs10.readdirSync(dir).length > 0) {
1000
1602
  const { overwrite } = await inquirer.prompt([
1001
1603
  {
1002
1604
  type: "confirm",
@@ -1011,24 +1613,25 @@ async function runCreate(nameArg) {
1011
1613
  }
1012
1614
  }
1013
1615
  log.step(`Writing project to ${dir}`);
1014
- for (const [rel, content] of Object.entries(projectFiles(options))) {
1015
- const target = path7.join(dir, rel);
1016
- fs5.mkdirSync(path7.dirname(target), { recursive: true });
1017
- fs5.writeFileSync(target, content);
1616
+ for (const [rel5, content] of Object.entries(projectFiles(options))) {
1617
+ const target = path13.join(dir, rel5);
1618
+ fs10.mkdirSync(path13.dirname(target), { recursive: true });
1619
+ fs10.writeFileSync(target, content);
1018
1620
  }
1019
1621
  log.success(`Created ${options.name}`);
1020
1622
  if (answers.install) {
1021
1623
  log.step("Installing dependencies");
1022
- const proc = Bun.spawn(["bun", "install"], { cwd: dir, stdout: "inherit", stderr: "inherit" });
1023
- if (await proc.exited !== 0)
1024
- log.error("bun install failed");
1624
+ await new Promise(async (resolve, reject) => {
1625
+ const proc = spawn("bun", ["install"], { cwd: dir, stdio: "inherit", shell: true });
1626
+ proc.on("exit", (code) => code === 0 ? resolve() : reject(new Error("bun install failed")));
1627
+ });
1025
1628
  }
1026
1629
  log.info(`Next: cd ${options.name} && bun run dev`);
1027
1630
  }
1028
1631
 
1029
- // src/generate.ts
1030
- import fs6 from "fs";
1031
- import path8 from "path";
1632
+ // packages/cli/src/generate.ts
1633
+ import fs11 from "node:fs";
1634
+ import path14 from "node:path";
1032
1635
  import inquirer2 from "inquirer";
1033
1636
  var SUFFIX2 = { universal: "", server: ".server", client: ".client" };
1034
1637
  var ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
@@ -1048,6 +1651,7 @@ function pageTemplate(name, loader) {
1048
1651
  const dataProp = loader ? "data" : "";
1049
1652
  const props = loader ? "{ data, params }" : "{ params }";
1050
1653
  const propType = loader ? "{ data: { title: string; slug: Record<string, string> }; params: Record<string, string> }" : "{ params: Record<string, string> }";
1654
+ void dataProp;
1051
1655
  return `${loaderBlock}export default function ${comp}(${props}: ${propType}) {
1052
1656
  return (
1053
1657
  <section>
@@ -1074,8 +1678,7 @@ function apiTemplate(methods) {
1074
1678
  });
1075
1679
  return `import type { ApiContext } from "@kiln-js/server";
1076
1680
 
1077
- ${handlers.join(`
1078
- `)}`;
1681
+ ${handlers.join("\n")}`;
1079
1682
  }
1080
1683
  var LAYOUT_TEMPLATE = `import type { ReactNode } from "react";
1081
1684
 
@@ -1084,11 +1687,9 @@ export default function Layout({ children }: { children: ReactNode }) {
1084
1687
  }
1085
1688
  `;
1086
1689
  function targetFor(kind, name, mode) {
1087
- if (kind === "page")
1088
- return path8.join(paths.pagesDir, `${name}${SUFFIX2[mode]}.tsx`);
1089
- if (kind === "api")
1090
- return path8.join(paths.apiDir, `${name}.ts`);
1091
- return path8.join(paths.pagesDir, name, "_layout.tsx");
1690
+ if (kind === "page") return path14.join(paths.pagesDir, `${name}${SUFFIX2[mode]}.tsx`);
1691
+ if (kind === "api") return path14.join(paths.apiDir, `${name}.ts`);
1692
+ return path14.join(paths.pagesDir, name, "_layout.tsx");
1092
1693
  }
1093
1694
  async function runGenerate(kindArg, nameArg, opts = {}) {
1094
1695
  resolveEntries();
@@ -1130,7 +1731,7 @@ async function runGenerate(kindArg, nameArg, opts = {}) {
1130
1731
  ])).mode;
1131
1732
  }
1132
1733
  let loader = !!opts.loader;
1133
- if (kind === "page" && opts.loader === undefined && mode !== "client") {
1734
+ if (kind === "page" && opts.loader === void 0 && mode !== "client") {
1134
1735
  loader = (await inquirer2.prompt([
1135
1736
  { type: "confirm", name: "loader", message: "Add a loader?", default: false }
1136
1737
  ])).loader;
@@ -1150,27 +1751,292 @@ async function runGenerate(kindArg, nameArg, opts = {}) {
1150
1751
  ])).methods;
1151
1752
  }
1152
1753
  const invalid = methods.filter((m) => !ALL_METHODS.includes(m));
1153
- if (invalid.length)
1154
- throw new Error(`Unsupported method(s): ${invalid.join(", ")}`);
1155
- if (methods.length === 0)
1156
- throw new Error("Pick at least one HTTP method");
1754
+ if (invalid.length) throw new Error(`Unsupported method(s): ${invalid.join(", ")}`);
1755
+ if (methods.length === 0) throw new Error("Pick at least one HTTP method");
1157
1756
  }
1158
- const file = targetFor(kind, name, mode);
1159
- if (fs6.existsSync(file)) {
1160
- throw new Error(`${path8.relative(paths.root, file)} already exists`);
1757
+ const file2 = targetFor(kind, name, mode);
1758
+ if (fs11.existsSync(file2)) {
1759
+ throw new Error(`${path14.relative(paths.root, file2)} already exists`);
1161
1760
  }
1162
1761
  const content = kind === "page" ? pageTemplate(name, loader) : kind === "api" ? apiTemplate(methods) : LAYOUT_TEMPLATE;
1163
- fs6.mkdirSync(path8.dirname(file), { recursive: true });
1164
- fs6.writeFileSync(file, content);
1165
- log.success(`Created ${path8.relative(paths.root, file).replace(/\\/g, "/")}`);
1762
+ fs11.mkdirSync(path14.dirname(file2), { recursive: true });
1763
+ fs11.writeFileSync(file2, content);
1764
+ log.success(`Created ${path14.relative(paths.root, file2).replace(/\\/g, "/")}`);
1166
1765
  log.info("Run `kiln routes` to see the new route.");
1167
1766
  }
1168
1767
 
1169
- // src/index.ts
1170
- var VERSION = "0.1.0";
1768
+ // packages/cli/src/typecheck.ts
1769
+ import { spawn as spawn2 } from "node:child_process";
1770
+ import { createRequire } from "node:module";
1771
+ import path15 from "node:path";
1772
+ var LINE = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/;
1773
+ function tscPath() {
1774
+ const req = createRequire(path15.join(paths.root, "package.json"));
1775
+ return path15.join(path15.dirname(req.resolve("typescript/package.json")), "bin", "tsc");
1776
+ }
1777
+ function runTsc() {
1778
+ return new Promise((resolve) => {
1779
+ const proc = spawn2(process.execPath, [tscPath(), "--noEmit", "-p", "tsconfig.json", "--pretty", "false"], {
1780
+ cwd: paths.root
1781
+ });
1782
+ let output = "";
1783
+ proc.stdout.on("data", (d) => output += d);
1784
+ proc.stderr.on("data", (d) => output += d);
1785
+ proc.on("close", () => resolve(output));
1786
+ });
1787
+ }
1788
+ async function runTypecheck() {
1789
+ resolveEntries();
1790
+ log.info("Typechecking");
1791
+ const started = performance.now();
1792
+ const output = await runTsc();
1793
+ const errors = output.split(/\r?\n/).map((line) => line.match(LINE)).filter((m) => m !== null);
1794
+ for (const [, file2, line, col, code, message] of errors) {
1795
+ const shown = path15.relative(paths.root, path15.resolve(paths.root, file2)).replace(/\\/g, "/");
1796
+ console.log(` ${colors.red("\u2716")} ${colors.cyan(`${shown}:${line}:${col}`)} ${colors.gray(code)}`);
1797
+ console.log(` ${message}`);
1798
+ }
1799
+ const time2 = formatDuration(performance.now() - started);
1800
+ if (errors.length === 0 && /error/i.test(output) === false) {
1801
+ log.success(`No type errors ${colors.gray(`(${time2})`)}`);
1802
+ return 0;
1803
+ }
1804
+ if (errors.length === 0) {
1805
+ console.log(output.trim());
1806
+ return 1;
1807
+ }
1808
+ log.error(`${errors.length} type error${errors.length === 1 ? "" : "s"} ${colors.gray(`(${time2})`)}`);
1809
+ return errors.length;
1810
+ }
1811
+
1812
+ // packages/cli/src/doctor.ts
1813
+ import fs12 from "node:fs";
1814
+ import path16 from "node:path";
1815
+ import { scanRoutes as scanRoutes3 } from "@kiln-js/core/scan";
1816
+ var file = (rel5) => path16.join(paths.root, rel5);
1817
+ var exists = (rel5) => fs12.existsSync(file(rel5));
1818
+ var read = (rel5) => exists(rel5) ? fs12.readFileSync(file(rel5), "utf8") : "";
1819
+ function atLeast(version, min) {
1820
+ const a = version.split(".").map(Number);
1821
+ const b = min.split(".").map(Number);
1822
+ for (let i = 0; i < b.length; i++) {
1823
+ if ((a[i] ?? 0) !== b[i]) return (a[i] ?? 0) > b[i];
1824
+ }
1825
+ return true;
1826
+ }
1827
+ function appSourceContains(needle) {
1828
+ const walk = (dir) => {
1829
+ if (!fs12.existsSync(dir)) return false;
1830
+ for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
1831
+ if (entry.name === "node_modules") continue;
1832
+ const full = path16.join(dir, entry.name);
1833
+ if (entry.isDirectory()) {
1834
+ if (walk(full)) return true;
1835
+ } else if (/\.(tsx?|jsx?|mdx?)$/.test(entry.name) && fs12.readFileSync(full, "utf8").includes(needle)) {
1836
+ return true;
1837
+ }
1838
+ }
1839
+ return false;
1840
+ };
1841
+ return walk(file("app"));
1842
+ }
1843
+ function runtimeSection() {
1844
+ const checks = [];
1845
+ if (runtime === "bun") {
1846
+ const version = globalThis.Bun.version;
1847
+ const ok = atLeast(version, "1.1.0");
1848
+ checks.push({ name: "Runtime", status: ok ? "ok" : "warn", detail: `Bun ${version}${ok ? "" : " (1.1 or later recommended)"}` });
1849
+ } else {
1850
+ const ok = Number(nodeVersion.split(".")[0]) >= 18;
1851
+ checks.push({ name: "Runtime", status: ok ? "ok" : "fail", detail: `Node ${nodeVersion}${ok ? "" : " (18 or later required)"}` });
1852
+ }
1853
+ checks.push({ name: "Kiln CLI", status: "ok", detail: `kiln ${cliVersion()}` });
1854
+ return { title: "Runtime", checks };
1855
+ }
1856
+ function projectSection() {
1857
+ const checks = [];
1858
+ checks.push({
1859
+ name: "package.json",
1860
+ status: exists("package.json") ? "ok" : "fail",
1861
+ detail: exists("package.json") ? "found" : "missing. Run kiln doctor inside an app folder."
1862
+ });
1863
+ checks.push({
1864
+ name: "node_modules",
1865
+ status: exists("node_modules") ? "ok" : "fail",
1866
+ detail: exists("node_modules") ? "installed" : "missing. Run bun install."
1867
+ });
1868
+ checks.push({
1869
+ name: "tsconfig.json",
1870
+ status: exists("tsconfig.json") ? "ok" : "warn",
1871
+ detail: exists("tsconfig.json") ? "found" : "missing. kiln typecheck needs it."
1872
+ });
1873
+ try {
1874
+ const routes = scanRoutes3(paths.pagesDir);
1875
+ checks.push({
1876
+ name: "Routes",
1877
+ status: routes.length > 0 ? "ok" : "fail",
1878
+ detail: routes.length > 0 ? `${routes.length} page routes, no conflicts` : "no pages in app/pages"
1879
+ });
1880
+ } catch (err) {
1881
+ checks.push({ name: "Routes", status: "fail", detail: err instanceof Error ? err.message : String(err) });
1882
+ }
1883
+ return { title: "Project", checks };
1884
+ }
1885
+ function packagesSection() {
1886
+ const expected = cliVersion();
1887
+ const checks = inspectPackages().map((p) => {
1888
+ const used = appSourceContains(`"${p.name}"`);
1889
+ if (p.version === null) {
1890
+ return used ? { name: p.name, status: "fail", detail: "imported by the app but not installed. Run bun install." } : { name: p.name, status: "warn", detail: "not installed (optional)" };
1891
+ }
1892
+ if (p.version !== expected) {
1893
+ return { name: p.name, status: "fail", detail: `${p.version}, but the CLI is ${expected}. Run bun install at the monorepo root.` };
1894
+ }
1895
+ return {
1896
+ name: p.name,
1897
+ status: "ok",
1898
+ detail: `${p.version} \xB7 ${p.linked ? "linked to the monorepo" : "installed"} \xB7 ${p.location}`
1899
+ };
1900
+ });
1901
+ return { title: "Packages", checks };
1902
+ }
1903
+ function configSection() {
1904
+ const checks = [];
1905
+ const usesDb = appSourceContains("DATABASE_URL");
1906
+ const envDefines = /^DATABASE_URL=/m.test(read(".env.local") + read(".env"));
1907
+ checks.push({
1908
+ name: "DATABASE_URL",
1909
+ status: !usesDb || envDefines ? "ok" : "warn",
1910
+ detail: !usesDb ? "not used" : envDefines ? "set in .env files" : "used in code but not in .env.local"
1911
+ });
1912
+ const usesMd = appSourceContains("@kiln-js/md");
1913
+ const configHasMd = /\bmd\s*\(/.test(read("vite.config.ts") + read("vite.config.js"));
1914
+ checks.push({
1915
+ name: "Markdown plugin",
1916
+ status: !usesMd || configHasMd ? "ok" : "warn",
1917
+ detail: !usesMd ? "not used" : configHasMd ? "registered in vite.config" : "imported but md() is not in vite.config"
1918
+ });
1919
+ const reactCopy = exists("node_modules/react-dom/node_modules/react");
1920
+ checks.push({
1921
+ name: "React copies",
1922
+ status: reactCopy ? "warn" : "ok",
1923
+ detail: reactCopy ? "two copies installed. Hooks can break. Pin one version." : "one copy"
1924
+ });
1925
+ return { title: "Configuration", checks };
1926
+ }
1927
+ var ICON = {
1928
+ ok: colors.mint("\u2714"),
1929
+ warn: colors.yellow("!"),
1930
+ fail: colors.red("\u2716")
1931
+ };
1932
+ function runDoctor() {
1933
+ log.info("Checking this project");
1934
+ const sections = [runtimeSection(), projectSection(), packagesSection(), configSection()];
1935
+ const all = sections.flatMap((s) => s.checks);
1936
+ const width = Math.max(...all.map((c) => c.name.length)) + 2;
1937
+ for (const section of sections) {
1938
+ console.log(`
1939
+ ${colors.bold(section.title)}`);
1940
+ for (const c of section.checks) {
1941
+ console.log(` ${ICON[c.status]} ${c.name.padEnd(width)} ${colors.gray(c.detail)}`);
1942
+ }
1943
+ }
1944
+ const fails = all.filter((c) => c.status === "fail").length;
1945
+ const warns = all.filter((c) => c.status === "warn").length;
1946
+ console.log("");
1947
+ if (fails) log.error(`${fails} problem${fails === 1 ? "" : "s"} to fix${warns ? `, ${warns} warning${warns === 1 ? "" : "s"}` : ""}`);
1948
+ else if (warns) log.warn(`No blocking problems, ${warns} warning${warns === 1 ? "" : "s"}`);
1949
+ else log.success("Everything looks good");
1950
+ return fails ? 1 : 0;
1951
+ }
1952
+
1953
+ // packages/cli/src/test.ts
1954
+ import { createServer as createViteServer2 } from "vite";
1955
+ import { kiln as kiln3 } from "@kiln-js/vite-plugin";
1956
+ import { scanRoutes as scanRoutes4 } from "@kiln-js/core/scan";
1957
+ function samplePath(pattern) {
1958
+ const parts = pattern.split("/").filter(Boolean).map((seg) => seg.startsWith(":") ? "example" : seg.startsWith("*") ? "a/b" : seg);
1959
+ return "/" + parts.join("/");
1960
+ }
1961
+ async function runTests(filters) {
1962
+ loadEnvFiles("development");
1963
+ const entries = resolveEntries();
1964
+ const origin = "http://localhost";
1965
+ const vite = await createViteServer2({
1966
+ root: paths.root,
1967
+ appType: "custom",
1968
+ plugins: kiln3({ pagesDir: paths.pagesDir, apiDir: paths.apiDir, appDir: "app" }),
1969
+ logLevel: "silent",
1970
+ server: { middlewareMode: true, hmr: false }
1971
+ });
1972
+ const results = [];
1973
+ try {
1974
+ const mod = await vite.ssrLoadModule(entries.server);
1975
+ const handler = mod.createHandler({
1976
+ head: "",
1977
+ entry: `/${entries.clientRel}`
1978
+ });
1979
+ const routes = scanRoutes4(paths.pagesDir).filter((r) => r.mode !== "client");
1980
+ const selected = routes.filter((r) => {
1981
+ const url = samplePath(r.pattern);
1982
+ return filters.length === 0 || filters.some((f) => url.startsWith(f));
1983
+ });
1984
+ log.info(`Rendering ${selected.length} page${selected.length === 1 ? "" : "s"}`);
1985
+ for (const route of selected) {
1986
+ const url = samplePath(route.pattern);
1987
+ const started = performance.now();
1988
+ const ms = () => performance.now() - started;
1989
+ try {
1990
+ const res = await handler(new Request(origin + url));
1991
+ const body = await res.text();
1992
+ const problems = [];
1993
+ const warnings = [];
1994
+ if (res.status >= 500) problems.push(`HTTP ${res.status} from the server`);
1995
+ if (res.status === 404) warnings.push("404 for the sample URL. Add fixture data if this page needs it.");
1996
+ if (body.trim().length === 0) problems.push("empty response body");
1997
+ if (/<title>Kiln App<\/title>/.test(body)) warnings.push("no <kiln:title>, so the default title is used");
1998
+ if (body.includes("Internal Server Error")) problems.push("the error page was rendered");
1999
+ results.push({ url, status: res.status, ms: ms(), problems, warnings });
2000
+ } catch (err) {
2001
+ const error = err instanceof Error ? err : new Error(String(err));
2002
+ vite.ssrFixStacktrace(error);
2003
+ const hints = diagnose(error, parseFrames(error.stack ?? "")).map((h) => h.title);
2004
+ results.push({
2005
+ url,
2006
+ status: "error",
2007
+ ms: ms(),
2008
+ problems: [`${error.name}: ${error.message}`, ...hints.map((h) => `hint: ${h}`)],
2009
+ warnings: []
2010
+ });
2011
+ }
2012
+ }
2013
+ } finally {
2014
+ await vite.close();
2015
+ }
2016
+ printResults(results);
2017
+ const failed = results.filter((r) => r.problems.length > 0).length;
2018
+ return failed;
2019
+ }
2020
+ function printResults(results) {
2021
+ for (const r of results) {
2022
+ const ok = r.problems.length === 0;
2023
+ const status = r.status === "error" ? colors.red("ERR") : r.status >= 500 ? colors.red(String(r.status)) : colors.mint(String(r.status));
2024
+ console.log(` ${ok ? colors.mint("\u2714") : colors.red("\u2716")} ${r.url.padEnd(28)} ${status} ${colors.gray(formatDuration(r.ms))}`);
2025
+ for (const p of r.problems) console.log(` ${colors.red("\u2716")} ${p}`);
2026
+ for (const w of r.warnings) console.log(` ${colors.yellow("!")} ${w}`);
2027
+ }
2028
+ const failed = results.filter((r) => r.problems.length > 0).length;
2029
+ console.log("");
2030
+ if (failed) log.error(`${failed} of ${results.length} page${results.length === 1 ? "" : "s"} failed`);
2031
+ else log.success(`All ${results.length} page${results.length === 1 ? "" : "s"} rendered`);
2032
+ }
2033
+
2034
+ // packages/cli/src/index.ts
2035
+ var VERSION = "0.1.5";
1171
2036
  var run = (fn) => async (...args) => {
1172
2037
  try {
1173
- await fn(...args);
2038
+ const result = await fn(...args);
2039
+ if (typeof result === "number" && result !== 0) process.exitCode = result;
1174
2040
  } catch (err) {
1175
2041
  printError(err, "while running kiln");
1176
2042
  process.exitCode = 1;
@@ -1178,14 +2044,18 @@ var run = (fn) => async (...args) => {
1178
2044
  };
1179
2045
  var cli = cac("kiln");
1180
2046
  cli.command("create [name]", "Scaffold a new Kiln app").action(run((name) => runCreate(name)));
1181
- cli.command("dev", "Start the dev server with SSR and HMR").option("--port <port>", "Port to listen on", { default: 3000 }).action(run((o) => startDev(Number(o.port))));
2047
+ cli.command("dev", "Start the dev server with SSR and HMR").option("--port <port>", "Port to listen on", { default: 3e3 }).action(run((o) => startDev(Number(o.port))));
1182
2048
  cli.command("build", "Build client and server bundles").option("--target <target>", "Deploy target: none | vercel", { default: "none" }).action(run((o) => runBuild(o.target)));
1183
- cli.command("start", "Serve the production build").option("--port <port>", "Port to listen on", { default: 3000 }).action(run((o) => runStart(Number(o.port))));
2049
+ cli.command("start", "Serve the production build").option("--port <port>", "Port to listen on", { default: 3e3 }).action(run((o) => runStart(Number(o.port))));
1184
2050
  cli.command("routes", "Print the route table").action(run(() => printRoutes()));
1185
- cli.command("generate [kind] [name]", "Generate a page, API route, or layout").alias("g").option("--mode <mode>", "Page mode: universal | server | client").option("--loader", "Add a loader to a page").option("--methods <methods>", "API methods, comma-separated (GET,POST)").action(run((kind, name, options) => runGenerate(kind, name, options)));
2051
+ cli.command("generate [kind] [name]", "Generate a page, API route, or layout").alias("g").option("--mode <mode>", "Page mode: universal | server | client").option("--loader", "Add a loader to a page").option("--methods <methods>", "API methods, comma-separated (GET,POST)").action(run(
2052
+ (kind, name, options) => runGenerate(kind, name, options)
2053
+ ));
2054
+ cli.command("typecheck", "Run TypeScript over the project").action(run(() => runTypecheck()));
2055
+ cli.command("doctor", "Check the project and its environment").action(run(() => runDoctor()));
2056
+ cli.command("test [...paths]", "Render every page and report errors").action(run((paths2) => runTests(paths2 ?? [])));
1186
2057
  var first = process.argv[2];
1187
- if (first && !first.startsWith("-"))
1188
- banner(VERSION);
2058
+ if (first && !first.startsWith("-")) banner(VERSION);
1189
2059
  cli.help();
1190
2060
  cli.version(VERSION);
1191
2061
  cli.parse();