mokup 0.2.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1436 @@
1
+ 'use strict';
2
+
3
+ const node_buffer = require('node:buffer');
4
+ const hono = require('@mokup/shared/hono');
5
+ const node_fs = require('node:fs');
6
+ const node_module = require('node:module');
7
+ const process = require('node:process');
8
+ const pathe = require('@mokup/shared/pathe');
9
+ const node_url = require('node:url');
10
+ const esbuild = require('@mokup/shared/esbuild');
11
+ const jsoncParser = require('@mokup/shared/jsonc-parser');
12
+ const runtime = require('@mokup/runtime');
13
+
14
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
15
+ function createLogger(enabled) {
16
+ return {
17
+ info: (...args) => {
18
+ if (enabled) {
19
+ console.info("[mokup]", ...args);
20
+ }
21
+ },
22
+ warn: (...args) => {
23
+ if (enabled) {
24
+ console.warn("[mokup]", ...args);
25
+ }
26
+ },
27
+ error: (...args) => {
28
+ if (enabled) {
29
+ console.error("[mokup]", ...args);
30
+ }
31
+ }
32
+ };
33
+ }
34
+
35
+ const methodSet = /* @__PURE__ */ new Set([
36
+ "GET",
37
+ "POST",
38
+ "PUT",
39
+ "PATCH",
40
+ "DELETE",
41
+ "OPTIONS",
42
+ "HEAD"
43
+ ]);
44
+ const methodSuffixSet = new Set(
45
+ Array.from(methodSet, (method) => method.toLowerCase())
46
+ );
47
+ const supportedExtensions = /* @__PURE__ */ new Set([
48
+ ".json",
49
+ ".jsonc",
50
+ ".ts",
51
+ ".js",
52
+ ".mjs",
53
+ ".cjs"
54
+ ]);
55
+
56
+ function normalizeMethod(method) {
57
+ if (!method) {
58
+ return void 0;
59
+ }
60
+ const normalized = method.toUpperCase();
61
+ if (methodSet.has(normalized)) {
62
+ return normalized;
63
+ }
64
+ return void 0;
65
+ }
66
+ function normalizePrefix(prefix) {
67
+ if (!prefix) {
68
+ return "";
69
+ }
70
+ const normalized = prefix.startsWith("/") ? prefix : `/${prefix}`;
71
+ return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
72
+ }
73
+ function resolveDirs(dir, root) {
74
+ const raw = typeof dir === "function" ? dir(root) : dir;
75
+ const resolved = Array.isArray(raw) ? raw : raw ? [raw] : ["mock"];
76
+ const normalized = resolved.map(
77
+ (entry) => pathe.isAbsolute(entry) ? entry : pathe.resolve(root, entry)
78
+ );
79
+ return Array.from(new Set(normalized));
80
+ }
81
+ function createDebouncer(delayMs, fn) {
82
+ let timer = null;
83
+ return () => {
84
+ if (timer) {
85
+ clearTimeout(timer);
86
+ }
87
+ timer = setTimeout(() => {
88
+ timer = null;
89
+ fn();
90
+ }, delayMs);
91
+ };
92
+ }
93
+ function toPosix(value) {
94
+ return value.replace(/\\/g, "/");
95
+ }
96
+ function isInDirs(file, dirs) {
97
+ const normalized = toPosix(file);
98
+ return dirs.some((dir) => {
99
+ const normalizedDir = toPosix(dir).replace(/\/$/, "");
100
+ return normalized === normalizedDir || normalized.startsWith(`${normalizedDir}/`);
101
+ });
102
+ }
103
+ function testPatterns(patterns, value) {
104
+ const list = Array.isArray(patterns) ? patterns : [patterns];
105
+ return list.some((pattern) => pattern.test(value));
106
+ }
107
+ function matchesFilter(file, include, exclude) {
108
+ const normalized = toPosix(file);
109
+ if (exclude && testPatterns(exclude, normalized)) {
110
+ return false;
111
+ }
112
+ if (include) {
113
+ return testPatterns(include, normalized);
114
+ }
115
+ return true;
116
+ }
117
+ function delay(ms) {
118
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
119
+ }
120
+
121
+ function toHonoPath(route) {
122
+ if (!route.tokens || route.tokens.length === 0) {
123
+ return "/";
124
+ }
125
+ const segments = route.tokens.map((token) => {
126
+ if (token.type === "static") {
127
+ return token.value;
128
+ }
129
+ if (token.type === "param") {
130
+ return `:${token.name}`;
131
+ }
132
+ if (token.type === "catchall") {
133
+ return `:${token.name}{.+}`;
134
+ }
135
+ return `:${token.name}{.+}?`;
136
+ });
137
+ return `/${segments.join("/")}`;
138
+ }
139
+ function isValidStatus(status) {
140
+ return typeof status === "number" && Number.isFinite(status) && status >= 200 && status <= 599;
141
+ }
142
+ function resolveStatus(routeStatus, responseStatus) {
143
+ if (isValidStatus(routeStatus)) {
144
+ return routeStatus;
145
+ }
146
+ if (isValidStatus(responseStatus)) {
147
+ return responseStatus;
148
+ }
149
+ return 200;
150
+ }
151
+ function applyRouteOverrides(response, route) {
152
+ const headers = new Headers(response.headers);
153
+ const hasHeaders = !!route.headers && Object.keys(route.headers).length > 0;
154
+ if (route.headers) {
155
+ for (const [key, value] of Object.entries(route.headers)) {
156
+ headers.set(key, value);
157
+ }
158
+ }
159
+ const status = resolveStatus(route.status, response.status);
160
+ if (status === response.status && !hasHeaders) {
161
+ return response;
162
+ }
163
+ return new Response(response.body, { status, headers });
164
+ }
165
+ function normalizeHandlerValue(c, value) {
166
+ if (value instanceof Response) {
167
+ return value;
168
+ }
169
+ if (typeof value === "undefined") {
170
+ const response = c.body(null);
171
+ if (response.status === 200) {
172
+ return new Response(response.body, {
173
+ status: 204,
174
+ headers: response.headers
175
+ });
176
+ }
177
+ return response;
178
+ }
179
+ if (typeof value === "string") {
180
+ return c.text(value);
181
+ }
182
+ if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
183
+ if (!c.res.headers.get("content-type")) {
184
+ c.header("content-type", "application/octet-stream");
185
+ }
186
+ const data = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value);
187
+ return c.body(data);
188
+ }
189
+ return c.json(value);
190
+ }
191
+ function createRouteHandler(route) {
192
+ return async (c) => {
193
+ const value = typeof route.handler === "function" ? await route.handler(c) : route.handler;
194
+ return normalizeHandlerValue(c, value);
195
+ };
196
+ }
197
+ function createFinalizeMiddleware(route) {
198
+ return async (c, next) => {
199
+ const response = await next();
200
+ const resolved = response ?? c.res;
201
+ if (route.delay && route.delay > 0) {
202
+ await delay(route.delay);
203
+ }
204
+ return applyRouteOverrides(resolved, route);
205
+ };
206
+ }
207
+ function wrapMiddleware(handler) {
208
+ return async (c, next) => {
209
+ const response = await handler(c, next);
210
+ return response ?? c.res;
211
+ };
212
+ }
213
+ function createHonoApp(routes) {
214
+ const app = new hono.Hono({ router: new hono.PatternRouter(), strict: false });
215
+ for (const route of routes) {
216
+ const middlewares = route.middlewares?.map((entry) => wrapMiddleware(entry.handle)) ?? [];
217
+ app.on(
218
+ route.method,
219
+ toHonoPath(route),
220
+ createFinalizeMiddleware(route),
221
+ ...middlewares,
222
+ createRouteHandler(route)
223
+ );
224
+ }
225
+ return app;
226
+ }
227
+ async function readRawBody(req) {
228
+ return await new Promise((resolve, reject) => {
229
+ const chunks = [];
230
+ req.on("data", (chunk) => {
231
+ if (typeof chunk === "string") {
232
+ chunks.push(node_buffer.Buffer.from(chunk));
233
+ return;
234
+ }
235
+ if (chunk instanceof Uint8Array) {
236
+ chunks.push(chunk);
237
+ return;
238
+ }
239
+ chunks.push(node_buffer.Buffer.from(String(chunk)));
240
+ });
241
+ req.on("end", () => {
242
+ if (chunks.length === 0) {
243
+ resolve(null);
244
+ return;
245
+ }
246
+ resolve(node_buffer.Buffer.concat(chunks));
247
+ });
248
+ req.on("error", reject);
249
+ });
250
+ }
251
+ function buildHeaders(headers) {
252
+ const result = new Headers();
253
+ for (const [key, value] of Object.entries(headers)) {
254
+ if (typeof value === "undefined") {
255
+ continue;
256
+ }
257
+ if (Array.isArray(value)) {
258
+ result.set(key, value.join(","));
259
+ } else {
260
+ result.set(key, value);
261
+ }
262
+ }
263
+ return result;
264
+ }
265
+ async function toRequest(req) {
266
+ const url = new URL(req.url ?? "/", "http://mokup.local");
267
+ const method = req.method ?? "GET";
268
+ const headers = buildHeaders(req.headers);
269
+ const init = { method, headers };
270
+ const rawBody = await readRawBody(req);
271
+ if (rawBody && method !== "GET" && method !== "HEAD") {
272
+ init.body = rawBody;
273
+ }
274
+ return new Request(url.toString(), init);
275
+ }
276
+ async function sendResponse(res, response) {
277
+ res.statusCode = response.status;
278
+ response.headers.forEach((value, key) => {
279
+ res.setHeader(key, value);
280
+ });
281
+ if (!response.body) {
282
+ res.end();
283
+ return;
284
+ }
285
+ const buffer = new Uint8Array(await response.arrayBuffer());
286
+ res.end(buffer);
287
+ }
288
+ function hasMatch(app, method, pathname) {
289
+ const matchMethod = method === "HEAD" ? "GET" : method;
290
+ const match = app.router.match(matchMethod, pathname);
291
+ return !!match && match[0].length > 0;
292
+ }
293
+ function createMiddleware(getApp, logger) {
294
+ return async (req, res, next) => {
295
+ const app = getApp();
296
+ if (!app) {
297
+ return next();
298
+ }
299
+ const url = req.url ?? "/";
300
+ const parsedUrl = new URL(url, "http://mokup.local");
301
+ const pathname = parsedUrl.pathname;
302
+ const method = normalizeMethod(req.method) ?? "GET";
303
+ if (!hasMatch(app, method, pathname)) {
304
+ return next();
305
+ }
306
+ const startedAt = Date.now();
307
+ try {
308
+ const response = await app.fetch(await toRequest(req));
309
+ if (res.writableEnded) {
310
+ return;
311
+ }
312
+ await sendResponse(res, response);
313
+ logger.info(`${method} ${pathname} ${Date.now() - startedAt}ms`);
314
+ } catch (error) {
315
+ if (!res.headersSent) {
316
+ res.statusCode = 500;
317
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
318
+ }
319
+ res.end("Mock handler error");
320
+ logger.error("Mock handler failed:", error);
321
+ }
322
+ };
323
+ }
324
+
325
+ const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/mokup.zAF8ClCC.cjs', document.baseURI).href)));
326
+ const mimeTypes = {
327
+ ".html": "text/html; charset=utf-8",
328
+ ".css": "text/css; charset=utf-8",
329
+ ".js": "text/javascript; charset=utf-8",
330
+ ".map": "application/json; charset=utf-8",
331
+ ".json": "application/json; charset=utf-8",
332
+ ".svg": "image/svg+xml",
333
+ ".png": "image/png",
334
+ ".jpg": "image/jpeg",
335
+ ".jpeg": "image/jpeg",
336
+ ".ico": "image/x-icon"
337
+ };
338
+ function normalizePlaygroundPath(value) {
339
+ if (!value) {
340
+ return "/_mokup";
341
+ }
342
+ const normalized = value.startsWith("/") ? value : `/${value}`;
343
+ return normalized.length > 1 && normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
344
+ }
345
+ function normalizeBase(base) {
346
+ if (!base || base === "/") {
347
+ return "";
348
+ }
349
+ return base.endsWith("/") ? base.slice(0, -1) : base;
350
+ }
351
+ function resolvePlaygroundRequestPath(base, playgroundPath) {
352
+ const normalizedBase = normalizeBase(base);
353
+ const normalizedPath = normalizePlaygroundPath(playgroundPath);
354
+ if (!normalizedBase) {
355
+ return normalizedPath;
356
+ }
357
+ if (normalizedPath.startsWith(normalizedBase)) {
358
+ return normalizedPath;
359
+ }
360
+ return `${normalizedBase}${normalizedPath}`;
361
+ }
362
+ function injectPlaygroundHmr(html, base) {
363
+ if (html.includes("mokup-playground-hmr")) {
364
+ return html;
365
+ }
366
+ const normalizedBase = normalizeBase(base);
367
+ const clientPath = `${normalizedBase}/@vite/client`;
368
+ const snippet = [
369
+ '<script type="module" id="mokup-playground-hmr">',
370
+ `import('${clientPath}').then(({ createHotContext }) => {`,
371
+ " const hot = createHotContext('/@mokup/playground')",
372
+ " hot.on('mokup:routes-changed', () => {",
373
+ " const api = window.__MOKUP_PLAYGROUND__",
374
+ " if (api && typeof api.reloadRoutes === 'function') {",
375
+ " api.reloadRoutes()",
376
+ " return",
377
+ " }",
378
+ " window.location.reload()",
379
+ " })",
380
+ "}).catch(() => {})",
381
+ "<\/script>"
382
+ ].join("\n");
383
+ if (html.includes("</body>")) {
384
+ return html.replace("</body>", `${snippet}
385
+ </body>`);
386
+ }
387
+ return `${html}
388
+ ${snippet}`;
389
+ }
390
+ function injectPlaygroundSw(html, script) {
391
+ if (!script) {
392
+ return html;
393
+ }
394
+ if (html.includes("mokup-playground-sw")) {
395
+ return html;
396
+ }
397
+ const snippet = [
398
+ '<script type="module" id="mokup-playground-sw">',
399
+ script,
400
+ "<\/script>"
401
+ ].join("\n");
402
+ if (html.includes("</head>")) {
403
+ return html.replace("</head>", `${snippet}
404
+ </head>`);
405
+ }
406
+ if (html.includes("</body>")) {
407
+ return html.replace("</body>", `${snippet}
408
+ </body>`);
409
+ }
410
+ return `${html}
411
+ ${snippet}`;
412
+ }
413
+ function isViteDevServer(server) {
414
+ return !!server && "ws" in server;
415
+ }
416
+ function resolvePlaygroundOptions(playground) {
417
+ if (playground === false) {
418
+ return { enabled: false, path: "/_mokup" };
419
+ }
420
+ if (playground && typeof playground === "object") {
421
+ return {
422
+ enabled: playground.enabled !== false,
423
+ path: normalizePlaygroundPath(playground.path)
424
+ };
425
+ }
426
+ return { enabled: true, path: "/_mokup" };
427
+ }
428
+ function resolvePlaygroundDist() {
429
+ const pkgPath = require$1.resolve("@mokup/playground/package.json");
430
+ return pathe.join(pkgPath, "..", "dist");
431
+ }
432
+ function sendJson(res, data, statusCode = 200) {
433
+ res.statusCode = statusCode;
434
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
435
+ res.end(JSON.stringify(data, null, 2));
436
+ }
437
+ function sendFile(res, content, contentType) {
438
+ res.statusCode = 200;
439
+ res.setHeader("Content-Type", contentType);
440
+ res.end(content);
441
+ }
442
+ function toPosixPath(value) {
443
+ return value.replace(/\\/g, "/");
444
+ }
445
+ function normalizePath(value) {
446
+ return toPosixPath(pathe.normalize(value));
447
+ }
448
+ function isAncestor(parent, child) {
449
+ const normalizedParent = normalizePath(parent).replace(/\/$/, "");
450
+ const normalizedChild = normalizePath(child);
451
+ return normalizedChild === normalizedParent || normalizedChild.startsWith(`${normalizedParent}/`);
452
+ }
453
+ function resolveGroupRoot(dirs, serverRoot) {
454
+ if (!dirs || dirs.length === 0) {
455
+ return serverRoot ?? process.cwd();
456
+ }
457
+ if (serverRoot) {
458
+ const normalizedRoot = normalizePath(serverRoot);
459
+ const canUseRoot = dirs.every((dir) => isAncestor(normalizedRoot, dir));
460
+ if (canUseRoot) {
461
+ return normalizedRoot;
462
+ }
463
+ }
464
+ if (dirs.length === 1) {
465
+ return normalizePath(pathe.dirname(dirs[0]));
466
+ }
467
+ let common = normalizePath(dirs[0]);
468
+ for (const dir of dirs.slice(1)) {
469
+ const normalizedDir = normalizePath(dir);
470
+ while (common && !isAncestor(common, normalizedDir)) {
471
+ const parent = normalizePath(pathe.dirname(common));
472
+ if (parent === common) {
473
+ break;
474
+ }
475
+ common = parent;
476
+ }
477
+ }
478
+ if (!common || common === "/") {
479
+ return serverRoot ?? process.cwd();
480
+ }
481
+ return common;
482
+ }
483
+ function formatRouteFile(file, root) {
484
+ if (!root) {
485
+ return toPosixPath(file);
486
+ }
487
+ const rel = toPosixPath(pathe.relative(root, file));
488
+ if (!rel || rel.startsWith("..")) {
489
+ return toPosixPath(file);
490
+ }
491
+ return rel;
492
+ }
493
+ function resolveGroups(dirs, root) {
494
+ const groups = [];
495
+ const seen = /* @__PURE__ */ new Set();
496
+ for (const dir of dirs) {
497
+ const normalized = normalizePath(dir);
498
+ if (seen.has(normalized)) {
499
+ continue;
500
+ }
501
+ seen.add(normalized);
502
+ const rel = toPosixPath(pathe.relative(root, normalized));
503
+ const label = rel && !rel.startsWith("..") ? rel : normalized;
504
+ groups.push({
505
+ key: normalized,
506
+ label,
507
+ path: normalized
508
+ });
509
+ }
510
+ return groups;
511
+ }
512
+ function resolveRouteGroup(routeFile, groups) {
513
+ if (groups.length === 0) {
514
+ return void 0;
515
+ }
516
+ const normalizedFile = toPosixPath(pathe.normalize(routeFile));
517
+ let matched;
518
+ for (const group of groups) {
519
+ if (normalizedFile === group.path || normalizedFile.startsWith(`${group.path}/`)) {
520
+ if (!matched || group.path.length > matched.path.length) {
521
+ matched = group;
522
+ }
523
+ }
524
+ }
525
+ return matched;
526
+ }
527
+ function toPlaygroundRoute(route, root, groups) {
528
+ const matchedGroup = resolveRouteGroup(route.file, groups);
529
+ const middlewareSources = route.middlewares?.map((entry) => formatRouteFile(entry.source, root));
530
+ return {
531
+ method: route.method,
532
+ url: route.template,
533
+ file: formatRouteFile(route.file, root),
534
+ type: typeof route.handler === "function" ? "handler" : "static",
535
+ status: route.status,
536
+ delay: route.delay,
537
+ middlewareCount: middlewareSources?.length ?? 0,
538
+ middlewares: middlewareSources,
539
+ groupKey: matchedGroup?.key,
540
+ group: matchedGroup?.label
541
+ };
542
+ }
543
+ function createPlaygroundMiddleware(params) {
544
+ const distDir = resolvePlaygroundDist();
545
+ const playgroundPath = params.config.path;
546
+ const indexPath = pathe.join(distDir, "index.html");
547
+ return async (req, res, next) => {
548
+ if (!params.config.enabled) {
549
+ return next();
550
+ }
551
+ const server = params.getServer?.();
552
+ const requestPath = resolvePlaygroundRequestPath(server?.config?.base ?? "/", playgroundPath);
553
+ const requestUrl = req.url ?? "/";
554
+ const url = new URL(requestUrl, "http://mokup.local");
555
+ const pathname = url.pathname;
556
+ const matchedPath = pathname.startsWith(requestPath) ? requestPath : pathname.startsWith(playgroundPath) ? playgroundPath : null;
557
+ if (!matchedPath) {
558
+ return next();
559
+ }
560
+ const subPath = pathname.slice(matchedPath.length);
561
+ if (subPath === "") {
562
+ const suffix = url.search ?? "";
563
+ res.statusCode = 302;
564
+ res.setHeader("Location", `${matchedPath}/${suffix}`);
565
+ res.end();
566
+ return;
567
+ }
568
+ if (subPath === "" || subPath === "/" || subPath === "/index.html") {
569
+ try {
570
+ const html = await node_fs.promises.readFile(indexPath, "utf8");
571
+ let output = html;
572
+ if (isViteDevServer(server)) {
573
+ output = injectPlaygroundHmr(output, server.config.base ?? "/");
574
+ output = injectPlaygroundSw(output, params.getSwScript?.());
575
+ }
576
+ const contentType = mimeTypes[".html"] ?? "text/html; charset=utf-8";
577
+ sendFile(res, output, contentType);
578
+ } catch (error) {
579
+ params.logger.error("Failed to load playground index:", error);
580
+ res.statusCode = 500;
581
+ res.end("Playground is not available.");
582
+ }
583
+ return;
584
+ }
585
+ if (subPath === "/routes") {
586
+ const dirs = params.getDirs?.() ?? [];
587
+ const baseRoot = resolveGroupRoot(dirs, server?.config?.root);
588
+ const groups = resolveGroups(dirs, baseRoot);
589
+ const routes = params.getRoutes();
590
+ sendJson(res, {
591
+ basePath: matchedPath,
592
+ root: baseRoot,
593
+ count: routes.length,
594
+ groups: groups.map((group) => ({ key: group.key, label: group.label })),
595
+ routes: routes.map((route) => toPlaygroundRoute(route, baseRoot, groups))
596
+ });
597
+ return;
598
+ }
599
+ const relPath = subPath.replace(/^\/+/, "");
600
+ if (relPath.includes("..")) {
601
+ res.statusCode = 400;
602
+ res.end("Invalid path.");
603
+ return;
604
+ }
605
+ const normalizedPath = pathe.normalize(relPath);
606
+ const filePath = pathe.join(distDir, normalizedPath);
607
+ try {
608
+ const content = await node_fs.promises.readFile(filePath);
609
+ const ext = pathe.extname(filePath);
610
+ const contentType = mimeTypes[ext] ?? "application/octet-stream";
611
+ sendFile(res, content, contentType);
612
+ } catch {
613
+ return next();
614
+ }
615
+ };
616
+ }
617
+
618
+ const jsonExtensions = /* @__PURE__ */ new Set([".json", ".jsonc"]);
619
+ function resolveTemplate(template, prefix) {
620
+ const normalized = template.startsWith("/") ? template : `/${template}`;
621
+ if (!prefix) {
622
+ return normalized;
623
+ }
624
+ const normalizedPrefix = normalizePrefix(prefix);
625
+ if (!normalizedPrefix) {
626
+ return normalized;
627
+ }
628
+ if (normalized === normalizedPrefix || normalized.startsWith(`${normalizedPrefix}/`)) {
629
+ return normalized;
630
+ }
631
+ if (normalized === "/") {
632
+ return `${normalizedPrefix}/`;
633
+ }
634
+ return `${normalizedPrefix}${normalized}`;
635
+ }
636
+ function stripMethodSuffix(base) {
637
+ const segments = base.split(".");
638
+ const last = segments.at(-1);
639
+ if (last && methodSuffixSet.has(last.toLowerCase())) {
640
+ segments.pop();
641
+ return {
642
+ name: segments.join("."),
643
+ method: last.toUpperCase()
644
+ };
645
+ }
646
+ return {
647
+ name: base,
648
+ method: void 0
649
+ };
650
+ }
651
+ function deriveRouteFromFile(file, rootDir, logger) {
652
+ const rel = toPosix(pathe.relative(rootDir, file));
653
+ const ext = pathe.extname(rel);
654
+ const withoutExt = rel.slice(0, rel.length - ext.length);
655
+ const dir = pathe.dirname(withoutExt);
656
+ const base = pathe.basename(withoutExt);
657
+ const { name, method } = stripMethodSuffix(base);
658
+ const resolvedMethod = method ?? (jsonExtensions.has(ext) ? "GET" : void 0);
659
+ if (!resolvedMethod) {
660
+ logger.warn(`Skip mock without method suffix: ${file}`);
661
+ return null;
662
+ }
663
+ if (!name) {
664
+ logger.warn(`Skip mock with empty route name: ${file}`);
665
+ return null;
666
+ }
667
+ const joined = dir === "." ? name : pathe.join(dir, name);
668
+ const segments = toPosix(joined).split("/");
669
+ if (segments.at(-1) === "index") {
670
+ segments.pop();
671
+ }
672
+ const template = segments.length === 0 ? "/" : `/${segments.join("/")}`;
673
+ const parsed = runtime.parseRouteTemplate(template);
674
+ if (parsed.errors.length > 0) {
675
+ for (const error of parsed.errors) {
676
+ logger.warn(`${error} in ${file}`);
677
+ }
678
+ return null;
679
+ }
680
+ for (const warning of parsed.warnings) {
681
+ logger.warn(`${warning} in ${file}`);
682
+ }
683
+ return {
684
+ template: parsed.template,
685
+ method: resolvedMethod,
686
+ tokens: parsed.tokens,
687
+ score: parsed.score
688
+ };
689
+ }
690
+ function resolveRule(params) {
691
+ const method = params.derivedMethod;
692
+ if (!method) {
693
+ params.logger.warn(`Skip mock without method suffix: ${params.file}`);
694
+ return null;
695
+ }
696
+ const template = resolveTemplate(params.derivedTemplate, params.prefix);
697
+ const parsed = runtime.parseRouteTemplate(template);
698
+ if (parsed.errors.length > 0) {
699
+ for (const error of parsed.errors) {
700
+ params.logger.warn(`${error} in ${params.file}`);
701
+ }
702
+ return null;
703
+ }
704
+ for (const warning of parsed.warnings) {
705
+ params.logger.warn(`${warning} in ${params.file}`);
706
+ }
707
+ const route = {
708
+ file: params.file,
709
+ template: parsed.template,
710
+ method,
711
+ tokens: parsed.tokens,
712
+ score: parsed.score,
713
+ handler: params.rule.handler
714
+ };
715
+ if (typeof params.rule.status === "number") {
716
+ route.status = params.rule.status;
717
+ }
718
+ if (params.rule.headers) {
719
+ route.headers = params.rule.headers;
720
+ }
721
+ if (typeof params.rule.delay === "number") {
722
+ route.delay = params.rule.delay;
723
+ }
724
+ return route;
725
+ }
726
+ function sortRoutes(routes) {
727
+ return routes.sort((a, b) => {
728
+ if (a.method !== b.method) {
729
+ return a.method.localeCompare(b.method);
730
+ }
731
+ const scoreCompare = runtime.compareRouteScore(a.score, b.score);
732
+ if (scoreCompare !== 0) {
733
+ return scoreCompare;
734
+ }
735
+ return a.template.localeCompare(b.template);
736
+ });
737
+ }
738
+
739
+ const configExtensions = [".ts", ".js", ".mjs", ".cjs"];
740
+ async function loadModule$1(file) {
741
+ const ext = configExtensions.find((extension) => file.endsWith(extension));
742
+ if (ext === ".cjs") {
743
+ const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/mokup.zAF8ClCC.cjs', document.baseURI).href)));
744
+ delete require$1.cache[file];
745
+ return require$1(file);
746
+ }
747
+ if (ext === ".js" || ext === ".mjs") {
748
+ return import(`${node_url.pathToFileURL(file).href}?t=${Date.now()}`);
749
+ }
750
+ if (ext === ".ts") {
751
+ const result = await esbuild.build({
752
+ entryPoints: [file],
753
+ bundle: true,
754
+ format: "esm",
755
+ platform: "node",
756
+ sourcemap: "inline",
757
+ target: "es2020",
758
+ write: false
759
+ });
760
+ const output = result.outputFiles[0];
761
+ const code = output?.text ?? "";
762
+ const dataUrl = `data:text/javascript;base64,${node_buffer.Buffer.from(code).toString(
763
+ "base64"
764
+ )}`;
765
+ return import(`${dataUrl}#${Date.now()}`);
766
+ }
767
+ return null;
768
+ }
769
+ async function loadModuleWithVite$1(server, file) {
770
+ const asDevServer = server;
771
+ if ("ssrLoadModule" in asDevServer) {
772
+ const moduleNode = asDevServer.moduleGraph.getModuleById(file);
773
+ if (moduleNode) {
774
+ asDevServer.moduleGraph.invalidateModule(moduleNode);
775
+ }
776
+ return asDevServer.ssrLoadModule(file);
777
+ }
778
+ return loadModule$1(file);
779
+ }
780
+ function getConfigFileCandidates(dir) {
781
+ return configExtensions.map((extension) => pathe.join(dir, `index.config${extension}`));
782
+ }
783
+ async function findConfigFile(dir, cache) {
784
+ const cached = cache.get(dir);
785
+ if (cached !== void 0) {
786
+ return cached;
787
+ }
788
+ for (const candidate of getConfigFileCandidates(dir)) {
789
+ try {
790
+ await node_fs.promises.stat(candidate);
791
+ cache.set(dir, candidate);
792
+ return candidate;
793
+ } catch {
794
+ continue;
795
+ }
796
+ }
797
+ cache.set(dir, null);
798
+ return null;
799
+ }
800
+ async function loadConfig(file, server) {
801
+ const mod = server ? await loadModuleWithVite$1(server, file) : await loadModule$1(file);
802
+ if (!mod) {
803
+ return null;
804
+ }
805
+ const value = mod?.default ?? mod;
806
+ if (!value || typeof value !== "object") {
807
+ return null;
808
+ }
809
+ return value;
810
+ }
811
+ function normalizeMiddlewares(value, source, logger) {
812
+ if (!value) {
813
+ return [];
814
+ }
815
+ const list = Array.isArray(value) ? value : [value];
816
+ const middlewares = [];
817
+ for (const [index, entry] of list.entries()) {
818
+ if (typeof entry !== "function") {
819
+ logger.warn(`Invalid middleware in ${source}`);
820
+ continue;
821
+ }
822
+ middlewares.push({ handle: entry, source, index });
823
+ }
824
+ return middlewares;
825
+ }
826
+ async function resolveDirectoryConfig(params) {
827
+ const { file, rootDir, server, logger, configCache, fileCache } = params;
828
+ const resolvedRoot = pathe.normalize(rootDir);
829
+ const resolvedFileDir = pathe.normalize(pathe.dirname(file));
830
+ const chain = [];
831
+ let current = resolvedFileDir;
832
+ while (true) {
833
+ chain.push(current);
834
+ if (current === resolvedRoot) {
835
+ break;
836
+ }
837
+ const parent = pathe.dirname(current);
838
+ if (parent === current) {
839
+ break;
840
+ }
841
+ current = parent;
842
+ }
843
+ chain.reverse();
844
+ const merged = { middlewares: [] };
845
+ for (const dir of chain) {
846
+ const configPath = await findConfigFile(dir, fileCache);
847
+ if (!configPath) {
848
+ continue;
849
+ }
850
+ let config = configCache.get(configPath);
851
+ if (config === void 0) {
852
+ config = await loadConfig(configPath, server);
853
+ configCache.set(configPath, config);
854
+ }
855
+ if (!config) {
856
+ logger.warn(`Invalid config in ${configPath}`);
857
+ continue;
858
+ }
859
+ if (config.headers) {
860
+ merged.headers = { ...merged.headers ?? {}, ...config.headers };
861
+ }
862
+ if (typeof config.status === "number") {
863
+ merged.status = config.status;
864
+ }
865
+ if (typeof config.delay === "number") {
866
+ merged.delay = config.delay;
867
+ }
868
+ if (typeof config.enabled === "boolean") {
869
+ merged.enabled = config.enabled;
870
+ }
871
+ const normalized = normalizeMiddlewares(config.middleware, configPath, logger);
872
+ if (normalized.length > 0) {
873
+ merged.middlewares.push(...normalized);
874
+ }
875
+ }
876
+ return merged;
877
+ }
878
+
879
+ async function walkDir(dir, rootDir, files) {
880
+ const entries = await node_fs.promises.readdir(dir, { withFileTypes: true });
881
+ for (const entry of entries) {
882
+ if (entry.name === "node_modules" || entry.name === ".git") {
883
+ continue;
884
+ }
885
+ const fullPath = pathe.join(dir, entry.name);
886
+ if (entry.isDirectory()) {
887
+ await walkDir(fullPath, rootDir, files);
888
+ continue;
889
+ }
890
+ if (entry.isFile()) {
891
+ files.push({ file: fullPath, rootDir });
892
+ }
893
+ }
894
+ }
895
+ async function exists(path) {
896
+ try {
897
+ await node_fs.promises.stat(path);
898
+ return true;
899
+ } catch {
900
+ return false;
901
+ }
902
+ }
903
+ async function collectFiles(dirs) {
904
+ const files = [];
905
+ for (const dir of dirs) {
906
+ if (!await exists(dir)) {
907
+ continue;
908
+ }
909
+ await walkDir(dir, dir, files);
910
+ }
911
+ return files;
912
+ }
913
+ function isSupportedFile(file) {
914
+ if (file.endsWith(".d.ts")) {
915
+ return false;
916
+ }
917
+ if (pathe.basename(file).startsWith("index.config.")) {
918
+ return false;
919
+ }
920
+ const ext = pathe.extname(file).toLowerCase();
921
+ return supportedExtensions.has(ext);
922
+ }
923
+
924
+ async function loadModule(file) {
925
+ const ext = pathe.extname(file).toLowerCase();
926
+ if (ext === ".cjs") {
927
+ const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('shared/mokup.zAF8ClCC.cjs', document.baseURI).href)));
928
+ delete require$1.cache[file];
929
+ return require$1(file);
930
+ }
931
+ if (ext === ".js" || ext === ".mjs") {
932
+ return import(`${node_url.pathToFileURL(file).href}?t=${Date.now()}`);
933
+ }
934
+ if (ext === ".ts") {
935
+ const result = await esbuild.build({
936
+ entryPoints: [file],
937
+ bundle: true,
938
+ format: "esm",
939
+ platform: "node",
940
+ sourcemap: "inline",
941
+ target: "es2020",
942
+ write: false
943
+ });
944
+ const output = result.outputFiles[0];
945
+ const code = output?.text ?? "";
946
+ const dataUrl = `data:text/javascript;base64,${node_buffer.Buffer.from(code).toString(
947
+ "base64"
948
+ )}`;
949
+ return import(`${dataUrl}#${Date.now()}`);
950
+ }
951
+ return null;
952
+ }
953
+ async function loadModuleWithVite(server, file) {
954
+ const asDevServer = server;
955
+ if ("ssrLoadModule" in asDevServer) {
956
+ const moduleNode = asDevServer.moduleGraph.getModuleById(file);
957
+ if (moduleNode) {
958
+ asDevServer.moduleGraph.invalidateModule(moduleNode);
959
+ }
960
+ return asDevServer.ssrLoadModule(file);
961
+ }
962
+ return loadModule(file);
963
+ }
964
+ async function readJsonFile(file, logger) {
965
+ try {
966
+ const content = await node_fs.promises.readFile(file, "utf8");
967
+ const errors = [];
968
+ const data = jsoncParser.parse(content, errors, {
969
+ allowTrailingComma: true,
970
+ disallowComments: false
971
+ });
972
+ if (errors.length > 0) {
973
+ logger.warn(`Invalid JSONC in ${file}`);
974
+ return void 0;
975
+ }
976
+ return data;
977
+ } catch (error) {
978
+ logger.warn(`Failed to read ${file}: ${String(error)}`);
979
+ return void 0;
980
+ }
981
+ }
982
+ async function loadRules(file, server, logger) {
983
+ const ext = pathe.extname(file).toLowerCase();
984
+ if (ext === ".json" || ext === ".jsonc") {
985
+ const json = await readJsonFile(file, logger);
986
+ if (typeof json === "undefined") {
987
+ return [];
988
+ }
989
+ return [
990
+ {
991
+ handler: json
992
+ }
993
+ ];
994
+ }
995
+ const mod = server ? await loadModuleWithVite(server, file) : await loadModule(file);
996
+ const value = mod?.default ?? mod;
997
+ if (!value) {
998
+ return [];
999
+ }
1000
+ if (Array.isArray(value)) {
1001
+ return value;
1002
+ }
1003
+ if (typeof value === "function") {
1004
+ return [
1005
+ {
1006
+ handler: value
1007
+ }
1008
+ ];
1009
+ }
1010
+ return [value];
1011
+ }
1012
+
1013
+ async function scanRoutes(params) {
1014
+ const routes = [];
1015
+ const seen = /* @__PURE__ */ new Set();
1016
+ const files = await collectFiles(params.dirs);
1017
+ const configCache = /* @__PURE__ */ new Map();
1018
+ const fileCache = /* @__PURE__ */ new Map();
1019
+ for (const fileInfo of files) {
1020
+ if (!isSupportedFile(fileInfo.file)) {
1021
+ continue;
1022
+ }
1023
+ if (!matchesFilter(fileInfo.file, params.include, params.exclude)) {
1024
+ continue;
1025
+ }
1026
+ const configParams = {
1027
+ file: fileInfo.file,
1028
+ rootDir: fileInfo.rootDir,
1029
+ logger: params.logger,
1030
+ configCache,
1031
+ fileCache
1032
+ };
1033
+ if (params.server) {
1034
+ configParams.server = params.server;
1035
+ }
1036
+ const config = await resolveDirectoryConfig(configParams);
1037
+ if (config.enabled === false) {
1038
+ continue;
1039
+ }
1040
+ const derived = deriveRouteFromFile(fileInfo.file, fileInfo.rootDir, params.logger);
1041
+ if (!derived) {
1042
+ continue;
1043
+ }
1044
+ const rules = await loadRules(fileInfo.file, params.server, params.logger);
1045
+ for (const [index, rule] of rules.entries()) {
1046
+ if (!rule || typeof rule !== "object") {
1047
+ continue;
1048
+ }
1049
+ const ruleValue = rule;
1050
+ const unsupportedKeys = ["response", "url", "method"].filter(
1051
+ (key2) => key2 in ruleValue
1052
+ );
1053
+ if (unsupportedKeys.length > 0) {
1054
+ params.logger.warn(
1055
+ `Skip mock with unsupported fields (${unsupportedKeys.join(", ")}): ${fileInfo.file}`
1056
+ );
1057
+ continue;
1058
+ }
1059
+ if (typeof rule.handler === "undefined") {
1060
+ params.logger.warn(`Skip mock without handler: ${fileInfo.file}`);
1061
+ continue;
1062
+ }
1063
+ const resolved = resolveRule({
1064
+ rule,
1065
+ derivedTemplate: derived.template,
1066
+ derivedMethod: derived.method,
1067
+ prefix: params.prefix,
1068
+ file: fileInfo.file,
1069
+ logger: params.logger
1070
+ });
1071
+ if (!resolved) {
1072
+ continue;
1073
+ }
1074
+ resolved.ruleIndex = index;
1075
+ if (config.headers) {
1076
+ resolved.headers = { ...config.headers, ...resolved.headers ?? {} };
1077
+ }
1078
+ if (typeof resolved.status === "undefined" && typeof config.status === "number") {
1079
+ resolved.status = config.status;
1080
+ }
1081
+ if (typeof resolved.delay === "undefined" && typeof config.delay === "number") {
1082
+ resolved.delay = config.delay;
1083
+ }
1084
+ if (config.middlewares.length > 0) {
1085
+ resolved.middlewares = config.middlewares;
1086
+ }
1087
+ const key = `${resolved.method} ${resolved.template}`;
1088
+ if (seen.has(key)) {
1089
+ params.logger.warn(`Duplicate mock route ${key} from ${fileInfo.file}`);
1090
+ }
1091
+ seen.add(key);
1092
+ routes.push(resolved);
1093
+ }
1094
+ }
1095
+ return sortRoutes(routes);
1096
+ }
1097
+
1098
+ const defaultSwPath = "/mokup-sw.js";
1099
+ const defaultSwScope = "/";
1100
+ function normalizeSwPath(path) {
1101
+ if (!path) {
1102
+ return defaultSwPath;
1103
+ }
1104
+ return path.startsWith("/") ? path : `/${path}`;
1105
+ }
1106
+ function normalizeSwScope(scope) {
1107
+ if (!scope) {
1108
+ return defaultSwScope;
1109
+ }
1110
+ return scope.startsWith("/") ? scope : `/${scope}`;
1111
+ }
1112
+ function normalizeBasePath(value) {
1113
+ if (!value) {
1114
+ return "/";
1115
+ }
1116
+ const normalized = value.startsWith("/") ? value : `/${value}`;
1117
+ if (normalized.length > 1 && normalized.endsWith("/")) {
1118
+ return normalized.slice(0, -1);
1119
+ }
1120
+ return normalized;
1121
+ }
1122
+ function resolveSwConfigFromEntries(entries, logger) {
1123
+ let path = defaultSwPath;
1124
+ let scope = defaultSwScope;
1125
+ let register = true;
1126
+ let unregister = false;
1127
+ const basePaths = [];
1128
+ let hasPath = false;
1129
+ let hasScope = false;
1130
+ let hasRegister = false;
1131
+ let hasUnregister = false;
1132
+ for (const entry of entries) {
1133
+ const config = entry.sw;
1134
+ if (config?.path) {
1135
+ const next = normalizeSwPath(config.path);
1136
+ if (!hasPath) {
1137
+ path = next;
1138
+ hasPath = true;
1139
+ } else if (path !== next) {
1140
+ logger.warn(`SW path "${next}" ignored; using "${path}".`);
1141
+ }
1142
+ }
1143
+ if (config?.scope) {
1144
+ const next = normalizeSwScope(config.scope);
1145
+ if (!hasScope) {
1146
+ scope = next;
1147
+ hasScope = true;
1148
+ } else if (scope !== next) {
1149
+ logger.warn(`SW scope "${next}" ignored; using "${scope}".`);
1150
+ }
1151
+ }
1152
+ if (typeof config?.register === "boolean") {
1153
+ if (!hasRegister) {
1154
+ register = config.register;
1155
+ hasRegister = true;
1156
+ } else if (register !== config.register) {
1157
+ logger.warn(
1158
+ `SW register="${String(config.register)}" ignored; using "${String(register)}".`
1159
+ );
1160
+ }
1161
+ }
1162
+ if (typeof config?.unregister === "boolean") {
1163
+ if (!hasUnregister) {
1164
+ unregister = config.unregister;
1165
+ hasUnregister = true;
1166
+ } else if (unregister !== config.unregister) {
1167
+ logger.warn(
1168
+ `SW unregister="${String(config.unregister)}" ignored; using "${String(unregister)}".`
1169
+ );
1170
+ }
1171
+ }
1172
+ if (typeof config?.basePath !== "undefined") {
1173
+ const values = Array.isArray(config.basePath) ? config.basePath : [config.basePath];
1174
+ for (const value of values) {
1175
+ basePaths.push(normalizeBasePath(value));
1176
+ }
1177
+ continue;
1178
+ }
1179
+ const normalizedPrefix = normalizePrefix(entry.prefix ?? "");
1180
+ if (normalizedPrefix) {
1181
+ basePaths.push(normalizedPrefix);
1182
+ }
1183
+ }
1184
+ return {
1185
+ path,
1186
+ scope,
1187
+ register,
1188
+ unregister,
1189
+ basePaths: Array.from(new Set(basePaths))
1190
+ };
1191
+ }
1192
+ function resolveSwConfig(options, logger) {
1193
+ const swEntries = options.filter((entry) => entry.mode === "sw");
1194
+ if (swEntries.length === 0) {
1195
+ return null;
1196
+ }
1197
+ return resolveSwConfigFromEntries(swEntries, logger);
1198
+ }
1199
+ function resolveSwUnregisterConfig(options, logger) {
1200
+ return resolveSwConfigFromEntries(options, logger);
1201
+ }
1202
+ function toViteImportPath(file, root) {
1203
+ const absolute = pathe.isAbsolute(file) ? file : pathe.resolve(root, file);
1204
+ const rel = pathe.relative(root, absolute);
1205
+ if (!rel.startsWith("..") && !pathe.isAbsolute(rel)) {
1206
+ return `/${toPosix(rel)}`;
1207
+ }
1208
+ return `/@fs/${toPosix(absolute)}`;
1209
+ }
1210
+ function shouldModuleize(handler) {
1211
+ if (typeof handler === "function") {
1212
+ return true;
1213
+ }
1214
+ if (typeof Response !== "undefined" && handler instanceof Response) {
1215
+ return true;
1216
+ }
1217
+ return false;
1218
+ }
1219
+ function toBinaryBody(handler) {
1220
+ if (handler instanceof ArrayBuffer) {
1221
+ return node_buffer.Buffer.from(new Uint8Array(handler)).toString("base64");
1222
+ }
1223
+ if (handler instanceof Uint8Array) {
1224
+ return node_buffer.Buffer.from(handler).toString("base64");
1225
+ }
1226
+ if (node_buffer.Buffer.isBuffer(handler)) {
1227
+ return handler.toString("base64");
1228
+ }
1229
+ return null;
1230
+ }
1231
+ function buildManifestResponse(route, moduleId) {
1232
+ if (moduleId) {
1233
+ const response = {
1234
+ type: "module",
1235
+ module: moduleId
1236
+ };
1237
+ if (typeof route.ruleIndex === "number") {
1238
+ response.ruleIndex = route.ruleIndex;
1239
+ }
1240
+ return response;
1241
+ }
1242
+ const handler = route.handler;
1243
+ if (typeof handler === "string") {
1244
+ return {
1245
+ type: "text",
1246
+ body: handler
1247
+ };
1248
+ }
1249
+ const binary = toBinaryBody(handler);
1250
+ if (binary) {
1251
+ return {
1252
+ type: "binary",
1253
+ body: binary,
1254
+ encoding: "base64"
1255
+ };
1256
+ }
1257
+ return {
1258
+ type: "json",
1259
+ body: handler
1260
+ };
1261
+ }
1262
+ function buildSwScript(params) {
1263
+ const { routes, root } = params;
1264
+ const runtimeImportPath = params.runtimeImportPath ?? "mokup/runtime";
1265
+ const basePaths = params.basePaths ?? [];
1266
+ const resolveModulePath = params.resolveModulePath ?? toViteImportPath;
1267
+ const ruleModules = /* @__PURE__ */ new Map();
1268
+ const middlewareModules = /* @__PURE__ */ new Map();
1269
+ const manifestRoutes = routes.map((route) => {
1270
+ const moduleId = shouldModuleize(route.handler) ? resolveModulePath(route.file, root) : null;
1271
+ if (moduleId) {
1272
+ ruleModules.set(moduleId, moduleId);
1273
+ }
1274
+ const middleware = route.middlewares?.map((entry) => {
1275
+ const modulePath = resolveModulePath(entry.source, root);
1276
+ middlewareModules.set(modulePath, modulePath);
1277
+ return {
1278
+ module: modulePath,
1279
+ ruleIndex: entry.index
1280
+ };
1281
+ });
1282
+ const response = buildManifestResponse(route, moduleId);
1283
+ const manifestRoute = {
1284
+ method: route.method,
1285
+ url: route.template,
1286
+ ...route.tokens ? { tokens: route.tokens } : {},
1287
+ ...route.score ? { score: route.score } : {},
1288
+ ...route.status ? { status: route.status } : {},
1289
+ ...route.headers ? { headers: route.headers } : {},
1290
+ ...route.delay ? { delay: route.delay } : {},
1291
+ ...middleware && middleware.length > 0 ? { middleware } : {},
1292
+ response
1293
+ };
1294
+ return manifestRoute;
1295
+ });
1296
+ const manifest = {
1297
+ version: 1,
1298
+ routes: manifestRoutes
1299
+ };
1300
+ const imports = [
1301
+ `import { createRuntimeApp, handle } from ${JSON.stringify(runtimeImportPath)}`
1302
+ ];
1303
+ const moduleEntries = [];
1304
+ let moduleIndex = 0;
1305
+ for (const id of ruleModules.keys()) {
1306
+ const name = `module${moduleIndex++}`;
1307
+ imports.push(`import * as ${name} from '${id}'`);
1308
+ moduleEntries.push({ id, name, kind: "rule" });
1309
+ }
1310
+ for (const id of middlewareModules.keys()) {
1311
+ const name = `module${moduleIndex++}`;
1312
+ imports.push(`import * as ${name} from '${id}'`);
1313
+ moduleEntries.push({ id, name, kind: "middleware" });
1314
+ }
1315
+ const lines = [];
1316
+ lines.push(...imports, "");
1317
+ lines.push(
1318
+ "const resolveModuleExport = (mod) => mod?.default ?? mod",
1319
+ "",
1320
+ "const toRuntimeRule = (value) => {",
1321
+ " if (typeof value === 'undefined') {",
1322
+ " return null",
1323
+ " }",
1324
+ " if (typeof value === 'function') {",
1325
+ " return { response: value }",
1326
+ " }",
1327
+ " if (value === null) {",
1328
+ " return { response: null }",
1329
+ " }",
1330
+ " if (typeof value === 'object') {",
1331
+ " if ('response' in value) {",
1332
+ " return value",
1333
+ " }",
1334
+ " if ('handler' in value) {",
1335
+ " const handlerRule = value",
1336
+ " return {",
1337
+ " response: handlerRule.handler,",
1338
+ " ...(typeof handlerRule.status === 'number' ? { status: handlerRule.status } : {}),",
1339
+ " ...(handlerRule.headers ? { headers: handlerRule.headers } : {}),",
1340
+ " ...(typeof handlerRule.delay === 'number' ? { delay: handlerRule.delay } : {}),",
1341
+ " }",
1342
+ " }",
1343
+ " return { response: value }",
1344
+ " }",
1345
+ " return { response: value }",
1346
+ "}",
1347
+ "",
1348
+ "const toRuntimeRules = (value) => {",
1349
+ " if (typeof value === 'undefined') {",
1350
+ " return []",
1351
+ " }",
1352
+ " if (Array.isArray(value)) {",
1353
+ " return value.map(toRuntimeRule).filter(Boolean)",
1354
+ " }",
1355
+ " const rule = toRuntimeRule(value)",
1356
+ " return rule ? [rule] : []",
1357
+ "}",
1358
+ ""
1359
+ );
1360
+ lines.push(
1361
+ `const manifest = ${JSON.stringify(manifest, null, 2)}`,
1362
+ ""
1363
+ );
1364
+ if (moduleEntries.length > 0) {
1365
+ lines.push("const moduleMap = {");
1366
+ for (const entry of moduleEntries) {
1367
+ if (entry.kind === "rule") {
1368
+ lines.push(
1369
+ ` ${JSON.stringify(entry.id)}: { default: toRuntimeRules(resolveModuleExport(${entry.name})) },`
1370
+ );
1371
+ continue;
1372
+ }
1373
+ lines.push(
1374
+ ` ${JSON.stringify(entry.id)}: ${entry.name},`
1375
+ );
1376
+ }
1377
+ lines.push("}", "");
1378
+ }
1379
+ const runtimeOptions = moduleEntries.length > 0 ? "{ manifest, moduleMap }" : "{ manifest }";
1380
+ lines.push(
1381
+ `const basePaths = ${JSON.stringify(basePaths)}`,
1382
+ "",
1383
+ "self.addEventListener('install', () => {",
1384
+ " self.skipWaiting()",
1385
+ "})",
1386
+ "",
1387
+ "self.addEventListener('activate', (event) => {",
1388
+ " event.waitUntil(self.clients.claim())",
1389
+ "})",
1390
+ "",
1391
+ "const shouldHandle = (request) => {",
1392
+ " if (!basePaths || basePaths.length === 0) {",
1393
+ " return true",
1394
+ " }",
1395
+ " const pathname = new URL(request.url).pathname",
1396
+ " return basePaths.some((basePath) => {",
1397
+ " if (basePath === '/') {",
1398
+ " return true",
1399
+ " }",
1400
+ " return pathname === basePath || pathname.startsWith(basePath + '/')",
1401
+ " })",
1402
+ "}",
1403
+ "",
1404
+ "const registerHandler = async () => {",
1405
+ ` const app = await createRuntimeApp(${runtimeOptions})`,
1406
+ " const handler = handle(app)",
1407
+ " self.addEventListener('fetch', (event) => {",
1408
+ " if (!shouldHandle(event.request)) {",
1409
+ " return",
1410
+ " }",
1411
+ " handler(event)",
1412
+ " })",
1413
+ "}",
1414
+ "",
1415
+ "registerHandler().catch((error) => {",
1416
+ " console.error('[mokup] Failed to build service worker app:', error)",
1417
+ "})",
1418
+ ""
1419
+ );
1420
+ return lines.join("\n");
1421
+ }
1422
+
1423
+ exports.buildSwScript = buildSwScript;
1424
+ exports.createDebouncer = createDebouncer;
1425
+ exports.createHonoApp = createHonoApp;
1426
+ exports.createLogger = createLogger;
1427
+ exports.createMiddleware = createMiddleware;
1428
+ exports.createPlaygroundMiddleware = createPlaygroundMiddleware;
1429
+ exports.isInDirs = isInDirs;
1430
+ exports.resolveDirs = resolveDirs;
1431
+ exports.resolvePlaygroundOptions = resolvePlaygroundOptions;
1432
+ exports.resolveSwConfig = resolveSwConfig;
1433
+ exports.resolveSwUnregisterConfig = resolveSwUnregisterConfig;
1434
+ exports.scanRoutes = scanRoutes;
1435
+ exports.sortRoutes = sortRoutes;
1436
+ exports.toPosix = toPosix;