@klnap/next-proxy-chain 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -230,22 +230,206 @@ function createConsoleLogger(minLevel = "info") {
230
230
  error: write("error")
231
231
  };
232
232
  }
233
- function formatDuration(ms) {
233
+
234
+ // src/core/diagnostics/sanitize.ts
235
+ var MAX_TEXT_LENGTH = 160;
236
+ function safeDiagnosticText(value, limit = MAX_TEXT_LENGTH) {
237
+ let output = "";
238
+ for (const char of value) {
239
+ const code = char.codePointAt(0);
240
+ if (code === 27 || code < 32 || code >= 127 && code <= 159 || code === 173 || code === 1564 || code === 6158 || code >= 8203 && code <= 8207 || code >= 8232 && code <= 8238 || code >= 8288 && code <= 8303 || code === 65279) {
241
+ output += "\uFFFD";
242
+ } else {
243
+ output += char;
244
+ }
245
+ if (output.length >= limit) return `${output.slice(0, limit)}\u2026`;
246
+ }
247
+ return output;
248
+ }
249
+ function safeDestination(value) {
250
+ if (!value) return void 0;
251
+ try {
252
+ const url = new URL(value, "http://proxy-chain.invalid");
253
+ return safeDiagnosticText(`${url.pathname}${url.search ? "?[query]" : ""}`);
254
+ } catch {
255
+ return safeDiagnosticText(value.split(/[?#]/, 1)[0] ?? "");
256
+ }
257
+ }
258
+
259
+ // src/core/diagnostics/formatter.ts
260
+ function runtime() {
261
+ return globalThis.process;
262
+ }
263
+ function shouldUseColor() {
264
+ const process = runtime();
265
+ const env = process?.env;
266
+ if (env?.NO_COLOR) return false;
267
+ if (env?.FORCE_COLOR) return env.FORCE_COLOR !== "0";
268
+ if (env?.CI || env?.TERM === "dumb" || !process?.stdout?.isTTY) return false;
269
+ try {
270
+ return process.stdout.getColorDepth?.() !== 1;
271
+ } catch {
272
+ return false;
273
+ }
274
+ }
275
+ function supportsUnicode() {
276
+ const process = runtime();
277
+ if (!process?.env) return false;
278
+ const env = process.env;
279
+ const locale = (env.LC_ALL || env.LC_CTYPE || env.LANG || "").toLowerCase();
280
+ return !/(^|\s)(c|posix)(\.|$|\s)/.test(locale) && !locale.includes("ascii");
281
+ }
282
+ function paint(text, code, enabled) {
283
+ return enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
284
+ }
285
+ function duration(ms) {
234
286
  return `${ms.toFixed(2)}ms`;
235
287
  }
236
- function formatPipelineLine(input) {
237
- const trace = input.traceId ? ` [${input.traceId.slice(0, 8)}]` : "";
238
- const req = `${input.method} ${input.path}${trace}`;
239
- const { name, outcome } = input;
240
- switch (outcome.kind) {
241
- case "passed":
242
- return `[proxy-chain] \xB7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> passed`;
288
+ function handlerLabel(handler) {
289
+ switch (handler.outcome) {
290
+ case "continue":
291
+ return { symbol: "\u2713", text: "continue", color: 32 };
292
+ case "rewrite":
293
+ return { symbol: "\u21AA", text: "rewrite", color: 36 };
294
+ case "redirect":
295
+ return { symbol: "\u2197", text: "redirect", color: 33 };
296
+ case "response":
297
+ return { symbol: "\u2713", text: `response ${handler.status}`, color: 32 };
298
+ case "skipped":
299
+ return { symbol: "\u25CB", text: "skipped", color: 2 };
300
+ case "not-reached":
301
+ return { symbol: "\u2013", text: "not reached", color: 2 };
302
+ case "recovered":
303
+ return { symbol: "!", text: "recovered", color: 33 };
304
+ case "timeout":
305
+ return { symbol: "\xD7", text: "timeout", color: 31 };
306
+ case "failed":
307
+ return { symbol: "\xD7", text: "failed", color: 31 };
308
+ }
309
+ }
310
+ function outcomeText(outcome) {
311
+ switch (outcome.type) {
312
+ case "next":
313
+ return "NEXT";
314
+ case "rewrite":
315
+ return `REWRITE ${outcome.destination}`;
316
+ case "redirect":
317
+ return `REDIRECT ${outcome.status}${outcome.destination ? ` ${outcome.destination}` : ""}`;
318
+ case "response":
319
+ return `RESPONSE ${outcome.status}`;
320
+ case "error":
321
+ return `ERROR ${outcome.status}`;
322
+ case "timeout":
323
+ return `ERROR ${outcome.status} \xB7 timeout ${outcome.timeoutMs}ms`;
324
+ }
325
+ }
326
+ function outcomeColor(outcome) {
327
+ switch (outcome.type) {
243
328
  case "next":
244
- return `[proxy-chain] ~ ${req} | ${name} (${formatDuration(outcome.duration)}) -> headers mutated (${outcome.headers})`;
245
- case "stop":
246
- return `[proxy-chain] \xD7 ${req} | ${name} (${formatDuration(outcome.duration)}) -> stop ${outcome.status}`;
329
+ return 32;
330
+ case "rewrite":
331
+ return 36;
332
+ case "redirect":
333
+ return 33;
334
+ case "error":
335
+ case "timeout":
336
+ return 31;
337
+ case "response":
338
+ return outcome.status >= 500 ? 31 : 32;
247
339
  }
248
340
  }
341
+ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
342
+ const path2 = trace.pathname ? ` ${safeDiagnosticText(trace.pathname)}` : "";
343
+ const header = `proxy-chain ${safeDiagnosticText(trace.method)}${path2}`;
344
+ const rows = [];
345
+ const handlers = trace.handlers;
346
+ if (level === "compact") {
347
+ const executed = handlers.filter(
348
+ (handler) => handler.outcome !== "skipped" && handler.outcome !== "not-reached"
349
+ ).length;
350
+ const skipped = handlers.filter((handler) => handler.outcome === "skipped").length;
351
+ return `${header} ${unicode ? "\u2192" : "->"} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)} \xB7 ${executed} executed \xB7 ${skipped} skipped \xB7 ${paint(duration(trace.durationMs), 2, color)}`;
352
+ }
353
+ rows.push(`${header.padEnd(52)} ${duration(trace.durationMs)}`);
354
+ const shown = handlers;
355
+ const symbols = unicode ? {
356
+ pass: "\u2502",
357
+ last: "\u2514",
358
+ continue: "\u2713",
359
+ rewrite: "\u21AA",
360
+ redirect: "\u2197",
361
+ skip: "\u25CB",
362
+ missing: "\u2013",
363
+ error: "\xD7",
364
+ recovered: "!"
365
+ } : {
366
+ pass: "|",
367
+ last: "`-",
368
+ continue: "+",
369
+ rewrite: "->",
370
+ redirect: "->",
371
+ skip: "o",
372
+ missing: "-",
373
+ error: "x",
374
+ recovered: "!"
375
+ };
376
+ for (let index = 0; index < shown.length; index++) {
377
+ const handler = shown[index];
378
+ const label = handlerLabel(handler);
379
+ const symbol = handler.outcome === "continue" ? symbols.continue : handler.outcome === "rewrite" ? symbols.rewrite : handler.outcome === "redirect" ? symbols.redirect : handler.outcome === "skipped" ? symbols.skip : handler.outcome === "not-reached" ? symbols.missing : handler.outcome === "recovered" ? symbols.recovered : symbols.error;
380
+ const prefix = symbols.pass;
381
+ const name = safeDiagnosticText(handler.name, 32);
382
+ const time = "durationMs" in handler ? paint(duration(handler.durationMs), 2, color) : "";
383
+ rows.push(
384
+ `${prefix} ${paint(symbol, label.color, color)} ${name.padEnd(16)} ${label.text.padEnd(14)} ${time}`.trimEnd()
385
+ );
386
+ if (level === "verbose") {
387
+ if (handler.details?.timeoutMs !== void 0) {
388
+ rows.push(
389
+ `${symbols.pass} timeout: ${handler.details.timeoutMs}ms (${handler.details.timeoutSource ?? "chain"})`
390
+ );
391
+ }
392
+ if (handler.details?.include) {
393
+ rows.push(
394
+ `${symbols.pass} include: ${handler.details.include.join(", ")}${handler.details.includeResult ? ` (${handler.details.includeResult})` : ""}`
395
+ );
396
+ }
397
+ if (handler.details?.exclude) {
398
+ rows.push(
399
+ `${symbols.pass} exclude: ${handler.details.exclude.join(", ")}${handler.details.excludeResult ? ` (${handler.details.excludeResult})` : ""}`
400
+ );
401
+ }
402
+ if (handler.details?.when) {
403
+ rows.push(
404
+ `${symbols.pass} when: ${handler.details.when === "matched" ? "true" : handler.details.when === "false" ? "false" : "not evaluated"}`
405
+ );
406
+ }
407
+ if (handler.outcome === "continue") rows.push(`${symbols.pass} source: ${handler.source}`);
408
+ if (handler.outcome === "skipped") rows.push(`${symbols.pass} reason: ${handler.reason}`);
409
+ if (handler.outcome === "rewrite") {
410
+ rows.push(`${symbols.pass} destination: ${handler.destination}`);
411
+ }
412
+ if (handler.outcome === "redirect" && handler.destination) {
413
+ rows.push(`${symbols.pass} destination: ${handler.destination}`);
414
+ }
415
+ }
416
+ if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout") {
417
+ const policy = handler.policy === "none" ? "chain default" : handler.policy;
418
+ rows.push(`${symbols.pass} error policy: ${policy}`);
419
+ }
420
+ if (handler.outcome === "timeout" && handler.details?.timeoutMs !== void 0) {
421
+ rows.push(`${symbols.pass} deadline: ${handler.details.timeoutMs}ms`);
422
+ }
423
+ }
424
+ rows.push(
425
+ `${symbols.last} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)}`
426
+ );
427
+ const output = rows.join("\n");
428
+ if (output.length <= 16384) return output;
429
+ const safeBoundary = output.lastIndexOf("\n", 16384);
430
+ return `${output.slice(0, safeBoundary < 0 ? 16384 : safeBoundary)}
431
+ ${unicode ? "\u2026" : "..."} diagnostics truncated`;
432
+ }
249
433
 
250
434
  // src/core/matching.ts
251
435
  var RESERVED_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
@@ -401,14 +585,25 @@ function withPaths(entry, filter) {
401
585
  const exclude = compileScopes(filter.exclude);
402
586
  const name = filter.name ?? base.name;
403
587
  assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
404
- return { run: base.run, include, exclude, name };
588
+ return {
589
+ run: base.run,
590
+ include,
591
+ exclude,
592
+ name,
593
+ debug: base.debug,
594
+ timeout: base.timeout,
595
+ when: base.when,
596
+ diagnosticRules: { include: filter.include, exclude: filter.exclude }
597
+ };
405
598
  }
406
- function ruleMatches(pathname, hostname, rule) {
407
- if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
599
+ function ruleMatchReason(pathname, hostname, rule) {
600
+ if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
601
+ return "exclude-match";
602
+ }
408
603
  if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
409
- return false;
604
+ return "include-mismatch";
410
605
  }
411
- return true;
606
+ return void 0;
412
607
  }
413
608
  function normalizeHost(raw) {
414
609
  if (!raw) return null;
@@ -623,6 +818,78 @@ async function withRuleTimeout(promise, timeoutMs, ruleName) {
623
818
  }
624
819
 
625
820
  // src/core/engine.ts
821
+ function monotonicNow() {
822
+ try {
823
+ if (typeof globalThis.performance?.now === "function") return globalThis.performance.now();
824
+ } catch {
825
+ }
826
+ return Date.now();
827
+ }
828
+ function normalizeDebugLevel(level) {
829
+ return level === true ? "detailed" : level;
830
+ }
831
+ function responseOutcome(response) {
832
+ const rewrite = response.headers.get("x-middleware-rewrite");
833
+ if (rewrite) {
834
+ return { type: "rewrite", destination: safeDestination(rewrite) ?? "/" };
835
+ }
836
+ const location = response.headers.get("location");
837
+ if (location && response.status >= 300 && response.status < 400) {
838
+ return {
839
+ type: "redirect",
840
+ status: response.status,
841
+ destination: safeDestination(location)
842
+ };
843
+ }
844
+ if (response instanceof NextResponse2 && response.headers.get("x-middleware-next") === "1") {
845
+ return { type: "next" };
846
+ }
847
+ return { type: "response", status: response.status };
848
+ }
849
+ function scopeNames(scopeList) {
850
+ if (scopeList === void 0) return void 0;
851
+ const scopes = Array.isArray(scopeList) ? scopeList : [scopeList];
852
+ return scopes.map((scope) => {
853
+ if (typeof scope === "string") return safeDiagnosticText(scope, 96);
854
+ if (scope instanceof RegExp) return safeDiagnosticText(scope.toString(), 96);
855
+ if (typeof scope !== "object" || scope === null) return "";
856
+ const value = scope;
857
+ const parts = [
858
+ value.path === void 0 ? void 0 : Array.isArray(value.path) ? value.path.map(String).join("|") : String(value.path),
859
+ value.host === void 0 ? void 0 : Array.isArray(value.host) ? value.host.map(String).join("|") : String(value.host)
860
+ ].filter(Boolean);
861
+ return safeDiagnosticText(parts.join(" @ "), 96);
862
+ });
863
+ }
864
+ function handlerDetails(rule, chainTimeout, when, includeResult, excludeResult) {
865
+ const include = scopeNames(rule.diagnosticRules?.include);
866
+ const exclude = scopeNames(rule.diagnosticRules?.exclude);
867
+ return {
868
+ ...include ? { include, includeResult } : {},
869
+ ...exclude ? { exclude, excludeResult } : {},
870
+ ...rule.when ? { when } : {},
871
+ timeoutMs: rule.timeout ?? chainTimeout,
872
+ timeoutSource: rule.timeout === void 0 ? "chain" : "handler"
873
+ };
874
+ }
875
+ function safeLogger(logger) {
876
+ const wrap = (method) => (...args) => {
877
+ try {
878
+ const result = logger[method](...args);
879
+ if (result && typeof result.then === "function") {
880
+ void Promise.resolve(result).catch(() => {
881
+ });
882
+ }
883
+ } catch {
884
+ }
885
+ };
886
+ return {
887
+ debug: wrap("debug"),
888
+ info: wrap("info"),
889
+ warn: wrap("warn"),
890
+ error: wrap("error")
891
+ };
892
+ }
626
893
  function isNextResponse(value) {
627
894
  return value instanceof NextResponse2 && value.headers.get("x-middleware-next") === "1";
628
895
  }
@@ -670,9 +937,10 @@ function resolveConfig(overrides, fallbackCreateContext) {
670
937
  requestHeaderPolicy: {},
671
938
  strictOverrideCheck: false,
672
939
  hostFolderHeader: void 0,
940
+ tracePath: true,
673
941
  ...rest,
674
942
  ...debug !== void 0 ? { debug } : {},
675
- logger: logger ?? createConsoleLogger(debug ? "debug" : "info")
943
+ logger: safeLogger(logger ?? createConsoleLogger("info"))
676
944
  };
677
945
  assertFiniteRuleTimeoutMs(config.ruleTimeoutMs);
678
946
  return config;
@@ -685,7 +953,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
685
953
  const rules = entries.map(toRule);
686
954
  const {
687
955
  logger,
688
- debug,
956
+ debug: debugLevel,
689
957
  cookieMergeStrategy,
690
958
  headerMergeStrategy,
691
959
  ruleTimeoutMs,
@@ -693,21 +961,74 @@ function proxyChain(optionsOrEntries, maybeEntries) {
693
961
  strictOverrideCheck,
694
962
  hostFolderHeader
695
963
  } = config;
964
+ const debug = debugLevel !== false;
965
+ const hasHandlerDebug = rules.some((rule) => rule.debug != null && rule.debug !== false);
966
+ const hasDetailedHandlerDebug = rules.some(
967
+ (rule) => rule.debug === true || rule.debug === "detailed" || rule.debug === "verbose"
968
+ );
969
+ const diagnosticsEnabled = debug || config.onTrace !== void 0 || hasHandlerDebug;
696
970
  assertOverrideMechanismSupported(strictOverrideCheck);
697
971
  for (let i = 0; i < rules.length; i++) {
698
972
  assertIncludeExcludeNoOverlap(rules[i].include, rules[i].exclude, ruleLabel(rules[i], i));
973
+ assertFiniteRuleTimeoutMs(rules[i].timeout);
699
974
  }
700
975
  return async function proxy(req, event) {
976
+ const startedAt = diagnosticsEnabled ? monotonicNow() : 0;
977
+ const diagnostics = diagnosticsEnabled ? [] : null;
978
+ let nextHandlerIndex = 0;
979
+ const finish = (response, forcedOutcome) => {
980
+ if (!diagnostics) return response;
981
+ for (let i = nextHandlerIndex; i < rules.length; i++) {
982
+ diagnostics.push({
983
+ name: safeDiagnosticText(ruleLabel(rules[i], i), 64),
984
+ outcome: "not-reached"
985
+ });
986
+ }
987
+ const trace = {
988
+ method: safeDiagnosticText(req.method, 16),
989
+ pathname: config.tracePath === false ? void 0 : safeDiagnosticText(req.nextUrl.pathname),
990
+ durationMs: monotonicNow() - startedAt,
991
+ outcome: forcedOutcome ?? responseOutcome(response),
992
+ handlers: diagnostics
993
+ };
994
+ if (config.onTrace) {
995
+ try {
996
+ void Promise.resolve(config.onTrace(trace)).catch(() => {
997
+ });
998
+ } catch {
999
+ }
1000
+ }
1001
+ const globalLevel = normalizeDebugLevel(debugLevel);
1002
+ if (globalLevel !== false || hasHandlerDebug) {
1003
+ const visible = diagnostics.filter((_handler, index) => {
1004
+ const local = rules[index]?.debug;
1005
+ if (local === false) return false;
1006
+ if (local === "compact") return globalLevel === "compact";
1007
+ if (local != null) return true;
1008
+ return globalLevel !== false && !(globalLevel === "compact" && hasDetailedHandlerDebug);
1009
+ });
1010
+ const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
1011
+ try {
1012
+ config.logger.info(
1013
+ formatTrace(
1014
+ level === "compact" ? trace : { ...trace, handlers: visible },
1015
+ level,
1016
+ shouldUseColor(),
1017
+ supportsUnicode()
1018
+ )
1019
+ );
1020
+ } catch {
1021
+ }
1022
+ }
1023
+ return response;
1024
+ };
701
1025
  let ctx;
702
1026
  try {
703
1027
  ctx = config.createContext(req, event);
704
- } catch (err) {
705
- logger.error({ err }, "createContext threw");
706
- return safeInternalError();
1028
+ } catch {
1029
+ if (!diagnosticsEnabled) logger.error("request context creation failed");
1030
+ return finish(safeInternalError(), { type: "error", status: 500, classification: "engine" });
707
1031
  }
708
- const method = req.method;
709
- const pathname = req.nextUrl.pathname;
710
- const traceId = req.headers.get("x-request-id") ?? req.headers.get("traceparent") ?? req.headers.get("x-b3-traceid") ?? void 0;
711
1032
  let currentReq = req;
712
1033
  let pendingRequestOverrides = null;
713
1034
  let pendingRewriteUrl = null;
@@ -745,16 +1066,83 @@ function proxyChain(optionsOrEntries, maybeEntries) {
745
1066
  appliedRequestOverrides.set(k, v);
746
1067
  });
747
1068
  };
748
- const recoverRuleError = async (err, i, label, req2, startedAt) => {
749
- if (!config.onError) {
750
- logger.error({ rule: label, err }, "rule threw");
751
- return { response: failClosed() };
1069
+ const recoverRuleError = async (err, i, label, req2, startedAt2) => {
1070
+ const timeoutError = err instanceof RuleTimeoutError;
1071
+ const durationMs = () => diagnosticsEnabled ? monotonicNow() - startedAt2 : 0;
1072
+ const errorHandler = rules[i].onError ?? config.onError;
1073
+ const errorPolicy = rules[i].onError ? "handler" : "chain";
1074
+ if (!errorHandler) {
1075
+ if (!diagnosticsEnabled) logger.error("handler failed");
1076
+ diagnostics?.push({
1077
+ name: safeDiagnosticText(label, 64),
1078
+ outcome: timeoutError ? "timeout" : "failed",
1079
+ durationMs: durationMs(),
1080
+ policy: "none",
1081
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1082
+ });
1083
+ nextHandlerIndex = i + 1;
1084
+ return {
1085
+ response: finish(
1086
+ failClosed(),
1087
+ timeoutError ? {
1088
+ type: "timeout",
1089
+ status: 500,
1090
+ timeoutMs: err instanceof RuleTimeoutError ? err.timeoutMs : ruleTimeoutMs
1091
+ } : { type: "error", status: 500, classification: "handler" }
1092
+ )
1093
+ };
752
1094
  }
753
1095
  try {
754
- const recovered = await config.onError(err, i, req2, ctx);
755
- if (recovered == null) return { response: failClosed() };
756
- if (isNextResult(recovered) || isNextResponse(recovered)) return { raw: recovered };
757
- if (!(recovered instanceof Response)) return { response: failClosed() };
1096
+ const recovered = await errorHandler(err, i, req2, ctx);
1097
+ if (recovered == null) {
1098
+ diagnostics?.push({
1099
+ name: safeDiagnosticText(label, 64),
1100
+ outcome: timeoutError ? "timeout" : "failed",
1101
+ durationMs: durationMs(),
1102
+ policy: errorPolicy,
1103
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1104
+ });
1105
+ nextHandlerIndex = i + 1;
1106
+ return {
1107
+ response: finish(
1108
+ failClosed(),
1109
+ timeoutError ? {
1110
+ type: "timeout",
1111
+ status: 500,
1112
+ timeoutMs: err instanceof RuleTimeoutError ? err.timeoutMs : ruleTimeoutMs
1113
+ } : { type: "error", status: 500, classification: "handler" }
1114
+ )
1115
+ };
1116
+ }
1117
+ if (isNextResult(recovered) || isNextResponse(recovered)) {
1118
+ diagnostics?.push({
1119
+ name: safeDiagnosticText(label, 64),
1120
+ outcome: "recovered",
1121
+ durationMs: durationMs(),
1122
+ recovery: "continue",
1123
+ policy: errorPolicy,
1124
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1125
+ });
1126
+ nextHandlerIndex = i + 1;
1127
+ return { raw: recovered };
1128
+ }
1129
+ if (!(recovered instanceof Response)) {
1130
+ diagnostics?.push({
1131
+ name: safeDiagnosticText(label, 64),
1132
+ outcome: timeoutError ? "timeout" : "failed",
1133
+ durationMs: durationMs(),
1134
+ policy: errorPolicy,
1135
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1136
+ });
1137
+ nextHandlerIndex = i + 1;
1138
+ return {
1139
+ response: finish(failClosed(), {
1140
+ type: "error",
1141
+ status: 500,
1142
+ classification: "handler"
1143
+ })
1144
+ };
1145
+ }
758
1146
  stripRoutingOverrides(recovered);
759
1147
  headerWrites.push({
760
1148
  ruleIndex: i,
@@ -766,35 +1154,45 @@ function proxyChain(optionsOrEntries, maybeEntries) {
766
1154
  ruleName: label,
767
1155
  items: cookieItemsFromHeaders(recovered.headers)
768
1156
  });
769
- if (debug) {
770
- logger.debug(
771
- formatPipelineLine({
772
- method,
773
- path: pathname,
774
- name: label,
775
- traceId,
776
- outcome: {
777
- kind: "stop",
778
- duration: performance.now() - startedAt,
779
- status: recovered.status
780
- }
781
- })
782
- );
783
- }
1157
+ diagnostics?.push({
1158
+ name: safeDiagnosticText(label, 64),
1159
+ outcome: "recovered",
1160
+ durationMs: durationMs(),
1161
+ recovery: responseOutcome(recovered).type === "redirect" ? "redirect" : responseOutcome(recovered).type === "rewrite" ? "rewrite" : "response",
1162
+ policy: errorPolicy,
1163
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1164
+ });
1165
+ nextHandlerIndex = i + 1;
784
1166
  return {
785
- response: finalizeResponse(
786
- recovered,
787
- headerWrites,
788
- cookieWrites,
789
- headerMergeStrategy,
790
- cookieMergeStrategy,
791
- logger,
792
- debug
1167
+ response: finish(
1168
+ finalizeResponse(
1169
+ recovered,
1170
+ headerWrites,
1171
+ cookieWrites,
1172
+ headerMergeStrategy,
1173
+ cookieMergeStrategy,
1174
+ logger,
1175
+ debug
1176
+ )
793
1177
  )
794
1178
  };
795
- } catch (onErrorErr) {
796
- logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
797
- return { response: failClosed() };
1179
+ } catch {
1180
+ if (!diagnosticsEnabled) logger.error("chain error handler failed");
1181
+ diagnostics?.push({
1182
+ name: safeDiagnosticText(label, 64),
1183
+ outcome: timeoutError ? "timeout" : "failed",
1184
+ durationMs: durationMs(),
1185
+ policy: errorPolicy,
1186
+ details: handlerDetails(rules[i], ruleTimeoutMs, "matched", "matched", "not-matched")
1187
+ });
1188
+ nextHandlerIndex = i + 1;
1189
+ return {
1190
+ response: finish(failClosed(), {
1191
+ type: "error",
1192
+ status: 500,
1193
+ classification: "handler"
1194
+ })
1195
+ };
798
1196
  }
799
1197
  };
800
1198
  try {
@@ -807,22 +1205,57 @@ function proxyChain(optionsOrEntries, maybeEntries) {
807
1205
  );
808
1206
  const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
809
1207
  if (matchPath === null) {
810
- return new NextResponse2("Bad Request", {
811
- status: 400,
812
- headers: { "content-type": "text/plain; charset=utf-8" }
1208
+ return finish(
1209
+ new NextResponse2("Bad Request", {
1210
+ status: 400,
1211
+ headers: { "content-type": "text/plain; charset=utf-8" }
1212
+ })
1213
+ );
1214
+ }
1215
+ nextHandlerIndex = i;
1216
+ const skipReason = ruleMatchReason(matchPath, reqHost, rule);
1217
+ if (skipReason) {
1218
+ diagnostics?.push({
1219
+ name: safeDiagnosticText(label, 64),
1220
+ outcome: "skipped",
1221
+ reason: skipReason,
1222
+ details: handlerDetails(
1223
+ rule,
1224
+ ruleTimeoutMs,
1225
+ "not-evaluated",
1226
+ skipReason === "include-mismatch" ? "mismatch" : void 0,
1227
+ skipReason === "exclude-match" ? "matched" : skipReason === "include-mismatch" && rule.exclude ? "not-matched" : void 0
1228
+ )
813
1229
  });
1230
+ nextHandlerIndex = i + 1;
1231
+ continue;
814
1232
  }
815
- if (!ruleMatches(matchPath, reqHost, rule)) continue;
816
- const startedAt = debug ? performance.now() : 0;
1233
+ const startedAt2 = diagnosticsEnabled ? monotonicNow() : 0;
817
1234
  let raw;
818
1235
  try {
819
- raw = await withRuleTimeout(
820
- Promise.resolve(rule.run(activeReq, ctx, event)),
821
- ruleTimeoutMs,
1236
+ const result = await withRuleTimeout(
1237
+ (async () => {
1238
+ if (rule.when && !await rule.when(activeReq, event, ctx)) {
1239
+ return { kind: "skipped" };
1240
+ }
1241
+ return { kind: "result", raw: await rule.run(activeReq, ctx, event) };
1242
+ })(),
1243
+ rule.timeout ?? ruleTimeoutMs,
822
1244
  label
823
1245
  );
1246
+ if (result.kind === "skipped") {
1247
+ diagnostics?.push({
1248
+ name: safeDiagnosticText(label, 64),
1249
+ outcome: "skipped",
1250
+ reason: "when-false",
1251
+ details: handlerDetails(rule, ruleTimeoutMs, "false", "matched", "not-matched")
1252
+ });
1253
+ nextHandlerIndex = i + 1;
1254
+ continue;
1255
+ }
1256
+ raw = result.raw;
824
1257
  } catch (err) {
825
- const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
1258
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt2);
826
1259
  if ("response" in recovered) return recovered.response;
827
1260
  raw = recovered.raw;
828
1261
  }
@@ -830,11 +1263,11 @@ function proxyChain(optionsOrEntries, maybeEntries) {
830
1263
  try {
831
1264
  outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
832
1265
  } catch (err) {
833
- const recovered = await recoverRuleError(err, i, label, activeReq, startedAt);
1266
+ const recovered = await recoverRuleError(err, i, label, activeReq, startedAt2);
834
1267
  if ("response" in recovered) return recovered.response;
835
1268
  outcome = resolveRuleResult(recovered.raw, requestHeaderPolicy, logger, debug);
836
1269
  }
837
- const duration = debug ? performance.now() - startedAt : 0;
1270
+ const duration2 = diagnosticsEnabled ? monotonicNow() - startedAt2 : 0;
838
1271
  if (outcome.kind === "continue") {
839
1272
  if (outcome.rewriteUrl) {
840
1273
  pendingRewriteUrl = outcome.rewriteUrl;
@@ -854,18 +1287,37 @@ function proxyChain(optionsOrEntries, maybeEntries) {
854
1287
  headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
855
1288
  cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
856
1289
  }
857
- if (debug) {
858
- const mutated = outcome.responseHeaders.size + outcome.cookies.size + (outcome.request ? 1 : 0) + (outcome.rewriteUrl ? 1 : 0);
859
- logger.debug(
860
- formatPipelineLine({
861
- method,
862
- path: pathname,
863
- name: label,
864
- traceId,
865
- outcome: mutated === 0 ? { kind: "passed", duration } : { kind: "next", duration, headers: outcome.responseHeaders.size }
866
- })
1290
+ if (diagnostics?.at(-1)?.outcome !== "recovered") {
1291
+ diagnostics?.push(
1292
+ outcome.rewriteUrl ? {
1293
+ name: safeDiagnosticText(label, 64),
1294
+ outcome: "rewrite",
1295
+ durationMs: duration2,
1296
+ destination: safeDestination(outcome.rewriteUrl) ?? "/",
1297
+ final: false,
1298
+ details: handlerDetails(
1299
+ rule,
1300
+ ruleTimeoutMs,
1301
+ "matched",
1302
+ "matched",
1303
+ "not-matched"
1304
+ )
1305
+ } : {
1306
+ name: safeDiagnosticText(label, 64),
1307
+ outcome: "continue",
1308
+ source: isNextResult(raw) ? "next()" : raw instanceof NextResponse2 && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1309
+ durationMs: duration2,
1310
+ details: handlerDetails(
1311
+ rule,
1312
+ ruleTimeoutMs,
1313
+ "matched",
1314
+ "matched",
1315
+ "not-matched"
1316
+ )
1317
+ }
867
1318
  );
868
1319
  }
1320
+ nextHandlerIndex = i + 1;
869
1321
  continue;
870
1322
  }
871
1323
  stripRoutingOverrides(outcome.response);
@@ -879,21 +1331,31 @@ function proxyChain(optionsOrEntries, maybeEntries) {
879
1331
  ruleName: label,
880
1332
  items: cookieItemsFromHeaders(outcome.response.headers)
881
1333
  });
882
- if (debug) {
883
- logger.debug(
884
- formatPipelineLine({
885
- method,
886
- path: pathname,
887
- name: label,
888
- traceId,
889
- outcome: {
890
- kind: "stop",
891
- duration,
892
- status: outcome.response.status
893
- }
894
- })
895
- );
896
- }
1334
+ const terminalOutcome = responseOutcome(outcome.response);
1335
+ diagnostics?.push(
1336
+ terminalOutcome.type === "redirect" ? {
1337
+ name: safeDiagnosticText(label, 64),
1338
+ outcome: "redirect",
1339
+ durationMs: duration2,
1340
+ status: terminalOutcome.status,
1341
+ destination: terminalOutcome.destination,
1342
+ details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1343
+ } : terminalOutcome.type === "rewrite" ? {
1344
+ name: safeDiagnosticText(label, 64),
1345
+ outcome: "rewrite",
1346
+ durationMs: duration2,
1347
+ destination: terminalOutcome.destination,
1348
+ final: true,
1349
+ details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1350
+ } : {
1351
+ name: safeDiagnosticText(label, 64),
1352
+ outcome: "response",
1353
+ durationMs: duration2,
1354
+ status: outcome.response.status,
1355
+ details: handlerDetails(rule, ruleTimeoutMs, "matched", "matched", "not-matched")
1356
+ }
1357
+ );
1358
+ nextHandlerIndex = i + 1;
897
1359
  const internalFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
898
1360
  if (internalFolder && outcome.response.headers.has("x-middleware-rewrite")) {
899
1361
  const rawRewrite = outcome.response.headers.get("x-middleware-rewrite");
@@ -903,14 +1365,22 @@ function proxyChain(optionsOrEntries, maybeEntries) {
903
1365
  applyFolderPrefix(rawRewrite, cleanFolder, currentReq.url)
904
1366
  );
905
1367
  }
906
- return finalizeResponse(
907
- outcome.response,
908
- headerWrites,
909
- cookieWrites,
910
- headerMergeStrategy,
911
- cookieMergeStrategy,
912
- logger,
913
- debug
1368
+ const finalTerminalOutcome = responseOutcome(outcome.response);
1369
+ const terminalTrace = diagnostics?.at(-1);
1370
+ if (finalTerminalOutcome.type === "rewrite" && terminalTrace?.outcome === "rewrite") {
1371
+ terminalTrace.destination = finalTerminalOutcome.destination;
1372
+ }
1373
+ return finish(
1374
+ finalizeResponse(
1375
+ outcome.response,
1376
+ headerWrites,
1377
+ cookieWrites,
1378
+ headerMergeStrategy,
1379
+ cookieMergeStrategy,
1380
+ logger,
1381
+ debug
1382
+ ),
1383
+ finalTerminalOutcome
914
1384
  );
915
1385
  }
916
1386
  const finalReq = materializeRequest();
@@ -937,7 +1407,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
937
1407
  } else {
938
1408
  final = NextResponse2.next(requestInit);
939
1409
  }
940
- return finalizeResponse(
1410
+ const finalResponse = finalizeResponse(
941
1411
  final,
942
1412
  headerWrites,
943
1413
  cookieWrites,
@@ -946,27 +1416,41 @@ function proxyChain(optionsOrEntries, maybeEntries) {
946
1416
  logger,
947
1417
  debug
948
1418
  );
1419
+ if (finalRewriteUrl) {
1420
+ const destination = safeDestination(finalRewriteUrl) ?? "/";
1421
+ const rewrite = diagnostics?.filter((handler) => handler.outcome === "rewrite").at(-1);
1422
+ if (rewrite?.outcome === "rewrite") {
1423
+ rewrite.destination = destination;
1424
+ rewrite.final = true;
1425
+ }
1426
+ }
1427
+ return finish(finalResponse);
949
1428
  } catch (err) {
950
- logger.error({ err }, "proxy chain failed");
1429
+ if (!diagnosticsEnabled) logger.error("proxy chain execution failed");
951
1430
  if (config.onError) {
952
1431
  try {
953
1432
  const recovered = await config.onError(err, -1, materializeRequest(), ctx);
954
1433
  if (recovered instanceof Response && !isNextResponse(recovered)) {
955
1434
  stripRoutingOverrides(recovered);
956
- return finalizeResponse(
957
- recovered,
958
- headerWrites,
959
- cookieWrites,
960
- headerMergeStrategy,
961
- cookieMergeStrategy,
962
- logger,
963
- debug
1435
+ return finish(
1436
+ finalizeResponse(
1437
+ recovered,
1438
+ headerWrites,
1439
+ cookieWrites,
1440
+ headerMergeStrategy,
1441
+ cookieMergeStrategy,
1442
+ logger,
1443
+ debug
1444
+ )
964
1445
  );
965
1446
  }
966
1447
  } catch {
967
1448
  }
968
1449
  }
969
- return failClosed();
1450
+ return finish(
1451
+ failClosed(),
1452
+ err instanceof RuleTimeoutError ? { type: "timeout", status: 500, timeoutMs: err.timeoutMs } : { type: "error", status: 500, classification: "engine" }
1453
+ );
970
1454
  }
971
1455
  };
972
1456
  }
@@ -1002,10 +1486,32 @@ function chain(entries, options) {
1002
1486
  const normalized = entries.map((entry) => toEntry(entry));
1003
1487
  return proxyChain(options ?? {}, normalized);
1004
1488
  }
1489
+
1490
+ // src/core/handler.ts
1491
+ function defineHandler(options) {
1492
+ const include = compileScopes(options.rules?.include);
1493
+ const exclude = compileScopes(options.rules?.exclude);
1494
+ const rule = {
1495
+ run: (request, context, event) => options.handler(request, event, context),
1496
+ name: options.name,
1497
+ include,
1498
+ exclude,
1499
+ debug: options.debug,
1500
+ timeout: options.timeout,
1501
+ when: options.rules?.when,
1502
+ onError: options.onError,
1503
+ diagnosticRules: {
1504
+ include: options.rules?.include,
1505
+ exclude: options.rules?.exclude
1506
+ }
1507
+ };
1508
+ return rule;
1509
+ }
1005
1510
  export {
1006
1511
  RuleTimeoutError,
1007
1512
  chain,
1008
1513
  createProxyContext,
1514
+ defineHandler,
1009
1515
  defineProxy,
1010
1516
  host,
1011
1517
  isNextResult,