ts-ref-kit 1.0.32 → 1.1.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/index.cjs +3 -3
- package/dist/cjs/parser/index.cjs +3 -3
- package/dist/esm/index.js +3 -3
- package/dist/esm/parser/index.js +3 -3
- package/package.json +2 -2
- package/types/parser/reflect-parser.d.ts +1 -63
- package/types/raw.d.ts +81 -0
- package/types/reflect-types/ClassDefinition.d.ts +6 -7
- package/types/reflect-types/EnumDefinition.d.ts +2 -1
- package/types/reflect-types/GenericClass.d.ts +12 -0
- package/types/reflect-types/GenericInterface.d.ts +10 -0
- package/types/reflect-types/GenericMethod.d.ts +12 -0
- package/types/reflect-types/GenericProperty.d.ts +7 -0
- package/types/reflect-types/InterfaceDefinition.d.ts +6 -5
- package/types/reflect-types/MethodDefinition.d.ts +10 -9
- package/types/reflect-types/PropertyDefinition.d.ts +9 -8
- package/types/reflect-types/{reflect-definitions.d.ts → TypeDefinition.d.ts} +7 -59
- package/types/reflect-types/ValidateResult.d.ts +16 -0
- package/types/reflect-types/fill-types.d.ts +3 -0
- package/types/reflect-types/function-validate.d.ts +9 -1
- package/types/reflect-types/index.d.ts +3 -3
- package/types/reflect-types/instance-validate.d.ts +5 -0
- package/types/reflect-types/package.d.ts +0 -7
- package/types/reflect-types/reflect-context.d.ts +10 -12
- package/types/reflect-types/share.d.ts +6 -0
- package/types/reflect-types/value-validate.d.ts +5 -0
- package/types/reflect-types/reflect-types.d.ts +0 -20
- package/types/reflect-types/reflect-validate.d.ts +0 -29
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var index_exports={};__export(index_exports,{AfterSerialized:()=>AfterSerialized,ClassDefinition:()=>ClassDefinition,EnumDefinition:()=>EnumDefinition,IgnoreSerialization:()=>IgnoreSerialization,InterfaceDefinition:()=>InterfaceDefinition,Lazy:()=>Lazy,MethodDefinition:()=>MethodDefinition3,PropertyDefinition:()=>PropertyDefinition3,PropertyWrapper:()=>PropertyWrapper,ReflectClass:()=>ReflectClass,ReflectContext:()=>ReflectContext,ReflectValidate:()=>ReflectValidate,Serialized:()=>Serialized,SerializedClass:()=>SerializedClass,SerializedName:()=>SerializedName,anyType:()=>anyType,asBoolean:()=>asBoolean,asNumber:()=>asNumber,asString:()=>asString,assertType:()=>assertType,callDecoratedMethod:()=>callDecoratedMethod,createNewInstance:()=>createNewInstance,defineDecoratedProperty:()=>defineDecoratedProperty,deserialize:()=>deserialize,deserializeArray:()=>deserializeArray,deserializeFrom:()=>deserializeFrom,done:()=>done,fillMethod:()=>fillMethod,fillProperty:()=>fillProperty,fillType:()=>fillType,getAnyValue:()=>getAnyValue,getClassByName:()=>getClassByName,getClassDefinition:()=>getClassDefinition2,getDecoratedProperty:()=>getDecoratedProperty,getDecoratedPropertyValue:()=>getDecoratedPropertyValue,getEnumDefinition:()=>getEnumDefinition2,getEnumNames:()=>getEnumNames,getEnumValues:()=>getEnumValues,getErrorTraceMessages:()=>getErrorTraceMessages,getInterfaceDefinition:()=>getInterfaceDefinition2,getOrSetValue:()=>getOrSetValue,getSerializeSettings:()=>getSerializeSettings,getTypeAliasDefinition:()=>getTypeAliasDefinition2,getTypeDef:()=>getTypeDef,getTypeDefinition:()=>getTypeDefinition,hasDecoratedMethod:()=>hasDecoratedMethod,hasGenerics:()=>hasGenerics,isArrayType:()=>isArrayType,isClassDefinition:()=>isClassDefinition,isDictionary:()=>isDictionary,isIgnoredType:()=>isIgnoredType,isIntersectionType:()=>isIntersectionType,isLiteralType:()=>isLiteralType,isNullable:()=>isNullable,isPrimitiveType:()=>isPrimitiveType,isTupleType:()=>isTupleType,isType:()=>isType,isTypeLiteralType:()=>isTypeLiteralType,isUnionType:()=>isUnionType,itSelf:()=>itSelf,mapAllProperties:()=>mapAllProperties,nullType:()=>nullType,registerMappable:()=>registerMappable,registerSerializedProperty:()=>registerSerializedProperty,registerTransform:()=>registerTransform,safeCall:()=>safeCall,safeSetValue:()=>safeSetValue,serialize:()=>serialize,serializeTo:()=>serializeTo,serializeToData:()=>serializeToData,setAnyValue:()=>setAnyValue,setDefaultIgnored:()=>setDefaultIgnored,validateArray:()=>validateArray,validateDictionary:()=>validateDictionary,validateFunctionArgument:()=>validateFunctionArgument,validateInstance:()=>validateInstance,validateValue:()=>validateValue});module.exports=__toCommonJS(index_exports);var primitiveTypes=["string","number","boolean","bigint","symbol"];function isIgnoredType(type){return!!(type.name&&["any","void","unknown"].includes(type.name))}function isPrimitiveType(type){return!!(type.name&&primitiveTypes.includes(type.name))}function isArrayType(type){return!!type.arrayElementType}function isLiteralType(type){return!!type.literalValue}function isTypeLiteralType(type){return!!type.typeLiteralMembers}function isUnionType(type){return!!type.unionMembers}function isIntersectionType(type){return!!type.intersectionMembers}function isTupleType(type){return!!type.tupleMembers}function isClassDefinition(type){return!!type.classDefinition}function hasGenerics(type){return!!type.generics}var classMap=new Map;var interfaceMap=new Map;var enumMap=new Map;var typeAliasMap=new Map;var classPool=new Map;var ReflectClass=(jsClass=>{classPool.set(jsClass.name,jsClass)});var ReflectContext={getClassDefinition,getInterfaceDefinition,getEnumDefinition,getTypeAliasDefinition};var reflect=Reflect;function getClassByName(className){var _a;initReflectContext();return(_a=getClassDefinition(className))==null?void 0:_a.jsClass}function getClassDefinition(arg){initReflectContext();switch(typeof arg){case"object":return getClassDefinition(arg.constructor);case"function":return getClassDefinition(arg.name)||Array.from(classMap.values()).find((classDef=>classDef.jsClass===arg));case"string":return classMap.get(arg)}}function getInterfaceDefinition(name){initReflectContext();return interfaceMap.get(name)}function getEnumDefinition(name){initReflectContext();return enumMap.get(name)}function getTypeAliasDefinition(name){initReflectContext();return typeAliasMap.get(name)}var initialized=false;var initReflectContext=()=>{if(initialized)return;reflect.__classes&&Object.entries(reflect.__classes).map(([className,rawClassDef])=>{const jsClass=reflect.__classDef[className];if(!jsClass)return void 0;classMap.set(className,new ClassDefinition(__spreadValues(__spreadValues({},rawClassDef),{jsClass})))});reflect.__interfaces&&Object.entries(reflect.__interfaces).map(([name,interfaceMeta])=>interfaceMap.set(name,new InterfaceDefinition(interfaceMeta)));reflect.__enums&&Object.entries(reflect.__enums).map(([name,enumMeta])=>enumMap.set(name,new EnumDefinition(enumMeta)));reflect.__typeAliases&&Object.entries(reflect.__typeAliases).map(([name,def])=>{typeAliasMap.set(name,fillType(def))});["__classDef","__classes","__interfaces","__enums","__typeAliases","initReflectContext"].forEach(it=>delete reflect[it]);initialized=true};var ClassDefinition=class{constructor(def){var _a,_b;this.name=def.name;this.superClassName=def.superClassName||"Object";this.superClass=getClassDefinition2(this.superClassName);this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[];this.jsClass=def.jsClass}get allMethods(){const results={};if(this.superClassName!=="Object"){const superClassDef=getClassDefinition2(this.superClassName);if(superClassDef){Object.assign(results,__spreadValues({},superClassDef.allMethods))}}Object.assign(results,__spreadValues({},toDictionary(this.methods,it=>[it.name,it])));return results}get allProperties(){var _a;return Object.assign(((_a=this.superClass)==null?void 0:_a.allProperties)||{},toDictionary(this.properties,it=>[it.name,it]))}get implementations(){if(!this._implementations){return mapNotNull(this._implementationNames,name=>getInterfaceDefinition2(name)||getTypeDefinition(name))}return this._implementations}get allImplementations(){var _a,_b;if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});(_b=(_a=this.superClass)==null?void 0:_a.allImplementations)==null?void 0:_b.forEach(it=>result.add(it));this._allImplementations=Array.from(result)}return this._allImplementations}getProperty(propName){return this.properties.find(it=>it.name===propName)}get type(){var _a,_b;const props={};(_b=(_a=this.superClass)==null?void 0:_a.type.typeLiteralMembers)==null?void 0:_b.forEach(prop=>props[prop.name]=prop);this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,classDefinition:this,typeLiteralMembers:Object.values(props)}}isSubClassOf(typeName){var _a;if(this.name===typeName)return true;if((_a=this.superClass)==null?void 0:_a.isSubClassOf(typeName))return true;return this.implementations.map(it=>it.name).includes(typeName)}isSuperClassOf(typeName){if(this.name===typeName)return true;const classDef=getClassDefinition2(typeName);if(!classDef)return false;return classDef.isSubClassOf(this.name)}toString(){return`class ${this.name}`}};function toDictionary(arr,handler){const dict={};arr.forEach(item=>{const[key,value]=handler(item);dict[key]=value});return dict}function mapNotNull(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}function setValue(target,field,value){if(target===void 0)return;target[field]=value}function getValue(target,field){if(target===void 0)return void 0;return target[field]}function mapNotNull2(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}var InterfaceDefinition=class _InterfaceDefinition{constructor(def){var _a,_b;this.name=def.name;this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[]}get implementations(){if(!this._implementations){this._implementations=mapNotNull2(this._implementationNames,name=>getInterfaceDefinition2(name)||getClassDefinition2(name)||getTypeDefinition(name))}return this._implementations}get allImplementations(){if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof _InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});this._allImplementations=Array.from(result)}return this._allImplementations}get type(){const props={};this.allImplementations.forEach(implDef=>{const type="type"in implDef?implDef.type:implDef;const interfaceProps=type.typeLiteralMembers;interfaceProps==null?void 0:interfaceProps.forEach(prop=>props[prop.name]=prop)});this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,typeLiteralMembers:Object.values(props)}}toString(){return`interface ${this.name}`}buildBaseObject(){const result={};this.properties.forEach(it=>setValue(result,it.name,void 0));this.methods.forEach(it=>setValue(result,it.name,()=>void 0));return result}};var EnumDefinition=class{constructor(def){this.name=def.name;this.members=new Map;def.members.forEach(member=>{const value=member.initializer===void 0?{name:"number"}:{literalValue:member.initializer};this.members.set(member.name,value)})}get type(){return{name:this.name,unionMembers:Array.from(this.members.values())}}get names(){return Array.from(this.members.keys())}};var MethodDefinition3=class{constructor(def){var _a;this.name=def.name;this.returnType=fillType(def.returnType);this.args=((_a=def.args)==null?void 0:_a.map(arg=>({name:arg.name,type:fillType(arg.type),isOptional:arg.isOptional})))||[];this.isPrivate=def.isPrivate||false;this.isStatic=def.isStatic||false;this.isAsync=def.isAsync||false}};function fillMethod(rawMethod){return new MethodDefinition3(rawMethod)}var PropertyDefinition3=class{constructor(def){this.name=def.name;this.isOptional=def.isOptional||false;this.isPrivate=def.isPrivate||false;this.isStatic=def.isStatic||false;this.type=fillType(def.type);this.accessor=def.accessor&&__spreadValues({},def.accessor)}};function fillProperty(rawProperty){return new PropertyDefinition3(rawProperty)}var anyType={name:"any"};var nullType={name:"null"};function getClassDefinition2(arg){return ReflectContext.getClassDefinition(arg)}function getInterfaceDefinition2(name){return ReflectContext.getInterfaceDefinition(name)}function getEnumDefinition2(name){return ReflectContext.getEnumDefinition(name)}function getTypeAliasDefinition2(name){return ReflectContext.getTypeAliasDefinition(name)}function getTypeDefinition(typeName){if(typeName==="any"||typeName==="Any"||typeName==="unknown"||typeName==="")return anyType;if(typeName==="null")return nullType;const classDef=getClassDefinition2(typeName)||getInterfaceDefinition2(typeName)||getEnumDefinition2(typeName);if(classDef)return classDef.type;const typeDef=getTypeAliasDefinition2(typeName);if(typeDef)return typeDef;return anyType}function getEnumNames(enumName){var _a;return((_a=getEnumDefinition2(enumName))==null?void 0:_a.names)||[]}function getEnumValues(args){const enumArg=Object.entries(args)[0];if(!enumArg)return[];const[enumName,obj]=enumArg;const enumDef=getEnumDefinition2(enumName);if(!enumDef)return Array.from(Object.keys(obj));return enumDef.names.map(name=>obj[name])}var typeMap=new Map;function fillType(rawType){const typeKey=stableStringify(rawType);if(rawType===void 0)return anyType;const typeDef=typeMap.get(typeKey);if(typeDef)return typeDef;const result={};typeMap.set(typeKey,result);if(typeof rawType==="string"){Object.assign(result,getTypeDefinition(rawType)||{},{name:rawType});return result}if(rawType.arrayElementType){Object.assign(result,{arrayElementType:fillType(rawType.arrayElementType)})}else if(rawType.unionMembers){Object.assign(result,{unionMembers:rawType.unionMembers.map(fillType)})}else if(rawType.intersectionMembers){Object.assign(result,{intersectionMembers:rawType.intersectionMembers.map(fillType)})}else if(rawType.tupleMembers){Object.assign(result,{tupleMembers:rawType.tupleMembers.map(fillType)})}else if(rawType.generics){Object.assign(result,fillType(rawType.generics[0]));result.generics=rawType.generics.slice(1).map(fillType)}return result}function stableStringify(obj){if(obj===null)return"null";if(obj===void 0)return"undefined";if(typeof obj!=="object")return JSON.stringify(obj);if(Array.isArray(obj)){return"["+obj.map(stableStringify).join(",")+"]"}const keys=Object.keys(obj).sort();return"{"+keys.map(k=>JSON.stringify(k)+":"+stableStringify(obj[k])).join(",")+"}"}var _ValidateResult=class _ValidateResult{constructor(success,errorMessage,cause){this.success=success;this.errorMessage=errorMessage;this.cause=cause}static failure(errorMessage,cause){return new _ValidateResult(false,errorMessage,cause)}get errorStackFlow(){if(!this.cause)return this.errorMessage;return[this.errorMessage,this.cause.errorStackFlow].join("\ncaused by: ")}};_ValidateResult.success=new _ValidateResult(true);var ValidateResult=_ValidateResult;var successResult=ValidateResult.success;var failedResult=ValidateResult.failure;var preservedTypes=[Promise,Date,Map,Set,Error,Function];function validateValue(value,type,depth=1){switch(true){case type.name==="undefined":return value===void 0?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isIgnoredType(type):return successResult;case isClassDefinition(type):return value instanceof Object?validateInstance(value,type.classDefinition.name,depth):failedResult(`declared as ${getTypeDisplayName(type)} but actually not an object`);case isArrayType(type):return validateArrayValue(value,type,depth);case isTupleType(type):return validateTupleValue(value,type,depth);case isUnionType(type):for(const unionMember of type.unionMembers||[]){const validateResult=validateValue(value,unionMember,depth);if(validateResult.success)return successResult}return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`);case isIntersectionType(type):for(const intersectionMember of type.intersectionMembers||[]){const validateResult=validateValue(value,intersectionMember,depth);if(!validateResult.success)return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`,validateResult)}return successResult;case isLiteralType(type):switch(typeof value){case"string":return value===trimQuotes(type.literalValue)?successResult:failedResult(`declared as string ${getTypeDisplayName(type)} but value not match`);case"number":return value===Number(type.literalValue)?successResult:failedResult(`declared as number ${getTypeDisplayName(type)} but value not match`);case"bigint":return value===BigInt(type.literalValue)?successResult:failedResult(`declared as bigint ${getTypeDisplayName(type)} but value not match`);case"boolean":return value===Boolean(type.literalValue)?successResult:failedResult(`declared as boolean ${getTypeDisplayName(type)} but value not match`);default:if(type.literalValue==="null"&&value===null)return successResult;return value===type.literalValue?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but value not match`)}case isTypeLiteralType(type):return validateProperties(value,type,depth);case type.isFunction:case type.isConstructor:return typeof value==="function"?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isPrimitiveType(type):return typeof value===type.name?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${typeof value}`);default:return validateSimpleValue(value,type,depth)}}function validateArrayValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not`)}if(depth===0)return successResult;for(const arrayItem of value){const validateResult=validateValue(arrayItem,type.arrayElementType||anyType,depth-1);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in array match`,validateResult)}}return successResult}function validateTupleValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not a tuple`)}if(depth===0)return successResult;let index=0;for(const tupleItem of type.tupleMembers){const tupleValue=value[index++];if(tupleItem.isOptionalInTuple&&tupleValue===void 0)continue;const validateResult=validateValue(value[index],tupleItem,depth);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in tuple match`,validateResult)}}return successResult}function validateProperties(value,type,depth=1){if(!(value instanceof Object)){return failedResult(`declared as ${getTypeDisplayName(type)} but not an object`)}else{for(const prop of type.typeLiteralMembers||[]){if(prop.isStatic)return successResult;if(prop.name.startsWith("[")&&prop.name.endsWith("]"))return successResult;if(depth===0)return successResult;let propType=prop.type||anyType;if(prop.isOptional)propType={unionMembers:[propType,{name:"undefined"}]};const propValue=getValue(value,prop.name);const validateResult=validateValue(propValue,propType,depth-1);if(!validateResult.success){return failedResult(`declared ${prop.name} as ${getTypeDisplayName(propType)}, but not match`,validateResult)}}return successResult}}function validateSimpleValue(value,type,depth=1){const typeName=typeof type==="string"?type:type.name;if(!typeName)return successResult;if(value===void 0){return failedResult(`declared as ${getTypeDisplayName(type)} but actually undefined`)}if(value===null){if(typeName==="null")return successResult;else return failedResult(`declared as ${getTypeDisplayName(type)} but actually null`)}for(const preservedType of preservedTypes){if(typeName===preservedType.name){return value instanceof preservedType?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${value.constructor.name}`)}}if(value instanceof Object&&!valueInstanceOf(value,typeName)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not instance of it`)}if(depth==0)return successResult;const result=validateValue(value,getTypeDefinition(typeName),depth);return result.success?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not match`,result)}function validateInstance(instance,typeName,depth=1){if(typeName){if(typeName!=="object"&&!valueInstanceOf(instance,typeName)){return failedResult(`declared as instance of ${typeName} but actually not`)}}else{typeName=instance.constructor.name}const typeDef=getTypeDefinition(typeName);if(typeName!=="any"&&typeDef===anyType){return failedResult(`${typeName} not defined`)}delete typeDef.classDefinition;return validateValue(instance,typeDef,depth)}function validateArray(array,typeName,depth=1){for(let i=0;i<array.length;i++){const result=validateInstance(array[i],typeName,depth);if(!result.success){return failedResult(`declared as instance of ${typeName}[] but [${i}] actually not`,result)}}return successResult}function validateDictionary(dict,typeName,depth=1){const entries=Object.entries(dict);for(let i=0;i<entries.length;i++){const[key,value]=entries[i];const result=validateInstance(value,typeName,depth);if(!result.success){return failedResult(`declared as instance of Dictionary<${typeName}> but [${key}] actually not`,result)}}return successResult}function valueInstanceOf(value,className){if(value===void 0)return true;if(value.constructor.name===className)return true;const classDef=getClassDefinition2(className);if(!classDef)return true;if(classDef.jsClass)return value instanceof classDef.jsClass;const instanceClassDef=getClassDefinition2(value);if(!instanceClassDef)return false;return instanceClassDef.isSubClassOf(classDef.name)}function trimQuotes(text){if(text.length>=2&&(text[0]==='"'&&text[text.length-1]==='"'||text[0]==="'"&&text[text.length-1]==="'")){return text.substring(1,text.length-1)}return text}function getTypeDisplayName(type){var _a,_b,_c;if(typeof type==="string"){return type}if(isClassDefinition(type)){return type.classDefinition.name}if(isArrayType(type)){return(((_a=type.arrayElementType)==null?void 0:_a.name)||"unknown")+"[]"}if(type.isConstructor){return"Class"}if(type.isFunction){return"Function"}if(isTypeLiteralType(type)){return"Object"}if(isTupleType(type)){return`(${type.tupleMembers.map(getTypeDisplayName).join(",")})`}if(isUnionType(type)){return((_b=type.unionMembers)==null?void 0:_b.map(getTypeDisplayName).join(" | "))||"unknown"}if(isIntersectionType(type)){return((_c=type.intersectionMembers)==null?void 0:_c.map(getTypeDisplayName).join(" & "))||"unknown"}if(isLiteralType(type)){return type.literalValue}return type.name||"unknown"}function getErrorTraceMessages(failureResult){const getAllTraceMessages=failureResult2=>failureResult2.errorMessage?[failureResult2.errorMessage,...failureResult2.cause?getAllTraceMessages(failureResult2.cause):[]]:[];return getAllTraceMessages(failureResult).join("\n-> ")}function validateFunctionArgument(args){const{funcName,optionsObj,value,argName,type,optional}=args;const v=value||optionsObj&&getValue(optionsObj,argName);if(v===void 0){if(!optional)throw Error(`Illegal arguments for ${funcName}: ${argName} is undefined`);else return}if(["string","number","boolean","bigint"].includes(type)){if(typeof v!==type)throw Error(`Illegal arguments for ${funcName}: ${argName} is not a ${type}`);return}if(typeof v!=="object")throw Error(`Illegal arguments for ${funcName}: ${argName} is not an object`);if(v===null)throw Error(`Illegal arguments for ${funcName}: ${argName} is null`);const result=validateInstance(v,type);if(!result.success)throw Error(`Illegal arguments for ${funcName}: ${result.errorMessage}`)}function safeSetValue(target,propName,value){const classDef=getClassDefinition2(target);if(!classDef){setValue(target,propName,value);return}const propDef=classDef.allProperties[propName];if(!propDef){throw new Error(`Property ${propName} is not defined in ${classDef.name}`)}const propType=propDef.type;const validateResult=validateValue(value,propType);if(!validateResult.success){throw new Error(validateResult.errorMessage)}setValue(target,propName,value)}function getTypeDef(type){if(typeof type==="string")return getTypeDefinition(type);if("array"in type)return{arrayElementType:getTypeDef(type.array)};if("union"in type)return{unionMembers:type.union.map(getTypeDef)};if("intersection"in type)return{intersectionMembers:type.intersection.map(getTypeDef)};if("tuple"in type)return{tupleMembers:type.tuple.map(getTypeDef)};else return type}function assertType(data,type,depth=5){const validateResult=validateValue(data,getTypeDef(type),depth);if(!validateResult.success){console.error(`assert failed with type: ${type}
|
|
2
|
-
${validateResult.errorStackFlow}`);debugger;throw new Error(`assert failed with type: ${type}, ${validateResult.errorStackFlow}`)}return data}function isNullable(type){return isType(null,type)}function isType(value,type){return validateValue(value,getTypeDef(type),3).success}var VALIDATE_WRAPPER=Symbol("VALIDATE_WRAPPER");var ReflectValidate=(target,propertyKey,descriptor)=>wrapValidateMethod(target,propertyKey,descriptor);function wrapValidateMethod(target,methodName,descriptor){const func=descriptor.value;if(typeof func!=="function")return;if(getValue(func,VALIDATE_WRAPPER))return;const getMethodDef=()=>{var _a,_b;return(_b=(_a=
|
|
3
|
-
${validateResult.errorStackFlow}`)}return value};let returnType=methodDef.returnType;if(returnType.name==="Promise"){returnType=((_a=returnType.generics)==null?void 0:_a[0])||anyType}if(result instanceof Promise){return result.then(res=>checkValue(res,returnType||anyType))}else{return checkValue(result,returnType||anyType)}}function getMethodDescription(className,methodDef){var _a;return`${className}.${methodDef.name}(${(_a=methodDef.args)==null?void 0:_a.map(it=>it.name).join(", ")})`}function safeCall(target,methodName,...args){const classDef=getClassDefinition2(target);if(!classDef)return;const methodDef=classDef.allMethods[methodName];if(!methodDef)return;validateMethodParams(target,methodDef,args);return getValue(target,methodName).apply(target,args)}var import_reflect_metadata=require("reflect-metadata");function asBoolean(value){if(String(value).toLocaleLowerCase()==="false")return false;return!!value}function asString(v){if(v===null||v===void 0||Number.isNaN(v)){return""}if(v instanceof Date&&String(v)==="Invalid Date"){return""}if(typeof v==="symbol"){return v.description||""}return String(v)}function asNumber(v){if(!v)return 0;if(v instanceof Date)return v.getDate();return Number(v)}function setAnyValue(target,field,value){;target[field]=value}function getAnyValue(target,field){return target[field]}function getOrSetValue(target,field,defaultWith){const value=target[field];if(value!==void 0)return value;const defaultValue=defaultWith();setAnyValue(target,field,defaultValue);return defaultValue}function isDictionary(value){return typeof value==="object"&&value!==null&&value.constructor===Object}function createNewInstance(clazz){const result=Object.create(clazz.prototype);result.constructor=this;return result}function defineDecoratedProperty(metaKey){return((self,propertyKey)=>Reflect.defineMetadata(metaKey,propertyKey,self.constructor))}function callDecoratedMethod(self,metaKey,...args){const method=getDecoratedPropertyValue(self,metaKey);if(method!==void 0&&method instanceof Function){return method.apply(self,args)}return void 0}function hasDecoratedMethod(self,metaKey){const method=getDecoratedPropertyValue(self,metaKey);return method!==void 0&&method instanceof Function}function getDecoratedProperty(target,metaKey){return Reflect.getMetadata(metaKey,target.constructor)}function getDecoratedPropertyValue(target,metaKey){const propName=getDecoratedProperty(target,metaKey);if(propName===void 0)return;return getAnyValue(target,propName)}var PropertyWrapper=function({getter,setter,fieldSymbol}){return(target,propertyKey)=>{Object.defineProperty(target,propertyKey,{get:function(){return getter?getter(this,propertyKey):PropertyWrapper.getField(target,propertyKey,fieldSymbol)},set:function(newValue){setter?setter(this,newValue,propertyKey):PropertyWrapper.setField(target,propertyKey,newValue,fieldSymbol)}})}};setAnyValue(PropertyWrapper,"getField",(owner,property,fieldSymbol)=>{var _a;return(_a=getAnyValue(owner,fieldSymbol))==null?void 0:_a[property]});setAnyValue(PropertyWrapper,"setField",(owner,property,newValue,fieldSymbol)=>{const fields=getAnyValue(owner,fieldSymbol)||{};fields[property]=newValue;setAnyValue(owner,fieldSymbol,fields)});function Lazy(creator){const symbol=Symbol("lazy");return PropertyWrapper({getter:(target,property)=>{const stored=PropertyWrapper.getField(target,property,symbol);if(stored)return stored.value;const value=creator(target,property);PropertyWrapper.setField(target,property,{value},symbol);return value},setter:()=>{},fieldSymbol:symbol})}var JSON_SERIALIZED=Symbol("JSON_SERIALIZED");var AFTER_SERIALIZED=Symbol("AFTER_SERIALIZED");var SerializeSettings=class{constructor(){this.settingsByName={};this.settingsBySerializedName={};this.ignoredProperties=[];this.defaultIgnored=false}add(prop){this.settingsByName[prop.propName]=prop;this.settingsBySerializedName[prop.serializedName]=prop}isPropertyIgnored(propName){if(this.defaultIgnored&&!this.settingsByName[propName]){return true}return this.ignoredProperties.indexOf(propName)!==-1}};var SerializedPropertySetting=class{constructor(target,propName,options){this.target=target;this.propName=propName;this.options=options;this.isArray=Reflect.getDesignType(target,propName)===Array;this.serializedName=options.name||asString(propName);this.class=options.class;this.fromJSON=this.createBuilder();this.toJSON=options.toJSON||(value=>serializeTo(value))}createBuilder(){if(this.options.fromJSON){return this.options.fromJSON}else if(this.class&&this.class instanceof Function){const clazz=this.class;return data=>{const transformer=jsonTransformers.get(clazz);return transformer?transformer.fromJson(data):deserialize(data,clazz)}}else{return data=>getValueByReflectType(this.target,this.propName,data)}}};function setDefaultIgnored(clazz,defaultIgnored){updateSerializeSettings(clazz,settings=>{settings.defaultIgnored=defaultIgnored})}function registerSerializedProperty(target,propName,options){const clazz=target.constructor;updateSerializeSettings(clazz,settings=>{settings.add(new SerializedPropertySetting(target,propName,options))})}function updateSerializeSettings(clazz,update){let settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){settings=new SerializeSettings}update(settings);Reflect.defineMetadata(JSON_SERIALIZED,settings,clazz)}var SerializedClass=Serialized();function Serialized(options){options=options||{};return(target,propName)=>registerSerializedProperty(target,asString(propName),options)}function SerializedName(serializedName){return(target,propName)=>registerSerializedProperty(target,asString(propName),{name:serializedName})}var IgnoreSerialization=(target,propName)=>updateSerializeSettings(target.constructor,settings=>settings.ignoredProperties.push(propName));function serialize(value){if(typeof value==="object")return JSON.stringify(serializeToData(value));return JSON.stringify(value)}function serializeTo(value){if(value===void 0)throw new Error("attempt to serialize undefined value");if(value===null)return null;const transformer=jsonTransformers.get(value.constructor);return transformer?transformer.toJson(value):serializeToData(value)}function serializeToData(object){var _a;if(object instanceof Array){return object.map(it=>serializeToData(it))}if(isDictionary(object)){const result={};Object.entries(object).forEach(it=>{const[prop,value]=it;result[prop]=serializeTo(value)});return result}const clazz=object.constructor;const reflectEnabled=(_a=getClassDefinition2(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){return object}const jsonMappingObject={};Object.entries(object).forEach(entry=>{const propName=entry[0];if(settings.isPropertyIgnored(propName))return;let value=entry[1];if(value===void 0||value instanceof Function||typeof value==="symbol")return;const propSetting=settings.settingsByName[propName];const serializedName=(propSetting==null?void 0:propSetting.serializedName)||propName;if(propSetting){if(propSetting.isArray){value=value.map(it=>propSetting.toJSON(it))}else{value=propSetting.toJSON(value)}}jsonMappingObject[serializedName]=value});return jsonMappingObject}function deserialize(json,constructorOrTarget){var _a;if(typeof json==="string"){json=JSON.parse(json)}if(constructorOrTarget===null)return json;if(constructorOrTarget===void 0)return json;try{const data=json;const clazz=constructorOrTarget instanceof Function?constructorOrTarget:constructorOrTarget.constructor;const reflectEnabled=(_a=getClassDefinition2(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const transformer=jsonTransformers.get(clazz);if(transformer)return transformer.fromJson(data);const target=constructorOrTarget instanceof Function?createNewInstance(constructorOrTarget):constructorOrTarget;deserializeFrom(data,target);if(reflectEnabled){const validateResult=validateInstance(target,clazz.name);if(!validateResult.success){throw new Error(`JSON deserialize validate failed: ${getErrorTraceMessages(validateResult)} `)}}return target}catch(e){console.error("failed to deserialize");console.dir(e);throw e}}function deserializeArray(json,clazz){const data=typeof json==="string"?JSON.parse(json):json;if(!(data instanceof Array)){return[]}return data.map(item=>deserialize(item,clazz))}function deserializeFrom(data,target){const clazz=target.constructor;const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){Object.assign(target,data);return}Object.keys(data).forEach(serializedName=>{const propDef=settings.settingsBySerializedName[serializedName];const jsonValue=data[serializedName];if(propDef===void 0){if(!settings.defaultIgnored){setAnyValue(target,serializedName,jsonValue)}return}const propName=propDef.propName;if(settings.isPropertyIgnored(propName)){return}let value;if(jsonValue instanceof Array){value=jsonValue.map(it=>propDef.fromJSON(it))}else{value=propDef.fromJSON(jsonValue)}setAnyValue(target,propName,value)});callDecoratedMethod(target,AFTER_SERIALIZED)}function getSerializeSettings(clazz){return Reflect.getMetadata(JSON_SERIALIZED,clazz)}function getValueByReflectType(target,propName,value){const reflectType=Reflect.getDesignType(target,propName);if(reflectType===void 0)return value;if(reflectType===Array)return deserializeArray(value);const transformer=jsonTransformers.get(reflectType);return transformer?transformer.fromJson(value):deserialize(value,reflectType)}var jsonTransformers=new Map;function registerTransform(clazz,transform){jsonTransformers.set(clazz,transform)}var itSelf=some=>some;var done=()=>void 0;registerTransform(String,{fromJson:asString,toJson:itSelf});registerTransform(Number,{fromJson:asNumber,toJson:itSelf});registerTransform(Boolean,{fromJson:asBoolean,toJson:itSelf});registerTransform(Date,{fromJson:anyValue=>new Date(asNumber(anyValue)),toJson:date=>date.getTime()});var AfterSerialized=defineDecoratedProperty(AFTER_SERIALIZED);var mapStatus=new Map;function registerMappable(mappableClass){if(mapStatus.get(mappableClass))return;const classDef=getClassDefinition2(mappableClass);const mapping=new Proxy({},{get(target,p){return doMap(p)},set(target,p,newValue){doMap(p)(newValue);return true}});function doMap(propName){return(fieldName,transform)=>{var _a,_b,_c;const propType=(_b=(_a=Object.values((classDef==null?void 0:classDef.allProperties)||{}))==null?void 0:_a.find(it=>it.name===propName))==null?void 0:_b.type;let propClass=(propType==null?void 0:propType.name)!==void 0?getClassByName(propType.name):void 0;if(propType&&isArrayType(propType)){propClass=((_c=propType.arrayElementType)==null?void 0:_c.name)!==void 0?getClassByName(propType.arrayElementType.name):void 0}if(typeof propName!=="string")return;registerSerializedProperty(mappableClass.prototype,propName,{name:fieldName,class:propClass,fromJSON:transform==null?void 0:transform.fromJSON,toJSON:transform==null?void 0:transform.toJSON});setDefaultIgnored(mappableClass,true)}}mappableClass.prototype.mapping(mapping);mapStatus.set(mappableClass,true)}function mapAllProperties(target,map){const classDef=getClassDefinition2(target);if(!classDef)return;classDef.properties.forEach(prop=>map[prop.name]())}var import_reflect_metadata2=require("reflect-metadata");var DESIGN_TYPE="design:type";var DESIGN_RETURNTYPE="design:returntype";var DESIGN_PARAMTYPES="design:paramtypes";function getDesignType(target,property){return Reflect.getMetadata(DESIGN_TYPE,target,property)}function getReturnType(target,property){return Reflect.getMetadata(DESIGN_RETURNTYPE,target,property)}function getParamTypes(target,property){return Reflect.getMetadata(DESIGN_PARAMTYPES,target,property)}function addMetadataList(key,value,target,propertyKey){const list=(propertyKey===void 0?Reflect.getMetadata(key,target):Reflect.getMetadata(key,target,propertyKey))||[];if(!list.includes(value))list.push(value);propertyKey===void 0?Reflect.defineMetadata(key,list,target):Reflect.defineMetadata(key,list,target,propertyKey)}Object.assign(Reflect,{getDesignType,getReturnType,getParamTypes,addMetadataList});0&&(module.exports={AfterSerialized,ClassDefinition,EnumDefinition,IgnoreSerialization,InterfaceDefinition,Lazy,MethodDefinition,PropertyDefinition,PropertyWrapper,ReflectClass,ReflectContext,ReflectValidate,Serialized,SerializedClass,SerializedName,anyType,asBoolean,asNumber,asString,assertType,callDecoratedMethod,createNewInstance,defineDecoratedProperty,deserialize,deserializeArray,deserializeFrom,done,fillMethod,fillProperty,fillType,getAnyValue,getClassByName,getClassDefinition,getDecoratedProperty,getDecoratedPropertyValue,getEnumDefinition,getEnumNames,getEnumValues,getErrorTraceMessages,getInterfaceDefinition,getOrSetValue,getSerializeSettings,getTypeAliasDefinition,getTypeDef,getTypeDefinition,hasDecoratedMethod,hasGenerics,isArrayType,isClassDefinition,isDictionary,isIgnoredType,isIntersectionType,isLiteralType,isNullable,isPrimitiveType,isTupleType,isType,isTypeLiteralType,isUnionType,itSelf,mapAllProperties,nullType,registerMappable,registerSerializedProperty,registerTransform,safeCall,safeSetValue,serialize,serializeTo,serializeToData,setAnyValue,setDefaultIgnored,validateArray,validateDictionary,validateFunctionArgument,validateInstance,validateValue});
|
|
1
|
+
var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var index_exports={};__export(index_exports,{AfterSerialized:()=>AfterSerialized,ClassDefinition:()=>ClassDefinition,EnumDefinition:()=>EnumDefinition,IgnoreSerialization:()=>IgnoreSerialization,InterfaceDefinition:()=>InterfaceDefinition,Lazy:()=>Lazy,MethodDefinition:()=>MethodDefinition,PropertyDefinition:()=>PropertyDefinition,PropertyWrapper:()=>PropertyWrapper,ReflectClass:()=>ReflectClass,ReflectValidate:()=>ReflectValidate,Serialized:()=>Serialized,SerializedClass:()=>SerializedClass,SerializedName:()=>SerializedName,ValidateResult:()=>ValidateResult,anyType:()=>anyType,asBoolean:()=>asBoolean,asNumber:()=>asNumber,asString:()=>asString,assertType:()=>assertType,callDecoratedMethod:()=>callDecoratedMethod,createNewInstance:()=>createNewInstance,defineDecoratedProperty:()=>defineDecoratedProperty,deserialize:()=>deserialize,deserializeArray:()=>deserializeArray,deserializeFrom:()=>deserializeFrom,done:()=>done,failedResult:()=>failedResult,fillMethod:()=>fillMethod,fillProperty:()=>fillProperty,getAnyValue:()=>getAnyValue,getClassByName:()=>getClassByName,getClassDefinition:()=>getClassDefinition,getDecoratedProperty:()=>getDecoratedProperty,getDecoratedPropertyValue:()=>getDecoratedPropertyValue,getEnumDefinition:()=>getEnumDefinition,getEnumNames:()=>getEnumNames,getEnumValues:()=>getEnumValues,getErrorTraceMessages:()=>getErrorTraceMessages,getInterfaceDefinition:()=>getInterfaceDefinition,getOrSetValue:()=>getOrSetValue,getSerializeSettings:()=>getSerializeSettings,getTypeAliasDefinition:()=>getTypeAliasDefinition,getTypeDef:()=>getTypeDef,getTypeDefinition:()=>getTypeDefinition,hasDecoratedMethod:()=>hasDecoratedMethod,hasGenerics:()=>hasGenerics,initReflectContext:()=>initReflectContext,isArrayType:()=>isArrayType,isClassDefinition:()=>isClassDefinition,isDictionary:()=>isDictionary,isIgnoredType:()=>isIgnoredType,isIntersectionType:()=>isIntersectionType,isLiteralType:()=>isLiteralType,isNullable:()=>isNullable,isPrimitiveType:()=>isPrimitiveType,isTupleType:()=>isTupleType,isType:()=>isType,isTypeLiteralType:()=>isTypeLiteralType,isUnionType:()=>isUnionType,itSelf:()=>itSelf,mapAllProperties:()=>mapAllProperties,nullType:()=>nullType,primitiveTypes:()=>primitiveTypes,registerMappable:()=>registerMappable,registerSerializedProperty:()=>registerSerializedProperty,registerTransform:()=>registerTransform,safeCall:()=>safeCall,serialize:()=>serialize,serializeTo:()=>serializeTo,serializeToData:()=>serializeToData,setAnyValue:()=>setAnyValue,setDefaultIgnored:()=>setDefaultIgnored,successResult:()=>successResult,validateArray:()=>validateArray,validateDictionary:()=>validateDictionary,validateFunctionArgument:()=>validateFunctionArgument,validateInstance:()=>validateInstance});module.exports=__toCommonJS(index_exports);var GenericProperty=class _GenericProperty extends PropertyDefinition{static create(proto,genericContext){const instance=createInstance(_GenericProperty,proto);instance.genericContext=genericContext;return instance}get type(){return fillType(this.rawDef.type,this.genericContext)}};var GenericMethod=class _GenericMethod extends MethodDefinition{static create(proto,genericContext){const instance=createInstance(_GenericMethod,proto);instance.genericContext=genericContext;return instance}get args(){var _a;return((_a=this.rawDef.args)==null?void 0:_a.map(arg=>({name:arg.name,type:fillType(arg.type,this.genericContext),isOptional:arg.isOptional})))||[]}get returnType(){return fillType(this.rawDef.returnType,this.genericContext)}};function createInstance(constructor,proto){const result=Object.create(constructor.prototype);Object.assign(result,proto);return result}function buildPropertiesAndMethods(ret,proto){ret.properties=proto.properties.map(p=>GenericProperty.create(p,ret.genericContext));ret.methods=proto.methods.map(m=>GenericMethod.create(m,ret.genericContext))}var GenericClass=class _GenericClass extends ClassDefinition{static create(proto,genericArgs){const instance=createInstance(_GenericClass,proto);instance.genericArgs=genericArgs;const ret=instance;ret.buildGenericContext();buildPropertiesAndMethods(ret,proto);return ret}buildGenericContext(){var _a;this.genericContext={};(_a=this.generics)==null?void 0:_a.forEach((genericName,index)=>this.genericContext[genericName]=this.genericArgs[index])}};var GenericInterface=class _GenericInterface extends InterfaceDefinition{static create(proto,genericArgs){const instance=createInstance(_GenericInterface,proto);instance.genericArgs=genericArgs;const ret=instance;ret.buildGenericContext();buildPropertiesAndMethods(ret,proto);return ret}buildGenericContext(){var _a;this.genericContext={};(_a=this.generics)==null?void 0:_a.forEach((genericName,index)=>this.genericContext[genericName]=this.genericArgs[index])}};var anyType={name:"any"};var nullType={name:"null"};var primitiveTypes=["string","number","boolean","bigint","symbol"];function isIgnoredType(type){return!!(type.name&&["any","void","unknown"].includes(type.name))}function isPrimitiveType(type){return!!(type.name&&primitiveTypes.includes(type.name))}function isArrayType(type){return!!type.arrayElementType}function isLiteralType(type){return!!type.literalValue}function isTypeLiteralType(type){return!!type.typeLiteralMembers}function isUnionType(type){return!!type.unionMembers}function isIntersectionType(type){return!!type.intersectionMembers}function isTupleType(type){return!!type.tupleMembers}function isClassDefinition(type){return!!type.classDefinition}function hasGenerics(type){return!!type.generics}function getTypeDefinition(typeName,genericArgs){if(typeName==="any"||typeName==="Any"||typeName==="unknown"||typeName==="")return anyType;if(typeName==="null")return nullType;const classDef=getClassDefinition(typeName);if(classDef){if(genericArgs)return GenericClass.create(classDef,genericArgs).type;else return classDef.type}if(primitiveTypes.includes(typeName)){return{name:typeName}}const interfaceDef=getInterfaceDefinition(typeName);if(interfaceDef){if(genericArgs)return GenericInterface.create(interfaceDef,genericArgs).type;return interfaceDef.type}const enumDef=getEnumDefinition(typeName);if(enumDef)return enumDef.type;const typeDef=getTypeAliasDefinition(typeName);if(typeDef)return typeDef;return anyType}var typeMap=new Map;function fillType(rawType,genericContext,genericArgs){const typeKey=stableStringify(rawType);if(rawType===void 0)return anyType;const typeDef=typeMap.get(typeKey);if(typeDef)return typeDef;const result={};typeMap.set(typeKey,result);if(typeof rawType==="string"){return(genericContext==null?void 0:genericContext[rawType])||getTypeDefinition(rawType,genericArgs)||anyType}if(rawType.arrayElementType){Object.assign(result,{arrayElementType:fillType(rawType.arrayElementType,genericContext)})}else if(rawType.unionMembers){Object.assign(result,{unionMembers:rawType.unionMembers.map(it=>fillType(it,genericContext))})}else if(rawType.intersectionMembers){Object.assign(result,{intersectionMembers:rawType.intersectionMembers.map(it=>fillType(it,genericContext))})}else if(rawType.tupleMembers){Object.assign(result,{tupleMembers:rawType.tupleMembers.map(it=>fillType(it,genericContext))})}else if(rawType.generics){const typeName=rawType.generics[0];const typeArgs=rawType.generics.slice(1).map(it=>fillType(it,genericContext));Object.assign(result,fillType(typeName,genericContext,typeArgs))}if(Object.keys(result).length===0)return anyType;return result}function stableStringify(obj){if(obj===null)return"null";if(obj===void 0)return"undefined";if(typeof obj!=="object")return JSON.stringify(obj);if(Array.isArray(obj)){return"["+obj.map(stableStringify).join(",")+"]"}const keys=Object.keys(obj).sort();return"{"+keys.map(k=>JSON.stringify(k)+":"+stableStringify(obj[k])).join(",")+"}"}var classMap=new Map;var interfaceMap=new Map;var enumMap=new Map;var typeAliasMap=new Map;var classPool=new Map;var ReflectClass=(jsClass=>{classPool.set(jsClass.name,jsClass)});var primitiveMap={string:String,number:Number,boolean:Boolean,object:Object};var reflect=Reflect;function getClassByName(className){var _a;return((_a=getClassDefinition(className))==null?void 0:_a.jsClass)||primitiveMap[className]}function getClassDefinition(arg){var _a,_b,_c;switch(typeof arg){case"object":return getClassDefinition(arg.constructor);case"function":const classDefByName=getClassDefinition(arg.name);if(classDefByName){return classDefByName}const classDefInStore=Array.from(classMap.values()).find((classDef=>classDef.jsClass===arg));if(classDefInStore){return classDefInStore}const classNameByRawDef=(_a=Object.entries(reflect.__classDef||{}).find(([_name,jsClass])=>jsClass===arg))==null?void 0:_a[0];if(classNameByRawDef){return getClassDefinition(classNameByRawDef)}else{return void 0}case"string":const className=arg;if(!classMap.has(className)){const rawClassDef=(_b=reflect.__classes)==null?void 0:_b[className];if(!rawClassDef){return void 0}const jsClass=(_c=reflect.__classDef)==null?void 0:_c[className];classMap.set(className,new ClassDefinition(__spreadValues(__spreadValues({},rawClassDef),{jsClass})))}return classMap.get(className)}}function getInterfaceDefinition(name){var _a;if(!interfaceMap.has(name)){const interfaceMeta=(_a=reflect.__interfaces)==null?void 0:_a[name];if(!interfaceMeta)return void 0;interfaceMap.set(name,new InterfaceDefinition(interfaceMeta))}return interfaceMap.get(name)}function getEnumDefinition(name){var _a;if(!enumMap.has(name)){const enumMeta=(_a=reflect.__enums)==null?void 0:_a[name];if(!enumMeta)return void 0;enumMap.set(name,new EnumDefinition(enumMeta))}return enumMap.get(name)}function getEnumNames(enumName){var _a;return((_a=getEnumDefinition(enumName))==null?void 0:_a.names)||[]}function getEnumValues(args){const enumArg=Object.entries(args)[0];if(!enumArg)return[];const[enumName,obj]=enumArg;const enumDef=getEnumDefinition(enumName);if(!enumDef)return Array.from(Object.keys(obj));return enumDef.names.map(name=>obj[name])}function getTypeAliasDefinition(name){var _a;if(!typeAliasMap.has(name)){const typeAliasMeta=fillType((_a=reflect.__typeAliases)==null?void 0:_a[name]);if(!typeAliasMeta)return void 0;typeAliasMap.set(name,typeAliasMeta)}return typeAliasMap.get(name)}function initReflectContext(){reflect.__classes&&Object.entries(reflect.__classes).map(([className,rawClassDef])=>{var _a;const jsClass=(_a=reflect.__classDef)==null?void 0:_a[className];if(!jsClass)return void 0;classMap.set(className,new ClassDefinition(__spreadValues(__spreadValues({},rawClassDef),{jsClass})))});reflect.__interfaces&&Object.entries(reflect.__interfaces).map(([name,interfaceMeta])=>interfaceMap.set(name,new InterfaceDefinition(interfaceMeta)));reflect.__enums&&Object.entries(reflect.__enums).map(([name,enumMeta])=>enumMap.set(name,new EnumDefinition(enumMeta)));reflect.__typeAliases&&Object.entries(reflect.__typeAliases).map(([name,def])=>{typeAliasMap.set(name,fillType(def))});["__classDef","__classes","__interfaces","__enums","__typeAliases","initReflectContext"].forEach(it=>delete reflect[it])}var ClassDefinition=class{constructor(def){var _a,_b;this.name=def.name;this.superClassName=def.superClassName||"Object";this.superClass=getClassDefinition(this.superClassName);this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[];this.jsClass=def.jsClass;this.generics=def.generics}get allMethods(){const results={};if(this.superClassName!=="Object"){const superClassDef=getClassDefinition(this.superClassName);if(superClassDef){Object.assign(results,__spreadValues({},superClassDef.allMethods))}}Object.assign(results,__spreadValues({},toDictionary(this.methods,it=>[it.name,it])));return results}get allProperties(){var _a;return Object.assign(((_a=this.superClass)==null?void 0:_a.allProperties)||{},toDictionary(this.properties,it=>[it.name,it]))}get implementations(){if(!this._implementations){return mapNotNull(this._implementationNames,name=>getInterfaceDefinition(name)||getTypeDefinition(name))}return this._implementations}get allImplementations(){var _a,_b;if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});(_b=(_a=this.superClass)==null?void 0:_a.allImplementations)==null?void 0:_b.forEach(it=>result.add(it));this._allImplementations=Array.from(result)}return this._allImplementations}getProperty(propName){return this.properties.find(it=>it.name===propName)}get type(){var _a,_b;const props={};(_b=(_a=this.superClass)==null?void 0:_a.type.typeLiteralMembers)==null?void 0:_b.forEach(prop=>props[prop.name]=prop);this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,classDefinition:this,typeLiteralMembers:Object.values(props)}}isSubClassOf(typeName){var _a;if(this.name===typeName)return true;if((_a=this.superClass)==null?void 0:_a.isSubClassOf(typeName))return true;return this.implementations.map(it=>it.name).includes(typeName)}isSuperClassOf(typeName){if(this.name===typeName)return true;const classDef=getClassDefinition(typeName);if(!classDef)return false;return classDef.isSubClassOf(this.name)}toString(){return`class ${this.name}`}};function toDictionary(arr,handler){const dict={};arr.forEach(item=>{const[key,value]=handler(item);dict[key]=value});return dict}function mapNotNull(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}function setValue(target,field,value){if(target===void 0)return;target[field]=value}function getValue(target,field){if(target===void 0)return void 0;return target[field]}function mapNotNull2(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}var InterfaceDefinition=class _InterfaceDefinition{constructor(def){var _a,_b;this.name=def.name;this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[];this.generics=def.generics}get implementations(){if(!this._implementations){this._implementations=mapNotNull2(this._implementationNames,name=>getInterfaceDefinition(name)||getClassDefinition(name).type||getTypeDefinition(name))}return this._implementations}get allImplementations(){if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof _InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});this._allImplementations=Array.from(result)}return this._allImplementations}get type(){const props={};this.allImplementations.forEach(implDef=>{const type="type"in implDef?implDef.type:implDef;const interfaceProps=type.typeLiteralMembers;interfaceProps==null?void 0:interfaceProps.forEach(prop=>props[prop.name]=prop)});this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,typeLiteralMembers:Object.values(props)}}toString(){return`interface ${this.name}`}buildBaseObject(){const result={};this.properties.forEach(it=>setValue(result,it.name,void 0));this.methods.forEach(it=>setValue(result,it.name,()=>void 0));return result}};var EnumDefinition=class{constructor(def){this.name=def.name;this.members=new Map;def.members.forEach(member=>{const value=member.initializer===void 0?{name:"number"}:{literalValue:member.initializer};this.members.set(member.name,value)})}get type(){return{name:this.name,unionMembers:Array.from(this.members.values())}}get names(){return Array.from(this.members.keys())}};var MethodDefinition=class{constructor(def){this.rawDef=def}get name(){return this.rawDef.name}get returnType(){return fillType(this.rawDef.returnType)}get args(){var _a;return((_a=this.rawDef.args)==null?void 0:_a.map(arg=>({name:arg.name,type:fillType(arg.type),isOptional:arg.isOptional})))||[]}get isPrivate(){return this.rawDef.isPrivate}get isStatic(){return this.rawDef.isStatic}get isAsync(){return this.rawDef.isAsync}};function fillMethod(rawMethod){return new MethodDefinition(rawMethod)}var PropertyDefinition=class{constructor(def){this.rawDef=def}get name(){return this.rawDef.name}get isOptional(){return this.rawDef.isOptional}get isPrivate(){return this.rawDef.isPrivate}get isStatic(){return this.rawDef.isStatic}get accessor(){return this.rawDef.accessor}get type(){return fillType(this.rawDef.type)}};function fillProperty(rawProperty){return new PropertyDefinition(rawProperty)}var _ValidateResult=class _ValidateResult{constructor(success,errorMessage,cause){this.success=success;this.errorMessage=errorMessage;this.cause=cause}static failure(errorMessage,cause){return new _ValidateResult(false,errorMessage,cause)}get errorStackFlow(){if(!this.cause)return this.errorMessage;return[this.errorMessage,this.cause.errorStackFlow].join("\ncaused by: ")}};_ValidateResult.success=new _ValidateResult(true);var ValidateResult=_ValidateResult;var successResult=ValidateResult.success;var failedResult=ValidateResult.failure;function getErrorTraceMessages(failureResult){const getAllTraceMessages=failureResult2=>failureResult2.errorMessage?[failureResult2.errorMessage,...failureResult2.cause?getAllTraceMessages(failureResult2.cause):[]]:[];return getAllTraceMessages(failureResult).join("\n-> ")}var preservedTypes=[Promise,Date,Map,Set,Error,Function];function validateValue(value,type,depth=1){switch(true){case type.name==="undefined":return value===void 0?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isIgnoredType(type):return successResult;case isClassDefinition(type):return value instanceof Object?validateClassInstance(value,type.classDefinition.name,depth):failedResult(`declared as ${getTypeDisplayName(type)} but actually not an object`);case isArrayType(type):return validateArrayValue(value,type,depth);case isTupleType(type):return validateTupleValue(value,type,depth);case isUnionType(type):for(const unionMember of type.unionMembers||[]){const validateResult=validateValue(value,unionMember,depth);if(validateResult.success)return successResult}return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`);case isIntersectionType(type):for(const intersectionMember of type.intersectionMembers||[]){const validateResult=validateValue(value,intersectionMember,depth);if(!validateResult.success)return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`,validateResult)}return successResult;case isLiteralType(type):switch(typeof value){case"string":return value===trimQuotes(type.literalValue)?successResult:failedResult(`declared as string ${getTypeDisplayName(type)} but value not match`);case"number":return value===Number(type.literalValue)?successResult:failedResult(`declared as number ${getTypeDisplayName(type)} but value not match`);case"bigint":return value===BigInt(type.literalValue)?successResult:failedResult(`declared as bigint ${getTypeDisplayName(type)} but value not match`);case"boolean":return value===Boolean(type.literalValue)?successResult:failedResult(`declared as boolean ${getTypeDisplayName(type)} but value not match`);default:if(type.literalValue==="null"&&value===null)return successResult;return value===type.literalValue?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but value not match`)}case isTypeLiteralType(type):return validateProperties(value,type,depth);case type.isFunction:case type.isConstructor:return typeof value==="function"?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isPrimitiveType(type):return typeof value===type.name?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${typeof value}`);default:return validateSimpleValue(value,type,depth)}}function validateArrayValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not`)}if(depth===0)return successResult;for(const arrayItem of value){const validateResult=validateValue(arrayItem,type.arrayElementType||anyType,depth-1);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in array match`,validateResult)}}return successResult}function validateTupleValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not a tuple`)}if(depth===0)return successResult;let index=0;for(const tupleItem of type.tupleMembers){const tupleValue=value[index++];if(tupleItem.isOptionalInTuple&&tupleValue===void 0)continue;const validateResult=validateValue(value[index],tupleItem,depth);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in tuple match`,validateResult)}}return successResult}function validateProperties(value,type,depth=1){if(!(value instanceof Object)){return failedResult(`declared as ${getTypeDisplayName(type)} but not an object`)}else{for(const prop of type.typeLiteralMembers||[]){if(prop.isStatic)return successResult;if(prop.name.startsWith("[")&&prop.name.endsWith("]"))return successResult;if(depth===0)return successResult;let propType=prop.type||anyType;if(prop.isOptional)propType={unionMembers:[propType,{name:"undefined"}]};const propValue=getValue(value,prop.name);const validateResult=validateValue(propValue,propType,depth-1);if(!validateResult.success){return failedResult(`declared ${prop.name} as ${getTypeDisplayName(propType)}, but not match`,validateResult)}}return successResult}}function validateSimpleValue(value,type,depth=1){const typeName=typeof type==="string"?type:type.name;if(!typeName)return successResult;if(value===void 0){return failedResult(`declared as ${getTypeDisplayName(type)} but actually undefined`)}if(value===null){if(typeName==="null")return successResult;else return failedResult(`declared as ${getTypeDisplayName(type)} but actually null`)}for(const preservedType of preservedTypes){if(typeName===preservedType.name){return value instanceof preservedType?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${value.constructor.name}`)}}if(value instanceof Object&&!valueInstanceOf(value,typeName)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not instance of it`)}if(depth==0)return successResult;const result=validateValue(value,getTypeDefinition(typeName),depth);return result.success?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not match`,result)}function validateClassInstance(instance,typeName,depth=3){if(typeName!=="object"&&!valueInstanceOf(instance,typeName)){return failedResult(`declared as instance of ${typeName} but actually not`)}const typeDef=getTypeDefinition(typeName);if(typeName!=="any"&&typeDef===anyType){return failedResult(`${typeName} not defined`)}delete typeDef.classDefinition;return validateValue(instance,typeDef,depth)}function valueInstanceOf(value,className){if(value===void 0)return true;if(value.constructor.name===className)return true;const classDef=getClassDefinition(className);if(!classDef)return true;if(classDef.jsClass)return value instanceof classDef.jsClass;const instanceClassDef=getClassDefinition(value);if(!instanceClassDef)return false;return instanceClassDef.isSubClassOf(classDef.name)}function trimQuotes(text){if(text.length>=2&&(text[0]==='"'&&text[text.length-1]==='"'||text[0]==="'"&&text[text.length-1]==="'")){return text.substring(1,text.length-1)}return text}function getTypeDisplayName(type){var _a,_b,_c;if(typeof type==="string"){return type}if(isClassDefinition(type)){return type.classDefinition.name}if(isArrayType(type)){return(((_a=type.arrayElementType)==null?void 0:_a.name)||"unknown")+"[]"}if(type.isConstructor){return"Class"}if(type.isFunction){return"Function"}if(isTypeLiteralType(type)){return"Object"}if(isTupleType(type)){return`(${type.tupleMembers.map(getTypeDisplayName).join(",")})`}if(isUnionType(type)){return((_b=type.unionMembers)==null?void 0:_b.map(getTypeDisplayName).join(" | "))||"unknown"}if(isIntersectionType(type)){return((_c=type.intersectionMembers)==null?void 0:_c.map(getTypeDisplayName).join(" & "))||"unknown"}if(isLiteralType(type)){return type.literalValue}return type.name||"unknown"}function validateInstance(instance,typeName,depth=3){typeName=typeName||instance.constructor.name;return validateClassInstance(instance,typeName,depth)}function validateArray(array,typeName,depth=1){for(let i=0;i<array.length;i++){const result=validateInstance(array[i],typeName,depth);if(!result.success){return failedResult(`declared as instance of ${typeName}[] but [${i}] actually not`,result)}}return successResult}function validateDictionary(dict,typeName,depth=1){const entries=Object.entries(dict);for(let i=0;i<entries.length;i++){const[key,value]=entries[i];const result=validateInstance(value,typeName,depth);if(!result.success){return failedResult(`declared as instance of Dictionary<${typeName}> but [${key}] actually not`,result)}}return successResult}function getTypeDef(type){if(typeof type==="string")return getTypeDefinition(type);if("array"in type)return{arrayElementType:getTypeDef(type.array)};if("union"in type)return{unionMembers:type.union.map(getTypeDef)};if("intersection"in type)return{intersectionMembers:type.intersection.map(getTypeDef)};if("tuple"in type)return{tupleMembers:type.tuple.map(getTypeDef)};else return type}function assertType(data,type,depth=5){const validateResult=validateValue(data,getTypeDef(type),depth);if(!validateResult.success){console.error(`assert failed with type: ${type}
|
|
2
|
+
${validateResult.errorStackFlow}`);debugger;throw new Error(`assert failed with type: ${type}, ${validateResult.errorStackFlow}`)}return data}function isNullable(type){return isType(null,type)}function isType(value,type){return validateValue(value,getTypeDef(type),3).success}var VALIDATE_WRAPPER=Symbol("VALIDATE_WRAPPER");var ReflectValidate=(target,propertyKey,descriptor)=>wrapValidateMethod(target,propertyKey,descriptor);function wrapValidateMethod(target,methodName,descriptor){const func=descriptor.value;if(typeof func!=="function")return;if(getValue(func,VALIDATE_WRAPPER))return;const getMethodDef=()=>{var _a,_b;return(_b=(_a=getClassDefinition(target))==null?void 0:_a.methods)==null?void 0:_b.find(it=>it.name===methodName)};const validateArgs=args=>validateMethodParams(target,getMethodDef(),args);const validateReturn=result=>validateMethodReturnValue(target,getMethodDef(),result);const newFunc=function(...args){validateArgs(args);const result=func.call(this,...args);return validateReturn(result)};newFunc[VALIDATE_WRAPPER]=func;descriptor.value=newFunc}function validateMethodParams(target,methodDef,args){var _a;(_a=methodDef==null?void 0:methodDef.args)==null?void 0:_a.forEach((argDef,index)=>{const arg=args==null?void 0:args[index];if(arg===void 0){if(!argDef.isOptional)throw new Error(`Illegal arguments for ${getMethodDescription(target.constructor.name,methodDef)}: ${argDef.name} is not optional`);else return}const validResult=validateValue(arg,argDef.type||anyType,1);if(!validResult.success){console.error("validateResult",validResult);throw new Error(`Illegal arguments for ${getMethodDescription(target.constructor.name,methodDef)}: ${argDef.name}: ${argDef.name} ${validResult.errorMessage}`)}})}function validateMethodReturnValue(target,methodDef,result){var _a;if(!methodDef)return result;const checkValue=(value,type)=>{const validateResult=validateValue(value,type,5);if(!validateResult.success){console.error(validateResult.errorStackFlow);throw new Error(`result for ${getMethodDescription(target.constructor.name,methodDef)} doesn't match type ${type.name}:
|
|
3
|
+
${validateResult.errorStackFlow}`)}return value};let returnType=methodDef.returnType;if(returnType.name==="Promise"){returnType=((_a=returnType.generics)==null?void 0:_a[0])||anyType}if(result instanceof Promise){return result.then(res=>checkValue(res,returnType||anyType))}else{return checkValue(result,returnType||anyType)}}function getMethodDescription(className,methodDef){var _a;return`${className}.${methodDef.name}(${(_a=methodDef.args)==null?void 0:_a.map(it=>it.name).join(", ")})`}function safeCall(target,methodName,...args){const classDef=getClassDefinition(target);if(!classDef)return;const methodDef=classDef.allMethods[methodName];if(!methodDef)return;validateMethodParams(target,methodDef,args);return getValue(target,methodName).apply(target,args)}function validateFunctionArgument(args){const{funcName,optionsObj,value,argName,type,optional}=args;const v=value||optionsObj&&getValue(optionsObj,argName);if(v===void 0){if(!optional)throw Error(`Illegal arguments for ${funcName}: ${argName} is undefined`);else return}if(["string","number","boolean","bigint"].includes(type)){if(typeof v!==type)throw Error(`Illegal arguments for ${funcName}: ${argName} is not a ${type}`);return}if(typeof v!=="object")throw Error(`Illegal arguments for ${funcName}: ${argName} is not an object`);if(v===null)throw Error(`Illegal arguments for ${funcName}: ${argName} is null`);const result=validateClassInstance(v,type);if(!result.success)throw Error(`Illegal arguments for ${funcName}: ${result.errorMessage}`)}var import_reflect_metadata=require("reflect-metadata");function asBoolean(value){if(String(value).toLocaleLowerCase()==="false")return false;return!!value}function asString(v){if(v===null||v===void 0||Number.isNaN(v)){return""}if(v instanceof Date&&String(v)==="Invalid Date"){return""}if(typeof v==="symbol"){return v.description||""}return String(v)}function asNumber(v){if(!v)return 0;if(v instanceof Date)return v.getDate();return Number(v)}function setAnyValue(target,field,value){;target[field]=value}function getAnyValue(target,field){return target[field]}function getOrSetValue(target,field,defaultWith){const value=target[field];if(value!==void 0)return value;const defaultValue=defaultWith();setAnyValue(target,field,defaultValue);return defaultValue}function isDictionary(value){return typeof value==="object"&&value!==null&&value.constructor===Object}function createNewInstance(clazz){const result=Object.create(clazz.prototype);result.constructor=this;return result}function defineDecoratedProperty(metaKey){return((self,propertyKey)=>Reflect.defineMetadata(metaKey,propertyKey,self.constructor))}function callDecoratedMethod(self,metaKey,...args){const method=getDecoratedPropertyValue(self,metaKey);if(method!==void 0&&method instanceof Function){return method.apply(self,args)}return void 0}function hasDecoratedMethod(self,metaKey){const method=getDecoratedPropertyValue(self,metaKey);return method!==void 0&&method instanceof Function}function getDecoratedProperty(target,metaKey){return Reflect.getMetadata(metaKey,target.constructor)}function getDecoratedPropertyValue(target,metaKey){const propName=getDecoratedProperty(target,metaKey);if(propName===void 0)return;return getAnyValue(target,propName)}var PropertyWrapper=function({getter,setter,fieldSymbol}){return(target,propertyKey)=>{Object.defineProperty(target,propertyKey,{get:function(){return getter?getter(this,propertyKey):PropertyWrapper.getField(target,propertyKey,fieldSymbol)},set:function(newValue){setter?setter(this,newValue,propertyKey):PropertyWrapper.setField(target,propertyKey,newValue,fieldSymbol)}})}};setAnyValue(PropertyWrapper,"getField",(owner,property,fieldSymbol)=>{var _a;return(_a=getAnyValue(owner,fieldSymbol))==null?void 0:_a[property]});setAnyValue(PropertyWrapper,"setField",(owner,property,newValue,fieldSymbol)=>{const fields=getAnyValue(owner,fieldSymbol)||{};fields[property]=newValue;setAnyValue(owner,fieldSymbol,fields)});function Lazy(creator){const symbol=Symbol("lazy");return PropertyWrapper({getter:(target,property)=>{const stored=PropertyWrapper.getField(target,property,symbol);if(stored)return stored.value;const value=creator(target,property);PropertyWrapper.setField(target,property,{value},symbol);return value},setter:()=>{},fieldSymbol:symbol})}var JSON_SERIALIZED=Symbol("JSON_SERIALIZED");var AFTER_SERIALIZED=Symbol("AFTER_SERIALIZED");var SerializeSettings=class{constructor(){this.settingsByName={};this.settingsBySerializedName={};this.ignoredProperties=[];this.defaultIgnored=false}add(prop){this.settingsByName[prop.propName]=prop;this.settingsBySerializedName[prop.serializedName]=prop}isPropertyIgnored(propName){if(this.defaultIgnored&&!this.settingsByName[propName]){return true}return this.ignoredProperties.indexOf(propName)!==-1}};var SerializedPropertySetting=class{constructor(target,propName,options){this.target=target;this.propName=propName;this.options=options;this.isArray=Reflect.getDesignType(target,propName)===Array;this.serializedName=options.name||asString(propName);this.class=options.class;this.fromJSON=this.createBuilder();this.toJSON=options.toJSON||(value=>serializeTo(value))}createBuilder(){if(this.options.fromJSON){return this.options.fromJSON}else if(this.class&&this.class instanceof Function){const clazz=this.class;return data=>{const transformer=jsonTransformers.get(clazz);return transformer?transformer.fromJson(data):deserialize(data,clazz)}}else{return data=>getValueByReflectType(this.target,this.propName,data)}}};function setDefaultIgnored(clazz,defaultIgnored){updateSerializeSettings(clazz,settings=>{settings.defaultIgnored=defaultIgnored})}function registerSerializedProperty(target,propName,options){const clazz=target.constructor;updateSerializeSettings(clazz,settings=>{settings.add(new SerializedPropertySetting(target,propName,options))})}function updateSerializeSettings(clazz,update){let settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){settings=new SerializeSettings}update(settings);Reflect.defineMetadata(JSON_SERIALIZED,settings,clazz)}var SerializedClass=Serialized();function Serialized(options){options=options||{};return(target,propName)=>registerSerializedProperty(target,asString(propName),options)}function SerializedName(serializedName){return(target,propName)=>registerSerializedProperty(target,asString(propName),{name:serializedName})}var IgnoreSerialization=(target,propName)=>updateSerializeSettings(target.constructor,settings=>settings.ignoredProperties.push(propName));function serialize(value){if(typeof value==="object")return JSON.stringify(serializeToData(value));return JSON.stringify(value)}function serializeTo(value){if(value===void 0)throw new Error("attempt to serialize undefined value");if(value===null)return null;const transformer=jsonTransformers.get(value.constructor);return transformer?transformer.toJson(value):serializeToData(value)}function serializeToData(object){var _a;if(object instanceof Array){return object.map(it=>serializeToData(it))}if(isDictionary(object)){const result={};Object.entries(object).forEach(it=>{const[prop,value]=it;result[prop]=serializeTo(value)});return result}const clazz=object.constructor;const reflectEnabled=(_a=getClassDefinition(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){return object}const jsonMappingObject={};Object.entries(object).forEach(entry=>{const propName=entry[0];if(settings.isPropertyIgnored(propName))return;let value=entry[1];if(value===void 0||value instanceof Function||typeof value==="symbol")return;const propSetting=settings.settingsByName[propName];const serializedName=(propSetting==null?void 0:propSetting.serializedName)||propName;if(propSetting){if(propSetting.isArray){value=value.map(it=>propSetting.toJSON(it))}else{value=propSetting.toJSON(value)}}jsonMappingObject[serializedName]=value});return jsonMappingObject}function deserialize(json,constructorOrTarget){var _a;if(typeof json==="string"){json=JSON.parse(json)}if(constructorOrTarget===null)return json;if(constructorOrTarget===void 0)return json;try{const data=json;const clazz=constructorOrTarget instanceof Function?constructorOrTarget:constructorOrTarget.constructor;const reflectEnabled=(_a=getClassDefinition(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const transformer=jsonTransformers.get(clazz);if(transformer)return transformer.fromJson(data);const target=constructorOrTarget instanceof Function?createNewInstance(constructorOrTarget):constructorOrTarget;deserializeFrom(data,target);if(reflectEnabled){const validateResult=validateInstance(target,clazz.name);if(!validateResult.success){throw new Error(`JSON deserialize validate failed: ${getErrorTraceMessages(validateResult)} `)}}return target}catch(e){console.error("failed to deserialize");console.dir(e);throw e}}function deserializeArray(json,clazz){const data=typeof json==="string"?JSON.parse(json):json;if(!(data instanceof Array)){return[]}return data.map(item=>deserialize(item,clazz))}function deserializeFrom(data,target){const clazz=target.constructor;const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){Object.assign(target,data);return}Object.keys(data).forEach(serializedName=>{const propDef=settings.settingsBySerializedName[serializedName];const jsonValue=data[serializedName];if(propDef===void 0){if(!settings.defaultIgnored){setAnyValue(target,serializedName,jsonValue)}return}const propName=propDef.propName;if(settings.isPropertyIgnored(propName)){return}let value;if(jsonValue instanceof Array){value=jsonValue.map(it=>propDef.fromJSON(it))}else{value=propDef.fromJSON(jsonValue)}setAnyValue(target,propName,value)});callDecoratedMethod(target,AFTER_SERIALIZED)}function getSerializeSettings(clazz){return Reflect.getMetadata(JSON_SERIALIZED,clazz)}function getValueByReflectType(target,propName,value){const reflectType=Reflect.getDesignType(target,propName);if(reflectType===void 0)return value;if(reflectType===Array)return deserializeArray(value);const transformer=jsonTransformers.get(reflectType);return transformer?transformer.fromJson(value):deserialize(value,reflectType)}var jsonTransformers=new Map;function registerTransform(clazz,transform){jsonTransformers.set(clazz,transform)}var itSelf=some=>some;var done=()=>void 0;registerTransform(String,{fromJson:asString,toJson:itSelf});registerTransform(Number,{fromJson:asNumber,toJson:itSelf});registerTransform(Boolean,{fromJson:asBoolean,toJson:itSelf});registerTransform(Date,{fromJson:anyValue=>new Date(asNumber(anyValue)),toJson:date=>date.getTime()});var AfterSerialized=defineDecoratedProperty(AFTER_SERIALIZED);var mapStatus=new Map;function registerMappable(mappableClass){if(mapStatus.get(mappableClass))return;const classDef=getClassDefinition(mappableClass);const mapping=new Proxy({},{get(target,p){return doMap(p)},set(target,p,newValue){doMap(p)(newValue);return true}});function doMap(propName){return(fieldName,transform)=>{var _a,_b,_c;const propType=(_b=(_a=Object.values((classDef==null?void 0:classDef.allProperties)||{}))==null?void 0:_a.find(it=>it.name===propName))==null?void 0:_b.type;let propClass=(propType==null?void 0:propType.name)!==void 0?getClassByName(propType.name):void 0;if(propType&&isArrayType(propType)){propClass=((_c=propType.arrayElementType)==null?void 0:_c.name)!==void 0?getClassByName(propType.arrayElementType.name):void 0}if(typeof propName!=="string")return;registerSerializedProperty(mappableClass.prototype,propName,{name:fieldName,class:propClass,fromJSON:transform==null?void 0:transform.fromJSON,toJSON:transform==null?void 0:transform.toJSON});setDefaultIgnored(mappableClass,true)}}mappableClass.prototype.mapping(mapping);mapStatus.set(mappableClass,true)}function mapAllProperties(target,map){const classDef=getClassDefinition(target);if(!classDef)return;classDef.properties.forEach(prop=>map[prop.name]())}var import_reflect_metadata2=require("reflect-metadata");var DESIGN_TYPE="design:type";var DESIGN_RETURNTYPE="design:returntype";var DESIGN_PARAMTYPES="design:paramtypes";function getDesignType(target,property){return Reflect.getMetadata(DESIGN_TYPE,target,property)}function getReturnType(target,property){return Reflect.getMetadata(DESIGN_RETURNTYPE,target,property)}function getParamTypes(target,property){return Reflect.getMetadata(DESIGN_PARAMTYPES,target,property)}function addMetadataList(key,value,target,propertyKey){const list=(propertyKey===void 0?Reflect.getMetadata(key,target):Reflect.getMetadata(key,target,propertyKey))||[];if(!list.includes(value))list.push(value);propertyKey===void 0?Reflect.defineMetadata(key,list,target):Reflect.defineMetadata(key,list,target,propertyKey)}Object.assign(Reflect,{getDesignType,getReturnType,getParamTypes,addMetadataList});0&&(module.exports={AfterSerialized,ClassDefinition,EnumDefinition,IgnoreSerialization,InterfaceDefinition,Lazy,MethodDefinition,PropertyDefinition,PropertyWrapper,ReflectClass,ReflectValidate,Serialized,SerializedClass,SerializedName,ValidateResult,anyType,asBoolean,asNumber,asString,assertType,callDecoratedMethod,createNewInstance,defineDecoratedProperty,deserialize,deserializeArray,deserializeFrom,done,failedResult,fillMethod,fillProperty,getAnyValue,getClassByName,getClassDefinition,getDecoratedProperty,getDecoratedPropertyValue,getEnumDefinition,getEnumNames,getEnumValues,getErrorTraceMessages,getInterfaceDefinition,getOrSetValue,getSerializeSettings,getTypeAliasDefinition,getTypeDef,getTypeDefinition,hasDecoratedMethod,hasGenerics,initReflectContext,isArrayType,isClassDefinition,isDictionary,isIgnoredType,isIntersectionType,isLiteralType,isNullable,isPrimitiveType,isTupleType,isType,isTypeLiteralType,isUnionType,itSelf,mapAllProperties,nullType,primitiveTypes,registerMappable,registerSerializedProperty,registerTransform,safeCall,serialize,serializeTo,serializeToData,setAnyValue,setDefaultIgnored,successResult,validateArray,validateDictionary,validateFunctionArgument,validateInstance});
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ue=Object.create;var C=Object.defineProperty;var me=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var Te=(e,n)=>{for(var t in n)C(e,t,{get:n[t],enumerable:!0})},H=(e,n,t,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of ye(n))!ge.call(e,o)&&o!==t&&C(e,o,{get:()=>n[o],enumerable:!(s=me(n,o))||s.enumerable});return e};var A=(e,n,t)=>(t=e!=null?ue(de(e)):{},H(n||!e||!e.__esModule?C(t,"default",{value:e,enumerable:!0}):t,e)),he=e=>H(C({},"__esModule",{value:!0}),e);var z=(e,n,t)=>new Promise((s,o)=>{var l=T=>{try{y(t.next(T))}catch(D){o(D)}},f=T=>{try{y(t.throw(T))}catch(D){o(D)}},y=T=>T.done?s(T.value):Promise.resolve(T.value).then(l,f);y((t=t.apply(e,n)).next())});var ke={};Te(ke,{DEBUG_CONFIG:()=>$,parseSource:()=>F,reflectLoader:()=>Q,reflectParserPlugin:()=>Me,setupReflectTypes:()=>De,updateReflectModules:()=>W});module.exports=he(ke);var j=A(require("typescript"),1);var i=A(require("typescript"),1),E=A(require("fs"),1),k=A(require("process"),1),w=A(require("path"),1),ne=require("url");var $={OUTPUT_LOG:!1},N=new Map,P=new Map,G=new Map,M=new Map,J=new Map,I=new Set,X={[i.default.SyntaxKind.BooleanKeyword]:"boolean",[i.default.SyntaxKind.StringKeyword]:"string",[i.default.SyntaxKind.BigIntKeyword]:"bigint",[i.default.SyntaxKind.NumberKeyword]:"number",[i.default.SyntaxKind.SymbolKeyword]:"symbol",[i.default.SyntaxKind.VoidKeyword]:"void",[i.default.SyntaxKind.UndefinedKeyword]:"undefined",[i.default.SyntaxKind.UnknownKeyword]:"unknown",[i.default.SyntaxKind.AnyKeyword]:"any",[i.default.SyntaxKind.ObjectKeyword]:"object"},O="any",te=["string","number","boolean","bigint","symbol"],ie=["any","Promise","Date","Error","undefined","unknown","object","Map","Set"],se=["Mappable","EnableReflect"];[...te,...ie,...se].forEach(fe);se.forEach(e=>P.set(e,{name:e}));var L,Y=!1,R=Reflect;function De(e){return z(this,null,function*(){let{filePaths:n,exclude:t,sourceFolder:s,distFolder:o}=e;if(s=w.resolve(s||k.cwd()),o=w.resolve(o||k.cwd()),R.__classes!==void 0)return;n=pe(n);let l=n.map(f=>w.join(s,f));F(l,t),R.__classes={};for(let[f,y]of N)R.__classes[f]=y;R.__interfaces={};for(let[f,y]of P)R.__interfaces[f]=y;R.__typeAliases={};for(let[f,y]of M)R.__typeAliases[f]=y;R.__constTypes={};for(let[f,y]of J)R.__constTypes[f]=y;yield Promise.all(n.map(f=>W(f,o)))})}function W(e,n){return z(this,null,function*(){let t=w.resolve(n,e);if(!E.existsSync(t))return;if(E.statSync(t).isDirectory()){E.readdirSync(t).forEach(T=>{W(w.join(e,T),n)});return}if(!e.endsWith(".js"))return;let o=w.join(n,e),f=yield import((0,ne.pathToFileURL)(o).href);R.__classDef={},Object.values(f).forEach(y=>{typeof y=="function"&&(R.__classDef[y.name]=y)})})}function F(e,n){if(e||(e=[k.cwd()]),e=pe(e),!Y){let t=re(e,n),s=i.default.createProgram(t,{});L=s.getTypeChecker(),t=t.map(l=>Z(l)),s.getSourceFiles().filter(l=>t.includes(Z(l.fileName))).forEach(l=>{b(`parse file: ${l.fileName}`),ae(l)});for(let l of I.keys())!N.has(l)&&!P.has(l)&&!G.has(l)&&!M.has(l)&&!te.includes(l)&&!ie.includes(l)&&(b(`remove unknown typeName: ${l}`),I.delete(l));Array.from(N.values()).forEach(_e),Array.from(P.values()).forEach(Oe),[N,P,M].forEach(Ne),Y=!0}return{classDefinitions:N,interfaceDefinitions:P,enumDefinitions:G,typeAliasDefinitions:M,constTypeDefinitions:J}}function re(e,n){let t=[];return e.forEach(s=>{if(s=w.resolve(s),Ke(s,n)){b(`ignore excluded ${s}`);return}if(!E.existsSync(s)){console.error(`Path ${s} does not exist.`);return}if(E.statSync(s).isFile()){t.push(s);return}E.readdirSync(s).forEach(f=>t.push(...re([w.join(s,f)],n)))}),t}function ae(e){i.default.isClassDeclaration(e)?we(e):i.default.isInterfaceDeclaration(e)?Re(e):i.default.isEnumDeclaration(e)?xe(e):i.default.isTypeAliasDeclaration(e)?be(e):i.default.isConstTypeReference(e)?Ee(e):e.forEachChild(ae)}function we(e){var y,T,D,x,u,h,K,v,U,d,r,m;let n=c(e.name);if(!n)return;let t=c((D=(T=(y=e.heritageClauses)==null?void 0:y.find(a=>a.token===i.default.SyntaxKind.ExtendsKeyword))==null?void 0:T.types)==null?void 0:D[0].expression),s=(u=(x=e.heritageClauses)==null?void 0:x.find(a=>a.token===i.default.SyntaxKind.ImplementsKeyword))==null?void 0:u.types.map(a=>c(a.expression)),o=[],l=[];for(let a of e.members)if(i.default.isPropertyDeclaration(a))o.push({name:c(a.name),isOptional:a.questionToken!==void 0,type:g(a),isPrivate:(h=a.modifiers)==null?void 0:h.some(p=>p.kind===i.default.SyntaxKind.PrivateKeyword),isStatic:(K=a.modifiers)==null?void 0:K.some(p=>p.kind===i.default.SyntaxKind.StaticKeyword)});else if(i.default.isMethodDeclaration(a))l.push({name:c(a.name),returnType:g(a),isPrivate:(v=a.modifiers)==null?void 0:v.some(p=>p.kind===i.default.SyntaxKind.PrivateKeyword),isStatic:(U=a.modifiers)==null?void 0:U.some(p=>p.kind===i.default.SyntaxKind.StaticKeyword),isAsync:(d=a.modifiers)==null?void 0:d.some(p=>p.kind===i.default.SyntaxKind.AsyncKeyword),args:a.parameters.map(p=>({name:c(p.name),type:g(p),isOptional:p.questionToken!==void 0}))});else if(i.default.isGetAccessorDeclaration(a)){let p=o.find(_=>_.name===c(a.name));p||(p={name:c(a.name),isOptional:a.questionToken===void 0,type:g(a)},o.push(p)),p.accessor=p.accessor||{},p.accessor.getter={isPrivate:((r=a.modifiers)==null?void 0:r.some(_=>_.kind===i.default.SyntaxKind.PrivateKeyword))||!1},p.isPrivate=p.accessor.getter.isPrivate}else if(i.default.isSetAccessorDeclaration(a)){let p=o.find(_=>_.name===c(a.name));p||(p={name:c(a.name),isOptional:a.questionToken===void 0,type:g(a)},o.push(p)),p.accessor=p.accessor||{},p.accessor.setter={isPrivate:((m=a.modifiers)==null?void 0:m.some(_=>_.kind===i.default.SyntaxKind.PrivateKeyword))||!1}}let f={name:n,superClassName:t,implementations:s,properties:o,methods:l};b(`Define class: ${c(e.name)}`),N.set(n,f)}function Re(e){var y,T,D,x;let n=c(e.name);if(!n)return;let t=((T=(y=e.heritageClauses)==null?void 0:y.find(u=>u.token===i.default.SyntaxKind.ExtendsKeyword))==null?void 0:T.types.map(u=>c(u.expression)))||[],s=[],o=[],l;for(let u of e.members)i.default.isPropertySignature(u)?s.push({name:c(u.name),isOptional:u.questionToken!==void 0,type:g(u),isPrivate:((D=u.modifiers)==null?void 0:D.some(h=>h.kind===i.default.SyntaxKind.PrivateKeyword))||!1}):i.default.isMethodSignature(u)?o.push({name:u.name.text,returnType:g(u),isPrivate:((x=u.modifiers)==null?void 0:x.some(h=>h.kind===i.default.SyntaxKind.PrivateKeyword))||!1,args:u.parameters.map(h=>({name:c(h.name),type:g(h),isOptional:h.questionToken!==void 0}))}):i.default.isIndexSignatureDeclaration(u)&&(l=g(u));let f=P.get(n);f?(f.implementations=q(f.implementations||[],t),f.methods=q(f.methods||[],o,(u,h)=>u.name===h.name),f.properties=q(f.properties||[],s,(u,h)=>u.name===h.name),f.indexElementType=l,b(`Merge interface ${c(e.name)}`)):(f={name:n,implementations:t,methods:o,properties:s,indexElementType:l},P.set(n,f),b(`Define interface ${c(e.name)}`))}function xe(e){let n=c(e.name);n&&(G.set(n,{name:n,members:e.members.map(t=>({name:c(t.name),initializer:c(t.initializer)}))}),b(`Define enum: ${c(e.name)}`))}function be(e){b(`Define typeAlias: ${c(e.name)}`),M.set(c(e.name),g(e))}function Ee(e){let n=e.parent.parent;i.default.isVariableDeclaration(n)&&n.initializer&&i.default.isAsExpression(n.initializer)&&J.set(c(n.name),oe(n.initializer.expression))}function oe(e){return i.default.isArrayLiteralExpression(e)?Se(e):i.default.isObjectLiteralExpression(e)?Pe(e):i.default.isNumericLiteral(e)?"number":i.default.isStringLiteral(e)?"string":i.default.isBigIntLiteral(e)?"bigint":[i.default.SyntaxKind.TrueKeyword,i.default.SyntaxKind.FalseKeyword].includes(e.kind)?"boolean":O}function Se(e){let n=[];return e.elements.forEach(t=>{if(i.default.isStringLiteral(t))return n.push(c(t))}),n.length===0?O:n.length===1?n[0]:{unionMembers:n}}function Pe(e){let n=[];return e.properties.map(t=>{i.default.isPropertyAssignment(t)?n.push({name:c(t.name),type:oe(t.initializer)}):b(`unsupported property: ${t.name}`)}),{typeLiteralMembers:n}}function fe(e){I.add(e)}function g(e,n=!1){if(e.type&&!n)return S(e.type);if(!L)return console.error("TypeChecker not initialized!"),O;let t=L.getTypeAtLocation(e),s=L.typeToTypeNode(t,void 0,void 0);return s?S("type"in s?s.type:s):O}function S(e){let n={};if(e===void 0)return O;if(i.default.isUnionTypeNode(e))n.unionMembers=e.types.map(S);else if(i.default.isIntersectionTypeNode(e))n.intersectionMembers=e.types.map(S);else if(i.default.isLiteralTypeNode(e))n.literalValue=c(e.literal);else if(i.default.isTypeLiteralNode(e)){let t=[];e.members.forEach(s=>{i.default.isPropertySignature(s)?t.push({name:c(s.name),isOptional:s.questionToken!==void 0,type:g(s)}):i.default.isIndexSignatureDeclaration(s)?n.indexElementType=g(s):t.push({name:c(s.name)||"",isOptional:s.questionToken!==void 0,type:S()})}),n.typeLiteralMembers=t}else if(i.default.isArrayTypeNode(e))n.arrayElementType=S(e.elementType);else if(i.default.isFunctionTypeNode(e))n.isFunction=!0;else if(i.default.isTypeReferenceNode(e))if(fe(c(e.typeName)),e.typeArguments)n.generics=[c(e.typeName),...e.typeArguments.map(t=>S(t))];else return c(e.typeName);else{if(i.default.isIndexedAccessTypeNode(e))return g(e,!0);if(i.default.isThisTypeNode(e))return g(e);if(i.default.isParenthesizedTypeNode(e))return g(e);if(i.default.isConditionalTypeNode(e))return g(e);if(i.default.isTypeQueryNode(e))return g(e);if(i.default.isConstructorTypeNode(e))n.isConstructor=!0;else if(i.default.isTupleTypeNode(e))n.tupleMembers=e.elements.map(S);else{if(Object.keys(X).includes(String(e.kind)))return X[e.kind]||O;if(i.default.isOptionalTypeNode(e))Object.assign(n,g(e)),n.isOptionalInTuple=!0;else if(i.default.isNamedTupleMember(e))Object.assign(n,g(e));else return i.default.isTypeOperatorNode(e)&&e.operator===i.default.SyntaxKind.KeyOfKeyword,g(e,!0)}}return n}var q=(e,n,t)=>[...(e==null?void 0:e.filter(s=>!(n!=null&&n.some(o=>(t||(()=>o===s))(o,s)))))||[],...n||[]];function V(e){if(e!==void 0&&e!==O)return typeof e=="string"?I.has(e)?e:void 0:e}function _e(e){var n,t;(n=e.methods)==null||n.forEach(le),(t=e.properties)==null||t.forEach(ce)}function Oe(e){var n,t;(n=e.methods)==null||n.forEach(le),(t=e.properties)==null||t.forEach(ce)}function ce(e){e.type=V(e.type)}function le(e){var n;(n=e.args)==null||n.forEach(t=>t.type=V(t.type)),e.returnType=V(e.returnType)}function c(e){if(!e)return e;if(e.end<0)return e.text;try{return i.default.isQualifiedName(e)?c(e.right):e.getText()}catch(n){return e.text}}function B(e){e&&Object.entries(e).forEach(n=>{let[t,s]=n;s instanceof Array&&s.length===0||s===!1||s===void 0?delete e[t]:s.constructor===Array?s.forEach(B):s.constructor===Object&&B(s)})}function Ne(e){for(let n of e.values())B(n)}function Ke(e,n){return n?(n=n instanceof Array?n:[n],n.some(t=>(t instanceof RegExp||(t=new RegExp(t.replace(/\./g,"\\.").replace(/\*/g,".*"))),e.match(t)))):!1}function Z(e,n=k.cwd()){return ee(e).replace(ee(n)+"/","")}function ee(e){let n=w.sep;return e.split(n).join("/")}function pe(e){return e instanceof Array?e:[e]}function b(e){$.OUTPUT_LOG&&console.log(e)}function Q(e){let{sourcePaths:n,exclude:t,forEnabledClassOnly:s,outputLog:o}=e;if(o&&($.OUTPUT_LOG=!0),!n)throw new Error("need provide source paths for reflect loader");let{classDefinitions:l,interfaceDefinitions:f,enumDefinitions:y,typeAliasDefinitions:T}=F(n,t),D=[],x=[];function u(d){let r=l.get(d),m=[];return r?(r.superClassName&&m.push(r.superClassName),m.push(...r.implementations||[])):(r=f.get(d),r?m.push(...r.implementations||[]):(r=T.get(d),r&&m.push(...r.implementations||[]))),m.flatMap(a=>[a,...u(a)])||[]}function h(d,r){return u(d.name).includes(r)}function K(d){if(j.default.isClassDeclaration(d)&&d.name!==void 0){let r=d.name.text,m=l.get(r);if(!r||!m||s&&!h(m,"EnableReflect"))return;x.push(`Reflect.__classDef = Object.assign(Reflect.__classDef || {}, { ${r} })`);return}d.forEachChild(K)}function v(){let d=[];return l.forEach((r,m)=>{s&&!h(r,"EnableReflect")||d.push(`Reflect.__classes = Object.assign(Reflect.__classes || {}, { ${m}: ${JSON.stringify(r)} })`)}),f.forEach((r,m)=>{s&&!h(r,"EnableReflect")||d.push(`Reflect.__interfaces = Object.assign(Reflect.__interfaces || {}, { ${m}: ${JSON.stringify(r)} })`)}),y.forEach((r,m)=>{d.push(`Reflect.__enums = Object.assign(Reflect.__enums || {}, { ${m}: ${JSON.stringify(r)} })`)}),T.forEach((r,m)=>{d.push(`Reflect.__typeAliases = Object.assign(Reflect.__typeAliases || {}, { ${m}: ${JSON.stringify(r)} })`)}),d.join(`
|
|
2
|
-
`)}return{outputAllMetas:
|
|
3
|
-
${t}`:n.transform(t,
|
|
1
|
+
var me=Object.create;var L=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var he=(e,n)=>{for(var t in n)L(e,t,{get:n[t],enumerable:!0})},X=(e,n,t,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let f of ye(n))!Te.call(e,f)&&f!==t&&L(e,f,{get:()=>n[f],enumerable:!(i=de(n,f))||i.enumerable});return e};var k=(e,n,t)=>(t=e!=null?me(ge(e)):{},X(n||!e||!e.__esModule?L(t,"default",{value:e,enumerable:!0}):t,e)),we=e=>X(L({},"__esModule",{value:!0}),e);var G=(e,n,t)=>new Promise((i,f)=>{var l=T=>{try{m(t.next(T))}catch(D){f(D)}},r=T=>{try{m(t.throw(T))}catch(D){f(D)}},m=T=>T.done?i(T.value):Promise.resolve(T.value).then(l,r);m((t=t.apply(e,n)).next())});var ve={};he(ve,{DEBUG_CONFIG:()=>j,parseSource:()=>U,reflectLoader:()=>H,reflectParserPlugin:()=>Me,setupReflectTypes:()=>De,updateReflectModules:()=>Q});module.exports=we(ve);var q=k(require("typescript"),1);var s=k(require("typescript"),1),x=k(require("fs"),1),v=k(require("process"),1),R=k(require("path"),1),te=require("url");var j={OUTPUT_LOG:!1},_=new Map,P=new Map,F=new Map,M=new Map,W=new Map,I=new Set,Y={[s.default.SyntaxKind.BooleanKeyword]:"boolean",[s.default.SyntaxKind.StringKeyword]:"string",[s.default.SyntaxKind.BigIntKeyword]:"bigint",[s.default.SyntaxKind.NumberKeyword]:"number",[s.default.SyntaxKind.SymbolKeyword]:"symbol",[s.default.SyntaxKind.VoidKeyword]:"void",[s.default.SyntaxKind.UndefinedKeyword]:"undefined",[s.default.SyntaxKind.UnknownKeyword]:"unknown",[s.default.SyntaxKind.AnyKeyword]:"any",[s.default.SyntaxKind.ObjectKeyword]:"object"},b="any",ie=["string","number","boolean","bigint","symbol"],se=["any","Promise","Date","Error","undefined","unknown","object","Map","Set"],re=["Mappable","EnableReflect"];[...ie,...se,...re].forEach(ce);re.forEach(e=>P.set(e,{name:e}));var $,Z=!1,w=Reflect;function De(e){return G(this,null,function*(){let{filePaths:n,exclude:t,sourceFolder:i,distFolder:f}=e;if(i=R.resolve(i||v.cwd()),f=R.resolve(f||v.cwd()),w.__classes!==void 0)return;n=ue(n);let l=n.map(r=>R.join(i,r));U(l,t),w.__classes={};for(let[r,m]of _)w.__classes[r]=m;w.__interfaces={};for(let[r,m]of P)w.__interfaces[r]=m;w.__typeAliases={};for(let[r,m]of M)w.__typeAliases[r]=m;w.__enums={};for(let[r,m]of F)w.__enums[r]=m;w.__constTypes={};for(let[r,m]of W)w.__constTypes[r]=m;yield Promise.all(n.map(r=>Q(r,f)))})}function Q(e,n){return G(this,null,function*(){let t=R.resolve(n,e);if(!x.existsSync(t))return;if(x.statSync(t).isDirectory()){x.readdirSync(t).forEach(T=>{Q(R.join(e,T),n)});return}if(!e.endsWith(".js"))return;let f=R.join(n,e),r=yield import((0,te.pathToFileURL)(f).href);w.__classDef={},Object.values(r).forEach(m=>{typeof m=="function"&&(w.__classDef[m.name]=m)})})}function U(e,n){if(e||(e=[v.cwd()]),e=ue(e),!Z){let t=ae(e,n),i=s.default.createProgram(t,{});$=i.getTypeChecker(),t=t.map(l=>ee(l)),i.getSourceFiles().filter(l=>t.includes(ee(l.fileName))).forEach(l=>{S(`parse file: ${l.fileName}`),oe(l)});for(let l of I.keys())!_.has(l)&&!P.has(l)&&!F.has(l)&&!M.has(l)&&!ie.includes(l)&&!se.includes(l)&&(S(`remove unknown typeName: ${l}`),I.delete(l));Array.from(_.values()).forEach(Oe),Array.from(P.values()).forEach(be),[_,P,M].forEach(_e),Z=!0}return{classDefinitions:_,interfaceDefinitions:P,enumDefinitions:F,typeAliasDefinitions:M,constTypeDefinitions:W}}function ae(e,n){let t=[];return e.forEach(i=>{if(i=R.resolve(i),Ae(i,n)){S(`ignore excluded ${i}`);return}if(!x.existsSync(i)){console.error(`Path ${i} does not exist.`);return}if(x.statSync(i).isFile()){t.push(i);return}x.readdirSync(i).forEach(r=>t.push(...ae([R.join(i,r)],n)))}),t}function oe(e){s.default.isClassDeclaration(e)?Re(e):s.default.isInterfaceDeclaration(e)?Ee(e):s.default.isEnumDeclaration(e)?Se(e):s.default.isTypeAliasDeclaration(e)?xe(e):s.default.isConstTypeReference(e)?Ne(e):e.forEachChild(oe)}function Re(e){var m,T,D,E,N,p,h,C,z,y,o,d,A;let n=a(e.name);if(!n)return;let t=a((D=(T=(m=e.heritageClauses)==null?void 0:m.find(c=>c.token===s.default.SyntaxKind.ExtendsKeyword))==null?void 0:T.types)==null?void 0:D[0].expression),i=(N=(E=e.heritageClauses)==null?void 0:E.find(c=>c.token===s.default.SyntaxKind.ImplementsKeyword))==null?void 0:N.types.map(c=>a(c.expression)),f=[],l=[];for(let c of e.members)if(s.default.isPropertyDeclaration(c))f.push({name:a(c.name),isOptional:c.questionToken!==void 0,type:g(c),isPrivate:(p=c.modifiers)==null?void 0:p.some(u=>u.kind===s.default.SyntaxKind.PrivateKeyword),isStatic:(h=c.modifiers)==null?void 0:h.some(u=>u.kind===s.default.SyntaxKind.StaticKeyword)});else if(s.default.isMethodDeclaration(c))l.push({name:a(c.name),returnType:g(c),isPrivate:(C=c.modifiers)==null?void 0:C.some(u=>u.kind===s.default.SyntaxKind.PrivateKeyword),isStatic:(z=c.modifiers)==null?void 0:z.some(u=>u.kind===s.default.SyntaxKind.StaticKeyword),isAsync:(y=c.modifiers)==null?void 0:y.some(u=>u.kind===s.default.SyntaxKind.AsyncKeyword),args:c.parameters.map(u=>({name:a(u.name),type:g(u),isOptional:u.questionToken!==void 0}))});else if(s.default.isGetAccessorDeclaration(c)){let u=f.find(O=>O.name===a(c.name));u||(u={name:a(c.name),isOptional:c.questionToken===void 0,type:g(c)},f.push(u)),u.accessor=u.accessor||{},u.accessor.getter={isPrivate:((o=c.modifiers)==null?void 0:o.some(O=>O.kind===s.default.SyntaxKind.PrivateKeyword))||!1},u.isPrivate=u.accessor.getter.isPrivate}else if(s.default.isSetAccessorDeclaration(c)){let u=f.find(O=>O.name===a(c.name));u||(u={name:a(c.name),isOptional:c.questionToken===void 0,type:g(c)},f.push(u)),u.accessor=u.accessor||{},u.accessor.setter={isPrivate:((d=c.modifiers)==null?void 0:d.some(O=>O.kind===s.default.SyntaxKind.PrivateKeyword))||!1}}let r={name:n,superClassName:t,implementations:i,properties:f,methods:l,generics:(A=e.typeParameters)==null?void 0:A.map(c=>a(c.name))};S(`Define class: ${a(e.name)}`),_.set(n,r)}function Ee(e){var m,T,D,E,N;let n=a(e.name);if(!n)return;let t=((T=(m=e.heritageClauses)==null?void 0:m.find(p=>p.token===s.default.SyntaxKind.ExtendsKeyword))==null?void 0:T.types.map(p=>a(p.expression)))||[],i=[],f=[],l;for(let p of e.members)s.default.isPropertySignature(p)?i.push({name:a(p.name),isOptional:p.questionToken!==void 0,type:g(p),isPrivate:((D=p.modifiers)==null?void 0:D.some(h=>h.kind===s.default.SyntaxKind.PrivateKeyword))||!1}):s.default.isMethodSignature(p)?f.push({name:p.name.text,returnType:g(p),isPrivate:((E=p.modifiers)==null?void 0:E.some(h=>h.kind===s.default.SyntaxKind.PrivateKeyword))||!1,args:p.parameters.map(h=>({name:a(h.name),type:g(h),isOptional:h.questionToken!==void 0}))}):s.default.isIndexSignatureDeclaration(p)&&(l=g(p));let r=P.get(n);r?(r.implementations=B(r.implementations||[],t),r.methods=B(r.methods||[],f,(p,h)=>p.name===h.name),r.properties=B(r.properties||[],i,(p,h)=>p.name===h.name),r.indexElementType=l,S(`Merge interface ${a(e.name)}`)):(r={name:n,implementations:t,methods:f,properties:i,indexElementType:l,generics:(N=e.typeParameters)==null?void 0:N.map(p=>a(p.name))},P.set(n,r),S(`Define interface ${a(e.name)}`))}function Se(e){let n=a(e.name);n&&(F.set(n,{name:n,members:e.members.map(t=>({name:a(t.name),initializer:a(t.initializer)}))}),S(`Define enum: ${a(e.name)}`))}function xe(e){S(`Define typeAlias: ${a(e.name)}`),M.set(a(e.name),g(e))}function Ne(e){let n=e.parent.parent;s.default.isVariableDeclaration(n)&&n.initializer&&s.default.isAsExpression(n.initializer)&&W.set(a(n.name),fe(n.initializer.expression))}function fe(e){return s.default.isArrayLiteralExpression(e)?Ke(e):s.default.isObjectLiteralExpression(e)?Pe(e):s.default.isNumericLiteral(e)?"number":s.default.isStringLiteral(e)?"string":s.default.isBigIntLiteral(e)?"bigint":[s.default.SyntaxKind.TrueKeyword,s.default.SyntaxKind.FalseKeyword].includes(e.kind)?"boolean":b}function Ke(e){let n=[];return e.elements.forEach(t=>{if(s.default.isStringLiteral(t))return n.push(a(t))}),n.length===0?b:n.length===1?n[0]:{unionMembers:n}}function Pe(e){let n=[];return e.properties.map(t=>{s.default.isPropertyAssignment(t)?n.push({name:a(t.name),type:fe(t.initializer)}):S(`unsupported property: ${t.name}`)}),{typeLiteralMembers:n}}function ce(e){I.add(e)}function g(e,n=!1){if(e.type&&!n)return K(e.type);if(!$)return console.error("TypeChecker not initialized!"),b;let t=$.getTypeAtLocation(e),i=$.typeToTypeNode(t,void 0,void 0);return i?K("type"in i?i.type:i):b}function K(e){let n={};if(e===void 0)return b;if(s.default.isUnionTypeNode(e))n.unionMembers=e.types.map(K);else if(s.default.isIntersectionTypeNode(e))n.intersectionMembers=e.types.map(K);else if(s.default.isLiteralTypeNode(e))n.literalValue=a(e.literal);else if(s.default.isTypeLiteralNode(e)){let t=[];e.members.forEach(i=>{s.default.isPropertySignature(i)?t.push({name:a(i.name),isOptional:i.questionToken!==void 0,type:g(i)}):s.default.isIndexSignatureDeclaration(i)?n.indexElementType=g(i):t.push({name:a(i.name)||"",isOptional:i.questionToken!==void 0,type:K()})}),n.typeLiteralMembers=t}else if(s.default.isArrayTypeNode(e))n.arrayElementType=K(e.elementType);else if(s.default.isFunctionTypeNode(e))n.isFunction=!0;else if(s.default.isTypeReferenceNode(e))if(ce(a(e.typeName)),e.typeArguments)n.generics=[a(e.typeName),...e.typeArguments.map(t=>K(t))];else return a(e.typeName);else{if(s.default.isIndexedAccessTypeNode(e))return g(e,!0);if(s.default.isThisTypeNode(e))return g(e);if(s.default.isParenthesizedTypeNode(e))return g(e);if(s.default.isConditionalTypeNode(e))return g(e);if(s.default.isTypeQueryNode(e))return g(e);if(s.default.isConstructorTypeNode(e))n.isConstructor=!0;else if(s.default.isTupleTypeNode(e))n.tupleMembers=e.elements.map(K);else{if(Object.keys(Y).includes(String(e.kind)))return Y[e.kind]||b;if(s.default.isOptionalTypeNode(e))Object.assign(n,g(e)),n.isOptionalInTuple=!0;else if(s.default.isNamedTupleMember(e))Object.assign(n,g(e));else return s.default.isTypeOperatorNode(e)&&e.operator===s.default.SyntaxKind.KeyOfKeyword,g(e,!0)}}return n}var B=(e,n,t)=>[...(e==null?void 0:e.filter(i=>!(n!=null&&n.some(f=>(t||(()=>f===i))(f,i)))))||[],...n||[]];function V(e,n){if(e!==void 0&&e!==b)return typeof e=="string"?I.has(e)||n!=null&&n.includes(e)?e:void 0:e}function Oe(e){var n,t;(n=e.methods)==null||n.forEach(i=>pe(i,e.generics)),(t=e.properties)==null||t.forEach(i=>le(i,e.generics))}function be(e){var n,t;(n=e.methods)==null||n.forEach(i=>pe(i,e.generics)),(t=e.properties)==null||t.forEach(i=>le(i,e.generics))}function le(e,n){e.type=V(e.type,n)}function pe(e,n){var t;(t=e.args)==null||t.forEach(i=>i.type=V(i.type,n)),e.returnType=V(e.returnType,n)}function a(e){if(!e)return e;if(e.end<0)return e.text;try{return s.default.isQualifiedName(e)?a(e.right):e.getText()}catch(n){return e.text}}function J(e){e&&Object.entries(e).forEach(n=>{let[t,i]=n;i instanceof Array&&i.length===0||i===!1||i===void 0?delete e[t]:i.constructor===Array?i.forEach(J):i.constructor===Object&&J(i)})}function _e(e){for(let n of e.values())J(n)}function Ae(e,n){return n?(n=n instanceof Array?n:[n],n.some(t=>(t instanceof RegExp||(t=new RegExp(t.replace(/\./g,"\\.").replace(/\*/g,".*"))),e.match(t)))):!1}function ee(e,n=v.cwd()){return ne(e).replace(ne(n)+"/","")}function ne(e){let n=R.sep;return e.split(n).join("/")}function ue(e){return e instanceof Array?e:[e]}function S(e){j.OUTPUT_LOG&&console.log(e)}function H(e){let{sourcePaths:n,exclude:t,forEnabledClassOnly:i,outputLog:f}=e;if(f&&(j.OUTPUT_LOG=!0),!n)throw new Error("need provide source paths for reflect loader");let{classDefinitions:l,interfaceDefinitions:r,enumDefinitions:m,typeAliasDefinitions:T}=U(n,t),D=[],E=[];function N(y){let o=l.get(y),d=[];return o?(o.superClassName&&d.push(o.superClassName),d.push(...o.implementations||[])):(o=r.get(y),o?d.push(...o.implementations||[]):(o=T.get(y),o&&d.push(...o.implementations||[]))),d.flatMap(A=>[A,...N(A)])||[]}function p(y,o){return N(y.name).includes(o)}function h(y){if(q.default.isClassDeclaration(y)&&y.name!==void 0){let o=y.name.text,d=l.get(o);if(!o||!d||i&&!p(d,"EnableReflect"))return;E.push(`Reflect.__classDef = Object.assign(Reflect.__classDef || {}, { ${o} })`);return}y.forEachChild(h)}function C(){let y=[];return l.forEach((o,d)=>{i&&!p(o,"EnableReflect")||y.push(`Reflect.__classes = Object.assign(Reflect.__classes || {}, { ${d}: ${JSON.stringify(o)} })`)}),r.forEach((o,d)=>{i&&!p(o,"EnableReflect")||y.push(`Reflect.__interfaces = Object.assign(Reflect.__interfaces || {}, { ${d}: ${JSON.stringify(o)} })`)}),m.forEach((o,d)=>{y.push(`Reflect.__enums = Object.assign(Reflect.__enums || {}, { ${d}: ${JSON.stringify(o)} })`)}),T.forEach((o,d)=>{y.push(`Reflect.__typeAliases = Object.assign(Reflect.__typeAliases || {}, { ${d}: ${JSON.stringify(o)} })`)}),y.join(`
|
|
2
|
+
`)}return{outputAllMetas:C,transform:(y,o)=>{if(o.endsWith(".ts")&&!(typeof n=="string"?[n]:n).every(d=>!o.startsWith(d)))try{let d=q.default.createSourceFile(o,y,q.default.ScriptTarget.Latest,!1);return D.length=0,E.length=0,h(d),`${D.join(";")};${y};${E.join(";")}`}catch(d){return console.error(`[reflect-parser-plugin] Error processing ${o}:`,d),null}}}}var ke=process.cwd().replace(/\\/g,"/")+"/";function Me(e){let n=H(e);return{name:"reflect-parser-plugin",enforce:"pre",transform:(t,i)=>(i=i.replace(ke,""),i===e.entry?`${n.outputAllMetas()}
|
|
3
|
+
${t}`:n.transform(t,i))}}0&&(module.exports={DEBUG_CONFIG,parseSource,reflectLoader,reflectParserPlugin,setupReflectTypes,updateReflectModules});
|
package/dist/esm/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var __defProp=Object.defineProperty;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var primitiveTypes=["string","number","boolean","bigint","symbol"];function isIgnoredType(type){return!!(type.name&&["any","void","unknown"].includes(type.name))}function isPrimitiveType(type){return!!(type.name&&primitiveTypes.includes(type.name))}function isArrayType(type){return!!type.arrayElementType}function isLiteralType(type){return!!type.literalValue}function isTypeLiteralType(type){return!!type.typeLiteralMembers}function isUnionType(type){return!!type.unionMembers}function isIntersectionType(type){return!!type.intersectionMembers}function isTupleType(type){return!!type.tupleMembers}function isClassDefinition(type){return!!type.classDefinition}function hasGenerics(type){return!!type.generics}var classMap=new Map;var interfaceMap=new Map;var enumMap=new Map;var typeAliasMap=new Map;var classPool=new Map;var ReflectClass=(jsClass=>{classPool.set(jsClass.name,jsClass)});var ReflectContext={getClassDefinition,getInterfaceDefinition,getEnumDefinition,getTypeAliasDefinition};var reflect=Reflect;function getClassByName(className){var _a;initReflectContext();return(_a=getClassDefinition(className))==null?void 0:_a.jsClass}function getClassDefinition(arg){initReflectContext();switch(typeof arg){case"object":return getClassDefinition(arg.constructor);case"function":return getClassDefinition(arg.name)||Array.from(classMap.values()).find((classDef=>classDef.jsClass===arg));case"string":return classMap.get(arg)}}function getInterfaceDefinition(name){initReflectContext();return interfaceMap.get(name)}function getEnumDefinition(name){initReflectContext();return enumMap.get(name)}function getTypeAliasDefinition(name){initReflectContext();return typeAliasMap.get(name)}var initialized=false;var initReflectContext=()=>{if(initialized)return;reflect.__classes&&Object.entries(reflect.__classes).map(([className,rawClassDef])=>{const jsClass=reflect.__classDef[className];if(!jsClass)return void 0;classMap.set(className,new ClassDefinition(__spreadValues(__spreadValues({},rawClassDef),{jsClass})))});reflect.__interfaces&&Object.entries(reflect.__interfaces).map(([name,interfaceMeta])=>interfaceMap.set(name,new InterfaceDefinition(interfaceMeta)));reflect.__enums&&Object.entries(reflect.__enums).map(([name,enumMeta])=>enumMap.set(name,new EnumDefinition(enumMeta)));reflect.__typeAliases&&Object.entries(reflect.__typeAliases).map(([name,def])=>{typeAliasMap.set(name,fillType(def))});["__classDef","__classes","__interfaces","__enums","__typeAliases","initReflectContext"].forEach(it=>delete reflect[it]);initialized=true};var ClassDefinition=class{constructor(def){var _a,_b;this.name=def.name;this.superClassName=def.superClassName||"Object";this.superClass=getClassDefinition2(this.superClassName);this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[];this.jsClass=def.jsClass}get allMethods(){const results={};if(this.superClassName!=="Object"){const superClassDef=getClassDefinition2(this.superClassName);if(superClassDef){Object.assign(results,__spreadValues({},superClassDef.allMethods))}}Object.assign(results,__spreadValues({},toDictionary(this.methods,it=>[it.name,it])));return results}get allProperties(){var _a;return Object.assign(((_a=this.superClass)==null?void 0:_a.allProperties)||{},toDictionary(this.properties,it=>[it.name,it]))}get implementations(){if(!this._implementations){return mapNotNull(this._implementationNames,name=>getInterfaceDefinition2(name)||getTypeDefinition(name))}return this._implementations}get allImplementations(){var _a,_b;if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});(_b=(_a=this.superClass)==null?void 0:_a.allImplementations)==null?void 0:_b.forEach(it=>result.add(it));this._allImplementations=Array.from(result)}return this._allImplementations}getProperty(propName){return this.properties.find(it=>it.name===propName)}get type(){var _a,_b;const props={};(_b=(_a=this.superClass)==null?void 0:_a.type.typeLiteralMembers)==null?void 0:_b.forEach(prop=>props[prop.name]=prop);this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,classDefinition:this,typeLiteralMembers:Object.values(props)}}isSubClassOf(typeName){var _a;if(this.name===typeName)return true;if((_a=this.superClass)==null?void 0:_a.isSubClassOf(typeName))return true;return this.implementations.map(it=>it.name).includes(typeName)}isSuperClassOf(typeName){if(this.name===typeName)return true;const classDef=getClassDefinition2(typeName);if(!classDef)return false;return classDef.isSubClassOf(this.name)}toString(){return`class ${this.name}`}};function toDictionary(arr,handler){const dict={};arr.forEach(item=>{const[key,value]=handler(item);dict[key]=value});return dict}function mapNotNull(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}function setValue(target,field,value){if(target===void 0)return;target[field]=value}function getValue(target,field){if(target===void 0)return void 0;return target[field]}function mapNotNull2(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}var InterfaceDefinition=class _InterfaceDefinition{constructor(def){var _a,_b;this.name=def.name;this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[]}get implementations(){if(!this._implementations){this._implementations=mapNotNull2(this._implementationNames,name=>getInterfaceDefinition2(name)||getClassDefinition2(name)||getTypeDefinition(name))}return this._implementations}get allImplementations(){if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof _InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});this._allImplementations=Array.from(result)}return this._allImplementations}get type(){const props={};this.allImplementations.forEach(implDef=>{const type="type"in implDef?implDef.type:implDef;const interfaceProps=type.typeLiteralMembers;interfaceProps==null?void 0:interfaceProps.forEach(prop=>props[prop.name]=prop)});this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,typeLiteralMembers:Object.values(props)}}toString(){return`interface ${this.name}`}buildBaseObject(){const result={};this.properties.forEach(it=>setValue(result,it.name,void 0));this.methods.forEach(it=>setValue(result,it.name,()=>void 0));return result}};var EnumDefinition=class{constructor(def){this.name=def.name;this.members=new Map;def.members.forEach(member=>{const value=member.initializer===void 0?{name:"number"}:{literalValue:member.initializer};this.members.set(member.name,value)})}get type(){return{name:this.name,unionMembers:Array.from(this.members.values())}}get names(){return Array.from(this.members.keys())}};var MethodDefinition3=class{constructor(def){var _a;this.name=def.name;this.returnType=fillType(def.returnType);this.args=((_a=def.args)==null?void 0:_a.map(arg=>({name:arg.name,type:fillType(arg.type),isOptional:arg.isOptional})))||[];this.isPrivate=def.isPrivate||false;this.isStatic=def.isStatic||false;this.isAsync=def.isAsync||false}};function fillMethod(rawMethod){return new MethodDefinition3(rawMethod)}var PropertyDefinition3=class{constructor(def){this.name=def.name;this.isOptional=def.isOptional||false;this.isPrivate=def.isPrivate||false;this.isStatic=def.isStatic||false;this.type=fillType(def.type);this.accessor=def.accessor&&__spreadValues({},def.accessor)}};function fillProperty(rawProperty){return new PropertyDefinition3(rawProperty)}var anyType={name:"any"};var nullType={name:"null"};function getClassDefinition2(arg){return ReflectContext.getClassDefinition(arg)}function getInterfaceDefinition2(name){return ReflectContext.getInterfaceDefinition(name)}function getEnumDefinition2(name){return ReflectContext.getEnumDefinition(name)}function getTypeAliasDefinition2(name){return ReflectContext.getTypeAliasDefinition(name)}function getTypeDefinition(typeName){if(typeName==="any"||typeName==="Any"||typeName==="unknown"||typeName==="")return anyType;if(typeName==="null")return nullType;const classDef=getClassDefinition2(typeName)||getInterfaceDefinition2(typeName)||getEnumDefinition2(typeName);if(classDef)return classDef.type;const typeDef=getTypeAliasDefinition2(typeName);if(typeDef)return typeDef;return anyType}function getEnumNames(enumName){var _a;return((_a=getEnumDefinition2(enumName))==null?void 0:_a.names)||[]}function getEnumValues(args){const enumArg=Object.entries(args)[0];if(!enumArg)return[];const[enumName,obj]=enumArg;const enumDef=getEnumDefinition2(enumName);if(!enumDef)return Array.from(Object.keys(obj));return enumDef.names.map(name=>obj[name])}var typeMap=new Map;function fillType(rawType){const typeKey=stableStringify(rawType);if(rawType===void 0)return anyType;const typeDef=typeMap.get(typeKey);if(typeDef)return typeDef;const result={};typeMap.set(typeKey,result);if(typeof rawType==="string"){Object.assign(result,getTypeDefinition(rawType)||{},{name:rawType});return result}if(rawType.arrayElementType){Object.assign(result,{arrayElementType:fillType(rawType.arrayElementType)})}else if(rawType.unionMembers){Object.assign(result,{unionMembers:rawType.unionMembers.map(fillType)})}else if(rawType.intersectionMembers){Object.assign(result,{intersectionMembers:rawType.intersectionMembers.map(fillType)})}else if(rawType.tupleMembers){Object.assign(result,{tupleMembers:rawType.tupleMembers.map(fillType)})}else if(rawType.generics){Object.assign(result,fillType(rawType.generics[0]));result.generics=rawType.generics.slice(1).map(fillType)}return result}function stableStringify(obj){if(obj===null)return"null";if(obj===void 0)return"undefined";if(typeof obj!=="object")return JSON.stringify(obj);if(Array.isArray(obj)){return"["+obj.map(stableStringify).join(",")+"]"}const keys=Object.keys(obj).sort();return"{"+keys.map(k=>JSON.stringify(k)+":"+stableStringify(obj[k])).join(",")+"}"}var _ValidateResult=class _ValidateResult{constructor(success,errorMessage,cause){this.success=success;this.errorMessage=errorMessage;this.cause=cause}static failure(errorMessage,cause){return new _ValidateResult(false,errorMessage,cause)}get errorStackFlow(){if(!this.cause)return this.errorMessage;return[this.errorMessage,this.cause.errorStackFlow].join("\ncaused by: ")}};_ValidateResult.success=new _ValidateResult(true);var ValidateResult=_ValidateResult;var successResult=ValidateResult.success;var failedResult=ValidateResult.failure;var preservedTypes=[Promise,Date,Map,Set,Error,Function];function validateValue(value,type,depth=1){switch(true){case type.name==="undefined":return value===void 0?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isIgnoredType(type):return successResult;case isClassDefinition(type):return value instanceof Object?validateInstance(value,type.classDefinition.name,depth):failedResult(`declared as ${getTypeDisplayName(type)} but actually not an object`);case isArrayType(type):return validateArrayValue(value,type,depth);case isTupleType(type):return validateTupleValue(value,type,depth);case isUnionType(type):for(const unionMember of type.unionMembers||[]){const validateResult=validateValue(value,unionMember,depth);if(validateResult.success)return successResult}return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`);case isIntersectionType(type):for(const intersectionMember of type.intersectionMembers||[]){const validateResult=validateValue(value,intersectionMember,depth);if(!validateResult.success)return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`,validateResult)}return successResult;case isLiteralType(type):switch(typeof value){case"string":return value===trimQuotes(type.literalValue)?successResult:failedResult(`declared as string ${getTypeDisplayName(type)} but value not match`);case"number":return value===Number(type.literalValue)?successResult:failedResult(`declared as number ${getTypeDisplayName(type)} but value not match`);case"bigint":return value===BigInt(type.literalValue)?successResult:failedResult(`declared as bigint ${getTypeDisplayName(type)} but value not match`);case"boolean":return value===Boolean(type.literalValue)?successResult:failedResult(`declared as boolean ${getTypeDisplayName(type)} but value not match`);default:if(type.literalValue==="null"&&value===null)return successResult;return value===type.literalValue?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but value not match`)}case isTypeLiteralType(type):return validateProperties(value,type,depth);case type.isFunction:case type.isConstructor:return typeof value==="function"?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isPrimitiveType(type):return typeof value===type.name?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${typeof value}`);default:return validateSimpleValue(value,type,depth)}}function validateArrayValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not`)}if(depth===0)return successResult;for(const arrayItem of value){const validateResult=validateValue(arrayItem,type.arrayElementType||anyType,depth-1);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in array match`,validateResult)}}return successResult}function validateTupleValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not a tuple`)}if(depth===0)return successResult;let index=0;for(const tupleItem of type.tupleMembers){const tupleValue=value[index++];if(tupleItem.isOptionalInTuple&&tupleValue===void 0)continue;const validateResult=validateValue(value[index],tupleItem,depth);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in tuple match`,validateResult)}}return successResult}function validateProperties(value,type,depth=1){if(!(value instanceof Object)){return failedResult(`declared as ${getTypeDisplayName(type)} but not an object`)}else{for(const prop of type.typeLiteralMembers||[]){if(prop.isStatic)return successResult;if(prop.name.startsWith("[")&&prop.name.endsWith("]"))return successResult;if(depth===0)return successResult;let propType=prop.type||anyType;if(prop.isOptional)propType={unionMembers:[propType,{name:"undefined"}]};const propValue=getValue(value,prop.name);const validateResult=validateValue(propValue,propType,depth-1);if(!validateResult.success){return failedResult(`declared ${prop.name} as ${getTypeDisplayName(propType)}, but not match`,validateResult)}}return successResult}}function validateSimpleValue(value,type,depth=1){const typeName=typeof type==="string"?type:type.name;if(!typeName)return successResult;if(value===void 0){return failedResult(`declared as ${getTypeDisplayName(type)} but actually undefined`)}if(value===null){if(typeName==="null")return successResult;else return failedResult(`declared as ${getTypeDisplayName(type)} but actually null`)}for(const preservedType of preservedTypes){if(typeName===preservedType.name){return value instanceof preservedType?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${value.constructor.name}`)}}if(value instanceof Object&&!valueInstanceOf(value,typeName)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not instance of it`)}if(depth==0)return successResult;const result=validateValue(value,getTypeDefinition(typeName),depth);return result.success?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not match`,result)}function validateInstance(instance,typeName,depth=1){if(typeName){if(typeName!=="object"&&!valueInstanceOf(instance,typeName)){return failedResult(`declared as instance of ${typeName} but actually not`)}}else{typeName=instance.constructor.name}const typeDef=getTypeDefinition(typeName);if(typeName!=="any"&&typeDef===anyType){return failedResult(`${typeName} not defined`)}delete typeDef.classDefinition;return validateValue(instance,typeDef,depth)}function validateArray(array,typeName,depth=1){for(let i=0;i<array.length;i++){const result=validateInstance(array[i],typeName,depth);if(!result.success){return failedResult(`declared as instance of ${typeName}[] but [${i}] actually not`,result)}}return successResult}function validateDictionary(dict,typeName,depth=1){const entries=Object.entries(dict);for(let i=0;i<entries.length;i++){const[key,value]=entries[i];const result=validateInstance(value,typeName,depth);if(!result.success){return failedResult(`declared as instance of Dictionary<${typeName}> but [${key}] actually not`,result)}}return successResult}function valueInstanceOf(value,className){if(value===void 0)return true;if(value.constructor.name===className)return true;const classDef=getClassDefinition2(className);if(!classDef)return true;if(classDef.jsClass)return value instanceof classDef.jsClass;const instanceClassDef=getClassDefinition2(value);if(!instanceClassDef)return false;return instanceClassDef.isSubClassOf(classDef.name)}function trimQuotes(text){if(text.length>=2&&(text[0]==='"'&&text[text.length-1]==='"'||text[0]==="'"&&text[text.length-1]==="'")){return text.substring(1,text.length-1)}return text}function getTypeDisplayName(type){var _a,_b,_c;if(typeof type==="string"){return type}if(isClassDefinition(type)){return type.classDefinition.name}if(isArrayType(type)){return(((_a=type.arrayElementType)==null?void 0:_a.name)||"unknown")+"[]"}if(type.isConstructor){return"Class"}if(type.isFunction){return"Function"}if(isTypeLiteralType(type)){return"Object"}if(isTupleType(type)){return`(${type.tupleMembers.map(getTypeDisplayName).join(",")})`}if(isUnionType(type)){return((_b=type.unionMembers)==null?void 0:_b.map(getTypeDisplayName).join(" | "))||"unknown"}if(isIntersectionType(type)){return((_c=type.intersectionMembers)==null?void 0:_c.map(getTypeDisplayName).join(" & "))||"unknown"}if(isLiteralType(type)){return type.literalValue}return type.name||"unknown"}function getErrorTraceMessages(failureResult){const getAllTraceMessages=failureResult2=>failureResult2.errorMessage?[failureResult2.errorMessage,...failureResult2.cause?getAllTraceMessages(failureResult2.cause):[]]:[];return getAllTraceMessages(failureResult).join("\n-> ")}function validateFunctionArgument(args){const{funcName,optionsObj,value,argName,type,optional}=args;const v=value||optionsObj&&getValue(optionsObj,argName);if(v===void 0){if(!optional)throw Error(`Illegal arguments for ${funcName}: ${argName} is undefined`);else return}if(["string","number","boolean","bigint"].includes(type)){if(typeof v!==type)throw Error(`Illegal arguments for ${funcName}: ${argName} is not a ${type}`);return}if(typeof v!=="object")throw Error(`Illegal arguments for ${funcName}: ${argName} is not an object`);if(v===null)throw Error(`Illegal arguments for ${funcName}: ${argName} is null`);const result=validateInstance(v,type);if(!result.success)throw Error(`Illegal arguments for ${funcName}: ${result.errorMessage}`)}function safeSetValue(target,propName,value){const classDef=getClassDefinition2(target);if(!classDef){setValue(target,propName,value);return}const propDef=classDef.allProperties[propName];if(!propDef){throw new Error(`Property ${propName} is not defined in ${classDef.name}`)}const propType=propDef.type;const validateResult=validateValue(value,propType);if(!validateResult.success){throw new Error(validateResult.errorMessage)}setValue(target,propName,value)}function getTypeDef(type){if(typeof type==="string")return getTypeDefinition(type);if("array"in type)return{arrayElementType:getTypeDef(type.array)};if("union"in type)return{unionMembers:type.union.map(getTypeDef)};if("intersection"in type)return{intersectionMembers:type.intersection.map(getTypeDef)};if("tuple"in type)return{tupleMembers:type.tuple.map(getTypeDef)};else return type}function assertType(data,type,depth=5){const validateResult=validateValue(data,getTypeDef(type),depth);if(!validateResult.success){console.error(`assert failed with type: ${type}
|
|
2
|
-
${validateResult.errorStackFlow}`);debugger;throw new Error(`assert failed with type: ${type}, ${validateResult.errorStackFlow}`)}return data}function isNullable(type){return isType(null,type)}function isType(value,type){return validateValue(value,getTypeDef(type),3).success}var VALIDATE_WRAPPER=Symbol("VALIDATE_WRAPPER");var ReflectValidate=(target,propertyKey,descriptor)=>wrapValidateMethod(target,propertyKey,descriptor);function wrapValidateMethod(target,methodName,descriptor){const func=descriptor.value;if(typeof func!=="function")return;if(getValue(func,VALIDATE_WRAPPER))return;const getMethodDef=()=>{var _a,_b;return(_b=(_a=
|
|
3
|
-
${validateResult.errorStackFlow}`)}return value};let returnType=methodDef.returnType;if(returnType.name==="Promise"){returnType=((_a=returnType.generics)==null?void 0:_a[0])||anyType}if(result instanceof Promise){return result.then(res=>checkValue(res,returnType||anyType))}else{return checkValue(result,returnType||anyType)}}function getMethodDescription(className,methodDef){var _a;return`${className}.${methodDef.name}(${(_a=methodDef.args)==null?void 0:_a.map(it=>it.name).join(", ")})`}function safeCall(target,methodName,...args){const classDef=getClassDefinition2(target);if(!classDef)return;const methodDef=classDef.allMethods[methodName];if(!methodDef)return;validateMethodParams(target,methodDef,args);return getValue(target,methodName).apply(target,args)}import"reflect-metadata";function asBoolean(value){if(String(value).toLocaleLowerCase()==="false")return false;return!!value}function asString(v){if(v===null||v===void 0||Number.isNaN(v)){return""}if(v instanceof Date&&String(v)==="Invalid Date"){return""}if(typeof v==="symbol"){return v.description||""}return String(v)}function asNumber(v){if(!v)return 0;if(v instanceof Date)return v.getDate();return Number(v)}function setAnyValue(target,field,value){;target[field]=value}function getAnyValue(target,field){return target[field]}function getOrSetValue(target,field,defaultWith){const value=target[field];if(value!==void 0)return value;const defaultValue=defaultWith();setAnyValue(target,field,defaultValue);return defaultValue}function isDictionary(value){return typeof value==="object"&&value!==null&&value.constructor===Object}function createNewInstance(clazz){const result=Object.create(clazz.prototype);result.constructor=this;return result}function defineDecoratedProperty(metaKey){return((self,propertyKey)=>Reflect.defineMetadata(metaKey,propertyKey,self.constructor))}function callDecoratedMethod(self,metaKey,...args){const method=getDecoratedPropertyValue(self,metaKey);if(method!==void 0&&method instanceof Function){return method.apply(self,args)}return void 0}function hasDecoratedMethod(self,metaKey){const method=getDecoratedPropertyValue(self,metaKey);return method!==void 0&&method instanceof Function}function getDecoratedProperty(target,metaKey){return Reflect.getMetadata(metaKey,target.constructor)}function getDecoratedPropertyValue(target,metaKey){const propName=getDecoratedProperty(target,metaKey);if(propName===void 0)return;return getAnyValue(target,propName)}var PropertyWrapper=function({getter,setter,fieldSymbol}){return(target,propertyKey)=>{Object.defineProperty(target,propertyKey,{get:function(){return getter?getter(this,propertyKey):PropertyWrapper.getField(target,propertyKey,fieldSymbol)},set:function(newValue){setter?setter(this,newValue,propertyKey):PropertyWrapper.setField(target,propertyKey,newValue,fieldSymbol)}})}};setAnyValue(PropertyWrapper,"getField",(owner,property,fieldSymbol)=>{var _a;return(_a=getAnyValue(owner,fieldSymbol))==null?void 0:_a[property]});setAnyValue(PropertyWrapper,"setField",(owner,property,newValue,fieldSymbol)=>{const fields=getAnyValue(owner,fieldSymbol)||{};fields[property]=newValue;setAnyValue(owner,fieldSymbol,fields)});function Lazy(creator){const symbol=Symbol("lazy");return PropertyWrapper({getter:(target,property)=>{const stored=PropertyWrapper.getField(target,property,symbol);if(stored)return stored.value;const value=creator(target,property);PropertyWrapper.setField(target,property,{value},symbol);return value},setter:()=>{},fieldSymbol:symbol})}var JSON_SERIALIZED=Symbol("JSON_SERIALIZED");var AFTER_SERIALIZED=Symbol("AFTER_SERIALIZED");var SerializeSettings=class{constructor(){this.settingsByName={};this.settingsBySerializedName={};this.ignoredProperties=[];this.defaultIgnored=false}add(prop){this.settingsByName[prop.propName]=prop;this.settingsBySerializedName[prop.serializedName]=prop}isPropertyIgnored(propName){if(this.defaultIgnored&&!this.settingsByName[propName]){return true}return this.ignoredProperties.indexOf(propName)!==-1}};var SerializedPropertySetting=class{constructor(target,propName,options){this.target=target;this.propName=propName;this.options=options;this.isArray=Reflect.getDesignType(target,propName)===Array;this.serializedName=options.name||asString(propName);this.class=options.class;this.fromJSON=this.createBuilder();this.toJSON=options.toJSON||(value=>serializeTo(value))}createBuilder(){if(this.options.fromJSON){return this.options.fromJSON}else if(this.class&&this.class instanceof Function){const clazz=this.class;return data=>{const transformer=jsonTransformers.get(clazz);return transformer?transformer.fromJson(data):deserialize(data,clazz)}}else{return data=>getValueByReflectType(this.target,this.propName,data)}}};function setDefaultIgnored(clazz,defaultIgnored){updateSerializeSettings(clazz,settings=>{settings.defaultIgnored=defaultIgnored})}function registerSerializedProperty(target,propName,options){const clazz=target.constructor;updateSerializeSettings(clazz,settings=>{settings.add(new SerializedPropertySetting(target,propName,options))})}function updateSerializeSettings(clazz,update){let settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){settings=new SerializeSettings}update(settings);Reflect.defineMetadata(JSON_SERIALIZED,settings,clazz)}var SerializedClass=Serialized();function Serialized(options){options=options||{};return(target,propName)=>registerSerializedProperty(target,asString(propName),options)}function SerializedName(serializedName){return(target,propName)=>registerSerializedProperty(target,asString(propName),{name:serializedName})}var IgnoreSerialization=(target,propName)=>updateSerializeSettings(target.constructor,settings=>settings.ignoredProperties.push(propName));function serialize(value){if(typeof value==="object")return JSON.stringify(serializeToData(value));return JSON.stringify(value)}function serializeTo(value){if(value===void 0)throw new Error("attempt to serialize undefined value");if(value===null)return null;const transformer=jsonTransformers.get(value.constructor);return transformer?transformer.toJson(value):serializeToData(value)}function serializeToData(object){var _a;if(object instanceof Array){return object.map(it=>serializeToData(it))}if(isDictionary(object)){const result={};Object.entries(object).forEach(it=>{const[prop,value]=it;result[prop]=serializeTo(value)});return result}const clazz=object.constructor;const reflectEnabled=(_a=getClassDefinition2(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){return object}const jsonMappingObject={};Object.entries(object).forEach(entry=>{const propName=entry[0];if(settings.isPropertyIgnored(propName))return;let value=entry[1];if(value===void 0||value instanceof Function||typeof value==="symbol")return;const propSetting=settings.settingsByName[propName];const serializedName=(propSetting==null?void 0:propSetting.serializedName)||propName;if(propSetting){if(propSetting.isArray){value=value.map(it=>propSetting.toJSON(it))}else{value=propSetting.toJSON(value)}}jsonMappingObject[serializedName]=value});return jsonMappingObject}function deserialize(json,constructorOrTarget){var _a;if(typeof json==="string"){json=JSON.parse(json)}if(constructorOrTarget===null)return json;if(constructorOrTarget===void 0)return json;try{const data=json;const clazz=constructorOrTarget instanceof Function?constructorOrTarget:constructorOrTarget.constructor;const reflectEnabled=(_a=getClassDefinition2(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const transformer=jsonTransformers.get(clazz);if(transformer)return transformer.fromJson(data);const target=constructorOrTarget instanceof Function?createNewInstance(constructorOrTarget):constructorOrTarget;deserializeFrom(data,target);if(reflectEnabled){const validateResult=validateInstance(target,clazz.name);if(!validateResult.success){throw new Error(`JSON deserialize validate failed: ${getErrorTraceMessages(validateResult)} `)}}return target}catch(e){console.error("failed to deserialize");console.dir(e);throw e}}function deserializeArray(json,clazz){const data=typeof json==="string"?JSON.parse(json):json;if(!(data instanceof Array)){return[]}return data.map(item=>deserialize(item,clazz))}function deserializeFrom(data,target){const clazz=target.constructor;const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){Object.assign(target,data);return}Object.keys(data).forEach(serializedName=>{const propDef=settings.settingsBySerializedName[serializedName];const jsonValue=data[serializedName];if(propDef===void 0){if(!settings.defaultIgnored){setAnyValue(target,serializedName,jsonValue)}return}const propName=propDef.propName;if(settings.isPropertyIgnored(propName)){return}let value;if(jsonValue instanceof Array){value=jsonValue.map(it=>propDef.fromJSON(it))}else{value=propDef.fromJSON(jsonValue)}setAnyValue(target,propName,value)});callDecoratedMethod(target,AFTER_SERIALIZED)}function getSerializeSettings(clazz){return Reflect.getMetadata(JSON_SERIALIZED,clazz)}function getValueByReflectType(target,propName,value){const reflectType=Reflect.getDesignType(target,propName);if(reflectType===void 0)return value;if(reflectType===Array)return deserializeArray(value);const transformer=jsonTransformers.get(reflectType);return transformer?transformer.fromJson(value):deserialize(value,reflectType)}var jsonTransformers=new Map;function registerTransform(clazz,transform){jsonTransformers.set(clazz,transform)}var itSelf=some=>some;var done=()=>void 0;registerTransform(String,{fromJson:asString,toJson:itSelf});registerTransform(Number,{fromJson:asNumber,toJson:itSelf});registerTransform(Boolean,{fromJson:asBoolean,toJson:itSelf});registerTransform(Date,{fromJson:anyValue=>new Date(asNumber(anyValue)),toJson:date=>date.getTime()});var AfterSerialized=defineDecoratedProperty(AFTER_SERIALIZED);var mapStatus=new Map;function registerMappable(mappableClass){if(mapStatus.get(mappableClass))return;const classDef=getClassDefinition2(mappableClass);const mapping=new Proxy({},{get(target,p){return doMap(p)},set(target,p,newValue){doMap(p)(newValue);return true}});function doMap(propName){return(fieldName,transform)=>{var _a,_b,_c;const propType=(_b=(_a=Object.values((classDef==null?void 0:classDef.allProperties)||{}))==null?void 0:_a.find(it=>it.name===propName))==null?void 0:_b.type;let propClass=(propType==null?void 0:propType.name)!==void 0?getClassByName(propType.name):void 0;if(propType&&isArrayType(propType)){propClass=((_c=propType.arrayElementType)==null?void 0:_c.name)!==void 0?getClassByName(propType.arrayElementType.name):void 0}if(typeof propName!=="string")return;registerSerializedProperty(mappableClass.prototype,propName,{name:fieldName,class:propClass,fromJSON:transform==null?void 0:transform.fromJSON,toJSON:transform==null?void 0:transform.toJSON});setDefaultIgnored(mappableClass,true)}}mappableClass.prototype.mapping(mapping);mapStatus.set(mappableClass,true)}function mapAllProperties(target,map){const classDef=getClassDefinition2(target);if(!classDef)return;classDef.properties.forEach(prop=>map[prop.name]())}import"reflect-metadata";var DESIGN_TYPE="design:type";var DESIGN_RETURNTYPE="design:returntype";var DESIGN_PARAMTYPES="design:paramtypes";function getDesignType(target,property){return Reflect.getMetadata(DESIGN_TYPE,target,property)}function getReturnType(target,property){return Reflect.getMetadata(DESIGN_RETURNTYPE,target,property)}function getParamTypes(target,property){return Reflect.getMetadata(DESIGN_PARAMTYPES,target,property)}function addMetadataList(key,value,target,propertyKey){const list=(propertyKey===void 0?Reflect.getMetadata(key,target):Reflect.getMetadata(key,target,propertyKey))||[];if(!list.includes(value))list.push(value);propertyKey===void 0?Reflect.defineMetadata(key,list,target):Reflect.defineMetadata(key,list,target,propertyKey)}Object.assign(Reflect,{getDesignType,getReturnType,getParamTypes,addMetadataList});export{AfterSerialized,ClassDefinition,EnumDefinition,IgnoreSerialization,InterfaceDefinition,Lazy,MethodDefinition3 as MethodDefinition,PropertyDefinition3 as PropertyDefinition,PropertyWrapper,ReflectClass,ReflectContext,ReflectValidate,Serialized,SerializedClass,SerializedName,anyType,asBoolean,asNumber,asString,assertType,callDecoratedMethod,createNewInstance,defineDecoratedProperty,deserialize,deserializeArray,deserializeFrom,done,fillMethod,fillProperty,fillType,getAnyValue,getClassByName,getClassDefinition2 as getClassDefinition,getDecoratedProperty,getDecoratedPropertyValue,getEnumDefinition2 as getEnumDefinition,getEnumNames,getEnumValues,getErrorTraceMessages,getInterfaceDefinition2 as getInterfaceDefinition,getOrSetValue,getSerializeSettings,getTypeAliasDefinition2 as getTypeAliasDefinition,getTypeDef,getTypeDefinition,hasDecoratedMethod,hasGenerics,isArrayType,isClassDefinition,isDictionary,isIgnoredType,isIntersectionType,isLiteralType,isNullable,isPrimitiveType,isTupleType,isType,isTypeLiteralType,isUnionType,itSelf,mapAllProperties,nullType,registerMappable,registerSerializedProperty,registerTransform,safeCall,safeSetValue,serialize,serializeTo,serializeToData,setAnyValue,setDefaultIgnored,validateArray,validateDictionary,validateFunctionArgument,validateInstance,validateValue};
|
|
1
|
+
var __defProp=Object.defineProperty;var __getOwnPropSymbols=Object.getOwnPropertySymbols;var __hasOwnProp=Object.prototype.hasOwnProperty;var __propIsEnum=Object.prototype.propertyIsEnumerable;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __spreadValues=(a,b)=>{for(var prop in b||(b={}))if(__hasOwnProp.call(b,prop))__defNormalProp(a,prop,b[prop]);if(__getOwnPropSymbols)for(var prop of __getOwnPropSymbols(b)){if(__propIsEnum.call(b,prop))__defNormalProp(a,prop,b[prop])}return a};var GenericProperty=class _GenericProperty extends PropertyDefinition{static create(proto,genericContext){const instance=createInstance(_GenericProperty,proto);instance.genericContext=genericContext;return instance}get type(){return fillType(this.rawDef.type,this.genericContext)}};var GenericMethod=class _GenericMethod extends MethodDefinition{static create(proto,genericContext){const instance=createInstance(_GenericMethod,proto);instance.genericContext=genericContext;return instance}get args(){var _a;return((_a=this.rawDef.args)==null?void 0:_a.map(arg=>({name:arg.name,type:fillType(arg.type,this.genericContext),isOptional:arg.isOptional})))||[]}get returnType(){return fillType(this.rawDef.returnType,this.genericContext)}};function createInstance(constructor,proto){const result=Object.create(constructor.prototype);Object.assign(result,proto);return result}function buildPropertiesAndMethods(ret,proto){ret.properties=proto.properties.map(p=>GenericProperty.create(p,ret.genericContext));ret.methods=proto.methods.map(m=>GenericMethod.create(m,ret.genericContext))}var GenericClass=class _GenericClass extends ClassDefinition{static create(proto,genericArgs){const instance=createInstance(_GenericClass,proto);instance.genericArgs=genericArgs;const ret=instance;ret.buildGenericContext();buildPropertiesAndMethods(ret,proto);return ret}buildGenericContext(){var _a;this.genericContext={};(_a=this.generics)==null?void 0:_a.forEach((genericName,index)=>this.genericContext[genericName]=this.genericArgs[index])}};var GenericInterface=class _GenericInterface extends InterfaceDefinition{static create(proto,genericArgs){const instance=createInstance(_GenericInterface,proto);instance.genericArgs=genericArgs;const ret=instance;ret.buildGenericContext();buildPropertiesAndMethods(ret,proto);return ret}buildGenericContext(){var _a;this.genericContext={};(_a=this.generics)==null?void 0:_a.forEach((genericName,index)=>this.genericContext[genericName]=this.genericArgs[index])}};var anyType={name:"any"};var nullType={name:"null"};var primitiveTypes=["string","number","boolean","bigint","symbol"];function isIgnoredType(type){return!!(type.name&&["any","void","unknown"].includes(type.name))}function isPrimitiveType(type){return!!(type.name&&primitiveTypes.includes(type.name))}function isArrayType(type){return!!type.arrayElementType}function isLiteralType(type){return!!type.literalValue}function isTypeLiteralType(type){return!!type.typeLiteralMembers}function isUnionType(type){return!!type.unionMembers}function isIntersectionType(type){return!!type.intersectionMembers}function isTupleType(type){return!!type.tupleMembers}function isClassDefinition(type){return!!type.classDefinition}function hasGenerics(type){return!!type.generics}function getTypeDefinition(typeName,genericArgs){if(typeName==="any"||typeName==="Any"||typeName==="unknown"||typeName==="")return anyType;if(typeName==="null")return nullType;const classDef=getClassDefinition(typeName);if(classDef){if(genericArgs)return GenericClass.create(classDef,genericArgs).type;else return classDef.type}if(primitiveTypes.includes(typeName)){return{name:typeName}}const interfaceDef=getInterfaceDefinition(typeName);if(interfaceDef){if(genericArgs)return GenericInterface.create(interfaceDef,genericArgs).type;return interfaceDef.type}const enumDef=getEnumDefinition(typeName);if(enumDef)return enumDef.type;const typeDef=getTypeAliasDefinition(typeName);if(typeDef)return typeDef;return anyType}var typeMap=new Map;function fillType(rawType,genericContext,genericArgs){const typeKey=stableStringify(rawType);if(rawType===void 0)return anyType;const typeDef=typeMap.get(typeKey);if(typeDef)return typeDef;const result={};typeMap.set(typeKey,result);if(typeof rawType==="string"){return(genericContext==null?void 0:genericContext[rawType])||getTypeDefinition(rawType,genericArgs)||anyType}if(rawType.arrayElementType){Object.assign(result,{arrayElementType:fillType(rawType.arrayElementType,genericContext)})}else if(rawType.unionMembers){Object.assign(result,{unionMembers:rawType.unionMembers.map(it=>fillType(it,genericContext))})}else if(rawType.intersectionMembers){Object.assign(result,{intersectionMembers:rawType.intersectionMembers.map(it=>fillType(it,genericContext))})}else if(rawType.tupleMembers){Object.assign(result,{tupleMembers:rawType.tupleMembers.map(it=>fillType(it,genericContext))})}else if(rawType.generics){const typeName=rawType.generics[0];const typeArgs=rawType.generics.slice(1).map(it=>fillType(it,genericContext));Object.assign(result,fillType(typeName,genericContext,typeArgs))}if(Object.keys(result).length===0)return anyType;return result}function stableStringify(obj){if(obj===null)return"null";if(obj===void 0)return"undefined";if(typeof obj!=="object")return JSON.stringify(obj);if(Array.isArray(obj)){return"["+obj.map(stableStringify).join(",")+"]"}const keys=Object.keys(obj).sort();return"{"+keys.map(k=>JSON.stringify(k)+":"+stableStringify(obj[k])).join(",")+"}"}var classMap=new Map;var interfaceMap=new Map;var enumMap=new Map;var typeAliasMap=new Map;var classPool=new Map;var ReflectClass=(jsClass=>{classPool.set(jsClass.name,jsClass)});var primitiveMap={string:String,number:Number,boolean:Boolean,object:Object};var reflect=Reflect;function getClassByName(className){var _a;return((_a=getClassDefinition(className))==null?void 0:_a.jsClass)||primitiveMap[className]}function getClassDefinition(arg){var _a,_b,_c;switch(typeof arg){case"object":return getClassDefinition(arg.constructor);case"function":const classDefByName=getClassDefinition(arg.name);if(classDefByName){return classDefByName}const classDefInStore=Array.from(classMap.values()).find((classDef=>classDef.jsClass===arg));if(classDefInStore){return classDefInStore}const classNameByRawDef=(_a=Object.entries(reflect.__classDef||{}).find(([_name,jsClass])=>jsClass===arg))==null?void 0:_a[0];if(classNameByRawDef){return getClassDefinition(classNameByRawDef)}else{return void 0}case"string":const className=arg;if(!classMap.has(className)){const rawClassDef=(_b=reflect.__classes)==null?void 0:_b[className];if(!rawClassDef){return void 0}const jsClass=(_c=reflect.__classDef)==null?void 0:_c[className];classMap.set(className,new ClassDefinition(__spreadValues(__spreadValues({},rawClassDef),{jsClass})))}return classMap.get(className)}}function getInterfaceDefinition(name){var _a;if(!interfaceMap.has(name)){const interfaceMeta=(_a=reflect.__interfaces)==null?void 0:_a[name];if(!interfaceMeta)return void 0;interfaceMap.set(name,new InterfaceDefinition(interfaceMeta))}return interfaceMap.get(name)}function getEnumDefinition(name){var _a;if(!enumMap.has(name)){const enumMeta=(_a=reflect.__enums)==null?void 0:_a[name];if(!enumMeta)return void 0;enumMap.set(name,new EnumDefinition(enumMeta))}return enumMap.get(name)}function getEnumNames(enumName){var _a;return((_a=getEnumDefinition(enumName))==null?void 0:_a.names)||[]}function getEnumValues(args){const enumArg=Object.entries(args)[0];if(!enumArg)return[];const[enumName,obj]=enumArg;const enumDef=getEnumDefinition(enumName);if(!enumDef)return Array.from(Object.keys(obj));return enumDef.names.map(name=>obj[name])}function getTypeAliasDefinition(name){var _a;if(!typeAliasMap.has(name)){const typeAliasMeta=fillType((_a=reflect.__typeAliases)==null?void 0:_a[name]);if(!typeAliasMeta)return void 0;typeAliasMap.set(name,typeAliasMeta)}return typeAliasMap.get(name)}function initReflectContext(){reflect.__classes&&Object.entries(reflect.__classes).map(([className,rawClassDef])=>{var _a;const jsClass=(_a=reflect.__classDef)==null?void 0:_a[className];if(!jsClass)return void 0;classMap.set(className,new ClassDefinition(__spreadValues(__spreadValues({},rawClassDef),{jsClass})))});reflect.__interfaces&&Object.entries(reflect.__interfaces).map(([name,interfaceMeta])=>interfaceMap.set(name,new InterfaceDefinition(interfaceMeta)));reflect.__enums&&Object.entries(reflect.__enums).map(([name,enumMeta])=>enumMap.set(name,new EnumDefinition(enumMeta)));reflect.__typeAliases&&Object.entries(reflect.__typeAliases).map(([name,def])=>{typeAliasMap.set(name,fillType(def))});["__classDef","__classes","__interfaces","__enums","__typeAliases","initReflectContext"].forEach(it=>delete reflect[it])}var ClassDefinition=class{constructor(def){var _a,_b;this.name=def.name;this.superClassName=def.superClassName||"Object";this.superClass=getClassDefinition(this.superClassName);this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[];this.jsClass=def.jsClass;this.generics=def.generics}get allMethods(){const results={};if(this.superClassName!=="Object"){const superClassDef=getClassDefinition(this.superClassName);if(superClassDef){Object.assign(results,__spreadValues({},superClassDef.allMethods))}}Object.assign(results,__spreadValues({},toDictionary(this.methods,it=>[it.name,it])));return results}get allProperties(){var _a;return Object.assign(((_a=this.superClass)==null?void 0:_a.allProperties)||{},toDictionary(this.properties,it=>[it.name,it]))}get implementations(){if(!this._implementations){return mapNotNull(this._implementationNames,name=>getInterfaceDefinition(name)||getTypeDefinition(name))}return this._implementations}get allImplementations(){var _a,_b;if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});(_b=(_a=this.superClass)==null?void 0:_a.allImplementations)==null?void 0:_b.forEach(it=>result.add(it));this._allImplementations=Array.from(result)}return this._allImplementations}getProperty(propName){return this.properties.find(it=>it.name===propName)}get type(){var _a,_b;const props={};(_b=(_a=this.superClass)==null?void 0:_a.type.typeLiteralMembers)==null?void 0:_b.forEach(prop=>props[prop.name]=prop);this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,classDefinition:this,typeLiteralMembers:Object.values(props)}}isSubClassOf(typeName){var _a;if(this.name===typeName)return true;if((_a=this.superClass)==null?void 0:_a.isSubClassOf(typeName))return true;return this.implementations.map(it=>it.name).includes(typeName)}isSuperClassOf(typeName){if(this.name===typeName)return true;const classDef=getClassDefinition(typeName);if(!classDef)return false;return classDef.isSubClassOf(this.name)}toString(){return`class ${this.name}`}};function toDictionary(arr,handler){const dict={};arr.forEach(item=>{const[key,value]=handler(item);dict[key]=value});return dict}function mapNotNull(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}function setValue(target,field,value){if(target===void 0)return;target[field]=value}function getValue(target,field){if(target===void 0)return void 0;return target[field]}function mapNotNull2(arr,mapper){return(arr==null?void 0:arr.map(mapper).filter(it=>it!==void 0))||[]}var InterfaceDefinition=class _InterfaceDefinition{constructor(def){var _a,_b;this.name=def.name;this._implementationNames=def.implementations||[];this.methods=((_a=def.methods)==null?void 0:_a.map(fillMethod))||[];this.properties=((_b=def.properties)==null?void 0:_b.map(fillProperty))||[];this.generics=def.generics}get implementations(){if(!this._implementations){this._implementations=mapNotNull2(this._implementationNames,name=>getInterfaceDefinition(name)||getClassDefinition(name).type||getTypeDefinition(name))}return this._implementations}get allImplementations(){if(this._allImplementations===void 0){const result=new Set(this.implementations);this.implementations.forEach(implDef=>{if(implDef instanceof _InterfaceDefinition)implDef.allImplementations.forEach(it=>result.add(it));else result.add(implDef)});this._allImplementations=Array.from(result)}return this._allImplementations}get type(){const props={};this.allImplementations.forEach(implDef=>{const type="type"in implDef?implDef.type:implDef;const interfaceProps=type.typeLiteralMembers;interfaceProps==null?void 0:interfaceProps.forEach(prop=>props[prop.name]=prop)});this.properties.forEach(prop=>props[prop.name]=prop);return{name:this.name,typeLiteralMembers:Object.values(props)}}toString(){return`interface ${this.name}`}buildBaseObject(){const result={};this.properties.forEach(it=>setValue(result,it.name,void 0));this.methods.forEach(it=>setValue(result,it.name,()=>void 0));return result}};var EnumDefinition=class{constructor(def){this.name=def.name;this.members=new Map;def.members.forEach(member=>{const value=member.initializer===void 0?{name:"number"}:{literalValue:member.initializer};this.members.set(member.name,value)})}get type(){return{name:this.name,unionMembers:Array.from(this.members.values())}}get names(){return Array.from(this.members.keys())}};var MethodDefinition=class{constructor(def){this.rawDef=def}get name(){return this.rawDef.name}get returnType(){return fillType(this.rawDef.returnType)}get args(){var _a;return((_a=this.rawDef.args)==null?void 0:_a.map(arg=>({name:arg.name,type:fillType(arg.type),isOptional:arg.isOptional})))||[]}get isPrivate(){return this.rawDef.isPrivate}get isStatic(){return this.rawDef.isStatic}get isAsync(){return this.rawDef.isAsync}};function fillMethod(rawMethod){return new MethodDefinition(rawMethod)}var PropertyDefinition=class{constructor(def){this.rawDef=def}get name(){return this.rawDef.name}get isOptional(){return this.rawDef.isOptional}get isPrivate(){return this.rawDef.isPrivate}get isStatic(){return this.rawDef.isStatic}get accessor(){return this.rawDef.accessor}get type(){return fillType(this.rawDef.type)}};function fillProperty(rawProperty){return new PropertyDefinition(rawProperty)}var _ValidateResult=class _ValidateResult{constructor(success,errorMessage,cause){this.success=success;this.errorMessage=errorMessage;this.cause=cause}static failure(errorMessage,cause){return new _ValidateResult(false,errorMessage,cause)}get errorStackFlow(){if(!this.cause)return this.errorMessage;return[this.errorMessage,this.cause.errorStackFlow].join("\ncaused by: ")}};_ValidateResult.success=new _ValidateResult(true);var ValidateResult=_ValidateResult;var successResult=ValidateResult.success;var failedResult=ValidateResult.failure;function getErrorTraceMessages(failureResult){const getAllTraceMessages=failureResult2=>failureResult2.errorMessage?[failureResult2.errorMessage,...failureResult2.cause?getAllTraceMessages(failureResult2.cause):[]]:[];return getAllTraceMessages(failureResult).join("\n-> ")}var preservedTypes=[Promise,Date,Map,Set,Error,Function];function validateValue(value,type,depth=1){switch(true){case type.name==="undefined":return value===void 0?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isIgnoredType(type):return successResult;case isClassDefinition(type):return value instanceof Object?validateClassInstance(value,type.classDefinition.name,depth):failedResult(`declared as ${getTypeDisplayName(type)} but actually not an object`);case isArrayType(type):return validateArrayValue(value,type,depth);case isTupleType(type):return validateTupleValue(value,type,depth);case isUnionType(type):for(const unionMember of type.unionMembers||[]){const validateResult=validateValue(value,unionMember,depth);if(validateResult.success)return successResult}return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`);case isIntersectionType(type):for(const intersectionMember of type.intersectionMembers||[]){const validateResult=validateValue(value,intersectionMember,depth);if(!validateResult.success)return failedResult(`declared as ${getTypeDisplayName(type)} but all value not match`,validateResult)}return successResult;case isLiteralType(type):switch(typeof value){case"string":return value===trimQuotes(type.literalValue)?successResult:failedResult(`declared as string ${getTypeDisplayName(type)} but value not match`);case"number":return value===Number(type.literalValue)?successResult:failedResult(`declared as number ${getTypeDisplayName(type)} but value not match`);case"bigint":return value===BigInt(type.literalValue)?successResult:failedResult(`declared as bigint ${getTypeDisplayName(type)} but value not match`);case"boolean":return value===Boolean(type.literalValue)?successResult:failedResult(`declared as boolean ${getTypeDisplayName(type)} but value not match`);default:if(type.literalValue==="null"&&value===null)return successResult;return value===type.literalValue?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but value not match`)}case isTypeLiteralType(type):return validateProperties(value,type,depth);case type.isFunction:case type.isConstructor:return typeof value==="function"?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not`);case isPrimitiveType(type):return typeof value===type.name?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${typeof value}`);default:return validateSimpleValue(value,type,depth)}}function validateArrayValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not`)}if(depth===0)return successResult;for(const arrayItem of value){const validateResult=validateValue(arrayItem,type.arrayElementType||anyType,depth-1);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in array match`,validateResult)}}return successResult}function validateTupleValue(value,type,depth=1){if(!Array.isArray(value)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not a tuple`)}if(depth===0)return successResult;let index=0;for(const tupleItem of type.tupleMembers){const tupleValue=value[index++];if(tupleItem.isOptionalInTuple&&tupleValue===void 0)continue;const validateResult=validateValue(value[index],tupleItem,depth);if(!validateResult.success){return failedResult(`declared as ${getTypeDisplayName(type)} but not all values in tuple match`,validateResult)}}return successResult}function validateProperties(value,type,depth=1){if(!(value instanceof Object)){return failedResult(`declared as ${getTypeDisplayName(type)} but not an object`)}else{for(const prop of type.typeLiteralMembers||[]){if(prop.isStatic)return successResult;if(prop.name.startsWith("[")&&prop.name.endsWith("]"))return successResult;if(depth===0)return successResult;let propType=prop.type||anyType;if(prop.isOptional)propType={unionMembers:[propType,{name:"undefined"}]};const propValue=getValue(value,prop.name);const validateResult=validateValue(propValue,propType,depth-1);if(!validateResult.success){return failedResult(`declared ${prop.name} as ${getTypeDisplayName(propType)}, but not match`,validateResult)}}return successResult}}function validateSimpleValue(value,type,depth=1){const typeName=typeof type==="string"?type:type.name;if(!typeName)return successResult;if(value===void 0){return failedResult(`declared as ${getTypeDisplayName(type)} but actually undefined`)}if(value===null){if(typeName==="null")return successResult;else return failedResult(`declared as ${getTypeDisplayName(type)} but actually null`)}for(const preservedType of preservedTypes){if(typeName===preservedType.name){return value instanceof preservedType?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually ${value.constructor.name}`)}}if(value instanceof Object&&!valueInstanceOf(value,typeName)){return failedResult(`declared as ${getTypeDisplayName(type)} but actually not instance of it`)}if(depth==0)return successResult;const result=validateValue(value,getTypeDefinition(typeName),depth);return result.success?successResult:failedResult(`declared as ${getTypeDisplayName(type)} but actually not match`,result)}function validateClassInstance(instance,typeName,depth=3){if(typeName!=="object"&&!valueInstanceOf(instance,typeName)){return failedResult(`declared as instance of ${typeName} but actually not`)}const typeDef=getTypeDefinition(typeName);if(typeName!=="any"&&typeDef===anyType){return failedResult(`${typeName} not defined`)}delete typeDef.classDefinition;return validateValue(instance,typeDef,depth)}function valueInstanceOf(value,className){if(value===void 0)return true;if(value.constructor.name===className)return true;const classDef=getClassDefinition(className);if(!classDef)return true;if(classDef.jsClass)return value instanceof classDef.jsClass;const instanceClassDef=getClassDefinition(value);if(!instanceClassDef)return false;return instanceClassDef.isSubClassOf(classDef.name)}function trimQuotes(text){if(text.length>=2&&(text[0]==='"'&&text[text.length-1]==='"'||text[0]==="'"&&text[text.length-1]==="'")){return text.substring(1,text.length-1)}return text}function getTypeDisplayName(type){var _a,_b,_c;if(typeof type==="string"){return type}if(isClassDefinition(type)){return type.classDefinition.name}if(isArrayType(type)){return(((_a=type.arrayElementType)==null?void 0:_a.name)||"unknown")+"[]"}if(type.isConstructor){return"Class"}if(type.isFunction){return"Function"}if(isTypeLiteralType(type)){return"Object"}if(isTupleType(type)){return`(${type.tupleMembers.map(getTypeDisplayName).join(",")})`}if(isUnionType(type)){return((_b=type.unionMembers)==null?void 0:_b.map(getTypeDisplayName).join(" | "))||"unknown"}if(isIntersectionType(type)){return((_c=type.intersectionMembers)==null?void 0:_c.map(getTypeDisplayName).join(" & "))||"unknown"}if(isLiteralType(type)){return type.literalValue}return type.name||"unknown"}function validateInstance(instance,typeName,depth=3){typeName=typeName||instance.constructor.name;return validateClassInstance(instance,typeName,depth)}function validateArray(array,typeName,depth=1){for(let i=0;i<array.length;i++){const result=validateInstance(array[i],typeName,depth);if(!result.success){return failedResult(`declared as instance of ${typeName}[] but [${i}] actually not`,result)}}return successResult}function validateDictionary(dict,typeName,depth=1){const entries=Object.entries(dict);for(let i=0;i<entries.length;i++){const[key,value]=entries[i];const result=validateInstance(value,typeName,depth);if(!result.success){return failedResult(`declared as instance of Dictionary<${typeName}> but [${key}] actually not`,result)}}return successResult}function getTypeDef(type){if(typeof type==="string")return getTypeDefinition(type);if("array"in type)return{arrayElementType:getTypeDef(type.array)};if("union"in type)return{unionMembers:type.union.map(getTypeDef)};if("intersection"in type)return{intersectionMembers:type.intersection.map(getTypeDef)};if("tuple"in type)return{tupleMembers:type.tuple.map(getTypeDef)};else return type}function assertType(data,type,depth=5){const validateResult=validateValue(data,getTypeDef(type),depth);if(!validateResult.success){console.error(`assert failed with type: ${type}
|
|
2
|
+
${validateResult.errorStackFlow}`);debugger;throw new Error(`assert failed with type: ${type}, ${validateResult.errorStackFlow}`)}return data}function isNullable(type){return isType(null,type)}function isType(value,type){return validateValue(value,getTypeDef(type),3).success}var VALIDATE_WRAPPER=Symbol("VALIDATE_WRAPPER");var ReflectValidate=(target,propertyKey,descriptor)=>wrapValidateMethod(target,propertyKey,descriptor);function wrapValidateMethod(target,methodName,descriptor){const func=descriptor.value;if(typeof func!=="function")return;if(getValue(func,VALIDATE_WRAPPER))return;const getMethodDef=()=>{var _a,_b;return(_b=(_a=getClassDefinition(target))==null?void 0:_a.methods)==null?void 0:_b.find(it=>it.name===methodName)};const validateArgs=args=>validateMethodParams(target,getMethodDef(),args);const validateReturn=result=>validateMethodReturnValue(target,getMethodDef(),result);const newFunc=function(...args){validateArgs(args);const result=func.call(this,...args);return validateReturn(result)};newFunc[VALIDATE_WRAPPER]=func;descriptor.value=newFunc}function validateMethodParams(target,methodDef,args){var _a;(_a=methodDef==null?void 0:methodDef.args)==null?void 0:_a.forEach((argDef,index)=>{const arg=args==null?void 0:args[index];if(arg===void 0){if(!argDef.isOptional)throw new Error(`Illegal arguments for ${getMethodDescription(target.constructor.name,methodDef)}: ${argDef.name} is not optional`);else return}const validResult=validateValue(arg,argDef.type||anyType,1);if(!validResult.success){console.error("validateResult",validResult);throw new Error(`Illegal arguments for ${getMethodDescription(target.constructor.name,methodDef)}: ${argDef.name}: ${argDef.name} ${validResult.errorMessage}`)}})}function validateMethodReturnValue(target,methodDef,result){var _a;if(!methodDef)return result;const checkValue=(value,type)=>{const validateResult=validateValue(value,type,5);if(!validateResult.success){console.error(validateResult.errorStackFlow);throw new Error(`result for ${getMethodDescription(target.constructor.name,methodDef)} doesn't match type ${type.name}:
|
|
3
|
+
${validateResult.errorStackFlow}`)}return value};let returnType=methodDef.returnType;if(returnType.name==="Promise"){returnType=((_a=returnType.generics)==null?void 0:_a[0])||anyType}if(result instanceof Promise){return result.then(res=>checkValue(res,returnType||anyType))}else{return checkValue(result,returnType||anyType)}}function getMethodDescription(className,methodDef){var _a;return`${className}.${methodDef.name}(${(_a=methodDef.args)==null?void 0:_a.map(it=>it.name).join(", ")})`}function safeCall(target,methodName,...args){const classDef=getClassDefinition(target);if(!classDef)return;const methodDef=classDef.allMethods[methodName];if(!methodDef)return;validateMethodParams(target,methodDef,args);return getValue(target,methodName).apply(target,args)}function validateFunctionArgument(args){const{funcName,optionsObj,value,argName,type,optional}=args;const v=value||optionsObj&&getValue(optionsObj,argName);if(v===void 0){if(!optional)throw Error(`Illegal arguments for ${funcName}: ${argName} is undefined`);else return}if(["string","number","boolean","bigint"].includes(type)){if(typeof v!==type)throw Error(`Illegal arguments for ${funcName}: ${argName} is not a ${type}`);return}if(typeof v!=="object")throw Error(`Illegal arguments for ${funcName}: ${argName} is not an object`);if(v===null)throw Error(`Illegal arguments for ${funcName}: ${argName} is null`);const result=validateClassInstance(v,type);if(!result.success)throw Error(`Illegal arguments for ${funcName}: ${result.errorMessage}`)}import"reflect-metadata";function asBoolean(value){if(String(value).toLocaleLowerCase()==="false")return false;return!!value}function asString(v){if(v===null||v===void 0||Number.isNaN(v)){return""}if(v instanceof Date&&String(v)==="Invalid Date"){return""}if(typeof v==="symbol"){return v.description||""}return String(v)}function asNumber(v){if(!v)return 0;if(v instanceof Date)return v.getDate();return Number(v)}function setAnyValue(target,field,value){;target[field]=value}function getAnyValue(target,field){return target[field]}function getOrSetValue(target,field,defaultWith){const value=target[field];if(value!==void 0)return value;const defaultValue=defaultWith();setAnyValue(target,field,defaultValue);return defaultValue}function isDictionary(value){return typeof value==="object"&&value!==null&&value.constructor===Object}function createNewInstance(clazz){const result=Object.create(clazz.prototype);result.constructor=this;return result}function defineDecoratedProperty(metaKey){return((self,propertyKey)=>Reflect.defineMetadata(metaKey,propertyKey,self.constructor))}function callDecoratedMethod(self,metaKey,...args){const method=getDecoratedPropertyValue(self,metaKey);if(method!==void 0&&method instanceof Function){return method.apply(self,args)}return void 0}function hasDecoratedMethod(self,metaKey){const method=getDecoratedPropertyValue(self,metaKey);return method!==void 0&&method instanceof Function}function getDecoratedProperty(target,metaKey){return Reflect.getMetadata(metaKey,target.constructor)}function getDecoratedPropertyValue(target,metaKey){const propName=getDecoratedProperty(target,metaKey);if(propName===void 0)return;return getAnyValue(target,propName)}var PropertyWrapper=function({getter,setter,fieldSymbol}){return(target,propertyKey)=>{Object.defineProperty(target,propertyKey,{get:function(){return getter?getter(this,propertyKey):PropertyWrapper.getField(target,propertyKey,fieldSymbol)},set:function(newValue){setter?setter(this,newValue,propertyKey):PropertyWrapper.setField(target,propertyKey,newValue,fieldSymbol)}})}};setAnyValue(PropertyWrapper,"getField",(owner,property,fieldSymbol)=>{var _a;return(_a=getAnyValue(owner,fieldSymbol))==null?void 0:_a[property]});setAnyValue(PropertyWrapper,"setField",(owner,property,newValue,fieldSymbol)=>{const fields=getAnyValue(owner,fieldSymbol)||{};fields[property]=newValue;setAnyValue(owner,fieldSymbol,fields)});function Lazy(creator){const symbol=Symbol("lazy");return PropertyWrapper({getter:(target,property)=>{const stored=PropertyWrapper.getField(target,property,symbol);if(stored)return stored.value;const value=creator(target,property);PropertyWrapper.setField(target,property,{value},symbol);return value},setter:()=>{},fieldSymbol:symbol})}var JSON_SERIALIZED=Symbol("JSON_SERIALIZED");var AFTER_SERIALIZED=Symbol("AFTER_SERIALIZED");var SerializeSettings=class{constructor(){this.settingsByName={};this.settingsBySerializedName={};this.ignoredProperties=[];this.defaultIgnored=false}add(prop){this.settingsByName[prop.propName]=prop;this.settingsBySerializedName[prop.serializedName]=prop}isPropertyIgnored(propName){if(this.defaultIgnored&&!this.settingsByName[propName]){return true}return this.ignoredProperties.indexOf(propName)!==-1}};var SerializedPropertySetting=class{constructor(target,propName,options){this.target=target;this.propName=propName;this.options=options;this.isArray=Reflect.getDesignType(target,propName)===Array;this.serializedName=options.name||asString(propName);this.class=options.class;this.fromJSON=this.createBuilder();this.toJSON=options.toJSON||(value=>serializeTo(value))}createBuilder(){if(this.options.fromJSON){return this.options.fromJSON}else if(this.class&&this.class instanceof Function){const clazz=this.class;return data=>{const transformer=jsonTransformers.get(clazz);return transformer?transformer.fromJson(data):deserialize(data,clazz)}}else{return data=>getValueByReflectType(this.target,this.propName,data)}}};function setDefaultIgnored(clazz,defaultIgnored){updateSerializeSettings(clazz,settings=>{settings.defaultIgnored=defaultIgnored})}function registerSerializedProperty(target,propName,options){const clazz=target.constructor;updateSerializeSettings(clazz,settings=>{settings.add(new SerializedPropertySetting(target,propName,options))})}function updateSerializeSettings(clazz,update){let settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){settings=new SerializeSettings}update(settings);Reflect.defineMetadata(JSON_SERIALIZED,settings,clazz)}var SerializedClass=Serialized();function Serialized(options){options=options||{};return(target,propName)=>registerSerializedProperty(target,asString(propName),options)}function SerializedName(serializedName){return(target,propName)=>registerSerializedProperty(target,asString(propName),{name:serializedName})}var IgnoreSerialization=(target,propName)=>updateSerializeSettings(target.constructor,settings=>settings.ignoredProperties.push(propName));function serialize(value){if(typeof value==="object")return JSON.stringify(serializeToData(value));return JSON.stringify(value)}function serializeTo(value){if(value===void 0)throw new Error("attempt to serialize undefined value");if(value===null)return null;const transformer=jsonTransformers.get(value.constructor);return transformer?transformer.toJson(value):serializeToData(value)}function serializeToData(object){var _a;if(object instanceof Array){return object.map(it=>serializeToData(it))}if(isDictionary(object)){const result={};Object.entries(object).forEach(it=>{const[prop,value]=it;result[prop]=serializeTo(value)});return result}const clazz=object.constructor;const reflectEnabled=(_a=getClassDefinition(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){return object}const jsonMappingObject={};Object.entries(object).forEach(entry=>{const propName=entry[0];if(settings.isPropertyIgnored(propName))return;let value=entry[1];if(value===void 0||value instanceof Function||typeof value==="symbol")return;const propSetting=settings.settingsByName[propName];const serializedName=(propSetting==null?void 0:propSetting.serializedName)||propName;if(propSetting){if(propSetting.isArray){value=value.map(it=>propSetting.toJSON(it))}else{value=propSetting.toJSON(value)}}jsonMappingObject[serializedName]=value});return jsonMappingObject}function deserialize(json,constructorOrTarget){var _a;if(typeof json==="string"){json=JSON.parse(json)}if(constructorOrTarget===null)return json;if(constructorOrTarget===void 0)return json;try{const data=json;const clazz=constructorOrTarget instanceof Function?constructorOrTarget:constructorOrTarget.constructor;const reflectEnabled=(_a=getClassDefinition(clazz))==null?void 0:_a.isSubClassOf("Mappable");if(reflectEnabled)registerMappable(clazz);const transformer=jsonTransformers.get(clazz);if(transformer)return transformer.fromJson(data);const target=constructorOrTarget instanceof Function?createNewInstance(constructorOrTarget):constructorOrTarget;deserializeFrom(data,target);if(reflectEnabled){const validateResult=validateInstance(target,clazz.name);if(!validateResult.success){throw new Error(`JSON deserialize validate failed: ${getErrorTraceMessages(validateResult)} `)}}return target}catch(e){console.error("failed to deserialize");console.dir(e);throw e}}function deserializeArray(json,clazz){const data=typeof json==="string"?JSON.parse(json):json;if(!(data instanceof Array)){return[]}return data.map(item=>deserialize(item,clazz))}function deserializeFrom(data,target){const clazz=target.constructor;const settings=Reflect.getMetadata(JSON_SERIALIZED,clazz);if(settings===void 0){Object.assign(target,data);return}Object.keys(data).forEach(serializedName=>{const propDef=settings.settingsBySerializedName[serializedName];const jsonValue=data[serializedName];if(propDef===void 0){if(!settings.defaultIgnored){setAnyValue(target,serializedName,jsonValue)}return}const propName=propDef.propName;if(settings.isPropertyIgnored(propName)){return}let value;if(jsonValue instanceof Array){value=jsonValue.map(it=>propDef.fromJSON(it))}else{value=propDef.fromJSON(jsonValue)}setAnyValue(target,propName,value)});callDecoratedMethod(target,AFTER_SERIALIZED)}function getSerializeSettings(clazz){return Reflect.getMetadata(JSON_SERIALIZED,clazz)}function getValueByReflectType(target,propName,value){const reflectType=Reflect.getDesignType(target,propName);if(reflectType===void 0)return value;if(reflectType===Array)return deserializeArray(value);const transformer=jsonTransformers.get(reflectType);return transformer?transformer.fromJson(value):deserialize(value,reflectType)}var jsonTransformers=new Map;function registerTransform(clazz,transform){jsonTransformers.set(clazz,transform)}var itSelf=some=>some;var done=()=>void 0;registerTransform(String,{fromJson:asString,toJson:itSelf});registerTransform(Number,{fromJson:asNumber,toJson:itSelf});registerTransform(Boolean,{fromJson:asBoolean,toJson:itSelf});registerTransform(Date,{fromJson:anyValue=>new Date(asNumber(anyValue)),toJson:date=>date.getTime()});var AfterSerialized=defineDecoratedProperty(AFTER_SERIALIZED);var mapStatus=new Map;function registerMappable(mappableClass){if(mapStatus.get(mappableClass))return;const classDef=getClassDefinition(mappableClass);const mapping=new Proxy({},{get(target,p){return doMap(p)},set(target,p,newValue){doMap(p)(newValue);return true}});function doMap(propName){return(fieldName,transform)=>{var _a,_b,_c;const propType=(_b=(_a=Object.values((classDef==null?void 0:classDef.allProperties)||{}))==null?void 0:_a.find(it=>it.name===propName))==null?void 0:_b.type;let propClass=(propType==null?void 0:propType.name)!==void 0?getClassByName(propType.name):void 0;if(propType&&isArrayType(propType)){propClass=((_c=propType.arrayElementType)==null?void 0:_c.name)!==void 0?getClassByName(propType.arrayElementType.name):void 0}if(typeof propName!=="string")return;registerSerializedProperty(mappableClass.prototype,propName,{name:fieldName,class:propClass,fromJSON:transform==null?void 0:transform.fromJSON,toJSON:transform==null?void 0:transform.toJSON});setDefaultIgnored(mappableClass,true)}}mappableClass.prototype.mapping(mapping);mapStatus.set(mappableClass,true)}function mapAllProperties(target,map){const classDef=getClassDefinition(target);if(!classDef)return;classDef.properties.forEach(prop=>map[prop.name]())}import"reflect-metadata";var DESIGN_TYPE="design:type";var DESIGN_RETURNTYPE="design:returntype";var DESIGN_PARAMTYPES="design:paramtypes";function getDesignType(target,property){return Reflect.getMetadata(DESIGN_TYPE,target,property)}function getReturnType(target,property){return Reflect.getMetadata(DESIGN_RETURNTYPE,target,property)}function getParamTypes(target,property){return Reflect.getMetadata(DESIGN_PARAMTYPES,target,property)}function addMetadataList(key,value,target,propertyKey){const list=(propertyKey===void 0?Reflect.getMetadata(key,target):Reflect.getMetadata(key,target,propertyKey))||[];if(!list.includes(value))list.push(value);propertyKey===void 0?Reflect.defineMetadata(key,list,target):Reflect.defineMetadata(key,list,target,propertyKey)}Object.assign(Reflect,{getDesignType,getReturnType,getParamTypes,addMetadataList});export{AfterSerialized,ClassDefinition,EnumDefinition,IgnoreSerialization,InterfaceDefinition,Lazy,MethodDefinition,PropertyDefinition,PropertyWrapper,ReflectClass,ReflectValidate,Serialized,SerializedClass,SerializedName,ValidateResult,anyType,asBoolean,asNumber,asString,assertType,callDecoratedMethod,createNewInstance,defineDecoratedProperty,deserialize,deserializeArray,deserializeFrom,done,failedResult,fillMethod,fillProperty,getAnyValue,getClassByName,getClassDefinition,getDecoratedProperty,getDecoratedPropertyValue,getEnumDefinition,getEnumNames,getEnumValues,getErrorTraceMessages,getInterfaceDefinition,getOrSetValue,getSerializeSettings,getTypeAliasDefinition,getTypeDef,getTypeDefinition,hasDecoratedMethod,hasGenerics,initReflectContext,isArrayType,isClassDefinition,isDictionary,isIgnoredType,isIntersectionType,isLiteralType,isNullable,isPrimitiveType,isTupleType,isType,isTypeLiteralType,isUnionType,itSelf,mapAllProperties,nullType,primitiveTypes,registerMappable,registerSerializedProperty,registerTransform,safeCall,serialize,serializeTo,serializeToData,setAnyValue,setDefaultIgnored,successResult,validateArray,validateDictionary,validateFunctionArgument,validateInstance};
|
package/dist/esm/parser/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var I=(e,n,t)=>new Promise((s,p)=>{var c=T=>{try{y(t.next(T))}catch(D){p(D)}},o=T=>{try{y(t.throw(T))}catch(D){p(D)}},y=T=>T.done?s(T.value):Promise.resolve(T.value).then(c,o);y((t=t.apply(e,n)).next())});import V from"typescript";import i from"typescript";import*as E from"fs";import*as M from"process";import*as w from"path";import{pathToFileURL as fe}from"url";var z={OUTPUT_LOG:!1},N=new Map,P=new Map,F=new Map,A=new Map,q=new Map,C=new Set,B={[i.SyntaxKind.BooleanKeyword]:"boolean",[i.SyntaxKind.StringKeyword]:"string",[i.SyntaxKind.BigIntKeyword]:"bigint",[i.SyntaxKind.NumberKeyword]:"number",[i.SyntaxKind.SymbolKeyword]:"symbol",[i.SyntaxKind.VoidKeyword]:"void",[i.SyntaxKind.UndefinedKeyword]:"undefined",[i.SyntaxKind.UnknownKeyword]:"unknown",[i.SyntaxKind.AnyKeyword]:"any",[i.SyntaxKind.ObjectKeyword]:"object"},O="any",H=["string","number","boolean","bigint","symbol"],X=["any","Promise","Date","Error","undefined","unknown","object","Map","Set"],Y=["Mappable","EnableReflect"];[...H,...X,...Y].forEach(ie);Y.forEach(e=>P.set(e,{name:e}));var v,J=!1,R=Reflect;function Ee(e){return I(this,null,function*(){let{filePaths:n,exclude:t,sourceFolder:s,distFolder:p}=e;if(s=w.resolve(s||M.cwd()),p=w.resolve(p||M.cwd()),R.__classes!==void 0)return;n=ae(n);let c=n.map(o=>w.join(s,o));G(c,t),R.__classes={};for(let[o,y]of N)R.__classes[o]=y;R.__interfaces={};for(let[o,y]of P)R.__interfaces[o]=y;R.__typeAliases={};for(let[o,y]of A)R.__typeAliases[o]=y;R.__constTypes={};for(let[o,y]of q)R.__constTypes[o]=y;yield Promise.all(n.map(o=>Z(o,p)))})}function Z(e,n){return I(this,null,function*(){let t=w.resolve(n,e);if(!E.existsSync(t))return;if(E.statSync(t).isDirectory()){E.readdirSync(t).forEach(T=>{Z(w.join(e,T),n)});return}if(!e.endsWith(".js"))return;let p=w.join(n,e),o=yield import(fe(p).href);R.__classDef={},Object.values(o).forEach(y=>{typeof y=="function"&&(R.__classDef[y.name]=y)})})}function G(e,n){if(e||(e=[M.cwd()]),e=ae(e),!J){let t=ee(e,n),s=i.createProgram(t,{});v=s.getTypeChecker(),t=t.map(c=>W(c)),s.getSourceFiles().filter(c=>t.includes(W(c.fileName))).forEach(c=>{b(`parse file: ${c.fileName}`),ne(c)});for(let c of C.keys())!N.has(c)&&!P.has(c)&&!F.has(c)&&!A.has(c)&&!H.includes(c)&&!X.includes(c)&&(b(`remove unknown typeName: ${c}`),C.delete(c));Array.from(N.values()).forEach(ge),Array.from(P.values()).forEach(Te),[N,P,A].forEach(he),J=!0}return{classDefinitions:N,interfaceDefinitions:P,enumDefinitions:F,typeAliasDefinitions:A,constTypeDefinitions:q}}function ee(e,n){let t=[];return e.forEach(s=>{if(s=w.resolve(s),De(s,n)){b(`ignore excluded ${s}`);return}if(!E.existsSync(s)){console.error(`Path ${s} does not exist.`);return}if(E.statSync(s).isFile()){t.push(s);return}E.readdirSync(s).forEach(o=>t.push(...ee([w.join(s,o)],n)))}),t}function ne(e){i.isClassDeclaration(e)?ce(e):i.isInterfaceDeclaration(e)?le(e):i.isEnumDeclaration(e)?pe(e):i.isTypeAliasDeclaration(e)?ue(e):i.isConstTypeReference(e)?me(e):e.forEachChild(ne)}function ce(e){var y,T,D,x,u,h,K,k,L,d,r,m;let n=f(e.name);if(!n)return;let t=f((D=(T=(y=e.heritageClauses)==null?void 0:y.find(a=>a.token===i.SyntaxKind.ExtendsKeyword))==null?void 0:T.types)==null?void 0:D[0].expression),s=(u=(x=e.heritageClauses)==null?void 0:x.find(a=>a.token===i.SyntaxKind.ImplementsKeyword))==null?void 0:u.types.map(a=>f(a.expression)),p=[],c=[];for(let a of e.members)if(i.isPropertyDeclaration(a))p.push({name:f(a.name),isOptional:a.questionToken!==void 0,type:g(a),isPrivate:(h=a.modifiers)==null?void 0:h.some(l=>l.kind===i.SyntaxKind.PrivateKeyword),isStatic:(K=a.modifiers)==null?void 0:K.some(l=>l.kind===i.SyntaxKind.StaticKeyword)});else if(i.isMethodDeclaration(a))c.push({name:f(a.name),returnType:g(a),isPrivate:(k=a.modifiers)==null?void 0:k.some(l=>l.kind===i.SyntaxKind.PrivateKeyword),isStatic:(L=a.modifiers)==null?void 0:L.some(l=>l.kind===i.SyntaxKind.StaticKeyword),isAsync:(d=a.modifiers)==null?void 0:d.some(l=>l.kind===i.SyntaxKind.AsyncKeyword),args:a.parameters.map(l=>({name:f(l.name),type:g(l),isOptional:l.questionToken!==void 0}))});else if(i.isGetAccessorDeclaration(a)){let l=p.find(_=>_.name===f(a.name));l||(l={name:f(a.name),isOptional:a.questionToken===void 0,type:g(a)},p.push(l)),l.accessor=l.accessor||{},l.accessor.getter={isPrivate:((r=a.modifiers)==null?void 0:r.some(_=>_.kind===i.SyntaxKind.PrivateKeyword))||!1},l.isPrivate=l.accessor.getter.isPrivate}else if(i.isSetAccessorDeclaration(a)){let l=p.find(_=>_.name===f(a.name));l||(l={name:f(a.name),isOptional:a.questionToken===void 0,type:g(a)},p.push(l)),l.accessor=l.accessor||{},l.accessor.setter={isPrivate:((m=a.modifiers)==null?void 0:m.some(_=>_.kind===i.SyntaxKind.PrivateKeyword))||!1}}let o={name:n,superClassName:t,implementations:s,properties:p,methods:c};b(`Define class: ${f(e.name)}`),N.set(n,o)}function le(e){var y,T,D,x;let n=f(e.name);if(!n)return;let t=((T=(y=e.heritageClauses)==null?void 0:y.find(u=>u.token===i.SyntaxKind.ExtendsKeyword))==null?void 0:T.types.map(u=>f(u.expression)))||[],s=[],p=[],c;for(let u of e.members)i.isPropertySignature(u)?s.push({name:f(u.name),isOptional:u.questionToken!==void 0,type:g(u),isPrivate:((D=u.modifiers)==null?void 0:D.some(h=>h.kind===i.SyntaxKind.PrivateKeyword))||!1}):i.isMethodSignature(u)?p.push({name:u.name.text,returnType:g(u),isPrivate:((x=u.modifiers)==null?void 0:x.some(h=>h.kind===i.SyntaxKind.PrivateKeyword))||!1,args:u.parameters.map(h=>({name:f(h.name),type:g(h),isOptional:h.questionToken!==void 0}))}):i.isIndexSignatureDeclaration(u)&&(c=g(u));let o=P.get(n);o?(o.implementations=$(o.implementations||[],t),o.methods=$(o.methods||[],p,(u,h)=>u.name===h.name),o.properties=$(o.properties||[],s,(u,h)=>u.name===h.name),o.indexElementType=c,b(`Merge interface ${f(e.name)}`)):(o={name:n,implementations:t,methods:p,properties:s,indexElementType:c},P.set(n,o),b(`Define interface ${f(e.name)}`))}function pe(e){let n=f(e.name);n&&(F.set(n,{name:n,members:e.members.map(t=>({name:f(t.name),initializer:f(t.initializer)}))}),b(`Define enum: ${f(e.name)}`))}function ue(e){b(`Define typeAlias: ${f(e.name)}`),A.set(f(e.name),g(e))}function me(e){let n=e.parent.parent;i.isVariableDeclaration(n)&&n.initializer&&i.isAsExpression(n.initializer)&&q.set(f(n.name),te(n.initializer.expression))}function te(e){return i.isArrayLiteralExpression(e)?ye(e):i.isObjectLiteralExpression(e)?de(e):i.isNumericLiteral(e)?"number":i.isStringLiteral(e)?"string":i.isBigIntLiteral(e)?"bigint":[i.SyntaxKind.TrueKeyword,i.SyntaxKind.FalseKeyword].includes(e.kind)?"boolean":O}function ye(e){let n=[];return e.elements.forEach(t=>{if(i.isStringLiteral(t))return n.push(f(t))}),n.length===0?O:n.length===1?n[0]:{unionMembers:n}}function de(e){let n=[];return e.properties.map(t=>{i.isPropertyAssignment(t)?n.push({name:f(t.name),type:te(t.initializer)}):b(`unsupported property: ${t.name}`)}),{typeLiteralMembers:n}}function ie(e){C.add(e)}function g(e,n=!1){if(e.type&&!n)return S(e.type);if(!v)return console.error("TypeChecker not initialized!"),O;let t=v.getTypeAtLocation(e),s=v.typeToTypeNode(t,void 0,void 0);return s?S("type"in s?s.type:s):O}function S(e){let n={};if(e===void 0)return O;if(i.isUnionTypeNode(e))n.unionMembers=e.types.map(S);else if(i.isIntersectionTypeNode(e))n.intersectionMembers=e.types.map(S);else if(i.isLiteralTypeNode(e))n.literalValue=f(e.literal);else if(i.isTypeLiteralNode(e)){let t=[];e.members.forEach(s=>{i.isPropertySignature(s)?t.push({name:f(s.name),isOptional:s.questionToken!==void 0,type:g(s)}):i.isIndexSignatureDeclaration(s)?n.indexElementType=g(s):t.push({name:f(s.name)||"",isOptional:s.questionToken!==void 0,type:S()})}),n.typeLiteralMembers=t}else if(i.isArrayTypeNode(e))n.arrayElementType=S(e.elementType);else if(i.isFunctionTypeNode(e))n.isFunction=!0;else if(i.isTypeReferenceNode(e))if(ie(f(e.typeName)),e.typeArguments)n.generics=[f(e.typeName),...e.typeArguments.map(t=>S(t))];else return f(e.typeName);else{if(i.isIndexedAccessTypeNode(e))return g(e,!0);if(i.isThisTypeNode(e))return g(e);if(i.isParenthesizedTypeNode(e))return g(e);if(i.isConditionalTypeNode(e))return g(e);if(i.isTypeQueryNode(e))return g(e);if(i.isConstructorTypeNode(e))n.isConstructor=!0;else if(i.isTupleTypeNode(e))n.tupleMembers=e.elements.map(S);else{if(Object.keys(B).includes(String(e.kind)))return B[e.kind]||O;if(i.isOptionalTypeNode(e))Object.assign(n,g(e)),n.isOptionalInTuple=!0;else if(i.isNamedTupleMember(e))Object.assign(n,g(e));else return i.isTypeOperatorNode(e)&&e.operator===i.SyntaxKind.KeyOfKeyword,g(e,!0)}}return n}var $=(e,n,t)=>[...(e==null?void 0:e.filter(s=>!(n!=null&&n.some(p=>(t||(()=>p===s))(p,s)))))||[],...n||[]];function j(e){if(e!==void 0&&e!==O)return typeof e=="string"?C.has(e)?e:void 0:e}function ge(e){var n,t;(n=e.methods)==null||n.forEach(re),(t=e.properties)==null||t.forEach(se)}function Te(e){var n,t;(n=e.methods)==null||n.forEach(re),(t=e.properties)==null||t.forEach(se)}function se(e){e.type=j(e.type)}function re(e){var n;(n=e.args)==null||n.forEach(t=>t.type=j(t.type)),e.returnType=j(e.returnType)}function f(e){if(!e)return e;if(e.end<0)return e.text;try{return i.isQualifiedName(e)?f(e.right):e.getText()}catch(n){return e.text}}function U(e){e&&Object.entries(e).forEach(n=>{let[t,s]=n;s instanceof Array&&s.length===0||s===!1||s===void 0?delete e[t]:s.constructor===Array?s.forEach(U):s.constructor===Object&&U(s)})}function he(e){for(let n of e.values())U(n)}function De(e,n){return n?(n=n instanceof Array?n:[n],n.some(t=>(t instanceof RegExp||(t=new RegExp(t.replace(/\./g,"\\.").replace(/\*/g,".*"))),e.match(t)))):!1}function W(e,n=M.cwd()){return Q(e).replace(Q(n)+"/","")}function Q(e){let n=w.sep;return e.split(n).join("/")}function ae(e){return e instanceof Array?e:[e]}function b(e){z.OUTPUT_LOG&&console.log(e)}function oe(e){let{sourcePaths:n,exclude:t,forEnabledClassOnly:s,outputLog:p}=e;if(p&&(z.OUTPUT_LOG=!0),!n)throw new Error("need provide source paths for reflect loader");let{classDefinitions:c,interfaceDefinitions:o,enumDefinitions:y,typeAliasDefinitions:T}=G(n,t),D=[],x=[];function u(d){let r=c.get(d),m=[];return r?(r.superClassName&&m.push(r.superClassName),m.push(...r.implementations||[])):(r=o.get(d),r?m.push(...r.implementations||[]):(r=T.get(d),r&&m.push(...r.implementations||[]))),m.flatMap(a=>[a,...u(a)])||[]}function h(d,r){return u(d.name).includes(r)}function K(d){if(V.isClassDeclaration(d)&&d.name!==void 0){let r=d.name.text,m=c.get(r);if(!r||!m||s&&!h(m,"EnableReflect"))return;x.push(`Reflect.__classDef = Object.assign(Reflect.__classDef || {}, { ${r} })`);return}d.forEachChild(K)}function k(){let d=[];return c.forEach((r,m)=>{s&&!h(r,"EnableReflect")||d.push(`Reflect.__classes = Object.assign(Reflect.__classes || {}, { ${m}: ${JSON.stringify(r)} })`)}),o.forEach((r,m)=>{s&&!h(r,"EnableReflect")||d.push(`Reflect.__interfaces = Object.assign(Reflect.__interfaces || {}, { ${m}: ${JSON.stringify(r)} })`)}),y.forEach((r,m)=>{d.push(`Reflect.__enums = Object.assign(Reflect.__enums || {}, { ${m}: ${JSON.stringify(r)} })`)}),T.forEach((r,m)=>{d.push(`Reflect.__typeAliases = Object.assign(Reflect.__typeAliases || {}, { ${m}: ${JSON.stringify(r)} })`)}),d.join(`
|
|
2
|
-
`)}return{outputAllMetas:
|
|
3
|
-
${
|
|
1
|
+
var I=(e,n,i)=>new Promise((t,u)=>{var c=T=>{try{m(i.next(T))}catch(D){u(D)}},r=T=>{try{m(i.throw(T))}catch(D){u(D)}},m=T=>T.done?t(T.value):Promise.resolve(T.value).then(c,r);m((i=i.apply(e,n)).next())});import V from"typescript";import s from"typescript";import*as x from"fs";import*as M from"process";import*as R from"path";import{pathToFileURL as ce}from"url";var z={OUTPUT_LOG:!1},_=new Map,P=new Map,L=new Map,k=new Map,G=new Map,$=new Set,J={[s.SyntaxKind.BooleanKeyword]:"boolean",[s.SyntaxKind.StringKeyword]:"string",[s.SyntaxKind.BigIntKeyword]:"bigint",[s.SyntaxKind.NumberKeyword]:"number",[s.SyntaxKind.SymbolKeyword]:"symbol",[s.SyntaxKind.VoidKeyword]:"void",[s.SyntaxKind.UndefinedKeyword]:"undefined",[s.SyntaxKind.UnknownKeyword]:"unknown",[s.SyntaxKind.AnyKeyword]:"any",[s.SyntaxKind.ObjectKeyword]:"object"},b="any",X=["string","number","boolean","bigint","symbol"],Y=["any","Promise","Date","Error","undefined","unknown","object","Map","Set"],Z=["Mappable","EnableReflect"];[...X,...Y,...Z].forEach(se);Z.forEach(e=>P.set(e,{name:e}));var C,W=!1,w=Reflect;function Ne(e){return I(this,null,function*(){let{filePaths:n,exclude:i,sourceFolder:t,distFolder:u}=e;if(t=R.resolve(t||M.cwd()),u=R.resolve(u||M.cwd()),w.__classes!==void 0)return;n=oe(n);let c=n.map(r=>R.join(t,r));B(c,i),w.__classes={};for(let[r,m]of _)w.__classes[r]=m;w.__interfaces={};for(let[r,m]of P)w.__interfaces[r]=m;w.__typeAliases={};for(let[r,m]of k)w.__typeAliases[r]=m;w.__enums={};for(let[r,m]of L)w.__enums[r]=m;w.__constTypes={};for(let[r,m]of G)w.__constTypes[r]=m;yield Promise.all(n.map(r=>ee(r,u)))})}function ee(e,n){return I(this,null,function*(){let i=R.resolve(n,e);if(!x.existsSync(i))return;if(x.statSync(i).isDirectory()){x.readdirSync(i).forEach(T=>{ee(R.join(e,T),n)});return}if(!e.endsWith(".js"))return;let u=R.join(n,e),r=yield import(ce(u).href);w.__classDef={},Object.values(r).forEach(m=>{typeof m=="function"&&(w.__classDef[m.name]=m)})})}function B(e,n){if(e||(e=[M.cwd()]),e=oe(e),!W){let i=ne(e,n),t=s.createProgram(i,{});C=t.getTypeChecker(),i=i.map(c=>Q(c)),t.getSourceFiles().filter(c=>i.includes(Q(c.fileName))).forEach(c=>{S(`parse file: ${c.fileName}`),te(c)});for(let c of $.keys())!_.has(c)&&!P.has(c)&&!L.has(c)&&!k.has(c)&&!X.includes(c)&&!Y.includes(c)&&(S(`remove unknown typeName: ${c}`),$.delete(c));Array.from(_.values()).forEach(Te),Array.from(P.values()).forEach(he),[_,P,k].forEach(we),W=!0}return{classDefinitions:_,interfaceDefinitions:P,enumDefinitions:L,typeAliasDefinitions:k,constTypeDefinitions:G}}function ne(e,n){let i=[];return e.forEach(t=>{if(t=R.resolve(t),De(t,n)){S(`ignore excluded ${t}`);return}if(!x.existsSync(t)){console.error(`Path ${t} does not exist.`);return}if(x.statSync(t).isFile()){i.push(t);return}x.readdirSync(t).forEach(r=>i.push(...ne([R.join(t,r)],n)))}),i}function te(e){s.isClassDeclaration(e)?le(e):s.isInterfaceDeclaration(e)?pe(e):s.isEnumDeclaration(e)?ue(e):s.isTypeAliasDeclaration(e)?me(e):s.isConstTypeReference(e)?de(e):e.forEachChild(te)}function le(e){var m,T,D,E,N,l,h,v,F,y,o,d,A;let n=a(e.name);if(!n)return;let i=a((D=(T=(m=e.heritageClauses)==null?void 0:m.find(f=>f.token===s.SyntaxKind.ExtendsKeyword))==null?void 0:T.types)==null?void 0:D[0].expression),t=(N=(E=e.heritageClauses)==null?void 0:E.find(f=>f.token===s.SyntaxKind.ImplementsKeyword))==null?void 0:N.types.map(f=>a(f.expression)),u=[],c=[];for(let f of e.members)if(s.isPropertyDeclaration(f))u.push({name:a(f.name),isOptional:f.questionToken!==void 0,type:g(f),isPrivate:(l=f.modifiers)==null?void 0:l.some(p=>p.kind===s.SyntaxKind.PrivateKeyword),isStatic:(h=f.modifiers)==null?void 0:h.some(p=>p.kind===s.SyntaxKind.StaticKeyword)});else if(s.isMethodDeclaration(f))c.push({name:a(f.name),returnType:g(f),isPrivate:(v=f.modifiers)==null?void 0:v.some(p=>p.kind===s.SyntaxKind.PrivateKeyword),isStatic:(F=f.modifiers)==null?void 0:F.some(p=>p.kind===s.SyntaxKind.StaticKeyword),isAsync:(y=f.modifiers)==null?void 0:y.some(p=>p.kind===s.SyntaxKind.AsyncKeyword),args:f.parameters.map(p=>({name:a(p.name),type:g(p),isOptional:p.questionToken!==void 0}))});else if(s.isGetAccessorDeclaration(f)){let p=u.find(O=>O.name===a(f.name));p||(p={name:a(f.name),isOptional:f.questionToken===void 0,type:g(f)},u.push(p)),p.accessor=p.accessor||{},p.accessor.getter={isPrivate:((o=f.modifiers)==null?void 0:o.some(O=>O.kind===s.SyntaxKind.PrivateKeyword))||!1},p.isPrivate=p.accessor.getter.isPrivate}else if(s.isSetAccessorDeclaration(f)){let p=u.find(O=>O.name===a(f.name));p||(p={name:a(f.name),isOptional:f.questionToken===void 0,type:g(f)},u.push(p)),p.accessor=p.accessor||{},p.accessor.setter={isPrivate:((d=f.modifiers)==null?void 0:d.some(O=>O.kind===s.SyntaxKind.PrivateKeyword))||!1}}let r={name:n,superClassName:i,implementations:t,properties:u,methods:c,generics:(A=e.typeParameters)==null?void 0:A.map(f=>a(f.name))};S(`Define class: ${a(e.name)}`),_.set(n,r)}function pe(e){var m,T,D,E,N;let n=a(e.name);if(!n)return;let i=((T=(m=e.heritageClauses)==null?void 0:m.find(l=>l.token===s.SyntaxKind.ExtendsKeyword))==null?void 0:T.types.map(l=>a(l.expression)))||[],t=[],u=[],c;for(let l of e.members)s.isPropertySignature(l)?t.push({name:a(l.name),isOptional:l.questionToken!==void 0,type:g(l),isPrivate:((D=l.modifiers)==null?void 0:D.some(h=>h.kind===s.SyntaxKind.PrivateKeyword))||!1}):s.isMethodSignature(l)?u.push({name:l.name.text,returnType:g(l),isPrivate:((E=l.modifiers)==null?void 0:E.some(h=>h.kind===s.SyntaxKind.PrivateKeyword))||!1,args:l.parameters.map(h=>({name:a(h.name),type:g(h),isOptional:h.questionToken!==void 0}))}):s.isIndexSignatureDeclaration(l)&&(c=g(l));let r=P.get(n);r?(r.implementations=j(r.implementations||[],i),r.methods=j(r.methods||[],u,(l,h)=>l.name===h.name),r.properties=j(r.properties||[],t,(l,h)=>l.name===h.name),r.indexElementType=c,S(`Merge interface ${a(e.name)}`)):(r={name:n,implementations:i,methods:u,properties:t,indexElementType:c,generics:(N=e.typeParameters)==null?void 0:N.map(l=>a(l.name))},P.set(n,r),S(`Define interface ${a(e.name)}`))}function ue(e){let n=a(e.name);n&&(L.set(n,{name:n,members:e.members.map(i=>({name:a(i.name),initializer:a(i.initializer)}))}),S(`Define enum: ${a(e.name)}`))}function me(e){S(`Define typeAlias: ${a(e.name)}`),k.set(a(e.name),g(e))}function de(e){let n=e.parent.parent;s.isVariableDeclaration(n)&&n.initializer&&s.isAsExpression(n.initializer)&&G.set(a(n.name),ie(n.initializer.expression))}function ie(e){return s.isArrayLiteralExpression(e)?ye(e):s.isObjectLiteralExpression(e)?ge(e):s.isNumericLiteral(e)?"number":s.isStringLiteral(e)?"string":s.isBigIntLiteral(e)?"bigint":[s.SyntaxKind.TrueKeyword,s.SyntaxKind.FalseKeyword].includes(e.kind)?"boolean":b}function ye(e){let n=[];return e.elements.forEach(i=>{if(s.isStringLiteral(i))return n.push(a(i))}),n.length===0?b:n.length===1?n[0]:{unionMembers:n}}function ge(e){let n=[];return e.properties.map(i=>{s.isPropertyAssignment(i)?n.push({name:a(i.name),type:ie(i.initializer)}):S(`unsupported property: ${i.name}`)}),{typeLiteralMembers:n}}function se(e){$.add(e)}function g(e,n=!1){if(e.type&&!n)return K(e.type);if(!C)return console.error("TypeChecker not initialized!"),b;let i=C.getTypeAtLocation(e),t=C.typeToTypeNode(i,void 0,void 0);return t?K("type"in t?t.type:t):b}function K(e){let n={};if(e===void 0)return b;if(s.isUnionTypeNode(e))n.unionMembers=e.types.map(K);else if(s.isIntersectionTypeNode(e))n.intersectionMembers=e.types.map(K);else if(s.isLiteralTypeNode(e))n.literalValue=a(e.literal);else if(s.isTypeLiteralNode(e)){let i=[];e.members.forEach(t=>{s.isPropertySignature(t)?i.push({name:a(t.name),isOptional:t.questionToken!==void 0,type:g(t)}):s.isIndexSignatureDeclaration(t)?n.indexElementType=g(t):i.push({name:a(t.name)||"",isOptional:t.questionToken!==void 0,type:K()})}),n.typeLiteralMembers=i}else if(s.isArrayTypeNode(e))n.arrayElementType=K(e.elementType);else if(s.isFunctionTypeNode(e))n.isFunction=!0;else if(s.isTypeReferenceNode(e))if(se(a(e.typeName)),e.typeArguments)n.generics=[a(e.typeName),...e.typeArguments.map(i=>K(i))];else return a(e.typeName);else{if(s.isIndexedAccessTypeNode(e))return g(e,!0);if(s.isThisTypeNode(e))return g(e);if(s.isParenthesizedTypeNode(e))return g(e);if(s.isConditionalTypeNode(e))return g(e);if(s.isTypeQueryNode(e))return g(e);if(s.isConstructorTypeNode(e))n.isConstructor=!0;else if(s.isTupleTypeNode(e))n.tupleMembers=e.elements.map(K);else{if(Object.keys(J).includes(String(e.kind)))return J[e.kind]||b;if(s.isOptionalTypeNode(e))Object.assign(n,g(e)),n.isOptionalInTuple=!0;else if(s.isNamedTupleMember(e))Object.assign(n,g(e));else return s.isTypeOperatorNode(e)&&e.operator===s.SyntaxKind.KeyOfKeyword,g(e,!0)}}return n}var j=(e,n,i)=>[...(e==null?void 0:e.filter(t=>!(n!=null&&n.some(u=>(i||(()=>u===t))(u,t)))))||[],...n||[]];function U(e,n){if(e!==void 0&&e!==b)return typeof e=="string"?$.has(e)||n!=null&&n.includes(e)?e:void 0:e}function Te(e){var n,i;(n=e.methods)==null||n.forEach(t=>ae(t,e.generics)),(i=e.properties)==null||i.forEach(t=>re(t,e.generics))}function he(e){var n,i;(n=e.methods)==null||n.forEach(t=>ae(t,e.generics)),(i=e.properties)==null||i.forEach(t=>re(t,e.generics))}function re(e,n){e.type=U(e.type,n)}function ae(e,n){var i;(i=e.args)==null||i.forEach(t=>t.type=U(t.type,n)),e.returnType=U(e.returnType,n)}function a(e){if(!e)return e;if(e.end<0)return e.text;try{return s.isQualifiedName(e)?a(e.right):e.getText()}catch(n){return e.text}}function q(e){e&&Object.entries(e).forEach(n=>{let[i,t]=n;t instanceof Array&&t.length===0||t===!1||t===void 0?delete e[i]:t.constructor===Array?t.forEach(q):t.constructor===Object&&q(t)})}function we(e){for(let n of e.values())q(n)}function De(e,n){return n?(n=n instanceof Array?n:[n],n.some(i=>(i instanceof RegExp||(i=new RegExp(i.replace(/\./g,"\\.").replace(/\*/g,".*"))),e.match(i)))):!1}function Q(e,n=M.cwd()){return H(e).replace(H(n)+"/","")}function H(e){let n=R.sep;return e.split(n).join("/")}function oe(e){return e instanceof Array?e:[e]}function S(e){z.OUTPUT_LOG&&console.log(e)}function fe(e){let{sourcePaths:n,exclude:i,forEnabledClassOnly:t,outputLog:u}=e;if(u&&(z.OUTPUT_LOG=!0),!n)throw new Error("need provide source paths for reflect loader");let{classDefinitions:c,interfaceDefinitions:r,enumDefinitions:m,typeAliasDefinitions:T}=B(n,i),D=[],E=[];function N(y){let o=c.get(y),d=[];return o?(o.superClassName&&d.push(o.superClassName),d.push(...o.implementations||[])):(o=r.get(y),o?d.push(...o.implementations||[]):(o=T.get(y),o&&d.push(...o.implementations||[]))),d.flatMap(A=>[A,...N(A)])||[]}function l(y,o){return N(y.name).includes(o)}function h(y){if(V.isClassDeclaration(y)&&y.name!==void 0){let o=y.name.text,d=c.get(o);if(!o||!d||t&&!l(d,"EnableReflect"))return;E.push(`Reflect.__classDef = Object.assign(Reflect.__classDef || {}, { ${o} })`);return}y.forEachChild(h)}function v(){let y=[];return c.forEach((o,d)=>{t&&!l(o,"EnableReflect")||y.push(`Reflect.__classes = Object.assign(Reflect.__classes || {}, { ${d}: ${JSON.stringify(o)} })`)}),r.forEach((o,d)=>{t&&!l(o,"EnableReflect")||y.push(`Reflect.__interfaces = Object.assign(Reflect.__interfaces || {}, { ${d}: ${JSON.stringify(o)} })`)}),m.forEach((o,d)=>{y.push(`Reflect.__enums = Object.assign(Reflect.__enums || {}, { ${d}: ${JSON.stringify(o)} })`)}),T.forEach((o,d)=>{y.push(`Reflect.__typeAliases = Object.assign(Reflect.__typeAliases || {}, { ${d}: ${JSON.stringify(o)} })`)}),y.join(`
|
|
2
|
+
`)}return{outputAllMetas:v,transform:(y,o)=>{if(o.endsWith(".ts")&&!(typeof n=="string"?[n]:n).every(d=>!o.startsWith(d)))try{let d=V.createSourceFile(o,y,V.ScriptTarget.Latest,!1);return D.length=0,E.length=0,h(d),`${D.join(";")};${y};${E.join(";")}`}catch(d){return console.error(`[reflect-parser-plugin] Error processing ${o}:`,d),null}}}}var Re=process.cwd().replace(/\\/g,"/")+"/";function Me(e){let n=fe(e);return{name:"reflect-parser-plugin",enforce:"pre",transform:(i,t)=>(t=t.replace(Re,""),t===e.entry?`${n.outputAllMetas()}
|
|
3
|
+
${i}`:n.transform(i,t))}}export{z as DEBUG_CONFIG,B as parseSource,fe as reflectLoader,Me as reflectParserPlugin,Ne as setupReflectTypes,ee as updateReflectModules};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ts-ref-kit",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Type reflection and validation library for TypeScript",
|
|
5
5
|
"main": "dist/cjs/index.js",
|
|
6
6
|
"module": "dist/esm/index.js",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
},
|
|
33
33
|
"scripts": {
|
|
34
34
|
"build-types": "tsc --emitDeclarationOnly --outDir types",
|
|
35
|
-
"clean": "
|
|
35
|
+
"clean": "rimraf -rf dist types",
|
|
36
36
|
"build": "npm run clean && node esbuild.config.js && node esbuild.parser.config.js && tsc --emitDeclarationOnly --outDir types"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
@@ -1,69 +1,7 @@
|
|
|
1
|
+
import type { RawClassDefinition, RawInterfaceDefinition, RawEnumDefinition, RawTypeDef } from '../raw';
|
|
1
2
|
export declare const DEBUG_CONFIG: {
|
|
2
3
|
OUTPUT_LOG: boolean;
|
|
3
4
|
};
|
|
4
|
-
type Any = any;
|
|
5
|
-
export interface RawClassDefinition {
|
|
6
|
-
name: string;
|
|
7
|
-
superClassName?: string;
|
|
8
|
-
implementations?: string[];
|
|
9
|
-
methods?: RawMethodDefinition[];
|
|
10
|
-
properties?: RawPropertyDefinition[];
|
|
11
|
-
}
|
|
12
|
-
export interface RawInterfaceDefinition {
|
|
13
|
-
name: string;
|
|
14
|
-
implementations?: string[];
|
|
15
|
-
methods?: RawMethodDefinition[];
|
|
16
|
-
properties?: RawPropertyDefinition[];
|
|
17
|
-
indexElementType?: RawTypeDef;
|
|
18
|
-
}
|
|
19
|
-
export interface RawEnumDefinition {
|
|
20
|
-
name: string;
|
|
21
|
-
members: {
|
|
22
|
-
name: string;
|
|
23
|
-
initializer: string | undefined;
|
|
24
|
-
}[];
|
|
25
|
-
}
|
|
26
|
-
export interface RawMethodDefinition {
|
|
27
|
-
name: string;
|
|
28
|
-
isPrivate?: boolean;
|
|
29
|
-
isStatic?: boolean;
|
|
30
|
-
isAsync?: boolean;
|
|
31
|
-
returnType?: RawTypeDef;
|
|
32
|
-
args?: {
|
|
33
|
-
name: string;
|
|
34
|
-
type?: RawTypeDef;
|
|
35
|
-
isOptional: boolean;
|
|
36
|
-
}[];
|
|
37
|
-
}
|
|
38
|
-
export interface RawPropertyDefinition {
|
|
39
|
-
name: string;
|
|
40
|
-
isOptional?: boolean;
|
|
41
|
-
isPrivate?: boolean;
|
|
42
|
-
isStatic?: boolean;
|
|
43
|
-
type?: RawTypeDef;
|
|
44
|
-
accessor?: {
|
|
45
|
-
getter?: {
|
|
46
|
-
isPrivate: boolean;
|
|
47
|
-
};
|
|
48
|
-
setter?: {
|
|
49
|
-
isPrivate: boolean;
|
|
50
|
-
};
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
type RawTypeDef = string | RawTypeDefinition;
|
|
54
|
-
export interface RawTypeDefinition {
|
|
55
|
-
arrayElementType?: RawTypeDef;
|
|
56
|
-
indexElementType?: RawTypeDef;
|
|
57
|
-
literalValue?: Any;
|
|
58
|
-
typeLiteralMembers?: RawPropertyDefinition[];
|
|
59
|
-
unionMembers?: RawTypeDef[];
|
|
60
|
-
intersectionMembers?: RawTypeDef[];
|
|
61
|
-
generics?: RawTypeDef[];
|
|
62
|
-
isFunction?: boolean;
|
|
63
|
-
tupleMembers?: RawTypeDef[];
|
|
64
|
-
isOptionalInTuple?: boolean;
|
|
65
|
-
isConstructor?: boolean;
|
|
66
|
-
}
|
|
67
5
|
type FilePathRule = string | RegExp | (string | RegExp)[];
|
|
68
6
|
export declare function setupReflectTypes(cfg: {
|
|
69
7
|
filePaths: string | string[];
|
package/types/raw.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export interface RawClassDefinition {
|
|
2
|
+
name: string;
|
|
3
|
+
superClassName?: string;
|
|
4
|
+
implementations?: string[];
|
|
5
|
+
methods?: RawMethodDefinition[];
|
|
6
|
+
properties?: RawPropertyDefinition[];
|
|
7
|
+
generics?: string[];
|
|
8
|
+
}
|
|
9
|
+
export interface RawInterfaceDefinition {
|
|
10
|
+
name: string;
|
|
11
|
+
implementations?: string[];
|
|
12
|
+
methods?: RawMethodDefinition[];
|
|
13
|
+
properties?: RawPropertyDefinition[];
|
|
14
|
+
indexElementType?: RawTypeDef;
|
|
15
|
+
generics?: string[];
|
|
16
|
+
}
|
|
17
|
+
export interface RawEnumDefinition {
|
|
18
|
+
name: string;
|
|
19
|
+
members: {
|
|
20
|
+
name: string;
|
|
21
|
+
initializer: string | undefined;
|
|
22
|
+
}[];
|
|
23
|
+
}
|
|
24
|
+
export interface RawMethodDefinition {
|
|
25
|
+
name: string;
|
|
26
|
+
isPrivate?: boolean;
|
|
27
|
+
isStatic?: boolean;
|
|
28
|
+
isAsync?: boolean;
|
|
29
|
+
returnType?: RawTypeDef;
|
|
30
|
+
args?: {
|
|
31
|
+
name: string;
|
|
32
|
+
type?: RawTypeDef;
|
|
33
|
+
isOptional: boolean;
|
|
34
|
+
}[];
|
|
35
|
+
}
|
|
36
|
+
export interface RawPropertyDefinition {
|
|
37
|
+
name: string;
|
|
38
|
+
isOptional?: boolean;
|
|
39
|
+
isPrivate?: boolean;
|
|
40
|
+
isStatic?: boolean;
|
|
41
|
+
type?: RawTypeDef;
|
|
42
|
+
accessor?: {
|
|
43
|
+
getter?: {
|
|
44
|
+
isPrivate: boolean;
|
|
45
|
+
};
|
|
46
|
+
setter?: {
|
|
47
|
+
isPrivate: boolean;
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export type RawTypeDef = string | RawTypeDefinition;
|
|
52
|
+
export interface RawTypeDefinition {
|
|
53
|
+
arrayElementType?: RawTypeDef;
|
|
54
|
+
indexElementType?: RawTypeDef;
|
|
55
|
+
literalValue?: unknown;
|
|
56
|
+
typeLiteralMembers?: RawPropertyDefinition[];
|
|
57
|
+
unionMembers?: RawTypeDef[];
|
|
58
|
+
intersectionMembers?: RawTypeDef[];
|
|
59
|
+
generics?: RawTypeDef[];
|
|
60
|
+
isFunction?: boolean;
|
|
61
|
+
tupleMembers?: RawTypeDef[];
|
|
62
|
+
isOptionalInTuple?: boolean;
|
|
63
|
+
isConstructor?: boolean;
|
|
64
|
+
}
|
|
65
|
+
export type Any = any;
|
|
66
|
+
export type AnyObject = {
|
|
67
|
+
[prop: string]: Any;
|
|
68
|
+
};
|
|
69
|
+
export type AnyFunction = (...args: Any[]) => Any;
|
|
70
|
+
export type AnyConstructorFunction = new (...args: Any[]) => Any;
|
|
71
|
+
export type Dictionary<T> = {
|
|
72
|
+
[key: string]: T;
|
|
73
|
+
};
|
|
74
|
+
export interface ReflectObject {
|
|
75
|
+
__classDef: Dictionary<AnyConstructorFunction>;
|
|
76
|
+
__classes: Dictionary<RawClassDefinition>;
|
|
77
|
+
__interfaces: Dictionary<RawInterfaceDefinition>;
|
|
78
|
+
__enums: Dictionary<RawEnumDefinition>;
|
|
79
|
+
__typeAliases: Dictionary<RawTypeDef>;
|
|
80
|
+
__constTypes: Dictionary<RawTypeDef>;
|
|
81
|
+
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import type { AnyConstructorFunction, Dictionary } from '
|
|
4
|
-
type ImplementationOfClass = InterfaceDefinition | TypeDefinition;
|
|
1
|
+
import { Implementation, type TypeDefinition } from './index';
|
|
2
|
+
import { MethodDefinition, PropertyDefinition } from './index';
|
|
3
|
+
import type { AnyConstructorFunction, Dictionary, RawClassDefinition } from '../raw';
|
|
5
4
|
export declare class ClassDefinition {
|
|
5
|
+
readonly generics: string[];
|
|
6
6
|
readonly name: string;
|
|
7
7
|
readonly superClassName: string;
|
|
8
8
|
readonly superClass: ClassDefinition | undefined;
|
|
@@ -17,12 +17,11 @@ export declare class ClassDefinition {
|
|
|
17
17
|
});
|
|
18
18
|
get allMethods(): Dictionary<MethodDefinition>;
|
|
19
19
|
get allProperties(): Dictionary<PropertyDefinition>;
|
|
20
|
-
get implementations():
|
|
21
|
-
get allImplementations():
|
|
20
|
+
get implementations(): Implementation[];
|
|
21
|
+
get allImplementations(): Implementation[];
|
|
22
22
|
getProperty(propName: string): PropertyDefinition | undefined;
|
|
23
23
|
get type(): TypeDefinition;
|
|
24
24
|
isSubClassOf(typeName: string): boolean;
|
|
25
25
|
isSuperClassOf(typeName: string): boolean;
|
|
26
26
|
toString(): string;
|
|
27
27
|
}
|
|
28
|
-
export {};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { RawEnumDefinition
|
|
1
|
+
import type { RawEnumDefinition } from '../raw';
|
|
2
|
+
import { type TypeDefinition } from './TypeDefinition';
|
|
2
3
|
export declare class EnumDefinition {
|
|
3
4
|
readonly name: string;
|
|
4
5
|
readonly members: Map<string, TypeDefinition>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ClassDefinition, type TypeDefinition } from './index';
|
|
2
|
+
import { type Dictionary } from '../raw';
|
|
3
|
+
import { GenericProperty } from './GenericProperty';
|
|
4
|
+
import { GenericMethod } from './GenericMethod';
|
|
5
|
+
export declare class GenericClass extends ClassDefinition {
|
|
6
|
+
genericArgs: TypeDefinition[];
|
|
7
|
+
properties: GenericProperty[];
|
|
8
|
+
methods: GenericMethod[];
|
|
9
|
+
genericContext: Dictionary<TypeDefinition>;
|
|
10
|
+
static create(proto: ClassDefinition, genericArgs: TypeDefinition[]): GenericClass;
|
|
11
|
+
buildGenericContext(): void;
|
|
12
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { InterfaceDefinition, MethodDefinition, PropertyDefinition, type TypeDefinition } from './index';
|
|
2
|
+
import { type Dictionary } from '../raw';
|
|
3
|
+
export declare class GenericInterface extends InterfaceDefinition {
|
|
4
|
+
genericArgs: TypeDefinition[];
|
|
5
|
+
properties: PropertyDefinition[];
|
|
6
|
+
methods: MethodDefinition[];
|
|
7
|
+
genericContext: Dictionary<TypeDefinition>;
|
|
8
|
+
static create(proto: InterfaceDefinition, genericArgs: TypeDefinition[]): GenericInterface;
|
|
9
|
+
buildGenericContext(): void;
|
|
10
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { MethodDefinition, type TypeDefinition } from './index';
|
|
2
|
+
import { type Dictionary } from '../raw';
|
|
3
|
+
export declare class GenericMethod extends MethodDefinition {
|
|
4
|
+
genericContext: Dictionary<TypeDefinition>;
|
|
5
|
+
static create(proto: MethodDefinition, genericContext: Dictionary<TypeDefinition>): GenericMethod;
|
|
6
|
+
get args(): {
|
|
7
|
+
name: string;
|
|
8
|
+
type: TypeDefinition;
|
|
9
|
+
isOptional: boolean;
|
|
10
|
+
}[];
|
|
11
|
+
get returnType(): TypeDefinition;
|
|
12
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Dictionary } from '../raw';
|
|
2
|
+
import { type TypeDefinition, PropertyDefinition } from './index';
|
|
3
|
+
export declare class GenericProperty extends PropertyDefinition {
|
|
4
|
+
genericContext: Dictionary<TypeDefinition>;
|
|
5
|
+
static create(proto: PropertyDefinition, genericContext: Dictionary<TypeDefinition>): GenericProperty;
|
|
6
|
+
get type(): TypeDefinition;
|
|
7
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { type TypeDefinition } from './index';
|
|
2
2
|
import { MethodDefinition, PropertyDefinition } from './index';
|
|
3
|
-
|
|
3
|
+
import { type RawInterfaceDefinition } from '../raw';
|
|
4
|
+
export type Implementation = InterfaceDefinition | TypeDefinition;
|
|
4
5
|
export declare class InterfaceDefinition {
|
|
6
|
+
readonly generics: string[];
|
|
5
7
|
readonly name: string;
|
|
6
8
|
readonly methods: MethodDefinition[];
|
|
7
9
|
readonly properties: PropertyDefinition[];
|
|
@@ -9,10 +11,9 @@ export declare class InterfaceDefinition {
|
|
|
9
11
|
private _implementations?;
|
|
10
12
|
private _allImplementations?;
|
|
11
13
|
constructor(def: RawInterfaceDefinition);
|
|
12
|
-
get implementations():
|
|
13
|
-
get allImplementations():
|
|
14
|
+
get implementations(): Implementation[];
|
|
15
|
+
get allImplementations(): Implementation[];
|
|
14
16
|
get type(): TypeDefinition;
|
|
15
17
|
toString(): string;
|
|
16
18
|
buildBaseObject(): {};
|
|
17
19
|
}
|
|
18
|
-
export {};
|
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { type RawMethodDefinition
|
|
1
|
+
import { type RawMethodDefinition } from '../raw';
|
|
2
2
|
export declare class MethodDefinition {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
args: {
|
|
3
|
+
protected rawDef: RawMethodDefinition;
|
|
4
|
+
constructor(def: RawMethodDefinition);
|
|
5
|
+
get name(): string;
|
|
6
|
+
get returnType(): import("./TypeDefinition").TypeDefinition;
|
|
7
|
+
get args(): {
|
|
9
8
|
name: string;
|
|
10
|
-
type
|
|
9
|
+
type: import("./TypeDefinition").TypeDefinition;
|
|
11
10
|
isOptional: boolean;
|
|
12
11
|
}[];
|
|
13
|
-
|
|
12
|
+
get isPrivate(): boolean;
|
|
13
|
+
get isStatic(): boolean;
|
|
14
|
+
get isAsync(): boolean;
|
|
14
15
|
}
|
|
15
16
|
export declare function fillMethod(rawMethod: RawMethodDefinition): MethodDefinition;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { type RawPropertyDefinition
|
|
1
|
+
import { type RawPropertyDefinition } from '../raw';
|
|
2
2
|
export declare class PropertyDefinition {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
3
|
+
protected rawDef: RawPropertyDefinition;
|
|
4
|
+
constructor(def: RawPropertyDefinition);
|
|
5
|
+
get name(): string;
|
|
6
|
+
get isOptional(): boolean;
|
|
7
|
+
get isPrivate(): boolean;
|
|
8
|
+
get isStatic(): boolean;
|
|
9
|
+
get accessor(): {
|
|
9
10
|
getter?: {
|
|
10
11
|
isPrivate: boolean;
|
|
11
12
|
};
|
|
@@ -13,6 +14,6 @@ export declare class PropertyDefinition {
|
|
|
13
14
|
isPrivate: boolean;
|
|
14
15
|
};
|
|
15
16
|
};
|
|
16
|
-
|
|
17
|
+
get type(): import("./TypeDefinition").TypeDefinition;
|
|
17
18
|
}
|
|
18
19
|
export declare function fillProperty(rawProperty: RawPropertyDefinition): PropertyDefinition;
|
|
@@ -1,64 +1,10 @@
|
|
|
1
1
|
import { ClassDefinition, PropertyDefinition } from './index';
|
|
2
|
-
export
|
|
3
|
-
arrayElementType?: RawTypeDef;
|
|
4
|
-
literalValue?: unknown;
|
|
5
|
-
typeLiteralMembers?: RawPropertyDefinition[];
|
|
6
|
-
unionMembers?: RawTypeDef[];
|
|
7
|
-
intersectionMembers?: RawTypeDef[];
|
|
8
|
-
isFunction?: boolean;
|
|
9
|
-
tupleMembers?: RawTypeDef[];
|
|
10
|
-
isOptionalInTuple?: boolean;
|
|
11
|
-
isConstructor?: boolean;
|
|
12
|
-
generics?: RawTypeDef[];
|
|
13
|
-
}
|
|
14
|
-
type RawTypeDef = string | RawTypeDefinition;
|
|
15
|
-
export interface RawClassDefinition {
|
|
16
|
-
name: string;
|
|
17
|
-
superClassName?: string;
|
|
18
|
-
implementations?: string[];
|
|
19
|
-
methods?: RawMethodDefinition[];
|
|
20
|
-
properties?: RawPropertyDefinition[];
|
|
21
|
-
}
|
|
22
|
-
export interface RawInterfaceDefinition {
|
|
23
|
-
name: string;
|
|
24
|
-
implementations?: string[];
|
|
25
|
-
methods?: RawMethodDefinition[];
|
|
26
|
-
properties?: RawPropertyDefinition[];
|
|
27
|
-
}
|
|
28
|
-
export interface RawEnumDefinition {
|
|
29
|
-
name: string;
|
|
30
|
-
members: {
|
|
31
|
-
name: string;
|
|
32
|
-
initializer: string | undefined;
|
|
33
|
-
}[];
|
|
34
|
-
}
|
|
35
|
-
export interface RawMethodDefinition {
|
|
2
|
+
export declare const anyType: {
|
|
36
3
|
name: string;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
isAsync?: boolean;
|
|
40
|
-
returnType?: RawTypeDef;
|
|
41
|
-
args?: {
|
|
42
|
-
name: string;
|
|
43
|
-
type?: RawTypeDef;
|
|
44
|
-
isOptional: boolean;
|
|
45
|
-
}[];
|
|
46
|
-
}
|
|
47
|
-
export interface RawPropertyDefinition {
|
|
4
|
+
};
|
|
5
|
+
export declare const nullType: {
|
|
48
6
|
name: string;
|
|
49
|
-
|
|
50
|
-
isPrivate?: boolean;
|
|
51
|
-
isStatic?: boolean;
|
|
52
|
-
type?: RawTypeDef;
|
|
53
|
-
accessor?: {
|
|
54
|
-
getter?: {
|
|
55
|
-
isPrivate: boolean;
|
|
56
|
-
};
|
|
57
|
-
setter?: {
|
|
58
|
-
isPrivate: boolean;
|
|
59
|
-
};
|
|
60
|
-
};
|
|
61
|
-
}
|
|
7
|
+
};
|
|
62
8
|
export interface TypeDefinition {
|
|
63
9
|
name?: string;
|
|
64
10
|
arrayElementType?: TypeDefinition;
|
|
@@ -73,6 +19,7 @@ export interface TypeDefinition {
|
|
|
73
19
|
generics?: TypeDefinition[];
|
|
74
20
|
classDefinition?: ClassDefinition;
|
|
75
21
|
}
|
|
22
|
+
export declare const primitiveTypes: string[];
|
|
76
23
|
export declare function isIgnoredType(type: TypeDefinition): boolean;
|
|
77
24
|
export declare function isPrimitiveType(type: TypeDefinition): type is {
|
|
78
25
|
name: string;
|
|
@@ -101,4 +48,5 @@ export declare function isClassDefinition(type: TypeDefinition): type is {
|
|
|
101
48
|
export declare function hasGenerics(type: TypeDefinition): type is {
|
|
102
49
|
generics: TypeDefinition[];
|
|
103
50
|
};
|
|
104
|
-
export
|
|
51
|
+
export declare function getTypeDefinition(typeName: string, genericArgs?: TypeDefinition[]): TypeDefinition;
|
|
52
|
+
export type EnableReflect = object;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare class ValidateResult {
|
|
2
|
+
readonly success: boolean;
|
|
3
|
+
readonly errorMessage?: string;
|
|
4
|
+
readonly cause?: ValidateResult;
|
|
5
|
+
private constructor();
|
|
6
|
+
static success: ValidateResult;
|
|
7
|
+
static failure(errorMessage: string, cause?: ValidateResult): ValidateResult;
|
|
8
|
+
get errorStackFlow(): string;
|
|
9
|
+
}
|
|
10
|
+
interface FailureResult extends ValidateResult {
|
|
11
|
+
cause?: FailureResult;
|
|
12
|
+
}
|
|
13
|
+
export declare const successResult: ValidateResult;
|
|
14
|
+
export declare const failedResult: typeof ValidateResult.failure;
|
|
15
|
+
export declare function getErrorTraceMessages(failureResult: FailureResult): string;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { TypeDefinition } from './TypeDefinition';
|
|
2
|
+
import { type Dictionary, RawTypeDefinition } from '../raw';
|
|
3
|
+
export declare function fillType(rawType: RawTypeDefinition | string | undefined, genericContext?: Dictionary<TypeDefinition>, genericArgs?: TypeDefinition[]): TypeDefinition;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AnyFunction } from '
|
|
1
|
+
import { type AnyFunction } from '../raw';
|
|
2
2
|
declare const VALIDATE_WRAPPER: unique symbol;
|
|
3
3
|
declare global {
|
|
4
4
|
interface Function {
|
|
@@ -7,4 +7,12 @@ declare global {
|
|
|
7
7
|
}
|
|
8
8
|
export declare const ReflectValidate: MethodDecorator;
|
|
9
9
|
export declare function safeCall(target: object, methodName: string, ...args: unknown[]): unknown;
|
|
10
|
+
export declare function validateFunctionArgument(args: {
|
|
11
|
+
funcName: string;
|
|
12
|
+
optionsObj?: object;
|
|
13
|
+
value?: unknown;
|
|
14
|
+
argName: string;
|
|
15
|
+
type: string;
|
|
16
|
+
optional?: boolean;
|
|
17
|
+
}): void;
|
|
10
18
|
export {};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
export * from './reflect-definitions';
|
|
2
1
|
export * from './reflect-context';
|
|
2
|
+
export * from './TypeDefinition';
|
|
3
3
|
export * from './ClassDefinition';
|
|
4
4
|
export * from './InterfaceDefinition';
|
|
5
5
|
export * from './EnumDefinition';
|
|
6
6
|
export * from './MethodDefinition';
|
|
7
7
|
export * from './PropertyDefinition';
|
|
8
|
-
export * from './
|
|
9
|
-
export * from './
|
|
8
|
+
export * from './ValidateResult';
|
|
9
|
+
export * from './instance-validate';
|
|
10
10
|
export * from './assert-type';
|
|
11
11
|
export * from './function-validate';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Dictionary } from '../raw';
|
|
2
|
+
import { ValidateResult } from './ValidateResult';
|
|
3
|
+
export declare function validateInstance<T extends object>(instance: T, typeName?: string, depth?: number): ValidateResult;
|
|
4
|
+
export declare function validateArray<T extends object>(array: T[], typeName?: string, depth?: number): ValidateResult;
|
|
5
|
+
export declare function validateDictionary<T extends object>(dict: Dictionary<T>, typeName?: string, depth?: number): ValidateResult;
|
|
@@ -1,10 +1,3 @@
|
|
|
1
|
-
export type Dictionary<T> = {
|
|
2
|
-
[key: string]: T;
|
|
3
|
-
};
|
|
4
|
-
type Any = any;
|
|
5
|
-
export type AnyConstructorFunction = new (...args: Any[]) => Any;
|
|
6
|
-
export type AnyFunction = (...args: Any[]) => Any;
|
|
7
1
|
export declare function setValue<T>(target: unknown, field: string | symbol, value: T): void;
|
|
8
2
|
export declare function getValue<T>(target: unknown, field: string | symbol): T | undefined;
|
|
9
3
|
export declare function mapNotNull<T, U>(arr: T[] | undefined, mapper: (item: T) => U | undefined): U[];
|
|
10
|
-
export {};
|
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
import type { AnyConstructorFunction } from './package';
|
|
2
1
|
import { type TypeDefinition } from './index';
|
|
3
2
|
import { ClassDefinition, EnumDefinition, InterfaceDefinition } from './index';
|
|
3
|
+
import type { AnyConstructorFunction } from '../raw';
|
|
4
4
|
export declare const ReflectClass: ClassDecorator;
|
|
5
|
-
export declare const ReflectContext: {
|
|
6
|
-
getClassDefinition: typeof getClassDefinition;
|
|
7
|
-
getInterfaceDefinition: typeof getInterfaceDefinition;
|
|
8
|
-
getEnumDefinition: typeof getEnumDefinition;
|
|
9
|
-
getTypeAliasDefinition: typeof getTypeAliasDefinition;
|
|
10
|
-
};
|
|
11
5
|
export declare function getClassByName(className: string): AnyConstructorFunction | undefined;
|
|
12
|
-
declare function getClassDefinition(arg: AnyConstructorFunction | object | string): ClassDefinition | undefined;
|
|
13
|
-
declare function getInterfaceDefinition(name: string): InterfaceDefinition | undefined;
|
|
14
|
-
declare function getEnumDefinition(name: string): EnumDefinition | undefined;
|
|
15
|
-
declare function
|
|
16
|
-
export {
|
|
6
|
+
export declare function getClassDefinition(arg: AnyConstructorFunction | object | string): ClassDefinition | undefined;
|
|
7
|
+
export declare function getInterfaceDefinition(name: string): InterfaceDefinition | undefined;
|
|
8
|
+
export declare function getEnumDefinition(name: string): EnumDefinition | undefined;
|
|
9
|
+
export declare function getEnumNames(enumName: string): string[];
|
|
10
|
+
export declare function getEnumValues(args: {
|
|
11
|
+
[enumName: string]: Record<string, string | number>;
|
|
12
|
+
}): (string | number)[];
|
|
13
|
+
export declare function getTypeAliasDefinition(name: string): TypeDefinition | undefined;
|
|
14
|
+
export declare function initReflectContext(): void;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { GenericClass } from './GenericClass';
|
|
2
|
+
import { GenericInterface } from './GenericInterface';
|
|
3
|
+
import { ClassDefinition } from './ClassDefinition';
|
|
4
|
+
import { InterfaceDefinition } from './InterfaceDefinition';
|
|
5
|
+
export declare function createInstance<S, T extends S>(constructor: new (...args: unknown[]) => T, proto: S): T;
|
|
6
|
+
export declare function buildPropertiesAndMethods(ret: GenericClass | GenericInterface, proto: ClassDefinition | InterfaceDefinition): void;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type TypeDefinition } from './TypeDefinition';
|
|
2
|
+
import { ValidateResult } from './ValidateResult';
|
|
3
|
+
export declare function validateValue(value: unknown, type: TypeDefinition, depth?: number): ValidateResult;
|
|
4
|
+
export declare function validateClassInstance<T extends object>(instance: T, typeName: string, depth?: number): ValidateResult;
|
|
5
|
+
export declare function safeSetValue(target: object, propName: string, value: unknown): void;
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import type { RawTypeDefinition, TypeDefinition } from './index';
|
|
2
|
-
import { ClassDefinition, EnumDefinition, InterfaceDefinition } from './index';
|
|
3
|
-
import type { AnyConstructorFunction } from './package';
|
|
4
|
-
export declare const anyType: {
|
|
5
|
-
name: string;
|
|
6
|
-
};
|
|
7
|
-
export declare const nullType: {
|
|
8
|
-
name: string;
|
|
9
|
-
};
|
|
10
|
-
export declare function getClassDefinition(arg: AnyConstructorFunction | object | string): ClassDefinition | undefined;
|
|
11
|
-
export declare function getInterfaceDefinition(name: string): InterfaceDefinition | undefined;
|
|
12
|
-
export declare function getEnumDefinition(name: string): EnumDefinition | undefined;
|
|
13
|
-
export declare function getTypeAliasDefinition(name: string): TypeDefinition | undefined;
|
|
14
|
-
export declare function getTypeDefinition(typeName: string): TypeDefinition;
|
|
15
|
-
export declare function getEnumNames(enumName: string): string[];
|
|
16
|
-
export declare function getEnumValues(args: {
|
|
17
|
-
[enumName: string]: Record<string, string | number>;
|
|
18
|
-
}): (string | number)[];
|
|
19
|
-
export declare function fillType(rawType: RawTypeDefinition | string | undefined): TypeDefinition;
|
|
20
|
-
export type EnableReflect = object;
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { type TypeDefinition } from './index';
|
|
2
|
-
import { type Dictionary } from './package';
|
|
3
|
-
declare class ValidateResult {
|
|
4
|
-
readonly success: boolean;
|
|
5
|
-
readonly errorMessage?: string;
|
|
6
|
-
readonly cause?: ValidateResult;
|
|
7
|
-
private constructor();
|
|
8
|
-
static success: ValidateResult;
|
|
9
|
-
static failure(errorMessage: string, cause?: ValidateResult): ValidateResult;
|
|
10
|
-
get errorStackFlow(): string;
|
|
11
|
-
}
|
|
12
|
-
export declare function validateValue(value: unknown, type: TypeDefinition, depth?: number): ValidateResult;
|
|
13
|
-
export declare function validateInstance<T extends object>(instance: T, typeName?: string, depth?: number): ValidateResult;
|
|
14
|
-
export declare function validateArray<T extends object>(array: T[], typeName?: string, depth?: number): ValidateResult;
|
|
15
|
-
export declare function validateDictionary<T extends object>(dict: Dictionary<T>, typeName?: string, depth?: number): ValidateResult;
|
|
16
|
-
interface FailureResult extends ValidateResult {
|
|
17
|
-
cause?: FailureResult;
|
|
18
|
-
}
|
|
19
|
-
export declare function getErrorTraceMessages(failureResult: FailureResult): string;
|
|
20
|
-
export declare function validateFunctionArgument(args: {
|
|
21
|
-
funcName: string;
|
|
22
|
-
optionsObj?: object;
|
|
23
|
-
value?: unknown;
|
|
24
|
-
argName: string;
|
|
25
|
-
type: string;
|
|
26
|
-
optional?: boolean;
|
|
27
|
-
}): void;
|
|
28
|
-
export declare function safeSetValue(target: object, propName: string, value: unknown): void;
|
|
29
|
-
export {};
|