-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.min.js
More file actions
34 lines (27 loc) · 93.9 KB
/
main.min.js
File metadata and controls
34 lines (27 loc) · 93.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
Copyright © 2025-2026 Leo Zhang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
MIT License
Copyright (c) 2020 Kris Zyp
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CBOR={})}(this,(function(e){"use strict";let t,r,n;try{t=new TextDecoder}catch(e){}let i=0;const s={};let o,a,l,f,u,c,d,h=11281e4,y=1681e4,p={},g=0,w=0,b=[],m=[],A={useRecords:!1,mapsAsObjects:!0},v=!1,O=2;try{new Function("")}catch(e){O=1/0}class k{constructor(e){if(e&&(!e.keyMap&&!e._keyMap||e.useRecords||(e.useRecords=!1,e.mapsAsObjects=!0),!1===e.useRecords&&void 0===e.mapsAsObjects&&(e.mapsAsObjects=!0),e.getStructures&&(e.getShared=e.getStructures),e.getShared&&!e.structures&&((e.structures=[]).uninitialized=!0),e.keyMap)){this.mapKey=new Map;for(let[t,r]of Object.entries(e.keyMap))this.mapKey.set(r,t)}Object.assign(this,e)}decodeKey(e){return this.keyMap&&this.mapKey.get(e)||e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(e){if(!this._keyMap)return e;let t=new Map;for(let[r,n]of Object.entries(e))t.set(this._keyMap.hasOwnProperty(r)?this._keyMap[r]:r,n);return t}decodeKeys(e){if(!this._keyMap||"Map"!=e.constructor.name)return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let t={};return e.forEach(((e,r)=>t[M(this._mapKey.has(r)?this._mapKey.get(r):r)]=e)),t}mapDecode(e,t){let r=this.decode(e);return this._keyMap&&"Array"===r.constructor.name?r.map((e=>this.decodeKeys(e))):r}decode(e,t){if(r)return H((()=>(Y(),this?this.decode(e,t):k.prototype.decode.call(A,e,t))));n=t>-1?t:e.length,i=0,w=0,a=null,l=null,r=e;try{c=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(t){if(r=null,e instanceof Uint8Array)throw t;throw new Error("Source must be a Uint8Array or Buffer but was a "+(e&&"object"==typeof e?e.constructor.name:typeof e))}if(this instanceof k){if(p=this,u=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return o=this.structures,E();(!o||o.length>0)&&(o=[])}else p=A,(!o||o.length>0)&&(o=[]),u=null;return E()}decodeMultiple(e,t){let r,n=0;try{let s=e.length;v=!0;let o=this?this.decode(e,s):Z.decode(e,s);if(!t){for(r=[o];i<s;)n=i,r.push(E());return r}if(!1===t(o))return;for(;i<s;)if(n=i,!1===t(E()))return}catch(e){throw e.lastPosition=n,e.values=r,e}finally{v=!1,Y()}}}function E(){try{let e=I();if(l){if(i>=l.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}i=l.postBundlePosition,l=null}if(i==n)o=null,r=null,f&&(f=null);else{if(i>n){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}if(!v)throw new Error("Data read, but end of buffer not reached")}return e}catch(e){throw Y(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer"))&&(e.incomplete=!0),e}}function I(){let e=r[i++],t=e>>5;if(e&=31,e>23)switch(e){case 24:e=r[i++];break;case 25:if(7==t)return function(){let e=r[i++],t=r[i++],n=(127&e)>>2;if(31===n)return t||3&e?NaN:128&e?-1/0:1/0;if(0===n){let r=((3&e)<<8|t)/(1<<24);return 128&e?-r:r}return _[3]=128&e|56+(n>>1),_[2]=(7&e)<<5|t>>3,_[1]=t<<5,_[0]=0,P[0]}();e=c.getUint16(i),i+=2;break;case 26:if(7==t){let e=c.getFloat32(i);if(p.useFloat32>2){let t=q[(127&r[i])<<1|r[i+1]>>7];return i+=4,(t*e+(e>0?.5:-.5)>>0)/t}return i+=4,e}e=c.getUint32(i),i+=4;break;case 27:if(7==t){let e=c.getFloat64(i);return i+=8,e}if(t>1){if(c.getUint32(i)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");e=c.getUint32(i+4)}else p.int64AsNumber?(e=4294967296*c.getUint32(i),e+=c.getUint32(i+4)):e=c.getBigUint64(i);i+=8;break;case 31:switch(t){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let e,r=[],n=0;for(;(e=I())!=s;){if(n>=h)throw new Error(`Array length exceeds ${h}`);r[n++]=e}return 4==t?r:3==t?r.join(""):Buffer.concat(r);case 5:let i;if(p.mapsAsObjects){let e={},t=0;if(p.keyMap)for(;(i=I())!=s;){if(t++>=y)throw new Error(`Property count exceeds ${y}`);e[M(p.decodeKey(i))]=I()}else for(;(i=I())!=s;){if(t++>=y)throw new Error(`Property count exceeds ${y}`);e[M(i)]=I()}return e}{d&&(p.mapsAsObjects=!0,d=!1);let e=new Map;if(p.keyMap){let t=0;for(;(i=I())!=s;){if(t++>=y)throw new Error(`Map size exceeds ${y}`);e.set(p.decodeKey(i),I())}}else{let t=0;for(;(i=I())!=s;){if(t++>=y)throw new Error(`Map size exceeds ${y}`);e.set(i,I())}}return e}case 7:return s;default:throw new Error("Invalid major type for indefinite length "+t)}default:throw new Error("Unknown token "+e)}switch(t){case 0:return e;case 1:return~e;case 2:return f=e,p.copyBuffers?Uint8Array.prototype.slice.call(r,i,i+=f):r.subarray(i,i+=f);case 3:if(w>=i)return a.slice(i-g,(i+=e)-g);if(0==w&&n<140&&e<32){let t=e<16?V(e):function(e){let t=i,n=new Array(e);for(let s=0;s<e;s++){const e=r[i++];if((128&e)>0)return void(i=t);n[s]=e}return B.apply(String,n)}(e);if(null!=t)return t}return x(e);case 4:if(e>=h)throw new Error(`Array length exceeds ${h}`);let t=new Array(e);for(let r=0;r<e;r++)t[r]=I();return t;case 5:if(e>=y)throw new Error(`Map size exceeds ${h}`);if(p.mapsAsObjects){let t={};if(p.keyMap)for(let r=0;r<e;r++)t[M(p.decodeKey(I()))]=I();else for(let r=0;r<e;r++)t[M(I())]=I();return t}{d&&(p.mapsAsObjects=!0,d=!1);let t=new Map;if(p.keyMap)for(let r=0;r<e;r++)t.set(p.decodeKey(I()),I());else for(let r=0;r<e;r++)t.set(I(),I());return t}case 6:if(e>=57337){let t=o[8191&e];if(t)return t.read||(t.read=S(t)),t.read();if(e<65536){if(57343==e){let e=$(),t=I(),r=I();F(t,r);let n={};if(p.keyMap)for(let t=2;t<e;t++){n[M(p.decodeKey(r[t-2]))]=I()}else for(let t=2;t<e;t++){n[M(r[t-2])]=I()}return n}if(57342==e){let e=$(),t=I();for(let r=2;r<e;r++)F(t++,I());return I()}if(57337==e)return function(){let e=$(),t=i+I();for(let t=2;t<e;t++){let e=$();i+=e}let r=i;return i=t,l=[j($()),j($())],l.position0=0,l.position1=0,l.postBundlePosition=i,i=r,I()}();if(p.getShared&&(J(),t=o[8191&e],t))return t.read||(t.read=S(t)),t.read()}}let s=b[e];if(s)return s.handlesRead?s(I):s(I());{let t=I();for(let r=0;r<m.length;r++){let n=m[r](e,t);if(void 0!==n)return n}return new R(t,e)}case 7:switch(e){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let t=(u||K())[e];if(void 0!==t)return t;throw new Error("Unknown token "+e)}default:if(isNaN(e)){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}throw new Error("Unknown CBOR token "+e)}var f}const U=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function S(e){if(!e)throw new Error("Structure is required in record definition");return e.slowReads=0,function(){let e=r[i++];if(e&=31,e>23)switch(e){case 24:e=r[i++];break;case 25:e=c.getUint16(i),i+=2;break;case 26:e=c.getUint32(i),i+=4;break;default:throw new Error("Expected array header, but got "+r[i-1])}let t=this.compiledReader;for(;t;){if(t.propertyCount===e)return t(I);t=t.next}if(this.slowReads++>=O){let r=this.length==e?this:this.slice(0,e);return t=p.keyMap?new Function("r","return {"+r.map((e=>p.decodeKey(e))).map((e=>U.test(e)?M(e)+":r()":"["+JSON.stringify(e)+"]:r()")).join(",")+"}"):new Function("r","return {"+r.map((e=>U.test(e)?M(e)+":r()":"["+JSON.stringify(e)+"]:r()")).join(",")+"}"),this.compiledReader&&(t.next=this.compiledReader),t.propertyCount=e,this.compiledReader=t,t(I)}let n={};if(p.keyMap)for(let t=0;t<e;t++)n[M(p.decodeKey(this[t]))]=I();else for(let t=0;t<e;t++)n[M(this[t])]=I();return n}}function M(e){if("string"==typeof e)return"__proto__"===e?"__proto_":e;if("number"==typeof e||"boolean"==typeof e||"bigint"==typeof e)return e.toString();if(null==e)return e+"";throw new Error("Invalid property name type "+typeof e)}let x=j;function j(e){let n;if(e<16&&(n=V(e)))return n;if(e>64&&t)return t.decode(r.subarray(i,i+=e));const s=i+e,o=[];for(n="";i<s;){const e=r[i++];if(0==(128&e))o.push(e);else if(192==(224&e)){const t=63&r[i++];o.push((31&e)<<6|t)}else if(224==(240&e)){const t=63&r[i++],n=63&r[i++];o.push((31&e)<<12|t<<6|n)}else if(240==(248&e)){let t=(7&e)<<18|(63&r[i++])<<12|(63&r[i++])<<6|63&r[i++];t>65535&&(t-=65536,o.push(t>>>10&1023|55296),t=56320|1023&t),o.push(t)}else o.push(e);o.length>=4096&&(n+=B.apply(String,o),o.length=0)}return o.length>0&&(n+=B.apply(String,o)),n}let B=String.fromCharCode;function V(e){if(e<4){if(e<2){if(0===e)return"";{let e=r[i++];return(128&e)>1?void(i-=1):B(e)}}{let t=r[i++],n=r[i++];if((128&t)>0||(128&n)>0)return void(i-=2);if(e<3)return B(t,n);let s=r[i++];return(128&s)>0?void(i-=3):B(t,n,s)}}{let t=r[i++],n=r[i++],s=r[i++],o=r[i++];if((128&t)>0||(128&n)>0||(128&s)>0||(128&o)>0)return void(i-=4);if(e<6){if(4===e)return B(t,n,s,o);{let e=r[i++];return(128&e)>0?void(i-=5):B(t,n,s,o,e)}}if(e<8){let a=r[i++],l=r[i++];if((128&a)>0||(128&l)>0)return void(i-=6);if(e<7)return B(t,n,s,o,a,l);let f=r[i++];return(128&f)>0?void(i-=7):B(t,n,s,o,a,l,f)}{let a=r[i++],l=r[i++],f=r[i++],u=r[i++];if((128&a)>0||(128&l)>0||(128&f)>0||(128&u)>0)return void(i-=8);if(e<10){if(8===e)return B(t,n,s,o,a,l,f,u);{let e=r[i++];return(128&e)>0?void(i-=9):B(t,n,s,o,a,l,f,u,e)}}if(e<12){let c=r[i++],d=r[i++];if((128&c)>0||(128&d)>0)return void(i-=10);if(e<11)return B(t,n,s,o,a,l,f,u,c,d);let h=r[i++];return(128&h)>0?void(i-=11):B(t,n,s,o,a,l,f,u,c,d,h)}{let c=r[i++],d=r[i++],h=r[i++],y=r[i++];if((128&c)>0||(128&d)>0||(128&h)>0||(128&y)>0)return void(i-=12);if(e<14){if(12===e)return B(t,n,s,o,a,l,f,u,c,d,h,y);{let e=r[i++];return(128&e)>0?void(i-=13):B(t,n,s,o,a,l,f,u,c,d,h,y,e)}}{let p=r[i++],g=r[i++];if((128&p)>0||(128&g)>0)return void(i-=14);if(e<15)return B(t,n,s,o,a,l,f,u,c,d,h,y,p,g);let w=r[i++];return(128&w)>0?void(i-=15):B(t,n,s,o,a,l,f,u,c,d,h,y,p,g,w)}}}}}let P=new Float32Array(1),_=new Uint8Array(P.buffer,0,4);new Array(4096);class R{constructor(e,t){this.value=e,this.tag=t}}b[0]=e=>new Date(e),b[1]=e=>new Date(Math.round(1e3*e)),b[2]=e=>{let t=BigInt(0);for(let r=0,n=e.byteLength;r<n;r++)t=BigInt(e[r])+(t<<BigInt(8));return t},b[3]=e=>BigInt(-1)-b[2](e),b[4]=e=>+(e[1]+"e"+e[0]),b[5]=e=>e[1]*Math.exp(e[0]*Math.log(2));const F=(e,t)=>{let r=o[e-=57344];r&&r.isShared&&((o.restoreStructures||(o.restoreStructures=[]))[e]=r),o[e]=t,t.read=S(t)};b[105]=e=>{let t=e.length,r=e[1];F(e[0],r);let n={};for(let i=2;i<t;i++){n[M(r[i-2])]=e[i]}return n},b[14]=e=>l?l[0].slice(l.position0,l.position0+=e):new R(e,14),b[15]=e=>l?l[1].slice(l.position1,l.position1+=e):new R(e,15);let T={Error:Error,RegExp:RegExp};b[27]=e=>(T[e[0]]||Error)(e[1],e[2]);const D=e=>{if(132!=r[i++]){let e=new Error("Packed values structure must be followed by a 4 element array");throw r.length<i&&(e.incomplete=!0),e}let t=e();if(!t||!t.length){let e=new Error("Packed values structure must be followed by a 4 element array");throw e.incomplete=!0,e}return u=u?t.concat(u.slice(t.length)):t,u.prefixes=e(),u.suffixes=e(),e()};function N(e,t){return"string"==typeof e?e+t:e instanceof Array?e.concat(t):Object.assign({},e,t)}function K(){if(!u){if(!p.getShared)throw new Error("No packed values available");J()}return u}D.handlesRead=!0,b[51]=D,b[6]=e=>{if(!u){if(!p.getShared)return new R(e,6);J()}if("number"==typeof e)return u[16+(e>=0?2*e:-2*e-1)];let t=new Error("No support for non-integer packed references yet");throw void 0===e&&(t.incomplete=!0),t},b[28]=e=>{f||(f=new Map,f.id=0);let t,n=f.id++,s=i;t=r[i]>>5==4?[]:{};let o={target:t};f.set(n,o);let a=e();return o.used?(Object.getPrototypeOf(t)!==Object.getPrototypeOf(a)&&(i=s,t=a,f.set(n,{target:t}),a=e()),Object.assign(t,a)):(o.target=a,a)},b[28].handlesRead=!0,b[29]=e=>{let t=f.get(e);return t.used=!0,t.target},b[258]=e=>new Set(e),(b[259]=e=>(p.mapsAsObjects&&(p.mapsAsObjects=!1,d=!0),e())).handlesRead=!0;m.push(((e,t)=>e>=225&&e<=255?N(K().prefixes[e-224],t):e>=28704&&e<=32767?N(K().prefixes[e-28672],t):e>=1879052288&&e<=2147483647?N(K().prefixes[e-1879048192],t):e>=216&&e<=223?N(t,K().suffixes[e-216]):e>=27647&&e<=28671?N(t,K().suffixes[e-27639]):e>=1811940352&&e<=1879048191?N(t,K().suffixes[e-1811939328]):1399353956==e?{packedValues:u,structures:o.slice(0),version:t}:55799==e?t:void 0));const C=1==new Uint8Array(new Uint16Array([1]).buffer)[0],z=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,"undefined"==typeof BigUint64Array?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,"undefined"==typeof BigInt64Array?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],L=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e<z.length;e++)W(z[e],L[e]);function W(e,t){let r,n="get"+e.name.slice(0,-5);"function"==typeof e?r=e.BYTES_PER_ELEMENT:e=null;for(let i=0;i<2;i++){if(!i&&1==r)continue;let s=2==r?1:4==r?2:8==r?3:0;b[i?t:t-4]=1==r||i==C?n=>{if(!e)throw new Error("Could not find typed array for code "+t);return p.copyBuffers||1!==r&&(2!==r||1&n.byteOffset)&&(4!==r||3&n.byteOffset)&&(8!==r||7&n.byteOffset)?new e(Uint8Array.prototype.slice.call(n,0).buffer):new e(n.buffer,n.byteOffset,n.byteLength>>s)}:r=>{if(!e)throw new Error("Could not find typed array for code "+t);let o=new DataView(r.buffer,r.byteOffset,r.byteLength),a=r.length>>s,l=new e(a),f=o[n];for(let e=0;e<a;e++)l[e]=f.call(o,e<<s,i);return l}}}function $(){let e=31&r[i++];if(e>23)switch(e){case 24:e=r[i++];break;case 25:e=c.getUint16(i),i+=2;break;case 26:e=c.getUint32(i),i+=4}return e}function J(){if(p.getShared){let e=H((()=>(r=null,p.getShared())))||{},t=e.structures||[];p.sharedVersion=e.version,u=p.sharedValues=e.packedValues,!0===o?p.structures=o=t:o.splice.apply(o,[0,t.length].concat(t))}}function H(e){let t=n,s=i,u=g,d=w,h=a,y=f,b=l,m=new Uint8Array(r.slice(0,n)),A=o,O=p,k=v,E=e();return n=t,i=s,g=u,w=d,a=h,f=y,l=b,r=m,v=k,o=A,p=O,c=new DataView(r.buffer,r.byteOffset,r.byteLength),E}function Y(){r=null,f=null,o=null}const q=new Array(147);for(let e=0;e<256;e++)q[e]=+("1e"+Math.floor(45.15-.30103*e));let Z=new k({useRecords:!1});const G=Z.decode,Q=Z.decodeMultiple,X={NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4};let ee,te,re;try{ee=new TextEncoder}catch(e){}const ne="object"==typeof globalThis&&globalThis.Buffer,ie=void 0!==ne,se=ie?ne.allocUnsafeSlow:Uint8Array,oe=ie?ne:Uint8Array,ae=ie?4294967296:2144337920;let le,fe,ue,ce,de=0,he=null;const ye=/[\u0080-\uFFFF]/,pe=Symbol("record-id");class ge extends k{constructor(e){let t,r,n,i,s;super(e),this.offset=0,e=e||{};let o=oe.prototype.utf8Write?function(e,t,r){return fe.utf8Write(e,t,r)}:!(!ee||!ee.encodeInto)&&function(e,t){return ee.encodeInto(e,fe.subarray(t)).written},a=this,l=e.structures||e.saveStructures,f=e.maxSharedStructures;if(null==f&&(f=l?128:0),f>8190)throw new Error("Maximum maxSharedStructure is 8190");let u=e.sequential;u&&(f=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let c,d,h,y=e.sharedValues;if(y){h=Object.create(null);for(let e=0,t=y.length;e<t;e++)h[y[e]]=e}let p=[],g=0,w=0;this.mapEncode=function(e,t){if(this._keyMap&&!this._mapped&&"Array"===e.constructor.name)e=e.map((e=>this.encodeKeys(e)));return this.encode(e,t)},this.encode=function(o,l){if(fe||(fe=new se(8192),ue=new DataView(fe.buffer,0,8192),de=0),ce=fe.length-10,ce-de<2048?(fe=new se(fe.length),ue=new DataView(fe.buffer,0,fe.length),ce=fe.length-10,de=0):l===Re&&(de=de+7&2147483640),t=de,a.useSelfDescribedHeader&&(ue.setUint32(de,3654940416),de+=3),s=a.structuredClone?new Map:null,a.bundleStrings&&"string"!=typeof o?(he=[],he.size=1/0):he=null,r=a.structures,r){if(r.uninitialized){let e=a.getShared()||{};a.structures=r=e.structures||[],a.sharedVersion=e.version;let t=a.sharedValues=e.packedValues;if(t){h={};for(let e=0,r=t.length;e<r;e++)h[t[e]]=e}}let e=r.length;if(e>f&&!u&&(e=f),!r.transitions){r.transitions=Object.create(null);for(let t=0;t<e;t++){let e=r[t];if(!e)continue;let n,i=r.transitions;for(let r=0,s=e.length;r<s;r++){void 0===i[pe]&&(i[pe]=t);let s=e[r];n=i[s],n||(n=i[s]=Object.create(null)),i=n}i[pe]=1048576|t}}u||(r.nextId=e)}if(n&&(n=!1),i=r||[],d=h,e.pack){let t=new Map;if(t.values=[],t.encoder=a,t.maxValues=e.maxPrivatePackedValues||(h?16:1/0),t.objectMap=h||!1,t.samplingPackedValues=c,Oe(o,t),t.values.length>0){fe[de++]=216,fe[de++]=51,me(4);let e=t.values;b(e),me(0),me(0),d=Object.create(h||null);for(let t=0,r=e.length;t<r;t++)d[e[t]]=t}}le=l&Te;try{if(le)return;if(b(o),he&&Ue(t,b),a.offset=de,s&&s.idsToInsert){de+=2*s.idsToInsert.length,de>ce&&A(de),a.offset=de;let e=function(e,t){let r,n=2*t.length,i=e.length-n;t.sort(((e,t)=>e.offset>t.offset?1:-1));for(let r=0;r<t.length;r++){let n=t[r];n.id=r;for(let t of n.references)e[t++]=r>>8,e[t]=255&r}for(;r=t.pop();){let t=r.offset;e.copyWithin(t+n,t,i),n-=2;let s=t+n;e[s++]=216,e[s++]=28,i=t}return e}(fe.subarray(t,de),s.idsToInsert);return s=null,e}return l&Re?(fe.start=t,fe.end=de,fe):fe.subarray(t,de)}finally{if(r)if(w<10&&w++,r.length>f&&(r.length=f),g>1e4)r.transitions=null,w=0,g=0,p.length>0&&(p=[]);else if(p.length>0&&!u){for(let e=0,t=p.length;e<t;e++)p[e][pe]=void 0;p=[]}if(n&&a.saveShared){a.structures.length>f&&(a.structures=a.structures.slice(0,f));let e=fe.subarray(t,de);return!1===a.updateSharedData()?a.encode(o):e}l&Fe&&(de=t)}},this.findCommonStringsToPack=()=>(c=new Map,h||(h=Object.create(null)),e=>{let t=e&&e.threshold||4,r=this.pack?e.maxPrivatePackedValues||16:0;y||(y=this.sharedValues=[]);for(let[e,i]of c)i.count>t&&(h[e]=r++,y.push(e),n=!0);for(;this.saveShared&&!1===this.updateSharedData(););c=null});const b=r=>{de>ce&&(fe=A(de));var n,i=typeof r;if("string"===i){if(d){let t=d[r];if(t>=0)return void(t<16?fe[de++]=t+224:(fe[de++]=198,b(1&t?15-t>>1:t-16>>1)));if(c&&!e.pack){let e=c.get(r);e?e.count++:c.set(r,{count:1})}}let i,s=r.length;if(he&&s>=4&&s<1024){if((he.size+=s)>61440){let e,r=(he[0]?3*he[0].length+he[1].length:0)+10;de+r>ce&&(fe=A(de+r)),fe[de++]=217,fe[de++]=223,fe[de++]=249,fe[de++]=he.position?132:130,fe[de++]=26,e=de-t,de+=4,he.position&&Ue(t,b),he=["",""],he.size=0,he.position=e}let e=ye.test(r);return he[e?0:1]+=r,fe[de++]=e?206:207,void b(s)}i=s<32?1:s<256?2:s<65536?3:5;let a=3*s;if(de+a>ce&&(fe=A(de+a)),s<64||!o){let e,t,o,a=de+i;for(e=0;e<s;e++)t=r.charCodeAt(e),t<128?fe[a++]=t:t<2048?(fe[a++]=t>>6|192,fe[a++]=63&t|128):55296==(64512&t)&&56320==(64512&(o=r.charCodeAt(e+1)))?(t=65536+((1023&t)<<10)+(1023&o),e++,fe[a++]=t>>18|240,fe[a++]=t>>12&63|128,fe[a++]=t>>6&63|128,fe[a++]=63&t|128):(fe[a++]=t>>12|224,fe[a++]=t>>6&63|128,fe[a++]=63&t|128);n=a-de-i}else n=o(r,de+i,a);n<24?fe[de++]=96|n:n<256?(i<2&&fe.copyWithin(de+2,de+1,de+1+n),fe[de++]=120,fe[de++]=n):n<65536?(i<3&&fe.copyWithin(de+3,de+2,de+2+n),fe[de++]=121,fe[de++]=n>>8,fe[de++]=255&n):(i<5&&fe.copyWithin(de+5,de+3,de+3+n),fe[de++]=122,ue.setUint32(de,n),de+=4),de+=n}else if("number"===i)if(this.alwaysUseFloat||r>>>0!==r)if(this.alwaysUseFloat||r>>0!==r){let e;if((e=this.useFloat32)>0&&r<4294967296&&r>=-2147483648){let t;if(fe[de++]=250,ue.setFloat32(de,r),e<4||(t=r*q[(127&fe[de])<<1|fe[de+1]>>7])>>0===t)return void(de+=4);de--}fe[de++]=251,ue.setFloat64(de,r),de+=8}else r>=-24?fe[de++]=31-r:r>=-256?(fe[de++]=56,fe[de++]=~r):r>=-65536?(fe[de++]=57,ue.setUint16(de,~r),de+=2):(fe[de++]=58,ue.setUint32(de,~r),de+=4);else r<24?fe[de++]=r:r<256?(fe[de++]=24,fe[de++]=r):r<65536?(fe[de++]=25,fe[de++]=r>>8,fe[de++]=255&r):(fe[de++]=26,ue.setUint32(de,r),de+=4);else if("object"===i)if(r){if(s){let e=s.get(r);if(e){if(fe[de++]=216,fe[de++]=29,fe[de++]=25,!e.references){let t=s.idsToInsert||(s.idsToInsert=[]);e.references=[],t.push(e)}return e.references.push(de-t),void(de+=2)}s.set(r,{offset:de-t})}let e=r.constructor;if(e===Object)m(r);else if(e===Array){(n=r.length)<24?fe[de++]=128|n:me(n);for(let e=0;e<n;e++)b(r[e])}else if(e===Map)if((this.mapsAsObjects?!1!==this.useTag259ForMaps:this.useTag259ForMaps)&&(fe[de++]=217,fe[de++]=1,fe[de++]=3),(n=r.size)<24?fe[de++]=160|n:n<256?(fe[de++]=184,fe[de++]=n):n<65536?(fe[de++]=185,fe[de++]=n>>8,fe[de++]=255&n):(fe[de++]=186,ue.setUint32(de,n),de+=4),a.keyMap)for(let[e,t]of r)b(a.encodeKey(e)),b(t);else for(let[e,t]of r)b(e),b(t);else{for(let e=0,t=te.length;e<t;e++){if(r instanceof re[e]){let t=te[e],n=t.tag;return null==n&&(n=t.getTag&&t.getTag.call(this,r)),n<24?fe[de++]=192|n:n<256?(fe[de++]=216,fe[de++]=n):n<65536?(fe[de++]=217,fe[de++]=n>>8,fe[de++]=255&n):n>-1&&(fe[de++]=218,ue.setUint32(de,n),de+=4),void t.encode.call(this,r,b,A)}}if(r[Symbol.iterator]){if(le){let e=new Error("Iterable should be serialized as iterator");throw e.iteratorNotHandled=!0,e}fe[de++]=159;for(let e of r)b(e);return void(fe[de++]=255)}if(r[Symbol.asyncIterator]||ve(r)){let e=new Error("Iterable/blob should be serialized as iterator");throw e.iteratorNotHandled=!0,e}if(this.useToJSON&&r.toJSON){const e=r.toJSON();if(e!==r)return b(e)}m(r)}}else fe[de++]=246;else if("boolean"===i)fe[de++]=r?245:244;else if("bigint"===i){if(r<BigInt(1)<<BigInt(64)&&r>=0)fe[de++]=27,ue.setBigUint64(de,r);else if(r>-(BigInt(1)<<BigInt(64))&&r<0)fe[de++]=59,ue.setBigUint64(de,-r-BigInt(1));else{if(!this.largeBigIntToFloat){r>=BigInt(0)?fe[de++]=194:(fe[de++]=195,r=BigInt(-1)-r);let e=[];for(;r;)e.push(Number(r&BigInt(255))),r>>=BigInt(8);return void Ie(new Uint8Array(e.reverse()),A)}fe[de++]=251,ue.setFloat64(de,Number(r))}de+=8}else{if("undefined"!==i)throw new Error("Unknown type: "+i);fe[de++]=247}},m=!1===this.useRecords?this.variableMapSize?e=>{let t=Object.keys(e),r=Object.values(e),n=t.length;if(n<24?fe[de++]=160|n:n<256?(fe[de++]=184,fe[de++]=n):n<65536?(fe[de++]=185,fe[de++]=n>>8,fe[de++]=255&n):(fe[de++]=186,ue.setUint32(de,n),de+=4),a.keyMap)for(let e=0;e<n;e++)b(a.encodeKey(t[e])),b(r[e]);else for(let e=0;e<n;e++)b(t[e]),b(r[e])}:e=>{fe[de++]=185;let r=de-t;de+=2;let n=0;if(a.keyMap)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(b(a.encodeKey(t)),b(e[t]),n++);else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(b(t),b(e[t]),n++);fe[r+++t]=n>>8,fe[r+t]=255&n}:(e,t)=>{let r,s,o,a=i.transitions||(i.transitions=Object.create(null)),l=0,u=0;if(this.keyMap){o=Object.keys(e).map((e=>this.encodeKey(e))),u=o.length;for(let e=0;e<u;e++){let t=o[e];r=a[t],r||(r=a[t]=Object.create(null),l++),a=r}}else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(r=a[t],r||(1048576&a[pe]&&(s=65535&a[pe]),r=a[t]=Object.create(null),l++),a=r,u++);let c=a[pe];if(void 0!==c)c&=65535,fe[de++]=217,fe[de++]=c>>8|224,fe[de++]=255&c;else{if(o||(o=a.__keys__||(a.__keys__=Object.keys(e))),void 0===s?(c=i.nextId++,c||(c=0,i.nextId=1),c>=256&&(i.nextId=(c=f)+1)):c=s,i[c]=o,!(c<f)){if(a[pe]=c,ue.setUint32(de,3655335680),de+=3,l&&(g+=w*l),p.length>=256-f&&(p.shift()[pe]=void 0),p.push(a),me(u+2),b(57344+c),b(o),t)return;for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&b(e[t]);return}fe[de++]=217,fe[de++]=c>>8|224,fe[de++]=255&c,a=i.transitions;for(let e=0;e<u;e++)(void 0===a[pe]||1048576&a[pe])&&(a[pe]=c),a=a[o[e]];a[pe]=1048576|c,n=!0}if(u<24?fe[de++]=128|u:me(u),!t)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&b(e[t])},A=e=>{let r;if(e>16777216){if(e-t>ae)throw new Error("Encoded buffer would be larger than maximum buffer size");r=Math.min(ae,4096*Math.round(Math.max((e-t)*(e>67108864?1.25:2),4194304)/4096))}else r=1+(Math.max(e-t<<2,fe.length-1)>>12)<<12;let n=new se(r);return ue=new DataView(n.buffer,0,r),fe.copy?fe.copy(n,0,t,e):n.set(fe.slice(t,e)),de-=t,t=0,ce=n.length-10,fe=n};let v=100,O=1e3;function*k(e,r,n){let i=e.constructor;if(i===Object){let t=!1!==a.useRecords;t?m(e,!0):we(Object.keys(e).length,160);for(let n in e){let i=e[n];t||b(n),i&&"object"==typeof i?r[n]?yield*k(i,r[n]):yield*E(i,r,n):b(i)}}else if(i===Array){let n=e.length;me(n);for(let i=0;i<n;i++){let n=e[i];n&&("object"==typeof n||de-t>v)?r.element?yield*k(n,r.element):yield*E(n,r,"element"):b(n)}}else if(e[Symbol.iterator]&&!e.buffer){fe[de++]=159;for(let n of e)n&&("object"==typeof n||de-t>v)?r.element?yield*k(n,r.element):yield*E(n,r,"element"):b(n);fe[de++]=255}else ve(e)?(we(e.size,64),yield fe.subarray(t,de),yield e,I()):e[Symbol.asyncIterator]?(fe[de++]=159,yield fe.subarray(t,de),yield e,I(),fe[de++]=255):b(e);n&&de>t?yield fe.subarray(t,de):de-t>v&&(yield fe.subarray(t,de),I())}function*E(e,r,n){let i=de-t;try{b(e),de-t>v&&(yield fe.subarray(t,de),I())}catch(s){if(!s.iteratorNotHandled)throw s;r[n]={},de=t+i,yield*k.call(this,e,r[n])}}function I(){v=O,a.encode(null,Te)}function U(e,t,r){return v=t&&t.chunkThreshold?O=t.chunkThreshold:100,e&&"object"==typeof e?(a.encode(null,Te),r(e,a.iterateProperties||(a.iterateProperties={}),!0)):[a.encode(e)]}async function*S(e,t){for(let r of k(e,t,!0)){let e=r.constructor;if(e===oe||e===Uint8Array)yield r;else if(ve(r)){let e,t=r.stream().getReader();for(;!(e=await t.read()).done;)yield e.value}else if(r[Symbol.asyncIterator])for await(let e of r)I(),e?yield*S(e,t.async||(t.async={})):yield a.encode(e);else yield r}}this.encodeAsIterable=function(e,t){return U(e,t,k)},this.encodeAsAsyncIterable=function(e,t){return U(e,t,S)}}useBuffer(e){fe=e,ue=new DataView(fe.buffer,fe.byteOffset,fe.byteLength),de=0}clearSharedData(){this.structures&&(this.structures=[]),this.sharedValues&&(this.sharedValues=void 0)}updateSharedData(){let e=this.sharedVersion||0;this.sharedVersion=e+1;let t=this.structures.slice(0),r=new be(t,this.sharedValues,this.sharedVersion),n=this.saveShared(r,(t=>(t&&t.version||0)==e));return!1===n?(r=this.getShared()||{},this.structures=r.structures||[],this.sharedValues=r.packedValues,this.sharedVersion=r.version,this.structures.nextId=this.structures.length):t.forEach(((e,t)=>this.structures[t]=e)),n}}function we(e,t){e<24?fe[de++]=t|e:e<256?(fe[de++]=24|t,fe[de++]=e):e<65536?(fe[de++]=25|t,fe[de++]=e>>8,fe[de++]=255&e):(fe[de++]=26|t,ue.setUint32(de,e),de+=4)}class be{constructor(e,t,r){this.structures=e,this.packedValues=t,this.version=r}}function me(e){e<24?fe[de++]=128|e:e<256?(fe[de++]=152,fe[de++]=e):e<65536?(fe[de++]=153,fe[de++]=e>>8,fe[de++]=255&e):(fe[de++]=154,ue.setUint32(de,e),de+=4)}const Ae="undefined"==typeof Blob?function(){}:Blob;function ve(e){if(e instanceof Ae)return!0;let t=e[Symbol.toStringTag];return"Blob"===t||"File"===t}function Oe(e,t){switch(typeof e){case"string":if(e.length>3){if(t.objectMap[e]>-1||t.values.length>=t.maxValues)return;let r=t.get(e);if(r)2==++r.count&&t.values.push(e);else if(t.set(e,{count:1}),t.samplingPackedValues){let r=t.samplingPackedValues.get(e);r?r.count++:t.samplingPackedValues.set(e,{count:1})}}break;case"object":if(e)if(e instanceof Array)for(let r=0,n=e.length;r<n;r++)Oe(e[r],t);else{let n=!t.encoder.useRecords;for(var r in e)e.hasOwnProperty(r)&&(n&&Oe(r,t),Oe(e[r],t))}break;case"function":console.log(e)}}const ke=1==new Uint8Array(new Uint16Array([1]).buffer)[0];function Ee(e,t){return!ke&&t>1&&(e-=4),{tag:e,encode:function(e,t){let r=e.byteLength,n=e.byteOffset||0,i=e.buffer||e;t(ie?ne.from(i,n,r):new Uint8Array(i,n,r))}}}function Ie(e,t){let r=e.byteLength;r<24?fe[de++]=64+r:r<256?(fe[de++]=88,fe[de++]=r):r<65536?(fe[de++]=89,fe[de++]=r>>8,fe[de++]=255&r):(fe[de++]=90,ue.setUint32(de,r),de+=4),de+r>=fe.length&&t(de+r),fe.set(e.buffer?e:new Uint8Array(e),de),de+=r}function Ue(e,t){ue.setUint32(he.position+e,de-he.position-e+1);let r=he;he=null,t(r[0]),t(r[1])}re=[Date,Set,Error,RegExp,R,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,"undefined"==typeof BigUint64Array?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,"undefined"==typeof BigInt64Array?function(){}:BigInt64Array,Float32Array,Float64Array,be],te=[{tag:1,encode(e,t){let r=e.getTime()/1e3;(this.useTimestamp32||0===e.getMilliseconds())&&r>=0&&r<4294967296?(fe[de++]=26,ue.setUint32(de,r),de+=4):(fe[de++]=251,ue.setFloat64(de,r),de+=8)}},{tag:258,encode(e,t){t(Array.from(e))}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t(["RegExp",e.source,e.flags])}},{getTag:e=>e.tag,encode(e,t){t(e.value)}},{encode(e,t,r){Ie(e,r)}},{getTag(e){if(e.constructor===Uint8Array&&(this.tagUint8Array||ie&&!1!==this.tagUint8Array))return 64},encode(e,t,r){Ie(e,r)}},Ee(68,1),Ee(69,2),Ee(70,4),Ee(71,8),Ee(72,1),Ee(77,2),Ee(78,4),Ee(79,8),Ee(85,4),Ee(86,8),{encode(e,t){let r=e.packedValues||[],n=e.structures||[];if(r.values.length>0){fe[de++]=216,fe[de++]=51,me(4);let e=r.values;t(e),me(0),me(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let t=0,r=e.length;t<r;t++)packedObjectMap[e[t]]=t}if(n){ue.setUint32(de,3655335424),de+=3;let r=n.slice(0);r.unshift(57344),r.push(new R(e.version,1399353956)),t(r)}else t(new R(e.version,1399353956))}}];let Se=new ge({useRecords:!1});const Me=Se.encode,xe=Se.encodeAsIterable,je=Se.encodeAsAsyncIterable,{NEVER:Be,ALWAYS:Ve,DECIMAL_ROUND:Pe,DECIMAL_FIT:_e}=X,Re=512,Fe=1024,Te=2048;e.ALWAYS=Ve,e.DECIMAL_FIT=_e,e.DECIMAL_ROUND=Pe,e.Decoder=k,e.Encoder=ge,e.FLOAT32_OPTIONS=X,e.NEVER=Be,e.REUSE_BUFFER_MODE=Re,e.Tag=R,e.addExtension=function(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");re.unshift(e.Class),te.unshift(e)}!function(e){b[e.tag]=e.decode}(e)},e.clearSource=Y,e.decode=G,e.decodeIter=function(e,t={}){if(!e||"object"!=typeof e)throw new Error("first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise");const r=new k(t);let n;const i=e=>{let t;n&&(e=Buffer.concat([n,e]),n=void 0);try{t=r.decodeMultiple(e)}catch(r){if(!r.incomplete)throw r;n=e.slice(r.lastPosition),t=r.values}return t};return"function"==typeof e[Symbol.iterator]?function*(){for(const t of e)yield*i(t)}():"function"==typeof e[Symbol.asyncIterator]?async function*(){for await(const t of e)yield*i(t)}():void 0},e.decodeMultiple=Q,e.encode=Me,e.encodeAsAsyncIterable=je,e.encodeAsIterable=xe,e.encodeIter=function(e,t={}){if(e&&"object"==typeof e){if("function"==typeof e[Symbol.iterator])return function*(e,t){const r=new ge(t);for(const t of e)yield r.encode(t)}(e,t);if("function"==typeof e.then||"function"==typeof e[Symbol.asyncIterator])return async function*(e,t){const r=new ge(t);for await(const t of e)yield r.encode(t)}(e,t);throw new Error("first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise")}throw new Error("first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable")},e.isNativeAccelerationEnabled=!1,e.roundFloat32=function(e){P[0]=e;let t=q[(127&_[3])<<1|_[2]>>7];return(t*e+(e>0?.5:-.5)>>0)/t},e.setSizeLimits=function(e){e.maxMapSize&&(y=e.maxMapSize),e.maxArraySize&&(h=e.maxArraySize),e.maxObjectSize&&e.maxObjectSize}}));
(function(){function t(t=100){async function r(){"scheduler"in window&&"yield"in scheduler?await scheduler.yield():await new Promise(t=>{i.push(t),o.port2.postMessage(null)}),n=Date.now(),a=null}let n=0,a=null;const o=new MessageChannel,i=[];return o.port1.onmessage=()=>i.shift()?.(),function(o=!1){const i=Date.now();return!o&&i-n<=t?null:(a||(a=r()),a)}}async function r(t,r){const n=await crypto.subtle.importKey("raw",p.encode(t),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:6e5,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function n(t,r,n){const{include:a,exclude:o}=n;if(o&&o[t]){const n=o[t];if("function"==typeof n){if(n(r))return!1;}else if(Array.isArray(n)&&n.some(n=>r===n||r.startsWith(n+"/")))return!1}if(a&&a[t]){const n=a[t];if("function"==typeof n)return n(r);if(Array.isArray(n)&&0<n.length)return n.some(n=>r===n||r.startsWith(n+"/"))}return!0}function a(t,r,n=new WeakMap,a=new Map){if(!t||"object"!=typeof t)return t;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)||t instanceof Date)return t;if(n.has(t))return n.get(t);if(t instanceof Blob){if(a.has(t))return a.get(t);const n=(h++).toString(16);r.push({uuid:n,blob:t});const o={__le_blob_ref:n,type:t.type,size:t.size};return a.set(t,o),o}let o;if(Array.isArray(t)){const i=Object.keys(t),s=i.length<t.length||i.some(t=>isNaN(t));if(s){o={__le_sparse:!0,length:t.length,data:{}},n.set(t,o);for(const s of i)o.data[s]=LittleExport.prepForCBOR(t[s],r,n,a)}else{o=Array(t.length),n.set(t,o);for(let s=0;s<t.length;s++)o[s]=LittleExport.prepForCBOR(t[s],r,n,a)}}else for(const i in o={},n.set(t,o),t)Object.prototype.hasOwnProperty.call(t,i)&&(o[i]=LittleExport.prepForCBOR(t[i],r,n,a));return o}async function o(t,r){if(!t||"object"!=typeof t)return t;if(t.__le_blob_ref){if(!r)return null;try{const n=await r.getFileHandle(t.__le_blob_ref),a=await n.getFile();return a.slice(0,a.size,t.type)}catch(t){return null}}if(t.__le_sparse){const n=Array(t.length);for(const a in t.data)n[a]=await o(t.data[a],r);return n}if(Array.isArray(t)){const n=Array(t.length);for(let a=0;a<t.length;a++)n[a]=await LittleExport.restoreFromCBOR(t[a],r);return n}if(t.constructor===Object){const a={};for(const n in t)a[n]=await LittleExport.restoreFromCBOR(t[n],r);return a}return t}function i(t,r){const n=new TextEncoder;let a=new Uint8Array(0);const o=(t,r)=>{if(null==r)return;const o=` ${t}=${r+""}\n`,i=n.encode(o);let s=i.length,d=s+"";for(;;){const t=i.length+d.length;if(t===s)break;s=t,d=s+""}const l=n.encode(`${d}${o}`),c=new Uint8Array(a.length+l.length);c.set(a),c.set(l,a.length),a=c};return o("path",t),8589934591<r&&o("size",r),a}function s(t,r,n,a="0",o="000644"){const i=8589934591<r?0:r,s=S.slice(0);s[156]=a.charCodeAt(0);const d=p.encode(t),l=Math.min(d.length,100);s.set(d.subarray(0,l),0),o&&p.encodeInto(o.padEnd(7,"\0"),s.subarray(100,108));const c=(t,r,n)=>{const a=Math.floor(t).toString(8).padStart(n-1,"0");return a.length>=n?void LittleExport.warn("PAX attempted to write octal that was too long (due to either sizes or timestamp)."):void(p.encodeInto(a,s.subarray(r,r+n-1)),s[r+n-1]=0)};c(i,124,12),c(n,136,12);let u=0;for(let d=0;512>d;d++)u+=s[d];const f=u.toString(8).padStart(6,"0");return p.encodeInto(f,s.subarray(148)),s[154]=0,s[155]=32,s}function d(t){const r=m.decode(t.slice(148,156)).replace(/\0/g,"").trim(),n=parseInt(r,8);if(isNaN(n))return!1;let a=0;for(let r=0;512>r;r++)a+=148<=r&&156>r?32:t[r];return a===n}async function l(r={}){function a(t,r,n){return w?R(t,r,n):f.PROCESS}async function o(t,r){try{return await t()}catch(t){if(l.onerror&&l.onerror(t),S)return y(`Error: ${r} - ${t.message}`),null;throw t}}async function i(t,r,o,s){if(E)return!1;if(void 0===C[s])if(w){let r=a(t);if(r&&"function"==typeof r.then&&(r=await r),C[s]=r,C[s]===f.ABORT)return E=!0,!1}else C[s]=f.PROCESS;if(C[s]===f.SKIP)return!1;if(C[s]===f.TRUST)return!0;if(w&&r){F[s]||(F[s]=new Set);for(let t=1;t<=r.length;t++){const n=r.slice(0,t).join("/");if(F[s].has(n))return!0}let n=a(t,r,null);return(n&&"function"==typeof n.then&&(n=await n),n===f.ABORT)?(E=!0,!1):n!==f.SKIP&&(n===f.TRUST&&F[s].add(r.join("/")),!0)}return!!w||n(s,o,l)}const s=window.CBOR,l={logSpeed:100,cborExtensionName:"cbor",...r},c=l.decoder||new s.Decoder({structuredClone:!0,bundleStrings:!0,copyBuffers:!1,...l.cborOptions}),h=l.cborExtensionName;let g=l.source;g||(await new Promise(t=>{const r=document.createElement("input");r.type="file",r.onchange=r=>{const n=r.target.files[0];t(n)},r.click()}));const y=l.logger||(()=>{}),b=t(l.logSpeed),S=!1!==l.graceful,w="function"==typeof l.onVisit,R=l.onVisit;let E=!1,T=null;const C={},F={};let I={category:"",detail:""};const v={};let A=!1;try{async function t(t){for(;!N.has(t)&&!j;){const{value:t,done:r}=await W.read();r?j=!0:N.push(t)}return N.has(t)}async function S(r){for(let n=r;0<n&&(0!==N.totalSize||j||(await t(1)),0!==N.totalSize);){const t=Math.min(n,N.totalSize);N.read(t),n-=t}}async function k(t,r){try{for(let n=r;0<n;){const a=b();if(a){let t=`Importing ${I.category}: ${(K/1e6).toFixed(2)} MB`;t+=1e6<r?` (${I.detail}: ${((r-n)/1e6).toFixed(1)}/${(r/1e6).toFixed(1)} MB)`:` (${I.detail})`,y(t),await a}if(0<N.totalSize){const r=Math.min(n,N.totalSize);await N.consume(r,async r=>{await t.write(r),n-=r.byteLength})}else{let{value:r,done:a}=await W.read();if(a)throw new Error("Unexpected EOF.");r.byteLength<=n?(await t.write(r),n-=r.byteLength):(await t.write(r.subarray(0,n)),N.push(r.subarray(n)),n=0)}}}catch(r){try{await t.abort()}catch(t){}throw r}finally{try{await t.close()}catch(t){}}}function R(t){const r={};for(let n=0;n<t.length;){let a=-1;for(let r=n;r<t.length;r++)if(32===t[r]){a=r;break}if(-1===a)break;const o=m.decode(t.subarray(n,a)),i=parseInt(o,10);if(isNaN(i))break;const s=t.subarray(n,n+i),d=m.decode(s),l=d.indexOf("=");if(-1!==l){const t=d.indexOf(" "),n=d.slice(t+1,l),a=d.slice(l+1,-1);r[n]=a}n+=i}return r}let F;if("string"==typeof g){const t=await fetch(g,r.fetchInit);if(!t.ok)throw new Error("Fetching of URL failed.");F=t.body}else if(g&&"function"==typeof g.stream)F=g.stream();else throw new Error("Invalid source.");const B=F.getReader(),x=[];let L=0;for(;8>L;){const{value:t,done:r}=await B.read();if(r)break;x.push(t),L+=t.byteLength}B.releaseLock();let K=0;const z=new ReadableStream({async start(t){for(const r of x)t.enqueue(r);const r=F.getReader();try{for(;;){const{value:n,done:a}=await r.read();if(a)break;t.enqueue(n)}t.close()}catch(r){t.error(r)}}}),D=new Uint8Array(8);if(0<L){let t=0;for(const r of x){const n=8-t;if(0>=n)break;const a=Math.min(n,r.byteLength);D.set(r.subarray(0,a),t),t+=a}}const U=m.decode(D.slice(0,6));let _;if("LE_ENC"===U){if(null===l.password)throw new Error("A password is required to decrypt this data.");let t=l.password||prompt("Enter the password:");if(!t)throw new Error("A password is required to decrypt this data.");_=new O(z,t,b).readable().pipeThrough(new DecompressionStream("gzip"))}else _=31===D[0]&&139===D[1]?z.pipeThrough(new DecompressionStream("gzip")):z;_=_.pipeThrough(new TransformStream({transform(t,r){K+=t.byteLength,r.enqueue(t)}}));const W=_.getReader(),N=new P;let j=!1,q=0;T=!1!==l.opfs&&navigator.storage?await navigator.storage.getDirectory():null;const H="._littleexport_temp_"+crypto.randomUUID();let M;try{T&&(M=await T.getDirectoryHandle(H,{create:!0}))}catch(t){}const V=new Set;for(let r=null;!E;){const g=await t(512);if(!g){if(!1!==l.verifyFile&&!A)if(0<q&&0===N.totalSize)LittleExport.warn("Warning: Stream ended without standard EOF blocks; import likely successful.");else throw new Error("Archive truncated: Stream ended prematurely.");break}const P=N.read(512);if(!1!==l.verifyFile&&0===P[0]&&P.every(t=>0===t)){A=!0;continue}if(!1!==l.verifyFile&&!d(P)){if(0<q&&0===N.totalSize&&j)break;throw new Error("Corrupt TAR header: Checksum mismatch.")}let O=m.decode(P.slice(0,100)).replace(/\0/g,"").trim();const F=P[156],B=m.decode(P.slice(124,136)).replace(/\0/g,"").trim(),x=parseInt(B,8)||0,L=(512-x%512)%512;if(120===F){if(!(await t(x)))throw new Error("Unexpected EOF.");const n=N.read(x);await S(L),r=R(n);continue}let z=x;if(r&&(r.path&&(O=r.path),r.size&&(z=parseInt(r.size,10)),r=null),q++,O.startsWith("data/idb/")){I.category="IndexedDB";const t=O.split("/");I.detail=t[2]?decodeURIComponent(t[2]):"data"}else if(O.startsWith("data/cache/")){I.category="Cache";const t=O.split("/");I.detail=t[2]?decodeURIComponent(t[2]):"item"}else O.startsWith("opfs/")?(I.category="OPFS",I.detail=O.replace("opfs/","")):O.startsWith("data/blobs/")?(I.category="Blobs",I.detail="Re-linking Data"):(I.category="Config",I.detail=O);const D=b();if(D&&(I.category&&y(`Importing ${I.category}: ${(K/1e6).toFixed(2)} MB (${I.detail})`),await D),O.startsWith("data/")){if(O.startsWith("data/blobs/")){const t=O.split("/").pop();if(M){let r=!1;await o(async()=>{const n=await M.getFileHandle(t,{create:!0});await k(await n.createWritable(),z),r=!0},`Blob ${t}`),r||(await S(z))}else await S(z);await S(L);continue}else{if(0===z){await S(L);continue}if(!(await t(z)))throw new Error("Unexpected EOF for metadata.");const r=N.read(z);if("data/ls.json"===O&&!1!==l.localStorage){if(await i(u.LS,null,null,"localStorage")){const t=JSON.parse(m.decode(r)),o=C.localStorage===f.TRUST;for(const r in t){if(E)break;let i=o;if(!i)if(w){let n=a(u.LS,[r],{value:t[r]});if(n&&"function"==typeof n.then&&(n=await n),n===f.ABORT){E=!0;break}i=n!==f.SKIP}else i=n("localStorage",r,l);i&&localStorage.setItem(r,t[r])}}}else if("data/ss.json"===O&&!1!==l.sessionStorage){if(await i(u.SS,null,null,"sessionStorage")){const t=JSON.parse(m.decode(r)),o=C.sessionStorage===f.TRUST;for(const r in t){if(E)break;let i=o;if(!i)if(w){let n=a(u.SS,[r],{value:t[r]});if(n&&"function"==typeof n.then&&(n=await n),n===f.ABORT){E=!0;break}i=n!==f.SKIP}else i=n("sessionStorage",r,l);i&&sessionStorage.setItem(r,t[r])}}}else if("data/cookies.json"===O&&!1!==l.cookies){if(await i(u.COOKIE,null,null,"cookies")){const t=JSON.parse(m.decode(r)),o=C.cookies===f.TRUST;for(const r in t){if(E)break;let i=o;if(!i)if(w){let n=a(u.COOKIE,[r],{value:t[r]});if(n&&"function"==typeof n.then&&(n=await n),n===f.ABORT){E=!0;break}i=n!==f.SKIP}else i=n("cookies",r,l);i&&(document.cookie=`${r}=${t[r]}; path=/; max-age=31536000`)}}}else if(O.startsWith("data/custom/")&&l.onCustomItem)await l.onCustomItem(O.replace("data/custom/",""),r);else if(O.startsWith("data/idb/")&&s&&!1!==l.idb){const t=O.split("/"),n=decodeURIComponent(t[2]);if(O.endsWith("schema."+h)){if(!(await i(u.IDB,[n],n,"idb")))continue;const t=c.decode(r);V.add(n),v[n]&&(v[n].close(),delete v[n]),await o(async()=>{await new Promise((r,n)=>{const a=indexedDB.deleteDatabase(t.name);a.onsuccess=r,a.onerror=()=>n(a.error),a.onblocked=()=>n(new Error(`Database ${t.name} deletion blocked.`))}),await new Promise((r,n)=>{const a=indexedDB.open(t.name,t.version);a.onupgradeneeded=r=>{const n=r.target.result;t.stores.forEach(t=>{if(!n.objectStoreNames.contains(t.name)){const r=n.createObjectStore(t.name,{keyPath:t.keyPath,autoIncrement:t.autoIncrement});t.indexes.forEach(t=>r.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multiEntry}))}})},a.onsuccess=t=>{t.target.result.close(),r()},a.onerror=n,a.onblocked=()=>n(new Error(`Database ${t.name} opening blocked.`))})},`IDB schema ${n}`)}else{const a=decodeURIComponent(t[3]);if(!V.has(n))continue;if(!(await i(u.IDB,[n,a],`${n}/${a}`,"idb")))continue;const s=c.decode(r),[d,l]=await LittleExport.restoreFromCBOR(s,M);if(!v[n]){const t=await o(async()=>await new Promise((t,r)=>{const a=indexedDB.open(n),o=setTimeout(()=>r(new Error(`Database ${n} timed out.`)),5e3);a.onblocked=()=>{clearTimeout(o),r(new Error(`Database ${n} opening blocked.`))},a.onsuccess=()=>{clearTimeout(o),t(a.result)},a.onerror=()=>{clearTimeout(o),r(a.error)}}),`Opening IDB ${n}`);if(!t)continue;v[n]=t}await o(async()=>{const t=v[n].transaction(a,"readwrite"),r=t.objectStore(a);for(let t=0;t<d.length;t++)r.put(l[t],r.keyPath?void 0:d[t]);await new Promise((r,n)=>{t.oncomplete=r,t.onerror=()=>n(t.error),t.onabort=()=>n(new Error("Transaction aborted."))})},`IDB ${n}/${a}`)}}else if(O.startsWith("data/cache/")&&s&&!1!==l.cache){const t=O.split("/"),n=decodeURIComponent(t[2]);(await i(u.CACHE,[n],n,"cache"))&&(await o(async()=>{const t=c.decode(r),a=await caches.open(n),o=await LittleExport.restoreFromCBOR(t.data,M),i=o instanceof Blob?o:new Blob([o]),s=new Response(i,{status:t.meta.status,headers:t.meta.headers});await a.put(t.meta.url,s)},`Cache ${n}`))}}}else if(!1!==l.opfs){const t=O.startsWith("opfs/")?O.slice(5):O,r=t.endsWith("/")||53===P[156],n=t.replace(/\/$/,""),a=n.split("/").filter(t=>t.length);if(0<a.length){const t=[...a];(await i(u.OPFS,t,n,"opfs"))?await o(async()=>{let t=T;if(r)for(const r of a)t=await t.getDirectoryHandle(r,{create:!0});else{const r=a[a.length-1],n=a.slice(0,-1);for(const r of n)t=await t.getDirectoryHandle(r,{create:!0});const o=await t.getFileHandle(r,{create:!0});if(0<z)await k(await o.createWritable(),z);else{const t=await o.createWritable();await t.close()}}},`OPFS ${n}`):await S(z)}else await S(z)}else await S(z);await S(L)}Object.values(v).forEach(t=>t.close()),E||y("Import complete!")}catch(t){if(Object.values(v).forEach(t=>{try{t.close()}catch(t){}}),y(`Error: ${t.message}`),l.onerror&&l.onerror(t),!S)throw t}finally{if(T)try{await T.removeEntry(TEMP_BLOB_DIR,{recursive:!0})}catch(t){}}}function c(t,r,n={}){const{readable:a,writable:o}=new TransformStream,i=new k(o,r),s=n.pathPrefix||"",l=s&&!s.endsWith("/")?s+"/":s;return(async()=>{try{if(window.FileSystemDirectoryHandle&&t instanceof FileSystemDirectoryHandle){async function r(t,o){for await(const[r,i]of t.entries()){if("directory"===i.kind&&"PaxHeaders"===r)continue;const t=o?`${o}/${r}`:r;"file"===i.kind?n.push({entry:i,fullPath:t}):a.push({entry:i,fullPath:t})}n.sort((t,r)=>t.fullPath.includes("schema.")&&!r.fullPath.includes("schema.")?-1:!t.fullPath.includes("schema.")&&r.fullPath.includes("schema.")?1:t.fullPath.localeCompare(r.fullPath));for(const r of n){const t=await r.entry.getFile();await i.writeStream(l+r.fullPath,t.size,t.stream())}for(const n of a)await i.writeDir(l+n.fullPath),await r(n.entry,n.fullPath)}const n=[],a=[];await r(t,"")}else if(t instanceof FileList||Array.isArray(t)&&t[0]instanceof File){const r=Array.from(t).sort((t,r)=>{const n=t.webkitRelativePath||t.name,a=r.webkitRelativePath||r.name;return n.includes("schema.")&&!a.includes("schema.")?-1:!n.includes("schema.")&&a.includes("schema.")?1:n.localeCompare(a)}),n=r.find(t=>t.webkitRelativePath&&t.webkitRelativePath.includes("/"))||r[0],a=n?n.webkitRelativePath:"",o=a&&a.includes("/")?a.split("/")[0]+"/":"";for(const t of r){let r=t.webkitRelativePath;r&&r.startsWith(o)&&(r=r.slice(o.length)),r||(r=t.name),await i.writeStream(l+r,t.size,t.stream())}}await i.close()}catch(t){try{await o.abort(e)}catch(t){}}})(),a}const u={OPFS:1,IDB:2,LS:4,SS:8,COOKIE:16,CACHE:32},f={SKIP:0,PROCESS:1,TRUST:2,ABORT:3};let h=0;const g=4194304,y=65536,p=new TextEncoder,m=new TextDecoder("utf-8",{fatal:!1}),b={USTAR_MAGIC:new Uint8Array([117,115,116,97,114,0]),USTAR_VER:new Uint8Array([48,48]),EMPTY_SPACE:new Uint8Array(8).fill(32)},S=new Uint8Array(512);(function(){const t=(t,r)=>p.encodeInto(t,S.subarray(r));t("000644 \0",100),t("000000 \0",108),t("000000 \0",116),S.set(b.EMPTY_SPACE,148),S[156]=48,S.set(b.USTAR_MAGIC,257),S.set(b.USTAR_VER,263)})();class k{constructor(t,r){this.writer=t.getWriter(),this.yielder=r,this.pos=0,this.time=Math.floor(Date.now()/1e3),this.buffer=new Uint8Array(y),this.bufferOffset=0}async writeEntry(t,r){const n="string"==typeof r?p.encode(r):r,a=n.byteLength;this.onFileProgress&&this.onFileProgress(0,a),await this.smartWrite(t,a,async()=>{await this.write(n)}),this.onFileProgress&&this.onFileProgress(a,a)}async writeStream(t,r,n){let a=0;await this.flush(),await this.smartWrite(t,r,async()=>{const t=n.getReader();try{for(;;){const{done:n,value:o}=await t.read();if(n)break;if(o){const t=r-a;if(0>=t)continue;const n=o.byteLength>t?o.subarray(0,t):o;await this.write(n),a+=n.byteLength,this.onFileProgress&&this.onFileProgress(a,r)}const i=this.yielder();i&&(await i)}if(a<r){const t=r-a,n=new Uint8Array(t);await this.write(n)}}finally{t.releaseLock()}})}async smartWrite(t,r,n){const a=p.encode(t),o=100<a.length||8589934591<r;if(o){const n=i(t,r),a="PaxHeaders/"+(50<t.length?t.slice(0,50):t);await this.write(s(a,n.length,this.time,"x")),await this.write(n),await this.pad()}await this.write(s(t,r,this.time,0===r&&t.endsWith("/")?"5":"0")),n&&(await n()),await this.pad()}async writeDir(t){t.endsWith("/")||(t+="/");const r=p.encode(t),n=100<r.length;if(n){const r=i(t,0),n="PaxHeaders/"+(50<t.length?t.slice(0,50):t);await this.write(s(n,r.length,this.time,"x")),await this.write(r),await this.pad()}const a=s(t,0,this.time,"5","000755");await this.write(a)}async write(t){const r=t.byteLength;r>=y?(await this.flush(),await this.writer.write(t)):this.bufferOffset+r>y?(await this.flush(),this.buffer.set(t,0),this.bufferOffset=r):(this.buffer.set(t,this.bufferOffset),this.bufferOffset+=r),this.pos+=r}async pad(){const t=(512-this.pos%512)%512;0<t&&(await this.write(new Uint8Array(t)))}async flush(){0<this.bufferOffset&&(await this.writer.write(this.buffer.slice(0,this.bufferOffset)),this.bufferOffset=0)}async close(){await this.write(new Uint8Array(1024)),await this.flush(),await this.writer.close()}}class w{constructor(t,n){this.salt=n,this.keyPromise=r(t,n),this.chunks=[],this.currentSize=0}async start(t){t.enqueue(p.encode("LE_ENC")),t.enqueue(this.salt),await this.encryptAndPush(new Uint8Array(0),t,await this.keyPromise)}async transform(t,r){if(this.chunks.push(t),this.currentSize+=t.byteLength,this.currentSize>=g){const t=new Uint8Array(this.currentSize);let n=0;for(const r of this.chunks)t.set(r,n),n+=r.byteLength;const a=await this.keyPromise;let o=0;for(;o+g<=t.length;)await this.encryptAndPush(t.subarray(o,o+g),r,a),o+=g;const i=t.subarray(o);this.chunks=0<i.length?[i]:[],this.currentSize=i.length}}async flush(t){if(0<this.currentSize){const r=new Uint8Array(this.currentSize);let n=0;for(const t of this.chunks)r.set(t,n),n+=t.byteLength;await this.encryptAndPush(r,t,await this.keyPromise)}}async encryptAndPush(t,r,n){const a=crypto.getRandomValues(new Uint8Array(12)),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},n,t),i=new DataView(new ArrayBuffer(4));i.setUint32(0,o.byteLength,!0),r.enqueue(a),r.enqueue(new Uint8Array(i.buffer)),r.enqueue(new Uint8Array(o))}}class P{constructor(){this.chunks=[],this.totalSize=0,this.offset=0}push(t){t&&0!==t.byteLength&&(this.chunks.push(t),this.totalSize+=t.byteLength)}has(t){return this.totalSize>=t}_internalConsume(t,r){for(let n=0;n<t&&0<this.chunks.length;){const a=this.chunks[0],o=a.byteLength-this.offset,i=t-n,s=Math.min(o,i);r(a.subarray(this.offset,this.offset+s)),this.offset+=s,this.offset>=a.byteLength&&(this.chunks.shift(),this.offset=0),this.totalSize-=s,n+=s}}read(t){if(0===t)return new Uint8Array(0);if(this.totalSize<t)throw new Error("Insufficient chunk data.");if(0<this.chunks.length&&this.chunks[0].byteLength-this.offset>=t){const r=this.chunks[0].subarray(this.offset,this.offset+t);return this.offset+=t,this.offset>=this.chunks[0].byteLength&&(this.chunks.shift(),this.offset=0),this.totalSize-=t,r}const r=new Uint8Array(t);let n=0;return this._internalConsume(t,t=>{r.set(t,n),n+=t.byteLength}),r}async consume(t,r){for(let n=t;0<n&&0<this.chunks.length;){const t=this.chunks[0],a=t.byteLength-this.offset,o=Math.min(a,n);await r(t.subarray(this.offset,this.offset+o)),this.offset+=o,this.offset>=t.byteLength&&(this.chunks.shift(),this.offset=0),this.totalSize-=o,n-=o}}}class O{constructor(t,r,n){this.stream=t,this.password=r,this.yielder=n,this.buffer=new P}readable(){async function t(t){for(;!a.buffer.has(t);){const{value:t,done:r}=await o.read();if(r)return!1;a.buffer.push(t)}return!0}const a=this;let o;return new ReadableStream({async start(n){o=a.stream.getReader();try{if(!(await t(22)))throw new Error("Not an encrypted archive.");const i=m.decode(a.buffer.read(6));if("LE_ENC"!==i)throw new Error("Not an encrypted archive.");const s=a.buffer.read(16),d=await r(a.password,s);if(!(await t(16)))throw new Error("Corrupt header.");const l=a.buffer.read(12),c=a.buffer.read(4),u=new DataView(c.buffer,c.byteOffset,c.byteLength).getUint32(0,!0);if(16!==u||!(await t(u)))throw new Error("Corrupt header.");const f=a.buffer.read(u);try{await crypto.subtle.decrypt({name:"AES-GCM",iv:l},d,f)}catch(t){throw new Error("Incorrect password or corrupt file.")}for(;;){const t=a.yielder();if(t&&(await t),!a.buffer.has(16)){const{value:t,done:r}=await o.read();if(r){if(0===a.buffer.totalSize)break;throw new Error("Truncated encrypted stream.")}a.buffer.push(t);continue}const r=a.buffer.read(12),i=a.buffer.read(4),s=new DataView(i.buffer,i.byteOffset,i.byteLength).getUint32(0,!0);for(;!a.buffer.has(s);){const{value:t,done:r}=await o.read();if(r)throw new Error("Unexpected EOF in ciphertext.");a.buffer.push(t);const n=a.yielder();n&&(await n)}const l=a.buffer.read(s),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},d,l),u=a.yielder(!0);u&&(await u),n.enqueue(new Uint8Array(c))}n.close()}catch(t){n.error(t)}finally{o.releaseLock()}}})}}window.LittleExport={importData:l,exportData:async function(r={}){function a(t,r,n){return m?b(t,r,n):f.PROCESS}async function o(t,r){try{return await t()}catch(t){if(s.onerror&&s.onerror(t),y)return c(`Error: ${r} - ${t.message}`),null;throw t}}h=0;const i=window.CBOR,s={fileName:"archive",logSpeed:100,customItems:[],include:{},exclude:{},cborExtensionName:"cbor",...r},d=s.encoder||new i.Encoder({structuredClone:!0,copyBuffers:!1,bundleStrings:!0,...s.cborOptions}),l=s.cborExtensionName,c=s.logger||(()=>{}),g=t(s.logSpeed),y=!1!==s.graceful,m="function"==typeof s.onVisit,b=s.onVisit;let S=!1;const P={category:"",detail:""};let O,R=[],E=s.fileName.includes(".")?s.fileName:s.password?`${s.fileName}.enc`:`${s.fileName}.tar.gz`;if(window.showSaveFilePicker&&!1!==s.download)try{const t=await window.showSaveFilePicker({suggestedName:E});O=await t.createWritable()}catch(t){if("AbortError"===t.name)return void c("Export cancelled.");LittleExport.warn("FileSystem picker failed, falling back.")}O||(O=new WritableStream({write(t){R.push(t)},close(){}}));let T=0;const C=new TransformStream({async transform(t,r){T+=t.byteLength;const n=g();if(n){if(P.category)if("Finishing"===P.category)c("Finishing...");else{let t=`Exporting ${P.category}: ${(T/1e6).toFixed(2)} MB`;t+=1e6<v.total?` (${P.detail}: ${(v.written/1e6).toFixed(1)}/${(v.total/1e6).toFixed(1)} MB)`:` (${P.detail})`,c(t)}await n}r.enqueue(t)}}),F=new CompressionStream("gzip");let I=F.readable;if(s.password){P.category="Setup",P.detail="Encrypting...";const t=crypto.getRandomValues(new Uint8Array(16));I=I.pipeThrough(new TransformStream(new w(s.password,t)))}let v={written:0,total:0};const A=I.pipeThrough(C).pipeTo(O),B=new k(F.writable,g);B.onFileProgress=(t,r)=>{v.written=t,v.total=r};try{for(const t of s.customItems){if(S)break;P.category="custom",P.detail=t.path;const r=`data/custom/${t.path}`;t.data instanceof Blob?await B.writeStream(r,t.data.size,t.data.stream()):await B.writeEntry(r,"string"==typeof t.data?t.data:JSON.stringify(t.data))}if(!S&&!1!==s.opfs&&navigator.storage){let t=a(u.OPFS);if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT&&(S=!0),!S&&t!==f.SKIP){async function r(t,i,d){try{for await(const l of t.values()){if(S)return;v.written=0,v.total=0;const t=[...i,l.name],c=t.join("/");let h=d;if(P.detail=c,!d)if(m){let r=a(u.OPFS,t,{kind:l.kind,handle:l});if(r&&"function"==typeof r.then&&(r=await r),h=r,h===f.ABORT)return void(S=!0);if(h===f.SKIP)continue}else{if(!n("opfs",c,s))continue;h=f.PROCESS}const y=h===f.TRUST;"file"===l.kind?await o(async()=>{const t=await l.getFile();await B.writeStream(`opfs/${c}`,t.size,t.stream())},`OPFS file ${c}`):(await B.writeDir(`opfs/${c}`),await r(l,t,!!y&&f.TRUST));const b=g();b&&(await b)}}catch(t){if(c(`Error: accessing OPFS folder /${i.join("/")} failed (${t.message})`),s.onerror&&s.onerror(t),!y)throw t}}P.category="OPFS";const i=await navigator.storage.getDirectory(),d=t===f.TRUST;await r(i,[],!!d&&f.TRUST)}v.written=0,v.total=0}if(!S&&!1!==s.idb&&window.indexedDB&&i){let t=a(u.IDB);if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT&&(S=!0),!S&&t!==f.SKIP){P.category="IndexedDB";const r=t===f.TRUST,i=await window.indexedDB.databases();for(const{name:t,version:c}of i){if(S)break;v.written=0,v.total=0,P.detail=t;const i=encodeURIComponent(t),h=await o(async()=>await new Promise((r,n)=>{const a=indexedDB.open(t),o=setTimeout(()=>n(new Error(`Database ${t} timed out.`)),5e3);a.onblocked=()=>{clearTimeout(o),n(new Error(`Database ${t} blocked.`))},a.onsuccess=()=>{clearTimeout(o),r(a.result)},a.onerror=()=>{clearTimeout(o),n(a.error)}}),`Opening IDB ${t}`);if(!h)continue;let y=r?f.TRUST:f.PROCESS;if(!r)if(m){let r=a(u.IDB,[t],{database:h});if(r&&"function"==typeof r.then&&(r=await r),y=r,y===f.ABORT){S=!0,h.close();break}if(y===f.SKIP){h.close();continue}}else if(!n("idb",t,s)){h.close();continue}const p=y===f.TRUST;try{const r=Array.from(h.objectStoreNames);if(0===r.length){await B.writeEntry(`data/idb/${i}/schema.${l}`,d.encode({name:t,version:c,stores:[]}));continue}const y=[],b=h.transaction(r,"readonly");for(const t of r){const r=b.objectStore(t);y.push({name:t,keyPath:r.keyPath,autoIncrement:r.autoIncrement,indexes:Array.from(r.indexNames).map(t=>{const n=r.index(t);return{name:n.name,keyPath:n.keyPath,unique:n.unique,multiEntry:n.multiEntry}})})}await B.writeEntry(`data/idb/${i}/schema.${l}`,d.encode({name:t,version:c,stores:y}));for(const c of r){if(S)break;let r=p?f.TRUST:f.PROCESS;if(!p)if(m){let n=a(u.IDB,[t,c],{database:h});if(n&&"function"==typeof n.then&&(n=await n),r=n,r===f.ABORT){S=!0;break}if(r===f.SKIP)continue}else if(!n("idb",`${t}/${c}`,s))continue;P.detail=`${t}/${c}`;let y=null,b=0,k=!0;for(;k&&!S;){const r=await o(async()=>{return await new Promise((t,r)=>{const n=h.transaction(c,"readonly"),a=n.objectStore(c),o=null===y?null:IDBKeyRange.lowerBound(y,!0),i=a.openCursor(o),s=[],d=[];i.onsuccess=r=>{const n=r.target.result;n&&s.length<25?(s.push(n.key),d.push(n.value),y=n.key,n.continue()):t({keys:s,values:d,done:!n})},i.onerror=()=>r(i.error)})},`Reading IDB ${t}/${c}`);if(!r)break;if(k=!r.done,0<r.keys.length){const t=[];for(let n=0;n<r.values.length;n++){const a=[],o=LittleExport.prepForCBOR(r.values[n],a);t.push(o);for(const t of a)await B.writeStream(`data/blobs/${t.uuid}`,t.blob.size,t.blob.stream())}await B.writeEntry(`data/idb/${i}/${encodeURIComponent(c)}/${b++}.${l}`,d.encode([r.keys,t]));const n=g();n&&(await n)}}}}finally{h.close()}}}v.written=0,v.total=0}if(!S&&!1!==s.localStorage){let t=a(u.LS);if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT&&(S=!0),!S&&t!==f.SKIP){P.category="Storage";const r={},o=t===f.TRUST;for(let t=0;t<localStorage.length&&!S;t++){const i=localStorage.key(t);P.detail=`localStorage: ${i}`;let d=o;if(!d)if(m){let t=a(u.LS,[i],{value:localStorage.getItem(i)});if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT){S=!0;break}d=t!==f.SKIP}else d=n("localStorage",i,s);d&&(r[i]=localStorage.getItem(i))}!S&&0<Object.keys(r).length&&(await B.writeEntry("data/ls.json",JSON.stringify(r)))}}if(!S&&!1!==s.sessionStorage){let t=a(u.SS);if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT&&(S=!0),!S&&t!==f.SKIP){P.category="Storage";const r={},o=t===f.TRUST;for(let t=0;t<sessionStorage.length&&!S;t++){const i=sessionStorage.key(t);P.detail=`sessionStorage: ${i}`;let d=o;if(!d)if(m){let t=a(u.SS,[i],{value:sessionStorage.getItem(i)});if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT){S=!0;break}d=t!==f.SKIP}else d=n("sessionStorage",i,s);d&&(r[i]=sessionStorage.getItem(i))}!S&&0<Object.keys(r).length&&(await B.writeEntry("data/ss.json",JSON.stringify(r)))}}if(!S&&!1!==s.cookies){let t=a(u.COOKIE);if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT&&(S=!0),!S&&t!==f.SKIP){P.category="Storage";const r={},o=t===f.TRUST,i=document.cookie.split(";").map(t=>t.trim()).filter(Boolean);for(const t of i){if(S)break;const i=t.indexOf("="),d=-1<i?t.slice(0,i).trim():t.trim(),l=-1<i?t.slice(i+1).trim():"";if(!d)continue;P.detail=`Cookie: ${d}`;let c=o;if(!c)if(m){let t=a(u.COOKIE,[d],{value:l});if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT){S=!0;break}c=t!==f.SKIP}else c=n("cookies",d,s);c&&(r[d]=l)}!S&&0<Object.keys(r).length&&(await B.writeEntry("data/cookies.json",JSON.stringify(r)))}}if(!S&&!1!==s.cache&&window.caches&&i){let t=a(u.CACHE);if(t&&"function"==typeof t.then&&(t=await t),t===f.ABORT&&(S=!0),!S&&t!==f.SKIP){P.category="Cache";const r=await caches.keys(),i=t===f.TRUST;for(const t of r){if(S)break;v.written=0,v.total=0;let r=i;if(!r)if(m){let n=a(u.CACHE,[t],null);if(n&&"function"==typeof n.then&&(n=await n),n===f.ABORT){S=!0;break}r=n!==f.SKIP}else r=n("cache",t,s);if(!r)continue;P.detail=t;const c=g();c&&(await c),await o(async()=>{const r=await caches.open(t);for(const n of await r.keys()){const a=await r.match(n);if(!a)continue;const o=await a.blob(),i=btoa(n.url).slice(0,50).replace(/\//g,"_"),s=[],c=LittleExport.prepForCBOR(o,s);for(const t of s)await B.writeStream(`data/blobs/${t.uuid}`,t.blob.size,t.blob.stream());await B.writeEntry(`data/cache/${encodeURIComponent(t)}/${i}.${l}`,d.encode({meta:{url:n.url,status:a.status,headers:Object.fromEntries(a.headers),type:o.type},data:c}))}},`Cache ${t}`)}}v.written=0,v.total=0}P.category="Finishing",await B.close(),await A;let t=null;if(0<R.length&&(t=new Blob(R,{type:"application/octet-stream"})),!1!==s.download){if(t){const r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=E,n.click(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}return c("Export complete!"),null}return c("Export complete!"),t}catch(t){try{await O.abort(t).catch(()=>{})}catch(t){}if(c(`Error: ${t.message}`),s.onerror&&s.onerror(t),!y)throw t}},deriveKey:r,prepForCBOR:a,restoreFromCBOR:o,importFromFolder:async function(r={}){const n=r,a=t(n.logSpeed);let o=n.logger||(()=>{});const i=t=>l({...n,source:{stream:()=>t}});if(window.showDirectoryPicker&&!1===n.legacy)try{const t=await window.showDirectoryPicker(),r=c(t,a,{pathPrefix:n.pathPrefix});return await i(r)}catch(t){if("AbortError"===t.name)return void o("User cancelled the directory picker.");LittleExport.warn("Directory Picker failed, falling back to legacy input.",t)}return new Promise((t,r)=>{const o=document.createElement("input");o.type="file",o.webkitdirectory=!0,o.multiple=!0,o.style.display="none",document.body.appendChild(o),o.onchange=async()=>{if(!o.files||0===o.files.length)return void t();try{const r=c(o.files,a,{pathPrefix:n.pathPrefix});await i(r),t()}catch(t){r(t)}finally{document.body.removeChild(o)}},o.oncancel=()=>{document.body.removeChild(o),t()},o.click()})},folderToTarStream:c,clearData:async function(t={}){if(0===Object.keys(t).length&&(t={opfs:!0,idb:!0,localStorage:!0,sessionStorage:!0,cookies:!0,cache:!0}),t.opfs&&navigator.storage)try{const t=await navigator.storage.getDirectory();for await(const r of t.keys())await t.removeEntry(r,{recursive:!0})}catch(t){LittleExport.warn("Failed to clear OPFS:",t)}if(t.localStorage)try{localStorage.clear()}catch(t){LittleExport.warn("Failed to clear localStorage:",t)}if(t.sessionStorage)try{sessionStorage.clear()}catch(t){LittleExport.warn("Failed to clear sessionStorage:",t)}if(t.cookies)try{const t=document.cookie.split(";");for(let r=0;r<t.length;r++){const n=t[r],a=n.indexOf("="),o=-1<a?n.trim().substring(0,a):n.trim();document.cookie=`${o}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`,document.cookie=`${o}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=${window.location.hostname}; path=/`;const i=window.location.hostname.split(".");if(2<i.length){const t=i.slice(-2).join(".");document.cookie=`${o}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; domain=.${t}; path=/`}}}catch(t){LittleExport.warn("Failed to clear cookies:",t)}if(t.cache&&window.caches)try{const t=await caches.keys();for(const r of t)await caches.delete(r)}catch(t){LittleExport.warn("Failed to clear cache:",t)}if(t.idb&&window.indexedDB)try{const t=await window.indexedDB.databases();await Promise.all(t.map(t=>new Promise((r,n)=>{const a=indexedDB.deleteDatabase(t.name);a.onsuccess=r,a.onerror=()=>n(a.error),a.onblocked=()=>{LittleExport.warn(`Database ${t.name} deletion blocked.`),r()}})))}catch(t){LittleExport.warn("Failed to clear IndexedDB:",t)}},TYPE:u,warn:console.warn,DECISION:f}})();
const SW_URL="./sw.min.js",ALWAYS_CONFIRM_LEAVE=!1,RFS_PREFIX="rfs",SYSTEM_FILE="rfs_system.json",CHUNK_SIZE=4194304,CONCURRENCY=4,YIELD_TIME=50,IGNORED_NAMES=new Set([".DS_Store","Thumbs.db","desktop.ini","__MACOSX",".AppleDouble",".LSOverride",".Trashes",".TemporaryItems",".Spotlight-V100",".fseventsd",".DocumentRevisions-V100","System Volume Information","$RECYCLE.BIN"]);function isJunk(a){return IGNORED_NAMES.has(a)||a.startsWith("._")||a.startsWith(".Trash-")}window.addEventListener("beforeunload",function(a){if(ALWAYS_CONFIRM_LEAVE||currentlyBusy)return a.preventDefault(),a.returnValue="Changes you made may not be saved.","Changes you made may not be saved."});let folderName,dirHandle,observer,isListingFolders=!1,currentlyBusy=!1,changes=[],showingSync=!1,_registryCache=null,_opfsRoot=null;async function getOpfsRoot(){return _opfsRoot||(_opfsRoot=await navigator.storage.getDirectory()),_opfsRoot}function setUiBusy(a){currentlyBusy!==a&&(currentlyBusy=a,Array.from(document.getElementsByTagName("button")).forEach(a=>a.disabled=currentlyBusy))}function createLogger(a,b){let c=null,d=0;return function(e,f=!1){const g=Date.now();return e!==c&&null!==e&&(c=e,(f||g-d>YIELD_TIME)&&(a.textContent=e,d=g)),b(f)}}const checkYield=function(){let a=0;const b=[],c=new MessageChannel;c.port1.onmessage=()=>{const a=b.shift();a&&a()};const d=()=>new Promise(a=>{b.push(a),c.port2.postMessage(null)});return function(b=!1){return b||Date.now()-a>YIELD_TIME?(a=Date.now(),(async()=>{"scheduler"in window&&"yield"in scheduler?await scheduler.yield():await d()})()):null}}(),logProgress=createLogger(document.getElementById("progress"),checkYield);navigator.storage.persist().then(a=>console.log(a?"Storage persisted.":"Storage not persisted."));async function waitForController(){if(navigator.serviceWorker.controller)return navigator.serviceWorker.controller;await navigator.serviceWorker.register(SW_URL);const a=await navigator.serviceWorker.ready;return navigator.serviceWorker.controller||a.active}async function getRegistry(){return _registryCache?_registryCache:await navigator.locks.request("rfs_registry_lock",{mode:"shared"},async()=>{if(_registryCache)return _registryCache;try{const a=await getOpfsRoot(),b=await a.getFileHandle(SYSTEM_FILE),c=await b.getFile(),d=await c.text();_registryCache=d?JSON.parse(d):{}}catch(a){_registryCache={}}return _registryCache})}async function saveRegistry(a){_registryCache=a,await navigator.locks.request("rfs_registry_lock",{mode:"exclusive"},async()=>{const b=await getOpfsRoot(),c=await b.getFileHandle(SYSTEM_FILE,{create:!0}),d=await c.createWritable();await d.write(JSON.stringify(a)),await d.close()})}async function updateRegistryEntry(a,b){return navigator.locks.request("rfs_registry_lock",{mode:"exclusive"},async()=>{const c=await getOpfsRoot();let d={};try{const a=await c.getFileHandle(SYSTEM_FILE),b=await a.getFile();d=JSON.parse(await b.text())}catch(a){d={}}null===b?delete d[a]:d[a]={...(d[a]||{}),...b,lastModified:Date.now()},_registryCache=d;const e=await c.getFileHandle(SYSTEM_FILE,{create:!0}),f=await e.createWritable();await f.write(JSON.stringify(d)),await f.close(),navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"INVALIDATE_CACHE",folderName:a})})}async function analyzeAndImportFolder(a,b=null){setUiBusy(!0);try{async function c(c){try{if(b){const a=c.join("/");return b.some(b=>b.webkitRelativePath.endsWith(`/${a}`)||b.webkitRelativePath===a)}if("directory"===a.kind){let b=a;for(let a=0;a<c.length-1;a++)b=await b.getDirectoryHandle(c[a]);return await b.getFileHandle(c[c.length-1]),!0}if(a.isDirectory)return new Promise(b=>{a.getFile(c.join("/"),{create:!1},()=>b(!0),()=>b(!1))})}catch(a){return!1}}let d=!1,e=!1,f="";if((await c(["manifest.enc"]))&&(d=!0),d||((await c(["data","custom",SYSTEM_FILE]))?e=!0:(await c(["opfs","rfs",SYSTEM_FILE]))?e=!0:(await c(["custom",SYSTEM_FILE]))?(e=!0,f="data"):(await c(["rfs",SYSTEM_FILE]))?(e=!0,f="opfs"):(await c(["ls.json"]))&&(e=!0,f="data")),d){const c=prompt(`"${a.name||"Folder"}" appears to be an encrypted folder. Enter a name to mount it as:`,a.name);return c?void(b?alert("Encrypted folder import via file input not supported yet. Use drag-and-drop or the directory picker."):"directory"===a.kind?await processFolderSelection(c,a):alert("Please use Upload Folder for encrypted folders.")):void 0}if(e){if(confirm("Found RuntimeFS data archive. Import? (This may overwrite multiple folders and already existing data.)")){let c;c=b?LittleExport.folderToTarStream(b,checkYield,{pathPrefix:f}):LittleExport.folderToTarStream(a,checkYield,{pathPrefix:f}),await startImport({stream:()=>c})}return}const g=document.getElementById("folderName").value.trim()||prompt("Enter a name for the folder:",a.name||"");if(!g)return;b?await processFilesAndStore(g,b):"directory"===a.kind?await processFolderSelection(g,a):alert("Please use drag-and-drop for this folder.")}catch(a){console.error("Import error:",a),alert("An error occurred during import: "+a.message)}finally{setUiBusy(!1)}}async function uploadFolder(){try{if(window.showDirectoryPicker){setUiBusy(!0);const a=await window.showDirectoryPicker({mode:"read"});await analyzeAndImportFolder(a)}else document.getElementById("folderUploadFallbackInput").click()}catch(a){"AbortError"!==a.name&&(console.error(a),alert("Error accessing folder: "+a.message))}finally{setUiBusy(!1)}}async function uploadFolderFallback(a){const b=a.target;return b.files.length?void(await analyzeAndImportFolder({},Array.from(b.files)),b.value=""):void setUiBusy(!1)}async function processFolderSelection(a,b){if(await navigator.locks.request(`rfs_write_${a}`,async()=>{dirHandle=b,folderName=a;try{const c=await b.getFileHandle("manifest.enc"),d=await getOpfsRoot(),e=await d.getDirectoryHandle(RFS_PREFIX,{create:!0});try{await e.removeEntry(a,{recursive:!0})}catch(a){if("NotFoundError"!==a.name)throw new Error("RuntimeFS cannot currently remove this folder; try closing other open RuntimeFS tabs.")}await decryptAndLoadFolderToOpfs(b,c,await e.getDirectoryHandle(a,{create:!0})),await updateRegistryEntry(a,{encryptionType:null})}catch(c){if(c.message&&c.message.includes("RuntimeFS cannot currently remove"))return alert(c.message),void setUiBusy(!1);await processFolderStreaming(a,b)}}),observer){try{observer.disconnect()}catch(a){}observer=null}if("FileSystemObserver"in window)try{observer=new FileSystemObserver(a=>changes.push(...a)),await observer.observe(dirHandle,{recursive:!0}),showingSync||(Array.from(document.body.getElementsByClassName("supportCheck")).forEach(a=>a.style.display="revert"),showingSync=!0)}catch(a){console.warn("Observer failed:",a),showingSync&&(Array.from(document.body.getElementsByClassName("supportCheck")).forEach(a=>a.style.display="none"),showingSync=!1),observer=null}changes.length=0,document.getElementById("folderName").value="",document.getElementById("openFolderName").value=a,await updateRegistryEntry(a,{encryptionType:null}),await logProgress("",!0),setUiBusy(!1),await listFolders()}async function decryptAndLoadFolderToOpfs(a,b,c){const d=prompt("Enter the password to decrypt this folder:");if(!d)throw new Error("Password required.");const e=await b.getFile(),f=await e.arrayBuffer(),g=f.slice(0,16),h=f.slice(16,28),i=f.slice(28),j=await deriveKeyFromPassword(d,g);let k;try{const a=await crypto.subtle.decrypt({name:"AES-GCM",iv:h},j,i);k=JSON.parse(new TextDecoder().decode(a))}catch(a){throw new Error("Decryption failed. Wrong password?")}const l=await a.getDirectoryHandle("content"),m=Object.entries(k),n=m.length;let o=0;const p=new Map;p.set(".",c);const q=async()=>{for(;0<m.length;){const a=m.shift();if(!a)break;const[b,d]=a,e=logProgress(`Decrypting (${o}/${n}): ${b}`);e&&(await e);const f=b.split("/"),g=f.pop();let h=c;if(0<f.length){let a=".";h=await p.get(".");for(const b of f){const c=a;if(a+="/"+b,!p.has(a)){const d=p.get(c),e=d.then(a=>a.getDirectoryHandle(b,{create:!0}));p.set(a,e)}h=await p.get(a)}}let i;try{const a=await l.getFileHandle(d.id);i=await a.getFile()}catch(a){console.warn(`Missing file: ${b}`),o++;continue}const k=await h.getFileHandle(g,{create:!0}),q=await k.createWritable();if(0<d.size){const a=i.stream().getReader(),b=Math.ceil(d.size/CHUNK_SIZE);let c=new Uint8Array(0),e=0;try{for(;e<b;){const f=checkYield();f&&(await f);const g=e===b-1,h=g?d.size%CHUNK_SIZE||CHUNK_SIZE:CHUNK_SIZE,i=h+28;for(;c.length<i;){const{done:b,value:d}=await a.read();if(b)break;const e=new Uint8Array(c.length+d.length);e.set(c),e.set(d,c.length),c=e}if(c.length<i)break;const k=c.subarray(0,i);c=c.subarray(i);const l=k.subarray(0,12),m=k.subarray(12),n=await crypto.subtle.decrypt({name:"AES-GCM",iv:l},j,m);await q.write(new Uint8Array(n)),e++}}finally{a.releaseLock()}}try{await q.close()}catch(a){if("TypeError"!==a.name)throw a}o++}};await Promise.all(Array(CONCURRENCY).fill(null).map(q)),await logProgress("",!0)}async function processFilesAndStore(a,b){await navigator.locks.request(`rfs_write_${a}`,async()=>{const c=await getOpfsRoot(),d=await c.getDirectoryHandle(RFS_PREFIX,{create:!0});try{await d.removeEntry(a,{recursive:!0})}catch(a){}const e=await d.getDirectoryHandle(a,{create:!0});let f=0;for(const a of b)f+=a.size;let g=0;const h=Array.from(b).filter(a=>!isJunk(a.name)),i=()=>{const a=(g/1e6).toFixed(2),b=(f/1e6).toFixed(2),c=0<f?(100*(g/f)).toFixed(2):"100.00";return logProgress(`Uploading: ${c}% (${a} / ${b} MB)`)},j=Array(CONCURRENCY).fill(null).map(async()=>{for(const a=new Map;0<h.length;){const b=h.shift();if(!b)break;let c=b.webkitRelativePath||b.name;const d=c.split("/");1<d.length&&d.shift(),c=d.join("/");let f=0;await writeStreamToOpfs(e,c,b,{dirCache:a,onProgress:async a=>{if(g+=a,f+=a,1048576<f){let a=i();a&&(await a),f=0}}});const j=checkYield();j&&(await j)}});await Promise.all(j),document.getElementById("folderName").value="",document.getElementById("openFolderName").value=a,await updateRegistryEntry(a,{encryptionType:null}),await logProgress("",!0),await listFolders()})}async function processFolderStreaming(a,b){const c=await getOpfsRoot(),d=await c.getDirectoryHandle(RFS_PREFIX,{create:!0});try{await d.removeEntry(a,{recursive:!0})}catch(a){if("NotFoundError"!==a.name)return alert("RuntimeFS cannot currently remove this folder; try closing other open RuntimeFS tabs."),void setUiBusy(!1)}const e=await d.getDirectoryHandle(a,{create:!0}),f=[];let g=!1,h=!1,i=0,j=0;const k=()=>{const a=(j/1e6).toFixed(2),b=(i/1e6).toFixed(2);let c=g?`Finishing: ${a} MB / ${b} MB`:`Scanning: ${a} MB / ${b} MB`;return logProgress(c)},l=async()=>{for(const a=new Map;!h;){const b=f.shift();if(!b){if(g)break;await new Promise(a=>setTimeout(a,20));continue}const c=b.fileOverride;let d=0;await writeStreamToOpfs(b.dest,b.entry.name,c,{dirCache:a,onProgress:async a=>{if(j+=a,d+=a,1048576<d){let a=k();a&&(await a),d=0}}});const e=checkYield();e&&(await e)}},m=async()=>{for(const a=[{source:b,dest:e}];0<a.length&&!h;){const{source:b,dest:c}=a.shift();try{for await(const d of b.values()){if(h)break;if(isJunk(d.name))continue;if("file"===d.kind){const a=await d.getFile();i+=a.size,f.push({dest:c,entry:d,fileOverride:a});let b=k();for(b&&(await b);500<f.length&&!h;){await new Promise(a=>setTimeout(a,20));const a=checkYield();a&&(await a)}}else if("directory"===d.kind){const b=await c.getDirectoryHandle(d.name,{create:!0});a.push({source:d,dest:b})}const b=checkYield();b&&(await b)}}catch(a){console.warn("Error reading directory stream:",a)}}g=!0};try{const a=Array(CONCURRENCY).fill(null).map(l);await Promise.all([m(),...a])}catch(a){throw h=!0,a}document.getElementById("folderName").value="",document.getElementById("openFolderName").value=a,await updateRegistryEntry(a,{encryptionType:null}),await logProgress("",!0),await listFolders(),setUiBusy(!1)}async function writeStreamToOpfs(a,b,c,d={}){const{dirCache:e=null,onProgress:f=null}=d,g=b.split("/"),h=g.pop();let i=a;if(0<g.length){let b="";for(const c of g){const d=b;if(b+=(b?"/":"")+c,e){if(!e.has(b)){const f=d?e.get(d):Promise.resolve(a),g=f.then(a=>a.getDirectoryHandle(c,{create:!0}));e.set(b,g)}i=await e.get(b)}else i=await i.getDirectoryHandle(c,{create:!0})}}const j=await i.getFileHandle(h,{create:!0}),k=await j.createWritable({keepExistingData:!1});try{if(!f)await k.write(c);else{const a=new TransformStream({async transform(a,b){b.enqueue(a);const c=f(a.byteLength);c&&(await c)}});await c.stream().pipeThrough(a).pipeTo(k,{preventClose:!0})}}finally{try{await k.close()}catch(a){}}}async function cleanupOrphans(){await navigator.locks.request("rfs_global_import",{ifAvailable:!0},async a=>{if(a)try{const a=await getOpfsRoot(),b=await a.getDirectoryHandle(RFS_PREFIX),c=await getRegistry(),d=new Set(Object.keys(c)),e=[];for await(const a of b.keys())e.push(a);for(const a of e)d.has(a)||(await navigator.locks.request(`rfs_write_${a}`,{ifAvailable:!0},async c=>{c&&(await b.removeEntry(a,{recursive:!0}).catch(()=>{}))}))}catch(a){}})}async function listFolders(){if(!isListingFolders){isListingFolders=!0;const a=document.getElementById("folderList");try{const b=await getRegistry();a.textContent="";const c=document.createDocumentFragment(),d=Object.keys(b).sort();d.forEach(a=>{const d=b[a],e=document.createElement("li");e.textContent="password"===d.encryptionType?`[Locked] ${a}`:a,c.appendChild(e)}),a.appendChild(c)}finally{isListingFolders=!1}}}async function deleteFolder(a,b=!1){const c=a||document.getElementById("deleteFolderName").value.trim();if(!c)return alert("Enter a folder name first.");if(b||confirm(`Remove "${c}"?`)){setUiBusy(!0),logProgress("Deleting...",!0);const d=await getOpfsRoot();try{const a=await d.getDirectoryHandle(RFS_PREFIX);await a.removeEntry(c,{recursive:!0})}catch(a){if("NotFoundError"!==a.name)return alert("RuntimeFS cannot currently remove this folder; try closing other open RuntimeFS tabs."),void setUiBusy(!1)}await updateRegistryEntry(c,null),folderName===c&&(folderName=void 0,dirHandle=void 0,document.getElementById("openFolderName").value="",observer&&(observer.disconnect(),observer=null),showingSync&&(Array.from(document.body.getElementsByClassName("supportCheck")).forEach(a=>a.style.display="none"),showingSync=!1)),a||(document.getElementById("deleteFolderName").value=""),await listFolders(),logProgress("",!0),b||setUiBusy(!1)}}async function openFile(a){const b=(a||document.getElementById("openFolderName").value.trim()).trim(),c=document.getElementById("fileName").value.trim();if(!b)return alert("Provide a folder name.");setUiBusy(!0);try{const a=await getRegistry(),d=a[b];if(!d)return void alert("Folder not found.");const e=document.getElementById("regex").value.trim(),f=document.getElementById("headers").value.trim();(d.rules!==e||d.headers!==f)&&(await updateRegistryEntry(b,{rules:e,headers:f}));let g=null;if("password"===d.encryptionType){const a=prompt(`Enter password for "${b}":`);if(!a)return;g=await deriveKeyFromPassword(a,base64ToBuffer(d.salt))}const h=await waitForController();await new Promise((a,c)=>{const d=new MessageChannel;d.port1.onmessage=()=>a(),h.postMessage({type:"SET_RULES",rules:e,headers:f,key:g,folderName:b},[d.port2]),setTimeout(()=>c(new Error("Service Worker timeout.")),4e3)});const i=c.split("/").map(encodeURIComponent).join("/");window.open(`n/${encodeURIComponent(b)}/${i}`,"_blank")}catch(a){console.error(a),alert(a.message)}finally{setUiBusy(!1)}}async function exportData(){setUiBusy(!0);try{let a=prompt("Enter a password (or leave blank for no encryption):");if(null===a)return void setUiBusy(!1);a=a||void 0;const b=document.getElementById("c1").checked,c=document.getElementById("c2").checked,d=document.getElementById("c3").checked,e=document.getElementById("c4").checked,f=document.getElementById("c5").checked,g=document.getElementById("c6").checked,h=document.getElementById("c7").checked,i=[];if(e||f){const a=await getRegistry(),b={};for(const[c,d]of Object.entries(a))b[c]={...d};i.push({path:SYSTEM_FILE,data:JSON.stringify(b)})}const j={opfs:[SYSTEM_FILE]},k={opfs:[]};e&&!f?k.opfs.push(RFS_PREFIX):!e&&f&&j.opfs.push(RFS_PREFIX),logProgress("Starting export...",!0);let l=2;await LittleExport.exportData({fileName:"result",password:a,cookies:b,localStorage:c,idb:d,opfs:e||f,cache:g,session:h,customItems:i,include:0<k.opfs.length?k:{},exclude:j,graceful:!0,logger:function(a){"Export cancelled."===a?l=1:logProgress(a)},onerror:a=>{l=0,console.error("Error while exporting:",a),alert("Error while exporting: "+a)}}),1!=l&&alert(2==l?"Export complete!":"Export may have failed or been incomplete.")}catch(a){console.error("Export failed:",a),alert("Export failed: "+a.message)}finally{setUiBusy(!1),logProgress("",!0)}}async function importData(){const a=document.createElement("input");a.type="file",a.onchange=a=>{a.target.files[0]&&startImport(a.target.files[0])},a.click()}async function startImport(a){await navigator.locks.request("rfs_global_import",async()=>{setUiBusy(!0),_registryCache=null,localStorage.setItem("rfs_partial","1");try{let b;logProgress("Starting import...",!0);const c={graceful:!0,logger:logProgress,onCustomItem:async(a,c)=>{a===SYSTEM_FILE&&(b=JSON.parse(new TextDecoder().decode(c)))},onerror:a=>{"A password is required to decrypt this data."===a.message?(alert("A password is required to decrypt this data."),d=1):(console.error(a),d=0,alert("Import encountered an error: "+a.message))}};let d=2;c.source=a,await LittleExport.importData(c),logProgress("Merging metadata...",!0);const e=await getRegistry(),f={...e,...(b||{})};await saveRegistry(f),await validateAndRepairRegistry(),localStorage.removeItem("rfs_partial"),await listFolders(),1!=d&&alert(2===d?"Import complete! Reload to fix any issues.":"Import may have failed or been incomplete; reload to fix any issues.")}catch(a){console.error("Import failed:",a),alert("Import failed:",a)}finally{setUiBusy(!1),logProgress("",!0)}})}async function validateAndRepairRegistry(){const a=await getOpfsRoot(),b=await getRegistry();let c=!1;try{const d=await a.getDirectoryHandle(RFS_PREFIX,{create:!0}),e=[];for await(const a of d.keys())e.push(a);e.forEach(a=>{b[a]||(b[a]={created:Date.now(),headers:localStorage.getItem("fsHeaders")||"",rules:localStorage.getItem("fsRegex")||""},c=!0)});const f=Object.keys(b);await Promise.all(f.map(async a=>{try{await d.getDirectoryHandle(a)}catch(d){delete b[a],c=!0}})),c&&(await saveRegistry(b))}catch(a){console.warn("Repair failed:",a)}}function base64ToBuffer(a){const b=atob(a),c=b.length,d=new Uint8Array(c);for(let e=0;e<c;e++)d[e]=b.charCodeAt(e);return d.buffer}function bufferToBase64(a){let b="";const c=new Uint8Array(a),d=c.byteLength;for(let e=0;e<d;e++)b+=String.fromCharCode(c[e]);return btoa(b)}async function deriveKeyFromPassword(a,b){const c=new TextEncoder,d=await crypto.subtle.importKey("raw",c.encode(a),{name:"PBKDF2"},!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:b,iterations:6e5,hash:"SHA-256"},d,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])}let syncTimeout=-1;async function syncFiles(){return folderName&&dirHandle?void(setUiBusy(!0),0<changes.length?(await performSyncToOpfs(),document.getElementById("syncInfo").textContent="Sync complete."):document.getElementById("syncInfo").textContent="No changes to sync.",clearTimeout(syncTimeout),syncTimeout=setTimeout(()=>document.getElementById("syncInfo").textContent="",1e3),setUiBusy(!1)):alert("It seems that syncing isn't supported for your browser.")}async function syncAndOpenFile(){return folderName&&dirHandle?void(setUiBusy(!0),clearTimeout(syncTimeout),0<changes.length?(await performSyncToOpfs(),document.getElementById("syncInfo").textContent="Sync complete."):document.getElementById("syncInfo").textContent="No changes to sync.",syncTimeout=setTimeout(()=>document.getElementById("syncInfo").textContent="",1e3),await openFile(folderName),setUiBusy(!1)):alert("It seems that syncing isn't supported for your browser.")}async function performSyncToOpfs(){console.log(`Syncing ${changes.length}${1===changes.length?" change...":" changes..."}`),await navigator.locks.request(`rfs_write_${folderName}`,async()=>{const a=await getOpfsRoot(),b=await a.getDirectoryHandle(RFS_PREFIX),c=await b.getDirectoryHandle(folderName),d=changes.splice(0,changes.length);changes.length=0;for(const a of d){const b=a.relativePathComponents;if(!b)continue;const d=b.join("/");try{if("deleted"===a.type){let a=c;const d=b.slice(0,-1),e=b[b.length-1];for(const b of d)a=await a.getDirectoryHandle(b);await a.removeEntry(e,{recursive:!0})}else{let a=dirHandle;for(let c=0;c<b.length-1;c++)a=await a.getDirectoryHandle(b[c]);const e=await a.getFileHandle(b[b.length-1]),g=await e.getFile();await writeStreamToOpfs(c,d,g,{totalSize:g.size})}}catch(a){console.warn(`Sync failed for ${d}:`,a)}}navigator.serviceWorker.controller&&navigator.serviceWorker.controller.postMessage({type:"INVALIDATE_CACHE",folderName:folderName})})}async function uploadAndEncryptWithPassword(){const a=document.getElementById("encryptFolderName").value.trim(),b=prompt("Enter a password:");if(!a||!b)return;setUiBusy(!0);let c;try{c=await window.showDirectoryPicker({mode:"read"})}catch(a){if("AbortError"!==a.name)throw a}await navigator.locks.request(`rfs_write_${a}`,async()=>{const d=await getOpfsRoot(),e=await d.getDirectoryHandle(RFS_PREFIX,{create:!0});try{await e.removeEntry(a,{recursive:!0})}catch(a){if("NotFoundError"!==a.name)return void alert("RuntimeFS cannot currently remove this folder; try closing other open RuntimeFS tabs.")}const f=await e.getDirectoryHandle(a,{create:!0}),g=await f.getDirectoryHandle("content",{create:!0}),h=crypto.getRandomValues(new Uint8Array(16)),i=await deriveKeyFromPassword(b,h),j={},k=[],l=[{dir:c,path:""}];let m=!0,n=0;const o=async()=>{for(;;){if(0===k.length){if(!m)break;const a=checkYield();a&&(await a);continue}const a=k.shift(),{entry:b,entryPath:c,fileId:d}=a,e=checkYield();if(e){const b=(n/1e6).toFixed(2);await logProgress(`Encrypting: ${b} MB (${a.entryPath})`),await e}const f=await b.getFile();n+=f.size,j[c]={id:d,size:f.size,type:f.type};const h=await g.getFileHandle(d,{create:!0}),l=await h.createWritable();if(0<f.size){const a=f.stream().getReader();let b=[],c=0;try{for(;;){const{done:d,value:e}=await a.read();if(e&&(b.push(e),c+=e.byteLength),(d||c>=CHUNK_SIZE)&&0<c){const a=new Uint8Array(c);let e=0;for(const d of b)a.set(d,e),e+=d.byteLength;let f=0;for(;f<c;){const e=c-f;if(!d&&e<CHUNK_SIZE){const d=a.slice(f);b=[d],c=d.byteLength;break}const g=checkYield();g&&(await g);const h=Math.min(CHUNK_SIZE,e),j=a.subarray(f,f+h),k=crypto.getRandomValues(new Uint8Array(12)),m=await crypto.subtle.encrypt({name:"AES-GCM",iv:k},i,j);f+=h,await l.write(k),await l.write(new Uint8Array(m))}f>=c&&(b=[],c=0)}if(d)break}}finally{a.releaseLock();try{await l.close()}catch(a){}}}else await l.close()}},p=(async()=>{for(;0<l.length;){const{dir:a,path:b}=l.shift();for await(const c of a.values()){if(isJunk(c.name))continue;const a=b?`${b}/${c.name}`:c.name;if("file"===c.kind){const b=crypto.randomUUID();for(k.push({entry:c,entryPath:a,fileId:b});500<k.length;)await new Promise(a=>setTimeout(a,20))}else l.push({dir:c,path:a})}}m=!1})(),q=Array(CONCURRENCY).fill(null).map(o);await p,await Promise.all(q),await logProgress("Saving manifest...",!0);const r=JSON.stringify(j),s=new TextEncoder().encode(r),t=crypto.getRandomValues(new Uint8Array(12)),u=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},i,s),v=await f.getFileHandle("manifest.enc",{create:!0}),w=await v.createWritable();await w.write(h),await w.write(t),await w.write(new Uint8Array(u)),await w.close(),await updateRegistryEntry(a,{encryptionType:"password",salt:bufferToBase64(h)}),document.getElementById("encryptFolderName").value="",await listFolders(),setUiBusy(!1),await logProgress("",!0)})}document.addEventListener("DOMContentLoaded",()=>{if("file:"===window.location.protocol)return void alert("RuntimeFS cannot run from a local file:// context; use an online version or test from localhost instead.");if(!window.isSecureContext)return void alert("RuntimeFS cannot run in a non-secure context.");if(!("serviceWorker"in navigator))return void alert("RuntimeFS cannot run without ServiceWorkers enabled.");document.getElementById("folderName").addEventListener("keydown",a=>{"Enter"!==a.key||currentlyBusy||uploadFolder()}),document.getElementById("openFolderName").addEventListener("keydown",a=>{"Enter"!==a.key||currentlyBusy||(a.shiftKey?openFileInPlace():a.ctrlKey||a.metaKey?syncAndOpenFile():openFile())}),document.getElementById("fileName").addEventListener("keydown",a=>{"Enter"!==a.key||currentlyBusy||(a.shiftKey?openFileInPlace():a.ctrlKey||a.metaKey?syncAndOpenFile():openFile())}),document.getElementById("deleteFolderName").addEventListener("keydown",a=>{"Enter"!==a.key||currentlyBusy||deleteFolder()}),document.getElementById("folderUploadFallbackInput").addEventListener("change",uploadFolderFallback),window.showSaveFilePicker&&(document.getElementById("encryptionSection").style.display="revert");const a=document.body;a.addEventListener("dragover",b=>{b.preventDefault(),a.style.backgroundColor="#385b7e"}),a.addEventListener("dragleave",()=>{a.style.backgroundColor=""}),a.addEventListener("drop",async b=>{if(b.preventDefault(),a.style.backgroundColor="",currentlyBusy)return;const c=Array.from(b.dataTransfer.items);if(!c.length)return;const d=c[0].webkitGetAsEntry?c[0].webkitGetAsEntry():null,e=[];for(let a=0;a<c.length;a++)if("file"===c[a].kind){const b=c[a].getAsFile();b&&e.push(b)}let f=null;if("file"===c[0].kind&&window.FileSystemDirectoryHandle)try{f=c[0].getAsFileSystemHandle()}catch(a){console.warn("FileSystemHandle access denied.")}let g=null;if(f)try{g=await f}catch(a){}if(await new Promise(a=>setTimeout(a,10)),g&&"directory"===g.kind)return void(await analyzeAndImportFolder(g));if(d&&d.isDirectory){const a=prompt("Please choose a folder name:",d.name);if(a){setUiBusy(!0);const b=[],c=[{entry:d,path:""}];let e=0,g=!1,h=!1,i="";for(;0<c.length;){const{entry:a,path:j}=c.shift();if(isJunk(a.name))continue;if(a.isFile){const c=await new Promise((b,c)=>a.file(b,c));Object.defineProperty(c,"webkitRelativePath",{value:j+c.name}),b.push(c);const f=c.webkitRelativePath;if(f.endsWith(`data/custom/${SYSTEM_FILE}`))g=!0;else if(f.endsWith(`custom/${SYSTEM_FILE}`))g=!0,i="data";else if("ls.json"===f||f.endsWith("/ls.json")){const a=f.split("/");(1===a.length||2===a.length&&a[0]===d.name)&&(g=!0,i="data")}f.endsWith("manifest.enc")&&(h=!0),e++}else if(a.isDirectory){const b=a.createReader();let d;do{d=await new Promise((a,c)=>b.readEntries(a,c));for(const b of d)c.push({entry:b,path:j+a.name+"/"})}while(0<d.length)}let k=logProgress(`Scanned ${e} files...`);k&&(await k)}if(h)return alert("Encrypted folder import via drag-and-drop legacy mode is not supported in your browser."),void setUiBusy(!1);if(g){if(confirm("Found RuntimeFS data archive. Import? (This may overwrite multiple folders and already existing data.)")){const a=LittleExport.folderToTarStream(b,checkYield,{pathPrefix:i});return await startImport({stream:()=>a}),void setUiBusy(!1)}setUiBusy(!1)}await logProgress(`Processed ${b.length} files...`,!0),await processFilesAndStore(a,b),setUiBusy(!1)}return}const h=e;if(0!==h.length)if(1<h.length){const a=prompt(`You dropped ${h.length} files. Enter a name to create a new folder for them:`);a&&(setUiBusy(!0),await processFilesAndStore(a,h),setUiBusy(!1))}else{const a=h[0],b=/\.(tar\.gz|tar|enc|cbor)$/i.test(a.name)||a.name===SYSTEM_FILE;if(b){if(confirm("Found RuntimeFS data archive. Import? (This may overwrite multiple folders and already existing data.)\nClick OK to extract and import it as system data or cancel to upload as file."))return void startImport(a)}const c=a.name.replace(/\.[^/.]+$/,""),d=prompt(`Enter a folder name to upload "${a.name}" into:`,c);d&&(setUiBusy(!0),await processFilesAndStore(d,[a]),setUiBusy(!1))}}),navigator.serviceWorker.register(SW_URL).then(a=>{a.addEventListener("updatefound",()=>{const b=a.installing;b.addEventListener("statechange",()=>{"installed"===b.state&&navigator.serviceWorker.controller&&location.reload()})})}).catch(console.error),navigator.serviceWorker.addEventListener("message",async a=>{a.data&&"SW_READY"===a.data.type&&(await listFolders()),a.data&&"INVALIDATE_CACHE"===a.data.type&&(await listFolders())}),localStorage.getItem("rfs_partial")?validateAndRepairRegistry().then(async()=>{const a=await getOpfsRoot();for await(const b of a.keys())b.startsWith("._littleexport_temp_")&&(await a.removeEntry(b,{recursive:!0}).catch(()=>{}));return localStorage.removeItem("rfs_partial"),cleanupOrphans()}).then(listFolders):cleanupOrphans().then(listFolders);const b=document.getElementById("regex"),c=document.getElementById("headers");b.value=localStorage.getItem("fsRegex")||"",c.value=localStorage.getItem("fsHeaders")||"",b.addEventListener("input",()=>localStorage.setItem("fsRegex",b.value)),c.addEventListener("input",()=>localStorage.setItem("fsHeaders",c.value))});async function openFileInPlace(){if(!navigator.serviceWorker.controller)return void alert("Service Worker is not controlling the page. Please reload and try again.");const a=document.getElementById("openFolderName").value.trim(),b=document.getElementById("fileName").value.trim();if(!a)return alert("Provide a folder name.");setUiBusy(!0);try{const c=await getRegistry(),d=c[a];if(!d)return void alert("Folder not found.");const e=document.getElementById("regex").value.trim(),f=document.getElementById("headers").value.trim();(d.rules!==e||d.headers!==f)&&(await updateRegistryEntry(a,{rules:e,headers:f}));let g=null;if("password"===d.encryptionType){const b=prompt(`Enter password for "${a}":`);if(!b)return;g=await deriveKeyFromPassword(b,base64ToBuffer(d.salt))}const h=await waitForController();await Promise.race([new Promise(b=>{const c=new MessageChannel;c.port1.onmessage=()=>b(),h.postMessage({type:"SET_RULES",rules:e,headers:f,key:g,folderName:a},[c.port2])}),new Promise((a,b)=>setTimeout(()=>b(new Error("Service Worker response timed out.")),4e3))]);const i=b?b.split("/").map(encodeURIComponent).join("/"):"index.html",j=`n/${encodeURIComponent(a)}/${i}`,k=await fetch(j,{headers:{Accept:"text/html"}});if(!k.ok){if(403===k.status)return alert("Session authentication failed.");throw new Error(`Failed to load HTML: ${k.status} ${k.statusText}`)}let l=await k.text();const m=j.substring(0,j.lastIndexOf("/")+1),n=`<base href="${m}">`;let o="";k.headers.forEach((a,b)=>{o+=`<meta http-equiv="${b.replace(/"/g,""")}" content="${a.replace(/"/g,""")}">\n`}),l=/<head\b[^>]*>/i.test(l)?l.replace(/(<head\b[^>]*>)/i,`$1${n}${o}`):/<html\b[^>]*>/i.test(l)?l.replace(/(<html\b[^>]*>)/i,`$1<head>${n}${o}</head>`):`<head>${n}${o}</head>${l}`,document.open(),document.write(l),document.close()}catch(a){console.error(a),alert(a.message)}finally{setUiBusy(!1)}}