dome-embedded-app-sdk 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.domeSdk=t():e.domeSdk=t()}(this,()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{CardClientMessageType:()=>Ge,CardFsErrorCode:()=>rt,CardFsFileType:()=>tt,CardMessageType:()=>$e,CardPermission:()=>Je,CardSdk:()=>at,CommonClientMessageType:()=>We,CryptoA01:()=>Ze,DomeEmbeddedAppSdk:()=>Ye,ViewerClientMessageType:()=>qe,ViewerMessageType:()=>He,ViewerSdk:()=>Qe,cardPermission:()=>et,getKeyFromBlob:()=>st});const r="0.4.1";let n,s,i;try{n=new TextDecoder}catch(e){}let a=0;const o=[],c={};let l,d,u,h,f,p,y,g=11281e4,m=1681e4,E=o,_=0,w={},S=0,b=0,A=[],I=[],F={useRecords:!1,mapsAsObjects:!0},C=!1,T=2;try{new Function("")}catch(e){T=1/0}class R{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[v(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(s)return Z(()=>(ee(),this?this.decode(e,t):R.prototype.decode.call(F,e,t)));i=t>-1?t:e.length,a=0,_=0,b=0,d=null,E=o,u=null,s=e;try{p=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(t){if(s=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 R){if(w=this,f=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return l=this.structures,O();(!l||l.length>0)&&(l=[])}else w=F,(!l||l.length>0)&&(l=[]),f=null;return O()}decodeMultiple(e,t){let r,n=0;try{let s=e.length;C=!0;let i=this?this.decode(e,s):re.decode(e,s);if(!t){for(r=[i];a<s;)n=a,r.push(O());return r}if(!1===t(i))return;for(;a<s;)if(n=a,!1===t(O()))return}catch(e){throw e.lastPosition=n,e.values=r,e}finally{C=!1,ee()}}}function O(){try{let e=N();if(u){if(a>=u.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}a=u.postBundlePosition,u=null}if(a==i)l=null,s=null,h&&(h=null);else{if(a>i){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}if(!C)throw new Error("Data read, but end of buffer not reached")}return e}catch(e){throw ee(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer"))&&(e.incomplete=!0),e}}function N(){let e=s[a++],t=e>>5;if(e&=31,e>23)switch(e){case 24:e=s[a++];break;case 25:if(7==t)return function(){let e=s[a++],t=s[a++],r=(127&e)>>2;if(31===r)return t||3&e?NaN:128&e?-1/0:1/0;if(0===r){let r=((3&e)<<8|t)/(1<<24);return 128&e?-r:r}return x[3]=128&e|56+(r>>1),x[2]=(7&e)<<5|t>>3,x[1]=t<<5,x[0]=0,j[0]}();e=p.getUint16(a),a+=2;break;case 26:if(7==t){let e=p.getFloat32(a);if(w.useFloat32>2){let t=te[(127&s[a])<<1|s[a+1]>>7];return a+=4,(t*e+(e>0?.5:-.5)|0)/t}return a+=4,e}e=p.getUint32(a),a+=4;break;case 27:if(7==t){let e=p.getFloat64(a);return a+=8,e}if(t>1){if(p.getUint32(a)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");e=p.getUint32(a+4)}else w.int64AsNumber?(e=4294967296*p.getUint32(a),e+=p.getUint32(a+4)):e=p.getBigUint64(a);a+=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=N())!=c;){if(n>=g)throw new Error(`Array length exceeds ${g}`);r[n++]=e}return 4==t?r:3==t?r.join(""):Buffer.concat(r);case 5:let s;if(w.mapsAsObjects){let e={},t=0;if(w.keyMap)for(;(s=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[v(w.decodeKey(s))]=N()}else for(;(s=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[v(s)]=N()}return e}{y&&(w.mapsAsObjects=!0,y=!1);let e=new Map;if(w.keyMap){let t=0;for(;(s=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(w.decodeKey(s),N())}}else{let t=0;for(;(s=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(s,N())}}return e}case 7:return c;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 r=e,w.copyBuffers?Uint8Array.prototype.slice.call(s,a,a+=r):s.subarray(a,a+=r);case 3:if(b>=a)return d.slice(a-S,(a+=e)-S);if(0==b&&i<140&&e<32){let t=e<16?P(e):B(e);if(null!=t)return t}return D(e);case 4:if(e>=g)throw new Error(`Array length exceeds ${g}`);let t=new Array(e);for(let r=0;r<e;r++)t[r]=N();return t;case 5:if(e>=m)throw new Error(`Map size exceeds ${g}`);if(w.mapsAsObjects){let t={};if(w.keyMap)for(let r=0;r<e;r++)t[v(w.decodeKey(N()))]=N();else for(let r=0;r<e;r++)t[v(N())]=N();return t}{y&&(w.mapsAsObjects=!0,y=!1);let t=new Map;if(w.keyMap)for(let r=0;r<e;r++)t.set(w.decodeKey(N()),N());else for(let r=0;r<e;r++)t.set(N(),N());return t}case 6:if(e>=57337){let t=l[8191&e];if(t)return t.read||(t.read=L(t)),t.read();if(e<65536){if(57343==e){let e=X(),t=N(),r=N();V(t,r);let n={};if(w.keyMap)for(let t=2;t<e;t++){n[v(w.decodeKey(r[t-2]))]=N()}else for(let t=2;t<e;t++){n[v(r[t-2])]=N()}return n}if(57342==e){let e=X(),t=N();for(let r=2;r<e;r++)V(t++,N());return N()}if(57337==e)return function(){let e=X(),t=a+N();for(let t=2;t<e;t++){let e=X();a+=e}let r=a;return a=t,u=[M(X()),M(X())],u.position0=0,u.position1=0,u.postBundlePosition=a,a=r,N()}();if(w.getShared&&(Q(),t=l[8191&e],t))return t.read||(t.read=L(t)),t.read()}}let n=A[e];if(n)return n.handlesRead?n(N):n(N());{let t=N();for(let r=0;r<I.length;r++){let n=I[r](e,t);if(void 0!==n)return n}return new K(t,e)}case 7:switch(e){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let t=(f||q())[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 r}const k=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function L(e){if(!e)throw new Error("Structure is required in record definition");return e.slowReads=0,function(){let e=s[a++];if(e&=31,e>23)switch(e){case 24:e=s[a++];break;case 25:e=p.getUint16(a),a+=2;break;case 26:e=p.getUint32(a),a+=4;break;default:throw new Error("Expected array header, but got "+s[a-1])}let t=this.compiledReader;for(;t;){if(t.propertyCount===e)return t(N);t=t.next}if(this.slowReads++>=T){let r=this.length==e?this:this.slice(0,e);return t=w.keyMap?new Function("r","return {"+r.map(e=>w.decodeKey(e)).map(e=>k.test(e)?v(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+r.map(e=>k.test(e)?v(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"),this.compiledReader&&(t.next=this.compiledReader),t.propertyCount=e,this.compiledReader=t,t(N)}let r={};if(w.keyMap)for(let t=0;t<e;t++)r[v(w.decodeKey(this[t]))]=N();else for(let t=0;t<e;t++)r[v(this[t])]=N();return r}}function v(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 D=M;function M(e){let t;if(e<16&&(t=P(e)))return t;if(e>64&&n)return n.decode(s.subarray(a,a+=e));const r=a+e,i=[];for(t="";a<r;){const e=s[a++];if(128&e)if(192==(224&e)){const t=63&s[a++];i.push((31&e)<<6|t)}else if(224==(240&e)){const t=63&s[a++],r=63&s[a++];i.push((31&e)<<12|t<<6|r)}else if(240==(248&e)){let t=(7&e)<<18|(63&s[a++])<<12|(63&s[a++])<<6|63&s[a++];t>65535&&(t-=65536,i.push(t>>>10&1023|55296),t=56320|1023&t),i.push(t)}else i.push(e);else i.push(e);i.length>=4096&&(t+=U.apply(String,i),i.length=0)}return i.length>0&&(t+=U.apply(String,i)),t}let U=String.fromCharCode;function B(e){let t=a,r=new Array(e);for(let n=0;n<e;n++){const e=s[a++];if((128&e)>0)return void(a=t);r[n]=e}return U.apply(String,r)}function P(e){if(e<4){if(e<2){if(0===e)return"";{let e=s[a++];return(128&e)>1?void(a-=1):U(e)}}{let t=s[a++],r=s[a++];if((128&t)>0||(128&r)>0)return void(a-=2);if(e<3)return U(t,r);let n=s[a++];return(128&n)>0?void(a-=3):U(t,r,n)}}{let t=s[a++],r=s[a++],n=s[a++],i=s[a++];if((128&t)>0||(128&r)>0||(128&n)>0||(128&i)>0)return void(a-=4);if(e<6){if(4===e)return U(t,r,n,i);{let e=s[a++];return(128&e)>0?void(a-=5):U(t,r,n,i,e)}}if(e<8){let o=s[a++],c=s[a++];if((128&o)>0||(128&c)>0)return void(a-=6);if(e<7)return U(t,r,n,i,o,c);let l=s[a++];return(128&l)>0?void(a-=7):U(t,r,n,i,o,c,l)}{let o=s[a++],c=s[a++],l=s[a++],d=s[a++];if((128&o)>0||(128&c)>0||(128&l)>0||(128&d)>0)return void(a-=8);if(e<10){if(8===e)return U(t,r,n,i,o,c,l,d);{let e=s[a++];return(128&e)>0?void(a-=9):U(t,r,n,i,o,c,l,d,e)}}if(e<12){let u=s[a++],h=s[a++];if((128&u)>0||(128&h)>0)return void(a-=10);if(e<11)return U(t,r,n,i,o,c,l,d,u,h);let f=s[a++];return(128&f)>0?void(a-=11):U(t,r,n,i,o,c,l,d,u,h,f)}{let u=s[a++],h=s[a++],f=s[a++],p=s[a++];if((128&u)>0||(128&h)>0||(128&f)>0||(128&p)>0)return void(a-=12);if(e<14){if(12===e)return U(t,r,n,i,o,c,l,d,u,h,f,p);{let e=s[a++];return(128&e)>0?void(a-=13):U(t,r,n,i,o,c,l,d,u,h,f,p,e)}}{let y=s[a++],g=s[a++];if((128&y)>0||(128&g)>0)return void(a-=14);if(e<15)return U(t,r,n,i,o,c,l,d,u,h,f,p,y,g);let m=s[a++];return(128&m)>0?void(a-=15):U(t,r,n,i,o,c,l,d,u,h,f,p,y,g,m)}}}}}let j=new Float32Array(1),x=new Uint8Array(j.buffer,0,4);new Array(4096);class K{constructor(e,t){this.value=e,this.tag=t}}A[0]=e=>new Date(e),A[1]=e=>new Date(Math.round(1e3*e)),A[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},A[3]=e=>BigInt(-1)-A[2](e),A[4]=e=>+(e[1]+"e"+e[0]),A[5]=e=>e[1]*Math.exp(e[0]*Math.log(2));const V=(e,t)=>{let r=l[e-=57344];r&&r.isShared&&((l.restoreStructures||(l.restoreStructures=[]))[e]=r),l[e]=t,t.read=L(t)};A[105]=e=>{let t=e.length,r=e[1];V(e[0],r);let n={};for(let s=2;s<t;s++){n[v(r[s-2])]=e[s]}return n},A[14]=e=>u?u[0].slice(u.position0,u.position0+=e):new K(e,14),A[15]=e=>u?u[1].slice(u.position1,u.position1+=e):new K(e,15);let H={Error,RegExp};A[27]=e=>(H[e[0]]||Error)(e[1],e[2]);const z=e=>{if(132!=s[a++]){let e=new Error("Packed values structure must be followed by a 4 element array");throw s.length<a&&(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 f=f?t.concat(f.slice(t.length)):t,f.prefixes=e(),f.suffixes=e(),e()};function W(e,t){return"string"==typeof e?e+t:e instanceof Array?e.concat(t):Object.assign({},e,t)}function q(){if(!f){if(!w.getShared)throw new Error("No packed values available");Q()}return f}z.handlesRead=!0,A[51]=z,A[6]=e=>{if(!f){if(!w.getShared)return new K(e,6);Q()}if("number"==typeof e)return f[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},A[28]=e=>{h||(h=new Map,h.id=0);let t,r=h.id++,n=a;t=s[a]>>5==4?[]:{};let i={target:t};h.set(r,i);let o=e();return i.used?(Object.getPrototypeOf(t)!==Object.getPrototypeOf(o)&&(a=n,t=o,h.set(r,{target:t}),o=e()),Object.assign(t,o)):(i.target=o,o)},A[28].handlesRead=!0,A[29]=e=>{let t=h.get(e);return t.used=!0,t.target},A[258]=e=>new Set(e),(A[259]=e=>(w.mapsAsObjects&&(w.mapsAsObjects=!1,y=!0),e())).handlesRead=!0;I.push((e,t)=>e>=225&&e<=255?W(q().prefixes[e-224],t):e>=28704&&e<=32767?W(q().prefixes[e-28672],t):e>=1879052288&&e<=2147483647?W(q().prefixes[e-1879048192],t):e>=216&&e<=223?W(t,q().suffixes[e-216]):e>=27647&&e<=28671?W(t,q().suffixes[e-27639]):e>=1811940352&&e<=1879048191?W(t,q().suffixes[e-1811939328]):1399353956==e?{packedValues:f,structures:l.slice(0),version:t}:55799==e?t:void 0);const G=1==new Uint8Array(new Uint16Array([1]).buffer)[0],$=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,"undefined"==typeof BigUint64Array?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,"undefined"==typeof BigInt64Array?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],J=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e<$.length;e++)Y($[e],J[e]);function Y(e,t){let r,n="get"+e.name.slice(0,-5);"function"==typeof e?r=e.BYTES_PER_ELEMENT:e=null;for(let s=0;s<2;s++){if(!s&&1==r)continue;let i=2==r?1:4==r?2:8==r?3:0;A[s?t:t-4]=1==r||s==G?n=>{if(!e)throw new Error("Could not find typed array for code "+t);return w.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>>i)}:r=>{if(!e)throw new Error("Could not find typed array for code "+t);let a=new DataView(r.buffer,r.byteOffset,r.byteLength),o=r.length>>i,c=new e(o),l=a[n];for(let e=0;e<o;e++)c[e]=l.call(a,e<<i,s);return c}}}function X(){let e=31&s[a++];if(e>23)switch(e){case 24:e=s[a++];break;case 25:e=p.getUint16(a),a+=2;break;case 26:e=p.getUint32(a),a+=4}return e}function Q(){if(w.getShared){let e=Z(()=>(s=null,w.getShared()))||{},t=e.structures||[];w.sharedVersion=e.version,f=w.sharedValues=e.packedValues,!0===l?w.structures=l=t:l.splice.apply(l,[0,t.length].concat(t))}}function Z(e){let t=i,r=a,n=_,o=S,c=b,f=d,y=E,g=h,m=u,A=new Uint8Array(s.slice(0,i)),I=l,F=w,T=C,R=e();return i=t,a=r,_=n,S=o,b=c,d=f,E=y,h=g,u=m,s=A,C=T,l=I,w=F,p=new DataView(s.buffer,s.byteOffset,s.byteLength),R}function ee(){s=null,h=null,l=null}const te=new Array(147);for(let e=0;e<256;e++)te[e]=+("1e"+Math.floor(45.15-.30103*e));let re=new R({useRecords:!1});const ne=re.decode;re.decodeMultiple;let se,ie,ae;try{se=new TextEncoder}catch(e){}const oe="object"==typeof globalThis&&globalThis.Buffer,ce=void 0!==oe,le=ce?oe.allocUnsafeSlow:Uint8Array,de=ce?oe:Uint8Array,ue=ce?4294967296:2144337920;let he,fe,pe,ye,ge=0,me=null;const Ee=/[\u0080-\uFFFF]/,_e=Symbol("record-id");function we(e,t){e<24?fe[ge++]=t|e:e<256?(fe[ge++]=24|t,fe[ge++]=e):e<65536?(fe[ge++]=25|t,fe[ge++]=e>>8,fe[ge++]=255&e):(fe[ge++]=26|t,pe.setUint32(ge,e),ge+=4)}class Se{constructor(e,t,r){this.structures=e,this.packedValues=t,this.version=r}}function be(e){e<24?fe[ge++]=128|e:e<256?(fe[ge++]=152,fe[ge++]=e):e<65536?(fe[ge++]=153,fe[ge++]=e>>8,fe[ge++]=255&e):(fe[ge++]=154,pe.setUint32(ge,e),ge+=4)}const Ae="undefined"==typeof Blob?function(){}:Blob;function Ie(e){if(e instanceof Ae)return!0;let t=e[Symbol.toStringTag];return"Blob"===t||"File"===t}function Fe(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++)Fe(e[r],t);else{let n=!t.encoder.useRecords;for(var r in e)e.hasOwnProperty(r)&&(n&&Fe(r,t),Fe(e[r],t))}break;case"function":console.log(e)}}const Ce=1==new Uint8Array(new Uint16Array([1]).buffer)[0];function Te(e,t){return!Ce&&t>1&&(e-=4),{tag:e,encode:function(e,t){let r=e.byteLength,n=e.byteOffset||0,s=e.buffer||e;t(ce?oe.from(s,n,r):new Uint8Array(s,n,r))}}}function Re(e,t){let r=e.byteLength;r<24?fe[ge++]=64+r:r<256?(fe[ge++]=88,fe[ge++]=r):r<65536?(fe[ge++]=89,fe[ge++]=r>>8,fe[ge++]=255&r):(fe[ge++]=90,pe.setUint32(ge,r),ge+=4),ge+r>=fe.length&&t(ge+r),fe.set(e.buffer?e:new Uint8Array(e),ge),ge+=r}function Oe(e,t){pe.setUint32(me.position+e,ge-me.position-e+1);let r=me;me=null,t(r[0]),t(r[1])}ae=[Date,Set,Error,RegExp,K,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,"undefined"==typeof BigUint64Array?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,"undefined"==typeof BigInt64Array?function(){}:BigInt64Array,Float32Array,Float64Array,Se],ie=[{tag:1,encode(e,t){let r=e.getTime()/1e3;(this.useTimestamp32||0===e.getMilliseconds())&&r>=0&&r<4294967296?(fe[ge++]=26,pe.setUint32(ge,r),ge+=4):(fe[ge++]=251,pe.setFloat64(ge,r),ge+=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){Re(e,r)}},{getTag(e){if(e.constructor===Uint8Array&&(this.tagUint8Array||ce&&!1!==this.tagUint8Array))return 64},encode(e,t,r){Re(e,r)}},Te(68,1),Te(69,2),Te(70,4),Te(71,8),Te(72,1),Te(77,2),Te(78,4),Te(79,8),Te(85,4),Te(86,8),{encode(e,t){let r=e.packedValues||[],n=e.structures||[];if(r.values.length>0){fe[ge++]=216,fe[ge++]=51,be(4);let e=r.values;t(e),be(0),be(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let t=0,r=e.length;t<r;t++)packedObjectMap[e[t]]=t}if(n){pe.setUint32(ge,3655335424),ge+=3;let r=n.slice(0);r.unshift(57344),r.push(new K(e.version,1399353956)),t(r)}else t(new K(e.version,1399353956))}}];let Ne=new class extends R{constructor(e){let t,r,n,s,i;super(e),this.offset=0,e=e||{};let a=de.prototype.utf8Write?function(e,t,r){return fe.utf8Write(e,t,r)}:!(!se||!se.encodeInto)&&function(e,t){return se.encodeInto(e,fe.subarray(t)).written},o=this,c=e.structures||e.saveStructures,l=e.maxSharedStructures;if(null==l&&(l=c?128:0),l>8190)throw new Error("Maximum maxSharedStructure is 8190");let d=e.sequential;d&&(l=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let u,h,f,p=e.sharedValues;if(p){f=Object.create(null);for(let e=0,t=p.length;e<t;e++)f[p[e]]=e}let y=[],g=0,m=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(a,c){if(fe||(fe=new le(8192),pe=new DataView(fe.buffer,0,8192),ge=0),ye=fe.length-10,ye-ge<2048?(fe=new le(fe.length),pe=new DataView(fe.buffer,0,fe.length),ye=fe.length-10,ge=0):c===Ue&&(ge=ge+7&2147483640),t=ge,o.useSelfDescribedHeader&&(pe.setUint32(ge,3654940416),ge+=3),i=o.structuredClone?new Map:null,o.bundleStrings&&"string"!=typeof a?(me=[],me.size=1/0):me=null,r=o.structures,r){if(r.uninitialized){let e=o.getShared()||{};o.structures=r=e.structures||[],o.sharedVersion=e.version;let t=o.sharedValues=e.packedValues;if(t){f={};for(let e=0,r=t.length;e<r;e++)f[t[e]]=e}}let e=r.length;if(e>l&&!d&&(e=l),!r.transitions){r.transitions=Object.create(null);for(let t=0;t<e;t++){let e=r[t];if(!e)continue;let n,s=r.transitions;for(let r=0,i=e.length;r<i;r++){void 0===s[_e]&&(s[_e]=t);let i=e[r];n=s[i],n||(n=s[i]=Object.create(null)),s=n}s[_e]=1048576|t}}d||(r.nextId=e)}if(n&&(n=!1),s=r||[],h=f,e.pack){let t=new Map;if(t.values=[],t.encoder=o,t.maxValues=e.maxPrivatePackedValues||(f?16:1/0),t.objectMap=f||!1,t.samplingPackedValues=u,Fe(a,t),t.values.length>0){fe[ge++]=216,fe[ge++]=51,be(4);let e=t.values;E(e),be(0),be(0),h=Object.create(f||null);for(let t=0,r=e.length;t<r;t++)h[e[t]]=t}}he=c&Pe;try{if(he)return;if(E(a),me&&Oe(t,E),o.offset=ge,i&&i.idsToInsert){ge+=2*i.idsToInsert.length,ge>ye&&w(ge),o.offset=ge;let e=function(e,t){let r,n=2*t.length,s=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,s),n-=2;let i=t+n;e[i++]=216,e[i++]=28,s=t}return e}(fe.subarray(t,ge),i.idsToInsert);return i=null,e}return c&Ue?(fe.start=t,fe.end=ge,fe):fe.subarray(t,ge)}finally{if(r)if(m<10&&m++,r.length>l&&(r.length=l),g>1e4)r.transitions=null,m=0,g=0,y.length>0&&(y=[]);else if(y.length>0&&!d){for(let e=0,t=y.length;e<t;e++)y[e][_e]=void 0;y=[]}if(n&&o.saveShared){o.structures.length>l&&(o.structures=o.structures.slice(0,l));let e=fe.subarray(t,ge);return!1===o.updateSharedData()?o.encode(a):e}c&Be&&(ge=t)}},this.findCommonStringsToPack=()=>(u=new Map,f||(f=Object.create(null)),e=>{let t=e&&e.threshold||4,r=this.pack?e.maxPrivatePackedValues||16:0;p||(p=this.sharedValues=[]);for(let[e,s]of u)s.count>t&&(f[e]=r++,p.push(e),n=!0);for(;this.saveShared&&!1===this.updateSharedData(););u=null});const E=r=>{ge>ye&&(fe=w(ge));var n,s=typeof r;if("string"===s){if(h){let t=h[r];if(t>=0)return void(t<16?fe[ge++]=t+224:(fe[ge++]=198,E(1&t?15-t>>1:t-16>>1)));if(u&&!e.pack){let e=u.get(r);e?e.count++:u.set(r,{count:1})}}let s,i=r.length;if(me&&i>=4&&i<1024){if((me.size+=i)>61440){let e,r=(me[0]?3*me[0].length+me[1].length:0)+10;ge+r>ye&&(fe=w(ge+r)),fe[ge++]=217,fe[ge++]=223,fe[ge++]=249,fe[ge++]=me.position?132:130,fe[ge++]=26,e=ge-t,ge+=4,me.position&&Oe(t,E),me=["",""],me.size=0,me.position=e}let e=Ee.test(r);return me[e?0:1]+=r,fe[ge++]=e?206:207,void E(i)}s=i<32?1:i<256?2:i<65536?3:5;let o=3*i;if(ge+o>ye&&(fe=w(ge+o)),i<64||!a){let e,t,a,o=ge+s;for(e=0;e<i;e++)t=r.charCodeAt(e),t<128?fe[o++]=t:t<2048?(fe[o++]=t>>6|192,fe[o++]=63&t|128):55296==(64512&t)&&56320==(64512&(a=r.charCodeAt(e+1)))?(t=65536+((1023&t)<<10)+(1023&a),e++,fe[o++]=t>>18|240,fe[o++]=t>>12&63|128,fe[o++]=t>>6&63|128,fe[o++]=63&t|128):(fe[o++]=t>>12|224,fe[o++]=t>>6&63|128,fe[o++]=63&t|128);n=o-ge-s}else n=a(r,ge+s,o);n<24?fe[ge++]=96|n:n<256?(s<2&&fe.copyWithin(ge+2,ge+1,ge+1+n),fe[ge++]=120,fe[ge++]=n):n<65536?(s<3&&fe.copyWithin(ge+3,ge+2,ge+2+n),fe[ge++]=121,fe[ge++]=n>>8,fe[ge++]=255&n):(s<5&&fe.copyWithin(ge+5,ge+3,ge+3+n),fe[ge++]=122,pe.setUint32(ge,n),ge+=4),ge+=n}else if("number"===s)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[ge++]=250,pe.setFloat32(ge,r),e<4||((t=r*te[(127&fe[ge])<<1|fe[ge+1]>>7])|0)===t)return void(ge+=4);ge--}fe[ge++]=251,pe.setFloat64(ge,r),ge+=8}else r>=-24?fe[ge++]=31-r:r>=-256?(fe[ge++]=56,fe[ge++]=~r):r>=-65536?(fe[ge++]=57,pe.setUint16(ge,~r),ge+=2):(fe[ge++]=58,pe.setUint32(ge,~r),ge+=4);else r<24?fe[ge++]=r:r<256?(fe[ge++]=24,fe[ge++]=r):r<65536?(fe[ge++]=25,fe[ge++]=r>>8,fe[ge++]=255&r):(fe[ge++]=26,pe.setUint32(ge,r),ge+=4);else if("object"===s)if(r){if(i){let e=i.get(r);if(e){if(fe[ge++]=216,fe[ge++]=29,fe[ge++]=25,!e.references){let t=i.idsToInsert||(i.idsToInsert=[]);e.references=[],t.push(e)}return e.references.push(ge-t),void(ge+=2)}i.set(r,{offset:ge-t})}let e=r.constructor;if(e===Object)_(r);else if(e===Array){(n=r.length)<24?fe[ge++]=128|n:be(n);for(let e=0;e<n;e++)E(r[e])}else if(e===Map)if((this.mapsAsObjects?!1!==this.useTag259ForMaps:this.useTag259ForMaps)&&(fe[ge++]=217,fe[ge++]=1,fe[ge++]=3),(n=r.size)<24?fe[ge++]=160|n:n<256?(fe[ge++]=184,fe[ge++]=n):n<65536?(fe[ge++]=185,fe[ge++]=n>>8,fe[ge++]=255&n):(fe[ge++]=186,pe.setUint32(ge,n),ge+=4),o.keyMap)for(let[e,t]of r)E(o.encodeKey(e)),E(t);else for(let[e,t]of r)E(e),E(t);else{for(let e=0,t=ie.length;e<t;e++){if(r instanceof ae[e]){let t=ie[e],n=t.tag;return null==n&&(n=t.getTag&&t.getTag.call(this,r)),n<24?fe[ge++]=192|n:n<256?(fe[ge++]=216,fe[ge++]=n):n<65536?(fe[ge++]=217,fe[ge++]=n>>8,fe[ge++]=255&n):n>-1&&(fe[ge++]=218,pe.setUint32(ge,n),ge+=4),void t.encode.call(this,r,E,w)}}if(r[Symbol.iterator]){if(he){let e=new Error("Iterable should be serialized as iterator");throw e.iteratorNotHandled=!0,e}fe[ge++]=159;for(let e of r)E(e);return void(fe[ge++]=255)}if(r[Symbol.asyncIterator]||Ie(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 E(e)}_(r)}}else fe[ge++]=246;else if("boolean"===s)fe[ge++]=r?245:244;else if("bigint"===s){if(r<BigInt(1)<<BigInt(64)&&r>=0)fe[ge++]=27,pe.setBigUint64(ge,r);else if(r>-(BigInt(1)<<BigInt(64))&&r<0)fe[ge++]=59,pe.setBigUint64(ge,-r-BigInt(1));else{if(!this.largeBigIntToFloat){r>=BigInt(0)?fe[ge++]=194:(fe[ge++]=195,r=BigInt(-1)-r);let e=[];for(;r;)e.push(Number(r&BigInt(255))),r>>=BigInt(8);return void Re(new Uint8Array(e.reverse()),w)}fe[ge++]=251,pe.setFloat64(ge,Number(r))}ge+=8}else{if("undefined"!==s)throw new Error("Unknown type: "+s);fe[ge++]=247}},_=!1===this.useRecords?this.variableMapSize?e=>{let t=Object.keys(e),r=Object.values(e),n=t.length;if(n<24?fe[ge++]=160|n:n<256?(fe[ge++]=184,fe[ge++]=n):n<65536?(fe[ge++]=185,fe[ge++]=n>>8,fe[ge++]=255&n):(fe[ge++]=186,pe.setUint32(ge,n),ge+=4),o.keyMap)for(let e=0;e<n;e++)E(o.encodeKey(t[e])),E(r[e]);else for(let e=0;e<n;e++)E(t[e]),E(r[e])}:e=>{fe[ge++]=185;let r=ge-t;ge+=2;let n=0;if(o.keyMap)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(o.encodeKey(t)),E(e[t]),n++);else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(t),E(e[t]),n++);fe[r+++t]=n>>8,fe[r+t]=255&n}:(e,t)=>{let r,i,a,o=s.transitions||(s.transitions=Object.create(null)),c=0,d=0;if(this.keyMap){a=Object.keys(e).map(e=>this.encodeKey(e)),d=a.length;for(let e=0;e<d;e++){let t=a[e];r=o[t],r||(r=o[t]=Object.create(null),c++),o=r}}else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(r=o[t],r||(1048576&o[_e]&&(i=65535&o[_e]),r=o[t]=Object.create(null),c++),o=r,d++);let u=o[_e];if(void 0!==u)u&=65535,fe[ge++]=217,fe[ge++]=u>>8|224,fe[ge++]=255&u;else{if(a||(a=o.__keys__||(o.__keys__=Object.keys(e))),void 0===i?(u=s.nextId++,u||(u=0,s.nextId=1),u>=256&&(s.nextId=(u=l)+1)):u=i,s[u]=a,!(u<l)){if(o[_e]=u,pe.setUint32(ge,3655335680),ge+=3,c&&(g+=m*c),y.length>=256-l&&(y.shift()[_e]=void 0),y.push(o),be(d+2),E(57344+u),E(a),t)return;for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&E(e[t]);return}fe[ge++]=217,fe[ge++]=u>>8|224,fe[ge++]=255&u,o=s.transitions;for(let e=0;e<d;e++)(void 0===o[_e]||1048576&o[_e])&&(o[_e]=u),o=o[a[e]];o[_e]=1048576|u,n=!0}if(d<24?fe[ge++]=128|d:be(d),!t)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&E(e[t])},w=e=>{let r;if(e>16777216){if(e-t>ue)throw new Error("Encoded buffer would be larger than maximum buffer size");r=Math.min(ue,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 le(r);return pe=new DataView(n.buffer,0,r),fe.copy?fe.copy(n,0,t,e):n.set(fe.slice(t,e)),ge-=t,t=0,ye=n.length-10,fe=n};let S=100,b=1e3;function*A(e,r,n){let s=e.constructor;if(s===Object){let t=!1!==o.useRecords;t?_(e,!0):we(Object.keys(e).length,160);for(let n in e){let s=e[n];t||E(n),s&&"object"==typeof s?r[n]?yield*A(s,r[n]):yield*I(s,r,n):E(s)}}else if(s===Array){let n=e.length;be(n);for(let s=0;s<n;s++){let n=e[s];n&&("object"==typeof n||ge-t>S)?r.element?yield*A(n,r.element):yield*I(n,r,"element"):E(n)}}else if(e[Symbol.iterator]&&!e.buffer){fe[ge++]=159;for(let n of e)n&&("object"==typeof n||ge-t>S)?r.element?yield*A(n,r.element):yield*I(n,r,"element"):E(n);fe[ge++]=255}else Ie(e)?(we(e.size,64),yield fe.subarray(t,ge),yield e,F()):e[Symbol.asyncIterator]?(fe[ge++]=159,yield fe.subarray(t,ge),yield e,F(),fe[ge++]=255):E(e);n&&ge>t?yield fe.subarray(t,ge):ge-t>S&&(yield fe.subarray(t,ge),F())}function*I(e,r,n){let s=ge-t;try{E(e),ge-t>S&&(yield fe.subarray(t,ge),F())}catch(i){if(!i.iteratorNotHandled)throw i;r[n]={},ge=t+s,yield*A.call(this,e,r[n])}}function F(){S=b,o.encode(null,Pe)}function C(e,t,r){return S=t&&t.chunkThreshold?b=t.chunkThreshold:100,e&&"object"==typeof e?(o.encode(null,Pe),r(e,o.iterateProperties||(o.iterateProperties={}),!0)):[o.encode(e)]}async function*T(e,t){for(let r of A(e,t,!0)){let e=r.constructor;if(e===de||e===Uint8Array)yield r;else if(Ie(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)F(),e?yield*T(e,t.async||(t.async={})):yield o.encode(e);else yield r}}this.encodeAsIterable=function(e,t){return C(e,t,A)},this.encodeAsAsyncIterable=function(e,t){return C(e,t,T)}}useBuffer(e){fe=e,pe=new DataView(fe.buffer,fe.byteOffset,fe.byteLength),ge=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 Se(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}}({useRecords:!1});const ke=Ne.encode,{NEVER:Le,ALWAYS:ve,DECIMAL_ROUND:De,DECIMAL_FIT:Me}=(Ne.encodeAsIterable,Ne.encodeAsAsyncIterable,{NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4}),Ue=512,Be=1024,Pe=2048;const je="dome-sdk-critical-error-style";function xe(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ke(e){if("undefined"==typeof document)return;const{title:t,errorCode:r,lang:n="en"}=e;!function(){if("undefined"==typeof document)return;if(document.getElementById(je))return;const e=document.createElement("style");e.id=je,e.textContent="\n :root {\n color-scheme: light dark;\n --itui-bg: #ffffff;\n --itui-overlay-bg: #ffffff;\n --itui-text-primary: #212121;\n --itui-text-secondary: #757575;\n --itui-border-color: #dee2e6;\n --itui-brand-color: #de0f17;\n --itui-info-color: #2196f3;\n }\n\n @media (prefers-color-scheme: dark) {\n :root {\n --itui-bg: #121212;\n --itui-overlay-bg: #212121;\n --itui-text-primary: #abb5bd;\n --itui-text-secondary: #80868c;\n --itui-border-color: #495057;\n --itui-brand-color: #ce4247;\n --itui-info-color: #5197cf;\n }\n }\n\n body.dome-sdk-critical-error {\n margin: 0;\n display: grid;\n place-items: center;\n padding: 24px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,\n 'Helvetica Neue', Arial, sans-serif;\n background: var(--itui-bg);\n color: var(--itui-text-primary);\n }\n\n .dome-sdk-critical-error__card {\n width: 80%;\n background: var(--itui-overlay-bg);\n border: 1px solid var(--itui-border-color);\n border-radius: 14px;\n padding: 24px;\n }\n\n .dome-sdk-critical-error__title {\n margin: 0 0 12px 0;\n line-height: 1.2;\n color: var(--itui-brand-color);\n }\n\n .dome-sdk-critical-error__text {\n line-height: 1.5;\n }\n\n .dome-sdk-critical-error__link {\n color: var(--itui-info-color);\n text-decoration: none;\n }\n\n .dome-sdk-critical-error__link:hover {\n text-decoration: underline;\n }\n\n .dome-sdk-critical-error__meta {\n font-size: 12px;\n color: var(--itui-text-secondary);\n }\n ",document.head.appendChild(e)}(),document.title=t,document.documentElement.lang=n,document.body.className="dome-sdk-critical-error";const s=xe(t),i=xe(r),a=xe("Chat with us");document.body.innerHTML=`\n <main class="dome-sdk-critical-error__card" role="alert" aria-live="assertive">\n <h3 class="dome-sdk-critical-error__title">${s}</h3>\n <p class="dome-sdk-critical-error__meta">${i}</p>\n <p class="dome-sdk-critical-error__text">\n Please contact support for further assistance.\n <a\n class="dome-sdk-critical-error__link"\n href="https://dome.so/user/dome/#/ui/fax2xpwj65000wjpausr"\n target="_blank"\n rel="noopener noreferrer"\n >${a}</a>\n </p>\n </main>\n `}const Ve=new Set(["dome","intouchapp"]);var He,ze,We,qe,Ge,$e,Je;!function(e){e.CONNECTION_SUCCESS="CONNECTION_SUCCESS",e.INIT="INIT",e.REQUEST_SAVE="REQUEST_SAVE",e.REQUEST_CLOSE="REQUEST_CLOSE",e.REQUEST_INITIAL_DATA="REQUEST_INITIAL_DATA",e.SET_DIRTY="SET_DIRTY",e.SEND_CLOSE="SEND_CLOSE",e.SEND_EXCEPTION="SEND_EXCEPTION"}(He||(He={})),function(e){e.INIT_MESSAGE_CHANNEL="INIT_MESSAGE_CHANNEL"}(ze||(ze={})),function(e){e.CONNECT="CONNECT"}(We||(We={})),function(e){e.REQUEST_CLOSE="REQUEST_CLOSE",e.REQUEST_SAVE="REQUEST_SAVE",e.DATA_CHANGE="DATA_CHANGE",e.SAVE_ERROR="SAVE_ERROR",e.SAVE_SUCCESS="SAVE_SUCCESS",e.INIT_ACK="INIT_ACK"}(qe||(qe={})),function(e){e.DATA_CHANGE="DATA_CHANGE",e.CFS_ERROR="CFS_ERROR",e.CFS_WRITE_SUCCESS="CFS_WRITE_SUCCESS",e.CFS_FILE_DATA="CFS_FILE_DATA",e.CFS_WRITE_FILE_ACK="CFS_WRITE_FILE_ACK",e.CFS_READ_FILE_ACK="CFS_READ_FILE_ACK",e.CFS_DELETE_FILE_ACK="CFS_DELETE_FILE_ACK",e.CFS_LIST_FILES_ACK="CFS_LIST_FILES_ACK",e.INIT_ACK="INIT_ACK",e.INIT_ERROR="INIT_ERROR",e.AF1_DATA_TOKEN_ACK="AF1_DATA_TOKEN_ACK",e.ERROR="ERROR",e.REFRESH="REFRESH",e.LOGGING_ENABLE="LOGGING_ENABLE",e.LOGGING_DISABLE="LOGGING_DISABLE",e.LOGGING_CLEAR="LOGGING_CLEAR",e.LOGGING_GET="LOGGING_GET"}(Ge||(Ge={})),function(e){e.APP_READY="APP_READY",e.INIT="INIT",e.CFS_READ_FILE="CFS_READ_FILE",e.CFS_WRITE_FILE="CFS_WRITE_FILE",e.CFS_DELETE_FILE="CFS_DELETE_FILE",e.CFS_LIST_FILES="CFS_LIST_FILES",e.FILE_DIRTY="FILE_DIRTY",e.OPEN_DEEPLINK="OPEN_DEEPLINK",e.AF1_DATA_TOKEN="AF1_DATA_TOKEN",e.LOGGING_GET_RET="LOGGING_GET_RET"}($e||($e={}));class Ye{constructor(){this.targetOrigin="*",this.isAppReady=!1,this.port2=null,this.runtimeHost="unknown",this.parentHostDetails=null,this.parentCapabilities=null,this.handleDeepLinkClick=e=>{if("webapp"!==this.runtimeHost)return;if(!(e.target instanceof Element))return;const t=e.target.closest("a[href]");if(!t)return;const r=t.getAttribute("href")??"";this.emitDeepLink(r)&&e.preventDefault()},console.info(`Initializing Dome Embedded App SDK v${r}`),this.detectHost(),this.setupDeepLinkInterception()}detectHost(){void 0!==window.AndroidBridge?this.runtimeHost="android":void 0!==window.webkit?this.runtimeHost="ios":this.runtimeHost="webapp",this.runtimeHost}setupDeepLinkInterception(){"webapp"===this.runtimeHost&&"undefined"!=typeof document&&document.addEventListener("click",this.handleDeepLinkClick,!0)}emitDeepLink(e){if("string"!=typeof e||""===e.trim())return console.warn("emitDeepLink called without a valid href"),!1;const t=e.split(":")[0]?.toLowerCase();return!(!t||!Ve.has(t))&&(this.sendMessage($e.OPEN_DEEPLINK,{url:e}),!0)}updateParentContext(e,t){if(!e&&!t)return;const r={...this.parentHostDetails??{type:this.runtimeHost},...e??{}};r.type||(r.type=this.runtimeHost);const n=t??this.parentCapabilities??r.capabilities;t&&(this.parentCapabilities=t),n?r.capabilities=n:delete r.capabilities,this.parentHostDetails=r,this.parentCapabilities=n??null,n?console.info("Host capabilities detected",{host_type:r.type,capabilities:n}):console.info("Host capabilities not found",{hostType:r.type})}getHost(){return this.parentHostDetails??{type:this.runtimeHost}}sendMessage(e,t,r){const n=this.buildVersionedMessage(e,t??null);if("android"!==this.runtimeHost)if(this.port2)this.port2.postMessage(n);else{switch(this.runtimeHost){case"ios":window?.webkit?.messageHandlers?window.webkit?.messageHandlers.appHandler.postMessage(JSON.stringify(n)):console.error("webkit.messageHandlers not found");break;case"webapp":console.error("Web connection is not established.");break;default:console.error("Unsupported host, cannot send message.")}this.runtimeHost}else{if(r){const e=this.toUint8Array(r),t=n.data&&"object"==typeof n.data?{...n.data,v:"1.0",data:e}:{v:"1.0",data:e},s=this.encodeCborMessage({...n,v:"1.0",data:t});this.port2?this.port2.postMessage(s):window.AndroidBridge?.sendMessage(s)}else{const e=JSON.stringify(n);this.port2?this.port2.postMessage(e):window.AndroidBridge?.sendMessage(e)}this.runtimeHost}}sendAppInit(){this.isAppReady||(this.isAppReady=!0,this.sendMessage(He.INIT,{sdk:{ver:r}}))}safeInvoke(e,t,r){const n=t?.[e];"function"==typeof n?n(r):console.warn(`Handler for '${String(e)}' is not defined.`)}setupParentConnection(){return new Promise((e,t)=>{switch(this.runtimeHost){case"android":window.receiveFromAndroid=e=>{let t=e;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=this.decodeCborBuffer(t);if(!e)return;t=e}const{type:r,data:n}=t||{};r&&this.handleMessage(r,n)};let n,s=!1;const i=()=>{s||(s=!0,n&&(clearTimeout(n),n=void 0),"android"===this.runtimeHost&&this.sendMessage(He.CONNECTION_SUCCESS),e())};this.setupMessageChannelListener(i),window.AndroidBridge?.sendMessage(JSON.stringify(this.buildVersionedMessage(ze.INIT_MESSAGE_CHANNEL,{sdk:{ver:r}}))),n=setTimeout(()=>{s||(s=!0,console.error("Android message channel CONNECT not received within timeout. Rendering critical error UI."),Ke({title:"Initialization Error",errorCode:"MESSAGE_CHANNEL_CONNECT_TIMEOUT"}),t(new Error("Android message channel initialization timed out.")))},5e3);break;case"ios":window.receiveFromIOS=e=>{this.handleMessage(e.type,e.data)},e();break;case"webapp":if(this.port2)return console.warn("Connection already established. Skipping reinitialization."),void e();this.setupMessageChannelListener(()=>{this.notifyConnectionSuccess(),e()}),window.parent?window.parent.postMessage({type:ze.INIT_MESSAGE_CHANNEL,data:{sdk:{ver:r}}},this.targetOrigin):console.error("Parent window not available to initialize message channel.");break;default:console.error("Unknown host."),t("Unknown host")}})}setupMessageChannelListener(e){if("undefined"==typeof window)return;const t=r=>{let n=r.data;if("string"==typeof n)try{n=JSON.parse(n)}catch{}(n?.type??n)===We.CONNECT&&(r.ports&&0!==r.ports.length?(this.port2=r.ports[0],this.port2.onmessage=e=>this.handlePortMessage(e),window.removeEventListener("message",t),e?.()):console.warn("Message channel CONNECT missing ports"))};window.addEventListener("message",t)}notifyConnectionSuccess(){this.sendMessage(He.CONNECTION_SUCCESS)}handlePortMessage(e){let t=e.data;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=this.decodeCborBuffer(t);if(!e)return;t=e}else if("string"==typeof t)try{t=JSON.parse(t)}catch{return}const{type:r,data:n}=t||{};r&&this.handleMessage(r,n)}handleMessage(e,t){throw new Error("Subclasses must implement handleMessage.")}decodeCborBuffer(e){let t;try{t=ne(this.toUint8Array(e))}catch{return null}if(t&&"object"==typeof t&&"data"in t){const e=t.data;if(e&&"object"==typeof e&&"data"in e){const r=e,n=r.data;if("string"==typeof r.object)try{r.object=JSON.parse(r.object)}catch{}const s=this.normalizeBinaryPayload(n);if(s)t.data={...r,data:s};else if("string"==typeof n)try{t.data={...r,data:JSON.parse(n)}}catch{t.data=r}}else{const r=this.normalizeBinaryPayload(e);r&&(t.data=r)}}return t}encodeCborMessage(e){const t=ke(e);return t.buffer instanceof ArrayBuffer&&0===t.byteOffset&&t.byteLength===t.buffer.byteLength?t.buffer:Uint8Array.prototype.slice.call(t).buffer}toUint8Array(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}normalizeBinaryPayload(e){if(e instanceof ArrayBuffer)return e;if(e instanceof Uint8Array)return this.copyBufferView(e.buffer,e.byteOffset,e.byteLength);if(ArrayBuffer.isView(e)){const t=e;return this.copyBufferView(t.buffer,t.byteOffset,t.byteLength)}return null}buildVersionedMessage(e,t){return t&&"object"==typeof t&&!Array.isArray(t)?{type:e,v:"1.0",data:{...t,v:"1.0"}}:{type:e,v:"1.0",data:{v:"1.0",data:t}}}copyBufferView(e,t,r){return e instanceof ArrayBuffer&&0===t&&r===e.byteLength?e:new Uint8Array(e,t,r).slice().buffer}}function Xe(e){const{prefix:t="",given:r="",middle:n="",family:s="",suffix:i=""}=e||{};return[t,r,n,s,i].filter(e=>e).join(" ").trim()}class Qe extends Ye{constructor(){super(),this.handler=null,this.pendingRequests=new Map,this.pendingInitAck=null}static init(e){return Qe.initialized?(console.warn("ViewerSdk is already initialized. Skipping initialization."),Qe.instance):(Qe.instance||(Qe.instance=new Qe,Qe.instance.setupParentConnection().then(()=>{try{Qe.instance.initializeViewerSdk()}catch(e){console.error("Error in initializeViewerSdk:",e)}}).catch(e=>{console.error("init: Error setting up parent connection!",e),console.trace("called from:")})),e&&Qe.instance.setHandler(e),Qe.initialized=!0,Qe.instance)}setHandler(e){this.handler=e,this.pendingInitAck&&(this.safeInvoke("onInitialData",this.handler,this.pendingInitAck),this.pendingInitAck=null)}canRead(e){return!!e?.includes("r")}canWrite(e){return!!e?.includes("w")||!!e?.includes("*")}initializeViewerSdk(){this.sendAppInit()}requestInitialData(){this.sendMessage(He.REQUEST_INITIAL_DATA)}requestSave(e,t){const r=function(){if("undefined"!=typeof window&&window.crypto&&window.crypto.randomUUID)return window.crypto.randomUUID();if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();throw new Error("UUID generation is not supported in this environment")}();return this.sendMessage(He.REQUEST_SAVE,{doc:e,isDataDirty:t,requestId:r}),new Promise((e,t)=>{this.pendingRequests.set(r,e),this.pendingRequests.set(r+"_reject",t),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),this.pendingRequests.delete(r+"_reject"))},3e4)})}handleOnSave(e){const{requestId:t,status:r,message:n}=e,s=this.pendingRequests.get(t),i=this.pendingRequests.get(t+"_reject");s&&("error"===r?i?.({status:r,message:n}):s({status:r,message:n}),this.pendingRequests.delete(t),this.pendingRequests.delete(t+"_reject"))}setDirty(e){this.sendMessage(He.SET_DIRTY,e)}sendClose(e,t){this.sendMessage(He.SEND_CLOSE,{doc:e,isDataDirty:t})}sendException(e){this.sendMessage(He.SEND_EXCEPTION,e)}handleMessage(e,t){if(e===qe.INIT_ACK&&this.updateParentContext(t?.host,t?.capabilities),this.handler)switch(e){case qe.INIT_ACK:this.safeInvoke("onInitialData",this.handler,t);break;case qe.DATA_CHANGE:this.safeInvoke("onDataChange",this.handler,t);break;case qe.REQUEST_CLOSE:this.safeInvoke("onCloseRequest",this.handler);break;case qe.REQUEST_SAVE:this.safeInvoke("onSaveRequest",this.handler);break;case qe.SAVE_SUCCESS:case qe.SAVE_ERROR:this.handleOnSave(t);break;default:console.warn(`No handler found for message type: ${e}`)}else e===qe.INIT_ACK?(console.warn("Handler not set. Storing INIT_ACK message for later processing."),this.pendingInitAck=t):console.error("Message handler not found for type:",e)}}Qe.initialized=!1;class Ze{constructor(){if(this.subtleCrypto=window.crypto?.subtle,!this.subtleCrypto)throw new Error("SubtleCrypto API is not available in this environment.")}async decrypt(e,t,r){try{if(!e)throw new Error("Invalid token");const n=this.base64UrlDecode(e);if(128!==n[0])throw new Error("Invalid version");n.slice(1,9);const s=n.slice(9,25),i=n.slice(25,-32),a=n.slice(-32),o=await this.deriveKey(t,r),{hmacKey:c,aesKey:l}=await this.splitKey(o),d=n.slice(0,-32);if(!new Uint8Array(await this.subtleCrypto.sign("HMAC",c,d)).every((e,t)=>e===a[t]))throw new Error("Invalid HMAC. Token has been tampered with!");const u=await this.subtleCrypto.decrypt({name:"AES-CBC",iv:s},l,i);return(new TextDecoder).decode(u)}catch(e){throw console.log("Error in decrypt:",e),e}}async deriveKey(e,t,r=1e4){const n=new TextEncoder,s=await this.subtleCrypto.importKey("raw",n.encode(e),"PBKDF2",!1,["deriveKey"]);return this.subtleCrypto.deriveKey({name:"PBKDF2",hash:"SHA-256",salt:n.encode(t),iterations:r},s,{name:"AES-CBC",length:256},!0,["encrypt","decrypt"])}async splitKey(e){const t=new Uint8Array(await this.subtleCrypto.exportKey("raw",e));return{hmacKey:await this.subtleCrypto.importKey("raw",t.slice(0,16),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"]),aesKey:await this.subtleCrypto.importKey("raw",t.slice(16),{name:"AES-CBC"},!1,["encrypt","decrypt"])}}base64UrlDecode(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t);return new Uint8Array([...r].map(e=>e.charCodeAt(0)))}}!function(e){e.READ="r",e.WRITE="w",e.FORWARD="f",e.SHARE="s",e.DOWNLOAD="d"}(Je||(Je={}));const et=Je;var tt,rt;!function(e){e.TEXT="text",e.JSON="json",e.BINARY="binary"}(tt||(tt={})),function(e){e.NO_INTERNET="NO_INTERNET",e.NO_PERMISSION="NO_PERMISSION",e.NOT_FOUND="NOT_FOUND",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.INVALID_REQUEST="INVALID_REQUEST",e.UNKNOWN="UNKNOWN"}(rt||(rt={}));const nt="1.1.0";function st(e){let t;if(1!==e.v)throw new Error(`Unsupported key blob version: ${e.v}`);return t=function(e){const{seed:t,obf:r}=e,n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r[e]^t+17*e&255;return n}(e),function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}(t)}class it{constructor(e,t){this.cardIuid=e,this.containerIuid=t,this.openPromise=null}isSupported(){return"undefined"!=typeof indexedDB}async openDb(){return this.isSupported()?(this.openPromise||(this.openPromise=new Promise(e=>{this.openWithVersion(it.DB_VERSION,e)})),this.openPromise):null}openWithVersion(e,t){let r="ensure";const n=indexedDB.open(this.cardIuid,e);n.onupgradeneeded=e=>{r=0===(e.oldVersion||0)?"create":"ensure",this.configureStores(n.result)},n.onsuccess=()=>{const e=n.result;if(!this.hasRequiredStores(e)){const r=e.version+1;return e.close(),void this.openWithVersion(r,t)}this.updateStoresMetadata(e,"ensure"===r).catch(()=>{}).finally(()=>t(e))},n.onerror=()=>t(null)}configureStores(e){e.objectStoreNames.contains(it.DATA_STORE)||e.createObjectStore(it.DATA_STORE),e.objectStoreNames.contains(it.NAME_LOOKUP_STORE)||e.createObjectStore(it.NAME_LOOKUP_STORE),e.objectStoreNames.contains(it.INFO_STORE)||e.createObjectStore(it.INFO_STORE),e.objectStoreNames.contains(it.FOLDER_CACHE_STORE)||e.createObjectStore(it.FOLDER_CACHE_STORE)}hasRequiredStores(e){const t=e.objectStoreNames;return t.contains(it.DATA_STORE)&&t.contains(it.NAME_LOOKUP_STORE)&&t.contains(it.INFO_STORE)&&t.contains(it.FOLDER_CACHE_STORE)}static nowMicros(){return Math.trunc(1e3*Date.now())}updateStoresMetadata(e,t){return Promise.all([this.ensureStoreVersion(e,it.DATA_STORE),this.ensureStoreVersion(e,it.NAME_LOOKUP_STORE),this.ensureStoreVersion(e,it.FOLDER_CACHE_STORE),this.updateCardInfo(e,t)]).then(()=>{})}ensureStoreVersion(e,t){return e.objectStoreNames.contains(t)?new Promise(r=>{try{const n=e.transaction(t,"readwrite"),s=n.objectStore(t),i=()=>r();n.oncomplete=i,n.onerror=i,n.onabort=i,s.put(nt,it.STORE_VERSION_KEY)}catch{r()}}):Promise.resolve()}async updateCardInfo(e,t){if(!e.objectStoreNames.contains(it.INFO_STORE))return;const r=await this.readInfoValue(e,"container_iuid"),n=t?await this.readInfoValue(e,"ts_c"):void 0,s=this.containerIuid??r??null,i=t&&n?n:it.nowMicros();await Promise.all([this.writeInfoValue(e,"container_iuid",s),this.writeInfoValue(e,"ts_c",i)]).catch(()=>{})}readInfoValue(e,t){return new Promise(r=>{try{const n=e.transaction(it.INFO_STORE,"readonly"),s=n.objectStore(it.INFO_STORE).get(t);s.onsuccess=()=>r(s.result),s.onerror=()=>r(void 0)}catch{r(void 0)}})}writeInfoValue(e,t,r){return new Promise(n=>{try{const s=e.transaction(it.INFO_STORE,"readwrite"),i=s.objectStore(it.INFO_STORE),a=()=>n();s.oncomplete=a,s.onerror=a,s.onabort=a,i.put(r,t)}catch{n()}})}keyFor(e){return e}static normalizeFolderName(e){if("string"!=typeof e)return it.DEFAULT_FOLDER_KEY;let t=e.trim();return t?(t=t.replace(/^\/+/,""),t?(t.endsWith("/")||(t+="/"),t||it.DEFAULT_FOLDER_KEY):it.DEFAULT_FOLDER_KEY):it.DEFAULT_FOLDER_KEY}folderListingKey(e){return it.normalizeFolderName(e)}static normalizeName(e){if("string"!=typeof e)return null;const t=e.trim();return t||null}async put(e,t){const r=await this.openDb();r&&await new Promise(n=>{const s=r.transaction(it.DATA_STORE,"readwrite");s.objectStore(it.DATA_STORE).put(t,e).onsuccess=()=>n(),s.oncomplete=()=>n(),s.onerror=()=>n(),s.onabort=()=>n()})}async get(e){const t=await this.openDb();if(t)return new Promise(r=>{const n=t.transaction(it.DATA_STORE,"readonly").objectStore(it.DATA_STORE).get(e);n.onsuccess=()=>r(n.result),n.onerror=()=>r(void 0)})}async delete(e){const t=await this.openDb();t&&await new Promise(r=>{const n=t.transaction(it.DATA_STORE,"readwrite");n.objectStore(it.DATA_STORE).delete(e).onsuccess=()=>r(),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}static async hashName(e){const t="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(!t?.subtle?.digest)throw new Error("CardFS name hashing requires SubtleCrypto support");const r=it.encodeText(e),n=await t.subtle.digest("SHA-256",r);return it.bufferToBase64(n)}static encodeText(e){if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e).buffer;const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t.buffer}static bufferToBase64(e){let t="";const r=new Uint8Array(e);for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return btoa(t)}async getIuidForName(e){const t=it.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const n=await it.hashName(t);return new Promise(e=>{const t=r.transaction(it.NAME_LOOKUP_STORE,"readonly").objectStore(it.NAME_LOOKUP_STORE).get(n);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)})}async upsertNameLookup(e,t){const r=it.normalizeName(e);if(!r)return;const n=await this.openDb();if(!n)return;const s=await it.hashName(r);await new Promise(e=>{const r=n.transaction(it.NAME_LOOKUP_STORE,"readwrite"),i=r.objectStore(it.NAME_LOOKUP_STORE);i.put(t,s);i.openCursor().onsuccess=e=>{const r=e.target.result;r&&(r.key!==s&&r.value===t&&r.delete(),r.continue())},r.oncomplete=()=>e(),r.onerror=()=>e(),r.onabort=()=>e()})}async deleteNameLookupByName(e){const t=it.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const n=await it.hashName(t);await new Promise(e=>{const t=r.transaction(it.NAME_LOOKUP_STORE,"readwrite");t.objectStore(it.NAME_LOOKUP_STORE).delete(n),t.oncomplete=()=>e(),t.onerror=()=>e(),t.onabort=()=>e()})}async deleteNameLookupByIuid(e){if(!e)return;const t=await this.openDb();t&&await new Promise(r=>{const n=t.transaction(it.NAME_LOOKUP_STORE,"readwrite");n.objectStore(it.NAME_LOOKUP_STORE).openCursor().onsuccess=t=>{const r=t.target.result;r&&(r.value===e&&r.delete(),r.continue())},n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}static estimateSize(e){if(null==e)return 0;if("undefined"!=typeof Blob&&e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(ArrayBuffer.isView(e))return e.byteLength;if("string"==typeof e)return new Blob([e]).size;try{return new Blob([JSON.stringify(e)]).size}catch{return 0}}async cacheDocument(e,t){if(!e?.iuid)return;await this.put(this.keyFor(`${e.iuid}_object`),e);const r=it.normalizeName(e.name);if(r&&await this.upsertNameLookup(r,e.iuid),void 0===t)return void await this.delete(this.keyFor(`${e.iuid}_data`));it.estimateSize(t)<=it.MAX_DATA_BYTES?await this.put(this.keyFor(`${e.iuid}_data`),t):await this.delete(this.keyFor(`${e.iuid}_data`))}async getByName(e){const t=it.normalizeName(e);if(!t)return null;const r=await this.getIuidForName(t);if(!r)return null;const n=await this.get(this.keyFor(`${r}_object`));if(!n)return null;return{iuid:r,object:n,data:await this.get(this.keyFor(`${r}_data`))}}async getByIuid(e){if(!e)return null;const t=await this.get(this.keyFor(`${e}_object`));if(!t)return null;return{iuid:e,object:t,data:await this.get(this.keyFor(`${e}_data`))}}async deleteByName(e){const t=await this.getByName(e);await this.deleteNameLookupByName(e),t&&(await this.delete(this.keyFor(`${t.iuid}_object`)),await this.delete(this.keyFor(`${t.iuid}_data`)))}async deleteByIuid(e,t){t&&await this.deleteNameLookupByName(t),await this.deleteNameLookupByIuid(e),await this.delete(this.keyFor(`${e}_object`)),await this.delete(this.keyFor(`${e}_data`))}async cacheFolderListing(e,t){const r=await this.openDb();if(!r)return;const n=this.folderListingKey(e??t.folder_name),s="object"==typeof t.data&&null!==t.data?t.data:Array.isArray(t.documents)?t.documents:{},i=Array.isArray(s)?{results:[...s]}:{...s},a={folder_name:n,folder_iuid:t.folder_iuid??null,card_iuid:this.cardIuid,time_last_fetch:Date.now(),data:i,last_index:t.last_index??null,last_page:t.last_page??null};await new Promise(e=>{const t=r.transaction(it.FOLDER_CACHE_STORE,"readwrite");t.objectStore(it.FOLDER_CACHE_STORE).put(a,n).onsuccess=()=>e(),t.oncomplete=()=>e(),t.onerror=()=>e(),t.onabort=()=>e()})}async getFolderListing(e){const t=await this.openDb();if(!t)return null;const r=this.folderListingKey(e);return new Promise(e=>{const n=t.transaction(it.FOLDER_CACHE_STORE,"readonly").objectStore(it.FOLDER_CACHE_STORE).get(r);n.onsuccess=()=>e(n.result),n.onerror=()=>e(null)})}}it.DB_VERSION=3,it.DATA_STORE="cardfs",it.NAME_LOOKUP_STORE="cardfs_name_iuid_lookup",it.INFO_STORE="info",it.FOLDER_CACHE_STORE="folder_cache",it.STORE_VERSION_KEY="ver",it.DEFAULT_FOLDER_KEY="/",it.MAX_DATA_BYTES=5242880;class at extends Ye{buildCardFsMessagePayload(e,t){return{...e.name?{name:e.name}:{},...e.iuid?{iuid:e.iuid}:{},...t??{}}}formatFolderPath(e){if("string"!=typeof e)return;let t=e.trim();return t&&(t=t.replace(/^\/+/,""),t)?(t.endsWith("/")||(t+="/"),t):void 0}assertValidReadHandler(e){if(!e||"function"!=typeof e.next)throw new Error("cardFS.read requires a handler with a next() function");return e}assertValidListHandler(e){if(!e||"function"!=typeof e.next)throw new Error("cardFS.list requires a handler with a next() function");return e}invokeReadHandlerNext(e,t){try{e.next(t)}catch(e){console.error("cardFS.read handler next() threw",e)}}invokeReadHandlerError(e,t){if(e.error)try{e.error(t)}catch(e){console.error("cardFS.read handler error() threw",e)}}sanitizeReadData(e,t){if(null==e)return{value:e,stripped:!1};try{if(it.estimateSize(e)>it.MAX_DATA_BYTES){const e=t?` for ${t}`:"";return console.warn(`cardFS.read payload data exceeded ${it.MAX_DATA_BYTES} bytes${e}; omitting data`),{value:void 0,stripped:!0}}}catch(e){console.warn("cardFS.read payload size estimation failed",e)}return{value:e,stripped:!1}}normalizeReadData(e,t,r){if(null==e)return e;const n="string"==typeof t?t.toLowerCase():"",s="string"==typeof r?r.toLowerCase():"",i=n.includes("application/json")||n.endsWith("+json")||s===tt.JSON,a=n.startsWith("text/")||s===tt.TEXT,o=e instanceof ArrayBuffer||ArrayBuffer.isView(e),c=()=>{const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return(new TextDecoder).decode(t)};if(i){if(e&&"object"==typeof e&&!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))return e;if(o)try{return JSON.parse(c())}catch{return c()}if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}if(a){const t=o?c():e;if("string"==typeof t)try{return JSON.parse(t)}catch{return t}return t}return e}encodeTextPayload(e){if("string"==typeof e)return e;if(null==e)return"";if("object"==typeof e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}encodeJsonPayload(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return String(e??"")}}normalizeWriteData(e,t){return t===tt.TEXT?this.encodeTextPayload(e):t===tt.BINARY?e:this.encodeJsonPayload(e)}base64EncodeBinaryData(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let r="";for(let e=0;e<t.length;e+=1)r+=String.fromCharCode(t[e]);return btoa(r)}getWriteDataSizeBytes(e){return null==e?0:"string"==typeof e?(new TextEncoder).encode(e).length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:0}getCardIuid(){return this.dataStore?.iuid||null}ensureCardFsCache(){if(!this.shouldUseCardFsFallback())return null;if(!this.cardFsCache){const e=this.getCardIuid();e&&(this.cardFsCache=new it(e,this.containerIuid))}return this.cardFsCache}supportsParentCardFs(){const e=this.parentCapabilities?.card_fs;return!!e?.ver&&e.ver===nt}shouldUseCardFsFallback(){return!this.supportsParentCardFs()}constructor(){super(),this.handler=null,this.accessToken="",this.devMode=!1,this.permission=null,this.userRole=null,this.fsReadRequests=new Map,this.fsWriteRequests=new Map,this.fsListRequests=new Map,this.cardFsCache=null,this.pendingAcks=new Map,this.consoleCaptureInstalled=!1,this.consoleCaptureEnabled=!1,this.consoleCaptureMinLevel=null,this.consoleLogBuffer=new Array(at.MAX_CONSOLE_LOG_ENTRIES).fill(null),this.consoleLogWriteIndex=0,this.consoleLogSize=0,this.handleMessage=(e,t)=>{if(e===Ge.INIT_ACK&&this.updateParentContext(t?.host,t?.capabilities),e===Ge.CFS_ERROR){const e=t?.messageId,r=this.createCardFsError(t,"Unknown cardFS error");if(e&&this.pendingAcks.has(e)){const t=this.pendingAcks.get(e);clearTimeout(t.timeout),this.pendingAcks.delete(e),t.reject(r)}if(e){if(this.fsReadRequests.has(e))return void this.failFsReadRequest(e,r);if(this.fsWriteRequests.has(e))return void this.failFsWriteRequest(e,r);if(this.fsListRequests.has(e))return void this.failFsListRequest(e,r)}return void console.warn("CardSdk: CFS_ERROR received but no matching fs request",t?.messageId??t?.name)}this.handleFsAckMessage(e,t);const r=t?.messageId;if(e!==Ge.CFS_LIST_FILES_ACK){if(r&&this.pendingAcks.has(r)){const n=this.pendingAcks.get(r);if(n.ackType===e)return clearTimeout(n.timeout),this.pendingAcks.delete(r),void n.resolve(t)}if(r||!this.resolvePendingAckByType(e,t)){if(!this.handler)throw new Error("Message handler not found!");switch(e){case Ge.INIT_ACK:this.applyLoggingConfig(t?.logging),this.dataStore.kw1=t.key_wa1,this.dataStore.iuid=t.iuid,"boolean"==typeof t?.dev_mode&&(this.devMode=t.dev_mode,this.dataStore.dev_mode=t.dev_mode),t.iuid?this.shouldUseCardFsFallback()?this.cardFsCache=new it(t.iuid,this.containerIuid):this.cardFsCache=null:this.shouldUseCardFsFallback()||(this.cardFsCache=null);try{this.cryptoA01.decrypt(this.dataStore.denc,t.key_wa1+this.dataStore.kw2,t.iuid).then(e=>{const r=JSON.parse(e),n=r?.container?.iuid;n&&(this.containerIuid=n,this.shouldUseCardFsFallback()&&this.dataStore?.iuid&&(this.cardFsCache=new it(this.dataStore.iuid,this.containerIuid)));const s="string"==typeof r?.api_token?r.api_token.trim():"";s?this.accessToken=s:console.warn("CardSdk: INIT_ACK payload missing api_token; fallback APIs may fail without auth"),this.permission=r?.perms_v2??null,this.userRole=r?.role??null;const i=this.attachUserFullName(r?.user);this.handler&&this.safeInvoke("onInit",this.handler,{...r,user:i,ui:t.ui}),delete this.dataStore.denc}).catch(e=>{throw console.error("Final decrypt error",e),e})}catch(e){console.error("Decryption failed!",e),this.sendEventError("dec2_failed",e.message)}break;case Ge.INIT_ERROR:this.safeInvoke("onInitError",this.handler,t);break;case Ge.CFS_FILE_DATA:{const e=t?.messageId;if(e&&this.fsReadRequests.has(e)){const{messageId:r,...n}=t||{};return void this.handleFsReadDataMessage(e,n)}console.warn("CardSdk: CFS_FILE_DATA received but no matching fsRead request",t?.messageId??t?.name);break}case Ge.DATA_CHANGE:this.safeInvoke("onFileChange",this.handler,t);case Ge.CFS_WRITE_SUCCESS:{const e=t?.messageId;if(e&&this.fsWriteRequests.has(e))return void this.handleFsWriteSuccess(e,t);console.warn("CardSdk: CFS_WRITE_SUCCESS received but no matching fsWrite request",t?.messageId??t?.name);break}case Ge.ERROR:this.safeInvoke("onError",this.handler,t);break;case Ge.REFRESH:this.safeInvoke("onRefreshRequest",this.handler,t);break;case Ge.AF1_DATA_TOKEN_ACK:break;case Ge.LOGGING_ENABLE:this.applyLoggingConfig({status:"enabled",level:t?.level??t?.logging?.level});break;case Ge.LOGGING_DISABLE:this.consoleCaptureEnabled=!1;break;case Ge.LOGGING_CLEAR:this.clearConsoleLogs();break;case Ge.LOGGING_GET:this.sendConsoleLogs();break;case Ge.CFS_READ_FILE_ACK:case Ge.CFS_WRITE_FILE_ACK:case Ge.CFS_DELETE_FILE_ACK:break;default:console.warn(`No handler found for message type: ${e}`)}}}else r&&this.fsListRequests.has(r)?this.handleFsListDataMessage(r,t):console.warn("CardSdk: CFS_LIST_FILES_ACK received but no matching fsList request",t?.messageId??t?.name)},this.cryptoA01=new Ze,this.cardFS={read:(e,t,r=!0)=>{this.cardFSRead(e,t,r)},readById:(e,t,r=!0)=>{this.cardFSReadById(e,t,r)},write:(e,t,r,n)=>this.cardFSWrite(e,t,r,n),writeById:(e,t,r,n)=>this.cardFSWriteById(e,t,r,n),delete:(e,t)=>this.cardFSDelete(e,t),deleteById:(e,t)=>this.cardFSDeleteById(e,t),list:(e,t)=>this.cardFSList(e,t)}}static async init(e,t,r){try{return at.instance||(at.instance=new at,at.instance.setupParentConnection().then(()=>{at.instance.initializeCardSdk(e)}).catch(e=>{console.error(e)}),t&&at.instance.setHandler(t)),at.instance}catch(e){throw console.error("CardSdk: Unrecoverable error in init",e),e}}setHandler(e){this.handler=e}isCardFsFallbackEnabled(){return this.shouldUseCardFsFallback()}openDeepLink(e){this.emitDeepLink(e)||console.warn("openDeepLink ignored; provide a dome:// or intouchapp:// href")}hasPerm(e){if(!e)return!1;const t=this.userRole?.abbr;if(!t)return!0;if("o"===t)return!0;const r=this.permission?.[t];return"string"==typeof r?!!r.includes("*")||r.includes(e):at.DEFAULT_ROLE_PERMISSIONS.includes(e)}canRead(){return this.hasPerm(Je.READ)}canWrite(){return this.hasPerm(Je.WRITE)}deriveSecretSeed(e){const t=e.split("").reverse().join("").substring(4,25);if(!t)throw new Error("Cannot decrypt (1)");return t}getCardIuidEnc(e){try{const t=e.pathname.split("/wa/").filter(Boolean);if(t.length<2)return null;return(t[1]?.split("/")[0]??null)||null}catch(e){return console.warn("CardSdk: Failed to extract seed token",e),null}}async requestAf1DataFromParent(e){const t=await this.sendMessageWithAck($e.AF1_DATA_TOKEN,{sdk:{ver:r}},Ge.AF1_DATA_TOKEN_ACK),{messageId:n,...s}=t||{},{cie:i,ck:a,dev_token:o}=s;if(!i||!a||!o)throw new Error("Invalid AF1 data token payload");const c=await this.fetchAf1Data(i,a,o,e),l=c?.data_af1??c?.data?.data_af1;if(!l)throw new Error("AF1 data fetch returned empty payload");return window.IT_DATA_AF1=l,c?.ver&&(window.IT_VERSION=c.ver),c?.env&&(window.IT_ENV=c.env),{dataAf1:l,cie:i}}async fetchAf1Data(e,t,r,n){if(!(e&&t&&r&&n))throw new Error("Invalid AF1 data fetch parameters");const s=new URL(`https://dome.so/api/v1/cards/e/${encodeURIComponent(e)}/data_af1/`);s.searchParams.set("dt",r),s.searchParams.set("rt",n),s.searchParams.set("ck",t);const i=await fetch(s.toString(),{method:"GET"});if(!i.ok){const e=await i.text().catch(()=>i.statusText);throw new Error(`AF1 data fetch failed: ${i.status} ${e}`)}return i.json()}async initializeCardSdk(e){let t="CardSdk::initializeCardSdk:";try{if(!e)throw new Error("Invalid secret");const r=window.location.href,n=new URL(r),s=n.searchParams.get("rt");if(!s)throw new Error("Missing request token");let i=this.getCardIuidEnc(n),a=window.IT_DATA_AF1;if(!a){const{dataAf1:e,cie:t}=await this.requestAf1DataFromParent(s);a=e,i=t||i}if(!a)throw console.error(t,"No data"),new Error("No data");if(!i)throw new Error("Cannot decrypt (missing seed)");const o=this.deriveSecretSeed(i),c=await this.cryptoA01.decrypt(a,e,o);try{const e=JSON.parse(c);if(!e.ite)throw new Error("Invalid data");this.dataStore={denc:e.d,kw2:e.kw2},at.instance.sendInit(e.ite)}catch(e){throw console.error("Initial Decryption failed (2):",e),e}}catch(e){console.error(t,"Init failed:",e),this.sendEventError("init_failed",e.message)}}async sendInit(e){const t={token:e,sdk:{ver:r}},n=this.getWebappDetails();n&&(t.wa=n),this.sendMessage($e.INIT,t)}getWebappDetails(){if("undefined"==typeof window)return null;let e={};const t=window.IT_VERSION,r=window.IT_ENV;return t&&(e.ver=String(t)),r&&(e.env=String(r)),Object.keys(e).length?e:null}sendMessageWithAck(e,t,r,n=15e3,s,i){const a=crypto.randomUUID();if(s)try{s(a)}catch(e){return Promise.reject(e)}return new Promise((s,o)=>{const c=setTimeout(()=>{this.pendingAcks.delete(a);const e=new Error(`${r} not received in time`);this.isCardFsAckType(r)&&(e.code=rt.TIMEOUT),o(e)},n);this.pendingAcks.set(a,{resolve:s,reject:o,timeout:c,ackType:r}),this.sendMessage(e,{...t,messageId:a},i)})}resolvePendingAckByType(e,t){for(const[r,n]of this.pendingAcks.entries())if(n.ackType===e)return clearTimeout(n.timeout),this.pendingAcks.delete(r),n.resolve(t),!0;return!1}cardFSRead(e,t,r=!0){const n={name:e},s=this.assertValidReadHandler(t);this.cardFSReadInternal(n,s,r,"read")}cardFSReadById(e,t,r=!0){const n={iuid:e},s=this.assertValidReadHandler(t);this.cardFSReadInternal(n,s,r,"readById")}cardFSReadInternal(e,t,r,n){if(this.shouldUseCardFsFallback())return void this.cardFSReadFallback(e,void 0,t,r).catch(e=>{const r=e instanceof Error?e:new Error(String(e));this.invokeReadHandlerError(t,this.toCardFsErrorPayload(r))});let s=null;const i=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document";this.sendMessageWithAck($e.CFS_READ_FILE,this.buildCardFsMessagePayload(e,{allow_stale:r}),Ge.CFS_READ_FILE_ACK,at.CARD_FS_ACK_TIMEOUT_MS,e=>{s=e;const a={name:i,handler:t,allowStale:r,timeoutMessage:`cardFS.${n} timed out for ${i}`};this.fsReadRequests.set(e,a)}).catch(e=>{const r=e instanceof Error?e:new Error(String(e));s?this.failFsReadRequest(s,r):this.invokeReadHandlerError(t,this.toCardFsErrorPayload(r))})}isCardFsAckType(e){return e===Ge.CFS_READ_FILE_ACK||e===Ge.CFS_WRITE_FILE_ACK||e===Ge.CFS_DELETE_FILE_ACK||e===Ge.CFS_LIST_FILES_ACK}cardFSWrite(e,t,r=tt.JSON,n){const s={name:e};return"android"===this.runtimeHost&&r===tt.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then(e=>this.cardFSWriteInternal(s,e,r,n,"write")):this.cardFSWriteInternal(s,t,r,n,"write")}cardFSWriteById(e,t,r=tt.JSON,n){const s={iuid:e};return"android"===this.runtimeHost&&r===tt.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then(e=>this.cardFSWriteInternal(s,e,r,n,"writeById")):this.cardFSWriteInternal(s,t,r,n,"writeById")}cardFSWriteInternal(e,t,r,n,s){return this.shouldUseCardFsFallback()?this.cardFSWriteFallback(e,t,r).catch(e=>{throw this.toCardFsErrorPayload(e)}):new Promise((i,a)=>{let o=null;const c=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document",l=this.normalizeWriteData(t,r),d=this.getWriteDataSizeBytes(l),u="cbor"===this.parentCapabilities?.card_fs?.array_buffer,h=r===tt.BINARY&&"android"===this.runtimeHost&&u;let f=l;r!==tt.BINARY||h||(l instanceof ArrayBuffer||ArrayBuffer.isView(l)?f=this.base64EncodeBinaryData(l):console.warn("cardFS.write binary payload is not ArrayBuffer/TypedArray; sending raw data")),e.name,e.iuid,this.sendMessageWithAck($e.CFS_WRITE_FILE,this.buildCardFsMessagePayload(e,{data:h?null:f,file_type:r,file_size:d}),Ge.CFS_WRITE_FILE_ACK,at.CARD_FS_ACK_TIMEOUT_MS,e=>{o=e;const t={name:c,onUpdate:n,resolve:i,reject:a,timeoutMessage:`cardFS.${s} timed out for ${c}`};this.fsWriteRequests.set(e,t)},h?l:void 0).catch(e=>{const t=e instanceof Error?e:new Error(String(e));o?this.failFsWriteRequest(o,t):a(this.toCardFsErrorPayload(t))})})}cardFSDelete(e,t){const r={name:e};return this.cardFSDeleteInternal(r,t,"delete")}cardFSDeleteById(e,t){const r={iuid:e};return this.cardFSDeleteInternal(r,t,"deleteById")}cardFSDeleteInternal(e,t,r){return this.shouldUseCardFsFallback()?this.cardFSDeleteFallback(e).then(e=>{try{t?.(e)}catch(e){console.error(`cardFS.${r} fallback callback threw`,e)}return e}).catch(e=>{throw this.toCardFsErrorPayload(e)}):new Promise((r,n)=>{this.sendMessageWithAck($e.CFS_DELETE_FILE,this.buildCardFsMessagePayload(e),Ge.CFS_DELETE_FILE_ACK,at.CARD_FS_ACK_TIMEOUT_MS).then(e=>{const{messageId:n,...s}=e||{};t?.(s),r(s)}).catch(e=>{n(this.toCardFsErrorPayload(e))})})}cardFSList(e,t){const r=this.assertValidListHandler(t),n=this.formatFolderPath(e);if(this.shouldUseCardFsFallback())return void this.cardFSListFallbackStream(n,r);const s=n?{name:n}:{},i=crypto.randomUUID(),a={name:n??"folder listing",handler:r,timeoutMessage:"cardFS.list timed out"};this.fsListRequests.set(i,a),this.resetFsListProgressTimeout(i),this.sendMessage($e.CFS_LIST_FILES,{...s,messageId:i})}async cardFSListFallbackStream(e,t){const r=this.ensureCardFsCache();let n=!1;if(r)try{const s=await r.getFolderListing(e);if(s){const e=Array.isArray(s.data?.results)?s.data.results:[];t.next(this.normalizeListResult({documents:e,folder_name:s.folder_name,folder_iuid:s.folder_iuid??void 0,last_index:s.last_index??null,last_page:s.last_page??null,from_cache:!0,is_dirty:!0,is_complete:!1})),n=!0}}catch(e){console.warn("cardFS.list cache lookup failed",e)}try{const r=await this.cardFSListFallback(e);t.next(this.normalizeListResult({...r,is_complete:!0}))}catch(e){n?console.warn("cardFS.list fresh fetch failed",e):t.error?.(this.toCardFsErrorPayload(e))}}resetFsReadProgressTimeout(e){const t=this.fsReadRequests.get(e);t&&(t.progressTimeout&&clearTimeout(t.progressTimeout),t.progressTimeout=setTimeout(()=>{this.failFsReadRequest(e,{code:rt.TIMEOUT,message:t.timeoutMessage})},at.FS_RESPONSE_TIMEOUT_MS))}resetFsWriteProgressTimeout(e){const t=this.fsWriteRequests.get(e);t&&(t.progressTimeout&&clearTimeout(t.progressTimeout),t.progressTimeout=setTimeout(()=>{this.failFsWriteRequest(e,{code:rt.TIMEOUT,message:t.timeoutMessage})},at.FS_RESPONSE_TIMEOUT_MS))}resetFsListProgressTimeout(e){const t=this.fsListRequests.get(e);t&&(t.progressTimeout&&clearTimeout(t.progressTimeout),t.progressTimeout=setTimeout(()=>{this.failFsListRequest(e,{code:rt.TIMEOUT,message:t.timeoutMessage})},at.FS_RESPONSE_TIMEOUT_MS))}handleFsReadDataMessage(e,t){const r=this.fsReadRequests.get(e);if(!r)return;let n=t?.data;"string"!=typeof n||"base64"!==t?.encoding&&!this.isBinaryReadPayload(t)||(n=this.decodeBase64BinaryData(n));const s=this.sanitizeReadData(n,r.name),i=this.normalizeReadData(s.value,t?.object?.mimetype,t?.file_type),a=Boolean(t?.from_cache??t?.is_stale),o={name:t?.name,iuid:t?.iuid??null,object:t?.object,data:i,is_dirty:"boolean"==typeof t?.is_dirty?t.is_dirty:void 0,is_stale:Boolean(t?.is_stale??t?.from_cache),is_complete:"boolean"==typeof t?.is_complete?t.is_complete:!r.allowStale||!a};this.invokeReadHandlerNext(r.handler,o),o.is_complete&&r.progressTimeout&&(clearTimeout(r.progressTimeout),r.progressTimeout=void 0),r.cleanupTimeout&&clearTimeout(r.cleanupTimeout),r.cleanupTimeout=setTimeout(()=>{this.clearFsReadRequest(e)},at.FS_READ_RETENTION_MS)}handleFsAckMessage(e,t){const r=t?.messageId;if(!r)return!1;if(e===Ge.CFS_READ_FILE_ACK){const e=this.fsReadRequests.get(r);return!!e&&(this.resetFsReadProgressTimeout(r),e.cleanupTimeout&&clearTimeout(e.cleanupTimeout),e.cleanupTimeout=setTimeout(()=>{this.clearFsReadRequest(r)},at.FS_READ_RETENTION_MS),!0)}if(e===Ge.CFS_WRITE_FILE_ACK){const e=this.fsWriteRequests.get(r);if(!e)return!1;const{messageId:n,...s}=t||{};if("function"==typeof e.onUpdate)try{e.onUpdate(s)}catch(e){console.error("cardFS.write onUpdate callback threw",e)}return this.resetFsWriteProgressTimeout(r),!0}return!1}clearFsReadRequest(e){const t=this.fsReadRequests.get(e);if(t)return t.progressTimeout&&clearTimeout(t.progressTimeout),t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),this.fsReadRequests.delete(e),t}sendConsoleLogs(){const e={logs:this.getConsoleLogs().map(e=>({l:e.level,ts:e.timestamp,args:e.args})),ver:"1.0.0",sdk:{ver:r}};this.sendMessage($e.LOGGING_GET_RET,e)}setupConsoleCapture(){if(this.consoleCaptureInstalled||"undefined"==typeof console)return;["log","info","warn","error","debug"].forEach(e=>{const t=console[e];if("function"!=typeof t)return;const r=t.bind(console);console[e]=(...t)=>{try{this.recordConsoleEntry(e,t)}catch{}r(...t)}}),this.consoleCaptureInstalled=!0}applyLoggingConfig(e){if(!e)return;"enabled"===e.status?(this.consoleCaptureEnabled=!0,this.setupConsoleCapture()):"disabled"===e.status&&(this.consoleCaptureEnabled=!1);const t="string"==typeof e.level?e.level.toLowerCase():null;t&&this.isConsoleLogLevel(t)&&(this.consoleCaptureMinLevel=t)}isConsoleLogLevel(e){return"log"===e||"info"===e||"warn"===e||"error"===e||"debug"===e}shouldCaptureLevel(e){if(!this.consoleCaptureEnabled)return!1;if(!this.consoleCaptureMinLevel)return!0;const t=["debug","log","info","warn","error"];return t.indexOf(e)>=t.indexOf(this.consoleCaptureMinLevel)}recordConsoleEntry(e,t){if(!this.shouldCaptureLevel(e))return;const r={level:e,timestamp:(new Date).toISOString(),args:t.map(e=>this.serializeConsoleArg(e))};this.consoleLogBuffer[this.consoleLogWriteIndex]=r,this.consoleLogWriteIndex=(this.consoleLogWriteIndex+1)%at.MAX_CONSOLE_LOG_ENTRIES,this.consoleLogSize=Math.min(this.consoleLogSize+1,at.MAX_CONSOLE_LOG_ENTRIES)}clearConsoleLogs(){this.consoleLogBuffer.fill(null),this.consoleLogWriteIndex=0,this.consoleLogSize=0}getConsoleLogs(){if(0===this.consoleLogSize)return[];if(this.consoleLogSize<at.MAX_CONSOLE_LOG_ENTRIES)return this.consoleLogBuffer.slice(0,this.consoleLogSize).filter(e=>null!==e);const e=[];for(let t=0;t<at.MAX_CONSOLE_LOG_ENTRIES;t+=1){const r=(this.consoleLogWriteIndex+t)%at.MAX_CONSOLE_LOG_ENTRIES,n=this.consoleLogBuffer[r];n&&e.push(n)}return e}serializeConsoleArg(e){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return this.truncateSerializedArg(e);if(void 0===e)return this.truncateSerializedArg({type:"undefined"});if("bigint"==typeof e)return this.truncateSerializedArg({type:"bigint",value:e.toString()});if("symbol"==typeof e)return this.truncateSerializedArg({type:"symbol",value:e.toString()});if("function"==typeof e)return this.truncateSerializedArg({type:"function",name:e.name||null});if(e instanceof Error)return this.truncateSerializedArg({type:"error",name:e.name,message:e.message,stack:e.stack??null});try{return this.truncateSerializedArg(JSON.parse(JSON.stringify(e)))}catch{try{return this.truncateSerializedArg({type:"object",value:String(e)})}catch{return this.truncateSerializedArg({type:"object",value:"[unserializable]"})}}}truncateSerializedArg(e){try{if("string"==typeof e)return e.length>at.MAX_CONSOLE_ARG_CHARS?{type:"truncated",preview:e.slice(0,at.MAX_CONSOLE_ARG_CHARS),original_length:e.length}:e;const t=JSON.stringify(e);if("string"==typeof t&&t.length>at.MAX_CONSOLE_ARG_CHARS)return{type:"truncated",preview:this.buildTruncatedPreview(e),original_length:t.length}}catch{}return e}buildTruncatedPreview(e){const t=new WeakSet,r=(e,n)=>{if("string"==typeof e)return(e=>e.length<=at.MAX_CONSOLE_STRING_PREVIEW_CHARS?e:{type:"truncated",preview:e.slice(0,at.MAX_CONSOLE_STRING_PREVIEW_CHARS),original_length:e.length})(e);if(!e||"object"!=typeof e)return e;if(t.has(e))return{type:"circular"};if(n>=3)return{type:"truncated",reason:"max_depth"};if(t.add(e),Array.isArray(e)){const t=e.slice(0,5).map(e=>r(e,n+1));return e.length>5&&t.push({type:"truncated",remaining:e.length-5}),t}const s=Object.entries(e),i={};for(const[e,t]of s.slice(0,5))i[e]=r(t,n+1);return s.length>5&&(i.__truncated__={remaining:s.length-5}),i};return r(e,0)}failFsReadRequest(e,t){const r=this.clearFsReadRequest(e);r&&this.invokeReadHandlerError(r.handler,this.toCardFsErrorPayload(t))}clearFsWriteRequest(e){const t=this.fsWriteRequests.get(e);if(t)return t.progressTimeout&&clearTimeout(t.progressTimeout),this.fsWriteRequests.delete(e),t}clearFsListRequest(e){const t=this.fsListRequests.get(e);if(t)return t.progressTimeout&&clearTimeout(t.progressTimeout),this.fsListRequests.delete(e),t}failFsWriteRequest(e,t){const r=this.clearFsWriteRequest(e);r&&r.reject(this.toCardFsErrorPayload(t))}failFsListRequest(e,t){const r=this.clearFsListRequest(e);r&&r.handler.error?.(this.toCardFsErrorPayload(t))}handleFsWriteSuccess(e,t){const r=this.clearFsWriteRequest(e);if(!r)return;const{messageId:n,...s}=t||{};r.resolve(s)}handleFsListDataMessage(e,t){const r=this.fsListRequests.get(e);if(!r)return;this.resetFsListProgressTimeout(e);const{messageId:n,...s}=t||{},i=this.normalizeListResult(s);r.handler.next(i),i.is_complete&&this.clearFsListRequest(e)}createCardFsError(e,t){const r=new Error(e?.message||t),n=e?.error_code;return n&&Object.values(rt).includes(n)&&(r.code=n),r}toCardFsErrorPayload(e,t="Unknown cardFS error"){const r="string"==typeof e?.message?e.message:"string"==typeof e?e:t,n=e?.code??e?.error_code;return n&&Object.values(rt).includes(n)?{code:n,message:r}:{message:r}}async cardFSReadFallback(e,t,r,n=!0){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.read fallback is disabled because parent supports card_fs");const s=this.getCardIuid();if(!s)throw new Error("cardFS.read fallback failed: card not initialized");const i=this.ensureCardFsCache();let a,o=!1;const c=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document",l=(n,s,i,a,c,l,d)=>{if(!n)return null;const u=c??e.name??n?.name??e.iuid??"document",h=l??n?.iuid??e.iuid??null,f=!1!==d?.includeData,p=f?this.sanitizeReadData(s,u).value:void 0,y={name:u,iuid:h,object:n,data:f?this.normalizeReadData(p,n?.mimetype,n?.file_type??n?.fileType):void 0,is_dirty:"boolean"==typeof d?.isDirty?d.isDirty:!i,is_stale:i,is_complete:a};return t&&this.fsReadRequests.has(t)?this.handleFsReadDataMessage(t,y):this.invokeReadHandlerNext(r,y),o=!0,y};if(i)try{if(n){let t=null;if(e.iuid&&(t=await i.getByIuid(e.iuid)),!t&&e.name&&(t=await i.getByName(e.name)),t?.object){const r=t.object?.name??e.name??t.iuid;l(t.object,t.data,!0,!1,r,t.iuid),a={iuid:t.iuid,name:r,object:t.object,data:t.data}}}}catch(e){console.warn("cardFS.read cache lookup failed",e)}try{const t=await this.fetchDocumentPayload(s,e);await(i?.cacheDocument(t.object,t.data));const r=t.object?.name??e.name??e.iuid;if(o){const e=a?.object?.data_hash,n=t.object?.data_hash,s=void 0!==e&&void 0!==n&&e===n;l(t.object,t.data,!1,!0,r,t.object?.iuid,{includeData:!s,isDirty:!s})}else l(t.object,t.data,!1,!0,r,t.object?.iuid)}catch(n){const s=n instanceof Error?n:new Error(String(n)),c=this.getCardFsErrorCode(s);if(c===rt.NOT_FOUND&&i)try{const t=a?.iuid??e.iuid,r=a?.name??e.name;t?await i.deleteByIuid(t,r):r&&await i.deleteByName(r)}catch(e){console.warn("cardFS.read cache cleanup failed",e)}if(!o){throw Object.assign(new Error(s.message),{code:c})}if(c===rt.NOT_FOUND||c===rt.NO_PERMISSION){const e={code:c,message:s.message};t&&this.fsReadRequests.has(t)?this.failFsReadRequest(t,e):this.invokeReadHandlerError(r,e)}else console.warn("cardFS.read fresh fetch failed",n)}if(!o)throw new Error(`cardFS.read fallback could not locate ${c}`)}async cardFSWriteFallback(e,t,r,n){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.write fallback is disabled because parent supports card_fs");const s=this.getCardIuid();if(!s)throw new Error("cardFS.write fallback failed: card not initialized");try{const i=this.normalizeWriteData(t,r);await this.upsertDocumentViaApi(s,e,i,r);const a=await this.fetchDocumentPayload(s,e);await(this.ensureCardFsCache()?.cacheDocument(a.object,a.data));const o={name:a.object?.name??e.name??null,iuid:a.object?.iuid??e.iuid??null,object:a.object,data:a.data};return n&&this.fsWriteRequests.has(n)&&this.handleFsWriteSuccess(n,o),o}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,n=r&&Object.values(rt).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:n})}}async cardFSDeleteFallback(e){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.delete fallback is disabled because parent supports card_fs");const t=this.getCardIuid();if(!t)throw new Error("cardFS.delete fallback failed: card not initialized");try{const r=this.ensureCardFsCache(),n=await this.fetchDocumentMetadataByTarget(t,e).catch(()=>null),s=n?.iuid??e.iuid??null,i=n?.name??e.name??null;if(!s)return e.name&&await(r?.deleteByName(e.name)),{name:i,iuid:null,deleted:!1};const a=await fetch(`/api/v1/documents/${s}/`,{method:"DELETE",headers:this.authHeader()});if(!a.ok&&404!==a.status){const e=await a.text().catch(()=>"delete failed");throw new Error(`cardFS.delete fallback failed: ${e}`)}await(r?.deleteByIuid(s,i??void 0));return{name:i??s,iuid:s,deleted:404!==a.status}}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,n=r&&Object.values(rt).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:n})}}async cardFSListFallback(e){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.list fallback is disabled because parent supports card_fs");const t=this.getCardIuid();if(!t)throw new Error("cardFS.list fallback failed: card not initialized");const r=this.ensureCardFsCache(),n=this.formatFolderPath(e),s=n??"/";try{const e=await this.fetchFolderListing(t,n);return r&&(await r.cacheFolderListing(n,{folder_name:e.folder_name??s,folder_iuid:e.folder_iuid,last_index:e.last_index??null,last_page:e.last_page??null,data:e.documents}),await Promise.all(e.documents.map(e=>r.cacheDocument(e,void 0)))),{documents:e.documents,folder_name:e.folder_name??s,folder_iuid:e.folder_iuid,last_index:e.last_index??null,last_page:e.last_page??null,is_dirty:!0,is_complete:!0}}catch(e){const t=await(r?.getFolderListing(n));if(t){return{documents:Array.isArray(t.data?.results)?t.data.results:[],folder_name:t.folder_name??s,folder_iuid:t.folder_iuid??void 0,last_index:t.last_index??null,last_page:t.last_page??null,from_cache:!0,is_dirty:!0,is_complete:!0}}const i=e instanceof Error?e:new Error(String(e)),a=i?.code??i?.error_code,o=a&&Object.values(rt).includes(a)?a:this.getCardFsErrorCode(i);throw Object.assign(new Error(i.message),{code:o})}}authHeader(){return this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}async fetchDocumentMetadataByTarget(e,t){return t.iuid?this.fetchDocumentMetadataByIuid(t.iuid):t.name?this.fetchDocumentMetadataByName(e,t.name):null}async fetchDocumentMetadataByIuid(e){const t=await fetch(`/api/v1/documents/${e}/`,{method:"GET",headers:this.authHeader()});if(404===t.status)return null;if(!t.ok){const e=await t.text().catch(()=>"metadata lookup failed");throw new Error(`cardFS metadata fetch failed: ${e}`)}return t.json().catch(()=>null)}normalizeDocumentsResponse(e){return Array.isArray(e?.results)?e.results:Array.isArray(e)?e:e?[e]:[]}normalizeListResult(e){const t=Array.isArray(e?.documents)?e.documents:[],r=Boolean(e?.from_cache??e?.is_stale),n="boolean"==typeof e?.is_complete?e.is_complete:!r,s="boolean"!=typeof e?.is_dirty||e.is_dirty;return{...e,documents:t,is_stale:r,is_complete:n,is_dirty:s}}getCardFsErrorCode(e){if(!e)return rt.UNKNOWN;const t=e?.status??e?.statusCode;if(0===t)return rt.NO_INTERNET;if(401===t||403===t)return rt.NO_PERMISSION;if(404===t)return rt.NOT_FOUND;if(500===t)return rt.SERVER_ERROR;const r="string"==typeof e?.message?e.message.toLowerCase():"";return r.includes("not found")?rt.NOT_FOUND:r.includes("permission")||r.includes("unauthorized")||r.includes("forbidden")?rt.NO_PERMISSION:r.includes("network")||r.includes("failed to fetch")||r.includes("offline")?rt.NO_INTERNET:rt.UNKNOWN}isBinaryReadPayload(e){if((e?.file_type??e?.object?.file_type??e?.object?.fileType)===tt.BINARY)return!0;const t=e?.object?.mimetype??e?.object?.mime_type??e?.object?.mimeType;if("string"==typeof t){const e=t.toLowerCase();return!e.startsWith("text/")&&!e.includes("json")}return!1}decodeBase64BinaryData(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r.buffer}async fetchDocumentMetadataByName(e,t){if(!t)return null;const r=await fetch(`/api/v1/documents/with_card/${e}/?name=${encodeURIComponent(t)}`,{method:"GET",headers:this.authHeader()});if(!r.ok){if(404===r.status)return null;const e=await r.text().catch(()=>"metadata lookup failed");throw new Error(`cardFS metadata fetch failed: ${e}`)}const n=await r.json().catch(()=>null),s=this.normalizeDocumentsResponse(n);return s.find(e=>e?.name===t)??s[0]??null}async fetchFolderListing(e,t){const r=t?`?name=${encodeURIComponent(t)}`:"",n=await fetch(`/api/v1/documents/with_card/${e}/${r}`,{method:"GET",headers:this.authHeader()});if(!n.ok){const e=await n.text().catch(()=>"list failed");throw new Error(`cardFS.list failed: ${e}`)}const s=await n.json().catch(()=>null);return{documents:this.normalizeDocumentsResponse(s),folder_name:t,folder_iuid:void 0,last_index:s?.last_index??s?.last_page??null,last_page:s?.last_page??null}}async fetchDocumentPayload(e,t){const r="string"==typeof t?{name:t}:t,n=await this.fetchDocumentMetadataByTarget(e,r);if(!n){const e=r.name?`"${r.name}"`:r.iuid?`iuid ${r.iuid}`:"document";throw new Error(`cardFS document not found: ${e}`)}return{object:n,data:await this.fetchDocumentData(n)}}async fetchDocumentData(e){if(void 0!==e?.data)return e.data;const t=e?.orig?.url||e?.url?.original||e?.url;if(!t||"string"!=typeof t)return null;const r=await fetch(t);if(!r.ok){const e=await r.text().catch(()=>"download failed");throw new Error(`cardFS data fetch failed: ${e}`)}const n=r.headers.get("Content-Type")||"";return n.includes("application/json")?r.json():n.startsWith("text/")?r.text():r.arrayBuffer()}async buildFileFormData(e,t,r){let n;if(t instanceof File)n=t;else if("undefined"!=typeof Blob&&t instanceof Blob)n=new File([t],e,{type:t.type||"application/octet-stream"});else{const s=r===tt.TEXT?"text/plain":r===tt.JSON?"application/json":"application/octet-stream";n=new File([t],e,{type:s})}const s=new FormData;return s.append("file",n),s}async upsertDocumentViaApi(e,t,r,n){if(t.iuid){let e=t.name;if(!e){const r=await this.fetchDocumentMetadataByIuid(t.iuid).catch(()=>null);e=r?.name??t.iuid}const s=await this.buildFileFormData(e??t.iuid??"document",r,n),i=await fetch(`/api/v1/documents/${t.iuid}/`,{method:"PUT",headers:this.authHeader(),body:s});if(!i.ok){const e=await i.text().catch(()=>"update failed");throw new Error(`cardFS.write update failed: ${e}`)}return}const s=await this.buildFileFormData(t.name??t.iuid??"document",r,n),i=t.name?await this.fetchDocumentMetadataByName(e,t.name).catch(()=>null):null;if(i?.iuid){const e=await fetch(`/api/v1/documents/${i.iuid}/`,{method:"PUT",headers:this.authHeader(),body:s});if(!e.ok){const t=await e.text().catch(()=>"update failed");throw new Error(`cardFS.write update failed: ${t}`)}return}if(s.append("parent_iuid",e),s.append("attached_to_iuid",e),!t.name)throw new Error('cardFS.write failed: "name" missing');s.append("filename",t.name);const a=await fetch("/api/v1/documents/",{method:"POST",headers:this.authHeader(),body:s});if(!a.ok){const e=await a.text().catch(()=>"upload failed");throw new Error(`cardFS.write upload failed: ${e}`)}}formatErrorMessage(e){if("string"==typeof e&&e.trim())return e;if(e instanceof Error)return e.message||e.toString();if(e&&"object"==typeof e){if("string"==typeof e.message)return e.message;try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return null!=e?String(e):"Unknown error"}sendEventError(e,t,r=void 0){const n={message:this.formatErrorMessage(t),error_code:e,data:r??null};this.handler&&this.safeInvoke("onError",this.handler,n)}setFileDirty(e){this.sendMessage($e.FILE_DIRTY,e)}getUsername(e){const t=e?.name;return t&&Object.values(t).some(e=>e)?Xe(t):""}attachUserFullName(e){return e&&"object"==typeof e?{...e,getFullName(){return Xe(this?.name)}}:e}}return at.FS_RESPONSE_TIMEOUT_MS=3e4,at.FS_READ_RETENTION_MS=15e3,at.CARD_FS_ACK_TIMEOUT_MS=15e3,at.MAX_CONSOLE_ARG_CHARS=2e3,at.MAX_CONSOLE_LOG_ENTRIES=100,at.MAX_CONSOLE_STRING_PREVIEW_CHARS=200,at.DEFAULT_ROLE_PERMISSIONS="r",t})());
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.domeSdk=t():e.domeSdk=t()}(this,()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{CardClientMessageType:()=>We,CardFsErrorCode:()=>et,CardFsFileType:()=>Ze,CardMessageType:()=>qe,CardPermission:()=>Ge,CardSdk:()=>it,CommonClientMessageType:()=>He,CryptoA01:()=>Xe,DomeEmbeddedAppSdk:()=>$e,ViewerClientMessageType:()=>ze,ViewerMessageType:()=>Ke,ViewerSdk:()=>Ye,cardPermission:()=>Qe,getKeyFromBlob:()=>rt});const r="0.4.2";let n,i,s;try{n=new TextDecoder}catch(e){}let a=0;const o=[],c={};let l,d,u,h,f,p,y,g=11281e4,m=1681e4,E=o,_=0,w={},S=0,b=0,A=[],I=[],F={useRecords:!1,mapsAsObjects:!0},C=!1,T=2;try{new Function("")}catch(e){T=1/0}class R{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[L(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(i)return Z(()=>(ee(),this?this.decode(e,t):R.prototype.decode.call(F,e,t)));s=t>-1?t:e.length,a=0,_=0,b=0,d=null,E=o,u=null,i=e;try{p=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(t){if(i=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 R){if(w=this,f=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues),this.structures)return l=this.structures,O();(!l||l.length>0)&&(l=[])}else w=F,(!l||l.length>0)&&(l=[]),f=null;return O()}decodeMultiple(e,t){let r,n=0;try{let i=e.length;C=!0;let s=this?this.decode(e,i):re.decode(e,i);if(!t){for(r=[s];a<i;)n=a,r.push(O());return r}if(!1===t(s))return;for(;a<i;)if(n=a,!1===t(O()))return}catch(e){throw e.lastPosition=n,e.values=r,e}finally{C=!1,ee()}}}function O(){try{let e=N();if(u){if(a>=u.postBundlePosition){let e=new Error("Unexpected bundle position");throw e.incomplete=!0,e}a=u.postBundlePosition,u=null}if(a==s)l=null,i=null,h&&(h=null);else{if(a>s){let e=new Error("Unexpected end of CBOR data");throw e.incomplete=!0,e}if(!C)throw new Error("Data read, but end of buffer not reached")}return e}catch(e){throw ee(),(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer"))&&(e.incomplete=!0),e}}function N(){let e=i[a++],t=e>>5;if(e&=31,e>23)switch(e){case 24:e=i[a++];break;case 25:if(7==t)return function(){let e=i[a++],t=i[a++],r=(127&e)>>2;if(31===r)return t||3&e?NaN:128&e?-1/0:1/0;if(0===r){let r=((3&e)<<8|t)/(1<<24);return 128&e?-r:r}return x[3]=128&e|56+(r>>1),x[2]=(7&e)<<5|t>>3,x[1]=t<<5,x[0]=0,j[0]}();e=p.getUint16(a),a+=2;break;case 26:if(7==t){let e=p.getFloat32(a);if(w.useFloat32>2){let t=te[(127&i[a])<<1|i[a+1]>>7];return a+=4,(t*e+(e>0?.5:-.5)|0)/t}return a+=4,e}e=p.getUint32(a),a+=4;break;case 27:if(7==t){let e=p.getFloat64(a);return a+=8,e}if(t>1){if(p.getUint32(a)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");e=p.getUint32(a+4)}else w.int64AsNumber?(e=4294967296*p.getUint32(a),e+=p.getUint32(a+4)):e=p.getBigUint64(a);a+=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=N())!=c;){if(n>=g)throw new Error(`Array length exceeds ${g}`);r[n++]=e}return 4==t?r:3==t?r.join(""):Buffer.concat(r);case 5:let i;if(w.mapsAsObjects){let e={},t=0;if(w.keyMap)for(;(i=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[L(w.decodeKey(i))]=N()}else for(;(i=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[L(i)]=N()}return e}{y&&(w.mapsAsObjects=!0,y=!1);let e=new Map;if(w.keyMap){let t=0;for(;(i=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(w.decodeKey(i),N())}}else{let t=0;for(;(i=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(i,N())}}return e}case 7:return c;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 r=e,w.copyBuffers?Uint8Array.prototype.slice.call(i,a,a+=r):i.subarray(a,a+=r);case 3:if(b>=a)return d.slice(a-S,(a+=e)-S);if(0==b&&s<140&&e<32){let t=e<16?P(e):B(e);if(null!=t)return t}return D(e);case 4:if(e>=g)throw new Error(`Array length exceeds ${g}`);let t=new Array(e);for(let r=0;r<e;r++)t[r]=N();return t;case 5:if(e>=m)throw new Error(`Map size exceeds ${g}`);if(w.mapsAsObjects){let t={};if(w.keyMap)for(let r=0;r<e;r++)t[L(w.decodeKey(N()))]=N();else for(let r=0;r<e;r++)t[L(N())]=N();return t}{y&&(w.mapsAsObjects=!0,y=!1);let t=new Map;if(w.keyMap)for(let r=0;r<e;r++)t.set(w.decodeKey(N()),N());else for(let r=0;r<e;r++)t.set(N(),N());return t}case 6:if(e>=57337){let t=l[8191&e];if(t)return t.read||(t.read=v(t)),t.read();if(e<65536){if(57343==e){let e=X(),t=N(),r=N();V(t,r);let n={};if(w.keyMap)for(let t=2;t<e;t++){n[L(w.decodeKey(r[t-2]))]=N()}else for(let t=2;t<e;t++){n[L(r[t-2])]=N()}return n}if(57342==e){let e=X(),t=N();for(let r=2;r<e;r++)V(t++,N());return N()}if(57337==e)return function(){let e=X(),t=a+N();for(let t=2;t<e;t++){let e=X();a+=e}let r=a;return a=t,u=[M(X()),M(X())],u.position0=0,u.position1=0,u.postBundlePosition=a,a=r,N()}();if(w.getShared&&(Q(),t=l[8191&e],t))return t.read||(t.read=v(t)),t.read()}}let n=A[e];if(n)return n.handlesRead?n(N):n(N());{let t=N();for(let r=0;r<I.length;r++){let n=I[r](e,t);if(void 0!==n)return n}return new K(t,e)}case 7:switch(e){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:let t=(f||q())[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 r}const k=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function v(e){if(!e)throw new Error("Structure is required in record definition");return e.slowReads=0,function(){let e=i[a++];if(e&=31,e>23)switch(e){case 24:e=i[a++];break;case 25:e=p.getUint16(a),a+=2;break;case 26:e=p.getUint32(a),a+=4;break;default:throw new Error("Expected array header, but got "+i[a-1])}let t=this.compiledReader;for(;t;){if(t.propertyCount===e)return t(N);t=t.next}if(this.slowReads++>=T){let r=this.length==e?this:this.slice(0,e);return t=w.keyMap?new Function("r","return {"+r.map(e=>w.decodeKey(e)).map(e=>k.test(e)?L(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+r.map(e=>k.test(e)?L(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"),this.compiledReader&&(t.next=this.compiledReader),t.propertyCount=e,this.compiledReader=t,t(N)}let r={};if(w.keyMap)for(let t=0;t<e;t++)r[L(w.decodeKey(this[t]))]=N();else for(let t=0;t<e;t++)r[L(this[t])]=N();return r}}function L(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 D=M;function M(e){let t;if(e<16&&(t=P(e)))return t;if(e>64&&n)return n.decode(i.subarray(a,a+=e));const r=a+e,s=[];for(t="";a<r;){const e=i[a++];if(128&e)if(192==(224&e)){const t=63&i[a++];s.push((31&e)<<6|t)}else if(224==(240&e)){const t=63&i[a++],r=63&i[a++];s.push((31&e)<<12|t<<6|r)}else if(240==(248&e)){let t=(7&e)<<18|(63&i[a++])<<12|(63&i[a++])<<6|63&i[a++];t>65535&&(t-=65536,s.push(t>>>10&1023|55296),t=56320|1023&t),s.push(t)}else s.push(e);else s.push(e);s.length>=4096&&(t+=U.apply(String,s),s.length=0)}return s.length>0&&(t+=U.apply(String,s)),t}let U=String.fromCharCode;function B(e){let t=a,r=new Array(e);for(let n=0;n<e;n++){const e=i[a++];if((128&e)>0)return void(a=t);r[n]=e}return U.apply(String,r)}function P(e){if(e<4){if(e<2){if(0===e)return"";{let e=i[a++];return(128&e)>1?void(a-=1):U(e)}}{let t=i[a++],r=i[a++];if((128&t)>0||(128&r)>0)return void(a-=2);if(e<3)return U(t,r);let n=i[a++];return(128&n)>0?void(a-=3):U(t,r,n)}}{let t=i[a++],r=i[a++],n=i[a++],s=i[a++];if((128&t)>0||(128&r)>0||(128&n)>0||(128&s)>0)return void(a-=4);if(e<6){if(4===e)return U(t,r,n,s);{let e=i[a++];return(128&e)>0?void(a-=5):U(t,r,n,s,e)}}if(e<8){let o=i[a++],c=i[a++];if((128&o)>0||(128&c)>0)return void(a-=6);if(e<7)return U(t,r,n,s,o,c);let l=i[a++];return(128&l)>0?void(a-=7):U(t,r,n,s,o,c,l)}{let o=i[a++],c=i[a++],l=i[a++],d=i[a++];if((128&o)>0||(128&c)>0||(128&l)>0||(128&d)>0)return void(a-=8);if(e<10){if(8===e)return U(t,r,n,s,o,c,l,d);{let e=i[a++];return(128&e)>0?void(a-=9):U(t,r,n,s,o,c,l,d,e)}}if(e<12){let u=i[a++],h=i[a++];if((128&u)>0||(128&h)>0)return void(a-=10);if(e<11)return U(t,r,n,s,o,c,l,d,u,h);let f=i[a++];return(128&f)>0?void(a-=11):U(t,r,n,s,o,c,l,d,u,h,f)}{let u=i[a++],h=i[a++],f=i[a++],p=i[a++];if((128&u)>0||(128&h)>0||(128&f)>0||(128&p)>0)return void(a-=12);if(e<14){if(12===e)return U(t,r,n,s,o,c,l,d,u,h,f,p);{let e=i[a++];return(128&e)>0?void(a-=13):U(t,r,n,s,o,c,l,d,u,h,f,p,e)}}{let y=i[a++],g=i[a++];if((128&y)>0||(128&g)>0)return void(a-=14);if(e<15)return U(t,r,n,s,o,c,l,d,u,h,f,p,y,g);let m=i[a++];return(128&m)>0?void(a-=15):U(t,r,n,s,o,c,l,d,u,h,f,p,y,g,m)}}}}}let j=new Float32Array(1),x=new Uint8Array(j.buffer,0,4);new Array(4096);class K{constructor(e,t){this.value=e,this.tag=t}}A[0]=e=>new Date(e),A[1]=e=>new Date(Math.round(1e3*e)),A[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},A[3]=e=>BigInt(-1)-A[2](e),A[4]=e=>+(e[1]+"e"+e[0]),A[5]=e=>e[1]*Math.exp(e[0]*Math.log(2));const V=(e,t)=>{let r=l[e-=57344];r&&r.isShared&&((l.restoreStructures||(l.restoreStructures=[]))[e]=r),l[e]=t,t.read=v(t)};A[105]=e=>{let t=e.length,r=e[1];V(e[0],r);let n={};for(let i=2;i<t;i++){n[L(r[i-2])]=e[i]}return n},A[14]=e=>u?u[0].slice(u.position0,u.position0+=e):new K(e,14),A[15]=e=>u?u[1].slice(u.position1,u.position1+=e):new K(e,15);let H={Error,RegExp};A[27]=e=>(H[e[0]]||Error)(e[1],e[2]);const z=e=>{if(132!=i[a++]){let e=new Error("Packed values structure must be followed by a 4 element array");throw i.length<a&&(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 f=f?t.concat(f.slice(t.length)):t,f.prefixes=e(),f.suffixes=e(),e()};function W(e,t){return"string"==typeof e?e+t:e instanceof Array?e.concat(t):Object.assign({},e,t)}function q(){if(!f){if(!w.getShared)throw new Error("No packed values available");Q()}return f}z.handlesRead=!0,A[51]=z,A[6]=e=>{if(!f){if(!w.getShared)return new K(e,6);Q()}if("number"==typeof e)return f[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},A[28]=e=>{h||(h=new Map,h.id=0);let t,r=h.id++,n=a;t=i[a]>>5==4?[]:{};let s={target:t};h.set(r,s);let o=e();return s.used?(Object.getPrototypeOf(t)!==Object.getPrototypeOf(o)&&(a=n,t=o,h.set(r,{target:t}),o=e()),Object.assign(t,o)):(s.target=o,o)},A[28].handlesRead=!0,A[29]=e=>{let t=h.get(e);return t.used=!0,t.target},A[258]=e=>new Set(e),(A[259]=e=>(w.mapsAsObjects&&(w.mapsAsObjects=!1,y=!0),e())).handlesRead=!0;I.push((e,t)=>e>=225&&e<=255?W(q().prefixes[e-224],t):e>=28704&&e<=32767?W(q().prefixes[e-28672],t):e>=1879052288&&e<=2147483647?W(q().prefixes[e-1879048192],t):e>=216&&e<=223?W(t,q().suffixes[e-216]):e>=27647&&e<=28671?W(t,q().suffixes[e-27639]):e>=1811940352&&e<=1879048191?W(t,q().suffixes[e-1811939328]):1399353956==e?{packedValues:f,structures:l.slice(0),version:t}:55799==e?t:void 0);const G=1==new Uint8Array(new Uint16Array([1]).buffer)[0],$=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,"undefined"==typeof BigUint64Array?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,"undefined"==typeof BigInt64Array?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array],J=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e<$.length;e++)Y($[e],J[e]);function Y(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;A[i?t:t-4]=1==r||i==G?n=>{if(!e)throw new Error("Could not find typed array for code "+t);return w.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 a=new DataView(r.buffer,r.byteOffset,r.byteLength),o=r.length>>s,c=new e(o),l=a[n];for(let e=0;e<o;e++)c[e]=l.call(a,e<<s,i);return c}}}function X(){let e=31&i[a++];if(e>23)switch(e){case 24:e=i[a++];break;case 25:e=p.getUint16(a),a+=2;break;case 26:e=p.getUint32(a),a+=4}return e}function Q(){if(w.getShared){let e=Z(()=>(i=null,w.getShared()))||{},t=e.structures||[];w.sharedVersion=e.version,f=w.sharedValues=e.packedValues,!0===l?w.structures=l=t:l.splice.apply(l,[0,t.length].concat(t))}}function Z(e){let t=s,r=a,n=_,o=S,c=b,f=d,y=E,g=h,m=u,A=new Uint8Array(i.slice(0,s)),I=l,F=w,T=C,R=e();return s=t,a=r,_=n,S=o,b=c,d=f,E=y,h=g,u=m,i=A,C=T,l=I,w=F,p=new DataView(i.buffer,i.byteOffset,i.byteLength),R}function ee(){i=null,h=null,l=null}const te=new Array(147);for(let e=0;e<256;e++)te[e]=+("1e"+Math.floor(45.15-.30103*e));let re=new R({useRecords:!1});const ne=re.decode;re.decodeMultiple;let ie,se,ae;try{ie=new TextEncoder}catch(e){}const oe="object"==typeof globalThis&&globalThis.Buffer,ce=void 0!==oe,le=ce?oe.allocUnsafeSlow:Uint8Array,de=ce?oe:Uint8Array,ue=ce?4294967296:2144337920;let he,fe,pe,ye,ge=0,me=null;const Ee=/[\u0080-\uFFFF]/,_e=Symbol("record-id");function we(e,t){e<24?fe[ge++]=t|e:e<256?(fe[ge++]=24|t,fe[ge++]=e):e<65536?(fe[ge++]=25|t,fe[ge++]=e>>8,fe[ge++]=255&e):(fe[ge++]=26|t,pe.setUint32(ge,e),ge+=4)}class Se{constructor(e,t,r){this.structures=e,this.packedValues=t,this.version=r}}function be(e){e<24?fe[ge++]=128|e:e<256?(fe[ge++]=152,fe[ge++]=e):e<65536?(fe[ge++]=153,fe[ge++]=e>>8,fe[ge++]=255&e):(fe[ge++]=154,pe.setUint32(ge,e),ge+=4)}const Ae="undefined"==typeof Blob?function(){}:Blob;function Ie(e){if(e instanceof Ae)return!0;let t=e[Symbol.toStringTag];return"Blob"===t||"File"===t}function Fe(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++)Fe(e[r],t);else{let n=!t.encoder.useRecords;for(var r in e)e.hasOwnProperty(r)&&(n&&Fe(r,t),Fe(e[r],t))}break;case"function":console.log(e)}}const Ce=1==new Uint8Array(new Uint16Array([1]).buffer)[0];function Te(e,t){return!Ce&&t>1&&(e-=4),{tag:e,encode:function(e,t){let r=e.byteLength,n=e.byteOffset||0,i=e.buffer||e;t(ce?oe.from(i,n,r):new Uint8Array(i,n,r))}}}function Re(e,t){let r=e.byteLength;r<24?fe[ge++]=64+r:r<256?(fe[ge++]=88,fe[ge++]=r):r<65536?(fe[ge++]=89,fe[ge++]=r>>8,fe[ge++]=255&r):(fe[ge++]=90,pe.setUint32(ge,r),ge+=4),ge+r>=fe.length&&t(ge+r),fe.set(e.buffer?e:new Uint8Array(e),ge),ge+=r}function Oe(e,t){pe.setUint32(me.position+e,ge-me.position-e+1);let r=me;me=null,t(r[0]),t(r[1])}ae=[Date,Set,Error,RegExp,K,ArrayBuffer,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,"undefined"==typeof BigUint64Array?function(){}:BigUint64Array,Int8Array,Int16Array,Int32Array,"undefined"==typeof BigInt64Array?function(){}:BigInt64Array,Float32Array,Float64Array,Se],se=[{tag:1,encode(e,t){let r=e.getTime()/1e3;(this.useTimestamp32||0===e.getMilliseconds())&&r>=0&&r<4294967296?(fe[ge++]=26,pe.setUint32(ge,r),ge+=4):(fe[ge++]=251,pe.setFloat64(ge,r),ge+=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){Re(e,r)}},{getTag(e){if(e.constructor===Uint8Array&&(this.tagUint8Array||ce&&!1!==this.tagUint8Array))return 64},encode(e,t,r){Re(e,r)}},Te(68,1),Te(69,2),Te(70,4),Te(71,8),Te(72,1),Te(77,2),Te(78,4),Te(79,8),Te(85,4),Te(86,8),{encode(e,t){let r=e.packedValues||[],n=e.structures||[];if(r.values.length>0){fe[ge++]=216,fe[ge++]=51,be(4);let e=r.values;t(e),be(0),be(0),packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let t=0,r=e.length;t<r;t++)packedObjectMap[e[t]]=t}if(n){pe.setUint32(ge,3655335424),ge+=3;let r=n.slice(0);r.unshift(57344),r.push(new K(e.version,1399353956)),t(r)}else t(new K(e.version,1399353956))}}];let Ne=new class extends R{constructor(e){let t,r,n,i,s;super(e),this.offset=0,e=e||{};let a=de.prototype.utf8Write?function(e,t,r){return fe.utf8Write(e,t,r)}:!(!ie||!ie.encodeInto)&&function(e,t){return ie.encodeInto(e,fe.subarray(t)).written},o=this,c=e.structures||e.saveStructures,l=e.maxSharedStructures;if(null==l&&(l=c?128:0),l>8190)throw new Error("Maximum maxSharedStructure is 8190");let d=e.sequential;d&&(l=0),this.structures||(this.structures=[]),this.saveStructures&&(this.saveShared=this.saveStructures);let u,h,f,p=e.sharedValues;if(p){f=Object.create(null);for(let e=0,t=p.length;e<t;e++)f[p[e]]=e}let y=[],g=0,m=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(a,c){if(fe||(fe=new le(8192),pe=new DataView(fe.buffer,0,8192),ge=0),ye=fe.length-10,ye-ge<2048?(fe=new le(fe.length),pe=new DataView(fe.buffer,0,fe.length),ye=fe.length-10,ge=0):c===Ue&&(ge=ge+7&2147483640),t=ge,o.useSelfDescribedHeader&&(pe.setUint32(ge,3654940416),ge+=3),s=o.structuredClone?new Map:null,o.bundleStrings&&"string"!=typeof a?(me=[],me.size=1/0):me=null,r=o.structures,r){if(r.uninitialized){let e=o.getShared()||{};o.structures=r=e.structures||[],o.sharedVersion=e.version;let t=o.sharedValues=e.packedValues;if(t){f={};for(let e=0,r=t.length;e<r;e++)f[t[e]]=e}}let e=r.length;if(e>l&&!d&&(e=l),!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[_e]&&(i[_e]=t);let s=e[r];n=i[s],n||(n=i[s]=Object.create(null)),i=n}i[_e]=1048576|t}}d||(r.nextId=e)}if(n&&(n=!1),i=r||[],h=f,e.pack){let t=new Map;if(t.values=[],t.encoder=o,t.maxValues=e.maxPrivatePackedValues||(f?16:1/0),t.objectMap=f||!1,t.samplingPackedValues=u,Fe(a,t),t.values.length>0){fe[ge++]=216,fe[ge++]=51,be(4);let e=t.values;E(e),be(0),be(0),h=Object.create(f||null);for(let t=0,r=e.length;t<r;t++)h[e[t]]=t}}he=c&Pe;try{if(he)return;if(E(a),me&&Oe(t,E),o.offset=ge,s&&s.idsToInsert){ge+=2*s.idsToInsert.length,ge>ye&&w(ge),o.offset=ge;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,ge),s.idsToInsert);return s=null,e}return c&Ue?(fe.start=t,fe.end=ge,fe):fe.subarray(t,ge)}finally{if(r)if(m<10&&m++,r.length>l&&(r.length=l),g>1e4)r.transitions=null,m=0,g=0,y.length>0&&(y=[]);else if(y.length>0&&!d){for(let e=0,t=y.length;e<t;e++)y[e][_e]=void 0;y=[]}if(n&&o.saveShared){o.structures.length>l&&(o.structures=o.structures.slice(0,l));let e=fe.subarray(t,ge);return!1===o.updateSharedData()?o.encode(a):e}c&Be&&(ge=t)}},this.findCommonStringsToPack=()=>(u=new Map,f||(f=Object.create(null)),e=>{let t=e&&e.threshold||4,r=this.pack?e.maxPrivatePackedValues||16:0;p||(p=this.sharedValues=[]);for(let[e,i]of u)i.count>t&&(f[e]=r++,p.push(e),n=!0);for(;this.saveShared&&!1===this.updateSharedData(););u=null});const E=r=>{ge>ye&&(fe=w(ge));var n,i=typeof r;if("string"===i){if(h){let t=h[r];if(t>=0)return void(t<16?fe[ge++]=t+224:(fe[ge++]=198,E(1&t?15-t>>1:t-16>>1)));if(u&&!e.pack){let e=u.get(r);e?e.count++:u.set(r,{count:1})}}let i,s=r.length;if(me&&s>=4&&s<1024){if((me.size+=s)>61440){let e,r=(me[0]?3*me[0].length+me[1].length:0)+10;ge+r>ye&&(fe=w(ge+r)),fe[ge++]=217,fe[ge++]=223,fe[ge++]=249,fe[ge++]=me.position?132:130,fe[ge++]=26,e=ge-t,ge+=4,me.position&&Oe(t,E),me=["",""],me.size=0,me.position=e}let e=Ee.test(r);return me[e?0:1]+=r,fe[ge++]=e?206:207,void E(s)}i=s<32?1:s<256?2:s<65536?3:5;let o=3*s;if(ge+o>ye&&(fe=w(ge+o)),s<64||!a){let e,t,a,o=ge+i;for(e=0;e<s;e++)t=r.charCodeAt(e),t<128?fe[o++]=t:t<2048?(fe[o++]=t>>6|192,fe[o++]=63&t|128):55296==(64512&t)&&56320==(64512&(a=r.charCodeAt(e+1)))?(t=65536+((1023&t)<<10)+(1023&a),e++,fe[o++]=t>>18|240,fe[o++]=t>>12&63|128,fe[o++]=t>>6&63|128,fe[o++]=63&t|128):(fe[o++]=t>>12|224,fe[o++]=t>>6&63|128,fe[o++]=63&t|128);n=o-ge-i}else n=a(r,ge+i,o);n<24?fe[ge++]=96|n:n<256?(i<2&&fe.copyWithin(ge+2,ge+1,ge+1+n),fe[ge++]=120,fe[ge++]=n):n<65536?(i<3&&fe.copyWithin(ge+3,ge+2,ge+2+n),fe[ge++]=121,fe[ge++]=n>>8,fe[ge++]=255&n):(i<5&&fe.copyWithin(ge+5,ge+3,ge+3+n),fe[ge++]=122,pe.setUint32(ge,n),ge+=4),ge+=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[ge++]=250,pe.setFloat32(ge,r),e<4||((t=r*te[(127&fe[ge])<<1|fe[ge+1]>>7])|0)===t)return void(ge+=4);ge--}fe[ge++]=251,pe.setFloat64(ge,r),ge+=8}else r>=-24?fe[ge++]=31-r:r>=-256?(fe[ge++]=56,fe[ge++]=~r):r>=-65536?(fe[ge++]=57,pe.setUint16(ge,~r),ge+=2):(fe[ge++]=58,pe.setUint32(ge,~r),ge+=4);else r<24?fe[ge++]=r:r<256?(fe[ge++]=24,fe[ge++]=r):r<65536?(fe[ge++]=25,fe[ge++]=r>>8,fe[ge++]=255&r):(fe[ge++]=26,pe.setUint32(ge,r),ge+=4);else if("object"===i)if(r){if(s){let e=s.get(r);if(e){if(fe[ge++]=216,fe[ge++]=29,fe[ge++]=25,!e.references){let t=s.idsToInsert||(s.idsToInsert=[]);e.references=[],t.push(e)}return e.references.push(ge-t),void(ge+=2)}s.set(r,{offset:ge-t})}let e=r.constructor;if(e===Object)_(r);else if(e===Array){(n=r.length)<24?fe[ge++]=128|n:be(n);for(let e=0;e<n;e++)E(r[e])}else if(e===Map)if((this.mapsAsObjects?!1!==this.useTag259ForMaps:this.useTag259ForMaps)&&(fe[ge++]=217,fe[ge++]=1,fe[ge++]=3),(n=r.size)<24?fe[ge++]=160|n:n<256?(fe[ge++]=184,fe[ge++]=n):n<65536?(fe[ge++]=185,fe[ge++]=n>>8,fe[ge++]=255&n):(fe[ge++]=186,pe.setUint32(ge,n),ge+=4),o.keyMap)for(let[e,t]of r)E(o.encodeKey(e)),E(t);else for(let[e,t]of r)E(e),E(t);else{for(let e=0,t=se.length;e<t;e++){if(r instanceof ae[e]){let t=se[e],n=t.tag;return null==n&&(n=t.getTag&&t.getTag.call(this,r)),n<24?fe[ge++]=192|n:n<256?(fe[ge++]=216,fe[ge++]=n):n<65536?(fe[ge++]=217,fe[ge++]=n>>8,fe[ge++]=255&n):n>-1&&(fe[ge++]=218,pe.setUint32(ge,n),ge+=4),void t.encode.call(this,r,E,w)}}if(r[Symbol.iterator]){if(he){let e=new Error("Iterable should be serialized as iterator");throw e.iteratorNotHandled=!0,e}fe[ge++]=159;for(let e of r)E(e);return void(fe[ge++]=255)}if(r[Symbol.asyncIterator]||Ie(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 E(e)}_(r)}}else fe[ge++]=246;else if("boolean"===i)fe[ge++]=r?245:244;else if("bigint"===i){if(r<BigInt(1)<<BigInt(64)&&r>=0)fe[ge++]=27,pe.setBigUint64(ge,r);else if(r>-(BigInt(1)<<BigInt(64))&&r<0)fe[ge++]=59,pe.setBigUint64(ge,-r-BigInt(1));else{if(!this.largeBigIntToFloat){r>=BigInt(0)?fe[ge++]=194:(fe[ge++]=195,r=BigInt(-1)-r);let e=[];for(;r;)e.push(Number(r&BigInt(255))),r>>=BigInt(8);return void Re(new Uint8Array(e.reverse()),w)}fe[ge++]=251,pe.setFloat64(ge,Number(r))}ge+=8}else{if("undefined"!==i)throw new Error("Unknown type: "+i);fe[ge++]=247}},_=!1===this.useRecords?this.variableMapSize?e=>{let t=Object.keys(e),r=Object.values(e),n=t.length;if(n<24?fe[ge++]=160|n:n<256?(fe[ge++]=184,fe[ge++]=n):n<65536?(fe[ge++]=185,fe[ge++]=n>>8,fe[ge++]=255&n):(fe[ge++]=186,pe.setUint32(ge,n),ge+=4),o.keyMap)for(let e=0;e<n;e++)E(o.encodeKey(t[e])),E(r[e]);else for(let e=0;e<n;e++)E(t[e]),E(r[e])}:e=>{fe[ge++]=185;let r=ge-t;ge+=2;let n=0;if(o.keyMap)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(o.encodeKey(t)),E(e[t]),n++);else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(t),E(e[t]),n++);fe[r+++t]=n>>8,fe[r+t]=255&n}:(e,t)=>{let r,s,a,o=i.transitions||(i.transitions=Object.create(null)),c=0,d=0;if(this.keyMap){a=Object.keys(e).map(e=>this.encodeKey(e)),d=a.length;for(let e=0;e<d;e++){let t=a[e];r=o[t],r||(r=o[t]=Object.create(null),c++),o=r}}else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(r=o[t],r||(1048576&o[_e]&&(s=65535&o[_e]),r=o[t]=Object.create(null),c++),o=r,d++);let u=o[_e];if(void 0!==u)u&=65535,fe[ge++]=217,fe[ge++]=u>>8|224,fe[ge++]=255&u;else{if(a||(a=o.__keys__||(o.__keys__=Object.keys(e))),void 0===s?(u=i.nextId++,u||(u=0,i.nextId=1),u>=256&&(i.nextId=(u=l)+1)):u=s,i[u]=a,!(u<l)){if(o[_e]=u,pe.setUint32(ge,3655335680),ge+=3,c&&(g+=m*c),y.length>=256-l&&(y.shift()[_e]=void 0),y.push(o),be(d+2),E(57344+u),E(a),t)return;for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&E(e[t]);return}fe[ge++]=217,fe[ge++]=u>>8|224,fe[ge++]=255&u,o=i.transitions;for(let e=0;e<d;e++)(void 0===o[_e]||1048576&o[_e])&&(o[_e]=u),o=o[a[e]];o[_e]=1048576|u,n=!0}if(d<24?fe[ge++]=128|d:be(d),!t)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&E(e[t])},w=e=>{let r;if(e>16777216){if(e-t>ue)throw new Error("Encoded buffer would be larger than maximum buffer size");r=Math.min(ue,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 le(r);return pe=new DataView(n.buffer,0,r),fe.copy?fe.copy(n,0,t,e):n.set(fe.slice(t,e)),ge-=t,t=0,ye=n.length-10,fe=n};let S=100,b=1e3;function*A(e,r,n){let i=e.constructor;if(i===Object){let t=!1!==o.useRecords;t?_(e,!0):we(Object.keys(e).length,160);for(let n in e){let i=e[n];t||E(n),i&&"object"==typeof i?r[n]?yield*A(i,r[n]):yield*I(i,r,n):E(i)}}else if(i===Array){let n=e.length;be(n);for(let i=0;i<n;i++){let n=e[i];n&&("object"==typeof n||ge-t>S)?r.element?yield*A(n,r.element):yield*I(n,r,"element"):E(n)}}else if(e[Symbol.iterator]&&!e.buffer){fe[ge++]=159;for(let n of e)n&&("object"==typeof n||ge-t>S)?r.element?yield*A(n,r.element):yield*I(n,r,"element"):E(n);fe[ge++]=255}else Ie(e)?(we(e.size,64),yield fe.subarray(t,ge),yield e,F()):e[Symbol.asyncIterator]?(fe[ge++]=159,yield fe.subarray(t,ge),yield e,F(),fe[ge++]=255):E(e);n&&ge>t?yield fe.subarray(t,ge):ge-t>S&&(yield fe.subarray(t,ge),F())}function*I(e,r,n){let i=ge-t;try{E(e),ge-t>S&&(yield fe.subarray(t,ge),F())}catch(s){if(!s.iteratorNotHandled)throw s;r[n]={},ge=t+i,yield*A.call(this,e,r[n])}}function F(){S=b,o.encode(null,Pe)}function C(e,t,r){return S=t&&t.chunkThreshold?b=t.chunkThreshold:100,e&&"object"==typeof e?(o.encode(null,Pe),r(e,o.iterateProperties||(o.iterateProperties={}),!0)):[o.encode(e)]}async function*T(e,t){for(let r of A(e,t,!0)){let e=r.constructor;if(e===de||e===Uint8Array)yield r;else if(Ie(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)F(),e?yield*T(e,t.async||(t.async={})):yield o.encode(e);else yield r}}this.encodeAsIterable=function(e,t){return C(e,t,A)},this.encodeAsAsyncIterable=function(e,t){return C(e,t,T)}}useBuffer(e){fe=e,pe=new DataView(fe.buffer,fe.byteOffset,fe.byteLength),ge=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 Se(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}}({useRecords:!1});const ke=Ne.encode,{NEVER:ve,ALWAYS:Le,DECIMAL_ROUND:De,DECIMAL_FIT:Me}=(Ne.encodeAsIterable,Ne.encodeAsAsyncIterable,{NEVER:0,ALWAYS:1,DECIMAL_ROUND:3,DECIMAL_FIT:4}),Ue=512,Be=1024,Pe=2048;function je(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}const xe=new Set(["dome","intouchapp"]);var Ke,Ve,He,ze,We,qe,Ge;!function(e){e.CONNECTION_SUCCESS="CONNECTION_SUCCESS",e.INIT="INIT",e.REQUEST_SAVE="REQUEST_SAVE",e.REQUEST_CLOSE="REQUEST_CLOSE",e.REQUEST_INITIAL_DATA="REQUEST_INITIAL_DATA",e.SET_DIRTY="SET_DIRTY",e.SEND_CLOSE="SEND_CLOSE",e.SEND_EXCEPTION="SEND_EXCEPTION"}(Ke||(Ke={})),function(e){e.INIT_MESSAGE_CHANNEL="INIT_MESSAGE_CHANNEL"}(Ve||(Ve={})),function(e){e.CONNECT="CONNECT"}(He||(He={})),function(e){e.REQUEST_CLOSE="REQUEST_CLOSE",e.REQUEST_SAVE="REQUEST_SAVE",e.DATA_CHANGE="DATA_CHANGE",e.SAVE_ERROR="SAVE_ERROR",e.SAVE_SUCCESS="SAVE_SUCCESS",e.INIT_ACK="INIT_ACK"}(ze||(ze={})),function(e){e.DATA_CHANGE="DATA_CHANGE",e.CFS_ERROR="CFS_ERROR",e.CFS_WRITE_SUCCESS="CFS_WRITE_SUCCESS",e.CFS_FILE_DATA="CFS_FILE_DATA",e.CFS_WRITE_FILE_ACK="CFS_WRITE_FILE_ACK",e.CFS_READ_FILE_ACK="CFS_READ_FILE_ACK",e.CFS_DELETE_FILE_ACK="CFS_DELETE_FILE_ACK",e.CFS_LIST_FILES_ACK="CFS_LIST_FILES_ACK",e.INIT_ACK="INIT_ACK",e.INIT_ERROR="INIT_ERROR",e.AF1_DATA_TOKEN_ACK="AF1_DATA_TOKEN_ACK",e.ERROR="ERROR",e.REFRESH="REFRESH",e.LOGGING_ENABLE="LOGGING_ENABLE",e.LOGGING_DISABLE="LOGGING_DISABLE",e.LOGGING_CLEAR="LOGGING_CLEAR",e.LOGGING_GET="LOGGING_GET"}(We||(We={})),function(e){e.APP_READY="APP_READY",e.INIT="INIT",e.CFS_READ_FILE="CFS_READ_FILE",e.CFS_WRITE_FILE="CFS_WRITE_FILE",e.CFS_DELETE_FILE="CFS_DELETE_FILE",e.CFS_LIST_FILES="CFS_LIST_FILES",e.FILE_DIRTY="FILE_DIRTY",e.OPEN_DEEPLINK="OPEN_DEEPLINK",e.AF1_DATA_TOKEN="AF1_DATA_TOKEN",e.LOGGING_GET_RET="LOGGING_GET_RET"}(qe||(qe={}));class $e{constructor(){this.targetOrigin="*",this.isAppReady=!1,this.port2=null,this.runtimeHost="unknown",this.parentHostDetails=null,this.parentCapabilities=null,this.handleDeepLinkClick=e=>{if("webapp"!==this.runtimeHost)return;if(!(e.target instanceof Element))return;const t=e.target.closest("a[href]");if(!t)return;const r=t.getAttribute("href")??"";this.emitDeepLink(r)&&e.preventDefault()},console.info(`Initializing Dome Embedded App SDK v${r}`),this.detectHost(),this.setupDeepLinkInterception()}detectHost(){void 0!==window.AndroidBridge?this.runtimeHost="android":void 0!==window.webkit?this.runtimeHost="ios":this.runtimeHost="webapp",this.runtimeHost}setupDeepLinkInterception(){"webapp"===this.runtimeHost&&"undefined"!=typeof document&&document.addEventListener("click",this.handleDeepLinkClick,!0)}emitDeepLink(e){if("string"!=typeof e||""===e.trim())return console.warn("emitDeepLink called without a valid href"),!1;const t=e.split(":")[0]?.toLowerCase();return!(!t||!xe.has(t))&&(this.sendMessage(qe.OPEN_DEEPLINK,{url:e}),!0)}updateParentContext(e,t){if(!e&&!t)return;const r={...this.parentHostDetails??{type:this.runtimeHost},...e??{}};r.type||(r.type=this.runtimeHost);const n=t??this.parentCapabilities??r.capabilities;t&&(this.parentCapabilities=t),n?r.capabilities=n:delete r.capabilities,this.parentHostDetails=r,this.parentCapabilities=n??null,n?console.info("Host capabilities detected",{host_type:r.type,capabilities:n}):console.info("Host capabilities not found",{hostType:r.type})}getHost(){return this.parentHostDetails??{type:this.runtimeHost}}sendMessage(e,t,r){const n=this.buildVersionedMessage(e,t??null);if("android"!==this.runtimeHost)if(this.port2)this.port2.postMessage(n);else{switch(this.runtimeHost){case"ios":window?.webkit?.messageHandlers?window.webkit?.messageHandlers.appHandler.postMessage(JSON.stringify(n)):console.error("webkit.messageHandlers not found");break;case"webapp":console.error("Web connection is not established.");break;default:console.error("Unsupported host, cannot send message.")}this.runtimeHost}else{if(r){const e=this.toUint8Array(r),t=n.data&&"object"==typeof n.data?{...n.data,v:"1.0",data:e}:{v:"1.0",data:e},i=this.encodeCborMessage({...n,v:"1.0",data:t});this.port2?this.port2.postMessage(i):window.AndroidBridge?.sendMessage(i)}else{const e=JSON.stringify(n);this.port2?this.port2.postMessage(e):window.AndroidBridge?.sendMessage(e)}this.runtimeHost}}sendAppInit(){this.isAppReady||(this.isAppReady=!0,this.sendMessage(Ke.INIT,{sdk:{ver:r}}))}safeInvoke(e,t,r){const n=t?.[e];"function"==typeof n?n(r):console.warn(`Handler for '${String(e)}' is not defined.`)}setupParentConnection(){return new Promise((e,t)=>{switch(this.runtimeHost){case"android":window.receiveFromAndroid=e=>{let t=e;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=this.decodeCborBuffer(t);if(!e)return;t=e}const{type:r,data:n}=t||{};r&&this.handleMessage(r,n)};let n,i=!1;const s=()=>{i||(i=!0,n&&(clearTimeout(n),n=void 0),"android"===this.runtimeHost&&this.sendMessage(Ke.CONNECTION_SUCCESS),e())};this.setupMessageChannelListener(s),window.AndroidBridge?.sendMessage(JSON.stringify(this.buildVersionedMessage(Ve.INIT_MESSAGE_CHANNEL,{sdk:{ver:r}}))),n=setTimeout(()=>{if(!i){i=!0,console.error("Android message channel CONNECT not received within timeout. Rendering critical error UI.");try{!function(e){if("undefined"==typeof document)return;const{title:t,errorCode:r,lang:n="en"}=e,i=je(t),s=je(r),a=je("Chat with us"),o=`\n<!DOCTYPE html>\n<html lang="${je(n)}">\n <head>\n <meta charset="UTF-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n <title>${i}</title>\n <style>\n :root {\n color-scheme: light dark;\n --itui-bg: #ffffff;\n --itui-overlay-bg: #ffffff;\n --itui-text-primary: #212121;\n --itui-text-secondary: #757575;\n --itui-border-color: #dee2e6;\n --itui-brand-color: #de0f17;\n --itui-info-color: #2196f3;\n }\n\n @media (prefers-color-scheme: dark) {\n :root {\n --itui-bg: #121212;\n --itui-overlay-bg: #212121;\n --itui-text-primary: #abb5bd;\n --itui-text-secondary: #80868c;\n --itui-border-color: #495057;\n --itui-brand-color: #ce4247;\n --itui-info-color: #5197cf;\n }\n }\n\n html,\n body.dome-sdk-critical-error {\n height: 100%;\n min-height: 100%;\n }\n\n body.dome-sdk-critical-error {\n margin: 0;\n box-sizing: border-box;\n display: grid;\n place-items: center;\n padding: 24px;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,\n 'Helvetica Neue', Arial, sans-serif;\n background: var(--itui-bg);\n color: var(--itui-text-primary);\n }\n\n .dome-sdk-critical-error__card {\n width: 80%;\n background: var(--itui-overlay-bg);\n border: 1px solid var(--itui-border-color);\n border-radius: 14px;\n padding: 24px;\n text-align: center;\n }\n\n .dome-sdk-critical-error__title {\n margin: 0 0 12px 0;\n line-height: 1.2;\n color: var(--itui-brand-color);\n }\n\n .dome-sdk-critical-error__text {\n line-height: 1.5;\n }\n\n .dome-sdk-critical-error__link {\n color: var(--itui-info-color);\n text-decoration: none;\n }\n\n .dome-sdk-critical-error__link:hover {\n text-decoration: underline;\n }\n\n .dome-sdk-critical-error__meta {\n font-size: 12px;\n color: var(--itui-text-secondary);\n }\n\t </style>\n </head>\n <body class="dome-sdk-critical-error">\n <main class="dome-sdk-critical-error__card" role="alert" aria-live="assertive">\n <h3 class="dome-sdk-critical-error__title">${i}</h3>\n <p class="dome-sdk-critical-error__meta">${s}</p>\n <p class="dome-sdk-critical-error__text">\n Please contact support for further assistance.\n <a class="dome-sdk-critical-error__link" href="https://dome.so/user/dome/#/ui/fax2xpwj65000wjpausr" target="_blank" rel="noopener noreferrer">${a}</a>\n </p>\n </main>\n </body>\n</html>\n `;document.open(),document.write(o),document.close()}({title:"Initialization Error",errorCode:"MESSAGE_CHANNEL_CONNECT_TIMEOUT"})}catch(e){console.error("Failed to render critical error UI.",e)}t(new Error("Android message channel initialization timed out."))}},5e3);break;case"ios":window.receiveFromIOS=e=>{this.handleMessage(e.type,e.data)},e();break;case"webapp":if(this.port2)return console.warn("Connection already established. Skipping reinitialization."),void e();let a,o=!1;const c=()=>{o||(o=!0,a&&(clearTimeout(a),a=void 0),this.notifyConnectionSuccess(),e())};this.setupMessageChannelListener(c),window.parent?window.parent.postMessage({type:Ve.INIT_MESSAGE_CHANNEL,data:{sdk:{ver:r}}},this.targetOrigin):console.error("Parent window not available to initialize message channel."),a=setTimeout(()=>{o||(o=!0,console.error("Web message channel CONNECT not received within timeout."),t(new Error("Web message channel initialization timed out.")))},5e3);break;default:console.error("Unknown host."),t("Unknown host")}})}setupMessageChannelListener(e){if("undefined"==typeof window)return;const t=r=>{let n=r.data;if("string"==typeof n)try{n=JSON.parse(n)}catch{}(n?.type??n)===He.CONNECT&&(r.ports&&0!==r.ports.length?(this.port2=r.ports[0],this.port2.onmessage=e=>this.handlePortMessage(e),window.removeEventListener("message",t),e?.()):console.warn("Message channel CONNECT missing ports"))};window.addEventListener("message",t)}notifyConnectionSuccess(){this.sendMessage(Ke.CONNECTION_SUCCESS)}handlePortMessage(e){let t=e.data;if(t instanceof ArrayBuffer||ArrayBuffer.isView(t)){const e=this.decodeCborBuffer(t);if(!e)return;t=e}else if("string"==typeof t)try{t=JSON.parse(t)}catch{return}const{type:r,data:n}=t||{};r&&this.handleMessage(r,n)}handleMessage(e,t){throw new Error("Subclasses must implement handleMessage.")}decodeCborBuffer(e){let t;try{t=ne(this.toUint8Array(e))}catch{return null}if(t&&"object"==typeof t&&"data"in t){const e=t.data;if(e&&"object"==typeof e&&"data"in e){const r=e,n=r.data;if("string"==typeof r.object)try{r.object=JSON.parse(r.object)}catch{}const i=this.normalizeBinaryPayload(n);if(i)t.data={...r,data:i};else if("string"==typeof n)try{t.data={...r,data:JSON.parse(n)}}catch{t.data=r}}else{const r=this.normalizeBinaryPayload(e);r&&(t.data=r)}}return t}encodeCborMessage(e){const t=ke(e);return t.buffer instanceof ArrayBuffer&&0===t.byteOffset&&t.byteLength===t.buffer.byteLength?t.buffer:Uint8Array.prototype.slice.call(t).buffer}toUint8Array(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}normalizeBinaryPayload(e){if(e instanceof ArrayBuffer)return e;if(e instanceof Uint8Array)return this.copyBufferView(e.buffer,e.byteOffset,e.byteLength);if(ArrayBuffer.isView(e)){const t=e;return this.copyBufferView(t.buffer,t.byteOffset,t.byteLength)}return null}buildVersionedMessage(e,t){return t&&"object"==typeof t&&!Array.isArray(t)?{type:e,v:"1.0",data:{...t,v:"1.0"}}:{type:e,v:"1.0",data:{v:"1.0",data:t}}}copyBufferView(e,t,r){return e instanceof ArrayBuffer&&0===t&&r===e.byteLength?e:new Uint8Array(e,t,r).slice().buffer}}function Je(e){const{prefix:t="",given:r="",middle:n="",family:i="",suffix:s=""}=e||{};return[t,r,n,i,s].filter(e=>e).join(" ").trim()}class Ye extends $e{constructor(){super(),this.handler=null,this.pendingRequests=new Map,this.pendingInitAck=null}static init(e){return Ye.initialized?(console.warn("ViewerSdk is already initialized. Skipping initialization."),Ye.instance):(Ye.instance||(Ye.instance=new Ye,Ye.instance.setupParentConnection().then(()=>{try{Ye.instance.initializeViewerSdk()}catch(e){console.error("Error in initializeViewerSdk:",e)}}).catch(e=>{console.error("init: Error setting up parent connection!",e),console.trace("called from:")})),e&&Ye.instance.setHandler(e),Ye.initialized=!0,Ye.instance)}setHandler(e){this.handler=e,this.pendingInitAck&&(this.safeInvoke("onInitialData",this.handler,this.pendingInitAck),this.pendingInitAck=null)}canRead(e){return!!e?.includes("r")}canWrite(e){return!!e?.includes("w")||!!e?.includes("*")}initializeViewerSdk(){this.sendAppInit()}requestInitialData(){this.sendMessage(Ke.REQUEST_INITIAL_DATA)}requestSave(e,t){const r=function(){if("undefined"!=typeof window&&window.crypto&&window.crypto.randomUUID)return window.crypto.randomUUID();if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();throw new Error("UUID generation is not supported in this environment")}();return this.sendMessage(Ke.REQUEST_SAVE,{doc:e,isDataDirty:t,requestId:r}),new Promise((e,t)=>{this.pendingRequests.set(r,e),this.pendingRequests.set(r+"_reject",t),setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),this.pendingRequests.delete(r+"_reject"))},3e4)})}handleOnSave(e){const{requestId:t,status:r,message:n}=e,i=this.pendingRequests.get(t),s=this.pendingRequests.get(t+"_reject");i&&("error"===r?s?.({status:r,message:n}):i({status:r,message:n}),this.pendingRequests.delete(t),this.pendingRequests.delete(t+"_reject"))}setDirty(e){this.sendMessage(Ke.SET_DIRTY,e)}sendClose(e,t){this.sendMessage(Ke.SEND_CLOSE,{doc:e,isDataDirty:t})}sendException(e){this.sendMessage(Ke.SEND_EXCEPTION,e)}handleMessage(e,t){if(e===ze.INIT_ACK&&this.updateParentContext(t?.host,t?.capabilities),this.handler)switch(e){case ze.INIT_ACK:this.safeInvoke("onInitialData",this.handler,t);break;case ze.DATA_CHANGE:this.safeInvoke("onDataChange",this.handler,t);break;case ze.REQUEST_CLOSE:this.safeInvoke("onCloseRequest",this.handler);break;case ze.REQUEST_SAVE:this.safeInvoke("onSaveRequest",this.handler);break;case ze.SAVE_SUCCESS:case ze.SAVE_ERROR:this.handleOnSave(t);break;default:console.warn(`No handler found for message type: ${e}`)}else e===ze.INIT_ACK?(console.warn("Handler not set. Storing INIT_ACK message for later processing."),this.pendingInitAck=t):console.error("Message handler not found for type:",e)}}Ye.initialized=!1;class Xe{constructor(){if(this.subtleCrypto=window.crypto?.subtle,!this.subtleCrypto)throw new Error("SubtleCrypto API is not available in this environment.")}async decrypt(e,t,r){try{if(!e)throw new Error("Invalid token");const n=this.base64UrlDecode(e);if(128!==n[0])throw new Error("Invalid version");n.slice(1,9);const i=n.slice(9,25),s=n.slice(25,-32),a=n.slice(-32),o=await this.deriveKey(t,r),{hmacKey:c,aesKey:l}=await this.splitKey(o),d=n.slice(0,-32);if(!new Uint8Array(await this.subtleCrypto.sign("HMAC",c,d)).every((e,t)=>e===a[t]))throw new Error("Invalid HMAC. Token has been tampered with!");const u=await this.subtleCrypto.decrypt({name:"AES-CBC",iv:i},l,s);return(new TextDecoder).decode(u)}catch(e){throw console.log("Error in decrypt:",e),e}}async deriveKey(e,t,r=1e4){const n=new TextEncoder,i=await this.subtleCrypto.importKey("raw",n.encode(e),"PBKDF2",!1,["deriveKey"]);return this.subtleCrypto.deriveKey({name:"PBKDF2",hash:"SHA-256",salt:n.encode(t),iterations:r},i,{name:"AES-CBC",length:256},!0,["encrypt","decrypt"])}async splitKey(e){const t=new Uint8Array(await this.subtleCrypto.exportKey("raw",e));return{hmacKey:await this.subtleCrypto.importKey("raw",t.slice(0,16),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"]),aesKey:await this.subtleCrypto.importKey("raw",t.slice(16),{name:"AES-CBC"},!1,["encrypt","decrypt"])}}base64UrlDecode(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t);return new Uint8Array([...r].map(e=>e.charCodeAt(0)))}}!function(e){e.READ="r",e.WRITE="w",e.FORWARD="f",e.SHARE="s",e.DOWNLOAD="d"}(Ge||(Ge={}));const Qe=Ge;var Ze,et;!function(e){e.TEXT="text",e.JSON="json",e.BINARY="binary"}(Ze||(Ze={})),function(e){e.NO_INTERNET="NO_INTERNET",e.NO_PERMISSION="NO_PERMISSION",e.NOT_FOUND="NOT_FOUND",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.INVALID_REQUEST="INVALID_REQUEST",e.UNKNOWN="UNKNOWN"}(et||(et={}));const tt="1.1.0";function rt(e){let t;if(1!==e.v)throw new Error(`Unsupported key blob version: ${e.v}`);return t=function(e){const{seed:t,obf:r}=e,n=new Uint8Array(r.length);for(let e=0;e<r.length;e++)n[e]=r[e]^t+17*e&255;return n}(e),function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}(t)}class nt{constructor(e,t){this.cardIuid=e,this.containerIuid=t,this.openPromise=null}isSupported(){return"undefined"!=typeof indexedDB}async openDb(){return this.isSupported()?(this.openPromise||(this.openPromise=new Promise(e=>{this.openWithVersion(nt.DB_VERSION,e)})),this.openPromise):null}openWithVersion(e,t){let r="ensure";const n=indexedDB.open(this.cardIuid,e);n.onupgradeneeded=e=>{r=0===(e.oldVersion||0)?"create":"ensure",this.configureStores(n.result)},n.onsuccess=()=>{const e=n.result;if(!this.hasRequiredStores(e)){const r=e.version+1;return e.close(),void this.openWithVersion(r,t)}this.updateStoresMetadata(e,"ensure"===r).catch(()=>{}).finally(()=>t(e))},n.onerror=()=>t(null)}configureStores(e){e.objectStoreNames.contains(nt.DATA_STORE)||e.createObjectStore(nt.DATA_STORE),e.objectStoreNames.contains(nt.NAME_LOOKUP_STORE)||e.createObjectStore(nt.NAME_LOOKUP_STORE),e.objectStoreNames.contains(nt.INFO_STORE)||e.createObjectStore(nt.INFO_STORE),e.objectStoreNames.contains(nt.FOLDER_CACHE_STORE)||e.createObjectStore(nt.FOLDER_CACHE_STORE)}hasRequiredStores(e){const t=e.objectStoreNames;return t.contains(nt.DATA_STORE)&&t.contains(nt.NAME_LOOKUP_STORE)&&t.contains(nt.INFO_STORE)&&t.contains(nt.FOLDER_CACHE_STORE)}static nowMicros(){return Math.trunc(1e3*Date.now())}updateStoresMetadata(e,t){return Promise.all([this.ensureStoreVersion(e,nt.DATA_STORE),this.ensureStoreVersion(e,nt.NAME_LOOKUP_STORE),this.ensureStoreVersion(e,nt.FOLDER_CACHE_STORE),this.updateCardInfo(e,t)]).then(()=>{})}ensureStoreVersion(e,t){return e.objectStoreNames.contains(t)?new Promise(r=>{try{const n=e.transaction(t,"readwrite"),i=n.objectStore(t),s=()=>r();n.oncomplete=s,n.onerror=s,n.onabort=s,i.put(tt,nt.STORE_VERSION_KEY)}catch{r()}}):Promise.resolve()}async updateCardInfo(e,t){if(!e.objectStoreNames.contains(nt.INFO_STORE))return;const r=await this.readInfoValue(e,"container_iuid"),n=t?await this.readInfoValue(e,"ts_c"):void 0,i=this.containerIuid??r??null,s=t&&n?n:nt.nowMicros();await Promise.all([this.writeInfoValue(e,"container_iuid",i),this.writeInfoValue(e,"ts_c",s)]).catch(()=>{})}readInfoValue(e,t){return new Promise(r=>{try{const n=e.transaction(nt.INFO_STORE,"readonly"),i=n.objectStore(nt.INFO_STORE).get(t);i.onsuccess=()=>r(i.result),i.onerror=()=>r(void 0)}catch{r(void 0)}})}writeInfoValue(e,t,r){return new Promise(n=>{try{const i=e.transaction(nt.INFO_STORE,"readwrite"),s=i.objectStore(nt.INFO_STORE),a=()=>n();i.oncomplete=a,i.onerror=a,i.onabort=a,s.put(r,t)}catch{n()}})}keyFor(e){return e}static normalizeFolderName(e){if("string"!=typeof e)return nt.DEFAULT_FOLDER_KEY;let t=e.trim();return t?(t=t.replace(/^\/+/,""),t?(t.endsWith("/")||(t+="/"),t||nt.DEFAULT_FOLDER_KEY):nt.DEFAULT_FOLDER_KEY):nt.DEFAULT_FOLDER_KEY}folderListingKey(e){return nt.normalizeFolderName(e)}static normalizeName(e){if("string"!=typeof e)return null;const t=e.trim();return t||null}async put(e,t){const r=await this.openDb();r&&await new Promise(n=>{const i=r.transaction(nt.DATA_STORE,"readwrite");i.objectStore(nt.DATA_STORE).put(t,e).onsuccess=()=>n(),i.oncomplete=()=>n(),i.onerror=()=>n(),i.onabort=()=>n()})}async get(e){const t=await this.openDb();if(t)return new Promise(r=>{const n=t.transaction(nt.DATA_STORE,"readonly").objectStore(nt.DATA_STORE).get(e);n.onsuccess=()=>r(n.result),n.onerror=()=>r(void 0)})}async delete(e){const t=await this.openDb();t&&await new Promise(r=>{const n=t.transaction(nt.DATA_STORE,"readwrite");n.objectStore(nt.DATA_STORE).delete(e).onsuccess=()=>r(),n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}static async hashName(e){const t="undefined"!=typeof globalThis?globalThis.crypto:void 0;if(!t?.subtle?.digest)throw new Error("CardFS name hashing requires SubtleCrypto support");const r=nt.encodeText(e),n=await t.subtle.digest("SHA-256",r);return nt.bufferToBase64(n)}static encodeText(e){if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e).buffer;const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t.buffer}static bufferToBase64(e){let t="";const r=new Uint8Array(e);for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return btoa(t)}async getIuidForName(e){const t=nt.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const n=await nt.hashName(t);return new Promise(e=>{const t=r.transaction(nt.NAME_LOOKUP_STORE,"readonly").objectStore(nt.NAME_LOOKUP_STORE).get(n);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)})}async upsertNameLookup(e,t){const r=nt.normalizeName(e);if(!r)return;const n=await this.openDb();if(!n)return;const i=await nt.hashName(r);await new Promise(e=>{const r=n.transaction(nt.NAME_LOOKUP_STORE,"readwrite"),s=r.objectStore(nt.NAME_LOOKUP_STORE);s.put(t,i);s.openCursor().onsuccess=e=>{const r=e.target.result;r&&(r.key!==i&&r.value===t&&r.delete(),r.continue())},r.oncomplete=()=>e(),r.onerror=()=>e(),r.onabort=()=>e()})}async deleteNameLookupByName(e){const t=nt.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const n=await nt.hashName(t);await new Promise(e=>{const t=r.transaction(nt.NAME_LOOKUP_STORE,"readwrite");t.objectStore(nt.NAME_LOOKUP_STORE).delete(n),t.oncomplete=()=>e(),t.onerror=()=>e(),t.onabort=()=>e()})}async deleteNameLookupByIuid(e){if(!e)return;const t=await this.openDb();t&&await new Promise(r=>{const n=t.transaction(nt.NAME_LOOKUP_STORE,"readwrite");n.objectStore(nt.NAME_LOOKUP_STORE).openCursor().onsuccess=t=>{const r=t.target.result;r&&(r.value===e&&r.delete(),r.continue())},n.oncomplete=()=>r(),n.onerror=()=>r(),n.onabort=()=>r()})}static estimateSize(e){if(null==e)return 0;if("undefined"!=typeof Blob&&e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(ArrayBuffer.isView(e))return e.byteLength;if("string"==typeof e)return new Blob([e]).size;try{return new Blob([JSON.stringify(e)]).size}catch{return 0}}async cacheDocument(e,t){if(!e?.iuid)return;await this.put(this.keyFor(`${e.iuid}_object`),e);const r=nt.normalizeName(e.name);if(r&&await this.upsertNameLookup(r,e.iuid),void 0===t)return void await this.delete(this.keyFor(`${e.iuid}_data`));nt.estimateSize(t)<=nt.MAX_DATA_BYTES?await this.put(this.keyFor(`${e.iuid}_data`),t):await this.delete(this.keyFor(`${e.iuid}_data`))}async getByName(e){const t=nt.normalizeName(e);if(!t)return null;const r=await this.getIuidForName(t);if(!r)return null;const n=await this.get(this.keyFor(`${r}_object`));if(!n)return null;return{iuid:r,object:n,data:await this.get(this.keyFor(`${r}_data`))}}async getByIuid(e){if(!e)return null;const t=await this.get(this.keyFor(`${e}_object`));if(!t)return null;return{iuid:e,object:t,data:await this.get(this.keyFor(`${e}_data`))}}async deleteByName(e){const t=await this.getByName(e);await this.deleteNameLookupByName(e),t&&(await this.delete(this.keyFor(`${t.iuid}_object`)),await this.delete(this.keyFor(`${t.iuid}_data`)))}async deleteByIuid(e,t){t&&await this.deleteNameLookupByName(t),await this.deleteNameLookupByIuid(e),await this.delete(this.keyFor(`${e}_object`)),await this.delete(this.keyFor(`${e}_data`))}async cacheFolderListing(e,t){const r=await this.openDb();if(!r)return;const n=this.folderListingKey(e??t.folder_name),i="object"==typeof t.data&&null!==t.data?t.data:Array.isArray(t.documents)?t.documents:{},s=Array.isArray(i)?{results:[...i]}:{...i},a={folder_name:n,folder_iuid:t.folder_iuid??null,card_iuid:this.cardIuid,time_last_fetch:Date.now(),data:s,last_index:t.last_index??null,last_page:t.last_page??null};await new Promise(e=>{const t=r.transaction(nt.FOLDER_CACHE_STORE,"readwrite");t.objectStore(nt.FOLDER_CACHE_STORE).put(a,n).onsuccess=()=>e(),t.oncomplete=()=>e(),t.onerror=()=>e(),t.onabort=()=>e()})}async getFolderListing(e){const t=await this.openDb();if(!t)return null;const r=this.folderListingKey(e);return new Promise(e=>{const n=t.transaction(nt.FOLDER_CACHE_STORE,"readonly").objectStore(nt.FOLDER_CACHE_STORE).get(r);n.onsuccess=()=>e(n.result),n.onerror=()=>e(null)})}}nt.DB_VERSION=3,nt.DATA_STORE="cardfs",nt.NAME_LOOKUP_STORE="cardfs_name_iuid_lookup",nt.INFO_STORE="info",nt.FOLDER_CACHE_STORE="folder_cache",nt.STORE_VERSION_KEY="ver",nt.DEFAULT_FOLDER_KEY="/",nt.MAX_DATA_BYTES=5242880;class it extends $e{buildCardFsMessagePayload(e,t){return{...e.name?{name:e.name}:{},...e.iuid?{iuid:e.iuid}:{},...t??{}}}formatFolderPath(e){if("string"!=typeof e)return;let t=e.trim();return t&&(t=t.replace(/^\/+/,""),t)?(t.endsWith("/")||(t+="/"),t):void 0}assertValidReadHandler(e){if(!e||"function"!=typeof e.next)throw new Error("cardFS.read requires a handler with a next() function");return e}assertValidListHandler(e){if(!e||"function"!=typeof e.next)throw new Error("cardFS.list requires a handler with a next() function");return e}invokeReadHandlerNext(e,t){try{e.next(t)}catch(e){console.error("cardFS.read handler next() threw",e)}}invokeReadHandlerError(e,t){if(e.error)try{e.error(t)}catch(e){console.error("cardFS.read handler error() threw",e)}}sanitizeReadData(e,t){if(null==e)return{value:e,stripped:!1};try{if(nt.estimateSize(e)>nt.MAX_DATA_BYTES){const e=t?` for ${t}`:"";return console.warn(`cardFS.read payload data exceeded ${nt.MAX_DATA_BYTES} bytes${e}; omitting data`),{value:void 0,stripped:!0}}}catch(e){console.warn("cardFS.read payload size estimation failed",e)}return{value:e,stripped:!1}}normalizeReadData(e,t,r){if(null==e)return e;const n="string"==typeof t?t.toLowerCase():"",i="string"==typeof r?r.toLowerCase():"",s=n.includes("application/json")||n.endsWith("+json")||i===Ze.JSON,a=n.startsWith("text/")||i===Ze.TEXT,o=e instanceof ArrayBuffer||ArrayBuffer.isView(e),c=()=>{const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return(new TextDecoder).decode(t)};if(s){if(e&&"object"==typeof e&&!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))return e;if(o)try{return JSON.parse(c())}catch{return c()}if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}if(a){const t=o?c():e;if("string"==typeof t)try{return JSON.parse(t)}catch{return t}return t}return e}encodeTextPayload(e){if("string"==typeof e)return e;if(null==e)return"";if("object"==typeof e)try{return JSON.stringify(e)}catch{return String(e)}return String(e)}encodeJsonPayload(e){if("string"==typeof e)return e;try{return JSON.stringify(e??{})}catch{return String(e??"")}}normalizeWriteData(e,t){return t===Ze.TEXT?this.encodeTextPayload(e):t===Ze.BINARY?e:this.encodeJsonPayload(e)}base64EncodeBinaryData(e){const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let r="";for(let e=0;e<t.length;e+=1)r+=String.fromCharCode(t[e]);return btoa(r)}getWriteDataSizeBytes(e){return null==e?0:"string"==typeof e?(new TextEncoder).encode(e).length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:"undefined"!=typeof Blob&&e instanceof Blob?e.size:0}getCardIuid(){return this.dataStore?.iuid||null}ensureCardFsCache(){if(!this.shouldUseCardFsFallback())return null;if(!this.cardFsCache){const e=this.getCardIuid();e&&(this.cardFsCache=new nt(e,this.containerIuid))}return this.cardFsCache}supportsParentCardFs(){const e=this.parentCapabilities?.card_fs;return!!e?.ver&&e.ver===tt}shouldUseCardFsFallback(){return!this.supportsParentCardFs()}constructor(){super(),this.handler=null,this.accessToken="",this.devMode=!1,this.permission=null,this.userRole=null,this.fsReadRequests=new Map,this.fsWriteRequests=new Map,this.fsListRequests=new Map,this.cardFsCache=null,this.pendingAcks=new Map,this.consoleCaptureInstalled=!1,this.consoleCaptureEnabled=!1,this.consoleCaptureMinLevel=null,this.consoleLogBuffer=new Array(it.MAX_CONSOLE_LOG_ENTRIES).fill(null),this.consoleLogWriteIndex=0,this.consoleLogSize=0,this.handleMessage=(e,t)=>{if(e===We.INIT_ACK&&this.updateParentContext(t?.host,t?.capabilities),e===We.CFS_ERROR){const e=t?.messageId,r=this.createCardFsError(t,"Unknown cardFS error");if(e&&this.pendingAcks.has(e)){const t=this.pendingAcks.get(e);clearTimeout(t.timeout),this.pendingAcks.delete(e),t.reject(r)}if(e){if(this.fsReadRequests.has(e))return void this.failFsReadRequest(e,r);if(this.fsWriteRequests.has(e))return void this.failFsWriteRequest(e,r);if(this.fsListRequests.has(e))return void this.failFsListRequest(e,r)}return void console.warn("CardSdk: CFS_ERROR received but no matching fs request",t?.messageId??t?.name)}this.handleFsAckMessage(e,t);const r=t?.messageId;if(e!==We.CFS_LIST_FILES_ACK){if(r&&this.pendingAcks.has(r)){const n=this.pendingAcks.get(r);if(n.ackType===e)return clearTimeout(n.timeout),this.pendingAcks.delete(r),void n.resolve(t)}if(r||!this.resolvePendingAckByType(e,t)){if(!this.handler)throw new Error("Message handler not found!");switch(e){case We.INIT_ACK:this.applyLoggingConfig(t?.logging),this.dataStore.kw1=t.key_wa1,this.dataStore.iuid=t.iuid,"boolean"==typeof t?.dev_mode&&(this.devMode=t.dev_mode,this.dataStore.dev_mode=t.dev_mode),t.iuid?this.shouldUseCardFsFallback()?this.cardFsCache=new nt(t.iuid,this.containerIuid):this.cardFsCache=null:this.shouldUseCardFsFallback()||(this.cardFsCache=null);try{this.cryptoA01.decrypt(this.dataStore.denc,t.key_wa1+this.dataStore.kw2,t.iuid).then(e=>{const r=JSON.parse(e),n=r?.container?.iuid;n&&(this.containerIuid=n,this.shouldUseCardFsFallback()&&this.dataStore?.iuid&&(this.cardFsCache=new nt(this.dataStore.iuid,this.containerIuid)));const i="string"==typeof r?.api_token?r.api_token.trim():"";i?this.accessToken=i:console.warn("CardSdk: INIT_ACK payload missing api_token; fallback APIs may fail without auth"),this.permission=r?.perms_v2??null,this.userRole=r?.role??null;const s=this.attachUserFullName(r?.user);this.handler&&this.safeInvoke("onInit",this.handler,{...r,user:s,ui:t.ui}),delete this.dataStore.denc}).catch(e=>{throw console.error("Final decrypt error",e),e})}catch(e){console.error("Decryption failed!",e),this.sendEventError("dec2_failed",e.message)}break;case We.INIT_ERROR:this.safeInvoke("onInitError",this.handler,t);break;case We.CFS_FILE_DATA:{const e=t?.messageId;if(e&&this.fsReadRequests.has(e)){const{messageId:r,...n}=t||{};return void this.handleFsReadDataMessage(e,n)}console.warn("CardSdk: CFS_FILE_DATA received but no matching fsRead request",t?.messageId??t?.name);break}case We.DATA_CHANGE:this.safeInvoke("onFileChange",this.handler,t);case We.CFS_WRITE_SUCCESS:{const e=t?.messageId;if(e&&this.fsWriteRequests.has(e))return void this.handleFsWriteSuccess(e,t);console.warn("CardSdk: CFS_WRITE_SUCCESS received but no matching fsWrite request",t?.messageId??t?.name);break}case We.ERROR:this.safeInvoke("onError",this.handler,t);break;case We.REFRESH:this.safeInvoke("onRefreshRequest",this.handler,t);break;case We.AF1_DATA_TOKEN_ACK:break;case We.LOGGING_ENABLE:this.applyLoggingConfig({status:"enabled",level:t?.level??t?.logging?.level});break;case We.LOGGING_DISABLE:this.consoleCaptureEnabled=!1;break;case We.LOGGING_CLEAR:this.clearConsoleLogs();break;case We.LOGGING_GET:this.sendConsoleLogs();break;case We.CFS_READ_FILE_ACK:case We.CFS_WRITE_FILE_ACK:case We.CFS_DELETE_FILE_ACK:break;default:console.warn(`No handler found for message type: ${e}`)}}}else r&&this.fsListRequests.has(r)?this.handleFsListDataMessage(r,t):console.warn("CardSdk: CFS_LIST_FILES_ACK received but no matching fsList request",t?.messageId??t?.name)},this.cryptoA01=new Xe,this.cardFS={read:(e,t,r=!0)=>{this.cardFSRead(e,t,r)},readById:(e,t,r=!0)=>{this.cardFSReadById(e,t,r)},write:(e,t,r,n)=>this.cardFSWrite(e,t,r,n),writeById:(e,t,r,n)=>this.cardFSWriteById(e,t,r,n),delete:(e,t)=>this.cardFSDelete(e,t),deleteById:(e,t)=>this.cardFSDeleteById(e,t),list:(e,t)=>this.cardFSList(e,t)}}static async init(e,t,r){try{return it.instance||(it.instance=new it,it.instance.setupParentConnection().then(()=>{it.instance.initializeCardSdk(e)}).catch(e=>{console.error(e)}),t&&it.instance.setHandler(t)),it.instance}catch(e){throw console.error("CardSdk: Unrecoverable error in init",e),e}}setHandler(e){this.handler=e}isCardFsFallbackEnabled(){return this.shouldUseCardFsFallback()}openDeepLink(e){this.emitDeepLink(e)||console.warn("openDeepLink ignored; provide a dome:// or intouchapp:// href")}hasPerm(e){if(!e)return!1;const t=this.userRole?.abbr;if(!t)return!0;if("o"===t)return!0;const r=this.permission?.[t];return"string"==typeof r?!!r.includes("*")||r.includes(e):it.DEFAULT_ROLE_PERMISSIONS.includes(e)}canRead(){return this.hasPerm(Ge.READ)}canWrite(){return this.hasPerm(Ge.WRITE)}deriveSecretSeed(e){const t=e.split("").reverse().join("").substring(4,25);if(!t)throw new Error("Cannot decrypt (1)");return t}getCardIuidEnc(e){try{const t=e.pathname.split("/wa/").filter(Boolean);if(t.length<2)return null;return(t[1]?.split("/")[0]??null)||null}catch(e){return console.warn("CardSdk: Failed to extract seed token",e),null}}async requestAf1DataFromParent(e){const t=await this.sendMessageWithAck(qe.AF1_DATA_TOKEN,{sdk:{ver:r}},We.AF1_DATA_TOKEN_ACK),{messageId:n,...i}=t||{},{cie:s,ck:a,dev_token:o}=i;if(!s||!a||!o)throw new Error("Invalid AF1 data token payload");const c=await this.fetchAf1Data(s,a,o,e),l=c?.data_af1??c?.data?.data_af1;if(!l)throw new Error("AF1 data fetch returned empty payload");return window.IT_DATA_AF1=l,c?.ver&&(window.IT_VERSION=c.ver),c?.env&&(window.IT_ENV=c.env),{dataAf1:l,cie:s}}async fetchAf1Data(e,t,r,n){if(!(e&&t&&r&&n))throw new Error("Invalid AF1 data fetch parameters");const i=new URL(`https://dome.so/api/v1/cards/e/${encodeURIComponent(e)}/data_af1/`);i.searchParams.set("dt",r),i.searchParams.set("rt",n),i.searchParams.set("ck",t);const s=await fetch(i.toString(),{method:"GET"});if(!s.ok){const e=await s.text().catch(()=>s.statusText);throw new Error(`AF1 data fetch failed: ${s.status} ${e}`)}return s.json()}async initializeCardSdk(e){let t="CardSdk::initializeCardSdk:";try{if(!e)throw new Error("Invalid secret");const r=window.location.href,n=new URL(r),i=n.searchParams.get("rt");if(!i)throw new Error("Missing request token");let s=this.getCardIuidEnc(n),a=window.IT_DATA_AF1;if(!a){const{dataAf1:e,cie:t}=await this.requestAf1DataFromParent(i);a=e,s=t||s}if(!a)throw console.error(t,"No data"),new Error("No data");if(!s)throw new Error("Cannot decrypt (missing seed)");const o=this.deriveSecretSeed(s),c=await this.cryptoA01.decrypt(a,e,o);try{const e=JSON.parse(c);if(!e.ite)throw new Error("Invalid data");this.dataStore={denc:e.d,kw2:e.kw2},it.instance.sendInit(e.ite)}catch(e){throw console.error("Initial Decryption failed (2):",e),e}}catch(e){console.error(t,"Init failed:",e),this.sendEventError("init_failed",e.message)}}async sendInit(e){const t={token:e,sdk:{ver:r}},n=this.getWebappDetails();n&&(t.wa=n),this.sendMessage(qe.INIT,t)}getWebappDetails(){if("undefined"==typeof window)return null;let e={};const t=window.IT_VERSION,r=window.IT_ENV;return t&&(e.ver=String(t)),r&&(e.env=String(r)),Object.keys(e).length?e:null}sendMessageWithAck(e,t,r,n=15e3,i,s){const a=crypto.randomUUID();if(i)try{i(a)}catch(e){return Promise.reject(e)}return new Promise((i,o)=>{const c=setTimeout(()=>{this.pendingAcks.delete(a);const e=new Error(`${r} not received in time`);this.isCardFsAckType(r)&&(e.code=et.TIMEOUT),o(e)},n);this.pendingAcks.set(a,{resolve:i,reject:o,timeout:c,ackType:r}),this.sendMessage(e,{...t,messageId:a},s)})}resolvePendingAckByType(e,t){for(const[r,n]of this.pendingAcks.entries())if(n.ackType===e)return clearTimeout(n.timeout),this.pendingAcks.delete(r),n.resolve(t),!0;return!1}cardFSRead(e,t,r=!0){const n={name:e},i=this.assertValidReadHandler(t);this.cardFSReadInternal(n,i,r,"read")}cardFSReadById(e,t,r=!0){const n={iuid:e},i=this.assertValidReadHandler(t);this.cardFSReadInternal(n,i,r,"readById")}cardFSReadInternal(e,t,r,n){if(this.shouldUseCardFsFallback())return void this.cardFSReadFallback(e,void 0,t,r).catch(e=>{const r=e instanceof Error?e:new Error(String(e));this.invokeReadHandlerError(t,this.toCardFsErrorPayload(r))});let i=null;const s=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document";this.sendMessageWithAck(qe.CFS_READ_FILE,this.buildCardFsMessagePayload(e,{allow_stale:r}),We.CFS_READ_FILE_ACK,it.CARD_FS_ACK_TIMEOUT_MS,e=>{i=e;const a={name:s,handler:t,allowStale:r,timeoutMessage:`cardFS.${n} timed out for ${s}`};this.fsReadRequests.set(e,a)}).catch(e=>{const r=e instanceof Error?e:new Error(String(e));i?this.failFsReadRequest(i,r):this.invokeReadHandlerError(t,this.toCardFsErrorPayload(r))})}isCardFsAckType(e){return e===We.CFS_READ_FILE_ACK||e===We.CFS_WRITE_FILE_ACK||e===We.CFS_DELETE_FILE_ACK||e===We.CFS_LIST_FILES_ACK}cardFSWrite(e,t,r=Ze.JSON,n){const i={name:e};return"android"===this.runtimeHost&&r===Ze.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then(e=>this.cardFSWriteInternal(i,e,r,n,"write")):this.cardFSWriteInternal(i,t,r,n,"write")}cardFSWriteById(e,t,r=Ze.JSON,n){const i={iuid:e};return"android"===this.runtimeHost&&r===Ze.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then(e=>this.cardFSWriteInternal(i,e,r,n,"writeById")):this.cardFSWriteInternal(i,t,r,n,"writeById")}cardFSWriteInternal(e,t,r,n,i){return this.shouldUseCardFsFallback()?this.cardFSWriteFallback(e,t,r).catch(e=>{throw this.toCardFsErrorPayload(e)}):new Promise((s,a)=>{let o=null;const c=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document",l=this.normalizeWriteData(t,r),d=this.getWriteDataSizeBytes(l),u="cbor"===this.parentCapabilities?.card_fs?.array_buffer,h=r===Ze.BINARY&&"android"===this.runtimeHost&&u;let f=l;r!==Ze.BINARY||h||(l instanceof ArrayBuffer||ArrayBuffer.isView(l)?f=this.base64EncodeBinaryData(l):console.warn("cardFS.write binary payload is not ArrayBuffer/TypedArray; sending raw data")),e.name,e.iuid,this.sendMessageWithAck(qe.CFS_WRITE_FILE,this.buildCardFsMessagePayload(e,{data:h?null:f,file_type:r,file_size:d}),We.CFS_WRITE_FILE_ACK,it.CARD_FS_ACK_TIMEOUT_MS,e=>{o=e;const t={name:c,onUpdate:n,resolve:s,reject:a,timeoutMessage:`cardFS.${i} timed out for ${c}`};this.fsWriteRequests.set(e,t)},h?l:void 0).catch(e=>{const t=e instanceof Error?e:new Error(String(e));o?this.failFsWriteRequest(o,t):a(this.toCardFsErrorPayload(t))})})}cardFSDelete(e,t){const r={name:e};return this.cardFSDeleteInternal(r,t,"delete")}cardFSDeleteById(e,t){const r={iuid:e};return this.cardFSDeleteInternal(r,t,"deleteById")}cardFSDeleteInternal(e,t,r){return this.shouldUseCardFsFallback()?this.cardFSDeleteFallback(e).then(e=>{try{t?.(e)}catch(e){console.error(`cardFS.${r} fallback callback threw`,e)}return e}).catch(e=>{throw this.toCardFsErrorPayload(e)}):new Promise((r,n)=>{this.sendMessageWithAck(qe.CFS_DELETE_FILE,this.buildCardFsMessagePayload(e),We.CFS_DELETE_FILE_ACK,it.CARD_FS_ACK_TIMEOUT_MS).then(e=>{const{messageId:n,...i}=e||{};t?.(i),r(i)}).catch(e=>{n(this.toCardFsErrorPayload(e))})})}cardFSList(e,t){const r=this.assertValidListHandler(t),n=this.formatFolderPath(e);if(this.shouldUseCardFsFallback())return void this.cardFSListFallbackStream(n,r);const i=n?{name:n}:{},s=crypto.randomUUID(),a={name:n??"folder listing",handler:r,timeoutMessage:"cardFS.list timed out"};this.fsListRequests.set(s,a),this.resetFsListProgressTimeout(s),this.sendMessage(qe.CFS_LIST_FILES,{...i,messageId:s})}async cardFSListFallbackStream(e,t){const r=this.ensureCardFsCache();let n=!1;if(r)try{const i=await r.getFolderListing(e);if(i){const e=Array.isArray(i.data?.results)?i.data.results:[];t.next(this.normalizeListResult({documents:e,folder_name:i.folder_name,folder_iuid:i.folder_iuid??void 0,last_index:i.last_index??null,last_page:i.last_page??null,from_cache:!0,is_dirty:!0,is_complete:!1})),n=!0}}catch(e){console.warn("cardFS.list cache lookup failed",e)}try{const r=await this.cardFSListFallback(e);t.next(this.normalizeListResult({...r,is_complete:!0}))}catch(e){n?console.warn("cardFS.list fresh fetch failed",e):t.error?.(this.toCardFsErrorPayload(e))}}resetFsReadProgressTimeout(e){const t=this.fsReadRequests.get(e);t&&(t.progressTimeout&&clearTimeout(t.progressTimeout),t.progressTimeout=setTimeout(()=>{this.failFsReadRequest(e,{code:et.TIMEOUT,message:t.timeoutMessage})},it.FS_RESPONSE_TIMEOUT_MS))}resetFsWriteProgressTimeout(e){const t=this.fsWriteRequests.get(e);t&&(t.progressTimeout&&clearTimeout(t.progressTimeout),t.progressTimeout=setTimeout(()=>{this.failFsWriteRequest(e,{code:et.TIMEOUT,message:t.timeoutMessage})},it.FS_RESPONSE_TIMEOUT_MS))}resetFsListProgressTimeout(e){const t=this.fsListRequests.get(e);t&&(t.progressTimeout&&clearTimeout(t.progressTimeout),t.progressTimeout=setTimeout(()=>{this.failFsListRequest(e,{code:et.TIMEOUT,message:t.timeoutMessage})},it.FS_RESPONSE_TIMEOUT_MS))}handleFsReadDataMessage(e,t){const r=this.fsReadRequests.get(e);if(!r)return;let n=t?.data;"string"!=typeof n||"base64"!==t?.encoding&&!this.isBinaryReadPayload(t)||(n=this.decodeBase64BinaryData(n));const i=this.sanitizeReadData(n,r.name),s=this.normalizeReadData(i.value,t?.object?.mimetype,t?.file_type),a=Boolean(t?.from_cache??t?.is_stale),o={name:t?.name,iuid:t?.iuid??null,object:t?.object,data:s,is_dirty:"boolean"==typeof t?.is_dirty?t.is_dirty:void 0,is_stale:Boolean(t?.is_stale??t?.from_cache),is_complete:"boolean"==typeof t?.is_complete?t.is_complete:!r.allowStale||!a};this.invokeReadHandlerNext(r.handler,o),o.is_complete&&r.progressTimeout&&(clearTimeout(r.progressTimeout),r.progressTimeout=void 0),r.cleanupTimeout&&clearTimeout(r.cleanupTimeout),r.cleanupTimeout=setTimeout(()=>{this.clearFsReadRequest(e)},it.FS_READ_RETENTION_MS)}handleFsAckMessage(e,t){const r=t?.messageId;if(!r)return!1;if(e===We.CFS_READ_FILE_ACK){const e=this.fsReadRequests.get(r);return!!e&&(this.resetFsReadProgressTimeout(r),e.cleanupTimeout&&clearTimeout(e.cleanupTimeout),e.cleanupTimeout=setTimeout(()=>{this.clearFsReadRequest(r)},it.FS_READ_RETENTION_MS),!0)}if(e===We.CFS_WRITE_FILE_ACK){const e=this.fsWriteRequests.get(r);if(!e)return!1;const{messageId:n,...i}=t||{};if("function"==typeof e.onUpdate)try{e.onUpdate(i)}catch(e){console.error("cardFS.write onUpdate callback threw",e)}return this.resetFsWriteProgressTimeout(r),!0}return!1}clearFsReadRequest(e){const t=this.fsReadRequests.get(e);if(t)return t.progressTimeout&&clearTimeout(t.progressTimeout),t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),this.fsReadRequests.delete(e),t}sendConsoleLogs(){const e={logs:this.getConsoleLogs().map(e=>({l:e.level,ts:e.timestamp,args:e.args})),ver:"1.0.0",sdk:{ver:r}};this.sendMessage(qe.LOGGING_GET_RET,e)}setupConsoleCapture(){if(this.consoleCaptureInstalled||"undefined"==typeof console)return;["log","info","warn","error","debug"].forEach(e=>{const t=console[e];if("function"!=typeof t)return;const r=t.bind(console);console[e]=(...t)=>{try{this.recordConsoleEntry(e,t)}catch{}r(...t)}}),this.consoleCaptureInstalled=!0}applyLoggingConfig(e){if(!e)return;"enabled"===e.status?(this.consoleCaptureEnabled=!0,this.setupConsoleCapture()):"disabled"===e.status&&(this.consoleCaptureEnabled=!1);const t="string"==typeof e.level?e.level.toLowerCase():null;t&&this.isConsoleLogLevel(t)&&(this.consoleCaptureMinLevel=t)}isConsoleLogLevel(e){return"log"===e||"info"===e||"warn"===e||"error"===e||"debug"===e}shouldCaptureLevel(e){if(!this.consoleCaptureEnabled)return!1;if(!this.consoleCaptureMinLevel)return!0;const t=["debug","log","info","warn","error"];return t.indexOf(e)>=t.indexOf(this.consoleCaptureMinLevel)}recordConsoleEntry(e,t){if(!this.shouldCaptureLevel(e))return;const r={level:e,timestamp:(new Date).toISOString(),args:t.map(e=>this.serializeConsoleArg(e))};this.consoleLogBuffer[this.consoleLogWriteIndex]=r,this.consoleLogWriteIndex=(this.consoleLogWriteIndex+1)%it.MAX_CONSOLE_LOG_ENTRIES,this.consoleLogSize=Math.min(this.consoleLogSize+1,it.MAX_CONSOLE_LOG_ENTRIES)}clearConsoleLogs(){this.consoleLogBuffer.fill(null),this.consoleLogWriteIndex=0,this.consoleLogSize=0}getConsoleLogs(){if(0===this.consoleLogSize)return[];if(this.consoleLogSize<it.MAX_CONSOLE_LOG_ENTRIES)return this.consoleLogBuffer.slice(0,this.consoleLogSize).filter(e=>null!==e);const e=[];for(let t=0;t<it.MAX_CONSOLE_LOG_ENTRIES;t+=1){const r=(this.consoleLogWriteIndex+t)%it.MAX_CONSOLE_LOG_ENTRIES,n=this.consoleLogBuffer[r];n&&e.push(n)}return e}serializeConsoleArg(e){if(null===e||"string"==typeof e||"number"==typeof e||"boolean"==typeof e)return this.truncateSerializedArg(e);if(void 0===e)return this.truncateSerializedArg({type:"undefined"});if("bigint"==typeof e)return this.truncateSerializedArg({type:"bigint",value:e.toString()});if("symbol"==typeof e)return this.truncateSerializedArg({type:"symbol",value:e.toString()});if("function"==typeof e)return this.truncateSerializedArg({type:"function",name:e.name||null});if(e instanceof Error)return this.truncateSerializedArg({type:"error",name:e.name,message:e.message,stack:e.stack??null});try{return this.truncateSerializedArg(JSON.parse(JSON.stringify(e)))}catch{try{return this.truncateSerializedArg({type:"object",value:String(e)})}catch{return this.truncateSerializedArg({type:"object",value:"[unserializable]"})}}}truncateSerializedArg(e){try{if("string"==typeof e)return e.length>it.MAX_CONSOLE_ARG_CHARS?{type:"truncated",preview:e.slice(0,it.MAX_CONSOLE_ARG_CHARS),original_length:e.length}:e;const t=JSON.stringify(e);if("string"==typeof t&&t.length>it.MAX_CONSOLE_ARG_CHARS)return{type:"truncated",preview:this.buildTruncatedPreview(e),original_length:t.length}}catch{}return e}buildTruncatedPreview(e){const t=new WeakSet,r=(e,n)=>{if("string"==typeof e)return(e=>e.length<=it.MAX_CONSOLE_STRING_PREVIEW_CHARS?e:{type:"truncated",preview:e.slice(0,it.MAX_CONSOLE_STRING_PREVIEW_CHARS),original_length:e.length})(e);if(!e||"object"!=typeof e)return e;if(t.has(e))return{type:"circular"};if(n>=3)return{type:"truncated",reason:"max_depth"};if(t.add(e),Array.isArray(e)){const t=e.slice(0,5).map(e=>r(e,n+1));return e.length>5&&t.push({type:"truncated",remaining:e.length-5}),t}const i=Object.entries(e),s={};for(const[e,t]of i.slice(0,5))s[e]=r(t,n+1);return i.length>5&&(s.__truncated__={remaining:i.length-5}),s};return r(e,0)}failFsReadRequest(e,t){const r=this.clearFsReadRequest(e);r&&this.invokeReadHandlerError(r.handler,this.toCardFsErrorPayload(t))}clearFsWriteRequest(e){const t=this.fsWriteRequests.get(e);if(t)return t.progressTimeout&&clearTimeout(t.progressTimeout),this.fsWriteRequests.delete(e),t}clearFsListRequest(e){const t=this.fsListRequests.get(e);if(t)return t.progressTimeout&&clearTimeout(t.progressTimeout),this.fsListRequests.delete(e),t}failFsWriteRequest(e,t){const r=this.clearFsWriteRequest(e);r&&r.reject(this.toCardFsErrorPayload(t))}failFsListRequest(e,t){const r=this.clearFsListRequest(e);r&&r.handler.error?.(this.toCardFsErrorPayload(t))}handleFsWriteSuccess(e,t){const r=this.clearFsWriteRequest(e);if(!r)return;const{messageId:n,...i}=t||{};r.resolve(i)}handleFsListDataMessage(e,t){const r=this.fsListRequests.get(e);if(!r)return;this.resetFsListProgressTimeout(e);const{messageId:n,...i}=t||{},s=this.normalizeListResult(i);r.handler.next(s),s.is_complete&&this.clearFsListRequest(e)}createCardFsError(e,t){const r=new Error(e?.message||t),n=e?.error_code;return n&&Object.values(et).includes(n)&&(r.code=n),r}toCardFsErrorPayload(e,t="Unknown cardFS error"){const r="string"==typeof e?.message?e.message:"string"==typeof e?e:t,n=e?.code??e?.error_code;return n&&Object.values(et).includes(n)?{code:n,message:r}:{message:r}}async cardFSReadFallback(e,t,r,n=!0){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.read fallback is disabled because parent supports card_fs");const i=this.getCardIuid();if(!i)throw new Error("cardFS.read fallback failed: card not initialized");const s=this.ensureCardFsCache();let a,o=!1;const c=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document",l=(n,i,s,a,c,l,d)=>{if(!n)return null;const u=c??e.name??n?.name??e.iuid??"document",h=l??n?.iuid??e.iuid??null,f=!1!==d?.includeData,p=f?this.sanitizeReadData(i,u).value:void 0,y={name:u,iuid:h,object:n,data:f?this.normalizeReadData(p,n?.mimetype,n?.file_type??n?.fileType):void 0,is_dirty:"boolean"==typeof d?.isDirty?d.isDirty:!s,is_stale:s,is_complete:a};return t&&this.fsReadRequests.has(t)?this.handleFsReadDataMessage(t,y):this.invokeReadHandlerNext(r,y),o=!0,y};if(s)try{if(n){let t=null;if(e.iuid&&(t=await s.getByIuid(e.iuid)),!t&&e.name&&(t=await s.getByName(e.name)),t?.object){const r=t.object?.name??e.name??t.iuid;l(t.object,t.data,!0,!1,r,t.iuid),a={iuid:t.iuid,name:r,object:t.object,data:t.data}}}}catch(e){console.warn("cardFS.read cache lookup failed",e)}try{const t=await this.fetchDocumentPayload(i,e);await(s?.cacheDocument(t.object,t.data));const r=t.object?.name??e.name??e.iuid;if(o){const e=a?.object?.data_hash,n=t.object?.data_hash,i=void 0!==e&&void 0!==n&&e===n;l(t.object,t.data,!1,!0,r,t.object?.iuid,{includeData:!i,isDirty:!i})}else l(t.object,t.data,!1,!0,r,t.object?.iuid)}catch(n){const i=n instanceof Error?n:new Error(String(n)),c=this.getCardFsErrorCode(i);if(c===et.NOT_FOUND&&s)try{const t=a?.iuid??e.iuid,r=a?.name??e.name;t?await s.deleteByIuid(t,r):r&&await s.deleteByName(r)}catch(e){console.warn("cardFS.read cache cleanup failed",e)}if(!o){throw Object.assign(new Error(i.message),{code:c})}if(c===et.NOT_FOUND||c===et.NO_PERMISSION){const e={code:c,message:i.message};t&&this.fsReadRequests.has(t)?this.failFsReadRequest(t,e):this.invokeReadHandlerError(r,e)}else console.warn("cardFS.read fresh fetch failed",n)}if(!o)throw new Error(`cardFS.read fallback could not locate ${c}`)}async cardFSWriteFallback(e,t,r,n){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.write fallback is disabled because parent supports card_fs");const i=this.getCardIuid();if(!i)throw new Error("cardFS.write fallback failed: card not initialized");try{const s=this.normalizeWriteData(t,r);await this.upsertDocumentViaApi(i,e,s,r);const a=await this.fetchDocumentPayload(i,e);await(this.ensureCardFsCache()?.cacheDocument(a.object,a.data));const o={name:a.object?.name??e.name??null,iuid:a.object?.iuid??e.iuid??null,object:a.object,data:a.data};return n&&this.fsWriteRequests.has(n)&&this.handleFsWriteSuccess(n,o),o}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,n=r&&Object.values(et).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:n})}}async cardFSDeleteFallback(e){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.delete fallback is disabled because parent supports card_fs");const t=this.getCardIuid();if(!t)throw new Error("cardFS.delete fallback failed: card not initialized");try{const r=this.ensureCardFsCache(),n=await this.fetchDocumentMetadataByTarget(t,e).catch(()=>null),i=n?.iuid??e.iuid??null,s=n?.name??e.name??null;if(!i)return e.name&&await(r?.deleteByName(e.name)),{name:s,iuid:null,deleted:!1};const a=await fetch(`/api/v1/documents/${i}/`,{method:"DELETE",headers:this.authHeader()});if(!a.ok&&404!==a.status){const e=await a.text().catch(()=>"delete failed");throw new Error(`cardFS.delete fallback failed: ${e}`)}await(r?.deleteByIuid(i,s??void 0));return{name:s??i,iuid:i,deleted:404!==a.status}}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,n=r&&Object.values(et).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:n})}}async cardFSListFallback(e){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.list fallback is disabled because parent supports card_fs");const t=this.getCardIuid();if(!t)throw new Error("cardFS.list fallback failed: card not initialized");const r=this.ensureCardFsCache(),n=this.formatFolderPath(e),i=n??"/";try{const e=await this.fetchFolderListing(t,n);return r&&(await r.cacheFolderListing(n,{folder_name:e.folder_name??i,folder_iuid:e.folder_iuid,last_index:e.last_index??null,last_page:e.last_page??null,data:e.documents}),await Promise.all(e.documents.map(e=>r.cacheDocument(e,void 0)))),{documents:e.documents,folder_name:e.folder_name??i,folder_iuid:e.folder_iuid,last_index:e.last_index??null,last_page:e.last_page??null,is_dirty:!0,is_complete:!0}}catch(e){const t=await(r?.getFolderListing(n));if(t){return{documents:Array.isArray(t.data?.results)?t.data.results:[],folder_name:t.folder_name??i,folder_iuid:t.folder_iuid??void 0,last_index:t.last_index??null,last_page:t.last_page??null,from_cache:!0,is_dirty:!0,is_complete:!0}}const s=e instanceof Error?e:new Error(String(e)),a=s?.code??s?.error_code,o=a&&Object.values(et).includes(a)?a:this.getCardFsErrorCode(s);throw Object.assign(new Error(s.message),{code:o})}}authHeader(){return this.accessToken?{Authorization:`Bearer ${this.accessToken}`}:{}}async fetchDocumentMetadataByTarget(e,t){return t.iuid?this.fetchDocumentMetadataByIuid(t.iuid):t.name?this.fetchDocumentMetadataByName(e,t.name):null}async fetchDocumentMetadataByIuid(e){const t=await fetch(`/api/v1/documents/${e}/`,{method:"GET",headers:this.authHeader()});if(404===t.status)return null;if(!t.ok){const e=await t.text().catch(()=>"metadata lookup failed");throw new Error(`cardFS metadata fetch failed: ${e}`)}return t.json().catch(()=>null)}normalizeDocumentsResponse(e){return Array.isArray(e?.results)?e.results:Array.isArray(e)?e:e?[e]:[]}normalizeListResult(e){const t=Array.isArray(e?.documents)?e.documents:[],r=Boolean(e?.from_cache??e?.is_stale),n="boolean"==typeof e?.is_complete?e.is_complete:!r,i="boolean"!=typeof e?.is_dirty||e.is_dirty;return{...e,documents:t,is_stale:r,is_complete:n,is_dirty:i}}getCardFsErrorCode(e){if(!e)return et.UNKNOWN;const t=e?.status??e?.statusCode;if(0===t)return et.NO_INTERNET;if(401===t||403===t)return et.NO_PERMISSION;if(404===t)return et.NOT_FOUND;if(500===t)return et.SERVER_ERROR;const r="string"==typeof e?.message?e.message.toLowerCase():"";return r.includes("not found")?et.NOT_FOUND:r.includes("permission")||r.includes("unauthorized")||r.includes("forbidden")?et.NO_PERMISSION:r.includes("network")||r.includes("failed to fetch")||r.includes("offline")?et.NO_INTERNET:et.UNKNOWN}isBinaryReadPayload(e){if((e?.file_type??e?.object?.file_type??e?.object?.fileType)===Ze.BINARY)return!0;const t=e?.object?.mimetype??e?.object?.mime_type??e?.object?.mimeType;if("string"==typeof t){const e=t.toLowerCase();return!e.startsWith("text/")&&!e.includes("json")}return!1}decodeBase64BinaryData(e){const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)r[e]=t.charCodeAt(e);return r.buffer}async fetchDocumentMetadataByName(e,t){if(!t)return null;const r=await fetch(`/api/v1/documents/with_card/${e}/?name=${encodeURIComponent(t)}`,{method:"GET",headers:this.authHeader()});if(!r.ok){if(404===r.status)return null;const e=await r.text().catch(()=>"metadata lookup failed");throw new Error(`cardFS metadata fetch failed: ${e}`)}const n=await r.json().catch(()=>null),i=this.normalizeDocumentsResponse(n);return i.find(e=>e?.name===t)??i[0]??null}async fetchFolderListing(e,t){const r=t?`?name=${encodeURIComponent(t)}`:"",n=await fetch(`/api/v1/documents/with_card/${e}/${r}`,{method:"GET",headers:this.authHeader()});if(!n.ok){const e=await n.text().catch(()=>"list failed");throw new Error(`cardFS.list failed: ${e}`)}const i=await n.json().catch(()=>null);return{documents:this.normalizeDocumentsResponse(i),folder_name:t,folder_iuid:void 0,last_index:i?.last_index??i?.last_page??null,last_page:i?.last_page??null}}async fetchDocumentPayload(e,t){const r="string"==typeof t?{name:t}:t,n=await this.fetchDocumentMetadataByTarget(e,r);if(!n){const e=r.name?`"${r.name}"`:r.iuid?`iuid ${r.iuid}`:"document";throw new Error(`cardFS document not found: ${e}`)}return{object:n,data:await this.fetchDocumentData(n)}}async fetchDocumentData(e){if(void 0!==e?.data)return e.data;const t=e?.orig?.url||e?.url?.original||e?.url;if(!t||"string"!=typeof t)return null;const r=await fetch(t);if(!r.ok){const e=await r.text().catch(()=>"download failed");throw new Error(`cardFS data fetch failed: ${e}`)}const n=r.headers.get("Content-Type")||"";return n.includes("application/json")?r.json():n.startsWith("text/")?r.text():r.arrayBuffer()}async buildFileFormData(e,t,r){let n;if(t instanceof File)n=t;else if("undefined"!=typeof Blob&&t instanceof Blob)n=new File([t],e,{type:t.type||"application/octet-stream"});else{const i=r===Ze.TEXT?"text/plain":r===Ze.JSON?"application/json":"application/octet-stream";n=new File([t],e,{type:i})}const i=new FormData;return i.append("file",n),i}async upsertDocumentViaApi(e,t,r,n){if(t.iuid){let e=t.name;if(!e){const r=await this.fetchDocumentMetadataByIuid(t.iuid).catch(()=>null);e=r?.name??t.iuid}const i=await this.buildFileFormData(e??t.iuid??"document",r,n),s=await fetch(`/api/v1/documents/${t.iuid}/`,{method:"PUT",headers:this.authHeader(),body:i});if(!s.ok){const e=await s.text().catch(()=>"update failed");throw new Error(`cardFS.write update failed: ${e}`)}return}const i=await this.buildFileFormData(t.name??t.iuid??"document",r,n),s=t.name?await this.fetchDocumentMetadataByName(e,t.name).catch(()=>null):null;if(s?.iuid){const e=await fetch(`/api/v1/documents/${s.iuid}/`,{method:"PUT",headers:this.authHeader(),body:i});if(!e.ok){const t=await e.text().catch(()=>"update failed");throw new Error(`cardFS.write update failed: ${t}`)}return}if(i.append("parent_iuid",e),i.append("attached_to_iuid",e),!t.name)throw new Error('cardFS.write failed: "name" missing');i.append("filename",t.name);const a=await fetch("/api/v1/documents/",{method:"POST",headers:this.authHeader(),body:i});if(!a.ok){const e=await a.text().catch(()=>"upload failed");throw new Error(`cardFS.write upload failed: ${e}`)}}formatErrorMessage(e){if("string"==typeof e&&e.trim())return e;if(e instanceof Error)return e.message||e.toString();if(e&&"object"==typeof e){if("string"==typeof e.message)return e.message;try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}return null!=e?String(e):"Unknown error"}sendEventError(e,t,r=void 0){const n={message:this.formatErrorMessage(t),error_code:e,data:r??null};this.handler&&this.safeInvoke("onError",this.handler,n)}setFileDirty(e){this.sendMessage(qe.FILE_DIRTY,e)}getUsername(e){const t=e?.name;return t&&Object.values(t).some(e=>e)?Je(t):""}attachUserFullName(e){return e&&"object"==typeof e?{...e,getFullName(){return Je(this?.name)}}:e}}return it.FS_RESPONSE_TIMEOUT_MS=3e4,it.FS_READ_RETENTION_MS=15e3,it.CARD_FS_ACK_TIMEOUT_MS=15e3,it.MAX_CONSOLE_ARG_CHARS=2e3,it.MAX_CONSOLE_LOG_ENTRIES=100,it.MAX_CONSOLE_STRING_PREVIEW_CHARS=200,it.DEFAULT_ROLE_PERMISSIONS="r",t})());
2
2
  //# sourceMappingURL=index.js.map