@mionjs/run-types 0.8.3-alpha.0 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dist/cjs/src/constants.cjs.map +1 -1
- package/.dist/cjs/src/constants.functions.cjs.map +1 -1
- package/.dist/cjs/src/constants.kind.cjs.map +1 -1
- package/.dist/cjs/src/createRunType.cjs.map +1 -1
- package/.dist/cjs/src/createRunTypeFunctions.cjs.map +1 -1
- package/.dist/cjs/src/jitCompilers/json/toJsCode.cjs +34 -26
- package/.dist/cjs/src/jitCompilers/json/toJsCode.cjs.map +1 -1
- package/.dist/cjs/src/lib/baseRunTypes.cjs +0 -31
- package/.dist/cjs/src/lib/baseRunTypes.cjs.map +1 -1
- package/.dist/cjs/src/lib/baseRunTypes.d.ts +0 -2
- package/.dist/cjs/src/lib/jitFnCompiler.cjs +6 -4
- package/.dist/cjs/src/lib/jitFnCompiler.cjs.map +1 -1
- package/.dist/cjs/src/lib/jitFnCompiler.d.ts +2 -2
- package/.dist/cjs/src/nodes/atomic/any.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/bigInt.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/boolean.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/date.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/enum.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/enumMember.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/literal.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/never.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/null.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/number.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/object.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/regexp.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/string.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/symbol.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/undefined.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/unknown.cjs.map +1 -1
- package/.dist/cjs/src/nodes/atomic/void.cjs.map +1 -1
- package/.dist/cjs/src/nodes/collection/class.cjs.map +1 -1
- package/.dist/cjs/src/nodes/collection/functionParams.cjs.map +1 -1
- package/.dist/cjs/src/nodes/collection/interface.cjs +24 -4
- package/.dist/cjs/src/nodes/collection/interface.cjs.map +1 -1
- package/.dist/cjs/src/nodes/collection/intersection.cjs.map +1 -1
- package/.dist/cjs/src/nodes/collection/tuple.cjs.map +1 -1
- package/.dist/cjs/src/nodes/collection/union.cjs.map +1 -1
- package/.dist/cjs/src/nodes/collection/unionDiscriminator.cjs.map +1 -1
- package/.dist/cjs/src/nodes/function/function.cjs +22 -18
- package/.dist/cjs/src/nodes/function/function.cjs.map +1 -1
- package/.dist/cjs/src/nodes/function/function.d.ts +1 -0
- package/.dist/cjs/src/nodes/member/array.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/callSignature.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/genericMember.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/indexProperty.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/method.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/methodSignature.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/param.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/property.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/restParams.cjs.map +1 -1
- package/.dist/cjs/src/nodes/member/tupleMember.cjs.map +1 -1
- package/.dist/cjs/src/nodes/native/Iterable.cjs.map +1 -1
- package/.dist/cjs/src/nodes/native/map.cjs.map +1 -1
- package/.dist/cjs/src/nodes/native/nonSerializable.cjs.map +1 -1
- package/.dist/cjs/src/nodes/native/promise.cjs.map +1 -1
- package/.dist/cjs/src/nodes/native/set.cjs.map +1 -1
- package/.dist/cjs/src/run-types-pure-fns.cjs.map +1 -1
- package/.dist/cjs/src/types.cjs +1 -1
- package/.dist/cjs/src/types.d.ts +1 -0
- package/.dist/esm/src/constants.functions.js.map +1 -1
- package/.dist/esm/src/constants.js.map +1 -1
- package/.dist/esm/src/constants.kind.js.map +1 -1
- package/.dist/esm/src/createRunType.js.map +1 -1
- package/.dist/esm/src/createRunTypeFunctions.js.map +1 -1
- package/.dist/esm/src/jitCompilers/json/toJsCode.js +34 -26
- package/.dist/esm/src/jitCompilers/json/toJsCode.js.map +1 -1
- package/.dist/esm/src/lib/baseRunTypes.d.ts +0 -2
- package/.dist/esm/src/lib/baseRunTypes.js +1 -32
- package/.dist/esm/src/lib/baseRunTypes.js.map +1 -1
- package/.dist/esm/src/lib/jitFnCompiler.d.ts +2 -2
- package/.dist/esm/src/lib/jitFnCompiler.js +6 -4
- package/.dist/esm/src/lib/jitFnCompiler.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/any.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/bigInt.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/boolean.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/date.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/enum.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/enumMember.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/literal.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/never.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/null.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/number.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/object.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/regexp.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/string.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/symbol.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/undefined.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/unknown.js.map +1 -1
- package/.dist/esm/src/nodes/atomic/void.js.map +1 -1
- package/.dist/esm/src/nodes/collection/class.js.map +1 -1
- package/.dist/esm/src/nodes/collection/functionParams.js.map +1 -1
- package/.dist/esm/src/nodes/collection/interface.js +24 -4
- package/.dist/esm/src/nodes/collection/interface.js.map +1 -1
- package/.dist/esm/src/nodes/collection/intersection.js.map +1 -1
- package/.dist/esm/src/nodes/collection/tuple.js.map +1 -1
- package/.dist/esm/src/nodes/collection/union.js.map +1 -1
- package/.dist/esm/src/nodes/collection/unionDiscriminator.js.map +1 -1
- package/.dist/esm/src/nodes/function/function.d.ts +1 -0
- package/.dist/esm/src/nodes/function/function.js +22 -18
- package/.dist/esm/src/nodes/function/function.js.map +1 -1
- package/.dist/esm/src/nodes/member/array.js.map +1 -1
- package/.dist/esm/src/nodes/member/callSignature.js.map +1 -1
- package/.dist/esm/src/nodes/member/genericMember.js.map +1 -1
- package/.dist/esm/src/nodes/member/indexProperty.js.map +1 -1
- package/.dist/esm/src/nodes/member/method.js.map +1 -1
- package/.dist/esm/src/nodes/member/methodSignature.js.map +1 -1
- package/.dist/esm/src/nodes/member/param.js.map +1 -1
- package/.dist/esm/src/nodes/member/property.js.map +1 -1
- package/.dist/esm/src/nodes/member/restParams.js.map +1 -1
- package/.dist/esm/src/nodes/member/tupleMember.js.map +1 -1
- package/.dist/esm/src/nodes/native/Iterable.js.map +1 -1
- package/.dist/esm/src/nodes/native/map.js.map +1 -1
- package/.dist/esm/src/nodes/native/nonSerializable.js.map +1 -1
- package/.dist/esm/src/nodes/native/promise.js.map +1 -1
- package/.dist/esm/src/nodes/native/set.js.map +1 -1
- package/.dist/esm/src/run-types-pure-fns.js.map +1 -1
- package/.dist/esm/src/types.d.ts +1 -0
- package/.dist/esm/src/types.js +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRunType.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"createRunType.js","sources":["../../../src/createRunType.ts"],"sourcesContent":["/* eslint-disable no-case-declarations */\n/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {RunType, Mutable, SrcType} from './types.ts';\nimport type {BaseRunType} from './lib/baseRunTypes.ts';\nimport type {TypeClass, Type} from '@deepkit/type';\nimport {ReflectionKind, resolveReceiveType, ReceiveType, reflect, typeAnnotation, stringifyType} from '@deepkit/type';\nimport {\n hasArguments,\n hasExtendsArguments,\n hasImplements,\n hasIndexType,\n hasParameters,\n hasReturn,\n hasType,\n hasTypes,\n isNativeUtilityStringTypes,\n isNonSerializableClass,\n isNonSerializableObject,\n} from './lib/guards.ts';\nimport {StringRunType} from './nodes/atomic/string.ts';\nimport {DateRunType} from './nodes/atomic/date.ts';\nimport {NumberRunType} from './nodes/atomic/number.ts';\nimport {BooleanRunType} from './nodes/atomic/boolean.ts';\nimport {NullRunType} from './nodes/atomic/null.ts';\nimport {BigIntRunType} from './nodes/atomic/bigInt.ts';\nimport {AnyRunType} from './nodes/atomic/any.ts';\nimport {UndefinedRunType} from './nodes/atomic/undefined.ts';\nimport {UnknownRunType} from './nodes/atomic/unknown.ts';\nimport {VoidRunType} from './nodes/atomic/void.ts';\nimport {ArrayRunType} from './nodes/member/array.ts';\nimport {LiteralRunType} from './nodes/atomic/literal.ts';\nimport {RegexpRunType} from './nodes/atomic/regexp.ts';\nimport {NeverRunType} from './nodes/atomic/never.ts';\nimport {EnumRunType} from './nodes/atomic/enum.ts';\nimport {EnumMemberRunType} from './nodes/atomic/enumMember.ts';\nimport {UnionRunType} from './nodes/collection/union.ts';\nimport {TupleRunType} from './nodes/collection/tuple.ts';\nimport {FunctionParamsRunType} from './nodes/collection/functionParams.ts';\nimport {TupleMemberRunType} from './nodes/member/tupleMember.ts';\nimport {InterfaceRunType} from './nodes/collection/interface.ts';\nimport {PropertyRunType} from './nodes/member/property.ts';\nimport {IndexSignatureRunType} from './nodes/member/indexProperty.ts';\nimport {MethodSignatureRunType} from './nodes/member/methodSignature.ts';\nimport {CallSignatureRunType} from './nodes/member/callSignature.ts';\nimport {FunctionRunType} from './nodes/function/function.ts';\nimport {PromiseRunType} from './nodes/native/promise.ts';\nimport {ObjectRunType} from './nodes/atomic/object.ts';\nimport {IntersectionRunType} from './nodes/collection/intersection.ts';\nimport {ParameterRunType} from './nodes/member/param.ts';\nimport {MethodRunType} from './nodes/member/method.ts';\nimport {RestParamsRunType} from './nodes/member/restParams.ts';\nimport {ClassRunType} from './nodes/collection/class.ts';\nimport {MapRunType} from './nodes/native/map.ts';\nimport {ReflectionSubKind} from './constants.kind.ts';\nimport {SetRunType} from './nodes/native/set.ts';\nimport {SymbolRunType} from './nodes/atomic/symbol.ts';\nimport {NonSerializableRunType} from './nodes/native/nonSerializable.ts';\nimport {registerErrorDeserializers} from '@mionjs/core';\n\nexport function runType<T>(type?: ReceiveType<T>): RunType {\n const start = Date.now();\n const src = resolveReceiveType(type) as SrcType;\n const took0 = Date.now() - start;\n createRunTypes(src);\n const took1 = Date.now() - start;\n const diff = took1 - took0;\n // max RunType overhead 60 ms\n if (diff > 60) console.warn(`RunType overhead is very long: ${diff}ms for ${stringifyType(src)}`);\n return src._rt;\n}\n\nexport function reflectFunction<Fn extends (...args: any[]) => any>(fn: Fn): FunctionRunType {\n const src = reflect(fn) as SrcType;\n runType(src);\n return src._rt as FunctionRunType;\n}\n\n// We need to traverse all possible associated nodes to create all the runTypes\nfunction createRunTypes(src: SrcType): void {\n registerErrorDeserializers();\n const stack: Type[] = [src];\n\n while (stack.length > 0) {\n const current = stack.pop();\n if (!current || (current as SrcType)._rt) continue;\n\n try {\n createRunType(current as Mutable<SrcType>);\n } catch (error) {\n const typesStackMessage = '\\nTypes Stack: ' + stack.map((t) => t.typeName || t.kind).join(', ');\n (error as Error).message += typesStackMessage;\n throw error;\n }\n\n // single child type nodes\n if (hasType(current)) stack.push(current.type);\n if (hasReturn(current)) stack.push(current.return);\n if (hasIndexType(current)) stack.push(current.indexType);\n if (current.origin) stack.push(current.origin);\n if (current.indexAccessOrigin?.index) stack.push(current.indexAccessOrigin?.index);\n if (current.indexAccessOrigin?.container) stack.push(current.indexAccessOrigin?.container);\n\n // multiple child type nodes\n if (hasTypes(current)) pushToStack(current.types, stack);\n if (hasParameters(current)) pushToStack(current.parameters, stack);\n if (hasArguments(current)) pushToStack(current.arguments, stack);\n if (hasExtendsArguments(current)) pushToStack(current.extendsArguments, stack);\n if (hasImplements(current)) pushToStack(current.implements, stack);\n if (current.typeArguments) pushToStack(current.typeArguments, stack);\n if (current.decorators) pushToStack(current.decorators, stack);\n if (current.scheduleDecorators) pushToStack(current.scheduleDecorators, stack);\n\n // annotations\n if (current.annotations) {\n const annotations = typeAnnotation.getAnnotations(current);\n for (const annotation of annotations) stack.push(annotation.options);\n }\n\n // originTypes\n current.originTypes?.forEach((ot) => {\n if (ot.typeArguments) pushToStack(ot.typeArguments, stack);\n });\n\n // sometimes parent is an orphan so we need to explicitly add it to the stack\n if (current.parent && !(current.parent as SrcType)?._rt) stack.push(current.parent);\n }\n}\n\nfunction pushToStack(subTypes: Type[], stack: Type[]) {\n if (Array.isArray(subTypes)) stack.push(...subTypes);\n}\n\nfunction createRunType(deepkitType: Mutable<SrcType>): RunType {\n // console.log('deepkitType', deepkitType);\n\n /*\n RunType reference is stored in the deepkitType._runType so we can access both the deepkitType and the mion RunType,\n basically every runType stores a reference to a deepkit type and vice versa.\n This also relies on deepkit handling circular types to prevent infinite loop when we are generating RunTypes.\n */\n const existingType: RunType | undefined = deepkitType._rt;\n // TODO: IMPORTANT: seems like deepkit can generate multiple types objects for the same type, so we need to handle this\n // we are attaching the runType to the deepkit type (deepkitType._runType), to link the two types together\n // but as deepkit can generate multiple types that means existingType will be null and the markAsCircular function is not working as expected\n if (existingType) return existingType;\n\n let rt: BaseRunType;\n\n switch (deepkitType.kind) {\n // ###################### ATOMIC RUNTYPES ######################\n // Primitive types and other atomic types that don't contain other types\n case ReflectionKind.any:\n rt = new AnyRunType();\n break;\n case ReflectionKind.bigint:\n rt = new BigIntRunType();\n break;\n case ReflectionKind.boolean:\n rt = new BooleanRunType();\n break;\n case ReflectionKind.enum:\n rt = new EnumRunType();\n break;\n case ReflectionKind.enumMember:\n // enum members are resolved by the enum type, so this is not expected to be called\n rt = new EnumMemberRunType();\n break;\n case ReflectionKind.literal:\n rt = new LiteralRunType();\n break;\n case ReflectionKind.never:\n // TODO add the string format feature\n rt = isNativeUtilityStringTypes(deepkitType) ? new StringRunType() : new NeverRunType();\n break;\n case ReflectionKind.null:\n rt = new NullRunType();\n break;\n case ReflectionKind.number:\n rt = new NumberRunType();\n break;\n case ReflectionKind.object:\n rt = new ObjectRunType();\n break;\n case ReflectionKind.regexp:\n rt = new RegexpRunType();\n break;\n case ReflectionKind.string:\n rt = new StringRunType();\n break;\n case ReflectionKind.symbol:\n rt = new SymbolRunType();\n break;\n case ReflectionKind.templateLiteral:\n // deepkit automatically resolves template literals unions to literals\n // this is only called when you define the type of a template literal i.e: type T = `foo${string}`;\n // this is not supported at the moment but would be useful for type safe urls etc\n throw new Error(\n 'Template Literals are resolved by the compiler to Literals ie: const tl = `${string}World`. Template literal types are not supported. ie type TL = `${string}World`'\n );\n case ReflectionKind.undefined:\n rt = new UndefinedRunType();\n break;\n case ReflectionKind.unknown:\n rt = new UnknownRunType();\n break;\n case ReflectionKind.void:\n rt = new VoidRunType();\n break;\n\n // ###################### MEMBER RUNTYPES ######################\n // Types that represent members of collections or other structures\n case ReflectionKind.array:\n rt = new ArrayRunType();\n break;\n case ReflectionKind.callSignature:\n rt = new CallSignatureRunType();\n break;\n case ReflectionKind.function:\n if (deepkitType.subKind === ReflectionSubKind.params) {\n rt = new FunctionParamsRunType();\n } else {\n const frt = new FunctionRunType();\n // TODO review an change how we compile function parameters and return type\n // those should also be jit functions, no need to check for array\n // and maybe add option to target individual parameters\n (frt.parameterRunTypes as Mutable<RunType>).src = deepkitType;\n rt = frt;\n }\n break;\n case ReflectionKind.indexSignature:\n rt = new IndexSignatureRunType();\n break;\n case ReflectionKind.method:\n rt = new MethodRunType();\n break;\n case ReflectionKind.methodSignature:\n rt = new MethodSignatureRunType();\n break;\n case ReflectionKind.parameter:\n rt = new ParameterRunType();\n break;\n case ReflectionKind.property:\n case ReflectionKind.propertySignature:\n rt = new PropertyRunType();\n break;\n case ReflectionKind.rest:\n rt = new RestParamsRunType();\n break;\n case ReflectionKind.tupleMember:\n rt = new TupleMemberRunType();\n break;\n case ReflectionKind.promise:\n rt = new PromiseRunType();\n break;\n\n // ###################### COLLECTION RUNTYPES ######################\n case ReflectionKind.objectLiteral:\n if (isNonSerializableObject(deepkitType)) {\n rt = new NonSerializableRunType();\n } else {\n rt = new InterfaceRunType();\n }\n break;\n case ReflectionKind.class:\n rt = initClassRunType(deepkitType);\n break;\n // Types that contain other types as members\n case ReflectionKind.infer:\n throw new Error(\n 'Infer type not supported, ie: type MyType =Type<T> = T extends (...args: any[]) => infer R ? R : any; https://www.typescriptlang.org/docs/handbook/2/conditional-types.html'\n );\n\n case ReflectionKind.intersection:\n rt = new IntersectionRunType();\n break;\n\n case ReflectionKind.tuple:\n rt = new TupleRunType();\n break;\n case ReflectionKind.typeParameter:\n throw new Error(\n 'TypeParameter not implemented. Type parameters are the generic placeholders in type definitions (e.g., T in Array<T>, ErrType in TypedError<ErrType>). ' +\n 'Type parameters are typically resolved during type instantiation and should not appear in runtime type checking.' +\n 'This error is typically caused by a generic type missing type arguments, e.g.: TypedError instead of TypedError<\"my-error\">.'\n );\n // rType = resolveTypeParameter(deepkitType, opts, mapper);\n case ReflectionKind.union:\n rt = new UnionRunType();\n break;\n default:\n rt = new AnyRunType();\n break;\n }\n rt.onCreated(deepkitType);\n // console.log('rt', rt);\n return rt;\n}\n\nfunction initClassRunType(src: TypeClass & {subKind?: number}): BaseRunType {\n switch (src.classType) {\n case Date:\n src.subKind = ReflectionSubKind.date;\n return new DateRunType();\n case Map:\n src.subKind = ReflectionSubKind.map;\n return new MapRunType();\n case Set:\n src.subKind = ReflectionSubKind.set;\n return new SetRunType();\n default:\n if (isNonSerializableClass(src)) {\n src.subKind = ReflectionSubKind.nonSerializable;\n return new NonSerializableRunType();\n }\n return new ClassRunType();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEM,SAAU,QAAW,OAAX,QAAO,IAAA,CAAA,GAAyB;AAAhC,UAAO,IAAA;AACnB,QAAM,QAAQ,KAAK,IAAA;AACnB,QAAM,MAAM,mBAAmB,IAAI;AACnC,QAAM,QAAQ,KAAK,IAAA,IAAQ;AAC3B,iBAAe,GAAG;AAClB,QAAM,QAAQ,KAAK,IAAA,IAAQ;AAC3B,QAAM,OAAO,QAAQ;AAErB,MAAI,OAAO;AAAI,YAAQ,KAAK,kCAAkC,IAAI,UAAU,cAAc,GAAG,CAAC,EAAE;AAChG,SAAO,IAAI;AACd;;AAEK,SAAU,gBAAoD,IAAM;AACtE,QAAM,MAAM,QAAQ,EAAE;AACtB,UAAQ,GAAG;AACX,SAAO,IAAI;AACf;;AAGA,SAAS,eAAe,KAAY;AAChC,6BAAA;AACA,QAAM,QAAgB,CAAC,GAAG;AAE1B,SAAO,MAAM,SAAS,GAAG;AACrB,UAAM,UAAU,MAAM,IAAA;AACtB,QAAI,CAAC,WAAY,QAAoB;AAAK;AAE1C,QAAI;AACA,oBAAc,OAA2B;AAAA,IAC7C,SAAS,OAAO;AACZ,YAAM,oBAAoB,oBAAoB,MAAM,IAAG,aAAC,CAAC,MAAM,EAAE,YA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,WAAK,IAAI,WAAA;AACT;AAAA,EAAA;AAER,KAAG,UAAU,WAAW;AAExB,SAAO;AACX;;AAEA,SAAS,iBAAiB,KAAmC;AACzD,UAAQ,IAAI,WAAA;AAAA,IACR,KAAK;AACD,UAAI,UAAU,kBAAkB;AAChC,aAAO,IAAI,YAAA;AAAA,IACf,KAAK;AACD,UAAI,UAAU,kBAAkB;AAChC,aAAO,IAAI,WAAA;AAAA,IACf,KAAK;AACD,UAAI,UAAU,kBAAkB;AAChC,aAAO,IAAI,WAAA;AAAA,IACf;AACI,UAAI,uBAAuB,GAAG,GAAG;AAC7B,YAAI,UAAU,kBAAkB;AAChC,eAAO,IAAI,uBAAA;AAAA,MACf;AACA,aAAO,IAAI,aAAA;AAAA,EAAY;AAEnC;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRunTypeFunctions.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"createRunTypeFunctions.js","sources":["../../../src/createRunTypeFunctions.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 {JitFunctions} from './constants.functions.ts';\nimport {ReceiveType} from '@deepkit/type';\nimport {runType} from './createRunType.ts';\nimport {RunTypeOptions} from './types.ts';\nimport {\n FromBinaryFn,\n IsTypeFn,\n JsonStringifyFn,\n PrepareForJsonFn,\n RestoreFromJsonFn,\n ToBinaryFn,\n ToCodeFn,\n TypeErrorsFn,\n} from '@mionjs/core';\nimport {BaseRunType} from './lib/baseRunTypes.ts';\nimport {registerJitFunctionCompiler} from './lib/jitFnsRegistry.ts';\n\n// All these functions are async because they might need to compile the jit function first\n// At the moment they are compiled synchronously, but in the future they might be async\n// Also some the src code to compile or functionality of the JIT functions might be loaded dynamically\n// ie: mocking functionality is loaded only when mockTypeFn is called\n\n/** Returns a function that checks if the given value is of the specified type. */\nexport async function createIsTypeFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): Promise<IsTypeFn> {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.isType, opts);\n}\n\n/** Returns a function that get Type error data. */\nexport async function createTypeErrorsFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): Promise<TypeErrorsFn> {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.typeErrors, opts);\n}\n\n/**\n * Returns a function that prepares a javascript type to be compatible with json.stringify.\n * Allows json.stringify special types like dates, bigints, maps, set, etc... that are not supported by json.stringify\n */\nexport async function createPrepareForJsonFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): Promise<PrepareForJsonFn> {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.prepareForJson, opts);\n}\n\n/**\n * Returns a function that restores a javascript type from json.parse.\n * Allows restoring special types like dates, bigints, maps, set, etc... that are not supported by json.parse\n * */\nexport async function createRestoreFromJsonFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): Promise<RestoreFromJsonFn> {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.restoreFromJson, opts);\n}\n\n/**\n * Returns a function that stringifies a javascript value to a json string.\n * Stringifies special types like dates, bigints, maps, set, etc...\n * Is equivalent to calling prepareForJson and then json.stringify but more efficient.\n */\nexport async function createStringifyJsonFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): Promise<JsonStringifyFn> {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.stringifyJson, opts);\n}\n\n/** Returns a function that serializes any type value to a binary format. */\nexport async function createToBinaryFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): Promise<ToBinaryFn> {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.toBinary, opts);\n}\n\n/** Returns a function that deserializes a binary value to the specified type. */\nexport async function createFromBinaryFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): Promise<FromBinaryFn> {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.fromBinary, opts);\n}\n\n/** Returns a function that converts a value to javascript code, including set etc */\nexport function createToJavascriptFn<T>(opts?: RunTypeOptions, type?: ReceiveType<T>): ToCodeFn {\n const rt = runType(type);\n return rt.createJitFunction(JitFunctions.toJSCode, opts);\n}\n\n/** Returns a function that mocks a value of the specified type. */\nexport async function createMockTypeFn<T>(type?: ReceiveType<T>): Promise<(opts?: Partial<RunTypeOptions>) => T> {\n const rt = runType(type) as BaseRunType;\n await registerJitFunctionCompiler(JitFunctions.mock);\n return (opts?: Partial<RunTypeOptions>) => rt.mockType(opts) as T;\n}\n"],"names":["__ΩRunTypeOptions"],"mappings":";;;;;;;;;;;AA8BA,eAAsB,eAAkB,MAAuB,OAAzC,eAAc,IAAA,CAAA,GAAgD;AAA9D,iBAAc,IAAA;AAChC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,QAAQ,IAAI;AACxD;;AAGD,eAAsB,mBAAsB,MAAuB,OAA7C,mBAAkB,IAAA,CAAA,GAAgD;AAAlE,qBAAkB,IAAA;AACpC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,YAAY,IAAI;AAC5D;;AAMD,eAAsB,uBAA0B,MAAuB,OAAjD,uBAAsB,IAAA,CAAA,GAAgD;AAAtE,yBAAsB,IAAA;AACxC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,gBAAgB,IAAI;AAChE;;AAMD,eAAsB,wBAA2B,MAAuB,OAAlD,wBAAuB,IAAA,CAAA,GAAgD;AAAvE,0BAAuB,IAAA;AACzC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,iBAAiB,IAAI;AACjE;;AAOD,eAAsB,sBAAyB,MAAuB,OAAhD,sBAAqB,IAAA,CAAA,GAAgD;AAArE,wBAAqB,IAAA;AACvC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,eAAe,IAAI;AAC/D;;AAGD,eAAsB,iBAAoB,MAAuB,OAA3C,iBAAgB,IAAA,CAAA,GAAgD;AAAhE,mBAAgB,IAAA;AAClC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,UAAU,IAAI;AAC1D;;AAGD,eAAsB,mBAAsB,MAAuB,OAA7C,mBAAkB,IAAA,CAAA,GAAgD;AAAlE,qBAAkB,IAAA;AACpC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,YAAY,IAAI;AAC5D;;SAGe,qBAAwB,MAAuB,OAA/C,qBAAoB,IAAA,CAAA,GAAgD;AAApE,uBAAoB,IAAA;AAChC,QAAM,KAAK,QAAQ,IAAI;AACvB,SAAO,GAAG,kBAAkB,aAAa,UAAU,IAAI;AAC1D;;AAGD,eAAsB,iBAAoB,OAApB,iBAAgB,IAAA,CAAA,GAAyB;AAAzC,mBAAgB,IAAA;AAClC,QAAM,KAAK,QAAQ,IAAI;AACvB,QAAM,4BAA4B,aAAa,IAAI;AACnD,SAAA,aAAO,CAAC,SAAmC,GAAG,SAAS,IAAI,GAAM,CAAA,MAAA,YAAA,MAAAA,mBAAA,QAAA,IAAA,cAAA,CAAA;AACpE;;"}
|
|
@@ -4,14 +4,6 @@ import { JitFunctions } from "../../constants.functions.js";
|
|
|
4
4
|
import { isSafePropName } from "../../lib/utils.js";
|
|
5
5
|
import { createStringifyCompiler, createStringifyIterable } from "./stringifyJson.js";
|
|
6
6
|
import { cpf_sanitizeCompiledFn } from "../../run-types-pure-fns.js";
|
|
7
|
-
function getParentSiblingNames(srcMS) {
|
|
8
|
-
let parent = srcMS.parent;
|
|
9
|
-
if (parent?.kind === ReflectionKind.propertySignature) parent = parent.parent;
|
|
10
|
-
if (parent?.kind !== ReflectionKind.objectLiteral) return void 0;
|
|
11
|
-
const types = parent.types;
|
|
12
|
-
if (!types) return void 0;
|
|
13
|
-
return new Set(types.map((t) => t.name).filter((n) => n !== void 0));
|
|
14
|
-
}
|
|
15
7
|
function createToCodeCompiler() {
|
|
16
8
|
const fnID = JitFunctions.toJSCode.id;
|
|
17
9
|
const visitJsonStringify = createStringifyCompiler(fnID);
|
|
@@ -37,11 +29,14 @@ function createToCodeCompiler() {
|
|
|
37
29
|
if (isCompilingFnProp(rt, comp)) {
|
|
38
30
|
return { code: `'undefined'`, type: "E" };
|
|
39
31
|
} else if (isCompilingClosureFn(rt, comp)) {
|
|
32
|
+
const parentRef = getParentObjRef(srcMS, comp);
|
|
40
33
|
const isPureFn = rt.getChildVarName(comp) === "createPureFn";
|
|
41
|
-
const fnName = isPureFn ? `${
|
|
42
|
-
const fnCode = `${
|
|
43
|
-
const paramList = isPureFn ? `${
|
|
34
|
+
const fnName = isPureFn ? `${parentRef}.fnName` : `${parentRef}.jitFnHash`;
|
|
35
|
+
const fnCode = `${parentRef}.code`;
|
|
36
|
+
const paramList = isPureFn ? `${parentRef}.paramNames.join(',')` : `'utl'`;
|
|
44
37
|
const closureCode = `'function get_'+${fnName}+'('+${paramList}+'){'+${fnCode}+'}'`;
|
|
38
|
+
const isWrapped = parentRef !== comp.vλl;
|
|
39
|
+
if (isWrapped) return { code: closureCode, type: "E" };
|
|
45
40
|
return { code: `'${safeName}:'+${closureCode}${sep}`, type: "E" };
|
|
46
41
|
} else if (rt.src.subKind === ReflectionSubKind.params) {
|
|
47
42
|
const paramsCode = visitJsonStringify(rt, comp);
|
|
@@ -94,21 +89,6 @@ function createToCodeCompiler() {
|
|
|
94
89
|
return visitJsonStringify(runType, comp);
|
|
95
90
|
}
|
|
96
91
|
}
|
|
97
|
-
function isCompilingClosureFn(runType, comp) {
|
|
98
|
-
const childName = runType.getChildVarName(comp);
|
|
99
|
-
if (childName !== "createJitFn" && childName !== "createPureFn") return false;
|
|
100
|
-
const siblings = getParentSiblingNames(runType.src);
|
|
101
|
-
if (!siblings) return false;
|
|
102
|
-
if (!siblings.has("code")) return false;
|
|
103
|
-
if (childName === "createJitFn") return siblings.has("jitFnHash");
|
|
104
|
-
return siblings.has("bodyHash");
|
|
105
|
-
}
|
|
106
|
-
function isCompilingFnProp(runType, comp) {
|
|
107
|
-
if (runType.getChildVarName(comp) !== "fn") return false;
|
|
108
|
-
const siblings = getParentSiblingNames(runType.src);
|
|
109
|
-
if (!siblings) return false;
|
|
110
|
-
return siblings.has("code") && (siblings.has("createJitFn") || siblings.has("createPureFn"));
|
|
111
|
-
}
|
|
112
92
|
return compileToCode;
|
|
113
93
|
}
|
|
114
94
|
let lazyFn = void 0;
|
|
@@ -116,6 +96,34 @@ function emitToCode(runType, comp) {
|
|
|
116
96
|
if (!lazyFn) lazyFn = createToCodeCompiler();
|
|
117
97
|
return lazyFn(runType, comp);
|
|
118
98
|
}
|
|
99
|
+
function getParentSiblingNames(srcMS) {
|
|
100
|
+
let parent = srcMS.parent;
|
|
101
|
+
if (parent?.kind === ReflectionKind.propertySignature) parent = parent.parent;
|
|
102
|
+
if (parent?.kind !== ReflectionKind.objectLiteral) return void 0;
|
|
103
|
+
const types = parent.types;
|
|
104
|
+
if (!types) return void 0;
|
|
105
|
+
return new Set(types.map((t) => t.name).filter((n) => n !== void 0));
|
|
106
|
+
}
|
|
107
|
+
function isCompilingClosureFn(runType, comp) {
|
|
108
|
+
const childName = runType.getChildVarName(comp);
|
|
109
|
+
if (childName !== "createJitFn" && childName !== "createPureFn") return false;
|
|
110
|
+
const siblings = getParentSiblingNames(runType.src);
|
|
111
|
+
if (!siblings) return false;
|
|
112
|
+
if (childName === "createJitFn") return siblings.has("jitFnHash");
|
|
113
|
+
return siblings.has("bodyHash");
|
|
114
|
+
}
|
|
115
|
+
function isCompilingFnProp(runType, comp) {
|
|
116
|
+
if (runType.getChildVarName(comp) !== "fn") return false;
|
|
117
|
+
const siblings = getParentSiblingNames(runType.src);
|
|
118
|
+
if (!siblings) return false;
|
|
119
|
+
return siblings.has("createJitFn") && siblings.has("jitFnHash") || siblings.has("createPureFn") && siblings.has("bodyHash");
|
|
120
|
+
}
|
|
121
|
+
function getParentObjRef(_srcMS, comp) {
|
|
122
|
+
const stack = comp.stack;
|
|
123
|
+
const parentItem = stack[stack.length - 2];
|
|
124
|
+
if (parentItem && parentItem.vλl !== comp.vλl) return parentItem.vλl;
|
|
125
|
+
return comp.vλl;
|
|
126
|
+
}
|
|
119
127
|
export {
|
|
120
128
|
createToCodeCompiler,
|
|
121
129
|
emitToCode
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toJsCode.js","sources":["../../../../../src/jitCompilers/json/toJsCode.ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {JitCode} from '../../types.ts';\nimport type {BaseRunType} from '../../lib/baseRunTypes.ts';\nimport type {ClassRunType} from '../../nodes/collection/class.ts';\nimport type {MethodSignatureRunType} from '../../nodes/member/methodSignature.ts';\nimport type {IterableRunType} from '../../nodes/native/Iterable.ts';\nimport {ReflectionKind, type TypeMethodSignature, type TypeObjectLiteral, type TypePropertySignature} from '@deepkit/type';\nimport {ReflectionSubKind} from '../../constants.kind.ts';\nimport {JitFunctions} from '../../constants.functions.ts';\nimport {JitFnCompiler} from '../../lib/jitFnCompiler.ts';\nimport {isSafePropName} from '../../lib/utils.ts';\nimport {createStringifyCompiler, createStringifyIterable} from './stringifyJson.ts';\nimport {cpf_sanitizeCompiledFn} from '../../run-types-pure-fns.ts';\n\n/** Gets sibling property/method names from a MethodSignature's parent ObjectLiteral */\nfunction getParentSiblingNames(srcMS: TypeMethodSignature): Set<string | number | symbol> | undefined {\n let parent = srcMS.parent as any;\n // Handle deepkit bug where parent can be TypePropertySignature instead of TypeObjectLiteral\n if (parent?.kind === ReflectionKind.propertySignature) parent = parent.parent;\n if (parent?.kind !== ReflectionKind.objectLiteral) return undefined;\n const types = (parent as TypeObjectLiteral).types;\n if (!types) return undefined;\n return new Set(types.map((t: any) => t.name).filter((n: any) => n !== undefined));\n}\n\nexport function createToCodeCompiler() {\n const fnID = JitFunctions.toJSCode.id;\n const visitJsonStringify = createStringifyCompiler(fnID);\n const visitJsonStringifyIterable = createStringifyIterable(fnID);\n\n /**\n * Compiles jit code to generate JavaScript code from data structures that match a Type.\n * Process is similar to transform JS to JSON, but with few differences.\n *\n * 1 - jitFunctions and pureFunctions are emitted as src code\n * 2 - Some native classes are supported and initialized using the new operator, ie: new Map(<data>), new Set(<data>), new Date(<data>), etc...\n *\n * THIS IS MOSTLY USED INTERNALLY FOR AOT CODE GENERATION AND A VERY BASIC IMPLEMENTATION.\n * !!! NOT INTENDED FOR PUBLIC USE !!!\n */\n function compileToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n const src = runType.src;\n const kind = src.kind;\n\n switch (kind) {\n // ###################### ATOMIC RUNTYPES ######################\n case ReflectionKind.undefined:\n return {code: `'undefined'`, type: 'E'};\n case ReflectionKind.symbol:\n return {code: `'Symbol('+'\"'+${comp.vλl}.description+'\"'+')'`, type: 'E'};\n // ###################### MEMBER RUNTYPES ######################\n case ReflectionKind.methodSignature: {\n const rt = runType as MethodSignatureRunType;\n const srcMS = src as TypeMethodSignature;\n const accessor = srcMS.name;\n const name = String(accessor);\n const isSafe = isSafePropName(accessor);\n const safeName = isSafe ? name : JSON.stringify(name);\n const sep = rt.skipCommas ? '' : '+\",\"';\n if (isCompilingFnProp(rt, comp)) {\n // special case for JitFunctions/PureFunctions that we know should return undefined for fn param\n return {code: `'undefined'`, type: 'E'};\n } else if (isCompilingClosureFn(rt, comp)) {\n // special case for JitFunctions/PureFunctions where we generate the fn from the data instead of fn.toString()\n const isPureFn = rt.getChildVarName(comp) === 'createPureFn';\n const fnName = isPureFn ? `${comp.vλl}.fnName` : `${comp.vλl}.jitFnHash`;\n const fnCode = `${comp.vλl}.code`;\n const paramList = isPureFn ? `${comp.vλl}.paramNames.join(',')` : `'utl'`;\n const closureCode = `'function get_'+${fnName}+'('+${paramList}+'){'+${fnCode}+'}'`;\n return {code: `'${safeName}:'+${closureCode}${sep}`, type: 'E'};\n } else if (rt.src.subKind === ReflectionSubKind.params) {\n const paramsCode = visitJsonStringify(rt, comp);\n if (rt.isOptional())\n return {\n code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${paramsCode?.code}${sep})`,\n type: 'E',\n };\n return {code: `'${safeName}:'+${paramsCode?.code}${sep}`, type: 'E'};\n } else {\n const fnName = comp.addPureFunction(cpf_sanitizeCompiledFn);\n const parent = srcMS.parent as any as TypePropertySignature;\n\n // in some scenarios the parent is a propertySignature instead the Expected TypeObjectLiteral so we have to handle that\n // this seems to be a deepkit bug when using omit and then redefining the property @see SrcCodeJitCompiledFn type\n const isDuplicatedChild = parent?.kind === ReflectionKind.propertySignature && parent?.name === srcMS.name;\n if (isDuplicatedChild) return {code: `${fnName}(${comp.vλl}.toString())`, type: 'E'};\n const accessorCode = isSafe ? `.${safeName}` : `[${safeName}]`;\n const fnCode = `${fnName}(${comp.vλl}${accessorCode}.toString())`;\n if (rt.isOptional())\n return {code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${fnCode}${sep})`, type: 'E'};\n return {code: `'${safeName}:'+${fnCode}${sep}`, type: 'E'};\n }\n }\n case ReflectionKind.function:\n case ReflectionKind.method:\n case ReflectionKind.callSignature:\n if (runType.src.subKind === ReflectionSubKind.params) {\n return visitJsonStringify(runType, comp);\n } else {\n // TODO: we are relying in fn.toString() to generate code, this might not work properly in all js engines\n return {code: `${comp.vλl}.toString()`, type: 'E'};\n }\n // ###################### COLLECTION RUNTYPES ######################\n case ReflectionKind.class: {\n switch (runType.src.subKind) {\n case ReflectionSubKind.date:\n return {code: `'new Date('+${visitJsonStringify(runType, comp).code}+')'`, type: 'E'};\n case ReflectionSubKind.map: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Map(', ')');\n }\n case ReflectionSubKind.set: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Set(', ')');\n }\n case ReflectionSubKind.nonSerializable:\n throw new Error(`Can not generate code for Non Serializable types.`);\n default: {\n const rt = runType as unknown as ClassRunType;\n throw new Error(`Can not generate code for classes. Class: ${rt.getClassName()}`);\n }\n }\n }\n default:\n return visitJsonStringify(runType, comp);\n }\n }\n\n /** Detects if we're compiling a createJitFn or createPureFn closure by checking sibling properties */\n function isCompilingClosureFn(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n const childName = runType.getChildVarName(comp);\n if (childName !== 'createJitFn' && childName !== 'createPureFn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n if (!siblings.has('code')) return false;\n if (childName === 'createJitFn') return siblings.has('jitFnHash');\n return siblings.has('bodyHash'); // createPureFn\n }\n\n /** Detects if we're compiling the fn property of a JitCompiledFn or CompiledPureFunction */\n function isCompilingFnProp(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n if (runType.getChildVarName(comp) !== 'fn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n return siblings.has('code') && (siblings.has('createJitFn') || siblings.has('createPureFn'));\n }\n\n return compileToCode;\n}\n\n// lazy loading as this function wont be used often just for (AOT)\n// TODO move to async code loading (but this would need a big refactor of the router)\nlet lazyFn: undefined | ((runType: BaseRunType, comp: JitFnCompiler) => JitCode) = undefined;\nexport function emitToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n if (!lazyFn) lazyFn = createToCodeCompiler();\n return lazyFn(runType, comp);\n}\n"],"names":[],"mappings":";;;;;;AAqBA,SAAS,sBAAsB,OAAuE;AAClG,MAAI,SAAS,MAAM;AAEnB,MAAI,QAAQ,SAAS,eAAe,4BAA4B,OAAO;AACvE,MAAI,QAAQ,SAAS,eAAe,cAAe,QAAO;AAC1D,QAAM,QAAS,OAA6B;AAC5C,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,IAAI,IAAI,MAAM,IAAI,CAAC,MAAW,EAAE,IAAI,EAAE,OAAO,CAAC,MAAW,MAAM,MAAS,CAAC;AACp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ts"],"sourcesContent":["/* ########\n * 2025 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\n\nimport type {JitCode} from '../../types.ts';\nimport type {BaseRunType} from '../../lib/baseRunTypes.ts';\nimport type {ClassRunType} from '../../nodes/collection/class.ts';\nimport type {MethodSignatureRunType} from '../../nodes/member/methodSignature.ts';\nimport type {IterableRunType} from '../../nodes/native/Iterable.ts';\nimport {ReflectionKind, type TypeMethodSignature, type TypeObjectLiteral, type TypePropertySignature} from '@deepkit/type';\nimport {ReflectionSubKind} from '../../constants.kind.ts';\nimport {JitFunctions} from '../../constants.functions.ts';\nimport {JitFnCompiler} from '../../lib/jitFnCompiler.ts';\nimport {isSafePropName} from '../../lib/utils.ts';\nimport {createStringifyCompiler, createStringifyIterable} from './stringifyJson.ts';\nimport {cpf_sanitizeCompiledFn} from '../../run-types-pure-fns.ts';\n\nexport function createToCodeCompiler() {\n const fnID = JitFunctions.toJSCode.id;\n const visitJsonStringify = createStringifyCompiler(fnID);\n const visitJsonStringifyIterable = createStringifyIterable(fnID);\n\n /**\n * Compiles jit code to generate JavaScript code from data structures that match a Type.\n * Process is similar to transform JS to JSON, but with few differences.\n *\n * 1 - jitFunctions and pureFunctions are emitted as src code\n * 2 - Some native classes are supported and initialized using the new operator, ie: new Map(<data>), new Set(<data>), new Date(<data>), etc...\n *\n * THIS IS MOSTLY USED INTERNALLY FOR AOT CODE GENERATION AND A VERY BASIC IMPLEMENTATION.\n * !!! NOT INTENDED FOR PUBLIC USE !!!\n */\n function compileToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n const src = runType.src;\n const kind = src.kind;\n\n switch (kind) {\n // ###################### ATOMIC RUNTYPES ######################\n case ReflectionKind.undefined:\n return {code: `'undefined'`, type: 'E'};\n case ReflectionKind.symbol:\n return {code: `'Symbol('+'\"'+${comp.vλl}.description+'\"'+')'`, type: 'E'};\n // ###################### MEMBER RUNTYPES ######################\n case ReflectionKind.methodSignature: {\n const rt = runType as MethodSignatureRunType;\n const srcMS = src as TypeMethodSignature;\n const accessor = srcMS.name;\n const name = String(accessor);\n const isSafe = isSafePropName(accessor);\n const safeName = isSafe ? name : JSON.stringify(name);\n const sep = rt.skipCommas ? '' : '+\",\"';\n if (isCompilingFnProp(rt, comp)) {\n // special case for JitFunctions/PureFunctions that we know should return undefined for fn param\n return {code: `'undefined'`, type: 'E'};\n } else if (isCompilingClosureFn(rt, comp)) {\n // special case for JitFunctions/PureFunctions where we generate the fn from the data instead of fn.toString()\n // When using Pick/Omit, deepkit wraps methodSignature in a propertySignature,\n // so comp.vλl points to the fn value instead of the parent object. Use getParentObjRef to get the right ref.\n const parentRef = getParentObjRef(srcMS, comp);\n const isPureFn = rt.getChildVarName(comp) === 'createPureFn';\n const fnName = isPureFn ? `${parentRef}.fnName` : `${parentRef}.jitFnHash`;\n const fnCode = `${parentRef}.code`;\n const paramList = isPureFn ? `${parentRef}.paramNames.join(',')` : `'utl'`;\n const closureCode = `'function get_'+${fnName}+'('+${paramList}+'){'+${fnCode}+'}'`;\n // When wrapped in a propertySignature (Pick/Omit types), the outer handler already emits the property name\n const isWrapped = parentRef !== comp.vλl;\n if (isWrapped) return {code: closureCode, type: 'E'};\n return {code: `'${safeName}:'+${closureCode}${sep}`, type: 'E'};\n } else if (rt.src.subKind === ReflectionSubKind.params) {\n const paramsCode = visitJsonStringify(rt, comp);\n if (rt.isOptional())\n return {\n code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${paramsCode?.code}${sep})`,\n type: 'E',\n };\n return {code: `'${safeName}:'+${paramsCode?.code}${sep}`, type: 'E'};\n } else {\n const fnName = comp.addPureFunction(cpf_sanitizeCompiledFn);\n const parent = srcMS.parent as any as TypePropertySignature;\n\n // in some scenarios the parent is a propertySignature instead the Expected TypeObjectLiteral so we have to handle that\n // this seems to be a deepkit bug when using omit and then redefining the property @see SrcCodeJitCompiledFn type\n const isDuplicatedChild = parent?.kind === ReflectionKind.propertySignature && parent?.name === srcMS.name;\n if (isDuplicatedChild) return {code: `${fnName}(${comp.vλl}.toString())`, type: 'E'};\n const accessorCode = isSafe ? `.${safeName}` : `[${safeName}]`;\n const fnCode = `${fnName}(${comp.vλl}${accessorCode}.toString())`;\n if (rt.isOptional())\n return {code: `(${comp.getChildVλl()} === undefined ? \"\" : '${safeName}:'+${fnCode}${sep})`, type: 'E'};\n return {code: `'${safeName}:'+${fnCode}${sep}`, type: 'E'};\n }\n }\n case ReflectionKind.function:\n case ReflectionKind.method:\n case ReflectionKind.callSignature:\n if (runType.src.subKind === ReflectionSubKind.params) {\n return visitJsonStringify(runType, comp);\n } else {\n // TODO: we are relying in fn.toString() to generate code, this might not work properly in all js engines\n return {code: `${comp.vλl}.toString()`, type: 'E'};\n }\n // ###################### COLLECTION RUNTYPES ######################\n case ReflectionKind.class: {\n switch (runType.src.subKind) {\n case ReflectionSubKind.date:\n return {code: `'new Date('+${visitJsonStringify(runType, comp).code}+')'`, type: 'E'};\n case ReflectionSubKind.map: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Map(', ')');\n }\n case ReflectionSubKind.set: {\n return visitJsonStringifyIterable(runType as unknown as IterableRunType, comp, 'new Set(', ')');\n }\n case ReflectionSubKind.nonSerializable:\n throw new Error(`Can not generate code for Non Serializable types.`);\n default: {\n const rt = runType as unknown as ClassRunType;\n throw new Error(`Can not generate code for classes. Class: ${rt.getClassName()}`);\n }\n }\n }\n default:\n return visitJsonStringify(runType, comp);\n }\n }\n\n return compileToCode;\n}\n\n// lazy loading as this function wont be used often just for (AOT)\n// TODO move to async code loading (but this would need a big refactor of the router)\nlet lazyFn: undefined | ((runType: BaseRunType, comp: JitFnCompiler) => JitCode) = undefined;\nexport function emitToCode(runType: BaseRunType, comp: JitFnCompiler): JitCode {\n if (!lazyFn) lazyFn = createToCodeCompiler();\n return lazyFn(runType, comp);\n}\n\n/** Gets sibling property/method names from a MethodSignature's parent ObjectLiteral */\nfunction getParentSiblingNames(srcMS: TypeMethodSignature): Set<string | number | symbol> | undefined {\n let parent = srcMS.parent as any;\n // Handle deepkit bug where parent can be TypePropertySignature instead of TypeObjectLiteral\n if (parent?.kind === ReflectionKind.propertySignature) parent = parent.parent;\n if (parent?.kind !== ReflectionKind.objectLiteral) return undefined;\n const types = (parent as TypeObjectLiteral).types;\n if (!types) return undefined;\n return new Set(types.map((t: any) => t.name).filter((n: any) => n !== undefined));\n}\n\n/** Detects if we're compiling a createJitFn or createPureFn closure by checking sibling properties */\nfunction isCompilingClosureFn(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n const childName = runType.getChildVarName(comp);\n if (childName !== 'createJitFn' && childName !== 'createPureFn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n if (childName === 'createJitFn') return siblings.has('jitFnHash');\n return siblings.has('bodyHash'); // createPureFn\n}\n\n/** Detects if we're compiling the fn property of a JitCompiledFn or CompiledPureFunction */\nfunction isCompilingFnProp(runType: MethodSignatureRunType, comp: JitFnCompiler): boolean {\n if (runType.getChildVarName(comp) !== 'fn') return false;\n const siblings = getParentSiblingNames(runType.src as TypeMethodSignature);\n if (!siblings) return false;\n return (\n (siblings.has('createJitFn') && siblings.has('jitFnHash')) || (siblings.has('createPureFn') && siblings.has('bodyHash'))\n );\n}\n\n/**\n * Gets the runtime reference to the parent object that contains the methodSignature.\n * When using Pick/Omit, deepkit wraps methodSignature in a propertySignature,\n * causing comp.vλl to point to the fn value (e.g. `obj.createJitFn`) instead of the parent object (`obj`).\n * Detects this by comparing the current vλl with the previous stack item's vλl.\n * If they differ, we are inside a propertySignature wrapper and use the parent stack item's vλl.\n */\nfunction getParentObjRef(_srcMS: TypeMethodSignature, comp: JitFnCompiler): string {\n const stack = comp.stack;\n const parentItem = stack[stack.length - 2];\n if (parentItem && parentItem.vλl !== comp.vλl) return parentItem.vλl;\n return comp.vλl;\n}\n"],"names":[],"mappings":";;;;;;AAoBO,SAAS,uBAAuB;AACnC,Q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;AAClC;AAGA,SAAS,kBAAkB,SAAiC,MAA8B;AACtF,MAAI,QAAQ,gBAAgB,IAAI,MAAM,KAAM,QAAO;AACnD,QAAM,WAAW,sBAAsB,QAAQ,GAA0B;AACzE,MAAI,CAAC,SAAU,QAAO;AACtB,SACK,SAAS,IAAI,aAAa,KAAK,SAAS,IAAI,WAAW,KAAO,SAAS,IAAI,cAAc,KAAK,SAAS,IAAI,UAAU;AAE9H;AASA,SAAS,gBAAgB,QAA6B,MAA6B;AAC/E,QAAM,QAAQ,KAAK;AACnB,QAAM,aAAa,MAAM,MAAM,SAAS,CAAC;AACzC,MAAI,cAAc,WAAW,QAAQ,KAAK,YAAY,WAAW;AACjE,SAAO,KAAK;AAChB;"}
|
|
@@ -52,7 +52,6 @@ export declare abstract class CollectionRunType<T extends Type> extends BaseRunT
|
|
|
52
52
|
emitUnknownKeyErrors(comp: JitErrorsFnCompiler): JitCode;
|
|
53
53
|
emitStripUnknownKeys(comp: JitFnCompiler): JitCode;
|
|
54
54
|
emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode;
|
|
55
|
-
private getChildrenTypeID;
|
|
56
55
|
}
|
|
57
56
|
export declare abstract class MemberRunType<T extends Type> extends BaseRunType<T> implements RunTypeChildAccessor {
|
|
58
57
|
abstract isOptional(): boolean;
|
|
@@ -71,5 +70,4 @@ export declare abstract class MemberRunType<T extends Type> extends BaseRunType<
|
|
|
71
70
|
emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode;
|
|
72
71
|
visitToBinary(comp: JitFnCompiler): JitCode;
|
|
73
72
|
visitFromBinary(comp: JitFnCompiler): JitCode;
|
|
74
|
-
private getMemberTypeID;
|
|
75
73
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { getENV, createUniqueHash, getJitUtils
|
|
2
|
-
import { maxStackErrorMessage } from "../constants.js";
|
|
1
|
+
import { getENV, createUniqueHash, getJitUtils } from "@mionjs/core";
|
|
3
2
|
import { CodeTypes, JitFunctions } from "../constants.functions.js";
|
|
4
3
|
import { ReflectionKind, stringifyType } from "@deepkit/type";
|
|
5
4
|
import { getPropIndex, memorize } from "./utils.js";
|
|
@@ -204,22 +203,6 @@ class CollectionRunType extends BaseRunType {
|
|
|
204
203
|
const codes = this.getJitChildren(comp).map((c) => comp.compileUnknownKeysToUndefined(c, S).code).filter((code) => !!code);
|
|
205
204
|
return { code: codes.join(";"), type: S };
|
|
206
205
|
}
|
|
207
|
-
getChildrenTypeID = memorize((stack = []) => {
|
|
208
|
-
if (stack.length > MAX_STACK_DEPTH) throw new Error(maxStackErrorMessage);
|
|
209
|
-
const circularJitConf = this.checkIsCircularAndGetRefId(stack);
|
|
210
|
-
if (circularJitConf) return circularJitConf;
|
|
211
|
-
stack.push(this);
|
|
212
|
-
const childrenIds = [];
|
|
213
|
-
const children = this.getChildRunTypes();
|
|
214
|
-
for (const child of children) {
|
|
215
|
-
childrenIds.push(child.getTypeID());
|
|
216
|
-
}
|
|
217
|
-
const isArray = this.src.kind === ReflectionKind.tuple || this.src.kind === ReflectionKind.array;
|
|
218
|
-
const groupID = isArray ? `[${childrenIds.join(",")}]` : `{${childrenIds.join(",")}}`;
|
|
219
|
-
const kind = this.src.subKind || this.src.kind;
|
|
220
|
-
stack.pop();
|
|
221
|
-
return `${kind}${groupID}`;
|
|
222
|
-
});
|
|
223
206
|
}
|
|
224
207
|
class MemberRunType extends BaseRunType {
|
|
225
208
|
/** used to compile json stringify */
|
|
@@ -284,20 +267,6 @@ class MemberRunType extends BaseRunType {
|
|
|
284
267
|
if (!code?.code) return { code: void 0, type: S };
|
|
285
268
|
return code;
|
|
286
269
|
}
|
|
287
|
-
getMemberTypeID = memorize((stack = []) => {
|
|
288
|
-
if (stack.length > MAX_STACK_DEPTH) throw new Error(maxStackErrorMessage);
|
|
289
|
-
const optional = this.isOptional() ? "?" : "";
|
|
290
|
-
const kind = this.src.name?.toString() || this.src.index?.kind || this.src.subKind || this.src.kind;
|
|
291
|
-
const kindID = `${kind}${optional}`;
|
|
292
|
-
const circularJitConf = this.checkIsCircularAndGetRefId(stack);
|
|
293
|
-
if (circularJitConf) return `${kindID}:${circularJitConf}`;
|
|
294
|
-
stack.push(this);
|
|
295
|
-
const member = this.getMemberType();
|
|
296
|
-
const memberTypeID = member.getTypeID();
|
|
297
|
-
const typeID = `${kindID}:${memberTypeID}`;
|
|
298
|
-
stack.pop();
|
|
299
|
-
return typeID;
|
|
300
|
-
});
|
|
301
270
|
}
|
|
302
271
|
export {
|
|
303
272
|
AtomicRunType,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"baseRunTypes.js","sources":["../../../../src/lib/baseRunTypes.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\nimport {MAX_STACK_DEPTH, JitCompiledFn, createUniqueHash, getJitUtils, getENV} from '@mionjs/core';\nimport type {\n RunType,\n Mutable,\n RunTypeChildAccessor,\n JitFnID,\n SrcType,\n SrcCollection,\n CustomVλl,\n JitFn,\n JitCode,\n RunTypeOptions,\n StrNumber,\n DeepPartial,\n RunTypeFamily,\n} from '../types.ts';\nimport type {mockType} from '../mocking/mockType.ts';\nimport {maxStackErrorMessage} from '../constants.ts';\nimport {type CodeType, JitFunctions, CodeTypes} from '../constants.functions.ts';\nimport {ReflectionKind, stringifyType} from '@deepkit/type';\nimport type {TypeIndexSignature, TypeProperty, Type} from '@deepkit/type';\nimport {getPropIndex, memorize} from './utils.ts';\nimport {createJitCompiler, MockJitCompiler} from './jitFnCompiler.ts';\nimport {getJITFnHash} from './createJitFunction.ts';\nimport type {JitFnCompiler, JitErrorsFnCompiler} from './jitFnCompiler.ts';\nimport {type AnyKindName, getReflectionName} from '../constants.kind.ts';\nimport {initFormatAnnotations} from './formats.ts';\nimport {createTypeId} from './typeId.ts';\nimport {getJitFunctionCompiler, registerJitFunctionCompiler} from './jitFnsRegistry.ts';\nimport {defaultMockOptions} from '../mocking/constants.mock.ts';\n\nconst RB = CodeTypes.returnBlock;\nconst S = CodeTypes.statement;\nconst E = CodeTypes.expression;\n\nexport abstract class BaseRunType<T extends Type = Type> implements RunType {\n isCircular?: boolean;\n readonly src: SrcType<T> = null as any; // real value will be set after construction by the createRunType function\n abstract getFamily(): RunTypeFamily; // Atomic, Collection, Member, Function\n /**\n * This single functions controls whether or not the code for a type should be inlined into the parent function\n * or should create a separate jit function for it, add as a dependency and call it.\n * @returns\n */\n isJitInlined = (): boolean => {\n // if is circular, always create a separate jit function as need to self invoke\n if (this.isCircular) return false;\n if (getENV('DEBUG_JIT') === 'INLINED') return true;\n // all array are self invoked for isType and are usually repeated type like string[] or number[] so worth deduplicating\n if (this.src.kind === ReflectionKind.array) return false;\n // collection with name might be used in different places so worth deduplicating\n if (this.src.typeName && this.getFamily() === 'C') return false;\n return true;\n };\n getKindName = memorize((): AnyKindName => getReflectionName(this));\n getTypeName = (): string => this.src.typeName || this.getKindName();\n stringify = memorize((): string => stringifyType(this.src));\n skipJit(comp: JitFnCompiler): boolean {\n return false;\n }\n /** Returns the format portion of the type ID (cached in src._formatId), or undefined if no format. */\n getFormatTypeID(): string | undefined {\n // _formatId is cached by computeDeepkitFormatID during getDeepkitTypeId call\n // Empty string means no format, undefined means not computed yet\n const formatId = (this.src as any)._formatId;\n return formatId || undefined;\n }\n /** Returns the type ID which is cached in src._typeId by getDeepkitTypeId(). Format ID is already included. */\n getTypeID(): StrNumber {\n if (this.src._typeId === undefined) {\n throw new Error(`Missing cached type ID for ${this.getTypeName()}. Ensure getDeepkitTypeId() has been called.`);\n }\n return this.src._typeId;\n }\n getJitHash(opts: RunTypeOptions): string {\n const optsCopy = {...opts};\n // remove mock options as not relevant for jit functionality\n if (optsCopy.mock) delete optsCopy.mock;\n return createUniqueHash(this.getTypeID().toString() + JSON.stringify(optsCopy));\n }\n getParent = (): BaseRunType | undefined => (this.src.parent as SrcType)?._rt as BaseRunType;\n checkIsCircularAndGetRefId(stack: RunType[] = []): StrNumber | undefined {\n const inStackIndex = stack.findIndex((rt) => {\n if (rt === this) return true;\n // some nodes seems to be different objects in memory but are the same id, so we check by id as well\n return rt.src.id && this.src.id && rt.src.id === this.src.id;\n }); // cant use isSameJitType because it uses getTypeID and would loop forever\n const inStackSrcId = stack.findIndex((rt) => rt.src.id && this.src.id && rt.src.id === this.src.id);\n const isInStack = inStackIndex >= 0; // recursive reference\n if (isInStack) {\n this.isCircular = true;\n const name = this.src.typeName || ''; // todo: not sure if all the circular references will have a name\n const refId = '$' + this.src.kind + `_${inStackIndex}` + name; // ensures different circular types have different typeID\n return refId;\n }\n return undefined;\n }\n /**\n * Method that should be called Immediately after the RunType gets created to link the SrcType and RunType.\n * This is more flexible than passing params to the constructor helps to avoid circular dependencies, etc.\n * */\n onCreated(src: SrcType<any>): void {\n (this as Mutable<RunType>).src = src;\n (src as Mutable<SrcType>)._rt = this;\n initFormatAnnotations(this);\n // Cache the type ID on the src object - this includes format information\n createTypeId(src);\n }\n /**\n * Some elements might need a standalone name variable that ignores the vλl value of the parents.\n * returns a variable that is being compiled, ignores the parents variable names */\n getCustomVλl(comp: JitFnCompiler): CustomVλl | undefined {\n return undefined;\n }\n /**\n * Some elements might need a custom static path to be able to reference the source of an error.\n * ie: when validating a Map we need to differentiate if the value that failed is the key or the value of a map's entry.\n */\n getStaticPathLiteral(comp: JitFnCompiler): string | number | undefined {\n return undefined;\n }\n\n // ########## Mock ##########\n\n async mock(opts?: DeepPartial<RunTypeOptions>): Promise<any> {\n // although the mock function is not jit, it is also stored in the registry\n // this is because we don't want to load mock related functionality if not needed\n await registerJitFunctionCompiler(JitFunctions.mock);\n return this.mockType(opts);\n }\n\n /** synchronous version of mock, throws an error if the mock function has not been loaded */\n mockType(opts: DeepPartial<RunTypeOptions> = {}): any {\n const mockFn = getJitFunctionCompiler(JitFunctions.mock) as typeof mockType;\n if (!mockFn)\n throw new Error(\n `Function ${JitFunctions.mock.name} has not been loaded. make sure you have called loadJitCompilerFunction(JitFunctions.mock) before calling mockType.`\n );\n const fnID = JitFunctions.mock.id;\n // options sent to the compiler will be set to empty as mock options are handled separately from the compiler\n const mockingOpts = {...opts, mock: {...defaultMockOptions, ...(opts.mock || {})}} as RunTypeOptions;\n const hash = getJITFnHash(fnID, this, mockingOpts);\n const comp = new MockJitCompiler(this, mockingOpts, undefined, hash, this.getTypeID());\n return mockFn(this, comp);\n }\n\n // ########## Create Jit Functions ##########\n\n createJitFunction = (jitFn: JitFn, opts: RunTypeOptions = {}): ((...args: any[]) => any) => {\n return this.createJitCompiledFunction(jitFn.id, undefined, opts).fn;\n };\n\n createJitCompiledFunction(fnID: JitFnID, parentCop?: JitFnCompiler, opts: RunTypeOptions = {}): JitCompiledFn {\n const fnHash = getJITFnHash(fnID, this, opts);\n const jitCompiled = getJitUtils().getJIT(fnHash);\n if (jitCompiled) {\n if (getENV('DEBUG_JIT') === 'VERBOSE')\n console.log(`\\x1b[32m Using cached function: ${jitCompiled.jitFnHash} \\x1b[0m`);\n return jitCompiled;\n }\n const newJitCompiler: JitFnCompiler = createJitCompiler(\n this,\n fnID,\n parentCop,\n undefined,\n undefined,\n opts\n ) as JitFnCompiler;\n try {\n const codeType = this.getFamily() === 'A' ? E : S;\n newJitCompiler.compile(this, codeType, fnID);\n newJitCompiler.createJitFunction();\n } catch (e: any) {\n // if something goes wrong during compilation we want to remove the compiler from\n // the cache as this is automatically added to jitUtils cache during compilation\n newJitCompiler.removeFromJitCache();\n // TODO: we need to print the full path to the type that is causing the error\n // for this ideally we should add a parent Compiler and print the trace only from the root\n if (typeof e?.message === 'string' && !newJitCompiler.hasStackTrace(e.message))\n e.message += newJitCompiler.getStackTrace();\n throw e;\n }\n return newJitCompiler as JitCompiledFn;\n }\n\n // ########## emit Methods that generates src code ##########\n\n abstract emitIsType(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitTypeErrors(comp: JitErrorsFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitHasUnknownKeys(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitUnknownKeyErrors(comp: JitErrorsFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitStripUnknownKeys(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitUnknownKeysToUndefined(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n // todo: maybe we should move these two into a single file like the rest of serializers\n abstract emitPrepareForJson(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitRestoreFromJson(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n}\n\n/**\n * RunType that is atomic an does not contains any other child runTypes.\n * ie: string, number, boolean, any, null, undefined, void, never, bigint, etc.\n * */\nexport abstract class AtomicRunType<T extends Type> extends BaseRunType<T> {\n getFamily(): 'A' {\n return 'A';\n }\n emitPrepareForJson(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitRestoreFromJson(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitHasUnknownKeys(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: E};\n }\n emitUnknownKeyErrors(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitStripUnknownKeys(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n}\n\n/**\n * RunType that contains a collection or child runTypes.\n * Collection RunTypes are the only ones that can have circular references. as a child of a collection RunType can be the parent of the collection RunType.\n * i.e: interface, child runTypes are it's properties\n * i.e: tuple, it's child runTypes are the tuple members\n */\nexport abstract class CollectionRunType<T extends Type> extends BaseRunType<T> {\n getFamily(): 'C' {\n return 'C';\n }\n getChildRunTypes = (): BaseRunType[] => {\n const childTypes = ((this.src as SrcCollection).types as SrcType[]) || []; // deepkit stores child types in the types property\n return childTypes.map((t) => t._rt as BaseRunType);\n };\n getJitChildren(comp: JitFnCompiler): BaseRunType[] {\n let skipIndex = false; // if there are multiple index signatures, only the first one will be used as they must be same type just different keys\n return this.getChildRunTypes().filter((c) => {\n if (c.skipJit(comp)) return false;\n const isIndex = c.src.kind === ReflectionKind.indexSignature;\n if (isIndex && skipIndex) return false;\n if (isIndex) skipIndex = true;\n return true;\n });\n }\n areAllChildrenOptional(children: BaseRunType[]) {\n return children.every(\n (prop) =>\n (prop as MemberRunType<any>)?.isOptional() ||\n (prop.src as TypeProperty)?.optional ||\n prop.src.kind === ReflectionKind.indexSignature\n );\n }\n emitHasUnknownKeys(comp: JitFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileHasUnknownKeys(c, E).code)\n .filter((code) => !!code);\n return {code: codes.join(' || '), type: E};\n }\n emitUnknownKeyErrors(comp: JitErrorsFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileUnknownKeyErrors(c, S).code)\n .filter((code) => !!code);\n return {code: codes.join(';'), type: S};\n }\n emitStripUnknownKeys(comp: JitFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileStripUnknownKeys(c, S).code)\n .filter((code) => !!code);\n return {code: codes.join(';'), type: S};\n }\n emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileUnknownKeysToUndefined(c, S).code)\n .filter((code) => !!code);\n return {code: codes.join(';'), type: S};\n }\n private getChildrenTypeID = memorize((stack: BaseRunType<any>[] = []): StrNumber => {\n if (stack.length > MAX_STACK_DEPTH) throw new Error(maxStackErrorMessage);\n const circularJitConf = this.checkIsCircularAndGetRefId(stack);\n if (circularJitConf) return circularJitConf;\n stack.push(this);\n const childrenIds: (string | number)[] = [];\n const children = this.getChildRunTypes();\n for (const child of children) {\n childrenIds.push(child.getTypeID());\n }\n const isArray = this.src.kind === ReflectionKind.tuple || this.src.kind === ReflectionKind.array;\n const groupID = isArray ? `[${childrenIds.join(',')}]` : `{${childrenIds.join(',')}}`;\n const kind = this.src.subKind || this.src.kind;\n stack.pop();\n return `${kind}${groupID}`;\n });\n}\n\n/**\n * RunType that contains a single member or child RunType. usually part of a collection RunType.\n * i.e object properties, {prop: memberType} where memberType is the child RunType\n */\nexport abstract class MemberRunType<T extends Type> extends BaseRunType<T> implements RunTypeChildAccessor {\n abstract isOptional(): boolean;\n abstract getChildVarName(comp: JitFnCompiler): string | number;\n abstract getChildLiteral(comp: JitFnCompiler): string | number;\n abstract useArrayAccessor(): boolean;\n /** used to compile json stringify */\n skipCommas?: boolean;\n /** used to compile json stringify */\n tempChildVλl?: string;\n getFamily(): 'M' {\n return 'M';\n }\n getMemberType(): BaseRunType {\n const memberType = (this.src as any).type as SrcType; // deepkit stores member types in the type property\n return memberType._rt as BaseRunType;\n }\n getChildIndex(comp: JitFnCompiler) {\n const start = comp?.opts?.paramsSlice?.start;\n if (start) return getPropIndex(this.src) - start;\n return getPropIndex(this.src);\n }\n getJitChild(comp: JitFnCompiler): BaseRunType | undefined {\n const member: BaseRunType = this.getMemberType();\n if (member.skipJit(comp)) return undefined;\n return member;\n }\n emitHasUnknownKeys(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileHasUnknownKeys(child, E);\n if (!codeResult?.code) return {code: undefined, type: E};\n const childName = comp.getChildVλl();\n const finalCode = this.isOptional() ? `(${childName} !== undefined && ${codeResult.code})` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n emitUnknownKeyErrors(comp: JitErrorsFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileUnknownKeyErrors(child, S);\n if (!codeResult?.code) return {code: undefined, type: S};\n const finalCode = this.isOptional() ? `if (${comp.getChildVλl()} !== undefined) {${codeResult.code}}` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n emitStripUnknownKeys(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileStripUnknownKeys(child, S);\n if (!codeResult?.code) return {code: undefined, type: S};\n const finalCode = this.isOptional() ? `if (${comp.getChildVλl()} !== undefined) {${codeResult.code}}` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileUnknownKeysToUndefined(child, S);\n if (!codeResult?.code) return {code: undefined, type: S};\n const finalCode = this.isOptional() ? `if (${comp.getChildVλl()} !== undefined) {${codeResult.code}}` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n visitToBinary(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const code = comp.compileToBinary(child, S);\n if (!code?.code) return {code: undefined, type: S};\n return this.isOptional()\n ? {code: `(${comp.getChildVλl()} !== undefined ? ${code.code} : utl.writeBinaryNull())`, type: S}\n : code;\n }\n visitFromBinary(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const code = comp.compileFromBinary(child, S);\n if (!code?.code) return {code: undefined, type: S};\n return code;\n }\n private getMemberTypeID = memorize((stack: BaseRunType<any>[] = []): StrNumber => {\n if (stack.length > MAX_STACK_DEPTH) throw new Error(maxStackErrorMessage);\n const optional = this.isOptional() ? '?' : '';\n const kind =\n (this.src as TypeProperty).name?.toString() ||\n (this.src as TypeIndexSignature).index?.kind ||\n this.src.subKind ||\n this.src.kind;\n const kindID = `${kind}${optional}`;\n const circularJitConf = this.checkIsCircularAndGetRefId(stack);\n if (circularJitConf) return `${kindID}:${circularJitConf}`;\n // TODO: some properties could be skipped from the JIT ID. so we could implement a mechanism to mark them to be skipped\n // ie: sample and sampleChars from StringFormat are too large but they do not affect jit code generation as those properties are only used during mocking\n stack.push(this);\n const member = this.getMemberType();\n const memberTypeID = member.getTypeID();\n const typeID = `${kindID}:${memberTypeID}`;\n stack.pop();\n return typeID;\n });\n}\n\n// ########## Load Composable Functions ##########\n"],"names":[],"mappings":";;;;;;;;;;;;AAsCW,UAAU;AACrB,MAAM,IAAI,UAAU;AACpB,MAAM,IAAI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,UAAM,SAAS,KAAK,cAAA;AACpB,UAAM,eAAe,OAAO,UAAA;AAC5B,UAAM,SAAS,GAAG,MAAM,IAAI,YAAY;AACxC,UAAM,IAAA;AACN,WAAO;AAAA,EACX,CAAC;AACL;"}
|
|
1
|
+
{"version":3,"file":"baseRunTypes.js","sources":["../../../../src/lib/baseRunTypes.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n/* ########\n * 2024 mion\n * Author: Ma-jerez\n * License: MIT\n * The software is provided \"as is\", without warranty of any kind.\n * ######## */\nimport {MAX_STACK_DEPTH, JitCompiledFn, createUniqueHash, getJitUtils, getENV} from '@mionjs/core';\nimport type {\n RunType,\n Mutable,\n RunTypeChildAccessor,\n JitFnID,\n SrcType,\n SrcCollection,\n CustomVλl,\n JitFn,\n JitCode,\n RunTypeOptions,\n StrNumber,\n DeepPartial,\n RunTypeFamily,\n} from '../types.ts';\nimport type {mockType} from '../mocking/mockType.ts';\nimport {maxStackErrorMessage} from '../constants.ts';\nimport {type CodeType, JitFunctions, CodeTypes} from '../constants.functions.ts';\nimport {ReflectionKind, stringifyType} from '@deepkit/type';\nimport type {TypeIndexSignature, TypeProperty, Type} from '@deepkit/type';\nimport {getPropIndex, memorize} from './utils.ts';\nimport {createJitCompiler, MockJitCompiler} from './jitFnCompiler.ts';\nimport {getJITFnHash} from './createJitFunction.ts';\nimport type {JitFnCompiler, JitErrorsFnCompiler} from './jitFnCompiler.ts';\nimport {type AnyKindName, getReflectionName} from '../constants.kind.ts';\nimport {initFormatAnnotations} from './formats.ts';\nimport {createTypeId} from './typeId.ts';\nimport {getJitFunctionCompiler, registerJitFunctionCompiler} from './jitFnsRegistry.ts';\nimport {defaultMockOptions} from '../mocking/constants.mock.ts';\n\nconst RB = CodeTypes.returnBlock;\nconst S = CodeTypes.statement;\nconst E = CodeTypes.expression;\n\nexport abstract class BaseRunType<T extends Type = Type> implements RunType {\n isCircular?: boolean;\n readonly src: SrcType<T> = null as any; // real value will be set after construction by the createRunType function\n abstract getFamily(): RunTypeFamily; // Atomic, Collection, Member, Function\n /**\n * This single functions controls whether or not the code for a type should be inlined into the parent function\n * or should create a separate jit function for it, add as a dependency and call it.\n * @returns\n */\n isJitInlined = (): boolean => {\n // if is circular, always create a separate jit function as need to self invoke\n if (this.isCircular) return false;\n if (getENV('DEBUG_JIT') === 'INLINED') return true;\n // all array are self invoked for isType and are usually repeated type like string[] or number[] so worth deduplicating\n if (this.src.kind === ReflectionKind.array) return false;\n // collection with name might be used in different places so worth deduplicating\n if (this.src.typeName && this.getFamily() === 'C') return false;\n return true;\n };\n getKindName = memorize((): AnyKindName => getReflectionName(this));\n getTypeName = (): string => this.src.typeName || this.getKindName();\n stringify = memorize((): string => stringifyType(this.src));\n skipJit(comp: JitFnCompiler): boolean {\n return false;\n }\n /** Returns the format portion of the type ID (cached in src._formatId), or undefined if no format. */\n getFormatTypeID(): string | undefined {\n // _formatId is cached by computeDeepkitFormatID during getDeepkitTypeId call\n // Empty string means no format, undefined means not computed yet\n const formatId = (this.src as any)._formatId;\n return formatId || undefined;\n }\n /** Returns the type ID which is cached in src._typeId by getDeepkitTypeId(). Format ID is already included. */\n getTypeID(): StrNumber {\n if (this.src._typeId === undefined) {\n throw new Error(`Missing cached type ID for ${this.getTypeName()}. Ensure getDeepkitTypeId() has been called.`);\n }\n return this.src._typeId;\n }\n getJitHash(opts: RunTypeOptions): string {\n const optsCopy = {...opts};\n // remove mock options as not relevant for jit functionality\n if (optsCopy.mock) delete optsCopy.mock;\n return createUniqueHash(this.getTypeID().toString() + JSON.stringify(optsCopy));\n }\n getParent = (): BaseRunType | undefined => (this.src.parent as SrcType)?._rt as BaseRunType;\n checkIsCircularAndGetRefId(stack: RunType[] = []): StrNumber | undefined {\n const inStackIndex = stack.findIndex((rt) => {\n if (rt === this) return true;\n // some nodes seems to be different objects in memory but are the same id, so we check by id as well\n return rt.src.id && this.src.id && rt.src.id === this.src.id;\n }); // cant use isSameJitType because it uses getTypeID and would loop forever\n const inStackSrcId = stack.findIndex((rt) => rt.src.id && this.src.id && rt.src.id === this.src.id);\n const isInStack = inStackIndex >= 0; // recursive reference\n if (isInStack) {\n this.isCircular = true;\n const name = this.src.typeName || ''; // todo: not sure if all the circular references will have a name\n const refId = '$' + this.src.kind + `_${inStackIndex}` + name; // ensures different circular types have different typeID\n return refId;\n }\n return undefined;\n }\n /**\n * Method that should be called Immediately after the RunType gets created to link the SrcType and RunType.\n * This is more flexible than passing params to the constructor helps to avoid circular dependencies, etc.\n * */\n onCreated(src: SrcType<any>): void {\n (this as Mutable<RunType>).src = src;\n (src as Mutable<SrcType>)._rt = this;\n initFormatAnnotations(this);\n // Cache the type ID on the src object - this includes format information\n createTypeId(src);\n }\n /**\n * Some elements might need a standalone name variable that ignores the vλl value of the parents.\n * returns a variable that is being compiled, ignores the parents variable names */\n getCustomVλl(comp: JitFnCompiler): CustomVλl | undefined {\n return undefined;\n }\n /**\n * Some elements might need a custom static path to be able to reference the source of an error.\n * ie: when validating a Map we need to differentiate if the value that failed is the key or the value of a map's entry.\n */\n getStaticPathLiteral(comp: JitFnCompiler): string | number | undefined {\n return undefined;\n }\n\n // ########## Mock ##########\n\n async mock(opts?: DeepPartial<RunTypeOptions>): Promise<any> {\n // although the mock function is not jit, it is also stored in the registry\n // this is because we don't want to load mock related functionality if not needed\n await registerJitFunctionCompiler(JitFunctions.mock);\n return this.mockType(opts);\n }\n\n /** synchronous version of mock, throws an error if the mock function has not been loaded */\n mockType(opts: DeepPartial<RunTypeOptions> = {}): any {\n const mockFn = getJitFunctionCompiler(JitFunctions.mock) as typeof mockType;\n if (!mockFn)\n throw new Error(\n `Function ${JitFunctions.mock.name} has not been loaded. make sure you have called loadJitCompilerFunction(JitFunctions.mock) before calling mockType.`\n );\n const fnID = JitFunctions.mock.id;\n // options sent to the compiler will be set to empty as mock options are handled separately from the compiler\n const mockingOpts = {...opts, mock: {...defaultMockOptions, ...(opts.mock || {})}} as RunTypeOptions;\n const hash = getJITFnHash(fnID, this, mockingOpts);\n const comp = new MockJitCompiler(this, mockingOpts, undefined, hash, this.getTypeID());\n return mockFn(this, comp);\n }\n\n // ########## Create Jit Functions ##########\n\n createJitFunction = (jitFn: JitFn, opts: RunTypeOptions = {}): ((...args: any[]) => any) => {\n return this.createJitCompiledFunction(jitFn.id, undefined, opts).fn;\n };\n\n createJitCompiledFunction(fnID: JitFnID, parentCop?: JitFnCompiler, opts: RunTypeOptions = {}): JitCompiledFn {\n const fnHash = getJITFnHash(fnID, this, opts);\n const jitCompiled = getJitUtils().getJIT(fnHash);\n if (jitCompiled) {\n if (getENV('DEBUG_JIT') === 'VERBOSE')\n console.log(`\\x1b[32m Using cached function: ${jitCompiled.jitFnHash} \\x1b[0m`);\n return jitCompiled;\n }\n const newJitCompiler: JitFnCompiler = createJitCompiler(\n this,\n fnID,\n parentCop,\n undefined,\n undefined,\n opts\n ) as JitFnCompiler;\n try {\n const codeType = this.getFamily() === 'A' ? E : S;\n newJitCompiler.compile(this, codeType, fnID);\n newJitCompiler.createJitFunction();\n } catch (e: any) {\n // if something goes wrong during compilation we want to remove the compiler from\n // the cache as this is automatically added to jitUtils cache during compilation\n newJitCompiler.removeFromJitCache();\n // TODO: we need to print the full path to the type that is causing the error\n // for this ideally we should add a parent Compiler and print the trace only from the root\n if (typeof e?.message === 'string' && !newJitCompiler.hasStackTrace(e.message))\n e.message += newJitCompiler.getStackTrace();\n throw e;\n }\n return newJitCompiler as JitCompiledFn;\n }\n\n // ########## emit Methods that generates src code ##########\n\n abstract emitIsType(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitTypeErrors(comp: JitErrorsFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitHasUnknownKeys(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitUnknownKeyErrors(comp: JitErrorsFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitStripUnknownKeys(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitUnknownKeysToUndefined(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n // todo: maybe we should move these two into a single file like the rest of serializers\n abstract emitPrepareForJson(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n abstract emitRestoreFromJson(comp: JitFnCompiler, expectedCType: CodeType): JitCode;\n}\n\n/**\n * RunType that is atomic an does not contains any other child runTypes.\n * ie: string, number, boolean, any, null, undefined, void, never, bigint, etc.\n * */\nexport abstract class AtomicRunType<T extends Type> extends BaseRunType<T> {\n getFamily(): 'A' {\n return 'A';\n }\n emitPrepareForJson(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitRestoreFromJson(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitHasUnknownKeys(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: E};\n }\n emitUnknownKeyErrors(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitStripUnknownKeys(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode {\n return {code: undefined, type: S};\n }\n}\n\n/**\n * RunType that contains a collection or child runTypes.\n * Collection RunTypes are the only ones that can have circular references. as a child of a collection RunType can be the parent of the collection RunType.\n * i.e: interface, child runTypes are it's properties\n * i.e: tuple, it's child runTypes are the tuple members\n */\nexport abstract class CollectionRunType<T extends Type> extends BaseRunType<T> {\n getFamily(): 'C' {\n return 'C';\n }\n getChildRunTypes = (): BaseRunType[] => {\n const childTypes = ((this.src as SrcCollection).types as SrcType[]) || []; // deepkit stores child types in the types property\n return childTypes.map((t) => t._rt as BaseRunType);\n };\n getJitChildren(comp: JitFnCompiler): BaseRunType[] {\n let skipIndex = false; // if there are multiple index signatures, only the first one will be used as they must be same type just different keys\n return this.getChildRunTypes().filter((c) => {\n if (c.skipJit(comp)) return false;\n const isIndex = c.src.kind === ReflectionKind.indexSignature;\n if (isIndex && skipIndex) return false;\n if (isIndex) skipIndex = true;\n return true;\n });\n }\n areAllChildrenOptional(children: BaseRunType[]) {\n return children.every(\n (prop) =>\n (prop as MemberRunType<any>)?.isOptional() ||\n (prop.src as TypeProperty)?.optional ||\n prop.src.kind === ReflectionKind.indexSignature\n );\n }\n emitHasUnknownKeys(comp: JitFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileHasUnknownKeys(c, E).code)\n .filter((code) => !!code);\n return {code: codes.join(' || '), type: E};\n }\n emitUnknownKeyErrors(comp: JitErrorsFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileUnknownKeyErrors(c, S).code)\n .filter((code) => !!code);\n return {code: codes.join(';'), type: S};\n }\n emitStripUnknownKeys(comp: JitFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileStripUnknownKeys(c, S).code)\n .filter((code) => !!code);\n return {code: codes.join(';'), type: S};\n }\n emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode {\n const codes = this.getJitChildren(comp)\n .map((c) => comp.compileUnknownKeysToUndefined(c, S).code)\n .filter((code) => !!code);\n return {code: codes.join(';'), type: S};\n }\n}\n\n/**\n * RunType that contains a single member or child RunType. usually part of a collection RunType.\n * i.e object properties, {prop: memberType} where memberType is the child RunType\n */\nexport abstract class MemberRunType<T extends Type> extends BaseRunType<T> implements RunTypeChildAccessor {\n abstract isOptional(): boolean;\n abstract getChildVarName(comp: JitFnCompiler): string | number;\n abstract getChildLiteral(comp: JitFnCompiler): string | number;\n abstract useArrayAccessor(): boolean;\n /** used to compile json stringify */\n skipCommas?: boolean;\n /** used to compile json stringify */\n tempChildVλl?: string;\n getFamily(): 'M' {\n return 'M';\n }\n getMemberType(): BaseRunType {\n const memberType = (this.src as any).type as SrcType; // deepkit stores member types in the type property\n return memberType._rt as BaseRunType;\n }\n getChildIndex(comp: JitFnCompiler) {\n const start = comp?.opts?.paramsSlice?.start;\n if (start) return getPropIndex(this.src) - start;\n return getPropIndex(this.src);\n }\n getJitChild(comp: JitFnCompiler): BaseRunType | undefined {\n const member: BaseRunType = this.getMemberType();\n if (member.skipJit(comp)) return undefined;\n return member;\n }\n emitHasUnknownKeys(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileHasUnknownKeys(child, E);\n if (!codeResult?.code) return {code: undefined, type: E};\n const childName = comp.getChildVλl();\n const finalCode = this.isOptional() ? `(${childName} !== undefined && ${codeResult.code})` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n emitUnknownKeyErrors(comp: JitErrorsFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileUnknownKeyErrors(child, S);\n if (!codeResult?.code) return {code: undefined, type: S};\n const finalCode = this.isOptional() ? `if (${comp.getChildVλl()} !== undefined) {${codeResult.code}}` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n emitStripUnknownKeys(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileStripUnknownKeys(child, S);\n if (!codeResult?.code) return {code: undefined, type: S};\n const finalCode = this.isOptional() ? `if (${comp.getChildVλl()} !== undefined) {${codeResult.code}}` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n emitUnknownKeysToUndefined(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const codeResult = comp.compileUnknownKeysToUndefined(child, S);\n if (!codeResult?.code) return {code: undefined, type: S};\n const finalCode = this.isOptional() ? `if (${comp.getChildVλl()} !== undefined) {${codeResult.code}}` : codeResult.code;\n return {code: finalCode, type: codeResult.type};\n }\n visitToBinary(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const code = comp.compileToBinary(child, S);\n if (!code?.code) return {code: undefined, type: S};\n return this.isOptional()\n ? {code: `(${comp.getChildVλl()} !== undefined ? ${code.code} : utl.writeBinaryNull())`, type: S}\n : code;\n }\n visitFromBinary(comp: JitFnCompiler): JitCode {\n const child = this.getJitChild(comp);\n const code = comp.compileFromBinary(child, S);\n if (!code?.code) return {code: undefined, type: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M,QAAW,MAAM,EAAA;AAChD,WAAO,KAAK,WAAA,IACN,EAAC,MAAM,IAAI,KAAK,YAAA,CAAa,oBAAoB,KAAK,IAAI,6BAA6B,MAAM,MAC7F;AAAA,EACV;AAAA,EACA,gBAAgB,MAA8B;AAC1C,UAAM,QAAQ,KAAK,YAAY,IAAI;AACnC,UAAM,OAAO,KAAK,kBAAkB,OAAO,CAAC;AAC5C,QAAI,CAAC,MAAM,KAAM,QAAO,EAAC,MAAM,QAAW,MAAM,EAAA;AAChD,WAAO;AAAA,EACX;AACJ;"}
|
|
@@ -30,8 +30,8 @@ export declare class BaseFnCompiler<FnArgsNames extends JitFnArgs = JitFnArgs, I
|
|
|
30
30
|
readonly code: string;
|
|
31
31
|
readonly contextCodeItems: Map<string, string>;
|
|
32
32
|
readonly isNoop?: boolean;
|
|
33
|
-
readonly jitDependencies: Array<string
|
|
34
|
-
readonly pureFnDependencies: Array<string
|
|
33
|
+
readonly jitDependencies: Array<string> | undefined;
|
|
34
|
+
readonly pureFnDependencies: Array<string> | undefined;
|
|
35
35
|
readonly stack: StackItem[];
|
|
36
36
|
popItem: StackItem | undefined;
|
|
37
37
|
get length(): number;
|
|
@@ -57,8 +57,8 @@ class BaseFnCompiler {
|
|
|
57
57
|
*/
|
|
58
58
|
isNoop = false;
|
|
59
59
|
/** The list of all jit functions that are used by this function and it's children. */
|
|
60
|
-
jitDependencies
|
|
61
|
-
pureFnDependencies
|
|
60
|
+
jitDependencies;
|
|
61
|
+
pureFnDependencies;
|
|
62
62
|
/** The list of types being compiled.*/
|
|
63
63
|
stack = [];
|
|
64
64
|
popItem;
|
|
@@ -179,7 +179,8 @@ ${fnCode}`);
|
|
|
179
179
|
}
|
|
180
180
|
updateDependencies(childComp) {
|
|
181
181
|
if (childComp.isNoop) return;
|
|
182
|
-
if (this.jitDependencies
|
|
182
|
+
if (this.jitDependencies?.includes(childComp.jitFnHash)) return;
|
|
183
|
+
if (!this.jitDependencies) this.jitDependencies = [];
|
|
183
184
|
this.jitDependencies.push(childComp.jitFnHash);
|
|
184
185
|
}
|
|
185
186
|
removeFromJitCache() {
|
|
@@ -496,7 +497,8 @@ ${fnCode}`);
|
|
|
496
497
|
`Pure function with name ${fnName} can not be added as jit dependency in namespace ${namespace}, be sure to register the pure function first by calling getJitUtils().addPureFn()`
|
|
497
498
|
);
|
|
498
499
|
const key = `${namespace}::${fnName}`;
|
|
499
|
-
if (this.pureFnDependencies
|
|
500
|
+
if (this.pureFnDependencies?.includes(key)) return;
|
|
501
|
+
if (!this.pureFnDependencies) this.pureFnDependencies = [];
|
|
500
502
|
this.pureFnDependencies.push(key);
|
|
501
503
|
}
|
|
502
504
|
}
|