@klnap/next-proxy-chain 1.2.0 → 3.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 +18 -0
- package/README.md +277 -219
- package/dist/index.cjs +513 -440
- package/dist/index.d.cts +96 -189
- package/dist/index.d.ts +96 -189
- package/dist/index.js +512 -431
- package/docs/api.md +190 -0
- package/docs/concepts.md +88 -0
- package/docs/guides.md +210 -0
- package/docs/security.md +104 -0
- package/llms.txt +17 -0
- package/package.json +19 -18
package/dist/index.js
CHANGED
|
@@ -1,80 +1,95 @@
|
|
|
1
|
-
// src/core/constants.ts
|
|
2
|
-
var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
|
|
3
|
-
var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
|
|
4
|
-
"host",
|
|
5
|
-
"connection",
|
|
6
|
-
"keep-alive",
|
|
7
|
-
"proxy-authenticate",
|
|
8
|
-
"proxy-authorization",
|
|
9
|
-
"te",
|
|
10
|
-
"trailer",
|
|
11
|
-
"transfer-encoding",
|
|
12
|
-
"upgrade",
|
|
13
|
-
"content-length",
|
|
14
|
-
"cookie",
|
|
15
|
-
"authorization",
|
|
16
|
-
"x-forwarded-host",
|
|
17
|
-
"x-forwarded-for",
|
|
18
|
-
"x-forwarded-proto",
|
|
19
|
-
"x-real-ip",
|
|
20
|
-
"x-middleware-next",
|
|
21
|
-
"x-middleware-override-headers"
|
|
22
|
-
]);
|
|
23
|
-
var CONTEXT_RULE = /* @__PURE__ */ Symbol.for("proxy-chain.context-rule");
|
|
24
|
-
|
|
25
|
-
// src/core/actions.ts
|
|
26
|
-
function next(options = {}) {
|
|
27
|
-
return { [NEXT]: true, ...options };
|
|
28
|
-
}
|
|
29
|
-
function isNextResult(value) {
|
|
30
|
-
return typeof value === "object" && value !== null && NEXT in value;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
1
|
// src/core/engine.ts
|
|
34
|
-
import { NextRequest, NextResponse as NextResponse2 } from "next/server";
|
|
2
|
+
import { NextRequest, NextResponse as NextResponse2 } from "next/server.js";
|
|
35
3
|
|
|
36
4
|
// src/core/context.ts
|
|
37
|
-
|
|
38
|
-
|
|
5
|
+
var RESERVED_CONTEXT_KEYS = /* @__PURE__ */ new Set([
|
|
6
|
+
"requestId",
|
|
7
|
+
"startedAt",
|
|
8
|
+
"elapsedMs",
|
|
9
|
+
"originalUrl",
|
|
10
|
+
"originalPathname",
|
|
11
|
+
"originalHostname",
|
|
12
|
+
"signal"
|
|
13
|
+
]);
|
|
14
|
+
function createRequestMetadata(request, requestId, startedAt, invocationStartedAt) {
|
|
15
|
+
const metadata = /* @__PURE__ */ Object.create(null);
|
|
16
|
+
Object.defineProperties(metadata, {
|
|
17
|
+
requestId: { value: requestId, enumerable: true },
|
|
18
|
+
startedAt: { value: startedAt, enumerable: true },
|
|
19
|
+
elapsedMs: {
|
|
20
|
+
get: () => performance.now() - invocationStartedAt,
|
|
21
|
+
enumerable: true
|
|
22
|
+
},
|
|
23
|
+
originalUrl: { value: request.url, enumerable: true },
|
|
24
|
+
originalPathname: { value: request.nextUrl.pathname, enumerable: true },
|
|
25
|
+
originalHostname: { value: request.nextUrl.hostname, enumerable: true }
|
|
26
|
+
});
|
|
27
|
+
return metadata;
|
|
28
|
+
}
|
|
29
|
+
function createApplicationState() {
|
|
30
|
+
return /* @__PURE__ */ Object.create(null);
|
|
31
|
+
}
|
|
32
|
+
function createHandlerContext(metadata, applicationState, signal) {
|
|
33
|
+
const target = /* @__PURE__ */ Object.create(null);
|
|
34
|
+
Object.defineProperties(target, {
|
|
35
|
+
requestId: { value: metadata.requestId, enumerable: true },
|
|
36
|
+
startedAt: { value: metadata.startedAt, enumerable: true },
|
|
37
|
+
elapsedMs: { get: () => metadata.elapsedMs, enumerable: true },
|
|
38
|
+
originalUrl: { value: metadata.originalUrl, enumerable: true },
|
|
39
|
+
originalPathname: { value: metadata.originalPathname, enumerable: true },
|
|
40
|
+
originalHostname: { value: metadata.originalHostname, enumerable: true },
|
|
41
|
+
signal: { value: signal, enumerable: true }
|
|
42
|
+
});
|
|
43
|
+
return new Proxy(target, {
|
|
44
|
+
get(view, property) {
|
|
45
|
+
return Reflect.has(view, property) ? Reflect.get(view, property, view) : Reflect.get(applicationState, property, applicationState);
|
|
46
|
+
},
|
|
47
|
+
set(_view, property, value) {
|
|
48
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
49
|
+
return Reflect.set(applicationState, property, value, applicationState);
|
|
50
|
+
},
|
|
51
|
+
deleteProperty(_view, property) {
|
|
52
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
53
|
+
return Reflect.deleteProperty(applicationState, property);
|
|
54
|
+
},
|
|
55
|
+
defineProperty(_view, property, descriptor) {
|
|
56
|
+
if (RESERVED_CONTEXT_KEYS.has(property)) return false;
|
|
57
|
+
return Reflect.defineProperty(applicationState, property, {
|
|
58
|
+
...descriptor,
|
|
59
|
+
configurable: true
|
|
60
|
+
});
|
|
61
|
+
},
|
|
62
|
+
getPrototypeOf() {
|
|
63
|
+
return null;
|
|
64
|
+
},
|
|
65
|
+
setPrototypeOf() {
|
|
66
|
+
return false;
|
|
67
|
+
},
|
|
68
|
+
has(view, property) {
|
|
69
|
+
return Reflect.has(view, property) || Reflect.has(applicationState, property);
|
|
70
|
+
},
|
|
71
|
+
ownKeys(view) {
|
|
72
|
+
return [.../* @__PURE__ */ new Set([...Reflect.ownKeys(view), ...Reflect.ownKeys(applicationState)])];
|
|
73
|
+
},
|
|
74
|
+
getOwnPropertyDescriptor(view, property) {
|
|
75
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(view, property);
|
|
76
|
+
if (descriptor) return descriptor;
|
|
77
|
+
const applicationDescriptor = Reflect.getOwnPropertyDescriptor(applicationState, property);
|
|
78
|
+
return applicationDescriptor ? { ...applicationDescriptor, configurable: true } : void 0;
|
|
79
|
+
},
|
|
80
|
+
preventExtensions() {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
39
84
|
}
|
|
40
85
|
|
|
41
86
|
// src/core/headers.ts
|
|
42
|
-
function normalizeHeaderName(name) {
|
|
43
|
-
return name.toLowerCase();
|
|
44
|
-
}
|
|
45
|
-
function headersInitToHeaders(init) {
|
|
46
|
-
return new Headers(init);
|
|
47
|
-
}
|
|
48
87
|
function headersDiffer(base, overrides) {
|
|
49
88
|
for (const [key, value] of overrides.entries()) {
|
|
50
89
|
if (base.get(key) !== value) return true;
|
|
51
90
|
}
|
|
52
91
|
return false;
|
|
53
92
|
}
|
|
54
|
-
function isRequestHeaderAllowed(name, policy = {}) {
|
|
55
|
-
const key = normalizeHeaderName(name);
|
|
56
|
-
const allowed = new Set((policy.allowed ?? []).map(normalizeHeaderName));
|
|
57
|
-
if (allowed.has(key)) return true;
|
|
58
|
-
if (key.startsWith("x-middleware-")) return false;
|
|
59
|
-
const blocked = /* @__PURE__ */ new Set([
|
|
60
|
-
...DEFAULT_BLOCKED_REQUEST_HEADERS.map(normalizeHeaderName),
|
|
61
|
-
...(policy.blocked ?? []).map(normalizeHeaderName)
|
|
62
|
-
]);
|
|
63
|
-
return !blocked.has(key);
|
|
64
|
-
}
|
|
65
|
-
function mergeRequestHeaderOverrides(target, overrides, policy = {}) {
|
|
66
|
-
const dropped = [];
|
|
67
|
-
let applied = 0;
|
|
68
|
-
overrides.forEach((value, key) => {
|
|
69
|
-
if (!isRequestHeaderAllowed(key, policy)) {
|
|
70
|
-
dropped.push(key);
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
target.set(key, value);
|
|
74
|
-
applied++;
|
|
75
|
-
});
|
|
76
|
-
return { applied, dropped };
|
|
77
|
-
}
|
|
78
93
|
function parseCookieName(setCookie) {
|
|
79
94
|
const eq = setCookie.indexOf("=");
|
|
80
95
|
return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
|
|
@@ -180,30 +195,6 @@ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
|
|
|
180
195
|
}
|
|
181
196
|
}
|
|
182
197
|
|
|
183
|
-
// src/core/host-folder-prefix.ts
|
|
184
|
-
function physicalFolderPrefix(raw) {
|
|
185
|
-
return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
|
|
186
|
-
}
|
|
187
|
-
function isInsideFolder(pathname, folder) {
|
|
188
|
-
if (folder === "/") return true;
|
|
189
|
-
return pathname === folder || pathname.startsWith(`${folder}/`);
|
|
190
|
-
}
|
|
191
|
-
function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
|
|
192
|
-
try {
|
|
193
|
-
const parsed = new URL(rewriteUrl, baseUrl);
|
|
194
|
-
if (!isInsideFolder(parsed.pathname, folder)) {
|
|
195
|
-
parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
|
|
196
|
-
return parsed.toString();
|
|
197
|
-
}
|
|
198
|
-
return rewriteUrl;
|
|
199
|
-
} catch {
|
|
200
|
-
if (!isInsideFolder(rewriteUrl, folder)) {
|
|
201
|
-
return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
|
|
202
|
-
}
|
|
203
|
-
return rewriteUrl;
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
198
|
// src/core/logger.ts
|
|
208
199
|
var LEVEL_RANK = {
|
|
209
200
|
debug: 10,
|
|
@@ -303,6 +294,8 @@ function handlerLabel(handler) {
|
|
|
303
294
|
return { symbol: "!", text: "recovered", color: 33 };
|
|
304
295
|
case "timeout":
|
|
305
296
|
return { symbol: "\xD7", text: "timeout", color: 31 };
|
|
297
|
+
case "request-cancelled":
|
|
298
|
+
return { symbol: "\u2298", text: "request cancelled", color: 33 };
|
|
306
299
|
case "failed":
|
|
307
300
|
return { symbol: "\xD7", text: "failed", color: 31 };
|
|
308
301
|
}
|
|
@@ -321,6 +314,8 @@ function outcomeText(outcome) {
|
|
|
321
314
|
return `ERROR ${outcome.status}`;
|
|
322
315
|
case "timeout":
|
|
323
316
|
return `ERROR ${outcome.status} \xB7 timeout ${outcome.timeoutMs}ms`;
|
|
317
|
+
case "request-cancelled":
|
|
318
|
+
return "REQUEST CANCELLED";
|
|
324
319
|
}
|
|
325
320
|
}
|
|
326
321
|
function outcomeColor(outcome) {
|
|
@@ -334,23 +329,23 @@ function outcomeColor(outcome) {
|
|
|
334
329
|
case "error":
|
|
335
330
|
case "timeout":
|
|
336
331
|
return 31;
|
|
332
|
+
case "request-cancelled":
|
|
333
|
+
return 33;
|
|
337
334
|
case "response":
|
|
338
335
|
return outcome.status >= 500 ? 31 : 32;
|
|
339
336
|
}
|
|
340
337
|
}
|
|
341
338
|
function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
|
|
342
339
|
const path2 = trace.pathname ? ` ${safeDiagnosticText(trace.pathname)}` : "";
|
|
343
|
-
const header = `proxy-chain ${safeDiagnosticText(trace.method)}${path2}`;
|
|
340
|
+
const header = `[proxy-chain] ${safeDiagnosticText(trace.method)}${path2}`;
|
|
344
341
|
const rows = [];
|
|
345
342
|
const handlers = trace.handlers;
|
|
346
343
|
if (level === "compact") {
|
|
347
|
-
const
|
|
348
|
-
|
|
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)}`;
|
|
344
|
+
const reached = handlers.filter((handler) => handler.outcome !== "not-reached").length;
|
|
345
|
+
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`;
|
|
352
346
|
}
|
|
353
|
-
rows.push(
|
|
347
|
+
rows.push(header);
|
|
348
|
+
rows.push(` Request: ${safeDiagnosticText(trace.requestId, 64)}`);
|
|
354
349
|
const shown = handlers;
|
|
355
350
|
const symbols = unicode ? {
|
|
356
351
|
pass: "\u2502",
|
|
@@ -361,6 +356,7 @@ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
|
|
|
361
356
|
skip: "\u25CB",
|
|
362
357
|
missing: "\u2013",
|
|
363
358
|
error: "\xD7",
|
|
359
|
+
cancelled: "\u2298",
|
|
364
360
|
recovered: "!"
|
|
365
361
|
} : {
|
|
366
362
|
pass: "|",
|
|
@@ -371,12 +367,13 @@ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
|
|
|
371
367
|
skip: "o",
|
|
372
368
|
missing: "-",
|
|
373
369
|
error: "x",
|
|
370
|
+
cancelled: "!",
|
|
374
371
|
recovered: "!"
|
|
375
372
|
};
|
|
376
373
|
for (let index = 0; index < shown.length; index++) {
|
|
377
374
|
const handler = shown[index];
|
|
378
375
|
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;
|
|
376
|
+
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;
|
|
380
377
|
const prefix = symbols.pass;
|
|
381
378
|
const name = safeDiagnosticText(handler.name, 32);
|
|
382
379
|
const time = "durationMs" in handler ? paint(duration(handler.durationMs), 2, color) : "";
|
|
@@ -413,17 +410,20 @@ function formatTrace(trace, level, color = shouldUseColor(), unicode = true) {
|
|
|
413
410
|
rows.push(`${symbols.pass} destination: ${handler.destination}`);
|
|
414
411
|
}
|
|
415
412
|
}
|
|
416
|
-
if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout") {
|
|
413
|
+
if (handler.outcome === "recovered" || handler.outcome === "failed" || handler.outcome === "timeout" || handler.outcome === "request-cancelled") {
|
|
417
414
|
const policy = handler.policy === "none" ? "chain default" : handler.policy;
|
|
418
|
-
rows.push(
|
|
415
|
+
rows.push(
|
|
416
|
+
`${symbols.pass} ${handler.outcome === "request-cancelled" ? "cancellation policy" : "error policy"}: ${policy}`
|
|
417
|
+
);
|
|
419
418
|
}
|
|
420
|
-
if (handler.outcome === "timeout" && handler.
|
|
421
|
-
rows.push(`${symbols.pass} deadline: ${handler.
|
|
419
|
+
if (handler.outcome === "timeout" && handler.timeoutMs !== void 0) {
|
|
420
|
+
rows.push(`${symbols.pass} deadline: ${handler.timeoutMs}ms`);
|
|
422
421
|
}
|
|
423
422
|
}
|
|
424
423
|
rows.push(
|
|
425
424
|
`${symbols.last} ${paint(outcomeText(trace.outcome), outcomeColor(trace.outcome), color)}`
|
|
426
425
|
);
|
|
426
|
+
rows.push(` Total: ${paint(duration(trace.durationMs), 2, color)}`);
|
|
427
427
|
const output = rows.join("\n");
|
|
428
428
|
if (output.length <= 16384) return output;
|
|
429
429
|
const safeBoundary = output.lastIndexOf("\n", 16384);
|
|
@@ -510,16 +510,14 @@ function path(pattern) {
|
|
|
510
510
|
if (pattern instanceof RegExp) return compileRegexPath(pattern);
|
|
511
511
|
return compileStringPath(pattern);
|
|
512
512
|
}
|
|
513
|
-
function
|
|
513
|
+
function toPathRegexes(matcher) {
|
|
514
514
|
const list = Array.isArray(matcher) ? matcher : [matcher];
|
|
515
|
-
|
|
516
|
-
if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
|
|
517
|
-
return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
|
|
515
|
+
return list.map((m) => toStatelessRegExp(path(m)));
|
|
518
516
|
}
|
|
519
517
|
function compileScopes(input) {
|
|
520
518
|
if (input == null) return void 0;
|
|
521
519
|
const list = Array.isArray(input) ? input : [input];
|
|
522
|
-
const compilePath = (matcher) =>
|
|
520
|
+
const compilePath = (matcher) => toPathRegexes(matcher);
|
|
523
521
|
const compiled = [];
|
|
524
522
|
for (const item of list) {
|
|
525
523
|
if (typeof item === "string" || item instanceof RegExp) {
|
|
@@ -545,7 +543,7 @@ function scopeMatches(pathname, hostname, scope) {
|
|
|
545
543
|
if (!hostname || !scope.host.test(hostname)) return false;
|
|
546
544
|
}
|
|
547
545
|
if (scope.path) {
|
|
548
|
-
if (!scope.path.test(pathname)) return false;
|
|
546
|
+
if (!scope.path.some((alternative) => alternative.test(pathname))) return false;
|
|
549
547
|
}
|
|
550
548
|
return true;
|
|
551
549
|
}
|
|
@@ -560,12 +558,12 @@ function toRule(entry) {
|
|
|
560
558
|
const harden = (scopes) => scopes?.map((s) => {
|
|
561
559
|
if (!s.host && !s.path) {
|
|
562
560
|
throw new Error(
|
|
563
|
-
"[proxy-chain] include/exclude scope needs
|
|
561
|
+
"[proxy-chain] include/exclude scope needs a path, host, or host/path object."
|
|
564
562
|
);
|
|
565
563
|
}
|
|
566
564
|
return {
|
|
567
565
|
host: s.host ? toStatelessRegExp(s.host) : void 0,
|
|
568
|
-
path: s.path
|
|
566
|
+
path: s.path?.map(toStatelessRegExp)
|
|
569
567
|
};
|
|
570
568
|
});
|
|
571
569
|
return {
|
|
@@ -579,23 +577,6 @@ function ruleLabel(rule, index) {
|
|
|
579
577
|
const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
|
|
580
578
|
return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
|
|
581
579
|
}
|
|
582
|
-
function withPaths(entry, filter) {
|
|
583
|
-
const base = toRule(entry);
|
|
584
|
-
const include = compileScopes(filter.include);
|
|
585
|
-
const exclude = compileScopes(filter.exclude);
|
|
586
|
-
const name = filter.name ?? base.name;
|
|
587
|
-
assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
|
|
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
|
-
};
|
|
598
|
-
}
|
|
599
580
|
function ruleMatchReason(pathname, hostname, rule) {
|
|
600
581
|
if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
|
|
601
582
|
return "exclude-match";
|
|
@@ -626,7 +607,8 @@ function canonicalPathname(pathname) {
|
|
|
626
607
|
return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
|
|
627
608
|
}
|
|
628
609
|
function scopeKey(scope) {
|
|
629
|
-
|
|
610
|
+
const path2 = scope.path?.map((alternative) => `${alternative.source}::${alternative.flags}`).join("&");
|
|
611
|
+
return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${path2 ?? "*"}`;
|
|
630
612
|
}
|
|
631
613
|
function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
632
614
|
if (!include?.length || !exclude?.length) return;
|
|
@@ -641,7 +623,7 @@ function assertIncludeExcludeNoOverlap(include, exclude, label) {
|
|
|
641
623
|
}
|
|
642
624
|
|
|
643
625
|
// src/core/pipeline.ts
|
|
644
|
-
import { NextResponse } from "next/server";
|
|
626
|
+
import { NextResponse } from "next/server.js";
|
|
645
627
|
function safeInternalError() {
|
|
646
628
|
return new NextResponse("Internal Server Error", {
|
|
647
629
|
status: 500,
|
|
@@ -688,48 +670,26 @@ function assertOverrideMechanismSupported(strict = false) {
|
|
|
688
670
|
return false;
|
|
689
671
|
}
|
|
690
672
|
}
|
|
691
|
-
function resolveRuleResult(res
|
|
692
|
-
if (res
|
|
673
|
+
function resolveRuleResult(res) {
|
|
674
|
+
if (res === void 0) {
|
|
693
675
|
return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
|
|
694
676
|
}
|
|
695
|
-
if (!
|
|
677
|
+
if (!(res instanceof Response)) {
|
|
696
678
|
throw new TypeError(
|
|
697
|
-
`[proxy-chain] rule must return
|
|
679
|
+
`[proxy-chain] rule must return a Response or undefined. Got ${typeof res}.`
|
|
698
680
|
);
|
|
699
681
|
}
|
|
700
|
-
if (isNextResult(res)) {
|
|
701
|
-
let request;
|
|
702
|
-
if (res.request) {
|
|
703
|
-
const filtered = new Headers();
|
|
704
|
-
const { dropped } = mergeRequestHeaderOverrides(
|
|
705
|
-
filtered,
|
|
706
|
-
headersInitToHeaders(res.request),
|
|
707
|
-
requestHeaderPolicy
|
|
708
|
-
);
|
|
709
|
-
if (debug && dropped.length) {
|
|
710
|
-
logger.warn({ dropped }, "blocked request header mutation");
|
|
711
|
-
}
|
|
712
|
-
if ([...filtered.keys()].length) request = filtered;
|
|
713
|
-
}
|
|
714
|
-
const headerInit = res.headers ? headersInitToHeaders(res.headers) : void 0;
|
|
715
|
-
return {
|
|
716
|
-
kind: "continue",
|
|
717
|
-
request,
|
|
718
|
-
responseHeaders: headerInit ? responseHeaderItems(headerInit) : /* @__PURE__ */ new Map(),
|
|
719
|
-
cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
|
|
720
|
-
};
|
|
721
|
-
}
|
|
722
682
|
if (res instanceof NextResponse && res.headers.get("x-middleware-next") === "1") {
|
|
723
683
|
let request;
|
|
724
684
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
if ([...target.keys()].length) request = target;
|
|
685
|
+
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
686
|
+
if (hasRequestOverride) {
|
|
687
|
+
request = decoded;
|
|
729
688
|
}
|
|
730
689
|
return {
|
|
731
690
|
kind: "continue",
|
|
732
691
|
request,
|
|
692
|
+
...hasRequestOverride ? { requestMode: "replace" } : {},
|
|
733
693
|
responseHeaders: responseHeaderItems(res.headers),
|
|
734
694
|
cookies: cookieItemsFromHeaders(res.headers)
|
|
735
695
|
};
|
|
@@ -738,14 +698,14 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
|
|
|
738
698
|
if (rewriteHeader && (res.status === 200 || !res.status)) {
|
|
739
699
|
let request;
|
|
740
700
|
const decoded = decodeOverriddenRequestHeaders(res.headers);
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
if ([...target.keys()].length) request = target;
|
|
701
|
+
const hasRequestOverride = res.headers.has("x-middleware-override-headers");
|
|
702
|
+
if (hasRequestOverride) {
|
|
703
|
+
request = decoded;
|
|
745
704
|
}
|
|
746
705
|
return {
|
|
747
706
|
kind: "continue",
|
|
748
707
|
request,
|
|
708
|
+
...hasRequestOverride ? { requestMode: "replace" } : {},
|
|
749
709
|
responseHeaders: responseHeaderItems(res.headers),
|
|
750
710
|
cookies: cookieItemsFromHeaders(res.headers),
|
|
751
711
|
rewriteUrl: rewriteHeader
|
|
@@ -784,6 +744,7 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
|
|
|
784
744
|
}
|
|
785
745
|
|
|
786
746
|
// src/core/timeout.ts
|
|
747
|
+
var MAX_TIMEOUT_MS = 2147483647;
|
|
787
748
|
var RuleTimeoutError = class extends Error {
|
|
788
749
|
ruleName;
|
|
789
750
|
timeoutMs;
|
|
@@ -794,36 +755,94 @@ var RuleTimeoutError = class extends Error {
|
|
|
794
755
|
this.timeoutMs = timeoutMs;
|
|
795
756
|
}
|
|
796
757
|
};
|
|
797
|
-
|
|
798
|
-
|
|
758
|
+
var RequestCancellationError = class extends Error {
|
|
759
|
+
constructor() {
|
|
760
|
+
super("[proxy-chain] incoming request was cancelled");
|
|
761
|
+
this.name = "AbortError";
|
|
762
|
+
}
|
|
763
|
+
};
|
|
764
|
+
function assertValidTimeout(timeoutMs) {
|
|
765
|
+
if (timeoutMs !== void 0 && (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS)) {
|
|
799
766
|
throw new RangeError(
|
|
800
|
-
`[proxy-chain]
|
|
767
|
+
`[proxy-chain] timeout must be an integer from 0 through ${MAX_TIMEOUT_MS} milliseconds`
|
|
801
768
|
);
|
|
802
769
|
}
|
|
803
770
|
}
|
|
804
|
-
async function
|
|
805
|
-
|
|
806
|
-
|
|
771
|
+
async function runInExecutionScope(requestSignal, timeoutMs, ruleName, run) {
|
|
772
|
+
assertValidTimeout(timeoutMs);
|
|
773
|
+
const controller = new AbortController();
|
|
774
|
+
if (requestSignal.aborted) {
|
|
775
|
+
controller.abort();
|
|
776
|
+
throw new RequestCancellationError();
|
|
777
|
+
}
|
|
778
|
+
const scopeStartedAt = performance.now();
|
|
779
|
+
const timeoutError = timeoutMs > 0 ? new RuleTimeoutError(ruleName, timeoutMs) : void 0;
|
|
780
|
+
let failure;
|
|
781
|
+
let rejectCancelled;
|
|
782
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
783
|
+
rejectCancelled = reject;
|
|
784
|
+
});
|
|
785
|
+
const cancel = (error) => {
|
|
786
|
+
if (failure) return;
|
|
787
|
+
failure = error;
|
|
788
|
+
controller.abort();
|
|
789
|
+
rejectCancelled(error);
|
|
790
|
+
};
|
|
791
|
+
const assertActive = () => {
|
|
792
|
+
if (requestSignal.aborted) cancel(new RequestCancellationError());
|
|
793
|
+
else if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
794
|
+
cancel(timeoutError);
|
|
795
|
+
}
|
|
796
|
+
if (failure) throw failure;
|
|
797
|
+
};
|
|
798
|
+
const onRequestAbort = () => cancel(new RequestCancellationError());
|
|
799
|
+
requestSignal.addEventListener("abort", onRequestAbort, { once: true });
|
|
807
800
|
let timer;
|
|
808
|
-
|
|
809
|
-
timer = setTimeout(() =>
|
|
801
|
+
if (timeoutError) {
|
|
802
|
+
timer = setTimeout(() => cancel(timeoutError), timeoutMs);
|
|
803
|
+
}
|
|
804
|
+
const work = Promise.resolve().then(async () => {
|
|
805
|
+
if (controller.signal.aborted) throw failure ?? new RequestCancellationError();
|
|
806
|
+
try {
|
|
807
|
+
const result = await run(controller.signal, assertActive);
|
|
808
|
+
if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
809
|
+
cancel(timeoutError);
|
|
810
|
+
}
|
|
811
|
+
if (failure) throw failure;
|
|
812
|
+
return result;
|
|
813
|
+
} catch (error) {
|
|
814
|
+
if (timeoutError && !failure && performance.now() - scopeStartedAt >= timeoutMs) {
|
|
815
|
+
cancel(timeoutError);
|
|
816
|
+
}
|
|
817
|
+
throw failure ?? error;
|
|
818
|
+
}
|
|
810
819
|
});
|
|
811
820
|
try {
|
|
812
|
-
return await Promise.race([
|
|
821
|
+
return await Promise.race([work, cancelled]);
|
|
822
|
+
} catch (error) {
|
|
823
|
+
throw failure ?? error;
|
|
813
824
|
} finally {
|
|
814
825
|
if (timer !== void 0) clearTimeout(timer);
|
|
815
|
-
|
|
826
|
+
requestSignal.removeEventListener("abort", onRequestAbort);
|
|
827
|
+
void work.catch(() => {
|
|
816
828
|
});
|
|
817
829
|
}
|
|
818
830
|
}
|
|
831
|
+
async function runInRecoveryScope(requestSignal, run) {
|
|
832
|
+
const controller = new AbortController();
|
|
833
|
+
const abort = () => controller.abort();
|
|
834
|
+
if (requestSignal.aborted) controller.abort();
|
|
835
|
+
else requestSignal.addEventListener("abort", abort, { once: true });
|
|
836
|
+
try {
|
|
837
|
+
return await run(controller.signal);
|
|
838
|
+
} finally {
|
|
839
|
+
requestSignal.removeEventListener("abort", abort);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
819
842
|
|
|
820
843
|
// src/core/engine.ts
|
|
821
844
|
function monotonicNow() {
|
|
822
|
-
|
|
823
|
-
if (typeof globalThis.performance?.now === "function") return globalThis.performance.now();
|
|
824
|
-
} catch {
|
|
825
|
-
}
|
|
826
|
-
return Date.now();
|
|
845
|
+
return performance.now();
|
|
827
846
|
}
|
|
828
847
|
function normalizeDebugLevel(level) {
|
|
829
848
|
return level === true ? "detailed" : level;
|
|
@@ -890,76 +909,56 @@ function safeLogger(logger) {
|
|
|
890
909
|
error: wrap("error")
|
|
891
910
|
};
|
|
892
911
|
}
|
|
893
|
-
function
|
|
894
|
-
return value instanceof
|
|
912
|
+
function isTerminalRecovery(value) {
|
|
913
|
+
return value instanceof Response && resolveRuleResult(value).kind === "stop";
|
|
914
|
+
}
|
|
915
|
+
function isContinuingRecovery(value) {
|
|
916
|
+
return value instanceof Response && resolveRuleResult(value).kind === "continue";
|
|
895
917
|
}
|
|
896
918
|
function stripRoutingOverrides(res) {
|
|
897
919
|
const plain = !(res instanceof NextResponse2);
|
|
898
|
-
|
|
920
|
+
const keys = [...res.headers.keys()];
|
|
921
|
+
const remove = keys.filter((key) => {
|
|
899
922
|
const lower = key.toLowerCase();
|
|
900
|
-
|
|
901
|
-
res.headers.delete(key);
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
function isPathFilter(value) {
|
|
906
|
-
if (value === null || typeof value !== "object") return false;
|
|
907
|
-
if ("nextUrl" in value) return false;
|
|
908
|
-
return "include" in value || "exclude" in value || "name" in value;
|
|
909
|
-
}
|
|
910
|
-
function defineProxy(nameOrRun, maybeRun) {
|
|
911
|
-
const defaultName = typeof nameOrRun === "string" ? nameOrRun : void 0;
|
|
912
|
-
const run = typeof nameOrRun === "function" ? nameOrRun : maybeRun;
|
|
913
|
-
const proxy = ((reqOrFilter, eventOrCtx, maybeEvent) => {
|
|
914
|
-
if (isPathFilter(reqOrFilter)) {
|
|
915
|
-
return withPaths(run, {
|
|
916
|
-
...reqOrFilter,
|
|
917
|
-
name: reqOrFilter.name ?? defaultName
|
|
918
|
-
});
|
|
919
|
-
}
|
|
920
|
-
return run(reqOrFilter, eventOrCtx, maybeEvent);
|
|
921
|
-
});
|
|
922
|
-
Object.defineProperty(proxy, "name", {
|
|
923
|
-
value: defaultName ?? "",
|
|
924
|
-
configurable: true
|
|
923
|
+
return lower === "x-middleware-override-headers" || lower.startsWith("x-middleware-request-") || plain && (lower === "x-middleware-next" || lower === "x-middleware-rewrite");
|
|
925
924
|
});
|
|
926
|
-
|
|
927
|
-
|
|
925
|
+
if (!remove.length) return res;
|
|
926
|
+
try {
|
|
927
|
+
for (const key of remove) res.headers.delete(key);
|
|
928
|
+
return res;
|
|
929
|
+
} catch {
|
|
930
|
+
const headers = new Headers(res.headers);
|
|
931
|
+
for (const key of remove) headers.delete(key);
|
|
932
|
+
const init = { headers, status: res.status, statusText: res.statusText };
|
|
933
|
+
return res instanceof NextResponse2 ? new NextResponse2(res.body, init) : new Response(res.body, init);
|
|
934
|
+
}
|
|
928
935
|
}
|
|
929
|
-
function resolveConfig(overrides
|
|
930
|
-
const { logger, debug,
|
|
936
|
+
function resolveConfig(overrides) {
|
|
937
|
+
const { logger, debug, ...rest } = overrides;
|
|
931
938
|
const config = {
|
|
932
|
-
createContext: createContext ?? fallbackCreateContext,
|
|
933
939
|
cookieMergeStrategy: "last-write-wins",
|
|
934
940
|
headerMergeStrategy: "last-write-wins",
|
|
935
941
|
debug: false,
|
|
936
|
-
|
|
937
|
-
requestHeaderPolicy: {},
|
|
942
|
+
timeout: 0,
|
|
938
943
|
strictOverrideCheck: false,
|
|
939
|
-
hostFolderHeader: void 0,
|
|
940
944
|
tracePath: true,
|
|
941
945
|
...rest,
|
|
942
946
|
...debug !== void 0 ? { debug } : {},
|
|
943
947
|
logger: safeLogger(logger ?? createConsoleLogger("info"))
|
|
944
948
|
};
|
|
945
|
-
|
|
949
|
+
assertValidTimeout(config.timeout);
|
|
946
950
|
return config;
|
|
947
951
|
}
|
|
948
|
-
function
|
|
949
|
-
const
|
|
950
|
-
const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
|
|
951
|
-
const fallbackCreateContext = createProxyContext;
|
|
952
|
-
const config = resolveConfig(options, fallbackCreateContext);
|
|
952
|
+
function executeChain(options, entries) {
|
|
953
|
+
const config = resolveConfig(options);
|
|
953
954
|
const rules = entries.map(toRule);
|
|
954
955
|
const {
|
|
955
956
|
logger,
|
|
956
957
|
debug: debugLevel,
|
|
957
958
|
cookieMergeStrategy,
|
|
958
959
|
headerMergeStrategy,
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
strictOverrideCheck,
|
|
962
|
-
hostFolderHeader
|
|
960
|
+
timeout,
|
|
961
|
+
strictOverrideCheck
|
|
963
962
|
} = config;
|
|
964
963
|
const debug = debugLevel !== false;
|
|
965
964
|
const hasHandlerDebug = rules.some((rule) => rule.debug != null && rule.debug !== false);
|
|
@@ -970,10 +969,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
970
969
|
assertOverrideMechanismSupported(strictOverrideCheck);
|
|
971
970
|
for (let i = 0; i < rules.length; i++) {
|
|
972
971
|
assertIncludeExcludeNoOverlap(rules[i].include, rules[i].exclude, ruleLabel(rules[i], i));
|
|
973
|
-
|
|
972
|
+
assertValidTimeout(rules[i].timeout);
|
|
974
973
|
}
|
|
975
974
|
return async function proxy(req, event) {
|
|
976
|
-
const startedAt =
|
|
975
|
+
const startedAt = Date.now();
|
|
976
|
+
const invocationStartedAt = monotonicNow();
|
|
977
|
+
const requestId = `req_${globalThis.crypto.randomUUID()}`;
|
|
978
|
+
const metadata = createRequestMetadata(req, requestId, startedAt, invocationStartedAt);
|
|
979
|
+
const applicationState = createApplicationState();
|
|
977
980
|
const diagnostics = diagnosticsEnabled ? [] : null;
|
|
978
981
|
let nextHandlerIndex = 0;
|
|
979
982
|
const finish = (response, forcedOutcome) => {
|
|
@@ -985,9 +988,11 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
985
988
|
});
|
|
986
989
|
}
|
|
987
990
|
const trace = {
|
|
991
|
+
requestId,
|
|
992
|
+
startedAt,
|
|
988
993
|
method: safeDiagnosticText(req.method, 16),
|
|
989
|
-
pathname: config.tracePath === false ? void 0 : safeDiagnosticText(
|
|
990
|
-
durationMs: monotonicNow() -
|
|
994
|
+
pathname: config.tracePath === false ? void 0 : safeDiagnosticText(metadata.originalPathname),
|
|
995
|
+
durationMs: monotonicNow() - invocationStartedAt,
|
|
991
996
|
outcome: forcedOutcome ?? responseOutcome(response),
|
|
992
997
|
handlers: diagnostics
|
|
993
998
|
};
|
|
@@ -1000,14 +1005,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1000
1005
|
}
|
|
1001
1006
|
const globalLevel = normalizeDebugLevel(debugLevel);
|
|
1002
1007
|
if (globalLevel !== false || hasHandlerDebug) {
|
|
1003
|
-
const
|
|
1008
|
+
const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
|
|
1009
|
+
const visible = level === "compact" ? diagnostics : diagnostics.filter((_handler, index) => {
|
|
1004
1010
|
const local = rules[index]?.debug;
|
|
1005
1011
|
if (local === false) return false;
|
|
1006
1012
|
if (local === "compact") return globalLevel === "compact";
|
|
1007
1013
|
if (local != null) return true;
|
|
1008
1014
|
return globalLevel !== false && !(globalLevel === "compact" && hasDetailedHandlerDebug);
|
|
1009
1015
|
});
|
|
1010
|
-
const level = (globalLevel === "compact" || globalLevel === false) && hasDetailedHandlerDebug ? "detailed" : globalLevel === false ? "compact" : globalLevel;
|
|
1011
1016
|
try {
|
|
1012
1017
|
config.logger.info(
|
|
1013
1018
|
formatTrace(
|
|
@@ -1022,15 +1027,10 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1022
1027
|
}
|
|
1023
1028
|
return response;
|
|
1024
1029
|
};
|
|
1025
|
-
|
|
1026
|
-
try {
|
|
1027
|
-
ctx = config.createContext(req, event);
|
|
1028
|
-
} catch {
|
|
1029
|
-
if (!diagnosticsEnabled) logger.error("request context creation failed");
|
|
1030
|
-
return finish(safeInternalError(), { type: "error", status: 500, classification: "engine" });
|
|
1031
|
-
}
|
|
1030
|
+
const contextFor = (signal) => createHandlerContext(metadata, applicationState, signal);
|
|
1032
1031
|
let currentReq = req;
|
|
1033
1032
|
let pendingRequestOverrides = null;
|
|
1033
|
+
let replaceRequestHeaders = false;
|
|
1034
1034
|
let pendingRewriteUrl = null;
|
|
1035
1035
|
const headerWrites = [];
|
|
1036
1036
|
const cookieWrites = [];
|
|
@@ -1043,96 +1043,182 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1043
1043
|
logger,
|
|
1044
1044
|
debug
|
|
1045
1045
|
);
|
|
1046
|
+
const requestCancelledResponse = () => finish(
|
|
1047
|
+
finalizeResponse(
|
|
1048
|
+
NextResponse2.next(),
|
|
1049
|
+
headerWrites,
|
|
1050
|
+
cookieWrites,
|
|
1051
|
+
headerMergeStrategy,
|
|
1052
|
+
cookieMergeStrategy,
|
|
1053
|
+
logger,
|
|
1054
|
+
debug
|
|
1055
|
+
),
|
|
1056
|
+
{ type: "request-cancelled" }
|
|
1057
|
+
);
|
|
1046
1058
|
const materializeRequest = () => {
|
|
1047
1059
|
if (!pendingRequestOverrides) return currentReq;
|
|
1048
|
-
if (!headersDiffer(currentReq.headers, pendingRequestOverrides)) {
|
|
1060
|
+
if (!replaceRequestHeaders && !headersDiffer(currentReq.headers, pendingRequestOverrides)) {
|
|
1049
1061
|
pendingRequestOverrides = null;
|
|
1050
1062
|
return currentReq;
|
|
1051
1063
|
}
|
|
1052
|
-
const
|
|
1064
|
+
const nextUrl = currentReq.nextUrl.clone();
|
|
1065
|
+
const merged = replaceRequestHeaders ? new Headers() : new Headers(currentReq.headers);
|
|
1053
1066
|
pendingRequestOverrides.forEach((v, k) => {
|
|
1054
1067
|
merged.set(k, v);
|
|
1055
1068
|
});
|
|
1056
1069
|
pendingRequestOverrides = null;
|
|
1070
|
+
replaceRequestHeaders = false;
|
|
1057
1071
|
currentReq = new NextRequest(currentReq, { headers: merged });
|
|
1072
|
+
currentReq.nextUrl.pathname = nextUrl.pathname;
|
|
1073
|
+
currentReq.nextUrl.search = nextUrl.search;
|
|
1058
1074
|
return currentReq;
|
|
1059
1075
|
};
|
|
1060
|
-
const
|
|
1061
|
-
|
|
1062
|
-
|
|
1076
|
+
const queueRequestOverrides = (overrides, mode) => {
|
|
1077
|
+
if (mode === "replace") {
|
|
1078
|
+
pendingRequestOverrides = new Headers();
|
|
1079
|
+
replaceRequestHeaders = true;
|
|
1080
|
+
} else if (!pendingRequestOverrides) {
|
|
1081
|
+
pendingRequestOverrides = new Headers();
|
|
1082
|
+
}
|
|
1063
1083
|
const target = pendingRequestOverrides;
|
|
1064
1084
|
overrides.forEach((v, k) => {
|
|
1065
1085
|
target.set(k, v);
|
|
1066
|
-
appliedRequestOverrides.set(k, v);
|
|
1067
1086
|
});
|
|
1068
1087
|
};
|
|
1069
|
-
const recoverRuleError = async (err, i, label, req2,
|
|
1088
|
+
const recoverRuleError = async (err, i, label, req2, durationMs, phase) => {
|
|
1070
1089
|
const timeoutError = err instanceof RuleTimeoutError;
|
|
1071
|
-
const
|
|
1090
|
+
const requestCancelled = err instanceof RequestCancellationError;
|
|
1072
1091
|
const errorHandler = rules[i].onError ?? config.onError;
|
|
1073
1092
|
const errorPolicy = rules[i].onError ? "handler" : "chain";
|
|
1074
|
-
|
|
1075
|
-
|
|
1093
|
+
const diagnosticPhase = phase === "before-handler" ? "handler" : phase;
|
|
1094
|
+
const details = handlerDetails(rules[i], timeout, "matched", "matched", "not-matched");
|
|
1095
|
+
const stopFailure = (policy) => {
|
|
1076
1096
|
diagnostics?.push({
|
|
1077
1097
|
name: safeDiagnosticText(label, 64),
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1098
|
+
...requestCancelled ? {
|
|
1099
|
+
outcome: "request-cancelled",
|
|
1100
|
+
durationMs,
|
|
1101
|
+
phase: phase === "result" ? "handler" : phase,
|
|
1102
|
+
policy
|
|
1103
|
+
} : {
|
|
1104
|
+
outcome: timeoutError ? "timeout" : "failed",
|
|
1105
|
+
durationMs,
|
|
1106
|
+
phase: diagnosticPhase,
|
|
1107
|
+
policy,
|
|
1108
|
+
...timeoutError ? { timeoutMs: err.timeoutMs } : {}
|
|
1109
|
+
},
|
|
1110
|
+
details
|
|
1082
1111
|
});
|
|
1083
1112
|
nextHandlerIndex = i + 1;
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1113
|
+
if (requestCancelled) {
|
|
1114
|
+
return {
|
|
1115
|
+
response: finish(
|
|
1116
|
+
finalizeResponse(
|
|
1117
|
+
NextResponse2.next(),
|
|
1118
|
+
headerWrites,
|
|
1119
|
+
cookieWrites,
|
|
1120
|
+
headerMergeStrategy,
|
|
1121
|
+
cookieMergeStrategy,
|
|
1122
|
+
logger,
|
|
1123
|
+
debug
|
|
1124
|
+
),
|
|
1125
|
+
{ type: "request-cancelled" }
|
|
1126
|
+
)
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
if (timeoutError) {
|
|
1130
|
+
return {
|
|
1131
|
+
response: finish(failClosed(), {
|
|
1088
1132
|
type: "timeout",
|
|
1089
1133
|
status: 500,
|
|
1090
|
-
timeoutMs: err
|
|
1091
|
-
}
|
|
1092
|
-
|
|
1134
|
+
timeoutMs: err.timeoutMs
|
|
1135
|
+
})
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
return {
|
|
1139
|
+
response: finish(failClosed(), {
|
|
1140
|
+
type: "error",
|
|
1141
|
+
status: 500,
|
|
1142
|
+
classification: "handler"
|
|
1143
|
+
})
|
|
1093
1144
|
};
|
|
1145
|
+
};
|
|
1146
|
+
if (!errorHandler) {
|
|
1147
|
+
if (!diagnosticsEnabled) logger.error("handler failed");
|
|
1148
|
+
return stopFailure("none");
|
|
1094
1149
|
}
|
|
1095
1150
|
try {
|
|
1096
|
-
const recovered = await
|
|
1151
|
+
const recovered = await runInRecoveryScope(
|
|
1152
|
+
req2.signal,
|
|
1153
|
+
(signal) => errorHandler(err, i, req2, contextFor(signal))
|
|
1154
|
+
);
|
|
1155
|
+
if (timeoutError || requestCancelled) {
|
|
1156
|
+
if (isTerminalRecovery(recovered)) {
|
|
1157
|
+
const response2 = stripRoutingOverrides(recovered);
|
|
1158
|
+
headerWrites.push({
|
|
1159
|
+
ruleIndex: i,
|
|
1160
|
+
ruleName: label,
|
|
1161
|
+
items: responseHeaderItems(response2.headers)
|
|
1162
|
+
});
|
|
1163
|
+
cookieWrites.push({
|
|
1164
|
+
ruleIndex: i,
|
|
1165
|
+
ruleName: label,
|
|
1166
|
+
items: cookieItemsFromHeaders(response2.headers)
|
|
1167
|
+
});
|
|
1168
|
+
diagnostics?.push({
|
|
1169
|
+
name: safeDiagnosticText(label, 64),
|
|
1170
|
+
...requestCancelled ? {
|
|
1171
|
+
outcome: "request-cancelled",
|
|
1172
|
+
durationMs,
|
|
1173
|
+
phase: phase === "result" ? "handler" : phase,
|
|
1174
|
+
policy: errorPolicy,
|
|
1175
|
+
recovery: "response"
|
|
1176
|
+
} : {
|
|
1177
|
+
outcome: "timeout",
|
|
1178
|
+
durationMs,
|
|
1179
|
+
phase: diagnosticPhase,
|
|
1180
|
+
policy: errorPolicy,
|
|
1181
|
+
recovery: "response",
|
|
1182
|
+
timeoutMs: err.timeoutMs
|
|
1183
|
+
},
|
|
1184
|
+
details
|
|
1185
|
+
});
|
|
1186
|
+
nextHandlerIndex = i + 1;
|
|
1187
|
+
return {
|
|
1188
|
+
response: finish(
|
|
1189
|
+
finalizeResponse(
|
|
1190
|
+
response2,
|
|
1191
|
+
headerWrites,
|
|
1192
|
+
cookieWrites,
|
|
1193
|
+
headerMergeStrategy,
|
|
1194
|
+
cookieMergeStrategy,
|
|
1195
|
+
logger,
|
|
1196
|
+
debug
|
|
1197
|
+
),
|
|
1198
|
+
requestCancelled ? { type: "request-cancelled" } : {
|
|
1199
|
+
type: "timeout",
|
|
1200
|
+
status: recovered.status,
|
|
1201
|
+
timeoutMs: err.timeoutMs
|
|
1202
|
+
}
|
|
1203
|
+
)
|
|
1204
|
+
};
|
|
1205
|
+
}
|
|
1206
|
+
return stopFailure(errorPolicy);
|
|
1207
|
+
}
|
|
1097
1208
|
if (recovered == null) {
|
|
1098
|
-
|
|
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
|
-
};
|
|
1209
|
+
return stopFailure(errorPolicy);
|
|
1116
1210
|
}
|
|
1117
|
-
if (
|
|
1118
|
-
|
|
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 };
|
|
1211
|
+
if (isContinuingRecovery(recovered)) {
|
|
1212
|
+
return { raw: recovered, recovered: { durationMs, policy: errorPolicy, details } };
|
|
1128
1213
|
}
|
|
1129
1214
|
if (!(recovered instanceof Response)) {
|
|
1130
1215
|
diagnostics?.push({
|
|
1131
1216
|
name: safeDiagnosticText(label, 64),
|
|
1132
|
-
outcome:
|
|
1133
|
-
durationMs
|
|
1217
|
+
outcome: "failed",
|
|
1218
|
+
durationMs,
|
|
1219
|
+
phase: diagnosticPhase,
|
|
1134
1220
|
policy: errorPolicy,
|
|
1135
|
-
details
|
|
1221
|
+
details
|
|
1136
1222
|
});
|
|
1137
1223
|
nextHandlerIndex = i + 1;
|
|
1138
1224
|
return {
|
|
@@ -1143,30 +1229,30 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1143
1229
|
})
|
|
1144
1230
|
};
|
|
1145
1231
|
}
|
|
1146
|
-
stripRoutingOverrides(recovered);
|
|
1232
|
+
const response = stripRoutingOverrides(recovered);
|
|
1147
1233
|
headerWrites.push({
|
|
1148
1234
|
ruleIndex: i,
|
|
1149
1235
|
ruleName: label,
|
|
1150
|
-
items: responseHeaderItems(
|
|
1236
|
+
items: responseHeaderItems(response.headers)
|
|
1151
1237
|
});
|
|
1152
1238
|
cookieWrites.push({
|
|
1153
1239
|
ruleIndex: i,
|
|
1154
1240
|
ruleName: label,
|
|
1155
|
-
items: cookieItemsFromHeaders(
|
|
1241
|
+
items: cookieItemsFromHeaders(response.headers)
|
|
1156
1242
|
});
|
|
1157
1243
|
diagnostics?.push({
|
|
1158
1244
|
name: safeDiagnosticText(label, 64),
|
|
1159
1245
|
outcome: "recovered",
|
|
1160
|
-
durationMs
|
|
1161
|
-
recovery: responseOutcome(
|
|
1246
|
+
durationMs,
|
|
1247
|
+
recovery: responseOutcome(response).type === "redirect" ? "redirect" : responseOutcome(response).type === "rewrite" ? "rewrite" : "response",
|
|
1162
1248
|
policy: errorPolicy,
|
|
1163
|
-
details
|
|
1249
|
+
details
|
|
1164
1250
|
});
|
|
1165
1251
|
nextHandlerIndex = i + 1;
|
|
1166
1252
|
return {
|
|
1167
1253
|
response: finish(
|
|
1168
1254
|
finalizeResponse(
|
|
1169
|
-
|
|
1255
|
+
response,
|
|
1170
1256
|
headerWrites,
|
|
1171
1257
|
cookieWrites,
|
|
1172
1258
|
headerMergeStrategy,
|
|
@@ -1178,27 +1264,26 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1178
1264
|
};
|
|
1179
1265
|
} catch {
|
|
1180
1266
|
if (!diagnosticsEnabled) logger.error("chain error handler failed");
|
|
1181
|
-
|
|
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
|
-
};
|
|
1267
|
+
return stopFailure(errorPolicy);
|
|
1196
1268
|
}
|
|
1197
1269
|
};
|
|
1198
1270
|
try {
|
|
1199
1271
|
for (let i = 0; i < rules.length; i++) {
|
|
1200
1272
|
const rule = rules[i];
|
|
1201
1273
|
const label = ruleLabel(rule, i);
|
|
1274
|
+
nextHandlerIndex = i;
|
|
1275
|
+
if (req.signal.aborted) {
|
|
1276
|
+
const cancelled = await recoverRuleError(
|
|
1277
|
+
new RequestCancellationError(),
|
|
1278
|
+
i,
|
|
1279
|
+
label,
|
|
1280
|
+
materializeRequest(),
|
|
1281
|
+
0,
|
|
1282
|
+
"before-handler"
|
|
1283
|
+
);
|
|
1284
|
+
if ("response" in cancelled) return cancelled.response;
|
|
1285
|
+
return requestCancelledResponse();
|
|
1286
|
+
}
|
|
1202
1287
|
const activeReq = materializeRequest();
|
|
1203
1288
|
const reqHost = normalizeHost(
|
|
1204
1289
|
activeReq.headers.get("host") ?? activeReq.headers.get("x-forwarded-host")
|
|
@@ -1212,7 +1297,6 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1212
1297
|
})
|
|
1213
1298
|
);
|
|
1214
1299
|
}
|
|
1215
|
-
nextHandlerIndex = i;
|
|
1216
1300
|
const skipReason = ruleMatchReason(matchPath, reqHost, rule);
|
|
1217
1301
|
if (skipReason) {
|
|
1218
1302
|
diagnostics?.push({
|
|
@@ -1221,7 +1305,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1221
1305
|
reason: skipReason,
|
|
1222
1306
|
details: handlerDetails(
|
|
1223
1307
|
rule,
|
|
1224
|
-
|
|
1308
|
+
timeout,
|
|
1225
1309
|
"not-evaluated",
|
|
1226
1310
|
skipReason === "include-mismatch" ? "mismatch" : void 0,
|
|
1227
1311
|
skipReason === "exclude-match" ? "matched" : skipReason === "include-mismatch" && rule.exclude ? "not-matched" : void 0
|
|
@@ -1230,44 +1314,66 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1230
1314
|
nextHandlerIndex = i + 1;
|
|
1231
1315
|
continue;
|
|
1232
1316
|
}
|
|
1233
|
-
const
|
|
1234
|
-
|
|
1317
|
+
const executionStartedAt = monotonicNow();
|
|
1318
|
+
const effectiveTimeout = rule.timeout ?? timeout;
|
|
1319
|
+
let phase = rule.when ? "when" : "handler";
|
|
1320
|
+
let result;
|
|
1321
|
+
let recoveredRule;
|
|
1235
1322
|
try {
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1323
|
+
result = await runInExecutionScope(
|
|
1324
|
+
req.signal,
|
|
1325
|
+
effectiveTimeout,
|
|
1326
|
+
label,
|
|
1327
|
+
async (signal, assertActive) => {
|
|
1328
|
+
const context = contextFor(signal);
|
|
1329
|
+
if (rule.when) {
|
|
1330
|
+
const matches = await rule.when(activeReq, event, context);
|
|
1331
|
+
assertActive();
|
|
1332
|
+
if (!matches) return { kind: "skipped" };
|
|
1240
1333
|
}
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1334
|
+
phase = "handler";
|
|
1335
|
+
assertActive();
|
|
1336
|
+
return {
|
|
1337
|
+
kind: "result",
|
|
1338
|
+
raw: await rule.run(activeReq, context, event)
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1245
1341
|
);
|
|
1246
1342
|
if (result.kind === "skipped") {
|
|
1247
1343
|
diagnostics?.push({
|
|
1248
1344
|
name: safeDiagnosticText(label, 64),
|
|
1249
1345
|
outcome: "skipped",
|
|
1250
1346
|
reason: "when-false",
|
|
1251
|
-
details: handlerDetails(rule,
|
|
1347
|
+
details: handlerDetails(rule, timeout, "false", "matched", "not-matched")
|
|
1252
1348
|
});
|
|
1253
1349
|
nextHandlerIndex = i + 1;
|
|
1254
1350
|
continue;
|
|
1255
1351
|
}
|
|
1256
|
-
raw = result.raw;
|
|
1257
1352
|
} catch (err) {
|
|
1258
|
-
const recovered = await recoverRuleError(
|
|
1353
|
+
const recovered = await recoverRuleError(
|
|
1354
|
+
err,
|
|
1355
|
+
i,
|
|
1356
|
+
label,
|
|
1357
|
+
activeReq,
|
|
1358
|
+
monotonicNow() - executionStartedAt,
|
|
1359
|
+
phase
|
|
1360
|
+
);
|
|
1259
1361
|
if ("response" in recovered) return recovered.response;
|
|
1260
|
-
|
|
1362
|
+
result = { kind: "result", raw: recovered.raw };
|
|
1363
|
+
recoveredRule = recovered.recovered;
|
|
1261
1364
|
}
|
|
1365
|
+
let raw = result.raw;
|
|
1366
|
+
let duration2 = monotonicNow() - executionStartedAt;
|
|
1262
1367
|
let outcome;
|
|
1263
1368
|
try {
|
|
1264
|
-
outcome = resolveRuleResult(raw
|
|
1369
|
+
outcome = resolveRuleResult(raw);
|
|
1265
1370
|
} catch (err) {
|
|
1266
|
-
const recovered = await recoverRuleError(err, i, label, activeReq,
|
|
1371
|
+
const recovered = await recoverRuleError(err, i, label, activeReq, duration2, "result");
|
|
1267
1372
|
if ("response" in recovered) return recovered.response;
|
|
1268
|
-
|
|
1373
|
+
raw = recovered.raw;
|
|
1374
|
+
recoveredRule = recovered.recovered;
|
|
1375
|
+
outcome = resolveRuleResult(raw);
|
|
1269
1376
|
}
|
|
1270
|
-
const duration2 = diagnosticsEnabled ? monotonicNow() - startedAt2 : 0;
|
|
1271
1377
|
if (outcome.kind === "continue") {
|
|
1272
1378
|
if (outcome.rewriteUrl) {
|
|
1273
1379
|
pendingRewriteUrl = outcome.rewriteUrl;
|
|
@@ -1282,12 +1388,21 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1282
1388
|
currentReq.nextUrl.pathname = outcome.rewriteUrl;
|
|
1283
1389
|
}
|
|
1284
1390
|
}
|
|
1285
|
-
if (outcome.request) queueRequestOverrides(outcome.request);
|
|
1391
|
+
if (outcome.request) queueRequestOverrides(outcome.request, outcome.requestMode);
|
|
1286
1392
|
if (outcome.responseHeaders.size || outcome.cookies.size) {
|
|
1287
1393
|
headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
|
|
1288
1394
|
cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
|
|
1289
1395
|
}
|
|
1290
|
-
if (
|
|
1396
|
+
if (recoveredRule) {
|
|
1397
|
+
diagnostics?.push({
|
|
1398
|
+
name: safeDiagnosticText(label, 64),
|
|
1399
|
+
outcome: "recovered",
|
|
1400
|
+
durationMs: recoveredRule.durationMs,
|
|
1401
|
+
recovery: outcome.rewriteUrl ? "rewrite" : "continue",
|
|
1402
|
+
policy: recoveredRule.policy,
|
|
1403
|
+
details: recoveredRule.details
|
|
1404
|
+
});
|
|
1405
|
+
} else {
|
|
1291
1406
|
diagnostics?.push(
|
|
1292
1407
|
outcome.rewriteUrl ? {
|
|
1293
1408
|
name: safeDiagnosticText(label, 64),
|
|
@@ -1295,43 +1410,31 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1295
1410
|
durationMs: duration2,
|
|
1296
1411
|
destination: safeDestination(outcome.rewriteUrl) ?? "/",
|
|
1297
1412
|
final: false,
|
|
1298
|
-
details: handlerDetails(
|
|
1299
|
-
rule,
|
|
1300
|
-
ruleTimeoutMs,
|
|
1301
|
-
"matched",
|
|
1302
|
-
"matched",
|
|
1303
|
-
"not-matched"
|
|
1304
|
-
)
|
|
1413
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1305
1414
|
} : {
|
|
1306
1415
|
name: safeDiagnosticText(label, 64),
|
|
1307
1416
|
outcome: "continue",
|
|
1308
|
-
source:
|
|
1417
|
+
source: raw instanceof NextResponse2 && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
|
|
1309
1418
|
durationMs: duration2,
|
|
1310
|
-
details: handlerDetails(
|
|
1311
|
-
rule,
|
|
1312
|
-
ruleTimeoutMs,
|
|
1313
|
-
"matched",
|
|
1314
|
-
"matched",
|
|
1315
|
-
"not-matched"
|
|
1316
|
-
)
|
|
1419
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1317
1420
|
}
|
|
1318
1421
|
);
|
|
1319
1422
|
}
|
|
1320
1423
|
nextHandlerIndex = i + 1;
|
|
1321
1424
|
continue;
|
|
1322
1425
|
}
|
|
1323
|
-
stripRoutingOverrides(outcome.response);
|
|
1426
|
+
const response = stripRoutingOverrides(outcome.response);
|
|
1324
1427
|
headerWrites.push({
|
|
1325
1428
|
ruleIndex: i,
|
|
1326
1429
|
ruleName: label,
|
|
1327
|
-
items: responseHeaderItems(
|
|
1430
|
+
items: responseHeaderItems(response.headers)
|
|
1328
1431
|
});
|
|
1329
1432
|
cookieWrites.push({
|
|
1330
1433
|
ruleIndex: i,
|
|
1331
1434
|
ruleName: label,
|
|
1332
|
-
items: cookieItemsFromHeaders(
|
|
1435
|
+
items: cookieItemsFromHeaders(response.headers)
|
|
1333
1436
|
});
|
|
1334
|
-
const terminalOutcome = responseOutcome(
|
|
1437
|
+
const terminalOutcome = responseOutcome(response);
|
|
1335
1438
|
diagnostics?.push(
|
|
1336
1439
|
terminalOutcome.type === "redirect" ? {
|
|
1337
1440
|
name: safeDiagnosticText(label, 64),
|
|
@@ -1339,40 +1442,31 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1339
1442
|
durationMs: duration2,
|
|
1340
1443
|
status: terminalOutcome.status,
|
|
1341
1444
|
destination: terminalOutcome.destination,
|
|
1342
|
-
details: handlerDetails(rule,
|
|
1445
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1343
1446
|
} : terminalOutcome.type === "rewrite" ? {
|
|
1344
1447
|
name: safeDiagnosticText(label, 64),
|
|
1345
1448
|
outcome: "rewrite",
|
|
1346
1449
|
durationMs: duration2,
|
|
1347
1450
|
destination: terminalOutcome.destination,
|
|
1348
1451
|
final: true,
|
|
1349
|
-
details: handlerDetails(rule,
|
|
1452
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1350
1453
|
} : {
|
|
1351
1454
|
name: safeDiagnosticText(label, 64),
|
|
1352
1455
|
outcome: "response",
|
|
1353
1456
|
durationMs: duration2,
|
|
1354
|
-
status:
|
|
1355
|
-
details: handlerDetails(rule,
|
|
1457
|
+
status: response.status,
|
|
1458
|
+
details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
|
|
1356
1459
|
}
|
|
1357
1460
|
);
|
|
1358
1461
|
nextHandlerIndex = i + 1;
|
|
1359
|
-
const
|
|
1360
|
-
if (internalFolder && outcome.response.headers.has("x-middleware-rewrite")) {
|
|
1361
|
-
const rawRewrite = outcome.response.headers.get("x-middleware-rewrite");
|
|
1362
|
-
const cleanFolder = physicalFolderPrefix(internalFolder);
|
|
1363
|
-
outcome.response.headers.set(
|
|
1364
|
-
"x-middleware-rewrite",
|
|
1365
|
-
applyFolderPrefix(rawRewrite, cleanFolder, currentReq.url)
|
|
1366
|
-
);
|
|
1367
|
-
}
|
|
1368
|
-
const finalTerminalOutcome = responseOutcome(outcome.response);
|
|
1462
|
+
const finalTerminalOutcome = responseOutcome(response);
|
|
1369
1463
|
const terminalTrace = diagnostics?.at(-1);
|
|
1370
1464
|
if (finalTerminalOutcome.type === "rewrite" && terminalTrace?.outcome === "rewrite") {
|
|
1371
1465
|
terminalTrace.destination = finalTerminalOutcome.destination;
|
|
1372
1466
|
}
|
|
1373
1467
|
return finish(
|
|
1374
1468
|
finalizeResponse(
|
|
1375
|
-
|
|
1469
|
+
response,
|
|
1376
1470
|
headerWrites,
|
|
1377
1471
|
cookieWrites,
|
|
1378
1472
|
headerMergeStrategy,
|
|
@@ -1384,21 +1478,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1384
1478
|
);
|
|
1385
1479
|
}
|
|
1386
1480
|
const finalReq = materializeRequest();
|
|
1387
|
-
const
|
|
1388
|
-
let finalRewriteUrl = pendingRewriteUrl;
|
|
1389
|
-
if (internalHostFolder) {
|
|
1390
|
-
const cleanFolder = physicalFolderPrefix(internalHostFolder);
|
|
1391
|
-
if (finalRewriteUrl) {
|
|
1392
|
-
finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
|
|
1393
|
-
} else {
|
|
1394
|
-
const currentPath = finalReq.nextUrl.pathname;
|
|
1395
|
-
if (!isInsideFolder(currentPath, cleanFolder)) {
|
|
1396
|
-
const targetUrl = finalReq.nextUrl.clone();
|
|
1397
|
-
targetUrl.pathname = cleanFolder + (currentPath === "/" ? "" : currentPath);
|
|
1398
|
-
finalRewriteUrl = targetUrl.toString();
|
|
1399
|
-
}
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1481
|
+
const finalRewriteUrl = pendingRewriteUrl;
|
|
1402
1482
|
const requestInit = finalReq !== req ? { request: { headers: finalReq.headers } } : void 0;
|
|
1403
1483
|
let final;
|
|
1404
1484
|
if (finalRewriteUrl) {
|
|
@@ -1429,12 +1509,15 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1429
1509
|
if (!diagnosticsEnabled) logger.error("proxy chain execution failed");
|
|
1430
1510
|
if (config.onError) {
|
|
1431
1511
|
try {
|
|
1432
|
-
const recovered = await
|
|
1433
|
-
|
|
1434
|
-
|
|
1512
|
+
const recovered = await runInRecoveryScope(
|
|
1513
|
+
req.signal,
|
|
1514
|
+
(signal) => config.onError(err, -1, materializeRequest(), contextFor(signal))
|
|
1515
|
+
);
|
|
1516
|
+
if (isTerminalRecovery(recovered)) {
|
|
1517
|
+
const response = stripRoutingOverrides(recovered);
|
|
1435
1518
|
return finish(
|
|
1436
1519
|
finalizeResponse(
|
|
1437
|
-
|
|
1520
|
+
response,
|
|
1438
1521
|
headerWrites,
|
|
1439
1522
|
cookieWrites,
|
|
1440
1523
|
headerMergeStrategy,
|
|
@@ -1455,44 +1538,28 @@ function proxyChain(optionsOrEntries, maybeEntries) {
|
|
|
1455
1538
|
};
|
|
1456
1539
|
}
|
|
1457
1540
|
|
|
1458
|
-
// src/core/
|
|
1459
|
-
function
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
function isScopeObject2(value) {
|
|
1463
|
-
return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
|
|
1464
|
-
}
|
|
1465
|
-
function toFilter(scope) {
|
|
1466
|
-
if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
|
|
1467
|
-
return { include: scope };
|
|
1468
|
-
}
|
|
1469
|
-
function fromNative(handler) {
|
|
1470
|
-
const run = (req, ctx, event) => handler(req, event, ctx);
|
|
1471
|
-
const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
|
|
1472
|
-
return { run, name };
|
|
1473
|
-
}
|
|
1474
|
-
function toEntry(entry) {
|
|
1475
|
-
if (Array.isArray(entry)) {
|
|
1476
|
-
const [target, scope] = entry;
|
|
1477
|
-
const filter = toFilter(scope);
|
|
1478
|
-
if (isContextRule(target)) return target(filter);
|
|
1479
|
-
return withPaths(fromNative(target), filter);
|
|
1541
|
+
// src/core/handler.ts
|
|
1542
|
+
function assertHandlerConfig(options) {
|
|
1543
|
+
if (!options || typeof options !== "object" || typeof options.name !== "string" || options.name.trim() === "" || typeof options.handle !== "function") {
|
|
1544
|
+
throw new TypeError("[proxy-chain] configured handlers require a non-empty name and handle");
|
|
1480
1545
|
}
|
|
1481
|
-
if (
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1546
|
+
if ("handler" in options) {
|
|
1547
|
+
throw new TypeError(
|
|
1548
|
+
"[proxy-chain] configured handler property 'handler' is unsupported; use 'handle'"
|
|
1549
|
+
);
|
|
1550
|
+
}
|
|
1551
|
+
if ("config" in options || "options" in options) {
|
|
1552
|
+
throw new TypeError("[proxy-chain] handler configuration must use top-level options");
|
|
1553
|
+
}
|
|
1554
|
+
assertValidTimeout(options.timeout);
|
|
1488
1555
|
}
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1556
|
+
function toHandlerRule(options) {
|
|
1557
|
+
assertHandlerConfig(options);
|
|
1558
|
+
const { handle } = options;
|
|
1492
1559
|
const include = compileScopes(options.rules?.include);
|
|
1493
1560
|
const exclude = compileScopes(options.rules?.exclude);
|
|
1494
|
-
|
|
1495
|
-
run: (request, context, event) =>
|
|
1561
|
+
return {
|
|
1562
|
+
run: (request, context, event) => handle(request, event, context),
|
|
1496
1563
|
name: options.name,
|
|
1497
1564
|
include,
|
|
1498
1565
|
exclude,
|
|
@@ -1505,17 +1572,31 @@ function defineHandler(options) {
|
|
|
1505
1572
|
exclude: options.rules?.exclude
|
|
1506
1573
|
}
|
|
1507
1574
|
};
|
|
1508
|
-
|
|
1575
|
+
}
|
|
1576
|
+
function defineHandler(options) {
|
|
1577
|
+
assertHandlerConfig(options);
|
|
1578
|
+
return options;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
// src/core/chain.ts
|
|
1582
|
+
function fromNative(handle) {
|
|
1583
|
+
const run = (req, ctx, event) => handle(req, event, ctx);
|
|
1584
|
+
const name = handle.name && handle.name !== "proxy" ? handle.name : void 0;
|
|
1585
|
+
return { run, name };
|
|
1586
|
+
}
|
|
1587
|
+
function toEntry(entry) {
|
|
1588
|
+
if (typeof entry === "function") return fromNative(entry);
|
|
1589
|
+
if (Array.isArray(entry)) {
|
|
1590
|
+
throw new TypeError("[proxy-chain] tuple entries are not supported; use a configured handler");
|
|
1591
|
+
}
|
|
1592
|
+
if (entry && typeof entry === "object") return toHandlerRule(entry);
|
|
1593
|
+
throw new TypeError("[proxy-chain] chain entries must be native handlers or configured handlers");
|
|
1594
|
+
}
|
|
1595
|
+
function chain(entries, options) {
|
|
1596
|
+
const normalized = entries.map((entry) => toEntry(entry));
|
|
1597
|
+
return executeChain(options ?? {}, normalized);
|
|
1509
1598
|
}
|
|
1510
1599
|
export {
|
|
1511
|
-
RuleTimeoutError,
|
|
1512
1600
|
chain,
|
|
1513
|
-
|
|
1514
|
-
defineHandler,
|
|
1515
|
-
defineProxy,
|
|
1516
|
-
host,
|
|
1517
|
-
isNextResult,
|
|
1518
|
-
next,
|
|
1519
|
-
path,
|
|
1520
|
-
proxyChain
|
|
1601
|
+
defineHandler
|
|
1521
1602
|
};
|