@mionjs/router 0.8.3-alpha.0 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dist/cjs/index.cjs +2 -0
- package/.dist/cjs/index.cjs.map +1 -1
- package/.dist/cjs/src/defaultRoutes.cjs.map +1 -1
- package/.dist/cjs/src/lib/aotEmitter.cjs +7 -3
- package/.dist/cjs/src/lib/aotEmitter.cjs.map +1 -1
- package/.dist/cjs/src/lib/aotEmitter.d.ts +6 -0
- package/.dist/cjs/src/lib/reflection.cjs +51 -19
- package/.dist/cjs/src/lib/reflection.cjs.map +1 -1
- package/.dist/cjs/src/lib/reflection.d.ts +3 -1
- package/.dist/cjs/src/lib/remoteMethods.cjs +26 -10
- package/.dist/cjs/src/lib/remoteMethods.cjs.map +1 -1
- package/.dist/cjs/src/lib/test/aotEmitter-test-router.cjs.map +1 -1
- package/.dist/cjs/src/router.cjs +61 -8
- package/.dist/cjs/src/router.cjs.map +1 -1
- package/.dist/cjs/src/router.d.ts +2 -0
- package/.dist/cjs/src/routes/client.routes.cjs +12 -12
- package/.dist/cjs/src/routes/client.routes.cjs.map +1 -1
- package/.dist/cjs/src/routes/client.routes.d.ts +5 -2
- package/.dist/cjs/src/routes/mion.routes.d.ts +0 -1
- package/.dist/cjs/src/routesFlow.cjs +3 -3
- package/.dist/cjs/src/routesFlow.cjs.map +1 -1
- package/.dist/cjs/src/types/general.cjs +1 -1
- package/.dist/cjs/src/types/general.d.ts +1 -0
- package/.dist/cjs/src/types/remoteMethods.cjs +3 -3
- package/.dist/cjs/src/types/remoteMethods.cjs.map +1 -1
- package/.dist/cjs/src/types/remoteMethods.d.ts +3 -3
- package/.dist/esm/index.js +3 -1
- package/.dist/esm/src/defaultRoutes.js.map +1 -1
- package/.dist/esm/src/lib/aotEmitter.d.ts +6 -0
- package/.dist/esm/src/lib/aotEmitter.js +8 -4
- package/.dist/esm/src/lib/aotEmitter.js.map +1 -1
- package/.dist/esm/src/lib/reflection.d.ts +3 -1
- package/.dist/esm/src/lib/reflection.js +53 -21
- package/.dist/esm/src/lib/reflection.js.map +1 -1
- package/.dist/esm/src/lib/remoteMethods.js +26 -10
- package/.dist/esm/src/lib/remoteMethods.js.map +1 -1
- package/.dist/esm/src/lib/test/aotEmitter-test-router.js.map +1 -1
- package/.dist/esm/src/router.d.ts +2 -0
- package/.dist/esm/src/router.js +64 -11
- package/.dist/esm/src/router.js.map +1 -1
- package/.dist/esm/src/routes/client.routes.d.ts +5 -2
- package/.dist/esm/src/routes/client.routes.js +15 -15
- package/.dist/esm/src/routes/client.routes.js.map +1 -1
- package/.dist/esm/src/routes/mion.routes.d.ts +0 -1
- package/.dist/esm/src/routesFlow.js +1 -1
- package/.dist/esm/src/routesFlow.js.map +1 -1
- package/.dist/esm/src/types/general.d.ts +1 -0
- package/.dist/esm/src/types/general.js +1 -1
- package/.dist/esm/src/types/remoteMethods.d.ts +3 -3
- package/.dist/esm/src/types/remoteMethods.js +3 -3
- package/.dist/esm/src/types/remoteMethods.js.map +1 -1
- package/package.json +4 -4
|
@@ -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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AI,MAAM;AACjC,SAAO;AACX;;AAGA,SAAS,qBAAqB,SAA0B;AACpD,SAAA,aAAO,CAAC,QAAoB;AAExB,UAAM,eAAe,IAAI,SAAS,KAAK,QAAQ,MAAM;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,MAAA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O;AACX;;AAGA,SAAS,qBAAqB,SAA0B;AACpD,SAAA,aAAO,CAAC,QAAoB;AAExB,UAAM,eAAe,IAAI,SAAS,KAAK,QAAQ,MAAM;AAGrD,UAAM,QAAQH,cAAAA,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/)
|
|
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
|
|
11
|
-
const __ΩMiddleFnOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩMiddleFnMethod, "options", "description", "validateParams", "validateReturn", "runOnError", "MiddleFnOptions", `n#.$fP.%.&.'.(Jo"#o!"w
|
|
12
|
-
const __ΩHeadersMiddleFnOptions = [() => __ΩPartial, () => __ΩPick, () => __ΩHeadersMethod, "options", "description", "validateParams", "validateReturn", "runOnError", "HeadersMiddleFnOptions", `n#.$fP.%.&.'.(Jo"#o!"w
|
|
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
|
|
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;
|
package/.dist/esm/index.js
CHANGED
|
@@ -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
|
|
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@methodsMetadata: Methods metadata middleware (returns metadata alongside any route response)\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
|
-
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";
|
|
1
|
+
import { JIT_FUNCTION_IDS, isMionAOTEmitMode, getENV, getJitFnCaches, __ΩClientSrcCodeJITCompiledFnsCache as ___ClientSrcCodeJITCompiledFnsCache, __ΩSrcCodeJITCompiledFnsCache as ___SrcCodeJITCompiledFnsCache, __ΩClientSrcCodePureFunctionsCache as ___ClientSrcCodePureFunctionsCache, __Ω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") === "
|
|
23
|
+
if (getENV("MION_COMPILE") === "middleware")
|
|
22
24
|
return;
|
|
23
25
|
if (typeof process.send !== "function")
|
|
24
26
|
return;
|
|
@@ -33,8 +35,9 @@ async function emitAOTCaches() {
|
|
|
33
35
|
}
|
|
34
36
|
emitAOTCaches.__type = ["emitAOTCaches", "P$`/!"];
|
|
35
37
|
async function serializeCachesToCode(jitFnsCache, pureFnsCache, routerCache) {
|
|
36
|
-
const
|
|
37
|
-
const
|
|
38
|
+
const isClient = getENV("MION_AOT_IS_CLIENT") === "true";
|
|
39
|
+
const jitToJSCode = isClient ? (createToJavascriptFn.Ω = [[() => ___ClientSrcCodeJITCompiledFnsCache, "n!"]], createToJavascriptFn()) : (createToJavascriptFn.Ω = [[() => ___SrcCodeJITCompiledFnsCache, "n!"]], createToJavascriptFn());
|
|
40
|
+
const pureToJSCode = isClient ? (createToJavascriptFn.Ω = [[() => ___ClientSrcCodePureFunctionsCache, "n!"]], createToJavascriptFn()) : (createToJavascriptFn.Ω = [[() => ___SrcCodePureFunctionsCache, "n!"]], createToJavascriptFn());
|
|
38
41
|
const routerToJSCode = (createToJavascriptFn.Ω = [[() => ___MethodsCache, "n!"]], createToJavascriptFn());
|
|
39
42
|
const finalJitFns = filterExcludedJitFns(jitFnsCache, EXCLUDED_JIT_FN_IDS);
|
|
40
43
|
const finalPureFns = filterExcludedPureFns(pureFnsCache, EXCLUDED_PURE_FN_NAMES);
|
|
@@ -62,6 +65,7 @@ function filterExcludedPureFns(pureFnsCache, excludedFnNames) {
|
|
|
62
65
|
filterExcludedPureFns.__type = [() => ___PureFunctionsCache, "pureFnsCache", "excludedFnNames", () => ___PureFunctionsCache, "filterExcludedPureFns", 'Pn!2"&F2#n$/%'];
|
|
63
66
|
export {
|
|
64
67
|
__ΩAOTCacheMessage,
|
|
68
|
+
__ΩPlatformReadyMessage,
|
|
65
69
|
__ΩSerializedCaches,
|
|
66
70
|
emitAOTCaches,
|
|
67
71
|
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 //
|
|
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 ClientSrcCodeJITCompiledFnsCache,\n ClientSrcCodePureFunctionsCache,\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 isClient = getENV('MION_AOT_IS_CLIENT') === 'true';\n const jitToJSCode = isClient\n ? createToJavascriptFn<ClientSrcCodeJITCompiledFnsCache>()\n : createToJavascriptFn<SrcCodeJITCompiledFnsCache>();\n const pureToJSCode = isClient\n ? createToJavascriptFn<ClientSrcCodePureFunctionsCache>()\n : 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":["__ΩClientSrcCodeJITCompiledFnsCache","__ΩSrcCodeJITCompiledFnsCache","__ΩClientSrcCodePureFunctionsCache","__ΩSrcCodePureFunctionsCache"],"mappings":";;;;;;;;;;;AA8CA,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,WAAW,OAAO,oBAAoB,MAAM;AA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'../types/handlers.ts';
|
|
3
3
|
import { RouterOptions } from '../types/general.ts';
|
|
4
|
+
import { RouteOptions, MiddleFnOptions, HeadersMiddleFnOptions, MiddleFnMethod, HeadersMethod } from '../types/remoteMethods.ts';
|
|
4
5
|
type MethodReflect = Omit<MethodWithJitFns, 'id' | 'type' | 'nestLevel' | 'pointer' | 'options'>;
|
|
5
6
|
export declare class AOTCacheError extends Error {
|
|
6
7
|
constructor(routeId: string, type?: 'route' | 'middleFn' | 'rawMiddleFn');
|
|
7
8
|
}
|
|
8
9
|
export declare function resetRunTypesCache(): void;
|
|
9
10
|
export declare function resetReflectionCaches(): void;
|
|
10
|
-
export declare function getHandlerReflection(handler: Handler, routeId: string, routerOptions: RouterOptions, isHeadersMiddleFn?: boolean): Promise<MethodReflect>;
|
|
11
|
+
export declare function getHandlerReflection(handler: Handler, routeId: string, routerOptions: RouterOptions, handlerOptions?: RouteOptions | MiddleFnOptions | HeadersMiddleFnOptions, isHeadersMiddleFn?: boolean, methodStrictTypes?: boolean): Promise<MethodReflect>;
|
|
11
12
|
export declare function getRawMethodReflection(handler: Handler, routeId: string, routerOptions: RouterOptions): Promise<MethodReflect>;
|
|
13
|
+
export declare function ensureBinaryJitFns(method: MiddleFnMethod | HeadersMethod): Promise<void>;
|
|
12
14
|
export {};
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { __ΩHandler as ___Handler } from "../types/handlers.js";
|
|
2
2
|
import { __ΩRouterOptions as ___RouterOptions } from "../types/general.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { HEADER_HOOK_DEFAULT_PARAMS, ROUTE_DEFAULT_PARAMS, DEFAULT_ROUTE_OPTIONS } from "../constants.js";
|
|
4
|
+
import { HandlerType, EMPTY_HASH, getJitFunctionsFromHash, getNoopJitFns, HeadersSubset } from "@mionjs/core";
|
|
5
5
|
import { getPersistedMethodMetadata } from "./methodsCache.js";
|
|
6
|
+
import { __ΩRouteOptions as ___RouteOptions, __ΩMiddleFnOptions as ___MiddleFnOptions, __ΩHeadersMiddleFnOptions as ___HeadersMiddleFnOptions, __ΩMiddleFnMethod as ___MiddleFnMethod, __ΩHeadersMethod as ___HeadersMethod } from "../types/remoteMethods.js";
|
|
6
7
|
const __ΩOmit = ["T", "K", () => __ΩPick, () => __ΩExclude, "Omit", 'b!b"e!!e!!ge!"o$#o##w%y'];
|
|
7
8
|
const __ΩPick = ["T", "K", "Pick", 'l+e#!e"!fRb!b"Pde""N#!w#y'];
|
|
8
9
|
const __ΩExclude = ["T", "U", "Exclude", 'l6!Re$!RPe#!e$"qk#%QRb!b"Pde"!p)w#y'];
|
|
@@ -102,16 +103,16 @@ function extractReflectionFromCached(cached) {
|
|
|
102
103
|
return reflectionItems;
|
|
103
104
|
}
|
|
104
105
|
extractReflectionFromCached.__type = [() => __ΩCachedMethodMetadata, "cached", () => __ΩMethodReflect, "extractReflectionFromCached", 'Pn!2"n#/$'];
|
|
105
|
-
async function getHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn = false) {
|
|
106
|
+
async function getHandlerReflection(handler, routeId, routerOptions, handlerOptions = {}, isHeadersMiddleFn = false, methodStrictTypes) {
|
|
106
107
|
const cached = getPersistedMethodMetadata(routeId);
|
|
107
108
|
if (cached)
|
|
108
109
|
return extractReflectionFromCached(cached);
|
|
109
110
|
if (routerOptions.aot)
|
|
110
111
|
throw new AOTCacheError(routeId, isHeadersMiddleFn ? "middleFn" : "route");
|
|
111
112
|
const rt = await loadRunTypesModule();
|
|
112
|
-
return generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt);
|
|
113
|
+
return generateHandlerReflection(handler, routeId, routerOptions, handlerOptions, isHeadersMiddleFn, rt, methodStrictTypes);
|
|
113
114
|
}
|
|
114
|
-
getHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", "isHeadersMiddleFn", () => false, () => __ΩMethodReflect, "getHandlerReflection", "Pn!2\"&2#n$2%
|
|
115
|
+
getHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", () => ___RouteOptions, () => ___MiddleFnOptions, () => ___HeadersMiddleFnOptions, "handlerOptions", () => ({}), "isHeadersMiddleFn", () => false, "methodStrictTypes", () => __ΩMethodReflect, "getHandlerReflection", "Pn!2\"&2#n$2%Pn&n'n(J2)>*)2+>,)2-8n.`//"];
|
|
115
116
|
async function getRawMethodReflection(handler, routeId, routerOptions) {
|
|
116
117
|
const cached = getPersistedMethodMetadata(routeId);
|
|
117
118
|
if (cached)
|
|
@@ -122,10 +123,15 @@ async function getRawMethodReflection(handler, routeId, routerOptions) {
|
|
|
122
123
|
return generateRawMethodReflection(handler, routeId, rt);
|
|
123
124
|
}
|
|
124
125
|
getRawMethodReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", () => __ΩMethodReflect, "getRawMethodReflection", "Pn!2\"&2#n$2%n&`/'"];
|
|
125
|
-
function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMiddleFn, rt) {
|
|
126
|
+
function generateHandlerReflection(handler, routeId, routerOptions, handlerOptions, isHeadersMiddleFn, rt, methodStrictTypes) {
|
|
126
127
|
const reflectionItems = {};
|
|
127
128
|
let handlerRunType;
|
|
128
|
-
const
|
|
129
|
+
const needsBinary = (handlerOptions?.serializer ?? routerOptions.serializer) === "binary";
|
|
130
|
+
const effectiveStrictTypes = methodStrictTypes ?? routerOptions.strictTypes;
|
|
131
|
+
const runTypeOptions = {
|
|
132
|
+
...routerOptions?.runTypeOptions || DEFAULT_ROUTE_OPTIONS.runTypeOptions,
|
|
133
|
+
...effectiveStrictTypes !== void 0 ? { strictTypes: effectiveStrictTypes } : {}
|
|
134
|
+
};
|
|
129
135
|
try {
|
|
130
136
|
handlerRunType = rt.reflectFunction(handler);
|
|
131
137
|
} catch (error) {
|
|
@@ -139,7 +145,7 @@ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMid
|
|
|
139
145
|
reflectionItems.paramsJitHash = EMPTY_HASH;
|
|
140
146
|
reflectionItems.paramsJitFns = getNoopJitFns();
|
|
141
147
|
} else {
|
|
142
|
-
reflectionItems.paramsJitFns = getFunctionJitFns(handler, paramsOpts, rt, false);
|
|
148
|
+
reflectionItems.paramsJitFns = getFunctionJitFns(handler, paramsOpts, rt, false, needsBinary);
|
|
143
149
|
reflectionItems.paramsJitHash = handlerRunType.getParameters().getJitHash(paramsOpts);
|
|
144
150
|
}
|
|
145
151
|
} catch (error) {
|
|
@@ -153,7 +159,7 @@ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMid
|
|
|
153
159
|
...runTypeOptions,
|
|
154
160
|
paramsSlice: void 0
|
|
155
161
|
};
|
|
156
|
-
const jitFns = getTypeJitFunctions(headersRunType, opts, rt);
|
|
162
|
+
const jitFns = getTypeJitFunctions(headersRunType, opts, rt, false);
|
|
157
163
|
const jitHash = headersRunType.getJitHash(opts);
|
|
158
164
|
reflectionItems.headersParam = { headerNames, jitFns, jitHash };
|
|
159
165
|
} catch (error) {
|
|
@@ -164,7 +170,7 @@ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMid
|
|
|
164
170
|
if (returnHeadersRunType) {
|
|
165
171
|
const opts = {};
|
|
166
172
|
const headerNames = getHeaderNames(returnHeadersRunType, routeId, rt);
|
|
167
|
-
const jitFns = getFunctionJitFns(handler, opts, rt, true);
|
|
173
|
+
const jitFns = getFunctionJitFns(handler, opts, rt, true, false);
|
|
168
174
|
const jitHash = returnHeadersRunType.getJitHash(opts);
|
|
169
175
|
reflectionItems.headersReturn = { headerNames, jitFns, jitHash };
|
|
170
176
|
}
|
|
@@ -175,8 +181,8 @@ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMid
|
|
|
175
181
|
reflectionItems.returnJitFns = getNoopJitFns();
|
|
176
182
|
reflectionItems.returnJitHash = EMPTY_HASH;
|
|
177
183
|
} else {
|
|
178
|
-
reflectionItems.returnJitFns = getFunctionJitFns(handler, returnOpts, rt, true);
|
|
179
|
-
reflectionItems.returnJitHash = handlerRunType.
|
|
184
|
+
reflectionItems.returnJitFns = getFunctionJitFns(handler, returnOpts, rt, true, needsBinary);
|
|
185
|
+
reflectionItems.returnJitHash = handlerRunType.getResolvedReturnType().getJitHash(returnOpts);
|
|
180
186
|
}
|
|
181
187
|
} catch (error) {
|
|
182
188
|
throw new Error(`Can not get Jit Functions for Return of route/middleFn "${routeId}." Error: ${error?.message}`);
|
|
@@ -184,7 +190,7 @@ function generateHandlerReflection(handler, routeId, routerOptions, isHeadersMid
|
|
|
184
190
|
reflectionItems.isAsync = handlerRunType.isAsync();
|
|
185
191
|
return reflectionItems;
|
|
186
192
|
}
|
|
187
|
-
generateHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", "isHeadersMiddleFn", () => __ΩRunTypesFunctions, "rt", () => __ΩMethodReflect, "generateHandlerReflection", `Pn!2"&2#n$2%
|
|
193
|
+
generateHandlerReflection.__type = [() => ___Handler, "handler", "routeId", () => ___RouterOptions, "routerOptions", () => ___RouteOptions, () => ___MiddleFnOptions, () => ___HeadersMiddleFnOptions, "handlerOptions", "isHeadersMiddleFn", () => __ΩRunTypesFunctions, "rt", "methodStrictTypes", () => __ΩMethodReflect, "generateHandlerReflection", `Pn!2"&2#n$2%Pn&n'n(J2))2*n+2,)2-8n.//`];
|
|
188
194
|
function generateRawMethodReflection(handler, routeId, rt) {
|
|
189
195
|
let handlerRunType;
|
|
190
196
|
try {
|
|
@@ -277,21 +283,23 @@ function getFakeCompiler(routerOptions) {
|
|
|
277
283
|
return { opts: routerOptions };
|
|
278
284
|
}
|
|
279
285
|
getFakeCompiler.__type = [() => ___RouterOptions, "routerOptions", "JitFnCompiler", "getFakeCompiler", 'Pn!2""w#/$'];
|
|
280
|
-
function getTypeJitFunctions(runType, opts, rtModule) {
|
|
286
|
+
function getTypeJitFunctions(runType, opts, rtModule, needsBinary = false) {
|
|
281
287
|
const jitFns = {
|
|
282
288
|
isType: runType.createJitCompiledFunction(rtModule.JitFunctions.isType.id, void 0, opts),
|
|
283
289
|
typeErrors: runType.createJitCompiledFunction(rtModule.JitFunctions.typeErrors.id, void 0, opts),
|
|
284
290
|
prepareForJson: runType.createJitCompiledFunction(rtModule.JitFunctions.prepareForJson.id, void 0, opts),
|
|
285
291
|
restoreFromJson: runType.createJitCompiledFunction(rtModule.JitFunctions.restoreFromJson.id, void 0, opts),
|
|
286
292
|
stringifyJson: runType.createJitCompiledFunction(rtModule.JitFunctions.stringifyJson.id, void 0, opts),
|
|
287
|
-
|
|
288
|
-
|
|
293
|
+
...needsBinary ? {
|
|
294
|
+
toBinary: runType.createJitCompiledFunction(rtModule.JitFunctions.toBinary.id, void 0, opts),
|
|
295
|
+
fromBinary: runType.createJitCompiledFunction(rtModule.JitFunctions.fromBinary.id, void 0, opts)
|
|
296
|
+
} : {}
|
|
289
297
|
};
|
|
290
298
|
return jitFns;
|
|
291
299
|
}
|
|
292
|
-
getTypeJitFunctions.__type = ["BaseRunType", "runType", "RunTypeOptions", "opts", () => __ΩRunTypesFunctions, "rtModule", "JitCompiledFunctions", "getTypeJitFunctions", `P"w!2"P"w#-J2$n%2&"w
|
|
300
|
+
getTypeJitFunctions.__type = ["BaseRunType", "runType", "RunTypeOptions", "opts", () => __ΩRunTypesFunctions, "rtModule", "needsBinary", () => false, "JitCompiledFunctions", "getTypeJitFunctions", `P"w!2"P"w#-J2$n%2&)2'>("w)/*`];
|
|
293
301
|
const functionRunTypeCache = (WeakMap.Ω = [["AnyFn", '"w!'], ["FunctionRunType", '"w!']], /* @__PURE__ */ new WeakMap());
|
|
294
|
-
function getFunctionJitFns(fn, opts, rtModule, isReturn) {
|
|
302
|
+
function getFunctionJitFns(fn, opts, rtModule, isReturn, needsBinary = false) {
|
|
295
303
|
let runType = functionRunTypeCache.get(fn);
|
|
296
304
|
if (!runType) {
|
|
297
305
|
runType = rtModule.reflectFunction(fn);
|
|
@@ -304,14 +312,38 @@ function getFunctionJitFns(fn, opts, rtModule, isReturn) {
|
|
|
304
312
|
prepareForJson: createFn(rtModule.JitFunctions.prepareForJson, opts),
|
|
305
313
|
restoreFromJson: createFn(rtModule.JitFunctions.restoreFromJson, opts),
|
|
306
314
|
stringifyJson: createFn(rtModule.JitFunctions.stringifyJson, opts),
|
|
307
|
-
|
|
308
|
-
|
|
315
|
+
...needsBinary ? {
|
|
316
|
+
toBinary: createFn(rtModule.JitFunctions.toBinary, opts),
|
|
317
|
+
fromBinary: createFn(rtModule.JitFunctions.fromBinary, opts)
|
|
318
|
+
} : {}
|
|
309
319
|
};
|
|
310
320
|
return jitFunctions;
|
|
311
321
|
}
|
|
312
|
-
getFunctionJitFns.__type = ["fn", "RunTypeOptions", "opts", () => __ΩRunTypesFunctions, "rtModule", "isReturn", "JitCompiledFunctions", "getFunctionJitFns", `P"2!P"w"-J2#n$2%)2&"w
|
|
322
|
+
getFunctionJitFns.__type = ["fn", "RunTypeOptions", "opts", () => __ΩRunTypesFunctions, "rtModule", "isReturn", "needsBinary", () => false, "JitCompiledFunctions", "getFunctionJitFns", `P"2!P"w"-J2#n$2%)2&)2'>("w)/*`];
|
|
323
|
+
async function ensureBinaryJitFns(method) {
|
|
324
|
+
if (method.paramsJitFns.toBinary && method.returnJitFns.toBinary)
|
|
325
|
+
return;
|
|
326
|
+
const rt = await loadRunTypesModule();
|
|
327
|
+
const isHeader = method.type === HandlerType.headersMiddleFn;
|
|
328
|
+
const paramsSlice = isHeader ? { start: HEADER_HOOK_DEFAULT_PARAMS.length } : { start: ROUTE_DEFAULT_PARAMS.length };
|
|
329
|
+
const opts = { paramsSlice };
|
|
330
|
+
if (!method.paramsJitFns.toBinary && method.paramsJitHash !== EMPTY_HASH) {
|
|
331
|
+
const runType = rt.reflectFunction(method.handler);
|
|
332
|
+
const createFn = runType.createJitCompiledParamsFunction.bind(runType);
|
|
333
|
+
method.paramsJitFns.toBinary = createFn(rt.JitFunctions.toBinary, opts);
|
|
334
|
+
method.paramsJitFns.fromBinary = createFn(rt.JitFunctions.fromBinary, opts);
|
|
335
|
+
}
|
|
336
|
+
if (!method.returnJitFns.toBinary && method.returnJitHash !== EMPTY_HASH && method.hasReturnData) {
|
|
337
|
+
const runType = rt.reflectFunction(method.handler);
|
|
338
|
+
const createFn = runType.createJitCompiledReturnFunction.bind(runType);
|
|
339
|
+
method.returnJitFns.toBinary = createFn(rt.JitFunctions.toBinary);
|
|
340
|
+
method.returnJitFns.fromBinary = createFn(rt.JitFunctions.fromBinary);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
ensureBinaryJitFns.__type = [() => ___MiddleFnMethod, () => ___HeadersMethod, "method", "ensureBinaryJitFns", 'PPn!n"J2#$`/$'];
|
|
313
344
|
export {
|
|
314
345
|
AOTCacheError,
|
|
346
|
+
ensureBinaryJitFns,
|
|
315
347
|
getHandlerReflection,
|
|
316
348
|
getRawMethodReflection,
|
|
317
349
|
resetReflectionCaches,
|