@klnap/next-proxy-chain 1.1.1 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +195 -79
- package/dist/index.cjs +956 -258
- package/dist/index.d.cts +164 -82
- package/dist/index.d.ts +164 -82
- package/dist/index.js +954 -254
- package/package.json +35 -22
package/dist/index.cjs
CHANGED
|
@@ -22,13 +22,11 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
RuleTimeoutError: () => RuleTimeoutError,
|
|
24
24
|
chain: () => chain,
|
|
25
|
-
|
|
26
|
-
defineProxy: () => defineProxy,
|
|
25
|
+
defineHandler: () => defineHandler,
|
|
27
26
|
host: () => host,
|
|
28
27
|
isNextResult: () => isNextResult,
|
|
29
28
|
next: () => next,
|
|
30
|
-
path: () => path
|
|
31
|
-
proxyChain: () => proxyChain
|
|
29
|
+
path: () => path
|
|
32
30
|
});
|
|
33
31
|
module.exports = __toCommonJS(index_exports);
|
|
34
32
|
|
|
@@ -54,7 +52,7 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
|
|
|
54
52
|
"x-middleware-next",
|
|
55
53
|
"x-middleware-override-headers"
|
|
56
54
|
]);
|
|
57
|
-
var
|
|
55
|
+
var DEFINED_HANDLER = /* @__PURE__ */ Symbol.for("proxy-chain.defined-handler");
|
|
58
56
|
|
|
59
57
|
// src/core/actions.ts
|
|
60
58
|
function next(options = {}) {
|
|
@@ -65,11 +63,88 @@ function isNextResult(value) {
|
|
|
65
63
|
}
|
|
66
64
|
|
|
67
65
|
// src/core/engine.ts
|
|
68
|
-
var import_server2 = require("next/server");
|
|
66
|
+
var import_server2 = require("next/server.js");
|
|
69
67
|
|
|
70
68
|
// src/core/context.ts
|
|
71
|
-
|
|
72
|
-
|
|
69
|
+
var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
|
|
70
|
+
"requestId",
|
|
71
|
+
"startedAt",
|
|
72
|
+
"elapsedMs",
|
|
73
|
+
"originalUrl",
|
|
74
|
+
"originalPathname",
|
|
75
|
+
"originalHostname",
|
|
76
|
+
"signal"
|
|
77
|
+
]);
|
|
78
|
+
function createRequestMetadata(request, requestId, startedAt, invocationStartedAt) {
|
|
79
|
+
const metadata = /* @__PURE__ */ Object.create(null);
|
|
80
|
+
Object.defineProperties(metadata, {
|
|
81
|
+
requestId: { value: requestId, enumerable: true },
|
|
82
|
+
startedAt: { value: startedAt, enumerable: true },
|
|
83
|
+
elapsedMs: {
|
|
84
|
+
get: () => performance.now() - invocationStartedAt,
|
|
85
|
+
enumerable: true
|
|
86
|
+
},
|
|
87
|
+
originalUrl: { value: request.url, enumerable: true },
|
|
88
|
+
originalPathname: { value: request.nextUrl.pathname, enumerable: true },
|
|
89
|
+
originalHostname: { value: request.nextUrl.hostname, enumerable: true }
|
|
90
|
+
});
|
|
91
|
+
return metadata;
|
|
92
|
+
}
|
|
93
|
+
function createApplicationState() {
|
|
94
|
+
return /* @__PURE__ */ Object.create(null);
|
|
95
|
+
}
|
|
96
|
+
function createHandlerContext(metadata, applicationState, signal) {
|
|
97
|
+
const target = /* @__PURE__ */ Object.create(null);
|
|
98
|
+
Object.defineProperties(target, {
|
|
99
|
+
requestId: { value: metadata.requestId, enumerable: true },
|
|
100
|
+
startedAt: { value: metadata.startedAt, enumerable: true },
|
|
101
|
+
elapsedMs: { get: () => metadata.elapsedMs, enumerable: true },
|
|
102
|
+
originalUrl: { value: metadata.originalUrl, enumerable: true },
|
|
103
|
+
originalPathname: { value: metadata.originalPathname, enumerable: true },
|
|
104
|
+
originalHostname: { value: metadata.originalHostname, enumerable: true },
|
|
105
|
+
signal: { value: signal, enumerable: true }
|
|
106
|
+
});
|
|
107
|
+
return new Proxy(target, {
|
|
108
|
+
get(view, property) {
|
|
109
|
+
return Reflect.has(view, property) ? Reflect.get(view, property, view) : Reflect.get(applicationState, property, applicationState);
|
|
110
|
+
},
|
|
111
|
+
set(_view, property, value) {
|
|
112
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
113
|
+
return Reflect.set(applicationState, property, value, applicationState);
|
|
114
|
+
},
|
|
115
|
+
deleteProperty(_view, property) {
|
|
116
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
117
|
+
return Reflect.deleteProperty(applicationState, property);
|
|
118
|
+
},
|
|
119
|
+
defineProperty(_view, property, descriptor) {
|
|
120
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
121
|
+
return Reflect.defineProperty(applicationState, property, {
|
|
122
|
+
...descriptor,
|
|
123
|
+
configurable: true
|
|
124
|
+
});
|
|
125
|
+
},
|
|
126
|
+
getPrototypeOf() {
|
|
127
|
+
return null;
|
|
128
|
+
},
|
|
129
|
+
setPrototypeOf() {
|
|
130
|
+
return false;
|
|
131
|
+
},
|
|
132
|
+
has(view, property) {
|
|
133
|
+
return Reflect.has(view, property) || Reflect.has(applicationState, property);
|
|
134
|
+
},
|
|
135
|
+
ownKeys(view) {
|
|
136
|
+
return [.../* @__PURE__ */ new Set([...Reflect.ownKeys(view), ...Reflect.ownKeys(applicationState)])];
|
|
137
|
+
},
|
|
138
|
+
getOwnPropertyDescriptor(view, property) {
|
|
139
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(view, property);
|
|
140
|
+
if (descriptor) return descriptor;
|
|
141
|
+
const applicationDescriptor = Reflect.getOwnPropertyDescriptor(applicationState, property);
|
|
142
|
+
return applicationDescriptor ? { ...applicationDescriptor, configurable: true } : void 0;
|
|
143
|
+
},
|
|
144
|
+
preventExtensions() {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
});
|
|
73
148
|
}
|
|
74
149
|
|
|
75
150
|
// src/core/headers.ts
|
|
@@ -214,30 +289,6 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
|
|
|
214
289
|
}
|
|
215
290
|
}
|
|
216
291
|
|
|
217
|
-
// src/core/host-folder-prefix.ts
|
|
218
|
-
function physicalFolderPrefix(raw) {
|
|
219
|
-
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
220
|
-
}
|
|
221
|
-
function isInsideFolder(pathname, folder) {
|
|
222
|
-
if (folder === "/") return true;
|
|
223
|
-
return pathname === folder || pathname.startsWith(`${folder}/`);
|
|
224
|
-
}
|
|
225
|
-
function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
|
|
226
|
-
try {
|
|
227
|
-
const parsed = new URL(rewriteUrl, baseUrl);
|
|
228
|
-
if (!isInsideFolder(parsed.pathname, folder)) {
|
|
229
|
-
parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
230
|
-
return parsed.toString();
|
|
231
|
-
}
|
|
232
|
-
return rewriteUrl;
|
|
233
|
-
} catch {
|
|
234
|
-
if (!isInsideFolder(rewriteUrl, folder)) {
|
|
235
|
-
return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
|
|
236
|
-
}
|
|
237
|
-
return rewriteUrl;
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
|
|
241
292
|
// src/core/logger.ts
|
|
242
293
|
var LEVEL_RANK = {
|
|
243
294
|
debug: 10,
|
|
@@ -264,22 +315,215 @@ function createConsoleLogger(minLevel = "info") {
|
|
|
264
315
|
error: write("error")
|
|
265
316
|
};
|
|
266
317
|
}
|
|
267
|
-
|
|
318
|
+
|
|
319
|
+
// src/core/diagnostics/sanitize.ts
|
|
320
|
+
var MAX_TEXT_LENGTH = 160;
|
|
321
|
+
function safeDiagnosticText(value, limit = MAX_TEXT_LENGTH) {
|
|
322
|
+
let output = "";
|
|
323
|
+
for (const char of value) {
|
|
324
|
+
const code = char.codePointAt(0);
|
|
325
|
+
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) {
|
|
326
|
+
output += "\uFFFD";
|
|
327
|
+
} else {
|
|
328
|
+
output += char;
|
|
329
|
+
}
|
|
330
|
+
if (output.length >= limit) return `${output.slice(0, limit)}\u2026`;
|
|
331
|
+
}
|
|
332
|
+
return output;
|
|
333
|
+
}
|
|
334
|
+
function safeDestination(value) {
|
|
335
|
+
if (!value) return void 0;
|
|
336
|
+
try {
|
|
337
|
+
const url = new URL(value, "http://proxy-chain.invalid");
|
|
338
|
+
return safeDiagnosticText(`${url.pathname}${url.search ? "?[query]" : ""}`);
|
|
339
|
+
} catch {
|
|
340
|
+
return safeDiagnosticText(value.split(/[?#]/, 1)[0] ?? "");
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/core/diagnostics/formatter.ts
|
|
345
|
+
function runtime() {
|
|
346
|
+
return globalThis.process;
|
|
347
|
+
}
|
|
348
|
+
function shouldUseColor() {
|
|
349
|
+
const process = runtime();
|
|
350
|
+
const env = process?.env;
|
|
351
|
+
if (env?.NO_COLOR) return false;
|
|
352
|
+
if (env?.FORCE_COLOR) return env.FORCE_COLOR !== "0";
|
|
353
|
+
if (env?.CI || env?.TERM === "dumb" || !process?.stdout?.isTTY) return false;
|
|
354
|
+
try {
|
|
355
|
+
return process.stdout.getColorDepth?.() !== 1;
|
|
356
|
+
} catch {
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function supportsUnicode() {
|
|
361
|
+
const process = runtime();
|
|
362
|
+
if (!process?.env) return false;
|
|
363
|
+
const env = process.env;
|
|
364
|
+
const locale = (env.LC_ALL || env.LC_CTYPE || env.LANG || "").toLowerCase();
|
|
365
|
+
return !/(^|\s)(c|posix)(\.|$|\s)/.test(locale) && !locale.includes("ascii");
|
|
366
|
+
}
|
|
367
|
+
function paint(text, code, enabled) {
|
|
368
|
+
return enabled ? `\x1B[${code}m${text}\x1B[0m` : text;
|
|
369
|
+
}
|
|
370
|
+
function duration(ms) {
|
|
268
371
|
return `${ms.toFixed(2)}ms`;
|
|
269
372
|
}
|
|
270
|
-
function
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
373
|
+
function handlerLabel(handler) {
|
|
374
|
+
switch (handler.outcome) {
|
|
375
|
+
case "continue":
|
|
376
|
+
return { symbol: "\u2713", text: "continue", color: 32 };
|
|
377
|
+
case "rewrite":
|
|
378
|
+
return { symbol: "\u21AA", text: "rewrite", color: 36 };
|
|
379
|
+
case "redirect":
|
|
380
|
+
return { symbol: "\u2197", text: "redirect", color: 33 };
|
|
381
|
+
case "response":
|
|
382
|
+
return { symbol: "\u2713", text: `response ${handler.status}`, color: 32 };
|
|
383
|
+
case "skipped":
|
|
384
|
+
return { symbol: "\u25CB", text: "skipped", color: 2 };
|
|
385
|
+
case "not-reached":
|
|
386
|
+
return { symbol: "\u2013", text: "not reached", color: 2 };
|
|
387
|
+
case "recovered":
|
|
388
|
+
return { symbol: "!", text: "recovered", color: 33 };
|
|
389
|
+
case "timeout":
|
|
390
|
+
return { symbol: "\xD7", text: "timeout", color: 31 };
|
|
391
|
+
case "request-cancelled":
|
|
392
|
+
return { symbol: "\u2298", text: "request cancelled", color: 33 };
|
|
393
|
+
case "failed":
|
|
394
|
+
return { symbol: "\xD7", text: "failed", color: 31 };
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function outcomeText(outcome) {
|
|
398
|
+
switch (outcome.type) {
|
|
399
|
+
case "next":
|
|
400
|
+
return "NEXT";
|
|
401
|
+
case "rewrite":
|
|
402
|
+
return `REWRITE ${outcome.destination}`;
|
|
403
|
+
case "redirect":
|
|
404
|
+
return `REDIRECT ${outcome.status}${outcome.destination ? ` ${outcome.destination}` : ""}`;
|
|
405
|
+
case "response":
|
|
406
|
+
return `RESPONSE ${outcome.status}`;
|
|
407
|
+
case "error":
|
|
408
|
+
return `ERROR ${outcome.status}`;
|
|
409
|
+
case "timeout":
|
|
410
|
+
return `ERROR ${outcome.status} \xB7 timeout ${outcome.timeoutMs}ms`;
|
|
411
|
+
case "request-cancelled":
|
|
412
|
+
return "REQUEST CANCELLED";
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
function outcomeColor(outcome) {
|
|
416
|
+
switch (outcome.type) {
|
|
277
417
|
case "next":
|
|
278
|
-
return
|
|
279
|
-
case "
|
|
280
|
-
return
|
|
418
|
+
return 32;
|
|
419
|
+
case "rewrite":
|
|
420
|
+
return 36;
|
|
421
|
+
case "redirect":
|
|
422
|
+
return 33;
|
|
423
|
+
case "error":
|
|
424
|
+
case "timeout":
|
|
425
|
+
return 31;
|
|
426
|
+
case "request-cancelled":
|
|
427
|
+
return 33;
|
|
428
|
+
case "response":
|
|
429
|
+
return outcome.status >= 500 ? 31 : 32;
|
|
281
430
|
}
|
|
282
431
|
}
|
|
432
|
+
function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
|
|
433
|
+
const path2 = trace.pathname ? ` ${safeDiagnosticText(trace.pathname)}` : "";
|
|
434
|
+
const header = `[proxy-chain] ${safeDiagnosticText(trace.method)}${path2}`;
|
|
435
|
+
const rows = [];
|
|
436
|
+
const handlers = trace.handlers;
|
|
437
|
+
if (level === "compact") {
|
|
438
|
+
const reached = handlers.filter((handler) => handler.outcome !== "not-reached").length;
|
|
439
|
+
return `[proxy-chain] ${safeDiagnosticText(trace.requestId)} \xB7 ${safeDiagnosticText(trace.method)}${path2} \xB7 ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)} \xB7 ${paint(duration(trace.durationMs), 2, color)} \xB7 ${reached}/${handlers.length} handlers`;
|
|
440
|
+
}
|
|
441
|
+
rows.push(header);
|
|
442
|
+
rows.push(` Request: ${safeDiagnosticText(trace.requestId, 64)}`);
|
|
443
|
+
const shown = handlers;
|
|
444
|
+
const symbols = unicode ? {
|
|
445
|
+
pass: "\u2502",
|
|
446
|
+
last: "\u2514",
|
|
447
|
+
continue: "\u2713",
|
|
448
|
+
rewrite: "\u21AA",
|
|
449
|
+
redirect: "\u2197",
|
|
450
|
+
skip: "\u25CB",
|
|
451
|
+
missing: "\u2013",
|
|
452
|
+
error: "\xD7",
|
|
453
|
+
cancelled: "\u2298",
|
|
454
|
+
recovered: "!"
|
|
455
|
+
} : {
|
|
456
|
+
pass: "|",
|
|
457
|
+
last: "`-",
|
|
458
|
+
continue: "+",
|
|
459
|
+
rewrite: "->",
|
|
460
|
+
redirect: "->",
|
|
461
|
+
skip: "o",
|
|
462
|
+
missing: "-",
|
|
463
|
+
error: "x",
|
|
464
|
+
cancelled: "!",
|
|
465
|
+
recovered: "!"
|
|
466
|
+
};
|
|
467
|
+
for (let index = 0; index < shown.length; index++) {
|
|
468
|
+
const handler = shown[index];
|
|
469
|
+
const label = handlerLabel(handler);
|
|
470
|
+
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 : handler.outcome === "request-cancelled" ? symbols.cancelled : symbols.error;
|
|
471
|
+
const prefix = symbols.pass;
|
|
472
|
+
const name = safeDiagnosticText(handler.name, 32);
|
|
473
|
+
const time = "durationMs" in handler ? paint(duration(handler.durationMs), 2, color) : "";
|
|
474
|
+
rows.push(
|
|
475
|
+
`${prefix} ${paint(symbol, label.color, color)} ${name.padEnd(16)} ${label.text.padEnd(14)} ${time}`.trimEnd()
|
|
476
|
+
);
|
|
477
|
+
if (level === "verbose") {
|
|
478
|
+
if (handler.details?.timeoutMs !== void 0) {
|
|
479
|
+
rows.push(
|
|
480
|
+
`${symbols.pass} timeout: ${handler.details.timeoutMs}ms (${handler.details.timeoutSource ?? "chain"})`
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
if (handler.details?.include) {
|
|
484
|
+
rows.push(
|
|
485
|
+
`${symbols.pass} include: ${handler.details.include.join(", ")}${handler.details.includeResult ? ` (${handler.details.includeResult})` : ""}`
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
if (handler.details?.exclude) {
|
|
489
|
+
rows.push(
|
|
490
|
+
`${symbols.pass} exclude: ${handler.details.exclude.join(", ")}${handler.details.excludeResult ? ` (${handler.details.excludeResult})` : ""}`
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
if (handler.details?.when) {
|
|
494
|
+
rows.push(
|
|
495
|
+
`${symbols.pass} when: ${handler.details.when === "matched" ? "true" : handler.details.when === "false" ? "false" : "not evaluated"}`
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
if (handler.outcome === "continue") rows.push(`${symbols.pass} source: ${handler.source}`);
|
|
499
|
+
if (handler.outcome === "skipped") rows.push(`${symbols.pass} reason: ${handler.reason}`);
|
|
500
|
+
if (handler.outcome === "rewrite") {
|
|
501
|
+
rows.push(`${symbols.pass} destination: ${handler.destination}`);
|
|
502
|
+
}
|
|
503
|
+
if (handler.outcome === "redirect" && handler.destination) {
|
|
504
|
+
rows.push(`${symbols.pass} destination: ${handler.destination}`);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout" || handler.outcome === "request-cancelled") {
|
|
508
|
+
const policy = handler.policy === "none" ? "chain default" : handler.policy;
|
|
509
|
+
rows.push(
|
|
510
|
+
`${symbols.pass} ${handler.outcome === "request-cancelled" ? "cancellation policy" : "error policy"}: ${policy}`
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
if (handler.outcome === "timeout" && handler.timeoutMs !== void 0) {
|
|
514
|
+
rows.push(`${symbols.pass} deadline: ${handler.timeoutMs}ms`);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
rows.push(
|
|
518
|
+
`${symbols.last} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)}`
|
|
519
|
+
);
|
|
520
|
+
rows.push(` Total: ${paint(duration(trace.durationMs), 2, color)}`);
|
|
521
|
+
const output = rows.join("\n");
|
|
522
|
+
if (output.length <= 16384) return output;
|
|
523
|
+
const safeBoundary = output.lastIndexOf("\n", 16384);
|
|
524
|
+
return `${output.slice(0, safeBoundary < 0 ? 16384 : safeBoundary)}
|
|
525
|
+
${unicode ? "\u2026" : "..."} diagnostics truncated`;
|
|
526
|
+
}
|
|
283
527
|
|
|
284
528
|
// src/core/matching.ts
|
|
285
529
|
var RESERVED_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
|
|
@@ -435,14 +679,25 @@ function withPaths(entry, filter) {
|
|
|
435
679
|
const exclude = compileScopes(filter.exclude);
|
|
436
680
|
const name = filter.name ?? base.name;
|
|
437
681
|
assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
|
|
438
|
-
return {
|
|
682
|
+
return {
|
|
683
|
+
run: base.run,
|
|
684
|
+
include,
|
|
685
|
+
exclude,
|
|
686
|
+
name,
|
|
687
|
+
debug: base.debug,
|
|
688
|
+
timeout: base.timeout,
|
|
689
|
+
when: base.when,
|
|
690
|
+
diagnosticRules: { include: filter.include, exclude: filter.exclude }
|
|
691
|
+
};
|
|
439
692
|
}
|
|
440
|
-
function
|
|
441
|
-
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope)))
|
|
693
|
+
function ruleMatchReason(pathname, hostname, rule) {
|
|
694
|
+
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
695
|
+
return "exclude-match";
|
|
696
|
+
}
|
|
442
697
|
if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
443
|
-
return
|
|
698
|
+
return "include-mismatch";
|
|
444
699
|
}
|
|
445
|
-
return
|
|
700
|
+
return void 0;
|
|
446
701
|
}
|
|
447
702
|
function normalizeHost(raw) {
|
|
448
703
|
if (!raw) return null;
|
|
@@ -480,7 +735,7 @@ function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
|
480
735
|
}
|
|
481
736
|
|
|
482
737
|
// src/core/pipeline.ts
|
|
483
|
-
var import_server = require("next/server");
|
|
738
|
+
var import_server = require("next/server.js");
|
|
484
739
|
function safeInternalError() {
|
|
485
740
|
return new import_server.NextResponse("Internal Server Error", {
|
|
486
741
|
status: 500,
|
|
@@ -561,14 +816,16 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
561
816
|
if (res instanceof import_server.NextResponse && res.headers.get("x-middleware-next") === "1") {
|
|
562
817
|
let request;
|
|
563
818
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
564
|
-
|
|
819
|
+
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
820
|
+
if (hasRequestOverride) {
|
|
565
821
|
const target = new Headers();
|
|
566
822
|
mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
|
|
567
|
-
|
|
823
|
+
request = target;
|
|
568
824
|
}
|
|
569
825
|
return {
|
|
570
826
|
kind: "continue",
|
|
571
827
|
request,
|
|
828
|
+
...hasRequestOverride ? { requestMode: "replace" } : {},
|
|
572
829
|
responseHeaders: responseHeaderItems(res.headers),
|
|
573
830
|
cookies: cookieItemsFromHeaders(res.headers)
|
|
574
831
|
};
|
|
@@ -577,14 +834,16 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
577
834
|
if (rewriteHeader && (res.status === 200 || !res.status)) {
|
|
578
835
|
let request;
|
|
579
836
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
580
|
-
|
|
837
|
+
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
838
|
+
if (hasRequestOverride) {
|
|
581
839
|
const target = new Headers();
|
|
582
840
|
mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
|
|
583
|
-
|
|
841
|
+
request = target;
|
|
584
842
|
}
|
|
585
843
|
return {
|
|
586
844
|
kind: "continue",
|
|
587
845
|
request,
|
|
846
|
+
...hasRequestOverride ? { requestMode: "replace" } : {},
|
|
588
847
|
responseHeaders: responseHeaderItems(res.headers),
|
|
589
848
|
cookies: cookieItemsFromHeaders(res.headers),
|
|
590
849
|
rewriteUrl: rewriteHeader
|
|
@@ -623,6 +882,7 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
|
|
|
623
882
|
}
|
|
624
883
|
|
|
625
884
|
// src/core/timeout.ts
|
|
885
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
626
886
|
var RuleTimeoutError = class extends Error {
|
|
627
887
|
ruleName;
|
|
628
888
|
timeoutMs;
|
|
@@ -633,117 +893,281 @@ var RuleTimeoutError = class extends Error {
|
|
|
633
893
|
this.timeoutMs = timeoutMs;
|
|
634
894
|
}
|
|
635
895
|
};
|
|
636
|
-
|
|
637
|
-
|
|
896
|
+
var RequestCancellationError = class extends Error {
|
|
897
|
+
constructor() {
|
|
898
|
+
super("[proxy-chain] incoming request was cancelled");
|
|
899
|
+
this.name = "AbortError";
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
function assertValidTimeout(timeoutMs) {
|
|
903
|
+
if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS)) {
|
|
638
904
|
throw new RangeError(
|
|
639
|
-
`[proxy-chain]
|
|
905
|
+
`[proxy-chain] timeout must be an integer from 0 through ${MAX_TIMEOUT_MS} milliseconds`
|
|
640
906
|
);
|
|
641
907
|
}
|
|
642
908
|
}
|
|
643
|
-
async function
|
|
644
|
-
|
|
645
|
-
|
|
909
|
+
async function runInExecutionScope(requestSignal, timeoutMs, ruleName, run) {
|
|
910
|
+
assertValidTimeout(timeoutMs);
|
|
911
|
+
const controller = new AbortController();
|
|
912
|
+
if (requestSignal.aborted) {
|
|
913
|
+
controller.abort();
|
|
914
|
+
throw new RequestCancellationError();
|
|
915
|
+
}
|
|
916
|
+
const scopeStartedAt = performance.now();
|
|
917
|
+
const timeoutError = timeoutMs > 0 ? new RuleTimeoutError(ruleName, timeoutMs) : void 0;
|
|
918
|
+
let failure;
|
|
919
|
+
let rejectCancelled;
|
|
920
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
921
|
+
rejectCancelled = reject;
|
|
922
|
+
});
|
|
923
|
+
const cancel = (error) => {
|
|
924
|
+
if (failure) return;
|
|
925
|
+
failure = error;
|
|
926
|
+
controller.abort();
|
|
927
|
+
rejectCancelled(error);
|
|
928
|
+
};
|
|
929
|
+
const assertActive = () => {
|
|
930
|
+
if (requestSignal.aborted) cancel(new RequestCancellationError());
|
|
931
|
+
else if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
932
|
+
cancel(timeoutError);
|
|
933
|
+
}
|
|
934
|
+
if (failure) throw failure;
|
|
935
|
+
};
|
|
936
|
+
const onRequestAbort = () => cancel(new RequestCancellationError());
|
|
937
|
+
requestSignal.addEventListener("abort", onRequestAbort, { once: true });
|
|
646
938
|
let timer;
|
|
647
|
-
|
|
648
|
-
timer = setTimeout(() =>
|
|
939
|
+
if (timeoutError) {
|
|
940
|
+
timer = setTimeout(() => cancel(timeoutError), timeoutMs);
|
|
941
|
+
}
|
|
942
|
+
const work = Promise.resolve().then(async () => {
|
|
943
|
+
if (controller.signal.aborted) throw failure ?? new RequestCancellationError();
|
|
944
|
+
try {
|
|
945
|
+
const result = await run(controller.signal, assertActive);
|
|
946
|
+
if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
947
|
+
cancel(timeoutError);
|
|
948
|
+
}
|
|
949
|
+
if (failure) throw failure;
|
|
950
|
+
return result;
|
|
951
|
+
} catch (error) {
|
|
952
|
+
if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
953
|
+
cancel(timeoutError);
|
|
954
|
+
}
|
|
955
|
+
throw failure ?? error;
|
|
956
|
+
}
|
|
649
957
|
});
|
|
650
958
|
try {
|
|
651
|
-
return await Promise.race([
|
|
959
|
+
return await Promise.race([work, cancelled]);
|
|
960
|
+
} catch (error) {
|
|
961
|
+
throw failure ?? error;
|
|
652
962
|
} finally {
|
|
653
963
|
if (timer !== void 0) clearTimeout(timer);
|
|
654
|
-
|
|
964
|
+
requestSignal.removeEventListener("abort", onRequestAbort);
|
|
965
|
+
void work.catch(() => {
|
|
655
966
|
});
|
|
656
967
|
}
|
|
657
968
|
}
|
|
969
|
+
async function runInRecoveryScope(requestSignal, run) {
|
|
970
|
+
const controller = new AbortController();
|
|
971
|
+
const abort = () => controller.abort();
|
|
972
|
+
if (requestSignal.aborted) controller.abort();
|
|
973
|
+
else requestSignal.addEventListener("abort", abort, { once: true });
|
|
974
|
+
try {
|
|
975
|
+
return await run(controller.signal);
|
|
976
|
+
} finally {
|
|
977
|
+
requestSignal.removeEventListener("abort", abort);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
658
980
|
|
|
659
981
|
// src/core/engine.ts
|
|
982
|
+
function monotonicNow() {
|
|
983
|
+
return performance.now();
|
|
984
|
+
}
|
|
985
|
+
function normalizeDebugLevel(level) {
|
|
986
|
+
return level === true ? "detailed" : level;
|
|
987
|
+
}
|
|
988
|
+
function responseOutcome(response) {
|
|
989
|
+
const rewrite = response.headers.get("x-middleware-rewrite");
|
|
990
|
+
if (rewrite) {
|
|
991
|
+
return { type: "rewrite", destination: safeDestination(rewrite) ?? "/" };
|
|
992
|
+
}
|
|
993
|
+
const location = response.headers.get("location");
|
|
994
|
+
if (location && response.status >= 300 && response.status < 400) {
|
|
995
|
+
return {
|
|
996
|
+
type: "redirect",
|
|
997
|
+
status: response.status,
|
|
998
|
+
destination: safeDestination(location)
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
if (response instanceof import_server2.NextResponse && response.headers.get("x-middleware-next") === "1") {
|
|
1002
|
+
return { type: "next" };
|
|
1003
|
+
}
|
|
1004
|
+
return { type: "response", status: response.status };
|
|
1005
|
+
}
|
|
1006
|
+
function scopeNames(scopeList) {
|
|
1007
|
+
if (scopeList === void 0) return void 0;
|
|
1008
|
+
const scopes = Array.isArray(scopeList) ? scopeList : [scopeList];
|
|
1009
|
+
return scopes.map((scope) => {
|
|
1010
|
+
if (typeof scope === "string") return safeDiagnosticText(scope, 96);
|
|
1011
|
+
if (scope instanceof RegExp) return safeDiagnosticText(scope.toString(), 96);
|
|
1012
|
+
if (typeof scope !== "object" || scope === null) return "";
|
|
1013
|
+
const value = scope;
|
|
1014
|
+
const parts = [
|
|
1015
|
+
value.path === void 0 ? void 0 : Array.isArray(value.path) ? value.path.map(String).join("|") : String(value.path),
|
|
1016
|
+
value.host === void 0 ? void 0 : Array.isArray(value.host) ? value.host.map(String).join("|") : String(value.host)
|
|
1017
|
+
].filter(Boolean);
|
|
1018
|
+
return safeDiagnosticText(parts.join(" @ "), 96);
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
function handlerDetails(rule, chainTimeout, when, includeResult, excludeResult) {
|
|
1022
|
+
const include = scopeNames(rule.diagnosticRules?.include);
|
|
1023
|
+
const exclude = scopeNames(rule.diagnosticRules?.exclude);
|
|
1024
|
+
return {
|
|
1025
|
+
...include ? { include, includeResult } : {},
|
|
1026
|
+
...exclude ? { exclude, excludeResult } : {},
|
|
1027
|
+
...rule.when ? { when } : {},
|
|
1028
|
+
timeoutMs: rule.timeout ?? chainTimeout,
|
|
1029
|
+
timeoutSource: rule.timeout === void 0 ? "chain" : "handler"
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
function safeLogger(logger) {
|
|
1033
|
+
const wrap = (method) => (...args) => {
|
|
1034
|
+
try {
|
|
1035
|
+
const result = logger[method](...args);
|
|
1036
|
+
if (result && typeof result.then === "function") {
|
|
1037
|
+
void Promise.resolve(result).catch(() => {
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
} catch {
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
return {
|
|
1044
|
+
debug: wrap("debug"),
|
|
1045
|
+
info: wrap("info"),
|
|
1046
|
+
warn: wrap("warn"),
|
|
1047
|
+
error: wrap("error")
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
660
1050
|
function isNextResponse(value) {
|
|
661
1051
|
return value instanceof import_server2.NextResponse && value.headers.get("x-middleware-next") === "1";
|
|
662
1052
|
}
|
|
663
1053
|
function stripRoutingOverrides(res) {
|
|
664
1054
|
const plain = !(res instanceof import_server2.NextResponse);
|
|
665
|
-
|
|
1055
|
+
const keys = [...res.headers.keys()];
|
|
1056
|
+
const remove = keys.filter((key) => {
|
|
666
1057
|
const lower = key.toLowerCase();
|
|
667
|
-
|
|
668
|
-
res.headers.delete(key);
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
function isPathFilter(value) {
|
|
673
|
-
if (value === null || typeof value !== "object") return false;
|
|
674
|
-
if ("nextUrl" in value) return false;
|
|
675
|
-
return "include" in value || "exclude" in value || "name" in value;
|
|
676
|
-
}
|
|
677
|
-
function defineProxy(nameOrRun, maybeRun) {
|
|
678
|
-
const defaultName = typeof nameOrRun === "string" ? nameOrRun : void 0;
|
|
679
|
-
const run = typeof nameOrRun === "function" ? nameOrRun : maybeRun;
|
|
680
|
-
const proxy = ((reqOrFilter, eventOrCtx, maybeEvent) => {
|
|
681
|
-
if (isPathFilter(reqOrFilter)) {
|
|
682
|
-
return withPaths(run, {
|
|
683
|
-
...reqOrFilter,
|
|
684
|
-
name: reqOrFilter.name ?? defaultName
|
|
685
|
-
});
|
|
686
|
-
}
|
|
687
|
-
return run(reqOrFilter, eventOrCtx, maybeEvent);
|
|
1058
|
+
return lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite");
|
|
688
1059
|
});
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
1060
|
+
if (!remove.length) return res;
|
|
1061
|
+
try {
|
|
1062
|
+
for (const key of remove) res.headers.delete(key);
|
|
1063
|
+
return res;
|
|
1064
|
+
} catch {
|
|
1065
|
+
const headers = new Headers(res.headers);
|
|
1066
|
+
for (const key of remove) headers.delete(key);
|
|
1067
|
+
const init = { headers, status: res.status, statusText: res.statusText };
|
|
1068
|
+
return res instanceof import_server2.NextResponse ? new import_server2.NextResponse(res.body, init) : new Response(res.body, init);
|
|
1069
|
+
}
|
|
695
1070
|
}
|
|
696
|
-
function resolveConfig(overrides
|
|
697
|
-
const { logger, debug,
|
|
1071
|
+
function resolveConfig(overrides) {
|
|
1072
|
+
const { logger, debug, ...rest } = overrides;
|
|
698
1073
|
const config = {
|
|
699
|
-
createContext: createContext ?? fallbackCreateContext,
|
|
700
1074
|
cookieMergeStrategy: "last-write-wins",
|
|
701
1075
|
headerMergeStrategy: "last-write-wins",
|
|
702
1076
|
debug: false,
|
|
703
|
-
|
|
1077
|
+
timeout: 0,
|
|
704
1078
|
requestHeaderPolicy: {},
|
|
705
1079
|
strictOverrideCheck: false,
|
|
706
|
-
|
|
1080
|
+
tracePath: true,
|
|
707
1081
|
...rest,
|
|
708
1082
|
...debug !== void 0 ? { debug } : {},
|
|
709
|
-
logger: logger ?? createConsoleLogger(
|
|
1083
|
+
logger: safeLogger(logger ?? createConsoleLogger("info"))
|
|
710
1084
|
};
|
|
711
|
-
|
|
1085
|
+
assertValidTimeout(config.timeout);
|
|
712
1086
|
return config;
|
|
713
1087
|
}
|
|
714
|
-
function
|
|
715
|
-
const
|
|
716
|
-
const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
|
|
717
|
-
const fallbackCreateContext = createProxyContext;
|
|
718
|
-
const config = resolveConfig(options, fallbackCreateContext);
|
|
1088
|
+
function executeChain(options, entries) {
|
|
1089
|
+
const config = resolveConfig(options);
|
|
719
1090
|
const rules = entries.map(toRule);
|
|
720
1091
|
const {
|
|
721
1092
|
logger,
|
|
722
|
-
debug,
|
|
1093
|
+
debug: debugLevel,
|
|
723
1094
|
cookieMergeStrategy,
|
|
724
1095
|
headerMergeStrategy,
|
|
725
|
-
|
|
1096
|
+
timeout,
|
|
726
1097
|
requestHeaderPolicy,
|
|
727
|
-
strictOverrideCheck
|
|
728
|
-
hostFolderHeader
|
|
1098
|
+
strictOverrideCheck
|
|
729
1099
|
} = config;
|
|
1100
|
+
const debug = debugLevel !== false;
|
|
1101
|
+
const hasHandlerDebug = rules.some((rule) => rule.debug != null && rule.debug !== false);
|
|
1102
|
+
const hasDetailedHandlerDebug = rules.some(
|
|
1103
|
+
(rule) => rule.debug === true || rule.debug === "detailed" || rule.debug === "verbose"
|
|
1104
|
+
);
|
|
1105
|
+
const diagnosticsEnabled = debug || config.onTrace !== void 0 || hasHandlerDebug;
|
|
730
1106
|
assertOverrideMechanismSupported(strictOverrideCheck);
|
|
731
1107
|
for (let i = 0; i < rules.length; i++) {
|
|
732
1108
|
assertIncludeExcludeNoOverlap(rules[i].include, rules[i].exclude, ruleLabel(rules[i], i));
|
|
1109
|
+
assertValidTimeout(rules[i].timeout);
|
|
733
1110
|
}
|
|
734
1111
|
return async function proxy(req, event) {
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
const
|
|
743
|
-
|
|
744
|
-
|
|
1112
|
+
const startedAt = Date.now();
|
|
1113
|
+
const invocationStartedAt = monotonicNow();
|
|
1114
|
+
const requestId = `req_${globalThis.crypto.randomUUID()}`;
|
|
1115
|
+
const metadata = createRequestMetadata(req, requestId, startedAt, invocationStartedAt);
|
|
1116
|
+
const applicationState = createApplicationState();
|
|
1117
|
+
const diagnostics = diagnosticsEnabled ? [] : null;
|
|
1118
|
+
let nextHandlerIndex = 0;
|
|
1119
|
+
const finish = (response, forcedOutcome) => {
|
|
1120
|
+
if (!diagnostics) return response;
|
|
1121
|
+
for (let i = nextHandlerIndex; i < rules.length; i++) {
|
|
1122
|
+
diagnostics.push({
|
|
1123
|
+
name: safeDiagnosticText(ruleLabel(rules[i], i), 64),
|
|
1124
|
+
outcome: "not-reached"
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
const trace = {
|
|
1128
|
+
requestId,
|
|
1129
|
+
startedAt,
|
|
1130
|
+
method: safeDiagnosticText(req.method, 16),
|
|
1131
|
+
pathname: config.tracePath === false ? void 0 : safeDiagnosticText(metadata.originalPathname),
|
|
1132
|
+
durationMs: monotonicNow() - invocationStartedAt,
|
|
1133
|
+
outcome: forcedOutcome ?? responseOutcome(response),
|
|
1134
|
+
handlers: diagnostics
|
|
1135
|
+
};
|
|
1136
|
+
if (config.onTrace) {
|
|
1137
|
+
try {
|
|
1138
|
+
void Promise.resolve(config.onTrace(trace)).catch(() => {
|
|
1139
|
+
});
|
|
1140
|
+
} catch {
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
const globalLevel = normalizeDebugLevel(debugLevel);
|
|
1144
|
+
if (globalLevel !== false || hasHandlerDebug) {
|
|
1145
|
+
const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
|
|
1146
|
+
const visible = level === "compact" ? diagnostics : diagnostics.filter((_handler, index) => {
|
|
1147
|
+
const local = rules[index]?.debug;
|
|
1148
|
+
if (local === false) return false;
|
|
1149
|
+
if (local === "compact") return globalLevel === "compact";
|
|
1150
|
+
if (local != null) return true;
|
|
1151
|
+
return globalLevel !== false && !(globalLevel === "compact" && hasDetailedHandlerDebug);
|
|
1152
|
+
});
|
|
1153
|
+
try {
|
|
1154
|
+
config.logger.info(
|
|
1155
|
+
formatTrace(
|
|
1156
|
+
level === "compact" ? trace : { ...trace, handlers: visible },
|
|
1157
|
+
level,
|
|
1158
|
+
shouldUseColor(),
|
|
1159
|
+
supportsUnicode()
|
|
1160
|
+
)
|
|
1161
|
+
);
|
|
1162
|
+
} catch {
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
return response;
|
|
1166
|
+
};
|
|
1167
|
+
const contextFor = (signal) => createHandlerContext(metadata, applicationState, signal);
|
|
745
1168
|
let currentReq = req;
|
|
746
1169
|
let pendingRequestOverrides = null;
|
|
1170
|
+
let replaceRequestHeaders = false;
|
|
747
1171
|
let pendingRewriteUrl = null;
|
|
748
1172
|
const headerWrites = [];
|
|
749
1173
|
const cookieWrites = [];
|
|
@@ -756,119 +1180,352 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
756
1180
|
logger,
|
|
757
1181
|
debug
|
|
758
1182
|
);
|
|
1183
|
+
const requestCancelledResponse = () => finish(
|
|
1184
|
+
finalizeResponse(
|
|
1185
|
+
import_server2.NextResponse.next(),
|
|
1186
|
+
headerWrites,
|
|
1187
|
+
cookieWrites,
|
|
1188
|
+
headerMergeStrategy,
|
|
1189
|
+
cookieMergeStrategy,
|
|
1190
|
+
logger,
|
|
1191
|
+
debug
|
|
1192
|
+
),
|
|
1193
|
+
{ type: "request-cancelled" }
|
|
1194
|
+
);
|
|
759
1195
|
const materializeRequest = () => {
|
|
760
1196
|
if (!pendingRequestOverrides) return currentReq;
|
|
761
|
-
if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
|
|
1197
|
+
if (!replaceRequestHeaders && !headersDiffer(currentReq.headers, pendingRequestOverrides)) {
|
|
762
1198
|
pendingRequestOverrides = null;
|
|
763
1199
|
return currentReq;
|
|
764
1200
|
}
|
|
765
|
-
const
|
|
1201
|
+
const nextUrl = currentReq.nextUrl.clone();
|
|
1202
|
+
const merged = new Headers();
|
|
1203
|
+
if (replaceRequestHeaders) {
|
|
1204
|
+
currentReq.headers.forEach((value, key) => {
|
|
1205
|
+
if (!isRequestHeaderAllowed(key, requestHeaderPolicy)) merged.set(key, value);
|
|
1206
|
+
});
|
|
1207
|
+
} else {
|
|
1208
|
+
currentReq.headers.forEach((value, key) => {
|
|
1209
|
+
merged.set(key, value);
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
766
1212
|
pendingRequestOverrides.forEach((v, k) => {
|
|
767
1213
|
merged.set(k, v);
|
|
768
1214
|
});
|
|
769
1215
|
pendingRequestOverrides = null;
|
|
1216
|
+
replaceRequestHeaders = false;
|
|
770
1217
|
currentReq = new import_server2.NextRequest(currentReq, { headers: merged });
|
|
1218
|
+
currentReq.nextUrl.pathname = nextUrl.pathname;
|
|
1219
|
+
currentReq.nextUrl.search = nextUrl.search;
|
|
771
1220
|
return currentReq;
|
|
772
1221
|
};
|
|
773
|
-
const
|
|
774
|
-
|
|
775
|
-
|
|
1222
|
+
const queueRequestOverrides = (overrides, mode) => {
|
|
1223
|
+
if (mode === "replace") {
|
|
1224
|
+
pendingRequestOverrides = new Headers();
|
|
1225
|
+
replaceRequestHeaders = true;
|
|
1226
|
+
} else if (!pendingRequestOverrides) {
|
|
1227
|
+
pendingRequestOverrides = new Headers();
|
|
1228
|
+
}
|
|
776
1229
|
const target = pendingRequestOverrides;
|
|
777
1230
|
overrides.forEach((v, k) => {
|
|
778
1231
|
target.set(k, v);
|
|
779
|
-
appliedRequestOverrides.set(k, v);
|
|
780
1232
|
});
|
|
781
1233
|
};
|
|
782
|
-
const recoverRuleError = async (err, i, label, req2,
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
1234
|
+
const recoverRuleError = async (err, i, label, req2, durationMs, phase) => {
|
|
1235
|
+
const timeoutError = err instanceof RuleTimeoutError;
|
|
1236
|
+
const requestCancelled = err instanceof RequestCancellationError;
|
|
1237
|
+
const errorHandler = rules[i].onError ?? config.onError;
|
|
1238
|
+
const errorPolicy = rules[i].onError ? "handler" : "chain";
|
|
1239
|
+
const diagnosticPhase = phase === "before-handler" ? "handler" : phase;
|
|
1240
|
+
const details = handlerDetails(rules[i], timeout, "matched", "matched", "not-matched");
|
|
1241
|
+
const stopFailure = (policy) => {
|
|
1242
|
+
diagnostics?.push({
|
|
1243
|
+
name: safeDiagnosticText(label, 64),
|
|
1244
|
+
...requestCancelled ? {
|
|
1245
|
+
outcome: "request-cancelled",
|
|
1246
|
+
durationMs,
|
|
1247
|
+
phase: phase === "result" ? "handler" : phase,
|
|
1248
|
+
policy
|
|
1249
|
+
} : {
|
|
1250
|
+
outcome: timeoutError ? "timeout" : "failed",
|
|
1251
|
+
durationMs,
|
|
1252
|
+
phase: diagnosticPhase,
|
|
1253
|
+
policy,
|
|
1254
|
+
...timeoutError ? { timeoutMs: err.timeoutMs } : {}
|
|
1255
|
+
},
|
|
1256
|
+
details
|
|
1257
|
+
});
|
|
1258
|
+
nextHandlerIndex = i + 1;
|
|
1259
|
+
if (requestCancelled) {
|
|
1260
|
+
return {
|
|
1261
|
+
response: finish(
|
|
1262
|
+
finalizeResponse(
|
|
1263
|
+
import_server2.NextResponse.next(),
|
|
1264
|
+
headerWrites,
|
|
1265
|
+
cookieWrites,
|
|
1266
|
+
headerMergeStrategy,
|
|
1267
|
+
cookieMergeStrategy,
|
|
1268
|
+
logger,
|
|
1269
|
+
debug
|
|
1270
|
+
),
|
|
1271
|
+
{ type: "request-cancelled" }
|
|
1272
|
+
)
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
if (timeoutError) {
|
|
1276
|
+
return {
|
|
1277
|
+
response: finish(failClosed(), {
|
|
1278
|
+
type: "timeout",
|
|
1279
|
+
status: 500,
|
|
1280
|
+
timeoutMs: err.timeoutMs
|
|
1281
|
+
})
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
return {
|
|
1285
|
+
response: finish(failClosed(), {
|
|
1286
|
+
type: "error",
|
|
1287
|
+
status: 500,
|
|
1288
|
+
classification: "handler"
|
|
1289
|
+
})
|
|
1290
|
+
};
|
|
1291
|
+
};
|
|
1292
|
+
if (!errorHandler) {
|
|
1293
|
+
if (!diagnosticsEnabled) logger.error("handler failed");
|
|
1294
|
+
return stopFailure("none");
|
|
786
1295
|
}
|
|
787
1296
|
try {
|
|
788
|
-
const recovered = await
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
1297
|
+
const recovered = await runInRecoveryScope(
|
|
1298
|
+
req2.signal,
|
|
1299
|
+
(signal) => errorHandler(err, i, req2, contextFor(signal))
|
|
1300
|
+
);
|
|
1301
|
+
if (timeoutError || requestCancelled) {
|
|
1302
|
+
if (recovered instanceof Response && !isNextResponse(recovered)) {
|
|
1303
|
+
const response2 = stripRoutingOverrides(recovered);
|
|
1304
|
+
headerWrites.push({
|
|
1305
|
+
ruleIndex: i,
|
|
1306
|
+
ruleName: label,
|
|
1307
|
+
items: responseHeaderItems(response2.headers)
|
|
1308
|
+
});
|
|
1309
|
+
cookieWrites.push({
|
|
1310
|
+
ruleIndex: i,
|
|
1311
|
+
ruleName: label,
|
|
1312
|
+
items: cookieItemsFromHeaders(response2.headers)
|
|
1313
|
+
});
|
|
1314
|
+
diagnostics?.push({
|
|
1315
|
+
name: safeDiagnosticText(label, 64),
|
|
1316
|
+
...requestCancelled ? {
|
|
1317
|
+
outcome: "request-cancelled",
|
|
1318
|
+
durationMs,
|
|
1319
|
+
phase: phase === "result" ? "handler" : phase,
|
|
1320
|
+
policy: errorPolicy,
|
|
1321
|
+
recovery: "response"
|
|
1322
|
+
} : {
|
|
1323
|
+
outcome: "timeout",
|
|
1324
|
+
durationMs,
|
|
1325
|
+
phase: diagnosticPhase,
|
|
1326
|
+
policy: errorPolicy,
|
|
1327
|
+
recovery: "response",
|
|
1328
|
+
timeoutMs: err.timeoutMs
|
|
1329
|
+
},
|
|
1330
|
+
details
|
|
1331
|
+
});
|
|
1332
|
+
nextHandlerIndex = i + 1;
|
|
1333
|
+
return {
|
|
1334
|
+
response: finish(
|
|
1335
|
+
finalizeResponse(
|
|
1336
|
+
response2,
|
|
1337
|
+
headerWrites,
|
|
1338
|
+
cookieWrites,
|
|
1339
|
+
headerMergeStrategy,
|
|
1340
|
+
cookieMergeStrategy,
|
|
1341
|
+
logger,
|
|
1342
|
+
debug
|
|
1343
|
+
),
|
|
1344
|
+
requestCancelled ? { type: "request-cancelled" } : {
|
|
1345
|
+
type: "timeout",
|
|
1346
|
+
status: recovered.status,
|
|
1347
|
+
timeoutMs: err.timeoutMs
|
|
1348
|
+
}
|
|
1349
|
+
)
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
return stopFailure(errorPolicy);
|
|
1353
|
+
}
|
|
1354
|
+
if (recovered == null) {
|
|
1355
|
+
return stopFailure(errorPolicy);
|
|
1356
|
+
}
|
|
1357
|
+
if (isNextResult(recovered) || isNextResponse(recovered)) {
|
|
1358
|
+
diagnostics?.push({
|
|
1359
|
+
name: safeDiagnosticText(label, 64),
|
|
1360
|
+
outcome: "recovered",
|
|
1361
|
+
durationMs,
|
|
1362
|
+
recovery: "continue",
|
|
1363
|
+
policy: errorPolicy,
|
|
1364
|
+
details
|
|
1365
|
+
});
|
|
1366
|
+
nextHandlerIndex = i + 1;
|
|
1367
|
+
return { raw: recovered };
|
|
1368
|
+
}
|
|
1369
|
+
if (!(recovered instanceof Response)) {
|
|
1370
|
+
diagnostics?.push({
|
|
1371
|
+
name: safeDiagnosticText(label, 64),
|
|
1372
|
+
outcome: "failed",
|
|
1373
|
+
durationMs,
|
|
1374
|
+
phase: diagnosticPhase,
|
|
1375
|
+
policy: errorPolicy,
|
|
1376
|
+
details
|
|
1377
|
+
});
|
|
1378
|
+
nextHandlerIndex = i + 1;
|
|
1379
|
+
return {
|
|
1380
|
+
response: finish(failClosed(), {
|
|
1381
|
+
type: "error",
|
|
1382
|
+
status: 500,
|
|
1383
|
+
classification: "handler"
|
|
1384
|
+
})
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
const response = stripRoutingOverrides(recovered);
|
|
793
1388
|
headerWrites.push({
|
|
794
1389
|
ruleIndex: i,
|
|
795
1390
|
ruleName: label,
|
|
796
|
-
items: responseHeaderItems(
|
|
1391
|
+
items: responseHeaderItems(response.headers)
|
|
797
1392
|
});
|
|
798
1393
|
cookieWrites.push({
|
|
799
1394
|
ruleIndex: i,
|
|
800
1395
|
ruleName: label,
|
|
801
|
-
items: cookieItemsFromHeaders(
|
|
1396
|
+
items: cookieItemsFromHeaders(response.headers)
|
|
802
1397
|
});
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
duration: performance.now() - startedAt,
|
|
813
|
-
status: recovered.status
|
|
814
|
-
}
|
|
815
|
-
})
|
|
816
|
-
);
|
|
817
|
-
}
|
|
1398
|
+
diagnostics?.push({
|
|
1399
|
+
name: safeDiagnosticText(label, 64),
|
|
1400
|
+
outcome: "recovered",
|
|
1401
|
+
durationMs,
|
|
1402
|
+
recovery: responseOutcome(response).type === "redirect" ? "redirect" : responseOutcome(response).type === "rewrite" ? "rewrite" : "response",
|
|
1403
|
+
policy: errorPolicy,
|
|
1404
|
+
details
|
|
1405
|
+
});
|
|
1406
|
+
nextHandlerIndex = i + 1;
|
|
818
1407
|
return {
|
|
819
|
-
response:
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
1408
|
+
response: finish(
|
|
1409
|
+
finalizeResponse(
|
|
1410
|
+
response,
|
|
1411
|
+
headerWrites,
|
|
1412
|
+
cookieWrites,
|
|
1413
|
+
headerMergeStrategy,
|
|
1414
|
+
cookieMergeStrategy,
|
|
1415
|
+
logger,
|
|
1416
|
+
debug
|
|
1417
|
+
)
|
|
827
1418
|
)
|
|
828
1419
|
};
|
|
829
|
-
} catch
|
|
830
|
-
logger.error(
|
|
831
|
-
return
|
|
1420
|
+
} catch {
|
|
1421
|
+
if (!diagnosticsEnabled) logger.error("chain error handler failed");
|
|
1422
|
+
return stopFailure(errorPolicy);
|
|
832
1423
|
}
|
|
833
1424
|
};
|
|
834
1425
|
try {
|
|
835
1426
|
for (let i = 0; i < rules.length; i++) {
|
|
836
1427
|
const rule = rules[i];
|
|
837
1428
|
const label = ruleLabel(rule, i);
|
|
1429
|
+
nextHandlerIndex = i;
|
|
1430
|
+
if (req.signal.aborted) {
|
|
1431
|
+
const cancelled = await recoverRuleError(
|
|
1432
|
+
new RequestCancellationError(),
|
|
1433
|
+
i,
|
|
1434
|
+
label,
|
|
1435
|
+
materializeRequest(),
|
|
1436
|
+
0,
|
|
1437
|
+
"before-handler"
|
|
1438
|
+
);
|
|
1439
|
+
if ("response" in cancelled) return cancelled.response;
|
|
1440
|
+
return requestCancelledResponse();
|
|
1441
|
+
}
|
|
838
1442
|
const activeReq = materializeRequest();
|
|
839
1443
|
const reqHost = normalizeHost(
|
|
840
1444
|
activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
|
|
841
1445
|
);
|
|
842
1446
|
const matchPath = canonicalPathname(activeReq.nextUrl.pathname);
|
|
843
1447
|
if (matchPath === null) {
|
|
844
|
-
return
|
|
845
|
-
|
|
846
|
-
|
|
1448
|
+
return finish(
|
|
1449
|
+
new import_server2.NextResponse("Bad Request", {
|
|
1450
|
+
status: 400,
|
|
1451
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
1452
|
+
})
|
|
1453
|
+
);
|
|
1454
|
+
}
|
|
1455
|
+
const skipReason = ruleMatchReason(matchPath, reqHost, rule);
|
|
1456
|
+
if (skipReason) {
|
|
1457
|
+
diagnostics?.push({
|
|
1458
|
+
name: safeDiagnosticText(label, 64),
|
|
1459
|
+
outcome: "skipped",
|
|
1460
|
+
reason: skipReason,
|
|
1461
|
+
details: handlerDetails(
|
|
1462
|
+
rule,
|
|
1463
|
+
timeout,
|
|
1464
|
+
"not-evaluated",
|
|
1465
|
+
skipReason === "include-mismatch" ? "mismatch" : void 0,
|
|
1466
|
+
skipReason === "exclude-match" ? "matched" : skipReason === "include-mismatch" && rule.exclude ? "not-matched" : void 0
|
|
1467
|
+
)
|
|
847
1468
|
});
|
|
1469
|
+
nextHandlerIndex = i + 1;
|
|
1470
|
+
continue;
|
|
848
1471
|
}
|
|
849
|
-
|
|
850
|
-
const
|
|
851
|
-
let
|
|
1472
|
+
const executionStartedAt = monotonicNow();
|
|
1473
|
+
const effectiveTimeout = rule.timeout ?? timeout;
|
|
1474
|
+
let phase = rule.when ? "when" : "handler";
|
|
1475
|
+
let result;
|
|
852
1476
|
try {
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
label
|
|
1477
|
+
result = await runInExecutionScope(
|
|
1478
|
+
req.signal,
|
|
1479
|
+
effectiveTimeout,
|
|
1480
|
+
label,
|
|
1481
|
+
async (signal, assertActive) => {
|
|
1482
|
+
const context = contextFor(signal);
|
|
1483
|
+
if (rule.when) {
|
|
1484
|
+
const matches = await rule.when(activeReq, event, context);
|
|
1485
|
+
assertActive();
|
|
1486
|
+
if (!matches) return { kind: "skipped" };
|
|
1487
|
+
}
|
|
1488
|
+
phase = "handler";
|
|
1489
|
+
assertActive();
|
|
1490
|
+
return {
|
|
1491
|
+
kind: "result",
|
|
1492
|
+
raw: await rule.run(activeReq, context, event)
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
857
1495
|
);
|
|
1496
|
+
if (result.kind === "skipped") {
|
|
1497
|
+
diagnostics?.push({
|
|
1498
|
+
name: safeDiagnosticText(label, 64),
|
|
1499
|
+
outcome: "skipped",
|
|
1500
|
+
reason: "when-false",
|
|
1501
|
+
details: handlerDetails(rule, timeout, "false", "matched", "not-matched")
|
|
1502
|
+
});
|
|
1503
|
+
nextHandlerIndex = i + 1;
|
|
1504
|
+
continue;
|
|
1505
|
+
}
|
|
858
1506
|
} catch (err) {
|
|
859
|
-
const recovered = await recoverRuleError(
|
|
1507
|
+
const recovered = await recoverRuleError(
|
|
1508
|
+
err,
|
|
1509
|
+
i,
|
|
1510
|
+
label,
|
|
1511
|
+
activeReq,
|
|
1512
|
+
monotonicNow() - executionStartedAt,
|
|
1513
|
+
phase
|
|
1514
|
+
);
|
|
860
1515
|
if ("response" in recovered) return recovered.response;
|
|
861
|
-
|
|
1516
|
+
result = { kind: "result", raw: recovered.raw };
|
|
862
1517
|
}
|
|
1518
|
+
let raw = result.raw;
|
|
1519
|
+
let duration2 = monotonicNow() - executionStartedAt;
|
|
863
1520
|
let outcome;
|
|
864
1521
|
try {
|
|
865
1522
|
outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
|
|
866
1523
|
} catch (err) {
|
|
867
|
-
const recovered = await recoverRuleError(err, i, label, activeReq,
|
|
1524
|
+
const recovered = await recoverRuleError(err, i, label, activeReq, duration2, "result");
|
|
868
1525
|
if ("response" in recovered) return recovered.response;
|
|
869
|
-
|
|
1526
|
+
raw = recovered.raw;
|
|
1527
|
+
outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
|
|
870
1528
|
}
|
|
871
|
-
const duration = debug ? performance.now() - startedAt : 0;
|
|
872
1529
|
if (outcome.kind === "continue") {
|
|
873
1530
|
if (outcome.rewriteUrl) {
|
|
874
1531
|
pendingRewriteUrl = outcome.rewriteUrl;
|
|
@@ -883,86 +1540,88 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
883
1540
|
currentReq.nextUrl.pathname = outcome.rewriteUrl;
|
|
884
1541
|
}
|
|
885
1542
|
}
|
|
886
|
-
if (outcome.request) queueRequestOverrides(outcome.request);
|
|
1543
|
+
if (outcome.request) queueRequestOverrides(outcome.request, outcome.requestMode);
|
|
887
1544
|
if (outcome.responseHeaders.size || outcome.cookies.size) {
|
|
888
1545
|
headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
|
|
889
1546
|
cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
|
|
890
1547
|
}
|
|
891
|
-
if (
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
}
|
|
1548
|
+
if (diagnostics?.at(-1)?.outcome !== "recovered") {
|
|
1549
|
+
diagnostics?.push(
|
|
1550
|
+
outcome.rewriteUrl ? {
|
|
1551
|
+
name: safeDiagnosticText(label, 64),
|
|
1552
|
+
outcome: "rewrite",
|
|
1553
|
+
durationMs: duration2,
|
|
1554
|
+
destination: safeDestination(outcome.rewriteUrl) ?? "/",
|
|
1555
|
+
final: false,
|
|
1556
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1557
|
+
} : {
|
|
1558
|
+
name: safeDiagnosticText(label, 64),
|
|
1559
|
+
outcome: "continue",
|
|
1560
|
+
source: isNextResult(raw) ? "next()" : raw instanceof import_server2.NextResponse && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
|
|
1561
|
+
durationMs: duration2,
|
|
1562
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1563
|
+
}
|
|
901
1564
|
);
|
|
902
1565
|
}
|
|
1566
|
+
nextHandlerIndex = i + 1;
|
|
903
1567
|
continue;
|
|
904
1568
|
}
|
|
905
|
-
stripRoutingOverrides(outcome.response);
|
|
1569
|
+
const response = stripRoutingOverrides(outcome.response);
|
|
906
1570
|
headerWrites.push({
|
|
907
1571
|
ruleIndex: i,
|
|
908
1572
|
ruleName: label,
|
|
909
|
-
items: responseHeaderItems(
|
|
1573
|
+
items: responseHeaderItems(response.headers)
|
|
910
1574
|
});
|
|
911
1575
|
cookieWrites.push({
|
|
912
1576
|
ruleIndex: i,
|
|
913
1577
|
ruleName: label,
|
|
914
|
-
items: cookieItemsFromHeaders(
|
|
1578
|
+
items: cookieItemsFromHeaders(response.headers)
|
|
915
1579
|
});
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
1580
|
+
const terminalOutcome = responseOutcome(response);
|
|
1581
|
+
diagnostics?.push(
|
|
1582
|
+
terminalOutcome.type === "redirect" ? {
|
|
1583
|
+
name: safeDiagnosticText(label, 64),
|
|
1584
|
+
outcome: "redirect",
|
|
1585
|
+
durationMs: duration2,
|
|
1586
|
+
status: terminalOutcome.status,
|
|
1587
|
+
destination: terminalOutcome.destination,
|
|
1588
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1589
|
+
} : terminalOutcome.type === "rewrite" ? {
|
|
1590
|
+
name: safeDiagnosticText(label, 64),
|
|
1591
|
+
outcome: "rewrite",
|
|
1592
|
+
durationMs: duration2,
|
|
1593
|
+
destination: terminalOutcome.destination,
|
|
1594
|
+
final: true,
|
|
1595
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1596
|
+
} : {
|
|
1597
|
+
name: safeDiagnosticText(label, 64),
|
|
1598
|
+
outcome: "response",
|
|
1599
|
+
durationMs: duration2,
|
|
1600
|
+
status: response.status,
|
|
1601
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1602
|
+
}
|
|
1603
|
+
);
|
|
1604
|
+
nextHandlerIndex = i + 1;
|
|
1605
|
+
const finalTerminalOutcome = responseOutcome(response);
|
|
1606
|
+
const terminalTrace = diagnostics?.at(-1);
|
|
1607
|
+
if (finalTerminalOutcome.type === "rewrite" && terminalTrace?.outcome === "rewrite") {
|
|
1608
|
+
terminalTrace.destination = finalTerminalOutcome.destination;
|
|
939
1609
|
}
|
|
940
|
-
return
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1610
|
+
return finish(
|
|
1611
|
+
finalizeResponse(
|
|
1612
|
+
response,
|
|
1613
|
+
headerWrites,
|
|
1614
|
+
cookieWrites,
|
|
1615
|
+
headerMergeStrategy,
|
|
1616
|
+
cookieMergeStrategy,
|
|
1617
|
+
logger,
|
|
1618
|
+
debug
|
|
1619
|
+
),
|
|
1620
|
+
finalTerminalOutcome
|
|
948
1621
|
);
|
|
949
1622
|
}
|
|
950
1623
|
const finalReq = materializeRequest();
|
|
951
|
-
const
|
|
952
|
-
let finalRewriteUrl = pendingRewriteUrl;
|
|
953
|
-
if (internalHostFolder) {
|
|
954
|
-
const cleanFolder = physicalFolderPrefix(internalHostFolder);
|
|
955
|
-
if (finalRewriteUrl) {
|
|
956
|
-
finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
|
|
957
|
-
} else {
|
|
958
|
-
const currentPath = finalReq.nextUrl.pathname;
|
|
959
|
-
if (!isInsideFolder(currentPath, cleanFolder)) {
|
|
960
|
-
const targetUrl = finalReq.nextUrl.clone();
|
|
961
|
-
targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
|
|
962
|
-
finalRewriteUrl = targetUrl.toString();
|
|
963
|
-
}
|
|
964
|
-
}
|
|
965
|
-
}
|
|
1624
|
+
const finalRewriteUrl = pendingRewriteUrl;
|
|
966
1625
|
const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
|
|
967
1626
|
let final;
|
|
968
1627
|
if (finalRewriteUrl) {
|
|
@@ -971,7 +1630,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
971
1630
|
} else {
|
|
972
1631
|
final = import_server2.NextResponse.next(requestInit);
|
|
973
1632
|
}
|
|
974
|
-
|
|
1633
|
+
const finalResponse = finalizeResponse(
|
|
975
1634
|
final,
|
|
976
1635
|
headerWrites,
|
|
977
1636
|
cookieWrites,
|
|
@@ -980,34 +1639,51 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
980
1639
|
logger,
|
|
981
1640
|
debug
|
|
982
1641
|
);
|
|
1642
|
+
if (finalRewriteUrl) {
|
|
1643
|
+
const destination = safeDestination(finalRewriteUrl) ?? "/";
|
|
1644
|
+
const rewrite = diagnostics?.filter((handler) => handler.outcome === "rewrite").at(-1);
|
|
1645
|
+
if (rewrite?.outcome === "rewrite") {
|
|
1646
|
+
rewrite.destination = destination;
|
|
1647
|
+
rewrite.final = true;
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
return finish(finalResponse);
|
|
983
1651
|
} catch (err) {
|
|
984
|
-
logger.error(
|
|
1652
|
+
if (!diagnosticsEnabled) logger.error("proxy chain execution failed");
|
|
985
1653
|
if (config.onError) {
|
|
986
1654
|
try {
|
|
987
|
-
const recovered = await
|
|
1655
|
+
const recovered = await runInRecoveryScope(
|
|
1656
|
+
req.signal,
|
|
1657
|
+
(signal) => config.onError(err, -1, materializeRequest(), contextFor(signal))
|
|
1658
|
+
);
|
|
988
1659
|
if (recovered instanceof Response && !isNextResponse(recovered)) {
|
|
989
|
-
stripRoutingOverrides(recovered);
|
|
990
|
-
return
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
1660
|
+
const response = stripRoutingOverrides(recovered);
|
|
1661
|
+
return finish(
|
|
1662
|
+
finalizeResponse(
|
|
1663
|
+
response,
|
|
1664
|
+
headerWrites,
|
|
1665
|
+
cookieWrites,
|
|
1666
|
+
headerMergeStrategy,
|
|
1667
|
+
cookieMergeStrategy,
|
|
1668
|
+
logger,
|
|
1669
|
+
debug
|
|
1670
|
+
)
|
|
998
1671
|
);
|
|
999
1672
|
}
|
|
1000
1673
|
} catch {
|
|
1001
1674
|
}
|
|
1002
1675
|
}
|
|
1003
|
-
return
|
|
1676
|
+
return finish(
|
|
1677
|
+
failClosed(),
|
|
1678
|
+
err instanceof RuleTimeoutError ? { type: "timeout", status: 500, timeoutMs: err.timeoutMs } : { type: "error", status: 500, classification: "engine" }
|
|
1679
|
+
);
|
|
1004
1680
|
}
|
|
1005
1681
|
};
|
|
1006
1682
|
}
|
|
1007
1683
|
|
|
1008
1684
|
// src/core/chain.ts
|
|
1009
|
-
function
|
|
1010
|
-
return typeof value === "
|
|
1685
|
+
function isDefinedHandler(value) {
|
|
1686
|
+
return typeof value === "object" && value !== null && value[DEFINED_HANDLER] === true;
|
|
1011
1687
|
}
|
|
1012
1688
|
function isScopeObject2(value) {
|
|
1013
1689
|
return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
|
|
@@ -1025,26 +1701,48 @@ function toEntry(entry) {
|
|
|
1025
1701
|
if (Array.isArray(entry)) {
|
|
1026
1702
|
const [target, scope] = entry;
|
|
1027
1703
|
const filter = toFilter(scope);
|
|
1028
|
-
if (
|
|
1704
|
+
if (isDefinedHandler(target)) return withPaths(target, filter);
|
|
1029
1705
|
return withPaths(fromNative(target), filter);
|
|
1030
1706
|
}
|
|
1031
|
-
if (
|
|
1707
|
+
if (isDefinedHandler(entry)) return entry;
|
|
1032
1708
|
if (typeof entry === "function") return fromNative(entry);
|
|
1033
|
-
|
|
1709
|
+
throw new TypeError(
|
|
1710
|
+
"[proxy-chain] chain entries must be native handlers or defineHandler() results"
|
|
1711
|
+
);
|
|
1034
1712
|
}
|
|
1035
1713
|
function chain(entries, options) {
|
|
1036
1714
|
const normalized = entries.map((entry) => toEntry(entry));
|
|
1037
|
-
return
|
|
1715
|
+
return executeChain(options ?? {}, normalized);
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
// src/core/handler.ts
|
|
1719
|
+
function defineHandler(options) {
|
|
1720
|
+
assertValidTimeout(options.timeout);
|
|
1721
|
+
const include = compileScopes(options.rules?.include);
|
|
1722
|
+
const exclude = compileScopes(options.rules?.exclude);
|
|
1723
|
+
const rule = {
|
|
1724
|
+
run: (request, context, event) => options.handler(request, event, context),
|
|
1725
|
+
name: options.name,
|
|
1726
|
+
include,
|
|
1727
|
+
exclude,
|
|
1728
|
+
debug: options.debug,
|
|
1729
|
+
timeout: options.timeout,
|
|
1730
|
+
when: options.rules?.when,
|
|
1731
|
+
onError: options.onError,
|
|
1732
|
+
diagnosticRules: {
|
|
1733
|
+
include: options.rules?.include,
|
|
1734
|
+
exclude: options.rules?.exclude
|
|
1735
|
+
}
|
|
1736
|
+
};
|
|
1737
|
+
return { ...rule, [DEFINED_HANDLER]: true };
|
|
1038
1738
|
}
|
|
1039
1739
|
// Annotate the CommonJS export names for ESM import in node:
|
|
1040
1740
|
0 && (module.exports = {
|
|
1041
1741
|
RuleTimeoutError,
|
|
1042
1742
|
chain,
|
|
1043
|
-
|
|
1044
|
-
defineProxy,
|
|
1743
|
+
defineHandler,
|
|
1045
1744
|
host,
|
|
1046
1745
|
isNextResult,
|
|
1047
1746
|
next,
|
|
1048
|
-
path
|
|
1049
|
-
proxyChain
|
|
1747
|
+
path
|
|
1050
1748
|
});
|