@mionjs/core 0.8.4-alpha.0 → 0.8.6

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 (42) hide show
  1. package/.dist/cjs/index.cjs +4 -0
  2. package/.dist/cjs/index.cjs.map +1 -1
  3. package/.dist/cjs/src/binary/bodyDeserializer.cjs +5 -0
  4. package/.dist/cjs/src/binary/bodyDeserializer.cjs.map +1 -1
  5. package/.dist/cjs/src/binary/bodySerializer.cjs +1 -6
  6. package/.dist/cjs/src/binary/bodySerializer.cjs.map +1 -1
  7. package/.dist/cjs/src/constants.cjs +5 -3
  8. package/.dist/cjs/src/constants.cjs.map +1 -1
  9. package/.dist/cjs/src/constants.d.ts +1 -1
  10. package/.dist/cjs/src/pureFns/pureFn.cjs +6 -4
  11. package/.dist/cjs/src/pureFns/pureFn.cjs.map +1 -1
  12. package/.dist/cjs/src/pureFns/restoreJitFns.cjs +3 -3
  13. package/.dist/cjs/src/pureFns/restoreJitFns.cjs.map +1 -1
  14. package/.dist/cjs/src/routerUtils.cjs +16 -17
  15. package/.dist/cjs/src/routerUtils.cjs.map +1 -1
  16. package/.dist/cjs/src/routerUtils.d.ts +1 -1
  17. package/.dist/cjs/src/types/general.types.cjs +15 -5
  18. package/.dist/cjs/src/types/general.types.cjs.map +1 -1
  19. package/.dist/cjs/src/types/general.types.d.ts +17 -8
  20. package/.dist/cjs/src/types/pureFunctions.types.cjs +1 -1
  21. package/.dist/cjs/src/types/pureFunctions.types.d.ts +1 -1
  22. package/.dist/esm/index.js +5 -1
  23. package/.dist/esm/src/binary/bodyDeserializer.js +5 -0
  24. package/.dist/esm/src/binary/bodyDeserializer.js.map +1 -1
  25. package/.dist/esm/src/binary/bodySerializer.js +1 -6
  26. package/.dist/esm/src/binary/bodySerializer.js.map +1 -1
  27. package/.dist/esm/src/constants.d.ts +1 -1
  28. package/.dist/esm/src/constants.js +5 -3
  29. package/.dist/esm/src/constants.js.map +1 -1
  30. package/.dist/esm/src/pureFns/pureFn.js +6 -4
  31. package/.dist/esm/src/pureFns/pureFn.js.map +1 -1
  32. package/.dist/esm/src/pureFns/restoreJitFns.js +3 -3
  33. package/.dist/esm/src/pureFns/restoreJitFns.js.map +1 -1
  34. package/.dist/esm/src/routerUtils.d.ts +1 -1
  35. package/.dist/esm/src/routerUtils.js +16 -17
  36. package/.dist/esm/src/routerUtils.js.map +1 -1
  37. package/.dist/esm/src/types/general.types.d.ts +17 -8
  38. package/.dist/esm/src/types/general.types.js +16 -6
  39. package/.dist/esm/src/types/general.types.js.map +1 -1
  40. package/.dist/esm/src/types/pureFunctions.types.d.ts +1 -1
  41. package/.dist/esm/src/types/pureFunctions.types.js +1 -1
  42. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"general.types.cjs","sources":["../../../../src/types/general.types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-function-type */\n/* ###############\n * 2022 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ############### */\n\nimport {MIME_TYPES} from '../constants.ts';\nimport {TypeFormatError} from './formats/formats.types.ts';\nimport type {JITUtils} from '../jit/jitUtils.ts';\nimport {CompiledPureFunction, PersistedPureFunction, PureFunctionData} from './pureFunctions.types.ts';\n\n// ########################################## Serialization Modes ##########################################\n\nexport const SerializerModes = {\n /** Use prepareForJson (mutates original objects), and leaves JSON.stringify to the platform adapter */\n json: 1,\n /** Use toBinary JIT function for binary serialization */\n binary: 2,\n /** Use stringifyJson JIT function that do not mutates objects. */\n stringifyJson: 3,\n} as const;\n\n/**\n * Serializer mode for response body serialization.\n * - 'json': Use prepareForJson, platform adapter handles JSON.stringify\n * - 'binary': Use toBinary JIT function for binary serialization\n * - 'stringifyJson': Use stringifyJson JIT function that do not mutates objects.\n */\nexport type SerializerMode = keyof typeof SerializerModes;\nexport type SerializerCode = (typeof SerializerModes)[SerializerMode];\n\n// ########################################## Options ##########################################\n\nexport type CoreRouterOptions = {\n /** automatically generate and uuid */\n autoGenerateErrorId: boolean;\n /** basePath for all routes */\n basePath: string;\n /** suffix for all routes, ie file extension etc */\n suffix: string;\n};\n\n// ########################################## Errors ##########################################\n\n/** Base parameters for TypedError */\nexport interface TypedErrorParams<ErrType extends StrNumber> {\n /** Error type, can be used as discriminator in union types switch, etc*/\n type: ErrType;\n /** the error message */\n message?: string;\n /** original error used to create the TypedError */\n originalError?: Error;\n}\n\n/** Any error triggered by middleFns or routes must follow this interface, returned errors in the body also follows this interface */\nexport interface RpcErrorParams<ErrType extends StrNumber, ErrData = any> {\n /** Error type, can be used as discriminator in union types switch, etc*/\n type: ErrType;\n /** id of the error. */\n id?: number | string;\n /** the message that will be returned in the response */\n publicMessage?: string;\n /**\n * the error message, it is private and wont be returned in the response.\n * If not defined, it is assigned from originalError.message or publicMessage.\n */\n message?: string;\n /** options data related to the error, ie validation data */\n errorData?: ErrData;\n /** original error used to create the RpcError */\n originalError?: Error;\n /** optional http status code */\n statusCode?: number;\n}\n\nexport interface RpcErrorWithPublic<ErrType extends StrNumber, ErrData = any> extends RpcErrorParams<ErrType, ErrData> {\n publicMessage: string;\n}\n\nexport interface RpcErrorWithPrivate<ErrType extends StrNumber, ErrData = any> extends RpcErrorParams<ErrType, ErrData> {\n message: string;\n}\n\n/** Error data returned to the clients */\nexport interface PublicRpcError<ErrType extends StrNumber, ErrData = any> extends Omit<\n RpcErrorParams<ErrType, ErrData>,\n 'message' | 'originalError'\n> {\n readonly 'mion@isΣrrθr': true;\n type: ErrType;\n errorData?: ErrData;\n /**\n * When a RpcError gets sent to client only publicMessage is set.\n * */\n publicMessage: string;\n}\n\nexport type AnyErrorParams<ErrType extends StrNumber, ErrData = any> =\n | RpcErrorWithPublic<ErrType, ErrData>\n | RpcErrorWithPrivate<ErrType, ErrData>;\n\n/** Path segment for Map key errors */\nexport type MapKeyPathSegment = {key: unknown; index: number; failed: 'mapKey'};\n\n/** Path segment for Map value errors */\nexport type MapValuePathSegment = {key: unknown; index: number; failed: 'mapVal'};\n\n/** Path segment for Set item errors */\nexport type SetItemPathSegment = {key: unknown; index: number};\n\n/** Any path segment in a RunTypeError path */\nexport type PathSegment = StrNumber | MapKeyPathSegment | MapValuePathSegment | SetItemPathSegment;\n\nexport interface RunTypeError {\n /**\n * Path to the property that failed validation if the validated item was an object class, etc..\n * Index if item that failed validation was in an array.\n * For Maps: contains {key, index, failed: 'mapKey'|'mapVal'} objects.\n * For Sets: contains {key, index} objects.\n * Empty array if validated item was a single property */\n path: PathSegment[];\n /** the type of the expected data */\n expected: string;\n format?: TypeFormatError;\n // typeName?: string; // tyeName can not be included as two types could Have the same typeID and different names\n}\n\n// ########################################### JIT FUNCTIONS ###########################################\n\n/**\n * The argument names of the function to be compiled. The order of properties is important as must the same as the function args.\n * ie: {vλl: 'val', arg1: 'arg1', error: 'newRunTypeErr'} for the function (vλl, arg1, eArr) => any\n */\nexport type JitFnArgs = {\n /** The name of the value of to be */\n vλl: string;\n /** Other argument names */\n [key: string]: string;\n};\n\nexport interface JitCompiledFnData {\n readonly typeName: string;\n /** The id of the function (operation) to be compiled (isType, typeErrors, prepareForJson, restoreFromJson, etc) */\n readonly fnID: string;\n /** Unique id of the function */\n readonly jitFnHash: string;\n /** The names of the arguments of the function */\n readonly args: JitFnArgs;\n /** Default values for the arguments */\n readonly defaultParamValues: JitFnArgs;\n /**\n * This flag is set to true when the result of a jit compilation is a no operation (empty function).\n * if this flag is set to true, the function should not be called as it will not do anything.\n */\n readonly isNoop?: boolean;\n /** Code for the jit function. after the operation has been compiled */\n readonly code: string;\n /** The list of all jit functions that are used by this function and it's children. */\n readonly jitDependencies: Array<string>;\n /** Pure function dependencies in format \"namespace::fnHash\" */\n readonly pureFnDependencies: Array<string>;\n /** function param names if the compiled type is function params */\n paramNames?: string[];\n}\n\nexport interface JitCompiledFn<Fn extends AnyFn = AnyFn> extends JitCompiledFnData {\n /** The closure function that contains the jit function, this one contains the context code */\n readonly createJitFn: (utl: JITUtils) => Fn;\n /** The Jit Generated function once the compilation is finished */\n readonly fn: Fn;\n}\n\n/** Jit Functions serialized to src code file, it contains the create jit function\n * but not the actual fn as this one can not be serialized to code.\n */\nexport interface PersistedJitFn extends Omit<JitCompiledFn, 'fn'> {\n /** The Jit Generated function once the compilation is finished */\n readonly fn: undefined;\n}\n\nexport interface JitCompiledFunctions {\n isType: JitCompiledFn<IsTypeFn>;\n typeErrors: JitCompiledFn<TypeErrorsFn>;\n prepareForJson: JitCompiledFn<PrepareForJsonFn>;\n restoreFromJson: JitCompiledFn<RestoreFromJsonFn>;\n stringifyJson: JitCompiledFn<JsonStringifyFn>;\n toBinary: JitCompiledFn<ToBinaryFn>;\n fromBinary: JitCompiledFn<FromBinaryFn>;\n}\nexport interface SerializableJITFunctions {\n isType: JitCompiledFnData;\n typeErrors: JitCompiledFnData;\n prepareForJson: JitCompiledFnData;\n restoreFromJson: JitCompiledFnData;\n stringifyJson: JitCompiledFnData;\n toBinary: JitCompiledFnData;\n fromBinary: JitCompiledFnData;\n}\nexport interface JitFunctionsHashes {\n isType: string;\n typeErrors: string;\n prepareForJson: string;\n restoreFromJson: string;\n stringifyJson: string;\n toBinary: string;\n fromBinary: string;\n}\nexport type JsonStringifyFn = (value: any) => JSONString;\nexport type RestoreFromJsonFn = (value: JSONValue) => any;\nexport type PrepareForJsonFn = (value: any) => JSONValue;\nexport type TypeErrorsFn = (value: any) => RunTypeError[];\nexport type IsTypeFn = (value: any) => boolean;\nexport type ToCodeFn = (value: any) => string;\n/** Binary serialization function - serializes value to the serializer context */\nexport type ToBinaryFn = (value: any, serializer: DataViewSerializer) => void;\n/** Binary deserialization function - deserializes from the deserializer context and returns the value */\nexport type FromBinaryFn = (value: undefined, deserializer: DataViewDeserializer) => any;\n\n// ############################# JIT CACHES ###################################\n\n// jit and pure functions at runtime, contains both createJitFn and fn\nexport type JitFunctionsCache = Record<string, JitCompiledFn>;\n/** Namespaced cache structure for pure functions: { namespace: { fnHash: CompiledPureFunction } } */\nexport type PureFunctionsCache = Record<string, Record<string, CompiledPureFunction>>;\n\n// jit and pure functions persisted to src code, contains createJitFn but not fn\n// this allow usage in environments that can not use eval or new Function()\nexport type PersistedJitFunctionsCache = Record<string, PersistedJitFn>;\n/** Namespaced cache structure for persisted pure functions */\nexport type PersistedPureFunctionsCache = Record<string, Record<string, PersistedPureFunction>>;\n\n// jit and pure functions data, does not contain createJitFn or fn\n// this is used to serialize over the network, but requires using new Function() to restore functionality\nexport type FnsDataCache = Record<string, JitCompiledFnData>;\n/** Namespaced cache structure for pure function data */\nexport type PureFnsDataCache = Record<string, Record<string, PureFunctionData>>;\n\n// ########################################### JIT SRC CODE ####################################\n\nexport interface SrcCodeJitCompiledFn extends JitCompiledFnData {\n /** The closure function that contains the jit function, this one contains the context code */\n readonly createJitFn: (utl: JITUtils) => AnyFn;\n /** The Jit Generated function once the compilation is finished */\n readonly fn: undefined;\n}\nexport interface SrcCodeCompiledPureFunction extends PureFunctionData {\n /** The closure function that contains the pure function, this one contains the context code */\n readonly createPureFn: (utl: JITUtils) => AnyFn;\n /** The Jit Generated function once the compilation is finished */\n readonly fn: undefined;\n}\nexport type SrcCodeJITCompiledFnsCache = Record<string, SrcCodeJitCompiledFn>;\nexport type SrcCodePureFunctionsCache = Record<string, Record<string, SrcCodeCompiledPureFunction>>;\n\n// ########################################## other #########################################\n\nexport type StrNumber = string | number;\nexport type AnyFn = (...args: any[]) => any;\nexport type AnyObject = Record<string, unknown>;\nexport interface AnyClass<T = any> {\n new (...args: any[]): T;\n}\n\nexport interface SerializableClass<T = any> {\n new (): T;\n}\n\nexport type DeserializeClassFn<C extends InstanceType<AnyClass>> = (deserialized: DataOnly<C>) => C;\n\nexport type Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\nexport type Prettify<T> = {\n [P in keyof T]: T[P];\n} & {};\n\n// StrNumber is already defined at the top of the file\nexport type JSONValue = StrNumber | boolean | null | {[key: string]: JSONValue} | Array<JSONValue>;\nexport type JSONString = string;\n\n// prettier-ignore\ntype Native = Date | RegExp | URL | URLSearchParams | Blob | File | FileList | FormData | ArrayBuffer | SharedArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;\n\n/** Typescript mapping type that stripes methods and only keep properties.\n * it takes into account, dates, objects, classes, arrays, maps and sets.\n */\nexport type DataOnly<T> = T extends object\n ? T extends Native\n ? T\n : T extends Function\n ? never\n : T extends new (...args: any[]) => any\n ? never\n : T extends Array<infer U>\n ? Array<DataOnly<U>>\n : T extends Map<infer K, infer V>\n ? Map<DataOnly<K>, DataOnly<V>>\n : T extends Set<infer U>\n ? Set<DataOnly<U>>\n : {[K in keyof T as T[K] extends Function ? never : K]: DataOnly<T[K]>}\n : T;\n\n// TEST TYPES FOR PlainObject\n\n// class A {\n// n1?: number;\n// s?: string;\n// d?: Date;\n// map?: Map<string, RegExp>;\n// set?: Set<URL>;\n// arr?: A[];\n// method() {\n// return 'hello';\n// }\n// arrow = () => 'hello';\n// }\n\n// type PlainInterface = PlainObject<{\n// n1: number;\n// s: string;\n// d: Date;\n// a: A;\n// map: Map<string, A>;\n// set: Set<A>;\n// arr: A[];\n// method(): string;\n// arrow: () => string;\n// }>;\n\n// type PlainClass = PlainObject<A>;\n// type PlainSet = PlainObject<Set<A>>;\n// type PlainMap = PlainObject<Map<string, A>>;\n\n// ################# BINARY SERIALIZATION - IMPORTANT NOTE ##################################\n// DO NOT CHANGE THE INTERFACE NAMES AS THEY ARE HARDCODED IN THE JIT GENERATED CODE\n// ##########################################################################################\n\nexport type StrictArrayBuffer = ArrayBuffer & {buffer?: undefined};\n/** Input type for binary deserialization - accepts ArrayBuffer or any typed array view (including Node.js Buffer) */\nexport type BinaryInput = ArrayBuffer | ArrayBufferView;\nexport interface DataViewSerializer {\n index: number; // byte offset\n view: DataView;\n reset: () => void;\n getBuffer: () => StrictArrayBuffer;\n getBufferView: () => Uint8Array;\n markAsEnded: () => void;\n getLength(): number;\n // serialization functions\n serString(str: string): void;\n serFloat64(n: number): void;\n serEnum(n: number | string): void;\n setBitMask(bitMaskIndex: number, bitIndex: number): void;\n}\n\nexport interface DataViewDeserializer {\n index: number; // byte offset\n view: DataView;\n reset: () => void;\n setBuffer: (buffer: StrictArrayBuffer, byteOffset?: number, byteLength?: number) => void;\n markAsEnded: () => void;\n getLength(): number;\n // deserialization functions\n desString(): string;\n desFloat64(): number;\n desEnum(): number | string;\n}\n\nexport type MimeTypes = (typeof MIME_TYPES)[keyof typeof MIME_TYPES];\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAeO,MAAM,kBAAkB;AAAA;AAAA,EAE3B,MAAM;AAAA;AAAA,EAEN,QAAQ;AAAA;AAAA,EAER,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"general.types.cjs","sources":["../../../../src/types/general.types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unsafe-function-type */\n/* ###############\n * 2022 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ############### */\n\nimport {MIME_TYPES} from '../constants.ts';\nimport {TypeFormatError} from './formats/formats.types.ts';\nimport type {JITUtils} from '../jit/jitUtils.ts';\nimport {CompiledPureFunction, PersistedPureFunction, PureFunctionData} from './pureFunctions.types.ts';\n\n// ########################################## Serialization Modes ##########################################\n\nexport const SerializerModes = {\n /** Use prepareForJson (mutates original objects), and leaves JSON.stringify to the platform adapter */\n json: 1,\n /** Use toBinary JIT function for binary serialization */\n binary: 2,\n /** Use stringifyJson JIT function that do not mutates objects. */\n stringifyJson: 3,\n /** Client-only: sends plain JSON without JIT, fetches metadata in the same response */\n optimistic: 4,\n} as const;\n\n/**\n * Serializer mode for response body serialization.\n * - 'json': Use prepareForJson, platform adapter handles JSON.stringify\n * - 'binary': Use toBinary JIT function for binary serialization\n * - 'stringifyJson': Use stringifyJson JIT function that do not mutates objects.\n */\nexport type SerializerMode = keyof typeof SerializerModes;\nexport type SerializerCode = (typeof SerializerModes)[SerializerMode];\n\n// ########################################## Options ##########################################\n\nexport type CoreRouterOptions = {\n /** automatically generate and uuid */\n autoGenerateErrorId: boolean;\n /** basePath for all routes */\n basePath: string;\n /** suffix for all routes, ie file extension etc */\n suffix: string;\n};\n\n// ########################################## Errors ##########################################\n\n/** Base parameters for TypedError */\nexport interface TypedErrorParams<ErrType extends StrNumber> {\n /** Error type, can be used as discriminator in union types switch, etc*/\n type: ErrType;\n /** the error message */\n message?: string;\n /** original error used to create the TypedError */\n originalError?: Error;\n}\n\n/** Any error triggered by middleFns or routes must follow this interface, returned errors in the body also follows this interface */\nexport interface RpcErrorParams<ErrType extends StrNumber, ErrData = any> {\n /** Error type, can be used as discriminator in union types switch, etc*/\n type: ErrType;\n /** id of the error. */\n id?: number | string;\n /** the message that will be returned in the response */\n publicMessage?: string;\n /**\n * the error message, it is private and wont be returned in the response.\n * If not defined, it is assigned from originalError.message or publicMessage.\n */\n message?: string;\n /** options data related to the error, ie validation data */\n errorData?: ErrData;\n /** original error used to create the RpcError */\n originalError?: Error;\n /** optional http status code */\n statusCode?: number;\n}\n\nexport interface RpcErrorWithPublic<ErrType extends StrNumber, ErrData = any> extends RpcErrorParams<ErrType, ErrData> {\n publicMessage: string;\n}\n\nexport interface RpcErrorWithPrivate<ErrType extends StrNumber, ErrData = any> extends RpcErrorParams<ErrType, ErrData> {\n message: string;\n}\n\n/** Error data returned to the clients */\nexport interface PublicRpcError<ErrType extends StrNumber, ErrData = any> extends Omit<\n RpcErrorParams<ErrType, ErrData>,\n 'message' | 'originalError'\n> {\n readonly 'mion@isΣrrθr': true;\n type: ErrType;\n errorData?: ErrData;\n /**\n * When a RpcError gets sent to client only publicMessage is set.\n * */\n publicMessage: string;\n}\n\nexport type AnyErrorParams<ErrType extends StrNumber, ErrData = any> =\n | RpcErrorWithPublic<ErrType, ErrData>\n | RpcErrorWithPrivate<ErrType, ErrData>;\n\n/** Path segment for Map key errors */\nexport type MapKeyPathSegment = {key: unknown; index: number; failed: 'mapKey'};\n\n/** Path segment for Map value errors */\nexport type MapValuePathSegment = {key: unknown; index: number; failed: 'mapVal'};\n\n/** Path segment for Set item errors */\nexport type SetItemPathSegment = {key: unknown; index: number};\n\n/** Any path segment in a RunTypeError path */\nexport type PathSegment = StrNumber | MapKeyPathSegment | MapValuePathSegment | SetItemPathSegment;\n\nexport interface RunTypeError {\n /**\n * Path to the property that failed validation if the validated item was an object class, etc..\n * Index if item that failed validation was in an array.\n * For Maps: contains {key, index, failed: 'mapKey'|'mapVal'} objects.\n * For Sets: contains {key, index} objects.\n * Empty array if validated item was a single property */\n path: PathSegment[];\n /** the type of the expected data */\n expected: string;\n format?: TypeFormatError;\n // typeName?: string; // tyeName can not be included as two types could Have the same typeID and different names\n}\n\n// ########################################### JIT FUNCTIONS ###########################################\n\n/**\n * The argument names of the function to be compiled. The order of properties is important as must the same as the function args.\n * ie: {vλl: 'val', arg1: 'arg1', error: 'newRunTypeErr'} for the function (vλl, arg1, eArr) => any\n */\nexport type JitFnArgs = {\n /** The name of the value of to be */\n vλl: string;\n /** Other argument names */\n [key: string]: string;\n};\n\nexport interface JitCompiledFnData {\n readonly typeName: string;\n /** The id of the function (operation) to be compiled (isType, typeErrors, prepareForJson, restoreFromJson, etc) */\n readonly fnID: string;\n /** Unique id of the function */\n readonly jitFnHash: string;\n /** The names of the arguments of the function */\n readonly args: JitFnArgs;\n /** Default values for the arguments */\n readonly defaultParamValues: JitFnArgs;\n /**\n * This flag is set to true when the result of a jit compilation is a no operation (empty function).\n * if this flag is set to true, the function should not be called as it will not do anything.\n */\n readonly isNoop?: boolean;\n /** Code for the jit function. after the operation has been compiled */\n readonly code: string;\n /** The list of all jit functions that are used by this function and it's children. */\n readonly jitDependencies?: Array<string>;\n /** Pure function dependencies in format \"namespace::fnHash\" */\n readonly pureFnDependencies?: Array<string>;\n /** function param names if the compiled type is function params */\n paramNames?: string[];\n}\n\nexport interface JitCompiledFn<Fn extends AnyFn = AnyFn> extends JitCompiledFnData {\n /** The closure function that contains the jit function, this one contains the context code */\n readonly createJitFn: (utl: JITUtils) => Fn;\n /** The Jit Generated function once the compilation is finished */\n readonly fn: Fn;\n}\n\n/** Jit Functions serialized to src code file, it contains the create jit function\n * but not the actual fn as this one can not be serialized to code.\n */\nexport interface PersistedJitFn extends Omit<JitCompiledFn, 'fn'> {\n /** The Jit Generated function once the compilation is finished */\n readonly fn: undefined;\n}\n\nexport interface JitCompiledFunctions {\n isType: JitCompiledFn<IsTypeFn>;\n typeErrors: JitCompiledFn<TypeErrorsFn>;\n prepareForJson: JitCompiledFn<PrepareForJsonFn>;\n restoreFromJson: JitCompiledFn<RestoreFromJsonFn>;\n stringifyJson: JitCompiledFn<JsonStringifyFn>;\n toBinary?: JitCompiledFn<ToBinaryFn>;\n fromBinary?: JitCompiledFn<FromBinaryFn>;\n}\nexport interface SerializableJITFunctions {\n isType: JitCompiledFnData;\n typeErrors: JitCompiledFnData;\n prepareForJson: JitCompiledFnData;\n restoreFromJson: JitCompiledFnData;\n stringifyJson: JitCompiledFnData;\n toBinary?: JitCompiledFnData;\n fromBinary?: JitCompiledFnData;\n}\nexport interface JitFunctionsHashes {\n isType: string;\n typeErrors: string;\n prepareForJson: string;\n restoreFromJson: string;\n stringifyJson: string;\n toBinary?: string;\n fromBinary?: string;\n}\nexport type JsonStringifyFn = (value: any) => JSONString;\nexport type RestoreFromJsonFn = (value: JSONValue) => any;\nexport type PrepareForJsonFn = (value: any) => JSONValue;\nexport type TypeErrorsFn = (value: any) => RunTypeError[];\nexport type IsTypeFn = (value: any) => boolean;\nexport type ToCodeFn = (value: any) => string;\n/** Binary serialization function - serializes value to the serializer context */\nexport type ToBinaryFn = (value: any, serializer: DataViewSerializer) => void;\n/** Binary deserialization function - deserializes from the deserializer context and returns the value */\nexport type FromBinaryFn = (value: undefined, deserializer: DataViewDeserializer) => any;\n\n// ############################# JIT CACHES ###################################\n\n// jit and pure functions at runtime, contains both createJitFn and fn\nexport type JitFunctionsCache = Record<string, JitCompiledFn>;\n/** Namespaced cache structure for pure functions: { namespace: { fnHash: CompiledPureFunction } } */\nexport type PureFunctionsCache = Record<string, Record<string, CompiledPureFunction>>;\n\n// jit and pure functions persisted to src code, contains createJitFn but not fn\n// this allow usage in environments that can not use eval or new Function()\nexport type PersistedJitFunctionsCache = Record<string, PersistedJitFn>;\n/** Namespaced cache structure for persisted pure functions */\nexport type PersistedPureFunctionsCache = Record<string, Record<string, PersistedPureFunction>>;\n\n// jit and pure functions data, does not contain createJitFn or fn\n// this is used to serialize over the network, but requires using new Function() to restore functionality\nexport type FnsDataCache = Record<string, JitCompiledFnData>;\n/** Namespaced cache structure for pure function data */\nexport type PureFnsDataCache = Record<string, Record<string, PureFunctionData>>;\n\n// ########################################### JIT SRC CODE ####################################\n\nexport interface SrcCodeJitCompiledFn extends JitCompiledFnData {\n /** The closure function that contains the jit function, this one contains the context code */\n readonly createJitFn: (utl: JITUtils) => AnyFn;\n /** The Jit Generated function once the compilation is finished */\n readonly fn: undefined;\n}\nexport interface SrcCodeCompiledPureFunction extends PureFunctionData {\n /** The closure function that contains the pure function, this one contains the context code */\n readonly createPureFn: (utl: JITUtils) => AnyFn;\n /** The Jit Generated function once the compilation is finished */\n readonly fn: undefined;\n}\nexport type SrcCodeJITCompiledFnsCache = Record<string, SrcCodeJitCompiledFn>;\nexport type SrcCodePureFunctionsCache = Record<string, Record<string, SrcCodeCompiledPureFunction>>;\n\n/** Client version of SrcCodeJitCompiledFn - strips unused properties to reduce bundle size */\nexport type ClientSrcCodeJitCompiledFn = Omit<\n SrcCodeJitCompiledFn,\n 'code' | 'args' | 'defaultParamValues' | 'fnID' | 'paramNames'\n>;\n/** Client version of SrcCodeCompiledPureFunction - strips unused properties to reduce bundle size */\nexport type ClientSrcCodeCompiledPureFunction = Omit<SrcCodeCompiledPureFunction, 'code' | 'paramNames'>;\nexport type ClientSrcCodeJITCompiledFnsCache = Record<string, ClientSrcCodeJitCompiledFn>;\nexport type ClientSrcCodePureFunctionsCache = Record<string, Record<string, ClientSrcCodeCompiledPureFunction>>;\n\n// ########################################## other #########################################\n\nexport type StrNumber = string | number;\nexport type AnyFn = (...args: any[]) => any;\nexport type AnyObject = Record<string, unknown>;\nexport interface AnyClass<T = any> {\n new (...args: any[]): T;\n}\n\nexport interface SerializableClass<T = any> {\n new (): T;\n}\n\nexport type DeserializeClassFn<C extends InstanceType<AnyClass>> = (deserialized: DataOnly<C>) => C;\n\nexport type Mutable<T> = {\n -readonly [P in keyof T]: T[P];\n};\n\nexport type Prettify<T> = {\n [P in keyof T]: T[P];\n} & {};\n\n// StrNumber is already defined at the top of the file\nexport type JSONValue = StrNumber | boolean | null | {[key: string]: JSONValue} | Array<JSONValue>;\nexport type JSONString = string;\n\n// prettier-ignore\ntype Native = Date | RegExp | URL | URLSearchParams | Blob | File | FileList | FormData | ArrayBuffer | SharedArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;\n\n/** Typescript mapping type that stripes methods and only keep properties.\n * it takes into account, dates, objects, classes, arrays, maps and sets.\n */\nexport type DataOnly<T> = T extends object\n ? T extends Native\n ? T\n : T extends Function\n ? never\n : T extends new (...args: any[]) => any\n ? never\n : T extends Array<infer U>\n ? Array<DataOnly<U>>\n : T extends Map<infer K, infer V>\n ? Map<DataOnly<K>, DataOnly<V>>\n : T extends Set<infer U>\n ? Set<DataOnly<U>>\n : {[K in keyof T as T[K] extends Function ? never : K]: DataOnly<T[K]>}\n : T;\n\n// TEST TYPES FOR PlainObject\n\n// class A {\n// n1?: number;\n// s?: string;\n// d?: Date;\n// map?: Map<string, RegExp>;\n// set?: Set<URL>;\n// arr?: A[];\n// method() {\n// return 'hello';\n// }\n// arrow = () => 'hello';\n// }\n\n// type PlainInterface = PlainObject<{\n// n1: number;\n// s: string;\n// d: Date;\n// a: A;\n// map: Map<string, A>;\n// set: Set<A>;\n// arr: A[];\n// method(): string;\n// arrow: () => string;\n// }>;\n\n// type PlainClass = PlainObject<A>;\n// type PlainSet = PlainObject<Set<A>>;\n// type PlainMap = PlainObject<Map<string, A>>;\n\n// ################# BINARY SERIALIZATION - IMPORTANT NOTE ##################################\n// DO NOT CHANGE THE INTERFACE NAMES AS THEY ARE HARDCODED IN THE JIT GENERATED CODE\n// ##########################################################################################\n\nexport type StrictArrayBuffer = ArrayBuffer & {buffer?: undefined};\n/** Input type for binary deserialization - accepts ArrayBuffer or any typed array view (including Node.js Buffer) */\nexport type BinaryInput = ArrayBuffer | ArrayBufferView;\nexport interface DataViewSerializer {\n index: number; // byte offset\n view: DataView;\n reset: () => void;\n getBuffer: () => StrictArrayBuffer;\n getBufferView: () => Uint8Array;\n markAsEnded: () => void;\n getLength(): number;\n // serialization functions\n serString(str: string): void;\n serFloat64(n: number): void;\n serEnum(n: number | string): void;\n setBitMask(bitMaskIndex: number, bitIndex: number): void;\n}\n\nexport interface DataViewDeserializer {\n index: number; // byte offset\n view: DataView;\n reset: () => void;\n setBuffer: (buffer: StrictArrayBuffer, byteOffset?: number, byteLength?: number) => void;\n markAsEnded: () => void;\n getLength(): number;\n // deserialization functions\n desString(): string;\n desFloat64(): number;\n desEnum(): number | string;\n}\n\nexport type MimeTypes = (typeof MIME_TYPES)[keyof typeof MIME_TYPES];\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAeO,MAAM,kBAAkB;AAAA;AAAA,EAE3B,MAAM;AAAA;AAAA,EAEN,QAAQ;AAAA;AAAA,EAER,eAAe;AAAA;AAAA,EAEf,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -6,6 +6,7 @@ export declare const SerializerModes: {
6
6
  readonly json: 1;
7
7
  readonly binary: 2;
8
8
  readonly stringifyJson: 3;
9
+ readonly optimistic: 4;
9
10
  };
10
11
  export type SerializerMode = keyof typeof SerializerModes;
11
12
  export type SerializerCode = (typeof SerializerModes)[SerializerMode];
@@ -73,8 +74,8 @@ export interface JitCompiledFnData {
73
74
  readonly defaultParamValues: JitFnArgs;
74
75
  readonly isNoop?: boolean;
75
76
  readonly code: string;
76
- readonly jitDependencies: Array<string>;
77
- readonly pureFnDependencies: Array<string>;
77
+ readonly jitDependencies?: Array<string>;
78
+ readonly pureFnDependencies?: Array<string>;
78
79
  paramNames?: string[];
79
80
  }
80
81
  export interface JitCompiledFn<Fn extends AnyFn = AnyFn> extends JitCompiledFnData {
@@ -90,8 +91,8 @@ export interface JitCompiledFunctions {
90
91
  prepareForJson: JitCompiledFn<PrepareForJsonFn>;
91
92
  restoreFromJson: JitCompiledFn<RestoreFromJsonFn>;
92
93
  stringifyJson: JitCompiledFn<JsonStringifyFn>;
93
- toBinary: JitCompiledFn<ToBinaryFn>;
94
- fromBinary: JitCompiledFn<FromBinaryFn>;
94
+ toBinary?: JitCompiledFn<ToBinaryFn>;
95
+ fromBinary?: JitCompiledFn<FromBinaryFn>;
95
96
  }
96
97
  export interface SerializableJITFunctions {
97
98
  isType: JitCompiledFnData;
@@ -99,8 +100,8 @@ export interface SerializableJITFunctions {
99
100
  prepareForJson: JitCompiledFnData;
100
101
  restoreFromJson: JitCompiledFnData;
101
102
  stringifyJson: JitCompiledFnData;
102
- toBinary: JitCompiledFnData;
103
- fromBinary: JitCompiledFnData;
103
+ toBinary?: JitCompiledFnData;
104
+ fromBinary?: JitCompiledFnData;
104
105
  }
105
106
  export interface JitFunctionsHashes {
106
107
  isType: string;
@@ -108,8 +109,8 @@ export interface JitFunctionsHashes {
108
109
  prepareForJson: string;
109
110
  restoreFromJson: string;
110
111
  stringifyJson: string;
111
- toBinary: string;
112
- fromBinary: string;
112
+ toBinary?: string;
113
+ fromBinary?: string;
113
114
  }
114
115
  export type JsonStringifyFn = (value: any) => JSONString;
115
116
  export type RestoreFromJsonFn = (value: JSONValue) => any;
@@ -135,6 +136,10 @@ export interface SrcCodeCompiledPureFunction extends PureFunctionData {
135
136
  }
136
137
  export type SrcCodeJITCompiledFnsCache = Record<string, SrcCodeJitCompiledFn>;
137
138
  export type SrcCodePureFunctionsCache = Record<string, Record<string, SrcCodeCompiledPureFunction>>;
139
+ export type ClientSrcCodeJitCompiledFn = Omit<SrcCodeJitCompiledFn, 'code' | 'args' | 'defaultParamValues' | 'fnID' | 'paramNames'>;
140
+ export type ClientSrcCodeCompiledPureFunction = Omit<SrcCodeCompiledPureFunction, 'code' | 'paramNames'>;
141
+ export type ClientSrcCodeJITCompiledFnsCache = Record<string, ClientSrcCodeJitCompiledFn>;
142
+ export type ClientSrcCodePureFunctionsCache = Record<string, Record<string, ClientSrcCodeCompiledPureFunction>>;
138
143
  export type StrNumber = string | number;
139
144
  export type AnyFn = (...args: any[]) => any;
140
145
  export type AnyObject = Record<string, unknown>;
@@ -228,6 +233,10 @@ export declare type __ΩSrcCodeJitCompiledFn = any[];
228
233
  export declare type __ΩSrcCodeCompiledPureFunction = any[];
229
234
  export declare type __ΩSrcCodeJITCompiledFnsCache = any[];
230
235
  export declare type __ΩSrcCodePureFunctionsCache = any[];
236
+ export declare type __ΩClientSrcCodeJitCompiledFn = any[];
237
+ export declare type __ΩClientSrcCodeCompiledPureFunction = any[];
238
+ export declare type __ΩClientSrcCodeJITCompiledFnsCache = any[];
239
+ export declare type __ΩClientSrcCodePureFunctionsCache = any[];
231
240
  export declare type __ΩStrNumber = any[];
232
241
  export declare type __ΩAnyFn = any[];
233
242
  export declare type __ΩAnyObject = any[];
@@ -11,7 +11,7 @@ const __ΩGenericPureFunction = ["P", "val", "formatParams", () => __ΩPureFunct
11
11
  const __ΩErrorsPureFunction = ["P", "val", () => __ΩStrNumber, "pλth", () => src_types_general_types.__ΩRunTypeError, "εrr", "expected", "formatName", "formatParams", () => __ΩStrNumber, "formatPath", () => __ΩPureFunctionDeps, "deps", () => __ΩStrNumber, "accessPath", () => __ΩStrNumber, "fmtAccessPath", () => src_types_general_types.__ΩRunTypeError, "", "ErrorsPureFunction", `b!P"2"n#F2$n%F2&&2'&2(e"!2)n*F2+n,2-n.F2/8n0F218n2F/3w4y`];
12
12
  const __ΩPureFunction = ["args", "", "PureFunction", 'P"@2!"/"w#y'];
13
13
  const __ΩPureFunctionFactory = ["JITUtils", "jitUtils", () => __ΩPureFunction, "", "PureFunctionFactory", 'P"w!2"n#/$w%y'];
14
- const __ΩPureFunctionData = ["namespace", "paramNames", "code", "fnName", "bodyHash", "pureFnDependencies", "PureFunctionData", `P&4!9&F4"9&4#9&4$9&4%9&F4&9Mw'y`];
14
+ const __ΩPureFunctionData = ["namespace", "paramNames", "code", "fnName", "bodyHash", "pureFnDependencies", "PureFunctionData", `P&4!9&F4"9&4#9&4$9&4%9&F4&89Mw'y`];
15
15
  const __ΩCompiledPureFunction = [() => __ΩPureFunctionData, () => __ΩPureFunctionFactory, "createPureFn", () => __ΩPureFunction, "fn", "CompiledPureFunction", 'Pn!n"4#n$4%8Mw&y'];
16
16
  const __ΩPersistedPureFunction = [() => __ΩCompiledPureFunction, "fn", "PersistedPureFunction", 'Pn!-4"Mw#y'];
17
17
  const __ΩPureFnDef = ["args", "", "F", "namespace", "fnName", "isFactory", "pureFn", "PureFnDef", `P"@2!"/"c#P&4$89&4%89)4&8e"!4'9Mw(y`];
@@ -13,7 +13,7 @@ export interface PureFunctionData {
13
13
  readonly code: string;
14
14
  readonly fnName: string;
15
15
  readonly bodyHash: string;
16
- readonly pureFnDependencies: Array<string>;
16
+ readonly pureFnDependencies?: Array<string>;
17
17
  }
18
18
  export interface CompiledPureFunction extends PureFunctionData {
19
19
  createPureFn: PureFunctionFactory;
@@ -1,4 +1,4 @@
1
- import { SerializerModes, __ΩAnyClass, __ΩAnyErrorParams, __ΩAnyFn, __ΩAnyObject, __ΩBinaryInput, __ΩCoreRouterOptions, __ΩDataOnly, __ΩDataViewDeserializer, __ΩDataViewSerializer, __ΩDeserializeClassFn, __ΩFnsDataCache, __ΩFromBinaryFn, __ΩIsTypeFn, __ΩJSONString, __ΩJSONValue, __ΩJitCompiledFn, __ΩJitCompiledFnData, __ΩJitCompiledFunctions, __ΩJitFnArgs, __ΩJitFunctionsCache, __ΩJitFunctionsHashes, __ΩJsonStringifyFn, __ΩMapKeyPathSegment, __ΩMapValuePathSegment, __ΩMimeTypes, __ΩMutable, __ΩPathSegment, __ΩPersistedJitFn, __ΩPersistedJitFunctionsCache, __ΩPersistedPureFunctionsCache, __ΩPrepareForJsonFn, __ΩPrettify, __ΩPublicRpcError, __ΩPureFnsDataCache, __ΩPureFunctionsCache, __ΩRestoreFromJsonFn, __ΩRpcErrorParams, __ΩRpcErrorWithPrivate, __ΩRpcErrorWithPublic, __ΩRunTypeError, __ΩSerializableClass, __ΩSerializableJITFunctions, __ΩSerializerCode, __ΩSerializerMode, __ΩSetItemPathSegment, __ΩSrcCodeCompiledPureFunction, __ΩSrcCodeJITCompiledFnsCache, __ΩSrcCodeJitCompiledFn, __ΩSrcCodePureFunctionsCache, __ΩStrNumber, __ΩStrictArrayBuffer, __ΩToBinaryFn, __ΩToCodeFn, __ΩTypeErrorsFn, __ΩTypedErrorParams } from "./src/types/general.types.js";
1
+ import { SerializerModes, __ΩAnyClass, __ΩAnyErrorParams, __ΩAnyFn, __ΩAnyObject, __ΩBinaryInput, __ΩClientSrcCodeCompiledPureFunction, __ΩClientSrcCodeJITCompiledFnsCache, __ΩClientSrcCodeJitCompiledFn, __ΩClientSrcCodePureFunctionsCache, __ΩCoreRouterOptions, __ΩDataOnly, __ΩDataViewDeserializer, __ΩDataViewSerializer, __ΩDeserializeClassFn, __ΩFnsDataCache, __ΩFromBinaryFn, __ΩIsTypeFn, __ΩJSONString, __ΩJSONValue, __ΩJitCompiledFn, __ΩJitCompiledFnData, __ΩJitCompiledFunctions, __ΩJitFnArgs, __ΩJitFunctionsCache, __ΩJitFunctionsHashes, __ΩJsonStringifyFn, __ΩMapKeyPathSegment, __ΩMapValuePathSegment, __ΩMimeTypes, __ΩMutable, __ΩPathSegment, __ΩPersistedJitFn, __ΩPersistedJitFunctionsCache, __ΩPersistedPureFunctionsCache, __ΩPrepareForJsonFn, __ΩPrettify, __ΩPublicRpcError, __ΩPureFnsDataCache, __ΩPureFunctionsCache, __ΩRestoreFromJsonFn, __ΩRpcErrorParams, __ΩRpcErrorWithPrivate, __ΩRpcErrorWithPublic, __ΩRunTypeError, __ΩSerializableClass, __ΩSerializableJITFunctions, __ΩSerializerCode, __ΩSerializerMode, __ΩSetItemPathSegment, __ΩSrcCodeCompiledPureFunction, __ΩSrcCodeJITCompiledFnsCache, __ΩSrcCodeJitCompiledFn, __ΩSrcCodePureFunctionsCache, __ΩStrNumber, __ΩStrictArrayBuffer, __ΩToBinaryFn, __ΩToCodeFn, __ΩTypeErrorsFn, __ΩTypedErrorParams } from "./src/types/general.types.js";
2
2
  import { __ΩHeadersMetaData, __ΩHeadersMethodWithJitFns, __ΩMethodMetadata, __ΩMethodWithJitFns, __ΩMethodWithOptions, __ΩMethodWithOptsAndJitFns, __ΩMethodsCache, __ΩRemoteMethodOpts, __ΩRouteOnlyOptions, __ΩSerializableMethodsData } from "./src/types/method.types.js";
3
3
  import { __ΩCompiledPureFunction, __ΩErrorsPureFunction, __ΩGenericPureFunction, __ΩMapFromRef, __ΩMapFromServerFnRef, __ΩParsedFactoryFn, __ΩPersistedPureFunction, __ΩPureFnDef, __ΩPureFunction, __ΩPureFunctionData, __ΩPureFunctionDeps, __ΩPureFunctionFactory, __ΩPureServerFnRef, __ΩRoutesFlowMapping, __ΩRoutesFlowQuery } from "./src/types/pureFunctions.types.js";
4
4
  import { __ΩAliasTypeAnnotation, __ΩAliasTypeFormat, __ΩExtractFormatParams, __ΩFormatParam, __ΩFormatParamLiteral, __ΩFormatParamMeta, __ΩTypeFormatError, __ΩTypeFormatParams, __ΩTypeFormatParsedParams, __ΩTypeFormatPrimitives, __ΩTypeFormatValue } from "./src/types/formats/formats.types.js";
@@ -68,6 +68,10 @@ export {
68
68
  __ΩBrandUInt8,
69
69
  __ΩBrandUUID,
70
70
  __ΩBrandUrl,
71
+ __ΩClientSrcCodeCompiledPureFunction,
72
+ __ΩClientSrcCodeJITCompiledFnsCache,
73
+ __ΩClientSrcCodeJitCompiledFn,
74
+ __ΩClientSrcCodePureFunctionsCache,
71
75
  __ΩCompiledPureFunction,
72
76
  __ΩCoreRouterOptions,
73
77
  __ΩDataOnly,
@@ -36,6 +36,11 @@ function deserializeBinaryBody(path, buffer, isResponse) {
36
36
  }
37
37
  function deserializeMethod(key, method, deserializer, isResponse) {
38
38
  const jitFns = isResponse ? method.returnJitFns : method.paramsJitFns;
39
+ if (!jitFns.fromBinary?.fn)
40
+ throw new RpcError({
41
+ type: "missing-fromBinary-jit-fn",
42
+ publicMessage: `Missing fromBinary JIT function for method ${key}`
43
+ });
39
44
  try {
40
45
  return jitFns.fromBinary.fn(void 0, deserializer);
41
46
  } catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"bodyDeserializer.js","sources":["../../../../src/binary/bodyDeserializer.ts"],"sourcesContent":["import {createDataViewDeserializer} from './dataView.ts';\nimport {StatusCodes} from '../constants.ts';\nimport {RpcError} from '../errors.ts';\nimport type {BinaryInput, DataViewDeserializer} from '../types/general.types.ts';\nimport type {MethodWithJitFns} from '../types/method.types.ts';\nimport {routesCache} from '../routerUtils.ts';\n\n/**\n * Deserializes API body from binary format using JIT-compiled deserialization functions.\n * Reads the binary buffer and reconstructs the body record.\n * Method metadata is looked up from routesCache automatically.\n */\nexport function deserializeBinaryBody(\n path: string,\n buffer: BinaryInput,\n /** If true, the body is a response body, otherwise it's a request body */\n isResponse: boolean\n): {\n deserializer: DataViewDeserializer;\n body: Record<string, any>;\n} {\n try {\n // Create deserializer from buffer\n const deserializer = createDataViewDeserializer(path, buffer);\n const body: Record<string, any> = {};\n\n // Read items length from first 32 bits\n const itemsLength = deserializer.view.getUint32(0, true);\n deserializer.index += 4;\n\n // Deserialize each item\n for (let i = 0; i < itemsLength; i++) {\n // Deserialize key (method id)\n const key = deserializer.desString();\n\n // Find the corresponding method from routesCache\n const method = routesCache.getMethodJitFns(key);\n if (!method) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse\n ? 'binary-response-method-Deserialization-error'\n : 'binary-request-method-Deserialization-error',\n publicMessage: `Unknown method key in binary body: ${key}`,\n errorData: {methodId: key},\n });\n }\n\n // Deserialize value using the appropriate JIT function\n const value = deserializeMethod(key, method, deserializer, isResponse);\n body[key] = value;\n }\n\n deserializer.markAsEnded();\n return {deserializer, body};\n } catch (err: any) {\n if (err instanceof RpcError) throw err;\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse ? 'binary-response-Deserialize-error' : 'binary-request-Deserialization-error',\n publicMessage: `Failed to deserialize body from binary: ${err?.message || 'unknown error'}`,\n originalError: err,\n });\n }\n}\n\n/** Deserializes a single method's value from binary format */\nfunction deserializeMethod(key: string, method: MethodWithJitFns, deserializer: DataViewDeserializer, isResponse: boolean): any {\n const jitFns = isResponse ? method.returnJitFns : method.paramsJitFns;\n try {\n return jitFns.fromBinary.fn(undefined, deserializer);\n } catch (e: any) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse ? 'binary-response-method-Deserialization-error' : 'binary-request-method-Deserialization-error',\n publicMessage: `Failed to deserialize method ${key} from binary`,\n originalError: e,\n errorData: {methodId: key},\n });\n }\n}\n"],"names":[],"mappings":";;;;AAYO,SAAS,sBACZ,MACA,QAEA,YAIF;AACE,MAAI;AAEA,UAAM,eAAe,2BAA2B,MAAM,MAAM;AAC5D,UAAM,OAA4B,CAAA;AAGlC,UAAM,cAAc,aAAa,KAAK,UAAU,GAAG,IAAI;AACvD,iBAAa,SAAS;AAGtB,aAAS,IAAI,GAAG,IAAI,aAAa,KAAK;AAElC,YAAM,MAAM,aAAa,UAAA;AAGzB,YAAM,SAAS,YAAY,gBAAgB,GAAG;AAC9C,UAAI,CAAC,QAAQ;AACT,cAAM,IAAI,SAAS;AAAA,UACf,YAAY,YAAY;AAAA,UACxB,MAAM,aACA,iDACA;AAAA,UACN,eAAe,sCAAsC,GAAG;AAAA,UACxD,WAAW,EAAC,UAAU,IAAA;AAAA,QAAG,CAC5B;AAAA,MACL;AAGA,YAAM,QAAQ,kBAAkB,KAAK,QAAQ,cAAc,UAAU;AACrE,WAAK,GAAG,IAAI;AAAA,IAChB;AAEA,iBAAa,YAAA;AACb,WAAO,EAAC,cAAc,KAAA;AAAA,EAC1B,SAAS,KAAU;AACf,QAAI,eAAe,SAAU,OAAM;AACnC,UAAM,IAAI,SAAS;AAAA,MACf,YAAY,YAAY;AAAA,MACxB,MAAM,aAAa,sCAAsC;AAAA,MACzD,eAAe,2CAA2C,KAAK,WAAW,eAAe;AAAA,MACzF,eAAe;AAAA,IAAA,CAClB;AAAA,EACL;AACJ;AAGA,SAAS,kBAAkB,KAAa,QAA0B,cAAoC,YAA0B;AAC5H,QAAM,SAAS,aAAa,OAAO,eAAe,OAAO;AACzD,MAAI;AACA,WAAO,OAAO,WAAW,GAAG,QAAW,YAAY;AAAA,EACvD,SAAS,GAAQ;AACb,UAAM,IAAI,SAAS;AAAA,MACf,YAAY,YAAY;AAAA,MACxB,MAAM,aAAa,iDAAiD;AAAA,MACpE,eAAe,gCAAgC,GAAG;AAAA,MAClD,eAAe;AAAA,MACf,WAAW,EAAC,UAAU,IAAA;AAAA,IAAG,CAC5B;AAAA,EACL;AACJ;"}
1
+ {"version":3,"file":"bodyDeserializer.js","sources":["../../../../src/binary/bodyDeserializer.ts"],"sourcesContent":["import {createDataViewDeserializer} from './dataView.ts';\nimport {StatusCodes} from '../constants.ts';\nimport {RpcError} from '../errors.ts';\nimport type {BinaryInput, DataViewDeserializer} from '../types/general.types.ts';\nimport type {MethodWithJitFns} from '../types/method.types.ts';\nimport {routesCache} from '../routerUtils.ts';\n\n/**\n * Deserializes API body from binary format using JIT-compiled deserialization functions.\n * Reads the binary buffer and reconstructs the body record.\n * Method metadata is looked up from routesCache automatically.\n */\nexport function deserializeBinaryBody(\n path: string,\n buffer: BinaryInput,\n /** If true, the body is a response body, otherwise it's a request body */\n isResponse: boolean\n): {\n deserializer: DataViewDeserializer;\n body: Record<string, any>;\n} {\n try {\n // Create deserializer from buffer\n const deserializer = createDataViewDeserializer(path, buffer);\n const body: Record<string, any> = {};\n\n // Read items length from first 32 bits\n const itemsLength = deserializer.view.getUint32(0, true);\n deserializer.index += 4;\n\n // Deserialize each item\n for (let i = 0; i < itemsLength; i++) {\n // Deserialize key (method id)\n const key = deserializer.desString();\n\n // Find the corresponding method from routesCache\n const method = routesCache.getMethodJitFns(key);\n if (!method) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse\n ? 'binary-response-method-Deserialization-error'\n : 'binary-request-method-Deserialization-error',\n publicMessage: `Unknown method key in binary body: ${key}`,\n errorData: {methodId: key},\n });\n }\n\n // Deserialize value using the appropriate JIT function\n const value = deserializeMethod(key, method, deserializer, isResponse);\n body[key] = value;\n }\n\n deserializer.markAsEnded();\n return {deserializer, body};\n } catch (err: any) {\n if (err instanceof RpcError) throw err;\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse ? 'binary-response-Deserialize-error' : 'binary-request-Deserialization-error',\n publicMessage: `Failed to deserialize body from binary: ${err?.message || 'unknown error'}`,\n originalError: err,\n });\n }\n}\n\n/** Deserializes a single method's value from binary format */\nfunction deserializeMethod(key: string, method: MethodWithJitFns, deserializer: DataViewDeserializer, isResponse: boolean): any {\n const jitFns = isResponse ? method.returnJitFns : method.paramsJitFns;\n if (!jitFns.fromBinary?.fn)\n throw new RpcError({\n type: 'missing-fromBinary-jit-fn',\n publicMessage: `Missing fromBinary JIT function for method ${key}`,\n });\n try {\n return jitFns.fromBinary.fn(undefined, deserializer);\n } catch (e: any) {\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse ? 'binary-response-method-Deserialization-error' : 'binary-request-method-Deserialization-error',\n publicMessage: `Failed to deserialize method ${key} from binary`,\n originalError: e,\n errorData: {methodId: key},\n });\n }\n}\n"],"names":[],"mappings":";;;;AAYO,SAAS,sBACZ,MACA,QAEA,YAIF;AACE,MAAI;AAEA,UAAM,eAAe,2BAA2B,MAAM,MAAM;AAC5D,UAAM,OAA4B,CAAA;AAGlC,UAAM,cAAc,aAAa,KAAK,UAAU,GAAG,IAAI;AACvD,iBAAa,SAAS;AAGtB,aAAS,IAAI,GAAG,IAAI,aAAa,KAAK;AAElC,YAAM,MAAM,aAAa,UAAA;AAGzB,YAAM,SAAS,YAAY,gBAAgB,GAAG;AAC9C,UAAI,CAAC,QAAQ;AACT,cAAM,IAAI,SAAS;AAAA,UACf,YAAY,YAAY;AAAA,UACxB,MAAM,aACA,iDACA;AAAA,UACN,eAAe,sCAAsC,GAAG;AAAA,UACxD,WAAW,EAAC,UAAU,IAAA;AAAA,QAAG,CAC5B;AAAA,MACL;AAGA,YAAM,QAAQ,kBAAkB,KAAK,QAAQ,cAAc,UAAU;AACrE,WAAK,GAAG,IAAI;AAAA,IAChB;AAEA,iBAAa,YAAA;AACb,WAAO,EAAC,cAAc,KAAA;AAAA,EAC1B,SAAS,KAAU;AACf,QAAI,eAAe,SAAU,OAAM;AACnC,UAAM,IAAI,SAAS;AAAA,MACf,YAAY,YAAY;AAAA,MACxB,MAAM,aAAa,sCAAsC;AAAA,MACzD,eAAe,2CAA2C,KAAK,WAAW,eAAe;AAAA,MACzF,eAAe;AAAA,IAAA,CAClB;AAAA,EACL;AACJ;AAGA,SAAS,kBAAkB,KAAa,QAA0B,cAAoC,YAA0B;AAC5H,QAAM,SAAS,aAAa,OAAO,eAAe,OAAO;AACzD,MAAI,CAAC,OAAO,YAAY;AACpB,UAAM,IAAI,SAAS;AAAA,MACf,MAAM;AAAA,MACN,eAAe,8CAA8C,GAAG;AAAA,IAAA,CACnE;AACL,MAAI;AACA,WAAO,OAAO,WAAW,GAAG,QAAW,YAAY;AAAA,EACvD,SAAS,GAAQ;AACb,UAAM,IAAI,SAAS;AAAA,MACf,YAAY,YAAY;AAAA,MACxB,MAAM,aAAa,iDAAiD;AAAA,MACpE,eAAe,gCAAgC,GAAG;AAAA,MAClD,eAAe;AAAA,MACf,WAAW,EAAC,UAAU,IAAA;AAAA,IAAG,CAC5B;AAAA,EACL;AACJ;"}
@@ -30,12 +30,7 @@ function serializeBinaryBody(path, executionChain, body, isResponse, workflowRou
30
30
  }
31
31
  function serializeMethod(key, method, value, serializer, isResponse) {
32
32
  const toBinary = isResponse ? method.returnJitFns.toBinary : method.paramsJitFns.toBinary;
33
- if (!toBinary?.fn)
34
- throw new RpcError({
35
- type: "missing-toBinary-jit-fn",
36
- publicMessage: `Missing toBinary JIT function for method ${method.id}`
37
- });
38
- if (toBinary.isNoop) return false;
33
+ if (!toBinary?.fn || toBinary.isNoop) return false;
39
34
  if (key === MION_ROUTES.thrownErrors) return false;
40
35
  if (isResponse && (!method.hasReturnData || typeof value === "undefined")) return false;
41
36
  if (!isResponse && typeof value === "undefined") return false;
@@ -1 +1 @@
1
- {"version":3,"file":"bodySerializer.js","sources":["../../../../src/binary/bodySerializer.ts"],"sourcesContent":["import {createDataViewSerializer} from './dataView.ts';\nimport {MION_ROUTES, StatusCodes} from '../constants.ts';\nimport {RpcError} from '../errors.ts';\nimport type {DataViewSerializer} from '../types/general.types.ts';\nimport type {MethodWithJitFns} from '../types/method.types.ts';\n\n/**\n * Serializes API body to binary format using JIT-compiled serialization functions.\n * Combines the results of all body methods into a single binary buffer.\n *\n * Note: This function assumes all methods in executionChain have valid JIT functions.\n * Methods with noop JIT functions or undefined values should be filtered out before calling this function,\n * or handled by the caller. Any serialization errors will be thrown as RpcError.\n *\n */\nexport function serializeBinaryBody(\n path: string,\n executionChain: MethodWithJitFns[],\n body: Record<string, any>,\n isResponse: boolean,\n workflowRouteIds?: string[]\n): {\n serializer: DataViewSerializer;\n buffer: ReturnType<DataViewSerializer['getBuffer']>;\n} {\n try {\n const serializer = createDataViewSerializer(path, workflowRouteIds);\n\n // Reserve space for items length at index 0 (will be written after counting)\n const itemsLengthIndex = serializer.index;\n serializer.index += 4;\n\n let itemsLength = 0;\n // serialize each method's value (return value for responses, params for requests)\n for (let i = 0; i < executionChain.length; i++) {\n const method = executionChain[i];\n const key = method.id;\n const value = body[key];\n if (serializeMethod(key, method, value, serializer, isResponse)) {\n itemsLength++;\n }\n }\n // Write items length at reserved index 0\n serializer.view.setUint32(itemsLengthIndex, itemsLength, true);\n serializer.markAsEnded();\n\n return {serializer, buffer: serializer.getBuffer()};\n } catch (err: any) {\n if (err instanceof RpcError) throw err;\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse ? 'binary-response-Serialization-error' : 'binary-request-Serialization-error',\n publicMessage: `Failed to serialize body to binary: ${err?.message || 'unknown error'}`,\n originalError: err,\n });\n }\n}\n\n/**\n * Serializes a single method's value to binary format.\n * Returns true if the method was serialized, false if it was skipped.\n */\nfunction serializeMethod(\n key: string,\n method: MethodWithJitFns,\n value: any,\n serializer: DataViewSerializer,\n isResponse: boolean\n): boolean {\n const toBinary = isResponse ? method.returnJitFns.toBinary : method.paramsJitFns.toBinary;\n if (!toBinary?.fn)\n throw new RpcError({\n type: 'missing-toBinary-jit-fn',\n publicMessage: `Missing toBinary JIT function for method ${method.id}`,\n });\n if (toBinary.isNoop) return false;\n // skip @thrownErrors - should be handled separately by the caller if needed\n if (key === MION_ROUTES.thrownErrors) return false;\n // skip methods without return data or undefined values (for responses)\n if (isResponse && (!method.hasReturnData || typeof value === 'undefined')) return false;\n // skip methods with no params (for requests) or noop serialization\n if (!isResponse && typeof value === 'undefined') return false;\n // serialize key\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,OAAO,UAAU;AAC7B,SAAO;AACX;"}
1
+ {"version":3,"file":"bodySerializer.js","sources":["../../../../src/binary/bodySerializer.ts"],"sourcesContent":["import {createDataViewSerializer} from './dataView.ts';\nimport {MION_ROUTES, StatusCodes} from '../constants.ts';\nimport {RpcError} from '../errors.ts';\nimport type {DataViewSerializer} from '../types/general.types.ts';\nimport type {MethodWithJitFns} from '../types/method.types.ts';\n\n/**\n * Serializes API body to binary format using JIT-compiled serialization functions.\n * Combines the results of all body methods into a single binary buffer.\n *\n * Note: This function assumes all methods in executionChain have valid JIT functions.\n * Methods with noop JIT functions or undefined values should be filtered out before calling this function,\n * or handled by the caller. Any serialization errors will be thrown as RpcError.\n *\n */\nexport function serializeBinaryBody(\n path: string,\n executionChain: MethodWithJitFns[],\n body: Record<string, any>,\n isResponse: boolean,\n workflowRouteIds?: string[]\n): {\n serializer: DataViewSerializer;\n buffer: ReturnType<DataViewSerializer['getBuffer']>;\n} {\n try {\n const serializer = createDataViewSerializer(path, workflowRouteIds);\n\n // Reserve space for items length at index 0 (will be written after counting)\n const itemsLengthIndex = serializer.index;\n serializer.index += 4;\n\n let itemsLength = 0;\n // serialize each method's value (return value for responses, params for requests)\n for (let i = 0; i < executionChain.length; i++) {\n const method = executionChain[i];\n const key = method.id;\n const value = body[key];\n if (serializeMethod(key, method, value, serializer, isResponse)) {\n itemsLength++;\n }\n }\n // Write items length at reserved index 0\n serializer.view.setUint32(itemsLengthIndex, itemsLength, true);\n serializer.markAsEnded();\n\n return {serializer, buffer: serializer.getBuffer()};\n } catch (err: any) {\n if (err instanceof RpcError) throw err;\n throw new RpcError({\n statusCode: StatusCodes.UNEXPECTED_ERROR,\n type: isResponse ? 'binary-response-Serialization-error' : 'binary-request-Serialization-error',\n publicMessage: `Failed to serialize body to binary: ${err?.message || 'unknown error'}`,\n originalError: err,\n });\n }\n}\n\n/**\n * Serializes a single method's value to binary format.\n * Returns true if the method was serialized, false if it was skipped.\n */\nfunction serializeMethod(\n key: string,\n method: MethodWithJitFns,\n value: any,\n serializer: DataViewSerializer,\n isResponse: boolean\n): boolean {\n const toBinary = isResponse ? method.returnJitFns.toBinary : method.paramsJitFns.toBinary;\n if (!toBinary?.fn || toBinary.isNoop) return false;\n // skip @thrownErrors - should be handled separately by the caller if needed\n if (key === MION_ROUTES.thrownErrors) return false;\n // skip methods without return data or undefined values (for responses)\n if (isResponse && (!method.hasReturnData || typeof value === 'undefined')) return false;\n // skip methods with no params (for requests) or noop serialization\n if (!isResponse && typeof value === 'undefined') return false;\n // serialize key\n serializer.serString(key);\n // serialize value\n toBinary.fn(value, serializer);\n return true;\n}\n"],"names":[],"mappings":";;;AAeO,SAAS,oBACZ,MACA,gBACA,MACA,YACA,kBAIF;AACE,MAAI;AACA,UAAM,aAAa,yBAAyB,MAAM,gBAAgB;AAGlE,UAAM,mBAAmB,WAAW;AACpC,eAAW,SAAS;AAEpB,QAAI,cAAc;AAElB,aAAS,IAAI,GAAG,IAAI,eAAe,QAAQ,KAAK;AAC5C,YAAM,SAAS,eAAe,CAAC;AAC/B,YAAM,MAAM,OAAO;AACnB,YAAM,QAAQ,KAAK,GAAG;AACtB,UAAI,gBAAgB,KAAK,QAAQ,OAAO,YAAY,UAAU,GAAG;AAC7D;AAAA,MACJ;AAAA,IACJ;AAEA,eAAW,KAAK,UAAU,kBAAkB,aAAa,IAAI;AAC7D,eAAW,YAAA;AAEX,WAAO,EAAC,YAAY,QAAQ,WAAW,YAAU;AAAA,EACrD,SAAS,KAAU;AACf,QAAI,eAAe,SAAU,OAAM;AACnC,UAAM,IAAI,SAAS;AAAA,MACf,YAAY,YAAY;AAAA,MACxB,MAAM,aAAa,wCAAwC;AAAA,MAC3D,eAAe,uCAAuC,KAAK,WAAW,eAAe;AAAA,MACrF,eAAe;AAAA,IAAA,CAClB;AAAA,EACL;AACJ;AAMA,SAAS,gBACL,KACA,QACA,OACA,YACA,YACO;AACP,QAAM,WAAW,aAAa,OAAO,aAAa,WAAW,OAAO,aAAa;AACjF,MAAI,CAAC,UAAU,MAAM,SAAS,OAAQ,QAAO;AAE7C,MAAI,QAAQ,YAAY,aAAc,QAAO;AAE7C,MAAI,eAAe,CAAC,OAAO,iBAAiB,OAAO,UAAU,aAAc,QAAO;AAElF,MAAI,CAAC,cAAc,OAAO,UAAU,YAAa,QAAO;AAExD,aAAW,UAAU,GAAG;AAExB,WAAS,GAAG,OAAO,UAAU;AAC7B,SAAO;AACX;"}
@@ -7,7 +7,7 @@ export declare const MAX_UNKNOWN_KEYS = 10;
7
7
  export declare const MAX_STACK_DEPTH = 50;
8
8
  export declare const MION_ROUTES: {
9
9
  readonly methodsMetadataById: "mion@methodsMetadataById";
10
- readonly methodsMetadataByPath: "mion@methodsMetadataByPath";
10
+ readonly methodsMetadata: "mion@methodsMetadata";
11
11
  readonly platformError: "mion@platformError";
12
12
  readonly notFound: "mion@notFound";
13
13
  readonly thrownErrors: "@thrownErrors";
@@ -1,6 +1,8 @@
1
1
  const DEFAULT_CORE_OPTIONS = {
2
2
  /** automatically generate and uuid */
3
- autoGenerateErrorId: false
3
+ autoGenerateErrorId: false,
4
+ basePath: "",
5
+ suffix: ""
4
6
  };
5
7
  const PATH_SEPARATOR = "/";
6
8
  const ROUTE_PATH_ROOT = PATH_SEPARATOR;
@@ -10,8 +12,8 @@ const MAX_STACK_DEPTH = 50;
10
12
  const MION_ROUTES = {
11
13
  /** get remote methods metadata by method id */
12
14
  methodsMetadataById: "mion@methodsMetadataById",
13
- /** get remote methods metadata by route path, this include all middleFns in the ExecutionChain of the route. */
14
- methodsMetadataByPath: "mion@methodsMetadataByPath",
15
+ /** Middleware that returns methods metadata alongside any route response */
16
+ methodsMetadata: "mion@methodsMetadata",
15
17
  /** Platform or adapters errors that occur before reaching the router or outside the router and are platform/adapter related */
16
18
  platformError: "mion@platformError",
17
19
  /** not-found route. This route is called when a requested route doesn't exist */
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sources":["../../../src/constants.ts"],"sourcesContent":["/* ########\n * 2022 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {CoreRouterOptions} from './types/general.types.ts';\n\nexport const DEFAULT_CORE_OPTIONS: CoreRouterOptions = {\n /** automatically generate and uuid */\n autoGenerateErrorId: false,\n};\n\nexport const PATH_SEPARATOR = '/';\nexport const ROUTE_PATH_ROOT = PATH_SEPARATOR;\nexport const ROUTER_ITEM_SEPARATOR_CHAR = '/';\nexport const MAX_UNKNOWN_KEYS = 10;\nexport const MAX_STACK_DEPTH = 50;\n\n/**\n * Mion internal routes.\n */\nexport const MION_ROUTES = {\n /** get remote methods metadata by method id */\n methodsMetadataById: 'mion@methodsMetadataById',\n /** get remote methods metadata by route path, this include all middleFns in the ExecutionChain of the route. */\n methodsMetadataByPath: 'mion@methodsMetadataByPath',\n /** Platform or adapters errors that occur before reaching the router or outside the router and are platform/adapter related */\n platformError: 'mion@platformError',\n /** not-found route. This route is called when a requested route doesn't exist */\n notFound: 'mion@notFound',\n /**\n * !IMPORTANT!!\n * This is technically not a route, but a special key used to store unexpected errors in the response body.\n * is declared as a route to reuse existing router serialization/deserialization logic.\n * Errors thrown by routes/middleFns, these are not strongly typed\n * */\n thrownErrors: '@thrownErrors',\n} as const;\n\n/**\n * Mime types used by mion.\n * Only json and binary are supported out of the box.\n */\nexport const MIME_TYPES = {\n json: 'application/json',\n octetStream: 'application/octet-stream',\n} as const;\n\n/**\n * Standard HTTP status codes used by mion.\n * Status codes are a bit irrelevant in mion apps, the important part is the error type, that is a human readable code.\n * They are used mostly for backwards compatibility with HTTP.\n */\nexport const StatusCodes = {\n /** Any error in the server that is not related to the application, ie: server not ready, etc... */\n SERVER_ERROR: 500,\n /** Any expected and strongly typed error returned by a route/middleFn. ie: entity not found, etc. */\n APPLICATION_ERROR: 400,\n /** Any thrown or unexpected error in the application, ie: validation error, not found, etc, database error, serialization error, etc...\n * These are are typically irrecoverable and can be handled globally, ie redirect to login page if auth fails\n */\n UNEXPECTED_ERROR: 422,\n /** Not found error */\n NOT_FOUND: 404,\n /** Standard success code */\n OK: 200,\n} as const;\n\nexport const HandlerType = {\n route: 1,\n middleFn: 2,\n headersMiddleFn: 3,\n rawMiddleFn: 4,\n} as const;\n\nexport const JIT_FUNCTION_IDS = {\n isType: 'is',\n typeErrors: 'te',\n prepareForJson: 'tj',\n restoreFromJson: 'fj',\n stringifyJson: 'sj',\n toJSCode: 'tc',\n toBinary: 'tBi',\n fromBinary: 'fBi',\n format: 'fmt',\n unknownKeyErrors: 'uk',\n hasUnknownKeys: 'hk',\n stripUnknownKeys: 'sk',\n unknownKeysToUndefined: 'ku',\n aux: 'aux',\n mock: 'mock',\n pureFunction: 'pf',\n} as const;\n\n/** Empty hash used when no params exist or return type is void (no JIT functions generated) */\nexport const EMPTY_HASH = '';\n"],"names":[],"mappings":"AASO,MAAM,uBAA0C;AAAA;AAAA,EAEnD,qBAAqB;;AAGlB,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AACxB,MAAM,6BAA6B;AACnC,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AAKxB,MAAM,cAAc;AAAA;AAAA,EAEvB,qBAAqB;AAAA;AAAA,EAErB,uBAAuB;AAAA;AAAA,EAEvB,eAAe;AAAA;AAAA,EAEf,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,cAAc;;AAOX,MAAM,aAAa;AAAA,EACtB,MAAM;AAAA,EACN,aAAa;;AAQV,MAAM,cAAc;AAAA;AAAA,EAEvB,cAAc;AAAA;AAAA,EAEd,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAInB,kBAAkB;AAAA;AAAA,EAElB,WAAW;AAAA;AAAA,EAEX,IAAI;;AAGD,MAAM,cAAc;AAAA,EACvB,OAAO;AAAA,EACP,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,aAAa;;AAGV,MAAM,mBAAmB;AAAA,EAC5B,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,UAAU;AAAA,EACV,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,wBAAwB;AAAA,EACxB,KAAK;AAAA,EACL,MAAM;AAAA,EACN,cAAc;;AAIX,MAAM,aAAa;"}
1
+ {"version":3,"file":"constants.js","sources":["../../../src/constants.ts"],"sourcesContent":["/* ########\n * 2022 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {CoreRouterOptions} from './types/general.types.ts';\n\nexport const DEFAULT_CORE_OPTIONS: CoreRouterOptions = {\n /** automatically generate and uuid */\n autoGenerateErrorId: false,\n basePath: '',\n suffix: '',\n};\n\nexport const PATH_SEPARATOR = '/';\nexport const ROUTE_PATH_ROOT = PATH_SEPARATOR;\nexport const ROUTER_ITEM_SEPARATOR_CHAR = '/';\nexport const MAX_UNKNOWN_KEYS = 10;\nexport const MAX_STACK_DEPTH = 50;\n\n/**\n * Mion internal routes.\n */\nexport const MION_ROUTES = {\n /** get remote methods metadata by method id */\n methodsMetadataById: 'mion@methodsMetadataById',\n /** Middleware that returns methods metadata alongside any route response */\n methodsMetadata: 'mion@methodsMetadata',\n /** Platform or adapters errors that occur before reaching the router or outside the router and are platform/adapter related */\n platformError: 'mion@platformError',\n /** not-found route. This route is called when a requested route doesn't exist */\n notFound: 'mion@notFound',\n /**\n * !IMPORTANT!!\n * This is technically not a route, but a special key used to store unexpected errors in the response body.\n * is declared as a route to reuse existing router serialization/deserialization logic.\n * Errors thrown by routes/middleFns, these are not strongly typed\n * */\n thrownErrors: '@thrownErrors',\n} as const;\n\n/**\n * Mime types used by mion.\n * Only json and binary are supported out of the box.\n */\nexport const MIME_TYPES = {\n json: 'application/json',\n octetStream: 'application/octet-stream',\n} as const;\n\n/**\n * Standard HTTP status codes used by mion.\n * Status codes are a bit irrelevant in mion apps, the important part is the error type, that is a human readable code.\n * They are used mostly for backwards compatibility with HTTP.\n */\nexport const StatusCodes = {\n /** Any error in the server that is not related to the application, ie: server not ready, etc... */\n SERVER_ERROR: 500,\n /** Any expected and strongly typed error returned by a route/middleFn. ie: entity not found, etc. */\n APPLICATION_ERROR: 400,\n /** Any thrown or unexpected error in the application, ie: validation error, not found, etc, database error, serialization error, etc...\n * These are are typically irrecoverable and can be handled globally, ie redirect to login page if auth fails\n */\n UNEXPECTED_ERROR: 422,\n /** Not found error */\n NOT_FOUND: 404,\n /** Standard success code */\n OK: 200,\n} as const;\n\nexport const HandlerType = {\n route: 1,\n middleFn: 2,\n headersMiddleFn: 3,\n rawMiddleFn: 4,\n} as const;\n\nexport const JIT_FUNCTION_IDS = {\n isType: 'is',\n typeErrors: 'te',\n prepareForJson: 'tj',\n restoreFromJson: 'fj',\n stringifyJson: 'sj',\n toJSCode: 'tc',\n toBinary: 'tBi',\n fromBinary: 'fBi',\n format: 'fmt',\n unknownKeyErrors: 'uk',\n hasUnknownKeys: 'hk',\n stripUnknownKeys: 'sk',\n unknownKeysToUndefined: 'ku',\n aux: 'aux',\n mock: 'mock',\n pureFunction: 'pf',\n} as const;\n\n/** Empty hash used when no params exist or return type is void (no JIT functions generated) */\nexport const EMPTY_HASH = '';\n"],"names":[],"mappings":"AASO,MAAM,uBAA0C;AAAA;AAAA,EAEnD,qBAAqB;AAAA,EACrB,UAAU;AAAA,EACV,QAAQ;;AAGL,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AACxB,MAAM,6BAA6B;AACnC,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AAKxB,MAAM,cAAc;AAAA;AAAA,EAEvB,qBAAqB;AAAA;AAAA,EAErB,iBAAiB;AAAA;AAAA,EAEjB,eAAe;AAAA;AAAA,EAEf,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,cAAc;;AAOX,MAAM,aAAa;AAAA,EACtB,MAAM;AAAA,EACN,aAAa;;AAQV,MAAM,cAAc;AAAA;AAAA,EAEvB,cAAc;AAAA;AAAA,EAEd,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAInB,kBAAkB;AAAA;AAAA,EAElB,WAAW;AAAA;AAAA,EAEX,IAAI;;AAGD,MAAM,cAAc;AAAA,EACvB,OAAO;AAAA,EACP,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,aAAa;;AAGV,MAAM,mBAAmB;AAAA,EAC5B,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,EACjB,eAAe;AAAA,EACf,UAAU;AAAA,EACV,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,QAAQ;AAAA,EACR,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,wBAAwB;AAAA,EACxB,KAAK;AAAA,EACL,MAAM;AAAA,EACN,cAAc;;AAIX,MAAM,aAAa;"}
@@ -17,8 +17,7 @@ function registerPureFnFactory(namespace, functionID, createPureFn, parsedFn) {
17
17
  fnName: functionID,
18
18
  bodyHash: parsedFn.bodyHash,
19
19
  paramNames: parsedFn.paramNames,
20
- code: parsedFn.code,
21
- pureFnDependencies: []
20
+ code: parsedFn.code
22
21
  };
23
22
  const { proxy, getDependencies } = createDependencyTrackingProxy();
24
23
  try {
@@ -29,8 +28,11 @@ function registerPureFnFactory(namespace, functionID, createPureFn, parsedFn) {
29
28
  for (const dep of detectedDeps) {
30
29
  if (dep === functionID)
31
30
  continue;
32
- if (!compiled.pureFnDependencies.includes(dep))
33
- compiled.pureFnDependencies.push(dep);
31
+ if (compiled.pureFnDependencies?.includes(dep))
32
+ continue;
33
+ if (!compiled.pureFnDependencies)
34
+ compiled.pureFnDependencies = [];
35
+ compiled.pureFnDependencies.push(dep);
34
36
  }
35
37
  getJitUtils().addPureFn(namespace, compiled);
36
38
  return compiled;
@@ -1 +1 @@
1
- {"version":3,"file":"pureFn.js","sources":["../../../../src/pureFns/pureFn.ts"],"sourcesContent":["/* ########\n * 2026 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {CompiledPureFunction, ParsedFactoryFn, PureFunctionFactory} from '../types/pureFunctions.types.ts';\nimport {getJitUtils, type JITUtils} from '../jit/jitUtils.ts';\n\n// ╔══════════════════════════════════════════════════════════════════════════════╗\n// ║ WARNING: This function's call signature is parsed by the mion vite plugin ║\n// ║ at build time (see devtools/src/vite-plugin/extractPureFn.ts). ║\n// ║ Do NOT rename, change the parameter order, or modify the function ║\n// ║ signature without updating the corresponding AST extraction and ║\n// ║ transformer logic in @mionjs/devtools. ║\n// ╚══════════════════════════════════════════════════════════════════════════════╝\n\n/**\n * Registers a pure function factory with automatic dependency tracking.\n * The `parsedFn` argument (containing bodyHash, paramNames, and code) is injected\n * at build time by the mion vite plugin's transform hook — it must never be passed manually.\n * If the function is already registered under the same namespace + functionID, the existing\n * compiled entry is returned (idempotent). Dependencies on other pure functions are\n * auto-detected by running the factory once with a tracking proxy.\n *\n * This is intended to share util functions between server and clients\n */\nexport function registerPureFnFactory(\n namespace: string,\n functionID: string,\n createPureFn: PureFunctionFactory,\n parsedFn?: ParsedFactoryFn // injected by mion vite plugin\n): CompiledPureFunction {\n if (!parsedFn) throw new Error('registerPureFnFactory requires mion vite plugin transform to inject parsedFn');\n const existing = getJitUtils().getCompiledPureFn(namespace, functionID);\n if (existing) return existing;\n\n const compiled: CompiledPureFunction = {\n createPureFn,\n fn: null as any, // will be set later so all possible dependencies are resolved\n namespace,\n fnName: functionID,\n bodyHash: parsedFn.bodyHash,\n paramNames: parsedFn.paramNames,\n code: parsedFn.code,\n pureFnDependencies: [],\n };\n\n // Run the factory once with a tracking proxy to auto-detect dependencies\n const {proxy, getDependencies} = createDependencyTrackingProxy();\n try {\n createPureFn(proxy);\n } catch {\n // Factory may fail if dependencies aren't registered yet, that's ok\n // We still capture whatever was accessed before the error\n }\n const detectedDeps = getDependencies();\n for (const dep of detectedDeps) {\n if (dep === functionID) continue;\n if (!compiled.pureFnDependencies.includes(dep)) compiled.pureFnDependencies.push(dep);\n }\n\n getJitUtils().addPureFn(namespace, compiled);\n return compiled;\n}\n\n/** Creates a proxy of jitUtils that records all pure function accesses (getPureFn, usePureFn, etc.) */\nfunction createDependencyTrackingProxy(): {proxy: JITUtils; getDependencies: () => Set<string>} {\n const dependencies = new Set<string>();\n const realUtils = getJitUtils();\n\n const noopFn = () => () => {};\n\n const proxy = new Proxy(realUtils, {\n get(target, prop, receiver) {\n if (prop === 'getPureFn' || prop === 'usePureFn') {\n return (ns: string, fnName: string) => {\n dependencies.add(fnName);\n // Return a noop function so the factory can execute without errors\n const real = target.getPureFn(ns, fnName);\n return real ?? noopFn;\n };\n }\n if (prop === 'getCompiledPureFn') {\n return (ns: string, fnName: string) => {\n dependencies.add(fnName);\n return target.getCompiledPureFn(ns, fnName);\n };\n }\n if (prop === 'hasPureFn') {\n return (ns: string, fnName: string) => {\n dependencies.add(fnName);\n return target.hasPureFn(ns, fnName);\n };\n }\n if (prop === 'findCompiledPureFn') {\n return (fnName: string) => {\n dependencies.add(fnName);\n return target.findCompiledPureFn(fnName);\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n\n return {proxy, getDependencies: () => dependencies};\n}\n"],"names":[],"mappings":";;;;;AA4BM,SAAU,sBACZ,WACA,YACA,cACA;AAEA,MAAI,CAAC;AAAU,UAAM,IAAI,MAAM,8EAA8E;AAC7G,QAAM,WAAW,YAAA,EAAc,kBAAkB,WAAW,UAAU;AACtE,MAAI;AAAU,WAAO;AAErB,QAAM,WAAiC;AAAA,IACnC;AAAA,IACA,IAAI;AAAA;AAAA,IACJ;AAAA,IACA,QAAQ;AAAA,IACR,UAAU,SAAS;AAAA,IACnB,YAAY,SAAS;AAAA,IACrB,MAAM,SAAS;AAAA,IACf,oBAAoB,CAAA;AAAA,EAAA;AAIxB,QAAM,EAAC,OAAO,gBAA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AAO,OAAO,mBAAmB,MAAM;AAAA,QAC3C,GAAC,CAAA,UAAA,IAAA,SAAA,CAAA;AAAA,MACL;AACA,aAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;AAAA,IAC7C;AAAA,EAAA,CACH;AAED,SAAO,EAAC,OAAO,iBAAiB,MAAM,aAAA;AAC1C;;"}
1
+ {"version":3,"file":"pureFn.js","sources":["../../../../src/pureFns/pureFn.ts"],"sourcesContent":["/* ########\n * 2026 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {CompiledPureFunction, ParsedFactoryFn, PureFunctionFactory} from '../types/pureFunctions.types.ts';\nimport {getJitUtils, type JITUtils} from '../jit/jitUtils.ts';\n\n// ╔══════════════════════════════════════════════════════════════════════════════╗\n// ║ WARNING: This function's call signature is parsed by the mion vite plugin ║\n// ║ at build time (see devtools/src/vite-plugin/extractPureFn.ts). ║\n// ║ Do NOT rename, change the parameter order, or modify the function ║\n// ║ signature without updating the corresponding AST extraction and ║\n// ║ transformer logic in @mionjs/devtools. ║\n// ╚══════════════════════════════════════════════════════════════════════════════╝\n\n/**\n * Registers a pure function factory with automatic dependency tracking.\n * The `parsedFn` argument (containing bodyHash, paramNames, and code) is injected\n * at build time by the mion vite plugin's transform hook — it must never be passed manually.\n * If the function is already registered under the same namespace + functionID, the existing\n * compiled entry is returned (idempotent). Dependencies on other pure functions are\n * auto-detected by running the factory once with a tracking proxy.\n *\n * This is intended to share util functions between server and clients\n */\nexport function registerPureFnFactory(\n namespace: string,\n functionID: string,\n createPureFn: PureFunctionFactory,\n parsedFn?: ParsedFactoryFn // injected by mion vite plugin\n): CompiledPureFunction {\n if (!parsedFn) throw new Error('registerPureFnFactory requires mion vite plugin transform to inject parsedFn');\n const existing = getJitUtils().getCompiledPureFn(namespace, functionID);\n if (existing) return existing;\n\n const compiled: CompiledPureFunction = {\n createPureFn,\n fn: null as any, // will be set later so all possible dependencies are resolved\n namespace,\n fnName: functionID,\n bodyHash: parsedFn.bodyHash,\n paramNames: parsedFn.paramNames,\n code: parsedFn.code,\n };\n\n // Run the factory once with a tracking proxy to auto-detect dependencies\n const {proxy, getDependencies} = createDependencyTrackingProxy();\n try {\n createPureFn(proxy);\n } catch {\n // Factory may fail if dependencies aren't registered yet, that's ok\n // We still capture whatever was accessed before the error\n }\n const detectedDeps = getDependencies();\n for (const dep of detectedDeps) {\n if (dep === functionID) continue;\n if (compiled.pureFnDependencies?.includes(dep)) continue;\n if (!compiled.pureFnDependencies) (compiled as any).pureFnDependencies = [];\n compiled.pureFnDependencies!.push(dep);\n }\n\n getJitUtils().addPureFn(namespace, compiled);\n return compiled;\n}\n\n/** Creates a proxy of jitUtils that records all pure function accesses (getPureFn, usePureFn, etc.) */\nfunction createDependencyTrackingProxy(): {proxy: JITUtils; getDependencies: () => Set<string>} {\n const dependencies = new Set<string>();\n const realUtils = getJitUtils();\n\n const noopFn = () => () => {};\n\n const proxy = new Proxy(realUtils, {\n get(target, prop, receiver) {\n if (prop === 'getPureFn' || prop === 'usePureFn') {\n return (ns: string, fnName: string) => {\n dependencies.add(fnName);\n // Return a noop function so the factory can execute without errors\n const real = target.getPureFn(ns, fnName);\n return real ?? noopFn;\n };\n }\n if (prop === 'getCompiledPureFn') {\n return (ns: string, fnName: string) => {\n dependencies.add(fnName);\n return target.getCompiledPureFn(ns, fnName);\n };\n }\n if (prop === 'hasPureFn') {\n return (ns: string, fnName: string) => {\n dependencies.add(fnName);\n return target.hasPureFn(ns, fnName);\n };\n }\n if (prop === 'findCompiledPureFn') {\n return (fnName: string) => {\n dependencies.add(fnName);\n return target.findCompiledPureFn(fnName);\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n\n return {proxy, getDependencies: () => dependencies};\n}\n"],"names":[],"mappings":";;;;;AA4BM,SAAU,sBACZ,WACA,YACA,cACA;AAEA,MAAI,CAAC;AAAU,UAAM,IAAI,MAAM,8EAA8E;AAC7G,QAAM,WAAW,YAAA,EA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,CAAA;AAAA,MACL;AACA,UAAI,SAAS,aAAa;AACtB,eAAA,aAAO,CAAC,IAAY,WAAkB;AAClC,uBAAa,IAAI,MAAM;AACvB,iBAAO,OAAO,UAAU,IAAI,MAAM;AAAA,QACtC,GAAC,CAAA,MAAA,UAAA,IAAA,YAAA,CAAA;AAAA,MACL;AACA,UAAI,SAAS,sBAAsB;AAC/B,eAAA,aAAO,CAAC,WAAkB;AACtB,uBAAa,IAAI,MAAM;AACvB,iBAAO,OAAO,mBAAmB,MAAM;AAAA,QAC3C,GAAC,CAAA,UAAA,IAAA,SAAA,CAAA;AAAA,MACL;AACA,aAAO,QAAQ,IAAI,QAAQ,MAAM,QAAQ;AAAA,IAC7C;AAAA,EAAA,CACH;AAED,SAAO,EAAC,OAAO,iBAAiB,MAAM,aAAA;AAC1C;;"}
@@ -19,7 +19,7 @@ function restoreCompiledPureFn(pureCache, namespace, fnName, jUtil, visited) {
19
19
  const pureCompiled = nsCache[fnName];
20
20
  if (!pureCompiled) throw new Error(`Pure function ${fnName} not found in namespace ${namespace}`);
21
21
  if (pureCompiled.fn) return;
22
- const dependencies = pureCompiled.pureFnDependencies;
22
+ const dependencies = pureCompiled.pureFnDependencies || [];
23
23
  dependencies.forEach((depName) => restoreCompiledPureFn(pureCache, namespace, depName, jUtil, visited));
24
24
  if (pureCompiled.createPureFn) {
25
25
  pureCompiled.fn = pureCompiled.createPureFn(jUtil);
@@ -33,14 +33,14 @@ function restoreCompiledJitFn(jitCache, pureCache, fnHash, jUtil, visitedPure, v
33
33
  const jitCompiled = jitCache[fnHash];
34
34
  if (!jitCompiled) throw new Error(`Jit function ${fnHash} not found`);
35
35
  if (jitCompiled.fn) return;
36
- const pureDependencies = jitCompiled.pureFnDependencies;
36
+ const pureDependencies = jitCompiled.pureFnDependencies || [];
37
37
  pureDependencies.forEach((dep) => {
38
38
  const parts = dep.split("::");
39
39
  if (parts.length !== 2) throw new Error(`Invalid pure function dependency format: ${dep}, expected "namespace::fnHash"`);
40
40
  const [namespace, fnHash2] = parts;
41
41
  restoreCompiledPureFn(pureCache, namespace, fnHash2, jUtil, visitedPure);
42
42
  });
43
- const dependencies = jitCompiled.jitDependencies;
43
+ const dependencies = jitCompiled.jitDependencies || [];
44
44
  dependencies.forEach((dep) => restoreCompiledJitFn(jitCache, pureCache, dep, jUtil, visitedPure, visitedJit));
45
45
  if (jitCompiled.createJitFn) {
46
46
  jitCompiled.fn = jitCompiled.createJitFn(jUtil);
@@ -1 +1 @@
1
- {"version":3,"file":"restoreJitFns.js","sources":["../../../../src/pureFns/restoreJitFns.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 type {\n Mutable,\n JitCompiledFn,\n PersistedJitFunctionsCache,\n PersistedPureFunctionsCache,\n FnsDataCache,\n PureFnsDataCache,\n PureFunctionsCache,\n JitCompiledFnData,\n PersistedJitFn,\n} from '../types/general.types.ts';\nimport {JITUtils} from '../jit/jitUtils.ts';\nimport type {PersistedPureFunction} from '../types/pureFunctions.types.ts';\nimport type {CompiledPureFunction} from '../types/pureFunctions.types.ts';\nimport type {PureFunctionData} from '../types/pureFunctions.types.ts';\nimport type {PureFunctionFactory} from '../types/pureFunctions.types.ts';\nimport {TypedError} from '../errors.ts';\n\n/**\n * Restores the full state of a persisted/serialized jit functions.\n * This functions mutates the input caches!!!\n * Persisted functions are jit functions written to code that contains the createJitFn closure but not the fn.\n * Serialized functions are jit functions sent over the network that contains the code to recreate the createJitFn closure and fn.\n * The JIT fn itself can't be compiled to code as it contains references to context code and jitUtils.\n * So we need to restore it manually by invoking the closure function.\n * */\nexport function restoreCompiledJitFns(\n jitCache: PersistedJitFunctionsCache | FnsDataCache,\n pureCache: PureFunctionsCache | PersistedPureFunctionsCache | PureFnsDataCache,\n jUtil: JITUtils\n): void {\n // Use visited sets to prevent infinite recursion on circular dependencies\n // This is needed because during restoration, the `fn` property is not set until after\n // all dependencies are restored, so checking `fn` alone can't prevent circular calls\n const visitedPure = new Set<string>();\n const visitedJit = new Set<string>();\n\n // Iterate over all namespaces and restore pure functions\n for (const namespace in pureCache) {\n const nsCache = pureCache[namespace];\n const keysPureFns = Object.keys(nsCache);\n keysPureFns.forEach((key) => restoreCompiledPureFn(pureCache, namespace, key, jUtil, visitedPure));\n }\n const keysJitFns = Object.keys(jitCache);\n keysJitFns.forEach((key) => restoreCompiledJitFn(jitCache, pureCache, key, jUtil, visitedPure, visitedJit));\n}\n\nfunction restoreCompiledPureFn(\n pureCache: PureFunctionsCache | PersistedPureFunctionsCache | PureFnsDataCache,\n namespace: string,\n fnName: string,\n jUtil: JITUtils,\n visited: Set<string>\n) {\n // Use namespace:fnName as the visited key to handle same function names in different namespaces\n const visitedKey = `${namespace}:${fnName}`;\n // Skip if already visited (handles circular dependencies)\n if (visited.has(visitedKey)) return;\n visited.add(visitedKey);\n\n const nsCache = pureCache[namespace];\n if (!nsCache) throw new Error(`Pure function namespace ${namespace} not found`);\n const pureCompiled = nsCache[fnName];\n if (!pureCompiled) throw new Error(`Pure function ${fnName} not found in namespace ${namespace}`);\n if ((pureCompiled as CompiledPureFunction).fn) return;\n const dependencies = pureCompiled.pureFnDependencies;\n // Dependencies are in the same namespace\n dependencies.forEach((depName) => restoreCompiledPureFn(pureCache, namespace, depName, jUtil, visited));\n // persisted pure functions (AOT code caches) have the createJitFn but not the fn\n if ((pureCompiled as PersistedPureFunction).createPureFn) {\n (pureCompiled as any as Mutable<CompiledPureFunction>).fn = (pureCompiled as PersistedPureFunction).createPureFn(jUtil);\n return;\n }\n // serialized pure functions (network sent) do not contains neither createJitFn nor fn\n restorePureFunction(pureCompiled, jUtil);\n}\n\nfunction restoreCompiledJitFn(\n jitCache: PersistedJitFunctionsCache | FnsDataCache,\n pureCache: PureFunctionsCache | PersistedPureFunctionsCache | PureFnsDataCache,\n fnHash: string,\n jUtil: JITUtils,\n visitedPure: Set<string>,\n visitedJit: Set<string>\n) {\n // Skip if already visited (handles circular dependencies)\n if (visitedJit.has(fnHash)) return;\n visitedJit.add(fnHash);\n\n const jitCompiled = jitCache[fnHash];\n if (!jitCompiled) throw new Error(`Jit function ${fnHash} not found`);\n if ((jitCompiled as JitCompiledFn).fn) return;\n const pureDependencies = jitCompiled.pureFnDependencies;\n // Pure function dependencies are stored as \"namespace::fnHash\"\n pureDependencies.forEach((dep) => {\n const parts = dep.split('::');\n if (parts.length !== 2) throw new Error(`Invalid pure function dependency format: ${dep}, expected \"namespace::fnHash\"`);\n const [namespace, fnHash] = parts;\n restoreCompiledPureFn(pureCache, namespace, fnHash, jUtil, visitedPure);\n });\n const dependencies = jitCompiled.jitDependencies;\n dependencies.forEach((dep) => restoreCompiledJitFn(jitCache, pureCache, dep, jUtil, visitedPure, visitedJit));\n if ((jitCompiled as PersistedJitFn).createJitFn) {\n (jitCompiled as any as Mutable<JitCompiledFn>).fn = (jitCompiled as PersistedJitFn).createJitFn(jUtil);\n return;\n }\n restoreCreateJitFn(jitCompiled, jUtil);\n}\n\n/**\n * Restores a JIT function from serialized function data.\n * This functionsMutates the input data!!!\n * Creates a dynamic function using the serialized code (which already contains the complete function with context),\n * then executes it with jitUtils to produce the final JIT function.\n * @param fnData - The serialized function data containing code, args, and metadata\n * @returns A JitCompiledFn with both the createJitFn closure and the executed fn\n */\nfunction restoreCreateJitFn(fnData: JitCompiledFnData, jUtil: JITUtils): JitCompiledFn {\n const fnName = fnData.jitFnHash;\n // fnData.code already contains the complete function with context (e.g., \"const x = ...; return function fnName(args){...}\")\n const fnWithContext = `'use strict'; ${fnData.code}`;\n try {\n // Create wrapper function that works as a factory and returns the actual jit function\n const wrapperWithContext = new Function('utl', fnWithContext) as (utl: JITUtils) => (...args: any[]) => any;\n // Execute the wrapper with jitUtils to get the final function\n const fn = wrapperWithContext(jUtil);\n const jitFn = fnData as Mutable<JitCompiledFn>;\n jitFn.createJitFn = wrapperWithContext;\n jitFn.fn = fn;\n return jitFn;\n } catch (e: any) {\n throw new TypedError({\n type: 'jit-fn-restore-error',\n message: `Failed to restore JIT function ${fnName}: ${e?.message}`,\n });\n }\n}\n\n/**\n * Restores a pure function from serialized function data.\n * This function mutates the input data!!!\n * Creates a dynamic function using the serialized code (which already contains the complete function with context),\n * then executes it with jitUtils to produce the final pure function.\n * @param pureFnData - The serialized pure function data containing code and metadata\n * @returns A CompiledPureFunction with both the createJitFn closure and the executed fn\n */\nfunction restorePureFunction(pureFnData: PureFunctionData, jUtil: JITUtils): CompiledPureFunction {\n const fnName = pureFnData.fnName;\n // pureFnData.code already contains the complete function with context\n const fnWithContext = `'use strict'; ${pureFnData.code}`;\n try {\n // Create wrapper function that works as a factory and returns the actual pure function\n const wrapperWithContext = new Function('utl', fnWithContext) as PureFunctionFactory;\n // Execute the wrapper with jitUtils to get the final function\n const fn = wrapperWithContext(jUtil);\n const pureFn = pureFnData as Mutable<CompiledPureFunction>;\n pureFn.createPureFn = wrapperWithContext;\n pureFn.fn = fn;\n return pureFn;\n } catch (e: any) {\n throw new TypedError({\n type: 'pure-fn-restore-error',\n message: `Failed to restore pure function ${fnName}: ${e?.message}`,\n });\n }\n}\n"],"names":["fnHash"],"mappings":";AAiCO,SAAS,sBACZ,UACA,WACA,OACI;AAIJ,QAAM,kCAAkB,IAAA;AACxB,QAAM,iCAAiB,IAAA;AAGvB,aAAW,aAAa,WAAW;AAC/B,UAAM,UAAU,UAAU,SAAS;AACnC,UAAM,cAAc,OAAO,KAAK,OAAO;AACvC,gBAAY,QAAQ,CAAC,QAAQ,sBAAsB,WAAW,WAAW,KAAK,OAAO,WAAW,CAAC;AAAA,EACrG;AACA,QAAM,aAAa,OAAO,KAAK,QAAQ;AACvC,aAAW,QAAQ,CAAC,QAAQ,qBAAqB,UAAU,WAAW,KAAK,OAAO,aAAa,UAAU,CAAC;AAC9G;AAEA,SAAS,sBACL,WACA,WACA,QACA,OACA,SACF;AAEE,QAAM,aAAa,GAAG,SAAS,IAAI,MAAM;AAEzC,MAAI,QAAQ,IAAI,U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AA2B,OAAgC;AACnF,QAAM,SAAS,OAAO;AAEtB,QAAM,gBAAgB,iBAAiB,OAAO,IAAI;AAClD,MAAI;AAEA,UAAM,qBAAqB,IAAI,SAAS,OAAO,aAAa;AAE5D,UAAM,KAAK,mBAAmB,KAAK;AACnC,UAAM,QAAQ;AACd,UAAM,cAAc;AACpB,UAAM,KAAK;AACX,WAAO;AAAA,EACX,SAAS,GAAQ;AACb,UAAM,IAAI,WAAW;AAAA,MACjB,MAAM;AAAA,MACN,SAAS,kCAAkC,MAAM,KAAK,GAAG,OAAO;AAAA,IAAA,CACnE;AAAA,EACL;AACJ;AAUA,SAAS,oBAAoB,YAA8B,OAAuC;AAC9F,QAAM,SAAS,WAAW;AAE1B,QAAM,gBAAgB,iBAAiB,WAAW,IAAI;AACtD,MAAI;AAEA,UAAM,qBAAqB,IAAI,SAAS,OAAO,aAAa;AAE5D,UAAM,KAAK,mBAAmB,KAAK;AACnC,UAAM,SAAS;AACf,WAAO,eAAe;AACtB,WAAO,KAAK;AACZ,WAAO;AAAA,EACX,SAAS,GAAQ;AACb,UAAM,IAAI,WAAW;AAAA,MACjB,MAAM;AAAA,MACN,SAAS,mCAAmC,MAAM,KAAK,GAAG,OAAO;AAAA,IAAA,CACpE;AAAA,EACL;AACJ;"}
1
+ {"version":3,"file":"restoreJitFns.js","sources":["../../../../src/pureFns/restoreJitFns.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 type {\n Mutable,\n JitCompiledFn,\n PersistedJitFunctionsCache,\n PersistedPureFunctionsCache,\n FnsDataCache,\n PureFnsDataCache,\n PureFunctionsCache,\n JitCompiledFnData,\n PersistedJitFn,\n} from '../types/general.types.ts';\nimport {JITUtils} from '../jit/jitUtils.ts';\nimport type {PersistedPureFunction} from '../types/pureFunctions.types.ts';\nimport type {CompiledPureFunction} from '../types/pureFunctions.types.ts';\nimport type {PureFunctionData} from '../types/pureFunctions.types.ts';\nimport type {PureFunctionFactory} from '../types/pureFunctions.types.ts';\nimport {TypedError} from '../errors.ts';\n\n/**\n * Restores the full state of a persisted/serialized jit functions.\n * This functions mutates the input caches!!!\n * Persisted functions are jit functions written to code that contains the createJitFn closure but not the fn.\n * Serialized functions are jit functions sent over the network that contains the code to recreate the createJitFn closure and fn.\n * The JIT fn itself can't be compiled to code as it contains references to context code and jitUtils.\n * So we need to restore it manually by invoking the closure function.\n * */\nexport function restoreCompiledJitFns(\n jitCache: PersistedJitFunctionsCache | FnsDataCache,\n pureCache: PureFunctionsCache | PersistedPureFunctionsCache | PureFnsDataCache,\n jUtil: JITUtils\n): void {\n // Use visited sets to prevent infinite recursion on circular dependencies\n // This is needed because during restoration, the `fn` property is not set until after\n // all dependencies are restored, so checking `fn` alone can't prevent circular calls\n const visitedPure = new Set<string>();\n const visitedJit = new Set<string>();\n\n // Iterate over all namespaces and restore pure functions\n for (const namespace in pureCache) {\n const nsCache = pureCache[namespace];\n const keysPureFns = Object.keys(nsCache);\n keysPureFns.forEach((key) => restoreCompiledPureFn(pureCache, namespace, key, jUtil, visitedPure));\n }\n const keysJitFns = Object.keys(jitCache);\n keysJitFns.forEach((key) => restoreCompiledJitFn(jitCache, pureCache, key, jUtil, visitedPure, visitedJit));\n}\n\nfunction restoreCompiledPureFn(\n pureCache: PureFunctionsCache | PersistedPureFunctionsCache | PureFnsDataCache,\n namespace: string,\n fnName: string,\n jUtil: JITUtils,\n visited: Set<string>\n) {\n // Use namespace:fnName as the visited key to handle same function names in different namespaces\n const visitedKey = `${namespace}:${fnName}`;\n // Skip if already visited (handles circular dependencies)\n if (visited.has(visitedKey)) return;\n visited.add(visitedKey);\n\n const nsCache = pureCache[namespace];\n if (!nsCache) throw new Error(`Pure function namespace ${namespace} not found`);\n const pureCompiled = nsCache[fnName];\n if (!pureCompiled) throw new Error(`Pure function ${fnName} not found in namespace ${namespace}`);\n if ((pureCompiled as CompiledPureFunction).fn) return;\n const dependencies = pureCompiled.pureFnDependencies || [];\n // Dependencies are in the same namespace\n dependencies.forEach((depName) => restoreCompiledPureFn(pureCache, namespace, depName, jUtil, visited));\n // persisted pure functions (AOT code caches) have the createJitFn but not the fn\n if ((pureCompiled as PersistedPureFunction).createPureFn) {\n (pureCompiled as any as Mutable<CompiledPureFunction>).fn = (pureCompiled as PersistedPureFunction).createPureFn(jUtil);\n return;\n }\n // serialized pure functions (network sent) do not contains neither createJitFn nor fn\n restorePureFunction(pureCompiled, jUtil);\n}\n\nfunction restoreCompiledJitFn(\n jitCache: PersistedJitFunctionsCache | FnsDataCache,\n pureCache: PureFunctionsCache | PersistedPureFunctionsCache | PureFnsDataCache,\n fnHash: string,\n jUtil: JITUtils,\n visitedPure: Set<string>,\n visitedJit: Set<string>\n) {\n // Skip if already visited (handles circular dependencies)\n if (visitedJit.has(fnHash)) return;\n visitedJit.add(fnHash);\n\n const jitCompiled = jitCache[fnHash];\n if (!jitCompiled) throw new Error(`Jit function ${fnHash} not found`);\n if ((jitCompiled as JitCompiledFn).fn) return;\n const pureDependencies = jitCompiled.pureFnDependencies || [];\n // Pure function dependencies are stored as \"namespace::fnHash\"\n pureDependencies.forEach((dep) => {\n const parts = dep.split('::');\n if (parts.length !== 2) throw new Error(`Invalid pure function dependency format: ${dep}, expected \"namespace::fnHash\"`);\n const [namespace, fnHash] = parts;\n restoreCompiledPureFn(pureCache, namespace, fnHash, jUtil, visitedPure);\n });\n const dependencies = jitCompiled.jitDependencies || [];\n dependencies.forEach((dep) => restoreCompiledJitFn(jitCache, pureCache, dep, jUtil, visitedPure, visitedJit));\n if ((jitCompiled as PersistedJitFn).createJitFn) {\n (jitCompiled as any as Mutable<JitCompiledFn>).fn = (jitCompiled as PersistedJitFn).createJitFn(jUtil);\n return;\n }\n restoreCreateJitFn(jitCompiled, jUtil);\n}\n\n/**\n * Restores a JIT function from serialized function data.\n * This functionsMutates the input data!!!\n * Creates a dynamic function using the serialized code (which already contains the complete function with context),\n * then executes it with jitUtils to produce the final JIT function.\n * @param fnData - The serialized function data containing code, args, and metadata\n * @returns A JitCompiledFn with both the createJitFn closure and the executed fn\n */\nfunction restoreCreateJitFn(fnData: JitCompiledFnData, jUtil: JITUtils): JitCompiledFn {\n const fnName = fnData.jitFnHash;\n // fnData.code already contains the complete function with context (e.g., \"const x = ...; return function fnName(args){...}\")\n const fnWithContext = `'use strict'; ${fnData.code}`;\n try {\n // Create wrapper function that works as a factory and returns the actual jit function\n const wrapperWithContext = new Function('utl', fnWithContext) as (utl: JITUtils) => (...args: any[]) => any;\n // Execute the wrapper with jitUtils to get the final function\n const fn = wrapperWithContext(jUtil);\n const jitFn = fnData as Mutable<JitCompiledFn>;\n jitFn.createJitFn = wrapperWithContext;\n jitFn.fn = fn;\n return jitFn;\n } catch (e: any) {\n throw new TypedError({\n type: 'jit-fn-restore-error',\n message: `Failed to restore JIT function ${fnName}: ${e?.message}`,\n });\n }\n}\n\n/**\n * Restores a pure function from serialized function data.\n * This function mutates the input data!!!\n * Creates a dynamic function using the serialized code (which already contains the complete function with context),\n * then executes it with jitUtils to produce the final pure function.\n * @param pureFnData - The serialized pure function data containing code and metadata\n * @returns A CompiledPureFunction with both the createJitFn closure and the executed fn\n */\nfunction restorePureFunction(pureFnData: PureFunctionData, jUtil: JITUtils): CompiledPureFunction {\n const fnName = pureFnData.fnName;\n // pureFnData.code already contains the complete function with context\n const fnWithContext = `'use strict'; ${pureFnData.code}`;\n try {\n // Create wrapper function that works as a factory and returns the actual pure function\n const wrapperWithContext = new Function('utl', fnWithContext) as PureFunctionFactory;\n // Execute the wrapper with jitUtils to get the final function\n const fn = wrapperWithContext(jUtil);\n const pureFn = pureFnData as Mutable<CompiledPureFunction>;\n pureFn.createPureFn = wrapperWithContext;\n pureFn.fn = fn;\n return pureFn;\n } catch (e: any) {\n throw new TypedError({\n type: 'pure-fn-restore-error',\n message: `Failed to restore pure function ${fnName}: ${e?.message}`,\n });\n }\n}\n"],"names":["fnHash"],"mappings":";AAiCO,SAA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AAAA,MACjB,MAAM;AAAA,MACN,SAAS,mCAAmC,MAAM,KAAK,GAAG,OAAO;AAAA,IAAA,CACpE;AAAA,EACL;AACJ;"}
@@ -14,7 +14,7 @@ export declare const methodOptsCache: {
14
14
  setMethodOptions(id: string, options: RemoteMethodOpts): void;
15
15
  };
16
16
  export declare function addRoutesToCache(newCache: MethodsCache): void;
17
- export declare function getJitFnHashes(jitHash: string): JitFunctionsHashes;
17
+ export declare function getJitFnHashes(jitHash: string, needsBinary?: boolean): JitFunctionsHashes;
18
18
  export declare function getJitFunctionsFromHash(jitHash: string): JitCompiledFunctions;
19
19
  export declare function getHeaderJitFunctionsFromHash(jitHash: string): Pick<JitCompiledFunctions, 'isType' | 'typeErrors'>;
20
20
  export declare function getRouterItemId(itemPointer: string[]): string;
@@ -102,33 +102,36 @@ function addRoutesToCache(newCache) {
102
102
  }
103
103
  }
104
104
  }
105
- function getJitFnHashes(jitHash) {
105
+ function getJitFnHashes(jitHash, needsBinary = false) {
106
106
  return {
107
107
  isType: `${JIT_FUNCTION_IDS.isType}_${jitHash}`,
108
108
  typeErrors: `${JIT_FUNCTION_IDS.typeErrors}_${jitHash}`,
109
109
  prepareForJson: `${JIT_FUNCTION_IDS.prepareForJson}_${jitHash}`,
110
110
  restoreFromJson: `${JIT_FUNCTION_IDS.restoreFromJson}_${jitHash}`,
111
111
  stringifyJson: `${JIT_FUNCTION_IDS.stringifyJson}_${jitHash}`,
112
- toBinary: `${JIT_FUNCTION_IDS.toBinary}_${jitHash}`,
113
- fromBinary: `${JIT_FUNCTION_IDS.fromBinary}_${jitHash}`
112
+ ...needsBinary ? {
113
+ toBinary: `${JIT_FUNCTION_IDS.toBinary}_${jitHash}`,
114
+ fromBinary: `${JIT_FUNCTION_IDS.fromBinary}_${jitHash}`
115
+ } : {}
114
116
  };
115
117
  }
116
118
  function getJitFunctionsFromHash(jitHash) {
117
119
  if (jitHash === EMPTY_HASH) return noopJitFns;
118
120
  const cached = jitFunctionsCache.get(jitHash);
119
121
  if (cached) return cached;
120
- const hashes = getJitFnHashes(jitHash);
121
122
  const jUtils = getJitUtils();
122
123
  const jitFns = {
123
- isType: jUtils.getJIT(hashes.isType),
124
- typeErrors: jUtils.getJIT(hashes.typeErrors),
125
- prepareForJson: jUtils.getJIT(hashes.prepareForJson),
126
- restoreFromJson: jUtils.getJIT(hashes.restoreFromJson),
127
- stringifyJson: jUtils.getJIT(hashes.stringifyJson),
128
- toBinary: jUtils.getJIT(hashes.toBinary),
129
- fromBinary: jUtils.getJIT(hashes.fromBinary)
124
+ isType: jUtils.getJIT(`${JIT_FUNCTION_IDS.isType}_${jitHash}`),
125
+ typeErrors: jUtils.getJIT(`${JIT_FUNCTION_IDS.typeErrors}_${jitHash}`),
126
+ prepareForJson: jUtils.getJIT(`${JIT_FUNCTION_IDS.prepareForJson}_${jitHash}`),
127
+ restoreFromJson: jUtils.getJIT(`${JIT_FUNCTION_IDS.restoreFromJson}_${jitHash}`),
128
+ stringifyJson: jUtils.getJIT(`${JIT_FUNCTION_IDS.stringifyJson}_${jitHash}`)
130
129
  };
131
- for (const key in jitFns) {
130
+ const toBinaryJit = jUtils.getJIT(`${JIT_FUNCTION_IDS.toBinary}_${jitHash}`);
131
+ const fromBinaryJit = jUtils.getJIT(`${JIT_FUNCTION_IDS.fromBinary}_${jitHash}`);
132
+ if (toBinaryJit) jitFns.toBinary = toBinaryJit;
133
+ if (fromBinaryJit) jitFns.fromBinary = fromBinaryJit;
134
+ for (const key of ["isType", "typeErrors", "prepareForJson", "restoreFromJson", "stringifyJson"]) {
132
135
  if (!jitFns[key]) throw new Error(`Jit function ${key} not found for jitHash ${jitHash}`);
133
136
  }
134
137
  jitFunctionsCache.set(jitHash, jitFns);
@@ -167,9 +170,7 @@ const noopJitFns = {
167
170
  typeErrors: fakeJitFn(JIT_FUNCTION_IDS.typeErrors),
168
171
  prepareForJson: fakeJitFn(JIT_FUNCTION_IDS.prepareForJson),
169
172
  restoreFromJson: fakeJitFn(JIT_FUNCTION_IDS.restoreFromJson),
170
- stringifyJson: fakeJitFn(JIT_FUNCTION_IDS.stringifyJson),
171
- toBinary: fakeJitFn(JIT_FUNCTION_IDS.toBinary),
172
- fromBinary: fakeJitFn(JIT_FUNCTION_IDS.fromBinary)
173
+ stringifyJson: fakeJitFn(JIT_FUNCTION_IDS.stringifyJson)
173
174
  };
174
175
  function fakeJitFn(fnID) {
175
176
  return {
@@ -180,8 +181,6 @@ function fakeJitFn(fnID) {
180
181
  defaultParamValues: { vλl: "v" },
181
182
  isNoop: true,
182
183
  code: "",
183
- jitDependencies: [],
184
- pureFnDependencies: [],
185
184
  createJitFn: () => {
186
185
  throw new Error("isNoop JIT functions should not be called, this is a function when jit is never used");
187
186
  },