@moku-labs/web 0.1.0-alpha.1

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,809 @@
1
+ #!/usr/bin/env bun
2
+ import { existsSync, readFileSync, statSync, watch } from "node:fs";
3
+ import { extname, normalize, resolve, sep } from "node:path";
4
+ import { parseArgs } from "node:util";
5
+
6
+ //#region src/bin/help.ts
7
+ /** @file Help text and banner formatters for the moku CLI. */
8
+ /**
9
+ * Format the banner line shown before any output.
10
+ *
11
+ * @param version - The package version.
12
+ * @returns The banner string.
13
+ */
14
+ const formatBanner = (version) => `moku v${version}`;
15
+ /**
16
+ * Format the top-level help text listing all commands and global flags.
17
+ *
18
+ * @returns The help text.
19
+ */
20
+ const formatHelp = () => `
21
+ Usage: moku <command> [options]
22
+
23
+ Commands:
24
+ build [folder] Build static site (default folder: src/)
25
+ dev [folder] Start dev server with watch + rebuild
26
+ preview [folder] Build and serve site for local preview
27
+
28
+ Options:
29
+ --version Show version number
30
+ --help, -h Show help
31
+
32
+ Run moku <command> --help for command-specific options.`.trim();
33
+ /**
34
+ * Format the help text for `moku build`.
35
+ *
36
+ * @returns The help text.
37
+ */
38
+ const formatBuildHelp = () => `
39
+ Usage: moku build [folder] [options]
40
+
41
+ Arguments:
42
+ folder Source folder containing main.ts (default: src/)
43
+
44
+ Options:
45
+ --verbose, -v Show detailed build output
46
+ --mode <mode> Build mode: ssg, spa, hybrid
47
+ --help, -h Show help`.trim();
48
+ /**
49
+ * Format the help text for `moku dev`.
50
+ *
51
+ * @returns The help text.
52
+ */
53
+ const formatDevHelp = () => `
54
+ Usage: moku dev [folder] [options]
55
+
56
+ Arguments:
57
+ folder Source folder containing main.ts (default: src/)
58
+
59
+ Options:
60
+ --verbose, -v Show detailed build output
61
+ --port, -p <n> Server port (default: 4173)
62
+ --help, -h Show help`.trim();
63
+ /**
64
+ * Format the help text for `moku preview`.
65
+ *
66
+ * @returns The help text.
67
+ */
68
+ const formatPreviewHelp = () => `
69
+ Usage: moku preview [folder] [options]
70
+
71
+ Arguments:
72
+ folder Source folder containing main.ts (default: src/)
73
+
74
+ Options:
75
+ --port, -p <n> Server port (default: 3000)
76
+ --help, -h Show help`.trim();
77
+
78
+ //#endregion
79
+ //#region src/bin/parse.ts
80
+ /** @file Argument parsers for the moku CLI built on node:util parseArgs. */
81
+ const VALID_MODES = new Set([
82
+ "ssg",
83
+ "spa",
84
+ "hybrid"
85
+ ]);
86
+ const MIN_PORT = 1;
87
+ const MAX_PORT = 65535;
88
+ const DEFAULT_DEV_PORT = 4173;
89
+ const DEFAULT_PREVIEW_PORT = 3e3;
90
+ /**
91
+ * Classify the top-level invocation into version / help / unknown-flag / command.
92
+ *
93
+ * @param argv - The argv slice (already stripped of `process.argv[0..1]`).
94
+ * @returns A {@link TopLevel} discriminant.
95
+ */
96
+ const parseTopLevel = (argv) => {
97
+ if (argv.length === 0) return { kind: "help" };
98
+ const [first, ...rest] = argv;
99
+ if (first === void 0) return { kind: "help" };
100
+ if (first === "--version") return { kind: "version" };
101
+ if (first === "--help" || first === "-h") return { kind: "help" };
102
+ if (first.startsWith("-")) return {
103
+ kind: "unknown-flag",
104
+ flag: first
105
+ };
106
+ return {
107
+ kind: "command",
108
+ command: first,
109
+ rest
110
+ };
111
+ };
112
+ const parsePort = (value, fallback) => {
113
+ if (value === void 0) return {
114
+ ok: true,
115
+ value: fallback
116
+ };
117
+ const port = Number.parseInt(value, 10);
118
+ if (!Number.isFinite(port) || `${port}` !== value) return {
119
+ ok: false,
120
+ message: `Invalid port: ${value}. Must be a number.`
121
+ };
122
+ if (port < MIN_PORT || port > MAX_PORT) return {
123
+ ok: false,
124
+ message: `Invalid port: ${port}. Must be ${MIN_PORT}-${MAX_PORT}.`
125
+ };
126
+ return {
127
+ ok: true,
128
+ value: port
129
+ };
130
+ };
131
+ /**
132
+ * Parse `moku build` arguments.
133
+ *
134
+ * @param argv - Argv after the `build` keyword.
135
+ * @returns A {@link ParseResult} carrying a {@link BuildArgs} or an error message.
136
+ */
137
+ const parseBuild = (argv) => {
138
+ try {
139
+ const { values, positionals } = parseArgs({
140
+ args: argv,
141
+ options: {
142
+ verbose: {
143
+ type: "boolean",
144
+ short: "v",
145
+ default: false
146
+ },
147
+ mode: { type: "string" },
148
+ help: {
149
+ type: "boolean",
150
+ short: "h",
151
+ default: false
152
+ }
153
+ },
154
+ allowPositionals: true,
155
+ strict: true
156
+ });
157
+ if (values.mode !== void 0 && !VALID_MODES.has(values.mode)) return {
158
+ ok: false,
159
+ message: `Invalid mode: ${values.mode}. Must be one of: ssg, spa, hybrid.`
160
+ };
161
+ const mode = values.mode;
162
+ return {
163
+ ok: true,
164
+ value: {
165
+ folder: positionals[0] ?? "src",
166
+ verbose: values.verbose,
167
+ help: values.help,
168
+ ...mode === void 0 ? {} : { mode }
169
+ }
170
+ };
171
+ } catch (error) {
172
+ return {
173
+ ok: false,
174
+ message: error.message
175
+ };
176
+ }
177
+ };
178
+ /**
179
+ * Parse `moku dev` arguments.
180
+ *
181
+ * @param argv - Argv after the `dev` keyword.
182
+ * @returns A {@link ParseResult} carrying a {@link DevArgs} or an error message.
183
+ */
184
+ const parseDev = (argv) => {
185
+ try {
186
+ const { values, positionals } = parseArgs({
187
+ args: argv,
188
+ options: {
189
+ verbose: {
190
+ type: "boolean",
191
+ short: "v",
192
+ default: false
193
+ },
194
+ port: {
195
+ type: "string",
196
+ short: "p"
197
+ },
198
+ help: {
199
+ type: "boolean",
200
+ short: "h",
201
+ default: false
202
+ }
203
+ },
204
+ allowPositionals: true,
205
+ strict: true
206
+ });
207
+ const port = parsePort(values.port, DEFAULT_DEV_PORT);
208
+ if (!port.ok) return port;
209
+ return {
210
+ ok: true,
211
+ value: {
212
+ folder: positionals[0] ?? "src",
213
+ verbose: values.verbose,
214
+ help: values.help,
215
+ port: port.value
216
+ }
217
+ };
218
+ } catch (error) {
219
+ return {
220
+ ok: false,
221
+ message: error.message
222
+ };
223
+ }
224
+ };
225
+ /**
226
+ * Parse `moku preview` arguments.
227
+ *
228
+ * @param argv - Argv after the `preview` keyword.
229
+ * @returns A {@link ParseResult} carrying a {@link PreviewArgs} or an error message.
230
+ */
231
+ const parsePreview = (argv) => {
232
+ try {
233
+ const { values, positionals } = parseArgs({
234
+ args: argv,
235
+ options: {
236
+ port: {
237
+ type: "string",
238
+ short: "p"
239
+ },
240
+ help: {
241
+ type: "boolean",
242
+ short: "h",
243
+ default: false
244
+ }
245
+ },
246
+ allowPositionals: true,
247
+ strict: true
248
+ });
249
+ const port = parsePort(values.port, DEFAULT_PREVIEW_PORT);
250
+ if (!port.ok) return port;
251
+ return {
252
+ ok: true,
253
+ value: {
254
+ folder: positionals[0] ?? "src",
255
+ help: values.help,
256
+ port: port.value
257
+ }
258
+ };
259
+ } catch (error) {
260
+ return {
261
+ ok: false,
262
+ message: error.message
263
+ };
264
+ }
265
+ };
266
+
267
+ //#endregion
268
+ //#region src/bin/version.ts
269
+ const parseSemver = (raw) => {
270
+ const stripped = raw.split(/[+-]/, 1)[0] ?? raw;
271
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(stripped);
272
+ if (match === null) return null;
273
+ return {
274
+ major: Number(match[1]),
275
+ minor: Number(match[2]),
276
+ patch: Number(match[3])
277
+ };
278
+ };
279
+ const compareSemver = (a, b) => {
280
+ if (a.major !== b.major) return a.major - b.major;
281
+ if (a.minor !== b.minor) return a.minor - b.minor;
282
+ return a.patch - b.patch;
283
+ };
284
+ const satisfiesRange = (actual, min, prefix) => {
285
+ if (prefix === "^") return actual.major === min.major && compareSemver(actual, min) >= 0;
286
+ if (prefix === "~") {
287
+ if (actual.major !== min.major || actual.minor !== min.minor) return false;
288
+ return actual.patch >= min.patch;
289
+ }
290
+ return compareSemver(actual, min) >= 0;
291
+ };
292
+ const splitRange = (engine) => {
293
+ const trimmed = engine.trim();
294
+ const match = /^(>=|\^|~)(.+)$/.exec(trimmed);
295
+ if (match === null) return {
296
+ prefix: ">=",
297
+ rawMin: trimmed
298
+ };
299
+ return {
300
+ prefix: match[1],
301
+ rawMin: match[2] ?? ""
302
+ };
303
+ };
304
+ /**
305
+ * Check whether a Bun runtime version satisfies a simple engines range.
306
+ *
307
+ * Supports `>=A.B.C`, `^A.B.C`, `~A.B.C`. Returns ok=true if `engine` is
308
+ * undefined (no constraint). Pre-release suffixes on `bunVersion` are stripped
309
+ * for the comparison.
310
+ *
311
+ * @param bunVersion - The current `Bun.version` string.
312
+ * @param engine - The `engines.bun` field from package.json (or undefined).
313
+ * @returns A {@link VersionCheck} with `ok: false` carrying a user-facing message.
314
+ */
315
+ const checkBunVersion = (bunVersion, engine) => {
316
+ if (engine === void 0) return { ok: true };
317
+ const actual = parseSemver(bunVersion);
318
+ if (actual === null) return {
319
+ ok: false,
320
+ message: `Unable to parse Bun version: ${bunVersion}`
321
+ };
322
+ const { prefix, rawMin } = splitRange(engine);
323
+ const min = parseSemver(rawMin);
324
+ if (min === null) return {
325
+ ok: false,
326
+ message: `Unable to parse engine range: ${engine}`
327
+ };
328
+ if (satisfiesRange(actual, min, prefix)) return { ok: true };
329
+ return {
330
+ ok: false,
331
+ message: `Bun ${bunVersion} does not satisfy engines.bun "${engine}". Install Bun ${rawMin} or newer.`
332
+ };
333
+ };
334
+
335
+ //#endregion
336
+ //#region src/bin/cli.ts
337
+ /** @file runCli — pure dispatch over injected deps. Tested without spawning subprocesses. */
338
+ /**
339
+ * Top-level CLI dispatcher.
340
+ *
341
+ * Exit codes:
342
+ * 0 - success
343
+ * 1 - config / discovery error
344
+ * 2 - build / runtime error
345
+ * 3 - invalid arguments
346
+ * 4 - unsupported runtime
347
+ *
348
+ * @param argv - Argv slice (already stripped of `node`/`bun` + script path).
349
+ * @param deps - Injected dependencies.
350
+ * @returns The exit code wrapper.
351
+ */
352
+ const runCli = async (argv, deps) => {
353
+ const top = parseTopLevel(argv);
354
+ if (top.kind === "version") {
355
+ deps.stdout(deps.version);
356
+ return { code: 0 };
357
+ }
358
+ if (top.kind === "help") {
359
+ deps.stdout(formatBanner(deps.version));
360
+ deps.stdout(formatHelp());
361
+ return { code: 0 };
362
+ }
363
+ if (top.kind === "unknown-flag") {
364
+ deps.stderr(`Unknown flag: ${top.flag}`);
365
+ deps.stdout(formatHelp());
366
+ return { code: 3 };
367
+ }
368
+ const versionCheck = checkBunVersion(deps.bunVersion, deps.bunEngine);
369
+ if (!versionCheck.ok) {
370
+ deps.stderr(versionCheck.message);
371
+ return { code: 4 };
372
+ }
373
+ deps.stdout(formatBanner(deps.version));
374
+ switch (top.command) {
375
+ case "build": return deps.buildCommand(top.rest);
376
+ case "dev": return deps.devCommand(top.rest);
377
+ case "preview": return deps.previewCommand(top.rest);
378
+ default:
379
+ deps.stderr(`Unknown command: ${top.command}`);
380
+ deps.stdout(formatHelp());
381
+ return { code: 3 };
382
+ }
383
+ };
384
+
385
+ //#endregion
386
+ //#region src/bin/commands/prepare.ts
387
+ /**
388
+ * Parse argv, branch on help/error, then load the app. Reduces command
389
+ * complexity by hiding the four-way branch behind a single discriminant.
390
+ *
391
+ * @param options - Parser + loader + cwd.
392
+ * @returns A {@link PreparedOutcome}.
393
+ */
394
+ const prepareApp = async (options) => {
395
+ const parsed = options.parse(options.argv);
396
+ if (!parsed.ok) return {
397
+ kind: "bad-args",
398
+ message: parsed.message
399
+ };
400
+ if (parsed.value.help) return { kind: "help" };
401
+ const loaded = await options.loadApp({
402
+ cwd: options.cwd,
403
+ folder: parsed.value.folder
404
+ });
405
+ if (!loaded.ok) return {
406
+ kind: "load-failed",
407
+ message: loaded.message
408
+ };
409
+ return {
410
+ kind: "ready",
411
+ args: parsed.value,
412
+ app: loaded.value
413
+ };
414
+ };
415
+ /**
416
+ * Time a build run and report it.
417
+ *
418
+ * @param app - The loaded CliApp.
419
+ * @param stdout - Output channel.
420
+ * @returns Exit code (0 ok, 2 build failure) and message already emitted.
421
+ */
422
+ const runBuildOnce = async (app, stdout, stderr) => {
423
+ const start = performance.now();
424
+ try {
425
+ await app.build.run();
426
+ } catch (error) {
427
+ stderr(`Build failed: ${error.message}`);
428
+ return { code: 2 };
429
+ }
430
+ stdout(`Built in ${Math.round((performance.now() - start) / 100) / 10}s`);
431
+ return { code: 0 };
432
+ };
433
+
434
+ //#endregion
435
+ //#region src/bin/commands/build.ts
436
+ /** @file `moku build` command — load app, run app.build.run(), report timing. */
437
+ /**
438
+ * Run the build subcommand.
439
+ *
440
+ * @param argv - Argv after the `build` keyword.
441
+ * @param deps - Injected IO / loader dependencies.
442
+ * @returns Exit code: 0 ok, 1 config error, 2 build error, 3 arg error.
443
+ */
444
+ const buildCommand = async (argv, deps) => {
445
+ const prepared = await prepareApp({
446
+ argv,
447
+ parse: parseBuild,
448
+ loadApp: deps.loadApp,
449
+ cwd: deps.cwd
450
+ });
451
+ if (prepared.kind === "help") {
452
+ deps.stdout(formatBuildHelp());
453
+ return { code: 0 };
454
+ }
455
+ if (prepared.kind === "bad-args") {
456
+ deps.stderr(prepared.message);
457
+ deps.stdout(formatBuildHelp());
458
+ return { code: 3 };
459
+ }
460
+ if (prepared.kind === "load-failed") {
461
+ deps.stderr(prepared.message);
462
+ return { code: 1 };
463
+ }
464
+ return runBuildOnce(prepared.app, deps.stdout, deps.stderr);
465
+ };
466
+
467
+ //#endregion
468
+ //#region src/bin/commands/dev.ts
469
+ /** @file `moku dev` command — watch + invalidate + rebuild + serve loop. */
470
+ const makeRebuildHandler = (app, deps) => async (paths) => {
471
+ if (app.content !== void 0) app.content.invalidate(paths);
472
+ try {
473
+ await app.build.run();
474
+ deps.stdout(`[dev] Rebuilt (${paths.length} change${paths.length === 1 ? "" : "s"})`);
475
+ } catch (error) {
476
+ deps.stderr(`[dev] Rebuild failed: ${error.message}`);
477
+ }
478
+ };
479
+ const startDevServer = (app, deps, port) => {
480
+ const outdir = app.config?.build?.outdir ?? "dist";
481
+ const defaultLocale = app.config?.i18n?.defaultLocale ?? "en";
482
+ return deps.serve({
483
+ rootDir: resolve(deps.cwd, outdir),
484
+ port,
485
+ defaultLocale
486
+ });
487
+ };
488
+ /**
489
+ * Run the dev subcommand.
490
+ *
491
+ * Builds once, then watches `contentDir` and on each batch invalidates
492
+ * content paths BEFORE calling `app.build.run()` (hard rule from CLAUDE.md).
493
+ *
494
+ * @param argv - Argv after the `dev` keyword.
495
+ * @param deps - Injected IO / loader / watch / serve dependencies.
496
+ * @returns Exit code: 0 ok, 1 config error, 2 build error, 3 arg error.
497
+ */
498
+ const devCommand = async (argv, deps) => {
499
+ const prepared = await prepareApp({
500
+ argv,
501
+ parse: parseDev,
502
+ loadApp: deps.loadApp,
503
+ cwd: deps.cwd
504
+ });
505
+ if (prepared.kind === "help") {
506
+ deps.stdout(formatDevHelp());
507
+ return { code: 0 };
508
+ }
509
+ if (prepared.kind === "bad-args") {
510
+ deps.stderr(prepared.message);
511
+ deps.stdout(formatDevHelp());
512
+ return { code: 3 };
513
+ }
514
+ if (prepared.kind === "load-failed") {
515
+ deps.stderr(prepared.message);
516
+ return { code: 1 };
517
+ }
518
+ try {
519
+ await prepared.app.build.run();
520
+ } catch (error) {
521
+ deps.stderr(`Initial build failed: ${error.message}`);
522
+ return { code: 2 };
523
+ }
524
+ const handle = startDevServer(prepared.app, deps, prepared.args.port);
525
+ deps.stdout(`[dev] Serving at http://localhost:${handle.port}`);
526
+ deps.watch({
527
+ rootDir: deps.cwd,
528
+ contentDir: resolve(deps.cwd, "content"),
529
+ onChange: makeRebuildHandler(prepared.app, deps)
530
+ });
531
+ return { code: 0 };
532
+ };
533
+
534
+ //#endregion
535
+ //#region src/bin/commands/preview.ts
536
+ /** @file `moku preview` command — build once, then serve the outdir. */
537
+ const startPreviewServer = (app, cwd, port, serve) => {
538
+ const outdir = app.config?.build?.outdir ?? "dist";
539
+ const defaultLocale = app.config?.i18n?.defaultLocale ?? "en";
540
+ return serve({
541
+ rootDir: resolve(cwd, outdir),
542
+ port,
543
+ defaultLocale
544
+ });
545
+ };
546
+ /**
547
+ * Run the preview subcommand.
548
+ *
549
+ * @param argv - Argv after the `preview` keyword.
550
+ * @param deps - Injected IO / loader / serve dependencies.
551
+ * @returns Exit code: 0 ok, 1 config error, 2 build error, 3 arg error.
552
+ */
553
+ const previewCommand = async (argv, deps) => {
554
+ const prepared = await prepareApp({
555
+ argv,
556
+ parse: parsePreview,
557
+ loadApp: deps.loadApp,
558
+ cwd: deps.cwd
559
+ });
560
+ if (prepared.kind === "help") {
561
+ deps.stdout(formatPreviewHelp());
562
+ return { code: 0 };
563
+ }
564
+ if (prepared.kind === "bad-args") {
565
+ deps.stderr(prepared.message);
566
+ deps.stdout(formatPreviewHelp());
567
+ return { code: 3 };
568
+ }
569
+ if (prepared.kind === "load-failed") {
570
+ deps.stderr(prepared.message);
571
+ return { code: 1 };
572
+ }
573
+ const build = await runBuildOnce(prepared.app, deps.stdout, deps.stderr);
574
+ if (build.code !== 0) return build;
575
+ const handle = startPreviewServer(prepared.app, deps.cwd, prepared.args.port, deps.serve);
576
+ deps.stdout(`[preview] Serving at http://localhost:${handle.port}`);
577
+ return { code: 0 };
578
+ };
579
+
580
+ //#endregion
581
+ //#region src/bin/load-app.ts
582
+ /** @file Discovers and dynamically imports the consumer's main.ts entry. */
583
+ /**
584
+ * Dynamically import `{cwd}/{folder}/main.ts` and return its default export.
585
+ *
586
+ * Returns a structured result rather than throwing; the CLI maps errors to
587
+ * exit codes.
588
+ *
589
+ * @param options - The cwd and folder to look in.
590
+ * @returns A {@link LoadResult}.
591
+ */
592
+ const loadApp = async (options) => {
593
+ const mainPath = resolve(options.cwd, options.folder, "main.ts");
594
+ if (!existsSync(mainPath)) return {
595
+ ok: false,
596
+ message: `main.ts not found at ${mainPath}. Run \`moku <command> <folder>\` with the correct path.`,
597
+ path: mainPath
598
+ };
599
+ try {
600
+ const mod = await import(mainPath);
601
+ if (mod.default === void 0) return {
602
+ ok: false,
603
+ message: `${mainPath} has no default export. Export your createApp() result as default.`,
604
+ path: mainPath
605
+ };
606
+ return {
607
+ ok: true,
608
+ value: mod.default,
609
+ path: mainPath
610
+ };
611
+ } catch (error) {
612
+ return {
613
+ ok: false,
614
+ message: `Failed to import ${mainPath}: ${error.message}`,
615
+ path: mainPath
616
+ };
617
+ }
618
+ };
619
+
620
+ //#endregion
621
+ //#region src/bin/serve.ts
622
+ /** @file Static file handler used by `moku preview` and `moku dev`. */
623
+ const MIME_TYPES = new Map([
624
+ [".html", "text/html; charset=utf-8"],
625
+ [".css", "text/css; charset=utf-8"],
626
+ [".js", "application/javascript; charset=utf-8"],
627
+ [".mjs", "application/javascript; charset=utf-8"],
628
+ [".json", "application/json; charset=utf-8"],
629
+ [".svg", "image/svg+xml"],
630
+ [".png", "image/png"],
631
+ [".jpg", "image/jpeg"],
632
+ [".jpeg", "image/jpeg"],
633
+ [".gif", "image/gif"],
634
+ [".webp", "image/webp"],
635
+ [".ico", "image/x-icon"],
636
+ [".txt", "text/plain; charset=utf-8"],
637
+ [".xml", "application/xml; charset=utf-8"],
638
+ [".woff", "font/woff"],
639
+ [".woff2", "font/woff2"]
640
+ ]);
641
+ const mimeFor = (path) => MIME_TYPES.get(extname(path).toLowerCase()) ?? "application/octet-stream";
642
+ const isPathInside = (parent, child) => `${child}${sep}`.startsWith(`${parent}${sep}`);
643
+ const resolveTarget = (rootDir, urlPath) => {
644
+ const target = resolve(rootDir, normalize(`./${decodeURIComponent(urlPath).replaceAll("\\", "/").replace(/\/+/g, "/")}`));
645
+ if (!isPathInside(rootDir, target) && target !== rootDir) return null;
646
+ return target;
647
+ };
648
+ const resolveFilePath = (target, urlPath) => {
649
+ const candidate = urlPath.endsWith("/") ? resolve(target, "index.html") : target;
650
+ if (!existsSync(candidate)) return null;
651
+ if (!statSync(candidate).isDirectory()) return candidate;
652
+ const indexed = resolve(candidate, "index.html");
653
+ return existsSync(indexed) ? indexed : null;
654
+ };
655
+ const fileResponse = (path) => new Response(readFileSync(path), { headers: { "content-type": mimeFor(path) } });
656
+ /**
657
+ * Build a fetch-style handler that serves files from `rootDir`.
658
+ *
659
+ * Behavior:
660
+ * - Bare `/` redirects (307) to `/{defaultLocale}/`.
661
+ * - Paths ending in `/` look for `index.html`.
662
+ * - Path traversal attempts return 403.
663
+ * - Missing files return 404.
664
+ *
665
+ * @param options - The root directory and default locale.
666
+ * @returns A `(request: Request) => Promise<Response>` handler.
667
+ */
668
+ const createStaticHandler = (options) => {
669
+ const root = resolve(options.rootDir);
670
+ return async (request) => {
671
+ const url = new URL(request.url);
672
+ if (url.pathname === "/") return new Response(null, {
673
+ status: 307,
674
+ headers: { location: `/${options.defaultLocale}/` }
675
+ });
676
+ const target = resolveTarget(root, url.pathname);
677
+ if (target === null) return new Response("Forbidden", { status: 403 });
678
+ const filePath = resolveFilePath(target, url.pathname);
679
+ if (filePath === null) return new Response("Not Found", { status: 404 });
680
+ return fileResponse(filePath);
681
+ };
682
+ };
683
+
684
+ //#endregion
685
+ //#region src/bin/watch.ts
686
+ /**
687
+ * Create a trailing-edge debounced change batcher.
688
+ *
689
+ * Each `push(path)` (re)starts the debounce timer. When the timer fires the
690
+ * collected unique paths are passed to `onFlush` and a new batch begins.
691
+ * `flush()` drains immediately; `dispose()` cancels any pending flush without
692
+ * invoking the callback.
693
+ *
694
+ * @param options - Debounce window + flush callback.
695
+ * @returns The {@link ChangeBatcher} handle.
696
+ */
697
+ const createChangeBatcher = (options) => {
698
+ let pending = /* @__PURE__ */ new Set();
699
+ let timer = null;
700
+ const clearTimer = () => {
701
+ if (timer !== null) {
702
+ clearTimeout(timer);
703
+ timer = null;
704
+ }
705
+ };
706
+ const drain = () => {
707
+ clearTimer();
708
+ if (pending.size === 0) return;
709
+ const batch = [...pending];
710
+ pending = /* @__PURE__ */ new Set();
711
+ options.onFlush(batch);
712
+ };
713
+ return {
714
+ push: (path) => {
715
+ pending.add(path);
716
+ clearTimer();
717
+ timer = setTimeout(drain, options.debounceMs);
718
+ },
719
+ flush: drain,
720
+ dispose: () => {
721
+ clearTimer();
722
+ pending = /* @__PURE__ */ new Set();
723
+ }
724
+ };
725
+ };
726
+
727
+ //#endregion
728
+ //#region src/bin/moku.ts
729
+ /** @file moku CLI entry — wires runtime IO to runCli. NOT a plugin. */
730
+ const findPackageJson = () => {
731
+ const candidates = [
732
+ resolve(import.meta.dir, "..", "..", "package.json"),
733
+ resolve(import.meta.dir, "..", "package.json"),
734
+ resolve(process.cwd(), "package.json")
735
+ ];
736
+ for (const candidate of candidates) if (existsSync(candidate)) return JSON.parse(readFileSync(candidate, "utf8"));
737
+ return {};
738
+ };
739
+ const pkg = findPackageJson();
740
+ const stdout = (line) => {
741
+ process.stdout.write(`${line}\n`);
742
+ };
743
+ const stderr = (line) => {
744
+ process.stderr.write(`${line}\n`);
745
+ };
746
+ const serveStatic = (options) => {
747
+ const handler = createStaticHandler({
748
+ rootDir: options.rootDir,
749
+ defaultLocale: options.defaultLocale
750
+ });
751
+ const server = Bun.serve({
752
+ port: options.port,
753
+ fetch: handler
754
+ });
755
+ return {
756
+ port: server.port ?? options.port,
757
+ stop: () => server.stop()
758
+ };
759
+ };
760
+ const startWatcher = (options) => {
761
+ const batcher = createChangeBatcher({
762
+ debounceMs: 50,
763
+ onFlush: (paths) => options.onChange(paths)
764
+ });
765
+ if (!existsSync(options.contentDir)) return { stop: () => batcher.dispose() };
766
+ const watcher = watch(options.contentDir, { recursive: true }, (_event, filename) => {
767
+ if (filename !== null) batcher.push(filename.toString());
768
+ });
769
+ return { stop: () => {
770
+ watcher.close();
771
+ batcher.dispose();
772
+ } };
773
+ };
774
+ const main = async () => {
775
+ const result = await runCli(process.argv.slice(2), {
776
+ cwd: process.cwd(),
777
+ version: pkg.version ?? "0.0.0",
778
+ bunVersion: Bun.version,
779
+ bunEngine: pkg.engines?.bun,
780
+ stdout,
781
+ stderr,
782
+ buildCommand: (argv) => buildCommand(argv, {
783
+ cwd: process.cwd(),
784
+ stdout,
785
+ stderr,
786
+ loadApp
787
+ }),
788
+ devCommand: (argv) => devCommand(argv, {
789
+ cwd: process.cwd(),
790
+ stdout,
791
+ stderr,
792
+ loadApp,
793
+ watch: startWatcher,
794
+ serve: serveStatic
795
+ }),
796
+ previewCommand: (argv) => previewCommand(argv, {
797
+ cwd: process.cwd(),
798
+ stdout,
799
+ stderr,
800
+ loadApp,
801
+ serve: serveStatic
802
+ })
803
+ });
804
+ process.exit(result.code);
805
+ };
806
+ main();
807
+
808
+ //#endregion
809
+ export { };