@mokup/server 0.0.1 → 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.
- package/dist/index.cjs +1066 -0
- package/dist/index.d.cts +55 -1
- package/dist/index.d.mts +55 -1
- package/dist/index.d.ts +55 -1
- package/dist/index.mjs +1066 -2
- package/package.json +6 -2
package/dist/index.cjs
CHANGED
|
@@ -2,7 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
const runtime = require('@mokup/runtime');
|
|
4
4
|
const fetch = require('./shared/server.BdTl0qJd.cjs');
|
|
5
|
+
const node_process = require('node:process');
|
|
6
|
+
const hono = require('@mokup/shared/hono');
|
|
7
|
+
const pathe = require('@mokup/shared/pathe');
|
|
8
|
+
const node_fs = require('node:fs');
|
|
9
|
+
const node_module = require('node:module');
|
|
10
|
+
const node_buffer = require('node:buffer');
|
|
11
|
+
const node_url = require('node:url');
|
|
12
|
+
const esbuild = require('@mokup/shared/esbuild');
|
|
13
|
+
const jsoncParser = require('@mokup/shared/jsonc-parser');
|
|
5
14
|
|
|
15
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
6
16
|
function createConnectMiddleware(options) {
|
|
7
17
|
const runtime$1 = runtime.createRuntime(fetch.toRuntimeOptions(options));
|
|
8
18
|
const onNotFound = options.onNotFound ?? "next";
|
|
@@ -59,6 +69,1061 @@ function createFastifyPlugin(options) {
|
|
|
59
69
|
};
|
|
60
70
|
}
|
|
61
71
|
|
|
72
|
+
const methodSet = /* @__PURE__ */ new Set([
|
|
73
|
+
"GET",
|
|
74
|
+
"POST",
|
|
75
|
+
"PUT",
|
|
76
|
+
"PATCH",
|
|
77
|
+
"DELETE",
|
|
78
|
+
"OPTIONS",
|
|
79
|
+
"HEAD"
|
|
80
|
+
]);
|
|
81
|
+
const methodSuffixSet = new Set(
|
|
82
|
+
Array.from(methodSet, (method) => method.toLowerCase())
|
|
83
|
+
);
|
|
84
|
+
const supportedExtensions = /* @__PURE__ */ new Set([
|
|
85
|
+
".json",
|
|
86
|
+
".jsonc",
|
|
87
|
+
".ts",
|
|
88
|
+
".js",
|
|
89
|
+
".mjs",
|
|
90
|
+
".cjs"
|
|
91
|
+
]);
|
|
92
|
+
|
|
93
|
+
function normalizePrefix(prefix) {
|
|
94
|
+
if (!prefix) {
|
|
95
|
+
return "";
|
|
96
|
+
}
|
|
97
|
+
const normalized = prefix.startsWith("/") ? prefix : `/${prefix}`;
|
|
98
|
+
return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
|
|
99
|
+
}
|
|
100
|
+
function resolveDirs(dir, root) {
|
|
101
|
+
const raw = typeof dir === "function" ? dir(root) : dir;
|
|
102
|
+
const resolved = Array.isArray(raw) ? raw : raw ? [raw] : ["mock"];
|
|
103
|
+
const normalized = resolved.map(
|
|
104
|
+
(entry) => pathe.isAbsolute(entry) ? entry : pathe.resolve(root, entry)
|
|
105
|
+
);
|
|
106
|
+
return Array.from(new Set(normalized));
|
|
107
|
+
}
|
|
108
|
+
function createDebouncer(delayMs, fn) {
|
|
109
|
+
let timer = null;
|
|
110
|
+
return () => {
|
|
111
|
+
if (timer) {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
}
|
|
114
|
+
timer = setTimeout(() => {
|
|
115
|
+
timer = null;
|
|
116
|
+
fn();
|
|
117
|
+
}, delayMs);
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function toPosix(value) {
|
|
121
|
+
return value.replace(/\\/g, "/");
|
|
122
|
+
}
|
|
123
|
+
function isInDirs(file, dirs) {
|
|
124
|
+
const normalized = toPosix(file);
|
|
125
|
+
return dirs.some((dir) => {
|
|
126
|
+
const normalizedDir = toPosix(dir).replace(/\/$/, "");
|
|
127
|
+
return normalized === normalizedDir || normalized.startsWith(`${normalizedDir}/`);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
function testPatterns(patterns, value) {
|
|
131
|
+
const list = Array.isArray(patterns) ? patterns : [patterns];
|
|
132
|
+
return list.some((pattern) => pattern.test(value));
|
|
133
|
+
}
|
|
134
|
+
function matchesFilter(file, include, exclude) {
|
|
135
|
+
const normalized = toPosix(file);
|
|
136
|
+
if (exclude && testPatterns(exclude, normalized)) {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
if (include) {
|
|
140
|
+
return testPatterns(include, normalized);
|
|
141
|
+
}
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
function delay(ms) {
|
|
145
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function toHonoPath(route) {
|
|
149
|
+
if (!route.tokens || route.tokens.length === 0) {
|
|
150
|
+
return "/";
|
|
151
|
+
}
|
|
152
|
+
const segments = route.tokens.map((token) => {
|
|
153
|
+
if (token.type === "static") {
|
|
154
|
+
return token.value;
|
|
155
|
+
}
|
|
156
|
+
if (token.type === "param") {
|
|
157
|
+
return `:${token.name}`;
|
|
158
|
+
}
|
|
159
|
+
if (token.type === "catchall") {
|
|
160
|
+
return `:${token.name}{.+}`;
|
|
161
|
+
}
|
|
162
|
+
return `:${token.name}{.+}?`;
|
|
163
|
+
});
|
|
164
|
+
return `/${segments.join("/")}`;
|
|
165
|
+
}
|
|
166
|
+
function isValidStatus(status) {
|
|
167
|
+
return typeof status === "number" && Number.isFinite(status) && status >= 200 && status <= 599;
|
|
168
|
+
}
|
|
169
|
+
function resolveStatus(routeStatus, responseStatus) {
|
|
170
|
+
if (isValidStatus(routeStatus)) {
|
|
171
|
+
return routeStatus;
|
|
172
|
+
}
|
|
173
|
+
if (isValidStatus(responseStatus)) {
|
|
174
|
+
return responseStatus;
|
|
175
|
+
}
|
|
176
|
+
return 200;
|
|
177
|
+
}
|
|
178
|
+
function applyRouteOverrides(response, route) {
|
|
179
|
+
const headers = new Headers(response.headers);
|
|
180
|
+
const hasHeaders = !!route.headers && Object.keys(route.headers).length > 0;
|
|
181
|
+
if (route.headers) {
|
|
182
|
+
for (const [key, value] of Object.entries(route.headers)) {
|
|
183
|
+
headers.set(key, value);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
const status = resolveStatus(route.status, response.status);
|
|
187
|
+
if (status === response.status && !hasHeaders) {
|
|
188
|
+
return response;
|
|
189
|
+
}
|
|
190
|
+
return new Response(response.body, { status, headers });
|
|
191
|
+
}
|
|
192
|
+
function normalizeHandlerValue(c, value) {
|
|
193
|
+
if (value instanceof Response) {
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
if (typeof value === "undefined") {
|
|
197
|
+
const response = c.body(null);
|
|
198
|
+
if (response.status === 200) {
|
|
199
|
+
return new Response(response.body, {
|
|
200
|
+
status: 204,
|
|
201
|
+
headers: response.headers
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return response;
|
|
205
|
+
}
|
|
206
|
+
if (typeof value === "string") {
|
|
207
|
+
return c.text(value);
|
|
208
|
+
}
|
|
209
|
+
if (value instanceof Uint8Array || value instanceof ArrayBuffer) {
|
|
210
|
+
if (!c.res.headers.get("content-type")) {
|
|
211
|
+
c.header("content-type", "application/octet-stream");
|
|
212
|
+
}
|
|
213
|
+
const data = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value);
|
|
214
|
+
return c.body(data);
|
|
215
|
+
}
|
|
216
|
+
return c.json(value);
|
|
217
|
+
}
|
|
218
|
+
function createRouteHandler(route) {
|
|
219
|
+
return async (c) => {
|
|
220
|
+
const value = typeof route.handler === "function" ? await route.handler(c) : route.handler;
|
|
221
|
+
return normalizeHandlerValue(c, value);
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
function createFinalizeMiddleware(route) {
|
|
225
|
+
return async (c, next) => {
|
|
226
|
+
const response = await next();
|
|
227
|
+
const resolved = response ?? c.res;
|
|
228
|
+
if (route.delay && route.delay > 0) {
|
|
229
|
+
await delay(route.delay);
|
|
230
|
+
}
|
|
231
|
+
return applyRouteOverrides(resolved, route);
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
function wrapMiddleware(handler) {
|
|
235
|
+
return async (c, next) => {
|
|
236
|
+
const response = await handler(c, next);
|
|
237
|
+
return response ?? c.res;
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function createHonoApp(routes) {
|
|
241
|
+
const app = new hono.Hono({ router: new hono.PatternRouter(), strict: false });
|
|
242
|
+
for (const route of routes) {
|
|
243
|
+
const middlewares = route.middlewares?.map((entry) => wrapMiddleware(entry.handle)) ?? [];
|
|
244
|
+
app.on(
|
|
245
|
+
route.method,
|
|
246
|
+
toHonoPath(route),
|
|
247
|
+
createFinalizeMiddleware(route),
|
|
248
|
+
...middlewares,
|
|
249
|
+
createRouteHandler(route)
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
return app;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function createLogger(enabled) {
|
|
256
|
+
return {
|
|
257
|
+
info: (...args) => {
|
|
258
|
+
if (enabled) {
|
|
259
|
+
console.info("[mokup]", ...args);
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
warn: (...args) => {
|
|
263
|
+
if (enabled) {
|
|
264
|
+
console.warn("[mokup]", ...args);
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
error: (...args) => {
|
|
268
|
+
if (enabled) {
|
|
269
|
+
console.error("[mokup]", ...args);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const mimeTypes = {
|
|
276
|
+
".html": "text/html; charset=utf-8",
|
|
277
|
+
".css": "text/css; charset=utf-8",
|
|
278
|
+
".js": "text/javascript; charset=utf-8",
|
|
279
|
+
".map": "application/json; charset=utf-8",
|
|
280
|
+
".json": "application/json; charset=utf-8",
|
|
281
|
+
".svg": "image/svg+xml",
|
|
282
|
+
".png": "image/png",
|
|
283
|
+
".jpg": "image/jpeg",
|
|
284
|
+
".jpeg": "image/jpeg",
|
|
285
|
+
".ico": "image/x-icon"
|
|
286
|
+
};
|
|
287
|
+
function normalizePlaygroundPath(value) {
|
|
288
|
+
if (!value) {
|
|
289
|
+
return "/_mokup";
|
|
290
|
+
}
|
|
291
|
+
const normalized = value.startsWith("/") ? value : `/${value}`;
|
|
292
|
+
return normalized.length > 1 && normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
|
|
293
|
+
}
|
|
294
|
+
function resolvePlaygroundOptions(playground) {
|
|
295
|
+
if (playground === false) {
|
|
296
|
+
return { enabled: false, path: "/_mokup" };
|
|
297
|
+
}
|
|
298
|
+
if (playground && typeof playground === "object") {
|
|
299
|
+
return {
|
|
300
|
+
enabled: playground.enabled !== false,
|
|
301
|
+
path: normalizePlaygroundPath(playground.path)
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
return { enabled: true, path: "/_mokup" };
|
|
305
|
+
}
|
|
306
|
+
function resolvePlaygroundDist() {
|
|
307
|
+
const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
|
|
308
|
+
const pkgPath = require$1.resolve("@mokup/playground/package.json");
|
|
309
|
+
return pathe.join(pkgPath, "..", "dist");
|
|
310
|
+
}
|
|
311
|
+
function toPosixPath(value) {
|
|
312
|
+
return value.replace(/\\/g, "/");
|
|
313
|
+
}
|
|
314
|
+
function normalizePath(value) {
|
|
315
|
+
return toPosixPath(pathe.normalize(value));
|
|
316
|
+
}
|
|
317
|
+
function isAncestor(parent, child) {
|
|
318
|
+
const normalizedParent = normalizePath(parent).replace(/\/$/, "");
|
|
319
|
+
const normalizedChild = normalizePath(child);
|
|
320
|
+
return normalizedChild === normalizedParent || normalizedChild.startsWith(`${normalizedParent}/`);
|
|
321
|
+
}
|
|
322
|
+
function resolveGroupRoot(dirs, serverRoot) {
|
|
323
|
+
if (!dirs || dirs.length === 0) {
|
|
324
|
+
return serverRoot ?? node_process.cwd();
|
|
325
|
+
}
|
|
326
|
+
if (serverRoot) {
|
|
327
|
+
const normalizedRoot = normalizePath(serverRoot);
|
|
328
|
+
const canUseRoot = dirs.every((dir) => isAncestor(normalizedRoot, dir));
|
|
329
|
+
if (canUseRoot) {
|
|
330
|
+
return normalizedRoot;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
if (dirs.length === 1) {
|
|
334
|
+
return normalizePath(pathe.dirname(dirs[0]));
|
|
335
|
+
}
|
|
336
|
+
let common = normalizePath(dirs[0]);
|
|
337
|
+
for (const dir of dirs.slice(1)) {
|
|
338
|
+
const normalizedDir = normalizePath(dir);
|
|
339
|
+
while (common && !isAncestor(common, normalizedDir)) {
|
|
340
|
+
const parent = normalizePath(pathe.dirname(common));
|
|
341
|
+
if (parent === common) {
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
common = parent;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (!common || common === "/") {
|
|
348
|
+
return serverRoot ?? node_process.cwd();
|
|
349
|
+
}
|
|
350
|
+
return common;
|
|
351
|
+
}
|
|
352
|
+
function formatRouteFile(file, root) {
|
|
353
|
+
if (!root) {
|
|
354
|
+
return toPosixPath(file);
|
|
355
|
+
}
|
|
356
|
+
const rel = toPosixPath(pathe.relative(root, file));
|
|
357
|
+
if (!rel || rel.startsWith("..")) {
|
|
358
|
+
return toPosixPath(file);
|
|
359
|
+
}
|
|
360
|
+
return rel;
|
|
361
|
+
}
|
|
362
|
+
function resolveGroups(dirs, root) {
|
|
363
|
+
const groups = [];
|
|
364
|
+
const seen = /* @__PURE__ */ new Set();
|
|
365
|
+
for (const dir of dirs) {
|
|
366
|
+
const normalized = normalizePath(dir);
|
|
367
|
+
if (seen.has(normalized)) {
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
seen.add(normalized);
|
|
371
|
+
const rel = toPosixPath(pathe.relative(root, normalized));
|
|
372
|
+
const label = rel && !rel.startsWith("..") ? rel : normalized;
|
|
373
|
+
groups.push({
|
|
374
|
+
key: normalized,
|
|
375
|
+
label,
|
|
376
|
+
path: normalized
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
return groups;
|
|
380
|
+
}
|
|
381
|
+
function resolveRouteGroup(routeFile, groups) {
|
|
382
|
+
if (groups.length === 0) {
|
|
383
|
+
return void 0;
|
|
384
|
+
}
|
|
385
|
+
const normalizedFile = toPosixPath(pathe.normalize(routeFile));
|
|
386
|
+
let matched;
|
|
387
|
+
for (const group of groups) {
|
|
388
|
+
if (normalizedFile === group.path || normalizedFile.startsWith(`${group.path}/`)) {
|
|
389
|
+
if (!matched || group.path.length > matched.path.length) {
|
|
390
|
+
matched = group;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return matched;
|
|
395
|
+
}
|
|
396
|
+
function toPlaygroundRoute(route, root, groups) {
|
|
397
|
+
const matchedGroup = resolveRouteGroup(route.file, groups);
|
|
398
|
+
const middlewareSources = route.middlewares?.map((entry) => formatRouteFile(entry.source, root));
|
|
399
|
+
return {
|
|
400
|
+
method: route.method,
|
|
401
|
+
url: route.template,
|
|
402
|
+
file: formatRouteFile(route.file, root),
|
|
403
|
+
type: typeof route.handler === "function" ? "handler" : "static",
|
|
404
|
+
status: route.status,
|
|
405
|
+
delay: route.delay,
|
|
406
|
+
middlewareCount: middlewareSources?.length ?? 0,
|
|
407
|
+
middlewares: middlewareSources,
|
|
408
|
+
groupKey: matchedGroup?.key,
|
|
409
|
+
group: matchedGroup?.label
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
function registerPlaygroundRoutes(params) {
|
|
413
|
+
if (!params.config.enabled) {
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const playgroundPath = normalizePlaygroundPath(params.config.path);
|
|
417
|
+
const distDir = resolvePlaygroundDist();
|
|
418
|
+
const indexPath = pathe.join(distDir, "index.html");
|
|
419
|
+
const serveIndex = async () => {
|
|
420
|
+
try {
|
|
421
|
+
const html = await node_fs.promises.readFile(indexPath, "utf8");
|
|
422
|
+
const contentType = mimeTypes[".html"] ?? "text/html; charset=utf-8";
|
|
423
|
+
return new Response(html, { headers: { "Content-Type": contentType } });
|
|
424
|
+
} catch (error) {
|
|
425
|
+
params.logger.error("Failed to load playground index:", error);
|
|
426
|
+
return new Response("Playground is not available.", { status: 500 });
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
params.app.get(playgroundPath, (c) => c.redirect(`${playgroundPath}/`));
|
|
430
|
+
params.app.get(`${playgroundPath}/`, () => serveIndex());
|
|
431
|
+
params.app.get(`${playgroundPath}/index.html`, () => serveIndex());
|
|
432
|
+
params.app.get(`${playgroundPath}/routes`, (c) => {
|
|
433
|
+
const baseRoot = resolveGroupRoot(params.dirs, params.root);
|
|
434
|
+
const groups = resolveGroups(params.dirs, baseRoot);
|
|
435
|
+
return c.json({
|
|
436
|
+
basePath: playgroundPath,
|
|
437
|
+
root: baseRoot,
|
|
438
|
+
count: params.routes.length,
|
|
439
|
+
groups: groups.map((group) => ({ key: group.key, label: group.label })),
|
|
440
|
+
routes: params.routes.map((route) => toPlaygroundRoute(route, baseRoot, groups))
|
|
441
|
+
});
|
|
442
|
+
});
|
|
443
|
+
params.app.get(`${playgroundPath}/*`, async (c) => {
|
|
444
|
+
const pathname = c.req.path;
|
|
445
|
+
const relPath = pathname.slice(playgroundPath.length).replace(/^\/+/, "");
|
|
446
|
+
if (!relPath || relPath === "/") {
|
|
447
|
+
return serveIndex();
|
|
448
|
+
}
|
|
449
|
+
if (relPath.includes("..")) {
|
|
450
|
+
return new Response("Invalid path.", { status: 400 });
|
|
451
|
+
}
|
|
452
|
+
const normalizedPath = pathe.normalize(relPath);
|
|
453
|
+
const filePath = pathe.join(distDir, normalizedPath);
|
|
454
|
+
try {
|
|
455
|
+
const content = await node_fs.promises.readFile(filePath);
|
|
456
|
+
const ext = pathe.extname(filePath);
|
|
457
|
+
const contentType = mimeTypes[ext] ?? "application/octet-stream";
|
|
458
|
+
return new Response(content, { headers: { "Content-Type": contentType } });
|
|
459
|
+
} catch {
|
|
460
|
+
return c.notFound();
|
|
461
|
+
}
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const jsonExtensions = /* @__PURE__ */ new Set([".json", ".jsonc"]);
|
|
466
|
+
function resolveTemplate(template, prefix) {
|
|
467
|
+
const normalized = template.startsWith("/") ? template : `/${template}`;
|
|
468
|
+
if (!prefix) {
|
|
469
|
+
return normalized;
|
|
470
|
+
}
|
|
471
|
+
const normalizedPrefix = normalizePrefix(prefix);
|
|
472
|
+
if (!normalizedPrefix) {
|
|
473
|
+
return normalized;
|
|
474
|
+
}
|
|
475
|
+
if (normalized === normalizedPrefix || normalized.startsWith(`${normalizedPrefix}/`)) {
|
|
476
|
+
return normalized;
|
|
477
|
+
}
|
|
478
|
+
if (normalized === "/") {
|
|
479
|
+
return `${normalizedPrefix}/`;
|
|
480
|
+
}
|
|
481
|
+
return `${normalizedPrefix}${normalized}`;
|
|
482
|
+
}
|
|
483
|
+
function stripMethodSuffix(base) {
|
|
484
|
+
const segments = base.split(".");
|
|
485
|
+
const last = segments.at(-1);
|
|
486
|
+
if (last && methodSuffixSet.has(last.toLowerCase())) {
|
|
487
|
+
segments.pop();
|
|
488
|
+
return {
|
|
489
|
+
name: segments.join("."),
|
|
490
|
+
method: last.toUpperCase()
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
return {
|
|
494
|
+
name: base,
|
|
495
|
+
method: void 0
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function deriveRouteFromFile(file, rootDir, logger) {
|
|
499
|
+
const rel = toPosix(pathe.relative(rootDir, file));
|
|
500
|
+
const ext = pathe.extname(rel);
|
|
501
|
+
const withoutExt = rel.slice(0, rel.length - ext.length);
|
|
502
|
+
const dir = pathe.dirname(withoutExt);
|
|
503
|
+
const base = pathe.basename(withoutExt);
|
|
504
|
+
const { name, method } = stripMethodSuffix(base);
|
|
505
|
+
const resolvedMethod = method ?? (jsonExtensions.has(ext) ? "GET" : void 0);
|
|
506
|
+
if (!resolvedMethod) {
|
|
507
|
+
logger.warn(`Skip mock without method suffix: ${file}`);
|
|
508
|
+
return null;
|
|
509
|
+
}
|
|
510
|
+
if (!name) {
|
|
511
|
+
logger.warn(`Skip mock with empty route name: ${file}`);
|
|
512
|
+
return null;
|
|
513
|
+
}
|
|
514
|
+
const joined = dir === "." ? name : pathe.join(dir, name);
|
|
515
|
+
const segments = toPosix(joined).split("/");
|
|
516
|
+
if (segments.at(-1) === "index") {
|
|
517
|
+
segments.pop();
|
|
518
|
+
}
|
|
519
|
+
const template = segments.length === 0 ? "/" : `/${segments.join("/")}`;
|
|
520
|
+
const parsed = runtime.parseRouteTemplate(template);
|
|
521
|
+
if (parsed.errors.length > 0) {
|
|
522
|
+
for (const error of parsed.errors) {
|
|
523
|
+
logger.warn(`${error} in ${file}`);
|
|
524
|
+
}
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
for (const warning of parsed.warnings) {
|
|
528
|
+
logger.warn(`${warning} in ${file}`);
|
|
529
|
+
}
|
|
530
|
+
return {
|
|
531
|
+
template: parsed.template,
|
|
532
|
+
method: resolvedMethod,
|
|
533
|
+
tokens: parsed.tokens,
|
|
534
|
+
score: parsed.score
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
function resolveRule(params) {
|
|
538
|
+
const method = params.derivedMethod;
|
|
539
|
+
if (!method) {
|
|
540
|
+
params.logger.warn(`Skip mock without method suffix: ${params.file}`);
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
const template = resolveTemplate(params.derivedTemplate, params.prefix);
|
|
544
|
+
const parsed = runtime.parseRouteTemplate(template);
|
|
545
|
+
if (parsed.errors.length > 0) {
|
|
546
|
+
for (const error of parsed.errors) {
|
|
547
|
+
params.logger.warn(`${error} in ${params.file}`);
|
|
548
|
+
}
|
|
549
|
+
return null;
|
|
550
|
+
}
|
|
551
|
+
for (const warning of parsed.warnings) {
|
|
552
|
+
params.logger.warn(`${warning} in ${params.file}`);
|
|
553
|
+
}
|
|
554
|
+
const route = {
|
|
555
|
+
file: params.file,
|
|
556
|
+
template: parsed.template,
|
|
557
|
+
method,
|
|
558
|
+
tokens: parsed.tokens,
|
|
559
|
+
score: parsed.score,
|
|
560
|
+
handler: params.rule.handler
|
|
561
|
+
};
|
|
562
|
+
if (typeof params.rule.status === "number") {
|
|
563
|
+
route.status = params.rule.status;
|
|
564
|
+
}
|
|
565
|
+
if (params.rule.headers) {
|
|
566
|
+
route.headers = params.rule.headers;
|
|
567
|
+
}
|
|
568
|
+
if (typeof params.rule.delay === "number") {
|
|
569
|
+
route.delay = params.rule.delay;
|
|
570
|
+
}
|
|
571
|
+
return route;
|
|
572
|
+
}
|
|
573
|
+
function sortRoutes(routes) {
|
|
574
|
+
return routes.sort((a, b) => {
|
|
575
|
+
if (a.method !== b.method) {
|
|
576
|
+
return a.method.localeCompare(b.method);
|
|
577
|
+
}
|
|
578
|
+
const scoreCompare = runtime.compareRouteScore(a.score, b.score);
|
|
579
|
+
if (scoreCompare !== 0) {
|
|
580
|
+
return scoreCompare;
|
|
581
|
+
}
|
|
582
|
+
return a.template.localeCompare(b.template);
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const configExtensions = [".ts", ".js", ".mjs", ".cjs"];
|
|
587
|
+
async function loadModule$1(file) {
|
|
588
|
+
const ext = configExtensions.find((extension) => file.endsWith(extension));
|
|
589
|
+
if (ext === ".cjs") {
|
|
590
|
+
const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
|
|
591
|
+
delete require$1.cache[file];
|
|
592
|
+
return require$1(file);
|
|
593
|
+
}
|
|
594
|
+
if (ext === ".js" || ext === ".mjs") {
|
|
595
|
+
return import(`${node_url.pathToFileURL(file).href}?t=${Date.now()}`);
|
|
596
|
+
}
|
|
597
|
+
if (ext === ".ts") {
|
|
598
|
+
const result = await esbuild.build({
|
|
599
|
+
entryPoints: [file],
|
|
600
|
+
bundle: true,
|
|
601
|
+
format: "esm",
|
|
602
|
+
platform: "node",
|
|
603
|
+
sourcemap: "inline",
|
|
604
|
+
target: "es2020",
|
|
605
|
+
write: false
|
|
606
|
+
});
|
|
607
|
+
const output = result.outputFiles[0];
|
|
608
|
+
const code = output?.text ?? "";
|
|
609
|
+
const dataUrl = `data:text/javascript;base64,${node_buffer.Buffer.from(code).toString(
|
|
610
|
+
"base64"
|
|
611
|
+
)}`;
|
|
612
|
+
return import(`${dataUrl}#${Date.now()}`);
|
|
613
|
+
}
|
|
614
|
+
return null;
|
|
615
|
+
}
|
|
616
|
+
function getConfigFileCandidates(dir) {
|
|
617
|
+
return configExtensions.map((extension) => pathe.join(dir, `index.config${extension}`));
|
|
618
|
+
}
|
|
619
|
+
async function findConfigFile(dir, cache) {
|
|
620
|
+
const cached = cache.get(dir);
|
|
621
|
+
if (cached !== void 0) {
|
|
622
|
+
return cached;
|
|
623
|
+
}
|
|
624
|
+
for (const candidate of getConfigFileCandidates(dir)) {
|
|
625
|
+
try {
|
|
626
|
+
await node_fs.promises.stat(candidate);
|
|
627
|
+
cache.set(dir, candidate);
|
|
628
|
+
return candidate;
|
|
629
|
+
} catch {
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
cache.set(dir, null);
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
async function loadConfig(file) {
|
|
637
|
+
const mod = await loadModule$1(file);
|
|
638
|
+
if (!mod) {
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
641
|
+
const value = mod?.default ?? mod;
|
|
642
|
+
if (!value || typeof value !== "object") {
|
|
643
|
+
return null;
|
|
644
|
+
}
|
|
645
|
+
return value;
|
|
646
|
+
}
|
|
647
|
+
function normalizeMiddlewares(value, source, logger) {
|
|
648
|
+
if (!value) {
|
|
649
|
+
return [];
|
|
650
|
+
}
|
|
651
|
+
const list = Array.isArray(value) ? value : [value];
|
|
652
|
+
const middlewares = [];
|
|
653
|
+
for (const [index, entry] of list.entries()) {
|
|
654
|
+
if (typeof entry !== "function") {
|
|
655
|
+
logger.warn(`Invalid middleware in ${source}`);
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
middlewares.push({ handle: entry, source, index });
|
|
659
|
+
}
|
|
660
|
+
return middlewares;
|
|
661
|
+
}
|
|
662
|
+
async function resolveDirectoryConfig(params) {
|
|
663
|
+
const { file, rootDir, logger, configCache, fileCache } = params;
|
|
664
|
+
const resolvedRoot = pathe.normalize(rootDir);
|
|
665
|
+
const resolvedFileDir = pathe.normalize(pathe.dirname(file));
|
|
666
|
+
const chain = [];
|
|
667
|
+
let current = resolvedFileDir;
|
|
668
|
+
while (true) {
|
|
669
|
+
chain.push(current);
|
|
670
|
+
if (current === resolvedRoot) {
|
|
671
|
+
break;
|
|
672
|
+
}
|
|
673
|
+
const parent = pathe.dirname(current);
|
|
674
|
+
if (parent === current) {
|
|
675
|
+
break;
|
|
676
|
+
}
|
|
677
|
+
current = parent;
|
|
678
|
+
}
|
|
679
|
+
chain.reverse();
|
|
680
|
+
const merged = { middlewares: [] };
|
|
681
|
+
for (const dir of chain) {
|
|
682
|
+
const configPath = await findConfigFile(dir, fileCache);
|
|
683
|
+
if (!configPath) {
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
let config = configCache.get(configPath);
|
|
687
|
+
if (config === void 0) {
|
|
688
|
+
config = await loadConfig(configPath);
|
|
689
|
+
configCache.set(configPath, config);
|
|
690
|
+
}
|
|
691
|
+
if (!config) {
|
|
692
|
+
logger.warn(`Invalid config in ${configPath}`);
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
if (config.headers) {
|
|
696
|
+
merged.headers = { ...merged.headers ?? {}, ...config.headers };
|
|
697
|
+
}
|
|
698
|
+
if (typeof config.status === "number") {
|
|
699
|
+
merged.status = config.status;
|
|
700
|
+
}
|
|
701
|
+
if (typeof config.delay === "number") {
|
|
702
|
+
merged.delay = config.delay;
|
|
703
|
+
}
|
|
704
|
+
if (typeof config.enabled === "boolean") {
|
|
705
|
+
merged.enabled = config.enabled;
|
|
706
|
+
}
|
|
707
|
+
const normalized = normalizeMiddlewares(config.middleware, configPath, logger);
|
|
708
|
+
if (normalized.length > 0) {
|
|
709
|
+
merged.middlewares.push(...normalized);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return merged;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
async function walkDir(dir, rootDir, files) {
|
|
716
|
+
const entries = await node_fs.promises.readdir(dir, { withFileTypes: true });
|
|
717
|
+
for (const entry of entries) {
|
|
718
|
+
if (entry.name === "node_modules" || entry.name === ".git") {
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
const fullPath = pathe.join(dir, entry.name);
|
|
722
|
+
if (entry.isDirectory()) {
|
|
723
|
+
await walkDir(fullPath, rootDir, files);
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
if (entry.isFile()) {
|
|
727
|
+
files.push({ file: fullPath, rootDir });
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
async function exists(path) {
|
|
732
|
+
try {
|
|
733
|
+
await node_fs.promises.stat(path);
|
|
734
|
+
return true;
|
|
735
|
+
} catch {
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
async function collectFiles(dirs) {
|
|
740
|
+
const files = [];
|
|
741
|
+
for (const dir of dirs) {
|
|
742
|
+
if (!await exists(dir)) {
|
|
743
|
+
continue;
|
|
744
|
+
}
|
|
745
|
+
await walkDir(dir, dir, files);
|
|
746
|
+
}
|
|
747
|
+
return files;
|
|
748
|
+
}
|
|
749
|
+
function isSupportedFile(file) {
|
|
750
|
+
if (file.endsWith(".d.ts")) {
|
|
751
|
+
return false;
|
|
752
|
+
}
|
|
753
|
+
if (pathe.basename(file).startsWith("index.config.")) {
|
|
754
|
+
return false;
|
|
755
|
+
}
|
|
756
|
+
const ext = pathe.extname(file).toLowerCase();
|
|
757
|
+
return supportedExtensions.has(ext);
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
async function loadModule(file) {
|
|
761
|
+
const ext = pathe.extname(file).toLowerCase();
|
|
762
|
+
if (ext === ".cjs") {
|
|
763
|
+
const require$1 = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
|
|
764
|
+
delete require$1.cache[file];
|
|
765
|
+
return require$1(file);
|
|
766
|
+
}
|
|
767
|
+
if (ext === ".js" || ext === ".mjs") {
|
|
768
|
+
return import(`${node_url.pathToFileURL(file).href}?t=${Date.now()}`);
|
|
769
|
+
}
|
|
770
|
+
if (ext === ".ts") {
|
|
771
|
+
const result = await esbuild.build({
|
|
772
|
+
entryPoints: [file],
|
|
773
|
+
bundle: true,
|
|
774
|
+
format: "esm",
|
|
775
|
+
platform: "node",
|
|
776
|
+
sourcemap: "inline",
|
|
777
|
+
target: "es2020",
|
|
778
|
+
write: false
|
|
779
|
+
});
|
|
780
|
+
const output = result.outputFiles[0];
|
|
781
|
+
const code = output?.text ?? "";
|
|
782
|
+
const dataUrl = `data:text/javascript;base64,${node_buffer.Buffer.from(code).toString(
|
|
783
|
+
"base64"
|
|
784
|
+
)}`;
|
|
785
|
+
return import(`${dataUrl}#${Date.now()}`);
|
|
786
|
+
}
|
|
787
|
+
return null;
|
|
788
|
+
}
|
|
789
|
+
async function readJsonFile(file, logger) {
|
|
790
|
+
try {
|
|
791
|
+
const content = await node_fs.promises.readFile(file, "utf8");
|
|
792
|
+
const errors = [];
|
|
793
|
+
const data = jsoncParser.parse(content, errors, {
|
|
794
|
+
allowTrailingComma: true,
|
|
795
|
+
disallowComments: false
|
|
796
|
+
});
|
|
797
|
+
if (errors.length > 0) {
|
|
798
|
+
logger.warn(`Invalid JSONC in ${file}`);
|
|
799
|
+
return void 0;
|
|
800
|
+
}
|
|
801
|
+
return data;
|
|
802
|
+
} catch (error) {
|
|
803
|
+
logger.warn(`Failed to read ${file}: ${String(error)}`);
|
|
804
|
+
return void 0;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
async function loadRules(file, logger) {
|
|
808
|
+
const ext = pathe.extname(file).toLowerCase();
|
|
809
|
+
if (ext === ".json" || ext === ".jsonc") {
|
|
810
|
+
const json = await readJsonFile(file, logger);
|
|
811
|
+
if (typeof json === "undefined") {
|
|
812
|
+
return [];
|
|
813
|
+
}
|
|
814
|
+
return [
|
|
815
|
+
{
|
|
816
|
+
handler: json
|
|
817
|
+
}
|
|
818
|
+
];
|
|
819
|
+
}
|
|
820
|
+
const mod = await loadModule(file);
|
|
821
|
+
const value = mod?.default ?? mod;
|
|
822
|
+
if (!value) {
|
|
823
|
+
return [];
|
|
824
|
+
}
|
|
825
|
+
if (Array.isArray(value)) {
|
|
826
|
+
return value;
|
|
827
|
+
}
|
|
828
|
+
if (typeof value === "function") {
|
|
829
|
+
return [
|
|
830
|
+
{
|
|
831
|
+
handler: value
|
|
832
|
+
}
|
|
833
|
+
];
|
|
834
|
+
}
|
|
835
|
+
return [value];
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
async function scanRoutes(params) {
|
|
839
|
+
const routes = [];
|
|
840
|
+
const seen = /* @__PURE__ */ new Set();
|
|
841
|
+
const files = await collectFiles(params.dirs);
|
|
842
|
+
const configCache = /* @__PURE__ */ new Map();
|
|
843
|
+
const fileCache = /* @__PURE__ */ new Map();
|
|
844
|
+
for (const fileInfo of files) {
|
|
845
|
+
if (!isSupportedFile(fileInfo.file)) {
|
|
846
|
+
continue;
|
|
847
|
+
}
|
|
848
|
+
if (!matchesFilter(fileInfo.file, params.include, params.exclude)) {
|
|
849
|
+
continue;
|
|
850
|
+
}
|
|
851
|
+
const config = await resolveDirectoryConfig({
|
|
852
|
+
file: fileInfo.file,
|
|
853
|
+
rootDir: fileInfo.rootDir,
|
|
854
|
+
logger: params.logger,
|
|
855
|
+
configCache,
|
|
856
|
+
fileCache
|
|
857
|
+
});
|
|
858
|
+
if (config.enabled === false) {
|
|
859
|
+
continue;
|
|
860
|
+
}
|
|
861
|
+
const derived = deriveRouteFromFile(fileInfo.file, fileInfo.rootDir, params.logger);
|
|
862
|
+
if (!derived) {
|
|
863
|
+
continue;
|
|
864
|
+
}
|
|
865
|
+
const rules = await loadRules(fileInfo.file, params.logger);
|
|
866
|
+
for (const [index, rule] of rules.entries()) {
|
|
867
|
+
if (!rule || typeof rule !== "object") {
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
const ruleValue = rule;
|
|
871
|
+
const unsupportedKeys = ["response", "url", "method"].filter(
|
|
872
|
+
(key2) => key2 in ruleValue
|
|
873
|
+
);
|
|
874
|
+
if (unsupportedKeys.length > 0) {
|
|
875
|
+
params.logger.warn(
|
|
876
|
+
`Skip mock with unsupported fields (${unsupportedKeys.join(", ")}): ${fileInfo.file}`
|
|
877
|
+
);
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
if (typeof rule.handler === "undefined") {
|
|
881
|
+
params.logger.warn(`Skip mock without handler: ${fileInfo.file}`);
|
|
882
|
+
continue;
|
|
883
|
+
}
|
|
884
|
+
const resolved = resolveRule({
|
|
885
|
+
rule,
|
|
886
|
+
derivedTemplate: derived.template,
|
|
887
|
+
derivedMethod: derived.method,
|
|
888
|
+
prefix: params.prefix,
|
|
889
|
+
file: fileInfo.file,
|
|
890
|
+
logger: params.logger
|
|
891
|
+
});
|
|
892
|
+
if (!resolved) {
|
|
893
|
+
continue;
|
|
894
|
+
}
|
|
895
|
+
resolved.ruleIndex = index;
|
|
896
|
+
if (config.headers) {
|
|
897
|
+
resolved.headers = { ...config.headers, ...resolved.headers ?? {} };
|
|
898
|
+
}
|
|
899
|
+
if (typeof resolved.status === "undefined" && typeof config.status === "number") {
|
|
900
|
+
resolved.status = config.status;
|
|
901
|
+
}
|
|
902
|
+
if (typeof resolved.delay === "undefined" && typeof config.delay === "number") {
|
|
903
|
+
resolved.delay = config.delay;
|
|
904
|
+
}
|
|
905
|
+
if (config.middlewares.length > 0) {
|
|
906
|
+
resolved.middlewares = config.middlewares;
|
|
907
|
+
}
|
|
908
|
+
const key = `${resolved.method} ${resolved.template}`;
|
|
909
|
+
if (seen.has(key)) {
|
|
910
|
+
params.logger.warn(`Duplicate mock route ${key} from ${fileInfo.file}`);
|
|
911
|
+
}
|
|
912
|
+
seen.add(key);
|
|
913
|
+
routes.push(resolved);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
return sortRoutes(routes);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
function normalizeOptions(options) {
|
|
920
|
+
const list = Array.isArray(options) ? options : [options];
|
|
921
|
+
return list.length > 0 ? list : [{}];
|
|
922
|
+
}
|
|
923
|
+
function resolvePlaygroundInput(list) {
|
|
924
|
+
for (const entry of list) {
|
|
925
|
+
if (typeof entry.playground !== "undefined") {
|
|
926
|
+
return entry.playground;
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
return void 0;
|
|
930
|
+
}
|
|
931
|
+
function resolveFirst(list, getter) {
|
|
932
|
+
for (const entry of list) {
|
|
933
|
+
const value = getter(entry);
|
|
934
|
+
if (typeof value !== "undefined") {
|
|
935
|
+
return value;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return void 0;
|
|
939
|
+
}
|
|
940
|
+
function resolveRoot(list) {
|
|
941
|
+
const explicit = resolveFirst(list, (entry) => entry.root);
|
|
942
|
+
if (explicit) {
|
|
943
|
+
return explicit;
|
|
944
|
+
}
|
|
945
|
+
const deno = globalThis.Deno;
|
|
946
|
+
if (deno?.cwd) {
|
|
947
|
+
return deno.cwd();
|
|
948
|
+
}
|
|
949
|
+
return node_process.cwd();
|
|
950
|
+
}
|
|
951
|
+
function resolveAllDirs(list, root) {
|
|
952
|
+
const dirs = [];
|
|
953
|
+
const seen = /* @__PURE__ */ new Set();
|
|
954
|
+
for (const entry of list) {
|
|
955
|
+
for (const dir of resolveDirs(entry.dir, root)) {
|
|
956
|
+
if (seen.has(dir)) {
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
seen.add(dir);
|
|
960
|
+
dirs.push(dir);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return dirs;
|
|
964
|
+
}
|
|
965
|
+
function buildApp(params) {
|
|
966
|
+
const app = new hono.Hono({ strict: false });
|
|
967
|
+
registerPlaygroundRoutes({
|
|
968
|
+
app,
|
|
969
|
+
routes: params.routes,
|
|
970
|
+
dirs: params.dirs,
|
|
971
|
+
logger: params.logger,
|
|
972
|
+
config: params.playground,
|
|
973
|
+
root: params.root
|
|
974
|
+
});
|
|
975
|
+
if (params.routes.length > 0) {
|
|
976
|
+
const mockApp = createHonoApp(params.routes);
|
|
977
|
+
app.route("/", mockApp);
|
|
978
|
+
}
|
|
979
|
+
return app;
|
|
980
|
+
}
|
|
981
|
+
async function createDenoWatcher(params) {
|
|
982
|
+
const deno = globalThis.Deno;
|
|
983
|
+
if (!deno?.watchFs) {
|
|
984
|
+
return null;
|
|
985
|
+
}
|
|
986
|
+
const watcher = deno.watchFs(params.dirs, { recursive: true });
|
|
987
|
+
let closed = false;
|
|
988
|
+
(async () => {
|
|
989
|
+
try {
|
|
990
|
+
for await (const event of watcher) {
|
|
991
|
+
if (closed) {
|
|
992
|
+
break;
|
|
993
|
+
}
|
|
994
|
+
if (event.kind === "access") {
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
params.onChange();
|
|
998
|
+
}
|
|
999
|
+
} catch (error) {
|
|
1000
|
+
if (!closed) {
|
|
1001
|
+
params.logger.warn("Watcher failed:", error);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
})();
|
|
1005
|
+
return {
|
|
1006
|
+
close: async () => {
|
|
1007
|
+
closed = true;
|
|
1008
|
+
watcher.close();
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
async function createChokidarWatcher(params) {
|
|
1013
|
+
try {
|
|
1014
|
+
const { default: chokidar } = await import('@mokup/shared/chokidar');
|
|
1015
|
+
const watcher = chokidar.watch(params.dirs, { ignoreInitial: true });
|
|
1016
|
+
watcher.on("add", (file) => {
|
|
1017
|
+
if (isInDirs(file, params.dirs)) {
|
|
1018
|
+
params.onChange();
|
|
1019
|
+
}
|
|
1020
|
+
});
|
|
1021
|
+
watcher.on("change", (file) => {
|
|
1022
|
+
if (isInDirs(file, params.dirs)) {
|
|
1023
|
+
params.onChange();
|
|
1024
|
+
}
|
|
1025
|
+
});
|
|
1026
|
+
watcher.on("unlink", (file) => {
|
|
1027
|
+
if (isInDirs(file, params.dirs)) {
|
|
1028
|
+
params.onChange();
|
|
1029
|
+
}
|
|
1030
|
+
});
|
|
1031
|
+
return {
|
|
1032
|
+
close: async () => {
|
|
1033
|
+
await watcher.close();
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
} catch {
|
|
1037
|
+
return null;
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
async function createWatcher(params) {
|
|
1041
|
+
if (!params.enabled || params.dirs.length === 0) {
|
|
1042
|
+
return null;
|
|
1043
|
+
}
|
|
1044
|
+
const denoWatcher = await createDenoWatcher(params);
|
|
1045
|
+
if (denoWatcher) {
|
|
1046
|
+
return denoWatcher;
|
|
1047
|
+
}
|
|
1048
|
+
const chokidarWatcher = await createChokidarWatcher(params);
|
|
1049
|
+
if (chokidarWatcher) {
|
|
1050
|
+
return chokidarWatcher;
|
|
1051
|
+
}
|
|
1052
|
+
params.logger.warn("Watcher is not available in this runtime; file watching disabled.");
|
|
1053
|
+
return null;
|
|
1054
|
+
}
|
|
1055
|
+
async function createFetchServer(options = {}) {
|
|
1056
|
+
const optionList = normalizeOptions(options);
|
|
1057
|
+
const root = resolveRoot(optionList);
|
|
1058
|
+
const logEnabled = optionList.every((entry) => entry.log !== false);
|
|
1059
|
+
const watchEnabled = optionList.every((entry) => entry.watch !== false);
|
|
1060
|
+
const logger = createLogger(logEnabled);
|
|
1061
|
+
const playgroundConfig = resolvePlaygroundOptions(resolvePlaygroundInput(optionList));
|
|
1062
|
+
const dirs = resolveAllDirs(optionList, root);
|
|
1063
|
+
let routes = [];
|
|
1064
|
+
let app = buildApp({
|
|
1065
|
+
routes,
|
|
1066
|
+
dirs,
|
|
1067
|
+
playground: playgroundConfig,
|
|
1068
|
+
root,
|
|
1069
|
+
logger
|
|
1070
|
+
});
|
|
1071
|
+
const refreshRoutes = async () => {
|
|
1072
|
+
try {
|
|
1073
|
+
const collected = [];
|
|
1074
|
+
for (const entry of optionList) {
|
|
1075
|
+
const scanParams = {
|
|
1076
|
+
dirs: resolveDirs(entry.dir, root),
|
|
1077
|
+
prefix: entry.prefix ?? "",
|
|
1078
|
+
logger
|
|
1079
|
+
};
|
|
1080
|
+
if (entry.include) {
|
|
1081
|
+
scanParams.include = entry.include;
|
|
1082
|
+
}
|
|
1083
|
+
if (entry.exclude) {
|
|
1084
|
+
scanParams.exclude = entry.exclude;
|
|
1085
|
+
}
|
|
1086
|
+
const scanned = await scanRoutes(scanParams);
|
|
1087
|
+
collected.push(...scanned);
|
|
1088
|
+
}
|
|
1089
|
+
const resolvedRoutes = sortRoutes(collected);
|
|
1090
|
+
routes = resolvedRoutes;
|
|
1091
|
+
app = buildApp({
|
|
1092
|
+
routes,
|
|
1093
|
+
dirs,
|
|
1094
|
+
playground: playgroundConfig,
|
|
1095
|
+
root,
|
|
1096
|
+
logger
|
|
1097
|
+
});
|
|
1098
|
+
logger.info(`Loaded ${routes.length} mock routes.`);
|
|
1099
|
+
} catch (error) {
|
|
1100
|
+
logger.error("Failed to scan mock routes:", error);
|
|
1101
|
+
}
|
|
1102
|
+
};
|
|
1103
|
+
await refreshRoutes();
|
|
1104
|
+
const scheduleRefresh = createDebouncer(80, () => {
|
|
1105
|
+
void refreshRoutes();
|
|
1106
|
+
});
|
|
1107
|
+
const watcher = await createWatcher({
|
|
1108
|
+
enabled: watchEnabled,
|
|
1109
|
+
dirs,
|
|
1110
|
+
onChange: scheduleRefresh,
|
|
1111
|
+
logger
|
|
1112
|
+
});
|
|
1113
|
+
const fetch = async (request) => await app.fetch(request);
|
|
1114
|
+
const server = {
|
|
1115
|
+
fetch,
|
|
1116
|
+
refresh: refreshRoutes,
|
|
1117
|
+
getRoutes: () => routes
|
|
1118
|
+
};
|
|
1119
|
+
if (watcher) {
|
|
1120
|
+
server.close = async () => {
|
|
1121
|
+
await watcher.close();
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
return server;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
62
1127
|
function createHonoMiddleware(options) {
|
|
63
1128
|
const handler = fetch.createFetchHandler(options);
|
|
64
1129
|
const middleware = async (context, next) => {
|
|
@@ -182,6 +1247,7 @@ exports.createFetchHandler = fetch.createFetchHandler;
|
|
|
182
1247
|
exports.createConnectMiddleware = createConnectMiddleware;
|
|
183
1248
|
exports.createExpressMiddleware = createExpressMiddleware;
|
|
184
1249
|
exports.createFastifyPlugin = createFastifyPlugin;
|
|
1250
|
+
exports.createFetchServer = createFetchServer;
|
|
185
1251
|
exports.createHonoMiddleware = createHonoMiddleware;
|
|
186
1252
|
exports.createKoaMiddleware = createKoaMiddleware;
|
|
187
1253
|
exports.createMokupWorker = createMokupWorker;
|