@thednp/rpc 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +33 -19
- package/CHANGELOG.md +38 -0
- package/README.md +22 -9
- package/dist/express/express.d.mts +4 -2
- package/dist/express/express.d.mts.map +1 -1
- package/dist/express/express.mjs +41 -8
- package/dist/express/express.mjs.map +1 -1
- package/dist/fastify/fastify.d.mts.map +1 -1
- package/dist/fastify/fastify.mjs +37 -6
- package/dist/fastify/fastify.mjs.map +1 -1
- package/dist/fastify/plugin/fastify/plugin.d.mts +13 -0
- package/dist/fastify/plugin/fastify/plugin.d.mts.map +1 -1
- package/dist/fastify/plugin/fastify/plugin.mjs +37 -6
- package/dist/fastify/plugin/fastify/plugin.mjs.map +1 -1
- package/dist/h3/h3.d.mts.map +1 -1
- package/dist/h3/h3.mjs +47 -16
- package/dist/h3/h3.mjs.map +1 -1
- package/dist/helpers/helpers.d.mts +63 -5
- package/dist/helpers/helpers.d.mts.map +1 -1
- package/dist/helpers/helpers.mjs +58 -1
- package/dist/helpers/helpers.mjs.map +1 -1
- package/dist/hono/hono.d.mts.map +1 -1
- package/dist/hono/hono.mjs +37 -6
- package/dist/hono/hono.mjs.map +1 -1
- package/dist/index.d.mts +48 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +84 -50
- package/dist/index.mjs.map +1 -1
- package/dist/koa/koa.d.mts.map +1 -1
- package/dist/koa/koa.mjs +47 -16
- package/dist/koa/koa.mjs.map +1 -1
- package/dist/server/server.d.mts +219 -26
- package/dist/server/server.d.mts.map +1 -1
- package/dist/server/server.mjs +101 -68
- package/dist/server/server.mjs.map +1 -1
- package/package.json +20 -18
package/dist/index.d.mts
CHANGED
|
@@ -197,6 +197,11 @@ interface ServerFunctionOptions {
|
|
|
197
197
|
* @default "POST"
|
|
198
198
|
*/
|
|
199
199
|
method?: "GET" | "POST";
|
|
200
|
+
/**
|
|
201
|
+
* RPC endpoint prefix
|
|
202
|
+
* @default "__rpc"
|
|
203
|
+
*/
|
|
204
|
+
rpcPrefix?: string;
|
|
200
205
|
}
|
|
201
206
|
// primitives and their compositions
|
|
202
207
|
/**
|
|
@@ -279,12 +284,14 @@ interface RpcPluginOptionsInternal {
|
|
|
279
284
|
/**
|
|
280
285
|
* Partial Vite config used when scanning server files outside a running dev server.
|
|
281
286
|
*/
|
|
282
|
-
|
|
287
|
+
interface ScanConfig extends Pick<ResolvedConfig, "base"> {
|
|
283
288
|
root?: string;
|
|
284
289
|
server?: Partial<ResolvedConfig["server"]>;
|
|
285
290
|
serverFiles?: "exact" | "glob";
|
|
286
291
|
scanRoot?: string;
|
|
287
|
-
|
|
292
|
+
/** Default rpcPrefix to register scanned functions under when a function does not declare its own. Defaults to `__rpc` for backward compatibility. */
|
|
293
|
+
rpcPrefix?: string;
|
|
294
|
+
}
|
|
288
295
|
/**
|
|
289
296
|
* Entry in the server functions map: registered name, client handler,
|
|
290
297
|
* optional per-function options, and the original export name.
|
|
@@ -374,6 +381,19 @@ interface MiddlewareOptions<A extends RpcPluginOptions["adapter"] = "express"> {
|
|
|
374
381
|
* When unset (default), no origin validation is performed.
|
|
375
382
|
*/
|
|
376
383
|
origin?: string;
|
|
384
|
+
/**
|
|
385
|
+
* Server file matching mode. Use `"exact"` for `server.ts|js|mjs|mts`
|
|
386
|
+
* names, or `"glob"` to match `**\/*.server.{ts,js,mjs,mts}` inside the
|
|
387
|
+
* scan root. Only used for the lazy production scan when the middleware
|
|
388
|
+
* populates its prefix map on first request.
|
|
389
|
+
* @default "exact"
|
|
390
|
+
*/
|
|
391
|
+
serverFiles?: "exact" | "glob";
|
|
392
|
+
/**
|
|
393
|
+
* Root directory for scanning server files. Defaults to `<root>/src/api`.
|
|
394
|
+
* Only used for the lazy production scan.
|
|
395
|
+
*/
|
|
396
|
+
scanRoot?: string;
|
|
377
397
|
/**
|
|
378
398
|
* Async handler for request processing.
|
|
379
399
|
* Core middleware function that processes incoming requests.
|
|
@@ -393,13 +413,36 @@ interface MiddlewareOptions<A extends RpcPluginOptions["adapter"] = "express"> {
|
|
|
393
413
|
*/
|
|
394
414
|
handler?: FrameworkHooks[A]["handler"];
|
|
395
415
|
}
|
|
416
|
+
/**
|
|
417
|
+
* Options for a manual client stub created via `getClientStub`.
|
|
418
|
+
* Mirrors `ServerFunctionOptions` but client-only.
|
|
419
|
+
*/
|
|
420
|
+
interface StubOptions {
|
|
421
|
+
/**
|
|
422
|
+
* HTTP method for the stub.
|
|
423
|
+
* @default "POST"
|
|
424
|
+
*/
|
|
425
|
+
method: "GET" | "POST";
|
|
426
|
+
/**
|
|
427
|
+
* Fetch credentials policy.
|
|
428
|
+
* @default "same-origin"
|
|
429
|
+
*/
|
|
430
|
+
credentials: Credentials;
|
|
431
|
+
/**
|
|
432
|
+
* Content type for the request body. Only `"application/json"` is used for
|
|
433
|
+
* most stubs; other values are for `text/plain`, `application/x-www-form-urlencoded`,
|
|
434
|
+
* and `multipart/form-data` handlers.
|
|
435
|
+
* @default "application/json"
|
|
436
|
+
*/
|
|
437
|
+
contentType: ContentType;
|
|
438
|
+
}
|
|
396
439
|
/**
|
|
397
440
|
* Return shape of `innerModule`: a promise of the response data plus
|
|
398
441
|
* a `cancel` function to abort the underlying fetch request.
|
|
399
442
|
*/
|
|
400
|
-
type InnerModReturn = {
|
|
443
|
+
type InnerModReturn<T extends JsonValue> = {
|
|
401
444
|
/** Promise resolving to the server response data */
|
|
402
|
-
data: Promise<
|
|
445
|
+
data: Promise<T | void>;
|
|
403
446
|
/** Aborts the in-flight request with the given reason */
|
|
404
447
|
cancel: (reason: string) => void;
|
|
405
448
|
};
|
|
@@ -429,5 +472,5 @@ declare const loadRPCConfig: (f?: string) => Promise<RpcPluginOptions>;
|
|
|
429
472
|
*/
|
|
430
473
|
declare function rpcPlugin(devOptions?: Partial<RpcPluginOptions>): Plugin;
|
|
431
474
|
//#endregion
|
|
432
|
-
export { type BodyResult, type ClientFunction, type ClientFunctionWithOptions, type ContentType, type Credentials, type FrameworkHooks, type FrameworkMiddlewareFn, type InnerModReturn, type JsonArray, type JsonObject, type JsonPrimitive, type JsonValue, type MiddlewareOptions, type RpcPluginOptions, type RpcPluginOptionsInternal, type ScanConfig, type ServerFnArgs, type ServerFnEntry, type ServerFunction, type ServerFunctionInit, type ServerFunctionOptions, type SupportableContentType, rpcPlugin as default, defineConfig, loadRPCConfig };
|
|
475
|
+
export { type BodyResult, type ClientFunction, type ClientFunctionWithOptions, type ContentType, type Credentials, type FrameworkHooks, type FrameworkMiddlewareFn, type InnerModReturn, type JsonArray, type JsonObject, type JsonPrimitive, type JsonValue, type MiddlewareOptions, type RpcPluginOptions, type RpcPluginOptionsInternal, type ScanConfig, type ServerFnArgs, type ServerFnEntry, type ServerFunction, type ServerFunctionInit, type ServerFunctionOptions, type StubOptions, type SupportableContentType, rpcPlugin as default, defineConfig, loadRPCConfig };
|
|
433
476
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"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/index.ts"],"mappings":";;;;;;;;;;;;;;;;KAgBY,2BAA2B;;;;;KAM3B,uBACV,UAAU,2CAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,kBAAkB,SACvB,KAAK,iBAAiB,YACtB,MAAM,QAAQ,eAAe,iBAC1B;;;;;;;UCzBU;;EAEf,SAAS;;;;;;KAOC,oBAAoB,UAAU,wCACxC,iBAAiB,QAAQ,oBAAkB,QACxC;;;;;;KCWO,2BAA2B;;;;;KAM3B,uBACV,UAAU,2CAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,gBACL,KAAK,cACL,MAAM,4BACH;;;;;;;KCtDK,uBAAuB;;;;UAalB;;;;;;EAMf,UAAU,KAAK,SAAS,MAAM,SAAS;;;;;;KAO7B,mBAAmB,UAAU,uCACvC,iBAAiB,QAAQ,0BACtB;;;;;;KChCO,sBAAsB;;;;UAKjB;;;;;;EAMf,SAAS;;;;;;KAOC,kBAAkB,UAAU,sCACtC,iBAAiB,QAAQ,yBACtB;;;;;;;UCJY;;EAEf,SAAS;;EAET,MAAM;;EAEN,SAAS;;EAET,KAAK;;EAEL,IAAI;;;;;UAMW;;EAEf,SAAS;;EAET,MAAM;;EAEN,SAAS;;EAET,KAAK;;EAEL,IAAI;;;;;;KAOM;;;;KAUA;;;;KASA;;;;KAKA;EACN;EAAiC,MAAM;;EACvC;EAA2B;;EAE7B;EACA,MAAM;;EAEJ;EAAoC,MAAM;;;;;;UAM/B;;;;;EAKf,aAAa;;;;;EAKb,cAAc;;;;;;;EAOd;;;;;;KAOU;;;;KAIA;GAAgB,cAAc,YAAY;;;;;KAI1C,aAAa,WAAW;;;;KAIxB,YAAY,gBAAgB,YAAY;;;;;;;;;;;;;;;;;;;KAuBxC,mBAAmB;;;;;KAMnB,eACV,cAAc,YAAY,WAC1B,gBAAgB,YAAY,cACzB,QAAQ,gBAAgB,MAAM,UAAU,QAAQ;;;;;KAMzC,mBACV,cAAc,WAAW,YAAY,WACrC,gBAAgB,YAAY,cACzB,QAAQ,gBAAgB,MAAM,UAAU,QAAQ;;;;;;KAOzC,eACV,cAAc,YAAY,WAC1B,gBAAgB,YAAY,iBACtB,MAAM;;EAEZ,MAAM,QAAQ;;EAEd,SAAS;;;;;;KAOC,4BAA4B;;EAEtC;;EAEA,UAAU;;;;;UAMK;;EAEf;;EAEA;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"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/index.ts"],"mappings":";;;;;;;;;;;;;;;;KAgBY,2BAA2B;;;;;K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zB,QAAQ,gBAAgB,MAAM,UAAU,QAAQ;;;;;;KAOzC,eACV,cAAc,YAAY,WAC1B,gBAAgB,YAAY,iBACtB,MAAM;;EAEZ,MAAM,QAAQ;;EAEd,SAAS;;;;;;KAOC,4BAA4B;;EAEtC;;EAEA,UAAU;;;;;UAMK;;EAEf;;EAEA;;;;;UAMe,mBAAmB,KAAK;EACvC;EACA,SAAS,QAAQ;EACjB;EACA;;EAEA;;;;;;UAOe;;EAEf;;EAEA,SAAS;;EAET,UAAU;;EAEV;;;;;;;;UASe;;;;;;;;;;;EAWf;;;;;;;EAQA;;;;;;;EAQA;;;;;;;EAQA;;UAGe,kBACf,UAAU;;;;EAKV;;;;;;;;;;;;EAaA,gBAAgB;;;;;;;;;;EAWhB;;;;;;;;EASA;;;;;;;;EASA;;;;;EAMA;;;;;;;;;;;;;;;;;;EAmBA,UAAU,eAAe;;;;;;UAOV;;;;;EAKf;;;;;EAKA,aAAa;;;;;;;EAOb,aAAa;;;;;;KAOH,eAAe,UAAU;;EAEnC,MAAM,QAAQ;;EAEd,SAAS;;;;;;;;;;cCxVL,eAAe,GAAG,QAAQ,sBAAsB;;;;;;;;cAehD,gBAAgB,eAAe,QAAQ;;;;;;;;iBAkGpC,UACP,aAAY,QAAQ,oBACnB"}
|
package/dist/index.mjs
CHANGED
|
@@ -3,10 +3,12 @@ import { join, resolve } from "node:path";
|
|
|
3
3
|
import process from "node:process";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
5
|
import { readdir } from "node:fs/promises";
|
|
6
|
+
import { setGlobalPrefix } from "@thednp/rpc/server";
|
|
6
7
|
import { createRPCMiddleware } from "@thednp/rpc/express";
|
|
7
8
|
//#region src/options.ts
|
|
9
|
+
const defaultPrefix = "__rpc";
|
|
8
10
|
const defaultRPCOptions = {
|
|
9
|
-
rpcPrefix:
|
|
11
|
+
rpcPrefix: defaultPrefix,
|
|
10
12
|
adapter: "express",
|
|
11
13
|
serverFiles: "exact",
|
|
12
14
|
scanRoot: void 0
|
|
@@ -18,7 +20,7 @@ const ERROR_LOADING_FILE = "Error loading file:";
|
|
|
18
20
|
/** Error message when a value fails the safe-identifier validation. @param label - What kind of value was being validated. @param name - The rejected value */
|
|
19
21
|
const INVALID_IDENTIFIER = (label, name) => `Invalid ${label}: "${name}" must match /^[A-Za-z_$][A-Za-z0-9_$]*$/`;
|
|
20
22
|
/** 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 */
|
|
21
|
-
const INVALID_PATH_SEGMENT = (label, segment) => `Invalid ${label}: "${segment}" must match /^[A-Za-z0-9_
|
|
23
|
+
const INVALID_PATH_SEGMENT = (label, segment) => `Invalid ${label}: "${segment}" must match /^[A-Za-z0-9_$@:][A-Za-z0-9_$@:/-]*$/`;
|
|
22
24
|
/** 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 */
|
|
23
25
|
const CONFIG_FILE_NOT_FOUND = (configFile, configFilePath) => ` ⚠︎ The specified RPC config file ${configFile} cannot be found at ${configFilePath}, loading the defaults..`;
|
|
24
26
|
const NO_CONFIG_FOUND = ` ⚡︎ No RPC config found, loading the defaults..`;
|
|
@@ -27,11 +29,53 @@ const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;
|
|
|
27
29
|
const DUPLICATE_FUNCTION_NAME = (name) => `Duplicate server function "${name}" detected. Each server function must have a unique name. Remove or rename the duplicate.`;
|
|
28
30
|
//#endregion
|
|
29
31
|
//#region src/functionsMap.ts
|
|
30
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Global symbol under which the shared `serverFunctionsByPrefix` map is stored
|
|
34
|
+
* on `globalThis`. Keeping it on a `Symbol.for` key makes it instance-stable
|
|
35
|
+
* across the bundled entry copies (`index.mjs`, `server.mjs`, `express.mjs`,
|
|
36
|
+
* ...) and dev-server hot reloads, exactly like the request-context storage in
|
|
37
|
+
* `context.ts`. Without this, `scanForServerFiles` (bundled into the plugin)
|
|
38
|
+
* would populate a map copy the adapter middleware could not read.
|
|
39
|
+
*/
|
|
40
|
+
const functionsMapSymbol = Symbol.for("thednp.rpc.functionsMap");
|
|
41
|
+
/**
|
|
42
|
+
* Map of rpcPrefix -> Map of function names -> ServerFnEntry
|
|
43
|
+
* Enables multiple RPC instances with different prefixes to coexist
|
|
44
|
+
* without name collisions.
|
|
45
|
+
*/
|
|
46
|
+
const serverFunctionsByPrefix = globalThis[functionsMapSymbol] ??= /* @__PURE__ */ new Map();
|
|
47
|
+
/**
|
|
48
|
+
* Gets or creates the function map for a specific prefix.
|
|
49
|
+
* @param prefix - The RPC prefix (e.g., "__rpc", "v1:rpc", "admin:rpc")
|
|
50
|
+
* @returns Map of function names to ServerFnEntry for that prefix
|
|
51
|
+
*/
|
|
52
|
+
const getFunctionsForPrefix = (prefix) => {
|
|
53
|
+
if (!serverFunctionsByPrefix.has(prefix)) serverFunctionsByPrefix.set(prefix, /* @__PURE__ */ new Map());
|
|
54
|
+
return serverFunctionsByPrefix.get(prefix);
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Backward compatibility: default map for the default prefix.
|
|
58
|
+
* Legacy code can still use serverFunctionsMap.set(name, entry).
|
|
59
|
+
*/
|
|
60
|
+
const serverFunctionsMap = {
|
|
61
|
+
get: (key) => getFunctionsForPrefix(defaultPrefix).get(key),
|
|
62
|
+
set: (key, value) => getFunctionsForPrefix(defaultPrefix).set(key, value),
|
|
63
|
+
has: (key) => getFunctionsForPrefix(defaultPrefix).has(key),
|
|
64
|
+
delete: (key) => getFunctionsForPrefix(defaultPrefix).delete(key),
|
|
65
|
+
clear: () => getFunctionsForPrefix(defaultPrefix).clear(),
|
|
66
|
+
get size() {
|
|
67
|
+
return getFunctionsForPrefix(defaultPrefix).size;
|
|
68
|
+
},
|
|
69
|
+
entries: () => getFunctionsForPrefix(defaultPrefix).entries(),
|
|
70
|
+
keys: () => getFunctionsForPrefix(defaultPrefix).keys(),
|
|
71
|
+
values: () => getFunctionsForPrefix(defaultPrefix).values(),
|
|
72
|
+
forEach: (callback) => getFunctionsForPrefix(defaultPrefix).forEach(callback),
|
|
73
|
+
[Symbol.iterator]: () => getFunctionsForPrefix(defaultPrefix)[Symbol.iterator]()
|
|
74
|
+
};
|
|
31
75
|
//#endregion
|
|
32
76
|
//#region src/validate.ts
|
|
33
77
|
const SAFE_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
34
|
-
const SAFE_PATH_SEGMENT = /^[A-Za-z0-9_
|
|
78
|
+
const SAFE_PATH_SEGMENT = /^[A-Za-z0-9_$@:][A-Za-z0-9_$@:/-]*$/;
|
|
35
79
|
const CREDENTIALS_VALUES = [
|
|
36
80
|
"same-origin",
|
|
37
81
|
"include",
|
|
@@ -51,7 +95,8 @@ function validateIdentifier(name, label) {
|
|
|
51
95
|
}
|
|
52
96
|
/**
|
|
53
97
|
* Validates that a string is a safe path segment for RPC routing.
|
|
54
|
-
* Allows alphanumeric characters, underscores, dollar signs, at signs,
|
|
98
|
+
* Allows alphanumeric characters, underscores, dollar signs, at signs,
|
|
99
|
+
* colons, hyphens, and forward slashes.
|
|
55
100
|
* @param segment - The string to validate
|
|
56
101
|
* @param label - Human-readable label for error messages (e.g. "rpcPrefix")
|
|
57
102
|
* @returns The validated segment if it passes
|
|
@@ -101,53 +146,28 @@ const getModule = (fnName, fnEntry, options) => {
|
|
|
101
146
|
const safePrefix = validatePathSegment(options.rpcPrefix, "rpcPrefix");
|
|
102
147
|
const credentials = validateCredentials(options.credentials);
|
|
103
148
|
const method = validateMethod(options.method);
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
headers = `{ 'Content-Type': 'text/plain' }`;
|
|
110
|
-
break;
|
|
111
|
-
case "application/x-www-form-urlencoded":
|
|
112
|
-
body = `new URLSearchParams(args[0]).toString()`;
|
|
113
|
-
headers = `{ 'Content-Type': 'application/x-www-form-urlencoded' }`;
|
|
114
|
-
break;
|
|
115
|
-
case "multipart/form-data":
|
|
116
|
-
body = `args[0]`;
|
|
117
|
-
headers = `{}`;
|
|
118
|
-
break;
|
|
119
|
-
default:
|
|
120
|
-
body = `JSON.stringify(args)`;
|
|
121
|
-
headers = `{ 'Content-Type': 'application/json' }`;
|
|
122
|
-
}
|
|
123
|
-
if (method === "GET") {
|
|
124
|
-
body = `JSON.stringify(args)`;
|
|
125
|
-
headers = `{}`;
|
|
126
|
-
}
|
|
149
|
+
const contentType = options.contentType ?? "application/json";
|
|
150
|
+
const opts = [];
|
|
151
|
+
if (method !== "POST") opts.push(`method: "${method}"`);
|
|
152
|
+
if (credentials !== "same-origin") opts.push(`credentials: "${credentials}"`);
|
|
153
|
+
if (contentType !== "application/json") opts.push(`contentType: "${contentType}"`);
|
|
127
154
|
return `
|
|
128
|
-
export const ${safeFnEntry} = (
|
|
129
|
-
const body = ${body};
|
|
130
|
-
const headers = ${headers};
|
|
131
|
-
const prefix = "${safePrefix}";
|
|
132
|
-
const name = "${safeFnName}";
|
|
133
|
-
const credentials = "${credentials}";
|
|
134
|
-
const method = "${method}";
|
|
135
|
-
return innerModule(body, headers, credentials, prefix, name, method);
|
|
136
|
-
}`.trim();
|
|
155
|
+
export const ${safeFnEntry} = getClientStub("${safePrefix}", "${safeFnName}"${opts.length ? `, { ${opts.join(", ")} }` : ""});`.trim();
|
|
137
156
|
};
|
|
138
157
|
/**
|
|
139
158
|
* Generates the complete client-side module bundle by iterating all registered server functions
|
|
140
|
-
* and producing fetch-based stubs for each. The result is transformed by Vite
|
|
141
|
-
* the dev server or production build.
|
|
159
|
+
* for a specific prefix and producing fetch-based stubs for each. The result is transformed by Vite
|
|
160
|
+
* (or Oxc) during the dev server or production build.
|
|
142
161
|
* @param initialOptions - Plugin options containing rpcPrefix and optional adapter
|
|
143
162
|
* @returns A string of JavaScript code with all client RPC modules and their import dependencies
|
|
144
163
|
*/
|
|
145
164
|
const getClientModules = (initialOptions) => {
|
|
146
165
|
validatePathSegment(initialOptions.rpcPrefix, "rpcPrefix");
|
|
166
|
+
const prefixMap = getFunctionsForPrefix(initialOptions.rpcPrefix);
|
|
147
167
|
return `
|
|
148
168
|
|
|
149
|
-
import {
|
|
150
|
-
${Array.from(
|
|
169
|
+
import { getClientStub } from "@thednp/rpc/helpers";
|
|
170
|
+
${Array.from(prefixMap.entries()).filter(([, entry]) => entry.exportName).map(([registeredName, entry]) => getModule(registeredName, entry.exportName, {
|
|
151
171
|
...initialOptions,
|
|
152
172
|
...entry.options || {}
|
|
153
173
|
})).join("\n")}`.trim();
|
|
@@ -191,7 +211,7 @@ const EXACT_NAMES = [
|
|
|
191
211
|
];
|
|
192
212
|
/**
|
|
193
213
|
* Scans `src/api/` (or an explicit `scanRoot`) for server function files
|
|
194
|
-
* and populates the
|
|
214
|
+
* and populates the server functions map (scoped by rpcPrefix) with their exported functions.
|
|
195
215
|
* Uses Vite's SSR module loading to resolve and execute each file.
|
|
196
216
|
*
|
|
197
217
|
* Supports two matching modes via `config.serverFiles`:
|
|
@@ -249,16 +269,21 @@ const scanForServerFiles = async (initialCfg, devServer) => {
|
|
|
249
269
|
}
|
|
250
270
|
for (const [exportName, exportValue] of moduleEntries) {
|
|
251
271
|
const registeredName = exportValue.name;
|
|
252
|
-
|
|
272
|
+
const prefix = exportValue.options?.rpcPrefix || config.rpcPrefix || "__rpc";
|
|
273
|
+
const seenKey = `${prefix}:${registeredName}`;
|
|
274
|
+
if (seenNames.has(seenKey)) {
|
|
253
275
|
if (process.env.NODE_ENV !== "production") throw new Error(DUPLICATE_FUNCTION_NAME(registeredName));
|
|
254
276
|
console.warn(DUPLICATE_FUNCTION_NAME(registeredName));
|
|
255
277
|
continue;
|
|
256
278
|
}
|
|
257
|
-
seenNames.add(
|
|
258
|
-
|
|
279
|
+
seenNames.add(seenKey);
|
|
280
|
+
const prefixMap = getFunctionsForPrefix(prefix);
|
|
281
|
+
const existing = prefixMap.get(registeredName);
|
|
282
|
+
if (existing) existing.exportName = exportName;
|
|
283
|
+
else prefixMap.set(registeredName, {
|
|
259
284
|
name: registeredName,
|
|
260
285
|
handler: exportValue,
|
|
261
|
-
options: exportValue
|
|
286
|
+
options: exportValue.options,
|
|
262
287
|
exportName
|
|
263
288
|
});
|
|
264
289
|
}
|
|
@@ -323,6 +348,7 @@ const loadRPCConfig = async (configFile) => {
|
|
|
323
348
|
if (!existsSync(configFilePath)) {
|
|
324
349
|
console.warn(CONFIG_FILE_NOT_FOUND(configFile, configFilePath));
|
|
325
350
|
RPCConfig = defaultRPCOptions;
|
|
351
|
+
setGlobalPrefix(defaultRPCOptions.rpcPrefix);
|
|
326
352
|
return defaultRPCOptions;
|
|
327
353
|
}
|
|
328
354
|
const result = await loadConfigFile(env, configFile);
|
|
@@ -331,11 +357,15 @@ const loadRPCConfig = async (configFile) => {
|
|
|
331
357
|
...defaultRPCOptions,
|
|
332
358
|
configFile: configFilePath
|
|
333
359
|
}, result.config);
|
|
360
|
+
setGlobalPrefix(RPCConfig.rpcPrefix);
|
|
334
361
|
return RPCConfig;
|
|
335
362
|
}
|
|
336
363
|
RPCConfig = defaultRPCOptions;
|
|
337
364
|
}
|
|
338
|
-
if (RPCConfig !== void 0)
|
|
365
|
+
if (RPCConfig !== void 0) {
|
|
366
|
+
setGlobalPrefix(RPCConfig.rpcPrefix);
|
|
367
|
+
return RPCConfig;
|
|
368
|
+
}
|
|
339
369
|
for (const file of defaultConfigFiles) {
|
|
340
370
|
const configFilePath = resolve(env.root, file);
|
|
341
371
|
if (!existsSync(configFilePath)) continue;
|
|
@@ -354,6 +384,7 @@ const loadRPCConfig = async (configFile) => {
|
|
|
354
384
|
RPCConfig = defaultRPCOptions;
|
|
355
385
|
console.warn(FAILED_LOAD_CONFIG, error);
|
|
356
386
|
}
|
|
387
|
+
setGlobalPrefix(RPCConfig.rpcPrefix);
|
|
357
388
|
return RPCConfig;
|
|
358
389
|
};
|
|
359
390
|
/**
|
|
@@ -383,7 +414,8 @@ function rpcPlugin(devOptions = {}) {
|
|
|
383
414
|
const scanCfg = {
|
|
384
415
|
...config,
|
|
385
416
|
serverFiles: options.serverFiles,
|
|
386
|
-
scanRoot: options.scanRoot
|
|
417
|
+
scanRoot: options.scanRoot,
|
|
418
|
+
rpcPrefix: options.rpcPrefix
|
|
387
419
|
};
|
|
388
420
|
await scanForServerFiles(scanCfg, viteServer);
|
|
389
421
|
}
|
|
@@ -396,7 +428,8 @@ function rpcPlugin(devOptions = {}) {
|
|
|
396
428
|
const scanCfg = {
|
|
397
429
|
...config,
|
|
398
430
|
serverFiles: options.serverFiles,
|
|
399
|
-
scanRoot: options.scanRoot
|
|
431
|
+
scanRoot: options.scanRoot,
|
|
432
|
+
rpcPrefix: options.rpcPrefix
|
|
400
433
|
};
|
|
401
434
|
await scanForServerFiles(scanCfg);
|
|
402
435
|
}
|
|
@@ -408,7 +441,8 @@ function rpcPlugin(devOptions = {}) {
|
|
|
408
441
|
const scanCfg = {
|
|
409
442
|
...config,
|
|
410
443
|
serverFiles: options.serverFiles,
|
|
411
|
-
scanRoot: options.scanRoot
|
|
444
|
+
scanRoot: options.scanRoot,
|
|
445
|
+
rpcPrefix: options.rpcPrefix
|
|
412
446
|
};
|
|
413
447
|
await scanForServerFiles(scanCfg);
|
|
414
448
|
}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/options.ts","../src/constants.ts","../src/functionsMap.ts","../src/validate.ts","../src/getClientModules.ts","../src/server-helpers.ts","../src/scanForServerFiles.ts","../src/index.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\nexport const defaultServerFnOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n} satisfies ServerFunctionOptions;\n\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: \"__rpc\",\n adapter: \"express\",\n serverFiles: \"exact\",\n scanRoot: undefined,\n};\n\nexport const defaultMiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n} satisfies MiddlewareOptions;\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 = ` ⚡︎ 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","import type { ServerFnEntry } from \"./types.d.ts\";\n\nexport const serverFunctionsMap: Map<string, ServerFnEntry> = new Map<\n string,\n ServerFnEntry\n>();\n","import type { Credentials } from \"./types.d.ts\";\nimport { INVALID_IDENTIFIER, INVALID_PATH_SEGMENT } from \"./constants.ts\";\n\nconst SAFE_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst SAFE_PATH_SEGMENT = /^[A-Za-z0-9_$@][A-Za-z0-9_$@/-]*$/;\nconst CREDENTIALS_VALUES: readonly Credentials[] = [\n \"same-origin\",\n \"include\",\n \"omit\",\n];\n\n/**\n * Validates that a string is a safe JavaScript identifier.\n * Used to prevent code injection when interpolating export names into generated client code.\n * @param name - The string to validate\n * @param label - Human-readable label for error messages (e.g. \"export name\")\n * @returns The validated name if it passes\n * @throws Error if the name contains characters outside /^[A-Za-z_$][A-Za-z0-9_$]*$/\n */\nexport function validateIdentifier(name: string, label: string): string {\n if (!SAFE_IDENTIFIER.test(name)) {\n throw new Error(INVALID_IDENTIFIER(label, name));\n }\n return name;\n}\n\n/**\n * Validates that a string is a safe path segment for RPC routing.\n * Allows alphanumeric characters, underscores, dollar signs, at signs, hyphens, and forward slashes.\n * @param segment - The string to validate\n * @param label - Human-readable label for error messages (e.g. \"rpcPrefix\")\n * @returns The validated segment if it passes\n * @throws Error if the segment contains disallowed characters\n */\nexport function validatePathSegment(segment: string, label: string): string {\n if (!SAFE_PATH_SEGMENT.test(segment)) {\n throw new Error(INVALID_PATH_SEGMENT(label, segment));\n }\n return segment;\n}\n\n/**\n * Validates and normalizes the credentials option.\n * Accepts \"same-origin\", \"include\", or \"omit\"; defaults to \"same-origin\" when undefined.\n * @param value - Credentials value to validate\n * @returns The validated credentials string\n * @throws Error if the value is not one of the accepted credentials\n */\nexport function validateCredentials(value?: string): Credentials {\n const creds = value || \"same-origin\";\n if (!CREDENTIALS_VALUES.includes(creds as Credentials)) {\n throw new Error(\n `Invalid credentials: \"${value}\" must be one of ${\n CREDENTIALS_VALUES.join(\", \")\n }`,\n );\n }\n return creds as Credentials;\n}\n\n/**\n * Validates and normalizes the HTTP method option for a server function.\n * Accepts \"GET\" or \"POST\" (case-insensitive); defaults to \"POST\" when undefined.\n * @param value - Method value to validate\n * @returns The validated uppercase method string\n * @throws Error if the value is not \"GET\" or \"POST\"\n */\nexport function validateMethod(value?: string): \"GET\" | \"POST\" {\n const method = (value || \"POST\").toUpperCase();\n if (method !== \"GET\" && method !== \"POST\") {\n throw new Error(`Invalid method: \"${value}\" must be one of GET, POST`);\n }\n return method;\n}\n","/**\n * @module Client module generation.\n */\nimport type {\n RpcPluginOptionsInternal,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\nimport { serverFunctionsMap } from \"./functionsMap.ts\";\nimport {\n validateCredentials,\n validateIdentifier,\n validateMethod,\n validatePathSegment,\n} from \"./validate.ts\";\n\n/**\n * Generates a JavaScript client module string for a single server function.\n * All interpolated values are validated to prevent code injection.\n * @param fnName - Registered RPC function name (validated as path segment)\n * @param fnEntry - Export name used in the generated module (validated as identifier)\n * @param options - Content type, credentials, and RPC prefix settings\n * @returns A string of JavaScript code exporting the client stub\n */\nconst getModule = (\n fnName: string,\n fnEntry: string,\n options: Partial<ServerFunctionOptions> & {\n contentType: ServerFunctionOptions[\"contentType\"];\n rpcPrefix: string;\n },\n): string => {\n // Validate all interpolated strings to prevent code injection\n const safeFnName = validatePathSegment(fnName, \"function name\");\n const safeFnEntry = validateIdentifier(fnEntry, \"export name\");\n const safePrefix = validatePathSegment(options.rpcPrefix, \"rpcPrefix\");\n const credentials = validateCredentials(options.credentials);\n const method = validateMethod(options.method);\n let body = \"\";\n let headers = \"{}\";\n switch (options.contentType) {\n case \"text/plain\":\n {\n body = `args[0]`;\n headers = `{ 'Content-Type': 'text/plain' }`;\n }\n break;\n case \"application/x-www-form-urlencoded\":\n {\n body = `new URLSearchParams(args[0]).toString()`;\n headers = `{ 'Content-Type': 'application/x-www-form-urlencoded' }`;\n }\n break;\n case \"multipart/form-data\":\n {\n // FormData carries its own multipart content type with a random boundary,\n // so the browser must generate the header (setting it manually strips the boundary)\n body = `args[0]`;\n headers = `{}`;\n }\n break;\n default: {\n body = `JSON.stringify(args)`;\n headers = `{ 'Content-Type': 'application/json' }`;\n }\n }\n // GET requests cannot carry a body: args travel as a JSON query parameter\n if (method === \"GET\") {\n body = `JSON.stringify(args)`;\n headers = `{}`;\n }\n\n const output = `\nexport const ${safeFnEntry} = (...args) => {\n const body = ${body};\n const headers = ${headers};\n const prefix = \"${safePrefix}\";\n const name = \"${safeFnName}\";\n const credentials = \"${credentials}\";\n const method = \"${method}\";\n return innerModule(body, headers, credentials, prefix, name, method);\n}`;\n\n return output.trim();\n};\n\n/**\n * Generates the complete client-side module bundle by iterating all registered server functions\n * and producing fetch-based stubs for each. The result is transformed by Vite (or Oxc) during\n * the dev server or production build.\n * @param initialOptions - Plugin options containing rpcPrefix and optional adapter\n * @returns A string of JavaScript code with all client RPC modules and their import dependencies\n */\nexport const getClientModules = (\n initialOptions: RpcPluginOptionsInternal,\n): string => {\n // Validate prefix once at the top level\n validatePathSegment(initialOptions.rpcPrefix, \"rpcPrefix\");\n const entries = Array.from(serverFunctionsMap.entries())\n .filter(([, entry]) => entry.exportName)\n .map(([registeredName, entry]) =>\n getModule(registeredName, entry.exportName!, {\n ...initialOptions,\n ...((entry.options as ServerFunctionOptions) || {}),\n })\n )\n .join(\"\\n\");\n const output = `\n// Client-side RPC modules\nimport { innerModule } from \"@thednp/rpc/helpers\";\n${entries}`;\n\n return output.trim();\n};\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 { INTERNAL_SERVER_ERROR } from \"./constants.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 */\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 * 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\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","import type { ViteDevServer } from \"vite\";\nimport type { ClientFunctionWithOptions, ScanConfig } from \"./types.d.ts\";\nimport { readdir } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport process from \"node:process\";\n\nimport { serverFunctionsMap } from \"./functionsMap.ts\";\nimport { walkGlobFiles } from \"./server-helpers.ts\";\nimport {\n DUPLICATE_FUNCTION_NAME,\n ERROR_LOADING_FILE,\n NO_SERVER_FUNCTION_FOUND,\n} from \"./constants.ts\";\n\nlet isScanned = false;\n\n/** Absolute ids (normalized) of the scanned server function files. */\nexport const scannedServerFiles: Set<string> = new Set<string>();\n\nconst EXACT_NAMES = [\"server.ts\", \"server.js\", \"server.mjs\", \"server.mts\"];\n\n/**\n * Scans `src/api/` (or an explicit `scanRoot`) for server function files\n * and populates the global `serverFunctionsMap` with their exported functions.\n * Uses Vite's SSR module loading to resolve and execute each file.\n *\n * Supports two matching modes via `config.serverFiles`:\n * `\"exact\"` — classic `server.ts|js|mjs|mts` names in the api directory\n * `\"glob\"` — recursively walking `scanRoot` to match `*.server.{ts,js,mjs,mts}`\n * @param initialCfg - Optional Vite config overrides (root, base, server, serverFiles, scanRoot)\n * @param devServer - Optional running Vite dev server instance; when provided, skips creating a new one\n */\nexport const scanForServerFiles = async (\n initialCfg?: ScanConfig,\n devServer?: ViteDevServer,\n): Promise<void> => {\n if (isScanned && !devServer) {\n return;\n }\n // Vite is only needed to spin up the internal dev server that loads the\n // server function files, so it is imported lazily rather than at the top\n // of the module. This keeps consumers of the standalone server entry that\n // register their functions directly (e.g. serverless functions bundling\n // the API module) free of a static Vite dependency — when Vite is\n // externalized by the function bundler, this lazy import is left as a\n // runtime require that is never executed.\n const { createServer, normalizePath } = await import(\"vite\");\n const config = (!initialCfg && !devServer) || !initialCfg\n ? {\n root: process.cwd(),\n base: process.env.BASE || \"/\",\n server: { middlewareMode: true },\n }\n : {\n ...initialCfg,\n };\n\n let server = devServer;\n if (!server) {\n server = await createServer({\n server: { ...config.server, ws: false },\n appType: \"custom\",\n base: config.base || \"/\",\n root: config.root || process.cwd(),\n // The internal server is only used to load the server function files:\n // skip the project config so its plugins (including this one) do not\n // re-trigger a nested scan via `configureServer`.\n configFile: false,\n // The internal server never serves a page or HMR, so no dependency\n // optimization or WebSocket server is needed. Without `ws: false`, the\n // middleware-mode server creates a standalone HMR WebSocket on port\n // 24678, and concurrent scans (e.g. the Express middleware's lazy scan\n // racing the plugin scan) fail with EADDRINUSE. Without `noDiscovery`,\n // the default optimizers scan the project entry and pre-bundle the whole\n // `vite` package (imported by the linked @thednp/rpc dist files),\n // hanging startup at 2+ GB RSS.\n optimizeDeps: { noDiscovery: true },\n ssr: { optimizeDeps: { noDiscovery: true } },\n });\n }\n\n const root = config.root || process.cwd();\n const resolvedScanRoot = resolve(\n root,\n config.scanRoot ?? join(root, \"src\", \"api\"),\n );\n const serverFiles: \"exact\" | \"glob\" = config.serverFiles ??\n \"exact\";\n\n // Names registered during this scan run, used for duplicate detection\n // (see the registration loop below).\n const seenNames = new Set<string>();\n\n let files: string[];\n try {\n if (serverFiles === \"glob\") {\n files = await walkGlobFiles(resolvedScanRoot);\n } else {\n files = (await readdir(resolvedScanRoot, { withFileTypes: true }))\n .filter((f) => EXACT_NAMES.includes(f.name))\n .map((f) => join(resolvedScanRoot, f.name));\n }\n } catch (_e) {\n files = [];\n }\n\n try {\n for (const file of files) {\n scannedServerFiles.add(normalizePath(file));\n let moduleExports: Record<string, ClientFunctionWithOptions>;\n try {\n moduleExports = (await server.ssrLoadModule(file)) as Record<\n string,\n ClientFunctionWithOptions\n >;\n } catch (error) {\n console.error(ERROR_LOADING_FILE, file, error);\n continue;\n }\n const moduleEntries = Object.entries(moduleExports);\n if (!moduleEntries.length) {\n console.warn(NO_SERVER_FUNCTION_FOUND);\n return;\n }\n\n // `createServerFunction` auto-registers its name into the map at module\n // load, so the global map cannot be used for duplicate detection across\n // scans (dev re-scans the same modules via the same or fresh Vite graphs).\n // Track names seen in THIS scan run only: a name repeated within one scan\n // (e.g. two files exporting the same function name) is a genuine conflict.\n for (const [exportName, exportValue] of moduleEntries) {\n const registeredName = exportValue.name;\n if (seenNames.has(registeredName)) {\n if (process.env.NODE_ENV !== \"production\") {\n throw new Error(DUPLICATE_FUNCTION_NAME(registeredName));\n }\n console.warn(DUPLICATE_FUNCTION_NAME(registeredName));\n continue;\n }\n seenNames.add(registeredName);\n serverFunctionsMap.set(registeredName, {\n name: registeredName,\n handler: exportValue,\n options: exportValue?.options,\n exportName,\n });\n }\n }\n } finally {\n if (!devServer && server) {\n await server.close();\n }\n isScanned = true;\n }\n};\n","/** @module Main entrypoint for the RPC Vite plugin. Exports `rpcPlugin` (default), `defineConfig`, and `loadRPCConfig`. */\nimport type { ConfigEnv, Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport { loadConfigFromFile, mergeConfig } from \"vite\";\nimport { resolve } from \"node:path\";\nimport process from \"node:process\";\nimport { existsSync } from \"node:fs\";\nimport { defaultRPCOptions } from \"./options.ts\";\nimport type { RpcPluginOptions, ScanConfig } from \"./types.d.ts\";\nimport {\n CONFIG_FILE_NOT_FOUND,\n FAILED_LOAD_CONFIG,\n NO_CONFIG_FOUND,\n} from \"./constants.ts\";\n\nimport { getClientModules } from \"./getClientModules.ts\";\n// DEV server only\nimport {\n scanForServerFiles,\n scannedServerFiles,\n} from \"./scanForServerFiles.ts\";\nimport { serverFunctionsMap } from \"./functionsMap.ts\";\n\nimport { createRPCMiddleware } from \"@thednp/rpc/express\";\n\n/**\n * Loads and transforms a single RPC config file using Vite's config loader.\n * @param env - Vite config environment\n * @param file - Config file path (e.g. \"rpc.config.ts\")\n * @returns The loaded config augmented with the configFile path, or null on failure\n */\nconst loadConfigFile = async (env: ConfigEnv, file: string) => {\n const result = await loadConfigFromFile(env, file) as {\n path: string;\n config: Partial<RpcPluginOptions>;\n dependencies: string[];\n } | null;\n return result\n ? { ...result, config: { ...result.config, configFile: file } }\n : /* istanbul ignore next */ null;\n};\n\n/**\n * Type-safe helper to create an RPC configuration object.\n * Merges the provided partial config with built-in defaults.\n * @param uniConfig - System-wide RPC configuration overrides\n * @returns Complete RPC plugin options with defaults applied\n */\nconst defineConfig: (c: Partial<RpcPluginOptions>) => RpcPluginOptions = (\n uniConfig: Partial<RpcPluginOptions>,\n) => {\n return mergeConfig(defaultRPCOptions, uniConfig) as RpcPluginOptions;\n};\n\nlet RPCConfig: RpcPluginOptions;\n\n/**\n * Loads the RPC configuration by searching for config files in the project root.\n * Searches in order: `rpc.config.ts`, `rpc.config.js`, `rpc.config.mjs`, `rpc.config.mts`,\n * `.rpcrc.ts`, `.rpcrc.js`. Falls back to defaults if none found.\n * @param configFile - Optional explicit config file path; skips file search when provided\n * @returns Resolved RPC plugin options\n */\nconst loadRPCConfig: (f?: string) => Promise<RpcPluginOptions> = async (\n configFile?: string,\n) => {\n try {\n // istanbul ignore next\n const env: ConfigEnv & { root: string } = {\n command: \"serve\",\n root: process.cwd(),\n mode: process.env.NODE_ENV || \"development\",\n };\n const defaultConfigFiles = [\n \"rpc.config.ts\",\n \"rpc.config.js\",\n \"rpc.config.mjs\",\n \"rpc.config.mts\",\n \".rpcrc.ts\",\n \".rpcrc.js\",\n ];\n\n // If specific config file provided\n if (configFile) {\n const configFilePath = resolve(env.root, configFile);\n if (!existsSync(configFilePath)) {\n console.warn(CONFIG_FILE_NOT_FOUND(configFile, configFilePath));\n RPCConfig = defaultRPCOptions;\n return defaultRPCOptions as RpcPluginOptions;\n }\n\n const result = await loadConfigFile(env, configFile);\n // istanbul ignore else\n if (result && typeof result === \"object\") {\n RPCConfig = mergeConfig(\n {\n ...defaultRPCOptions,\n configFile: configFilePath,\n },\n result.config,\n ) as RpcPluginOptions;\n\n return RPCConfig;\n }\n // istanbul ignore next - this is a necessary fallback here\n RPCConfig = defaultRPCOptions;\n }\n\n if (RPCConfig !== undefined) {\n return RPCConfig;\n }\n\n // Try default config files\n for (const file of defaultConfigFiles) {\n const configFilePath = resolve(env.root, file);\n // istanbul ignore else\n if (!existsSync(configFilePath)) {\n continue;\n }\n\n const result = await loadConfigFile(env, file);\n // istanbul ignore else\n if (result) {\n RPCConfig = mergeConfig(\n {\n ...defaultRPCOptions,\n configFile: configFilePath,\n },\n result.config,\n ) as RpcPluginOptions;\n\n return RPCConfig;\n }\n }\n RPCConfig = defaultRPCOptions;\n // Last call load defaults no matter what\n console.warn(NO_CONFIG_FOUND);\n // return defaultRPCOptions as RpcPluginOptions;\n // RPCConfig = defaultRPCOptions;\n } catch (error) {\n RPCConfig = defaultRPCOptions;\n console.warn(FAILED_LOAD_CONFIG, error);\n // return defaultRPCOptions as RpcPluginOptions;\n }\n\n return RPCConfig;\n};\n\n/**\n * Vite plugin that enables automatic RPC generation.\n * Transforms server function imports into fetch-based client stubs during development and production builds.\n * In dev mode, attaches the RPC middleware to Vite's Connect server.\n * @param devOptions - Development-only overrides (merged on top of config file values)\n * @returns A Vite plugin object\n */\nfunction rpcPlugin(\n devOptions: Partial<RpcPluginOptions> = {},\n): Plugin {\n // Internal type - adapters are handled at runtime\n let options: RpcPluginOptions & { rpcPrefix: string } = mergeConfig(\n defaultRPCOptions,\n devOptions,\n ) as RpcPluginOptions;\n let config: ResolvedConfig;\n let viteServer: ViteDevServer;\n let isOxc = true;\n\n return {\n name: \"vite-plugin-universal-rpc\",\n enforce: \"pre\",\n // Plugin methods\n // config() {\n // return {\n // // optimizeDeps: {\n // // noDiscovery: true,\n // // include: [\"@thednp/rpc\"],\n // // },\n // ssr: {\n // noExternal: [\"@thednp/rpc\"],\n // },\n // };\n // },\n async configResolved(resolvedConfig) {\n const uniConfig = await loadRPCConfig();\n options = mergeConfig(uniConfig, devOptions) as RpcPluginOptions;\n\n config = resolvedConfig;\n },\n async configureServer(server) {\n viteServer = server;\n const { adapter: _adapter, ...rest } = options;\n // istanbul ignore else\n if (serverFunctionsMap.size === 0) {\n const scanCfg: ScanConfig = {\n ...config,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n };\n await scanForServerFiles(scanCfg, viteServer);\n }\n\n // in dev mode we always use express/connect adapter\n server.middlewares.use(createRPCMiddleware(rest));\n },\n\n async buildStart() {\n const viteVersion = this.meta?.viteVersion;\n isOxc = Number(viteVersion[0]) >= 8;\n\n // Prepare the server functions\n if (!viteServer && config) {\n const scanCfg: ScanConfig = {\n ...config,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n };\n await scanForServerFiles(scanCfg);\n }\n },\n async transform(code: string, id: string, ops?: { ssr?: boolean }) {\n // Only transform files with server functions for client builds\n if (\n !code.includes(\"createServerFunction\") || // any other file is unchanged\n ops?.ssr || // file loaded on server remains unchanged\n (code.includes(\"createServerFunction\") &&\n typeof process === \"undefined\") // file loaded in client IS CHANGED\n ) {\n return null;\n }\n\n const vite = await import(\"vite\");\n\n if (serverFunctionsMap.size === 0) {\n const scanCfg: ScanConfig = {\n ...config,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n };\n await scanForServerFiles(scanCfg);\n }\n\n // Only transform modules that were scanned as server function files:\n // pages or docs mentioning `createServerFunction` in prose must not\n // be rewritten into the generated client bundle.\n const idPath = vite.normalizePath(id.split(\"?\")[0]);\n if (!scannedServerFiles.has(idPath)) {\n return null;\n }\n\n const transformer = isOxc ? \"transformWithOxc\" : \"transformWithEsbuild\";\n const langProp = isOxc ? \"lang\" : \"loader\";\n const source = getClientModules({\n rpcPrefix: options.rpcPrefix,\n adapter: options.adapter,\n });\n\n const result = await vite[transformer](source, id, {\n [langProp]: \"js\",\n sourcemap: true,\n // target: \"es2023\"\n });\n\n return {\n code: result.code,\n map: result.map\n ? typeof result.map === \"string\"\n ? JSON.parse(result.map)\n : /* istanbul ignore next @preserve */ result.map\n : /* istanbul ignore next @preserve */ null,\n };\n },\n } satisfies Plugin;\n}\n\nexport { rpcPlugin as default };\nexport { defineConfig, loadRPCConfig };\nexport type * from \"./types.d.ts\";\nexport {};\n"],"mappings":";;;;;;;AAYA,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;CACT,aAAa;CACb,UAAU,KAAA;AACZ;;;ACXA,MAAa,2BAA2B;AAExC,MAAa,qBAAqB;;AAqBlC,MAAa,sBAAsB,OAAe,SAChD,WAAW,MAAM,KAAK,KAAK;;AAG7B,MAAa,wBAAwB,OAAe,YAClD,WAAW,MAAM,KAAK,QAAQ;;AAGhC,MAAa,yBACX,YACA,mBAEA,sCAAsC,WAAW,sBAAsB,eAAe;AAExF,MAAa,kBAAkB;AAE/B,MAAa,qBAAqB;;AAGlC,MAAa,2BAA2B,SACtC,8BAA8B,KAAK;;;AC/CrC,MAAa,qCAAiD,IAAI,IAGhE;;;ACFF,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAC1B,MAAM,qBAA6C;CACjD;CACA;CACA;AACF;;;;;;;;;AAUA,SAAgB,mBAAmB,MAAc,OAAuB;CACtE,IAAI,CAAC,gBAAgB,KAAK,IAAI,GAC5B,MAAM,IAAI,MAAM,mBAAmB,OAAO,IAAI,CAAC;CAEjD,OAAO;AACT;;;;;;;;;AAUA,SAAgB,oBAAoB,SAAiB,OAAuB;CAC1E,IAAI,CAAC,kBAAkB,KAAK,OAAO,GACjC,MAAM,IAAI,MAAM,qBAAqB,OAAO,OAAO,CAAC;CAEtD,OAAO;AACT;;;;;;;;AASA,SAAgB,oBAAoB,OAA6B;CAC/D,MAAM,QAAQ,SAAS;CACvB,IAAI,CAAC,mBAAmB,SAAS,KAAoB,GACnD,MAAM,IAAI,MACR,yBAAyB,MAAM,mBAC7B,mBAAmB,KAAK,IAAI,GAEhC;CAEF,OAAO;AACT;;;;;;;;AASA,SAAgB,eAAe,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KAAK,YAAY,CAAC,QAAQ,IAAI;KAChD,WAAW;IACZ,WAAW;GAEb,CAAC;GAED,OAAO;IACL,MAAM,OAAO;IACb,KAAK,OAAO,MACR,OAAO,OAAO,QAAQ,WACpB,KAAK,MAAM,OAAO,GAAG,IACpB,OAAO,MACT;GACP;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/options.ts","../src/constants.ts","../src/functionsMap.ts","../src/validate.ts","../src/getClientModules.ts","../src/server-helpers.ts","../src/scanForServerFiles.ts","../src/index.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","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 = ` ⚡︎ 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","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","import type { Credentials } from \"./types.d.ts\";\nimport { INVALID_IDENTIFIER, INVALID_PATH_SEGMENT } from \"./constants.ts\";\n\nconst SAFE_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\nconst SAFE_PATH_SEGMENT = /^[A-Za-z0-9_$@:][A-Za-z0-9_$@:/-]*$/;\nconst CREDENTIALS_VALUES: readonly Credentials[] = [\n \"same-origin\",\n \"include\",\n \"omit\",\n];\n\n/**\n * Validates that a string is a safe JavaScript identifier.\n * Used to prevent code injection when interpolating export names into generated client code.\n * @param name - The string to validate\n * @param label - Human-readable label for error messages (e.g. \"export name\")\n * @returns The validated name if it passes\n * @throws Error if the name contains characters outside /^[A-Za-z_$][A-Za-z0-9_$]*$/\n */\nexport function validateIdentifier(name: string, label: string): string {\n if (!SAFE_IDENTIFIER.test(name)) {\n throw new Error(INVALID_IDENTIFIER(label, name));\n }\n return name;\n}\n\n/**\n * Validates that a string is a safe path segment for RPC routing.\n * Allows alphanumeric characters, underscores, dollar signs, at signs,\n * colons, hyphens, and forward slashes.\n * @param segment - The string to validate\n * @param label - Human-readable label for error messages (e.g. \"rpcPrefix\")\n * @returns The validated segment if it passes\n * @throws Error if the segment contains disallowed characters\n */\nexport function validatePathSegment(segment: string, label: string): string {\n if (!SAFE_PATH_SEGMENT.test(segment)) {\n throw new Error(INVALID_PATH_SEGMENT(label, segment));\n }\n return segment;\n}\n\n/**\n * Validates and normalizes the credentials option.\n * Accepts \"same-origin\", \"include\", or \"omit\"; defaults to \"same-origin\" when undefined.\n * @param value - Credentials value to validate\n * @returns The validated credentials string\n * @throws Error if the value is not one of the accepted credentials\n */\nexport function validateCredentials(value?: string): Credentials {\n const creds = value || \"same-origin\";\n if (!CREDENTIALS_VALUES.includes(creds as Credentials)) {\n throw new Error(\n `Invalid credentials: \"${value}\" must be one of ${\n CREDENTIALS_VALUES.join(\", \")\n }`,\n );\n }\n return creds as Credentials;\n}\n\n/**\n * Validates and normalizes the HTTP method option for a server function.\n * Accepts \"GET\" or \"POST\" (case-insensitive); defaults to \"POST\" when undefined.\n * @param value - Method value to validate\n * @returns The validated uppercase method string\n * @throws Error if the value is not \"GET\" or \"POST\"\n */\nexport function validateMethod(value?: string): \"GET\" | \"POST\" {\n const method = (value || \"POST\").toUpperCase();\n if (method !== \"GET\" && method !== \"POST\") {\n throw new Error(`Invalid method: \"${value}\" must be one of GET, POST`);\n }\n return method;\n}\n","/**\n * @module Client module generation.\n */\nimport type {\n RpcPluginOptionsInternal,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\nimport { getFunctionsForPrefix } from \"./functionsMap.ts\";\nimport {\n validateCredentials,\n validateIdentifier,\n validateMethod,\n validatePathSegment,\n} from \"./validate.ts\";\n\n/**\n * Generates a JavaScript client module string for a single server function.\n * All interpolated values are validated to prevent code injection.\n * @param fnName - Registered RPC function name (validated as path segment)\n * @param fnEntry - Export name used in the generated module (validated as identifier)\n * @param options - Content type, credentials, and RPC prefix settings\n * @returns A string of JavaScript code exporting the client stub\n */\nconst getModule = (\n fnName: string,\n fnEntry: string,\n options: Partial<ServerFunctionOptions> & {\n contentType: ServerFunctionOptions[\"contentType\"];\n rpcPrefix: string;\n },\n): string => {\n // Validate all interpolated strings to prevent code injection\n const safeFnName = validatePathSegment(fnName, \"function name\");\n const safeFnEntry = validateIdentifier(fnEntry, \"export name\");\n const safePrefix = validatePathSegment(options.rpcPrefix, \"rpcPrefix\");\n const credentials = validateCredentials(options.credentials);\n const method = validateMethod(options.method);\n const contentType =\n (options.contentType ?? \"application/json\") as ServerFunctionOptions[\n \"contentType\"\n ];\n\n const opts: string[] = [];\n if (method !== \"POST\") opts.push(`method: \"${method}\"`);\n if (credentials !== \"same-origin\") opts.push(`credentials: \"${credentials}\"`);\n if (contentType !== \"application/json\") {\n opts.push(`contentType: \"${contentType}\"`);\n }\n const optsStr = opts.length ? `, { ${opts.join(\", \")} }` : \"\";\n\n const output = `\n export const ${safeFnEntry} = getClientStub(\"${safePrefix}\", \"${safeFnName}\"${optsStr});`;\n\n return output.trim();\n};\n\n/**\n * Generates the complete client-side module bundle by iterating all registered server functions\n * for a specific prefix and producing fetch-based stubs for each. The result is transformed by Vite\n * (or Oxc) during the dev server or production build.\n * @param initialOptions - Plugin options containing rpcPrefix and optional adapter\n * @returns A string of JavaScript code with all client RPC modules and their import dependencies\n */\nexport const getClientModules = (\n initialOptions: RpcPluginOptionsInternal,\n): string => {\n // Validate prefix once at the top level\n validatePathSegment(initialOptions.rpcPrefix, \"rpcPrefix\");\n\n // Get functions registered for this specific prefix\n const prefixMap = getFunctionsForPrefix(initialOptions.rpcPrefix);\n const entries = Array.from(prefixMap.entries())\n .filter(([, entry]) => entry.exportName)\n .map(([registeredName, entry]) =>\n getModule(registeredName, entry.exportName!, {\n ...initialOptions,\n ...((entry.options as ServerFunctionOptions) || {}),\n })\n )\n .join(\"\\n\");\n\n const output = `\n// Client-side RPC modules for prefix: ${initialOptions.rpcPrefix}\nimport { getClientStub } from \"@thednp/rpc/helpers\";\n${entries}`;\n\n return output.trim();\n};\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 { INTERNAL_SERVER_ERROR } from \"./constants.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 */\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 * 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\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\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","import type { ViteDevServer } from \"vite\";\nimport type { ClientFunctionWithOptions, ScanConfig } from \"./types.d.ts\";\nimport { readdir } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport process from \"node:process\";\n\nimport { getFunctionsForPrefix } from \"./functionsMap.ts\";\nimport { defaultPrefix } from \"./options.ts\";\nimport { walkGlobFiles } from \"./server-helpers.ts\";\nimport {\n DUPLICATE_FUNCTION_NAME,\n ERROR_LOADING_FILE,\n NO_SERVER_FUNCTION_FOUND,\n} from \"./constants.ts\";\n\nlet isScanned = false;\n\n/** Absolute ids (normalized) of the scanned server function files. */\nexport const scannedServerFiles: Set<string> = new Set<string>();\n\nconst EXACT_NAMES = [\"server.ts\", \"server.js\", \"server.mjs\", \"server.mts\"];\n\n/**\n * Scans `src/api/` (or an explicit `scanRoot`) for server function files\n * and populates the server functions map (scoped by rpcPrefix) with their exported functions.\n * Uses Vite's SSR module loading to resolve and execute each file.\n *\n * Supports two matching modes via `config.serverFiles`:\n * `\"exact\"` — classic `server.ts|js|mjs|mts` names in the api directory\n * `\"glob\"` — recursively walking `scanRoot` to match `*.server.{ts,js,mjs,mts}`\n * @param initialCfg - Optional Vite config overrides (root, base, server, serverFiles, scanRoot)\n * @param devServer - Optional running Vite dev server instance; when provided, skips creating a new one\n */\nexport const scanForServerFiles = async (\n initialCfg?: ScanConfig,\n devServer?: ViteDevServer,\n): Promise<void> => {\n if (isScanned && !devServer) {\n return;\n }\n // Vite is only needed to spin up the internal dev server that loads the\n // server function files, so it is imported lazily rather than at the top\n // of the module. This keeps consumers of the standalone server entry that\n // register their functions directly (e.g. serverless functions bundling\n // the API module) free of a static Vite dependency — when Vite is\n // externalized by the function bundler, this lazy import is left as a\n // runtime require that is never executed.\n const { createServer, normalizePath } = await import(\"vite\");\n const config = (!initialCfg && !devServer) || !initialCfg\n ? {\n root: process.cwd(),\n base: process.env.BASE || \"/\",\n server: { middlewareMode: true },\n }\n : {\n ...initialCfg,\n };\n\n let server = devServer;\n if (!server) {\n server = await createServer({\n server: { ...config.server, ws: false },\n appType: \"custom\",\n base: config.base || \"/\",\n root: config.root || process.cwd(),\n // The internal server is only used to load the server function files:\n // skip the project config so its plugins (including this one) do not\n // re-trigger a nested scan via `configureServer`.\n configFile: false,\n // The internal server never serves a page or HMR, so no dependency\n // optimization or WebSocket server is needed. Without `ws: false`, the\n // middleware-mode server creates a standalone HMR WebSocket on port\n // 24678, and concurrent scans (e.g. the Express middleware's lazy scan\n // racing the plugin scan) fail with EADDRINUSE. Without `noDiscovery`,\n // the default optimizers scan the project entry and pre-bundle the whole\n // `vite` package (imported by the linked @thednp/rpc dist files),\n // hanging startup at 2+ GB RSS.\n optimizeDeps: { noDiscovery: true },\n ssr: { optimizeDeps: { noDiscovery: true } },\n });\n }\n\n const root = config.root || process.cwd();\n const resolvedScanRoot = resolve(\n root,\n config.scanRoot ?? join(root, \"src\", \"api\"),\n );\n const serverFiles: \"exact\" | \"glob\" = config.serverFiles ??\n \"exact\";\n\n // Names registered during this scan run, used for duplicate detection.\n // Keyed by `${prefix}:${registeredName}` so the same name can coexist\n // under different rpcPrefixes (see the registration loop below).\n const seenNames = new Set<string>();\n\n let files: string[];\n try {\n if (serverFiles === \"glob\") {\n files = await walkGlobFiles(resolvedScanRoot);\n } else {\n files = (await readdir(resolvedScanRoot, { withFileTypes: true }))\n .filter((f) => EXACT_NAMES.includes(f.name))\n .map((f) => join(resolvedScanRoot, f.name));\n }\n } catch (_e) {\n files = [];\n }\n\n try {\n for (const file of files) {\n scannedServerFiles.add(normalizePath(file));\n let moduleExports: Record<string, ClientFunctionWithOptions>;\n try {\n moduleExports = (await server.ssrLoadModule(file)) as Record<\n string,\n ClientFunctionWithOptions\n >;\n } catch (error) {\n console.error(ERROR_LOADING_FILE, file, error);\n continue;\n }\n const moduleEntries = Object.entries(moduleExports);\n if (!moduleEntries.length) {\n console.warn(NO_SERVER_FUNCTION_FOUND);\n return;\n }\n\n // Register each export into its prefix-scoped map, recording the\n // original export name so `getClientModules` can emit the matching\n // client stub. `createServerFunction` already auto-registers its name\n // into the appropriate prefix-scoped map at module load, so a function\n // may already exist here — in that case only the export name is added.\n // Track names seen in THIS scan run only, keyed by prefix: a name\n // repeated within one scan under the same prefix (e.g. two files\n // exporting the same function name) is a genuine conflict.\n for (const [exportName, exportValue] of moduleEntries) {\n const registeredName = exportValue.name;\n const prefix = exportValue.options?.rpcPrefix ||\n config.rpcPrefix ||\n defaultPrefix;\n const seenKey = `${prefix}:${registeredName}`;\n if (seenNames.has(seenKey)) {\n if (process.env.NODE_ENV !== \"production\") {\n throw new Error(DUPLICATE_FUNCTION_NAME(registeredName));\n }\n console.warn(DUPLICATE_FUNCTION_NAME(registeredName));\n continue;\n }\n seenNames.add(seenKey);\n const prefixMap = getFunctionsForPrefix(prefix);\n const existing = prefixMap.get(registeredName);\n if (existing) {\n existing.exportName = exportName;\n } else {\n prefixMap.set(registeredName, {\n name: registeredName,\n handler: exportValue,\n options: exportValue.options,\n exportName,\n });\n }\n }\n }\n } finally {\n if (!devServer && server) {\n await server.close();\n }\n isScanned = true;\n }\n};\n","/** @module Main entrypoint for the RPC Vite plugin. Exports `rpcPlugin` (default), `defineConfig`, and `loadRPCConfig`. */\nimport type { ConfigEnv, Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport { loadConfigFromFile, mergeConfig } from \"vite\";\nimport { resolve } from \"node:path\";\nimport process from \"node:process\";\nimport { existsSync } from \"node:fs\";\nimport { defaultRPCOptions } from \"./options.ts\";\nimport type { RpcPluginOptions, ScanConfig } from \"./types.d.ts\";\nimport {\n CONFIG_FILE_NOT_FOUND,\n FAILED_LOAD_CONFIG,\n NO_CONFIG_FOUND,\n} from \"./constants.ts\";\n\nimport { getClientModules } from \"./getClientModules.ts\";\n// DEV server only\nimport {\n scanForServerFiles,\n scannedServerFiles,\n} from \"./scanForServerFiles.ts\";\nimport { serverFunctionsMap } from \"./functionsMap.ts\";\n\nimport { setGlobalPrefix } from \"@thednp/rpc/server\";\nimport { createRPCMiddleware } from \"@thednp/rpc/express\";\n\n/**\n * Loads and transforms a single RPC config file using Vite's config loader.\n * @param env - Vite config environment\n * @param file - Config file path (e.g. \"rpc.config.ts\")\n * @returns The loaded config augmented with the configFile path, or null on failure\n */\nconst loadConfigFile = async (env: ConfigEnv, file: string) => {\n const result = await loadConfigFromFile(env, file) as {\n path: string;\n config: Partial<RpcPluginOptions>;\n dependencies: string[];\n } | null;\n return result\n ? { ...result, config: { ...result.config, configFile: file } }\n : /* istanbul ignore next */ null;\n};\n\n/**\n * Type-safe helper to create an RPC configuration object.\n * Merges the provided partial config with built-in defaults.\n * @param uniConfig - System-wide RPC configuration overrides\n * @returns Complete RPC plugin options with defaults applied\n */\nconst defineConfig: (c: Partial<RpcPluginOptions>) => RpcPluginOptions = (\n uniConfig: Partial<RpcPluginOptions>,\n) => {\n return mergeConfig(defaultRPCOptions, uniConfig) as RpcPluginOptions;\n};\n\nlet RPCConfig: RpcPluginOptions;\n\n/**\n * Loads the RPC configuration by searching for config files in the project root.\n * Searches in order: `rpc.config.ts`, `rpc.config.js`, `rpc.config.mjs`, `rpc.config.mts`,\n * `.rpcrc.ts`, `.rpcrc.js`. Falls back to defaults if none found.\n * @param configFile - Optional explicit config file path; skips file search when provided\n * @returns Resolved RPC plugin options\n */\nconst loadRPCConfig: (f?: string) => Promise<RpcPluginOptions> = async (\n configFile?: string,\n) => {\n try {\n // istanbul ignore next\n const env: ConfigEnv & { root: string } = {\n command: \"serve\",\n root: process.cwd(),\n mode: process.env.NODE_ENV || \"development\",\n };\n const defaultConfigFiles = [\n \"rpc.config.ts\",\n \"rpc.config.js\",\n \"rpc.config.mjs\",\n \"rpc.config.mts\",\n \".rpcrc.ts\",\n \".rpcrc.js\",\n ];\n\n // If specific config file provided\n if (configFile) {\n const configFilePath = resolve(env.root, configFile);\n if (!existsSync(configFilePath)) {\n console.warn(CONFIG_FILE_NOT_FOUND(configFile, configFilePath));\n RPCConfig = defaultRPCOptions;\n setGlobalPrefix(defaultRPCOptions.rpcPrefix);\n return defaultRPCOptions as RpcPluginOptions;\n }\n\n const result = await loadConfigFile(env, configFile);\n // istanbul ignore else\n if (result && typeof result === \"object\") {\n RPCConfig = mergeConfig(\n {\n ...defaultRPCOptions,\n configFile: configFilePath,\n },\n result.config,\n ) as RpcPluginOptions;\n\n setGlobalPrefix(RPCConfig.rpcPrefix);\n return RPCConfig;\n }\n // istanbul ignore next - this is a necessary fallback here\n RPCConfig = defaultRPCOptions;\n }\n\n if (RPCConfig !== undefined) {\n setGlobalPrefix(RPCConfig.rpcPrefix);\n\n return RPCConfig;\n }\n\n // Try default config files\n for (const file of defaultConfigFiles) {\n const configFilePath = resolve(env.root, file);\n // istanbul ignore else\n if (!existsSync(configFilePath)) {\n continue;\n }\n\n const result = await loadConfigFile(env, file);\n // istanbul ignore else\n if (result) {\n RPCConfig = mergeConfig(\n {\n ...defaultRPCOptions,\n configFile: configFilePath,\n },\n result.config,\n ) as RpcPluginOptions;\n\n return RPCConfig;\n }\n }\n RPCConfig = defaultRPCOptions;\n // Last call load defaults no matter what\n console.warn(NO_CONFIG_FOUND);\n // return defaultRPCOptions as RpcPluginOptions;\n // RPCConfig = defaultRPCOptions;\n } catch (error) {\n RPCConfig = defaultRPCOptions;\n console.warn(FAILED_LOAD_CONFIG, error);\n // return defaultRPCOptions as RpcPluginOptions;\n }\n\n setGlobalPrefix(RPCConfig.rpcPrefix);\n\n return RPCConfig;\n};\n\n/**\n * Vite plugin that enables automatic RPC generation.\n * Transforms server function imports into fetch-based client stubs during development and production builds.\n * In dev mode, attaches the RPC middleware to Vite's Connect server.\n * @param devOptions - Development-only overrides (merged on top of config file values)\n * @returns A Vite plugin object\n */\nfunction rpcPlugin(\n devOptions: Partial<RpcPluginOptions> = {},\n): Plugin {\n // Internal type - adapters are handled at runtime\n let options: RpcPluginOptions & { rpcPrefix: string } = mergeConfig(\n defaultRPCOptions,\n devOptions,\n ) as RpcPluginOptions;\n let config: ResolvedConfig;\n let viteServer: ViteDevServer;\n let isOxc = true;\n\n return {\n name: \"vite-plugin-universal-rpc\",\n enforce: \"pre\",\n // Plugin methods\n async configResolved(resolvedConfig) {\n const uniConfig = await loadRPCConfig();\n options = mergeConfig(uniConfig, devOptions) as RpcPluginOptions;\n // setGlobalPrefix(options.rpcPrefix);\n\n config = resolvedConfig;\n },\n async configureServer(server) {\n viteServer = server;\n const { adapter: _adapter, ...rest } = options;\n // istanbul ignore else\n if (serverFunctionsMap.size === 0) {\n const scanCfg: ScanConfig = {\n ...config,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n rpcPrefix: options.rpcPrefix,\n };\n await scanForServerFiles(scanCfg, viteServer);\n }\n\n // in dev mode we always use express/connect adapter\n server.middlewares.use(createRPCMiddleware(rest));\n },\n\n async buildStart() {\n const viteVersion = this.meta?.viteVersion;\n isOxc = Number(viteVersion[0]) >= 8;\n\n // Prepare the server functions\n if (!viteServer && config) {\n const scanCfg: ScanConfig = {\n ...config,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n rpcPrefix: options.rpcPrefix,\n };\n await scanForServerFiles(scanCfg);\n }\n },\n async transform(code: string, id: string, ops?: { ssr?: boolean }) {\n // Only transform files with server functions for client builds\n if (\n !code.includes(\"createServerFunction\") || // any other file is unchanged\n ops?.ssr || // file loaded on server remains unchanged\n (code.includes(\"createServerFunction\") &&\n typeof process === \"undefined\") // file loaded in client IS CHANGED\n ) {\n return null;\n }\n\n const vite = await import(\"vite\");\n\n if (serverFunctionsMap.size === 0) {\n const scanCfg: ScanConfig = {\n ...config,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n rpcPrefix: options.rpcPrefix,\n };\n await scanForServerFiles(scanCfg);\n }\n\n // Only transform modules that were scanned as server function files:\n // pages or docs mentioning `createServerFunction` in prose must not\n // be rewritten into the generated client bundle.\n const idPath = vite.normalizePath(id.split(\"?\")[0]);\n if (!scannedServerFiles.has(idPath)) {\n return null;\n }\n\n const transformer = isOxc ? \"transformWithOxc\" : \"transformWithEsbuild\";\n const langProp = isOxc ? \"lang\" : \"loader\";\n const source = getClientModules({\n rpcPrefix: options.rpcPrefix,\n adapter: options.adapter,\n });\n\n const result = await vite[transformer](source, id, {\n [langProp]: \"js\",\n sourcemap: true,\n // target: \"es2023\"\n });\n\n return {\n code: result.code,\n map: result.map\n ? typeof result.map === \"string\"\n ? JSON.parse(result.map)\n : /* istanbul ignore next @preserve */ result.map\n : /* istanbul ignore next @preserve */ null,\n };\n },\n } satisfies Plugin;\n}\n\nexport { rpcPlugin as default };\nexport { defineConfig, loadRPCConfig };\nexport type * from \"./types.d.ts\";\nexport {};\n"],"mappings":";;;;;;;;AAYA,MAAa,gBAAgB;AAE7B,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;CACT,aAAa;CACb,UAAU,KAAA;AACZ;;;ACbA,MAAa,2BAA2B;AAExC,MAAa,qBAAqB;;AAqBlC,MAAa,sBAAsB,OAAe,SAChD,WAAW,MAAM,KAAK,KAAK;;AAG7B,MAAa,wBAAwB,OAAe,YAClD,WAAW,MAAM,KAAK,QAAQ;;AAGhC,MAAa,yBACX,YACA,mBAEA,sCAAsC,WAAW,sBAAsB,eAAe;AAExF,MAAa,kBAAkB;AAE/B,MAAa,qBAAqB;;AAGlC,MAAa,2BAA2B,SACtC,8BAA8B,KAAK;;;;;;;;;;;ACtCrC,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;;;;;AAMA,MAAa,qBAAiD;CAC5D,MAAM,QAAgB,sBAAsB,aAAa,CAAC,CAAC,IAAI,GAAG;CAClE,MAAM,KAAa,UACjB,sBAAsB,aAAa,CAAC,CAAC,IAAI,KAAK,KAAK;CACrD,MAAM,QAAgB,sBAAsB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,CAAC,EAAE;GAClD,IAAI,CAAC,mBAAmB,IAAI,MAAM,GAChC,OAAO;GAGT,MAAM,cAAc,QAAQ,qBAAqB;GACjD,MAAM,WAAW,QAAQ,SAAS;GAClC,MAAM,SAAS,iBAAiB;IAC9B,WAAW,QAAQ;IACnB,SAAS,QAAQ;GACnB,CAAC;GAED,MAAM,SAAS,MAAM,KAAK,YAAY,CAAC,QAAQ,IAAI;KAChD,WAAW;IACZ,WAAW;GAEb,CAAC;GAED,OAAO;IACL,MAAM,OAAO;IACb,KAAK,OAAO,MACR,OAAO,OAAO,QAAQ,WACpB,KAAK,MAAM,OAAO,GAAG,IACpB,OAAO,MACT;GACP;EACF;CACF;AACF"}
|
package/dist/koa/koa.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"koa.d.mts","names":[],"sources":["../../src/koa/types.d.ts","../../src/koa/createMiddleware.ts","../../src/koa/helpers.ts"],"mappings":";;;;;;;KAWY,uBAAuB;;;;UAKlB,mBAAmB;;EAElC,SAAS;IAAuB,gBAAgB;;;;;;UAMjC;;;;;;EAMf,UAAU,KAAK,SAAS,MAAM,SAAS;;;;;;KAO7B,mBAAmB,UAAU,qCACvC,iBAAiB,QAAQ,0BACtB;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"koa.d.mts","names":[],"sources":["../../src/koa/types.d.ts","../../src/koa/createMiddleware.ts","../../src/koa/helpers.ts"],"mappings":";;;;;;;KAWY,uBAAuB;;;;UAKlB,mBAAmB;;EAElC,SAAS;IAAuB,gBAAgB;;;;;;UAMjC;;;;;;EAMf,UAAU,KAAK,SAAS,MAAM,SAAS;;;;;;KAO7B,mBAAmB,UAAU,qCACvC,iBAAiB,QAAQ,0BACtB;;;;;;;;;;cCGQ,kBAAkB;;;;;;;;cA4ElB,qBAAqB;;;;;;;;iBCzGZ,UAAU,KAAK,MAAG;;;;;;;;iBAkBxB,WAAW,KAAK,KAAK,MAAM;;;;;;;;cAuC9B,WAAQ,KACd,eACJ,QAAQ;;;;;;;;;;;cA0FE,WAAQ,KACd,YAAU,kBACC"}
|