@mionjs/core 0.8.0-alpha.0 → 0.8.4-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dist/cjs/src/aot/aotCaches.cjs +18 -0
- package/.dist/cjs/src/aot/aotCaches.cjs.map +1 -0
- package/.dist/cjs/src/aot/aotCaches.d.ts +6 -0
- package/.dist/cjs/src/aot/emptyCaches.cjs +9 -0
- package/.dist/cjs/src/aot/emptyCaches.cjs.map +1 -0
- package/.dist/cjs/src/aot/emptyCaches.d.ts +3 -0
- package/.dist/cjs/src/aot/emptyServerPureFns.cjs +5 -0
- package/.dist/cjs/src/aot/emptyServerPureFns.cjs.map +1 -0
- package/.dist/cjs/src/aot/emptyServerPureFns.d.ts +1 -0
- package/.dist/cjs/src/aot/serverPureFnsCaches.cjs +5 -0
- package/.dist/cjs/src/aot/serverPureFnsCaches.cjs.map +1 -0
- package/.dist/cjs/src/aot/serverPureFnsCaches.d.ts +2 -0
- package/.dist/cjs/src/constants.cjs.map +1 -1
- package/.dist/cjs/src/errors.cjs.map +1 -1
- package/.dist/cjs/src/headers.cjs.map +1 -1
- package/.dist/cjs/src/pureFns/pureFn.cjs.map +1 -1
- package/.dist/cjs/src/pureFns/pureServerFn.cjs.map +1 -1
- package/.dist/cjs/src/types/general.types.cjs.map +1 -1
- package/.dist/cjs/src/types/method.types.cjs +1 -1
- package/.dist/cjs/src/types/method.types.d.ts +1 -0
- package/.dist/cjs/src/utils.cjs +2 -2
- package/.dist/cjs/src/utils.cjs.map +1 -1
- package/.dist/esm/src/aot/aotCaches.d.ts +6 -0
- package/.dist/esm/src/aot/aotCaches.js +18 -0
- package/.dist/esm/src/aot/aotCaches.js.map +1 -0
- package/.dist/esm/src/aot/emptyCaches.d.ts +3 -0
- package/.dist/esm/src/aot/emptyCaches.js +9 -0
- package/.dist/esm/src/aot/emptyCaches.js.map +1 -0
- package/.dist/esm/src/aot/emptyServerPureFns.d.ts +1 -0
- package/.dist/esm/src/aot/emptyServerPureFns.js +5 -0
- package/.dist/esm/src/aot/emptyServerPureFns.js.map +1 -0
- package/.dist/esm/src/aot/serverPureFnsCaches.d.ts +2 -0
- package/.dist/esm/src/aot/serverPureFnsCaches.js +5 -0
- package/.dist/esm/src/aot/serverPureFnsCaches.js.map +1 -0
- package/.dist/esm/src/constants.js.map +1 -1
- package/.dist/esm/src/errors.js.map +1 -1
- package/.dist/esm/src/headers.js.map +1 -1
- package/.dist/esm/src/pureFns/pureFn.js.map +1 -1
- package/.dist/esm/src/pureFns/pureServerFn.js.map +1 -1
- package/.dist/esm/src/types/general.types.js.map +1 -1
- package/.dist/esm/src/types/method.types.d.ts +1 -0
- package/.dist/esm/src/types/method.types.js +1 -1
- package/.dist/esm/src/utils.js +2 -2
- package/.dist/esm/src/utils.js.map +1 -1
- package/package.json +14 -2
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const src_aot_emptyCaches = require("./emptyCaches.cjs");
|
|
4
|
+
const core = require("@mionjs/core");
|
|
5
|
+
function loadAOTCaches() {
|
|
6
|
+
core.addAOTCaches(src_aot_emptyCaches.jitFnsCache, src_aot_emptyCaches.pureFnsCache);
|
|
7
|
+
core.addRoutesToCache(src_aot_emptyCaches.routerCache);
|
|
8
|
+
}
|
|
9
|
+
function getRawAOTCaches() {
|
|
10
|
+
return {
|
|
11
|
+
jitFnsCache: src_aot_emptyCaches.jitFnsCache,
|
|
12
|
+
pureFnsCache: src_aot_emptyCaches.pureFnsCache,
|
|
13
|
+
routerCache: src_aot_emptyCaches.routerCache
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
exports.getRawAOTCaches = getRawAOTCaches;
|
|
17
|
+
exports.loadAOTCaches = loadAOTCaches;
|
|
18
|
+
//# sourceMappingURL=aotCaches.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aotCaches.cjs","sources":["../../../../src/aot/aotCaches.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\n// this caches will be replaced by a virtual module by the mion Vite plugin with actual AOT caches when AOT is enabled\nimport {jitFnsCache, pureFnsCache, routerCache} from './emptyCaches.ts';\nimport {addAOTCaches, addRoutesToCache} from '@mionjs/core';\n\n/** Loads pre-compiled AOT caches from virtual modules and registers them in the global caches. */\nexport function loadAOTCaches(): void {\n addAOTCaches(jitFnsCache, pureFnsCache);\n addRoutesToCache(routerCache);\n}\n\n/** Returns the global caches. */\nexport function getRawAOTCaches() {\n return {\n jitFnsCache,\n pureFnsCache,\n routerCache,\n };\n}\n"],"names":["addAOTCaches","jitFnsCache","pureFnsCache","addRoutesToCache","routerCache"],"mappings":";;;;AAYO,SAAS,gBAAsB;AAClCA,OAAAA,aAAaC,oBAAAA,aAAaC,gCAAY;AACtCC,OAAAA,iBAAiBC,oBAAAA,WAAW;AAChC;AAGO,SAAS,kBAAkB;AAC9B,SAAO;AAAA,IAAA,aACHH,oBAAAA;AAAAA,IAAA,cACAC,oBAAAA;AAAAA,IAAA,aACAE,oBAAAA;AAAAA,EAAA;AAER;;;"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const jitFnsCache = {};
|
|
4
|
+
const pureFnsCache = {};
|
|
5
|
+
const routerCache = {};
|
|
6
|
+
exports.jitFnsCache = jitFnsCache;
|
|
7
|
+
exports.pureFnsCache = pureFnsCache;
|
|
8
|
+
exports.routerCache = routerCache;
|
|
9
|
+
//# sourceMappingURL=emptyCaches.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emptyCaches.cjs","sources":["../../../../src/aot/emptyCaches.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\n/**\n * Empty AOT caches.\n * This file will be replaced by a virtual module by the mion Vite plugin with actual AOT caches when AOT is enabled.\n */\nexport const jitFnsCache = {};\nexport const pureFnsCache = {};\nexport const routerCache = {};\n"],"names":[],"mappings":";;AAWO,MAAM,cAAc,CAAA;AACpB,MAAM,eAAe,CAAA;AACrB,MAAM,cAAc,CAAA;;;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emptyServerPureFns.cjs","sources":["../../../../src/aot/emptyServerPureFns.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\n/**\n * Empty server pure functions cache.\n * This file will be replaced by a virtual module by the mion Vite plugin with actual server pure functions when configured.\n */\nexport const serverPureFnsCache: Record<string, Record<string, any>> = {};\n"],"names":[],"mappings":";;AAWO,MAAM,qBAA0D,CAAA;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const serverPureFnsCache: Record<string, Record<string, any>>;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const src_aot_emptyServerPureFns = require("./emptyServerPureFns.cjs");
|
|
4
|
+
exports.serverPureFnsCache = src_aot_emptyServerPureFns.serverPureFnsCache;
|
|
5
|
+
//# sourceMappingURL=serverPureFnsCaches.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serverPureFnsCaches.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"constants.cjs","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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"errors.cjs","sources":["../../../src/errors.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 {\n CoreRouterOptions,\n AnyErrorParams,\n TypedErrorParams,\n DataOnly,\n RpcErrorParams,\n RunTypeError,\n StrNumber,\n} from './types/general.types.ts';\nimport {DEFAULT_CORE_OPTIONS} from './constants.ts';\nimport {randomUUID_V7} from './utils.ts';\nimport {getJitUtils} from './jit/jitUtils.ts';\n\n// ############# Validation Error Types #############\n\n/**\n * Error data structure for validation errors.\n * Contains the list of type errors from parameter validation.\n */\nexport interface ValidationErrorData {\n /** List of type validation errors with paths and expected types */\n typeErrors: RunTypeError[];\n}\n\n/**\n * Strongly typed validation error.\n * Thrown when route or middleFn parameters fail type validation.\n * This type is included in the client error unions so validation errors can be properly typed.\n */\nexport type ValidationError = RpcError<'validation-error', ValidationErrorData>;\n\nlet options: CoreRouterOptions = {...DEFAULT_CORE_OPTIONS};\n\nexport function setErrorOptions(opts: CoreRouterOptions) {\n options = opts;\n}\n\n/**\n * Generic strongly typed error class that can be used outside RPC context.\n * Contains the core error properties: mion@isΣrrθr, type, and message.\n */\nexport class TypedError<ErrType extends string> extends Error {\n /**\n * Unique error identifier,\n * Ideally this should be a symbol but we need to be able to serialize it so a namespaced prop is used instead\n */\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n public readonly 'mion@isΣrrθr': true = true;\n /** Error type, can be used as discriminator in union types*/\n public readonly type: ErrType;\n // Note: message and name are NOT declared as properties here\n // They are inherited from Error class and assigned in constructor\n // This prevents them from being included in type reflection for JIT validation\n\n constructor({message, originalError, type}: TypedErrorParams<ErrType>) {\n const errorMessage = message || originalError?.message || '';\n super(errorMessage);\n this.type = type;\n\n // Set message and name as non-enumerable to exclude from JSON.stringify\n Object.defineProperty(this, 'message', {\n value: errorMessage,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(this, 'name', {\n value: 'TypedError',\n writable: true,\n enumerable: false,\n configurable: true,\n });\n\n if (originalError?.stack) {\n try {\n this.stack = originalError.stack;\n } catch {\n // Fallback to defineProperty if direct assignment fails\n try {\n Object.defineProperty(this, 'stack', {\n value: originalError.stack,\n writable: true,\n configurable: true,\n });\n } catch {\n // If both methods fail, the error will use its own generated stack\n }\n }\n }\n\n Object.setPrototypeOf(this, TypedError.prototype);\n }\n}\n\n// type-rpc-error-start\nexport class RpcError<ErrType extends string, ErrData = any>\n extends TypedError<ErrType>\n implements RpcErrorParams<ErrType, ErrData>\n{\n // Note: name is NOT declared as a property here\n // It is inherited from Error class and assigned in constructor\n // This prevents it from being included in type reflection for JIT validation\n /**\n * id of the error, ideally each error should unique identifiable\n * * if RouterOptions.autoGenerateErrorId is set to true and id with timestamp+uuid will be generated\n * */\n public readonly id?: number | string;\n /** the message that will be returned in the response */\n public readonly publicMessage: string;\n /** options data related to the error, ie validation data, must be json serializable */\n public readonly errorData?: Readonly<ErrData>;\n /** optional http status code */\n statusCode?: number;\n\n constructor({message, publicMessage, originalError, errorData, type, id, statusCode}: AnyErrorParams<ErrType, ErrData>) {\n const originalMessage = message || originalError?.message || publicMessage || '';\n\n // Call parent TypedError constructor\n super({\n message: originalMessage,\n originalError,\n type,\n });\n\n const {autoGenerateErrorId} = options;\n this.id = id ?? (autoGenerateErrorId ? randomUUID_V7() : undefined);\n this.publicMessage = publicMessage || '';\n this.errorData = errorData;\n this.statusCode = statusCode;\n\n // Override name to be non-enumerable\n Object.defineProperty(this, 'name', {\n value: 'RpcError',\n writable: true,\n enumerable: false,\n configurable: true,\n });\n\n Object.setPrototypeOf(this, RpcError.prototype);\n }\n}\n// type-rpc-error-end\n\n// ####### Error Type Guards #######\n\nfunction hasUnknownKeys(obj: Record<StrNumber, any>, keys: StrNumber[]): boolean {\n for (const prop in obj) {\n // iterates over the object keys and if not found prop adds to unknownKeys\n let found = false;\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === prop) {\n found = true;\n break;\n }\n }\n if (!found) return true;\n }\n return false;\n}\n\n/** Returns true if the error is a TypedError or has the same structure. */\nexport function isTypedError(error: any): error is TypedError<any> {\n if (!error) return false;\n if (error instanceof TypedError) return true;\n return (\n error &&\n error['mion@isΣrrθr'] === true &&\n (typeof error.type === 'string' || typeof error.type === 'number') &&\n !hasUnknownKeys(error, ['mion@isΣrrθr', 'type', 'message'])\n );\n}\n\n/** Returns true if the error is a RpcError or has the same structure. */\nexport function isRpcError(error: any): error is RpcError<string> {\n if (!error) return false;\n if (error instanceof RpcError) return true;\n return (\n error &&\n error['mion@isΣrrθr'] === true &&\n (typeof error.type === 'string' || typeof error.type === 'number') &&\n (error.id === undefined || typeof error.id === 'string' || typeof error.id === 'number') &&\n !hasUnknownKeys(error, ['mion@isΣrrθr', 'id', 'message', 'publicMessage', 'errorData', 'type', 'statusCode'])\n );\n}\n\n/**\n * Returns true if the error is a TypedError, RpcError, or any other Javascript Error.\n * if available uses Error.isError() or 'mion@isΣrrθr' prop from TypedError\n * Does not do strict type checking. This function is intended to quickly identify errors.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError\n */\nexport function isAnyError(error: any): error is TypedError<any> | RpcError<string> | Error {\n if (!error) return false;\n const tErr = error as TypedError<string>;\n if (tErr['mion@isΣrrθr'] === true) return true;\n if (typeof (Error as any).isError === 'function') return (Error as any).isError(error);\n return error instanceof Error;\n}\n\nlet errorDeserializersRegistered = false;\n/**\n * Registers error deserializers for TypedError and RpcError.\n * This is required to automatically restore TypedError and RpcError sent over the network.\n */\nexport function registerErrorDeserializers() {\n if (errorDeserializersRegistered) return;\n if (!TypedError || !RpcError) return; // Not loaded yet\n errorDeserializersRegistered = true;\n\n getJitUtils().setDeserializeFn(TypedError, (data: DataOnly<any>) => {\n return new TypedError(data);\n });\n\n getJitUtils().setDeserializeFn(RpcError, (data: DataOnly<any>) => {\n return new RpcError(data);\n });\n}\n"],"names":["DEFAULT_CORE_OPTIONS","randomUUID_V7","getJitUtils"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headers.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"headers.cjs","sources":["../../../src/headers.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\n// type-headers-subset-start\n/** Type-safe wrapper for HTTP headers */\nexport class HeadersSubset<Required extends string, Optional extends string = never> {\n readonly headers: {[K in Required]: string} & {[K in Optional]?: string};\n constructor(headers: {[K in Required]: string} & {[K in Optional]?: string}) {\n this.headers = headers;\n }\n}\n// type-headers-subset-end\n"],"names":[],"mappings":";;MASa,cAAa;AAAA,EACb;AAAA,EACT,YAAY,SAA+D;AACvE,SAAK,UAAU;AAAA,EACnB;AAAA;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pureFn.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"pureFn.cjs","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":["getJitUtils"],"mappings":";;;;;;;AA4BM,SAAU,sBACZ,WACA,YACA,cACA;AAEA,MAAI,CAAC;AAAU,UAAM,IAAI,MAAM,8EAA8E;AAC7G,QAAM,WAAWA,iBAAAA,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,gBAAA,IAAmB,8BAAA;AACjC,MAAI;AACA,iBAAa,KAAK;AAAA,EACtB,QAAQ;AAAA,EAGR;AACA,QAAM,eAAe,gBAAA;AACrB,aAAW,OAAO,cAAc;AAC5B,QAAI,QAAQ;AAAY;AACxB,QAAI,CAAC,SAAS,mBAAmB,SAAS,GAAG;AAAG,eAAS,mBAAmB,KAAK,GAAG;AAAA,EACxF;AAEAA,mBAAAA,cAAc,UAAU,WAAW,QAAQ;AAC3C,SAAO;AACX;;AAGA,SAAS,gCAA6B;AAClC,QAAM,gBAAmB,IAAG,IAAA,CAAA,CAAA,GAAA,CAAA,GAAP,oBAAI;AACzB,QAAM,YAAYA,iBAAAA,YAAA;AAElB,QAAM,SAAS,MAAM,MAAK;AAAA,EAAE;AAE5B,QAAM,QAAQ,IAAI,MAAM,WAAW;AAAA,IAC/B,IAAI,QAAQ,MAAM,UAAQ;AACtB,UAAI,SAAS,eAAe,SAAS,aAAa;AAC9C,eAAA,aAAO,CAAC,IAAY,WAAkB;AAClC,uBAAa,IAAI,MAAM;AAEvB,gBAAM,OAAO,OAAO,UAAU,IAAI,MAAM;AACxC,iBAAO,QAAQ;AAAA,QACnB,GAAC,CAAA,MAAA,UAAA,IAAA,YAAA,CAAA;AAAA,MACL;AACA,UAAI,SAAS,qBAAqB;AAC9B,eAAA,aAAO,CAAC,IAAY,WAAkB;AAClC,uBAAa,IAAI,MAAM;AACvB,iBAAO,OAAO,kBAAkB,IAAI,MAAM;AAAA,QAC9C,GAAC,CAAA,MAAA,UAAA,IAAA,YAAA,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;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pureServerFn.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"pureServerFn.cjs","sources":["../../../../src/pureFns/pureServerFn.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 {PureFnDef, PureServerFnRef} from '../types/pureFunctions.types.ts';\n\n/** The namespace used for all pureServerFn functions */\nexport const PURE_SERVER_FN_NAMESPACE = 'pureServerFn';\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 * Defines a pure server function that will be extracted at build time and executed on the server.\n * At runtime, this returns a lightweight reference containing a PureServerFnRef.\n *\n * The bodyHash is injected at build time by the mion vite plugin's transform hook.\n *\n * Pure Server FN Rules:\n * - No closure variables\n * - No external imports except other pureServerFn references\n * - The 'pureServerFn' namespace is assigned automatically\n * - Functions can be named or anonymous (bodyHash is used as identifier)\n *\n * This is intended so clients can define functions that can be safely executed in the server\n */\nexport function pureServerFn<F extends (...args: any[]) => any>(pureFn: F, bodyHash?: string): PureServerFnRef<F>;\nexport function pureServerFn<F extends (...args: any[]) => any>(def: PureFnDef<F>, bodyHash?: string): PureServerFnRef<F>;\nexport function pureServerFn<F extends (...args: any[]) => any>(\n defOrFn: PureFnDef<F> | F,\n bodyHash?: string // injected by mion vite plugin\n): PureServerFnRef<F> {\n // Important: bodyHash is injected at build time by mion vite plugin\n if (!bodyHash) throw new Error('pureServerFn requires mion vite plugin transform to inject bodyHash');\n const isFn = typeof defOrFn === 'function';\n const def: PureFnDef<F> = isFn ? {pureFn: defOrFn, fnName: bodyHash} : defOrFn;\n const namespace = def.namespace || PURE_SERVER_FN_NAMESPACE;\n // When a plain function is passed directly, always use bodyHash as fnName to avoid collisions\n const fnName = def.fnName || def.pureFn.name || bodyHash;\n const isFactory = def.isFactory || false;\n return {namespace, fnName, bodyHash, pureFn: def.pureFn, isFactory};\n}\n"],"names":[],"mappings":";;;AAUO,MAAM,2BAA2B;;;SA0BxB,aACZ,SACA;AAGA,MAAI,CAAC;AAAU,UAAM,IAAI,MAAM,qEAAqE;AACpG,QAAM,OAAO,OAAO,YAAY;AAChC,QAAM,MAAoB,OAAO,EAAC,QAAQ,SAAS,QAAQ,aAAY;AACvE,QAAM,YAAY,IAAI,aAAa;AAEnC,QAAM,SAAS,IAAI,UAAU,IAAI,OAAO,QAAQ;AAChD,QAAM,YAAY,IAAI,aAAa;AACnC,SAAO,EAAC,WAAW,QAAQ,UAAU,QAAQ,IAAI,QAAQ,UAAA;AAC7D;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"general.types.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -4,7 +4,7 @@ const src_types_general_types = require("./general.types.cjs");
|
|
|
4
4
|
const __ΩRecord = ["K", "T", "Record", `l'e#"Rb!b"Pde"!N#!w#y`];
|
|
5
5
|
const __ΩPick = ["T", "K", "Pick", 'l+e#!e"!fRb!b"Pde""N#!w#y'];
|
|
6
6
|
const __ΩMethodMetadata = ["type", "id", "isAsync", "hasReturnData", "paramNames", "paramsJitHash", "returnJitHash", () => __ΩHeadersMetaData, "headersParam", () => __ΩHeadersMetaData, "headersReturn", "middleFnIds", "pointer", "nestLevel", "MethodMetadata", `P'4!&4")4#)4$&F4%8&4&&4'n(4)8n*4+8&F4,8&F4-'4.Mw/y`];
|
|
7
|
-
const __ΩRemoteMethodOpts = ["runOnError", "validateParams", "validateReturn", "description", () => src_types_general_types.__ΩSerializerMode, "serializer", "isMutation", "RemoteMethodOpts", `P)4!8)4"8)4#8&4$8n%4&8P)-J4'8Mw
|
|
7
|
+
const __ΩRemoteMethodOpts = ["runOnError", "validateParams", "validateReturn", "description", () => src_types_general_types.__ΩSerializerMode, "serializer", "isMutation", "strictTypes", "RemoteMethodOpts", `P)4!8)4"8)4#8&4$8n%4&8P)-J4'8)4(8Mw)y`];
|
|
8
8
|
const __ΩRouteOnlyOptions = [() => __ΩRemoteMethodOpts, false, "runOnError", () => src_types_general_types.__ΩSerializerMode, "serializer", "RouteOnlyOptions", 'Pn!."4#n$4%Mw&y'];
|
|
9
9
|
const __ΩMethodWithOptions = [() => __ΩMethodMetadata, () => __ΩRemoteMethodOpts, "options", "MethodWithOptions", 'Pn!n"4#Mw$y'];
|
|
10
10
|
const __ΩMethodsCache = [() => __ΩRecord, () => __ΩMethodWithOptions, "MethodsCache", '&n"o!#w#y'];
|
package/.dist/cjs/src/utils.cjs
CHANGED
|
@@ -21,11 +21,11 @@ function fromBase64Url(encoded) {
|
|
|
21
21
|
let isTest = void 0;
|
|
22
22
|
function isMionCompileMode() {
|
|
23
23
|
const val = getENV("MION_COMPILE");
|
|
24
|
-
return val === "
|
|
24
|
+
return val === "buildOnly" || val === "middleware";
|
|
25
25
|
}
|
|
26
26
|
function isMionAOTEmitMode() {
|
|
27
27
|
const val = getENV("MION_COMPILE");
|
|
28
|
-
return val === "
|
|
28
|
+
return val === "buildOnly" || val === "middleware" || val === "childProcess";
|
|
29
29
|
}
|
|
30
30
|
function isTestEnv() {
|
|
31
31
|
if (isTest !== void 0) return isTest;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","sources":["../../../src/utils.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 {getJitUtils} from './jit/jitUtils.ts';\nimport type {CompiledPureFunction} from './types/pureFunctions.types.ts';\n\n/** Generates a random UUID V7 (RFC 9562),\n * uses crypto.randomUUID() (v4) as random source as it's a native C++ binding that batches entropy,\n * might be faster than allocating typed arrays via crypto.getRandomValues */\nexport function randomUUID_V7(): string {\n const uuid = crypto.randomUUID();\n const tHex = Date.now().toString(16).padStart(12, '0');\n return `${tHex.substring(0, 8)}-${tHex.substring(8)}-7${uuid.substring(15)}`;\n}\n\n/**\n * Browser-safe function to access environment variables.\n * Returns undefined when running in browser environments where process is not available.\n * @param key - The environment variable key to retrieve\n * @returns The environment variable value or undefined if not available/in browser\n */\nexport function getENV(key: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n// ############# Base64 URL #############\n\n/** Encodes a string to URL-safe base64 (RFC 4648 §5) without padding */\nexport function toBase64Url(str: string): string {\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** Decodes a URL-safe base64 string (RFC 4648 §5) back to a string */\nexport function fromBase64Url(encoded: string): string {\n return atob(encoded.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\nlet isTest: boolean | undefined = undefined;\n/** Whether the process is in mion compile mode (
|
|
1
|
+
{"version":3,"file":"utils.cjs","sources":["../../../src/utils.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 {getJitUtils} from './jit/jitUtils.ts';\nimport type {CompiledPureFunction} from './types/pureFunctions.types.ts';\n\n/** Generates a random UUID V7 (RFC 9562),\n * uses crypto.randomUUID() (v4) as random source as it's a native C++ binding that batches entropy,\n * might be faster than allocating typed arrays via crypto.getRandomValues */\nexport function randomUUID_V7(): string {\n const uuid = crypto.randomUUID();\n const tHex = Date.now().toString(16).padStart(12, '0');\n return `${tHex.substring(0, 8)}-${tHex.substring(8)}-7${uuid.substring(15)}`;\n}\n\n/**\n * Browser-safe function to access environment variables.\n * Returns undefined when running in browser environments where process is not available.\n * @param key - The environment variable key to retrieve\n * @returns The environment variable value or undefined if not available/in browser\n */\nexport function getENV(key: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n// ############# Base64 URL #############\n\n/** Encodes a string to URL-safe base64 (RFC 4648 §5) without padding */\nexport function toBase64Url(str: string): string {\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** Decodes a URL-safe base64 string (RFC 4648 §5) back to a string */\nexport function fromBase64Url(encoded: string): string {\n return atob(encoded.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\nlet isTest: boolean | undefined = undefined;\n/** Whether the process is in mion compile mode (buildOnly or middleware).\n * In these modes platform adapters skip server.listen() — the server does NOT start. */\nexport function isMionCompileMode(): boolean {\n const val = getENV('MION_COMPILE');\n return val === 'buildOnly' || val === 'middleware';\n}\n\n/** Whether AOT caches should be generated and emitted (buildOnly, middleware, or childProcess).\n * Unlike isMionCompileMode(), this also includes 'childProcess' mode where the server DOES start\n * and keeps running after emitting AOT caches via IPC. */\nexport function isMionAOTEmitMode(): boolean {\n const val = getENV('MION_COMPILE');\n return val === 'buildOnly' || val === 'middleware' || val === 'childProcess';\n}\n\nexport function isTestEnv() {\n if (isTest !== undefined) return isTest;\n isTest = getENV('VITEST') !== undefined || getENV('NODE_ENV') === 'test';\n return isTest;\n}\n\n/**\n * Restores the full state of a compiled pure function,\n * The pure function 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 initPureFunction(compiled: CompiledPureFunction): asserts compiled is Required<CompiledPureFunction> {\n if (compiled.fn) return;\n compiled.fn = compiled.createPureFn(getJitUtils());\n}\n"],"names":["getJitUtils"],"mappings":";;;AAaO,SAAS,gBAAwB;AACpC,QAAM,OAAO,OAAO,WAAA;AACpB,QAAM,OAAO,KAAK,MAAM,SAAS,EAAE,EAAE,SAAS,IAAI,GAAG;AACrD,SAAO,GAAG,KAAK,UAAU,GAAG,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;AAC9E;AAQO,SAAS,OAAO,KAAiC;AACpD,MAAI,OAAO,YAAY,eAAe,QAAQ,KAAK;AAC/C,WAAO,QAAQ,IAAI,GAAG;AAAA,EAC1B;AACA,SAAO;AACX;AAKO,SAAS,YAAY,KAAqB;AAC7C,SAAO,KAAK,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE;AAC9E;AAGO,SAAS,cAAc,SAAyB;AACnD,SAAO,KAAK,QAAQ,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG,CAAC;AAC7D;AAEA,IAAI,SAA8B;AAG3B,SAAS,oBAA6B;AACzC,QAAM,MAAM,OAAO,cAAc;AACjC,SAAO,QAAQ,eAAe,QAAQ;AAC1C;AAKO,SAAS,oBAA6B;AACzC,QAAM,MAAM,OAAO,cAAc;AACjC,SAAO,QAAQ,eAAe,QAAQ,gBAAgB,QAAQ;AAClE;AAEO,SAAS,YAAY;AACxB,MAAI,WAAW,OAAW,QAAO;AACjC,WAAS,OAAO,QAAQ,MAAM,UAAa,OAAO,UAAU,MAAM;AAClE,SAAO;AACX;AAOO,SAAS,iBAAiB,UAAoF;AACjH,MAAI,SAAS,GAAI;AACjB,WAAS,KAAK,SAAS,aAAaA,iBAAAA,YAAA,CAAa;AACrD;;;;;;;;;"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { routerCache, pureFnsCache, jitFnsCache } from "./emptyCaches.js";
|
|
2
|
+
import { addAOTCaches, addRoutesToCache } from "@mionjs/core";
|
|
3
|
+
function loadAOTCaches() {
|
|
4
|
+
addAOTCaches(jitFnsCache, pureFnsCache);
|
|
5
|
+
addRoutesToCache(routerCache);
|
|
6
|
+
}
|
|
7
|
+
function getRawAOTCaches() {
|
|
8
|
+
return {
|
|
9
|
+
jitFnsCache,
|
|
10
|
+
pureFnsCache,
|
|
11
|
+
routerCache
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export {
|
|
15
|
+
getRawAOTCaches,
|
|
16
|
+
loadAOTCaches
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=aotCaches.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aotCaches.js","sources":["../../../../src/aot/aotCaches.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\n// this caches will be replaced by a virtual module by the mion Vite plugin with actual AOT caches when AOT is enabled\nimport {jitFnsCache, pureFnsCache, routerCache} from './emptyCaches.ts';\nimport {addAOTCaches, addRoutesToCache} from '@mionjs/core';\n\n/** Loads pre-compiled AOT caches from virtual modules and registers them in the global caches. */\nexport function loadAOTCaches(): void {\n addAOTCaches(jitFnsCache, pureFnsCache);\n addRoutesToCache(routerCache);\n}\n\n/** Returns the global caches. */\nexport function getRawAOTCaches() {\n return {\n jitFnsCache,\n pureFnsCache,\n routerCache,\n };\n}\n"],"names":[],"mappings":";;AAYO,SAAS,gBAAsB;AAClC,eAAa,aAAa,YAAY;AACtC,mBAAiB,WAAW;AAChC;AAGO,SAAS,kBAAkB;AAC9B,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAER;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emptyCaches.js","sources":["../../../../src/aot/emptyCaches.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\n/**\n * Empty AOT caches.\n * This file will be replaced by a virtual module by the mion Vite plugin with actual AOT caches when AOT is enabled.\n */\nexport const jitFnsCache = {};\nexport const pureFnsCache = {};\nexport const routerCache = {};\n"],"names":[],"mappings":"AAWO,MAAM,cAAc,CAAA;AACpB,MAAM,eAAe,CAAA;AACrB,MAAM,cAAc,CAAA;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const serverPureFnsCache: Record<string, Record<string, any>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"emptyServerPureFns.js","sources":["../../../../src/aot/emptyServerPureFns.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\n/**\n * Empty server pure functions cache.\n * This file will be replaced by a virtual module by the mion Vite plugin with actual server pure functions when configured.\n */\nexport const serverPureFnsCache: Record<string, Record<string, any>> = {};\n"],"names":[],"mappings":"AAWO,MAAM,qBAA0D,CAAA;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serverPureFnsCaches.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"errors.js","sources":["../../../src/errors.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 {\n CoreRouterOptions,\n AnyErrorParams,\n TypedErrorParams,\n DataOnly,\n RpcErrorParams,\n RunTypeError,\n StrNumber,\n} from './types/general.types.ts';\nimport {DEFAULT_CORE_OPTIONS} from './constants.ts';\nimport {randomUUID_V7} from './utils.ts';\nimport {getJitUtils} from './jit/jitUtils.ts';\n\n// ############# Validation Error Types #############\n\n/**\n * Error data structure for validation errors.\n * Contains the list of type errors from parameter validation.\n */\nexport interface ValidationErrorData {\n /** List of type validation errors with paths and expected types */\n typeErrors: RunTypeError[];\n}\n\n/**\n * Strongly typed validation error.\n * Thrown when route or middleFn parameters fail type validation.\n * This type is included in the client error unions so validation errors can be properly typed.\n */\nexport type ValidationError = RpcError<'validation-error', ValidationErrorData>;\n\nlet options: CoreRouterOptions = {...DEFAULT_CORE_OPTIONS};\n\nexport function setErrorOptions(opts: CoreRouterOptions) {\n options = opts;\n}\n\n/**\n * Generic strongly typed error class that can be used outside RPC context.\n * Contains the core error properties: mion@isΣrrθr, type, and message.\n */\nexport class TypedError<ErrType extends string> extends Error {\n /**\n * Unique error identifier,\n * Ideally this should be a symbol but we need to be able to serialize it so a namespaced prop is used instead\n */\n // eslint-disable-next-line @typescript-eslint/prefer-as-const\n public readonly 'mion@isΣrrθr': true = true;\n /** Error type, can be used as discriminator in union types*/\n public readonly type: ErrType;\n // Note: message and name are NOT declared as properties here\n // They are inherited from Error class and assigned in constructor\n // This prevents them from being included in type reflection for JIT validation\n\n constructor({message, originalError, type}: TypedErrorParams<ErrType>) {\n const errorMessage = message || originalError?.message || '';\n super(errorMessage);\n this.type = type;\n\n // Set message and name as non-enumerable to exclude from JSON.stringify\n Object.defineProperty(this, 'message', {\n value: errorMessage,\n writable: true,\n enumerable: false,\n configurable: true,\n });\n Object.defineProperty(this, 'name', {\n value: 'TypedError',\n writable: true,\n enumerable: false,\n configurable: true,\n });\n\n if (originalError?.stack) {\n try {\n this.stack = originalError.stack;\n } catch {\n // Fallback to defineProperty if direct assignment fails\n try {\n Object.defineProperty(this, 'stack', {\n value: originalError.stack,\n writable: true,\n configurable: true,\n });\n } catch {\n // If both methods fail, the error will use its own generated stack\n }\n }\n }\n\n Object.setPrototypeOf(this, TypedError.prototype);\n }\n}\n\n// type-rpc-error-start\nexport class RpcError<ErrType extends string, ErrData = any>\n extends TypedError<ErrType>\n implements RpcErrorParams<ErrType, ErrData>\n{\n // Note: name is NOT declared as a property here\n // It is inherited from Error class and assigned in constructor\n // This prevents it from being included in type reflection for JIT validation\n /**\n * id of the error, ideally each error should unique identifiable\n * * if RouterOptions.autoGenerateErrorId is set to true and id with timestamp+uuid will be generated\n * */\n public readonly id?: number | string;\n /** the message that will be returned in the response */\n public readonly publicMessage: string;\n /** options data related to the error, ie validation data, must be json serializable */\n public readonly errorData?: Readonly<ErrData>;\n /** optional http status code */\n statusCode?: number;\n\n constructor({message, publicMessage, originalError, errorData, type, id, statusCode}: AnyErrorParams<ErrType, ErrData>) {\n const originalMessage = message || originalError?.message || publicMessage || '';\n\n // Call parent TypedError constructor\n super({\n message: originalMessage,\n originalError,\n type,\n });\n\n const {autoGenerateErrorId} = options;\n this.id = id ?? (autoGenerateErrorId ? randomUUID_V7() : undefined);\n this.publicMessage = publicMessage || '';\n this.errorData = errorData;\n this.statusCode = statusCode;\n\n // Override name to be non-enumerable\n Object.defineProperty(this, 'name', {\n value: 'RpcError',\n writable: true,\n enumerable: false,\n configurable: true,\n });\n\n Object.setPrototypeOf(this, RpcError.prototype);\n }\n}\n// type-rpc-error-end\n\n// ####### Error Type Guards #######\n\nfunction hasUnknownKeys(obj: Record<StrNumber, any>, keys: StrNumber[]): boolean {\n for (const prop in obj) {\n // iterates over the object keys and if not found prop adds to unknownKeys\n let found = false;\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === prop) {\n found = true;\n break;\n }\n }\n if (!found) return true;\n }\n return false;\n}\n\n/** Returns true if the error is a TypedError or has the same structure. */\nexport function isTypedError(error: any): error is TypedError<any> {\n if (!error) return false;\n if (error instanceof TypedError) return true;\n return (\n error &&\n error['mion@isΣrrθr'] === true &&\n (typeof error.type === 'string' || typeof error.type === 'number') &&\n !hasUnknownKeys(error, ['mion@isΣrrθr', 'type', 'message'])\n );\n}\n\n/** Returns true if the error is a RpcError or has the same structure. */\nexport function isRpcError(error: any): error is RpcError<string> {\n if (!error) return false;\n if (error instanceof RpcError) return true;\n return (\n error &&\n error['mion@isΣrrθr'] === true &&\n (typeof error.type === 'string' || typeof error.type === 'number') &&\n (error.id === undefined || typeof error.id === 'string' || typeof error.id === 'number') &&\n !hasUnknownKeys(error, ['mion@isΣrrθr', 'id', 'message', 'publicMessage', 'errorData', 'type', 'statusCode'])\n );\n}\n\n/**\n * Returns true if the error is a TypedError, RpcError, or any other Javascript Error.\n * if available uses Error.isError() or 'mion@isΣrrθr' prop from TypedError\n * Does not do strict type checking. This function is intended to quickly identify errors.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError\n */\nexport function isAnyError(error: any): error is TypedError<any> | RpcError<string> | Error {\n if (!error) return false;\n const tErr = error as TypedError<string>;\n if (tErr['mion@isΣrrθr'] === true) return true;\n if (typeof (Error as any).isError === 'function') return (Error as any).isError(error);\n return error instanceof Error;\n}\n\nlet errorDeserializersRegistered = false;\n/**\n * Registers error deserializers for TypedError and RpcError.\n * This is required to automatically restore TypedError and RpcError sent over the network.\n */\nexport function registerErrorDeserializers() {\n if (errorDeserializersRegistered) return;\n if (!TypedError || !RpcError) return; // Not loaded yet\n errorDeserializersRegistered = true;\n\n getJitUtils().setDeserializeFn(TypedError, (data: DataOnly<any>) => {\n return new TypedError(data);\n });\n\n getJitUtils().setDeserializeFn(RpcError, (data: DataOnly<any>) => {\n return new RpcError(data);\n });\n}\n"],"names":[],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headers.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"headers.js","sources":["../../../src/headers.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\n// type-headers-subset-start\n/** Type-safe wrapper for HTTP headers */\nexport class HeadersSubset<Required extends string, Optional extends string = never> {\n readonly headers: {[K in Required]: string} & {[K in Optional]?: string};\n constructor(headers: {[K in Required]: string} & {[K in Optional]?: string}) {\n this.headers = headers;\n }\n}\n// type-headers-subset-end\n"],"names":[],"mappings":"MASa,cAAa;AAAA,EACb;AAAA,EACT,YAAY,SAA+D;AACvE,SAAK,UAAU;AAAA,EACnB;AAAA;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pureFn.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
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,gBAAA,IAAmB,8BAAA;AACjC,MAAI;AACA,iBAAa,KAAK;AAAA,EACtB,QAAQ;AAAA,EAGR;AACA,QAAM,eAAe,gBAAA;AACrB,aAAW,OAAO,cAAc;AAC5B,QAAI,QAAQ;AAAY;AACxB,QAAI,CAAC,SAAS,mBAAmB,SAAS,GAAG;AAAG,eAAS,mBAAmB,KAAK,GAAG;AAAA,EACxF;AAEA,gBAAc,UAAU,WAAW,QAAQ;AAC3C,SAAO;AACX;;AAGA,SAAS,gCAA6B;AAClC,QAAM,gBAAmB,IAAG,IAAA,CAAA,CAAA,GAAA,CAAA,GAAP,oBAAI;AACzB,QAAM,YAAY,YAAA;AAElB,QAAM,SAAS,MAAM,MAAK;AAAA,EAAE;AAE5B,QAAM,QAAQ,IAAI,MAAM,WAAW;AAAA,IAC/B,IAAI,QAAQ,MAAM,UAAQ;AACtB,UAAI,SAAS,eAAe,SAAS,aAAa;AAC9C,eAAA,aAAO,CAAC,IAAY,WAAkB;AAClC,uBAAa,IAAI,MAAM;AAEvB,gBAAM,OAAO,OAAO,UAAU,IAAI,MAAM;AACxC,iBAAO,QAAQ;AAAA,QACnB,GAAC,CAAA,MAAA,UAAA,IAAA,YAAA,CAAA;AAAA,MACL;AACA,UAAI,SAAS,qBAAqB;AAC9B,eAAA,aAAO,CAAC,IAAY,WAAkB;AAClC,uBAAa,IAAI,MAAM;AACvB,iBAAO,OAAO,kBAAkB,IAAI,MAAM;AAAA,QAC9C,GAAC,CAAA,MAAA,UAAA,IAAA,YAAA,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;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pureServerFn.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"pureServerFn.js","sources":["../../../../src/pureFns/pureServerFn.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 {PureFnDef, PureServerFnRef} from '../types/pureFunctions.types.ts';\n\n/** The namespace used for all pureServerFn functions */\nexport const PURE_SERVER_FN_NAMESPACE = 'pureServerFn';\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 * Defines a pure server function that will be extracted at build time and executed on the server.\n * At runtime, this returns a lightweight reference containing a PureServerFnRef.\n *\n * The bodyHash is injected at build time by the mion vite plugin's transform hook.\n *\n * Pure Server FN Rules:\n * - No closure variables\n * - No external imports except other pureServerFn references\n * - The 'pureServerFn' namespace is assigned automatically\n * - Functions can be named or anonymous (bodyHash is used as identifier)\n *\n * This is intended so clients can define functions that can be safely executed in the server\n */\nexport function pureServerFn<F extends (...args: any[]) => any>(pureFn: F, bodyHash?: string): PureServerFnRef<F>;\nexport function pureServerFn<F extends (...args: any[]) => any>(def: PureFnDef<F>, bodyHash?: string): PureServerFnRef<F>;\nexport function pureServerFn<F extends (...args: any[]) => any>(\n defOrFn: PureFnDef<F> | F,\n bodyHash?: string // injected by mion vite plugin\n): PureServerFnRef<F> {\n // Important: bodyHash is injected at build time by mion vite plugin\n if (!bodyHash) throw new Error('pureServerFn requires mion vite plugin transform to inject bodyHash');\n const isFn = typeof defOrFn === 'function';\n const def: PureFnDef<F> = isFn ? {pureFn: defOrFn, fnName: bodyHash} : defOrFn;\n const namespace = def.namespace || PURE_SERVER_FN_NAMESPACE;\n // When a plain function is passed directly, always use bodyHash as fnName to avoid collisions\n const fnName = def.fnName || def.pureFn.name || bodyHash;\n const isFactory = def.isFactory || false;\n return {namespace, fnName, bodyHash, pureFn: def.pureFn, isFactory};\n}\n"],"names":[],"mappings":";AAUO,MAAM,2BAA2B;;;SA0BxB,aACZ,SACA;AAGA,MAAI,CAAC;AAAU,UAAM,IAAI,MAAM,qEAAqE;AACpG,QAAM,OAAO,OAAO,YAAY;AAChC,QAAM,MAAoB,OAAO,EAAC,QAAQ,SAAS,QAAQ,aAAY;AACvE,QAAM,YAAY,IAAI,aAAa;AAEnC,QAAM,SAAS,IAAI,UAAU,IAAI,OAAO,QAAQ;AAChD,QAAM,YAAY,IAAI,aAAa;AACnC,SAAO,EAAC,WAAW,QAAQ,UAAU,QAAQ,IAAI,QAAQ,UAAA;AAC7D;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"general.types.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"general.types.js","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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -2,7 +2,7 @@ import { __ΩJitCompiledFunctions as ___JitCompiledFunctions, __ΩSerializerMode
|
|
|
2
2
|
const __ΩRecord = ["K", "T", "Record", `l'e#"Rb!b"Pde"!N#!w#y`];
|
|
3
3
|
const __ΩPick = ["T", "K", "Pick", 'l+e#!e"!fRb!b"Pde""N#!w#y'];
|
|
4
4
|
const __ΩMethodMetadata = ["type", "id", "isAsync", "hasReturnData", "paramNames", "paramsJitHash", "returnJitHash", () => __ΩHeadersMetaData, "headersParam", () => __ΩHeadersMetaData, "headersReturn", "middleFnIds", "pointer", "nestLevel", "MethodMetadata", `P'4!&4")4#)4$&F4%8&4&&4'n(4)8n*4+8&F4,8&F4-'4.Mw/y`];
|
|
5
|
-
const __ΩRemoteMethodOpts = ["runOnError", "validateParams", "validateReturn", "description", () => ___SerializerMode, "serializer", "isMutation", "RemoteMethodOpts", `P)4!8)4"8)4#8&4$8n%4&8P)-J4'8Mw
|
|
5
|
+
const __ΩRemoteMethodOpts = ["runOnError", "validateParams", "validateReturn", "description", () => ___SerializerMode, "serializer", "isMutation", "strictTypes", "RemoteMethodOpts", `P)4!8)4"8)4#8&4$8n%4&8P)-J4'8)4(8Mw)y`];
|
|
6
6
|
const __ΩRouteOnlyOptions = [() => __ΩRemoteMethodOpts, false, "runOnError", () => ___SerializerMode, "serializer", "RouteOnlyOptions", 'Pn!."4#n$4%Mw&y'];
|
|
7
7
|
const __ΩMethodWithOptions = [() => __ΩMethodMetadata, () => __ΩRemoteMethodOpts, "options", "MethodWithOptions", 'Pn!n"4#Mw$y'];
|
|
8
8
|
const __ΩMethodsCache = [() => __ΩRecord, () => __ΩMethodWithOptions, "MethodsCache", '&n"o!#w#y'];
|
package/.dist/esm/src/utils.js
CHANGED
|
@@ -19,11 +19,11 @@ function fromBase64Url(encoded) {
|
|
|
19
19
|
let isTest = void 0;
|
|
20
20
|
function isMionCompileMode() {
|
|
21
21
|
const val = getENV("MION_COMPILE");
|
|
22
|
-
return val === "
|
|
22
|
+
return val === "buildOnly" || val === "middleware";
|
|
23
23
|
}
|
|
24
24
|
function isMionAOTEmitMode() {
|
|
25
25
|
const val = getENV("MION_COMPILE");
|
|
26
|
-
return val === "
|
|
26
|
+
return val === "buildOnly" || val === "middleware" || val === "childProcess";
|
|
27
27
|
}
|
|
28
28
|
function isTestEnv() {
|
|
29
29
|
if (isTest !== void 0) return isTest;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../src/utils.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 {getJitUtils} from './jit/jitUtils.ts';\nimport type {CompiledPureFunction} from './types/pureFunctions.types.ts';\n\n/** Generates a random UUID V7 (RFC 9562),\n * uses crypto.randomUUID() (v4) as random source as it's a native C++ binding that batches entropy,\n * might be faster than allocating typed arrays via crypto.getRandomValues */\nexport function randomUUID_V7(): string {\n const uuid = crypto.randomUUID();\n const tHex = Date.now().toString(16).padStart(12, '0');\n return `${tHex.substring(0, 8)}-${tHex.substring(8)}-7${uuid.substring(15)}`;\n}\n\n/**\n * Browser-safe function to access environment variables.\n * Returns undefined when running in browser environments where process is not available.\n * @param key - The environment variable key to retrieve\n * @returns The environment variable value or undefined if not available/in browser\n */\nexport function getENV(key: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n// ############# Base64 URL #############\n\n/** Encodes a string to URL-safe base64 (RFC 4648 §5) without padding */\nexport function toBase64Url(str: string): string {\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** Decodes a URL-safe base64 string (RFC 4648 §5) back to a string */\nexport function fromBase64Url(encoded: string): string {\n return atob(encoded.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\nlet isTest: boolean | undefined = undefined;\n/** Whether the process is in mion compile mode (
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../src/utils.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 {getJitUtils} from './jit/jitUtils.ts';\nimport type {CompiledPureFunction} from './types/pureFunctions.types.ts';\n\n/** Generates a random UUID V7 (RFC 9562),\n * uses crypto.randomUUID() (v4) as random source as it's a native C++ binding that batches entropy,\n * might be faster than allocating typed arrays via crypto.getRandomValues */\nexport function randomUUID_V7(): string {\n const uuid = crypto.randomUUID();\n const tHex = Date.now().toString(16).padStart(12, '0');\n return `${tHex.substring(0, 8)}-${tHex.substring(8)}-7${uuid.substring(15)}`;\n}\n\n/**\n * Browser-safe function to access environment variables.\n * Returns undefined when running in browser environments where process is not available.\n * @param key - The environment variable key to retrieve\n * @returns The environment variable value or undefined if not available/in browser\n */\nexport function getENV(key: string): string | undefined {\n if (typeof process !== 'undefined' && process.env) {\n return process.env[key];\n }\n return undefined;\n}\n\n// ############# Base64 URL #############\n\n/** Encodes a string to URL-safe base64 (RFC 4648 §5) without padding */\nexport function toBase64Url(str: string): string {\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** Decodes a URL-safe base64 string (RFC 4648 §5) back to a string */\nexport function fromBase64Url(encoded: string): string {\n return atob(encoded.replace(/-/g, '+').replace(/_/g, '/'));\n}\n\nlet isTest: boolean | undefined = undefined;\n/** Whether the process is in mion compile mode (buildOnly or middleware).\n * In these modes platform adapters skip server.listen() — the server does NOT start. */\nexport function isMionCompileMode(): boolean {\n const val = getENV('MION_COMPILE');\n return val === 'buildOnly' || val === 'middleware';\n}\n\n/** Whether AOT caches should be generated and emitted (buildOnly, middleware, or childProcess).\n * Unlike isMionCompileMode(), this also includes 'childProcess' mode where the server DOES start\n * and keeps running after emitting AOT caches via IPC. */\nexport function isMionAOTEmitMode(): boolean {\n const val = getENV('MION_COMPILE');\n return val === 'buildOnly' || val === 'middleware' || val === 'childProcess';\n}\n\nexport function isTestEnv() {\n if (isTest !== undefined) return isTest;\n isTest = getENV('VITEST') !== undefined || getENV('NODE_ENV') === 'test';\n return isTest;\n}\n\n/**\n * Restores the full state of a compiled pure function,\n * The pure function 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 initPureFunction(compiled: CompiledPureFunction): asserts compiled is Required<CompiledPureFunction> {\n if (compiled.fn) return;\n compiled.fn = compiled.createPureFn(getJitUtils());\n}\n"],"names":[],"mappings":";AAaO,SAAS,gBAAwB;AACpC,QAAM,OAAO,OAAO,WAAA;AACpB,QAAM,OAAO,KAAK,MAAM,SAAS,EAAE,EAAE,SAAS,IAAI,GAAG;AACrD,SAAO,GAAG,KAAK,UAAU,GAAG,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;AAC9E;AAQO,SAAS,OAAO,KAAiC;AACpD,MAAI,OAAO,YAAY,eAAe,QAAQ,KAAK;AAC/C,WAAO,QAAQ,IAAI,GAAG;AAAA,EAC1B;AACA,SAAO;AACX;AAKO,SAAS,YAAY,KAAqB;AAC7C,SAAO,KAAK,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE;AAC9E;AAGO,SAAS,cAAc,SAAyB;AACnD,SAAO,KAAK,QAAQ,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG,CAAC;AAC7D;AAEA,IAAI,SAA8B;AAG3B,SAAS,oBAA6B;AACzC,QAAM,MAAM,OAAO,cAAc;AACjC,SAAO,QAAQ,eAAe,QAAQ;AAC1C;AAKO,SAAS,oBAA6B;AACzC,QAAM,MAAM,OAAO,cAAc;AACjC,SAAO,QAAQ,eAAe,QAAQ,gBAAgB,QAAQ;AAClE;AAEO,SAAS,YAAY;AACxB,MAAI,WAAW,OAAW,QAAO;AACjC,WAAS,OAAO,QAAQ,MAAM,UAAa,OAAO,UAAU,MAAM;AAClE,SAAO;AACX;AAOO,SAAS,iBAAiB,UAAoF;AACjH,MAAI,SAAS,GAAI;AACjB,WAAS,KAAK,SAAS,aAAa,YAAA,CAAa;AACrD;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mionjs/core",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.4-alpha.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Core functionality required across multiple mion packages",
|
|
6
6
|
"keywords": [
|
|
@@ -26,6 +26,18 @@
|
|
|
26
26
|
"types": "./.dist/esm/index.d.ts",
|
|
27
27
|
"require": "./.dist/cjs/index.cjs",
|
|
28
28
|
"default": "./.dist/esm/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./aot-caches": {
|
|
31
|
+
"source": "./src/aot/aotCaches.ts",
|
|
32
|
+
"types": "./.dist/esm/src/aot/aotCaches.d.ts",
|
|
33
|
+
"require": "./.dist/cjs/src/aot/aotCaches.cjs",
|
|
34
|
+
"default": "./.dist/esm/src/aot/aotCaches.js"
|
|
35
|
+
},
|
|
36
|
+
"./server-pure-fns": {
|
|
37
|
+
"source": "./src/aot/serverPureFnsCaches.ts",
|
|
38
|
+
"types": "./.dist/esm/src/aot/serverPureFnsCaches.d.ts",
|
|
39
|
+
"require": "./.dist/cjs/src/aot/serverPureFnsCaches.cjs",
|
|
40
|
+
"default": "./.dist/esm/src/aot/serverPureFnsCaches.js"
|
|
29
41
|
}
|
|
30
42
|
},
|
|
31
43
|
"directories": {
|
|
@@ -54,5 +66,5 @@
|
|
|
54
66
|
"bugs": {
|
|
55
67
|
"url": "https://github.com/MionKit/mion/issues"
|
|
56
68
|
},
|
|
57
|
-
"gitHead": "
|
|
69
|
+
"gitHead": "26f07a965e43529d4255e6f2ac8a633513026314"
|
|
58
70
|
}
|