@hzab/data-model 2.0.3-alpha.1 → 2.1.0-alpha.1

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/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import D from'axios';import {merge,pickBy,isNil,cloneDeep,each,isString,isNumber,isBoolean,isObject,get,isEmpty}from'lodash-es';import {nanoid}from'nanoid';import Re from'dayjs';import {useRef,useMemo}from'react';function He(t){return !!t&&typeof t=="object"&&t.from==="cache"&&!!t.cache?.promise}var Xt=class{options;cacheTTL=3e3;_cacheMap=new Map;constructor(t={}){let{options:e={}}=t;this.cacheTTL=e.cacheTTL??3e3,this.options=e;}handleAxRequest(t){if(this.hasCache(t)){let n=this.getCache(t);if(n){let o={from:"cache",code:200,key:n.key,config:t,cache:n};return Promise.reject(o)}}this.rmCache(t);let e,s,r=new Promise((n,o)=>{e=n,s=o;});r.catch(()=>{});let i=this.getCacheKey(t),a={key:i,expires:Date.now()+(this.options.cacheTTL??this.cacheTTL),config:t,promise:r,resolve:e,reject:s,settled:false,hasResult:false,clear:()=>{this._cacheMap.delete(i);}};return t.cache=this.addCache(a),t}isFresh(t){return !!t&&typeof t.expires=="number"&&t.expires>Date.now()}hasCache(t){let e=this.getCacheKey(t),s=this._cacheMap.get(e);return this.isFresh(s)?s.settled?!!s.hasResult:true:(this._cacheMap.delete(e),false)}getCache(t){return this.getCacheByKey(this.getCacheKey(t))}getCacheByKey(t){let e=this._cacheMap.get(t);if(this.isFresh(e))return e;e&&this._cacheMap.delete(t);}addCache(t,e=this.options){let{config:s}=t||{},r=t.key||this.getCacheKey(s||{}),i=this._cacheMap.get(r);if(i)return i;let a=e?.cacheTTL??this.cacheTTL,n={...t,key:r,expires:t.expires??Date.now()+a,config:s,promise:t.promise};return this._cacheMap.set(r,n),n}rmCache(t){this._cacheMap.delete(this.getCacheKey(t));}getCacheKey(t={}){let{baseURL:e,method:s,url:r,params:i,data:a}=t;return `${s}:${e}/${r}:${this.stableStringify(i)}:${this.stableStringify(a)}`}stableStringify(t){if(!t||typeof t!="object")return JSON.stringify(t);let e=Object.keys(t).sort().reduce((s,r)=>(s[r]=t[r],s),{});return JSON.stringify(e)}},U="token";function te(t){t.interceptors.response.use(async e=>{let s=e.config?.cache;return s?(s.settled=true,s.hasResult=true,s.resolve(e),await s.promise):e},async e=>{if(He(e))return e.cache.promise;let s=e?.config?.cache;return s&&!s.settled&&(s.settled=true,s.hasResult=false,s.reject(e),s.clear?.()),D.isCancel(e)&&console.info("axios \u8BF7\u6C42\u5DF2\u53D6\u6D88:",e),Promise.reject(e)});}var P=D.create();te(P);te(D);var Ge=new WeakMap,We=new WeakMap;function Yt(t){let e=D.create(t);return te(e),e}var E;function Je(){return E!==void 0?Promise.resolve(E):import('js-cookie').then(t=>E=t?.default||t).catch(()=>(E=null,null))}function Zt(t="",e){let{hasCookie:s=false}=e||{},r=t||"";if(s){let{cookieAttrs:i}=e||{},a=merge({expires:365},i);Je().then(n=>n?.set(U,r,a));}localStorage.setItem(U,r),et(r);}function es(t){let{hasCookie:e=false}=t||{};if(e&&E){let s=E.get(U);if(s)return s}return localStorage.getItem(U)||""}var C={axiosList:[P,D]};function Xe(t){for(let e of t)C.axiosList.includes(e)||C.axiosList.push(e);return C.axiosList}var ts=Xe,Ae;function ss(t){Ae=t;}function Ye(){return Ae}function xe(t,e,s,r,i,a,n){if(!n){r(i,a);return}let o=s.get(t);o||(o=new Map,s.set(t,o));let l=o.get(n);l!=null&&(e==="request"?t.interceptors.request.eject(l):t.interceptors.response.eject(l)),o.set(n,r(i,a));}function rs(t,e,s){let{id:r,...i}=s||{},a=Ce(e,{logPrefix:"Error axios request: ",...i});C.axiosList?.forEach(n=>{xe(n,"request",Ge,(o,l)=>n.interceptors.request.use(o,l),t,a,r);});}function is(t,e,s){let{id:r,...i}=s||{},a=Ce(e,{logPrefix:"Error axios response: ",...i});C.axiosList?.forEach(n=>{xe(n,"response",We,(o,l)=>n.interceptors.response.use(o,l),t,a,r);});}function Ce(t,e){let{replaceErrCb:s,logPrefix:r}=e||{},i=typeof t=="function";return s&&i?t:a=>(console.error(r,a),i?t(a):Promise.reject(a))}function De(t,e){C.axiosList?.forEach(s=>{s.defaults[t]=e;});}function Ze(t,e){C.axiosList?.forEach(s=>{s.defaults.headers[t]=e;});}function as(t=0){De("timeout",t);}function et(t){Ze("Authorization",t);}function ns(t){De("baseURL",t);}function os(){return new AbortController}function ls(){return D.CancelToken.source()}function de(t){return D.isCancel(t)}var us=P,tt="\u672A\u77E5\u9519\u8BEF",st="\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u662F\u5426\u5F00\u542F",W={defaultErrMsg:tt,networkErrMsg:st};function k(){return W}function Ee(t){typeof t.defaultErrMsg=="string"&&t.defaultErrMsg&&(W.defaultErrMsg=t.defaultErrMsg),typeof t.networkErrMsg=="string"&&t.networkErrMsg&&(W.networkErrMsg=t.networkErrMsg);}function cs(t){t&&Ee({defaultErrMsg:t});}function hs(t){t&&Ee({networkErrMsg:t});}function rt(){if(typeof navigator>"u")return true;if(navigator.onLine===false)return false;let t=navigator,e=t.connection||t.mozConnection||t.webkitConnection;return e?!(e?.type==="none"||e.downlink===0||e.effectiveType===null):true}function z(t){if(t instanceof FormData)return t;let e=new FormData;return Object.keys(t)?.forEach(s=>{e.set(s,t[s]);}),e}function q(t){if(!t||!(t instanceof FormData))return t||{};let e={};return t.forEach((s,r)=>{e[r]=s;}),e}var se=class{singletonKey;ctx;query;createApi;getApi;getListApi;getListFunc;updateApi;patchApi;deleteApi;multipleDeleteApi;getListReqMap;getListResMap;getReqMap;getResMap;createReqMap;createResMap;updateReqMap;updateResMap;patchReqMap;patchResMap;deleteReqMap;deleteResMap;multipleDeleteReqMap;multipleDeleteResMap;createMap;updateMap;patchMap;getMap;getListMap;constructor(t={}){this.singletonKey=t.singletonKey,this.ctx=t.ctx||{},this.query=t.query||{},this.createApi=t.createApi,this.getApi=t.getApi,this.getListApi=t.getListApi,this.getListFunc=t.getListFunc,this.updateApi=t.updateApi,this.patchApi=t.patchApi,this.deleteApi=t.deleteApi,this.multipleDeleteApi=t.multipleDeleteApi,this.getListReqMap=t.getListReqMap,this.getListResMap=t.getListResMap,this.getReqMap=t.getReqMap,this.getResMap=t.getResMap,this.createReqMap=t.createReqMap,this.createResMap=t.createResMap,this.updateReqMap=t.updateReqMap,this.updateResMap=t.updateResMap,this.patchReqMap=t.patchReqMap,this.patchResMap=t.patchResMap,this.deleteReqMap=t.deleteReqMap,this.deleteResMap=t.deleteResMap,this.multipleDeleteReqMap=t.multipleDeleteReqMap,this.multipleDeleteResMap=t.multipleDeleteResMap,this.createMap=t.createMap,this.updateMap=t.updateMap,this.patchMap=t.patchMap,this.getMap=t.getMap,this.getListMap=t.getListMap;}configure(t){let{query:e,ctx:s,singletonKey:r,...i}=t;return Object.assign(this,i),s&&(this.ctx=merge({},this.ctx,s)),e&&(this.query=merge({},this.query,e)),this}mergeQuery(t={}){return pickBy(merge({},this.query,t),e=>!isNil(e)&&e!=="")}applyResMap(t,e){return e?e(t):t}async handleInputParams(t,e){let s=q(t),r=t instanceof FormData?{...s}:cloneDeep(s);return e&&(r=await e(r,t)),r}resolveDeleteId(t,e,s){return t?.[e]||t?.params?.[e]||t?.data?.[e]||s?.[e]}async get(t={},e,s){let r=this.mergeQuery(t);this.getReqMap&&(r=await this.getReqMap(r));let i=await this.doGet(r,e,s);if(i==null)return null;let a=this.getMap?this.getMap(i):i;return this.applyResMap(a,this.getResMap)}async getList(t={},e,s){let r=this.mergeQuery(t);this.getListReqMap&&(r=await this.getListReqMap(r));let i;this.getListFunc?i=await this.getListFunc(r):i=await this.doGetList(r,e,s);let a=this.getListMap;return a&&(i.list=i.list.map(n=>a(n))),this.applyResMap(i,this.getListResMap)}async create(t,e,s){let r=await this.doCreate(t,e,s);return this.applyResMap(r,this.createResMap)}async update(t,e,s){let r=await this.doUpdate(t,e,s);return this.applyResMap(r,this.updateResMap)}async patch(t,e,s){let r=await this.doPatch(t,e,s);return this.applyResMap(r,this.patchResMap)}async delete(t={},e,s){let r=cloneDeep(t)||{};this.deleteReqMap&&(r=await this.deleteReqMap(r));let i=await this.doDelete(r,e,s);return this.applyResMap(i,this.deleteResMap)}async multipleDelete(t={},e,s){let r=cloneDeep(t)||{};this.multipleDeleteReqMap&&(r=await this.multipleDeleteReqMap(r));let i=await this.doMultipleDelete(r,e,s);return this.applyResMap(i,this.multipleDeleteResMap)}},b=class extends Error{code;_msg;cause;response;data;constructor(t,e={}){super(t),this.name="ModelError",Object.assign(this,e),this._msg=e._msg??t;}};function ds(t){return t instanceof b}var x=new Map;function re(t,e){if(x.has(t))return x.get(t);let s=e();return x.set(t,s),s}function ie(t){return x.get(t)}function ae(t,e){x.set(t,e);}function ne(t){return x.delete(t)}function oe(t){for(let e of [...x.keys()])e.startsWith(t)&&x.delete(e);}var it={isSuccess(t){return t?.code==200},getData(t){return t?.data},getMessage(t){let e=t;return e?.msg||e?.message||""},normalizeList(t){return t&&Array.isArray(t.content)&&t.pageNumber?{...t,list:t.content,pagination:{current:t.pageNumber,total:t.total}}:t}};function pe(t){return {...it,...t}}var S="http:",at=class _e extends se{responseAdapter;axios;axiosConf;getListAxiosConf;getAxiosConf;createAxiosConf;updateAxiosConf;patchAxiosConf;deleteAxiosConf;multipleDeleteAxiosConf;handleResponse;isResponse;isResponseData;static getInstance(e,s={}){return re(`${S}${e}`,()=>new _e({...s,singletonKey:e}))}static clearInstance(e){return ne(`${S}${e}`)}static clearAllInstances(){oe(S);}constructor(e={}){let s=e.singletonKey;if(s){let r=ie(`${S}${s}`);if(r)return super({}),r}super(e),this.responseAdapter=pe(e.responseAdapter),this.axios=e.axios||Ye()||P,this.axiosConf=e.axiosConf||{},this.getListAxiosConf=e.getListAxiosConf,this.getAxiosConf=e.getAxiosConf,this.createAxiosConf=e.createAxiosConf,this.updateAxiosConf=e.updateAxiosConf,this.patchAxiosConf=e.patchAxiosConf,this.deleteAxiosConf=e.deleteAxiosConf,this.multipleDeleteAxiosConf=e.multipleDeleteAxiosConf,this.handleResponse=e.handleResponse,this.isResponse=!!e.isResponse,this.isResponseData=!!e.isResponseData,s&&ae(`${S}${s}`,this);}configure(e){let{query:s,ctx:r,axiosConf:i,singletonKey:a,responseAdapter:n,isResponse:o,isResponseData:l,handleResponse:c,...u}=e;return super.configure({query:s,ctx:r}),Object.assign(this,u),o!==void 0&&(this.isResponse=!!o),l!==void 0&&(this.isResponseData=!!l),this.handleResponse=c,i&&(this.axiosConf=merge({},this.axiosConf,i)),n&&(this.responseAdapter=pe(n)),this}getApiUrl(e,s={},r=this.ctx,i){let{from:a}=i??{};if(!e){let l=`${a??""} api \u4E0D\u80FD\u4E3A\u7A7A\u3002`;throw console.error(`Error ${l} \u5177\u4F53\u5165\u53C2\uFF1Aapi\u3001record\u3001ctx\u3001opt\uFF1A`,e,s,r,i),new Error(l)}let n=e,o=merge({},s,r);return each(o,(l,c)=>{(isString(l)||isNumber(l)||isBoolean(l))&&(n=n.replace(new RegExp(`:${c}$|:${c}(?=/)`),String(l)));}),n}async doGet(e,s={},r){return new Promise((i,a)=>{let n=this.getApiUrl(this.getApi,e,s,{from:"get"});this.axios.get(n,{...this.axiosConf,...this.getAxiosConf,...r,params:e}).then(o=>{this.handleRes(o,l=>i(l),a);}).catch(o=>this.errorHandler(o,a));})}async doGetList(e,s={},r){return new Promise((i,a)=>{let n=this.getApiUrl(this.getListApi,e,s,{from:"getList"});this.axios.get(n,{...this.axiosConf,...this.getListAxiosConf,...r,params:e}).then(o=>{this.handleRes(o,l=>i(l),a);}).catch(o=>this.errorHandler(o,a));})}async doCreate(e,s,r){let i={...this.axiosConf,...this.createAxiosConf,...r},a=cloneDeep(q(e));this.createReqMap&&(a=await this.createReqMap(a,e));let n={...a},o=this.getApiUrl(this.createApi,a,s,{from:"create"});e instanceof FormData&&(i.headers={...i.headers??{},"Content-Type":"multipart/form-data"},a=z(a));try{let l=await this.axios.post(o,a,i);return await this.settleRes(l,void 0,n)}catch(l){return this.settleErr(l)}}async doUpdate(e,s,r){let i={...this.axiosConf,...this.updateAxiosConf,...r},a=cloneDeep(q(e));this.updateReqMap&&(a=await this.updateReqMap(a,e));let n={...a},o=this.getApiUrl(this.updateApi,a,s,{from:"update"});e instanceof FormData&&(i.headers={...i.headers??{},"Content-Type":"multipart/form-data"},a=z(a));try{let l=await this.axios.put(o,a,i);return await this.settleRes(l,void 0,n)}catch(l){return this.settleErr(l)}}async doPatch(e,s,r){let i={...this.axiosConf,...this.patchAxiosConf,...r},a=cloneDeep(q(e));this.patchReqMap&&(a=await this.patchReqMap(a,e));let n={...a},o=this.getApiUrl(this.patchApi,a,s,{from:"patch"});e instanceof FormData&&(i.headers={...i.headers??{},"Content-Type":"multipart/form-data"},a=z(a));try{let l=await this.axios.patch(o,a,i);return await this.settleRes(l,void 0,n)}catch(l){return this.settleErr(l)}}async doDelete(e,s,r){return new Promise((i,a)=>{let n=this.getApiUrl(this.deleteApi,Object.assign(cloneDeep(e),e.params,e.data),s,{from:"delete"});this.axios.delete(n,{...this.axiosConf,...this.deleteAxiosConf,...r,...e}).then(o=>{this.handleRes(o,l=>i(l),a);}).catch(o=>this.errorHandler(o,a));})}async doMultipleDelete(e,s,r){return new Promise((i,a)=>{let n=this.getApiUrl(this.multipleDeleteApi,Object.assign(cloneDeep(e),e.params,e.data),s,{from:"multipleDelete"});this.axios.delete(n,{...this.axiosConf,...this.multipleDeleteAxiosConf,...r,...e}).then(o=>{this.handleRes(o,l=>i(l),a);}).catch(o=>this.errorHandler(o,a));})}settleRes(e,s,r){return new Promise((i,a)=>{this.handleRes(e,async n=>{n=await(s?s(n):n),i(n);},a,{fallbackData:r});})}settleErr(e){return new Promise((s,r)=>{this.errorHandler(e,r);})}handleRes(e,s,r,i){if(de(e)){r(new b("canceled",{code:"ERR_CANCELED",cause:e,_msg:"canceled"}));return}if(this.isResponse){s(e);return}if(this.isResponseData){s(e?.data??e);return}if(typeof e!="object"){r(new b("response not object",{_msg:"response not object"}));return}let a=u=>u&&"status"in u&&"headers"in u&&"request"in u;if(this.handleResponse){let u=this.handleResponse(e);a(u)&&(u=u.data);let{code:d,data:g}=u,f=this.handleMsg(e);if(d===200){let w=g??{};if(isObject(w)){let N=w;Array.isArray(N.content)&&N.pageNumber&&(N.list=N.content,N.pagination={current:N.pageNumber,total:N.total}),N._msg=f,N._message=f;}s(w);}else {let w=new b(f,{code:d,response:e,_msg:f});Object.assign(w,{_message:f}),r(w);}return}let n=e,o=e;a(o)&&(o=o.data);let l=this.responseAdapter,c=l.getMessage(o,n)||this.handleMsg(e);if(l.isSuccess(o,n)){let u=l.getData(o,n),d=i?.fallbackData,g=(u==null||isObject(u)&&!Array.isArray(u)&&Object.keys(u).length===0)&&d!=null?{...d}:u??{};if(isObject(g)){let f=g;if(l.normalizeList){let w=l.normalizeList(f);w&&typeof w=="object"&&Object.assign(f,w);}f._msg=c,f._message=c,g=f;}s(g);}else {let u=o?.code,d=new b(c,{code:u,response:e,_msg:c});Object.assign(d,{_message:c}),r(d);}}errorHandler(e={},s){let{networkErrMsg:r}=k();if(de(e)){s(new b("canceled",{code:"ERR_CANCELED",cause:e,_msg:"canceled"}));return}if(this.isResponse){s(e);return}if(this.isResponseData){s(e?.data??e);return}let i=e?.response||e;if(i){let n=this.handleMsg(i,{useStatusText:true}),o=new b(n||r,{code:i.status,response:i,_msg:n||r,cause:e});return Object.assign(o,{_message:n||r}),s(o)}let a=new b(r,{_msg:r,cause:e});return Object.assign(a,{_message:r}),s(a)}handleMsg(e,s={useStatusText:false}){let{defaultErrMsg:r}=k(),{useStatusText:i}=s||{},a=e.data&&(e.data.message||e.data.msg)||e.msg||e.message||this.getNetworkErrMsg(e);return !a&&i&&(a=e.statusText),a||r}getNetworkErrMsg(e){let{networkErrMsg:s}=k();return (typeof e=="string"?e:e?.code)==="ERR_NETWORK"?s:rt()?"":s}},nt=at;function ps(t,e){if(typeof t!="string")return t;let{isFullPath:s}=e||{},r=typeof process<"u"&&process.env.WEBPACK_PUBLIC_PATH||".",i=String(r).replace(/^\//,"").replace(/\/$/,"");return s&&typeof location<"u"?`${(location.origin+location.pathname).replace(/[^/]+\.html\/?$/,"").replace(/\/$/,"")}/${i?.replace(/^\./,"")}/${t?.replace(/^\//,"")}`:`${i}/${t?.replace(/^\//,"")}`}var ot=new Set(["pageNum","pageSize","sortKey","sortType","orderByColumn","isAsc"]);function v(t){return Object.entries(t||{}).reduce((e,[s,r])=>(!isNil(r)&&r!==""&&!(Array.isArray(r)&&r.length===0)&&!(typeof r=="object"&&r!==null&&!Array.isArray(r)&&Object.keys(r).length===0)&&(e[s]=r),e),{})}function B(t){if(isNil(t)||typeof t=="number"||typeof t=="boolean")return t;if(t instanceof Date)return t.getTime();if(typeof t=="string"){let e=t.trim();if(e!==""&&/^-?\d+(\.\d+)?$/.test(e)&&!Number.isNaN(Number(e)))return Number(e);if(e.includes("-")||e.includes("/")||e.includes(":")){let s=Re(t);if(s.isValid())return s.valueOf()}}return t}function Q(t,e,s,r){if(typeof t!=typeof e)return typeof t=="number"&&typeof e=="string"&&!Number.isNaN(Number(e))||typeof t=="string"&&typeof e=="number"&&!Number.isNaN(Number(t))?Number(t)===Number(e):false;if(typeof t=="string"&&s){let i=r?t.toLowerCase():t,a=r?String(e).toLowerCase():String(e);return i.includes(a)}return t===e}function lt(t,e){let{$gt:s,$lt:r,$gte:i,$lte:a}=e,n=true,o=B(t),l=c=>B(c);return s!==void 0&&(n=n&&o>l(s)),r!==void 0&&(n=n&&o<l(r)),i!==void 0&&(n=n&&o>=l(i)),a!==void 0&&(n=n&&o<=l(a)),n}var ut=(t,e,s)=>{let{fuzzy:r=false,ignoreCase:i=false,searchFields:a}=s;return Object.entries(e).every(([n,o])=>{if(a&&a.length>0&&typeof o=="string"&&r&&!a.includes(n)){let c=get(t,n);return Q(c,o,false,i)}let l=get(t,n);return isNil(l)?isNil(o):Array.isArray(o)?o.some(c=>Q(l,c,r,i)):typeof o=="object"&&o!==null&&!Array.isArray(o)?lt(l,o):Q(l,o,r,i)})};function J(t,e){if(typeof e=="string")return get(t,e);if(!isNil(e)&&typeof e=="object"){let s=get(t,e.path);if(e.type==="date"&&s){let r=Re(s);s=r.isValid()?r.valueOf():0;}return typeof e.customFormat=="function"&&(s=e.customFormat(s,t)),s}}function ct(t,e){let s=B(t),r=B(e);return s===r?0:s==null?1:r==null?-1:s>r?1:s<r?-1:0}function ht(t){return Array.isArray(t)?t:t?[t]:[]}function Ie(t,e,s,r,i=0){for(let a=i;a<s.length;a+=1){let n=s[a],o=typeof n=="string"?n:n.path,l="desc";if(typeof r=="string"?l=r:r&&typeof r=="object"&&(l=r[o]||"desc"),typeof n=="object"&&typeof n.customCompare=="function"){let g=n.customCompare(t,e,{paths:s,pathIdx:a,path:o,sortType:l});if(g!==0)return l==="asc"?g:-g;continue}let c=J(t,n),u=J(e,n),d=ct(c,u);if(d!==0)return l==="asc"?d:-d}return 0}function X(t,e,s){let r=cloneDeep(t);if(!e&&s===void 0)return r;let i=ht(e);return i.length===0||r.sort((a,n)=>Ie(a,n,i,s)),r}function dt(t){return typeof t=="boolean"?t?"asc":"desc":t}function pt(t={}){let{pageNum:e,pageSize:s,sortKey:r,sortType:i,orderByColumn:a,isAsc:n,...o}=t,l=v(o);return Object.keys(l).forEach(c=>{ot.has(c)&&delete l[c];}),l}function ft(t,e=1,s=10){let r={current:Math.max(1,Number(e)||1),pageSize:Math.max(1,Number(s)||10),total:t.length},i=r.current??1,a=r.pageSize??10,n=(i-1)*a,o=n+a;return {list:cloneDeep(t.slice(n,o)),pagination:{...r}}}function I(t,e,s={}){return (s.matcher||ut)(t,v(e),s)}function le(t={}){let e=s=>({fuzzy:s?.fuzzy??t.fuzzy,ignoreCase:s?.ignoreCase??t.ignoreCase,searchFields:s?.searchFields??t.searchFields,matcher:s?.matcher??t.matcher});return {match(s,r,i){return I(s,r,e(i))},filter(s,r,i){let a=e(i),n=v(r);return isEmpty(n)?s:s.filter(o=>I(o,n,a))},sort(s,r,i){return X(s,r,i)},run(s,r={},i){let a=e(i),{pageNum:n=1,pageSize:o=10,sortKey:l,sortType:c,orderByColumn:u,isAsc:d}=r,g=pt(r),f=s;isEmpty(g)||(f=s.filter($e=>I($e,g,a)));let w=X(f,l??u,dt(c??d)),N=ft(w,n,o);return N.pagination.total=f.length,N}}}var fs=le(),y={SUC:200,NOT_FOUND:404,NOT_FOUNT:404,ERR:500,ERR_INPUT_ID:501},mt=class{_idKey;_list;constructor(t={}){let{idKey:e="id",list:s}=t;this._idKey=e||"id",this._list=s?cloneDeep(s):[];}get idKey(){return this._idKey}findItemById(t){if(this._isInvalidId(t))return null;let{_idKey:e}=this,s=this._list.find(r=>r[e]===t);return s?cloneDeep(s):null}findItem(t={},e={}){let{fuzzy:s=false,ignoreCase:r=false,searchFields:i,matcher:a}=e,n=t[this._idKey];if(!this._isInvalidId(n))return this.findItemById(n);let o=v(t);if(Object.keys(o).length===0)return null;let l={fuzzy:s,ignoreCase:r,searchFields:i,matcher:a},c=this._list.find(u=>I(u,o,l));return c?cloneDeep(c):null}findListByQuery(t={},e={}){let{fuzzy:s=true,ignoreCase:r=false,searchFields:i,matcher:a}=e,n=le({fuzzy:s,ignoreCase:r,searchFields:i,matcher:a});return Promise.resolve(n.run(this._list,t))}getSortList(t,e,s){let r=s||this._list;return X(r,t,e)}compareData(t,e,s){let{paths:r,pathIdx:i=0,sortType:a="desc"}=s;return Ie(t,e,r,a,i)}handleValByKey(t,e){return J(t,e)}findAllList(){return cloneDeep(this._list)}getCount(){return this._list.length}pushItem(t){let e=Array.isArray(t),s=e?t:[t],r=[];return s.forEach(i=>{let a=cloneDeep(i);this._setId(a),this._setCreateTime(a),this._list.push(a),r.push(a);}),e?r:r[0]}unshiftItem(t){let e=cloneDeep(t);return this._setId(e),this._setCreateTime(e),this._list.unshift(e),e}replaceItem(t){let{_idKey:e,_list:s}=this,r=t[e];if(this._isInvalidId(r))return y.ERR_INPUT_ID;let i=s.findIndex(a=>a[e]===r);return i<0?y.NOT_FOUND:(s.splice(i,1,cloneDeep(t)),this._setUpdateTime(s[i]),s[i])}updateItemValue(t){let{_idKey:e,_list:s}=this,r=t[e];if(this._isInvalidId(r))return y.ERR_INPUT_ID;let i=s.findIndex(n=>n[e]===r);if(i<0)return y.NOT_FOUND;let a=s[i];return Object.keys(t).forEach(n=>{n!==e&&(a[n]=t[n]);}),this._setUpdateTime(a),a}delItem(t){let{_idKey:e,_list:s}=this;if(this._isInvalidId(t))return y.ERR_INPUT_ID;let r=s.findIndex(i=>i[e]===t);return r<0?y.NOT_FOUND:(s.splice(r,1),y.SUC)}clearAll(){return this._list=[],y.SUC}deleteItems(t){let e=0;return t.forEach(s=>{this.delItem(s)===y.SUC&&e++;}),e}isEmpty(){return this._list.length===0}slice(t,e){return cloneDeep(this._list.slice(t,e))}_isItemMatchQuery(t,e,s={}){return I(t,e,s)}_filterEmptyQuery(t){return v(t)}_isInvalidId(t){return isNil(t)||t===""}_setId(t){return isObject(t)&&this._isInvalidId(t[this._idKey])&&(t[this._idKey]=nanoid()),t}_setCreateTime(t){isObject(t)&&this._isInvalidId(t.createTime)&&(t.createTime=Date.now());}_setUpdateTime(t){isObject(t)&&(t.updateTime=Date.now());}},yt=mt,L="array:",fe={404:"\u672A\u627E\u5230\u5BF9\u5E94\u5B50\u9879",501:"\u672A\u4F20\u5165\u8868\u5355 id"};function gt(t){return new Promise(e=>{setTimeout(()=>{e();},t);})}function me(t){return typeof t=="number"}var ms=class Oe extends se{store;_arrOptions;delayMs;static getInstance(e,s={}){return re(`${L}${e}`,()=>new Oe({...s,singletonKey:e}))}static clearInstance(e){return ne(`${L}${e}`)}static clearAllInstances(){oe(L);}constructor(e={}){let s=e.singletonKey;if(s){let r=ie(`${L}${s}`);if(r)return super({}),this.store=r.store,this._arrOptions=r._arrOptions,this.delayMs=r.delayMs,r}super(e),this.store=new yt(e),this._arrOptions=e.arrOptions,this.delayMs=e.delayMs??0,s&&ae(`${L}${s}`,this);}configure(e){let{query:s,ctx:r,list:i,idKey:a,singletonKey:n,arrOptions:o,delayMs:l,...c}=e;return super.configure({query:s,ctx:r,...c}),o&&(this._arrOptions=merge({},this._arrOptions,o)),l!=null&&(this.delayMs=l),this}async delay(){this.delayMs<=0||await gt(this.delayMs);}rejectCode(e){let s=fe[e]||"\u672A\u77E5\u9519\u8BEF";throw new b(s,{code:e,_msg:s})}async doGet(e,s,r){return this.store.findItem(e,this._arrOptions)}async doGetList(e,s,r){return this.store.findListByQuery(e,this._arrOptions)}async doCreate(e,s,r){let i=await this.handleInputParams(e,this.createReqMap);await this.delay();let a=this.store.pushItem(i);return cloneDeep(a)}async doUpdate(e,s,r){let i=await this.handleInputParams(e,this.updateReqMap);await this.delay();let a=this.store.replaceItem(i);return me(a)&&this.rejectCode(a),cloneDeep(a)}async doPatch(e,s,r){let i=await this.handleInputParams(e,this.patchReqMap),a=this.store.updateItemValue(i);return me(a)&&this.rejectCode(a),cloneDeep(a)}async doDelete(e,s,r){return await this.delay(),new Promise((i,a)=>{let n=this.resolveDeleteId(e,this.store.idKey,s),o=this.store.delItem(n);this.handleRes(o,i,a);})}async doMultipleDelete(e,s,r){let i=this.resolveDeleteId(e,this.store.idKey,s);if(typeof i=="string"&&(i=i.split(",")),!Array.isArray(i))throw new b("\u672A\u4F20\u5165\u8868\u5355 id",{code:y.ERR_INPUT_ID,_msg:"\u672A\u4F20\u5165\u8868\u5355 id"});let a=[],n=[];if(i.forEach(o=>{try{this.store.delItem(o)===y.SUC?a.push(o):n.push(o);}catch(l){console.error("error",l),n.push(o);}}),a.length===0)throw new b("\u6279\u91CF\u5220\u9664\u5168\u90E8\u5931\u8D25",{code:y.ERR,_msg:"\u6279\u91CF\u5220\u9664\u5168\u90E8\u5931\u8D25",data:{failList:n}});return {sucList:a,failList:n}}handleRes(e,s,r,i){let{resMap:a,payload:n}=i||{};if(e===y.SUC){let o=n?cloneDeep(n):{};a&&(o=a(o)),s(o);}else {let o=fe[e]||"\u672A\u77E5\u9519\u8BEF";r(new b(o,{code:e,_msg:o}));}}},m={...y,CONFLICT:409},bt={[m.NOT_FOUND]:"\u672A\u627E\u5230\u5BF9\u5E94\u5B50\u9879",[m.ERR]:"\u672A\u77E5\u9519\u8BEF",[m.ERR_INPUT_ID]:"\u672A\u4F20\u5165\u8868\u5355 id",[m.CONFLICT]:"\u8BB0\u5F55\u5DF2\u5B58\u5728\uFF08\u4E3B\u952E\u51B2\u7A81\uFF09"},Y=class extends b{constructor(t,e,s){let r=e||bt[t]||"\u672A\u77E5\u9519\u8BEF";super(r,{code:t,_msg:r,data:s}),this.name="IdbModelError";}};function ys(t){return t instanceof Y}function ye(t){if(!t||typeof t!="object")return false;let e=t;return e.name==="ConstraintError"?true:typeof e.message=="string"&&/key already exists|constraint/i.test(e.message)}var ve="__files",j=new Map;function Fe(t){let e=j.get(t);return e||(e={schemas:new Map,openChain:Promise.resolve(),connection:null},j.set(t,e)),e}function Se(t){let e=Fe(t.dbName),s={storeName:t.storeName,idKey:t.idKey||"id",indexes:t.indexes?[...t.indexes]:[],filesStoreName:t.filesStoreName||ve,minVersion:t.version??1},r=e.schemas.get(s.storeName);if(r){let i=new Map;r.indexes.forEach(a=>i.set(a.name,a)),s.indexes.forEach(a=>i.set(a.name,a)),s.indexes=[...i.values()],s.minVersion=Math.max(r.minVersion,s.minVersion),s.idKey=s.idKey||r.idKey;}return e.schemas.set(s.storeName,s),s}function wt(t){return new Promise((e,s)=>{t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error??new Error("IndexedDB request failed"));})}function Nt(t){return new Promise((e,s)=>{t.oncomplete=()=>e(),t.onerror=()=>s(t.error??new Error("IndexedDB transaction failed")),t.onabort=()=>s(t.error??new Error("IndexedDB transaction aborted"));})}function Mt(t,e,s){let r;t.objectStoreNames.contains(s.storeName)?r=e.objectStore(s.storeName):r=t.createObjectStore(s.storeName,{keyPath:s.idKey,autoIncrement:false});for(let i of s.indexes)r.indexNames.contains(i.name)||r.createIndex(i.name,i.keyPath,{unique:!!i.unique});t.objectStoreNames.contains(s.filesStoreName)||t.createObjectStore(s.filesStoreName,{keyPath:"id",autoIncrement:false});}function Rt(t,e,s){let r=j.get(s);if(r)for(let i of r.schemas.values())Mt(t,e,i);}function At(t,e){return !(!t.objectStoreNames.contains(e.storeName)||!t.objectStoreNames.contains(e.filesStoreName))}function xt(t,e){if(!t.objectStoreNames.contains(e.storeName))return false;try{let s=t.transaction(e.storeName,"readonly"),r=s.objectStore(e.storeName);for(let i of e.indexes)if(!r.indexNames.contains(i.name)){try{s.abort();}catch{}return !1}return !0}catch{return false}}function V(t,e){for(let s of e.schemas.values())if(!At(t,s)||!xt(t,s))return false;return e.schemas.size>0}function Ct(t){let e=1;for(let s of t.schemas.values())e=Math.max(e,s.minVersion);return e}function ge(t,e){return new Promise((s,r)=>{let i=indexedDB.open(t,e);i.onupgradeneeded=()=>{let a=i.result,n=i.transaction;n&&Rt(a,n,t);},i.onsuccess=()=>{let a=i.result;a.onversionchange=()=>{a.close();let n=j.get(t);n&&(n.connection=null);},s(a);},i.onerror=()=>{r(i.error??new Error(`Failed to open IndexedDB "${t}"`));},i.onblocked=()=>{};})}function Le(t){Se(t);let e=Fe(t.dbName),s=async()=>{if(e.connection){try{let a=await e.connection;if(V(a,e))return a;a.close();}catch{}e.connection=null;}let i=(async()=>{let a=Ct(e),n=await ge(t.dbName,a),o=0;for(;!V(n,e)&&o<32;){let l=n.version+1;n.close(),n=await ge(t.dbName,l),o+=1;}if(!V(n,e))throw n.close(),new Error(`IndexedDB "${t.dbName}" failed to satisfy registered stores after auto-upgrade`);return n})();e.connection=i;try{return await i}catch(a){throw e.connection=null,a}},r=e.openChain.then(s,s);return e.openChain=r.then(()=>{},()=>{}),r}async function R(t,e,s,r){let i=await Le(t),a=Array.isArray(s)?s:[s],n=i.transaction(a,e),o={};for(let l of a)o[l]=n.objectStore(l);try{let l=await r(o,n);return await Nt(n),l}catch(l){try{n.abort();}catch{}throw l}}function p(t){return wt(t)}async function Dt(t){let e=j.get(t);if(!e?.connection)return;let s=e.connection;e.connection=null;try{(await s).close();}catch{}}function ue(t){return typeof t=="object"&&t!==null&&typeof t.fileId=="string"&&typeof t.name=="string"&&typeof t.size=="number"}function Te(t){return typeof Blob<"u"&&t instanceof Blob}function Et(t){if(!t||typeof t!="object"||Array.isArray(t)||Te(t)||ue(t)||t instanceof Date)return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function _t(t){return {fileId:t.id,name:t.name,type:t.type,size:t.size}}async function It(t){return typeof t.arrayBuffer=="function"?t.arrayBuffer():new Response(t).arrayBuffer()}function Ot(t){return {id:t.id,blob:new Blob([t.buffer],{type:t.type||"application/octet-stream"}),name:t.name,type:t.type,size:t.size,createdAt:t.createdAt,storeName:t.storeName}}async function vt(t,e){if(!e)return null;let s=await p(t.get(e));return s?Ot(s):null}async function Ft(t,e){e&&await p(t.delete(e));}async function je(t,e){for(let s of e)await Ft(t,s);}function F(t,e=new Set){return ue(t)?(e.add(t.fileId),[...e]):Array.isArray(t)?(t.forEach(s=>F(s,e)),[...e]):(t&&typeof t=="object"&&Object.values(t).forEach(s=>F(s,e)),[...e])}function St(t,e,s){let r=t;for(let i=0;i<e.length-1;i+=1)r=r[e[i]];r[e[e.length-1]]=s;}async function Z(t,e,s){if(Te(t)){let r=e.length?String(e[e.length-1]):"file",i=typeof File<"u"&&t instanceof File?t.name:r,a=t.type||"application/octet-stream",n=await It(t);return s.push({path:[...e],buffer:n,name:i,type:a,size:t.size}),null}if(ue(t))return {...t};if(Array.isArray(t)){let r=[];for(let i=0;i<t.length;i+=1)r.push(await Z(t[i],[...e,i],s));return r}if(Et(t)){let r={};for(let[i,a]of Object.entries(t))r[i]=await Z(a,[...e,i],s);return r}return t}async function H(t){let e=[];return {data:await Z(t,[],e),pending:e}}async function G(t,e,s,r){let i=t;for(let a of e){let n={id:nanoid(),buffer:a.buffer,name:a.name,type:a.type,size:a.size,createdAt:Date.now(),storeName:r};await p(s.put(n)),St(i,a.path,_t(n));}return i}async function be(t,e,s){if(!e)return;let r=new Set(F(e)),i=new Set(F(s)),a=[...r].filter(n=>!i.has(n));await je(t,a);}var Lt=new Set(["pageNum","pageSize","sortKey","sortType"]);function qe(t){if(!t||typeof t!="object"||Array.isArray(t))return false;let e=t;return "$gt"in e||"$lt"in e||"$gte"in e||"$lte"in e}function Ke(t){let{$gt:e,$lt:s,$gte:r,$lte:i}=t,a=r!==void 0||e!==void 0,n=i!==void 0||s!==void 0,o=r!==void 0?r:e,l=i!==void 0?i:s,c=r===void 0&&e!==void 0,u=i===void 0&&s!==void 0;return a&&n?IDBKeyRange.bound(o,l,c,u):a?IDBKeyRange.lowerBound(o,c):n?IDBKeyRange.upperBound(l,u):null}function we(t,e,s){if(e==null||e===""||Array.isArray(e))return false;if(qe(e))return Ke(e)!=null;let r=s.fuzzy??true;return typeof e=="string"&&r?!!(s.searchFields&&s.searchFields.length>0&&!s.searchFields.includes(t)):typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ne(t,e,s,r){if(qe(e)){let i=Ke(e);return i?{source:s,indexName:r,keyPath:t,query:i}:null}return {source:s,indexName:r,keyPath:t,query:e}}function Tt(t,e={}){let s=e.idKey||"id",r=e.idbOptions||{},i={};if(Object.entries(t||{}).forEach(([n,o])=>{Lt.has(n)||o==null||o===""||(i[n]=o);}),s in i&&we(s,i[s],r))return Ne(s,i[s],"store");let a=[...e.indexes||[]].sort((n,o)=>+!!o.unique-+!!n.unique);for(let n of a){if(typeof n.keyPath!="string")continue;let o=n.keyPath;if(o in i&&we(o,i[o],r))return Ne(o,i[o],"index",n.name)}return null}async function jt(t,e,s){if(!e)return await s(t.getAll());if(e.source==="store")return await s(t.getAll(e.query));if(!e.indexName||!t.indexNames.contains(e.indexName))return await s(t.getAll());let r=t.index(e.indexName);return await s(r.getAll(e.query))}function qt(t,e={},s={}){let{fuzzy:r=true,ignoreCase:i=false,searchFields:a,matcher:n}=s;return le({fuzzy:r,ignoreCase:i,searchFields:a,matcher:n}).run(t,e)}function Kt(t){return `data-model:idb:${t}`}function Me(t){return `__idb_sync__:${t}`}function ee(t,e){t.forEach(s=>{try{s(e);}catch{}});}var O=new Map;function Ut(t,e,s){let r=O.get(t);r||(r=new Map,O.set(t,r));let i=r.get(e);return i||(i=new Set,r.set(e,i)),i.add(s),()=>{i.delete(s),i.size===0&&r.delete(e),r.size===0&&O.delete(t);}}function Bt(t,e){let s=O.get(t);if(s)for(let[r,i]of s)r!==e.tabId&&ee(i,e);}function $t(t,e){let s=O.get(t);s&&(s.delete(e),s.size===0&&O.delete(t));}function Pt(t,e={}){if(e.enabled===false)return null;let s=e.channelName||Kt(t),r=e.storageFallback!==false,i=nanoid(),a=new Set,n=null;if(typeof BroadcastChannel<"u")try{n=new BroadcastChannel(s),n.onmessage=c=>{let u=c.data;!u||u.v!==1||u.tabId===i||u.dbName&&u.dbName!==t||ee(a,u);};}catch{n=null;}let o=c=>{if(!(c.key!==Me(s)||!c.newValue))try{let u=JSON.parse(c.newValue);if(!u||u.v!==1||u.tabId===i||u.dbName&&u.dbName!==t)return;ee(a,u);}catch{}},l=!n;return l&&r&&typeof window<"u"&&window.addEventListener("storage",o),{tabId:i,channelName:s,publish(c){let u={v:1,tabId:i,ts:c.ts??Date.now(),dbName:c.dbName,storeName:c.storeName,action:c.action,ids:c.ids};if(n){try{n.postMessage(u);}catch{}return}if(r&&typeof localStorage<"u")try{localStorage.setItem(Me(s),JSON.stringify(u));}catch{}Bt(s,u);},subscribe(c){a.add(c);let u=l?Ut(s,i,c):null;return ()=>{a.delete(c),u?.();}},close(){if(a.clear(),$t(s,i),n){try{n.close();}catch{}n=null;}typeof window<"u"&&window.removeEventListener("storage",o);}}}var T="idb:";function kt(t){return t===false?{enabled:false}:t===true||t==null?{enabled:true}:{enabled:true,...t}}var gs=class Ue extends se{dbName;storeName;filesStoreName;version;idKey;indexes;idbOptions;objectUrls=new Set;syncBus=null;remoteListeners=new Set;static getInstance(e,s){return re(`${T}${e}`,()=>new Ue({...s,singletonKey:e}))}static clearInstance(e){return ne(`${T}${e}`)}static clearAllInstances(){oe(T);}constructor(e){let s=e.singletonKey;if(s){let i=ie(`${T}${s}`);if(i)return super({}),this.dbName=i.dbName,this.storeName=i.storeName,this.filesStoreName=i.filesStoreName,this.version=i.version,this.idKey=i.idKey,this.indexes=i.indexes,this.idbOptions=i.idbOptions,this.objectUrls=i.objectUrls,this.syncBus=i.syncBus,this.remoteListeners=i.remoteListeners,i}if(!e?.dbName)throw new Error("IndexedDbDataModel requires dbName");if(!e?.storeName)throw new Error("IndexedDbDataModel requires storeName");super(e),this.dbName=e.dbName,this.storeName=e.storeName,this.filesStoreName=e.filesStoreName||ve,this.version=e.version??1,this.idKey=e.idKey||"id",this.indexes=e.indexes,this.idbOptions=e.idbOptions||{},Se(this.dbOpt);let r=kt(e.sync);this.syncBus=Pt(this.dbName,r),this.syncBus&&this.syncBus.subscribe(i=>{i.storeName===this.storeName&&this.remoteListeners.forEach(a=>{try{a(i);}catch{}});}),s&&ae(`${T}${s}`,this);}configure(e){let{query:s,ctx:r,dbName:i,storeName:a,indexes:n,version:o,filesStoreName:l,singletonKey:c,idbOptions:u,...d}=e;return super.configure({query:s,ctx:r,...d}),u&&(this.idbOptions=merge({},this.idbOptions,u)),this}publishSync(e,s){this.syncBus?.publish({dbName:this.dbName,storeName:this.storeName,action:e,ids:s});}subscribe(e){return this.remoteListeners.add(e),()=>{this.remoteListeners.delete(e);}}get dbOpt(){return {dbName:this.dbName,version:this.version,storeName:this.storeName,idKey:this.idKey,indexes:this.indexes,filesStoreName:this.filesStoreName}}rejectCode(e,s,r){throw new Y(e,s,r)}async ready(){return Le(this.dbOpt)}async close(){this.revokeAllFileUrls(),this.remoteListeners.clear(),this.syncBus?.close(),this.syncBus=null,await Dt(this.dbName);}async doGet(e,s,r){let i=e[this.idKey],a;if(!isNil(i)&&i!=="")a=await R(this.dbOpt,"readonly",this.storeName,async n=>await p(n[this.storeName].get(i))||null);else {let n=v(e);a=(await R(this.dbOpt,"readonly",this.storeName,async o=>await p(o[this.storeName].getAll()))).find(o=>I(o,n,{fuzzy:false,ignoreCase:this.idbOptions.ignoreCase,searchFields:this.idbOptions.searchFields,matcher:this.idbOptions.matcher}))||null;}return a?cloneDeep(a):null}async doGetList(e,s,r){let i=Tt(e,{idKey:this.idKey,indexes:this.indexes,idbOptions:this.idbOptions}),a=await R(this.dbOpt,"readonly",this.storeName,async n=>jt(n[this.storeName],i,p));return qt(a,e,{fuzzy:this.idbOptions.fuzzy??true,ignoreCase:this.idbOptions.ignoreCase,searchFields:this.idbOptions.searchFields,matcher:this.idbOptions.matcher})}async doCreate(e,s,r){let i=await this.handleInputParams(e,this.createReqMap);(isNil(i[this.idKey])||i[this.idKey]==="")&&(i[this.idKey]=nanoid());let a=await H(i);try{let n=await R(this.dbOpt,"readwrite",[this.storeName,this.filesStoreName],async o=>{let l=await G(a.data,a.pending,o[this.filesStoreName],this.storeName);try{await p(o[this.storeName].add(l));}catch(c){throw ye(c)&&this.rejectCode(m.CONFLICT),c}return l});return this.publishSync("create",[n[this.idKey]]),cloneDeep(n)}catch(n){throw n instanceof Y||ye(n)&&this.rejectCode(m.CONFLICT),n}}async doUpdate(e,s,r){let i=await this.handleInputParams(e,this.updateReqMap),a=i[this.idKey];(isNil(a)||a==="")&&this.rejectCode(m.ERR_INPUT_ID);let n=await H(i),o=await R(this.dbOpt,"readwrite",[this.storeName,this.filesStoreName],async l=>{let c=await p(l[this.storeName].get(a));c||this.rejectCode(m.NOT_FOUND);let u=await G(n.data,n.pending,l[this.filesStoreName],this.storeName);return await be(l[this.filesStoreName],c,u),await p(l[this.storeName].put(u)),u});return this.publishSync("update",[a]),cloneDeep(o)}async doPatch(e,s,r){let i=await this.handleInputParams(e,this.patchReqMap),a=i[this.idKey];(isNil(a)||a==="")&&this.rejectCode(m.ERR_INPUT_ID);let n=await R(this.dbOpt,"readonly",this.storeName,async u=>await p(u[this.storeName].get(a)));n||this.rejectCode(m.NOT_FOUND);let o={...n,...i},l=await H(o),c=await R(this.dbOpt,"readwrite",[this.storeName,this.filesStoreName],async u=>{let d=await G(l.data,l.pending,u[this.filesStoreName],this.storeName);return await be(u[this.filesStoreName],n,d),await p(u[this.storeName].put(d)),d});return this.publishSync("patch",[a]),cloneDeep(c)}async doDelete(e,s,r){let i=this.resolveDeleteId(e,this.idKey,s);return (isNil(i)||i==="")&&this.rejectCode(m.ERR_INPUT_ID),await R(this.dbOpt,"readwrite",[this.storeName,this.filesStoreName],async a=>{let n=await p(a[this.storeName].get(i));n||this.rejectCode(m.NOT_FOUND);let o=F(n);await p(a[this.storeName].delete(i)),await je(a[this.filesStoreName],o);}),this.publishSync("delete",[i]),{}}async doMultipleDelete(e,s,r){let i=this.resolveDeleteId(e,this.idKey,s);typeof i=="string"&&(i=i.split(",")),Array.isArray(i)||this.rejectCode(m.ERR_INPUT_ID);let a=[],n=[];for(let o of i)try{await this.delete({params:{[this.idKey]:o}}),a.push(o);}catch{n.push(o);}return a.length===0&&this.rejectCode(m.ERR,"\u6279\u91CF\u5220\u9664\u5168\u90E8\u5931\u8D25",{failList:n}),this.publishSync("multipleDelete",a),{sucList:a,failList:n}}async getFile(e){return R(this.dbOpt,"readonly",this.filesStoreName,async s=>vt(s[this.filesStoreName],e))}async getFileUrl(e){let s=await this.getFile(e);if(!s)return null;let r=URL.createObjectURL(s.blob);return this.objectUrls.add(r),r}revokeFileUrl(e){e&&(URL.revokeObjectURL(e),this.objectUrls.delete(e));}revokeAllFileUrls(){for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls.clear();}async gcOrphanFiles(){return R(this.dbOpt,"readwrite",[this.storeName,this.filesStoreName],async e=>{let s=await p(e[this.storeName].getAll()),r=new Set;for(let n of s)F(n,r);let i=await p(e[this.filesStoreName].getAll()),a=0;for(let n of i)n.storeName&&n.storeName!==this.storeName||r.has(n.id)||(await p(e[this.filesStoreName].delete(n.id)),a+=1);return a}).then(e=>(e>0&&this.publishSync("gc"),e))}},ce=nt;var Vt=function(t={},e={}){let s=useRef(new ce(t));return useMemo(()=>{let{effectParams:r,effectQuery:i}=e||{};return r&&merge(s.current,r),i&&merge(s.current.query,i),s.current},e.effectTargets||[])};
2
+ export{ms as ArrayDataModel,mt as ArrayUtils,se as BaseDataModel,nt as DataModel,m as IDB_STATE_CODE,Y as IdbModelError,gs as IndexedDbDataModel,b as ModelError,Xt as RequestCache,y as STATE_CODE,U as TOKEN,us as axios,os as createAbortController,Yt as createAxiosClient,le as createQueryEngine,ce as default,fs as defaultQueryEngine,ut as defaultQueryMatcher,it as defaultResponseAdapter,ls as getCancelTokenSource,Ye as getDefaultAxios,ps as getPublicUrl,es as getToken,Ce as handleErrCb,He as isCacheHitError,de as isCancel,ue as isFileRef,ye as isIdbConstraintError,ys as isIdbModelError,ds as isModelError,Xe as registerAxios,pe as resolveResponseAdapter,et as setAxAuthorization,ns as setAxBaseUrl,De as setAxDefaults,Ze as setAxHeaders,rs as setAxRequest,is as setAxResponse,as as setAxTimeout,ts as setAxios,Ee as setDataModelMessages,ss as setDefaultAxios,cs as setDefaultErrMsg,hs as setNetworkErrMsg,Zt as setToken,C as temp,Vt as useDataModel};
package/package.json CHANGED
@@ -1,62 +1,78 @@
1
1
  {
2
2
  "name": "@hzab/data-model",
3
- "version": "2.0.3-alpha.1",
4
- "description": "data model",
5
- "main": "src",
6
- "scripts": {
7
- "dev": "npm run prepare && webpack serve -c ./config/webpack.config.js --env local",
8
- "build": "webpack -c ./config/webpack.config.js --env production",
9
- "version:alpha": "npm version prerelease --preid=alpha",
10
- "publish:alpha": "npm publish --tag alpha",
11
- "version:beta": "npm version prerelease --preid=beta",
12
- "publish:beta": "npm publish --tag beta",
13
- "version:patch": "npm version patch",
14
- "version:minior": "npm version minor",
15
- "version:major": "npm version major",
16
- "publish:stable": "npm publish --access public",
17
- "prepare": "husky install",
18
- "docs": "typedoc"
3
+ "version": "2.1.0-alpha.1",
4
+ "private": false,
5
+ "description": "数据模型 2.1:再导出 core + useDataModel;后继 API 与旧写法双轨",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "author": "CaiYansong",
9
+ "publishConfig": {
10
+ "access": "public"
19
11
  },
20
12
  "files": [
13
+ "dist",
21
14
  "src",
15
+ "README.md",
16
+ "LICENSE",
22
17
  "CHANGELOG.md"
23
18
  ],
24
- "keywords": [],
25
- "author": "CaiYansong",
26
- "license": "ISC",
27
- "devDependencies": {
28
- "@hzab/permissions": "^0.1.1",
29
- "@hzab/webpack-config": "^0.7.1",
30
- "@types/react": "^17.0.62",
31
- "@types/react-dom": "^17.0.20",
32
- "antd": "4.24.16",
33
- "axios": "1.13.6",
34
- "eslint": "^8.30.0",
35
- "js-cookie": "^3.0.5",
36
- "less": "^4.1.3",
19
+ "main": "./dist/index.cjs",
20
+ "module": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js",
26
+ "require": "./dist/index.cjs"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "sideEffects": [
31
+ "./dist/index.js",
32
+ "./dist/index.cjs"
33
+ ],
34
+ "dependencies": {
35
+ "axios": "^1.18.1",
36
+ "dayjs": "^1.11.11",
37
37
  "lodash-es": "^4.18.1",
38
- "mobx": "^6.7.0",
39
- "mobx-react": "^7.6.0",
40
- "react": "^17.0.2",
41
- "react-dom": "^17.0.2",
42
- "react-router-dom": "^6.14.1",
43
- "typedoc": "^0.24.8",
44
- "typescript": "^4.9.4"
38
+ "nanoid": "^3.3.15"
39
+ },
40
+ "engines": {
41
+ "node": ">=24"
45
42
  },
46
43
  "peerDependencies": {
47
- "axios": ">=1.6.2",
48
- "js-cookie": ">=3.0.5"
44
+ "js-cookie": "^3.0.5",
45
+ "react": "^17.0.0 || ^18.0.0 || ^19.0.0"
49
46
  },
50
- "dependencies": {
51
- "dayjs": "^1.11.7",
52
- "nanoid": "^3.3.7"
47
+ "peerDependenciesMeta": {
48
+ "js-cookie": {
49
+ "optional": true
50
+ }
53
51
  },
54
- "directories": {
55
- "lib": "lib"
52
+ "devDependencies": {
53
+ "@testing-library/react": "^16.3.3",
54
+ "@types/lodash-es": "^4.17.12",
55
+ "@types/node": "^24.0.0",
56
+ "@types/react": "^19.0.0",
57
+ "happy-dom": "^20.11.12",
58
+ "lodash-es": "^4.18.1",
59
+ "prettier": "^3.0.0",
60
+ "react": "^19.0.0",
61
+ "react-dom": "^19.2.8",
62
+ "tsup": "^8.5.1",
63
+ "typescript": "^5.9.3",
64
+ "vite": "^8.0.0",
65
+ "vitest": "^4.1.10",
66
+ "@hzab/eslint-config": "^0.0.0",
67
+ "@hzab/typescript-config": "^0.0.0",
68
+ "@hzab/vite-config": "^0.0.2-alpha.0",
69
+ "@hzab/data-model-core": "^2.1.0-alpha.0"
56
70
  },
57
- "lint-staged": {
58
- "**.{js,jsx,ts,tsx,css,scss,less,json,html}": [
59
- "prettier --write"
60
- ]
71
+ "scripts": {
72
+ "build": "tsup",
73
+ "typecheck": "tsc --noEmit -p tsconfig.json --rootDir .",
74
+ "test": "vitest run",
75
+ "lint": "eslint src --max-warnings=0",
76
+ "format:check": "prettier --check src"
61
77
  }
62
- }
78
+ }
package/src/hooks.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { useMemo, useRef } from "react";
2
2
  import { merge } from "lodash-es";
3
- import DataModel, { DataModelOptions } from "./data-model";
3
+ import DataModel from "@hzab/data-model-core";
4
+ import type { DataModelOptions } from "@hzab/data-model-core";
4
5
 
5
6
  /**
6
7
  * useDataModel 选项接口
@@ -23,8 +24,11 @@ export interface UseDataModelOptions<T = any> {
23
24
  * @param {Object} opt.effectQuery 动态的 query 数据
24
25
  * @returns DataModel 实例
25
26
  */
26
- export const useDataModel = function <T = any>(initParams: DataModelOptions<T> = {}, opt: UseDataModelOptions<T> = {}) {
27
- const model = useRef<DataModel<T>>(new DataModel(initParams));
27
+ export const useDataModel = function <T = any>(
28
+ initParams: DataModelOptions<T> = {},
29
+ opt: UseDataModelOptions<T> = {},
30
+ ) {
31
+ const model = useRef<DataModel<T>>(new DataModel<T>(initParams));
28
32
  return useMemo(() => {
29
33
  const { effectParams, effectQuery } = opt || {};
30
34
  if (effectParams) {
package/src/index.ts CHANGED
@@ -1,11 +1,14 @@
1
- import axios from "./axios";
2
- import DataModel from "./data-model";
3
-
4
- export * from "./axios";
5
- export * from "./data-model";
6
- export * from "./hooks";
7
- export * from "./type";
8
-
9
- export { axios, DataModel };
10
-
11
- export default DataModel;
1
+ /**
2
+ * 数据模型 2.1:再导出 `@hzab/data-model-core`(打进 dist,不单独发布),
3
+ * 并提供 `useDataModel`。后继 API 与旧写法双轨。
4
+ *
5
+ * 老页面 `import { useDataModel, DataModel, axios } from "@hzab/data-model"` 仍可用。
6
+ * 不要安装 `@hzab/data-model-core`(private,已被打进本包 dist)。
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+
11
+ export * from "@hzab/data-model-core";
12
+ export { useDataModel } from "./hooks";
13
+ export type { UseDataModelOptions } from "./hooks";
14
+ export { default } from "@hzab/data-model-core";