@mionjs/router 0.8.3-alpha.0 → 0.8.4-alpha.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/.dist/cjs/index.cjs +2 -0
- package/.dist/cjs/index.cjs.map +1 -1
- package/.dist/cjs/src/defaultRoutes.cjs.map +1 -1
- package/.dist/cjs/src/lib/aotEmitter.cjs +4 -1
- package/.dist/cjs/src/lib/aotEmitter.cjs.map +1 -1
- package/.dist/cjs/src/lib/aotEmitter.d.ts +6 -0
- package/.dist/cjs/src/lib/reflection.cjs +10 -6
- package/.dist/cjs/src/lib/reflection.cjs.map +1 -1
- package/.dist/cjs/src/lib/reflection.d.ts +1 -1
- package/.dist/cjs/src/lib/test/aotEmitter-test-router.cjs.map +1 -1
- package/.dist/cjs/src/router.cjs +34 -4
- package/.dist/cjs/src/router.cjs.map +1 -1
- package/.dist/cjs/src/router.d.ts +2 -0
- package/.dist/cjs/src/routesFlow.cjs +3 -3
- package/.dist/cjs/src/routesFlow.cjs.map +1 -1
- package/.dist/cjs/src/types/general.cjs +1 -1
- package/.dist/cjs/src/types/general.d.ts +1 -0
- package/.dist/cjs/src/types/remoteMethods.cjs +3 -3
- package/.dist/cjs/src/types/remoteMethods.cjs.map +1 -1
- package/.dist/cjs/src/types/remoteMethods.d.ts +3 -3
- package/.dist/esm/index.js +3 -1
- package/.dist/esm/src/defaultRoutes.js.map +1 -1
- package/.dist/esm/src/lib/aotEmitter.d.ts +6 -0
- package/.dist/esm/src/lib/aotEmitter.js +4 -1
- package/.dist/esm/src/lib/aotEmitter.js.map +1 -1
- package/.dist/esm/src/lib/reflection.d.ts +1 -1
- package/.dist/esm/src/lib/reflection.js +10 -6
- package/.dist/esm/src/lib/reflection.js.map +1 -1
- package/.dist/esm/src/lib/test/aotEmitter-test-router.js.map +1 -1
- package/.dist/esm/src/router.d.ts +2 -0
- package/.dist/esm/src/router.js +35 -5
- package/.dist/esm/src/router.js.map +1 -1
- package/.dist/esm/src/routesFlow.js +1 -1
- package/.dist/esm/src/routesFlow.js.map +1 -1
- package/.dist/esm/src/types/general.d.ts +1 -0
- package/.dist/esm/src/types/general.js +1 -1
- package/.dist/esm/src/types/remoteMethods.d.ts +3 -3
- package/.dist/esm/src/types/remoteMethods.js +3 -3
- package/.dist/esm/src/types/remoteMethods.js.map +1 -1
- package/package.json +4 -4
package/.dist/cjs/index.cjs
CHANGED
|
@@ -97,6 +97,7 @@ exports.getExecutableFromMiddleFn = src_router.getExecutableFromMiddleFn;
|
|
|
97
97
|
exports.getExecutableFromRawMiddleFn = src_router.getExecutableFromRawMiddleFn;
|
|
98
98
|
exports.getExecutableFromRoute = src_router.getExecutableFromRoute;
|
|
99
99
|
exports.getMiddleFnExecutable = src_router.getMiddleFnExecutable;
|
|
100
|
+
exports.getPlatformConfig = src_router.getPlatformConfig;
|
|
100
101
|
exports.getRouteEntries = src_router.getRouteEntries;
|
|
101
102
|
exports.getRouteExecutable = src_router.getRouteExecutable;
|
|
102
103
|
exports.getRouteExecutableFromPath = src_router.getRouteExecutableFromPath;
|
|
@@ -109,6 +110,7 @@ exports.isPrivateDefinition = src_router.isPrivateDefinition;
|
|
|
109
110
|
exports.isPrivateExecutable = src_router.isPrivateExecutable;
|
|
110
111
|
exports.registerRoutes = src_router.registerRoutes;
|
|
111
112
|
exports.resetRouter = src_router.resetRouter;
|
|
113
|
+
exports.setPlatformConfig = src_router.setPlatformConfig;
|
|
112
114
|
exports.shouldFullGenerateSpec = src_router.shouldFullGenerateSpec;
|
|
113
115
|
Object.defineProperty(exports, "startMiddleFns", {
|
|
114
116
|
enumerable: true,
|
package/.dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaultRoutes.cjs","sources":["../../../src/defaultRoutes.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n/**\n * Default routes script for AOT cache generation.\n *\n * This script initializes the mion router with only the built-in internal routes\n * (error routes, metadata routes, etc.). It is used by the Vite plugin as a fallback\n * when no user-provided
|
|
1
|
+
{"version":3,"file":"defaultRoutes.cjs","sources":["../../../src/defaultRoutes.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n/**\n * Default routes script for AOT cache generation.\n *\n * This script initializes the mion router with only the built-in internal routes\n * (error routes, metadata routes, etc.). It is used by the Vite plugin as a fallback\n * when no user-provided startScript is configured.\n *\n * When run with MION_COMPILE=buildOnly, the router's emitAOTCaches() will automatically\n * collect and send the serialized caches for these internal routes via IPC.\n *\n * Internal routes included:\n * - @thrownErrors: Error serialization route\n * - mion@notFound: Not-found handler\n * - mion@platformError: Platform error handler\n * - mion@methodsMetadataById: Remote methods metadata by ID\n * - mion@methodsMetadataByPath: Remote methods metadata by path\n */\n\nimport {middleFn, initMionRouter} from '@mionjs/router';\nimport type {Routes} from '@mionjs/router';\n\nconst routes = {\n // Only required as initMionRouter needs at least one route/middleFn\n 'mion@mionEmptyMiddleFn': middleFn((): void => undefined),\n} satisfies Routes;\n\n// Initialize the router — this registers all internal routes and emits AOT caches\n// skipClientRoutes must be false to ensure metadata routes are included in AOT caches\nexport const defaultApi = initMionRouter(routes, {skipClientRoutes: false});\nexport type DefaultApi = typeof defaultApi;\n"],"names":["middleFn","initMionRouter"],"mappings":";;;;;;;AA4BA,MAAM,SAAS;AAAA;AAAA,EAEX,0BAA0BA,OAAAA,SAAQ,aAAC,MAAY,QAAS,CAAA,IAAA,MAAA,CAAA,CAAA;;AAKrD,MAAM,aAAaC,OAAAA,eAAe,QAAQ,EAAC,kBAAkB,OAAM;;;;"}
|
|
@@ -3,11 +3,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
3
3
|
const core = require("@mionjs/core");
|
|
4
4
|
const src_lib_methodsCache = require("./methodsCache.cjs");
|
|
5
5
|
const runTypes = require("@mionjs/run-types");
|
|
6
|
+
const __ΩRecord = ["K", "T", "Record", `l'e#"Rb!b"Pde"!N#!w#y`];
|
|
6
7
|
function __assignType(fn, args) {
|
|
7
8
|
fn.__type = args;
|
|
8
9
|
return fn;
|
|
9
10
|
}
|
|
10
11
|
const __ΩAOTCacheMessage = ["mion-aot-caches", "type", "jitFnsCode", "pureFnsCode", "routerCacheCode", "AOTCacheMessage", 'P.!4"&4#&4$&4%Mw&y'];
|
|
12
|
+
const __ΩPlatformReadyMessage = ["mion-platform-ready", "type", () => __ΩRecord, "routerConfig", () => __ΩRecord, "platformConfig", "PlatformReadyMessage", `P.!4"&#o##4$&#o%#4&Mw'y`];
|
|
11
13
|
const __ΩSerializedCaches = ["jitFnsCode", "pureFnsCode", "routerCacheCode", "SerializedCaches", 'P&4!&4"&4#Mw$y'];
|
|
12
14
|
const EXCLUDED_JIT_FN_IDS = [core.JIT_FUNCTION_IDS.toJSCode];
|
|
13
15
|
const EXCLUDED_PURE_FN_NAMES = ["sanitizeCompiledFn"];
|
|
@@ -20,7 +22,7 @@ getSerializedCaches.__type = [() => __ΩSerializedCaches, "getSerializedCaches",
|
|
|
20
22
|
async function emitAOTCaches() {
|
|
21
23
|
if (!core.isMionAOTEmitMode())
|
|
22
24
|
return;
|
|
23
|
-
if (core.getENV("MION_COMPILE") === "
|
|
25
|
+
if (core.getENV("MION_COMPILE") === "middleware")
|
|
24
26
|
return;
|
|
25
27
|
if (typeof process.send !== "function")
|
|
26
28
|
return;
|
|
@@ -63,6 +65,7 @@ function filterExcludedPureFns(pureFnsCache, excludedFnNames) {
|
|
|
63
65
|
}
|
|
64
66
|
filterExcludedPureFns.__type = [() => core.__ΩPureFunctionsCache, "pureFnsCache", "excludedFnNames", () => core.__ΩPureFunctionsCache, "filterExcludedPureFns", 'Pn!2"&F2#n$/%'];
|
|
65
67
|
exports.__ΩAOTCacheMessage = __ΩAOTCacheMessage;
|
|
68
|
+
exports.__ΩPlatformReadyMessage = __ΩPlatformReadyMessage;
|
|
66
69
|
exports.__ΩSerializedCaches = __ΩSerializedCaches;
|
|
67
70
|
exports.emitAOTCaches = emitAOTCaches;
|
|
68
71
|
exports.getSerializedCaches = getSerializedCaches;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aotEmitter.cjs","sources":["../../../../src/lib/aotEmitter.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport {\n getJitFnCaches,\n getENV,\n isMionAOTEmitMode,\n JitFunctionsCache,\n PureFunctionsCache,\n MethodsCache,\n SrcCodeJITCompiledFnsCache,\n SrcCodePureFunctionsCache,\n JIT_FUNCTION_IDS,\n} from '@mionjs/core';\nimport {getPersistedMethods} from './methodsCache.ts';\nimport {createToJavascriptFn} from '@mionjs/run-types';\n\n/** IPC message type for AOT cache emission */\nexport interface AOTCacheMessage {\n type: 'mion-aot-caches';\n jitFnsCode: string;\n pureFnsCode: string;\n routerCacheCode: string;\n}\n\n/** Serialized cache data before converting to JS code */\nexport interface SerializedCaches {\n jitFnsCode: string;\n pureFnsCode: string;\n routerCacheCode: string;\n}\n\n/** JIT function IDs to exclude from AOT caches (toJSCode is only needed at compile time) */\nconst EXCLUDED_JIT_FN_IDS = [JIT_FUNCTION_IDS.toJSCode];\n\n/** Pure function names to exclude from AOT caches */\nconst EXCLUDED_PURE_FN_NAMES = ['sanitizeCompiledFn'];\n\n/** Returns serialized caches for in-process AOT generation (no IPC needed). Call after initMionRouter(). */\nexport async function getSerializedCaches(): Promise<SerializedCaches> {\n const {jitFnsCache, pureFnsCache} = getJitFnCaches();\n const routerCache = getPersistedMethods();\n return serializeCachesToCode(jitFnsCache, pureFnsCache, routerCache);\n}\n\n/**\n * Emits AOT caches to the parent process via IPC when running in MION_COMPILE mode.\n * This function is called automatically at the end of initMionRouter() and can also\n * be called manually for multi-step route registration patterns.\n */\nexport async function emitAOTCaches(): Promise<void> {\n // Only emit in AOT generation mode (compile, SSR, or serve)\n if (!isMionAOTEmitMode()) return;\n //
|
|
1
|
+
{"version":3,"file":"aotEmitter.cjs","sources":["../../../../src/lib/aotEmitter.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport {\n getJitFnCaches,\n getENV,\n isMionAOTEmitMode,\n JitFunctionsCache,\n PureFunctionsCache,\n MethodsCache,\n SrcCodeJITCompiledFnsCache,\n SrcCodePureFunctionsCache,\n JIT_FUNCTION_IDS,\n} from '@mionjs/core';\nimport {getPersistedMethods} from './methodsCache.ts';\nimport {createToJavascriptFn} from '@mionjs/run-types';\n\n/** IPC message type for AOT cache emission */\nexport interface AOTCacheMessage {\n type: 'mion-aot-caches';\n jitFnsCode: string;\n pureFnsCode: string;\n routerCacheCode: string;\n}\n\n/** IPC message sent by setPlatformConfig() to signal server readiness */\nexport interface PlatformReadyMessage {\n type: 'mion-platform-ready';\n routerConfig: Record<string, unknown>;\n platformConfig: Record<string, unknown>;\n}\n\n/** Serialized cache data before converting to JS code */\nexport interface SerializedCaches {\n jitFnsCode: string;\n pureFnsCode: string;\n routerCacheCode: string;\n}\n\n/** JIT function IDs to exclude from AOT caches (toJSCode is only needed at compile time) */\nconst EXCLUDED_JIT_FN_IDS = [JIT_FUNCTION_IDS.toJSCode];\n\n/** Pure function names to exclude from AOT caches */\nconst EXCLUDED_PURE_FN_NAMES = ['sanitizeCompiledFn'];\n\n/** Returns serialized caches for in-process AOT generation (no IPC needed). Call after initMionRouter(). */\nexport async function getSerializedCaches(): Promise<SerializedCaches> {\n const {jitFnsCache, pureFnsCache} = getJitFnCaches();\n const routerCache = getPersistedMethods();\n return serializeCachesToCode(jitFnsCache, pureFnsCache, routerCache);\n}\n\n/**\n * Emits AOT caches to the parent process via IPC when running in MION_COMPILE mode.\n * This function is called automatically at the end of initMionRouter() and can also\n * be called manually for multi-step route registration patterns.\n */\nexport async function emitAOTCaches(): Promise<void> {\n // Only emit in AOT generation mode (compile, SSR, or serve)\n if (!isMionAOTEmitMode()) return;\n // middleware mode: caches remain in global state, read directly via getSerializedCaches()\n if (getENV('MION_COMPILE') === 'middleware') return;\n\n // IPC mode: send to parent process\n if (typeof process.send !== 'function') return;\n\n // Get the caches\n const {jitFnsCache, pureFnsCache} = getJitFnCaches();\n const routerCache = getPersistedMethods();\n\n // Serialize caches to JS code (filtering happens inside, after createToJavascriptFn)\n const serialized = await serializeCachesToCode(jitFnsCache, pureFnsCache, routerCache);\n\n // Send to parent process\n const message: AOTCacheMessage = {\n type: 'mion-aot-caches',\n ...serialized,\n };\n\n process.send(message);\n}\n\n/**\n * Serializes the caches to JavaScript code strings using run-types toJSCode.\n * Filtering is done AFTER createToJavascriptFn because it adds compile-time-only JIT functions\n * to the global caches that should be excluded from the serialized output.\n */\nexport async function serializeCachesToCode(\n jitFnsCache: JitFunctionsCache,\n pureFnsCache: PureFunctionsCache,\n routerCache: MethodsCache\n): Promise<SerializedCaches> {\n const jitToJSCode = createToJavascriptFn<SrcCodeJITCompiledFnsCache>();\n const pureToJSCode = createToJavascriptFn<SrcCodePureFunctionsCache>();\n const routerToJSCode = createToJavascriptFn<MethodsCache>();\n // Filter AFTER createToJavascriptFn to exclude compile-time-only items (including those just added)\n const finalJitFns = filterExcludedJitFns(jitFnsCache, EXCLUDED_JIT_FN_IDS);\n const finalPureFns = filterExcludedPureFns(pureFnsCache, EXCLUDED_PURE_FN_NAMES);\n return {\n jitFnsCode: jitToJSCode(finalJitFns as unknown as SrcCodeJITCompiledFnsCache),\n pureFnsCode: pureToJSCode(finalPureFns as unknown as SrcCodePureFunctionsCache),\n routerCacheCode: routerToJSCode(routerCache),\n };\n}\n\n/**\n * Filters out excluded JIT functions by their function ID.\n * toJSCode is excluded because it's only needed at compile time.\n */\nfunction filterExcludedJitFns(jitFnsCache: JitFunctionsCache, excludedFnIds: string[]): JitFunctionsCache {\n if (!excludedFnIds.length) return jitFnsCache;\n return Object.fromEntries(\n Object.entries(jitFnsCache).filter(([, value]) => !excludedFnIds.includes(value.fnID as string))\n ) as JitFunctionsCache;\n}\n\n/**\n * Filters out excluded pure functions by their function name.\n * sanitizeCompiledFn is excluded because it's only needed at compile time.\n */\nfunction filterExcludedPureFns(pureFnsCache: PureFunctionsCache, excludedFnNames: string[]): PureFunctionsCache {\n if (!excludedFnNames.length) return pureFnsCache;\n return Object.fromEntries(\n Object.entries(pureFnsCache).map(([namespace, nsCache]) => [\n namespace,\n Object.fromEntries(Object.entries(nsCache).filter(([, value]) => !excludedFnNames.includes(value.fnName))),\n ])\n ) as PureFunctionsCache;\n}\n"],"names":["JIT_FUNCTION_IDS","getJitFnCaches","getPersistedMethods","isMionAOTEmitMode","getENV","createToJavascriptFn"],"mappings":";;;;;;;;;;;;;AA4CA,MAAM,sBAAsB,CAACA,KAAAA,iBAAiB,QAAQ;AAGtD,MAAM,yBAAyB,CAAC,oBAAoB;AAGpD,eAAsB,sBAAmB;AACrC,QAAM,EAAC,aAAa,aAAA,IAAgBC,oBAAA;AACpC,QAAM,cAAcC,qBAAAA,oBAAA;AACpB,SAAO,sBAAsB,aAAa,cAAc,WAAW;AACvE;;AAOA,eAAsB,gBAAa;AAE/B,MAAI,CAACC,KAAAA,kBAAA;AAAqB;AAE1B,MAAIC,KAAAA,OAAO,cAAc,MAAM;AAAc;AAG7C,MAAI,OAAO,QAAQ,SA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@@ -5,6 +5,11 @@ export interface AOTCacheMessage {
|
|
|
5
5
|
pureFnsCode: string;
|
|
6
6
|
routerCacheCode: string;
|
|
7
7
|
}
|
|
8
|
+
export interface PlatformReadyMessage {
|
|
9
|
+
type: 'mion-platform-ready';
|
|
10
|
+
routerConfig: Record<string, unknown>;
|
|
11
|
+
platformConfig: Record<string, unknown>;
|
|
12
|
+
}
|
|
8
13
|
export interface SerializedCaches {
|
|
9
14
|
jitFnsCode: string;
|
|
10
15
|
pureFnsCode: string;
|
|
@@ -14,4 +19,5 @@ export declare function getSerializedCaches(): Promise<SerializedCaches>;
|
|
|
14
19
|
export declare function emitAOTCaches(): Promise<void>;
|
|
15
20
|
export declare function serializeCachesToCode(jitFnsCache: JitFunctionsCache, pureFnsCache: PureFunctionsCache, routerCache: MethodsCache): Promise<SerializedCaches>;
|
|
16
21
|
export declare type __ΩAOTCacheMessage = any[];
|
|
22
|
+
export declare type __ΩPlatformReadyMessage = any[];
|
|
17
23
|
export declare type __ΩSerializedCaches = any[];
|
|
@@ -126,16 +126,16 @@ function extractReflectionFromCached(cached) {
|
|
|
126
126
|
return reflectionItems;
|
|
127
127
|
}
|
|
128
128
|
extractReflectionFromCached.__type = [() => __ΩCachedMethodMetadata, "cached", () => __ΩMethodReflect, "extractReflectionFromCached", 'Pn!2"n#/$'];
|
|
129
|
-
async function getHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn = false) {
|
|
129
|
+
async function getHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn = false, methodStrictTypes) {
|
|
130
130
|
const cached = src_lib_methodsCache.getPersistedMethodMetadata(routeId);
|
|
131
131
|
if (cached)
|
|
132
132
|
return extractReflectionFromCached(cached);
|
|
133
133
|
if (routerOptions.aot)
|
|
134
134
|
throw new AOTCacheError(routeId, isHeadersMiddleFn ? "middleFn" : "route");
|
|
135
135
|
const rt = await loadRunTypesModule();
|
|
136
|
-
return generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt);
|
|
136
|
+
return generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt, methodStrictTypes);
|
|
137
137
|
}
|
|
138
|
-
getHandlerReflection.__type = [() => src_types_handlers.__ΩHandler, "handler", "routeId", () => src_types_general.__ΩRouterOptions, "routerOptions", "isHeadersMiddleFn", () => false, () => __ΩMethodReflect, "getHandlerReflection", "Pn!2\"&2#n$2%)2&>'
|
|
138
|
+
getHandlerReflection.__type = [() => src_types_handlers.__ΩHandler, "handler", "routeId", () => src_types_general.__ΩRouterOptions, "routerOptions", "isHeadersMiddleFn", () => false, "methodStrictTypes", () => __ΩMethodReflect, "getHandlerReflection", "Pn!2\"&2#n$2%)2&>')2(8n)`/*"];
|
|
139
139
|
async function getRawMethodReflection(handler, routeId, routerOptions) {
|
|
140
140
|
const cached = src_lib_methodsCache.getPersistedMethodMetadata(routeId);
|
|
141
141
|
if (cached)
|
|
@@ -146,10 +146,14 @@ async function getRawMethodReflection(handler, routeId, routerOptions) {
|
|
|
146
146
|
return generateRawMethodReflection(handler, routeId, rt);
|
|
147
147
|
}
|
|
148
148
|
getRawMethodReflection.__type = [() => src_types_handlers.__ΩHandler, "handler", "routeId", () => src_types_general.__ΩRouterOptions, "routerOptions", () => __ΩMethodReflect, "getRawMethodReflection", "Pn!2\"&2#n$2%n&`/'"];
|
|
149
|
-
function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt) {
|
|
149
|
+
function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt, methodStrictTypes) {
|
|
150
150
|
const reflectionItems = {};
|
|
151
151
|
let handlerRunType;
|
|
152
|
-
const
|
|
152
|
+
const effectiveStrictTypes = methodStrictTypes ?? routerOptions.strictTypes;
|
|
153
|
+
const runTypeOptions = {
|
|
154
|
+
...routerOptions?.runTypeOptions || src_constants.DEFAULT_ROUTE_OPTIONS.runTypeOptions,
|
|
155
|
+
...effectiveStrictTypes !== void 0 ? { strictTypes: effectiveStrictTypes } : {}
|
|
156
|
+
};
|
|
153
157
|
try {
|
|
154
158
|
handlerRunType = rt.reflectFunction(handler);
|
|
155
159
|
} catch (error) {
|
|
@@ -208,7 +212,7 @@ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMid
|
|
|
208
212
|
reflectionItems.isAsync = handlerRunType.isAsync();
|
|
209
213
|
return reflectionItems;
|
|
210
214
|
}
|
|
211
|
-
generateHandlerReflection.__type = [() => src_types_handlers.__ΩHandler, "handler", "routeId", () => src_types_general.__ΩRouterOptions, "routerOptions", "isHeadersMiddleFn", () => __ΩRunTypesFunctions, "rt", () => __ΩMethodReflect, "generateHandlerReflection", `Pn!2"&2#n$2%)2&n'2(
|
|
215
|
+
generateHandlerReflection.__type = [() => src_types_handlers.__ΩHandler, "handler", "routeId", () => src_types_general.__ΩRouterOptions, "routerOptions", "isHeadersMiddleFn", () => __ΩRunTypesFunctions, "rt", "methodStrictTypes", () => __ΩMethodReflect, "generateHandlerReflection", `Pn!2"&2#n$2%)2&n'2()2)8n*/+`];
|
|
212
216
|
function generateRawMethodReflection(handler, routeId, rt) {
|
|
213
217
|
let handlerRunType;
|
|
214
218
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reflection.cjs","sources":["../../../../src/lib/reflection.ts"],"sourcesContent":["/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {MethodWithJitFns, AnyFn, JitCompiledFunctions, MethodMetadata} from '@mionjs/core';\n// Type-only imports from run-types - these don't load the module at runtime\nimport type {FunctionRunType, BaseRunType, MemberRunType, RunTypeOptions, JitFnCompiler} from '@mionjs/run-types';\nimport {Handler} from '../types/handlers.ts';\nimport {RouterOptions} from '../types/general.ts';\nimport {DEFAULT_ROUTE_OPTIONS, HEADER_HOOK_DEFAULT_PARAMS, ROUTE_DEFAULT_PARAMS} from '../constants.ts';\nimport {EMPTY_HASH, HeadersSubset, getJitFunctionsFromHash, getNoopJitFns} from '@mionjs/core';\nimport {getPersistedMethodMetadata} from './methodsCache.ts';\n\n// ############ This file is the only one importing '@mionjs/run-types' within the router ########\n// In AOT mode, run-types is NOT loaded - all reflection data comes from the AOT cache\n\ntype MethodReflect = Omit<MethodWithJitFns, 'id' | 'type' | 'nestLevel' | 'pointer' | 'options'>;\n\n// ############ AOT Cache Error ############\n\n/**\n * Error thrown when AOT mode is enabled but required data is missing from the AOT cache.\n * This indicates that the AOT caches need to be regenerated using 'mion-build-aot' command.\n */\nexport class AOTCacheError extends Error {\n constructor(routeId: string, type: 'route' | 'middleFn' | 'rawMiddleFn' = 'route') {\n const typeLabel = type === 'rawMiddleFn' ? 'Raw middleFn' : type === 'middleFn' ? 'MiddleFn' : 'Route/middleFn';\n super(`${typeLabel} \"${routeId}\" not found in AOT cache.\\n` + `Regenerate AOT caches using 'mion-build-aot' command.`);\n this.name = 'AOTCacheError';\n }\n}\n\n// ############ Run-Types Module Loading ############\ntype RunTypesModule = typeof import('@mionjs/run-types');\n// Type definition for the dynamically imported run-types module\ninterface RunTypesFunctions {\n JitFunctions: RunTypesModule['JitFunctions'];\n reflectFunction: RunTypesModule['reflectFunction'];\n isUnionRunType: RunTypesModule['isUnionRunType'];\n isClassRunType: RunTypesModule['isClassRunType'];\n isLiteralRunType: RunTypesModule['isLiteralRunType'];\n isNeverRunType: RunTypesModule['isNeverRunType'];\n}\n\n// Cached run-types module - loaded once and reused\nlet runTypesModule: RunTypesFunctions | null = null;\nlet runTypesLoadPromise: Promise<RunTypesFunctions> | null = null;\n\n/** Dynamically loads the @mionjs/run-types module. The module is cached after first load. */\nasync function loadRunTypesModule(): Promise<RunTypesFunctions> {\n // Return cached module if already loaded\n if (runTypesModule) return runTypesModule;\n\n // Return existing promise if load is in progress\n if (runTypesLoadPromise) return runTypesLoadPromise;\n\n // Start loading the module\n runTypesLoadPromise = import('@mionjs/run-types').then((module) => {\n runTypesModule = {\n JitFunctions: module.JitFunctions,\n reflectFunction: module.reflectFunction,\n isUnionRunType: module.isUnionRunType,\n isClassRunType: module.isClassRunType,\n isLiteralRunType: module.isLiteralRunType,\n isNeverRunType: module.isNeverRunType,\n };\n return runTypesModule;\n });\n\n return runTypesLoadPromise;\n}\n\n/** Resets the run-types module cache. Useful for testing purposes only. */\nexport function resetRunTypesCache(): void {\n runTypesModule = null;\n runTypesLoadPromise = null;\n}\n\n/** Resets all reflection caches. Useful for testing purposes only. */\nexport function resetReflectionCaches(): void {\n rawMiddleFnReflectionCache.clear();\n // Note: functionRunTypeCache uses WeakMap so it doesn't need explicit clearing\n // Note: _cachedReflection on MethodMetadata objects will be cleared when persistedMethods is reset\n}\n\n// ############ Raw MiddleFn Reflection Helper ############\n\n// Cache for common raw middleFn reflections\nconst rawMiddleFnReflectionCache = new Map<string, MethodReflect>();\n\n/**\n * Creates a MethodReflect for raw middleFns.\n * Raw middleFns don't need JIT functions - they always use NoopJitFns.\n * Results are cached to avoid creating duplicate objects.\n */\nfunction createRawMiddleFnReflection(isAsync: boolean, hasReturnData: boolean = false, paramNames: string[] = []): MethodReflect {\n // Create cache key from parameters\n const cacheKey = `${isAsync}_${hasReturnData}_${paramNames.join(',')}`;\n\n const cached = rawMiddleFnReflectionCache.get(cacheKey);\n if (cached) return cached;\n\n const reflection: MethodReflect = {\n paramNames,\n paramsJitFns: getNoopJitFns(),\n returnJitFns: getNoopJitFns(),\n paramsJitHash: EMPTY_HASH,\n returnJitHash: EMPTY_HASH,\n hasReturnData,\n isAsync,\n };\n\n rawMiddleFnReflectionCache.set(cacheKey, reflection);\n return reflection;\n}\n\n// ############ AOT Cache Extraction ############\n\n// Extend MethodMetadata type to include cached reflection\ntype CachedMethodMetadata = MethodMetadata & {\n _cachedReflection?: MethodReflect;\n};\n\n/**\n * Extracts reflection data from a cached method.\n * Used in AOT mode to restore method reflection without loading run-types.\n * Results are cached on the metadata object to avoid creating duplicate objects.\n */\nfunction extractReflectionFromCached(cached: CachedMethodMetadata): MethodReflect {\n // Return cached reflection if available\n if (cached._cachedReflection) return cached._cachedReflection;\n\n const reflectionItems: MethodReflect = {\n paramNames: cached.paramNames || [],\n paramsJitFns: getJitFunctionsFromHash(cached.paramsJitHash),\n returnJitFns: getJitFunctionsFromHash(cached.returnJitHash),\n paramsJitHash: cached.paramsJitHash,\n returnJitHash: cached.returnJitHash,\n hasReturnData: cached.hasReturnData,\n isAsync: cached.isAsync,\n };\n\n // Restore headers param if present\n if (cached.headersParam) {\n reflectionItems.headersParam = {\n headerNames: cached.headersParam.headerNames,\n jitFns: getJitFunctionsFromHash(cached.headersParam.jitHash) as Pick<JitCompiledFunctions, 'isType' | 'typeErrors'>,\n jitHash: cached.headersParam.jitHash,\n };\n }\n\n // Restore headers return if present\n if (cached.headersReturn) {\n reflectionItems.headersReturn = {\n headerNames: cached.headersReturn.headerNames,\n jitFns: getJitFunctionsFromHash(cached.headersReturn.jitHash) as Pick<JitCompiledFunctions, 'isType' | 'typeErrors'>,\n jitHash: cached.headersReturn.jitHash,\n };\n }\n\n // Cache for future calls\n cached._cachedReflection = reflectionItems;\n return reflectionItems;\n}\n\n// ############ Main Reflection Functions ############\n\n/**\n * Gets reflection data for a handler (route or middleFn).\n * In AOT mode, returns cached data without loading run-types.\n * In non-AOT mode, dynamically loads run-types and generates reflection.\n * Throws AOTCacheError if AOT mode is enabled and route is not in cache.\n */\nexport async function getHandlerReflection(\n handler: Handler,\n routeId: string,\n routerOptions: RouterOptions,\n isHeadersMiddleFn: boolean = false\n): Promise<MethodReflect> {\n // Check AOT cache first\n const cached = getPersistedMethodMetadata(routeId);\n if (cached) return extractReflectionFromCached(cached);\n if (routerOptions.aot) throw new AOTCacheError(routeId, isHeadersMiddleFn ? 'middleFn' : 'route');\n // Non-AOT mode: dynamically load run-types and generate reflection\n const rt = await loadRunTypesModule();\n return generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt);\n}\n\n/**\n * Gets reflection data for a raw middleFn.\n * Raw middleFns don't use full reflection - they don't need JIT functions.\n * Raw middleFns don't NEED to be in the AOT cache, but if they are, we can use\n * the cached data (especially the isAsync flag).\n * In AOT mode, this function does NOT load run-types.\n */\nexport async function getRawMethodReflection(\n handler: Handler,\n routeId: string,\n routerOptions: RouterOptions\n): Promise<MethodReflect> {\n // Check if raw middleFn is in cache - if so, use cached data (especially isAsync)\n const cached = getPersistedMethodMetadata(routeId);\n if (cached) return createRawMiddleFnReflection(cached.isAsync, cached.hasReturnData, cached.paramNames || []);\n // Raw middleFns don't need JIT functions, so we don't need to load run-types in AOT mode\n if (routerOptions.aot) return createRawMiddleFnReflection(true);\n // Non-AOT mode: dynamically load run-types to properly detect if handler is async\n const rt = await loadRunTypesModule();\n return generateRawMethodReflection(handler, routeId, rt);\n}\n\n// ############ Reflection Generation (requires run-types) ############\n\n/**\n * Generates reflection data for a handler using run-types.\n * This function is only called in non-AOT mode.\n */\nfunction generateHandlerReflection(\n handler: Handler,\n routeId: string,\n routerOptions: RouterOptions,\n isHeadersMiddleFn: boolean,\n rt: RunTypesFunctions\n): MethodReflect {\n const reflectionItems: Partial<MethodReflect> = {};\n let handlerRunType: FunctionRunType;\n const runTypeOptions = routerOptions?.runTypeOptions || DEFAULT_ROUTE_OPTIONS.runTypeOptions;\n try {\n handlerRunType = rt.reflectFunction(handler);\n } catch (error: any) {\n throw new Error(`Can not get RunType of handler for route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n const paramsSlice = isHeadersMiddleFn ? {start: HEADER_HOOK_DEFAULT_PARAMS.length} : {start: ROUTE_DEFAULT_PARAMS.length};\n const paramsOpts: RunTypeOptions = {...runTypeOptions, paramsSlice};\n\n try {\n reflectionItems.paramNames = handlerRunType.getParameterNames(paramsOpts);\n // Skip JIT generation if handler has no params (optimization for AOT cache size)\n if (reflectionItems.paramNames.length === 0) {\n reflectionItems.paramsJitHash = EMPTY_HASH;\n reflectionItems.paramsJitFns = getNoopJitFns();\n } else {\n reflectionItems.paramsJitFns = getFunctionJitFns(handler, paramsOpts, rt, false);\n reflectionItems.paramsJitHash = handlerRunType.getParameters().getJitHash(paramsOpts);\n }\n } catch (error: any) {\n throw new Error(`Can not compile Jit Functions for Parameters of route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n\n if (isHeadersMiddleFn) {\n const headersRunType = getParamsHeadersRunType(handlerRunType, routeId, routerOptions, rt);\n const headerNames: string[] = getHeaderNames(headersRunType, routeId, rt);\n\n try {\n const opts: RunTypeOptions = {\n ...runTypeOptions,\n paramsSlice: undefined,\n };\n\n const jitFns: JitCompiledFunctions = getTypeJitFunctions(headersRunType, opts, rt);\n const jitHash = headersRunType.getJitHash(opts);\n reflectionItems.headersParam = {headerNames, jitFns, jitHash};\n } catch (error: any) {\n throw new Error(\n `Can not compile Jit Functions for Headers of Headers MiddleFn \"${routeId}.\" Error: ${error?.message}`\n );\n }\n }\n\n const returnHeadersRunType = getReturnHeadersRunType(handlerRunType, rt);\n if (returnHeadersRunType) {\n const opts: RunTypeOptions = {};\n const headerNames: string[] = getHeaderNames(returnHeadersRunType, routeId, rt);\n const jitFns: JitCompiledFunctions = getFunctionJitFns(handler, opts, rt, true);\n const jitHash: string = returnHeadersRunType.getJitHash(opts);\n reflectionItems.headersReturn = {headerNames, jitFns, jitHash};\n }\n\n const returnOpts: RunTypeOptions = runTypeOptions;\n // If the return type is HeadersSubset or if it's a headersFn with array return, don't treat it as return data\n reflectionItems.hasReturnData = handlerRunType.hasReturnData();\n\n try {\n // Skip JIT generation if handler has void return (optimization for AOT cache size)\n if (!reflectionItems.hasReturnData) {\n reflectionItems.returnJitFns = getNoopJitFns();\n reflectionItems.returnJitHash = EMPTY_HASH;\n } else {\n // returnJitFns contains all run type functionality for the return value, it compiles when the property is first accessed\n reflectionItems.returnJitFns = getFunctionJitFns(handler, returnOpts, rt, true);\n reflectionItems.returnJitHash = handlerRunType.getReturnType().getJitHash(returnOpts);\n }\n } catch (error: any) {\n throw new Error(`Can not get Jit Functions for Return of route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n\n reflectionItems.isAsync = handlerRunType.isAsync();\n\n return reflectionItems as MethodReflect;\n}\n\n/**\n * Generates reflection data for a raw middleFn using run-types.\n * This function is only called in non-AOT mode.\n */\nfunction generateRawMethodReflection(handler: Handler, routeId: string, rt: RunTypesFunctions): MethodReflect {\n let handlerRunType: FunctionRunType;\n try {\n handlerRunType = rt.reflectFunction(handler);\n } catch (error: any) {\n throw new Error(`Can not get RunType of handler for route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n const isAsync = handlerRunType?.isAsync() || true;\n return createRawMiddleFnReflection(isAsync);\n}\n\n// ############ Helper Functions (require run-types module) ############\n\nfunction getParamsHeadersRunType(\n handlerRunType: FunctionRunType,\n routeId: string,\n routerOptions: RouterOptions,\n rt: RunTypesFunctions\n): BaseRunType {\n const paramRunTypes = handlerRunType.getParameters().getParamRunTypes(getFakeCompiler(routerOptions));\n const headersSubset = (paramRunTypes[1] as MemberRunType<any>)?.getMemberType?.(); // HeadersSubset is always index 1 after context\n\n if (!isHeaderSubSetRunType(headersSubset, rt)) {\n throw new Error(`Headers MiddleFn '${routeId}' second parameter must be a HeadersSubset.`);\n }\n return headersSubset;\n}\n\nfunction getReturnHeadersRunType(handlerRunType: FunctionRunType, rt: RunTypesFunctions): BaseRunType | undefined {\n const returnRunType = handlerRunType.getReturnType();\n if (rt.isUnionRunType(returnRunType)) {\n const headersSubset = returnRunType.getChildRunTypes().find((child) => isHeaderSubSetRunType(child, rt));\n if (!headersSubset) return undefined;\n return headersSubset;\n }\n if (!isHeaderSubSetRunType(returnRunType, rt)) return undefined;\n return returnRunType;\n}\n\nfunction isHeaderSubSetRunType(runType: BaseRunType | undefined, rt: RunTypesFunctions): runType is BaseRunType {\n if (!runType) return false;\n return rt.isClassRunType(runType, HeadersSubset);\n}\n\nfunction getHeaderNames(runType: BaseRunType, routeId: string, rt: RunTypesFunctions): string[] {\n // HeadersSubset is a generic class: HeadersSubset<Required, Optional>\n // We need to extract the literal string values from the Required and Optional type arguments\n // Use 'typeArguments' (not 'arguments') to get both Required and Optional with their defaults\n const typeArguments = (runType.src as any).typeArguments;\n if (!typeArguments || typeArguments.length === 0) {\n throw new Error(`HeadersSubset must have type arguments in route/middleFn ${routeId}`);\n }\n const headerNames: string[] = [];\n // Extract header names from Required type argument (first argument)\n const requiredArg = typeArguments[0];\n if (requiredArg) {\n const requiredNames = extractLiteralStringsFromType(requiredArg._rt, rt);\n headerNames.push(...requiredNames);\n }\n // Extract header names from Optional type argument (second argument, if present)\n if (typeArguments.length > 1) {\n const optionalArg = typeArguments[1];\n if (optionalArg) {\n const optionalNames = extractLiteralStringsFromType(optionalArg._rt, rt);\n headerNames.push(...optionalNames);\n }\n }\n if (headerNames.length === 0) throw new Error(`Header names array cannot be empty in route/middleFn ${routeId}`);\n return headerNames;\n}\n\n/**\n * Internal recursive function to extract literal string values from a type.\n * Handles single literal strings and union types (including nested unions).\n */\nfunction extractLiteralStringsFromTypeRecursive(runType: BaseRunType, rt: RunTypesFunctions): string[] {\n // Handle single literal string\n if (rt.isLiteralRunType(runType)) {\n const literal = (runType as any).getLiteralValue();\n if (typeof literal === 'string') {\n return [literal];\n }\n return [];\n }\n\n // Handle union of literal strings (recursively for nested unions)\n if (rt.isUnionRunType(runType)) {\n const children = runType.getChildRunTypes();\n const literals: string[] = [];\n for (const child of children) {\n // Recursively extract from each child (handles nested unions)\n const childLiterals = extractLiteralStringsFromTypeRecursive(child, rt);\n literals.push(...childLiterals);\n }\n return literals;\n }\n\n return [];\n}\n\n/**\n * Extracts literal string values from a type.\n * Handles 'never' type only at the root level, then delegates to recursive extraction.\n */\nfunction extractLiteralStringsFromType(runType: BaseRunType, rt: RunTypesFunctions): string[] {\n // Handle 'never' type at root level only (no headers)\n if (rt.isNeverRunType(runType)) return [];\n return extractLiteralStringsFromTypeRecursive(runType, rt);\n}\n\n// Create a fake compiler object with just the opts property needed by getParamRunTypes.\n// getParamRunTypes() requires a JitFnCompiler but we only need the opts property to slice parameters.\n// This is a workaround to avoid updating getParamRunTypes() signature\nfunction getFakeCompiler(routerOptions: RouterOptions): JitFnCompiler {\n return {opts: routerOptions} as any as JitFnCompiler;\n}\n\nfunction getTypeJitFunctions(\n runType: BaseRunType,\n opts: RunTypeOptions | undefined,\n rtModule: RunTypesFunctions\n): JitCompiledFunctions {\n const jitFns: JitCompiledFunctions = {\n isType: runType.createJitCompiledFunction(rtModule.JitFunctions.isType.id, undefined, opts),\n typeErrors: runType.createJitCompiledFunction(rtModule.JitFunctions.typeErrors.id, undefined, opts),\n prepareForJson: runType.createJitCompiledFunction(rtModule.JitFunctions.prepareForJson.id, undefined, opts),\n restoreFromJson: runType.createJitCompiledFunction(rtModule.JitFunctions.restoreFromJson.id, undefined, opts),\n stringifyJson: runType.createJitCompiledFunction(rtModule.JitFunctions.stringifyJson.id, undefined, opts),\n toBinary: runType.createJitCompiledFunction(rtModule.JitFunctions.toBinary.id, undefined, opts),\n fromBinary: runType.createJitCompiledFunction(rtModule.JitFunctions.fromBinary.id, undefined, opts),\n };\n return jitFns;\n}\n\n// Cache for function RunTypes to avoid duplicate reflectFunction calls\nconst functionRunTypeCache = new WeakMap<AnyFn, FunctionRunType>();\n\nfunction getFunctionJitFns<Fn extends AnyFn>(\n fn: Fn,\n opts: RunTypeOptions | undefined,\n rtModule: RunTypesFunctions,\n isReturn: boolean\n): JitCompiledFunctions {\n // Check cache first\n let runType = functionRunTypeCache.get(fn);\n if (!runType) {\n runType = rtModule.reflectFunction(fn);\n functionRunTypeCache.set(fn, runType);\n }\n\n const createFn = isReturn\n ? runType.createJitCompiledReturnFunction.bind(runType)\n : runType.createJitCompiledParamsFunction.bind(runType);\n const jitFunctions: JitCompiledFunctions = {\n isType: createFn(rtModule.JitFunctions.isType, opts),\n typeErrors: createFn(rtModule.JitFunctions.typeErrors, opts),\n prepareForJson: createFn(rtModule.JitFunctions.prepareForJson, opts),\n restoreFromJson: createFn(rtModule.JitFunctions.restoreFromJson, opts),\n stringifyJson: createFn(rtModule.JitFunctions.stringifyJson, opts),\n toBinary: createFn(rtModule.JitFunctions.toBinary, opts),\n fromBinary: createFn(rtModule.JitFunctions.fromBinary, opts),\n };\n return jitFunctions;\n}\n\n// ############ Null JIT Functions ############\n"],"names":["module","getNoopJitFns","EMPTY_HASH","getJitFunctionsFromHash","getPersistedMethodMetadata","DEFAULT_ROUTE_OPTIONS","HEADER_HOOK_DEFAULT_PARAMS","ROUTE_DEFAULT_PARAMS","HeadersSubset"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BM,MAAO,sBAAsB,MAAK;AAAA,EACpC,YAAY,SAAiB,OAA6C,SAAO;AAC7E,UAAM,YAAY,SAAS,gBAAgB,iBAAiB,SAAS,aAAa,aAAa;AAC/F,UAAM,GAAG,SAAS,KAAK,OAAO;AAAA,sDAAuF;AACrH,SAAK,OAAO;AAAA,EAChB;AAAA;;;;AAgBJ,IAAI,iBAA2C;AAC/C,IAAI,sBAAyD;AAG7D,eAAe,qBAAkB;AAE7B,MAAI;AAAgB,WAAO;AAG3B,MAAI;AAAqB,WAAO;AAGhC,wBAAsB,OAAO,mBAAmB,EAAE,KAAI,aAAC,CAACA,YAAU;AAC9D,qBAAiB;AAAA,MACb,cAAcA,QAAO;AAAA,MACrB,iBAAiBA,QAAO;AAAA,MACxB,gBAAgBA,QAAO;AAAA,MACvB,gBAAgBA,QAAO;AAAA,MACvB,kBAAkBA,QAAO;AAAA,MACzB,gBAAgBA,QAAO;AAAA,IAAA;AAE3B,WAAO;AAAA,EACX;AAEA,SAAO;AACX;;SAGgB,qBAAkB;AAC9B,mBAAiB;AACjB,wBAAsB;AAC1B;;SAGgB,wBAAqB;AACjC,6BAA2B,MAAA;AAG/B;;AAKA,MAAM,8BAAiC,IAAG,IAAA,CAAA,CAAA,GAAA,GAAA,CAAA,MAAA,kBAAA,IAAA,CAAA,uBAAH,IAAA;AAOvC,SAAS,4BAA4B,SAAkB,gBAAyB,OAAO,aAAuB,CAAA,GAAE;AAE5G,QAAM,WAA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\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {MethodWithJitFns, AnyFn, JitCompiledFunctions, MethodMetadata} from '@mionjs/core';\n// Type-only imports from run-types - these don't load the module at runtime\nimport type {FunctionRunType, BaseRunType, MemberRunType, RunTypeOptions, JitFnCompiler} from '@mionjs/run-types';\nimport {Handler} from '../types/handlers.ts';\nimport {RouterOptions} from '../types/general.ts';\nimport {DEFAULT_ROUTE_OPTIONS, HEADER_HOOK_DEFAULT_PARAMS, ROUTE_DEFAULT_PARAMS} from '../constants.ts';\nimport {EMPTY_HASH, HeadersSubset, getJitFunctionsFromHash, getNoopJitFns} from '@mionjs/core';\nimport {getPersistedMethodMetadata} from './methodsCache.ts';\n\n// ############ This file is the only one importing '@mionjs/run-types' within the router ########\n// In AOT mode, run-types is NOT loaded - all reflection data comes from the AOT cache\n\ntype MethodReflect = Omit<MethodWithJitFns, 'id' | 'type' | 'nestLevel' | 'pointer' | 'options'>;\n\n// ############ AOT Cache Error ############\n\n/**\n * Error thrown when AOT mode is enabled but required data is missing from the AOT cache.\n * This indicates that the AOT caches need to be regenerated using 'mion-build-aot' command.\n */\nexport class AOTCacheError extends Error {\n constructor(routeId: string, type: 'route' | 'middleFn' | 'rawMiddleFn' = 'route') {\n const typeLabel = type === 'rawMiddleFn' ? 'Raw middleFn' : type === 'middleFn' ? 'MiddleFn' : 'Route/middleFn';\n super(`${typeLabel} \"${routeId}\" not found in AOT cache.\\n` + `Regenerate AOT caches using 'mion-build-aot' command.`);\n this.name = 'AOTCacheError';\n }\n}\n\n// ############ Run-Types Module Loading ############\ntype RunTypesModule = typeof import('@mionjs/run-types');\n// Type definition for the dynamically imported run-types module\ninterface RunTypesFunctions {\n JitFunctions: RunTypesModule['JitFunctions'];\n reflectFunction: RunTypesModule['reflectFunction'];\n isUnionRunType: RunTypesModule['isUnionRunType'];\n isClassRunType: RunTypesModule['isClassRunType'];\n isLiteralRunType: RunTypesModule['isLiteralRunType'];\n isNeverRunType: RunTypesModule['isNeverRunType'];\n}\n\n// Cached run-types module - loaded once and reused\nlet runTypesModule: RunTypesFunctions | null = null;\nlet runTypesLoadPromise: Promise<RunTypesFunctions> | null = null;\n\n/** Dynamically loads the @mionjs/run-types module. The module is cached after first load. */\nasync function loadRunTypesModule(): Promise<RunTypesFunctions> {\n // Return cached module if already loaded\n if (runTypesModule) return runTypesModule;\n\n // Return existing promise if load is in progress\n if (runTypesLoadPromise) return runTypesLoadPromise;\n\n // Start loading the module\n runTypesLoadPromise = import('@mionjs/run-types').then((module) => {\n runTypesModule = {\n JitFunctions: module.JitFunctions,\n reflectFunction: module.reflectFunction,\n isUnionRunType: module.isUnionRunType,\n isClassRunType: module.isClassRunType,\n isLiteralRunType: module.isLiteralRunType,\n isNeverRunType: module.isNeverRunType,\n };\n return runTypesModule;\n });\n\n return runTypesLoadPromise;\n}\n\n/** Resets the run-types module cache. Useful for testing purposes only. */\nexport function resetRunTypesCache(): void {\n runTypesModule = null;\n runTypesLoadPromise = null;\n}\n\n/** Resets all reflection caches. Useful for testing purposes only. */\nexport function resetReflectionCaches(): void {\n rawMiddleFnReflectionCache.clear();\n // Note: functionRunTypeCache uses WeakMap so it doesn't need explicit clearing\n // Note: _cachedReflection on MethodMetadata objects will be cleared when persistedMethods is reset\n}\n\n// ############ Raw MiddleFn Reflection Helper ############\n\n// Cache for common raw middleFn reflections\nconst rawMiddleFnReflectionCache = new Map<string, MethodReflect>();\n\n/**\n * Creates a MethodReflect for raw middleFns.\n * Raw middleFns don't need JIT functions - they always use NoopJitFns.\n * Results are cached to avoid creating duplicate objects.\n */\nfunction createRawMiddleFnReflection(isAsync: boolean, hasReturnData: boolean = false, paramNames: string[] = []): MethodReflect {\n // Create cache key from parameters\n const cacheKey = `${isAsync}_${hasReturnData}_${paramNames.join(',')}`;\n\n const cached = rawMiddleFnReflectionCache.get(cacheKey);\n if (cached) return cached;\n\n const reflection: MethodReflect = {\n paramNames,\n paramsJitFns: getNoopJitFns(),\n returnJitFns: getNoopJitFns(),\n paramsJitHash: EMPTY_HASH,\n returnJitHash: EMPTY_HASH,\n hasReturnData,\n isAsync,\n };\n\n rawMiddleFnReflectionCache.set(cacheKey, reflection);\n return reflection;\n}\n\n// ############ AOT Cache Extraction ############\n\n// Extend MethodMetadata type to include cached reflection\ntype CachedMethodMetadata = MethodMetadata & {\n _cachedReflection?: MethodReflect;\n};\n\n/**\n * Extracts reflection data from a cached method.\n * Used in AOT mode to restore method reflection without loading run-types.\n * Results are cached on the metadata object to avoid creating duplicate objects.\n */\nfunction extractReflectionFromCached(cached: CachedMethodMetadata): MethodReflect {\n // Return cached reflection if available\n if (cached._cachedReflection) return cached._cachedReflection;\n\n const reflectionItems: MethodReflect = {\n paramNames: cached.paramNames || [],\n paramsJitFns: getJitFunctionsFromHash(cached.paramsJitHash),\n returnJitFns: getJitFunctionsFromHash(cached.returnJitHash),\n paramsJitHash: cached.paramsJitHash,\n returnJitHash: cached.returnJitHash,\n hasReturnData: cached.hasReturnData,\n isAsync: cached.isAsync,\n };\n\n // Restore headers param if present\n if (cached.headersParam) {\n reflectionItems.headersParam = {\n headerNames: cached.headersParam.headerNames,\n jitFns: getJitFunctionsFromHash(cached.headersParam.jitHash) as Pick<JitCompiledFunctions, 'isType' | 'typeErrors'>,\n jitHash: cached.headersParam.jitHash,\n };\n }\n\n // Restore headers return if present\n if (cached.headersReturn) {\n reflectionItems.headersReturn = {\n headerNames: cached.headersReturn.headerNames,\n jitFns: getJitFunctionsFromHash(cached.headersReturn.jitHash) as Pick<JitCompiledFunctions, 'isType' | 'typeErrors'>,\n jitHash: cached.headersReturn.jitHash,\n };\n }\n\n // Cache for future calls\n cached._cachedReflection = reflectionItems;\n return reflectionItems;\n}\n\n// ############ Main Reflection Functions ############\n\n/**\n * Gets reflection data for a handler (route or middleFn).\n * In AOT mode, returns cached data without loading run-types.\n * In non-AOT mode, dynamically loads run-types and generates reflection.\n * Throws AOTCacheError if AOT mode is enabled and route is not in cache.\n */\nexport async function getHandlerReflection(\n handler: Handler,\n routeId: string,\n routerOptions: RouterOptions,\n isHeadersMiddleFn: boolean = false,\n methodStrictTypes?: boolean\n): Promise<MethodReflect> {\n // Check AOT cache first\n const cached = getPersistedMethodMetadata(routeId);\n if (cached) return extractReflectionFromCached(cached);\n if (routerOptions.aot) throw new AOTCacheError(routeId, isHeadersMiddleFn ? 'middleFn' : 'route');\n // Non-AOT mode: dynamically load run-types and generate reflection\n const rt = await loadRunTypesModule();\n return generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt, methodStrictTypes);\n}\n\n/**\n * Gets reflection data for a raw middleFn.\n * Raw middleFns don't use full reflection - they don't need JIT functions.\n * Raw middleFns don't NEED to be in the AOT cache, but if they are, we can use\n * the cached data (especially the isAsync flag).\n * In AOT mode, this function does NOT load run-types.\n */\nexport async function getRawMethodReflection(\n handler: Handler,\n routeId: string,\n routerOptions: RouterOptions\n): Promise<MethodReflect> {\n // Check if raw middleFn is in cache - if so, use cached data (especially isAsync)\n const cached = getPersistedMethodMetadata(routeId);\n if (cached) return createRawMiddleFnReflection(cached.isAsync, cached.hasReturnData, cached.paramNames || []);\n // Raw middleFns don't need JIT functions, so we don't need to load run-types in AOT mode\n if (routerOptions.aot) return createRawMiddleFnReflection(true);\n // Non-AOT mode: dynamically load run-types to properly detect if handler is async\n const rt = await loadRunTypesModule();\n return generateRawMethodReflection(handler, routeId, rt);\n}\n\n// ############ Reflection Generation (requires run-types) ############\n\n/**\n * Generates reflection data for a handler using run-types.\n * This function is only called in non-AOT mode.\n */\nfunction generateHandlerReflection(\n handler: Handler,\n routeId: string,\n routerOptions: RouterOptions,\n isHeadersMiddleFn: boolean,\n rt: RunTypesFunctions,\n methodStrictTypes?: boolean\n): MethodReflect {\n const reflectionItems: Partial<MethodReflect> = {};\n let handlerRunType: FunctionRunType;\n const effectiveStrictTypes = methodStrictTypes ?? routerOptions.strictTypes;\n const runTypeOptions: RunTypeOptions = {\n ...(routerOptions?.runTypeOptions || DEFAULT_ROUTE_OPTIONS.runTypeOptions),\n ...(effectiveStrictTypes !== undefined ? {strictTypes: effectiveStrictTypes} : {}),\n };\n try {\n handlerRunType = rt.reflectFunction(handler);\n } catch (error: any) {\n throw new Error(`Can not get RunType of handler for route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n const paramsSlice = isHeadersMiddleFn ? {start: HEADER_HOOK_DEFAULT_PARAMS.length} : {start: ROUTE_DEFAULT_PARAMS.length};\n const paramsOpts: RunTypeOptions = {...runTypeOptions, paramsSlice};\n\n try {\n reflectionItems.paramNames = handlerRunType.getParameterNames(paramsOpts);\n // Skip JIT generation if handler has no params (optimization for AOT cache size)\n if (reflectionItems.paramNames.length === 0) {\n reflectionItems.paramsJitHash = EMPTY_HASH;\n reflectionItems.paramsJitFns = getNoopJitFns();\n } else {\n reflectionItems.paramsJitFns = getFunctionJitFns(handler, paramsOpts, rt, false);\n reflectionItems.paramsJitHash = handlerRunType.getParameters().getJitHash(paramsOpts);\n }\n } catch (error: any) {\n throw new Error(`Can not compile Jit Functions for Parameters of route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n\n if (isHeadersMiddleFn) {\n const headersRunType = getParamsHeadersRunType(handlerRunType, routeId, routerOptions, rt);\n const headerNames: string[] = getHeaderNames(headersRunType, routeId, rt);\n\n try {\n const opts: RunTypeOptions = {\n ...runTypeOptions,\n paramsSlice: undefined,\n };\n\n const jitFns: JitCompiledFunctions = getTypeJitFunctions(headersRunType, opts, rt);\n const jitHash = headersRunType.getJitHash(opts);\n reflectionItems.headersParam = {headerNames, jitFns, jitHash};\n } catch (error: any) {\n throw new Error(\n `Can not compile Jit Functions for Headers of Headers MiddleFn \"${routeId}.\" Error: ${error?.message}`\n );\n }\n }\n\n const returnHeadersRunType = getReturnHeadersRunType(handlerRunType, rt);\n if (returnHeadersRunType) {\n const opts: RunTypeOptions = {};\n const headerNames: string[] = getHeaderNames(returnHeadersRunType, routeId, rt);\n const jitFns: JitCompiledFunctions = getFunctionJitFns(handler, opts, rt, true);\n const jitHash: string = returnHeadersRunType.getJitHash(opts);\n reflectionItems.headersReturn = {headerNames, jitFns, jitHash};\n }\n\n const returnOpts: RunTypeOptions = runTypeOptions;\n // If the return type is HeadersSubset or if it's a headersFn with array return, don't treat it as return data\n reflectionItems.hasReturnData = handlerRunType.hasReturnData();\n\n try {\n // Skip JIT generation if handler has void return (optimization for AOT cache size)\n if (!reflectionItems.hasReturnData) {\n reflectionItems.returnJitFns = getNoopJitFns();\n reflectionItems.returnJitHash = EMPTY_HASH;\n } else {\n // returnJitFns contains all run type functionality for the return value, it compiles when the property is first accessed\n reflectionItems.returnJitFns = getFunctionJitFns(handler, returnOpts, rt, true);\n reflectionItems.returnJitHash = handlerRunType.getReturnType().getJitHash(returnOpts);\n }\n } catch (error: any) {\n throw new Error(`Can not get Jit Functions for Return of route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n\n reflectionItems.isAsync = handlerRunType.isAsync();\n\n return reflectionItems as MethodReflect;\n}\n\n/**\n * Generates reflection data for a raw middleFn using run-types.\n * This function is only called in non-AOT mode.\n */\nfunction generateRawMethodReflection(handler: Handler, routeId: string, rt: RunTypesFunctions): MethodReflect {\n let handlerRunType: FunctionRunType;\n try {\n handlerRunType = rt.reflectFunction(handler);\n } catch (error: any) {\n throw new Error(`Can not get RunType of handler for route/middleFn \"${routeId}.\" Error: ${error?.message}`);\n }\n const isAsync = handlerRunType?.isAsync() || true;\n return createRawMiddleFnReflection(isAsync);\n}\n\n// ############ Helper Functions (require run-types module) ############\n\nfunction getParamsHeadersRunType(\n handlerRunType: FunctionRunType,\n routeId: string,\n routerOptions: RouterOptions,\n rt: RunTypesFunctions\n): BaseRunType {\n const paramRunTypes = handlerRunType.getParameters().getParamRunTypes(getFakeCompiler(routerOptions));\n const headersSubset = (paramRunTypes[1] as MemberRunType<any>)?.getMemberType?.(); // HeadersSubset is always index 1 after context\n\n if (!isHeaderSubSetRunType(headersSubset, rt)) {\n throw new Error(`Headers MiddleFn '${routeId}' second parameter must be a HeadersSubset.`);\n }\n return headersSubset;\n}\n\nfunction getReturnHeadersRunType(handlerRunType: FunctionRunType, rt: RunTypesFunctions): BaseRunType | undefined {\n const returnRunType = handlerRunType.getReturnType();\n if (rt.isUnionRunType(returnRunType)) {\n const headersSubset = returnRunType.getChildRunTypes().find((child) => isHeaderSubSetRunType(child, rt));\n if (!headersSubset) return undefined;\n return headersSubset;\n }\n if (!isHeaderSubSetRunType(returnRunType, rt)) return undefined;\n return returnRunType;\n}\n\nfunction isHeaderSubSetRunType(runType: BaseRunType | undefined, rt: RunTypesFunctions): runType is BaseRunType {\n if (!runType) return false;\n return rt.isClassRunType(runType, HeadersSubset);\n}\n\nfunction getHeaderNames(runType: BaseRunType, routeId: string, rt: RunTypesFunctions): string[] {\n // HeadersSubset is a generic class: HeadersSubset<Required, Optional>\n // We need to extract the literal string values from the Required and Optional type arguments\n // Use 'typeArguments' (not 'arguments') to get both Required and Optional with their defaults\n const typeArguments = (runType.src as any).typeArguments;\n if (!typeArguments || typeArguments.length === 0) {\n throw new Error(`HeadersSubset must have type arguments in route/middleFn ${routeId}`);\n }\n const headerNames: string[] = [];\n // Extract header names from Required type argument (first argument)\n const requiredArg = typeArguments[0];\n if (requiredArg) {\n const requiredNames = extractLiteralStringsFromType(requiredArg._rt, rt);\n headerNames.push(...requiredNames);\n }\n // Extract header names from Optional type argument (second argument, if present)\n if (typeArguments.length > 1) {\n const optionalArg = typeArguments[1];\n if (optionalArg) {\n const optionalNames = extractLiteralStringsFromType(optionalArg._rt, rt);\n headerNames.push(...optionalNames);\n }\n }\n if (headerNames.length === 0) throw new Error(`Header names array cannot be empty in route/middleFn ${routeId}`);\n return headerNames;\n}\n\n/**\n * Internal recursive function to extract literal string values from a type.\n * Handles single literal strings and union types (including nested unions).\n */\nfunction extractLiteralStringsFromTypeRecursive(runType: BaseRunType, rt: RunTypesFunctions): string[] {\n // Handle single literal string\n if (rt.isLiteralRunType(runType)) {\n const literal = (runType as any).getLiteralValue();\n if (typeof literal === 'string') {\n return [literal];\n }\n return [];\n }\n\n // Handle union of literal strings (recursively for nested unions)\n if (rt.isUnionRunType(runType)) {\n const children = runType.getChildRunTypes();\n const literals: string[] = [];\n for (const child of children) {\n // Recursively extract from each child (handles nested unions)\n const childLiterals = extractLiteralStringsFromTypeRecursive(child, rt);\n literals.push(...childLiterals);\n }\n return literals;\n }\n\n return [];\n}\n\n/**\n * Extracts literal string values from a type.\n * Handles 'never' type only at the root level, then delegates to recursive extraction.\n */\nfunction extractLiteralStringsFromType(runType: BaseRunType, rt: RunTypesFunctions): string[] {\n // Handle 'never' type at root level only (no headers)\n if (rt.isNeverRunType(runType)) return [];\n return extractLiteralStringsFromTypeRecursive(runType, rt);\n}\n\n// Create a fake compiler object with just the opts property needed by getParamRunTypes.\n// getParamRunTypes() requires a JitFnCompiler but we only need the opts property to slice parameters.\n// This is a workaround to avoid updating getParamRunTypes() signature\nfunction getFakeCompiler(routerOptions: RouterOptions): JitFnCompiler {\n return {opts: routerOptions} as any as JitFnCompiler;\n}\n\nfunction getTypeJitFunctions(\n runType: BaseRunType,\n opts: RunTypeOptions | undefined,\n rtModule: RunTypesFunctions\n): JitCompiledFunctions {\n const jitFns: JitCompiledFunctions = {\n isType: runType.createJitCompiledFunction(rtModule.JitFunctions.isType.id, undefined, opts),\n typeErrors: runType.createJitCompiledFunction(rtModule.JitFunctions.typeErrors.id, undefined, opts),\n prepareForJson: runType.createJitCompiledFunction(rtModule.JitFunctions.prepareForJson.id, undefined, opts),\n restoreFromJson: runType.createJitCompiledFunction(rtModule.JitFunctions.restoreFromJson.id, undefined, opts),\n stringifyJson: runType.createJitCompiledFunction(rtModule.JitFunctions.stringifyJson.id, undefined, opts),\n toBinary: runType.createJitCompiledFunction(rtModule.JitFunctions.toBinary.id, undefined, opts),\n fromBinary: runType.createJitCompiledFunction(rtModule.JitFunctions.fromBinary.id, undefined, opts),\n };\n return jitFns;\n}\n\n// Cache for function RunTypes to avoid duplicate reflectFunction calls\nconst functionRunTypeCache = new WeakMap<AnyFn, FunctionRunType>();\n\nfunction getFunctionJitFns<Fn extends AnyFn>(\n fn: Fn,\n opts: RunTypeOptions | undefined,\n rtModule: RunTypesFunctions,\n isReturn: boolean\n): JitCompiledFunctions {\n // Check cache first\n let runType = functionRunTypeCache.get(fn);\n if (!runType) {\n runType = rtModule.reflectFunction(fn);\n functionRunTypeCache.set(fn, runType);\n }\n\n const createFn = isReturn\n ? runType.createJitCompiledReturnFunction.bind(runType)\n : runType.createJitCompiledParamsFunction.bind(runType);\n const jitFunctions: JitCompiledFunctions = {\n isType: createFn(rtModule.JitFunctions.isType, opts),\n typeErrors: createFn(rtModule.JitFunctions.typeErrors, opts),\n prepareForJson: createFn(rtModule.JitFunctions.prepareForJson, opts),\n restoreFromJson: createFn(rtModule.JitFunctions.restoreFromJson, opts),\n stringifyJson: createFn(rtModule.JitFunctions.stringifyJson, opts),\n toBinary: createFn(rtModule.JitFunctions.toBinary, opts),\n fromBinary: createFn(rtModule.JitFunctions.fromBinary, opts),\n };\n return jitFunctions;\n}\n\n// ############ Null JIT Functions ############\n"],"names":["module","getNoopJitFns","EMPTY_HASH","getJitFunctionsFromHash","getPersistedMethodMetadata","DEFAULT_ROUTE_OPTIONS","HEADER_HOOK_DEFAULT_PARAMS","ROUTE_DEFAULT_PARAMS","HeadersSubset"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BM,MAAO,sBAAsB,MAAK;AAAA,EACpC,YAAY,SAAiB,OAA6C,SAAO;AAC7E,UAAM,YAAY,SAAS,gBAAgB,iBAAiB,SAAS,aAAa,aAAa;AAC/F,UAAM,GAAG,SAAS,KAAK,OAAO;AAAA,sDAAuF;AACrH,SAAK,OAAO;AAAA,EAChB;AAAA;;;;AAgBJ,IAAI,iBAA2C;AAC/C,IAAI,sBAAyD;AAG7D,eAAe,qBAAkB;AAE7B,MAAI;AAAgB,WAAO;AAG3B,MAAI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ACA,UACA,UAAiB;AAGjB,MAAI,UAAU,qBAAqB,IAAI,EAAE;AACzC,MAAI,CAAC,SAAS;AACV,cAAU,SAAS,gBAAgB,EAAE;AACrC,yBAAqB,IAAI,IAAI,OAAO;AAAA,EACxC;AAEA,QAAM,WAAW,WACX,QAAQ,gCAAgC,KAAK,OAAO,IACpD,QAAQ,gCAAgC,KAAK,OAAO;AAC1D,QAAM,eAAqC;AAAA,IACvC,QAAQ,SAAS,SAAS,aAAa,QAAQ,IAAI;AAAA,IACnD,YAAY,SAAS,SAAS,aAAa,YAAY,IAAI;AAAA,IAC3D,gBAAgB,SAAS,SAAS,aAAa,gBAAgB,IAAI;AAAA,IACnE,iBAAiB,SAAS,SAAS,aAAa,iBAAiB,IAAI;AAAA,IACrE,eAAe,SAAS,SAAS,aAAa,eAAe,IAAI;AAAA,IACjE,UAAU,SAAS,SAAS,aAAa,UAAU,IAAI;AAAA,IACvD,YAAY,SAAS,SAAS,aAAa,YAAY,IAAI;AAAA,EAAA;AAE/D,SAAO;AACX;;;;;;;"}
|
|
@@ -7,6 +7,6 @@ export declare class AOTCacheError extends Error {
|
|
|
7
7
|
}
|
|
8
8
|
export declare function resetRunTypesCache(): void;
|
|
9
9
|
export declare function resetReflectionCaches(): void;
|
|
10
|
-
export declare function getHandlerReflection(handler: Handler, routeId: string, routerOptions: RouterOptions, isHeadersMiddleFn?: boolean): Promise<MethodReflect>;
|
|
10
|
+
export declare function getHandlerReflection(handler: Handler, routeId: string, routerOptions: RouterOptions, isHeadersMiddleFn?: boolean, methodStrictTypes?: boolean): Promise<MethodReflect>;
|
|
11
11
|
export declare function getRawMethodReflection(handler: Handler, routeId: string, routerOptions: RouterOptions): Promise<MethodReflect>;
|
|
12
12
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aotEmitter-test-router.cjs","sources":["../../../../../src/lib/test/aotEmitter-test-router.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n/**\n * Test router script for AOT emitter tests.\n * This script is spawned as a child process with MION_COMPILE=
|
|
1
|
+
{"version":3,"file":"aotEmitter-test-router.cjs","sources":["../../../../../src/lib/test/aotEmitter-test-router.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n/**\n * Test router script for AOT emitter tests.\n * This script is spawned as a child process with MION_COMPILE=buildOnly\n * to test that emitAOTCaches() correctly sends IPC messages.\n *\n * Uses initMionRouter which automatically calls emitAOTCaches() when MION_COMPILE=buildOnly.\n */\n\nimport {initMionRouter, route, middleFn, Routes, PublicApi} from '@mionjs/router';\n\ninterface User {\n id: string;\n name: string;\n}\n\nconst routes = {\n users: {\n getUser: route((ctx, id: string): User => ({id, name: 'Test User'})),\n createUser: route((ctx, user: User): string => `Created user ${user.name}`),\n },\n utils: {\n sum: route((ctx, a: number, b: number): number => a + b),\n },\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n log: middleFn((ctx): void => {\n // Log middleFn\n }),\n} satisfies Routes;\n\n// Initialize the router - this will call emitAOTCaches() automatically when MION_COMPILE=buildOnly\nexport const testApiPromise: Promise<PublicApi<typeof routes>> = initMionRouter(routes, {basePath: 'api/v1'});\n\nexport {routes};\n"],"names":["route","middleFn","initMionRouter"],"mappings":";;;;;;;;AAsBA,MAAM,SAAS;AAAA,EACX,OAAO;AAAA,IACH,SAASA,OAAAA,MAAK,aAAC,CAAC,KAAK,QAAsB,EAAC,IAAI,MAAM,gBAAa,CAAA,OAAA,MAAA,MAAA,SAAA,IAAA,aAAA,CAAA,CAAA;AAAA,IACnE,YAAYA,OAAAA,MAAK,aAAC,CAAC,KAAK,SAAuB,gBAAgB,KAAK,IAAI,IAAE,CAAA,OAAA,MAAA,SAAA,QAAA,IAAA,aAAA,CAAA,CAAA;AAAA,EAAA;AAAA,EAE9E,OAAO;AAAA,IACH,KAAKA,OAAAA,MAAK,aAAC,CAAC,KAAK,GAAW,MAAsB,IAAI,GAAC,CAAA,OAAA,KAAA,KAAA,IAAA,eAAA,CAAA,CAAA;AAAA,EAAA;AAAA;AAAA,EAG3D,KAAKC,OAAAA,SAAQ,aAAC,CAAC,QAAa;AAAA,EAE5B,GAAC,CAAA,OAAA,IAAA,SAAA,CAAA,CAAA;;AAIE,MAAM,iBAAoDC,OAAAA,eAAe,QAAQ,EAAC,UAAU,UAAS;;;"}
|
package/.dist/cjs/src/router.cjs
CHANGED
|
@@ -22,6 +22,7 @@ let complexity = 0;
|
|
|
22
22
|
let routerOptions = { ...src_constants.DEFAULT_ROUTE_OPTIONS };
|
|
23
23
|
let isRouterInitialized = false;
|
|
24
24
|
let allExecutablesIds;
|
|
25
|
+
let platformConfig;
|
|
25
26
|
const defaultStartMiddleFns = {
|
|
26
27
|
mionDeserializeRequest: src_routes_serializer_routes.serializerMiddleFns.mionDeserializeRequest
|
|
27
28
|
};
|
|
@@ -41,6 +42,18 @@ const geMiddleFnsSize = () => middleFnsById.size;
|
|
|
41
42
|
const getComplexity = () => complexity;
|
|
42
43
|
const getRouterOptions = () => routerOptions;
|
|
43
44
|
const getAnyExecutable = (id) => routesById.get(id) || middleFnsById.get(id) || rawMiddleFnsById.get(id);
|
|
45
|
+
function setPlatformConfig(config) {
|
|
46
|
+
platformConfig = config;
|
|
47
|
+
if (core.isMionAOTEmitMode() && typeof process.send === "function") {
|
|
48
|
+
const routerConfig = Object.fromEntries(Object.entries(routerOptions).filter(([, v]) => typeof v !== "function"));
|
|
49
|
+
try {
|
|
50
|
+
process.send({ type: "mion-platform-ready", routerConfig, platformConfig: config });
|
|
51
|
+
} catch (err) {
|
|
52
|
+
console.error("[mion] Failed to send platform-ready IPC:", err);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const getPlatformConfig = () => platformConfig;
|
|
44
57
|
const resetRouter = () => {
|
|
45
58
|
flatRouter.clear();
|
|
46
59
|
middleFnsById.clear();
|
|
@@ -56,6 +69,7 @@ const resetRouter = () => {
|
|
|
56
69
|
exports.endMiddleFns = [];
|
|
57
70
|
isRouterInitialized = false;
|
|
58
71
|
allExecutablesIds = void 0;
|
|
72
|
+
platformConfig = void 0;
|
|
59
73
|
src_lib_remoteMethods.resetRemoteMethodsMetadata();
|
|
60
74
|
src_lib_methodsCache.resetPersistedMethods();
|
|
61
75
|
core.resetRoutesCache();
|
|
@@ -268,7 +282,13 @@ async function getExecutableFromMiddleFn(middleFn, middleFnPointer, nestLevel) {
|
|
|
268
282
|
if (compiledMethod) {
|
|
269
283
|
executable = compiledMethod;
|
|
270
284
|
} else {
|
|
271
|
-
const reflectionData = await src_lib_reflection.getHandlerReflection(
|
|
285
|
+
const reflectionData = await src_lib_reflection.getHandlerReflection(
|
|
286
|
+
middleFn.handler,
|
|
287
|
+
middleFnId,
|
|
288
|
+
routerOptions,
|
|
289
|
+
isHeader,
|
|
290
|
+
middleFn.options?.strictTypes
|
|
291
|
+
);
|
|
272
292
|
executable = {
|
|
273
293
|
id: middleFnId,
|
|
274
294
|
type: isHeader ? core.HandlerType.headersMiddleFn : core.HandlerType.middleFn,
|
|
@@ -280,7 +300,8 @@ async function getExecutableFromMiddleFn(middleFn, middleFnPointer, nestLevel) {
|
|
|
280
300
|
runOnError: !!middleFn.options?.runOnError,
|
|
281
301
|
validateParams: middleFn.options?.validateParams ?? true,
|
|
282
302
|
validateReturn: middleFn.options?.validateReturn ?? false,
|
|
283
|
-
description: middleFn.options?.description
|
|
303
|
+
description: middleFn.options?.description,
|
|
304
|
+
strictTypes: middleFn.options?.strictTypes ?? routerOptions.strictTypes
|
|
284
305
|
}
|
|
285
306
|
};
|
|
286
307
|
src_lib_methodsCache.addToPersistedMethods(middleFnId, executable);
|
|
@@ -321,7 +342,13 @@ async function getExecutableFromRoute(route, routePointer, nestLevel) {
|
|
|
321
342
|
if (compiledMethod) {
|
|
322
343
|
executable = compiledMethod;
|
|
323
344
|
} else {
|
|
324
|
-
const reflectionData = await src_lib_reflection.getHandlerReflection(
|
|
345
|
+
const reflectionData = await src_lib_reflection.getHandlerReflection(
|
|
346
|
+
route.handler,
|
|
347
|
+
routeId,
|
|
348
|
+
routerOptions,
|
|
349
|
+
false,
|
|
350
|
+
route.options?.strictTypes
|
|
351
|
+
);
|
|
325
352
|
executable = {
|
|
326
353
|
id: routeId,
|
|
327
354
|
type: core.HandlerType.route,
|
|
@@ -335,7 +362,8 @@ async function getExecutableFromRoute(route, routePointer, nestLevel) {
|
|
|
335
362
|
validateReturn: route.options?.validateReturn ?? false,
|
|
336
363
|
description: route.options?.description,
|
|
337
364
|
serializer: route.options?.serializer ?? routerOptions.serializer,
|
|
338
|
-
isMutation: route.options?.isMutation
|
|
365
|
+
isMutation: route.options?.isMutation,
|
|
366
|
+
strictTypes: route.options?.strictTypes ?? routerOptions.strictTypes
|
|
339
367
|
}
|
|
340
368
|
};
|
|
341
369
|
src_lib_methodsCache.addToPersistedMethods(routeId, executable);
|
|
@@ -413,6 +441,7 @@ exports.getExecutableFromMiddleFn = getExecutableFromMiddleFn;
|
|
|
413
441
|
exports.getExecutableFromRawMiddleFn = getExecutableFromRawMiddleFn;
|
|
414
442
|
exports.getExecutableFromRoute = getExecutableFromRoute;
|
|
415
443
|
exports.getMiddleFnExecutable = getMiddleFnExecutable;
|
|
444
|
+
exports.getPlatformConfig = getPlatformConfig;
|
|
416
445
|
exports.getRouteEntries = getRouteEntries;
|
|
417
446
|
exports.getRouteExecutable = getRouteExecutable;
|
|
418
447
|
exports.getRouteExecutableFromPath = getRouteExecutableFromPath;
|
|
@@ -425,5 +454,6 @@ exports.isPrivateDefinition = isPrivateDefinition;
|
|
|
425
454
|
exports.isPrivateExecutable = isPrivateExecutable;
|
|
426
455
|
exports.registerRoutes = registerRoutes;
|
|
427
456
|
exports.resetRouter = resetRouter;
|
|
457
|
+
exports.setPlatformConfig = setPlatformConfig;
|
|
428
458
|
exports.shouldFullGenerateSpec = shouldFullGenerateSpec;
|
|
429
459
|
//# sourceMappingURL=router.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs","sources":["../../../src/router.ts"],"sourcesContent":["/* ########\n * 2022 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n/** Lightweight path join for error messages (avoids Node's 'path' module for edge compatibility) */\nimport type {Route, RouterOptions, Routes, RouterEntry} from './types/general.ts';\nimport type {\n RemoteMethod,\n MethodsExecutionChain,\n RawMethod,\n HeadersMethod,\n MiddleFnMethod,\n RouteMethod,\n} from './types/remoteMethods.ts';\nimport type {PublicApi, PrivateDef, MiddleFnsCollection} from './types/publicMethods.ts';\nimport type {HeadersMiddleFnDef, MiddleFnDef, RawMiddleFnDef} from './types/definitions.ts';\nimport {DEFAULT_ROUTE_OPTIONS, MAX_ROUTE_NESTING, WORKFLOW_KEY} from './constants.ts';\nimport {\n isRawMiddleFnDef,\n isHeadersMiddleFnDef,\n isExecutable,\n isMiddleFnDef,\n isRoute,\n isRoutes,\n isAnyMiddleFnDef,\n isPublicExecutable,\n} from './types/guards.ts';\nimport {\n HandlerType,\n SerializerModes,\n SerializerCode,\n SerializerMode,\n isTestEnv,\n isMionCompileMode,\n isMionAOTEmitMode,\n resetRoutesCache,\n} from '@mionjs/core';\nimport {getRawMethodReflection, getHandlerReflection} from './lib/reflection.ts';\nimport {serializerMiddleFns} from './routes/serializer.routes.ts';\nimport {getRouterItemId, getRoutePath, getENV, MION_ROUTES, routesCache} from '@mionjs/core';\nimport {setErrorOptions} from '@mionjs/core';\nimport {getPublicApi, resetRemoteMethodsMetadata} from './lib/remoteMethods.ts';\nimport {addToPersistedMethods, getPersistedMethod, resetPersistedMethods} from './lib/methodsCache.ts';\nimport {mionClientRoutes} from './routes/client.routes.ts';\nimport {mionErrorsRoutes} from './routes/errors.routes.ts';\nimport {clearRoutesFlowCache} from './routesFlow.ts';\nimport {clearContextPool} from './callContext.ts';\n\ntype RouterKeyEntryList = [string, RouterEntry][];\ntype RoutesWithId = {\n pathPointer: string[];\n routes: Routes;\n};\n\n// ############# PRIVATE STATE #############\n\nconst mionInternalRoutes = Object.values(MION_ROUTES) as string[];\nconst flatRouter: Map<string, MethodsExecutionChain> = new Map(); // Main Router\nconst middleFnsById: Map<string, MiddleFnMethod | HeadersMethod | RawMethod> = new Map();\nconst routesById: Map<string, RouteMethod> = new Map();\nconst rawMiddleFnsById: Map<string, RawMethod> = new Map();\nconst middleFnNames: Set<string> = new Set();\nconst routeNames: Set<string> = new Set();\nlet complexity = 0;\nlet routerOptions: RouterOptions = {...DEFAULT_ROUTE_OPTIONS};\nlet isRouterInitialized = false;\nlet allExecutablesIds: string[] | undefined;\n\n/** Global middleFns to be run before and after any other middleFns or routes set using `registerRoutes` */\nconst defaultStartMiddleFns = {\n mionDeserializeRequest: serializerMiddleFns.mionDeserializeRequest,\n};\nconst defaultEndMiddleFns = {\n mionSerializeResponse: serializerMiddleFns.mionSerializeResponse,\n};\nlet startMiddleFnsDef: MiddleFnsCollection = {...defaultStartMiddleFns};\nlet endMiddleFnsDef: MiddleFnsCollection = {...defaultEndMiddleFns};\nexport let startMiddleFns: RemoteMethod[] = [];\nexport let endMiddleFns: RemoteMethod[] = [];\n\n// ############# PUBLIC METHODS #############\n\nexport const getRouteExecutionChain = (path: string) => flatRouter.get(path);\nexport const getRouteEntries = () => flatRouter.entries();\nexport const geRoutesSize = () => flatRouter.size;\nexport const getRouteExecutable = (id: string) => routesById.get(id);\nexport const getMiddleFnExecutable = (id: string) => middleFnsById.get(id);\nexport const geMiddleFnsSize = () => middleFnsById.size;\nexport const getComplexity = () => complexity;\nexport const getRouterOptions = <Opts extends RouterOptions>(): Readonly<Opts> => routerOptions as Opts;\nexport const getAnyExecutable = (id: string) => routesById.get(id) || middleFnsById.get(id) || rawMiddleFnsById.get(id);\n\nexport const resetRouter = () => {\n flatRouter.clear();\n middleFnsById.clear();\n routesById.clear();\n rawMiddleFnsById.clear();\n middleFnNames.clear();\n routeNames.clear();\n complexity = 0;\n routerOptions = {...DEFAULT_ROUTE_OPTIONS};\n startMiddleFnsDef = {...defaultStartMiddleFns};\n endMiddleFnsDef = {...defaultEndMiddleFns};\n startMiddleFns = [];\n endMiddleFns = [];\n isRouterInitialized = false;\n allExecutablesIds = undefined;\n resetRemoteMethodsMetadata();\n resetPersistedMethods();\n resetRoutesCache();\n clearContextPool();\n clearRoutesFlowCache();\n // Note: We intentionally do NOT call resetJitFnCaches() here because:\n // 1. JIT function caches are global and should persist across router resets\n // 2. The serializableClassRegistry (cleared by resetJitFnCaches) is needed for\n // serialization/deserialization of classes like RpcError\n // resetJitFnCaches() should only be called in specific test scenarios that need\n // to test AOT cache loading behavior\n};\n\n// simpler router initialization\nexport async function initMionRouter<R extends Routes>(routes: R, opts?: Partial<RouterOptions>): Promise<PublicApi<R>> {\n await initRouter(opts);\n const publicApi = await registerRoutes(routes);\n // Emit AOT caches once after ALL routes (error, client, user) are registered\n await emitAOTCaches();\n return publicApi;\n}\n\n/**\n * Initializes the Router.\n * @param application\n * @param contextDataFactory a factory function that returns an object to be shared in the `callContext.shared`\n * @param routerOptions\n * @returns\n */\nexport async function initRouter(opts?: Partial<RouterOptions>): Promise<Readonly<RouterOptions>> {\n if (isRouterInitialized) throw new Error('Router has already been initialized');\n routerOptions = {...routerOptions, ...opts};\n validateSharedDataFactory(routerOptions);\n Object.freeze(routerOptions);\n setErrorOptions(routerOptions);\n if (routerOptions.aot) await loadAOTCaches();\n isRouterInitialized = true;\n await registerRoutes({...mionErrorsRoutes});\n if (!routerOptions.skipClientRoutes) await registerRoutes({...mionClientRoutes});\n if (!isTestEnv()) console.log('mion router initialized', {routerOptions});\n return routerOptions;\n}\n\nexport async function registerRoutes<R extends Routes>(routes: R): Promise<PublicApi<R>> {\n if (!isRouterInitialized) throw new Error('initRouter should be called first');\n startMiddleFns = await getExecutablesFromMiddleFnsCollection(startMiddleFnsDef);\n endMiddleFns = await getExecutablesFromMiddleFnsCollection(endMiddleFnsDef);\n await recursiveFlatRoutes(routes);\n if (shouldFullGenerateSpec()) {\n return getPublicApi(routes);\n }\n return {} as PublicApi<R>;\n}\n\n/** Add middleFns at the start af the ExecutionChain, adds them before any other existing start middleFns by default */\nexport function addStartMiddleFns(middleFnsDef: MiddleFnsCollection, appendBeforeExisting = true) {\n if (isRouterInitialized) throw new Error('Can not add start middleFns after the router has been initialized');\n if (appendBeforeExisting) {\n startMiddleFnsDef = {...middleFnsDef, ...startMiddleFnsDef};\n return;\n }\n startMiddleFnsDef = {...startMiddleFnsDef, ...middleFnsDef};\n}\n\n/** Add middleFns at the end af the ExecutionChain, adds them after any other existing end middleFns by default */\nexport function addEndMiddleFns(middleFnsDef: MiddleFnsCollection, prependAfterExisting = true) {\n if (isRouterInitialized) throw new Error('Can not add end middleFns after the router has been initialized');\n if (prependAfterExisting) {\n endMiddleFnsDef = {...endMiddleFnsDef, ...middleFnsDef};\n return;\n }\n endMiddleFnsDef = {...middleFnsDef, ...endMiddleFnsDef};\n}\n\nexport function isPrivateDefinition(entry: RouterEntry, id: string): entry is PrivateDef {\n if (isRoute(entry)) return false;\n if (isRawMiddleFnDef(entry)) return true;\n try {\n const executable = getMiddleFnExecutable(id) || getRouteExecutable(id);\n if (!executable)\n throw new Error(`Route or MiddleFn ${id} not found. Please check you have called router.registerRoutes first.`);\n return isPrivateExecutable(executable);\n } catch {\n // error thrown because entry is a Routes object and does not have any handler\n return false;\n }\n}\n\nexport function isPrivateExecutable(executable: RemoteMethod): boolean {\n if (executable.type === HandlerType.rawMiddleFn) return true;\n if (executable.type === HandlerType.route) return false;\n const hasPublicParams = !!executable.paramNames?.length;\n const hasHeaderParams = !!(executable as HeadersMethod).headersParam?.headerNames?.length;\n return !hasPublicParams && !hasHeaderParams && !executable.hasReturnData;\n}\n\nexport function getTotalExecutables(): number {\n return routesById.size + middleFnsById.size + rawMiddleFnsById.size;\n}\n\nexport function getAllExecutablesIds(): string[] {\n if (allExecutablesIds) return allExecutablesIds;\n allExecutablesIds = [...routesById.keys(), ...middleFnsById.keys(), ...rawMiddleFnsById.keys()];\n return allExecutablesIds;\n}\n\n// used by codegen\nexport function shouldFullGenerateSpec(): boolean {\n return routerOptions.getPublicRoutesData || getENV('GENERATE_ROUTER_SPEC') === 'true' || isMionCompileMode();\n}\n\nexport function getRouteExecutableFromPath(path: string): RouteMethod {\n const executionChain = flatRouter.get(path);\n if (!executionChain) {\n // Return the not-found route executable\n return getAnyExecutable(MION_ROUTES.notFound) as RouteMethod;\n }\n return executionChain.methods[executionChain.routeIndex] as RouteMethod;\n}\n\n// ############# PRIVATE METHODS #############\n\nasync function loadAOTCaches() {\n const loader = await import('./aot/aotCacheLoader.ts');\n return loader.loadRouterAOTCaches();\n}\n\nasync function emitAOTCaches() {\n if (!isMionAOTEmitMode()) return;\n // Dynamic import resolves relative to this source file.\n // This only runs via vite-node (MION_COMPILE=true), which always resolves from source.\n const aotEmitter = await import('./lib/aotEmitter.ts');\n return aotEmitter.emitAOTCaches();\n}\n\n/**\n * Optimized algorithm to flatten the routes object into a list of Executable objects.\n * @param routes\n * @param currentPointer current pointer in the routes object i.e. ['users', 'get']\n * @param preMiddleFns middleFns one level up preceding current pointer\n * @param postMiddleFns middleFns one level up following the current pointer\n * @param nestLevel\n */\nasync function recursiveFlatRoutes(\n routes: Routes,\n currentPointer: string[] = [],\n preMiddleFns: RemoteMethod[] = [],\n postMiddleFns: RemoteMethod[] = [],\n nestLevel = 0\n) {\n if (nestLevel > MAX_ROUTE_NESTING)\n throw new Error('Too many nested routes, you can only nest routes ${MAX_ROUTE_NESTING} levels');\n\n const entries = Object.entries(routes);\n if (entries.length === 0)\n throw new Error(\n `Invalid route: ${currentPointer.length ? joinPath(...currentPointer) : '*'}. Can Not define empty routes`\n );\n\n let minus1Props: ReturnType<typeof getRouteEntryProperties> | null = null;\n for (let index = 0; index < entries.length; index++) {\n const [key, item] = entries[index];\n // create the executable items\n const newPointer = [...currentPointer, key];\n let routeEntry: RemoteMethod | RoutesWithId;\n if (typeof key !== 'string' || !isNaN(key as any))\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. Numeric route names are not allowed`);\n if (key.includes(',')) throw new Error(`Invalid route: ${joinPath(...newPointer)}. Route names cannot contain commas.`);\n if (key === WORKFLOW_KEY)\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. '${WORKFLOW_KEY}' is a reserved mion route name.`);\n\n // generates a middleFn\n if (isAnyMiddleFnDef(item)) {\n routeEntry = await getExecutableFromAnyMiddleFn(item, newPointer, nestLevel);\n if (middleFnNames.has(routeEntry.id))\n throw new Error(\n `Invalid middleFn: ${joinPath(...newPointer)}. Naming collision, Naming collision, duplicated middleFn.`\n );\n middleFnNames.add(routeEntry.id);\n }\n\n // generates a route\n else if (isRoute(item)) {\n routeEntry = await getExecutableFromRoute(item, newPointer, nestLevel);\n if (routeNames.has(routeEntry.id))\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. Naming collision, duplicated route`);\n routeNames.add(routeEntry.id);\n }\n\n // generates structure required to go one level down\n else if (isRoutes(item)) {\n routeEntry = {\n pathPointer: newPointer,\n routes: item,\n };\n }\n\n // throws an error if the route is invalid\n else {\n const itemType = typeof item;\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. Type <${itemType}> is not a valid route.`);\n }\n\n // recurse into sublevels\n minus1Props = await recursiveCreateExecutionChainAsync(\n routeEntry,\n newPointer,\n preMiddleFns,\n postMiddleFns,\n nestLevel,\n index,\n entries,\n minus1Props\n );\n\n complexity++;\n }\n}\n\nasync function recursiveCreateExecutionChainAsync(\n routeEntry: RemoteMethod | RoutesWithId,\n currentPointer: string[],\n preMiddleFns: RemoteMethod[],\n postMiddleFns: RemoteMethod[],\n nestLevel: number,\n index: number,\n routeKeyedEntries: RouterKeyEntryList,\n minus1Props: ReturnType<typeof getRouteEntryProperties> | null\n) {\n const minus1 = getEntry(index - 1, routeKeyedEntries);\n const plus1 = getEntry(index + 1, routeKeyedEntries);\n const props = getRouteEntryProperties(minus1, routeEntry, plus1);\n\n if (props.isBetweenRoutes && minus1Props) {\n props.preLevelMiddleFns = minus1Props.preLevelMiddleFns;\n props.postLevelMiddleFns = minus1Props.postLevelMiddleFns;\n } else {\n for (let i = 0; i < routeKeyedEntries.length; i++) {\n const [k, entry] = routeKeyedEntries[i];\n complexity++;\n if (!isAnyMiddleFnDef(entry)) continue;\n const newPointer = [...currentPointer.slice(0, -1), k];\n const executable = await getExecutableFromAnyMiddleFn(entry, newPointer, nestLevel);\n if (i < index) props.preLevelMiddleFns.push(executable);\n if (i > index) props.postLevelMiddleFns.push(executable);\n }\n }\n const isExec = isExecutable(routeEntry);\n\n if (isExec && props.isRoute) {\n const path = getRoutePath(routeEntry.pointer, routerOptions);\n const routeMethod = routeEntry as RouteMethod;\n const levelMethods = [\n ...preMiddleFns,\n ...props.preLevelMiddleFns,\n routeEntry,\n ...props.postLevelMiddleFns,\n ...postMiddleFns,\n ];\n const methods = [...startMiddleFns, ...levelMethods, ...endMiddleFns];\n const executionChain: MethodsExecutionChain = {\n routeIndex: startMiddleFns.length + preMiddleFns.length + props.preLevelMiddleFns.length,\n methods,\n serializer: getSerializerCodeFromMode(routeMethod.options.serializer),\n };\n const middleFnIds = getPublicMiddleFnIds(methods);\n // add middleware functions deps, so can be serialized with the router\n if (middleFnIds.length) routeMethod.middleFnIds = middleFnIds;\n flatRouter.set(path, executionChain);\n } else if (!isExec) {\n await recursiveFlatRoutes(\n routeEntry.routes,\n routeEntry.pathPointer,\n [...preMiddleFns, ...props.preLevelMiddleFns],\n [...props.postLevelMiddleFns, ...postMiddleFns],\n nestLevel + 1\n );\n }\n\n return props;\n}\n\nasync function getExecutableFromAnyMiddleFn(\n middleFn: MiddleFnDef | HeadersMiddleFnDef | RawMiddleFnDef,\n middleFnPointer: string[],\n nestLevel: number\n) {\n if (isRawMiddleFnDef(middleFn)) return getExecutableFromRawMiddleFn(middleFn, middleFnPointer, nestLevel);\n return getExecutableFromMiddleFn(middleFn, middleFnPointer, nestLevel);\n}\n\nexport async function getExecutableFromMiddleFn(\n middleFn: MiddleFnDef | HeadersMiddleFnDef,\n middleFnPointer: string[],\n nestLevel: number\n): Promise<MiddleFnMethod | HeadersMethod> {\n const isHeader = isHeadersMiddleFnDef(middleFn);\n // todo fix header id should be same as any other one and then maybe map from id to header name\n const middleFnId = getRouterItemId(middleFnPointer);\n const existing = middleFnsById.get(middleFnId);\n if (existing) return existing as MiddleFnMethod;\n\n type MixedMiddleFn = (Omit<MiddleFnMethod, 'type'> | Omit<HeadersMethod, 'type'>) & {\n type: typeof HandlerType.middleFn | typeof HandlerType.headersMiddleFn;\n };\n\n const compiledMethod = getPersistedMethod(middleFnId, middleFn.handler);\n let executable: MixedMiddleFn;\n if (compiledMethod) {\n executable = compiledMethod as MixedMiddleFn;\n } else {\n const reflectionData = await getHandlerReflection(middleFn.handler, middleFnId, routerOptions, isHeader);\n executable = {\n id: middleFnId,\n type: isHeader ? HandlerType.headersMiddleFn : HandlerType.middleFn,\n nestLevel,\n handler: middleFn.handler,\n pointer: middleFnPointer,\n ...reflectionData,\n options: {\n runOnError: !!middleFn.options?.runOnError,\n validateParams: middleFn.options?.validateParams ?? true,\n validateReturn: middleFn.options?.validateReturn ?? false,\n description: middleFn.options?.description,\n },\n };\n addToPersistedMethods(middleFnId, executable);\n }\n\n middleFnsById.set(middleFnId, executable as any);\n routesCache.setMethodJitFns(middleFnId, executable as any);\n return executable as any;\n}\n\nexport async function getExecutableFromRawMiddleFn(\n middleFn: RawMiddleFnDef,\n middleFnPointer: string[],\n nestLevel: number\n): Promise<RawMethod> {\n const middleFnId = getRouterItemId(middleFnPointer);\n const existing = rawMiddleFnsById.get(middleFnId);\n if (existing) return existing as RawMethod;\n const reflectionData = await getRawMethodReflection(middleFn.handler, middleFnId, routerOptions);\n const executable: RawMethod = {\n id: middleFnId,\n type: HandlerType.rawMiddleFn,\n nestLevel,\n handler: middleFn.handler,\n pointer: middleFnPointer,\n ...reflectionData,\n options: {\n runOnError: !!middleFn.options?.runOnError,\n validateParams: false,\n validateReturn: false,\n description: middleFn.options?.description,\n },\n };\n rawMiddleFnsById.set(middleFnId, executable);\n routesCache.setMethodJitFns(middleFnId, executable as any);\n return executable;\n}\n\nexport async function getExecutableFromRoute(route: Route, routePointer: string[], nestLevel: number): Promise<RouteMethod> {\n const routeId = getRouterItemId(routePointer);\n const existing = routesById.get(routeId);\n if (existing) return existing as RouteMethod;\n\n const compiledMethod = getPersistedMethod(routeId, route.handler);\n let executable: RouteMethod;\n if (compiledMethod) {\n executable = compiledMethod as RouteMethod;\n } else {\n const reflectionData = await getHandlerReflection(route.handler, routeId, routerOptions);\n executable = {\n id: routeId,\n type: HandlerType.route,\n nestLevel,\n handler: route.handler,\n pointer: routePointer,\n ...reflectionData,\n options: {\n runOnError: false,\n validateParams: route.options?.validateParams ?? true,\n validateReturn: route.options?.validateReturn ?? false,\n description: route.options?.description,\n serializer: route.options?.serializer ?? routerOptions.serializer,\n isMutation: route.options?.isMutation,\n },\n };\n addToPersistedMethods(routeId, executable);\n }\n routesById.set(routeId, executable);\n routesCache.setMethodJitFns(routeId, executable as any);\n return executable;\n}\n\n/** Returns IDs of public middleware methods from the execution chain, excluding internal mion routes. */\nfunction getPublicMiddleFnIds(methods: RemoteMethod[]): string[] {\n const ids = methods\n .filter((exec) => isPublicExecutable(exec))\n .map((exec) => getRouterItemId(exec.pointer))\n .filter((mfId) => {\n if (mionInternalRoutes.includes(mfId)) return false;\n const exec = getMiddleFnExecutable(mfId);\n return exec && isPublicExecutable(exec);\n });\n return ids;\n}\n\nfunction getEntry(index: number, keyEntryList: RouterKeyEntryList) {\n return keyEntryList[index]?.[1];\n}\n\nfunction getRouteEntryProperties(\n minus1: RouterEntry | undefined,\n zero: RemoteMethod | RoutesWithId,\n plus1: RouterEntry | undefined\n) {\n const minus1IsRoute = minus1 && isRoute(minus1);\n const zeroIsRoute = (zero as RemoteMethod).type === HandlerType.route;\n const plus1IsRoute = plus1 && isRoute(plus1);\n\n const isExec = !!(zero as RemoteMethod).handler;\n\n return {\n isBetweenRoutes: minus1IsRoute && zeroIsRoute && plus1IsRoute,\n isExecutable: isExec,\n isRoute: zeroIsRoute,\n preLevelMiddleFns: [] as RemoteMethod[],\n postLevelMiddleFns: [] as RemoteMethod[],\n };\n}\n\nasync function getExecutablesFromMiddleFnsCollection(\n middleFnsDef: MiddleFnsCollection\n): Promise<(RawMethod | MiddleFnMethod | HeadersMethod)[]> {\n const results: (RawMethod | MiddleFnMethod | HeadersMethod)[] = [];\n for (const [key, middleFn] of Object.entries(middleFnsDef)) {\n if (isRawMiddleFnDef(middleFn)) {\n results.push(await getExecutableFromRawMiddleFn(middleFn, [key], 0));\n } else if (isHeadersMiddleFnDef(middleFn) || isMiddleFnDef(middleFn)) {\n results.push(await getExecutableFromMiddleFn(middleFn, [key], 0));\n } else {\n throw new Error(`Invalid middleFn: ${key}. Invalid middleFn definition`);\n }\n }\n return results;\n}\n\n/**\n * Validates that a contextDataFactory returns a valid context data object.\n * @param contextDataFactory The factory function to validate\n * @throws Error if the factory doesn't return a plain object with at least one property\n */\nfunction validateSharedDataFactory(opts?: Partial<RouterOptions>): void {\n if (!opts?.contextDataFactory) return;\n const testSharedData = opts.contextDataFactory();\n if (\n typeof testSharedData !== 'object' ||\n Array.isArray(testSharedData) ||\n testSharedData === null ||\n Object.keys(testSharedData).length === 0\n ) {\n throw new Error('contextDataFactory must return a plain object with at least one property');\n }\n}\n\n/** Maps serializer mode string to response body type code */\nfunction getSerializerCodeFromMode(mode: SerializerMode | undefined): SerializerCode {\n switch (mode) {\n case 'binary':\n return SerializerModes.binary;\n case 'stringifyJson':\n return SerializerModes.stringifyJson;\n case 'json':\n default:\n return SerializerModes.json;\n }\n}\n\n/** Path replacement as is not available in edge runtime */\nfunction joinPath(...parts: string[]): string {\n return parts.filter(Boolean).join('/');\n}\n"],"names":["MION_ROUTES","DEFAULT_ROUTE_OPTIONS","serializerMiddleFns","startMiddleFns","endMiddleFns","resetRemoteMethodsMetadata","resetPersistedMethods","resetRoutesCache","clearContextPool","clearRoutesFlowCache","setErrorOptions","mionErrorsRoutes","mionClientRoutes","isTestEnv","getPublicApi","isRoute","isRawMiddleFnDef","HandlerType","getENV","isMionCompileMode","isMionAOTEmitMode","MAX_ROUTE_NESTING","WORKFLOW_KEY","isAnyMiddleFnDef","isRoutes","isExecutable","getRoutePath","isHeadersMiddleFnDef","getRouterItemId","getPersistedMethod","getHandlerReflection","addToPersistedMethods","routesCache","getRawMethodReflection","isPublicExecutable","isMiddleFnDef","SerializerModes"],"mappings":";;;;;;;;;;;;;AA2DA,MAAM,qBAAqB,OAAO,OAAOA,gBAAW;AACpD,MAAM,iCAAqD,IAAA;AAC3D,MAAM,oCAA6E,IAAA;AACnF,MAAM,iCAA2C,IAAA;AACjD,MAAM,uCAA+C,IAAA;AACrD,MAAM,oCAAiC,IAAA;AACvC,MAAM,iCAA8B,IAAA;AACpC,IAAI,aAAa;AACjB,IAAI,gBAA+B,EAAC,GAAGC,oCAAA;AACvC,IAAI,sBAAsB;AAC1B,IAAI;AAGJ,MAAM,wBAAwB;AAAA,EAC1B,wBAAwBC,6BAAAA,oBAAoB;AAChD;AACA,MAAM,sBAAsB;AAAA,EACxB,uBAAuBA,6BAAAA,oBAAoB;AAC/C;AACA,IAAI,oBAAyC,EAAC,GAAG,sBAAA;AACjD,IAAI,kBAAuC,EAAC,GAAG,oBAAA;AACpCC,QAAAA,iBAAiC,CAAA;AACjCC,QAAAA,eAA+B,CAAA;AAInC,MAAM,yBAAyB,CAAC,SAAiB,WAAW,IAAI,IAAI;AACpE,MAAM,kBAAkB,MAAM,WAAW,QAAA;AACzC,MAAM,eAAe,MAAM,WAAW;AACtC,MAAM,qBAAqB,CAAC,OAAe,WAAW,IAAI,EAAE;AAC5D,MAAM,wBAAwB,CAAC,OAAe,cAAc,IAAI,EAAE;AAClE,MAAM,kBAAkB,MAAM,cAAc;AAC5C,MAAM,gBAAgB,MAAM;AAC5B,MAAM,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AAAA,IACvE,WAAWW,iBAAAA,qBAAqB,QAAQ,KAAKQ,iBAAAA,cAAc,QAAQ,GAAG;AAClE,cAAQ,KAAK,MAAM,0BAA0B,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC;AAAA,IACpE,OAAO;AACH,YAAM,IAAI,MAAM,qBAAqB,GAAG,+BAA+B;AAAA,IAC3E;AAAA,EACJ;AACA,SAAO;AACX;AAOA,SAAS,0BAA0B,MAAqC;AACpE,MAAI,CAAC,MAAM,mBAAoB;AAC/B,QAAM,iBAAiB,KAAK,mBAAA;AAC5B,MACI,OAAO,mBAAmB,YAC1B,MAAM,QAAQ,cAAc,KAC5B,mBAAmB,QACnB,OAAO,KAAK,cAAc,EAAE,WAAW,GACzC;AACE,UAAM,IAAI,MAAM,0EAA0E;AAAA,EAC9F;AACJ;AAGA,SAAS,0BAA0B,MAAkD;AACjF,UAAQ,MAAA;AAAA,IACJ,KAAK;AACD,aAAOC,KAAAA,gBAAgB;AAAA,IAC3B,KAAK;AACD,aAAOA,KAAAA,gBAAgB;AAAA,IAC3B,KAAK;AAAA,IACL;AACI,aAAOA,KAAAA,gBAAgB;AAAA,EAAA;AAEnC;AAGA,SAAS,YAAY,OAAyB;AAC1C,SAAO,MAAM,OAAO,OAAO,EAAE,KAAK,GAAG;AACzC;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"router.cjs","sources":["../../../src/router.ts"],"sourcesContent":["/* ########\n * 2022 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\n/** Lightweight path join for error messages (avoids Node's 'path' module for edge compatibility) */\nimport type {Route, RouterOptions, Routes, RouterEntry} from './types/general.ts';\nimport type {\n RemoteMethod,\n MethodsExecutionChain,\n RawMethod,\n HeadersMethod,\n MiddleFnMethod,\n RouteMethod,\n} from './types/remoteMethods.ts';\nimport type {PublicApi, PrivateDef, MiddleFnsCollection} from './types/publicMethods.ts';\nimport type {HeadersMiddleFnDef, MiddleFnDef, RawMiddleFnDef} from './types/definitions.ts';\nimport {DEFAULT_ROUTE_OPTIONS, MAX_ROUTE_NESTING, WORKFLOW_KEY} from './constants.ts';\nimport {\n isRawMiddleFnDef,\n isHeadersMiddleFnDef,\n isExecutable,\n isMiddleFnDef,\n isRoute,\n isRoutes,\n isAnyMiddleFnDef,\n isPublicExecutable,\n} from './types/guards.ts';\nimport {\n HandlerType,\n SerializerModes,\n SerializerCode,\n SerializerMode,\n isTestEnv,\n isMionCompileMode,\n isMionAOTEmitMode,\n resetRoutesCache,\n} from '@mionjs/core';\nimport {getRawMethodReflection, getHandlerReflection} from './lib/reflection.ts';\nimport {serializerMiddleFns} from './routes/serializer.routes.ts';\nimport {getRouterItemId, getRoutePath, getENV, MION_ROUTES, routesCache} from '@mionjs/core';\nimport {setErrorOptions} from '@mionjs/core';\nimport {getPublicApi, resetRemoteMethodsMetadata} from './lib/remoteMethods.ts';\nimport {addToPersistedMethods, getPersistedMethod, resetPersistedMethods} from './lib/methodsCache.ts';\nimport {mionClientRoutes} from './routes/client.routes.ts';\nimport {mionErrorsRoutes} from './routes/errors.routes.ts';\nimport {clearRoutesFlowCache} from './routesFlow.ts';\nimport {clearContextPool} from './callContext.ts';\n\ntype RouterKeyEntryList = [string, RouterEntry][];\ntype RoutesWithId = {\n pathPointer: string[];\n routes: Routes;\n};\n\n// ############# PRIVATE STATE #############\n\nconst mionInternalRoutes = Object.values(MION_ROUTES) as string[];\nconst flatRouter: Map<string, MethodsExecutionChain> = new Map(); // Main Router\nconst middleFnsById: Map<string, MiddleFnMethod | HeadersMethod | RawMethod> = new Map();\nconst routesById: Map<string, RouteMethod> = new Map();\nconst rawMiddleFnsById: Map<string, RawMethod> = new Map();\nconst middleFnNames: Set<string> = new Set();\nconst routeNames: Set<string> = new Set();\nlet complexity = 0;\nlet routerOptions: RouterOptions = {...DEFAULT_ROUTE_OPTIONS};\nlet isRouterInitialized = false;\nlet allExecutablesIds: string[] | undefined;\nlet platformConfig: Record<string, unknown> | undefined;\n\n/** Global middleFns to be run before and after any other middleFns or routes set using `registerRoutes` */\nconst defaultStartMiddleFns = {\n mionDeserializeRequest: serializerMiddleFns.mionDeserializeRequest,\n};\nconst defaultEndMiddleFns = {\n mionSerializeResponse: serializerMiddleFns.mionSerializeResponse,\n};\nlet startMiddleFnsDef: MiddleFnsCollection = {...defaultStartMiddleFns};\nlet endMiddleFnsDef: MiddleFnsCollection = {...defaultEndMiddleFns};\nexport let startMiddleFns: RemoteMethod[] = [];\nexport let endMiddleFns: RemoteMethod[] = [];\n\n// ############# PUBLIC METHODS #############\n\nexport const getRouteExecutionChain = (path: string) => flatRouter.get(path);\nexport const getRouteEntries = () => flatRouter.entries();\nexport const geRoutesSize = () => flatRouter.size;\nexport const getRouteExecutable = (id: string) => routesById.get(id);\nexport const getMiddleFnExecutable = (id: string) => middleFnsById.get(id);\nexport const geMiddleFnsSize = () => middleFnsById.size;\nexport const getComplexity = () => complexity;\nexport const getRouterOptions = <Opts extends RouterOptions>(): Readonly<Opts> => routerOptions as Opts;\nexport const getAnyExecutable = (id: string) => routesById.get(id) || middleFnsById.get(id) || rawMiddleFnsById.get(id);\n\n/** Sets platform adapter config and notifies the parent process (Vite plugin) that the server is ready.\n * Called automatically by platform adapters. Sends an IPC message containing both the\n * serializable router config and the platform adapter config. */\nexport function setPlatformConfig(config: Record<string, unknown>): void {\n platformConfig = config;\n if (isMionAOTEmitMode() && typeof process.send === 'function') {\n const routerConfig = Object.fromEntries(Object.entries(routerOptions).filter(([, v]) => typeof v !== 'function'));\n try {\n process.send({type: 'mion-platform-ready', routerConfig, platformConfig: config});\n } catch (err) {\n console.error('[mion] Failed to send platform-ready IPC:', err);\n }\n }\n}\n\n/** Returns the platform adapter config set by setPlatformConfig(). */\nexport const getPlatformConfig = (): Readonly<Record<string, unknown>> | undefined => platformConfig;\n\nexport const resetRouter = () => {\n flatRouter.clear();\n middleFnsById.clear();\n routesById.clear();\n rawMiddleFnsById.clear();\n middleFnNames.clear();\n routeNames.clear();\n complexity = 0;\n routerOptions = {...DEFAULT_ROUTE_OPTIONS};\n startMiddleFnsDef = {...defaultStartMiddleFns};\n endMiddleFnsDef = {...defaultEndMiddleFns};\n startMiddleFns = [];\n endMiddleFns = [];\n isRouterInitialized = false;\n allExecutablesIds = undefined;\n platformConfig = undefined;\n resetRemoteMethodsMetadata();\n resetPersistedMethods();\n resetRoutesCache();\n clearContextPool();\n clearRoutesFlowCache();\n // Note: We intentionally do NOT call resetJitFnCaches() here because:\n // 1. JIT function caches are global and should persist across router resets\n // 2. The serializableClassRegistry (cleared by resetJitFnCaches) is needed for\n // serialization/deserialization of classes like RpcError\n // resetJitFnCaches() should only be called in specific test scenarios that need\n // to test AOT cache loading behavior\n};\n\n// simpler router initialization\nexport async function initMionRouter<R extends Routes>(routes: R, opts?: Partial<RouterOptions>): Promise<PublicApi<R>> {\n await initRouter(opts);\n const publicApi = await registerRoutes(routes);\n // Emit AOT caches once after ALL routes (error, client, user) are registered\n await emitAOTCaches();\n return publicApi;\n}\n\n/**\n * Initializes the Router.\n * @param application\n * @param contextDataFactory a factory function that returns an object to be shared in the `callContext.shared`\n * @param routerOptions\n * @returns\n */\nexport async function initRouter(opts?: Partial<RouterOptions>): Promise<Readonly<RouterOptions>> {\n if (isRouterInitialized) throw new Error('Router has already been initialized');\n routerOptions = {...routerOptions, ...opts};\n validateSharedDataFactory(routerOptions);\n Object.freeze(routerOptions);\n setErrorOptions(routerOptions);\n if (routerOptions.aot) await loadAOTCaches();\n isRouterInitialized = true;\n await registerRoutes({...mionErrorsRoutes});\n if (!routerOptions.skipClientRoutes) await registerRoutes({...mionClientRoutes});\n if (!isTestEnv()) console.log('mion router initialized', {routerOptions});\n return routerOptions;\n}\n\nexport async function registerRoutes<R extends Routes>(routes: R): Promise<PublicApi<R>> {\n if (!isRouterInitialized) throw new Error('initRouter should be called first');\n startMiddleFns = await getExecutablesFromMiddleFnsCollection(startMiddleFnsDef);\n endMiddleFns = await getExecutablesFromMiddleFnsCollection(endMiddleFnsDef);\n await recursiveFlatRoutes(routes);\n if (shouldFullGenerateSpec()) {\n return getPublicApi(routes);\n }\n return {} as PublicApi<R>;\n}\n\n/** Add middleFns at the start af the ExecutionChain, adds them before any other existing start middleFns by default */\nexport function addStartMiddleFns(middleFnsDef: MiddleFnsCollection, appendBeforeExisting = true) {\n if (isRouterInitialized) throw new Error('Can not add start middleFns after the router has been initialized');\n if (appendBeforeExisting) {\n startMiddleFnsDef = {...middleFnsDef, ...startMiddleFnsDef};\n return;\n }\n startMiddleFnsDef = {...startMiddleFnsDef, ...middleFnsDef};\n}\n\n/** Add middleFns at the end af the ExecutionChain, adds them after any other existing end middleFns by default */\nexport function addEndMiddleFns(middleFnsDef: MiddleFnsCollection, prependAfterExisting = true) {\n if (isRouterInitialized) throw new Error('Can not add end middleFns after the router has been initialized');\n if (prependAfterExisting) {\n endMiddleFnsDef = {...endMiddleFnsDef, ...middleFnsDef};\n return;\n }\n endMiddleFnsDef = {...middleFnsDef, ...endMiddleFnsDef};\n}\n\nexport function isPrivateDefinition(entry: RouterEntry, id: string): entry is PrivateDef {\n if (isRoute(entry)) return false;\n if (isRawMiddleFnDef(entry)) return true;\n try {\n const executable = getMiddleFnExecutable(id) || getRouteExecutable(id);\n if (!executable)\n throw new Error(`Route or MiddleFn ${id} not found. Please check you have called router.registerRoutes first.`);\n return isPrivateExecutable(executable);\n } catch {\n // error thrown because entry is a Routes object and does not have any handler\n return false;\n }\n}\n\nexport function isPrivateExecutable(executable: RemoteMethod): boolean {\n if (executable.type === HandlerType.rawMiddleFn) return true;\n if (executable.type === HandlerType.route) return false;\n const hasPublicParams = !!executable.paramNames?.length;\n const hasHeaderParams = !!(executable as HeadersMethod).headersParam?.headerNames?.length;\n return !hasPublicParams && !hasHeaderParams && !executable.hasReturnData;\n}\n\nexport function getTotalExecutables(): number {\n return routesById.size + middleFnsById.size + rawMiddleFnsById.size;\n}\n\nexport function getAllExecutablesIds(): string[] {\n if (allExecutablesIds) return allExecutablesIds;\n allExecutablesIds = [...routesById.keys(), ...middleFnsById.keys(), ...rawMiddleFnsById.keys()];\n return allExecutablesIds;\n}\n\n// used by codegen\nexport function shouldFullGenerateSpec(): boolean {\n return routerOptions.getPublicRoutesData || getENV('GENERATE_ROUTER_SPEC') === 'true' || isMionCompileMode();\n}\n\nexport function getRouteExecutableFromPath(path: string): RouteMethod {\n const executionChain = flatRouter.get(path);\n if (!executionChain) {\n // Return the not-found route executable\n return getAnyExecutable(MION_ROUTES.notFound) as RouteMethod;\n }\n return executionChain.methods[executionChain.routeIndex] as RouteMethod;\n}\n\n// ############# PRIVATE METHODS #############\n\nasync function loadAOTCaches() {\n const loader = await import('./aot/aotCacheLoader.ts');\n return loader.loadRouterAOTCaches();\n}\n\nasync function emitAOTCaches() {\n if (!isMionAOTEmitMode()) return;\n // Dynamic import resolves relative to this source file.\n // This only runs via vite-node (MION_COMPILE=buildOnly|childProcess), which always resolves from source.\n const aotEmitter = await import('./lib/aotEmitter.ts');\n return aotEmitter.emitAOTCaches();\n}\n\n/**\n * Optimized algorithm to flatten the routes object into a list of Executable objects.\n * @param routes\n * @param currentPointer current pointer in the routes object i.e. ['users', 'get']\n * @param preMiddleFns middleFns one level up preceding current pointer\n * @param postMiddleFns middleFns one level up following the current pointer\n * @param nestLevel\n */\nasync function recursiveFlatRoutes(\n routes: Routes,\n currentPointer: string[] = [],\n preMiddleFns: RemoteMethod[] = [],\n postMiddleFns: RemoteMethod[] = [],\n nestLevel = 0\n) {\n if (nestLevel > MAX_ROUTE_NESTING)\n throw new Error('Too many nested routes, you can only nest routes ${MAX_ROUTE_NESTING} levels');\n\n const entries = Object.entries(routes);\n if (entries.length === 0)\n throw new Error(\n `Invalid route: ${currentPointer.length ? joinPath(...currentPointer) : '*'}. Can Not define empty routes`\n );\n\n let minus1Props: ReturnType<typeof getRouteEntryProperties> | null = null;\n for (let index = 0; index < entries.length; index++) {\n const [key, item] = entries[index];\n // create the executable items\n const newPointer = [...currentPointer, key];\n let routeEntry: RemoteMethod | RoutesWithId;\n if (typeof key !== 'string' || !isNaN(key as any))\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. Numeric route names are not allowed`);\n if (key.includes(',')) throw new Error(`Invalid route: ${joinPath(...newPointer)}. Route names cannot contain commas.`);\n if (key === WORKFLOW_KEY)\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. '${WORKFLOW_KEY}' is a reserved mion route name.`);\n\n // generates a middleFn\n if (isAnyMiddleFnDef(item)) {\n routeEntry = await getExecutableFromAnyMiddleFn(item, newPointer, nestLevel);\n if (middleFnNames.has(routeEntry.id))\n throw new Error(\n `Invalid middleFn: ${joinPath(...newPointer)}. Naming collision, Naming collision, duplicated middleFn.`\n );\n middleFnNames.add(routeEntry.id);\n }\n\n // generates a route\n else if (isRoute(item)) {\n routeEntry = await getExecutableFromRoute(item, newPointer, nestLevel);\n if (routeNames.has(routeEntry.id))\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. Naming collision, duplicated route`);\n routeNames.add(routeEntry.id);\n }\n\n // generates structure required to go one level down\n else if (isRoutes(item)) {\n routeEntry = {\n pathPointer: newPointer,\n routes: item,\n };\n }\n\n // throws an error if the route is invalid\n else {\n const itemType = typeof item;\n throw new Error(`Invalid route: ${joinPath(...newPointer)}. Type <${itemType}> is not a valid route.`);\n }\n\n // recurse into sublevels\n minus1Props = await recursiveCreateExecutionChainAsync(\n routeEntry,\n newPointer,\n preMiddleFns,\n postMiddleFns,\n nestLevel,\n index,\n entries,\n minus1Props\n );\n\n complexity++;\n }\n}\n\nasync function recursiveCreateExecutionChainAsync(\n routeEntry: RemoteMethod | RoutesWithId,\n currentPointer: string[],\n preMiddleFns: RemoteMethod[],\n postMiddleFns: RemoteMethod[],\n nestLevel: number,\n index: number,\n routeKeyedEntries: RouterKeyEntryList,\n minus1Props: ReturnType<typeof getRouteEntryProperties> | null\n) {\n const minus1 = getEntry(index - 1, routeKeyedEntries);\n const plus1 = getEntry(index + 1, routeKeyedEntries);\n const props = getRouteEntryProperties(minus1, routeEntry, plus1);\n\n if (props.isBetweenRoutes && minus1Props) {\n props.preLevelMiddleFns = minus1Props.preLevelMiddleFns;\n props.postLevelMiddleFns = minus1Props.postLevelMiddleFns;\n } else {\n for (let i = 0; i < routeKeyedEntries.length; i++) {\n const [k, entry] = routeKeyedEntries[i];\n complexity++;\n if (!isAnyMiddleFnDef(entry)) continue;\n const newPointer = [...currentPointer.slice(0, -1), k];\n const executable = await getExecutableFromAnyMiddleFn(entry, newPointer, nestLevel);\n if (i < index) props.preLevelMiddleFns.push(executable);\n if (i > index) props.postLevelMiddleFns.push(executable);\n }\n }\n const isExec = isExecutable(routeEntry);\n\n if (isExec && props.isRoute) {\n const path = getRoutePath(routeEntry.pointer, routerOptions);\n const routeMethod = routeEntry as RouteMethod;\n const levelMethods = [\n ...preMiddleFns,\n ...props.preLevelMiddleFns,\n routeEntry,\n ...props.postLevelMiddleFns,\n ...postMiddleFns,\n ];\n const methods = [...startMiddleFns, ...levelMethods, ...endMiddleFns];\n const executionChain: MethodsExecutionChain = {\n routeIndex: startMiddleFns.length + preMiddleFns.length + props.preLevelMiddleFns.length,\n methods,\n serializer: getSerializerCodeFromMode(routeMethod.options.serializer),\n };\n const middleFnIds = getPublicMiddleFnIds(methods);\n // add middleware functions deps, so can be serialized with the router\n if (middleFnIds.length) routeMethod.middleFnIds = middleFnIds;\n flatRouter.set(path, executionChain);\n } else if (!isExec) {\n await recursiveFlatRoutes(\n routeEntry.routes,\n routeEntry.pathPointer,\n [...preMiddleFns, ...props.preLevelMiddleFns],\n [...props.postLevelMiddleFns, ...postMiddleFns],\n nestLevel + 1\n );\n }\n\n return props;\n}\n\nasync function getExecutableFromAnyMiddleFn(\n middleFn: MiddleFnDef | HeadersMiddleFnDef | RawMiddleFnDef,\n middleFnPointer: string[],\n nestLevel: number\n) {\n if (isRawMiddleFnDef(middleFn)) return getExecutableFromRawMiddleFn(middleFn, middleFnPointer, nestLevel);\n return getExecutableFromMiddleFn(middleFn, middleFnPointer, nestLevel);\n}\n\nexport async function getExecutableFromMiddleFn(\n middleFn: MiddleFnDef | HeadersMiddleFnDef,\n middleFnPointer: string[],\n nestLevel: number\n): Promise<MiddleFnMethod | HeadersMethod> {\n const isHeader = isHeadersMiddleFnDef(middleFn);\n // todo fix header id should be same as any other one and then maybe map from id to header name\n const middleFnId = getRouterItemId(middleFnPointer);\n const existing = middleFnsById.get(middleFnId);\n if (existing) return existing as MiddleFnMethod;\n\n type MixedMiddleFn = (Omit<MiddleFnMethod, 'type'> | Omit<HeadersMethod, 'type'>) & {\n type: typeof HandlerType.middleFn | typeof HandlerType.headersMiddleFn;\n };\n\n const compiledMethod = getPersistedMethod(middleFnId, middleFn.handler);\n let executable: MixedMiddleFn;\n if (compiledMethod) {\n executable = compiledMethod as MixedMiddleFn;\n } else {\n const reflectionData = await getHandlerReflection(\n middleFn.handler,\n middleFnId,\n routerOptions,\n isHeader,\n middleFn.options?.strictTypes\n );\n executable = {\n id: middleFnId,\n type: isHeader ? HandlerType.headersMiddleFn : HandlerType.middleFn,\n nestLevel,\n handler: middleFn.handler,\n pointer: middleFnPointer,\n ...reflectionData,\n options: {\n runOnError: !!middleFn.options?.runOnError,\n validateParams: middleFn.options?.validateParams ?? true,\n validateReturn: middleFn.options?.validateReturn ?? false,\n description: middleFn.options?.description,\n strictTypes: middleFn.options?.strictTypes ?? routerOptions.strictTypes,\n },\n };\n addToPersistedMethods(middleFnId, executable);\n }\n\n middleFnsById.set(middleFnId, executable as any);\n routesCache.setMethodJitFns(middleFnId, executable as any);\n return executable as any;\n}\n\nexport async function getExecutableFromRawMiddleFn(\n middleFn: RawMiddleFnDef,\n middleFnPointer: string[],\n nestLevel: number\n): Promise<RawMethod> {\n const middleFnId = getRouterItemId(middleFnPointer);\n const existing = rawMiddleFnsById.get(middleFnId);\n if (existing) return existing as RawMethod;\n const reflectionData = await getRawMethodReflection(middleFn.handler, middleFnId, routerOptions);\n const executable: RawMethod = {\n id: middleFnId,\n type: HandlerType.rawMiddleFn,\n nestLevel,\n handler: middleFn.handler,\n pointer: middleFnPointer,\n ...reflectionData,\n options: {\n runOnError: !!middleFn.options?.runOnError,\n validateParams: false,\n validateReturn: false,\n description: middleFn.options?.description,\n },\n };\n rawMiddleFnsById.set(middleFnId, executable);\n routesCache.setMethodJitFns(middleFnId, executable as any);\n return executable;\n}\n\nexport async function getExecutableFromRoute(route: Route, routePointer: string[], nestLevel: number): Promise<RouteMethod> {\n const routeId = getRouterItemId(routePointer);\n const existing = routesById.get(routeId);\n if (existing) return existing as RouteMethod;\n\n const compiledMethod = getPersistedMethod(routeId, route.handler);\n let executable: RouteMethod;\n if (compiledMethod) {\n executable = compiledMethod as RouteMethod;\n } else {\n const reflectionData = await getHandlerReflection(\n route.handler,\n routeId,\n routerOptions,\n false,\n route.options?.strictTypes\n );\n executable = {\n id: routeId,\n type: HandlerType.route,\n nestLevel,\n handler: route.handler,\n pointer: routePointer,\n ...reflectionData,\n options: {\n runOnError: false,\n validateParams: route.options?.validateParams ?? true,\n validateReturn: route.options?.validateReturn ?? false,\n description: route.options?.description,\n serializer: route.options?.serializer ?? routerOptions.serializer,\n isMutation: route.options?.isMutation,\n strictTypes: route.options?.strictTypes ?? routerOptions.strictTypes,\n },\n };\n addToPersistedMethods(routeId, executable);\n }\n routesById.set(routeId, executable);\n routesCache.setMethodJitFns(routeId, executable as any);\n return executable;\n}\n\n/** Returns IDs of public middleware methods from the execution chain, excluding internal mion routes. */\nfunction getPublicMiddleFnIds(methods: RemoteMethod[]): string[] {\n const ids = methods\n .filter((exec) => isPublicExecutable(exec))\n .map((exec) => getRouterItemId(exec.pointer))\n .filter((mfId) => {\n if (mionInternalRoutes.includes(mfId)) return false;\n const exec = getMiddleFnExecutable(mfId);\n return exec && isPublicExecutable(exec);\n });\n return ids;\n}\n\nfunction getEntry(index: number, keyEntryList: RouterKeyEntryList) {\n return keyEntryList[index]?.[1];\n}\n\nfunction getRouteEntryProperties(\n minus1: RouterEntry | undefined,\n zero: RemoteMethod | RoutesWithId,\n plus1: RouterEntry | undefined\n) {\n const minus1IsRoute = minus1 && isRoute(minus1);\n const zeroIsRoute = (zero as RemoteMethod).type === HandlerType.route;\n const plus1IsRoute = plus1 && isRoute(plus1);\n\n const isExec = !!(zero as RemoteMethod).handler;\n\n return {\n isBetweenRoutes: minus1IsRoute && zeroIsRoute && plus1IsRoute,\n isExecutable: isExec,\n isRoute: zeroIsRoute,\n preLevelMiddleFns: [] as RemoteMethod[],\n postLevelMiddleFns: [] as RemoteMethod[],\n };\n}\n\nasync function getExecutablesFromMiddleFnsCollection(\n middleFnsDef: MiddleFnsCollection\n): Promise<(RawMethod | MiddleFnMethod | HeadersMethod)[]> {\n const results: (RawMethod | MiddleFnMethod | HeadersMethod)[] = [];\n for (const [key, middleFn] of Object.entries(middleFnsDef)) {\n if (isRawMiddleFnDef(middleFn)) {\n results.push(await getExecutableFromRawMiddleFn(middleFn, [key], 0));\n } else if (isHeadersMiddleFnDef(middleFn) || isMiddleFnDef(middleFn)) {\n results.push(await getExecutableFromMiddleFn(middleFn, [key], 0));\n } else {\n throw new Error(`Invalid middleFn: ${key}. Invalid middleFn definition`);\n }\n }\n return results;\n}\n\n/**\n * Validates that a contextDataFactory returns a valid context data object.\n * @param contextDataFactory The factory function to validate\n * @throws Error if the factory doesn't return a plain object with at least one property\n */\nfunction validateSharedDataFactory(opts?: Partial<RouterOptions>): void {\n if (!opts?.contextDataFactory) return;\n const testSharedData = opts.contextDataFactory();\n if (\n typeof testSharedData !== 'object' ||\n Array.isArray(testSharedData) ||\n testSharedData === null ||\n Object.keys(testSharedData).length === 0\n ) {\n throw new Error('contextDataFactory must return a plain object with at least one property');\n }\n}\n\n/** Maps serializer mode string to response body type code */\nfunction getSerializerCodeFromMode(mode: SerializerMode | undefined): SerializerCode {\n switch (mode) {\n case 'binary':\n return SerializerModes.binary;\n case 'stringifyJson':\n return SerializerModes.stringifyJson;\n case 'json':\n default:\n return SerializerModes.json;\n }\n}\n\n/** Path replacement as is not available in edge runtime */\nfunction joinPath(...parts: string[]): string {\n return parts.filter(Boolean).join('/');\n}\n"],"names":["MION_ROUTES","DEFAULT_ROUTE_OPTIONS","serializerMiddleFns","startMiddleFns","endMiddleFns","isMionAOTEmitMode","resetRemoteMethodsMetadata","resetPersistedMethods","resetRoutesCache","clearContextPool","clearRoutesFlowCache","setErrorOptions","mionErrorsRoutes","mionClientRoutes","isTestEnv","getPublicApi","isRoute","isRawMiddleFnDef","HandlerType","getENV","isMionCompileMode","MAX_ROUTE_NESTING","WORKFLOW_KEY","isAnyMiddleFnDef","isRoutes","isExecutable","getRoutePath","isHeadersMiddleFnDef","getRouterItemId","getPersistedMethod","getHandlerReflection","addToPersistedMethods","routesCache","getRawMethodReflection","isPublicExecutable","isMiddleFnDef","SerializerModes"],"mappings":";;;;;;;;;;;;;AA2DA,MAAM,qBAAqB,OAAO,OAAOA,gBAAW;AACpD,MAAM,iCAAqD,IAAA;AAC3D,MAAM,oCAA6E,IAAA;AACnF,MAAM,iCAA2C,IAAA;AACjD,MAAM,uCAA+C,IAAA;AACrD,MAAM,oCAAiC,IAAA;AACvC,MAAM,iCAA8B,IAAA;AACpC,IAAI,aAAa;AACjB,IAAI,gBAA+B,EAAC,GAAGC,oCAAA;AACvC,IAAI,sBAAsB;AAC1B,IAAI;AACJ,IAAI;AAGJ,MAAM,wBAAwB;AAAA,EAC1B,wBAAwBC,6BAAAA,oBAAoB;AAChD;AACA,MAAM,sBAAsB;AAAA,EACxB,uBAAuBA,6BAAAA,oBAAoB;AAC/C;AACA,IAAI,oBAAyC,EAAC,GAAG,sBAAA;AACjD,IAAI,kBAAuC,EAAC,GAAG,oBAAA;AACpCC,QAAAA,iBAAiC,CAAA;AACjCC,QAAAA,eAA+B,CAAA;AAInC,MAAM,yBAAyB,CAAC,SAAiB,WAAW,IAAI,IAAI;AACpE,MAAM,kBAAkB,MAAM,WAAW,QAAA;AACzC,MAAM,eAAe,MAAM,WAAW;AAC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