@kiln-js/cli 0.0.0-stage → 0.1.1-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.
@@ -0,0 +1 @@
1
+ export declare function runBuild(target?: string): Promise<void>;
@@ -0,0 +1,5 @@
1
+ type Encoding = "br" | "gzip";
2
+ export declare function pickEncoding(header: string | null): Encoding | null;
3
+ export declare function compressResponse(req: Request, res: Response): Promise<Response>;
4
+ export declare function serveStatic(req: Request, filePath: string): Promise<Response | null>;
5
+ export {};
@@ -0,0 +1 @@
1
+ export declare function runCreate(nameArg?: string): Promise<void>;
package/dist/dev.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function startDev(port: number): Promise<void>;
@@ -0,0 +1,6 @@
1
+ export interface Entries {
2
+ client: string;
3
+ server: string;
4
+ clientRel: string;
5
+ }
6
+ export declare function resolveEntries(): Entries;
package/dist/env.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function loadEnvFiles(mode: "development" | "production"): Record<string, string>;
@@ -0,0 +1,13 @@
1
+ export interface Frame {
2
+ fn: string;
3
+ file: string;
4
+ line: number;
5
+ column: number;
6
+ }
7
+ export declare function parseFrames(stack: string): Frame[];
8
+ export declare function printError(err: unknown, context: string): void;
9
+ export declare function renderDevError(err: unknown, meta: {
10
+ method: string;
11
+ pathname: string;
12
+ }): string;
13
+ export declare function renderProdError(requestId: string): string;
@@ -0,0 +1,6 @@
1
+ export interface GenerateOptions {
2
+ mode?: string;
3
+ loader?: boolean;
4
+ methods?: string;
5
+ }
6
+ export declare function runGenerate(kindArg?: string, nameArg?: string, opts?: GenerateOptions): Promise<void>;
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,1191 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/index.ts
5
+ import { cac } from "cac";
6
+
7
+ // src/dev.ts
8
+ import http from "http";
9
+ import { createServer as createViteServer } from "vite";
10
+ import { kiln } from "@kiln/vite-plugin";
11
+
12
+ // src/paths.ts
13
+ import path from "path";
14
+ var root = process.cwd();
15
+ var paths = {
16
+ root,
17
+ pagesDir: path.resolve(root, "app/pages"),
18
+ apiDir: path.resolve(root, "app/api"),
19
+ kilnDir: path.resolve(root, ".kiln"),
20
+ clientOut: path.resolve(root, "dist/client"),
21
+ serverOut: path.resolve(root, "dist/server")
22
+ };
23
+
24
+ // src/entries.ts
25
+ import fs from "fs";
26
+ import path2 from "path";
27
+ var EXTENSIONS = ["tsx", "ts", "jsx", "js"];
28
+ var ENV_TYPES = `// Generated by Kiln. Do not edit.
29
+ export {};
30
+
31
+ declare global {
32
+ namespace JSX {
33
+ interface IntrinsicElements {
34
+ "kiln:title": { children?: string | number | (string | number)[] };
35
+ }
36
+ }
37
+ }
38
+ `;
39
+ var DEFAULT_CLIENT = `import { createClient } from "@kiln/client";
40
+
41
+ createClient().then((client) => client.start());
42
+ `;
43
+ var DEFAULT_SERVER = `import { createAppHandler, type KilnAssets } from "@kiln/server";
44
+
45
+ export function createHandler(assets: KilnAssets) {
46
+ return createAppHandler({ assets });
47
+ }
48
+ `;
49
+ function ensureKilnDir() {
50
+ fs.mkdirSync(paths.kilnDir, { recursive: true });
51
+ }
52
+ function findUserEntry(name) {
53
+ for (const ext of EXTENSIONS) {
54
+ const file = path2.join(paths.root, "app", `${name}.${ext}`);
55
+ if (fs.existsSync(file))
56
+ return file;
57
+ }
58
+ return null;
59
+ }
60
+ function writeGenerated(name, source) {
61
+ ensureKilnDir();
62
+ const target = path2.join(paths.kilnDir, name);
63
+ fs.writeFileSync(target, source);
64
+ return target;
65
+ }
66
+ function resolveEntries() {
67
+ writeGenerated("env.d.ts", ENV_TYPES);
68
+ const client = findUserEntry("client") ?? writeGenerated("client.tsx", DEFAULT_CLIENT);
69
+ const server = findUserEntry("server") ?? writeGenerated("server.ts", DEFAULT_SERVER);
70
+ return {
71
+ client,
72
+ server,
73
+ clientRel: path2.relative(paths.root, client).split(path2.sep).join("/")
74
+ };
75
+ }
76
+
77
+ // src/env.ts
78
+ import { loadEnv } from "vite";
79
+ function loadEnvFiles(mode) {
80
+ const env = loadEnv(mode, paths.root, "");
81
+ for (const [key, value] of Object.entries(env)) {
82
+ if (process.env[key] === undefined)
83
+ process.env[key] = value;
84
+ }
85
+ return env;
86
+ }
87
+
88
+ // src/log.ts
89
+ var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
90
+ var sgr = (open, close) => (s) => useColor ? `\x1B[${open}m${s}\x1B[${close}m` : s;
91
+ var fg = (r, g, b) => sgr(`38;2;${r};${g};${b}`, "39");
92
+ var colors = {
93
+ bold: sgr("1", "22"),
94
+ dim: sgr("2", "22"),
95
+ red: sgr("31", "39"),
96
+ yellow: sgr("33", "39"),
97
+ cyan: sgr("36", "39"),
98
+ fire: fg(255, 122, 69),
99
+ ember: fg(255, 92, 122),
100
+ mint: fg(94, 234, 212),
101
+ violet: fg(167, 139, 250),
102
+ sky: fg(125, 211, 252),
103
+ gray: fg(120, 124, 140)
104
+ };
105
+ var pill = (label, [r, g, b]) => sgr(`48;2;${r};${g};${b};1;38;2;20;20;24`, "49;22;39")(` ${label} `);
106
+ var strip = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
107
+ var visible = (s) => [...strip(s)].length;
108
+ var METHOD_COLORS = {
109
+ GET: colors.sky,
110
+ POST: colors.mint,
111
+ PUT: colors.violet,
112
+ PATCH: colors.violet,
113
+ DELETE: colors.ember
114
+ };
115
+ var methodColor = (m) => METHOD_COLORS[m] ?? colors.bold;
116
+ var statusColor = (s) => s >= 500 ? colors.ember : s >= 400 ? colors.yellow : s >= 300 ? colors.violet : colors.mint;
117
+ function gradient(text, from, to) {
118
+ if (!useColor)
119
+ return text;
120
+ const chars = [...text];
121
+ const painted = chars.map((ch, i) => {
122
+ const t = chars.length < 2 ? 0 : i / (chars.length - 1);
123
+ const [r, g, b] = from.map((v, k) => Math.round(v + (to[k] - v) * t));
124
+ return `\x1B[38;2;${r};${g};${b}m${ch}`;
125
+ }).join("");
126
+ return `${painted}\x1B[39m`;
127
+ }
128
+ function formatDuration(ms) {
129
+ if (ms < 1000)
130
+ return `${Math.round(ms)}ms`;
131
+ return `${(ms / 1000).toFixed(2)}s`;
132
+ }
133
+ function formatBytes(bytes) {
134
+ if (bytes < 1024)
135
+ return `${bytes} B`;
136
+ if (bytes < 1024 ** 2)
137
+ return `${(bytes / 1024).toFixed(1)} kB`;
138
+ return `${(bytes / 1024 ** 2).toFixed(2)} MB`;
139
+ }
140
+ var log = {
141
+ info: (msg) => console.log(`${pill("kiln", [255, 122, 69])} ${msg}`),
142
+ step: (msg) => console.log(` ${colors.gray("\u203A")} ${msg}`),
143
+ success: (msg) => console.log(` ${colors.mint("\u2714")} ${msg}`),
144
+ warn: (msg) => console.log(` ${colors.yellow("\u26A0")} ${colors.yellow(msg)}`),
145
+ 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) {
148
+ const verb = methodColor(method)(method.padEnd(6));
149
+ console.log(` ${colors.gray("\u203A")} ${verb}${colors.bold(pathname)} ${statusColor(status)(String(status))} ${colors.gray(time)}`);
150
+ }
151
+ };
152
+ function spinner(label) {
153
+ const start = performance.now();
154
+ if (!useColor) {
155
+ console.log(` \u203A ${label}`);
156
+ return {
157
+ done(ok = true, note = "") {
158
+ console.log(` ${ok ? "\u2714" : "\u2716"} ${label} ${note}`.trimEnd());
159
+ }
160
+ };
161
+ }
162
+ const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
163
+ let i = 0;
164
+ const draw = () => process.stdout.write(`\r\x1B[2K ${colors.fire(frames[i++ % frames.length])} ${label}`);
165
+ draw();
166
+ const timer = setInterval(draw, 80);
167
+ return {
168
+ done(ok = true, note = "") {
169
+ clearInterval(timer);
170
+ const icon = ok ? colors.mint("\u2714") : colors.ember("\u2716");
171
+ 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}` : ""}
174
+ `);
175
+ }
176
+ };
177
+ }
178
+ async function task(label, fn) {
179
+ const s = spinner(label);
180
+ try {
181
+ const result = await fn();
182
+ s.done(true);
183
+ return result;
184
+ } catch (err) {
185
+ s.done(false);
186
+ throw err;
187
+ }
188
+ }
189
+ function box(lines, paint = colors.fire) {
190
+ const width = Math.max(...lines.map(visible)) + 4;
191
+ const top = paint(`\u256D${"\u2500".repeat(width)}\u256E`);
192
+ 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
+ `));
196
+ }
197
+ function table(rows, headers) {
198
+ const all = [headers, ...rows];
199
+ const widths = headers.map((_, i) => Math.max(...all.map((r) => visible(r[i] ?? ""))) + 2);
200
+ const pad = (cell, i) => cell + " ".repeat(widths[i] - visible(cell));
201
+ console.log(" " + headers.map((h, i) => colors.fire(colors.bold(pad(h, i)))).join("").trimEnd());
202
+ console.log(" " + colors.gray("\u2500".repeat(widths.reduce((a, b) => a + b, 0))));
203
+ for (const row of rows) {
204
+ console.log(" " + row.map((c, i) => pad(c, i)).join("").trimEnd());
205
+ }
206
+ }
207
+ function banner(version) {
208
+ const title = gradient("\u25C6 KILN", [255, 122, 69], [167, 139, 250]);
209
+ console.log(`
210
+ ${title} ${colors.gray(`v${version}`)} ${colors.dim("ssr framework")}
211
+ `);
212
+ }
213
+
214
+ // src/errors.ts
215
+ import fs2 from "fs";
216
+ import path3 from "path";
217
+ var norm = (p) => p.replace(/\\/g, "/");
218
+ var rootNorm = norm(paths.root);
219
+ var toError = (err) => err instanceof Error ? err : new Error(String(err));
220
+ var rel = (file) => norm(path3.relative(paths.root, file));
221
+ 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}`;
223
+ function parseFrames(stack) {
224
+ const frames = [];
225
+ for (const raw of stack.split(`
226
+ `)) {
227
+ const m = raw.trim().match(/^at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/);
228
+ if (!m)
229
+ continue;
230
+ frames.push({
231
+ fn: m[1] ?? "<anonymous>",
232
+ file: m[2].replace(/^file:\/\/\/?/, ""),
233
+ line: Number(m[3]),
234
+ column: Number(m[4])
235
+ });
236
+ }
237
+ return frames;
238
+ }
239
+ var isUserFile = (file) => {
240
+ const n = norm(file);
241
+ return n.startsWith(rootNorm) && !n.includes("/node_modules/");
242
+ };
243
+ function findOrigin(frames) {
244
+ return frames.find((f) => isUserFile(f.file) && fs2.existsSync(f.file));
245
+ }
246
+ function codeLines(f, radius = 2) {
247
+ try {
248
+ const lines = fs2.readFileSync(f.file, "utf8").split(/\r?\n/);
249
+ const from = Math.max(1, f.line - radius);
250
+ const to = Math.min(lines.length, f.line + radius);
251
+ const out = [];
252
+ for (let n = from;n <= to; n++) {
253
+ out.push({ n, text: lines[n - 1] ?? "", hot: n === f.line });
254
+ }
255
+ return out;
256
+ } catch {
257
+ return [];
258
+ }
259
+ }
260
+ function printError(err, context) {
261
+ 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}`));
266
+ 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
+ }
276
+ }
277
+ }
278
+ console.error("");
279
+ }
280
+ function renderDevError(err, meta) {
281
+ const error = toError(err);
282
+ const frames = parseFrames(error.stack ?? "");
283
+ 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("");
298
+ return `<!doctype html>
299
+ <html lang="en">
300
+ <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>
329
+ </head>
330
+ <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>
335
+ <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>
360
+ </body>
361
+ </html>`;
362
+ }
363
+ function renderProdError(requestId) {
364
+ return `<!doctype html>
365
+ <html lang="en">
366
+ <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>
377
+ </head>
378
+ <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>
385
+ </body>
386
+ </html>`;
387
+ }
388
+
389
+ // src/dev.ts
390
+ var toError2 = (err) => err instanceof Error ? err : new Error(String(err));
391
+ function getHandlerFactory(mod, file) {
392
+ const factory = mod.createHandler;
393
+ if (typeof factory !== "function") {
394
+ const exports = Object.keys(mod).join(", ") || "(none)";
395
+ throw new Error(`${file} must export "createHandler(assets)". Found exports: ${exports}`);
396
+ }
397
+ return factory;
398
+ }
399
+ async function toWebRequest(req, origin) {
400
+ const headers = new Headers;
401
+ 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);
406
+ }
407
+ const init = { method: req.method, headers };
408
+ if (req.method !== "GET" && req.method !== "HEAD") {
409
+ const chunks = [];
410
+ for await (const chunk of req)
411
+ chunks.push(chunk);
412
+ init.body = Buffer.concat(chunks);
413
+ }
414
+ return new Request(new URL(req.url ?? "/", origin), init);
415
+ }
416
+ async function startDev(port) {
417
+ const startedAt = performance.now();
418
+ loadEnvFiles("development");
419
+ const entries = resolveEntries();
420
+ const origin = `http://localhost:${port}`;
421
+ let vite;
422
+ let lastRenderFailed = false;
423
+ async function handleSsr(req, res) {
424
+ const url = req.url ?? "/";
425
+ const pathname = new URL(url, origin).pathname;
426
+ const start = performance.now();
427
+ 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));
432
+ const isHtml = (response.headers.get("content-type") ?? "").includes("text/html");
433
+ const body = isHtml ? await vite.transformIndexHtml(url, await response.text()) : Buffer.from(await response.arrayBuffer());
434
+ res.statusCode = response.status;
435
+ response.headers.forEach((value, key) => {
436
+ if (key !== "content-length")
437
+ res.setHeader(key, value);
438
+ });
439
+ res.end(body);
440
+ lastRenderFailed = false;
441
+ log.request(req.method ?? "GET", pathname, response.status, formatDuration(performance.now() - start));
442
+ } catch (err) {
443
+ const error = toError2(err);
444
+ vite.ssrFixStacktrace(error);
445
+ lastRenderFailed = true;
446
+ log.error(`${req.method} ${pathname} 500 ${formatDuration(performance.now() - start)}`);
447
+ printError(error, `${req.method} ${pathname}`);
448
+ if (pathname.startsWith("/api/")) {
449
+ res.statusCode = 500;
450
+ res.setHeader("content-type", "application/json");
451
+ res.end(JSON.stringify({ error: error.message }));
452
+ return;
453
+ }
454
+ const page = renderDevError(error, { method: req.method ?? "GET", pathname });
455
+ const html = await vite.transformIndexHtml(url, page).catch(() => page);
456
+ res.statusCode = 500;
457
+ res.setHeader("content-type", "text/html; charset=utf-8");
458
+ res.end(html);
459
+ }
460
+ }
461
+ const server = http.createServer((req, res) => {
462
+ vite.middlewares(req, res, () => {
463
+ handleSsr(req, res);
464
+ });
465
+ });
466
+ vite = await createViteServer({
467
+ root: paths.root,
468
+ appType: "custom",
469
+ plugins: kiln({ pagesDir: paths.pagesDir, apiDir: paths.apiDir }),
470
+ logLevel: "warn",
471
+ server: { middlewareMode: true, hmr: { server } }
472
+ });
473
+ vite.watcher.on("change", (file) => {
474
+ const shown = file.replace(paths.root, "").replace(/\\/g, "/");
475
+ log.change(shown);
476
+ if (lastRenderFailed) {
477
+ lastRenderFailed = false;
478
+ setTimeout(() => vite.ws.send({ type: "full-reload" }), 100);
479
+ }
480
+ });
481
+ 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);
487
+ });
488
+ process.once("SIGINT", async () => {
489
+ log.info("Shutting down");
490
+ await vite.close();
491
+ server.close();
492
+ process.exit(0);
493
+ });
494
+ }
495
+
496
+ // src/build.ts
497
+ import fs3 from "fs";
498
+ import path4 from "path";
499
+ import { build } from "vite";
500
+ import { kiln as kiln2 } from "@kiln/vite-plugin";
501
+ import { adaptVercel } from "@kiln/adapter-vercel";
502
+ var TARGETS = ["none", "vercel"];
503
+ 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);
509
+ }, 0);
510
+ }
511
+ async function runBuild(target = "none") {
512
+ if (!TARGETS.includes(target)) {
513
+ throw new Error(`Unknown target "${target}". Use one of: ${TARGETS.join(", ")}`);
514
+ }
515
+ const total = performance.now();
516
+ loadEnvFiles("production");
517
+ 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({
544
+ root: paths.root,
545
+ clientOut: paths.clientOut,
546
+ serverOut: paths.serverOut,
547
+ clientRel: entries.clientRel
548
+ }));
549
+ }
550
+ const lines = [
551
+ `${colors.bold("Build complete")} ${colors.gray(formatDuration(performance.now() - total))}`,
552
+ `${colors.sky("client")} ${formatBytes(dirSize(paths.clientOut))}`,
553
+ `${colors.violet("server")} ${formatBytes(dirSize(paths.serverOut))}`
554
+ ];
555
+ if (target === "vercel") {
556
+ lines.push(`${colors.fire("vercel")} .vercel/output ${colors.dim("\u2192 vercel deploy --prebuilt")}`);
557
+ }
558
+ box(lines, colors.mint);
559
+ }
560
+
561
+ // src/start.ts
562
+ import path5 from "path";
563
+ import { pathToFileURL } from "url";
564
+
565
+ // src/compress.ts
566
+ import { brotliCompressSync, gzipSync, constants } from "zlib";
567
+ var COMPRESSIBLE = /^(text\/|application\/(javascript|json|xml|xhtml\+xml|wasm)|image\/svg\+xml)/;
568
+ var MIN_SIZE = 1024;
569
+ var MAX_CACHE = 64;
570
+ var staticCache = new Map;
571
+ function cacheSet(key, value) {
572
+ if (staticCache.size >= MAX_CACHE) {
573
+ staticCache.delete(staticCache.keys().next().value);
574
+ }
575
+ staticCache.set(key, value);
576
+ }
577
+ function pickEncoding(header) {
578
+ if (!header)
579
+ return null;
580
+ const accepts = header.toLowerCase();
581
+ if (/\bbr\b/.test(accepts))
582
+ return "br";
583
+ if (/\bgzip\b/.test(accepts))
584
+ return "gzip";
585
+ return null;
586
+ }
587
+ function encode(body, encoding) {
588
+ const out = encoding === "br" ? brotliCompressSync(body, { params: { [constants.BROTLI_PARAM_QUALITY]: 5 } }) : gzipSync(body, { level: 6 });
589
+ return new Uint8Array(out);
590
+ }
591
+ async function compressResponse(req, res) {
592
+ const headers = new Headers(res.headers);
593
+ headers.append("vary", "Accept-Encoding");
594
+ const encoding = pickEncoding(req.headers.get("accept-encoding"));
595
+ const type = headers.get("content-type") ?? "";
596
+ if (!encoding || !COMPRESSIBLE.test(type) || headers.has("content-encoding") || !res.body) {
597
+ return new Response(res.body, { status: res.status, headers });
598
+ }
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 });
606
+ }
607
+ async function serveStatic(req, filePath) {
608
+ const file = Bun.file(filePath);
609
+ if (!await file.exists())
610
+ return null;
611
+ const etag = `W/"${file.size}-${file.lastModified}"`;
612
+ const isHashed = /[\\/]assets[\\/]/.test(filePath);
613
+ const headers = new Headers({
614
+ "content-type": file.type,
615
+ etag,
616
+ "cache-control": isHashed ? "public, max-age=31536000, immutable" : "no-cache",
617
+ vary: "Accept-Encoding"
618
+ });
619
+ if (req.headers.get("if-none-match") === etag) {
620
+ return new Response(null, { status: 304, headers });
621
+ }
622
+ 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 });
625
+ }
626
+ const key = `${filePath}|${etag}|${encoding}`;
627
+ let body = staticCache.get(key);
628
+ if (!body) {
629
+ body = encode(new Uint8Array(await file.arrayBuffer()), encoding);
630
+ cacheSet(key, body);
631
+ }
632
+ headers.set("content-encoding", encoding);
633
+ headers.set("content-length", String(body.byteLength));
634
+ return new Response(body, { headers });
635
+ }
636
+
637
+ // src/start.ts
638
+ async function runStart(port) {
639
+ const startedAt = performance.now();
640
+ loadEnvFiles("production");
641
+ const { clientRel } = resolveEntries();
642
+ const manifest = JSON.parse(await Bun.file(path5.join(paths.clientOut, ".vite/manifest.json")).text());
643
+ const entry = manifest[clientRel];
644
+ if (!entry)
645
+ throw new Error(`No manifest entry for ${clientRel}. Run "kiln build" first.`);
646
+ const assets = {
647
+ head: (entry.css ?? []).map((href) => `<link rel="stylesheet" href="/${href}">`).join(`
648
+ `),
649
+ entry: `/${entry.file}`
650
+ };
651
+ const serverEntry = await import(pathToFileURL(path5.join(paths.serverOut, "server.js")).href);
652
+ 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 });
676
+ }
677
+ return new Response(renderProdError(requestId), {
678
+ status: 500,
679
+ headers: { "content-type": "text/html; charset=utf-8" }
680
+ });
681
+ }
682
+ }
683
+ });
684
+ const shutdown = () => {
685
+ log.info("Shutting down");
686
+ server.stop();
687
+ process.exit(0);
688
+ };
689
+ process.once("SIGINT", shutdown);
690
+ 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);
695
+ }
696
+
697
+ // src/routes.ts
698
+ import fs4 from "fs";
699
+ import path6 from "path";
700
+ import { scanRoutes, scanApi } from "@kiln/core/scan";
701
+ var METHOD_RE = /export\s+(?:async\s+)?(?:function|const)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;
702
+ var MODE_COLORS = {
703
+ universal: colors.mint,
704
+ server: colors.sky,
705
+ client: colors.violet
706
+ };
707
+ var rel2 = (file) => path6.relative(paths.root, file).split(path6.sep).join("/");
708
+ function methodsOf(file) {
709
+ const src = fs4.readFileSync(file, "utf8");
710
+ return [...src.matchAll(METHOD_RE)].map((m) => m[1]);
711
+ }
712
+ function printRoutes() {
713
+ const pages = scanRoutes(paths.pagesDir);
714
+ const apis = scanApi(paths.apiDir);
715
+ const rows = [
716
+ ...pages.map((r) => [
717
+ colors.bold(r.pattern),
718
+ colors.gray("page"),
719
+ MODE_COLORS[r.mode](r.mode),
720
+ colors.dim(rel2(r.file))
721
+ ]),
722
+ ...apis.map((r) => {
723
+ const methods = methodsOf(r.file);
724
+ return [
725
+ colors.bold(r.pattern),
726
+ colors.fire("api"),
727
+ methods.map((m) => methodColor(m)(m)).join(" ") || colors.gray("none"),
728
+ colors.dim(rel2(r.file))
729
+ ];
730
+ })
731
+ ];
732
+ log.info(`${colors.bold(String(pages.length))} pages, ${colors.bold(String(apis.length))} api routes`);
733
+ table(rows, ["PATTERN", "KIND", "MODE / METHODS", "FILE"]);
734
+ }
735
+
736
+ // src/create.ts
737
+ import fs5 from "fs";
738
+ import path7 from "path";
739
+ import inquirer from "inquirer";
740
+
741
+ // src/templates.ts
742
+ var SCOPE = "@klin-js";
743
+ var CLI_PACKAGE = "kiln";
744
+ var KILN_VERSION = "0.1.0";
745
+ var VITE_VERSION = "5.4.21";
746
+ var pkg = (name) => `${SCOPE}/${name}`;
747
+ var kilnDep = (linked) => linked ? "*" : `^${KILN_VERSION}`;
748
+ var SUFFIX = { universal: "", server: ".server", client: ".client" };
749
+ function homePage(name, mode) {
750
+ 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 (
756
+ <section>
757
+ <kiln:title>Home \xB7 ${name}</kiln:title>
758
+ <h1>Welcome to ${name}</h1>
759
+ ${stateful ? "<button onClick={() => setCount((c) => c + 1)}>Clicked {count} times</button>" : "<p>Rendered on the server.</p>"}
760
+ </section>
761
+ );
762
+ }
763
+ `;
764
+ }
765
+ var ABOUT = (name) => `export default function About() {
766
+ return (
767
+ <section>
768
+ <kiln:title>About \xB7 ${name}</kiln:title>
769
+ <h1>About</h1>
770
+ <p>Rendered on the server. No JavaScript is sent for this page.</p>
771
+ </section>
772
+ );
773
+ }
774
+ `;
775
+ var LAYOUT = (withBlog) => `import type { ReactNode } from "react";
776
+ import { Link } from "${pkg("client")}";
777
+
778
+ export default function Layout({ children }: { children: ReactNode }) {
779
+ return (
780
+ <>
781
+ <nav>
782
+ <Link href="/">Home</Link>{" "}
783
+ <Link href="/about">About</Link>{" "}
784
+ ${withBlog ? `<Link href="/blog">Blog</Link>{" "}
785
+ <Link href="/pricing">Pricing</Link>` : ""}
786
+ </nav>
787
+ <main>{children}</main>
788
+ </>
789
+ );
790
+ }
791
+ `;
792
+ var BLOG_INDEX = `import { Link } from "${pkg("client")}";
793
+
794
+ export default function BlogIndex() {
795
+ return (
796
+ <section>
797
+ <kiln:title>Blog</kiln:title>
798
+ <h1>Blog</h1>
799
+ <ul>
800
+ <li><Link href="/blog/hello">Hello world</Link></li>
801
+ <li><Link href="/blog/kiln">Why Kiln</Link></li>
802
+ </ul>
803
+ </section>
804
+ );
805
+ }
806
+ `;
807
+ var BLOG_POST = `type Post = { title: string; body: string };
808
+
809
+ export async function loader({ params }: { params: Record<string, string> }): Promise<Post> {
810
+ return { title: "Post: " + params.slug, body: "Loaded on the server." };
811
+ }
812
+
813
+ export default function BlogPost({ data }: { data: Post }) {
814
+ return (
815
+ <article>
816
+ <kiln:title>{data.title}</kiln:title>
817
+ <h1>{data.title}</h1>
818
+ <p>{data.body}</p>
819
+ </article>
820
+ );
821
+ }
822
+ `;
823
+ var PRICING = `export default function Pricing() {
824
+ return (
825
+ <section>
826
+ <kiln:title>Pricing</kiln:title>
827
+ <h1>Pricing</h1>
828
+ <p>This page lives in the (marketing) group, so its URL is /pricing.</p>
829
+ </section>
830
+ );
831
+ }
832
+ `;
833
+ var HEALTH = `import type { ApiContext } from "${pkg("server")}";
834
+
835
+ export function GET(_ctx: ApiContext) {
836
+ return Response.json({ ok: true, time: new Date().toISOString() });
837
+ }
838
+ `;
839
+ var CSS = `body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
840
+ nav a { margin-right: 1rem; }
841
+ `;
842
+ var TSCONFIG = `{
843
+ "compilerOptions": {
844
+ "target": "ES2022",
845
+ "module": "ESNext",
846
+ "moduleResolution": "Bundler",
847
+ "jsx": "react-jsx",
848
+ "strict": true,
849
+ "skipLibCheck": true,
850
+ "noEmit": true,
851
+ "verbatimModuleSyntax": true,
852
+ "isolatedModules": true,
853
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
854
+ "types": ["vite/client", "bun"]
855
+ },
856
+ "include": ["app", ".kiln"]
857
+ }
858
+ `;
859
+ function projectFiles(o) {
860
+ const files = {};
861
+ const withBlog = o.template === "blog";
862
+ const pkgJson = {
863
+ name: o.name,
864
+ private: true,
865
+ type: "module",
866
+ scripts: {
867
+ dev: `${CLI_PACKAGE} dev`,
868
+ build: `${CLI_PACKAGE} build`,
869
+ start: `${CLI_PACKAGE} start`,
870
+ routes: `${CLI_PACKAGE} routes`,
871
+ generate: `${CLI_PACKAGE} generate`
872
+ },
873
+ dependencies: {
874
+ [pkg("client")]: kilnDep(o.linked),
875
+ [pkg("core")]: kilnDep(o.linked),
876
+ [pkg("server")]: kilnDep(o.linked),
877
+ react: "^18.3.1",
878
+ "react-dom": "^18.3.1"
879
+ },
880
+ devDependencies: {
881
+ "@types/bun": "latest",
882
+ "@types/react": "^18.3.0",
883
+ "@types/react-dom": "^18.3.0",
884
+ [CLI_PACKAGE]: kilnDep(o.linked),
885
+ typescript: "^5.6.0",
886
+ vite: VITE_VERSION
887
+ }
888
+ };
889
+ files["package.json"] = JSON.stringify(pkgJson, null, 2) + `
890
+ `;
891
+ 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;
899
+ files["app/pages/_layout.tsx"] = LAYOUT(withBlog);
900
+ files[`app/pages/index${SUFFIX[o.defaultMode]}.tsx`] = homePage(o.name, o.defaultMode);
901
+ if (o.template !== "minimal") {
902
+ files["app/pages/about.server.tsx"] = ABOUT(o.name);
903
+ }
904
+ if (withBlog) {
905
+ files["app/pages/blog/index.tsx"] = BLOG_INDEX;
906
+ files["app/pages/blog/[slug].tsx"] = BLOG_POST;
907
+ files["app/pages/(marketing)/pricing.tsx"] = PRICING;
908
+ }
909
+ if (o.api)
910
+ files["app/api/health.ts"] = HEALTH;
911
+ if (o.env) {
912
+ files[".env"] = `# Exposed to the browser through import.meta.env
913
+ KILN_PUBLIC_SITE_NAME=${o.name}
914
+ `;
915
+ }
916
+ if (o.customEntries) {
917
+ files["app/client.tsx"] = `import { createClient } from "${pkg("client")}";
918
+ import "./index.css";
919
+
920
+ createClient().then((client) => client.start());
921
+ `;
922
+ files["app/server.ts"] = `import { createAppHandler, type KilnAssets } from "${pkg("server")}";
923
+
924
+ export function createHandler(assets: KilnAssets) {
925
+ return createAppHandler({ assets });
926
+ }
927
+ `;
928
+ }
929
+ return files;
930
+ }
931
+
932
+ // src/create.ts
933
+ async function runCreate(nameArg) {
934
+ const answers = await inquirer.prompt([
935
+ {
936
+ type: "input",
937
+ name: "name",
938
+ message: "Project name:",
939
+ default: nameArg ?? "my-kiln-app",
940
+ validate: (v) => /^[a-z0-9][a-z0-9-_]*$/i.test(v) || "Use letters, numbers, - or _"
941
+ },
942
+ {
943
+ type: "list",
944
+ name: "template",
945
+ message: "Template:",
946
+ choices: [
947
+ { name: "Minimal (one page)", value: "minimal" },
948
+ { name: "Starter (about page, layout)", value: "starter" },
949
+ { name: "Blog (groups, loader, pricing)", value: "blog" }
950
+ ],
951
+ default: "starter"
952
+ },
953
+ {
954
+ type: "list",
955
+ name: "defaultMode",
956
+ message: "Rendering mode for the home page:",
957
+ choices: ["universal", "server", "client"],
958
+ default: "universal"
959
+ },
960
+ {
961
+ type: "confirm",
962
+ name: "api",
963
+ message: "Include an example API route (app/api/health.ts)?",
964
+ default: true
965
+ },
966
+ {
967
+ type: "checkbox",
968
+ name: "extras",
969
+ message: "Extras:",
970
+ choices: [
971
+ { name: "Environment file (.env)", value: "env", checked: true },
972
+ { name: "Custom client and server entries", value: "entries" }
973
+ ]
974
+ },
975
+ {
976
+ type: "confirm",
977
+ name: "linked",
978
+ message: "Inside the Kiln monorepo (examples/)? Links workspace packages instead of npm.",
979
+ default: true
980
+ },
981
+ {
982
+ type: "confirm",
983
+ name: "install",
984
+ message: "Install dependencies now?",
985
+ default: true
986
+ }
987
+ ]);
988
+ const extras = answers.extras ?? [];
989
+ const options = {
990
+ name: answers.name,
991
+ template: answers.template,
992
+ defaultMode: answers.defaultMode,
993
+ api: answers.api,
994
+ env: extras.includes("env"),
995
+ customEntries: extras.includes("entries"),
996
+ linked: answers.linked
997
+ };
998
+ const dir = path7.resolve(process.cwd(), options.name);
999
+ if (fs5.existsSync(dir) && fs5.readdirSync(dir).length > 0) {
1000
+ const { overwrite } = await inquirer.prompt([
1001
+ {
1002
+ type: "confirm",
1003
+ name: "overwrite",
1004
+ message: `${dir} is not empty. Write files anyway?`,
1005
+ default: false
1006
+ }
1007
+ ]);
1008
+ if (!overwrite) {
1009
+ log.info("Cancelled");
1010
+ return;
1011
+ }
1012
+ }
1013
+ 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);
1018
+ }
1019
+ log.success(`Created ${options.name}`);
1020
+ if (answers.install) {
1021
+ 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");
1025
+ }
1026
+ log.info(`Next: cd ${options.name} && bun run dev`);
1027
+ }
1028
+
1029
+ // src/generate.ts
1030
+ import fs6 from "fs";
1031
+ import path8 from "path";
1032
+ import inquirer2 from "inquirer";
1033
+ var SUFFIX2 = { universal: "", server: ".server", client: ".client" };
1034
+ var ALL_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
1035
+ var toComponent = (name) => {
1036
+ const last = name.split("/").filter(Boolean).pop() ?? "Page";
1037
+ const cleaned = last.replace(/[^a-zA-Z0-9]+(.)?/g, (_, c) => c ? c.toUpperCase() : "");
1038
+ return cleaned.charAt(0).toUpperCase() + cleaned.slice(1) || "Page";
1039
+ };
1040
+ var normalizeName = (raw) => raw.trim().replace(/^\/+|\/+$/g, "").replace(/\.(tsx|ts)$/, "");
1041
+ function pageTemplate(name, loader) {
1042
+ const comp = toComponent(name);
1043
+ const loaderBlock = loader ? `export async function loader({ params }: { params: Record<string, string> }) {
1044
+ return { title: "${comp}", slug: params };
1045
+ }
1046
+
1047
+ ` : "";
1048
+ const dataProp = loader ? "data" : "";
1049
+ const props = loader ? "{ data, params }" : "{ params }";
1050
+ const propType = loader ? "{ data: { title: string; slug: Record<string, string> }; params: Record<string, string> }" : "{ params: Record<string, string> }";
1051
+ return `${loaderBlock}export default function ${comp}(${props}: ${propType}) {
1052
+ return (
1053
+ <section>
1054
+ <kiln:title>${comp}</kiln:title>
1055
+ <h1>${comp}</h1>
1056
+ </section>
1057
+ );
1058
+ }
1059
+ `;
1060
+ }
1061
+ function apiTemplate(methods) {
1062
+ const handlers = methods.map((m) => {
1063
+ if (m === "GET" || m === "DELETE") {
1064
+ return `export async function ${m}({ params }: ApiContext) {
1065
+ return Response.json({ method: "${m}", params });
1066
+ }
1067
+ `;
1068
+ }
1069
+ return `export async function ${m}({ params, request }: ApiContext) {
1070
+ const body = await request.json();
1071
+ return Response.json({ method: "${m}", params, body });
1072
+ }
1073
+ `;
1074
+ });
1075
+ return `import type { ApiContext } from "@kiln/server";
1076
+
1077
+ ${handlers.join(`
1078
+ `)}`;
1079
+ }
1080
+ var LAYOUT_TEMPLATE = `import type { ReactNode } from "react";
1081
+
1082
+ export default function Layout({ children }: { children: ReactNode }) {
1083
+ return <section>{children}</section>;
1084
+ }
1085
+ `;
1086
+ 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");
1092
+ }
1093
+ async function runGenerate(kindArg, nameArg, opts = {}) {
1094
+ resolveEntries();
1095
+ const { kind } = await inquirer2.prompt([
1096
+ {
1097
+ type: "list",
1098
+ name: "kind",
1099
+ message: "What do you want to generate?",
1100
+ choices: [
1101
+ { name: "Page", value: "page" },
1102
+ { name: "API route", value: "api" },
1103
+ { name: "Layout", value: "layout" }
1104
+ ],
1105
+ default: kindArg,
1106
+ when: () => !["page", "api", "layout"].includes(kindArg ?? "")
1107
+ }
1108
+ ]).then((a) => ({ kind: kindArg ?? a.kind }));
1109
+ const { name: rawName } = await inquirer2.prompt([
1110
+ {
1111
+ type: "input",
1112
+ name: "name",
1113
+ message: "Route path (e.g. blog/[slug], (marketing)/pricing):",
1114
+ default: nameArg,
1115
+ when: () => !nameArg,
1116
+ validate: (v) => /^[\w\-\[\]().\/]+$/.test(normalizeName(v)) || "Use letters, -, _, [], (), or /"
1117
+ }
1118
+ ]).then((a) => ({ name: nameArg ?? a.name }));
1119
+ const name = normalizeName(rawName);
1120
+ let mode = opts.mode ?? "universal";
1121
+ if (kind === "page" && !opts.mode) {
1122
+ mode = (await inquirer2.prompt([
1123
+ {
1124
+ type: "list",
1125
+ name: "mode",
1126
+ message: "Rendering mode:",
1127
+ choices: ["universal", "server", "client"],
1128
+ default: "universal"
1129
+ }
1130
+ ])).mode;
1131
+ }
1132
+ let loader = !!opts.loader;
1133
+ if (kind === "page" && opts.loader === undefined && mode !== "client") {
1134
+ loader = (await inquirer2.prompt([
1135
+ { type: "confirm", name: "loader", message: "Add a loader?", default: false }
1136
+ ])).loader;
1137
+ }
1138
+ let methods = [];
1139
+ if (kind === "api") {
1140
+ if (opts.methods) {
1141
+ methods = opts.methods.split(",").map((m) => m.trim().toUpperCase());
1142
+ } else {
1143
+ methods = (await inquirer2.prompt([
1144
+ {
1145
+ type: "checkbox",
1146
+ name: "methods",
1147
+ message: "HTTP methods:",
1148
+ choices: ALL_METHODS.map((m) => ({ name: m, value: m, checked: m === "GET" }))
1149
+ }
1150
+ ])).methods;
1151
+ }
1152
+ 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");
1157
+ }
1158
+ const file = targetFor(kind, name, mode);
1159
+ if (fs6.existsSync(file)) {
1160
+ throw new Error(`${path8.relative(paths.root, file)} already exists`);
1161
+ }
1162
+ 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, "/")}`);
1166
+ log.info("Run `kiln routes` to see the new route.");
1167
+ }
1168
+
1169
+ // src/index.ts
1170
+ var VERSION = "0.1.0";
1171
+ var run = (fn) => async (...args) => {
1172
+ try {
1173
+ await fn(...args);
1174
+ } catch (err) {
1175
+ printError(err, "while running kiln");
1176
+ process.exitCode = 1;
1177
+ }
1178
+ };
1179
+ var cli = cac("kiln");
1180
+ 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))));
1182
+ 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))));
1184
+ 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)));
1186
+ var first = process.argv[2];
1187
+ if (first && !first.startsWith("-"))
1188
+ banner(VERSION);
1189
+ cli.help();
1190
+ cli.version(VERSION);
1191
+ cli.parse();
package/dist/log.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ type Paint = (s: string) => string;
2
+ type RGB = [number, number, number];
3
+ export declare const colors: {
4
+ bold: Paint;
5
+ dim: Paint;
6
+ red: Paint;
7
+ yellow: Paint;
8
+ cyan: Paint;
9
+ fire: Paint;
10
+ ember: Paint;
11
+ mint: Paint;
12
+ violet: Paint;
13
+ sky: Paint;
14
+ gray: Paint;
15
+ };
16
+ export declare const visible: (s: string) => number;
17
+ export declare const methodColor: (m: string) => Paint;
18
+ export declare const statusColor: (s: number) => Paint;
19
+ export declare function gradient(text: string, from: RGB, to: RGB): string;
20
+ export declare function formatDuration(ms: number): string;
21
+ export declare function formatBytes(bytes: number): string;
22
+ export declare const log: {
23
+ info: (msg: string) => void;
24
+ step: (msg: string) => void;
25
+ success: (msg: string) => void;
26
+ warn: (msg: string) => void;
27
+ error: (msg: string) => void;
28
+ change: (file: string) => void;
29
+ request(method: string, pathname: string, status: number, time: string): void;
30
+ };
31
+ export declare function spinner(label: string): {
32
+ done(ok?: boolean, note?: string): void;
33
+ };
34
+ export declare function task<T>(label: string, fn: () => Promise<T>): Promise<T>;
35
+ export declare const timed: typeof task;
36
+ export declare function box(lines: string[], paint?: Paint): void;
37
+ export declare function table(rows: string[][], headers: string[]): void;
38
+ export declare function banner(version: string): void;
39
+ export {};
@@ -0,0 +1,8 @@
1
+ export declare const paths: {
2
+ root: string;
3
+ pagesDir: string;
4
+ apiDir: string;
5
+ kilnDir: string;
6
+ clientOut: string;
7
+ serverOut: string;
8
+ };
@@ -0,0 +1 @@
1
+ export declare function printRoutes(): void;
@@ -0,0 +1 @@
1
+ export declare function runStart(port: number): Promise<void>;
@@ -0,0 +1,11 @@
1
+ export type RenderMode = "universal" | "server" | "client";
2
+ export interface ProjectOptions {
3
+ name: string;
4
+ template: "minimal" | "starter" | "blog";
5
+ defaultMode: RenderMode;
6
+ api: boolean;
7
+ env: boolean;
8
+ customEntries: boolean;
9
+ linked: boolean;
10
+ }
11
+ export declare function projectFiles(o: ProjectOptions): Record<string, string>;
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
- {
2
- "name": "@kiln-js/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "@kiln-js/cli",
3
+ "version": "0.1.1-hotfix",
4
+ "type": "module",
5
+ "bin": {
6
+ "kiln": "./dist/index.js"
7
+ },
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "bun build ./src/index.ts --outdir ./dist --target bun --packages external --banner \u0027#!/usr/bin/env bun\u0027 \u0026\u0026 tsc -p tsconfig.json --emitDeclarationOnly",
13
+ "typecheck": "tsc -p tsconfig.json --noEmit"
14
+ },
15
+ "dependencies": {
16
+ "@kiln-js/adapter-vercel": "*",
17
+ "@kiln-js/core": "*",
18
+ "@kiln-js/server": "*",
19
+ "@kiln-js/vite-plugin": "*",
20
+ "cac": "^6.7.14",
21
+ "inquirer": "^9.3.7",
22
+ "vite": "5.4.21"
23
+ },
24
+ "devDependencies": {
25
+ "@types/inquirer": "^9.0.7",
26
+ "@types/node": "^22.0.0"
27
+ }
6
28
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.