@dhaneshpurohit/mockstar 0.3.0 → 0.4.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +43 -4
  3. package/dist/cli.js +1214 -875
  4. package/dist/core/config/schema.d.ts +197 -165
  5. package/dist/core/config/schema.d.ts.map +1 -1
  6. package/dist/core/http/body-cap.d.ts +37 -0
  7. package/dist/core/http/body-cap.d.ts.map +1 -0
  8. package/dist/core/http/rate-limit.d.ts +55 -0
  9. package/dist/core/http/rate-limit.d.ts.map +1 -0
  10. package/dist/core/matching/discriminators.d.ts +25 -0
  11. package/dist/core/matching/discriminators.d.ts.map +1 -1
  12. package/dist/core/matching/index.d.ts +3 -1
  13. package/dist/core/matching/index.d.ts.map +1 -1
  14. package/dist/features/openapi/converter.d.ts.map +1 -1
  15. package/dist/features/pass-through.d.ts +7 -0
  16. package/dist/features/pass-through.d.ts.map +1 -1
  17. package/dist/features/proxy/cli.d.ts +11 -0
  18. package/dist/features/proxy/cli.d.ts.map +1 -1
  19. package/dist/features/proxy/dns.d.ts +21 -3
  20. package/dist/features/proxy/dns.d.ts.map +1 -1
  21. package/dist/features/proxy/index.d.ts +1 -1
  22. package/dist/features/proxy/index.d.ts.map +1 -1
  23. package/dist/features/proxy/port-bind.d.ts +18 -1
  24. package/dist/features/proxy/port-bind.d.ts.map +1 -1
  25. package/dist/features/proxy/sni-gate.d.ts +4 -3
  26. package/dist/features/proxy/sni-gate.d.ts.map +1 -1
  27. package/dist/features/url-validator.d.ts +48 -0
  28. package/dist/features/url-validator.d.ts.map +1 -1
  29. package/dist/features/webhooks/event-registry.d.ts +7 -0
  30. package/dist/features/webhooks/event-registry.d.ts.map +1 -1
  31. package/dist/features/webhooks/journal.d.ts +23 -0
  32. package/dist/features/webhooks/journal.d.ts.map +1 -1
  33. package/dist/features/webhooks/queue.d.ts +18 -0
  34. package/dist/features/webhooks/queue.d.ts.map +1 -1
  35. package/dist/features/webhooks/types.d.ts +15 -2
  36. package/dist/features/webhooks/types.d.ts.map +1 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +1048 -826
  39. package/dist/server.d.ts +17 -0
  40. package/dist/server.d.ts.map +1 -1
  41. package/dist/version.d.ts +1 -1
  42. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -2203,20 +2203,64 @@ JSONPath.prototype.safeVm = {
2203
2203
  JSONPath.prototype.vm = vm;
2204
2204
 
2205
2205
  // src/core/matching/discriminators.ts
2206
- function evaluateDiscriminators(pred, req) {
2206
+ function compileMatcher(spec) {
2207
+ if (typeof spec === "string")
2208
+ return { kind: "exact", value: spec };
2209
+ if ("equals" in spec)
2210
+ return { kind: "exact", value: spec.equals };
2211
+ if ("regex" in spec)
2212
+ return { kind: "regex", re: new RegExp(spec.regex) };
2213
+ if ("startsWith" in spec)
2214
+ return { kind: "startsWith", value: spec.startsWith };
2215
+ return { kind: "contains", value: spec.contains };
2216
+ }
2217
+ function compileDim(record) {
2218
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2219
+ }
2220
+ function compilePredicate(pred) {
2221
+ return {
2222
+ ...pred.query && { query: compileDim(pred.query) },
2223
+ ...pred.headers && { headers: compileDim(pred.headers) },
2224
+ ...pred.body && { body: pred.body }
2225
+ };
2226
+ }
2227
+ function compiledMatchOk(compiled, got) {
2228
+ if (compiled.kind === "exact")
2229
+ return got === compiled.value;
2230
+ if (got === undefined)
2231
+ return false;
2232
+ if (compiled.kind === "regex")
2233
+ return compiled.re.test(got);
2234
+ if (compiled.kind === "startsWith")
2235
+ return got.startsWith(compiled.value);
2236
+ return got.includes(compiled.value);
2237
+ }
2238
+ function describeCompiled(m) {
2239
+ switch (m.kind) {
2240
+ case "exact":
2241
+ return `=${m.value}`;
2242
+ case "regex":
2243
+ return `~/${m.re.source}/`;
2244
+ case "startsWith":
2245
+ return `^${m.value}`;
2246
+ case "contains":
2247
+ return `*${m.value}*`;
2248
+ }
2249
+ }
2250
+ function evaluateCompiledDiscriminators(pred, req) {
2207
2251
  if (pred.query) {
2208
- for (const [field, expected] of Object.entries(pred.query)) {
2252
+ for (const [field, expected] of pred.query) {
2209
2253
  const got = req.query.get(field);
2210
- if (!stringMatchOk(expected, got)) {
2211
- return { kind: "query", field, expected: describe(expected), got };
2254
+ if (!compiledMatchOk(expected, got)) {
2255
+ return { kind: "query", field, expected: describeCompiled(expected), got };
2212
2256
  }
2213
2257
  }
2214
2258
  }
2215
2259
  if (pred.headers) {
2216
- for (const [field, expected] of Object.entries(pred.headers)) {
2260
+ for (const [field, expected] of pred.headers) {
2217
2261
  const got = req.headers.get(field.toLowerCase());
2218
- if (!stringMatchOk(expected, got)) {
2219
- return { kind: "headers", field, expected: describe(expected), got };
2262
+ if (!compiledMatchOk(expected, got)) {
2263
+ return { kind: "headers", field, expected: describeCompiled(expected), got };
2220
2264
  }
2221
2265
  }
2222
2266
  }
@@ -2241,34 +2285,6 @@ function evaluateDiscriminators(pred, req) {
2241
2285
  }
2242
2286
  return null;
2243
2287
  }
2244
- function stringMatchOk(spec, got) {
2245
- if (typeof spec === "string")
2246
- return got === spec;
2247
- if ("equals" in spec)
2248
- return got === spec.equals;
2249
- if (got === undefined)
2250
- return false;
2251
- if ("regex" in spec)
2252
- return new RegExp(spec.regex).test(got);
2253
- if ("startsWith" in spec)
2254
- return got.startsWith(spec.startsWith);
2255
- if ("contains" in spec)
2256
- return got.includes(spec.contains);
2257
- return false;
2258
- }
2259
- function describe(spec) {
2260
- if (typeof spec === "string")
2261
- return `=${spec}`;
2262
- if ("equals" in spec)
2263
- return `=${spec.equals}`;
2264
- if ("regex" in spec)
2265
- return `~/${spec.regex}/`;
2266
- if ("startsWith" in spec)
2267
- return `^${spec.startsWith}`;
2268
- if ("contains" in spec)
2269
- return `*${spec.contains}*`;
2270
- return "?";
2271
- }
2272
2288
  function deepEquals(a, b) {
2273
2289
  if (a === b)
2274
2290
  return true;
@@ -2380,7 +2396,7 @@ function buildMatchIndex(entries) {
2380
2396
  const byMethod = new Map;
2381
2397
  const wildcardMethodRoot = createNode();
2382
2398
  entries.forEach((e, i) => {
2383
- const indexed = { entry: e, order: i };
2399
+ const indexed = { entry: e, order: i, compiled: compilePredicate(e.match) };
2384
2400
  if (e.match.method === "*") {
2385
2401
  insertPattern(wildcardMethodRoot, e.match.path, indexed);
2386
2402
  return;
@@ -2414,7 +2430,7 @@ function buildMatchIndex(entries) {
2414
2430
  match(method, path, req) {
2415
2431
  const hits = orderCandidates(candidates(method, path));
2416
2432
  for (const hit of hits) {
2417
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2433
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2418
2434
  if (!failure) {
2419
2435
  return { entry: hit.value.entry, params: hit.params };
2420
2436
  }
@@ -2427,7 +2443,7 @@ function buildMatchIndex(entries) {
2427
2443
  for (const hit of hits) {
2428
2444
  if (out.length >= limit)
2429
2445
  break;
2430
- const failure = evaluateDiscriminators(hit.value.entry.match, req);
2446
+ const failure = evaluateCompiledDiscriminators(hit.value.compiled, req);
2431
2447
  if (failure)
2432
2448
  out.push({ entry: hit.value.entry, params: hit.params, failure });
2433
2449
  }
@@ -2437,7 +2453,7 @@ function buildMatchIndex(entries) {
2437
2453
  }
2438
2454
 
2439
2455
  // src/core/scenarios/evaluator.ts
2440
- function compileMatcher(spec) {
2456
+ function compileMatcher2(spec) {
2441
2457
  if (typeof spec === "string")
2442
2458
  return { kind: "exact", value: spec };
2443
2459
  if ("equals" in spec)
@@ -2448,15 +2464,15 @@ function compileMatcher(spec) {
2448
2464
  return { kind: "startsWith", value: spec.startsWith };
2449
2465
  return { kind: "contains", value: spec.contains };
2450
2466
  }
2451
- function compileDim(record) {
2452
- return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher(v)]));
2467
+ function compileDim2(record) {
2468
+ return new Map(Object.entries(record).map(([k, v]) => [k, compileMatcher2(v)]));
2453
2469
  }
2454
- function compilePredicate(pred) {
2470
+ function compilePredicate2(pred) {
2455
2471
  return {
2456
- ...pred.params && { params: compileDim(pred.params) },
2457
- ...pred.query && { query: compileDim(pred.query) },
2458
- ...pred.headers && { headers: compileDim(pred.headers) },
2459
- ...pred.body && { body: compileDim(pred.body) }
2472
+ ...pred.params && { params: compileDim2(pred.params) },
2473
+ ...pred.query && { query: compileDim2(pred.query) },
2474
+ ...pred.headers && { headers: compileDim2(pred.headers) },
2475
+ ...pred.body && { body: compileDim2(pred.body) }
2460
2476
  };
2461
2477
  }
2462
2478
  function compileResponse(resp) {
@@ -2485,7 +2501,7 @@ function compileResponse(resp) {
2485
2501
  function compileScenarioRules(rules) {
2486
2502
  return rules.map((rule) => ({
2487
2503
  id: rule.id,
2488
- predicate: compilePredicate(rule.when),
2504
+ predicate: compilePredicate2(rule.when),
2489
2505
  response: compileResponse(rule.response)
2490
2506
  }));
2491
2507
  }
@@ -6596,13 +6612,6 @@ function timestampUnitFor(scheme) {
6596
6612
 
6597
6613
  // src/core/config/schema.ts
6598
6614
  var MatchMethod = exports_external.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "*"]);
6599
- var StringMatch = exports_external.union([
6600
- exports_external.string(),
6601
- exports_external.object({ equals: exports_external.string() }).strict(),
6602
- exports_external.object({ regex: exports_external.string() }).strict(),
6603
- exports_external.object({ startsWith: exports_external.string() }).strict(),
6604
- exports_external.object({ contains: exports_external.string() }).strict()
6605
- ]);
6606
6615
  function isUnsafeRegex(pattern) {
6607
6616
  return /\([^)]*[*+{][^)]*\)[*+{]/.test(pattern) || /\([^)]*\|[^)]*\)[*+{]/.test(pattern);
6608
6617
  }
@@ -6610,7 +6619,7 @@ var StringMatchWithRegexGuard = exports_external.union([
6610
6619
  exports_external.string(),
6611
6620
  exports_external.object({ equals: exports_external.string() }).strict(),
6612
6621
  exports_external.object({ regex: exports_external.string() }).strict().refine((v) => !isUnsafeRegex(v.regex), (v) => ({
6613
- message: `scenario regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
6622
+ message: `regex '${v.regex}' may cause catastrophic backtracking \u2014 use exact/startsWith/contains instead`
6614
6623
  })),
6615
6624
  exports_external.object({ startsWith: exports_external.string() }).strict(),
6616
6625
  exports_external.object({ contains: exports_external.string() }).strict()
@@ -6623,8 +6632,8 @@ var BodyMatch = exports_external.object({
6623
6632
  var MatchPredicate = exports_external.object({
6624
6633
  method: MatchMethod.default("*"),
6625
6634
  path: exports_external.string().min(1),
6626
- query: exports_external.record(StringMatch).optional(),
6627
- headers: exports_external.record(StringMatch).optional(),
6635
+ query: exports_external.record(StringMatchWithRegexGuard).optional(),
6636
+ headers: exports_external.record(StringMatchWithRegexGuard).optional(),
6628
6637
  body: BodyMatch.optional(),
6629
6638
  priority: exports_external.number().int().default(0)
6630
6639
  }).strict();
@@ -6834,7 +6843,7 @@ var MocksFile = exports_external.object({
6834
6843
  var TenantLimits = exports_external.object({
6835
6844
  maxBodyBytes: exports_external.number().int().positive().default(1048576),
6836
6845
  maxResponseBytes: exports_external.number().int().positive().default(1048576),
6837
- requestsPerSecond: exports_external.number().int().positive().default(1000),
6846
+ requestsPerSecond: exports_external.number().int().positive().default(1e4),
6838
6847
  journalSize: exports_external.number().int().positive().default(1000)
6839
6848
  }).strict();
6840
6849
  var TenantConfig = exports_external.object({
@@ -7171,130 +7180,117 @@ function preflight(bunVersion = detectBunVersion()) {
7171
7180
  };
7172
7181
  }
7173
7182
 
7174
- // node_modules/hono/dist/compose.js
7175
- var compose = (middleware, onError, onNotFound) => {
7176
- return (context, next) => {
7177
- let index2 = -1;
7178
- return dispatch(0);
7179
- async function dispatch(i) {
7180
- if (i <= index2) {
7181
- throw new Error("next() called multiple times");
7182
- }
7183
- index2 = i;
7184
- let res;
7185
- let isError = false;
7186
- let handler;
7187
- if (middleware[i]) {
7188
- handler = middleware[i][0][0];
7189
- context.req.routeIndex = i;
7190
- } else {
7191
- handler = i === middleware.length && next || undefined;
7192
- }
7193
- if (handler) {
7194
- try {
7195
- res = await handler(context, () => dispatch(i + 1));
7196
- } catch (err) {
7197
- if (err instanceof Error && onError) {
7198
- context.error = err;
7199
- res = await onError(err, context);
7200
- isError = true;
7201
- } else {
7202
- throw err;
7203
- }
7204
- }
7205
- } else {
7206
- if (context.finalized === false && onNotFound) {
7207
- res = await onNotFound(context);
7208
- }
7209
- }
7210
- if (res && (context.finalized === false || isError)) {
7211
- context.res = res;
7212
- }
7213
- return context;
7214
- }
7215
- };
7183
+ // node_modules/hono/dist/http-exception.js
7184
+ var HTTPException = class extends Error {
7185
+ res;
7186
+ status;
7187
+ constructor(status = 500, options) {
7188
+ super(options?.message, { cause: options?.cause });
7189
+ this.res = options?.res;
7190
+ this.status = status;
7191
+ }
7192
+ getResponse() {
7193
+ if (this.res)
7194
+ return new Response(this.res.body, {
7195
+ status: this.status,
7196
+ headers: this.res.headers
7197
+ });
7198
+ return new Response(this.message, { status: this.status });
7199
+ }
7216
7200
  };
7217
7201
 
7218
7202
  // node_modules/hono/dist/request/constants.js
7219
- var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
7203
+ var GET_MATCH_RESULT = Symbol();
7204
+
7205
+ // node_modules/hono/dist/utils/buffer.js
7206
+ var bufferToFormData = (arrayBuffer, contentType) => {
7207
+ return new Response(arrayBuffer, { headers: { "Content-Type": contentType.replace(/^[^;]+/, (mediaType) => mediaType.toLowerCase()) } }).formData();
7208
+ };
7220
7209
 
7221
7210
  // node_modules/hono/dist/utils/body.js
7222
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
7211
+ var MAX_NESTED_OBJECTS = 1e4;
7212
+ var isRawRequest = (request) => ("headers" in request);
7213
+ var parseBody = async (request, options = Object.create(null)) => {
7223
7214
  const { all = false, dot = false } = options;
7224
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
7225
- const contentType = headers.get("Content-Type");
7226
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
7227
- return parseFormData(request, { all, dot });
7228
- }
7215
+ const mediaType = (isRawRequest(request) ? request.headers : request.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();
7216
+ if (mediaType === "multipart/form-data" || mediaType === "application/x-www-form-urlencoded")
7217
+ return parseFormData(request, {
7218
+ all,
7219
+ dot
7220
+ });
7229
7221
  return {};
7230
7222
  };
7231
7223
  async function parseFormData(request, options) {
7232
- const formData = await request.formData();
7233
- if (formData) {
7224
+ if (!isRawRequest(request) && request.bodyCache.formData)
7225
+ return convertFormDataToBodyData(await request.bodyCache.formData, options);
7226
+ const headers = isRawRequest(request) ? request.headers : request.raw.headers;
7227
+ const arrayBuffer = await request.arrayBuffer();
7228
+ const formDataPromise = bufferToFormData(arrayBuffer, headers.get("Content-Type") || "");
7229
+ if (!isRawRequest(request))
7230
+ request.bodyCache.formData = formDataPromise;
7231
+ const formData = await formDataPromise;
7232
+ if (formData)
7234
7233
  return convertFormDataToBodyData(formData, options);
7235
- }
7236
7234
  return {};
7237
7235
  }
7238
7236
  function convertFormDataToBodyData(formData, options) {
7239
- const form = /* @__PURE__ */ Object.create(null);
7237
+ const form = Object.create(null);
7238
+ const nestingState = { count: 0 };
7240
7239
  formData.forEach((value, key) => {
7241
- const shouldParseAllValues = options.all || key.endsWith("[]");
7242
- if (!shouldParseAllValues) {
7240
+ if (!(options.all || key.endsWith("[]")))
7243
7241
  form[key] = value;
7244
- } else {
7242
+ else
7245
7243
  handleParsingAllValues(form, key, value);
7246
- }
7247
7244
  });
7248
- if (options.dot) {
7245
+ if (options.dot)
7249
7246
  Object.entries(form).forEach(([key, value]) => {
7250
- const shouldParseDotValues = key.includes(".");
7251
- if (shouldParseDotValues) {
7252
- handleParsingNestedValues(form, key, value);
7247
+ if (key.includes(".")) {
7248
+ handleParsingNestedValues(form, key, value, nestingState);
7253
7249
  delete form[key];
7254
7250
  }
7255
7251
  });
7256
- }
7257
7252
  return form;
7258
7253
  }
7259
7254
  var handleParsingAllValues = (form, key, value) => {
7260
7255
  if (form[key] !== undefined) {
7261
- if (Array.isArray(form[key])) {
7256
+ if (Array.isArray(form[key]))
7262
7257
  form[key].push(value);
7263
- } else {
7258
+ else
7264
7259
  form[key] = [form[key], value];
7265
- }
7266
- } else {
7267
- if (!key.endsWith("[]")) {
7268
- form[key] = value;
7269
- } else {
7270
- form[key] = [value];
7271
- }
7272
- }
7260
+ } else if (!key.endsWith("[]"))
7261
+ form[key] = value;
7262
+ else
7263
+ form[key] = [value];
7273
7264
  };
7274
- var handleParsingNestedValues = (form, key, value) => {
7275
- if (/(?:^|\.)__proto__\./.test(key)) {
7265
+ var handleParsingNestedValues = (form, key, value, state) => {
7266
+ if (/(?:^|\.)__proto__\./.test(key))
7276
7267
  return;
7277
- }
7278
7268
  let nestedForm = form;
7279
- const keys = key.split(".");
7269
+ const keys = key.split(".", 34);
7270
+ if (keys.length > 33)
7271
+ throwNestingLimitExceeded();
7280
7272
  keys.forEach((key2, index2) => {
7281
- if (index2 === keys.length - 1) {
7273
+ if (index2 === keys.length - 1)
7282
7274
  nestedForm[key2] = value;
7283
- } else {
7275
+ else {
7284
7276
  if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
7285
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
7277
+ if (state.count++ >= MAX_NESTED_OBJECTS)
7278
+ throwNestingLimitExceeded();
7279
+ nestedForm[key2] = Object.create(null);
7286
7280
  }
7287
7281
  nestedForm = nestedForm[key2];
7288
7282
  }
7289
7283
  });
7290
7284
  };
7285
+ var throwNestingLimitExceeded = () => {
7286
+ throw new Error("Nesting limit exceeded");
7287
+ };
7291
7288
 
7292
7289
  // node_modules/hono/dist/utils/url.js
7293
7290
  var splitPath2 = (path) => {
7294
7291
  const paths = path.split("/");
7295
- if (paths[0] === "") {
7292
+ if (paths[0] === "")
7296
7293
  paths.shift();
7297
- }
7298
7294
  return paths;
7299
7295
  };
7300
7296
  var splitRoutingPath = (routePath) => {
@@ -7309,34 +7305,46 @@ var extractGroupsFromPath = (path) => {
7309
7305
  groups.push([mark, match]);
7310
7306
  return mark;
7311
7307
  });
7312
- return { groups, path };
7308
+ return {
7309
+ groups,
7310
+ path
7311
+ };
7313
7312
  };
7314
7313
  var replaceGroupMarks = (paths, groups) => {
7315
7314
  for (let i = groups.length - 1;i >= 0; i--) {
7316
7315
  const [mark] = groups[i];
7317
- for (let j = paths.length - 1;j >= 0; j--) {
7316
+ for (let j = paths.length - 1;j >= 0; j--)
7318
7317
  if (paths[j].includes(mark)) {
7319
7318
  paths[j] = paths[j].replace(mark, groups[i][1]);
7320
7319
  break;
7321
7320
  }
7322
- }
7323
7321
  }
7324
7322
  return paths;
7325
7323
  };
7326
7324
  var patternCache = {};
7327
7325
  var getPattern = (label, next) => {
7328
- if (label === "*") {
7326
+ if (label === "*")
7329
7327
  return "*";
7330
- }
7331
7328
  const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
7332
7329
  if (match) {
7333
7330
  const cacheKey = `${label}#${next}`;
7334
7331
  if (!patternCache[cacheKey]) {
7335
- if (match[2]) {
7336
- patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
7337
- } else {
7338
- patternCache[cacheKey] = [label, match[1], true];
7339
- }
7332
+ if (match[2])
7333
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
7334
+ cacheKey,
7335
+ match[1],
7336
+ new RegExp(`^${match[2]}(?=/${next})`)
7337
+ ] : [
7338
+ label,
7339
+ match[1],
7340
+ new RegExp(`^${match[2]}$`)
7341
+ ];
7342
+ else
7343
+ patternCache[cacheKey] = [
7344
+ label,
7345
+ match[1],
7346
+ true
7347
+ ];
7340
7348
  }
7341
7349
  return patternCache[cacheKey];
7342
7350
  }
@@ -7355,7 +7363,7 @@ var tryDecode = (str, decoder) => {
7355
7363
  });
7356
7364
  }
7357
7365
  };
7358
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
7366
+ var decodeURIWithPreservedPercent = (value) => decodeURI(value.includes("%25") ? value.replace(/%25/g, "%2525") : value);
7359
7367
  var getPath = (request) => {
7360
7368
  const url = request.url;
7361
7369
  const start = url.indexOf("/", url.indexOf(":") + 4);
@@ -7367,10 +7375,16 @@ var getPath = (request) => {
7367
7375
  const hashIndex = url.indexOf("#", i);
7368
7376
  const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
7369
7377
  const path = url.slice(start, end);
7370
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
7371
- } else if (charCode === 63 || charCode === 35) {
7378
+ const decoded = tryDecode(path, decodeURIWithPreservedPercent);
7379
+ if (/%(?![0-9A-Fa-f]{2})/.test(path)) {
7380
+ const rewritten = new URL("http://localhost");
7381
+ rewritten.pathname = decoded.replace(/[\\\t\n\r]/g, encodeURIComponent);
7382
+ if (tryDecode(rewritten.pathname, decodeURIWithPreservedPercent) !== decoded)
7383
+ return tryDecode(path.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"), decodeURIWithPreservedPercent);
7384
+ }
7385
+ return decoded;
7386
+ } else if (charCode === 63 || charCode === 35)
7372
7387
  break;
7373
- }
7374
7388
  }
7375
7389
  return url.slice(start, i);
7376
7390
  };
@@ -7379,107 +7393,98 @@ var getPathNoStrict = (request) => {
7379
7393
  return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
7380
7394
  };
7381
7395
  var mergePath = (base, sub, ...rest) => {
7382
- if (rest.length) {
7396
+ if (rest.length)
7383
7397
  sub = mergePath(sub, ...rest);
7384
- }
7385
7398
  return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
7386
7399
  };
7387
7400
  var checkOptionalParameter = (path) => {
7388
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
7401
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":"))
7389
7402
  return null;
7390
- }
7391
7403
  const segments = path.split("/");
7392
7404
  const results = [];
7393
7405
  let basePath = "";
7394
7406
  segments.forEach((segment) => {
7395
- if (segment !== "" && !/\:/.test(segment)) {
7407
+ if (segment !== "" && !/\:/.test(segment))
7396
7408
  basePath += "/" + segment;
7397
- } else if (/\:/.test(segment)) {
7398
- if (/\?/.test(segment)) {
7399
- if (results.length === 0 && basePath === "") {
7409
+ else if (/\:/.test(segment)) {
7410
+ if (segment.charCodeAt(segment.length - 1) === 63) {
7411
+ if (results.length === 0 && basePath === "")
7400
7412
  results.push("/");
7401
- } else {
7413
+ else
7402
7414
  results.push(basePath);
7403
- }
7404
- const optionalSegment = segment.replace("?", "");
7415
+ const optionalSegment = segment.slice(0, -1);
7405
7416
  basePath += "/" + optionalSegment;
7406
7417
  results.push(basePath);
7407
- } else {
7418
+ } else
7408
7419
  basePath += "/" + segment;
7409
- }
7410
7420
  }
7411
7421
  });
7412
7422
  return results.filter((v, i, a) => a.indexOf(v) === i);
7413
7423
  };
7424
+ var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
7414
7425
  var _decodeURI = (value) => {
7415
- if (!/[%+]/.test(value)) {
7416
- return value;
7417
- }
7418
- if (value.indexOf("+") !== -1) {
7426
+ if (value.indexOf("+") !== -1)
7419
7427
  value = value.replace(/\+/g, " ");
7420
- }
7421
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
7428
+ return tryDecodeURIComponent(value);
7422
7429
  };
7423
7430
  var _getQueryParam = (url, key, multiple) => {
7431
+ const hashIndex = url.indexOf("#", 8);
7432
+ if (hashIndex !== -1)
7433
+ url = url.slice(0, hashIndex);
7424
7434
  let encoded;
7425
- if (!multiple && key && !/[%+]/.test(key)) {
7426
- let keyIndex2 = url.indexOf("?", 8);
7427
- if (keyIndex2 === -1) {
7435
+ if (!multiple && key && !/[%+&=]/.test(key)) {
7436
+ const queryIndex = url.indexOf("?", 8);
7437
+ let keyIndex2 = queryIndex;
7438
+ if (keyIndex2 === -1)
7428
7439
  return;
7429
- }
7430
- if (!url.startsWith(key, keyIndex2 + 1)) {
7440
+ if (!url.startsWith(key, keyIndex2 + 1))
7431
7441
  keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
7432
- }
7433
7442
  while (keyIndex2 !== -1) {
7434
7443
  const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
7435
- if (trailingKeyCode === 61) {
7436
- const valueIndex = keyIndex2 + key.length + 2;
7437
- const endIndex = url.indexOf("&", valueIndex);
7438
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
7439
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
7444
+ if (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {
7445
+ if (keyIndex2 > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex2)))
7446
+ break;
7447
+ if (trailingKeyCode === 61) {
7448
+ const valueIndex = keyIndex2 + key.length + 2;
7449
+ const endIndex = url.indexOf("&", valueIndex);
7450
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
7451
+ }
7440
7452
  return "";
7441
7453
  }
7442
7454
  keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
7443
7455
  }
7444
7456
  encoded = /[%+]/.test(url);
7445
- if (!encoded) {
7457
+ if (!encoded)
7446
7458
  return;
7447
- }
7448
7459
  }
7449
- const results = {};
7460
+ const results = Object.create(null);
7450
7461
  encoded ??= /[%+]/.test(url);
7451
7462
  let keyIndex = url.indexOf("?", 8);
7452
7463
  while (keyIndex !== -1) {
7453
7464
  const nextKeyIndex = url.indexOf("&", keyIndex + 1);
7454
7465
  let valueIndex = url.indexOf("=", keyIndex);
7455
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
7466
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1)
7456
7467
  valueIndex = -1;
7457
- }
7458
7468
  let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
7459
- if (encoded) {
7469
+ if (encoded)
7460
7470
  name = _decodeURI(name);
7461
- }
7462
7471
  keyIndex = nextKeyIndex;
7463
- if (name === "") {
7472
+ if (name === "")
7464
7473
  continue;
7465
- }
7466
7474
  let value;
7467
- if (valueIndex === -1) {
7475
+ if (valueIndex === -1)
7468
7476
  value = "";
7469
- } else {
7477
+ else {
7470
7478
  value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
7471
- if (encoded) {
7479
+ if (encoded)
7472
7480
  value = _decodeURI(value);
7473
- }
7474
7481
  }
7475
7482
  if (multiple) {
7476
- if (!(results[name] && Array.isArray(results[name]))) {
7483
+ if (!(results[name] && Array.isArray(results[name])))
7477
7484
  results[name] = [];
7478
- }
7479
7485
  results[name].push(value);
7480
- } else {
7486
+ } else
7481
7487
  results[name] ??= value;
7482
- }
7483
7488
  }
7484
7489
  return key ? results[key] : results;
7485
7490
  };
@@ -7490,7 +7495,6 @@ var getQueryParams = (url, key) => {
7490
7495
  var decodeURIComponent_ = decodeURIComponent;
7491
7496
 
7492
7497
  // node_modules/hono/dist/request.js
7493
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
7494
7498
  var HonoRequest = class {
7495
7499
  raw;
7496
7500
  #validatedData;
@@ -7502,24 +7506,22 @@ var HonoRequest = class {
7502
7506
  this.raw = request;
7503
7507
  this.path = path;
7504
7508
  this.#matchResult = matchResult;
7505
- this.#validatedData = {};
7506
7509
  }
7507
7510
  param(key) {
7508
7511
  return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
7509
7512
  }
7510
7513
  #getDecodedParam(key) {
7511
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
7514
+ const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key];
7512
7515
  const param = this.#getParamValue(paramKey);
7513
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
7516
+ return param && tryDecodeURIComponent(param);
7514
7517
  }
7515
7518
  #getAllDecodedParams() {
7516
7519
  const decoded = {};
7517
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
7520
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {});
7518
7521
  for (const key of keys) {
7519
7522
  const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
7520
- if (value !== undefined) {
7521
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
7522
- }
7523
+ if (value !== undefined)
7524
+ decoded[key] = tryDecodeURIComponent(value);
7523
7525
  }
7524
7526
  return decoded;
7525
7527
  }
@@ -7533,10 +7535,9 @@ var HonoRequest = class {
7533
7535
  return getQueryParams(this.url, key);
7534
7536
  }
7535
7537
  header(name) {
7536
- if (name) {
7538
+ if (name)
7537
7539
  return this.raw.headers.get(name) ?? undefined;
7538
- }
7539
- const headerData = {};
7540
+ const headerData = Object.create(null);
7540
7541
  this.raw.headers.forEach((value, key) => {
7541
7542
  headerData[key] = value;
7542
7543
  });
@@ -7548,18 +7549,15 @@ var HonoRequest = class {
7548
7549
  #cachedBody = (key) => {
7549
7550
  const { bodyCache, raw } = this;
7550
7551
  const cachedBody = bodyCache[key];
7551
- if (cachedBody) {
7552
+ if (cachedBody)
7552
7553
  return cachedBody;
7553
- }
7554
- const anyCachedKey = Object.keys(bodyCache)[0];
7555
- if (anyCachedKey) {
7554
+ for (const anyCachedKey in bodyCache)
7556
7555
  return bodyCache[anyCachedKey].then((body) => {
7557
- if (anyCachedKey === "json") {
7556
+ if (anyCachedKey === "json")
7558
7557
  body = JSON.stringify(body);
7559
- }
7560
- return new Response(body)[key]();
7558
+ const contentType = anyCachedKey === "formData" ? undefined : raw.headers.get("content-type");
7559
+ return new Response(body, { headers: contentType ? { "Content-Type": contentType } : undefined })[key]();
7561
7560
  });
7562
- }
7563
7561
  return bodyCache[key] = raw[key]();
7564
7562
  };
7565
7563
  json() {
@@ -7571,6 +7569,9 @@ var HonoRequest = class {
7571
7569
  arrayBuffer() {
7572
7570
  return this.#cachedBody("arrayBuffer");
7573
7571
  }
7572
+ bytes() {
7573
+ return this.#cachedBody("arrayBuffer").then((buffer) => new Uint8Array(buffer));
7574
+ }
7574
7575
  blob() {
7575
7576
  return this.#cachedBody("blob");
7576
7577
  }
@@ -7578,10 +7579,10 @@ var HonoRequest = class {
7578
7579
  return this.#cachedBody("formData");
7579
7580
  }
7580
7581
  addValidatedData(target, data) {
7581
- this.#validatedData[target] = data;
7582
+ (this.#validatedData ??= {})[target] = data;
7582
7583
  }
7583
7584
  valid(target) {
7584
- return this.#validatedData[target];
7585
+ return this.#validatedData?.[target];
7585
7586
  }
7586
7587
  get url() {
7587
7588
  return this.raw.url;
@@ -7614,28 +7615,27 @@ var raw = (value, callbacks) => {
7614
7615
  };
7615
7616
  var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
7616
7617
  if (typeof str === "object" && !(str instanceof String)) {
7617
- if (!(str instanceof Promise)) {
7618
+ if (!(str instanceof Promise))
7618
7619
  str = str.toString();
7619
- }
7620
- if (str instanceof Promise) {
7620
+ if (str instanceof Promise)
7621
7621
  str = await str;
7622
- }
7623
7622
  }
7624
7623
  const callbacks = str.callbacks;
7625
- if (!callbacks?.length) {
7624
+ if (!callbacks?.length)
7626
7625
  return Promise.resolve(str);
7627
- }
7628
- if (buffer) {
7626
+ if (buffer)
7629
7627
  buffer[0] += str;
7630
- } else {
7628
+ else
7631
7629
  buffer = [str];
7632
- }
7633
- const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
7634
- if (preserveCallbacks) {
7630
+ const resStr = Promise.all(callbacks.map((c) => c({
7631
+ phase,
7632
+ buffer,
7633
+ context
7634
+ }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
7635
+ if (preserveCallbacks)
7635
7636
  return raw(await resStr, callbacks);
7636
- } else {
7637
+ else
7637
7638
  return resStr;
7638
- }
7639
7639
  };
7640
7640
 
7641
7641
  // node_modules/hono/dist/context.js
@@ -7678,40 +7678,33 @@ var Context = class {
7678
7678
  return this.#req;
7679
7679
  }
7680
7680
  get event() {
7681
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
7681
+ if (this.#executionCtx && "respondWith" in this.#executionCtx)
7682
7682
  return this.#executionCtx;
7683
- } else {
7683
+ else
7684
7684
  throw Error("This context has no FetchEvent");
7685
- }
7686
7685
  }
7687
7686
  get executionCtx() {
7688
- if (this.#executionCtx) {
7687
+ if (this.#executionCtx)
7689
7688
  return this.#executionCtx;
7690
- } else {
7689
+ else
7691
7690
  throw Error("This context has no ExecutionContext");
7692
- }
7693
7691
  }
7694
7692
  get res() {
7695
- return this.#res ||= createResponseInstance(null, {
7696
- headers: this.#preparedHeaders ??= new Headers
7697
- });
7693
+ return this.#res ||= createResponseInstance(null, { headers: this.#preparedHeaders ??= new Headers });
7698
7694
  }
7699
7695
  set res(_res) {
7700
7696
  if (this.#res && _res) {
7701
7697
  _res = createResponseInstance(_res.body, _res);
7702
7698
  for (const [k, v] of this.#res.headers.entries()) {
7703
- if (k === "content-type") {
7699
+ if (k === "content-type")
7704
7700
  continue;
7705
- }
7706
7701
  if (k === "set-cookie") {
7707
7702
  const cookies = this.#res.headers.getSetCookie();
7708
7703
  _res.headers.delete("set-cookie");
7709
- for (const cookie of cookies) {
7704
+ for (const cookie of cookies)
7710
7705
  _res.headers.append("set-cookie", cookie);
7711
- }
7712
- } else {
7706
+ } else
7713
7707
  _res.headers.set(k, v);
7714
- }
7715
7708
  }
7716
7709
  }
7717
7710
  this.#res = _res;
@@ -7727,17 +7720,15 @@ var Context = class {
7727
7720
  this.#renderer = renderer;
7728
7721
  };
7729
7722
  header = (name, value, options) => {
7730
- if (this.finalized) {
7723
+ if (this.finalized && !this.#res.bodyUsed)
7731
7724
  this.#res = createResponseInstance(this.#res.body, this.#res);
7732
- }
7733
7725
  const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
7734
- if (value === undefined) {
7726
+ if (value === undefined)
7735
7727
  headers.delete(name);
7736
- } else if (options?.append) {
7728
+ else if (options?.append)
7737
7729
  headers.append(name, value);
7738
- } else {
7730
+ else
7739
7731
  headers.set(name, value);
7740
- }
7741
7732
  };
7742
7733
  status = (status) => {
7743
7734
  this.#status = status;
@@ -7750,37 +7741,46 @@ var Context = class {
7750
7741
  return this.#var ? this.#var.get(key) : undefined;
7751
7742
  };
7752
7743
  get var() {
7753
- if (!this.#var) {
7744
+ if (!this.#var)
7754
7745
  return {};
7755
- }
7756
7746
  return Object.fromEntries(this.#var);
7757
7747
  }
7758
7748
  #newResponse(data, arg, headers) {
7759
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
7760
- if (typeof arg === "object" && "headers" in arg) {
7761
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
7762
- for (const [key, value] of argHeaders) {
7763
- if (key.toLowerCase() === "set-cookie") {
7749
+ let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders;
7750
+ if (typeof arg === "object" && arg.headers) {
7751
+ responseHeaders ??= new Headers;
7752
+ for (const [key, value] of new Headers(arg.headers))
7753
+ if (key === "set-cookie")
7764
7754
  responseHeaders.append(key, value);
7765
- } else {
7755
+ else
7766
7756
  responseHeaders.set(key, value);
7767
- }
7768
- }
7769
7757
  }
7770
7758
  if (headers) {
7771
- for (const [k, v] of Object.entries(headers)) {
7772
- if (typeof v === "string") {
7773
- responseHeaders.set(k, v);
7774
- } else {
7775
- responseHeaders.delete(k);
7776
- for (const v2 of v) {
7777
- responseHeaders.append(k, v2);
7759
+ if (!responseHeaders) {
7760
+ let count = 0;
7761
+ for (const k in headers)
7762
+ if (++count > 1 || typeof headers[k] !== "string") {
7763
+ responseHeaders = new Headers;
7764
+ break;
7778
7765
  }
7779
- }
7780
7766
  }
7767
+ if (responseHeaders)
7768
+ for (const k in headers) {
7769
+ const v = headers[k];
7770
+ if (typeof v === "string")
7771
+ responseHeaders.set(k, v);
7772
+ else {
7773
+ responseHeaders.delete(k);
7774
+ for (const v2 of v)
7775
+ responseHeaders.append(k, v2);
7776
+ }
7777
+ }
7781
7778
  }
7782
7779
  const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
7783
- return createResponseInstance(data, { status, headers: responseHeaders });
7780
+ return createResponseInstance(data, {
7781
+ status,
7782
+ headers: responseHeaders ?? headers
7783
+ });
7784
7784
  }
7785
7785
  newResponse = (...args) => this.#newResponse(...args);
7786
7786
  body = (data, arg, headers) => this.#newResponse(data, arg, headers);
@@ -7805,10 +7805,57 @@ var Context = class {
7805
7805
  };
7806
7806
  };
7807
7807
 
7808
+ // node_modules/hono/dist/compose.js
7809
+ var compose = (middleware, onError, onNotFound) => {
7810
+ return (context, next) => {
7811
+ let index2 = -1;
7812
+ return dispatch(0);
7813
+ async function dispatch(i) {
7814
+ if (i <= index2)
7815
+ throw new Error("next() called multiple times");
7816
+ index2 = i;
7817
+ let res;
7818
+ let isError = false;
7819
+ let handler;
7820
+ if (middleware[i]) {
7821
+ handler = middleware[i][0][0];
7822
+ context.req.routeIndex = i;
7823
+ } else
7824
+ handler = i === middleware.length && next || undefined;
7825
+ if (handler)
7826
+ try {
7827
+ res = await handler(context, () => dispatch(i + 1));
7828
+ } catch (err) {
7829
+ if (err instanceof Error && onError) {
7830
+ context.error = err;
7831
+ res = await onError(err, context);
7832
+ isError = true;
7833
+ } else
7834
+ throw err;
7835
+ }
7836
+ else if (context.finalized === false && onNotFound)
7837
+ res = await onNotFound(context);
7838
+ if (res && (context.finalized === false || isError))
7839
+ context.res = res;
7840
+ return context;
7841
+ }
7842
+ };
7843
+ };
7844
+
7845
+ // node_modules/hono/dist/helper/route/index.js
7846
+ var matchedRoutes = (c) => c.req[GET_MATCH_RESULT][0].map(([[, route]]) => route);
7847
+ var routePath = (c, index2) => matchedRoutes(c).at(index2 ?? c.req.routeIndex)?.path ?? "";
7848
+
7808
7849
  // node_modules/hono/dist/router.js
7809
- var METHOD_NAME_ALL = "ALL";
7810
- var METHOD_NAME_ALL_LOWERCASE = "all";
7811
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
7850
+ var METHODS = [
7851
+ "get",
7852
+ "post",
7853
+ "put",
7854
+ "delete",
7855
+ "options",
7856
+ "patch",
7857
+ "query"
7858
+ ];
7812
7859
  var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
7813
7860
  var UnsupportedPathError = class extends Error {
7814
7861
  };
@@ -7816,6 +7863,61 @@ var UnsupportedPathError = class extends Error {
7816
7863
  // node_modules/hono/dist/utils/constants.js
7817
7864
  var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
7818
7865
 
7866
+ // node_modules/hono/dist/utils/mount.js
7867
+ var countTrailingSlashes = (path) => {
7868
+ let index2 = path.length;
7869
+ while (index2 > 0 && path.charCodeAt(index2 - 1) === 47)
7870
+ index2--;
7871
+ return path.length - index2;
7872
+ };
7873
+ var getPathPrefixLength = (c, pathPrefix, routePath2) => {
7874
+ if (!/[:*]/.test(pathPrefix))
7875
+ return pathPrefix.length;
7876
+ const path = c.req.path;
7877
+ const matchResult = c.req[GET_MATCH_RESULT];
7878
+ const paramNames = /* @__PURE__ */ new Set;
7879
+ let length = 0;
7880
+ for (const part of splitRoutingPath(pathPrefix)) {
7881
+ if (part[0] === ":" && part.endsWith("}?"))
7882
+ throw new Error(`mount(): Optional regular expression parameters are not supported in "${routePath2}".`);
7883
+ const pattern = getPattern(part);
7884
+ if (pattern && pattern !== "*") {
7885
+ const name = pattern[1];
7886
+ if (paramNames.has(name))
7887
+ throw new Error(`mount(): Duplicate path parameter "${name}" in "${routePath2}".`);
7888
+ paramNames.add(name);
7889
+ }
7890
+ if (pattern && pattern !== "*" && pattern[2] !== true) {
7891
+ const value = matchResult.length === 2 ? matchResult[1][matchResult[0][c.req.routeIndex][1][pattern[1]]] : matchResult[0][c.req.routeIndex][1][pattern[1]];
7892
+ length += value.length + 1;
7893
+ } else if (pattern || part.endsWith("*")) {
7894
+ const end = path.indexOf("/", length + 1);
7895
+ length = end === -1 ? path.length : end;
7896
+ } else
7897
+ length += part.length + 1;
7898
+ }
7899
+ return length;
7900
+ };
7901
+ var createMountedRequest = (c, pathPrefix, routePath2) => {
7902
+ if (/[^/]\*$/.test(routePath2))
7903
+ throw new Error(`mount(): Wildcard must follow "/" in "${routePath2}".`);
7904
+ const prefixLength = getPathPrefixLength(c, pathPrefix, routePath2);
7905
+ const path = c.req.path.slice(prefixLength) || "/";
7906
+ if (prefixLength > c.req.path.length || path[0] !== "/" || /\/(?:\.|%2e){1,2}(?:\/|$)/i.test(path))
7907
+ throw new HTTPException(400, { message: "Invalid mounted path" });
7908
+ const rawUrl = c.req.raw.url;
7909
+ if (/^[^/?#]*\/\/[^/?#\\]*[?#\\]/.test(rawUrl))
7910
+ throw new HTTPException(400, { message: "Invalid mounted path" });
7911
+ const rawPathEnd = rawUrl.search(/[?#]/);
7912
+ const rawTrailingSlashes = countTrailingSlashes(rawPathEnd === -1 ? rawUrl : rawUrl.slice(0, rawPathEnd));
7913
+ if (rawTrailingSlashes > 1 && countTrailingSlashes(c.req.path) === rawTrailingSlashes - 1)
7914
+ throw new HTTPException(400, { message: "Invalid mounted path" });
7915
+ const url = new URL(rawUrl);
7916
+ url.pathname = path.replace(/[\\\t\n\r]/g, encodeURIComponent);
7917
+ if (path.includes("%")) {}
7918
+ return new Request(url, c.req.raw);
7919
+ };
7920
+
7819
7921
  // node_modules/hono/dist/hono-base.js
7820
7922
  var notFoundHandler = (c) => {
7821
7923
  return c.text("404 Not Found", 404);
@@ -7828,13 +7930,14 @@ var errorHandler = (err, c) => {
7828
7930
  console.error(err);
7829
7931
  return c.text("Internal Server Error", 500);
7830
7932
  };
7831
- var Hono = class _Hono {
7933
+ var Hono = class Hono2 {
7832
7934
  get;
7833
7935
  post;
7834
7936
  put;
7835
7937
  delete;
7836
7938
  options;
7837
7939
  patch;
7940
+ query;
7838
7941
  all;
7839
7942
  on;
7840
7943
  use;
@@ -7844,16 +7947,15 @@ var Hono = class _Hono {
7844
7947
  #path = "/";
7845
7948
  routes = [];
7846
7949
  constructor(options = {}) {
7847
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
7848
- allMethods.forEach((method) => {
7950
+ [...METHODS, "all"].forEach((method) => {
7849
7951
  this[method] = (args1, ...args) => {
7850
- if (typeof args1 === "string") {
7952
+ const methodName = method.toUpperCase();
7953
+ if (typeof args1 === "string")
7851
7954
  this.#path = args1;
7852
- } else {
7853
- this.#addRoute(method, this.#path, args1);
7854
- }
7955
+ else
7956
+ this.#addRoute(methodName, this.#path, args1);
7855
7957
  args.forEach((handler) => {
7856
- this.#addRoute(method, this.#path, handler);
7958
+ this.#addRoute(methodName, this.#path, handler);
7857
7959
  });
7858
7960
  return this;
7859
7961
  };
@@ -7862,22 +7964,22 @@ var Hono = class _Hono {
7862
7964
  for (const p of [path].flat()) {
7863
7965
  this.#path = p;
7864
7966
  for (const m of [method].flat()) {
7865
- handlers.map((handler) => {
7866
- this.#addRoute(m.toUpperCase(), this.#path, handler);
7867
- });
7967
+ const methodName = m.toUpperCase();
7968
+ for (const handler of handlers)
7969
+ this.#addRoute(methodName, this.#path, handler);
7868
7970
  }
7869
7971
  }
7870
7972
  return this;
7871
7973
  };
7872
7974
  this.use = (arg1, ...handlers) => {
7873
- if (typeof arg1 === "string") {
7975
+ if (typeof arg1 === "string")
7874
7976
  this.#path = arg1;
7875
- } else {
7977
+ else {
7876
7978
  this.#path = "*";
7877
7979
  handlers.unshift(arg1);
7878
7980
  }
7879
7981
  handlers.forEach((handler) => {
7880
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
7982
+ this.#addRoute("ALL", this.#path, handler);
7881
7983
  });
7882
7984
  return this;
7883
7985
  };
@@ -7886,7 +7988,7 @@ var Hono = class _Hono {
7886
7988
  this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
7887
7989
  }
7888
7990
  #clone() {
7889
- const clone = new _Hono({
7991
+ const clone = new Hono2({
7890
7992
  router: this.router,
7891
7993
  getPath: this.getPath
7892
7994
  });
@@ -7901,13 +8003,13 @@ var Hono = class _Hono {
7901
8003
  const subApp = this.basePath(path);
7902
8004
  app.routes.map((r) => {
7903
8005
  let handler;
7904
- if (app.errorHandler === errorHandler) {
8006
+ if (app.errorHandler === errorHandler)
7905
8007
  handler = r.handler;
7906
- } else {
8008
+ else {
7907
8009
  handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
7908
8010
  handler[COMPOSED_HANDLER] = r.handler;
7909
8011
  }
7910
- subApp.#addRoute(r.method, r.path, handler);
8012
+ subApp.#addRoute(r.method, r.path, handler, r.basePath);
7911
8013
  });
7912
8014
  return this;
7913
8015
  }
@@ -7928,15 +8030,14 @@ var Hono = class _Hono {
7928
8030
  let replaceRequest;
7929
8031
  let optionHandler;
7930
8032
  if (options) {
7931
- if (typeof options === "function") {
8033
+ if (typeof options === "function")
7932
8034
  optionHandler = options;
7933
- } else {
8035
+ else {
7934
8036
  optionHandler = options.optionHandler;
7935
- if (options.replaceRequest === false) {
8037
+ if (options.replaceRequest === false)
7936
8038
  replaceRequest = (request) => request;
7937
- } else {
8039
+ else
7938
8040
  replaceRequest = options.replaceRequest;
7939
- }
7940
8041
  }
7941
8042
  }
7942
8043
  const getOptions = optionHandler ? (c) => {
@@ -7949,42 +8050,38 @@ var Hono = class _Hono {
7949
8050
  } catch {}
7950
8051
  return [c.env, executionContext];
7951
8052
  };
7952
- replaceRequest ||= (() => {
7953
- const mergedPath = mergePath(this._basePath, path);
7954
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
7955
- return (request) => {
7956
- const url = new URL(request.url);
7957
- url.pathname = url.pathname.slice(pathPrefixLength) || "/";
7958
- return new Request(url, request);
7959
- };
7960
- })();
8053
+ const defaultReplaceRequest = (c) => {
8054
+ const mountedRoutePath = routePath(c);
8055
+ return createMountedRequest(c, mountedRoutePath.replace(/\/?\*$/, ""), mountedRoutePath);
8056
+ };
7961
8057
  const handler = async (c, next) => {
7962
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
7963
- if (res) {
8058
+ const res = await applicationHandler(replaceRequest ? replaceRequest(c.req.raw) : defaultReplaceRequest(c), ...getOptions(c));
8059
+ if (res)
7964
8060
  return res;
7965
- }
7966
8061
  await next();
7967
8062
  };
7968
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
8063
+ this.#addRoute("ALL", mergePath(path, "*"), handler);
7969
8064
  return this;
7970
8065
  }
7971
- #addRoute(method, path, handler) {
7972
- method = method.toUpperCase();
8066
+ #addRoute(method, path, handler, baseRoutePath) {
7973
8067
  path = mergePath(this._basePath, path);
7974
- const r = { basePath: this._basePath, path, method, handler };
8068
+ const r = {
8069
+ basePath: baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath,
8070
+ path,
8071
+ method,
8072
+ handler
8073
+ };
7975
8074
  this.router.add(method, path, [handler, r]);
7976
8075
  this.routes.push(r);
7977
8076
  }
7978
8077
  #handleError(err, c) {
7979
- if (err instanceof Error) {
8078
+ if (err instanceof Error)
7980
8079
  return this.errorHandler(err, c);
7981
- }
7982
8080
  throw err;
7983
8081
  }
7984
8082
  #dispatch(request, executionCtx, env, method) {
7985
- if (method === "HEAD") {
8083
+ if (method === "HEAD")
7986
8084
  return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
7987
- }
7988
8085
  const path = this.getPath(request, { env });
7989
8086
  const matchResult = this.router.match(method, path);
7990
8087
  const c = new Context(request, {
@@ -8009,9 +8106,8 @@ var Hono = class _Hono {
8009
8106
  return (async () => {
8010
8107
  try {
8011
8108
  const context = await composed(c);
8012
- if (!context.finalized) {
8109
+ if (!context.finalized)
8013
8110
  throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
8014
- }
8015
8111
  return context.res;
8016
8112
  } catch (err) {
8017
8113
  return this.#handleError(err, c);
@@ -8022,9 +8118,8 @@ var Hono = class _Hono {
8022
8118
  return this.#dispatch(request, rest[1], rest[0], request.method);
8023
8119
  };
8024
8120
  request = (input, requestInit, Env, executionCtx) => {
8025
- if (input instanceof Request) {
8121
+ if (input instanceof Request)
8026
8122
  return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
8027
- }
8028
8123
  input = input.toString();
8029
8124
  return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
8030
8125
  };
@@ -8035,20 +8130,21 @@ var Hono = class _Hono {
8035
8130
  };
8036
8131
  };
8037
8132
 
8133
+ // node_modules/hono/dist/router/utils.js
8134
+ var createNullObject = () => Object.create(null);
8135
+
8038
8136
  // node_modules/hono/dist/router/reg-exp-router/matcher.js
8039
8137
  var emptyParam = [];
8040
8138
  function match(method, path) {
8041
8139
  const matchers = this.buildAllMatchers();
8042
8140
  const match2 = (method2, path2) => {
8043
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
8141
+ const matcher = matchers[method2] || matchers["ALL"];
8044
8142
  const staticMatch = matcher[2][path2];
8045
- if (staticMatch) {
8143
+ if (staticMatch)
8046
8144
  return staticMatch;
8047
- }
8048
8145
  const match3 = path2.match(matcher[0]);
8049
- if (!match3) {
8146
+ if (!match3)
8050
8147
  return [[], emptyParam];
8051
- }
8052
8148
  const index2 = match3.indexOf("", 1);
8053
8149
  return [matcher[1][index2], match3];
8054
8150
  };
@@ -8058,104 +8154,101 @@ function match(method, path) {
8058
8154
 
8059
8155
  // node_modules/hono/dist/router/reg-exp-router/node.js
8060
8156
  var LABEL_REG_EXP_STR = "[^/]+";
8061
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
8062
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
8063
- var PATH_ERROR = /* @__PURE__ */ Symbol();
8064
- var regExpMetaChars = new Set(".\\+*[^]$()");
8157
+ var ONLY_WILDCARD_REG_EXP_STR = "[^]*";
8158
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/[^]*)";
8159
+ var PATH_ERROR = Symbol();
8160
+ var regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
8065
8161
  function compareKey(a, b) {
8066
- if (a.length === 1) {
8162
+ if (a.length === 1)
8067
8163
  return b.length === 1 ? a < b ? -1 : 1 : -1;
8068
- }
8069
- if (b.length === 1) {
8070
- return 1;
8071
- }
8072
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
8164
+ if (b.length === 1)
8073
8165
  return 1;
8074
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
8166
+ if (a === "[^]*" || a === "(?:|/[^]*)")
8167
+ return b === "[^]*" ? -1 : 1;
8168
+ else if (b === "[^]*" || b === "(?:|/[^]*)")
8075
8169
  return -1;
8076
- }
8077
- if (a === LABEL_REG_EXP_STR) {
8170
+ if (a === "[^/]+")
8078
8171
  return 1;
8079
- } else if (b === LABEL_REG_EXP_STR) {
8172
+ else if (b === "[^/]+")
8080
8173
  return -1;
8081
- }
8082
8174
  return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
8083
8175
  }
8084
- var Node = class _Node {
8176
+ var Node = class Node2 {
8085
8177
  #index;
8086
8178
  #varIndex;
8087
- #children = /* @__PURE__ */ Object.create(null);
8088
- insert(tokens, index2, paramMap, context, pathErrorCheckOnly) {
8089
- if (tokens.length === 0) {
8090
- if (this.#index !== undefined) {
8091
- throw PATH_ERROR;
8092
- }
8093
- if (pathErrorCheckOnly) {
8094
- return;
8095
- }
8096
- this.#index = index2;
8097
- return;
8098
- }
8099
- const [token, ...restTokens] = tokens;
8100
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
8101
- let node;
8102
- if (pattern) {
8103
- const name = pattern[1];
8104
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
8105
- if (name && pattern[2]) {
8106
- if (regexpStr === ".*") {
8107
- throw PATH_ERROR;
8108
- }
8109
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
8110
- if (/\((?!\?:)/.test(regexpStr)) {
8111
- throw PATH_ERROR;
8112
- }
8113
- }
8114
- node = this.#children[regexpStr];
8115
- if (!node) {
8116
- if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
8117
- throw PATH_ERROR;
8118
- }
8119
- if (pathErrorCheckOnly) {
8120
- return;
8179
+ #children = createNullObject();
8180
+ insert(tokens, index2, paramMap, context, keys) {
8181
+ let node = this;
8182
+ for (let i = 0, len = tokens.length;i < len; i++) {
8183
+ const token = tokens[i];
8184
+ const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? [
8185
+ "",
8186
+ "",
8187
+ ONLY_WILDCARD_REG_EXP_STR
8188
+ ] : [
8189
+ "",
8190
+ "",
8191
+ LABEL_REG_EXP_STR
8192
+ ] : null : token === "/*" ? [
8193
+ "",
8194
+ "",
8195
+ TAIL_WILDCARD_REG_EXP_STR
8196
+ ] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
8197
+ let nextNode;
8198
+ if (pattern) {
8199
+ const name = pattern[1];
8200
+ let regexpStr = pattern[2] || "[^/]+";
8201
+ if (name && pattern[2]) {
8202
+ if (new RegExp(regexpStr).test(""))
8203
+ throw PATH_ERROR;
8204
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
8205
+ if (/\((?!\?:)/.test(regexpStr))
8206
+ throw PATH_ERROR;
8207
+ if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr))
8208
+ throw PATH_ERROR;
8209
+ }
8210
+ keys.push(regexpStr);
8211
+ nextNode = node.#children[regexpStr];
8212
+ if (!nextNode) {
8213
+ if (regexpStr !== "[^]*" && regexpStr !== "(?:|/[^]*)") {
8214
+ for (const k in node.#children)
8215
+ if ((regexpStr.length > 1 || k.length > 1) && k !== "[^]*" && k !== "(?:|/[^]*)")
8216
+ throw PATH_ERROR;
8217
+ }
8218
+ nextNode = node.#children[regexpStr] = new Node2;
8121
8219
  }
8122
- node = this.#children[regexpStr] = new _Node;
8123
8220
  if (name !== "") {
8124
- node.#varIndex = context.varIndex++;
8221
+ nextNode.#varIndex ??= context.varIndex++;
8222
+ paramMap.push([name, nextNode.#varIndex]);
8125
8223
  }
8126
- }
8127
- if (!pathErrorCheckOnly && name !== "") {
8128
- paramMap.push([name, node.#varIndex]);
8129
- }
8130
- } else {
8131
- node = this.#children[token];
8132
- if (!node) {
8133
- if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
8134
- throw PATH_ERROR;
8135
- }
8136
- if (pathErrorCheckOnly) {
8137
- return;
8224
+ } else {
8225
+ keys.push(token);
8226
+ nextNode = node.#children[token];
8227
+ if (!nextNode) {
8228
+ for (const k in node.#children)
8229
+ if (k.length > 1 && k !== "[^]*" && k !== "(?:|/[^]*)")
8230
+ throw PATH_ERROR;
8231
+ nextNode = node.#children[token] = new Node2;
8138
8232
  }
8139
- node = this.#children[token] = new _Node;
8140
8233
  }
8234
+ node = nextNode;
8141
8235
  }
8142
- node.insert(restTokens, index2, paramMap, context, pathErrorCheckOnly);
8236
+ if (node.#index !== undefined)
8237
+ throw PATH_ERROR;
8238
+ node.#index = index2;
8143
8239
  }
8144
8240
  buildRegExpStr() {
8145
- const childKeys = Object.keys(this.#children).sort(compareKey);
8146
- const strList = childKeys.map((k) => {
8241
+ const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
8147
8242
  const c = this.#children[k];
8148
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
8149
- });
8150
- if (typeof this.#index === "number") {
8243
+ const childStr = c.buildRegExpStr();
8244
+ return childStr === "" ? "" : (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr;
8245
+ }).filter(Boolean);
8246
+ if (typeof this.#index === "number" && this.#index !== -1)
8151
8247
  strList.unshift(`#${this.#index}`);
8152
- }
8153
- if (strList.length === 0) {
8248
+ if (strList.length === 0)
8154
8249
  return "";
8155
- }
8156
- if (strList.length === 1) {
8250
+ if (strList.length === 1)
8157
8251
  return strList[0];
8158
- }
8159
8252
  return "(?:" + strList.join("|") + ")";
8160
8253
  }
8161
8254
  };
@@ -8164,40 +8257,58 @@ var Node = class _Node {
8164
8257
  var Trie = class {
8165
8258
  #context = { varIndex: 0 };
8166
8259
  #root = new Node;
8167
- insert(path, index2, pathErrorCheckOnly) {
8260
+ #index = 0;
8261
+ paths = createNullObject();
8262
+ insert(path, isStatic) {
8263
+ const keys = [];
8264
+ if (isStatic) {
8265
+ this.#root.insert(path.split(""), -1, [], this.#context, keys);
8266
+ this.paths[path] = [
8267
+ -1,
8268
+ [],
8269
+ keys
8270
+ ];
8271
+ return;
8272
+ }
8168
8273
  const paramAssoc = [];
8169
8274
  const groups = [];
8275
+ let markedPath = path;
8170
8276
  for (let i = 0;; ) {
8171
8277
  let replaced = false;
8172
- path = path.replace(/\{[^}]+\}/g, (m) => {
8278
+ markedPath = markedPath.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g, (m) => {
8173
8279
  const mark = `@\\${i}`;
8174
8280
  groups[i] = [mark, m];
8175
8281
  i++;
8176
8282
  replaced = true;
8177
8283
  return mark;
8178
8284
  });
8179
- if (!replaced) {
8285
+ if (!replaced)
8180
8286
  break;
8181
- }
8182
8287
  }
8183
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
8288
+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./gs) || [];
8184
8289
  for (let i = groups.length - 1;i >= 0; i--) {
8185
8290
  const [mark] = groups[i];
8186
- for (let j = tokens.length - 1;j >= 0; j--) {
8291
+ for (let j = tokens.length - 1;j >= 0; j--)
8187
8292
  if (tokens[j].indexOf(mark) !== -1) {
8188
8293
  tokens[j] = tokens[j].replace(mark, groups[i][1]);
8189
8294
  break;
8190
8295
  }
8191
- }
8192
8296
  }
8193
- this.#root.insert(tokens, index2, paramAssoc, this.#context, pathErrorCheckOnly);
8194
- return paramAssoc;
8297
+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, keys);
8298
+ this.paths[path] = [
8299
+ this.#index++,
8300
+ paramAssoc,
8301
+ keys
8302
+ ];
8195
8303
  }
8196
8304
  buildRegExp() {
8197
8305
  let regexp = this.#root.buildRegExpStr();
8198
- if (regexp === "") {
8199
- return [/^$/, [], []];
8200
- }
8306
+ if (regexp === "")
8307
+ return [
8308
+ /^$/,
8309
+ [],
8310
+ []
8311
+ ];
8201
8312
  let captureIndex = 0;
8202
8313
  const indexReplacementMap = [];
8203
8314
  const paramReplacementMap = [];
@@ -8212,247 +8323,107 @@ var Trie = class {
8212
8323
  }
8213
8324
  return "";
8214
8325
  });
8215
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
8326
+ return [
8327
+ new RegExp(`^${regexp}`),
8328
+ indexReplacementMap,
8329
+ paramReplacementMap
8330
+ ];
8216
8331
  }
8217
8332
  };
8218
8333
 
8219
8334
  // node_modules/hono/dist/router/reg-exp-router/router.js
8220
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
8221
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
8222
- function buildWildcardRegExp(path) {
8223
- return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
8224
- }
8225
- function clearWildcardRegExpCache() {
8226
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
8227
- }
8228
- function buildMatcherFromPreprocessedRoutes(routes) {
8229
- const trie = new Trie;
8230
- const handlerData = [];
8231
- if (routes.length === 0) {
8232
- return nullMatcher;
8233
- }
8234
- const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
8235
- const staticMap = /* @__PURE__ */ Object.create(null);
8236
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
8237
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
8238
- if (pathErrorCheckOnly) {
8239
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
8240
- } else {
8241
- j++;
8242
- }
8243
- let paramAssoc;
8244
- try {
8245
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
8246
- } catch (e) {
8247
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
8248
- }
8249
- if (pathErrorCheckOnly) {
8250
- continue;
8251
- }
8252
- handlerData[j] = handlers.map(([h, paramCount]) => {
8253
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
8254
- paramCount -= 1;
8255
- for (;paramCount >= 0; paramCount--) {
8256
- const [key, value] = paramAssoc[paramCount];
8257
- paramIndexMap[key] = value;
8258
- }
8259
- return [h, paramIndexMap];
8260
- });
8261
- }
8262
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
8263
- for (let i = 0, len = handlerData.length;i < len; i++) {
8264
- for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
8265
- const map = handlerData[i][j]?.[1];
8266
- if (!map) {
8267
- continue;
8268
- }
8269
- const keys = Object.keys(map);
8270
- for (let k = 0, len3 = keys.length;k < len3; k++) {
8271
- map[keys[k]] = paramReplacementMap[map[keys[k]]];
8272
- }
8273
- }
8274
- }
8275
- const handlerMap = [];
8276
- for (const i in indexReplacementMap) {
8277
- handlerMap[i] = handlerData[indexReplacementMap[i]];
8278
- }
8279
- return [regexp, handlerMap, staticMap];
8280
- }
8281
- function findMiddleware(middleware, path) {
8282
- if (!middleware) {
8283
- return;
8284
- }
8285
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
8286
- if (buildWildcardRegExp(k).test(path)) {
8287
- return [...middleware[k]];
8288
- }
8289
- }
8290
- return;
8335
+ function endsWithWildcard(keys) {
8336
+ const tail = keys[keys.length - 1];
8337
+ return tail === "[^]*" || tail === "(?:|/[^]*)";
8338
+ }
8339
+ function covers(wildcard, target) {
8340
+ const last = wildcard.length - 1;
8341
+ for (let i = 0;i < last; i++)
8342
+ if (wildcard[i] !== target[i])
8343
+ return false;
8344
+ return wildcard[last] === "[^]*" || target.length === last || target[last] === "/";
8291
8345
  }
8292
8346
  var RegExpRouter = class {
8293
8347
  name = "RegExpRouter";
8294
- #middleware;
8295
- #routes;
8348
+ #handlers;
8349
+ #tries;
8296
8350
  constructor() {
8297
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
8298
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
8351
+ this.#handlers = { ["ALL"]: [] };
8352
+ this.#tries = { ["ALL"]: new Trie };
8353
+ }
8354
+ #insertPath(method, path) {
8355
+ try {
8356
+ this.#tries[method].insert(path, !/\*|\/:/.test(path));
8357
+ } catch (e) {
8358
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
8359
+ }
8299
8360
  }
8300
8361
  add(method, path, handler) {
8301
- const middleware = this.#middleware;
8302
- const routes = this.#routes;
8303
- if (!middleware || !routes) {
8362
+ const handlers = this.#handlers;
8363
+ if (!handlers)
8304
8364
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
8305
- }
8306
- if (!middleware[method]) {
8307
- [middleware, routes].forEach((handlerMap) => {
8308
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
8309
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
8310
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
8311
- });
8312
- });
8313
- }
8314
- if (path === "/*") {
8365
+ const tries = this.#tries;
8366
+ if (!handlers[method]) {
8367
+ tries[method] = new Trie;
8368
+ handlers[method] = [...handlers["ALL"]];
8369
+ for (const p in tries["ALL"].paths)
8370
+ this.#insertPath(method, p);
8371
+ }
8372
+ if (path === "/*")
8315
8373
  path = "*";
8316
- }
8317
- const paramCount = (path.match(/\/:/g) || []).length;
8318
- if (/\*$/.test(path)) {
8319
- const re = buildWildcardRegExp(path);
8320
- if (method === METHOD_NAME_ALL) {
8321
- Object.keys(middleware).forEach((m) => {
8322
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
8323
- });
8324
- } else {
8325
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
8326
- }
8327
- Object.keys(middleware).forEach((m) => {
8328
- if (method === METHOD_NAME_ALL || method === m) {
8329
- Object.keys(middleware[m]).forEach((p) => {
8330
- re.test(p) && middleware[m][p].push([handler, paramCount]);
8331
- });
8332
- }
8333
- });
8334
- Object.keys(routes).forEach((m) => {
8335
- if (method === METHOD_NAME_ALL || method === m) {
8336
- Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
8337
- }
8338
- });
8339
- return;
8340
- }
8374
+ const methods = method === "ALL" ? Object.keys(handlers) : [method];
8341
8375
  const paths = checkOptionalParameter(path) || [path];
8342
- for (let i = 0, len = paths.length;i < len; i++) {
8343
- const path2 = paths[i];
8344
- Object.keys(routes).forEach((m) => {
8345
- if (method === METHOD_NAME_ALL || method === m) {
8346
- routes[m][path2] ||= [
8347
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
8348
- ];
8349
- routes[m][path2].push([handler, paramCount - len + i + 1]);
8350
- }
8351
- });
8352
- }
8376
+ for (const path2 of paths)
8377
+ for (const m of methods) {
8378
+ if (!tries[m].paths[path2])
8379
+ this.#insertPath(m, path2);
8380
+ handlers[m].push([handler, path2]);
8381
+ }
8353
8382
  }
8354
8383
  match = match;
8355
8384
  buildAllMatchers() {
8356
- const matchers = /* @__PURE__ */ Object.create(null);
8357
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
8358
- matchers[method] ||= this.#buildMatcher(method);
8359
- });
8360
- this.#middleware = this.#routes = undefined;
8361
- clearWildcardRegExpCache();
8385
+ const matchers = createNullObject();
8386
+ for (const method of Object.keys(this.#handlers))
8387
+ matchers[method] = this.#buildMatcher(method);
8388
+ this.#handlers = this.#tries = undefined;
8362
8389
  return matchers;
8363
8390
  }
8364
8391
  #buildMatcher(method) {
8365
- const routes = [];
8366
- let hasOwnRoute = method === METHOD_NAME_ALL;
8367
- [this.#middleware, this.#routes].forEach((r) => {
8368
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
8369
- if (ownRoute.length !== 0) {
8370
- hasOwnRoute ||= true;
8371
- routes.push(...ownRoute);
8372
- } else if (method !== METHOD_NAME_ALL) {
8373
- routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
8374
- }
8375
- });
8376
- if (!hasOwnRoute) {
8377
- return null;
8378
- } else {
8379
- return buildMatcherFromPreprocessedRoutes(routes);
8380
- }
8392
+ const handlers = this.#handlers[method];
8393
+ const trie = this.#tries[method];
8394
+ const staticMap = createNullObject();
8395
+ const handlerData = [];
8396
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
8397
+ const own = createNullObject();
8398
+ const entries = handlers.map(([h, p], i) => {
8399
+ (own[p] ??= []).push(i);
8400
+ return [h, trie.paths[p][1].reduceRight((map, [key, varIndex]) => {
8401
+ map[key] = paramReplacementMap[varIndex];
8402
+ return map;
8403
+ }, createNullObject())];
8404
+ });
8405
+ const wildcards = Object.keys(own).filter((p) => endsWithWildcard(trie.paths[p][2]));
8406
+ for (const path in trie.paths) {
8407
+ const [index2, , keys] = trie.paths[path];
8408
+ const indexes = [...own[path]];
8409
+ for (const p of wildcards)
8410
+ if (p !== path && covers(trie.paths[p][2], keys))
8411
+ indexes.push(...own[p]);
8412
+ const data = indexes.sort((a, b) => a - b).map((i) => entries[i]);
8413
+ if (index2 === -1) {
8414
+ const last = Math.max(-1, ...data.flatMap(([, map]) => Object.values(map)));
8415
+ staticMap[path] = [data, last === -1 ? emptyParam : path.match(regexp).slice(0, last + 1)];
8416
+ } else
8417
+ handlerData[index2] = data;
8418
+ }
8419
+ return [
8420
+ regexp,
8421
+ indexReplacementMap.map((i) => handlerData[i]),
8422
+ staticMap
8423
+ ];
8381
8424
  }
8382
8425
  };
8383
8426
 
8384
- // node_modules/hono/dist/router/reg-exp-router/prepared-router.js
8385
- var PreparedRegExpRouter = class {
8386
- name = "PreparedRegExpRouter";
8387
- #matchers;
8388
- #relocateMap;
8389
- constructor(matchers, relocateMap) {
8390
- this.#matchers = matchers;
8391
- this.#relocateMap = relocateMap;
8392
- }
8393
- #addWildcard(method, handlerData) {
8394
- const matcher = this.#matchers[method];
8395
- matcher[1].forEach((list) => list && list.push(handlerData));
8396
- Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
8397
- }
8398
- #addPath(method, path, handler, indexes, map) {
8399
- const matcher = this.#matchers[method];
8400
- if (!map) {
8401
- matcher[2][path][0].push([handler, {}]);
8402
- } else {
8403
- indexes.forEach((index2) => {
8404
- if (typeof index2 === "number") {
8405
- matcher[1][index2].push([handler, map]);
8406
- } else {
8407
- matcher[2][index2 || path][0].push([handler, map]);
8408
- }
8409
- });
8410
- }
8411
- }
8412
- add(method, path, handler) {
8413
- if (!this.#matchers[method]) {
8414
- const all = this.#matchers[METHOD_NAME_ALL];
8415
- const staticMap = {};
8416
- for (const key in all[2]) {
8417
- staticMap[key] = [all[2][key][0].slice(), emptyParam];
8418
- }
8419
- this.#matchers[method] = [
8420
- all[0],
8421
- all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
8422
- staticMap
8423
- ];
8424
- }
8425
- if (path === "/*" || path === "*") {
8426
- const handlerData = [handler, {}];
8427
- if (method === METHOD_NAME_ALL) {
8428
- for (const m in this.#matchers) {
8429
- this.#addWildcard(m, handlerData);
8430
- }
8431
- } else {
8432
- this.#addWildcard(method, handlerData);
8433
- }
8434
- return;
8435
- }
8436
- const data = this.#relocateMap[path];
8437
- if (!data) {
8438
- throw new Error(`Path ${path} is not registered`);
8439
- }
8440
- for (const [indexes, map] of data) {
8441
- if (method === METHOD_NAME_ALL) {
8442
- for (const m in this.#matchers) {
8443
- this.#addPath(m, path, handler, indexes, map);
8444
- }
8445
- } else {
8446
- this.#addPath(method, path, handler, indexes, map);
8447
- }
8448
- }
8449
- }
8450
- buildAllMatchers() {
8451
- return this.#matchers;
8452
- }
8453
- match = match;
8454
- };
8455
-
8456
8427
  // node_modules/hono/dist/router/smart-router/router.js
8457
8428
  var SmartRouter = class {
8458
8429
  name = "SmartRouter";
@@ -8462,15 +8433,17 @@ var SmartRouter = class {
8462
8433
  this.#routers = init.routers;
8463
8434
  }
8464
8435
  add(method, path, handler) {
8465
- if (!this.#routes) {
8436
+ if (!this.#routes)
8466
8437
  throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
8467
- }
8468
- this.#routes.push([method, path, handler]);
8438
+ this.#routes.push([
8439
+ method,
8440
+ path,
8441
+ handler
8442
+ ]);
8469
8443
  }
8470
8444
  match(method, path) {
8471
- if (!this.#routes) {
8445
+ if (!this.#routes)
8472
8446
  throw new Error("Fatal error");
8473
- }
8474
8447
  const routers = this.#routers;
8475
8448
  const routes = this.#routes;
8476
8449
  const len = routers.length;
@@ -8479,14 +8452,12 @@ var SmartRouter = class {
8479
8452
  for (;i < len; i++) {
8480
8453
  const router = routers[i];
8481
8454
  try {
8482
- for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
8455
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++)
8483
8456
  router.add(...routes[i2]);
8484
- }
8485
8457
  res = router.match(method, path);
8486
8458
  } catch (e) {
8487
- if (e instanceof UnsupportedPathError) {
8459
+ if (e instanceof UnsupportedPathError)
8488
8460
  continue;
8489
- }
8490
8461
  throw e;
8491
8462
  }
8492
8463
  this.match = router.match.bind(router);
@@ -8494,92 +8465,62 @@ var SmartRouter = class {
8494
8465
  this.#routes = undefined;
8495
8466
  break;
8496
8467
  }
8497
- if (i === len) {
8468
+ if (i === len)
8498
8469
  throw new Error("Fatal error");
8499
- }
8500
8470
  this.name = `SmartRouter + ${this.activeRouter.name}`;
8501
8471
  return res;
8502
8472
  }
8503
8473
  get activeRouter() {
8504
- if (this.#routes || this.#routers.length !== 1) {
8474
+ if (this.#routes || this.#routers.length !== 1)
8505
8475
  throw new Error("No active router has been determined yet.");
8506
- }
8507
8476
  return this.#routers[0];
8508
8477
  }
8509
8478
  };
8510
8479
 
8511
8480
  // node_modules/hono/dist/router/trie-router/node.js
8512
- var emptyParams = /* @__PURE__ */ Object.create(null);
8513
- var hasChildren = (children) => {
8514
- for (const _ in children) {
8515
- return true;
8516
- }
8517
- return false;
8518
- };
8519
- var Node2 = class _Node2 {
8520
- #methods;
8521
- #children;
8522
- #patterns;
8523
- #order = 0;
8481
+ var emptyParams = createNullObject();
8482
+ var order = 0;
8483
+ var Node3 = class Node4 {
8484
+ #methods = [];
8485
+ #children = createNullObject();
8486
+ #patterns = [];
8487
+ #pattern;
8524
8488
  #params = emptyParams;
8525
- constructor(method, handler, children) {
8526
- this.#children = children || /* @__PURE__ */ Object.create(null);
8527
- this.#methods = [];
8528
- if (method && handler) {
8529
- const m = /* @__PURE__ */ Object.create(null);
8530
- m[method] = { handler, possibleKeys: [], score: 0 };
8531
- this.#methods = [m];
8532
- }
8533
- this.#patterns = [];
8534
- }
8535
8489
  insert(method, path, handler) {
8536
- this.#order = ++this.#order;
8537
8490
  let curNode = this;
8538
8491
  const parts = splitRoutingPath(path);
8539
- const possibleKeys = [];
8540
- for (let i = 0, len = parts.length;i < len; i++) {
8541
- const p = parts[i];
8542
- const nextP = parts[i + 1];
8543
- const pattern = getPattern(p, nextP);
8544
- const key = Array.isArray(pattern) ? pattern[0] : p;
8545
- if (key in curNode.#children) {
8546
- curNode = curNode.#children[key];
8547
- if (pattern) {
8548
- possibleKeys.push(pattern[1]);
8549
- }
8550
- continue;
8551
- }
8552
- curNode.#children[key] = new _Node2;
8553
- if (pattern) {
8554
- curNode.#patterns.push(pattern);
8555
- possibleKeys.push(pattern[1]);
8556
- }
8557
- curNode = curNode.#children[key];
8558
- }
8559
- curNode.#methods.push({
8560
- [method]: {
8561
- handler,
8562
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
8563
- score: this.#order
8564
- }
8565
- });
8566
- return curNode;
8492
+ const possibleKeys = /* @__PURE__ */ new Set;
8493
+ let i = 0;
8494
+ for (const p of parts) {
8495
+ const nextP = parts[++i];
8496
+ const pattern = getPattern(p, nextP) || (nextP === undefined && p && p.indexOf("*") === p.length - 1 ? p : null);
8497
+ const isParam = Array.isArray(pattern);
8498
+ const key = isParam ? pattern[0] : pattern || p;
8499
+ const child = curNode.#children[key] ||= new Node4;
8500
+ if (pattern && !child.#pattern) {
8501
+ child.#pattern = pattern;
8502
+ curNode.#patterns.push(child);
8503
+ }
8504
+ curNode = child;
8505
+ if (isParam)
8506
+ possibleKeys.add(pattern[1]);
8507
+ }
8508
+ curNode.#methods.push({ [method]: {
8509
+ handler,
8510
+ possibleKeys: [...possibleKeys],
8511
+ score: ++order
8512
+ } });
8567
8513
  }
8568
8514
  #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
8569
8515
  for (let i = 0, len = node.#methods.length;i < len; i++) {
8570
8516
  const m = node.#methods[i];
8571
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
8572
- const processedSet = {};
8573
- if (handlerSet !== undefined) {
8574
- handlerSet.params = /* @__PURE__ */ Object.create(null);
8517
+ const handlerSet = m[method] || m["ALL"];
8518
+ if (handlerSet) {
8519
+ handlerSet.params = createNullObject();
8575
8520
  handlerSets.push(handlerSet);
8576
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
8577
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
8578
- const key = handlerSet.possibleKeys[i2];
8579
- const processed = processedSet[handlerSet.score];
8580
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
8581
- processedSet[handlerSet.score] = true;
8582
- }
8521
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
8522
+ const key = handlerSet.possibleKeys[i2];
8523
+ handlerSet.params[key] = params?.[key] && !i2 ? params[key] : nodeParams[key] ?? params?.[key];
8583
8524
  }
8584
8525
  }
8585
8526
  }
@@ -8587,8 +8528,7 @@ var Node2 = class _Node2 {
8587
8528
  search(method, path) {
8588
8529
  const handlerSets = [];
8589
8530
  this.#params = emptyParams;
8590
- const curNode = this;
8591
- let curNodes = [curNode];
8531
+ let curNodes = [this];
8592
8532
  const parts = splitPath2(path);
8593
8533
  const curNodesQueue = [];
8594
8534
  const len = parts.length;
@@ -8603,61 +8543,61 @@ var Node2 = class _Node2 {
8603
8543
  if (nextNode) {
8604
8544
  nextNode.#params = node.#params;
8605
8545
  if (isLast) {
8606
- if (nextNode.#children["*"]) {
8546
+ if (nextNode.#children["*"])
8607
8547
  this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
8608
- }
8609
8548
  this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
8610
- } else {
8549
+ } else
8611
8550
  tempNodes.push(nextNode);
8612
- }
8613
8551
  }
8614
- for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
8615
- const pattern = node.#patterns[k];
8552
+ for (const child of node.#patterns) {
8553
+ const pattern = child.#pattern;
8616
8554
  const params = node.#params === emptyParams ? {} : { ...node.#params };
8617
- if (pattern === "*") {
8618
- const astNode = node.#children["*"];
8619
- if (astNode) {
8620
- this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
8621
- astNode.#params = params;
8622
- tempNodes.push(astNode);
8555
+ if (typeof pattern === "string") {
8556
+ if (pattern === "*" || part.startsWith(pattern.slice(0, -1))) {
8557
+ this.#pushHandlerSets(handlerSets, child, method, node.#params);
8558
+ if (pattern === "*") {
8559
+ child.#params = params;
8560
+ tempNodes.push(child);
8561
+ }
8623
8562
  }
8624
8563
  continue;
8625
8564
  }
8626
- const [key, name, matcher] = pattern;
8627
- if (!part && !(matcher instanceof RegExp)) {
8565
+ const [, name, matcher] = pattern;
8566
+ if (!part && matcher === true)
8628
8567
  continue;
8629
- }
8630
- const child = node.#children[key];
8631
- if (matcher instanceof RegExp) {
8632
- if (partOffsets === null) {
8633
- partOffsets = new Array(len);
8568
+ if (matcher !== true) {
8569
+ if (!partOffsets) {
8570
+ partOffsets = [];
8634
8571
  let offset = path[0] === "/" ? 1 : 0;
8635
8572
  for (let p = 0;p < len; p++) {
8636
8573
  partOffsets[p] = offset;
8637
8574
  offset += parts[p].length + 1;
8638
8575
  }
8639
8576
  }
8640
- const restPathString = path.substring(partOffsets[i]);
8577
+ const restPathString = path.slice(partOffsets[i]);
8641
8578
  const m = matcher.exec(restPathString);
8642
8579
  if (m) {
8643
- params[name] = m[0];
8580
+ if (!Object.hasOwn(params, name))
8581
+ params[name] = m[0];
8644
8582
  this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
8645
- if (hasChildren(child.#children)) {
8583
+ if (m[0].length === restPathString.length && child.#children["*"])
8584
+ this.#pushHandlerSets(handlerSets, child.#children["*"], method, node.#params, params);
8585
+ for (const _ in child.#children) {
8646
8586
  child.#params = params;
8647
- const componentCount = m[0].match(/\//)?.length ?? 0;
8648
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
8649
- targetCurNodes.push(child);
8587
+ const componentCount = m[0].match(/\//g)?.length ?? 0;
8588
+ (curNodesQueue[componentCount] ||= []).push(child);
8589
+ break;
8650
8590
  }
8651
8591
  continue;
8652
8592
  }
8653
8593
  }
8654
8594
  if (matcher === true || matcher.test(part)) {
8655
- params[name] = part;
8595
+ if (!Object.hasOwn(params, name))
8596
+ params[name] = part;
8656
8597
  if (isLast) {
8657
8598
  this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
8658
- if (child.#children["*"]) {
8599
+ if (child.#children["*"])
8659
8600
  this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
8660
- }
8661
8601
  } else {
8662
8602
  child.#params = params;
8663
8603
  tempNodes.push(child);
@@ -8668,11 +8608,10 @@ var Node2 = class _Node2 {
8668
8608
  const shifted = curNodesQueue.shift();
8669
8609
  curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
8670
8610
  }
8671
- if (handlerSets.length > 1) {
8611
+ if (handlerSets[1])
8672
8612
  handlerSets.sort((a, b) => {
8673
8613
  return a.score - b.score;
8674
8614
  });
8675
- }
8676
8615
  return [handlerSets.map(({ handler, params }) => [handler, params])];
8677
8616
  }
8678
8617
  };
@@ -8680,19 +8619,10 @@ var Node2 = class _Node2 {
8680
8619
  // node_modules/hono/dist/router/trie-router/router.js
8681
8620
  var TrieRouter = class {
8682
8621
  name = "TrieRouter";
8683
- #node;
8684
- constructor() {
8685
- this.#node = new Node2;
8686
- }
8622
+ #node = new Node3;
8687
8623
  add(method, path, handler) {
8688
- const results = checkOptionalParameter(path);
8689
- if (results) {
8690
- for (let i = 0, len = results.length;i < len; i++) {
8691
- this.#node.insert(method, results[i], handler);
8692
- }
8693
- return;
8694
- }
8695
- this.#node.insert(method, path, handler);
8624
+ for (const result of checkOptionalParameter(path) || [path])
8625
+ this.#node.insert(method, result, handler);
8696
8626
  }
8697
8627
  match(method, path) {
8698
8628
  return this.#node.search(method, path);
@@ -8700,12 +8630,10 @@ var TrieRouter = class {
8700
8630
  };
8701
8631
 
8702
8632
  // node_modules/hono/dist/hono.js
8703
- var Hono2 = class extends Hono {
8633
+ var Hono3 = class extends Hono {
8704
8634
  constructor(options = {}) {
8705
8635
  super(options);
8706
- this.router = options.router ?? new SmartRouter({
8707
- routers: [new RegExpRouter, new TrieRouter]
8708
- });
8636
+ this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter, new TrieRouter] });
8709
8637
  }
8710
8638
  };
8711
8639
 
@@ -8778,6 +8706,77 @@ function installProcessHandlers(opts) {
8778
8706
  process.off("uncaughtException", excHandler);
8779
8707
  };
8780
8708
  }
8709
+ // src/core/http/body-cap.ts
8710
+ function capRequestBodyStream(ctx, maxBodyBytes) {
8711
+ const original = ctx.req.raw;
8712
+ let tooLarge = false;
8713
+ if (original.body && !original.bodyUsed) {
8714
+ let total = 0;
8715
+ const limited = original.body.pipeThrough(new TransformStream({
8716
+ transform(chunk, controller) {
8717
+ total += chunk.byteLength;
8718
+ if (total > maxBodyBytes) {
8719
+ tooLarge = true;
8720
+ controller.error(new Error("body_too_large"));
8721
+ return;
8722
+ }
8723
+ controller.enqueue(chunk);
8724
+ }
8725
+ }));
8726
+ ctx.req.raw = new Request(original, { body: limited, duplex: "half" });
8727
+ }
8728
+ return { tooLarge: () => tooLarge };
8729
+ }
8730
+ function bodyTooLargeResponse(limit) {
8731
+ return new Response(JSON.stringify({ error: "body_too_large", limit }), {
8732
+ status: 413,
8733
+ headers: { "content-type": "application/json" }
8734
+ });
8735
+ }
8736
+
8737
+ // src/core/http/rate-limit.ts
8738
+ class TenantRateLimiter {
8739
+ buckets = new Map;
8740
+ now;
8741
+ constructor(opts = {}) {
8742
+ this.now = opts.now ?? (() => Date.now());
8743
+ }
8744
+ get bucketCount() {
8745
+ return this.buckets.size;
8746
+ }
8747
+ tryAcquire(tenant, limitPerSecond) {
8748
+ const nowMs = this.now();
8749
+ let bucket = this.buckets.get(tenant);
8750
+ if (!bucket) {
8751
+ bucket = { tokens: limitPerSecond, lastRefillMs: nowMs };
8752
+ this.buckets.set(tenant, bucket);
8753
+ } else {
8754
+ const elapsedMs = Math.max(0, nowMs - bucket.lastRefillMs);
8755
+ if (elapsedMs > 0) {
8756
+ const refill = elapsedMs * limitPerSecond / 1000;
8757
+ bucket.tokens = Math.min(limitPerSecond, bucket.tokens + refill);
8758
+ bucket.lastRefillMs = nowMs;
8759
+ }
8760
+ }
8761
+ if (bucket.tokens >= 1) {
8762
+ bucket.tokens -= 1;
8763
+ return { allowed: true, retryAfterSeconds: 0 };
8764
+ }
8765
+ const deficitMs = (1 - bucket.tokens) / limitPerSecond * 1000;
8766
+ const retryAfterSeconds = Math.max(1, Math.ceil(deficitMs / 1000));
8767
+ return { allowed: false, retryAfterSeconds };
8768
+ }
8769
+ }
8770
+ function rateLimitedResponse(limit, retryAfterSeconds) {
8771
+ return new Response(JSON.stringify({ error: "rate_limited", limit }), {
8772
+ status: 429,
8773
+ headers: {
8774
+ "content-type": "application/json",
8775
+ "retry-after": String(retryAfterSeconds)
8776
+ }
8777
+ });
8778
+ }
8779
+
8781
8780
  // src/core/journal/ring-buffer.ts
8782
8781
  class RingBuffer {
8783
8782
  capacity;
@@ -11186,7 +11185,7 @@ function constantTimeEquals(a2, b2) {
11186
11185
 
11187
11186
  // src/features/admin/endpoints.ts
11188
11187
  function adminRouter(deps) {
11189
- const app = new Hono2;
11188
+ const app = new Hono3;
11190
11189
  app.get("/health", (ctx) => ctx.json({ status: "ok" }));
11191
11190
  app.get("/ready", (ctx) => {
11192
11191
  const ready = deps.ready.current();
@@ -11368,7 +11367,11 @@ var PRIVATE_IPV4_RANGES = [
11368
11367
  [127, 0, 0, 8],
11369
11368
  [169, 254, 0, 16],
11370
11369
  [100, 64, 0, 10],
11371
- [0, 0, 0, 8]
11370
+ [0, 0, 0, 8],
11371
+ [192, 0, 0, 24],
11372
+ [198, 18, 0, 15],
11373
+ [224, 0, 0, 4],
11374
+ [240, 0, 0, 4]
11372
11375
  ];
11373
11376
  function validateUpstreamUrl(raw2, opts = {}) {
11374
11377
  const allowedSchemes = opts.allowedSchemes ?? ["https"];
@@ -11431,12 +11434,49 @@ async function validateUpstreamUrlResolved(raw2, opts = {}) {
11431
11434
  });
11432
11435
  return parsed;
11433
11436
  }
11437
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
11438
+ var DEFAULT_MAX_REDIRECT_HOPS = 5;
11439
+ async function fetchWithRedirectGuard(initialUrl, init, validation, maxRedirects = DEFAULT_MAX_REDIRECT_HOPS) {
11440
+ let currentUrl = initialUrl;
11441
+ let method = init.method;
11442
+ let body = init.body;
11443
+ let redirectsFollowed = 0;
11444
+ for (;; ) {
11445
+ const response = await fetch(currentUrl, {
11446
+ method,
11447
+ headers: init.headers,
11448
+ body: method === "GET" || method === "HEAD" ? undefined : body ?? undefined,
11449
+ redirect: "manual",
11450
+ signal: init.signal
11451
+ });
11452
+ const location = response.headers.get("location");
11453
+ if (!REDIRECT_STATUSES.has(response.status) || !location) {
11454
+ return { response, finalUrl: currentUrl, redirectsFollowed };
11455
+ }
11456
+ await response.body?.cancel();
11457
+ if (redirectsFollowed >= maxRedirects) {
11458
+ throw new UrlValidationError(currentUrl.href, `redirect chain exceeded ${maxRedirects} hop(s); blocked before following Location '${location}'`);
11459
+ }
11460
+ redirectsFollowed++;
11461
+ let nextUrl;
11462
+ try {
11463
+ nextUrl = new URL(location, currentUrl);
11464
+ } catch {
11465
+ throw new UrlValidationError(location, "redirect Location header is not a resolvable URL");
11466
+ }
11467
+ currentUrl = await validateUpstreamUrlResolved(nextUrl.href, validation);
11468
+ if (response.status === 303 || (response.status === 301 || response.status === 302) && method !== "GET" && method !== "HEAD") {
11469
+ method = "GET";
11470
+ body = null;
11471
+ }
11472
+ }
11473
+ }
11434
11474
  function isPrivateHost(hostname) {
11435
11475
  const stripped = hostname.replace(/^\[/, "").replace(/\]$/, "");
11436
11476
  const lowered = stripped.toLowerCase();
11437
11477
  if (lowered === "localhost" || lowered === "ip6-localhost" || lowered === "ip6-loopback")
11438
11478
  return true;
11439
- if (lowered === "::1" || lowered.startsWith("fe80:") || lowered.startsWith("fc") || lowered.startsWith("fd")) {
11479
+ if (isIpLiteral(stripped) && isPrivateIpv6(lowered)) {
11440
11480
  return true;
11441
11481
  }
11442
11482
  const ipv4MappedDotted = lowered.match(/^::ffff:([0-9.]+)$/);
@@ -11457,6 +11497,75 @@ function isPrivateHost(hostname) {
11457
11497
  }
11458
11498
  return false;
11459
11499
  }
11500
+ function expandIpv6(addr) {
11501
+ const halves = addr.split("::");
11502
+ if (halves.length > 2)
11503
+ return null;
11504
+ const parseGroups = (segment) => {
11505
+ if (segment === "")
11506
+ return [];
11507
+ const pieces = segment.split(":");
11508
+ const groups = [];
11509
+ for (let i2 = 0;i2 < pieces.length; i2++) {
11510
+ const piece = pieces[i2] ?? "";
11511
+ if (i2 === pieces.length - 1 && piece.includes(".")) {
11512
+ const octets = piece.split(".").map((o2) => Number.parseInt(o2, 10));
11513
+ if (octets.length !== 4 || octets.some((o2) => Number.isNaN(o2) || o2 < 0 || o2 > 255) || piece.split(".").some((o2) => !/^\d{1,3}$/.test(o2))) {
11514
+ return null;
11515
+ }
11516
+ const [a2 = 0, b2 = 0, c2 = 0, d2 = 0] = octets;
11517
+ groups.push(a2 << 8 | b2, c2 << 8 | d2);
11518
+ continue;
11519
+ }
11520
+ if (piece.length === 0 || piece.length > 4 || !/^[0-9a-f]+$/.test(piece))
11521
+ return null;
11522
+ const value = Number.parseInt(piece, 16);
11523
+ if (Number.isNaN(value))
11524
+ return null;
11525
+ groups.push(value);
11526
+ }
11527
+ return groups;
11528
+ };
11529
+ if (halves.length === 1) {
11530
+ const groups = parseGroups(halves[0] ?? "");
11531
+ return groups && groups.length === 8 ? groups : null;
11532
+ }
11533
+ const head = parseGroups(halves[0] ?? "");
11534
+ const tail = parseGroups(halves[1] ?? "");
11535
+ if (!head || !tail)
11536
+ return null;
11537
+ const missing = 8 - head.length - tail.length;
11538
+ if (missing < 0)
11539
+ return null;
11540
+ return [...head, ...Array(missing).fill(0), ...tail];
11541
+ }
11542
+ function ipv6PrefixMatch(groups, prefixGroups, prefixBits) {
11543
+ let bitsLeft = prefixBits;
11544
+ for (let i2 = 0;i2 < prefixGroups.length && bitsLeft > 0; i2++) {
11545
+ const bits = Math.min(16, bitsLeft);
11546
+ const mask = bits === 16 ? 65535 : 65535 << 16 - bits & 65535;
11547
+ if (((groups[i2] ?? 0) & mask) !== ((prefixGroups[i2] ?? 0) & mask))
11548
+ return false;
11549
+ bitsLeft -= bits;
11550
+ }
11551
+ return true;
11552
+ }
11553
+ function isPrivateIpv6(lowered) {
11554
+ const groups = expandIpv6(lowered);
11555
+ if (!groups)
11556
+ return false;
11557
+ if (groups.every((g2) => g2 === 0))
11558
+ return true;
11559
+ if (groups.slice(0, 7).every((g2) => g2 === 0) && groups[7] === 1)
11560
+ return true;
11561
+ if (ipv6PrefixMatch(groups, [64512], 7))
11562
+ return true;
11563
+ if (ipv6PrefixMatch(groups, [65152], 10))
11564
+ return true;
11565
+ if (ipv6PrefixMatch(groups, [100, 65435, 0, 0, 0, 0], 96))
11566
+ return true;
11567
+ return false;
11568
+ }
11460
11569
  function isPrivateIpv4(ip) {
11461
11570
  const parts = ip.split(".").map((p3) => Number.parseInt(p3, 10));
11462
11571
  if (parts.length !== 4 || parts.some((p3) => Number.isNaN(p3) || p3 < 0 || p3 > 255))
@@ -11468,16 +11577,13 @@ function isPrivateIpv4(ip) {
11468
11577
  }
11469
11578
  return false;
11470
11579
  }
11471
- function matchesIpv4(a2, _b, _c, _d, ra2, _rb, _rc, mask) {
11472
- if (mask === 8)
11473
- return a2 === ra2;
11474
- if (mask === 16)
11475
- return a2 === ra2 && _b === _rb;
11476
- if (mask === 12)
11477
- return a2 === ra2 && (_b & 240) === (_rb & 240);
11478
- if (mask === 10)
11479
- return a2 === ra2 && (_b & 192) === (_rb & 192);
11480
- return false;
11580
+ function matchesIpv4(a2, b2, c2, d2, ra2, rb, rc, mask) {
11581
+ if (mask <= 0 || mask > 32)
11582
+ return false;
11583
+ const value = (a2 << 24 | b2 << 16 | c2 << 8 | d2) >>> 0;
11584
+ const rangeValue = (ra2 << 24 | rb << 16 | rc << 8 | 0) >>> 0;
11585
+ const maskBits = mask === 32 ? 4294967295 : 4294967295 << 32 - mask >>> 0;
11586
+ return (value & maskBits) >>> 0 === (rangeValue & maskBits) >>> 0;
11481
11587
  }
11482
11588
 
11483
11589
  // src/features/pass-through.ts
@@ -11486,12 +11592,13 @@ async function renderPassThrough(entry, ctx, opts) {
11486
11592
  throw new Error(`renderPassThrough called for non-passthrough entry '${entry.id}'`);
11487
11593
  }
11488
11594
  const spec = entry.response;
11595
+ const validationOpts = {
11596
+ allowedSchemes: ["https", "http"],
11597
+ allowPrivateUpstreams: opts.allowPrivateUpstreams
11598
+ };
11489
11599
  let upstreamUrl;
11490
11600
  try {
11491
- upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, {
11492
- allowedSchemes: ["https", "http"],
11493
- allowPrivateUpstreams: opts.allowPrivateUpstreams
11494
- });
11601
+ upstreamUrl = await validateUpstreamUrlResolved(spec.upstream, validationOpts);
11495
11602
  } catch (err) {
11496
11603
  opts.logger.error({
11497
11604
  event: "passthrough_url_rejected",
@@ -11518,14 +11625,16 @@ async function renderPassThrough(entry, ctx, opts) {
11518
11625
  const controller = new AbortController;
11519
11626
  const timer = setTimeout(() => controller.abort(), spec.timeoutMs);
11520
11627
  timer.unref?.();
11628
+ const bodyCap = ctx.req.method === "GET" || ctx.req.method === "HEAD" ? null : capRequestBodyStream(ctx, opts.maxBodyBytes);
11521
11629
  const started = performance.now();
11522
11630
  try {
11523
- const upstreamRes = await fetch(targetUrl, {
11631
+ const requestBody = bodyCap ? await ctx.req.raw.arrayBuffer() : null;
11632
+ const { response: upstreamRes } = await fetchWithRedirectGuard(targetUrl, {
11524
11633
  method: ctx.req.method,
11525
11634
  headers,
11526
- body: ctx.req.method === "GET" || ctx.req.method === "HEAD" ? undefined : await ctx.req.raw.arrayBuffer(),
11635
+ body: requestBody,
11527
11636
  signal: controller.signal
11528
- });
11637
+ }, validationOpts);
11529
11638
  clearTimeout(timer);
11530
11639
  return new Response(upstreamRes.body, {
11531
11640
  status: upstreamRes.status,
@@ -11533,7 +11642,23 @@ async function renderPassThrough(entry, ctx, opts) {
11533
11642
  });
11534
11643
  } catch (err) {
11535
11644
  clearTimeout(timer);
11645
+ if (bodyCap?.tooLarge()) {
11646
+ return bodyTooLargeResponse(opts.maxBodyBytes);
11647
+ }
11536
11648
  const durationMs = performance.now() - started;
11649
+ if (err instanceof UrlValidationError) {
11650
+ opts.logger.error({
11651
+ event: "passthrough_redirect_rejected",
11652
+ entryId: entry.id,
11653
+ upstream: String(upstreamUrl),
11654
+ reason: err.reason
11655
+ });
11656
+ return new Response(JSON.stringify({
11657
+ error: "passthrough_upstream",
11658
+ upstream: String(upstreamUrl),
11659
+ reason: "upstream redirected to a URL rejected by validator"
11660
+ }), { status: 502, headers: { "content-type": "application/json" } });
11661
+ }
11537
11662
  const aborted = err instanceof DOMException && err.name === "AbortError";
11538
11663
  opts.logger.error({
11539
11664
  event: "passthrough_upstream_error",
@@ -12019,12 +12144,39 @@ class BoundedRetryQueue {
12019
12144
  #cap;
12020
12145
  #onDropped;
12021
12146
  #onSizeChange;
12147
+ #timers = new Map;
12148
+ #stopped = false;
12022
12149
  constructor(opts = {}) {
12023
12150
  this.#pq = new PQueue({ concurrency: opts.concurrency ?? DEFAULT_CONCURRENCY });
12024
12151
  this.#cap = opts.cap ?? DEFAULT_CAP;
12025
12152
  this.#onDropped = opts.onDropped;
12026
12153
  this.#onSizeChange = opts.onSizeChange;
12027
12154
  }
12155
+ stop() {
12156
+ if (this.#stopped)
12157
+ return;
12158
+ this.#stopped = true;
12159
+ for (const [timer, resolve4] of this.#timers) {
12160
+ clearTimeout(timer);
12161
+ resolve4();
12162
+ }
12163
+ this.#timers.clear();
12164
+ const abandoned = this.#waiting.splice(0, this.#waiting.length);
12165
+ for (const req of abandoned) {
12166
+ this.#dropDelivery(req);
12167
+ }
12168
+ }
12169
+ #sleep(ms) {
12170
+ if (ms <= 0 || this.#stopped)
12171
+ return Promise.resolve();
12172
+ return new Promise((resolve4) => {
12173
+ const timer = setTimeout(() => {
12174
+ this.#timers.delete(timer);
12175
+ resolve4();
12176
+ }, ms);
12177
+ this.#timers.set(timer, resolve4);
12178
+ });
12179
+ }
12028
12180
  #fireSizeChange() {
12029
12181
  if (!this.#onSizeChange)
12030
12182
  return;
@@ -12043,7 +12195,14 @@ class BoundedRetryQueue {
12043
12195
  inflight() {
12044
12196
  return this.#pq.pending;
12045
12197
  }
12198
+ liveTimerCount() {
12199
+ return this.#timers.size;
12200
+ }
12046
12201
  enqueue(req) {
12202
+ if (this.#stopped) {
12203
+ this.#dropDelivery(req);
12204
+ return;
12205
+ }
12047
12206
  while (this.size() >= this.#cap) {
12048
12207
  const oldest = this.#waiting.shift();
12049
12208
  if (oldest) {
@@ -12076,7 +12235,17 @@ class BoundedRetryQueue {
12076
12235
  if (attempt > 1) {
12077
12236
  const baseMs = req.retry.backoff[attempt - 2] ?? 0;
12078
12237
  const delayMs = applyJitter(baseMs, req.retry.jitterRatio);
12079
- await sleep(delayMs);
12238
+ await this.#sleep(delayMs);
12239
+ if (this.#stopped) {
12240
+ req.onTerminal({
12241
+ deliveryId: req.deliveryId,
12242
+ outcome: "failed",
12243
+ totalAttempts: attempt - 1,
12244
+ lastHttpStatus,
12245
+ totalDurationUs: Math.round((performance.now() - totalStart) * 1000)
12246
+ });
12247
+ return;
12248
+ }
12080
12249
  }
12081
12250
  const gate = req.circuitGate();
12082
12251
  if (gate === "open") {
@@ -12118,7 +12287,7 @@ class BoundedRetryQueue {
12118
12287
  lastError = errorToString(err);
12119
12288
  req.onAttempt({
12120
12289
  attempt,
12121
- outcome: attempt === req.retry.attempts ? "failed" : "success",
12290
+ outcome: attempt === req.retry.attempts ? "failed" : "retrying",
12122
12291
  durationUs: 0,
12123
12292
  error: lastError
12124
12293
  });
@@ -12156,11 +12325,6 @@ function applyJitter(baseMs, ratio) {
12156
12325
  const delta = baseMs * ratio;
12157
12326
  return Math.max(0, Math.round(baseMs - delta + Math.random() * 2 * delta));
12158
12327
  }
12159
- function sleep(ms) {
12160
- if (ms <= 0)
12161
- return Promise.resolve();
12162
- return new Promise((resolve4) => setTimeout(resolve4, ms));
12163
- }
12164
12328
  function errorToString(err) {
12165
12329
  if (err instanceof Error)
12166
12330
  return `${err.name}: ${err.message}`;
@@ -12280,6 +12444,13 @@ class DeliveryEventRegistry {
12280
12444
  this.#completed.delete(id);
12281
12445
  }
12282
12446
  }
12447
+ stop() {
12448
+ const pending = Array.from(this.#pending.values());
12449
+ for (const deferred of pending) {
12450
+ deferred.resolve(null);
12451
+ }
12452
+ this.#pending.clear();
12453
+ }
12283
12454
  pendingCount() {
12284
12455
  return this.#pending.size;
12285
12456
  }
@@ -12289,6 +12460,25 @@ class DeliveryEventRegistry {
12289
12460
  }
12290
12461
  // src/features/webhooks/journal.ts
12291
12462
  import { appendFileSync } from "fs";
12463
+ function redactUrlForJournal(rawUrl) {
12464
+ try {
12465
+ return `${new URL(rawUrl).origin}/[redacted]`;
12466
+ } catch {
12467
+ return "[redacted:unparseable-url]";
12468
+ }
12469
+ }
12470
+ var EMBEDDED_URL_PATTERN = /\bhttps?:\/\/[^\s'"()<>[\]{}]+/gi;
12471
+ function redactUrlsInText(text) {
12472
+ return text.replace(EMBEDDED_URL_PATTERN, (match2) => redactUrlForJournal(match2));
12473
+ }
12474
+ function redactEntry(entry) {
12475
+ return {
12476
+ ...entry,
12477
+ ...entry.resolvedUrl !== undefined && { resolvedUrl: redactUrlForJournal(entry.resolvedUrl) },
12478
+ ...entry.error !== undefined && { error: redactUrlsInText(entry.error) }
12479
+ };
12480
+ }
12481
+
12292
12482
  class WebhookJournalRegistry {
12293
12483
  #buffers = new Map;
12294
12484
  #capacityFor;
@@ -12298,11 +12488,12 @@ class WebhookJournalRegistry {
12298
12488
  this.#journalFile = opts.journalFile;
12299
12489
  }
12300
12490
  record(entry) {
12301
- const buf = this.#bufferFor(entry.tenant);
12302
- buf.push(entry);
12491
+ const redacted = redactEntry(entry);
12492
+ const buf = this.#bufferFor(redacted.tenant);
12493
+ buf.push(redacted);
12303
12494
  if (this.#journalFile) {
12304
12495
  try {
12305
- appendFileSync(this.#journalFile, `${JSON.stringify(entry)}
12496
+ appendFileSync(this.#journalFile, `${JSON.stringify(redacted)}
12306
12497
  `);
12307
12498
  } catch (err) {
12308
12499
  console.warn(`[mockstar] webhook journal file write failed: ${err.message ?? err}`);
@@ -12426,14 +12617,13 @@ function dispatchWebhooks(deps, input) {
12426
12617
  }
12427
12618
  async function performAttempt(spec, input, _deps) {
12428
12619
  const attemptStart = performance.now();
12429
- let urlString;
12430
12620
  const headerUrl = _deps.allowWebhookUrlHeader && spec.acceptHeaderOverride ? input.requestHeaders.get("x-mockstar-webhook-url") : undefined;
12431
- urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12432
- const allowedSchemes = spec.allowHttp ? ["http", "https"] : ["https"];
12433
- await validateUpstreamUrlResolved(urlString, {
12434
- allowedSchemes,
12621
+ const urlString = headerUrl ?? spec.urlTemplate.render(input.templateContext);
12622
+ const validationOpts = {
12623
+ allowedSchemes: spec.allowHttp ? ["http", "https"] : ["https"],
12435
12624
  allowPrivateUpstreams: spec.allowPrivateNetworks
12436
- });
12625
+ };
12626
+ const validatedUrl = await validateUpstreamUrlResolved(urlString, validationOpts);
12437
12627
  const renderedHeaders = new Headers;
12438
12628
  for (const [key, tmpl] of spec.headers) {
12439
12629
  renderedHeaders.set(key, tmpl.render(input.templateContext));
@@ -12465,14 +12655,20 @@ async function performAttempt(spec, input, _deps) {
12465
12655
  }
12466
12656
  const signal = AbortSignal.timeout(spec.timeoutMs);
12467
12657
  let response;
12658
+ let finalUrl;
12468
12659
  try {
12469
- response = await fetch(urlString, {
12660
+ const result = await fetchWithRedirectGuard(validatedUrl, {
12470
12661
  method: spec.method,
12471
12662
  headers: renderedHeaders,
12472
- body: spec.method === "GET" || spec.method === "DELETE" ? undefined : rawBody,
12663
+ body: spec.method === "GET" || spec.method === "DELETE" ? null : rawBody,
12473
12664
  signal
12474
- });
12665
+ }, validationOpts);
12666
+ response = result.response;
12667
+ finalUrl = result.finalUrl;
12475
12668
  } catch (err) {
12669
+ if (err instanceof UrlValidationError) {
12670
+ throw new Error(`webhook delivery redirect rejected: ${err.message}`);
12671
+ }
12476
12672
  throw new Error(`webhook delivery network error: ${err.message ?? err}`);
12477
12673
  }
12478
12674
  if (!isSuccessStatus(response.status, spec.expectResponse)) {
@@ -12487,7 +12683,7 @@ async function performAttempt(spec, input, _deps) {
12487
12683
  return {
12488
12684
  httpStatus: response.status,
12489
12685
  durationUs: Math.round((performance.now() - attemptStart) * 1000),
12490
- resolvedUrl: urlString
12686
+ resolvedUrl: finalUrl.href
12491
12687
  };
12492
12688
  }
12493
12689
  function isSuccessStatus(status, expect) {
@@ -12538,6 +12734,8 @@ function makeDeliveryId() {
12538
12734
  return crypto.randomUUID();
12539
12735
  }
12540
12736
  // src/server.ts
12737
+ var UNKNOWN_TENANT_BUCKET = ":unknown:";
12738
+ var DEFAULT_REQUESTS_PER_SECOND = 1e4;
12541
12739
  function createServer(opts) {
12542
12740
  const logger = opts.logger ?? createLogger({ deterministic: opts.deterministic });
12543
12741
  const metrics = new Metrics;
@@ -12545,6 +12743,7 @@ function createServer(opts) {
12545
12743
  const snap = opts.holder.get().tenants.get(tenant);
12546
12744
  return snap?.limits.journalSize ?? 1000;
12547
12745
  });
12746
+ const rateLimiter = new TenantRateLimiter({ now: opts.rateLimiterNow });
12548
12747
  const webhookJournal = new WebhookJournalRegistry((tenant) => {
12549
12748
  const snap = opts.holder.get().tenants.get(tenant);
12550
12749
  return snap?.limits.journalSize ?? 1000;
@@ -12589,7 +12788,7 @@ function createServer(opts) {
12589
12788
  const clock = createClock({ deterministic: opts.deterministic ?? false });
12590
12789
  const handlerTimeoutMs = opts.handlerTimeoutMs ?? 5000;
12591
12790
  const genRequestId = createRequestIdGenerator(opts.deterministic ?? false);
12592
- const app = new Hono2;
12791
+ const app = new Hono3;
12593
12792
  const replayWebhook = (tenant, deliveryId) => {
12594
12793
  const snap = opts.holder.get();
12595
12794
  const tenantSnap = snap.tenants.get(tenant);
@@ -12655,6 +12854,7 @@ function createServer(opts) {
12655
12854
  clock,
12656
12855
  journal,
12657
12856
  metrics,
12857
+ rateLimiter,
12658
12858
  handlerTimeoutMs,
12659
12859
  genRequestId,
12660
12860
  webhookJournal,
@@ -12663,15 +12863,22 @@ function createServer(opts) {
12663
12863
  circuitFor,
12664
12864
  allowWebhookUrlHeader
12665
12865
  }));
12866
+ const stopWebhooks = () => {
12867
+ for (const q3 of webhookQueues.values())
12868
+ q3.stop();
12869
+ webhookEvents.stop();
12870
+ };
12666
12871
  return {
12667
12872
  hono: app,
12668
12873
  journal,
12669
12874
  metrics,
12875
+ rateLimiter,
12670
12876
  ready,
12671
12877
  uninstallCrashHandlers,
12672
12878
  webhookJournal,
12673
12879
  webhookEvents,
12674
- replayWebhook
12880
+ replayWebhook,
12881
+ stopWebhooks
12675
12882
  };
12676
12883
  }
12677
12884
  async function dispatch(ctx, deps) {
@@ -12683,28 +12890,35 @@ async function dispatch(ctx, deps) {
12683
12890
  const startedUs = performance.now() * 1000;
12684
12891
  const matchPath = effectivePath(ctx);
12685
12892
  const method = ctx.req.method;
12893
+ const observedTenant = tenantSnap ? tenant : UNKNOWN_TENANT_BUCKET;
12686
12894
  let response;
12687
12895
  let matchedMockId = null;
12688
12896
  let scenarioId;
12689
12897
  let scenarioMissReason;
12690
12898
  let webhookTrigger;
12691
12899
  try {
12692
- if (!tenantSnap) {
12900
+ const rpsLimit = tenantSnap?.limits.requestsPerSecond ?? DEFAULT_REQUESTS_PER_SECOND;
12901
+ const rateResult = deps.rateLimiter.tryAcquire(observedTenant, rpsLimit);
12902
+ if (!rateResult.allowed) {
12903
+ response = rateLimitedResponse(rpsLimit, rateResult.retryAfterSeconds);
12904
+ } else if (!tenantSnap) {
12693
12905
  response = notFoundUnknownTenant(tenant, method, matchPath);
12694
12906
  } else {
12695
12907
  const contentLength = Number.parseInt(ctx.req.header("content-length") ?? "0", 10);
12696
12908
  if (contentLength > tenantSnap.limits.maxBodyBytes) {
12697
- response = new Response(JSON.stringify({ error: "body_too_large", limit: tenantSnap.limits.maxBodyBytes }), {
12698
- status: 413,
12699
- headers: { "content-type": "application/json" }
12700
- });
12909
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
12701
12910
  } else {
12702
- const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps);
12703
- response = result.response;
12704
- matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
12705
- scenarioId = result.scenarioId;
12706
- scenarioMissReason = result.scenarioMissReason;
12707
- webhookTrigger = result.webhookTrigger;
12911
+ const bodyResult = await safeParseBody(ctx, tenantSnap.limits.maxBodyBytes);
12912
+ if (!bodyResult.ok) {
12913
+ response = bodyTooLargeResponse(tenantSnap.limits.maxBodyBytes);
12914
+ } else {
12915
+ const result = await routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, bodyResult.body);
12916
+ response = result.response;
12917
+ matchedMockId = response.headers.get("x-mockstar-matched") ?? null;
12918
+ scenarioId = result.scenarioId;
12919
+ scenarioMissReason = result.scenarioMissReason;
12920
+ webhookTrigger = result.webhookTrigger;
12921
+ }
12708
12922
  }
12709
12923
  }
12710
12924
  } catch (err) {
@@ -12725,7 +12939,7 @@ async function dispatch(ctx, deps) {
12725
12939
  const durationUs = Math.round(performance.now() * 1000 - startedUs);
12726
12940
  const entry = {
12727
12941
  timestamp: Date.now(),
12728
- tenant,
12942
+ tenant: observedTenant,
12729
12943
  requestId,
12730
12944
  method,
12731
12945
  path: matchPath,
@@ -12737,15 +12951,15 @@ async function dispatch(ctx, deps) {
12737
12951
  };
12738
12952
  deps.journal.record(entry);
12739
12953
  deps.metrics.incCounter("mockstar_requests_total", {
12740
- tenant,
12954
+ tenant: observedTenant,
12741
12955
  method,
12742
12956
  status: String(response.status),
12743
12957
  matched: matchedMockId ? "1" : "0"
12744
12958
  });
12745
- deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant }, durationUs);
12959
+ deps.metrics.observeLatencyUs("mockstar_request_latency_us", { tenant: observedTenant }, durationUs);
12746
12960
  deps.logger.info({
12747
12961
  event: "request",
12748
- tenant,
12962
+ tenant: observedTenant,
12749
12963
  method,
12750
12964
  path: matchPath,
12751
12965
  status: response.status,
@@ -12794,9 +13008,8 @@ async function dispatch(ctx, deps) {
12794
13008
  });
12795
13009
  return response;
12796
13010
  }
12797
- async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps) {
13011
+ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap, requestId, deps, body) {
12798
13012
  const url = new URL(ctx.req.url);
12799
- const body = await safeParseBody(ctx);
12800
13013
  const req = {
12801
13014
  query: new Map(Array.from(url.searchParams)),
12802
13015
  headers: new Map(Array.from(ctx.req.raw.headers).map(([k2, v3]) => [k2.toLowerCase(), v3])),
@@ -12908,7 +13121,8 @@ async function routeToMock(ctx, matchPath, method, tenant, snapshot, tenantSnap,
12908
13121
  case "passthrough":
12909
13122
  response = await renderPassThrough(hit.entry, ctx, {
12910
13123
  allowPrivateUpstreams: tenantSnap.allowPrivateUpstreams,
12911
- logger: deps.logger
13124
+ logger: deps.logger,
13125
+ maxBodyBytes: tenantSnap.limits.maxBodyBytes
12912
13126
  });
12913
13127
  break;
12914
13128
  }
@@ -12926,20 +13140,27 @@ function notFoundUnknownTenant(tenant, method, path) {
12926
13140
  headers: { "content-type": "application/json" }
12927
13141
  });
12928
13142
  }
12929
- async function safeParseBody(ctx) {
13143
+ async function safeParseBody(ctx, maxBodyBytes) {
12930
13144
  const method = ctx.req.method;
12931
13145
  if (method === "GET" || method === "HEAD")
12932
- return null;
13146
+ return { ok: true, body: null };
12933
13147
  const contentType = ctx.req.header("content-type") ?? "";
12934
13148
  if (!contentType.includes("json"))
12935
- return null;
13149
+ return { ok: true, body: null };
13150
+ const { tooLarge } = capRequestBodyStream(ctx, maxBodyBytes);
12936
13151
  try {
12937
13152
  const text = await ctx.req.text();
12938
13153
  if (text.length === 0)
12939
- return null;
12940
- return JSON.parse(text);
12941
- } catch {
12942
- return null;
13154
+ return { ok: true, body: null };
13155
+ try {
13156
+ return { ok: true, body: JSON.parse(text) };
13157
+ } catch {
13158
+ return { ok: true, body: null };
13159
+ }
13160
+ } catch (err) {
13161
+ if (tooLarge())
13162
+ return { ok: false };
13163
+ throw err;
12943
13164
  }
12944
13165
  }
12945
13166
  function createRequestIdGenerator(deterministic) {
@@ -12991,6 +13212,7 @@ async function launch(opts) {
12991
13212
  holder,
12992
13213
  async stop() {
12993
13214
  watcher?.stop();
13215
+ server.stopWebhooks();
12994
13216
  server.uninstallCrashHandlers();
12995
13217
  }
12996
13218
  };