@klnap/next-proxy-chain 1.0.3 → 1.0.5

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,44 +20,14 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- DEFAULT_BLOCKED_REQUEST_HEADERS: () => DEFAULT_BLOCKED_REQUEST_HEADERS,
24
- NEXT: () => NEXT,
25
23
  RuleTimeoutError: () => RuleTimeoutError,
26
- applyMergedToResponse: () => applyMergedToResponse,
27
- assertIncludeExcludeNoOverlap: () => assertIncludeExcludeNoOverlap,
28
- assertOverrideMechanismSupported: () => assertOverrideMechanismSupported,
29
- compileScopes: () => compileScopes,
30
- cookieItemsFromHeaders: () => cookieItemsFromHeaders,
31
- createConsoleLogger: () => createConsoleLogger,
32
24
  createProxyContext: () => createProxyContext,
33
- decodeOverriddenRequestHeaders: () => decodeOverriddenRequestHeaders,
34
25
  defineProxy: () => defineProxy,
35
- finalizeResponse: () => finalizeResponse,
36
- formatPipelineLine: () => formatPipelineLine,
37
- headersDiffer: () => headersDiffer,
38
- headersInitToHeaders: () => headersInitToHeaders,
39
26
  host: () => host,
40
27
  isNextResult: () => isNextResult,
41
- isRequestHeaderAllowed: () => isRequestHeaderAllowed,
42
- listSetCookie: () => listSetCookie,
43
- mergeRequestHeaderOverrides: () => mergeRequestHeaderOverrides,
44
- mergeWrites: () => mergeWrites,
45
28
  next: () => next,
46
- normalizeHost: () => normalizeHost,
47
- parseCookieName: () => parseCookieName,
48
29
  path: () => path,
49
- pathMatches: () => pathMatches,
50
- proxyChain: () => proxyChain,
51
- resolveRuleResult: () => resolveRuleResult,
52
- responseHeaderItems: () => responseHeaderItems,
53
- ruleLabel: () => ruleLabel,
54
- ruleMatches: () => ruleMatches,
55
- safeInternalError: () => safeInternalError,
56
- toPathRegex: () => toPathRegex,
57
- toRule: () => toRule,
58
- toStatelessRegExp: () => toStatelessRegExp,
59
- withPaths: () => withPaths,
60
- withRuleTimeout: () => withRuleTimeout
30
+ proxyChain: () => proxyChain
61
31
  });
62
32
  module.exports = __toCommonJS(index_exports);
63
33
 
@@ -84,177 +54,21 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
84
54
  "x-middleware-override-headers"
85
55
  ]);
86
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
+
87
65
  // src/core/context.ts
88
66
  function createProxyContext() {
89
67
  return /* @__PURE__ */ new Map();
90
68
  }
91
69
 
92
- // src/core/matching.ts
93
- var RESERVED_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
94
- function extractMeaningfulName(value) {
95
- if (!value || RESERVED_FN_NAMES.has(value)) return void 0;
96
- return value;
97
- }
98
- function toStatelessRegExp(re) {
99
- const flags = re.flags.replace(/[gy]/g, "");
100
- return flags === re.flags ? re : new RegExp(re.source, flags);
101
- }
102
- function escapeRegex(value) {
103
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
104
- }
105
- function host(matcher) {
106
- const list = Array.isArray(matcher) ? matcher : [matcher];
107
- const parts = list.map((m) => {
108
- if (m instanceof RegExp) return `(?:${toStatelessRegExp(m).source})`;
109
- return `(?:${escapeRegex(m.toLowerCase())})`;
110
- });
111
- return toStatelessRegExp(new RegExp(`^(?:${parts.join("|")})$`, "i"));
112
- }
113
- function isScopeObject(value) {
114
- return "host" in value || "path" in value;
115
- }
116
- function segmentToRegex(segment) {
117
- if (segment === "**") return "(?:.*)";
118
- if (segment === "*") return "[^/]+";
119
- if (segment.startsWith(":")) return "[^/]+";
120
- return escapeRegex(segment);
121
- }
122
- function path(pattern, options = {}) {
123
- const { locales = [] } = options;
124
- const localePrefix = locales.length > 0 ? `(?:(?:${locales.map(escapeRegex).join("|")})\\/)?` : "";
125
- if (pattern instanceof RegExp) {
126
- const body2 = pattern.source.replace(/^\^/, "").replace(/\$$/, "");
127
- const needsStart = !pattern.source.startsWith("^");
128
- const needsEnd = !pattern.source.endsWith("$");
129
- return toStatelessRegExp(
130
- new RegExp(
131
- `${needsStart ? "^" : ""}${localePrefix ? `/${localePrefix}` : ""}${body2}${needsEnd ? "$" : ""}`,
132
- pattern.flags
133
- )
134
- );
135
- }
136
- const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
137
- const segments = normalized.slice(1).split("/");
138
- const trailingStar = segments.length > 0 && segments[segments.length - 1] === "*";
139
- const suffix = trailingStar ? "(?:\\/.*)?$" : "$";
140
- const body = trailingStar ? segments.slice(0, -1).map(segmentToRegex).concat("[^/]+").join("\\/") : segments.map(segmentToRegex).join("\\/");
141
- return new RegExp(`^/${localePrefix}${body}${suffix}`);
142
- }
143
- function toPathRegex(matcher, options) {
144
- const list = Array.isArray(matcher) ? matcher : [matcher];
145
- const regexes = list.map((m) => path(m, options));
146
- if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
147
- return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
148
- }
149
- function compileScopes(input, pathOptions) {
150
- if (input == null) return void 0;
151
- const list = Array.isArray(input) ? input : [input];
152
- const compilePath = (matcher) => {
153
- if (Array.isArray(matcher)) {
154
- const parts = matcher.map(
155
- (m) => typeof m === "string" ? path(m, pathOptions) : toStatelessRegExp(m)
156
- );
157
- if (parts.length === 1) return parts[0];
158
- return toStatelessRegExp(new RegExp(`(?:${parts.map((r) => `(?:${r.source})`).join("|")})`));
159
- }
160
- return typeof matcher === "string" ? path(matcher, pathOptions) : toStatelessRegExp(matcher);
161
- };
162
- const compiled = [];
163
- for (const item of list) {
164
- if (typeof item === "string" || item instanceof RegExp) {
165
- compiled.push({ path: compilePath(item) });
166
- continue;
167
- }
168
- if (item && typeof item === "object" && isScopeObject(item)) {
169
- if (item.host == null && item.path == null) {
170
- throw new Error("[proxy-chain] scope needs at least `host` or `path`");
171
- }
172
- compiled.push({
173
- host: item.host != null ? host(item.host) : void 0,
174
- path: item.path != null ? compilePath(item.path) : void 0
175
- });
176
- continue;
177
- }
178
- throw new Error("[proxy-chain] invalid include/exclude scope");
179
- }
180
- return compiled;
181
- }
182
- function scopeMatches(pathname, hostname, scope) {
183
- if (scope.host) {
184
- if (!hostname || !scope.host.test(hostname)) return false;
185
- }
186
- if (scope.path) {
187
- if (!scope.path.test(pathname)) return false;
188
- }
189
- return true;
190
- }
191
- function toRule(entry) {
192
- if (typeof entry === "function") {
193
- const name2 = extractMeaningfulName(entry.name);
194
- return name2 ? { run: entry, name: name2 } : { run: entry };
195
- }
196
- const rule = entry;
197
- const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
198
- const name = extractMeaningfulName(rule.name) ?? runName;
199
- const harden = (scopes) => scopes?.map((s) => ({
200
- host: s.host ? toStatelessRegExp(s.host) : void 0,
201
- path: s.path ? toStatelessRegExp(s.path) : void 0
202
- }));
203
- return {
204
- ...rule,
205
- name: name ?? void 0,
206
- include: harden(rule.include),
207
- exclude: harden(rule.exclude)
208
- };
209
- }
210
- function ruleLabel(rule, index) {
211
- const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
212
- return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
213
- }
214
- function withPaths(entry, filter) {
215
- const base = toRule(entry);
216
- const opts = filter.pathOptions;
217
- const include = compileScopes(filter.include, opts);
218
- const exclude = compileScopes(filter.exclude, opts);
219
- const name = filter.name ?? base.name;
220
- assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
221
- return { run: base.run, include, exclude, name };
222
- }
223
- function ruleMatches(pathname, hostname, rule) {
224
- if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
225
- if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
226
- return false;
227
- }
228
- return true;
229
- }
230
- function pathMatches(pathname, rule) {
231
- return ruleMatches(pathname, null, rule);
232
- }
233
- function normalizeHost(raw) {
234
- if (!raw) return null;
235
- const first = raw.split(",")[0]?.trim().toLowerCase();
236
- if (!first) return null;
237
- if (first.startsWith("[")) {
238
- const end = first.indexOf("]");
239
- return end === -1 ? first : first.slice(1, end);
240
- }
241
- const withoutPort = first.replace(/:\d+$/, "");
242
- return withoutPort || null;
243
- }
244
- function scopeKey(scope) {
245
- return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
246
- }
247
- function assertIncludeExcludeNoOverlap(include, exclude, label) {
248
- if (!include?.length || !exclude?.length) return;
249
- const excluded = new Set(exclude.map(scopeKey));
250
- for (const scope of include) {
251
- if (excluded.has(scopeKey(scope))) {
252
- throw new Error(
253
- `[proxy-chain] ${label}: include and exclude share an identical scope. Remove one.`
254
- );
255
- }
256
- }
257
- }
70
+ // src/core/engine.ts
71
+ var import_server2 = require("next/server");
258
72
 
259
73
  // src/core/headers.ts
260
74
  function normalizeHeaderName(name) {
@@ -298,15 +112,32 @@ function parseCookieName(setCookie) {
298
112
  return (eq === -1 ? setCookie : setCookie.slice(0, eq)).trim();
299
113
  }
300
114
  function listSetCookie(headers) {
301
- const extended = headers;
302
- if (typeof extended.getSetCookie === "function") return extended.getSetCookie();
115
+ if (typeof headers.getSetCookie === "function") return headers.getSetCookie();
303
116
  const single = headers.get("set-cookie");
304
117
  return single ? [single] : [];
305
118
  }
119
+ function cookieAttribute(setCookie, name) {
120
+ const parts = setCookie.split(";");
121
+ for (let i = 1; i < parts.length; i++) {
122
+ const piece = parts[i];
123
+ if (!piece) continue;
124
+ const eq = piece.indexOf("=");
125
+ const key = (eq === -1 ? piece : piece.slice(0, eq)).trim().toLowerCase();
126
+ if (key !== name) continue;
127
+ return (eq === -1 ? "" : piece.slice(eq + 1)).trim();
128
+ }
129
+ return "";
130
+ }
131
+ function cookieIdentityKey(setCookie) {
132
+ const name = parseCookieName(setCookie);
133
+ const path2 = cookieAttribute(setCookie, "path");
134
+ const domain = cookieAttribute(setCookie, "domain").toLowerCase();
135
+ return `${name};domain=${domain};path=${path2}`;
136
+ }
306
137
  function cookieItemsFromHeaders(headers) {
307
138
  const map = /* @__PURE__ */ new Map();
308
139
  for (const value of listSetCookie(headers)) {
309
- map.set(parseCookieName(value), value);
140
+ map.set(cookieIdentityKey(value), value);
310
141
  }
311
142
  return map;
312
143
  }
@@ -366,7 +197,12 @@ function mergeWrites(writes, strategy, onConflict) {
366
197
  }
367
198
  return resolved;
368
199
  }
369
- function applyMergedToResponse(res, headers, cookies) {
200
+ function applyMergedToResponse(res, headers, cookies, dropHeaders) {
201
+ if (dropHeaders) {
202
+ for (const key of dropHeaders) {
203
+ if (!headers.has(key)) res.headers.delete(key);
204
+ }
205
+ }
370
206
  for (const [key, value] of headers) {
371
207
  res.headers.set(key, value);
372
208
  }
@@ -376,12 +212,24 @@ function applyMergedToResponse(res, headers, cookies) {
376
212
  }
377
213
  }
378
214
 
379
- // src/core/actions.ts
380
- function next(options = {}) {
381
- return { [NEXT]: true, ...options };
215
+ // src/core/host-folder-prefix.ts
216
+ function physicalFolderPrefix(raw) {
217
+ return "/" + raw.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
382
218
  }
383
- function isNextResult(value) {
384
- return typeof value === "object" && value !== null && NEXT in value;
219
+ function applyFolderPrefix(rewriteUrl, folder, baseUrl) {
220
+ try {
221
+ const parsed = new URL(rewriteUrl, baseUrl);
222
+ if (!parsed.pathname.startsWith(folder)) {
223
+ parsed.pathname = folder + (parsed.pathname === "/" ? "" : parsed.pathname);
224
+ return parsed.toString();
225
+ }
226
+ return rewriteUrl;
227
+ } catch {
228
+ if (!rewriteUrl.startsWith(folder)) {
229
+ return folder + (rewriteUrl === "/" ? "" : rewriteUrl);
230
+ }
231
+ return rewriteUrl;
232
+ }
385
233
  }
386
234
 
387
235
  // src/core/logger.ts
@@ -427,27 +275,180 @@ function formatPipelineLine(input) {
427
275
  }
428
276
  }
429
277
 
430
- // src/core/timeout.ts
431
- var RuleTimeoutError = class extends Error {
432
- ruleName;
433
- timeoutMs;
434
- constructor(ruleName, timeoutMs) {
435
- super(`[proxy-chain] ${ruleName} timed out after ${timeoutMs}ms`);
436
- this.name = "RuleTimeoutError";
437
- this.ruleName = ruleName;
438
- this.timeoutMs = timeoutMs;
439
- }
440
- };
441
- async function withRuleTimeout(promise, timeoutMs, ruleName) {
442
- if (!timeoutMs || timeoutMs <= 0) return promise;
443
- let timer;
444
- const timeout = new Promise((_, reject) => {
445
- timer = setTimeout(() => reject(new RuleTimeoutError(ruleName, timeoutMs)), timeoutMs);
278
+ // src/core/matching.ts
279
+ var RESERVED_FN_NAMES = /* @__PURE__ */ new Set(["", "proxy", "anonymous", "run", "next"]);
280
+ function extractMeaningfulName(value) {
281
+ if (!value || RESERVED_FN_NAMES.has(value)) return void 0;
282
+ return value;
283
+ }
284
+ function toStatelessRegExp(re) {
285
+ const flags = re.flags.replace(/[gy]/g, "");
286
+ return flags === re.flags ? re : new RegExp(re.source, flags);
287
+ }
288
+ function escapeRegex(value) {
289
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
290
+ }
291
+ function hostGlobToRegex(value) {
292
+ return escapeRegex(value.toLowerCase()).replace(/\\\*/g, "[^.]+");
293
+ }
294
+ function host(matcher) {
295
+ const list = Array.isArray(matcher) ? matcher : [matcher];
296
+ const parts = list.map((m) => {
297
+ if (m instanceof RegExp) return `(?:${toStatelessRegExp(m).source})`;
298
+ return `(?:${hostGlobToRegex(m)})`;
446
299
  });
447
- try {
448
- return await Promise.race([promise, timeout]);
449
- } finally {
450
- if (timer !== void 0) clearTimeout(timer);
300
+ return toStatelessRegExp(new RegExp(`^(?:${parts.join("|")})$`, "i"));
301
+ }
302
+ function isScopeObject(value) {
303
+ return "host" in value || "path" in value;
304
+ }
305
+ function segmentToRegex(segment) {
306
+ if (segment === "**") return "(?:.*)";
307
+ if (segment === "*") return "[^/]+";
308
+ if (segment.startsWith(":")) return "[^/]+";
309
+ return escapeRegex(segment);
310
+ }
311
+ function hasEndAnchor(source) {
312
+ if (!source.endsWith("$")) return false;
313
+ let slashes = 0;
314
+ for (let i = source.length - 2; i >= 0 && source[i] === "\\"; i--) slashes++;
315
+ return slashes % 2 === 0;
316
+ }
317
+ function compileRegexPath(pattern) {
318
+ let source = pattern.source;
319
+ const hasStart = source.startsWith("^");
320
+ const hasEnd = hasEndAnchor(source);
321
+ if (hasStart) source = source.slice(1);
322
+ if (hasEnd) source = source.slice(0, -1);
323
+ const wrapFull = !hasStart && !hasEnd;
324
+ const start = hasStart || wrapFull ? "^" : "";
325
+ const end = hasEnd || wrapFull ? "$" : "";
326
+ return toStatelessRegExp(new RegExp(`${start}${source}${end}`, pattern.flags));
327
+ }
328
+ function compileStringPath(pattern) {
329
+ const normalized = (pattern.startsWith("/") ? pattern : `/${pattern}`).replace(/\/$/, "") || "/";
330
+ const segments = normalized === "/" ? [] : normalized.slice(1).split("/");
331
+ const last = segments[segments.length - 1];
332
+ const trailingStar = last === "*";
333
+ const trailingGlobstar = last === "**";
334
+ let pathPattern;
335
+ if (normalized === "/") {
336
+ pathPattern = "/";
337
+ } else if (trailingStar) {
338
+ const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
339
+ pathPattern = prefix ? `/${prefix}/[^/]+` : `/[^/]+`;
340
+ } else if (trailingGlobstar) {
341
+ const prefix = segments.slice(0, -1).map(segmentToRegex).join("/");
342
+ pathPattern = prefix ? `/${prefix}(?:/.*)?` : `/(?:.*)?`;
343
+ } else {
344
+ pathPattern = `/${segments.map(segmentToRegex).join("/")}`;
345
+ }
346
+ return new RegExp(`^${pathPattern}$`);
347
+ }
348
+ function path(pattern) {
349
+ if (pattern instanceof RegExp) return compileRegexPath(pattern);
350
+ return compileStringPath(pattern);
351
+ }
352
+ function toPathRegex(matcher) {
353
+ const list = Array.isArray(matcher) ? matcher : [matcher];
354
+ const regexes = list.map((m) => path(m));
355
+ if (regexes.length === 1) return toStatelessRegExp(regexes[0]);
356
+ return toStatelessRegExp(new RegExp(`(?:${regexes.map((r) => `(?:${r.source})`).join("|")})`));
357
+ }
358
+ function compileScopes(input) {
359
+ if (input == null) return void 0;
360
+ const list = Array.isArray(input) ? input : [input];
361
+ const compilePath = (matcher) => toPathRegex(matcher);
362
+ const compiled = [];
363
+ for (const item of list) {
364
+ if (typeof item === "string" || item instanceof RegExp) {
365
+ compiled.push({ path: compilePath(item) });
366
+ continue;
367
+ }
368
+ if (item && typeof item === "object" && isScopeObject(item)) {
369
+ if (item.host == null && item.path == null) {
370
+ throw new Error("[proxy-chain] scope needs at least `host` or `path`");
371
+ }
372
+ compiled.push({
373
+ host: item.host != null ? host(item.host) : void 0,
374
+ path: item.path != null ? compilePath(item.path) : void 0
375
+ });
376
+ continue;
377
+ }
378
+ throw new Error("[proxy-chain] invalid include/exclude scope");
379
+ }
380
+ return compiled;
381
+ }
382
+ function scopeMatches(pathname, hostname, scope) {
383
+ if (scope.host) {
384
+ if (!hostname || !scope.host.test(hostname)) return false;
385
+ }
386
+ if (scope.path) {
387
+ if (!scope.path.test(pathname)) return false;
388
+ }
389
+ return true;
390
+ }
391
+ function toRule(entry) {
392
+ if (typeof entry === "function") {
393
+ const name2 = extractMeaningfulName(entry.name);
394
+ return name2 ? { run: entry, name: name2 } : { run: entry };
395
+ }
396
+ const rule = entry;
397
+ const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
398
+ const name = extractMeaningfulName(rule.name) ?? runName;
399
+ const harden = (scopes) => scopes?.map((s) => ({
400
+ host: s.host ? toStatelessRegExp(s.host) : void 0,
401
+ path: s.path ? toStatelessRegExp(s.path) : void 0
402
+ }));
403
+ return {
404
+ ...rule,
405
+ name: name ?? void 0,
406
+ include: harden(rule.include),
407
+ exclude: harden(rule.exclude)
408
+ };
409
+ }
410
+ function ruleLabel(rule, index) {
411
+ const runName = typeof rule.run === "function" ? extractMeaningfulName(rule.run.name) : void 0;
412
+ return extractMeaningfulName(rule.name) ?? runName ?? `rule#${index}`;
413
+ }
414
+ function withPaths(entry, filter) {
415
+ const base = toRule(entry);
416
+ const include = compileScopes(filter.include);
417
+ const exclude = compileScopes(filter.exclude);
418
+ const name = filter.name ?? base.name;
419
+ assertIncludeExcludeNoOverlap(include, exclude, name ?? "proxy");
420
+ return { run: base.run, include, exclude, name };
421
+ }
422
+ function ruleMatches(pathname, hostname, rule) {
423
+ if (rule.exclude?.some((scope) => scopeMatches(pathname, hostname, scope))) return false;
424
+ if (rule.include && !rule.include.some((scope) => scopeMatches(pathname, hostname, scope))) {
425
+ return false;
426
+ }
427
+ return true;
428
+ }
429
+ function normalizeHost(raw) {
430
+ if (!raw) return null;
431
+ const first = raw.split(",")[0]?.trim().toLowerCase();
432
+ if (!first) return null;
433
+ if (first.startsWith("[")) {
434
+ const end = first.indexOf("]");
435
+ return end === -1 ? first : first.slice(1, end);
436
+ }
437
+ const withoutPort = first.replace(/:\d+$/, "");
438
+ return withoutPort || null;
439
+ }
440
+ function scopeKey(scope) {
441
+ return `${scope.host?.source ?? "*"}::${scope.host?.flags ?? ""}|${scope.path?.source ?? "*"}::${scope.path?.flags ?? ""}`;
442
+ }
443
+ function assertIncludeExcludeNoOverlap(include, exclude, label) {
444
+ if (!include?.length || !exclude?.length) return;
445
+ const excluded = new Set(exclude.map(scopeKey));
446
+ for (const scope of include) {
447
+ if (excluded.has(scopeKey(scope))) {
448
+ throw new Error(
449
+ `[proxy-chain] ${label}: include and exclude share an identical scope. Remove one.`
450
+ );
451
+ }
451
452
  }
452
453
  }
453
454
 
@@ -459,26 +460,42 @@ function safeInternalError() {
459
460
  headers: { "content-type": "text/plain; charset=utf-8" }
460
461
  });
461
462
  }
462
- var cachedOverrideSupported = null;
463
+ var UNSUPPORTED_OVERRIDE_MSG = "[proxy-chain] Warning: platform NextResponse.next() does not support x-middleware-next header overrides.";
464
+ var VERIFY_OVERRIDE_MSG = "[proxy-chain] Warning: unable to verify NextResponse request override mechanism.";
465
+ var cachedOverrideProbe = null;
466
+ var overrideProbeForTests = null;
467
+ function runOverrideProbe() {
468
+ if (overrideProbeForTests) return overrideProbeForTests();
469
+ const testRes = import_server.NextResponse.next({
470
+ request: { headers: new Headers({ "x-proxy-chain-probe": "1" }) }
471
+ });
472
+ return testRes.headers.get("x-middleware-next") === "1";
473
+ }
474
+ function throwForCachedProbe(probe) {
475
+ if (probe.kind === "unsupported") throw new Error(UNSUPPORTED_OVERRIDE_MSG);
476
+ throw probe.err instanceof Error ? probe.err : new Error(VERIFY_OVERRIDE_MSG);
477
+ }
478
+ function resolveCachedProbe(probe, strict) {
479
+ if (probe.kind === "supported") return true;
480
+ if (strict) throwForCachedProbe(probe);
481
+ return false;
482
+ }
463
483
  function assertOverrideMechanismSupported(strict = false) {
464
- if (cachedOverrideSupported !== null) return cachedOverrideSupported;
484
+ if (cachedOverrideProbe !== null) return resolveCachedProbe(cachedOverrideProbe, strict);
465
485
  try {
466
- const testRes = import_server.NextResponse.next({
467
- request: { headers: new Headers({ "x-proxy-chain-probe": "1" }) }
468
- });
469
- const isSupported = testRes.headers.get("x-middleware-next") === "1";
470
- cachedOverrideSupported = isSupported;
471
- if (!isSupported) {
472
- const msg = "[proxy-chain] Warning: platform NextResponse.next() does not support x-middleware-next header overrides.";
473
- if (strict) throw new Error(msg);
474
- console.warn(msg);
486
+ const isSupported = runOverrideProbe();
487
+ if (isSupported) {
488
+ cachedOverrideProbe = { kind: "supported" };
489
+ return true;
475
490
  }
476
- return isSupported;
491
+ cachedOverrideProbe = { kind: "unsupported" };
492
+ if (strict) throw new Error(UNSUPPORTED_OVERRIDE_MSG);
493
+ console.warn(UNSUPPORTED_OVERRIDE_MSG);
494
+ return false;
477
495
  } catch (err) {
478
- cachedOverrideSupported = false;
479
- const msg = "[proxy-chain] Warning: unable to verify NextResponse request override mechanism.";
480
- if (strict) throw err instanceof Error ? err : new Error(msg);
481
- console.warn(msg, err);
496
+ cachedOverrideProbe = { kind: "error", err };
497
+ if (strict) throw err instanceof Error ? err : new Error(VERIFY_OVERRIDE_MSG);
498
+ console.warn(VERIFY_OVERRIDE_MSG, err);
482
499
  return false;
483
500
  }
484
501
  }
@@ -500,11 +517,12 @@ function resolveRuleResult(res, requestHeaderPolicy, logger, debug) {
500
517
  }
501
518
  if ([...filtered.keys()].length) request = filtered;
502
519
  }
520
+ const headerInit = res.headers ? headersInitToHeaders(res.headers) : void 0;
503
521
  return {
504
522
  kind: "continue",
505
523
  request,
506
- responseHeaders: res.headers ? responseHeaderItems(headersInitToHeaders(res.headers)) : /* @__PURE__ */ new Map(),
507
- cookies: /* @__PURE__ */ new Map()
524
+ responseHeaders: headerInit ? responseHeaderItems(headerInit) : /* @__PURE__ */ new Map(),
525
+ cookies: headerInit ? cookieItemsFromHeaders(headerInit) : /* @__PURE__ */ new Map()
508
526
  };
509
527
  }
510
528
  if (res.headers.get("x-middleware-next") === "1") {
@@ -548,16 +566,57 @@ function finalizeResponse(res, headerWrites, cookieWrites, headerStrategy, cooki
548
566
  const cookies = mergeWrites(cookieWrites, cookieStrategy, (key, winner, loser) => {
549
567
  if (debug) logger.debug({ cookie: key, winner, loser }, "cookie conflict resolved");
550
568
  });
551
- applyMergedToResponse(res, headers, cookies);
569
+ const seenHeaders = /* @__PURE__ */ new Set();
570
+ for (const write of headerWrites) {
571
+ for (const key of write.items.keys()) seenHeaders.add(key);
572
+ }
573
+ const dropHeaders = [];
574
+ for (const key of seenHeaders) {
575
+ if (!headers.has(key)) dropHeaders.push(key);
576
+ }
577
+ applyMergedToResponse(res, headers, cookies, dropHeaders);
552
578
  return res;
553
579
  }
554
580
 
581
+ // src/core/timeout.ts
582
+ var RuleTimeoutError = class extends Error {
583
+ ruleName;
584
+ timeoutMs;
585
+ constructor(ruleName, timeoutMs) {
586
+ super(`[proxy-chain] ${ruleName} timed out after ${timeoutMs}ms`);
587
+ this.name = "RuleTimeoutError";
588
+ this.ruleName = ruleName;
589
+ this.timeoutMs = timeoutMs;
590
+ }
591
+ };
592
+ function assertFiniteRuleTimeoutMs(ruleTimeoutMs) {
593
+ if (ruleTimeoutMs != null && !Number.isFinite(ruleTimeoutMs)) {
594
+ throw new RangeError(
595
+ `[proxy-chain] ruleTimeoutMs must be a finite positive number, got ${ruleTimeoutMs}`
596
+ );
597
+ }
598
+ }
599
+ async function withRuleTimeout(promise, timeoutMs, ruleName) {
600
+ assertFiniteRuleTimeoutMs(timeoutMs);
601
+ if (timeoutMs == null || timeoutMs <= 0) return promise;
602
+ let timer;
603
+ const timeout = new Promise((_, reject) => {
604
+ timer = setTimeout(() => reject(new RuleTimeoutError(ruleName, timeoutMs)), timeoutMs);
605
+ });
606
+ try {
607
+ return await Promise.race([promise, timeout]);
608
+ } finally {
609
+ if (timer !== void 0) clearTimeout(timer);
610
+ void promise.catch(() => {
611
+ });
612
+ }
613
+ }
614
+
555
615
  // src/core/engine.ts
556
- var import_server2 = require("next/server");
557
616
  function isPathFilter(value) {
558
617
  if (value === null || typeof value !== "object") return false;
559
618
  if ("nextUrl" in value) return false;
560
- return "include" in value || "exclude" in value || "name" in value || "pathOptions" in value;
619
+ return "include" in value || "exclude" in value || "name" in value;
561
620
  }
562
621
  function defineProxy(nameOrRun, maybeRun) {
563
622
  const defaultName = typeof nameOrRun === "string" ? nameOrRun : void 0;
@@ -577,25 +636,29 @@ function defineProxy(nameOrRun, maybeRun) {
577
636
  });
578
637
  return proxy;
579
638
  }
580
- function resolveConfig(overrides = {}) {
581
- const { logger, debug, ...rest } = overrides;
582
- return {
583
- createContext: () => createProxyContext(),
639
+ function resolveConfig(overrides, fallbackCreateContext) {
640
+ const { logger, debug, createContext, ...rest } = overrides;
641
+ const config = {
642
+ createContext: createContext ?? fallbackCreateContext,
584
643
  cookieMergeStrategy: "last-write-wins",
585
644
  headerMergeStrategy: "last-write-wins",
586
645
  debug: false,
587
646
  ruleTimeoutMs: 0,
588
647
  requestHeaderPolicy: {},
589
648
  strictOverrideCheck: false,
649
+ hostFolderHeader: void 0,
590
650
  ...rest,
591
651
  ...debug !== void 0 ? { debug } : {},
592
652
  logger: logger ?? createConsoleLogger(debug ? "debug" : "info")
593
653
  };
654
+ assertFiniteRuleTimeoutMs(config.ruleTimeoutMs);
655
+ return config;
594
656
  }
595
657
  function proxyChain(optionsOrEntries, maybeEntries) {
596
658
  const options = Array.isArray(optionsOrEntries) ? {} : optionsOrEntries;
597
- const entries = Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries;
598
- const config = resolveConfig(options);
659
+ const entries = (Array.isArray(optionsOrEntries) ? optionsOrEntries : maybeEntries) ?? [];
660
+ const fallbackCreateContext = createProxyContext;
661
+ const config = resolveConfig(options, fallbackCreateContext);
599
662
  const rules = entries.map(toRule);
600
663
  const {
601
664
  logger,
@@ -604,7 +667,8 @@ function proxyChain(optionsOrEntries, maybeEntries) {
604
667
  headerMergeStrategy,
605
668
  ruleTimeoutMs,
606
669
  requestHeaderPolicy,
607
- strictOverrideCheck
670
+ strictOverrideCheck,
671
+ hostFolderHeader
608
672
  } = config;
609
673
  assertOverrideMechanismSupported(strictOverrideCheck);
610
674
  for (let i = 0; i < rules.length; i++) {
@@ -670,7 +734,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
670
734
  if (config.onError) {
671
735
  try {
672
736
  const recovered = await config.onError(err, i, activeReq, ctx);
673
- if (recovered == null) continue;
737
+ if (recovered == null) return safeInternalError();
674
738
  if (isNextResult(recovered)) {
675
739
  raw = recovered;
676
740
  } else if (recovered instanceof Response) {
@@ -709,7 +773,7 @@ function proxyChain(optionsOrEntries, maybeEntries) {
709
773
  debug
710
774
  );
711
775
  } else {
712
- continue;
776
+ return safeInternalError();
713
777
  }
714
778
  } catch (onErrorErr) {
715
779
  logger.error({ rule: label, err: onErrorErr }, "onError handler threw");
@@ -725,6 +789,9 @@ function proxyChain(optionsOrEntries, maybeEntries) {
725
789
  if (outcome.kind === "continue") {
726
790
  if (outcome.rewriteUrl) {
727
791
  pendingRewriteUrl = outcome.rewriteUrl;
792
+ if (currentReq === req) {
793
+ currentReq = new import_server2.NextRequest(currentReq);
794
+ }
728
795
  try {
729
796
  const parsed = new URL(outcome.rewriteUrl);
730
797
  currentReq.nextUrl.pathname = parsed.pathname;
@@ -777,24 +844,14 @@ function proxyChain(optionsOrEntries, maybeEntries) {
777
844
  })
778
845
  );
779
846
  }
780
- const internalFolder = appliedRequestOverrides.get("x-internal-host-folder");
847
+ const internalFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
781
848
  if (internalFolder && outcome.response.headers.has("x-middleware-rewrite")) {
782
849
  const rawRewrite = outcome.response.headers.get("x-middleware-rewrite");
783
- const cleanFolder = "/" + internalFolder.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
784
- try {
785
- const parsed = new URL(rawRewrite, currentReq.url);
786
- if (!parsed.pathname.startsWith(cleanFolder)) {
787
- parsed.pathname = cleanFolder + (parsed.pathname === "/" ? "" : parsed.pathname);
788
- outcome.response.headers.set("x-middleware-rewrite", parsed.toString());
789
- }
790
- } catch {
791
- if (!rawRewrite.startsWith(cleanFolder)) {
792
- outcome.response.headers.set(
793
- "x-middleware-rewrite",
794
- cleanFolder + (rawRewrite === "/" ? "" : rawRewrite)
795
- );
796
- }
797
- }
850
+ const cleanFolder = physicalFolderPrefix(internalFolder);
851
+ outcome.response.headers.set(
852
+ "x-middleware-rewrite",
853
+ applyFolderPrefix(rawRewrite, cleanFolder, currentReq.url)
854
+ );
798
855
  }
799
856
  return finalizeResponse(
800
857
  outcome.response,
@@ -807,22 +864,12 @@ function proxyChain(optionsOrEntries, maybeEntries) {
807
864
  );
808
865
  }
809
866
  const finalReq = materializeRequest();
810
- const internalHostFolder = appliedRequestOverrides.get("x-internal-host-folder");
867
+ const internalHostFolder = hostFolderHeader ? appliedRequestOverrides.get(hostFolderHeader) : null;
811
868
  let finalRewriteUrl = pendingRewriteUrl;
812
869
  if (internalHostFolder) {
813
- const cleanFolder = "/" + internalHostFolder.replace(/^\/+|\/+$/g, "").split("/").filter((seg) => !/^\(.*\)$/.test(seg)).join("/");
870
+ const cleanFolder = physicalFolderPrefix(internalHostFolder);
814
871
  if (finalRewriteUrl) {
815
- try {
816
- const parsed = new URL(finalRewriteUrl, finalReq.url);
817
- if (!parsed.pathname.startsWith(cleanFolder)) {
818
- parsed.pathname = cleanFolder + (parsed.pathname === "/" ? "" : parsed.pathname);
819
- finalRewriteUrl = parsed.toString();
820
- }
821
- } catch {
822
- if (!finalRewriteUrl.startsWith(cleanFolder)) {
823
- finalRewriteUrl = cleanFolder + (finalRewriteUrl === "/" ? "" : finalRewriteUrl);
824
- }
825
- }
872
+ finalRewriteUrl = applyFolderPrefix(finalRewriteUrl, cleanFolder, finalReq.url);
826
873
  } else {
827
874
  const currentPath = finalReq.nextUrl.pathname;
828
875
  if (!currentPath.startsWith(cleanFolder)) {
@@ -863,42 +910,12 @@ function proxyChain(optionsOrEntries, maybeEntries) {
863
910
  }
864
911
  // Annotate the CommonJS export names for ESM import in node:
865
912
  0 && (module.exports = {
866
- DEFAULT_BLOCKED_REQUEST_HEADERS,
867
- NEXT,
868
913
  RuleTimeoutError,
869
- applyMergedToResponse,
870
- assertIncludeExcludeNoOverlap,
871
- assertOverrideMechanismSupported,
872
- compileScopes,
873
- cookieItemsFromHeaders,
874
- createConsoleLogger,
875
914
  createProxyContext,
876
- decodeOverriddenRequestHeaders,
877
915
  defineProxy,
878
- finalizeResponse,
879
- formatPipelineLine,
880
- headersDiffer,
881
- headersInitToHeaders,
882
916
  host,
883
917
  isNextResult,
884
- isRequestHeaderAllowed,
885
- listSetCookie,
886
- mergeRequestHeaderOverrides,
887
- mergeWrites,
888
918
  next,
889
- normalizeHost,
890
- parseCookieName,
891
919
  path,
892
- pathMatches,
893
- proxyChain,
894
- resolveRuleResult,
895
- responseHeaderItems,
896
- ruleLabel,
897
- ruleMatches,
898
- safeInternalError,
899
- toPathRegex,
900
- toRule,
901
- toStatelessRegExp,
902
- withPaths,
903
- withRuleTimeout
920
+ proxyChain
904
921
  });