@klnap/next-proxy-chain 2.0.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/dist/index.cjs CHANGED
@@ -20,48 +20,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- RuleTimeoutError: () => RuleTimeoutError,
24
23
  chain: () => chain,
25
- defineHandler: () => defineHandler,
26
- host: () => host,
27
- isNextResult: () => isNextResult,
28
- next: () => next,
29
- path: () => path
24
+ defineHandler: () => defineHandler
30
25
  });
31
26
  module.exports = __toCommonJS(index_exports);
32
27
 
33
- // src/core/constants.ts
34
- var NEXT = /* @__PURE__ */ Symbol.for("proxy-chain.next");
35
- var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
36
- "host",
37
- "connection",
38
- "keep-alive",
39
- "proxy-authenticate",
40
- "proxy-authorization",
41
- "te",
42
- "trailer",
43
- "transfer-encoding",
44
- "upgrade",
45
- "content-length",
46
- "cookie",
47
- "authorization",
48
- "x-forwarded-host",
49
- "x-forwarded-for",
50
- "x-forwarded-proto",
51
- "x-real-ip",
52
- "x-middleware-next",
53
- "x-middleware-override-headers"
54
- ]);
55
- var DEFINED_HANDLER = /* @__PURE__ */ Symbol.for("proxy-chain.defined-handler");
56
-
57
- // src/core/actions.ts
58
- function next(options = {}) {
59
- return { [NEXT]: true, ...options };
60
- }
61
- function isNextResult(value) {
62
- return typeof value === "object" && value !== null && NEXT in value;
63
- }
64
-
65
28
  // src/core/engine.ts
66
29
  var import_server2 = require("next/server.js");
67
30
 
@@ -148,42 +111,12 @@ function createHandlerContext(metadata, applicationState, signal) {
148
111
  }
149
112
 
150
113
  // src/core/headers.ts
151
- function normalizeHeaderName(name) {
152
- return name.toLowerCase();
153
- }
154
- function headersInitToHeaders(init) {
155
- return new Headers(init);
156
- }
157
114
  function headersDiffer(base, overrides) {
158
115
  for (const [key, value] of overrides.entries()) {
159
116
  if (base.get(key) !== value) return true;
160
117
  }
161
118
  return false;
162
119
  }
163
- function isRequestHeaderAllowed(name, policy = {}) {
164
- const key = normalizeHeaderName(name);
165
- const allowed = new Set((policy.allowed ?? []).map(normalizeHeaderName));
166
- if (allowed.has(key)) return true;
167
- if (key.startsWith("x-middleware-")) return false;
168
- const blocked = /* @__PURE__ */ new Set([
169
- ...DEFAULT_BLOCKED_REQUEST_HEADERS.map(normalizeHeaderName),
170
- ...(policy.blocked ?? []).map(normalizeHeaderName)
171
- ]);
172
- return !blocked.has(key);
173
- }
174
- function mergeRequestHeaderOverrides(target, overrides, policy = {}) {
175
- const dropped = [];
176
- let applied = 0;
177
- overrides.forEach((value, key) => {
178
- if (!isRequestHeaderAllowed(key, policy)) {
179
- dropped.push(key);
180
- return;
181
- }
182
- target.set(key, value);
183
- applied++;
184
- });
185
- return { applied, dropped };
186
- }
187
120
  function parseCookieName(setCookie) {
188
121
  const eq = setCookie.indexOf("=");
189
122
  return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
@@ -604,16 +537,14 @@ function path(pattern) {
604
537
  if (pattern instanceof RegExp) return compileRegexPath(pattern);
605
538
  return compileStringPath(pattern);
606
539
  }
607
- function toPathRegex(matcher) {
540
+ function toPathRegexes(matcher) {
608
541
  const list = Array.isArray(matcher) ? matcher : [matcher];
609
- const regexes = list.map((m) => path(m));
610
- if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
611
- return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
542
+ return list.map((m) => toStatelessRegExp(path(m)));
612
543
  }
613
544
  function compileScopes(input) {
614
545
  if (input == null) return void 0;
615
546
  const list = Array.isArray(input) ? input : [input];
616
- const compilePath = (matcher) => toPathRegex(matcher);
547
+ const compilePath = (matcher) => toPathRegexes(matcher);
617
548
  const compiled = [];
618
549
  for (const item of list) {
619
550
  if (typeof item === "string" || item instanceof RegExp) {
@@ -639,7 +570,7 @@ function scopeMatches(pathname, hostname, scope) {
639
570
  if (!hostname || !scope.host.test(hostname)) return false;
640
571
  }
641
572
  if (scope.path) {
642
- if (!scope.path.test(pathname)) return false;
573
+ if (!scope.path.some((alternative) => alternative.test(pathname))) return false;
643
574
  }
644
575
  return true;
645
576
  }
@@ -654,12 +585,12 @@ function toRule(entry) {
654
585
  const harden = (scopes) => scopes?.map((s) => {
655
586
  if (!s.host && !s.path) {
656
587
  throw new Error(
657
- "[proxy-chain] include/exclude scope needs `host` or `path`. Build scopes with path() or host()."
588
+ "[proxy-chain] include/exclude scope needs a path, host, or host/path object."
658
589
  );
659
590
  }
660
591
  return {
661
592
  host: s.host ? toStatelessRegExp(s.host) : void 0,
662
- path: s.path ? toStatelessRegExp(s.path) : void 0
593
+ path: s.path?.map(toStatelessRegExp)
663
594
  };
664
595
  });
665
596
  return {
@@ -673,23 +604,6 @@ function ruleLabel(rule, index) {
673
604
  const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
674
605
  return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
675
606
  }
676
- function withPaths(entry, filter) {
677
- const base = toRule(entry);
678
- const include = compileScopes(filter.include);
679
- const exclude = compileScopes(filter.exclude);
680
- const name = filter.name ?? base.name;
681
- assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
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
- };
692
- }
693
607
  function ruleMatchReason(pathname, hostname, rule) {
694
608
  if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) {
695
609
  return "exclude-match";
@@ -720,7 +634,8 @@ function canonicalPathname(pathname) {
720
634
  return decoded.length > 1 ? decoded.replace(/\/+$/, "") || "/" : decoded;
721
635
  }
722
636
  function scopeKey(scope) {
723
- return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
637
+ const path2 = scope.path?.map((alternative) => `${alternative.source}::${alternative.flags}`).join("&");
638
+ return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${path2 ?? "*"}`;
724
639
  }
725
640
  function assertIncludeExcludeNoOverlap(include, exclude, label) {
726
641
  if (!include?.length || !exclude?.length) return;
@@ -782,45 +697,21 @@ function assertOverrideMechanismSupported(strict = false) {
782
697
  return false;
783
698
  }
784
699
  }
785
- function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
786
- if (res == null) {
700
+ function resolveRuleResult(res) {
701
+ if (res === void 0) {
787
702
  return { kind: "continue", responseHeaders: /* @__PURE__ */ new Map(), cookies: /* @__PURE__ */ new Map() };
788
703
  }
789
- if (!isNextResult(res) && !(res instanceof Response)) {
704
+ if (!(res instanceof Response)) {
790
705
  throw new TypeError(
791
- `[proxy-chain] rule must return next(), a Response, or undefined. Got ${typeof res}.`
706
+ `[proxy-chain] rule must return a Response or undefined. Got ${typeof res}.`
792
707
  );
793
708
  }
794
- if (isNextResult(res)) {
795
- let request;
796
- if (res.request) {
797
- const filtered = new Headers();
798
- const { dropped } = mergeRequestHeaderOverrides(
799
- filtered,
800
- headersInitToHeaders(res.request),
801
- requestHeaderPolicy
802
- );
803
- if (debug && dropped.length) {
804
- logger.warn({ dropped }, "blocked request header mutation");
805
- }
806
- if ([...filtered.keys()].length) request = filtered;
807
- }
808
- const headerInit = res.headers ? headersInitToHeaders(res.headers) : void 0;
809
- return {
810
- kind: "continue",
811
- request,
812
- responseHeaders: headerInit ? responseHeaderItems(headerInit) : /* @__PURE__ */ new Map(),
813
- cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
814
- };
815
- }
816
709
  if (res instanceof import_server.NextResponse && res.headers.get("x-middleware-next") === "1") {
817
710
  let request;
818
711
  const decoded = decodeOverriddenRequestHeaders(res.headers);
819
712
  const hasRequestOverride = res.headers.has("x-middleware-override-headers");
820
713
  if (hasRequestOverride) {
821
- const target = new Headers();
822
- mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
823
- request = target;
714
+ request = decoded;
824
715
  }
825
716
  return {
826
717
  kind: "continue",
@@ -836,9 +727,7 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
836
727
  const decoded = decodeOverriddenRequestHeaders(res.headers);
837
728
  const hasRequestOverride = res.headers.has("x-middleware-override-headers");
838
729
  if (hasRequestOverride) {
839
- const target = new Headers();
840
- mergeRequestHeaderOverrides(target, decoded, requestHeaderPolicy);
841
- request = target;
730
+ request = decoded;
842
731
  }
843
732
  return {
844
733
  kind: "continue",
@@ -1047,8 +936,11 @@ function safeLogger(logger) {
1047
936
  error: wrap("error")
1048
937
  };
1049
938
  }
1050
- function isNextResponse(value) {
1051
- return value instanceof import_server2.NextResponse && value.headers.get("x-middleware-next") === "1";
939
+ function isTerminalRecovery(value) {
940
+ return value instanceof Response && resolveRuleResult(value).kind === "stop";
941
+ }
942
+ function isContinuingRecovery(value) {
943
+ return value instanceof Response && resolveRuleResult(value).kind === "continue";
1052
944
  }
1053
945
  function stripRoutingOverrides(res) {
1054
946
  const plain = !(res instanceof import_server2.NextResponse);
@@ -1075,7 +967,6 @@ function resolveConfig(overrides) {
1075
967
  headerMergeStrategy: "last-write-wins",
1076
968
  debug: false,
1077
969
  timeout: 0,
1078
- requestHeaderPolicy: {},
1079
970
  strictOverrideCheck: false,
1080
971
  tracePath: true,
1081
972
  ...rest,
@@ -1094,7 +985,6 @@ function executeChain(options, entries) {
1094
985
  cookieMergeStrategy,
1095
986
  headerMergeStrategy,
1096
987
  timeout,
1097
- requestHeaderPolicy,
1098
988
  strictOverrideCheck
1099
989
  } = config;
1100
990
  const debug = debugLevel !== false;
@@ -1199,16 +1089,7 @@ function executeChain(options, entries) {
1199
1089
  return currentReq;
1200
1090
  }
1201
1091
  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
- }
1092
+ const merged = replaceRequestHeaders ? new Headers() : new Headers(currentReq.headers);
1212
1093
  pendingRequestOverrides.forEach((v, k) => {
1213
1094
  merged.set(k, v);
1214
1095
  });
@@ -1299,7 +1180,7 @@ function executeChain(options, entries) {
1299
1180
  (signal) => errorHandler(err, i, req2, contextFor(signal))
1300
1181
  );
1301
1182
  if (timeoutError || requestCancelled) {
1302
- if (recovered instanceof Response && !isNextResponse(recovered)) {
1183
+ if (isTerminalRecovery(recovered)) {
1303
1184
  const response2 = stripRoutingOverrides(recovered);
1304
1185
  headerWrites.push({
1305
1186
  ruleIndex: i,
@@ -1354,17 +1235,8 @@ function executeChain(options, entries) {
1354
1235
  if (recovered == null) {
1355
1236
  return stopFailure(errorPolicy);
1356
1237
  }
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 };
1238
+ if (isContinuingRecovery(recovered)) {
1239
+ return { raw: recovered, recovered: { durationMs, policy: errorPolicy, details } };
1368
1240
  }
1369
1241
  if (!(recovered instanceof Response)) {
1370
1242
  diagnostics?.push({
@@ -1473,6 +1345,7 @@ function executeChain(options, entries) {
1473
1345
  const effectiveTimeout = rule.timeout ?? timeout;
1474
1346
  let phase = rule.when ? "when" : "handler";
1475
1347
  let result;
1348
+ let recoveredRule;
1476
1349
  try {
1477
1350
  result = await runInExecutionScope(
1478
1351
  req.signal,
@@ -1514,17 +1387,19 @@ function executeChain(options, entries) {
1514
1387
  );
1515
1388
  if ("response" in recovered) return recovered.response;
1516
1389
  result = { kind: "result", raw: recovered.raw };
1390
+ recoveredRule = recovered.recovered;
1517
1391
  }
1518
1392
  let raw = result.raw;
1519
1393
  let duration2 = monotonicNow() - executionStartedAt;
1520
1394
  let outcome;
1521
1395
  try {
1522
- outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
1396
+ outcome = resolveRuleResult(raw);
1523
1397
  } catch (err) {
1524
1398
  const recovered = await recoverRuleError(err, i, label, activeReq, duration2, "result");
1525
1399
  if ("response" in recovered) return recovered.response;
1526
1400
  raw = recovered.raw;
1527
- outcome = resolveRuleResult(raw, requestHeaderPolicy, logger, debug);
1401
+ recoveredRule = recovered.recovered;
1402
+ outcome = resolveRuleResult(raw);
1528
1403
  }
1529
1404
  if (outcome.kind === "continue") {
1530
1405
  if (outcome.rewriteUrl) {
@@ -1545,7 +1420,16 @@ function executeChain(options, entries) {
1545
1420
  headerWrites.push({ ruleIndex: i, ruleName: label, items: outcome.responseHeaders });
1546
1421
  cookieWrites.push({ ruleIndex: i, ruleName: label, items: outcome.cookies });
1547
1422
  }
1548
- if (diagnostics?.at(-1)?.outcome !== "recovered") {
1423
+ if (recoveredRule) {
1424
+ diagnostics?.push({
1425
+ name: safeDiagnosticText(label, 64),
1426
+ outcome: "recovered",
1427
+ durationMs: recoveredRule.durationMs,
1428
+ recovery: outcome.rewriteUrl ? "rewrite" : "continue",
1429
+ policy: recoveredRule.policy,
1430
+ details: recoveredRule.details
1431
+ });
1432
+ } else {
1549
1433
  diagnostics?.push(
1550
1434
  outcome.rewriteUrl ? {
1551
1435
  name: safeDiagnosticText(label, 64),
@@ -1557,7 +1441,7 @@ function executeChain(options, entries) {
1557
1441
  } : {
1558
1442
  name: safeDiagnosticText(label, 64),
1559
1443
  outcome: "continue",
1560
- source: isNextResult(raw) ? "next()" : raw instanceof import_server2.NextResponse && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1444
+ source: raw instanceof import_server2.NextResponse && raw.headers.get("x-middleware-next") === "1" ? "NextResponse.next()" : "undefined",
1561
1445
  durationMs: duration2,
1562
1446
  details: handlerDetails(rule, timeout, "matched", "matched", "not-matched")
1563
1447
  }
@@ -1656,7 +1540,7 @@ function executeChain(options, entries) {
1656
1540
  req.signal,
1657
1541
  (signal) => config.onError(err, -1, materializeRequest(), contextFor(signal))
1658
1542
  );
1659
- if (recovered instanceof Response && !isNextResponse(recovered)) {
1543
+ if (isTerminalRecovery(recovered)) {
1660
1544
  const response = stripRoutingOverrides(recovered);
1661
1545
  return finish(
1662
1546
  finalizeResponse(
@@ -1681,47 +1565,28 @@ function executeChain(options, entries) {
1681
1565
  };
1682
1566
  }
1683
1567
 
1684
- // src/core/chain.ts
1685
- function isDefinedHandler(value) {
1686
- return typeof value === "object" && value !== null && value[DEFINED_HANDLER] === true;
1687
- }
1688
- function isScopeObject2(value) {
1689
- return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
1690
- }
1691
- function toFilter(scope) {
1692
- if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
1693
- return { include: scope };
1694
- }
1695
- function fromNative(handler) {
1696
- const run = (req, ctx, event) => handler(req, event, ctx);
1697
- const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
1698
- return { run, name };
1699
- }
1700
- function toEntry(entry) {
1701
- if (Array.isArray(entry)) {
1702
- const [target, scope] = entry;
1703
- const filter = toFilter(scope);
1704
- if (isDefinedHandler(target)) return withPaths(target, filter);
1705
- return withPaths(fromNative(target), filter);
1706
- }
1707
- if (isDefinedHandler(entry)) return entry;
1708
- if (typeof entry === "function") return fromNative(entry);
1709
- throw new TypeError(
1710
- "[proxy-chain] chain entries must be native handlers or defineHandler() results"
1711
- );
1712
- }
1713
- function chain(entries, options) {
1714
- const normalized = entries.map((entry) => toEntry(entry));
1715
- return executeChain(options ?? {}, normalized);
1716
- }
1717
-
1718
1568
  // src/core/handler.ts
1719
- function defineHandler(options) {
1569
+ function assertHandlerConfig(options) {
1570
+ if (!options || typeof options !== "object" || typeof options.name !== "string" || options.name.trim() === "" || typeof options.handle !== "function") {
1571
+ throw new TypeError("[proxy-chain] configured handlers require a non-empty name and handle");
1572
+ }
1573
+ if ("handler" in options) {
1574
+ throw new TypeError(
1575
+ "[proxy-chain] configured handler property 'handler' is unsupported; use 'handle'"
1576
+ );
1577
+ }
1578
+ if ("config" in options || "options" in options) {
1579
+ throw new TypeError("[proxy-chain] handler configuration must use top-level options");
1580
+ }
1720
1581
  assertValidTimeout(options.timeout);
1582
+ }
1583
+ function toHandlerRule(options) {
1584
+ assertHandlerConfig(options);
1585
+ const { handle } = options;
1721
1586
  const include = compileScopes(options.rules?.include);
1722
1587
  const exclude = compileScopes(options.rules?.exclude);
1723
- const rule = {
1724
- run: (request, context, event) => options.handler(request, event, context),
1588
+ return {
1589
+ run: (request, context, event) => handle(request, event, context),
1725
1590
  name: options.name,
1726
1591
  include,
1727
1592
  exclude,
@@ -1734,15 +1599,32 @@ function defineHandler(options) {
1734
1599
  exclude: options.rules?.exclude
1735
1600
  }
1736
1601
  };
1737
- return { ...rule, [DEFINED_HANDLER]: true };
1602
+ }
1603
+ function defineHandler(options) {
1604
+ assertHandlerConfig(options);
1605
+ return options;
1606
+ }
1607
+
1608
+ // src/core/chain.ts
1609
+ function fromNative(handle) {
1610
+ const run = (req, ctx, event) => handle(req, event, ctx);
1611
+ const name = handle.name && handle.name !== "proxy" ? handle.name : void 0;
1612
+ return { run, name };
1613
+ }
1614
+ function toEntry(entry) {
1615
+ if (typeof entry === "function") return fromNative(entry);
1616
+ if (Array.isArray(entry)) {
1617
+ throw new TypeError("[proxy-chain] tuple entries are not supported; use a configured handler");
1618
+ }
1619
+ if (entry && typeof entry === "object") return toHandlerRule(entry);
1620
+ throw new TypeError("[proxy-chain] chain entries must be native handlers or configured handlers");
1621
+ }
1622
+ function chain(entries, options) {
1623
+ const normalized = entries.map((entry) => toEntry(entry));
1624
+ return executeChain(options ?? {}, normalized);
1738
1625
  }
1739
1626
  // Annotate the CommonJS export names for ESM import in node:
1740
1627
  0 && (module.exports = {
1741
- RuleTimeoutError,
1742
1628
  chain,
1743
- defineHandler,
1744
- host,
1745
- isNextResult,
1746
- next,
1747
- path
1629
+ defineHandler
1748
1630
  });