@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.
Files changed (40) hide show
  1. package/.dist/cjs/index.cjs +2 -0
  2. package/.dist/cjs/index.cjs.map +1 -1
  3. package/.dist/cjs/src/defaultRoutes.cjs.map +1 -1
  4. package/.dist/cjs/src/lib/aotEmitter.cjs +4 -1
  5. package/.dist/cjs/src/lib/aotEmitter.cjs.map +1 -1
  6. package/.dist/cjs/src/lib/aotEmitter.d.ts +6 -0
  7. package/.dist/cjs/src/lib/reflection.cjs +10 -6
  8. package/.dist/cjs/src/lib/reflection.cjs.map +1 -1
  9. package/.dist/cjs/src/lib/reflection.d.ts +1 -1
  10. package/.dist/cjs/src/lib/test/aotEmitter-test-router.cjs.map +1 -1
  11. package/.dist/cjs/src/router.cjs +34 -4
  12. package/.dist/cjs/src/router.cjs.map +1 -1
  13. package/.dist/cjs/src/router.d.ts +2 -0
  14. package/.dist/cjs/src/routesFlow.cjs +3 -3
  15. package/.dist/cjs/src/routesFlow.cjs.map +1 -1
  16. package/.dist/cjs/src/types/general.cjs +1 -1
  17. package/.dist/cjs/src/types/general.d.ts +1 -0
  18. package/.dist/cjs/src/types/remoteMethods.cjs +3 -3
  19. package/.dist/cjs/src/types/remoteMethods.cjs.map +1 -1
  20. package/.dist/cjs/src/types/remoteMethods.d.ts +3 -3
  21. package/.dist/esm/index.js +3 -1
  22. package/.dist/esm/src/defaultRoutes.js.map +1 -1
  23. package/.dist/esm/src/lib/aotEmitter.d.ts +6 -0
  24. package/.dist/esm/src/lib/aotEmitter.js +4 -1
  25. package/.dist/esm/src/lib/aotEmitter.js.map +1 -1
  26. package/.dist/esm/src/lib/reflection.d.ts +1 -1
  27. package/.dist/esm/src/lib/reflection.js +10 -6
  28. package/.dist/esm/src/lib/reflection.js.map +1 -1
  29. package/.dist/esm/src/lib/test/aotEmitter-test-router.js.map +1 -1
  30. package/.dist/esm/src/router.d.ts +2 -0
  31. package/.dist/esm/src/router.js +35 -5
  32. package/.dist/esm/src/router.js.map +1 -1
  33. package/.dist/esm/src/routesFlow.js +1 -1
  34. package/.dist/esm/src/routesFlow.js.map +1 -1
  35. package/.dist/esm/src/types/general.d.ts +1 -0
  36. package/.dist/esm/src/types/general.js +1 -1
  37. package/.dist/esm/src/types/remoteMethods.d.ts +3 -3
  38. package/.dist/esm/src/types/remoteMethods.js +3 -3
  39. package/.dist/esm/src/types/remoteMethods.js.map +1 -1
  40. package/package.json +4 -4
@@ -13,6 +13,8 @@ export declare const geMiddleFnsSize: () => number;
13
13
  export declare const getComplexity: () => number;
14
14
  export declare const getRouterOptions: <Opts extends RouterOptions>() => Readonly<Opts>;
15
15
  export declare const getAnyExecutable: (id: string) => RouteMethod<any> | MiddleFnMethod<any> | HeadersMethod<any> | RawMethod<any> | undefined;
16
+ export declare function setPlatformConfig(config: Record<string, unknown>): void;
17
+ export declare const getPlatformConfig: () => Readonly<Record<string, unknown>> | undefined;
16
18
  export declare const resetRouter: () => void;
17
19
  export declare function initMionRouter<R extends Routes>(routes: R, opts?: Partial<RouterOptions>): Promise<PublicApi<R>>;
18
20
  export declare function initRouter(opts?: Partial<RouterOptions>): Promise<Readonly<RouterOptions>>;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const core = require("@mionjs/core");
4
- const virtual_mionServerPureFns = require("virtual:mion-server-pure-fns");
4
+ const serverPureFns = require("@mionjs/core/server-pure-fns");
5
5
  const src_router = require("./router.cjs");
6
6
  const src_types_general = require("./types/general.cjs");
7
7
  const src_types_remoteMethods = require("./types/remoteMethods.cjs");
@@ -156,7 +156,7 @@ function insertMappingMethods(middleMethods, mappings) {
156
156
  errorData: { mapping }
157
157
  });
158
158
  }
159
- if (!virtual_mionServerPureFns.serverPureFnsCache[core.PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash]?.fn) {
159
+ if (!serverPureFns.serverPureFnsCache[core.PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash]?.fn) {
160
160
  throw new core.RpcError({
161
161
  statusCode: core.StatusCodes.UNEXPECTED_ERROR,
162
162
  type: "routesFlow-mapping-missing-pure-fn",
@@ -201,7 +201,7 @@ createMappingMethod.__type = ["RoutesFlowMapping", "mapping", () => src_types_re
201
201
  function createMappingHandler(mapping) {
202
202
  return __assignType((ctx) => {
203
203
  const sourceOutput = ctx.response.body[mapping.fromId];
204
- const entry = virtual_mionServerPureFns.serverPureFnsCache[core.PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash];
204
+ const entry = serverPureFns.serverPureFnsCache[core.PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash];
205
205
  if (!entry?.fn) {
206
206
  throw new core.RpcError({
207
207
  statusCode: core.StatusCodes.UNEXPECTED_ERROR,
@@ -1 +1 @@
1
- {"version":3,"file":"routesFlow.cjs","sources":["../../../src/routesFlow.ts"],"sourcesContent":["/* ########\n * 2023 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport {\n RpcError,\n SerializerCode,\n SerializerModes,\n StatusCodes,\n HandlerType,\n getNoopJitFns,\n PURE_SERVER_FN_NAMESPACE,\n fromBase64Url,\n} from '@mionjs/core';\nimport {serverPureFnsCache} from 'virtual:mion-server-pure-fns';\nimport {getRouteExecutionChain, getRouterOptions, startMiddleFns, endMiddleFns} from './router.ts';\nimport {RouterOptions} from './types/general.ts';\nimport {MethodsExecutionChain, RemoteMethod} from './types/remoteMethods.ts';\nimport {RoutesFlowExecutionResult} from './types/context.ts';\nimport type {CallContext} from './types/context.ts';\nimport type {RoutesFlowQuery, RoutesFlowMapping} from '@mionjs/core';\n\n// ############# ROUTES_FLOW CACHE #############\n\n/** FILO cache for merged execution chains. Key is the query string, value is the cached chain. */\nconst routesFlowCache = new Map<string, MethodsExecutionChain>();\nconst cacheOrder: string[] = [];\n/** Cache for mapping RemoteMethods keyed by their unique ID */\nconst mappingMethodCache = new Map<string, RemoteMethod>();\n\n/** Clears the routesFlow cache and mapping method cache - useful for testing */\nexport function clearRoutesFlowCache(): void {\n routesFlowCache.clear();\n cacheOrder.length = 0;\n mappingMethodCache.clear();\n}\n\n/** Returns the current routesFlow cache size */\nexport function getRoutesFlowCacheSize(): number {\n return routesFlowCache.size;\n}\n\n/** Returns a cached routesFlow chain by query string */\nexport function getCachedRoutesFlow(query: string): MethodsExecutionChain | undefined {\n return routesFlowCache.get(query);\n}\n\n/** Adds a merged chain to the cache with FILO eviction */\nfunction addToRoutesFlowCache(query: string, chain: MethodsExecutionChain): void {\n const routerOpts = getRouterOptions();\n const maxSize = routerOpts.maxRoutesFlowsCacheSize;\n // Caching disabled\n if (maxSize <= 0) return;\n // Evict oldest entries if cache is full (FILO - First In, Last Out)\n while (cacheOrder.length >= maxSize) {\n const oldestKey = cacheOrder.shift();\n if (oldestKey) routesFlowCache.delete(oldestKey);\n }\n routesFlowCache.set(query, chain);\n cacheOrder.push(query);\n}\n\n// ############# QUERY PARSING #############\n\n/** Decodes a base64url-encoded JSON routesFlow query string, expects `data=<base64url>` format */\nfunction decodeRoutesFlowQuery(urlQuery: string): RoutesFlowQuery {\n try {\n const dataParam = urlQuery.startsWith('data=') ? urlQuery.slice(5) : urlQuery;\n const jsonString = fromBase64Url(dataParam);\n return JSON.parse(jsonString) as RoutesFlowQuery;\n } catch (e: any) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-invalid-query',\n publicMessage: 'RoutesFlow query string is not valid base64url-encoded JSON.',\n errorData: {parseError: e?.message || 'Unknown error'},\n });\n }\n}\n\n// ############# ROUTES_FLOW #############\n\n/** Builds or retrieves a cached merged execution chain for routesFlow requests */\nexport function getRoutesFlowExecutionChain(\n rawRequest: unknown,\n opts: RouterOptions,\n urlQuery?: string\n): RoutesFlowExecutionResult {\n // Validate urlQuery is provided\n if (!urlQuery) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-missing-query',\n publicMessage: 'RoutesFlow request requires a query string with route paths.',\n });\n }\n\n // Decode base64+JSON query\n const query = decodeRoutesFlowQuery(urlQuery);\n const routePaths = query.routes;\n const mappings = query.mappings;\n\n if (!routePaths || routePaths.length === 0) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-empty-routes',\n publicMessage: 'RoutesFlow request requires at least one route path in query string.',\n });\n }\n\n // Convert paths to route IDs (remove leading slash)\n const routeIds = routePaths.map((path) => (path.startsWith('/') ? path.slice(1) : path));\n\n // Check cache first\n let executionChain = routesFlowCache.get(urlQuery);\n if (executionChain) return {executionChain, routesFlowRouteIds: routeIds, mappings};\n\n // Build merged execution chain\n executionChain = buildMergedExecutionChain(routePaths, rawRequest, opts, mappings);\n addToRoutesFlowCache(urlQuery, executionChain);\n return {executionChain, routesFlowRouteIds: routeIds, mappings};\n}\n\n/**\n * Builds a merged execution chain from multiple route paths.\n * The merged chain includes all methods from all routes, with deduplication by ID.\n *\n * The chain is structured as:\n * 1. Start middleFns (e.g., mionDeserializeRequest) - from first route, at the beginning\n * 2. Middle methods (routes and their middleFns) - merged from all routes, with mapping steps inserted\n * 3. End middleFns (e.g., mionSerializeResponse) - from first route, at the end\n *\n * When mappings are provided, mapping steps are inserted after the source route\n * and before the target route to transform output → input.\n */\nfunction buildMergedExecutionChain(\n routePaths: string[],\n rawRequest: unknown,\n opts: RouterOptions,\n mappings?: RoutesFlowMapping[]\n): MethodsExecutionChain {\n const seenIds = new Set<string>();\n const middleMethods: RemoteMethod[] = [];\n let resolvedSerializer: SerializerCode | undefined;\n let firstRouteIndex = -1;\n const defaultSerializerCode = SerializerModes[opts.serializer];\n\n // Build sets of start and end middleFn IDs for filtering\n const startMiddleFnIds = new Set(startMiddleFns.map((m) => m.id));\n const endMiddleFnIds = new Set(endMiddleFns.map((m) => m.id));\n\n // Process each route path\n for (const routePath of routePaths) {\n // Apply path transform if configured\n const transformedPath = opts.pathTransform?.(rawRequest, routePath) || routePath;\n const chain = getRouteExecutionChain(transformedPath);\n if (!chain) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-route-not-found',\n publicMessage: `Route not found in routesFlow: ${routePath}`,\n errorData: {routePath},\n });\n }\n\n // Resolve serializer - use first route's serializer, or fall back to default if conflicting\n if (!resolvedSerializer) {\n resolvedSerializer = chain.serializer;\n // Track the route index from the first route (relative to start middleFns)\n firstRouteIndex = chain.routeIndex;\n } else if (resolvedSerializer !== chain.serializer) {\n resolvedSerializer = defaultSerializerCode;\n }\n\n // Add middle methods from this route's chain, deduplicating by ID\n // Skip start and end middleFns - they will be added separately\n for (const method of chain.methods) {\n if (seenIds.has(method.id)) continue;\n if (startMiddleFnIds.has(method.id)) continue;\n if (endMiddleFnIds.has(method.id)) continue;\n seenIds.add(method.id);\n middleMethods.push(method);\n }\n }\n\n // Insert mapping methods between source and target routes\n if (mappings && mappings.length > 0) {\n insertMappingMethods(middleMethods, mappings);\n }\n\n // Build final chain: start middleFns + middle methods + end middleFns\n const mergedMethods = [...startMiddleFns, ...middleMethods, ...endMiddleFns];\n\n return {\n // Use the first route's routeIndex since that's where the first route handler is\n routeIndex: firstRouteIndex,\n methods: mergedMethods,\n serializer: resolvedSerializer ?? defaultSerializerCode,\n };\n}\n\n// ############# MAPPING METHODS #############\n\n/**\n * Inserts mapping methods into the middleMethods array in the correct position.\n * Each mapping method is inserted after the source route (fromId) and before the target route (toId).\n * Mappings are processed in reverse insertion order to maintain correct indices.\n */\nfunction insertMappingMethods(middleMethods: RemoteMethod[], mappings: RoutesFlowMapping[]): void {\n // Build a map of route ID → index in middleMethods for quick lookup\n const idToIndex = new Map<string, number>();\n for (let i = 0; i < middleMethods.length; i++) {\n idToIndex.set(middleMethods[i].id, i);\n }\n\n // Collect insertions: each mapping creates one insertion point\n const insertions: Array<{index: number; method: RemoteMethod}> = [];\n\n for (const mapping of mappings) {\n const fromIndex = idToIndex.get(mapping.fromId);\n const toIndex = idToIndex.get(mapping.toId);\n\n if (fromIndex === undefined) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-invalid-source',\n publicMessage: `Mapping source route '${mapping.fromId}' not found in routesFlow execution chain.`,\n errorData: {mapping},\n });\n }\n if (toIndex === undefined) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-invalid-target',\n publicMessage: `Mapping target route '${mapping.toId}' not found in routesFlow execution chain.`,\n errorData: {mapping},\n });\n }\n\n // Validate the pure function exists in the serverPureFnsCache (populated by mion vite plugin)\n if (!serverPureFnsCache[PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash]?.fn) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-missing-pure-fn',\n publicMessage: `Mapping pure function '${mapping.bodyHash}' not found. Ensure the function is registered on the server.`,\n errorData: {mapping},\n });\n }\n\n // Insert after the source route (fromIndex + 1)\n insertions.push({\n index: fromIndex + 1,\n method: createMappingMethod(mapping),\n });\n }\n\n // Sort insertions by index descending so splice doesn't shift subsequent indices\n insertions.sort((a, b) => b.index - a.index);\n\n for (const {index, method} of insertions) {\n middleMethods.splice(index, 0, method);\n }\n}\n\n/** Creates or retrieves a cached RemoteMethod that acts as a raw middleFn to execute a mapping between routes */\nfunction createMappingMethod(mapping: RoutesFlowMapping): RemoteMethod {\n const id = `mionMapFrom_${mapping.fromId}_${mapping.bodyHash}_to_${mapping.toId}`;\n const cached = mappingMethodCache.get(id);\n if (cached) return cached;\n\n const noopJitFns = getNoopJitFns();\n const method = {\n type: HandlerType.rawMiddleFn,\n id,\n isAsync: false,\n hasReturnData: false,\n paramsJitHash: '',\n returnJitHash: '',\n paramsJitFns: noopJitFns,\n returnJitFns: noopJitFns,\n handler: createMappingHandler(mapping),\n options: {runOnError: false, validateParams: false},\n methodCaller: runMappingHandler,\n } as RemoteMethod;\n\n mappingMethodCache.set(id, method);\n return method;\n}\n\n/** Creates the handler function for a mapping step */\nfunction createMappingHandler(mapping: RoutesFlowMapping) {\n return (ctx: CallContext) => {\n // Get the output from the source route\n const sourceOutput = ctx.response.body[mapping.fromId];\n\n // Resolve and execute the pure function from serverPureFnsCache (populated by mion vite plugin)\n const entry = serverPureFnsCache[PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash];\n if (!entry?.fn) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-missing-pure-fn',\n publicMessage: `Mapping pure function '${mapping.bodyHash}' not found at runtime.`,\n });\n }\n const mappedValue = entry.fn(sourceOutput);\n\n // Replace null at paramIndex in target route's params\n const targetParams = ctx.request.body[mapping.toId] as any[];\n if (targetParams) (targetParams as any[])[mapping.paramIndex] = mappedValue;\n };\n}\n\n/** Custom method caller for mapping handlers — only passes the context */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nasync function runMappingHandler(context: CallContext, executable: RemoteMethod, ...args: unknown[]) {\n return executable.handler(context);\n}\n"],"names":["__ΩMethodsExecutionChain","__ΩRemoteMethod","getRouterOptions","fromBase64Url","RpcError","StatusCodes","SerializerModes","startMiddleFns","endMiddleFns","getRouteExecutionChain","serverPureFnsCache","PURE_SERVER_FN_NAMESPACE","getNoopJitFns","HandlerType"],"mappings":";;;;;;;;;;;;AA4BA,MAAM,mBAAsB,IAAG,IAAA,CAAA,CAAA,GAAA,GAAA,CAAA,MAAAA,wBAAAA,0BAAA,IAAA,CAAA,uBAAH,IAAA;AAC5B,MAAM,aAAuB,CAAA;AAE7B,MAAM,sBAAyB,IAAG,IAAA,CAAA,CAAA,GAAA,GAAA,CAAA,MAAAC,wBAAAA,iBAAA,IAAA,CAAA,uBAAH,IAAA;SAGf,uBAAoB;AAChC,kBAAgB,MAAA;AAChB,aAAW,SAAS;AACpB,qBAAmB,MAA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AM;AAGrD,UAAM,QAAQH,0BAAAA,mBAAmBC,KAAAA,wBAAwB,IAAI,QAAQ,QAAQ;AAC7E,QAAI,CAAC,OAAO,IAAI;AACZ,YAAM,IAAIP,KAAAA,SAAS;AAAA,QACf,YAAYC,KAAAA,YAAY;AAAA,QACxB,MAAM;AAAA,QACN,eAAe,0BAA0B,QAAQ,QAAQ;AAAA,MAAA,CAC5D;AAAA,IACL;AACA,UAAM,cAAc,MAAM,GAAG,YAAY;AAGzC,UAAM,eAAe,IAAI,QAAQ,KAAK,QAAQ,IAAI;AAClD,QAAI;AAAe,mBAAuB,QAAQ,UAAU,IAAI;AAAA,EACpE,GAAC,CAAA,eAAA,OAAA,IAAA,WAAA,CAAA;AACL;;AAIA,eAAe,kBAAkB,SAAsB,eAA6B,MAAe;AAC/F,SAAO,WAAW,QAAQ,OAAO;AACrC;;;;;;"}
1
+ {"version":3,"file":"routesFlow.cjs","sources":["../../../src/routesFlow.ts"],"sourcesContent":["/* ########\n * 2023 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport {\n RpcError,\n SerializerCode,\n SerializerModes,\n StatusCodes,\n HandlerType,\n getNoopJitFns,\n PURE_SERVER_FN_NAMESPACE,\n fromBase64Url,\n} from '@mionjs/core';\nimport {serverPureFnsCache} from '@mionjs/core/server-pure-fns';\nimport {getRouteExecutionChain, getRouterOptions, startMiddleFns, endMiddleFns} from './router.ts';\nimport {RouterOptions} from './types/general.ts';\nimport {MethodsExecutionChain, RemoteMethod} from './types/remoteMethods.ts';\nimport {RoutesFlowExecutionResult} from './types/context.ts';\nimport type {CallContext} from './types/context.ts';\nimport type {RoutesFlowQuery, RoutesFlowMapping} from '@mionjs/core';\n\n// ############# ROUTES_FLOW CACHE #############\n\n/** FILO cache for merged execution chains. Key is the query string, value is the cached chain. */\nconst routesFlowCache = new Map<string, MethodsExecutionChain>();\nconst cacheOrder: string[] = [];\n/** Cache for mapping RemoteMethods keyed by their unique ID */\nconst mappingMethodCache = new Map<string, RemoteMethod>();\n\n/** Clears the routesFlow cache and mapping method cache - useful for testing */\nexport function clearRoutesFlowCache(): void {\n routesFlowCache.clear();\n cacheOrder.length = 0;\n mappingMethodCache.clear();\n}\n\n/** Returns the current routesFlow cache size */\nexport function getRoutesFlowCacheSize(): number {\n return routesFlowCache.size;\n}\n\n/** Returns a cached routesFlow chain by query string */\nexport function getCachedRoutesFlow(query: string): MethodsExecutionChain | undefined {\n return routesFlowCache.get(query);\n}\n\n/** Adds a merged chain to the cache with FILO eviction */\nfunction addToRoutesFlowCache(query: string, chain: MethodsExecutionChain): void {\n const routerOpts = getRouterOptions();\n const maxSize = routerOpts.maxRoutesFlowsCacheSize;\n // Caching disabled\n if (maxSize <= 0) return;\n // Evict oldest entries if cache is full (FILO - First In, Last Out)\n while (cacheOrder.length >= maxSize) {\n const oldestKey = cacheOrder.shift();\n if (oldestKey) routesFlowCache.delete(oldestKey);\n }\n routesFlowCache.set(query, chain);\n cacheOrder.push(query);\n}\n\n// ############# QUERY PARSING #############\n\n/** Decodes a base64url-encoded JSON routesFlow query string, expects `data=<base64url>` format */\nfunction decodeRoutesFlowQuery(urlQuery: string): RoutesFlowQuery {\n try {\n const dataParam = urlQuery.startsWith('data=') ? urlQuery.slice(5) : urlQuery;\n const jsonString = fromBase64Url(dataParam);\n return JSON.parse(jsonString) as RoutesFlowQuery;\n } catch (e: any) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-invalid-query',\n publicMessage: 'RoutesFlow query string is not valid base64url-encoded JSON.',\n errorData: {parseError: e?.message || 'Unknown error'},\n });\n }\n}\n\n// ############# ROUTES_FLOW #############\n\n/** Builds or retrieves a cached merged execution chain for routesFlow requests */\nexport function getRoutesFlowExecutionChain(\n rawRequest: unknown,\n opts: RouterOptions,\n urlQuery?: string\n): RoutesFlowExecutionResult {\n // Validate urlQuery is provided\n if (!urlQuery) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-missing-query',\n publicMessage: 'RoutesFlow request requires a query string with route paths.',\n });\n }\n\n // Decode base64+JSON query\n const query = decodeRoutesFlowQuery(urlQuery);\n const routePaths = query.routes;\n const mappings = query.mappings;\n\n if (!routePaths || routePaths.length === 0) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-empty-routes',\n publicMessage: 'RoutesFlow request requires at least one route path in query string.',\n });\n }\n\n // Convert paths to route IDs (remove leading slash)\n const routeIds = routePaths.map((path) => (path.startsWith('/') ? path.slice(1) : path));\n\n // Check cache first\n let executionChain = routesFlowCache.get(urlQuery);\n if (executionChain) return {executionChain, routesFlowRouteIds: routeIds, mappings};\n\n // Build merged execution chain\n executionChain = buildMergedExecutionChain(routePaths, rawRequest, opts, mappings);\n addToRoutesFlowCache(urlQuery, executionChain);\n return {executionChain, routesFlowRouteIds: routeIds, mappings};\n}\n\n/**\n * Builds a merged execution chain from multiple route paths.\n * The merged chain includes all methods from all routes, with deduplication by ID.\n *\n * The chain is structured as:\n * 1. Start middleFns (e.g., mionDeserializeRequest) - from first route, at the beginning\n * 2. Middle methods (routes and their middleFns) - merged from all routes, with mapping steps inserted\n * 3. End middleFns (e.g., mionSerializeResponse) - from first route, at the end\n *\n * When mappings are provided, mapping steps are inserted after the source route\n * and before the target route to transform output → input.\n */\nfunction buildMergedExecutionChain(\n routePaths: string[],\n rawRequest: unknown,\n opts: RouterOptions,\n mappings?: RoutesFlowMapping[]\n): MethodsExecutionChain {\n const seenIds = new Set<string>();\n const middleMethods: RemoteMethod[] = [];\n let resolvedSerializer: SerializerCode | undefined;\n let firstRouteIndex = -1;\n const defaultSerializerCode = SerializerModes[opts.serializer];\n\n // Build sets of start and end middleFn IDs for filtering\n const startMiddleFnIds = new Set(startMiddleFns.map((m) => m.id));\n const endMiddleFnIds = new Set(endMiddleFns.map((m) => m.id));\n\n // Process each route path\n for (const routePath of routePaths) {\n // Apply path transform if configured\n const transformedPath = opts.pathTransform?.(rawRequest, routePath) || routePath;\n const chain = getRouteExecutionChain(transformedPath);\n if (!chain) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-route-not-found',\n publicMessage: `Route not found in routesFlow: ${routePath}`,\n errorData: {routePath},\n });\n }\n\n // Resolve serializer - use first route's serializer, or fall back to default if conflicting\n if (!resolvedSerializer) {\n resolvedSerializer = chain.serializer;\n // Track the route index from the first route (relative to start middleFns)\n firstRouteIndex = chain.routeIndex;\n } else if (resolvedSerializer !== chain.serializer) {\n resolvedSerializer = defaultSerializerCode;\n }\n\n // Add middle methods from this route's chain, deduplicating by ID\n // Skip start and end middleFns - they will be added separately\n for (const method of chain.methods) {\n if (seenIds.has(method.id)) continue;\n if (startMiddleFnIds.has(method.id)) continue;\n if (endMiddleFnIds.has(method.id)) continue;\n seenIds.add(method.id);\n middleMethods.push(method);\n }\n }\n\n // Insert mapping methods between source and target routes\n if (mappings && mappings.length > 0) {\n insertMappingMethods(middleMethods, mappings);\n }\n\n // Build final chain: start middleFns + middle methods + end middleFns\n const mergedMethods = [...startMiddleFns, ...middleMethods, ...endMiddleFns];\n\n return {\n // Use the first route's routeIndex since that's where the first route handler is\n routeIndex: firstRouteIndex,\n methods: mergedMethods,\n serializer: resolvedSerializer ?? defaultSerializerCode,\n };\n}\n\n// ############# MAPPING METHODS #############\n\n/**\n * Inserts mapping methods into the middleMethods array in the correct position.\n * Each mapping method is inserted after the source route (fromId) and before the target route (toId).\n * Mappings are processed in reverse insertion order to maintain correct indices.\n */\nfunction insertMappingMethods(middleMethods: RemoteMethod[], mappings: RoutesFlowMapping[]): void {\n // Build a map of route ID → index in middleMethods for quick lookup\n const idToIndex = new Map<string, number>();\n for (let i = 0; i < middleMethods.length; i++) {\n idToIndex.set(middleMethods[i].id, i);\n }\n\n // Collect insertions: each mapping creates one insertion point\n const insertions: Array<{index: number; method: RemoteMethod}> = [];\n\n for (const mapping of mappings) {\n const fromIndex = idToIndex.get(mapping.fromId);\n const toIndex = idToIndex.get(mapping.toId);\n\n if (fromIndex === undefined) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-invalid-source',\n publicMessage: `Mapping source route '${mapping.fromId}' not found in routesFlow execution chain.`,\n errorData: {mapping},\n });\n }\n if (toIndex === undefined) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-invalid-target',\n publicMessage: `Mapping target route '${mapping.toId}' not found in routesFlow execution chain.`,\n errorData: {mapping},\n });\n }\n\n // Validate the pure function exists in the serverPureFnsCache (populated by mion vite plugin)\n if (!serverPureFnsCache[PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash]?.fn) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-missing-pure-fn',\n publicMessage: `Mapping pure function '${mapping.bodyHash}' not found. Ensure the function is registered on the server.`,\n errorData: {mapping},\n });\n }\n\n // Insert after the source route (fromIndex + 1)\n insertions.push({\n index: fromIndex + 1,\n method: createMappingMethod(mapping),\n });\n }\n\n // Sort insertions by index descending so splice doesn't shift subsequent indices\n insertions.sort((a, b) => b.index - a.index);\n\n for (const {index, method} of insertions) {\n middleMethods.splice(index, 0, method);\n }\n}\n\n/** Creates or retrieves a cached RemoteMethod that acts as a raw middleFn to execute a mapping between routes */\nfunction createMappingMethod(mapping: RoutesFlowMapping): RemoteMethod {\n const id = `mionMapFrom_${mapping.fromId}_${mapping.bodyHash}_to_${mapping.toId}`;\n const cached = mappingMethodCache.get(id);\n if (cached) return cached;\n\n const noopJitFns = getNoopJitFns();\n const method = {\n type: HandlerType.rawMiddleFn,\n id,\n isAsync: false,\n hasReturnData: false,\n paramsJitHash: '',\n returnJitHash: '',\n paramsJitFns: noopJitFns,\n returnJitFns: noopJitFns,\n handler: createMappingHandler(mapping),\n options: {runOnError: false, validateParams: false},\n methodCaller: runMappingHandler,\n } as RemoteMethod;\n\n mappingMethodCache.set(id, method);\n return method;\n}\n\n/** Creates the handler function for a mapping step */\nfunction createMappingHandler(mapping: RoutesFlowMapping) {\n return (ctx: CallContext) => {\n // Get the output from the source route\n const sourceOutput = ctx.response.body[mapping.fromId];\n\n // Resolve and execute the pure function from serverPureFnsCache (populated by mion vite plugin)\n const entry = serverPureFnsCache[PURE_SERVER_FN_NAMESPACE]?.[mapping.bodyHash];\n if (!entry?.fn) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: 'routesFlow-mapping-missing-pure-fn',\n publicMessage: `Mapping pure function '${mapping.bodyHash}' not found at runtime.`,\n });\n }\n const mappedValue = entry.fn(sourceOutput);\n\n // Replace null at paramIndex in target route's params\n const targetParams = ctx.request.body[mapping.toId] as any[];\n if (targetParams) (targetParams as any[])[mapping.paramIndex] = mappedValue;\n };\n}\n\n/** Custom method caller for mapping handlers — only passes the context */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nasync function runMappingHandler(context: CallContext, executable: RemoteMethod, ...args: unknown[]) {\n return executable.handler(context);\n}\n"],"names":["__ΩMethodsExecutionChain","__ΩRemoteMethod","getRouterOptions","fromBase64Url","RpcError","StatusCodes","SerializerModes","startMiddleFns","endMiddleFns","getRouteExecutionChain","serverPureFnsCache","PURE_SERVER_FN_NAMESPACE","getNoopJitFns","HandlerType"],"mappings":";;;;;;;;;;;;AA4BA,MAAM,mBAAsB,IAAG,IAAA,CAAA,CAAA,GAAA,GAAA,CAAA,MAAAA,wBAAAA,0BAAA,IAAA,CAAA,uBAAH,IAAA;AAC5B,MAAM,aAAuB,CAAA;AAE7B,MAAM,sBAAyB,IAAG,IAAA,CAAA,CAAA,GAAA,GAAA,CAAA,MAAAC,wBAAAA,iBAAA,IAAA,CAAA,uBAAH,IAAA;SAGf,uBAAoB;AAChC,kBAAgB,MAAA;AAChB,aAAW,SAAS;AACpB,qBAAmB,MAAA;AACvB;;SAGgB,yBAAsB;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AAA,mBAAmBC,KAAAA,wBAAwB,IAAI,QAAQ,QAAQ;AAC7E,QAAI,CAAC,OAAO,IAAI;AACZ,YAAM,IAAIP,KAAAA,SAAS;AAAA,QACf,YAAYC,KAAAA,YAAY;AAAA,QACxB,MAAM;AAAA,QACN,eAAe,0BAA0B,QAAQ,QAAQ;AAAA,MAAA,CAC5D;AAAA,IACL;AACA,UAAM,cAAc,MAAM,GAAG,YAAY;AAGzC,UAAM,eAAe,IAAI,QAAQ,KAAK,QAAQ,IAAI;AAClD,QAAI;AAAe,mBAAuB,QAAQ,UAAU,IAAI;AAAA,EACpE,GAAC,CAAA,eAAA,OAAA,IAAA,WAAA,CAAA;AACL;;AAIA,eAAe,kBAAkB,SAAsB,eAA6B,MAAe;AAC/F,SAAO,WAAW,QAAQ,OAAO;AACrC;;;;;;"}
@@ -6,7 +6,7 @@ const src_types_definitions = require("./definitions.cjs");
6
6
  const __ΩRoute = [() => src_types_definitions.__ΩRouteDef, "Route", 'n!w"y'];
7
7
  const __ΩRouterEntry = [() => __ΩRoutes, () => src_types_definitions.__ΩMiddleFnDef, () => src_types_definitions.__ΩRouteDef, () => src_types_definitions.__ΩRawMiddleFnDef, () => src_types_definitions.__ΩHeadersMiddleFnDef, "RouterEntry", 'Pn!n"n#n$n%Jw&y'];
8
8
  const __ΩRoutes = [() => __ΩRouterEntry, "Routes", 'P&n!LMw"y'];
9
- const __ΩRouterOptions = ["Req", "ContextData", () => core.__ΩCoreRouterOptions, "basePath", "suffix", "request", "path", "", "pathTransform", () => src_types_context.__ΩContextDataFactory, "contextDataFactory", () => core.__ΩSerializerMode, "serializer", "RunTypeOptions", "runTypeOptions", "getPublicRoutesData", "autoGenerateErrorId", "skipClientRoutes", "aot", "maxContextPoolSize", "maxRoutesFlowsCacheSize", "RouterOptions", `"c!"c"Pn#&4$&4%Pe#!2&&2'&/(4)8e""o*"4+8n,4-"w.4/)40)41)42)43'44'45Mw6y`];
9
+ const __ΩRouterOptions = ["Req", "ContextData", () => core.__ΩCoreRouterOptions, "basePath", "suffix", "request", "path", "", "pathTransform", () => src_types_context.__ΩContextDataFactory, "contextDataFactory", () => core.__ΩSerializerMode, "serializer", "RunTypeOptions", "runTypeOptions", "strictTypes", "getPublicRoutesData", "autoGenerateErrorId", "skipClientRoutes", "aot", "maxContextPoolSize", "maxRoutesFlowsCacheSize", "RouterOptions", `"c!"c"Pn#&4$&4%Pe#!2&&2'&/(4)8e""o*"4+8n,4-"w.4/)408)41)42)43)44'45'46Mw7y`];
10
10
  exports.__ΩRoute = __ΩRoute;
11
11
  exports.__ΩRouterEntry = __ΩRouterEntry;
12
12
  exports.__ΩRouterOptions = __ΩRouterOptions;
@@ -14,6 +14,7 @@ export interface RouterOptions<Req = any, ContextData extends Record<string, any
14
14
  contextDataFactory?: ContextDataFactory<ContextData>;
15
15
  serializer: SerializerMode;
16
16
  runTypeOptions: RunTypeOptions;
17
+ strictTypes?: boolean;
17
18
  getPublicRoutesData: boolean;
18
19
  autoGenerateErrorId: boolean;
19
20
  skipClientRoutes: boolean;
@@ -7,9 +7,9 @@ const __ΩRouteMethod = ["H", () => __ΩRemoteMethod, () => HandlerType.route, "
7
7
  const __ΩMiddleFnMethod = ["H", () => __ΩRemoteMethod, () => HandlerType.middleFn, "type", "MiddleFnMethod", '"c!Pe"!o""i#4$Mw%y'];
8
8
  const __ΩHeadersMethod = ["H", () => __ΩRemoteMethod, () => HandlerType.headersMiddleFn, "type", "HeadersMethodWithJitFns", "headersParam", "HeadersMethod", `"c!Pe"!o""i#4$"w%4&Mw'y`];
9
9
  const __ΩRawMethod = ["H", () => __ΩRemoteMethod, () => HandlerType.rawMiddleFn, "type", "RemoteMethodOpts", false, "validateParams", false, "validateReturn", "options", "RawMethod", `"c!Pe"!o""i#4$P"w%P.&4'.(4)8MK4*Mw+y`];
10
- const __ΩRouteOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩRouteMethod, "options", "description", "validateParams", "validateReturn", "serializer", "isMutation", "RouteOptions", `n#.$fP.%.&.'.(.)Jo"#o!"w*y`];
11
- const __ΩMiddleFnOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩMiddleFnMethod, "options", "description", "validateParams", "validateReturn", "runOnError", "MiddleFnOptions", `n#.$fP.%.&.'.(Jo"#o!"w)y`];
12
- const __ΩHeadersMiddleFnOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩHeadersMethod, "options", "description", "validateParams", "validateReturn", "runOnError", "HeadersMiddleFnOptions", `n#.$fP.%.&.'.(Jo"#o!"w)y`];
10
+ const __ΩRouteOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩRouteMethod, "options", "description", "validateParams", "validateReturn", "serializer", "isMutation", "strictTypes", "RouteOptions", `n#.$fP.%.&.'.(.).*Jo"#o!"w+y`];
11
+ const __ΩMiddleFnOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩMiddleFnMethod, "options", "description", "validateParams", "validateReturn", "runOnError", "strictTypes", "MiddleFnOptions", `n#.$fP.%.&.'.(.)Jo"#o!"w*y`];
12
+ const __ΩHeadersMiddleFnOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩHeadersMethod, "options", "description", "validateParams", "validateReturn", "runOnError", "strictTypes", "HeadersMiddleFnOptions", `n#.$fP.%.&.'.(.)Jo"#o!"w*y`];
13
13
  const __ΩRawMiddleFnOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩRawMethod, "options", "description", "runOnError", "RawMiddleFnOptions", `n#.$fP.%.&Jo"#o!"w'y`];
14
14
  const __ΩMethodsExecutionChain = ["routeIndex", () => __ΩRemoteMethod, "methods", "SerializerCode", "serializer", "MethodsExecutionChain", `P'4!n"F4#"w$4%Mw&y`];
15
15
  exports.__ΩHeadersMethod = __ΩHeadersMethod;
@@ -1 +1 @@
1
- {"version":3,"file":"remoteMethods.cjs","sources":["../../../../src/types/remoteMethods.ts"],"sourcesContent":["// ####### Executables #######\n\nimport type {HeadersMethodWithJitFns, MethodWithJitFns, RemoteMethodOpts, RouteOnlyOptions, SerializerCode} from '@mionjs/core'; // do not import type only\nimport type {AnyHandler, Handler, HeaderHandler, RawMiddleFnHandler} from './handlers.ts'; // do not import type only\nimport {HandlerType} from '@mionjs/core'; // do not import type only\n\n/** Contains the handlers for middleFns and routes */\nexport interface RemoteMethod<H extends AnyHandler = AnyHandler> extends MethodWithJitFns {\n /** router options */\n options: RemoteMethodOpts;\n handler: H;\n methodCaller?: (...args: any[]) => any;\n}\n\nexport interface RouteMethod<H extends Handler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.route;\n options: RouteOnlyOptions;\n}\nexport interface MiddleFnMethod<H extends Handler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.middleFn;\n}\nexport interface HeadersMethod<H extends HeaderHandler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.headersMiddleFn;\n headersParam: HeadersMethodWithJitFns;\n}\nexport interface RawMethod<H extends RawMiddleFnHandler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.rawMiddleFn;\n options: RemoteMethodOpts & {\n validateParams: false;\n validateReturn?: false;\n };\n}\n\nexport type RouteOptions = Partial<\n Pick<RouteMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'serializer' | 'isMutation'>\n>;\nexport type MiddleFnOptions = Partial<\n Pick<MiddleFnMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError'>\n>;\nexport type HeadersMiddleFnOptions = Partial<\n Pick<HeadersMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError'>\n>;\n// RawMiddleFnOptions doesn't need encoding - raw middleFns handle their own serialization\nexport type RawMiddleFnOptions = Partial<Pick<RawMethod['options'], 'description' | 'runOnError'>>;\n\nexport interface MethodsExecutionChain {\n routeIndex: number;\n methods: RemoteMethod[];\n /** Precalculated serializer code for the route's response body type */\n serializer: SerializerCode;\n}\n"],"names":[],"mappings":";;;;;sEAe6B,OAAK,QAAA,oBAAA,WAAA,eAAA,yBAAA;yEAIL,UAAQ,QAAA,kBAAA,oBAAA;wEAGR,iBAAe,QAAA,2BAAA,gBAAA,iBAAA,yBAAA;oEAIf,aAAW,QAAA,oBAAA,OAAA,kBAAA,OAAA,kBAAA,WAAA,aAAA,sCAAA;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"remoteMethods.cjs","sources":["../../../../src/types/remoteMethods.ts"],"sourcesContent":["// ####### Executables #######\n\nimport type {HeadersMethodWithJitFns, MethodWithJitFns, RemoteMethodOpts, RouteOnlyOptions, SerializerCode} from '@mionjs/core'; // do not import type only\nimport type {AnyHandler, Handler, HeaderHandler, RawMiddleFnHandler} from './handlers.ts'; // do not import type only\nimport {HandlerType} from '@mionjs/core'; // do not import type only\n\n/** Contains the handlers for middleFns and routes */\nexport interface RemoteMethod<H extends AnyHandler = AnyHandler> extends MethodWithJitFns {\n /** router options */\n options: RemoteMethodOpts;\n handler: H;\n methodCaller?: (...args: any[]) => any;\n}\n\nexport interface RouteMethod<H extends Handler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.route;\n options: RouteOnlyOptions;\n}\nexport interface MiddleFnMethod<H extends Handler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.middleFn;\n}\nexport interface HeadersMethod<H extends HeaderHandler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.headersMiddleFn;\n headersParam: HeadersMethodWithJitFns;\n}\nexport interface RawMethod<H extends RawMiddleFnHandler = any> extends RemoteMethod<H> {\n type: typeof HandlerType.rawMiddleFn;\n options: RemoteMethodOpts & {\n validateParams: false;\n validateReturn?: false;\n };\n}\n\nexport type RouteOptions = Partial<\n Pick<\n RouteMethod['options'],\n 'description' | 'validateParams' | 'validateReturn' | 'serializer' | 'isMutation' | 'strictTypes'\n >\n>;\nexport type MiddleFnOptions = Partial<\n Pick<MiddleFnMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError' | 'strictTypes'>\n>;\nexport type HeadersMiddleFnOptions = Partial<\n Pick<HeadersMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError' | 'strictTypes'>\n>;\n// RawMiddleFnOptions doesn't need encoding - raw middleFns handle their own serialization\nexport type RawMiddleFnOptions = Partial<Pick<RawMethod['options'], 'description' | 'runOnError'>>;\n\nexport interface MethodsExecutionChain {\n routeIndex: number;\n methods: RemoteMethod[];\n /** Precalculated serializer code for the route's response body type */\n serializer: SerializerCode;\n}\n"],"names":[],"mappings":";;;;;sEAe6B,OAAK,QAAA,oBAAA,WAAA,eAAA,yBAAA;yEAIL,UAAQ,QAAA,kBAAA,oBAAA;wEAGR,iBAAe,QAAA,2BAAA,gBAAA,iBAAA,yBAAA;oEAIf,aAAW,QAAA,oBAAA,OAAA,kBAAA,OAAA,kBAAA,WAAA,aAAA,sCAAA;;;;;;;;;;;;;;;;"}
@@ -23,9 +23,9 @@ export interface RawMethod<H extends RawMiddleFnHandler = any> extends RemoteMet
23
23
  validateReturn?: false;
24
24
  };
25
25
  }
26
- export type RouteOptions = Partial<Pick<RouteMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'serializer' | 'isMutation'>>;
27
- export type MiddleFnOptions = Partial<Pick<MiddleFnMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError'>>;
28
- export type HeadersMiddleFnOptions = Partial<Pick<HeadersMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError'>>;
26
+ export type RouteOptions = Partial<Pick<RouteMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'serializer' | 'isMutation' | 'strictTypes'>>;
27
+ export type MiddleFnOptions = Partial<Pick<MiddleFnMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError' | 'strictTypes'>>;
28
+ export type HeadersMiddleFnOptions = Partial<Pick<HeadersMethod['options'], 'description' | 'validateParams' | 'validateReturn' | 'runOnError' | 'strictTypes'>>;
29
29
  export type RawMiddleFnOptions = Partial<Pick<RawMethod['options'], 'description' | 'runOnError'>>;
30
30
  export interface MethodsExecutionChain {
31
31
  routeIndex: number;
@@ -6,7 +6,7 @@ import { isAnyMiddleFnDef, isExecutable, isHeaderExecutable, isHeadersMiddleFnDe
6
6
  import { __ΩAnyHandler, __ΩHandler, __ΩHeaderHandler, __ΩRawMiddleFnHandler } from "./src/types/handlers.js";
7
7
  import { __ΩMayReturnError, __ΩMiddleFnsCollection, __ΩPrivateDef, __ΩPrivateMiddleFnDef, __ΩPublicApi, __ΩPublicHandler, __ΩPublicHeadersFn, __ΩPublicMiddleFn, __ΩPublicRoute, __ΩRemoteApi } from "./src/types/publicMethods.js";
8
8
  import { DEFAULT_ROUTE_OPTIONS, HEADER_HOOK_DEFAULT_PARAMS, IS_TEST_ENV, MAX_ROUTE_NESTING, NOT_FOUND_HOOK_NAME, NOT_FOUND_PATH, ROUTE_DEFAULT_PARAMS, WORKFLOW_KEY, WORKFLOW_PATH } from "./src/constants.js";
9
- import { addEndMiddleFns, addStartMiddleFns, endMiddleFns, geMiddleFnsSize, geRoutesSize, getAllExecutablesIds, getAnyExecutable, getComplexity, getExecutableFromMiddleFn, getExecutableFromRawMiddleFn, getExecutableFromRoute, getMiddleFnExecutable, getRouteEntries, getRouteExecutable, getRouteExecutableFromPath, getRouteExecutionChain, getRouterOptions, getTotalExecutables, initMionRouter, initRouter, isPrivateDefinition, isPrivateExecutable, registerRoutes, resetRouter, shouldFullGenerateSpec, startMiddleFns } from "./src/router.js";
9
+ import { addEndMiddleFns, addStartMiddleFns, endMiddleFns, geMiddleFnsSize, geRoutesSize, getAllExecutablesIds, getAnyExecutable, getComplexity, getExecutableFromMiddleFn, getExecutableFromRawMiddleFn, getExecutableFromRoute, getMiddleFnExecutable, getPlatformConfig, getRouteEntries, getRouteExecutable, getRouteExecutableFromPath, getRouteExecutionChain, getRouterOptions, getTotalExecutables, initMionRouter, initRouter, isPrivateDefinition, isPrivateExecutable, registerRoutes, resetRouter, setPlatformConfig, shouldFullGenerateSpec, startMiddleFns } from "./src/router.js";
10
10
  import { dispatchRoute } from "./src/dispatch.js";
11
11
  import { acquireCallContext, clearContextPool, createCallContext, getContextPoolStats, releaseCallContext } from "./src/callContext.js";
12
12
  import { getRouterFatalErrorResponse, onExecutableError } from "./src/lib/dispatchError.js";
@@ -93,6 +93,7 @@ export {
93
93
  getPersistedMethod,
94
94
  getPersistedMethodMetadata,
95
95
  getPersistedMethods,
96
+ getPlatformConfig,
96
97
  getPublicApi,
97
98
  getRouteEntries,
98
99
  getRouteExecutable,
@@ -139,6 +140,7 @@ export {
139
140
  serializeMethodDeps,
140
141
  serializePureDeps,
141
142
  setPersistedMethods,
143
+ setPlatformConfig,
142
144
  shouldFullGenerateSpec,
143
145
  startMiddleFns
144
146
  };
@@ -1 +1 @@
1
- {"version":3,"file":"defaultRoutes.js","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 startServerScript is configured.\n *\n * When run with MION_COMPILE=true, 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":[],"mappings":";;;;;AA4BA,MAAM,SAAS;AAAA;AAAA,EAEX,0BAA0B,SAAQ,aAAC,MAAY,QAAS,CAAA,IAAA,MAAA,CAAA,CAAA;;AAKrD,MAAM,aAAa,eAAe,QAAQ,EAAC,kBAAkB,OAAM;;"}
1
+ {"version":3,"file":"defaultRoutes.js","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":[],"mappings":";;;;;AA4BA,MAAM,SAAS;AAAA;AAAA,EAEX,0BAA0B,SAAQ,aAAC,MAAY,QAAS,CAAA,IAAA,MAAA,CAAA,CAAA;;AAKrD,MAAM,aAAa,eAAe,QAAQ,EAAC,kBAAkB,OAAM;;"}
@@ -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[];
@@ -1,11 +1,13 @@
1
1
  import { JIT_FUNCTION_IDS, isMionAOTEmitMode, getENV, getJitFnCaches, __ΩSrcCodeJITCompiledFnsCache as ___SrcCodeJITCompiledFnsCache, __ΩSrcCodePureFunctionsCache as ___SrcCodePureFunctionsCache, __ΩMethodsCache as ___MethodsCache, __ΩJitFunctionsCache as ___JitFunctionsCache, __ΩPureFunctionsCache as ___PureFunctionsCache } from "@mionjs/core";
2
2
  import { getPersistedMethods } from "./methodsCache.js";
3
3
  import { createToJavascriptFn } from "@mionjs/run-types";
4
+ const __ΩRecord = ["K", "T", "Record", `l'e#"Rb!b"Pde"!N#!w#y`];
4
5
  function __assignType(fn, args) {
5
6
  fn.__type = args;
6
7
  return fn;
7
8
  }
8
9
  const __ΩAOTCacheMessage = ["mion-aot-caches", "type", "jitFnsCode", "pureFnsCode", "routerCacheCode", "AOTCacheMessage", 'P.!4"&4#&4$&4%Mw&y'];
10
+ const __ΩPlatformReadyMessage = ["mion-platform-ready", "type", () => __ΩRecord, "routerConfig", () => __ΩRecord, "platformConfig", "PlatformReadyMessage", `P.!4"&#o##4$&#o%#4&Mw'y`];
9
11
  const __ΩSerializedCaches = ["jitFnsCode", "pureFnsCode", "routerCacheCode", "SerializedCaches", 'P&4!&4"&4#Mw$y'];
10
12
  const EXCLUDED_JIT_FN_IDS = [JIT_FUNCTION_IDS.toJSCode];
11
13
  const EXCLUDED_PURE_FN_NAMES = ["sanitizeCompiledFn"];
@@ -18,7 +20,7 @@ getSerializedCaches.__type = [() => __ΩSerializedCaches, "getSerializedCaches",
18
20
  async function emitAOTCaches() {
19
21
  if (!isMionAOTEmitMode())
20
22
  return;
21
- if (getENV("MION_COMPILE") === "viteSSR")
23
+ if (getENV("MION_COMPILE") === "middleware")
22
24
  return;
23
25
  if (typeof process.send !== "function")
24
26
  return;
@@ -62,6 +64,7 @@ function filterExcludedPureFns(pureFnsCache, excludedFnNames) {
62
64
  filterExcludedPureFns.__type = [() => ___PureFunctionsCache, "pureFnsCache", "excludedFnNames", () => ___PureFunctionsCache, "filterExcludedPureFns", 'Pn!2"&F2#n$/%'];
63
65
  export {
64
66
  __ΩAOTCacheMessage,
67
+ __ΩPlatformReadyMessage,
65
68
  __ΩSerializedCaches,
66
69
  emitAOTCaches,
67
70
  getSerializedCaches,
@@ -1 +1 @@
1
- {"version":3,"file":"aotEmitter.js","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 // viteSSR mode: caches remain in global state, read directly via getSerializedCaches()\n if (getENV('MION_COMPILE') === 'viteSSR') 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":[],"mappings":";;;;;;;;;AAqCA,MAAM,sBAAsB,CAAC,iBAAiB,QAAQ;AAGtD,MAAM,yBAAyB,CAAC,oBAAoB;AAGpD,eAAsB,sBAAmB;AACrC,QAAM,EAAC,aAAa,aAAA,IAAgB,eAAA;AACpC,QAAM,cAAc,oBAAA;AACpB,SAAO,sBAAsB,aAAa,cAAc,WAAW;AACvE;;AAOA,eAAsB,gBAAa;AAE/B,MAAI,CAAC,kBAAA;AAAqB;AAE1B,MAAI,OAAO,cAAc,MAAM;AAAW;AAG1C,MAAI,OAAO,QAAQ,SAAS;AAAY;AAGxC,QAAM,EAAC,aAAa,aAAA,IAAgB,eAAA;AACpC,QAAM,cAAc,oBAAA;AAGpB,QAAM,aAAa,MAAM,sBAAsB,aAAa,cAAc,WAAW;AAGrF,QAAM,UAA2B;AAAA,IAC7B,MAAM;AAAA,IACN,GAAG;AAAA,EAAA;AAGP,UAAQ,KAAK,OAAO;AACxB;;AAOA,eAAsB,sBAClB,aACA,cACA,aAAyB;AAEzB,QAAM,eAAc,wEAAA;AACpB,QAAM,gBAAe,uEAAA;AACrB,QAAM,kBAAiB,0DAAA;AAEvB,QAAM,cAAc,qBAAqB,aAAa,mBAAmB;AACzE,QAAM,eAAe,sBAAsB,cAAc,sBAAsB;AAC/E,SAAO;AAAA,IACH,YAAY,YAAY,WAAoD;AAAA,IAC5E,aAAa,aAAa,YAAoD;AAAA,IAC9E,iBAAiB,eAAe,WAAW;AAAA,EAAA;AAEnD;;AAMA,SAAS,qBAAqB,aAAgC,eAAuB;AACjF,MAAI,CAAC,cAAc;AAAQ,WAAO;AAClC,SAAO,OAAO,YACV,OAAO,QAAQ,WAAW,EAAE,OAAM,aAAC,CAAC,GAAG,KAAK,MAAM,CAAC,cAAc,SAAS,MAAM,IAAc,GAAC,CAAA,UAAA,IAAA,SAAA,CAAA,CAAA,CAAC;AAExG;;AAMA,SAAS,sBAAsB,cAAkC,iBAAyB;AACtF,MAAI,CAAC,gBAAgB;AAAQ,WAAO;AACpC,SAAO,OAAO,YACV,OAAO,QAAQ,YAAY,EAAE,IAAG,aAAC,CAAC,CAAC,WAAW,OAAO,MAAM;AAAA,IACvD;AAAA,IACA,OAAO,YAAY,OAAO,QAAQ,OAAO,EAAE,OAAM,aAAC,CAAC,GAAG,KAAK,MAAM,CAAC,gBAAgB,SAAS,MAAM,MAAM,8BAAE;AAAA,EAAA,GAC5G,CAAA,UAAA,IAAA,SAAA,CAAA,CAAA,CAAC;AAEV;;"}
1
+ {"version":3,"file":"aotEmitter.js","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":[],"mappings":";;;;;;;;;;;AA4CA,MAAM,sBAAsB,CAAC,iBAAiB,QAAQ;AAGtD,MAAM,yBAAyB,CAAC,oBAAoB;AAGpD,eAAsB,sBAAmB;AACrC,QAAM,EAAC,aAAa,aAAA,IAAgB,eAAA;AACpC,QAAM,cAAc,oBAAA;AACpB,SAAO,sBAAsB,aAAa,cAAc,WAAW;AACvE;;AAOA,eAAsB,gBAAa;AAE/B,MAAI,CAAC,kBAAA;AAAqB;AAE1B,MAAI,OAAO,cAAc,MAAM;AAAc;AAG7C,MAAI,OAAO,QAAQ,SAAS;AAAY;AAGxC,QAAM,EAAC,aAAa,aAAA,IAAgB,eAAA;AACpC,QAAM,cAAc,oBAAA;AAGpB,QAAM,aAAa,MAAM,sBAAsB,aAAa,cAAc,WAAW;AAGrF,QAAM,UAA2B;AAAA,IAC7B,MAAM;AAAA,IACN,GAAG;AAAA,EAAA;AAGP,UAAQ,KAAK,OAAO;AACxB;;AAOA,eAAsB,sBAClB,aACA,cACA,aAAyB;AAEzB,QAAM,eAAc,wEAAA;AACpB,QAAM,gBAAe,uEAAA;AACrB,QAAM,kBAAiB,0DAAA;AAEvB,QAAM,cAAc,qBAAqB,aAAa,mBAAmB;AACzE,QAAM,eAAe,sBAAsB,cAAc,sBAAsB;AAC/E,SAAO;AAAA,IACH,YAAY,YAAY,WAAoD;AAAA,IAC5E,aAAa,aAAa,YAAoD;AAAA,IAC9E,iBAAiB,eAAe,WAAW;AAAA,EAAA;AAEnD;;AAMA,SAAS,qBAAqB,aAAgC,eAAuB;AACjF,MAAI,CAAC,cAAc;AAAQ,WAAO;AAClC,SAAO,OAAO,YACV,OAAO,QAAQ,WAAW,EAAE,OAAM,aAAC,CAAC,GAAG,KAAK,MAAM,CAAC,cAAc,SAAS,MAAM,IAAc,GAAC,CAAA,UAAA,IAAA,SAAA,CAAA,CAAA,CAAC;AAExG;;AAMA,SAAS,sBAAsB,cAAkC,iBAAyB;AACtF,MAAI,CAAC,gBAAgB;AAAQ,WAAO;AACpC,SAAO,OAAO,YACV,OAAO,QAAQ,YAAY,EAAE,IAAG,aAAC,CAAC,CAAC,WAAW,OAAO,MAAM;AAAA,IACvD;AAAA,IACA,OAAO,YAAY,OAAO,QAAQ,OAAO,EAAE,OAAM,aAAC,CAAC,GAAG,KAAK,MAAM,CAAC,gBAAgB,SAAS,MAAM,MAAM,8BAAE;AAAA,EAAA,GAC5G,CAAA,UAAA,IAAA,SAAA,CAAA,CAAA,CAAC;AAEV;;"}
@@ -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 {};
@@ -102,16 +102,16 @@ function extractReflectionFromCached(cached) {
102
102
  return reflectionItems;
103
103
  }
104
104
  extractReflectionFromCached.__type = [() => __ΩCachedMethodMetadata, "cached", () => __ΩMethodReflect, "extractReflectionFromCached", 'Pn!2"n#/$'];
105
- async function getHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn = false) {
105
+ async function getHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn = false, methodStrictTypes) {
106
106
  const cached = getPersistedMethodMetadata(routeId);
107
107
  if (cached)
108
108
  return extractReflectionFromCached(cached);
109
109
  if (routerOptions.aot)
110
110
  throw new AOTCacheError(routeId, isHeadersMiddleFn ? "middleFn" : "route");
111
111
  const rt = await loadRunTypesModule();
112
- return generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt);
112
+ return generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt, methodStrictTypes);
113
113
  }
114
- getHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", "isHeadersMiddleFn", () => false, () => __ΩMethodReflect, "getHandlerReflection", "Pn!2\"&2#n$2%)2&>'n(`/)"];
114
+ getHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", "isHeadersMiddleFn", () => false, "methodStrictTypes", () => __ΩMethodReflect, "getHandlerReflection", "Pn!2\"&2#n$2%)2&>')2(8n)`/*"];
115
115
  async function getRawMethodReflection(handler, routeId, routerOptions) {
116
116
  const cached = getPersistedMethodMetadata(routeId);
117
117
  if (cached)
@@ -122,10 +122,14 @@ async function getRawMethodReflection(handler, routeId, routerOptions) {
122
122
  return generateRawMethodReflection(handler, routeId, rt);
123
123
  }
124
124
  getRawMethodReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", () => __ΩMethodReflect, "getRawMethodReflection", "Pn!2\"&2#n$2%n&`/'"];
125
- function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt) {
125
+ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt, methodStrictTypes) {
126
126
  const reflectionItems = {};
127
127
  let handlerRunType;
128
- const runTypeOptions = routerOptions?.runTypeOptions || DEFAULT_ROUTE_OPTIONS.runTypeOptions;
128
+ const effectiveStrictTypes = methodStrictTypes ?? routerOptions.strictTypes;
129
+ const runTypeOptions = {
130
+ ...routerOptions?.runTypeOptions || DEFAULT_ROUTE_OPTIONS.runTypeOptions,
131
+ ...effectiveStrictTypes !== void 0 ? { strictTypes: effectiveStrictTypes } : {}
132
+ };
129
133
  try {
130
134
  handlerRunType = rt.reflectFunction(handler);
131
135
  } catch (error) {
@@ -184,7 +188,7 @@ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMid
184
188
  reflectionItems.isAsync = handlerRunType.isAsync();
185
189
  return reflectionItems;
186
190
  }
187
- generateHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", "isHeadersMiddleFn", () => __ΩRunTypesFunctions, "rt", () => __ΩMethodReflect, "generateHandlerReflection", `Pn!2"&2#n$2%)2&n'2(n)/*`];
191
+ generateHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", "isHeadersMiddleFn", () => __ΩRunTypesFunctions, "rt", "methodStrictTypes", () => __ΩMethodReflect, "generateHandlerReflection", `Pn!2"&2#n$2%)2&n'2()2)8n*/+`];
188
192
  function generateRawMethodReflection(handler, routeId, rt) {
189
193
  let handlerRunType;
190
194
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"reflection.js","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":[],"mappings":";;;;;;;;;;;;;A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AAA;AAEjC,SAAS,kBACL,IACA,MACA,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;;"}
1
+ {"version":3,"file":"reflection.js","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 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":[],"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,CAAC,WAAU;AAC9D,qBAAiB;AAAA,MACb,cAAc,OAAO;AAAA,MACrB,iBAAiB,OAAO;AAAA,MACxB,gBAAgB,OAAO;AAAA,MACvB,gBAAgB,OAAO;AAAA,MACvB,kBAAkB,OAAO;AAAA,MACzB,gBAAgB,OAAO;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,WAAW,GAAG,OAAO,IAAI,aAAa,IAAI,WAAW,KAAK,GAAG,CAAC;AAEpE,QAAM,SA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,IAC1G,iBAAiB,QAAQ,0BAA0B,SAAS,aAAa,gBAAgB,IAAI,QAAW,IAAI;AAAA,IAC5G,eAAe,QAAQ,0BAA0B,SAAS,aAAa,cAAc,IAAI,QAAW,IAAI;AAAA,IACxG,UAAU,QAAQ,0BAA0B,SAAS,aAAa,SAAS,IAAI,QAAW,IAAI;AAAA,IAC9F,YAAY,QAAQ,0BAA0B,SAAS,aAAa,WAAW,IAAI,QAAW,IAAI;AAAA,EAAA;AAEtG,SAAO;AACX;;AAGA,MAAM,wBAA2B,QAAO,IAAA,CAAA,CAAA,SAAA,KAAA,GAAA,CAAA,mBAAA,KAAA,CAAA,uBAAP,QAAA;AAEjC,SAAS,kBACL,IACA,MACA,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;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"aotEmitter-test-router.js","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=true\n * to test that emitAOTCaches() correctly sends IPC messages.\n *\n * Uses initMionRouter which automatically calls emitAOTCaches() when MION_COMPILE=true.\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=true\nexport const testApiPromise: Promise<PublicApi<typeof routes>> = initMionRouter(routes, {basePath: 'api/v1'});\n\nexport {routes};\n"],"names":[],"mappings":";;;;;;AAsBA,MAAM,SAAS;AAAA,EACX,OAAO;AAAA,IACH,SAAS,MAAK,aAAC,CAAC,KAAK,QAAsB,EAAC,IAAI,MAAM,gBAAa,CAAA,OAAA,MAAA,MAAA,SAAA,IAAA,aAAA,CAAA,CAAA;AAAA,IACnE,YAAY,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,KAAK,MAAK,aAAC,CAAC,KAAK,GAAW,MAAsB,IAAI,GAAC,CAAA,OAAA,KAAA,KAAA,IAAA,eAAA,CAAA,CAAA;AAAA,EAAA;AAAA;AAAA,EAG3D,KAAK,SAAQ,aAAC,CAAC,QAAa;AAAA,EAE5B,GAAC,CAAA,OAAA,IAAA,SAAA,CAAA,CAAA;;AAIE,MAAM,iBAAoD,eAAe,QAAQ,EAAC,UAAU,UAAS;"}
1
+ {"version":3,"file":"aotEmitter-test-router.js","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":[],"mappings":";;;;;;AAsBA,MAAM,SAAS;AAAA,EACX,OAAO;AAAA,IACH,SAAS,MAAK,aAAC,CAAC,KAAK,QAAsB,EAAC,IAAI,MAAM,gBAAa,CAAA,OAAA,MAAA,MAAA,SAAA,IAAA,aAAA,CAAA,CAAA;AAAA,IACnE,YAAY,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,KAAK,MAAK,aAAC,CAAC,KAAK,GAAW,MAAsB,IAAI,GAAC,CAAA,OAAA,KAAA,KAAA,IAAA,eAAA,CAAA,CAAA;AAAA,EAAA;AAAA;AAAA,EAG3D,KAAK,SAAQ,aAAC,CAAC,QAAa;AAAA,EAE5B,GAAC,CAAA,OAAA,IAAA,SAAA,CAAA,CAAA;;AAIE,MAAM,iBAAoD,eAAe,QAAQ,EAAC,UAAU,UAAS;"}
@@ -13,6 +13,8 @@ export declare const geMiddleFnsSize: () => number;
13
13
  export declare const getComplexity: () => number;
14
14
  export declare const getRouterOptions: <Opts extends RouterOptions>() => Readonly<Opts>;
15
15
  export declare const getAnyExecutable: (id: string) => RouteMethod<any> | MiddleFnMethod<any> | HeadersMethod<any> | RawMethod<any> | undefined;
16
+ export declare function setPlatformConfig(config: Record<string, unknown>): void;
17
+ export declare const getPlatformConfig: () => Readonly<Record<string, unknown>> | undefined;
16
18
  export declare const resetRouter: () => void;
17
19
  export declare function initMionRouter<R extends Routes>(routes: R, opts?: Partial<RouterOptions>): Promise<PublicApi<R>>;
18
20
  export declare function initRouter(opts?: Partial<RouterOptions>): Promise<Readonly<RouterOptions>>;