@thednp/rpc 0.3.5 → 0.3.7

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.
Files changed (45) hide show
  1. package/AGENTS.md +39 -12
  2. package/CHANGELOG.md +165 -0
  3. package/README.md +2 -2
  4. package/dist/config/config.d.mts +0 -7
  5. package/dist/config/config.d.mts.map +1 -1
  6. package/dist/config/config.mjs +5 -1
  7. package/dist/config/config.mjs.map +1 -1
  8. package/dist/express/express.d.mts +62 -32
  9. package/dist/express/express.d.mts.map +1 -1
  10. package/dist/express/express.mjs +71 -23
  11. package/dist/express/express.mjs.map +1 -1
  12. package/dist/fastify/fastify.d.mts +81 -47
  13. package/dist/fastify/fastify.d.mts.map +1 -1
  14. package/dist/fastify/fastify.mjs +73 -23
  15. package/dist/fastify/fastify.mjs.map +1 -1
  16. package/dist/fastify/plugin/fastify/plugin.d.mts +30 -55
  17. package/dist/fastify/plugin/fastify/plugin.d.mts.map +1 -1
  18. package/dist/fastify/plugin/fastify/plugin.mjs +72 -22
  19. package/dist/fastify/plugin/fastify/plugin.mjs.map +1 -1
  20. package/dist/h3/h3.d.mts +73 -4
  21. package/dist/h3/h3.d.mts.map +1 -1
  22. package/dist/h3/h3.mjs +69 -22
  23. package/dist/h3/h3.mjs.map +1 -1
  24. package/dist/helpers/helpers.d.mts.map +1 -1
  25. package/dist/helpers/helpers.mjs +2 -0
  26. package/dist/helpers/helpers.mjs.map +1 -1
  27. package/dist/hono/hono.d.mts +71 -6
  28. package/dist/hono/hono.d.mts.map +1 -1
  29. package/dist/hono/hono.mjs +94 -24
  30. package/dist/hono/hono.mjs.map +1 -1
  31. package/dist/index.d.mts +43 -25
  32. package/dist/index.d.mts.map +1 -1
  33. package/dist/index.mjs +62 -28
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/koa/koa.d.mts +73 -11
  36. package/dist/koa/koa.d.mts.map +1 -1
  37. package/dist/koa/koa.mjs +75 -23
  38. package/dist/koa/koa.mjs.map +1 -1
  39. package/dist/server/server.d.mts +159 -18
  40. package/dist/server/server.d.mts.map +1 -1
  41. package/dist/server/server.mjs +186 -15
  42. package/dist/server/server.mjs.map +1 -1
  43. package/llms.txt +5 -3
  44. package/package.json +5 -3
  45. package/CLAUDE.md +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"koa.mjs","names":[],"sources":["../../src/options.ts","../../src/functionsMap.ts","../../src/constants.ts","../../src/koa/helpers.ts","../../src/koa/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\nexport const defaultServerFnOptions: ServerFunctionOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n};\n\nexport const defaultPrefix = \"__rpc\";\n\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: defaultPrefix,\n adapter: \"express\",\n serverFiles: \"exact\",\n scanRoot: undefined,\n};\n\nexport const defaultMiddlewareOptions: MiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n};\n","import type { ServerFnEntry } from \"./types.d.ts\";\nimport { defaultPrefix } from \"./options.ts\";\n\n/**\n * Global symbol under which the shared `serverFunctionsByPrefix` map is stored\n * on `globalThis`. Keeping it on a `Symbol.for` key makes it instance-stable\n * across the bundled entry copies (`index.mjs`, `server.mjs`, `express.mjs`,\n * ...) and dev-server hot reloads, exactly like the request-context storage in\n * `context.ts`. Without this, `scanForServerFiles` (bundled into the plugin)\n * would populate a map copy the adapter middleware could not read.\n */\nconst functionsMapSymbol = Symbol.for(\"thednp.rpc.functionsMap\");\n\n/**\n * Map of rpcPrefix -> Map of function names -> ServerFnEntry\n * Enables multiple RPC instances with different prefixes to coexist\n * without name collisions.\n */\nexport const serverFunctionsByPrefix: Map<\n string,\n Map<string, ServerFnEntry>\n> = ((globalThis as Record<symbol, Map<string, Map<string, ServerFnEntry>>>)[\n functionsMapSymbol\n] ??= new Map());\n\n/**\n * Gets or creates the function map for a specific prefix.\n * @param prefix - The RPC prefix (e.g., \"__rpc\", \"v1:rpc\", \"admin:rpc\")\n * @returns Map of function names to ServerFnEntry for that prefix\n */\nexport const getFunctionsForPrefix = (\n prefix: string,\n): Map<string, ServerFnEntry> => {\n if (!serverFunctionsByPrefix.has(prefix)) {\n serverFunctionsByPrefix.set(prefix, new Map());\n }\n return serverFunctionsByPrefix.get(prefix)!;\n};\n\n/**\n * Backward compatibility: default map for the default prefix.\n * Legacy code can still use serverFunctionsMap.set(name, entry).\n */\nexport const serverFunctionsMap: Map<string, ServerFnEntry> = {\n get: (key: string) => getFunctionsForPrefix(defaultPrefix).get(key),\n set: (key: string, value: ServerFnEntry) =>\n getFunctionsForPrefix(defaultPrefix).set(key, value),\n has: (key: string) => getFunctionsForPrefix(defaultPrefix).has(key),\n delete: (key: string) => getFunctionsForPrefix(defaultPrefix).delete(key),\n clear: () => getFunctionsForPrefix(defaultPrefix).clear(),\n get size() {\n return getFunctionsForPrefix(defaultPrefix).size;\n },\n entries: () => getFunctionsForPrefix(defaultPrefix).entries(),\n keys: () => getFunctionsForPrefix(defaultPrefix).keys(),\n values: () => getFunctionsForPrefix(defaultPrefix).values(),\n forEach: (\n callback: (\n value: ServerFnEntry,\n key: string,\n map: Map<string, ServerFnEntry>,\n ) => void,\n ) => getFunctionsForPrefix(defaultPrefix).forEach(callback),\n [Symbol.iterator]: () =>\n getFunctionsForPrefix(defaultPrefix)[Symbol.iterator](),\n} as unknown as Map<string, ServerFnEntry>;\n","export const OPERATION_ABORTED = \"Operation aborted\";\n\nexport const REQUEST_CANCELLED = \"Request was cancelled\";\n\nexport const FETCH_ERROR_PREFIX = \"Fetch error: \";\n\nexport const NO_SERVER_FUNCTION_FOUND = \"No server function found.\";\n\nexport const ERROR_LOADING_FILE = \"Error loading file:\";\n\nexport const FUNCTION_NOT_FOUND = \"Function not found\";\n\nexport const METHOD_NOT_ALLOWED = \"Method Not Allowed\";\n\nexport const REQUEST_FORBIDDEN = \"Forbidden\";\n\nexport const UNSUPPORTED_MEDIA_TYPE = \"Unsupported Media Type\";\n\nexport const BAD_REQUEST = \"Bad Request\";\n\nexport const INTERNAL_SERVER_ERROR = \"Internal Server Error\";\n\nexport const CLIENT_DISCONNECTED = \"client disconnected\";\n\n/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */\nexport const MIDDLEWARE_NAME_USED = (name: string) =>\n `The middleware name \"${name}\" is already used.`;\n\n/** Error message when a value fails the safe-identifier validation. @param label - What kind of value was being validated. @param name - The rejected value */\nexport const INVALID_IDENTIFIER = (label: string, name: string) =>\n `Invalid ${label}: \"${name}\" must match /^[A-Za-z_$][A-Za-z0-9_$]*$/`;\n\n/** Error message when a value fails the safe-path-segment validation. @param label - What kind of value was being validated. @param segment - The rejected value */\nexport const INVALID_PATH_SEGMENT = (label: string, segment: string) =>\n `Invalid ${label}: \"${segment}\" must match /^[A-Za-z0-9_$@:][A-Za-z0-9_$@:/-]*$/`;\n\n/** Warning message when a specified RPC config file cannot be resolved on disk. @param configFile - The requested config filename. @param configFilePath - The resolved absolute path */\nexport const CONFIG_FILE_NOT_FOUND = (\n configFile: string,\n configFilePath: string,\n) =>\n ` ⚠︎ The specified RPC config file ${configFile} cannot be found at ${configFilePath}, loading the defaults..`;\n\nexport const NO_CONFIG_FOUND =\n ` ⚡︎ No RPC config found, loading the defaults..`;\n\nexport const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;\n\n/** Error template for duplicate server function names across files. @param name - The duplicate registered name */\nexport const DUPLICATE_FUNCTION_NAME = (name: string) =>\n `Duplicate server function \"${name}\" detected. Each server function must have a unique name. Remove or rename the duplicate.`;\n","// src/koa/helpers.ts\nimport type { Buffer } from \"node:buffer\";\nimport type { ViteDevServer } from \"vite\";\nimport { createRPCMiddleware } from \"./createMiddleware.ts\";\nimport type { BodyResult } from \"@thednp/rpc\";\nimport type { Koa } from \"./index.ts\";\nimport type { KoaContext } from \"./types.d.ts\";\n\n/**\n * Convenience function to load RPC config and attach the RPC middleware to a Koa app.\n * Dynamically imports loadRPCConfig and registers the middleware.\n * @param app - Koa application instance\n */\nexport async function attachRPC(app: Koa) {\n // The main plugin entry statically imports Vite, so loadRPCConfig is\n // imported lazily: function bundles that never call attachRPC (e.g.\n // serverless functions) keep Vite out of the bundle (or externalized).\n const { loadRPCConfig } = await import(\"@thednp/rpc\");\n\n const config = await loadRPCConfig();\n const { adapter: _adapter, ...options } = config;\n app.use(createRPCMiddleware(options));\n}\n\n/**\n * Attaches Vite's dev server middlewares to a Koa app for development mode.\n * Bridges Koa's context-based middleware to Vite's Connect-compatible middleware stack\n * by forwarding Koa body, wrapping res.end, and delegating back to Koa on 404 or unhandled routes.\n * @param app - Koa application instance\n * @param vite - Running Vite dev server\n */\nexport function attachVite(app: Koa, vite: ViteDevServer): void {\n app.use(async (ctx: KoaContext, next) => {\n const req = ctx.req;\n const res = ctx.res;\n\n // Forward Koa body to req.body for Express/RPC middleware compatibility\n const requestBody = ctx.request?.body;\n if (requestBody !== undefined) {\n Object.assign(req, { body: requestBody });\n }\n\n const originalEnd = res.end.bind(res);\n let viteHandled = false;\n // @ts-ignore - Koa res.end type mismatch with Node's\n res.end = function (...args: unknown[]) {\n viteHandled = true;\n return originalEnd(args[0]);\n };\n\n await new Promise<void>((resolve) => {\n vite.middlewares(req, res, () => resolve(undefined));\n });\n\n // @ts-ignore - Koa res.end type mismatch with Node's\n res.end = originalEnd;\n\n if (!viteHandled || res.statusCode === 404) {\n await next();\n }\n });\n}\n\n/**\n * Reads and parses the HTTP request body from a Koa context.\n * If koa-body or another body parser already consumed the stream,\n * uses the pre-parsed body from `ctx.request.body`.\n * @param ctx - Koa context\n * @returns A promise resolving to the parsed body with its content type\n */\nexport const readBody = (\n ctx: KoaContext,\n): Promise<BodyResult> => {\n const contentType = ctx.request.headers[\"content-type\"]?.toLowerCase() || \"\";\n\n return new Promise((resolve, reject) => {\n // If an koa-body already consumed the stream\n // via app.use(koaBody()), use ctx.request.body directly\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n const reqBody = ctx.request.body;\n if (reqBody !== undefined) {\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart\n ? (reqBody as Record<string, unknown>)\n : isJSON\n ? reqBody\n : isUrlEncoded\n ? (reqBody as Record<string, unknown>)\n : String(reqBody),\n } as BodyResult);\n return;\n }\n\n // OR read the body normally\n let body = \"\";\n\n const toggleListeners = (add?: boolean) => {\n const method = add ? \"on\" : \"off\";\n ctx.req[method](\"data\", onData);\n ctx.req[method](\"end\", onEnd);\n ctx.req[method](\"error\", onError);\n };\n\n const onData = (chunk: Buffer) => {\n // chunks.push(chunk);\n body += chunk.toString();\n };\n\n const onEnd = () => {\n toggleListeners();\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n try {\n const data = isMultipart\n ? { raw: body }\n : isUrlEncoded\n ? Object.fromEntries(new URLSearchParams(body))\n : JSON.parse(body);\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart ? (data as Record<string, unknown>) : data,\n } as BodyResult);\n } catch (_er) {\n resolve({ contentType: \"text/plain\", data: String(body) });\n }\n };\n\n const onError = (err: Error) => {\n toggleListeners();\n reject(err);\n };\n\n toggleListeners(true);\n });\n};\n\n/**\n * Issues an HTTP redirect on a Koa context. Koa's `ctx.redirect(location)`\n * defaults to `302` and sets the `Location` header; the status code must be\n * overridden *after* the call (setting it before is ignored, see\n * koajs/koa#857). Defaults to `303 See Other` for convention\n * (Post/Redirect/Get).\n * @param ctx - Koa context\n * @param location - The URL to redirect to\n * @param status - HTTP status code, defaults to 303\n */\nexport const redirect = (\n ctx: KoaContext,\n location: string,\n status = 303,\n): void => {\n ctx.redirect(location);\n ctx.status = status;\n};\n","// src/koa/createMiddleware.ts\nimport type { Context, Next } from \"koa\";\nimport type { KoaMiddlewareFn, KoaMiddlewareOptions } from \"./types.d.ts\";\nimport type { JsonValue } from \"@thednp/rpc\";\nimport type { RequestEvent } from \"@thednp/rpc/server\";\nimport {\n escapeRegExp,\n formatError,\n getGlobalPrefix,\n hasContentTypeMismatch,\n isOriginAllowed,\n provideRequestContext,\n safeURL,\n scanForServerFiles,\n} from \"@thednp/rpc/server\";\nimport { getFunctionsForPrefix } from \"../functionsMap.ts\";\nimport {\n BAD_REQUEST,\n CLIENT_DISCONNECTED,\n FUNCTION_NOT_FOUND,\n METHOD_NOT_ALLOWED,\n MIDDLEWARE_NAME_USED,\n REQUEST_FORBIDDEN,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"../constants.ts\";\n\nimport {\n defaultMiddlewareOptions,\n defaultPrefix,\n defaultRPCOptions,\n} from \"../options.ts\";\nimport { readBody, redirect as koaRedirect } from \"./helpers.ts\";\n\nlet middlewareCount = 0;\nconst middlewareStack = new Set<string>();\n\n/**\n * Creates a Koa middleware with optional path and rpcPrefix filtering.\n * Middleware names are deduplicated. Prefix and path regexes are compiled once at creation time.\n * Koa URL is normalized via `new URL()` to strip query strings before matching.\n * @param initialOptions - Options for rpcPrefix, path matching, and the handler function\n * @returns A Koa middleware function\n */\nexport const createMiddleware: KoaMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as KoaMiddlewareOptions;\n\n const middlewareName = options.name;\n let rpcPrefix = options.rpcPrefix;\n const path = options.path;\n const handler = options.handler;\n\n let name = middlewareName;\n if (!name) {\n name = \"viteRPCMiddleware-\" + middlewareCount;\n middlewareCount += 1;\n }\n if (middlewareStack.has(name)) {\n throw new Error(MIDDLEWARE_NAME_USED(name));\n }\n middlewareStack.add(name);\n\n // Hoist regex compilation out of per-request path. Escape the prefix to\n // prevent regex injection via metacharacters in the config string.\n const prefixRegex: RegExp | null = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : null;\n const pathMatcher: RegExp | null = path\n ? (typeof path === \"string\" ? new RegExp(path) : path)\n : null;\n\n const middlewareHandler = async (ctx: Context, next: Next) => {\n const url = safeURL(ctx.url).pathname;\n\n // No need to continue when no handler provided\n if (!handler) {\n return next();\n }\n\n if (pathMatcher && !pathMatcher.test(url)) {\n return next();\n }\n\n if (prefixRegex && !prefixRegex.test(url)) {\n return next();\n }\n\n rpcPrefix = (rpcPrefix ?? defaultPrefix) as string;\n\n // When serving from production server, scan for server files\n if (getFunctionsForPrefix(rpcPrefix).size === 0) {\n await scanForServerFiles({\n rpcPrefix,\n serverFiles: (options as unknown as { serverFiles?: \"exact\" | \"glob\" })\n .serverFiles,\n scanRoot: (options as unknown as { scanRoot?: string }).scanRoot,\n } as never);\n }\n\n await handler(ctx, next);\n };\n\n Object.defineProperty(middlewareHandler, \"name\", {\n value: name,\n });\n\n return middlewareHandler;\n};\n\n/**\n * Creates the Koa RPC middleware that routes incoming requests to registered server functions.\n * Wraps the generic createMiddleware with the RPC handler that reads the body, dispatches\n * to the matching function, and sets the JSON-serialized result on ctx.body.\n * @param initialOptions - Options including rpcPrefix for URL routing\n * @returns A Koa middleware function\n */\nexport const createRPCMiddleware: KoaMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n { rpcPrefix: defaultRPCOptions.rpcPrefix },\n initialOptions,\n ) as KoaMiddlewareOptions;\n\n // Hoist prefix regex (escaped) and the literal prefix-for-replace out of the\n // per-request handler to avoid regex injection and per-request compilation.\n const rpcPrefix = options.rpcPrefix;\n const prefix = rpcPrefix || getGlobalPrefix() || defaultPrefix;\n const prefixRegex = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : /* istanbul ignore next */ null;\n const prefixReplace = `/${prefix}/`;\n\n return createMiddleware({\n ...options,\n handler: async (ctx: Context, _next: Next) => {\n const reqUrl = safeURL(ctx.url);\n const url = reqUrl.pathname;\n // const { rpcPrefix } = options;\n\n // Defense-in-depth: validate prefix match via escaped regex even though\n // the outer createMiddleware gates on the same prefix already.\n // istanbul ignore next\n if (prefixRegex && !prefixRegex.test(url)) {\n return;\n }\n\n // Optional origin check: reject requests whose Origin header is not in\n // the configured allowlist. Requests without an Origin header\n // (curl, native clients) pass through unchecked.\n if (!isOriginAllowed(options.origin, ctx.headers.origin)) {\n ctx.status = 403;\n ctx.body = { error: REQUEST_FORBIDDEN };\n return;\n }\n\n const functionName = url.replace(prefixReplace, \"\");\n const serverFunction = getFunctionsForPrefix(prefix).get(functionName);\n\n if (!serverFunction) {\n ctx.status = 404;\n ctx.body = { error: FUNCTION_NOT_FOUND };\n return;\n }\n\n try {\n const method = serverFunction.options?.method || \"POST\";\n if (ctx.method.toUpperCase() !== method) {\n ctx.status = 405;\n ctx.body = { error: METHOD_NOT_ALLOWED };\n return;\n }\n\n let args: JsonValue[] = [];\n if (method === \"GET\") {\n const raw = reqUrl.searchParams.get(\"args\");\n if (raw) {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) {\n ctx.status = 400;\n ctx.body = { error: BAD_REQUEST };\n return;\n }\n args = parsed as JsonValue[];\n }\n } else {\n // Content-type enforcement: strict for json/text, lenient between forms.\n // Requests without a Content-Type header are exempt (curl/GET compat).\n // Checked BEFORE readBody so mismatched bodies are never buffered.\n if (\n hasContentTypeMismatch(\n serverFunction.options?.contentType ?? \"application/json\",\n ctx.headers[\"content-type\"],\n )\n ) {\n ctx.status = 415;\n ctx.body = { error: UNSUPPORTED_MEDIA_TYPE };\n return;\n }\n const body = await readBody(ctx);\n args = Array.isArray(body.data)\n ? body.data as JsonValue[]\n : [body.data as JsonValue];\n }\n const requestEvent: RequestEvent = {\n request: ctx.req,\n response: ctx,\n nativeEvent: ctx,\n locals: ctx.state,\n functionName,\n redirect: (location, status = 303) => {\n requestEvent.redirected = { location, status };\n koaRedirect(ctx, location, status);\n },\n send: (status, body, headers) => {\n requestEvent.sent = { status, body, headers };\n if (headers) {\n for (const [name, value] of Object.entries(headers)) {\n ctx.set(name, value);\n }\n }\n ctx.status = status;\n ctx.body = body;\n },\n };\n const { data: resultData, cancel } = provideRequestContext(\n requestEvent,\n () => serverFunction.handler(...args),\n );\n const onClose = () => cancel(CLIENT_DISCONNECTED);\n ctx.req.on(\"close\", onClose);\n const result = await resultData;\n ctx.req.off(\"close\", onClose);\n\n // Skip the JSON send when the server function issued a redirect or\n // short-circuited with `send`; the bound Koa adapter already set\n // ctx.status/ctx.body.\n // istanbul ignore else\n if (!requestEvent.redirected && !requestEvent.sent) {\n ctx.status = 200;\n ctx.body = { data: result };\n }\n } catch (err) {\n console.error(String(err));\n const isProduction = process.env.NODE_ENV === \"production\";\n ctx.status = 500;\n ctx.body = formatError(err, isProduction);\n }\n },\n });\n};\n"],"mappings":";AAcA,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;CACT,aAAa;CACb,UAAU,KAAA;AACZ;AAEA,MAAa,2BAA8C;CACzD,WAAW,KAAA;CACX,MAAM,KAAA;CACN,QAAQ,KAAA;AACV;;;;;;;;;;;ACdA,MAAM,qBAAqB,OAAO,IAAI,yBAAyB;;;;;;AAO/D,MAAa,0BAGR,WACH,wCACI,IAAI,IAAI;;;;;;AAOd,MAAa,yBACX,WAC+B;CAC/B,IAAI,CAAC,wBAAwB,IAAI,MAAM,GACrC,wBAAwB,IAAI,wBAAQ,IAAI,IAAI,CAAC;CAE/C,OAAO,wBAAwB,IAAI,MAAM;AAC3C;;;AC3BA,MAAa,qBAAqB;AAElC,MAAa,qBAAqB;AAElC,MAAa,oBAAoB;AAEjC,MAAa,yBAAyB;AAEtC,MAAa,cAAc;AAI3B,MAAa,sBAAsB;;AAGnC,MAAa,wBAA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M,YAAY;MAC/B,aAAa,OAAO;OAAE;OAAQ;OAAM;MAAQ;MAC5C,IAAI,SACF,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,GAChD,IAAI,IAAI,MAAM,KAAK;MAGvB,IAAI,SAAS;MACb,IAAI,OAAO;KACb;IACF;IACA,MAAM,EAAE,MAAM,YAAY,WAAW,sBACnC,oBACM,eAAe,QAAQ,GAAG,IAAI,CACtC;IACA,MAAM,gBAAgB,OAAO,mBAAmB;IAChD,IAAI,IAAI,GAAG,SAAS,OAAO;IAC3B,MAAM,SAAS,MAAM;IACrB,IAAI,IAAI,IAAI,SAAS,OAAO;IAM5B,IAAI,CAAC,aAAa,cAAc,CAAC,aAAa,MAAM;KAClD,IAAI,SAAS;KACb,IAAI,OAAO,EAAE,MAAM,OAAO;IAC5B;GACF,SAAS,KAAK;IACZ,QAAQ,MAAM,OAAO,GAAG,CAAC;IACzB,MAAM,eAAe,QAAQ,IAAI,aAAa;IAC9C,IAAI,SAAS;IACb,IAAI,OAAO,YAAY,KAAK,YAAY;GAC1C;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"koa.mjs","names":[],"sources":["../../src/options.ts","../../src/functionsMap.ts","../../src/constants.ts","../../src/server-helpers.ts","../../src/koa/helpers.ts","../../src/koa/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\n/**\n * Defaults applied to a server function that declares no `method`,\n * `credentials`, or `contentType` of its own.\n */\nexport const defaultServerFnOptions: ServerFunctionOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n};\n\n/**\n * The built-in RPC endpoint prefix, used when neither an explicit prefix nor a\n * global one (`getGlobalPrefix`) is supplied. Kept for backward compatibility\n * with pre-multi-prefix setups, where every function lived under this one map.\n */\nexport const defaultPrefix = \"__rpc\";\n\n/**\n * Baseline plugin options. `defineConfig` merges a user's partial config over\n * these, and `loadRPCConfig` merges a loaded config file over them, so every\n * option has a defined value even when a config file omits it.\n */\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: defaultPrefix,\n serverFiles: \"exact\",\n scanRoot: undefined,\n};\n\n/**\n * Baseline middleware options. Note `rpcPrefix` is `undefined` rather than\n * `defaultPrefix` on purpose: leaving it unset lets `resolveRPCPrefix` fall\n * through to the global prefix, which is what makes a published global prefix\n * reach the middleware.\n */\nexport const defaultMiddlewareOptions: MiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n};\n","import type { ServerFnEntry } from \"./types.d.ts\";\nimport { defaultPrefix } from \"./options.ts\";\n\n/**\n * Global symbol under which the shared `serverFunctionsByPrefix` map is stored\n * on `globalThis`. Keeping it on a `Symbol.for` key makes it instance-stable\n * across the bundled entry copies (`index.mjs`, `server.mjs`, `express.mjs`,\n * ...) and dev-server hot reloads, exactly like the request-context storage in\n * `context.ts`. Without this, `scanForServerFiles` (bundled into the plugin)\n * would populate a map copy the adapter middleware could not read.\n */\nconst functionsMapSymbol = Symbol.for(\"thednp.rpc.functionsMap\");\n\n/**\n * Map of rpcPrefix -> Map of function names -> ServerFnEntry\n * Enables multiple RPC instances with different prefixes to coexist\n * without name collisions.\n */\nexport const serverFunctionsByPrefix: Map<\n string,\n Map<string, ServerFnEntry>\n> = ((globalThis as Record<symbol, Map<string, Map<string, ServerFnEntry>>>)[\n functionsMapSymbol\n] ??= new Map());\n\n/**\n * Gets or creates the function map for a specific prefix.\n * @param prefix - The RPC prefix (e.g., \"__rpc\", \"v1:rpc\", \"admin:rpc\")\n * @returns Map of function names to ServerFnEntry for that prefix\n */\nexport const getFunctionsForPrefix = (\n prefix: string,\n): Map<string, ServerFnEntry> => {\n if (!serverFunctionsByPrefix.has(prefix)) {\n serverFunctionsByPrefix.set(prefix, new Map());\n }\n return serverFunctionsByPrefix.get(prefix)!;\n};\n\n/**\n * Backward compatibility: default map for the default prefix.\n * Legacy code can still use serverFunctionsMap.set(name, entry).\n */\nexport const serverFunctionsMap: Map<string, ServerFnEntry> = {\n get: (key: string) => getFunctionsForPrefix(defaultPrefix).get(key),\n set: (key: string, value: ServerFnEntry) =>\n getFunctionsForPrefix(defaultPrefix).set(key, value),\n has: (key: string) => getFunctionsForPrefix(defaultPrefix).has(key),\n delete: (key: string) => getFunctionsForPrefix(defaultPrefix).delete(key),\n clear: () => getFunctionsForPrefix(defaultPrefix).clear(),\n get size() {\n return getFunctionsForPrefix(defaultPrefix).size;\n },\n entries: () => getFunctionsForPrefix(defaultPrefix).entries(),\n keys: () => getFunctionsForPrefix(defaultPrefix).keys(),\n values: () => getFunctionsForPrefix(defaultPrefix).values(),\n forEach: (\n callback: (\n value: ServerFnEntry,\n key: string,\n map: Map<string, ServerFnEntry>,\n ) => void,\n ) => getFunctionsForPrefix(defaultPrefix).forEach(callback),\n [Symbol.iterator]: () =>\n getFunctionsForPrefix(defaultPrefix)[Symbol.iterator](),\n} as unknown as Map<string, ServerFnEntry>;\n","/**\n * @module User-facing message strings.\n *\n * Two shapes live here: plain message constants (the exact text an RPC\n * response body carries) and message *factories* for the cases that need a\n * value interpolated. Both are part of the wire contract for the bodies below,\n * so the casing is deliberate — e.g. a client matching on\n * `METHOD_NOT_ALLOWED` must see `\"Method Not Allowed\"`, not `\"Method not\n * allowed\"`. These strings are also what keeps error responses generic: they\n * never include the requested function name, so a response cannot be used to\n * enumerate what exists.\n */\n/** Thrown-name for an operation stopped by its own `cancel()`. */\nexport const OPERATION_ABORTED = \"Operation aborted\";\n\n/** Warning text used when a request is cancelled by an HTTP 408/499 response. */\nexport const REQUEST_CANCELLED = \"Request was cancelled\";\n\n/** Prefix of the `Error` message the client helpers throw for a non-OK HTTP response. The status text is appended; the response body is deliberately not read, so server-side detail never reaches the client through this path. */\nexport const FETCH_ERROR_PREFIX = \"Fetch error: \";\n\n/** Warning logged when a scanned server module exports nothing. */\nexport const NO_SERVER_FUNCTION_FOUND = \"No server function found.\";\n\n/** Error logged when a server function file cannot be loaded by Vite's SSR loader. */\nexport const ERROR_LOADING_FILE = \"Error loading file:\";\n\n/** Body of a 404. Deliberately does not name the requested function. */\nexport const FUNCTION_NOT_FOUND = \"Function not found\";\n\n/** Body of a 405, returned when the HTTP method does not match the function's declared method. */\nexport const METHOD_NOT_ALLOWED = \"Method Not Allowed\";\n\n/** Body of a 403, returned when the optional origin allowlist rejects the request. */\nexport const REQUEST_FORBIDDEN = \"Forbidden\";\n\n/** Body of a 415, returned when the request's `Content-Type` does not satisfy the function's declared `contentType`. */\nexport const UNSUPPORTED_MEDIA_TYPE = \"Unsupported Media Type\";\n\n/** Body of a 413, returned when the request body exceeds the host's configured size limit. */\nexport const PAYLOAD_TOO_LARGE = \"Payload Too Large\";\n\n/** Body of a 400, returned when a GET `?args=` value parses but is not an array. */\nexport const BAD_REQUEST = \"Bad Request\";\n\n/** Body of a 500. Always generic — never the underlying error, so internals cannot leak. */\nexport const INTERNAL_SERVER_ERROR = \"Internal Server Error\";\n\n/** Abort reason used when the client disconnects mid-dispatch. */\nexport const CLIENT_DISCONNECTED = \"client disconnected\";\n\n/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */\nexport const MIDDLEWARE_NAME_USED = (name: string) =>\n `The middleware name \"${name}\" is already used.`;\n\n/** Error message when a value fails the safe-identifier validation. @param label - What kind of value was being validated. @param name - The rejected value */\nexport const INVALID_IDENTIFIER = (label: string, name: string) =>\n `Invalid ${label}: \"${name}\" must match /^[A-Za-z_$][A-Za-z0-9_$]*$/`;\n\n/** Error message when a value fails the safe-path-segment validation. @param label - What kind of value was being validated. @param segment - The rejected value */\nexport const INVALID_PATH_SEGMENT = (label: string, segment: string) =>\n `Invalid ${label}: \"${segment}\" must match /^[A-Za-z0-9_$@:][A-Za-z0-9_$@:/-]*$/`;\n\n/** Warning message when a specified RPC config file cannot be resolved on disk. @param configFile - The requested config filename. @param configFilePath - The resolved absolute path */\nexport const CONFIG_FILE_NOT_FOUND = (\n configFile: string,\n configFilePath: string,\n) =>\n ` ⚠︎ The specified RPC config file ${configFile} cannot be found at ${configFilePath}, loading the defaults..`;\n\n/** Warning logged when no config file is discovered and the defaults are used. */\nexport const NO_CONFIG_FOUND =\n ` ⚡︎ No RPC config found, loading the defaults..`;\n\n/** Warning logged when a config file exists but could not be loaded; the defaults are used. */\nexport const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;\n\n/** Error template for duplicate server function names across files. @param name - The duplicate registered name */\nexport const DUPLICATE_FUNCTION_NAME = (name: string) =>\n `Duplicate server function \"${name}\" detected. Each server function must have a unique name. Remove or rename the duplicate.`;\n","/** @module Server-side utilities. Exports the `RPCError` class for typed server-side errors, `formatError` for middleware error responses, `isFormContentType` and `hasContentTypeMismatch` for content-type validation, and `walkGlobFiles` for recursively discovering `*.server.*` files. Never import this module in client code — it is server-only. */\nimport type { ContentType, JsonObject, JsonValue } from \"./types.d.ts\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n BAD_REQUEST,\n INTERNAL_SERVER_ERROR,\n PAYLOAD_TOO_LARGE,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"./constants.ts\";\nimport { defaultPrefix } from \"./options.ts\";\n\nconst GLOB_REGEX = /^.+\\.server\\.(ts|js|mjs|mts)$/;\n\n/**\n * Recursively walks `dir` and collects absolute paths to files whose\n * basename matches the `*.server.{ts,js,mjs,mts}` glob pattern.\n */\nexport const walkGlobFiles = async (dir: string): Promise<string[]> => {\n const results: string[] = [];\n const stack = [dir];\n while (stack.length) {\n const current = stack.pop()!;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch (_e) {\n continue;\n }\n for (const entry of entries) {\n const fullPath = join(current, entry.name);\n if (entry.isFile() && GLOB_REGEX.test(entry.name)) {\n results.push(fullPath);\n } else if (entry.isDirectory()) {\n stack.push(fullPath);\n }\n }\n }\n return results;\n};\n\n/**\n * A typed error thrown from server functions.\n * The middleware serializes the `message` and `code` in the response,\n * allowing clients to recognise and handle specific error conditions.\n */\nexport class RPCError extends Error {\n /** Machine-readable error code (e.g. \"VALIDATION_FAILED\", \"UNAUTHORIZED\") */\n code: string;\n /** Optional diagnostic payload */\n data?: JsonValue;\n constructor(message: string, code = \"INTERNAL\", data?: JsonValue) {\n super(message);\n this.name = \"RPCError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/**\n * Formats an error for the RPC middleware response.\n * In development the full `RPCError` payload is included so developers\n * can quickly identify issues. Unexpected exceptions never expose their\n * message — only the generic \"Internal Server Error\" is sent, preventing\n * information disclosure; server-side diagnostics are preserved via the\n * middleware's `console.error` logging.\n */\nexport const formatError = (\n err: unknown,\n isProduction: boolean,\n): JsonObject => {\n if (isProduction) {\n return { error: INTERNAL_SERVER_ERROR };\n }\n if (err instanceof RPCError) {\n const payload: JsonObject = {\n error: err.message || INTERNAL_SERVER_ERROR,\n code: err.code,\n };\n if (err.data !== undefined) payload.data = err.data;\n return payload;\n }\n return { error: INTERNAL_SERVER_ERROR };\n};\n\n/**\n * Checks whether a content type maps to a form encoding\n * (`multipart/form-data` or `application/x-www-form-urlencoded`).\n * Form-declared functions accept either encoding so native browser\n * submissions (urlencoded) keep working without JavaScript.\n */\n/**\n * An error carrying an HTTP status, so the dispatch can answer that status\n * instead of flattening every failure to a `500`.\n */\nexport interface ClientHttpError extends Error {\n status?: number;\n statusCode?: number;\n}\n\n/**\n * Tags an error with an HTTP status for the dispatch to surface.\n *\n * Used where a malformed *request* is the fault — a body that does not parse\n * under a declared JSON `Content-Type`, a GET `?args=` value that is not valid\n * JSON. Every host framework rpc supports answers `400` for these (Express\n * `entity.parse.failed`, Fastify `FST_ERR_CTP_INVALID_JSON_BODY`, koa-bodyparser,\n * and h3's own `readBody`), and treating one as a server fault both misreports\n * the fault and turns a trivial client mistake into a log entry.\n * @param status - The HTTP status to answer with\n * @param message - Internal diagnostic message; never sent to the client\n * @returns An `Error` carrying `status`\n */\nexport const httpError = (status: number, message: string): ClientHttpError => {\n const err = new Error(message) as ClientHttpError;\n err.status = status;\n return err;\n};\n\n/**\n * Recognises an error that should produce a `4xx` response rather than a `500`.\n *\n * Matches the `status` / `statusCode` convention used by h3's `HTTPError`, the\n * `http-errors` objects Express's `body-parser` throws, and anything else that\n * carries a numeric 4xx. Shared by all five adapters so a host-framework\n * signal and an rpc-raised one are handled by the same rule.\n * @param err - The caught error\n * @returns True when the error denotes a client (4xx) fault\n */\nconst readClientStatus = (err: unknown): number | undefined => {\n const candidate = err as ClientHttpError | null | undefined;\n // Reads both conventions: h3's `HTTPError` and rpc's `httpError` use\n // `status`, while the `http-errors` objects Express's `body-parser` throws\n // and Koa's `ctx.throw` use `statusCode`.\n const status = candidate?.status ?? candidate?.statusCode;\n return typeof status === \"number\" && status >= 400 && status < 500\n ? status\n : undefined;\n};\n\n/**\n * Recognises an error that should produce a `4xx` response rather than a `500`.\n * Matches the `status` / `statusCode` convention used by h3's `HTTPError`, the\n * `http-errors` objects Express's `body-parser` throws, and anything else\n * carrying a numeric 4xx. Shared by all five adapters so a host-framework\n * signal and an rpc-raised one are handled by the same rule.\n * @param err - The caught error\n * @returns True when the error denotes a client (4xx) fault\n */\nexport const isClientHttpError = (err: unknown): boolean =>\n readClientStatus(err) !== undefined;\n\n/**\n * Reads the status to answer for a client error. Defaults to `400` rather than\n * `500` so an unrecognised 4xx is never reported as a server fault.\n * @param err - The caught error\n * @returns The 4xx status to answer with\n */\nexport const clientErrorStatus = (err: unknown): number =>\n readClientStatus(err) ?? 400;\n\nexport const clientErrorMessage = (status: number): string => {\n if (status === 413) return PAYLOAD_TOO_LARGE;\n if (status === 415) return UNSUPPORTED_MEDIA_TYPE;\n return BAD_REQUEST;\n};\n\nexport const isFormContentType = (contentType: string): boolean =>\n contentType === \"multipart/form-data\" ||\n contentType === \"application/x-www-form-urlencoded\";\n\n/**\n * Detects whether an incoming request's `Content-Type` header conflicts\n * with the function's declared content type. JSON and text functions are\n * enforced strictly (exact match wins), while form functions accept both\n * form encodings because the nojs fallback submits urlencoded forms to\n * multipart-declared endpoints. Requests without a `Content-Type` header\n * (curl, GET, legacy clients) are exempt from enforcement.\n * @param declared - The declared `contentType` from the server function options\n * @param rawHeader - The raw `Content-Type` request header, if present\n */\nexport const hasContentTypeMismatch = (\n declared: ContentType,\n rawHeader: string | undefined,\n): boolean => {\n // No Content-Type header → exempt (url bar, GET, curl compatibility)\n if (!rawHeader) return false;\n // Strip parameters (charset, boundary) before comparison\n const incomingType = rawHeader.trim().toLowerCase().split(\";\")[0].trim();\n if (isFormContentType(declared)) {\n // Forms: reject only non-form encodings (lenient between the two)\n return !isFormContentType(incomingType);\n }\n return incomingType !== declared;\n};\n\n/**\n * Decides whether a request may proceed, given the configured origin allowlist\n * and the two headers a browser can be made to reveal.\n *\n * Four tiers, evaluated in order — the first tier with a signal decides:\n *\n * 1. `origin` option unset → everything passes. No validation is performed.\n * 2. `Origin` present → the allowlist decides, exactly as {@link isOriginAllowed}.\n * 3. `Origin` absent but `Sec-Fetch-Site` present → allow only `same-origin`\n * and `none`; anything else (including an unrecognised value) is rejected.\n * 4. Both absent → passes. This is the deliberate, documented curl/native hole.\n *\n * Tier 2 must short-circuit ahead of tier 3. `Sec-Fetch-Site` is a coarse\n * four-value enum that cannot name a host, so on its own it would reject a\n * legitimate request from an allowlisted sibling subdomain (`same-site`). The\n * allowlist exists precisely to admit that case, and it can only do so while\n * `Origin` survives. `Sec-Fetch-Site` earns a vote only once the precise signal\n * has been stripped away by something in the chain — at which point there is\n * nothing left to trust, so it fails closed.\n *\n * Browsers never strip `Origin` themselves, so tier 3 can only fire when a\n * proxy, sanitising middleware, or misconfigured CDN removed it. No legitimate\n * browser request can regress.\n *\n * An empty (or whitespace-only) header value counts as **absent**, not as an\n * unrecognised signal. No browser emits an empty `Sec-Fetch-Site`, and adapters\n * disagree on what their header accessor returns for a missing header (Node's\n * `req.headers` yields `undefined`, Hono's `c.req.header()` may yield `\"\"`).\n * Normalising here keeps all five adapters behaving identically instead of\n * inheriting whichever convention their framework happens to use.\n * @param allowed - The configured `origin` option, if any\n * @param origin - The raw `Origin` request header, if present\n * @param site - The raw `Sec-Fetch-Site` request header, if present\n * @returns `true` when the request may proceed\n */\nexport const isOriginRequestAllowed = (\n allowed: string | string[] | undefined,\n origin: string | undefined,\n site: string | undefined,\n): boolean => {\n if (!allowed) return true; // tier 1 — the check is opt-in\n if (origin?.trim()) return isOriginAllowed(allowed, origin); // tier 2 — precise\n if (!site?.trim()) return true; // tier 4 — curl / native client\n // tier 3 — precision lost, so fail closed\n return site === \"same-origin\" || site === \"none\";\n};\n\n/**\n * Escapes special regex metacharacters in a string.\n * Used to safely embed user-configurable values (like rpcPrefix) into regular expressions,\n * preventing ReDoS and regex injection attacks.\n * @param s - The raw string to escape\n * @returns The escaped string safe for use in new RegExp()\n */\nexport function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Decides whether a request's `Origin` header is allowed by the configured\n * allowlist. Shared by all five adapters so the rule lives in exactly one place.\n *\n * - No `allowed` value (option unset) → everything passes: no validation.\n * - No `requestOrigin` header → passes, preserving curl/native-client access.\n * - Otherwise the header must match one of the entries exactly.\n *\n * A single string and a one-element array behave identically, so widening\n * `origin` to `string | string[]` is backward compatible.\n *\n * `Origin: null` (sandboxed iframes, `file://`, extension pages) is rejected\n * whenever an allowlist is set, because it never equals a real origin.\n * @param allowed - The configured `origin` option, if any\n * @param requestOrigin - The raw `Origin` request header, if present\n * @returns `true` when the request may proceed\n */\nexport const isOriginAllowed = (\n allowed: string | string[] | undefined,\n requestOrigin: string | undefined,\n): boolean => {\n if (!allowed || !requestOrigin) return true;\n return Array.isArray(allowed)\n ? allowed.includes(requestOrigin)\n : requestOrigin === allowed;\n};\n\nconst SAFE_URL_BASE = \"http://localhost\";\n\n/**\n * Parses a raw request URL against a fixed base without ever throwing.\n * Malformed request-targets (e.g. `/\\`, `//`, `/\\/`) make the WHATWG URL\n * parser throw `TypeError: Invalid URL`; the adapters call this while\n * building the per-request URL **before** their dispatch `try` block, so an\n * unhandled rejection there crashes raw `node:http` hosts (and Express 4).\n * On failure we fall back to the base root: the resulting pathname never\n * matches the RPC prefix, so the request is treated as non-RPC and falls\n * through to `next()` / 404 instead of crashing the process.\n * @param rawUrl - Raw request URL (path + optional query string)\n * @param base - Optional base URL, defaults to a fixed localhost origin\n * @returns A URL object; never throws\n */\nexport const safeURL = (rawUrl: string, base = SAFE_URL_BASE): URL => {\n try {\n return new URL(rawUrl, base);\n } catch {\n return new URL(\"/\", base);\n }\n};\n\nconst globalPrefixSymbol = Symbol.for(\"thednp.rpc.globalPrefix\");\n\n/** Global rpcPrefix from the last loaded config / middleware — fallback for functions without explicit prefix. */\nexport const getGlobalPrefix = (): string | undefined =>\n (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ];\n\n/**\n * Publishes the global RPC prefix, consulted by `resolveRPCPrefix` whenever no\n * explicit prefix is supplied. `loadRPCConfig` calls this on every return path\n * so a loaded config is the fallback for later registrations and dispatches.\n *\n * Stored on a `Symbol.for` key on `globalThis` so it stays instance-stable\n * across the bundled entry copies (`server.mjs`, `express.mjs`, ...) and dev\n * server hot reloads — the same technique as the request-context storage.\n * @param prefix - The prefix to publish, or `undefined` to clear it\n */\nexport const setGlobalPrefix = (prefix: string | undefined): void => {\n if (prefix) {\n (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ] = prefix;\n } else {\n delete (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ];\n }\n};\n\n/**\n * Resolves the effective RPC prefix: the explicit one when given, otherwise\n * the global prefix set by `setGlobalPrefix` / `loadRPCConfig`, otherwise the\n * built-in default.\n *\n * Every adapter resolves its prefix through this single function — in both the\n * outer `createMiddleware` gate and the `createRPCMiddleware` dispatch — so the\n * two halves of a request can never disagree, and so a prefix registered by\n * `createServerFunction` (which resolves the same way) is always the prefix the\n * middleware looks up. Resolving the two sides independently is what allowed\n * h3 to drift from the other four adapters, and what left the documented\n * global-prefix flow returning 404 on all of them.\n * @param rpcPrefix - Explicit prefix from config or middleware options\n * @returns The prefix to gate on, look up in, and strip from the request path\n */\nexport const resolveRPCPrefix = (rpcPrefix?: string): string =>\n rpcPrefix || getGlobalPrefix() || defaultPrefix;\n","// src/koa/helpers.ts\nimport type { Buffer } from \"node:buffer\";\nimport type { ViteDevServer } from \"vite\";\nimport { createRPCMiddleware } from \"./createMiddleware.ts\";\nimport { httpError } from \"../server-helpers.ts\";\nimport type { BodyResult } from \"@thednp/rpc\";\nimport type { Koa, KoaContext } from \"./types.d.ts\";\n\n/**\n * Convenience function to load RPC config and attach the RPC middleware to a Koa app.\n * Dynamically imports loadRPCConfig and registers the middleware.\n * @param app - Koa application instance\n */\nexport async function attachRPC(app: Koa) {\n // The main plugin entry statically imports Vite, so loadRPCConfig is\n // imported lazily: function bundles that never call attachRPC (e.g.\n // serverless functions) keep Vite out of the bundle (or externalized).\n const { loadRPCConfig } = await import(\"@thednp/rpc\");\n\n const options = await loadRPCConfig();\n app.use(createRPCMiddleware(options));\n}\n\n/**\n * Attaches Vite's dev server middlewares to a Koa app for development mode.\n * Bridges Koa's context-based middleware to Vite's Connect-compatible middleware stack\n * by forwarding Koa body, wrapping res.end, and delegating back to Koa on 404 or unhandled routes.\n * @param app - Koa application instance\n * @param vite - Running Vite dev server\n */\nexport function attachVite(app: Koa, vite: ViteDevServer): void {\n app.use(async (ctx: KoaContext, next) => {\n const req = ctx.req;\n const res = ctx.res;\n\n // Forward Koa body to req.body for Express/RPC middleware compatibility\n const requestBody = ctx.request?.body;\n if (requestBody !== undefined) {\n Object.assign(req, { body: requestBody });\n }\n\n const originalEnd = res.end.bind(res);\n let viteHandled = false;\n // @ts-ignore - Koa res.end type mismatch with Node's\n res.end = function (...args: unknown[]) {\n viteHandled = true;\n return originalEnd(args[0]);\n };\n\n await new Promise<void>((resolve) => {\n vite.middlewares(req, res, () => resolve(undefined));\n });\n\n // @ts-ignore - Koa res.end type mismatch with Node's\n res.end = originalEnd;\n\n if (!viteHandled || res.statusCode === 404) {\n await next();\n }\n });\n}\n\n/**\n * Reads and parses the HTTP request body from a Koa context.\n * If koa-body or another body parser already consumed the stream,\n * uses the pre-parsed body from `ctx.request.body`.\n * @param ctx - Koa context\n * @returns A promise resolving to the parsed body with its content type\n */\n/**\n * Parses a body leniently: JSON when it parses, otherwise the raw string.\n * Used for bodies that did not declare JSON — notably a request with no\n * `Content-Type` header, which must still arrive parsed if it carries JSON.\n * @param body - The raw body text\n * @returns The parsed JSON value, or the original string\n */\nconst parseJsonOrRawText = (body: string): unknown => {\n try {\n return JSON.parse(body);\n } catch {\n return body;\n }\n};\n\nexport const readBody = (\n ctx: KoaContext,\n): Promise<BodyResult> => {\n const contentType = ctx.request.headers[\"content-type\"]?.toLowerCase() || \"\";\n\n return new Promise((resolve, reject) => {\n // If an koa-body already consumed the stream\n // via app.use(koaBody()), use ctx.request.body directly\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n const reqBody = ctx.request.body;\n if (reqBody !== undefined) {\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart\n ? (reqBody as Record<string, unknown>)\n : isJSON\n ? reqBody\n : isUrlEncoded\n ? (reqBody as Record<string, unknown>)\n : String(reqBody),\n } as BodyResult);\n return;\n }\n\n // OR read the body normally\n let body = \"\";\n\n const toggleListeners = (add?: boolean) => {\n const method = add ? \"on\" : \"off\";\n ctx.req[method](\"data\", onData);\n ctx.req[method](\"end\", onEnd);\n ctx.req[method](\"error\", onError);\n };\n\n const onData = (chunk: Buffer) => {\n // chunks.push(chunk);\n body += chunk.toString();\n };\n\n const onEnd = () => {\n toggleListeners();\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n try {\n // Only a *declared* JSON body is parsed strictly; everything else keeps\n // the lenient sniff. Previously all three fell through to a single\n // `JSON.parse(body)`, so a malformed JSON body and a legitimate text\n // body produced the same exception and were indistinguishable — the\n // catch \"recovered\" both into a text/plain string, which silently\n // handed a JSON-declared function a string and answered 200.\n //\n // The lenient branch is deliberate and must stay: a request with no\n // `Content-Type` at all (curl, and the nojs form fallback) that\n // happens to carry JSON still has to arrive parsed.\n const data = isMultipart\n ? { raw: body }\n : isUrlEncoded\n ? Object.fromEntries(new URLSearchParams(body))\n : isJSON\n ? JSON.parse(body)\n : parseJsonOrRawText(body);\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart ? (data as Record<string, unknown>) : data,\n } as BodyResult);\n } catch (_er) {\n // A body that does not parse under a declared JSON Content-Type is a\n // client error. It used to resolve as `text/plain` with the raw string,\n // which silently handed a JSON-declared function a string and answered\n // 200 — failing open on malformed input. Every host framework rpc\n // supports answers 400 here (Express `entity.parse.failed`, Fastify\n // `FST_ERR_CTP_INVALID_JSON_BODY`, koa-bodyparser, h3's own readBody).\n reject(httpError(400, \"Invalid JSON body\"));\n }\n };\n\n const onError = (err: Error) => {\n toggleListeners();\n reject(err);\n };\n\n toggleListeners(true);\n });\n};\n\n/**\n * Issues an HTTP redirect on a Koa context. Koa's `ctx.redirect(location)`\n * defaults to `302` and sets the `Location` header; the status code must be\n * overridden *after* the call (setting it before is ignored, see\n * koajs/koa#857). Defaults to `303 See Other` for convention\n * (Post/Redirect/Get).\n * @param ctx - Koa context\n * @param location - The URL to redirect to\n * @param status - HTTP status code, defaults to 303\n */\nexport const redirect = (\n ctx: KoaContext,\n location: string,\n status = 303,\n): void => {\n ctx.redirect(location);\n ctx.status = status;\n};\n","// src/koa/createMiddleware.ts\nimport type { Context, Next } from \"koa\";\nimport type { KoaMiddlewareFn, KoaMiddlewareOptions } from \"./types.d.ts\";\nimport type { JsonValue } from \"@thednp/rpc\";\nimport type { RequestEvent } from \"@thednp/rpc/server\";\nimport {\n clientErrorMessage,\n clientErrorStatus,\n escapeRegExp,\n formatError,\n hasContentTypeMismatch,\n isClientHttpError,\n isOriginRequestAllowed,\n provideRequestContext,\n resolveRPCPrefix,\n safeURL,\n scanForServerFiles,\n} from \"@thednp/rpc/server\";\nimport { getFunctionsForPrefix } from \"../functionsMap.ts\";\nimport {\n BAD_REQUEST,\n CLIENT_DISCONNECTED,\n FUNCTION_NOT_FOUND,\n METHOD_NOT_ALLOWED,\n MIDDLEWARE_NAME_USED,\n REQUEST_FORBIDDEN,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"../constants.ts\";\n\nimport { defaultMiddlewareOptions } from \"../options.ts\";\nimport { readBody, redirect as koaRedirect } from \"./helpers.ts\";\n\nlet middlewareCount = 0;\nconst middlewareStack = new Set<string>();\n\n/**\n * Creates a Koa middleware with optional path and rpcPrefix filtering.\n * Middleware names are deduplicated. Prefix and path regexes are compiled once at creation time.\n * Koa URL is normalized via `new URL()` to strip query strings before matching.\n * @param initialOptions - Options for rpcPrefix, path matching, and the handler function\n * @returns A Koa middleware function\n */\nexport const createMiddleware: KoaMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as KoaMiddlewareOptions;\n\n const middlewareName = options.name;\n const rpcPrefix = options.rpcPrefix;\n const path = options.path;\n const handler = options.handler;\n\n let name = middlewareName;\n if (!name) {\n name = \"viteRPCMiddleware-\" + middlewareCount;\n middlewareCount += 1;\n }\n if (middlewareStack.has(name)) {\n throw new Error(MIDDLEWARE_NAME_USED(name));\n }\n middlewareStack.add(name);\n\n // Hoist regex compilation out of per-request path. Escape the prefix to\n // prevent regex injection via metacharacters in the config string.\n // Resolved once at creation time so the hoisted regex and the\n // function-map lookup can never disagree. `createRPCMiddleware` hands\n // over its already-resolved prefix, making this a no-op in that path.\n const resolvedPrefix = resolveRPCPrefix(rpcPrefix);\n // Gated only when an explicit prefix was supplied: a bare\n // `createMiddleware({ path, handler })` has never prefix-gated.\n // `createRPCMiddleware` always supplies one, so RPC dispatch does.\n const prefixRegex: RegExp | null = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(resolvedPrefix)}/`)\n : null;\n const pathMatcher: RegExp | null = path\n ? (typeof path === \"string\" ? new RegExp(path) : path)\n : null;\n\n const middlewareHandler = async (ctx: Context, next: Next) => {\n const url = safeURL(ctx.url).pathname;\n\n // No need to continue when no handler provided\n if (!handler) {\n return next();\n }\n\n if (pathMatcher && !pathMatcher.test(url)) {\n return next();\n }\n\n if (prefixRegex && !prefixRegex.test(url)) {\n return next();\n }\n\n // When serving from production server, scan for server files\n if (getFunctionsForPrefix(resolvedPrefix).size === 0) {\n await scanForServerFiles({\n rpcPrefix: resolvedPrefix,\n serverFiles: (options as unknown as { serverFiles?: \"exact\" | \"glob\" })\n .serverFiles,\n scanRoot: (options as unknown as { scanRoot?: string }).scanRoot,\n } as never);\n }\n\n await handler(ctx, next);\n };\n\n Object.defineProperty(middlewareHandler, \"name\", {\n value: name,\n });\n\n return middlewareHandler;\n};\n\n/**\n * Creates the Koa RPC middleware that routes incoming requests to registered server functions.\n * Wraps the generic createMiddleware with the RPC handler that reads the body, dispatches\n * to the matching function, and sets the JSON-serialized result on ctx.body.\n * @param initialOptions - Options including rpcPrefix for URL routing\n * @returns A Koa middleware function\n */\nexport const createRPCMiddleware: KoaMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as KoaMiddlewareOptions;\n\n // Hoist prefix regex (escaped) and the literal prefix-for-replace out of the\n // per-request handler to avoid regex injection and per-request compilation.\n const rpcPrefix = options.rpcPrefix;\n const prefix = resolveRPCPrefix(rpcPrefix);\n const prefixRegex = new RegExp(`^/${escapeRegExp(prefix)}/`);\n const prefixReplace = `/${prefix}/`;\n\n return createMiddleware({\n ...options,\n // Hand the resolved prefix down so the gate and the dispatch agree.\n rpcPrefix: prefix,\n handler: async (ctx: Context, _next: Next) => {\n const reqUrl = safeURL(ctx.url);\n const url = reqUrl.pathname;\n // const { rpcPrefix } = options;\n\n // Defense-in-depth: validate prefix match via escaped regex even though\n // the outer createMiddleware gates on the same prefix already.\n // istanbul ignore next\n if (prefixRegex && !prefixRegex.test(url)) {\n return;\n }\n\n // Optional origin check. When Origin survives, the allowlist decides;\n // when it has been stripped, Sec-Fetch-Site is consulted instead and\n // fails closed. See `isOriginRequestAllowed` for the four tiers.\n if (\n !isOriginRequestAllowed(\n options.origin,\n ctx.headers.origin,\n ctx.headers[\"sec-fetch-site\"],\n )\n ) {\n ctx.status = 403;\n ctx.body = { error: REQUEST_FORBIDDEN };\n return;\n }\n\n const functionName = url.replace(prefixReplace, \"\");\n const serverFunction = getFunctionsForPrefix(prefix).get(functionName);\n\n if (!serverFunction) {\n ctx.status = 404;\n ctx.body = { error: FUNCTION_NOT_FOUND };\n return;\n }\n\n try {\n const method = serverFunction.options?.method || \"POST\";\n if (ctx.method.toUpperCase() !== method) {\n ctx.status = 405;\n ctx.body = { error: METHOD_NOT_ALLOWED };\n return;\n }\n\n let args: JsonValue[] = [];\n if (method === \"GET\") {\n const raw = reqUrl.searchParams.get(\"args\");\n if (raw) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // A malformed `?args=` is a malformed request, not a server\n // fault, so it answers 400 like the non-array case above.\n ctx.status = 400;\n ctx.body = { error: BAD_REQUEST };\n return;\n }\n if (!Array.isArray(parsed)) {\n ctx.status = 400;\n ctx.body = { error: BAD_REQUEST };\n return;\n }\n args = parsed as JsonValue[];\n }\n } else {\n // Content-type enforcement: strict for json/text, lenient between forms.\n // Requests without a Content-Type header are exempt (curl/GET compat).\n // Checked BEFORE readBody so mismatched bodies are never buffered.\n if (\n hasContentTypeMismatch(\n serverFunction.options?.contentType ?? \"application/json\",\n ctx.headers[\"content-type\"],\n )\n ) {\n ctx.status = 415;\n ctx.body = { error: UNSUPPORTED_MEDIA_TYPE };\n return;\n }\n const body = await readBody(ctx);\n args = Array.isArray(body.data)\n ? body.data as JsonValue[]\n : [body.data as JsonValue];\n }\n const requestEvent: RequestEvent = {\n request: ctx.req,\n response: ctx,\n nativeEvent: ctx,\n locals: ctx.state,\n functionName,\n redirect: (location, status = 303) => {\n requestEvent.redirected = { location, status };\n koaRedirect(ctx, location, status);\n },\n send: (status, body, headers) => {\n requestEvent.sent = { status, body, headers };\n if (headers) {\n for (const [name, value] of Object.entries(headers)) {\n ctx.set(name, value);\n }\n }\n ctx.status = status;\n ctx.body = body;\n },\n };\n const { data: resultData, cancel } = provideRequestContext(\n requestEvent,\n () => serverFunction.handler(...args),\n );\n const onClose = () => cancel(CLIENT_DISCONNECTED);\n ctx.req.on(\"close\", onClose);\n const result = await resultData;\n ctx.req.off(\"close\", onClose);\n\n // Skip the JSON send when the server function issued a redirect or\n // short-circuited with `send`; the bound Koa adapter already set\n // ctx.status/ctx.body.\n // istanbul ignore else\n if (!requestEvent.redirected && !requestEvent.sent) {\n ctx.status = 200;\n ctx.body = { data: result };\n }\n } catch (err) {\n // A malformed request is a client error, not a server fault. rpc raises\n // these with a status (see `httpError`), and host frameworks signal the\n // same class the same way — h3's body limit throws 413 from inside the\n // read, Express's body-parser throws 400, and Fastify's parser does the\n // same before rpc is reached. Answering 500 for any of them both\n // misreports the fault and turns a trivial client mistake into a log\n // entry. The body comes from a fixed table, so nothing from the\n // underlying error is echoed back.\n if (isClientHttpError(err)) {\n const status = clientErrorStatus(err);\n ctx.status = status;\n ctx.body = { error: clientErrorMessage(status) };\n return;\n }\n console.error(String(err));\n const isProduction = process.env.NODE_ENV === \"production\";\n ctx.status = 500;\n ctx.body = formatError(err, isProduction);\n }\n },\n });\n};\n"],"mappings":";;;;;;;;AAwCA,MAAa,2BAA8C;CACzD,WAAW,KAAA;CACX,MAA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b,IAAI,OAAO,EAAE,MAAM,OAAO;IAC5B;GACF,SAAS,KAAK;IASZ,IAAI,kBAAkB,GAAG,GAAG;KAC1B,MAAM,SAAS,kBAAkB,GAAG;KACpC,IAAI,SAAS;KACb,IAAI,OAAO,EAAE,OAAO,mBAAmB,MAAM,EAAE;KAC/C;IACF;IACA,QAAQ,MAAM,OAAO,GAAG,CAAC;IACzB,MAAM,eAAe,QAAQ,IAAI,aAAa;IAC9C,IAAI,SAAS;IACb,IAAI,OAAO,YAAY,KAAK,YAAY;GAC1C;EACF;CACF,CAAC;AACH"}
@@ -74,6 +74,17 @@ interface H3MiddlewareHooks {
74
74
  }
75
75
  //#endregion
76
76
  //#region src/types.d.ts
77
+ /**
78
+ * Every framework adapter rpc ships a middleware for.
79
+ *
80
+ * This is the key type for {@link FrameworkHooks}, so `MiddlewareOptions<A>`
81
+ * can type each adapter's `handler` signature. It is a *type* only — the
82
+ * adapter you get is the one you import (`@thednp/rpc/express`,
83
+ * `@thednp/rpc/hono`, …). There is deliberately no config option that selects
84
+ * it: a runtime value could only ever disagree with the subpath actually
85
+ * mounted, and nothing read it.
86
+ */
87
+ type AdapterName = "express" | "hono" | "h3" | "fastify" | "koa";
77
88
  /**
78
89
  * Maps each supported framework adapter to its middleware hooks (handler signatures).
79
90
  * Used to keep the middleware options type-safe per adapter.
@@ -173,12 +184,13 @@ type ClientFunctionWithOptions = ClientFunction & {
173
184
  };
174
185
  /**
175
186
  * Internal plugin options accepted by `getClientModules`.
187
+ *
188
+ * Only the prefix: the generated stubs are adapter-agnostic, since they are
189
+ * plain `fetch` calls.
176
190
  */
177
191
  interface RpcPluginOptionsInternal {
178
192
  /** RPC endpoint prefix (e.g. "__rpc") */
179
193
  rpcPrefix: string;
180
- /** Framework adapter name */
181
- adapter?: string | undefined;
182
194
  }
183
195
  /**
184
196
  * Partial Vite config used when scanning server files outside a running dev server.
@@ -223,13 +235,6 @@ interface RpcPluginOptions {
223
235
  * rpcPrefix: "api/rpc"
224
236
  */
225
237
  rpcPrefix: "__rpc" | string;
226
- /**
227
- * Option to set an adapter for the middleware connection. The default is _express_,
228
- * which is the most popular and battle tested server app. The _express_ adapter is
229
- * also compatible with the vite's Connect development server.
230
- * @default express
231
- */
232
- adapter: "express" | "hono" | "h3" | "fastify" | "koa";
233
238
  /**
234
239
  * Root directory from which the plugin scans for server files.
235
240
  * Defaults to `<root>/src/api`. Use this in monorepos where server files
@@ -252,7 +257,7 @@ interface RpcPluginOptions {
252
257
  */
253
258
  silent?: boolean;
254
259
  }
255
- interface MiddlewareOptions<A extends RpcPluginOptions["adapter"] = "express"> {
260
+ interface MiddlewareOptions<A extends AdapterName = "express"> {
256
261
  /**
257
262
  * Name for the middleware (used for identification in Express stack)
258
263
  */
@@ -278,19 +283,30 @@ interface MiddlewareOptions<A extends RpcPluginOptions["adapter"] = "express"> {
278
283
  * // Results in endpoints like: /api/rpc/myFunction
279
284
  * rpcPrefix: "api/rpc"
280
285
  */
281
- rpcPrefix?: string | false;
286
+ rpcPrefix?: string;
282
287
  /**
283
288
  * Allowed request origin(s) — a single origin string or an allowlist of them
284
289
  * (e.g. `"https://example.com"` or
285
290
  * `["https://example.com", "https://admin.example.com"]`).
286
291
  *
287
- * When set, any request carrying an `Origin` header that matches none of the
288
- * entries is rejected with a 403 Forbidden response. Requests without an
289
- * `Origin` header (curl, native clients) pass through unchecked.
290
- * When unset (default), no origin validation is performed.
292
+ * Setting this option is the opt-in for origin validation. When set, a request
293
+ * is rejected with `403 Forbidden` according to four tiers:
294
+ *
295
+ * 1. `Origin` present → the allowlist decides. It must match one of the
296
+ * entries exactly; `Origin: null` (sandboxed iframes, `file://`, browser
297
+ * extensions) never equals a real origin, so it is rejected.
298
+ * 2. `Origin` absent but `Sec-Fetch-Site` present → allow only `same-origin`
299
+ * and `none`. Anything else, including an unrecognised value, is rejected.
300
+ * Browsers never strip `Origin` themselves, so reaching this tier means
301
+ * something in the chain (a proxy, a sanitising middleware, a CDN) removed
302
+ * it — at which point the check fails closed rather than silently becoming
303
+ * a no-op.
304
+ * 3. Both headers absent → the request passes. This is the deliberate
305
+ * curl/native-client hole: non-browser clients send neither header.
291
306
  *
292
- * `Origin: null` (sandboxed iframes, `file://`, extension pages) never
293
- * equals a real origin, so it is rejected whenever an allowlist is set.
307
+ * When unset (default), no origin validation is performed at all.
308
+ *
309
+ * @see `isOriginRequestAllowed` in `@thednp/rpc/server` for the exact rule.
294
310
  */
295
311
  origin?: string | string[];
296
312
  /**
@@ -405,7 +421,10 @@ export declare function createServerFunction<TArgs extends JsonArray = JsonArray
405
421
  * Generates the complete client-side module bundle by iterating all registered server functions
406
422
  * for a specific prefix and producing fetch-based stubs for each. The result is transformed by Vite
407
423
  * (or Oxc) during the dev server or production build.
408
- * @param initialOptions - Plugin options containing rpcPrefix and optional adapter
424
+ *
425
+ * The generated stubs are plain `fetch` calls, so they are adapter-agnostic —
426
+ * only the prefix is needed.
427
+ * @param initialOptions - Plugin options containing the rpcPrefix
409
428
  * @returns A string of JavaScript code with all client RPC modules and their import dependencies
410
429
  */
411
430
  export declare const getClientModules: (initialOptions: RpcPluginOptionsInternal) => string;
@@ -443,6 +462,46 @@ export declare const formatError: (err: unknown, isProduction: boolean) => JsonO
443
462
  * Form-declared functions accept either encoding so native browser
444
463
  * submissions (urlencoded) keep working without JavaScript.
445
464
  */
465
+ /**
466
+ * An error carrying an HTTP status, so the dispatch can answer that status
467
+ * instead of flattening every failure to a `500`.
468
+ */
469
+ export interface ClientHttpError extends Error {
470
+ status?: number;
471
+ statusCode?: number;
472
+ }
473
+ /**
474
+ * Tags an error with an HTTP status for the dispatch to surface.
475
+ *
476
+ * Used where a malformed *request* is the fault — a body that does not parse
477
+ * under a declared JSON `Content-Type`, a GET `?args=` value that is not valid
478
+ * JSON. Every host framework rpc supports answers `400` for these (Express
479
+ * `entity.parse.failed`, Fastify `FST_ERR_CTP_INVALID_JSON_BODY`, koa-bodyparser,
480
+ * and h3's own `readBody`), and treating one as a server fault both misreports
481
+ * the fault and turns a trivial client mistake into a log entry.
482
+ * @param status - The HTTP status to answer with
483
+ * @param message - Internal diagnostic message; never sent to the client
484
+ * @returns An `Error` carrying `status`
485
+ */
486
+ export declare const httpError: (status: number, message: string) => ClientHttpError;
487
+ /**
488
+ * Recognises an error that should produce a `4xx` response rather than a `500`.
489
+ * Matches the `status` / `statusCode` convention used by h3's `HTTPError`, the
490
+ * `http-errors` objects Express's `body-parser` throws, and anything else
491
+ * carrying a numeric 4xx. Shared by all five adapters so a host-framework
492
+ * signal and an rpc-raised one are handled by the same rule.
493
+ * @param err - The caught error
494
+ * @returns True when the error denotes a client (4xx) fault
495
+ */
496
+ export declare const isClientHttpError: (err: unknown) => boolean;
497
+ /**
498
+ * Reads the status to answer for a client error. Defaults to `400` rather than
499
+ * `500` so an unrecognised 4xx is never reported as a server fault.
500
+ * @param err - The caught error
501
+ * @returns The 4xx status to answer with
502
+ */
503
+ export declare const clientErrorStatus: (err: unknown) => number;
504
+ export declare const clientErrorMessage: (status: number) => string;
446
505
  export declare const isFormContentType: (contentType: string) => boolean;
447
506
  /**
448
507
  * Detects whether an incoming request's `Content-Type` header conflicts
@@ -455,6 +514,42 @@ export declare const isFormContentType: (contentType: string) => boolean;
455
514
  * @param rawHeader - The raw `Content-Type` request header, if present
456
515
  */
457
516
  export declare const hasContentTypeMismatch: (declared: ContentType, rawHeader: string | undefined) => boolean;
517
+ /**
518
+ * Decides whether a request may proceed, given the configured origin allowlist
519
+ * and the two headers a browser can be made to reveal.
520
+ *
521
+ * Four tiers, evaluated in order — the first tier with a signal decides:
522
+ *
523
+ * 1. `origin` option unset → everything passes. No validation is performed.
524
+ * 2. `Origin` present → the allowlist decides, exactly as {@link isOriginAllowed}.
525
+ * 3. `Origin` absent but `Sec-Fetch-Site` present → allow only `same-origin`
526
+ * and `none`; anything else (including an unrecognised value) is rejected.
527
+ * 4. Both absent → passes. This is the deliberate, documented curl/native hole.
528
+ *
529
+ * Tier 2 must short-circuit ahead of tier 3. `Sec-Fetch-Site` is a coarse
530
+ * four-value enum that cannot name a host, so on its own it would reject a
531
+ * legitimate request from an allowlisted sibling subdomain (`same-site`). The
532
+ * allowlist exists precisely to admit that case, and it can only do so while
533
+ * `Origin` survives. `Sec-Fetch-Site` earns a vote only once the precise signal
534
+ * has been stripped away by something in the chain — at which point there is
535
+ * nothing left to trust, so it fails closed.
536
+ *
537
+ * Browsers never strip `Origin` themselves, so tier 3 can only fire when a
538
+ * proxy, sanitising middleware, or misconfigured CDN removed it. No legitimate
539
+ * browser request can regress.
540
+ *
541
+ * An empty (or whitespace-only) header value counts as **absent**, not as an
542
+ * unrecognised signal. No browser emits an empty `Sec-Fetch-Site`, and adapters
543
+ * disagree on what their header accessor returns for a missing header (Node's
544
+ * `req.headers` yields `undefined`, Hono's `c.req.header()` may yield `""`).
545
+ * Normalising here keeps all five adapters behaving identically instead of
546
+ * inheriting whichever convention their framework happens to use.
547
+ * @param allowed - The configured `origin` option, if any
548
+ * @param origin - The raw `Origin` request header, if present
549
+ * @param site - The raw `Sec-Fetch-Site` request header, if present
550
+ * @returns `true` when the request may proceed
551
+ */
552
+ export declare const isOriginRequestAllowed: (allowed: string | string[] | undefined, origin: string | undefined, site: string | undefined) => boolean;
458
553
  /**
459
554
  * Escapes special regex metacharacters in a string.
460
555
  * Used to safely embed user-configurable values (like rpcPrefix) into regular expressions,
@@ -497,7 +592,33 @@ export declare const isOriginAllowed: (allowed: string | string[] | undefined, r
497
592
  export declare const safeURL: (rawUrl: string, base?: string) => URL;
498
593
  /** Global rpcPrefix from the last loaded config / middleware — fallback for functions without explicit prefix. */
499
594
  export declare const getGlobalPrefix: () => string | undefined;
595
+ /**
596
+ * Publishes the global RPC prefix, consulted by `resolveRPCPrefix` whenever no
597
+ * explicit prefix is supplied. `loadRPCConfig` calls this on every return path
598
+ * so a loaded config is the fallback for later registrations and dispatches.
599
+ *
600
+ * Stored on a `Symbol.for` key on `globalThis` so it stays instance-stable
601
+ * across the bundled entry copies (`server.mjs`, `express.mjs`, ...) and dev
602
+ * server hot reloads — the same technique as the request-context storage.
603
+ * @param prefix - The prefix to publish, or `undefined` to clear it
604
+ */
500
605
  export declare const setGlobalPrefix: (prefix: string | undefined) => void;
606
+ /**
607
+ * Resolves the effective RPC prefix: the explicit one when given, otherwise
608
+ * the global prefix set by `setGlobalPrefix` / `loadRPCConfig`, otherwise the
609
+ * built-in default.
610
+ *
611
+ * Every adapter resolves its prefix through this single function — in both the
612
+ * outer `createMiddleware` gate and the `createRPCMiddleware` dispatch — so the
613
+ * two halves of a request can never disagree, and so a prefix registered by
614
+ * `createServerFunction` (which resolves the same way) is always the prefix the
615
+ * middleware looks up. Resolving the two sides independently is what allowed
616
+ * h3 to drift from the other four adapters, and what left the documented
617
+ * global-prefix flow returning 404 on all of them.
618
+ * @param rpcPrefix - Explicit prefix from config or middleware options
619
+ * @returns The prefix to gate on, look up in, and strip from the request path
620
+ */
621
+ export declare const resolveRPCPrefix: (rpcPrefix?: string) => string;
501
622
  //#endregion
502
623
  //#region src/context.d.ts
503
624
  /**
@@ -635,9 +756,29 @@ export interface RequestMeta {
635
756
  export declare const getRequestMeta: (event: RequestEvent) => RequestMeta;
636
757
  //#endregion
637
758
  //#region src/options.d.ts
759
+ /**
760
+ * Defaults applied to a server function that declares no `method`,
761
+ * `credentials`, or `contentType` of its own.
762
+ */
638
763
  export declare const defaultServerFnOptions: ServerFunctionOptions;
764
+ /**
765
+ * The built-in RPC endpoint prefix, used when neither an explicit prefix nor a
766
+ * global one (`getGlobalPrefix`) is supplied. Kept for backward compatibility
767
+ * with pre-multi-prefix setups, where every function lived under this one map.
768
+ */
639
769
  export declare const defaultPrefix = "__rpc";
770
+ /**
771
+ * Baseline plugin options. `defineConfig` merges a user's partial config over
772
+ * these, and `loadRPCConfig` merges a loaded config file over them, so every
773
+ * option has a defined value even when a config file omits it.
774
+ */
640
775
  export declare const defaultRPCOptions: RpcPluginOptions;
776
+ /**
777
+ * Baseline middleware options. Note `rpcPrefix` is `undefined` rather than
778
+ * `defaultPrefix` on purpose: leaving it unset lets `resolveRPCPrefix` fall
779
+ * through to the global prefix, which is what makes a published global prefix
780
+ * reach the middleware.
781
+ */
641
782
  export declare const defaultMiddlewareOptions: MiddlewareOptions;
642
783
  //#endregion
643
784
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":["Response"],"sources":["../../src/express/types.d.ts","../../src/hono/types.d.ts","../../src/fastify/types.d.ts","../../src/koa/types.d.ts","../../src/h3/types.d.ts","../../src/types.d.ts","../../src/functionsMap.ts","../../src/scanForServerFiles.ts","../../src/createFunction.ts","../../src/getClientModules.ts","../../src/server-helpers.ts","../../src/context.ts","../../src/options.ts"],"mappings":";;;;;;;;;;;;;;;;UA+BiB;;;;;;;EAOf,UACE,KAAK,kBAAkB,SACvB,KAAK,iBAAiBA,YACtB,MAAM,QAAQ,eAAe,iBAC1B;;;;;;;UCzBU;;EAEf,SAAS;;;;;;;UCmCM;;;;;;;EAOf,UACE,KAAK,gBACL,KAAK,cACL,MAAM,4BACH;;;;;;;UCzCU;;;;;;EAMf,UAAU,KAAK,SAAS,MAAM,SAAS;;;;;;;UClBxB;;;;;;EAMf,SAAS;;;;;;;;UCKM;;EAEf,SAAS;;EAET,MAAM;;EAEN,SAAS;;EAET,KAAK;;EAEL,IAAI;;;;;KAiCM;;;;KASA;;;;;UAkBK;;;;;EAKf,aAAa;;;;;EAKb,cAAc;;;;;;;EAOd;;;;;EAKA;;;;;;KAOU;;;;KAIA;GAAgB,cAAc,YAAY;;;;;KAI1C,aAAa,WAAW;;;;KAIxB,YAAY,gBAAgB,YAAY;;;;;KAsCxC,mBACV,cAAc,WAAW,YAAY,WACrC,UAAU,cACP,QAAQ,gBAAgB,MAAM,UAAU,QAAQ;;;;;;KAOzC,eACV,cAAc,YAAY,WAC1B,UAAU,iBACJ,MAAM;;EAEZ,MAAM,QAAQ;;EAEd,SAAS;;;;;;KAOC,4BAA4B;;EAEtC;;EAEA,UAA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;;;;;;EAUjC,OACE,gBACA,MAAM,WACN,UAAU;;;;;EAMZ;IAAS;IAAgB,MAAM;IAAW,UAAU;;;;;;EAKpD;;EAEA,QAAQ;GACP;;;;;;;;;qBAiBU,wBAAyB,GAAC,MAC/B,cAAY,UACR,MACT;;;;;;qBAOU,yBAAwB;;;;;;;;;qBAgBxB,WAAQ,kBAAoB;;;;;;;;;;;;qBAe5B,eAAY,gBACT,MACR,WAAS,UACL;;;;;;;iBAWK;;EAEf;;EAEA;;EAEA;;EAEA,cAAc;;EAEd,SAAS;;EAET;;EAEA;;EAEA;;;;;;;;;;qBAsCW,iBAAc,OAAW,iBAAe;;;qBCnMxC,wBAAwB;qBAMxB;qBAEA,mBAAmB;qBAOnB,0BAA0B"}
1
+ {"version":3,"file":"server.d.mts","names":["Response"],"sources":["../../src/express/types.d.ts","../../src/hono/types.d.ts","../../src/fastify/types.d.ts","../../src/koa/types.d.ts","../../src/h3/types.d.ts","../../src/types.d.ts","../../src/functionsMap.ts","../../src/scanForServerFiles.ts","../../src/createFunction.ts","../../src/getClientModules.ts","../../src/server-helpers.ts","../../src/context.ts","../../src/options.ts"],"mappings":";;;;;;;;;;;;;;;;UA+BiB;;;;;;;EAOf,UACE,KAAK,kBAAkB,SACvB,KAAK,iBAAiBA,YACtB,MAAM,QAAQ,eAAe,iBAC1B;;;;;;;UCzBU;;EAEf,SAAS;;;;;;;UCmCM;;;;;;;EAOf,UACE,KAAK,gBACL,KAAK,cACL,MAAM,4BACH;;;;;;;UC5CU;;;;;;EAMf,UAAU,KAAK,SAAS,MAAM,SAAS;;;;;;;UCfxB;;;;;;EAMf,SAAS;;;;;;;;;;;;;;KCWC;;;;;UAMK;;EAEf,SAAS;;EAET,MAAM;;EAEN,SAAS;;EAET,KAAK;;EAEL,IAAI;;;;;KAiCM;;;;KASA;;;;;UAkBK;;;;;EAKf,aAAa;;;;;EAKb,cAAc;;;;;;;EAOd;;;;;EAKA;;;;;;KAOU;;;;KAIA;GAAgB,cAAc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