@spfn/core 0.3.0-beta.29 → 0.3.0-beta.30
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/nextjs/index.d.ts +3 -22
- package/dist/nextjs/index.js +67 -27
- package/dist/nextjs/index.js.map +1 -1
- package/dist/nextjs/server.d.ts +2 -2
- package/dist/nextjs/server.js +1 -1
- package/dist/nextjs/server.js.map +1 -1
- package/dist/{types-CxhPH4s_.d.ts → types-CKH0D3Dy.d.ts} +67 -1
- package/package.json +1 -1
- package/src/nextjs/README.md +69 -1
package/dist/nextjs/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Router, RouteDef } from '@spfn/core/route';
|
|
2
|
-
import { R as RequestInterceptor, a as ResponseInterceptor, I as InferRouteInput, b as InferRouteOutput, E as ExtractRoutes, A as ApiConfig } from '../types-
|
|
3
|
-
export { C as CallOptions,
|
|
2
|
+
import { R as RequestInterceptor, a as ResponseInterceptor, I as InferRouteInput, b as InferRouteOutput, E as ExtractRoutes, A as ApiConfig } from '../types-CKH0D3Dy.js';
|
|
3
|
+
export { c as ApiError, d as ApiOutcome, C as CallOptions, e as CookieOptions, f as RouterInput, g as RouterOutput, S as SetCookie, h as StructuredInput } from '../types-CKH0D3Dy.js';
|
|
4
4
|
import '@sinclair/typebox';
|
|
5
5
|
import '@spfn/core/errors';
|
|
6
6
|
|
|
@@ -178,23 +178,4 @@ declare function csrfHeaderValue(cookies: Iterable<[string, string]>): string |
|
|
|
178
178
|
*/
|
|
179
179
|
declare function documentCookieEntries(): Array<[string, string]>;
|
|
180
180
|
|
|
181
|
-
|
|
182
|
-
* Typed client error
|
|
183
|
-
*
|
|
184
|
-
* `errorType` tells apart why a call failed:
|
|
185
|
-
* - `'http'`: the server answered with a non-2xx status
|
|
186
|
-
* - `'network'`: the fetch or the body read failed (status 0)
|
|
187
|
-
* - `'timeout'`: the call's timeout elapsed before response headers arrived (status 408)
|
|
188
|
-
* - `'aborted'`: the caller's own signal aborted the call (status 0); `cause` is the signal's reason
|
|
189
|
-
*/
|
|
190
|
-
declare class ApiError extends Error {
|
|
191
|
-
readonly status: number;
|
|
192
|
-
readonly url: string;
|
|
193
|
-
readonly response?: unknown | undefined;
|
|
194
|
-
readonly errorType?: "http" | "network" | "timeout" | "aborted" | undefined;
|
|
195
|
-
constructor(message: string, status: number, url: string, response?: unknown | undefined, errorType?: "http" | "network" | "timeout" | "aborted" | undefined, options?: {
|
|
196
|
-
cause?: unknown;
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
export { ApiConfig, ApiError, CSRF_HEADER, type Client, InferRouteInput, InferRouteOutput, RequestInterceptor, ResponseInterceptor, type RouteClient, createApi, csrfHeaderValue, documentCookieEntries };
|
|
181
|
+
export { ApiConfig, CSRF_HEADER, type Client, InferRouteInput, InferRouteOutput, RequestInterceptor, ResponseInterceptor, type RouteClient, createApi, csrfHeaderValue, documentCookieEntries };
|
package/dist/nextjs/index.js
CHANGED
|
@@ -103,7 +103,7 @@ async function autoDetectServerCookies() {
|
|
|
103
103
|
return {};
|
|
104
104
|
}
|
|
105
105
|
try {
|
|
106
|
-
const { cookies } = await import('next/headers');
|
|
106
|
+
const { cookies } = await import('next/headers.js');
|
|
107
107
|
const cookieStore = await cookies();
|
|
108
108
|
const allCookies = cookieStore.getAll();
|
|
109
109
|
const result = Object.fromEntries(
|
|
@@ -164,40 +164,49 @@ async function fetchInAbortScope(url, init, timeout, customFetch = fetch) {
|
|
|
164
164
|
scope.close();
|
|
165
165
|
}
|
|
166
166
|
}
|
|
167
|
-
|
|
167
|
+
function errorFromResponse(response, body, fullUrl, errorRegistry, debug, logger3) {
|
|
168
168
|
if (debug) {
|
|
169
169
|
logErrorResponse(logger3, response.status, body);
|
|
170
170
|
}
|
|
171
|
-
|
|
172
|
-
if (
|
|
171
|
+
const deserializedError = deserializeRegisteredError(body, errorRegistry, debug, logger3);
|
|
172
|
+
if (deserializedError) {
|
|
173
173
|
if (debug) {
|
|
174
|
-
|
|
174
|
+
logThrowingDeserializedError(logger3, deserializedError);
|
|
175
175
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
176
|
+
return deserializedError;
|
|
177
|
+
}
|
|
178
|
+
return fallbackApiError(response, body, fullUrl, logger3);
|
|
179
|
+
}
|
|
180
|
+
function deserializeRegisteredError(body, errorRegistry, debug, logger3) {
|
|
181
|
+
if (!errorRegistry || !body || typeof body !== "object" || !("__type" in body)) {
|
|
182
|
+
if (debug) {
|
|
183
|
+
logErrorDeserializationSkipped(logger3, errorRegistry, body);
|
|
185
184
|
}
|
|
186
|
-
|
|
187
|
-
logErrorDeserializationSkipped(logger3, errorRegistry, body);
|
|
185
|
+
return null;
|
|
188
186
|
}
|
|
189
|
-
if (
|
|
187
|
+
if (debug) {
|
|
188
|
+
logErrorDeserializationAttempt(logger3, body.__type, errorRegistry.getRegisteredTypes());
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
const deserializedError = errorRegistry.deserialize(body);
|
|
190
192
|
if (debug) {
|
|
191
|
-
|
|
193
|
+
logErrorDeserializationSuccess(logger3, deserializedError);
|
|
194
|
+
}
|
|
195
|
+
return deserializedError;
|
|
196
|
+
} catch (deserializeError) {
|
|
197
|
+
if (debug) {
|
|
198
|
+
logErrorDeserializationFailure(logger3, deserializeError);
|
|
192
199
|
}
|
|
193
|
-
|
|
200
|
+
return null;
|
|
194
201
|
}
|
|
202
|
+
}
|
|
203
|
+
function fallbackApiError(response, body, fullUrl, logger3) {
|
|
195
204
|
if (response.status === 404 && process.env.NODE_ENV !== "production") {
|
|
196
205
|
logger3.warn(
|
|
197
206
|
"\n\u26A0\uFE0F 404 Not Found\n\nCheck the following:\n 1. Routes are registered in server.config.ts:\n \u2192 defineServerConfig().routes(appRouter)\n 2. Delete .spfn cache if you recently added new routes:\n \u2192 rm -rf .spfn\n"
|
|
198
207
|
);
|
|
199
208
|
}
|
|
200
|
-
|
|
209
|
+
return new ApiError(
|
|
201
210
|
body?.message || `HTTP ${response.status}: ${response.statusText}`,
|
|
202
211
|
response.status,
|
|
203
212
|
fullUrl,
|
|
@@ -355,19 +364,22 @@ var RouteCallBuilder = class _RouteCallBuilder {
|
|
|
355
364
|
|
|
356
365
|
// src/nextjs/client/core.ts
|
|
357
366
|
var apiLogger = logger.child("@spfn/core:api-client");
|
|
367
|
+
function transportOutcome(errorType, message, status, url, options) {
|
|
368
|
+
return { ok: false, errorType, status, error: new ApiError(message, status, url, void 0, errorType, options) };
|
|
369
|
+
}
|
|
358
370
|
function transportError(failure, site, timeout) {
|
|
359
371
|
if (failure.cause === "timeout") {
|
|
360
372
|
apiLogger.error("Request timeout", { ...site, timeout });
|
|
361
|
-
return
|
|
373
|
+
return transportOutcome("timeout", `Request timeout after ${timeout}ms`, 408, site.url);
|
|
362
374
|
}
|
|
363
375
|
if (failure.cause === "caller") {
|
|
364
376
|
apiLogger.debug("Request aborted by caller", site);
|
|
365
|
-
return
|
|
377
|
+
return transportOutcome("aborted", "Request aborted", 0, site.url, { cause: failure.error });
|
|
366
378
|
}
|
|
367
379
|
const { error } = failure;
|
|
368
380
|
if (error instanceof Error && error.name === "AbortError") {
|
|
369
381
|
apiLogger.error("Request timeout", { ...site, timeout });
|
|
370
|
-
return
|
|
382
|
+
return transportOutcome("timeout", `Request timeout after ${timeout}ms`, 408, site.url);
|
|
371
383
|
}
|
|
372
384
|
const errorMessage = error instanceof Error ? error.message : "Network error";
|
|
373
385
|
apiLogger.error("Network error", {
|
|
@@ -375,7 +387,29 @@ function transportError(failure, site, timeout) {
|
|
|
375
387
|
error: errorMessage,
|
|
376
388
|
errorName: error instanceof Error ? error.name : "unknown"
|
|
377
389
|
});
|
|
378
|
-
return
|
|
390
|
+
return transportOutcome("network", errorMessage, 0, site.url);
|
|
391
|
+
}
|
|
392
|
+
function notifyOutcome(onOutcome, outcome) {
|
|
393
|
+
if (!onOutcome) {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
const returned = onOutcome(outcome);
|
|
398
|
+
if (isThenable(returned)) {
|
|
399
|
+
Promise.resolve(returned).catch(logObserverFailure);
|
|
400
|
+
}
|
|
401
|
+
} catch (error) {
|
|
402
|
+
logObserverFailure(error);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
function isThenable(value) {
|
|
406
|
+
return typeof value?.then === "function";
|
|
407
|
+
}
|
|
408
|
+
function logObserverFailure(error) {
|
|
409
|
+
apiLogger.error("onOutcome observer failed; the call result is unchanged", {
|
|
410
|
+
errorName: error instanceof Error ? error.name : typeof error,
|
|
411
|
+
errorMessage: error instanceof Error ? error.message : String(error)
|
|
412
|
+
});
|
|
379
413
|
}
|
|
380
414
|
function createApi(config = {}) {
|
|
381
415
|
const {
|
|
@@ -385,6 +419,7 @@ function createApi(config = {}) {
|
|
|
385
419
|
fetch: customFetch = fetch,
|
|
386
420
|
onRequest: globalOnRequest,
|
|
387
421
|
onResponse: globalOnResponse,
|
|
422
|
+
onOutcome,
|
|
388
423
|
errorRegistry: errorRegistryConfig,
|
|
389
424
|
debug = false
|
|
390
425
|
} = config;
|
|
@@ -399,7 +434,7 @@ function createApi(config = {}) {
|
|
|
399
434
|
let appUrl = env.SPFN_APP_URL || "";
|
|
400
435
|
if (!appUrl && typeof window === "undefined") {
|
|
401
436
|
try {
|
|
402
|
-
const { headers: headers2 } = await import('next/headers');
|
|
437
|
+
const { headers: headers2 } = await import('next/headers.js');
|
|
403
438
|
const headersList = await headers2();
|
|
404
439
|
const host = headersList.get("host");
|
|
405
440
|
const protocol = headersList.get("x-forwarded-proto") || "http";
|
|
@@ -495,7 +530,9 @@ function createApi(config = {}) {
|
|
|
495
530
|
const appliedTimeout = options.timeout ?? timeout;
|
|
496
531
|
const fetched = await fetchInAbortScope(fullUrl, init, appliedTimeout, customFetch);
|
|
497
532
|
if (!fetched.ok) {
|
|
498
|
-
|
|
533
|
+
const outcome = transportError(fetched, { route: routeName, method, url: fullUrl }, appliedTimeout);
|
|
534
|
+
notifyOutcome(onOutcome, outcome);
|
|
535
|
+
throw outcome.error;
|
|
499
536
|
}
|
|
500
537
|
let { response, body } = fetched;
|
|
501
538
|
if (globalOnResponse) {
|
|
@@ -512,8 +549,11 @@ function createApi(config = {}) {
|
|
|
512
549
|
logResponse(apiLogger, routeName, response.status, !!body);
|
|
513
550
|
}
|
|
514
551
|
if (!response.ok) {
|
|
515
|
-
|
|
552
|
+
const error = errorFromResponse(response, body, fullUrl, errorRegistry$1, debug, apiLogger);
|
|
553
|
+
notifyOutcome(onOutcome, { ok: false, errorType: "http", status: response.status, error });
|
|
554
|
+
throw error;
|
|
516
555
|
}
|
|
556
|
+
notifyOutcome(onOutcome, { ok: true, response, body });
|
|
517
557
|
return body;
|
|
518
558
|
}
|
|
519
559
|
function buildProxy(prefix = "") {
|
package/dist/nextjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/nextjs/client/debug-logs.ts","../../src/nextjs/client/errors.ts","../../src/nextjs/shared.ts","../../src/nextjs/client/helpers.ts","../../src/nextjs/client/csrf.ts","../../src/nextjs/client/builder.ts","../../src/nextjs/client/core.ts"],"names":["logger","errorRegistry","coreErrorRegistry","headers"],"mappings":";;;;;;;AAMO,SAAS,sBAAA,CACZA,SACA,OAAA,EAEJ;AACI,EAAAA,OAAAA,CAAO,MAAM,sDAAA,EAAwD;AAAA,IACjE,aAAa,OAAA,CAAQ,MAAA;AAAA,IACrB,WAAA,EAAa,OAAA,CAAQ,GAAA,CAAI,CAAA,CAAA,KAAK,EAAE,IAAI;AAAA,GACvC,CAAA;AACL;AAEO,SAAS,UAAA,CACZA,OAAAA,EACA,SAAA,EACA,MAAA,EACA,KACA,OAAA,EAEJ;AACI,EAAAA,OAAAA,CAAO,MAAM,gBAAA,EAAa;AAAA,I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A,SAAS,UAAA,CAAW,SAAS,EAAA,EAC7B;AACI,IAAA,OAAO,IAAI,KAAA;AAAA,MACP,EAAC;AAAA,MACD;AAAA,QACI,GAAA,CAAI,SAAS,IAAA,EACb;AACI,UAAA,MAAM,cAAc,MAAA,GAAS,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,GAAK,IAAA;AAGnD,UAAA,OAAO,IAAI,gBAAA;AAAA,YACP,CAAC,KAAA,EAAY,OAAA,KAAyB,WAAA,CAAY,WAAA,EAAa,OAAO,OAAO,CAAA;AAAA,YAC7E;AAAA,WACJ;AAAA,QACJ;AAAA;AACJ,KACJ;AAAA,EACJ;AAEA,EAAA,OAAO,UAAA,EAAW;AACtB","file":"index.js","sourcesContent":["/**\n * Debug logging utilities for API client\n * Separates debug logging logic from main client code for better maintainability\n */\nimport type { Logger } from '@spfn/core/logger';\n\nexport function logCookieAutoDetection(\n logger: Logger,\n cookies: Array<{ name: string; value: string }>,\n): void\n{\n logger.debug('Auto-detected server environment, forwarding cookies', {\n cookieCount: cookies.length,\n cookieNames: cookies.map(c => c.name),\n });\n}\n\nexport function logRequest(\n logger: Logger,\n routeName: string,\n method: string,\n url: string,\n hasBody: boolean,\n): void\n{\n logger.debug('→ Request', {\n route: routeName,\n method,\n url,\n hasBody,\n });\n}\n\nexport function logResponse(\n logger: Logger,\n routeName: string,\n status: number,\n hasBody: boolean,\n): void\n{\n logger.debug('← Response', {\n route: routeName,\n status,\n hasBody,\n });\n}\n\nexport function logErrorResponse(\n logger: Logger,\n status: number,\n body: any,\n): void\n{\n logger.debug('Error response received', {\n status,\n hasBody: !!body,\n bodyType: typeof body,\n hasTypeField: body && typeof body === 'object' && '__type' in body,\n typeValue: body?.__type,\n });\n}\n\nexport function logErrorDeserializationAttempt(\n logger: Logger,\n errorType: string,\n registeredTypes: string[],\n): void\n{\n logger.debug('Attempting error deserialization', {\n errorType,\n hasRegistry: true,\n registeredTypes,\n });\n}\n\nexport function logErrorDeserializationSuccess(\n logger: Logger,\n error: Error | null,\n): void\n{\n logger.debug('Error deserialized successfully', {\n errorName: error?.name,\n errorConstructor: error?.constructor.name,\n message: error?.message,\n });\n}\n\nexport function logErrorDeserializationFailure(\n logger: Logger,\n error: unknown,\n): void\n{\n logger.debug('Deserialization failed', {\n errorName: error instanceof Error ? error.name : 'unknown',\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n}\n\nexport function logErrorDeserializationSkipped(\n logger: Logger,\n errorRegistry: any,\n body: any,\n): void\n{\n const reason = !errorRegistry\n ? 'no registry'\n : !body\n ? 'no body'\n : typeof body !== 'object'\n ? 'body not object'\n : !('__type' in body)\n ? 'no __type field'\n : 'unknown';\n\n logger.debug('Skipping error deserialization', { reason });\n}\n\nexport function logThrowingDeserializedError(\n logger: Logger,\n error: Error,\n): void\n{\n logger.debug('Throwing deserialized error', {\n errorName: error.name,\n errorConstructorName: error.constructor.name,\n prototype: Object.getPrototypeOf(error).constructor.name,\n });\n}\n","// ============================================================================\n// Client Error\n// ============================================================================\n\n/**\n * Typed client error\n *\n * `errorType` tells apart why a call failed:\n * - `'http'`: the server answered with a non-2xx status\n * - `'network'`: the fetch or the body read failed (status 0)\n * - `'timeout'`: the call's timeout elapsed before response headers arrived (status 408)\n * - `'aborted'`: the caller's own signal aborted the call (status 0); `cause` is the signal's reason\n */\nexport class ApiError extends Error\n{\n constructor(\n message: string,\n public readonly status: number,\n public readonly url: string,\n public readonly response?: unknown,\n public readonly errorType?: 'http' | 'network' | 'timeout' | 'aborted',\n options?: { cause?: unknown },\n )\n {\n super(message, options);\n this.name = 'ApiError';\n }\n}\n","/**\n * Shared utilities for Next.js client and proxy modules\n *\n * Contains common functions used by both client and proxy to avoid code duplication.\n */\n\n/**\n * Build URL with path parameters replaced\n *\n * @example\n * buildUrlWithParams('/users/:id/posts/:postId', { id: '123', postId: '456' })\n * // Returns: '/users/123/posts/456'\n */\nexport function buildUrlWithParams(path: string, params: Record<string, any>): string\n{\n let url = path;\n for (const [key, value] of Object.entries(params))\n {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n return url;\n}\n\n/**\n * Build query string from object\n *\n * @example\n * buildQueryString({ page: '1', limit: '10', tags: ['foo', 'bar'] })\n * // Returns: '?page=1&limit=10&tags=foo&tags=bar'\n */\nexport function buildQueryString(query: Record<string, any>): string\n{\n if (Object.keys(query).length === 0)\n {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query))\n {\n if (Array.isArray(value))\n {\n value.forEach((v) => searchParams.append(key, String(v)));\n }\n else\n {\n searchParams.append(key, String(value));\n }\n }\n\n return `?${searchParams.toString()}`;\n}\n\n/**\n * Build Cookie header string from cookies object\n *\n * @example\n * buildCookieHeader({ session: 'abc123', theme: 'dark' })\n * // Returns: 'session=abc123; theme=dark'\n */\nexport function buildCookieHeader(cookies: Record<string, string>): string\n{\n return Object.entries(cookies)\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n}\n\n/**\n * Parse response body based on content type\n *\n * Handles:\n * - 204 No Content: returns null (no body expected)\n * - application/json: parses JSON body\n * - Other content types: returns raw text\n */\nexport async function parseResponseBody(response: Response): Promise<any>\n{\n // 204 No Content has no body\n if (response.status === 204)\n {\n return null;\n }\n\n const contentType = response.headers.get('content-type');\n\n if (contentType?.includes('application/json'))\n {\n const text = await response.text();\n\n return text ? JSON.parse(text) : null;\n }\n else\n {\n return await response.text();\n }\n}\n","import type { Logger } from '@spfn/core/logger';\nimport type { ErrorRegistry } from '@spfn/core/errors';\nimport { logger } from '@spfn/core/logger';\nimport { ApiError } from './errors';\nimport * as debugLogs from './debug-logs';\nimport { parseResponseBody } from '../shared';\n\n// Re-export shared utilities\nexport { buildCookieHeader, parseResponseBody } from '../shared';\n\nconst cookieLogger = logger.child('@spfn/core:auto-cookies');\n\n/**\n * Auto-detect cookies from Next.js server environment\n * Returns empty object if not in server environment or if cookies are not accessible\n */\nexport async function autoDetectServerCookies(): Promise<Record<string, string>>\n{\n // Client environment — browser sends cookies automatically\n if (typeof window !== 'undefined')\n {\n return {};\n }\n\n try\n {\n // Next.js cookies() API is only available in server environment\n const { cookies } = await import('next/headers');\n const cookieStore = await cookies();\n const allCookies = cookieStore.getAll();\n\n const result = Object.fromEntries(\n allCookies.map(cookie => [cookie.name, cookie.value]),\n );\n\n cookieLogger.debug('Server cookies detected', {\n count: allCookies.length,\n names: allCookies.map(c => c.name),\n });\n\n return result;\n }\n catch (error)\n {\n // Server environment but cookies() not accessible\n // (e.g. static generation, build time, or outside request context)\n const err = error as Error;\n cookieLogger.warn('Failed to read server cookies', {\n message: err.message,\n name: err.name,\n });\n\n return {};\n }\n}\n\n/**\n * Why a call was aborted, as recorded by the abort scope that aborted it\n */\nexport type AbortCause = 'timeout' | 'caller';\n\n/**\n * What a fetch run in an abort scope produced: the response and its parsed body,\n * or the failure together with the abort cause the scope recorded, if any. For a\n * caller abort, `error` is the caller signal's reason.\n */\nexport type ScopedFetchResult =\n | { ok: true; response: Response; body: any }\n | { ok: false; error: unknown; cause?: AbortCause };\n\n/**\n * One controller that two sources may abort: the call's timer and the caller's signal\n *\n * The first source to fire is recorded as the cause and later ones are ignored, so a\n * caller aborting after the timer fired still reads as a timeout. Composed by hand\n * rather than with `AbortSignal.any` / `AbortSignal.timeout`, which browsers below\n * Safari 17.4 lack.\n */\nfunction openAbortScope(callerSignal: AbortSignal | undefined, timeout: number)\n{\n const controller = new AbortController();\n let cause: AbortCause | undefined;\n\n const abort = (source: AbortCause, reason?: unknown) =>\n {\n cause ??= source;\n controller.abort(reason);\n };\n const onCallerAbort = () => abort('caller', callerSignal?.reason);\n const timeoutId = setTimeout(() => abort('timeout'), timeout);\n\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n return {\n signal: controller.signal,\n cause: () => cause,\n stopTimer: () => clearTimeout(timeoutId),\n close: () =>\n {\n clearTimeout(timeoutId);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n },\n };\n}\n\n/**\n * Fetch and parse a response inside one abort scope\n *\n * The caller's signal is the one on the final `init`, after interceptors ran. The timer\n * stops when response headers arrive; the caller's abort stays effective until the body\n * is parsed. A failure is returned, not thrown, with the cause the scope recorded —\n * classification reads that record, never the error's name.\n *\n * A custom `fetch`'s body read may not honour the signal at all, so a caller abort during\n * that read can otherwise go unnoticed and the call resolves as if nothing happened. After\n * the body is parsed, the scope is checked again: a recorded `'caller'` cause still wins.\n */\nexport async function fetchInAbortScope(\n url: string,\n init: RequestInit,\n timeout: number,\n customFetch: typeof fetch = fetch,\n): Promise<ScopedFetchResult>\n{\n const callerSignal = init.signal ?? undefined;\n\n if (callerSignal?.aborted)\n {\n return { ok: false, error: callerSignal.reason, cause: 'caller' };\n }\n\n const scope = openAbortScope(callerSignal, timeout);\n\n try\n {\n const response = await customFetch(url, { ...init, signal: scope.signal });\n\n scope.stopTimer();\n\n const body = await parseResponseBody(response);\n\n if (scope.cause() === 'caller')\n {\n return { ok: false, error: callerSignal?.reason, cause: 'caller' };\n }\n\n return { ok: true, response, body };\n }\n catch (error)\n {\n const cause = scope.cause();\n\n return { ok: false, cause, error: cause === 'caller' ? callerSignal?.reason : error };\n }\n finally\n {\n scope.close();\n }\n}\n\n/**\n * Handle error response with deserialization support\n * Attempts to deserialize custom errors if errorRegistry is provided\n * Falls back to ApiError if deserialization fails or is not available\n */\nexport async function handleErrorResponse(\n response: Response,\n body: any,\n fullUrl: string,\n errorRegistry: ErrorRegistry | undefined,\n debug: boolean,\n logger: Logger,\n): Promise<never>\n{\n if (debug)\n {\n debugLogs.logErrorResponse(logger, response.status, body);\n }\n\n // Try to deserialize error if registry is provided\n let deserializedError: Error | null = null;\n\n if (errorRegistry && body && typeof body === 'object' && '__type' in body)\n {\n if (debug)\n {\n debugLogs.logErrorDeserializationAttempt(logger, body.__type, errorRegistry.getRegisteredTypes());\n }\n\n try\n {\n deserializedError = errorRegistry.deserialize(body as any);\n\n if (debug)\n {\n debugLogs.logErrorDeserializationSuccess(logger, deserializedError);\n }\n }\n catch (deserializeError)\n {\n // Deserialization itself failed (type not found, invalid data, etc.)\n if (debug)\n {\n debugLogs.logErrorDeserializationFailure(logger, deserializeError);\n }\n // Fall through to ApiError below\n }\n }\n else if (debug)\n {\n debugLogs.logErrorDeserializationSkipped(logger, errorRegistry, body);\n }\n\n // If deserialization succeeded, throw the deserialized error\n if (deserializedError)\n {\n if (debug)\n {\n debugLogs.logThrowingDeserializedError(logger, deserializedError);\n }\n\n throw deserializedError;\n }\n\n // Fallback to generic ApiError\n if (response.status === 404 && process.env.NODE_ENV !== 'production')\n {\n logger.warn(\n '\\n⚠️ 404 Not Found\\n\\n' +\n 'Check the following:\\n' +\n ' 1. Routes are registered in server.config.ts:\\n' +\n ' → defineServerConfig().routes(appRouter)\\n' +\n ' 2. Delete .spfn cache if you recently added new routes:\\n' +\n ' → rm -rf .spfn\\n',\n );\n }\n\n throw new ApiError(\n body?.message || `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n fullUrl,\n body,\n 'http',\n );\n}\n","/**\n * CSRF token transport for the RPC client\n *\n * The Next.js proxy sets a readable (non-HttpOnly) cookie carrying an HMAC of\n * the session's key id; this module mirrors it into a request header. The proxy\n * never compares cookie against header — it recomputes the value from the\n * session — so the cookie is transport only and reading it here is not a trust\n * decision. See the CSRF section of the @spfn/auth README.\n */\n\n/**\n * Header the readable CSRF cookie is mirrored into.\n *\n * Must match CSRF_HEADER in @spfn/auth. It is duplicated rather than imported\n * because @spfn/core cannot depend on @spfn/auth.\n */\nexport const CSRF_HEADER = 'x-spfn-csrf';\n\n/**\n * Cookie names carrying a CSRF token.\n *\n * @spfn/auth suffixes its cookie names with the server port so several local dev\n * instances on the same host do not overwrite each other's session, and the\n * browser cannot know that port — so match the family, not one name. Every\n * candidate is sent and the proxy accepts the request if any of them recomputes\n * to the expected value; a candidate an attacker tossed in never will.\n */\nconst CSRF_COOKIE_PATTERN = /^spfn_csrf(_\\d+)?$/;\n\n/**\n * Values that can be put in a header at all: printable ASCII, no space.\n *\n * A cookie jar is attacker-writable in the very case this feature exists for, and\n * `new Headers()` rejects a value outside Latin-1 — so a sibling subdomain that\n * tosses `spfn_csrf=한` would make every RPC call throw before it was sent, not\n * merely fail the check. A genuine token is 64 hex characters; anything that\n * cannot be a header value cannot be one.\n */\nconst HEADER_SAFE_VALUE = /^[!-~]+$/;\n\n/**\n * Upper bound on candidates sent, so a cookie-flooded jar stays a bounded header.\n *\n * Deliberately generous. The server recomputes the expected value once and then\n * only compares fixed-length strings, so extra candidates cost it almost nothing,\n * while every candidate dropped here is a chance to lock the user out of every\n * mutation — the far worse failure. Must not exceed the matching bound in\n * @spfn/auth's `matchesCsrfToken`, or values sent would never be looked at.\n */\nconst MAX_CANDIDATES = 32;\n\n/**\n * Choose which candidates to send when the jar holds more than the cap.\n *\n * `document.cookie` exposes neither Domain nor Path, so a tossed cookie is\n * indistinguishable from the genuine one here — the proxy is what tells them\n * apart, by recomputing. What this can do is refuse to drop the genuine value on\n * the floor. Browsers order the jar by path length descending, then by age\n * ascending, so a flood pushes the genuine cookie towards the end (attacker\n * cookies on a longer path) or towards the start (attacker cookies written later\n * on the same path). Keeping both ends survives either, where a plain prefix\n * survives only one.\n *\n * A jar flooded far past the cap is a denial of service that no client-side\n * choice fully prevents; the structural fix is a `__Host-` prefixed cookie name,\n * which a sibling subdomain cannot write at all.\n */\nfunction selectCandidates(values: string[]): string[]\n{\n // Identical duplicates carry no extra information, so collapsing them buys\n // back slots that a flood of one repeated value would otherwise burn.\n const unique = Array.from(new Set(values));\n\n if (unique.length <= MAX_CANDIDATES)\n {\n return unique;\n }\n\n const half = MAX_CANDIDATES / 2;\n\n return [...unique.slice(0, half), ...unique.slice(-half)];\n}\n\n/**\n * Collect the CSRF token candidates from cookie entries.\n *\n * Takes entries rather than a map because a name can legitimately appear twice:\n * a sibling subdomain that tosses `spfn_csrf` for the parent domain leaves the\n * browser holding two cookies of that name, and folding them into a map would\n * throw away whichever the tossed one displaced — locking the user out of every\n * mutation. Sending both keeps the real one in play, and the tossed one is inert\n * because the proxy recomputes what it expects.\n *\n * @returns Header value (comma-separated), or undefined when no cookie exists\n */\nexport function csrfHeaderValue(cookies: Iterable<[string, string]>): string | undefined\n{\n // A comma separates candidates on the wire, so a value containing one would\n // arrive as several. That cannot be a genuine token — they are hex — but it\n // would let a single tossed cookie spend the receiver's whole candidate\n // budget and bury the real value behind it. Drop those, and anything that\n // could not be a header value at all.\n const values = Array.from(cookies)\n .filter(([name, value]) => CSRF_COOKIE_PATTERN.test(name)\n && HEADER_SAFE_VALUE.test(value)\n && !value.includes(','))\n .map(([, value]) => value);\n\n const candidates = selectCandidates(values);\n\n return candidates.length > 0 ? candidates.join(',') : undefined;\n}\n\n/**\n * Read the browser cookie jar as entries, duplicates preserved.\n *\n * Empty outside a browser (SSR reads the jar it forwards instead).\n */\nexport function documentCookieEntries(): Array<[string, string]>\n{\n if (typeof document === 'undefined' || !document.cookie)\n {\n return [];\n }\n\n const entries: Array<[string, string]> = [];\n\n for (const pair of document.cookie.split(';'))\n {\n const separator = pair.indexOf('=');\n\n if (separator > 0)\n {\n entries.push([pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()]);\n }\n }\n\n return entries;\n}\n","// ============================================================================\n// Route Call Builder (Structured Input API)\n// ============================================================================\n\nimport type { RouteDef, Router } from '@spfn/core/route';\nimport type {\n CallOptions,\n ExtractRoutes,\n InferRouteInput,\n InferRouteOutput,\n RequestInterceptor,\n ResponseInterceptor,\n} from './types';\n\n/**\n * Pick only non-empty fields from StructuredInput\n *\n * This removes fields that are empty objects `{}` from the input type,\n * so users only need to provide fields that are actually defined in the route.\n */\ntype PickNonEmpty<T> = {\n [K in keyof T as T[K] extends Record<string, never> ? never : K]: T[K];\n};\n\n/**\n * Make fields that can be undefined into optional fields\n *\n * When a field is defined as `Type.Optional(Type.Object({...}))`,\n * the resulting type is `T | undefined`. This utility converts such fields\n * into proper optional fields (`field?: T`) so users don't need to pass them.\n */\ntype MakeOptionalIfUndefinable<T> =\n // Required fields (undefined is not assignable)\n { [K in keyof T as undefined extends T[K] ? never : K]: T[K] }\n // Optional fields (undefined is assignable)\n & { [K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined> };\n\n/**\n * Clean structured input - only include fields that have actual schema,\n * and make fields optional if they accept undefined\n */\ntype CleanStructuredInput<TInput> = MakeOptionalIfUndefinable<PickNonEmpty<TInput>>;\n\n/**\n * Check if input has any required fields\n *\n * Returns false if all fields are optional (i.e., {} is assignable to the input type)\n */\ntype HasAnyRequiredFields<TInput> = {} extends CleanStructuredInput<TInput> ? false : true;\n\n/**\n * Largest delay `setTimeout` honours; a longer one fires immediately\n */\nconst MAX_TIMEOUT_MS = 2147483647;\n\n/**\n * Route call builder with structured input API\n *\n * Input is structured with explicit params, query, body fields\n * that match the server-side route definition.\n *\n * @example\n * ```typescript\n * // GET /users/:id - params only\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // GET /users/:id?include=posts - params + query\n * const user = await api.getUser.call({\n * params: { id: '1' },\n * query: { include: 'posts' }\n * });\n *\n * // POST /users - body only\n * const user = await api.createUser.call({\n * body: { name: 'John', email: 'john@example.com' }\n * });\n *\n * // PUT /users/:id - params + body\n * const user = await api.updateUser.call({\n * params: { id: '1' },\n * body: { name: 'Jane' }\n * });\n *\n * // With options (headers, cookies, Next.js caching)\n * const user = await api.getUser\n * .headers({ 'X-Custom': 'value' })\n * .fetchOptions({ next: { revalidate: 60 } })\n * .call({ params: { id: '1' } });\n * ```\n */\nexport class RouteCallBuilder<\n TInput,\n TOutput,\n>\n{\n private _headers?: Record<string, string>;\n private _cookies?: Record<string, string>;\n private _fetchOptions?: RequestInit;\n private _timeout?: number;\n private _onRequest?: RequestInterceptor;\n private _onResponse?: ResponseInterceptor;\n\n constructor(\n private readonly executor: (input: any, options: CallOptions) => Promise<TOutput>,\n private readonly routeName: string,\n ) \n {}\n\n /**\n * Clone builder\n */\n private clone(): RouteCallBuilder<TInput, TOutput>\n {\n const builder = new RouteCallBuilder<TInput, TOutput>(\n this.executor,\n this.routeName,\n );\n builder._headers = this._headers;\n builder._cookies = this._cookies;\n builder._fetchOptions = this._fetchOptions;\n builder._timeout = this._timeout;\n builder._onRequest = this._onRequest;\n builder._onResponse = this._onResponse;\n\n return builder;\n }\n\n /**\n * Set request headers\n */\n headers(headers: Record<string, string>): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._headers = { ...this._headers, ...headers };\n\n return builder;\n }\n\n /**\n * Set cookies\n */\n cookies(cookies: Record<string, string>): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._cookies = { ...this._cookies, ...cookies };\n\n return builder;\n }\n\n /**\n * Set Next.js fetch options\n */\n fetchOptions(options: RequestInit & { next?: { revalidate?: number | false; tags?: string[] } }): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._fetchOptions = { ...this._fetchOptions, ...options };\n\n return builder;\n }\n\n /**\n * Set this call's timeout in milliseconds, overriding the client-wide one\n *\n * Throws a `TypeError`, before any request is made, unless `ms` is a finite number\n * greater than 0 and at most 2147483647 (the largest delay `setTimeout` honours).\n */\n timeout(ms: number): RouteCallBuilder<TInput, TOutput>\n {\n if (!Number.isFinite(ms) || ms <= 0 || ms > MAX_TIMEOUT_MS)\n {\n throw new TypeError(`timeout must be a finite number of milliseconds in (0, ${MAX_TIMEOUT_MS}], got ${String(ms)}`);\n }\n\n const builder = this.clone();\n builder._timeout = ms;\n\n return builder;\n }\n\n /**\n * Set request interceptor\n */\n onRequest(interceptor: RequestInterceptor): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._onRequest = interceptor;\n\n return builder;\n }\n\n /**\n * Set response interceptor\n */\n onResponse(interceptor: ResponseInterceptor): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._onResponse = interceptor;\n\n return builder;\n }\n\n /**\n * Execute the API call with structured input\n *\n * Input structure matches the server-side route definition:\n * - params: Path parameters (e.g., { id: '123' } for /users/:id)\n * - query: Query string parameters\n * - body: Request body (for POST, PUT, PATCH)\n */\n call(input?: CleanStructuredInput<TInput>): Promise<TOutput>\n {\n const options: CallOptions = {};\n\n if (this._headers)\n {\n options.headers = this._headers;\n }\n\n if (this._cookies)\n {\n options.cookies = this._cookies;\n }\n\n if (this._fetchOptions)\n {\n options.fetchOptions = this._fetchOptions;\n }\n\n if (this._timeout !== undefined)\n {\n options.timeout = this._timeout;\n }\n\n if (this._onRequest)\n {\n options.onRequest = this._onRequest;\n }\n\n if (this._onResponse)\n {\n options.onResponse = this._onResponse;\n }\n\n return this.executor(input || {}, options);\n }\n}\n\n/**\n * Individual route client with structured input API\n */\nexport type RouteClient<TRoute extends RouteDef<any, any>> = {\n /**\n * Set request headers\n */\n headers(headers: Record<string, string>): RouteClient<TRoute>;\n\n /**\n * Set cookies\n */\n cookies(cookies: Record<string, string>): RouteClient<TRoute>;\n\n /**\n * Set Next.js fetch options\n */\n fetchOptions(options: RequestInit & { next?: { revalidate?: number | false; tags?: string[] } }): RouteClient<TRoute>;\n\n /**\n * Set this call's timeout in milliseconds, overriding the client-wide one.\n * Throws a `TypeError` unless `ms` is finite, `> 0` and `<= 2147483647`.\n */\n timeout(ms: number): RouteClient<TRoute>;\n\n /**\n * Set request interceptor\n */\n onRequest(interceptor: RequestInterceptor): RouteClient<TRoute>;\n\n /**\n * Set response interceptor\n */\n onResponse(interceptor: ResponseInterceptor): RouteClient<TRoute>;\n\n /**\n * Execute the API call with structured input\n *\n * @example\n * ```typescript\n * // GET /users/:id\n * api.getUser.call({ params: { id: '123' } });\n *\n * // PUT /users/:id\n * api.updateUser.call({ params: { id: '123' }, body: { name: 'Jane' } });\n * ```\n */\n call: HasAnyRequiredFields<InferRouteInput<TRoute>> extends true\n ? (input: CleanStructuredInput<InferRouteInput<TRoute>>) => Promise<InferRouteOutput<TRoute>>\n : (input?: CleanStructuredInput<InferRouteInput<TRoute>>) => Promise<InferRouteOutput<TRoute>>;\n};\n\n/**\n * One property per route in a flattened route record.\n *\n * A slot the flattening could not resolve to a route definition is `never`, as it was\n * before nesting was flattened — a record whose values are neither routes nor routers\n * names nothing callable.\n */\ntype RouteClients<TRoutes> = {\n [K in keyof TRoutes]: TRoutes[K] extends RouteDef<any, any, any>\n ? RouteClient<TRoutes[K]>\n : never;\n};\n\n/**\n * Typed client for entire router\n *\n * One flat namespace, holding the same route names the server registers. A route\n * declared inside a nested `defineRouter` is reached by its own key — `api.getThing`,\n * never `api.group.getThing` — because that is the name `registerRoutes` mounts it\n * under, the name the RPC proxy resolves, and the name `RouterOutput` takes. The group\n * key is not a route and naming it is a compile error.\n *\n * @example\n * ```typescript\n * const appRouter = defineRouter({\n * getRoot,\n * users: defineRouter({ getUser }),\n * });\n *\n * const api = createApi<typeof appRouter>();\n *\n * await api.getUser.call({ params: { id: '1' } }); // not api.users.getUser\n * ```\n *\n * A name two branches both declare is left out of the namespace rather than resolved to\n * one of them — the same collision `RouterOutput` refuses. Routes mounted with\n * `.packages()` are deliberately absent: a package publishes its own route map and its\n * own client (`authApi`, `cmsApi`), and that is what calls them.\n */\nexport type Client<TRouter extends Router<any>> = RouteClients<ExtractRoutes<TRouter>>;\n","/**\n * Type-Safe RPC-Style Client with Structured Input API\n *\n * Provides full end-to-end type safety from server routes to client calls.\n * No metadata codegen required - method/path resolution happens at the proxy layer.\n *\n * @example\n * ```typescript\n * // Server\n * export const appRouter = defineRouter({\n * getUser: route.get('/users/:id')\n * .input({ params: Type.Object({ id: Type.String() }) })\n * .handler(async (c) => { ... }),\n * createUser: route.post('/users')\n * .input({ body: Type.Object({ name: Type.String() }) })\n * .handler(async (c) => { ... }),\n * });\n *\n * export type AppRouter = typeof appRouter;\n *\n * // Client - no metadata needed!\n * const api = createApi<AppRouter>();\n *\n * // ✅ GET (no body) - becomes GET /api/rpc/getUser?input={...}\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // ✅ POST (has body) - becomes POST /api/rpc/createUser\n * const newUser = await api.createUser.call({ body: { name: 'John' } });\n *\n * // ✅ With options (headers, cookies, interceptors)\n * const user = await api.getUser\n * .headers({ 'X-Custom': 'value' })\n * .cookies({ session: 'xxx' })\n * .fetchOptions({ next: { revalidate: 60 } })\n * .call({ params: { id: '1' } });\n * ```\n */\nimport { env } from '@spfn/core/config';\nimport { ErrorRegistry, errorRegistry as coreErrorRegistry } from '@spfn/core/errors';\nimport { logger } from '@spfn/core/logger';\nimport type { Router } from '@spfn/core/route';\nimport * as debugLogs from './debug-logs';\nimport { ApiError } from './errors';\nimport {\n fetchInAbortScope,\n handleErrorResponse,\n buildCookieHeader,\n autoDetectServerCookies,\n} from './helpers';\nimport { CSRF_HEADER, csrfHeaderValue, documentCookieEntries } from './csrf';\nimport { RouteCallBuilder } from './builder';\nimport type { ScopedFetchResult } from './helpers';\nimport type { ApiConfig, CallOptions } from './types';\nimport type { Client } from './builder';\n\nconst apiLogger = logger.child('@spfn/core:api-client');\n\n/**\n * Where a failed call went, for the log line its transport error writes\n */\ninterface CallSite\n{\n route: string;\n method: string;\n url: string;\n}\n\n/**\n * Classify a failed fetch by the abort cause its scope recorded\n *\n * - timeout → 408 `'timeout'`, reporting the applied timeout\n * - caller abort → status 0 `'aborted'`, the signal's reason as `cause`; logged at debug\n * level, since it is the caller's own intent\n * - no cause recorded but the error is a plain `AbortError` (a custom `fetch` aborting its\n * own controller, with neither our timer nor the caller's signal involved) → 408\n * `'timeout'`, as it always was before the scope recorded a cause\n * - anything else → status 0 `'network'`\n */\nfunction transportError(\n failure: Extract<ScopedFetchResult, { ok: false }>,\n site: CallSite,\n timeout: number,\n): ApiError\n{\n if (failure.cause === 'timeout')\n {\n apiLogger.error('Request timeout', { ...site, timeout });\n\n return new ApiError(`Request timeout after ${timeout}ms`, 408, site.url, undefined, 'timeout');\n }\n\n if (failure.cause === 'caller')\n {\n apiLogger.debug('Request aborted by caller', site);\n\n return new ApiError('Request aborted', 0, site.url, undefined, 'aborted', { cause: failure.error });\n }\n\n const { error } = failure;\n\n if (error instanceof Error && error.name === 'AbortError')\n {\n apiLogger.error('Request timeout', { ...site, timeout });\n\n return new ApiError(`Request timeout after ${timeout}ms`, 408, site.url, undefined, 'timeout');\n }\n\n const errorMessage = error instanceof Error ? error.message : 'Network error';\n apiLogger.error('Network error', {\n ...site,\n error: errorMessage,\n errorName: error instanceof Error ? error.name : 'unknown',\n });\n\n return new ApiError(errorMessage, 0, site.url, undefined, 'network');\n}\n\n// ============================================================================\n// Client Implementation\n// ============================================================================\n\n/**\n * Create type-safe RPC client\n *\n * No metadata required - the client sends routeName + input to the proxy,\n * and the proxy resolves the actual HTTP method and path from the router.\n *\n * @example\n * ```typescript\n * // Client - no metadata needed!\n * const api = createApi<AppRouter>();\n *\n * // GET request (no body) - browser cacheable\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // POST request (has body)\n * const newUser = await api.createUser.call({ body: { name: 'John' } });\n * ```\n */\nexport function createApi<TRouter extends Router<any>>(\n config: ApiConfig = {},\n): Client<TRouter>\n{\n const {\n baseUrl = '/api/rpc',\n headers: defaultHeaders = {},\n timeout = env.SERVER_TIMEOUT,\n fetch: customFetch = fetch,\n onRequest: globalOnRequest,\n onResponse: globalOnResponse,\n errorRegistry: errorRegistryConfig,\n debug = false,\n } = config;\n\n // Normalize errorRegistry: always include coreErrorRegistry\n const errorRegistry = Array.isArray(errorRegistryConfig)\n ? new ErrorRegistry([coreErrorRegistry, ...errorRegistryConfig])\n : errorRegistryConfig ?? coreErrorRegistry;\n\n if (debug)\n {\n apiLogger.debug('API client initialized', { baseUrl });\n }\n\n /**\n * Execute API call\n *\n * Determines GET vs POST based on body/formData presence:\n * - No body/formData → GET /api/rpc/{routeName}?input={...}\n * - Has body → POST /api/rpc/{routeName} with JSON body\n * - Has formData → POST /api/rpc/{routeName} with multipart/form-data\n */\n async function executeCall(\n routeName: string,\n input: any = {},\n options: CallOptions = {},\n ): Promise<any>\n {\n const hasBody = input.body !== undefined;\n const hasFormData = input.formData !== undefined && Object.keys(input.formData).length > 0;\n const method = (hasBody || hasFormData) ? 'POST' : 'GET';\n\n // Build full URL - handle SSR case where SPFN_APP_URL might not be set\n let appUrl = env.SPFN_APP_URL || '';\n\n // In SSR environment, if SPFN_APP_URL is not set, try to get host from request headers\n if (!appUrl && typeof window === 'undefined')\n {\n try\n {\n const { headers } = await import('next/headers');\n const headersList = await headers();\n const host = headersList.get('host');\n const protocol = headersList.get('x-forwarded-proto') || 'http';\n if (host)\n {\n appUrl = `${protocol}://${host}`;\n if (debug)\n {\n apiLogger.debug(`Auto-detected app URL from headers: ${appUrl}`);\n }\n }\n }\n catch\n {\n // Fallback: use relative URL and let fetch handle it\n if (debug)\n {\n apiLogger.warn('Could not determine app URL in SSR environment, using relative URL');\n }\n }\n }\n\n // Build URL based on method\n let fullUrl: string;\n if (method === 'GET')\n {\n // GET: encode input in query string\n const inputParam = encodeURIComponent(JSON.stringify(input));\n fullUrl = `${appUrl}${baseUrl}/${routeName}?input=${inputParam}`;\n }\n else\n {\n // POST: input goes in body\n fullUrl = `${appUrl}${baseUrl}/${routeName}`;\n }\n\n // Prepare headers\n // Note: Don't set Content-Type for formData - browser sets it with boundary\n const headers: Record<string, string> = {\n ...(hasFormData ? {} : { 'Content-Type': 'application/json' }),\n ...defaultHeaders,\n ...options.headers,\n };\n\n // Auto-detect server cookies and merge with user-provided cookies\n const autoDetectedCookies = await autoDetectServerCookies();\n const cookiesToSend = {\n ...autoDetectedCookies,\n ...(options.cookies || {}),\n };\n\n // Add Cookie header if we have cookies to send\n if (Object.keys(cookiesToSend).length > 0)\n {\n headers['Cookie'] = buildCookieHeader(cookiesToSend);\n }\n\n // Mirror the readable CSRF cookie into a header, from the browser jar or\n // — server-side — from the jar being forwarded.\n //\n // Carried on GET calls too, deliberately: the wire method here is chosen\n // by whether the input has a body, not by what the route does. A bodyless\n // mutation (`api.logout.call({})`) travels as GET and the proxy still\n // forwards it as the route's POST, so a GET-shaped call can be exactly\n // the request that needs the header. The proxy decides what to check from\n // the resolved route method, and ignores the header on safe routes.\n const csrfToken = csrfHeaderValue(\n typeof window === 'undefined' ? Object.entries(cookiesToSend) : documentCookieEntries(),\n );\n\n const csrfSetByCaller = Object.keys(headers).some(name => name.toLowerCase() === CSRF_HEADER);\n\n if (csrfToken && !csrfSetByCaller)\n {\n headers[CSRF_HEADER] = csrfToken;\n }\n\n // Log cookie auto-detection if debug enabled\n if (debug && Object.keys(autoDetectedCookies).length > 0)\n {\n const cookieArray = Object.entries(autoDetectedCookies).map(([name, value]) => ({ name, value }));\n debugLogs.logCookieAutoDetection(apiLogger, cookieArray);\n }\n\n // Build request init\n const requestInit: RequestInit = {\n method,\n headers,\n ...options.fetchOptions,\n };\n\n // Add body for POST\n if (method === 'POST')\n {\n if (hasFormData)\n {\n // Build FormData for file uploads\n const formData = new FormData();\n\n // Add non-formData fields (params, query, headers, cookies) as JSON metadata\n const metadata: Record<string, any> = {};\n if (input.params) metadata.params = input.params;\n if (input.query) metadata.query = input.query;\n if (input.headers) metadata.headers = input.headers;\n if (input.cookies) metadata.cookies = input.cookies;\n\n if (Object.keys(metadata).length > 0)\n {\n formData.append('__metadata', JSON.stringify(metadata));\n }\n\n // Add formData fields\n for (const [key, value] of Object.entries(input.formData))\n {\n if (value instanceof File)\n {\n formData.append(key, value);\n }\n else if (Array.isArray(value))\n {\n // Handle array of files or values\n for (const item of value)\n {\n if (item instanceof File)\n {\n formData.append(key, item);\n }\n else\n {\n formData.append(key, String(item));\n }\n }\n }\n else if (value !== undefined && value !== null)\n {\n formData.append(key, String(value));\n }\n }\n\n requestInit.body = formData;\n }\n else\n {\n requestInit.body = JSON.stringify(input);\n }\n }\n\n // Execute request interceptors\n let init = requestInit;\n if (globalOnRequest)\n {\n init = await globalOnRequest(fullUrl, init);\n }\n if (options.onRequest)\n {\n init = await options.onRequest(fullUrl, init);\n }\n\n if (debug)\n {\n debugLogs.logRequest(apiLogger, routeName, method, fullUrl, !!init.body);\n }\n\n // Execute fetch and parse the body inside one abort scope\n const appliedTimeout = options.timeout ?? timeout;\n const fetched = await fetchInAbortScope(fullUrl, init, appliedTimeout, customFetch);\n\n if (!fetched.ok)\n {\n throw transportError(fetched, { route: routeName, method, url: fullUrl }, appliedTimeout);\n }\n\n let { response, body } = fetched;\n\n // Execute global + local response interceptors\n //\n // These run outside the abort scope on purpose. That scope classifies a transport\n // failure, and an interceptor throwing is not one: Next.js implements `redirect()`\n // and `notFound()` by throwing an error carrying a digest, and an interceptor\n // raising a domain error of its own is not a transport failure either. Run inside\n // it, every one of those became `ApiError(..., 0, ..., 'network')` — the\n // navigation never happened and the caller was handed a network failure that never\n // occurred, which retry and offline handling keyed on `errorType === 'network'`\n // act on.\n if (globalOnResponse)\n {\n const result = await globalOnResponse(response, body);\n response = result.response;\n body = result.body;\n }\n if (options.onResponse)\n {\n const result = await options.onResponse(response, body);\n response = result.response;\n body = result.body;\n }\n\n if (debug)\n {\n debugLogs.logResponse(apiLogger, routeName, response.status, !!body);\n }\n\n // Handle error responses\n if (!response.ok)\n {\n await handleErrorResponse(response, body, fullUrl, errorRegistry, debug, apiLogger);\n }\n\n return body;\n }\n\n /**\n * Build client proxy\n *\n * Every property access returns a `RouteCallBuilder` for that one property read as a\n * whole route name, and that name goes on the wire as `/api/rpc/{routeName}`. The\n * proxy route resolves it against the generated route map, whose names are flat.\n *\n * Nesting needs nothing here: `registerRoutes` mounts a route declared inside a\n * nested `defineRouter` under its own key, so `api.getThing` is the call for a nested\n * `getThing` exactly as for a top-level one — which is the namespace `Client` types.\n * There is no dot-notation traversal: a property access never returns another proxy,\n * so `api.group.getThing` reads a property of a builder and is `undefined`.\n *\n * `prefix` is vestigial — nothing passes one, and adding a caller that did would\n * build a dotted name the route map cannot resolve.\n */\n function buildProxy(prefix = ''): any\n {\n return new Proxy(\n {},\n {\n get(_target, prop: string)\n {\n const currentPath = prefix ? `${prefix}.${prop}` : prop;\n\n // Return RouteCallBuilder that can either be called or chained\n return new RouteCallBuilder(\n (input: any, options: CallOptions) => executeCall(currentPath, input, options),\n currentPath,\n );\n },\n },\n );\n }\n\n return buildProxy() as Client<TRouter>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/nextjs/client/debug-logs.ts","../../src/nextjs/client/errors.ts","../../src/nextjs/shared.ts","../../src/nextjs/client/helpers.ts","../../src/nextjs/client/csrf.ts","../../src/nextjs/client/builder.ts","../../src/nextjs/client/core.ts"],"names":["logger","errorRegistry","coreErrorRegistry","headers"],"mappings":";;;;;;;AAMO,SAAS,sBAAA,CACZA,SACA,OAAA,EAEJ;AACI,EAAAA,OAAAA,CAAO,MAAM,sDAAA,EAAwD;AAAA,IACjE,aAAa,OAAA,CAAQ,MAAA;AAAA,IACrB,WAAA,EAAa,OAAA,CAAQ,GAAA,CAAI,CAAA,CAAA,KAAK,EAAE,IAAI;AAAA,GACvC,CAAA;AACL;AAEO,SAAS,UAAA,CACZA,OAAAA,EACA,SAAA,EACA,MAAA,EACA,KACA,OAAA,EAEJ;AACI,EAAAA,OAAAA,CAAO,MAAM,gBAAA,EAAa;AAAA,IACtB,KAAA,EAAO,SAAA;AAAA,IACP,MAAA;AAAA,IACA,GAAA;AAAA,IACA;AAAA,GACH,CAAA;AACL;AAEO,SAAS,WAAA,CACZA,OAAAA,EACA,SAAA,EACA,MAAA,EACA,OAAA,EAEJ;AACI,EAAAA,OAAAA,CAAO,MAAM,iBAAA,EAAc;AAAA,IACvB,KAAA,EAAO,SAAA;AAAA,IACP,MAAA;AAAA,IACA;AAAA,GACH,CAAA;AACL;AAEO,SAAS,gBAAA,CACZA,OAAAA,EACA,MAAA,EACA,IAAA,EAEJ;AACI,EAAAA,OAAAA,CAAO,MAAM,yBAAA,EAA2B;AAAA,IACpC,MAAA;AAAA,IACA,OAAA,EAAS,CAAC,CAAC,IAAA;AAAA,IACX,UAAU,OAAO,IAAA;AAAA,IACjB,YAAA,EAAc,IAAA,IAAQ,OAAO,IAAA,KAAS,YAAY,QAAA,IAAY,IAAA;AAAA,IAC9D,WAAW,IAAA,EAAM;AAAA,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AA,MACP,EAAC;AAAA,MACD;AAAA,QACI,GAAA,CAAI,SAAS,IAAA,EACb;AACI,UAAA,MAAM,cAAc,MAAA,GAAS,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA,GAAK,IAAA;AAGnD,UAAA,OAAO,IAAI,gBAAA;AAAA,YACP,CAAC,KAAA,EAAY,OAAA,KAAyB,WAAA,CAAY,WAAA,EAAa,OAAO,OAAO,CAAA;AAAA,YAC7E;AAAA,WACJ;AAAA,QACJ;AAAA;AACJ,KACJ;AAAA,EACJ;AAEA,EAAA,OAAO,UAAA,EAAW;AACtB","file":"index.js","sourcesContent":["/**\n * Debug logging utilities for API client\n * Separates debug logging logic from main client code for better maintainability\n */\nimport type { Logger } from '@spfn/core/logger';\n\nexport function logCookieAutoDetection(\n logger: Logger,\n cookies: Array<{ name: string; value: string }>,\n): void\n{\n logger.debug('Auto-detected server environment, forwarding cookies', {\n cookieCount: cookies.length,\n cookieNames: cookies.map(c => c.name),\n });\n}\n\nexport function logRequest(\n logger: Logger,\n routeName: string,\n method: string,\n url: string,\n hasBody: boolean,\n): void\n{\n logger.debug('→ Request', {\n route: routeName,\n method,\n url,\n hasBody,\n });\n}\n\nexport function logResponse(\n logger: Logger,\n routeName: string,\n status: number,\n hasBody: boolean,\n): void\n{\n logger.debug('← Response', {\n route: routeName,\n status,\n hasBody,\n });\n}\n\nexport function logErrorResponse(\n logger: Logger,\n status: number,\n body: any,\n): void\n{\n logger.debug('Error response received', {\n status,\n hasBody: !!body,\n bodyType: typeof body,\n hasTypeField: body && typeof body === 'object' && '__type' in body,\n typeValue: body?.__type,\n });\n}\n\nexport function logErrorDeserializationAttempt(\n logger: Logger,\n errorType: string,\n registeredTypes: string[],\n): void\n{\n logger.debug('Attempting error deserialization', {\n errorType,\n hasRegistry: true,\n registeredTypes,\n });\n}\n\nexport function logErrorDeserializationSuccess(\n logger: Logger,\n error: Error | null,\n): void\n{\n logger.debug('Error deserialized successfully', {\n errorName: error?.name,\n errorConstructor: error?.constructor.name,\n message: error?.message,\n });\n}\n\nexport function logErrorDeserializationFailure(\n logger: Logger,\n error: unknown,\n): void\n{\n logger.debug('Deserialization failed', {\n errorName: error instanceof Error ? error.name : 'unknown',\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n}\n\nexport function logErrorDeserializationSkipped(\n logger: Logger,\n errorRegistry: any,\n body: any,\n): void\n{\n const reason = !errorRegistry\n ? 'no registry'\n : !body\n ? 'no body'\n : typeof body !== 'object'\n ? 'body not object'\n : !('__type' in body)\n ? 'no __type field'\n : 'unknown';\n\n logger.debug('Skipping error deserialization', { reason });\n}\n\nexport function logThrowingDeserializedError(\n logger: Logger,\n error: Error,\n): void\n{\n logger.debug('Throwing deserialized error', {\n errorName: error.name,\n errorConstructorName: error.constructor.name,\n prototype: Object.getPrototypeOf(error).constructor.name,\n });\n}\n","// ============================================================================\n// Client Error\n// ============================================================================\n\n/**\n * Typed client error\n *\n * `errorType` tells apart why a call failed:\n * - `'http'`: the server answered with a non-2xx status\n * - `'network'`: the fetch or the body read failed (status 0)\n * - `'timeout'`: the call's timeout elapsed before response headers arrived (status 408)\n * - `'aborted'`: the caller's own signal aborted the call (status 0); `cause` is the signal's reason\n */\nexport class ApiError extends Error\n{\n constructor(\n message: string,\n public readonly status: number,\n public readonly url: string,\n public readonly response?: unknown,\n public readonly errorType?: 'http' | 'network' | 'timeout' | 'aborted',\n options?: { cause?: unknown },\n )\n {\n super(message, options);\n this.name = 'ApiError';\n }\n}\n","/**\n * Shared utilities for Next.js client and proxy modules\n *\n * Contains common functions used by both client and proxy to avoid code duplication.\n */\n\n/**\n * Build URL with path parameters replaced\n *\n * @example\n * buildUrlWithParams('/users/:id/posts/:postId', { id: '123', postId: '456' })\n * // Returns: '/users/123/posts/456'\n */\nexport function buildUrlWithParams(path: string, params: Record<string, any>): string\n{\n let url = path;\n for (const [key, value] of Object.entries(params))\n {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n return url;\n}\n\n/**\n * Build query string from object\n *\n * @example\n * buildQueryString({ page: '1', limit: '10', tags: ['foo', 'bar'] })\n * // Returns: '?page=1&limit=10&tags=foo&tags=bar'\n */\nexport function buildQueryString(query: Record<string, any>): string\n{\n if (Object.keys(query).length === 0)\n {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query))\n {\n if (Array.isArray(value))\n {\n value.forEach((v) => searchParams.append(key, String(v)));\n }\n else\n {\n searchParams.append(key, String(value));\n }\n }\n\n return `?${searchParams.toString()}`;\n}\n\n/**\n * Build Cookie header string from cookies object\n *\n * @example\n * buildCookieHeader({ session: 'abc123', theme: 'dark' })\n * // Returns: 'session=abc123; theme=dark'\n */\nexport function buildCookieHeader(cookies: Record<string, string>): string\n{\n return Object.entries(cookies)\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n}\n\n/**\n * Parse response body based on content type\n *\n * Handles:\n * - 204 No Content: returns null (no body expected)\n * - application/json: parses JSON body\n * - Other content types: returns raw text\n */\nexport async function parseResponseBody(response: Response): Promise<any>\n{\n // 204 No Content has no body\n if (response.status === 204)\n {\n return null;\n }\n\n const contentType = response.headers.get('content-type');\n\n if (contentType?.includes('application/json'))\n {\n const text = await response.text();\n\n return text ? JSON.parse(text) : null;\n }\n else\n {\n return await response.text();\n }\n}\n","import type { Logger } from '@spfn/core/logger';\nimport type { ErrorRegistry } from '@spfn/core/errors';\nimport { logger } from '@spfn/core/logger';\nimport { ApiError } from './errors';\nimport * as debugLogs from './debug-logs';\nimport { parseResponseBody } from '../shared';\n\n// Re-export shared utilities\nexport { buildCookieHeader, parseResponseBody } from '../shared';\n\nconst cookieLogger = logger.child('@spfn/core:auto-cookies');\n\n/**\n * Auto-detect cookies from Next.js server environment\n * Returns empty object if not in server environment or if cookies are not accessible\n */\nexport async function autoDetectServerCookies(): Promise<Record<string, string>>\n{\n // Client environment — browser sends cookies automatically\n if (typeof window !== 'undefined')\n {\n return {};\n }\n\n try\n {\n // Next.js cookies() API is only available in server environment\n const { cookies } = await import('next/headers.js');\n const cookieStore = await cookies();\n const allCookies = cookieStore.getAll();\n\n const result = Object.fromEntries(\n allCookies.map(cookie => [cookie.name, cookie.value]),\n );\n\n cookieLogger.debug('Server cookies detected', {\n count: allCookies.length,\n names: allCookies.map(c => c.name),\n });\n\n return result;\n }\n catch (error)\n {\n // Server environment but cookies() not accessible\n // (e.g. static generation, build time, or outside request context)\n const err = error as Error;\n cookieLogger.warn('Failed to read server cookies', {\n message: err.message,\n name: err.name,\n });\n\n return {};\n }\n}\n\n/**\n * Why a call was aborted, as recorded by the abort scope that aborted it\n */\nexport type AbortCause = 'timeout' | 'caller';\n\n/**\n * What a fetch run in an abort scope produced: the response and its parsed body,\n * or the failure together with the abort cause the scope recorded, if any. For a\n * caller abort, `error` is the caller signal's reason.\n */\nexport type ScopedFetchResult =\n | { ok: true; response: Response; body: any }\n | { ok: false; error: unknown; cause?: AbortCause };\n\n/**\n * One controller that two sources may abort: the call's timer and the caller's signal\n *\n * The first source to fire is recorded as the cause and later ones are ignored, so a\n * caller aborting after the timer fired still reads as a timeout. Composed by hand\n * rather than with `AbortSignal.any` / `AbortSignal.timeout`, which browsers below\n * Safari 17.4 lack.\n */\nfunction openAbortScope(callerSignal: AbortSignal | undefined, timeout: number)\n{\n const controller = new AbortController();\n let cause: AbortCause | undefined;\n\n const abort = (source: AbortCause, reason?: unknown) =>\n {\n cause ??= source;\n controller.abort(reason);\n };\n const onCallerAbort = () => abort('caller', callerSignal?.reason);\n const timeoutId = setTimeout(() => abort('timeout'), timeout);\n\n callerSignal?.addEventListener('abort', onCallerAbort, { once: true });\n\n return {\n signal: controller.signal,\n cause: () => cause,\n stopTimer: () => clearTimeout(timeoutId),\n close: () =>\n {\n clearTimeout(timeoutId);\n callerSignal?.removeEventListener('abort', onCallerAbort);\n },\n };\n}\n\n/**\n * Fetch and parse a response inside one abort scope\n *\n * The caller's signal is the one on the final `init`, after interceptors ran. The timer\n * stops when response headers arrive; the caller's abort stays effective until the body\n * is parsed. A failure is returned, not thrown, with the cause the scope recorded —\n * classification reads that record, never the error's name.\n *\n * A custom `fetch`'s body read may not honour the signal at all, so a caller abort during\n * that read can otherwise go unnoticed and the call resolves as if nothing happened. After\n * the body is parsed, the scope is checked again: a recorded `'caller'` cause still wins.\n */\nexport async function fetchInAbortScope(\n url: string,\n init: RequestInit,\n timeout: number,\n customFetch: typeof fetch = fetch,\n): Promise<ScopedFetchResult>\n{\n const callerSignal = init.signal ?? undefined;\n\n if (callerSignal?.aborted)\n {\n return { ok: false, error: callerSignal.reason, cause: 'caller' };\n }\n\n const scope = openAbortScope(callerSignal, timeout);\n\n try\n {\n const response = await customFetch(url, { ...init, signal: scope.signal });\n\n scope.stopTimer();\n\n const body = await parseResponseBody(response);\n\n if (scope.cause() === 'caller')\n {\n return { ok: false, error: callerSignal?.reason, cause: 'caller' };\n }\n\n return { ok: true, response, body };\n }\n catch (error)\n {\n const cause = scope.cause();\n\n return { ok: false, cause, error: cause === 'caller' ? callerSignal?.reason : error };\n }\n finally\n {\n scope.close();\n }\n}\n\n/**\n * Handle error response with deserialization support\n * Attempts to deserialize custom errors if errorRegistry is provided\n * Falls back to ApiError if deserialization fails or is not available\n */\nexport async function handleErrorResponse(\n response: Response,\n body: any,\n fullUrl: string,\n errorRegistry: ErrorRegistry | undefined,\n debug: boolean,\n logger: Logger,\n): Promise<never>\n{\n throw errorFromResponse(response, body, fullUrl, errorRegistry, debug, logger);\n}\n\n/**\n * The error an answered, non-2xx call ends with — what `handleErrorResponse` throws\n *\n * A body carrying a registered `__type` comes back as that class; anything else as an\n * `ApiError` of type `'http'`. Returned rather than thrown, so the caller can report the\n * very object it is about to throw.\n */\nexport function errorFromResponse(\n response: Response,\n body: any,\n fullUrl: string,\n errorRegistry: ErrorRegistry | undefined,\n debug: boolean,\n logger: Logger,\n): Error\n{\n if (debug)\n {\n debugLogs.logErrorResponse(logger, response.status, body);\n }\n\n const deserializedError = deserializeRegisteredError(body, errorRegistry, debug, logger);\n\n if (deserializedError)\n {\n if (debug)\n {\n debugLogs.logThrowingDeserializedError(logger, deserializedError);\n }\n\n return deserializedError;\n }\n\n return fallbackApiError(response, body, fullUrl, logger);\n}\n\n/**\n * Restore the registered error class a body names with `__type`, or null when the body\n * names none or the registry cannot restore it\n */\nfunction deserializeRegisteredError(\n body: any,\n errorRegistry: ErrorRegistry | undefined,\n debug: boolean,\n logger: Logger,\n): Error | null\n{\n if (!errorRegistry || !body || typeof body !== 'object' || !('__type' in body))\n {\n if (debug)\n {\n debugLogs.logErrorDeserializationSkipped(logger, errorRegistry, body);\n }\n\n return null;\n }\n\n if (debug)\n {\n debugLogs.logErrorDeserializationAttempt(logger, body.__type, errorRegistry.getRegisteredTypes());\n }\n\n try\n {\n const deserializedError = errorRegistry.deserialize(body as any);\n\n if (debug)\n {\n debugLogs.logErrorDeserializationSuccess(logger, deserializedError);\n }\n\n return deserializedError;\n }\n catch (deserializeError)\n {\n // Deserialization itself failed (type not found, invalid data, etc.)\n if (debug)\n {\n debugLogs.logErrorDeserializationFailure(logger, deserializeError);\n }\n\n return null;\n }\n}\n\n/**\n * The generic `'http'` ApiError for an answer no registered class claims\n */\nfunction fallbackApiError(response: Response, body: any, fullUrl: string, logger: Logger): ApiError\n{\n if (response.status === 404 && process.env.NODE_ENV !== 'production')\n {\n logger.warn(\n '\\n⚠️ 404 Not Found\\n\\n' +\n 'Check the following:\\n' +\n ' 1. Routes are registered in server.config.ts:\\n' +\n ' → defineServerConfig().routes(appRouter)\\n' +\n ' 2. Delete .spfn cache if you recently added new routes:\\n' +\n ' → rm -rf .spfn\\n',\n );\n }\n\n return new ApiError(\n body?.message || `HTTP ${response.status}: ${response.statusText}`,\n response.status,\n fullUrl,\n body,\n 'http',\n );\n}\n","/**\n * CSRF token transport for the RPC client\n *\n * The Next.js proxy sets a readable (non-HttpOnly) cookie carrying an HMAC of\n * the session's key id; this module mirrors it into a request header. The proxy\n * never compares cookie against header — it recomputes the value from the\n * session — so the cookie is transport only and reading it here is not a trust\n * decision. See the CSRF section of the @spfn/auth README.\n */\n\n/**\n * Header the readable CSRF cookie is mirrored into.\n *\n * Must match CSRF_HEADER in @spfn/auth. It is duplicated rather than imported\n * because @spfn/core cannot depend on @spfn/auth.\n */\nexport const CSRF_HEADER = 'x-spfn-csrf';\n\n/**\n * Cookie names carrying a CSRF token.\n *\n * @spfn/auth suffixes its cookie names with the server port so several local dev\n * instances on the same host do not overwrite each other's session, and the\n * browser cannot know that port — so match the family, not one name. Every\n * candidate is sent and the proxy accepts the request if any of them recomputes\n * to the expected value; a candidate an attacker tossed in never will.\n */\nconst CSRF_COOKIE_PATTERN = /^spfn_csrf(_\\d+)?$/;\n\n/**\n * Values that can be put in a header at all: printable ASCII, no space.\n *\n * A cookie jar is attacker-writable in the very case this feature exists for, and\n * `new Headers()` rejects a value outside Latin-1 — so a sibling subdomain that\n * tosses `spfn_csrf=한` would make every RPC call throw before it was sent, not\n * merely fail the check. A genuine token is 64 hex characters; anything that\n * cannot be a header value cannot be one.\n */\nconst HEADER_SAFE_VALUE = /^[!-~]+$/;\n\n/**\n * Upper bound on candidates sent, so a cookie-flooded jar stays a bounded header.\n *\n * Deliberately generous. The server recomputes the expected value once and then\n * only compares fixed-length strings, so extra candidates cost it almost nothing,\n * while every candidate dropped here is a chance to lock the user out of every\n * mutation — the far worse failure. Must not exceed the matching bound in\n * @spfn/auth's `matchesCsrfToken`, or values sent would never be looked at.\n */\nconst MAX_CANDIDATES = 32;\n\n/**\n * Choose which candidates to send when the jar holds more than the cap.\n *\n * `document.cookie` exposes neither Domain nor Path, so a tossed cookie is\n * indistinguishable from the genuine one here — the proxy is what tells them\n * apart, by recomputing. What this can do is refuse to drop the genuine value on\n * the floor. Browsers order the jar by path length descending, then by age\n * ascending, so a flood pushes the genuine cookie towards the end (attacker\n * cookies on a longer path) or towards the start (attacker cookies written later\n * on the same path). Keeping both ends survives either, where a plain prefix\n * survives only one.\n *\n * A jar flooded far past the cap is a denial of service that no client-side\n * choice fully prevents; the structural fix is a `__Host-` prefixed cookie name,\n * which a sibling subdomain cannot write at all.\n */\nfunction selectCandidates(values: string[]): string[]\n{\n // Identical duplicates carry no extra information, so collapsing them buys\n // back slots that a flood of one repeated value would otherwise burn.\n const unique = Array.from(new Set(values));\n\n if (unique.length <= MAX_CANDIDATES)\n {\n return unique;\n }\n\n const half = MAX_CANDIDATES / 2;\n\n return [...unique.slice(0, half), ...unique.slice(-half)];\n}\n\n/**\n * Collect the CSRF token candidates from cookie entries.\n *\n * Takes entries rather than a map because a name can legitimately appear twice:\n * a sibling subdomain that tosses `spfn_csrf` for the parent domain leaves the\n * browser holding two cookies of that name, and folding them into a map would\n * throw away whichever the tossed one displaced — locking the user out of every\n * mutation. Sending both keeps the real one in play, and the tossed one is inert\n * because the proxy recomputes what it expects.\n *\n * @returns Header value (comma-separated), or undefined when no cookie exists\n */\nexport function csrfHeaderValue(cookies: Iterable<[string, string]>): string | undefined\n{\n // A comma separates candidates on the wire, so a value containing one would\n // arrive as several. That cannot be a genuine token — they are hex — but it\n // would let a single tossed cookie spend the receiver's whole candidate\n // budget and bury the real value behind it. Drop those, and anything that\n // could not be a header value at all.\n const values = Array.from(cookies)\n .filter(([name, value]) => CSRF_COOKIE_PATTERN.test(name)\n && HEADER_SAFE_VALUE.test(value)\n && !value.includes(','))\n .map(([, value]) => value);\n\n const candidates = selectCandidates(values);\n\n return candidates.length > 0 ? candidates.join(',') : undefined;\n}\n\n/**\n * Read the browser cookie jar as entries, duplicates preserved.\n *\n * Empty outside a browser (SSR reads the jar it forwards instead).\n */\nexport function documentCookieEntries(): Array<[string, string]>\n{\n if (typeof document === 'undefined' || !document.cookie)\n {\n return [];\n }\n\n const entries: Array<[string, string]> = [];\n\n for (const pair of document.cookie.split(';'))\n {\n const separator = pair.indexOf('=');\n\n if (separator > 0)\n {\n entries.push([pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()]);\n }\n }\n\n return entries;\n}\n","// ============================================================================\n// Route Call Builder (Structured Input API)\n// ============================================================================\n\nimport type { RouteDef, Router } from '@spfn/core/route';\nimport type {\n CallOptions,\n ExtractRoutes,\n InferRouteInput,\n InferRouteOutput,\n RequestInterceptor,\n ResponseInterceptor,\n} from './types';\n\n/**\n * Pick only non-empty fields from StructuredInput\n *\n * This removes fields that are empty objects `{}` from the input type,\n * so users only need to provide fields that are actually defined in the route.\n */\ntype PickNonEmpty<T> = {\n [K in keyof T as T[K] extends Record<string, never> ? never : K]: T[K];\n};\n\n/**\n * Make fields that can be undefined into optional fields\n *\n * When a field is defined as `Type.Optional(Type.Object({...}))`,\n * the resulting type is `T | undefined`. This utility converts such fields\n * into proper optional fields (`field?: T`) so users don't need to pass them.\n */\ntype MakeOptionalIfUndefinable<T> =\n // Required fields (undefined is not assignable)\n { [K in keyof T as undefined extends T[K] ? never : K]: T[K] }\n // Optional fields (undefined is assignable)\n & { [K in keyof T as undefined extends T[K] ? K : never]?: Exclude<T[K], undefined> };\n\n/**\n * Clean structured input - only include fields that have actual schema,\n * and make fields optional if they accept undefined\n */\ntype CleanStructuredInput<TInput> = MakeOptionalIfUndefinable<PickNonEmpty<TInput>>;\n\n/**\n * Check if input has any required fields\n *\n * Returns false if all fields are optional (i.e., {} is assignable to the input type)\n */\ntype HasAnyRequiredFields<TInput> = {} extends CleanStructuredInput<TInput> ? false : true;\n\n/**\n * Largest delay `setTimeout` honours; a longer one fires immediately\n */\nconst MAX_TIMEOUT_MS = 2147483647;\n\n/**\n * Route call builder with structured input API\n *\n * Input is structured with explicit params, query, body fields\n * that match the server-side route definition.\n *\n * @example\n * ```typescript\n * // GET /users/:id - params only\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // GET /users/:id?include=posts - params + query\n * const user = await api.getUser.call({\n * params: { id: '1' },\n * query: { include: 'posts' }\n * });\n *\n * // POST /users - body only\n * const user = await api.createUser.call({\n * body: { name: 'John', email: 'john@example.com' }\n * });\n *\n * // PUT /users/:id - params + body\n * const user = await api.updateUser.call({\n * params: { id: '1' },\n * body: { name: 'Jane' }\n * });\n *\n * // With options (headers, cookies, Next.js caching)\n * const user = await api.getUser\n * .headers({ 'X-Custom': 'value' })\n * .fetchOptions({ next: { revalidate: 60 } })\n * .call({ params: { id: '1' } });\n * ```\n */\nexport class RouteCallBuilder<\n TInput,\n TOutput,\n>\n{\n private _headers?: Record<string, string>;\n private _cookies?: Record<string, string>;\n private _fetchOptions?: RequestInit;\n private _timeout?: number;\n private _onRequest?: RequestInterceptor;\n private _onResponse?: ResponseInterceptor;\n\n constructor(\n private readonly executor: (input: any, options: CallOptions) => Promise<TOutput>,\n private readonly routeName: string,\n ) \n {}\n\n /**\n * Clone builder\n */\n private clone(): RouteCallBuilder<TInput, TOutput>\n {\n const builder = new RouteCallBuilder<TInput, TOutput>(\n this.executor,\n this.routeName,\n );\n builder._headers = this._headers;\n builder._cookies = this._cookies;\n builder._fetchOptions = this._fetchOptions;\n builder._timeout = this._timeout;\n builder._onRequest = this._onRequest;\n builder._onResponse = this._onResponse;\n\n return builder;\n }\n\n /**\n * Set request headers\n */\n headers(headers: Record<string, string>): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._headers = { ...this._headers, ...headers };\n\n return builder;\n }\n\n /**\n * Set cookies\n */\n cookies(cookies: Record<string, string>): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._cookies = { ...this._cookies, ...cookies };\n\n return builder;\n }\n\n /**\n * Set Next.js fetch options\n */\n fetchOptions(options: RequestInit & { next?: { revalidate?: number | false; tags?: string[] } }): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._fetchOptions = { ...this._fetchOptions, ...options };\n\n return builder;\n }\n\n /**\n * Set this call's timeout in milliseconds, overriding the client-wide one\n *\n * Throws a `TypeError`, before any request is made, unless `ms` is a finite number\n * greater than 0 and at most 2147483647 (the largest delay `setTimeout` honours).\n */\n timeout(ms: number): RouteCallBuilder<TInput, TOutput>\n {\n if (!Number.isFinite(ms) || ms <= 0 || ms > MAX_TIMEOUT_MS)\n {\n throw new TypeError(`timeout must be a finite number of milliseconds in (0, ${MAX_TIMEOUT_MS}], got ${String(ms)}`);\n }\n\n const builder = this.clone();\n builder._timeout = ms;\n\n return builder;\n }\n\n /**\n * Set request interceptor\n */\n onRequest(interceptor: RequestInterceptor): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._onRequest = interceptor;\n\n return builder;\n }\n\n /**\n * Set response interceptor\n */\n onResponse(interceptor: ResponseInterceptor): RouteCallBuilder<TInput, TOutput>\n {\n const builder = this.clone();\n builder._onResponse = interceptor;\n\n return builder;\n }\n\n /**\n * Execute the API call with structured input\n *\n * Input structure matches the server-side route definition:\n * - params: Path parameters (e.g., { id: '123' } for /users/:id)\n * - query: Query string parameters\n * - body: Request body (for POST, PUT, PATCH)\n */\n call(input?: CleanStructuredInput<TInput>): Promise<TOutput>\n {\n const options: CallOptions = {};\n\n if (this._headers)\n {\n options.headers = this._headers;\n }\n\n if (this._cookies)\n {\n options.cookies = this._cookies;\n }\n\n if (this._fetchOptions)\n {\n options.fetchOptions = this._fetchOptions;\n }\n\n if (this._timeout !== undefined)\n {\n options.timeout = this._timeout;\n }\n\n if (this._onRequest)\n {\n options.onRequest = this._onRequest;\n }\n\n if (this._onResponse)\n {\n options.onResponse = this._onResponse;\n }\n\n return this.executor(input || {}, options);\n }\n}\n\n/**\n * Individual route client with structured input API\n */\nexport type RouteClient<TRoute extends RouteDef<any, any>> = {\n /**\n * Set request headers\n */\n headers(headers: Record<string, string>): RouteClient<TRoute>;\n\n /**\n * Set cookies\n */\n cookies(cookies: Record<string, string>): RouteClient<TRoute>;\n\n /**\n * Set Next.js fetch options\n */\n fetchOptions(options: RequestInit & { next?: { revalidate?: number | false; tags?: string[] } }): RouteClient<TRoute>;\n\n /**\n * Set this call's timeout in milliseconds, overriding the client-wide one.\n * Throws a `TypeError` unless `ms` is finite, `> 0` and `<= 2147483647`.\n */\n timeout(ms: number): RouteClient<TRoute>;\n\n /**\n * Set request interceptor\n */\n onRequest(interceptor: RequestInterceptor): RouteClient<TRoute>;\n\n /**\n * Set response interceptor\n */\n onResponse(interceptor: ResponseInterceptor): RouteClient<TRoute>;\n\n /**\n * Execute the API call with structured input\n *\n * @example\n * ```typescript\n * // GET /users/:id\n * api.getUser.call({ params: { id: '123' } });\n *\n * // PUT /users/:id\n * api.updateUser.call({ params: { id: '123' }, body: { name: 'Jane' } });\n * ```\n */\n call: HasAnyRequiredFields<InferRouteInput<TRoute>> extends true\n ? (input: CleanStructuredInput<InferRouteInput<TRoute>>) => Promise<InferRouteOutput<TRoute>>\n : (input?: CleanStructuredInput<InferRouteInput<TRoute>>) => Promise<InferRouteOutput<TRoute>>;\n};\n\n/**\n * One property per route in a flattened route record.\n *\n * A slot the flattening could not resolve to a route definition is `never`, as it was\n * before nesting was flattened — a record whose values are neither routes nor routers\n * names nothing callable.\n */\ntype RouteClients<TRoutes> = {\n [K in keyof TRoutes]: TRoutes[K] extends RouteDef<any, any, any>\n ? RouteClient<TRoutes[K]>\n : never;\n};\n\n/**\n * Typed client for entire router\n *\n * One flat namespace, holding the same route names the server registers. A route\n * declared inside a nested `defineRouter` is reached by its own key — `api.getThing`,\n * never `api.group.getThing` — because that is the name `registerRoutes` mounts it\n * under, the name the RPC proxy resolves, and the name `RouterOutput` takes. The group\n * key is not a route and naming it is a compile error.\n *\n * @example\n * ```typescript\n * const appRouter = defineRouter({\n * getRoot,\n * users: defineRouter({ getUser }),\n * });\n *\n * const api = createApi<typeof appRouter>();\n *\n * await api.getUser.call({ params: { id: '1' } }); // not api.users.getUser\n * ```\n *\n * A name two branches both declare is left out of the namespace rather than resolved to\n * one of them — the same collision `RouterOutput` refuses. Routes mounted with\n * `.packages()` are deliberately absent: a package publishes its own route map and its\n * own client (`authApi`, `cmsApi`), and that is what calls them.\n */\nexport type Client<TRouter extends Router<any>> = RouteClients<ExtractRoutes<TRouter>>;\n","/**\n * Type-Safe RPC-Style Client with Structured Input API\n *\n * Provides full end-to-end type safety from server routes to client calls.\n * No metadata codegen required - method/path resolution happens at the proxy layer.\n *\n * @example\n * ```typescript\n * // Server\n * export const appRouter = defineRouter({\n * getUser: route.get('/users/:id')\n * .input({ params: Type.Object({ id: Type.String() }) })\n * .handler(async (c) => { ... }),\n * createUser: route.post('/users')\n * .input({ body: Type.Object({ name: Type.String() }) })\n * .handler(async (c) => { ... }),\n * });\n *\n * export type AppRouter = typeof appRouter;\n *\n * // Client - no metadata needed!\n * const api = createApi<AppRouter>();\n *\n * // ✅ GET (no body) - becomes GET /api/rpc/getUser?input={...}\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // ✅ POST (has body) - becomes POST /api/rpc/createUser\n * const newUser = await api.createUser.call({ body: { name: 'John' } });\n *\n * // ✅ With options (headers, cookies, interceptors)\n * const user = await api.getUser\n * .headers({ 'X-Custom': 'value' })\n * .cookies({ session: 'xxx' })\n * .fetchOptions({ next: { revalidate: 60 } })\n * .call({ params: { id: '1' } });\n * ```\n */\nimport { env } from '@spfn/core/config';\nimport { ErrorRegistry, errorRegistry as coreErrorRegistry } from '@spfn/core/errors';\nimport { logger } from '@spfn/core/logger';\nimport type { Router } from '@spfn/core/route';\nimport * as debugLogs from './debug-logs';\nimport { ApiError } from './errors';\nimport {\n fetchInAbortScope,\n errorFromResponse,\n buildCookieHeader,\n autoDetectServerCookies,\n} from './helpers';\nimport { CSRF_HEADER, csrfHeaderValue, documentCookieEntries } from './csrf';\nimport { RouteCallBuilder } from './builder';\nimport type { ScopedFetchResult } from './helpers';\nimport type { ApiConfig, ApiOutcome, CallOptions } from './types';\nimport type { Client } from './builder';\n\nconst apiLogger = logger.child('@spfn/core:api-client');\n\n/**\n * Where a failed call went, for the log line its transport error writes\n */\ninterface CallSite\n{\n route: string;\n method: string;\n url: string;\n}\n\n/**\n * A call that got no answer, as both the observer and the caller see it\n */\ntype TransportOutcome = Extract<ApiOutcome, { errorType: 'network' | 'timeout' | 'aborted' }>;\n\n/**\n * Build the `ApiError` of one transport kind together with its outcome\n *\n * Built here rather than read back from `ApiError.errorType`, which is optional, so the\n * outcome's kind is the one the error was made with — no cast to trust.\n */\nfunction transportOutcome(\n errorType: TransportOutcome['errorType'],\n message: string,\n status: number,\n url: string,\n options?: { cause?: unknown },\n): TransportOutcome\n{\n return { ok: false, errorType, status, error: new ApiError(message, status, url, undefined, errorType, options) };\n}\n\n/**\n * Classify a failed fetch by the abort cause its scope recorded\n *\n * - timeout → 408 `'timeout'`, reporting the applied timeout\n * - caller abort → status 0 `'aborted'`, the signal's reason as `cause`; logged at debug\n * level, since it is the caller's own intent\n * - no cause recorded but the error is a plain `AbortError` (a custom `fetch` aborting its\n * own controller, with neither our timer nor the caller's signal involved) → 408\n * `'timeout'`, as it always was before the scope recorded a cause\n * - anything else → status 0 `'network'`\n */\nfunction transportError(\n failure: Extract<ScopedFetchResult, { ok: false }>,\n site: CallSite,\n timeout: number,\n): TransportOutcome\n{\n if (failure.cause === 'timeout')\n {\n apiLogger.error('Request timeout', { ...site, timeout });\n\n return transportOutcome('timeout', `Request timeout after ${timeout}ms`, 408, site.url);\n }\n\n if (failure.cause === 'caller')\n {\n apiLogger.debug('Request aborted by caller', site);\n\n return transportOutcome('aborted', 'Request aborted', 0, site.url, { cause: failure.error });\n }\n\n const { error } = failure;\n\n if (error instanceof Error && error.name === 'AbortError')\n {\n apiLogger.error('Request timeout', { ...site, timeout });\n\n return transportOutcome('timeout', `Request timeout after ${timeout}ms`, 408, site.url);\n }\n\n const errorMessage = error instanceof Error ? error.message : 'Network error';\n apiLogger.error('Network error', {\n ...site,\n error: errorMessage,\n errorName: error instanceof Error ? error.name : 'unknown',\n });\n\n return transportOutcome('network', errorMessage, 0, site.url);\n}\n\n/**\n * Tell the app's observer how a call ended, without letting it change the call\n *\n * A synchronous throw is caught here and a returned thenable gets a `.catch`; either is\n * logged by name and message only — never the request or the body. Nothing is awaited.\n */\nfunction notifyOutcome(onOutcome: ApiConfig['onOutcome'], outcome: ApiOutcome): void\n{\n if (!onOutcome)\n {\n return;\n }\n\n try\n {\n const returned: unknown = onOutcome(outcome);\n\n if (isThenable(returned))\n {\n Promise.resolve(returned).catch(logObserverFailure);\n }\n }\n catch (error)\n {\n logObserverFailure(error);\n }\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown>\n{\n return typeof (value as PromiseLike<unknown> | null)?.then === 'function';\n}\n\nfunction logObserverFailure(error: unknown): void\n{\n apiLogger.error('onOutcome observer failed; the call result is unchanged', {\n errorName: error instanceof Error ? error.name : typeof error,\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n}\n\n// ============================================================================\n// Client Implementation\n// ============================================================================\n\n/**\n * Create type-safe RPC client\n *\n * No metadata required - the client sends routeName + input to the proxy,\n * and the proxy resolves the actual HTTP method and path from the router.\n *\n * @example\n * ```typescript\n * // Client - no metadata needed!\n * const api = createApi<AppRouter>();\n *\n * // GET request (no body) - browser cacheable\n * const user = await api.getUser.call({ params: { id: '1' } });\n *\n * // POST request (has body)\n * const newUser = await api.createUser.call({ body: { name: 'John' } });\n * ```\n */\nexport function createApi<TRouter extends Router<any>>(\n config: ApiConfig = {},\n): Client<TRouter>\n{\n const {\n baseUrl = '/api/rpc',\n headers: defaultHeaders = {},\n timeout = env.SERVER_TIMEOUT,\n fetch: customFetch = fetch,\n onRequest: globalOnRequest,\n onResponse: globalOnResponse,\n onOutcome,\n errorRegistry: errorRegistryConfig,\n debug = false,\n } = config;\n\n // Normalize errorRegistry: always include coreErrorRegistry\n const errorRegistry = Array.isArray(errorRegistryConfig)\n ? new ErrorRegistry([coreErrorRegistry, ...errorRegistryConfig])\n : errorRegistryConfig ?? coreErrorRegistry;\n\n if (debug)\n {\n apiLogger.debug('API client initialized', { baseUrl });\n }\n\n /**\n * Execute API call\n *\n * Determines GET vs POST based on body/formData presence:\n * - No body/formData → GET /api/rpc/{routeName}?input={...}\n * - Has body → POST /api/rpc/{routeName} with JSON body\n * - Has formData → POST /api/rpc/{routeName} with multipart/form-data\n */\n async function executeCall(\n routeName: string,\n input: any = {},\n options: CallOptions = {},\n ): Promise<any>\n {\n const hasBody = input.body !== undefined;\n const hasFormData = input.formData !== undefined && Object.keys(input.formData).length > 0;\n const method = (hasBody || hasFormData) ? 'POST' : 'GET';\n\n // Build full URL - handle SSR case where SPFN_APP_URL might not be set\n let appUrl = env.SPFN_APP_URL || '';\n\n // In SSR environment, if SPFN_APP_URL is not set, try to get host from request headers\n if (!appUrl && typeof window === 'undefined')\n {\n try\n {\n const { headers } = await import('next/headers.js');\n const headersList = await headers();\n const host = headersList.get('host');\n const protocol = headersList.get('x-forwarded-proto') || 'http';\n if (host)\n {\n appUrl = `${protocol}://${host}`;\n if (debug)\n {\n apiLogger.debug(`Auto-detected app URL from headers: ${appUrl}`);\n }\n }\n }\n catch\n {\n // Fallback: use relative URL and let fetch handle it\n if (debug)\n {\n apiLogger.warn('Could not determine app URL in SSR environment, using relative URL');\n }\n }\n }\n\n // Build URL based on method\n let fullUrl: string;\n if (method === 'GET')\n {\n // GET: encode input in query string\n const inputParam = encodeURIComponent(JSON.stringify(input));\n fullUrl = `${appUrl}${baseUrl}/${routeName}?input=${inputParam}`;\n }\n else\n {\n // POST: input goes in body\n fullUrl = `${appUrl}${baseUrl}/${routeName}`;\n }\n\n // Prepare headers\n // Note: Don't set Content-Type for formData - browser sets it with boundary\n const headers: Record<string, string> = {\n ...(hasFormData ? {} : { 'Content-Type': 'application/json' }),\n ...defaultHeaders,\n ...options.headers,\n };\n\n // Auto-detect server cookies and merge with user-provided cookies\n const autoDetectedCookies = await autoDetectServerCookies();\n const cookiesToSend = {\n ...autoDetectedCookies,\n ...(options.cookies || {}),\n };\n\n // Add Cookie header if we have cookies to send\n if (Object.keys(cookiesToSend).length > 0)\n {\n headers['Cookie'] = buildCookieHeader(cookiesToSend);\n }\n\n // Mirror the readable CSRF cookie into a header, from the browser jar or\n // — server-side — from the jar being forwarded.\n //\n // Carried on GET calls too, deliberately: the wire method here is chosen\n // by whether the input has a body, not by what the route does. A bodyless\n // mutation (`api.logout.call({})`) travels as GET and the proxy still\n // forwards it as the route's POST, so a GET-shaped call can be exactly\n // the request that needs the header. The proxy decides what to check from\n // the resolved route method, and ignores the header on safe routes.\n const csrfToken = csrfHeaderValue(\n typeof window === 'undefined' ? Object.entries(cookiesToSend) : documentCookieEntries(),\n );\n\n const csrfSetByCaller = Object.keys(headers).some(name => name.toLowerCase() === CSRF_HEADER);\n\n if (csrfToken && !csrfSetByCaller)\n {\n headers[CSRF_HEADER] = csrfToken;\n }\n\n // Log cookie auto-detection if debug enabled\n if (debug && Object.keys(autoDetectedCookies).length > 0)\n {\n const cookieArray = Object.entries(autoDetectedCookies).map(([name, value]) => ({ name, value }));\n debugLogs.logCookieAutoDetection(apiLogger, cookieArray);\n }\n\n // Build request init\n const requestInit: RequestInit = {\n method,\n headers,\n ...options.fetchOptions,\n };\n\n // Add body for POST\n if (method === 'POST')\n {\n if (hasFormData)\n {\n // Build FormData for file uploads\n const formData = new FormData();\n\n // Add non-formData fields (params, query, headers, cookies) as JSON metadata\n const metadata: Record<string, any> = {};\n if (input.params) metadata.params = input.params;\n if (input.query) metadata.query = input.query;\n if (input.headers) metadata.headers = input.headers;\n if (input.cookies) metadata.cookies = input.cookies;\n\n if (Object.keys(metadata).length > 0)\n {\n formData.append('__metadata', JSON.stringify(metadata));\n }\n\n // Add formData fields\n for (const [key, value] of Object.entries(input.formData))\n {\n if (value instanceof File)\n {\n formData.append(key, value);\n }\n else if (Array.isArray(value))\n {\n // Handle array of files or values\n for (const item of value)\n {\n if (item instanceof File)\n {\n formData.append(key, item);\n }\n else\n {\n formData.append(key, String(item));\n }\n }\n }\n else if (value !== undefined && value !== null)\n {\n formData.append(key, String(value));\n }\n }\n\n requestInit.body = formData;\n }\n else\n {\n requestInit.body = JSON.stringify(input);\n }\n }\n\n // Execute request interceptors\n let init = requestInit;\n if (globalOnRequest)\n {\n init = await globalOnRequest(fullUrl, init);\n }\n if (options.onRequest)\n {\n init = await options.onRequest(fullUrl, init);\n }\n\n if (debug)\n {\n debugLogs.logRequest(apiLogger, routeName, method, fullUrl, !!init.body);\n }\n\n // Execute fetch and parse the body inside one abort scope\n const appliedTimeout = options.timeout ?? timeout;\n const fetched = await fetchInAbortScope(fullUrl, init, appliedTimeout, customFetch);\n\n if (!fetched.ok)\n {\n const outcome = transportError(fetched, { route: routeName, method, url: fullUrl }, appliedTimeout);\n notifyOutcome(onOutcome, outcome);\n throw outcome.error;\n }\n\n let { response, body } = fetched;\n\n // Execute global + local response interceptors\n //\n // These run outside the abort scope on purpose. That scope classifies a transport\n // failure, and an interceptor throwing is not one: Next.js implements `redirect()`\n // and `notFound()` by throwing an error carrying a digest, and an interceptor\n // raising a domain error of its own is not a transport failure either. Run inside\n // it, every one of those became `ApiError(..., 0, ..., 'network')` — the\n // navigation never happened and the caller was handed a network failure that never\n // occurred, which retry and offline handling keyed on `errorType === 'network'`\n // act on.\n if (globalOnResponse)\n {\n const result = await globalOnResponse(response, body);\n response = result.response;\n body = result.body;\n }\n if (options.onResponse)\n {\n const result = await options.onResponse(response, body);\n response = result.response;\n body = result.body;\n }\n\n if (debug)\n {\n debugLogs.logResponse(apiLogger, routeName, response.status, !!body);\n }\n\n // Handle error responses; the observer sees the same error the caller catches\n if (!response.ok)\n {\n const error = errorFromResponse(response, body, fullUrl, errorRegistry, debug, apiLogger);\n notifyOutcome(onOutcome, { ok: false, errorType: 'http', status: response.status, error });\n throw error;\n }\n\n notifyOutcome(onOutcome, { ok: true, response, body });\n\n return body;\n }\n\n /**\n * Build client proxy\n *\n * Every property access returns a `RouteCallBuilder` for that one property read as a\n * whole route name, and that name goes on the wire as `/api/rpc/{routeName}`. The\n * proxy route resolves it against the generated route map, whose names are flat.\n *\n * Nesting needs nothing here: `registerRoutes` mounts a route declared inside a\n * nested `defineRouter` under its own key, so `api.getThing` is the call for a nested\n * `getThing` exactly as for a top-level one — which is the namespace `Client` types.\n * There is no dot-notation traversal: a property access never returns another proxy,\n * so `api.group.getThing` reads a property of a builder and is `undefined`.\n *\n * `prefix` is vestigial — nothing passes one, and adding a caller that did would\n * build a dotted name the route map cannot resolve.\n */\n function buildProxy(prefix = ''): any\n {\n return new Proxy(\n {},\n {\n get(_target, prop: string)\n {\n const currentPath = prefix ? `${prefix}.${prop}` : prop;\n\n // Return RouteCallBuilder that can either be called or chained\n return new RouteCallBuilder(\n (input: any, options: CallOptions) => executeCall(currentPath, input, options),\n currentPath,\n );\n },\n },\n );\n }\n\n return buildProxy() as Client<TRouter>;\n}\n"]}
|
package/dist/nextjs/server.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { NextRequest, NextResponse } from 'next/server';
|
|
1
|
+
import { NextRequest, NextResponse } from 'next/server.js';
|
|
2
2
|
import { HttpMethod } from '@spfn/core/route';
|
|
3
3
|
import { InterceptorRule as InterceptorRule$1 } from '@spfn/core/nextjs/server';
|
|
4
|
-
import { S as SetCookie } from '../types-
|
|
4
|
+
import { S as SetCookie } from '../types-CKH0D3Dy.js';
|
|
5
5
|
import '@sinclair/typebox';
|
|
6
6
|
import '@spfn/core/errors';
|
|
7
7
|
|
package/dist/nextjs/server.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/security/proxy-signature.ts","../../src/nextjs/shared.ts","../../src/nextjs/proxy/interceptors/helpers.ts","../../src/nextjs/proxy/interceptors/registry.ts","../../src/nextjs/proxy/helpers.ts","../../src/nextjs/proxy/rpc.ts"],"names":["headersToForward"],"mappings":";;;;;;AA0BO,IAAM,sBAAA,GAAyB,wBAAA;AAC/B,IAAM,sBAAA,GAAyB,wBAAA;AAC/B,IAAM,kBAAA,GAAqB,oBAAA;AAC3B,IAAM,mBAAA,GAAsB,qBAAA;AAM5B,IAAM,sBAAA,GAAyB,wBAAA;AAG/B,IAAM,cAAA,GAAiB,SAAA;AAoBvB,SAAS,cAAc,GAAA,EAC9B;AACI,EAAA,MAAM,GAAA,GAAM,GAAA,CAAI,O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n * Proxy → Backend request signing (HMAC-SHA256) with key rotation\n *\n * Shared between the Next.js RPC proxy (which signs outbound requests) and the\n * backend proxy-guard middleware (which verifies them). Keeping the canonical\n * string and HMAC logic in one pure module guarantees both sides agree.\n *\n * The signature proves a request passed through a trusted proxy that holds the\n * shared secret. It does NOT authenticate the end user — that is the JWT layer's\n * job — and it cannot stop a client from calling the proxy itself. Its role is to\n * stop direct-to-backend calls that bypass the proxy.\n *\n * Keys are identified by a short keyId so secrets can be rotated without downtime:\n * the proxy signs with the active key and stamps its keyId in a header; the\n * backend keeps a set of accepted keys (current + previous) and selects by keyId.\n * Roll a new key in, let both sides pick it up, switch the proxy to it, then drop\n * the old one after a grace period — no request is ever rejected mid-rotation.\n *\n * @module security/proxy-signature\n */\nimport { createHmac, randomBytes, timingSafeEqual, createHash } from 'node:crypto';\n\n// ============================================================================\n// Header names\n// ============================================================================\n\nexport const PROXY_SIGNATURE_HEADER = 'x-spfn-proxy-signature';\nexport const PROXY_TIMESTAMP_HEADER = 'x-spfn-proxy-timestamp';\nexport const PROXY_NONCE_HEADER = 'x-spfn-proxy-nonce';\nexport const PROXY_KEY_ID_HEADER = 'x-spfn-proxy-key-id';\n/**\n * The real client IP, forwarded by the proxy. The backend trusts this only when\n * the request is proxy-verified (proxy-guard `clientType` ≠ untrusted) — the proxy\n * itself sees no spoofable hop, so a verified request's value is the true client.\n */\nexport const PROXY_CLIENT_IP_HEADER = 'x-spfn-proxy-client-ip';\n\n/** keyId used when a raw secret carries no `keyId:` prefix (back-compat). */\nexport const DEFAULT_KEY_ID = 'default';\n\n// ============================================================================\n// Keys\n// ============================================================================\n\n/**\n * A signing key: a short identifier plus its secret. Encoded in env as\n * `<keyId>:<secret>` (e.g. `v2:9f3c...`); a bare secret gets `DEFAULT_KEY_ID`.\n */\nexport interface ProxyKey\n{\n keyId: string;\n secret: string;\n}\n\n/**\n * Parse one `<keyId>:<secret>` (or bare `<secret>`) string into a ProxyKey.\n * keyId is everything before the FIRST colon; the secret keeps any later colons.\n */\nexport function parseProxyKey(raw: string): ProxyKey\n{\n const idx = raw.indexOf(':');\n if (idx === -1)\n {\n return { keyId: DEFAULT_KEY_ID, secret: raw };\n }\n\n // A leading colon (':secret') yields an empty keyId; the backend treats an empty\n // keyId header as \"missing\" and rejects, so normalize it to DEFAULT_KEY_ID.\n return { keyId: raw.slice(0, idx) || DEFAULT_KEY_ID, secret: raw.slice(idx + 1) };\n}\n\n/**\n * Build the backend's accepted key set from raw env values. Each input may be a\n * single key or a comma-separated list (for multiple grace keys). Earlier inputs\n * win on keyId collision, so pass the active secret first.\n */\nexport function parseProxyKeySet(raws: Array<string | undefined | null>): ProxyKey[]\n{\n const keys: ProxyKey[] = [];\n const seen = new Set<string>();\n\n for (const raw of raws)\n {\n if (!raw)\n {\n continue;\n }\n\n for (const part of raw.split(','))\n {\n const trimmed = part.trim();\n if (!trimmed)\n {\n continue;\n }\n\n const key = parseProxyKey(trimmed);\n if (!key.secret || seen.has(key.keyId))\n {\n continue;\n }\n\n seen.add(key.keyId);\n keys.push(key);\n }\n }\n\n return keys;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * The parts of a request that are bound into the signature.\n */\nexport interface SignatureParts\n{\n /** Resolved backend HTTP method (GET/POST/PUT/...) */\n method: string;\n\n /**\n * Raw (wire) backend path, percent-encoding preserved, leading slash, NO query.\n * Proxy signs its outbound request-target path; the backend reconstructs the\n * SAME bytes from `new URL(c.req.url).pathname` (NOT the decoded `c.req.path`).\n */\n path: string;\n\n /**\n * Raw (wire) query string including leading `?`, or '' when there is none.\n * Both sides use the verbatim search string so query params are authenticated.\n */\n query: string;\n\n /** Unix epoch milliseconds, as a string */\n timestamp: string;\n\n /** Random per-request nonce */\n nonce: string;\n\n /**\n * SHA-256 hex of the raw request body, or empty string when there is no body\n * (GET/HEAD, or multipart uploads which are excluded by design). Bound for ANY\n * non-multipart content-type, not just application/json.\n *\n * Multipart is excluded so the proxy can stream large uploads without buffering\n * them to hash. The signature therefore proves *provenance* (came through the\n * trusted proxy) and binds method/path/query/timestamp for a multipart request,\n * but NOT the body bytes. Two consequences, by design:\n * - Multipart *content* integrity/validation is the application's job (size,\n * type, checksum, business rules) — not the transport signature's.\n * - If you don't trust the proxy→backend hop itself, secure it with TLS/mTLS;\n * signing a prefix of the stream would be a half-measure (the tail stays\n * unprotected) and is intentionally not done.\n */\n bodyHash: string;\n}\n\n/**\n * Headers produced by signing — ready to set on the outbound fetch.\n */\nexport interface SignatureHeaders\n{\n [PROXY_SIGNATURE_HEADER]: string;\n [PROXY_TIMESTAMP_HEADER]: string;\n [PROXY_NONCE_HEADER]: string;\n [PROXY_KEY_ID_HEADER]: string;\n}\n\n// ============================================================================\n// Canonical string + HMAC\n// ============================================================================\n\n/**\n * Build the canonical string that gets signed. Field order is fixed and each\n * field is newline-separated, so a captured signature cannot be replayed against\n * a different method, path, or body.\n */\nexport function buildCanonicalString(parts: SignatureParts): string\n{\n return [parts.method.toUpperCase(), parts.path, parts.query, parts.timestamp, parts.nonce, parts.bodyHash].join('\\n');\n}\n\n/**\n * Hash a request body. Accepts a string (proxy side, from JSON.stringify) or a\n * Buffer (backend side, straight from the stream — avoids a bytes→string→bytes\n * round-trip). Returns '' for empty/no body. A utf8 string and its Buffer hash\n * identically, so both sides agree.\n */\nexport function hashBody(body: string | Buffer | undefined | null): string\n{\n if (!body || body.length === 0)\n {\n return '';\n }\n\n return typeof body === 'string'\n ? createHash('sha256').update(body, 'utf8').digest('hex')\n : createHash('sha256').update(body).digest('hex');\n}\n\n/**\n * Compute the HMAC-SHA256 signature (hex) for the given parts.\n */\nexport function computeSignature(secret: string, parts: SignatureParts): string\n{\n return createHmac('sha256', secret).update(buildCanonicalString(parts)).digest('hex');\n}\n\n/**\n * Generate a fresh random nonce (hex).\n */\nexport function generateNonce(): string\n{\n return randomBytes(16).toString('hex');\n}\n\n// ============================================================================\n// Sign (proxy side)\n// ============================================================================\n\nexport interface SignInput\n{\n /** The active signing key. */\n key: ProxyKey;\n method: string;\n /** Raw (wire) path, leading slash, percent-encoding preserved, NO query. */\n path: string;\n /** Raw (wire) query string including leading `?`, or '' / omitted for none. */\n query?: string;\n /** Raw request body string, if any. Omit for GET / multipart uploads. */\n body?: string | null;\n /** Override the timestamp (testing). Defaults to Date.now(). */\n timestamp?: string;\n /** Override the nonce (testing). Defaults to a random nonce. */\n nonce?: string;\n}\n\n/**\n * Sign an outbound proxy request and return the headers to attach (including the\n * keyId so the backend knows which key to verify against).\n */\nexport function signProxyRequest(input: SignInput): SignatureHeaders\n{\n const timestamp = input.timestamp ?? String(Date.now());\n const nonce = input.nonce ?? generateNonce();\n const signature = computeSignature(input.key.secret, {\n method: input.method,\n path: input.path,\n query: input.query ?? '',\n timestamp,\n nonce,\n bodyHash: hashBody(input.body),\n });\n\n return {\n [PROXY_SIGNATURE_HEADER]: signature,\n [PROXY_TIMESTAMP_HEADER]: timestamp,\n [PROXY_NONCE_HEADER]: nonce,\n [PROXY_KEY_ID_HEADER]: input.key.keyId,\n };\n}\n\n// ============================================================================\n// Verify (backend side)\n// ============================================================================\n\nexport type VerifyFailureReason =\n | 'missing-headers'\n | 'stale-timestamp'\n | 'bad-timestamp'\n | 'unknown-key'\n | 'signature-mismatch';\n\n// ('body-read-error' / 'origin-not-allowed' / 'nonce-replay' are guard-level\n// reasons carried separately by the middleware, not produced by verify itself.)\n\nexport interface VerifyResult\n{\n valid: boolean;\n reason?: VerifyFailureReason;\n /** The verified nonce, for optional replay tracking by the caller. */\n nonce?: string;\n /** The keyId the request was verified against (for logging/metrics). */\n keyId?: string;\n}\n\nexport interface VerifyInput\n{\n /** Accepted keys (active + grace). Selected by the request's keyId header. */\n keys: ProxyKey[];\n method: string;\n /** Raw (wire) path from `new URL(c.req.url).pathname` — NOT decoded `c.req.path`. */\n path: string;\n /** Raw (wire) query string from `new URL(c.req.url).search`, or '' for none. */\n query?: string;\n /** Raw request body (string or Buffer) as received, if any. */\n body?: string | Buffer | null;\n signature: string | null | undefined;\n timestamp: string | null | undefined;\n nonce: string | null | undefined;\n keyId: string | null | undefined;\n /** Allowed clock skew / replay window in ms. Default 30s. */\n windowMs?: number;\n /** Current time (testing). Defaults to Date.now(). */\n now?: number;\n}\n\n/**\n * Constant-time hex string comparison. Returns false on any length diff.\n *\n * Buffer.from(_, 'hex') does NOT throw on invalid hex — it silently truncates at\n * the first bad char — so a malformed signature yields a shorter buffer that the\n * length check rejects. No try/catch needed.\n */\nfunction safeEqualHex(a: string, b: string): boolean\n{\n const bufA = Buffer.from(a, 'hex');\n const bufB = Buffer.from(b, 'hex');\n\n if (bufA.length === 0 || bufA.length !== bufB.length)\n {\n return false;\n }\n\n return timingSafeEqual(bufA, bufB);\n}\n\n/**\n * Verify an inbound request's proxy signature against the accepted key set.\n *\n * Checks, in order: headers present, timestamp within window (replay guard),\n * keyId known, and HMAC match. Nonce-level replay rejection is left to the caller\n * (optional, Redis-backed) since not every deployment has a shared store.\n */\nexport function verifyProxyRequest(input: VerifyInput): VerifyResult\n{\n const { signature, timestamp, nonce, keyId } = input;\n\n if (!signature || !timestamp || !nonce || !keyId)\n {\n return { valid: false, reason: 'missing-headers' };\n }\n\n const ts = Number(timestamp);\n if (!Number.isFinite(ts))\n {\n return { valid: false, reason: 'bad-timestamp' };\n }\n\n const now = input.now ?? Date.now();\n const windowMs = input.windowMs ?? 30_000;\n if (Math.abs(now - ts) > windowMs)\n {\n return { valid: false, reason: 'stale-timestamp' };\n }\n\n const key = input.keys.find(k => k.keyId === keyId);\n if (!key)\n {\n return { valid: false, reason: 'unknown-key' };\n }\n\n const expected = computeSignature(key.secret, {\n method: input.method,\n path: input.path,\n query: input.query ?? '',\n timestamp,\n nonce,\n bodyHash: hashBody(input.body),\n });\n\n if (!safeEqualHex(signature, expected))\n {\n return { valid: false, reason: 'signature-mismatch' };\n }\n\n return { valid: true, nonce, keyId };\n}\n","/**\n * Shared utilities for Next.js client and proxy modules\n *\n * Contains common functions used by both client and proxy to avoid code duplication.\n */\n\n/**\n * Build URL with path parameters replaced\n *\n * @example\n * buildUrlWithParams('/users/:id/posts/:postId', { id: '123', postId: '456' })\n * // Returns: '/users/123/posts/456'\n */\nexport function buildUrlWithParams(path: string, params: Record<string, any>): string\n{\n let url = path;\n for (const [key, value] of Object.entries(params))\n {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n return url;\n}\n\n/**\n * Build query string from object\n *\n * @example\n * buildQueryString({ page: '1', limit: '10', tags: ['foo', 'bar'] })\n * // Returns: '?page=1&limit=10&tags=foo&tags=bar'\n */\nexport function buildQueryString(query: Record<string, any>): string\n{\n if (Object.keys(query).length === 0)\n {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query))\n {\n if (Array.isArray(value))\n {\n value.forEach((v) => searchParams.append(key, String(v)));\n }\n else\n {\n searchParams.append(key, String(value));\n }\n }\n\n return `?${searchParams.toString()}`;\n}\n\n/**\n * Build Cookie header string from cookies object\n *\n * @example\n * buildCookieHeader({ session: 'abc123', theme: 'dark' })\n * // Returns: 'session=abc123; theme=dark'\n */\nexport function buildCookieHeader(cookies: Record<string, string>): string\n{\n return Object.entries(cookies)\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n}\n\n/**\n * Parse response body based on content type\n *\n * Handles:\n * - 204 No Content: returns null (no body expected)\n * - application/json: parses JSON body\n * - Other content types: returns raw text\n */\nexport async function parseResponseBody(response: Response): Promise<any>\n{\n // 204 No Content has no body\n if (response.status === 204)\n {\n return null;\n }\n\n const contentType = response.headers.get('content-type');\n\n if (contentType?.includes('application/json'))\n {\n const text = await response.text();\n\n return text ? JSON.parse(text) : null;\n }\n else\n {\n return await response.text();\n }\n}\n","/**\n * SPFN Next.js Proxy Interceptor Execution Engine\n */\n\nimport type {\n InterceptorRule,\n RequestInterceptor,\n ResponseInterceptor,\n RequestInterceptorContext,\n ResponseInterceptorContext,\n} from './types';\n\n/**\n * Check if path matches pattern\n *\n * Supports:\n * - Wildcards: '/_auth/*' matches '/_auth/login'\n * - Path params: '/users/:id' matches '/users/123'\n * - RegExp: /^\\/_auth\\/.+$/ matches '/_auth/login'\n * - Exact match: '/_auth/login' matches '/_auth/login'\n * - All: '*' matches any path\n *\n * @param path - Request path to test\n * @param pattern - Pattern to match against\n * @returns True if path matches pattern\n */\nexport function matchPath(path: string, pattern: string | RegExp): boolean\n{\n // Match all\n if (pattern === '*')\n {\n return true;\n }\n\n // RegExp pattern\n if (pattern instanceof RegExp)\n {\n return pattern.test(path);\n }\n\n // String pattern\n // Convert wildcard pattern to RegExp\n // '/_auth/*' -> /^\\/_auth\\/.*/\n // '/users/:id' -> /^\\/users\\/[^/]+$/\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/:[^/]+/g, '[^/]+')\n .replace(/\\//g, '\\\\/');\n\n const regex = new RegExp(`^${regexPattern}$`);\n\n return regex.test(path);\n}\n\n/**\n * Check if method matches pattern\n *\n * @param method - Request method (e.g., 'POST')\n * @param pattern - Method pattern (e.g., 'POST' or ['POST', 'PUT'])\n * @returns True if method matches pattern\n */\nexport function matchMethod(\n method: string,\n pattern?: string | string[],\n): boolean\n{\n // No method filter = match all\n if (!pattern)\n {\n return true;\n }\n\n // Single method\n if (typeof pattern === 'string')\n {\n return method.toUpperCase() === pattern.toUpperCase();\n }\n\n // Multiple methods\n return pattern.some((m) => m.toUpperCase() === method.toUpperCase());\n}\n\n/**\n * Filter interceptors that match the request\n *\n * @param rules - All interceptor rules\n * @param path - Request path\n * @param method - Request method\n * @returns Matched interceptors\n */\nexport function filterMatchingInterceptors(\n rules: InterceptorRule[],\n path: string,\n method: string,\n): InterceptorRule[]\n{\n return rules.filter((rule) => \n {\n return matchPath(path, rule.pathPattern) && matchMethod(method, rule.method);\n });\n}\n\n/**\n * Execute request interceptors in chain\n *\n * Interceptors are executed in order:\n * 1. First registered interceptor\n * 2. Second registered interceptor\n * 3. ... and so on\n *\n * Each interceptor must call next() to continue the chain.\n * If next() is not called, the chain stops and remaining interceptors are skipped.\n *\n * @param context - Request interceptor context\n * @param interceptors - Interceptors to execute\n */\nexport async function executeRequestInterceptors(\n context: RequestInterceptorContext,\n interceptors: RequestInterceptor[],\n): Promise<void>\n{\n let index = 0;\n\n const next = async (): Promise<void> => \n {\n if (index >= interceptors.length)\n {\n return;\n }\n\n const interceptor = interceptors[index];\n index++;\n\n await interceptor(context, next);\n };\n\n await next();\n}\n\n/**\n * Execute response interceptors in chain\n *\n * Interceptors are executed in order:\n * 1. First registered interceptor\n * 2. Second registered interceptor\n * 3. ... and so on\n *\n * Each interceptor must call next() to continue the chain.\n * If next() is not called, the chain stops and remaining interceptors are skipped.\n *\n * @param context - Response interceptor context\n * @param interceptors - Interceptors to execute\n */\nexport async function executeResponseInterceptors(\n context: ResponseInterceptorContext,\n interceptors: ResponseInterceptor[],\n): Promise<void>\n{\n let index = 0;\n\n const next = async (): Promise<void> => \n {\n if (index >= interceptors.length)\n {\n return;\n }\n\n const interceptor = interceptors[index];\n index++;\n\n await interceptor(context, next);\n };\n\n await next();\n}\n","/**\n * Global Interceptor Registry\n *\n * Allows packages to automatically register their interceptors\n * for Next.js proxy without manual configuration.\n *\n * Uses globalThis for persistence across module reloads (HMR).\n */\nimport type { InterceptorRule } from './types';\n\n// ============================================================================\n// Global Type Declarations\n// ============================================================================\n\n/**\n * Extend globalThis with interceptor registry\n *\n * Using globalThis allows the registry to persist across module reloads (HMR).\n * preventing duplicate registrations during development with HMR.\n */\ndeclare global\n{\n var __SPFN_INTERCEPTOR_REGISTRY__: InterceptorRegistry | undefined;\n}\n\n/**\n * Global interceptor registry\n *\n * Packages register their interceptors on import,\n * and proxy automatically discovers and applies them.\n */\nexport class InterceptorRegistry\n{\n private interceptors = new Map<string, InterceptorRule[]>();\n\n /**\n * Register interceptors for a package\n *\n * @param packageName - Unique package identifier (e.g., 'auth', 'storage')\n * @param interceptors - Array of interceptor rules\n *\n * @example\n * ```typescript\n * registerInterceptors('auth', [\n * {\n * pathPattern: '/_auth/*',\n * request: async (ctx, next) => { ... }\n * }\n * ]);\n * ```\n */\n register(packageName: string, interceptors: InterceptorRule[]): void\n {\n if (!this.interceptors.has(packageName))\n {\n this.interceptors.set(packageName, interceptors);\n }\n }\n\n /**\n * Get all registered interceptors\n *\n * @param exclude - Package names to exclude\n * @returns Flat array of all interceptor rules\n */\n getAll(exclude: string[] = []): InterceptorRule[]\n {\n const all: InterceptorRule[] = [];\n\n for (const [packageName, interceptors] of this.interceptors.entries())\n {\n if (!exclude.includes(packageName))\n {\n all.push(...interceptors);\n }\n }\n\n return all;\n }\n\n /**\n * Get interceptors for specific package\n *\n * @param packageName - Package identifier\n * @returns Interceptor rules or undefined\n */\n get(packageName: string): InterceptorRule[] | undefined\n {\n return this.interceptors.get(packageName);\n }\n\n /**\n * Get list of registered package names\n */\n getPackageNames(): string[]\n {\n return Array.from(this.interceptors.keys());\n }\n\n /**\n * Check if package has registered interceptors\n */\n has(packageName: string): boolean\n {\n return this.interceptors.has(packageName);\n }\n\n /**\n * Unregister interceptors for a package\n *\n * @param packageName - Package identifier\n */\n unregister(packageName: string): void\n {\n this.interceptors.delete(packageName);\n }\n\n /**\n * Clear all registered interceptors\n *\n * Useful for testing\n */\n clear(): void\n {\n this.interceptors.clear();\n }\n\n /**\n * Get total count of registered interceptors\n */\n count(): number\n {\n let total = 0;\n for (const interceptors of this.interceptors.values())\n {\n total += interceptors.length;\n }\n\n return total;\n }\n}\n\n/**\n * Global singleton registry instance\n *\n * Uses globalThis to persist across module reloads (HMR).\n * This prevents duplicate registrations during development.\n */\nexport const interceptorRegistry = (() =>\n{\n if (!globalThis.__SPFN_INTERCEPTOR_REGISTRY__)\n {\n globalThis.__SPFN_INTERCEPTOR_REGISTRY__ = new InterceptorRegistry();\n }\n\n return globalThis.__SPFN_INTERCEPTOR_REGISTRY__;\n})();\n\n/**\n * Register interceptors for a package\n *\n * This should be called during package initialization (on import).\n * The interceptors will be automatically applied by the Next.js proxy.\n *\n * @param packageName - Unique package identifier (e.g., 'auth', 'storage')\n * @param interceptors - Array of interceptor rules\n *\n * @example\n * ```typescript\n * // packages/auth/src/adapters/nextjs/interceptors/index.ts\n * import { registerInterceptors } from '@spfn/core/nextjs';\n *\n * const authInterceptors = [\n * {\n * pathPattern: '/_auth/*',\n * request: async (ctx, next) => {\n * // Add JWT token\n * ctx.headers['Authorization'] = 'Bearer token';\n * await next();\n * }\n * }\n * ];\n *\n * // Auto-register on import\n * registerInterceptors('auth', authInterceptors);\n * ```\n */\nexport function registerInterceptors(\n packageName: string,\n interceptors: InterceptorRule[],\n): void\n{\n interceptorRegistry.register(packageName, interceptors);\n}\n","/**\n * Helper functions for proxy handler\n * Separates utility logic from main proxy handler for better maintainability\n */\nimport { NextRequest } from 'next/server';\nimport type { CookieOptions, SetCookie } from '../client';\nimport type { InterceptorRule, RequestInterceptorContext, ResponseInterceptorContext } from './interceptors/types';\nimport type { InterceptorRegistry } from './interceptors';\nimport { PROXY_CLIENT_IP_HEADER } from '../../security/proxy-signature';\n\n// Re-export from shared\nexport { parseResponseBody } from '../shared';\n\n/**\n * Resolve the real client IP from a forwarded chain.\n *\n * `X-Forwarded-For` is `client, proxy1, proxy2, …` — each trusted hop appends the\n * address it received the connection from, so the rightmost `trustedHops` entries\n * are added by our own infra and can't be spoofed. The client as the outermost\n * trusted hop saw it is `parts[len - trustedHops]`. A client that prepends a fake\n * value just lengthens the chain to the left and is ignored.\n *\n * @param xff - raw X-Forwarded-For header value\n * @param trustedHops - number of trusted proxies in front (e.g. LB + nginx = 2)\n */\nexport function clientIpFromForwardedChain(\n xff: string | null | undefined,\n trustedHops: number,\n): string | undefined\n{\n if (!xff) return undefined;\n\n const parts = xff.split(',').map(s => s.trim()).filter(Boolean);\n if (parts.length === 0) return undefined;\n\n const idx = parts.length - Math.max(1, trustedHops);\n\n // Fewer entries than configured hops (misconfig / fewer real hops): best-effort\n // to the leftmost rather than returning nothing.\n return parts[idx] ?? parts[0];\n}\n\nfunction trustedProxyHops(): number\n{\n const raw = Number.parseInt(process.env.TRUSTED_PROXY_HOPS ?? '', 10);\n\n return Number.isFinite(raw) && raw > 0 ? raw : 1;\n}\n\n/**\n * Build request headers for proxying\n * Forwards important headers from source and adds default headers\n *\n * @param sourceHeaders - Source headers (can be Headers object or Record)\n * @param defaultHeaders - Default headers to add\n */\nexport function buildProxyHeaders(\n sourceHeaders: Headers | Record<string, string>,\n defaultHeaders: Record<string, string>,\n): Headers\n{\n const headers = new Headers();\n\n // Forward important headers from source\n const headersToForward = [\n 'content-type',\n 'authorization',\n 'cookie',\n 'user-agent',\n 'accept',\n 'accept-language',\n // Forwarded so the backend proxy-guard can enforce its origin allowlist on\n // the real browser Origin; without this allowedOrigins would be a no-op.\n 'origin',\n ];\n\n for (const header of headersToForward)\n {\n const value = sourceHeaders instanceof Headers\n ? sourceHeaders.get(header)\n : sourceHeaders[header];\n\n if (value)\n {\n headers.set(header, value);\n }\n }\n\n // Forward the real client IP so the backend can rate-limit per user. The\n // backend trusts this header only on proxy-verified requests, so a direct\n // caller can't spoof it. Resolved hop-aware from the inbound X-Forwarded-For.\n const xff = sourceHeaders instanceof Headers\n ? sourceHeaders.get('x-forwarded-for')\n : sourceHeaders['x-forwarded-for'];\n const clientIp = clientIpFromForwardedChain(xff, trustedProxyHops());\n if (clientIp)\n {\n headers.set(PROXY_CLIENT_IP_HEADER, clientIp);\n }\n\n // Add default headers\n for (const [key, value] of Object.entries(defaultHeaders))\n {\n headers.set(key, value);\n }\n\n return headers;\n}\n\n/**\n * Parse cookies from Cookie header string\n *\n * @param cookieHeader - Cookie header string (e.g., \"session=abc; theme=dark\")\n * @returns Map of cookie name-value pairs\n */\nexport function parseCookies(cookieHeader: string | null | undefined): Map<string, string>\n{\n const cookiesMap = new Map<string, string>();\n\n if (!cookieHeader)\n {\n return cookiesMap;\n }\n\n const cookiePairs = cookieHeader.split(';').map(c => c.trim());\n for (const pair of cookiePairs)\n {\n const [name, ...valueParts] = pair.split('=');\n if (name && valueParts.length > 0)\n {\n const value = valueParts.join('='); // Handle = in cookie value\n cookiesMap.set(name.trim(), value.trim());\n }\n }\n\n return cookiesMap;\n}\n\n/**\n * Parse cookies from NextRequest (Next.js specific helper)\n * Combines cookies from both NextRequest.cookies and Cookie header\n */\nexport function parseCookiesFromNextRequest(request: NextRequest): Map<string, string>\n{\n const cookiesMap = new Map<string, string>();\n\n // Add cookies from NextRequest (browser cookies)\n for (const cookie of request.cookies.getAll())\n {\n cookiesMap.set(cookie.name, cookie.value);\n }\n\n // Add cookies from Cookie header (server-side forwarded cookies)\n const cookieHeader = request.headers.get('cookie');\n if (cookieHeader)\n {\n const parsed = parseCookies(cookieHeader);\n for (const [name, value] of parsed.entries())\n {\n cookiesMap.set(name, value);\n }\n }\n\n return cookiesMap;\n}\n\n// Mapping of option names to Set-Cookie attribute formats\nconst optionMappings: Array<{\n key: keyof CookieOptions;\n format: (value: any) => string | null;\n}> = [\n { key: 'httpOnly', format: (v) => v ? 'HttpOnly' : null },\n { key: 'secure', format: (v) => v ? 'Secure' : null },\n { key: 'sameSite', format: (v) => v ? `SameSite=${v}` : null },\n { key: 'maxAge', format: (v) => v !== undefined ? `Max-Age=${v}` : null },\n { key: 'path', format: (v) => v ? `Path=${v}` : null },\n { key: 'domain', format: (v) => v ? `Domain=${v}` : null },\n];\n\n/**\n * Build Set-Cookie header string from cookie options\n */\nexport function buildSetCookieHeader(cookie: SetCookie): string\n{\n const parts = [`${cookie.name}=${cookie.value}`];\n const options = cookie.options || {};\n\n for (const { key, format } of optionMappings)\n {\n const value = options[key];\n if (value !== undefined && value !== false)\n {\n const formatted = format(value);\n if (formatted)\n {\n parts.push(formatted);\n }\n }\n }\n\n return parts.join('; ');\n}\n\n/**\n * Build error response JSON\n */\nexport function buildErrorResponse(\n errorType: string,\n message: string,\n debug: boolean,\n error?: Error,\n): any\n{\n return {\n error: errorType,\n message,\n ...(debug && error?.stack && { stack: error.stack }),\n };\n}\n\nconst headersToForward = [\n 'content-type',\n 'cache-control',\n 'set-cookie',\n 'etag',\n 'last-modified',\n];\n\n/**\n * Forward response headers back to client\n */\nexport function forwardResponseHeaders(\n sourceHeaders: Headers,\n targetHeaders: Headers,\n): void\n{\n for (const header of headersToForward)\n {\n const value = sourceHeaders.get(header);\n if (value)\n {\n targetHeaders.set(header, value);\n }\n }\n}\n\n/**\n * Collect all interceptors (auto-discovered + config)\n */\nexport function collectInterceptors(\n autoDiscoverInterceptors: boolean,\n disableAutoInterceptors: string[] | undefined,\n configInterceptors: InterceptorRule[] | undefined,\n registry: InterceptorRegistry,\n): InterceptorRule[]\n{\n const allInterceptors: InterceptorRule[] = [];\n\n // Auto-discover from registry\n if (autoDiscoverInterceptors)\n {\n const registeredInterceptors = registry.getAll(disableAutoInterceptors || []);\n allInterceptors.push(...registeredInterceptors);\n }\n\n // Add config interceptors\n if (configInterceptors)\n {\n allInterceptors.push(...configInterceptors);\n }\n\n return allInterceptors;\n}\n\n/**\n * Build RequestInterceptorContext\n */\nexport function buildRequestContext(\n path: string,\n method: string,\n headers: Headers,\n body: any,\n searchParams: URLSearchParams,\n cookiesMap: Map<string, string>,\n request: NextRequest,\n): RequestInterceptorContext\n{\n return {\n path: `/${path}`,\n method,\n headers: Object.fromEntries(headers.entries()),\n body,\n query: Object.fromEntries(searchParams.entries()),\n cookies: cookiesMap,\n request,\n metadata: {},\n };\n}\n\n/**\n * Build ResponseInterceptorContext\n */\nexport function buildResponseContext(\n path: string,\n method: string,\n requestHeaders: Headers,\n requestBody: any,\n response: Response,\n responseBody: any,\n requestMetadata: Record<string, any>,\n cookies: Map<string, string>,\n): ResponseInterceptorContext\n{\n return {\n path: `/${path}`,\n method,\n request: {\n headers: Object.fromEntries(requestHeaders.entries()),\n body: requestBody,\n },\n response: {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n body: responseBody,\n },\n cookies,\n setCookies: [],\n metadata: requestMetadata,\n };\n}\n","/**\n * RPC-Style Proxy for define-route System\n *\n * Next.js API Route handler that resolves routeName to method/path\n * and forwards requests to SPFN backend.\n *\n * @example\n * ```typescript\n * // app/api/rpc/[routeName]/route.ts\n * import { createRpcProxy } from '@spfn/core/nextjs/server';\n * import { eventRouteMap } from '@spfn/core/event';\n * import { routeMap } from '@/generated/route-map';\n *\n * export const { GET, POST } = createRpcProxy({\n * routeMap: { ...routeMap, ...eventRouteMap },\n * });\n * ```\n *\n * The generated `routeMap` already holds the routes of every package router the\n * app mounts with `.packages()`, so no package map is merged by hand.\n * `eventRouteMap` is the exception: a hand-written constant, not a mounted\n * router.\n */\nimport { NextRequest, NextResponse } from 'next/server';\n\nimport { env } from '@spfn/core/config';\nimport { logger } from '@spfn/core/logger';\nimport type { HttpMethod } from '@spfn/core/route';\n\nimport { signProxyRequest, parseProxyKeySet } from '../../security/proxy-signature';\nimport { buildUrlWithParams, buildQueryString } from '../shared';\nimport { interceptorRegistry } from './interceptors';\nimport { executeRequestInterceptors, executeResponseInterceptors, filterMatchingInterceptors } from './interceptors';\nimport {\n buildProxyHeaders,\n parseCookiesFromNextRequest,\n buildSetCookieHeader,\n buildErrorResponse,\n forwardResponseHeaders,\n parseResponseBody,\n collectInterceptors,\n buildRequestContext,\n buildResponseContext,\n} from './helpers';\nimport type { TypedProxyConfig } from './types';\n\nconst rpcLogger = logger.child('@spfn/core:rpc-proxy');\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Route info from generated route map\n */\nexport interface RouteMapEntry\n{\n method: HttpMethod;\n path: string;\n}\n\n/**\n * Generated route map type\n */\nexport type RouteMap = Record<string, RouteMapEntry>;\n\n/**\n * RPC proxy configuration\n */\nexport interface RpcProxyConfig extends Omit<TypedProxyConfig, 'onRequest' | 'onResponse'>\n{\n /**\n * Route map containing routeName → {method, path} mappings\n *\n * The generated map carries the app's own routes and those of every package\n * router it mounts with `.packages()`. Merge `eventRouteMap` beside it when\n * the app uses SSE — that one is a constant rather than a mounted router.\n *\n * @example\n * ```typescript\n * import { eventRouteMap } from '@spfn/core/event';\n * import { routeMap } from '@/generated/route-map';\n *\n * export const { GET, POST } = createRpcProxy({\n * routeMap: { ...routeMap, ...eventRouteMap },\n * });\n * ```\n */\n routeMap: RouteMap;\n\n /**\n * Shared secret for signing proxy→backend requests (HMAC-SHA256).\n *\n * When set, every forwarded request carries an HMAC signature the backend's\n * proxy-guard middleware verifies, letting it reject direct-to-backend calls\n * that bypass this proxy. Set the SAME value here and on the backend.\n *\n * @default process.env.SPFN_PROXY_SECRET (undefined → signing disabled)\n */\n proxySecret?: string;\n}\n\n// ============================================================================\n// RPC Proxy Handler\n// ============================================================================\n\n/**\n * Create RPC proxy handler for Next.js API Route\n *\n * Handles requests in the format:\n * - GET /api/rpc/{routeName}?input={...}\n * - POST /api/rpc/{routeName} with body\n *\n * Resolves routeName to actual HTTP method and path from routeMap,\n * then forwards to SPFN backend.\n */\nexport function createRpcProxy(config: RpcProxyConfig)\n{\n const {\n apiUrl = env.SPFN_API_URL || 'http://localhost:8790',\n debug = env.NODE_ENV === 'development',\n timeout = env.RPC_PROXY_TIMEOUT,\n headers: defaultHeaders = {},\n interceptors,\n autoDiscoverInterceptors = true,\n disableAutoInterceptors,\n proxySecret = env.SPFN_PROXY_SECRET,\n routeMap,\n } = config;\n\n // Parse the active signing key once — it's fixed for the proxy's lifetime.\n // Use the SAME parser the backend uses (comma key set) and take the active key,\n // so a `v2:new,v1:old` secret is interpreted identically on both sides.\n const proxyKey = proxySecret ? (parseProxyKeySet([proxySecret])[0] ?? null) : null;\n\n // proxy-guard signs route-relative paths; if SPFN_API_URL carries a base path the\n // backend keeps (no ingress strip), the signed path won't match c.req.url and\n // strict mode 403s everything. Warn loudly so it's diagnosable.\n if (proxyKey)\n {\n try\n {\n const basePath = new URL(apiUrl).pathname;\n if (basePath !== '/' && basePath !== '')\n {\n rpcLogger.warn(\n `SPFN_API_URL has a base path (\"${basePath}\"). proxy-guard signs route-relative paths, `\n + 'so the backend must receive paths WITHOUT this prefix (e.g. ingress strip) or strict '\n + 'mode will reject all signed requests with 403.',\n );\n }\n }\n catch\n {\n // invalid apiUrl is surfaced elsewhere\n }\n }\n\n /**\n * Resolve route info from routeMap\n */\n function resolveRoute(routeName: string): { method: string; path: string } | null\n {\n const entry = routeMap[routeName];\n if (entry)\n {\n return { method: entry.method, path: entry.path };\n }\n\n return null;\n }\n\n /**\n * Handle RPC request\n */\n async function handleRpc(\n request: NextRequest,\n context: { params: Promise<{ routeName?: string }> },\n ): Promise<NextResponse>\n {\n const startTime = Date.now();\n const params = await context.params;\n\n try\n {\n const routeName = params.routeName;\n\n if (!routeName)\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Missing routeName parameter', debug),\n { status: 400 },\n );\n }\n\n // Parse input from query string (GET) or body (POST)\n let input: {\n params?: Record<string, any>;\n query?: Record<string, any>;\n body?: Record<string, any>;\n formData?: Record<string, any>;\n headers?: Record<string, any>;\n cookies?: Record<string, any>;\n } = {};\n let rawFormData: FormData | null = null;\n\n if (request.method === 'GET')\n {\n const inputParam = request.nextUrl.searchParams.get('input');\n if (inputParam)\n {\n try\n {\n input = JSON.parse(decodeURIComponent(inputParam));\n }\n catch\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Invalid input parameter', debug),\n { status: 400 },\n );\n }\n }\n }\n else\n {\n // POST - check Content-Type for formData vs JSON\n const contentType = request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data'))\n {\n // Parse multipart/form-data\n try\n {\n rawFormData = await request.formData();\n\n // Extract __metadata if present (contains params, query, etc.)\n const metadataStr = rawFormData.get('__metadata');\n if (metadataStr && typeof metadataStr === 'string')\n {\n const metadata = JSON.parse(metadataStr);\n input.params = metadata.params;\n input.query = metadata.query;\n input.headers = metadata.headers;\n input.cookies = metadata.cookies;\n }\n\n // Collect formData fields (excluding __metadata)\n input.formData = {};\n rawFormData.forEach((value, key) =>\n {\n if (key === '__metadata') return;\n\n const existing = input.formData![key];\n if (existing !== undefined)\n {\n // Multiple values with same key\n if (Array.isArray(existing))\n {\n existing.push(value);\n }\n else\n {\n input.formData![key] = [existing, value];\n }\n }\n else\n {\n input.formData![key] = value;\n }\n });\n }\n catch (error)\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Invalid form data', debug),\n { status: 400 },\n );\n }\n }\n else\n {\n // Parse JSON body\n try\n {\n input = await request.json();\n }\n catch\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Invalid JSON body', debug),\n { status: 400 },\n );\n }\n }\n }\n\n // Resolve route info from routeMap\n const routeInfo = resolveRoute(routeName);\n\n if (!routeInfo)\n {\n rpcLogger.warn(`Route not found: ${routeName}`);\n\n return NextResponse.json(\n buildErrorResponse('Not Found', `Route \"${routeName}\" not found`, debug),\n { status: 404 },\n );\n }\n\n const { method: targetMethod, path: targetPath } = routeInfo;\n\n // Build target URL with params and query\n const inputParams = input.params || {};\n const inputQuery = input.query || {};\n const inputBody = input.body;\n const inputFormData = input.formData;\n const hasFormData = rawFormData !== null && inputFormData && Object.keys(inputFormData).length > 0;\n\n const resolvedPath = buildUrlWithParams(targetPath, inputParams);\n const queryString = buildQueryString(inputQuery);\n const targetUrl = `${apiUrl}${resolvedPath}${queryString}`;\n\n if (debug)\n {\n rpcLogger.debug('→ RPC request', {\n routeName,\n targetMethod,\n targetPath: resolvedPath,\n targetUrl,\n hasBody: !!inputBody,\n hasFormData,\n });\n }\n\n // Build headers\n const headers = buildProxyHeaders(request.headers, defaultHeaders);\n\n // Remove Content-Type for formData (let fetch set it with boundary)\n if (hasFormData)\n {\n headers.delete('content-type');\n }\n\n // Build fetch options\n const fetchOptions: RequestInit = {\n method: targetMethod,\n headers,\n };\n\n // Add body for POST/PUT/PATCH\n if (['POST', 'PUT', 'PATCH'].includes(targetMethod))\n {\n if (hasFormData && rawFormData)\n {\n // Forward formData to backend (rebuild without __metadata)\n const forwardFormData = new FormData();\n rawFormData.forEach((value, key) =>\n {\n if (key !== '__metadata')\n {\n forwardFormData.append(key, value);\n }\n });\n fetchOptions.body = forwardFormData;\n }\n else if (inputBody)\n {\n fetchOptions.body = JSON.stringify(inputBody);\n }\n }\n\n // ============================================================\n // Advanced Interceptors - BEFORE FETCH\n // ============================================================\n\n // Collect and filter interceptors\n const allInterceptors = collectInterceptors(autoDiscoverInterceptors, disableAutoInterceptors, interceptors, interceptorRegistry);\n const matchingInterceptors = filterMatchingInterceptors(allInterceptors, resolvedPath, targetMethod);\n\n if (debug && matchingInterceptors.length > 0)\n {\n rpcLogger.debug(`Found ${matchingInterceptors.length} matching interceptors for ${targetMethod} ${resolvedPath}`);\n }\n\n // Create RequestInterceptorContext\n const cookiesMap = parseCookiesFromNextRequest(request);\n const requestCtx = buildRequestContext(\n resolvedPath.slice(1), // Remove leading slash\n targetMethod,\n headers,\n inputBody,\n new URLSearchParams(queryString.slice(1)), // Remove leading ?\n cookiesMap,\n request,\n );\n\n // Execute request interceptors\n const requestInterceptorsToRun = matchingInterceptors.map(r => r.request).filter((i): i is NonNullable<typeof i> => !!i);\n if (requestInterceptorsToRun.length > 0)\n {\n await executeRequestInterceptors(requestCtx, requestInterceptorsToRun);\n\n // Apply modified headers\n for (const [key, value] of Object.entries(requestCtx.headers))\n {\n headers.set(key, value);\n }\n\n // Apply modified body\n if (requestCtx.body)\n {\n fetchOptions.body = JSON.stringify(requestCtx.body);\n }\n }\n\n // An interceptor refused the request (e.g. the CSRF check in @spfn/auth).\n // Return its response without touching the backend; no response\n // interceptor runs, so the only cookies a refusal can carry are the\n // ones the refusing interceptor attached to the abort. The CSRF check\n // attaches a fresh token there, so the refusal is what repairs the\n // browser instead of merely reporting the damage.\n if (requestCtx.abort)\n {\n rpcLogger.warn('Request refused by an interceptor', {\n routeName,\n status: requestCtx.abort.status,\n });\n\n const abortResponse = NextResponse.json(\n requestCtx.abort.body,\n { status: requestCtx.abort.status },\n );\n\n for (const cookie of requestCtx.abort.setCookies ?? [])\n {\n abortResponse.headers.append('Set-Cookie', buildSetCookieHeader(cookie));\n }\n\n return abortResponse;\n }\n\n // ============================================================\n // Proxy → Backend signature (proxy-guard)\n // ============================================================\n // Sign the FINAL request (after interceptors settled body/headers) so\n // the backend can prove it came through this trusted proxy. JSON body\n // is hashed into the signature; large multipart uploads are excluded.\n if (proxyKey)\n {\n const signedBody = typeof fetchOptions.body === 'string' ? fetchOptions.body : undefined;\n // Sign the route-relative path (no SPFN_API_URL base prefix) so it\n // matches the backend's `new URL(c.req.url).pathname` whether the\n // prefix is absent or stripped by an ingress. resolvedPath is already\n // the percent-encoded wire form; queryString is the raw search.\n const signatureHeaders = signProxyRequest({\n key: proxyKey,\n method: targetMethod,\n path: resolvedPath,\n query: queryString,\n body: signedBody,\n });\n\n for (const [headerName, value] of Object.entries(signatureHeaders))\n {\n headers.set(headerName, value);\n }\n }\n\n // Execute fetch with timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try\n {\n const response = await fetch(targetUrl, {\n ...fetchOptions,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n let body = await parseResponseBody(response);\n\n // ============================================================\n // Advanced Interceptors - AFTER FETCH\n // ============================================================\n\n // Create ResponseInterceptorContext\n const responseCtx = buildResponseContext(\n resolvedPath.slice(1),\n targetMethod,\n headers,\n inputBody,\n response,\n body,\n requestCtx.metadata,\n requestCtx.cookies,\n );\n\n // Execute response interceptors\n const responseInterceptorsToRun = matchingInterceptors.map(r => r.response).filter((i): i is NonNullable<typeof i> => !!i);\n if (responseInterceptorsToRun.length > 0)\n {\n await executeResponseInterceptors(responseCtx, responseInterceptorsToRun);\n body = responseCtx.response.body;\n }\n\n const duration = Date.now() - startTime;\n\n if (debug)\n {\n rpcLogger.debug('← RPC response', {\n routeName,\n status: responseCtx.response.status,\n duration: `${duration}ms`,\n });\n }\n\n // Build Next.js response\n // 204 No Content should use NextResponse directly, not NextResponse.json()\n const nextResponse = responseCtx.response.status === 204\n ? new NextResponse(null, {\n status: 204,\n statusText: responseCtx.response.statusText,\n })\n : NextResponse.json(body, {\n status: responseCtx.response.status,\n statusText: responseCtx.response.statusText,\n });\n\n // Forward response headers\n forwardResponseHeaders(response.headers, nextResponse.headers);\n\n // Apply setCookies from interceptors\n for (const cookie of responseCtx.setCookies)\n {\n const setCookieHeader = buildSetCookieHeader(cookie);\n nextResponse.headers.append('Set-Cookie', setCookieHeader);\n\n if (debug)\n {\n rpcLogger.debug('Set-Cookie header added', {\n name: cookie.name,\n });\n }\n }\n\n return nextResponse;\n }\n catch (error)\n {\n clearTimeout(timeoutId);\n\n // Handle timeout\n if (error instanceof Error && error.name === 'AbortError')\n {\n rpcLogger.error('Request timeout', {\n routeName,\n targetUrl,\n timeout,\n });\n\n return NextResponse.json(\n buildErrorResponse('Gateway Timeout', `Request timed out after ${timeout}ms`, debug, error),\n { status: 504 },\n );\n }\n\n // Handle other fetch errors\n const fetchErr = error as Error;\n rpcLogger.error('Fetch error', {\n routeName,\n targetUrl,\n error: fetchErr.message,\n });\n\n return NextResponse.json(\n buildErrorResponse('Bad Gateway', fetchErr.message || 'Failed to connect to backend', debug, fetchErr),\n { status: 502 },\n );\n }\n }\n catch (error)\n {\n const duration = Date.now() - startTime;\n const err = error as Error;\n\n rpcLogger.error('RPC proxy error', {\n error: err.message,\n stack: err.stack,\n duration: `${duration}ms`,\n });\n\n return NextResponse.json(\n buildErrorResponse('Internal Server Error', err.message || 'Unknown error', debug, err),\n { status: 500 },\n );\n }\n }\n\n // Return route handlers\n return {\n GET: (req: NextRequest, context: { params: Promise<{ routeName?: string }> }) =>\n handleRpc(req, context),\n POST: (req: NextRequest, context: { params: Promise<{ routeName?: string }> }) =>\n handleRpc(req, context),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/security/proxy-signature.ts","../../src/nextjs/shared.ts","../../src/nextjs/proxy/interceptors/helpers.ts","../../src/nextjs/proxy/interceptors/registry.ts","../../src/nextjs/proxy/helpers.ts","../../src/nextjs/proxy/rpc.ts"],"names":["headersToForward"],"mappings":";;;;;;AA0BO,IAAM,sBAAA,GAAyB,wBAAA;AAC/B,IAAM,sB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A,IACJ;AAAA,EACJ;AAGA,EAAA,OAAO;AAAA,IACH,KAAK,CAAC,GAAA,EAAkB,OAAA,KACpB,SAAA,CAAU,KAAK,OAAO,CAAA;AAAA,IAC1B,MAAM,CAAC,GAAA,EAAkB,OAAA,KACrB,SAAA,CAAU,KAAK,OAAO;AAAA,GAC9B;AACJ","file":"server.js","sourcesContent":["/**\n * Proxy → Backend request signing (HMAC-SHA256) with key rotation\n *\n * Shared between the Next.js RPC proxy (which signs outbound requests) and the\n * backend proxy-guard middleware (which verifies them). Keeping the canonical\n * string and HMAC logic in one pure module guarantees both sides agree.\n *\n * The signature proves a request passed through a trusted proxy that holds the\n * shared secret. It does NOT authenticate the end user — that is the JWT layer's\n * job — and it cannot stop a client from calling the proxy itself. Its role is to\n * stop direct-to-backend calls that bypass the proxy.\n *\n * Keys are identified by a short keyId so secrets can be rotated without downtime:\n * the proxy signs with the active key and stamps its keyId in a header; the\n * backend keeps a set of accepted keys (current + previous) and selects by keyId.\n * Roll a new key in, let both sides pick it up, switch the proxy to it, then drop\n * the old one after a grace period — no request is ever rejected mid-rotation.\n *\n * @module security/proxy-signature\n */\nimport { createHmac, randomBytes, timingSafeEqual, createHash } from 'node:crypto';\n\n// ============================================================================\n// Header names\n// ============================================================================\n\nexport const PROXY_SIGNATURE_HEADER = 'x-spfn-proxy-signature';\nexport const PROXY_TIMESTAMP_HEADER = 'x-spfn-proxy-timestamp';\nexport const PROXY_NONCE_HEADER = 'x-spfn-proxy-nonce';\nexport const PROXY_KEY_ID_HEADER = 'x-spfn-proxy-key-id';\n/**\n * The real client IP, forwarded by the proxy. The backend trusts this only when\n * the request is proxy-verified (proxy-guard `clientType` ≠ untrusted) — the proxy\n * itself sees no spoofable hop, so a verified request's value is the true client.\n */\nexport const PROXY_CLIENT_IP_HEADER = 'x-spfn-proxy-client-ip';\n\n/** keyId used when a raw secret carries no `keyId:` prefix (back-compat). */\nexport const DEFAULT_KEY_ID = 'default';\n\n// ============================================================================\n// Keys\n// ============================================================================\n\n/**\n * A signing key: a short identifier plus its secret. Encoded in env as\n * `<keyId>:<secret>` (e.g. `v2:9f3c...`); a bare secret gets `DEFAULT_KEY_ID`.\n */\nexport interface ProxyKey\n{\n keyId: string;\n secret: string;\n}\n\n/**\n * Parse one `<keyId>:<secret>` (or bare `<secret>`) string into a ProxyKey.\n * keyId is everything before the FIRST colon; the secret keeps any later colons.\n */\nexport function parseProxyKey(raw: string): ProxyKey\n{\n const idx = raw.indexOf(':');\n if (idx === -1)\n {\n return { keyId: DEFAULT_KEY_ID, secret: raw };\n }\n\n // A leading colon (':secret') yields an empty keyId; the backend treats an empty\n // keyId header as \"missing\" and rejects, so normalize it to DEFAULT_KEY_ID.\n return { keyId: raw.slice(0, idx) || DEFAULT_KEY_ID, secret: raw.slice(idx + 1) };\n}\n\n/**\n * Build the backend's accepted key set from raw env values. Each input may be a\n * single key or a comma-separated list (for multiple grace keys). Earlier inputs\n * win on keyId collision, so pass the active secret first.\n */\nexport function parseProxyKeySet(raws: Array<string | undefined | null>): ProxyKey[]\n{\n const keys: ProxyKey[] = [];\n const seen = new Set<string>();\n\n for (const raw of raws)\n {\n if (!raw)\n {\n continue;\n }\n\n for (const part of raw.split(','))\n {\n const trimmed = part.trim();\n if (!trimmed)\n {\n continue;\n }\n\n const key = parseProxyKey(trimmed);\n if (!key.secret || seen.has(key.keyId))\n {\n continue;\n }\n\n seen.add(key.keyId);\n keys.push(key);\n }\n }\n\n return keys;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * The parts of a request that are bound into the signature.\n */\nexport interface SignatureParts\n{\n /** Resolved backend HTTP method (GET/POST/PUT/...) */\n method: string;\n\n /**\n * Raw (wire) backend path, percent-encoding preserved, leading slash, NO query.\n * Proxy signs its outbound request-target path; the backend reconstructs the\n * SAME bytes from `new URL(c.req.url).pathname` (NOT the decoded `c.req.path`).\n */\n path: string;\n\n /**\n * Raw (wire) query string including leading `?`, or '' when there is none.\n * Both sides use the verbatim search string so query params are authenticated.\n */\n query: string;\n\n /** Unix epoch milliseconds, as a string */\n timestamp: string;\n\n /** Random per-request nonce */\n nonce: string;\n\n /**\n * SHA-256 hex of the raw request body, or empty string when there is no body\n * (GET/HEAD, or multipart uploads which are excluded by design). Bound for ANY\n * non-multipart content-type, not just application/json.\n *\n * Multipart is excluded so the proxy can stream large uploads without buffering\n * them to hash. The signature therefore proves *provenance* (came through the\n * trusted proxy) and binds method/path/query/timestamp for a multipart request,\n * but NOT the body bytes. Two consequences, by design:\n * - Multipart *content* integrity/validation is the application's job (size,\n * type, checksum, business rules) — not the transport signature's.\n * - If you don't trust the proxy→backend hop itself, secure it with TLS/mTLS;\n * signing a prefix of the stream would be a half-measure (the tail stays\n * unprotected) and is intentionally not done.\n */\n bodyHash: string;\n}\n\n/**\n * Headers produced by signing — ready to set on the outbound fetch.\n */\nexport interface SignatureHeaders\n{\n [PROXY_SIGNATURE_HEADER]: string;\n [PROXY_TIMESTAMP_HEADER]: string;\n [PROXY_NONCE_HEADER]: string;\n [PROXY_KEY_ID_HEADER]: string;\n}\n\n// ============================================================================\n// Canonical string + HMAC\n// ============================================================================\n\n/**\n * Build the canonical string that gets signed. Field order is fixed and each\n * field is newline-separated, so a captured signature cannot be replayed against\n * a different method, path, or body.\n */\nexport function buildCanonicalString(parts: SignatureParts): string\n{\n return [parts.method.toUpperCase(), parts.path, parts.query, parts.timestamp, parts.nonce, parts.bodyHash].join('\\n');\n}\n\n/**\n * Hash a request body. Accepts a string (proxy side, from JSON.stringify) or a\n * Buffer (backend side, straight from the stream — avoids a bytes→string→bytes\n * round-trip). Returns '' for empty/no body. A utf8 string and its Buffer hash\n * identically, so both sides agree.\n */\nexport function hashBody(body: string | Buffer | undefined | null): string\n{\n if (!body || body.length === 0)\n {\n return '';\n }\n\n return typeof body === 'string'\n ? createHash('sha256').update(body, 'utf8').digest('hex')\n : createHash('sha256').update(body).digest('hex');\n}\n\n/**\n * Compute the HMAC-SHA256 signature (hex) for the given parts.\n */\nexport function computeSignature(secret: string, parts: SignatureParts): string\n{\n return createHmac('sha256', secret).update(buildCanonicalString(parts)).digest('hex');\n}\n\n/**\n * Generate a fresh random nonce (hex).\n */\nexport function generateNonce(): string\n{\n return randomBytes(16).toString('hex');\n}\n\n// ============================================================================\n// Sign (proxy side)\n// ============================================================================\n\nexport interface SignInput\n{\n /** The active signing key. */\n key: ProxyKey;\n method: string;\n /** Raw (wire) path, leading slash, percent-encoding preserved, NO query. */\n path: string;\n /** Raw (wire) query string including leading `?`, or '' / omitted for none. */\n query?: string;\n /** Raw request body string, if any. Omit for GET / multipart uploads. */\n body?: string | null;\n /** Override the timestamp (testing). Defaults to Date.now(). */\n timestamp?: string;\n /** Override the nonce (testing). Defaults to a random nonce. */\n nonce?: string;\n}\n\n/**\n * Sign an outbound proxy request and return the headers to attach (including the\n * keyId so the backend knows which key to verify against).\n */\nexport function signProxyRequest(input: SignInput): SignatureHeaders\n{\n const timestamp = input.timestamp ?? String(Date.now());\n const nonce = input.nonce ?? generateNonce();\n const signature = computeSignature(input.key.secret, {\n method: input.method,\n path: input.path,\n query: input.query ?? '',\n timestamp,\n nonce,\n bodyHash: hashBody(input.body),\n });\n\n return {\n [PROXY_SIGNATURE_HEADER]: signature,\n [PROXY_TIMESTAMP_HEADER]: timestamp,\n [PROXY_NONCE_HEADER]: nonce,\n [PROXY_KEY_ID_HEADER]: input.key.keyId,\n };\n}\n\n// ============================================================================\n// Verify (backend side)\n// ============================================================================\n\nexport type VerifyFailureReason =\n | 'missing-headers'\n | 'stale-timestamp'\n | 'bad-timestamp'\n | 'unknown-key'\n | 'signature-mismatch';\n\n// ('body-read-error' / 'origin-not-allowed' / 'nonce-replay' are guard-level\n// reasons carried separately by the middleware, not produced by verify itself.)\n\nexport interface VerifyResult\n{\n valid: boolean;\n reason?: VerifyFailureReason;\n /** The verified nonce, for optional replay tracking by the caller. */\n nonce?: string;\n /** The keyId the request was verified against (for logging/metrics). */\n keyId?: string;\n}\n\nexport interface VerifyInput\n{\n /** Accepted keys (active + grace). Selected by the request's keyId header. */\n keys: ProxyKey[];\n method: string;\n /** Raw (wire) path from `new URL(c.req.url).pathname` — NOT decoded `c.req.path`. */\n path: string;\n /** Raw (wire) query string from `new URL(c.req.url).search`, or '' for none. */\n query?: string;\n /** Raw request body (string or Buffer) as received, if any. */\n body?: string | Buffer | null;\n signature: string | null | undefined;\n timestamp: string | null | undefined;\n nonce: string | null | undefined;\n keyId: string | null | undefined;\n /** Allowed clock skew / replay window in ms. Default 30s. */\n windowMs?: number;\n /** Current time (testing). Defaults to Date.now(). */\n now?: number;\n}\n\n/**\n * Constant-time hex string comparison. Returns false on any length diff.\n *\n * Buffer.from(_, 'hex') does NOT throw on invalid hex — it silently truncates at\n * the first bad char — so a malformed signature yields a shorter buffer that the\n * length check rejects. No try/catch needed.\n */\nfunction safeEqualHex(a: string, b: string): boolean\n{\n const bufA = Buffer.from(a, 'hex');\n const bufB = Buffer.from(b, 'hex');\n\n if (bufA.length === 0 || bufA.length !== bufB.length)\n {\n return false;\n }\n\n return timingSafeEqual(bufA, bufB);\n}\n\n/**\n * Verify an inbound request's proxy signature against the accepted key set.\n *\n * Checks, in order: headers present, timestamp within window (replay guard),\n * keyId known, and HMAC match. Nonce-level replay rejection is left to the caller\n * (optional, Redis-backed) since not every deployment has a shared store.\n */\nexport function verifyProxyRequest(input: VerifyInput): VerifyResult\n{\n const { signature, timestamp, nonce, keyId } = input;\n\n if (!signature || !timestamp || !nonce || !keyId)\n {\n return { valid: false, reason: 'missing-headers' };\n }\n\n const ts = Number(timestamp);\n if (!Number.isFinite(ts))\n {\n return { valid: false, reason: 'bad-timestamp' };\n }\n\n const now = input.now ?? Date.now();\n const windowMs = input.windowMs ?? 30_000;\n if (Math.abs(now - ts) > windowMs)\n {\n return { valid: false, reason: 'stale-timestamp' };\n }\n\n const key = input.keys.find(k => k.keyId === keyId);\n if (!key)\n {\n return { valid: false, reason: 'unknown-key' };\n }\n\n const expected = computeSignature(key.secret, {\n method: input.method,\n path: input.path,\n query: input.query ?? '',\n timestamp,\n nonce,\n bodyHash: hashBody(input.body),\n });\n\n if (!safeEqualHex(signature, expected))\n {\n return { valid: false, reason: 'signature-mismatch' };\n }\n\n return { valid: true, nonce, keyId };\n}\n","/**\n * Shared utilities for Next.js client and proxy modules\n *\n * Contains common functions used by both client and proxy to avoid code duplication.\n */\n\n/**\n * Build URL with path parameters replaced\n *\n * @example\n * buildUrlWithParams('/users/:id/posts/:postId', { id: '123', postId: '456' })\n * // Returns: '/users/123/posts/456'\n */\nexport function buildUrlWithParams(path: string, params: Record<string, any>): string\n{\n let url = path;\n for (const [key, value] of Object.entries(params))\n {\n url = url.replace(`:${key}`, encodeURIComponent(String(value)));\n }\n\n return url;\n}\n\n/**\n * Build query string from object\n *\n * @example\n * buildQueryString({ page: '1', limit: '10', tags: ['foo', 'bar'] })\n * // Returns: '?page=1&limit=10&tags=foo&tags=bar'\n */\nexport function buildQueryString(query: Record<string, any>): string\n{\n if (Object.keys(query).length === 0)\n {\n return '';\n }\n\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(query))\n {\n if (Array.isArray(value))\n {\n value.forEach((v) => searchParams.append(key, String(v)));\n }\n else\n {\n searchParams.append(key, String(value));\n }\n }\n\n return `?${searchParams.toString()}`;\n}\n\n/**\n * Build Cookie header string from cookies object\n *\n * @example\n * buildCookieHeader({ session: 'abc123', theme: 'dark' })\n * // Returns: 'session=abc123; theme=dark'\n */\nexport function buildCookieHeader(cookies: Record<string, string>): string\n{\n return Object.entries(cookies)\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n}\n\n/**\n * Parse response body based on content type\n *\n * Handles:\n * - 204 No Content: returns null (no body expected)\n * - application/json: parses JSON body\n * - Other content types: returns raw text\n */\nexport async function parseResponseBody(response: Response): Promise<any>\n{\n // 204 No Content has no body\n if (response.status === 204)\n {\n return null;\n }\n\n const contentType = response.headers.get('content-type');\n\n if (contentType?.includes('application/json'))\n {\n const text = await response.text();\n\n return text ? JSON.parse(text) : null;\n }\n else\n {\n return await response.text();\n }\n}\n","/**\n * SPFN Next.js Proxy Interceptor Execution Engine\n */\n\nimport type {\n InterceptorRule,\n RequestInterceptor,\n ResponseInterceptor,\n RequestInterceptorContext,\n ResponseInterceptorContext,\n} from './types';\n\n/**\n * Check if path matches pattern\n *\n * Supports:\n * - Wildcards: '/_auth/*' matches '/_auth/login'\n * - Path params: '/users/:id' matches '/users/123'\n * - RegExp: /^\\/_auth\\/.+$/ matches '/_auth/login'\n * - Exact match: '/_auth/login' matches '/_auth/login'\n * - All: '*' matches any path\n *\n * @param path - Request path to test\n * @param pattern - Pattern to match against\n * @returns True if path matches pattern\n */\nexport function matchPath(path: string, pattern: string | RegExp): boolean\n{\n // Match all\n if (pattern === '*')\n {\n return true;\n }\n\n // RegExp pattern\n if (pattern instanceof RegExp)\n {\n return pattern.test(path);\n }\n\n // String pattern\n // Convert wildcard pattern to RegExp\n // '/_auth/*' -> /^\\/_auth\\/.*/\n // '/users/:id' -> /^\\/users\\/[^/]+$/\n const regexPattern = pattern\n .replace(/\\*/g, '.*')\n .replace(/:[^/]+/g, '[^/]+')\n .replace(/\\//g, '\\\\/');\n\n const regex = new RegExp(`^${regexPattern}$`);\n\n return regex.test(path);\n}\n\n/**\n * Check if method matches pattern\n *\n * @param method - Request method (e.g., 'POST')\n * @param pattern - Method pattern (e.g., 'POST' or ['POST', 'PUT'])\n * @returns True if method matches pattern\n */\nexport function matchMethod(\n method: string,\n pattern?: string | string[],\n): boolean\n{\n // No method filter = match all\n if (!pattern)\n {\n return true;\n }\n\n // Single method\n if (typeof pattern === 'string')\n {\n return method.toUpperCase() === pattern.toUpperCase();\n }\n\n // Multiple methods\n return pattern.some((m) => m.toUpperCase() === method.toUpperCase());\n}\n\n/**\n * Filter interceptors that match the request\n *\n * @param rules - All interceptor rules\n * @param path - Request path\n * @param method - Request method\n * @returns Matched interceptors\n */\nexport function filterMatchingInterceptors(\n rules: InterceptorRule[],\n path: string,\n method: string,\n): InterceptorRule[]\n{\n return rules.filter((rule) => \n {\n return matchPath(path, rule.pathPattern) && matchMethod(method, rule.method);\n });\n}\n\n/**\n * Execute request interceptors in chain\n *\n * Interceptors are executed in order:\n * 1. First registered interceptor\n * 2. Second registered interceptor\n * 3. ... and so on\n *\n * Each interceptor must call next() to continue the chain.\n * If next() is not called, the chain stops and remaining interceptors are skipped.\n *\n * @param context - Request interceptor context\n * @param interceptors - Interceptors to execute\n */\nexport async function executeRequestInterceptors(\n context: RequestInterceptorContext,\n interceptors: RequestInterceptor[],\n): Promise<void>\n{\n let index = 0;\n\n const next = async (): Promise<void> => \n {\n if (index >= interceptors.length)\n {\n return;\n }\n\n const interceptor = interceptors[index];\n index++;\n\n await interceptor(context, next);\n };\n\n await next();\n}\n\n/**\n * Execute response interceptors in chain\n *\n * Interceptors are executed in order:\n * 1. First registered interceptor\n * 2. Second registered interceptor\n * 3. ... and so on\n *\n * Each interceptor must call next() to continue the chain.\n * If next() is not called, the chain stops and remaining interceptors are skipped.\n *\n * @param context - Response interceptor context\n * @param interceptors - Interceptors to execute\n */\nexport async function executeResponseInterceptors(\n context: ResponseInterceptorContext,\n interceptors: ResponseInterceptor[],\n): Promise<void>\n{\n let index = 0;\n\n const next = async (): Promise<void> => \n {\n if (index >= interceptors.length)\n {\n return;\n }\n\n const interceptor = interceptors[index];\n index++;\n\n await interceptor(context, next);\n };\n\n await next();\n}\n","/**\n * Global Interceptor Registry\n *\n * Allows packages to automatically register their interceptors\n * for Next.js proxy without manual configuration.\n *\n * Uses globalThis for persistence across module reloads (HMR).\n */\nimport type { InterceptorRule } from './types';\n\n// ============================================================================\n// Global Type Declarations\n// ============================================================================\n\n/**\n * Extend globalThis with interceptor registry\n *\n * Using globalThis allows the registry to persist across module reloads (HMR).\n * preventing duplicate registrations during development with HMR.\n */\ndeclare global\n{\n var __SPFN_INTERCEPTOR_REGISTRY__: InterceptorRegistry | undefined;\n}\n\n/**\n * Global interceptor registry\n *\n * Packages register their interceptors on import,\n * and proxy automatically discovers and applies them.\n */\nexport class InterceptorRegistry\n{\n private interceptors = new Map<string, InterceptorRule[]>();\n\n /**\n * Register interceptors for a package\n *\n * @param packageName - Unique package identifier (e.g., 'auth', 'storage')\n * @param interceptors - Array of interceptor rules\n *\n * @example\n * ```typescript\n * registerInterceptors('auth', [\n * {\n * pathPattern: '/_auth/*',\n * request: async (ctx, next) => { ... }\n * }\n * ]);\n * ```\n */\n register(packageName: string, interceptors: InterceptorRule[]): void\n {\n if (!this.interceptors.has(packageName))\n {\n this.interceptors.set(packageName, interceptors);\n }\n }\n\n /**\n * Get all registered interceptors\n *\n * @param exclude - Package names to exclude\n * @returns Flat array of all interceptor rules\n */\n getAll(exclude: string[] = []): InterceptorRule[]\n {\n const all: InterceptorRule[] = [];\n\n for (const [packageName, interceptors] of this.interceptors.entries())\n {\n if (!exclude.includes(packageName))\n {\n all.push(...interceptors);\n }\n }\n\n return all;\n }\n\n /**\n * Get interceptors for specific package\n *\n * @param packageName - Package identifier\n * @returns Interceptor rules or undefined\n */\n get(packageName: string): InterceptorRule[] | undefined\n {\n return this.interceptors.get(packageName);\n }\n\n /**\n * Get list of registered package names\n */\n getPackageNames(): string[]\n {\n return Array.from(this.interceptors.keys());\n }\n\n /**\n * Check if package has registered interceptors\n */\n has(packageName: string): boolean\n {\n return this.interceptors.has(packageName);\n }\n\n /**\n * Unregister interceptors for a package\n *\n * @param packageName - Package identifier\n */\n unregister(packageName: string): void\n {\n this.interceptors.delete(packageName);\n }\n\n /**\n * Clear all registered interceptors\n *\n * Useful for testing\n */\n clear(): void\n {\n this.interceptors.clear();\n }\n\n /**\n * Get total count of registered interceptors\n */\n count(): number\n {\n let total = 0;\n for (const interceptors of this.interceptors.values())\n {\n total += interceptors.length;\n }\n\n return total;\n }\n}\n\n/**\n * Global singleton registry instance\n *\n * Uses globalThis to persist across module reloads (HMR).\n * This prevents duplicate registrations during development.\n */\nexport const interceptorRegistry = (() =>\n{\n if (!globalThis.__SPFN_INTERCEPTOR_REGISTRY__)\n {\n globalThis.__SPFN_INTERCEPTOR_REGISTRY__ = new InterceptorRegistry();\n }\n\n return globalThis.__SPFN_INTERCEPTOR_REGISTRY__;\n})();\n\n/**\n * Register interceptors for a package\n *\n * This should be called during package initialization (on import).\n * The interceptors will be automatically applied by the Next.js proxy.\n *\n * @param packageName - Unique package identifier (e.g., 'auth', 'storage')\n * @param interceptors - Array of interceptor rules\n *\n * @example\n * ```typescript\n * // packages/auth/src/adapters/nextjs/interceptors/index.ts\n * import { registerInterceptors } from '@spfn/core/nextjs';\n *\n * const authInterceptors = [\n * {\n * pathPattern: '/_auth/*',\n * request: async (ctx, next) => {\n * // Add JWT token\n * ctx.headers['Authorization'] = 'Bearer token';\n * await next();\n * }\n * }\n * ];\n *\n * // Auto-register on import\n * registerInterceptors('auth', authInterceptors);\n * ```\n */\nexport function registerInterceptors(\n packageName: string,\n interceptors: InterceptorRule[],\n): void\n{\n interceptorRegistry.register(packageName, interceptors);\n}\n","/**\n * Helper functions for proxy handler\n * Separates utility logic from main proxy handler for better maintainability\n */\nimport { NextRequest } from 'next/server.js';\nimport type { CookieOptions, SetCookie } from '../client';\nimport type { InterceptorRule, RequestInterceptorContext, ResponseInterceptorContext } from './interceptors/types';\nimport type { InterceptorRegistry } from './interceptors';\nimport { PROXY_CLIENT_IP_HEADER } from '../../security/proxy-signature';\n\n// Re-export from shared\nexport { parseResponseBody } from '../shared';\n\n/**\n * Resolve the real client IP from a forwarded chain.\n *\n * `X-Forwarded-For` is `client, proxy1, proxy2, …` — each trusted hop appends the\n * address it received the connection from, so the rightmost `trustedHops` entries\n * are added by our own infra and can't be spoofed. The client as the outermost\n * trusted hop saw it is `parts[len - trustedHops]`. A client that prepends a fake\n * value just lengthens the chain to the left and is ignored.\n *\n * @param xff - raw X-Forwarded-For header value\n * @param trustedHops - number of trusted proxies in front (e.g. LB + nginx = 2)\n */\nexport function clientIpFromForwardedChain(\n xff: string | null | undefined,\n trustedHops: number,\n): string | undefined\n{\n if (!xff) return undefined;\n\n const parts = xff.split(',').map(s => s.trim()).filter(Boolean);\n if (parts.length === 0) return undefined;\n\n const idx = parts.length - Math.max(1, trustedHops);\n\n // Fewer entries than configured hops (misconfig / fewer real hops): best-effort\n // to the leftmost rather than returning nothing.\n return parts[idx] ?? parts[0];\n}\n\nfunction trustedProxyHops(): number\n{\n const raw = Number.parseInt(process.env.TRUSTED_PROXY_HOPS ?? '', 10);\n\n return Number.isFinite(raw) && raw > 0 ? raw : 1;\n}\n\n/**\n * Build request headers for proxying\n * Forwards important headers from source and adds default headers\n *\n * @param sourceHeaders - Source headers (can be Headers object or Record)\n * @param defaultHeaders - Default headers to add\n */\nexport function buildProxyHeaders(\n sourceHeaders: Headers | Record<string, string>,\n defaultHeaders: Record<string, string>,\n): Headers\n{\n const headers = new Headers();\n\n // Forward important headers from source\n const headersToForward = [\n 'content-type',\n 'authorization',\n 'cookie',\n 'user-agent',\n 'accept',\n 'accept-language',\n // Forwarded so the backend proxy-guard can enforce its origin allowlist on\n // the real browser Origin; without this allowedOrigins would be a no-op.\n 'origin',\n ];\n\n for (const header of headersToForward)\n {\n const value = sourceHeaders instanceof Headers\n ? sourceHeaders.get(header)\n : sourceHeaders[header];\n\n if (value)\n {\n headers.set(header, value);\n }\n }\n\n // Forward the real client IP so the backend can rate-limit per user. The\n // backend trusts this header only on proxy-verified requests, so a direct\n // caller can't spoof it. Resolved hop-aware from the inbound X-Forwarded-For.\n const xff = sourceHeaders instanceof Headers\n ? sourceHeaders.get('x-forwarded-for')\n : sourceHeaders['x-forwarded-for'];\n const clientIp = clientIpFromForwardedChain(xff, trustedProxyHops());\n if (clientIp)\n {\n headers.set(PROXY_CLIENT_IP_HEADER, clientIp);\n }\n\n // Add default headers\n for (const [key, value] of Object.entries(defaultHeaders))\n {\n headers.set(key, value);\n }\n\n return headers;\n}\n\n/**\n * Parse cookies from Cookie header string\n *\n * @param cookieHeader - Cookie header string (e.g., \"session=abc; theme=dark\")\n * @returns Map of cookie name-value pairs\n */\nexport function parseCookies(cookieHeader: string | null | undefined): Map<string, string>\n{\n const cookiesMap = new Map<string, string>();\n\n if (!cookieHeader)\n {\n return cookiesMap;\n }\n\n const cookiePairs = cookieHeader.split(';').map(c => c.trim());\n for (const pair of cookiePairs)\n {\n const [name, ...valueParts] = pair.split('=');\n if (name && valueParts.length > 0)\n {\n const value = valueParts.join('='); // Handle = in cookie value\n cookiesMap.set(name.trim(), value.trim());\n }\n }\n\n return cookiesMap;\n}\n\n/**\n * Parse cookies from NextRequest (Next.js specific helper)\n * Combines cookies from both NextRequest.cookies and Cookie header\n */\nexport function parseCookiesFromNextRequest(request: NextRequest): Map<string, string>\n{\n const cookiesMap = new Map<string, string>();\n\n // Add cookies from NextRequest (browser cookies)\n for (const cookie of request.cookies.getAll())\n {\n cookiesMap.set(cookie.name, cookie.value);\n }\n\n // Add cookies from Cookie header (server-side forwarded cookies)\n const cookieHeader = request.headers.get('cookie');\n if (cookieHeader)\n {\n const parsed = parseCookies(cookieHeader);\n for (const [name, value] of parsed.entries())\n {\n cookiesMap.set(name, value);\n }\n }\n\n return cookiesMap;\n}\n\n// Mapping of option names to Set-Cookie attribute formats\nconst optionMappings: Array<{\n key: keyof CookieOptions;\n format: (value: any) => string | null;\n}> = [\n { key: 'httpOnly', format: (v) => v ? 'HttpOnly' : null },\n { key: 'secure', format: (v) => v ? 'Secure' : null },\n { key: 'sameSite', format: (v) => v ? `SameSite=${v}` : null },\n { key: 'maxAge', format: (v) => v !== undefined ? `Max-Age=${v}` : null },\n { key: 'path', format: (v) => v ? `Path=${v}` : null },\n { key: 'domain', format: (v) => v ? `Domain=${v}` : null },\n];\n\n/**\n * Build Set-Cookie header string from cookie options\n */\nexport function buildSetCookieHeader(cookie: SetCookie): string\n{\n const parts = [`${cookie.name}=${cookie.value}`];\n const options = cookie.options || {};\n\n for (const { key, format } of optionMappings)\n {\n const value = options[key];\n if (value !== undefined && value !== false)\n {\n const formatted = format(value);\n if (formatted)\n {\n parts.push(formatted);\n }\n }\n }\n\n return parts.join('; ');\n}\n\n/**\n * Build error response JSON\n */\nexport function buildErrorResponse(\n errorType: string,\n message: string,\n debug: boolean,\n error?: Error,\n): any\n{\n return {\n error: errorType,\n message,\n ...(debug && error?.stack && { stack: error.stack }),\n };\n}\n\nconst headersToForward = [\n 'content-type',\n 'cache-control',\n 'set-cookie',\n 'etag',\n 'last-modified',\n];\n\n/**\n * Forward response headers back to client\n */\nexport function forwardResponseHeaders(\n sourceHeaders: Headers,\n targetHeaders: Headers,\n): void\n{\n for (const header of headersToForward)\n {\n const value = sourceHeaders.get(header);\n if (value)\n {\n targetHeaders.set(header, value);\n }\n }\n}\n\n/**\n * Collect all interceptors (auto-discovered + config)\n */\nexport function collectInterceptors(\n autoDiscoverInterceptors: boolean,\n disableAutoInterceptors: string[] | undefined,\n configInterceptors: InterceptorRule[] | undefined,\n registry: InterceptorRegistry,\n): InterceptorRule[]\n{\n const allInterceptors: InterceptorRule[] = [];\n\n // Auto-discover from registry\n if (autoDiscoverInterceptors)\n {\n const registeredInterceptors = registry.getAll(disableAutoInterceptors || []);\n allInterceptors.push(...registeredInterceptors);\n }\n\n // Add config interceptors\n if (configInterceptors)\n {\n allInterceptors.push(...configInterceptors);\n }\n\n return allInterceptors;\n}\n\n/**\n * Build RequestInterceptorContext\n */\nexport function buildRequestContext(\n path: string,\n method: string,\n headers: Headers,\n body: any,\n searchParams: URLSearchParams,\n cookiesMap: Map<string, string>,\n request: NextRequest,\n): RequestInterceptorContext\n{\n return {\n path: `/${path}`,\n method,\n headers: Object.fromEntries(headers.entries()),\n body,\n query: Object.fromEntries(searchParams.entries()),\n cookies: cookiesMap,\n request,\n metadata: {},\n };\n}\n\n/**\n * Build ResponseInterceptorContext\n */\nexport function buildResponseContext(\n path: string,\n method: string,\n requestHeaders: Headers,\n requestBody: any,\n response: Response,\n responseBody: any,\n requestMetadata: Record<string, any>,\n cookies: Map<string, string>,\n): ResponseInterceptorContext\n{\n return {\n path: `/${path}`,\n method,\n request: {\n headers: Object.fromEntries(requestHeaders.entries()),\n body: requestBody,\n },\n response: {\n ok: response.ok,\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n body: responseBody,\n },\n cookies,\n setCookies: [],\n metadata: requestMetadata,\n };\n}\n","/**\n * RPC-Style Proxy for define-route System\n *\n * Next.js API Route handler that resolves routeName to method/path\n * and forwards requests to SPFN backend.\n *\n * @example\n * ```typescript\n * // app/api/rpc/[routeName]/route.ts\n * import { createRpcProxy } from '@spfn/core/nextjs/server';\n * import { eventRouteMap } from '@spfn/core/event';\n * import { routeMap } from '@/generated/route-map';\n *\n * export const { GET, POST } = createRpcProxy({\n * routeMap: { ...routeMap, ...eventRouteMap },\n * });\n * ```\n *\n * The generated `routeMap` already holds the routes of every package router the\n * app mounts with `.packages()`, so no package map is merged by hand.\n * `eventRouteMap` is the exception: a hand-written constant, not a mounted\n * router.\n */\nimport { NextRequest, NextResponse } from 'next/server.js';\n\nimport { env } from '@spfn/core/config';\nimport { logger } from '@spfn/core/logger';\nimport type { HttpMethod } from '@spfn/core/route';\n\nimport { signProxyRequest, parseProxyKeySet } from '../../security/proxy-signature';\nimport { buildUrlWithParams, buildQueryString } from '../shared';\nimport { interceptorRegistry } from './interceptors';\nimport { executeRequestInterceptors, executeResponseInterceptors, filterMatchingInterceptors } from './interceptors';\nimport {\n buildProxyHeaders,\n parseCookiesFromNextRequest,\n buildSetCookieHeader,\n buildErrorResponse,\n forwardResponseHeaders,\n parseResponseBody,\n collectInterceptors,\n buildRequestContext,\n buildResponseContext,\n} from './helpers';\nimport type { TypedProxyConfig } from './types';\n\nconst rpcLogger = logger.child('@spfn/core:rpc-proxy');\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Route info from generated route map\n */\nexport interface RouteMapEntry\n{\n method: HttpMethod;\n path: string;\n}\n\n/**\n * Generated route map type\n */\nexport type RouteMap = Record<string, RouteMapEntry>;\n\n/**\n * RPC proxy configuration\n */\nexport interface RpcProxyConfig extends Omit<TypedProxyConfig, 'onRequest' | 'onResponse'>\n{\n /**\n * Route map containing routeName → {method, path} mappings\n *\n * The generated map carries the app's own routes and those of every package\n * router it mounts with `.packages()`. Merge `eventRouteMap` beside it when\n * the app uses SSE — that one is a constant rather than a mounted router.\n *\n * @example\n * ```typescript\n * import { eventRouteMap } from '@spfn/core/event';\n * import { routeMap } from '@/generated/route-map';\n *\n * export const { GET, POST } = createRpcProxy({\n * routeMap: { ...routeMap, ...eventRouteMap },\n * });\n * ```\n */\n routeMap: RouteMap;\n\n /**\n * Shared secret for signing proxy→backend requests (HMAC-SHA256).\n *\n * When set, every forwarded request carries an HMAC signature the backend's\n * proxy-guard middleware verifies, letting it reject direct-to-backend calls\n * that bypass this proxy. Set the SAME value here and on the backend.\n *\n * @default process.env.SPFN_PROXY_SECRET (undefined → signing disabled)\n */\n proxySecret?: string;\n}\n\n// ============================================================================\n// RPC Proxy Handler\n// ============================================================================\n\n/**\n * Create RPC proxy handler for Next.js API Route\n *\n * Handles requests in the format:\n * - GET /api/rpc/{routeName}?input={...}\n * - POST /api/rpc/{routeName} with body\n *\n * Resolves routeName to actual HTTP method and path from routeMap,\n * then forwards to SPFN backend.\n */\nexport function createRpcProxy(config: RpcProxyConfig)\n{\n const {\n apiUrl = env.SPFN_API_URL || 'http://localhost:8790',\n debug = env.NODE_ENV === 'development',\n timeout = env.RPC_PROXY_TIMEOUT,\n headers: defaultHeaders = {},\n interceptors,\n autoDiscoverInterceptors = true,\n disableAutoInterceptors,\n proxySecret = env.SPFN_PROXY_SECRET,\n routeMap,\n } = config;\n\n // Parse the active signing key once — it's fixed for the proxy's lifetime.\n // Use the SAME parser the backend uses (comma key set) and take the active key,\n // so a `v2:new,v1:old` secret is interpreted identically on both sides.\n const proxyKey = proxySecret ? (parseProxyKeySet([proxySecret])[0] ?? null) : null;\n\n // proxy-guard signs route-relative paths; if SPFN_API_URL carries a base path the\n // backend keeps (no ingress strip), the signed path won't match c.req.url and\n // strict mode 403s everything. Warn loudly so it's diagnosable.\n if (proxyKey)\n {\n try\n {\n const basePath = new URL(apiUrl).pathname;\n if (basePath !== '/' && basePath !== '')\n {\n rpcLogger.warn(\n `SPFN_API_URL has a base path (\"${basePath}\"). proxy-guard signs route-relative paths, `\n + 'so the backend must receive paths WITHOUT this prefix (e.g. ingress strip) or strict '\n + 'mode will reject all signed requests with 403.',\n );\n }\n }\n catch\n {\n // invalid apiUrl is surfaced elsewhere\n }\n }\n\n /**\n * Resolve route info from routeMap\n */\n function resolveRoute(routeName: string): { method: string; path: string } | null\n {\n const entry = routeMap[routeName];\n if (entry)\n {\n return { method: entry.method, path: entry.path };\n }\n\n return null;\n }\n\n /**\n * Handle RPC request\n */\n async function handleRpc(\n request: NextRequest,\n context: { params: Promise<{ routeName?: string }> },\n ): Promise<NextResponse>\n {\n const startTime = Date.now();\n const params = await context.params;\n\n try\n {\n const routeName = params.routeName;\n\n if (!routeName)\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Missing routeName parameter', debug),\n { status: 400 },\n );\n }\n\n // Parse input from query string (GET) or body (POST)\n let input: {\n params?: Record<string, any>;\n query?: Record<string, any>;\n body?: Record<string, any>;\n formData?: Record<string, any>;\n headers?: Record<string, any>;\n cookies?: Record<string, any>;\n } = {};\n let rawFormData: FormData | null = null;\n\n if (request.method === 'GET')\n {\n const inputParam = request.nextUrl.searchParams.get('input');\n if (inputParam)\n {\n try\n {\n input = JSON.parse(decodeURIComponent(inputParam));\n }\n catch\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Invalid input parameter', debug),\n { status: 400 },\n );\n }\n }\n }\n else\n {\n // POST - check Content-Type for formData vs JSON\n const contentType = request.headers.get('content-type') || '';\n\n if (contentType.includes('multipart/form-data'))\n {\n // Parse multipart/form-data\n try\n {\n rawFormData = await request.formData();\n\n // Extract __metadata if present (contains params, query, etc.)\n const metadataStr = rawFormData.get('__metadata');\n if (metadataStr && typeof metadataStr === 'string')\n {\n const metadata = JSON.parse(metadataStr);\n input.params = metadata.params;\n input.query = metadata.query;\n input.headers = metadata.headers;\n input.cookies = metadata.cookies;\n }\n\n // Collect formData fields (excluding __metadata)\n input.formData = {};\n rawFormData.forEach((value, key) =>\n {\n if (key === '__metadata') return;\n\n const existing = input.formData![key];\n if (existing !== undefined)\n {\n // Multiple values with same key\n if (Array.isArray(existing))\n {\n existing.push(value);\n }\n else\n {\n input.formData![key] = [existing, value];\n }\n }\n else\n {\n input.formData![key] = value;\n }\n });\n }\n catch (error)\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Invalid form data', debug),\n { status: 400 },\n );\n }\n }\n else\n {\n // Parse JSON body\n try\n {\n input = await request.json();\n }\n catch\n {\n return NextResponse.json(\n buildErrorResponse('Bad Request', 'Invalid JSON body', debug),\n { status: 400 },\n );\n }\n }\n }\n\n // Resolve route info from routeMap\n const routeInfo = resolveRoute(routeName);\n\n if (!routeInfo)\n {\n rpcLogger.warn(`Route not found: ${routeName}`);\n\n return NextResponse.json(\n buildErrorResponse('Not Found', `Route \"${routeName}\" not found`, debug),\n { status: 404 },\n );\n }\n\n const { method: targetMethod, path: targetPath } = routeInfo;\n\n // Build target URL with params and query\n const inputParams = input.params || {};\n const inputQuery = input.query || {};\n const inputBody = input.body;\n const inputFormData = input.formData;\n const hasFormData = rawFormData !== null && inputFormData && Object.keys(inputFormData).length > 0;\n\n const resolvedPath = buildUrlWithParams(targetPath, inputParams);\n const queryString = buildQueryString(inputQuery);\n const targetUrl = `${apiUrl}${resolvedPath}${queryString}`;\n\n if (debug)\n {\n rpcLogger.debug('→ RPC request', {\n routeName,\n targetMethod,\n targetPath: resolvedPath,\n targetUrl,\n hasBody: !!inputBody,\n hasFormData,\n });\n }\n\n // Build headers\n const headers = buildProxyHeaders(request.headers, defaultHeaders);\n\n // Remove Content-Type for formData (let fetch set it with boundary)\n if (hasFormData)\n {\n headers.delete('content-type');\n }\n\n // Build fetch options\n const fetchOptions: RequestInit = {\n method: targetMethod,\n headers,\n };\n\n // Add body for POST/PUT/PATCH\n if (['POST', 'PUT', 'PATCH'].includes(targetMethod))\n {\n if (hasFormData && rawFormData)\n {\n // Forward formData to backend (rebuild without __metadata)\n const forwardFormData = new FormData();\n rawFormData.forEach((value, key) =>\n {\n if (key !== '__metadata')\n {\n forwardFormData.append(key, value);\n }\n });\n fetchOptions.body = forwardFormData;\n }\n else if (inputBody)\n {\n fetchOptions.body = JSON.stringify(inputBody);\n }\n }\n\n // ============================================================\n // Advanced Interceptors - BEFORE FETCH\n // ============================================================\n\n // Collect and filter interceptors\n const allInterceptors = collectInterceptors(autoDiscoverInterceptors, disableAutoInterceptors, interceptors, interceptorRegistry);\n const matchingInterceptors = filterMatchingInterceptors(allInterceptors, resolvedPath, targetMethod);\n\n if (debug && matchingInterceptors.length > 0)\n {\n rpcLogger.debug(`Found ${matchingInterceptors.length} matching interceptors for ${targetMethod} ${resolvedPath}`);\n }\n\n // Create RequestInterceptorContext\n const cookiesMap = parseCookiesFromNextRequest(request);\n const requestCtx = buildRequestContext(\n resolvedPath.slice(1), // Remove leading slash\n targetMethod,\n headers,\n inputBody,\n new URLSearchParams(queryString.slice(1)), // Remove leading ?\n cookiesMap,\n request,\n );\n\n // Execute request interceptors\n const requestInterceptorsToRun = matchingInterceptors.map(r => r.request).filter((i): i is NonNullable<typeof i> => !!i);\n if (requestInterceptorsToRun.length > 0)\n {\n await executeRequestInterceptors(requestCtx, requestInterceptorsToRun);\n\n // Apply modified headers\n for (const [key, value] of Object.entries(requestCtx.headers))\n {\n headers.set(key, value);\n }\n\n // Apply modified body\n if (requestCtx.body)\n {\n fetchOptions.body = JSON.stringify(requestCtx.body);\n }\n }\n\n // An interceptor refused the request (e.g. the CSRF check in @spfn/auth).\n // Return its response without touching the backend; no response\n // interceptor runs, so the only cookies a refusal can carry are the\n // ones the refusing interceptor attached to the abort. The CSRF check\n // attaches a fresh token there, so the refusal is what repairs the\n // browser instead of merely reporting the damage.\n if (requestCtx.abort)\n {\n rpcLogger.warn('Request refused by an interceptor', {\n routeName,\n status: requestCtx.abort.status,\n });\n\n const abortResponse = NextResponse.json(\n requestCtx.abort.body,\n { status: requestCtx.abort.status },\n );\n\n for (const cookie of requestCtx.abort.setCookies ?? [])\n {\n abortResponse.headers.append('Set-Cookie', buildSetCookieHeader(cookie));\n }\n\n return abortResponse;\n }\n\n // ============================================================\n // Proxy → Backend signature (proxy-guard)\n // ============================================================\n // Sign the FINAL request (after interceptors settled body/headers) so\n // the backend can prove it came through this trusted proxy. JSON body\n // is hashed into the signature; large multipart uploads are excluded.\n if (proxyKey)\n {\n const signedBody = typeof fetchOptions.body === 'string' ? fetchOptions.body : undefined;\n // Sign the route-relative path (no SPFN_API_URL base prefix) so it\n // matches the backend's `new URL(c.req.url).pathname` whether the\n // prefix is absent or stripped by an ingress. resolvedPath is already\n // the percent-encoded wire form; queryString is the raw search.\n const signatureHeaders = signProxyRequest({\n key: proxyKey,\n method: targetMethod,\n path: resolvedPath,\n query: queryString,\n body: signedBody,\n });\n\n for (const [headerName, value] of Object.entries(signatureHeaders))\n {\n headers.set(headerName, value);\n }\n }\n\n // Execute fetch with timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try\n {\n const response = await fetch(targetUrl, {\n ...fetchOptions,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Parse response\n let body = await parseResponseBody(response);\n\n // ============================================================\n // Advanced Interceptors - AFTER FETCH\n // ============================================================\n\n // Create ResponseInterceptorContext\n const responseCtx = buildResponseContext(\n resolvedPath.slice(1),\n targetMethod,\n headers,\n inputBody,\n response,\n body,\n requestCtx.metadata,\n requestCtx.cookies,\n );\n\n // Execute response interceptors\n const responseInterceptorsToRun = matchingInterceptors.map(r => r.response).filter((i): i is NonNullable<typeof i> => !!i);\n if (responseInterceptorsToRun.length > 0)\n {\n await executeResponseInterceptors(responseCtx, responseInterceptorsToRun);\n body = responseCtx.response.body;\n }\n\n const duration = Date.now() - startTime;\n\n if (debug)\n {\n rpcLogger.debug('← RPC response', {\n routeName,\n status: responseCtx.response.status,\n duration: `${duration}ms`,\n });\n }\n\n // Build Next.js response\n // 204 No Content should use NextResponse directly, not NextResponse.json()\n const nextResponse = responseCtx.response.status === 204\n ? new NextResponse(null, {\n status: 204,\n statusText: responseCtx.response.statusText,\n })\n : NextResponse.json(body, {\n status: responseCtx.response.status,\n statusText: responseCtx.response.statusText,\n });\n\n // Forward response headers\n forwardResponseHeaders(response.headers, nextResponse.headers);\n\n // Apply setCookies from interceptors\n for (const cookie of responseCtx.setCookies)\n {\n const setCookieHeader = buildSetCookieHeader(cookie);\n nextResponse.headers.append('Set-Cookie', setCookieHeader);\n\n if (debug)\n {\n rpcLogger.debug('Set-Cookie header added', {\n name: cookie.name,\n });\n }\n }\n\n return nextResponse;\n }\n catch (error)\n {\n clearTimeout(timeoutId);\n\n // Handle timeout\n if (error instanceof Error && error.name === 'AbortError')\n {\n rpcLogger.error('Request timeout', {\n routeName,\n targetUrl,\n timeout,\n });\n\n return NextResponse.json(\n buildErrorResponse('Gateway Timeout', `Request timed out after ${timeout}ms`, debug, error),\n { status: 504 },\n );\n }\n\n // Handle other fetch errors\n const fetchErr = error as Error;\n rpcLogger.error('Fetch error', {\n routeName,\n targetUrl,\n error: fetchErr.message,\n });\n\n return NextResponse.json(\n buildErrorResponse('Bad Gateway', fetchErr.message || 'Failed to connect to backend', debug, fetchErr),\n { status: 502 },\n );\n }\n }\n catch (error)\n {\n const duration = Date.now() - startTime;\n const err = error as Error;\n\n rpcLogger.error('RPC proxy error', {\n error: err.message,\n stack: err.stack,\n duration: `${duration}ms`,\n });\n\n return NextResponse.json(\n buildErrorResponse('Internal Server Error', err.message || 'Unknown error', debug, err),\n { status: 500 },\n );\n }\n }\n\n // Return route handlers\n return {\n GET: (req: NextRequest, context: { params: Promise<{ routeName?: string }> }) =>\n handleRpc(req, context),\n POST: (req: NextRequest, context: { params: Promise<{ routeName?: string }> }) =>\n handleRpc(req, context),\n };\n}\n"]}
|
|
@@ -2,6 +2,25 @@ import { TSchema, Static } from '@sinclair/typebox';
|
|
|
2
2
|
import { ErrorRegistry, ErrorRegistryInput } from '@spfn/core/errors';
|
|
3
3
|
import { RouteDef, RouteInput } from '@spfn/core/route';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Typed client error
|
|
7
|
+
*
|
|
8
|
+
* `errorType` tells apart why a call failed:
|
|
9
|
+
* - `'http'`: the server answered with a non-2xx status
|
|
10
|
+
* - `'network'`: the fetch or the body read failed (status 0)
|
|
11
|
+
* - `'timeout'`: the call's timeout elapsed before response headers arrived (status 408)
|
|
12
|
+
* - `'aborted'`: the caller's own signal aborted the call (status 0); `cause` is the signal's reason
|
|
13
|
+
*/
|
|
14
|
+
declare class ApiError extends Error {
|
|
15
|
+
readonly status: number;
|
|
16
|
+
readonly url: string;
|
|
17
|
+
readonly response?: unknown | undefined;
|
|
18
|
+
readonly errorType?: "http" | "network" | "timeout" | "aborted" | undefined;
|
|
19
|
+
constructor(message: string, status: number, url: string, response?: unknown | undefined, errorType?: "http" | "network" | "timeout" | "aborted" | undefined, options?: {
|
|
20
|
+
cause?: unknown;
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
5
24
|
/**
|
|
6
25
|
* Convert File types in schema to actual File for client usage
|
|
7
26
|
*
|
|
@@ -266,6 +285,32 @@ type ResponseInterceptor = (response: Response, body: any) => Promise<{
|
|
|
266
285
|
response: Response;
|
|
267
286
|
body: any;
|
|
268
287
|
};
|
|
288
|
+
/**
|
|
289
|
+
* How one call ended, as `ApiConfig.onOutcome` is told it
|
|
290
|
+
*
|
|
291
|
+
* - `ok: true`: the server answered 2xx; `response` and `body` are what the response
|
|
292
|
+
* interceptors left, and `body` is what the call returns
|
|
293
|
+
* - `'http'`: the server answered with an error status; `error` is the object the call
|
|
294
|
+
* throws — the registered class a `__type` body names (`NotFoundError`,
|
|
295
|
+
* `UnauthorizedError`, …) or else an `ApiError`, hence `Error`
|
|
296
|
+
* - `'network'` / `'timeout'` / `'aborted'`: no answer; `error` is the `ApiError` the call
|
|
297
|
+
* throws, `status` its status (0, 408, 0)
|
|
298
|
+
*/
|
|
299
|
+
type ApiOutcome = {
|
|
300
|
+
ok: true;
|
|
301
|
+
response: Response;
|
|
302
|
+
body: unknown;
|
|
303
|
+
} | {
|
|
304
|
+
ok: false;
|
|
305
|
+
errorType: 'http';
|
|
306
|
+
status: number;
|
|
307
|
+
error: Error;
|
|
308
|
+
} | {
|
|
309
|
+
ok: false;
|
|
310
|
+
errorType: 'network' | 'timeout' | 'aborted';
|
|
311
|
+
status: number;
|
|
312
|
+
error: ApiError;
|
|
313
|
+
};
|
|
269
314
|
/**
|
|
270
315
|
* Client configuration
|
|
271
316
|
*/
|
|
@@ -299,6 +344,27 @@ interface ApiConfig {
|
|
|
299
344
|
* Global response interceptor
|
|
300
345
|
*/
|
|
301
346
|
onResponse?: ResponseInterceptor;
|
|
347
|
+
/**
|
|
348
|
+
* Told once how each call that reached fetch ended — after the response interceptors
|
|
349
|
+
* ran, before the call returns or throws
|
|
350
|
+
*
|
|
351
|
+
* Observed: a transport failure (`'network'`, `'timeout'`, `'aborted'`) and every
|
|
352
|
+
* answer, error statuses included; `error` is the very object the call then throws.
|
|
353
|
+
* Not observed: a throw from an `onRequest` or `onResponse` interceptor, or from
|
|
354
|
+
* building the request — those are the app's own and reach the caller unchanged.
|
|
355
|
+
*
|
|
356
|
+
* Called synchronously and never awaited. A throw from it, or a rejection of the
|
|
357
|
+
* promise it returns, is logged and never changes what the call returns or throws.
|
|
358
|
+
* Config only: there is no per-call observer.
|
|
359
|
+
*
|
|
360
|
+
* @example
|
|
361
|
+
* ```typescript
|
|
362
|
+
* const api = createApi<AppRouter>({
|
|
363
|
+
* onOutcome: (outcome) => setServerStatus(outcome.ok ? 'up' : outcome.errorType),
|
|
364
|
+
* });
|
|
365
|
+
* ```
|
|
366
|
+
*/
|
|
367
|
+
onOutcome?: (outcome: ApiOutcome) => void;
|
|
302
368
|
/**
|
|
303
369
|
* Custom error registry for deserialization
|
|
304
370
|
*
|
|
@@ -372,4 +438,4 @@ interface CallOptions {
|
|
|
372
438
|
};
|
|
373
439
|
}
|
|
374
440
|
|
|
375
|
-
export type
|
|
441
|
+
export { type ApiConfig as A, type CallOptions as C, type ExtractRoutes as E, type InferRouteInput as I, type RequestInterceptor as R, type SetCookie as S, type ResponseInterceptor as a, type InferRouteOutput as b, ApiError as c, type ApiOutcome as d, type CookieOptions as e, type RouterInput as f, type RouterOutput as g, type StructuredInput as h };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spfn/core",
|
|
3
|
-
"version": "0.3.0-beta.
|
|
3
|
+
"version": "0.3.0-beta.30",
|
|
4
4
|
"description": "Full-stack TypeScript backend for Next.js: file-based typed routes, Drizzle entities and repositories, PostgreSQL transactions and a generated end-to-end client, in one fixed vertical slice per feature",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
package/src/nextjs/README.md
CHANGED
|
@@ -40,7 +40,7 @@ import { createRpcProxy, registerInterceptors } from '@spfn/core/nextjs/server';
|
|
|
40
40
|
From `@spfn/core/nextjs` (client-safe):
|
|
41
41
|
|
|
42
42
|
- Values: `createApi`, `ApiError`
|
|
43
|
-
- Types: `Client`, `RouteClient`, `ApiConfig`, `CallOptions`, `InferRouteInput`,
|
|
43
|
+
- Types: `Client`, `RouteClient`, `ApiConfig`, `ApiOutcome`, `CallOptions`, `InferRouteInput`,
|
|
44
44
|
`InferRouteOutput`, `RouterInput`, `RouterOutput`, `StructuredInput`,
|
|
45
45
|
`RequestInterceptor`, `ResponseInterceptor`, `CookieOptions`, `SetCookie`
|
|
46
46
|
|
|
@@ -233,6 +233,7 @@ interface ApiConfig {
|
|
|
233
233
|
fetch?: typeof fetch; // custom fetch impl
|
|
234
234
|
onRequest?: RequestInterceptor; // global, (url, init) => init
|
|
235
235
|
onResponse?: ResponseInterceptor; // global, (response, body) => { response, body }
|
|
236
|
+
onOutcome?: (outcome: ApiOutcome) => void; // told once how each call that reached fetch ended
|
|
236
237
|
errorRegistry?: ErrorRegistry | ErrorRegistryInput[]; // custom error deserialization
|
|
237
238
|
debug?: boolean; // default false
|
|
238
239
|
}
|
|
@@ -659,12 +660,79 @@ export async function createUser(formData: FormData) {
|
|
|
659
660
|
Only a failed fetch (`0` / `'network'`), a timed-out one (`408` / `'timeout'`) and one the
|
|
660
661
|
caller aborted (`0` / `'aborted'`) are.
|
|
661
662
|
|
|
663
|
+
### How do I learn how every call ended?
|
|
664
|
+
|
|
665
|
+
Give `createApi` an `onOutcome`. It is told once how each call that reached `fetch` ended,
|
|
666
|
+
before that call returns or throws:
|
|
667
|
+
|
|
668
|
+
```typescript
|
|
669
|
+
type ApiOutcome =
|
|
670
|
+
| { ok: true; response: Response; body: unknown }
|
|
671
|
+
| { ok: false; errorType: 'http'; status: number; error: Error }
|
|
672
|
+
| { ok: false; errorType: 'network' | 'timeout' | 'aborted'; status: number; error: ApiError };
|
|
673
|
+
```
|
|
674
|
+
|
|
675
|
+
- **Observed**: every answer — `ok: true` with the `response` and `body` your `onResponse`
|
|
676
|
+
interceptors left, or `'http'` with the final response's status — and every call that got
|
|
677
|
+
no answer (`'network'` 0, `'timeout'` 408, `'aborted'` 0).
|
|
678
|
+
- **`error` is the object the call throws**: for `'http'`, the registered class a `__type`
|
|
679
|
+
body names (`NotFoundError`, `UnauthorizedError`, …) or else an `ApiError`, hence `Error`;
|
|
680
|
+
for the transport kinds, the `ApiError`.
|
|
681
|
+
- **Not observed**: a throw from an `onRequest` or `onResponse` interceptor (`redirect()`,
|
|
682
|
+
`notFound()`, your own errors) or from building the request. Those are yours and reach the
|
|
683
|
+
caller unchanged.
|
|
684
|
+
- **The observer cannot change the call.** It is called synchronously and never awaited; a
|
|
685
|
+
throw or a rejected promise from it is logged (`onOutcome`, the error's name and message)
|
|
686
|
+
and the call still returns or throws what it would have.
|
|
687
|
+
- **Config only**: there is no per-call `onOutcome`.
|
|
688
|
+
|
|
689
|
+
```typescript
|
|
690
|
+
import { createApi } from '@spfn/core/nextjs';
|
|
691
|
+
import type { ApiOutcome } from '@spfn/core/nextjs';
|
|
692
|
+
import { UnauthorizedError } from '@spfn/core/errors';
|
|
693
|
+
|
|
694
|
+
type ServerStatus = 'up' | 'unreachable' | 'failing' | 'signed-out';
|
|
695
|
+
|
|
696
|
+
let serverStatus: ServerStatus = 'up';
|
|
697
|
+
|
|
698
|
+
function statusOf(outcome: ApiOutcome): ServerStatus
|
|
699
|
+
{
|
|
700
|
+
if (outcome.ok)
|
|
701
|
+
{
|
|
702
|
+
return 'up';
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
if (outcome.errorType !== 'http')
|
|
706
|
+
{
|
|
707
|
+
return outcome.errorType === 'aborted' ? serverStatus : 'unreachable';
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
if (outcome.error instanceof UnauthorizedError)
|
|
711
|
+
{
|
|
712
|
+
return 'signed-out';
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
return outcome.status >= 500 ? 'failing' : 'up';
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
export const api = createApi<AppRouter>({
|
|
719
|
+
onOutcome: (outcome) =>
|
|
720
|
+
{
|
|
721
|
+
serverStatus = statusOf(outcome);
|
|
722
|
+
},
|
|
723
|
+
});
|
|
724
|
+
```
|
|
725
|
+
|
|
662
726
|
---
|
|
663
727
|
|
|
664
728
|
## Types reference
|
|
665
729
|
|
|
666
730
|
```typescript
|
|
667
731
|
// client (@spfn/core/nextjs)
|
|
732
|
+
type ApiOutcome =
|
|
733
|
+
| { ok: true; response: Response; body: unknown }
|
|
734
|
+
| { ok: false; errorType: 'http'; status: number; error: Error }
|
|
735
|
+
| { ok: false; errorType: 'network' | 'timeout' | 'aborted'; status: number; error: ApiError };
|
|
668
736
|
type RequestInterceptor = (url: string, init: RequestInit) => Promise<RequestInit> | RequestInit;
|
|
669
737
|
type ResponseInterceptor = (response: Response, body: any)
|
|
670
738
|
=> Promise<{ response: Response; body: any }> | { response: Response; body: any };
|