UNPKG

@farris/devkit-vue

Version:
1,702 lines (1,700 loc) 131 kB
(function(global, factory) { typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("vue"), require("axios")) : typeof define === "function" && define.amd ? define(["exports", "vue", "axios"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.FarrisDevkitVue = {}, global.Vue, global.axios)); })(this, function(exports2, vue, axios) { "use strict";var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; const Type = Function; function isType(v) { return typeof v === "function"; } var InjectFlags = /* @__PURE__ */ ((InjectFlags2) => { InjectFlags2[InjectFlags2["Default"] = 0] = "Default"; InjectFlags2[InjectFlags2["Self"] = 1] = "Self"; InjectFlags2[InjectFlags2["SkipSelf"] = 2] = "SkipSelf"; InjectFlags2[InjectFlags2["Optional"] = 4] = "Optional"; return InjectFlags2; })(InjectFlags || {}); var OptionFlags = /* @__PURE__ */ ((OptionFlags2) => { OptionFlags2[OptionFlags2["Optional"] = 1] = "Optional"; OptionFlags2[OptionFlags2["CheckSelf"] = 2] = "CheckSelf"; OptionFlags2[OptionFlags2["CheckParent"] = 4] = "CheckParent"; OptionFlags2[OptionFlags2["Default"] = 6] = "Default"; return OptionFlags2; })(OptionFlags || {}); const EMPTY = []; const IDENT = function(value) { return value; }; const CIRCULAR = IDENT; const MULTI_PROVIDER_FN = function() { return Array.prototype.slice.call(arguments); }; const NEW_LINE = /\n/gm; const NO_NEW_LINE = "ɵ"; const _THROW_IF_NOT_FOUND = {}; const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND; const NG_TEMP_TOKEN_PATH = "ngTempTokenPath"; function stringify(token) { if (typeof token === "string") { return token; } if (Array.isArray(token)) { return "[" + token.map(stringify).join(", ") + "]"; } if (token == null) { return "" + token; } if (token.overriddenName) { return `${token.overriddenName}`; } if (token.name) { return `${token.name}`; } const res = token.toString(); if (res == null) { return "" + res; } const newLineIndex = res.indexOf("\n"); return newLineIndex === -1 ? res : res.substring(0, newLineIndex); } function getClosureSafeProperty(objWithPropertyToExtract) { for (const key in objWithPropertyToExtract) { if (objWithPropertyToExtract[key] === getClosureSafeProperty) { return key; } } throw Error("Could not find renamed property on target object."); } function formatError(text, obj, injectorErrorName, source = null) { text = text && text.charAt(0) === "\n" && text.charAt(1) == NO_NEW_LINE ? text.substr(2) : text; let context = stringify(obj); if (Array.isArray(obj)) { context = obj.map(stringify).join(" -> "); } else if (typeof obj === "object") { const parts = []; for (const key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key]; parts.push( key + ":" + (typeof value === "string" ? JSON.stringify(value) : stringify(value)) ); } } context = `{${parts.join(", ")}}`; } return `${injectorErrorName}${source ? "(" + source + ")" : ""}[${context}]: ${text.replace(NEW_LINE, "\n ")}`; } function staticError(text, obj) { return new Error(formatError(text, obj, "StaticInjectorError")); } function ɵɵdefineInjectable(opts) { return { token: opts.token, providedIn: opts.providedIn || null, factory: opts.factory, value: void 0 }; } const NG_PROV_DEF = getClosureSafeProperty({ ɵprov: getClosureSafeProperty }); getClosureSafeProperty({ ɵinj: getClosureSafeProperty }); const NG_INJECTABLE_DEF = getClosureSafeProperty({ ngInjectableDef: getClosureSafeProperty }); function getOwnDefinition(type, def) { return def && def.token === type ? def : null; } function getInjectableDef(type) { return getOwnDefinition(type, type[NG_PROV_DEF]) || getOwnDefinition(type, type[NG_INJECTABLE_DEF]); } class InjectionToken { constructor(_desc, options) { __publicField(this, "ngMetadataName", "InjectionToken"); __publicField(this, "ɵprov"); this._desc = _desc; this.ɵprov = void 0; if (typeof options === "number") { this.__NG_ELEMENT_ID__ = options; } else if (options !== void 0) { this.ɵprov = ɵɵdefineInjectable({ token: this, providedIn: options.providedIn || "root", factory: options.factory }); } } toString() { return `InjectionToken ${this._desc}`; } } function createInjectionToken(token) { return new InjectionToken(token); } class Injector { } class NullInjector { get(token, notFoundValue = THROW_IF_NOT_FOUND) { if (notFoundValue === THROW_IF_NOT_FOUND) { const error = new Error(`NullInjectorError: No provider for ${stringify(token)}!`); error.name = "NullInjectorError"; throw error; } return notFoundValue; } } const NULL_INJECTOR = new NullInjector(); const __forward_ref__ = getClosureSafeProperty({ __forward_ref__: getClosureSafeProperty }); function resolveForwardRef(type) { return isForwardRef(type) ? type() : type; } function forwardRef(forwardRefFn) { forwardRefFn.__forward_ref__ = forwardRef; forwardRefFn.toString = function() { return stringify(this()); }; return forwardRefFn; } function isForwardRef(fn) { return typeof fn === "function" && fn.hasOwnProperty(__forward_ref__) && fn.__forward_ref__ === forwardRef; } const INJECTOR = new InjectionToken("INJECTOR", -1); const USE_VALUE = getClosureSafeProperty({ provide: String, useValue: getClosureSafeProperty }); let _currentInjector = void 0; function setCurrentInjector(injector) { const former = _currentInjector; _currentInjector = injector; return former; } class StaticInjector { constructor(providers, parent = NULL_INJECTOR, source = null) { __publicField(this, "parent"); __publicField(this, "source"); __publicField(this, "scope"); __publicField(this, "_records"); parent = parent ? parent : NULL_INJECTOR; this.parent = parent; this.source = source; const records = this._records = /* @__PURE__ */ new Map(); records.set(Injector, { token: Injector, fn: IDENT, deps: EMPTY, value: this, useNew: false }); records.set(INJECTOR, { token: INJECTOR, fn: IDENT, deps: EMPTY, value: this, useNew: false }); this.scope = recursivelyProcessProviders(records, providers); } get(token, notFoundValue, flags = InjectFlags.Default) { const records = this._records; let record = records.get(token); if (record === void 0) { const injectableDef = getInjectableDef(token); if (injectableDef) { const providedIn = injectableDef && injectableDef.providedIn; if (providedIn === "any" || providedIn != null && providedIn === this.scope) { records.set( token, record = resolveProvider({ provide: token, useFactory: injectableDef.factory, deps: EMPTY }) ); } } if (record === void 0) { records.set(token, null); } } const lastInjector = setCurrentInjector(this); try { return tryResolveToken(token, record, records, this.parent, notFoundValue, flags); } catch (e) { throw e; } finally { setCurrentInjector(lastInjector); } } toString() { const tokens = []; const records = this._records; records.forEach((v, token) => tokens.push(stringify(token))); return `StaticInjector[${tokens.join(", ")}]`; } } function multiProviderMixError(token) { return staticError("Cannot mix multi providers and regular providers", token); } const INJECTOR_SCOPE = new InjectionToken("Set Injector scope."); function recursivelyProcessProviders(records, provider) { let scope = null; if (provider) { provider = resolveForwardRef(provider); if (Array.isArray(provider)) { for (let i = 0; i < provider.length; i++) { scope = recursivelyProcessProviders(records, provider[i]) || scope; } } else if (typeof provider === "function") { throw staticError("Function/Class not supported", provider); } else if (provider && typeof provider === "object" && provider.provide) { let token = resolveForwardRef(provider.provide); const resolvedProvider = resolveProvider(provider); if (provider.multi === true) { let multiProvider = records.get(token); if (multiProvider) { if (multiProvider.fn !== MULTI_PROVIDER_FN) { throw multiProviderMixError(token); } } else { records.set(token, multiProvider = { token: provider.provide, deps: [], useNew: false, fn: MULTI_PROVIDER_FN, value: EMPTY }); } token = provider; multiProvider.deps.push({ token, options: OptionFlags.Default }); } const record = records.get(token); if (record && record.fn === MULTI_PROVIDER_FN) { throw multiProviderMixError(token); } if (token === INJECTOR_SCOPE) { scope = resolvedProvider.value; } records.set(token, resolvedProvider); } else { throw staticError("Unexpected provider", provider); } } return scope; } function resolveProvider(provider) { const deps = computeDeps(provider); let fn = IDENT; let value = EMPTY; let useNew = false; const provide = resolveForwardRef(provider.provide); if (USE_VALUE in provider) { value = provider.useValue; } else if (provider.useFactory) { fn = provider.useFactory; } else if (provider.useExisting) ; else if (provider.useClass) { useNew = true; fn = resolveForwardRef(provider.useClass); } else if (typeof provide === "function") { useNew = true; fn = provide; } else { throw staticError( "StaticProvider does not have [useValue|useFactory|useExisting|useClass] or [provide] is not newable", provider ); } return { deps, fn, useNew, value }; } function computeDeps(provider) { let deps = EMPTY; const providerDeps = provider.deps; if (providerDeps && providerDeps.length) { deps = []; for (let i = 0; i < providerDeps.length; i++) { const options = OptionFlags.Default; const token = resolveForwardRef(providerDeps[i]); deps.push({ token, options }); } } else if (provider.useExisting) { const token = resolveForwardRef(provider.useExisting); deps = [{ token, options: OptionFlags.Default }]; } else if (!providerDeps && !(USE_VALUE in provider)) { throw staticError("'deps' required", provider); } return deps; } function tryResolveToken(token, record, records, parent, notFoundValue, flags) { try { return resolveToken(token, record, records, parent, notFoundValue, flags); } catch (e) { const path = e[NG_TEMP_TOKEN_PATH] = e[NG_TEMP_TOKEN_PATH] || []; path.unshift(token); if (record && record.value === CIRCULAR) { record.value = EMPTY; } throw e; } } function resolveToken(token, record, records, parent, notFoundValue, flags) { let value; if (record && !(flags & InjectFlags.SkipSelf)) { value = record.value; if (value === CIRCULAR) { throw Error(NO_NEW_LINE + "Circular dependency"); } else if (value === EMPTY) { record.value = CIRCULAR; const useNew = record.useNew; const fn = record.fn; const depRecords = record.deps; let deps = EMPTY; if (depRecords.length) { deps = []; for (let i = 0; i < depRecords.length; i++) { const depRecord = depRecords[i]; const options = depRecord.options; const childRecord = options & OptionFlags.CheckSelf ? records.get(depRecord.token) : void 0; deps.push( tryResolveToken( depRecord.token, childRecord, records, !childRecord && !(options & OptionFlags.CheckParent) ? NULL_INJECTOR : parent, options & OptionFlags.Optional ? null : THROW_IF_NOT_FOUND, InjectFlags.Default ) ); } } record.value = value = useNew ? new fn(...deps) : fn.apply(void 0, deps); } } else if (!(flags & InjectFlags.Self)) { value = parent.get(token, notFoundValue, InjectFlags.Default); } else if (!(flags & InjectFlags.Optional)) { value = NULL_INJECTOR.get(token, notFoundValue); } else { value = NULL_INJECTOR.get(token, typeof notFoundValue !== "undefined" ? notFoundValue : null); } return value; } function INJECTOR_IMPL__PRE_R3__(providers, parent, name) { return new StaticInjector(providers, parent, name); } const INJECTOR_IMPL = INJECTOR_IMPL__PRE_R3__; function createInjector(options, parent) { if (Array.isArray(options)) { return INJECTOR_IMPL(options, parent, ""); } else { return INJECTOR_IMPL(options.providers, options.parent, options.name || ""); } } const ANNOTATIONS = "__annotations__"; const PROP_METADATA = "__prop__metadata__"; function makeMetaCtor(metaFactory) { return function ctor(...args) { if (metaFactory) { const values = metaFactory(...args); for (const propName in values) { this[propName] = values[propName]; } } }; } function makeTypeMetadataDecorator(name, props, parentClass, chainFn, typeFn) { const metaCtor = makeMetaCtor(props); function DecoratorFactory(...args) { if (this instanceof DecoratorFactory) { metaCtor.call(this, ...args); return this; } const annotationInstance = new DecoratorFactory(...args); const typeDecorator = function createTypeDecorator(cls) { typeFn && typeFn(cls, ...args); const annotations = cls.hasOwnProperty(ANNOTATIONS) ? cls[ANNOTATIONS] : Object.defineProperty(cls, ANNOTATIONS, { value: [] })[ANNOTATIONS]; annotations.push(annotationInstance); return cls; }; if (chainFn) { chainFn(typeDecorator); } return typeDecorator; } if (parentClass) { DecoratorFactory.prototype = Object.create(parentClass.prototype); } DecoratorFactory.prototype.ngMetadataName = name; DecoratorFactory.annotationCls = DecoratorFactory; return DecoratorFactory; } function getAllPropMetas(target) { const constructor = target.constructor; let allPropMetas = null; if (constructor.hasOwnProperty(PROP_METADATA)) { allPropMetas = constructor[PROP_METADATA]; } else { allPropMetas = Object.defineProperty(constructor, PROP_METADATA, { value: {} })[PROP_METADATA]; } return allPropMetas; } function getSinglePropMetas(target, propName) { const allPropMetas = getAllPropMetas(target); if (allPropMetas.hasOwnProperty(propName)) { return allPropMetas[propName]; } return []; } function makePropMetadataDecorator(name, metaFactory, parentClass) { const metaCtor = makeMetaCtor(metaFactory); function PropDecoratorFactory(...args) { if (this instanceof PropDecoratorFactory) { metaCtor.apply(this, args); return this; } const decoratorInstance = new PropDecoratorFactory(...args); function PropDecorator(target, propName) { const allPropMetas = getAllPropMetas(target); allPropMetas[propName] = getSinglePropMetas(target, propName); allPropMetas[propName].unshift(decoratorInstance); } return PropDecorator; } if (parentClass) { PropDecoratorFactory.prototype = Object.create(parentClass.prototype); } PropDecoratorFactory.prototype.metadataName = name; PropDecoratorFactory.annotationClass = PropDecoratorFactory; return PropDecoratorFactory; } class PropMetadataReader { /** * 获取所有属性的所有类型元数据 */ static getPropsMetas(constructor) { const propsMetas = constructor[PROP_METADATA]; if (!propsMetas) { return {}; } return propsMetas; } /** * 获取所有属性某一类型的元数据 */ static getPropsMetasByName(constructor, metaName) { const propsMetas = this.getPropsMetas(constructor); if (!propsMetas) { return {}; } const sameNamePropsMetas = {}; Object.keys(propsMetas).forEach((propName) => { const propMetas = propsMetas[propName]; const targetPropMeta = propMetas.find((propMeta) => { return propMeta.metadataName === metaName; }); if (!targetPropMeta) { return; } sameNamePropsMetas[propName] = targetPropMeta; }); return sameNamePropsMetas; } } class Effect { /** * 副作用构造器 * @param effectFunction 副作用方法 */ constructor(effectFunction) { /** * 副作用方法 */ __publicField(this, "internalFunction"); this.effectFunction = effectFunction; this.internalFunction = this.effectFunction; } /** * 执行副作用 * @param change 变更 */ run(change) { this.internalFunction(change); } } class EffectManager { /** * 构造函数 */ constructor() { /** * 副作用集合 */ __publicField(this, "innerEffects", []); } /** * 添加副作用 */ addEffect(effect) { if (this.innerEffects.indexOf(effect) > -1) { return; } this.innerEffects.push(effect); } /** * 删除副作用 */ removeEffect(effect) { this.innerEffects = this.innerEffects.filter((internalEffect) => effect !== internalEffect); } /** * 获取全部副作用 */ getEffects() { return this.innerEffects; } /** * 执行全部副作用 */ trigger(change) { this.innerEffects.forEach((effect) => { effect.run(change); }); } } const _Token = class _Token { static create(redix) { const timestamp = Date.now().valueOf(); let uuid = 0; if (timestamp > _Token.previous) { _Token.previous = timestamp; uuid = timestamp; } else { _Token.previous = _Token.previous + 100; uuid = _Token.previous; } return uuid.toString(redix); } }; __publicField(_Token, "previous", 0); let Token = _Token; const EXCEPTION_HANDLER_TOKEN = new InjectionToken("@farris/exception_handler_token"); const STATE_PROP_META_NAME = "STATE"; const stateMetaFactory = (meta) => { return meta; }; const State = makePropMetadataDecorator(STATE_PROP_META_NAME, stateMetaFactory); const GETTER_PROP_META_NAME = "GETTER"; const getterMetaFactory = (meta) => { return meta; }; const Getter = makePropMetadataDecorator(GETTER_PROP_META_NAME, getterMetaFactory); const ACTION_PROP_META_NAME = "ACTION"; const actionMetaFactory = (meta) => { return meta; }; const Action = makePropMetadataDecorator(ACTION_PROP_META_NAME, actionMetaFactory); const COMMAND_ACTION_PROP_META_NAME = "COMMAND_ACTION"; const commandActionMetaFactory = (meta) => { return meta; }; const CommandAction = makePropMetadataDecorator(COMMAND_ACTION_PROP_META_NAME, commandActionMetaFactory); class PropWrapper { /** * 构造函数 */ constructor(viewModel, propName, propMeta, scope) { /** * 视图模型 */ __publicField(this, "viewModel"); /** * 属性名车给你 */ __publicField(this, "propName"); /** * 属性元数据 */ __publicField(this, "propMeta"); /** * 副作用上下文 */ __publicField(this, "scope"); this.viewModel = viewModel; this.propName = propName; this.propMeta = propMeta; this.scope = scope; } } class StatePropWrapper extends PropWrapper { /** * 构造函数 */ constructor(viewModel, propName, propMeta, scope) { super(viewModel, propName, propMeta, scope); } /** * 包装属性 * @summary * 将状态属性包装为ref,并自动解包 */ wrap() { const viewModel = this.viewModel; const initValue = viewModel[this.propName]; function createAccessor() { const valueRef = vue.ref(initValue); const accessor = { get() { return vue.unref(valueRef); }, set(value) { valueRef.value = value; } }; return accessor; } let cachedAccessor = null; function getCachedAccessor() { if (!cachedAccessor) { cachedAccessor = createAccessor(); } return cachedAccessor; } Object.defineProperty(viewModel, this.propName, { enumerable: true, configurable: true, get() { const accessor = getCachedAccessor(); return accessor.get(); }, set(value) { const accessor = getCachedAccessor(); accessor.set(value); } }); } /** * 注销 */ dispose() { } } class GetterPropWrapper extends PropWrapper { /** * 构造函数 */ constructor(viewModel, propName, propMeta, scope) { super(viewModel, propName, propMeta, scope); } /** * 包装属性 * @summary * 将get方法包装成计算属性 */ wrap() { const viewModel = this.viewModel; const viewModelPrototype = viewModel.constructor.prototype; const getterPropDescriptor = Object.getOwnPropertyDescriptor(viewModelPrototype, this.propName); if (!getterPropDescriptor || !getterPropDescriptor.get) { return; } const getter = getterPropDescriptor.get; const computedGetter = this.scope.run(() => { return vue.computed(() => { return getter.call(viewModel); }); }); Object.defineProperty(viewModel, this.propName, { enumerable: true, configurable: true, get() { return computedGetter; } }); } /** * 注销 */ dispose() { } } class ActionPropWrapper extends PropWrapper { /** * 构造函数 */ constructor(viewModel, propName, propMeta, scope) { super(viewModel, propName, propMeta, scope); } /** * 包装属性 * @summary * 对原始动作进行包装,跟踪方法的执行过程 */ wrap() { const viewModel = this.viewModel; const viewModelPrototype = viewModel.constructor.prototype; const actionPropDescriptor = Object.getOwnPropertyDescriptor(viewModelPrototype, this.propName); if (!actionPropDescriptor || !actionPropDescriptor.value) { return; } const action = actionPropDescriptor.value; const wrappedAction = this.wrapAction(action); Object.defineProperty(viewModel, this.propName, { enumerable: true, configurable: true, get() { return wrappedAction; } }); } /** * 包装动作 */ wrapAction(action) { const viewModel = this.viewModel; const wrappedAction = function() { const args = Array.from(arguments); return action.call(viewModel, ...args); }; return wrappedAction; } /** * 注销 */ dispose() { } } class CommandActionPropWrapper extends ActionPropWrapper { /** * 构造函数 */ constructor(viewModel, propName, propMeta, scope) { super(viewModel, propName, propMeta, scope); } /** * 包装属性 * @summary * 对原始动作进行包装,跟踪方法的执行过程 */ wrap() { const viewModel = this.viewModel; const propMeta = this.propMeta; const commandAction = function(eventParams) { const command = { name: propMeta.name, params: { ...propMeta.params }, eventParams: eventParams ? JSON.parse(JSON.stringify(eventParams)) : null }; return viewModel.dispatch(command); }; const wrappedAction = this.wrapAction(commandAction); Object.defineProperty(viewModel, this.propName, { enumerable: true, configurable: true, get() { return wrappedAction; } }); } /** * 注销 */ dispose() { } } class PropWrapperFactory { /** * 创建属性包装器 */ create(viewModel, propName, propMeta, scope) { let wrapper; switch (propMeta.metadataName) { case STATE_PROP_META_NAME: wrapper = new StatePropWrapper(viewModel, propName, propMeta, scope); break; case GETTER_PROP_META_NAME: wrapper = new GetterPropWrapper(viewModel, propName, propMeta, scope); break; case ACTION_PROP_META_NAME: wrapper = new ActionPropWrapper(viewModel, propName, propMeta, scope); break; case COMMAND_ACTION_PROP_META_NAME: wrapper = new CommandActionPropWrapper(viewModel, propName, propMeta, scope); break; default: throw new Error(`No PropWrapper for ${propMeta.metadataName}`); } return wrapper; } } const PRIMITIVE_FIELD_META_NAME = "PRIMITIVE_FIELD"; const primitiveFieldMetaFactory = (meta) => { return meta; }; const Field = makePropMetadataDecorator(PRIMITIVE_FIELD_META_NAME, primitiveFieldMetaFactory); const ENTITY_FIELD_META_NAME = "ENTITY_FIELD"; const entityFieldMetaFactory = (meta) => { return meta; }; const EntityField = makePropMetadataDecorator(ENTITY_FIELD_META_NAME, entityFieldMetaFactory); const ENTITY_LIST_FIELD_META_NAME = "ENTITY_LIST_FIELD"; const entitylistFieldMetaFactory = (meta) => { return meta; }; const EntityListField = makePropMetadataDecorator(ENTITY_LIST_FIELD_META_NAME, entitylistFieldMetaFactory); var FieldType = /* @__PURE__ */ ((FieldType2) => { FieldType2["Primitive"] = "Primitive"; FieldType2["Entity"] = "Entity"; FieldType2["EntityList"] = "EntityArray"; return FieldType2; })(FieldType || {}); var EntityPathNodeType = /* @__PURE__ */ ((EntityPathNodeType2) => { EntityPathNodeType2["IdValue"] = "IdValue"; EntityPathNodeType2["PropName"] = "PropName"; return EntityPathNodeType2; })(EntityPathNodeType || {}); class EntityPathNode { /** * 构造函数 */ constructor(nodeType, nodeValue) { /** * 类型 */ __publicField(this, "nodeType"); /** * 节点值 */ __publicField(this, "nodeValue"); /** * 上一路径节点 */ __publicField(this, "prevNode"); /** * 下一路径节点 */ __publicField(this, "nextNode"); this.nodeType = nodeType; this.nodeValue = nodeValue; } /** * 获取节点类型 */ getNodeType() { return this.nodeType; } /** * 获取节点值 */ getNodeValue() { return this.nodeValue; } /** * 设置节点值 */ setNodeValue(nodeValue) { this.nodeValue = nodeValue; } /** * 获取上一节点 */ getPrevNode() { return this.prevNode; } /** * 获取下一节点 */ getNextNode() { return this.nextNode; } /** * 设置上一节点 */ setPrevNode(prevNode) { this.prevNode = prevNode; } /** * 设置下一节点 */ setNextNode(nextNode) { this.nextNode = nextNode; } } class EntityPath { /** * 构造函数 */ constructor() { /** * 路径节点集合 */ __publicField(this, "nodes"); this.nodes = []; } /** * 获取路径节点 */ getNodes() { return this.nodes; } /** * 获取第一个节点 */ getFirstNode() { return this.nodes[0]; } /** * 获取最后一个节点 */ getLastNode() { return this.nodes[this.nodes.length - 1]; } /** * 获取父实体路径 */ getParentEntityPath() { const parentEntityPath = new EntityPath(); const parentPathNodes = this.nodes.concat([]); parentPathNodes.pop(); parentPathNodes.forEach((parentPathNode) => { parentEntityPath.appendNode(parentPathNode); }); return parentEntityPath; } /** * 添加节点 */ appendNode(node) { const prevNode = this.nodes.length === 0 ? null : this.nodes[0]; if (prevNode) { prevNode.setNextNode(node); } node.setPrevNode(prevNode); this.nodes.push(node); } /** * 是否和当前路径相等 */ isSame(entityPath) { const targetNodes = entityPath.getNodes(); if (this.nodes.length !== targetNodes.length) { return false; } const isDifferent = this.nodes.some((node, index) => { const targetNode = targetNodes[index]; const isDifferentType = node.getNodeType() !== targetNode.getNodeType(); const isDifferentValue = node.getNodeValue() !== targetNode.getNodeValue(); if (isDifferentType || isDifferentValue) { return true; } }); return !isDifferent; } /** * 是否为当前路径的祖先路径 */ isAncestor(ancestorPath) { const ancestorNodes = ancestorPath.getNodes(); const descendantNodes = this.nodes; if (ancestorNodes.length >= descendantNodes.length) { return false; } const isDifferent = ancestorNodes.some((ancestorNode, index) => { const descendantNode = descendantNodes[index]; const isDifferentType = ancestorNode.getNodeValue() !== descendantNode.getNodeType(); const isDifferentValue = ancestorNode.getNodeValue() !== descendantNode.getNodeValue(); if (isDifferentType || isDifferentValue) { return true; } }); return !isDifferent; } /** * 是否为当前路径的父路径 */ isParent(parentPath) { const ancestorNodes = parentPath.getNodes(); const descendantNodes = this.nodes; if (ancestorNodes.length !== descendantNodes.length - 1) { return false; } return this.isAncestor(parentPath); } /** * 克隆路径 */ clone() { const clonedEntityPath = new EntityPath(); this.nodes.forEach((node) => { const type = node.getNodeType(); const value = node.getNodeValue(); const clonedNode = new EntityPathNode(type, value); clonedEntityPath.appendNode(clonedNode); }); return clonedEntityPath; } /** * 转换为短路径 * @returns */ toShortPath() { return "/" + this.nodes.filter((node) => node.getNodeType() === EntityPathNodeType.PropName).join("/"); } } class EntityPathBuilder { /** * 构造函数 */ constructor(entityState) { /** * 实体状态 */ __publicField(this, "entityState"); this.entityState = entityState; } /** * 构造实体路径 */ build(path, isEntityListPath = false) { if (path instanceof EntityPath) { return path; } this.checkPath(path); const entityList = this.entityState.getEntityList(); const pathArray = this.convertToPathArray(path); const longPathArray = this.convertToLongPath(pathArray, entityList, isEntityListPath); const entityPath = this.buildEntityPath(longPathArray); return entityPath; } /** * 根据长路径数组构造实体路径对象 */ buildEntityPath(longPathArray) { const entityPath = new EntityPath(); longPathArray.forEach((pathItem) => { const isIdPathItem = this.isIdPathItem(pathItem); const nodeType = isIdPathItem ? EntityPathNodeType.IdValue : EntityPathNodeType.PropName; let nodeValue; if (isIdPathItem) { nodeValue = pathItem.slice(1).slice(0, -1); } else { nodeValue = pathItem; } const pathNode = new EntityPathNode(nodeType, nodeValue); entityPath.appendNode(pathNode); }); return entityPath; } /** * 转换为长路径 * 短路径:/childs/grands/assoInfo/name * 长路径:/[id]/childs/[childId]/assoInfo/name */ convertToLongPath(pathArray, entityList, isEntityListPath = false) { if (this.isShortPath(pathArray) === false) { return pathArray; } const pathArrayLen = pathArray.length; const longPathArray = []; if (isEntityListPath && pathArray.length === 0) { return longPathArray; } let currentEntity = entityList.getCurrentEntity(); const currentId = currentEntity.idValue; longPathArray.push(`[${currentId}]`); pathArray.forEach((pathItem, pathIndex) => { const entitySchema = currentEntity.getSchema(); const fieldSchema = entitySchema.getFieldSchemaByName(pathItem); if (!fieldSchema) { throw new Error(`${pathItem} not exist`); } if (fieldSchema.type === FieldType.EntityList) { const childEntityList = currentEntity[pathItem]; const currentChildEntity = childEntityList.getCurrentEntity(); longPathArray.push(pathItem); if (isEntityListPath && pathIndex === pathArrayLen - 1) { return; } longPathArray.push(`[${currentChildEntity.idValue}]`); currentEntity = currentChildEntity; } else if (fieldSchema.type === FieldType.Entity) { longPathArray.push(pathItem); currentEntity = currentEntity[pathItem]; } else { longPathArray.push(pathItem); } }); return longPathArray; } /** * 转换为路径数据 */ convertToPathArray(path) { if (Array.isArray(path)) { return path; } const pathArray = path.split("/").filter((pathItem) => { return pathItem; }); return pathArray; } /** * 检查路径是否合法 */ checkPath(path) { if (!path) { throw new Error("path can not be empty"); } if (Array.isArray(path) === true) { return; } if (typeof path !== "string") { throw new Error("path must be an string or array"); } if (path.startsWith("/") === false) { throw new Error("path must be starts with /"); } } /** * 检查是否为长路径 */ isShortPath(pathArray) { const firstPathItem = pathArray[0]; if (firstPathItem && firstPathItem.startsWith("[")) { return false; } return true; } /** * 检查是否为ID路径片段 */ isIdPathItem(pathItem) { return pathItem.startsWith("["); } } class EntitySchema { /** * 构造函数 */ constructor() { /** * 字段描述集合 */ __publicField(this, "fieldSchemaMap"); /** * 主键值 */ __publicField(this, "idKey"); this.fieldSchemaMap = /* @__PURE__ */ new Map(); } /** * 获取全部字段描述 */ getFieldSchemas() { const fieldSchemas = Array.from(this.fieldSchemaMap.values()); return fieldSchemas; } /** * 根据字段Type获取字段描述 */ getFieldSchemasByType(type) { const fieldSchemas = this.getFieldSchemas(); const targetFieldSchemas = fieldSchemas.filter((fieldSchema) => { return fieldSchema.type === type; }); return targetFieldSchemas; } /** * 根据字段Name获取字段描述 */ getFieldSchemaByName(name) { if (!this.fieldSchemaMap.has(name)) { return; } const targetFieldSchema = this.fieldSchemaMap.get(name); return targetFieldSchema; } /** * 根据字段Path获取字段描述 */ getFieldSchemaByPath(entityPath) { const entityPathNodes = entityPath.getNodes(); let currentEntitySchema = this; let currentFieldSchema; entityPathNodes.forEach((entityPathNode) => { const pathNodeType = entityPathNode.getNodeType(); const pathNodeValue = entityPathNode.getNodeValue(); if (pathNodeType === EntityPathNodeType.IdValue) { return; } currentFieldSchema = currentEntitySchema.getFieldSchemaByName(pathNodeValue); if (currentFieldSchema.type === FieldType.Entity) { currentEntitySchema = currentFieldSchema.entitySchema; } else if (currentFieldSchema.type === FieldType.EntityList) { currentEntitySchema = currentFieldSchema.entitySchema; } }); return currentFieldSchema; } /** * 添加字段信息 */ addFieldSchema(fieldSchema) { this.fieldSchemaMap.set(fieldSchema.name, fieldSchema); } /** * 设置主键字段 */ setIdKey(primaryKey) { this.idKey = primaryKey; } /** * 获取主键字段 */ getIdKey() { return this.idKey; } } class EntitySchemaCreator { /** * 构造函数 */ constructor(entityType) { /** * 实体类型 */ __publicField(this, "entityType"); /** * 实体描述 */ __publicField(this, "entitySchema"); this.entityType = entityType; this.entitySchema = new EntitySchema(); } /** * 创建实体描述 */ create() { this.addFieldSchemas(); return this.entitySchema; } /** * 添加实体 */ addFieldSchemas() { this.addPrimitiveFieldSchemas(); this.addEntityFieldSchemas(); this.addEntityListFieldSchemas(); } /** * 添加简单字段描述 */ addPrimitiveFieldSchemas() { const fieldMetas = PropMetadataReader.getPropsMetasByName(this.entityType, PRIMITIVE_FIELD_META_NAME); Object.keys(fieldMetas).map((propName) => { const fieldMeta = fieldMetas[propName]; const fieldSchema = { type: FieldType.Primitive, name: propName }; this.entitySchema.addFieldSchema(fieldSchema); if (fieldMeta.primary === true) { this.entitySchema.setIdKey(propName); } }); } /** * 添加实体字段描述 */ addEntityFieldSchemas() { const fieldMetas = PropMetadataReader.getPropsMetasByName(this.entityType, ENTITY_FIELD_META_NAME); Object.keys(fieldMetas).map((propName) => { const fieldMeta = fieldMetas[propName]; const fieldSchema = { type: FieldType.Entity, name: propName, entitySchema: createEntitySchema(fieldMeta.entityType) }; this.entitySchema.addFieldSchema(fieldSchema); }); } /** * 添加实体列表字段描述 */ addEntityListFieldSchemas() { const fieldMetas = PropMetadataReader.getPropsMetasByName(this.entityType, ENTITY_LIST_FIELD_META_NAME); Object.keys(fieldMetas).map((propName) => { const fieldMeta = fieldMetas[propName]; const fieldSchema = { type: FieldType.EntityList, name: propName, entitySchema: createEntitySchema(fieldMeta.entityType) }; this.entitySchema.addFieldSchema(fieldSchema); }); } } function createEntitySchema(entityType) { const schemaCreator = new EntitySchemaCreator(entityType); const schema = schemaCreator.create(); return schema; } class EntityNode { constructor() { /** * 父节点 */ __publicField(this, "parentEntityNode"); } /** * 设置父实体节点 */ setParentEntityNode(parentEntityNode) { this.parentEntityNode = parentEntityNode; } /** * 获取父实体节点 */ getParentEntityNode() { return this.parentEntityNode; } } function createEntity(entityType, entityData) { if (!entityType) { throw new Error(`The entityType parameter can't be empty`); } if (!entityData) { throw new Error(`The entityData parameter should be an array`); } const entitySchema = createEntitySchema(entityType); const entity = createEntityBySchema(entitySchema, entityData); return entity; } function createEntityBySchema(entitySchema, entityData) { if (!entitySchema) { throw new Error(`The entitySchema parameter can't be empty`); } if (!entityData) { throw new Error(`The entityData parameter should be an array`); } const entity = new Entity(entitySchema); entity.loadData(entityData); return entity; } function createEntities(entityType, entityDatas) { if (!entityType) { throw new Error(`The entityType parameter can't be empty`); } if (!Array.isArray(entityDatas)) { throw new Error(`The entityDatas parameter should be an array`); } const entitySchema = createEntitySchema(entityType); const entities = createEntitiesBySchema(entitySchema, entityDatas); return entities; } function createEntitiesBySchema(entitySchema, entityDatas) { if (!entitySchema) { throw new Error(`The entitySchema parameter can't be empty`); } if (!Array.isArray(entityDatas)) { throw new Error(`The entityDatas parameter should be an array`); } const entities = entityDatas.map((entityData) => { const entity = createEntityBySchema(entitySchema, entityData); return entity; }); return entities; } class EntityList extends EntityNode { /** * 构造函数 */ constructor(entitySchema) { super(); /** * 实体描述 */ __publicField(this, "entitySchema"); /** * 实体集合 */ __publicField(this, "entities"); /** * 当前实体ID */ __publicField(this, "currentId"); this.entitySchema = entitySchema; this.entities = []; } /** * 加载数据 */ loadData(entityDatas) { if (!Array.isArray(entityDatas)) { throw new Error("The entityDatas parameter should be an array"); } const entities = createEntitiesBySchema(this.entitySchema, entityDatas); this.loadEntities(entities); } /** * 加载实体 */ loadEntities(entities) { this.entities = []; entities.forEach((entity) => { this.appendEntity(entity); }); if (entities.length === 0) { this.currentId = null; } else { const firstEntity = this.entities[0]; this.setCurrentId(firstEntity.idValue); } } /** * 批量追加实体 */ appendEntities(entities) { if (Array.isArray(entities) !== true) { return; } entities.forEach((entity) => { entity.setParentEntityNode(entity); this.entities.push(entity); }); if (this.entities.length > 0) { const lastEntity = this.entities[this.entities.length - 1]; this.setCurrentId(lastEntity.idValue); } } /** * 追加实体 */ appendEntity(entity) { entity.setParentEntityNode(entity); this.entities.push(entity); if (this.entities.length > 0) { const lastEntity = this.entities[this.entities.length - 1]; this.setCurrentId(lastEntity.idValue); } } /** * 获取全部实体 */ getEntities() { return this.entities; } /** * 获取当前实体 */ getCurrentEntity() { if (!this.currentId) { return this.createEmpltyEntity(); } const currentEntity = this.getEntityById(this.currentId); if (!currentEntity) { return this.createEmpltyEntity(); } return currentEntity; } /** * 获取实体 */ setCurrentId(id) { const currentEntity = this.entities.find((entity) => { return entity.idValue === id; }); if (!currentEntity) { this.currentId = null; return; } this.currentId = currentEntity.idValue; } /** * 获取实体 */ getEntityById(id) { const targetEntity = this.entities.find((entity) => { return entity.idValue === id; }); return targetEntity; } /** * 删除实体 */ removeEntityById(id) { const targetIndex = this.entities.findIndex((entity) => { return entity.idValue === id; }); if (targetIndex === -1) { return; } const currentEntity = this.getCurrentEntity(); if (currentEntity.idValue === id) { let newCurrentIndex = null; if (targetIndex === this.entities.length - 1) { newCurrentIndex = targetIndex - 1; } else { newCurrentIndex = targetIndex + 1; } const newCurrentEntity = this.entities[newCurrentIndex]; if (newCurrentEntity) { this.setCurrentId(newCurrentEntity.idValue); } else { this.setCurrentId(null); } } this.entities.splice(targetIndex, 1); } /** * 批量删除实体 */ removeEntityByIds(ids) { if (!Array.isArray(ids)) { return; } ids.forEach((id) => { this.removeEntityById(id); }); } /** * 转换为JSON对象 */ toJSON() { const entityListData = this.entities.map((entity) => { return entity.toJSON(); }); return entityListData; } /** * 创建空实体 */ createEmpltyEntity() { const emptyEntity = createEntityBySchema(this.entitySchema, {}); return emptyEntity; } } function createEntityList(entityType, entityDatas) { if (!entityType) { throw new Error(`The entityType parameter can't be empty`); } if (!Array.isArray(entityDatas)) { throw new Error(`The entityDatas parameter should be an array`); } const entitySchema = createEntitySchema(entityType); const entityList = createEntityListBySchema(entitySchema, entityDatas); return entityList; } function createEntityListBySchema(entitySchema, entityDatas) { if (!entitySchema) { throw new Error(`The entitySchema parameter can't be empty`); } if (!Array.isArray(entityDatas)) { throw new Error(`The entityDatas parameter should be an array`); } const entityList = new EntityList(entitySchema); entityList.loadData(entityDatas); return entityList; } class EntityDataLoader { /** * 构造函数 */ constructor(entity) { /** * 实体 */ __publicField(this, "entity"); /** * 实体描述 */ __publicField(this, "entitySchema"); this.entity = entity; this.entitySchema = entity.getSchema(); } /** * 加载数据 */ load(entityData) { this.loadPrimitiveFields(entityData); this.loadEntityFields(entityData); this.loadEntityListFields(entityData); } /** * 加载简单字段数据 */ loadPrimitiveFields(entityData) { const entity = this.entity; const fieldSchemas = this.entitySchema.getFieldSchemasByType(FieldType.Primitive); fieldSchemas.forEach((fieldSchema) => { const propName = fieldSchema.name; entity[propName] = entityData[propName]; }); } /** * 加载实体字段数据 */ loadEntityFields(entityData) { const entity = this.entity; const fieldSchemas = this.entitySchema.getFieldSchemasByType(FieldType.Entity); fieldSchemas.forEach((fieldSchema) => { const propName = fieldSchema.name; const childEntitySchema = fieldSchema.entitySchema; const childEntityData = entityData[propName] || {}; const childEntity = createEntityBySchema(childEntitySchema, childEntityData); childEntity.setParentEntityNode(entity); entity[propName] = childEntity; }); } /** * 加载实体列表字段数据 */ loadEntityListFields(entityData) { const entity = this.entity; const fieldSchemas = this.entitySchema.getFieldSchemasByType(FieldType.EntityList); fieldSchemas.forEach((fieldSchema) => { const propName = fieldSchema.name; const childEntitySchema = fieldSchema.entitySchema; const childEntityListData = entityData[propName] || []; const childEntityList = createEntityListBySchema(childEntitySchema, childEntityListData); childEntityList.setParentEntityNode(entity); entity[propName] = childEntityList; }); } } class EntityDataPeeker { /** * 构造函数 */ constructor(entity) { /** * 实体 */ __publicField(this, "entity"); /** * 实体描述 */ __publicField(this, "entitySchema"); this.entity = entity; this.entitySchema = entity.getSchema(); } /** * 提取数据 */ peek() { const entityData = {}; this.peekPrimitiveFields(entityData); this.peekEntityFields(entityData); this.peekEntityListFields(entityData); return entityData; } /** * 提取简单字段数据 */ peekPrimitiveFields(entityData) { const entity = this.entity; const fieldSchemas = this.entitySchema.getFieldSchemasByType(FieldType.Primitive); fieldSchemas.forEach((fieldSchema) => { const propName = fieldSchema.name; entityData[propName] = entity[propName]; }); } /** * 提取实体字段数据 */ peekEntityFields(entityData) { const entity = this.entity; const fieldSchemas = this.entitySchema.getFieldSchemasByType(FieldType.Entity); fieldSchemas.forEach((fieldSchema) => { const propName = fieldSchema.name; const childEntity = entity[propName]; const childEntityData = childEntity ? childEntity.toJSON() : {}; entityData[propName] = childEntityData; }); } /** * 提取实体列表字段数据 */ peekEntityListFields(entityData) { const entity = this.entity; const fieldSchemas = this.entitySchema.getFieldSchemasByType(FieldType.EntityList);