@klnap/next-proxy-chain 1.0.7 → 1.1.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 CHANGED
@@ -4,6 +4,28 @@ All notable changes to `@klnap/next-proxy-chain` will be documented in this file
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
5
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [1.1.0] - 2026-11-22
8
+
9
+ ### Added
10
+
11
+ - `chain(entries, options?)`: the recommended entry point. Plain functions receive the native `(request, event)` arguments. `defineProxy()` rules receive `(request, context, event)`.
12
+ - Scoped tuples: `[handler, scope]`, where `scope` is a path string, an array, a RegExp, or an object `{ include?, exclude? }`. Include objects accept `host`.
13
+ - Exported types `ChainEntry`, `ChainScope`, and `NativeProxy`.
14
+ - `chain()` passes the request context to plain handlers as an optional third argument: `(request, event, context)`.
15
+
16
+ ### Deprecated
17
+
18
+ - `proxyChain()` is deprecated in favor of `chain()`. It keeps its behavior. Its removal would be a major release.
19
+
20
+ ### Fixed
21
+
22
+ - A native Next.js handler passed to `proxyChain()` received the context instead of `event`, so `event.waitUntil()` failed and the request returned `500`. `chain()` avoids this. `proxyChain()` keeps its signature.
23
+
24
+ ### Documentation
25
+
26
+ - README rewritten to start with `chain()`. Advanced features follow in separate sections.
27
+ - `docs/api.md` and `docs/concepts.md` describe native handlers and context rules.
28
+
7
29
  ## [1.0.7] - 2026-11-22
8
30
 
9
31
  ### Fixed
package/README.md CHANGED
@@ -1,32 +1,20 @@
1
1
  # @klnap/next-proxy-chain
2
2
 
3
- Compose independent request rules for Next.js `proxy.ts` (or `middleware.ts`) without writing one long function.
3
+ Run several Next.js `proxy.ts` (or `middleware.ts`) handlers as one chain. Each handler can be a plain native Next.js function, scoped to certain paths, and the chain stops or continues according to what each handler returns.
4
4
 
5
- Next.js gives each app one `proxy` export. Once that file also checks sessions, sets security headers, picks a locale, and redirects old URLs, the order of those checks matters, and each one has to know about the others. This package lets each concern be its own rule. The rules run in order, can be limited to certain paths or hosts, and share request-scoped state without any global variables.
5
+ Next.js exports one proxy per app. As soon as the file contains an auth check, a locale redirect, and some security headers, the order matters and the pieces end up in one long function. This package keeps each handler separate and keeps the order visible.
6
6
 
7
7
  ```ts
8
- import { defineProxy, next, path, proxyChain } from '@klnap/next-proxy-chain'
9
- import { NextResponse } from 'next/server'
10
-
11
- const securityHeaders = defineProxy('security-headers', () =>
12
- next({ headers: { 'x-frame-options': 'DENY' } })
13
- )
14
-
15
- const requireSession = defineProxy('require-session', (req) => {
16
- if (!req.cookies.has('session')) {
17
- return NextResponse.redirect(new URL('/login', req.url))
18
- }
19
- return next()
20
- })
21
-
22
- export default proxyChain([securityHeaders, requireSession({ include: path('/dashboard/**') })])
8
+ import { chain } from '@klnap/next-proxy-chain'
23
9
 
24
- export const config = {
25
- matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
26
- }
10
+ export default chain([
11
+ intlProxy,
12
+ [authProxy, '/dashboard/**'],
13
+ securityProxy,
14
+ ])
27
15
  ```
28
16
 
29
- This sets `X-Frame-Options` on every response and sends visitors without a session cookie from `/dashboard` to `/login`. The security header comes first, so it also appears on the redirect.
17
+ `intlProxy`, `authProxy` and `securityProxy` are ordinary Next.js proxy functions: `(request, event) => NextResponse | Response | undefined`. You do not wrap them, and you do not change what they return.
30
18
 
31
19
  ## Install
32
20
 
@@ -38,44 +26,148 @@ bun add @klnap/next-proxy-chain
38
26
 
39
27
  `next` is a peer dependency (`>=15.0.0`). The package has no runtime dependencies.
40
28
 
41
- ## When to use it
29
+ ## Basic composition
30
+
31
+ Pass handlers in the order they should run. Each one receives the native `(request, event)` arguments, so `event.waitUntil()` works.
32
+
33
+ ```ts
34
+ import { chain } from '@klnap/next-proxy-chain'
35
+ import { NextResponse } from 'next/server'
36
+
37
+ function analytics(request, event) {
38
+ event.waitUntil(sendPageView(request.nextUrl.pathname))
39
+ return NextResponse.next()
40
+ }
41
+
42
+ export default chain([analytics, intlProxy, securityProxy])
43
+ ```
42
44
 
43
- Use it when one Proxy file needs several independent concerns, for example:
45
+ A handler continues the chain by returning `undefined` or `NextResponse.next()`. A handler stops the chain by returning a `Response`, `NextResponse.redirect()`, `NextResponse.json()`, or `Response.redirect()`. The rest of this page explains each case.
44
46
 
45
- - a session check on some routes and not others,
46
- - security headers on every response,
47
- - a locale rewrite,
48
- - a redirect from old URLs,
49
- - request IDs passed to route handlers.
47
+ ## Scoped handlers
50
48
 
51
- A single redirect rule does not need it. Write `NextResponse.redirect` directly in `proxy.ts`.
49
+ Wrap a handler in a tuple to run it only for some paths or hosts:
52
50
 
53
- It is a composition layer, not a security product. It does not authenticate users, verify tokens, or replace Next.js routing. It runs the rules you write, in the order you list them.
51
+ ```ts
52
+ export default chain([
53
+ // Only /dashboard and its children.
54
+ [authProxy, '/dashboard/**'],
54
55
 
55
- ## How it works
56
+ // Everything except /login.
57
+ [adminProxy, { exclude: '/admin/login' }],
58
+
59
+ // RegExp works too.
60
+ [privateProxy, { exclude: /^\/public(\/.*)?$/ }],
61
+
62
+ // Several patterns and a host.
63
+ [billingProxy, { include: { host: 'app.example.com', path: ['/billing/**', '/invoices/**'] } }],
64
+ ])
65
+ ```
56
66
 
57
- - Rules run in array order. A rule continues by returning `next()` or nothing, and stops the chain by returning a `Response`.
58
- - A rule can be scoped with `include` and `exclude` paths or hosts. Rules that do not match are skipped.
59
- - Headers and cookies set by earlier rules are kept on the final response, unless a later rule overrides them.
60
- - Each request gets its own context. Rules can share values through it without globals.
61
- - Errors and timeouts can be recovered with `onError`. By default they produce a 500.
67
+ Path patterns:
68
+
69
+ - `*` matches one segment: `/api/*` matches `/api/users`, not `/api/users/123`.
70
+ - `**` matches any depth, including zero segments: `/docs/**` matches `/docs` and `/docs/a/b`.
71
+ - `:name` matches one segment and does not capture a value.
72
+ - A RegExp is matched against the decoded path. Anchor it with `^` and `$` for an exact match.
73
+
74
+ Segments are compared whole. `/tenant` does not match `/tenant-other`. A pattern such as `/files/*.pdf` throws when the chain is created, because wildcards must be whole segments.
75
+
76
+ ## Context and typed rules
77
+
78
+ A handler that needs per-request state is written with `defineProxy()`. It receives a context object as its second argument:
79
+
80
+ ```ts
81
+ import { chain, defineProxy, next } from '@klnap/next-proxy-chain'
62
82
 
63
- [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md) explains the execution model in full.
83
+ type Session = { user?: string }
84
+
85
+ const readSession = defineProxy<Session>('read-session', (request, session) => {
86
+ session.user = request.cookies.get('user')?.value
87
+ return next()
88
+ })
89
+
90
+ const requireUser = defineProxy<Session>('require-user', (request, session) => {
91
+ if (!session.user) return NextResponse.redirect(new URL('/login', request.url))
92
+ return next()
93
+ })
94
+
95
+ export default chain(
96
+ [readSession, [requireUser, '/dashboard/**']],
97
+ { createContext: (): Session => ({}) }
98
+ )
99
+ ```
100
+
101
+ - The context is created for each request and is not shared between requests.
102
+ - `createContext` is required when a rule declares a context type. Passing a rule that expects a different type is a compile-time error.
103
+ - Rules run in array order. Put the rule that sets a value before the rule that reads it.
104
+
105
+ Use `defineProxy()` only when you need the context or a named rule. A plain function is enough for everything else.
106
+
107
+ ## Continuing and stopping
108
+
109
+ | A handler returns | Effect |
110
+ | :--- | :--- |
111
+ | `undefined` or nothing | Continue. |
112
+ | `NextResponse.next()` | Continue. Its request-header overrides are kept. |
113
+ | `NextResponse.rewrite(url)` | Continue. The rewrite is applied at the end unless a later handler stops. |
114
+ | `NextResponse.redirect(url)`, `NextResponse.json()`, `Response`, `Response.redirect()` | Stop and return that response. |
115
+ | `next({ request, headers })` | Continue, and apply the given headers. This is a library token; plain Next.js handlers should return `NextResponse.next()`. |
116
+ | A thrown error or a rejected promise | Fail closed with `500`, unless `onError` is set. |
117
+
118
+ Stopping is immediate. A handler after a stopping handler does not run, so put checks that must always run before any handler that might answer the request.
119
+
120
+ Headers and cookies that earlier handlers set are kept on the response that stops the chain. Handlers after it do not contribute.
121
+
122
+ ## Options
123
+
124
+ `chain(entries, options)` accepts the same options as `proxyChain`:
125
+
126
+ | Option | Purpose |
127
+ | :--- | :--- |
128
+ | `createContext` | Creates the context for each request. Required for typed rules. |
129
+ | `onError` | Returns a `Response` to stop with, `next()` to continue, or nothing for a `500`. |
130
+ | `ruleTimeoutMs` | Time limit per handler. `0` (default) disables it. |
131
+ | `headerMergeStrategy`, `cookieMergeStrategy` | How conflicting response headers and cookies are resolved. |
132
+ | `requestHeaderPolicy` | Which request headers `next({ request })` may set. |
133
+ | `debug`, `logger` | One log line per handler, and a custom logger. |
134
+ | `strictOverrideCheck` | Throw at startup if Next.js does not apply request overrides. |
135
+ | `hostFolderHeader` | Opt-in multi-tenant folder prefix for rewrites. |
136
+
137
+ The full reference is in [docs/api.md](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md).
138
+
139
+ ## Native compatibility
140
+
141
+ - A plain handler gets `(request, event)`, exactly as in a native `proxy.ts`. `chain()` also passes the request context as an optional third argument, which Next.js never uses.
142
+ - `export default chain([...])` is the default export that Next.js expects. Put `export const config = { matcher }` next to it as usual.
143
+ - Handlers can be async.
144
+ - Handlers returned by other packages work unchanged, if they follow the native signature.
145
+
146
+ `proxyChain()` is a deprecated alias that is still exported and unchanged. Its plain functions receive `(request, context, event)`. Use `chain()` in new code.
64
147
 
65
148
  ## Documentation
66
149
 
67
- - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): rule order, continuation, scoping, headers, cookies, errors.
68
- - [Guides](https://github.com/klnap/next-proxy-chain/blob/main/docs/guides.md): recipes for common tasks, with links to runnable examples.
150
+ - [Concepts](https://github.com/klnap/next-proxy-chain/blob/main/docs/concepts.md): execution order, continuation, scoping, headers, cookies, errors.
151
+ - [Guides](https://github.com/klnap/next-proxy-chain/blob/main/docs/guides.md): recipes for common tasks.
69
152
  - [API reference](https://github.com/klnap/next-proxy-chain/blob/main/docs/api.md): every export and option.
70
153
  - [Security](https://github.com/klnap/next-proxy-chain/blob/main/docs/security.md): trust boundaries and safe usage.
71
154
 
72
- Runnable examples live in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/). They are type-checked and tested in this repository.
155
+ Runnable examples are in [`examples/`](https://github.com/klnap/next-proxy-chain/blob/main/examples/).
156
+
157
+ ## Migration
158
+
159
+ No change is required. `proxyChain()` and `defineProxy()` keep working. To move to `chain()`:
160
+
161
+ 1. Replace `proxyChain(entries)` with `chain(entries)`.
162
+ 2. Plain functions that used the old `(request, context, event)` signature: rewrite them with `defineProxy()`, which keeps that signature.
163
+ 3. Replace `path()` and `host()` helpers with strings, arrays, or objects where you like. They still work.
73
164
 
74
165
  ## Compatibility
75
166
 
76
- - Next.js: peer `>=15.0.0`. The test suite runs against Next.js 16.3.2. Next.js 15 `middleware.ts` is covered by integration tests that model its behavior, not by a Next.js 15 application.
167
+ - Next.js: peer `>=15.0.0`. The test suite runs against Next.js 16.3.2 through a live app. Next.js 15 is covered by integration tests that model its behavior; it has not been run as a live application.
77
168
  - Node.js `>=20`, Bun `>=1`.
78
- - Next.js 16 runs `proxy.ts` on the Node.js runtime by default. The package uses only Web platform APIs (`Headers`, `Request`, `Response`, `URL`), so it should also work on the Edge runtime, but that is not tested here.
169
+ - Next.js 16 runs `proxy.ts` on the Node.js runtime by default. The package uses only Web platform APIs, so it should also run on the Edge runtime for Next.js 15 `middleware.ts`, but that is not tested here.
170
+ - Framework-neutral use (Express, Hono) is not supported. The package depends on Next.js request and response semantics.
79
171
 
80
172
  ## Links
81
173
 
package/dist/index.cjs CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  RuleTimeoutError: () => RuleTimeoutError,
24
+ chain: () => chain,
24
25
  createProxyContext: () => createProxyContext,
25
26
  defineProxy: () => defineProxy,
26
27
  host: () => host,
@@ -53,6 +54,7 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
53
54
  "x-middleware-next",
54
55
  "x-middleware-override-headers"
55
56
  ]);
57
+ var CONTEXT_RULE = /* @__PURE__ */ Symbol.for("proxy-chain.context-rule");
56
58
 
57
59
  // src/core/actions.ts
58
60
  function next(options = {}) {
@@ -62,14 +64,14 @@ function isNextResult(value) {
62
64
  return typeof value === "object" && value !== null && NEXT in value;
63
65
  }
64
66
 
67
+ // src/core/engine.ts
68
+ var import_server2 = require("next/server");
69
+
65
70
  // src/core/context.ts
66
71
  function createProxyContext() {
67
72
  return /* @__PURE__ */ new Map();
68
73
  }
69
74
 
70
- // src/core/engine.ts
71
- var import_server2 = require("next/server");
72
-
73
75
  // src/core/headers.ts
74
76
  function normalizeHeaderName(name) {
75
77
  return name.toLowerCase();
@@ -688,6 +690,7 @@ function defineProxy(nameOrRun, maybeRun) {
688
690
  value: defaultName ?? "",
689
691
  configurable: true
690
692
  });
693
+ Object.defineProperty(proxy, CONTEXT_RULE, { value: true });
691
694
  return proxy;
692
695
  }
693
696
  function resolveConfig(overrides, fallbackCreateContext) {
@@ -1001,9 +1004,42 @@ function proxyChain(optionsOrEntries, maybeEntries) {
1001
1004
  }
1002
1005
  };
1003
1006
  }
1007
+
1008
+ // src/core/chain.ts
1009
+ function isContextRule(value) {
1010
+ return typeof value === "function" && value[CONTEXT_RULE] === true;
1011
+ }
1012
+ function isScopeObject2(value) {
1013
+ return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
1014
+ }
1015
+ function toFilter(scope) {
1016
+ if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
1017
+ return { include: scope };
1018
+ }
1019
+ function fromNative(handler) {
1020
+ const run = (req, ctx, event) => handler(req, event, ctx);
1021
+ const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
1022
+ return { run, name };
1023
+ }
1024
+ function toEntry(entry) {
1025
+ if (Array.isArray(entry)) {
1026
+ const [target, scope] = entry;
1027
+ const filter = toFilter(scope);
1028
+ if (isContextRule(target)) return target(filter);
1029
+ return withPaths(fromNative(target), filter);
1030
+ }
1031
+ if (isContextRule(entry)) return entry;
1032
+ if (typeof entry === "function") return fromNative(entry);
1033
+ return entry;
1034
+ }
1035
+ function chain(entries, options) {
1036
+ const normalized = entries.map((entry) => toEntry(entry));
1037
+ return proxyChain(options ?? {}, normalized);
1038
+ }
1004
1039
  // Annotate the CommonJS export names for ESM import in node:
1005
1040
  0 && (module.exports = {
1006
1041
  RuleTimeoutError,
1042
+ chain,
1007
1043
  createProxyContext,
1008
1044
  defineProxy,
1009
1045
  host,
package/dist/index.d.cts CHANGED
@@ -54,12 +54,27 @@ type ProxyPathFilter = {
54
54
  exclude?: RouteScopeList;
55
55
  name?: string;
56
56
  };
57
+ /**
58
+ * Type-only brand carried by defineProxy() rules. It records the context type a rule expects.
59
+ * Chain entries match on it as an object, which keeps handler parameters contextually typed.
60
+ */
61
+ declare const CONTEXT_BRAND: unique symbol;
62
+ /** Entry type for a defineProxy() rule that expects context TContext. */
63
+ type ContextRuleEntry<TContext = ProxyContext> = {
64
+ readonly [CONTEXT_BRAND]: TContext;
65
+ };
66
+ /**
67
+ * A native Next.js proxy handler: `(request, event)`. Use it in chain() without any wrapper.
68
+ */
69
+ type NativeProxy<TContext = ProxyContext> = (req: NextRequest, event: NextFetchEvent,
70
+ /** Request context from createContext. Next.js never passes it; chain() does, as the third argument. */
71
+ context: TContext) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
57
72
  /**
58
73
  * A single proxy execution function.
59
74
  */
60
75
  type ProxyFn<TContext = ProxyContext> = (req: NextRequest, ctx: TContext, event: NextFetchEvent) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
61
76
  type ProxyRule<TContext = ProxyContext> = BaseProxyRule<ProxyFn<TContext>>;
62
- type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>);
77
+ type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>) & ContextRuleEntry<TContext>;
63
78
  type Entry<TContext = ProxyContext> = ProxyFn<TContext> | ProxyRule<TContext>;
64
79
  type MergeStrategy = 'last-write-wins' | 'first-write-wins' | ((key: string, existing: string, incoming: string) => string | null);
65
80
  interface ChainLogger {
@@ -126,12 +141,6 @@ declare function next(options?: NextOptions): NextResult;
126
141
  */
127
142
  declare function isNextResult(value: unknown): value is NextResult;
128
143
 
129
- /**
130
- * Creates an isolated per-request context instance.
131
- * Backed by Map to eliminate prototype pollution risks.
132
- */
133
- declare function createProxyContext(): ProxyContext;
134
-
135
144
  /**
136
145
  * Creates a reusable, scope-aware proxy rule function.
137
146
  *
@@ -154,12 +163,38 @@ type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<NextRes
154
163
  * i18nRule,
155
164
  * ])
156
165
  */
166
+ /** @deprecated Use chain(). Plain functions here receive (request, context, event). */
157
167
  declare function proxyChain(entries: Entry<ProxyContext>[]): ProxyHandler;
158
168
  declare function proxyChain(options: ProxyChainOptions<ProxyContext>, entries: Entry<ProxyContext>[]): ProxyHandler;
159
169
  declare function proxyChain<TContext>(options: ProxyChainOptions<TContext> & {
160
170
  createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
161
171
  }, entries: Entry<TContext>[]): ProxyHandler;
162
172
 
173
+ /** Scope for a tuple entry: `[handler, scope]`. A string, RegExp, or array is shorthand for `include`. */
174
+ type ChainScope = Omit<ProxyPathFilter, 'name'> | PathMatcher | readonly PathMatcher[];
175
+ /** One entry of chain(): a native handler, a defineProxy() rule, a rule object, or a scoped tuple. */
176
+ type ChainEntry<TContext = ProxyContext> = NativeProxy<TContext> | ContextRuleEntry<TContext> | ProxyRule<TContext> | readonly [NativeProxy<TContext> | ContextRuleEntry<TContext>, ChainScope];
177
+ /**
178
+ * Composes native Next.js proxy handlers and optional rules into one proxy.
179
+ *
180
+ * - A plain function receives `(request, event)`, exactly like a native `proxy.ts` export.
181
+ * - A `defineProxy()` rule receives `(request, context, event)`.
182
+ * - `[handler, scope]` runs the handler only for matching paths or hosts.
183
+ *
184
+ * @example
185
+ * export default chain([intlProxy, [authProxy, { include: '/dashboard/**' }]])
186
+ */
187
+ declare function chain(entries: readonly ChainEntry<ProxyContext>[], options?: ProxyChainOptions<ProxyContext>): ReturnType<typeof proxyChain>;
188
+ declare function chain<TContext>(entries: readonly ChainEntry<TContext>[], options: ProxyChainOptions<TContext> & {
189
+ createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
190
+ }): ReturnType<typeof proxyChain>;
191
+
192
+ /**
193
+ * Creates an isolated per-request context instance.
194
+ * Backed by Map to eliminate prototype pollution risks.
195
+ */
196
+ declare function createProxyContext(): ProxyContext;
197
+
163
198
  /**
164
199
  * Builds a compiled Host matcher RegExp from domain names, `*.example.com` wildcards, or regex patterns.
165
200
  */
@@ -178,4 +213,4 @@ declare class RuleTimeoutError extends Error {
178
213
  constructor(ruleName: string, timeoutMs: number);
179
214
  }
180
215
 
181
- export { type ChainLogger, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
216
+ export { type ChainEntry, type ChainLogger, type ChainScope, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NativeProxy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, chain, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
package/dist/index.d.ts CHANGED
@@ -54,12 +54,27 @@ type ProxyPathFilter = {
54
54
  exclude?: RouteScopeList;
55
55
  name?: string;
56
56
  };
57
+ /**
58
+ * Type-only brand carried by defineProxy() rules. It records the context type a rule expects.
59
+ * Chain entries match on it as an object, which keeps handler parameters contextually typed.
60
+ */
61
+ declare const CONTEXT_BRAND: unique symbol;
62
+ /** Entry type for a defineProxy() rule that expects context TContext. */
63
+ type ContextRuleEntry<TContext = ProxyContext> = {
64
+ readonly [CONTEXT_BRAND]: TContext;
65
+ };
66
+ /**
67
+ * A native Next.js proxy handler: `(request, event)`. Use it in chain() without any wrapper.
68
+ */
69
+ type NativeProxy<TContext = ProxyContext> = (req: NextRequest, event: NextFetchEvent,
70
+ /** Request context from createContext. Next.js never passes it; chain() does, as the third argument. */
71
+ context: TContext) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
57
72
  /**
58
73
  * A single proxy execution function.
59
74
  */
60
75
  type ProxyFn<TContext = ProxyContext> = (req: NextRequest, ctx: TContext, event: NextFetchEvent) => NextResponse | Response | NextResult | undefined | void | Promise<NextResponse | Response | NextResult | undefined | void>;
61
76
  type ProxyRule<TContext = ProxyContext> = BaseProxyRule<ProxyFn<TContext>>;
62
- type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>);
77
+ type DefinedProxy<TContext = ProxyContext> = ProxyFn<TContext> & ((filter: ProxyPathFilter) => ProxyRule<TContext>) & ContextRuleEntry<TContext>;
63
78
  type Entry<TContext = ProxyContext> = ProxyFn<TContext> | ProxyRule<TContext>;
64
79
  type MergeStrategy = 'last-write-wins' | 'first-write-wins' | ((key: string, existing: string, incoming: string) => string | null);
65
80
  interface ChainLogger {
@@ -126,12 +141,6 @@ declare function next(options?: NextOptions): NextResult;
126
141
  */
127
142
  declare function isNextResult(value: unknown): value is NextResult;
128
143
 
129
- /**
130
- * Creates an isolated per-request context instance.
131
- * Backed by Map to eliminate prototype pollution risks.
132
- */
133
- declare function createProxyContext(): ProxyContext;
134
-
135
144
  /**
136
145
  * Creates a reusable, scope-aware proxy rule function.
137
146
  *
@@ -154,12 +163,38 @@ type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<NextRes
154
163
  * i18nRule,
155
164
  * ])
156
165
  */
166
+ /** @deprecated Use chain(). Plain functions here receive (request, context, event). */
157
167
  declare function proxyChain(entries: Entry<ProxyContext>[]): ProxyHandler;
158
168
  declare function proxyChain(options: ProxyChainOptions<ProxyContext>, entries: Entry<ProxyContext>[]): ProxyHandler;
159
169
  declare function proxyChain<TContext>(options: ProxyChainOptions<TContext> & {
160
170
  createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
161
171
  }, entries: Entry<TContext>[]): ProxyHandler;
162
172
 
173
+ /** Scope for a tuple entry: `[handler, scope]`. A string, RegExp, or array is shorthand for `include`. */
174
+ type ChainScope = Omit<ProxyPathFilter, 'name'> | PathMatcher | readonly PathMatcher[];
175
+ /** One entry of chain(): a native handler, a defineProxy() rule, a rule object, or a scoped tuple. */
176
+ type ChainEntry<TContext = ProxyContext> = NativeProxy<TContext> | ContextRuleEntry<TContext> | ProxyRule<TContext> | readonly [NativeProxy<TContext> | ContextRuleEntry<TContext>, ChainScope];
177
+ /**
178
+ * Composes native Next.js proxy handlers and optional rules into one proxy.
179
+ *
180
+ * - A plain function receives `(request, event)`, exactly like a native `proxy.ts` export.
181
+ * - A `defineProxy()` rule receives `(request, context, event)`.
182
+ * - `[handler, scope]` runs the handler only for matching paths or hosts.
183
+ *
184
+ * @example
185
+ * export default chain([intlProxy, [authProxy, { include: '/dashboard/**' }]])
186
+ */
187
+ declare function chain(entries: readonly ChainEntry<ProxyContext>[], options?: ProxyChainOptions<ProxyContext>): ReturnType<typeof proxyChain>;
188
+ declare function chain<TContext>(entries: readonly ChainEntry<TContext>[], options: ProxyChainOptions<TContext> & {
189
+ createContext: (req: NextRequest, event: NextFetchEvent) => TContext;
190
+ }): ReturnType<typeof proxyChain>;
191
+
192
+ /**
193
+ * Creates an isolated per-request context instance.
194
+ * Backed by Map to eliminate prototype pollution risks.
195
+ */
196
+ declare function createProxyContext(): ProxyContext;
197
+
163
198
  /**
164
199
  * Builds a compiled Host matcher RegExp from domain names, `*.example.com` wildcards, or regex patterns.
165
200
  */
@@ -178,4 +213,4 @@ declare class RuleTimeoutError extends Error {
178
213
  constructor(ruleName: string, timeoutMs: number);
179
214
  }
180
215
 
181
- export { type ChainLogger, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
216
+ export { type ChainEntry, type ChainLogger, type ChainScope, type DefinedProxy, type Entry, type HostMatcher, type MergeStrategy, type NativeProxy, type NextOptions, type NextResult, type OnErrorHandler, type OnErrorResult, type PathMatcher, type ProxyChainOptions, type ProxyContext, type ProxyFn, type ProxyPathFilter, type ProxyRule, type RequestHeaderPolicy, RuleTimeoutError, chain, createProxyContext, defineProxy, host, isNextResult, next, path, proxyChain };
package/dist/index.js CHANGED
@@ -20,6 +20,7 @@ var DEFAULT_BLOCKED_REQUEST_HEADERS = Object.freeze([
20
20
  "x-middleware-next",
21
21
  "x-middleware-override-headers"
22
22
  ]);
23
+ var CONTEXT_RULE = /* @__PURE__ */ Symbol.for("proxy-chain.context-rule");
23
24
 
24
25
  // src/core/actions.ts
25
26
  function next(options = {}) {
@@ -29,14 +30,14 @@ function isNextResult(value) {
29
30
  return typeof value === "object" && value !== null && NEXT in value;
30
31
  }
31
32
 
33
+ // src/core/engine.ts
34
+ import { NextRequest, NextResponse as NextResponse2 } from "next/server";
35
+
32
36
  // src/core/context.ts
33
37
  function createProxyContext() {
34
38
  return /* @__PURE__ */ new Map();
35
39
  }
36
40
 
37
- // src/core/engine.ts
38
- import { NextRequest, NextResponse as NextResponse2 } from "next/server";
39
-
40
41
  // src/core/headers.ts
41
42
  function normalizeHeaderName(name) {
42
43
  return name.toLowerCase();
@@ -655,6 +656,7 @@ function defineProxy(nameOrRun, maybeRun) {
655
656
  value: defaultName ?? "",
656
657
  configurable: true
657
658
  });
659
+ Object.defineProperty(proxy, CONTEXT_RULE, { value: true });
658
660
  return proxy;
659
661
  }
660
662
  function resolveConfig(overrides, fallbackCreateContext) {
@@ -968,8 +970,41 @@ function proxyChain(optionsOrEntries, maybeEntries) {
968
970
  }
969
971
  };
970
972
  }
973
+
974
+ // src/core/chain.ts
975
+ function isContextRule(value) {
976
+ return typeof value === "function" && value[CONTEXT_RULE] === true;
977
+ }
978
+ function isScopeObject2(value) {
979
+ return typeof value === "object" && value !== null && !(value instanceof RegExp) && !Array.isArray(value);
980
+ }
981
+ function toFilter(scope) {
982
+ if (isScopeObject2(scope)) return { include: scope.include, exclude: scope.exclude };
983
+ return { include: scope };
984
+ }
985
+ function fromNative(handler) {
986
+ const run = (req, ctx, event) => handler(req, event, ctx);
987
+ const name = handler.name && handler.name !== "proxy" ? handler.name : void 0;
988
+ return { run, name };
989
+ }
990
+ function toEntry(entry) {
991
+ if (Array.isArray(entry)) {
992
+ const [target, scope] = entry;
993
+ const filter = toFilter(scope);
994
+ if (isContextRule(target)) return target(filter);
995
+ return withPaths(fromNative(target), filter);
996
+ }
997
+ if (isContextRule(entry)) return entry;
998
+ if (typeof entry === "function") return fromNative(entry);
999
+ return entry;
1000
+ }
1001
+ function chain(entries, options) {
1002
+ const normalized = entries.map((entry) => toEntry(entry));
1003
+ return proxyChain(options ?? {}, normalized);
1004
+ }
971
1005
  export {
972
1006
  RuleTimeoutError,
1007
+ chain,
973
1008
  createProxyContext,
974
1009
  defineProxy,
975
1010
  host,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@klnap/next-proxy-chain",
3
- "version": "1.0.7",
3
+ "version": "1.1.0",
4
4
  "description": "Compose independent request rules for Next.js proxy.ts and middleware.ts.",
5
5
  "repository": {
6
6
  "type": "git",