diff --git a/intern-log/dist/assets/index-B3Rf3B1G.js b/intern-log/dist/assets/index-Cy5zm918.js similarity index 64% rename from intern-log/dist/assets/index-B3Rf3B1G.js rename to intern-log/dist/assets/index-Cy5zm918.js index 727627e..6e64196 100644 --- a/intern-log/dist/assets/index-B3Rf3B1G.js +++ b/intern-log/dist/assets/index-Cy5zm918.js @@ -2,23 +2,23 @@ * @vue/shared v3.5.44 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/function Ia(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const ct={},Ar=[],En=()=>{},Ru=()=>!1,Jo=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Xo=e=>e.startsWith("onUpdate:"),Et=Object.assign,ja=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},Xf=Object.prototype.hasOwnProperty,ot=(e,t)=>Xf.call(e,t),Le=Array.isArray,rr=e=>Fs(e)==="[object Map]",Bn=e=>Fs(e)==="[object Set]",Fl=e=>Fs(e)==="[object Date]",ze=e=>typeof e=="function",bt=e=>typeof e=="string",$n=e=>typeof e=="symbol",at=e=>e!==null&&typeof e=="object",Lu=e=>(at(e)||ze(e))&&ze(e.then)&&ze(e.catch),Ku=Object.prototype.toString,Fs=e=>Ku.call(e),Qf=e=>Fs(e).slice(8,-1),Fu=e=>Fs(e)==="[object Object]",Da=e=>bt(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,bs=Ia(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Qo=e=>{const t=Object.create(null);return n=>t[n]||(t[n]=e(n))},Zf=/-\w/g,hn=Qo(e=>e.replace(Zf,t=>t.slice(1).toUpperCase())),ed=/\B([A-Z])/g,cr=Qo(e=>e.replace(ed,"-$1").toLowerCase()),Nu=Qo(e=>e.charAt(0).toUpperCase()+e.slice(1)),zi=Qo(e=>e?`on${Nu(e)}`:""),Cn=(e,t)=>!Object.is(e,t),So=(e,...t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:s,value:n})},Zo=e=>{const t=parseFloat(e);return isNaN(t)?e:t},td=e=>{const t=bt(e)?Number(e):NaN;return isNaN(t)?e:t};let Nl;const ei=()=>Nl||(Nl=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function sr(e){if(Le(e)){const t={};for(let n=0;nn.startsWith("/*")?"":n).split(nd).forEach(n=>{if(n){const s=n.split(rd);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function et(e){let t="";if(bt(e))t=e;else if(Le(e))for(let n=0;nUn(n,t))}const Uu=e=>!!(e&&e.__v_isRef===!0),re=e=>bt(e)?e:e==null?"":Le(e)||at(e)&&(e.toString===Ku||!ze(e.toString))?Uu(e)?re(e.value):JSON.stringify(e,qu,2):String(e),qu=(e,t)=>Uu(t)?qu(e,t.value):rr(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,o],a)=>(n[Gi(s,a)+" =>"]=o,n),{})}:Bn(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>Gi(n))}:$n(t)?Gi(t):at(t)&&!Le(t)&&!Fu(t)?String(t):t,Gi=(e,t="")=>{var n;return $n(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};/** +**/function ja(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const ct={},Ar=[],En=()=>{},Lu=()=>!1,Qo=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Zo=e=>e.startsWith("onUpdate:"),Et=Object.assign,Da=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},Qf=Object.prototype.hasOwnProperty,ot=(e,t)=>Qf.call(e,t),Le=Array.isArray,rr=e=>Fs(e)==="[object Map]",Bn=e=>Fs(e)==="[object Set]",Nl=e=>Fs(e)==="[object Date]",ze=e=>typeof e=="function",bt=e=>typeof e=="string",$n=e=>typeof e=="symbol",at=e=>e!==null&&typeof e=="object",Ku=e=>(at(e)||ze(e))&&ze(e.then)&&ze(e.catch),Fu=Object.prototype.toString,Fs=e=>Fu.call(e),Zf=e=>Fs(e).slice(8,-1),Nu=e=>Fs(e)==="[object Object]",Ra=e=>bt(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,bs=ja(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),ei=e=>{const t=Object.create(null);return n=>t[n]||(t[n]=e(n))},ed=/-\w/g,hn=ei(e=>e.replace(ed,t=>t.slice(1).toUpperCase())),td=/\B([A-Z])/g,cr=ei(e=>e.replace(td,"-$1").toLowerCase()),Vu=ei(e=>e.charAt(0).toUpperCase()+e.slice(1)),Yi=ei(e=>e?`on${Vu(e)}`:""),Cn=(e,t)=>!Object.is(e,t),So=(e,...t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:s,value:n})},ti=e=>{const t=parseFloat(e);return isNaN(t)?e:t},nd=e=>{const t=bt(e)?Number(e):NaN;return isNaN(t)?e:t};let Vl;const ni=()=>Vl||(Vl=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function sr(e){if(Le(e)){const t={};for(let n=0;nn.startsWith("/*")?"":n).split(rd).forEach(n=>{if(n){const s=n.split(sd);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function et(e){let t="";if(bt(e))t=e;else if(Le(e))for(let n=0;nUn(n,t))}const qu=e=>!!(e&&e.__v_isRef===!0),re=e=>bt(e)?e:e==null?"":Le(e)||at(e)&&(e.toString===Fu||!ze(e.toString))?qu(e)?re(e.value):JSON.stringify(e,Hu,2):String(e),Hu=(e,t)=>qu(t)?Hu(e,t.value):rr(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,o],a)=>(n[Ji(s,a)+" =>"]=o,n),{})}:Bn(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>Ji(n))}:$n(t)?Ji(t):at(t)&&!Le(t)&&!Nu(t)?String(t):t,Ji=(e,t="")=>{var n;return $n(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};/** * @vue/reactivity v3.5.44 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let Mt;class cd{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!t&&Mt&&(Mt.active?(this.parent=Mt,this.index=(Mt.scopes||(Mt.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes){const s=this.scopes.slice();for(t=0,n=s.length;t0&&--this._on===0){if(Mt===this)Mt=this.prevScope;else{let t=Mt;for(;t;){if(t.prevScope===this){t.prevScope=this.prevScope;break}t=t.prevScope}}this.prevScope=void 0}}stop(t){if(this._active){this._active=!1;let n,s;for(n=0,s=this.effects.length;n0)return;if(_s){let t=_s;for(_s=void 0;t;){const n=t.next;t.next=void 0,t.flags&=-9,t=n}}let e;for(;ws;){let t=ws;for(ws=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(s){e||(e=s)}t=n}}if(e)throw e}function Gu(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Yu(e){let t,n=e.depsTail,s=n;for(;s;){const o=s.prevDep;s.version===-1?(s===n&&(n=o),Fa(s),dd(s)):t=s,s.dep.activeLink=s.prevActiveLink,s.prevActiveLink=void 0,s=o}e.deps=t,e.depsTail=n}function ua(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(Ju(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function Ju(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===As)||(e.globalVersion=As,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!ua(e))))return;e.flags|=2;const t=e.dep,n=dt,s=vn;dt=e,vn=!0;try{Gu(e);const o=e.fn(e._value);(t.version===0||Cn(o,e._value))&&(e.flags|=128,e._value=o,t.version++)}catch(o){throw t.version++,o}finally{dt=n,vn=s,Yu(e),e.flags&=-3}}function Fa(e,t=!1){const{dep:n,prevSub:s,nextSub:o}=e;if(s&&(s.nextSub=o,e.prevSub=void 0),o&&(o.prevSub=s,e.nextSub=void 0),n.subs===e&&(n.subs=s,!s&&n.computed)){n.computed.flags&=-5;for(let a=n.computed.deps;a;a=a.nextDep)Fa(a,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function dd(e){const{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}let vn=!0;const Xu=[];function An(){Xu.push(vn),vn=!1}function Pn(){const e=Xu.pop();vn=e===void 0?!0:e}function Ul(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const n=dt;dt=void 0;try{t()}finally{dt=n}}}let As=0;class pd{constructor(t,n){this.sub=t,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class Na{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!dt||!vn||dt===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==dt)n=this.activeLink=new pd(dt,this),dt.deps?(n.prevDep=dt.depsTail,dt.depsTail.nextDep=n,dt.depsTail=n):dt.deps=dt.depsTail=n,Qu(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const s=n.nextDep;s.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=s),n.prevDep=dt.depsTail,n.nextDep=void 0,dt.depsTail.nextDep=n,dt.depsTail=n,dt.deps===n&&(dt.deps=s)}return n}trigger(t){this.version++,As++,this.notify(t)}notify(t){La();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{Ka()}}}function Qu(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let s=t.deps;s;s=s.nextDep)Qu(s)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const ca=new WeakMap,Pr=Symbol(""),fa=Symbol(""),Ps=Symbol("");function Kt(e,t,n){if(vn&&dt){let s=ca.get(e);s||ca.set(e,s=new Map);let o=s.get(n);o||(s.set(n,o=new Na),o.map=s,o.key=n),o.track()}}function Rn(e,t,n,s,o,a){const c=ca.get(e);if(!c){As++;return}const d=h=>{h&&h.trigger()};if(La(),t==="clear")c.forEach(d);else{const h=Le(e),y=h&&Da(n);if(h&&n==="length"){const m=Number(s);c.forEach((k,D)=>{(D==="length"||D===Ps||!$n(D)&&D>=m)&&d(k)})}else switch((n!==void 0||c.has(void 0))&&d(c.get(n)),y&&d(c.get(Ps)),t){case"add":h?y&&d(c.get("length")):(d(c.get(Pr)),rr(e)&&d(c.get(fa)));break;case"delete":h||(d(c.get(Pr)),rr(e)&&d(c.get(fa)));break;case"set":rr(e)&&d(c.get(Pr));break}}Ka()}function qr(e){const t=rt(e);return t===e||(Kt(t,"iterate",Ps),ln(e))?t:Tn(e)?or(e)?t.map(n=>ir(un(n))):t.map(ir):t.map(un)}function ti(e){return Kt(e=rt(e),"iterate",Ps),e}function _n(e,t){return Tn(e)?ir(or(e)?un(t):t):un(t)}const hd={__proto__:null,[Symbol.iterator](){return Ji(this,Symbol.iterator,e=>_n(this,e))},concat(...e){return qr(this).concat(...e.map(t=>Le(t)?qr(t):t))},entries(){return Ji(this,"entries",e=>(e[1]=_n(this,e[1]),e))},every(e,t){return In(this,"every",e,t,void 0,arguments)},filter(e,t){return In(this,"filter",e,t,n=>n.map(s=>_n(this,s)),arguments)},find(e,t){return In(this,"find",e,t,n=>_n(this,n),arguments)},findIndex(e,t){return In(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return In(this,"findLast",e,t,n=>_n(this,n),arguments)},findLastIndex(e,t){return In(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return In(this,"forEach",e,t,void 0,arguments)},includes(...e){return Xi(this,"includes",e)},indexOf(...e){return Xi(this,"indexOf",e)},join(e){return qr(this).join(e)},lastIndexOf(...e){return Xi(this,"lastIndexOf",e)},map(e,t){return In(this,"map",e,t,void 0,arguments)},pop(){return ps(this,"pop")},push(...e){return ps(this,"push",e)},reduce(e,...t){return Hl(this,"reduce",e,t)},reduceRight(e,...t){return Hl(this,"reduceRight",e,t)},shift(){return ps(this,"shift")},some(e,t){return In(this,"some",e,t,void 0,arguments)},splice(...e){return ps(this,"splice",e)},toReversed(){return qr(this).toReversed()},toSorted(e){return qr(this).toSorted(e)},toSpliced(...e){return qr(this).toSpliced(...e)},unshift(...e){return ps(this,"unshift",e)},values(){return Ji(this,"values",e=>_n(this,e))}};function Ji(e,t,n){const s=ti(e),o=s[t],a=o.call(s);if(s!==e&&!ln(e)){if(a[Symbol.toStringTag]==="Array Iterator"){const c=Object.create(Object.getPrototypeOf(a));return c.next=()=>ql(a.next(),n),o!==Zu[t]&&Object.defineProperties(c,{return:{get(){const d=a.return;return typeof d=="function"?d.bind(a):d}},throw:{get(){const d=a.throw;return typeof d=="function"?d.bind(a):d}}}),c}a._next=a.next,a.next=()=>ql(a._next(),n)}return a}function ql(e,t){return e.done||(e.value=t(e.value)),e}const Zu=Array.prototype;function In(e,t,n,s,o,a){const c=ti(e),d=c!==e&&!ln(e),h=c[t];if(h!==Zu[t]){const k=h.apply(e,a);return d?un(k):k}let y=n;c!==e&&(d?y=function(k,D){return n.call(this,_n(e,k),D,e)}:n.length>2&&(y=function(k,D){return n.call(this,k,D,e)}));const m=h.call(c,y,s);return d&&o?o(m):m}function Hl(e,t,n,s){const o=ti(e),a=o!==e&&!ln(e);let c=n,d=!1;o!==e&&(a?(d=s.length===0,c=function(y,m,k){return d&&(d=!1,y=_n(e,y)),n.call(this,y,_n(e,m),k,e)}):n.length>3&&(c=function(y,m,k){return n.call(this,y,m,k,e)}));const h=o[t](c,...s);return d?_n(e,h):h}function Xi(e,t,n){const s=rt(e);Kt(s,"iterate",Ps);const o=s[t](...n);return(o===-1||o===!1)&&qa(n[0])?(n[0]=rt(n[0]),s[t](...n)):o}function ps(e,t,n=[]){An(),La();const s=rt(e)[t].apply(e,n);return Ka(),Pn(),s}const vd=Ia("__proto__,__v_isRef,__isVue"),ec=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter($n));function md(e){$n(e)||(e=String(e));const t=rt(this);return Kt(t,"has",e),t.hasOwnProperty(e)}class tc{constructor(t=!1,n=!1){this._isReadonly=t,this._isShallow=n}get(t,n,s){if(n==="__v_skip")return t.__v_skip;const o=this._isReadonly,a=this._isShallow;if(n==="__v_isReactive")return!o;if(n==="__v_isReadonly")return o;if(n==="__v_isShallow")return a;if(n==="__v_raw")return s===(o?a?Ed:oc:a?sc:rc).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(s)?t:void 0;const c=Le(t);if(!o){let h;if(c&&(h=hd[n]))return h;if(n==="hasOwnProperty")return md}const d=Reflect.get(t,n,Nt(t)?t:s);if(($n(n)?ec.has(n):vd(n))||(o||Kt(t,"get",n),a))return d;if(Nt(d)){const h=c&&Da(n)?d:d.value;return o&&at(h)?pa(h):h}return at(d)?o?pa(d):Ba(d):d}}class nc extends tc{constructor(t=!1){super(!1,t)}set(t,n,s,o){let a=t[n];const c=Le(t)&&Da(n);if(!this._isShallow){const y=Tn(a);if(!ln(s)&&!Tn(s)&&(a=rt(a),s=rt(s)),!c&&Nt(a)&&!Nt(s))return y||(a.value=s),!0}const d=c?Number(n)e,go=e=>Reflect.getPrototypeOf(e);function _d(e,t,n){return function(...s){const o=this.__v_raw,a=rt(o),c=rr(a),d=e==="entries"||e===Symbol.iterator&&c,h=e==="keys"&&c,y=o[e](...s),m=n?da:t?ir:un;return!t&&Kt(a,"iterate",h?fa:Pr),Et(Object.create(y),{next(){const{value:k,done:D}=y.next();return D?{value:k,done:D}:{value:d?[m(k[0]),m(k[1])]:m(k),done:D}}})}}function bo(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function kd(e,t){const n={get(o){const a=this.__v_raw,c=rt(a),d=rt(o);e||(Cn(o,d)&&Kt(c,"get",o),Kt(c,"get",d));const{has:h}=go(c),y=t?da:e?ir:un;if(h.call(c,o))return y(a.get(o));if(h.call(c,d))return y(a.get(d));a!==c&&a.get(o)},get size(){const o=this.__v_raw;return!e&&Kt(rt(o),"iterate",Pr),o.size},has(o){const a=this.__v_raw,c=rt(a),d=rt(o);return e||(Cn(o,d)&&Kt(c,"has",o),Kt(c,"has",d)),o===d?a.has(o):a.has(o)||a.has(d)},forEach(o,a){const c=this,d=c.__v_raw,h=rt(d),y=t?da:e?ir:un;return!e&&Kt(h,"iterate",Pr),d.forEach((m,k)=>o.call(a,y(m),y(k),c))}};return Et(n,e?{add:bo("add"),set:bo("set"),delete:bo("delete"),clear:bo("clear")}:{add(o){const a=rt(this),c=go(a),d=rt(o),h=!t&&!ln(o)&&!Tn(o)?d:o;return c.has.call(a,h)||Cn(o,h)&&c.has.call(a,o)||Cn(d,h)&&c.has.call(a,d)||(a.add(h),Rn(a,"add",h,h)),this},set(o,a){!t&&!ln(a)&&!Tn(a)&&(a=rt(a));const c=rt(this),{has:d,get:h}=go(c);let y=d.call(c,o);y||(o=rt(o),y=d.call(c,o));const m=h.call(c,o);return c.set(o,a),y?Cn(a,m)&&Rn(c,"set",o,a):Rn(c,"add",o,a),this},delete(o){const a=rt(this),{has:c,get:d}=go(a);let h=c.call(a,o);h||(o=rt(o),h=c.call(a,o)),d&&d.call(a,o);const y=a.delete(o);return h&&Rn(a,"delete",o,void 0),y},clear(){const o=rt(this),a=o.size!==0,c=o.clear();return a&&Rn(o,"clear",void 0,void 0),c}}),["keys","values","entries",Symbol.iterator].forEach(o=>{n[o]=_d(o,e,t)}),n}function Va(e,t){const n=kd(e,t);return(s,o,a)=>o==="__v_isReactive"?!e:o==="__v_isReadonly"?e:o==="__v_isShallow"?t:o==="__v_raw"?s:Reflect.get(ot(n,o)&&o in s?n:s,o,a)}const xd={get:Va(!1,!1)},Cd={get:Va(!1,!0)},Sd={get:Va(!0,!1)};const rc=new WeakMap,sc=new WeakMap,oc=new WeakMap,Ed=new WeakMap;function $d(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function Ba(e){return Tn(e)?e:Ua(e,!1,gd,xd,rc)}function Ad(e){return Ua(e,!1,wd,Cd,sc)}function pa(e){return Ua(e,!0,bd,Sd,oc)}function Ua(e,t,n,s,o){if(!at(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;const a=o.get(e);if(a)return a;const c=$d(Qf(e));if(c===0)return e;const d=new Proxy(e,c===2?s:n);return o.set(e,d),d}function or(e){return Tn(e)?or(e.__v_raw):!!(e&&e.__v_isReactive)}function Tn(e){return!!(e&&e.__v_isReadonly)}function ln(e){return!!(e&&e.__v_isShallow)}function qa(e){return e?!!e.__v_raw:!1}function rt(e){const t=e&&e.__v_raw;return t?rt(t):e}function Pd(e){return!ot(e,"__v_skip")&&Object.isExtensible(e)&&Vu(e,"__v_skip",!0),e}const un=e=>at(e)?Ba(e):e,ir=e=>at(e)?pa(e):e;function Nt(e){return e?e.__v_isRef===!0:!1}function N(e){return Td(e,!1)}function Td(e,t){return Nt(e)?e:new Od(e,t)}class Od{constructor(t,n){this.dep=new Na,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?t:rt(t),this._value=n?t:un(t),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(t){const n=this._rawValue,s=this.__v_isShallow||ln(t)||Tn(t);t=s?t:rt(t),Cn(t,n)&&(this._rawValue=t,this._value=s?t:un(t),this.dep.trigger())}}function Qt(e){return Nt(e)?e.value:e}const Md={get:(e,t,n)=>t==="__v_raw"?e:Qt(Reflect.get(e,t,n)),set:(e,t,n,s)=>{const o=e[t];return Nt(o)&&!Nt(n)?(o.value=n,!0):Reflect.set(e,t,n,s)}};function ic(e){return or(e)?e:new Proxy(e,Md)}class Id{constructor(t,n,s){this.fn=t,this.setter=n,this._value=void 0,this.dep=new Na(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=As-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=s}notify(){if(this.flags|=16,!(this.flags&8)&&dt!==this)return zu(this,!0),!0}get value(){const t=this.dep.track();return Ju(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function jd(e,t,n=!1){let s,o;return ze(e)?s=e:(s=e.get,o=e.set),new Id(s,o,n)}const wo={},Oo=new WeakMap;let Cr;function Dd(e,t=!1,n=Cr){if(n){let s=Oo.get(n);s||Oo.set(n,s=[]),s.push(e)}}function Rd(e,t,n=ct){const{immediate:s,deep:o,once:a,scheduler:c,augmentJob:d,call:h}=n,y=Q=>o?Q:ln(Q)||o===!1||o===0?Ln(Q,1):Ln(Q);let m,k,D,O,K=!1,W=!1;if(Nt(e)?(k=()=>e.value,K=ln(e)):or(e)?(k=()=>y(e),K=!0):Le(e)?(W=!0,K=e.some(Q=>or(Q)||ln(Q)),k=()=>e.map(Q=>{if(Nt(Q))return Q.value;if(or(Q))return y(Q);if(ze(Q))return h?h(Q,2):Q()})):ze(e)?t?k=h?()=>h(e,2):e:k=()=>{if(D){An();try{D()}finally{Pn()}}const Q=Cr;Cr=m;try{return h?h(e,3,[O]):e(O)}finally{Cr=Q}}:k=En,t&&o){const Q=k,le=o===!0?1/0:o;k=()=>Ln(Q(),le)}const de=fd(),Z=()=>{m.stop(),de&&de.active&&ja(de.effects,m)};if(a&&t){const Q=t;t=(...le)=>{try{return Q(...le)}finally{Z()}}}let E=W?new Array(e.length).fill(wo):wo;const L=Q=>{if(!(!(m.flags&1)||!m.dirty&&!Q))if(t){const le=m.run();if(Q||o||K||(W?le.some((ce,ee)=>Cn(ce,E[ee])):Cn(le,E))){const ce=Cr;An();try{D&&D(),Cr=m;const ee=[le,E===wo?void 0:W&&E[0]===wo?[]:E,O];E=le,h?h(t,3,ee):t(...ee)}finally{Cr=ce,Pn()}}}else m.run()};return d&&d(L),m=new Hu(k),m.scheduler=c?()=>c(L,!1):L,O=Q=>Dd(Q,!1,m),D=m.onStop=()=>{const Q=Oo.get(m);if(Q){if(h)h(Q,4);else for(const le of Q)le();Oo.delete(m)}},t?s?L(!0):E=m.run():c?c(L.bind(null,!0),!0):m.run(),Z.pause=m.pause.bind(m),Z.resume=m.resume.bind(m),Z.stop=Z,Z}function Ln(e,t=1/0,n){if(t<=0||!at(e)||e.__v_skip||(n=n||new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,Nt(e))Ln(e.value,t,n);else if(Le(e))for(let s=0;s{Ln(s,t,n)});else if(Fu(e)){for(const s in e)Ln(e[s],t,n);for(const s of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,s)&&Ln(e[s],t,n)}return e}/** +**/let Mt;class fd{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!t&&Mt&&(Mt.active?(this.parent=Mt,this.index=(Mt.scopes||(Mt.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes){const s=this.scopes.slice();for(t=0,n=s.length;t0&&--this._on===0){if(Mt===this)Mt=this.prevScope;else{let t=Mt;for(;t;){if(t.prevScope===this){t.prevScope=this.prevScope;break}t=t.prevScope}}this.prevScope=void 0}}stop(t){if(this._active){this._active=!1;let n,s;for(n=0,s=this.effects.length;n0)return;if(_s){let t=_s;for(_s=void 0;t;){const n=t.next;t.next=void 0,t.flags&=-9,t=n}}let e;for(;ws;){let t=ws;for(ws=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(s){e||(e=s)}t=n}}if(e)throw e}function Yu(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Ju(e){let t,n=e.depsTail,s=n;for(;s;){const o=s.prevDep;s.version===-1?(s===n&&(n=o),Na(s),pd(s)):t=s,s.dep.activeLink=s.prevActiveLink,s.prevActiveLink=void 0,s=o}e.deps=t,e.depsTail=n}function fa(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(Xu(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function Xu(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===As)||(e.globalVersion=As,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!fa(e))))return;e.flags|=2;const t=e.dep,n=dt,s=vn;dt=e,vn=!0;try{Yu(e);const o=e.fn(e._value);(t.version===0||Cn(o,e._value))&&(e.flags|=128,e._value=o,t.version++)}catch(o){throw t.version++,o}finally{dt=n,vn=s,Ju(e),e.flags&=-3}}function Na(e,t=!1){const{dep:n,prevSub:s,nextSub:o}=e;if(s&&(s.nextSub=o,e.prevSub=void 0),o&&(o.prevSub=s,e.nextSub=void 0),n.subs===e&&(n.subs=s,!s&&n.computed)){n.computed.flags&=-5;for(let a=n.computed.deps;a;a=a.nextDep)Na(a,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function pd(e){const{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}let vn=!0;const Qu=[];function An(){Qu.push(vn),vn=!1}function Pn(){const e=Qu.pop();vn=e===void 0?!0:e}function ql(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const n=dt;dt=void 0;try{t()}finally{dt=n}}}let As=0;class hd{constructor(t,n){this.sub=t,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class Va{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!dt||!vn||dt===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==dt)n=this.activeLink=new hd(dt,this),dt.deps?(n.prevDep=dt.depsTail,dt.depsTail.nextDep=n,dt.depsTail=n):dt.deps=dt.depsTail=n,Zu(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const s=n.nextDep;s.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=s),n.prevDep=dt.depsTail,n.nextDep=void 0,dt.depsTail.nextDep=n,dt.depsTail=n,dt.deps===n&&(dt.deps=s)}return n}trigger(t){this.version++,As++,this.notify(t)}notify(t){Ka();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{Fa()}}}function Zu(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let s=t.deps;s;s=s.nextDep)Zu(s)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const da=new WeakMap,Pr=Symbol(""),pa=Symbol(""),Ps=Symbol("");function Kt(e,t,n){if(vn&&dt){let s=da.get(e);s||da.set(e,s=new Map);let o=s.get(n);o||(s.set(n,o=new Va),o.map=s,o.key=n),o.track()}}function Rn(e,t,n,s,o,a){const c=da.get(e);if(!c){As++;return}const d=h=>{h&&h.trigger()};if(Ka(),t==="clear")c.forEach(d);else{const h=Le(e),y=h&&Ra(n);if(h&&n==="length"){const m=Number(s);c.forEach((k,D)=>{(D==="length"||D===Ps||!$n(D)&&D>=m)&&d(k)})}else switch((n!==void 0||c.has(void 0))&&d(c.get(n)),y&&d(c.get(Ps)),t){case"add":h?y&&d(c.get("length")):(d(c.get(Pr)),rr(e)&&d(c.get(pa)));break;case"delete":h||(d(c.get(Pr)),rr(e)&&d(c.get(pa)));break;case"set":rr(e)&&d(c.get(Pr));break}}Fa()}function qr(e){const t=rt(e);return t===e||(Kt(t,"iterate",Ps),ln(e))?t:Tn(e)?or(e)?t.map(n=>ir(un(n))):t.map(ir):t.map(un)}function ri(e){return Kt(e=rt(e),"iterate",Ps),e}function _n(e,t){return Tn(e)?ir(or(e)?un(t):t):un(t)}const vd={__proto__:null,[Symbol.iterator](){return Qi(this,Symbol.iterator,e=>_n(this,e))},concat(...e){return qr(this).concat(...e.map(t=>Le(t)?qr(t):t))},entries(){return Qi(this,"entries",e=>(e[1]=_n(this,e[1]),e))},every(e,t){return In(this,"every",e,t,void 0,arguments)},filter(e,t){return In(this,"filter",e,t,n=>n.map(s=>_n(this,s)),arguments)},find(e,t){return In(this,"find",e,t,n=>_n(this,n),arguments)},findIndex(e,t){return In(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return In(this,"findLast",e,t,n=>_n(this,n),arguments)},findLastIndex(e,t){return In(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return In(this,"forEach",e,t,void 0,arguments)},includes(...e){return Zi(this,"includes",e)},indexOf(...e){return Zi(this,"indexOf",e)},join(e){return qr(this).join(e)},lastIndexOf(...e){return Zi(this,"lastIndexOf",e)},map(e,t){return In(this,"map",e,t,void 0,arguments)},pop(){return ps(this,"pop")},push(...e){return ps(this,"push",e)},reduce(e,...t){return Wl(this,"reduce",e,t)},reduceRight(e,...t){return Wl(this,"reduceRight",e,t)},shift(){return ps(this,"shift")},some(e,t){return In(this,"some",e,t,void 0,arguments)},splice(...e){return ps(this,"splice",e)},toReversed(){return qr(this).toReversed()},toSorted(e){return qr(this).toSorted(e)},toSpliced(...e){return qr(this).toSpliced(...e)},unshift(...e){return ps(this,"unshift",e)},values(){return Qi(this,"values",e=>_n(this,e))}};function Qi(e,t,n){const s=ri(e),o=s[t],a=o.call(s);if(s!==e&&!ln(e)){if(a[Symbol.toStringTag]==="Array Iterator"){const c=Object.create(Object.getPrototypeOf(a));return c.next=()=>Hl(a.next(),n),o!==ec[t]&&Object.defineProperties(c,{return:{get(){const d=a.return;return typeof d=="function"?d.bind(a):d}},throw:{get(){const d=a.throw;return typeof d=="function"?d.bind(a):d}}}),c}a._next=a.next,a.next=()=>Hl(a._next(),n)}return a}function Hl(e,t){return e.done||(e.value=t(e.value)),e}const ec=Array.prototype;function In(e,t,n,s,o,a){const c=ri(e),d=c!==e&&!ln(e),h=c[t];if(h!==ec[t]){const k=h.apply(e,a);return d?un(k):k}let y=n;c!==e&&(d?y=function(k,D){return n.call(this,_n(e,k),D,e)}:n.length>2&&(y=function(k,D){return n.call(this,k,D,e)}));const m=h.call(c,y,s);return d&&o?o(m):m}function Wl(e,t,n,s){const o=ri(e),a=o!==e&&!ln(e);let c=n,d=!1;o!==e&&(a?(d=s.length===0,c=function(y,m,k){return d&&(d=!1,y=_n(e,y)),n.call(this,y,_n(e,m),k,e)}):n.length>3&&(c=function(y,m,k){return n.call(this,y,m,k,e)}));const h=o[t](c,...s);return d?_n(e,h):h}function Zi(e,t,n){const s=rt(e);Kt(s,"iterate",Ps);const o=s[t](...n);return(o===-1||o===!1)&&Ha(n[0])?(n[0]=rt(n[0]),s[t](...n)):o}function ps(e,t,n=[]){An(),Ka();const s=rt(e)[t].apply(e,n);return Fa(),Pn(),s}const md=ja("__proto__,__v_isRef,__isVue"),tc=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter($n));function yd(e){$n(e)||(e=String(e));const t=rt(this);return Kt(t,"has",e),t.hasOwnProperty(e)}class nc{constructor(t=!1,n=!1){this._isReadonly=t,this._isShallow=n}get(t,n,s){if(n==="__v_skip")return t.__v_skip;const o=this._isReadonly,a=this._isShallow;if(n==="__v_isReactive")return!o;if(n==="__v_isReadonly")return o;if(n==="__v_isShallow")return a;if(n==="__v_raw")return s===(o?a?$d:ic:a?oc:sc).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(s)?t:void 0;const c=Le(t);if(!o){let h;if(c&&(h=vd[n]))return h;if(n==="hasOwnProperty")return yd}const d=Reflect.get(t,n,Nt(t)?t:s);if(($n(n)?tc.has(n):md(n))||(o||Kt(t,"get",n),a))return d;if(Nt(d)){const h=c&&Ra(n)?d:d.value;return o&&at(h)?va(h):h}return at(d)?o?va(d):Ua(d):d}}class rc extends nc{constructor(t=!1){super(!1,t)}set(t,n,s,o){let a=t[n];const c=Le(t)&&Ra(n);if(!this._isShallow){const y=Tn(a);if(!ln(s)&&!Tn(s)&&(a=rt(a),s=rt(s)),!c&&Nt(a)&&!Nt(s))return y||(a.value=s),!0}const d=c?Number(n)e,go=e=>Reflect.getPrototypeOf(e);function kd(e,t,n){return function(...s){const o=this.__v_raw,a=rt(o),c=rr(a),d=e==="entries"||e===Symbol.iterator&&c,h=e==="keys"&&c,y=o[e](...s),m=n?ha:t?ir:un;return!t&&Kt(a,"iterate",h?pa:Pr),Et(Object.create(y),{next(){const{value:k,done:D}=y.next();return D?{value:k,done:D}:{value:d?[m(k[0]),m(k[1])]:m(k),done:D}}})}}function bo(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function xd(e,t){const n={get(o){const a=this.__v_raw,c=rt(a),d=rt(o);e||(Cn(o,d)&&Kt(c,"get",o),Kt(c,"get",d));const{has:h}=go(c),y=t?ha:e?ir:un;if(h.call(c,o))return y(a.get(o));if(h.call(c,d))return y(a.get(d));a!==c&&a.get(o)},get size(){const o=this.__v_raw;return!e&&Kt(rt(o),"iterate",Pr),o.size},has(o){const a=this.__v_raw,c=rt(a),d=rt(o);return e||(Cn(o,d)&&Kt(c,"has",o),Kt(c,"has",d)),o===d?a.has(o):a.has(o)||a.has(d)},forEach(o,a){const c=this,d=c.__v_raw,h=rt(d),y=t?ha:e?ir:un;return!e&&Kt(h,"iterate",Pr),d.forEach((m,k)=>o.call(a,y(m),y(k),c))}};return Et(n,e?{add:bo("add"),set:bo("set"),delete:bo("delete"),clear:bo("clear")}:{add(o){const a=rt(this),c=go(a),d=rt(o),h=!t&&!ln(o)&&!Tn(o)?d:o;return c.has.call(a,h)||Cn(o,h)&&c.has.call(a,o)||Cn(d,h)&&c.has.call(a,d)||(a.add(h),Rn(a,"add",h,h)),this},set(o,a){!t&&!ln(a)&&!Tn(a)&&(a=rt(a));const c=rt(this),{has:d,get:h}=go(c);let y=d.call(c,o);y||(o=rt(o),y=d.call(c,o));const m=h.call(c,o);return c.set(o,a),y?Cn(a,m)&&Rn(c,"set",o,a):Rn(c,"add",o,a),this},delete(o){const a=rt(this),{has:c,get:d}=go(a);let h=c.call(a,o);h||(o=rt(o),h=c.call(a,o)),d&&d.call(a,o);const y=a.delete(o);return h&&Rn(a,"delete",o,void 0),y},clear(){const o=rt(this),a=o.size!==0,c=o.clear();return a&&Rn(o,"clear",void 0,void 0),c}}),["keys","values","entries",Symbol.iterator].forEach(o=>{n[o]=kd(o,e,t)}),n}function Ba(e,t){const n=xd(e,t);return(s,o,a)=>o==="__v_isReactive"?!e:o==="__v_isReadonly"?e:o==="__v_isShallow"?t:o==="__v_raw"?s:Reflect.get(ot(n,o)&&o in s?n:s,o,a)}const Cd={get:Ba(!1,!1)},Sd={get:Ba(!1,!0)},Ed={get:Ba(!0,!1)};const sc=new WeakMap,oc=new WeakMap,ic=new WeakMap,$d=new WeakMap;function Ad(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function Ua(e){return Tn(e)?e:qa(e,!1,bd,Cd,sc)}function Pd(e){return qa(e,!1,_d,Sd,oc)}function va(e){return qa(e,!0,wd,Ed,ic)}function qa(e,t,n,s,o){if(!at(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;const a=o.get(e);if(a)return a;const c=Ad(Zf(e));if(c===0)return e;const d=new Proxy(e,c===2?s:n);return o.set(e,d),d}function or(e){return Tn(e)?or(e.__v_raw):!!(e&&e.__v_isReactive)}function Tn(e){return!!(e&&e.__v_isReadonly)}function ln(e){return!!(e&&e.__v_isShallow)}function Ha(e){return e?!!e.__v_raw:!1}function rt(e){const t=e&&e.__v_raw;return t?rt(t):e}function Td(e){return!ot(e,"__v_skip")&&Object.isExtensible(e)&&Bu(e,"__v_skip",!0),e}const un=e=>at(e)?Ua(e):e,ir=e=>at(e)?va(e):e;function Nt(e){return e?e.__v_isRef===!0:!1}function N(e){return Od(e,!1)}function Od(e,t){return Nt(e)?e:new Md(e,t)}class Md{constructor(t,n){this.dep=new Va,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?t:rt(t),this._value=n?t:un(t),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(t){const n=this._rawValue,s=this.__v_isShallow||ln(t)||Tn(t);t=s?t:rt(t),Cn(t,n)&&(this._rawValue=t,this._value=s?t:un(t),this.dep.trigger())}}function Qt(e){return Nt(e)?e.value:e}const Id={get:(e,t,n)=>t==="__v_raw"?e:Qt(Reflect.get(e,t,n)),set:(e,t,n,s)=>{const o=e[t];return Nt(o)&&!Nt(n)?(o.value=n,!0):Reflect.set(e,t,n,s)}};function ac(e){return or(e)?e:new Proxy(e,Id)}class jd{constructor(t,n,s){this.fn=t,this.setter=n,this._value=void 0,this.dep=new Va(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=As-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=s}notify(){if(this.flags|=16,!(this.flags&8)&&dt!==this)return Gu(this,!0),!0}get value(){const t=this.dep.track();return Xu(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function Dd(e,t,n=!1){let s,o;return ze(e)?s=e:(s=e.get,o=e.set),new jd(s,o,n)}const wo={},Mo=new WeakMap;let Cr;function Rd(e,t=!1,n=Cr){if(n){let s=Mo.get(n);s||Mo.set(n,s=[]),s.push(e)}}function Ld(e,t,n=ct){const{immediate:s,deep:o,once:a,scheduler:c,augmentJob:d,call:h}=n,y=Q=>o?Q:ln(Q)||o===!1||o===0?Ln(Q,1):Ln(Q);let m,k,D,O,K=!1,W=!1;if(Nt(e)?(k=()=>e.value,K=ln(e)):or(e)?(k=()=>y(e),K=!0):Le(e)?(W=!0,K=e.some(Q=>or(Q)||ln(Q)),k=()=>e.map(Q=>{if(Nt(Q))return Q.value;if(or(Q))return y(Q);if(ze(Q))return h?h(Q,2):Q()})):ze(e)?t?k=h?()=>h(e,2):e:k=()=>{if(D){An();try{D()}finally{Pn()}}const Q=Cr;Cr=m;try{return h?h(e,3,[O]):e(O)}finally{Cr=Q}}:k=En,t&&o){const Q=k,le=o===!0?1/0:o;k=()=>Ln(Q(),le)}const de=dd(),Z=()=>{m.stop(),de&&de.active&&Da(de.effects,m)};if(a&&t){const Q=t;t=(...le)=>{try{return Q(...le)}finally{Z()}}}let E=W?new Array(e.length).fill(wo):wo;const L=Q=>{if(!(!(m.flags&1)||!m.dirty&&!Q))if(t){const le=m.run();if(Q||o||K||(W?le.some((ce,ee)=>Cn(ce,E[ee])):Cn(le,E))){const ce=Cr;An();try{D&&D(),Cr=m;const ee=[le,E===wo?void 0:W&&E[0]===wo?[]:E,O];E=le,h?h(t,3,ee):t(...ee)}finally{Cr=ce,Pn()}}}else m.run()};return d&&d(L),m=new Wu(k),m.scheduler=c?()=>c(L,!1):L,O=Q=>Rd(Q,!1,m),D=m.onStop=()=>{const Q=Mo.get(m);if(Q){if(h)h(Q,4);else for(const le of Q)le();Mo.delete(m)}},t?s?L(!0):E=m.run():c?c(L.bind(null,!0),!0):m.run(),Z.pause=m.pause.bind(m),Z.resume=m.resume.bind(m),Z.stop=Z,Z}function Ln(e,t=1/0,n){if(t<=0||!at(e)||e.__v_skip||(n=n||new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,Nt(e))Ln(e.value,t,n);else if(Le(e))for(let s=0;s{Ln(s,t,n)});else if(Nu(e)){for(const s in e)Ln(e[s],t,n);for(const s of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,s)&&Ln(e[s],t,n)}return e}/** * @vue/runtime-core v3.5.44 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/function Ns(e,t,n,s){try{return s?e(...s):e()}catch(o){ni(o,t,n)}}function cn(e,t,n,s){if(ze(e)){const o=Ns(e,t,n,s);return o&&Lu(o)&&o.catch(a=>{ni(a,t,n)}),o}if(Le(e)){const o=[];for(let a=0;a>>1,o=Wt[s],a=Ts(o);a=Ts(n)?Wt.push(e):Wt.splice(Kd(t),0,e),e.flags|=1,lc()}}function lc(){Mo||(Mo=ac.then(fc))}function Fd(e){if(!Le(e))tr&&e.id===-1?tr.splice(Hr+1,0,e):e.flags&1||(kn.push(e),e.flags|=1);else for(let t=0;t=t))continue;Wt.splice(s,1),s=e?s-1:pn,o.flags&4&&(o.flags&=-2),o(),o.flags&4||(o.flags&=-2)}}}function cc(e,t,n=0){if(kn.length){let s=kn,o=0;if(t){s=[];for(let c=0;cTs(c)-Ts(d));if(kn.length=o,tr){for(let c=0;ce.id==null?e.flags&2?-1:1/0:e.id;function fc(e){try{for(pn=0;pn{s._d&&Lo(-1);const a=Io(t),c=Tr.length;let d;try{d=e(...o)}finally{for(let h=Tr.length;h>c;h--)Nc();Io(a),s._d&&Lo(1)}return d};return s._n=!0,s._c=!0,s._d=!0,s}function $e(e,t){if(an===null)return e;const n=li(an),s=e.dirs||(e.dirs=[]);for(let o=0;o1)return n&&ze(t)?t.call(s&&s.proxy):t}}const Bd=Symbol.for("v-scx"),Ud=()=>Eo(Bd);function gt(e,t,n){return pc(e,t,n)}function pc(e,t,n=ct){const{immediate:s,deep:o,flush:a,once:c}=n,d=Et({},n),h=t&&s||!t&&a!=="post";let y;if(Rs){if(a==="sync"){const O=Ud();y=O.__watcherHandles||(O.__watcherHandles=[])}else if(!h){const O=()=>{};return O.stop=En,O.resume=En,O.pause=En,O}}const m=zt;d.call=(O,K,W)=>cn(O,m,K,W);let k=!1;a==="post"?d.scheduler=O=>{O.i=m,Ht(O,m&&m.suspense)}:a!=="sync"&&(k=!0,d.scheduler=(O,K)=>{K?O():Ha(O)}),d.augmentJob=O=>{t&&(O.flags|=4),k&&(O.flags|=2,m&&(O.id=m.uid,O.i=m))};const D=Rd(e,t,d);return Rs&&(y?y.push(D):h&&D()),D}function qd(e,t,n){const s=this.proxy,o=bt(e)?e.includes(".")?hc(s,e):()=>s[e]:e.bind(s,s);let a;ze(t)?a=t:(a=t.handler,n=t);const c=Bs(this),d=pc(o,a.bind(s),n);return c(),d}function hc(e,t){const n=t.split(".");return()=>{let s=e;for(let o=0;oe.__isTeleport,Er=e=>e&&(e.disabled||e.disabled===""),Hd=e=>e&&(e.defer||e.defer===""),Wl=e=>typeof SVGElement<"u"&&e instanceof SVGElement,zl=e=>typeof MathMLElement=="function"&&e instanceof MathMLElement,ha=(e,t)=>{const n=e&&e.to;return bt(n)?t?t(n):null:n},Wd={name:"Teleport",__isTeleport:!0,process(e,t,n,s,o,a,c,d,h,y){const{mc:m,pc:k,pbc:D,o:{insert:O,querySelector:K,createText:W,createComment:de,parentNode:Z}}=y,E=Er(t.props);let{dynamicChildren:L}=t;const Q=(ee,A,x)=>{ee.shapeFlag&16&&m(ee.children,A,x,o,a,c,d,h)},le=(ee=t)=>{const A=Er(ee.props),x=ee.target=ha(ee.props,K),ie=va(x,ee,W,O);x&&(c!=="svg"&&Wl(x)?c="svg":c!=="mathml"&&zl(x)&&(c="mathml"),o&&o.isCE&&(o.ce._teleportTargets||(o.ce._teleportTargets=new Set)).add(x),A||(Q(ee,x,ie),ms(ee,!1)))},ce=ee=>{const A=()=>{if(Zn.get(ee)===A){if(Zn.delete(ee),Er(ee.props)){const x=Z(ee.el)||n;Q(ee,x,ee.anchor),ms(ee,!0)}le(ee)}};Zn.set(ee,A),Ht(A,a)};if(e==null){const ee=t.el=W(""),A=t.anchor=W("");if(O(ee,n,s),O(A,n,s),Hd(t.props)||a&&a.pendingBranch){ce(t);return}E&&(Q(t,n,A),ms(t,!0)),le()}else{t.el=e.el;const ee=t.anchor=e.anchor,A=Zn.get(e);if(A){A.flags|=8,Zn.delete(e),ce(t);return}t.targetStart=e.targetStart;const x=t.target=e.target,ie=t.targetAnchor=e.targetAnchor,xe=Er(e.props),J=xe?n:x,Ce=xe?ee:ie;if(c==="svg"||Wl(x)?c="svg":(c==="mathml"||zl(x))&&(c="mathml"),L?(D(e.dynamicChildren,L,J,o,a,c,d),Ya(e,t,!0)):h||k(e,t,J,Ce,o,a,c,d,!1),E)xe?t.props&&e.props&&t.props.to!==e.props.to&&(t.props.to=e.props.to):_o(t,n,ee,y,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){const Ke=ha(t.props,K);Ke&&(t.target=Ke,_o(t,Ke,null,y,0))}else xe&&_o(t,x,ie,y,1);ms(t,E)}},remove(e,t,n,{um:s,o:{remove:o}},a){const{shapeFlag:c,children:d,anchor:h,targetStart:y,targetAnchor:m,target:k,props:D}=e,O=Er(D),K=a||!O,W=Zn.get(e);if(W&&(W.flags|=8,Zn.delete(e)),k&&(o(y),o(m)),a&&o(h),!W&&(O||k)&&c&16)for(let de=0;de{e.isMounted=!0}),xc(()=>{e.isUnmounting=!0}),e}const sn=[Function,Array],yc={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:sn,onEnter:sn,onAfterEnter:sn,onEnterCancelled:sn,onBeforeLeave:sn,onLeave:sn,onAfterLeave:sn,onLeaveCancelled:sn,onBeforeAppear:sn,onAppear:sn,onAfterAppear:sn,onAppearCancelled:sn},Gd={name:"BaseTransition",props:yc,setup(e,{slots:t}){const n=Ja(),s=mc();return()=>{const o=t.default&&Wa(t.default(),!0),a=o&&o.length?gc(o):n.subTree?Ee():void 0;if(!a)return;const c=rt(e),{mode:d}=c;if(s.isLeaving)return Zi(a);const h=jo(a);if(!h)return Zi(a);let y=Os(h,c,s,n,k=>y=k);h.type!==Ft&&ar(h,y);let m=n.subTree&&jo(n.subTree);if(m&&m.type!==Ft&&!$r(m,h)&&Ms(n.subTree)){let k=Os(m,c,s,n);if(ar(m,k),d==="out-in"&&h.type!==Ft)return s.isLeaving=!0,k.afterLeave=()=>{s.isLeaving=!1,n.job.flags&8||n.update(),delete k.afterLeave,m=void 0},Zi(a);d==="in-out"&&h.type!==Ft?k.delayLeave=(D,O,K)=>{const W=bc(s,m);W[String(m.key)]=m,D[on]=()=>{O(),D[on]=void 0,delete y.delayedLeave,m=void 0},y.delayedLeave=()=>{K(),delete y.delayedLeave,m=void 0}}:m=void 0}else m&&(m=void 0);return a}}};function gc(e){let t=e[0];if(e.length>1){for(const n of e)if(n.type!==Ft){t=n;break}}return t}const Yd=Gd;function bc(e,t){const{leavingVNodes:n}=e;let s=n.get(t.type);return s||(s=Object.create(null),n.set(t.type,s)),s}function Os(e,t,n,s,o){const{appear:a,mode:c,persisted:d=!1,onBeforeEnter:h,onEnter:y,onAfterEnter:m,onEnterCancelled:k,onBeforeLeave:D,onLeave:O,onAfterLeave:K,onLeaveCancelled:W,onBeforeAppear:de,onAppear:Z,onAfterAppear:E,onAppearCancelled:L}=t,Q=String(e.key),le=bc(n,e),ce=(x,ie)=>{x&&cn(x,s,9,ie)},ee=(x,ie)=>{const xe=ie[1];ce(x,ie),Le(x)?x.every(J=>J.length<=1)&&xe():x.length<=1&&xe()},A={mode:c,persisted:d,beforeEnter(x){let ie=h;if(!n.isMounted)if(a)ie=de||h;else return;x[on]&&x[on](!0);const xe=le[Q];if(xe&&$r(e,xe)){let J=xe.el[on];if(!J){const Ce=Ms(xe);J=Ce&&Ce.el[on]}J&&J()}ce(ie,[x])},enter(x){if(le[Q]===e)return;let ie=y,xe=m,J=k;if(!n.isMounted)if(a)ie=Z||y,xe=E||m,J=L||k;else return;let Ce=!1;x[hs]=Xe=>{Ce||(Ce=!0,Xe?ce(J,[x]):ce(xe,[x]),A.delayedLeave&&A.delayedLeave(),x[hs]=void 0)};const Ke=x[hs].bind(null,!1);ie?ee(ie,[x,Ke]):Ke()},leave(x,ie){const xe=String(e.key);if(x[hs]&&x[hs](!0),n.isUnmounting)return ie();ce(D,[x]);let J=!1;x[on]=Ke=>{J||(J=!0,ie(),Ke?ce(W,[x]):ce(K,[x]),x[on]=void 0,le[xe]===e&&delete le[xe])};const Ce=x[on].bind(null,!1);le[xe]=e,O?ee(O,[x,Ce]):Ce()},clone(x){const ie=Os(x,t,n,s,o);return o&&o(ie),ie}};return A}function Zi(e){if(si(e))return e=lr(e),e.children=null,e}function jo(e){if(!si(e))return ri(e.type)&&e.children?gc(e.children):e;if(e.component)return e.component.subTree;const{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&ze(n.default))return n.default()}}function ar(e,t){if(e.shapeFlag&6&&e.component){e.transition=t;const n=e.component.subTree;ar(ri(n.type)&&jo(n)||n,t)}else if(e.shapeFlag&128)e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback);else if(e.transition=t,e.type===Re&&Le(e.children)){const n=Ac(e.children,!1);n&&ar(n,t)}}function Wa(e,t=!1,n){let s=[],o=0;for(let a=0;a1)for(let a=0;aks(W,t&&(Le(t)?t[de]:t),n,s,o));return}if(xs(s)&&!o){s.shapeFlag&512&&s.type.__asyncResolved&&s.component.subTree.component&&ks(e,t,n,s.component.subTree);return}const a=s.shapeFlag&4?li(s.component):s.el,c=o?null:a,{i:d,r:h}=e,y=t&&t.r,m=d.refs===ct?d.refs={}:d.refs,k=d.setupState,D=rt(k),O=k===ct?Ru:W=>Gl(m,W)?!1:ot(D,W),K=(W,de)=>!(de&&Gl(m,de));if(y!=null&&y!==h){if(Yl(t),bt(y))m[y]=null,O(y)&&(k[y]=null);else if(Nt(y)){const W=t;K(y,W.k)&&(y.value=null),W.k&&(m[W.k]=null)}}if(ze(h))Ns(h,d,12,[c,m]);else{const W=bt(h),de=Nt(h);if(W||de){const Z=()=>{if(e.f){const E=W?O(h)?k[h]:m[h]:K()||!e.k?h.value:m[e.k];if(o)Le(E)&&ja(E,a);else if(Le(E))E.includes(a)||E.push(a);else if(W)m[h]=[a],O(h)&&(k[h]=m[h]);else{const L=[a];K(h,e.k)&&(h.value=L),e.k&&(m[e.k]=L)}}else W?(m[h]=c,O(h)&&(k[h]=c)):de&&(K(h,e.k)&&(h.value=c),e.k&&(m[e.k]=c))};if(c){const E=()=>{Z(),Do.delete(e)};E.id=-1,Do.set(e,E),Ht(E,n)}else Yl(e),Z()}}}function Yl(e){const t=Do.get(e);t&&(t.flags|=8,Do.delete(e))}ei().requestIdleCallback;ei().cancelIdleCallback;const xs=e=>!!e.type.__asyncLoader,si=e=>e.type.__isKeepAlive;function Jd(e,t){_c(e,"a",t)}function Xd(e,t){_c(e,"da",t)}function _c(e,t,n=zt){const s=e.__wdc||(e.__wdc=()=>{let o=n;for(;o;){if(o.isDeactivated)return;o=o.parent}return e()});if(oi(t,s,n),n){let o=n.parent;for(;o&&o.parent;)si(o.parent.vnode)&&Qd(s,t,n,o),o=o.parent}}function Qd(e,t,n,s){const o=oi(t,e,s,!0);dr(()=>{ja(s[t],o)},n)}function oi(e,t,n=zt,s=!1){if(n){const o=n[e]||(n[e]=[]),a=t.__weh||(t.__weh=(...c)=>{An();const d=Bs(n),h=cn(t,n,e,c);return d(),Pn(),h});return s?o.unshift(a):o.push(a),a}}const qn=e=>(t,n=zt)=>{(!Rs||e==="sp")&&oi(e,(...s)=>t(...s),n)},Zd=qn("bm"),fn=qn("m"),ep=qn("bu"),kc=qn("u"),xc=qn("bum"),dr=qn("um"),tp=qn("sp"),np=qn("rtg"),rp=qn("rtc");function sp(e,t=zt){oi("ec",e,t)}const op=Symbol.for("v-ndc");function ut(e,t,n,s){let o;const a=n,c=Le(e);if(c||bt(e)){const d=c&&or(e);let h=!1,y=!1;d&&(h=!ln(e),y=Tn(e),e=ti(e)),o=new Array(e.length);for(let m=0,k=e.length;mt(d,h,void 0,a));else{const d=Object.keys(e);o=new Array(d.length);for(let h=0,y=d.length;he?qc(e)?li(e):ma(e.parent):null,Cs=Et(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>ma(e.parent),$root:e=>ma(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Sc(e),$forceUpdate:e=>e.f||(e.f=()=>{Ha(e.update)}),$nextTick:e=>e.n||(e.n=ts.bind(e.proxy)),$watch:e=>qd.bind(e)}),ea=(e,t)=>e!==ct&&!e.__isScriptSetup&&ot(e,t),ip={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:n,setupState:s,data:o,props:a,accessCache:c,type:d,appContext:h}=e;if(t[0]!=="$"){const D=c[t];if(D!==void 0)switch(D){case 1:return s[t];case 2:return o[t];case 4:return n[t];case 3:return a[t]}else{if(ea(s,t))return c[t]=1,s[t];if(o!==ct&&ot(o,t))return c[t]=2,o[t];if(ot(a,t))return c[t]=3,a[t];if(n!==ct&&ot(n,t))return c[t]=4,n[t];ya&&(c[t]=0)}}const y=Cs[t];let m,k;if(y)return t==="$attrs"&&Kt(e.attrs,"get",""),y(e);if((m=d.__cssModules)&&(m=m[t]))return m;if(n!==ct&&ot(n,t))return c[t]=4,n[t];if(k=h.config.globalProperties,ot(k,t))return k[t]},set({_:e},t,n){const{data:s,setupState:o,ctx:a}=e;return ea(o,t)?(o[t]=n,!0):s!==ct&&ot(s,t)?(s[t]=n,!0):ot(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(a[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:s,appContext:o,props:a,type:c}},d){let h;return!!(n[d]||e!==ct&&d[0]!=="$"&&ot(e,d)||ea(t,d)||ot(a,d)||ot(s,d)||ot(Cs,d)||ot(o.config.globalProperties,d)||(h=c.__cssModules)&&h[d])},defineProperty(e,t,n){return n.get!=null?e._.accessCache[t]=0:ot(n,"value")&&this.set(e,t,n.value,null),Reflect.defineProperty(e,t,n)}};function Jl(e){return Le(e)?e.reduce((t,n)=>(t[n]=null,t),{}):e}let ya=!0;function ap(e){const t=Sc(e),n=e.proxy,s=e.ctx;ya=!1,t.beforeCreate&&Xl(t.beforeCreate,e,"bc");const{data:o,computed:a,methods:c,watch:d,provide:h,inject:y,created:m,beforeMount:k,mounted:D,beforeUpdate:O,updated:K,activated:W,deactivated:de,beforeDestroy:Z,beforeUnmount:E,destroyed:L,unmounted:Q,render:le,renderTracked:ce,renderTriggered:ee,errorCaptured:A,serverPrefetch:x,expose:ie,inheritAttrs:xe,components:J,directives:Ce,filters:Ke}=t;if(y&&lp(y,s,null),c)for(const Ue in c){const ge=c[Ue];ze(ge)&&(s[Ue]=ge.bind(n))}if(o){const Ue=o.call(n,n);at(Ue)&&(e.data=Ba(Ue))}if(ya=!0,a)for(const Ue in a){const ge=a[Ue],Me=ze(ge)?ge.bind(n,n):ze(ge.get)?ge.get.bind(n,n):En,Fe=!ze(ge)&&ze(ge.set)?ge.set.bind(n):En,fe=it({get:Me,set:Fe});Object.defineProperty(s,Ue,{enumerable:!0,configurable:!0,get:()=>fe.value,set:G=>fe.value=G})}if(d)for(const Ue in d)Cc(d[Ue],s,n,Ue);if(h){const Ue=ze(h)?h.call(n):h;Reflect.ownKeys(Ue).forEach(ge=>{Vd(ge,Ue[ge])})}m&&Xl(m,e,"c");function He(Ue,ge){Le(ge)?ge.forEach(Me=>Ue(Me.bind(n))):ge&&Ue(ge.bind(n))}if(He(Zd,k),He(fn,D),He(ep,O),He(kc,K),He(Jd,W),He(Xd,de),He(sp,A),He(rp,ce),He(np,ee),He(xc,E),He(dr,Q),He(tp,x),Le(ie))if(ie.length){const Ue=e.exposed||(e.exposed={});ie.forEach(ge=>{Object.defineProperty(Ue,ge,{get:()=>n[ge],set:Me=>n[ge]=Me,enumerable:!0})})}else e.exposed||(e.exposed={});le&&e.render===En&&(e.render=le),xe!=null&&(e.inheritAttrs=xe),J&&(e.components=J),Ce&&(e.directives=Ce),x&&wc(e)}function lp(e,t,n=En){Le(e)&&(e=ga(e));for(const s in e){const o=e[s];let a;at(o)?"default"in o?a=Eo(o.from||s,o.default,!0):a=Eo(o.from||s):a=Eo(o),Nt(a)?Object.defineProperty(t,s,{enumerable:!0,configurable:!0,get:()=>a.value,set:c=>a.value=c}):t[s]=a}}function Xl(e,t,n){cn(Le(e)?e.map(s=>s.bind(t.proxy)):e.bind(t.proxy),t,n)}function Cc(e,t,n,s){let o=s.includes(".")?hc(n,s):()=>n[s];if(bt(e)){const a=t[e];ze(a)&>(o,a)}else if(ze(e))gt(o,e.bind(n));else if(at(e))if(Le(e))e.forEach(a=>Cc(a,t,n,s));else{const a=ze(e.handler)?e.handler.bind(n):t[e.handler];ze(a)&>(o,a,e)}}function Sc(e){const t=e.type,{mixins:n,extends:s}=t,{mixins:o,optionsCache:a,config:{optionMergeStrategies:c}}=e.appContext,d=a.get(t);let h;return d?h=d:!o.length&&!n&&!s?h=t:(h={},o.length&&o.forEach(y=>Ro(h,y,c,!0)),Ro(h,t,c)),at(t)&&a.set(t,h),h}function Ro(e,t,n,s=!1){const{mixins:o,extends:a}=t;a&&Ro(e,a,n,!0),o&&o.forEach(c=>Ro(e,c,n,!0));for(const c in t)if(!(s&&c==="expose")){const d=up[c]||n&&n[c];e[c]=d?d(e[c],t[c]):t[c]}return e}const up={data:Ql,props:Zl,emits:Zl,methods:ys,computed:ys,beforeCreate:qt,created:qt,beforeMount:qt,mounted:qt,beforeUpdate:qt,updated:qt,beforeDestroy:qt,beforeUnmount:qt,destroyed:qt,unmounted:qt,activated:qt,deactivated:qt,errorCaptured:qt,serverPrefetch:qt,components:ys,directives:ys,watch:fp,provide:Ql,inject:cp};function Ql(e,t){return t?e?function(){return Et(ze(e)?e.call(this,this):e,ze(t)?t.call(this,this):t)}:t:e}function cp(e,t){return ys(ga(e),ga(t))}function ga(e){if(Le(e)){const t={};for(let n=0;nt==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${hn(t)}Modifiers`]||e[`${cr(t)}Modifiers`];function vp(e,t,...n){if(e.isUnmounted)return;const s=e.vnode.props||ct;let o=n;const a=t.startsWith("update:"),c=a&&hp(s,t.slice(7));c&&(c.trim&&(o=n.map(m=>bt(m)?m.trim():m)),c.number&&(o=o.map(Zo)));let d,h=s[d=zi(t)]||s[d=zi(hn(t))];!h&&a&&(h=s[d=zi(cr(t))]),h&&cn(h,e,6,o);const y=s[d+"Once"];if(y){if(!e.emitted)e.emitted={};else if(e.emitted[d])return;e.emitted[d]=!0,cn(y,e,6,o)}}const mp=new WeakMap;function $c(e,t,n=!1){const s=n?mp:t.emitsCache,o=s.get(e);if(o!==void 0)return o;const a=e.emits;let c={},d=!1;if(!ze(e)){const h=y=>{const m=$c(y,t,!0);m&&(d=!0,Et(c,m))};!n&&t.mixins.length&&t.mixins.forEach(h),e.extends&&h(e.extends),e.mixins&&e.mixins.forEach(h)}return!a&&!d?(at(e)&&s.set(e,null),null):(Le(a)?a.forEach(h=>c[h]=null):Et(c,a),at(e)&&s.set(e,c),c)}function ii(e,t){return!e||!Jo(t)?!1:(t=t.slice(2),t=t==="Once"?t:t.replace(/Once$/,""),ot(e,t[0].toLowerCase()+t.slice(1))||ot(e,cr(t))||ot(e,t))}function eu(e){const{type:t,vnode:n,proxy:s,withProxy:o,propsOptions:[a],slots:c,attrs:d,emit:h,render:y,renderCache:m,props:k,data:D,setupState:O,ctx:K,inheritAttrs:W}=e,de=Io(e);let Z,E;try{if(n.shapeFlag&4){const Q=o||s,le=Q;Z=xn(y.call(le,Q,m,k,O,D,K)),E=d}else{const Q=t;Z=xn(Q.length>1?Q(k,{attrs:d,slots:c,emit:h}):Q(k,null)),E=t.props?d:yp(d)}}catch(Q){Tr.length=0,ni(Q,e,1),Z=Oe(Ft)}let L=Z;if(E&&W!==!1){const Q=Object.keys(E),{shapeFlag:le}=L;Q.length&&le&7&&(a&&Q.some(Xo)&&(E=gp(E,a)),L=lr(L,E,!1,!0))}if(n.dirs&&(L=lr(L,null,!1,!0),L.dirs=L.dirs?L.dirs.concat(n.dirs):n.dirs),n.transition){const Q=ri(L.type)&&jo(L)||L;ar(Q,n.transition)}return Z=L,Io(de),Z}function Ac(e,t=!0){let n;for(let s=0;s{let t;for(const n in e)(n==="class"||n==="style"||Jo(n))&&((t||(t={}))[n]=e[n]);return t},gp=(e,t)=>{const n={};for(const s in e)(!Xo(s)||!(s.slice(9)in t))&&(n[s]=e[s]);return n};function bp(e,t,n){const{props:s,children:o,component:a}=e,{props:c,children:d,patchFlag:h}=t,y=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&h>=0){if(h&1024)return!0;if(h&16)return s?tu(s,c,y):!!c;if(h&8){const m=t.dynamicProps;for(let k=0;kObject.create(Tc),Mc=e=>Object.getPrototypeOf(e)===Tc;function _p(e,t,n,s=!1){const o={},a=Oc();e.propsDefaults=Object.create(null),Ic(e,t,o,a);for(const c in e.propsOptions[0])c in o||(o[c]=void 0);n?e.props=s?o:Ad(o):e.type.props?e.props=o:e.props=a,e.attrs=a}function kp(e,t,n,s){const{props:o,attrs:a,vnode:{patchFlag:c}}=e,d=rt(o),[h]=e.propsOptions;let y=!1;if((s||c>0)&&!(c&16)){if(c&8){const m=e.vnode.dynamicProps;for(let k=0;k{h=!0;const[D,O]=jc(k,t,!0);Et(c,D),O&&d.push(...O)};!n&&t.mixins.length&&t.mixins.forEach(m),e.extends&&m(e.extends),e.mixins&&e.mixins.forEach(m)}if(!a&&!h)return at(e)&&s.set(e,Ar),Ar;if(Le(a))for(let m=0;me==="_"||e==="_ctx"||e==="$stable",Ga=e=>Le(e)?e.map(xn):[xn(e)],Cp=(e,t,n)=>{if(t._n)return t;const s=fr((...o)=>Ga(t(...o)),n);return s._c=!1,s},Dc=(e,t,n)=>{const s=e._ctx;for(const o in e){if(za(o))continue;const a=e[o];if(ze(a))t[o]=Cp(o,a,s);else if(a!=null){const c=Ga(a);t[o]=()=>c}}},Rc=(e,t)=>{const n=Ga(t);e.slots.default=()=>n},Lc=(e,t,n)=>{for(const s in t)(n||!za(s))&&(e[s]=t[s])},Sp=(e,t,n)=>{const s=e.slots=Oc();if(e.vnode.shapeFlag&32){const o=t._;o?(Lc(s,t,n),n&&Vu(s,"_",o,!0)):Dc(t,s)}else t&&Rc(e,t)},Ep=(e,t,n)=>{const{vnode:s,slots:o}=e;let a=!0,c=ct;if(s.shapeFlag&32){const d=t._;d?n&&d===1?a=!1:Lc(o,t,n):(a=!t.$stable,Dc(t,o)),c=t}else t&&(Rc(e,t),c={default:1});if(a)for(const d in o)!za(d)&&c[d]==null&&delete o[d]},Ht=Op;function $p(e){return Ap(e)}function Ap(e,t){const n=ei();n.__VUE__=!0;const{insert:s,remove:o,patchProp:a,createElement:c,createText:d,createComment:h,setText:y,setElementText:m,parentNode:k,nextSibling:D,setScopeId:O=En,insertStaticContent:K}=e,W=(w,g,P,ae=null,se=null,ue=null,ye=void 0,oe=null,we=!!g.dynamicChildren)=>{if(w===g)return;w&&!$r(w,g)&&(ae=ht(w),G(w,se,ue,!0),w=null),g.patchFlag===-2&&(we=!1,g.dynamicChildren=null),g.dynamicChildren&&w&&w.dynamicChildren&&w.dynamicChildren.hasOnce&&(g.dynamicChildren===Ar&&(g.dynamicChildren=[]),g.dynamicChildren.hasOnce=!0);const{type:H,ref:U,shapeFlag:Y}=g;switch(H){case ai:de(w,g,P,ae);break;case Ft:Z(w,g,P,ae);break;case $o:w==null&&E(g,P,ae,ye);break;case Re:J(w,g,P,ae,se,ue,ye,oe,we);break;default:Y&1?le(w,g,P,ae,se,ue,ye,oe,we):Y&6?Ce(w,g,P,ae,se,ue,ye,oe,we):(Y&64||Y&128)&&H.process(w,g,P,ae,se,ue,ye,oe,we,Jt)}U!=null&&se?ks(U,w&&w.ref,ue,g||w,!g):U==null&&w&&w.ref!=null&&ks(w.ref,null,ue,w,!0)},de=(w,g,P,ae)=>{if(w==null)s(g.el=d(g.children),P,ae);else{const se=g.el=w.el;g.children!==w.children&&y(se,g.children)}},Z=(w,g,P,ae)=>{w==null?s(g.el=h(g.children||""),P,ae):g.el=w.el},E=(w,g,P,ae)=>{[w.el,w.anchor]=K(w.children,g,P,ae,w.el,w.anchor)},L=({el:w,anchor:g},P,ae)=>{let se;for(;w&&w!==g;)se=D(w),s(w,P,ae),w=se;s(g,P,ae)},Q=({el:w,anchor:g})=>{let P;for(;w&&w!==g;)P=D(w),o(w),w=P;o(g)},le=(w,g,P,ae,se,ue,ye,oe,we)=>{if(g.type==="svg"?ye="svg":g.type==="math"&&(ye="mathml"),w==null)ce(g,P,ae,se,ue,ye,oe,we);else{const H=w.el&&w.el._isVueCE?w.el:null;try{H&&H._beginPatch(),x(w,g,se,ue,ye,oe,we)}finally{H&&H._endPatch()}}},ce=(w,g,P,ae,se,ue,ye,oe)=>{let we,H;const{props:U,shapeFlag:Y,transition:Ae,dirs:Ne}=w;if(we=w.el=c(w.type,ue,U&&U.is,U),Y&8?m(we,w.children):Y&16&&A(w.children,we,null,ae,se,ta(w,ue),ye,oe),Ne&&_r(w,null,ae,"created"),ee(we,w,w.scopeId,ye,ae),U){for(const Ye in U)Ye!=="value"&&!bs(Ye)&&a(we,Ye,null,U[Ye],ue,ae);"value"in U&&a(we,"value",null,U.value,ue),(H=U.onVnodeBeforeMount)&&gn(H,ae,w)}Ne&&_r(w,null,ae,"beforeMount");const Je=Pp(se,Ae);Je&&Ae.beforeEnter(we),s(we,g,P),((H=U&&U.onVnodeMounted)||Je||Ne)&&Ht(()=>{try{H&&gn(H,ae,w),Je&&Ae.enter(we),Ne&&_r(w,null,ae,"mounted")}finally{}},se)},ee=(w,g,P,ae,se)=>{if(P&&O(w,P),ae)for(let ue=0;ue{for(let H=we;H{const oe=g.el=w.el;let{patchFlag:we,dynamicChildren:H,dirs:U}=g;we|=w.patchFlag&16;const Y=w.props||ct,Ae=g.props||ct;let Ne;if(P&&kr(P,!1),(Ne=Ae.onVnodeBeforeUpdate)&&gn(Ne,P,g,w),U&&_r(g,w,P,"beforeUpdate"),P&&kr(P,!0),H&&(!w.dynamicChildren||w.dynamicChildren.length!==H.length)&&(we=0,ye=!1,H=null),(Y.innerHTML&&Ae.innerHTML==null||Y.textContent&&Ae.textContent==null)&&m(oe,""),H?ie(w.dynamicChildren,H,oe,P,ae,ta(g,se),ue):ye||ge(w,g,oe,null,P,ae,ta(g,se),ue,!1),we>0){if(we&16)xe(oe,Y,Ae,P,se);else if(we&2&&Y.class!==Ae.class&&a(oe,"class",null,Ae.class,se),we&4&&a(oe,"style",Y.style,Ae.style,se),we&8){const Je=g.dynamicProps;for(let Ye=0;Ye{Ne&&gn(Ne,P,g,w),U&&_r(g,w,P,"updated")},ae)},ie=(w,g,P,ae,se,ue,ye)=>{for(let oe=0;oe{if(g!==P){if(g!==ct)for(const ue in g)!bs(ue)&&!(ue in P)&&a(w,ue,g[ue],null,se,ae);for(const ue in P){if(bs(ue))continue;const ye=P[ue],oe=g[ue];ye!==oe&&ue!=="value"&&a(w,ue,oe,ye,se,ae)}"value"in P&&a(w,"value",g.value,P.value,se)}},J=(w,g,P,ae,se,ue,ye,oe,we)=>{const H=g.el=w?w.el:d(""),U=g.anchor=w?w.anchor:d("");let{patchFlag:Y,dynamicChildren:Ae,slotScopeIds:Ne}=g;Ne&&(oe=oe?oe.concat(Ne):Ne),w==null?(s(H,P,ae),s(U,P,ae),A(g.children||[],P,U,se,ue,ye,oe,we)):Y>0&&Y&64&&Ae&&w.dynamicChildren&&w.dynamicChildren.length===Ae.length?(ie(w.dynamicChildren,Ae,P,se,ue,ye,oe),(g.key!=null||se&&g===se.subTree)&&Ya(w,g,!0)):ge(w,g,P,U,se,ue,ye,oe,we)},Ce=(w,g,P,ae,se,ue,ye,oe,we)=>{g.slotScopeIds=oe,w==null?g.shapeFlag&512?se.ctx.activate(g,P,ae,ye,we):Ke(g,P,ae,se,ue,ye,we):Xe(w,g,we)},Ke=(w,g,P,ae,se,ue,ye)=>{const oe=w.component=Kp(w,ae,se);if(si(w)&&(oe.ctx.renderer=Jt),Fp(oe,!1,ye),oe.asyncDep){if(se&&se.registerDep(oe,He,ye,ue),!w.el){const we=oe.subTree=Oe(Ft);Z(null,we,g,P),w.placeholder=we.el}}else He(oe,w,g,P,se,ue,ye)},Xe=(w,g,P)=>{const ae=g.component=w.component;if(bp(w,g,P))if(ae.asyncDep&&!ae.asyncResolved){g.el=w.el,g.placeholder=w.placeholder,Ue(ae,g,P);return}else ae.next=g,ae.update();else g.el=w.el,g.placeholder=w.placeholder,ae.vnode=g},He=(w,g,P,ae,se,ue,ye)=>{const oe=()=>{if(w.isMounted){let{next:Y,bu:Ae,u:Ne,parent:Je,vnode:Ye}=w;{const Bt=Kc(w);if(Bt){Y&&(Y.el=Ye.el,Ue(w,Y,ye)),Bt.asyncDep.then(()=>{Ht(()=>{w.isUnmounted||H()},se)});return}}let Qe=Y,vt;kr(w,!1),Y?(Y.el=Ye.el,Ue(w,Y,ye)):Y=Ye,Ae&&So(Ae),(vt=Y.props&&Y.props.onVnodeBeforeUpdate)&&gn(vt,Je,Y,Ye),kr(w,!0);const _t=eu(w),Xt=w.subTree;w.subTree=_t,W(Xt,_t,k(Xt.el),ht(Xt),w,se,ue),Y.el=_t.el,Qe===null&&wp(w,_t.el),Ne&&Ht(Ne,se),(vt=Y.props&&Y.props.onVnodeUpdated)&&Ht(()=>gn(vt,Je,Y,Ye),se)}else{let Y;const{el:Ae,props:Ne}=g,{bm:Je,m:Ye,parent:Qe,root:vt,type:_t}=w,Xt=xs(g);kr(w,!1),Je&&So(Je),!Xt&&(Y=Ne&&Ne.onVnodeBeforeMount)&&gn(Y,Qe,g),kr(w,!0);{vt.ce&&vt.ce._hasShadowRoot()&&vt.ce._injectChildStyle(_t,w.parent?w.parent.type:void 0);const Bt=w.subTree=eu(w);W(null,Bt,P,ae,w,se,ue),g.el=Bt.el}if(Ye&&Ht(Ye,se),!Xt&&(Y=Ne&&Ne.onVnodeMounted)){const Bt=g;Ht(()=>gn(Y,Qe,Bt),se)}(g.shapeFlag&256||Qe&&xs(Qe.vnode)&&Qe.vnode.shapeFlag&256)&&w.a&&Ht(w.a,se),w.isMounted=!0,g=P=ae=null}};w.scope.on();const we=w.effect=new Hu(oe);w.scope.off();const H=w.update=we.run.bind(we),U=w.job=we.runIfDirty.bind(we);U.i=w,U.id=w.uid,we.scheduler=()=>Ha(U),kr(w,!0),H()},Ue=(w,g,P)=>{g.component=w;const ae=w.vnode.props;w.vnode=g,w.next=null,kp(w,g.props,ae,P),Ep(w,g.children,P),An(),uc(w),Pn()},ge=(w,g,P,ae,se,ue,ye,oe,we=!1)=>{const H=w&&w.children,U=w?w.shapeFlag:0,Y=g.children,{patchFlag:Ae,shapeFlag:Ne}=g;if(Ae>0){if(Ae&128){Fe(H,Y,P,ae,se,ue,ye,oe,we);return}else if(Ae&256){Me(H,Y,P,ae,se,ue,ye,oe,we);return}}Ne&8?(U&16&&pt(H,se,ue),Y!==H&&m(P,Y)):U&16?Ne&16?Fe(H,Y,P,ae,se,ue,ye,oe,we):pt(H,se,ue,!0):(U&8&&m(P,""),Ne&16&&A(Y,P,ae,se,ue,ye,oe,we))},Me=(w,g,P,ae,se,ue,ye,oe,we)=>{w=w||Ar,g=g||Ar;const H=w.length,U=g.length,Y=Math.min(H,U);let Ae;for(Ae=0;AeU?pt(w,se,ue,!0,!1,Y):A(g,P,ae,se,ue,ye,oe,we,Y)},Fe=(w,g,P,ae,se,ue,ye,oe,we)=>{let H=0;const U=g.length;let Y=w.length-1,Ae=U-1;for(;H<=Y&&H<=Ae;){const Ne=w[H],Je=g[H]=we?Dn(g[H]):xn(g[H]);if($r(Ne,Je))W(Ne,Je,P,null,se,ue,ye,oe,we);else break;H++}for(;H<=Y&&H<=Ae;){const Ne=w[Y],Je=g[Ae]=we?Dn(g[Ae]):xn(g[Ae]);if($r(Ne,Je))W(Ne,Je,P,null,se,ue,ye,oe,we);else break;Y--,Ae--}if(H>Y){if(H<=Ae){const Ne=Ae+1,Je=NeAe)for(;H<=Y;)G(w[H],se,ue,!0),H++;else{const Ne=H,Je=H,Ye=new Map;for(H=Je;H<=Ae;H++){const Ot=g[H]=we?Dn(g[H]):xn(g[H]);Ot.key!=null&&Ye.set(Ot.key,H)}let Qe,vt=0;const _t=Ae-Je+1;let Xt=!1,Bt=0;const Zt=new Array(_t);for(H=0;H<_t;H++)Zt[H]=0;for(H=Ne;H<=Y;H++){const Ot=w[H];if(vt>=_t){G(Ot,se,ue,!0);continue}let $t;if(Ot.key!=null)$t=Ye.get(Ot.key);else for(Qe=Je;Qe<=Ae;Qe++)if(Zt[Qe-Je]===0&&$r(Ot,g[Qe])){$t=Qe;break}$t===void 0?G(Ot,se,ue,!0):(Zt[$t-Je]=H+1,$t>=Bt?Bt=$t:Xt=!0,W(Ot,g[$t],P,null,se,ue,ye,oe,we),vt++)}const pr=Xt?Tp(Zt):Ar;for(Qe=pr.length-1,H=_t-1;H>=0;H--){const Ot=Je+H,$t=g[Ot],Ie=g[Ot+1],Hn=Ot+1{const{el:ue,type:ye,transition:oe,children:we,shapeFlag:H}=w;if(H&6){fe(w.component.subTree,g,P,ae);return}if(H&128){w.suspense.move(g,P,ae);return}if(H&64){ye.move(w,g,P,Jt);return}if(ye===Re){s(ue,g,P);for(let Y=0;Yoe.enter(ue),se));else{const{leave:Y,delayLeave:Ae,afterLeave:Ne}=oe,Je=()=>{w.ctx.isUnmounted?o(ue):s(ue,g,P)},Ye=()=>{const Qe=ue._isLeaving||!!ue[on];ue._isLeaving&&ue[on](!0),oe.persisted&&!Qe?Je():Y(ue,()=>{Je(),Ne&&Ne()})};Ae?Ae(ue,Je,Ye):Ye()}else s(ue,g,P)},G=(w,g,P,ae=!1,se=!1)=>{const{type:ue,props:ye,ref:oe,children:we,dynamicChildren:H,shapeFlag:U,patchFlag:Y,dirs:Ae,cacheIndex:Ne,memo:Je}=w;if((Y===-2||H&&H.hasOnce)&&(se=!1),oe!=null&&(An(),ks(oe,null,P,w,!0),Pn()),Ne!=null&&(!w.ctx||w.ctx===g)&&(g.renderCache[Ne]=void 0),U&256){g.ctx.deactivate(w);return}const Ye=U&1&&Ae,Qe=!xs(w);let vt;if(Qe&&(vt=ye&&ye.onVnodeBeforeUnmount)&&gn(vt,g,w),U&6)st(w.component,P,ae);else{if(U&128){w.suspense.unmount(P,ae);return}Ye&&_r(w,null,g,"beforeUnmount"),U&64?w.type.remove(w,g,P,Jt,ae):H&&!H.hasOnce&&(ue!==Re||Y>0&&Y&64)?pt(H,g,P,!1,!0):(ue===Re&&Y&384||!se&&U&16)&&pt(we,g,P),ae&&X(w)}const _t=Je!=null&&Ne==null;(Qe&&(vt=ye&&ye.onVnodeUnmounted)||Ye||_t)&&Ht(()=>{vt&&gn(vt,g,w),Ye&&_r(w,null,g,"unmounted"),_t&&(w.el=null)},P)},X=w=>{const{type:g,el:P,anchor:ae,transition:se}=w,ue=g===Re;if(ue&&!se){ke(P,ae);return}if(g===$o){Q(w),se&&!se.persisted&&se.afterLeave&&se.afterLeave();return}const ye=ue?Ms(w):w,oe=()=>{ue?k(P)&&ke(P,ae):o(P),se&&!se.persisted&&se.afterLeave&&se.afterLeave()};if(ye&&ye.shapeFlag&1&&se&&!se.persisted){const{leave:we,delayLeave:H}=se,U=ye.el,Y=()=>we(U,oe);H?H(U,oe,Y):Y()}else oe()},ke=(w,g)=>{let P;for(;w!==g;)P=D(w),o(w),w=P;o(g)},st=(w,g,P)=>{const{bum:ae,scope:se,job:ue,subTree:ye,um:oe,m:we,a:H}=w;ru(we),ru(H),ae&&So(ae),se.stop(),ue?(ue.flags|=8,G(ye,w,g,P)):w.vnode.el&&ye&&(ye.transition=w.vnode.transition,G(ye,w,g,P)),oe&&Ht(oe,g),Ht(()=>{w.isUnmounted=!0},g)},pt=(w,g,P,ae=!1,se=!1,ue=0)=>{for(let ye=ue;ye{if(w.shapeFlag&6)return ht(w.component.subTree);if(w.shapeFlag&128)return w.suspense.next();const g=D(w.anchor||w.el),P=g&&g[vc];return P?D(P):g},Yt=(w,g,P)=>{const ae=w&&g._vnode?void 0:w&&w.component?w.component.uid:Lp();Nd(()=>{w==null?g._vnode&&G(g._vnode,null,null,!0):W(g._vnode||null,w,g,null,null,null,P),g._vnode=w},ae)},Jt={p:W,um:G,m:fe,r:X,mt:Ke,mc:A,pc:ge,pbc:ie,n:ht,o:e};return{render:Yt,hydrate:void 0,createApp:pp(Yt)}}function ta({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function kr({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Pp(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Ya(e,t,n=!1){const s=e.children,o=t.children;if(Le(s)&&Le(o))for(let a=0;a>1,e[n[d]]0&&(t[s]=n[a-1]),n[a]=s)}}for(a=n.length,c=n[a-1];a-- >0;)n[a]=c,c=t[c];return n}function Kc(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:Kc(t)}function ru(e){if(e)for(let t=0;te.__isSuspense;function Op(e,t){t&&t.pendingBranch?Le(e)?t.effects.push(...e):t.effects.push(e):Fd(e)}const Re=Symbol.for("v-fgt"),ai=Symbol.for("v-txt"),Ft=Symbol.for("v-cmt"),$o=Symbol.for("v-stc"),Tr=[];let rn=null;function F(e=!1){Tr.push(rn=e?null:[])}function Nc(){Tr.pop(),rn=Tr[Tr.length-1]||null}let Is=1;function Lo(e,t=!1){Is+=e,e<0&&rn&&t&&(rn.hasOnce=!0)}function Vc(e){return e.dynamicChildren=Is>0?rn||Ar:null,Nc(),Is>0&&rn&&rn.push(e),e}function q(e,t,n,s,o,a){return Vc(u(e,t,n,s,o,a,!0))}function It(e,t,n,s,o){return Vc(Oe(e,t,n,s,o,!0))}function js(e){return e?e.__v_isVNode===!0:!1}function $r(e,t){return e.type===t.type&&e.key===t.key}const Bc=({key:e})=>e??null,Ao=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?bt(e)||Nt(e)||ze(e)?{i:an,r:e,k:t,f:!!n}:e:null);function u(e,t=null,n=null,s=0,o=null,a=e===Re?0:1,c=!1,d=!1){const h={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Bc(t),ref:t&&Ao(t),scopeId:dc,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:s,dynamicProps:o,dynamicChildren:null,appContext:null,ctx:an};return d?(Ko(h,n),a&128&&e.normalize(h)):n&&(h.shapeFlag|=bt(n)?8:16),Is>0&&!c&&rn&&(h.patchFlag>0||a&6)&&h.patchFlag!==32&&rn.push(h),h}const Oe=Mp;function Mp(e,t=null,n=null,s=0,o=null,a=!1){if((!e||e===op)&&(e=Ft),js(e)){const d=lr(e,t,!0);return n&&Ko(d,n),Is>0&&!a&&rn&&(d.shapeFlag&6?rn[rn.indexOf(e)]=d:rn.push(d)),d.patchFlag=-2,d}if(Up(e)&&(e=e.__vccOpts),t){t=Ip(t);let{class:d,style:h}=t;d&&!bt(d)&&(t.class=et(d)),at(h)&&(qa(h)&&!Le(h)&&(h=Et({},h)),t.style=sr(h))}const c=bt(e)?1:Fc(e)?128:ri(e)?64:at(e)?4:ze(e)?2:0;return u(e,t,n,s,o,c,a,!0)}function Ip(e){return e?qa(e)||Mc(e)?Et({},e):e:null}function lr(e,t,n=!1,s=!1){const{props:o,ref:a,patchFlag:c,children:d,transition:h}=e,y=t?Dp(o||{},t):o,m={__v_isVNode:!0,__v_skip:!0,type:e.type,props:y,key:y&&Bc(y),ref:t&&t.ref?n&&a?Le(a)?a.concat(Ao(t)):[a,Ao(t)]:Ao(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:d,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Re?c===-1?16:c|16:c,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:h,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&lr(e.ssContent),ssFallback:e.ssFallback&&lr(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce,cacheIndex:e.cacheIndex};return h&&s&&ar(m,h.clone(m)),m}function nn(e=" ",t=0){return Oe(ai,null,e,t)}function jp(e,t){const n=Oe($o,null,e);return n.staticCount=t,n}function Ee(e="",t=!1){return t?(F(),It(Ft,null,e)):Oe(Ft,null,e)}function xn(e){return e==null||typeof e=="boolean"?Oe(Ft):Le(e)?Oe(Re,null,e.slice()):js(e)?Dn(e):Oe(ai,null,String(e))}function Dn(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:lr(e)}function Ko(e,t){let n=0;const{shapeFlag:s}=e;if(t==null)t=null;else if(Le(t))n=16;else if(typeof t=="object")if(s&65){const o=t.default;o&&(o._c&&(o._d=!1),Ko(e,o()),o._c&&(o._d=!0));return}else{n=32;const o=t._;!o&&!Mc(t)?t._ctx=an:o===3&&an&&(an.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else if(ze(t)){if(s&65){Ko(e,{default:t});return}t={default:t,_ctx:an},n=32}else t=String(t),s&64?(n=16,t=[nn(t)]):n=8;e.children=t,e.shapeFlag|=n}function Dp(...e){const t={};for(let n=0;nzt||an;let Fo,Ds;{const e=ei(),t=(n,s)=>{let o;return(o=e[n])||(o=e[n]=[]),o.push(s),a=>{o.length>1?o.forEach(c=>c(a)):o[0](a)}};Fo=t("__VUE_INSTANCE_SETTERS__",n=>zt=n),Ds=t("__VUE_SSR_SETTERS__",n=>Rs=n)}const Bs=e=>{const t=zt;return Fo(e),e.scope.on(),()=>{e.scope.off(),Fo(t)}},su=()=>{zt&&zt.scope.off(),Fo(null)};function qc(e){return e.vnode.shapeFlag&4}let Rs=!1;function Fp(e,t=!1,n=!1){t&&Ds(t);const{props:s,children:o}=e.vnode,a=qc(e);_p(e,s,a,t),Sp(e,o,n||t);const c=a?Np(e,t):void 0;return t&&Ds(!1),c}function Np(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,ip);const{setup:s}=n;if(s){An();const o=e.setupContext=s.length>1?Bp(e):null,a=Bs(e),c=Ns(s,e,0,[e.props,o]),d=Lu(c);if(Pn(),a(),(d||e.sp)&&!xs(e)&&wc(e),d){if(c.then(su,su),t)return c.then(h=>{Ds(!0);try{ou(e,h,t)}finally{Ds(!1)}}).catch(h=>{ni(h,e,0)});e.asyncDep=c}else ou(e,c)}else Hc(e)}function ou(e,t,n){ze(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:at(t)&&(e.setupState=ic(t)),Hc(e)}function Hc(e,t,n){const s=e.type;e.render||(e.render=s.render||En);{const o=Bs(e);An();try{ap(e)}finally{Pn(),o()}}}const Vp={get(e,t){return Kt(e,"get",""),e[t]}};function Bp(e){const t=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,Vp),slots:e.slots,emit:e.emit,expose:t}}function li(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(ic(Pd(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Cs)return Cs[n](e)},has(t,n){return n in t||n in Cs}})):e.proxy}function Up(e){return ze(e)&&"__vccOpts"in e}const it=(e,t)=>jd(e,t,Rs);function qp(e,t,n){try{Lo(-1);const s=arguments.length;return s===2?at(t)&&!Le(t)?js(t)?Oe(e,null,[t]):Oe(e,t):Oe(e,null,t):(s>3?n=Array.prototype.slice.call(arguments,2):s===3&&js(n)&&(n=[n]),Oe(e,t,n))}finally{Lo(1)}}const Hp="3.5.44";/** +**/function Ns(e,t,n,s){try{return s?e(...s):e()}catch(o){si(o,t,n)}}function cn(e,t,n,s){if(ze(e)){const o=Ns(e,t,n,s);return o&&Ku(o)&&o.catch(a=>{si(a,t,n)}),o}if(Le(e)){const o=[];for(let a=0;a>>1,o=Wt[s],a=Ts(o);a=Ts(n)?Wt.push(e):Wt.splice(Fd(t),0,e),e.flags|=1,uc()}}function uc(){Io||(Io=lc.then(dc))}function Nd(e){if(!Le(e))tr&&e.id===-1?tr.splice(Hr+1,0,e):e.flags&1||(kn.push(e),e.flags|=1);else for(let t=0;t=t))continue;Wt.splice(s,1),s=e?s-1:pn,o.flags&4&&(o.flags&=-2),o(),o.flags&4||(o.flags&=-2)}}}function fc(e,t,n=0){if(kn.length){let s=kn,o=0;if(t){s=[];for(let c=0;cTs(c)-Ts(d));if(kn.length=o,tr){for(let c=0;ce.id==null?e.flags&2?-1:1/0:e.id;function dc(e){try{for(pn=0;pn{s._d&&Ko(-1);const a=jo(t),c=Tr.length;let d;try{d=e(...o)}finally{for(let h=Tr.length;h>c;h--)Vc();jo(a),s._d&&Ko(1)}return d};return s._n=!0,s._c=!0,s._d=!0,s}function $e(e,t){if(an===null)return e;const n=ci(an),s=e.dirs||(e.dirs=[]);for(let o=0;o1)return n&&ze(t)?t.call(s&&s.proxy):t}}const Ud=Symbol.for("v-scx"),qd=()=>Eo(Ud);function gt(e,t,n){return hc(e,t,n)}function hc(e,t,n=ct){const{immediate:s,deep:o,flush:a,once:c}=n,d=Et({},n),h=t&&s||!t&&a!=="post";let y;if(Rs){if(a==="sync"){const O=qd();y=O.__watcherHandles||(O.__watcherHandles=[])}else if(!h){const O=()=>{};return O.stop=En,O.resume=En,O.pause=En,O}}const m=zt;d.call=(O,K,W)=>cn(O,m,K,W);let k=!1;a==="post"?d.scheduler=O=>{O.i=m,Ht(O,m&&m.suspense)}:a!=="sync"&&(k=!0,d.scheduler=(O,K)=>{K?O():Wa(O)}),d.augmentJob=O=>{t&&(O.flags|=4),k&&(O.flags|=2,m&&(O.id=m.uid,O.i=m))};const D=Ld(e,t,d);return Rs&&(y?y.push(D):h&&D()),D}function Hd(e,t,n){const s=this.proxy,o=bt(e)?e.includes(".")?vc(s,e):()=>s[e]:e.bind(s,s);let a;ze(t)?a=t:(a=t.handler,n=t);const c=Bs(this),d=hc(o,a.bind(s),n);return c(),d}function vc(e,t){const n=t.split(".");return()=>{let s=e;for(let o=0;oe.__isTeleport,Er=e=>e&&(e.disabled||e.disabled===""),Wd=e=>e&&(e.defer||e.defer===""),zl=e=>typeof SVGElement<"u"&&e instanceof SVGElement,Gl=e=>typeof MathMLElement=="function"&&e instanceof MathMLElement,ma=(e,t)=>{const n=e&&e.to;return bt(n)?t?t(n):null:n},zd={name:"Teleport",__isTeleport:!0,process(e,t,n,s,o,a,c,d,h,y){const{mc:m,pc:k,pbc:D,o:{insert:O,querySelector:K,createText:W,createComment:de,parentNode:Z}}=y,E=Er(t.props);let{dynamicChildren:L}=t;const Q=(ee,A,x)=>{ee.shapeFlag&16&&m(ee.children,A,x,o,a,c,d,h)},le=(ee=t)=>{const A=Er(ee.props),x=ee.target=ma(ee.props,K),ie=ya(x,ee,W,O);x&&(c!=="svg"&&zl(x)?c="svg":c!=="mathml"&&Gl(x)&&(c="mathml"),o&&o.isCE&&(o.ce._teleportTargets||(o.ce._teleportTargets=new Set)).add(x),A||(Q(ee,x,ie),ms(ee,!1)))},ce=ee=>{const A=()=>{if(Zn.get(ee)===A){if(Zn.delete(ee),Er(ee.props)){const x=Z(ee.el)||n;Q(ee,x,ee.anchor),ms(ee,!0)}le(ee)}};Zn.set(ee,A),Ht(A,a)};if(e==null){const ee=t.el=W(""),A=t.anchor=W("");if(O(ee,n,s),O(A,n,s),Wd(t.props)||a&&a.pendingBranch){ce(t);return}E&&(Q(t,n,A),ms(t,!0)),le()}else{t.el=e.el;const ee=t.anchor=e.anchor,A=Zn.get(e);if(A){A.flags|=8,Zn.delete(e),ce(t);return}t.targetStart=e.targetStart;const x=t.target=e.target,ie=t.targetAnchor=e.targetAnchor,Ce=Er(e.props),J=Ce?n:x,xe=Ce?ee:ie;if(c==="svg"||zl(x)?c="svg":(c==="mathml"||Gl(x))&&(c="mathml"),L?(D(e.dynamicChildren,L,J,o,a,c,d),Ja(e,t,!0)):h||k(e,t,J,xe,o,a,c,d,!1),E)Ce?t.props&&e.props&&t.props.to!==e.props.to&&(t.props.to=e.props.to):_o(t,n,ee,y,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){const Ne=ma(t.props,K);Ne&&(t.target=Ne,_o(t,Ne,null,y,0))}else Ce&&_o(t,x,ie,y,1);ms(t,E)}},remove(e,t,n,{um:s,o:{remove:o}},a){const{shapeFlag:c,children:d,anchor:h,targetStart:y,targetAnchor:m,target:k,props:D}=e,O=Er(D),K=a||!O,W=Zn.get(e);if(W&&(W.flags|=8,Zn.delete(e)),k&&(o(y),o(m)),a&&o(h),!W&&(O||k)&&c&16)for(let de=0;de{e.isMounted=!0}),Cc(()=>{e.isUnmounting=!0}),e}const sn=[Function,Array],gc={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:sn,onEnter:sn,onAfterEnter:sn,onEnterCancelled:sn,onBeforeLeave:sn,onLeave:sn,onAfterLeave:sn,onLeaveCancelled:sn,onBeforeAppear:sn,onAppear:sn,onAfterAppear:sn,onAppearCancelled:sn},Yd={name:"BaseTransition",props:gc,setup(e,{slots:t}){const n=Xa(),s=yc();return()=>{const o=t.default&&za(t.default(),!0),a=o&&o.length?bc(o):n.subTree?Ee():void 0;if(!a)return;const c=rt(e),{mode:d}=c;if(s.isLeaving)return ta(a);const h=Do(a);if(!h)return ta(a);let y=Os(h,c,s,n,k=>y=k);h.type!==Ft&&ar(h,y);let m=n.subTree&&Do(n.subTree);if(m&&m.type!==Ft&&!$r(m,h)&&Ms(n.subTree)){let k=Os(m,c,s,n);if(ar(m,k),d==="out-in"&&h.type!==Ft)return s.isLeaving=!0,k.afterLeave=()=>{s.isLeaving=!1,n.job.flags&8||n.update(),delete k.afterLeave,m=void 0},ta(a);d==="in-out"&&h.type!==Ft?k.delayLeave=(D,O,K)=>{const W=wc(s,m);W[String(m.key)]=m,D[on]=()=>{O(),D[on]=void 0,delete y.delayedLeave,m=void 0},y.delayedLeave=()=>{K(),delete y.delayedLeave,m=void 0}}:m=void 0}else m&&(m=void 0);return a}}};function bc(e){let t=e[0];if(e.length>1){for(const n of e)if(n.type!==Ft){t=n;break}}return t}const Jd=Yd;function wc(e,t){const{leavingVNodes:n}=e;let s=n.get(t.type);return s||(s=Object.create(null),n.set(t.type,s)),s}function Os(e,t,n,s,o){const{appear:a,mode:c,persisted:d=!1,onBeforeEnter:h,onEnter:y,onAfterEnter:m,onEnterCancelled:k,onBeforeLeave:D,onLeave:O,onAfterLeave:K,onLeaveCancelled:W,onBeforeAppear:de,onAppear:Z,onAfterAppear:E,onAppearCancelled:L}=t,Q=String(e.key),le=wc(n,e),ce=(x,ie)=>{x&&cn(x,s,9,ie)},ee=(x,ie)=>{const Ce=ie[1];ce(x,ie),Le(x)?x.every(J=>J.length<=1)&&Ce():x.length<=1&&Ce()},A={mode:c,persisted:d,beforeEnter(x){let ie=h;if(!n.isMounted)if(a)ie=de||h;else return;x[on]&&x[on](!0);const Ce=le[Q];if(Ce&&$r(e,Ce)){let J=Ce.el[on];if(!J){const xe=Ms(Ce);J=xe&&xe.el[on]}J&&J()}ce(ie,[x])},enter(x){if(le[Q]===e)return;let ie=y,Ce=m,J=k;if(!n.isMounted)if(a)ie=Z||y,Ce=E||m,J=L||k;else return;let xe=!1;x[hs]=Xe=>{xe||(xe=!0,Xe?ce(J,[x]):ce(Ce,[x]),A.delayedLeave&&A.delayedLeave(),x[hs]=void 0)};const Ne=x[hs].bind(null,!1);ie?ee(ie,[x,Ne]):Ne()},leave(x,ie){const Ce=String(e.key);if(x[hs]&&x[hs](!0),n.isUnmounting)return ie();ce(D,[x]);let J=!1;x[on]=Ne=>{J||(J=!0,ie(),Ne?ce(W,[x]):ce(K,[x]),x[on]=void 0,le[Ce]===e&&delete le[Ce])};const xe=x[on].bind(null,!1);le[Ce]=e,O?ee(O,[x,xe]):xe()},clone(x){const ie=Os(x,t,n,s,o);return o&&o(ie),ie}};return A}function ta(e){if(ii(e))return e=lr(e),e.children=null,e}function Do(e){if(!ii(e))return oi(e.type)&&e.children?bc(e.children):e;if(e.component)return e.component.subTree;const{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&ze(n.default))return n.default()}}function ar(e,t){if(e.shapeFlag&6&&e.component){e.transition=t;const n=e.component.subTree;ar(oi(n.type)&&Do(n)||n,t)}else if(e.shapeFlag&128)e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback);else if(e.transition=t,e.type===Re&&Le(e.children)){const n=Pc(e.children,!1);n&&ar(n,t)}}function za(e,t=!1,n){let s=[],o=0;for(let a=0;a1)for(let a=0;aks(W,t&&(Le(t)?t[de]:t),n,s,o));return}if(xs(s)&&!o){s.shapeFlag&512&&s.type.__asyncResolved&&s.component.subTree.component&&ks(e,t,n,s.component.subTree);return}const a=s.shapeFlag&4?ci(s.component):s.el,c=o?null:a,{i:d,r:h}=e,y=t&&t.r,m=d.refs===ct?d.refs={}:d.refs,k=d.setupState,D=rt(k),O=k===ct?Lu:W=>Yl(m,W)?!1:ot(D,W),K=(W,de)=>!(de&&Yl(m,de));if(y!=null&&y!==h){if(Jl(t),bt(y))m[y]=null,O(y)&&(k[y]=null);else if(Nt(y)){const W=t;K(y,W.k)&&(y.value=null),W.k&&(m[W.k]=null)}}if(ze(h))Ns(h,d,12,[c,m]);else{const W=bt(h),de=Nt(h);if(W||de){const Z=()=>{if(e.f){const E=W?O(h)?k[h]:m[h]:K()||!e.k?h.value:m[e.k];if(o)Le(E)&&Da(E,a);else if(Le(E))E.includes(a)||E.push(a);else if(W)m[h]=[a],O(h)&&(k[h]=m[h]);else{const L=[a];K(h,e.k)&&(h.value=L),e.k&&(m[e.k]=L)}}else W?(m[h]=c,O(h)&&(k[h]=c)):de&&(K(h,e.k)&&(h.value=c),e.k&&(m[e.k]=c))};if(c){const E=()=>{Z(),Ro.delete(e)};E.id=-1,Ro.set(e,E),Ht(E,n)}else Jl(e),Z()}}}function Jl(e){const t=Ro.get(e);t&&(t.flags|=8,Ro.delete(e))}ni().requestIdleCallback;ni().cancelIdleCallback;const xs=e=>!!e.type.__asyncLoader,ii=e=>e.type.__isKeepAlive;function Xd(e,t){kc(e,"a",t)}function Qd(e,t){kc(e,"da",t)}function kc(e,t,n=zt){const s=e.__wdc||(e.__wdc=()=>{let o=n;for(;o;){if(o.isDeactivated)return;o=o.parent}return e()});if(ai(t,s,n),n){let o=n.parent;for(;o&&o.parent;)ii(o.parent.vnode)&&Zd(s,t,n,o),o=o.parent}}function Zd(e,t,n,s){const o=ai(t,e,s,!0);dr(()=>{Da(s[t],o)},n)}function ai(e,t,n=zt,s=!1){if(n){const o=n[e]||(n[e]=[]),a=t.__weh||(t.__weh=(...c)=>{An();const d=Bs(n),h=cn(t,n,e,c);return d(),Pn(),h});return s?o.unshift(a):o.push(a),a}}const qn=e=>(t,n=zt)=>{(!Rs||e==="sp")&&ai(e,(...s)=>t(...s),n)},ep=qn("bm"),fn=qn("m"),tp=qn("bu"),xc=qn("u"),Cc=qn("bum"),dr=qn("um"),np=qn("sp"),rp=qn("rtg"),sp=qn("rtc");function op(e,t=zt){ai("ec",e,t)}const ip=Symbol.for("v-ndc");function ut(e,t,n,s){let o;const a=n,c=Le(e);if(c||bt(e)){const d=c&&or(e);let h=!1,y=!1;d&&(h=!ln(e),y=Tn(e),e=ri(e)),o=new Array(e.length);for(let m=0,k=e.length;mt(d,h,void 0,a));else{const d=Object.keys(e);o=new Array(d.length);for(let h=0,y=d.length;he?Hc(e)?ci(e):ga(e.parent):null,Cs=Et(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>ga(e.parent),$root:e=>ga(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Ec(e),$forceUpdate:e=>e.f||(e.f=()=>{Wa(e.update)}),$nextTick:e=>e.n||(e.n=ts.bind(e.proxy)),$watch:e=>Hd.bind(e)}),na=(e,t)=>e!==ct&&!e.__isScriptSetup&&ot(e,t),ap={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:n,setupState:s,data:o,props:a,accessCache:c,type:d,appContext:h}=e;if(t[0]!=="$"){const D=c[t];if(D!==void 0)switch(D){case 1:return s[t];case 2:return o[t];case 4:return n[t];case 3:return a[t]}else{if(na(s,t))return c[t]=1,s[t];if(o!==ct&&ot(o,t))return c[t]=2,o[t];if(ot(a,t))return c[t]=3,a[t];if(n!==ct&&ot(n,t))return c[t]=4,n[t];ba&&(c[t]=0)}}const y=Cs[t];let m,k;if(y)return t==="$attrs"&&Kt(e.attrs,"get",""),y(e);if((m=d.__cssModules)&&(m=m[t]))return m;if(n!==ct&&ot(n,t))return c[t]=4,n[t];if(k=h.config.globalProperties,ot(k,t))return k[t]},set({_:e},t,n){const{data:s,setupState:o,ctx:a}=e;return na(o,t)?(o[t]=n,!0):s!==ct&&ot(s,t)?(s[t]=n,!0):ot(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(a[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:s,appContext:o,props:a,type:c}},d){let h;return!!(n[d]||e!==ct&&d[0]!=="$"&&ot(e,d)||na(t,d)||ot(a,d)||ot(s,d)||ot(Cs,d)||ot(o.config.globalProperties,d)||(h=c.__cssModules)&&h[d])},defineProperty(e,t,n){return n.get!=null?e._.accessCache[t]=0:ot(n,"value")&&this.set(e,t,n.value,null),Reflect.defineProperty(e,t,n)}};function Xl(e){return Le(e)?e.reduce((t,n)=>(t[n]=null,t),{}):e}let ba=!0;function lp(e){const t=Ec(e),n=e.proxy,s=e.ctx;ba=!1,t.beforeCreate&&Ql(t.beforeCreate,e,"bc");const{data:o,computed:a,methods:c,watch:d,provide:h,inject:y,created:m,beforeMount:k,mounted:D,beforeUpdate:O,updated:K,activated:W,deactivated:de,beforeDestroy:Z,beforeUnmount:E,destroyed:L,unmounted:Q,render:le,renderTracked:ce,renderTriggered:ee,errorCaptured:A,serverPrefetch:x,expose:ie,inheritAttrs:Ce,components:J,directives:xe,filters:Ne}=t;if(y&&up(y,s,null),c)for(const Ue in c){const ge=c[Ue];ze(ge)&&(s[Ue]=ge.bind(n))}if(o){const Ue=o.call(n,n);at(Ue)&&(e.data=Ua(Ue))}if(ba=!0,a)for(const Ue in a){const ge=a[Ue],Me=ze(ge)?ge.bind(n,n):ze(ge.get)?ge.get.bind(n,n):En,Ke=!ze(ge)&&ze(ge.set)?ge.set.bind(n):En,fe=it({get:Me,set:Ke});Object.defineProperty(s,Ue,{enumerable:!0,configurable:!0,get:()=>fe.value,set:G=>fe.value=G})}if(d)for(const Ue in d)Sc(d[Ue],s,n,Ue);if(h){const Ue=ze(h)?h.call(n):h;Reflect.ownKeys(Ue).forEach(ge=>{Bd(ge,Ue[ge])})}m&&Ql(m,e,"c");function He(Ue,ge){Le(ge)?ge.forEach(Me=>Ue(Me.bind(n))):ge&&Ue(ge.bind(n))}if(He(ep,k),He(fn,D),He(tp,O),He(xc,K),He(Xd,W),He(Qd,de),He(op,A),He(sp,ce),He(rp,ee),He(Cc,E),He(dr,Q),He(np,x),Le(ie))if(ie.length){const Ue=e.exposed||(e.exposed={});ie.forEach(ge=>{Object.defineProperty(Ue,ge,{get:()=>n[ge],set:Me=>n[ge]=Me,enumerable:!0})})}else e.exposed||(e.exposed={});le&&e.render===En&&(e.render=le),Ce!=null&&(e.inheritAttrs=Ce),J&&(e.components=J),xe&&(e.directives=xe),x&&_c(e)}function up(e,t,n=En){Le(e)&&(e=wa(e));for(const s in e){const o=e[s];let a;at(o)?"default"in o?a=Eo(o.from||s,o.default,!0):a=Eo(o.from||s):a=Eo(o),Nt(a)?Object.defineProperty(t,s,{enumerable:!0,configurable:!0,get:()=>a.value,set:c=>a.value=c}):t[s]=a}}function Ql(e,t,n){cn(Le(e)?e.map(s=>s.bind(t.proxy)):e.bind(t.proxy),t,n)}function Sc(e,t,n,s){let o=s.includes(".")?vc(n,s):()=>n[s];if(bt(e)){const a=t[e];ze(a)&>(o,a)}else if(ze(e))gt(o,e.bind(n));else if(at(e))if(Le(e))e.forEach(a=>Sc(a,t,n,s));else{const a=ze(e.handler)?e.handler.bind(n):t[e.handler];ze(a)&>(o,a,e)}}function Ec(e){const t=e.type,{mixins:n,extends:s}=t,{mixins:o,optionsCache:a,config:{optionMergeStrategies:c}}=e.appContext,d=a.get(t);let h;return d?h=d:!o.length&&!n&&!s?h=t:(h={},o.length&&o.forEach(y=>Lo(h,y,c,!0)),Lo(h,t,c)),at(t)&&a.set(t,h),h}function Lo(e,t,n,s=!1){const{mixins:o,extends:a}=t;a&&Lo(e,a,n,!0),o&&o.forEach(c=>Lo(e,c,n,!0));for(const c in t)if(!(s&&c==="expose")){const d=cp[c]||n&&n[c];e[c]=d?d(e[c],t[c]):t[c]}return e}const cp={data:Zl,props:eu,emits:eu,methods:ys,computed:ys,beforeCreate:qt,created:qt,beforeMount:qt,mounted:qt,beforeUpdate:qt,updated:qt,beforeDestroy:qt,beforeUnmount:qt,destroyed:qt,unmounted:qt,activated:qt,deactivated:qt,errorCaptured:qt,serverPrefetch:qt,components:ys,directives:ys,watch:dp,provide:Zl,inject:fp};function Zl(e,t){return t?e?function(){return Et(ze(e)?e.call(this,this):e,ze(t)?t.call(this,this):t)}:t:e}function fp(e,t){return ys(wa(e),wa(t))}function wa(e){if(Le(e)){const t={};for(let n=0;nt==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${hn(t)}Modifiers`]||e[`${cr(t)}Modifiers`];function mp(e,t,...n){if(e.isUnmounted)return;const s=e.vnode.props||ct;let o=n;const a=t.startsWith("update:"),c=a&&vp(s,t.slice(7));c&&(c.trim&&(o=n.map(m=>bt(m)?m.trim():m)),c.number&&(o=o.map(ti)));let d,h=s[d=Yi(t)]||s[d=Yi(hn(t))];!h&&a&&(h=s[d=Yi(cr(t))]),h&&cn(h,e,6,o);const y=s[d+"Once"];if(y){if(!e.emitted)e.emitted={};else if(e.emitted[d])return;e.emitted[d]=!0,cn(y,e,6,o)}}const yp=new WeakMap;function Ac(e,t,n=!1){const s=n?yp:t.emitsCache,o=s.get(e);if(o!==void 0)return o;const a=e.emits;let c={},d=!1;if(!ze(e)){const h=y=>{const m=Ac(y,t,!0);m&&(d=!0,Et(c,m))};!n&&t.mixins.length&&t.mixins.forEach(h),e.extends&&h(e.extends),e.mixins&&e.mixins.forEach(h)}return!a&&!d?(at(e)&&s.set(e,null),null):(Le(a)?a.forEach(h=>c[h]=null):Et(c,a),at(e)&&s.set(e,c),c)}function li(e,t){return!e||!Qo(t)?!1:(t=t.slice(2),t=t==="Once"?t:t.replace(/Once$/,""),ot(e,t[0].toLowerCase()+t.slice(1))||ot(e,cr(t))||ot(e,t))}function tu(e){const{type:t,vnode:n,proxy:s,withProxy:o,propsOptions:[a],slots:c,attrs:d,emit:h,render:y,renderCache:m,props:k,data:D,setupState:O,ctx:K,inheritAttrs:W}=e,de=jo(e);let Z,E;try{if(n.shapeFlag&4){const Q=o||s,le=Q;Z=xn(y.call(le,Q,m,k,O,D,K)),E=d}else{const Q=t;Z=xn(Q.length>1?Q(k,{attrs:d,slots:c,emit:h}):Q(k,null)),E=t.props?d:gp(d)}}catch(Q){Tr.length=0,si(Q,e,1),Z=Oe(Ft)}let L=Z;if(E&&W!==!1){const Q=Object.keys(E),{shapeFlag:le}=L;Q.length&&le&7&&(a&&Q.some(Zo)&&(E=bp(E,a)),L=lr(L,E,!1,!0))}if(n.dirs&&(L=lr(L,null,!1,!0),L.dirs=L.dirs?L.dirs.concat(n.dirs):n.dirs),n.transition){const Q=oi(L.type)&&Do(L)||L;ar(Q,n.transition)}return Z=L,jo(de),Z}function Pc(e,t=!0){let n;for(let s=0;s{let t;for(const n in e)(n==="class"||n==="style"||Qo(n))&&((t||(t={}))[n]=e[n]);return t},bp=(e,t)=>{const n={};for(const s in e)(!Zo(s)||!(s.slice(9)in t))&&(n[s]=e[s]);return n};function wp(e,t,n){const{props:s,children:o,component:a}=e,{props:c,children:d,patchFlag:h}=t,y=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&h>=0){if(h&1024)return!0;if(h&16)return s?nu(s,c,y):!!c;if(h&8){const m=t.dynamicProps;for(let k=0;kObject.create(Oc),Ic=e=>Object.getPrototypeOf(e)===Oc;function kp(e,t,n,s=!1){const o={},a=Mc();e.propsDefaults=Object.create(null),jc(e,t,o,a);for(const c in e.propsOptions[0])c in o||(o[c]=void 0);n?e.props=s?o:Pd(o):e.type.props?e.props=o:e.props=a,e.attrs=a}function xp(e,t,n,s){const{props:o,attrs:a,vnode:{patchFlag:c}}=e,d=rt(o),[h]=e.propsOptions;let y=!1;if((s||c>0)&&!(c&16)){if(c&8){const m=e.vnode.dynamicProps;for(let k=0;k{h=!0;const[D,O]=Dc(k,t,!0);Et(c,D),O&&d.push(...O)};!n&&t.mixins.length&&t.mixins.forEach(m),e.extends&&m(e.extends),e.mixins&&e.mixins.forEach(m)}if(!a&&!h)return at(e)&&s.set(e,Ar),Ar;if(Le(a))for(let m=0;me==="_"||e==="_ctx"||e==="$stable",Ya=e=>Le(e)?e.map(xn):[xn(e)],Sp=(e,t,n)=>{if(t._n)return t;const s=fr((...o)=>Ya(t(...o)),n);return s._c=!1,s},Rc=(e,t,n)=>{const s=e._ctx;for(const o in e){if(Ga(o))continue;const a=e[o];if(ze(a))t[o]=Sp(o,a,s);else if(a!=null){const c=Ya(a);t[o]=()=>c}}},Lc=(e,t)=>{const n=Ya(t);e.slots.default=()=>n},Kc=(e,t,n)=>{for(const s in t)(n||!Ga(s))&&(e[s]=t[s])},Ep=(e,t,n)=>{const s=e.slots=Mc();if(e.vnode.shapeFlag&32){const o=t._;o?(Kc(s,t,n),n&&Bu(s,"_",o,!0)):Rc(t,s)}else t&&Lc(e,t)},$p=(e,t,n)=>{const{vnode:s,slots:o}=e;let a=!0,c=ct;if(s.shapeFlag&32){const d=t._;d?n&&d===1?a=!1:Kc(o,t,n):(a=!t.$stable,Rc(t,o)),c=t}else t&&(Lc(e,t),c={default:1});if(a)for(const d in o)!Ga(d)&&c[d]==null&&delete o[d]},Ht=Mp;function Ap(e){return Pp(e)}function Pp(e,t){const n=ni();n.__VUE__=!0;const{insert:s,remove:o,patchProp:a,createElement:c,createText:d,createComment:h,setText:y,setElementText:m,parentNode:k,nextSibling:D,setScopeId:O=En,insertStaticContent:K}=e,W=(w,g,P,ae=null,se=null,ue=null,ye=void 0,oe=null,we=!!g.dynamicChildren)=>{if(w===g)return;w&&!$r(w,g)&&(ae=ht(w),G(w,se,ue,!0),w=null),g.patchFlag===-2&&(we=!1,g.dynamicChildren=null),g.dynamicChildren&&w&&w.dynamicChildren&&w.dynamicChildren.hasOnce&&(g.dynamicChildren===Ar&&(g.dynamicChildren=[]),g.dynamicChildren.hasOnce=!0);const{type:H,ref:U,shapeFlag:Y}=g;switch(H){case ui:de(w,g,P,ae);break;case Ft:Z(w,g,P,ae);break;case $o:w==null&&E(g,P,ae,ye);break;case Re:J(w,g,P,ae,se,ue,ye,oe,we);break;default:Y&1?le(w,g,P,ae,se,ue,ye,oe,we):Y&6?xe(w,g,P,ae,se,ue,ye,oe,we):(Y&64||Y&128)&&H.process(w,g,P,ae,se,ue,ye,oe,we,Jt)}U!=null&&se?ks(U,w&&w.ref,ue,g||w,!g):U==null&&w&&w.ref!=null&&ks(w.ref,null,ue,w,!0)},de=(w,g,P,ae)=>{if(w==null)s(g.el=d(g.children),P,ae);else{const se=g.el=w.el;g.children!==w.children&&y(se,g.children)}},Z=(w,g,P,ae)=>{w==null?s(g.el=h(g.children||""),P,ae):g.el=w.el},E=(w,g,P,ae)=>{[w.el,w.anchor]=K(w.children,g,P,ae,w.el,w.anchor)},L=({el:w,anchor:g},P,ae)=>{let se;for(;w&&w!==g;)se=D(w),s(w,P,ae),w=se;s(g,P,ae)},Q=({el:w,anchor:g})=>{let P;for(;w&&w!==g;)P=D(w),o(w),w=P;o(g)},le=(w,g,P,ae,se,ue,ye,oe,we)=>{if(g.type==="svg"?ye="svg":g.type==="math"&&(ye="mathml"),w==null)ce(g,P,ae,se,ue,ye,oe,we);else{const H=w.el&&w.el._isVueCE?w.el:null;try{H&&H._beginPatch(),x(w,g,se,ue,ye,oe,we)}finally{H&&H._endPatch()}}},ce=(w,g,P,ae,se,ue,ye,oe)=>{let we,H;const{props:U,shapeFlag:Y,transition:Ae,dirs:Fe}=w;if(we=w.el=c(w.type,ue,U&&U.is,U),Y&8?m(we,w.children):Y&16&&A(w.children,we,null,ae,se,ra(w,ue),ye,oe),Fe&&_r(w,null,ae,"created"),ee(we,w,w.scopeId,ye,ae),U){for(const Ye in U)Ye!=="value"&&!bs(Ye)&&a(we,Ye,null,U[Ye],ue,ae);"value"in U&&a(we,"value",null,U.value,ue),(H=U.onVnodeBeforeMount)&&gn(H,ae,w)}Fe&&_r(w,null,ae,"beforeMount");const Je=Tp(se,Ae);Je&&Ae.beforeEnter(we),s(we,g,P),((H=U&&U.onVnodeMounted)||Je||Fe)&&Ht(()=>{try{H&&gn(H,ae,w),Je&&Ae.enter(we),Fe&&_r(w,null,ae,"mounted")}finally{}},se)},ee=(w,g,P,ae,se)=>{if(P&&O(w,P),ae)for(let ue=0;ue{for(let H=we;H{const oe=g.el=w.el;let{patchFlag:we,dynamicChildren:H,dirs:U}=g;we|=w.patchFlag&16;const Y=w.props||ct,Ae=g.props||ct;let Fe;if(P&&kr(P,!1),(Fe=Ae.onVnodeBeforeUpdate)&&gn(Fe,P,g,w),U&&_r(g,w,P,"beforeUpdate"),P&&kr(P,!0),H&&(!w.dynamicChildren||w.dynamicChildren.length!==H.length)&&(we=0,ye=!1,H=null),(Y.innerHTML&&Ae.innerHTML==null||Y.textContent&&Ae.textContent==null)&&m(oe,""),H?ie(w.dynamicChildren,H,oe,P,ae,ra(g,se),ue):ye||ge(w,g,oe,null,P,ae,ra(g,se),ue,!1),we>0){if(we&16)Ce(oe,Y,Ae,P,se);else if(we&2&&Y.class!==Ae.class&&a(oe,"class",null,Ae.class,se),we&4&&a(oe,"style",Y.style,Ae.style,se),we&8){const Je=g.dynamicProps;for(let Ye=0;Ye{Fe&&gn(Fe,P,g,w),U&&_r(g,w,P,"updated")},ae)},ie=(w,g,P,ae,se,ue,ye)=>{for(let oe=0;oe{if(g!==P){if(g!==ct)for(const ue in g)!bs(ue)&&!(ue in P)&&a(w,ue,g[ue],null,se,ae);for(const ue in P){if(bs(ue))continue;const ye=P[ue],oe=g[ue];ye!==oe&&ue!=="value"&&a(w,ue,oe,ye,se,ae)}"value"in P&&a(w,"value",g.value,P.value,se)}},J=(w,g,P,ae,se,ue,ye,oe,we)=>{const H=g.el=w?w.el:d(""),U=g.anchor=w?w.anchor:d("");let{patchFlag:Y,dynamicChildren:Ae,slotScopeIds:Fe}=g;Fe&&(oe=oe?oe.concat(Fe):Fe),w==null?(s(H,P,ae),s(U,P,ae),A(g.children||[],P,U,se,ue,ye,oe,we)):Y>0&&Y&64&&Ae&&w.dynamicChildren&&w.dynamicChildren.length===Ae.length?(ie(w.dynamicChildren,Ae,P,se,ue,ye,oe),(g.key!=null||se&&g===se.subTree)&&Ja(w,g,!0)):ge(w,g,P,U,se,ue,ye,oe,we)},xe=(w,g,P,ae,se,ue,ye,oe,we)=>{g.slotScopeIds=oe,w==null?g.shapeFlag&512?se.ctx.activate(g,P,ae,ye,we):Ne(g,P,ae,se,ue,ye,we):Xe(w,g,we)},Ne=(w,g,P,ae,se,ue,ye)=>{const oe=w.component=Fp(w,ae,se);if(ii(w)&&(oe.ctx.renderer=Jt),Np(oe,!1,ye),oe.asyncDep){if(se&&se.registerDep(oe,He,ye,ue),!w.el){const we=oe.subTree=Oe(Ft);Z(null,we,g,P),w.placeholder=we.el}}else He(oe,w,g,P,se,ue,ye)},Xe=(w,g,P)=>{const ae=g.component=w.component;if(wp(w,g,P))if(ae.asyncDep&&!ae.asyncResolved){g.el=w.el,g.placeholder=w.placeholder,Ue(ae,g,P);return}else ae.next=g,ae.update();else g.el=w.el,g.placeholder=w.placeholder,ae.vnode=g},He=(w,g,P,ae,se,ue,ye)=>{const oe=()=>{if(w.isMounted){let{next:Y,bu:Ae,u:Fe,parent:Je,vnode:Ye}=w;{const Bt=Fc(w);if(Bt){Y&&(Y.el=Ye.el,Ue(w,Y,ye)),Bt.asyncDep.then(()=>{Ht(()=>{w.isUnmounted||H()},se)});return}}let Qe=Y,vt;kr(w,!1),Y?(Y.el=Ye.el,Ue(w,Y,ye)):Y=Ye,Ae&&So(Ae),(vt=Y.props&&Y.props.onVnodeBeforeUpdate)&&gn(vt,Je,Y,Ye),kr(w,!0);const _t=tu(w),Xt=w.subTree;w.subTree=_t,W(Xt,_t,k(Xt.el),ht(Xt),w,se,ue),Y.el=_t.el,Qe===null&&_p(w,_t.el),Fe&&Ht(Fe,se),(vt=Y.props&&Y.props.onVnodeUpdated)&&Ht(()=>gn(vt,Je,Y,Ye),se)}else{let Y;const{el:Ae,props:Fe}=g,{bm:Je,m:Ye,parent:Qe,root:vt,type:_t}=w,Xt=xs(g);kr(w,!1),Je&&So(Je),!Xt&&(Y=Fe&&Fe.onVnodeBeforeMount)&&gn(Y,Qe,g),kr(w,!0);{vt.ce&&vt.ce._hasShadowRoot()&&vt.ce._injectChildStyle(_t,w.parent?w.parent.type:void 0);const Bt=w.subTree=tu(w);W(null,Bt,P,ae,w,se,ue),g.el=Bt.el}if(Ye&&Ht(Ye,se),!Xt&&(Y=Fe&&Fe.onVnodeMounted)){const Bt=g;Ht(()=>gn(Y,Qe,Bt),se)}(g.shapeFlag&256||Qe&&xs(Qe.vnode)&&Qe.vnode.shapeFlag&256)&&w.a&&Ht(w.a,se),w.isMounted=!0,g=P=ae=null}};w.scope.on();const we=w.effect=new Wu(oe);w.scope.off();const H=w.update=we.run.bind(we),U=w.job=we.runIfDirty.bind(we);U.i=w,U.id=w.uid,we.scheduler=()=>Wa(U),kr(w,!0),H()},Ue=(w,g,P)=>{g.component=w;const ae=w.vnode.props;w.vnode=g,w.next=null,xp(w,g.props,ae,P),$p(w,g.children,P),An(),cc(w),Pn()},ge=(w,g,P,ae,se,ue,ye,oe,we=!1)=>{const H=w&&w.children,U=w?w.shapeFlag:0,Y=g.children,{patchFlag:Ae,shapeFlag:Fe}=g;if(Ae>0){if(Ae&128){Ke(H,Y,P,ae,se,ue,ye,oe,we);return}else if(Ae&256){Me(H,Y,P,ae,se,ue,ye,oe,we);return}}Fe&8?(U&16&&pt(H,se,ue),Y!==H&&m(P,Y)):U&16?Fe&16?Ke(H,Y,P,ae,se,ue,ye,oe,we):pt(H,se,ue,!0):(U&8&&m(P,""),Fe&16&&A(Y,P,ae,se,ue,ye,oe,we))},Me=(w,g,P,ae,se,ue,ye,oe,we)=>{w=w||Ar,g=g||Ar;const H=w.length,U=g.length,Y=Math.min(H,U);let Ae;for(Ae=0;AeU?pt(w,se,ue,!0,!1,Y):A(g,P,ae,se,ue,ye,oe,we,Y)},Ke=(w,g,P,ae,se,ue,ye,oe,we)=>{let H=0;const U=g.length;let Y=w.length-1,Ae=U-1;for(;H<=Y&&H<=Ae;){const Fe=w[H],Je=g[H]=we?Dn(g[H]):xn(g[H]);if($r(Fe,Je))W(Fe,Je,P,null,se,ue,ye,oe,we);else break;H++}for(;H<=Y&&H<=Ae;){const Fe=w[Y],Je=g[Ae]=we?Dn(g[Ae]):xn(g[Ae]);if($r(Fe,Je))W(Fe,Je,P,null,se,ue,ye,oe,we);else break;Y--,Ae--}if(H>Y){if(H<=Ae){const Fe=Ae+1,Je=FeAe)for(;H<=Y;)G(w[H],se,ue,!0),H++;else{const Fe=H,Je=H,Ye=new Map;for(H=Je;H<=Ae;H++){const Ot=g[H]=we?Dn(g[H]):xn(g[H]);Ot.key!=null&&Ye.set(Ot.key,H)}let Qe,vt=0;const _t=Ae-Je+1;let Xt=!1,Bt=0;const Zt=new Array(_t);for(H=0;H<_t;H++)Zt[H]=0;for(H=Fe;H<=Y;H++){const Ot=w[H];if(vt>=_t){G(Ot,se,ue,!0);continue}let $t;if(Ot.key!=null)$t=Ye.get(Ot.key);else for(Qe=Je;Qe<=Ae;Qe++)if(Zt[Qe-Je]===0&&$r(Ot,g[Qe])){$t=Qe;break}$t===void 0?G(Ot,se,ue,!0):(Zt[$t-Je]=H+1,$t>=Bt?Bt=$t:Xt=!0,W(Ot,g[$t],P,null,se,ue,ye,oe,we),vt++)}const pr=Xt?Op(Zt):Ar;for(Qe=pr.length-1,H=_t-1;H>=0;H--){const Ot=Je+H,$t=g[Ot],Ie=g[Ot+1],Hn=Ot+1{const{el:ue,type:ye,transition:oe,children:we,shapeFlag:H}=w;if(H&6){fe(w.component.subTree,g,P,ae);return}if(H&128){w.suspense.move(g,P,ae);return}if(H&64){ye.move(w,g,P,Jt);return}if(ye===Re){s(ue,g,P);for(let Y=0;Yoe.enter(ue),se));else{const{leave:Y,delayLeave:Ae,afterLeave:Fe}=oe,Je=()=>{w.ctx.isUnmounted?o(ue):s(ue,g,P)},Ye=()=>{const Qe=ue._isLeaving||!!ue[on];ue._isLeaving&&ue[on](!0),oe.persisted&&!Qe?Je():Y(ue,()=>{Je(),Fe&&Fe()})};Ae?Ae(ue,Je,Ye):Ye()}else s(ue,g,P)},G=(w,g,P,ae=!1,se=!1)=>{const{type:ue,props:ye,ref:oe,children:we,dynamicChildren:H,shapeFlag:U,patchFlag:Y,dirs:Ae,cacheIndex:Fe,memo:Je}=w;if((Y===-2||H&&H.hasOnce)&&(se=!1),oe!=null&&(An(),ks(oe,null,P,w,!0),Pn()),Fe!=null&&(!w.ctx||w.ctx===g)&&(g.renderCache[Fe]=void 0),U&256){g.ctx.deactivate(w);return}const Ye=U&1&&Ae,Qe=!xs(w);let vt;if(Qe&&(vt=ye&&ye.onVnodeBeforeUnmount)&&gn(vt,g,w),U&6)st(w.component,P,ae);else{if(U&128){w.suspense.unmount(P,ae);return}Ye&&_r(w,null,g,"beforeUnmount"),U&64?w.type.remove(w,g,P,Jt,ae):H&&!H.hasOnce&&(ue!==Re||Y>0&&Y&64)?pt(H,g,P,!1,!0):(ue===Re&&Y&384||!se&&U&16)&&pt(we,g,P),ae&&X(w)}const _t=Je!=null&&Fe==null;(Qe&&(vt=ye&&ye.onVnodeUnmounted)||Ye||_t)&&Ht(()=>{vt&&gn(vt,g,w),Ye&&_r(w,null,g,"unmounted"),_t&&(w.el=null)},P)},X=w=>{const{type:g,el:P,anchor:ae,transition:se}=w,ue=g===Re;if(ue&&!se){ke(P,ae);return}if(g===$o){Q(w),se&&!se.persisted&&se.afterLeave&&se.afterLeave();return}const ye=ue?Ms(w):w,oe=()=>{ue?k(P)&&ke(P,ae):o(P),se&&!se.persisted&&se.afterLeave&&se.afterLeave()};if(ye&&ye.shapeFlag&1&&se&&!se.persisted){const{leave:we,delayLeave:H}=se,U=ye.el,Y=()=>we(U,oe);H?H(U,oe,Y):Y()}else oe()},ke=(w,g)=>{let P;for(;w!==g;)P=D(w),o(w),w=P;o(g)},st=(w,g,P)=>{const{bum:ae,scope:se,job:ue,subTree:ye,um:oe,m:we,a:H}=w;su(we),su(H),ae&&So(ae),se.stop(),ue?(ue.flags|=8,G(ye,w,g,P)):w.vnode.el&&ye&&(ye.transition=w.vnode.transition,G(ye,w,g,P)),oe&&Ht(oe,g),Ht(()=>{w.isUnmounted=!0},g)},pt=(w,g,P,ae=!1,se=!1,ue=0)=>{for(let ye=ue;ye{if(w.shapeFlag&6)return ht(w.component.subTree);if(w.shapeFlag&128)return w.suspense.next();const g=D(w.anchor||w.el),P=g&&g[mc];return P?D(P):g},Yt=(w,g,P)=>{const ae=w&&g._vnode?void 0:w&&w.component?w.component.uid:Kp();Vd(()=>{w==null?g._vnode&&G(g._vnode,null,null,!0):W(g._vnode||null,w,g,null,null,null,P),g._vnode=w},ae)},Jt={p:W,um:G,m:fe,r:X,mt:Ne,mc:A,pc:ge,pbc:ie,n:ht,o:e};return{render:Yt,hydrate:void 0,createApp:hp(Yt)}}function ra({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function kr({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Tp(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Ja(e,t,n=!1){const s=e.children,o=t.children;if(Le(s)&&Le(o))for(let a=0;a>1,e[n[d]]0&&(t[s]=n[a-1]),n[a]=s)}}for(a=n.length,c=n[a-1];a-- >0;)n[a]=c,c=t[c];return n}function Fc(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:Fc(t)}function su(e){if(e)for(let t=0;te.__isSuspense;function Mp(e,t){t&&t.pendingBranch?Le(e)?t.effects.push(...e):t.effects.push(e):Nd(e)}const Re=Symbol.for("v-fgt"),ui=Symbol.for("v-txt"),Ft=Symbol.for("v-cmt"),$o=Symbol.for("v-stc"),Tr=[];let rn=null;function F(e=!1){Tr.push(rn=e?null:[])}function Vc(){Tr.pop(),rn=Tr[Tr.length-1]||null}let Is=1;function Ko(e,t=!1){Is+=e,e<0&&rn&&t&&(rn.hasOnce=!0)}function Bc(e){return e.dynamicChildren=Is>0?rn||Ar:null,Vc(),Is>0&&rn&&rn.push(e),e}function q(e,t,n,s,o,a){return Bc(u(e,t,n,s,o,a,!0))}function It(e,t,n,s,o){return Bc(Oe(e,t,n,s,o,!0))}function js(e){return e?e.__v_isVNode===!0:!1}function $r(e,t){return e.type===t.type&&e.key===t.key}const Uc=({key:e})=>e??null,Ao=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?bt(e)||Nt(e)||ze(e)?{i:an,r:e,k:t,f:!!n}:e:null);function u(e,t=null,n=null,s=0,o=null,a=e===Re?0:1,c=!1,d=!1){const h={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Uc(t),ref:t&&Ao(t),scopeId:pc,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:s,dynamicProps:o,dynamicChildren:null,appContext:null,ctx:an};return d?(Fo(h,n),a&128&&e.normalize(h)):n&&(h.shapeFlag|=bt(n)?8:16),Is>0&&!c&&rn&&(h.patchFlag>0||a&6)&&h.patchFlag!==32&&rn.push(h),h}const Oe=Ip;function Ip(e,t=null,n=null,s=0,o=null,a=!1){if((!e||e===ip)&&(e=Ft),js(e)){const d=lr(e,t,!0);return n&&Fo(d,n),Is>0&&!a&&rn&&(d.shapeFlag&6?rn[rn.indexOf(e)]=d:rn.push(d)),d.patchFlag=-2,d}if(qp(e)&&(e=e.__vccOpts),t){t=jp(t);let{class:d,style:h}=t;d&&!bt(d)&&(t.class=et(d)),at(h)&&(Ha(h)&&!Le(h)&&(h=Et({},h)),t.style=sr(h))}const c=bt(e)?1:Nc(e)?128:oi(e)?64:at(e)?4:ze(e)?2:0;return u(e,t,n,s,o,c,a,!0)}function jp(e){return e?Ha(e)||Ic(e)?Et({},e):e:null}function lr(e,t,n=!1,s=!1){const{props:o,ref:a,patchFlag:c,children:d,transition:h}=e,y=t?Rp(o||{},t):o,m={__v_isVNode:!0,__v_skip:!0,type:e.type,props:y,key:y&&Uc(y),ref:t&&t.ref?n&&a?Le(a)?a.concat(Ao(t)):[a,Ao(t)]:Ao(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:d,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Re?c===-1?16:c|16:c,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:h,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&lr(e.ssContent),ssFallback:e.ssFallback&&lr(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce,cacheIndex:e.cacheIndex};return h&&s&&ar(m,h.clone(m)),m}function nn(e=" ",t=0){return Oe(ui,null,e,t)}function Dp(e,t){const n=Oe($o,null,e);return n.staticCount=t,n}function Ee(e="",t=!1){return t?(F(),It(Ft,null,e)):Oe(Ft,null,e)}function xn(e){return e==null||typeof e=="boolean"?Oe(Ft):Le(e)?Oe(Re,null,e.slice()):js(e)?Dn(e):Oe(ui,null,String(e))}function Dn(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:lr(e)}function Fo(e,t){let n=0;const{shapeFlag:s}=e;if(t==null)t=null;else if(Le(t))n=16;else if(typeof t=="object")if(s&65){const o=t.default;o&&(o._c&&(o._d=!1),Fo(e,o()),o._c&&(o._d=!0));return}else{n=32;const o=t._;!o&&!Ic(t)?t._ctx=an:o===3&&an&&(an.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else if(ze(t)){if(s&65){Fo(e,{default:t});return}t={default:t,_ctx:an},n=32}else t=String(t),s&64?(n=16,t=[nn(t)]):n=8;e.children=t,e.shapeFlag|=n}function Rp(...e){const t={};for(let n=0;nzt||an;let No,Ds;{const e=ni(),t=(n,s)=>{let o;return(o=e[n])||(o=e[n]=[]),o.push(s),a=>{o.length>1?o.forEach(c=>c(a)):o[0](a)}};No=t("__VUE_INSTANCE_SETTERS__",n=>zt=n),Ds=t("__VUE_SSR_SETTERS__",n=>Rs=n)}const Bs=e=>{const t=zt;return No(e),e.scope.on(),()=>{e.scope.off(),No(t)}},ou=()=>{zt&&zt.scope.off(),No(null)};function Hc(e){return e.vnode.shapeFlag&4}let Rs=!1;function Np(e,t=!1,n=!1){t&&Ds(t);const{props:s,children:o}=e.vnode,a=Hc(e);kp(e,s,a,t),Ep(e,o,n||t);const c=a?Vp(e,t):void 0;return t&&Ds(!1),c}function Vp(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,ap);const{setup:s}=n;if(s){An();const o=e.setupContext=s.length>1?Up(e):null,a=Bs(e),c=Ns(s,e,0,[e.props,o]),d=Ku(c);if(Pn(),a(),(d||e.sp)&&!xs(e)&&_c(e),d){if(c.then(ou,ou),t)return c.then(h=>{Ds(!0);try{iu(e,h,t)}finally{Ds(!1)}}).catch(h=>{si(h,e,0)});e.asyncDep=c}else iu(e,c)}else Wc(e)}function iu(e,t,n){ze(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:at(t)&&(e.setupState=ac(t)),Wc(e)}function Wc(e,t,n){const s=e.type;e.render||(e.render=s.render||En);{const o=Bs(e);An();try{lp(e)}finally{Pn(),o()}}}const Bp={get(e,t){return Kt(e,"get",""),e[t]}};function Up(e){const t=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,Bp),slots:e.slots,emit:e.emit,expose:t}}function ci(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(ac(Td(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Cs)return Cs[n](e)},has(t,n){return n in t||n in Cs}})):e.proxy}function qp(e){return ze(e)&&"__vccOpts"in e}const it=(e,t)=>Dd(e,t,Rs);function Hp(e,t,n){try{Ko(-1);const s=arguments.length;return s===2?at(t)&&!Le(t)?js(t)?Oe(e,null,[t]):Oe(e,t):Oe(e,null,t):(s>3?n=Array.prototype.slice.call(arguments,2):s===3&&js(n)&&(n=[n]),Oe(e,t,n))}finally{Ko(1)}}const Wp="3.5.44";/** * @vue/runtime-dom v3.5.44 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let _a;const iu=typeof window<"u"&&window.trustedTypes;if(iu)try{_a=iu.createPolicy("vue",{createHTML:e=>e})}catch{}const Wc=_a?e=>_a.createHTML(e):e=>e,Wp="http://www.w3.org/2000/svg",zp="http://www.w3.org/1998/Math/MathML",jn=typeof document<"u"?document:null,au=jn&&jn.createElement("template"),Gp={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,s)=>{const o=t==="svg"?jn.createElementNS(Wp,e):t==="mathml"?jn.createElementNS(zp,e):n?jn.createElement(e,{is:n}):jn.createElement(e);return e==="select"&&s&&s.multiple!=null&&o.setAttribute("multiple",s.multiple),o},createText:e=>jn.createTextNode(e),createComment:e=>jn.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>jn.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,s,o,a){const c=n?n.previousSibling:t.lastChild;if(o&&(o===a||o.nextSibling))for(;t.insertBefore(o.cloneNode(!0),n),!(o===a||!(o=o.nextSibling)););else{au.innerHTML=Wc(s==="svg"?`${e}`:s==="mathml"?`${e}`:e);const d=au.content;if(s==="svg"||s==="mathml"){const h=d.firstChild;for(;h.firstChild;)d.appendChild(h.firstChild);d.removeChild(h)}t.insertBefore(d,n)}return[c?c.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Qn="transition",vs="animation",Jr=Symbol("_vtc"),zc={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Gc=Et({},yc,zc),Yp=e=>(e.displayName="Transition",e.props=Gc,e),ns=Yp((e,{slots:t})=>qp(Yd,Yc(e),t)),xr=(e,t=[])=>{Le(e)?e.forEach(n=>n(...t)):e&&e(...t)},lu=e=>e?Le(e)?e.some(t=>t.length>1):e.length>1:!1;function Yc(e){const t={};for(const J in e)J in zc||(t[J]=e[J]);if(e.css===!1)return t;const{name:n="v",type:s,duration:o,enterFromClass:a=`${n}-enter-from`,enterActiveClass:c=`${n}-enter-active`,enterToClass:d=`${n}-enter-to`,appearFromClass:h=a,appearActiveClass:y=c,appearToClass:m=d,leaveFromClass:k=`${n}-leave-from`,leaveActiveClass:D=`${n}-leave-active`,leaveToClass:O=`${n}-leave-to`}=e,K=Jp(o),W=K&&K[0],de=K&&K[1],{onBeforeEnter:Z,onEnter:E,onEnterCancelled:L,onLeave:Q,onLeaveCancelled:le,onBeforeAppear:ce=Z,onAppear:ee=E,onAppearCancelled:A=L}=t,x=(J,Ce,Ke,Xe)=>{J._enterCancelled=Xe,er(J,Ce?m:d),er(J,Ce?y:c),Ke&&Ke()},ie=(J,Ce)=>{J._isLeaving=!1,er(J,k),er(J,O),er(J,D),Ce&&Ce()},xe=J=>(Ce,Ke)=>{const Xe=J?ee:E,He=()=>x(Ce,J,Ke);xr(Xe,[Ce,He]),uu(()=>{er(Ce,J?h:a),bn(Ce,J?m:d),lu(Xe)||cu(Ce,s,W,He)})};return Et(t,{onBeforeEnter(J){xr(Z,[J]),bn(J,a),bn(J,c)},onBeforeAppear(J){xr(ce,[J]),bn(J,h),bn(J,y)},onEnter:xe(!1),onAppear:xe(!0),onLeave(J,Ce){J._isLeaving=!0;const Ke=()=>ie(J,Ce);bn(J,k),J._enterCancelled?(bn(J,D),ka(J)):(ka(J),bn(J,D)),uu(()=>{J._isLeaving&&(er(J,k),bn(J,O),lu(Q)||cu(J,s,de,Ke))}),xr(Q,[J,Ke])},onEnterCancelled(J){x(J,!1,void 0,!0),xr(L,[J])},onAppearCancelled(J){x(J,!0,void 0,!0),xr(A,[J])},onLeaveCancelled(J){ie(J),xr(le,[J])}})}function Jp(e){if(e==null)return null;if(at(e))return[na(e.enter),na(e.leave)];{const t=na(e);return[t,t]}}function na(e){return td(e)}function bn(e,t){t.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[Jr]||(e[Jr]=new Set)).add(t)}function er(e,t){t.split(/\s+/).forEach(s=>s&&e.classList.remove(s));const n=e[Jr];n&&(n.delete(t),n.size||(e[Jr]=void 0))}function uu(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let Xp=0;function cu(e,t,n,s){const o=e._endId=++Xp,a=()=>{o===e._endId&&s()};if(n!=null)return setTimeout(a,n);const{type:c,timeout:d,propCount:h}=Jc(e,t);if(!c)return s();const y=c+"end";let m=0;const k=()=>{e.removeEventListener(y,D),a()},D=O=>{O.target===e&&++m>=h&&k()};setTimeout(()=>{m(n[K]||"").split(", "),o=s(`${Qn}Delay`),a=s(`${Qn}Duration`),c=fu(o,a),d=s(`${vs}Delay`),h=s(`${vs}Duration`),y=fu(d,h);let m=null,k=0,D=0;t===Qn?c>0&&(m=Qn,k=c,D=a.length):t===vs?y>0&&(m=vs,k=y,D=h.length):(k=Math.max(c,y),m=k>0?c>y?Qn:vs:null,D=m?m===Qn?a.length:h.length:0);const O=m===Qn&&/\b(?:transform|all)(?:,|$)/.test(s(`${Qn}Property`).toString());return{type:m,timeout:k,propCount:D,hasTransform:O}}function fu(e,t){for(;e.lengthdu(n)+du(e[s])))}function du(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function ka(e){return(e?e.ownerDocument:document).body.offsetHeight}function Qp(e,t,n){const s=e[Jr];s&&(t=(t?[t,...s]:[...s]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const pu=Symbol("_vod"),Xc=Symbol("_vsh"),Zp=Symbol(""),eh=/(?:^|;)\s*display\s*:/;function th(e,t,n){const s=e.style,o=bt(n);let a=!1;if(n&&!o){if(t)if(bt(t))for(const c of t.split(";")){const d=c.slice(0,c.indexOf(":")).trim();n[d]==null&&gs(s,d,"")}else for(const c in t)n[c]==null&&gs(s,c,"");for(const c in n){c==="display"&&(a=!0);const d=n[c];d!=null?rh(e,c,!bt(t)&&t?t[c]:void 0,d)||gs(s,c,d):gs(s,c,"")}}else if(o){if(t!==n){const c=s[Zp];c&&(n+=";"+c),s.cssText=n,a=eh.test(n)}}else t&&e.removeAttribute("style");pu in e&&((!o||t!==n)&&(e[pu]=a?s.display:""),e[Xc]&&(s.display="none"))}const ko=/\s*!important$/;function gs(e,t,n){if(Le(n))n.forEach(s=>gs(e,t,s));else if(n==null&&(n=""),t.startsWith("--"))ko.test(n)?e.setProperty(t,n.replace(ko,""),"important"):e.setProperty(t,n);else{const s=nh(e,t);ko.test(n)?e.setProperty(cr(s),n.replace(ko,""),"important"):e[s]=n}}const hu=["Webkit","Moz","ms"],ra={};function nh(e,t){const n=ra[t];if(n)return n;let s=hn(t);if(s!=="filter"&&s in e)return ra[t]=s;s=Nu(s);for(let o=0;osa||(uh.then(()=>sa=0),sa=Date.now());function fh(e,t){const n=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=n.attached)return;const o=n.value;if(Le(o)){const a=s.stopImmediatePropagation;s.stopImmediatePropagation=()=>{a.call(s),s._stopped=!0};const c=o.slice(),d=[s];for(let h=0;he.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,dh=(e,t,n,s,o,a)=>{const c=o==="svg";t==="class"?Qp(e,s,c):t==="style"?th(e,n,s):Jo(t)?Xo(t)||oh(e,t,n,s,a):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):ph(e,t,s,c))?(yu(e,t,s),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&mu(e,t,s,c,a,t!=="value")):e._isVueCE&&(hh(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!bt(s)))?yu(e,hn(t),s,a,t):(t==="true-value"?e._trueValue=s:t==="false-value"&&(e._falseValue=s),mu(e,t,s,c))};function ph(e,t,n,s){if(s)return!!(t==="innerHTML"||t==="textContent"||t in e&&bu(t)&&ze(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="sandbox"&&e.tagName==="IFRAME"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const o=e.tagName;if(o==="IMG"||o==="VIDEO"||o==="CANVAS"||o==="SOURCE")return!1}return bu(t)&&bt(n)?!1:t in e}function hh(e,t){const n=e._def.props;if(!n)return!1;const s=hn(t);return Array.isArray(n)?n.some(o=>hn(o)===s):Object.keys(n).some(o=>hn(o)===s)}const Qc=new WeakMap,Zc=new WeakMap,No=Symbol("_moveCb"),wu=Symbol("_enterCb"),xa=new WeakMap,vh=e=>(delete e.props.mode,e),mh=vh({name:"TransitionGroup",props:Et({},Gc,{tag:String,moveClass:String}),setup(e,{slots:t}){const n=Ja(),s=mc();let o,a,c,d;const h=()=>(d===void 0&&(d=o.length>0&&Ch(o[0].el,n.vnode.el,_u(e))),d);return kc(()=>{if(xa.delete(n),!h()){o=[],c=void 0;return}const y=_u(e);o.forEach(gh);const m=c&&xh(c,n.vnode.el);c=void 0,o.forEach(D=>bh(D,m));const k=o.filter(wh);ka(n.vnode.el),k.forEach(D=>{const O=D.el,K=O.style;bn(O,y),K.transform=K.webkitTransform=K.transitionDuration="";const W=O[No]=de=>{de&&de.target!==O||(!de||de.propertyName.endsWith("transform"))&&(O.removeEventListener("transitionend",W),O[No]=null,er(O,y))};O.addEventListener("transitionend",W)}),o=[]}),()=>{const y=rt(e),m=Yc(y);let k=y.tag||Re;if(o=[],d=void 0,a)for(let D=0;Ds.willMove()&&s.item.contains(t));return n&&ui(n.item,n)}function Ch(e,t,n){const s=e.cloneNode(),o=e[Jr];o&&o.forEach(d=>{d.split(/\s+/).forEach(h=>h&&s.classList.remove(h))}),n.split(/\s+/).forEach(d=>d&&s.classList.add(d)),s.style.display="none";const a=t.nodeType===1?t:t.parentNode;a.appendChild(s);const{hasTransform:c}=Jc(s);return a.removeChild(s),c}const Xr=e=>{const t=e.props["onUpdate:modelValue"]||!1;return Le(t)?n=>So(t,n):t};function Sh(e){e.target.composing=!0}function ku(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const Sn=Symbol("_assign"),xo=Symbol("_initialValue");function oa(e,t,n){return t&&(e=e.trim()),n&&(e=Zo(e)),e}const De={created(e,{modifiers:{lazy:t,trim:n,number:s}},o){e.parentNode&&(e.type==="text"?e[xo]=e.defaultValue.replace(/[\r\n]/g,""):e.type==="textarea"&&(e[xo]=e.defaultValue.replace(/\r\n?/g,` -`))),e[Sn]=Xr(o);const a=s||o.props&&o.props.type==="number";nr(e,t?"change":"input",c=>{c.target.composing||e[Sn](oa(e.value,n,a))}),(n||a)&&nr(e,"change",()=>{e.value=oa(e.value,n,a)}),t||(nr(e,"compositionstart",Sh),nr(e,"compositionend",ku),nr(e,"change",ku))},mounted(e,{value:t,modifiers:{trim:n,number:s}}){const o=t??"",a=e[xo];delete e[xo],a!==void 0&&(e.type==="text"||e.type==="textarea")&&e.value!==a?e[Sn](oa(e.value,n,s)):e.value=o},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:s,trim:o,number:a}},c){if(e[Sn]=Xr(c),e.composing)return;const d=(a||e.type==="number")&&!/^0\d/.test(e.value)?Zo(e.value):e.value,h=t??"";if(d===h)return;const y=e.getRootNode();(y instanceof Document||y instanceof ShadowRoot)&&y.activeElement===e&&e.type!=="range"&&(s&&t===n||o&&e.value.trim()===h)||(e.value=h)}},Eh={deep:!0,created(e,t,n){e[Sn]=Xr(n),nr(e,"change",()=>{const s=e._modelValue,o=Ls(e),a=e.checked,c=e[Sn];if(Le(s)){const d=Ra(s,o),h=d!==-1;if(a&&!h)c(s.concat(o));else if(!a&&h){const y=[...s];y.splice(d,1),c(y)}}else if(Bn(s)){const d=new Set(s);a?d.add(o):d.delete(o),c(d)}else c(ef(e,a))})},mounted:xu,beforeUpdate(e,t,n){e[Sn]=Xr(n),xu(e,t,n)}};function xu(e,{value:t,oldValue:n},s){e._modelValue=t;let o;if(Le(t))o=Ra(t,s.props.value)>-1;else if(Bn(t))o=t.has(s.props.value);else{if(t===n)return;o=Un(t,ef(e,!0))}e.checked!==o&&(e.checked=o)}const Fn={deep:!0,created(e,{value:t,modifiers:{number:n}},s){e._modelValue=t,nr(e,"change",()=>{const o=Array.prototype.filter.call(e.options,h=>h.selected).map(h=>n?Zo(Ls(h)):Ls(h)),a=e.multiple,c=a?Bn(e._modelValue)?new Set(o):o:o[0],d=e._pendingValue=[a,a?Le(c)?o.slice():o:c];try{e[Sn](c)}finally{ts(()=>{e._pendingValue===d&&(e._pendingValue=void 0)})}}),e[Sn]=Xr(s)},mounted(e,{value:t}){Cu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Sn]=Xr(n)},updated(e,{value:t}){const n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!$h(t,n[1],n[0]))&&Cu(e,t)}};function $h(e,t,n){if(!n||Le(e))return Un(e,t);if(Bn(e)){if(e.size!==t.length)return!1;for(const s of t)if(!e.has(s))return!1;return!0}return!1}function Cu(e,t){const n=e.multiple,s=Le(t);if(!(n&&!s&&!Bn(t))){for(let o=0,a=e.options.length;oString(y)===String(d)):c.selected=Ra(t,d)>-1}else c.selected=t.has(d);else if(Un(Ls(c),t)){e.selectedIndex!==o&&(e.selectedIndex=o);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function Ls(e){return"_value"in e?e._value:e.value}function ef(e,t){const n=t?"_trueValue":"_falseValue";return n in e?e[n]:t}const Ah=["ctrl","shift","alt","meta"],Ph={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>Ah.some(n=>e[`${n}Key`]&&!t.includes(n))},Mr=(e,t)=>{if(!e)return e;const n=e._withMods||(e._withMods={}),s=t.join(".");return n[s]||(n[s]=(o,...a)=>{for(let c=0;c{const n=e._withKeys||(e._withKeys={}),s=t.join(".");return n[s]||(n[s]=o=>{if(!("key"in o))return;const a=cr(o.key);if(t.some(c=>c===a||Th[c]===a))return e(o)})},Oh=Et({patchProp:dh},Gp);let Su;function Mh(){return Su||(Su=$p(Oh))}const Ih=(...e)=>{const t=Mh().createApp(...e),{mount:n}=t;return t.mount=s=>{const o=Dh(s);if(!o)return;const a=t._component;!ze(a)&&!a.render&&!a.template&&(a.template=o.innerHTML),o.nodeType===1&&(o.textContent="");const c=n(o,!1,jh(o));return o instanceof Element&&(o.removeAttribute("v-cloak"),o.setAttribute("data-v-app","")),c},t};function jh(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Dh(e){return bt(e)?document.querySelector(e):e}function At(e){return''+e+""}const Rh={calendar:At(''),clock:At(''),"check-circle":At(''),edit:At(''),tag:At(''),star:At(''),close:At(''),flag:At(''),chart:At(''),export:At(''),"chevron-left":At(''),"chevron-right":At(''),"chevron-down":At(''),plus:At(''),search:At(''),settings:At(''),memo:At(''),lock:At(''),wallet:At('')},Lh=["innerHTML"],lt=Vt({__name:"Icon",props:{name:{},size:{default:16}},setup(e){const t=e,n=it(()=>Rh[t.name]||"");return(s,o)=>(F(),q("span",{class:"icon",style:sr({width:e.size+"px",height:e.size+"px"}),innerHTML:n.value},null,12,Lh))}}),Kh=["aria-label"],Fh={class:"dialog-title"},Nh={class:"dialog-msg"},Vh={class:"dialog-btns"},Bh=Vt({__name:"ConfirmDialog",props:{open:{type:Boolean},title:{},message:{},confirmText:{default:"确认"},cancelText:{default:"取消"},danger:{type:Boolean,default:!1}},emits:["cancel","confirm"],setup(e,{emit:t}){const n=e,s=t;function o(a){n.open&&a.key==="Escape"&&s("cancel")}return gt(()=>n.open,a=>{a?window.addEventListener("keydown",o):window.removeEventListener("keydown",o)}),dr(()=>window.removeEventListener("keydown",o)),(a,c)=>(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:c[2]||(c[2]=Mr(d=>s("cancel"),["self"]))},[u("div",{class:"dialog",role:"dialog","aria-label":e.title},[u("div",Fh,re(e.title),1),u("div",Nh,re(e.message),1),u("div",Vh,[u("button",{class:"btn btn-sm",onClick:c[0]||(c[0]=d=>s("cancel"))},re(e.cancelText),1),u("button",{class:et(["btn btn-sm",e.danger?"btn-danger-solid":"btn-primary"]),onClick:c[1]||(c[1]=d=>s("confirm"))},re(e.confirmText),3)])],8,Kh)])):Ee("",!0)]),_:1})]))}}),Gt=(e,t)=>{const n=e.__vccOpts||e;for(const[s,o]of t)n[s]=o;return n},ur=Gt(Bh,[["__scopeId","data-v-f27041d4"]]);var Eu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Uh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var tf={exports:{}};(function(e,t){((n,s)=>{e.exports=s()})(Eu,function(){var n=function(r,i){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(l,f){l.__proto__=f}:function(l,f){for(var p in f)Object.prototype.hasOwnProperty.call(f,p)&&(l[p]=f[p])}))(r,i)},s=function(){return(s=Object.assign||function(r){for(var i,l=1,f=arguments.length;l"u"||a.Promise||(a.Promise=Promise);var y=Object.getPrototypeOf,m={}.hasOwnProperty;function k(r,i){return m.call(r,i)}function D(r,i){typeof i=="function"&&(i=i(y(r))),(typeof Reflect>"u"?c:Reflect.ownKeys)(i).forEach(function(l){K(r,l,i[l])})}var O=Object.defineProperty;function K(r,i,l,f){O(r,i,h(l&&k(l,"get")&&typeof l.get=="function"?{get:l.get,set:l.set,configurable:!0}:{value:l,configurable:!0,writable:!0},f))}function W(r){return{from:function(i){return r.prototype=Object.create(i.prototype),K(r.prototype,"constructor",r),{extend:D.bind(null,r.prototype)}}}}var de=Object.getOwnPropertyDescriptor,Z=[].slice;function E(r,i,l){return Z.call(r,i,l)}function L(r,i){return i(r)}function Q(r){if(!r)throw new Error("Assertion Failed")}function le(r){a.setImmediate?setImmediate(r):setTimeout(r,0)}function ce(r,i){if(typeof i=="string"&&k(r,i))return r[i];if(!i)return r;if(typeof i!="string"){for(var l=[],f=0,p=i.length;fe})}catch{}const zc=xa?e=>xa.createHTML(e):e=>e,zp="http://www.w3.org/2000/svg",Gp="http://www.w3.org/1998/Math/MathML",jn=typeof document<"u"?document:null,lu=jn&&jn.createElement("template"),Yp={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,s)=>{const o=t==="svg"?jn.createElementNS(zp,e):t==="mathml"?jn.createElementNS(Gp,e):n?jn.createElement(e,{is:n}):jn.createElement(e);return e==="select"&&s&&s.multiple!=null&&o.setAttribute("multiple",s.multiple),o},createText:e=>jn.createTextNode(e),createComment:e=>jn.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>jn.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,s,o,a){const c=n?n.previousSibling:t.lastChild;if(o&&(o===a||o.nextSibling))for(;t.insertBefore(o.cloneNode(!0),n),!(o===a||!(o=o.nextSibling)););else{lu.innerHTML=zc(s==="svg"?`${e}`:s==="mathml"?`${e}`:e);const d=lu.content;if(s==="svg"||s==="mathml"){const h=d.firstChild;for(;h.firstChild;)d.appendChild(h.firstChild);d.removeChild(h)}t.insertBefore(d,n)}return[c?c.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Qn="transition",vs="animation",Jr=Symbol("_vtc"),Gc={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Yc=Et({},gc,Gc),Jp=e=>(e.displayName="Transition",e.props=Yc,e),ns=Jp((e,{slots:t})=>Hp(Jd,Jc(e),t)),xr=(e,t=[])=>{Le(e)?e.forEach(n=>n(...t)):e&&e(...t)},uu=e=>e?Le(e)?e.some(t=>t.length>1):e.length>1:!1;function Jc(e){const t={};for(const J in e)J in Gc||(t[J]=e[J]);if(e.css===!1)return t;const{name:n="v",type:s,duration:o,enterFromClass:a=`${n}-enter-from`,enterActiveClass:c=`${n}-enter-active`,enterToClass:d=`${n}-enter-to`,appearFromClass:h=a,appearActiveClass:y=c,appearToClass:m=d,leaveFromClass:k=`${n}-leave-from`,leaveActiveClass:D=`${n}-leave-active`,leaveToClass:O=`${n}-leave-to`}=e,K=Xp(o),W=K&&K[0],de=K&&K[1],{onBeforeEnter:Z,onEnter:E,onEnterCancelled:L,onLeave:Q,onLeaveCancelled:le,onBeforeAppear:ce=Z,onAppear:ee=E,onAppearCancelled:A=L}=t,x=(J,xe,Ne,Xe)=>{J._enterCancelled=Xe,er(J,xe?m:d),er(J,xe?y:c),Ne&&Ne()},ie=(J,xe)=>{J._isLeaving=!1,er(J,k),er(J,O),er(J,D),xe&&xe()},Ce=J=>(xe,Ne)=>{const Xe=J?ee:E,He=()=>x(xe,J,Ne);xr(Xe,[xe,He]),cu(()=>{er(xe,J?h:a),bn(xe,J?m:d),uu(Xe)||fu(xe,s,W,He)})};return Et(t,{onBeforeEnter(J){xr(Z,[J]),bn(J,a),bn(J,c)},onBeforeAppear(J){xr(ce,[J]),bn(J,h),bn(J,y)},onEnter:Ce(!1),onAppear:Ce(!0),onLeave(J,xe){J._isLeaving=!0;const Ne=()=>ie(J,xe);bn(J,k),J._enterCancelled?(bn(J,D),Ca(J)):(Ca(J),bn(J,D)),cu(()=>{J._isLeaving&&(er(J,k),bn(J,O),uu(Q)||fu(J,s,de,Ne))}),xr(Q,[J,Ne])},onEnterCancelled(J){x(J,!1,void 0,!0),xr(L,[J])},onAppearCancelled(J){x(J,!0,void 0,!0),xr(A,[J])},onLeaveCancelled(J){ie(J),xr(le,[J])}})}function Xp(e){if(e==null)return null;if(at(e))return[sa(e.enter),sa(e.leave)];{const t=sa(e);return[t,t]}}function sa(e){return nd(e)}function bn(e,t){t.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[Jr]||(e[Jr]=new Set)).add(t)}function er(e,t){t.split(/\s+/).forEach(s=>s&&e.classList.remove(s));const n=e[Jr];n&&(n.delete(t),n.size||(e[Jr]=void 0))}function cu(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let Qp=0;function fu(e,t,n,s){const o=e._endId=++Qp,a=()=>{o===e._endId&&s()};if(n!=null)return setTimeout(a,n);const{type:c,timeout:d,propCount:h}=Xc(e,t);if(!c)return s();const y=c+"end";let m=0;const k=()=>{e.removeEventListener(y,D),a()},D=O=>{O.target===e&&++m>=h&&k()};setTimeout(()=>{m(n[K]||"").split(", "),o=s(`${Qn}Delay`),a=s(`${Qn}Duration`),c=du(o,a),d=s(`${vs}Delay`),h=s(`${vs}Duration`),y=du(d,h);let m=null,k=0,D=0;t===Qn?c>0&&(m=Qn,k=c,D=a.length):t===vs?y>0&&(m=vs,k=y,D=h.length):(k=Math.max(c,y),m=k>0?c>y?Qn:vs:null,D=m?m===Qn?a.length:h.length:0);const O=m===Qn&&/\b(?:transform|all)(?:,|$)/.test(s(`${Qn}Property`).toString());return{type:m,timeout:k,propCount:D,hasTransform:O}}function du(e,t){for(;e.lengthpu(n)+pu(e[s])))}function pu(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function Ca(e){return(e?e.ownerDocument:document).body.offsetHeight}function Zp(e,t,n){const s=e[Jr];s&&(t=(t?[t,...s]:[...s]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const hu=Symbol("_vod"),Qc=Symbol("_vsh"),eh=Symbol(""),th=/(?:^|;)\s*display\s*:/;function nh(e,t,n){const s=e.style,o=bt(n);let a=!1;if(n&&!o){if(t)if(bt(t))for(const c of t.split(";")){const d=c.slice(0,c.indexOf(":")).trim();n[d]==null&&gs(s,d,"")}else for(const c in t)n[c]==null&&gs(s,c,"");for(const c in n){c==="display"&&(a=!0);const d=n[c];d!=null?sh(e,c,!bt(t)&&t?t[c]:void 0,d)||gs(s,c,d):gs(s,c,"")}}else if(o){if(t!==n){const c=s[eh];c&&(n+=";"+c),s.cssText=n,a=th.test(n)}}else t&&e.removeAttribute("style");hu in e&&((!o||t!==n)&&(e[hu]=a?s.display:""),e[Qc]&&(s.display="none"))}const ko=/\s*!important$/;function gs(e,t,n){if(Le(n))n.forEach(s=>gs(e,t,s));else if(n==null&&(n=""),t.startsWith("--"))ko.test(n)?e.setProperty(t,n.replace(ko,""),"important"):e.setProperty(t,n);else{const s=rh(e,t);ko.test(n)?e.setProperty(cr(s),n.replace(ko,""),"important"):e[s]=n}}const vu=["Webkit","Moz","ms"],oa={};function rh(e,t){const n=oa[t];if(n)return n;let s=hn(t);if(s!=="filter"&&s in e)return oa[t]=s;s=Vu(s);for(let o=0;oia||(ch.then(()=>ia=0),ia=Date.now());function dh(e,t){const n=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=n.attached)return;const o=n.value;if(Le(o)){const a=s.stopImmediatePropagation;s.stopImmediatePropagation=()=>{a.call(s),s._stopped=!0};const c=o.slice(),d=[s];for(let h=0;he.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,ph=(e,t,n,s,o,a)=>{const c=o==="svg";t==="class"?Zp(e,s,c):t==="style"?nh(e,n,s):Qo(t)?Zo(t)||ih(e,t,n,s,a):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):hh(e,t,s,c))?(gu(e,t,s),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&yu(e,t,s,c,a,t!=="value")):e._isVueCE&&(vh(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!bt(s)))?gu(e,hn(t),s,a,t):(t==="true-value"?e._trueValue=s:t==="false-value"&&(e._falseValue=s),yu(e,t,s,c))};function hh(e,t,n,s){if(s)return!!(t==="innerHTML"||t==="textContent"||t in e&&wu(t)&&ze(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="sandbox"&&e.tagName==="IFRAME"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const o=e.tagName;if(o==="IMG"||o==="VIDEO"||o==="CANVAS"||o==="SOURCE")return!1}return wu(t)&&bt(n)?!1:t in e}function vh(e,t){const n=e._def.props;if(!n)return!1;const s=hn(t);return Array.isArray(n)?n.some(o=>hn(o)===s):Object.keys(n).some(o=>hn(o)===s)}const Zc=new WeakMap,ef=new WeakMap,Vo=Symbol("_moveCb"),_u=Symbol("_enterCb"),Sa=new WeakMap,mh=e=>(delete e.props.mode,e),yh=mh({name:"TransitionGroup",props:Et({},Yc,{tag:String,moveClass:String}),setup(e,{slots:t}){const n=Xa(),s=yc();let o,a,c,d;const h=()=>(d===void 0&&(d=o.length>0&&Sh(o[0].el,n.vnode.el,ku(e))),d);return xc(()=>{if(Sa.delete(n),!h()){o=[],c=void 0;return}const y=ku(e);o.forEach(bh);const m=c&&Ch(c,n.vnode.el);c=void 0,o.forEach(D=>wh(D,m));const k=o.filter(_h);Ca(n.vnode.el),k.forEach(D=>{const O=D.el,K=O.style;bn(O,y),K.transform=K.webkitTransform=K.transitionDuration="";const W=O[Vo]=de=>{de&&de.target!==O||(!de||de.propertyName.endsWith("transform"))&&(O.removeEventListener("transitionend",W),O[Vo]=null,er(O,y))};O.addEventListener("transitionend",W)}),o=[]}),()=>{const y=rt(e),m=Jc(y);let k=y.tag||Re;if(o=[],d=void 0,a)for(let D=0;Ds.willMove()&&s.item.contains(t));return n&&fi(n.item,n)}function Sh(e,t,n){const s=e.cloneNode(),o=e[Jr];o&&o.forEach(d=>{d.split(/\s+/).forEach(h=>h&&s.classList.remove(h))}),n.split(/\s+/).forEach(d=>d&&s.classList.add(d)),s.style.display="none";const a=t.nodeType===1?t:t.parentNode;a.appendChild(s);const{hasTransform:c}=Xc(s);return a.removeChild(s),c}const Xr=e=>{const t=e.props["onUpdate:modelValue"]||!1;return Le(t)?n=>So(t,n):t};function Eh(e){e.target.composing=!0}function xu(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const Sn=Symbol("_assign"),xo=Symbol("_initialValue");function aa(e,t,n){return t&&(e=e.trim()),n&&(e=ti(e)),e}const De={created(e,{modifiers:{lazy:t,trim:n,number:s}},o){e.parentNode&&(e.type==="text"?e[xo]=e.defaultValue.replace(/[\r\n]/g,""):e.type==="textarea"&&(e[xo]=e.defaultValue.replace(/\r\n?/g,` +`))),e[Sn]=Xr(o);const a=s||o.props&&o.props.type==="number";nr(e,t?"change":"input",c=>{c.target.composing||e[Sn](aa(e.value,n,a))}),(n||a)&&nr(e,"change",()=>{e.value=aa(e.value,n,a)}),t||(nr(e,"compositionstart",Eh),nr(e,"compositionend",xu),nr(e,"change",xu))},mounted(e,{value:t,modifiers:{trim:n,number:s}}){const o=t??"",a=e[xo];delete e[xo],a!==void 0&&(e.type==="text"||e.type==="textarea")&&e.value!==a?e[Sn](aa(e.value,n,s)):e.value=o},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:s,trim:o,number:a}},c){if(e[Sn]=Xr(c),e.composing)return;const d=(a||e.type==="number")&&!/^0\d/.test(e.value)?ti(e.value):e.value,h=t??"";if(d===h)return;const y=e.getRootNode();(y instanceof Document||y instanceof ShadowRoot)&&y.activeElement===e&&e.type!=="range"&&(s&&t===n||o&&e.value.trim()===h)||(e.value=h)}},$h={deep:!0,created(e,t,n){e[Sn]=Xr(n),nr(e,"change",()=>{const s=e._modelValue,o=Ls(e),a=e.checked,c=e[Sn];if(Le(s)){const d=La(s,o),h=d!==-1;if(a&&!h)c(s.concat(o));else if(!a&&h){const y=[...s];y.splice(d,1),c(y)}}else if(Bn(s)){const d=new Set(s);a?d.add(o):d.delete(o),c(d)}else c(tf(e,a))})},mounted:Cu,beforeUpdate(e,t,n){e[Sn]=Xr(n),Cu(e,t,n)}};function Cu(e,{value:t,oldValue:n},s){e._modelValue=t;let o;if(Le(t))o=La(t,s.props.value)>-1;else if(Bn(t))o=t.has(s.props.value);else{if(t===n)return;o=Un(t,tf(e,!0))}e.checked!==o&&(e.checked=o)}const Fn={deep:!0,created(e,{value:t,modifiers:{number:n}},s){e._modelValue=t,nr(e,"change",()=>{const o=Array.prototype.filter.call(e.options,h=>h.selected).map(h=>n?ti(Ls(h)):Ls(h)),a=e.multiple,c=a?Bn(e._modelValue)?new Set(o):o:o[0],d=e._pendingValue=[a,a?Le(c)?o.slice():o:c];try{e[Sn](c)}finally{ts(()=>{e._pendingValue===d&&(e._pendingValue=void 0)})}}),e[Sn]=Xr(s)},mounted(e,{value:t}){Su(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Sn]=Xr(n)},updated(e,{value:t}){const n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!Ah(t,n[1],n[0]))&&Su(e,t)}};function Ah(e,t,n){if(!n||Le(e))return Un(e,t);if(Bn(e)){if(e.size!==t.length)return!1;for(const s of t)if(!e.has(s))return!1;return!0}return!1}function Su(e,t){const n=e.multiple,s=Le(t);if(!(n&&!s&&!Bn(t))){for(let o=0,a=e.options.length;oString(y)===String(d)):c.selected=La(t,d)>-1}else c.selected=t.has(d);else if(Un(Ls(c),t)){e.selectedIndex!==o&&(e.selectedIndex=o);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function Ls(e){return"_value"in e?e._value:e.value}function tf(e,t){const n=t?"_trueValue":"_falseValue";return n in e?e[n]:t}const Ph=["ctrl","shift","alt","meta"],Th={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>Ph.some(n=>e[`${n}Key`]&&!t.includes(n))},Mr=(e,t)=>{if(!e)return e;const n=e._withMods||(e._withMods={}),s=t.join(".");return n[s]||(n[s]=(o,...a)=>{for(let c=0;c{const n=e._withKeys||(e._withKeys={}),s=t.join(".");return n[s]||(n[s]=o=>{if(!("key"in o))return;const a=cr(o.key);if(t.some(c=>c===a||Oh[c]===a))return e(o)})},Mh=Et({patchProp:ph},Yp);let Eu;function Ih(){return Eu||(Eu=Ap(Mh))}const jh=(...e)=>{const t=Ih().createApp(...e),{mount:n}=t;return t.mount=s=>{const o=Rh(s);if(!o)return;const a=t._component;!ze(a)&&!a.render&&!a.template&&(a.template=o.innerHTML),o.nodeType===1&&(o.textContent="");const c=n(o,!1,Dh(o));return o instanceof Element&&(o.removeAttribute("v-cloak"),o.setAttribute("data-v-app","")),c},t};function Dh(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Rh(e){return bt(e)?document.querySelector(e):e}function At(e){return''+e+""}const Lh={calendar:At(''),clock:At(''),"check-circle":At(''),edit:At(''),tag:At(''),star:At(''),close:At(''),flag:At(''),chart:At(''),export:At(''),"chevron-left":At(''),"chevron-right":At(''),"chevron-down":At(''),plus:At(''),search:At(''),settings:At(''),memo:At(''),lock:At(''),wallet:At('')},Kh=["innerHTML"],lt=Vt({__name:"Icon",props:{name:{},size:{default:16}},setup(e){const t=e,n=it(()=>Lh[t.name]||"");return(s,o)=>(F(),q("span",{class:"icon",style:sr({width:e.size+"px",height:e.size+"px"}),innerHTML:n.value},null,12,Kh))}}),Fh=["aria-label"],Nh={class:"dialog-title"},Vh={class:"dialog-msg"},Bh={class:"dialog-btns"},Uh=Vt({__name:"ConfirmDialog",props:{open:{type:Boolean},title:{},message:{},confirmText:{default:"确认"},cancelText:{default:"取消"},danger:{type:Boolean,default:!1}},emits:["cancel","confirm"],setup(e,{emit:t}){const n=e,s=t;function o(a){n.open&&a.key==="Escape"&&s("cancel")}return gt(()=>n.open,a=>{a?window.addEventListener("keydown",o):window.removeEventListener("keydown",o)}),dr(()=>window.removeEventListener("keydown",o)),(a,c)=>(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:c[2]||(c[2]=Mr(d=>s("cancel"),["self"]))},[u("div",{class:"dialog",role:"dialog","aria-label":e.title},[u("div",Nh,re(e.title),1),u("div",Vh,re(e.message),1),u("div",Bh,[u("button",{class:"btn btn-sm",onClick:c[0]||(c[0]=d=>s("cancel"))},re(e.cancelText),1),u("button",{class:et(["btn btn-sm",e.danger?"btn-danger-solid":"btn-primary"]),onClick:c[1]||(c[1]=d=>s("confirm"))},re(e.confirmText),3)])],8,Fh)])):Ee("",!0)]),_:1})]))}}),Gt=(e,t)=>{const n=e.__vccOpts||e;for(const[s,o]of t)n[s]=o;return n},ur=Gt(Uh,[["__scopeId","data-v-f27041d4"]]);var $u=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qh(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var nf={exports:{}};(function(e,t){((n,s)=>{e.exports=s()})($u,function(){var n=function(r,i){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(l,f){l.__proto__=f}:function(l,f){for(var p in f)Object.prototype.hasOwnProperty.call(f,p)&&(l[p]=f[p])}))(r,i)},s=function(){return(s=Object.assign||function(r){for(var i,l=1,f=arguments.length;l"u"||a.Promise||(a.Promise=Promise);var y=Object.getPrototypeOf,m={}.hasOwnProperty;function k(r,i){return m.call(r,i)}function D(r,i){typeof i=="function"&&(i=i(y(r))),(typeof Reflect>"u"?c:Reflect.ownKeys)(i).forEach(function(l){K(r,l,i[l])})}var O=Object.defineProperty;function K(r,i,l,f){O(r,i,h(l&&k(l,"get")&&typeof l.get=="function"?{get:l.get,set:l.set,configurable:!0}:{value:l,configurable:!0,writable:!0},f))}function W(r){return{from:function(i){return r.prototype=Object.create(i.prototype),K(r.prototype,"constructor",r),{extend:D.bind(null,r.prototype)}}}}var de=Object.getOwnPropertyDescriptor,Z=[].slice;function E(r,i,l){return Z.call(r,i,l)}function L(r,i){return i(r)}function Q(r){if(!r)throw new Error("Assertion Failed")}function le(r){a.setImmediate?setImmediate(r):setTimeout(r,0)}function ce(r,i){if(typeof i=="string"&&k(r,i))return r[i];if(!i)return r;if(typeof i!="string"){for(var l=[],f=0,p=i.length;f"u"?[]:(Ye=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[Je=crypto.subtle.digest("SHA-512",new Uint8Array([0])),y(Je),Ye]:[Ye,y(Ye),Ye]),Ye=Je[0],Br=Je[1],Br=Br&&Br.then,Qe=Ye&&Ye.constructor,vt=!!Je[2],_t=function(r,i){Hn.push([r,i]),Bt&&(queueMicrotask($f),Bt=!1)},Xt=!0,Bt=!0,Zt=[],pr=[],Ot=P,$t={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:g,pgp:!1,env:{},finalize:g},Ie=$t,Hn=[],hr=0,Ws=[];function Se(r){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var i=this._PSD=Ie;if(typeof r!="function"){if(r!==Ae)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&yi(this,this._value)}else this._state=null,this._value=null,++i.ref,function l(f,p){try{p(function(v){if(f._state===null){if(v===f)throw new TypeError("A promise cannot be resolved with itself.");var b=f._lib&&Rr();v&&typeof v.then=="function"?l(f,function(_,S){v instanceof Se?v._then(_,S):v.then(_,S)}):(f._state=!0,f._value=v,al(f)),b&&Lr()}},yi.bind(null,f))}catch(v){yi(f,v)}}(this,r)}var mi={get:function(){var r=Ie,i=Js;function l(f,p){var v=this,b=!r.global&&(r!==Ie||i!==Js),_=b&&!zn(),S=new Se(function(V,T){gi(v,new il(ul(f,r,b,_),ul(p,r,b,_),V,T,r))});return this._consoleTask&&(S._consoleTask=this._consoleTask),S}return l.prototype=Ae,l},set:function(r){K(this,"then",r&&r.prototype===Ae?mi:{get:function(){return r},set:mi.set})}};function il(r,i,l,f,p){this.onFulfilled=typeof r=="function"?r:null,this.onRejected=typeof i=="function"?i:null,this.resolve=l,this.reject=f,this.psd=p}function yi(r,i){var l,f;pr.push(i),r._state===null&&(l=r._lib&&Rr(),i=Ot(i),r._state=!1,r._value=i,f=r,Zt.some(function(p){return p._value===f._value})||Zt.push(f),al(r),l)&&Lr()}function al(r){var i=r._listeners;r._listeners=[];for(var l=0,f=i.length;l{for(var b=Zt.length;b;)if(Zt[--b]._value===v._value)return Zt.splice(b,1)})(i),l.resolve(f)}catch(v){l.reject(v)}finally{--hr==0&&bi(),--l.psd.ref||l.psd.finalize()}}function $f(){vr($t,function(){Rr()&&Lr()})}function Rr(){var r=Xt;return Bt=Xt=!1,r}function Lr(){var r,i,l;do for(;0.",cl="String expected.",Qs="__dbnames",_i="readonly",ki="readwrite";function yr(r,i){return r?i?function(){return r.apply(this,arguments)&&i.apply(this,arguments)}:r:i}var fl={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Zs(r){return typeof r!="string"||/\./.test(r)?function(i){return i}:function(i){return i[r]===void 0&&r in i&&delete(i=Ce(i))[r],i}}function dl(){throw je.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function tt(r,i){try{var l=pl(r),f=pl(i);if(l!==f)return l==="Array"?1:f==="Array"?-1:l==="binary"?1:f==="binary"?-1:l==="string"?1:f==="string"?-1:l==="Date"?1:f!=="Date"?NaN:-1;switch(l){case"number":case"Date":case"string":return i{var _=T,S=b;if(typeof S!="function"&&S!==null)throw new TypeError("Class extends value "+String(S)+" is not a constructor or null");function V(){this.constructor=_}function T(){return b!==null&&b.apply(this,arguments)||this}return n(_,S),_.prototype=S===null?Object.create(S):(V.prototype=S.prototype,new V),Object.defineProperty(T.prototype,"db",{get:function(){return i},enumerable:!1,configurable:!0}),T.prototype.table=function(){return l},T})(r)),new Set),p=r.prototype;p;p=y(p))Object.getOwnPropertyNames(p).forEach(function(b){return f.add(b)});function v(b){if(!b)return b;var _,S=Object.create(r.prototype);for(_ in b)if(!f.has(_))try{S[_]=b[_]}catch{}return S}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=v,this.hook("reading",v),r},ft.prototype.defineClass=function(){return this.mapToClass(function(r){h(this,r)})},ft.prototype.add=function(r,i){var l=this,f=this.schema.primKey,p=f.auto,v=f.keyPath,b=r;return v&&p&&(b=Zs(v)(r)),this._trans("readwrite",function(_){return l.core.mutate({trans:_,type:"add",keys:i!=null?[i]:null,values:[b]})}).then(function(_){return _.numFailures?Se.reject(_.failures[0]):_.lastResult}).then(function(_){if(v)try{ee(r,v,_)}catch{}return _})},ft.prototype.upsert=function(r,i){var l=this,f=this.schema.primKey.keyPath;return this._trans("readwrite",function(p){return l.core.get({trans:p,key:r}).then(function(v){var b=v??{};return ml(b,i),f&&ee(b,f,r),l.core.mutate({trans:p,type:"put",values:[b],keys:[r],upsert:!0,updates:{keys:[r],changeSpecs:[i]}}).then(function(_){return _.numFailures?Se.reject(_.failures[0]):!!v})})})},ft.prototype.update=function(r,i){return typeof r!="object"||d(r)?this.where(":id").equals(r).modify(i):(r=ce(r,this.schema.primKey.keyPath))===void 0?Ct(new je.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(r).modify(i)},ft.prototype.put=function(r,i){var l=this,f=this.schema.primKey,p=f.auto,v=f.keyPath,b=r;return v&&p&&(b=Zs(v)(r)),this._trans("readwrite",function(_){return l.core.mutate({trans:_,type:"put",values:[b],keys:i!=null?[i]:null})}).then(function(_){return _.numFailures?Se.reject(_.failures[0]):_.lastResult}).then(function(_){if(v)try{ee(r,v,_)}catch{}return _})},ft.prototype.delete=function(r){var i=this;return this._trans("readwrite",function(l){return i.core.mutate({trans:l,type:"delete",keys:[r]}).then(function(f){return eo(i,[r],f)}).then(function(f){return f.numFailures?Se.reject(f.failures[0]):void 0})})},ft.prototype.clear=function(){var r=this;return this._trans("readwrite",function(i){return r.core.mutate({trans:i,type:"deleteRange",range:fl}).then(function(l){return eo(r,null,l)})}).then(function(i){return i.numFailures?Se.reject(i.failures[0]):void 0})},ft.prototype.bulkGet=function(r){var i=this;return this._trans("readonly",function(l){return i.core.getMany({keys:r,trans:l}).then(function(f){return f.map(function(p){return i.hook.reading.fire(p)})})})},ft.prototype.bulkAdd=function(r,i,l){var f=this,p=Array.isArray(i)?i:void 0,v=(l=l||(p?void 0:i))?l.allKeys:void 0;return this._trans("readwrite",function(b){var _=f.schema.primKey,V=_.auto,_=_.keyPath;if(_&&p)throw new je.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(p&&p.length!==r.length)throw new je.InvalidArgument("Arguments objects and keys must have the same length");var S=r.length,V=_&&V?r.map(Zs(_)):r;return f.core.mutate({trans:b,type:"add",keys:p,values:V,wantResults:v}).then(function(T){var C=T.numFailures,$=T.failures;if(C===0)return v?T.results:T.lastResult;throw new ht("".concat(f.name,".bulkAdd(): ").concat(C," of ").concat(S," operations failed"),$)})})},ft.prototype.bulkPut=function(r,i,l){var f=this,p=Array.isArray(i)?i:void 0,v=(l=l||(p?void 0:i))?l.allKeys:void 0;return this._trans("readwrite",function(b){var _=f.schema.primKey,V=_.auto,_=_.keyPath;if(_&&p)throw new je.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(p&&p.length!==r.length)throw new je.InvalidArgument("Arguments objects and keys must have the same length");var S=r.length,V=_&&V?r.map(Zs(_)):r;return f.core.mutate({trans:b,type:"put",keys:p,values:V,wantResults:v}).then(function(T){var C=T.numFailures,$=T.failures;if(C===0)return v?T.results:T.lastResult;throw new ht("".concat(f.name,".bulkPut(): ").concat(C," of ").concat(S," operations failed"),$)})})},ft.prototype.bulkUpdate=function(r){var i=this,l=this.core,f=r.map(function(b){return b.key}),p=r.map(function(b){return b.changes}),v=[];return this._trans("readwrite",function(b){return l.getMany({trans:b,keys:f,cache:"clone"}).then(function(_){var S=[],V=[],T=(r.forEach(function(C,$){var R=C.key,I=C.changes,M=_[$];if(M){for(var j=0,z=Object.keys(I);jB+te&&j(B+V)})})}var z=Fr(l)&&l.limit===1/0&&(typeof r!="function"||I)&&{index:l.index,range:l.range};return j(0).then(function(){if(0{for(var Be=Math.min(me.length,Te.length),Ge=-1,Ze=0;Ze=$})).length===0?Se.resolve():(j.forEach(function(B){M.push(function(){var te,pe,ve,_e=z,me=B._cfg.dbschema,Pe=(uo(C,_e,I),uo(C,me,I),z=C._dbSchema=me,Ti(_e,me)),be=(Pe.add.forEach(function(Te){Oi(I,Te[0],Te[1].primKey,Te[1].indexes)}),Pe.change.forEach(function(Te){if(Te.recreate)throw new je.Upgrade("Not yet support for changing primary key");var he=I.objectStore(Te.name);Te.add.forEach(function(Ve){return ao(he,Ve)}),Te.change.forEach(function(Ve){he.deleteIndex(Ve.name),ao(he,Ve)}),Te.del.forEach(function(Ve){return he.deleteIndex(Ve)})}),B._cfg.contentUpgrade);if(be&&B._cfg.version>$)return oo(C,I),R._memoizedTables={},te=A(me),Pe.del.forEach(function(Te){te[Te]=_e[Te]}),Pi(C,[C.Transaction.prototype]),io(C,[C.Transaction.prototype],c(te),te),R.schema=te,(pe=fe(be))&&Kr(),me=Se.follow(function(){var Te;(ve=be(R))&&pe&&(Te=zn.bind(null,null),ve.then(Te,Te))}),ve&&typeof ve.then=="function"?Se.resolve(ve):me.then(function(){return ve})}),M.push(function(te){var pe,ve,_e=B._cfg.dbschema;pe=_e,ve=te,[].slice.call(ve.db.objectStoreNames).forEach(function(me){return pe[me]==null&&ve.db.deleteObjectStore(me)}),Pi(C,[C.Transaction.prototype]),io(C,[C.Transaction.prototype],C._storeNames,C._dbSchema),R.schema=C._dbSchema}),M.push(function(te){C.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(C.idbdb.version/10)===B._cfg.version?(C.idbdb.deleteObjectStore("$meta"),delete C._dbSchema.$meta,C._storeNames=C._storeNames.filter(function(pe){return pe!=="$meta"})):te.objectStore("$meta").put(B._cfg.version,"version"))})}),function B(){return M.length?Se.resolve(M.shift()(R.idbtrans)).then(B):Se.resolve()}().then(function(){Sl(z,I)}))}).catch(b);var S,V;c(p).forEach(function(T){Oi(l,T,p[T].primKey,p[T].indexes)}),oo(r,l),Se.follow(function(){return r.on.populate.fire(v)}).catch(b)})}function Nf(r,i){Sl(r._dbSchema,i),i.db.version%10!=0||i.objectStoreNames.contains("$meta")||i.db.createObjectStore("$meta").add(Math.ceil(i.db.version/10-1),"version");var l=lo(0,r.idbdb,i);uo(r,r._dbSchema,i);for(var f=0,p=Ti(l,r._dbSchema).change;f{if(b.change.length||b.recreate)return console.warn("Unable to patch indexes of table ".concat(b.name," because it has changes on the type of index or primary key.")),{value:void 0};var _=i.objectStore(b.name);b.add.forEach(function(S){U&&console.debug("Dexie upgrade patch: Creating missing index ".concat(b.name,".").concat(S.src)),ao(_,S)})})(p[f]);if(typeof v=="object")return v.value}}function Ti(r,i){var l,f={del:[],add:[],change:[]};for(l in r)i[l]||f.del.push(l);for(l in i){var p=r[l],v=i[l];if(p){var b={name:l,def:v,recreate:!1,del:[],add:[],change:[]};if(""+(p.primKey.keyPath||"")!=""+(v.primKey.keyPath||"")||p.primKey.auto!==v.primKey.auto)b.recreate=!0,f.change.push(b);else{var _=p.idxByName,S=v.idxByName,V=void 0;for(V in _)S[V]||b.del.push(V);for(V in S){var T=_[V],C=S[V];T?T.src!==C.src&&b.change.push(C):b.add.push(C)}(0{var r,i,l;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(r=new Set,i=new FinalizationRegistry(function(f){r.delete(f)}),{toArray:function(){return Array.from(r).map(function(f){return f.deref()}).filter(function(f){return f!==void 0})},add:function(f){var p=new WeakRef(f._novip);r.add(p),i.register(f._novip,p,p),r.size>f._options.maxConnections&&(p=r.values().next().value,r.delete(p),i.unregister(p))},remove:function(f){if(f)for(var p=r.values(),v=p.next();!v.done;){var b=v.value;if(b.deref()===f._novip)return r.delete(b),void i.unregister(b);v=p.next()}}}):(l=[],{toArray:function(){return l},add:function(f){l.push(f._novip)},remove:function(f){f&&(f=l.indexOf(f._novip))!==-1&&l.splice(f,1)}})})();function Mi(r,i){var l=r._dbNamesDB;return l||(l=r._dbNamesDB=new Mn(Qs,{addons:[],indexedDB:r,IDBKeyRange:i})).version(1).stores({dbnames:"name"}),l.table("dbnames")}function Ii(r){return r&&typeof r.databases=="function"}function ji(r){return Wn(function(){return Ie.letThrough=!0,r()})}function Di(r){return!("from"in r)}var Dt=function(r,i){var l;if(!this)return l=new Dt,r&&"d"in r&&h(l,r),l;h(this,arguments.length?{d:1,from:r,to:1Math.pow(2,62)?0:j.oldVersion,C=z<1,r.idbdb=M.result,v&&Nf(r,T),Ff(r,z/10,T,R))},R),M.onsuccess=mt(function(){T=null;var j,z,B,te,pe,ve,_e=r.idbdb=M.result,me=E(_e.objectStoreNames);if(0"u"?Se.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function($){function R(){return indexedDB.databases().finally($)}S=setInterval(R,100),R()}).finally(function(){return clearInterval(S)}):Promise.resolve()).then(_)]).then(function(){return b(),i.onReadyBeingFired=[],Se.resolve(ji(function(){return r.on.ready.fire(r.vip)})).then(function $(){var R;if(0i.limit?f.length=i.limit:r.length===i.limit&&f.length{if(l===void 0)return f!==void 0?-1:0;if(f===void 0)return 1;if((l=tt(l,f))===0){if(p&&v)return 0;if(p)return 1;if(v)return-1}return l})(r.lower,i.lower,r.lowerOpen,i.lowerOpen)<=0&&0<=((l,f,p,v)=>{if(l===void 0)return f!==void 0?1:0;if(f===void 0)return-1;if((l=tt(l,f))===0){if(p&&v)return 0;if(p)return-1;if(v)return 1}return l})(r.upper,i.upper,r.upperOpen,i.upperOpen)}function Gf(r,i,l,f){r.subscribers.add(l),f.addEventListener("abort",function(){var p,v;r.subscribers.delete(l),r.subscribers.size===0&&(p=r,v=i,setTimeout(function(){p.subscribers.size===0&&ge(v,p)},3e3))})}var Yf={stack:"dbcore",level:0,name:"Cache",create:function(r){var i=r.schema.name;return s(s({},r),{transaction:function(l,f,p){var v,b,_=r.transaction(l,f,p);return f==="readwrite"&&(p=(v=new AbortController).signal,_.addEventListener("abort",(b=function(S){return function(){if(v.abort(),f==="readwrite"){for(var V=new Set,T=0,C=l;T{var z=gr["idb://".concat(R,"/").concat(I)];if(!z)return[];if(!(R=z.queries[M]))return[null,!1,z,null];var B=R[(j.query?j.query.index.name:null)||""];if(!B)return[null,!1,z,null];switch(M){case"query":var te=(pe=j.direction)!=null?pe:"next",pe=B.find(function(ve){var _e;return ve.req.limit===j.limit&&ve.req.values===j.values&&((_e=ve.req.direction)!=null?_e:"next")===te&&Rl(ve.req.query.range,j.query.range)});return pe?[pe,!0,z,B]:[B.find(function(ve){var _e;return("limit"in ve.req?ve.req.limit:1/0)>=j.limit&&((_e=ve.req.direction)!=null?_e:"next")===te&&(!j.values||ve.req.values)&&zf(ve.req.query.range,j.query.range)}),!1,z,B];case"count":return pe=B.find(function(ve){return Rl(ve.req.query.range,j.query.range)}),[pe,!!pe,z,B]}})(i,l,"query",v),$=C[0],V=C[2],T=C[3],$&&C[1]?$.obsSet=v.obsSet:(C=f.query(v).then(function(R){var I=R.result;if($&&($.res=I),b){for(var M=0,j=I.length;M{var pe=Rr();try{v&&Kr();var ve=Wn(r,te);return ve=v?ve.finally(zn):ve}finally{pe&&Lr()}})(z={subscr:j,signal:b.signal,requery:$,querier:r,trans:null}),C||(Jn.storagemutated.subscribe(I),C=!0),Promise.resolve(B).then(function(te){l=!0,i=te,_||z.signal.aborted||(R()||(V=j,R())?$():(S={},wi(function(){return!_&&p.next&&p.next(te)})))},function(te){l=!1,["DatabaseClosedError","AbortError"].includes(te==null?void 0:te.name)||_||wi(function(){_||p.error&&p.error(te)})}))};return setTimeout($,0),T});return f.hasValue=function(){return l},f.getValue=function(){return i},f}var br=Mn;function Hi(r){var i=Xn;try{Xn=!0,Jn.storagemutated.fire(r),Fi(r,!0)}finally{Xn=i}}D(br,s(s({},G),{delete:function(r){return new br(r,{addons:[]}).delete()},exists:function(r){return new br(r,{addons:[]}).open().then(function(i){return i.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(r){try{return i=br.dependencies,l=i.indexedDB,i=i.IDBKeyRange,(Ii(l)?Promise.resolve(l.databases()).then(function(f){return f.map(function(p){return p.name}).filter(function(p){return p!==Qs})}):Mi(l,i).toCollection().primaryKeys()).then(r)}catch{return Ct(new je.MissingAPI)}var i,l},defineClass:function(){return function(r){h(this,r)}},ignoreTransaction:function(r){return Ie.trans?vr(Ie.transless||$t,r):r()},vip:ji,async:function(r){return function(){try{var i=Ni(r.apply(this,arguments));return i&&typeof i.then=="function"?i:Se.resolve(i)}catch(l){return Ct(l)}}},spawn:function(r,i,l){try{var f=Ni(r.apply(l,i||[]));return f&&typeof f.then=="function"?f:Se.resolve(f)}catch(p){return Ct(p)}},currentTransaction:{get:function(){return Ie.trans||null}},waitFor:function(r,i){return r=Se.resolve(typeof r=="function"?br.ignoreTransaction(r):r).timeout(i||6e4),Ie.trans?Ie.trans.waitFor(r):r},Promise:Se,debug:{get:function(){return U},set:function(r){Y(r)}},derive:W,extend:h,props:D,override:L,Events:os,on:Jn,liveQuery:Ll,extendObservabilitySet:fo,getByKeyPath:ce,setByKeyPath:ee,delByKeyPath:function(r,i){typeof i=="string"?ee(r,i,void 0):"length"in i&&[].map.call(i,function(l){ee(r,l,void 0)})},shallowClone:A,deepClone:Ce,getObjectDiff:Vi,cmp:tt,asap:le,minKey:-1/0,addons:[],connections:{get:cs.toArray},errnames:Yt,dependencies:mo,cache:gr,semVer:"4.4.6",version:"4.4.6".split(".").map(function(r){return parseInt(r)}).reduce(function(r,i,l){return r+i/Math.pow(10,2*l)})})),br.maxKey=ls(br.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Jn(so,function(r){Xn||(r=new CustomEvent(Si,{detail:r}),Xn=!0,dispatchEvent(r),Xn=!1)}),addEventListener(Si,function(r){r=r.detail,Xn||Hi(r)}));var Ur,Xn=!1,Kl=function(){};return typeof BroadcastChannel<"u"&&((Kl=function(){(Ur=new BroadcastChannel(Si)).onmessage=function(r){return r.data&&Hi(r.data)}})(),typeof Ur.unref=="function"&&Ur.unref(),Jn(so,function(r){Xn||Ur.postMessage(r)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(r){if(!Mn.disableBfCache&&r.persisted){U&&console.debug("Dexie: handling persisted pagehide"),Ur!=null&&Ur.close();for(var i=0,l=cs.toArray();in.key===e);return t?t.label:"其他"}const zh={class:"dialog",role:"dialog","aria-label":"编辑工作记录"},Gh={class:"dialog-head"},Yh={key:0,class:"muted dialog-sub"},Jh={class:"dialog-body"},Xh={class:"form-grid"},Qh={class:"field span2"},Zh={key:0,class:"form-error"},ev={class:"field"},tv=["value"],nv={class:"field"},rv=["value"],sv={class:"field"},ov={class:"field"},iv={class:"field span2"},av={class:"field"},lv={class:"field"},uv={class:"dialog-btns"},cv=Vt({__name:"EditLogDialog",props:{open:{type:Boolean},item:{},projects:{},date:{}},emits:["cancel","save"],setup(e,{emit:t}){const n=e,s=t,o=N(""),a=N(null),c=N("dev"),d=N(null),h=N(""),y=N(""),m=N(0),k=N(0),D=N(""),O=N(null),K=it(()=>{var L;const Z=n.projects.filter(Q=>Q.archived!==1),E=(L=n.item)==null?void 0:L.project_id;if(E&&!Z.some(Q=>Q.id===E)){const Q=n.projects.find(ce=>ce.id===E),le=Z.slice();return Q&&le.unshift({...Q,name:Q.name+"(已归档)"}),le}return Z});function W(Z){n.open&&Z.key==="Escape"&&s("cancel")}gt(()=>n.open,async Z=>{var E;if(Z){const L=n.item;o.value=(L==null?void 0:L.content)??"",a.value=(L==null?void 0:L.project_id)??null,c.value=(L==null?void 0:L.category)??"dev",d.value=(L==null?void 0:L.minutes)??null,h.value=(L==null?void 0:L.takeaway)??"",y.value=(L==null?void 0:L.remark)??"",m.value=(L==null?void 0:L.is_milestone)??0,k.value=(L==null?void 0:L.needs_followup)??0,D.value="",window.addEventListener("keydown",W),await ts(),(E=O.value)==null||E.focus()}else window.removeEventListener("keydown",W)}),dr(()=>window.removeEventListener("keydown",W)),gt(o,()=>{D.value&&(D.value="")});function de(){const Z=o.value.trim();if(!Z){D.value="请填写工作内容";return}if(!n.item||!n.item.id){s("cancel");return}s("save",{id:n.item.id,content:Z,project_id:a.value,category:c.value,minutes:d.value&&d.value>0?d.value:null,takeaway:h.value.trim()||null,remark:y.value.trim()||null,is_milestone:m.value?1:0,needs_followup:k.value?1:0})}return(Z,E)=>(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:E[10]||(E[10]=Mr(L=>s("cancel"),["self"]))},[u("div",zh,[u("div",Gh,[u("div",null,[E[11]||(E[11]=u("div",{class:"dialog-title"},"编辑工作记录",-1)),e.date?(F(),q("div",Yh,re(e.date),1)):Ee("",!0)]),u("button",{class:"icon-btn",title:"关闭",onClick:E[0]||(E[0]=L=>s("cancel"))},[Oe(lt,{name:"close",size:16})])]),u("div",Jh,[u("div",Xh,[u("div",Qh,[E[12]||(E[12]=u("label",null,"工作内容(必填)",-1)),$e(u("input",{ref_key:"contentInput",ref:O,class:et(["input",{invalid:D.value}]),"onUpdate:modelValue":E[1]||(E[1]=L=>o.value=L),onKeydown:jt(de,["enter"])},null,34),[[De,o.value]]),D.value?(F(),q("div",Zh,re(D.value),1)):Ee("",!0)]),u("div",ev,[E[14]||(E[14]=u("label",null,"所属项目",-1)),$e(u("select",{class:"select","onUpdate:modelValue":E[2]||(E[2]=L=>a.value=L)},[E[13]||(E[13]=u("option",{value:null},"无项目",-1)),(F(!0),q(Re,null,ut(K.value,L=>(F(),q("option",{key:L.id,value:L.id},re(L.name),9,tv))),128))],512),[[Fn,a.value]])]),u("div",nv,[E[15]||(E[15]=u("label",null,"工作分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":E[3]||(E[3]=L=>c.value=L)},[(F(!0),q(Re,null,ut(Qt(Us),L=>(F(),q("option",{key:L.key,value:L.key},re(L.label),9,rv))),128))],512),[[Fn,c.value]])]),u("div",sv,[E[16]||(E[16]=u("label",null,"耗时(分钟)",-1)),$e(u("input",{class:"input",type:"number",min:"0","onUpdate:modelValue":E[4]||(E[4]=L=>d.value=L),placeholder:"选填"},null,512),[[De,d.value,void 0,{number:!0}]])]),u("div",ov,[E[17]||(E[17]=u("label",null,"主要收获",-1)),$e(u("input",{class:"input","onUpdate:modelValue":E[5]||(E[5]=L=>h.value=L),placeholder:"一句话:学到了什么"},null,512),[[De,h.value]])]),u("div",iv,[E[18]||(E[18]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":E[6]||(E[6]=L=>y.value=L),placeholder:"背景、链接、未决事项(选填)"},null,512),[[De,y.value]])]),u("div",av,[E[19]||(E[19]=u("label",null,"成果标记",-1)),u("button",{class:et(["toggle-btn",{on:m.value===1}]),onClick:E[7]||(E[7]=L=>m.value=m.value===1?0:1)},re(m.value===1?"已标记为成果":"未标记"),3)]),u("div",lv,[E[20]||(E[20]=u("label",null,"待跟进",-1)),u("button",{class:et(["toggle-btn",{onwarn:k.value===1}]),onClick:E[8]||(E[8]=L=>k.value=k.value===1?0:1)},re(k.value===1?"需要跟进":"无需跟进"),3)])])]),u("div",uv,[u("button",{class:"btn btn-sm",onClick:E[9]||(E[9]=L=>s("cancel"))},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:de},"保存修改")])])])):Ee("",!0)]),_:1})]))}}),fv=Gt(cv,[["__scopeId","data-v-63bc0b48"]]);function Ss(e){return e<10?"0"+e:String(e)}function Nn(e){return e.getFullYear()+"-"+Ss(e.getMonth()+1)+"-"+Ss(e.getDate())}function xt(){return Nn(new Date)}function wt(){const e=new Date;return Nn(e)+"T"+Ss(e.getHours())+":"+Ss(e.getMinutes())+":"+Ss(e.getSeconds())}function Vn(e){if(!e)return"--:--";const t=e.indexOf("T");return t>=0?e.slice(t+1,t+6):e.slice(0,5)}function rs(e){const t=e.split("-").map(Number);return new Date(t[0],t[1]-1,t[2])}function Kn(e,t){const n=rs(e);return n.setDate(n.getDate()+t),Nn(n)}function Bo(e,t){const n=rs(e),s=n.getDate();n.setDate(1),n.setMonth(n.getMonth()+t);const o=new Date(n.getFullYear(),n.getMonth()+1,0).getDate();return n.setDate(Math.min(s,o)),Nn(n)}function Es(e){const t=rs(e),n=(t.getDay()+6)%7;return t.setDate(t.getDate()-n),Nn(t)}function dv(e){const t=rs(e).getDay();return t===0||t===6}function pv(e,t){return Math.round((new Date(t).getTime()-new Date(e).getTime())/6e4)}function sf(e){const t=rs(e),n=["周日","周一","周二","周三","周四","周五","周六"];return t.getFullYear()+" 年 "+(t.getMonth()+1)+" 月 "+t.getDate()+" 日 "+n[t.getDay()]}async function yt(e,t){const n=await ne.setting.get(e);return n?n.value:t}async function kt(e,t){await ne.setting.put({key:e,value:t})}async function jr(){const e=await Promise.all([yt("work_start","09:00"),yt("work_end","18:00"),yt("grace_minutes","10"),yt("lunch_minutes","60"),yt("remind_weekly","friday")]);return{work_start:e[0],work_end:e[1],grace_minutes:Number(e[2])||0,lunch_minutes:Number(e[3])||0,remind_weekly:e[4]}}async function hv(){const e=await yt("last_project",""),t=await yt("last_category","dev");return{project_id:e?Number(e):null,category:t||"dev"}}async function vv(){return yt("last_location","")}async function mv(e,t){const n=t.trim();await kt("last_location",n),n&&await Uo(n);const s=await mn(e);s&&s.id?await ne.attendance.update(s.id,{location:n||null}):n&&await ne.attendance.add({date:e,clock_in_at:null,clock_out_at:null,kind:"normal",note:null,location:n,created_at:wt()})}async function Qa(){const e=await yt("location_presets","");if(!e)return Au.slice();try{const t=JSON.parse(e);if(Array.isArray(t))return t.filter(n=>typeof n=="string"&&n.trim()).map(n=>n.trim())}catch{}return Au.slice()}async function of(e){const t=Array.from(new Set(e.map(n=>n.trim()).filter(Boolean)));await kt("location_presets",JSON.stringify(t))}async function Uo(e){const t=e.trim();if(!t)return;const n=await Qa();n.includes(t)||await of([...n,t])}async function Ks(e=!1){const t=await ne.project.orderBy("name").toArray();return e?t:t.filter(n=>n.archived!==1)}async function yv(e){await ne.project.add({name:e.trim(),archived:0,created_at:wt()})}async function gv(e,t){await ne.project.update(e,{name:t.trim()})}async function bv(e,t){await ne.project.update(e,{archived:t?1:0})}async function mn(e){return ne.attendance.where("date").equals(e).first()}async function af(e,t){const n=((t===void 0?await yt("last_location",""):t)||"").trim(),s=await mn(e);if(s&&s.id){if(!s.clock_in_at){const o={clock_in_at:wt()};n&&(o.location=n),await ne.attendance.update(s.id,o)}n&&(await kt("last_location",n),await Uo(n));return}await ne.attendance.add({date:e,clock_in_at:wt(),clock_out_at:null,kind:"normal",note:null,location:n||null,created_at:wt()}),n&&(await kt("last_location",n),await Uo(n))}async function wv(e){const t=await mn(e);t&&t.id&&t.clock_in_at&&!t.clock_out_at&&await ne.attendance.update(t.id,{clock_out_at:wt()})}async function _v(){const e=new Date,t=Nn(e);if(e.getHours()<4){const s=await mn(Kn(t,-1));if(s&&s.id&&s.clock_in_at&&!s.clock_out_at)return await ne.attendance.update(s.id,{clock_out_at:wt()}),s.date}const n=await mn(t);if(n&&n.id&&n.clock_in_at&&!n.clock_out_at)return await ne.attendance.update(n.id,{clock_out_at:wt()}),n.date;throw new Error("没有进行中的打卡")}async function kv(e,t,n,s,o){(o||"").trim()&&await Uo(o);const a=await mn(e),c={date:e,clock_in_at:t,clock_out_at:n,kind:"makeup",note:s||null,location:(o||"").trim()||null,created_at:wt()};a&&a.id?await ne.attendance.update(a.id,c):await ne.attendance.add(c)}async function xv(e,t,n){const s=(n||"").trim();if(!s)return;const o=await mn(e);o&&o.id&&await ne.attendance.update(o.id,{[t]:e+"T"+s+":00"})}async function ci(e,t){return ne.attendance.where("date").between(e,t,!0,!0).toArray()}async function Cv(e,t){const n=await mn(e);if(t){const s={date:e,kind:"leave",clock_in_at:null,clock_out_at:null,created_at:wt()};n&&n.id?await ne.attendance.update(n.id,s):await ne.attendance.add({...s,note:null,location:null})}else n&&n.id&&await ne.attendance.update(n.id,{kind:"normal"})}async function Sv(e){const t=await ne.work_log.where("date").equals(e).first();return t||{id:await ne.work_log.add({date:e,created_at:wt()}),date:e,created_at:wt()}}async function Ev(e){return ne.work_log.where("date").equals(e).first()}async function $v(e){const t=await Ev(e);return!t||!t.id?[]:(await ne.log_item.where("work_log_id").equals(t.id).toArray()).sort((s,o)=>o.id-s.id)}async function Av(e,t){const n=await Sv(e);await ne.log_item.add({work_log_id:n.id,content:t.content,project_id:t.project_id,category:t.category,minutes:t.minutes,is_milestone:0,needs_followup:0,takeaway:t.takeaway,remark:t.remark,sort_order:0,created_at:wt()}),await kt("last_project",t.project_id?String(t.project_id):""),await kt("last_category",t.category)}async function ia(e,t){await ne.log_item.update(e,t)}async function Pv(e){await ne.log_item.delete(e)}async function fi(e,t){const n=await ne.work_log.where("date").between(e,t,!0,!0).toArray();if(!n.length)return[];const s=new Map(n.map(a=>[a.id,a.date]));return(await ne.log_item.where("work_log_id").anyOf(n.map(a=>a.id)).toArray()).map(a=>({...a,date:s.get(a.work_log_id)||""})).sort((a,c)=>a.date===c.date?a.id-c.id:a.datet.updated_at[c.id,c.date]));return(await ne.log_item.toArray()).filter(c=>((c.content||"")+" "+(c.takeaway||"")+" "+(c.remark||"")).toLowerCase().includes(n)).sort((c,d)=>d.id-c.id).slice(0,t).map(c=>({...c,date:o.get(c.work_log_id)||""}))}async function Lv(e,t=4){const n=e.trim().toLowerCase();return n?(await ne.memo.toArray()).filter(o=>((o.title||"")+" "+(o.content||"")).toLowerCase().includes(n)).sort((o,a)=>o.updated_at{await Promise.all([ne.project.clear(),ne.work_log.clear(),ne.log_item.clear(),ne.attendance.clear(),ne.weekly_note.clear(),ne.setting.clear(),ne.memo.clear(),ne.credential.clear(),ne.table("transaction").clear()]),n.project&&n.project.length&&await ne.project.bulkAdd(n.project),n.work_log&&n.work_log.length&&await ne.work_log.bulkAdd(n.work_log),n.log_item&&n.log_item.length&&await ne.log_item.bulkAdd(n.log_item),n.attendance&&n.attendance.length&&await ne.attendance.bulkAdd(n.attendance),n.weekly_note&&n.weekly_note.length&&await ne.weekly_note.bulkAdd(n.weekly_note),n.setting&&n.setting.length&&await ne.setting.bulkAdd(n.setting),n.memo&&n.memo.length&&await ne.memo.bulkAdd(n.memo),n.credential&&n.credential.length&&await ne.credential.bulkAdd(n.credential),n.transaction&&n.transaction.length&&await ne.table("transaction").bulkAdd(n.transaction)})}function Co(e){const t=e.split(":");return Number(t[0])*60+Number(t[1])}function qs(e,t,n,s){if(e&&e.kind==="leave")return{status:"leave",label:"请假",makeup:!1,workedMinutes:null};if(dv(t))return{status:"rest",label:"休息日",makeup:!1,workedMinutes:null};if(!e||!e.clock_in_at)return s?{status:"none",label:"未打卡",makeup:!1,workedMinutes:null}:{status:"absent",label:"缺勤",makeup:!!(e&&e.kind==="makeup"),workedMinutes:null};const o=e.kind==="makeup";if(!e.clock_out_at)return{status:"incomplete",label:s?"进行中":"未完成",makeup:o,workedMinutes:null};const a=Co(Vn(e.clock_in_at)),c=Co(Vn(e.clock_out_at)),d=Co(n.work_start),h=Co(n.work_end);let y="normal";!o&&a>d+n.grace_minutes?y="late":!o&&c{Po.value=Po.value.filter(n=>n.id!==t)},2e3)}function Wv(){return Po}const Sa=N(null),Ea=N(null),Hs=N(0);function Sr(){Hs.value++}const zv={class:"day-panel"},Gv={class:"dp-head"},Yv={class:"dp-date"},Jv={class:"card sec"},Xv={class:"att-grid"},Qv={class:"att-cell"},Zv={key:0,class:"edit-row"},em={key:1,class:"att-val"},tm={class:"att-cell"},nm={key:0,class:"edit-row"},rm={key:1,class:"att-val"},sm={class:"att-cell"},om=["list"],im=["id"],am=["value"],lm={class:"att-cell"},um={class:"att-val status-val"},cm={key:0,class:"tag"},fm={key:1,class:"muted"},dm={key:0,class:"att-note muted"},pm={class:"att-actions"},hm=["disabled"],vm=["disabled"],mm=["disabled"],ym=["disabled"],gm={key:0,class:"card sec makeup"},bm={class:"form-grid"},wm={class:"field"},_m={class:"field"},km={class:"field span2"},xm=["list"],Cm={class:"field span2"},Sm={key:0,class:"form-error"},Em={class:"form-footer"},$m={class:"card sec"},Am={class:"form-grid"},Pm={class:"field span2"},Tm={key:0,class:"form-error"},Om={class:"field"},Mm=["value"],Im={class:"field"},jm=["value"],Dm={class:"field"},Rm={class:"field"},Lm={class:"field span2"},Km={class:"form-footer"},Fm=["disabled"],Nm=["disabled"],Vm={class:"list-sec"},Bm={class:"sec-title"},Um={key:0,class:"empty muted"},qm={class:"item-main"},Hm={class:"tag"},Wm=["onClick"],zm={key:0,class:"muted item-meta"},Gm={key:1,class:"muted num item-meta"},Ym=["onClick"],Jm=["onClick"],Xm=["onClick"],Qm=["onClick"],Zm={key:0,class:"item-sub"},ey={key:0,class:"muted2"},ty={key:1,class:"muted"},ny={key:1,class:"dp-foot muted num"},ry=Vt({__name:"DayPanel",props:{date:{}},setup(e){const t=e,n=N(!0),s=N(null),o=N(void 0),a=N([]),c=N([]),d=N(""),h=N([]),y=it(()=>"loc-list-"+t.date),m=it(()=>t.date===xt());async function k(){n.value=!0,s.value=await jr(),o.value=await mn(t.date),a.value=await $v(t.date),c.value=await Ks(!0),h.value=await Qa(),d.value=o.value&&o.value.location||await vv(),n.value=!1}fn(k),gt(()=>t.date,k),gt(Hs,()=>{k()});const D=it(()=>c.value.filter(H=>H.archived!==1));function O(H){if(!H)return"";const U=c.value.find(Y=>Y.id===H);return U?U.name:"已删除项目"}const K=it(()=>s.value?qs(o.value,t.date,s.value,m.value):null),W=it(()=>a.value.reduce((H,U)=>H+(U.minutes||0),0)),de=N(!1);async function Z(){de.value||(de.value=!0,await af(t.date,d.value),await k(),Sr(),qe("上班打卡成功"),de.value=!1)}async function E(){de.value||(de.value=!0,await wv(t.date),await k(),Sr(),qe("下班打卡成功"),de.value=!1)}async function L(){await mv(t.date,d.value),Sr(),qe("地点已更新")}const Q=N(!1),le=it(()=>{var H;return((H=o.value)==null?void 0:H.kind)==="leave"});function ce(){if(o.value&&o.value.clock_in_at){Q.value=!0;return}ee(!0)}async function ee(H){Q.value=!1,await Cv(t.date,H),await k(),Sr(),qe(H?"已标记为休假":"已取消休假")}const A=N(null),x=N(""),ie=N(null);gt(A,async H=>{var U;H&&(await ts(),(U=ie.value)==null||U.focus())});function xe(H){var Y,Ae;const U=H==="in"?(Y=o.value)==null?void 0:Y.clock_in_at:(Ae=o.value)==null?void 0:Ae.clock_out_at;A.value=H,x.value=U?Vn(U):H==="in"?"09:00":"18:00"}function J(){A.value=null}async function Ce(){const H=A.value;H&&(A.value=null,x.value&&(await xv(t.date,H==="in"?"clock_in_at":"clock_out_at",x.value),await k(),Sr(),qe("打卡时间已修改")))}const Ke=N(!1),Xe=N("09:00"),He=N("18:00"),Ue=N(""),ge=N(""),Me=N("");function Fe(){ge.value=d.value,Me.value="",Ke.value=!Ke.value}async function fe(){if(!Xe.value||!He.value){Me.value="请填写上班与下班时间";return}await kv(t.date,t.date+"T"+Xe.value+":00",t.date+"T"+He.value+":00",Ue.value.trim(),ge.value),Ke.value=!1,Ue.value="",Me.value="",await k(),Sr(),qe("补卡已保存")}const G=N(""),X=N("");gt(G,()=>{X.value&&(X.value="")});const ke=N(null),st=N("dev"),pt=N(null),ht=N(""),Yt=N(""),Jt=N(!1),je=it(()=>!!(G.value.trim()||pt.value||ht.value.trim()||Yt.value.trim()));fn(async()=>{const H=await hv();ke.value=H.project_id,st.value=H.category});function w(){G.value="",pt.value=null,ht.value="",Yt.value="",X.value=""}async function g(){const H=G.value.trim();if(!H){X.value="请填写工作内容";return}Jt.value||(Jt.value=!0,await Av(t.date,{content:H,project_id:ke.value,category:st.value,minutes:pt.value&&pt.value>0?pt.value:null,takeaway:ht.value.trim()||null,remark:Yt.value.trim()||null}),w(),await k(),qe("记录已添加"),Jt.value=!1)}const P=N(null);function ae(H){P.value=H}async function se(H){const U=H.id,Y={content:H.content,project_id:H.project_id,category:H.category,minutes:H.minutes,takeaway:H.takeaway,remark:H.remark,is_milestone:H.is_milestone,needs_followup:H.needs_followup};await ia(U,Y),P.value=null,await k(),qe("修改已保存")}async function ue(H){await ia(H.id,{is_milestone:H.is_milestone?0:1}),await k()}async function ye(H){await ia(H.id,{needs_followup:H.needs_followup?0:1}),await k()}const oe=N(null);async function we(){oe.value&&oe.value.id&&await Pv(oe.value.id),oe.value=null,await k(),qe("记录已删除")}return(H,U)=>(F(),q("div",zv,[u("div",Gv,[u("div",Yv,re(Qt(sf)(e.date)),1)]),u("div",Jv,[U[25]||(U[25]=u("div",{class:"sec-title"},"出勤信息",-1)),u("div",Xv,[u("div",Qv,[U[21]||(U[21]=u("label",null,"上班时间",-1)),A.value==="in"?(F(),q("div",Zv,[$e(u("input",{ref_key:"timeInput",ref:ie,type:"time",class:"input time-input","onUpdate:modelValue":U[0]||(U[0]=Y=>x.value=Y),onKeydown:[jt(Ce,["enter"]),jt(J,["esc"])]},null,544),[[De,x.value]]),u("button",{class:"btn btn-primary btn-sm",onClick:Ce},"确认"),u("button",{class:"btn btn-sm",onClick:J},"取消")])):(F(),q("div",em,[u("span",{class:et(["num",{"val-empty":!(o.value&&o.value.clock_in_at)}])},re(o.value&&o.value.clock_in_at?Qt(Vn)(o.value.clock_in_at):"未打卡"),3),o.value&&o.value.id?(F(),q("button",{key:0,class:"icon-btn",title:"修改上班时间",onClick:U[1]||(U[1]=Y=>xe("in"))},[Oe(lt,{name:"edit",size:13})])):Ee("",!0)]))]),u("div",tm,[U[22]||(U[22]=u("label",null,"下班时间",-1)),A.value==="out"?(F(),q("div",nm,[$e(u("input",{ref_key:"timeInput",ref:ie,type:"time",class:"input time-input","onUpdate:modelValue":U[2]||(U[2]=Y=>x.value=Y),onKeydown:[jt(Ce,["enter"]),jt(J,["esc"])]},null,544),[[De,x.value]]),u("button",{class:"btn btn-primary btn-sm",onClick:Ce},"确认"),u("button",{class:"btn btn-sm",onClick:J},"取消")])):(F(),q("div",rm,[u("span",{class:et(["num",{"val-empty":!(o.value&&o.value.clock_out_at)}])},re(o.value&&o.value.clock_out_at?Qt(Vn)(o.value.clock_out_at):"未打卡"),3),o.value&&o.value.id?(F(),q("button",{key:0,class:"icon-btn",title:"修改下班时间",onClick:U[3]||(U[3]=Y=>xe("out"))},[Oe(lt,{name:"edit",size:13})])):Ee("",!0)]))]),u("div",sm,[U[23]||(U[23]=u("label",null,"上班地点",-1)),$e(u("input",{class:"input","onUpdate:modelValue":U[4]||(U[4]=Y=>d.value=Y),list:y.value,placeholder:"可直接输入",title:"上班地点,可自由输入",onChange:L},null,40,om),[[De,d.value]]),u("datalist",{id:y.value},[(F(!0),q(Re,null,ut(h.value,Y=>(F(),q("option",{key:Y,value:Y},null,8,am))),128))],8,im)]),u("div",lm,[U[24]||(U[24]=u("label",null,"考勤状态",-1)),u("div",um,[K.value?(F(),q(Re,{key:0},[u("span",{class:et(["dot",K.value.status])},null,2),u("span",null,re(K.value.label),1),o.value&&o.value.kind==="makeup"?(F(),q("span",cm,"补卡")):Ee("",!0)],64)):(F(),q("span",fm,"--"))])])]),o.value&&o.value.note?(F(),q("div",dm,"补卡说明:"+re(o.value.note),1)):Ee("",!0),u("div",pm,[m.value&&(!o.value||!o.value.clock_in_at)?(F(),q("button",{key:0,class:"btn btn-primary btn-sm",disabled:de.value,onClick:Z},"上班打卡",8,hm)):m.value&&o.value&&o.value.clock_in_at&&!o.value.clock_out_at?(F(),q("button",{key:1,class:"btn btn-primary btn-sm",disabled:de.value,onClick:E},"下班打卡",8,vm)):Ee("",!0),!m.value&&(!o.value||!o.value.clock_in_at)?(F(),q("button",{key:2,class:"btn btn-sm",onClick:Fe},"补卡")):Ee("",!0),le.value?(F(),q("button",{key:4,class:"btn btn-sm",disabled:de.value,onClick:U[5]||(U[5]=Y=>ee(!1))},"取消休假",8,ym)):(F(),q("button",{key:3,class:"btn btn-sm",disabled:de.value,onClick:ce},"标记休假",8,mm))])]),Ke.value?(F(),q("div",gm,[U[30]||(U[30]=u("div",{class:"sec-title"},"补卡登记",-1)),u("div",bm,[u("div",wm,[U[26]||(U[26]=u("label",null,"上班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":U[6]||(U[6]=Y=>Xe.value=Y)},null,512),[[De,Xe.value]])]),u("div",_m,[U[27]||(U[27]=u("label",null,"下班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":U[7]||(U[7]=Y=>He.value=Y)},null,512),[[De,He.value]])]),u("div",km,[U[28]||(U[28]=u("label",null,"上班地点",-1)),$e(u("input",{class:"input",list:y.value,"onUpdate:modelValue":U[8]||(U[8]=Y=>ge.value=Y),placeholder:"可直接输入"},null,8,xm),[[De,ge.value]])]),u("div",Cm,[U[29]||(U[29]=u("label",null,"补卡原因",-1)),$e(u("input",{class:"input","onUpdate:modelValue":U[9]||(U[9]=Y=>Ue.value=Y),placeholder:"如:外出拜访客户忘记打卡"},null,512),[[De,Ue.value]])])]),Me.value?(F(),q("div",Sm,re(Me.value),1)):Ee("",!0),u("div",Em,[u("button",{class:"btn btn-sm",onClick:U[10]||(U[10]=Y=>Ke.value=!1)},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:fe},"保存补卡")])])):Ee("",!0),u("div",$m,[U[38]||(U[38]=u("div",{class:"sec-head"},[u("span",{class:"sec-title"},"新增工作记录"),u("span",{class:"muted form-hint"},"内容必填,其余选填")],-1)),u("div",Am,[u("div",Pm,[U[31]||(U[31]=u("label",null,"工作内容(必填)",-1)),$e(u("input",{class:et(["input",{invalid:X.value}]),"onUpdate:modelValue":U[11]||(U[11]=Y=>G.value=Y),placeholder:"做了什么,一句话一条",onKeydown:jt(g,["enter"])},null,34),[[De,G.value]]),X.value?(F(),q("div",Tm,re(X.value),1)):Ee("",!0)]),u("div",Om,[U[33]||(U[33]=u("label",null,"所属项目",-1)),$e(u("select",{class:"select","onUpdate:modelValue":U[12]||(U[12]=Y=>ke.value=Y)},[U[32]||(U[32]=u("option",{value:null},"无项目",-1)),(F(!0),q(Re,null,ut(D.value,Y=>(F(),q("option",{key:Y.id,value:Y.id},re(Y.name),9,Mm))),128))],512),[[Fn,ke.value]])]),u("div",Im,[U[34]||(U[34]=u("label",null,"工作分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":U[13]||(U[13]=Y=>st.value=Y)},[(F(!0),q(Re,null,ut(Qt(Us),Y=>(F(),q("option",{key:Y.key,value:Y.key},re(Y.label),9,jm))),128))],512),[[Fn,st.value]])]),u("div",Dm,[U[35]||(U[35]=u("label",null,"耗时(分钟)",-1)),$e(u("input",{class:"input",type:"number",min:"0","onUpdate:modelValue":U[14]||(U[14]=Y=>pt.value=Y),placeholder:"选填"},null,512),[[De,pt.value,void 0,{number:!0}]])]),u("div",Rm,[U[36]||(U[36]=u("label",null,"主要收获",-1)),$e(u("input",{class:"input","onUpdate:modelValue":U[15]||(U[15]=Y=>ht.value=Y),placeholder:"一句话:学到了什么"},null,512),[[De,ht.value]])]),u("div",Lm,[U[37]||(U[37]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":U[16]||(U[16]=Y=>Yt.value=Y),placeholder:"背景、链接、未决事项(选填)"},null,512),[[De,Yt.value]])])]),u("div",Km,[u("button",{class:"btn btn-sm",disabled:!je.value,onClick:w},"重置",8,Fm),u("button",{class:"btn btn-primary btn-sm",disabled:Jt.value,onClick:g},"添加记录",8,Nm)])]),u("div",Vm,[u("div",Bm,"工作记录("+re(a.value.length)+")",1),!a.value.length&&!n.value?(F(),q("div",Um,"暂无记录")):Ee("",!0),(F(!0),q(Re,null,ut(a.value,Y=>(F(),q("div",{key:Y.id,class:"item"},[u("div",qm,[u("span",Hm,re(Qt(Xa)(Y.category)),1),u("span",{class:"item-content",title:"点击编辑",onClick:Ae=>ae(Y)},re(Y.content),9,Wm),Y.project_id?(F(),q("span",zm,re(O(Y.project_id)),1)):Ee("",!0),Y.minutes?(F(),q("span",Gm,re(Y.minutes)+" 分钟",1)):Ee("",!0),U[39]||(U[39]=u("span",{class:"flex1"},null,-1)),u("button",{class:"icon-btn",title:"编辑完整信息",onClick:Ae=>ae(Y)},[Oe(lt,{name:"edit",size:14})],8,Ym),u("button",{class:et(["icon-btn",{active:Y.is_milestone===1}]),title:"成果标记",onClick:Ae=>ue(Y)},[Oe(lt,{name:"star",size:14})],10,Jm),u("button",{class:et(["icon-btn",{"active-warn":Y.needs_followup===1}]),title:"待跟进",onClick:Ae=>ye(Y)},[Oe(lt,{name:"flag",size:14})],10,Xm),u("button",{class:"icon-btn",title:"删除",onClick:Ae=>oe.value=Y},[Oe(lt,{name:"close",size:14})],8,Qm)]),Y.takeaway||Y.remark?(F(),q("div",Zm,[Y.takeaway?(F(),q("div",ey,"收获:"+re(Y.takeaway),1)):Ee("",!0),Y.remark?(F(),q("div",ty,"备注:"+re(Y.remark),1)):Ee("",!0)])):Ee("",!0)]))),128)),a.value.length?(F(),q("div",ny,[nn(" 共 "+re(a.value.length)+" 条事项 ",1),W.value?(F(),q(Re,{key:0},[nn(" · "+re((W.value/60).toFixed(1))+" 小时",1)],64)):Ee("",!0)])):Ee("",!0)]),Oe(ur,{open:!!oe.value,title:"删除确认",message:oe.value?"将删除工作记录「"+oe.value.content+"」。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:U[17]||(U[17]=Y=>oe.value=null),onConfirm:we},null,8,["open","message"]),Oe(ur,{open:Q.value,title:"标记休假确认",message:"该日已有打卡记录,标记休假将清空上下班时间。是否继续?","confirm-text":"标记休假",danger:"",onCancel:U[18]||(U[18]=Y=>Q.value=!1),onConfirm:U[19]||(U[19]=Y=>ee(!0))},null,8,["open"]),Oe(fv,{open:!!P.value,item:P.value,projects:c.value,date:e.date,onCancel:U[20]||(U[20]=Y=>P.value=null),onSave:se},null,8,["open","item","projects","date"])]))}}),lf=Gt(ry,[["__scopeId","data-v-2e90c9d8"]]),sy={class:"cal-page"},oy={class:"cal-toolbar"},iy={class:"cal-title num"},ay={class:"cal-head"},ly={class:"cal-grid"},uy=["title","onClick"],cy={class:"cal-marks"},fy={key:0,class:"drawer"},dy={class:"drawer-head"},py={class:"drawer-body"},hy=Vt({__name:"CalendarView",setup(e){const t=N(xt()),n=it(()=>Number(t.value.slice(0,4))),s=it(()=>Number(t.value.slice(5,7))-1),o=it(()=>n.value+" 年 "+(s.value+1)+" 月"),a=["一","二","三","四","五","六","日"],c=it(()=>{const Q=(new Date(n.value,s.value,1).getDay()+6)%7,le=new Date(n.value,s.value+1,0).getDate(),ce=[];for(let ee=0;ee[xe.date,xe])),A=le[2],x=new Map;for(const xe of c.value){if(!xe.inMonth)continue;const J=qs(ee.get(xe.date),xe.date,ce,xe.date===h),Ce=A.filter(Ke=>Ke.date===xe.date);x.set(xe.date,{status:J.status,label:J.label,location:((ie=ee.get(xe.date))==null?void 0:ie.location)||"",hasLog:Ce.length>0,hasMilestone:Ce.some(Ke=>Ke.is_milestone===1)})}d.value=x}gt([n,s],y,{immediate:!0}),gt(Hs,()=>{y()});function m(L){var Q;return((Q=d.value.get(L))==null?void 0:Q.status)??""}function k(L){const Q=d.value.get(L);return Q?L+" · "+Q.label+(Q.location?" · "+Q.location:""):L}function D(L){var Q;return!!((Q=d.value.get(L))!=null&&Q.hasLog)}function O(L){var Q;return!!((Q=d.value.get(L))!=null&&Q.hasMilestone)}function K(){t.value=Bo(t.value,-1)}function W(){t.value=Bo(t.value,1)}function de(){t.value=xt()}const Z=N(null);function E(L,Q){Q&&(Z.value=L)}return gt(Sa,L=>{L&&(t.value=L,Z.value=L,Sa.value=null)},{immediate:!0}),(L,Q)=>(F(),q("div",sy,[u("div",oy,[u("button",{class:"icon-btn",onClick:K},[Oe(lt,{name:"chevron-left",size:16})]),u("span",iy,re(o.value),1),u("button",{class:"icon-btn",onClick:W},[Oe(lt,{name:"chevron-right",size:16})]),u("button",{class:"btn btn-sm",onClick:de},"回到今天")]),u("div",ay,[(F(),q(Re,null,ut(a,le=>u("span",{key:le,class:"cal-week muted"},re(le),1)),64))]),u("div",ly,[(F(!0),q(Re,null,ut(c.value,(le,ce)=>(F(),q("button",{key:ce,class:et(["cal-cell",{blank:!le.inMonth,weekend:le.weekend,selected:Z.value===le.date}]),title:le.inMonth?k(le.date):void 0,onClick:ee=>E(le.date,le.inMonth)},[le.inMonth?(F(),q(Re,{key:0},[u("span",{class:et(["daynum num",{today:le.date===Qt(h)}])},re(Number(le.date.slice(8,10))),3),u("span",cy,[m(le.date)?(F(),q("span",{key:0,class:et(["dot",m(le.date)])},null,2)):Ee("",!0),D(le.date)?(F(),It(lt,{key:1,name:"check-circle",size:12,class:"mark-log"})):Ee("",!0),O(le.date)?(F(),It(lt,{key:2,name:"star",size:12,class:"mark-star"})):Ee("",!0)])],64)):Ee("",!0)],10,uy))),128))]),Oe(ns,{name:"drawer"},{default:fr(()=>[Z.value?(F(),q("aside",fy,[u("div",dy,[Q[1]||(Q[1]=u("span",{class:"drawer-title"},"当日详情",-1)),u("button",{class:"icon-btn",onClick:Q[0]||(Q[0]=le=>Z.value=null)},[Oe(lt,{name:"close",size:16})])]),u("div",py,[Oe(lf,{date:Z.value},null,8,["date"])])])):Ee("",!0)]),_:1})]))}}),vy=Gt(hy,[["__scopeId","data-v-6a6322fa"]]),my={class:"detail-page"},yy={class:"detail-toolbar"},gy=["value"],by=["disabled"],wy=Vt({__name:"TodayView",setup(e){const t=N(xt()),n=it(()=>t.value===xt());function s(){t.value=Kn(t.value,-1)}function o(){t.value=Kn(t.value,1)}function a(){t.value=xt()}function c(d){const h=d.target.value;h&&(t.value=h)}return(d,h)=>(F(),q("div",my,[u("div",yy,[u("button",{class:"icon-btn",title:"前一天",onClick:s},[Oe(lt,{name:"chevron-left",size:16})]),u("span",{class:et(["date-title num",{"is-today":n.value}])},re(Qt(sf)(t.value)),3),u("button",{class:"icon-btn",title:"后一天",onClick:o},[Oe(lt,{name:"chevron-right",size:16})]),u("input",{type:"date",class:"input w-date",value:t.value,onChange:c},null,40,gy),u("button",{class:"btn btn-sm",disabled:n.value,onClick:a},"回到今天",8,by)]),Oe(lf,{date:t.value},null,8,["date"])]))}}),_y=Gt(wy,[["__scopeId","data-v-ac366cf6"]]),ky={class:"stats"},xy={class:"cards"},Cy={class:"card stat-card"},Sy={class:"stat-num num"},Ey={class:"card stat-card"},$y={class:"stat-num num"},Ay={class:"card stat-card"},Py={class:"stat-num num"},Ty={class:"card stat-card"},Oy={class:"stat-num num"},My={class:"card section"},Iy={class:"heat"},jy=["title"],Dy={class:"two-col"},Ry={class:"card section"},Ly={class:"bar-label"},Ky={class:"bar-track"},Fy={class:"muted num bar-num"},Ny={key:0,class:"muted"},Vy={class:"card section"},By={class:"bar-label"},Uy={class:"bar-track"},qy={class:"muted num bar-num"},Hy={key:0,class:"muted"},Wy={class:"card section"},zy={class:"bar-label loc-label"},Gy={class:"bar-track"},Yy={class:"muted num bar-num"},Jy={key:0,class:"muted"},Xy=Vt({__name:"StatsView",setup(e){const t=N({attendDays:0,totalHours:"0",itemCount:0,streak:0}),n=N([]),s=N([]),o=N([]),a=N([]);async function c(){const y=xt(),m="2000-01-01",k=await Promise.all([jr(),ci(m,y),fi(m,y),Ks(!0)]),D=k[0],O=k[1],K=k[2],W=k[3],de=O.filter(J=>J.clock_in_at||J.kind==="makeup");let Z=0;for(const J of de){const Ce=qs(J,J.date,D,J.date===y);Z+=Ce.workedMinutes??0}const E=new Set(K.map(J=>J.date));let L=0,Q=y;for(E.has(Q)||(Q=Kn(y,-1));E.has(Q);)L++,Q=Kn(Q,-1);t.value={attendDays:de.length,totalHours:(Z/60).toFixed(1),itemCount:K.length,streak:L};const le=new Map;for(const J of de){const Ce=J.location||"未记录";le.set(Ce,(le.get(Ce)||0)+1)}a.value=Array.from(le.entries()).map(J=>({name:J[0],count:J[1],percent:Math.round(J[1]/(de.length||1)*100)})).sort((J,Ce)=>Ce.count-J.count);const ce=K.length||1;s.value=Us.map(J=>{const Ce=K.filter(Ke=>Ke.category===J.key).length;return{key:J.key,label:J.label,count:Ce,percent:Math.round(Ce/ce*100)}}).filter(J=>J.count>0).sort((J,Ce)=>Ce.count-J.count);const ee=new Map(W.map(J=>[J.id,J.name])),A=new Map;for(const J of K){const Ce=J.project_id?ee.get(J.project_id)||"已删除项目":"无项目";A.set(Ce,(A.get(Ce)||0)+1)}o.value=Array.from(A.entries()).map(J=>({name:J[0],count:J[1],percent:Math.round(J[1]/ce*100)})).sort((J,Ce)=>Ce.count-J.count);const x=new Map;for(const J of K)x.set(J.date,(x.get(J.date)||0)+1);const ie=Es(y),xe=[];for(let J=11;J>=0;J--){const Ce=Kn(ie,-7*J),Ke=[];for(let Xe=0;Xe<7;Xe++){const He=Kn(Ce,Xe);Ke.push({date:He,count:x.get(He)||0})}xe.push(Ke)}n.value=xe}fn(async()=>{await c()}),gt(Hs,()=>{c()});function d(y){return y===0?0:y===1?1:y<=3?2:y<=5?3:4}function h(y,m){return y+" · "+(m?m+" 条":"无记录")}return(y,m)=>(F(),q("div",ky,[u("div",xy,[u("div",Cy,[m[0]||(m[0]=u("div",{class:"muted"},"出勤天数",-1)),u("div",Sy,re(t.value.attendDays),1)]),u("div",Ey,[m[1]||(m[1]=u("div",{class:"muted"},"累计工时(小时)",-1)),u("div",$y,re(t.value.totalHours),1)]),u("div",Ay,[m[2]||(m[2]=u("div",{class:"muted"},"记录条数",-1)),u("div",Py,re(t.value.itemCount),1)]),u("div",Ty,[m[3]||(m[3]=u("div",{class:"muted"},"连续记录(天)",-1)),u("div",Oy,re(t.value.streak),1)])]),u("div",My,[m[4]||(m[4]=u("div",{class:"section-title"},"记录热力图(近 12 周)",-1)),u("div",Iy,[(F(!0),q(Re,null,ut(n.value,(k,D)=>(F(),q("div",{key:D,class:"heat-col"},[(F(!0),q(Re,null,ut(k,O=>(F(),q("span",{key:O.date,class:et(["heat-cell","lv"+d(O.count)]),title:h(O.date,O.count)},null,10,jy))),128))]))),128))]),m[5]||(m[5]=jp('
少多
',1))]),u("div",Dy,[u("div",Ry,[m[6]||(m[6]=u("div",{class:"section-title"},"分类分布",-1)),(F(!0),q(Re,null,ut(s.value,k=>(F(),q("div",{key:k.key,class:"bar-row"},[u("span",Ly,re(k.label),1),u("span",Ky,[u("span",{class:"bar-fill",style:sr({width:k.percent+"%"})},null,4)]),u("span",Fy,re(k.count)+" 条 · "+re(k.percent)+"%",1)]))),128)),s.value.length?Ee("",!0):(F(),q("div",Ny,"暂无数据"))]),u("div",Vy,[m[7]||(m[7]=u("div",{class:"section-title"},"项目投入",-1)),(F(!0),q(Re,null,ut(o.value,k=>(F(),q("div",{key:k.name,class:"bar-row"},[u("span",By,re(k.name),1),u("span",Uy,[u("span",{class:"bar-fill",style:sr({width:k.percent+"%"})},null,4)]),u("span",qy,re(k.count)+" 条 · "+re(k.percent)+"%",1)]))),128)),o.value.length?Ee("",!0):(F(),q("div",Hy,"暂无数据"))])]),u("div",Wy,[m[8]||(m[8]=u("div",{class:"section-title"},"地点分布(按出勤天)",-1)),(F(!0),q(Re,null,ut(a.value,k=>(F(),q("div",{key:k.name,class:"bar-row"},[u("span",zy,re(k.name),1),u("span",Gy,[u("span",{class:"bar-fill",style:sr({width:k.percent+"%"})},null,4)]),u("span",Yy,re(k.count)+" 天 · "+re(k.percent)+"%",1)]))),128)),a.value.length?Ee("",!0):(F(),q("div",Jy,"暂无数据"))])]))}}),Qy=Gt(Xy,[["__scopeId","data-v-73e5ba49"]]);async function Zy(e,t,n){const s=xt(),o=await Promise.all([jr(),ci(e,t),fi(e,t),Ks(!0),Ov(e,t)]),a=o[0],c=o[1],d=o[2],h=o[3],y=o[4];let m=0,k=0,D=0;for(const A of c){(A.clock_in_at||A.kind==="makeup")&&m++,A.kind==="makeup"&&D++;const x=qs(A,A.date,a,A.date===s);k+=x.workedMinutes??0}const O=new Map;for(const A of c){if(!(A.clock_in_at||A.kind==="makeup"))continue;const x=A.location||"未记录";O.set(x,(O.get(x)||0)+1)}const K=Array.from(O.entries()).map(A=>({name:A[0],count:A[1]})).sort((A,x)=>x.count-A.count),W=d.length||1,de=Us.map(A=>{const x=d.filter(ie=>ie.category===A.key).length;return{key:A.key,label:A.label,count:x,percent:Math.round(x/W*100)}}).filter(A=>A.count>0).sort((A,x)=>x.count-A.count),Z=new Map(h.map(A=>[A.id,A.name])),E=new Map;for(const A of d){const x=A.project_id?Z.get(A.project_id)||"已删除项目":"无项目";E.set(x,(E.get(x)||0)+1)}const L=Array.from(E.entries()).map(A=>({name:A[0],count:A[1]})).sort((A,x)=>x.count-A.count),Q=d.filter(A=>A.is_milestone===1).map(A=>({date:A.date,content:A.content})),le=d.filter(A=>A.needs_followup===1).map(A=>({date:A.date,content:A.content,remark:A.remark||""})),ce=d.filter(A=>!!A.takeaway).map(A=>({date:A.date,text:A.takeaway})),ee=y.map(A=>({weekStart:A.week_start,highlights:A.highlights||"",challenges:A.challenges||"",plan_next:A.plan_next||""}));return{range:{start:e,end:t,label:n},attendDays:m,totalHours:(k/60).toFixed(1),makeupCount:D,leaveCount:c.filter(A=>A.kind==="leave").length,itemCount:d.length,categoryStats:de,projectStats:L,locationStats:K,milestones:Q,followups:le,takeaways:ce,weekNotes:ee}}function eg(e){const t=[];t.push("# 实习工作总结("+e.range.start+" ~ "+e.range.end+")"),t.push(""),t.push("## 一、考勤概况"),t.push(""),t.push("出勤 "+e.attendDays+" 天,累计工时 "+e.totalHours+" 小时,补卡 "+e.makeupCount+" 次"+(e.leaveCount?",请假 "+e.leaveCount+" 天":""));const n=e.locationStats.filter(s=>s.name!=="未记录");n.length&&t.push("其中:"+n.map(s=>s.name+" "+s.count+" 天").join(",")),t.push(""),t.push("## 二、工作内容分布"),t.push(""),t.push(e.categoryStats.length?e.categoryStats.map(s=>s.label+" "+s.percent+"%("+s.count+" 条)").join(","):"(无记录)"),t.push(""),t.push("## 三、项目投入"),t.push(""),t.push(e.projectStats.length?e.projectStats.map(s=>s.name+" "+s.count+" 条").join(","):"(无记录)"),t.push(""),t.push("## 四、主要成果"),t.push(""),e.milestones.length?e.milestones.forEach((s,o)=>t.push(o+1+". 【成果】"+s.content+"("+s.date+")")):t.push("(无)"),t.push(""),t.push("## 五、待跟进事项"),t.push(""),e.followups.length?e.followups.forEach(s=>t.push("- 【待跟进】"+s.content+(s.remark?"("+s.date+" 备注:"+s.remark+")":"("+s.date+")"))):t.push("(无)"),t.push(""),t.push("## 六、学习与成长"),t.push(""),e.takeaways.length?e.takeaways.forEach(s=>t.push("- "+s.text+"("+s.date+")")):t.push("(无)");for(const s of e.weekNotes)t.push(""),t.push("### 周记("+s.weekStart+" 起)"),t.push(""),t.push("- 本周亮点:"+(s.highlights||"(无)")),t.push("- 踩的坑:"+(s.challenges||"(无)")),t.push("- 下周计划:"+(s.plan_next||"(无)"));return t.push(""),t.join(` -`)}const tg="modulepreload",ng=function(e,t){return new URL(e,t).href},Pu={},uf=function(t,n,s){let o=Promise.resolve();if(n&&n.length>0){const c=document.getElementsByTagName("link"),d=document.querySelector("meta[property=csp-nonce]"),h=(d==null?void 0:d.nonce)||(d==null?void 0:d.getAttribute("nonce"));o=Promise.allSettled(n.map(y=>{if(y=ng(y,s),y in Pu)return;Pu[y]=!0;const m=y.endsWith(".css"),k=m?'[rel="stylesheet"]':"";if(!!s)for(let K=c.length-1;K>=0;K--){const W=c[K];if(W.href===y&&(!m||W.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${y}"]${k}`))return;const O=document.createElement("link");if(O.rel=m?"stylesheet":tg,m||(O.as="script"),O.crossOrigin="",O.href=y,h&&O.setAttribute("nonce",h),document.head.appendChild(O),m)return new Promise((K,W)=>{O.addEventListener("load",K),O.addEventListener("error",()=>W(new Error(`Unable to preload CSS for ${y}`)))})}))}function a(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return o.then(c=>{for(const d of c||[])d.status==="rejected"&&a(d.reason);return t().catch(a)})};/*! Capacitor: https://capacitorjs.com/ - MIT License */const rg=e=>{const t=new Map;t.set("web",{name:"web"});const n=e.CapacitorPlatforms||{currentPlatform:{name:"web"},platforms:t},s=(a,c)=>{n.platforms.set(a,c)},o=a=>{n.platforms.has(a)&&(n.currentPlatform=n.platforms.get(a))};return n.addPlatform=s,n.setPlatform=o,n},sg=e=>e.CapacitorPlatforms=rg(e),cf=sg(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});cf.addPlatform;cf.setPlatform;var Qr;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(Qr||(Qr={}));class aa extends Error{constructor(t,n,s){super(t),this.message=t,this.code=n,this.data=s}}const og=e=>{var t,n;return e!=null&&e.androidBridge?"android":!((n=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||n===void 0)&&n.bridge?"ios":"web"},ig=e=>{var t,n,s,o,a;const c=e.CapacitorCustomPlatform||null,d=e.Capacitor||{},h=d.Plugins=d.Plugins||{},y=e.CapacitorPlatforms,m=()=>c!==null?c.name:og(e),k=((t=y==null?void 0:y.currentPlatform)===null||t===void 0?void 0:t.getPlatform)||m,D=()=>k()!=="web",O=((n=y==null?void 0:y.currentPlatform)===null||n===void 0?void 0:n.isNativePlatform)||D,K=ee=>{const A=Q.get(ee);return!!(A!=null&&A.platforms.has(k())||Z(ee))},W=((s=y==null?void 0:y.currentPlatform)===null||s===void 0?void 0:s.isPluginAvailable)||K,de=ee=>{var A;return(A=d.PluginHeaders)===null||A===void 0?void 0:A.find(x=>x.name===ee)},Z=((o=y==null?void 0:y.currentPlatform)===null||o===void 0?void 0:o.getPluginHeader)||de,E=ee=>e.console.error(ee),L=(ee,A,x)=>Promise.reject(`${x} does not have an implementation of "${A}".`),Q=new Map,le=(ee,A={})=>{const x=Q.get(ee);if(x)return console.warn(`Capacitor plugin "${ee}" already registered. Cannot register plugins twice.`),x.proxy;const ie=k(),xe=Z(ee);let J;const Ce=async()=>(!J&&ie in A?J=typeof A[ie]=="function"?J=await A[ie]():J=A[ie]:c!==null&&!J&&"web"in A&&(J=typeof A.web=="function"?J=await A.web():J=A.web),J),Ke=(Fe,fe)=>{var G,X;if(xe){const ke=xe==null?void 0:xe.methods.find(st=>fe===st.name);if(ke)return ke.rtype==="promise"?st=>d.nativePromise(ee,fe.toString(),st):(st,pt)=>d.nativeCallback(ee,fe.toString(),st,pt);if(Fe)return(G=Fe[fe])===null||G===void 0?void 0:G.bind(Fe)}else{if(Fe)return(X=Fe[fe])===null||X===void 0?void 0:X.bind(Fe);throw new aa(`"${ee}" plugin is not implemented on ${ie}`,Qr.Unimplemented)}},Xe=Fe=>{let fe;const G=(...X)=>{const ke=Ce().then(st=>{const pt=Ke(st,Fe);if(pt){const ht=pt(...X);return fe=ht==null?void 0:ht.remove,ht}else throw new aa(`"${ee}.${Fe}()" is not implemented on ${ie}`,Qr.Unimplemented)});return Fe==="addListener"&&(ke.remove=async()=>fe()),ke};return G.toString=()=>`${Fe.toString()}() { [capacitor code] }`,Object.defineProperty(G,"name",{value:Fe,writable:!1,configurable:!1}),G},He=Xe("addListener"),Ue=Xe("removeListener"),ge=(Fe,fe)=>{const G=He({eventName:Fe},fe),X=async()=>{const st=await G;Ue({eventName:Fe,callbackId:st},fe)},ke=new Promise(st=>G.then(()=>st({remove:X})));return ke.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await X()},ke},Me=new Proxy({},{get(Fe,fe){switch(fe){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return xe?ge:He;case"removeListener":return Ue;default:return Xe(fe)}}});return h[ee]=Me,Q.set(ee,{name:ee,proxy:Me,platforms:new Set([...Object.keys(A),...xe?[ie]:[]])}),Me},ce=((a=y==null?void 0:y.currentPlatform)===null||a===void 0?void 0:a.registerPlugin)||le;return d.convertFileSrc||(d.convertFileSrc=ee=>ee),d.getPlatform=k,d.handleError=E,d.isNativePlatform=O,d.isPluginAvailable=W,d.pluginMethodNoop=L,d.registerPlugin=ce,d.Exception=aa,d.DEBUG=!!d.DEBUG,d.isLoggingEnabled=!!d.isLoggingEnabled,d.platform=d.getPlatform(),d.isNative=d.isNativePlatform(),d},ag=e=>e.Capacitor=ig(e),Zr=ag(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ff=Zr.registerPlugin;Zr.Plugins;class df{constructor(t){this.listeners={},this.retainedEventArguments={},this.windowListeners={},t&&(console.warn(`Capacitor WebPlugin "${t.name}" config object was deprecated in v3 and will be removed in v4.`),this.config=t)}addListener(t,n){let s=!1;this.listeners[t]||(this.listeners[t]=[],s=!0),this.listeners[t].push(n);const a=this.windowListeners[t];a&&!a.registered&&this.addWindowListener(a),s&&this.sendRetainedArgumentsForEvent(t);const c=async()=>this.removeListener(t,n);return Promise.resolve({remove:c})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,n,s){const o=this.listeners[t];if(!o){if(s){let a=this.retainedEventArguments[t];a||(a=[]),a.push(n),this.retainedEventArguments[t]=a}return}o.forEach(a=>a(n))}hasListeners(t){return!!this.listeners[t].length}registerWindowListener(t,n){this.windowListeners[n]={registered:!1,windowEventName:t,pluginEventName:n,handler:s=>{this.notifyListeners(n,s)}}}unimplemented(t="not implemented"){return new Zr.Exception(t,Qr.Unimplemented)}unavailable(t="not available"){return new Zr.Exception(t,Qr.Unavailable)}async removeListener(t,n){const s=this.listeners[t];if(!s)return;const o=s.indexOf(n);this.listeners[t].splice(o,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const n=this.retainedEventArguments[t];n&&(delete this.retainedEventArguments[t],n.forEach(s=>{this.notifyListeners(t,s)}))}}const Tu=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Ou=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class lg extends df{async getCookies(){const t=document.cookie,n={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[o,a]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");o=Ou(o).trim(),a=Ou(a).trim(),n[o]=a}),n}async setCookie(t){try{const n=Tu(t.key),s=Tu(t.value),o=`; expires=${(t.expires||"").replace("expires=","")}`,a=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${n}=${s||""}${o}; path=${a}; ${c};`}catch(n){return Promise.reject(n)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(n){return Promise.reject(n)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const n of t)document.cookie=n.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}ff("CapacitorCookies",{web:()=>new lg});const ug=async e=>new Promise((t,n)=>{const s=new FileReader;s.onload=()=>{const o=s.result;t(o.indexOf(",")>=0?o.split(",")[1]:o)},s.onerror=o=>n(o),s.readAsDataURL(e)}),cg=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(o=>o.toLocaleLowerCase()).reduce((o,a,c)=>(o[a]=e[t[c]],o),{})},fg=(e,t=!0)=>e?Object.entries(e).reduce((s,o)=>{const[a,c]=o;let d,h;return Array.isArray(c)?(h="",c.forEach(y=>{d=t?encodeURIComponent(y):y,h+=`${a}=${d}&`}),h.slice(0,-1)):(d=t?encodeURIComponent(c):c,h=`${a}=${d}`),`${s}&${h}`},"").substr(1):null,dg=(e,t={})=>{const n=Object.assign({method:e.method||"GET",headers:e.headers},t),o=cg(e.headers)["content-type"]||"";if(typeof e.data=="string")n.body=e.data;else if(o.includes("application/x-www-form-urlencoded")){const a=new URLSearchParams;for(const[c,d]of Object.entries(e.data||{}))a.set(c,d);n.body=a.toString()}else if(o.includes("multipart/form-data")||e.data instanceof FormData){const a=new FormData;if(e.data instanceof FormData)e.data.forEach((d,h)=>{a.append(h,d)});else for(const d of Object.keys(e.data))a.append(d,e.data[d]);n.body=a;const c=new Headers(n.headers);c.delete("content-type"),n.headers=c}else(o.includes("application/json")||typeof e.data=="object")&&(n.body=JSON.stringify(e.data));return n};class pg extends df{async request(t){const n=dg(t,t.webFetchExtra),s=fg(t.params,t.shouldEncodeUrlParams),o=s?`${t.url}?${s}`:t.url,a=await fetch(o,n),c=a.headers.get("content-type")||"";let{responseType:d="text"}=a.ok?t:{};c.includes("application/json")&&(d="json");let h,y;switch(d){case"arraybuffer":case"blob":y=await a.blob(),h=await ug(y);break;case"json":h=await a.json();break;case"document":case"text":default:h=await a.text()}const m={};return a.headers.forEach((k,D)=>{m[D]=k}),{data:h,headers:m,status:a.status,url:a.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}ff("CapacitorHttp",{web:()=>new pg});async function el(e,t){const n=window;if(n.electronAPI&&n.electronAPI.saveFile){const c=await n.electronAPI.saveFile(e,t);return c&&c.saved?c.path:""}if(Zr.isNativePlatform()){const{Filesystem:c,Directory:d,Encoding:h}=await uf(async()=>{const{Filesystem:y,Directory:m,Encoding:k}=await import("./index-Cym4sQrs.js");return{Filesystem:y,Directory:m,Encoding:k}},[],import.meta.url);try{return(await c.writeFile({path:e,data:t,directory:d.Documents,encoding:h.UTF8,recursive:!0})).uri}catch{return(await c.writeFile({path:e,data:t,directory:d.Cache,encoding:h.UTF8,recursive:!0})).uri}}const s=new Blob([t],{type:"text/plain;charset=utf-8"}),o=URL.createObjectURL(s),a=document.createElement("a");return a.href=o,a.download=e,a.click(),window.setTimeout(()=>URL.revokeObjectURL(o),1e4),""}const hg=Object.freeze(Object.defineProperty({__proto__:null,downloadText:el},Symbol.toStringTag,{value:"Module"}));async function $a(e){try{await navigator.clipboard.writeText(e)}catch{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}}async function vg(e){const t=await Promise.all([yt("ai_base_url",""),yt("ai_api_key",""),yt("ai_model","")]),n=t[0].trim().replace(/\/+$/,""),s=t[1].trim(),o=t[2].trim();if(!n||!o)throw new Error("请先在设置页配置 AI 接口地址与模型名称");const a=n+"/chat/completions",c={"Content-Type":"application/json"};s&&(c.Authorization="Bearer "+s);const h=JSON.stringify({model:o,messages:[{role:"system",content:"你是一名严谨的中文助理。请将用户提供的工作总结 Markdown 草稿润色为通顺、专业、简洁的工作总结。要求:保留原有章节结构与全部事实数据(数字、日期、条目),不得虚构或遗漏内容,只输出 Markdown 正文。"},{role:"user",content:e}],temperature:.3});let y;try{y=await fetch(a,{method:"POST",headers:c,body:h})}catch{throw new Error("无法访问 AI 接口:请检查地址是否正确、服务端是否允许浏览器跨域访问")}if(!y.ok){let D="接口返回 "+y.status;try{const O=await y.json();O&&O.error&&O.error.message&&(D+=":"+O.error.message)}catch{}throw new Error(D)}const m=await y.json(),k=m&&m.choices&&m.choices[0]&&m.choices[0].message&&m.choices[0].message.content;if(!k)throw new Error("接口未返回内容");return String(k)}const mg={class:"report"},yg={class:"report-toolbar"},gg={class:"seg"},bg=["onClick"],wg=["disabled"],_g=["disabled"],kg={key:0,class:"ai-error"},xg={class:"report-grid"},Cg={class:"report-left"},Sg={class:"card section"},Eg={class:"section-title"},$g={class:"muted note-saved"},Ag={class:"card section"},Pg={class:"report-right"},Tg={key:0,class:"card section"},Og={class:"sum-row"},Mg={class:"num"},Ig={class:"sum-row"},jg={class:"num"},Dg={class:"sum-row"},Rg={class:"num"},Lg={class:"sum-row"},Kg={class:"num"},Fg={class:"sum-row"},Ng={class:"num"},Vg={class:"muted"},Bg={class:"num"},Ug={key:0,class:"muted sum-empty"},qg={class:"muted"},Hg={key:1,class:"muted sum-empty"},Wg={class:"muted"},zg={key:2,class:"muted sum-empty"},Gg={class:"muted"},Yg={key:3,class:"muted sum-empty"},Jg=Vt({__name:"ReportView",setup(e){const t=[{key:"week",label:"本周"},{key:"month",label:"本月"},{key:"all",label:"全部"},{key:"custom",label:"自定义"}],n=N("week"),s=N(Es(xt())),o=N(xt()),a=N(null),c=N(""),d=N(!1),h=N(!1),y=N(null),m=N(""),k=N(Es(xt())),D=N(""),O=N(""),K=N(""),W=N(!1);async function de(){const A=await Za(k.value);D.value=(A==null?void 0:A.highlights)||"",O.value=(A==null?void 0:A.challenges)||"",K.value=(A==null?void 0:A.plan_next)||"",W.value=!1}async function Z(){await Tv(k.value,{highlights:D.value.trim()||null,challenges:O.value.trim()||null,plan_next:K.value.trim()||null}),W.value=!0,await L()}function E(A){const x=xt();if(A==="week"){const ie=Es(x);return{start:ie,end:Kn(ie,6),label:"本周"}}if(A==="month"){const ie=x.slice(0,7);return{start:ie+"-01",end:x,label:ie+" 本月"}}return A==="all"?{start:"2000-01-01",end:x,label:"全部实习期"}:{start:s.value,end:o.value,label:s.value+" ~ "+o.value}}async function L(){d.value=!0;const A=E(n.value),x=await Zy(A.start,A.end,A.label);a.value=x,c.value=eg(x),d.value=!1}gt(n,L),gt([s,o],()=>{n.value==="custom"&&L()}),fn(async()=>{await de(),await L()});async function Q(){const A=xt().replace(/-/g,""),x=await el("实习工作总结_"+A+".md",c.value);qe(x?"总结已导出到:"+x:"总结已导出到系统下载目录")}async function le(){await $a(c.value),qe("总结已复制到剪贴板")}async function ce(){if(h.value)return;m.value="";const A=c.value.trim();if(!A){m.value="当前草稿为空,无法润色";return}h.value=!0;try{y.value=c.value,c.value=await vg(A),qe("AI 润色完成")}catch(x){y.value=null,m.value=x instanceof Error?x.message:"润色失败"}h.value=!1}function ee(){y.value!==null&&(c.value=y.value),y.value=null}return(A,x)=>(F(),q("div",mg,[u("div",yg,[u("div",gg,[(F(),q(Re,null,ut(t,ie=>u("button",{key:ie.key,class:et(["seg-btn",{active:n.value===ie.key}]),onClick:xe=>n.value=ie.key},re(ie.label),11,bg)),64))]),n.value==="custom"?(F(),q(Re,{key:0},[$e(u("input",{type:"date",class:"input w-date","onUpdate:modelValue":x[0]||(x[0]=ie=>s.value=ie)},null,512),[[De,s.value]]),x[6]||(x[6]=u("span",{class:"muted"},"至",-1)),$e(u("input",{type:"date",class:"input w-date","onUpdate:modelValue":x[1]||(x[1]=ie=>o.value=ie)},null,512),[[De,o.value]])],64)):Ee("",!0),x[10]||(x[10]=u("span",{class:"flex1"},null,-1)),u("button",{class:"btn btn-sm",disabled:h.value,onClick:ce},[Oe(lt,{name:"edit",size:14}),x[7]||(x[7]=nn("AI 润色 ",-1))],8,wg),y.value!==null?(F(),q("button",{key:1,class:"btn btn-sm",onClick:ee},"还原润色前")):Ee("",!0),u("button",{class:"btn btn-sm",disabled:d.value,onClick:L},[Oe(lt,{name:"edit",size:14}),x[8]||(x[8]=nn("重新生成 ",-1))],8,_g),u("button",{class:"btn btn-sm",onClick:le},"复制"),u("button",{class:"btn btn-primary btn-sm",onClick:Q},[Oe(lt,{name:"export",size:14}),x[9]||(x[9]=nn("导出 Markdown ",-1))])]),m.value?(F(),q("div",kg,re(m.value),1)):Ee("",!0),u("div",xg,[u("div",Cg,[u("div",Sg,[u("div",Eg,"本周周记("+re(k.value)+" 起)",1),x[11]||(x[11]=u("label",{class:"note-label muted"},"本周亮点",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":x[2]||(x[2]=ie=>D.value=ie),placeholder:"本周最有价值的一件事",onBlur:Z},null,544),[[De,D.value]]),x[12]||(x[12]=u("label",{class:"note-label muted"},"踩的坑",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":x[3]||(x[3]=ie=>O.value=ie),placeholder:"遇到的问题与教训",onBlur:Z},null,544),[[De,O.value]]),x[13]||(x[13]=u("label",{class:"note-label muted"},"下周计划",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":x[4]||(x[4]=ie=>K.value=ie),placeholder:"下周准备做什么",onBlur:Z},null,544),[[De,K.value]]),u("div",$g,re(W.value?"已保存":"失焦自动保存"),1)]),u("div",Ag,[x[14]||(x[14]=u("div",{class:"section-title"},"总结草稿(可编辑)",-1)),$e(u("textarea",{class:"textarea md-editor","onUpdate:modelValue":x[5]||(x[5]=ie=>c.value=ie),spellcheck:"false"},null,512),[[De,c.value]])])]),u("div",Pg,[a.value?(F(),q("div",Tg,[x[20]||(x[20]=u("div",{class:"section-title"},"数据摘要",-1)),u("div",Og,[x[15]||(x[15]=u("span",{class:"muted"},"出勤",-1)),u("span",Mg,re(a.value.attendDays)+" 天",1)]),u("div",Ig,[x[16]||(x[16]=u("span",{class:"muted"},"工时",-1)),u("span",jg,re(a.value.totalHours)+" 小时",1)]),u("div",Dg,[x[17]||(x[17]=u("span",{class:"muted"},"补卡",-1)),u("span",Rg,re(a.value.makeupCount)+" 次",1)]),u("div",Lg,[x[18]||(x[18]=u("span",{class:"muted"},"请假",-1)),u("span",Kg,re(a.value.leaveCount)+" 天",1)]),u("div",Fg,[x[19]||(x[19]=u("span",{class:"muted"},"记录",-1)),u("span",Ng,re(a.value.itemCount)+" 条",1)]),x[21]||(x[21]=u("div",{class:"section-sub"},"分类分布",-1)),(F(!0),q(Re,null,ut(a.value.categoryStats,ie=>(F(),q("div",{key:ie.key,class:"sum-row"},[u("span",Vg,re(ie.label),1),u("span",Bg,re(ie.count)+" 条 · "+re(ie.percent)+"%",1)]))),128)),a.value.categoryStats.length?Ee("",!0):(F(),q("div",Ug,"(无)")),x[22]||(x[22]=u("div",{class:"section-sub"},"主要成果",-1)),(F(!0),q(Re,null,ut(a.value.milestones,(ie,xe)=>(F(),q("div",{key:"m"+xe,class:"sum-item"},[nn(re(ie.content),1),u("span",qg,"("+re(ie.date)+")",1)]))),128)),a.value.milestones.length?Ee("",!0):(F(),q("div",Hg,"(无)")),x[23]||(x[23]=u("div",{class:"section-sub"},"待跟进",-1)),(F(!0),q(Re,null,ut(a.value.followups,(ie,xe)=>(F(),q("div",{key:"f"+xe,class:"sum-item"},[nn(re(ie.content),1),u("span",Wg,"("+re(ie.date)+")",1)]))),128)),a.value.followups.length?Ee("",!0):(F(),q("div",zg,"(无)")),x[24]||(x[24]=u("div",{class:"section-sub"},"学习与成长",-1)),(F(!0),q(Re,null,ut(a.value.takeaways,(ie,xe)=>(F(),q("div",{key:"t"+xe,class:"sum-item"},[nn(re(ie.text),1),u("span",Gg,"("+re(ie.date)+")",1)]))),128)),a.value.takeaways.length?Ee("",!0):(F(),q("div",Yg,"(无)"))])):Ee("",!0)])])]))}}),Xg=Gt(Jg,[["__scopeId","data-v-43f9c59b"]]),Qg=["aria-label"],Zg={class:"dialog-head"},eb={class:"dialog-title"},tb={class:"dialog-body"},nb={class:"form-grid"},rb={class:"field span2"},sb={class:"seg"},ob={class:"field"},ib={class:"field"},ab={class:"field"},lb=["value"],ub={key:0,class:"field"},cb={class:"seg"},fb={class:"field span2"},db={key:0,class:"form-error"},pb={class:"dialog-btns"},hb=Vt({__name:"TransactionDialog",props:{open:{type:Boolean},title:{},initial:{}},emits:["cancel","save"],setup(e,{emit:t}){const n=e,s=t,o=N("expense"),a=N("餐饮"),c=N(""),d=N(""),h=N(""),y=N(!1),m=N(!1),k=N(""),D=N(null);function O(Z){n.open&&Z.key==="Escape"&&s("cancel")}gt(()=>n.open,async Z=>{var E;Z?(o.value=n.initial.type==="income"?"income":"expense",a.value=n.initial.category,c.value=n.initial.amountYuan,d.value=n.initial.date,h.value=n.initial.note,y.value=n.initial.reimbursable===1,m.value=n.initial.reimbursed===1,k.value="",window.addEventListener("keydown",O),await ts(),(E=D.value)==null||E.focus()):window.removeEventListener("keydown",O)}),dr(()=>window.removeEventListener("keydown",O)),gt(o,Z=>{a.value=Z==="expense"?Wr[0]:Vo[0]});const K=it(()=>o.value==="expense"?Wr:Vo);function W(){return a.value&&K.value.includes(a.value)?a.value:K.value[0]}function de(){const Z=Number(c.value);if(!c.value.trim()||!isFinite(Z)||Z<=0){k.value="请填写大于 0 的金额";return}if(!d.value){k.value="请选择日期";return}const E=o.value==="expense"&&y.value?1:0;s("save",{type:o.value,category:W(),amount:Math.round(Z*100),date:d.value,note:h.value.trim(),reimbursable:E,reimbursed:E&&m.value?1:0})}return(Z,E)=>(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:E[11]||(E[11]=Mr(L=>s("cancel"),["self"]))},[u("div",{class:"dialog",role:"dialog","aria-label":e.title},[u("div",Zg,[u("span",eb,re(e.title),1),u("button",{class:"icon-btn",title:"关闭",onClick:E[0]||(E[0]=L=>s("cancel"))},[Oe(lt,{name:"close",size:16})])]),u("div",tb,[u("div",nb,[u("div",rb,[E[12]||(E[12]=u("label",null,"类型",-1)),u("div",sb,[u("button",{class:et(["seg-btn",{active:o.value==="expense"}]),onClick:E[1]||(E[1]=L=>o.value="expense")},"支出",2),u("button",{class:et(["seg-btn",{active:o.value==="income"}]),onClick:E[2]||(E[2]=L=>o.value="income")},"收入",2)])]),u("div",ob,[E[13]||(E[13]=u("label",null,"金额(元,必填)",-1)),$e(u("input",{ref_key:"amountInput",ref:D,class:et(["input",{invalid:k.value}]),"onUpdate:modelValue":E[3]||(E[3]=L=>c.value=L),type:"number",min:"0",step:"0.01",placeholder:"0.00"},null,2),[[De,c.value]])]),u("div",ib,[E[14]||(E[14]=u("label",null,"日期(必填)",-1)),$e(u("input",{class:"input",type:"date","onUpdate:modelValue":E[4]||(E[4]=L=>d.value=L)},null,512),[[De,d.value]])]),u("div",ab,[E[15]||(E[15]=u("label",null,"分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":E[5]||(E[5]=L=>a.value=L)},[(F(!0),q(Re,null,ut(K.value,L=>(F(),q("option",{key:L,value:L},re(L),9,lb))),128))],512),[[Fn,a.value]])]),o.value==="expense"?(F(),q("div",ub,[E[16]||(E[16]=u("label",null,"报销状态",-1)),u("div",cb,[u("button",{class:et(["seg-btn",{active:!y.value}]),onClick:E[6]||(E[6]=L=>{y.value=!1,m.value=!1})},"无需报销",2),u("button",{class:et(["seg-btn",{active:y.value&&!m.value}]),onClick:E[7]||(E[7]=L=>{y.value=!0,m.value=!1})},"待报销",2),u("button",{class:et(["seg-btn",{active:y.value&&m.value}]),onClick:E[8]||(E[8]=L=>{y.value=!0,m.value=!0})},"已报销",2)])])):Ee("",!0),u("div",fb,[E[17]||(E[17]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":E[9]||(E[9]=L=>h.value=L),placeholder:"选填"},null,512),[[De,h.value]])])]),k.value?(F(),q("div",db,re(k.value),1)):Ee("",!0)]),u("div",pb,[u("button",{class:"btn btn-sm",onClick:E[10]||(E[10]=L=>s("cancel"))},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:de},"保存")])],8,Qg)])):Ee("",!0)]),_:1})]))}}),vb=Gt(hb,[["__scopeId","data-v-e3568c0d"]]),mb={class:"ledger-page"},yb={class:"ledger-toolbar"},gb={class:"month-title num"},bb={class:"cards"},wb={class:"card stat-card"},_b={class:"stat-num num amt-income"},kb={class:"card stat-card"},xb={class:"stat-num num"},Cb={class:"card stat-card"},Sb={class:"card stat-card"},Eb={class:"stat-num num amt-warn"},$b={class:"card sec"},Ab={class:"form-grid"},Pb={class:"field span2"},Tb={class:"seg"},Ob={class:"field"},Mb={class:"field"},Ib={class:"field"},jb=["value"],Db={key:0,class:"field"},Rb={class:"field span2"},Lb={key:0,class:"form-error"},Kb={class:"form-footer"},Fb=["disabled"],Nb=["disabled"],Vb={key:0,class:"card sec"},Bb={class:"bar-label"},Ub={class:"bar-track"},qb={class:"muted num bar-num"},Hb={class:"card table-card"},Wb={class:"tx-table"},zb={class:"num"},Gb={class:"tag"},Yb={class:"td-note"},Jb={key:0,class:"muted"},Xb={key:1,class:"tx-done"},Qb={key:2,class:"tx-pending"},Zb={class:"ops"},ew=["onClick"],tw=["onClick"],nw=["onClick"],rw={key:0},sw={class:"muted vault-note num"},ow=Vt({__name:"LedgerView",setup(e){const t=N(xt()),n=N([]),s=N(!0),o=N("expense"),a=N(""),c=N(Wr[0]),d=N(xt()),h=N(""),y=N(!1),m=N(""),k=N(!1),D=N(!1),O=N(null),K=N({type:"expense",category:Wr[0],amountYuan:"",date:xt(),note:"",reimbursable:0,reimbursed:0}),W=N(null),de=it(()=>t.value.slice(0,7)+"-01"),Z=it(()=>{const fe=Number(t.value.slice(0,4)),G=Number(t.value.slice(5,7))-1,X=new Date(fe,G+1,0).getDate();return t.value.slice(0,7)+"-"+(X<10?"0"+X:String(X))}),E=it(()=>Number(t.value.slice(0,4))+" 年 "+Number(t.value.slice(5,7))+" 月");async function L(){s.value=!0;try{n.value=await Kv(de.value,Z.value)}catch(fe){qe("账目加载失败:"+(fe instanceof Error?fe.message:String(fe)))}s.value=!1}fn(L),gt(t,L),gt(o,fe=>{c.value=fe==="expense"?Wr[0]:Vo[0]});const Q=it(()=>n.value.slice().sort((fe,G)=>fe.date===G.date?G.id-fe.id:fe.date{let fe=0,G=0,X=0;for(const ke of n.value)ke.type==="income"?fe+=ke.amount:(G+=ke.amount,ke.reimbursable===1&&ke.reimbursed!==1&&(X+=ke.amount));return{income:fe,expense:G,pending:X,balance:fe-G}}),ce=N("all"),ee=N("all"),A=it(()=>Q.value.filter(fe=>!(ce.value!=="all"&&fe.type!==ce.value||ee.value==="pending"&&!(fe.type==="expense"&&fe.reimbursable===1&&fe.reimbursed!==1)||ee.value==="done"&&!(fe.reimbursable===1&&fe.reimbursed===1)))),x=it(()=>{const fe=new Map;let G=0;for(const ke of n.value)ke.type==="expense"&&(fe.set(ke.category,(fe.get(ke.category)||0)+ke.amount),G+=ke.amount);const X=G||1;return Array.from(fe.entries()).map(ke=>({name:ke[0],amount:ke[1],percent:Math.round(ke[1]/X*100)})).sort((ke,st)=>st.amount-ke.amount)});function ie(fe){return(fe/100).toFixed(2)}function xe(fe){return(fe.type==="income"?"+":"-")+ie(fe.amount)}function J(){t.value=Bo(t.value,-1)}function Ce(){t.value=Bo(t.value,1)}function Ke(){t.value=xt()}gt(a,()=>{m.value&&(m.value="")});async function Xe(){const fe=Number(a.value);if(!a.value.trim()||!isFinite(fe)||fe<=0){m.value="请填写大于 0 的金额";return}if(!d.value){m.value="请选择日期";return}if(!k.value){k.value=!0;try{await Fv({type:o.value,category:c.value,amount:Math.round(fe*100),date:d.value,note:h.value.trim(),reimbursable:o.value==="expense"&&y.value?1:0,reimbursed:0})}catch(G){qe("添加失败:"+(G instanceof Error?G.message:String(G))),k.value=!1;return}a.value="",h.value="",y.value=!1,m.value="",await L(),qe("记账已添加"),k.value=!1}}function He(){a.value="",h.value="",y.value=!1,m.value=""}async function Ue(fe){await Bv(fe.id),await L(),qe("已标记为已报销")}function ge(fe){O.value=fe.id,K.value={type:fe.type,category:fe.category,amountYuan:ie(fe.amount),date:fe.date,note:fe.note||"",reimbursable:fe.reimbursable,reimbursed:fe.reimbursed},D.value=!0}async function Me(fe){const G=O.value;await Nv(G,fe),D.value=!1,await L(),qe("账目已更新")}async function Fe(){W.value&&W.value.id&&await Vv(W.value.id),W.value=null,await L(),qe("账目已删除")}return(fe,G)=>(F(),q("div",mb,[u("div",yb,[u("button",{class:"icon-btn",onClick:J},[Oe(lt,{name:"chevron-left",size:16})]),u("span",gb,re(E.value),1),u("button",{class:"icon-btn",onClick:Ce},[Oe(lt,{name:"chevron-right",size:16})]),u("button",{class:"btn btn-sm",onClick:Ke},"回到本月"),G[13]||(G[13]=u("span",{class:"flex1"},null,-1)),$e(u("select",{class:"select w-filter","onUpdate:modelValue":G[0]||(G[0]=X=>ce.value=X)},[...G[11]||(G[11]=[u("option",{value:"all"},"全部类型",-1),u("option",{value:"expense"},"仅支出",-1),u("option",{value:"income"},"仅收入",-1)])],512),[[Fn,ce.value]]),$e(u("select",{class:"select w-filter","onUpdate:modelValue":G[1]||(G[1]=X=>ee.value=X)},[...G[12]||(G[12]=[u("option",{value:"all"},"全部报销",-1),u("option",{value:"pending"},"待报销",-1),u("option",{value:"done"},"已报销",-1)])],512),[[Fn,ee.value]])]),u("div",bb,[u("div",wb,[G[14]||(G[14]=u("div",{class:"muted"},"本月收入(元)",-1)),u("div",_b,re(ie(le.value.income)),1)]),u("div",kb,[G[15]||(G[15]=u("div",{class:"muted"},"本月支出(元)",-1)),u("div",xb,re(ie(le.value.expense)),1)]),u("div",Cb,[G[16]||(G[16]=u("div",{class:"muted"},"本月结余(元)",-1)),u("div",{class:et(["stat-num num",{"amt-income":le.value.balance>=0,"amt-expense":le.value.balance<0}])},re(ie(le.value.balance)),3)]),u("div",Sb,[G[17]||(G[17]=u("div",{class:"muted"},"待报销(元)",-1)),u("div",Eb,re(ie(le.value.pending)),1)])]),u("div",$b,[G[24]||(G[24]=u("div",{class:"sec-head"},[u("span",{class:"sec-title"},"新增一笔"),u("span",{class:"muted form-hint"},"金额必填,回车快速添加")],-1)),u("div",Ab,[u("div",Pb,[G[18]||(G[18]=u("label",null,"类型",-1)),u("div",Tb,[u("button",{class:et(["seg-btn",{active:o.value==="expense"}]),onClick:G[2]||(G[2]=X=>o.value="expense")},"支出",2),u("button",{class:et(["seg-btn",{active:o.value==="income"}]),onClick:G[3]||(G[3]=X=>o.value="income")},"收入",2)])]),u("div",Ob,[G[19]||(G[19]=u("label",null,"金额(元,必填)",-1)),$e(u("input",{class:et(["input",{invalid:m.value}]),"onUpdate:modelValue":G[4]||(G[4]=X=>a.value=X),type:"number",min:"0",step:"0.01",placeholder:"0.00",onKeydown:jt(Xe,["enter"])},null,34),[[De,a.value]])]),u("div",Mb,[G[20]||(G[20]=u("label",null,"日期",-1)),$e(u("input",{class:"input",type:"date","onUpdate:modelValue":G[5]||(G[5]=X=>d.value=X)},null,512),[[De,d.value]])]),u("div",Ib,[G[21]||(G[21]=u("label",null,"分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":G[6]||(G[6]=X=>c.value=X)},[(F(!0),q(Re,null,ut(o.value==="expense"?Qt(Wr):Qt(Vo),X=>(F(),q("option",{key:X,value:X},re(X),9,jb))),128))],512),[[Fn,c.value]])]),o.value==="expense"?(F(),q("div",Db,[G[22]||(G[22]=u("label",null,"报销",-1)),u("button",{class:et(["toggle-btn",{on:y.value}]),onClick:G[7]||(G[7]=X=>y.value=!y.value)},re(y.value?"需要报销":"无需报销"),3)])):Ee("",!0),u("div",Rb,[G[23]||(G[23]=u("label",null,"备注",-1)),$e(u("input",{class:"input","onUpdate:modelValue":G[8]||(G[8]=X=>h.value=X),placeholder:"选填,如:客户现场午餐",onKeydown:jt(Xe,["enter"])},null,544),[[De,h.value]])])]),m.value?(F(),q("div",Lb,re(m.value),1)):Ee("",!0),u("div",Kb,[u("button",{class:"btn btn-sm",disabled:!(a.value.trim()||h.value.trim()),onClick:He},"重置",8,Fb),u("button",{class:"btn btn-primary btn-sm",disabled:k.value,onClick:Xe},"添加记录",8,Nb)])]),x.value.length?(F(),q("div",Vb,[G[25]||(G[25]=u("div",{class:"sec-title"},"本月支出分类",-1)),(F(!0),q(Re,null,ut(x.value,X=>(F(),q("div",{key:X.name,class:"bar-row"},[u("span",Bb,re(X.name),1),u("span",Ub,[u("span",{class:"bar-fill",style:sr({width:X.percent+"%"})},null,4)]),u("span",qb,re(ie(X.amount))+" 元 · "+re(X.percent)+"%",1)]))),128))])):Ee("",!0),u("div",Hb,[u("table",Wb,[G[27]||(G[27]=u("thead",null,[u("tr",null,[u("th",null,"日期"),u("th",null,"分类"),u("th",null,"金额(元)"),u("th",null,"备注"),u("th",null,"报销"),u("th",{class:"th-ops"},"操作")])],-1)),u("tbody",null,[(F(!0),q(Re,null,ut(A.value,X=>(F(),q("tr",{key:X.id},[u("td",zb,re(X.date),1),u("td",null,[u("span",Gb,re(X.category),1)]),u("td",{class:et(["num",X.type==="income"?"amt-income":"amt-expense"])},re(xe(X)),3),u("td",Yb,re(X.note||"--"),1),u("td",null,[X.type!=="expense"||X.reimbursable!==1?(F(),q("span",Jb,"--")):X.reimbursed===1?(F(),q("span",Xb,"已报销")):(F(),q("span",Qb,"待报销"))]),u("td",null,[u("div",Zb,[X.type==="expense"&&X.reimbursable===1&&X.reimbursed!==1?(F(),q("button",{key:0,class:"btn btn-xs",onClick:ke=>Ue(X)},"标记已报销",8,ew)):Ee("",!0),u("button",{class:"btn btn-xs",onClick:ke=>ge(X)},"编辑",8,tw),u("button",{class:"btn btn-xs",onClick:ke=>W.value=X},"删除",8,nw)])])]))),128)),!A.value.length&&!s.value?(F(),q("tr",rw,[...G[26]||(G[26]=[u("td",{colspan:"6",class:"empty muted"},"本月暂无账目",-1)])])):Ee("",!0)])])]),u("div",sw,"筛选结果 "+re(A.value.length)+" 条 / 本月共 "+re(n.value.length)+" 条",1),Oe(vb,{open:D.value,title:(O.value,"编辑账目"),initial:K.value,onCancel:G[9]||(G[9]=X=>D.value=!1),onSave:Me},null,8,["open","title","initial"]),Oe(ur,{open:!!W.value,title:"删除确认",message:W.value?"将删除 "+W.value.date+" 的账目("+W.value.category+" "+ie(W.value.amount)+" 元)。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:G[10]||(G[10]=X=>W.value=null),onConfirm:Fe},null,8,["open","message"])]))}}),iw=Gt(ow,[["__scopeId","data-v-848ec3d4"]]),aw={class:"memo-page"},lw={class:"card memo-list"},uw={class:"pane-head"},cw={class:"pane-title"},fw={class:"memo-scroll"},dw=["onClick"],pw={class:"memo-item-title"},hw={class:"muted memo-item-sub"},vw={class:"muted num memo-item-time"},mw={key:0,class:"muted empty"},yw={class:"card memo-editor"},gw={class:"editor-foot"},bw={class:"muted foot-info"},ww=["disabled"],_w=["disabled"],kw={key:1,class:"empty muted editor-empty"},xw=Vt({__name:"MemoView",setup(e){const t=N([]),n=N(null),s=N(!1),o=N(""),a=N(""),c=N(null),d=N(null);async function h(){if(t.value=await Mv(),n.value&&n.value.id){const ce=t.value.find(ee=>ee.id===n.value.id);ce&&(n.value=ce)}}fn(async()=>{await h(),t.value.length&&k(t.value[0]),window.addEventListener("keydown",y)}),dr(()=>window.removeEventListener("keydown",y)),gt(Ea,async ce=>{if(!ce)return;t.value.length||await h();const ee=t.value.find(A=>A.id===ce);Ea.value=null,ee&&D(ee)},{immediate:!0});function y(ce){(ce.ctrlKey||ce.metaKey)&&ce.key.toLowerCase()==="s"&&s.value&&m.value&&(ce.preventDefault(),de())}const m=it(()=>{if(!s.value)return!1;const ce=n.value?n.value.title:"",ee=n.value?n.value.content:"";return o.value!==ce||a.value!==ee});function k(ce){n.value=ce,s.value=!0,o.value=ce.title,a.value=ce.content}function D(ce){if(!(s.value&&n.value&&n.value.id===ce.id)){if(m.value){d.value={type:"select",memo:ce};return}k(ce)}}function O(){if(m.value){d.value={type:"new"};return}K()}function K(){n.value=null,s.value=!0,o.value="",a.value=""}function W(){n.value?k(n.value):K()}async function de(){if(!o.value.trim()&&!a.value.trim()){qe("标题与内容不能都为空");return}if(n.value&&n.value.id)await jv(n.value.id,o.value,a.value),qe("备忘已保存");else{const ce=await Iv(o.value,a.value);n.value=ce,o.value=ce.title,a.value=ce.content,qe("备忘已创建")}await h()}function Z(){n.value&&n.value.id&&(c.value=n.value)}async function E(){c.value&&c.value.id&&(await Dv(c.value.id),qe("备忘已删除")),c.value=null,await h(),K()}function L(){const ce=d.value;d.value=null,ce&&(ce.type==="select"?k(ce.memo):K())}function Q(ce){return(ce.content||"").replace(/\s+/g," ").slice(0,30)}function le(ce){return ce.replace("T"," ").slice(0,16)}return(ce,ee)=>(F(),q("div",aw,[u("aside",lw,[u("div",uw,[u("span",cw,"备忘录("+re(t.value.length)+")",1),u("button",{class:"btn btn-primary btn-sm",onClick:O},"新建")]),u("div",fw,[(F(!0),q(Re,null,ut(t.value,A=>(F(),q("div",{key:A.id,class:et(["memo-item",{active:s.value&&n.value&&n.value.id===A.id}]),onClick:x=>D(A)},[u("div",pw,re(A.title||"无标题"),1),u("div",hw,re(Q(A)||"空"),1),u("div",vw,re(le(A.updated_at)),1)],10,dw))),128)),t.value.length?Ee("",!0):(F(),q("div",mw,"暂无备忘"))])]),u("section",yw,[s.value?(F(),q(Re,{key:0},[$e(u("input",{class:"input title-input","onUpdate:modelValue":ee[0]||(ee[0]=A=>o.value=A),placeholder:"标题"},null,512),[[De,o.value]]),$e(u("textarea",{class:"textarea content-textarea","onUpdate:modelValue":ee[1]||(ee[1]=A=>a.value=A),placeholder:"内容"},null,512),[[De,a.value]]),u("div",gw,[u("span",bw,[m.value?(F(),q(Re,{key:0},[nn("有未保存修改")],64)):n.value&&n.value.id?(F(),q(Re,{key:1},[nn("更新于 "+re(le(n.value.updated_at)),1)],64)):(F(),q(Re,{key:2},[nn("新备忘")],64))]),ee[4]||(ee[4]=u("span",{class:"flex1"},null,-1)),n.value&&n.value.id?(F(),q("button",{key:0,class:"btn btn-sm",onClick:Z},"删除")):Ee("",!0),u("button",{class:"btn btn-sm",disabled:!m.value,onClick:W},"放弃修改",8,ww),u("button",{class:"btn btn-primary btn-sm",disabled:!m.value,onClick:de},"保存",8,_w)])],64)):(F(),q("div",kw,"选择左侧备忘,或点击右上角新建"))]),Oe(ur,{open:!!c.value,title:"删除确认",message:c.value?"将删除备忘「"+(c.value.title||"无标题")+"」。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:ee[2]||(ee[2]=A=>c.value=null),onConfirm:E},null,8,["open","message"]),Oe(ur,{open:!!d.value,title:"未保存提示",message:"当前备忘有未保存的修改,继续操作将丢失这些修改。","confirm-text":"放弃修改并继续",onCancel:ee[3]||(ee[3]=A=>d.value=null),onConfirm:L},null,8,["open"])]))}}),Cw=Gt(xw,[["__scopeId","data-v-74d60dba"]]),Sw=["aria-label"],Ew={class:"dialog-head"},$w={class:"dialog-title"},Aw={class:"dialog-body"},Pw={class:"form-grid"},Tw={class:"field span2"},Ow={class:"field span2"},Mw={class:"field span2"},Iw={class:"pwd-row"},jw={class:"field span2"},Dw={key:0,class:"form-error"},Rw={class:"dialog-btns"},Lw=Vt({__name:"CredentialDialog",props:{open:{type:Boolean},title:{},initial:{}},emits:["cancel","save"],setup(e,{emit:t}){const n=e,s=t,o=N(""),a=N(""),c=N(""),d=N(""),h=N(""),y=N(null);function m(O){n.open&&O.key==="Escape"&&s("cancel")}gt(()=>n.open,async O=>{var K;O?(o.value=n.initial.system,a.value=n.initial.account,c.value=n.initial.password,d.value=n.initial.remark,h.value="",window.addEventListener("keydown",m),await ts(),(K=y.value)==null||K.focus()):window.removeEventListener("keydown",m)}),dr(()=>window.removeEventListener("keydown",m));function k(){const O="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",K="!@#$%^&*",W=crypto.getRandomValues(new Uint8Array(14));let de="";for(let Z=0;Z(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:K[6]||(K[6]=Mr(W=>s("cancel"),["self"]))},[u("div",{class:"dialog",role:"dialog","aria-label":e.title},[u("div",Ew,[u("span",$w,re(e.title),1),u("button",{class:"icon-btn",title:"关闭",onClick:K[0]||(K[0]=W=>s("cancel"))},[Oe(lt,{name:"close",size:16})])]),u("div",Aw,[u("div",Pw,[u("div",Tw,[K[7]||(K[7]=u("label",null,"系统名称(必填)",-1)),$e(u("input",{ref_key:"systemInput",ref:y,class:"input","onUpdate:modelValue":K[1]||(K[1]=W=>o.value=W),placeholder:"如:企业邮箱 / OA / VPN"},null,512),[[De,o.value]])]),u("div",Ow,[K[8]||(K[8]=u("label",null,"账号(必填)",-1)),$e(u("input",{class:"input","onUpdate:modelValue":K[2]||(K[2]=W=>a.value=W),placeholder:"用户名、工号或邮箱"},null,512),[[De,a.value]])]),u("div",Mw,[K[9]||(K[9]=u("label",null,"密码(必填)",-1)),u("div",Iw,[$e(u("input",{class:"input","onUpdate:modelValue":K[3]||(K[3]=W=>c.value=W),placeholder:"输入或点击生成"},null,512),[[De,c.value]]),u("button",{class:"btn btn-sm",onClick:k},"生成")])]),u("div",jw,[K[10]||(K[10]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":K[4]||(K[4]=W=>d.value=W),placeholder:"用途、到期时间、负责人等(选填)"},null,512),[[De,d.value]])])]),h.value?(F(),q("div",Dw,re(h.value),1)):Ee("",!0)]),u("div",Rw,[u("button",{class:"btn btn-sm",onClick:K[5]||(K[5]=W=>s("cancel"))},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:D},"保存")])],8,Sw)])):Ee("",!0)]),_:1})]))}}),Kw=Gt(Lw,[["__scopeId","data-v-f383b0a6"]]),pf=15e4;function qo(e){const t=new Uint8Array(e);let n="";for(let s=0;s{n.value&&(Yo(),n.value=!1,y.value=[],k.value={},qe("长时间未操作,密码库已自动锁定"))},$_)}function A(){n.value&&ee()}fn(async()=>{t.value=await vf(),window.addEventListener("click",A),window.addEventListener("keydown",A),n.value&&ee()}),dr(()=>{window.removeEventListener("click",A),window.removeEventListener("keydown",A),ce!==null&&window.clearTimeout(ce)});const x=it(()=>{const G=m.value.trim().toLowerCase();return G?y.value.filter(X=>(X.system+" "+X.account+" "+(X.remark||"")).toLowerCase().includes(G)):y.value});async function ie(){if(!s.value){if(c.value="",!o.value){c.value="请输入主密码";return}if(o.value.length<6){c.value="主密码至少 6 位";return}if(o.value!==a.value){c.value="两次输入的主密码不一致";return}s.value=!0;try{await Nw(o.value),o.value="",a.value="",n.value=!0,ee(),await le(),qe("主密码已设置,密码库已解锁")}catch(G){c.value=G instanceof Error?G.message:"设置失败"}s.value=!1}}async function xe(){if(!s.value){if(h.value="",!d.value){h.value="请输入主密码";return}s.value=!0;try{await Vw(d.value),d.value="",n.value=!0,ee(),await le()}catch(G){h.value=G instanceof Error?G.message:"解锁失败"}s.value=!1}}function J(){Yo(),n.value=!1,y.value=[],k.value={},ce!==null&&window.clearTimeout(ce),qe("密码库已锁定")}async function Ce(G){const X=G.id;if(k.value[X]){k.value[X]=!1;return}try{G.passwordPlain=await la(X),k.value[X]=!0}catch(ke){qe(ke instanceof Error?ke.message:"解密失败")}}async function Ke(G){try{const X=await la(G.id);await $a(X),qe("密码已复制")}catch(X){qe(X instanceof Error?X.message:"复制失败")}}async function Xe(G){await $a(G.account),qe("账号已复制")}function He(){O.value=null,K.value={system:"",account:"",password:"",remark:""},D.value=!0}async function Ue(G){try{const X=await la(G.id);O.value=G.id,K.value={system:G.system,account:G.account,password:X,remark:G.remark||""},D.value=!0}catch(X){qe(X instanceof Error?X.message:"解密失败")}}async function ge(G){const X=O.value??void 0;await Hw(G,X),D.value=!1,await le(),qe(X?"账号已更新":"账号已添加")}async function Me(){W.value&&W.value.id&&(await Ww(W.value.id),qe("账号已删除")),W.value=null,await le()}function Fe(){Z.value="",E.value="",L.value="",Q.value="",de.value=!0}async function fe(){Q.value="";try{const G=await zw(Z.value,E.value);de.value=!1,Z.value="",E.value="",L.value="",qe("主密码已修改,"+G+" 条账号密码已重新加密")}catch(G){Q.value=G instanceof Error?G.message:"修改失败"}}return(G,X)=>(F(),q("div",Yw,[t.value===null?(F(),q("div",Jw,"加载中")):n.value?(F(),q(Re,{key:2},[u("div",r_,[u("div",s_,[Oe(lt,{name:"search",size:14,class:"search-icon"}),$e(u("input",{class:"input","onUpdate:modelValue":X[3]||(X[3]=ke=>m.value=ke),placeholder:"搜索系统名称、账号或备注"},null,512),[[De,m.value]])]),X[16]||(X[16]=u("span",{class:"flex1"},null,-1)),u("button",{class:"btn btn-sm",onClick:Fe},"修改主密码"),u("button",{class:"btn btn-sm",onClick:J},"锁定"),u("button",{class:"btn btn-primary btn-sm",onClick:He},"新增账号")]),u("div",o_,[u("table",i_,[X[18]||(X[18]=u("thead",null,[u("tr",null,[u("th",null,"系统名称"),u("th",null,"账号"),u("th",null,"密码"),u("th",null,"备注"),u("th",{class:"th-ops"},"操作")])],-1)),u("tbody",null,[(F(!0),q(Re,null,ut(x.value,ke=>(F(),q("tr",{key:ke.id},[u("td",a_,re(ke.system),1),u("td",null,[u("span",{class:"copyable",title:"点击复制账号",onClick:st=>Xe(ke)},re(ke.account),9,l_)]),u("td",null,[u("div",u_,[u("span",c_,re(k.value[ke.id]?ke.passwordPlain:"........"),1),u("button",{class:"btn btn-xs",onClick:st=>Ce(ke)},re(k.value[ke.id]?"隐藏":"显示"),9,f_),u("button",{class:"btn btn-xs",onClick:st=>Ke(ke)},"复制",8,d_)])]),u("td",p_,re(ke.remark||"--"),1),u("td",null,[u("div",h_,[u("button",{class:"btn btn-xs",onClick:st=>Ue(ke)},"编辑",8,v_),u("button",{class:"btn btn-xs",onClick:st=>W.value=ke},"删除",8,m_)])])]))),128)),x.value.length?Ee("",!0):(F(),q("tr",y_,[...X[17]||(X[17]=[u("td",{colspan:"5",class:"empty muted"},"暂无账号,点击右上角新增",-1)])]))])])]),u("div",g_,"共 "+re(y.value.length)+" 条账号记录 · 密码以 AES-256-GCM 加密存储于本机",1)],64)):(F(),q("div",Xw,[u("div",Qw,[Oe(lt,{name:"lock",size:26})]),t.value===!1?(F(),q(Re,{key:0},[X[12]||(X[12]=u("div",{class:"lock-title"},"设置主密码",-1)),X[13]||(X[13]=u("div",{class:"muted lock-tip"},"主密码用于加密保存在本机的账号密码,遗忘后无法找回,请务必牢记",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[0]||(X[0]=ke=>o.value=ke),placeholder:"设置主密码(至少 6 位)",onKeydown:jt(ie,["enter"])},null,544),[[De,o.value]]),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[1]||(X[1]=ke=>a.value=ke),placeholder:"再次输入主密码",onKeydown:jt(ie,["enter"])},null,544),[[De,a.value]]),c.value?(F(),q("div",Zw,re(c.value),1)):Ee("",!0),u("button",{class:"btn btn-primary lock-btn",disabled:s.value,onClick:ie},"完成设置并解锁",8,e_)],64)):(F(),q(Re,{key:1},[X[14]||(X[14]=u("div",{class:"lock-title"},"密码库已锁定",-1)),X[15]||(X[15]=u("div",{class:"muted lock-tip"},"输入主密码解锁后查看与复制密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[2]||(X[2]=ke=>d.value=ke),placeholder:"主密码",onKeydown:jt(xe,["enter"])},null,544),[[De,d.value]]),h.value?(F(),q("div",t_,re(h.value),1)):Ee("",!0),u("button",{class:"btn btn-primary lock-btn",disabled:s.value,onClick:xe},"解锁",8,n_)],64))])),Oe(Kw,{open:D.value,title:O.value?"编辑账号":"新增账号",initial:K.value,onCancel:X[4]||(X[4]=ke=>D.value=!1),onSave:ge},null,8,["open","title","initial"]),Oe(ur,{open:!!W.value,title:"删除确认",message:W.value?"将删除系统「"+W.value.system+"」的账号记录。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:X[5]||(X[5]=ke=>W.value=null),onConfirm:Me},null,8,["open","message"]),(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[de.value?(F(),q("div",{key:0,class:"mask",onClick:X[11]||(X[11]=Mr(ke=>de.value=!1,["self"]))},[u("div",b_,[u("div",w_,[X[19]||(X[19]=u("span",{class:"dialog-title"},"修改主密码",-1)),u("button",{class:"icon-btn",title:"关闭",onClick:X[6]||(X[6]=ke=>de.value=!1)},[Oe(lt,{name:"close",size:16})])]),u("div",__,[u("div",k_,[X[20]||(X[20]=u("label",null,"旧主密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[7]||(X[7]=ke=>Z.value=ke)},null,512),[[De,Z.value]])]),u("div",x_,[X[21]||(X[21]=u("label",null,"新主密码(至少 6 位)",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[8]||(X[8]=ke=>E.value=ke)},null,512),[[De,E.value]])]),u("div",C_,[X[22]||(X[22]=u("label",null,"确认新主密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[9]||(X[9]=ke=>L.value=ke)},null,512),[[De,L.value]])]),Q.value?(F(),q("div",S_,re(Q.value),1)):Ee("",!0),X[23]||(X[23]=u("div",{class:"muted vp-tip"},"确认后所有账号密码将使用新主密码重新加密",-1))]),u("div",E_,[u("button",{class:"btn btn-sm",onClick:X[10]||(X[10]=ke=>de.value=!1)},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:fe},"确认修改")])])])):Ee("",!0)]),_:1})]))]))}}),P_=Gt(A_,[["__scopeId","data-v-6820bc9c"]]);function T_(e){return'"'+(e==null?"":String(e)).replace(/"/g,'""')+'"'}async function Mu(e,t){const s="\uFEFF"+t.map(d=>d.map(T_).join(",")).join(`\r -`);if(Zr.isNativePlatform()){const{downloadText:d}=await uf(async()=>{const{downloadText:h}=await Promise.resolve().then(()=>hg);return{downloadText:h}},void 0,import.meta.url);return d(e,s)}const o=new Blob([s],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(o),c=document.createElement("a");return c.href=a,c.download=e,c.click(),window.setTimeout(()=>URL.revokeObjectURL(a),1e4),""}class O_ extends Ir{constructor(){super("intern_worklog_users"),this.version(1).stores({user:"id, &username"})}}const Or=new O_,pi="intern_worklog",nl="dsh_session_user";function hi(){try{const e=localStorage.getItem(nl);if(!e)return null;const t=JSON.parse(e);if(t&&t.userId&&t.username)return t}catch{}return null}function yf(e){localStorage.setItem(nl,JSON.stringify(e))}function gf(){localStorage.removeItem(nl)}const rl="dsh_cloud_creds";function bf(e,t){localStorage.setItem(rl,JSON.stringify({username:e,password:t}))}function vi(){try{const e=localStorage.getItem(rl);if(!e)return null;const t=JSON.parse(e);if(t&&t.username&&t.password)return t}catch{}return null}function wf(){localStorage.removeItem(rl)}function sl(e){Hh(new nf(pi+"_"+e))}async function M_(e,t,n){const s=e.trim();if(s.length<2||s.length>20)throw new Error("用户名需 2 到 20 个字符");if(t.length<6)throw new Error("登录密码至少 6 位");if(await Or.user.where("username").equals(s).first())throw new Error("用户名已存在");const a=tl(),c=await Wo(t,a),d="u_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6);await Or.user.add({id:d,username:s,pwd_hash:c,pwd_salt:a,created_at:new Date().toISOString()}),sl(d);let h=0;n&&await _f()&&(h=await L_(),await Or.user.update(d,{legacy_imported_at:new Date().toISOString()}));const y={userId:d,username:s};return yf(y),bf(y.username,t),h&&K_(h),y}async function I_(e,t){const n=e.trim(),s=await Or.user.where("username").equals(n).first();if(!s)throw new Error("用户不存在");if(await Wo(t,s.pwd_salt)!==s.pwd_hash)throw new Error("密码不正确");sl(s.id);const a={userId:s.id,username:s.username};return yf(a),bf(a.username,t),a}async function j_(){Yo(),rf(),gf(),wf()}async function D_(e,t){const n=hi();if(!n)throw new Error("未登录");if(t.length<6)throw new Error("新密码至少 6 位");const s=await Or.user.get(n.userId);if(!s)throw new Error("用户不存在");if(await Wo(e,s.pwd_salt)!==s.pwd_hash)throw new Error("旧密码不正确");const a=tl(),c=await Wo(t,a);await Or.user.update(s.id,{pwd_hash:c,pwd_salt:a})}async function R_(){const e=hi();if(!e)throw new Error("未登录");Yo(),rf(),await Ir.delete(pi+"_"+e.userId),await Or.user.delete(e.userId),gf(),wf()}async function _f(){return Ir.exists(pi)}async function L_(){if(!ne)throw new Error("用户数据库未就绪");const e=new nf(pi),t=await Promise.all([e.project.toArray(),e.work_log.toArray(),e.log_item.toArray(),e.attendance.toArray(),e.weekly_note.toArray(),e.setting.toArray(),e.memo.toArray(),e.credential.toArray()]);await ne.transaction("rw",[ne.project,ne.work_log,ne.log_item,ne.attendance,ne.weekly_note,ne.setting,ne.memo,ne.credential],async()=>{await Promise.all([ne.project.clear(),ne.work_log.clear(),ne.log_item.clear(),ne.attendance.clear(),ne.weekly_note.clear(),ne.setting.clear(),ne.memo.clear(),ne.credential.clear()]),t[0].length&&await ne.project.bulkAdd(t[0]),t[1].length&&await ne.work_log.bulkAdd(t[1]),t[2].length&&await ne.log_item.bulkAdd(t[2]),t[3].length&&await ne.attendance.bulkAdd(t[3]),t[4].length&&await ne.weekly_note.bulkAdd(t[4]),t[5].length&&await ne.setting.bulkAdd(t[5]),t[6].length&&await ne.memo.bulkAdd(t[6]),t[7].length&&await ne.credential.bulkAdd(t[7])});const n=t[0].length+t[1].length+t[2].length+t[3].length+t[4].length+t[6].length+t[7].length;return e.close(),n}function K_(e){try{sessionStorage.setItem("dsh_migrate_toast",String(e))}catch{}}const F_="https://daywk.linyux.cn",Aa=["project","work_log","log_item","attendance","weekly_note","setting","memo","credential","transaction"],Pa=new Set(["sync_cursor","sync_last_time","sync_token","last_project","last_category"]);function N_(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Iu(e){const t={...e};return delete t.id,t}function ju(e){return JSON.stringify(e)}async function V_(e){return ne.table(e).toArray()}function Ta(e,t){return e==="setting"?t.key:t.id}async function B_(){for(const e of Aa){const t=ne.table(e),n=await t.toArray();for(const s of n){if(e==="setting"&&Pa.has(s.key))continue;const o={};s.uuid||(o.uuid=N_()),s.updated_at||(o.updated_at=s.created_at||wt()),Object.keys(o).length&&await t.update(Ta(e,s),o)}}}async function ol(){return await yt("sync_base_url","")||F_}async function kf(){const e=vi();if(!e)throw new Error("未登录,无法同步");return{baseUrl:await ol(),username:e.username,password:e.password}}async function U_(){return Sf(await kf())}async function xf(){const e=vi();if(!e)throw new Error("未登录");const t=await ol(),n={"Content-Type":"application/json"},s=JSON.stringify({username:e.username,password:e.password});let o=await fetch(t+"/api/auth/register",{method:"POST",headers:n,body:s});if(o.status===409){if(o=await fetch(t+"/api/auth/login",{method:"POST",headers:n,body:s}),!o.ok)throw new Error("云端已存在同名账号且密码不一致,请检查")}else if(!o.ok)throw new Error("云端绑定失败:"+o.status)}async function q_(){return vi()!=null}async function H_(){return yt("sync_last_time","")}async function Cf(e,t){const n=await fetch(e+"/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t.username.trim(),password:t.password})});if(!n.ok)throw new Error("云端账号或密码不正确");const s=await n.json();if(!s||!s.token)throw new Error("云端登录异常");return String(s.token)}async function W_(e,t){let n=await yt("sync_token","");return n||(n=await Cf(e,t),await kt("sync_token",n),n)}let $s=!1,To=!1,Oa=!1,Gr=null,wn=null,Ma="",Du=!1;async function Yr(){if($s){To=!0;return}try{if(!await q_())return;await Sf(await kf())}catch{}}function z_(){Du||(Du=!0,ne.on("changes",()=>{Oa||$s||(Gr&&window.clearTimeout(Gr),Gr=window.setTimeout(()=>{Yr()},3e3))}))}function G_(){wn&&(wn.close(),wn=null,Ma=""),Gr&&(window.clearTimeout(Gr),Gr=null)}function Y_(e,t){const n=e+"|"+t;if(!(wn&&Ma===n)){wn&&(wn.close(),wn=null);try{wn=new EventSource(e+"/api/events?token="+encodeURIComponent(t)),Ma=n,wn.onmessage=()=>{Yr()}}catch{wn=null}}}async function Sf(e){if($s)return To=!0,{pushed:0,pulled:0,removed:0,at:""};$s=!0,Oa=!0;try{const t=await J_(e);return To&&(To=!1,window.setTimeout(()=>{Yr()},800)),t}finally{$s=!1,Oa=!1}}async function J_(e){const t=e.baseUrl.trim().replace(/\/+$/,"");if(!t)throw new Error("请先配置同步服务地址");await B_();const n=await ne.sync_mirror.toArray(),s=new Map;for(const Z of n)s.set(Z.table+"|"+Z.uuid,Z);const o={},a=[];let c=0;for(const Z of Aa){let E=await V_(Z);Z==="setting"&&(E=E.filter(Q=>!Pa.has(Q.key)));const L=new Map;for(const Q of E)L.set(Q.uuid,Q);for(const[Q,le]of L){const ce=Iu(le),ee=ju(ce),A=s.get(Z+"|"+Q);(!A||A.hash!==ee)&&(o[Z]=o[Z]||[],o[Z].push(ce),c++)}for(const[Q,le]of s)Q.startsWith(Z+"|")&&!L.has(le.uuid)&&a.push({table:Z,uuid:le.uuid,deleted_at:wt()});o[Z]=o[Z]||[]}const d=await W_(t,e),h=Z=>fetch(t+"/api/sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Z},body:JSON.stringify({device:"client",tables:o,tombstones:a})});let y=await h(d);if(y.status===401){await kt("sync_token","");const Z=await Cf(t,e);await kt("sync_token",Z),y=await h(Z)}if(!y.ok)throw new Error("同步服务返回 "+y.status);const m=await y.json(),k=m.tables||{},D=m.tombstones||[];let O=0,K=0;const W=[];for(const Z of Aa){const E=ne.table(Z),L=await E.toArray(),Q=new Map;for(const x of L)Q.set(x.uuid,x);const le=k[Z]||[],ce=new Map;for(const x of le)ce.set(x.uuid,x);const ee=new Set(D.filter(x=>x.table===Z).map(x=>x.uuid));for(const[x,ie]of Q)ee.has(x)&&(await E.delete(Ta(Z,ie)),K++);for(const[x,ie]of le){if(ee.has(x))continue;const xe=Q.get(x);if(!xe)await E.add({...ie}),O++;else{const J=String(xe.updated_at||"");if(String(ie.updated_at||"")>J){const Ke={...ie};Z==="setting"&&delete Ke.key,await E.update(Ta(Z,xe),Ke),O++}}}const A=await E.toArray();for(const x of A)Z==="setting"&&Pa.has(x.key)||W.push({table:Z,uuid:x.uuid,hash:ju(Iu(x))})}await ne.sync_mirror.clear(),W.length&&await ne.sync_mirror.bulkAdd(W.map(Z=>({...Z}))),Y_(t,d);const de=wt();return await kt("sync_last_time",de),{pushed:c,pulled:O,removed:K,at:de}}const X_={class:"settings"},Q_={class:"card section"},Z_={class:"muted acc-line"},e1={class:"ai-grid"},t1={class:"rule-item"},n1={class:"rule-item"},r1={class:"rule-item"},s1={key:0,class:"form-error"},o1={class:"rule-save"},i1={class:"card section"},a1={class:"rule-grid"},l1={class:"rule-item"},u1={class:"rule-item"},c1={class:"rule-item"},f1={class:"rule-item"},d1={class:"rule-item"},p1={class:"card section"},h1={class:"proj-add"},v1={key:0,class:"muted proj-tip"},m1=["onKeydown"],y1=["onClick"],g1=["onClick"],b1=["onClick"],w1={key:1,class:"muted"},_1={class:"card section"},k1={class:"card section"},x1={class:"muted acc-line"},C1={class:"rule-item"},S1={class:"rule-save"},E1=["disabled"],$1={key:0,class:"muted acc-line"},A1={key:1,class:"form-error"},P1={class:"card section"},T1={class:"ai-grid"},O1={class:"rule-item"},M1={class:"rule-item"},I1={class:"rule-item"},j1={class:"card section"},D1={class:"backup-row"},R1={key:0,class:"import-error"},L1=Vt({__name:"SettingsView",setup(e){var je;const t=N({work_start:"09:00",work_end:"18:00",grace_minutes:10,lunch_minutes:60,remind_weekly:"friday"}),n=N([]),s=N(""),o=N(""),a=N(""),c=N(""),d=N(""),h=N(""),y=N(null),m=N(""),k=N(null),D=N(null),O=N(""),K=N(((je=hi())==null?void 0:je.username)||""),W=N(""),de=N(""),Z=N(""),E=N(""),L=N(!1),Q="0.2.0",le=N(""),ce=N(""),ee=N(""),A=N(""),x=N(!1),ie=N("");async function xe(){var w;le.value=await ol(),ce.value=((w=vi())==null?void 0:w.username)||"",ie.value=await H_()}async function J(){await kt("sync_base_url",le.value.trim()),qe("同步地址已保存")}async function Ce(){A.value="";try{await xf(),qe("云端绑定已重建")}catch(w){A.value=w instanceof Error?w.message:"绑定失败"}}async function Ke(){if(!x.value){A.value="",x.value=!0;try{await J();const w=await U_();ie.value=w.at,ee.value="推送 "+w.pushed+" 条 · 拉取 "+w.pulled+" 条 · 删除 "+w.removed+" 条",qe("同步完成")}catch(w){A.value=w instanceof Error?w.message:"同步失败"}x.value=!1}}async function Xe(){if(E.value="",de.value!==Z.value){E.value="两次输入的新密码不一致";return}try{await D_(W.value,de.value),W.value="",de.value="",Z.value="",qe("登录密码已修改")}catch(w){E.value=w instanceof Error?w.message:"修改失败"}}async function He(){await R_(),window.location.reload()}async function Ue(){t.value=await jr(),n.value=await Ks(!0),a.value=(await Qa()).join(` -`),c.value=await yt("ai_base_url",""),d.value=await yt("ai_api_key",""),h.value=await yt("ai_model",""),await xe()}async function ge(){await kt("ai_base_url",c.value.trim()),await kt("ai_api_key",d.value.trim()),await kt("ai_model",h.value.trim()),qe("AI 配置已保存")}async function Me(){const w=xt(),g=await Promise.all([fi("2000-01-01",w),Ks(!0)]),P=g[0],ae=g[1],se=new Map(ae.map(oe=>[oe.id,oe.name])),ue=[["日期","分类","项目","内容","耗时(分钟)","成果","待跟进","收获","备注"]];for(const oe of P)ue.push([oe.date,Xa(oe.category),oe.project_id&&se.get(oe.project_id)||"",oe.content,oe.minutes==null?"":oe.minutes,oe.is_milestone?"是":"",oe.needs_followup?"是":"",oe.takeaway||"",oe.remark||""]);const ye=await Mu("工作记录_"+w.replace(/-/g,"")+".csv",ue);qe(ye?"CSV 已导出到:"+ye:"CSV 已导出到系统下载目录")}async function Fe(){const w=xt(),g=await Promise.all([jr(),ci("2000-01-01",w)]),P=g[0],ae=g[1],se=["周日","周一","周二","周三","周四","周五","周六"],ue=[["日期","星期","状态","上班时间","下班时间","地点","类型","说明"]];for(const oe of ae){const we=qs(oe,oe.date,P,oe.date===w);ue.push([oe.date,se[rs(oe.date).getDay()],we.label,oe.clock_in_at?Vn(oe.clock_in_at):"",oe.clock_out_at?Vn(oe.clock_out_at):"",oe.location||"",oe.kind==="makeup"?"补卡":oe.kind==="leave"?"休假":"正常",oe.note||""])}const ye=await Mu("考勤记录_"+w.replace(/-/g,"")+".csv",ue);qe(ye?"CSV 已导出到:"+ye:"CSV 已导出到系统下载目录")}fn(Ue);async function fe(){await kt("work_start",t.value.work_start),await kt("work_end",t.value.work_end),await kt("grace_minutes",String(t.value.grace_minutes)),await kt("lunch_minutes",String(t.value.lunch_minutes)),await kt("remind_weekly",t.value.remind_weekly),qe("打卡规则已保存")}async function G(){await of(a.value.split(` -`)),qe("常用地点已保存")}async function X(){const w=s.value.trim();if(w){try{await yv(w),o.value="",s.value=""}catch{o.value="项目名已存在"}await Ue()}}function ke(w){y.value=w.id,m.value=w.name}async function st(w){const g=m.value.trim();if(g)try{await gv(w.id,g),o.value=""}catch{o.value="项目名已存在"}y.value=null,await Ue()}async function pt(w){await bv(w.id,w.archived!==1),await Ue()}async function ht(){try{const w=await Uv(),g=await el("实习日志备份_"+xt().replace(/-/g,"")+".json",w);qe(g?"备份已导出到:"+g:"备份已导出到系统下载目录")}catch(w){qe("导出失败:"+(w instanceof Error?w.message:String(w)))}}function Yt(w){const g=w.target,P=g.files&&g.files[0];if(O.value="",!P)return;const ae=P.name;P.text().then(se=>{D.value={name:ae,text:se}}),g.value=""}async function Jt(){if(D.value)try{await qv(D.value.text),D.value=null,O.value="",await Ue(),qe("数据导入完成")}catch(w){D.value=null,O.value=w instanceof Error?w.message:"导入失败"}}return(w,g)=>(F(),q("div",X_,[u("div",Q_,[g[23]||(g[23]=u("div",{class:"section-title"},"账号与隐私",-1)),u("div",Z_,"版本 v"+re(Qt(Q))+" · 当前用户:"+re(K.value)+" · 每位用户独立数据库隔离存储于本机 · 登录密码仅保存 PBKDF2 哈希",1),u("div",e1,[u("div",t1,[g[20]||(g[20]=u("label",null,"旧登录密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":g[0]||(g[0]=P=>W.value=P)},null,512),[[De,W.value]])]),u("div",n1,[g[21]||(g[21]=u("label",null,"新登录密码(至少 6 位)",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":g[1]||(g[1]=P=>de.value=P)},null,512),[[De,de.value]])]),u("div",r1,[g[22]||(g[22]=u("label",null,"确认新登录密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":g[2]||(g[2]=P=>Z.value=P)},null,512),[[De,Z.value]])])]),E.value?(F(),q("div",s1,re(E.value),1)):Ee("",!0),u("div",o1,[u("button",{class:"btn btn-primary btn-sm",onClick:Xe},"修改登录密码"),u("button",{class:"btn btn-sm btn-danger",onClick:g[3]||(g[3]=P=>L.value=!0)},"删除此用户及全部数据")])]),u("div",i1,[g[30]||(g[30]=u("div",{class:"section-title"},"打卡规则",-1)),u("div",a1,[u("div",l1,[g[24]||(g[24]=u("label",null,"上班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":g[4]||(g[4]=P=>t.value.work_start=P)},null,512),[[De,t.value.work_start]])]),u("div",u1,[g[25]||(g[25]=u("label",null,"下班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":g[5]||(g[5]=P=>t.value.work_end=P)},null,512),[[De,t.value.work_end]])]),u("div",c1,[g[26]||(g[26]=u("label",null,"迟到宽限(分钟)",-1)),$e(u("input",{type:"number",class:"input",min:"0","onUpdate:modelValue":g[6]||(g[6]=P=>t.value.grace_minutes=P)},null,512),[[De,t.value.grace_minutes,void 0,{number:!0}]])]),u("div",f1,[g[27]||(g[27]=u("label",null,"午休扣除(分钟)",-1)),$e(u("input",{type:"number",class:"input",min:"0","onUpdate:modelValue":g[7]||(g[7]=P=>t.value.lunch_minutes=P)},null,512),[[De,t.value.lunch_minutes,void 0,{number:!0}]])]),u("div",d1,[g[29]||(g[29]=u("label",null,"周记提醒",-1)),$e(u("select",{class:"select","onUpdate:modelValue":g[8]||(g[8]=P=>t.value.remind_weekly=P)},[...g[28]||(g[28]=[u("option",{value:"friday"},"每周五提醒",-1),u("option",{value:"off"},"关闭",-1)])],512),[[Fn,t.value.remind_weekly]])])]),u("div",{class:"rule-save"},[u("button",{class:"btn btn-primary btn-sm",onClick:fe},"保存规则")])]),u("div",p1,[g[31]||(g[31]=u("div",{class:"section-title"},"项目管理",-1)),u("div",h1,[$e(u("input",{class:"input","onUpdate:modelValue":g[9]||(g[9]=P=>s.value=P),placeholder:"新项目名称",onKeydown:jt(X,["enter"])},null,544),[[De,s.value]]),u("button",{class:"btn btn-sm",onClick:X},"添加")]),o.value?(F(),q("div",v1,re(o.value),1)):Ee("",!0),(F(!0),q(Re,null,ut(n.value,P=>(F(),q("div",{key:P.id,class:"proj-row"},[y.value===P.id?(F(),q(Re,{key:0},[$e(u("input",{class:"input","onUpdate:modelValue":g[10]||(g[10]=ae=>m.value=ae),onKeydown:jt(ae=>st(P),["enter"])},null,40,m1),[[De,m.value]]),u("button",{class:"btn btn-sm",onClick:ae=>st(P)},"保存",8,y1),u("button",{class:"btn btn-sm",onClick:g[11]||(g[11]=ae=>y.value=null)},"取消")],64)):(F(),q(Re,{key:1},[u("span",{class:et(["proj-name",{archived:P.archived===1}])},re(P.name),3),u("button",{class:"icon-btn",title:"重命名",onClick:ae=>ke(P)},[Oe(lt,{name:"edit",size:14})],8,g1),u("button",{class:"btn btn-sm",onClick:ae=>pt(P)},re(P.archived===1?"恢复":"归档"),9,b1)],64))]))),128)),n.value.length?Ee("",!0):(F(),q("div",w1,"暂无项目,先添加一个"))]),u("div",_1,[g[33]||(g[33]=u("div",{class:"section-title"},"常用地点",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":g[12]||(g[12]=P=>a.value=P),placeholder:"每行一个地点,如:公司、客户现场、出差、居家办公"},null,512),[[De,a.value]]),u("div",{class:"rule-save"},[u("button",{class:"btn btn-primary btn-sm",onClick:G},"保存地点"),g[32]||(g[32]=u("span",{class:"muted loc-note"},"打卡时可直接输入新地点,保存后自动加入列表",-1))])]),u("div",k1,[g[35]||(g[35]=u("div",{class:"section-title"},"多端数据同步",-1)),u("div",x1,"云端账号:"+re(ce.value||"未绑定")+" · 登录即自动绑定并同步(变更实时推送 + 每 5 分钟兜底);密码库以密文同步,主密码永不出本机",1),u("div",C1,[g[34]||(g[34]=u("label",null,"同步服务地址(默认即可)",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[13]||(g[13]=P=>le.value=P),placeholder:"https://daywk.linyux.cn"},null,512),[[De,le.value]])]),u("div",S1,[u("button",{class:"btn btn-sm",onClick:J},"保存地址"),u("button",{class:"btn btn-primary btn-sm",disabled:x.value,onClick:Ke},re(x.value?"同步中":"立即同步"),9,E1),u("button",{class:"btn btn-sm",onClick:Ce},"重建云端绑定")]),ee.value?(F(),q("div",$1,"上次同步:"+re(ie.value||"--")+" · "+re(ee.value),1)):Ee("",!0),A.value?(F(),q("div",A1,re(A.value),1)):Ee("",!0)]),u("div",P1,[g[40]||(g[40]=u("div",{class:"section-title"},"AI 润色配置(可选)",-1)),u("div",T1,[u("div",O1,[g[36]||(g[36]=u("label",null,"接口地址(OpenAI 兼容,到 /v1 为止)",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[14]||(g[14]=P=>c.value=P),placeholder:"https://api.example.com/v1"},null,512),[[De,c.value]])]),u("div",M1,[g[37]||(g[37]=u("label",null,"API Key",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[15]||(g[15]=P=>d.value=P),placeholder:"sk-..."},null,512),[[De,d.value]])]),u("div",I1,[g[38]||(g[38]=u("label",null,"模型名称",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[16]||(g[16]=P=>h.value=P),placeholder:"如:deepseek-chat"},null,512),[[De,h.value]])])]),u("div",{class:"rule-save"},[u("button",{class:"btn btn-primary btn-sm",onClick:ge},"保存 AI 配置"),g[39]||(g[39]=u("span",{class:"muted loc-note"},"配置仅保存在本机浏览器;总结页可用 AI 润色草稿,需服务端允许浏览器跨域",-1))])]),u("div",j1,[g[41]||(g[41]=u("div",{class:"section-title"},"数据备份",-1)),u("div",D1,[u("button",{class:"btn btn-sm",onClick:ht},"导出 JSON 备份"),u("button",{class:"btn btn-sm",onClick:g[17]||(g[17]=P=>{var ae;return(ae=k.value)==null?void 0:ae.click()})},"导入 JSON 备份"),u("button",{class:"btn btn-sm",onClick:Me},"导出工作记录 CSV"),u("button",{class:"btn btn-sm",onClick:Fe},"导出考勤 CSV"),u("input",{ref_key:"fileInput",ref:k,type:"file",accept:"application/json,.json",style:{display:"none"},onChange:Yt},null,544)]),O.value?(F(),q("div",R1,re(O.value),1)):Ee("",!0),g[42]||(g[42]=u("div",{class:"muted backup-note"},"数据保存在浏览器 IndexedDB 中,建议定期导出 JSON 备份。",-1))]),Oe(ur,{open:!!D.value,title:"导入确认",message:D.value?"将从文件「"+D.value.name+"」导入备份。现有全部数据将被覆盖,且不可恢复,请先确认已导出当前备份。":"","confirm-text":"覆盖导入",danger:"",onCancel:g[18]||(g[18]=P=>D.value=null),onConfirm:Jt},null,8,["open","message"]),Oe(ur,{open:L.value,title:"删除用户确认",message:"将永久删除用户「"+K.value+"」及其全部数据:工作日志、考勤、备忘录、账号密码库都将被清除,且不可恢复。请确认。","confirm-text":"永久删除",danger:"",onCancel:g[19]||(g[19]=P=>L.value=!1),onConfirm:He},null,8,["open","message"])]))}}),K1=Gt(L1,[["__scopeId","data-v-81598f02"]]),F1={class:"login-page"},N1={class:"card login-card"},V1={class:"login-brand"},B1={class:"brand-icon"},U1={class:"seg"},q1=["placeholder"],H1={key:1,class:"mig-row"},W1={key:2,class:"form-error"},z1=["disabled"],G1=Vt({__name:"LoginView",emits:["login"],setup(e,{emit:t}){const n=t,s=N("login"),o=N(""),a=N(""),c=N(""),d=N(!0),h=N(!1),y=N(""),m=N(!1);fn(async()=>{h.value=await _f()});function k(O){s.value=O,y.value="",c.value=""}async function D(){if(!m.value){y.value="",m.value=!0;try{let O;if(s.value==="login")O=await I_(o.value,a.value);else{if(a.value.length<6){y.value="登录密码至少 6 位",m.value=!1;return}if(a.value!==c.value){y.value="两次输入的密码不一致",m.value=!1;return}O=await M_(o.value,a.value,d.value)}n("login",O)}catch(O){y.value=O instanceof Error?O.message:"操作失败"}m.value=!1}}return(O,K)=>(F(),q("div",F1,[u("div",N1,[u("div",V1,[u("div",B1,[Oe(lt,{name:"calendar",size:22})]),K[6]||(K[6]=u("div",{class:"login-title"},"实习工作日志",-1)),K[7]||(K[7]=u("div",{class:"muted login-sub"},"打卡 · 记录 · 总结 · 备忘录 · 密码库",-1)),K[8]||(K[8]=u("div",{class:"muted login-sub"},"每位用户独立数据库,数据彼此隔离并保存在本机",-1))]),u("div",U1,[u("button",{class:et(["seg-btn",{active:s.value==="login"}]),onClick:K[0]||(K[0]=W=>k("login"))},"登录",2),u("button",{class:et(["seg-btn",{active:s.value==="create"}]),onClick:K[1]||(K[1]=W=>k("create"))},"创建用户",2)]),$e(u("input",{class:"input","onUpdate:modelValue":K[2]||(K[2]=W=>o.value=W),placeholder:"用户名(2 到 20 个字符)",onKeydown:jt(D,["enter"])},null,544),[[De,o.value]]),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":K[3]||(K[3]=W=>a.value=W),placeholder:s.value==="login"?"登录密码":"设置登录密码(至少 6 位)",onKeydown:jt(D,["enter"])},null,40,q1),[[De,a.value]]),s.value==="create"?$e((F(),q("input",{key:0,type:"password",class:"input","onUpdate:modelValue":K[4]||(K[4]=W=>c.value=W),placeholder:"再次输入密码",onKeydown:jt(D,["enter"])},null,544)),[[De,c.value]]):Ee("",!0),s.value==="create"&&h.value?(F(),q("label",H1,[$e(u("input",{type:"checkbox","onUpdate:modelValue":K[5]||(K[5]=W=>d.value=W)},null,512),[[Eh,d.value]]),K[9]||(K[9]=u("span",null,"导入本机原有工作日志数据到此用户(原数据保留不删除)",-1))])):Ee("",!0),y.value?(F(),q("div",W1,re(y.value),1)):Ee("",!0),u("button",{class:"btn btn-primary login-btn",disabled:m.value,onClick:D},re(s.value==="login"?"登录":"创建并进入"),9,z1),K[10]||(K[10]=u("div",{class:"muted login-note"}," 登录后自动开启云端同步(密码会保存在本机用于云同步);系统只保存密码哈希,忘记密码将无法访问该用户数据 ",-1))])]))}}),Y1=Gt(G1,[["__scopeId","data-v-d3d6c8cb"]]),J1={key:1,class:"app"},X1={class:"side"},Q1=["data-tip","onClick"],Z1={class:"main"},e0={class:"topbar"},t0={class:"title"},n0={class:"gsearch"},r0={key:0,class:"gs-panel"},s0={key:0,class:"gs-group muted"},o0=["onMousedown"],i0={class:"tag"},a0={class:"gs-text"},l0={class:"muted num gs-date"},u0={key:1,class:"gs-group muted"},c0=["onMousedown"],f0={class:"gs-text"},d0={class:"muted gs-sub"},p0={key:1,class:"gs-empty muted"},h0={class:"user-chip num"},v0=["disabled"],m0={class:"num"},y0={class:"content"},g0={class:"content-inner"},b0={class:"toast-wrap"},w0=Vt({__name:"App",setup(e){const t=Wv(),n=N(hi());async function s(ge){n.value=ge,location.hash="#/calendar",le.value="calendar",await xe(),await Ue(),c();try{await xf(),await Yr()}catch{}showToast("欢迎,"+ge.username);const Me=sessionStorage.getItem("dsh_migrate_toast");Me&&(sessionStorage.removeItem("dsh_migrate_toast"),showToast("已迁移原有数据 "+Me+" 条"))}async function o(){G_(),a!==null&&(window.clearInterval(a),a=null),await j_(),n.value=null,le.value="calendar",location.hash="#/calendar",showToast("已退出登录")}let a=null;function c(){z_(),a!==null&&window.clearInterval(a),a=window.setInterval(()=>{Yr()},60*1e3),Yr()}const d=N(null),h=N(""),y=N(!1),m=N({logs:[],memos:[]});let k=null;const D=it(()=>!!(m.value.logs.length||m.value.memos.length));function O(){k&&window.clearTimeout(k);const ge=h.value;k=window.setTimeout(async()=>{const Me=ge.trim();if(!Me){m.value={logs:[],memos:[]};return}const Fe=await Promise.all([Rv(Me,8),Lv(Me,4)]);m.value={logs:Fe[0],memos:Fe[1]}},200)}function K(){h.value="",m.value={logs:[],memos:[]},y.value=!1}function W(ge){Sa.value=ge.date,ce("calendar"),K()}function de(ge){Ea.value=ge.id,ce("memo"),K()}function Z(){window.setTimeout(()=>{y.value=!1},150)}function E(ge){var Me;(ge.ctrlKey||ge.metaKey)&&ge.key.toLowerCase()==="k"&&(ge.preventDefault(),(Me=d.value)==null||Me.focus())}const L=[{key:"calendar",name:"日历",icon:"calendar"},{key:"today",name:"详情",icon:"edit"},{key:"stats",name:"统计",icon:"chart"},{key:"report",name:"总结",icon:"export"},{key:"ledger",name:"记账",icon:"wallet"},{key:"memo",name:"备忘录",icon:"memo"},{key:"vault",name:"密码库",icon:"lock"},{key:"settings",name:"设置",icon:"settings"}];function Q(){const ge=(location.hash||"").replace("#/","");return L.some(Me=>Me.key===ge)?ge:"calendar"}const le=N(Q());window.addEventListener("hashchange",()=>{le.value=Q()});function ce(ge){location.hash="#/"+ge}const ee=it(()=>L.find(ge=>ge.key===le.value)||L[0]),A=N(xt()),x=N(void 0),ie=N(!1);async function xe(){if(x.value=await mn(A.value),ie.value=!1,new Date().getHours()<4){const Me=await mn(Kn(A.value,-1));ie.value=!!(Me&&Me.clock_in_at&&!Me.clock_out_at)}}const J=it(()=>{const ge=x.value;return ge&&ge.clock_in_at&&!ge.clock_out_at?!0:ie.value&&!(ge&&ge.clock_in_at)}),Ce=it(()=>{const ge=x.value;return!!(ge&&ge.clock_in_at&&ge.clock_out_at)}),Ke=it(()=>{const ge=x.value;return J.value?"下班打卡":Ce.value?"已打卡 "+Vn(ge==null?void 0:ge.clock_in_at)+" - "+Vn(ge==null?void 0:ge.clock_out_at):"上班打卡"});async function Xe(){if(J.value)try{await _v()}catch{}else await af(A.value);await xe(),Sr()}gt(Hs,()=>{n.value&&xe()});const He=N(!1);async function Ue(){if((await jr()).remind_weekly==="off"){He.value=!1;return}const Me=new Date().getDay();if(Me===5||Me===6||Me===0){const Fe=await Za(Es(A.value));He.value=!Fe||!Fe.highlights&&!Fe.challenges&&!Fe.plan_next}else He.value=!1}return fn(async()=>{window.addEventListener("keydown",E),n.value&&(sl(n.value.userId),await xe(),await Ue(),c())}),(ge,Me)=>{var Fe;return n.value?(F(),q("div",J1,[u("nav",X1,[(F(),q(Re,null,ut(L,fe=>u("button",{key:fe.key,class:et(["nav-btn",{active:le.value===fe.key}]),"data-tip":fe.name,onClick:G=>ce(fe.key)},[Oe(lt,{name:fe.icon,size:18},null,8,["name"])],10,Q1)),64))]),u("div",Z1,[u("header",e0,[u("span",t0,re(ee.value.name),1),u("div",n0,[Oe(lt,{name:"search",size:14,class:"gs-icon"}),$e(u("input",{ref_key:"gsInput",ref:d,class:"input gs-input","onUpdate:modelValue":Me[0]||(Me[0]=fe=>h.value=fe),placeholder:"搜索工作记录与备忘录(Ctrl+K)",onInput:O,onFocus:Me[1]||(Me[1]=fe=>y.value=!0),onBlur:Z,onKeydown:jt(K,["esc"])},null,544),[[De,h.value]]),y.value&&h.value.trim()?(F(),q("div",r0,[D.value?(F(),q(Re,{key:0},[m.value.logs.length?(F(),q("div",s0,"工作记录")):Ee("",!0),(F(!0),q(Re,null,ut(m.value.logs,fe=>(F(),q("div",{key:"l"+fe.id,class:"gs-item",onMousedown:Mr(G=>W(fe),["prevent"])},[u("span",i0,re(Qt(Xa)(fe.category)),1),u("span",a0,re(fe.content),1),u("span",l0,re(fe.date),1)],40,o0))),128)),m.value.memos.length?(F(),q("div",u0,"备忘录")):Ee("",!0),(F(!0),q(Re,null,ut(m.value.memos,fe=>(F(),q("div",{key:"m"+fe.id,class:"gs-item",onMousedown:Mr(G=>de(fe),["prevent"])},[u("span",f0,re(fe.title||"无标题"),1),u("span",d0,re(fe.content),1)],40,c0))),128))],64)):(F(),q("div",p0,"无匹配结果"))])):Ee("",!0)]),Me[4]||(Me[4]=u("span",{class:"flex1"},null,-1)),He.value?(F(),q("button",{key:0,class:"week-tip",onClick:Me[2]||(Me[2]=fe=>ce("report"))},[...Me[3]||(Me[3]=[u("span",{class:"dot",style:{background:"var(--warn)"}},null,-1),nn(" 填写本周周记 ",-1)])])):Ee("",!0),u("span",h0,re((Fe=n.value)==null?void 0:Fe.username),1),u("button",{class:"btn btn-sm",onClick:o},"退出"),u("button",{class:"btn btn-primary btn-sm",disabled:Ce.value,onClick:Xe},[Oe(lt,{name:Ce.value?"check-circle":"clock",size:14},null,8,["name"]),u("span",m0,re(Ke.value),1)],8,v0)]),u("main",y0,[u("div",g0,[le.value==="calendar"?(F(),It(vy,{key:0})):le.value==="today"?(F(),It(_y,{key:1})):le.value==="stats"?(F(),It(Qy,{key:2})):le.value==="report"?(F(),It(Xg,{key:3})):le.value==="ledger"?(F(),It(iw,{key:4})):le.value==="memo"?(F(),It(Cw,{key:5})):le.value==="vault"?(F(),It(P_,{key:6})):(F(),It(K1,{key:7}))])])]),u("div",b0,[Oe(yh,{name:"toast"},{default:fr(()=>[(F(!0),q(Re,null,ut(Qt(t),fe=>(F(),q("div",{key:fe.id,class:"toast"},re(fe.text),1))),128))]),_:1})])])):(F(),It(Y1,{key:0,onLogin:s}))}}}),_0=Gt(w0,[["__scopeId","data-v-219a8436"]]);Ih(_0).mount("#app");"serviceWorker"in navigator&&location.protocol.startsWith("http")&&window.addEventListener("load",()=>{navigator.serviceWorker.register("sw.js").catch(()=>{})});export{df as W,uf as _,dg as b,ff as r}; + `+v:""),this.inner=v||null):typeof p=="object"&&(this.message="".concat(p.name," ").concat(p.message),this.inner=p):(this.message=X[i]||l,this.inner=null)}return W(f).from(Jt),r[i]=f,r},{}),w=(je.Syntax=SyntaxError,je.Type=TypeError,je.Range=RangeError,G.reduce(function(r,i){return r[i+"Error"]=je[i],r},{}));G=Ye.reduce(function(r,i){return["Syntax","Type","Range"].indexOf(i)===-1&&(r[i+"Error"]=je[i]),r},{});function g(){}function P(r){return r}function ae(r,i){return r==null||r===P?i:function(l){return i(r(l))}}function se(r,i){return function(){r.apply(this,arguments),i.apply(this,arguments)}}function ue(r,i){return r===g?i:function(){var l=r.apply(this,arguments),f=(l!==void 0&&(arguments[0]=l),this.onsuccess),p=this.onerror,v=(this.onsuccess=null,this.onerror=null,i.apply(this,arguments));return f&&(this.onsuccess=this.onsuccess?se(f,this.onsuccess):f),p&&(this.onerror=this.onerror?se(p,this.onerror):p),v!==void 0?v:l}}function ye(r,i){return r===g?i:function(){r.apply(this,arguments);var l=this.onsuccess,f=this.onerror;this.onsuccess=this.onerror=null,i.apply(this,arguments),l&&(this.onsuccess=this.onsuccess?se(l,this.onsuccess):l),f&&(this.onerror=this.onerror?se(f,this.onerror):f)}}function oe(r,i){return r===g?i:function(){var l=r.apply(this,arguments),f=(h(arguments[0],l),this.onsuccess),p=this.onerror,v=(this.onsuccess=null,this.onerror=null,i.apply(this,arguments));return f&&(this.onsuccess=this.onsuccess?se(f,this.onsuccess):f),p&&(this.onerror=this.onerror?se(p,this.onerror):p),l===void 0?v===void 0?void 0:v:h(l,v)}}function we(r,i){return r===g?i:function(){return i.apply(this,arguments)!==!1&&r.apply(this,arguments)}}function H(r,i){return r===g?i:function(){var l=r.apply(this,arguments);if(l&&typeof l.then=="function"){for(var f=this,p=arguments.length,v=new Array(p);p--;)v[p]=arguments[p];return l.then(function(){return i.apply(f,v)})}return i.apply(this,arguments)}}G.ModifyError=pt,G.DexieError=ke,G.BulkError=ht;var U=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Y(r){U=r}var Ae={},Fe=100,Je=typeof Promise>"u"?[]:(Ye=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[Je=crypto.subtle.digest("SHA-512",new Uint8Array([0])),y(Je),Ye]:[Ye,y(Ye),Ye]),Ye=Je[0],Br=Je[1],Br=Br&&Br.then,Qe=Ye&&Ye.constructor,vt=!!Je[2],_t=function(r,i){Hn.push([r,i]),Bt&&(queueMicrotask(Af),Bt=!1)},Xt=!0,Bt=!0,Zt=[],pr=[],Ot=P,$t={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:g,pgp:!1,env:{},finalize:g},Ie=$t,Hn=[],hr=0,Ws=[];function Se(r){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var i=this._PSD=Ie;if(typeof r!="function"){if(r!==Ae)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&bi(this,this._value)}else this._state=null,this._value=null,++i.ref,function l(f,p){try{p(function(v){if(f._state===null){if(v===f)throw new TypeError("A promise cannot be resolved with itself.");var b=f._lib&&Rr();v&&typeof v.then=="function"?l(f,function(_,S){v instanceof Se?v._then(_,S):v.then(_,S)}):(f._state=!0,f._value=v,ll(f)),b&&Lr()}},bi.bind(null,f))}catch(v){bi(f,v)}}(this,r)}var gi={get:function(){var r=Ie,i=Js;function l(f,p){var v=this,b=!r.global&&(r!==Ie||i!==Js),_=b&&!zn(),S=new Se(function(V,T){wi(v,new al(cl(f,r,b,_),cl(p,r,b,_),V,T,r))});return this._consoleTask&&(S._consoleTask=this._consoleTask),S}return l.prototype=Ae,l},set:function(r){K(this,"then",r&&r.prototype===Ae?gi:{get:function(){return r},set:gi.set})}};function al(r,i,l,f,p){this.onFulfilled=typeof r=="function"?r:null,this.onRejected=typeof i=="function"?i:null,this.resolve=l,this.reject=f,this.psd=p}function bi(r,i){var l,f;pr.push(i),r._state===null&&(l=r._lib&&Rr(),i=Ot(i),r._state=!1,r._value=i,f=r,Zt.some(function(p){return p._value===f._value})||Zt.push(f),ll(r),l)&&Lr()}function ll(r){var i=r._listeners;r._listeners=[];for(var l=0,f=i.length;l{for(var b=Zt.length;b;)if(Zt[--b]._value===v._value)return Zt.splice(b,1)})(i),l.resolve(f)}catch(v){l.reject(v)}finally{--hr==0&&_i(),--l.psd.ref||l.psd.finalize()}}function Af(){vr($t,function(){Rr()&&Lr()})}function Rr(){var r=Xt;return Bt=Xt=!1,r}function Lr(){var r,i,l;do for(;0.",fl="String expected.",Qs="__dbnames",xi="readonly",Ci="readwrite";function yr(r,i){return r?i?function(){return r.apply(this,arguments)&&i.apply(this,arguments)}:r:i}var dl={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Zs(r){return typeof r!="string"||/\./.test(r)?function(i){return i}:function(i){return i[r]===void 0&&r in i&&delete(i=xe(i))[r],i}}function pl(){throw je.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function tt(r,i){try{var l=hl(r),f=hl(i);if(l!==f)return l==="Array"?1:f==="Array"?-1:l==="binary"?1:f==="binary"?-1:l==="string"?1:f==="string"?-1:l==="Date"?1:f!=="Date"?NaN:-1;switch(l){case"number":case"Date":case"string":return i{var _=T,S=b;if(typeof S!="function"&&S!==null)throw new TypeError("Class extends value "+String(S)+" is not a constructor or null");function V(){this.constructor=_}function T(){return b!==null&&b.apply(this,arguments)||this}return n(_,S),_.prototype=S===null?Object.create(S):(V.prototype=S.prototype,new V),Object.defineProperty(T.prototype,"db",{get:function(){return i},enumerable:!1,configurable:!0}),T.prototype.table=function(){return l},T})(r)),new Set),p=r.prototype;p;p=y(p))Object.getOwnPropertyNames(p).forEach(function(b){return f.add(b)});function v(b){if(!b)return b;var _,S=Object.create(r.prototype);for(_ in b)if(!f.has(_))try{S[_]=b[_]}catch{}return S}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=v,this.hook("reading",v),r},ft.prototype.defineClass=function(){return this.mapToClass(function(r){h(this,r)})},ft.prototype.add=function(r,i){var l=this,f=this.schema.primKey,p=f.auto,v=f.keyPath,b=r;return v&&p&&(b=Zs(v)(r)),this._trans("readwrite",function(_){return l.core.mutate({trans:_,type:"add",keys:i!=null?[i]:null,values:[b]})}).then(function(_){return _.numFailures?Se.reject(_.failures[0]):_.lastResult}).then(function(_){if(v)try{ee(r,v,_)}catch{}return _})},ft.prototype.upsert=function(r,i){var l=this,f=this.schema.primKey.keyPath;return this._trans("readwrite",function(p){return l.core.get({trans:p,key:r}).then(function(v){var b=v??{};return yl(b,i),f&&ee(b,f,r),l.core.mutate({trans:p,type:"put",values:[b],keys:[r],upsert:!0,updates:{keys:[r],changeSpecs:[i]}}).then(function(_){return _.numFailures?Se.reject(_.failures[0]):!!v})})})},ft.prototype.update=function(r,i){return typeof r!="object"||d(r)?this.where(":id").equals(r).modify(i):(r=ce(r,this.schema.primKey.keyPath))===void 0?Ct(new je.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(r).modify(i)},ft.prototype.put=function(r,i){var l=this,f=this.schema.primKey,p=f.auto,v=f.keyPath,b=r;return v&&p&&(b=Zs(v)(r)),this._trans("readwrite",function(_){return l.core.mutate({trans:_,type:"put",values:[b],keys:i!=null?[i]:null})}).then(function(_){return _.numFailures?Se.reject(_.failures[0]):_.lastResult}).then(function(_){if(v)try{ee(r,v,_)}catch{}return _})},ft.prototype.delete=function(r){var i=this;return this._trans("readwrite",function(l){return i.core.mutate({trans:l,type:"delete",keys:[r]}).then(function(f){return eo(i,[r],f)}).then(function(f){return f.numFailures?Se.reject(f.failures[0]):void 0})})},ft.prototype.clear=function(){var r=this;return this._trans("readwrite",function(i){return r.core.mutate({trans:i,type:"deleteRange",range:dl}).then(function(l){return eo(r,null,l)})}).then(function(i){return i.numFailures?Se.reject(i.failures[0]):void 0})},ft.prototype.bulkGet=function(r){var i=this;return this._trans("readonly",function(l){return i.core.getMany({keys:r,trans:l}).then(function(f){return f.map(function(p){return i.hook.reading.fire(p)})})})},ft.prototype.bulkAdd=function(r,i,l){var f=this,p=Array.isArray(i)?i:void 0,v=(l=l||(p?void 0:i))?l.allKeys:void 0;return this._trans("readwrite",function(b){var _=f.schema.primKey,V=_.auto,_=_.keyPath;if(_&&p)throw new je.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(p&&p.length!==r.length)throw new je.InvalidArgument("Arguments objects and keys must have the same length");var S=r.length,V=_&&V?r.map(Zs(_)):r;return f.core.mutate({trans:b,type:"add",keys:p,values:V,wantResults:v}).then(function(T){var C=T.numFailures,$=T.failures;if(C===0)return v?T.results:T.lastResult;throw new ht("".concat(f.name,".bulkAdd(): ").concat(C," of ").concat(S," operations failed"),$)})})},ft.prototype.bulkPut=function(r,i,l){var f=this,p=Array.isArray(i)?i:void 0,v=(l=l||(p?void 0:i))?l.allKeys:void 0;return this._trans("readwrite",function(b){var _=f.schema.primKey,V=_.auto,_=_.keyPath;if(_&&p)throw new je.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(p&&p.length!==r.length)throw new je.InvalidArgument("Arguments objects and keys must have the same length");var S=r.length,V=_&&V?r.map(Zs(_)):r;return f.core.mutate({trans:b,type:"put",keys:p,values:V,wantResults:v}).then(function(T){var C=T.numFailures,$=T.failures;if(C===0)return v?T.results:T.lastResult;throw new ht("".concat(f.name,".bulkPut(): ").concat(C," of ").concat(S," operations failed"),$)})})},ft.prototype.bulkUpdate=function(r){var i=this,l=this.core,f=r.map(function(b){return b.key}),p=r.map(function(b){return b.changes}),v=[];return this._trans("readwrite",function(b){return l.getMany({trans:b,keys:f,cache:"clone"}).then(function(_){var S=[],V=[],T=(r.forEach(function(C,$){var R=C.key,I=C.changes,M=_[$];if(M){for(var j=0,z=Object.keys(I);jB+te&&j(B+V)})})}var z=Fr(l)&&l.limit===1/0&&(typeof r!="function"||I)&&{index:l.index,range:l.range};return j(0).then(function(){if(0{for(var Be=Math.min(me.length,Te.length),Ge=-1,Ze=0;Ze=$})).length===0?Se.resolve():(j.forEach(function(B){M.push(function(){var te,pe,ve,_e=z,me=B._cfg.dbschema,Pe=(uo(C,_e,I),uo(C,me,I),z=C._dbSchema=me,Mi(_e,me)),be=(Pe.add.forEach(function(Te){Ii(I,Te[0],Te[1].primKey,Te[1].indexes)}),Pe.change.forEach(function(Te){if(Te.recreate)throw new je.Upgrade("Not yet support for changing primary key");var he=I.objectStore(Te.name);Te.add.forEach(function(Ve){return ao(he,Ve)}),Te.change.forEach(function(Ve){he.deleteIndex(Ve.name),ao(he,Ve)}),Te.del.forEach(function(Ve){return he.deleteIndex(Ve)})}),B._cfg.contentUpgrade);if(be&&B._cfg.version>$)return oo(C,I),R._memoizedTables={},te=A(me),Pe.del.forEach(function(Te){te[Te]=_e[Te]}),Oi(C,[C.Transaction.prototype]),io(C,[C.Transaction.prototype],c(te),te),R.schema=te,(pe=fe(be))&&Kr(),me=Se.follow(function(){var Te;(ve=be(R))&&pe&&(Te=zn.bind(null,null),ve.then(Te,Te))}),ve&&typeof ve.then=="function"?Se.resolve(ve):me.then(function(){return ve})}),M.push(function(te){var pe,ve,_e=B._cfg.dbschema;pe=_e,ve=te,[].slice.call(ve.db.objectStoreNames).forEach(function(me){return pe[me]==null&&ve.db.deleteObjectStore(me)}),Oi(C,[C.Transaction.prototype]),io(C,[C.Transaction.prototype],C._storeNames,C._dbSchema),R.schema=C._dbSchema}),M.push(function(te){C.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(C.idbdb.version/10)===B._cfg.version?(C.idbdb.deleteObjectStore("$meta"),delete C._dbSchema.$meta,C._storeNames=C._storeNames.filter(function(pe){return pe!=="$meta"})):te.objectStore("$meta").put(B._cfg.version,"version"))})}),function B(){return M.length?Se.resolve(M.shift()(R.idbtrans)).then(B):Se.resolve()}().then(function(){El(z,I)}))}).catch(b);var S,V;c(p).forEach(function(T){Ii(l,T,p[T].primKey,p[T].indexes)}),oo(r,l),Se.follow(function(){return r.on.populate.fire(v)}).catch(b)})}function Vf(r,i){El(r._dbSchema,i),i.db.version%10!=0||i.objectStoreNames.contains("$meta")||i.db.createObjectStore("$meta").add(Math.ceil(i.db.version/10-1),"version");var l=lo(0,r.idbdb,i);uo(r,r._dbSchema,i);for(var f=0,p=Mi(l,r._dbSchema).change;f{if(b.change.length||b.recreate)return console.warn("Unable to patch indexes of table ".concat(b.name," because it has changes on the type of index or primary key.")),{value:void 0};var _=i.objectStore(b.name);b.add.forEach(function(S){U&&console.debug("Dexie upgrade patch: Creating missing index ".concat(b.name,".").concat(S.src)),ao(_,S)})})(p[f]);if(typeof v=="object")return v.value}}function Mi(r,i){var l,f={del:[],add:[],change:[]};for(l in r)i[l]||f.del.push(l);for(l in i){var p=r[l],v=i[l];if(p){var b={name:l,def:v,recreate:!1,del:[],add:[],change:[]};if(""+(p.primKey.keyPath||"")!=""+(v.primKey.keyPath||"")||p.primKey.auto!==v.primKey.auto)b.recreate=!0,f.change.push(b);else{var _=p.idxByName,S=v.idxByName,V=void 0;for(V in _)S[V]||b.del.push(V);for(V in S){var T=_[V],C=S[V];T?T.src!==C.src&&b.change.push(C):b.add.push(C)}(0{var r,i,l;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(r=new Set,i=new FinalizationRegistry(function(f){r.delete(f)}),{toArray:function(){return Array.from(r).map(function(f){return f.deref()}).filter(function(f){return f!==void 0})},add:function(f){var p=new WeakRef(f._novip);r.add(p),i.register(f._novip,p,p),r.size>f._options.maxConnections&&(p=r.values().next().value,r.delete(p),i.unregister(p))},remove:function(f){if(f)for(var p=r.values(),v=p.next();!v.done;){var b=v.value;if(b.deref()===f._novip)return r.delete(b),void i.unregister(b);v=p.next()}}}):(l=[],{toArray:function(){return l},add:function(f){l.push(f._novip)},remove:function(f){f&&(f=l.indexOf(f._novip))!==-1&&l.splice(f,1)}})})();function ji(r,i){var l=r._dbNamesDB;return l||(l=r._dbNamesDB=new Mn(Qs,{addons:[],indexedDB:r,IDBKeyRange:i})).version(1).stores({dbnames:"name"}),l.table("dbnames")}function Di(r){return r&&typeof r.databases=="function"}function Ri(r){return Wn(function(){return Ie.letThrough=!0,r()})}function Li(r){return!("from"in r)}var Dt=function(r,i){var l;if(!this)return l=new Dt,r&&"d"in r&&h(l,r),l;h(this,arguments.length?{d:1,from:r,to:1Math.pow(2,62)?0:j.oldVersion,C=z<1,r.idbdb=M.result,v&&Vf(r,T),Nf(r,z/10,T,R))},R),M.onsuccess=mt(function(){T=null;var j,z,B,te,pe,ve,_e=r.idbdb=M.result,me=E(_e.objectStoreNames);if(0"u"?Se.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function($){function R(){return indexedDB.databases().finally($)}S=setInterval(R,100),R()}).finally(function(){return clearInterval(S)}):Promise.resolve()).then(_)]).then(function(){return b(),i.onReadyBeingFired=[],Se.resolve(Ri(function(){return r.on.ready.fire(r.vip)})).then(function $(){var R;if(0i.limit?f.length=i.limit:r.length===i.limit&&f.length{if(l===void 0)return f!==void 0?-1:0;if(f===void 0)return 1;if((l=tt(l,f))===0){if(p&&v)return 0;if(p)return 1;if(v)return-1}return l})(r.lower,i.lower,r.lowerOpen,i.lowerOpen)<=0&&0<=((l,f,p,v)=>{if(l===void 0)return f!==void 0?1:0;if(f===void 0)return-1;if((l=tt(l,f))===0){if(p&&v)return 0;if(p)return-1;if(v)return 1}return l})(r.upper,i.upper,r.upperOpen,i.upperOpen)}function Yf(r,i,l,f){r.subscribers.add(l),f.addEventListener("abort",function(){var p,v;r.subscribers.delete(l),r.subscribers.size===0&&(p=r,v=i,setTimeout(function(){p.subscribers.size===0&&ge(v,p)},3e3))})}var Jf={stack:"dbcore",level:0,name:"Cache",create:function(r){var i=r.schema.name;return s(s({},r),{transaction:function(l,f,p){var v,b,_=r.transaction(l,f,p);return f==="readwrite"&&(p=(v=new AbortController).signal,_.addEventListener("abort",(b=function(S){return function(){if(v.abort(),f==="readwrite"){for(var V=new Set,T=0,C=l;T{var z=gr["idb://".concat(R,"/").concat(I)];if(!z)return[];if(!(R=z.queries[M]))return[null,!1,z,null];var B=R[(j.query?j.query.index.name:null)||""];if(!B)return[null,!1,z,null];switch(M){case"query":var te=(pe=j.direction)!=null?pe:"next",pe=B.find(function(ve){var _e;return ve.req.limit===j.limit&&ve.req.values===j.values&&((_e=ve.req.direction)!=null?_e:"next")===te&&Ll(ve.req.query.range,j.query.range)});return pe?[pe,!0,z,B]:[B.find(function(ve){var _e;return("limit"in ve.req?ve.req.limit:1/0)>=j.limit&&((_e=ve.req.direction)!=null?_e:"next")===te&&(!j.values||ve.req.values)&&Gf(ve.req.query.range,j.query.range)}),!1,z,B];case"count":return pe=B.find(function(ve){return Ll(ve.req.query.range,j.query.range)}),[pe,!!pe,z,B]}})(i,l,"query",v),$=C[0],V=C[2],T=C[3],$&&C[1]?$.obsSet=v.obsSet:(C=f.query(v).then(function(R){var I=R.result;if($&&($.res=I),b){for(var M=0,j=I.length;M{var pe=Rr();try{v&&Kr();var ve=Wn(r,te);return ve=v?ve.finally(zn):ve}finally{pe&&Lr()}})(z={subscr:j,signal:b.signal,requery:$,querier:r,trans:null}),C||(Jn.storagemutated.subscribe(I),C=!0),Promise.resolve(B).then(function(te){l=!0,i=te,_||z.signal.aborted||(R()||(V=j,R())?$():(S={},ki(function(){return!_&&p.next&&p.next(te)})))},function(te){l=!1,["DatabaseClosedError","AbortError"].includes(te==null?void 0:te.name)||_||ki(function(){_||p.error&&p.error(te)})}))};return setTimeout($,0),T});return f.hasValue=function(){return l},f.getValue=function(){return i},f}var br=Mn;function zi(r){var i=Xn;try{Xn=!0,Jn.storagemutated.fire(r),Vi(r,!0)}finally{Xn=i}}D(br,s(s({},G),{delete:function(r){return new br(r,{addons:[]}).delete()},exists:function(r){return new br(r,{addons:[]}).open().then(function(i){return i.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(r){try{return i=br.dependencies,l=i.indexedDB,i=i.IDBKeyRange,(Di(l)?Promise.resolve(l.databases()).then(function(f){return f.map(function(p){return p.name}).filter(function(p){return p!==Qs})}):ji(l,i).toCollection().primaryKeys()).then(r)}catch{return Ct(new je.MissingAPI)}var i,l},defineClass:function(){return function(r){h(this,r)}},ignoreTransaction:function(r){return Ie.trans?vr(Ie.transless||$t,r):r()},vip:Ri,async:function(r){return function(){try{var i=Bi(r.apply(this,arguments));return i&&typeof i.then=="function"?i:Se.resolve(i)}catch(l){return Ct(l)}}},spawn:function(r,i,l){try{var f=Bi(r.apply(l,i||[]));return f&&typeof f.then=="function"?f:Se.resolve(f)}catch(p){return Ct(p)}},currentTransaction:{get:function(){return Ie.trans||null}},waitFor:function(r,i){return r=Se.resolve(typeof r=="function"?br.ignoreTransaction(r):r).timeout(i||6e4),Ie.trans?Ie.trans.waitFor(r):r},Promise:Se,debug:{get:function(){return U},set:function(r){Y(r)}},derive:W,extend:h,props:D,override:L,Events:os,on:Jn,liveQuery:Kl,extendObservabilitySet:fo,getByKeyPath:ce,setByKeyPath:ee,delByKeyPath:function(r,i){typeof i=="string"?ee(r,i,void 0):"length"in i&&[].map.call(i,function(l){ee(r,l,void 0)})},shallowClone:A,deepClone:xe,getObjectDiff:Ui,cmp:tt,asap:le,minKey:-1/0,addons:[],connections:{get:cs.toArray},errnames:Yt,dependencies:mo,cache:gr,semVer:"4.4.6",version:"4.4.6".split(".").map(function(r){return parseInt(r)}).reduce(function(r,i,l){return r+i/Math.pow(10,2*l)})})),br.maxKey=ls(br.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Jn(so,function(r){Xn||(r=new CustomEvent($i,{detail:r}),Xn=!0,dispatchEvent(r),Xn=!1)}),addEventListener($i,function(r){r=r.detail,Xn||zi(r)}));var Ur,Xn=!1,Fl=function(){};return typeof BroadcastChannel<"u"&&((Fl=function(){(Ur=new BroadcastChannel($i)).onmessage=function(r){return r.data&&zi(r.data)}})(),typeof Ur.unref=="function"&&Ur.unref(),Jn(so,function(r){Xn||Ur.postMessage(r)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(r){if(!Mn.disableBfCache&&r.persisted){U&&console.debug("Dexie: handling persisted pagehide"),Ur!=null&&Ur.close();for(var i=0,l=cs.toArray();in.key===e);return t?t.label:"其他"}const Yh={class:"dialog",role:"dialog","aria-label":"编辑工作记录"},Jh={class:"dialog-head"},Xh={key:0,class:"muted dialog-sub"},Qh={class:"dialog-body"},Zh={class:"form-grid"},ev={class:"field span2"},tv={key:0,class:"form-error"},nv={class:"field"},rv=["value"],sv={class:"field"},ov=["value"],iv={class:"field"},av={class:"field"},lv={class:"field span2"},uv={class:"field"},cv={class:"field"},fv={class:"dialog-btns"},dv=Vt({__name:"EditLogDialog",props:{open:{type:Boolean},item:{},projects:{},date:{}},emits:["cancel","save"],setup(e,{emit:t}){const n=e,s=t,o=N(""),a=N(null),c=N("dev"),d=N(null),h=N(""),y=N(""),m=N(0),k=N(0),D=N(""),O=N(null),K=it(()=>{var L;const Z=n.projects.filter(Q=>Q.archived!==1),E=(L=n.item)==null?void 0:L.project_id;if(E&&!Z.some(Q=>Q.id===E)){const Q=n.projects.find(ce=>ce.id===E),le=Z.slice();return Q&&le.unshift({...Q,name:Q.name+"(已归档)"}),le}return Z});function W(Z){n.open&&Z.key==="Escape"&&s("cancel")}gt(()=>n.open,async Z=>{var E;if(Z){const L=n.item;o.value=(L==null?void 0:L.content)??"",a.value=(L==null?void 0:L.project_id)??null,c.value=(L==null?void 0:L.category)??"dev",d.value=(L==null?void 0:L.minutes)??null,h.value=(L==null?void 0:L.takeaway)??"",y.value=(L==null?void 0:L.remark)??"",m.value=(L==null?void 0:L.is_milestone)??0,k.value=(L==null?void 0:L.needs_followup)??0,D.value="",window.addEventListener("keydown",W),await ts(),(E=O.value)==null||E.focus()}else window.removeEventListener("keydown",W)}),dr(()=>window.removeEventListener("keydown",W)),gt(o,()=>{D.value&&(D.value="")});function de(){const Z=o.value.trim();if(!Z){D.value="请填写工作内容";return}if(!n.item||!n.item.id){s("cancel");return}s("save",{id:n.item.id,content:Z,project_id:a.value,category:c.value,minutes:d.value&&d.value>0?d.value:null,takeaway:h.value.trim()||null,remark:y.value.trim()||null,is_milestone:m.value?1:0,needs_followup:k.value?1:0})}return(Z,E)=>(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:E[10]||(E[10]=Mr(L=>s("cancel"),["self"]))},[u("div",Yh,[u("div",Jh,[u("div",null,[E[11]||(E[11]=u("div",{class:"dialog-title"},"编辑工作记录",-1)),e.date?(F(),q("div",Xh,re(e.date),1)):Ee("",!0)]),u("button",{class:"icon-btn",title:"关闭",onClick:E[0]||(E[0]=L=>s("cancel"))},[Oe(lt,{name:"close",size:16})])]),u("div",Qh,[u("div",Zh,[u("div",ev,[E[12]||(E[12]=u("label",null,"工作内容(必填)",-1)),$e(u("input",{ref_key:"contentInput",ref:O,class:et(["input",{invalid:D.value}]),"onUpdate:modelValue":E[1]||(E[1]=L=>o.value=L),onKeydown:jt(de,["enter"])},null,34),[[De,o.value]]),D.value?(F(),q("div",tv,re(D.value),1)):Ee("",!0)]),u("div",nv,[E[14]||(E[14]=u("label",null,"所属项目",-1)),$e(u("select",{class:"select","onUpdate:modelValue":E[2]||(E[2]=L=>a.value=L)},[E[13]||(E[13]=u("option",{value:null},"无项目",-1)),(F(!0),q(Re,null,ut(K.value,L=>(F(),q("option",{key:L.id,value:L.id},re(L.name),9,rv))),128))],512),[[Fn,a.value]])]),u("div",sv,[E[15]||(E[15]=u("label",null,"工作分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":E[3]||(E[3]=L=>c.value=L)},[(F(!0),q(Re,null,ut(Qt(Us),L=>(F(),q("option",{key:L.key,value:L.key},re(L.label),9,ov))),128))],512),[[Fn,c.value]])]),u("div",iv,[E[16]||(E[16]=u("label",null,"耗时(分钟)",-1)),$e(u("input",{class:"input",type:"number",min:"0","onUpdate:modelValue":E[4]||(E[4]=L=>d.value=L),placeholder:"选填"},null,512),[[De,d.value,void 0,{number:!0}]])]),u("div",av,[E[17]||(E[17]=u("label",null,"主要收获",-1)),$e(u("input",{class:"input","onUpdate:modelValue":E[5]||(E[5]=L=>h.value=L),placeholder:"一句话:学到了什么"},null,512),[[De,h.value]])]),u("div",lv,[E[18]||(E[18]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":E[6]||(E[6]=L=>y.value=L),placeholder:"背景、链接、未决事项(选填)"},null,512),[[De,y.value]])]),u("div",uv,[E[19]||(E[19]=u("label",null,"成果标记",-1)),u("button",{class:et(["toggle-btn",{on:m.value===1}]),onClick:E[7]||(E[7]=L=>m.value=m.value===1?0:1)},re(m.value===1?"已标记为成果":"未标记"),3)]),u("div",cv,[E[20]||(E[20]=u("label",null,"待跟进",-1)),u("button",{class:et(["toggle-btn",{onwarn:k.value===1}]),onClick:E[8]||(E[8]=L=>k.value=k.value===1?0:1)},re(k.value===1?"需要跟进":"无需跟进"),3)])])]),u("div",fv,[u("button",{class:"btn btn-sm",onClick:E[9]||(E[9]=L=>s("cancel"))},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:de},"保存修改")])])])):Ee("",!0)]),_:1})]))}}),pv=Gt(dv,[["__scopeId","data-v-63bc0b48"]]);function Ss(e){return e<10?"0"+e:String(e)}function Nn(e){return e.getFullYear()+"-"+Ss(e.getMonth()+1)+"-"+Ss(e.getDate())}function xt(){return Nn(new Date)}function wt(){const e=new Date;return Nn(e)+"T"+Ss(e.getHours())+":"+Ss(e.getMinutes())+":"+Ss(e.getSeconds())}function Vn(e){if(!e)return"--:--";const t=e.indexOf("T");return t>=0?e.slice(t+1,t+6):e.slice(0,5)}function rs(e){const t=e.split("-").map(Number);return new Date(t[0],t[1]-1,t[2])}function Kn(e,t){const n=rs(e);return n.setDate(n.getDate()+t),Nn(n)}function Uo(e,t){const n=rs(e),s=n.getDate();n.setDate(1),n.setMonth(n.getMonth()+t);const o=new Date(n.getFullYear(),n.getMonth()+1,0).getDate();return n.setDate(Math.min(s,o)),Nn(n)}function Es(e){const t=rs(e),n=(t.getDay()+6)%7;return t.setDate(t.getDate()-n),Nn(t)}function hv(e){const t=rs(e).getDay();return t===0||t===6}function vv(e,t){return Math.round((new Date(t).getTime()-new Date(e).getTime())/6e4)}function of(e){const t=rs(e),n=["周日","周一","周二","周三","周四","周五","周六"];return t.getFullYear()+" 年 "+(t.getMonth()+1)+" 月 "+t.getDate()+" 日 "+n[t.getDay()]}async function yt(e,t){const n=await ne.setting.get(e);return n?n.value:t}async function kt(e,t){await ne.setting.put({key:e,value:t})}async function jr(){const e=await Promise.all([yt("work_start","09:00"),yt("work_end","18:00"),yt("grace_minutes","10"),yt("lunch_minutes","60"),yt("remind_weekly","friday")]);return{work_start:e[0],work_end:e[1],grace_minutes:Number(e[2])||0,lunch_minutes:Number(e[3])||0,remind_weekly:e[4]}}async function mv(){const e=await yt("last_project",""),t=await yt("last_category","dev");return{project_id:e?Number(e):null,category:t||"dev"}}async function yv(){return yt("last_location","")}async function gv(e,t){const n=t.trim();await kt("last_location",n),n&&await qo(n);const s=await mn(e);s&&s.id?await ne.attendance.update(s.id,{location:n||null}):n&&await ne.attendance.add({date:e,clock_in_at:null,clock_out_at:null,kind:"normal",note:null,location:n,created_at:wt()})}async function Za(){const e=await yt("location_presets","");if(!e)return Pu.slice();try{const t=JSON.parse(e);if(Array.isArray(t))return t.filter(n=>typeof n=="string"&&n.trim()).map(n=>n.trim())}catch{}return Pu.slice()}async function af(e){const t=Array.from(new Set(e.map(n=>n.trim()).filter(Boolean)));await kt("location_presets",JSON.stringify(t))}async function qo(e){const t=e.trim();if(!t)return;const n=await Za();n.includes(t)||await af([...n,t])}async function Ks(e=!1){const t=await ne.project.orderBy("name").toArray();return e?t:t.filter(n=>n.archived!==1)}async function bv(e){await ne.project.add({name:e.trim(),archived:0,created_at:wt()})}async function wv(e,t){await ne.project.update(e,{name:t.trim()})}async function _v(e,t){await ne.project.update(e,{archived:t?1:0})}async function mn(e){return ne.attendance.where("date").equals(e).first()}async function lf(e,t){const n=((t===void 0?await yt("last_location",""):t)||"").trim(),s=await mn(e);if(s&&s.id){if(!s.clock_in_at){const o={clock_in_at:wt()};n&&(o.location=n),await ne.attendance.update(s.id,o)}n&&(await kt("last_location",n),await qo(n));return}await ne.attendance.add({date:e,clock_in_at:wt(),clock_out_at:null,kind:"normal",note:null,location:n||null,created_at:wt()}),n&&(await kt("last_location",n),await qo(n))}async function kv(e){const t=await mn(e);t&&t.id&&t.clock_in_at&&!t.clock_out_at&&await ne.attendance.update(t.id,{clock_out_at:wt()})}async function xv(){const e=new Date,t=Nn(e);if(e.getHours()<4){const s=await mn(Kn(t,-1));if(s&&s.id&&s.clock_in_at&&!s.clock_out_at)return await ne.attendance.update(s.id,{clock_out_at:wt()}),s.date}const n=await mn(t);if(n&&n.id&&n.clock_in_at&&!n.clock_out_at)return await ne.attendance.update(n.id,{clock_out_at:wt()}),n.date;throw new Error("没有进行中的打卡")}async function Cv(e,t,n,s,o){(o||"").trim()&&await qo(o);const a=await mn(e),c={date:e,clock_in_at:t,clock_out_at:n,kind:"makeup",note:s||null,location:(o||"").trim()||null,created_at:wt()};a&&a.id?await ne.attendance.update(a.id,c):await ne.attendance.add(c)}async function Sv(e,t,n){const s=(n||"").trim();if(!s)return;const o=await mn(e);o&&o.id&&await ne.attendance.update(o.id,{[t]:e+"T"+s+":00"})}async function di(e,t){return ne.attendance.where("date").between(e,t,!0,!0).toArray()}async function Ev(e,t){const n=await mn(e);if(t){const s={date:e,kind:"leave",clock_in_at:null,clock_out_at:null,created_at:wt()};n&&n.id?await ne.attendance.update(n.id,s):await ne.attendance.add({...s,note:null,location:null})}else n&&n.id&&await ne.attendance.update(n.id,{kind:"normal"})}async function $v(e){const t=await ne.work_log.where("date").equals(e).first();return t||{id:await ne.work_log.add({date:e,created_at:wt()}),date:e,created_at:wt()}}async function Av(e){return ne.work_log.where("date").equals(e).first()}async function Pv(e){const t=await Av(e);return!t||!t.id?[]:(await ne.log_item.where("work_log_id").equals(t.id).toArray()).sort((s,o)=>o.id-s.id)}async function Tv(e,t){const n=await $v(e);await ne.log_item.add({work_log_id:n.id,content:t.content,project_id:t.project_id,category:t.category,minutes:t.minutes,is_milestone:0,needs_followup:0,takeaway:t.takeaway,remark:t.remark,sort_order:0,created_at:wt()}),await kt("last_project",t.project_id?String(t.project_id):""),await kt("last_category",t.category)}async function la(e,t){await ne.log_item.update(e,t)}async function Ov(e){await ne.log_item.delete(e)}async function pi(e,t){const n=await ne.work_log.where("date").between(e,t,!0,!0).toArray();if(!n.length)return[];const s=new Map(n.map(a=>[a.id,a.date]));return(await ne.log_item.where("work_log_id").anyOf(n.map(a=>a.id)).toArray()).map(a=>({...a,date:s.get(a.work_log_id)||""})).sort((a,c)=>a.date===c.date?a.id-c.id:a.datet.updated_at[c.id,c.date]));return(await ne.log_item.toArray()).filter(c=>((c.content||"")+" "+(c.takeaway||"")+" "+(c.remark||"")).toLowerCase().includes(n)).sort((c,d)=>d.id-c.id).slice(0,t).map(c=>({...c,date:o.get(c.work_log_id)||""}))}async function Fv(e,t=4){const n=e.trim().toLowerCase();return n?(await ne.memo.toArray()).filter(o=>((o.title||"")+" "+(o.content||"")).toLowerCase().includes(n)).sort((o,a)=>o.updated_at{await Promise.all([ne.project.clear(),ne.work_log.clear(),ne.log_item.clear(),ne.attendance.clear(),ne.weekly_note.clear(),ne.setting.clear(),ne.memo.clear(),ne.credential.clear(),ne.table("transaction").clear()]),n.project&&n.project.length&&await ne.project.bulkAdd(n.project),n.work_log&&n.work_log.length&&await ne.work_log.bulkAdd(n.work_log),n.log_item&&n.log_item.length&&await ne.log_item.bulkAdd(n.log_item),n.attendance&&n.attendance.length&&await ne.attendance.bulkAdd(n.attendance),n.weekly_note&&n.weekly_note.length&&await ne.weekly_note.bulkAdd(n.weekly_note),n.setting&&n.setting.length&&await ne.setting.bulkAdd(n.setting),n.memo&&n.memo.length&&await ne.memo.bulkAdd(n.memo),n.credential&&n.credential.length&&await ne.credential.bulkAdd(n.credential),n.transaction&&n.transaction.length&&await ne.table("transaction").bulkAdd(n.transaction)})}function Co(e){const t=e.split(":");return Number(t[0])*60+Number(t[1])}function qs(e,t,n,s){if(e&&e.kind==="leave")return{status:"leave",label:"请假",makeup:!1,workedMinutes:null};if(hv(t))return{status:"rest",label:"休息日",makeup:!1,workedMinutes:null};if(!e||!e.clock_in_at)return s?{status:"none",label:"未打卡",makeup:!1,workedMinutes:null}:{status:"absent",label:"缺勤",makeup:!!(e&&e.kind==="makeup"),workedMinutes:null};const o=e.kind==="makeup";if(!e.clock_out_at)return{status:"incomplete",label:s?"进行中":"未完成",makeup:o,workedMinutes:null};const a=Co(Vn(e.clock_in_at)),c=Co(Vn(e.clock_out_at)),d=Co(n.work_start),h=Co(n.work_end);let y="normal";!o&&a>d+n.grace_minutes?y="late":!o&&c{Po.value=Po.value.filter(n=>n.id!==t)},2e3)}function Gv(){return Po}const $a=N(null),Aa=N(null),Hs=N(0);function Sr(){Hs.value++}const Yv={class:"day-panel"},Jv={class:"dp-head"},Xv={class:"dp-date"},Qv={class:"card sec"},Zv={class:"att-grid"},em={class:"att-cell"},tm={key:0,class:"edit-row"},nm={key:1,class:"att-val"},rm={class:"att-cell"},sm={key:0,class:"edit-row"},om={key:1,class:"att-val"},im={class:"att-cell"},am=["list"],lm=["id"],um=["value"],cm={class:"att-cell"},fm={class:"att-val status-val"},dm={key:0,class:"tag"},pm={key:1,class:"muted"},hm={key:0,class:"att-note muted"},vm={class:"att-actions"},mm=["disabled"],ym=["disabled"],gm=["disabled"],bm=["disabled"],wm={key:0,class:"card sec makeup"},_m={class:"form-grid"},km={class:"field"},xm={class:"field"},Cm={class:"field span2"},Sm=["list"],Em={class:"field span2"},$m={key:0,class:"form-error"},Am={class:"form-footer"},Pm={class:"card sec"},Tm={class:"form-grid"},Om={class:"field span2"},Mm={key:0,class:"form-error"},Im={class:"field"},jm=["value"],Dm={class:"field"},Rm=["value"],Lm={class:"field"},Km={class:"field"},Fm={class:"field span2"},Nm={class:"form-footer"},Vm=["disabled"],Bm=["disabled"],Um={class:"list-sec"},qm={class:"sec-title"},Hm={key:0,class:"empty muted"},Wm={class:"item-main"},zm={class:"tag"},Gm=["onClick"],Ym={key:0,class:"muted item-meta"},Jm={key:1,class:"muted num item-meta"},Xm=["onClick"],Qm=["onClick"],Zm=["onClick"],ey=["onClick"],ty={key:0,class:"item-sub"},ny={key:0,class:"muted2"},ry={key:1,class:"muted"},sy={key:1,class:"dp-foot muted num"},oy=Vt({__name:"DayPanel",props:{date:{}},setup(e){const t=e,n=N(!0),s=N(null),o=N(void 0),a=N([]),c=N([]),d=N(""),h=N([]),y=it(()=>"loc-list-"+t.date),m=it(()=>t.date===xt());async function k(){n.value=!0,s.value=await jr(),o.value=await mn(t.date),a.value=await Pv(t.date),c.value=await Ks(!0),h.value=await Za(),d.value=o.value&&o.value.location||await yv(),n.value=!1}fn(k),gt(()=>t.date,k),gt(Hs,()=>{k()});const D=it(()=>c.value.filter(H=>H.archived!==1));function O(H){if(!H)return"";const U=c.value.find(Y=>Y.id===H);return U?U.name:"已删除项目"}const K=it(()=>s.value?qs(o.value,t.date,s.value,m.value):null),W=it(()=>a.value.reduce((H,U)=>H+(U.minutes||0),0)),de=N(!1);async function Z(){de.value||(de.value=!0,await lf(t.date,d.value),await k(),Sr(),qe("上班打卡成功"),de.value=!1)}async function E(){de.value||(de.value=!0,await kv(t.date),await k(),Sr(),qe("下班打卡成功"),de.value=!1)}async function L(){await gv(t.date,d.value),Sr(),qe("地点已更新")}const Q=N(!1),le=it(()=>{var H;return((H=o.value)==null?void 0:H.kind)==="leave"});function ce(){if(o.value&&o.value.clock_in_at){Q.value=!0;return}ee(!0)}async function ee(H){Q.value=!1,await Ev(t.date,H),await k(),Sr(),qe(H?"已标记为休假":"已取消休假")}const A=N(null),x=N(""),ie=N(null);gt(A,async H=>{var U;H&&(await ts(),(U=ie.value)==null||U.focus())});function Ce(H){var Y,Ae;const U=H==="in"?(Y=o.value)==null?void 0:Y.clock_in_at:(Ae=o.value)==null?void 0:Ae.clock_out_at;A.value=H,x.value=U?Vn(U):H==="in"?"09:00":"18:00"}function J(){A.value=null}async function xe(){const H=A.value;H&&(A.value=null,x.value&&(await Sv(t.date,H==="in"?"clock_in_at":"clock_out_at",x.value),await k(),Sr(),qe("打卡时间已修改")))}const Ne=N(!1),Xe=N("09:00"),He=N("18:00"),Ue=N(""),ge=N(""),Me=N("");function Ke(){ge.value=d.value,Me.value="",Ne.value=!Ne.value}async function fe(){if(!Xe.value||!He.value){Me.value="请填写上班与下班时间";return}await Cv(t.date,t.date+"T"+Xe.value+":00",t.date+"T"+He.value+":00",Ue.value.trim(),ge.value),Ne.value=!1,Ue.value="",Me.value="",await k(),Sr(),qe("补卡已保存")}const G=N(""),X=N("");gt(G,()=>{X.value&&(X.value="")});const ke=N(null),st=N("dev"),pt=N(null),ht=N(""),Yt=N(""),Jt=N(!1),je=it(()=>!!(G.value.trim()||pt.value||ht.value.trim()||Yt.value.trim()));fn(async()=>{const H=await mv();ke.value=H.project_id,st.value=H.category});function w(){G.value="",pt.value=null,ht.value="",Yt.value="",X.value=""}async function g(){const H=G.value.trim();if(!H){X.value="请填写工作内容";return}Jt.value||(Jt.value=!0,await Tv(t.date,{content:H,project_id:ke.value,category:st.value,minutes:pt.value&&pt.value>0?pt.value:null,takeaway:ht.value.trim()||null,remark:Yt.value.trim()||null}),w(),await k(),qe("记录已添加"),Jt.value=!1)}const P=N(null);function ae(H){P.value=H}async function se(H){const U=H.id,Y={content:H.content,project_id:H.project_id,category:H.category,minutes:H.minutes,takeaway:H.takeaway,remark:H.remark,is_milestone:H.is_milestone,needs_followup:H.needs_followup};await la(U,Y),P.value=null,await k(),qe("修改已保存")}async function ue(H){await la(H.id,{is_milestone:H.is_milestone?0:1}),await k()}async function ye(H){await la(H.id,{needs_followup:H.needs_followup?0:1}),await k()}const oe=N(null);async function we(){oe.value&&oe.value.id&&await Ov(oe.value.id),oe.value=null,await k(),qe("记录已删除")}return(H,U)=>(F(),q("div",Yv,[u("div",Jv,[u("div",Xv,re(Qt(of)(e.date)),1)]),u("div",Qv,[U[25]||(U[25]=u("div",{class:"sec-title"},"出勤信息",-1)),u("div",Zv,[u("div",em,[U[21]||(U[21]=u("label",null,"上班时间",-1)),A.value==="in"?(F(),q("div",tm,[$e(u("input",{ref_key:"timeInput",ref:ie,type:"time",class:"input time-input","onUpdate:modelValue":U[0]||(U[0]=Y=>x.value=Y),onKeydown:[jt(xe,["enter"]),jt(J,["esc"])]},null,544),[[De,x.value]]),u("button",{class:"btn btn-primary btn-sm",onClick:xe},"确认"),u("button",{class:"btn btn-sm",onClick:J},"取消")])):(F(),q("div",nm,[u("span",{class:et(["num",{"val-empty":!(o.value&&o.value.clock_in_at)}])},re(o.value&&o.value.clock_in_at?Qt(Vn)(o.value.clock_in_at):"未打卡"),3),o.value&&o.value.id?(F(),q("button",{key:0,class:"icon-btn",title:"修改上班时间",onClick:U[1]||(U[1]=Y=>Ce("in"))},[Oe(lt,{name:"edit",size:13})])):Ee("",!0)]))]),u("div",rm,[U[22]||(U[22]=u("label",null,"下班时间",-1)),A.value==="out"?(F(),q("div",sm,[$e(u("input",{ref_key:"timeInput",ref:ie,type:"time",class:"input time-input","onUpdate:modelValue":U[2]||(U[2]=Y=>x.value=Y),onKeydown:[jt(xe,["enter"]),jt(J,["esc"])]},null,544),[[De,x.value]]),u("button",{class:"btn btn-primary btn-sm",onClick:xe},"确认"),u("button",{class:"btn btn-sm",onClick:J},"取消")])):(F(),q("div",om,[u("span",{class:et(["num",{"val-empty":!(o.value&&o.value.clock_out_at)}])},re(o.value&&o.value.clock_out_at?Qt(Vn)(o.value.clock_out_at):"未打卡"),3),o.value&&o.value.id?(F(),q("button",{key:0,class:"icon-btn",title:"修改下班时间",onClick:U[3]||(U[3]=Y=>Ce("out"))},[Oe(lt,{name:"edit",size:13})])):Ee("",!0)]))]),u("div",im,[U[23]||(U[23]=u("label",null,"上班地点",-1)),$e(u("input",{class:"input","onUpdate:modelValue":U[4]||(U[4]=Y=>d.value=Y),list:y.value,placeholder:"可直接输入",title:"上班地点,可自由输入",onChange:L},null,40,am),[[De,d.value]]),u("datalist",{id:y.value},[(F(!0),q(Re,null,ut(h.value,Y=>(F(),q("option",{key:Y,value:Y},null,8,um))),128))],8,lm)]),u("div",cm,[U[24]||(U[24]=u("label",null,"考勤状态",-1)),u("div",fm,[K.value?(F(),q(Re,{key:0},[u("span",{class:et(["dot",K.value.status])},null,2),u("span",null,re(K.value.label),1),o.value&&o.value.kind==="makeup"?(F(),q("span",dm,"补卡")):Ee("",!0)],64)):(F(),q("span",pm,"--"))])])]),o.value&&o.value.note?(F(),q("div",hm,"补卡说明:"+re(o.value.note),1)):Ee("",!0),u("div",vm,[m.value&&(!o.value||!o.value.clock_in_at)?(F(),q("button",{key:0,class:"btn btn-primary btn-sm",disabled:de.value,onClick:Z},"上班打卡",8,mm)):m.value&&o.value&&o.value.clock_in_at&&!o.value.clock_out_at?(F(),q("button",{key:1,class:"btn btn-primary btn-sm",disabled:de.value,onClick:E},"下班打卡",8,ym)):Ee("",!0),!m.value&&(!o.value||!o.value.clock_in_at)?(F(),q("button",{key:2,class:"btn btn-sm",onClick:Ke},"补卡")):Ee("",!0),le.value?(F(),q("button",{key:4,class:"btn btn-sm",disabled:de.value,onClick:U[5]||(U[5]=Y=>ee(!1))},"取消休假",8,bm)):(F(),q("button",{key:3,class:"btn btn-sm",disabled:de.value,onClick:ce},"标记休假",8,gm))])]),Ne.value?(F(),q("div",wm,[U[30]||(U[30]=u("div",{class:"sec-title"},"补卡登记",-1)),u("div",_m,[u("div",km,[U[26]||(U[26]=u("label",null,"上班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":U[6]||(U[6]=Y=>Xe.value=Y)},null,512),[[De,Xe.value]])]),u("div",xm,[U[27]||(U[27]=u("label",null,"下班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":U[7]||(U[7]=Y=>He.value=Y)},null,512),[[De,He.value]])]),u("div",Cm,[U[28]||(U[28]=u("label",null,"上班地点",-1)),$e(u("input",{class:"input",list:y.value,"onUpdate:modelValue":U[8]||(U[8]=Y=>ge.value=Y),placeholder:"可直接输入"},null,8,Sm),[[De,ge.value]])]),u("div",Em,[U[29]||(U[29]=u("label",null,"补卡原因",-1)),$e(u("input",{class:"input","onUpdate:modelValue":U[9]||(U[9]=Y=>Ue.value=Y),placeholder:"如:外出拜访客户忘记打卡"},null,512),[[De,Ue.value]])])]),Me.value?(F(),q("div",$m,re(Me.value),1)):Ee("",!0),u("div",Am,[u("button",{class:"btn btn-sm",onClick:U[10]||(U[10]=Y=>Ne.value=!1)},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:fe},"保存补卡")])])):Ee("",!0),u("div",Pm,[U[38]||(U[38]=u("div",{class:"sec-head"},[u("span",{class:"sec-title"},"新增工作记录"),u("span",{class:"muted form-hint"},"内容必填,其余选填")],-1)),u("div",Tm,[u("div",Om,[U[31]||(U[31]=u("label",null,"工作内容(必填)",-1)),$e(u("input",{class:et(["input",{invalid:X.value}]),"onUpdate:modelValue":U[11]||(U[11]=Y=>G.value=Y),placeholder:"做了什么,一句话一条",onKeydown:jt(g,["enter"])},null,34),[[De,G.value]]),X.value?(F(),q("div",Mm,re(X.value),1)):Ee("",!0)]),u("div",Im,[U[33]||(U[33]=u("label",null,"所属项目",-1)),$e(u("select",{class:"select","onUpdate:modelValue":U[12]||(U[12]=Y=>ke.value=Y)},[U[32]||(U[32]=u("option",{value:null},"无项目",-1)),(F(!0),q(Re,null,ut(D.value,Y=>(F(),q("option",{key:Y.id,value:Y.id},re(Y.name),9,jm))),128))],512),[[Fn,ke.value]])]),u("div",Dm,[U[34]||(U[34]=u("label",null,"工作分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":U[13]||(U[13]=Y=>st.value=Y)},[(F(!0),q(Re,null,ut(Qt(Us),Y=>(F(),q("option",{key:Y.key,value:Y.key},re(Y.label),9,Rm))),128))],512),[[Fn,st.value]])]),u("div",Lm,[U[35]||(U[35]=u("label",null,"耗时(分钟)",-1)),$e(u("input",{class:"input",type:"number",min:"0","onUpdate:modelValue":U[14]||(U[14]=Y=>pt.value=Y),placeholder:"选填"},null,512),[[De,pt.value,void 0,{number:!0}]])]),u("div",Km,[U[36]||(U[36]=u("label",null,"主要收获",-1)),$e(u("input",{class:"input","onUpdate:modelValue":U[15]||(U[15]=Y=>ht.value=Y),placeholder:"一句话:学到了什么"},null,512),[[De,ht.value]])]),u("div",Fm,[U[37]||(U[37]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":U[16]||(U[16]=Y=>Yt.value=Y),placeholder:"背景、链接、未决事项(选填)"},null,512),[[De,Yt.value]])])]),u("div",Nm,[u("button",{class:"btn btn-sm",disabled:!je.value,onClick:w},"重置",8,Vm),u("button",{class:"btn btn-primary btn-sm",disabled:Jt.value,onClick:g},"添加记录",8,Bm)])]),u("div",Um,[u("div",qm,"工作记录("+re(a.value.length)+")",1),!a.value.length&&!n.value?(F(),q("div",Hm,"暂无记录")):Ee("",!0),(F(!0),q(Re,null,ut(a.value,Y=>(F(),q("div",{key:Y.id,class:"item"},[u("div",Wm,[u("span",zm,re(Qt(Qa)(Y.category)),1),u("span",{class:"item-content",title:"点击编辑",onClick:Ae=>ae(Y)},re(Y.content),9,Gm),Y.project_id?(F(),q("span",Ym,re(O(Y.project_id)),1)):Ee("",!0),Y.minutes?(F(),q("span",Jm,re(Y.minutes)+" 分钟",1)):Ee("",!0),U[39]||(U[39]=u("span",{class:"flex1"},null,-1)),u("button",{class:"icon-btn",title:"编辑完整信息",onClick:Ae=>ae(Y)},[Oe(lt,{name:"edit",size:14})],8,Xm),u("button",{class:et(["icon-btn",{active:Y.is_milestone===1}]),title:"成果标记",onClick:Ae=>ue(Y)},[Oe(lt,{name:"star",size:14})],10,Qm),u("button",{class:et(["icon-btn",{"active-warn":Y.needs_followup===1}]),title:"待跟进",onClick:Ae=>ye(Y)},[Oe(lt,{name:"flag",size:14})],10,Zm),u("button",{class:"icon-btn",title:"删除",onClick:Ae=>oe.value=Y},[Oe(lt,{name:"close",size:14})],8,ey)]),Y.takeaway||Y.remark?(F(),q("div",ty,[Y.takeaway?(F(),q("div",ny,"收获:"+re(Y.takeaway),1)):Ee("",!0),Y.remark?(F(),q("div",ry,"备注:"+re(Y.remark),1)):Ee("",!0)])):Ee("",!0)]))),128)),a.value.length?(F(),q("div",sy,[nn(" 共 "+re(a.value.length)+" 条事项 ",1),W.value?(F(),q(Re,{key:0},[nn(" · "+re((W.value/60).toFixed(1))+" 小时",1)],64)):Ee("",!0)])):Ee("",!0)]),Oe(ur,{open:!!oe.value,title:"删除确认",message:oe.value?"将删除工作记录「"+oe.value.content+"」。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:U[17]||(U[17]=Y=>oe.value=null),onConfirm:we},null,8,["open","message"]),Oe(ur,{open:Q.value,title:"标记休假确认",message:"该日已有打卡记录,标记休假将清空上下班时间。是否继续?","confirm-text":"标记休假",danger:"",onCancel:U[18]||(U[18]=Y=>Q.value=!1),onConfirm:U[19]||(U[19]=Y=>ee(!0))},null,8,["open"]),Oe(pv,{open:!!P.value,item:P.value,projects:c.value,date:e.date,onCancel:U[20]||(U[20]=Y=>P.value=null),onSave:se},null,8,["open","item","projects","date"])]))}}),uf=Gt(oy,[["__scopeId","data-v-2e90c9d8"]]),iy={class:"cal-page"},ay={class:"cal-toolbar"},ly={class:"cal-title num"},uy={class:"cal-head"},cy={class:"cal-grid"},fy=["title","onClick"],dy={class:"cal-marks"},py={key:0,class:"drawer"},hy={class:"drawer-head"},vy={class:"drawer-body"},my=Vt({__name:"CalendarView",setup(e){const t=N(xt()),n=it(()=>Number(t.value.slice(0,4))),s=it(()=>Number(t.value.slice(5,7))-1),o=it(()=>n.value+" 年 "+(s.value+1)+" 月"),a=["一","二","三","四","五","六","日"],c=it(()=>{const Q=(new Date(n.value,s.value,1).getDay()+6)%7,le=new Date(n.value,s.value+1,0).getDate(),ce=[];for(let ee=0;ee[Ce.date,Ce])),A=le[2],x=new Map;for(const Ce of c.value){if(!Ce.inMonth)continue;const J=qs(ee.get(Ce.date),Ce.date,ce,Ce.date===h),xe=A.filter(Ne=>Ne.date===Ce.date);x.set(Ce.date,{status:J.status,label:J.label,location:((ie=ee.get(Ce.date))==null?void 0:ie.location)||"",hasLog:xe.length>0,hasMilestone:xe.some(Ne=>Ne.is_milestone===1)})}d.value=x}gt([n,s],y,{immediate:!0}),gt(Hs,()=>{y()});function m(L){var Q;return((Q=d.value.get(L))==null?void 0:Q.status)??""}function k(L){const Q=d.value.get(L);return Q?L+" · "+Q.label+(Q.location?" · "+Q.location:""):L}function D(L){var Q;return!!((Q=d.value.get(L))!=null&&Q.hasLog)}function O(L){var Q;return!!((Q=d.value.get(L))!=null&&Q.hasMilestone)}function K(){t.value=Uo(t.value,-1)}function W(){t.value=Uo(t.value,1)}function de(){t.value=xt()}const Z=N(null);function E(L,Q){Q&&(Z.value=L)}return gt($a,L=>{L&&(t.value=L,Z.value=L,$a.value=null)},{immediate:!0}),(L,Q)=>(F(),q("div",iy,[u("div",ay,[u("button",{class:"icon-btn",onClick:K},[Oe(lt,{name:"chevron-left",size:16})]),u("span",ly,re(o.value),1),u("button",{class:"icon-btn",onClick:W},[Oe(lt,{name:"chevron-right",size:16})]),u("button",{class:"btn btn-sm",onClick:de},"回到今天")]),u("div",uy,[(F(),q(Re,null,ut(a,le=>u("span",{key:le,class:"cal-week muted"},re(le),1)),64))]),u("div",cy,[(F(!0),q(Re,null,ut(c.value,(le,ce)=>(F(),q("button",{key:ce,class:et(["cal-cell",{blank:!le.inMonth,weekend:le.weekend,selected:Z.value===le.date}]),title:le.inMonth?k(le.date):void 0,onClick:ee=>E(le.date,le.inMonth)},[le.inMonth?(F(),q(Re,{key:0},[u("span",{class:et(["daynum num",{today:le.date===Qt(h)}])},re(Number(le.date.slice(8,10))),3),u("span",dy,[m(le.date)?(F(),q("span",{key:0,class:et(["dot",m(le.date)])},null,2)):Ee("",!0),D(le.date)?(F(),It(lt,{key:1,name:"check-circle",size:12,class:"mark-log"})):Ee("",!0),O(le.date)?(F(),It(lt,{key:2,name:"star",size:12,class:"mark-star"})):Ee("",!0)])],64)):Ee("",!0)],10,fy))),128))]),Oe(ns,{name:"drawer"},{default:fr(()=>[Z.value?(F(),q("aside",py,[u("div",hy,[Q[1]||(Q[1]=u("span",{class:"drawer-title"},"当日详情",-1)),u("button",{class:"icon-btn",onClick:Q[0]||(Q[0]=le=>Z.value=null)},[Oe(lt,{name:"close",size:16})])]),u("div",vy,[Oe(uf,{date:Z.value},null,8,["date"])])])):Ee("",!0)]),_:1})]))}}),yy=Gt(my,[["__scopeId","data-v-6a6322fa"]]),gy={class:"detail-page"},by={class:"detail-toolbar"},wy=["value"],_y=["disabled"],ky=Vt({__name:"TodayView",setup(e){const t=N(xt()),n=it(()=>t.value===xt());function s(){t.value=Kn(t.value,-1)}function o(){t.value=Kn(t.value,1)}function a(){t.value=xt()}function c(d){const h=d.target.value;h&&(t.value=h)}return(d,h)=>(F(),q("div",gy,[u("div",by,[u("button",{class:"icon-btn",title:"前一天",onClick:s},[Oe(lt,{name:"chevron-left",size:16})]),u("span",{class:et(["date-title num",{"is-today":n.value}])},re(Qt(of)(t.value)),3),u("button",{class:"icon-btn",title:"后一天",onClick:o},[Oe(lt,{name:"chevron-right",size:16})]),u("input",{type:"date",class:"input w-date",value:t.value,onChange:c},null,40,wy),u("button",{class:"btn btn-sm",disabled:n.value,onClick:a},"回到今天",8,_y)]),Oe(uf,{date:t.value},null,8,["date"])]))}}),xy=Gt(ky,[["__scopeId","data-v-ac366cf6"]]),Cy={class:"stats"},Sy={class:"cards"},Ey={class:"card stat-card"},$y={class:"stat-num num"},Ay={class:"card stat-card"},Py={class:"stat-num num"},Ty={class:"card stat-card"},Oy={class:"stat-num num"},My={class:"card stat-card"},Iy={class:"stat-num num"},jy={class:"card section"},Dy={class:"heat"},Ry=["title"],Ly={class:"two-col"},Ky={class:"card section"},Fy={class:"bar-label"},Ny={class:"bar-track"},Vy={class:"muted num bar-num"},By={key:0,class:"muted"},Uy={class:"card section"},qy={class:"bar-label"},Hy={class:"bar-track"},Wy={class:"muted num bar-num"},zy={key:0,class:"muted"},Gy={class:"card section"},Yy={class:"bar-label loc-label"},Jy={class:"bar-track"},Xy={class:"muted num bar-num"},Qy={key:0,class:"muted"},Zy=Vt({__name:"StatsView",setup(e){const t=N({attendDays:0,totalHours:"0",itemCount:0,streak:0}),n=N([]),s=N([]),o=N([]),a=N([]);async function c(){const y=xt(),m="2000-01-01",k=await Promise.all([jr(),di(m,y),pi(m,y),Ks(!0)]),D=k[0],O=k[1],K=k[2],W=k[3],de=O.filter(J=>J.clock_in_at||J.kind==="makeup");let Z=0;for(const J of de){const xe=qs(J,J.date,D,J.date===y);Z+=xe.workedMinutes??0}const E=new Set(K.map(J=>J.date));let L=0,Q=y;for(E.has(Q)||(Q=Kn(y,-1));E.has(Q);)L++,Q=Kn(Q,-1);t.value={attendDays:de.length,totalHours:(Z/60).toFixed(1),itemCount:K.length,streak:L};const le=new Map;for(const J of de){const xe=J.location||"未记录";le.set(xe,(le.get(xe)||0)+1)}a.value=Array.from(le.entries()).map(J=>({name:J[0],count:J[1],percent:Math.round(J[1]/(de.length||1)*100)})).sort((J,xe)=>xe.count-J.count);const ce=K.length||1;s.value=Us.map(J=>{const xe=K.filter(Ne=>Ne.category===J.key).length;return{key:J.key,label:J.label,count:xe,percent:Math.round(xe/ce*100)}}).filter(J=>J.count>0).sort((J,xe)=>xe.count-J.count);const ee=new Map(W.map(J=>[J.id,J.name])),A=new Map;for(const J of K){const xe=J.project_id?ee.get(J.project_id)||"已删除项目":"无项目";A.set(xe,(A.get(xe)||0)+1)}o.value=Array.from(A.entries()).map(J=>({name:J[0],count:J[1],percent:Math.round(J[1]/ce*100)})).sort((J,xe)=>xe.count-J.count);const x=new Map;for(const J of K)x.set(J.date,(x.get(J.date)||0)+1);const ie=Es(y),Ce=[];for(let J=11;J>=0;J--){const xe=Kn(ie,-7*J),Ne=[];for(let Xe=0;Xe<7;Xe++){const He=Kn(xe,Xe);Ne.push({date:He,count:x.get(He)||0})}Ce.push(Ne)}n.value=Ce}fn(async()=>{await c()}),gt(Hs,()=>{c()});function d(y){return y===0?0:y===1?1:y<=3?2:y<=5?3:4}function h(y,m){return y+" · "+(m?m+" 条":"无记录")}return(y,m)=>(F(),q("div",Cy,[u("div",Sy,[u("div",Ey,[m[0]||(m[0]=u("div",{class:"muted"},"出勤天数",-1)),u("div",$y,re(t.value.attendDays),1)]),u("div",Ay,[m[1]||(m[1]=u("div",{class:"muted"},"累计工时(小时)",-1)),u("div",Py,re(t.value.totalHours),1)]),u("div",Ty,[m[2]||(m[2]=u("div",{class:"muted"},"记录条数",-1)),u("div",Oy,re(t.value.itemCount),1)]),u("div",My,[m[3]||(m[3]=u("div",{class:"muted"},"连续记录(天)",-1)),u("div",Iy,re(t.value.streak),1)])]),u("div",jy,[m[4]||(m[4]=u("div",{class:"section-title"},"记录热力图(近 12 周)",-1)),u("div",Dy,[(F(!0),q(Re,null,ut(n.value,(k,D)=>(F(),q("div",{key:D,class:"heat-col"},[(F(!0),q(Re,null,ut(k,O=>(F(),q("span",{key:O.date,class:et(["heat-cell","lv"+d(O.count)]),title:h(O.date,O.count)},null,10,Ry))),128))]))),128))]),m[5]||(m[5]=Dp('
少多
',1))]),u("div",Ly,[u("div",Ky,[m[6]||(m[6]=u("div",{class:"section-title"},"分类分布",-1)),(F(!0),q(Re,null,ut(s.value,k=>(F(),q("div",{key:k.key,class:"bar-row"},[u("span",Fy,re(k.label),1),u("span",Ny,[u("span",{class:"bar-fill",style:sr({width:k.percent+"%"})},null,4)]),u("span",Vy,re(k.count)+" 条 · "+re(k.percent)+"%",1)]))),128)),s.value.length?Ee("",!0):(F(),q("div",By,"暂无数据"))]),u("div",Uy,[m[7]||(m[7]=u("div",{class:"section-title"},"项目投入",-1)),(F(!0),q(Re,null,ut(o.value,k=>(F(),q("div",{key:k.name,class:"bar-row"},[u("span",qy,re(k.name),1),u("span",Hy,[u("span",{class:"bar-fill",style:sr({width:k.percent+"%"})},null,4)]),u("span",Wy,re(k.count)+" 条 · "+re(k.percent)+"%",1)]))),128)),o.value.length?Ee("",!0):(F(),q("div",zy,"暂无数据"))])]),u("div",Gy,[m[8]||(m[8]=u("div",{class:"section-title"},"地点分布(按出勤天)",-1)),(F(!0),q(Re,null,ut(a.value,k=>(F(),q("div",{key:k.name,class:"bar-row"},[u("span",Yy,re(k.name),1),u("span",Jy,[u("span",{class:"bar-fill",style:sr({width:k.percent+"%"})},null,4)]),u("span",Xy,re(k.count)+" 天 · "+re(k.percent)+"%",1)]))),128)),a.value.length?Ee("",!0):(F(),q("div",Qy,"暂无数据"))])]))}}),eg=Gt(Zy,[["__scopeId","data-v-73e5ba49"]]);async function tg(e,t,n){const s=xt(),o=await Promise.all([jr(),di(e,t),pi(e,t),Ks(!0),Iv(e,t)]),a=o[0],c=o[1],d=o[2],h=o[3],y=o[4];let m=0,k=0,D=0;for(const A of c){(A.clock_in_at||A.kind==="makeup")&&m++,A.kind==="makeup"&&D++;const x=qs(A,A.date,a,A.date===s);k+=x.workedMinutes??0}const O=new Map;for(const A of c){if(!(A.clock_in_at||A.kind==="makeup"))continue;const x=A.location||"未记录";O.set(x,(O.get(x)||0)+1)}const K=Array.from(O.entries()).map(A=>({name:A[0],count:A[1]})).sort((A,x)=>x.count-A.count),W=d.length||1,de=Us.map(A=>{const x=d.filter(ie=>ie.category===A.key).length;return{key:A.key,label:A.label,count:x,percent:Math.round(x/W*100)}}).filter(A=>A.count>0).sort((A,x)=>x.count-A.count),Z=new Map(h.map(A=>[A.id,A.name])),E=new Map;for(const A of d){const x=A.project_id?Z.get(A.project_id)||"已删除项目":"无项目";E.set(x,(E.get(x)||0)+1)}const L=Array.from(E.entries()).map(A=>({name:A[0],count:A[1]})).sort((A,x)=>x.count-A.count),Q=d.filter(A=>A.is_milestone===1).map(A=>({date:A.date,content:A.content})),le=d.filter(A=>A.needs_followup===1).map(A=>({date:A.date,content:A.content,remark:A.remark||""})),ce=d.filter(A=>!!A.takeaway).map(A=>({date:A.date,text:A.takeaway})),ee=y.map(A=>({weekStart:A.week_start,highlights:A.highlights||"",challenges:A.challenges||"",plan_next:A.plan_next||""}));return{range:{start:e,end:t,label:n},attendDays:m,totalHours:(k/60).toFixed(1),makeupCount:D,leaveCount:c.filter(A=>A.kind==="leave").length,itemCount:d.length,categoryStats:de,projectStats:L,locationStats:K,milestones:Q,followups:le,takeaways:ce,weekNotes:ee}}function ng(e){const t=[];t.push("# 实习工作总结("+e.range.start+" ~ "+e.range.end+")"),t.push(""),t.push("## 一、考勤概况"),t.push(""),t.push("出勤 "+e.attendDays+" 天,累计工时 "+e.totalHours+" 小时,补卡 "+e.makeupCount+" 次"+(e.leaveCount?",请假 "+e.leaveCount+" 天":""));const n=e.locationStats.filter(s=>s.name!=="未记录");n.length&&t.push("其中:"+n.map(s=>s.name+" "+s.count+" 天").join(",")),t.push(""),t.push("## 二、工作内容分布"),t.push(""),t.push(e.categoryStats.length?e.categoryStats.map(s=>s.label+" "+s.percent+"%("+s.count+" 条)").join(","):"(无记录)"),t.push(""),t.push("## 三、项目投入"),t.push(""),t.push(e.projectStats.length?e.projectStats.map(s=>s.name+" "+s.count+" 条").join(","):"(无记录)"),t.push(""),t.push("## 四、主要成果"),t.push(""),e.milestones.length?e.milestones.forEach((s,o)=>t.push(o+1+". 【成果】"+s.content+"("+s.date+")")):t.push("(无)"),t.push(""),t.push("## 五、待跟进事项"),t.push(""),e.followups.length?e.followups.forEach(s=>t.push("- 【待跟进】"+s.content+(s.remark?"("+s.date+" 备注:"+s.remark+")":"("+s.date+")"))):t.push("(无)"),t.push(""),t.push("## 六、学习与成长"),t.push(""),e.takeaways.length?e.takeaways.forEach(s=>t.push("- "+s.text+"("+s.date+")")):t.push("(无)");for(const s of e.weekNotes)t.push(""),t.push("### 周记("+s.weekStart+" 起)"),t.push(""),t.push("- 本周亮点:"+(s.highlights||"(无)")),t.push("- 踩的坑:"+(s.challenges||"(无)")),t.push("- 下周计划:"+(s.plan_next||"(无)"));return t.push(""),t.join(` +`)}const rg="modulepreload",sg=function(e,t){return new URL(e,t).href},Tu={},cf=function(t,n,s){let o=Promise.resolve();if(n&&n.length>0){const c=document.getElementsByTagName("link"),d=document.querySelector("meta[property=csp-nonce]"),h=(d==null?void 0:d.nonce)||(d==null?void 0:d.getAttribute("nonce"));o=Promise.allSettled(n.map(y=>{if(y=sg(y,s),y in Tu)return;Tu[y]=!0;const m=y.endsWith(".css"),k=m?'[rel="stylesheet"]':"";if(!!s)for(let K=c.length-1;K>=0;K--){const W=c[K];if(W.href===y&&(!m||W.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${y}"]${k}`))return;const O=document.createElement("link");if(O.rel=m?"stylesheet":rg,m||(O.as="script"),O.crossOrigin="",O.href=y,h&&O.setAttribute("nonce",h),document.head.appendChild(O),m)return new Promise((K,W)=>{O.addEventListener("load",K),O.addEventListener("error",()=>W(new Error(`Unable to preload CSS for ${y}`)))})}))}function a(c){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=c,window.dispatchEvent(d),!d.defaultPrevented)throw c}return o.then(c=>{for(const d of c||[])d.status==="rejected"&&a(d.reason);return t().catch(a)})};/*! Capacitor: https://capacitorjs.com/ - MIT License */const og=e=>{const t=new Map;t.set("web",{name:"web"});const n=e.CapacitorPlatforms||{currentPlatform:{name:"web"},platforms:t},s=(a,c)=>{n.platforms.set(a,c)},o=a=>{n.platforms.has(a)&&(n.currentPlatform=n.platforms.get(a))};return n.addPlatform=s,n.setPlatform=o,n},ig=e=>e.CapacitorPlatforms=og(e),ff=ig(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});ff.addPlatform;ff.setPlatform;var Qr;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(Qr||(Qr={}));class ua extends Error{constructor(t,n,s){super(t),this.message=t,this.code=n,this.data=s}}const ag=e=>{var t,n;return e!=null&&e.androidBridge?"android":!((n=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||n===void 0)&&n.bridge?"ios":"web"},lg=e=>{var t,n,s,o,a;const c=e.CapacitorCustomPlatform||null,d=e.Capacitor||{},h=d.Plugins=d.Plugins||{},y=e.CapacitorPlatforms,m=()=>c!==null?c.name:ag(e),k=((t=y==null?void 0:y.currentPlatform)===null||t===void 0?void 0:t.getPlatform)||m,D=()=>k()!=="web",O=((n=y==null?void 0:y.currentPlatform)===null||n===void 0?void 0:n.isNativePlatform)||D,K=ee=>{const A=Q.get(ee);return!!(A!=null&&A.platforms.has(k())||Z(ee))},W=((s=y==null?void 0:y.currentPlatform)===null||s===void 0?void 0:s.isPluginAvailable)||K,de=ee=>{var A;return(A=d.PluginHeaders)===null||A===void 0?void 0:A.find(x=>x.name===ee)},Z=((o=y==null?void 0:y.currentPlatform)===null||o===void 0?void 0:o.getPluginHeader)||de,E=ee=>e.console.error(ee),L=(ee,A,x)=>Promise.reject(`${x} does not have an implementation of "${A}".`),Q=new Map,le=(ee,A={})=>{const x=Q.get(ee);if(x)return console.warn(`Capacitor plugin "${ee}" already registered. Cannot register plugins twice.`),x.proxy;const ie=k(),Ce=Z(ee);let J;const xe=async()=>(!J&&ie in A?J=typeof A[ie]=="function"?J=await A[ie]():J=A[ie]:c!==null&&!J&&"web"in A&&(J=typeof A.web=="function"?J=await A.web():J=A.web),J),Ne=(Ke,fe)=>{var G,X;if(Ce){const ke=Ce==null?void 0:Ce.methods.find(st=>fe===st.name);if(ke)return ke.rtype==="promise"?st=>d.nativePromise(ee,fe.toString(),st):(st,pt)=>d.nativeCallback(ee,fe.toString(),st,pt);if(Ke)return(G=Ke[fe])===null||G===void 0?void 0:G.bind(Ke)}else{if(Ke)return(X=Ke[fe])===null||X===void 0?void 0:X.bind(Ke);throw new ua(`"${ee}" plugin is not implemented on ${ie}`,Qr.Unimplemented)}},Xe=Ke=>{let fe;const G=(...X)=>{const ke=xe().then(st=>{const pt=Ne(st,Ke);if(pt){const ht=pt(...X);return fe=ht==null?void 0:ht.remove,ht}else throw new ua(`"${ee}.${Ke}()" is not implemented on ${ie}`,Qr.Unimplemented)});return Ke==="addListener"&&(ke.remove=async()=>fe()),ke};return G.toString=()=>`${Ke.toString()}() { [capacitor code] }`,Object.defineProperty(G,"name",{value:Ke,writable:!1,configurable:!1}),G},He=Xe("addListener"),Ue=Xe("removeListener"),ge=(Ke,fe)=>{const G=He({eventName:Ke},fe),X=async()=>{const st=await G;Ue({eventName:Ke,callbackId:st},fe)},ke=new Promise(st=>G.then(()=>st({remove:X})));return ke.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await X()},ke},Me=new Proxy({},{get(Ke,fe){switch(fe){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return Ce?ge:He;case"removeListener":return Ue;default:return Xe(fe)}}});return h[ee]=Me,Q.set(ee,{name:ee,proxy:Me,platforms:new Set([...Object.keys(A),...Ce?[ie]:[]])}),Me},ce=((a=y==null?void 0:y.currentPlatform)===null||a===void 0?void 0:a.registerPlugin)||le;return d.convertFileSrc||(d.convertFileSrc=ee=>ee),d.getPlatform=k,d.handleError=E,d.isNativePlatform=O,d.isPluginAvailable=W,d.pluginMethodNoop=L,d.registerPlugin=ce,d.Exception=ua,d.DEBUG=!!d.DEBUG,d.isLoggingEnabled=!!d.isLoggingEnabled,d.platform=d.getPlatform(),d.isNative=d.isNativePlatform(),d},ug=e=>e.Capacitor=lg(e),Zr=ug(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),df=Zr.registerPlugin;Zr.Plugins;class pf{constructor(t){this.listeners={},this.retainedEventArguments={},this.windowListeners={},t&&(console.warn(`Capacitor WebPlugin "${t.name}" config object was deprecated in v3 and will be removed in v4.`),this.config=t)}addListener(t,n){let s=!1;this.listeners[t]||(this.listeners[t]=[],s=!0),this.listeners[t].push(n);const a=this.windowListeners[t];a&&!a.registered&&this.addWindowListener(a),s&&this.sendRetainedArgumentsForEvent(t);const c=async()=>this.removeListener(t,n);return Promise.resolve({remove:c})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,n,s){const o=this.listeners[t];if(!o){if(s){let a=this.retainedEventArguments[t];a||(a=[]),a.push(n),this.retainedEventArguments[t]=a}return}o.forEach(a=>a(n))}hasListeners(t){return!!this.listeners[t].length}registerWindowListener(t,n){this.windowListeners[n]={registered:!1,windowEventName:t,pluginEventName:n,handler:s=>{this.notifyListeners(n,s)}}}unimplemented(t="not implemented"){return new Zr.Exception(t,Qr.Unimplemented)}unavailable(t="not available"){return new Zr.Exception(t,Qr.Unavailable)}async removeListener(t,n){const s=this.listeners[t];if(!s)return;const o=s.indexOf(n);this.listeners[t].splice(o,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const n=this.retainedEventArguments[t];n&&(delete this.retainedEventArguments[t],n.forEach(s=>{this.notifyListeners(t,s)}))}}const Ou=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Mu=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class cg extends pf{async getCookies(){const t=document.cookie,n={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[o,a]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");o=Mu(o).trim(),a=Mu(a).trim(),n[o]=a}),n}async setCookie(t){try{const n=Ou(t.key),s=Ou(t.value),o=`; expires=${(t.expires||"").replace("expires=","")}`,a=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${n}=${s||""}${o}; path=${a}; ${c};`}catch(n){return Promise.reject(n)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(n){return Promise.reject(n)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const n of t)document.cookie=n.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}df("CapacitorCookies",{web:()=>new cg});const fg=async e=>new Promise((t,n)=>{const s=new FileReader;s.onload=()=>{const o=s.result;t(o.indexOf(",")>=0?o.split(",")[1]:o)},s.onerror=o=>n(o),s.readAsDataURL(e)}),dg=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(o=>o.toLocaleLowerCase()).reduce((o,a,c)=>(o[a]=e[t[c]],o),{})},pg=(e,t=!0)=>e?Object.entries(e).reduce((s,o)=>{const[a,c]=o;let d,h;return Array.isArray(c)?(h="",c.forEach(y=>{d=t?encodeURIComponent(y):y,h+=`${a}=${d}&`}),h.slice(0,-1)):(d=t?encodeURIComponent(c):c,h=`${a}=${d}`),`${s}&${h}`},"").substr(1):null,hg=(e,t={})=>{const n=Object.assign({method:e.method||"GET",headers:e.headers},t),o=dg(e.headers)["content-type"]||"";if(typeof e.data=="string")n.body=e.data;else if(o.includes("application/x-www-form-urlencoded")){const a=new URLSearchParams;for(const[c,d]of Object.entries(e.data||{}))a.set(c,d);n.body=a.toString()}else if(o.includes("multipart/form-data")||e.data instanceof FormData){const a=new FormData;if(e.data instanceof FormData)e.data.forEach((d,h)=>{a.append(h,d)});else for(const d of Object.keys(e.data))a.append(d,e.data[d]);n.body=a;const c=new Headers(n.headers);c.delete("content-type"),n.headers=c}else(o.includes("application/json")||typeof e.data=="object")&&(n.body=JSON.stringify(e.data));return n};class vg extends pf{async request(t){const n=hg(t,t.webFetchExtra),s=pg(t.params,t.shouldEncodeUrlParams),o=s?`${t.url}?${s}`:t.url,a=await fetch(o,n),c=a.headers.get("content-type")||"";let{responseType:d="text"}=a.ok?t:{};c.includes("application/json")&&(d="json");let h,y;switch(d){case"arraybuffer":case"blob":y=await a.blob(),h=await fg(y);break;case"json":h=await a.json();break;case"document":case"text":default:h=await a.text()}const m={};return a.headers.forEach((k,D)=>{m[D]=k}),{data:h,headers:m,status:a.status,url:a.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}df("CapacitorHttp",{web:()=>new vg});async function tl(e,t){const n=window;if(n.electronAPI&&n.electronAPI.saveFile){const c=await n.electronAPI.saveFile(e,t);return c&&c.saved?c.path:""}if(Zr.isNativePlatform()){const{Filesystem:c,Directory:d,Encoding:h}=await cf(async()=>{const{Filesystem:y,Directory:m,Encoding:k}=await import("./index-zYm_cjgi.js");return{Filesystem:y,Directory:m,Encoding:k}},[],import.meta.url);try{return(await c.writeFile({path:e,data:t,directory:d.Documents,encoding:h.UTF8,recursive:!0})).uri}catch{return(await c.writeFile({path:e,data:t,directory:d.Cache,encoding:h.UTF8,recursive:!0})).uri}}const s=new Blob([t],{type:"text/plain;charset=utf-8"}),o=URL.createObjectURL(s),a=document.createElement("a");return a.href=o,a.download=e,a.click(),window.setTimeout(()=>URL.revokeObjectURL(o),1e4),""}const mg=Object.freeze(Object.defineProperty({__proto__:null,downloadText:tl},Symbol.toStringTag,{value:"Module"}));async function Pa(e){try{await navigator.clipboard.writeText(e)}catch{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t)}}async function yg(e){const t=await Promise.all([yt("ai_base_url",""),yt("ai_api_key",""),yt("ai_model","")]),n=t[0].trim().replace(/\/+$/,""),s=t[1].trim(),o=t[2].trim();if(!n||!o)throw new Error("请先在设置页配置 AI 接口地址与模型名称");const a=n+"/chat/completions",c={"Content-Type":"application/json"};s&&(c.Authorization="Bearer "+s);const h=JSON.stringify({model:o,messages:[{role:"system",content:"你是一名严谨的中文助理。请将用户提供的工作总结 Markdown 草稿润色为通顺、专业、简洁的工作总结。要求:保留原有章节结构与全部事实数据(数字、日期、条目),不得虚构或遗漏内容,只输出 Markdown 正文。"},{role:"user",content:e}],temperature:.3});let y;try{y=await fetch(a,{method:"POST",headers:c,body:h})}catch{throw new Error("无法访问 AI 接口:请检查地址是否正确、服务端是否允许浏览器跨域访问")}if(!y.ok){let D="接口返回 "+y.status;try{const O=await y.json();O&&O.error&&O.error.message&&(D+=":"+O.error.message)}catch{}throw new Error(D)}const m=await y.json(),k=m&&m.choices&&m.choices[0]&&m.choices[0].message&&m.choices[0].message.content;if(!k)throw new Error("接口未返回内容");return String(k)}const gg={class:"report"},bg={class:"report-toolbar"},wg={class:"seg"},_g=["onClick"],kg=["disabled"],xg=["disabled"],Cg={key:0,class:"ai-error"},Sg={class:"report-grid"},Eg={class:"report-left"},$g={class:"card section"},Ag={class:"section-title"},Pg={class:"muted note-saved"},Tg={class:"card section"},Og={class:"report-right"},Mg={key:0,class:"card section"},Ig={class:"sum-row"},jg={class:"num"},Dg={class:"sum-row"},Rg={class:"num"},Lg={class:"sum-row"},Kg={class:"num"},Fg={class:"sum-row"},Ng={class:"num"},Vg={class:"sum-row"},Bg={class:"num"},Ug={class:"muted"},qg={class:"num"},Hg={key:0,class:"muted sum-empty"},Wg={class:"muted"},zg={key:1,class:"muted sum-empty"},Gg={class:"muted"},Yg={key:2,class:"muted sum-empty"},Jg={class:"muted"},Xg={key:3,class:"muted sum-empty"},Qg=Vt({__name:"ReportView",setup(e){const t=[{key:"week",label:"本周"},{key:"month",label:"本月"},{key:"all",label:"全部"},{key:"custom",label:"自定义"}],n=N("week"),s=N(Es(xt())),o=N(xt()),a=N(null),c=N(""),d=N(!1),h=N(!1),y=N(null),m=N(""),k=N(Es(xt())),D=N(""),O=N(""),K=N(""),W=N(!1);async function de(){const A=await el(k.value);D.value=(A==null?void 0:A.highlights)||"",O.value=(A==null?void 0:A.challenges)||"",K.value=(A==null?void 0:A.plan_next)||"",W.value=!1}async function Z(){await Mv(k.value,{highlights:D.value.trim()||null,challenges:O.value.trim()||null,plan_next:K.value.trim()||null}),W.value=!0,await L()}function E(A){const x=xt();if(A==="week"){const ie=Es(x);return{start:ie,end:Kn(ie,6),label:"本周"}}if(A==="month"){const ie=x.slice(0,7);return{start:ie+"-01",end:x,label:ie+" 本月"}}return A==="all"?{start:"2000-01-01",end:x,label:"全部实习期"}:{start:s.value,end:o.value,label:s.value+" ~ "+o.value}}async function L(){d.value=!0;const A=E(n.value),x=await tg(A.start,A.end,A.label);a.value=x,c.value=ng(x),d.value=!1}gt(n,L),gt([s,o],()=>{n.value==="custom"&&L()}),fn(async()=>{await de(),await L()});async function Q(){const A=xt().replace(/-/g,""),x=await tl("实习工作总结_"+A+".md",c.value);qe(x?"总结已导出到:"+x:"总结已导出到系统下载目录")}async function le(){await Pa(c.value),qe("总结已复制到剪贴板")}async function ce(){if(h.value)return;m.value="";const A=c.value.trim();if(!A){m.value="当前草稿为空,无法润色";return}h.value=!0;try{y.value=c.value,c.value=await yg(A),qe("AI 润色完成")}catch(x){y.value=null,m.value=x instanceof Error?x.message:"润色失败"}h.value=!1}function ee(){y.value!==null&&(c.value=y.value),y.value=null}return(A,x)=>(F(),q("div",gg,[u("div",bg,[u("div",wg,[(F(),q(Re,null,ut(t,ie=>u("button",{key:ie.key,class:et(["seg-btn",{active:n.value===ie.key}]),onClick:Ce=>n.value=ie.key},re(ie.label),11,_g)),64))]),n.value==="custom"?(F(),q(Re,{key:0},[$e(u("input",{type:"date",class:"input w-date","onUpdate:modelValue":x[0]||(x[0]=ie=>s.value=ie)},null,512),[[De,s.value]]),x[6]||(x[6]=u("span",{class:"muted"},"至",-1)),$e(u("input",{type:"date",class:"input w-date","onUpdate:modelValue":x[1]||(x[1]=ie=>o.value=ie)},null,512),[[De,o.value]])],64)):Ee("",!0),x[10]||(x[10]=u("span",{class:"flex1"},null,-1)),u("button",{class:"btn btn-sm",disabled:h.value,onClick:ce},[Oe(lt,{name:"edit",size:14}),x[7]||(x[7]=nn("AI 润色 ",-1))],8,kg),y.value!==null?(F(),q("button",{key:1,class:"btn btn-sm",onClick:ee},"还原润色前")):Ee("",!0),u("button",{class:"btn btn-sm",disabled:d.value,onClick:L},[Oe(lt,{name:"edit",size:14}),x[8]||(x[8]=nn("重新生成 ",-1))],8,xg),u("button",{class:"btn btn-sm",onClick:le},"复制"),u("button",{class:"btn btn-primary btn-sm",onClick:Q},[Oe(lt,{name:"export",size:14}),x[9]||(x[9]=nn("导出 Markdown ",-1))])]),m.value?(F(),q("div",Cg,re(m.value),1)):Ee("",!0),u("div",Sg,[u("div",Eg,[u("div",$g,[u("div",Ag,"本周周记("+re(k.value)+" 起)",1),x[11]||(x[11]=u("label",{class:"note-label muted"},"本周亮点",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":x[2]||(x[2]=ie=>D.value=ie),placeholder:"本周最有价值的一件事",onBlur:Z},null,544),[[De,D.value]]),x[12]||(x[12]=u("label",{class:"note-label muted"},"踩的坑",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":x[3]||(x[3]=ie=>O.value=ie),placeholder:"遇到的问题与教训",onBlur:Z},null,544),[[De,O.value]]),x[13]||(x[13]=u("label",{class:"note-label muted"},"下周计划",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":x[4]||(x[4]=ie=>K.value=ie),placeholder:"下周准备做什么",onBlur:Z},null,544),[[De,K.value]]),u("div",Pg,re(W.value?"已保存":"失焦自动保存"),1)]),u("div",Tg,[x[14]||(x[14]=u("div",{class:"section-title"},"总结草稿(可编辑)",-1)),$e(u("textarea",{class:"textarea md-editor","onUpdate:modelValue":x[5]||(x[5]=ie=>c.value=ie),spellcheck:"false"},null,512),[[De,c.value]])])]),u("div",Og,[a.value?(F(),q("div",Mg,[x[20]||(x[20]=u("div",{class:"section-title"},"数据摘要",-1)),u("div",Ig,[x[15]||(x[15]=u("span",{class:"muted"},"出勤",-1)),u("span",jg,re(a.value.attendDays)+" 天",1)]),u("div",Dg,[x[16]||(x[16]=u("span",{class:"muted"},"工时",-1)),u("span",Rg,re(a.value.totalHours)+" 小时",1)]),u("div",Lg,[x[17]||(x[17]=u("span",{class:"muted"},"补卡",-1)),u("span",Kg,re(a.value.makeupCount)+" 次",1)]),u("div",Fg,[x[18]||(x[18]=u("span",{class:"muted"},"请假",-1)),u("span",Ng,re(a.value.leaveCount)+" 天",1)]),u("div",Vg,[x[19]||(x[19]=u("span",{class:"muted"},"记录",-1)),u("span",Bg,re(a.value.itemCount)+" 条",1)]),x[21]||(x[21]=u("div",{class:"section-sub"},"分类分布",-1)),(F(!0),q(Re,null,ut(a.value.categoryStats,ie=>(F(),q("div",{key:ie.key,class:"sum-row"},[u("span",Ug,re(ie.label),1),u("span",qg,re(ie.count)+" 条 · "+re(ie.percent)+"%",1)]))),128)),a.value.categoryStats.length?Ee("",!0):(F(),q("div",Hg,"(无)")),x[22]||(x[22]=u("div",{class:"section-sub"},"主要成果",-1)),(F(!0),q(Re,null,ut(a.value.milestones,(ie,Ce)=>(F(),q("div",{key:"m"+Ce,class:"sum-item"},[nn(re(ie.content),1),u("span",Wg,"("+re(ie.date)+")",1)]))),128)),a.value.milestones.length?Ee("",!0):(F(),q("div",zg,"(无)")),x[23]||(x[23]=u("div",{class:"section-sub"},"待跟进",-1)),(F(!0),q(Re,null,ut(a.value.followups,(ie,Ce)=>(F(),q("div",{key:"f"+Ce,class:"sum-item"},[nn(re(ie.content),1),u("span",Gg,"("+re(ie.date)+")",1)]))),128)),a.value.followups.length?Ee("",!0):(F(),q("div",Yg,"(无)")),x[24]||(x[24]=u("div",{class:"section-sub"},"学习与成长",-1)),(F(!0),q(Re,null,ut(a.value.takeaways,(ie,Ce)=>(F(),q("div",{key:"t"+Ce,class:"sum-item"},[nn(re(ie.text),1),u("span",Jg,"("+re(ie.date)+")",1)]))),128)),a.value.takeaways.length?Ee("",!0):(F(),q("div",Xg,"(无)"))])):Ee("",!0)])])]))}}),Zg=Gt(Qg,[["__scopeId","data-v-43f9c59b"]]),eb=["aria-label"],tb={class:"dialog-head"},nb={class:"dialog-title"},rb={class:"dialog-body"},sb={class:"form-grid"},ob={class:"field span2"},ib={class:"seg"},ab={class:"field"},lb={class:"field"},ub={class:"field"},cb=["value"],fb={key:0,class:"field"},db={class:"seg"},pb={class:"field span2"},hb={key:0,class:"form-error"},vb={class:"dialog-btns"},mb=Vt({__name:"TransactionDialog",props:{open:{type:Boolean},title:{},initial:{}},emits:["cancel","save"],setup(e,{emit:t}){const n=e,s=t,o=N("expense"),a=N("餐饮"),c=N(""),d=N(""),h=N(""),y=N(!1),m=N(!1),k=N(""),D=N(null);function O(Z){n.open&&Z.key==="Escape"&&s("cancel")}gt(()=>n.open,async Z=>{var E;Z?(o.value=n.initial.type==="income"?"income":"expense",a.value=n.initial.category,c.value=n.initial.amountYuan,d.value=n.initial.date,h.value=n.initial.note,y.value=n.initial.reimbursable===1,m.value=n.initial.reimbursed===1,k.value="",window.addEventListener("keydown",O),await ts(),(E=D.value)==null||E.focus()):window.removeEventListener("keydown",O)}),dr(()=>window.removeEventListener("keydown",O)),gt(o,Z=>{a.value=Z==="expense"?Wr[0]:Bo[0]});const K=it(()=>o.value==="expense"?Wr:Bo);function W(){return a.value&&K.value.includes(a.value)?a.value:K.value[0]}function de(){const Z=Number(c.value);if(!c.value.trim()||!isFinite(Z)||Z<=0){k.value="请填写大于 0 的金额";return}if(!d.value){k.value="请选择日期";return}const E=o.value==="expense"&&y.value?1:0;s("save",{type:o.value,category:W(),amount:Math.round(Z*100),date:d.value,note:h.value.trim(),reimbursable:E,reimbursed:E&&m.value?1:0})}return(Z,E)=>(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:E[11]||(E[11]=Mr(L=>s("cancel"),["self"]))},[u("div",{class:"dialog",role:"dialog","aria-label":e.title},[u("div",tb,[u("span",nb,re(e.title),1),u("button",{class:"icon-btn",title:"关闭",onClick:E[0]||(E[0]=L=>s("cancel"))},[Oe(lt,{name:"close",size:16})])]),u("div",rb,[u("div",sb,[u("div",ob,[E[12]||(E[12]=u("label",null,"类型",-1)),u("div",ib,[u("button",{class:et(["seg-btn",{active:o.value==="expense"}]),onClick:E[1]||(E[1]=L=>o.value="expense")},"支出",2),u("button",{class:et(["seg-btn",{active:o.value==="income"}]),onClick:E[2]||(E[2]=L=>o.value="income")},"收入",2)])]),u("div",ab,[E[13]||(E[13]=u("label",null,"金额(元,必填)",-1)),$e(u("input",{ref_key:"amountInput",ref:D,class:et(["input",{invalid:k.value}]),"onUpdate:modelValue":E[3]||(E[3]=L=>c.value=L),type:"number",min:"0",step:"0.01",placeholder:"0.00"},null,2),[[De,c.value]])]),u("div",lb,[E[14]||(E[14]=u("label",null,"日期(必填)",-1)),$e(u("input",{class:"input",type:"date","onUpdate:modelValue":E[4]||(E[4]=L=>d.value=L)},null,512),[[De,d.value]])]),u("div",ub,[E[15]||(E[15]=u("label",null,"分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":E[5]||(E[5]=L=>a.value=L)},[(F(!0),q(Re,null,ut(K.value,L=>(F(),q("option",{key:L,value:L},re(L),9,cb))),128))],512),[[Fn,a.value]])]),o.value==="expense"?(F(),q("div",fb,[E[16]||(E[16]=u("label",null,"报销状态",-1)),u("div",db,[u("button",{class:et(["seg-btn",{active:!y.value}]),onClick:E[6]||(E[6]=L=>{y.value=!1,m.value=!1})},"无需报销",2),u("button",{class:et(["seg-btn",{active:y.value&&!m.value}]),onClick:E[7]||(E[7]=L=>{y.value=!0,m.value=!1})},"待报销",2),u("button",{class:et(["seg-btn",{active:y.value&&m.value}]),onClick:E[8]||(E[8]=L=>{y.value=!0,m.value=!0})},"已报销",2)])])):Ee("",!0),u("div",pb,[E[17]||(E[17]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":E[9]||(E[9]=L=>h.value=L),placeholder:"选填"},null,512),[[De,h.value]])])]),k.value?(F(),q("div",hb,re(k.value),1)):Ee("",!0)]),u("div",vb,[u("button",{class:"btn btn-sm",onClick:E[10]||(E[10]=L=>s("cancel"))},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:de},"保存")])],8,eb)])):Ee("",!0)]),_:1})]))}}),yb=Gt(mb,[["__scopeId","data-v-e3568c0d"]]),gb={class:"ledger-page"},bb={class:"ledger-toolbar"},wb={class:"month-title num"},_b={class:"cards"},kb={class:"card stat-card"},xb={class:"stat-num num amt-income"},Cb={class:"card stat-card"},Sb={class:"stat-num num"},Eb={class:"card stat-card"},$b={class:"card stat-card"},Ab={class:"stat-num num amt-warn"},Pb={class:"card sec"},Tb={class:"form-grid"},Ob={class:"field span2"},Mb={class:"seg"},Ib={class:"field"},jb={class:"field"},Db={class:"field"},Rb=["value"],Lb={key:0,class:"field"},Kb={class:"field span2"},Fb={key:0,class:"form-error"},Nb={class:"form-footer"},Vb=["disabled"],Bb=["disabled"],Ub={key:0,class:"card sec"},qb={class:"bar-label"},Hb={class:"bar-track"},Wb={class:"muted num bar-num"},zb={class:"card table-card"},Gb={class:"tx-table"},Yb={class:"num"},Jb={class:"tag"},Xb={class:"td-note"},Qb={key:0,class:"muted"},Zb={key:1,class:"tx-done"},ew={key:2,class:"tx-pending"},tw={class:"ops"},nw=["onClick"],rw=["onClick"],sw=["onClick"],ow={key:0},iw={class:"muted vault-note num"},aw=Vt({__name:"LedgerView",setup(e){const t=N(xt()),n=N([]),s=N(!0),o=N("expense"),a=N(""),c=N(Wr[0]),d=N(xt()),h=N(""),y=N(!1),m=N(""),k=N(!1),D=N(!1),O=N(null),K=N({type:"expense",category:Wr[0],amountYuan:"",date:xt(),note:"",reimbursable:0,reimbursed:0}),W=N(null),de=it(()=>t.value.slice(0,7)+"-01"),Z=it(()=>{const fe=Number(t.value.slice(0,4)),G=Number(t.value.slice(5,7))-1,X=new Date(fe,G+1,0).getDate();return t.value.slice(0,7)+"-"+(X<10?"0"+X:String(X))}),E=it(()=>Number(t.value.slice(0,4))+" 年 "+Number(t.value.slice(5,7))+" 月");async function L(){s.value=!0;try{n.value=await Nv(de.value,Z.value)}catch(fe){qe("账目加载失败:"+(fe instanceof Error?fe.message:String(fe)))}s.value=!1}fn(L),gt(t,L),gt(o,fe=>{c.value=fe==="expense"?Wr[0]:Bo[0]});const Q=it(()=>n.value.slice().sort((fe,G)=>fe.date===G.date?G.id-fe.id:fe.date{let fe=0,G=0,X=0;for(const ke of n.value)ke.type==="income"?fe+=ke.amount:(G+=ke.amount,ke.reimbursable===1&&ke.reimbursed!==1&&(X+=ke.amount));return{income:fe,expense:G,pending:X,balance:fe-G}}),ce=N("all"),ee=N("all"),A=it(()=>Q.value.filter(fe=>!(ce.value!=="all"&&fe.type!==ce.value||ee.value==="pending"&&!(fe.type==="expense"&&fe.reimbursable===1&&fe.reimbursed!==1)||ee.value==="done"&&!(fe.reimbursable===1&&fe.reimbursed===1)))),x=it(()=>{const fe=new Map;let G=0;for(const ke of n.value)ke.type==="expense"&&(fe.set(ke.category,(fe.get(ke.category)||0)+ke.amount),G+=ke.amount);const X=G||1;return Array.from(fe.entries()).map(ke=>({name:ke[0],amount:ke[1],percent:Math.round(ke[1]/X*100)})).sort((ke,st)=>st.amount-ke.amount)});function ie(fe){return(fe/100).toFixed(2)}function Ce(fe){return(fe.type==="income"?"+":"-")+ie(fe.amount)}function J(){t.value=Uo(t.value,-1)}function xe(){t.value=Uo(t.value,1)}function Ne(){t.value=xt()}gt(a,()=>{m.value&&(m.value="")});async function Xe(){const fe=Number(a.value);if(!a.value.trim()||!isFinite(fe)||fe<=0){m.value="请填写大于 0 的金额";return}if(!d.value){m.value="请选择日期";return}if(!k.value){k.value=!0;try{await Vv({type:o.value,category:c.value,amount:Math.round(fe*100),date:d.value,note:h.value.trim(),reimbursable:o.value==="expense"&&y.value?1:0,reimbursed:0})}catch(G){qe("添加失败:"+(G instanceof Error?G.message:String(G))),k.value=!1;return}a.value="",h.value="",y.value=!1,m.value="",await L(),qe("记账已添加"),k.value=!1}}function He(){a.value="",h.value="",y.value=!1,m.value=""}async function Ue(fe){await qv(fe.id),await L(),qe("已标记为已报销")}function ge(fe){O.value=fe.id,K.value={type:fe.type,category:fe.category,amountYuan:ie(fe.amount),date:fe.date,note:fe.note||"",reimbursable:fe.reimbursable,reimbursed:fe.reimbursed},D.value=!0}async function Me(fe){const G=O.value;await Bv(G,fe),D.value=!1,await L(),qe("账目已更新")}async function Ke(){W.value&&W.value.id&&await Uv(W.value.id),W.value=null,await L(),qe("账目已删除")}return(fe,G)=>(F(),q("div",gb,[u("div",bb,[u("button",{class:"icon-btn",onClick:J},[Oe(lt,{name:"chevron-left",size:16})]),u("span",wb,re(E.value),1),u("button",{class:"icon-btn",onClick:xe},[Oe(lt,{name:"chevron-right",size:16})]),u("button",{class:"btn btn-sm",onClick:Ne},"回到本月"),G[13]||(G[13]=u("span",{class:"flex1"},null,-1)),$e(u("select",{class:"select w-filter","onUpdate:modelValue":G[0]||(G[0]=X=>ce.value=X)},[...G[11]||(G[11]=[u("option",{value:"all"},"全部类型",-1),u("option",{value:"expense"},"仅支出",-1),u("option",{value:"income"},"仅收入",-1)])],512),[[Fn,ce.value]]),$e(u("select",{class:"select w-filter","onUpdate:modelValue":G[1]||(G[1]=X=>ee.value=X)},[...G[12]||(G[12]=[u("option",{value:"all"},"全部报销",-1),u("option",{value:"pending"},"待报销",-1),u("option",{value:"done"},"已报销",-1)])],512),[[Fn,ee.value]])]),u("div",_b,[u("div",kb,[G[14]||(G[14]=u("div",{class:"muted"},"本月收入(元)",-1)),u("div",xb,re(ie(le.value.income)),1)]),u("div",Cb,[G[15]||(G[15]=u("div",{class:"muted"},"本月支出(元)",-1)),u("div",Sb,re(ie(le.value.expense)),1)]),u("div",Eb,[G[16]||(G[16]=u("div",{class:"muted"},"本月结余(元)",-1)),u("div",{class:et(["stat-num num",{"amt-income":le.value.balance>=0,"amt-expense":le.value.balance<0}])},re(ie(le.value.balance)),3)]),u("div",$b,[G[17]||(G[17]=u("div",{class:"muted"},"待报销(元)",-1)),u("div",Ab,re(ie(le.value.pending)),1)])]),u("div",Pb,[G[24]||(G[24]=u("div",{class:"sec-head"},[u("span",{class:"sec-title"},"新增一笔"),u("span",{class:"muted form-hint"},"金额必填,回车快速添加")],-1)),u("div",Tb,[u("div",Ob,[G[18]||(G[18]=u("label",null,"类型",-1)),u("div",Mb,[u("button",{class:et(["seg-btn",{active:o.value==="expense"}]),onClick:G[2]||(G[2]=X=>o.value="expense")},"支出",2),u("button",{class:et(["seg-btn",{active:o.value==="income"}]),onClick:G[3]||(G[3]=X=>o.value="income")},"收入",2)])]),u("div",Ib,[G[19]||(G[19]=u("label",null,"金额(元,必填)",-1)),$e(u("input",{class:et(["input",{invalid:m.value}]),"onUpdate:modelValue":G[4]||(G[4]=X=>a.value=X),type:"number",min:"0",step:"0.01",placeholder:"0.00",onKeydown:jt(Xe,["enter"])},null,34),[[De,a.value]])]),u("div",jb,[G[20]||(G[20]=u("label",null,"日期",-1)),$e(u("input",{class:"input",type:"date","onUpdate:modelValue":G[5]||(G[5]=X=>d.value=X)},null,512),[[De,d.value]])]),u("div",Db,[G[21]||(G[21]=u("label",null,"分类",-1)),$e(u("select",{class:"select","onUpdate:modelValue":G[6]||(G[6]=X=>c.value=X)},[(F(!0),q(Re,null,ut(o.value==="expense"?Qt(Wr):Qt(Bo),X=>(F(),q("option",{key:X,value:X},re(X),9,Rb))),128))],512),[[Fn,c.value]])]),o.value==="expense"?(F(),q("div",Lb,[G[22]||(G[22]=u("label",null,"报销",-1)),u("button",{class:et(["toggle-btn",{on:y.value}]),onClick:G[7]||(G[7]=X=>y.value=!y.value)},re(y.value?"需要报销":"无需报销"),3)])):Ee("",!0),u("div",Kb,[G[23]||(G[23]=u("label",null,"备注",-1)),$e(u("input",{class:"input","onUpdate:modelValue":G[8]||(G[8]=X=>h.value=X),placeholder:"选填,如:客户现场午餐",onKeydown:jt(Xe,["enter"])},null,544),[[De,h.value]])])]),m.value?(F(),q("div",Fb,re(m.value),1)):Ee("",!0),u("div",Nb,[u("button",{class:"btn btn-sm",disabled:!(a.value.trim()||h.value.trim()),onClick:He},"重置",8,Vb),u("button",{class:"btn btn-primary btn-sm",disabled:k.value,onClick:Xe},"添加记录",8,Bb)])]),x.value.length?(F(),q("div",Ub,[G[25]||(G[25]=u("div",{class:"sec-title"},"本月支出分类",-1)),(F(!0),q(Re,null,ut(x.value,X=>(F(),q("div",{key:X.name,class:"bar-row"},[u("span",qb,re(X.name),1),u("span",Hb,[u("span",{class:"bar-fill",style:sr({width:X.percent+"%"})},null,4)]),u("span",Wb,re(ie(X.amount))+" 元 · "+re(X.percent)+"%",1)]))),128))])):Ee("",!0),u("div",zb,[u("table",Gb,[G[27]||(G[27]=u("thead",null,[u("tr",null,[u("th",null,"日期"),u("th",null,"分类"),u("th",null,"金额(元)"),u("th",null,"备注"),u("th",null,"报销"),u("th",{class:"th-ops"},"操作")])],-1)),u("tbody",null,[(F(!0),q(Re,null,ut(A.value,X=>(F(),q("tr",{key:X.id},[u("td",Yb,re(X.date),1),u("td",null,[u("span",Jb,re(X.category),1)]),u("td",{class:et(["num",X.type==="income"?"amt-income":"amt-expense"])},re(Ce(X)),3),u("td",Xb,re(X.note||"--"),1),u("td",null,[X.type!=="expense"||X.reimbursable!==1?(F(),q("span",Qb,"--")):X.reimbursed===1?(F(),q("span",Zb,"已报销")):(F(),q("span",ew,"待报销"))]),u("td",null,[u("div",tw,[X.type==="expense"&&X.reimbursable===1&&X.reimbursed!==1?(F(),q("button",{key:0,class:"btn btn-xs",onClick:ke=>Ue(X)},"标记已报销",8,nw)):Ee("",!0),u("button",{class:"btn btn-xs",onClick:ke=>ge(X)},"编辑",8,rw),u("button",{class:"btn btn-xs",onClick:ke=>W.value=X},"删除",8,sw)])])]))),128)),!A.value.length&&!s.value?(F(),q("tr",ow,[...G[26]||(G[26]=[u("td",{colspan:"6",class:"empty muted"},"本月暂无账目",-1)])])):Ee("",!0)])])]),u("div",iw,"筛选结果 "+re(A.value.length)+" 条 / 本月共 "+re(n.value.length)+" 条",1),Oe(yb,{open:D.value,title:(O.value,"编辑账目"),initial:K.value,onCancel:G[9]||(G[9]=X=>D.value=!1),onSave:Me},null,8,["open","title","initial"]),Oe(ur,{open:!!W.value,title:"删除确认",message:W.value?"将删除 "+W.value.date+" 的账目("+W.value.category+" "+ie(W.value.amount)+" 元)。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:G[10]||(G[10]=X=>W.value=null),onConfirm:Ke},null,8,["open","message"])]))}}),lw=Gt(aw,[["__scopeId","data-v-848ec3d4"]]),uw={class:"memo-page"},cw={class:"card memo-list"},fw={class:"pane-head"},dw={class:"pane-title"},pw={class:"memo-scroll"},hw=["onClick"],vw={class:"memo-item-title"},mw={class:"muted memo-item-sub"},yw={class:"muted num memo-item-time"},gw={key:0,class:"muted empty"},bw={class:"card memo-editor"},ww={class:"editor-foot"},_w={class:"muted foot-info"},kw=["disabled"],xw=["disabled"],Cw={key:1,class:"empty muted editor-empty"},Sw=Vt({__name:"MemoView",setup(e){const t=N([]),n=N(null),s=N(!1),o=N(""),a=N(""),c=N(null),d=N(null);async function h(){if(t.value=await jv(),n.value&&n.value.id){const ce=t.value.find(ee=>ee.id===n.value.id);ce&&(n.value=ce)}}fn(async()=>{await h(),t.value.length&&k(t.value[0]),window.addEventListener("keydown",y)}),dr(()=>window.removeEventListener("keydown",y)),gt(Aa,async ce=>{if(!ce)return;t.value.length||await h();const ee=t.value.find(A=>A.id===ce);Aa.value=null,ee&&D(ee)},{immediate:!0});function y(ce){(ce.ctrlKey||ce.metaKey)&&ce.key.toLowerCase()==="s"&&s.value&&m.value&&(ce.preventDefault(),de())}const m=it(()=>{if(!s.value)return!1;const ce=n.value?n.value.title:"",ee=n.value?n.value.content:"";return o.value!==ce||a.value!==ee});function k(ce){n.value=ce,s.value=!0,o.value=ce.title,a.value=ce.content}function D(ce){if(!(s.value&&n.value&&n.value.id===ce.id)){if(m.value){d.value={type:"select",memo:ce};return}k(ce)}}function O(){if(m.value){d.value={type:"new"};return}K()}function K(){n.value=null,s.value=!0,o.value="",a.value=""}function W(){n.value?k(n.value):K()}async function de(){if(!o.value.trim()&&!a.value.trim()){qe("标题与内容不能都为空");return}if(n.value&&n.value.id)await Rv(n.value.id,o.value,a.value),qe("备忘已保存");else{const ce=await Dv(o.value,a.value);n.value=ce,o.value=ce.title,a.value=ce.content,qe("备忘已创建")}await h()}function Z(){n.value&&n.value.id&&(c.value=n.value)}async function E(){c.value&&c.value.id&&(await Lv(c.value.id),qe("备忘已删除")),c.value=null,await h(),K()}function L(){const ce=d.value;d.value=null,ce&&(ce.type==="select"?k(ce.memo):K())}function Q(ce){return(ce.content||"").replace(/\s+/g," ").slice(0,30)}function le(ce){return ce.replace("T"," ").slice(0,16)}return(ce,ee)=>(F(),q("div",uw,[u("aside",cw,[u("div",fw,[u("span",dw,"备忘录("+re(t.value.length)+")",1),u("button",{class:"btn btn-primary btn-sm",onClick:O},"新建")]),u("div",pw,[(F(!0),q(Re,null,ut(t.value,A=>(F(),q("div",{key:A.id,class:et(["memo-item",{active:s.value&&n.value&&n.value.id===A.id}]),onClick:x=>D(A)},[u("div",vw,re(A.title||"无标题"),1),u("div",mw,re(Q(A)||"空"),1),u("div",yw,re(le(A.updated_at)),1)],10,hw))),128)),t.value.length?Ee("",!0):(F(),q("div",gw,"暂无备忘"))])]),u("section",bw,[s.value?(F(),q(Re,{key:0},[$e(u("input",{class:"input title-input","onUpdate:modelValue":ee[0]||(ee[0]=A=>o.value=A),placeholder:"标题"},null,512),[[De,o.value]]),$e(u("textarea",{class:"textarea content-textarea","onUpdate:modelValue":ee[1]||(ee[1]=A=>a.value=A),placeholder:"内容"},null,512),[[De,a.value]]),u("div",ww,[u("span",_w,[m.value?(F(),q(Re,{key:0},[nn("有未保存修改")],64)):n.value&&n.value.id?(F(),q(Re,{key:1},[nn("更新于 "+re(le(n.value.updated_at)),1)],64)):(F(),q(Re,{key:2},[nn("新备忘")],64))]),ee[4]||(ee[4]=u("span",{class:"flex1"},null,-1)),n.value&&n.value.id?(F(),q("button",{key:0,class:"btn btn-sm",onClick:Z},"删除")):Ee("",!0),u("button",{class:"btn btn-sm",disabled:!m.value,onClick:W},"放弃修改",8,kw),u("button",{class:"btn btn-primary btn-sm",disabled:!m.value,onClick:de},"保存",8,xw)])],64)):(F(),q("div",Cw,"选择左侧备忘,或点击右上角新建"))]),Oe(ur,{open:!!c.value,title:"删除确认",message:c.value?"将删除备忘「"+(c.value.title||"无标题")+"」。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:ee[2]||(ee[2]=A=>c.value=null),onConfirm:E},null,8,["open","message"]),Oe(ur,{open:!!d.value,title:"未保存提示",message:"当前备忘有未保存的修改,继续操作将丢失这些修改。","confirm-text":"放弃修改并继续",onCancel:ee[3]||(ee[3]=A=>d.value=null),onConfirm:L},null,8,["open"])]))}}),Ew=Gt(Sw,[["__scopeId","data-v-74d60dba"]]),$w=["aria-label"],Aw={class:"dialog-head"},Pw={class:"dialog-title"},Tw={class:"dialog-body"},Ow={class:"form-grid"},Mw={class:"field span2"},Iw={class:"field span2"},jw={class:"field span2"},Dw={class:"pwd-row"},Rw={class:"field span2"},Lw={key:0,class:"form-error"},Kw={class:"dialog-btns"},Fw=Vt({__name:"CredentialDialog",props:{open:{type:Boolean},title:{},initial:{}},emits:["cancel","save"],setup(e,{emit:t}){const n=e,s=t,o=N(""),a=N(""),c=N(""),d=N(""),h=N(""),y=N(null);function m(O){n.open&&O.key==="Escape"&&s("cancel")}gt(()=>n.open,async O=>{var K;O?(o.value=n.initial.system,a.value=n.initial.account,c.value=n.initial.password,d.value=n.initial.remark,h.value="",window.addEventListener("keydown",m),await ts(),(K=y.value)==null||K.focus()):window.removeEventListener("keydown",m)}),dr(()=>window.removeEventListener("keydown",m));function k(){const O="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",K="!@#$%^&*",W=crypto.getRandomValues(new Uint8Array(14));let de="";for(let Z=0;Z(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[e.open?(F(),q("div",{key:0,class:"mask",onClick:K[6]||(K[6]=Mr(W=>s("cancel"),["self"]))},[u("div",{class:"dialog",role:"dialog","aria-label":e.title},[u("div",Aw,[u("span",Pw,re(e.title),1),u("button",{class:"icon-btn",title:"关闭",onClick:K[0]||(K[0]=W=>s("cancel"))},[Oe(lt,{name:"close",size:16})])]),u("div",Tw,[u("div",Ow,[u("div",Mw,[K[7]||(K[7]=u("label",null,"系统名称(必填)",-1)),$e(u("input",{ref_key:"systemInput",ref:y,class:"input","onUpdate:modelValue":K[1]||(K[1]=W=>o.value=W),placeholder:"如:企业邮箱 / OA / VPN"},null,512),[[De,o.value]])]),u("div",Iw,[K[8]||(K[8]=u("label",null,"账号(必填)",-1)),$e(u("input",{class:"input","onUpdate:modelValue":K[2]||(K[2]=W=>a.value=W),placeholder:"用户名、工号或邮箱"},null,512),[[De,a.value]])]),u("div",jw,[K[9]||(K[9]=u("label",null,"密码(必填)",-1)),u("div",Dw,[$e(u("input",{class:"input","onUpdate:modelValue":K[3]||(K[3]=W=>c.value=W),placeholder:"输入或点击生成"},null,512),[[De,c.value]]),u("button",{class:"btn btn-sm",onClick:k},"生成")])]),u("div",Rw,[K[10]||(K[10]=u("label",null,"备注",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":K[4]||(K[4]=W=>d.value=W),placeholder:"用途、到期时间、负责人等(选填)"},null,512),[[De,d.value]])])]),h.value?(F(),q("div",Lw,re(h.value),1)):Ee("",!0)]),u("div",Kw,[u("button",{class:"btn btn-sm",onClick:K[5]||(K[5]=W=>s("cancel"))},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:D},"保存")])],8,$w)])):Ee("",!0)]),_:1})]))}}),Nw=Gt(Fw,[["__scopeId","data-v-f383b0a6"]]),hf=15e4;function Ho(e){const t=new Uint8Array(e);let n="";for(let s=0;s{n.value&&(Jo(),n.value=!1,y.value=[],k.value={},qe("长时间未操作,密码库已自动锁定"))},P_)}function A(){n.value&&ee()}fn(async()=>{t.value=await mf(),window.addEventListener("click",A),window.addEventListener("keydown",A),n.value&&ee()}),dr(()=>{window.removeEventListener("click",A),window.removeEventListener("keydown",A),ce!==null&&window.clearTimeout(ce)});const x=it(()=>{const G=m.value.trim().toLowerCase();return G?y.value.filter(X=>(X.system+" "+X.account+" "+(X.remark||"")).toLowerCase().includes(G)):y.value});async function ie(){if(!s.value){if(c.value="",!o.value){c.value="请输入主密码";return}if(o.value.length<6){c.value="主密码至少 6 位";return}if(o.value!==a.value){c.value="两次输入的主密码不一致";return}s.value=!0;try{await Bw(o.value),o.value="",a.value="",n.value=!0,ee(),await le(),qe("主密码已设置,密码库已解锁")}catch(G){c.value=G instanceof Error?G.message:"设置失败"}s.value=!1}}async function Ce(){if(!s.value){if(h.value="",!d.value){h.value="请输入主密码";return}s.value=!0;try{await Uw(d.value),d.value="",n.value=!0,ee(),await le()}catch(G){h.value=G instanceof Error?G.message:"解锁失败"}s.value=!1}}function J(){Jo(),n.value=!1,y.value=[],k.value={},ce!==null&&window.clearTimeout(ce),qe("密码库已锁定")}async function xe(G){const X=G.id;if(k.value[X]){k.value[X]=!1;return}try{G.passwordPlain=await ca(X),k.value[X]=!0}catch(ke){qe(ke instanceof Error?ke.message:"解密失败")}}async function Ne(G){try{const X=await ca(G.id);await Pa(X),qe("密码已复制")}catch(X){qe(X instanceof Error?X.message:"复制失败")}}async function Xe(G){await Pa(G.account),qe("账号已复制")}function He(){O.value=null,K.value={system:"",account:"",password:"",remark:""},D.value=!0}async function Ue(G){try{const X=await ca(G.id);O.value=G.id,K.value={system:G.system,account:G.account,password:X,remark:G.remark||""},D.value=!0}catch(X){qe(X instanceof Error?X.message:"解密失败")}}async function ge(G){const X=O.value??void 0;await zw(G,X),D.value=!1,await le(),qe(X?"账号已更新":"账号已添加")}async function Me(){W.value&&W.value.id&&(await Gw(W.value.id),qe("账号已删除")),W.value=null,await le()}function Ke(){Z.value="",E.value="",L.value="",Q.value="",de.value=!0}async function fe(){Q.value="";try{const G=await Yw(Z.value,E.value);de.value=!1,Z.value="",E.value="",L.value="",qe("主密码已修改,"+G+" 条账号密码已重新加密")}catch(G){Q.value=G instanceof Error?G.message:"修改失败"}}return(G,X)=>(F(),q("div",Xw,[t.value===null?(F(),q("div",Qw,"加载中")):n.value?(F(),q(Re,{key:2},[u("div",o_,[u("div",i_,[Oe(lt,{name:"search",size:14,class:"search-icon"}),$e(u("input",{class:"input","onUpdate:modelValue":X[3]||(X[3]=ke=>m.value=ke),placeholder:"搜索系统名称、账号或备注"},null,512),[[De,m.value]])]),X[16]||(X[16]=u("span",{class:"flex1"},null,-1)),u("button",{class:"btn btn-sm",onClick:Ke},"修改主密码"),u("button",{class:"btn btn-sm",onClick:J},"锁定"),u("button",{class:"btn btn-primary btn-sm",onClick:He},"新增账号")]),u("div",a_,[u("table",l_,[X[18]||(X[18]=u("thead",null,[u("tr",null,[u("th",null,"系统名称"),u("th",null,"账号"),u("th",null,"密码"),u("th",null,"备注"),u("th",{class:"th-ops"},"操作")])],-1)),u("tbody",null,[(F(!0),q(Re,null,ut(x.value,ke=>(F(),q("tr",{key:ke.id},[u("td",u_,re(ke.system),1),u("td",null,[u("span",{class:"copyable",title:"点击复制账号",onClick:st=>Xe(ke)},re(ke.account),9,c_)]),u("td",null,[u("div",f_,[u("span",d_,re(k.value[ke.id]?ke.passwordPlain:"........"),1),u("button",{class:"btn btn-xs",onClick:st=>xe(ke)},re(k.value[ke.id]?"隐藏":"显示"),9,p_),u("button",{class:"btn btn-xs",onClick:st=>Ne(ke)},"复制",8,h_)])]),u("td",v_,re(ke.remark||"--"),1),u("td",null,[u("div",m_,[u("button",{class:"btn btn-xs",onClick:st=>Ue(ke)},"编辑",8,y_),u("button",{class:"btn btn-xs",onClick:st=>W.value=ke},"删除",8,g_)])])]))),128)),x.value.length?Ee("",!0):(F(),q("tr",b_,[...X[17]||(X[17]=[u("td",{colspan:"5",class:"empty muted"},"暂无账号,点击右上角新增",-1)])]))])])]),u("div",w_,"共 "+re(y.value.length)+" 条账号记录 · 密码以 AES-256-GCM 加密存储于本机",1)],64)):(F(),q("div",Zw,[u("div",e_,[Oe(lt,{name:"lock",size:26})]),t.value===!1?(F(),q(Re,{key:0},[X[12]||(X[12]=u("div",{class:"lock-title"},"设置主密码",-1)),X[13]||(X[13]=u("div",{class:"muted lock-tip"},"主密码用于加密保存在本机的账号密码,遗忘后无法找回,请务必牢记",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[0]||(X[0]=ke=>o.value=ke),placeholder:"设置主密码(至少 6 位)",onKeydown:jt(ie,["enter"])},null,544),[[De,o.value]]),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[1]||(X[1]=ke=>a.value=ke),placeholder:"再次输入主密码",onKeydown:jt(ie,["enter"])},null,544),[[De,a.value]]),c.value?(F(),q("div",t_,re(c.value),1)):Ee("",!0),u("button",{class:"btn btn-primary lock-btn",disabled:s.value,onClick:ie},"完成设置并解锁",8,n_)],64)):(F(),q(Re,{key:1},[X[14]||(X[14]=u("div",{class:"lock-title"},"密码库已锁定",-1)),X[15]||(X[15]=u("div",{class:"muted lock-tip"},"输入主密码解锁后查看与复制密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[2]||(X[2]=ke=>d.value=ke),placeholder:"主密码",onKeydown:jt(Ce,["enter"])},null,544),[[De,d.value]]),h.value?(F(),q("div",r_,re(h.value),1)):Ee("",!0),u("button",{class:"btn btn-primary lock-btn",disabled:s.value,onClick:Ce},"解锁",8,s_)],64))])),Oe(Nw,{open:D.value,title:O.value?"编辑账号":"新增账号",initial:K.value,onCancel:X[4]||(X[4]=ke=>D.value=!1),onSave:ge},null,8,["open","title","initial"]),Oe(ur,{open:!!W.value,title:"删除确认",message:W.value?"将删除系统「"+W.value.system+"」的账号记录。删除后不可恢复。":"","confirm-text":"删除",danger:"",onCancel:X[5]||(X[5]=ke=>W.value=null),onConfirm:Me},null,8,["open","message"]),(F(),It(Vs,{to:"body"},[Oe(ns,{name:"modal"},{default:fr(()=>[de.value?(F(),q("div",{key:0,class:"mask",onClick:X[11]||(X[11]=Mr(ke=>de.value=!1,["self"]))},[u("div",__,[u("div",k_,[X[19]||(X[19]=u("span",{class:"dialog-title"},"修改主密码",-1)),u("button",{class:"icon-btn",title:"关闭",onClick:X[6]||(X[6]=ke=>de.value=!1)},[Oe(lt,{name:"close",size:16})])]),u("div",x_,[u("div",C_,[X[20]||(X[20]=u("label",null,"旧主密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[7]||(X[7]=ke=>Z.value=ke)},null,512),[[De,Z.value]])]),u("div",S_,[X[21]||(X[21]=u("label",null,"新主密码(至少 6 位)",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[8]||(X[8]=ke=>E.value=ke)},null,512),[[De,E.value]])]),u("div",E_,[X[22]||(X[22]=u("label",null,"确认新主密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":X[9]||(X[9]=ke=>L.value=ke)},null,512),[[De,L.value]])]),Q.value?(F(),q("div",$_,re(Q.value),1)):Ee("",!0),X[23]||(X[23]=u("div",{class:"muted vp-tip"},"确认后所有账号密码将使用新主密码重新加密",-1))]),u("div",A_,[u("button",{class:"btn btn-sm",onClick:X[10]||(X[10]=ke=>de.value=!1)},"取消"),u("button",{class:"btn btn-primary btn-sm",onClick:fe},"确认修改")])])])):Ee("",!0)]),_:1})]))]))}}),O_=Gt(T_,[["__scopeId","data-v-6820bc9c"]]);function M_(e){return'"'+(e==null?"":String(e)).replace(/"/g,'""')+'"'}async function Iu(e,t){const s="\uFEFF"+t.map(d=>d.map(M_).join(",")).join(`\r +`);if(Zr.isNativePlatform()){const{downloadText:d}=await cf(async()=>{const{downloadText:h}=await Promise.resolve().then(()=>mg);return{downloadText:h}},void 0,import.meta.url);return d(e,s)}const o=new Blob([s],{type:"text/csv;charset=utf-8"}),a=URL.createObjectURL(o),c=document.createElement("a");return c.href=a,c.download=e,c.click(),window.setTimeout(()=>URL.revokeObjectURL(a),1e4),""}class I_ extends Ir{constructor(){super("intern_worklog_users"),this.version(1).stores({user:"id, &username"})}}const Or=new I_,vi="intern_worklog",rl="dsh_session_user";function mi(){try{const e=localStorage.getItem(rl);if(!e)return null;const t=JSON.parse(e);if(t&&t.userId&&t.username)return t}catch{}return null}function gf(e){localStorage.setItem(rl,JSON.stringify(e))}function bf(){localStorage.removeItem(rl)}const sl="dsh_cloud_creds";function wf(e,t){localStorage.setItem(sl,JSON.stringify({username:e,password:t}))}function yi(){try{const e=localStorage.getItem(sl);if(!e)return null;const t=JSON.parse(e);if(t&&t.username&&t.password)return t}catch{}return null}function _f(){localStorage.removeItem(sl)}function ol(e){zh(new rf(vi+"_"+e))}async function j_(e,t,n){const s=e.trim();if(s.length<2||s.length>20)throw new Error("用户名需 2 到 20 个字符");if(t.length<6)throw new Error("登录密码至少 6 位");if(await Or.user.where("username").equals(s).first())throw new Error("用户名已存在");const a=nl(),c=await zo(t,a),d="u_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6);await Or.user.add({id:d,username:s,pwd_hash:c,pwd_salt:a,created_at:new Date().toISOString()}),ol(d);let h=0;n&&await kf()&&(h=await F_(),await Or.user.update(d,{legacy_imported_at:new Date().toISOString()}));const y={userId:d,username:s};return gf(y),wf(y.username,t),h&&N_(h),y}async function D_(e,t){const n=e.trim(),s=await Or.user.where("username").equals(n).first();if(!s)throw new Error("用户不存在");if(await zo(t,s.pwd_salt)!==s.pwd_hash)throw new Error("密码不正确");ol(s.id);const a={userId:s.id,username:s.username};return gf(a),wf(a.username,t),a}async function R_(){Jo(),sf(),bf(),_f()}async function L_(e,t){const n=mi();if(!n)throw new Error("未登录");if(t.length<6)throw new Error("新密码至少 6 位");const s=await Or.user.get(n.userId);if(!s)throw new Error("用户不存在");if(await zo(e,s.pwd_salt)!==s.pwd_hash)throw new Error("旧密码不正确");const a=nl(),c=await zo(t,a);await Or.user.update(s.id,{pwd_hash:c,pwd_salt:a})}async function K_(){const e=mi();if(!e)throw new Error("未登录");Jo(),sf(),await Ir.delete(vi+"_"+e.userId),await Or.user.delete(e.userId),bf(),_f()}async function kf(){return Ir.exists(vi)}async function F_(){if(!ne)throw new Error("用户数据库未就绪");const e=new rf(vi),t=await Promise.all([e.project.toArray(),e.work_log.toArray(),e.log_item.toArray(),e.attendance.toArray(),e.weekly_note.toArray(),e.setting.toArray(),e.memo.toArray(),e.credential.toArray()]);await ne.transaction("rw",[ne.project,ne.work_log,ne.log_item,ne.attendance,ne.weekly_note,ne.setting,ne.memo,ne.credential],async()=>{await Promise.all([ne.project.clear(),ne.work_log.clear(),ne.log_item.clear(),ne.attendance.clear(),ne.weekly_note.clear(),ne.setting.clear(),ne.memo.clear(),ne.credential.clear()]),t[0].length&&await ne.project.bulkAdd(t[0]),t[1].length&&await ne.work_log.bulkAdd(t[1]),t[2].length&&await ne.log_item.bulkAdd(t[2]),t[3].length&&await ne.attendance.bulkAdd(t[3]),t[4].length&&await ne.weekly_note.bulkAdd(t[4]),t[5].length&&await ne.setting.bulkAdd(t[5]),t[6].length&&await ne.memo.bulkAdd(t[6]),t[7].length&&await ne.credential.bulkAdd(t[7])});const n=t[0].length+t[1].length+t[2].length+t[3].length+t[4].length+t[6].length+t[7].length;return e.close(),n}function N_(e){try{sessionStorage.setItem("dsh_migrate_toast",String(e))}catch{}}const V_="https://daywk.linyux.cn",Xo=["project","work_log","log_item","attendance","weekly_note","setting","memo","credential","transaction"],Ta=new Set(["sync_cursor","sync_last_time","sync_token","last_project","last_category"]);function B_(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function ju(e){const t={...e};return delete t.id,t}function Du(e){return JSON.stringify(e)}async function U_(e){return ne.table(e).toArray()}function Oa(e,t){return e==="setting"?t.key:t.id}async function q_(){for(const e of Xo){const t=ne.table(e),n=await t.toArray();for(const s of n){if(e==="setting"&&Ta.has(s.key))continue;const o={};s.uuid||(o.uuid=B_()),s.updated_at||(o.updated_at=s.created_at||wt()),Object.keys(o).length&&await t.update(Oa(e,s),o)}}}async function il(){return await yt("sync_base_url","")||V_}async function xf(){const e=yi();if(!e)throw new Error("未登录,无法同步");return{baseUrl:await il(),username:e.username,password:e.password}}async function H_(){return Ef(await xf())}async function Cf(){const e=yi();if(!e)throw new Error("未登录");const t=await il(),n={"Content-Type":"application/json"},s=JSON.stringify({username:e.username,password:e.password});let o=await fetch(t+"/api/auth/register",{method:"POST",headers:n,body:s});if(o.status===409){if(o=await fetch(t+"/api/auth/login",{method:"POST",headers:n,body:s}),!o.ok)throw new Error("云端已存在同名账号且密码不一致,请检查")}else if(!o.ok)throw new Error("云端绑定失败:"+o.status)}async function W_(){return yi()!=null}async function z_(){return yt("sync_last_time","")}async function Sf(e,t){const n=await fetch(e+"/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:t.username.trim(),password:t.password})});if(!n.ok)throw new Error("云端账号或密码不正确");const s=await n.json();if(!s||!s.token)throw new Error("云端登录异常");return String(s.token)}async function G_(e,t){let n=await yt("sync_token","");return n||(n=await Sf(e,t),await kt("sync_token",n),n)}let $s=!1,To=!1,Ma=!1,Gr=null,wn=null,Ia="",Ru=!1,Oo=null;async function Yr(){if($s){To=!0;return}try{if(!await W_())return;await Ef(await xf())}catch{}}function Y_(){if(Ru)return;Ru=!0,Oo=Wh(async()=>{const t={};for(const n of Xo)t[n]=await ne.table(n).count();return t}).subscribe({next:()=>{Ma||$s||(Gr&&globalThis.clearTimeout(Gr),Gr=globalThis.setTimeout(()=>{Yr()},3e3))},error:()=>{}})}function J_(){Oo&&(Oo.unsubscribe(),Oo=null),wn&&(wn.close(),wn=null,Ia=""),Gr&&(globalThis.clearTimeout(Gr),Gr=null)}function X_(e,t){const n=e+"|"+t;if(!(wn&&Ia===n)){wn&&(wn.close(),wn=null);try{wn=new EventSource(e+"/api/events?token="+encodeURIComponent(t)),Ia=n,wn.onmessage=()=>{Yr()}}catch{wn=null}}}async function Ef(e){if($s)return To=!0,{pushed:0,pulled:0,removed:0,at:""};$s=!0,Ma=!0;try{const t=await Q_(e);return To&&(To=!1,globalThis.setTimeout(()=>{Yr()},800)),t}finally{$s=!1,Ma=!1}}async function Q_(e){const t=e.baseUrl.trim().replace(/\/+$/,"");if(!t)throw new Error("请先配置同步服务地址");await q_();const n=await ne.sync_mirror.toArray(),s=new Map;for(const Z of n)s.set(Z.table+"|"+Z.uuid,Z);const o={},a=[];let c=0;for(const Z of Xo){let E=await U_(Z);Z==="setting"&&(E=E.filter(Q=>!Ta.has(Q.key)));const L=new Map;for(const Q of E)L.set(Q.uuid,Q);for(const[Q,le]of L){const ce=ju(le),ee=Du(ce),A=s.get(Z+"|"+Q);(!A||A.hash!==ee)&&(o[Z]=o[Z]||[],o[Z].push(ce),c++)}for(const[Q,le]of s)Q.startsWith(Z+"|")&&!L.has(le.uuid)&&a.push({table:Z,uuid:le.uuid,deleted_at:wt()});o[Z]=o[Z]||[]}const d=await G_(t,e),h=Z=>fetch(t+"/api/sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+Z},body:JSON.stringify({device:"client",tables:o,tombstones:a})});let y=await h(d);if(y.status===401){await kt("sync_token","");const Z=await Sf(t,e);await kt("sync_token",Z),y=await h(Z)}if(!y.ok)throw new Error("同步服务返回 "+y.status);const m=await y.json(),k=m.tables||{},D=m.tombstones||[];let O=0,K=0;const W=[];for(const Z of Xo){const E=ne.table(Z),L=await E.toArray(),Q=new Map;for(const x of L)Q.set(x.uuid,x);const le=k[Z]||[],ce=new Map;for(const x of le)ce.set(x.uuid,x);const ee=new Set(D.filter(x=>x.table===Z).map(x=>x.uuid));for(const[x,ie]of Q)ee.has(x)&&(await E.delete(Oa(Z,ie)),K++);for(const x of le){if(ee.has(x.uuid))continue;const ie=Q.get(x.uuid);if(!ie)await E.add({...x}),O++;else{const Ce=String(ie.updated_at||"");if(String(x.updated_at||"")>Ce){const xe={...x};Z==="setting"&&delete xe.key,await E.update(Oa(Z,ie),xe),O++}}}const A=await E.toArray();for(const x of A)Z==="setting"&&Ta.has(x.key)||W.push({table:Z,uuid:x.uuid,hash:Du(ju(x))})}await ne.sync_mirror.clear(),W.length&&await ne.sync_mirror.bulkAdd(W.map(Z=>({...Z}))),X_(t,d);const de=wt();return await kt("sync_last_time",de),{pushed:c,pulled:O,removed:K,at:de}}const Z_={class:"settings"},e1={class:"card section"},t1={class:"muted acc-line"},n1={class:"ai-grid"},r1={class:"rule-item"},s1={class:"rule-item"},o1={class:"rule-item"},i1={key:0,class:"form-error"},a1={class:"rule-save"},l1={class:"card section"},u1={class:"rule-grid"},c1={class:"rule-item"},f1={class:"rule-item"},d1={class:"rule-item"},p1={class:"rule-item"},h1={class:"rule-item"},v1={class:"card section"},m1={class:"proj-add"},y1={key:0,class:"muted proj-tip"},g1=["onKeydown"],b1=["onClick"],w1=["onClick"],_1=["onClick"],k1={key:1,class:"muted"},x1={class:"card section"},C1={class:"card section"},S1={class:"muted acc-line"},E1={class:"rule-item"},$1={class:"rule-save"},A1=["disabled"],P1={key:0,class:"muted acc-line"},T1={key:1,class:"form-error"},O1={class:"card section"},M1={class:"ai-grid"},I1={class:"rule-item"},j1={class:"rule-item"},D1={class:"rule-item"},R1={class:"card section"},L1={class:"backup-row"},K1={key:0,class:"import-error"},F1=Vt({__name:"SettingsView",setup(e){var je;const t=N({work_start:"09:00",work_end:"18:00",grace_minutes:10,lunch_minutes:60,remind_weekly:"friday"}),n=N([]),s=N(""),o=N(""),a=N(""),c=N(""),d=N(""),h=N(""),y=N(null),m=N(""),k=N(null),D=N(null),O=N(""),K=N(((je=mi())==null?void 0:je.username)||""),W=N(""),de=N(""),Z=N(""),E=N(""),L=N(!1),Q="0.2.0",le=N(""),ce=N(""),ee=N(""),A=N(""),x=N(!1),ie=N("");async function Ce(){var w;le.value=await il(),ce.value=((w=yi())==null?void 0:w.username)||"",ie.value=await z_()}async function J(){await kt("sync_base_url",le.value.trim()),qe("同步地址已保存")}async function xe(){A.value="";try{await Cf(),qe("云端绑定已重建")}catch(w){A.value=w instanceof Error?w.message:"绑定失败"}}async function Ne(){if(!x.value){A.value="",x.value=!0;try{await J();const w=await H_();ie.value=w.at,ee.value="推送 "+w.pushed+" 条 · 拉取 "+w.pulled+" 条 · 删除 "+w.removed+" 条",qe("同步完成")}catch(w){A.value=w instanceof Error?w.message:"同步失败"}x.value=!1}}async function Xe(){if(E.value="",de.value!==Z.value){E.value="两次输入的新密码不一致";return}try{await L_(W.value,de.value),W.value="",de.value="",Z.value="",qe("登录密码已修改")}catch(w){E.value=w instanceof Error?w.message:"修改失败"}}async function He(){await K_(),window.location.reload()}async function Ue(){t.value=await jr(),n.value=await Ks(!0),a.value=(await Za()).join(` +`),c.value=await yt("ai_base_url",""),d.value=await yt("ai_api_key",""),h.value=await yt("ai_model",""),await Ce()}async function ge(){await kt("ai_base_url",c.value.trim()),await kt("ai_api_key",d.value.trim()),await kt("ai_model",h.value.trim()),qe("AI 配置已保存")}async function Me(){const w=xt(),g=await Promise.all([pi("2000-01-01",w),Ks(!0)]),P=g[0],ae=g[1],se=new Map(ae.map(oe=>[oe.id,oe.name])),ue=[["日期","分类","项目","内容","耗时(分钟)","成果","待跟进","收获","备注"]];for(const oe of P)ue.push([oe.date,Qa(oe.category),oe.project_id&&se.get(oe.project_id)||"",oe.content,oe.minutes==null?"":oe.minutes,oe.is_milestone?"是":"",oe.needs_followup?"是":"",oe.takeaway||"",oe.remark||""]);const ye=await Iu("工作记录_"+w.replace(/-/g,"")+".csv",ue);qe(ye?"CSV 已导出到:"+ye:"CSV 已导出到系统下载目录")}async function Ke(){const w=xt(),g=await Promise.all([jr(),di("2000-01-01",w)]),P=g[0],ae=g[1],se=["周日","周一","周二","周三","周四","周五","周六"],ue=[["日期","星期","状态","上班时间","下班时间","地点","类型","说明"]];for(const oe of ae){const we=qs(oe,oe.date,P,oe.date===w);ue.push([oe.date,se[rs(oe.date).getDay()],we.label,oe.clock_in_at?Vn(oe.clock_in_at):"",oe.clock_out_at?Vn(oe.clock_out_at):"",oe.location||"",oe.kind==="makeup"?"补卡":oe.kind==="leave"?"休假":"正常",oe.note||""])}const ye=await Iu("考勤记录_"+w.replace(/-/g,"")+".csv",ue);qe(ye?"CSV 已导出到:"+ye:"CSV 已导出到系统下载目录")}fn(Ue);async function fe(){await kt("work_start",t.value.work_start),await kt("work_end",t.value.work_end),await kt("grace_minutes",String(t.value.grace_minutes)),await kt("lunch_minutes",String(t.value.lunch_minutes)),await kt("remind_weekly",t.value.remind_weekly),qe("打卡规则已保存")}async function G(){await af(a.value.split(` +`)),qe("常用地点已保存")}async function X(){const w=s.value.trim();if(w){try{await bv(w),o.value="",s.value=""}catch{o.value="项目名已存在"}await Ue()}}function ke(w){y.value=w.id,m.value=w.name}async function st(w){const g=m.value.trim();if(g)try{await wv(w.id,g),o.value=""}catch{o.value="项目名已存在"}y.value=null,await Ue()}async function pt(w){await _v(w.id,w.archived!==1),await Ue()}async function ht(){try{const w=await Hv(),g=await tl("实习日志备份_"+xt().replace(/-/g,"")+".json",w);qe(g?"备份已导出到:"+g:"备份已导出到系统下载目录")}catch(w){qe("导出失败:"+(w instanceof Error?w.message:String(w)))}}function Yt(w){const g=w.target,P=g.files&&g.files[0];if(O.value="",!P)return;const ae=P.name;P.text().then(se=>{D.value={name:ae,text:se}}),g.value=""}async function Jt(){if(D.value)try{await Wv(D.value.text),D.value=null,O.value="",await Ue(),qe("数据导入完成")}catch(w){D.value=null,O.value=w instanceof Error?w.message:"导入失败"}}return(w,g)=>(F(),q("div",Z_,[u("div",e1,[g[23]||(g[23]=u("div",{class:"section-title"},"账号与隐私",-1)),u("div",t1,"版本 v"+re(Qt(Q))+" · 当前用户:"+re(K.value)+" · 每位用户独立数据库隔离存储于本机 · 登录密码仅保存 PBKDF2 哈希",1),u("div",n1,[u("div",r1,[g[20]||(g[20]=u("label",null,"旧登录密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":g[0]||(g[0]=P=>W.value=P)},null,512),[[De,W.value]])]),u("div",s1,[g[21]||(g[21]=u("label",null,"新登录密码(至少 6 位)",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":g[1]||(g[1]=P=>de.value=P)},null,512),[[De,de.value]])]),u("div",o1,[g[22]||(g[22]=u("label",null,"确认新登录密码",-1)),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":g[2]||(g[2]=P=>Z.value=P)},null,512),[[De,Z.value]])])]),E.value?(F(),q("div",i1,re(E.value),1)):Ee("",!0),u("div",a1,[u("button",{class:"btn btn-primary btn-sm",onClick:Xe},"修改登录密码"),u("button",{class:"btn btn-sm btn-danger",onClick:g[3]||(g[3]=P=>L.value=!0)},"删除此用户及全部数据")])]),u("div",l1,[g[30]||(g[30]=u("div",{class:"section-title"},"打卡规则",-1)),u("div",u1,[u("div",c1,[g[24]||(g[24]=u("label",null,"上班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":g[4]||(g[4]=P=>t.value.work_start=P)},null,512),[[De,t.value.work_start]])]),u("div",f1,[g[25]||(g[25]=u("label",null,"下班时间",-1)),$e(u("input",{type:"time",class:"input","onUpdate:modelValue":g[5]||(g[5]=P=>t.value.work_end=P)},null,512),[[De,t.value.work_end]])]),u("div",d1,[g[26]||(g[26]=u("label",null,"迟到宽限(分钟)",-1)),$e(u("input",{type:"number",class:"input",min:"0","onUpdate:modelValue":g[6]||(g[6]=P=>t.value.grace_minutes=P)},null,512),[[De,t.value.grace_minutes,void 0,{number:!0}]])]),u("div",p1,[g[27]||(g[27]=u("label",null,"午休扣除(分钟)",-1)),$e(u("input",{type:"number",class:"input",min:"0","onUpdate:modelValue":g[7]||(g[7]=P=>t.value.lunch_minutes=P)},null,512),[[De,t.value.lunch_minutes,void 0,{number:!0}]])]),u("div",h1,[g[29]||(g[29]=u("label",null,"周记提醒",-1)),$e(u("select",{class:"select","onUpdate:modelValue":g[8]||(g[8]=P=>t.value.remind_weekly=P)},[...g[28]||(g[28]=[u("option",{value:"friday"},"每周五提醒",-1),u("option",{value:"off"},"关闭",-1)])],512),[[Fn,t.value.remind_weekly]])])]),u("div",{class:"rule-save"},[u("button",{class:"btn btn-primary btn-sm",onClick:fe},"保存规则")])]),u("div",v1,[g[31]||(g[31]=u("div",{class:"section-title"},"项目管理",-1)),u("div",m1,[$e(u("input",{class:"input","onUpdate:modelValue":g[9]||(g[9]=P=>s.value=P),placeholder:"新项目名称",onKeydown:jt(X,["enter"])},null,544),[[De,s.value]]),u("button",{class:"btn btn-sm",onClick:X},"添加")]),o.value?(F(),q("div",y1,re(o.value),1)):Ee("",!0),(F(!0),q(Re,null,ut(n.value,P=>(F(),q("div",{key:P.id,class:"proj-row"},[y.value===P.id?(F(),q(Re,{key:0},[$e(u("input",{class:"input","onUpdate:modelValue":g[10]||(g[10]=ae=>m.value=ae),onKeydown:jt(ae=>st(P),["enter"])},null,40,g1),[[De,m.value]]),u("button",{class:"btn btn-sm",onClick:ae=>st(P)},"保存",8,b1),u("button",{class:"btn btn-sm",onClick:g[11]||(g[11]=ae=>y.value=null)},"取消")],64)):(F(),q(Re,{key:1},[u("span",{class:et(["proj-name",{archived:P.archived===1}])},re(P.name),3),u("button",{class:"icon-btn",title:"重命名",onClick:ae=>ke(P)},[Oe(lt,{name:"edit",size:14})],8,w1),u("button",{class:"btn btn-sm",onClick:ae=>pt(P)},re(P.archived===1?"恢复":"归档"),9,_1)],64))]))),128)),n.value.length?Ee("",!0):(F(),q("div",k1,"暂无项目,先添加一个"))]),u("div",x1,[g[33]||(g[33]=u("div",{class:"section-title"},"常用地点",-1)),$e(u("textarea",{class:"textarea","onUpdate:modelValue":g[12]||(g[12]=P=>a.value=P),placeholder:"每行一个地点,如:公司、客户现场、出差、居家办公"},null,512),[[De,a.value]]),u("div",{class:"rule-save"},[u("button",{class:"btn btn-primary btn-sm",onClick:G},"保存地点"),g[32]||(g[32]=u("span",{class:"muted loc-note"},"打卡时可直接输入新地点,保存后自动加入列表",-1))])]),u("div",C1,[g[35]||(g[35]=u("div",{class:"section-title"},"多端数据同步",-1)),u("div",S1,"云端账号:"+re(ce.value||"未绑定")+" · 登录即自动绑定并同步(变更实时推送 + 每 5 分钟兜底);密码库以密文同步,主密码永不出本机",1),u("div",E1,[g[34]||(g[34]=u("label",null,"同步服务地址(默认即可)",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[13]||(g[13]=P=>le.value=P),placeholder:"https://daywk.linyux.cn"},null,512),[[De,le.value]])]),u("div",$1,[u("button",{class:"btn btn-sm",onClick:J},"保存地址"),u("button",{class:"btn btn-primary btn-sm",disabled:x.value,onClick:Ne},re(x.value?"同步中":"立即同步"),9,A1),u("button",{class:"btn btn-sm",onClick:xe},"重建云端绑定")]),ee.value?(F(),q("div",P1,"上次同步:"+re(ie.value||"--")+" · "+re(ee.value),1)):Ee("",!0),A.value?(F(),q("div",T1,re(A.value),1)):Ee("",!0)]),u("div",O1,[g[40]||(g[40]=u("div",{class:"section-title"},"AI 润色配置(可选)",-1)),u("div",M1,[u("div",I1,[g[36]||(g[36]=u("label",null,"接口地址(OpenAI 兼容,到 /v1 为止)",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[14]||(g[14]=P=>c.value=P),placeholder:"https://api.example.com/v1"},null,512),[[De,c.value]])]),u("div",j1,[g[37]||(g[37]=u("label",null,"API Key",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[15]||(g[15]=P=>d.value=P),placeholder:"sk-..."},null,512),[[De,d.value]])]),u("div",D1,[g[38]||(g[38]=u("label",null,"模型名称",-1)),$e(u("input",{class:"input","onUpdate:modelValue":g[16]||(g[16]=P=>h.value=P),placeholder:"如:deepseek-chat"},null,512),[[De,h.value]])])]),u("div",{class:"rule-save"},[u("button",{class:"btn btn-primary btn-sm",onClick:ge},"保存 AI 配置"),g[39]||(g[39]=u("span",{class:"muted loc-note"},"配置仅保存在本机浏览器;总结页可用 AI 润色草稿,需服务端允许浏览器跨域",-1))])]),u("div",R1,[g[41]||(g[41]=u("div",{class:"section-title"},"数据备份",-1)),u("div",L1,[u("button",{class:"btn btn-sm",onClick:ht},"导出 JSON 备份"),u("button",{class:"btn btn-sm",onClick:g[17]||(g[17]=P=>{var ae;return(ae=k.value)==null?void 0:ae.click()})},"导入 JSON 备份"),u("button",{class:"btn btn-sm",onClick:Me},"导出工作记录 CSV"),u("button",{class:"btn btn-sm",onClick:Ke},"导出考勤 CSV"),u("input",{ref_key:"fileInput",ref:k,type:"file",accept:"application/json,.json",style:{display:"none"},onChange:Yt},null,544)]),O.value?(F(),q("div",K1,re(O.value),1)):Ee("",!0),g[42]||(g[42]=u("div",{class:"muted backup-note"},"数据保存在浏览器 IndexedDB 中,建议定期导出 JSON 备份。",-1))]),Oe(ur,{open:!!D.value,title:"导入确认",message:D.value?"将从文件「"+D.value.name+"」导入备份。现有全部数据将被覆盖,且不可恢复,请先确认已导出当前备份。":"","confirm-text":"覆盖导入",danger:"",onCancel:g[18]||(g[18]=P=>D.value=null),onConfirm:Jt},null,8,["open","message"]),Oe(ur,{open:L.value,title:"删除用户确认",message:"将永久删除用户「"+K.value+"」及其全部数据:工作日志、考勤、备忘录、账号密码库都将被清除,且不可恢复。请确认。","confirm-text":"永久删除",danger:"",onCancel:g[19]||(g[19]=P=>L.value=!1),onConfirm:He},null,8,["open","message"])]))}}),N1=Gt(F1,[["__scopeId","data-v-81598f02"]]),V1={class:"login-page"},B1={class:"card login-card"},U1={class:"login-brand"},q1={class:"brand-icon"},H1={class:"seg"},W1=["placeholder"],z1={key:1,class:"mig-row"},G1={key:2,class:"form-error"},Y1=["disabled"],J1=Vt({__name:"LoginView",emits:["login"],setup(e,{emit:t}){const n=t,s=N("login"),o=N(""),a=N(""),c=N(""),d=N(!0),h=N(!1),y=N(""),m=N(!1);fn(async()=>{h.value=await kf()});function k(O){s.value=O,y.value="",c.value=""}async function D(){if(!m.value){y.value="",m.value=!0;try{let O;if(s.value==="login")O=await D_(o.value,a.value);else{if(a.value.length<6){y.value="登录密码至少 6 位",m.value=!1;return}if(a.value!==c.value){y.value="两次输入的密码不一致",m.value=!1;return}O=await j_(o.value,a.value,d.value)}n("login",O)}catch(O){y.value=O instanceof Error?O.message:"操作失败"}m.value=!1}}return(O,K)=>(F(),q("div",V1,[u("div",B1,[u("div",U1,[u("div",q1,[Oe(lt,{name:"calendar",size:22})]),K[6]||(K[6]=u("div",{class:"login-title"},"实习工作日志",-1)),K[7]||(K[7]=u("div",{class:"muted login-sub"},"打卡 · 记录 · 总结 · 备忘录 · 密码库",-1)),K[8]||(K[8]=u("div",{class:"muted login-sub"},"每位用户独立数据库,数据彼此隔离并保存在本机",-1))]),u("div",H1,[u("button",{class:et(["seg-btn",{active:s.value==="login"}]),onClick:K[0]||(K[0]=W=>k("login"))},"登录",2),u("button",{class:et(["seg-btn",{active:s.value==="create"}]),onClick:K[1]||(K[1]=W=>k("create"))},"创建用户",2)]),$e(u("input",{class:"input","onUpdate:modelValue":K[2]||(K[2]=W=>o.value=W),placeholder:"用户名(2 到 20 个字符)",onKeydown:jt(D,["enter"])},null,544),[[De,o.value]]),$e(u("input",{type:"password",class:"input","onUpdate:modelValue":K[3]||(K[3]=W=>a.value=W),placeholder:s.value==="login"?"登录密码":"设置登录密码(至少 6 位)",onKeydown:jt(D,["enter"])},null,40,W1),[[De,a.value]]),s.value==="create"?$e((F(),q("input",{key:0,type:"password",class:"input","onUpdate:modelValue":K[4]||(K[4]=W=>c.value=W),placeholder:"再次输入密码",onKeydown:jt(D,["enter"])},null,544)),[[De,c.value]]):Ee("",!0),s.value==="create"&&h.value?(F(),q("label",z1,[$e(u("input",{type:"checkbox","onUpdate:modelValue":K[5]||(K[5]=W=>d.value=W)},null,512),[[$h,d.value]]),K[9]||(K[9]=u("span",null,"导入本机原有工作日志数据到此用户(原数据保留不删除)",-1))])):Ee("",!0),y.value?(F(),q("div",G1,re(y.value),1)):Ee("",!0),u("button",{class:"btn btn-primary login-btn",disabled:m.value,onClick:D},re(s.value==="login"?"登录":"创建并进入"),9,Y1),K[10]||(K[10]=u("div",{class:"muted login-note"}," 登录后自动开启云端同步(密码会保存在本机用于云同步);系统只保存密码哈希,忘记密码将无法访问该用户数据 ",-1))])]))}}),X1=Gt(J1,[["__scopeId","data-v-d3d6c8cb"]]),Q1={key:1,class:"app"},Z1={class:"side"},e0=["data-tip","onClick"],t0={class:"main"},n0={class:"topbar"},r0={class:"title"},s0={class:"gsearch"},o0={key:0,class:"gs-panel"},i0={key:0,class:"gs-group muted"},a0=["onMousedown"],l0={class:"tag"},u0={class:"gs-text"},c0={class:"muted num gs-date"},f0={key:1,class:"gs-group muted"},d0=["onMousedown"],p0={class:"gs-text"},h0={class:"muted gs-sub"},v0={key:1,class:"gs-empty muted"},m0={class:"user-chip num"},y0=["disabled"],g0={class:"num"},b0={class:"content"},w0={class:"content-inner"},_0={class:"toast-wrap"},k0=Vt({__name:"App",setup(e){const t=Gv(),n=N(mi());async function s(ge){n.value=ge,location.hash="#/calendar",le.value="calendar",await Ce(),await Ue(),c();try{await Cf(),await Yr()}catch{}showToast("欢迎,"+ge.username);const Me=sessionStorage.getItem("dsh_migrate_toast");Me&&(sessionStorage.removeItem("dsh_migrate_toast"),showToast("已迁移原有数据 "+Me+" 条"))}async function o(){J_(),a!==null&&(window.clearInterval(a),a=null),await R_(),n.value=null,le.value="calendar",location.hash="#/calendar",showToast("已退出登录")}let a=null;function c(){Y_(),a!==null&&window.clearInterval(a),a=window.setInterval(()=>{Yr()},60*1e3),Yr()}const d=N(null),h=N(""),y=N(!1),m=N({logs:[],memos:[]});let k=null;const D=it(()=>!!(m.value.logs.length||m.value.memos.length));function O(){k&&window.clearTimeout(k);const ge=h.value;k=window.setTimeout(async()=>{const Me=ge.trim();if(!Me){m.value={logs:[],memos:[]};return}const Ke=await Promise.all([Kv(Me,8),Fv(Me,4)]);m.value={logs:Ke[0],memos:Ke[1]}},200)}function K(){h.value="",m.value={logs:[],memos:[]},y.value=!1}function W(ge){$a.value=ge.date,ce("calendar"),K()}function de(ge){Aa.value=ge.id,ce("memo"),K()}function Z(){window.setTimeout(()=>{y.value=!1},150)}function E(ge){var Me;(ge.ctrlKey||ge.metaKey)&&ge.key.toLowerCase()==="k"&&(ge.preventDefault(),(Me=d.value)==null||Me.focus())}const L=[{key:"calendar",name:"日历",icon:"calendar"},{key:"today",name:"详情",icon:"edit"},{key:"stats",name:"统计",icon:"chart"},{key:"report",name:"总结",icon:"export"},{key:"ledger",name:"记账",icon:"wallet"},{key:"memo",name:"备忘录",icon:"memo"},{key:"vault",name:"密码库",icon:"lock"},{key:"settings",name:"设置",icon:"settings"}];function Q(){const ge=(location.hash||"").replace("#/","");return L.some(Me=>Me.key===ge)?ge:"calendar"}const le=N(Q());window.addEventListener("hashchange",()=>{le.value=Q()});function ce(ge){location.hash="#/"+ge}const ee=it(()=>L.find(ge=>ge.key===le.value)||L[0]),A=N(xt()),x=N(void 0),ie=N(!1);async function Ce(){if(x.value=await mn(A.value),ie.value=!1,new Date().getHours()<4){const Me=await mn(Kn(A.value,-1));ie.value=!!(Me&&Me.clock_in_at&&!Me.clock_out_at)}}const J=it(()=>{const ge=x.value;return ge&&ge.clock_in_at&&!ge.clock_out_at?!0:ie.value&&!(ge&&ge.clock_in_at)}),xe=it(()=>{const ge=x.value;return!!(ge&&ge.clock_in_at&&ge.clock_out_at)}),Ne=it(()=>{const ge=x.value;return J.value?"下班打卡":xe.value?"已打卡 "+Vn(ge==null?void 0:ge.clock_in_at)+" - "+Vn(ge==null?void 0:ge.clock_out_at):"上班打卡"});async function Xe(){if(J.value)try{await xv()}catch{}else await lf(A.value);await Ce(),Sr()}gt(Hs,()=>{n.value&&Ce()});const He=N(!1);async function Ue(){if((await jr()).remind_weekly==="off"){He.value=!1;return}const Me=new Date().getDay();if(Me===5||Me===6||Me===0){const Ke=await el(Es(A.value));He.value=!Ke||!Ke.highlights&&!Ke.challenges&&!Ke.plan_next}else He.value=!1}return fn(async()=>{window.addEventListener("keydown",E),n.value&&(ol(n.value.userId),await Ce(),await Ue(),c())}),(ge,Me)=>{var Ke;return n.value?(F(),q("div",Q1,[u("nav",Z1,[(F(),q(Re,null,ut(L,fe=>u("button",{key:fe.key,class:et(["nav-btn",{active:le.value===fe.key}]),"data-tip":fe.name,onClick:G=>ce(fe.key)},[Oe(lt,{name:fe.icon,size:18},null,8,["name"])],10,e0)),64))]),u("div",t0,[u("header",n0,[u("span",r0,re(ee.value.name),1),u("div",s0,[Oe(lt,{name:"search",size:14,class:"gs-icon"}),$e(u("input",{ref_key:"gsInput",ref:d,class:"input gs-input","onUpdate:modelValue":Me[0]||(Me[0]=fe=>h.value=fe),placeholder:"搜索工作记录与备忘录(Ctrl+K)",onInput:O,onFocus:Me[1]||(Me[1]=fe=>y.value=!0),onBlur:Z,onKeydown:jt(K,["esc"])},null,544),[[De,h.value]]),y.value&&h.value.trim()?(F(),q("div",o0,[D.value?(F(),q(Re,{key:0},[m.value.logs.length?(F(),q("div",i0,"工作记录")):Ee("",!0),(F(!0),q(Re,null,ut(m.value.logs,fe=>(F(),q("div",{key:"l"+fe.id,class:"gs-item",onMousedown:Mr(G=>W(fe),["prevent"])},[u("span",l0,re(Qt(Qa)(fe.category)),1),u("span",u0,re(fe.content),1),u("span",c0,re(fe.date),1)],40,a0))),128)),m.value.memos.length?(F(),q("div",f0,"备忘录")):Ee("",!0),(F(!0),q(Re,null,ut(m.value.memos,fe=>(F(),q("div",{key:"m"+fe.id,class:"gs-item",onMousedown:Mr(G=>de(fe),["prevent"])},[u("span",p0,re(fe.title||"无标题"),1),u("span",h0,re(fe.content),1)],40,d0))),128))],64)):(F(),q("div",v0,"无匹配结果"))])):Ee("",!0)]),Me[4]||(Me[4]=u("span",{class:"flex1"},null,-1)),He.value?(F(),q("button",{key:0,class:"week-tip",onClick:Me[2]||(Me[2]=fe=>ce("report"))},[...Me[3]||(Me[3]=[u("span",{class:"dot",style:{background:"var(--warn)"}},null,-1),nn(" 填写本周周记 ",-1)])])):Ee("",!0),u("span",m0,re((Ke=n.value)==null?void 0:Ke.username),1),u("button",{class:"btn btn-sm",onClick:o},"退出"),u("button",{class:"btn btn-primary btn-sm",disabled:xe.value,onClick:Xe},[Oe(lt,{name:xe.value?"check-circle":"clock",size:14},null,8,["name"]),u("span",g0,re(Ne.value),1)],8,y0)]),u("main",b0,[u("div",w0,[le.value==="calendar"?(F(),It(yy,{key:0})):le.value==="today"?(F(),It(xy,{key:1})):le.value==="stats"?(F(),It(eg,{key:2})):le.value==="report"?(F(),It(Zg,{key:3})):le.value==="ledger"?(F(),It(lw,{key:4})):le.value==="memo"?(F(),It(Ew,{key:5})):le.value==="vault"?(F(),It(O_,{key:6})):(F(),It(N1,{key:7}))])])]),u("div",_0,[Oe(gh,{name:"toast"},{default:fr(()=>[(F(!0),q(Re,null,ut(Qt(t),fe=>(F(),q("div",{key:fe.id,class:"toast"},re(fe.text),1))),128))]),_:1})])])):(F(),It(X1,{key:0,onLogin:s}))}}}),x0=Gt(k0,[["__scopeId","data-v-219a8436"]]);jh(x0).mount("#app");"serviceWorker"in navigator&&location.protocol.startsWith("http")&&window.addEventListener("load",()=>{navigator.serviceWorker.register("sw.js").catch(()=>{})});export{pf as W,cf as _,hg as b,df as r}; diff --git a/intern-log/dist/assets/index-Cym4sQrs.js b/intern-log/dist/assets/index-zYm_cjgi.js similarity index 69% rename from intern-log/dist/assets/index-Cym4sQrs.js rename to intern-log/dist/assets/index-zYm_cjgi.js index cbbdefa..0b90d5d 100644 --- a/intern-log/dist/assets/index-Cym4sQrs.js +++ b/intern-log/dist/assets/index-zYm_cjgi.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./web-DNeKtcdd.js","./index-B3Rf3B1G.js","./index-DWsZ3Bb0.css"])))=>i.map(i=>d[i]); -import{r as s,_ as i}from"./index-B3Rf3B1G.js";var t;(function(e){e.Documents="DOCUMENTS",e.Data="DATA",e.Library="LIBRARY",e.Cache="CACHE",e.External="EXTERNAL",e.ExternalStorage="EXTERNAL_STORAGE"})(t||(t={}));var a;(function(e){e.UTF8="utf8",e.ASCII="ascii",e.UTF16="utf16"})(a||(a={}));const E=s("Filesystem",{web:()=>i(()=>import("./web-DNeKtcdd.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>new e.FilesystemWeb)});export{t as Directory,a as Encoding,E as Filesystem}; +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./web-DOIpoVam.js","./index-Cy5zm918.js","./index-DWsZ3Bb0.css"])))=>i.map(i=>d[i]); +import{r as s,_ as i}from"./index-Cy5zm918.js";var t;(function(e){e.Documents="DOCUMENTS",e.Data="DATA",e.Library="LIBRARY",e.Cache="CACHE",e.External="EXTERNAL",e.ExternalStorage="EXTERNAL_STORAGE"})(t||(t={}));var a;(function(e){e.UTF8="utf8",e.ASCII="ascii",e.UTF16="utf16"})(a||(a={}));const E=s("Filesystem",{web:()=>i(()=>import("./web-DOIpoVam.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>new e.FilesystemWeb)});export{t as Directory,a as Encoding,E as Filesystem}; diff --git a/intern-log/dist/assets/web-DNeKtcdd.js b/intern-log/dist/assets/web-DOIpoVam.js similarity index 98% rename from intern-log/dist/assets/web-DNeKtcdd.js rename to intern-log/dist/assets/web-DOIpoVam.js index ae38615..a9b2f6d 100644 --- a/intern-log/dist/assets/web-DNeKtcdd.js +++ b/intern-log/dist/assets/web-DOIpoVam.js @@ -1 +1 @@ -import{W as P,b as x}from"./index-B3Rf3B1G.js";import{Encoding as E}from"./index-Cym4sQrs.js";function m(w){const e=w.split("/").filter(t=>t!=="."),r=[];return e.forEach(t=>{t===".."&&r.length>0&&r[r.length-1]!==".."?r.pop():r.push(t)}),r.join("/")}function R(w,e){w=m(w),e=m(e);const r=w.split("/"),t=e.split("/");return w!==e&&r.every((i,n)=>i===t[n])}class g extends P{constructor(){super(...arguments),this.DB_VERSION=1,this.DB_NAME="Disc",this._writeCmds=["add","put","delete"],this.downloadFile=async e=>{var r,t;const i=x(e,e.webFetchExtra),n=await fetch(e.url,i);let s;if(!e.progress)s=await n.blob();else if(!(n!=null&&n.body))s=new Blob;else{const c=n.body.getReader();let o=0;const d=[],h=n.headers.get("content-type"),y=parseInt(n.headers.get("content-length")||"0",10);for(;;){const{done:f,value:p}=await c.read();if(f)break;d.push(p),o+=(p==null?void 0:p.length)||0;const b={url:e.url,bytes:o,contentLength:y};this.notifyListeners("progress",b)}const u=new Uint8Array(o);let l=0;for(const f of d)typeof f>"u"||(u.set(f,l),l+=f.length);s=new Blob([u.buffer],{type:h||void 0})}return{path:(await this.writeFile({path:e.path,directory:(r=e.directory)!==null&&r!==void 0?r:void 0,recursive:(t=e.recursive)!==null&&t!==void 0?t:!1,data:s})).uri,blob:s}}}async initDb(){if(this._db!==void 0)return this._db;if(!("indexedDB"in window))throw this.unavailable("This browser doesn't support IndexedDB");return new Promise((e,r)=>{const t=indexedDB.open(this.DB_NAME,this.DB_VERSION);t.onupgradeneeded=g.doUpgrade,t.onsuccess=()=>{this._db=t.result,e(t.result)},t.onerror=()=>r(t.error),t.onblocked=()=>{console.warn("db blocked")}})}static doUpgrade(e){const t=e.target.result;switch(e.oldVersion){case 0:case 1:default:t.objectStoreNames.contains("FileStorage")&&t.deleteObjectStore("FileStorage"),t.createObjectStore("FileStorage",{keyPath:"path"}).createIndex("by_folder","folder")}}async dbRequest(e,r){const t=this._writeCmds.indexOf(e)!==-1?"readwrite":"readonly";return this.initDb().then(i=>new Promise((n,s)=>{const o=i.transaction(["FileStorage"],t).objectStore("FileStorage")[e](...r);o.onsuccess=()=>n(o.result),o.onerror=()=>s(o.error)}))}async dbIndexRequest(e,r,t){const i=this._writeCmds.indexOf(r)!==-1?"readwrite":"readonly";return this.initDb().then(n=>new Promise((s,a)=>{const h=n.transaction(["FileStorage"],i).objectStore("FileStorage").index(e)[r](...t);h.onsuccess=()=>s(h.result),h.onerror=()=>a(h.error)}))}getPath(e,r){const t=r!==void 0?r.replace(/^[/]+|[/]+$/g,""):"";let i="";return e!==void 0&&(i+="/"+e),r!==""&&(i+="/"+t),i}async clear(){(await this.initDb()).transaction(["FileStorage"],"readwrite").objectStore("FileStorage").clear()}async readFile(e){const r=this.getPath(e.directory,e.path),t=await this.dbRequest("get",[r]);if(t===void 0)throw Error("File does not exist.");return{data:t.content?t.content:""}}async writeFile(e){const r=this.getPath(e.directory,e.path);let t=e.data;const i=e.encoding,n=e.recursive,s=await this.dbRequest("get",[r]);if(s&&s.type==="directory")throw Error("The supplied path is a directory.");const a=r.substr(0,r.lastIndexOf("/"));if(await this.dbRequest("get",[a])===void 0){const h=a.indexOf("/",1);if(h!==-1){const y=a.substr(h);await this.mkdir({path:y,directory:e.directory,recursive:n})}}if(!i&&!(t instanceof Blob)&&(t=t.indexOf(",")>=0?t.split(",")[1]:t,!this.isBase64String(t)))throw Error("The supplied data is not valid base64 content.");const o=Date.now(),d={path:r,folder:a,type:"file",size:t instanceof Blob?t.size:t.length,ctime:o,mtime:o,content:t};return await this.dbRequest("put",[d]),{uri:d.path}}async appendFile(e){const r=this.getPath(e.directory,e.path);let t=e.data;const i=e.encoding,n=r.substr(0,r.lastIndexOf("/")),s=Date.now();let a=s;const c=await this.dbRequest("get",[r]);if(c&&c.type==="directory")throw Error("The supplied path is a directory.");if(await this.dbRequest("get",[n])===void 0){const h=n.indexOf("/",1);if(h!==-1){const y=n.substr(h);await this.mkdir({path:y,directory:e.directory,recursive:!0})}}if(!i&&!this.isBase64String(t))throw Error("The supplied data is not valid base64 content.");if(c!==void 0){if(c.content instanceof Blob)throw Error("The occupied entry contains a Blob object which cannot be appended to.");c.content!==void 0&&!i?t=btoa(atob(c.content)+atob(t)):t=c.content+t,a=c.ctime}const d={path:r,folder:n,type:"file",size:t.length,ctime:a,mtime:s,content:t};await this.dbRequest("put",[d])}async deleteFile(e){const r=this.getPath(e.directory,e.path);if(await this.dbRequest("get",[r])===void 0)throw Error("File does not exist.");if((await this.dbIndexRequest("by_folder","getAllKeys",[IDBKeyRange.only(r)])).length!==0)throw Error("Folder is not empty.");await this.dbRequest("delete",[r])}async mkdir(e){const r=this.getPath(e.directory,e.path),t=e.recursive,i=r.substr(0,r.lastIndexOf("/")),n=(r.match(/\//g)||[]).length,s=await this.dbRequest("get",[i]),a=await this.dbRequest("get",[r]);if(n===1)throw Error("Cannot create Root directory");if(a!==void 0)throw Error("Current directory does already exist.");if(!t&&n!==2&&s===void 0)throw Error("Parent directory must exist");if(t&&n!==2&&s===void 0){const d=i.substr(i.indexOf("/",1));await this.mkdir({path:d,directory:e.directory,recursive:t})}const c=Date.now(),o={path:r,folder:i,type:"directory",size:0,ctime:c,mtime:c};await this.dbRequest("put",[o])}async rmdir(e){const{path:r,directory:t,recursive:i}=e,n=this.getPath(t,r),s=await this.dbRequest("get",[n]);if(s===void 0)throw Error("Folder does not exist.");if(s.type!=="directory")throw Error("Requested path is not a directory");const a=await this.readdir({path:r,directory:t});if(a.files.length!==0&&!i)throw Error("Folder is not empty");for(const c of a.files){const o=`${r}/${c.name}`;(await this.stat({path:o,directory:t})).type==="file"?await this.deleteFile({path:o,directory:t}):await this.rmdir({path:o,directory:t,recursive:i})}await this.dbRequest("delete",[n])}async readdir(e){const r=this.getPath(e.directory,e.path),t=await this.dbRequest("get",[r]);if(e.path!==""&&t===void 0)throw Error("Folder does not exist.");const i=await this.dbIndexRequest("by_folder","getAllKeys",[IDBKeyRange.only(r)]);return{files:await Promise.all(i.map(async s=>{let a=await this.dbRequest("get",[s]);return a===void 0&&(a=await this.dbRequest("get",[s+"/"])),{name:s.substring(r.length+1),type:a.type,size:a.size,ctime:a.ctime,mtime:a.mtime,uri:a.path}}))}}async getUri(e){const r=this.getPath(e.directory,e.path);let t=await this.dbRequest("get",[r]);return t===void 0&&(t=await this.dbRequest("get",[r+"/"])),{uri:(t==null?void 0:t.path)||r}}async stat(e){const r=this.getPath(e.directory,e.path);let t=await this.dbRequest("get",[r]);if(t===void 0&&(t=await this.dbRequest("get",[r+"/"])),t===void 0)throw Error("Entry does not exist.");return{type:t.type,size:t.size,ctime:t.ctime,mtime:t.mtime,uri:t.path}}async rename(e){await this._copy(e,!0)}async copy(e){return this._copy(e,!1)}async requestPermissions(){return{publicStorage:"granted"}}async checkPermissions(){return{publicStorage:"granted"}}async _copy(e,r=!1){let{toDirectory:t}=e;const{to:i,from:n,directory:s}=e;if(!i||!n)throw Error("Both to and from must be provided");t||(t=s);const a=this.getPath(s,n),c=this.getPath(t,i);if(a===c)return{uri:c};if(R(a,c))throw Error("To path cannot contain the from path");let o;try{o=await this.stat({path:i,directory:t})}catch{const l=i.split("/");l.pop();const f=l.join("/");if(l.length>0&&(await this.stat({path:f,directory:t})).type!=="directory")throw new Error("Parent directory of the to path is a file")}if(o&&o.type==="directory")throw new Error("Cannot overwrite a directory with a file");const d=await this.stat({path:n,directory:s}),h=async(u,l,f)=>{const p=this.getPath(t,u),b=await this.dbRequest("get",[p]);b.ctime=l,b.mtime=f,await this.dbRequest("put",[b])},y=d.ctime?d.ctime:Date.now();switch(d.type){case"file":{const u=await this.readFile({path:n,directory:s});r&&await this.deleteFile({path:n,directory:s});let l;!(u.data instanceof Blob)&&!this.isBase64String(u.data)&&(l=E.UTF8);const f=await this.writeFile({path:i,directory:t,data:u.data,encoding:l});return r&&await h(i,y,d.mtime),f}case"directory":{if(o)throw Error("Cannot move a directory over an existing object");try{await this.mkdir({path:i,directory:t,recursive:!1}),r&&await h(i,y,d.mtime)}catch{}const u=(await this.readdir({path:n,directory:s})).files;for(const l of u)await this._copy({from:`${n}/${l.name}`,to:`${i}/${l.name}`,directory:s,toDirectory:t},r);r&&await this.rmdir({path:n,directory:s})}}return{uri:c}}isBase64String(e){try{return btoa(atob(e))==e}catch{return!1}}}g._debug=!0;export{g as FilesystemWeb}; +import{W as P,b as x}from"./index-Cy5zm918.js";import{Encoding as E}from"./index-zYm_cjgi.js";function m(w){const e=w.split("/").filter(t=>t!=="."),r=[];return e.forEach(t=>{t===".."&&r.length>0&&r[r.length-1]!==".."?r.pop():r.push(t)}),r.join("/")}function R(w,e){w=m(w),e=m(e);const r=w.split("/"),t=e.split("/");return w!==e&&r.every((i,n)=>i===t[n])}class g extends P{constructor(){super(...arguments),this.DB_VERSION=1,this.DB_NAME="Disc",this._writeCmds=["add","put","delete"],this.downloadFile=async e=>{var r,t;const i=x(e,e.webFetchExtra),n=await fetch(e.url,i);let s;if(!e.progress)s=await n.blob();else if(!(n!=null&&n.body))s=new Blob;else{const c=n.body.getReader();let o=0;const d=[],h=n.headers.get("content-type"),y=parseInt(n.headers.get("content-length")||"0",10);for(;;){const{done:f,value:p}=await c.read();if(f)break;d.push(p),o+=(p==null?void 0:p.length)||0;const b={url:e.url,bytes:o,contentLength:y};this.notifyListeners("progress",b)}const u=new Uint8Array(o);let l=0;for(const f of d)typeof f>"u"||(u.set(f,l),l+=f.length);s=new Blob([u.buffer],{type:h||void 0})}return{path:(await this.writeFile({path:e.path,directory:(r=e.directory)!==null&&r!==void 0?r:void 0,recursive:(t=e.recursive)!==null&&t!==void 0?t:!1,data:s})).uri,blob:s}}}async initDb(){if(this._db!==void 0)return this._db;if(!("indexedDB"in window))throw this.unavailable("This browser doesn't support IndexedDB");return new Promise((e,r)=>{const t=indexedDB.open(this.DB_NAME,this.DB_VERSION);t.onupgradeneeded=g.doUpgrade,t.onsuccess=()=>{this._db=t.result,e(t.result)},t.onerror=()=>r(t.error),t.onblocked=()=>{console.warn("db blocked")}})}static doUpgrade(e){const t=e.target.result;switch(e.oldVersion){case 0:case 1:default:t.objectStoreNames.contains("FileStorage")&&t.deleteObjectStore("FileStorage"),t.createObjectStore("FileStorage",{keyPath:"path"}).createIndex("by_folder","folder")}}async dbRequest(e,r){const t=this._writeCmds.indexOf(e)!==-1?"readwrite":"readonly";return this.initDb().then(i=>new Promise((n,s)=>{const o=i.transaction(["FileStorage"],t).objectStore("FileStorage")[e](...r);o.onsuccess=()=>n(o.result),o.onerror=()=>s(o.error)}))}async dbIndexRequest(e,r,t){const i=this._writeCmds.indexOf(r)!==-1?"readwrite":"readonly";return this.initDb().then(n=>new Promise((s,a)=>{const h=n.transaction(["FileStorage"],i).objectStore("FileStorage").index(e)[r](...t);h.onsuccess=()=>s(h.result),h.onerror=()=>a(h.error)}))}getPath(e,r){const t=r!==void 0?r.replace(/^[/]+|[/]+$/g,""):"";let i="";return e!==void 0&&(i+="/"+e),r!==""&&(i+="/"+t),i}async clear(){(await this.initDb()).transaction(["FileStorage"],"readwrite").objectStore("FileStorage").clear()}async readFile(e){const r=this.getPath(e.directory,e.path),t=await this.dbRequest("get",[r]);if(t===void 0)throw Error("File does not exist.");return{data:t.content?t.content:""}}async writeFile(e){const r=this.getPath(e.directory,e.path);let t=e.data;const i=e.encoding,n=e.recursive,s=await this.dbRequest("get",[r]);if(s&&s.type==="directory")throw Error("The supplied path is a directory.");const a=r.substr(0,r.lastIndexOf("/"));if(await this.dbRequest("get",[a])===void 0){const h=a.indexOf("/",1);if(h!==-1){const y=a.substr(h);await this.mkdir({path:y,directory:e.directory,recursive:n})}}if(!i&&!(t instanceof Blob)&&(t=t.indexOf(",")>=0?t.split(",")[1]:t,!this.isBase64String(t)))throw Error("The supplied data is not valid base64 content.");const o=Date.now(),d={path:r,folder:a,type:"file",size:t instanceof Blob?t.size:t.length,ctime:o,mtime:o,content:t};return await this.dbRequest("put",[d]),{uri:d.path}}async appendFile(e){const r=this.getPath(e.directory,e.path);let t=e.data;const i=e.encoding,n=r.substr(0,r.lastIndexOf("/")),s=Date.now();let a=s;const c=await this.dbRequest("get",[r]);if(c&&c.type==="directory")throw Error("The supplied path is a directory.");if(await this.dbRequest("get",[n])===void 0){const h=n.indexOf("/",1);if(h!==-1){const y=n.substr(h);await this.mkdir({path:y,directory:e.directory,recursive:!0})}}if(!i&&!this.isBase64String(t))throw Error("The supplied data is not valid base64 content.");if(c!==void 0){if(c.content instanceof Blob)throw Error("The occupied entry contains a Blob object which cannot be appended to.");c.content!==void 0&&!i?t=btoa(atob(c.content)+atob(t)):t=c.content+t,a=c.ctime}const d={path:r,folder:n,type:"file",size:t.length,ctime:a,mtime:s,content:t};await this.dbRequest("put",[d])}async deleteFile(e){const r=this.getPath(e.directory,e.path);if(await this.dbRequest("get",[r])===void 0)throw Error("File does not exist.");if((await this.dbIndexRequest("by_folder","getAllKeys",[IDBKeyRange.only(r)])).length!==0)throw Error("Folder is not empty.");await this.dbRequest("delete",[r])}async mkdir(e){const r=this.getPath(e.directory,e.path),t=e.recursive,i=r.substr(0,r.lastIndexOf("/")),n=(r.match(/\//g)||[]).length,s=await this.dbRequest("get",[i]),a=await this.dbRequest("get",[r]);if(n===1)throw Error("Cannot create Root directory");if(a!==void 0)throw Error("Current directory does already exist.");if(!t&&n!==2&&s===void 0)throw Error("Parent directory must exist");if(t&&n!==2&&s===void 0){const d=i.substr(i.indexOf("/",1));await this.mkdir({path:d,directory:e.directory,recursive:t})}const c=Date.now(),o={path:r,folder:i,type:"directory",size:0,ctime:c,mtime:c};await this.dbRequest("put",[o])}async rmdir(e){const{path:r,directory:t,recursive:i}=e,n=this.getPath(t,r),s=await this.dbRequest("get",[n]);if(s===void 0)throw Error("Folder does not exist.");if(s.type!=="directory")throw Error("Requested path is not a directory");const a=await this.readdir({path:r,directory:t});if(a.files.length!==0&&!i)throw Error("Folder is not empty");for(const c of a.files){const o=`${r}/${c.name}`;(await this.stat({path:o,directory:t})).type==="file"?await this.deleteFile({path:o,directory:t}):await this.rmdir({path:o,directory:t,recursive:i})}await this.dbRequest("delete",[n])}async readdir(e){const r=this.getPath(e.directory,e.path),t=await this.dbRequest("get",[r]);if(e.path!==""&&t===void 0)throw Error("Folder does not exist.");const i=await this.dbIndexRequest("by_folder","getAllKeys",[IDBKeyRange.only(r)]);return{files:await Promise.all(i.map(async s=>{let a=await this.dbRequest("get",[s]);return a===void 0&&(a=await this.dbRequest("get",[s+"/"])),{name:s.substring(r.length+1),type:a.type,size:a.size,ctime:a.ctime,mtime:a.mtime,uri:a.path}}))}}async getUri(e){const r=this.getPath(e.directory,e.path);let t=await this.dbRequest("get",[r]);return t===void 0&&(t=await this.dbRequest("get",[r+"/"])),{uri:(t==null?void 0:t.path)||r}}async stat(e){const r=this.getPath(e.directory,e.path);let t=await this.dbRequest("get",[r]);if(t===void 0&&(t=await this.dbRequest("get",[r+"/"])),t===void 0)throw Error("Entry does not exist.");return{type:t.type,size:t.size,ctime:t.ctime,mtime:t.mtime,uri:t.path}}async rename(e){await this._copy(e,!0)}async copy(e){return this._copy(e,!1)}async requestPermissions(){return{publicStorage:"granted"}}async checkPermissions(){return{publicStorage:"granted"}}async _copy(e,r=!1){let{toDirectory:t}=e;const{to:i,from:n,directory:s}=e;if(!i||!n)throw Error("Both to and from must be provided");t||(t=s);const a=this.getPath(s,n),c=this.getPath(t,i);if(a===c)return{uri:c};if(R(a,c))throw Error("To path cannot contain the from path");let o;try{o=await this.stat({path:i,directory:t})}catch{const l=i.split("/");l.pop();const f=l.join("/");if(l.length>0&&(await this.stat({path:f,directory:t})).type!=="directory")throw new Error("Parent directory of the to path is a file")}if(o&&o.type==="directory")throw new Error("Cannot overwrite a directory with a file");const d=await this.stat({path:n,directory:s}),h=async(u,l,f)=>{const p=this.getPath(t,u),b=await this.dbRequest("get",[p]);b.ctime=l,b.mtime=f,await this.dbRequest("put",[b])},y=d.ctime?d.ctime:Date.now();switch(d.type){case"file":{const u=await this.readFile({path:n,directory:s});r&&await this.deleteFile({path:n,directory:s});let l;!(u.data instanceof Blob)&&!this.isBase64String(u.data)&&(l=E.UTF8);const f=await this.writeFile({path:i,directory:t,data:u.data,encoding:l});return r&&await h(i,y,d.mtime),f}case"directory":{if(o)throw Error("Cannot move a directory over an existing object");try{await this.mkdir({path:i,directory:t,recursive:!1}),r&&await h(i,y,d.mtime)}catch{}const u=(await this.readdir({path:n,directory:s})).files;for(const l of u)await this._copy({from:`${n}/${l.name}`,to:`${i}/${l.name}`,directory:s,toDirectory:t},r);r&&await this.rmdir({path:n,directory:s})}}return{uri:c}}isBase64String(e){try{return btoa(atob(e))==e}catch{return!1}}}g._debug=!0;export{g as FilesystemWeb}; diff --git a/intern-log/dist/index.html b/intern-log/dist/index.html index d31957e..d462543 100644 --- a/intern-log/dist/index.html +++ b/intern-log/dist/index.html @@ -8,7 +8,7 @@ 实习工作日志 - + diff --git a/intern-log/package.json b/intern-log/package.json index b4fda13..04e7d25 100644 --- a/intern-log/package.json +++ b/intern-log/package.json @@ -12,19 +12,20 @@ "cap:sync": "vite build && npx cap sync android" }, "dependencies": { - "dexie": "^4.0.8", - "vue": "^3.5.13", "@capacitor/core": "^6.2.0", - "@capacitor/filesystem": "^6.0.2" + "@capacitor/filesystem": "^6.0.2", + "dexie": "^4.0.8", + "vue": "^3.5.13" }, "devDependencies": { + "@capacitor/android": "^6.2.0", + "@capacitor/cli": "^6.2.0", "@vitejs/plugin-vue": "^5.2.1", - "typescript": "~5.6.3", - "vite": "^5.4.11", "electron": "^33.2.0", "electron-builder": "^25.1.8", - "@capacitor/cli": "^6.2.0", - "@capacitor/android": "^6.2.0" + "fake-indexeddb": "^6.2.5", + "typescript": "~5.6.3", + "vite": "^5.4.11" }, "description": "实习工作日志:打卡、记录、备忘录与密码库", "main": "electron/main.cjs", diff --git a/intern-log/pnpm-lock.yaml b/intern-log/pnpm-lock.yaml index b514b79..6b43cee 100644 --- a/intern-log/pnpm-lock.yaml +++ b/intern-log/pnpm-lock.yaml @@ -36,6 +36,9 @@ importers: electron-builder: specifier: ^25.1.8 version: 25.1.8(bluebird@3.7.2)(electron-builder-squirrel-windows@25.1.8)(supports-color@7.2.0) + fake-indexeddb: + specifier: ^6.2.5 + version: 6.2.5 typescript: specifier: ~5.6.3 version: 5.6.3 @@ -1012,6 +1015,10 @@ packages: resolution: {integrity: sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==} engines: {'0': node >=0.6.0} + fake-indexeddb@6.2.5: + resolution: {integrity: sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==} + engines: {node: '>=18'} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -3090,6 +3097,8 @@ snapshots: extsprintf@1.4.1: optional: true + fake-indexeddb@6.2.5: {} + fast-deep-equal@3.1.3: {} fast-json-stable-stringify@2.1.0: {} diff --git a/intern-log/repro/sync-repro.cjs b/intern-log/repro/sync-repro.cjs new file mode 100644 index 0000000..278a9da --- /dev/null +++ b/intern-log/repro/sync-repro.cjs @@ -0,0 +1,10070 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/dist/dexie.js +var require_dexie = __commonJS({ + "intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/dist/dexie.js"(exports2, module2) { + (function(global2, factory) { + typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.Dexie = factory()); + })(exports2, function() { + "use strict"; + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + var __assign = function() { + __assign = Object.assign || function __assign2(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + } + typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + var _global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; + var keys = Object.keys; + var isArray = Array.isArray; + if (typeof Promise !== "undefined" && !_global.Promise) { + _global.Promise = Promise; + } + function extend(obj, extension) { + if (typeof extension !== "object") + return obj; + keys(extension).forEach(function(key) { + obj[key] = extension[key]; + }); + return obj; + } + var getProto = Object.getPrototypeOf; + var _hasOwn = {}.hasOwnProperty; + function hasOwn(obj, prop) { + return _hasOwn.call(obj, prop); + } + function props(proto, extension) { + if (typeof extension === "function") + extension = extension(getProto(proto)); + (typeof Reflect === "undefined" ? keys : Reflect.ownKeys)(extension).forEach(function(key) { + setProp(proto, key, extension[key]); + }); + } + var defineProperty = Object.defineProperty; + function setProp(obj, prop, functionOrGetSet, options) { + defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === "function" ? { + get: functionOrGetSet.get, + set: functionOrGetSet.set, + configurable: true + } : { value: functionOrGetSet, configurable: true, writable: true }, options)); + } + function derive(Child) { + return { + from: function(Parent) { + Child.prototype = Object.create(Parent.prototype); + setProp(Child.prototype, "constructor", Child); + return { + extend: props.bind(null, Child.prototype) + }; + } + }; + } + var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; + function getPropertyDescriptor(obj, prop) { + var pd = getOwnPropertyDescriptor(obj, prop); + var proto; + return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop); + } + var _slice = [].slice; + function slice(args, start, end) { + return _slice.call(args, start, end); + } + function override(origFunc, overridedFactory) { + return overridedFactory(origFunc); + } + function assert(b) { + if (!b) + throw new Error("Assertion Failed"); + } + function asap$1(fn) { + if (_global.setImmediate) + setImmediate(fn); + else + setTimeout(fn, 0); + } + function arrayToObject(array, extractor) { + return array.reduce(function(result, item, i) { + var nameAndValue = extractor(item, i); + if (nameAndValue) + result[nameAndValue[0]] = nameAndValue[1]; + return result; + }, {}); + } + function getByKeyPath(obj, keyPath) { + if (typeof keyPath === "string" && hasOwn(obj, keyPath)) + return obj[keyPath]; + if (!keyPath) + return obj; + if (typeof keyPath !== "string") { + var rv = []; + for (var i = 0, l = keyPath.length; i < l; ++i) { + var val = getByKeyPath(obj, keyPath[i]); + rv.push(val); + } + return rv; + } + var period = keyPath.indexOf("."); + if (period !== -1) { + var innerObj = obj[keyPath.substr(0, period)]; + return innerObj == null ? void 0 : getByKeyPath(innerObj, keyPath.substr(period + 1)); + } + return void 0; + } + function setByKeyPath(obj, keyPath, value) { + if (!obj || keyPath === void 0) + return; + if ("isFrozen" in Object && Object.isFrozen(obj)) + return; + if (typeof keyPath !== "string" && "length" in keyPath) { + assert(typeof value !== "string" && "length" in value); + for (var i = 0, l = keyPath.length; i < l; ++i) { + setByKeyPath(obj, keyPath[i], value[i]); + } + } else { + var period = keyPath.indexOf("."); + if (period !== -1) { + var currentKeyPath = keyPath.substr(0, period); + var remainingKeyPath = keyPath.substr(period + 1); + if (remainingKeyPath === "") + if (value === void 0) { + if (isArray(obj) && !isNaN(parseInt(currentKeyPath))) + obj.splice(currentKeyPath, 1); + else + delete obj[currentKeyPath]; + } else + obj[currentKeyPath] = value; + else { + var innerObj = obj[currentKeyPath]; + if (!innerObj || !hasOwn(obj, currentKeyPath)) { + if (value === void 0) + return; + innerObj = obj[currentKeyPath] = {}; + } + setByKeyPath(innerObj, remainingKeyPath, value); + } + } else { + if (value === void 0) { + if (isArray(obj) && !isNaN(parseInt(keyPath))) + obj.splice(keyPath, 1); + else + delete obj[keyPath]; + } else + obj[keyPath] = value; + } + } + } + function delByKeyPath(obj, keyPath) { + if (typeof keyPath === "string") + setByKeyPath(obj, keyPath, void 0); + else if ("length" in keyPath) + [].map.call(keyPath, function(kp) { + setByKeyPath(obj, kp, void 0); + }); + } + function shallowClone(obj) { + var rv = {}; + for (var m in obj) { + if (hasOwn(obj, m)) + rv[m] = obj[m]; + } + return rv; + } + var concat = [].concat; + function flatten(a) { + return concat.apply([], a); + } + var intrinsicTypeNames = "BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(flatten([8, 16, 32, 64].map(function(num) { + return ["Int", "Uint", "Float"].map(function(t) { + return t + num + "Array"; + }); + }))).filter(function(t) { + return _global[t]; + }); + var intrinsicTypes = new Set(intrinsicTypeNames.map(function(t) { + return _global[t]; + })); + function cloneSimpleObjectTree(o) { + var rv = {}; + for (var k in o) + if (hasOwn(o, k)) { + var v = o[k]; + rv[k] = !v || typeof v !== "object" || intrinsicTypes.has(v.constructor) ? v : cloneSimpleObjectTree(v); + } + return rv; + } + var circularRefs = null; + function deepClone(any) { + circularRefs = /* @__PURE__ */ new WeakMap(); + var rv = innerDeepClone(any); + circularRefs = null; + return rv; + } + function innerDeepClone(x) { + if (!x || typeof x !== "object") + return x; + var rv = circularRefs.get(x); + if (rv) + return rv; + if (isArray(x)) { + rv = []; + circularRefs.set(x, rv); + for (var i = 0, l = x.length; i < l; ++i) { + rv.push(innerDeepClone(x[i])); + } + } else if (intrinsicTypes.has(x.constructor)) { + rv = x; + } else { + var proto = getProto(x); + rv = proto === Object.prototype ? {} : Object.create(proto); + circularRefs.set(x, rv); + for (var prop in x) { + if (hasOwn(x, prop)) { + rv[prop] = innerDeepClone(x[prop]); + } + } + } + return rv; + } + var toString = {}.toString; + function toStringTag(o) { + return toString.call(o).slice(8, -1); + } + var iteratorSymbol = typeof Symbol !== "undefined" ? Symbol.iterator : "@@iterator"; + var getIteratorOf = typeof iteratorSymbol === "symbol" ? function(x) { + var i; + return x != null && (i = x[iteratorSymbol]) && i.apply(x); + } : function() { + return null; + }; + function delArrayItem(a, x) { + var i = a.indexOf(x); + if (i >= 0) + a.splice(i, 1); + return i >= 0; + } + var NO_CHAR_ARRAY = {}; + function getArrayOf(arrayLike) { + var i, a, x, it; + if (arguments.length === 1) { + if (isArray(arrayLike)) + return arrayLike.slice(); + if (this === NO_CHAR_ARRAY && typeof arrayLike === "string") + return [arrayLike]; + if (it = getIteratorOf(arrayLike)) { + a = []; + while (x = it.next(), !x.done) + a.push(x.value); + return a; + } + if (arrayLike == null) + return [arrayLike]; + i = arrayLike.length; + if (typeof i === "number") { + a = new Array(i); + while (i--) + a[i] = arrayLike[i]; + return a; + } + return [arrayLike]; + } + i = arguments.length; + a = new Array(i); + while (i--) + a[i] = arguments[i]; + return a; + } + var isAsyncFunction = typeof Symbol !== "undefined" ? function(fn) { + return fn[Symbol.toStringTag] === "AsyncFunction"; + } : function() { + return false; + }; + var dexieErrorNames = [ + "Modify", + "Bulk", + "OpenFailed", + "VersionChange", + "Schema", + "Upgrade", + "InvalidTable", + "MissingAPI", + "NoSuchDatabase", + "InvalidArgument", + "SubTransaction", + "Unsupported", + "Internal", + "DatabaseClosed", + "PrematureCommit", + "ForeignAwait" + ]; + var idbDomErrorNames = [ + "Unknown", + "Constraint", + "Data", + "TransactionInactive", + "ReadOnly", + "Version", + "NotFound", + "InvalidState", + "InvalidAccess", + "Abort", + "Timeout", + "QuotaExceeded", + "Syntax", + "DataClone" + ]; + var errorList = dexieErrorNames.concat(idbDomErrorNames); + var defaultTexts = { + VersionChanged: "Database version changed by other database connection", + DatabaseClosed: "Database has been closed", + Abort: "Transaction aborted", + TransactionInactive: "Transaction has already completed or failed", + MissingAPI: "IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb" + }; + function DexieError(name, msg) { + this.name = name; + this.message = msg; + } + derive(DexieError).from(Error).extend({ + toString: function() { + return this.name + ": " + this.message; + } + }); + function getMultiErrorMessage(msg, failures) { + return msg + ". Errors: " + Object.keys(failures).map(function(key) { + return failures[key].toString(); + }).filter(function(v, i, s) { + return s.indexOf(v) === i; + }).join("\n"); + } + function ModifyError(msg, failures, successCount, failedKeys) { + this.failures = failures; + this.failedKeys = failedKeys; + this.successCount = successCount; + this.message = getMultiErrorMessage(msg, failures); + } + derive(ModifyError).from(DexieError); + function BulkError(msg, failures) { + this.name = "BulkError"; + this.failures = Object.keys(failures).map(function(pos) { + return failures[pos]; + }); + this.failuresByPos = failures; + this.message = getMultiErrorMessage(msg, this.failures); + } + derive(BulkError).from(DexieError); + var errnames = errorList.reduce(function(obj, name) { + return obj[name] = name + "Error", obj; + }, {}); + var BaseException = DexieError; + var exceptions = errorList.reduce(function(obj, name) { + var fullName = name + "Error"; + function DexieError2(msgOrInner, inner) { + this.name = fullName; + if (!msgOrInner) { + this.message = defaultTexts[name] || fullName; + this.inner = null; + } else if (typeof msgOrInner === "string") { + this.message = "".concat(msgOrInner).concat(!inner ? "" : "\n " + inner); + this.inner = inner || null; + } else if (typeof msgOrInner === "object") { + this.message = "".concat(msgOrInner.name, " ").concat(msgOrInner.message); + this.inner = msgOrInner; + } + } + derive(DexieError2).from(BaseException); + obj[name] = DexieError2; + return obj; + }, {}); + exceptions.Syntax = SyntaxError; + exceptions.Type = TypeError; + exceptions.Range = RangeError; + var exceptionMap = idbDomErrorNames.reduce(function(obj, name) { + obj[name + "Error"] = exceptions[name]; + return obj; + }, {}); + function mapError(domError, message) { + if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) + return domError; + var rv = new exceptionMap[domError.name](message || domError.message, domError); + if ("stack" in domError) { + setProp(rv, "stack", { + get: function() { + return this.inner.stack; + } + }); + } + return rv; + } + var fullNameExceptions = errorList.reduce(function(obj, name) { + if (["Syntax", "Type", "Range"].indexOf(name) === -1) + obj[name + "Error"] = exceptions[name]; + return obj; + }, {}); + fullNameExceptions.ModifyError = ModifyError; + fullNameExceptions.DexieError = DexieError; + fullNameExceptions.BulkError = BulkError; + function nop() { + } + function mirror(val) { + return val; + } + function pureFunctionChain(f1, f2) { + if (f1 == null || f1 === mirror) + return f2; + return function(val) { + return f2(f1(val)); + }; + } + function callBoth(on1, on2) { + return function() { + on1.apply(this, arguments); + on2.apply(this, arguments); + }; + } + function hookCreatingChain(f1, f2) { + if (f1 === nop) + return f2; + return function() { + var res = f1.apply(this, arguments); + if (res !== void 0) + arguments[0] = res; + var onsuccess = this.onsuccess, onerror = this.onerror; + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res2 !== void 0 ? res2 : res; + }; + } + function hookDeletingChain(f1, f2) { + if (f1 === nop) + return f2; + return function() { + f1.apply(this, arguments); + var onsuccess = this.onsuccess, onerror = this.onerror; + this.onsuccess = this.onerror = null; + f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + }; + } + function hookUpdatingChain(f1, f2) { + if (f1 === nop) + return f2; + return function() { + var res = f1.apply(this, arguments); + var modifications = arguments[0]; + extend(modifications, res); + var onsuccess = this.onsuccess, onerror = this.onerror; + this.onsuccess = null; + this.onerror = null; + var res2 = f2.apply(this, arguments); + if (onsuccess) + this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess; + if (onerror) + this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror; + return res === void 0 ? res2 === void 0 ? void 0 : res2 : extend(res, res2); + }; + } + function reverseStoppableEventChain(f1, f2) { + if (f1 === nop) + return f2; + return function() { + if (f2.apply(this, arguments) === false) + return false; + return f1.apply(this, arguments); + }; + } + function promisableChain(f1, f2) { + if (f1 === nop) + return f2; + return function() { + var res = f1.apply(this, arguments); + if (res && typeof res.then === "function") { + var thiz = this, i = arguments.length, args = new Array(i); + while (i--) + args[i] = arguments[i]; + return res.then(function() { + return f2.apply(thiz, args); + }); + } + return f2.apply(this, arguments); + }; + } + var debug = typeof location !== "undefined" && /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); + function setDebug(value, filter) { + debug = value; + } + var INTERNAL = {}; + var ZONE_ECHO_LIMIT = 100, _a$1 = typeof Promise === "undefined" ? [] : function() { + var globalP = Promise.resolve(); + if (typeof crypto === "undefined" || !crypto.subtle) + return [globalP, getProto(globalP), globalP]; + var nativeP = crypto.subtle.digest("SHA-512", new Uint8Array([0])); + return [nativeP, getProto(nativeP), globalP]; + }(), resolvedNativePromise = _a$1[0], nativePromiseProto = _a$1[1], resolvedGlobalPromise = _a$1[2], nativePromiseThen = nativePromiseProto && nativePromiseProto.then; + var NativePromise = resolvedNativePromise && resolvedNativePromise.constructor; + var patchGlobalPromise = !!resolvedGlobalPromise; + function schedulePhysicalTick() { + queueMicrotask(physicalTick); + } + var asap = function(callback, args) { + microtickQueue.push([callback, args]); + if (needsNewPhysicalTick) { + schedulePhysicalTick(); + needsNewPhysicalTick = false; + } + }; + var isOutsideMicroTick = true, needsNewPhysicalTick = true, unhandledErrors = [], rejectingErrors = [], rejectionMapper = mirror; + var globalPSD = { + id: "global", + global: true, + ref: 0, + unhandleds: [], + onunhandled: nop, + pgp: false, + env: {}, + finalize: nop + }; + var PSD = globalPSD; + var microtickQueue = []; + var numScheduledCalls = 0; + var tickFinalizers = []; + function DexiePromise(fn) { + if (typeof this !== "object") + throw new TypeError("Promises must be constructed via new"); + this._listeners = []; + this._lib = false; + var psd = this._PSD = PSD; + if (typeof fn !== "function") { + if (fn !== INTERNAL) + throw new TypeError("Not a function"); + this._state = arguments[1]; + this._value = arguments[2]; + if (this._state === false) + handleRejection(this, this._value); + return; + } + this._state = null; + this._value = null; + ++psd.ref; + executePromiseTask(this, fn); + } + var thenProp = { + get: function() { + var psd = PSD, microTaskId = totalEchoes; + function then(onFulfilled, onRejected) { + var _this = this; + var possibleAwait = !psd.global && (psd !== PSD || microTaskId !== totalEchoes); + var cleanup = possibleAwait && !decrementExpectedAwaits(); + var rv = new DexiePromise(function(resolve, reject) { + propagateToListener(_this, new Listener(nativeAwaitCompatibleWrap(onFulfilled, psd, possibleAwait, cleanup), nativeAwaitCompatibleWrap(onRejected, psd, possibleAwait, cleanup), resolve, reject, psd)); + }); + if (this._consoleTask) + rv._consoleTask = this._consoleTask; + return rv; + } + then.prototype = INTERNAL; + return then; + }, + set: function(value) { + setProp(this, "then", value && value.prototype === INTERNAL ? thenProp : { + get: function() { + return value; + }, + set: thenProp.set + }); + } + }; + props(DexiePromise.prototype, { + then: thenProp, + _then: function(onFulfilled, onRejected) { + propagateToListener(this, new Listener(null, null, onFulfilled, onRejected, PSD)); + }, + catch: function(onRejected) { + if (arguments.length === 1) + return this.then(null, onRejected); + var type2 = arguments[0], handler = arguments[1]; + return typeof type2 === "function" ? this.then(null, function(err) { + return err instanceof type2 ? handler(err) : PromiseReject(err); + }) : this.then(null, function(err) { + return err && err.name === type2 ? handler(err) : PromiseReject(err); + }); + }, + finally: function(onFinally) { + return this.then(function(value) { + return DexiePromise.resolve(onFinally()).then(function() { + return value; + }); + }, function(err) { + return DexiePromise.resolve(onFinally()).then(function() { + return PromiseReject(err); + }); + }); + }, + timeout: function(ms, msg) { + var _this = this; + return ms < Infinity ? new DexiePromise(function(resolve, reject) { + var handle = setTimeout(function() { + return reject(new exceptions.Timeout(msg)); + }, ms); + _this.then(resolve, reject).finally(clearTimeout.bind(null, handle)); + }) : this; + } + }); + if (typeof Symbol !== "undefined" && Symbol.toStringTag) + setProp(DexiePromise.prototype, Symbol.toStringTag, "Dexie.Promise"); + globalPSD.env = snapShot(); + function Listener(onFulfilled, onRejected, resolve, reject, zone) { + this.onFulfilled = typeof onFulfilled === "function" ? onFulfilled : null; + this.onRejected = typeof onRejected === "function" ? onRejected : null; + this.resolve = resolve; + this.reject = reject; + this.psd = zone; + } + props(DexiePromise, { + all: function() { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function(resolve, reject) { + if (values.length === 0) + resolve([]); + var remaining = values.length; + values.forEach(function(a, i) { + return DexiePromise.resolve(a).then(function(x) { + values[i] = x; + if (!--remaining) + resolve(values); + }, reject); + }); + }); + }, + resolve: function(value) { + if (value instanceof DexiePromise) + return value; + if (value && typeof value.then === "function") + return new DexiePromise(function(resolve, reject) { + value.then(resolve, reject); + }); + var rv = new DexiePromise(INTERNAL, true, value); + return rv; + }, + reject: PromiseReject, + race: function() { + var values = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function(resolve, reject) { + values.map(function(value) { + return DexiePromise.resolve(value).then(resolve, reject); + }); + }); + }, + PSD: { + get: function() { + return PSD; + }, + set: function(value) { + return PSD = value; + } + }, + totalEchoes: { get: function() { + return totalEchoes; + } }, + newPSD: newScope, + usePSD, + scheduler: { + get: function() { + return asap; + }, + set: function(value) { + asap = value; + } + }, + rejectionMapper: { + get: function() { + return rejectionMapper; + }, + set: function(value) { + rejectionMapper = value; + } + }, + follow: function(fn, zoneProps) { + return new DexiePromise(function(resolve, reject) { + return newScope(function(resolve2, reject2) { + var psd = PSD; + psd.unhandleds = []; + psd.onunhandled = reject2; + psd.finalize = callBoth(function() { + var _this = this; + run_at_end_of_this_or_next_physical_tick(function() { + _this.unhandleds.length === 0 ? resolve2() : reject2(_this.unhandleds[0]); + }); + }, psd.finalize); + fn(); + }, zoneProps, resolve, reject); + }); + } + }); + if (NativePromise) { + if (NativePromise.allSettled) + setProp(DexiePromise, "allSettled", function() { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function(resolve) { + if (possiblePromises.length === 0) + resolve([]); + var remaining = possiblePromises.length; + var results = new Array(remaining); + possiblePromises.forEach(function(p, i) { + return DexiePromise.resolve(p).then(function(value) { + return results[i] = { status: "fulfilled", value }; + }, function(reason) { + return results[i] = { status: "rejected", reason }; + }).then(function() { + return --remaining || resolve(results); + }); + }); + }); + }); + if (NativePromise.any && typeof AggregateError !== "undefined") + setProp(DexiePromise, "any", function() { + var possiblePromises = getArrayOf.apply(null, arguments).map(onPossibleParallellAsync); + return new DexiePromise(function(resolve, reject) { + if (possiblePromises.length === 0) + reject(new AggregateError([])); + var remaining = possiblePromises.length; + var failures = new Array(remaining); + possiblePromises.forEach(function(p, i) { + return DexiePromise.resolve(p).then(function(value) { + return resolve(value); + }, function(failure) { + failures[i] = failure; + if (!--remaining) + reject(new AggregateError(failures)); + }); + }); + }); + }); + if (NativePromise.withResolvers) + DexiePromise.withResolvers = NativePromise.withResolvers; + } + function executePromiseTask(promise, fn) { + try { + fn(function(value) { + if (promise._state !== null) + return; + if (value === promise) + throw new TypeError("A promise cannot be resolved with itself."); + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + if (value && typeof value.then === "function") { + executePromiseTask(promise, function(resolve, reject) { + value instanceof DexiePromise ? value._then(resolve, reject) : value.then(resolve, reject); + }); + } else { + promise._state = true; + promise._value = value; + propagateAllListeners(promise); + } + if (shouldExecuteTick) + endMicroTickScope(); + }, handleRejection.bind(null, promise)); + } catch (ex) { + handleRejection(promise, ex); + } + } + function handleRejection(promise, reason) { + rejectingErrors.push(reason); + if (promise._state !== null) + return; + var shouldExecuteTick = promise._lib && beginMicroTickScope(); + reason = rejectionMapper(reason); + promise._state = false; + promise._value = reason; + addPossiblyUnhandledError(promise); + propagateAllListeners(promise); + if (shouldExecuteTick) + endMicroTickScope(); + } + function propagateAllListeners(promise) { + var listeners = promise._listeners; + promise._listeners = []; + for (var i = 0, len = listeners.length; i < len; ++i) { + propagateToListener(promise, listeners[i]); + } + var psd = promise._PSD; + --psd.ref || psd.finalize(); + if (numScheduledCalls === 0) { + ++numScheduledCalls; + asap(function() { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } + } + function propagateToListener(promise, listener) { + if (promise._state === null) { + promise._listeners.push(listener); + return; + } + var cb = promise._state ? listener.onFulfilled : listener.onRejected; + if (cb === null) { + return (promise._state ? listener.resolve : listener.reject)(promise._value); + } + ++listener.psd.ref; + ++numScheduledCalls; + asap(callListener, [cb, promise, listener]); + } + function callListener(cb, promise, listener) { + try { + var ret, value = promise._value; + if (!promise._state && rejectingErrors.length) + rejectingErrors = []; + ret = debug && promise._consoleTask ? promise._consoleTask.run(function() { + return cb(value); + }) : cb(value); + if (!promise._state && rejectingErrors.indexOf(value) === -1) { + markErrorAsHandled(promise); + } + listener.resolve(ret); + } catch (e) { + listener.reject(e); + } finally { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + --listener.psd.ref || listener.psd.finalize(); + } + } + function physicalTick() { + usePSD(globalPSD, function() { + beginMicroTickScope() && endMicroTickScope(); + }); + } + function beginMicroTickScope() { + var wasRootExec = isOutsideMicroTick; + isOutsideMicroTick = false; + needsNewPhysicalTick = false; + return wasRootExec; + } + function endMicroTickScope() { + var callbacks, i, l; + do { + while (microtickQueue.length > 0) { + callbacks = microtickQueue; + microtickQueue = []; + l = callbacks.length; + for (i = 0; i < l; ++i) { + var item = callbacks[i]; + item[0].apply(null, item[1]); + } + } + } while (microtickQueue.length > 0); + isOutsideMicroTick = true; + needsNewPhysicalTick = true; + } + function finalizePhysicalTick() { + var unhandledErrs = unhandledErrors; + unhandledErrors = []; + unhandledErrs.forEach(function(p) { + p._PSD.onunhandled.call(null, p._value, p); + }); + var finalizers = tickFinalizers.slice(0); + var i = finalizers.length; + while (i) + finalizers[--i](); + } + function run_at_end_of_this_or_next_physical_tick(fn) { + function finalizer() { + fn(); + tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1); + } + tickFinalizers.push(finalizer); + ++numScheduledCalls; + asap(function() { + if (--numScheduledCalls === 0) + finalizePhysicalTick(); + }, []); + } + function addPossiblyUnhandledError(promise) { + if (!unhandledErrors.some(function(p) { + return p._value === promise._value; + })) + unhandledErrors.push(promise); + } + function markErrorAsHandled(promise) { + var i = unhandledErrors.length; + while (i) + if (unhandledErrors[--i]._value === promise._value) { + unhandledErrors.splice(i, 1); + return; + } + } + function PromiseReject(reason) { + return new DexiePromise(INTERNAL, false, reason); + } + function wrap(fn, errorCatcher) { + var psd = PSD; + return function() { + var wasRootExec = beginMicroTickScope(), outerScope = PSD; + try { + switchToZone(psd, true); + return fn.apply(this, arguments); + } catch (e) { + errorCatcher && errorCatcher(e); + } finally { + switchToZone(outerScope, false); + if (wasRootExec) + endMicroTickScope(); + } + }; + } + var task = { awaits: 0, echoes: 0, id: 0 }; + var taskCounter = 0; + var zoneStack = []; + var zoneEchoes = 0; + var totalEchoes = 0; + var zone_id_counter = 0; + function newScope(fn, props2, a1, a2) { + var parent = PSD, psd = Object.create(parent); + psd.parent = parent; + psd.ref = 0; + psd.global = false; + psd.id = ++zone_id_counter; + globalPSD.env; + psd.env = patchGlobalPromise ? { + Promise: DexiePromise, + PromiseProp: { + value: DexiePromise, + configurable: true, + writable: true + }, + all: DexiePromise.all, + race: DexiePromise.race, + allSettled: DexiePromise.allSettled, + any: DexiePromise.any, + resolve: DexiePromise.resolve, + reject: DexiePromise.reject + } : {}; + if (props2) + extend(psd, props2); + ++parent.ref; + psd.finalize = function() { + --this.parent.ref || this.parent.finalize(); + }; + var rv = usePSD(psd, fn, a1, a2); + if (psd.ref === 0) + psd.finalize(); + return rv; + } + function incrementExpectedAwaits() { + if (!task.id) + task.id = ++taskCounter; + ++task.awaits; + task.echoes += ZONE_ECHO_LIMIT; + return task.id; + } + function decrementExpectedAwaits() { + if (!task.awaits) + return false; + if (--task.awaits === 0) + task.id = 0; + task.echoes = task.awaits * ZONE_ECHO_LIMIT; + return true; + } + if (("" + nativePromiseThen).indexOf("[native code]") === -1) { + incrementExpectedAwaits = decrementExpectedAwaits = nop; + } + function onPossibleParallellAsync(possiblePromise) { + if (task.echoes && possiblePromise && possiblePromise.constructor === NativePromise) { + incrementExpectedAwaits(); + return possiblePromise.then(function(x) { + decrementExpectedAwaits(); + return x; + }, function(e) { + decrementExpectedAwaits(); + return rejection(e); + }); + } + return possiblePromise; + } + function zoneEnterEcho(targetZone) { + ++totalEchoes; + if (!task.echoes || --task.echoes === 0) { + task.echoes = task.awaits = task.id = 0; + } + zoneStack.push(PSD); + switchToZone(targetZone, true); + } + function zoneLeaveEcho() { + var zone = zoneStack[zoneStack.length - 1]; + zoneStack.pop(); + switchToZone(zone, false); + } + function switchToZone(targetZone, bEnteringZone) { + var currentZone = PSD; + if (bEnteringZone ? task.echoes && (!zoneEchoes++ || targetZone !== PSD) : zoneEchoes && (!--zoneEchoes || targetZone !== PSD)) { + queueMicrotask(bEnteringZone ? zoneEnterEcho.bind(null, targetZone) : zoneLeaveEcho); + } + if (targetZone === PSD) + return; + PSD = targetZone; + if (currentZone === globalPSD) + globalPSD.env = snapShot(); + if (patchGlobalPromise) { + var GlobalPromise = globalPSD.env.Promise; + var targetEnv = targetZone.env; + if (currentZone.global || targetZone.global) { + Object.defineProperty(_global, "Promise", targetEnv.PromiseProp); + GlobalPromise.all = targetEnv.all; + GlobalPromise.race = targetEnv.race; + GlobalPromise.resolve = targetEnv.resolve; + GlobalPromise.reject = targetEnv.reject; + if (targetEnv.allSettled) + GlobalPromise.allSettled = targetEnv.allSettled; + if (targetEnv.any) + GlobalPromise.any = targetEnv.any; + } + } + } + function snapShot() { + var GlobalPromise = _global.Promise; + return patchGlobalPromise ? { + Promise: GlobalPromise, + PromiseProp: Object.getOwnPropertyDescriptor(_global, "Promise"), + all: GlobalPromise.all, + race: GlobalPromise.race, + allSettled: GlobalPromise.allSettled, + any: GlobalPromise.any, + resolve: GlobalPromise.resolve, + reject: GlobalPromise.reject + } : {}; + } + function usePSD(psd, fn, a1, a2, a3) { + var outerScope = PSD; + try { + switchToZone(psd, true); + return fn(a1, a2, a3); + } finally { + switchToZone(outerScope, false); + } + } + function nativeAwaitCompatibleWrap(fn, zone, possibleAwait, cleanup) { + return typeof fn !== "function" ? fn : function() { + var outerZone = PSD; + if (possibleAwait) + incrementExpectedAwaits(); + switchToZone(zone, true); + try { + return fn.apply(this, arguments); + } finally { + switchToZone(outerZone, false); + if (cleanup) + queueMicrotask(decrementExpectedAwaits); + } + }; + } + function execInGlobalContext(cb) { + if (Promise === NativePromise && task.echoes === 0) { + if (zoneEchoes === 0) { + cb(); + } else { + enqueueNativeMicroTask(cb); + } + } else { + setTimeout(cb, 0); + } + } + var rejection = DexiePromise.reject; + function tempTransaction(db2, mode, storeNames, fn) { + if (!db2.idbdb || !db2._state.openComplete && !PSD.letThrough && !db2._vip) { + if (db2._state.openComplete) { + return rejection(new exceptions.DatabaseClosed(db2._state.dbOpenError)); + } + if (!db2._state.isBeingOpened) { + if (!db2._state.autoOpen) + return rejection(new exceptions.DatabaseClosed()); + db2.open().catch(nop); + } + return db2._state.dbReadyPromise.then(function() { + return tempTransaction(db2, mode, storeNames, fn); + }); + } else { + var trans = db2._createTransaction(mode, storeNames, db2._dbSchema); + try { + trans.create(); + db2._state.PR1398_maxLoop = 3; + } catch (ex) { + if (ex.name === errnames.InvalidState && db2.isOpen() && --db2._state.PR1398_maxLoop > 0) { + console.warn("Dexie: Need to reopen db"); + db2.close({ disableAutoOpen: false }); + return db2.open().then(function() { + return tempTransaction(db2, mode, storeNames, fn); + }); + } + return rejection(ex); + } + return trans._promise(mode, function(resolve, reject) { + return newScope(function() { + PSD.trans = trans; + return fn(resolve, reject, trans); + }); + }).then(function(result) { + if (mode === "readwrite") + try { + trans.idbtrans.commit(); + } catch (_a2) { + } + return mode === "readonly" ? result : trans._completion.then(function() { + return result; + }); + }); + } + } + var DEXIE_VERSION = "4.4.6"; + var maxString = String.fromCharCode(65535); + var minKey = -Infinity; + var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array."; + var STRING_EXPECTED = "String expected."; + var DEFAULT_MAX_CONNECTIONS = 1e3; + var DBNAMES_DB = "__dbnames"; + var READONLY = "readonly"; + var READWRITE = "readwrite"; + function combine(filter1, filter2) { + return filter1 ? filter2 ? function() { + return filter1.apply(this, arguments) && filter2.apply(this, arguments); + } : filter1 : filter2; + } + var AnyRange = { + type: 3, + lower: -Infinity, + lowerOpen: false, + upper: [[]], + upperOpen: false + }; + function workaroundForUndefinedPrimKey(keyPath) { + return typeof keyPath === "string" && !/\./.test(keyPath) ? function(obj) { + if (obj[keyPath] === void 0 && keyPath in obj) { + obj = deepClone(obj); + delete obj[keyPath]; + } + return obj; + } : function(obj) { + return obj; + }; + } + function Entity2() { + throw exceptions.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor."); + } + function cmp3(a, b) { + try { + var ta = type(a); + var tb = type(b); + if (ta !== tb) { + if (ta === "Array") + return 1; + if (tb === "Array") + return -1; + if (ta === "binary") + return 1; + if (tb === "binary") + return -1; + if (ta === "string") + return 1; + if (tb === "string") + return -1; + if (ta === "Date") + return 1; + if (tb !== "Date") + return NaN; + return -1; + } + switch (ta) { + case "number": + case "Date": + case "string": + return a > b ? 1 : a < b ? -1 : 0; + case "binary": { + return compareUint8Arrays(getUint8Array(a), getUint8Array(b)); + } + case "Array": + return compareArrays(a, b); + } + } catch (_a2) { + } + return NaN; + } + function compareArrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + var res = cmp3(a[i], b[i]); + if (res !== 0) + return res; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function compareUint8Arrays(a, b) { + var al = a.length; + var bl = b.length; + var l = al < bl ? al : bl; + for (var i = 0; i < l; ++i) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } + return al === bl ? 0 : al < bl ? -1 : 1; + } + function type(x) { + var t = typeof x; + if (t !== "object") + return t; + if (ArrayBuffer.isView(x)) + return "binary"; + var tsTag = toStringTag(x); + return tsTag === "ArrayBuffer" ? "binary" : tsTag; + } + function getUint8Array(a) { + if (a instanceof Uint8Array) + return a; + if (ArrayBuffer.isView(a)) + return new Uint8Array(a.buffer, a.byteOffset, a.byteLength); + return new Uint8Array(a); + } + function builtInDeletionTrigger(table, keys2, res) { + var yProps = table.schema.yProps; + if (!yProps) + return res; + if (keys2 && res.numFailures > 0) + keys2 = keys2.filter(function(_, i) { + return !res.failures[i]; + }); + return Promise.all(yProps.map(function(_a2) { + var updatesTable = _a2.updatesTable; + return keys2 ? table.db.table(updatesTable).where("k").anyOf(keys2).delete() : table.db.table(updatesTable).clear(); + })).then(function() { + return res; + }); + } + var PropModification2 = function() { + function PropModification3(spec) { + this["@@propmod"] = spec; + } + PropModification3.prototype.execute = function(value) { + var _a2; + var spec = this["@@propmod"]; + if (spec.add !== void 0) { + var term = spec.add; + if (isArray(term)) { + return __spreadArray(__spreadArray([], isArray(value) ? value : [], true), term, true).sort(); + } + if (typeof term === "number") + return (Number(value) || 0) + term; + if (typeof term === "bigint") { + try { + return BigInt(value) + term; + } catch (_b) { + return BigInt(0) + term; + } + } + throw new TypeError("Invalid term ".concat(term)); + } + if (spec.remove !== void 0) { + var subtrahend_1 = spec.remove; + if (isArray(subtrahend_1)) { + return isArray(value) ? value.filter(function(item) { + return !subtrahend_1.includes(item); + }).sort() : []; + } + if (typeof subtrahend_1 === "number") + return Number(value) - subtrahend_1; + if (typeof subtrahend_1 === "bigint") { + try { + return BigInt(value) - subtrahend_1; + } catch (_c) { + return BigInt(0) - subtrahend_1; + } + } + throw new TypeError("Invalid subtrahend ".concat(subtrahend_1)); + } + var prefixToReplace = (_a2 = spec.replacePrefix) === null || _a2 === void 0 ? void 0 : _a2[0]; + if (prefixToReplace && typeof value === "string" && value.startsWith(prefixToReplace)) { + return spec.replacePrefix[1] + value.substring(prefixToReplace.length); + } + return value; + }; + return PropModification3; + }(); + function applyUpdateSpec(obj, changes) { + var keyPaths = keys(changes); + var numKeys = keyPaths.length; + var anythingModified = false; + for (var i = 0; i < numKeys; ++i) { + var keyPath = keyPaths[i]; + var value = changes[keyPath]; + var origValue = getByKeyPath(obj, keyPath); + if (value instanceof PropModification2) { + setByKeyPath(obj, keyPath, value.execute(origValue)); + anythingModified = true; + } else if (origValue !== value) { + setByKeyPath(obj, keyPath, value); + anythingModified = true; + } + } + return anythingModified; + } + var Table = function() { + function Table2() { + } + Table2.prototype._trans = function(mode, fn, writeLocked) { + var trans = this._tx || PSD.trans; + var tableName = this.name; + var task2 = debug && typeof console !== "undefined" && console.createTask && console.createTask("Dexie: ".concat(mode === "readonly" ? "read" : "write", " ").concat(this.name)); + function checkTableInTransaction(resolve, reject, trans2) { + if (!trans2.schema[tableName]) + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + return fn(trans2.idbtrans, trans2); + } + var wasRootExec = beginMicroTickScope(); + try { + var p = trans && trans.db._novip === this.db._novip ? trans === PSD.trans ? trans._promise(mode, checkTableInTransaction, writeLocked) : newScope(function() { + return trans._promise(mode, checkTableInTransaction, writeLocked); + }, { trans, transless: PSD.transless || PSD }) : tempTransaction(this.db, mode, [this.name], checkTableInTransaction); + if (task2) { + p._consoleTask = task2; + p = p.catch(function(err) { + console.trace(err); + return rejection(err); + }); + } + return p; + } finally { + if (wasRootExec) + endMicroTickScope(); + } + }; + Table2.prototype.get = function(keyOrCrit, cb) { + var _this = this; + if (keyOrCrit && keyOrCrit.constructor === Object) + return this.where(keyOrCrit).first(cb); + if (keyOrCrit == null) + return rejection(new exceptions.Type("Invalid argument to Table.get()")); + return this._trans("readonly", function(trans) { + return _this.core.get({ trans, key: keyOrCrit }).then(function(res) { + return _this.hook.reading.fire(res); + }); + }).then(cb); + }; + Table2.prototype.where = function(indexOrCrit) { + if (typeof indexOrCrit === "string") + return new this.db.WhereClause(this, indexOrCrit); + if (isArray(indexOrCrit)) + return new this.db.WhereClause(this, "[".concat(indexOrCrit.join("+"), "]")); + var keyPaths = keys(indexOrCrit); + if (keyPaths.length === 1) + return this.where(keyPaths[0]).equals(indexOrCrit[keyPaths[0]]); + var compoundIndex = this.schema.indexes.concat(this.schema.primKey).filter(function(ix) { + if (ix.compound && keyPaths.every(function(keyPath) { + return ix.keyPath.indexOf(keyPath) >= 0; + })) { + for (var i = 0; i < keyPaths.length; ++i) { + if (keyPaths.indexOf(ix.keyPath[i]) === -1) + return false; + } + return true; + } + return false; + }).sort(function(a, b) { + return a.keyPath.length - b.keyPath.length; + })[0]; + if (compoundIndex && this.db._maxKey !== maxString) { + var keyPathsInValidOrder = compoundIndex.keyPath.slice(0, keyPaths.length); + return this.where(keyPathsInValidOrder).equals(keyPathsInValidOrder.map(function(kp) { + return indexOrCrit[kp]; + })); + } + if (!compoundIndex && debug) + console.warn("The query ".concat(JSON.stringify(indexOrCrit), " on ").concat(this.name, " would benefit from a ") + "compound index [".concat(keyPaths.join("+"), "]")); + var idxByName = this.schema.idxByName; + function equals(a, b) { + return cmp3(a, b) === 0; + } + var _a2 = keyPaths.reduce(function(_a3, keyPath) { + var prevIndex = _a3[0], prevFilterFn = _a3[1]; + var index = idxByName[keyPath]; + var value = indexOrCrit[keyPath]; + return [ + prevIndex || index, + prevIndex || !index ? combine(prevFilterFn, index && index.multi ? function(x) { + var prop = getByKeyPath(x, keyPath); + return isArray(prop) && prop.some(function(item) { + return equals(value, item); + }); + } : function(x) { + return equals(value, getByKeyPath(x, keyPath)); + }) : prevFilterFn + ]; + }, [null, null]), idx = _a2[0], filterFunction = _a2[1]; + return idx ? this.where(idx.name).equals(indexOrCrit[idx.keyPath]).filter(filterFunction) : compoundIndex ? this.filter(filterFunction) : this.where(keyPaths).equals(""); + }; + Table2.prototype.filter = function(filterFunction) { + return this.toCollection().and(filterFunction); + }; + Table2.prototype.count = function(thenShortcut) { + return this.toCollection().count(thenShortcut); + }; + Table2.prototype.offset = function(offset) { + return this.toCollection().offset(offset); + }; + Table2.prototype.limit = function(numRows) { + return this.toCollection().limit(numRows); + }; + Table2.prototype.each = function(callback) { + return this.toCollection().each(callback); + }; + Table2.prototype.toArray = function(thenShortcut) { + return this.toCollection().toArray(thenShortcut); + }; + Table2.prototype.toCollection = function() { + return new this.db.Collection(new this.db.WhereClause(this)); + }; + Table2.prototype.orderBy = function(index) { + return new this.db.Collection(new this.db.WhereClause(this, isArray(index) ? "[".concat(index.join("+"), "]") : index)); + }; + Table2.prototype.reverse = function() { + return this.toCollection().reverse(); + }; + Table2.prototype.mapToClass = function(constructor) { + var _a2 = this, db2 = _a2.db, tableName = _a2.name; + this.schema.mappedClass = constructor; + if (constructor.prototype instanceof Entity2) { + constructor = function(_super) { + __extends(class_1, _super); + function class_1() { + return _super !== null && _super.apply(this, arguments) || this; + } + Object.defineProperty(class_1.prototype, "db", { + get: function() { + return db2; + }, + enumerable: false, + configurable: true + }); + class_1.prototype.table = function() { + return tableName; + }; + return class_1; + }(constructor); + } + var inheritedProps = /* @__PURE__ */ new Set(); + for (var proto = constructor.prototype; proto; proto = getProto(proto)) { + Object.getOwnPropertyNames(proto).forEach(function(propName) { + return inheritedProps.add(propName); + }); + } + var readHook = function(obj) { + if (!obj) + return obj; + var res = Object.create(constructor.prototype); + for (var m in obj) + if (!inheritedProps.has(m)) + try { + res[m] = obj[m]; + } catch (_) { + } + return res; + }; + if (this.schema.readHook) { + this.hook.reading.unsubscribe(this.schema.readHook); + } + this.schema.readHook = readHook; + this.hook("reading", readHook); + return constructor; + }; + Table2.prototype.defineClass = function() { + function Class(content) { + extend(this, content); + } + return this.mapToClass(Class); + }; + Table2.prototype.add = function(obj, key) { + var _this = this; + var _a2 = this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans("readwrite", function(trans) { + return _this.core.mutate({ + trans, + type: "add", + keys: key != null ? [key] : null, + values: [objToAdd] + }); + }).then(function(res) { + return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; + }).then(function(lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } catch (_) { + } + } + return lastResult; + }); + }; + Table2.prototype.upsert = function(key, modifications) { + var _this = this; + var keyPath = this.schema.primKey.keyPath; + return this._trans("readwrite", function(trans) { + return _this.core.get({ trans, key }).then(function(existing) { + var obj = existing !== null && existing !== void 0 ? existing : {}; + applyUpdateSpec(obj, modifications); + if (keyPath) + setByKeyPath(obj, keyPath, key); + return _this.core.mutate({ + trans, + type: "put", + values: [obj], + keys: [key], + upsert: true, + updates: { keys: [key], changeSpecs: [modifications] } + }).then(function(res) { + return res.numFailures ? DexiePromise.reject(res.failures[0]) : !!existing; + }); + }); + }); + }; + Table2.prototype.update = function(keyOrObject, modifications) { + if (typeof keyOrObject === "object" && !isArray(keyOrObject)) { + var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath); + if (key === void 0) + return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key")); + return this.where(":id").equals(key).modify(modifications); + } else { + return this.where(":id").equals(keyOrObject).modify(modifications); + } + }; + Table2.prototype.put = function(obj, key) { + var _this = this; + var _a2 = this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; + var objToAdd = obj; + if (keyPath && auto) { + objToAdd = workaroundForUndefinedPrimKey(keyPath)(obj); + } + return this._trans("readwrite", function(trans) { + return _this.core.mutate({ + trans, + type: "put", + values: [objToAdd], + keys: key != null ? [key] : null + }); + }).then(function(res) { + return res.numFailures ? DexiePromise.reject(res.failures[0]) : res.lastResult; + }).then(function(lastResult) { + if (keyPath) { + try { + setByKeyPath(obj, keyPath, lastResult); + } catch (_) { + } + } + return lastResult; + }); + }; + Table2.prototype.delete = function(key) { + var _this = this; + return this._trans("readwrite", function(trans) { + return _this.core.mutate({ trans, type: "delete", keys: [key] }).then(function(res) { + return builtInDeletionTrigger(_this, [key], res); + }).then(function(res) { + return res.numFailures ? DexiePromise.reject(res.failures[0]) : void 0; + }); + }); + }; + Table2.prototype.clear = function() { + var _this = this; + return this._trans("readwrite", function(trans) { + return _this.core.mutate({ trans, type: "deleteRange", range: AnyRange }).then(function(res) { + return builtInDeletionTrigger(_this, null, res); + }); + }).then(function(res) { + return res.numFailures ? DexiePromise.reject(res.failures[0]) : void 0; + }); + }; + Table2.prototype.bulkGet = function(keys2) { + var _this = this; + return this._trans("readonly", function(trans) { + return _this.core.getMany({ + keys: keys2, + trans + }).then(function(result) { + return result.map(function(res) { + return _this.hook.reading.fire(res); + }); + }); + }); + }; + Table2.prototype.bulkAdd = function(objects, keysOrOptions, options) { + var _this = this; + var keys2 = Array.isArray(keysOrOptions) ? keysOrOptions : void 0; + options = options || (keys2 ? void 0 : keysOrOptions); + var wantResults = options ? options.allKeys : void 0; + return this._trans("readwrite", function(trans) { + var _a2 = _this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; + if (keyPath && keys2) + throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); + if (keys2 && keys2.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToAdd = keyPath && auto ? objects.map(workaroundForUndefinedPrimKey(keyPath)) : objects; + return _this.core.mutate({ + trans, + type: "add", + keys: keys2, + values: objectsToAdd, + wantResults + }).then(function(_a3) { + var numFailures = _a3.numFailures, results = _a3.results, lastResult = _a3.lastResult, failures = _a3.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError("".concat(_this.name, ".bulkAdd(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); + }); + }); + }; + Table2.prototype.bulkPut = function(objects, keysOrOptions, options) { + var _this = this; + var keys2 = Array.isArray(keysOrOptions) ? keysOrOptions : void 0; + options = options || (keys2 ? void 0 : keysOrOptions); + var wantResults = options ? options.allKeys : void 0; + return this._trans("readwrite", function(trans) { + var _a2 = _this.schema.primKey, auto = _a2.auto, keyPath = _a2.keyPath; + if (keyPath && keys2) + throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); + if (keys2 && keys2.length !== objects.length) + throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length"); + var numObjects = objects.length; + var objectsToPut = keyPath && auto ? objects.map(workaroundForUndefinedPrimKey(keyPath)) : objects; + return _this.core.mutate({ + trans, + type: "put", + keys: keys2, + values: objectsToPut, + wantResults + }).then(function(_a3) { + var numFailures = _a3.numFailures, results = _a3.results, lastResult = _a3.lastResult, failures = _a3.failures; + var result = wantResults ? results : lastResult; + if (numFailures === 0) + return result; + throw new BulkError("".concat(_this.name, ".bulkPut(): ").concat(numFailures, " of ").concat(numObjects, " operations failed"), failures); + }); + }); + }; + Table2.prototype.bulkUpdate = function(keysAndChanges) { + var _this = this; + var coreTable = this.core; + var keys2 = keysAndChanges.map(function(entry) { + return entry.key; + }); + var changeSpecs = keysAndChanges.map(function(entry) { + return entry.changes; + }); + var offsetMap = []; + return this._trans("readwrite", function(trans) { + return coreTable.getMany({ trans, keys: keys2, cache: "clone" }).then(function(objs) { + var resultKeys = []; + var resultObjs = []; + keysAndChanges.forEach(function(_a2, idx) { + var key = _a2.key, changes = _a2.changes; + var obj = objs[idx]; + if (obj) { + for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) { + var keyPath = _b[_i]; + var value = changes[keyPath]; + if (keyPath === _this.schema.primKey.keyPath) { + if (cmp3(value, key) !== 0) { + throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()"); + } + } else { + setByKeyPath(obj, keyPath, value); + } + } + offsetMap.push(idx); + resultKeys.push(key); + resultObjs.push(obj); + } + }); + var numEntries = resultKeys.length; + return coreTable.mutate({ + trans, + type: "put", + keys: resultKeys, + values: resultObjs, + updates: { + keys: keys2, + changeSpecs + } + }).then(function(_a2) { + var numFailures = _a2.numFailures, failures = _a2.failures; + if (numFailures === 0) + return numEntries; + for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) { + var offset = _b[_i]; + var mappedOffset = offsetMap[Number(offset)]; + if (mappedOffset != null) { + var failure = failures[offset]; + delete failures[offset]; + failures[mappedOffset] = failure; + } + } + throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures); + }); + }); + }); + }; + Table2.prototype.bulkDelete = function(keys2) { + var _this = this; + var numKeys = keys2.length; + return this._trans("readwrite", function(trans) { + return _this.core.mutate({ trans, type: "delete", keys: keys2 }).then(function(res) { + return builtInDeletionTrigger(_this, keys2, res); + }); + }).then(function(_a2) { + var numFailures = _a2.numFailures, lastResult = _a2.lastResult, failures = _a2.failures; + if (numFailures === 0) + return lastResult; + throw new BulkError("".concat(_this.name, ".bulkDelete(): ").concat(numFailures, " of ").concat(numKeys, " operations failed"), failures); + }); + }; + return Table2; + }(); + function Events(ctx) { + var evs = {}; + var rv = function(eventName, subscriber) { + if (subscriber) { + var i2 = arguments.length, args = new Array(i2 - 1); + while (--i2) + args[i2 - 1] = arguments[i2]; + evs[eventName].subscribe.apply(null, args); + return ctx; + } else if (typeof eventName === "string") { + return evs[eventName]; + } + }; + rv.addEventType = add3; + for (var i = 1, l = arguments.length; i < l; ++i) { + add3(arguments[i]); + } + return rv; + function add3(eventName, chainFunction, defaultFunction) { + if (typeof eventName === "object") + return addConfiguredEvents(eventName); + if (!chainFunction) + chainFunction = reverseStoppableEventChain; + if (!defaultFunction) + defaultFunction = nop; + var context = { + subscribers: [], + fire: defaultFunction, + subscribe: function(cb) { + if (context.subscribers.indexOf(cb) === -1) { + context.subscribers.push(cb); + context.fire = chainFunction(context.fire, cb); + } + }, + unsubscribe: function(cb) { + context.subscribers = context.subscribers.filter(function(fn) { + return fn !== cb; + }); + context.fire = context.subscribers.reduce(chainFunction, defaultFunction); + } + }; + evs[eventName] = rv[eventName] = context; + return context; + } + function addConfiguredEvents(cfg) { + keys(cfg).forEach(function(eventName) { + var args = cfg[eventName]; + if (isArray(args)) { + add3(eventName, cfg[eventName][0], cfg[eventName][1]); + } else if (args === "asap") { + var context = add3(eventName, mirror, function fire() { + var i2 = arguments.length, args2 = new Array(i2); + while (i2--) + args2[i2] = arguments[i2]; + context.subscribers.forEach(function(fn) { + asap$1(function fireEvent() { + fn.apply(null, args2); + }); + }); + }); + } else + throw new exceptions.InvalidArgument("Invalid event config"); + }); + } + } + function makeClassConstructor(prototype, constructor) { + derive(constructor).from({ prototype }); + return constructor; + } + function createTableConstructor(db2) { + return makeClassConstructor(Table.prototype, function Table2(name, tableSchema, trans) { + this.db = db2; + this._tx = trans; + this.name = name; + this.schema = tableSchema; + this.hook = db2._allTables[name] ? db2._allTables[name].hook : Events(null, { + creating: [hookCreatingChain, nop], + reading: [pureFunctionChain, mirror], + updating: [hookUpdatingChain, nop], + deleting: [hookDeletingChain, nop] + }); + }); + } + function isPlainKeyRange(ctx, ignoreLimitFilter) { + return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter); + } + function addFilter(ctx, fn) { + ctx.filter = combine(ctx.filter, fn); + } + function addReplayFilter(ctx, factory, isLimitFilter) { + var curr = ctx.replayFilter; + ctx.replayFilter = curr ? function() { + return combine(curr(), factory()); + } : factory; + ctx.justLimit = isLimitFilter && !curr; + } + function addMatchFilter(ctx, fn) { + ctx.isMatch = combine(ctx.isMatch, fn); + } + function getIndexOrStore(ctx, coreSchema) { + if (ctx.isPrimKey) + return coreSchema.primaryKey; + var index = coreSchema.getIndexByKeyPath(ctx.index); + if (!index) + throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + coreSchema.name + " is not indexed"); + return index; + } + function openCursor(ctx, coreTable, trans) { + var index = getIndexOrStore(ctx, coreTable.schema); + return coreTable.openCursor({ + trans, + values: !ctx.keysOnly, + reverse: ctx.dir === "prev", + unique: !!ctx.unique, + query: { + index, + range: ctx.range + } + }); + } + function iter(ctx, fn, coreTrans, coreTable) { + var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter; + if (!ctx.or) { + return iterate(openCursor(ctx, coreTable, coreTrans), combine(ctx.algorithm, filter), fn, !ctx.keysOnly && ctx.valueMapper); + } else { + var set_1 = {}; + var union = function(item, cursor, advance) { + if (!filter || filter(cursor, advance, function(result) { + return cursor.stop(result); + }, function(err) { + return cursor.fail(err); + })) { + var primaryKey = cursor.primaryKey; + var key = "" + primaryKey; + if (key === "[object ArrayBuffer]") + key = "" + new Uint8Array(primaryKey); + if (!hasOwn(set_1, key)) { + set_1[key] = true; + fn(item, cursor, advance); + } + } + }; + return Promise.all([ + ctx.or._iterate(union, coreTrans), + iterate(openCursor(ctx, coreTable, coreTrans), ctx.algorithm, union, !ctx.keysOnly && ctx.valueMapper) + ]); + } + } + function iterate(cursorPromise, filter, fn, valueMapper) { + var mappedFn = valueMapper ? function(x, c, a) { + return fn(valueMapper(x), c, a); + } : fn; + var wrappedFn = wrap(mappedFn); + return cursorPromise.then(function(cursor) { + if (cursor) { + return cursor.start(function() { + var c = function() { + return cursor.continue(); + }; + if (!filter || filter(cursor, function(advancer) { + return c = advancer; + }, function(val) { + cursor.stop(val); + c = nop; + }, function(e) { + cursor.fail(e); + c = nop; + })) + wrappedFn(cursor.value, cursor, function(advancer) { + return c = advancer; + }); + c(); + }); + } + }); + } + var Collection = function() { + function Collection2() { + } + Collection2.prototype._read = function(fn, cb) { + var ctx = this._ctx; + return ctx.error ? ctx.table._trans(null, rejection.bind(null, ctx.error)) : ctx.table._trans("readonly", fn).then(cb); + }; + Collection2.prototype._write = function(fn) { + var ctx = this._ctx; + return ctx.error ? ctx.table._trans(null, rejection.bind(null, ctx.error)) : ctx.table._trans("readwrite", fn, "locked"); + }; + Collection2.prototype._addAlgorithm = function(fn) { + var ctx = this._ctx; + ctx.algorithm = combine(ctx.algorithm, fn); + }; + Collection2.prototype._iterate = function(fn, coreTrans) { + return iter(this._ctx, fn, coreTrans, this._ctx.table.core); + }; + Collection2.prototype.clone = function(props2) { + var rv = Object.create(this.constructor.prototype), ctx = Object.create(this._ctx); + if (props2) + extend(ctx, props2); + rv._ctx = ctx; + return rv; + }; + Collection2.prototype.raw = function() { + this._ctx.valueMapper = null; + return this; + }; + Collection2.prototype.each = function(fn) { + var ctx = this._ctx; + return this._read(function(trans) { + return iter(ctx, fn, trans, ctx.table.core); + }); + }; + Collection2.prototype.count = function(cb) { + var _this = this; + return this._read(function(trans) { + var ctx = _this._ctx; + var coreTable = ctx.table.core; + if (isPlainKeyRange(ctx, true)) { + return coreTable.count({ + trans, + query: { + index: getIndexOrStore(ctx, coreTable.schema), + range: ctx.range + } + }).then(function(count2) { + return Math.min(count2, ctx.limit); + }); + } else { + var count = 0; + return iter(ctx, function() { + ++count; + return false; + }, trans, coreTable).then(function() { + return count; + }); + } + }).then(cb); + }; + Collection2.prototype.sortBy = function(keyPath, cb) { + var parts = keyPath.split(".").reverse(), lastPart = parts[0], lastIndex = parts.length - 1; + function getval(obj, i) { + if (i) + return getval(obj[parts[i]], i - 1); + return obj[lastPart]; + } + var order = this._ctx.dir === "next" ? 1 : -1; + function sorter(a, b) { + var aVal = getval(a, lastIndex), bVal = getval(b, lastIndex); + return cmp3(aVal, bVal) * order; + } + return this.toArray(function(a) { + return a.slice().sort(sorter); + }).then(cb); + }; + Collection2.prototype.toArray = function(cb) { + var _this = this; + return this._read(function(trans) { + var ctx = _this._ctx; + if (isPlainKeyRange(ctx, true) && ctx.limit > 0) { + var valueMapper_1 = ctx.valueMapper; + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans, + limit: ctx.limit, + values: true, + direction: ctx.dir === "prev" ? "prev" : void 0, + query: { + index, + range: ctx.range + } + }).then(function(_a2) { + var result = _a2.result; + return valueMapper_1 ? result.map(valueMapper_1) : result; + }); + } else { + var a_1 = []; + return iter(ctx, function(item) { + return a_1.push(item); + }, trans, ctx.table.core).then(function() { + return a_1; + }); + } + }, cb); + }; + Collection2.prototype.offset = function(offset) { + var ctx = this._ctx; + if (offset <= 0) + return this; + ctx.offset += offset; + if (isPlainKeyRange(ctx)) { + addReplayFilter(ctx, function() { + var offsetLeft = offset; + return function(cursor, advance) { + if (offsetLeft === 0) + return true; + if (offsetLeft === 1) { + --offsetLeft; + return false; + } + advance(function() { + cursor.advance(offsetLeft); + offsetLeft = 0; + }); + return false; + }; + }); + } else { + addReplayFilter(ctx, function() { + var offsetLeft = offset; + return function() { + return --offsetLeft < 0; + }; + }); + } + return this; + }; + Collection2.prototype.limit = function(numRows) { + this._ctx.limit = Math.min(this._ctx.limit, numRows); + addReplayFilter(this._ctx, function() { + var rowsLeft = numRows; + return function(cursor, advance, resolve) { + if (--rowsLeft <= 0) + advance(resolve); + return rowsLeft >= 0; + }; + }, true); + return this; + }; + Collection2.prototype.until = function(filterFunction, bIncludeStopEntry) { + addFilter(this._ctx, function(cursor, advance, resolve) { + if (filterFunction(cursor.value)) { + advance(resolve); + return bIncludeStopEntry; + } else { + return true; + } + }); + return this; + }; + Collection2.prototype.first = function(cb) { + return this.limit(1).toArray(function(a) { + return a[0]; + }).then(cb); + }; + Collection2.prototype.last = function(cb) { + return this.reverse().first(cb); + }; + Collection2.prototype.filter = function(filterFunction) { + addFilter(this._ctx, function(cursor) { + return filterFunction(cursor.value); + }); + addMatchFilter(this._ctx, filterFunction); + return this; + }; + Collection2.prototype.and = function(filter) { + return this.filter(filter); + }; + Collection2.prototype.or = function(indexName) { + return new this.db.WhereClause(this._ctx.table, indexName, this); + }; + Collection2.prototype.reverse = function() { + this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev"; + if (this._ondirectionchange) + this._ondirectionchange(this._ctx.dir); + return this; + }; + Collection2.prototype.desc = function() { + return this.reverse(); + }; + Collection2.prototype.eachKey = function(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function(val, cursor) { + cb(cursor.key, cursor); + }); + }; + Collection2.prototype.eachUniqueKey = function(cb) { + this._ctx.unique = "unique"; + return this.eachKey(cb); + }; + Collection2.prototype.eachPrimaryKey = function(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + return this.each(function(val, cursor) { + cb(cursor.primaryKey, cursor); + }); + }; + Collection2.prototype.keys = function(cb) { + var ctx = this._ctx; + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function(item, cursor) { + a.push(cursor.key); + }).then(function() { + return a; + }).then(cb); + }; + Collection2.prototype.primaryKeys = function(cb) { + var ctx = this._ctx; + if (isPlainKeyRange(ctx, true) && ctx.limit > 0) { + return this._read(function(trans) { + var index = getIndexOrStore(ctx, ctx.table.core.schema); + return ctx.table.core.query({ + trans, + values: false, + limit: ctx.limit, + direction: ctx.dir === "prev" ? "prev" : void 0, + query: { + index, + range: ctx.range + } + }); + }).then(function(_a2) { + var result = _a2.result; + return result; + }).then(cb); + } + ctx.keysOnly = !ctx.isMatch; + var a = []; + return this.each(function(item, cursor) { + a.push(cursor.primaryKey); + }).then(function() { + return a; + }).then(cb); + }; + Collection2.prototype.uniqueKeys = function(cb) { + this._ctx.unique = "unique"; + return this.keys(cb); + }; + Collection2.prototype.firstKey = function(cb) { + return this.limit(1).keys(function(a) { + return a[0]; + }).then(cb); + }; + Collection2.prototype.lastKey = function(cb) { + return this.reverse().firstKey(cb); + }; + Collection2.prototype.distinct = function() { + var ctx = this._ctx, idx = ctx.index && ctx.table.schema.idxByName[ctx.index]; + if (!idx || !idx.multi) + return this; + var set = {}; + addFilter(this._ctx, function(cursor) { + var strKey = cursor.primaryKey.toString(); + var found = hasOwn(set, strKey); + set[strKey] = true; + return !found; + }); + return this; + }; + Collection2.prototype.modify = function(changes) { + var _this = this; + var ctx = this._ctx; + return this._write(function(trans) { + var modifyer; + if (typeof changes === "function") { + modifyer = changes; + } else { + modifyer = function(item) { + return applyUpdateSpec(item, changes); + }; + } + var coreTable = ctx.table.core; + var _a2 = coreTable.schema.primaryKey, outbound = _a2.outbound, extractKey2 = _a2.extractKey; + var limit = 200; + var modifyChunkSize = _this.db._options.modifyChunkSize; + if (modifyChunkSize) { + if (typeof modifyChunkSize == "object") { + limit = modifyChunkSize[coreTable.name] || modifyChunkSize["*"] || 200; + } else { + limit = modifyChunkSize; + } + } + var totalFailures = []; + var successCount = 0; + var failedKeys = []; + var applyMutateResult = function(expectedCount, res) { + var failures = res.failures, numFailures = res.numFailures; + successCount += expectedCount - numFailures; + for (var _i = 0, _a3 = keys(failures); _i < _a3.length; _i++) { + var pos = _a3[_i]; + totalFailures.push(failures[pos]); + } + }; + var isUnconditionalDelete = changes === deleteCallback; + return _this.clone().primaryKeys().then(function(keys2) { + var criteria = isPlainKeyRange(ctx) && ctx.limit === Infinity && (typeof changes !== "function" || isUnconditionalDelete) && { + index: ctx.index, + range: ctx.range + }; + var nextChunk = function(offset) { + var count = Math.min(limit, keys2.length - offset); + var keysInChunk = keys2.slice(offset, offset + count); + return (isUnconditionalDelete ? Promise.resolve([]) : coreTable.getMany({ + trans, + keys: keysInChunk, + cache: "immutable" + })).then(function(values) { + var addValues = []; + var putValues = []; + var putKeys = outbound ? [] : null; + var deleteKeys = isUnconditionalDelete ? keysInChunk : []; + if (!isUnconditionalDelete) + for (var i = 0; i < count; ++i) { + var origValue = values[i]; + var ctx_1 = { + value: deepClone(origValue), + primKey: keys2[offset + i] + }; + if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) { + if (ctx_1.value == null) { + deleteKeys.push(keys2[offset + i]); + } else if (!outbound && cmp3(extractKey2(origValue), extractKey2(ctx_1.value)) !== 0) { + deleteKeys.push(keys2[offset + i]); + addValues.push(ctx_1.value); + } else { + putValues.push(ctx_1.value); + if (outbound) + putKeys.push(keys2[offset + i]); + } + } + } + return Promise.resolve(addValues.length > 0 && coreTable.mutate({ trans, type: "add", values: addValues }).then(function(res) { + for (var pos in res.failures) { + deleteKeys.splice(parseInt(pos), 1); + } + applyMutateResult(addValues.length, res); + })).then(function() { + return (putValues.length > 0 || criteria && typeof changes === "object") && coreTable.mutate({ + trans, + type: "put", + keys: putKeys, + values: putValues, + criteria, + changeSpec: typeof changes !== "function" && changes, + isAdditionalChunk: offset > 0 + }).then(function(res) { + return applyMutateResult(putValues.length, res); + }); + }).then(function() { + return (deleteKeys.length > 0 || criteria && isUnconditionalDelete) && coreTable.mutate({ + trans, + type: "delete", + keys: deleteKeys, + criteria, + isAdditionalChunk: offset > 0 + }).then(function(res) { + return builtInDeletionTrigger(ctx.table, deleteKeys, res); + }).then(function(res) { + return applyMutateResult(deleteKeys.length, res); + }); + }).then(function() { + return keys2.length > offset + count && nextChunk(offset + limit); + }); + }); + }; + return nextChunk(0).then(function() { + if (totalFailures.length > 0) + throw new ModifyError("Error modifying one or more objects", totalFailures, successCount, failedKeys); + return keys2.length; + }); + }); + }); + }; + Collection2.prototype.delete = function() { + var ctx = this._ctx, range = ctx.range; + if (isPlainKeyRange(ctx) && !ctx.table.schema.yProps && (ctx.isPrimKey || range.type === 3)) { + return this._write(function(trans) { + var primaryKey = ctx.table.core.schema.primaryKey; + var coreRange = range; + return ctx.table.core.count({ trans, query: { index: primaryKey, range: coreRange } }).then(function(count) { + return ctx.table.core.mutate({ trans, type: "deleteRange", range: coreRange }).then(function(_a2) { + var failures = _a2.failures, numFailures = _a2.numFailures; + if (numFailures) + throw new ModifyError("Could not delete some values", Object.keys(failures).map(function(pos) { + return failures[pos]; + }), count - numFailures); + return count - numFailures; + }); + }); + }); + } + return this.modify(deleteCallback); + }; + return Collection2; + }(); + var deleteCallback = function(value, ctx) { + return ctx.value = null; + }; + function createCollectionConstructor(db2) { + return makeClassConstructor(Collection.prototype, function Collection2(whereClause, keyRangeGenerator) { + this.db = db2; + var keyRange = AnyRange, error = null; + if (keyRangeGenerator) + try { + keyRange = keyRangeGenerator(); + } catch (ex) { + error = ex; + } + var whereCtx = whereClause._ctx; + var table = whereCtx.table; + var readingHook = table.hook.reading.fire; + this._ctx = { + table, + index: whereCtx.index, + isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name, + range: keyRange, + keysOnly: false, + dir: "next", + unique: "", + algorithm: null, + filter: null, + replayFilter: null, + justLimit: true, + isMatch: null, + offset: 0, + limit: Infinity, + error, + or: whereCtx.or, + valueMapper: readingHook !== mirror ? readingHook : null + }; + }); + } + function simpleCompare(a, b) { + return a < b ? -1 : a === b ? 0 : 1; + } + function simpleCompareReverse(a, b) { + return a > b ? -1 : a === b ? 0 : 1; + } + function fail(collectionOrWhereClause, err, T) { + var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause.Collection(collectionOrWhereClause) : collectionOrWhereClause; + collection._ctx.error = T ? new T(err) : new TypeError(err); + return collection; + } + function emptyCollection(whereClause) { + return new whereClause.Collection(whereClause, function() { + return rangeEqual(""); + }).limit(0); + } + function upperFactory(dir) { + return dir === "next" ? function(s) { + return s.toUpperCase(); + } : function(s) { + return s.toLowerCase(); + }; + } + function lowerFactory(dir) { + return dir === "next" ? function(s) { + return s.toLowerCase(); + } : function(s) { + return s.toUpperCase(); + }; + } + function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp4, dir) { + var length = Math.min(key.length, lowerNeedle.length); + var llp = -1; + for (var i = 0; i < length; ++i) { + var lwrKeyChar = lowerKey[i]; + if (lwrKeyChar !== lowerNeedle[i]) { + if (cmp4(key[i], upperNeedle[i]) < 0) + return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1); + if (cmp4(key[i], lowerNeedle[i]) < 0) + return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1); + if (llp >= 0) + return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1); + return null; + } + if (cmp4(key[i], lwrKeyChar) < 0) + llp = i; + } + if (length < lowerNeedle.length && dir === "next") + return key + upperNeedle.substr(key.length); + if (length < key.length && dir === "prev") + return key.substr(0, upperNeedle.length); + return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1); + } + function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) { + var upper, lower, compare, upperNeedles, lowerNeedles, direction, nextKeySuffix, needlesLen = needles.length; + if (!needles.every(function(s) { + return typeof s === "string"; + })) { + return fail(whereClause, STRING_EXPECTED); + } + function initDirection(dir) { + upper = upperFactory(dir); + lower = lowerFactory(dir); + compare = dir === "next" ? simpleCompare : simpleCompareReverse; + var needleBounds = needles.map(function(needle) { + return { lower: lower(needle), upper: upper(needle) }; + }).sort(function(a, b) { + return compare(a.lower, b.lower); + }); + upperNeedles = needleBounds.map(function(nb) { + return nb.upper; + }); + lowerNeedles = needleBounds.map(function(nb) { + return nb.lower; + }); + direction = dir; + nextKeySuffix = dir === "next" ? "" : suffix; + } + initDirection("next"); + var c = new whereClause.Collection(whereClause, function() { + return createRange(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix); + }); + c._ondirectionchange = function(direction2) { + initDirection(direction2); + }; + var firstPossibleNeedle = 0; + c._addAlgorithm(function(cursor, advance, resolve) { + var key = cursor.key; + if (typeof key !== "string") + return false; + var lowerKey = lower(key); + if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) { + return true; + } else { + var lowestPossibleCasing = null; + for (var i = firstPossibleNeedle; i < needlesLen; ++i) { + var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction); + if (casing === null && lowestPossibleCasing === null) + firstPossibleNeedle = i + 1; + else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) { + lowestPossibleCasing = casing; + } + } + if (lowestPossibleCasing !== null) { + advance(function() { + cursor.continue(lowestPossibleCasing + nextKeySuffix); + }); + } else { + advance(resolve); + } + return false; + } + }); + return c; + } + function createRange(lower, upper, lowerOpen, upperOpen) { + return { + type: 2, + lower, + upper, + lowerOpen, + upperOpen + }; + } + function rangeEqual(value) { + return { + type: 1, + lower: value, + upper: value + }; + } + var WhereClause = function() { + function WhereClause2() { + } + Object.defineProperty(WhereClause2.prototype, "Collection", { + get: function() { + return this._ctx.table.db.Collection; + }, + enumerable: false, + configurable: true + }); + WhereClause2.prototype.between = function(lower, upper, includeLower, includeUpper) { + includeLower = includeLower !== false; + includeUpper = includeUpper === true; + try { + if (this._cmp(lower, upper) > 0 || this._cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) + return emptyCollection(this); + return new this.Collection(this, function() { + return createRange(lower, upper, !includeLower, !includeUpper); + }); + } catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + }; + WhereClause2.prototype.equals = function(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function() { + return rangeEqual(value); + }); + }; + WhereClause2.prototype.above = function(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function() { + return createRange(value, void 0, true); + }); + }; + WhereClause2.prototype.aboveOrEqual = function(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function() { + return createRange(value, void 0, false); + }); + }; + WhereClause2.prototype.below = function(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function() { + return createRange(void 0, value, false, true); + }); + }; + WhereClause2.prototype.belowOrEqual = function(value) { + if (value == null) + return fail(this, INVALID_KEY_ARGUMENT); + return new this.Collection(this, function() { + return createRange(void 0, value); + }); + }; + WhereClause2.prototype.startsWith = function(str) { + if (typeof str !== "string") + return fail(this, STRING_EXPECTED); + return this.between(str, str + maxString, true, true); + }; + WhereClause2.prototype.startsWithIgnoreCase = function(str) { + if (str === "") + return this.startsWith(str); + return addIgnoreCaseAlgorithm(this, function(x, a) { + return x.indexOf(a[0]) === 0; + }, [str], maxString); + }; + WhereClause2.prototype.equalsIgnoreCase = function(str) { + return addIgnoreCaseAlgorithm(this, function(x, a) { + return x === a[0]; + }, [str], ""); + }; + WhereClause2.prototype.anyOfIgnoreCase = function() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function(x, a) { + return a.indexOf(x) !== -1; + }, set, ""); + }; + WhereClause2.prototype.startsWithAnyOfIgnoreCase = function() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return emptyCollection(this); + return addIgnoreCaseAlgorithm(this, function(x, a) { + return a.some(function(n) { + return x.indexOf(n) === 0; + }); + }, set, maxString); + }; + WhereClause2.prototype.anyOf = function() { + var _this = this; + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + var compare = this._cmp; + try { + set.sort(compare); + } catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + if (set.length === 0) + return emptyCollection(this); + var c = new this.Collection(this, function() { + return createRange(set[0], set[set.length - 1]); + }); + c._ondirectionchange = function(direction) { + compare = direction === "next" ? _this._ascending : _this._descending; + set.sort(compare); + }; + var i = 0; + c._addAlgorithm(function(cursor, advance, resolve) { + var key = cursor.key; + while (compare(key, set[i]) > 0) { + ++i; + if (i === set.length) { + advance(resolve); + return false; + } + } + if (compare(key, set[i]) === 0) { + return true; + } else { + advance(function() { + cursor.continue(set[i]); + }); + return false; + } + }); + return c; + }; + WhereClause2.prototype.notEqual = function(value) { + return this.inAnyRange([ + [minKey, value], + [value, this.db._maxKey] + ], { includeLowers: false, includeUppers: false }); + }; + WhereClause2.prototype.noneOf = function() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (set.length === 0) + return new this.Collection(this); + try { + set.sort(this._ascending); + } catch (e) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var ranges = set.reduce(function(res, val) { + return res ? res.concat([[res[res.length - 1][1], val]]) : [[minKey, val]]; + }, null); + ranges.push([set[set.length - 1], this.db._maxKey]); + return this.inAnyRange(ranges, { + includeLowers: false, + includeUppers: false + }); + }; + WhereClause2.prototype.inAnyRange = function(ranges, options) { + var _this = this; + var cmp4 = this._cmp, ascending = this._ascending, descending = this._descending, min = this._min, max = this._max; + if (ranges.length === 0) + return emptyCollection(this); + if (!ranges.every(function(range) { + return range[0] !== void 0 && range[1] !== void 0 && ascending(range[0], range[1]) <= 0; + })) { + return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument); + } + var includeLowers = !options || options.includeLowers !== false; + var includeUppers = options && options.includeUppers === true; + function addRange2(ranges2, newRange) { + var i = 0, l = ranges2.length; + for (; i < l; ++i) { + var range = ranges2[i]; + if (cmp4(newRange[0], range[1]) < 0 && cmp4(newRange[1], range[0]) > 0) { + range[0] = min(range[0], newRange[0]); + range[1] = max(range[1], newRange[1]); + break; + } + } + if (i === l) + ranges2.push(newRange); + return ranges2; + } + var sortDirection = ascending; + function rangeSorter(a, b) { + return sortDirection(a[0], b[0]); + } + var set; + try { + set = ranges.reduce(addRange2, []); + set.sort(rangeSorter); + } catch (ex) { + return fail(this, INVALID_KEY_ARGUMENT); + } + var rangePos = 0; + var keyIsBeyondCurrentEntry = includeUppers ? function(key) { + return ascending(key, set[rangePos][1]) > 0; + } : function(key) { + return ascending(key, set[rangePos][1]) >= 0; + }; + var keyIsBeforeCurrentEntry = includeLowers ? function(key) { + return descending(key, set[rangePos][0]) > 0; + } : function(key) { + return descending(key, set[rangePos][0]) >= 0; + }; + function keyWithinCurrentRange(key) { + return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key); + } + var checkKey = keyIsBeyondCurrentEntry; + var c = new this.Collection(this, function() { + return createRange(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers); + }); + c._ondirectionchange = function(direction) { + if (direction === "next") { + checkKey = keyIsBeyondCurrentEntry; + sortDirection = ascending; + } else { + checkKey = keyIsBeforeCurrentEntry; + sortDirection = descending; + } + set.sort(rangeSorter); + }; + c._addAlgorithm(function(cursor, advance, resolve) { + var key = cursor.key; + while (checkKey(key)) { + ++rangePos; + if (rangePos === set.length) { + advance(resolve); + return false; + } + } + if (keyWithinCurrentRange(key)) { + return true; + } else if (_this._cmp(key, set[rangePos][1]) === 0 || _this._cmp(key, set[rangePos][0]) === 0) { + return false; + } else { + advance(function() { + if (sortDirection === ascending) + cursor.continue(set[rangePos][0]); + else + cursor.continue(set[rangePos][1]); + }); + return false; + } + }); + return c; + }; + WhereClause2.prototype.startsWithAnyOf = function() { + var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments); + if (!set.every(function(s) { + return typeof s === "string"; + })) { + return fail(this, "startsWithAnyOf() only works with strings"); + } + if (set.length === 0) + return emptyCollection(this); + return this.inAnyRange(set.map(function(str) { + return [str, str + maxString]; + })); + }; + return WhereClause2; + }(); + function createWhereClauseConstructor(db2) { + return makeClassConstructor(WhereClause.prototype, function WhereClause2(table, index, orCollection) { + this.db = db2; + this._ctx = { + table, + index: index === ":id" ? null : index, + or: orCollection + }; + this._cmp = this._ascending = cmp3; + this._descending = function(a, b) { + return cmp3(b, a); + }; + this._max = function(a, b) { + return cmp3(a, b) > 0 ? a : b; + }; + this._min = function(a, b) { + return cmp3(a, b) < 0 ? a : b; + }; + this._IDBKeyRange = db2._deps.IDBKeyRange; + if (!this._IDBKeyRange) + throw new exceptions.MissingAPI(); + }); + } + function eventRejectHandler(reject) { + return wrap(function(event) { + preventDefault(event); + reject(event.target.error); + return false; + }); + } + function preventDefault(event) { + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); + } + var DEXIE_STORAGE_MUTATED_EVENT_NAME = "storagemutated"; + var STORAGE_MUTATED_DOM_EVENT_NAME = "x-storagemutated-1"; + var globalEvents = Events(null, DEXIE_STORAGE_MUTATED_EVENT_NAME); + var Transaction = function() { + function Transaction2() { + } + Transaction2.prototype._lock = function() { + assert(!PSD.global); + ++this._reculock; + if (this._reculock === 1 && !PSD.global) + PSD.lockOwnerFor = this; + return this; + }; + Transaction2.prototype._unlock = function() { + assert(!PSD.global); + if (--this._reculock === 0) { + if (!PSD.global) + PSD.lockOwnerFor = null; + while (this._blockedFuncs.length > 0 && !this._locked()) { + var fnAndPSD = this._blockedFuncs.shift(); + try { + usePSD(fnAndPSD[1], fnAndPSD[0]); + } catch (e) { + } + } + } + return this; + }; + Transaction2.prototype._locked = function() { + return this._reculock && PSD.lockOwnerFor !== this; + }; + Transaction2.prototype.create = function(idbtrans) { + var _this = this; + if (!this.mode) + return this; + var idbdb = this.db.idbdb; + var dbOpenError = this.db._state.dbOpenError; + assert(!this.idbtrans); + if (!idbtrans && !idbdb) { + switch (dbOpenError && dbOpenError.name) { + case "DatabaseClosedError": + throw new exceptions.DatabaseClosed(dbOpenError); + case "MissingAPIError": + throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError); + default: + throw new exceptions.OpenFailed(dbOpenError); + } + } + if (!this.active) + throw new exceptions.TransactionInactive(); + assert(this._completion._state === null); + idbtrans = this.idbtrans = idbtrans || (this.db.core ? this.db.core.transaction(this.storeNames, this.mode, { durability: this.chromeTransactionDurability }) : idbdb.transaction(this.storeNames, this.mode, { + durability: this.chromeTransactionDurability + })); + idbtrans.onerror = wrap(function(ev) { + preventDefault(ev); + _this._reject(idbtrans.error); + }); + idbtrans.onabort = wrap(function(ev) { + preventDefault(ev); + _this.active && _this._reject(new exceptions.Abort(idbtrans.error)); + _this.active = false; + _this.on("abort").fire(ev); + }); + idbtrans.oncomplete = wrap(function() { + _this.active = false; + _this._resolve(); + if ("mutatedParts" in idbtrans) { + globalEvents.storagemutated.fire(idbtrans["mutatedParts"]); + } + }); + return this; + }; + Transaction2.prototype._promise = function(mode, fn, bWriteLock) { + var _this = this; + if (mode === "readwrite" && this.mode !== "readwrite") + return rejection(new exceptions.ReadOnly("Transaction is readonly")); + if (!this.active) + return rejection(new exceptions.TransactionInactive()); + if (this._locked()) { + return new DexiePromise(function(resolve, reject) { + _this._blockedFuncs.push([ + function() { + _this._promise(mode, fn, bWriteLock).then(resolve, reject); + }, + PSD + ]); + }); + } else if (bWriteLock) { + return newScope(function() { + var p2 = new DexiePromise(function(resolve, reject) { + _this._lock(); + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p2.finally(function() { + return _this._unlock(); + }); + p2._lib = true; + return p2; + }); + } else { + var p = new DexiePromise(function(resolve, reject) { + var rv = fn(resolve, reject, _this); + if (rv && rv.then) + rv.then(resolve, reject); + }); + p._lib = true; + return p; + } + }; + Transaction2.prototype._root = function() { + return this.parent ? this.parent._root() : this; + }; + Transaction2.prototype.waitFor = function(promiseLike) { + var root = this._root(); + var promise = DexiePromise.resolve(promiseLike); + if (root._waitingFor) { + root._waitingFor = root._waitingFor.then(function() { + return promise; + }); + } else { + root._waitingFor = promise; + root._waitingQueue = []; + var store = root.idbtrans.objectStore(root.storeNames[0]); + (function spin() { + ++root._spinCount; + while (root._waitingQueue.length) + root._waitingQueue.shift()(); + if (root._waitingFor) + store.get(-Infinity).onsuccess = spin; + })(); + } + var currentWaitPromise = root._waitingFor; + return new DexiePromise(function(resolve, reject) { + promise.then(function(res) { + return root._waitingQueue.push(wrap(resolve.bind(null, res))); + }, function(err) { + return root._waitingQueue.push(wrap(reject.bind(null, err))); + }).finally(function() { + if (root._waitingFor === currentWaitPromise) { + root._waitingFor = null; + } + }); + }); + }; + Transaction2.prototype.abort = function() { + if (this.active) { + this.active = false; + if (this.idbtrans) + this.idbtrans.abort(); + this._reject(new exceptions.Abort()); + } + }; + Transaction2.prototype.table = function(tableName) { + var memoizedTables = this._memoizedTables || (this._memoizedTables = {}); + if (hasOwn(memoizedTables, tableName)) + return memoizedTables[tableName]; + var tableSchema = this.schema[tableName]; + if (!tableSchema) { + throw new exceptions.NotFound("Table " + tableName + " not part of transaction"); + } + var transactionBoundTable = new this.db.Table(tableName, tableSchema, this); + transactionBoundTable.core = this.db.core.table(tableName); + memoizedTables[tableName] = transactionBoundTable; + return transactionBoundTable; + }; + return Transaction2; + }(); + function createTransactionConstructor(db2) { + return makeClassConstructor(Transaction.prototype, function Transaction2(mode, storeNames, dbschema, chromeTransactionDurability, parent) { + var _this = this; + if (mode !== "readonly") + storeNames.forEach(function(storeName) { + var _a2; + var yProps = (_a2 = dbschema[storeName]) === null || _a2 === void 0 ? void 0 : _a2.yProps; + if (yProps) + storeNames = storeNames.concat(yProps.map(function(p) { + return p.updatesTable; + })); + }); + this.db = db2; + this.mode = mode; + this.storeNames = storeNames; + this.schema = dbschema; + this.chromeTransactionDurability = chromeTransactionDurability; + this.idbtrans = null; + this.on = Events(this, "complete", "error", "abort"); + this.parent = parent || null; + this.active = true; + this._reculock = 0; + this._blockedFuncs = []; + this._resolve = null; + this._reject = null; + this._waitingFor = null; + this._waitingQueue = null; + this._spinCount = 0; + this._completion = new DexiePromise(function(resolve, reject) { + _this._resolve = resolve; + _this._reject = reject; + }); + this._completion.then(function() { + _this.active = false; + _this.on.complete.fire(); + }, function(e) { + var wasActive = _this.active; + _this.active = false; + _this.on.error.fire(e); + _this.parent ? _this.parent._reject(e) : wasActive && _this.idbtrans && _this.idbtrans.abort(); + return rejection(e); + }); + }); + } + function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey, type2) { + return { + name, + keyPath, + unique, + multi, + auto, + compound, + src: (unique && !isPrimKey ? "&" : "") + (multi ? "*" : "") + (auto ? "++" : "") + nameFromKeyPath(keyPath), + type: type2 + }; + } + function nameFromKeyPath(keyPath) { + return typeof keyPath === "string" ? keyPath : keyPath ? "[" + [].join.call(keyPath, "+") + "]" : ""; + } + function createTableSchema(name, primKey, indexes) { + return { + name, + primKey, + indexes, + mappedClass: null, + idxByName: arrayToObject(indexes, function(index) { + return [index.name, index]; + }) + }; + } + function safariMultiStoreFix(storeNames) { + return storeNames.length === 1 ? storeNames[0] : storeNames; + } + var getMaxKey = function(IdbKeyRange) { + try { + IdbKeyRange.only([[]]); + getMaxKey = function() { + return [[]]; + }; + return [[]]; + } catch (e) { + getMaxKey = function() { + return maxString; + }; + return maxString; + } + }; + function getKeyExtractor(keyPath) { + if (keyPath == null) { + return function() { + return void 0; + }; + } else if (typeof keyPath === "string") { + return getSinglePathKeyExtractor(keyPath); + } else { + return function(obj) { + return getByKeyPath(obj, keyPath); + }; + } + } + function getSinglePathKeyExtractor(keyPath) { + var split = keyPath.split("."); + if (split.length === 1) { + return function(obj) { + return obj[keyPath]; + }; + } else { + return function(obj) { + return getByKeyPath(obj, keyPath); + }; + } + } + function arrayify(arrayLike) { + return [].slice.call(arrayLike); + } + var _id_counter = 0; + function getKeyPathAlias(keyPath) { + return keyPath == null ? ":id" : typeof keyPath === "string" ? keyPath : "[".concat(keyPath.join("+"), "]"); + } + function createDBCore(db2, IdbKeyRange, tmpTrans) { + function extractSchema(db3, trans) { + var tables2 = arrayify(db3.objectStoreNames); + var tempStore = tables2.length > 0 ? trans.objectStore(tables2[0]) : {}; + return { + schema: { + name: db3.name, + tables: tables2.map(function(table) { + return trans.objectStore(table); + }).map(function(store) { + var keyPath = store.keyPath, autoIncrement = store.autoIncrement; + var compound = isArray(keyPath); + var outbound = keyPath == null; + var indexByKeyPath = {}; + var result = { + name: store.name, + primaryKey: { + name: null, + isPrimaryKey: true, + outbound, + compound, + keyPath, + autoIncrement, + unique: true, + extractKey: getKeyExtractor(keyPath) + }, + indexes: arrayify(store.indexNames).map(function(indexName) { + return store.index(indexName); + }).map(function(index) { + var name = index.name, unique = index.unique, multiEntry = index.multiEntry, keyPath2 = index.keyPath; + var compound2 = isArray(keyPath2); + var result2 = { + name, + compound: compound2, + keyPath: keyPath2, + unique, + multiEntry, + extractKey: getKeyExtractor(keyPath2) + }; + indexByKeyPath[getKeyPathAlias(keyPath2)] = result2; + return result2; + }), + getIndexByKeyPath: function(keyPath2) { + return indexByKeyPath[getKeyPathAlias(keyPath2)]; + } + }; + indexByKeyPath[":id"] = result.primaryKey; + if (keyPath != null) { + indexByKeyPath[getKeyPathAlias(keyPath)] = result.primaryKey; + } + return result; + }) + }, + hasGetAll: tables2.length > 0 && "getAll" in tempStore && !(typeof navigator !== "undefined" && /Safari/.test(navigator.userAgent) && !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604), + hasIdb3Features: "getAllRecords" in tempStore + }; + } + function makeIDBKeyRange(range) { + if (range.type === 3) + return null; + if (range.type === 4) + throw new Error("Cannot convert never type to IDBKeyRange"); + var lower = range.lower, upper = range.upper, lowerOpen = range.lowerOpen, upperOpen = range.upperOpen; + var idbRange = lower === void 0 ? upper === void 0 ? null : IdbKeyRange.upperBound(upper, !!upperOpen) : upper === void 0 ? IdbKeyRange.lowerBound(lower, !!lowerOpen) : IdbKeyRange.bound(lower, upper, !!lowerOpen, !!upperOpen); + return idbRange; + } + function createDbCoreTable(tableSchema) { + var tableName = tableSchema.name; + function mutate(_a3) { + var trans = _a3.trans, type2 = _a3.type, keys2 = _a3.keys, values = _a3.values, range = _a3.range; + return new Promise(function(resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var outbound = store.keyPath == null; + var isAddOrPut = type2 === "put" || type2 === "add"; + if (!isAddOrPut && type2 !== "delete" && type2 !== "deleteRange") + throw new Error("Invalid operation type: " + type2); + var length = (keys2 || values || { length: 1 }).length; + if (keys2 && values && keys2.length !== values.length) { + throw new Error("Given keys array must have same length as given values array."); + } + if (length === 0) + return resolve({ + numFailures: 0, + failures: {}, + results: [], + lastResult: void 0 + }); + var req; + var reqs = []; + var failures = []; + var numFailures = 0; + var errorHandler = function(event) { + ++numFailures; + preventDefault(event); + }; + if (type2 === "deleteRange") { + if (range.type === 4) + return resolve({ + numFailures, + failures, + results: [], + lastResult: void 0 + }); + if (range.type === 3) + reqs.push(req = store.clear()); + else + reqs.push(req = store.delete(makeIDBKeyRange(range))); + } else { + var _a4 = isAddOrPut ? outbound ? [values, keys2] : [values, null] : [keys2, null], args1 = _a4[0], args2 = _a4[1]; + if (isAddOrPut) { + for (var i = 0; i < length; ++i) { + reqs.push(req = args2 && args2[i] !== void 0 ? store[type2](args1[i], args2[i]) : store[type2](args1[i])); + req.onerror = errorHandler; + } + } else { + for (var i = 0; i < length; ++i) { + reqs.push(req = store[type2](args1[i])); + req.onerror = errorHandler; + } + } + } + var done = function(event) { + var lastResult = event.target.result; + reqs.forEach(function(req2, i2) { + return req2.error != null && (failures[i2] = req2.error); + }); + resolve({ + numFailures, + failures, + results: type2 === "delete" ? keys2 : reqs.map(function(req2) { + return req2.result; + }), + lastResult + }); + }; + req.onerror = function(event) { + errorHandler(event); + done(event); + }; + req.onsuccess = done; + }); + } + function openCursor2(_a3) { + var trans = _a3.trans, values = _a3.values, query2 = _a3.query, reverse = _a3.reverse, unique = _a3.unique; + return new Promise(function(resolve, reject) { + resolve = wrap(resolve); + var index = query2.index, range = query2.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var direction = reverse ? unique ? "prevunique" : "prev" : unique ? "nextunique" : "next"; + var req = values || !("openKeyCursor" in source) ? source.openCursor(makeIDBKeyRange(range), direction) : source.openKeyCursor(makeIDBKeyRange(range), direction); + req.onerror = eventRejectHandler(reject); + req.onsuccess = wrap(function(ev) { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + cursor.___id = ++_id_counter; + cursor.done = false; + var _cursorContinue = cursor.continue.bind(cursor); + var _cursorContinuePrimaryKey = cursor.continuePrimaryKey; + if (_cursorContinuePrimaryKey) + _cursorContinuePrimaryKey = _cursorContinuePrimaryKey.bind(cursor); + var _cursorAdvance = cursor.advance.bind(cursor); + var doThrowCursorIsNotStarted = function() { + throw new Error("Cursor not started"); + }; + var doThrowCursorIsStopped = function() { + throw new Error("Cursor not stopped"); + }; + cursor.trans = trans; + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsNotStarted; + cursor.fail = wrap(reject); + cursor.next = function() { + var _this = this; + var gotOne = 1; + return this.start(function() { + return gotOne-- ? _this.continue() : _this.stop(); + }).then(function() { + return _this; + }); + }; + cursor.start = function(callback) { + var iterationPromise = new Promise(function(resolveIteration, rejectIteration) { + resolveIteration = wrap(resolveIteration); + req.onerror = eventRejectHandler(rejectIteration); + cursor.fail = rejectIteration; + cursor.stop = function(value) { + cursor.stop = cursor.continue = cursor.continuePrimaryKey = cursor.advance = doThrowCursorIsStopped; + resolveIteration(value); + }; + }); + var guardedCallback = function() { + if (req.result) { + try { + callback(); + } catch (err) { + cursor.fail(err); + } + } else { + cursor.done = true; + cursor.start = function() { + throw new Error("Cursor behind last entry"); + }; + cursor.stop(); + } + }; + req.onsuccess = wrap(function(ev2) { + req.onsuccess = guardedCallback; + guardedCallback(); + }); + cursor.continue = _cursorContinue; + cursor.continuePrimaryKey = _cursorContinuePrimaryKey; + cursor.advance = _cursorAdvance; + guardedCallback(); + return iterationPromise; + }; + resolve(cursor); + }, reject); + }); + } + function query(hasGetAll2, hasIdb3Features2) { + return function(request) { + return new Promise(function(resolve, reject) { + var _a3; + resolve = wrap(resolve); + var trans = request.trans, values = request.values, limit = request.limit, query2 = request.query; + var direction = (_a3 = request.direction) !== null && _a3 !== void 0 ? _a3 : "next"; + var nonInfinitLimit = limit === Infinity ? void 0 : limit; + var index = query2.index, range = query2.range; + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + if (limit === 0) + return resolve({ result: [] }); + if (hasIdb3Features2) { + var options = { + query: idbKeyRange, + count: nonInfinitLimit, + direction + }; + var req = values ? source.getAll(options) : source.getAllKeys(options); + req.onsuccess = function(event) { + return resolve({ result: event.target.result }); + }; + req.onerror = eventRejectHandler(reject); + } else if (hasGetAll2 && direction === "next") { + var req = values ? source.getAll(idbKeyRange, nonInfinitLimit) : source.getAllKeys(idbKeyRange, nonInfinitLimit); + req.onsuccess = function(event) { + return resolve({ result: event.target.result }); + }; + req.onerror = eventRejectHandler(reject); + } else { + var count_1 = 0; + var req_1 = values || !("openKeyCursor" in source) ? source.openCursor(idbKeyRange, direction) : source.openKeyCursor(idbKeyRange, direction); + var result_1 = []; + req_1.onsuccess = function() { + var cursor = req_1.result; + if (!cursor) + return resolve({ result: result_1 }); + result_1.push(values ? cursor.value : cursor.primaryKey); + if (++count_1 === limit) + return resolve({ result: result_1 }); + cursor.continue(); + }; + req_1.onerror = eventRejectHandler(reject); + } + }); + }; + } + return { + name: tableName, + schema: tableSchema, + mutate, + getMany: function(_a3) { + var trans = _a3.trans, keys2 = _a3.keys; + return new Promise(function(resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var length = keys2.length; + var result = new Array(length); + var keyCount = 0; + var callbackCount = 0; + var req; + var successHandler = function(event) { + var req2 = event.target; + if ((result[req2._pos] = req2.result) != null) + ; + if (++callbackCount === keyCount) + resolve(result); + }; + var errorHandler = eventRejectHandler(reject); + for (var i = 0; i < length; ++i) { + var key = keys2[i]; + if (key != null) { + req = store.get(keys2[i]); + req._pos = i; + req.onsuccess = successHandler; + req.onerror = errorHandler; + ++keyCount; + } + } + if (keyCount === 0) + resolve(result); + }); + }, + get: function(_a3) { + var trans = _a3.trans, key = _a3.key; + return new Promise(function(resolve, reject) { + resolve = wrap(resolve); + var store = trans.objectStore(tableName); + var req = store.get(key); + req.onsuccess = function(event) { + return resolve(event.target.result); + }; + req.onerror = eventRejectHandler(reject); + }); + }, + query: query(hasGetAll, hasIdb3Features), + openCursor: openCursor2, + count: function(_a3) { + var query2 = _a3.query, trans = _a3.trans; + var index = query2.index, range = query2.range; + return new Promise(function(resolve, reject) { + var store = trans.objectStore(tableName); + var source = index.isPrimaryKey ? store : store.index(index.name); + var idbKeyRange = makeIDBKeyRange(range); + var req = idbKeyRange ? source.count(idbKeyRange) : source.count(); + req.onsuccess = wrap(function(ev) { + return resolve(ev.target.result); + }); + req.onerror = eventRejectHandler(reject); + }); + } + }; + } + var _a2 = extractSchema(db2, tmpTrans), schema = _a2.schema, hasGetAll = _a2.hasGetAll, hasIdb3Features = _a2.hasIdb3Features; + var tables = schema.tables.map(function(tableSchema) { + return createDbCoreTable(tableSchema); + }); + var tableMap = {}; + tables.forEach(function(table) { + return tableMap[table.name] = table; + }); + return { + stack: "dbcore", + transaction: db2.transaction.bind(db2), + table: function(name) { + var result = tableMap[name]; + if (!result) + throw new Error("Table '".concat(name, "' not found")); + return tableMap[name]; + }, + MIN_KEY: -Infinity, + MAX_KEY: getMaxKey(IdbKeyRange), + schema + }; + } + function createMiddlewareStack(stackImpl, middlewares) { + return middlewares.reduce(function(down, _a2) { + var create = _a2.create; + return __assign(__assign({}, down), create(down)); + }, stackImpl); + } + function createMiddlewareStacks(middlewares, idbdb, _a2, tmpTrans) { + var IDBKeyRange = _a2.IDBKeyRange; + _a2.indexedDB; + var dbcore = createMiddlewareStack(createDBCore(idbdb, IDBKeyRange, tmpTrans), middlewares.dbcore); + return { + dbcore + }; + } + function generateMiddlewareStacks(db2, tmpTrans) { + var idbdb = tmpTrans.db; + var stacks = createMiddlewareStacks(db2._middlewares, idbdb, db2._deps, tmpTrans); + db2.core = stacks.dbcore; + db2.tables.forEach(function(table) { + var tableName = table.name; + if (db2.core.schema.tables.some(function(tbl) { + return tbl.name === tableName; + })) { + table.core = db2.core.table(tableName); + if (db2[tableName] instanceof db2.Table) { + db2[tableName].core = table.core; + } + } + }); + } + function setApiOnPlace(db2, objs, tableNames, dbschema) { + tableNames.forEach(function(tableName) { + var schema = dbschema[tableName]; + objs.forEach(function(obj) { + var propDesc = getPropertyDescriptor(obj, tableName); + if (!propDesc || "value" in propDesc && propDesc.value === void 0) { + if (obj === db2.Transaction.prototype || obj instanceof db2.Transaction) { + setProp(obj, tableName, { + get: function() { + return this.table(tableName); + }, + set: function(value) { + defineProperty(this, tableName, { + value, + writable: true, + configurable: true, + enumerable: true + }); + } + }); + } else { + obj[tableName] = new db2.Table(tableName, schema); + } + } + }); + }); + } + function removeTablesApi(db2, objs) { + objs.forEach(function(obj) { + for (var key in obj) { + if (obj[key] instanceof db2.Table) + delete obj[key]; + } + }); + } + function lowerVersionFirst(a, b) { + return a._cfg.version - b._cfg.version; + } + function runUpgraders(db2, oldVersion, idbUpgradeTrans, reject) { + var globalSchema = db2._dbSchema; + if (idbUpgradeTrans.objectStoreNames.contains("$meta") && !globalSchema.$meta) { + globalSchema.$meta = createTableSchema("$meta", parseIndexSyntax("")[0], []); + db2._storeNames.push("$meta"); + } + var trans = db2._createTransaction("readwrite", db2._storeNames, globalSchema); + trans.create(idbUpgradeTrans); + trans._completion.catch(reject); + var rejectTransaction = trans._reject.bind(trans); + var transless = PSD.transless || PSD; + newScope(function() { + PSD.trans = trans; + PSD.transless = transless; + if (oldVersion === 0) { + keys(globalSchema).forEach(function(tableName) { + createTable(idbUpgradeTrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes); + }); + generateMiddlewareStacks(db2, idbUpgradeTrans); + DexiePromise.follow(function() { + return db2.on.populate.fire(trans); + }).catch(rejectTransaction); + } else { + generateMiddlewareStacks(db2, idbUpgradeTrans); + return getExistingVersion(db2, trans, oldVersion).then(function(oldVersion2) { + return updateTablesAndIndexes(db2, oldVersion2, trans, idbUpgradeTrans); + }).catch(rejectTransaction); + } + }); + } + function patchCurrentVersion(db2, idbUpgradeTrans) { + createMissingTables(db2._dbSchema, idbUpgradeTrans); + if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains("$meta")) { + idbUpgradeTrans.db.createObjectStore("$meta").add(Math.ceil(idbUpgradeTrans.db.version / 10 - 1), "version"); + } + var globalSchema = buildGlobalSchema(db2, db2.idbdb, idbUpgradeTrans); + adjustToExistingIndexNames(db2, db2._dbSchema, idbUpgradeTrans); + var diff = getSchemaDiff(globalSchema, db2._dbSchema); + var _loop_1 = function(tableChange2) { + if (tableChange2.change.length || tableChange2.recreate) { + console.warn("Unable to patch indexes of table ".concat(tableChange2.name, " because it has changes on the type of index or primary key.")); + return { value: void 0 }; + } + var store = idbUpgradeTrans.objectStore(tableChange2.name); + tableChange2.add.forEach(function(idx) { + if (debug) + console.debug("Dexie upgrade patch: Creating missing index ".concat(tableChange2.name, ".").concat(idx.src)); + addIndex(store, idx); + }); + }; + for (var _i = 0, _a2 = diff.change; _i < _a2.length; _i++) { + var tableChange = _a2[_i]; + var state_1 = _loop_1(tableChange); + if (typeof state_1 === "object") + return state_1.value; + } + } + function getExistingVersion(db2, trans, oldVersion) { + if (trans.storeNames.includes("$meta")) { + return trans.table("$meta").get("version").then(function(metaVersion) { + return metaVersion != null ? metaVersion : oldVersion; + }); + } else { + return DexiePromise.resolve(oldVersion); + } + } + function updateTablesAndIndexes(db2, oldVersion, trans, idbUpgradeTrans) { + var queue = []; + var versions = db2._versions; + var globalSchema = db2._dbSchema = buildGlobalSchema(db2, db2.idbdb, idbUpgradeTrans); + var versToRun = versions.filter(function(v) { + return v._cfg.version >= oldVersion; + }); + if (versToRun.length === 0) { + return DexiePromise.resolve(); + } + versToRun.forEach(function(version) { + queue.push(function() { + var oldSchema = globalSchema; + var newSchema = version._cfg.dbschema; + adjustToExistingIndexNames(db2, oldSchema, idbUpgradeTrans); + adjustToExistingIndexNames(db2, newSchema, idbUpgradeTrans); + globalSchema = db2._dbSchema = newSchema; + var diff = getSchemaDiff(oldSchema, newSchema); + diff.add.forEach(function(tuple) { + createTable(idbUpgradeTrans, tuple[0], tuple[1].primKey, tuple[1].indexes); + }); + diff.change.forEach(function(change) { + if (change.recreate) { + throw new exceptions.Upgrade("Not yet support for changing primary key"); + } else { + var store_1 = idbUpgradeTrans.objectStore(change.name); + change.add.forEach(function(idx) { + return addIndex(store_1, idx); + }); + change.change.forEach(function(idx) { + store_1.deleteIndex(idx.name); + addIndex(store_1, idx); + }); + change.del.forEach(function(idxName) { + return store_1.deleteIndex(idxName); + }); + } + }); + var contentUpgrade = version._cfg.contentUpgrade; + if (contentUpgrade && version._cfg.version > oldVersion) { + generateMiddlewareStacks(db2, idbUpgradeTrans); + trans._memoizedTables = {}; + var upgradeSchema_1 = shallowClone(newSchema); + diff.del.forEach(function(table) { + upgradeSchema_1[table] = oldSchema[table]; + }); + removeTablesApi(db2, [db2.Transaction.prototype]); + setApiOnPlace(db2, [db2.Transaction.prototype], keys(upgradeSchema_1), upgradeSchema_1); + trans.schema = upgradeSchema_1; + var contentUpgradeIsAsync_1 = isAsyncFunction(contentUpgrade); + if (contentUpgradeIsAsync_1) { + incrementExpectedAwaits(); + } + var returnValue_1; + var promiseFollowed = DexiePromise.follow(function() { + returnValue_1 = contentUpgrade(trans); + if (returnValue_1) { + if (contentUpgradeIsAsync_1) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue_1.then(decrementor, decrementor); + } + } + }); + return returnValue_1 && typeof returnValue_1.then === "function" ? DexiePromise.resolve(returnValue_1) : promiseFollowed.then(function() { + return returnValue_1; + }); + } + }); + queue.push(function(idbtrans) { + var newSchema = version._cfg.dbschema; + deleteRemovedTables(newSchema, idbtrans); + removeTablesApi(db2, [db2.Transaction.prototype]); + setApiOnPlace(db2, [db2.Transaction.prototype], db2._storeNames, db2._dbSchema); + trans.schema = db2._dbSchema; + }); + queue.push(function(idbtrans) { + if (db2.idbdb.objectStoreNames.contains("$meta")) { + if (Math.ceil(db2.idbdb.version / 10) === version._cfg.version) { + db2.idbdb.deleteObjectStore("$meta"); + delete db2._dbSchema.$meta; + db2._storeNames = db2._storeNames.filter(function(name) { + return name !== "$meta"; + }); + } else { + idbtrans.objectStore("$meta").put(version._cfg.version, "version"); + } + } + }); + }); + function runQueue() { + return queue.length ? DexiePromise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : DexiePromise.resolve(); + } + return runQueue().then(function() { + createMissingTables(globalSchema, idbUpgradeTrans); + }); + } + function getSchemaDiff(oldSchema, newSchema) { + var diff = { + del: [], + add: [], + change: [] + }; + var table; + for (table in oldSchema) { + if (!newSchema[table]) + diff.del.push(table); + } + for (table in newSchema) { + var oldDef = oldSchema[table], newDef = newSchema[table]; + if (!oldDef) { + diff.add.push([table, newDef]); + } else { + var change = { + name: table, + def: newDef, + recreate: false, + del: [], + add: [], + change: [] + }; + if ("" + (oldDef.primKey.keyPath || "") !== "" + (newDef.primKey.keyPath || "") || oldDef.primKey.auto !== newDef.primKey.auto) { + change.recreate = true; + diff.change.push(change); + } else { + var oldIndexes = oldDef.idxByName; + var newIndexes = newDef.idxByName; + var idxName = void 0; + for (idxName in oldIndexes) { + if (!newIndexes[idxName]) + change.del.push(idxName); + } + for (idxName in newIndexes) { + var oldIdx = oldIndexes[idxName], newIdx = newIndexes[idxName]; + if (!oldIdx) + change.add.push(newIdx); + else if (oldIdx.src !== newIdx.src) + change.change.push(newIdx); + } + if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) { + diff.change.push(change); + } + } + } + } + return diff; + } + function createTable(idbtrans, tableName, primKey, indexes) { + var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto }); + indexes.forEach(function(idx) { + return addIndex(store, idx); + }); + return store; + } + function createMissingTables(newSchema, idbtrans) { + keys(newSchema).forEach(function(tableName) { + if (!idbtrans.db.objectStoreNames.contains(tableName)) { + if (debug) + console.debug("Dexie: Creating missing table", tableName); + createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes); + } + }); + } + function deleteRemovedTables(newSchema, idbtrans) { + [].slice.call(idbtrans.db.objectStoreNames).forEach(function(storeName) { + return newSchema[storeName] == null && idbtrans.db.deleteObjectStore(storeName); + }); + } + function addIndex(store, idx) { + store.createIndex(idx.name, idx.keyPath, { + unique: idx.unique, + multiEntry: idx.multi + }); + } + function buildGlobalSchema(db2, idbdb, tmpTrans) { + var globalSchema = {}; + var dbStoreNames = slice(idbdb.objectStoreNames, 0); + dbStoreNames.forEach(function(storeName) { + var store = tmpTrans.objectStore(storeName); + var keyPath = store.keyPath; + var primKey = createIndexSpec(nameFromKeyPath(keyPath), keyPath || "", true, false, !!store.autoIncrement, keyPath && typeof keyPath !== "string", true); + var indexes = []; + for (var j = 0; j < store.indexNames.length; ++j) { + var idbindex = store.index(store.indexNames[j]); + keyPath = idbindex.keyPath; + var index = createIndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== "string", false); + indexes.push(index); + } + globalSchema[storeName] = createTableSchema(storeName, primKey, indexes); + }); + return globalSchema; + } + function readGlobalSchema(db2, idbdb, tmpTrans) { + db2.verno = idbdb.version / 10; + var globalSchema = db2._dbSchema = buildGlobalSchema(db2, idbdb, tmpTrans); + db2._storeNames = slice(idbdb.objectStoreNames, 0); + setApiOnPlace(db2, [db2._allTables], keys(globalSchema), globalSchema); + } + function verifyInstalledSchema(db2, tmpTrans) { + var installedSchema = buildGlobalSchema(db2, db2.idbdb, tmpTrans); + var diff = getSchemaDiff(installedSchema, db2._dbSchema); + return !(diff.add.length || diff.change.some(function(ch) { + return ch.add.length || ch.change.length; + })); + } + function adjustToExistingIndexNames(db2, schema, idbtrans) { + var storeNames = idbtrans.db.objectStoreNames; + for (var i = 0; i < storeNames.length; ++i) { + var storeName = storeNames[i]; + var store = idbtrans.objectStore(storeName); + db2._hasGetAll = "getAll" in store; + for (var j = 0; j < store.indexNames.length; ++j) { + var indexName = store.indexNames[j]; + var keyPath = store.index(indexName).keyPath; + var dexieName = typeof keyPath === "string" ? keyPath : "[" + slice(keyPath).join("+") + "]"; + if (schema[storeName]) { + var indexSpec = schema[storeName].idxByName[dexieName]; + if (indexSpec) { + indexSpec.name = indexName; + delete schema[storeName].idxByName[dexieName]; + schema[storeName].idxByName[indexName] = indexSpec; + } + } + } + } + if (typeof navigator !== "undefined" && /Safari/.test(navigator.userAgent) && !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && _global.WorkerGlobalScope && _global instanceof _global.WorkerGlobalScope && [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604) { + db2._hasGetAll = false; + } + } + function parseIndexSyntax(primKeyAndIndexes) { + return primKeyAndIndexes.split(",").map(function(index, indexNum) { + var _a2; + var typeSplit = index.split(":"); + var type2 = (_a2 = typeSplit[1]) === null || _a2 === void 0 ? void 0 : _a2.trim(); + index = typeSplit[0].trim(); + var name = index.replace(/([&*]|\+\+)/g, ""); + var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split("+") : name; + return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0, type2); + }); + } + var Version = function() { + function Version2() { + } + Version2.prototype._createTableSchema = function(name, primKey, indexes) { + return createTableSchema(name, primKey, indexes); + }; + Version2.prototype._parseIndexSyntax = function(primKeyAndIndexes) { + return parseIndexSyntax(primKeyAndIndexes); + }; + Version2.prototype._parseStoresSpec = function(stores, outSchema) { + var _this = this; + keys(stores).forEach(function(tableName) { + if (stores[tableName] !== null) { + var indexes = _this._parseIndexSyntax(stores[tableName]); + var primKey = indexes.shift(); + if (!primKey) { + throw new exceptions.Schema("Invalid schema for table " + tableName + ": " + stores[tableName]); + } + primKey.unique = true; + if (primKey.multi) + throw new exceptions.Schema("Primary key cannot be multiEntry*"); + indexes.forEach(function(idx) { + if (idx.auto) + throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)"); + if (!idx.keyPath) + throw new exceptions.Schema("Index must have a name and cannot be an empty string"); + }); + var tblSchema = _this._createTableSchema(tableName, primKey, indexes); + outSchema[tableName] = tblSchema; + } + }); + }; + Version2.prototype.stores = function(stores) { + var db2 = this.db; + this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores; + var versions = db2._versions; + var storesSpec = {}; + var dbschema = {}; + versions.forEach(function(version) { + extend(storesSpec, version._cfg.storesSource); + dbschema = version._cfg.dbschema = {}; + version._parseStoresSpec(storesSpec, dbschema); + }); + db2._dbSchema = dbschema; + removeTablesApi(db2, [db2._allTables, db2, db2.Transaction.prototype]); + setApiOnPlace(db2, [db2._allTables, db2, db2.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema); + db2._storeNames = keys(dbschema); + return this; + }; + Version2.prototype.upgrade = function(upgradeFunction) { + this._cfg.contentUpgrade = promisableChain(this._cfg.contentUpgrade || nop, upgradeFunction); + return this; + }; + return Version2; + }(); + function createVersionConstructor(db2) { + return makeClassConstructor(Version.prototype, function Version2(versionNumber) { + this.db = db2; + this._cfg = { + version: versionNumber, + storesSource: null, + dbschema: {}, + tables: {}, + contentUpgrade: null + }; + }); + } + var connections = createConnectionsManager(); + function createConnectionsManager() { + if (typeof FinalizationRegistry !== "undefined" && typeof WeakRef !== "undefined") { + var _refs_1 = /* @__PURE__ */ new Set(); + var _registry_1 = new FinalizationRegistry(function(ref) { + _refs_1.delete(ref); + }); + var toArray = function() { + return Array.from(_refs_1).map(function(ref) { + return ref.deref(); + }).filter(function(db2) { + return db2 !== void 0; + }); + }; + var add3 = function(db2) { + var ref = new WeakRef(db2._novip); + _refs_1.add(ref); + _registry_1.register(db2._novip, ref, ref); + if (_refs_1.size > db2._options.maxConnections) { + var oldestRef = _refs_1.values().next().value; + _refs_1.delete(oldestRef); + _registry_1.unregister(oldestRef); + } + }; + var remove3 = function(db2) { + if (!db2) + return; + var iterator = _refs_1.values(); + var result = iterator.next(); + while (!result.done) { + var ref = result.value; + if (ref.deref() === db2._novip) { + _refs_1.delete(ref); + _registry_1.unregister(ref); + return; + } + result = iterator.next(); + } + }; + return { toArray, add: add3, remove: remove3 }; + } else { + var connections_1 = []; + var toArray = function() { + return connections_1; + }; + var add3 = function(db2) { + connections_1.push(db2._novip); + }; + var remove3 = function(db2) { + if (!db2) + return; + var index = connections_1.indexOf(db2._novip); + if (index !== -1) { + connections_1.splice(index, 1); + } + }; + return { toArray, add: add3, remove: remove3 }; + } + } + function getDbNamesTable(indexedDB2, IDBKeyRange) { + var dbNamesDB = indexedDB2["_dbNamesDB"]; + if (!dbNamesDB) { + dbNamesDB = indexedDB2["_dbNamesDB"] = new Dexie$1(DBNAMES_DB, { + addons: [], + indexedDB: indexedDB2, + IDBKeyRange + }); + dbNamesDB.version(1).stores({ dbnames: "name" }); + } + return dbNamesDB.table("dbnames"); + } + function hasDatabasesNative(indexedDB2) { + return indexedDB2 && typeof indexedDB2.databases === "function"; + } + function getDatabaseNames(_a2) { + var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; + return hasDatabasesNative(indexedDB2) ? Promise.resolve(indexedDB2.databases()).then(function(infos) { + return infos.map(function(info) { + return info.name; + }).filter(function(name) { + return name !== DBNAMES_DB; + }); + }) : getDbNamesTable(indexedDB2, IDBKeyRange).toCollection().primaryKeys(); + } + function _onDatabaseCreated(_a2, name) { + var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; + !hasDatabasesNative(indexedDB2) && name !== DBNAMES_DB && getDbNamesTable(indexedDB2, IDBKeyRange).put({ name }).catch(nop); + } + function _onDatabaseDeleted(_a2, name) { + var indexedDB2 = _a2.indexedDB, IDBKeyRange = _a2.IDBKeyRange; + !hasDatabasesNative(indexedDB2) && name !== DBNAMES_DB && getDbNamesTable(indexedDB2, IDBKeyRange).delete(name).catch(nop); + } + function vip(fn) { + return newScope(function() { + PSD.letThrough = true; + return fn(); + }); + } + function idbReady() { + var isSafari = !navigator.userAgentData && /Safari\//.test(navigator.userAgent) && !/Chrom(e|ium)\//.test(navigator.userAgent); + if (!isSafari || !indexedDB.databases) + return Promise.resolve(); + var intervalId; + return new Promise(function(resolve) { + var tryIdb = function() { + return indexedDB.databases().finally(resolve); + }; + intervalId = setInterval(tryIdb, 100); + tryIdb(); + }).finally(function() { + return clearInterval(intervalId); + }); + } + var _a; + function isEmptyRange(node) { + return !("from" in node); + } + var RangeSet2 = function(fromOrTree, to) { + if (this) { + extend(this, arguments.length ? { d: 1, from: fromOrTree, to: arguments.length > 1 ? to : fromOrTree } : { d: 0 }); + } else { + var rv = new RangeSet2(); + if (fromOrTree && "d" in fromOrTree) { + extend(rv, fromOrTree); + } + return rv; + } + }; + props(RangeSet2.prototype, (_a = { + add: function(rangeSet) { + mergeRanges2(this, rangeSet); + return this; + }, + addKey: function(key) { + addRange(this, key, key); + return this; + }, + addKeys: function(keys2) { + var _this = this; + keys2.forEach(function(key) { + return addRange(_this, key, key); + }); + return this; + }, + hasKey: function(key) { + var node = getRangeSetIterator(this).next(key).value; + return node && cmp3(node.from, key) <= 0 && cmp3(node.to, key) >= 0; + } + }, _a[iteratorSymbol] = function() { + return getRangeSetIterator(this); + }, _a)); + function addRange(target, from, to) { + var diff = cmp3(from, to); + if (isNaN(diff)) + return; + if (diff > 0) + throw RangeError(); + if (isEmptyRange(target)) + return extend(target, { from, to, d: 1 }); + var left = target.l; + var right = target.r; + if (cmp3(to, target.from) < 0) { + left ? addRange(left, from, to) : target.l = { from, to, d: 1, l: null, r: null }; + return rebalance(target); + } + if (cmp3(from, target.to) > 0) { + right ? addRange(right, from, to) : target.r = { from, to, d: 1, l: null, r: null }; + return rebalance(target); + } + if (cmp3(from, target.from) < 0) { + target.from = from; + target.l = null; + target.d = right ? right.d + 1 : 1; + } + if (cmp3(to, target.to) > 0) { + target.to = to; + target.r = null; + target.d = target.l ? target.l.d + 1 : 1; + } + var rightWasCutOff = !target.r; + if (left && !target.l) { + mergeRanges2(target, left); + } + if (right && rightWasCutOff) { + mergeRanges2(target, right); + } + } + function mergeRanges2(target, newSet) { + function _addRangeSet(target2, _a2) { + var from = _a2.from, to = _a2.to, l = _a2.l, r = _a2.r; + addRange(target2, from, to); + if (l) + _addRangeSet(target2, l); + if (r) + _addRangeSet(target2, r); + } + if (!isEmptyRange(newSet)) + _addRangeSet(target, newSet); + } + function rangesOverlap2(rangeSet1, rangeSet2) { + var i1 = getRangeSetIterator(rangeSet2); + var nextResult1 = i1.next(); + if (nextResult1.done) + return false; + var a = nextResult1.value; + var i2 = getRangeSetIterator(rangeSet1); + var nextResult2 = i2.next(a.from); + var b = nextResult2.value; + while (!nextResult1.done && !nextResult2.done) { + if (cmp3(b.from, a.to) <= 0 && cmp3(b.to, a.from) >= 0) + return true; + cmp3(a.from, b.from) < 0 ? a = (nextResult1 = i1.next(b.from)).value : b = (nextResult2 = i2.next(a.from)).value; + } + return false; + } + function getRangeSetIterator(node) { + var state = isEmptyRange(node) ? null : { s: 0, n: node }; + return { + next: function(key) { + var keyProvided = arguments.length > 0; + while (state) { + switch (state.s) { + case 0: + state.s = 1; + if (keyProvided) { + while (state.n.l && cmp3(key, state.n.from) < 0) + state = { up: state, n: state.n.l, s: 1 }; + } else { + while (state.n.l) + state = { up: state, n: state.n.l, s: 1 }; + } + case 1: + state.s = 2; + if (!keyProvided || cmp3(key, state.n.to) <= 0) + return { value: state.n, done: false }; + case 2: + if (state.n.r) { + state.s = 3; + state = { up: state, n: state.n.r, s: 0 }; + continue; + } + case 3: + state = state.up; + } + } + return { done: true }; + } + }; + } + function rebalance(target) { + var _a2, _b; + var diff = (((_a2 = target.r) === null || _a2 === void 0 ? void 0 : _a2.d) || 0) - (((_b = target.l) === null || _b === void 0 ? void 0 : _b.d) || 0); + var r = diff > 1 ? "r" : diff < -1 ? "l" : ""; + if (r) { + var l = r === "r" ? "l" : "r"; + var rootClone = __assign({}, target); + var oldRootRight = target[r]; + target.from = oldRootRight.from; + target.to = oldRootRight.to; + target[r] = oldRootRight[r]; + rootClone[r] = oldRootRight[l]; + target[l] = rootClone; + rootClone.d = computeDepth(rootClone); + } + target.d = computeDepth(target); + } + function computeDepth(_a2) { + var r = _a2.r, l = _a2.l; + return (r ? l ? Math.max(r.d, l.d) : r.d : l ? l.d : 0) + 1; + } + function extendObservabilitySet(target, newSet) { + keys(newSet).forEach(function(part) { + if (target[part]) + mergeRanges2(target[part], newSet[part]); + else + target[part] = cloneSimpleObjectTree(newSet[part]); + }); + return target; + } + function obsSetsOverlap(os1, os2) { + return os1.all || os2.all || Object.keys(os1).some(function(key) { + return os2[key] && rangesOverlap2(os2[key], os1[key]); + }); + } + var cache = {}; + var unsignaledParts = {}; + var isTaskEnqueued = false; + function signalSubscribersLazily(part, optimistic) { + extendObservabilitySet(unsignaledParts, part); + if (!isTaskEnqueued) { + isTaskEnqueued = true; + setTimeout(function() { + isTaskEnqueued = false; + var parts = unsignaledParts; + unsignaledParts = {}; + signalSubscribersNow(parts, false); + }, 0); + } + } + function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) { + if (deleteAffectedCacheEntries === void 0) { + deleteAffectedCacheEntries = false; + } + var queriesToSignal = /* @__PURE__ */ new Set(); + if (updatedParts.all) { + for (var _i = 0, _a2 = Object.values(cache); _i < _a2.length; _i++) { + var tblCache = _a2[_i]; + collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); + } + } else { + for (var key in updatedParts) { + var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key); + if (parts) { + var dbName = parts[1], tableName = parts[2]; + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (tblCache) + collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries); + } + } + } + queriesToSignal.forEach(function(requery) { + return requery(); + }); + } + function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) { + var updatedEntryLists = []; + for (var _i = 0, _a2 = Object.entries(tblCache.queries.query); _i < _a2.length; _i++) { + var _b = _a2[_i], indexName = _b[0], entries = _b[1]; + var filteredEntries = []; + for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) { + var entry = entries_1[_c]; + if (obsSetsOverlap(updatedParts, entry.obsSet)) { + entry.subscribers.forEach(function(requery) { + return outQueriesToSignal.add(requery); + }); + } else if (deleteAffectedCacheEntries) { + filteredEntries.push(entry); + } + } + if (deleteAffectedCacheEntries) + updatedEntryLists.push([indexName, filteredEntries]); + } + if (deleteAffectedCacheEntries) { + for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) { + var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1]; + tblCache.queries.query[indexName] = filteredEntries; + } + } + } + function dexieOpen(db2) { + var state = db2._state; + var indexedDB2 = db2._deps.indexedDB; + if (state.isBeingOpened || db2.idbdb) + return state.dbReadyPromise.then(function() { + return state.dbOpenError ? rejection(state.dbOpenError) : db2; + }); + state.isBeingOpened = true; + state.dbOpenError = null; + state.openComplete = false; + var openCanceller = state.openCanceller; + var nativeVerToOpen = Math.round(db2.verno * 10); + var schemaPatchMode = false; + function throwIfCancelled() { + if (state.openCanceller !== openCanceller) + throw new exceptions.DatabaseClosed("db.open() was cancelled"); + } + var resolveDbReady = state.dbReadyResolve, upgradeTransaction = null, wasCreated = false; + var tryOpenDB = function() { + return new DexiePromise(function(resolve, reject) { + throwIfCancelled(); + if (!indexedDB2) + throw new exceptions.MissingAPI(); + var dbName = db2.name; + var req = state.autoSchema || !nativeVerToOpen ? indexedDB2.open(dbName) : indexedDB2.open(dbName, nativeVerToOpen); + if (!req) + throw new exceptions.MissingAPI(); + req.onerror = eventRejectHandler(reject); + req.onblocked = wrap(db2._fireOnBlocked); + req.onupgradeneeded = wrap(function(e) { + upgradeTransaction = req.transaction; + if (state.autoSchema && !db2._options.allowEmptyDB) { + req.onerror = preventDefault; + upgradeTransaction.abort(); + req.result.close(); + var delreq = indexedDB2.deleteDatabase(dbName); + delreq.onsuccess = delreq.onerror = wrap(function() { + reject(new exceptions.NoSuchDatabase("Database ".concat(dbName, " doesnt exist"))); + }); + } else { + upgradeTransaction.onerror = eventRejectHandler(reject); + var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; + wasCreated = oldVer < 1; + db2.idbdb = req.result; + if (schemaPatchMode) { + patchCurrentVersion(db2, upgradeTransaction); + } + runUpgraders(db2, oldVer / 10, upgradeTransaction, reject); + } + }, reject); + req.onsuccess = wrap(function() { + upgradeTransaction = null; + var idbdb = db2.idbdb = req.result; + var objectStoreNames = slice(idbdb.objectStoreNames); + if (objectStoreNames.length > 0) + try { + var tmpTrans = idbdb.transaction(safariMultiStoreFix(objectStoreNames), "readonly"); + if (state.autoSchema) + readGlobalSchema(db2, idbdb, tmpTrans); + else { + adjustToExistingIndexNames(db2, db2._dbSchema, tmpTrans); + if (!verifyInstalledSchema(db2, tmpTrans) && !schemaPatchMode) { + console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."); + idbdb.close(); + nativeVerToOpen = idbdb.version + 1; + schemaPatchMode = true; + return resolve(tryOpenDB()); + } + } + generateMiddlewareStacks(db2, tmpTrans); + } catch (e) { + } + connections.add(db2); + idbdb.onversionchange = wrap(function(ev) { + state.vcFired = true; + db2.on("versionchange").fire(ev); + }); + idbdb.onclose = wrap(function() { + db2.close({ disableAutoOpen: false }); + }); + if (wasCreated) + _onDatabaseCreated(db2._deps, dbName); + resolve(); + }, reject); + }).catch(function(err) { + switch (err === null || err === void 0 ? void 0 : err.name) { + case "UnknownError": + if (state.PR1398_maxLoop > 0) { + state.PR1398_maxLoop--; + console.warn("Dexie: Workaround for Chrome UnknownError on open()"); + return tryOpenDB(); + } + break; + case "VersionError": + if (nativeVerToOpen > 0) { + nativeVerToOpen = 0; + return tryOpenDB(); + } + break; + } + return DexiePromise.reject(err); + }); + }; + return DexiePromise.race([ + openCanceller, + (typeof navigator === "undefined" ? DexiePromise.resolve() : idbReady()).then(tryOpenDB) + ]).then(function() { + throwIfCancelled(); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function() { + return db2.on.ready.fire(db2.vip); + })).then(function fireRemainders() { + if (state.onReadyBeingFired.length > 0) { + var remainders_1 = state.onReadyBeingFired.reduce(promisableChain, nop); + state.onReadyBeingFired = []; + return DexiePromise.resolve(vip(function() { + return remainders_1(db2.vip); + })).then(fireRemainders); + } + }); + }).finally(function() { + if (state.openCanceller === openCanceller) { + state.onReadyBeingFired = null; + state.isBeingOpened = false; + } + }).catch(function(err) { + state.dbOpenError = err; + try { + upgradeTransaction && upgradeTransaction.abort(); + } catch (_a2) { + } + if (openCanceller === state.openCanceller) { + db2._close(); + } + return rejection(err); + }).finally(function() { + state.openComplete = true; + resolveDbReady(); + }).then(function() { + if (wasCreated) { + var everything_1 = {}; + db2.tables.forEach(function(table) { + table.schema.indexes.forEach(function(idx) { + if (idx.name) + everything_1["idb://".concat(db2.name, "/").concat(table.name, "/").concat(idx.name)] = new RangeSet2(-Infinity, [[[]]]); + }); + everything_1["idb://".concat(db2.name, "/").concat(table.name, "/")] = everything_1["idb://".concat(db2.name, "/").concat(table.name, "/:dels")] = new RangeSet2(-Infinity, [[[]]]); + }); + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME).fire(everything_1); + signalSubscribersNow(everything_1, true); + } + return db2; + }); + } + function awaitIterator(iterator) { + var callNext = function(result) { + return iterator.next(result); + }, doThrow = function(error) { + return iterator.throw(error); + }, onSuccess = step(callNext), onError = step(doThrow); + function step(getNext) { + return function(val) { + var next = getNext(val), value = next.value; + return next.done ? value : !value || typeof value.then !== "function" ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError); + }; + } + return step(callNext)(); + } + function extractTransactionArgs(mode, _tableArgs_, scopeFunc) { + var i = arguments.length; + if (i < 2) + throw new exceptions.InvalidArgument("Too few arguments"); + var args = new Array(i - 1); + while (--i) + args[i - 1] = arguments[i]; + scopeFunc = args.pop(); + var tables = flatten(args); + return [mode, tables, scopeFunc]; + } + function enterTransactionScope(db2, mode, storeNames, parentTransaction, scopeFunc) { + return DexiePromise.resolve().then(function() { + var transless = PSD.transless || PSD; + var trans = db2._createTransaction(mode, storeNames, db2._dbSchema, parentTransaction); + trans.explicit = true; + var zoneProps = { + trans, + transless + }; + if (parentTransaction) { + trans.idbtrans = parentTransaction.idbtrans; + } else { + try { + trans.create(); + trans.idbtrans._explicit = true; + db2._state.PR1398_maxLoop = 3; + } catch (ex) { + if (ex.name === errnames.InvalidState && db2.isOpen() && --db2._state.PR1398_maxLoop > 0) { + console.warn("Dexie: Need to reopen db"); + db2.close({ disableAutoOpen: false }); + return db2.open().then(function() { + return enterTransactionScope(db2, mode, storeNames, null, scopeFunc); + }); + } + return rejection(ex); + } + } + var scopeFuncIsAsync = isAsyncFunction(scopeFunc); + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var returnValue; + var promiseFollowed = DexiePromise.follow(function() { + returnValue = scopeFunc.call(trans, trans); + if (returnValue) { + if (scopeFuncIsAsync) { + var decrementor = decrementExpectedAwaits.bind(null, null); + returnValue.then(decrementor, decrementor); + } else if (typeof returnValue.next === "function" && typeof returnValue.throw === "function") { + returnValue = awaitIterator(returnValue); + } + } + }, zoneProps); + return (returnValue && typeof returnValue.then === "function" ? DexiePromise.resolve(returnValue).then(function(x) { + return trans.active ? x : rejection(new exceptions.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")); + }) : promiseFollowed.then(function() { + return returnValue; + })).then(function(x) { + if (parentTransaction) + trans._resolve(); + return trans._completion.then(function() { + return x; + }); + }).catch(function(e) { + trans._reject(e); + return rejection(e); + }); + }); + } + function pad2(a, value, count) { + var result = isArray(a) ? a.slice() : [a]; + for (var i = 0; i < count; ++i) + result.push(value); + return result; + } + function createVirtualIndexMiddleware(down) { + return __assign(__assign({}, down), { table: function(tableName) { + var table = down.table(tableName); + var schema = table.schema; + var indexLookup = /* @__PURE__ */ Object.create(null); + var allVirtualIndexes = []; + function addVirtualIndexes(keyPath, keyTail, lowLevelIndex) { + var keyPathAlias = getKeyPathAlias(keyPath); + var indexList = indexLookup[keyPathAlias] = indexLookup[keyPathAlias] || []; + var keyLength = keyPath == null ? 0 : typeof keyPath === "string" ? 1 : keyPath.length; + var isVirtual = keyTail > 0; + var virtualIndex = __assign(__assign({}, lowLevelIndex), { name: isVirtual ? "".concat(keyPathAlias, "(virtual-from:").concat(lowLevelIndex.name, ")") : lowLevelIndex.name, lowLevelIndex, isVirtual, keyTail, keyLength, extractKey: getKeyExtractor(keyPath), unique: !isVirtual && lowLevelIndex.unique }); + indexList.push(virtualIndex); + if (!virtualIndex.isPrimaryKey) { + allVirtualIndexes.push(virtualIndex); + } + if (keyLength > 1) { + var virtualKeyPath = keyLength === 2 ? keyPath[0] : keyPath.slice(0, keyLength - 1); + addVirtualIndexes(virtualKeyPath, keyTail + 1, lowLevelIndex); + } + indexList.sort(function(a, b) { + return a.keyTail - b.keyTail; + }); + return virtualIndex; + } + var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey); + indexLookup[":id"] = [primaryKey]; + for (var _i = 0, _a2 = schema.indexes; _i < _a2.length; _i++) { + var index = _a2[_i]; + addVirtualIndexes(index.keyPath, 0, index); + } + function findBestIndex(keyPath) { + var result2 = indexLookup[getKeyPathAlias(keyPath)]; + return result2 && result2[0]; + } + function translateRange(range, keyTail) { + return { + type: range.type === 1 ? 2 : range.type, + lower: pad2(range.lower, range.lowerOpen ? down.MAX_KEY : down.MIN_KEY, keyTail), + lowerOpen: true, + upper: pad2(range.upper, range.upperOpen ? down.MIN_KEY : down.MAX_KEY, keyTail), + upperOpen: true + }; + } + function translateRequest(req) { + var index2 = req.query.index; + return index2.isVirtual ? __assign(__assign({}, req), { query: { + index: index2.lowLevelIndex, + range: translateRange(req.query.range, index2.keyTail) + } }) : req; + } + var result = __assign(__assign({}, table), { schema: __assign(__assign({}, schema), { primaryKey, indexes: allVirtualIndexes, getIndexByKeyPath: findBestIndex }), count: function(req) { + return table.count(translateRequest(req)); + }, query: function(req) { + return table.query(translateRequest(req)); + }, openCursor: function(req) { + var _a3 = req.query.index, keyTail = _a3.keyTail, isVirtual = _a3.isVirtual, keyLength = _a3.keyLength; + if (!isVirtual) + return table.openCursor(req); + function createVirtualCursor(cursor) { + function _continue(key) { + key != null ? cursor.continue(pad2(key, req.reverse ? down.MAX_KEY : down.MIN_KEY, keyTail)) : req.unique ? cursor.continue(cursor.key.slice(0, keyLength).concat(req.reverse ? down.MIN_KEY : down.MAX_KEY, keyTail)) : cursor.continue(); + } + var virtualCursor = Object.create(cursor, { + continue: { value: _continue }, + continuePrimaryKey: { + value: function(key, primaryKey2) { + cursor.continuePrimaryKey(pad2(key, down.MAX_KEY, keyTail), primaryKey2); + } + }, + primaryKey: { + get: function() { + return cursor.primaryKey; + } + }, + key: { + get: function() { + var key = cursor.key; + return keyLength === 1 ? key[0] : key.slice(0, keyLength); + } + }, + value: { + get: function() { + return cursor.value; + } + } + }); + return virtualCursor; + } + return table.openCursor(translateRequest(req)).then(function(cursor) { + return cursor && createVirtualCursor(cursor); + }); + } }); + return result; + } }); + } + var virtualIndexMiddleware = { + stack: "dbcore", + name: "VirtualIndexMiddleware", + level: 1, + create: createVirtualIndexMiddleware + }; + function getObjectDiff(a, b, rv, prfx) { + rv = rv || {}; + prfx = prfx || ""; + keys(a).forEach(function(prop) { + if (!hasOwn(b, prop)) { + rv[prfx + prop] = void 0; + } else { + var ap = a[prop], bp = b[prop]; + if (typeof ap === "object" && typeof bp === "object" && ap && bp) { + var apTypeName = toStringTag(ap); + var bpTypeName = toStringTag(bp); + if (apTypeName !== bpTypeName) { + rv[prfx + prop] = b[prop]; + } else if (apTypeName === "Object") { + getObjectDiff(ap, bp, rv, prfx + prop + "."); + } else if (ap !== bp) { + rv[prfx + prop] = b[prop]; + } + } else if (ap !== bp) + rv[prfx + prop] = b[prop]; + } + }); + keys(b).forEach(function(prop) { + if (!hasOwn(a, prop)) { + rv[prfx + prop] = b[prop]; + } + }); + return rv; + } + function getEffectiveKeys(primaryKey, req) { + if (req.type === "delete") + return req.keys; + return req.keys || req.values.map(primaryKey.extractKey); + } + var hooksMiddleware = { + stack: "dbcore", + name: "HooksMiddleware", + level: 2, + create: function(downCore) { + return __assign(__assign({}, downCore), { table: function(tableName) { + var downTable = downCore.table(tableName); + var primaryKey = downTable.schema.primaryKey; + var tableMiddleware = __assign(__assign({}, downTable), { mutate: function(req) { + var dxTrans = PSD.trans; + var _a2 = dxTrans.table(tableName).hook, deleting = _a2.deleting, creating = _a2.creating, updating = _a2.updating; + switch (req.type) { + case "add": + if (creating.fire === nop) + break; + return dxTrans._promise("readwrite", function() { + return addPutOrDelete(req); + }, true); + case "put": + if (creating.fire === nop && updating.fire === nop) + break; + return dxTrans._promise("readwrite", function() { + return addPutOrDelete(req); + }, true); + case "delete": + if (deleting.fire === nop) + break; + return dxTrans._promise("readwrite", function() { + return addPutOrDelete(req); + }, true); + case "deleteRange": + if (deleting.fire === nop) + break; + return dxTrans._promise("readwrite", function() { + return deleteRange(req); + }, true); + } + return downTable.mutate(req); + function addPutOrDelete(req2) { + var dxTrans2 = PSD.trans; + var keys2 = req2.keys || getEffectiveKeys(primaryKey, req2); + if (!keys2) + throw new Error("Keys missing"); + req2 = req2.type === "add" || req2.type === "put" ? __assign(__assign({}, req2), { keys: keys2 }) : __assign({}, req2); + if (req2.type !== "delete") + req2.values = __spreadArray([], req2.values, true); + if (req2.keys) + req2.keys = __spreadArray([], req2.keys, true); + return getExistingValues(downTable, req2, keys2).then(function(existingValues) { + var contexts = keys2.map(function(key, i) { + var existingValue = existingValues[i]; + var ctx = { onerror: null, onsuccess: null }; + if (req2.type === "delete") { + deleting.fire.call(ctx, key, existingValue, dxTrans2); + } else if (req2.type === "add" || existingValue === void 0) { + var generatedPrimaryKey = creating.fire.call(ctx, key, req2.values[i], dxTrans2); + if (key == null && generatedPrimaryKey != null) { + key = generatedPrimaryKey; + req2.keys[i] = key; + if (!primaryKey.outbound) { + setByKeyPath(req2.values[i], primaryKey.keyPath, key); + } + } + } else { + var objectDiff = getObjectDiff(existingValue, req2.values[i]); + var additionalChanges_1 = updating.fire.call(ctx, objectDiff, key, existingValue, dxTrans2); + if (additionalChanges_1) { + var requestedValue_1 = req2.values[i]; + Object.keys(additionalChanges_1).forEach(function(keyPath) { + if (hasOwn(requestedValue_1, keyPath)) { + requestedValue_1[keyPath] = additionalChanges_1[keyPath]; + } else { + setByKeyPath(requestedValue_1, keyPath, additionalChanges_1[keyPath]); + } + }); + } + } + return ctx; + }); + return downTable.mutate(req2).then(function(_a3) { + var failures = _a3.failures, results = _a3.results, numFailures = _a3.numFailures, lastResult = _a3.lastResult; + for (var i = 0; i < keys2.length; ++i) { + var primKey = results ? results[i] : keys2[i]; + var ctx = contexts[i]; + if (primKey == null) { + ctx.onerror && ctx.onerror(failures[i]); + } else { + ctx.onsuccess && ctx.onsuccess( + req2.type === "put" && existingValues[i] ? req2.values[i] : primKey + ); + } + } + return { failures, results, numFailures, lastResult }; + }).catch(function(error) { + contexts.forEach(function(ctx) { + return ctx.onerror && ctx.onerror(error); + }); + return Promise.reject(error); + }); + }); + } + function deleteRange(req2) { + return deleteNextChunk(req2.trans, req2.range, 1e4); + } + function deleteNextChunk(trans, range, limit) { + return downTable.query({ + trans, + values: false, + query: { index: primaryKey, range }, + limit + }).then(function(_a3) { + var result = _a3.result; + return addPutOrDelete({ + type: "delete", + keys: result, + trans + }).then(function(res) { + if (res.numFailures > 0) + return Promise.reject(res.failures[0]); + if (result.length < limit) { + return { + failures: [], + numFailures: 0, + lastResult: void 0 + }; + } else { + return deleteNextChunk(trans, __assign(__assign({}, range), { lower: result[result.length - 1], lowerOpen: true }), limit); + } + }); + }); + } + } }); + return tableMiddleware; + } }); + } + }; + function getExistingValues(table, req, effectiveKeys) { + return req.type === "add" ? Promise.resolve([]) : table.getMany({ + trans: req.trans, + keys: effectiveKeys, + cache: "immutable" + }); + } + function getFromTransactionCache(keys2, cache2, clone) { + try { + if (!cache2) + return null; + if (cache2.keys.length < keys2.length) + return null; + var result = []; + for (var i = 0, j = 0; i < cache2.keys.length && j < keys2.length; ++i) { + if (cmp3(cache2.keys[i], keys2[j]) !== 0) + continue; + result.push(clone ? deepClone(cache2.values[i]) : cache2.values[i]); + ++j; + } + return result.length === keys2.length ? result : null; + } catch (_a2) { + return null; + } + } + var cacheExistingValuesMiddleware = { + stack: "dbcore", + level: -1, + create: function(core) { + return { + table: function(tableName) { + var table = core.table(tableName); + return __assign(__assign({}, table), { getMany: function(req) { + if (!req.cache) { + return table.getMany(req); + } + var cachedResult = getFromTransactionCache(req.keys, req.trans["_cache"], req.cache === "clone"); + if (cachedResult) { + return DexiePromise.resolve(cachedResult); + } + return table.getMany(req).then(function(res) { + req.trans["_cache"] = { + keys: req.keys, + values: req.cache === "clone" ? deepClone(res) : res + }; + return res; + }); + }, mutate: function(req) { + if (req.type !== "add") + req.trans["_cache"] = null; + return table.mutate(req); + } }); + } + }; + } + }; + function isCachableContext(ctx, table) { + return ctx.trans.mode === "readonly" && !!ctx.subscr && !ctx.trans.explicit && ctx.trans.db._options.cache !== "disabled" && !table.schema.primaryKey.outbound; + } + function isCachableRequest(type2, req) { + switch (type2) { + case "query": + return req.values && !req.unique; + case "get": + return false; + case "getMany": + return false; + case "count": + return false; + case "openCursor": + return false; + } + } + var observabilityMiddleware = { + stack: "dbcore", + level: 0, + name: "Observability", + create: function(core) { + var dbName = core.schema.name; + var FULL_RANGE = new RangeSet2(core.MIN_KEY, core.MAX_KEY); + return __assign(__assign({}, core), { transaction: function(stores, mode, options) { + if (PSD.subscr && mode !== "readonly") { + throw new exceptions.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(PSD.querier)); + } + return core.transaction(stores, mode, options); + }, table: function(tableName) { + var table = core.table(tableName); + var schema = table.schema; + var primaryKey = schema.primaryKey, indexes = schema.indexes; + var extractKey2 = primaryKey.extractKey, outbound = primaryKey.outbound; + var indexesWithAutoIncPK = primaryKey.autoIncrement && indexes.filter(function(index) { + return index.compound && index.keyPath.includes(primaryKey.keyPath); + }); + var tableClone = __assign(__assign({}, table), { mutate: function(req) { + var _a2, _b; + var trans = req.trans; + var mutatedParts = req.mutatedParts || (req.mutatedParts = {}); + var getRangeSet = function(indexName) { + var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); + return mutatedParts[part] || (mutatedParts[part] = new RangeSet2()); + }; + var pkRangeSet = getRangeSet(""); + var delsRangeSet = getRangeSet(":dels"); + var type2 = req.type; + var _c = req.type === "deleteRange" ? [req.range] : req.type === "delete" ? [req.keys] : req.values.length < 50 ? [ + getEffectiveKeys(primaryKey, req).filter(function(id) { + return id; + }), + req.values + ] : [], keys2 = _c[0], newObjs = _c[1]; + var oldCache = req.trans["_cache"]; + if (isArray(keys2)) { + pkRangeSet.addKeys(keys2); + var oldObjs = type2 === "delete" || keys2.length === newObjs.length ? getFromTransactionCache(keys2, oldCache) : null; + if (!oldObjs) { + delsRangeSet.addKeys(keys2); + } + if (oldObjs || newObjs) { + trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs); + } + } else if (keys2) { + var range = { + from: (_a2 = keys2.lower) !== null && _a2 !== void 0 ? _a2 : core.MIN_KEY, + to: (_b = keys2.upper) !== null && _b !== void 0 ? _b : core.MAX_KEY + }; + delsRangeSet.add(range); + pkRangeSet.add(range); + } else { + pkRangeSet.add(FULL_RANGE); + delsRangeSet.add(FULL_RANGE); + schema.indexes.forEach(function(idx) { + return getRangeSet(idx.name).add(FULL_RANGE); + }); + } + return table.mutate(req).then(function(res) { + if (keys2 && (req.type === "add" || req.type === "put")) { + pkRangeSet.addKeys(res.results); + if (indexesWithAutoIncPK) { + indexesWithAutoIncPK.forEach(function(idx) { + var idxVals = req.values.map(function(v) { + return idx.extractKey(v); + }); + var pkPos = idx.keyPath.findIndex(function(prop) { + return prop === primaryKey.keyPath; + }); + for (var i = 0, len = res.results.length; i < len; ++i) { + idxVals[i][pkPos] = res.results[i]; + } + getRangeSet(idx.name).addKeys(idxVals); + }); + } + } + trans.mutatedParts = extendObservabilitySet(trans.mutatedParts || {}, mutatedParts); + return res; + }); + } }); + var getRange = function(_a2) { + var _b, _c; + var _d = _a2.query, index = _d.index, range = _d.range; + return [ + index, + new RangeSet2((_b = range.lower) !== null && _b !== void 0 ? _b : core.MIN_KEY, (_c = range.upper) !== null && _c !== void 0 ? _c : core.MAX_KEY) + ]; + }; + var readSubscribers = { + get: function(req) { + return [primaryKey, new RangeSet2(req.key)]; + }, + getMany: function(req) { + return [primaryKey, new RangeSet2().addKeys(req.keys)]; + }, + count: getRange, + query: getRange, + openCursor: getRange + }; + keys(readSubscribers).forEach(function(method) { + tableClone[method] = function(req) { + var subscr = PSD.subscr; + var isLiveQuery = !!subscr; + var cachable = isCachableContext(PSD, table) && isCachableRequest(method, req); + var obsSet = cachable ? req.obsSet = {} : subscr; + if (isLiveQuery) { + var getRangeSet = function(indexName) { + var part = "idb://".concat(dbName, "/").concat(tableName, "/").concat(indexName); + return obsSet[part] || (obsSet[part] = new RangeSet2()); + }; + var pkRangeSet_1 = getRangeSet(""); + var delsRangeSet_1 = getRangeSet(":dels"); + var _a2 = readSubscribers[method](req), queriedIndex = _a2[0], queriedRanges = _a2[1]; + if (method === "query" && queriedIndex.isPrimaryKey && !req.values) { + delsRangeSet_1.add(queriedRanges); + } else { + getRangeSet(queriedIndex.name || "").add(queriedRanges); + } + if (!queriedIndex.isPrimaryKey) { + if (method === "count") { + delsRangeSet_1.add(FULL_RANGE); + } else { + var keysPromise_1 = method === "query" && outbound && req.values && table.query(__assign(__assign({}, req), { values: false })); + return table[method].apply(this, arguments).then(function(res) { + if (method === "query") { + if (outbound && req.values) { + return keysPromise_1.then(function(_a3) { + var resultingKeys = _a3.result; + pkRangeSet_1.addKeys(resultingKeys); + return res; + }); + } + var pKeys = req.values ? res.result.map(extractKey2) : res.result; + if (req.values) { + pkRangeSet_1.addKeys(pKeys); + } else { + delsRangeSet_1.addKeys(pKeys); + } + } else if (method === "openCursor") { + var cursor_1 = res; + var wantValues_1 = req.values; + return cursor_1 && Object.create(cursor_1, { + key: { + get: function() { + delsRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.key; + } + }, + primaryKey: { + get: function() { + var pkey = cursor_1.primaryKey; + delsRangeSet_1.addKey(pkey); + return pkey; + } + }, + value: { + get: function() { + wantValues_1 && pkRangeSet_1.addKey(cursor_1.primaryKey); + return cursor_1.value; + } + } + }); + } + return res; + }); + } + } + } + return table[method].apply(this, arguments); + }; + }); + return tableClone; + } }); + } + }; + function trackAffectedIndexes(getRangeSet, schema, oldObjs, newObjs) { + function addAffectedIndex(ix) { + var rangeSet = getRangeSet(ix.name || ""); + function extractKey2(obj) { + return obj != null ? ix.extractKey(obj) : null; + } + var addKeyOrKeys = function(key) { + return ix.multiEntry && isArray(key) ? key.forEach(function(key2) { + return rangeSet.addKey(key2); + }) : rangeSet.addKey(key); + }; + (oldObjs || newObjs).forEach(function(_, i) { + var oldKey = oldObjs && extractKey2(oldObjs[i]); + var newKey = newObjs && extractKey2(newObjs[i]); + if (cmp3(oldKey, newKey) !== 0) { + if (oldKey != null) + addKeyOrKeys(oldKey); + if (newKey != null) + addKeyOrKeys(newKey); + } + }); + } + schema.indexes.forEach(addAffectedIndex); + } + function adjustOptimisticFromFailures(tblCache, req, res) { + if (res.numFailures === 0) + return req; + if (req.type === "deleteRange") { + return null; + } + var numBulkOps = req.keys ? req.keys.length : "values" in req && req.values ? req.values.length : 1; + if (res.numFailures === numBulkOps) { + return null; + } + var clone = __assign({}, req); + if (isArray(clone.keys)) { + clone.keys = clone.keys.filter(function(_, i) { + return !(i in res.failures); + }); + } + if ("values" in clone && isArray(clone.values)) { + clone.values = clone.values.filter(function(_, i) { + return !(i in res.failures); + }); + } + return clone; + } + function isAboveLower(key, range) { + return range.lower === void 0 ? true : range.lowerOpen ? cmp3(key, range.lower) > 0 : cmp3(key, range.lower) >= 0; + } + function isBelowUpper(key, range) { + return range.upper === void 0 ? true : range.upperOpen ? cmp3(key, range.upper) < 0 : cmp3(key, range.upper) <= 0; + } + function isWithinRange(key, range) { + return isAboveLower(key, range) && isBelowUpper(key, range); + } + function applyOptimisticOps(result, req, ops, table, cacheEntry, immutable) { + if (!ops || ops.length === 0) + return result; + var index = req.query.index; + var multiEntry = index.multiEntry; + var queryRange = req.query.range; + var primaryKey = table.schema.primaryKey; + var extractPrimKey = primaryKey.extractKey; + var extractIndex = index.extractKey; + var extractLowLevelIndex = (index.lowLevelIndex || index).extractKey; + var finalResult = ops.reduce(function(result2, op) { + var modifedResult = result2; + var includedValues = []; + if (op.type === "add" || op.type === "put") { + var includedPKs = new RangeSet2(); + for (var i = op.values.length - 1; i >= 0; --i) { + var value = op.values[i]; + var pk = extractPrimKey(value); + if (includedPKs.hasKey(pk)) + continue; + var key = extractIndex(value); + if (multiEntry && isArray(key) ? key.some(function(k) { + return isWithinRange(k, queryRange); + }) : isWithinRange(key, queryRange)) { + includedPKs.addKey(pk); + includedValues.push(value); + } + } + } + switch (op.type) { + case "add": { + var existingKeys_1 = new RangeSet2().addKeys(req.values ? result2.map(function(v) { + return extractPrimKey(v); + }) : result2); + modifedResult = result2.concat(req.values ? includedValues.filter(function(v) { + var key2 = extractPrimKey(v); + if (existingKeys_1.hasKey(key2)) + return false; + existingKeys_1.addKey(key2); + return true; + }) : includedValues.map(function(v) { + return extractPrimKey(v); + }).filter(function(k) { + if (existingKeys_1.hasKey(k)) + return false; + existingKeys_1.addKey(k); + return true; + })); + break; + } + case "put": { + var keySet_1 = new RangeSet2().addKeys(op.values.map(function(v) { + return extractPrimKey(v); + })); + modifedResult = result2.filter( + function(item) { + return !keySet_1.hasKey(req.values ? extractPrimKey(item) : item); + } + ).concat( + req.values ? includedValues : includedValues.map(function(v) { + return extractPrimKey(v); + }) + ); + break; + } + case "delete": + var keysToDelete_1 = new RangeSet2().addKeys(op.keys); + modifedResult = result2.filter(function(item) { + return !keysToDelete_1.hasKey(req.values ? extractPrimKey(item) : item); + }); + break; + case "deleteRange": + var range_1 = op.range; + modifedResult = result2.filter(function(item) { + return !isWithinRange(extractPrimKey(item), range_1); + }); + break; + } + return modifedResult; + }, result); + if (finalResult === result) + return result; + var sorter = function(a, b) { + return cmp3(extractLowLevelIndex(a), extractLowLevelIndex(b)) || cmp3(extractPrimKey(a), extractPrimKey(b)); + }; + finalResult.sort(req.direction === "prev" || req.direction === "prevunique" ? function(a, b) { + return sorter(b, a); + } : sorter); + if (req.limit && req.limit < Infinity) { + if (finalResult.length > req.limit) { + finalResult.length = req.limit; + } else if (result.length === req.limit && finalResult.length < req.limit) { + cacheEntry.dirty = true; + } + } + return immutable ? Object.freeze(finalResult) : finalResult; + } + function areRangesEqual(r1, r2) { + return cmp3(r1.lower, r2.lower) === 0 && cmp3(r1.upper, r2.upper) === 0 && !!r1.lowerOpen === !!r2.lowerOpen && !!r1.upperOpen === !!r2.upperOpen; + } + function compareLowers(lower1, lower2, lowerOpen1, lowerOpen2) { + if (lower1 === void 0) + return lower2 !== void 0 ? -1 : 0; + if (lower2 === void 0) + return 1; + var c = cmp3(lower1, lower2); + if (c === 0) { + if (lowerOpen1 && lowerOpen2) + return 0; + if (lowerOpen1) + return 1; + if (lowerOpen2) + return -1; + } + return c; + } + function compareUppers(upper1, upper2, upperOpen1, upperOpen2) { + if (upper1 === void 0) + return upper2 !== void 0 ? 1 : 0; + if (upper2 === void 0) + return -1; + var c = cmp3(upper1, upper2); + if (c === 0) { + if (upperOpen1 && upperOpen2) + return 0; + if (upperOpen1) + return -1; + if (upperOpen2) + return 1; + } + return c; + } + function isSuperRange(r1, r2) { + return compareLowers(r1.lower, r2.lower, r1.lowerOpen, r2.lowerOpen) <= 0 && compareUppers(r1.upper, r2.upper, r1.upperOpen, r2.upperOpen) >= 0; + } + function findCompatibleQuery(dbName, tableName, type2, req) { + var _a2; + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (!tblCache) + return []; + var queries = tblCache.queries[type2]; + if (!queries) + return [null, false, tblCache, null]; + var indexName = req.query ? req.query.index.name : null; + var entries = queries[indexName || ""]; + if (!entries) + return [null, false, tblCache, null]; + switch (type2) { + case "query": + var reqDirection_1 = (_a2 = req.direction) !== null && _a2 !== void 0 ? _a2 : "next"; + var equalEntry = entries.find(function(entry) { + var _a3; + return entry.req.limit === req.limit && entry.req.values === req.values && ((_a3 = entry.req.direction) !== null && _a3 !== void 0 ? _a3 : "next") === reqDirection_1 && areRangesEqual(entry.req.query.range, req.query.range); + }); + if (equalEntry) + return [ + equalEntry, + true, + tblCache, + entries + ]; + var superEntry = entries.find(function(entry) { + var _a3; + var limit = "limit" in entry.req ? entry.req.limit : Infinity; + return limit >= req.limit && ((_a3 = entry.req.direction) !== null && _a3 !== void 0 ? _a3 : "next") === reqDirection_1 && (req.values ? entry.req.values : true) && isSuperRange(entry.req.query.range, req.query.range); + }); + return [superEntry, false, tblCache, entries]; + case "count": + var countQuery = entries.find(function(entry) { + return areRangesEqual(entry.req.query.range, req.query.range); + }); + return [countQuery, !!countQuery, tblCache, entries]; + } + } + function subscribeToCacheEntry(cacheEntry, container, requery, signal) { + cacheEntry.subscribers.add(requery); + signal.addEventListener("abort", function() { + cacheEntry.subscribers.delete(requery); + if (cacheEntry.subscribers.size === 0) { + enqueForDeletion(cacheEntry, container); + } + }); + } + function enqueForDeletion(cacheEntry, container) { + setTimeout(function() { + if (cacheEntry.subscribers.size === 0) { + delArrayItem(container, cacheEntry); + } + }, 3e3); + } + var cacheMiddleware = { + stack: "dbcore", + level: 0, + name: "Cache", + create: function(core) { + var dbName = core.schema.name; + var coreMW = __assign(__assign({}, core), { transaction: function(stores, mode, options) { + var idbtrans = core.transaction(stores, mode, options); + if (mode === "readwrite") { + var ac_1 = new AbortController(); + var signal = ac_1.signal; + var endTransaction = function(wasCommitted) { + return function() { + ac_1.abort(); + if (mode === "readwrite") { + var affectedSubscribers_1 = /* @__PURE__ */ new Set(); + for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) { + var storeName = stores_1[_i]; + var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)]; + if (tblCache) { + var table = core.table(storeName); + var ops = tblCache.optimisticOps.filter(function(op) { + return op.trans === idbtrans; + }); + if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) { + for (var _a2 = 0, _b = Object.values(tblCache.queries.query); _a2 < _b.length; _a2++) { + var entries = _b[_a2]; + for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) { + var entry = _d[_c]; + if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) { + delArrayItem(entries, entry); + entry.subscribers.forEach(function(requery) { + return affectedSubscribers_1.add(requery); + }); + } + } + } + } else if (ops.length > 0) { + tblCache.optimisticOps = tblCache.optimisticOps.filter(function(op) { + return op.trans !== idbtrans; + }); + for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) { + var entries = _f[_e]; + for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) { + var entry = _h[_g]; + if (entry.res != null && idbtrans.mutatedParts) { + if (wasCommitted && !entry.dirty) { + var freezeResults = Object.isFrozen(entry.res); + var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults); + if (entry.dirty) { + delArrayItem(entries, entry); + entry.subscribers.forEach(function(requery) { + return affectedSubscribers_1.add(requery); + }); + } else if (modRes !== entry.res) { + entry.res = modRes; + entry.promise = DexiePromise.resolve({ + result: modRes + }); + } + } else { + if (entry.dirty) { + delArrayItem(entries, entry); + } + entry.subscribers.forEach(function(requery) { + return affectedSubscribers_1.add(requery); + }); + } + } + } + } + } + } + } + affectedSubscribers_1.forEach(function(requery) { + return requery(); + }); + } + }; + }; + idbtrans.addEventListener("abort", endTransaction(false), { + signal + }); + idbtrans.addEventListener("error", endTransaction(false), { + signal + }); + idbtrans.addEventListener("complete", endTransaction(true), { + signal + }); + } + return idbtrans; + }, table: function(tableName) { + var downTable = core.table(tableName); + var primKey = downTable.schema.primaryKey; + var tableMW = __assign(__assign({}, downTable), { mutate: function(req) { + var trans = PSD.trans; + if (primKey.outbound || trans.db._options.cache === "disabled" || trans.explicit || trans.idbtrans.mode !== "readwrite") { + return downTable.mutate(req); + } + var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)]; + if (!tblCache) + return downTable.mutate(req); + var promise = downTable.mutate(req); + if ((req.type === "add" || req.type === "put") && (req.values.length >= 50 || getEffectiveKeys(primKey, req).some(function(key) { + return key == null; + }))) { + promise.then(function(res) { + var reqWithResolvedKeys = __assign(__assign({}, req), { values: req.values.map(function(value, i) { + var _a2; + if (res.failures[i]) + return value; + var valueWithKey = ((_a2 = primKey.keyPath) === null || _a2 === void 0 ? void 0 : _a2.includes(".")) ? deepClone(value) : __assign({}, value); + setByKeyPath(valueWithKey, primKey.keyPath, res.results[i]); + return valueWithKey; + }) }); + var adjustedReq = adjustOptimisticFromFailures(tblCache, reqWithResolvedKeys, res); + tblCache.optimisticOps.push(adjustedReq); + queueMicrotask(function() { + return req.mutatedParts && signalSubscribersLazily(req.mutatedParts); + }); + }); + } else { + tblCache.optimisticOps.push(req); + req.mutatedParts && signalSubscribersLazily(req.mutatedParts); + promise.then(function(res) { + if (res.numFailures > 0) { + delArrayItem(tblCache.optimisticOps, req); + var adjustedReq = adjustOptimisticFromFailures(tblCache, req, res); + if (adjustedReq) { + tblCache.optimisticOps.push(adjustedReq); + } + req.mutatedParts && signalSubscribersLazily(req.mutatedParts); + } + }); + promise.catch(function() { + delArrayItem(tblCache.optimisticOps, req); + req.mutatedParts && signalSubscribersLazily(req.mutatedParts); + }); + } + return promise; + }, query: function(req) { + var _a2; + if (!isCachableContext(PSD, downTable) || !isCachableRequest("query", req)) + return downTable.query(req); + var freezeResults = ((_a2 = PSD.trans) === null || _a2 === void 0 ? void 0 : _a2.db._options.cache) === "immutable"; + var _b = PSD, requery = _b.requery, signal = _b.signal; + var _c = findCompatibleQuery(dbName, tableName, "query", req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3]; + if (cacheEntry && exactMatch) { + cacheEntry.obsSet = req.obsSet; + } else { + var promise = downTable.query(req).then(function(res) { + var result = res.result; + if (cacheEntry) + cacheEntry.res = result; + if (freezeResults) { + for (var i = 0, l = result.length; i < l; ++i) { + Object.freeze(result[i]); + } + Object.freeze(result); + } + return res; + }).catch(function(error) { + if (container && cacheEntry) + delArrayItem(container, cacheEntry); + return Promise.reject(error); + }); + cacheEntry = { + obsSet: req.obsSet, + promise, + subscribers: /* @__PURE__ */ new Set(), + type: "query", + req, + dirty: false + }; + if (container) { + container.push(cacheEntry); + } else { + container = [cacheEntry]; + if (!tblCache) { + tblCache = cache["idb://".concat(dbName, "/").concat(tableName)] = { + queries: { + query: {}, + count: {} + }, + objs: /* @__PURE__ */ new Map(), + optimisticOps: [], + unsignaledParts: {} + }; + } + tblCache.queries.query[req.query.index.name || ""] = container; + } + } + subscribeToCacheEntry(cacheEntry, container, requery, signal); + return cacheEntry.promise.then(function(res) { + var result = applyOptimisticOps(res.result, req, tblCache === null || tblCache === void 0 ? void 0 : tblCache.optimisticOps, downTable, cacheEntry, freezeResults); + return { + result: freezeResults ? result : deepClone(result) + }; + }); + } }); + return tableMW; + } }); + return coreMW; + } + }; + function vipify(target, vipDb) { + return new Proxy(target, { + get: function(target2, prop, receiver) { + if (prop === "db") + return vipDb; + return Reflect.get(target2, prop, receiver); + } + }); + } + var Dexie$1 = function() { + function Dexie4(name, options) { + var _this = this; + this._middlewares = {}; + this.verno = 0; + var deps = Dexie4.dependencies; + this._options = options = __assign({ + addons: Dexie4.addons, + autoOpen: true, + indexedDB: deps.indexedDB, + IDBKeyRange: deps.IDBKeyRange, + cache: "cloned", + maxConnections: DEFAULT_MAX_CONNECTIONS + }, options); + this._deps = { + indexedDB: options.indexedDB, + IDBKeyRange: options.IDBKeyRange + }; + var addons = options.addons; + this._dbSchema = {}; + this._versions = []; + this._storeNames = []; + this._allTables = {}; + this.idbdb = null; + this._novip = this; + var state = { + dbOpenError: null, + isBeingOpened: false, + onReadyBeingFired: null, + openComplete: false, + dbReadyResolve: nop, + dbReadyPromise: null, + cancelOpen: nop, + openCanceller: null, + autoSchema: true, + PR1398_maxLoop: 3, + autoOpen: options.autoOpen + }; + state.dbReadyPromise = new DexiePromise(function(resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function(_, reject) { + state.cancelOpen = reject; + }); + this._state = state; + this.name = name; + this.on = Events(this, "populate", "blocked", "versionchange", "close", { + ready: [promisableChain, nop] + }); + this.once = function(event, callback) { + var fn = function() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + _this.on(event).unsubscribe(fn); + callback.apply(_this, args); + }; + return _this.on(event, fn); + }; + this.on.ready.subscribe = override(this.on.ready.subscribe, function(subscribe) { + return function(subscriber, bSticky) { + Dexie4.vip(function() { + var state2 = _this._state; + if (state2.openComplete) { + if (!state2.dbOpenError) + DexiePromise.resolve().then(subscriber); + if (bSticky) + subscribe(subscriber); + } else if (state2.onReadyBeingFired) { + state2.onReadyBeingFired.push(subscriber); + if (bSticky) + subscribe(subscriber); + } else { + subscribe(subscriber); + var db_1 = _this; + if (!bSticky) + subscribe(function unsubscribe() { + db_1.on.ready.unsubscribe(subscriber); + db_1.on.ready.unsubscribe(unsubscribe); + }); + } + }); + }; + }); + this.Collection = createCollectionConstructor(this); + this.Table = createTableConstructor(this); + this.Transaction = createTransactionConstructor(this); + this.Version = createVersionConstructor(this); + this.WhereClause = createWhereClauseConstructor(this); + this.on("versionchange", function(ev) { + if (ev.newVersion > 0) + console.warn("Another connection wants to upgrade database '".concat(_this.name, "'. Closing db now to resume the upgrade.")); + else + console.warn("Another connection wants to delete database '".concat(_this.name, "'. Closing db now to resume the delete request.")); + _this.close({ disableAutoOpen: false }); + }); + this.on("blocked", function(ev) { + if (!ev.newVersion || ev.newVersion < ev.oldVersion) + console.warn("Dexie.delete('".concat(_this.name, "') was blocked")); + else + console.warn("Upgrade '".concat(_this.name, "' blocked by other connection holding version ").concat(ev.oldVersion / 10)); + }); + this._maxKey = getMaxKey(options.IDBKeyRange); + this._createTransaction = function(mode, storeNames, dbschema, parentTransaction) { + return new _this.Transaction(mode, storeNames, dbschema, _this._options.chromeTransactionDurability, parentTransaction); + }; + this._fireOnBlocked = function(ev) { + _this.on("blocked").fire(ev); + connections.toArray().filter(function(c) { + return c.name === _this.name && c !== _this && !c._state.vcFired; + }).map(function(c) { + return c.on("versionchange").fire(ev); + }); + }; + this.use(cacheExistingValuesMiddleware); + this.use(cacheMiddleware); + this.use(observabilityMiddleware); + this.use(virtualIndexMiddleware); + this.use(hooksMiddleware); + var vipDB = new Proxy(this, { + get: function(_, prop, receiver) { + if (prop === "_vip") + return true; + if (prop === "table") + return function(tableName) { + return vipify(_this.table(tableName), vipDB); + }; + var rv = Reflect.get(_, prop, receiver); + if (rv instanceof Table) + return vipify(rv, vipDB); + if (prop === "tables") + return rv.map(function(t) { + return vipify(t, vipDB); + }); + if (prop === "_createTransaction") + return function() { + var tx = rv.apply(this, arguments); + return vipify(tx, vipDB); + }; + return rv; + } + }); + this.vip = vipDB; + addons.forEach(function(addon) { + return addon(_this); + }); + } + Dexie4.prototype.version = function(versionNumber) { + if (isNaN(versionNumber) || versionNumber < 0.1) + throw new exceptions.Type("Given version is not a positive number"); + versionNumber = Math.round(versionNumber * 10) / 10; + if (this.idbdb || this._state.isBeingOpened) + throw new exceptions.Schema("Cannot add version when database is open"); + this.verno = Math.max(this.verno, versionNumber); + var versions = this._versions; + var versionInstance = versions.filter(function(v) { + return v._cfg.version === versionNumber; + })[0]; + if (versionInstance) + return versionInstance; + versionInstance = new this.Version(versionNumber); + versions.push(versionInstance); + versions.sort(lowerVersionFirst); + versionInstance.stores({}); + this._state.autoSchema = false; + return versionInstance; + }; + Dexie4.prototype._whenReady = function(fn) { + var _this = this; + return this.idbdb && (this._state.openComplete || PSD.letThrough || this._vip) ? fn() : new DexiePromise(function(resolve, reject) { + if (_this._state.openComplete) { + return reject(new exceptions.DatabaseClosed(_this._state.dbOpenError)); + } + if (!_this._state.isBeingOpened) { + if (!_this._state.autoOpen) { + reject(new exceptions.DatabaseClosed()); + return; + } + _this.open().catch(nop); + } + _this._state.dbReadyPromise.then(resolve, reject); + }).then(fn); + }; + Dexie4.prototype.use = function(_a2) { + var stack = _a2.stack, create = _a2.create, level = _a2.level, name = _a2.name; + if (name) + this.unuse({ stack, name }); + var middlewares = this._middlewares[stack] || (this._middlewares[stack] = []); + middlewares.push({ + stack, + create, + level: level == null ? 10 : level, + name + }); + middlewares.sort(function(a, b) { + return a.level - b.level; + }); + return this; + }; + Dexie4.prototype.unuse = function(_a2) { + var stack = _a2.stack, name = _a2.name, create = _a2.create; + if (stack && this._middlewares[stack]) { + this._middlewares[stack] = this._middlewares[stack].filter(function(mw) { + return create ? mw.create !== create : name ? mw.name !== name : false; + }); + } + return this; + }; + Dexie4.prototype.open = function() { + var _this = this; + return usePSD( + globalPSD, + function() { + return dexieOpen(_this); + } + ); + }; + Dexie4.prototype._close = function() { + this.on.close.fire(new CustomEvent("close")); + var state = this._state; + connections.remove(this); + if (this.idbdb) { + try { + this.idbdb.close(); + } catch (e) { + } + this.idbdb = null; + } + if (!state.isBeingOpened) { + state.dbReadyPromise = new DexiePromise(function(resolve) { + state.dbReadyResolve = resolve; + }); + state.openCanceller = new DexiePromise(function(_, reject) { + state.cancelOpen = reject; + }); + } + }; + Dexie4.prototype.close = function(_a2) { + var _b = _a2 === void 0 ? { disableAutoOpen: true } : _a2, disableAutoOpen = _b.disableAutoOpen; + var state = this._state; + if (disableAutoOpen) { + if (state.isBeingOpened) { + state.cancelOpen(new exceptions.DatabaseClosed()); + } + this._close(); + state.autoOpen = false; + state.dbOpenError = new exceptions.DatabaseClosed(); + } else { + this._close(); + state.autoOpen = this._options.autoOpen || state.isBeingOpened; + state.openComplete = false; + state.dbOpenError = null; + } + }; + Dexie4.prototype.delete = function(closeOptions) { + var _this = this; + if (closeOptions === void 0) { + closeOptions = { disableAutoOpen: true }; + } + var hasInvalidArguments = arguments.length > 0 && typeof arguments[0] !== "object"; + var state = this._state; + return new DexiePromise(function(resolve, reject) { + var doDelete = function() { + _this.close(closeOptions); + var req = _this._deps.indexedDB.deleteDatabase(_this.name); + req.onsuccess = wrap(function() { + _onDatabaseDeleted(_this._deps, _this.name); + resolve(); + }); + req.onerror = eventRejectHandler(reject); + req.onblocked = _this._fireOnBlocked; + }; + if (hasInvalidArguments) + throw new exceptions.InvalidArgument("Invalid closeOptions argument to db.delete()"); + if (state.isBeingOpened) { + state.dbReadyPromise.then(doDelete); + } else { + doDelete(); + } + }); + }; + Dexie4.prototype.backendDB = function() { + return this.idbdb; + }; + Dexie4.prototype.isOpen = function() { + return this.idbdb !== null; + }; + Dexie4.prototype.hasBeenClosed = function() { + var dbOpenError = this._state.dbOpenError; + return dbOpenError && dbOpenError.name === "DatabaseClosed"; + }; + Dexie4.prototype.hasFailed = function() { + return this._state.dbOpenError !== null; + }; + Dexie4.prototype.dynamicallyOpened = function() { + return this._state.autoSchema; + }; + Object.defineProperty(Dexie4.prototype, "tables", { + get: function() { + var _this = this; + return keys(this._allTables).map(function(name) { + return _this._allTables[name]; + }); + }, + enumerable: false, + configurable: true + }); + Dexie4.prototype.transaction = function() { + var args = extractTransactionArgs.apply(this, arguments); + return this._transaction.apply(this, args); + }; + Dexie4.prototype._transaction = function(mode, tables, scopeFunc) { + var _this = this; + var parentTransaction = PSD.trans; + if (!parentTransaction || parentTransaction.db !== this || mode.indexOf("!") !== -1) + parentTransaction = null; + var onlyIfCompatible = mode.indexOf("?") !== -1; + mode = mode.replace("!", "").replace("?", ""); + var idbMode, storeNames; + try { + storeNames = tables.map(function(table) { + var storeName = table instanceof _this.Table ? table.name : table; + if (typeof storeName !== "string") + throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); + return storeName; + }); + if (mode == "r" || mode === READONLY) + idbMode = READONLY; + else if (mode == "rw" || mode == READWRITE) + idbMode = READWRITE; + else + throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode); + if (parentTransaction) { + if (parentTransaction.mode === READONLY && idbMode === READWRITE) { + if (onlyIfCompatible) { + parentTransaction = null; + } else + throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); + } + if (parentTransaction) { + storeNames.forEach(function(storeName) { + if (parentTransaction && parentTransaction.storeNames.indexOf(storeName) === -1) { + if (onlyIfCompatible) { + parentTransaction = null; + } else + throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction."); + } + }); + } + if (onlyIfCompatible && parentTransaction && !parentTransaction.active) { + parentTransaction = null; + } + } + } catch (e) { + return parentTransaction ? parentTransaction._promise(null, function(_, reject) { + reject(e); + }) : rejection(e); + } + var enterTransaction = enterTransactionScope.bind(null, this, idbMode, storeNames, parentTransaction, scopeFunc); + return parentTransaction ? parentTransaction._promise(idbMode, enterTransaction, "lock") : PSD.trans ? usePSD(PSD.transless, function() { + return _this._whenReady(enterTransaction); + }) : this._whenReady(enterTransaction); + }; + Dexie4.prototype.table = function(tableName) { + if (!hasOwn(this._allTables, tableName)) { + throw new exceptions.InvalidTable("Table ".concat(tableName, " does not exist")); + } + return this._allTables[tableName]; + }; + return Dexie4; + }(); + var symbolObservable = typeof Symbol !== "undefined" && "observable" in Symbol ? Symbol.observable : "@@observable"; + var Observable = function() { + function Observable2(subscribe) { + this._subscribe = subscribe; + } + Observable2.prototype.subscribe = function(x, error, complete) { + return this._subscribe(!x || typeof x === "function" ? { next: x, error, complete } : x); + }; + Observable2.prototype[symbolObservable] = function() { + return this; + }; + return Observable2; + }(); + var domDeps; + try { + domDeps = { + indexedDB: _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB, + IDBKeyRange: _global.IDBKeyRange || _global.webkitIDBKeyRange + }; + } catch (e) { + domDeps = { indexedDB: null, IDBKeyRange: null }; + } + function liveQuery2(querier) { + var hasValue = false; + var currentValue; + var observable = new Observable(function(observer) { + var scopeFuncIsAsync = isAsyncFunction(querier); + function execute(ctx) { + var wasRootExec = beginMicroTickScope(); + try { + if (scopeFuncIsAsync) { + incrementExpectedAwaits(); + } + var rv = newScope(querier, ctx); + if (scopeFuncIsAsync) { + rv = rv.finally(decrementExpectedAwaits); + } + return rv; + } finally { + wasRootExec && endMicroTickScope(); + } + } + var closed = false; + var abortController; + var accumMuts = {}; + var currentObs = {}; + var subscription = { + get closed() { + return closed; + }, + unsubscribe: function() { + if (closed) + return; + closed = true; + if (abortController) + abortController.abort(); + if (startedListening) + globalEvents.storagemutated.unsubscribe(mutationListener); + } + }; + observer.start && observer.start(subscription); + var startedListening = false; + var doQuery = function() { + return execInGlobalContext(_doQuery); + }; + function shouldNotify() { + return obsSetsOverlap(currentObs, accumMuts); + } + var mutationListener = function(parts) { + extendObservabilitySet(accumMuts, parts); + if (shouldNotify()) { + doQuery(); + } + }; + var _doQuery = function() { + if (closed || !domDeps.indexedDB) { + return; + } + accumMuts = {}; + var subscr = {}; + if (abortController) + abortController.abort(); + abortController = new AbortController(); + var ctx = { + subscr, + signal: abortController.signal, + requery: doQuery, + querier, + trans: null + }; + var ret = execute(ctx); + if (!startedListening) { + globalEvents.storagemutated.subscribe(mutationListener); + startedListening = true; + } + Promise.resolve(ret).then(function(result) { + hasValue = true; + currentValue = result; + if (closed || ctx.signal.aborted) { + return; + } + if (shouldNotify()) { + doQuery(); + } else { + currentObs = subscr; + if (shouldNotify()) { + doQuery(); + } else { + accumMuts = {}; + execInGlobalContext(function() { + return !closed && observer.next && observer.next(result); + }); + } + } + }, function(err) { + hasValue = false; + if (!["DatabaseClosedError", "AbortError"].includes(err === null || err === void 0 ? void 0 : err.name)) { + if (!closed) + execInGlobalContext(function() { + if (closed) + return; + observer.error && observer.error(err); + }); + } + }); + }; + setTimeout(doQuery, 0); + return subscription; + }); + observable.hasValue = function() { + return hasValue; + }; + observable.getValue = function() { + return currentValue; + }; + return observable; + } + var Dexie3 = Dexie$1; + props(Dexie3, __assign(__assign({}, fullNameExceptions), { + delete: function(databaseName) { + var db2 = new Dexie3(databaseName, { addons: [] }); + return db2.delete(); + }, + exists: function(name) { + return new Dexie3(name, { addons: [] }).open().then(function(db2) { + db2.close(); + return true; + }).catch("NoSuchDatabaseError", function() { + return false; + }); + }, + getDatabaseNames: function(cb) { + try { + return getDatabaseNames(Dexie3.dependencies).then(cb); + } catch (_a2) { + return rejection(new exceptions.MissingAPI()); + } + }, + defineClass: function() { + function Class(content) { + extend(this, content); + } + return Class; + }, + ignoreTransaction: function(scopeFunc) { + return PSD.trans ? usePSD(PSD.transless || globalPSD, scopeFunc) : scopeFunc(); + }, + vip, + async: function(generatorFn) { + return function() { + try { + var rv = awaitIterator(generatorFn.apply(this, arguments)); + if (!rv || typeof rv.then !== "function") + return DexiePromise.resolve(rv); + return rv; + } catch (e) { + return rejection(e); + } + }; + }, + spawn: function(generatorFn, args, thiz) { + try { + var rv = awaitIterator(generatorFn.apply(thiz, args || [])); + if (!rv || typeof rv.then !== "function") + return DexiePromise.resolve(rv); + return rv; + } catch (e) { + return rejection(e); + } + }, + currentTransaction: { + get: function() { + return PSD.trans || null; + } + }, + waitFor: function(promiseOrFunction, optionalTimeout) { + var promise = DexiePromise.resolve(typeof promiseOrFunction === "function" ? Dexie3.ignoreTransaction(promiseOrFunction) : promiseOrFunction).timeout(optionalTimeout || 6e4); + return PSD.trans ? PSD.trans.waitFor(promise) : promise; + }, + Promise: DexiePromise, + debug: { + get: function() { + return debug; + }, + set: function(value) { + setDebug(value); + } + }, + derive, + extend, + props, + override, + Events, + on: globalEvents, + liveQuery: liveQuery2, + extendObservabilitySet, + getByKeyPath, + setByKeyPath, + delByKeyPath, + shallowClone, + deepClone, + getObjectDiff, + cmp: cmp3, + asap: asap$1, + minKey, + addons: [], + connections: { + get: connections.toArray + }, + errnames, + dependencies: domDeps, + cache, + semVer: DEXIE_VERSION, + version: DEXIE_VERSION.split(".").map(function(n) { + return parseInt(n); + }).reduce(function(p, c, i) { + return p + c / Math.pow(10, i * 2); + }) + })); + Dexie3.maxKey = getMaxKey(Dexie3.dependencies.IDBKeyRange); + if (typeof dispatchEvent !== "undefined" && typeof addEventListener !== "undefined") { + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function(updatedParts) { + if (!propagatingLocally) { + var event_1; + event_1 = new CustomEvent(STORAGE_MUTATED_DOM_EVENT_NAME, { + detail: updatedParts + }); + propagatingLocally = true; + dispatchEvent(event_1); + propagatingLocally = false; + } + }); + addEventListener(STORAGE_MUTATED_DOM_EVENT_NAME, function(_a2) { + var detail = _a2.detail; + if (!propagatingLocally) { + propagateLocally(detail); + } + }); + } + function propagateLocally(updateParts) { + var wasMe = propagatingLocally; + try { + propagatingLocally = true; + globalEvents.storagemutated.fire(updateParts); + signalSubscribersNow(updateParts, true); + } finally { + propagatingLocally = wasMe; + } + } + var propagatingLocally = false; + var bc; + var createBC = function() { + }; + if (typeof BroadcastChannel !== "undefined") { + createBC = function() { + bc = new BroadcastChannel(STORAGE_MUTATED_DOM_EVENT_NAME); + bc.onmessage = function(ev) { + return ev.data && propagateLocally(ev.data); + }; + }; + createBC(); + if (typeof bc.unref === "function") { + bc.unref(); + } + globalEvents(DEXIE_STORAGE_MUTATED_EVENT_NAME, function(changedParts) { + if (!propagatingLocally) { + bc.postMessage(changedParts); + } + }); + } + if (typeof addEventListener !== "undefined") { + addEventListener("pagehide", function(event) { + if (!Dexie$1.disableBfCache && event.persisted) { + if (debug) + console.debug("Dexie: handling persisted pagehide"); + bc === null || bc === void 0 ? void 0 : bc.close(); + for (var _i = 0, _a2 = connections.toArray(); _i < _a2.length; _i++) { + var db2 = _a2[_i]; + db2.close({ disableAutoOpen: false }); + } + } + }); + addEventListener("pageshow", function(event) { + if (!Dexie$1.disableBfCache && event.persisted) { + if (debug) + console.debug("Dexie: handling persisted pageshow"); + createBC(); + propagateLocally({ all: new RangeSet2(-Infinity, [[]]) }); + } + }); + } + function add2(value) { + return new PropModification2({ add: value }); + } + function remove2(value) { + return new PropModification2({ remove: value }); + } + function replacePrefix2(a, b) { + return new PropModification2({ replacePrefix: [a, b] }); + } + DexiePromise.rejectionMapper = mapError; + setDebug(debug); + var namedExports = /* @__PURE__ */ Object.freeze({ + __proto__: null, + DEFAULT_MAX_CONNECTIONS, + Dexie: Dexie$1, + Entity: Entity2, + PropModification: PropModification2, + RangeSet: RangeSet2, + add: add2, + cmp: cmp3, + default: Dexie$1, + liveQuery: liveQuery2, + mergeRanges: mergeRanges2, + rangesOverlap: rangesOverlap2, + remove: remove2, + replacePrefix: replacePrefix2 + }); + __assign(Dexie$1, namedExports, { default: Dexie$1 }); + return Dexie$1; + }); + } +}); + +// intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/import-wrapper.mjs +var import_dexie, DexieSymbol, Dexie, liveQuery, mergeRanges, rangesOverlap, RangeSet, cmp2, Entity, PropModification, replacePrefix, add, remove, DexieYProvider, import_wrapper_default; +var init_import_wrapper = __esm({ + "intern-log/node_modules/.pnpm/dexie@4.4.6/node_modules/dexie/import-wrapper.mjs"() { + import_dexie = __toESM(require_dexie(), 1); + DexieSymbol = Symbol.for("Dexie"); + Dexie = globalThis[DexieSymbol] || (globalThis[DexieSymbol] = import_dexie.default); + if (import_dexie.default.semVer !== Dexie.semVer) { + throw new Error(`Two different versions of Dexie loaded in the same app: ${import_dexie.default.semVer} and ${Dexie.semVer}`); + } + ({ + liveQuery, + mergeRanges, + rangesOverlap, + RangeSet, + cmp: cmp2, + Entity, + PropModification, + replacePrefix, + add, + remove, + DexieYProvider + } = Dexie); + import_wrapper_default = Dexie; + } +}); + +// intern-log/src/db/schema.ts +var schema_exports = {}; +__export(schema_exports, { + CATEGORIES: () => CATEGORIES, + DEFAULT_LOCATIONS: () => DEFAULT_LOCATIONS, + EXPENSE_CATEGORIES: () => EXPENSE_CATEGORIES, + INCOME_CATEGORIES: () => INCOME_CATEGORIES, + SCHEMA_VERSION: () => SCHEMA_VERSION, + WorklogDB: () => WorklogDB, + bindDatabase: () => bindDatabase, + categoryLabel: () => categoryLabel, + db: () => db, + unbindDatabase: () => unbindDatabase +}); +function bindDatabase(instance) { + db = instance; +} +function unbindDatabase() { + if (db) db.close(); + db = void 0; +} +function categoryLabel(key) { + const found = CATEGORIES.find((c) => c.key === key); + return found ? found.label : "\u5176\u4ED6"; +} +var WorklogDB, db, SCHEMA_VERSION, EXPENSE_CATEGORIES, INCOME_CATEGORIES, DEFAULT_LOCATIONS, CATEGORIES; +var init_schema = __esm({ + "intern-log/src/db/schema.ts"() { + "use strict"; + init_import_wrapper(); + WorklogDB = class extends import_wrapper_default { + constructor(dbName = "intern_worklog") { + super(dbName); + this.version(1).stores({ + project: "++id, &name, archived", + work_log: "++id, &date", + log_item: "++id, work_log_id, project_id, category", + attendance: "++id, &date", + weekly_note: "++id, &week_start", + setting: "key" + }); + this.version(2).stores({ + memo: "++id, updated_at", + credential: "++id, system, updated_at" + }); + this.version(3).stores({ + transaction: "++id, date, type, category" + }); + this.version(4).stores({ + sync_mirror: "++id, table, uuid", + tombstone: "++id, table, uuid, deleted_at" + }); + } + }; + SCHEMA_VERSION = 4; + EXPENSE_CATEGORIES = ["\u9910\u996E", "\u4EA4\u901A", "\u4F4F\u623F", "\u901A\u8BAF", "\u5B66\u4E60", "\u5A31\u4E50", "\u5176\u4ED6"]; + INCOME_CATEGORIES = ["\u5DE5\u8D44", "\u62A5\u9500", "\u5176\u4ED6"]; + DEFAULT_LOCATIONS = ["\u516C\u53F8", "\u5BA2\u6237\u73B0\u573A", "\u51FA\u5DEE", "\u5C45\u5BB6\u529E\u516C"]; + CATEGORIES = [ + { key: "dev", label: "\u5F00\u53D1" }, + { key: "bugfix", label: "BUG\u4FEE\u590D" }, + { key: "test", label: "\u6D4B\u8BD5" }, + { key: "learning", label: "\u5B66\u4E60\u6210\u957F" }, + { key: "meeting", label: "\u4F1A\u8BAE\u6C9F\u901A" }, + { key: "doc", label: "\u6587\u6863\u8F93\u51FA" }, + { key: "other", label: "\u5176\u4ED6" } + ]; + } +}); + +// intern-log/src/lib/date.ts +function pad(n) { + return n < 10 ? "0" + n : String(n); +} +function toDateStr(d) { + return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()); +} +function nowLocalISO() { + const d = /* @__PURE__ */ new Date(); + return toDateStr(d) + "T" + pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds()); +} +var init_date = __esm({ + "intern-log/src/lib/date.ts"() { + "use strict"; + } +}); + +// intern-log/src/db/repo.ts +async function getSetting(key, fallback) { + const row = await db.setting.get(key); + return row ? row.value : fallback; +} +async function setSetting(key, value) { + await db.setting.put({ key, value }); +} +var init_repo = __esm({ + "intern-log/src/db/repo.ts"() { + "use strict"; + init_schema(); + init_date(); + } +}); + +// intern-log/src/lib/crypto.ts +var init_crypto = __esm({ + "intern-log/src/lib/crypto.ts"() { + "use strict"; + } +}); + +// intern-log/src/db/vault.ts +var init_vault = __esm({ + "intern-log/src/db/vault.ts"() { + "use strict"; + init_schema(); + init_repo(); + init_crypto(); + init_date(); + } +}); + +// intern-log/src/db/auth.ts +function getCloudCreds() { + try { + const raw = localStorage.getItem(CREDS_KEY); + if (!raw) return null; + const c = JSON.parse(raw); + if (c && c.username && c.password) return c; + } catch { + } + return null; +} +var UserRegistry, registry, CREDS_KEY; +var init_auth = __esm({ + "intern-log/src/db/auth.ts"() { + "use strict"; + init_import_wrapper(); + init_schema(); + init_vault(); + init_crypto(); + UserRegistry = class extends import_wrapper_default { + constructor() { + super("intern_worklog_users"); + this.version(1).stores({ user: "id, &username" }); + } + }; + registry = new UserRegistry(); + CREDS_KEY = "dsh_cloud_creds"; + } +}); + +// intern-log/src/sync/engine.ts +var engine_exports = {}; +__export(engine_exports, { + DEFAULT_SYNC_BASE: () => DEFAULT_SYNC_BASE, + SYNC_TABLES: () => SYNC_TABLES, + autoSyncNow: () => autoSyncNow, + enableRealtimeSync: () => enableRealtimeSync, + ensureCloudBinding: () => ensureCloudBinding, + getCloudUser: () => getCloudUser, + getSyncBase: () => getSyncBase, + getSyncLastTime: () => getSyncLastTime, + isSyncConfigured: () => isSyncConfigured, + registerCloudAccount: () => registerCloudAccount, + runSync: () => runSync, + stopRealtime: () => stopRealtime, + syncWithStoredConfig: () => syncWithStoredConfig +}); +function newUuid() { + if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID(); + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { + const r = Math.random() * 16 | 0; + return (c === "x" ? r : r & 3 | 8).toString(16); + }); +} +function stripId(row) { + const copy = { ...row }; + delete copy.id; + return copy; +} +function rowHash(row) { + return JSON.stringify(row); +} +async function getTable(name) { + return db.table(name).toArray(); +} +function pkOf(t, row) { + return t === "setting" ? row.key : row.id; +} +async function ensureSyncFields() { + for (const t of TABLES) { + const table = db.table(t); + const rows = await table.toArray(); + for (const row of rows) { + if (t === "setting" && EXCLUDE_SETTING_KEYS.has(row.key)) continue; + const patch = {}; + if (!row.uuid) patch.uuid = newUuid(); + if (!row.updated_at) patch.updated_at = row.created_at || nowLocalISO(); + if (Object.keys(patch).length) await table.update(pkOf(t, row), patch); + } + } +} +async function getSyncBase() { + return await getSetting("sync_base_url", "") || DEFAULT_SYNC_BASE; +} +async function loadSyncConfig() { + const creds = getCloudCreds(); + if (!creds) throw new Error("\u672A\u767B\u5F55\uFF0C\u65E0\u6CD5\u540C\u6B65"); + return { baseUrl: await getSyncBase(), username: creds.username, password: creds.password }; +} +async function syncWithStoredConfig() { + return runSync(await loadSyncConfig()); +} +async function ensureCloudBinding() { + const creds = getCloudCreds(); + if (!creds) throw new Error("\u672A\u767B\u5F55"); + const base = await getSyncBase(); + const headers = { "Content-Type": "application/json" }; + const body = JSON.stringify({ username: creds.username, password: creds.password }); + let resp = await fetch(base + "/api/auth/register", { method: "POST", headers, body }); + if (resp.status === 409) { + resp = await fetch(base + "/api/auth/login", { method: "POST", headers, body }); + if (!resp.ok) throw new Error("\u4E91\u7AEF\u5DF2\u5B58\u5728\u540C\u540D\u8D26\u53F7\u4E14\u5BC6\u7801\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u68C0\u67E5"); + } else if (!resp.ok) { + throw new Error("\u4E91\u7AEF\u7ED1\u5B9A\u5931\u8D25\uFF1A" + resp.status); + } +} +function getCloudUser() { + const c = getCloudCreds(); + return c ? c.username : null; +} +async function isSyncConfigured() { + return getCloudCreds() != null; +} +async function getSyncLastTime() { + return getSetting("sync_last_time", ""); +} +async function registerCloudAccount(baseUrl, username, password) { + const base = baseUrl.trim().replace(/\/+$/, ""); + if (!base || !username.trim() || password.length < 6) { + throw new Error("\u8BF7\u5B8C\u6574\u586B\u5199\u540C\u6B65\u5730\u5740\u3001\u7528\u6237\u540D\u4E0E\u81F3\u5C11 6 \u4F4D\u7684\u5BC6\u7801"); + } + let resp; + try { + resp = await fetch(base + "/api/auth/register", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username: username.trim(), password }) + }); + } catch { + throw new Error("\u65E0\u6CD5\u8BBF\u95EE\u540C\u6B65\u670D\u52A1\uFF1A\u8BF7\u68C0\u67E5\u5730\u5740\u3001\u7AEF\u53E3\u4E0E\u7F51\u7EDC"); + } + if (resp.status === 409) throw new Error("\u4E91\u7AEF\u7528\u6237\u540D\u5DF2\u5B58\u5728\uFF0C\u53EF\u76F4\u63A5\u540C\u6B65"); + if (!resp.ok) throw new Error("\u4E91\u7AEF\u6CE8\u518C\u5931\u8D25\uFF1A" + resp.status); +} +async function loginCloud(base, config) { + const resp = await fetch(base + "/api/auth/login", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username: config.username.trim(), password: config.password }) + }); + if (!resp.ok) throw new Error("\u4E91\u7AEF\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E"); + const j = await resp.json(); + if (!j || !j.token) throw new Error("\u4E91\u7AEF\u767B\u5F55\u5F02\u5E38"); + return String(j.token); +} +async function ensureToken(base, config) { + let token = await getSetting("sync_token", ""); + if (token) return token; + token = await loginCloud(base, config); + await setSetting("sync_token", token); + return token; +} +async function autoSyncNow() { + if (syncRunning) { + pendingSync = true; + return; + } + try { + if (!await isSyncConfigured()) return; + await runSync(await loadSyncConfig()); + } catch { + } +} +function enableRealtimeSync() { + if (realtimeAttached) return; + realtimeAttached = true; + const sub = liveQuery(async () => { + const counts = {}; + for (const t of TABLES) counts[t] = await db.table(t).count(); + return counts; + }); + realtimeSub = sub.subscribe({ + next: () => { + if (changesSuppressed || syncRunning) return; + if (changeDebounce) globalThis.clearTimeout(changeDebounce); + changeDebounce = globalThis.setTimeout(() => { + void autoSyncNow(); + }, 3e3); + }, + error: () => { + } + }); +} +function stopRealtime() { + if (realtimeSub) { + realtimeSub.unsubscribe(); + realtimeSub = null; + } + if (sse) { + sse.close(); + sse = null; + sseKey = ""; + } + if (changeDebounce) { + globalThis.clearTimeout(changeDebounce); + changeDebounce = null; + } +} +function ensureSSE(base, token) { + const key = base + "|" + token; + if (sse && sseKey === key) return; + if (sse) { + sse.close(); + sse = null; + } + try { + sse = new EventSource(base + "/api/events?token=" + encodeURIComponent(token)); + sseKey = key; + sse.onmessage = () => { + void autoSyncNow(); + }; + } catch { + sse = null; + } +} +async function runSync(config) { + if (syncRunning) { + pendingSync = true; + return { pushed: 0, pulled: 0, removed: 0, at: "" }; + } + syncRunning = true; + changesSuppressed = true; + try { + const result = await doRunSync(config); + if (pendingSync) { + pendingSync = false; + globalThis.setTimeout(() => { + void autoSyncNow(); + }, 800); + } + return result; + } finally { + syncRunning = false; + changesSuppressed = false; + } +} +async function doRunSync(config) { + const base = config.baseUrl.trim().replace(/\/+$/, ""); + if (!base) throw new Error("\u8BF7\u5148\u914D\u7F6E\u540C\u6B65\u670D\u52A1\u5730\u5740"); + await ensureSyncFields(); + const mirrorRows = await db.sync_mirror.toArray(); + const mirror = /* @__PURE__ */ new Map(); + for (const m of mirrorRows) mirror.set(m.table + "|" + m.uuid, m); + const pushTables = {}; + const tombstones = []; + let pushed = 0; + for (const t of TABLES) { + let rows = await getTable(t); + if (t === "setting") rows = rows.filter((r) => !EXCLUDE_SETTING_KEYS.has(r.key)); + const current = /* @__PURE__ */ new Map(); + for (const row of rows) current.set(row.uuid, row); + for (const [u, row] of current) { + const clean = stripId(row); + const h = rowHash(clean); + const m = mirror.get(t + "|" + u); + if (!m || m.hash !== h) { + pushTables[t] = pushTables[t] || []; + pushTables[t].push(clean); + pushed++; + } + } + for (const [key, m] of mirror) { + if (key.startsWith(t + "|") && !current.has(m.uuid)) { + tombstones.push({ table: t, uuid: m.uuid, deleted_at: nowLocalISO() }); + } + } + pushTables[t] = pushTables[t] || []; + } + const token = await ensureToken(base, config); + const doPush = (tk) => fetch(base + "/api/sync", { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: "Bearer " + tk }, + body: JSON.stringify({ device: "client", tables: pushTables, tombstones }) + }); + let resp = await doPush(token); + if (resp.status === 401) { + await setSetting("sync_token", ""); + const token2 = await loginCloud(base, config); + await setSetting("sync_token", token2); + resp = await doPush(token2); + } + if (!resp.ok) throw new Error("\u540C\u6B65\u670D\u52A1\u8FD4\u56DE " + resp.status); + const data = await resp.json(); + const serverTables = data.tables || {}; + const serverTombstones = data.tombstones || []; + let pulled = 0; + let removed = 0; + const finalMirror = []; + for (const t of TABLES) { + const table = db.table(t); + const localRows = await table.toArray(); + const byUuid = /* @__PURE__ */ new Map(); + for (const row of localRows) byUuid.set(row.uuid, row); + const serverRows = serverTables[t] || []; + const serverByUuid = /* @__PURE__ */ new Map(); + for (const row of serverRows) serverByUuid.set(row.uuid, row); + const dead = new Set(serverTombstones.filter((x) => x.table === t).map((x) => x.uuid)); + for (const [u, row] of byUuid) { + if (dead.has(u)) { + await table.delete(pkOf(t, row)); + removed++; + } + } + for (const srow of serverRows) { + if (dead.has(srow.uuid)) continue; + const local = byUuid.get(srow.uuid); + if (!local) { + await table.add({ ...srow }); + pulled++; + } else { + const localUa = String(local.updated_at || ""); + const serverUa = String(srow.updated_at || ""); + if (serverUa > localUa) { + const patch = { ...srow }; + if (t === "setting") delete patch.key; + await table.update(pkOf(t, local), patch); + pulled++; + } + } + } + const finalRows = await table.toArray(); + for (const row of finalRows) { + if (t === "setting" && EXCLUDE_SETTING_KEYS.has(row.key)) continue; + finalMirror.push({ table: t, uuid: row.uuid, hash: rowHash(stripId(row)) }); + } + } + await db.sync_mirror.clear(); + if (finalMirror.length) await db.sync_mirror.bulkAdd(finalMirror.map((m) => ({ ...m }))); + ensureSSE(base, token); + const at = nowLocalISO(); + await setSetting("sync_last_time", at); + return { pushed, pulled, removed, at }; +} +var DEFAULT_SYNC_BASE, TABLES, EXCLUDE_SETTING_KEYS, SYNC_TABLES, syncRunning, pendingSync, changesSuppressed, changeDebounce, sse, sseKey, realtimeAttached, realtimeSub; +var init_engine = __esm({ + "intern-log/src/sync/engine.ts"() { + "use strict"; + init_import_wrapper(); + init_schema(); + init_repo(); + init_auth(); + init_date(); + DEFAULT_SYNC_BASE = "https://daywk.linyux.cn"; + TABLES = ["project", "work_log", "log_item", "attendance", "weekly_note", "setting", "memo", "credential", "transaction"]; + EXCLUDE_SETTING_KEYS = /* @__PURE__ */ new Set(["sync_cursor", "sync_last_time", "sync_token", "last_project", "last_category"]); + SYNC_TABLES = TABLES; + syncRunning = false; + pendingSync = false; + changesSuppressed = false; + changeDebounce = null; + sse = null; + sseKey = ""; + realtimeAttached = false; + realtimeSub = null; + } +}); + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/errors.js +var messages = { + AbortError: "A request was aborted, for example through a call to IDBTransaction.abort.", + ConstraintError: "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one.", + DataCloneError: "The data being stored could not be cloned by the internal structured cloning algorithm.", + DataError: "Data provided to an operation does not meet requirements.", + InvalidAccessError: "An invalid operation was performed on an object. For example transaction creation attempt was made, but an empty scope was provided.", + InvalidStateError: "An operation was called on an object on which it is not allowed or at a time when it is not allowed. Also occurs if a request is made on a source object that has been deleted or removed. Use TransactionInactiveError or ReadOnlyError when possible, as they are more specific variations of InvalidStateError.", + NotFoundError: "The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.", + ReadOnlyError: 'The mutating operation was attempted in a "readonly" transaction.', + TransactionInactiveError: "A request was placed against a transaction which is currently not active, or which is finished.", + SyntaxError: "The keypath argument contains an invalid key path", + VersionError: "An attempt was made to open a database using a lower version than the existing version." +}; +var setErrorCode = (error, value) => { + Object.defineProperty(error, "code", { + value, + writable: false, + enumerable: true, + configurable: false + }); +}; +var AbortError = class extends DOMException { + constructor(message = messages.AbortError) { + super(message, "AbortError"); + } +}; +var ConstraintError = class extends DOMException { + constructor(message = messages.ConstraintError) { + super(message, "ConstraintError"); + } +}; +var DataError = class extends DOMException { + constructor(message = messages.DataError) { + super(message, "DataError"); + setErrorCode(this, 0); + } +}; +var InvalidAccessError = class extends DOMException { + constructor(message = messages.InvalidAccessError) { + super(message, "InvalidAccessError"); + } +}; +var InvalidStateError = class extends DOMException { + constructor(message = messages.InvalidStateError) { + super(message, "InvalidStateError"); + setErrorCode(this, 11); + } +}; +var NotFoundError = class extends DOMException { + constructor(message = messages.NotFoundError) { + super(message, "NotFoundError"); + } +}; +var ReadOnlyError = class extends DOMException { + constructor(message = messages.ReadOnlyError) { + super(message, "ReadOnlyError"); + } +}; +var SyntaxError2 = class extends DOMException { + constructor(message = messages.VersionError) { + super(message, "SyntaxError"); + setErrorCode(this, 12); + } +}; +var TransactionInactiveError = class extends DOMException { + constructor(message = messages.TransactionInactiveError) { + super(message, "TransactionInactiveError"); + setErrorCode(this, 0); + } +}; +var VersionError = class extends DOMException { + constructor(message = messages.VersionError) { + super(message, "VersionError"); + } +}; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/isSharedArrayBuffer.js +function isSharedArrayBuffer(input) { + return typeof SharedArrayBuffer !== "undefined" && input instanceof SharedArrayBuffer; +} + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKeyWithoutThrowing.js +var INVALID_TYPE = Symbol("INVALID_TYPE"); +var INVALID_VALUE = Symbol("INVALID_VALUE"); +var valueToKeyWithoutThrowing = (input, seen) => { + if (typeof input === "number") { + if (isNaN(input)) { + return INVALID_VALUE; + } + return input; + } else if (Object.prototype.toString.call(input) === "[object Date]") { + const ms = input.valueOf(); + if (isNaN(ms)) { + return INVALID_VALUE; + } + return new Date(ms); + } else if (typeof input === "string") { + return input; + } else if ( + // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type + input instanceof ArrayBuffer || isSharedArrayBuffer(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input) + ) { + if ("detached" in input ? input.detached : input.byteLength === 0) { + return INVALID_VALUE; + } + let arrayBuffer; + let offset = 0; + let length = 0; + if (input instanceof ArrayBuffer || isSharedArrayBuffer(input)) { + arrayBuffer = input; + length = input.byteLength; + } else { + arrayBuffer = input.buffer; + offset = input.byteOffset; + length = input.byteLength; + } + return arrayBuffer.slice(offset, offset + length); + } else if (Array.isArray(input)) { + if (seen === void 0) { + seen = /* @__PURE__ */ new Set(); + } else if (seen.has(input)) { + return INVALID_VALUE; + } + seen.add(input); + let hasInvalid = false; + const keys = Array.from({ + length: input.length + }, (_, i) => { + if (hasInvalid) { + return; + } + const hop = Object.hasOwn(input, i); + if (!hop) { + hasInvalid = true; + return; + } + const entry = input[i]; + const key = valueToKeyWithoutThrowing(entry, seen); + if (key === INVALID_VALUE || key === INVALID_TYPE) { + hasInvalid = true; + return; + } + return key; + }); + if (hasInvalid) { + return INVALID_VALUE; + } + return keys; + } else { + return INVALID_TYPE; + } +}; +var valueToKeyWithoutThrowing_default = valueToKeyWithoutThrowing; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKey.js +var valueToKey = (input, seen) => { + const result = valueToKeyWithoutThrowing_default(input, seen); + if (result === INVALID_VALUE || result === INVALID_TYPE) { + throw new DataError(); + } + return result; +}; +var valueToKey_default = valueToKey; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/cmp.js +var getType = (x) => { + if (typeof x === "number") { + return "Number"; + } + if (Object.prototype.toString.call(x) === "[object Date]") { + return "Date"; + } + if (Array.isArray(x)) { + return "Array"; + } + if (typeof x === "string") { + return "String"; + } + if (x instanceof ArrayBuffer) { + return "Binary"; + } + throw new DataError(); +}; +var cmp = (first, second) => { + if (second === void 0) { + throw new TypeError(); + } + first = valueToKey_default(first); + second = valueToKey_default(second); + const t1 = getType(first); + const t2 = getType(second); + if (t1 !== t2) { + if (t1 === "Array") { + return 1; + } + if (t1 === "Binary" && (t2 === "String" || t2 === "Date" || t2 === "Number")) { + return 1; + } + if (t1 === "String" && (t2 === "Date" || t2 === "Number")) { + return 1; + } + if (t1 === "Date" && t2 === "Number") { + return 1; + } + return -1; + } + if (t1 === "Binary") { + first = new Uint8Array(first); + second = new Uint8Array(second); + } + if (t1 === "Array" || t1 === "Binary") { + const length = Math.min(first.length, second.length); + for (let i = 0; i < length; i++) { + const result = cmp(first[i], second[i]); + if (result !== 0) { + return result; + } + } + if (first.length > second.length) { + return 1; + } + if (first.length < second.length) { + return -1; + } + return 0; + } + if (t1 === "Date") { + if (first.getTime() === second.getTime()) { + return 0; + } + } else { + if (first === second) { + return 0; + } + } + return first > second ? 1 : -1; +}; +var cmp_default = cmp; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBKeyRange.js +var FDBKeyRange = class _FDBKeyRange { + static only(value) { + if (arguments.length === 0) { + throw new TypeError(); + } + value = valueToKey_default(value); + return new _FDBKeyRange(value, value, false, false); + } + static lowerBound(lower, open = false) { + if (arguments.length === 0) { + throw new TypeError(); + } + lower = valueToKey_default(lower); + return new _FDBKeyRange(lower, void 0, open, true); + } + static upperBound(upper, open = false) { + if (arguments.length === 0) { + throw new TypeError(); + } + upper = valueToKey_default(upper); + return new _FDBKeyRange(void 0, upper, true, open); + } + static bound(lower, upper, lowerOpen = false, upperOpen = false) { + if (arguments.length < 2) { + throw new TypeError(); + } + const cmpResult = cmp_default(lower, upper); + if (cmpResult === 1 || cmpResult === 0 && (lowerOpen || upperOpen)) { + throw new DataError(); + } + lower = valueToKey_default(lower); + upper = valueToKey_default(upper); + return new _FDBKeyRange(lower, upper, lowerOpen, upperOpen); + } + constructor(lower, upper, lowerOpen, upperOpen) { + this.lower = lower; + this.upper = upper; + this.lowerOpen = lowerOpen; + this.upperOpen = upperOpen; + } + // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes + includes(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + key = valueToKey_default(key); + if (this.lower !== void 0) { + const cmpResult = cmp_default(this.lower, key); + if (cmpResult === 1 || cmpResult === 0 && this.lowerOpen) { + return false; + } + } + if (this.upper !== void 0) { + const cmpResult = cmp_default(this.upper, key); + if (cmpResult === -1 || cmpResult === 0 && this.upperOpen) { + return false; + } + } + return true; + } + get [Symbol.toStringTag]() { + return "IDBKeyRange"; + } +}; +var FDBKeyRange_default = FDBKeyRange; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/extractKey.js +var extractKey = (keyPath, value) => { + if (Array.isArray(keyPath)) { + const result = []; + for (let item of keyPath) { + if (item !== void 0 && item !== null && typeof item !== "string" && item.toString) { + item = item.toString(); + } + const key = extractKey(item, value).key; + result.push(valueToKey_default(key)); + } + return { + type: "found", + key: result + }; + } + if (keyPath === "") { + return { + type: "found", + key: value + }; + } + let remainingKeyPath = keyPath; + let object = value; + while (remainingKeyPath !== null) { + let identifier; + const i = remainingKeyPath.indexOf("."); + if (i >= 0) { + identifier = remainingKeyPath.slice(0, i); + remainingKeyPath = remainingKeyPath.slice(i + 1); + } else { + identifier = remainingKeyPath; + remainingKeyPath = null; + } + const isSpecialIdentifier = identifier === "length" && (typeof object === "string" || Array.isArray(object)) || (identifier === "size" || identifier === "type") && typeof Blob !== "undefined" && object instanceof Blob || (identifier === "name" || identifier === "lastModified") && typeof File !== "undefined" && object instanceof File; + if (!isSpecialIdentifier && (typeof object !== "object" || object === null || !Object.hasOwn(object, identifier))) { + return { + type: "notFound" + }; + } + object = object[identifier]; + } + return { + type: "found", + key: object + }; +}; +var extractKey_default = extractKey; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/cloneValueForInsertion.js +function cloneValueForInsertion(value, transaction) { + if (transaction._state !== "active") { + throw new Error("Assert: transaction state is active"); + } + transaction._state = "inactive"; + try { + return structuredClone(value); + } finally { + transaction._state = "active"; + } +} + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBCursor.js +var getEffectiveObjectStore = (cursor) => { + if (cursor.source instanceof FDBObjectStore_default) { + return cursor.source; + } + return cursor.source.objectStore; +}; +var makeKeyRange = (range, lowers, uppers) => { + let lower = range !== void 0 ? range.lower : void 0; + let upper = range !== void 0 ? range.upper : void 0; + for (const lowerTemp of lowers) { + if (lowerTemp === void 0) { + continue; + } + if (lower === void 0 || cmp_default(lower, lowerTemp) === 1) { + lower = lowerTemp; + } + } + for (const upperTemp of uppers) { + if (upperTemp === void 0) { + continue; + } + if (upper === void 0 || cmp_default(upper, upperTemp) === -1) { + upper = upperTemp; + } + } + if (lower !== void 0 && upper !== void 0) { + return FDBKeyRange_default.bound(lower, upper); + } + if (lower !== void 0) { + return FDBKeyRange_default.lowerBound(lower); + } + if (upper !== void 0) { + return FDBKeyRange_default.upperBound(upper); + } +}; +var FDBCursor = class { + _gotValue = false; + _position = void 0; + // Key of previously returned record + _objectStorePosition = void 0; + _keyOnly = false; + _key = void 0; + _primaryKey = void 0; + constructor(source, range, direction = "next", request, keyOnly = false) { + this._range = range; + this._source = source; + this._direction = direction; + this._request = request; + this._keyOnly = keyOnly; + } + // Read only properties + get source() { + return this._source; + } + set source(val) { + } + get request() { + return this._request; + } + set request(val) { + } + get direction() { + return this._direction; + } + set direction(val) { + } + get key() { + return this._key; + } + set key(val) { + } + get primaryKey() { + return this._primaryKey; + } + set primaryKey(val) { + } + // https://w3c.github.io/IndexedDB/#iterate-a-cursor + _iterate(key, primaryKey) { + const sourceIsObjectStore = this.source instanceof FDBObjectStore_default; + const records = this.source instanceof FDBObjectStore_default ? this.source._rawObjectStore.records : this.source._rawIndex.records; + let foundRecord; + if (this.direction === "next") { + const range = makeKeyRange(this._range, [key, this._position], []); + for (const record of records.values(range)) { + const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0; + const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0; + if (key !== void 0) { + if (cmpResultKey === -1) { + continue; + } + } + if (primaryKey !== void 0) { + if (cmpResultKey === -1) { + continue; + } + const cmpResultPrimaryKey = cmp_default(record.value, primaryKey); + if (cmpResultKey === 0 && cmpResultPrimaryKey === -1) { + continue; + } + } + if (this._position !== void 0 && sourceIsObjectStore) { + if (cmpResultPosition !== 1) { + continue; + } + } + if (this._position !== void 0 && !sourceIsObjectStore) { + if (cmpResultPosition === -1) { + continue; + } + if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== 1) { + continue; + } + } + if (this._range !== void 0) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "nextunique") { + const range = makeKeyRange(this._range, [key, this._position], []); + for (const record of records.values(range)) { + if (key !== void 0) { + if (cmp_default(record.key, key) === -1) { + continue; + } + } + if (this._position !== void 0) { + if (cmp_default(record.key, this._position) !== 1) { + continue; + } + } + if (this._range !== void 0) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "prev") { + const range = makeKeyRange(this._range, [], [key, this._position]); + for (const record of records.values(range, "prev")) { + const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0; + const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0; + if (key !== void 0) { + if (cmpResultKey === 1) { + continue; + } + } + if (primaryKey !== void 0) { + if (cmpResultKey === 1) { + continue; + } + const cmpResultPrimaryKey = cmp_default(record.value, primaryKey); + if (cmpResultKey === 0 && cmpResultPrimaryKey === 1) { + continue; + } + } + if (this._position !== void 0 && sourceIsObjectStore) { + if (cmpResultPosition !== -1) { + continue; + } + } + if (this._position !== void 0 && !sourceIsObjectStore) { + if (cmpResultPosition === 1) { + continue; + } + if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== -1) { + continue; + } + } + if (this._range !== void 0) { + if (!this._range.includes(record.key)) { + continue; + } + } + foundRecord = record; + break; + } + } else if (this.direction === "prevunique") { + let tempRecord; + const range = makeKeyRange(this._range, [], [key, this._position]); + for (const record of records.values(range, "prev")) { + if (key !== void 0) { + if (cmp_default(record.key, key) === 1) { + continue; + } + } + if (this._position !== void 0) { + if (cmp_default(record.key, this._position) !== -1) { + continue; + } + } + if (this._range !== void 0) { + if (!this._range.includes(record.key)) { + continue; + } + } + tempRecord = record; + break; + } + if (tempRecord) { + foundRecord = records.get(tempRecord.key); + } + } + let result; + if (!foundRecord) { + this._key = void 0; + if (!sourceIsObjectStore) { + this._objectStorePosition = void 0; + } + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + this.value = void 0; + } + result = null; + } else { + this._position = foundRecord.key; + if (!sourceIsObjectStore) { + this._objectStorePosition = foundRecord.value; + } + this._key = foundRecord.key; + if (sourceIsObjectStore) { + this._primaryKey = structuredClone(foundRecord.key); + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + this.value = structuredClone(foundRecord.value); + } + } else { + this._primaryKey = structuredClone(foundRecord.value); + if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") { + if (this.source instanceof FDBObjectStore_default) { + throw new Error("This should never happen"); + } + const value = this.source.objectStore._rawObjectStore.getValue(foundRecord.value); + this.value = structuredClone(value); + } + } + this._gotValue = true; + result = this; + } + return result; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-update-IDBRequest-any-value + update(value) { + if (value === void 0) { + throw new TypeError(); + } + const effectiveObjectStore = getEffectiveObjectStore(this); + const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue || !Object.hasOwn(this, "value")) { + throw new InvalidStateError(); + } + const clone = cloneValueForInsertion(value, transaction); + if (effectiveObjectStore.keyPath !== null) { + let tempKey; + try { + tempKey = extractKey_default(effectiveObjectStore.keyPath, clone).key; + } catch (err) { + } + if (cmp_default(tempKey, effectiveKey) !== 0) { + throw new DataError(); + } + } + const record = { + key: effectiveKey, + value: clone + }; + return transaction._execRequestAsync({ + operation: effectiveObjectStore._rawObjectStore.storeRecord.bind(effectiveObjectStore._rawObjectStore, record, false, transaction._rollbackLog), + source: this + }); + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-advance-void-unsigned-long-count + advance(count) { + if (!Number.isInteger(count) || count <= 0) { + throw new TypeError(); + } + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue) { + throw new InvalidStateError(); + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: () => { + let result; + for (let i = 0; i < count; i++) { + result = this._iterate(); + if (!result) { + break; + } + } + return result; + }, + request: this._request, + source: this.source + }); + this._gotValue = false; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-continue-void-any-key + continue(key) { + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue) { + throw new InvalidStateError(); + } + if (key !== void 0) { + key = valueToKey_default(key); + const cmpResult = cmp_default(key, this._position); + if (cmpResult <= 0 && (this.direction === "next" || this.direction === "nextunique") || cmpResult >= 0 && (this.direction === "prev" || this.direction === "prevunique")) { + throw new DataError(); + } + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: this._iterate.bind(this, key), + request: this._request, + source: this.source + }); + this._gotValue = false; + } + // hthttps://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey + continuePrimaryKey(key, primaryKey) { + const effectiveObjectStore = getEffectiveObjectStore(this); + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (this.source instanceof FDBObjectStore_default || this.direction !== "next" && this.direction !== "prev") { + throw new InvalidAccessError(); + } + if (!this._gotValue) { + throw new InvalidStateError(); + } + if (key === void 0 || primaryKey === void 0) { + throw new DataError(); + } + key = valueToKey_default(key); + const cmpResult = cmp_default(key, this._position); + if (cmpResult === -1 && this.direction === "next" || cmpResult === 1 && this.direction === "prev") { + throw new DataError(); + } + const cmpResult2 = cmp_default(primaryKey, this._objectStorePosition); + if (cmpResult === 0) { + if (cmpResult2 <= 0 && this.direction === "next" || cmpResult2 >= 0 && this.direction === "prev") { + throw new DataError(); + } + } + if (this._request) { + this._request.readyState = "pending"; + } + transaction._execRequestAsync({ + operation: this._iterate.bind(this, key, primaryKey), + request: this._request, + source: this.source + }); + this._gotValue = false; + } + delete() { + const effectiveObjectStore = getEffectiveObjectStore(this); + const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position; + const transaction = effectiveObjectStore.transaction; + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (effectiveObjectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) { + throw new InvalidStateError(); + } + if (!this._gotValue || !Object.hasOwn(this, "value")) { + throw new InvalidStateError(); + } + return transaction._execRequestAsync({ + operation: effectiveObjectStore._rawObjectStore.deleteRecord.bind(effectiveObjectStore._rawObjectStore, effectiveKey, transaction._rollbackLog), + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBCursor"; + } +}; +var FDBCursor_default = FDBCursor; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBCursorWithValue.js +var FDBCursorWithValue = class extends FDBCursor_default { + value = void 0; + constructor(source, range, direction, request) { + super(source, range, direction, request); + } + get [Symbol.toStringTag]() { + return "IDBCursorWithValue"; + } +}; +var FDBCursorWithValue_default = FDBCursorWithValue; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeEventTarget.js +var stopped = (event, listener) => { + return event.immediatePropagationStopped || event.eventPhase === event.CAPTURING_PHASE && listener.capture === false || event.eventPhase === event.BUBBLING_PHASE && listener.capture === true; +}; +var invokeEventListeners = (event, obj) => { + event.currentTarget = obj; + const errors = []; + const invoke = (callbackOrObject) => { + try { + const callback2 = typeof callbackOrObject === "function" ? callbackOrObject : callbackOrObject.handleEvent; + callback2.call(event.currentTarget, event); + } catch (err) { + errors.push(err); + } + }; + for (const listener of obj.listeners.slice()) { + if (event.type !== listener.type || stopped(event, listener)) { + continue; + } + invoke(listener.callback); + } + const typeToProp = { + abort: "onabort", + blocked: "onblocked", + close: "onclose", + complete: "oncomplete", + error: "onerror", + success: "onsuccess", + upgradeneeded: "onupgradeneeded", + versionchange: "onversionchange" + }; + const prop = typeToProp[event.type]; + if (prop === void 0) { + throw new Error(`Unknown event type: "${event.type}"`); + } + const callback = event.currentTarget[prop]; + if (callback) { + const listener = { + callback, + capture: false, + type: event.type + }; + if (!stopped(event, listener)) { + invoke(listener.callback); + } + } + if (errors.length) { + throw new AggregateError(errors); + } +}; +var FakeEventTarget = class { + listeners = []; + // These will be overridden in individual subclasses and made not readonly + addEventListener(type, callback, options) { + const capture = !!(typeof options === "object" && options ? options.capture : options); + this.listeners.push({ + callback, + capture, + type + }); + } + removeEventListener(type, callback, options) { + const capture = !!(typeof options === "object" && options ? options.capture : options); + const i = this.listeners.findIndex((listener) => { + return listener.type === type && listener.callback === callback && listener.capture === capture; + }); + this.listeners.splice(i, 1); + } + // http://www.w3.org/TR/dom/#dispatching-events + dispatchEvent(event) { + if (event.dispatched || !event.initialized) { + throw new InvalidStateError("The object is in an invalid state."); + } + event.isTrusted = false; + event.dispatched = true; + event.target = this; + event.eventPhase = event.CAPTURING_PHASE; + for (const obj of event.eventPath) { + if (!event.propagationStopped) { + invokeEventListeners(event, obj); + } + } + event.eventPhase = event.AT_TARGET; + if (!event.propagationStopped) { + invokeEventListeners(event, event.target); + } + if (event.bubbles) { + event.eventPath.reverse(); + event.eventPhase = event.BUBBLING_PHASE; + for (const obj of event.eventPath) { + if (!event.propagationStopped) { + invokeEventListeners(event, obj); + } + } + } + event.dispatched = false; + event.eventPhase = event.NONE; + event.currentTarget = null; + if (event.canceled) { + return false; + } + return true; + } +}; +var FakeEventTarget_default = FakeEventTarget; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBRequest.js +var FDBRequest = class extends FakeEventTarget_default { + _result = null; + _error = null; + source = null; + transaction = null; + readyState = "pending"; + onsuccess = null; + onerror = null; + get error() { + if (this.readyState === "pending") { + throw new InvalidStateError(); + } + return this._error; + } + set error(value) { + this._error = value; + } + get result() { + if (this.readyState === "pending") { + throw new InvalidStateError(); + } + return this._result; + } + set result(value) { + this._result = value; + } + get [Symbol.toStringTag]() { + return "IDBRequest"; + } +}; +var FDBRequest_default = FDBRequest; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeDOMStringList.js +var FakeDOMStringList = class { + constructor(...values) { + this._values = values; + for (let i = 0; i < values.length; i++) { + this[i] = values[i]; + } + } + contains(value) { + return this._values.includes(value); + } + item(i) { + if (i < 0 || i >= this._values.length) { + return null; + } + return this._values[i]; + } + get length() { + return this._values.length; + } + [Symbol.iterator]() { + return this._values[Symbol.iterator](); + } + // Handled by proxy + // Used internally, should not be used by others. I could maybe get rid of these and replace rather than mutate, but too lazy to check the spec. + _push(...values) { + for (let i = 0; i < values.length; i++) { + this[this._values.length + i] = values[i]; + } + this._values.push(...values); + } + _sort(...values) { + this._values.sort(...values); + for (let i = 0; i < this._values.length; i++) { + this[i] = this._values[i]; + } + return this; + } +}; +var FakeDOMStringList_default = FakeDOMStringList; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/valueToKeyRange.js +var valueToKeyRange = (value, nullDisallowedFlag = false) => { + if (value instanceof FDBKeyRange_default) { + return value; + } + if (value === null || value === void 0) { + if (nullDisallowedFlag) { + throw new DataError(); + } + return new FDBKeyRange_default(void 0, void 0, false, false); + } + const key = valueToKey_default(value); + return FDBKeyRange_default.only(key); +}; +var valueToKeyRange_default = valueToKeyRange; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/getKeyPath.js +var convertKey = (key) => typeof key === "object" && key ? key + "" : key; +function getKeyPath(keyPath) { + return Array.isArray(keyPath) ? keyPath.map(convertKey) : convertKey(keyPath); +} + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/isPotentiallyValidKeyRange.js +var isPotentiallyValidKeyRange = (value) => { + if (value instanceof FDBKeyRange_default) { + return true; + } + const key = valueToKeyWithoutThrowing_default(value); + return key !== INVALID_TYPE; +}; +var isPotentiallyValidKeyRange_default = isPotentiallyValidKeyRange; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/enforceRange.js +var enforceRange = (num, type) => { + const min = 0; + const max = type === "unsigned long" ? 4294967295 : 9007199254740991; + if (isNaN(num) || num < min || num > max) { + throw new TypeError(); + } + if (num >= 0) { + return Math.floor(num); + } +}; +var enforceRange_default = enforceRange; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/extractGetAllOptions.js +var extractGetAllOptions = (queryOrOptions, count, numArguments) => { + let query; + let direction; + if (queryOrOptions === void 0 || queryOrOptions === null || isPotentiallyValidKeyRange_default(queryOrOptions)) { + query = queryOrOptions; + if (numArguments > 1 && count !== void 0) { + count = enforceRange_default(count, "unsigned long"); + } + } else { + const getAllOptions = queryOrOptions; + if (getAllOptions.query !== void 0) { + query = getAllOptions.query; + } + if (getAllOptions.count !== void 0) { + count = enforceRange_default(getAllOptions.count, "unsigned long"); + } + if (getAllOptions.direction !== void 0) { + direction = getAllOptions.direction; + } + } + return { + query, + count, + direction + }; +}; +var extractGetAllOptions_default = extractGetAllOptions; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBIndex.js +var confirmActiveTransaction = (index) => { + if (index._rawIndex.deleted || index.objectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (index.objectStore.transaction._state !== "active") { + throw new TransactionInactiveError(); + } +}; +var FDBIndex = class { + constructor(objectStore, rawIndex) { + this._rawIndex = rawIndex; + this._name = rawIndex.name; + this.objectStore = objectStore; + this.keyPath = getKeyPath(rawIndex.keyPath); + this.multiEntry = rawIndex.multiEntry; + this.unique = rawIndex.unique; + } + get name() { + return this._name; + } + // https://w3c.github.io/IndexedDB/#dom-idbindex-name + set name(name) { + const transaction = this.objectStore.transaction; + if (!transaction.db._runningVersionchangeTransaction) { + throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); + } + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + if (this._rawIndex.deleted || this.objectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + name = String(name); + if (name === this._name) { + return; + } + if (this.objectStore.indexNames.contains(name)) { + throw new ConstraintError(); + } + const oldName = this._name; + const oldIndexNames = [...this.objectStore.indexNames]; + this._name = name; + this._rawIndex.name = name; + this.objectStore._indexesCache.delete(oldName); + this.objectStore._indexesCache.set(name, this); + this.objectStore._rawObjectStore.rawIndexes.delete(oldName); + this.objectStore._rawObjectStore.rawIndexes.set(name, this._rawIndex); + this.objectStore.indexNames = new FakeDOMStringList_default(...Array.from(this.objectStore._rawObjectStore.rawIndexes.keys()).filter((indexName) => { + const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName); + return index && !index.deleted; + }).sort()); + if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) { + transaction._rollbackLog.push(() => { + this._name = oldName; + this._rawIndex.name = oldName; + this.objectStore._indexesCache.delete(name); + this.objectStore._indexesCache.set(oldName, this); + this.objectStore._rawObjectStore.rawIndexes.delete(name); + this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex); + this.objectStore.indexNames = new FakeDOMStringList_default(...oldIndexNames); + }); + } + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction + openCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = void 0; + } + if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { + range = FDBKeyRange_default.only(valueToKey_default(range)); + } + const request = new FDBRequest_default(); + request.source = this; + request.transaction = this.objectStore.transaction; + const cursor = new FDBCursorWithValue_default(this, range, direction, request); + return this.objectStore.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openKeyCursor-IDBRequest-any-range-IDBCursorDirection-direction + openKeyCursor(range, direction) { + confirmActiveTransaction(this); + if (range === null) { + range = void 0; + } + if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { + range = FDBKeyRange_default.only(valueToKey_default(range)); + } + const request = new FDBRequest_default(); + request.source = this; + request.transaction = this.objectStore.transaction; + const cursor = new FDBCursor_default(this, range, direction, request, true); + return this.objectStore.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + get(key) { + confirmActiveTransaction(this); + if (!(key instanceof FDBKeyRange_default)) { + key = valueToKey_default(key); + } + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getValue.bind(this._rawIndex, key), + source: this + }); + } + // http://w3c.github.io/IndexedDB/#dom-idbindex-getall + getAll(queryOrOptions, count) { + const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = valueToKeyRange_default(options.query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllValues.bind(this._rawIndex, range, options.count, options.direction), + source: this + }); + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-getKey-IDBRequest-any-key + getKey(key) { + confirmActiveTransaction(this); + if (!(key instanceof FDBKeyRange_default)) { + key = valueToKey_default(key); + } + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getKey.bind(this._rawIndex, key), + source: this + }); + } + // http://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys + getAllKeys(queryOrOptions, count) { + const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); + confirmActiveTransaction(this); + const range = valueToKeyRange_default(options.query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllKeys.bind(this._rawIndex, range, options.count, options.direction), + source: this + }); + } + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(options) { + let query; + let count; + let direction; + if (options !== void 0) { + if (options.query !== void 0) { + query = options.query; + } + if (options.count !== void 0) { + count = enforceRange_default(options.count, "unsigned long"); + } + if (options.direction !== void 0) { + direction = options.direction; + } + } + confirmActiveTransaction(this); + const range = valueToKeyRange_default(query); + return this.objectStore.transaction._execRequestAsync({ + operation: this._rawIndex.getAllRecords.bind(this._rawIndex, range, count, direction), + source: this + }); + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-count-IDBRequest-any-key + count(key) { + confirmActiveTransaction(this); + if (key === null) { + key = void 0; + } + if (key !== void 0 && !(key instanceof FDBKeyRange_default)) { + key = FDBKeyRange_default.only(valueToKey_default(key)); + } + return this.objectStore.transaction._execRequestAsync({ + operation: () => { + return this._rawIndex.count(key); + }, + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBIndex"; + } +}; +var FDBIndex_default = FDBIndex; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/canInjectKey.js +var canInjectKey = (keyPath, value) => { + if (Array.isArray(keyPath)) { + throw new Error("The key paths used in this section are always strings and never sequences, since it is not possible to create a object store which has a key generator and also has a key path that is a sequence."); + } + const identifiers = keyPath.split("."); + if (identifiers.length === 0) { + throw new Error("Assert: identifiers is not empty"); + } + identifiers.pop(); + for (const identifier of identifiers) { + if (typeof value !== "object" && !Array.isArray(value)) { + return false; + } + const hop = Object.hasOwn(value, identifier); + if (!hop) { + return true; + } + value = value[identifier]; + } + return typeof value === "object" || Array.isArray(value); +}; +var canInjectKey_default = canInjectKey; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBRecord.js +var FDBRecord = class { + constructor(key, primaryKey, value) { + this._key = key; + this._primaryKey = primaryKey; + this._value = value; + } + get key() { + return this._key; + } + set key(_) { + } + get primaryKey() { + return this._primaryKey; + } + set primaryKey(_) { + } + get value() { + return this._value; + } + set value(_) { + } + get [Symbol.toStringTag]() { + return "IDBRecord"; + } +}; +var FDBRecord_default = FDBRecord; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js +var MAX_TOMBSTONE_FACTOR = 2 / 3; +var EVERYTHING_KEY_RANGE = new FDBKeyRange_default(void 0, void 0, false, false); +var BinarySearchTree = class { + _numTombstones = 0; + _numNodes = 0; + /** + * + * @param keysAreUnique - whether keys can be unique, and thus whether we cn skip checking `record.value` when + * comparing. This is basically used to distinguish ObjectStores (where the value is the entire object, not used + * as a key) from non-unique Indexes (where both the key and the value are meaningful keys used for sorting) + */ + constructor(keysAreUnique) { + this._keysAreUnique = !!keysAreUnique; + } + size() { + return this._numNodes - this._numTombstones; + } + get(record) { + return this._getByComparator(this._root, (otherRecord) => this._compare(record, otherRecord)); + } + contains(record) { + return !!this.get(record); + } + _compare(a, b) { + const keyComparison = cmp_default(a.key, b.key); + if (keyComparison !== 0) { + return keyComparison; + } + return this._keysAreUnique ? 0 : cmp_default(a.value, b.value); + } + _getByComparator(node, comparator) { + let current = node; + while (current) { + const comparison = comparator(current.record); + if (comparison < 0) { + current = current.left; + } else if (comparison > 0) { + current = current.right; + } else { + return current.record; + } + } + } + /** + * Put a new record, and return the overwritten record if an overwrite occurred. + * @param record + * @param noOverwrite - throw a ConstraintError in case of overwrite + */ + put(record, noOverwrite = false) { + if (!this._root) { + this._root = { + record, + left: void 0, + right: void 0, + parent: void 0, + deleted: false, + // the root is always black in a red-black tree + red: false + }; + this._numNodes++; + return; + } + return this._put(this._root, record, noOverwrite); + } + _put(node, record, noOverwrite) { + const comparison = this._compare(record, node.record); + if (comparison < 0) { + if (node.left) { + return this._put(node.left, record, noOverwrite); + } else { + node.left = { + record, + left: void 0, + right: void 0, + parent: node, + deleted: false, + red: true + }; + this._onNewNodeInserted(node.left); + } + } else if (comparison > 0) { + if (node.right) { + return this._put(node.right, record, noOverwrite); + } else { + node.right = { + record, + left: void 0, + right: void 0, + parent: node, + deleted: false, + red: true + }; + this._onNewNodeInserted(node.right); + } + } else if (node.deleted) { + node.deleted = false; + node.record = record; + this._numTombstones--; + } else if (noOverwrite) { + throw new ConstraintError(); + } else { + const overwrittenRecord = node.record; + node.record = record; + return overwrittenRecord; + } + } + delete(record) { + if (!this._root) { + return; + } + this._delete(this._root, record); + if (this._numTombstones > this._numNodes * MAX_TOMBSTONE_FACTOR) { + const records = [...this.getAllRecords()]; + this._root = this._rebuild(records, void 0, false); + this._numNodes = records.length; + this._numTombstones = 0; + } + } + _delete(node, record) { + if (!node) { + return; + } + const comparison = this._compare(record, node.record); + if (comparison < 0) { + this._delete(node.left, record); + } else if (comparison > 0) { + this._delete(node.right, record); + } else if (!node.deleted) { + this._numTombstones++; + node.deleted = true; + } + } + *getAllRecords(descending = false) { + yield* this.getRecords(EVERYTHING_KEY_RANGE, descending); + } + *getRecords(keyRange, descending = false) { + yield* this._getRecordsForNode(this._root, keyRange, descending); + } + *_getRecordsForNode(node, keyRange, descending = false) { + if (!node) { + return; + } + yield* this._findRecords(node, keyRange, descending); + } + *_findRecords(node, keyRange, descending = false) { + const { + lower, + upper, + lowerOpen, + upperOpen + } = keyRange; + const { + record: { + key + } + } = node; + const lowerComparison = lower === void 0 ? -1 : cmp_default(lower, key); + const upperComparison = upper === void 0 ? 1 : cmp_default(upper, key); + const moreLeft = this._keysAreUnique ? lowerComparison < 0 : lowerComparison <= 0; + const moreRight = this._keysAreUnique ? upperComparison > 0 : upperComparison >= 0; + const moreStart = descending ? moreRight : moreLeft; + const moreEnd = descending ? moreLeft : moreRight; + const start = descending ? "right" : "left"; + const end = descending ? "left" : "right"; + const lowerMatches = lowerOpen ? lowerComparison < 0 : lowerComparison <= 0; + const upperMatches = upperOpen ? upperComparison > 0 : upperComparison >= 0; + if (moreStart && node[start]) { + yield* this._findRecords(node[start], keyRange, descending); + } + if (lowerMatches && upperMatches && !node.deleted) { + yield node.record; + } + if (moreEnd && node[end]) { + yield* this._findRecords(node[end], keyRange, descending); + } + } + _onNewNodeInserted(newNode) { + this._numNodes++; + this._rebalanceTree(newNode); + } + // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion + _rebalanceTree(node) { + let parent = node.parent; + do { + if (!parent.red) { + return; + } + const grandparent = parent.parent; + if (!grandparent) { + parent.red = false; + return; + } + const parentIsRightChild = parent === grandparent.right; + const uncle = parentIsRightChild ? grandparent.left : grandparent.right; + if (!uncle || !uncle.red) { + if (node === (parentIsRightChild ? parent.left : parent.right)) { + this._rotateSubtree(parent, parentIsRightChild); + node = parent; + parent = parentIsRightChild ? grandparent.right : grandparent.left; + } + this._rotateSubtree(grandparent, !parentIsRightChild); + parent.red = false; + grandparent.red = true; + return; + } + parent.red = false; + uncle.red = false; + grandparent.red = true; + node = grandparent; + } while (node.parent ? parent = node.parent : false); + } + // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Implementation + _rotateSubtree(node, right) { + const parent = node.parent; + const newRoot = right ? node.left : node.right; + const newChild = right ? newRoot.right : newRoot.left; + node[right ? "left" : "right"] = newChild; + if (newChild) { + newChild.parent = node; + } + newRoot[right ? "right" : "left"] = node; + newRoot.parent = parent; + node.parent = newRoot; + if (parent) { + parent[node === parent.right ? "right" : "left"] = newRoot; + } else { + this._root = newRoot; + } + return newRoot; + } + // rebuild the whole tree from scratch, used to avoid too many deletion tombstones accumulating + _rebuild(records, parent, red) { + const { + length + } = records; + if (!length) { + return void 0; + } + const mid = length >>> 1; + const node = { + record: records[mid], + left: void 0, + right: void 0, + parent, + deleted: false, + red + }; + const left = this._rebuild(records.slice(0, mid), node, !red); + const right = this._rebuild(records.slice(mid + 1), node, !red); + node.left = left; + node.right = right; + return node; + } +}; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/RecordStore.js +var RecordStore = class { + constructor(keysAreUnique) { + this.keysAreUnique = keysAreUnique; + this.records = new BinarySearchTree(this.keysAreUnique); + } + get(key) { + const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); + return this.records.getRecords(range).next().value; + } + /** + * Put a new record, and return the overwritten record if an overwrite occurred. + * @param newRecord + * @param noOverwrite - throw a ConstraintError in case of overwrite + */ + put(newRecord, noOverwrite = false) { + return this.records.put(newRecord, noOverwrite); + } + delete(key) { + const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); + const deletedRecords = [...this.records.getRecords(range)]; + for (const record of deletedRecords) { + this.records.delete(record); + } + return deletedRecords; + } + deleteByValue(key) { + const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key); + const deletedRecords = []; + for (const record of this.records.getAllRecords()) { + if (range.includes(record.value)) { + this.records.delete(record); + deletedRecords.push(record); + } + } + return deletedRecords; + } + clear() { + const deletedRecords = [...this.records.getAllRecords()]; + this.records = new BinarySearchTree(this.keysAreUnique); + return deletedRecords; + } + values(range, direction = "next") { + const descending = direction === "prev" || direction === "prevunique"; + const records = range ? this.records.getRecords(range, descending) : this.records.getAllRecords(descending); + return { + [Symbol.iterator]: () => { + const next = () => { + return records.next(); + }; + if (direction === "next" || direction === "prev") { + return { + next + }; + } + if (direction === "nextunique") { + let previousValue = void 0; + return { + next: () => { + let current2 = next(); + while (!current2.done && previousValue !== void 0 && cmp_default(previousValue.key, current2.value.key) === 0) { + current2 = next(); + } + previousValue = current2.value; + return current2; + } + }; + } + let current = next(); + let nextResult = next(); + return { + next: () => { + while (!nextResult.done && cmp_default(current.value.key, nextResult.value.key) === 0) { + current = nextResult; + nextResult = next(); + } + const result = current; + current = nextResult; + nextResult = next(); + return result; + } + }; + } + }; + } + size() { + return this.records.size(); + } +}; +var RecordStore_default = RecordStore; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/Index.js +var Index = class { + deleted = false; + // Initialized should be used to decide whether to throw an error or abort the versionchange transaction when there is a + // constraint + initialized = false; + constructor(rawObjectStore, name, keyPath, multiEntry, unique) { + this.rawObjectStore = rawObjectStore; + this.name = name; + this.keyPath = keyPath; + this.multiEntry = multiEntry; + this.unique = unique; + this.records = new RecordStore_default(unique); + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-index + getKey(key) { + const record = this.records.get(key); + return record !== void 0 ? record.value : void 0; + } + // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index + getAllKeys(range, count, direction) { + if (count === void 0 || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#index-referenced-value-retrieval-operation + getValue(key) { + const record = this.records.get(key); + return record !== void 0 ? this.rawObjectStore.getValue(record.value) : void 0; + } + // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index + getAllValues(range, count, direction) { + if (count === void 0 || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(this.rawObjectStore.getValue(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + // https://www.w3.org/TR/IndexedDB/#dom-idbindex-getallrecords + getAllRecords(range, count, direction) { + if (count === void 0 || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(this.rawObjectStore.getKey(record.value)), this.rawObjectStore.getValue(record.value))); + if (records.length >= count) { + break; + } + } + return records; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store (step 7) + storeRecord(newRecord) { + let indexKey; + try { + indexKey = extractKey_default(this.keyPath, newRecord.value).key; + } catch (err) { + if (err.name === "DataError") { + return; + } + throw err; + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + try { + valueToKey_default(indexKey); + } catch (e) { + return; + } + } else { + const keep = []; + for (const part of indexKey) { + if (keep.indexOf(part) < 0) { + try { + keep.push(valueToKey_default(part)); + } catch (err) { + } + } + } + indexKey = keep; + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + if (this.unique) { + const existingRecord = this.records.get(indexKey); + if (existingRecord) { + throw new ConstraintError(); + } + } + } else { + if (this.unique) { + for (const individualIndexKey of indexKey) { + const existingRecord = this.records.get(individualIndexKey); + if (existingRecord) { + throw new ConstraintError(); + } + } + } + } + if (!this.multiEntry || !Array.isArray(indexKey)) { + this.records.put({ + key: indexKey, + value: newRecord.key + }); + } else { + for (const individualIndexKey of indexKey) { + this.records.put({ + key: individualIndexKey, + value: newRecord.key + }); + } + } + } + initialize(transaction) { + if (this.initialized) { + throw new Error("Index already initialized"); + } + transaction._execRequestAsync({ + operation: () => { + try { + for (const record of this.rawObjectStore.records.values()) { + this.storeRecord(record); + } + this.initialized = true; + } catch (err) { + transaction._abort(err.name); + } + }, + source: null + }); + } + count(range) { + let count = 0; + for (const record of this.records.values(range)) { + count += 1; + } + return count; + } +}; +var Index_default = Index; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/validateKeyPath.js +var validateKeyPath = (keyPath, parent) => { + if (keyPath !== void 0 && keyPath !== null && typeof keyPath !== "string" && keyPath.toString && (parent === "array" || !Array.isArray(keyPath))) { + keyPath = keyPath.toString(); + } + if (typeof keyPath === "string") { + if (keyPath === "" && parent !== "string") { + return; + } + try { + const validIdentifierRegex = ( + // eslint-disable-next-line no-misleading-character-class + /^(?:[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC])(?:[$0-9A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC])*$/ + ); + if (keyPath.length >= 1 && validIdentifierRegex.test(keyPath)) { + return; + } + } catch (err) { + throw new SyntaxError2(err.message); + } + if (keyPath.indexOf(" ") >= 0) { + throw new SyntaxError2("The keypath argument contains an invalid key path (no spaces allowed)."); + } + } + if (Array.isArray(keyPath) && keyPath.length > 0) { + if (parent) { + throw new SyntaxError2("The keypath argument contains an invalid key path (nested arrays)."); + } + for (const part of keyPath) { + validateKeyPath(part, "array"); + } + return; + } else if (typeof keyPath === "string" && keyPath.indexOf(".") >= 0) { + keyPath = keyPath.split("."); + for (const part of keyPath) { + validateKeyPath(part, "string"); + } + return; + } + throw new SyntaxError2(); +}; +var validateKeyPath_default = validateKeyPath; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBObjectStore.js +var confirmActiveTransaction2 = (objectStore) => { + if (objectStore._rawObjectStore.deleted) { + throw new InvalidStateError(); + } + if (objectStore.transaction._state !== "active") { + throw new TransactionInactiveError(); + } +}; +var buildRecordAddPut = (objectStore, value, key) => { + confirmActiveTransaction2(objectStore); + if (objectStore.transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (objectStore.keyPath !== null) { + if (key !== void 0) { + throw new DataError(); + } + } + const clone = cloneValueForInsertion(value, objectStore.transaction); + if (objectStore.keyPath !== null) { + const tempKey = extractKey_default(objectStore.keyPath, clone); + if (tempKey.type === "found") { + valueToKey_default(tempKey.key); + } else { + if (!objectStore._rawObjectStore.keyGenerator) { + throw new DataError(); + } else if (!canInjectKey_default(objectStore.keyPath, clone)) { + throw new DataError(); + } + } + } + if (objectStore.keyPath === null && objectStore._rawObjectStore.keyGenerator === null && key === void 0) { + throw new DataError(); + } + if (key !== void 0) { + key = valueToKey_default(key); + } + return { + key, + value: clone + }; +}; +var FDBObjectStore = class { + _indexesCache = /* @__PURE__ */ new Map(); + constructor(transaction, rawObjectStore) { + this._rawObjectStore = rawObjectStore; + this._name = rawObjectStore.name; + this.keyPath = getKeyPath(rawObjectStore.keyPath); + this.autoIncrement = rawObjectStore.autoIncrement; + this.transaction = transaction; + this.indexNames = new FakeDOMStringList_default(...Array.from(rawObjectStore.rawIndexes.keys()).sort()); + } + get name() { + return this._name; + } + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-name + set name(name) { + const transaction = this.transaction; + if (!transaction.db._runningVersionchangeTransaction) { + throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError(); + } + confirmActiveTransaction2(this); + name = String(name); + if (name === this._name) { + return; + } + if (this._rawObjectStore.rawDatabase.rawObjectStores.has(name)) { + throw new ConstraintError(); + } + const oldName = this._name; + const oldObjectStoreNames = [...transaction.db.objectStoreNames]; + this._name = name; + this._rawObjectStore.name = name; + this.transaction._objectStoresCache.delete(oldName); + this.transaction._objectStoresCache.set(name, this); + this._rawObjectStore.rawDatabase.rawObjectStores.delete(oldName); + this._rawObjectStore.rawDatabase.rawObjectStores.set(name, this._rawObjectStore); + transaction.db.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._rawObjectStore.rawDatabase.rawObjectStores.keys()).filter((objectStoreName) => { + const objectStore = this._rawObjectStore.rawDatabase.rawObjectStores.get(objectStoreName); + return objectStore && !objectStore.deleted; + }).sort()); + const oldScope = new Set(transaction._scope); + const oldTransactionObjectStoreNames = [...transaction.objectStoreNames]; + this.transaction._scope.delete(oldName); + transaction._scope.add(name); + transaction.objectStoreNames = new FakeDOMStringList_default(...Array.from(transaction._scope).sort()); + if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) { + transaction._rollbackLog.push(() => { + this._name = oldName; + this._rawObjectStore.name = oldName; + this.transaction._objectStoresCache.delete(name); + this.transaction._objectStoresCache.set(oldName, this); + this._rawObjectStore.rawDatabase.rawObjectStores.delete(name); + this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore); + transaction.db.objectStoreNames = new FakeDOMStringList_default(...oldObjectStoreNames); + transaction._scope = oldScope; + transaction.objectStoreNames = new FakeDOMStringList_default(...oldTransactionObjectStoreNames); + }); + } + } + put(value, key) { + if (arguments.length === 0) { + throw new TypeError(); + } + const record = buildRecordAddPut(this, value, key); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, false, this.transaction._rollbackLog), + source: this + }); + } + add(value, key) { + if (arguments.length === 0) { + throw new TypeError(); + } + const record = buildRecordAddPut(this, value, key); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, true, this.transaction._rollbackLog), + source: this + }); + } + delete(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction2(this); + if (this.transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + if (!(key instanceof FDBKeyRange_default)) { + key = valueToKey_default(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.deleteRecord.bind(this._rawObjectStore, key, this.transaction._rollbackLog), + source: this + }); + } + get(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction2(this); + if (!(key instanceof FDBKeyRange_default)) { + key = valueToKey_default(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getValue.bind(this._rawObjectStore, key), + source: this + }); + } + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall + getAll(queryOrOptions, count) { + const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); + confirmActiveTransaction2(this); + const range = valueToKeyRange_default(options.query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllValues.bind(this._rawObjectStore, range, options.count, options.direction), + source: this + }); + } + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey + getKey(key) { + if (arguments.length === 0) { + throw new TypeError(); + } + confirmActiveTransaction2(this); + if (!(key instanceof FDBKeyRange_default)) { + key = valueToKey_default(key); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getKey.bind(this._rawObjectStore, key), + source: this + }); + } + // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys + getAllKeys(queryOrOptions, count) { + const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length); + confirmActiveTransaction2(this); + const range = valueToKeyRange_default(options.query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllKeys.bind(this._rawObjectStore, range, options.count, options.direction), + source: this + }); + } + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(options) { + let query; + let count; + let direction; + if (options !== void 0) { + if (options.query !== void 0) { + query = options.query; + } + if (options.count !== void 0) { + count = enforceRange_default(options.count, "unsigned long"); + } + if (options.direction !== void 0) { + direction = options.direction; + } + } + confirmActiveTransaction2(this); + const range = valueToKeyRange_default(query); + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.getAllRecords.bind(this._rawObjectStore, range, count, direction), + source: this + }); + } + clear() { + confirmActiveTransaction2(this); + if (this.transaction.mode === "readonly") { + throw new ReadOnlyError(); + } + return this.transaction._execRequestAsync({ + operation: this._rawObjectStore.clear.bind(this._rawObjectStore, this.transaction._rollbackLog), + source: this + }); + } + openCursor(range, direction) { + confirmActiveTransaction2(this); + if (range === null) { + range = void 0; + } + if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { + range = FDBKeyRange_default.only(valueToKey_default(range)); + } + const request = new FDBRequest_default(); + request.source = this; + request.transaction = this.transaction; + const cursor = new FDBCursorWithValue_default(this, range, direction, request); + return this.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + openKeyCursor(range, direction) { + confirmActiveTransaction2(this); + if (range === null) { + range = void 0; + } + if (range !== void 0 && !(range instanceof FDBKeyRange_default)) { + range = FDBKeyRange_default.only(valueToKey_default(range)); + } + const request = new FDBRequest_default(); + request.source = this; + request.transaction = this.transaction; + const cursor = new FDBCursor_default(this, range, direction, request, true); + return this.transaction._execRequestAsync({ + operation: cursor._iterate.bind(cursor), + request, + source: this + }); + } + // tslint:-next-line max-line-length + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-createIndex-IDBIndex-DOMString-name-DOMString-sequence-DOMString--keyPath-IDBIndexParameters-optionalParameters + createIndex(name, keyPath, optionalParameters = {}) { + if (arguments.length < 2) { + throw new TypeError(); + } + const multiEntry = optionalParameters.multiEntry !== void 0 ? optionalParameters.multiEntry : false; + const unique = optionalParameters.unique !== void 0 ? optionalParameters.unique : false; + if (this.transaction.mode !== "versionchange") { + throw new InvalidStateError(); + } + confirmActiveTransaction2(this); + if (this.indexNames.contains(name)) { + throw new ConstraintError(); + } + validateKeyPath_default(keyPath); + if (Array.isArray(keyPath) && multiEntry) { + throw new InvalidAccessError(); + } + const indexNames = [...this.indexNames]; + const index = new Index_default(this._rawObjectStore, name, keyPath, multiEntry, unique); + this.indexNames._push(name); + this.indexNames._sort(); + this.transaction._createdIndexes.add(index); + this._rawObjectStore.rawIndexes.set(name, index); + index.initialize(this.transaction); + this.transaction._rollbackLog.push(() => { + index.deleted = true; + this.indexNames = new FakeDOMStringList_default(...indexNames); + this._rawObjectStore.rawIndexes.delete(index.name); + }); + return new FDBIndex_default(this, index); + } + // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index + index(name) { + if (arguments.length === 0) { + throw new TypeError(); + } + if (this._rawObjectStore.deleted || this.transaction._state === "finished") { + throw new InvalidStateError(); + } + const index = this._indexesCache.get(name); + if (index !== void 0) { + return index; + } + const rawIndex = this._rawObjectStore.rawIndexes.get(name); + if (!this.indexNames.contains(name) || rawIndex === void 0) { + throw new NotFoundError(); + } + const index2 = new FDBIndex_default(this, rawIndex); + this._indexesCache.set(name, index2); + return index2; + } + deleteIndex(name) { + if (arguments.length === 0) { + throw new TypeError(); + } + if (this.transaction.mode !== "versionchange") { + throw new InvalidStateError(); + } + confirmActiveTransaction2(this); + const rawIndex = this._rawObjectStore.rawIndexes.get(name); + if (rawIndex === void 0) { + throw new NotFoundError(); + } + this.transaction._rollbackLog.push(() => { + rawIndex.deleted = false; + this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex); + this.indexNames._push(rawIndex.name); + this.indexNames._sort(); + }); + this.indexNames = new FakeDOMStringList_default(...Array.from(this.indexNames).filter((indexName) => { + return indexName !== name; + })); + rawIndex.deleted = true; + this.transaction._execRequestAsync({ + operation: () => { + const rawIndex2 = this._rawObjectStore.rawIndexes.get(name); + if (rawIndex === rawIndex2) { + this._rawObjectStore.rawIndexes.delete(name); + } + }, + source: this + }); + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-count-IDBRequest-any-key + count(key) { + confirmActiveTransaction2(this); + if (key === null) { + key = void 0; + } + if (key !== void 0 && !(key instanceof FDBKeyRange_default)) { + key = FDBKeyRange_default.only(valueToKey_default(key)); + } + return this.transaction._execRequestAsync({ + operation: () => { + return this._rawObjectStore.count(key); + }, + source: this + }); + } + get [Symbol.toStringTag]() { + return "IDBObjectStore"; + } +}; +var FDBObjectStore_default = FDBObjectStore; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/FakeEvent.js +var Event = class { + eventPath = []; + NONE = 0; + CAPTURING_PHASE = 1; + AT_TARGET = 2; + BUBBLING_PHASE = 3; + // Flags + propagationStopped = false; + immediatePropagationStopped = false; + canceled = false; + initialized = true; + dispatched = false; + target = null; + currentTarget = null; + eventPhase = 0; + defaultPrevented = false; + isTrusted = false; + timeStamp = Date.now(); + constructor(type, eventInitDict = {}) { + this.type = type; + this.bubbles = eventInitDict.bubbles !== void 0 ? eventInitDict.bubbles : false; + this.cancelable = eventInitDict.cancelable !== void 0 ? eventInitDict.cancelable : false; + } + preventDefault() { + if (this.cancelable) { + this.canceled = true; + } + } + stopPropagation() { + this.propagationStopped = true; + } + stopImmediatePropagation() { + this.propagationStopped = true; + this.immediatePropagationStopped = true; + } +}; +var FakeEvent_default = Event; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/scheduling.js +function getSetImmediateFromJsdom() { + if (typeof navigator !== "undefined" && /jsdom/.test(navigator.userAgent)) { + const outerRealmFunctionConstructor = Node.constructor; + return new outerRealmFunctionConstructor("return setImmediate")(); + } else { + return void 0; + } +} +var schedulerPostTask = typeof scheduler !== "undefined" && ((fn) => scheduler.postTask(fn)); +var doSetTimeout = (fn) => setTimeout(fn, 0); +var queueTask = (fn) => { + const setImmediate2 = globalThis.setImmediate || getSetImmediateFromJsdom() || schedulerPostTask || doSetTimeout; + setImmediate2(fn); +}; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBTransaction.js +var prioritizedListenerTypes = ["error", "abort", "complete"]; +var FDBTransaction = class extends FakeEventTarget_default { + _state = "active"; + _started = false; + _rollbackLog = []; + _objectStoresCache = /* @__PURE__ */ new Map(); + _openRequest = null; + error = null; + onabort = null; + oncomplete = null; + onerror = null; + _prioritizedListeners = /* @__PURE__ */ new Map(); + _requests = []; + _createdIndexes = /* @__PURE__ */ new Set(); + _createdObjectStores = /* @__PURE__ */ new Set(); + constructor(storeNames, mode, durability, db2) { + super(); + this._scope = new Set(storeNames); + this.mode = mode; + this.durability = durability; + this.db = db2; + this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._scope).sort()); + for (const type of prioritizedListenerTypes) { + this.addEventListener(type, () => { + this._prioritizedListeners.get(type)?.(); + }); + } + } + // https://w3c.github.io/IndexedDB/#abort-transaction + _abort(errName) { + for (const f of this._rollbackLog.reverse()) { + f(); + } + if (errName !== null) { + const e = new DOMException(void 0, errName); + this.error = e; + } + for (const { + request + } of this._requests) { + if (request.readyState !== "done") { + request.readyState = "done"; + if (request.source) { + queueTask(() => { + request.result = void 0; + request.error = new AbortError(); + const event = new FakeEvent_default("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = [this.db, this]; + try { + request.dispatchEvent(event); + } catch (_err) { + if (this._state === "active") { + this._abort("AbortError"); + } + } + }); + } + } + } + queueTask(() => { + const isUpgradeTransaction = this.mode === "versionchange"; + if (isUpgradeTransaction) { + this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter((connection) => !connection._rawDatabase.transactions.includes(this)); + } + const event = new FakeEvent_default("abort", { + bubbles: true, + cancelable: false + }); + event.eventPath = [this.db]; + this.dispatchEvent(event); + if (isUpgradeTransaction) { + const request = this._openRequest; + request.transaction = null; + request.result = void 0; + } + }); + this._state = "finished"; + } + abort() { + if (this._state === "committing" || this._state === "finished") { + throw new InvalidStateError(); + } + this._state = "active"; + this._abort(null); + } + // http://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore + objectStore(name) { + if (this._state !== "active") { + throw new InvalidStateError(); + } + const objectStore = this._objectStoresCache.get(name); + if (objectStore !== void 0) { + return objectStore; + } + const rawObjectStore = this.db._rawDatabase.rawObjectStores.get(name); + if (!this._scope.has(name) || rawObjectStore === void 0) { + throw new NotFoundError(); + } + const objectStore2 = new FDBObjectStore_default(this, rawObjectStore); + this._objectStoresCache.set(name, objectStore2); + return objectStore2; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-asynchronously-executing-a-request + _execRequestAsync(obj) { + const source = obj.source; + const operation = obj.operation; + let request = Object.hasOwn(obj, "request") ? obj.request : null; + if (this._state !== "active") { + throw new TransactionInactiveError(); + } + if (!request) { + if (!source) { + request = new FDBRequest_default(); + } else { + request = new FDBRequest_default(); + request.source = source; + request.transaction = source.transaction; + } + } + this._requests.push({ + operation, + request + }); + return request; + } + _start() { + this._started = true; + let operation; + let request; + while (this._requests.length > 0) { + const r = this._requests.shift(); + if (r && r.request.readyState !== "done") { + request = r.request; + operation = r.operation; + break; + } + } + if (request && operation) { + if (!request.source) { + operation(); + } else { + let defaultAction; + let event; + try { + const result = operation(); + request.readyState = "done"; + request.result = result; + request.error = void 0; + if (this._state === "inactive") { + this._state = "active"; + } + event = new FakeEvent_default("success", { + bubbles: false, + cancelable: false + }); + } catch (err) { + request.readyState = "done"; + request.result = void 0; + request.error = err; + if (this._state === "inactive") { + this._state = "active"; + } + event = new FakeEvent_default("error", { + bubbles: true, + cancelable: true + }); + defaultAction = this._abort.bind(this, err.name); + } + try { + event.eventPath = [this.db, this]; + request.dispatchEvent(event); + } catch (_err) { + if (this._state === "active") { + this._abort("AbortError"); + defaultAction = void 0; + } + } + if (!event.canceled) { + if (defaultAction) { + defaultAction(); + } + } + } + queueTask(this._start.bind(this)); + return; + } + if (this._state !== "finished") { + this._state = "finished"; + if (!this.error) { + const event = new FakeEvent_default("complete"); + this.dispatchEvent(event); + } + } + } + commit() { + if (this._state !== "active") { + throw new InvalidStateError(); + } + this._state = "committing"; + } + get [Symbol.toStringTag]() { + return "IDBTransaction"; + } +}; +var FDBTransaction_default = FDBTransaction; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/KeyGenerator.js +var MAX_KEY = 9007199254740992; +var KeyGenerator = class { + // This is kind of wrong. Should start at 1 and increment only after record is saved + num = 0; + next() { + if (this.num >= MAX_KEY) { + throw new ConstraintError(); + } + this.num += 1; + return this.num; + } + // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator + setIfLarger(num) { + const value = Math.floor(Math.min(num, MAX_KEY)) - 1; + if (value >= this.num) { + this.num = value + 1; + } + } +}; +var KeyGenerator_default = KeyGenerator; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/ObjectStore.js +var ObjectStore = class { + deleted = false; + records = new RecordStore_default(true); + rawIndexes = /* @__PURE__ */ new Map(); + constructor(rawDatabase, name, keyPath, autoIncrement) { + this.rawDatabase = rawDatabase; + this.keyGenerator = autoIncrement === true ? new KeyGenerator_default() : null; + this.deleted = false; + this.name = name; + this.keyPath = keyPath; + this.autoIncrement = autoIncrement; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store + getKey(key) { + const record = this.records.get(key); + return record !== void 0 ? structuredClone(record.key) : void 0; + } + // http://w3c.github.io/IndexedDB/#retrieve-multiple-keys-from-an-object-store + getAllKeys(range, count, direction) { + if (count === void 0 || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.key)); + if (records.length >= count) { + break; + } + } + return records; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store + getValue(key) { + const record = this.records.get(key); + return record !== void 0 ? structuredClone(record.value) : void 0; + } + // http://w3c.github.io/IndexedDB/#retrieve-multiple-values-from-an-object-store + getAllValues(range, count, direction) { + if (count === void 0 || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(structuredClone(record.value)); + if (records.length >= count) { + break; + } + } + return records; + } + // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords + getAllRecords(range, count, direction) { + if (count === void 0 || count === 0) { + count = Infinity; + } + const records = []; + for (const record of this.records.values(range, direction)) { + records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(record.key), structuredClone(record.value))); + if (records.length >= count) { + break; + } + } + return records; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store + storeRecord(newRecord, noOverwrite, rollbackLog) { + if (this.keyPath !== null) { + const key = extractKey_default(this.keyPath, newRecord.value).key; + if (key !== void 0) { + newRecord.key = key; + } + } + const rollbackLogForThisOperation = []; + if (this.keyGenerator !== null && newRecord.key === void 0) { + let rolledBack2 = false; + const keyGeneratorBefore = this.keyGenerator.num; + const rollbackKeyGenerator = () => { + if (rolledBack2) { + return; + } + rolledBack2 = true; + if (this.keyGenerator) { + this.keyGenerator.num = keyGeneratorBefore; + } + }; + rollbackLogForThisOperation.push(rollbackKeyGenerator); + if (rollbackLog) { + rollbackLog.push(rollbackKeyGenerator); + } + newRecord.key = this.keyGenerator.next(); + if (this.keyPath !== null) { + if (Array.isArray(this.keyPath)) { + throw new Error("Cannot have an array key path in an object store with a key generator"); + } + let remainingKeyPath = this.keyPath; + let object = newRecord.value; + let identifier; + let i = 0; + while (i >= 0) { + if (typeof object !== "object") { + throw new DataError(); + } + i = remainingKeyPath.indexOf("."); + if (i >= 0) { + identifier = remainingKeyPath.slice(0, i); + remainingKeyPath = remainingKeyPath.slice(i + 1); + if (!Object.hasOwn(object, identifier)) { + Object.defineProperty(object, identifier, { + configurable: true, + enumerable: true, + writable: true, + value: {} + }); + } + object = object[identifier]; + } + } + identifier = remainingKeyPath; + Object.defineProperty(object, identifier, { + configurable: true, + enumerable: true, + writable: true, + value: newRecord.key + }); + } + } else if (this.keyGenerator !== null && typeof newRecord.key === "number") { + this.keyGenerator.setIfLarger(newRecord.key); + } + const existingRecord = this.records.put(newRecord, noOverwrite); + let rolledBack = false; + const rollbackStoreRecord = () => { + if (rolledBack) { + return; + } + rolledBack = true; + if (existingRecord) { + this.storeRecord(existingRecord, false); + } else { + this.deleteRecord(newRecord.key); + } + }; + rollbackLogForThisOperation.push(rollbackStoreRecord); + if (rollbackLog) { + rollbackLog.push(rollbackStoreRecord); + } + if (existingRecord) { + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.deleteByValue(newRecord.key); + } + } + try { + for (const rawIndex of this.rawIndexes.values()) { + if (rawIndex.initialized) { + rawIndex.storeRecord(newRecord); + } + } + } catch (err) { + if (err.name === "ConstraintError") { + for (const rollback of rollbackLogForThisOperation) { + rollback(); + } + } + throw err; + } + return newRecord.key; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-records-from-an-object-store + deleteRecord(key, rollbackLog) { + const deletedRecords = this.records.delete(key); + if (rollbackLog) { + for (const record of deletedRecords) { + rollbackLog.push(() => { + this.storeRecord(record, true); + }); + } + } + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.deleteByValue(key); + } + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-clearing-an-object-store + clear(rollbackLog) { + const deletedRecords = this.records.clear(); + if (rollbackLog) { + for (const record of deletedRecords) { + rollbackLog.push(() => { + this.storeRecord(record, true); + }); + } + } + for (const rawIndex of this.rawIndexes.values()) { + rawIndex.records.clear(); + } + } + count(range) { + if (range === void 0 || range.lower === void 0 && range.upper === void 0) { + return this.records.size(); + } + let count = 0; + for (const record of this.records.values(range)) { + count += 1; + } + return count; + } +}; +var ObjectStore_default = ObjectStore; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/closeConnection.js +var closeConnection = (connection, forced = false) => { + connection._closePending = true; + const transactionsComplete = connection._rawDatabase.transactions.every((transaction) => { + return transaction._state === "finished"; + }); + if (transactionsComplete) { + connection._closed = true; + connection._rawDatabase.connections = connection._rawDatabase.connections.filter((otherConnection) => { + return connection !== otherConnection; + }); + if (forced) { + const event = new FakeEvent_default("close", { + bubbles: false, + cancelable: false + }); + event.eventPath = []; + connection.dispatchEvent(event); + } + } else { + queueTask(() => { + closeConnection(connection, forced); + }); + } +}; +var closeConnection_default = closeConnection; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBDatabase.js +var confirmActiveVersionchangeTransaction = (database) => { + let transaction; + if (database._runningVersionchangeTransaction) { + transaction = database._rawDatabase.transactions.findLast((tx) => { + return tx.mode === "versionchange"; + }); + } + if (!transaction) { + throw new InvalidStateError(); + } + if (transaction._state !== "active") { + throw new TransactionInactiveError(); + } + return transaction; +}; +var FDBDatabase = class extends FakeEventTarget_default { + _closePending = false; + _closed = false; + _runningVersionchangeTransaction = false; + constructor(rawDatabase) { + super(); + this._rawDatabase = rawDatabase; + this._rawDatabase.connections.push(this); + this.name = rawDatabase.name; + this.version = rawDatabase.version; + this.objectStoreNames = new FakeDOMStringList_default(...Array.from(rawDatabase.rawObjectStores.keys()).sort()); + } + // http://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore + createObjectStore(name, options = {}) { + if (name === void 0) { + throw new TypeError(); + } + const transaction = confirmActiveVersionchangeTransaction(this); + const keyPath = options !== null && options.keyPath !== void 0 ? options.keyPath : null; + const autoIncrement = options !== null && options.autoIncrement !== void 0 ? options.autoIncrement : false; + if (keyPath !== null) { + validateKeyPath_default(keyPath); + } + if (this._rawDatabase.rawObjectStores.has(name)) { + throw new ConstraintError(); + } + if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) { + throw new InvalidAccessError(); + } + const objectStoreNames = [...this.objectStoreNames]; + const transactionObjectStoreNames = [...transaction.objectStoreNames]; + const rawObjectStore = new ObjectStore_default(this._rawDatabase, name, keyPath, autoIncrement); + this.objectStoreNames._push(name); + this.objectStoreNames._sort(); + transaction._scope.add(name); + transaction._createdObjectStores.add(rawObjectStore); + this._rawDatabase.rawObjectStores.set(name, rawObjectStore); + transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames); + transaction._rollbackLog.push(() => { + rawObjectStore.deleted = true; + this.objectStoreNames = new FakeDOMStringList_default(...objectStoreNames); + transaction.objectStoreNames = new FakeDOMStringList_default(...transactionObjectStoreNames); + transaction._scope.delete(rawObjectStore.name); + this._rawDatabase.rawObjectStores.delete(rawObjectStore.name); + }); + return transaction.objectStore(name); + } + // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore + deleteObjectStore(name) { + if (name === void 0) { + throw new TypeError(); + } + const transaction = confirmActiveVersionchangeTransaction(this); + const store = this._rawDatabase.rawObjectStores.get(name); + if (store === void 0) { + throw new NotFoundError(); + } + this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this.objectStoreNames).filter((objectStoreName) => { + return objectStoreName !== name; + })); + transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames); + const objectStore = transaction._objectStoresCache.get(name); + let prevIndexNames; + if (objectStore) { + prevIndexNames = [...objectStore.indexNames]; + objectStore.indexNames = new FakeDOMStringList_default(); + } + transaction._rollbackLog.push(() => { + store.deleted = false; + this._rawDatabase.rawObjectStores.set(store.name, store); + this.objectStoreNames._push(store.name); + transaction.objectStoreNames._push(store.name); + this.objectStoreNames._sort(); + if (objectStore && prevIndexNames) { + objectStore.indexNames = new FakeDOMStringList_default(...prevIndexNames); + } + }); + store.deleted = true; + this._rawDatabase.rawObjectStores.delete(name); + transaction._objectStoresCache.delete(name); + } + transaction(storeNames, mode, options) { + mode = mode !== void 0 ? mode : "readonly"; + if (mode !== "readonly" && mode !== "readwrite" && mode !== "versionchange") { + throw new TypeError("Invalid mode: " + mode); + } + const hasActiveVersionchange = this._rawDatabase.transactions.some((transaction) => { + return transaction._state === "active" && transaction.mode === "versionchange" && transaction.db === this; + }); + if (hasActiveVersionchange) { + throw new InvalidStateError(); + } + if (this._closePending) { + throw new InvalidStateError(); + } + if (!Array.isArray(storeNames)) { + storeNames = [storeNames]; + } + if (storeNames.length === 0 && mode !== "versionchange") { + throw new InvalidAccessError(); + } + for (const storeName of storeNames) { + if (!this.objectStoreNames.contains(storeName)) { + throw new NotFoundError("No objectStore named " + storeName + " in this database"); + } + } + const durability = options?.durability ?? "default"; + if (durability !== "default" && durability !== "strict" && durability !== "relaxed") { + throw new TypeError( + // based on Firefox's error message + `'${durability}' (value of 'durability' member of IDBTransactionOptions) is not a valid value for enumeration IDBTransactionDurability` + ); + } + const tx = new FDBTransaction_default(storeNames, mode, durability, this); + this._rawDatabase.transactions.push(tx); + this._rawDatabase.processTransactions(); + return tx; + } + close() { + closeConnection_default(this); + } + get [Symbol.toStringTag]() { + return "IDBDatabase"; + } +}; +var FDBDatabase_default = FDBDatabase; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBOpenDBRequest.js +var FDBOpenDBRequest = class extends FDBRequest_default { + onupgradeneeded = null; + onblocked = null; + get [Symbol.toStringTag]() { + return "IDBOpenDBRequest"; + } +}; +var FDBOpenDBRequest_default = FDBOpenDBRequest; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBVersionChangeEvent.js +var FDBVersionChangeEvent = class extends FakeEvent_default { + constructor(type, parameters = {}) { + super(type); + this.newVersion = parameters.newVersion !== void 0 ? parameters.newVersion : null; + this.oldVersion = parameters.oldVersion !== void 0 ? parameters.oldVersion : 0; + } + get [Symbol.toStringTag]() { + return "IDBVersionChangeEvent"; + } +}; +var FDBVersionChangeEvent_default = FDBVersionChangeEvent; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/intersection.js +function intersection(set1, set2) { + if ("intersection" in set1) { + return set1.intersection(set2); + } + return new Set([...set1].filter((item) => set2.has(item))); +} + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/Database.js +var Database = class { + transactions = []; + rawObjectStores = /* @__PURE__ */ new Map(); + connections = []; + constructor(name, version) { + this.name = name; + this.version = version; + this.processTransactions = this.processTransactions.bind(this); + } + processTransactions() { + queueTask(() => { + const running = this.transactions.filter((transaction) => transaction._started && transaction._state !== "finished"); + const waiting = this.transactions.filter((transaction) => !transaction._started && transaction._state !== "finished"); + const next = waiting.find((transaction, i) => { + const anyRunning = running.some((other) => !(transaction.mode === "readonly" && other.mode === "readonly") && intersection(other._scope, transaction._scope).size > 0); + if (anyRunning) { + return false; + } + const anyWaiting = waiting.slice(0, i).some((other) => intersection(other._scope, transaction._scope).size > 0); + return !anyWaiting; + }); + if (next) { + next.addEventListener("complete", this.processTransactions); + next.addEventListener("abort", this.processTransactions); + next._start(); + } + }); + } +}; +var Database_default = Database; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/lib/validateRequiredArguments.js +function validateRequiredArguments(numArguments, expectedNumArguments, methodName) { + if (numArguments < expectedNumArguments) { + throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} required, but only ${arguments.length} passed`); + } +} + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/FDBFactory.js +var runTaskInConnectionQueue = (connectionQueues, name, task) => { + const queue = connectionQueues.get(name) ?? Promise.resolve(); + connectionQueues.set(name, queue.then(task)); +}; +var waitForOthersClosedDelete = (databases, name, openDatabases, cb) => { + const anyOpen = openDatabases.some((openDatabase2) => { + return !openDatabase2._closed && !openDatabase2._closePending; + }); + if (anyOpen) { + queueTask(() => waitForOthersClosedDelete(databases, name, openDatabases, cb)); + return; + } + databases.delete(name); + cb(null); +}; +var deleteDatabase = (databases, connectionQueues, name, request, cb) => { + const deleteDBTask = () => { + return new Promise((resolve) => { + const db2 = databases.get(name); + const oldVersion = db2 !== void 0 ? db2.version : 0; + const onComplete = (err) => { + try { + if (err) { + cb(err); + } else { + cb(null, oldVersion); + } + } finally { + resolve(); + } + }; + try { + const db3 = databases.get(name); + if (db3 === void 0) { + onComplete(null); + return; + } + const openConnections = db3.connections.filter((connection) => { + return !connection._closed; + }); + for (const openDatabase2 of openConnections) { + if (!openDatabase2._closePending) { + queueTask(() => { + const event = new FDBVersionChangeEvent_default("versionchange", { + newVersion: null, + oldVersion: db3.version + }); + openDatabase2.dispatchEvent(event); + }); + } + } + queueTask(() => { + const anyOpen = openConnections.some((openDatabase3) => { + return !openDatabase3._closed && !openDatabase3._closePending; + }); + if (anyOpen) { + queueTask(() => { + const event = new FDBVersionChangeEvent_default("blocked", { + newVersion: null, + oldVersion: db3.version + }); + request.dispatchEvent(event); + }); + } + waitForOthersClosedDelete(databases, name, openConnections, onComplete); + }); + } catch (err) { + onComplete(err); + } + }); + }; + runTaskInConnectionQueue(connectionQueues, name, deleteDBTask); +}; +var runVersionchangeTransaction = (connection, version, request, cb) => { + connection._runningVersionchangeTransaction = true; + const oldVersion = connection._oldVersion = connection.version; + const openConnections = connection._rawDatabase.connections.filter((otherDatabase) => { + return connection !== otherDatabase; + }); + for (const openDatabase2 of openConnections) { + if (!openDatabase2._closed && !openDatabase2._closePending) { + queueTask(() => { + const event = new FDBVersionChangeEvent_default("versionchange", { + newVersion: version, + oldVersion + }); + openDatabase2.dispatchEvent(event); + }); + } + } + queueTask(() => { + const anyOpen = openConnections.some((openDatabase3) => { + return !openDatabase3._closed && !openDatabase3._closePending; + }); + if (anyOpen) { + queueTask(() => { + const event = new FDBVersionChangeEvent_default("blocked", { + newVersion: version, + oldVersion + }); + request.dispatchEvent(event); + }); + } + const waitForOthersClosed = () => { + const anyOpen2 = openConnections.some((openDatabase2) => { + return !openDatabase2._closed && !openDatabase2._closePending; + }); + if (anyOpen2) { + queueTask(waitForOthersClosed); + return; + } + connection._rawDatabase.version = version; + connection.version = version; + const transaction = connection.transaction(Array.from(connection.objectStoreNames), "versionchange"); + transaction._openRequest = request; + request.result = connection; + request.readyState = "done"; + request.transaction = transaction; + transaction._rollbackLog.push(() => { + connection._rawDatabase.version = oldVersion; + connection.version = oldVersion; + }); + transaction._state = "active"; + const event = new FDBVersionChangeEvent_default("upgradeneeded", { + newVersion: version, + oldVersion + }); + let didThrow = false; + try { + request.dispatchEvent(event); + } catch (_err) { + didThrow = true; + } + const concludeUpgrade = () => { + if (transaction._state === "active") { + transaction._state = "inactive"; + if (didThrow) { + transaction._abort("AbortError"); + } + } + }; + if (didThrow) { + concludeUpgrade(); + } else { + queueTask(concludeUpgrade); + } + transaction._prioritizedListeners.set("error", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = void 0; + }); + transaction._prioritizedListeners.set("abort", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = void 0; + queueTask(() => { + request.transaction = null; + cb(new AbortError()); + }); + }); + transaction._prioritizedListeners.set("complete", () => { + connection._runningVersionchangeTransaction = false; + connection._oldVersion = void 0; + queueTask(() => { + request.transaction = null; + if (connection._closePending) { + cb(new AbortError()); + } else { + cb(null); + } + }); + }); + }; + waitForOthersClosed(); + }); +}; +var openDatabase = (databases, connectionQueues, name, version, request, cb) => { + const openDBTask = () => { + return new Promise((resolve) => { + const onComplete = (err) => { + try { + if (err) { + cb(err); + } else { + cb(null, connection); + } + } finally { + resolve(); + } + }; + let db2 = databases.get(name); + if (db2 === void 0) { + db2 = new Database_default(name, 0); + databases.set(name, db2); + } + if (version === void 0) { + version = db2.version !== 0 ? db2.version : 1; + } + if (db2.version > version) { + return onComplete(new VersionError()); + } + const connection = new FDBDatabase_default(db2); + if (db2.version < version) { + runVersionchangeTransaction(connection, version, request, (err) => { + onComplete(err); + }); + } else { + onComplete(null); + } + }); + }; + runTaskInConnectionQueue(connectionQueues, name, openDBTask); +}; +var FDBFactory = class { + _databases = /* @__PURE__ */ new Map(); + // https://w3c.github.io/IndexedDB/#connection-queue + _connectionQueues = /* @__PURE__ */ new Map(); + // promise chain as lightweight FIFO task queue + // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp + cmp(first, second) { + validateRequiredArguments(arguments.length, 2, "IDBFactory.cmp"); + return cmp_default(first, second); + } + // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase + deleteDatabase(name) { + validateRequiredArguments(arguments.length, 1, "IDBFactory.deleteDatabase"); + const request = new FDBOpenDBRequest_default(); + request.source = null; + queueTask(() => { + deleteDatabase(this._databases, this._connectionQueues, name, request, (err, oldVersion) => { + if (err) { + request.error = new DOMException(err.message, err.name); + request.readyState = "done"; + const event = new FakeEvent_default("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = []; + request.dispatchEvent(event); + return; + } + request.result = void 0; + request.readyState = "done"; + const event2 = new FDBVersionChangeEvent_default("success", { + newVersion: null, + oldVersion + }); + request.dispatchEvent(event2); + }); + }); + return request; + } + // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version + open(name, version) { + validateRequiredArguments(arguments.length, 1, "IDBFactory.open"); + if (arguments.length > 1 && version !== void 0) { + version = enforceRange_default(version, "MAX_SAFE_INTEGER"); + } + if (version === 0) { + throw new TypeError("Database version cannot be 0"); + } + const request = new FDBOpenDBRequest_default(); + request.source = null; + queueTask(() => { + openDatabase(this._databases, this._connectionQueues, name, version, request, (err, connection) => { + if (err) { + request.result = void 0; + request.readyState = "done"; + request.error = new DOMException(err.message, err.name); + const event = new FakeEvent_default("error", { + bubbles: true, + cancelable: true + }); + event.eventPath = []; + request.dispatchEvent(event); + return; + } + request.result = connection; + request.readyState = "done"; + const event2 = new FakeEvent_default("success"); + event2.eventPath = []; + request.dispatchEvent(event2); + }); + }); + return request; + } + // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases + databases() { + return Promise.resolve(Array.from(this._databases.entries(), ([name, database]) => { + const activeVersionChangeConnection = database.connections.find((connection) => connection._runningVersionchangeTransaction); + const version = activeVersionChangeConnection ? activeVersionChangeConnection._oldVersion : database.version; + return { + name, + version + }; + }).filter(({ + version + }) => { + return version > 0; + })); + } + get [Symbol.toStringTag]() { + return "IDBFactory"; + } +}; +var FDBFactory_default = FDBFactory; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/build/esm/fakeIndexedDB.js +var fakeIndexedDB = new FDBFactory_default(); +var fakeIndexedDB_default = fakeIndexedDB; + +// intern-log/node_modules/.pnpm/fake-indexeddb@6.2.5/node_modules/fake-indexeddb/auto/index.mjs +var globalVar = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" ? self : typeof global !== "undefined" ? global : Function("return this;")(); +var createPropertyDescriptor = (value) => { + return { + value, + enumerable: false, + configurable: true, + writable: true + }; +}; +Object.defineProperties(globalVar, { + indexedDB: createPropertyDescriptor(fakeIndexedDB_default), + IDBCursor: createPropertyDescriptor(FDBCursor_default), + IDBCursorWithValue: createPropertyDescriptor(FDBCursorWithValue_default), + IDBDatabase: createPropertyDescriptor(FDBDatabase_default), + IDBFactory: createPropertyDescriptor(FDBFactory_default), + IDBIndex: createPropertyDescriptor(FDBIndex_default), + IDBKeyRange: createPropertyDescriptor(FDBKeyRange_default), + IDBObjectStore: createPropertyDescriptor(FDBObjectStore_default), + IDBOpenDBRequest: createPropertyDescriptor(FDBOpenDBRequest_default), + IDBRecord: createPropertyDescriptor(FDBRecord_default), + IDBRequest: createPropertyDescriptor(FDBRequest_default), + IDBTransaction: createPropertyDescriptor(FDBTransaction_default), + IDBVersionChangeEvent: createPropertyDescriptor(FDBVersionChangeEvent_default) +}); + +// intern-log/repro/sync-repro.ts +init_schema(); +async function main() { + bindDatabase(new WorklogDB("repro_db")); + const mod = await Promise.resolve().then(() => (init_schema(), schema_exports)); + const db2 = mod.db; + await db2.project.bulkAdd([{ name: "P1", archived: 0, created_at: "2025-01-01T00:00:00" }]); + await db2.work_log.bulkAdd([{ date: "2025-01-02", created_at: "2025-01-02T00:00:00" }]); + await db2.setting.bulkAdd([ + { key: "work_start", value: "09:00" }, + { key: "sync_base_url", value: "http://127.0.0.1:3780" } + ]); + await db2.attendance.bulkAdd([{ date: "2025-01-02", clock_in_at: "2025-01-02T09:00:00", clock_out_at: "2025-01-02T18:00:00", kind: "normal", note: null, created_at: "2025-01-02T09:00:00" }]); + await db2.table("transaction").bulkAdd([{ type: "expense", category: "\u9910\u996E", amount: 2500, date: "2025-01-02", note: "lunch", reimbursable: 1, reimbursed: 0, created_at: "2025-01-02T12:00:00" }]); + const engine = await Promise.resolve().then(() => (init_engine(), engine_exports)); + engine.enableRealtimeSync(); + await fetch("http://127.0.0.1:3780/api/auth/register", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username: "rt", password: "rt123456" }) + }).catch(() => { + }); + const r1 = await engine.runSync({ baseUrl: "http://127.0.0.1:3780", username: "rt", password: "rt123456" }); + console.log("SYNC1 OK:", JSON.stringify(r1)); + await db2.table("log_item").add({ + work_log_id: 1, + content: "\u5B9E\u65F6\u6D4B\u8BD5\u6761\u76EE", + project_id: null, + category: "dev", + minutes: null, + is_milestone: 0, + needs_followup: 0, + takeaway: null, + remark: null, + sort_order: 0, + created_at: "2025-01-02T10:00:00" + }); + await new Promise((r) => setTimeout(r, 4500)); + console.log("REALTIME PATH DONE"); + const r2 = await engine.runSync({ baseUrl: "http://127.0.0.1:3780", username: "rt", password: "rt123456" }); + console.log("SYNC2 OK:", JSON.stringify(r2)); + process.exit(0); +} +main().catch((e) => { + console.error("FAILED:", e && (e.stack || e.message) || e); + process.exit(1); +}); diff --git a/intern-log/repro/sync-repro.ts b/intern-log/repro/sync-repro.ts new file mode 100644 index 0000000..6ebb748 --- /dev/null +++ b/intern-log/repro/sync-repro.ts @@ -0,0 +1,48 @@ +import 'fake-indexeddb/auto' +import { bindDatabase, WorklogDB } from '../src/db/schema' + +async function main() { + bindDatabase(new WorklogDB('repro_db')) + const mod = await import('../src/db/schema') + const db = mod.db + + await db.project.bulkAdd([{ name: 'P1', archived: 0, created_at: '2025-01-01T00:00:00' }]) + await db.work_log.bulkAdd([{ date: '2025-01-02', created_at: '2025-01-02T00:00:00' }]) + await db.setting.bulkAdd([ + { key: 'work_start', value: '09:00' }, + { key: 'sync_base_url', value: 'http://127.0.0.1:3780' } + ]) + await db.attendance.bulkAdd([{ date: '2025-01-02', clock_in_at: '2025-01-02T09:00:00', clock_out_at: '2025-01-02T18:00:00', kind: 'normal', note: null, created_at: '2025-01-02T09:00:00' }]) + await db.table('transaction').bulkAdd([{ type: 'expense', category: '餐饮', amount: 2500, date: '2025-01-02', note: 'lunch', reimbursable: 1, reimbursed: 0, created_at: '2025-01-02T12:00:00' }]) + + const engine = await import('../src/sync/engine') + engine.enableRealtimeSync() + + await fetch('http://127.0.0.1:3780/api/auth/register', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username: 'rt', password: 'rt123456' }) + }).catch(() => { /* 已注册则忽略 */ }) + + const r1 = await engine.runSync({ baseUrl: 'http://127.0.0.1:3780', username: 'rt', password: 'rt123456' }) + console.log('SYNC1 OK:', JSON.stringify(r1)) + + // 触发本地变更,走实时推送路径 + await db.table('log_item').add({ + work_log_id: 1, content: '实时测试条目', project_id: null, category: 'dev', + minutes: null, is_milestone: 0, needs_followup: 0, takeaway: null, + remark: null, sort_order: 0, created_at: '2025-01-02T10:00:00' + }) + await new Promise(r => setTimeout(r, 4500)) + console.log('REALTIME PATH DONE') + + // 二次同步幂等验证 + const r2 = await engine.runSync({ baseUrl: 'http://127.0.0.1:3780', username: 'rt', password: 'rt123456' }) + console.log('SYNC2 OK:', JSON.stringify(r2)) + process.exit(0) +} + +main().catch(e => { + console.error('FAILED:', (e && (e.stack || e.message)) || e) + process.exit(1) +}) diff --git a/intern-log/src/sync/engine.ts b/intern-log/src/sync/engine.ts index ea23d60..66f56c0 100644 --- a/intern-log/src/sync/engine.ts +++ b/intern-log/src/sync/engine.ts @@ -1,5 +1,6 @@ // 多端同步引擎:全量差异对比 + 记录级新者胜 + 软删除墓碑 // 实时性:本地变更 3 秒内推送;服务端变更通过 SSE 秒级通知其他端;60 秒轮询兜底 +import Dexie, { liveQuery } from 'dexie' import { db } from '../db/schema' import { getSetting, setSetting } from '../db/repo' import { getCloudCreds } from '../db/auth' @@ -167,6 +168,7 @@ let changeDebounce: number | null = null let sse: EventSource | null = null let sseKey = '' let realtimeAttached = false +let realtimeSub: { unsubscribe: () => void } | null = null export async function autoSyncNow(): Promise { if (syncRunning) { @@ -179,20 +181,29 @@ export async function autoSyncNow(): Promise { } catch { /* 自动同步静默失败,等待下次触发 */ } } -// 实时触发:本地任何数据变更 3 秒后自动推送 +// 实时触发:本地任何数据变更 3 秒后自动推送(Dexie 4 核心 liveQuery,跨全部业务表) export function enableRealtimeSync(): void { if (realtimeAttached) return realtimeAttached = true - ;(db as unknown as AnyRow).on('changes', () => { - if (changesSuppressed || syncRunning) return - if (changeDebounce) window.clearTimeout(changeDebounce) - changeDebounce = window.setTimeout(() => { void autoSyncNow() }, 3000) + const sub = liveQuery(async () => { + const counts: Record = {} + for (const t of TABLES) counts[t] = await db.table(t).count() + return counts + }) + realtimeSub = sub.subscribe({ + next: () => { + if (changesSuppressed || syncRunning) return + if (changeDebounce) globalThis.clearTimeout(changeDebounce) + changeDebounce = globalThis.setTimeout(() => { void autoSyncNow() }, 3000) + }, + error: () => { /* 忽略监听错误,轮询兜底 */ } }) } export function stopRealtime(): void { + if (realtimeSub) { realtimeSub.unsubscribe(); realtimeSub = null } if (sse) { sse.close(); sse = null; sseKey = '' } - if (changeDebounce) { window.clearTimeout(changeDebounce); changeDebounce = null } + if (changeDebounce) { globalThis.clearTimeout(changeDebounce); changeDebounce = null } } // 服务端 SSE 通知:其他端有变更时立即拉取 @@ -220,7 +231,7 @@ export async function runSync(config: SyncConfig): Promise { const result = await doRunSync(config) if (pendingSync) { pendingSync = false - window.setTimeout(() => { void autoSyncNow() }, 800) + globalThis.setTimeout(() => { void autoSyncNow() }, 800) } return result } finally { @@ -308,9 +319,9 @@ async function doRunSync(config: SyncConfig): Promise { removed++ } } - for (const [u, srow] of serverRows) { - if (dead.has(u)) continue - const local = byUuid.get(u) + for (const srow of serverRows) { + if (dead.has(srow.uuid)) continue + const local = byUuid.get(srow.uuid) if (!local) { await table.add({ ...srow }) pulled++