@kiln-js/cli 0.1.5 → 0.1.6

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 path7 from "node:path";
9
+ import http from "node:http";
9
10
  import { createServer as createViteServer } from "vite";
10
11
  import { kiln } 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,9 +52,8 @@ 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
  }
@@ -74,18 +74,17 @@ function resolveEntries() {
74
74
  };
75
75
  }
76
76
 
77
- // src/env.ts
77
+ // packages/cli/src/env.ts
78
78
  import { loadEnv } from "vite";
79
79
  function loadEnvFiles(mode) {
80
80
  const env = loadEnv(mode, paths.root, "");
81
81
  for (const [key, value] of Object.entries(env)) {
82
- if (process.env[key] === undefined)
83
- process.env[key] = value;
82
+ if (process.env[key] === void 0) process.env[key] = value;
84
83
  }
85
84
  return env;
86
85
  }
87
86
 
88
- // src/log.ts
87
+ // packages/cli/src/log.ts
89
88
  var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
90
89
  var sgr = (open, close) => (s) => useColor ? `\x1B[${open}m${s}\x1B[${close}m` : s;
91
90
  var fg = (r, g, b) => sgr(`38;2;${r};${g};${b}`, "39");
@@ -95,6 +94,7 @@ var colors = {
95
94
  red: sgr("31", "39"),
96
95
  yellow: sgr("33", "39"),
97
96
  cyan: sgr("36", "39"),
97
+ // Kiln palette
98
98
  fire: fg(255, 122, 69),
99
99
  ember: fg(255, 92, 122),
100
100
  mint: fg(94, 234, 212),
@@ -115,8 +115,7 @@ var METHOD_COLORS = {
115
115
  var methodColor = (m) => METHOD_COLORS[m] ?? colors.bold;
116
116
  var statusColor = (s) => s >= 500 ? colors.ember : s >= 400 ? colors.yellow : s >= 300 ? colors.violet : colors.mint;
117
117
  function gradient(text, from, to) {
118
- if (!useColor)
119
- return text;
118
+ if (!useColor) return text;
120
119
  const chars = [...text];
121
120
  const painted = chars.map((ch, i) => {
122
121
  const t = chars.length < 2 ? 0 : i / (chars.length - 1);
@@ -126,15 +125,12 @@ function gradient(text, from, to) {
126
125
  return `${painted}\x1B[39m`;
127
126
  }
128
127
  function formatDuration(ms) {
129
- if (ms < 1000)
130
- return `${Math.round(ms)}ms`;
131
- return `${(ms / 1000).toFixed(2)}s`;
128
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
129
+ return `${(ms / 1e3).toFixed(2)}s`;
132
130
  }
133
131
  function formatBytes(bytes) {
134
- if (bytes < 1024)
135
- return `${bytes} B`;
136
- if (bytes < 1024 ** 2)
137
- return `${(bytes / 1024).toFixed(1)} kB`;
132
+ if (bytes < 1024) return `${bytes} B`;
133
+ if (bytes < 1024 ** 2) return `${(bytes / 1024).toFixed(1)} kB`;
138
134
  return `${(bytes / 1024 ** 2).toFixed(2)} MB`;
139
135
  }
140
136
  var log = {
@@ -143,10 +139,12 @@ var log = {
143
139
  success: (msg) => console.log(` ${colors.mint("\u2714")} ${msg}`),
144
140
  warn: (msg) => console.log(` ${colors.yellow("\u26A0")} ${colors.yellow(msg)}`),
145
141
  error: (msg) => console.error(` ${colors.ember("\u2716")} ${colors.ember(msg)}`),
146
- change: (file) => console.log(` ${colors.violet("\u21BB")} ${colors.dim("changed")} ${file}`),
142
+ change: (file2) => console.log(` ${colors.violet("\u21BB")} ${colors.dim("changed")} ${file2}`),
147
143
  request(method, pathname, status, time) {
148
144
  const verb = methodColor(method)(method.padEnd(6));
149
- console.log(` ${colors.gray("\u203A")} ${verb}${colors.bold(pathname)} ${statusColor(status)(String(status))} ${colors.gray(time)}`);
145
+ console.log(
146
+ ` ${colors.gray("\u203A")} ${verb}${colors.bold(pathname)} ${statusColor(status)(String(status))} ${colors.gray(time)}`
147
+ );
150
148
  }
151
149
  };
152
150
  function spinner(label) {
@@ -190,9 +188,10 @@ function box(lines, paint = colors.fire) {
190
188
  const width = Math.max(...lines.map(visible)) + 4;
191
189
  const top = paint(`\u256D${"\u2500".repeat(width)}\u256E`);
192
190
  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
- `));
191
+ const body = lines.map(
192
+ (l) => `${paint("\u2502")} ${l}${" ".repeat(width - visible(l) - 2)}${paint("\u2502")}`
193
+ );
194
+ console.log([top, ...body, bottom].map((l) => ` ${l}`).join("\n"));
196
195
  }
197
196
  function table(rows, headers) {
198
197
  const all = [headers, ...rows];
@@ -211,152 +210,331 @@ function banner(version) {
211
210
  `);
212
211
  }
213
212
 
214
- // src/errors.ts
215
- import fs2 from "fs";
216
- import path3 from "path";
213
+ // packages/cli/src/errors.ts
214
+ import fs2 from "node:fs";
215
+ import path4 from "node:path";
216
+
217
+ // packages/cli/src/hints.ts
218
+ import path3 from "node:path";
217
219
  var norm = (p) => p.replace(/\\/g, "/");
218
- var rootNorm = norm(paths.root);
220
+ var rel = (file2) => norm(path3.relative(paths.root, file2));
221
+ var BROWSER_GLOBAL = /^(window|document|localStorage|sessionStorage|navigator|matchMedia|IntersectionObserver|ResizeObserver|location|history)$/;
222
+ function diagnose(error, frames) {
223
+ const hints = [];
224
+ const msg = error.message;
225
+ const layout = frames.find((f) => /_layout\.[jt]sx?$/.test(norm(f.file)));
226
+ const browserName = msg.match(/^(\w+) is not defined/)?.[1];
227
+ if (error.name === "ReferenceError" && browserName && BROWSER_GLOBAL.test(browserName)) {
228
+ hints.push({
229
+ title: `"${browserName}" is a browser API, but it ran while the server rendered the page`,
230
+ steps: [
231
+ 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.",
232
+ "Move the code into useEffect, which runs only in the browser.",
233
+ "Or wrap the browser-only part in <ClientOnly fallback={...}> from @kiln-js/core.",
234
+ "If the whole page needs the browser, use the .client suffix for that page."
235
+ ]
236
+ });
237
+ }
238
+ if (/Cannot find module|Failed to resolve import|Could not resolve|Cannot find package/.test(msg)) {
239
+ hints.push({
240
+ title: "An import could not be resolved",
241
+ steps: [
242
+ "Check the path: relative paths start with ./ or ../, and file names are case-sensitive.",
243
+ "For packages, run bun install in the project root.",
244
+ "After adding a dependency, restart kiln dev."
245
+ ]
246
+ });
247
+ }
248
+ if (/must export "createHandler/.test(msg)) {
249
+ hints.push({
250
+ title: "The server entry does not export createHandler",
251
+ steps: [
252
+ "app/server.ts must export: export function createHandler(assets) { ... }",
253
+ "Use createAppHandler from @kiln-js/server inside it."
254
+ ]
255
+ });
256
+ }
257
+ if (/server-only and cannot be imported/.test(msg)) {
258
+ hints.push({
259
+ title: "A .server module is imported by browser code",
260
+ steps: [
261
+ "Move the import into a loader or action, which the build removes from the browser bundle.",
262
+ "Or move the helper that uses it into a .server module."
263
+ ]
264
+ });
265
+ }
266
+ if (/DATABASE_URL is not set/.test(msg)) {
267
+ hints.push({
268
+ title: "A required environment variable is missing",
269
+ steps: [
270
+ "Add DATABASE_URL to .env.local for local development.",
271
+ "On Vercel, add it under Settings \u2192 Environment Variables."
272
+ ]
273
+ });
274
+ }
275
+ if (/Invalid environment/.test(msg)) {
276
+ hints.push({
277
+ title: "Environment validation failed",
278
+ steps: ["Each line under the message names a variable. Add it to .env.local or fix its value."]
279
+ });
280
+ }
281
+ if (error.name === "SyntaxError" && frames.some((f) => norm(f.file).endsWith(".md"))) {
282
+ hints.push({
283
+ title: "A Markdown file reached the JavaScript parser",
284
+ steps: [
285
+ "Add md() from @kiln-js/md to the plugins in vite.config.ts.",
286
+ "Restart kiln dev after changing the config."
287
+ ]
288
+ });
289
+ }
290
+ if (/Hydration failed|did not match|Text content does not match|#418|#423|#425/.test(msg)) {
291
+ hints.push({
292
+ title: "The server and the browser rendered different HTML",
293
+ steps: [
294
+ "Common causes: Date.now(), Math.random(), toLocaleString(), and window checks during render.",
295
+ "Move those values into useEffect, or wrap them in <ClientOnly>."
296
+ ]
297
+ });
298
+ }
299
+ if (/conflict: .* both map to/.test(msg)) {
300
+ hints.push({
301
+ title: "Two files map to the same URL",
302
+ steps: [
303
+ "Rename one of the files, or move it into a (group) folder if it should share a layout without changing the URL."
304
+ ]
305
+ });
306
+ }
307
+ return hints;
308
+ }
309
+
310
+ // packages/cli/src/errors.ts
311
+ var norm2 = (p) => p.replace(/\\/g, "/");
312
+ var rootNorm = norm2(paths.root);
219
313
  var toError = (err) => err instanceof Error ? err : new Error(String(err));
220
- var rel = (file) => norm(path3.relative(paths.root, file));
314
+ var rel2 = (file2) => norm2(path4.relative(paths.root, file2));
221
315
  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}`;
316
+ var editorLink = (f) => `vscode://file/${encodeURI(norm2(f.file))}:${f.line}:${f.column}`;
223
317
  function parseFrames(stack) {
224
318
  const frames = [];
225
- for (const raw of stack.split(`
226
- `)) {
319
+ for (const raw of stack.split("\n")) {
227
320
  const m = raw.trim().match(/^at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/);
228
- if (!m)
229
- continue;
321
+ if (!m) continue;
230
322
  frames.push({
231
323
  fn: m[1] ?? "<anonymous>",
232
- file: m[2].replace(/^file:\/\/\/?/, ""),
324
+ // Dev URLs carry a ?t=timestamp suffix, which is not part of the path.
325
+ file: m[2].replace(/^file:\/\/\/?/, "").split("?")[0],
233
326
  line: Number(m[3]),
234
327
  column: Number(m[4])
235
328
  });
236
329
  }
237
330
  return frames;
238
331
  }
239
- var isUserFile = (file) => {
240
- const n = norm(file);
332
+ function isAppFrame(f) {
333
+ const n = norm2(f.file);
241
334
  return n.startsWith(rootNorm) && !n.includes("/node_modules/");
242
- };
335
+ }
243
336
  function findOrigin(frames) {
244
- return frames.find((f) => isUserFile(f.file) && fs2.existsSync(f.file));
337
+ return frames.find((f) => isAppFrame(f) && fs2.existsSync(f.file));
245
338
  }
246
- function codeLines(f, radius = 2) {
339
+ function codeLines(f, radius = 3) {
247
340
  try {
248
341
  const lines = fs2.readFileSync(f.file, "utf8").split(/\r?\n/);
249
342
  const from = Math.max(1, f.line - radius);
250
343
  const to = Math.min(lines.length, f.line + radius);
251
344
  const out = [];
252
- for (let n = from;n <= to; n++) {
253
- out.push({ n, text: lines[n - 1] ?? "", hot: n === f.line });
254
- }
345
+ for (let n = from; n <= to; n++) out.push({ n, text: lines[n - 1] ?? "", hot: n === f.line });
255
346
  return out;
256
347
  } catch {
257
348
  return [];
258
349
  }
259
350
  }
351
+ function terminalCode(f) {
352
+ const lines = codeLines(f, 3);
353
+ const width = String(lines[lines.length - 1]?.n ?? 0).length;
354
+ const rows = [];
355
+ for (const l of lines) {
356
+ const num = String(l.n).padStart(width);
357
+ if (l.hot) {
358
+ rows.push(`${colors.red("\u25B8")} ${colors.red(num)} ${colors.gray("\u2502")} ${l.text}`);
359
+ rows.push(` ${" ".repeat(width)} ${colors.gray("\u2502")} ${" ".repeat(Math.max(0, f.column - 1))}${colors.red("^")}`);
360
+ } else {
361
+ rows.push(` ${colors.gray(num)} ${colors.gray("\u2502")} ${colors.gray(l.text)}`);
362
+ }
363
+ }
364
+ return rows;
365
+ }
260
366
  function printError(err, context) {
261
367
  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}`));
368
+ const frames = parseFrames(error.stack ?? "");
369
+ const origin = findOrigin(frames);
370
+ const hints = diagnose(error, frames);
371
+ const appFrames = frames.filter(isAppFrame);
372
+ const hidden = frames.length - appFrames.length;
373
+ const c = colors;
374
+ const lines = [""];
375
+ lines.push(` ${c.red("\u2716")} ${c.bold(c.red(error.name))} ${c.bold(error.message)}`);
376
+ lines.push(` ${c.gray(context)}`);
266
377
  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
- }
378
+ lines.push("");
379
+ lines.push(` ${c.gray("at")} ${c.cyan(`${rel2(origin.file)}:${origin.line}:${origin.column}`)}`);
380
+ lines.push("");
381
+ for (const row of terminalCode(origin)) lines.push(` ${row}`);
382
+ }
383
+ for (const hint of hints) {
384
+ lines.push("");
385
+ lines.push(` ${c.yellow("hint")} ${c.bold(hint.title)}`);
386
+ for (const step of hint.steps) lines.push(` ${c.gray("\u203A")} ${step}`);
387
+ }
388
+ if (appFrames.length > 0) {
389
+ lines.push("");
390
+ lines.push(` ${c.gray("stack")}`);
391
+ for (const f of appFrames.slice(0, 6)) {
392
+ lines.push(` ${c.dim(f.fn.padEnd(28))} ${c.gray(`${rel2(f.file)}:${f.line}`)}`);
276
393
  }
277
394
  }
278
- console.error("");
395
+ if (hidden > 0) lines.push(` ${c.gray(`+ ${hidden} internal frames`)}`);
396
+ lines.push("");
397
+ console.error(lines.join("\n"));
398
+ }
399
+ var OVERLAY_CSS = `
400
+ :root {
401
+ --bg: #0e1116; --panel: #161b22; --line: #262d38; --text: #e6edf3; --muted: #8b949e;
402
+ --accent: #f85149; --link: #79c0ff; --warn: #e3b341; --hot: rgba(248, 81, 73, 0.14);
403
+ color-scheme: dark;
404
+ }
405
+ @media (prefers-color-scheme: light) {
406
+ :root {
407
+ --bg: #f6f8fa; --panel: #ffffff; --line: #d0d7de; --text: #1f2328; --muted: #656d76;
408
+ --accent: #cf222e; --link: #0550ae; --warn: #9a6700; --hot: rgba(207, 34, 46, 0.1);
409
+ color-scheme: light;
410
+ }
411
+ }
412
+ * { box-sizing: border-box; }
413
+ body { margin: 0; background: var(--bg); color: var(--text);
414
+ font: 14px/1.55 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }
415
+ .overlay[hidden] { display: none; }
416
+ .bar { position: sticky; top: 0; z-index: 1; display: flex; align-items: center; gap: 16px;
417
+ padding: 10px 24px; background: var(--panel); border-bottom: 1px solid var(--line); flex-wrap: wrap; }
418
+ .brand { font-weight: 700; }
419
+ .route { display: flex; gap: 8px; align-items: center; color: var(--muted);
420
+ font: 13px ui-monospace, SFMono-Regular, Consolas, monospace; }
421
+ .method { color: var(--text); font-weight: 600; }
422
+ .actions { margin-left: auto; display: flex; gap: 8px; }
423
+ button { font: inherit; font-size: 13px; padding: 5px 10px; border-radius: 6px; cursor: pointer;
424
+ border: 1px solid var(--line); background: transparent; color: var(--text); }
425
+ main { max-width: 1040px; margin: 0 auto; padding: 28px 24px 64px; display: grid; gap: 16px; }
426
+ .kind { margin: 0; color: var(--accent); font: 600 12px ui-monospace, monospace;
427
+ text-transform: uppercase; letter-spacing: 0.08em; }
428
+ .hero h1 { margin: 6px 0 10px; font-size: 22px; line-height: 1.35; word-break: break-word; }
429
+ .where { color: var(--link); text-decoration: none; font: 13px ui-monospace, monospace; }
430
+ .card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; }
431
+ .card h2 { margin: 0; font-size: 14px; padding: 12px 16px; border-bottom: 1px solid var(--line); }
432
+ .hint { border-color: color-mix(in srgb, var(--warn) 45%, var(--line)); }
433
+ .hint h2 { color: var(--warn); }
434
+ .hint ul { margin: 0; padding: 12px 16px 14px 36px; }
435
+ .card-head { display: flex; justify-content: space-between; align-items: center; gap: 12px;
436
+ padding: 10px 16px; border-bottom: 1px solid var(--line); color: var(--muted); font-size: 13px; }
437
+ .open { color: var(--link); text-decoration: none; }
438
+ .code { overflow: auto; padding: 8px 0; font: 13px/1.7 ui-monospace, SFMono-Regular, Consolas, monospace; }
439
+ .ln { display: flex; white-space: pre; padding: 0 16px; }
440
+ .num { width: 48px; flex: none; color: var(--muted); user-select: none; }
441
+ .ln.hot { background: var(--hot); }
442
+ .ln.hot .txt { font-weight: 600; }
443
+ .caret-row .txt { color: var(--accent); }
444
+ .frames { margin: 0; padding: 8px 16px 12px 44px; }
445
+ .frames li { padding: 4px 0; }
446
+ .frames a { color: var(--link); text-decoration: none; font: 13px ui-monospace, monospace; word-break: break-all; }
447
+ .fn { color: var(--muted); margin-right: 10px; font: 13px ui-monospace, monospace; }
448
+ .none { color: var(--muted); list-style: none; margin-left: -28px; }
449
+ details.internal { border-top: 1px solid var(--line); }
450
+ details.internal summary { cursor: pointer; color: var(--muted); padding: 10px 16px; }
451
+ details.internal .frames { padding-top: 0; }
452
+ footer { text-align: center; color: var(--muted); font-size: 13px; }
453
+ `;
454
+ var OVERLAY_JS = `
455
+ (function () {
456
+ var raw = document.getElementById("raw").content.textContent;
457
+ var copy = document.getElementById("copy");
458
+ copy.onclick = function () {
459
+ if (!navigator.clipboard) return;
460
+ navigator.clipboard.writeText(raw).then(function () {
461
+ copy.textContent = "Copied";
462
+ setTimeout(function () { copy.textContent = "Copy stack"; }, 1500);
463
+ });
464
+ };
465
+ function hide() { document.querySelector(".overlay").hidden = true; }
466
+ document.getElementById("dismiss").onclick = hide;
467
+ document.addEventListener("keydown", function (e) { if (e.key === "Escape") hide(); });
468
+ })();
469
+ `;
470
+ function frameItem(f) {
471
+ return `<li><span class="fn">${esc(f.fn)}</span><a href="${editorLink(f)}">${esc(rel2(f.file))}:${f.line}:${f.column}</a></li>`;
472
+ }
473
+ function hintCard(h) {
474
+ return `<section class="card hint"><h2>${esc(h.title)}</h2><ul>${h.steps.map((s) => `<li>${esc(s)}</li>`).join("")}</ul></section>`;
475
+ }
476
+ function sourceCard(f) {
477
+ const rows = codeLines(f, 4).map((l) => {
478
+ const row = `<div class="ln${l.hot ? " hot" : ""}"><span class="num">${l.n}</span><span class="txt">${esc(l.text) || " "}</span></div>`;
479
+ if (!l.hot) return row;
480
+ const caret = `<div class="ln caret-row"><span class="num"></span><span class="txt" style="white-space:pre">${" ".repeat(
481
+ Math.max(0, f.column - 1)
482
+ )}<span>^</span></span></div>`;
483
+ return row + caret;
484
+ }).join("");
485
+ return `<section class="card">
486
+ <div class="card-head"><span>Source</span><a class="open" href="${editorLink(f)}">Open in editor \u2192</a></div>
487
+ <div class="code">${rows}</div>
488
+ </section>`;
279
489
  }
280
490
  function renderDevError(err, meta) {
281
491
  const error = toError(err);
282
492
  const frames = parseFrames(error.stack ?? "");
283
493
  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("");
494
+ const hints = diagnose(error, frames);
495
+ const appFrames = frames.filter(isAppFrame);
496
+ const internal = frames.filter((f) => !isAppFrame(f));
497
+ const time = (/* @__PURE__ */ new Date()).toLocaleTimeString();
498
+ const where = origin ? `<a class="where" href="${editorLink(origin)}">${esc(rel2(origin.file))}:${origin.line}:${origin.column}</a>` : "";
499
+ const internalBlock = internal.length ? `<details class="internal"><summary>${internal.length} internal frames</summary><ol class="frames">${internal.map(frameItem).join("")}</ol></details>` : "";
500
+ const appList = appFrames.length ? appFrames.map(frameItem).join("") : `<li class="none">No frames from your code</li>`;
298
501
  return `<!doctype html>
299
502
  <html lang="en">
300
503
  <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>
504
+ <meta charset="utf-8" />
505
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
506
+ <title>${esc(error.name)}: ${esc(error.message)}</title>
507
+ <style>${OVERLAY_CSS}</style>
329
508
  </head>
330
509
  <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>
510
+ <div class="overlay">
511
+ <header class="bar">
512
+ <span class="brand">Kiln</span>
513
+ <span class="route"><span class="method">${esc(meta.method)}</span>${esc(meta.pathname)}</span>
514
+ <span class="route">${esc(time)}</span>
515
+ <div class="actions">
516
+ <button id="copy" type="button">Copy stack</button>
517
+ <button id="dismiss" type="button">Dismiss</button>
518
+ </div>
519
+ </header>
520
+ <main>
521
+ <section class="hero">
522
+ <p class="kind">${esc(error.name)}</p>
335
523
  <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>
524
+ ${where}
525
+ </section>
526
+ ${hints.map(hintCard).join("")}
527
+ ${origin ? sourceCard(origin) : ""}
528
+ <section class="card">
529
+ <div class="card-head"><span>Call stack</span><span>${appFrames.length} in your code</span></div>
530
+ <ol class="frames">${appList}</ol>
531
+ ${internalBlock}
532
+ </section>
533
+ <footer>Save a file to reload. Press Esc to dismiss.</footer>
534
+ </main>
535
+ </div>
536
+ <template id="raw">${esc(error.stack ?? error.message)}</template>
537
+ <script>${OVERLAY_JS}</script>
360
538
  </body>
361
539
  </html>`;
362
540
  }
@@ -364,57 +542,194 @@ function renderProdError(requestId) {
364
542
  return `<!doctype html>
365
543
  <html lang="en">
366
544
  <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>
545
+ <meta charset="utf-8" />
546
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
547
+ <title>Server error</title>
548
+ <style>
549
+ :root { color-scheme: light dark; }
550
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #fafafa; color: #111;
551
+ font: 16px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif; }
552
+ @media (prefers-color-scheme: dark) { body { background: #0e1116; color: #e6edf3; } }
553
+ main { max-width: 420px; padding: 32px; text-align: center; }
554
+ .status { margin: 0; font-size: 56px; font-weight: 700; color: #dc2626; }
555
+ .ref { font: 13px ui-monospace, monospace; opacity: 0.7; }
556
+ a { color: inherit; }
557
+ </style>
377
558
  </head>
378
559
  <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>
560
+ <main>
561
+ <p class="status">500</p>
562
+ <h1 style="font-size: 22px; margin: 8px 0;">Something went wrong</h1>
563
+ <p>The error was logged on the server.</p>
564
+ <p class="ref">Reference ${esc(requestId)}</p>
565
+ <p><a href="/">Back to home</a></p>
566
+ </main>
385
567
  </body>
386
568
  </html>`;
387
569
  }
388
570
 
389
- // src/dev.ts
390
- var toError2 = (err) => err instanceof Error ? err : new Error(String(err));
391
- function getHandlerFactory(mod, file) {
571
+ // packages/cli/src/versions.ts
572
+ import fs3 from "node:fs";
573
+ import path5 from "node:path";
574
+ import { createRequire } from "node:module";
575
+ var PACKAGES = ["core", "server", "client", "vite-plugin", "md", "adapter-vercel"];
576
+ function cliVersion() {
577
+ const file2 = new URL("../package.json", import.meta.url);
578
+ return JSON.parse(fs3.readFileSync(file2, "utf8")).version;
579
+ }
580
+ function findVersionProblems() {
581
+ const expected = cliVersion();
582
+ const req = createRequire(path5.join(paths.root, "package.json"));
583
+ const problems = [];
584
+ for (const short of PACKAGES) {
585
+ const name = `@kiln-js/${short}`;
586
+ let pkgPath;
587
+ try {
588
+ pkgPath = req.resolve(`${name}/package.json`);
589
+ } catch {
590
+ continue;
591
+ }
592
+ const found = JSON.parse(fs3.readFileSync(pkgPath, "utf8")).version;
593
+ if (found !== expected) {
594
+ problems.push({ name, found, location: path5.relative(paths.root, path5.dirname(pkgPath)) || "." });
595
+ }
596
+ }
597
+ return problems;
598
+ }
599
+ function assertVersionsMatch() {
600
+ const problems = findVersionProblems();
601
+ if (problems.length === 0) return;
602
+ const expected = cliVersion();
603
+ const list = problems.map((p) => ` ${p.name} ${p.found} at ${p.location}`).join("\n");
604
+ throw new Error(
605
+ `The Kiln packages in this app do not match the CLI (${expected}):
606
+ ${list}
607
+
608
+ Mixed versions cause "does not provide an export named" errors.
609
+
610
+ Fix:
611
+ 1. Delete the stray installs: Remove-Item -Recurse -Force node_modules (in the folder printed above)
612
+ 2. Run bun install at the monorepo root, so packages link to packages/
613
+ 3. Run bun run dev from inside the app folder (for example examples\\kiln-docs)`
614
+ );
615
+ }
616
+
617
+ // packages/cli/src/preflight.ts
618
+ import fs4 from "node:fs";
619
+ import path6 from "node:path";
620
+ import { pathToFileURL } from "node:url";
621
+ var ENTRY_PACKAGES = ["@kiln-js/core", "@kiln-js/server", "@kiln-js/client", "@kiln-js/md"];
622
+ function resolvePackage(name) {
623
+ let dir = paths.root;
624
+ for (; ; ) {
625
+ const pkgDir = path6.join(dir, "node_modules", ...name.split("/"));
626
+ const pkgJson = path6.join(pkgDir, "package.json");
627
+ if (fs4.existsSync(pkgJson)) {
628
+ const json = JSON.parse(fs4.readFileSync(pkgJson, "utf8"));
629
+ const dot = json.exports?.["."];
630
+ const rel4 = (typeof dot === "string" ? dot : dot?.import) ?? json.module ?? json.main ?? "index.js";
631
+ return { file: path6.join(pkgDir, rel4) };
632
+ }
633
+ const parent = path6.dirname(dir);
634
+ if (parent === dir) return null;
635
+ dir = parent;
636
+ }
637
+ }
638
+ async function preflightImports() {
639
+ const failures = [];
640
+ for (const name of ENTRY_PACKAGES) {
641
+ const resolved = resolvePackage(name);
642
+ if (!resolved) continue;
643
+ try {
644
+ await import(pathToFileURL(resolved.file).href);
645
+ } catch (err) {
646
+ failures.push({
647
+ name,
648
+ file: path6.relative(paths.root, resolved.file).replace(/\\/g, "/"),
649
+ message: err instanceof Error ? err.message : String(err)
650
+ });
651
+ }
652
+ }
653
+ if (failures.length === 0) return;
654
+ const lines = failures.map((f) => ` ${f.name} (${f.file})
655
+ ${f.message}`).join("\n");
656
+ throw new Error(
657
+ `Kiln cannot load its own packages in this folder:
658
+ ${lines}
659
+
660
+ The packages in use do not export what the app needs. This usually means an
661
+ old published copy is installed under this folder or a parent folder.
662
+
663
+ Fix:
664
+ 1. Run Get-Command kiln -All and remove any global install:
665
+ npm uninstall -g @kiln-js/cli
666
+ bun remove -g @kiln-js/cli
667
+ 2. Delete the stray folders reported above (node_modules and .kiln under examples\\).
668
+ 3. From the monorepo root, run bun install and node scripts/build.mjs
669
+ 4. From the app folder, run bun run dev`
670
+ );
671
+ }
672
+
673
+ // packages/cli/src/dev.ts
674
+ function findAppFolders(base) {
675
+ try {
676
+ return fs5.readdirSync(base, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules").map((e) => path7.join(base, e.name)).filter((dir) => fs5.existsSync(path7.join(dir, "app", "pages")));
677
+ } catch {
678
+ return [];
679
+ }
680
+ }
681
+ function assertAppFolder() {
682
+ if (fs5.existsSync(paths.pagesDir)) return;
683
+ const found = findAppFolders(paths.root);
684
+ const hint = found.length > 0 ? `Found app folder(s) below this one. Run one of these instead:
685
+ ` + found.map((d) => ` cd ${path7.relative(process.cwd(), d)} && kiln dev`).join("\n") : "Run kiln dev in the folder that contains package.json and app/pages.";
686
+ throw new Error(`No app/pages folder in ${paths.root}.
687
+ ${hint}`);
688
+ }
689
+ function toError2(err) {
690
+ if (err instanceof Error) return err;
691
+ if (typeof err === "object" && err !== null) {
692
+ const { message, name } = err;
693
+ const error = new Error(String(message ?? "Unknown error"));
694
+ if (typeof name === "string") error.name = name;
695
+ return error;
696
+ }
697
+ return new Error(String(err));
698
+ }
699
+ function fixStack(vite, error) {
700
+ try {
701
+ vite.ssrFixStacktrace(error);
702
+ } catch {
703
+ }
704
+ }
705
+ function getHandlerFactory(mod, file2) {
392
706
  const factory = mod.createHandler;
393
707
  if (typeof factory !== "function") {
394
708
  const exports = Object.keys(mod).join(", ") || "(none)";
395
- throw new Error(`${file} must export "createHandler(assets)". Found exports: ${exports}`);
709
+ throw new Error(`${file2} must export "createHandler(assets)". Found exports: ${exports}`);
396
710
  }
397
711
  return factory;
398
712
  }
399
713
  async function toWebRequest(req, origin) {
400
- const headers = new Headers;
714
+ const headers = new Headers();
401
715
  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);
716
+ if (value === void 0) continue;
717
+ for (const v of Array.isArray(value) ? value : [value]) headers.append(key, v);
406
718
  }
407
719
  const init = { method: req.method, headers };
408
720
  if (req.method !== "GET" && req.method !== "HEAD") {
409
721
  const chunks = [];
410
- for await (const chunk of req)
411
- chunks.push(chunk);
722
+ for await (const chunk of req) chunks.push(chunk);
412
723
  init.body = Buffer.concat(chunks);
413
724
  }
414
725
  return new Request(new URL(req.url ?? "/", origin), init);
415
726
  }
416
727
  async function startDev(port) {
728
+ assertVersionsMatch();
729
+ await preflightImports();
730
+ assertAppFolder();
417
731
  const startedAt = performance.now();
732
+ globalThis.__KILN_DEV__ = true;
418
733
  loadEnvFiles("development");
419
734
  const entries = resolveEntries();
420
735
  const origin = `http://localhost:${port}`;
@@ -433,15 +748,16 @@ async function startDev(port) {
433
748
  const body = isHtml ? await vite.transformIndexHtml(url, await response.text()) : Buffer.from(await response.arrayBuffer());
434
749
  res.statusCode = response.status;
435
750
  response.headers.forEach((value, key) => {
436
- if (key !== "content-length")
437
- res.setHeader(key, value);
751
+ if (key !== "content-length" && key !== "set-cookie") res.setHeader(key, value);
438
752
  });
753
+ const cookies = response.headers.getSetCookie();
754
+ if (cookies.length) res.setHeader("set-cookie", cookies);
439
755
  res.end(body);
440
756
  lastRenderFailed = false;
441
757
  log.request(req.method ?? "GET", pathname, response.status, formatDuration(performance.now() - start));
442
758
  } catch (err) {
443
759
  const error = toError2(err);
444
- vite.ssrFixStacktrace(error);
760
+ fixStack(vite, error);
445
761
  lastRenderFailed = true;
446
762
  log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - start)}`);
447
763
  printError(error, `${req.method} ${pathname}`);
@@ -460,18 +776,22 @@ async function startDev(port) {
460
776
  }
461
777
  const server = http.createServer((req, res) => {
462
778
  vite.middlewares(req, res, () => {
463
- handleSsr(req, res);
779
+ void handleSsr(req, res);
464
780
  });
465
781
  });
466
782
  vite = await createViteServer({
467
783
  root: paths.root,
468
784
  appType: "custom",
469
- plugins: kiln({ pagesDir: paths.pagesDir, apiDir: paths.apiDir }),
785
+ plugins: kiln({
786
+ pagesDir: paths.pagesDir,
787
+ apiDir: paths.apiDir,
788
+ appDir: path7.join(paths.root, "app")
789
+ }),
470
790
  logLevel: "warn",
471
791
  server: { middlewareMode: true, hmr: { server } }
472
792
  });
473
- vite.watcher.on("change", (file) => {
474
- const shown = file.replace(paths.root, "").replace(/\\/g, "/");
793
+ vite.watcher.on("change", (file2) => {
794
+ const shown = file2.replace(paths.root, "").replace(/\\/g, "/");
475
795
  log.change(shown);
476
796
  if (lastRenderFailed) {
477
797
  lastRenderFailed = false;
@@ -479,11 +799,14 @@ async function startDev(port) {
479
799
  }
480
800
  });
481
801
  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);
802
+ box(
803
+ [
804
+ colors.bold("Kiln dev server"),
805
+ `${colors.sky(origin)} ${colors.gray(`ready in ${formatDuration(performance.now() - startedAt)}`)}`,
806
+ colors.dim("press Ctrl+C to stop")
807
+ ],
808
+ colors.fire
809
+ );
487
810
  });
488
811
  process.once("SIGINT", async () => {
489
812
  log.info("Shutting down");
@@ -493,19 +816,18 @@ async function startDev(port) {
493
816
  });
494
817
  }
495
818
 
496
- // src/build.ts
497
- import fs3 from "fs";
498
- import path4 from "path";
819
+ // packages/cli/src/build.ts
820
+ import fs6 from "node:fs";
821
+ import path8 from "node:path";
499
822
  import { build } from "vite";
500
823
  import { adaptVercel } from "@kiln-js/adapter-vercel";
501
824
  import { kiln as kiln2 } from "@kiln-js/vite-plugin";
502
825
  var TARGETS = ["none", "vercel"];
503
826
  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);
827
+ if (!fs6.existsSync(dir)) return 0;
828
+ return fs6.readdirSync(dir, { withFileTypes: true }).reduce((sum, entry) => {
829
+ const full = path8.join(dir, entry.name);
830
+ return sum + (entry.isDirectory() ? dirSize(full) : fs6.statSync(full).size);
509
831
  }, 0);
510
832
  }
511
833
  async function runBuild(target = "none") {
@@ -517,35 +839,44 @@ async function runBuild(target = "none") {
517
839
  const entries = resolveEntries();
518
840
  const plugins = kiln2({ pagesDir: paths.pagesDir, apiDir: paths.apiDir });
519
841
  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({
842
+ await task(
843
+ "client bundle",
844
+ () => build({
544
845
  root: paths.root,
545
- clientOut: paths.clientOut,
546
- serverOut: paths.serverOut,
547
- clientRel: entries.clientRel
548
- }));
846
+ plugins,
847
+ logLevel: "warn",
848
+ build: {
849
+ outDir: paths.clientOut,
850
+ emptyOutDir: true,
851
+ manifest: true,
852
+ rollupOptions: { input: entries.client }
853
+ }
854
+ })
855
+ );
856
+ await task(
857
+ "server bundle",
858
+ () => build({
859
+ root: paths.root,
860
+ plugins,
861
+ logLevel: "warn",
862
+ build: {
863
+ ssr: entries.server,
864
+ outDir: paths.serverOut,
865
+ emptyOutDir: true,
866
+ rollupOptions: { output: { entryFileNames: "server.js" } }
867
+ }
868
+ })
869
+ );
870
+ if (target === "vercel") {
871
+ await task(
872
+ "vercel output",
873
+ () => adaptVercel({
874
+ root: paths.root,
875
+ clientOut: paths.clientOut,
876
+ serverOut: paths.serverOut,
877
+ clientRel: entries.clientRel
878
+ })
879
+ );
549
880
  }
550
881
  const lines = [
551
882
  `${colors.bold("Build complete")} ${colors.gray(formatDuration(performance.now() - total))}`,
@@ -558,30 +889,47 @@ async function runBuild(target = "none") {
558
889
  box(lines, colors.mint);
559
890
  }
560
891
 
561
- // src/start.ts
562
- import path5 from "path";
563
- import { pathToFileURL } from "url";
892
+ // packages/cli/src/start.ts
893
+ import fs8 from "node:fs";
894
+ import path10 from "node:path";
895
+ import { randomUUID } from "node:crypto";
896
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
564
897
 
565
- // src/compress.ts
566
- import { brotliCompressSync, gzipSync, constants } from "zlib";
898
+ // packages/cli/src/compress.ts
899
+ import fs7 from "node:fs";
900
+ import path9 from "node:path";
901
+ import { brotliCompressSync, gzipSync, constants } from "node:zlib";
567
902
  var COMPRESSIBLE = /^(text\/|application\/(javascript|json|xml|xhtml\+xml|wasm)|image\/svg\+xml)/;
568
903
  var MIN_SIZE = 1024;
569
904
  var MAX_CACHE = 64;
570
- var staticCache = new Map;
905
+ var MIME = {
906
+ ".html": "text/html; charset=utf-8",
907
+ ".js": "text/javascript; charset=utf-8",
908
+ ".mjs": "text/javascript; charset=utf-8",
909
+ ".css": "text/css; charset=utf-8",
910
+ ".json": "application/json; charset=utf-8",
911
+ ".map": "application/json; charset=utf-8",
912
+ ".txt": "text/plain; charset=utf-8",
913
+ ".svg": "image/svg+xml",
914
+ ".png": "image/png",
915
+ ".jpg": "image/jpeg",
916
+ ".jpeg": "image/jpeg",
917
+ ".gif": "image/gif",
918
+ ".webp": "image/webp",
919
+ ".ico": "image/x-icon",
920
+ ".woff": "font/woff",
921
+ ".woff2": "font/woff2"
922
+ };
923
+ var staticCache = /* @__PURE__ */ new Map();
571
924
  function cacheSet(key, value) {
572
- if (staticCache.size >= MAX_CACHE) {
573
- staticCache.delete(staticCache.keys().next().value);
574
- }
925
+ if (staticCache.size >= MAX_CACHE) staticCache.delete(staticCache.keys().next().value);
575
926
  staticCache.set(key, value);
576
927
  }
577
928
  function pickEncoding(header) {
578
- if (!header)
579
- return null;
929
+ if (!header) return null;
580
930
  const accepts = header.toLowerCase();
581
- if (/\bbr\b/.test(accepts))
582
- return "br";
583
- if (/\bgzip\b/.test(accepts))
584
- return "gzip";
931
+ if (/\bbr\b/.test(accepts)) return "br";
932
+ if (/\bgzip\b/.test(accepts)) return "gzip";
585
933
  return null;
586
934
  }
587
935
  function encode(body, encoding) {
@@ -591,27 +939,31 @@ function encode(body, encoding) {
591
939
  async function compressResponse(req, res) {
592
940
  const headers = new Headers(res.headers);
593
941
  headers.append("vary", "Accept-Encoding");
594
- const encoding = pickEncoding(req.headers.get("accept-encoding"));
942
+ const accept = req.headers.get("accept-encoding");
595
943
  const type = headers.get("content-type") ?? "";
596
- if (!encoding || !COMPRESSIBLE.test(type) || headers.has("content-encoding") || !res.body) {
944
+ const skip = !res.body || req.method === "HEAD" || headers.has("content-encoding") || !COMPRESSIBLE.test(type) || !pickEncoding(accept);
945
+ if (skip || !res.body) return new Response(res.body, { status: res.status, headers });
946
+ if (!(accept ?? "").toLowerCase().includes("gzip")) {
597
947
  return new Response(res.body, { status: res.status, headers });
598
948
  }
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 });
949
+ headers.delete("content-length");
950
+ headers.set("content-encoding", "gzip");
951
+ const gzipped = res.body.pipeThrough(new CompressionStream("gzip"));
952
+ return new Response(gzipped, { status: res.status, headers });
606
953
  }
607
954
  async function serveStatic(req, filePath) {
608
- const file = Bun.file(filePath);
609
- if (!await file.exists())
955
+ let stat;
956
+ try {
957
+ stat = await fs7.promises.stat(filePath);
958
+ } catch {
610
959
  return null;
611
- const etag = `W/"${file.size}-${file.lastModified}"`;
960
+ }
961
+ if (!stat.isFile()) return null;
962
+ const type = MIME[path9.extname(filePath).toLowerCase()] ?? "application/octet-stream";
963
+ const etag = `W/"${stat.size}-${stat.mtimeMs}"`;
612
964
  const isHashed = /[\\/]assets[\\/]/.test(filePath);
613
965
  const headers = new Headers({
614
- "content-type": file.type,
966
+ "content-type": type,
615
967
  etag,
616
968
  "cache-control": isHashed ? "public, max-age=31536000, immutable" : "no-cache",
617
969
  vary: "Accept-Encoding"
@@ -619,14 +971,16 @@ async function serveStatic(req, filePath) {
619
971
  if (req.headers.get("if-none-match") === etag) {
620
972
  return new Response(null, { status: 304, headers });
621
973
  }
974
+ const raw = new Uint8Array(await fs7.promises.readFile(filePath));
622
975
  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 });
976
+ if (!encoding || !COMPRESSIBLE.test(type) || raw.byteLength < MIN_SIZE) {
977
+ headers.set("content-length", String(raw.byteLength));
978
+ return new Response(raw, { headers });
625
979
  }
626
980
  const key = `${filePath}|${etag}|${encoding}`;
627
981
  let body = staticCache.get(key);
628
982
  if (!body) {
629
- body = encode(new Uint8Array(await file.arrayBuffer()), encoding);
983
+ body = encode(raw, encoding);
630
984
  cacheSet(key, body);
631
985
  }
632
986
  headers.set("content-encoding", encoding);
@@ -634,51 +988,111 @@ async function serveStatic(req, filePath) {
634
988
  return new Response(body, { headers });
635
989
  }
636
990
 
637
- // src/start.ts
991
+ // packages/cli/src/runtime.ts
992
+ import http2 from "node:http";
993
+ var runtime = globalThis.Bun ? "bun" : "node";
994
+ var nodeVersion = process.versions.node;
995
+ function serve(port, fetch) {
996
+ if (runtime === "bun") {
997
+ const bun = globalThis.Bun;
998
+ const server2 = bun.serve({ port, fetch });
999
+ return { port, stop: () => server2.stop() };
1000
+ }
1001
+ const server = http2.createServer(async (req, res) => {
1002
+ try {
1003
+ await writeResponse(res, await fetch(await toRequest(req, port)));
1004
+ } catch (err) {
1005
+ console.error("[kiln] request failed", err);
1006
+ if (!res.headersSent) res.statusCode = 500;
1007
+ res.end("Internal Server Error");
1008
+ }
1009
+ });
1010
+ server.listen(port);
1011
+ return { port, stop: () => server.close() };
1012
+ }
1013
+ async function toRequest(req, port) {
1014
+ const headers = new Headers();
1015
+ for (const [key, value] of Object.entries(req.headers)) {
1016
+ if (value === void 0) continue;
1017
+ for (const v of Array.isArray(value) ? value : [value]) headers.append(key, v);
1018
+ }
1019
+ const method = req.method ?? "GET";
1020
+ const init = { method, headers };
1021
+ if (method !== "GET" && method !== "HEAD") {
1022
+ const chunks = [];
1023
+ for await (const chunk of req) chunks.push(chunk);
1024
+ init.body = Buffer.concat(chunks);
1025
+ }
1026
+ return new Request(new URL(req.url ?? "/", `http://localhost:${port}`), init);
1027
+ }
1028
+ async function writeResponse(res, response) {
1029
+ res.statusCode = response.status;
1030
+ response.headers.forEach((value, key) => {
1031
+ if (key !== "set-cookie") res.setHeader(key, value);
1032
+ });
1033
+ const cookies = response.headers.getSetCookie?.() ?? [];
1034
+ if (cookies.length) res.setHeader("set-cookie", cookies);
1035
+ if (!response.body) {
1036
+ res.end();
1037
+ return;
1038
+ }
1039
+ const reader = response.body.getReader();
1040
+ for (; ; ) {
1041
+ const { done, value } = await reader.read();
1042
+ if (done) break;
1043
+ res.write(value);
1044
+ }
1045
+ res.end();
1046
+ }
1047
+
1048
+ // packages/cli/src/start.ts
1049
+ function safeDecode(p) {
1050
+ try {
1051
+ return decodeURIComponent(p);
1052
+ } catch {
1053
+ return null;
1054
+ }
1055
+ }
638
1056
  async function runStart(port) {
639
1057
  const startedAt = performance.now();
640
1058
  loadEnvFiles("production");
641
1059
  const { clientRel } = resolveEntries();
642
- const manifest = JSON.parse(await Bun.file(path5.join(paths.clientOut, ".vite/manifest.json")).text());
1060
+ const manifest = JSON.parse(fs8.readFileSync(path10.join(paths.clientOut, ".vite", "manifest.json"), "utf8"));
643
1061
  const entry = manifest[clientRel];
644
- if (!entry)
645
- throw new Error(`No manifest entry for ${clientRel}. Run "kiln build" first.`);
1062
+ if (!entry) throw new Error(`No manifest entry for ${clientRel}. Run "kiln build" first.`);
646
1063
  const assets = {
647
- head: (entry.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}">`).join(`
648
- `),
1064
+ head: (entry.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}">`).join("\n"),
649
1065
  entry: `/${entry.file}`
650
1066
  };
651
- const serverEntry = await import(pathToFileURL(path5.join(paths.serverOut, "server.js")).href);
1067
+ const serverEntry = await import(pathToFileURL2(path10.join(paths.serverOut, "server.js")).href);
652
1068
  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 });
1069
+ const server = serve(port, async (req) => {
1070
+ const started = performance.now();
1071
+ const { pathname } = new URL(req.url);
1072
+ const requestId = randomUUID().slice(0, 8);
1073
+ try {
1074
+ if (pathname !== "/") {
1075
+ const decoded = safeDecode(pathname);
1076
+ if (decoded === null) return new Response("Bad Request", { status: 400 });
1077
+ const filePath = path10.join(paths.clientOut, decoded);
1078
+ if (filePath.startsWith(paths.clientOut + path10.sep)) {
1079
+ const asset = await serveStatic(req, filePath);
1080
+ if (asset) return asset;
676
1081
  }
677
- return new Response(renderProdError(requestId), {
678
- status: 500,
679
- headers: { "content-type": "text/html; charset=utf-8" }
680
- });
681
1082
  }
1083
+ const res = await compressResponse(req, await handler(req));
1084
+ log.request(req.method, pathname, res.status, formatDuration(performance.now() - started));
1085
+ return res;
1086
+ } catch (err) {
1087
+ log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - started)} [${requestId}]`);
1088
+ printError(err, `${req.method} ${pathname} [${requestId}]`);
1089
+ if (pathname.startsWith("/api/")) {
1090
+ return Response.json({ error: "Internal Server Error", requestId }, { status: 500 });
1091
+ }
1092
+ return new Response(renderProdError(requestId), {
1093
+ status: 500,
1094
+ headers: { "content-type": "text/html; charset=utf-8" }
1095
+ });
682
1096
  }
683
1097
  });
684
1098
  const shutdown = () => {
@@ -688,15 +1102,18 @@ async function runStart(port) {
688
1102
  };
689
1103
  process.once("SIGINT", shutdown);
690
1104
  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);
1105
+ box(
1106
+ [
1107
+ colors.bold("Kiln production server"),
1108
+ `${colors.sky(`http://localhost:${port}`)} ${colors.gray(`${runtime} \xB7 ready in ${formatDuration(performance.now() - startedAt)}`)}`
1109
+ ],
1110
+ colors.mint
1111
+ );
695
1112
  }
696
1113
 
697
- // src/routes.ts
698
- import fs4 from "fs";
699
- import path6 from "path";
1114
+ // packages/cli/src/routes.ts
1115
+ import fs9 from "node:fs";
1116
+ import path11 from "node:path";
700
1117
  import { scanRoutes, scanApi } from "@kiln-js/core/scan";
701
1118
  var METHOD_RE = /export\s+(?:async\s+)?(?:function|const)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
702
1119
  var MODE_COLORS = {
@@ -704,9 +1121,9 @@ var MODE_COLORS = {
704
1121
  server: colors.sky,
705
1122
  client: colors.violet
706
1123
  };
707
- var rel2 = (file) => path6.relative(paths.root, file).split(path6.sep).join("/");
708
- function methodsOf(file) {
709
- const src = fs4.readFileSync(file, "utf8");
1124
+ var rel3 = (file2) => path11.relative(paths.root, file2).split(path11.sep).join("/");
1125
+ function methodsOf(file2) {
1126
+ const src = fs9.readFileSync(file2, "utf8");
710
1127
  return [...src.matchAll(METHOD_RE)].map((m) => m[1]);
711
1128
  }
712
1129
  function printRoutes() {
@@ -717,7 +1134,7 @@ function printRoutes() {
717
1134
  colors.bold(r.pattern),
718
1135
  colors.gray("page"),
719
1136
  MODE_COLORS[r.mode](r.mode),
720
- colors.dim(rel2(r.file))
1137
+ colors.dim(rel3(r.file))
721
1138
  ]),
722
1139
  ...apis.map((r) => {
723
1140
  const methods = methodsOf(r.file);
@@ -725,7 +1142,7 @@ function printRoutes() {
725
1142
  colors.bold(r.pattern),
726
1143
  colors.fire("api"),
727
1144
  methods.map((m) => methodColor(m)(m)).join(" ") || colors.gray("none"),
728
- colors.dim(rel2(r.file))
1145
+ colors.dim(rel3(r.file))
729
1146
  ];
730
1147
  })
731
1148
  ];
@@ -733,12 +1150,12 @@ function printRoutes() {
733
1150
  table(rows, ["PATTERN", "KIND", "MODE / METHODS", "FILE"]);
734
1151
  }
735
1152
 
736
- // src/create.ts
737
- import fs5 from "fs";
738
- import path7 from "path";
1153
+ // packages/cli/src/create.ts
1154
+ import fs10 from "node:fs";
1155
+ import path12 from "node:path";
739
1156
  import inquirer from "inquirer";
740
1157
 
741
- // src/templates.ts
1158
+ // packages/cli/src/templates.ts
742
1159
  var SCOPE = "@kiln-js";
743
1160
  var CLI_PACKAGE = "kiln";
744
1161
  var KILN_VERSION = "0.1.3";
@@ -748,11 +1165,8 @@ var kilnDep = (linked) => linked ? "*" : `^${KILN_VERSION}`;
748
1165
  var SUFFIX = { universal: "", server: ".server", client: ".client" };
749
1166
  function homePage(name, mode) {
750
1167
  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 (
1168
+ return `${stateful ? 'import { useState } from "react";\n\n' : ""}export default function Home() {
1169
+ ${stateful ? " const [count, setCount] = useState(0);\n" : ""} return (
756
1170
  <section>
757
1171
  <kiln:title>Home \xB7 ${name}</kiln:title>
758
1172
  <h1>Welcome to ${name}</h1>
@@ -781,8 +1195,7 @@ export default function Layout({ children }: { children: ReactNode }) {
781
1195
  <nav>
782
1196
  <Link href="/">Home</Link>{" "}
783
1197
  <Link href="/about">About</Link>{" "}
784
- ${withBlog ? `<Link href="/blog">Blog</Link>{" "}
785
- <Link href="/pricing">Pricing</Link>` : ""}
1198
+ ${withBlog ? '<Link href="/blog">Blog</Link>{" "}\n <Link href="/pricing">Pricing</Link>' : ""}
786
1199
  </nav>
787
1200
  <main>{children}</main>
788
1201
  </>
@@ -886,15 +1299,9 @@ function projectFiles(o) {
886
1299
  vite: VITE_VERSION
887
1300
  }
888
1301
  };
889
- files["package.json"] = JSON.stringify(pkgJson, null, 2) + `
890
- `;
1302
+ files["package.json"] = JSON.stringify(pkgJson, null, 2) + "\n";
891
1303
  files["tsconfig.json"] = TSCONFIG;
892
- files[".gitignore"] = `node_modules
893
- dist
894
- .kiln
895
- .env.local
896
- .vercel
897
- `;
1304
+ files[".gitignore"] = "node_modules\ndist\n.kiln\n.env.local\n.vercel\n";
898
1305
  files["app/index.css"] = CSS;
899
1306
  files["app/pages/_layout.tsx"] = LAYOUT(withBlog);
900
1307
  files[`app/pages/index${SUFFIX[o.defaultMode]}.tsx`] = homePage(o.name, o.defaultMode);
@@ -906,8 +1313,7 @@ dist
906
1313
  files["app/pages/blog/[slug].tsx"] = BLOG_POST;
907
1314
  files["app/pages/(marketing)/pricing.tsx"] = PRICING;
908
1315
  }
909
- if (o.api)
910
- files["app/api/health.ts"] = HEALTH;
1316
+ if (o.api) files["app/api/health.ts"] = HEALTH;
911
1317
  if (o.env) {
912
1318
  files[".env"] = `# Exposed to the browser through import.meta.env
913
1319
  KILN_PUBLIC_SITE_NAME=${o.name}
@@ -929,7 +1335,8 @@ export function createHandler(assets: KilnAssets) {
929
1335
  return files;
930
1336
  }
931
1337
 
932
- // src/create.ts
1338
+ // packages/cli/src/create.ts
1339
+ import { spawn } from "node:child_process";
933
1340
  async function runCreate(nameArg) {
934
1341
  const answers = await inquirer.prompt([
935
1342
  {
@@ -995,8 +1402,8 @@ async function runCreate(nameArg) {
995
1402
  customEntries: extras.includes("entries"),
996
1403
  linked: answers.linked
997
1404
  };
998
- const dir = path7.resolve(process.cwd(), options.name);
999
- if (fs5.existsSync(dir) && fs5.readdirSync(dir).length > 0) {
1405
+ const dir = path12.resolve(process.cwd(), options.name);
1406
+ if (fs10.existsSync(dir) && fs10.readdirSync(dir).length > 0) {
1000
1407
  const { overwrite } = await inquirer.prompt([
1001
1408
  {
1002
1409
  type: "confirm",
@@ -1011,24 +1418,25 @@ async function runCreate(nameArg) {
1011
1418
  }
1012
1419
  }
1013
1420
  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);
1421
+ for (const [rel4, content] of Object.entries(projectFiles(options))) {
1422
+ const target = path12.join(dir, rel4);
1423
+ fs10.mkdirSync(path12.dirname(target), { recursive: true });
1424
+ fs10.writeFileSync(target, content);
1018
1425
  }
1019
1426
  log.success(`Created ${options.name}`);
1020
1427
  if (answers.install) {
1021
1428
  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");
1429
+ await new Promise(async (resolve, reject) => {
1430
+ const proc = spawn("bun", ["install"], { cwd: dir, stdio: "inherit", shell: true });
1431
+ proc.on("exit", (code) => code === 0 ? resolve() : reject(new Error("bun install failed")));
1432
+ });
1025
1433
  }
1026
1434
  log.info(`Next: cd ${options.name} && bun run dev`);
1027
1435
  }
1028
1436
 
1029
- // src/generate.ts
1030
- import fs6 from "fs";
1031
- import path8 from "path";
1437
+ // packages/cli/src/generate.ts
1438
+ import fs11 from "node:fs";
1439
+ import path13 from "node:path";
1032
1440
  import inquirer2 from "inquirer";
1033
1441
  var SUFFIX2 = { universal: "", server: ".server", client: ".client" };
1034
1442
  var ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
@@ -1048,6 +1456,7 @@ function pageTemplate(name, loader) {
1048
1456
  const dataProp = loader ? "data" : "";
1049
1457
  const props = loader ? "{ data, params }" : "{ params }";
1050
1458
  const propType = loader ? "{ data: { title: string; slug: Record<string, string> }; params: Record<string, string> }" : "{ params: Record<string, string> }";
1459
+ void dataProp;
1051
1460
  return `${loaderBlock}export default function ${comp}(${props}: ${propType}) {
1052
1461
  return (
1053
1462
  <section>
@@ -1074,8 +1483,7 @@ function apiTemplate(methods) {
1074
1483
  });
1075
1484
  return `import type { ApiContext } from "@kiln-js/server";
1076
1485
 
1077
- ${handlers.join(`
1078
- `)}`;
1486
+ ${handlers.join("\n")}`;
1079
1487
  }
1080
1488
  var LAYOUT_TEMPLATE = `import type { ReactNode } from "react";
1081
1489
 
@@ -1084,11 +1492,9 @@ export default function Layout({ children }: { children: ReactNode }) {
1084
1492
  }
1085
1493
  `;
1086
1494
  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");
1495
+ if (kind === "page") return path13.join(paths.pagesDir, `${name}${SUFFIX2[mode]}.tsx`);
1496
+ if (kind === "api") return path13.join(paths.apiDir, `${name}.ts`);
1497
+ return path13.join(paths.pagesDir, name, "_layout.tsx");
1092
1498
  }
1093
1499
  async function runGenerate(kindArg, nameArg, opts = {}) {
1094
1500
  resolveEntries();
@@ -1130,7 +1536,7 @@ async function runGenerate(kindArg, nameArg, opts = {}) {
1130
1536
  ])).mode;
1131
1537
  }
1132
1538
  let loader = !!opts.loader;
1133
- if (kind === "page" && opts.loader === undefined && mode !== "client") {
1539
+ if (kind === "page" && opts.loader === void 0 && mode !== "client") {
1134
1540
  loader = (await inquirer2.prompt([
1135
1541
  { type: "confirm", name: "loader", message: "Add a loader?", default: false }
1136
1542
  ])).loader;
@@ -1150,27 +1556,278 @@ async function runGenerate(kindArg, nameArg, opts = {}) {
1150
1556
  ])).methods;
1151
1557
  }
1152
1558
  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");
1559
+ if (invalid.length) throw new Error(`Unsupported method(s): ${invalid.join(", ")}`);
1560
+ if (methods.length === 0) throw new Error("Pick at least one HTTP method");
1157
1561
  }
1158
- const file = targetFor(kind, name, mode);
1159
- if (fs6.existsSync(file)) {
1160
- throw new Error(`${path8.relative(paths.root, file)} already exists`);
1562
+ const file2 = targetFor(kind, name, mode);
1563
+ if (fs11.existsSync(file2)) {
1564
+ throw new Error(`${path13.relative(paths.root, file2)} already exists`);
1161
1565
  }
1162
1566
  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, "/")}`);
1567
+ fs11.mkdirSync(path13.dirname(file2), { recursive: true });
1568
+ fs11.writeFileSync(file2, content);
1569
+ log.success(`Created ${path13.relative(paths.root, file2).replace(/\\/g, "/")}`);
1166
1570
  log.info("Run `kiln routes` to see the new route.");
1167
1571
  }
1168
1572
 
1169
- // src/index.ts
1170
- var VERSION = "0.1.0";
1573
+ // packages/cli/src/typecheck.ts
1574
+ import { spawn as spawn2 } from "node:child_process";
1575
+ import { createRequire as createRequire2 } from "node:module";
1576
+ import path14 from "node:path";
1577
+ var LINE = /^(.+?)\((\d+),(\d+)\): error (TS\d+): (.*)$/;
1578
+ function tscPath() {
1579
+ const req = createRequire2(path14.join(paths.root, "package.json"));
1580
+ return path14.join(path14.dirname(req.resolve("typescript/package.json")), "bin", "tsc");
1581
+ }
1582
+ function runTsc() {
1583
+ return new Promise((resolve) => {
1584
+ const proc = spawn2(process.execPath, [tscPath(), "--noEmit", "-p", "tsconfig.json", "--pretty", "false"], {
1585
+ cwd: paths.root
1586
+ });
1587
+ let output = "";
1588
+ proc.stdout.on("data", (d) => output += d);
1589
+ proc.stderr.on("data", (d) => output += d);
1590
+ proc.on("close", () => resolve(output));
1591
+ });
1592
+ }
1593
+ async function runTypecheck() {
1594
+ resolveEntries();
1595
+ log.info("Typechecking");
1596
+ const started = performance.now();
1597
+ const output = await runTsc();
1598
+ const errors = output.split(/\r?\n/).map((line) => line.match(LINE)).filter((m) => m !== null);
1599
+ for (const [, file2, line, col, code, message] of errors) {
1600
+ const shown = path14.relative(paths.root, path14.resolve(paths.root, file2)).replace(/\\/g, "/");
1601
+ console.log(` ${colors.red("\u2716")} ${colors.cyan(`${shown}:${line}:${col}`)} ${colors.gray(code)}`);
1602
+ console.log(` ${message}`);
1603
+ }
1604
+ const time = formatDuration(performance.now() - started);
1605
+ if (errors.length === 0 && /error/i.test(output) === false) {
1606
+ log.success(`No type errors ${colors.gray(`(${time})`)}`);
1607
+ return 0;
1608
+ }
1609
+ if (errors.length === 0) {
1610
+ console.log(output.trim());
1611
+ return 1;
1612
+ }
1613
+ log.error(`${errors.length} type error${errors.length === 1 ? "" : "s"} ${colors.gray(`(${time})`)}`);
1614
+ return errors.length;
1615
+ }
1616
+
1617
+ // packages/cli/src/doctor.ts
1618
+ import fs12 from "node:fs";
1619
+ import path15 from "node:path";
1620
+ import { scanRoutes as scanRoutes2 } from "@kiln-js/core/scan";
1621
+ var file = (rel4) => path15.join(paths.root, rel4);
1622
+ var exists = (rel4) => fs12.existsSync(file(rel4));
1623
+ var read = (rel4) => exists(rel4) ? fs12.readFileSync(file(rel4), "utf8") : "";
1624
+ function atLeast(version, min) {
1625
+ const a = version.split(".").map(Number);
1626
+ const b = min.split(".").map(Number);
1627
+ for (let i = 0; i < b.length; i++) {
1628
+ if ((a[i] ?? 0) !== b[i]) return (a[i] ?? 0) > b[i];
1629
+ }
1630
+ return true;
1631
+ }
1632
+ function appSourceContains(needle) {
1633
+ const walk = (dir) => {
1634
+ if (!fs12.existsSync(dir)) return false;
1635
+ for (const entry of fs12.readdirSync(dir, { withFileTypes: true })) {
1636
+ if (entry.name === "node_modules") continue;
1637
+ const full = path15.join(dir, entry.name);
1638
+ if (entry.isDirectory()) {
1639
+ if (walk(full)) return true;
1640
+ } else if (/\.(tsx?|jsx?|mdx?)$/.test(entry.name) && fs12.readFileSync(full, "utf8").includes(needle)) {
1641
+ return true;
1642
+ }
1643
+ }
1644
+ return false;
1645
+ };
1646
+ return walk(file("app"));
1647
+ }
1648
+ function checks() {
1649
+ const out = [];
1650
+ if (runtime === "bun") {
1651
+ const version = globalThis.Bun.version;
1652
+ out.push({
1653
+ name: "Runtime",
1654
+ status: atLeast(version, "1.1.0") ? "ok" : "warn",
1655
+ detail: `Bun ${version}${atLeast(version, "1.1.0") ? "" : " (1.1 or later recommended)"}`
1656
+ });
1657
+ } else {
1658
+ const ok = Number(nodeVersion.split(".")[0]) >= 18;
1659
+ out.push({
1660
+ name: "Runtime",
1661
+ status: ok ? "ok" : "fail",
1662
+ detail: `Node ${nodeVersion}${ok ? "" : " (18 or later required)"}`
1663
+ });
1664
+ }
1665
+ out.push({
1666
+ name: "package.json",
1667
+ status: exists("package.json") ? "ok" : "fail",
1668
+ detail: exists("package.json") ? "found" : "missing. Run this inside a Kiln project."
1669
+ });
1670
+ out.push({
1671
+ name: "node_modules",
1672
+ status: exists("node_modules") ? "ok" : "fail",
1673
+ detail: exists("node_modules") ? "installed" : "missing. Run bun install."
1674
+ });
1675
+ out.push({
1676
+ name: "tsconfig.json",
1677
+ status: exists("tsconfig.json") ? "ok" : "warn",
1678
+ detail: exists("tsconfig.json") ? "found" : "missing. kiln typecheck needs it."
1679
+ });
1680
+ try {
1681
+ const routes = scanRoutes2(paths.pagesDir);
1682
+ out.push({
1683
+ name: "Routes",
1684
+ status: routes.length > 0 ? "ok" : "fail",
1685
+ detail: routes.length > 0 ? `${routes.length} page routes, no conflicts` : "no pages in app/pages"
1686
+ });
1687
+ } catch (err) {
1688
+ out.push({ name: "Routes", status: "fail", detail: err instanceof Error ? err.message : String(err) });
1689
+ }
1690
+ const pkg2 = read("package.json");
1691
+ out.push({
1692
+ name: "kiln dependency",
1693
+ status: pkg2.includes('"kiln"') ? "ok" : "warn",
1694
+ detail: pkg2.includes('"kiln"') ? "listed" : "add kiln to devDependencies"
1695
+ });
1696
+ out.push({
1697
+ name: "React copies",
1698
+ status: exists("node_modules/react-dom/node_modules/react") ? "warn" : "ok",
1699
+ detail: exists("node_modules/react-dom/node_modules/react") ? "two copies of React are installed. Hooks can break. Pin one version." : "one copy"
1700
+ });
1701
+ const usesDb = appSourceContains("DATABASE_URL");
1702
+ const envDefines = /^DATABASE_URL=/m.test(read(".env.local") + read(".env"));
1703
+ out.push({
1704
+ name: "DATABASE_URL",
1705
+ status: !usesDb || envDefines ? "ok" : "warn",
1706
+ detail: !usesDb ? "not used" : envDefines ? "set in .env files" : "used in code but not in .env.local"
1707
+ });
1708
+ const usesMd = appSourceContains("@kiln-js/md");
1709
+ const configHasMd = /\bmd\s*\(/.test(read("vite.config.ts") + read("vite.config.js"));
1710
+ out.push({
1711
+ name: "Markdown plugin",
1712
+ status: !usesMd || configHasMd ? "ok" : "warn",
1713
+ detail: !usesMd ? "not used" : configHasMd ? "registered in vite.config" : "imported but md() is not in vite.config"
1714
+ });
1715
+ const versionProblems = findVersionProblems();
1716
+ out.push({
1717
+ name: "Kiln versions",
1718
+ status: versionProblems.length ? "fail" : "ok",
1719
+ detail: versionProblems.length ? versionProblems.map((p) => `${p.name} ${p.found} (CLI ${cliVersion()})`).join(", ") : `all match ${cliVersion()}`
1720
+ });
1721
+ return out;
1722
+ }
1723
+ function runDoctor() {
1724
+ log.info("Checking this project");
1725
+ const results = checks();
1726
+ const icon = {
1727
+ ok: colors.mint("\u2714"),
1728
+ warn: colors.yellow("!"),
1729
+ fail: colors.red("\u2716")
1730
+ };
1731
+ const width = Math.max(...results.map((r) => r.name.length)) + 2;
1732
+ for (const r of results) {
1733
+ console.log(` ${icon[r.status]} ${r.name.padEnd(width)} ${colors.gray(r.detail)}`);
1734
+ }
1735
+ const fails = results.filter((r) => r.status === "fail").length;
1736
+ const warns = results.filter((r) => r.status === "warn").length;
1737
+ console.log("");
1738
+ if (fails) log.error(`${fails} problem${fails === 1 ? "" : "s"} to fix${warns ? `, ${warns} warning${warns === 1 ? "" : "s"}` : ""}`);
1739
+ else if (warns) log.warn(`No blocking problems, ${warns} warning${warns === 1 ? "" : "s"}`);
1740
+ else log.success("Everything looks good");
1741
+ return fails ? 1 : 0;
1742
+ }
1743
+
1744
+ // packages/cli/src/test.ts
1745
+ import { createServer as createViteServer2 } from "vite";
1746
+ import { kiln as kiln3 } from "@kiln-js/vite-plugin";
1747
+ import { scanRoutes as scanRoutes3 } from "@kiln-js/core/scan";
1748
+ function samplePath(pattern) {
1749
+ const parts = pattern.split("/").filter(Boolean).map((seg) => seg.startsWith(":") ? "example" : seg.startsWith("*") ? "a/b" : seg);
1750
+ return "/" + parts.join("/");
1751
+ }
1752
+ async function runTests(filters) {
1753
+ loadEnvFiles("development");
1754
+ const entries = resolveEntries();
1755
+ const origin = "http://localhost";
1756
+ const vite = await createViteServer2({
1757
+ root: paths.root,
1758
+ appType: "custom",
1759
+ plugins: kiln3({ pagesDir: paths.pagesDir, apiDir: paths.apiDir, appDir: "app" }),
1760
+ logLevel: "silent",
1761
+ server: { middlewareMode: true, hmr: false }
1762
+ });
1763
+ const results = [];
1764
+ try {
1765
+ const mod = await vite.ssrLoadModule(entries.server);
1766
+ const handler = mod.createHandler({
1767
+ head: "",
1768
+ entry: `/${entries.clientRel}`
1769
+ });
1770
+ const routes = scanRoutes3(paths.pagesDir).filter((r) => r.mode !== "client");
1771
+ const selected = routes.filter((r) => {
1772
+ const url = samplePath(r.pattern);
1773
+ return filters.length === 0 || filters.some((f) => url.startsWith(f));
1774
+ });
1775
+ log.info(`Rendering ${selected.length} page${selected.length === 1 ? "" : "s"}`);
1776
+ for (const route of selected) {
1777
+ const url = samplePath(route.pattern);
1778
+ const started = performance.now();
1779
+ const ms = () => performance.now() - started;
1780
+ try {
1781
+ const res = await handler(new Request(origin + url));
1782
+ const body = await res.text();
1783
+ const problems = [];
1784
+ const warnings = [];
1785
+ if (res.status >= 500) problems.push(`HTTP ${res.status} from the server`);
1786
+ if (res.status === 404) warnings.push("404 for the sample URL. Add fixture data if this page needs it.");
1787
+ if (body.trim().length === 0) problems.push("empty response body");
1788
+ if (/<title>Kiln App<\/title>/.test(body)) warnings.push("no <kiln:title>, so the default title is used");
1789
+ if (body.includes("Internal Server Error")) problems.push("the error page was rendered");
1790
+ results.push({ url, status: res.status, ms: ms(), problems, warnings });
1791
+ } catch (err) {
1792
+ const error = err instanceof Error ? err : new Error(String(err));
1793
+ vite.ssrFixStacktrace(error);
1794
+ const hints = diagnose(error, parseFrames(error.stack ?? "")).map((h) => h.title);
1795
+ results.push({
1796
+ url,
1797
+ status: "error",
1798
+ ms: ms(),
1799
+ problems: [`${error.name}: ${error.message}`, ...hints.map((h) => `hint: ${h}`)],
1800
+ warnings: []
1801
+ });
1802
+ }
1803
+ }
1804
+ } finally {
1805
+ await vite.close();
1806
+ }
1807
+ printResults(results);
1808
+ const failed = results.filter((r) => r.problems.length > 0).length;
1809
+ return failed;
1810
+ }
1811
+ function printResults(results) {
1812
+ for (const r of results) {
1813
+ const ok = r.problems.length === 0;
1814
+ const status = r.status === "error" ? colors.red("ERR") : r.status >= 500 ? colors.red(String(r.status)) : colors.mint(String(r.status));
1815
+ console.log(` ${ok ? colors.mint("\u2714") : colors.red("\u2716")} ${r.url.padEnd(28)} ${status} ${colors.gray(formatDuration(r.ms))}`);
1816
+ for (const p of r.problems) console.log(` ${colors.red("\u2716")} ${p}`);
1817
+ for (const w of r.warnings) console.log(` ${colors.yellow("!")} ${w}`);
1818
+ }
1819
+ const failed = results.filter((r) => r.problems.length > 0).length;
1820
+ console.log("");
1821
+ if (failed) log.error(`${failed} of ${results.length} page${results.length === 1 ? "" : "s"} failed`);
1822
+ else log.success(`All ${results.length} page${results.length === 1 ? "" : "s"} rendered`);
1823
+ }
1824
+
1825
+ // packages/cli/src/index.ts
1826
+ var VERSION = "0.1.5";
1171
1827
  var run = (fn) => async (...args) => {
1172
1828
  try {
1173
- await fn(...args);
1829
+ const result = await fn(...args);
1830
+ if (typeof result === "number" && result !== 0) process.exitCode = result;
1174
1831
  } catch (err) {
1175
1832
  printError(err, "while running kiln");
1176
1833
  process.exitCode = 1;
@@ -1178,14 +1835,18 @@ var run = (fn) => async (...args) => {
1178
1835
  };
1179
1836
  var cli = cac("kiln");
1180
1837
  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))));
1838
+ 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
1839
  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))));
1840
+ cli.command("start", "Serve the production build").option("--port <port>", "Port to listen on", { default: 3e3 }).action(run((o) => runStart(Number(o.port))));
1184
1841
  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)));
1842
+ 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(
1843
+ (kind, name, options) => runGenerate(kind, name, options)
1844
+ ));
1845
+ cli.command("typecheck", "Run TypeScript over the project").action(run(() => runTypecheck()));
1846
+ cli.command("doctor", "Check the project and its environment").action(run(() => runDoctor()));
1847
+ cli.command("test [...paths]", "Render every page and report errors").action(run((paths2) => runTests(paths2 ?? [])));
1186
1848
  var first = process.argv[2];
1187
- if (first && !first.startsWith("-"))
1188
- banner(VERSION);
1849
+ if (first && !first.startsWith("-")) banner(VERSION);
1189
1850
  cli.help();
1190
1851
  cli.version(VERSION);
1191
1852
  cli.parse();