dome-embedded-app-sdk 0.3.6-experimental.7 → 0.3.6-experimental.9
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 +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
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 s in r)e.o(r,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:r[s]})},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:()=>Ze,CardFsFileType:()=>Qe,CardMessageType:()=>ze,CardPermission:()=>qe,CardSdk:()=>st,CommonClientMessageType:()=>Ve,CryptoA01:()=>Ye,DomeEmbeddedAppSdk:()=>Ge,ViewerClientMessageType:()=>He,ViewerMessageType:()=>xe,ViewerSdk:()=>Je,cardPermission:()=>Xe,getKeyFromBlob:()=>tt});const r=JSON.parse('{"rE":"0.3.6-experimental.7"}');let s,n,i;try{s=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,S={},w=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,s]of Object.entries(e))t.set(this._keyMap.hasOwnProperty(r)?this._keyMap[r]:r,s);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(n)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,n=e;try{p=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(t){if(n=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(S=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 S=F,(!l||l.length>0)&&(l=[]),f=null;return O()}decodeMultiple(e,t){let r,s=0;try{let n=e.length;C=!0;let i=this?this.decode(e,n):re.decode(e,n);if(!t){for(r=[i];a<n;)s=a,r.push(O());return r}if(!1===t(i))return;for(;a<n;)if(s=a,!1===t(O()))return}catch(e){throw e.lastPosition=s,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,n=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=n[a++],t=e>>5;if(e&=31,e>23)switch(e){case 24:e=n[a++];break;case 25:if(7==t)return function(){let e=n[a++],t=n[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(S.useFloat32>2){let t=te[(127&n[a])<<1|n[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 S.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=[],s=0;for(;(e=N())!=c;){if(s>=g)throw new Error(`Array length exceeds ${g}`);r[s++]=e}return 4==t?r:3==t?r.join(""):Buffer.concat(r);case 5:let n;if(S.mapsAsObjects){let e={},t=0;if(S.keyMap)for(;(n=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[v(S.decodeKey(n))]=N()}else for(;(n=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[v(n)]=N()}return e}{y&&(S.mapsAsObjects=!0,y=!1);let e=new Map;if(S.keyMap){let t=0;for(;(n=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(S.decodeKey(n),N())}}else{let t=0;for(;(n=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(n,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,S.copyBuffers?Uint8Array.prototype.slice.call(n,a,a+=r):n.subarray(a,a+=r);case 3:if(b>=a)return d.slice(a-w,(a+=e)-w);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(S.mapsAsObjects){let t={};if(S.keyMap)for(let r=0;r<e;r++)t[v(S.decodeKey(N()))]=N();else for(let r=0;r<e;r++)t[v(N())]=N();return t}{y&&(S.mapsAsObjects=!0,y=!1);let t=new Map;if(S.keyMap)for(let r=0;r<e;r++)t.set(S.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 s={};if(S.keyMap)for(let t=2;t<e;t++){s[v(S.decodeKey(r[t-2]))]=N()}else for(let t=2;t<e;t++){s[v(r[t-2])]=N()}return s}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(S.getShared&&(Q(),t=l[8191&e],t))return t.read||(t.read=L(t)),t.read()}}let s=A[e];if(s)return s.handlesRead?s(N):s(N());{let t=N();for(let r=0;r<I.length;r++){let s=I[r](e,t);if(void 0!==s)return s}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=n[a++];if(e&=31,e>23)switch(e){case 24:e=n[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 "+n[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=S.keyMap?new Function("r","return {"+r.map((e=>S.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(S.keyMap)for(let t=0;t<e;t++)r[v(S.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&&s)return s.decode(n.subarray(a,a+=e));const r=a+e,i=[];for(t="";a<r;){const e=n[a++];if(128&e)if(192==(224&e)){const t=63&n[a++];i.push((31&e)<<6|t)}else if(224==(240&e)){const t=63&n[a++],r=63&n[a++];i.push((31&e)<<12|t<<6|r)}else if(240==(248&e)){let t=(7&e)<<18|(63&n[a++])<<12|(63&n[a++])<<6|63&n[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 s=0;s<e;s++){const e=n[a++];if((128&e)>0)return void(a=t);r[s]=e}return U.apply(String,r)}function P(e){if(e<4){if(e<2){if(0===e)return"";{let e=n[a++];return(128&e)>1?void(a-=1):U(e)}}{let t=n[a++],r=n[a++];if((128&t)>0||(128&r)>0)return void(a-=2);if(e<3)return U(t,r);let s=n[a++];return(128&s)>0?void(a-=3):U(t,r,s)}}{let t=n[a++],r=n[a++],s=n[a++],i=n[a++];if((128&t)>0||(128&r)>0||(128&s)>0||(128&i)>0)return void(a-=4);if(e<6){if(4===e)return U(t,r,s,i);{let e=n[a++];return(128&e)>0?void(a-=5):U(t,r,s,i,e)}}if(e<8){let o=n[a++],c=n[a++];if((128&o)>0||(128&c)>0)return void(a-=6);if(e<7)return U(t,r,s,i,o,c);let l=n[a++];return(128&l)>0?void(a-=7):U(t,r,s,i,o,c,l)}{let o=n[a++],c=n[a++],l=n[a++],d=n[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,s,i,o,c,l,d);{let e=n[a++];return(128&e)>0?void(a-=9):U(t,r,s,i,o,c,l,d,e)}}if(e<12){let u=n[a++],h=n[a++];if((128&u)>0||(128&h)>0)return void(a-=10);if(e<11)return U(t,r,s,i,o,c,l,d,u,h);let f=n[a++];return(128&f)>0?void(a-=11):U(t,r,s,i,o,c,l,d,u,h,f)}{let u=n[a++],h=n[a++],f=n[a++],p=n[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,s,i,o,c,l,d,u,h,f,p);{let e=n[a++];return(128&e)>0?void(a-=13):U(t,r,s,i,o,c,l,d,u,h,f,p,e)}}{let y=n[a++],g=n[a++];if((128&y)>0||(128&g)>0)return void(a-=14);if(e<15)return U(t,r,s,i,o,c,l,d,u,h,f,p,y,g);let m=n[a++];return(128&m)>0?void(a-=15):U(t,r,s,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,s=e.byteLength;r<s;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 s={};for(let n=2;n<t;n++){s[v(r[n-2])]=e[n]}return s},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 W=e=>{if(132!=n[a++]){let e=new Error("Packed values structure must be followed by a 4 element array");throw n.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 z(e,t){return"string"==typeof e?e+t:e instanceof Array?e.concat(t):Object.assign({},e,t)}function q(){if(!f){if(!S.getShared)throw new Error("No packed values available");Q()}return f}W.handlesRead=!0,A[51]=W,A[6]=e=>{if(!f){if(!S.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++,s=a;t=n[a]>>5==4?[]:{};let i={target:t};h.set(r,i);let o=e();return i.used?(Object.getPrototypeOf(t)!==Object.getPrototypeOf(o)&&(a=s,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=>(S.mapsAsObjects&&(S.mapsAsObjects=!1,y=!0),e())).handlesRead=!0;I.push(((e,t)=>e>=225&&e<=255?z(q().prefixes[e-224],t):e>=28704&&e<=32767?z(q().prefixes[e-28672],t):e>=1879052288&&e<=2147483647?z(q().prefixes[e-1879048192],t):e>=216&&e<=223?z(t,q().suffixes[e-216]):e>=27647&&e<=28671?z(t,q().suffixes[e-27639]):e>=1811940352&&e<=1879048191?z(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,s="get"+e.name.slice(0,-5);"function"==typeof e?r=e.BYTES_PER_ELEMENT:e=null;for(let n=0;n<2;n++){if(!n&&1==r)continue;let i=2==r?1:4==r?2:8==r?3:0;A[n?t:t-4]=1==r||n==G?s=>{if(!e)throw new Error("Could not find typed array for code "+t);return S.copyBuffers||1!==r&&(2!==r||1&s.byteOffset)&&(4!==r||3&s.byteOffset)&&(8!==r||7&s.byteOffset)?new e(Uint8Array.prototype.slice.call(s,0).buffer):new e(s.buffer,s.byteOffset,s.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[s];for(let e=0;e<o;e++)c[e]=l.call(a,e<<i,n);return c}}}function X(){let e=31&n[a++];if(e>23)switch(e){case 24:e=n[a++];break;case 25:e=p.getUint16(a),a+=2;break;case 26:e=p.getUint32(a),a+=4}return e}function Q(){if(S.getShared){let e=Z((()=>(n=null,S.getShared())))||{},t=e.structures||[];S.sharedVersion=e.version,f=S.sharedValues=e.packedValues,!0===l?S.structures=l=t:l.splice.apply(l,[0,t.length].concat(t))}}function Z(e){let t=i,r=a,s=_,o=w,c=b,f=d,y=E,g=h,m=u,A=new Uint8Array(n.slice(0,i)),I=l,F=S,T=C,R=e();return i=t,a=r,_=s,w=o,b=c,d=f,E=y,h=g,u=m,n=A,C=T,l=I,S=F,p=new DataView(n.buffer,n.byteOffset,n.byteLength),R}function ee(){n=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 se=re.decode;re.decodeMultiple;let ne,ie,ae;try{ne=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 Se(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 we{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,s=e.length;r<s;r++)Fe(e[r],t);else{let s=!t.encoder.useRecords;for(var r in e)e.hasOwnProperty(r)&&(s&&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,s=e.byteOffset||0,n=e.buffer||e;t(ce?oe.from(n,s,r):new Uint8Array(n,s,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,we],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||[],s=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(s){pe.setUint32(ge,3655335424),ge+=3;let r=s.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,s,n,i;super(e),this.offset=0,e=e||{};let a=de.prototype.utf8Write?function(e,t,r){return fe.utf8Write(e,t,r)}:!(!ne||!ne.encodeInto)&&function(e,t){return ne.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 s,n=r.transitions;for(let r=0,i=e.length;r<i;r++){void 0===n[_e]&&(n[_e]=t);let i=e[r];s=n[i],s||(s=n[i]=Object.create(null)),n=s}n[_e]=1048576|t}}d||(r.nextId=e)}if(s&&(s=!1),n=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&&S(ge),o.offset=ge;let e=function(e,t){let r,s=2*t.length,n=e.length-s;t.sort(((e,t)=>e.offset>t.offset?1:-1));for(let r=0;r<t.length;r++){let s=t[r];s.id=r;for(let t of s.references)e[t++]=r>>8,e[t]=255&r}for(;r=t.pop();){let t=r.offset;e.copyWithin(t+s,t,n),s-=2;let i=t+s;e[i++]=216,e[i++]=28,n=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(s&&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,n]of u)n.count>t&&(f[e]=r++,p.push(e),s=!0);for(;this.saveShared&&!1===this.updateSharedData(););u=null});const E=r=>{ge>ye&&(fe=S(ge));var s,n=typeof r;if("string"===n){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 n,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=S(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)}n=i<32?1:i<256?2:i<65536?3:5;let o=3*i;if(ge+o>ye&&(fe=S(ge+o)),i<64||!a){let e,t,a,o=ge+n;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);s=o-ge-n}else s=a(r,ge+n,o);s<24?fe[ge++]=96|s:s<256?(n<2&&fe.copyWithin(ge+2,ge+1,ge+1+s),fe[ge++]=120,fe[ge++]=s):s<65536?(n<3&&fe.copyWithin(ge+3,ge+2,ge+2+s),fe[ge++]=121,fe[ge++]=s>>8,fe[ge++]=255&s):(n<5&&fe.copyWithin(ge+5,ge+3,ge+3+s),fe[ge++]=122,pe.setUint32(ge,s),ge+=4),ge+=s}else if("number"===n)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"===n)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){(s=r.length)<24?fe[ge++]=128|s:be(s);for(let e=0;e<s;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),(s=r.size)<24?fe[ge++]=160|s:s<256?(fe[ge++]=184,fe[ge++]=s):s<65536?(fe[ge++]=185,fe[ge++]=s>>8,fe[ge++]=255&s):(fe[ge++]=186,pe.setUint32(ge,s),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],s=t.tag;return null==s&&(s=t.getTag&&t.getTag.call(this,r)),s<24?fe[ge++]=192|s:s<256?(fe[ge++]=216,fe[ge++]=s):s<65536?(fe[ge++]=217,fe[ge++]=s>>8,fe[ge++]=255&s):s>-1&&(fe[ge++]=218,pe.setUint32(ge,s),ge+=4),void t.encode.call(this,r,E,S)}}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"===n)fe[ge++]=r?245:244;else if("bigint"===n){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()),S)}fe[ge++]=251,pe.setFloat64(ge,Number(r))}ge+=8}else{if("undefined"!==n)throw new Error("Unknown type: "+n);fe[ge++]=247}},_=!1===this.useRecords?this.variableMapSize?e=>{let t=Object.keys(e),r=Object.values(e),s=t.length;if(s<24?fe[ge++]=160|s:s<256?(fe[ge++]=184,fe[ge++]=s):s<65536?(fe[ge++]=185,fe[ge++]=s>>8,fe[ge++]=255&s):(fe[ge++]=186,pe.setUint32(ge,s),ge+=4),o.keyMap)for(let e=0;e<s;e++)E(o.encodeKey(t[e])),E(r[e]);else for(let e=0;e<s;e++)E(t[e]),E(r[e])}:e=>{fe[ge++]=185;let r=ge-t;ge+=2;let s=0;if(o.keyMap)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(o.encodeKey(t)),E(e[t]),s++);else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(t),E(e[t]),s++);fe[r+++t]=s>>8,fe[r+t]=255&s}:(e,t)=>{let r,i,a,o=n.transitions||(n.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=n.nextId++,u||(u=0,n.nextId=1),u>=256&&(n.nextId=(u=l)+1)):u=i,n[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=n.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,s=!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])},S=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 s=new le(r);return pe=new DataView(s.buffer,0,r),fe.copy?fe.copy(s,0,t,e):s.set(fe.slice(t,e)),ge-=t,t=0,ye=s.length-10,fe=s};let w=100,b=1e3;function*A(e,r,s){let n=e.constructor;if(n===Object){let t=!1!==o.useRecords;t?_(e,!0):Se(Object.keys(e).length,160);for(let s in e){let n=e[s];t||E(s),n&&"object"==typeof n?r[s]?yield*A(n,r[s]):yield*I(n,r,s):E(n)}}else if(n===Array){let s=e.length;be(s);for(let n=0;n<s;n++){let s=e[n];s&&("object"==typeof s||ge-t>w)?r.element?yield*A(s,r.element):yield*I(s,r,"element"):E(s)}}else if(e[Symbol.iterator]&&!e.buffer){fe[ge++]=159;for(let s of e)s&&("object"==typeof s||ge-t>w)?r.element?yield*A(s,r.element):yield*I(s,r,"element"):E(s);fe[ge++]=255}else Ie(e)?(Se(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);s&&ge>t?yield fe.subarray(t,ge):ge-t>w&&(yield fe.subarray(t,ge),F())}function*I(e,r,s){let n=ge-t;try{E(e),ge-t>w&&(yield fe.subarray(t,ge),F())}catch(i){if(!i.iteratorNotHandled)throw i;r[s]={},ge=t+n,yield*A.call(this,e,r[s])}}function F(){w=b,o.encode(null,Pe)}function C(e,t,r){return w=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 we(t,this.sharedValues,this.sharedVersion),s=this.saveShared(r,(t=>(t&&t.version||0)==e));return!1===s?(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)),s}}({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=new Set(["dome","intouchapp"]);var xe,Ke,Ve,He,We,ze,qe;!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"}(xe||(xe={})),function(e){e.INIT_MESSAGE_CHANNEL="INIT_MESSAGE_CHANNEL"}(Ke||(Ke={})),function(e){e.CONNECT="CONNECT"}(Ve||(Ve={})),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"}(He||(He={})),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"}(ze||(ze={}));class Ge{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.rE}`),this.detectHost(),this.setupDeepLinkInterception()}detectHost(){void 0!==window.AndroidBridge?this.runtimeHost="android":void 0!==window.webkit?this.runtimeHost="ios":this.runtimeHost="webapp",console.debug(`Detected host: ${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||!je.has(t))&&(this.sendMessage(ze.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 s=t??this.parentCapabilities??r.capabilities;t&&(this.parentCapabilities=t),s?r.capabilities=s:delete r.capabilities,this.parentHostDetails=r,this.parentCapabilities=s??null,s?console.info("Host capabilities detected",{host_type:r.type,capabilities:s}):console.info("Host capabilities not found",{hostType:r.type})}getHost(){return this.parentHostDetails??{type:this.runtimeHost}}sendMessage(e,t,r){const s={type:e,data:t??null};if("android"!==this.runtimeHost){if(this.port2)return this.port2.postMessage(s),void console.debug("Sent message via message channel:",s);switch(this.runtimeHost){case"ios":window?.webkit?.messageHandlers?window.webkit?.messageHandlers.appHandler.postMessage(JSON.stringify(s)):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.")}console.debug(`Sent message to ${this.runtimeHost}:`,s)}else{if(r){const e=this.toUint8Array(r),t=s.data&&"object"==typeof s.data?{...s.data,v:"1.0",data:e}:{v:"1.0",data:e},n=this.encodeCborMessage({...s,v:"1.0",data:t});this.port2?this.port2.postMessage(n):window.AndroidBridge?.sendMessage(n)}else{const e=JSON.stringify(s);this.port2?this.port2.postMessage(e):window.AndroidBridge?.sendMessage(e)}console.debug(`Sent message to ${this.runtimeHost}:`,s)}}sendAppInit(){this.isAppReady||(this.isAppReady=!0,this.sendMessage(xe.INIT,{sdk:{ver:r.rE}}))}safeInvoke(e,t,r){const s=t?.[e];"function"==typeof s?s(r):console.warn(`Handler for '${String(e)}' is not defined.`)}setupParentConnection(){return new Promise(((e,t)=>{switch(this.runtimeHost){case"android":window.receiveFromAndroid=e=>{console.debug("Message received from Android:",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:s}=t||{};r&&this.handleMessage(r,s)};let s=!1;const n=()=>{s||(s=!0,"android"===this.runtimeHost&&this.sendMessage(xe.CONNECTION_SUCCESS),console.debug("Message channel connect resolved; proceeding with INIT"),e())};this.setupMessageChannelListener(n),window.AndroidBridge?.sendMessage(JSON.stringify({type:Ke.INIT_MESSAGE_CHANNEL,data:{sdk:{ver:r.rE}}})),console.debug("Sent INIT_MESSAGE_CHANNEL to Android bridge");break;case"ios":window.receiveFromIOS=e=>{console.debug("Message received from iOS:",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:Ke.INIT_MESSAGE_CHANNEL,data:{sdk:{ver:r.rE}}},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 s=r.data;if("string"==typeof s)try{s=JSON.parse(s)}catch{}(s?.type??s)===Ve.CONNECT&&(console.debug("Message channel CONNECT received",s),r.ports&&0!==r.ports.length?(this.port2=r.ports[0],this.port2.onmessage=e=>this.handlePortMessage(e),console.debug("Message channel port connected"),window.removeEventListener("message",t),e?.()):console.warn("Message channel CONNECT missing ports"))};window.addEventListener("message",t)}notifyConnectionSuccess(){this.sendMessage(xe.CONNECTION_SUCCESS)}handlePortMessage(e){console.debug("received message event from port",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:s}=t||{};r&&(console.debug(`Handling port message event. type: ${r}, data: ${s}`),this.handleMessage(r,s))}handleMessage(e,t){throw new Error("Subclasses must implement handleMessage.")}decodeCborBuffer(e){let t;try{t=se(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=this.normalizeBinaryPayload(e.data);r&&(t.data={...e,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}copyBufferView(e,t,r){return e instanceof ArrayBuffer&&0===t&&r===e.byteLength?e:new Uint8Array(e,t,r).slice().buffer}}function $e(e){const{prefix:t="",given:r="",middle:s="",family:n="",suffix:i=""}=e||{};return[t,r,s,n,i].filter((e=>e)).join(" ").trim()}class Je extends Ge{constructor(){super(),this.handler=null,this.pendingRequests=new Map,this.pendingInitAck=null}static init(e){return console.debug("init called",e&&"with handler"),Je.initialized?(console.warn("ViewerSdk is already initialized. Skipping initialization."),Je.instance):(Je.instance||(Je.instance=new Je,Je.instance.setupParentConnection().then((()=>{try{Je.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&&Je.instance.setHandler(e),Je.initialized=!0,Je.instance)}setHandler(e){this.handler=e,this.pendingInitAck&&(console.debug("Processing pending INIT_ACK message after handler is set."),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(){console.debug("initializing viewer sdk"),this.sendAppInit()}requestInitialData(){this.sendMessage(xe.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(xe.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:s}=e,n=this.pendingRequests.get(t),i=this.pendingRequests.get(t+"_reject");n&&("error"===r?i?.({status:r,message:s}):n({status:r,message:s}),this.pendingRequests.delete(t),this.pendingRequests.delete(t+"_reject"))}setDirty(e){this.sendMessage(xe.SET_DIRTY,e)}sendClose(e,t){this.sendMessage(xe.SEND_CLOSE,{doc:e,isDataDirty:t})}sendException(e){this.sendMessage(xe.SEND_EXCEPTION,e)}handleMessage(e,t){if(console.debug("handleMessage called for:",e,"with data:",t),e===He.INIT_ACK&&this.updateParentContext(t?.host,t?.capabilities),this.handler)switch(e){case He.INIT_ACK:this.safeInvoke("onInitialData",this.handler,t);break;case He.DATA_CHANGE:this.safeInvoke("onDataChange",this.handler,t);break;case He.REQUEST_CLOSE:this.safeInvoke("onCloseRequest",this.handler);break;case He.REQUEST_SAVE:this.safeInvoke("onSaveRequest",this.handler);break;case He.SAVE_SUCCESS:case He.SAVE_ERROR:this.handleOnSave(t);break;default:console.warn(`No handler found for message type: ${e}`)}else e===He.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)}}Je.initialized=!1;class Ye{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 s=this.base64UrlDecode(e);if(128!==s[0])throw new Error("Invalid version");s.slice(1,9);const n=s.slice(9,25),i=s.slice(25,-32),a=s.slice(-32),o=await this.deriveKey(t,r),{hmacKey:c,aesKey:l}=await this.splitKey(o),d=s.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:n},l,i);return(new TextDecoder).decode(u)}catch(e){throw console.log("Error in decrypt:",e),e}}async deriveKey(e,t,r=1e4){const s=new TextEncoder,n=await this.subtleCrypto.importKey("raw",s.encode(e),"PBKDF2",!1,["deriveKey"]);return this.subtleCrypto.deriveKey({name:"PBKDF2",hash:"SHA-256",salt:s.encode(t),iterations:r},n,{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"}(qe||(qe={}));const Xe=qe;var Qe,Ze;!function(e){e.TEXT="text",e.JSON="json",e.BINARY="binary"}(Qe||(Qe={})),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"}(Ze||(Ze={}));const et="1.1.0";function tt(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,s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r[e]^t+17*e&255;return s}(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 rt{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(rt.DB_VERSION,e)}))),this.openPromise):null}openWithVersion(e,t){let r="ensure";const s=indexedDB.open(this.cardIuid,e);s.onupgradeneeded=e=>{r=0===(e.oldVersion||0)?"create":"ensure",this.configureStores(s.result)},s.onsuccess=()=>{const e=s.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)))},s.onerror=()=>t(null)}configureStores(e){e.objectStoreNames.contains(rt.DATA_STORE)||e.createObjectStore(rt.DATA_STORE),e.objectStoreNames.contains(rt.NAME_LOOKUP_STORE)||e.createObjectStore(rt.NAME_LOOKUP_STORE),e.objectStoreNames.contains(rt.INFO_STORE)||e.createObjectStore(rt.INFO_STORE),e.objectStoreNames.contains(rt.FOLDER_CACHE_STORE)||e.createObjectStore(rt.FOLDER_CACHE_STORE)}hasRequiredStores(e){const t=e.objectStoreNames;return t.contains(rt.DATA_STORE)&&t.contains(rt.NAME_LOOKUP_STORE)&&t.contains(rt.INFO_STORE)&&t.contains(rt.FOLDER_CACHE_STORE)}static nowMicros(){return Math.trunc(1e3*Date.now())}updateStoresMetadata(e,t){return Promise.all([this.ensureStoreVersion(e,rt.DATA_STORE),this.ensureStoreVersion(e,rt.NAME_LOOKUP_STORE),this.ensureStoreVersion(e,rt.FOLDER_CACHE_STORE),this.updateCardInfo(e,t)]).then((()=>{}))}ensureStoreVersion(e,t){return e.objectStoreNames.contains(t)?new Promise((r=>{try{const s=e.transaction(t,"readwrite"),n=s.objectStore(t),i=()=>r();s.oncomplete=i,s.onerror=i,s.onabort=i,n.put(et,rt.STORE_VERSION_KEY)}catch{r()}})):Promise.resolve()}async updateCardInfo(e,t){if(!e.objectStoreNames.contains(rt.INFO_STORE))return;const r=await this.readInfoValue(e,"container_iuid"),s=t?await this.readInfoValue(e,"ts_c"):void 0,n=this.containerIuid??r??null,i=t&&s?s:rt.nowMicros();await Promise.all([this.writeInfoValue(e,"container_iuid",n),this.writeInfoValue(e,"ts_c",i)]).catch((()=>{}))}readInfoValue(e,t){return new Promise((r=>{try{const s=e.transaction(rt.INFO_STORE,"readonly"),n=s.objectStore(rt.INFO_STORE).get(t);n.onsuccess=()=>r(n.result),n.onerror=()=>r(void 0)}catch{r(void 0)}}))}writeInfoValue(e,t,r){return new Promise((s=>{try{const n=e.transaction(rt.INFO_STORE,"readwrite"),i=n.objectStore(rt.INFO_STORE),a=()=>s();n.oncomplete=a,n.onerror=a,n.onabort=a,i.put(r,t)}catch{s()}}))}keyFor(e){return e}static normalizeFolderName(e){if("string"!=typeof e)return rt.DEFAULT_FOLDER_KEY;let t=e.trim();return t?(t=t.replace(/^\/+/,""),t?(t.endsWith("/")||(t+="/"),t||rt.DEFAULT_FOLDER_KEY):rt.DEFAULT_FOLDER_KEY):rt.DEFAULT_FOLDER_KEY}folderListingKey(e){return rt.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((s=>{const n=r.transaction(rt.DATA_STORE,"readwrite");n.objectStore(rt.DATA_STORE).put(t,e).onsuccess=()=>s(),n.oncomplete=()=>s(),n.onerror=()=>s(),n.onabort=()=>s()}))}async get(e){const t=await this.openDb();if(t)return new Promise((r=>{const s=t.transaction(rt.DATA_STORE,"readonly").objectStore(rt.DATA_STORE).get(e);s.onsuccess=()=>r(s.result),s.onerror=()=>r(void 0)}))}async delete(e){const t=await this.openDb();t&&await new Promise((r=>{const s=t.transaction(rt.DATA_STORE,"readwrite");s.objectStore(rt.DATA_STORE).delete(e).onsuccess=()=>r(),s.oncomplete=()=>r(),s.onerror=()=>r(),s.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=rt.encodeText(e),s=await t.subtle.digest("SHA-256",r);return rt.bufferToBase64(s)}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=rt.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const s=await rt.hashName(t);return new Promise((e=>{const t=r.transaction(rt.NAME_LOOKUP_STORE,"readonly").objectStore(rt.NAME_LOOKUP_STORE).get(s);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)}))}async upsertNameLookup(e,t){const r=rt.normalizeName(e);if(!r)return;const s=await this.openDb();if(!s)return;const n=await rt.hashName(r);await new Promise((e=>{const r=s.transaction(rt.NAME_LOOKUP_STORE,"readwrite"),i=r.objectStore(rt.NAME_LOOKUP_STORE);i.put(t,n);i.openCursor().onsuccess=e=>{const r=e.target.result;r&&(r.key!==n&&r.value===t&&r.delete(),r.continue())},r.oncomplete=()=>e(),r.onerror=()=>e(),r.onabort=()=>e()}))}async deleteNameLookupByName(e){const t=rt.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const s=await rt.hashName(t);await new Promise((e=>{const t=r.transaction(rt.NAME_LOOKUP_STORE,"readwrite");t.objectStore(rt.NAME_LOOKUP_STORE).delete(s),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 s=t.transaction(rt.NAME_LOOKUP_STORE,"readwrite");s.objectStore(rt.NAME_LOOKUP_STORE).openCursor().onsuccess=t=>{const r=t.target.result;r&&(r.value===e&&r.delete(),r.continue())},s.oncomplete=()=>r(),s.onerror=()=>r(),s.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=rt.normalizeName(e.name);if(r&&await this.upsertNameLookup(r,e.iuid),void 0===t)return void await this.delete(this.keyFor(`${e.iuid}_data`));rt.estimateSize(t)<=rt.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=rt.normalizeName(e);if(!t)return null;const r=await this.getIuidForName(t);if(!r)return null;const s=await this.get(this.keyFor(`${r}_object`));if(!s)return null;return{iuid:r,object:s,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 s=this.folderListingKey(e??t.folder_name),n="object"==typeof t.data&&null!==t.data?t.data:Array.isArray(t.documents)?t.documents:{},i=Array.isArray(n)?{results:[...n]}:{...n},a={folder_name:s,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(rt.FOLDER_CACHE_STORE,"readwrite");t.objectStore(rt.FOLDER_CACHE_STORE).put(a,s).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 s=t.transaction(rt.FOLDER_CACHE_STORE,"readonly").objectStore(rt.FOLDER_CACHE_STORE).get(r);s.onsuccess=()=>e(s.result),s.onerror=()=>e(null)}))}}rt.DB_VERSION=3,rt.DATA_STORE="cardfs",rt.NAME_LOOKUP_STORE="cardfs_name_iuid_lookup",rt.INFO_STORE="info",rt.FOLDER_CACHE_STORE="folder_cache",rt.STORE_VERSION_KEY="ver",rt.DEFAULT_FOLDER_KEY="/",rt.MAX_DATA_BYTES=5242880;class st extends Ge{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(rt.estimateSize(e)>rt.MAX_DATA_BYTES){const e=t?` for ${t}`:"";return console.warn(`cardFS.read payload data exceeded ${rt.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){if(null==e)return e;const r="string"==typeof t?t.toLowerCase():"";if(!r)return e;const s=r.includes("application/json")||r.endsWith("+json"),n=r.startsWith("text/"),i=e instanceof ArrayBuffer||ArrayBuffer.isView(e),a=()=>{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(i)try{return JSON.parse(a())}catch{return a()}if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}if(n){if(i)return a();if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}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===Qe.TEXT?this.encodeTextPayload(e):t===Qe.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 rt(e,this.containerIuid))}return this.cardFsCache}supportsParentCardFs(){const e=this.parentCapabilities?.card_fs;return!!e?.ver&&e.ver===et}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(st.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 s=this.pendingAcks.get(r);if(s.ackType===e)return clearTimeout(s.timeout),this.pendingAcks.delete(r),void s.resolve(t)}if(r||!this.resolvePendingAckByType(e,t)){if(!this.handler)throw new Error("Message handler not found!");switch(e){case We.INIT_ACK:console.debug("CardSdk: INIT_ACK received"),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 rt(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=>{console.debug("CardSdk: INIT_ACK: decrypted data ",e);const r=JSON.parse(e),s=r?.container?.iuid;s&&(this.containerIuid=s,this.shouldUseCardFsFallback()&&this.dataStore?.iuid&&(this.cardFsCache=new rt(this.dataStore.iuid,this.containerIuid)));const n="string"==typeof r?.api_token?r.api_token.trim():"";n?(this.accessToken=n,console.debug("CardSdk: Stored API token from INIT_ACK payload")):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 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,...s}=t||{};return void this.handleFsReadDataMessage(e,s)}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 Ye,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,s)=>this.cardFSWrite(e,t,r,s),writeById:(e,t,r,s)=>this.cardFSWriteById(e,t,r,s),delete:(e,t)=>this.cardFSDelete(e,t),deleteById:(e,t)=>this.cardFSDeleteById(e,t),list:(e,t)=>this.cardFSList(e,t)},console.debug("CardSdk::constructor: done")}static async init(e,t,r){try{return console.debug("CardSdk::init"),st.instance?st.instance:(st.instance=new st,st.instance.setupParentConnection().then((()=>{st.instance.initializeCardSdk(e)})).catch((e=>{console.error(e)})),t&&st.instance.setHandler(t),st.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):st.DEFAULT_ROLE_PERMISSIONS.includes(e)}canRead(){return this.hasPerm(qe.READ)}canWrite(){return this.hasPerm(qe.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(ze.AF1_DATA_TOKEN,{sdk:{ver:r.rE}},We.AF1_DATA_TOKEN_ACK),{messageId:s,...n}=t||{},{cie:i,ck:a,dev_token:o}=n;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,s){if(!(e&&t&&r&&s))throw new Error("Invalid AF1 data fetch parameters");const n=new URL(`https://dome.so/api/v1/cards/e/${encodeURIComponent(e)}/data_af1/`);n.searchParams.set("dt",r),n.searchParams.set("rt",s),n.searchParams.set("ck",t);const i=await fetch(n.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(console.debug(t,"enter"),!e)throw new Error("Invalid secret");const r=window.location.href;console.debug(t,"url:",r);const s=new URL(r),n=s.searchParams.get("rt");if(!n)throw new Error("Missing request token");let i=this.getCardIuidEnc(s),a=window.IT_DATA_AF1;if(!a){console.debug(t,"IT_DATA_AF1 missing. Requesting token via parent");const{dataAf1:e,cie:r}=await this.requestAf1DataFromParent(n);a=e,i=r||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);console.debug(t,"ss:",o);const c=await this.cryptoA01.decrypt(a,e,o);try{const e=JSON.parse(c);if(console.debug("CardSdk: dataFromServer:",e),!e.ite)throw new Error("Invalid data");this.dataStore={denc:e.d,kw2:e.kw2},st.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.rE}},s=this.getWebappDetails();s&&(t.wa=s),this.sendMessage(ze.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,s=15e3,n,i){const a=crypto.randomUUID();if(n)try{n(a)}catch(e){return Promise.reject(e)}return new Promise(((n,o)=>{const c=setTimeout((()=>{this.pendingAcks.delete(a);const e=new Error(`${r} not received in time`);this.isCardFsAckType(r)&&(e.code=Ze.TIMEOUT),o(e)}),s);this.pendingAcks.set(a,{resolve:n,reject:o,timeout:c,ackType:r}),this.sendMessage(e,{...t,messageId:a},i)}))}resolvePendingAckByType(e,t){for(const[r,s]of this.pendingAcks.entries())if(s.ackType===e)return clearTimeout(s.timeout),this.pendingAcks.delete(r),s.resolve(t),!0;return!1}cardFSRead(e,t,r=!0){const s={name:e},n=this.assertValidReadHandler(t);this.cardFSReadInternal(s,n,r,"read")}cardFSReadById(e,t,r=!0){const s={iuid:e},n=this.assertValidReadHandler(t);this.cardFSReadInternal(s,n,r,"readById")}cardFSReadInternal(e,t,r,s){if(this.shouldUseCardFsFallback())return console.debug(`cardFS.${s} using fallback implementation for`,e),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))}));console.debug(`cardFS.${s} delegating to parent for`,e);let n=null;const i=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document";this.sendMessageWithAck(ze.CFS_READ_FILE,this.buildCardFsMessagePayload(e,{allow_stale:r}),We.CFS_READ_FILE_ACK,st.CARD_FS_ACK_TIMEOUT_MS,(e=>{n=e;const a={name:i,handler:t,allowStale:r,timeoutMessage:`cardFS.${s} timed out for ${i}`};this.fsReadRequests.set(e,a)})).catch((e=>{const r=e instanceof Error?e:new Error(String(e));n?this.failFsReadRequest(n,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=Qe.JSON,s){const n={name:e};return"android"===this.runtimeHost&&r===Qe.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then((e=>this.cardFSWriteInternal(n,e,r,s,"write"))):this.cardFSWriteInternal(n,t,r,s,"write")}cardFSWriteById(e,t,r=Qe.JSON,s){const n={iuid:e};return"android"===this.runtimeHost&&r===Qe.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then((e=>this.cardFSWriteInternal(n,e,r,s,"writeById"))):this.cardFSWriteInternal(n,t,r,s,"writeById")}cardFSWriteInternal(e,t,r,s,n){return this.shouldUseCardFsFallback()?(console.debug(`cardFS.${n} using fallback implementation for`,e),this.cardFSWriteFallback(e,t,r).catch((e=>{throw this.toCardFsErrorPayload(e)}))):(console.debug(`cardFS.${n} delegating to parent for`,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===Qe.BINARY&&"android"===this.runtimeHost&&u;let f=l;r!==Qe.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")),console.debug("cardFS.write sending",{name:e.name,iuid:e.iuid,file_type:r,file_size:d,data:f}),this.sendMessageWithAck(ze.CFS_WRITE_FILE,this.buildCardFsMessagePayload(e,{data:h?null:f,file_type:r,file_size:d}),We.CFS_WRITE_FILE_ACK,st.CARD_FS_ACK_TIMEOUT_MS,(e=>{o=e;const t={name:c,onUpdate:s,resolve:i,reject:a,timeoutMessage:`cardFS.${n} 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()?(console.debug(`cardFS.${r} using fallback implementation for`,e),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)}))):(console.debug(`cardFS.${r} delegating to parent for`,e),new Promise(((r,s)=>{this.sendMessageWithAck(ze.CFS_DELETE_FILE,this.buildCardFsMessagePayload(e),We.CFS_DELETE_FILE_ACK,st.CARD_FS_ACK_TIMEOUT_MS).then((e=>{const{messageId:s,...n}=e||{};t?.(n),r(n)})).catch((e=>{s(this.toCardFsErrorPayload(e))}))})))}cardFSList(e,t){const r=this.assertValidListHandler(t),s=this.formatFolderPath(e);if(this.shouldUseCardFsFallback())return console.debug("cardFS.list using fallback implementation"),void this.cardFSListFallbackStream(s,r);console.debug("cardFS.list delegating to parent");const n=s?{name:s}:{},i=crypto.randomUUID(),a={name:s??"folder listing",handler:r,timeoutMessage:"cardFS.list timed out"};this.fsListRequests.set(i,a),this.resetFsListProgressTimeout(i),this.sendMessage(ze.CFS_LIST_FILES,{...n,messageId:i})}async cardFSListFallbackStream(e,t){const r=this.ensureCardFsCache();let s=!1;if(r)try{const n=await r.getFolderListing(e);if(n){const e=Array.isArray(n.data?.results)?n.data.results:[];t.next(this.normalizeListResult({documents:e,folder_name:n.folder_name,folder_iuid:n.folder_iuid??void 0,last_index:n.last_index??null,last_page:n.last_page??null,from_cache:!0,is_dirty:!0,is_complete:!1})),s=!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){s?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:Ze.TIMEOUT,message:t.timeoutMessage})}),st.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:Ze.TIMEOUT,message:t.timeoutMessage})}),st.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:Ze.TIMEOUT,message:t.timeoutMessage})}),st.FS_RESPONSE_TIMEOUT_MS))}handleFsReadDataMessage(e,t){const r=this.fsReadRequests.get(e);if(!r)return;let s=t?.data;"string"!=typeof s||"base64"!==t?.encoding&&!this.isBinaryReadPayload(t)||(s=this.decodeBase64BinaryData(s));const n=this.sanitizeReadData(s,r.name),i=this.normalizeReadData(n.value,t?.object?.mimetype),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};console.debug("cardFS.read received",o),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)}),st.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)}),st.FS_READ_RETENTION_MS),!0)}if(e===We.CFS_WRITE_FILE_ACK){const e=this.fsWriteRequests.get(r);if(!e)return!1;const{messageId:s,...n}=t||{};if("function"==typeof e.onUpdate)try{e.onUpdate(n)}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.rE}};this.sendMessage(ze.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)%st.MAX_CONSOLE_LOG_ENTRIES,this.consoleLogSize=Math.min(this.consoleLogSize+1,st.MAX_CONSOLE_LOG_ENTRIES)}clearConsoleLogs(){this.consoleLogBuffer.fill(null),this.consoleLogWriteIndex=0,this.consoleLogSize=0}getConsoleLogs(){if(0===this.consoleLogSize)return[];if(this.consoleLogSize<st.MAX_CONSOLE_LOG_ENTRIES)return this.consoleLogBuffer.slice(0,this.consoleLogSize).filter((e=>null!==e));const e=[];for(let t=0;t<st.MAX_CONSOLE_LOG_ENTRIES;t+=1){const r=(this.consoleLogWriteIndex+t)%st.MAX_CONSOLE_LOG_ENTRIES,s=this.consoleLogBuffer[r];s&&e.push(s)}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>st.MAX_CONSOLE_ARG_CHARS?{type:"truncated",preview:e.slice(0,st.MAX_CONSOLE_ARG_CHARS),original_length:e.length}:e;const t=JSON.stringify(e);if("string"==typeof t&&t.length>st.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,s)=>{if("string"==typeof e)return(e=>e.length<=st.MAX_CONSOLE_STRING_PREVIEW_CHARS?e:{type:"truncated",preview:e.slice(0,st.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(s>=3)return{type:"truncated",reason:"max_depth"};if(t.add(e),Array.isArray(e)){const t=e.slice(0,5).map((e=>r(e,s+1)));return e.length>5&&t.push({type:"truncated",remaining:e.length-5}),t}const n=Object.entries(e),i={};for(const[e,t]of n.slice(0,5))i[e]=r(t,s+1);return n.length>5&&(i.__truncated__={remaining:n.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:s,...n}=t||{};console.debug("cardFS.write response",n),r.resolve(n)}handleFsListDataMessage(e,t){const r=this.fsListRequests.get(e);if(!r)return;this.resetFsListProgressTimeout(e);const{messageId:s,...n}=t||{},i=this.normalizeListResult(n);r.handler.next(i),i.is_complete&&this.clearFsListRequest(e)}createCardFsError(e,t){const r=new Error(e?.message||t),s=e?.error_code;return s&&Object.values(Ze).includes(s)&&(r.code=s),r}toCardFsErrorPayload(e,t="Unknown cardFS error"){const r="string"==typeof e?.message?e.message:"string"==typeof e?e:t,s=e?.code??e?.error_code;return s&&Object.values(Ze).includes(s)?{code:s,message:r}:{message:r}}async cardFSReadFallback(e,t,r,s=!0){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.read fallback is disabled because parent supports card_fs");const n=this.getCardIuid();if(!n)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=(s,n,i,a,c,l,d)=>{if(!s)return null;const u=c??e.name??s?.name??e.iuid??"document",h=l??s?.iuid??e.iuid??null,f=!1!==d?.includeData,p=f?this.sanitizeReadData(n,u).value:void 0,y={name:u,iuid:h,object:s,data:f?this.normalizeReadData(p,s?.mimetype):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):(console.debug("cardFS.read received",y),this.invokeReadHandlerNext(r,y)),o=!0,y};if(i)try{if(s){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(n,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,s=t.object?.data_hash,n=void 0!==e&&void 0!==s&&e===s;l(t.object,t.data,!1,!0,r,t.object?.iuid,{includeData:!n,isDirty:!n})}else l(t.object,t.data,!1,!0,r,t.object?.iuid)}catch(s){const n=s instanceof Error?s:new Error(String(s)),c=this.getCardFsErrorCode(n);if(c===Ze.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(n.message),{code:c})}if(c===Ze.NOT_FOUND||c===Ze.NO_PERMISSION){const e={code:c,message:n.message};t&&this.fsReadRequests.has(t)?this.failFsReadRequest(t,e):this.invokeReadHandlerError(r,e)}else console.warn("cardFS.read fresh fetch failed",s)}if(!o)throw new Error(`cardFS.read fallback could not locate ${c}`)}async cardFSWriteFallback(e,t,r,s){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.write fallback is disabled because parent supports card_fs");const n=this.getCardIuid();if(!n)throw new Error("cardFS.write fallback failed: card not initialized");console.debug("cardFS.write fallback invoked for target",e);try{const i=this.normalizeWriteData(t,r);await this.upsertDocumentViaApi(n,e,i,r);const a=await this.fetchDocumentPayload(n,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 s&&this.fsWriteRequests.has(s)?this.handleFsWriteSuccess(s,o):console.debug("cardFS.write response",o),o}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,s=r&&Object.values(Ze).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:s})}}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");console.debug("cardFS.delete fallback invoked for target",e);try{const r=this.ensureCardFsCache(),s=await this.fetchDocumentMetadataByTarget(t,e).catch((()=>null)),n=s?.iuid??e.iuid??null,i=s?.name??e.name??null;if(!n)return e.name&&await(r?.deleteByName(e.name)),{name:i,iuid:null,deleted:!1};const a=await fetch(`/api/v1/documents/${n}/`,{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(n,i??void 0));return{name:i??n,iuid:n,deleted:404!==a.status}}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,s=r&&Object.values(Ze).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:s})}}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(),s=this.formatFolderPath(e),n=s??"/";try{const e=await this.fetchFolderListing(t,s);return r&&(await r.cacheFolderListing(s,{folder_name:e.folder_name??n,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??n,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(s));if(t){return{documents:Array.isArray(t.data?.results)?t.data.results:[],folder_name:t.folder_name??n,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(Ze).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),s="boolean"==typeof e?.is_complete?e.is_complete:!r,n="boolean"!=typeof e?.is_dirty||e.is_dirty;return{...e,documents:t,is_stale:r,is_complete:s,is_dirty:n}}getCardFsErrorCode(e){if(!e)return Ze.UNKNOWN;const t=e?.status??e?.statusCode;if(0===t)return Ze.NO_INTERNET;if(401===t||403===t)return Ze.NO_PERMISSION;if(404===t)return Ze.NOT_FOUND;if(500===t)return Ze.SERVER_ERROR;const r="string"==typeof e?.message?e.message.toLowerCase():"";return r.includes("not found")?Ze.NOT_FOUND:r.includes("permission")||r.includes("unauthorized")||r.includes("forbidden")?Ze.NO_PERMISSION:r.includes("network")||r.includes("failed to fetch")||r.includes("offline")?Ze.NO_INTERNET:Ze.UNKNOWN}isBinaryReadPayload(e){if((e?.file_type??e?.object?.file_type??e?.object?.fileType)===Qe.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 s=await r.json().catch((()=>null)),n=this.normalizeDocumentsResponse(s);return n.find((e=>e?.name===t))??n[0]??null}async fetchFolderListing(e,t){const r=t?`?name=${encodeURIComponent(t)}`:"",s=await fetch(`/api/v1/documents/with_card/${e}/${r}`,{method:"GET",headers:this.authHeader()});if(!s.ok){const e=await s.text().catch((()=>"list failed"));throw new Error(`cardFS.list failed: ${e}`)}const n=await s.json().catch((()=>null));return{documents:this.normalizeDocumentsResponse(n),folder_name:t,folder_iuid:void 0,last_index:n?.last_index??n?.last_page??null,last_page:n?.last_page??null}}async fetchDocumentPayload(e,t){const r="string"==typeof t?{name:t}:t,s=await this.fetchDocumentMetadataByTarget(e,r);if(!s){const e=r.name?`"${r.name}"`:r.iuid?`iuid ${r.iuid}`:"document";throw new Error(`cardFS document not found: ${e}`)}return{object:s,data:await this.fetchDocumentData(s)}}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 s=r.headers.get("Content-Type")||"";return s.includes("application/json")?r.json():s.startsWith("text/")?r.text():r.arrayBuffer()}async buildFileFormData(e,t,r){let s;if(t instanceof File)s=t;else if("undefined"!=typeof Blob&&t instanceof Blob)s=new File([t],e,{type:t.type||"application/octet-stream"});else{const n=r===Qe.TEXT?"text/plain":r===Qe.JSON?"application/json":"application/octet-stream";s=new File([t],e,{type:n})}const n=new FormData;return n.append("file",s),n}async upsertDocumentViaApi(e,t,r,s){if(t.iuid){let e=t.name;if(!e){const r=await this.fetchDocumentMetadataByIuid(t.iuid).catch((()=>null));e=r?.name??t.iuid}const n=await this.buildFileFormData(e??t.iuid??"document",r,s),i=await fetch(`/api/v1/documents/${t.iuid}/`,{method:"PUT",headers:this.authHeader(),body:n});if(!i.ok){const e=await i.text().catch((()=>"update failed"));throw new Error(`cardFS.write update failed: ${e}`)}return}const n=await this.buildFileFormData(t.name??t.iuid??"document",r,s),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:n});if(!e.ok){const t=await e.text().catch((()=>"update failed"));throw new Error(`cardFS.write update failed: ${t}`)}return}if(n.append("parent_iuid",e),n.append("attached_to_iuid",e),!t.name)throw new Error('cardFS.write failed: "name" missing');n.append("filename",t.name);const a=await fetch("/api/v1/documents/",{method:"POST",headers:this.authHeader(),body:n});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 s={message:this.formatErrorMessage(t),error_code:e,data:r??null};this.handler&&this.safeInvoke("onError",this.handler,s)}setFileDirty(e){this.sendMessage(ze.FILE_DIRTY,e)}getUsername(e){const t=e?.name;return t&&Object.values(t).some((e=>e))?$e(t):""}attachUserFullName(e){return e&&"object"==typeof e?{...e,getFullName(){return $e(this?.name)}}:e}}return st.FS_RESPONSE_TIMEOUT_MS=3e4,st.FS_READ_RETENTION_MS=15e3,st.CARD_FS_ACK_TIMEOUT_MS=15e3,st.MAX_CONSOLE_ARG_CHARS=2e3,st.MAX_CONSOLE_LOG_ENTRIES=100,st.MAX_CONSOLE_STRING_PREVIEW_CHARS=200,st.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 s in r)e.o(r,s)&&!e.o(t,s)&&Object.defineProperty(t,s,{enumerable:!0,get:r[s]})},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:()=>Ze,CardFsFileType:()=>Qe,CardMessageType:()=>ze,CardPermission:()=>qe,CardSdk:()=>st,CommonClientMessageType:()=>Ve,CryptoA01:()=>Ye,DomeEmbeddedAppSdk:()=>Ge,ViewerClientMessageType:()=>He,ViewerMessageType:()=>xe,ViewerSdk:()=>Je,cardPermission:()=>Xe,getKeyFromBlob:()=>tt});const r=JSON.parse('{"rE":"0.3.6-experimental.9"}');let s,n,i;try{s=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,S={},w=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,s]of Object.entries(e))t.set(this._keyMap.hasOwnProperty(r)?this._keyMap[r]:r,s);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(n)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,n=e;try{p=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))}catch(t){if(n=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(S=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 S=F,(!l||l.length>0)&&(l=[]),f=null;return O()}decodeMultiple(e,t){let r,s=0;try{let n=e.length;C=!0;let i=this?this.decode(e,n):re.decode(e,n);if(!t){for(r=[i];a<n;)s=a,r.push(O());return r}if(!1===t(i))return;for(;a<n;)if(s=a,!1===t(O()))return}catch(e){throw e.lastPosition=s,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,n=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=n[a++],t=e>>5;if(e&=31,e>23)switch(e){case 24:e=n[a++];break;case 25:if(7==t)return function(){let e=n[a++],t=n[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(S.useFloat32>2){let t=te[(127&n[a])<<1|n[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 S.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=[],s=0;for(;(e=N())!=c;){if(s>=g)throw new Error(`Array length exceeds ${g}`);r[s++]=e}return 4==t?r:3==t?r.join(""):Buffer.concat(r);case 5:let n;if(S.mapsAsObjects){let e={},t=0;if(S.keyMap)for(;(n=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[v(S.decodeKey(n))]=N()}else for(;(n=N())!=c;){if(t++>=m)throw new Error(`Property count exceeds ${m}`);e[v(n)]=N()}return e}{y&&(S.mapsAsObjects=!0,y=!1);let e=new Map;if(S.keyMap){let t=0;for(;(n=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(S.decodeKey(n),N())}}else{let t=0;for(;(n=N())!=c;){if(t++>=m)throw new Error(`Map size exceeds ${m}`);e.set(n,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,S.copyBuffers?Uint8Array.prototype.slice.call(n,a,a+=r):n.subarray(a,a+=r);case 3:if(b>=a)return d.slice(a-w,(a+=e)-w);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(S.mapsAsObjects){let t={};if(S.keyMap)for(let r=0;r<e;r++)t[v(S.decodeKey(N()))]=N();else for(let r=0;r<e;r++)t[v(N())]=N();return t}{y&&(S.mapsAsObjects=!0,y=!1);let t=new Map;if(S.keyMap)for(let r=0;r<e;r++)t.set(S.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 s={};if(S.keyMap)for(let t=2;t<e;t++){s[v(S.decodeKey(r[t-2]))]=N()}else for(let t=2;t<e;t++){s[v(r[t-2])]=N()}return s}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(S.getShared&&(Q(),t=l[8191&e],t))return t.read||(t.read=L(t)),t.read()}}let s=A[e];if(s)return s.handlesRead?s(N):s(N());{let t=N();for(let r=0;r<I.length;r++){let s=I[r](e,t);if(void 0!==s)return s}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=n[a++];if(e&=31,e>23)switch(e){case 24:e=n[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 "+n[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=S.keyMap?new Function("r","return {"+r.map((e=>S.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(S.keyMap)for(let t=0;t<e;t++)r[v(S.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&&s)return s.decode(n.subarray(a,a+=e));const r=a+e,i=[];for(t="";a<r;){const e=n[a++];if(128&e)if(192==(224&e)){const t=63&n[a++];i.push((31&e)<<6|t)}else if(224==(240&e)){const t=63&n[a++],r=63&n[a++];i.push((31&e)<<12|t<<6|r)}else if(240==(248&e)){let t=(7&e)<<18|(63&n[a++])<<12|(63&n[a++])<<6|63&n[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 s=0;s<e;s++){const e=n[a++];if((128&e)>0)return void(a=t);r[s]=e}return U.apply(String,r)}function P(e){if(e<4){if(e<2){if(0===e)return"";{let e=n[a++];return(128&e)>1?void(a-=1):U(e)}}{let t=n[a++],r=n[a++];if((128&t)>0||(128&r)>0)return void(a-=2);if(e<3)return U(t,r);let s=n[a++];return(128&s)>0?void(a-=3):U(t,r,s)}}{let t=n[a++],r=n[a++],s=n[a++],i=n[a++];if((128&t)>0||(128&r)>0||(128&s)>0||(128&i)>0)return void(a-=4);if(e<6){if(4===e)return U(t,r,s,i);{let e=n[a++];return(128&e)>0?void(a-=5):U(t,r,s,i,e)}}if(e<8){let o=n[a++],c=n[a++];if((128&o)>0||(128&c)>0)return void(a-=6);if(e<7)return U(t,r,s,i,o,c);let l=n[a++];return(128&l)>0?void(a-=7):U(t,r,s,i,o,c,l)}{let o=n[a++],c=n[a++],l=n[a++],d=n[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,s,i,o,c,l,d);{let e=n[a++];return(128&e)>0?void(a-=9):U(t,r,s,i,o,c,l,d,e)}}if(e<12){let u=n[a++],h=n[a++];if((128&u)>0||(128&h)>0)return void(a-=10);if(e<11)return U(t,r,s,i,o,c,l,d,u,h);let f=n[a++];return(128&f)>0?void(a-=11):U(t,r,s,i,o,c,l,d,u,h,f)}{let u=n[a++],h=n[a++],f=n[a++],p=n[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,s,i,o,c,l,d,u,h,f,p);{let e=n[a++];return(128&e)>0?void(a-=13):U(t,r,s,i,o,c,l,d,u,h,f,p,e)}}{let y=n[a++],g=n[a++];if((128&y)>0||(128&g)>0)return void(a-=14);if(e<15)return U(t,r,s,i,o,c,l,d,u,h,f,p,y,g);let m=n[a++];return(128&m)>0?void(a-=15):U(t,r,s,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,s=e.byteLength;r<s;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 s={};for(let n=2;n<t;n++){s[v(r[n-2])]=e[n]}return s},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 W=e=>{if(132!=n[a++]){let e=new Error("Packed values structure must be followed by a 4 element array");throw n.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 z(e,t){return"string"==typeof e?e+t:e instanceof Array?e.concat(t):Object.assign({},e,t)}function q(){if(!f){if(!S.getShared)throw new Error("No packed values available");Q()}return f}W.handlesRead=!0,A[51]=W,A[6]=e=>{if(!f){if(!S.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++,s=a;t=n[a]>>5==4?[]:{};let i={target:t};h.set(r,i);let o=e();return i.used?(Object.getPrototypeOf(t)!==Object.getPrototypeOf(o)&&(a=s,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=>(S.mapsAsObjects&&(S.mapsAsObjects=!1,y=!0),e())).handlesRead=!0;I.push(((e,t)=>e>=225&&e<=255?z(q().prefixes[e-224],t):e>=28704&&e<=32767?z(q().prefixes[e-28672],t):e>=1879052288&&e<=2147483647?z(q().prefixes[e-1879048192],t):e>=216&&e<=223?z(t,q().suffixes[e-216]):e>=27647&&e<=28671?z(t,q().suffixes[e-27639]):e>=1811940352&&e<=1879048191?z(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,s="get"+e.name.slice(0,-5);"function"==typeof e?r=e.BYTES_PER_ELEMENT:e=null;for(let n=0;n<2;n++){if(!n&&1==r)continue;let i=2==r?1:4==r?2:8==r?3:0;A[n?t:t-4]=1==r||n==G?s=>{if(!e)throw new Error("Could not find typed array for code "+t);return S.copyBuffers||1!==r&&(2!==r||1&s.byteOffset)&&(4!==r||3&s.byteOffset)&&(8!==r||7&s.byteOffset)?new e(Uint8Array.prototype.slice.call(s,0).buffer):new e(s.buffer,s.byteOffset,s.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[s];for(let e=0;e<o;e++)c[e]=l.call(a,e<<i,n);return c}}}function X(){let e=31&n[a++];if(e>23)switch(e){case 24:e=n[a++];break;case 25:e=p.getUint16(a),a+=2;break;case 26:e=p.getUint32(a),a+=4}return e}function Q(){if(S.getShared){let e=Z((()=>(n=null,S.getShared())))||{},t=e.structures||[];S.sharedVersion=e.version,f=S.sharedValues=e.packedValues,!0===l?S.structures=l=t:l.splice.apply(l,[0,t.length].concat(t))}}function Z(e){let t=i,r=a,s=_,o=w,c=b,f=d,y=E,g=h,m=u,A=new Uint8Array(n.slice(0,i)),I=l,F=S,T=C,R=e();return i=t,a=r,_=s,w=o,b=c,d=f,E=y,h=g,u=m,n=A,C=T,l=I,S=F,p=new DataView(n.buffer,n.byteOffset,n.byteLength),R}function ee(){n=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 se=re.decode;re.decodeMultiple;let ne,ie,ae;try{ne=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 Se(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 we{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,s=e.length;r<s;r++)Fe(e[r],t);else{let s=!t.encoder.useRecords;for(var r in e)e.hasOwnProperty(r)&&(s&&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,s=e.byteOffset||0,n=e.buffer||e;t(ce?oe.from(n,s,r):new Uint8Array(n,s,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,we],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||[],s=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(s){pe.setUint32(ge,3655335424),ge+=3;let r=s.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,s,n,i;super(e),this.offset=0,e=e||{};let a=de.prototype.utf8Write?function(e,t,r){return fe.utf8Write(e,t,r)}:!(!ne||!ne.encodeInto)&&function(e,t){return ne.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 s,n=r.transitions;for(let r=0,i=e.length;r<i;r++){void 0===n[_e]&&(n[_e]=t);let i=e[r];s=n[i],s||(s=n[i]=Object.create(null)),n=s}n[_e]=1048576|t}}d||(r.nextId=e)}if(s&&(s=!1),n=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&&S(ge),o.offset=ge;let e=function(e,t){let r,s=2*t.length,n=e.length-s;t.sort(((e,t)=>e.offset>t.offset?1:-1));for(let r=0;r<t.length;r++){let s=t[r];s.id=r;for(let t of s.references)e[t++]=r>>8,e[t]=255&r}for(;r=t.pop();){let t=r.offset;e.copyWithin(t+s,t,n),s-=2;let i=t+s;e[i++]=216,e[i++]=28,n=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(s&&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,n]of u)n.count>t&&(f[e]=r++,p.push(e),s=!0);for(;this.saveShared&&!1===this.updateSharedData(););u=null});const E=r=>{ge>ye&&(fe=S(ge));var s,n=typeof r;if("string"===n){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 n,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=S(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)}n=i<32?1:i<256?2:i<65536?3:5;let o=3*i;if(ge+o>ye&&(fe=S(ge+o)),i<64||!a){let e,t,a,o=ge+n;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);s=o-ge-n}else s=a(r,ge+n,o);s<24?fe[ge++]=96|s:s<256?(n<2&&fe.copyWithin(ge+2,ge+1,ge+1+s),fe[ge++]=120,fe[ge++]=s):s<65536?(n<3&&fe.copyWithin(ge+3,ge+2,ge+2+s),fe[ge++]=121,fe[ge++]=s>>8,fe[ge++]=255&s):(n<5&&fe.copyWithin(ge+5,ge+3,ge+3+s),fe[ge++]=122,pe.setUint32(ge,s),ge+=4),ge+=s}else if("number"===n)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"===n)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){(s=r.length)<24?fe[ge++]=128|s:be(s);for(let e=0;e<s;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),(s=r.size)<24?fe[ge++]=160|s:s<256?(fe[ge++]=184,fe[ge++]=s):s<65536?(fe[ge++]=185,fe[ge++]=s>>8,fe[ge++]=255&s):(fe[ge++]=186,pe.setUint32(ge,s),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],s=t.tag;return null==s&&(s=t.getTag&&t.getTag.call(this,r)),s<24?fe[ge++]=192|s:s<256?(fe[ge++]=216,fe[ge++]=s):s<65536?(fe[ge++]=217,fe[ge++]=s>>8,fe[ge++]=255&s):s>-1&&(fe[ge++]=218,pe.setUint32(ge,s),ge+=4),void t.encode.call(this,r,E,S)}}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"===n)fe[ge++]=r?245:244;else if("bigint"===n){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()),S)}fe[ge++]=251,pe.setFloat64(ge,Number(r))}ge+=8}else{if("undefined"!==n)throw new Error("Unknown type: "+n);fe[ge++]=247}},_=!1===this.useRecords?this.variableMapSize?e=>{let t=Object.keys(e),r=Object.values(e),s=t.length;if(s<24?fe[ge++]=160|s:s<256?(fe[ge++]=184,fe[ge++]=s):s<65536?(fe[ge++]=185,fe[ge++]=s>>8,fe[ge++]=255&s):(fe[ge++]=186,pe.setUint32(ge,s),ge+=4),o.keyMap)for(let e=0;e<s;e++)E(o.encodeKey(t[e])),E(r[e]);else for(let e=0;e<s;e++)E(t[e]),E(r[e])}:e=>{fe[ge++]=185;let r=ge-t;ge+=2;let s=0;if(o.keyMap)for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(o.encodeKey(t)),E(e[t]),s++);else for(let t in e)("function"!=typeof e.hasOwnProperty||e.hasOwnProperty(t))&&(E(t),E(e[t]),s++);fe[r+++t]=s>>8,fe[r+t]=255&s}:(e,t)=>{let r,i,a,o=n.transitions||(n.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=n.nextId++,u||(u=0,n.nextId=1),u>=256&&(n.nextId=(u=l)+1)):u=i,n[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=n.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,s=!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])},S=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 s=new le(r);return pe=new DataView(s.buffer,0,r),fe.copy?fe.copy(s,0,t,e):s.set(fe.slice(t,e)),ge-=t,t=0,ye=s.length-10,fe=s};let w=100,b=1e3;function*A(e,r,s){let n=e.constructor;if(n===Object){let t=!1!==o.useRecords;t?_(e,!0):Se(Object.keys(e).length,160);for(let s in e){let n=e[s];t||E(s),n&&"object"==typeof n?r[s]?yield*A(n,r[s]):yield*I(n,r,s):E(n)}}else if(n===Array){let s=e.length;be(s);for(let n=0;n<s;n++){let s=e[n];s&&("object"==typeof s||ge-t>w)?r.element?yield*A(s,r.element):yield*I(s,r,"element"):E(s)}}else if(e[Symbol.iterator]&&!e.buffer){fe[ge++]=159;for(let s of e)s&&("object"==typeof s||ge-t>w)?r.element?yield*A(s,r.element):yield*I(s,r,"element"):E(s);fe[ge++]=255}else Ie(e)?(Se(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);s&&ge>t?yield fe.subarray(t,ge):ge-t>w&&(yield fe.subarray(t,ge),F())}function*I(e,r,s){let n=ge-t;try{E(e),ge-t>w&&(yield fe.subarray(t,ge),F())}catch(i){if(!i.iteratorNotHandled)throw i;r[s]={},ge=t+n,yield*A.call(this,e,r[s])}}function F(){w=b,o.encode(null,Pe)}function C(e,t,r){return w=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 we(t,this.sharedValues,this.sharedVersion),s=this.saveShared(r,(t=>(t&&t.version||0)==e));return!1===s?(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)),s}}({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=new Set(["dome","intouchapp"]);var xe,Ke,Ve,He,We,ze,qe;!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"}(xe||(xe={})),function(e){e.INIT_MESSAGE_CHANNEL="INIT_MESSAGE_CHANNEL"}(Ke||(Ke={})),function(e){e.CONNECT="CONNECT"}(Ve||(Ve={})),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"}(He||(He={})),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"}(ze||(ze={}));class Ge{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.rE}`),this.detectHost(),this.setupDeepLinkInterception()}detectHost(){void 0!==window.AndroidBridge?this.runtimeHost="android":void 0!==window.webkit?this.runtimeHost="ios":this.runtimeHost="webapp",console.debug(`Detected host: ${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||!je.has(t))&&(this.sendMessage(ze.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 s=t??this.parentCapabilities??r.capabilities;t&&(this.parentCapabilities=t),s?r.capabilities=s:delete r.capabilities,this.parentHostDetails=r,this.parentCapabilities=s??null,s?console.info("Host capabilities detected",{host_type:r.type,capabilities:s}):console.info("Host capabilities not found",{hostType:r.type})}getHost(){return this.parentHostDetails??{type:this.runtimeHost}}sendMessage(e,t,r){const s={type:e,data:t??null};if("android"!==this.runtimeHost){if(this.port2)return this.port2.postMessage(s),void console.debug("Sent message via message channel:",s);switch(this.runtimeHost){case"ios":window?.webkit?.messageHandlers?window.webkit?.messageHandlers.appHandler.postMessage(JSON.stringify(s)):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.")}console.debug(`Sent message to ${this.runtimeHost}:`,s)}else{if(r){const e=this.toUint8Array(r),t=s.data&&"object"==typeof s.data?{...s.data,v:"1.0",data:e}:{v:"1.0",data:e},n=this.encodeCborMessage({...s,v:"1.0",data:t});this.port2?this.port2.postMessage(n):window.AndroidBridge?.sendMessage(n)}else{const e=JSON.stringify(s);this.port2?this.port2.postMessage(e):window.AndroidBridge?.sendMessage(e)}console.debug(`Sent message to ${this.runtimeHost}:`,s)}}sendAppInit(){this.isAppReady||(this.isAppReady=!0,this.sendMessage(xe.INIT,{sdk:{ver:r.rE}}))}safeInvoke(e,t,r){const s=t?.[e];"function"==typeof s?s(r):console.warn(`Handler for '${String(e)}' is not defined.`)}setupParentConnection(){return new Promise(((e,t)=>{switch(this.runtimeHost){case"android":window.receiveFromAndroid=e=>{console.debug("Message received from Android:",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:s}=t||{};r&&this.handleMessage(r,s)};let s=!1;const n=()=>{s||(s=!0,"android"===this.runtimeHost&&this.sendMessage(xe.CONNECTION_SUCCESS),console.debug("Message channel connect resolved; proceeding with INIT"),e())};this.setupMessageChannelListener(n),window.AndroidBridge?.sendMessage(JSON.stringify({type:Ke.INIT_MESSAGE_CHANNEL,data:{sdk:{ver:r.rE}}})),console.debug("Sent INIT_MESSAGE_CHANNEL to Android bridge");break;case"ios":window.receiveFromIOS=e=>{console.debug("Message received from iOS:",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:Ke.INIT_MESSAGE_CHANNEL,data:{sdk:{ver:r.rE}}},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 s=r.data;if("string"==typeof s)try{s=JSON.parse(s)}catch{}(s?.type??s)===Ve.CONNECT&&(console.debug("Message channel CONNECT received",s),r.ports&&0!==r.ports.length?(this.port2=r.ports[0],this.port2.onmessage=e=>this.handlePortMessage(e),console.debug("Message channel port connected"),window.removeEventListener("message",t),e?.()):console.warn("Message channel CONNECT missing ports"))};window.addEventListener("message",t)}notifyConnectionSuccess(){this.sendMessage(xe.CONNECTION_SUCCESS)}handlePortMessage(e){console.debug("received message event from port",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:s}=t||{};r&&(console.debug(`Handling port message event. type: ${r}, data: ${s}`),this.handleMessage(r,s))}handleMessage(e,t){throw new Error("Subclasses must implement handleMessage.")}decodeCborBuffer(e){let t;try{t=se(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,s=r.data,n=this.normalizeBinaryPayload(s);if(n)t.data={...r,data:n};else if("string"==typeof s)try{t.data={...r,data:JSON.parse(s)}}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}copyBufferView(e,t,r){return e instanceof ArrayBuffer&&0===t&&r===e.byteLength?e:new Uint8Array(e,t,r).slice().buffer}}function $e(e){const{prefix:t="",given:r="",middle:s="",family:n="",suffix:i=""}=e||{};return[t,r,s,n,i].filter((e=>e)).join(" ").trim()}class Je extends Ge{constructor(){super(),this.handler=null,this.pendingRequests=new Map,this.pendingInitAck=null}static init(e){return console.debug("init called",e&&"with handler"),Je.initialized?(console.warn("ViewerSdk is already initialized. Skipping initialization."),Je.instance):(Je.instance||(Je.instance=new Je,Je.instance.setupParentConnection().then((()=>{try{Je.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&&Je.instance.setHandler(e),Je.initialized=!0,Je.instance)}setHandler(e){this.handler=e,this.pendingInitAck&&(console.debug("Processing pending INIT_ACK message after handler is set."),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(){console.debug("initializing viewer sdk"),this.sendAppInit()}requestInitialData(){this.sendMessage(xe.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(xe.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:s}=e,n=this.pendingRequests.get(t),i=this.pendingRequests.get(t+"_reject");n&&("error"===r?i?.({status:r,message:s}):n({status:r,message:s}),this.pendingRequests.delete(t),this.pendingRequests.delete(t+"_reject"))}setDirty(e){this.sendMessage(xe.SET_DIRTY,e)}sendClose(e,t){this.sendMessage(xe.SEND_CLOSE,{doc:e,isDataDirty:t})}sendException(e){this.sendMessage(xe.SEND_EXCEPTION,e)}handleMessage(e,t){if(console.debug("handleMessage called for:",e,"with data:",t),e===He.INIT_ACK&&this.updateParentContext(t?.host,t?.capabilities),this.handler)switch(e){case He.INIT_ACK:this.safeInvoke("onInitialData",this.handler,t);break;case He.DATA_CHANGE:this.safeInvoke("onDataChange",this.handler,t);break;case He.REQUEST_CLOSE:this.safeInvoke("onCloseRequest",this.handler);break;case He.REQUEST_SAVE:this.safeInvoke("onSaveRequest",this.handler);break;case He.SAVE_SUCCESS:case He.SAVE_ERROR:this.handleOnSave(t);break;default:console.warn(`No handler found for message type: ${e}`)}else e===He.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)}}Je.initialized=!1;class Ye{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 s=this.base64UrlDecode(e);if(128!==s[0])throw new Error("Invalid version");s.slice(1,9);const n=s.slice(9,25),i=s.slice(25,-32),a=s.slice(-32),o=await this.deriveKey(t,r),{hmacKey:c,aesKey:l}=await this.splitKey(o),d=s.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:n},l,i);return(new TextDecoder).decode(u)}catch(e){throw console.log("Error in decrypt:",e),e}}async deriveKey(e,t,r=1e4){const s=new TextEncoder,n=await this.subtleCrypto.importKey("raw",s.encode(e),"PBKDF2",!1,["deriveKey"]);return this.subtleCrypto.deriveKey({name:"PBKDF2",hash:"SHA-256",salt:s.encode(t),iterations:r},n,{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"}(qe||(qe={}));const Xe=qe;var Qe,Ze;!function(e){e.TEXT="text",e.JSON="json",e.BINARY="binary"}(Qe||(Qe={})),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"}(Ze||(Ze={}));const et="1.1.0";function tt(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,s=new Uint8Array(r.length);for(let e=0;e<r.length;e++)s[e]=r[e]^t+17*e&255;return s}(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 rt{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(rt.DB_VERSION,e)}))),this.openPromise):null}openWithVersion(e,t){let r="ensure";const s=indexedDB.open(this.cardIuid,e);s.onupgradeneeded=e=>{r=0===(e.oldVersion||0)?"create":"ensure",this.configureStores(s.result)},s.onsuccess=()=>{const e=s.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)))},s.onerror=()=>t(null)}configureStores(e){e.objectStoreNames.contains(rt.DATA_STORE)||e.createObjectStore(rt.DATA_STORE),e.objectStoreNames.contains(rt.NAME_LOOKUP_STORE)||e.createObjectStore(rt.NAME_LOOKUP_STORE),e.objectStoreNames.contains(rt.INFO_STORE)||e.createObjectStore(rt.INFO_STORE),e.objectStoreNames.contains(rt.FOLDER_CACHE_STORE)||e.createObjectStore(rt.FOLDER_CACHE_STORE)}hasRequiredStores(e){const t=e.objectStoreNames;return t.contains(rt.DATA_STORE)&&t.contains(rt.NAME_LOOKUP_STORE)&&t.contains(rt.INFO_STORE)&&t.contains(rt.FOLDER_CACHE_STORE)}static nowMicros(){return Math.trunc(1e3*Date.now())}updateStoresMetadata(e,t){return Promise.all([this.ensureStoreVersion(e,rt.DATA_STORE),this.ensureStoreVersion(e,rt.NAME_LOOKUP_STORE),this.ensureStoreVersion(e,rt.FOLDER_CACHE_STORE),this.updateCardInfo(e,t)]).then((()=>{}))}ensureStoreVersion(e,t){return e.objectStoreNames.contains(t)?new Promise((r=>{try{const s=e.transaction(t,"readwrite"),n=s.objectStore(t),i=()=>r();s.oncomplete=i,s.onerror=i,s.onabort=i,n.put(et,rt.STORE_VERSION_KEY)}catch{r()}})):Promise.resolve()}async updateCardInfo(e,t){if(!e.objectStoreNames.contains(rt.INFO_STORE))return;const r=await this.readInfoValue(e,"container_iuid"),s=t?await this.readInfoValue(e,"ts_c"):void 0,n=this.containerIuid??r??null,i=t&&s?s:rt.nowMicros();await Promise.all([this.writeInfoValue(e,"container_iuid",n),this.writeInfoValue(e,"ts_c",i)]).catch((()=>{}))}readInfoValue(e,t){return new Promise((r=>{try{const s=e.transaction(rt.INFO_STORE,"readonly"),n=s.objectStore(rt.INFO_STORE).get(t);n.onsuccess=()=>r(n.result),n.onerror=()=>r(void 0)}catch{r(void 0)}}))}writeInfoValue(e,t,r){return new Promise((s=>{try{const n=e.transaction(rt.INFO_STORE,"readwrite"),i=n.objectStore(rt.INFO_STORE),a=()=>s();n.oncomplete=a,n.onerror=a,n.onabort=a,i.put(r,t)}catch{s()}}))}keyFor(e){return e}static normalizeFolderName(e){if("string"!=typeof e)return rt.DEFAULT_FOLDER_KEY;let t=e.trim();return t?(t=t.replace(/^\/+/,""),t?(t.endsWith("/")||(t+="/"),t||rt.DEFAULT_FOLDER_KEY):rt.DEFAULT_FOLDER_KEY):rt.DEFAULT_FOLDER_KEY}folderListingKey(e){return rt.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((s=>{const n=r.transaction(rt.DATA_STORE,"readwrite");n.objectStore(rt.DATA_STORE).put(t,e).onsuccess=()=>s(),n.oncomplete=()=>s(),n.onerror=()=>s(),n.onabort=()=>s()}))}async get(e){const t=await this.openDb();if(t)return new Promise((r=>{const s=t.transaction(rt.DATA_STORE,"readonly").objectStore(rt.DATA_STORE).get(e);s.onsuccess=()=>r(s.result),s.onerror=()=>r(void 0)}))}async delete(e){const t=await this.openDb();t&&await new Promise((r=>{const s=t.transaction(rt.DATA_STORE,"readwrite");s.objectStore(rt.DATA_STORE).delete(e).onsuccess=()=>r(),s.oncomplete=()=>r(),s.onerror=()=>r(),s.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=rt.encodeText(e),s=await t.subtle.digest("SHA-256",r);return rt.bufferToBase64(s)}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=rt.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const s=await rt.hashName(t);return new Promise((e=>{const t=r.transaction(rt.NAME_LOOKUP_STORE,"readonly").objectStore(rt.NAME_LOOKUP_STORE).get(s);t.onsuccess=()=>e(t.result),t.onerror=()=>e(void 0)}))}async upsertNameLookup(e,t){const r=rt.normalizeName(e);if(!r)return;const s=await this.openDb();if(!s)return;const n=await rt.hashName(r);await new Promise((e=>{const r=s.transaction(rt.NAME_LOOKUP_STORE,"readwrite"),i=r.objectStore(rt.NAME_LOOKUP_STORE);i.put(t,n);i.openCursor().onsuccess=e=>{const r=e.target.result;r&&(r.key!==n&&r.value===t&&r.delete(),r.continue())},r.oncomplete=()=>e(),r.onerror=()=>e(),r.onabort=()=>e()}))}async deleteNameLookupByName(e){const t=rt.normalizeName(e);if(!t)return;const r=await this.openDb();if(!r)return;const s=await rt.hashName(t);await new Promise((e=>{const t=r.transaction(rt.NAME_LOOKUP_STORE,"readwrite");t.objectStore(rt.NAME_LOOKUP_STORE).delete(s),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 s=t.transaction(rt.NAME_LOOKUP_STORE,"readwrite");s.objectStore(rt.NAME_LOOKUP_STORE).openCursor().onsuccess=t=>{const r=t.target.result;r&&(r.value===e&&r.delete(),r.continue())},s.oncomplete=()=>r(),s.onerror=()=>r(),s.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=rt.normalizeName(e.name);if(r&&await this.upsertNameLookup(r,e.iuid),void 0===t)return void await this.delete(this.keyFor(`${e.iuid}_data`));rt.estimateSize(t)<=rt.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=rt.normalizeName(e);if(!t)return null;const r=await this.getIuidForName(t);if(!r)return null;const s=await this.get(this.keyFor(`${r}_object`));if(!s)return null;return{iuid:r,object:s,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 s=this.folderListingKey(e??t.folder_name),n="object"==typeof t.data&&null!==t.data?t.data:Array.isArray(t.documents)?t.documents:{},i=Array.isArray(n)?{results:[...n]}:{...n},a={folder_name:s,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(rt.FOLDER_CACHE_STORE,"readwrite");t.objectStore(rt.FOLDER_CACHE_STORE).put(a,s).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 s=t.transaction(rt.FOLDER_CACHE_STORE,"readonly").objectStore(rt.FOLDER_CACHE_STORE).get(r);s.onsuccess=()=>e(s.result),s.onerror=()=>e(null)}))}}rt.DB_VERSION=3,rt.DATA_STORE="cardfs",rt.NAME_LOOKUP_STORE="cardfs_name_iuid_lookup",rt.INFO_STORE="info",rt.FOLDER_CACHE_STORE="folder_cache",rt.STORE_VERSION_KEY="ver",rt.DEFAULT_FOLDER_KEY="/",rt.MAX_DATA_BYTES=5242880;class st extends Ge{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(rt.estimateSize(e)>rt.MAX_DATA_BYTES){const e=t?` for ${t}`:"";return console.warn(`cardFS.read payload data exceeded ${rt.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){if(null==e)return e;const r="string"==typeof t?t.toLowerCase():"";if(!r)return e;const s=r.includes("application/json")||r.endsWith("+json"),n=r.startsWith("text/"),i=e instanceof ArrayBuffer||ArrayBuffer.isView(e),a=()=>{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(i)try{return JSON.parse(a())}catch{return a()}if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}if(n){if(i)return a();if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e}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===Qe.TEXT?this.encodeTextPayload(e):t===Qe.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 rt(e,this.containerIuid))}return this.cardFsCache}supportsParentCardFs(){const e=this.parentCapabilities?.card_fs;return!!e?.ver&&e.ver===et}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(st.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 s=this.pendingAcks.get(r);if(s.ackType===e)return clearTimeout(s.timeout),this.pendingAcks.delete(r),void s.resolve(t)}if(r||!this.resolvePendingAckByType(e,t)){if(!this.handler)throw new Error("Message handler not found!");switch(e){case We.INIT_ACK:console.debug("CardSdk: INIT_ACK received"),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 rt(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=>{console.debug("CardSdk: INIT_ACK: decrypted data ",e);const r=JSON.parse(e),s=r?.container?.iuid;s&&(this.containerIuid=s,this.shouldUseCardFsFallback()&&this.dataStore?.iuid&&(this.cardFsCache=new rt(this.dataStore.iuid,this.containerIuid)));const n="string"==typeof r?.api_token?r.api_token.trim():"";n?(this.accessToken=n,console.debug("CardSdk: Stored API token from INIT_ACK payload")):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 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,...s}=t||{};return void this.handleFsReadDataMessage(e,s)}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 Ye,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,s)=>this.cardFSWrite(e,t,r,s),writeById:(e,t,r,s)=>this.cardFSWriteById(e,t,r,s),delete:(e,t)=>this.cardFSDelete(e,t),deleteById:(e,t)=>this.cardFSDeleteById(e,t),list:(e,t)=>this.cardFSList(e,t)},console.debug("CardSdk::constructor: done")}static async init(e,t,r){try{return console.debug("CardSdk::init"),st.instance?st.instance:(st.instance=new st,st.instance.setupParentConnection().then((()=>{st.instance.initializeCardSdk(e)})).catch((e=>{console.error(e)})),t&&st.instance.setHandler(t),st.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):st.DEFAULT_ROLE_PERMISSIONS.includes(e)}canRead(){return this.hasPerm(qe.READ)}canWrite(){return this.hasPerm(qe.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(ze.AF1_DATA_TOKEN,{sdk:{ver:r.rE}},We.AF1_DATA_TOKEN_ACK),{messageId:s,...n}=t||{},{cie:i,ck:a,dev_token:o}=n;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,s){if(!(e&&t&&r&&s))throw new Error("Invalid AF1 data fetch parameters");const n=new URL(`https://dome.so/api/v1/cards/e/${encodeURIComponent(e)}/data_af1/`);n.searchParams.set("dt",r),n.searchParams.set("rt",s),n.searchParams.set("ck",t);const i=await fetch(n.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(console.debug(t,"enter"),!e)throw new Error("Invalid secret");const r=window.location.href;console.debug(t,"url:",r);const s=new URL(r),n=s.searchParams.get("rt");if(!n)throw new Error("Missing request token");let i=this.getCardIuidEnc(s),a=window.IT_DATA_AF1;if(!a){console.debug(t,"IT_DATA_AF1 missing. Requesting token via parent");const{dataAf1:e,cie:r}=await this.requestAf1DataFromParent(n);a=e,i=r||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);console.debug(t,"ss:",o);const c=await this.cryptoA01.decrypt(a,e,o);try{const e=JSON.parse(c);if(console.debug("CardSdk: dataFromServer:",e),!e.ite)throw new Error("Invalid data");this.dataStore={denc:e.d,kw2:e.kw2},st.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.rE}},s=this.getWebappDetails();s&&(t.wa=s),this.sendMessage(ze.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,s=15e3,n,i){const a=crypto.randomUUID();if(n)try{n(a)}catch(e){return Promise.reject(e)}return new Promise(((n,o)=>{const c=setTimeout((()=>{this.pendingAcks.delete(a);const e=new Error(`${r} not received in time`);this.isCardFsAckType(r)&&(e.code=Ze.TIMEOUT),o(e)}),s);this.pendingAcks.set(a,{resolve:n,reject:o,timeout:c,ackType:r}),this.sendMessage(e,{...t,messageId:a},i)}))}resolvePendingAckByType(e,t){for(const[r,s]of this.pendingAcks.entries())if(s.ackType===e)return clearTimeout(s.timeout),this.pendingAcks.delete(r),s.resolve(t),!0;return!1}cardFSRead(e,t,r=!0){const s={name:e},n=this.assertValidReadHandler(t);this.cardFSReadInternal(s,n,r,"read")}cardFSReadById(e,t,r=!0){const s={iuid:e},n=this.assertValidReadHandler(t);this.cardFSReadInternal(s,n,r,"readById")}cardFSReadInternal(e,t,r,s){if(this.shouldUseCardFsFallback())return console.debug(`cardFS.${s} using fallback implementation for`,e),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))}));console.debug(`cardFS.${s} delegating to parent for`,e);let n=null;const i=e.name?`"${e.name}"`:e.iuid?`iuid ${e.iuid}`:"document";this.sendMessageWithAck(ze.CFS_READ_FILE,this.buildCardFsMessagePayload(e,{allow_stale:r}),We.CFS_READ_FILE_ACK,st.CARD_FS_ACK_TIMEOUT_MS,(e=>{n=e;const a={name:i,handler:t,allowStale:r,timeoutMessage:`cardFS.${s} timed out for ${i}`};this.fsReadRequests.set(e,a)})).catch((e=>{const r=e instanceof Error?e:new Error(String(e));n?this.failFsReadRequest(n,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=Qe.JSON,s){const n={name:e};return"android"===this.runtimeHost&&r===Qe.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then((e=>this.cardFSWriteInternal(n,e,r,s,"write"))):this.cardFSWriteInternal(n,t,r,s,"write")}cardFSWriteById(e,t,r=Qe.JSON,s){const n={iuid:e};return"android"===this.runtimeHost&&r===Qe.BINARY&&"undefined"!=typeof Blob&&t instanceof Blob?t.arrayBuffer().then((e=>this.cardFSWriteInternal(n,e,r,s,"writeById"))):this.cardFSWriteInternal(n,t,r,s,"writeById")}cardFSWriteInternal(e,t,r,s,n){return this.shouldUseCardFsFallback()?(console.debug(`cardFS.${n} using fallback implementation for`,e),this.cardFSWriteFallback(e,t,r).catch((e=>{throw this.toCardFsErrorPayload(e)}))):(console.debug(`cardFS.${n} delegating to parent for`,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===Qe.BINARY&&"android"===this.runtimeHost&&u;let f=l;r!==Qe.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")),console.debug("cardFS.write sending",{name:e.name,iuid:e.iuid,file_type:r,file_size:d,data:f}),this.sendMessageWithAck(ze.CFS_WRITE_FILE,this.buildCardFsMessagePayload(e,{data:h?null:f,file_type:r,file_size:d}),We.CFS_WRITE_FILE_ACK,st.CARD_FS_ACK_TIMEOUT_MS,(e=>{o=e;const t={name:c,onUpdate:s,resolve:i,reject:a,timeoutMessage:`cardFS.${n} 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()?(console.debug(`cardFS.${r} using fallback implementation for`,e),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)}))):(console.debug(`cardFS.${r} delegating to parent for`,e),new Promise(((r,s)=>{this.sendMessageWithAck(ze.CFS_DELETE_FILE,this.buildCardFsMessagePayload(e),We.CFS_DELETE_FILE_ACK,st.CARD_FS_ACK_TIMEOUT_MS).then((e=>{const{messageId:s,...n}=e||{};t?.(n),r(n)})).catch((e=>{s(this.toCardFsErrorPayload(e))}))})))}cardFSList(e,t){const r=this.assertValidListHandler(t),s=this.formatFolderPath(e);if(this.shouldUseCardFsFallback())return console.debug("cardFS.list using fallback implementation"),void this.cardFSListFallbackStream(s,r);console.debug("cardFS.list delegating to parent");const n=s?{name:s}:{},i=crypto.randomUUID(),a={name:s??"folder listing",handler:r,timeoutMessage:"cardFS.list timed out"};this.fsListRequests.set(i,a),this.resetFsListProgressTimeout(i),this.sendMessage(ze.CFS_LIST_FILES,{...n,messageId:i})}async cardFSListFallbackStream(e,t){const r=this.ensureCardFsCache();let s=!1;if(r)try{const n=await r.getFolderListing(e);if(n){const e=Array.isArray(n.data?.results)?n.data.results:[];t.next(this.normalizeListResult({documents:e,folder_name:n.folder_name,folder_iuid:n.folder_iuid??void 0,last_index:n.last_index??null,last_page:n.last_page??null,from_cache:!0,is_dirty:!0,is_complete:!1})),s=!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){s?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:Ze.TIMEOUT,message:t.timeoutMessage})}),st.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:Ze.TIMEOUT,message:t.timeoutMessage})}),st.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:Ze.TIMEOUT,message:t.timeoutMessage})}),st.FS_RESPONSE_TIMEOUT_MS))}handleFsReadDataMessage(e,t){const r=this.fsReadRequests.get(e);if(!r)return;let s=t?.data;"string"!=typeof s||"base64"!==t?.encoding&&!this.isBinaryReadPayload(t)||(s=this.decodeBase64BinaryData(s));const n=this.sanitizeReadData(s,r.name),i=this.normalizeReadData(n.value,t?.object?.mimetype),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};console.debug("cardFS.read received",o),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)}),st.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)}),st.FS_READ_RETENTION_MS),!0)}if(e===We.CFS_WRITE_FILE_ACK){const e=this.fsWriteRequests.get(r);if(!e)return!1;const{messageId:s,...n}=t||{};if("function"==typeof e.onUpdate)try{e.onUpdate(n)}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.rE}};this.sendMessage(ze.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)%st.MAX_CONSOLE_LOG_ENTRIES,this.consoleLogSize=Math.min(this.consoleLogSize+1,st.MAX_CONSOLE_LOG_ENTRIES)}clearConsoleLogs(){this.consoleLogBuffer.fill(null),this.consoleLogWriteIndex=0,this.consoleLogSize=0}getConsoleLogs(){if(0===this.consoleLogSize)return[];if(this.consoleLogSize<st.MAX_CONSOLE_LOG_ENTRIES)return this.consoleLogBuffer.slice(0,this.consoleLogSize).filter((e=>null!==e));const e=[];for(let t=0;t<st.MAX_CONSOLE_LOG_ENTRIES;t+=1){const r=(this.consoleLogWriteIndex+t)%st.MAX_CONSOLE_LOG_ENTRIES,s=this.consoleLogBuffer[r];s&&e.push(s)}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>st.MAX_CONSOLE_ARG_CHARS?{type:"truncated",preview:e.slice(0,st.MAX_CONSOLE_ARG_CHARS),original_length:e.length}:e;const t=JSON.stringify(e);if("string"==typeof t&&t.length>st.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,s)=>{if("string"==typeof e)return(e=>e.length<=st.MAX_CONSOLE_STRING_PREVIEW_CHARS?e:{type:"truncated",preview:e.slice(0,st.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(s>=3)return{type:"truncated",reason:"max_depth"};if(t.add(e),Array.isArray(e)){const t=e.slice(0,5).map((e=>r(e,s+1)));return e.length>5&&t.push({type:"truncated",remaining:e.length-5}),t}const n=Object.entries(e),i={};for(const[e,t]of n.slice(0,5))i[e]=r(t,s+1);return n.length>5&&(i.__truncated__={remaining:n.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:s,...n}=t||{};console.debug("cardFS.write response",n),r.resolve(n)}handleFsListDataMessage(e,t){const r=this.fsListRequests.get(e);if(!r)return;this.resetFsListProgressTimeout(e);const{messageId:s,...n}=t||{},i=this.normalizeListResult(n);r.handler.next(i),i.is_complete&&this.clearFsListRequest(e)}createCardFsError(e,t){const r=new Error(e?.message||t),s=e?.error_code;return s&&Object.values(Ze).includes(s)&&(r.code=s),r}toCardFsErrorPayload(e,t="Unknown cardFS error"){const r="string"==typeof e?.message?e.message:"string"==typeof e?e:t,s=e?.code??e?.error_code;return s&&Object.values(Ze).includes(s)?{code:s,message:r}:{message:r}}async cardFSReadFallback(e,t,r,s=!0){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.read fallback is disabled because parent supports card_fs");const n=this.getCardIuid();if(!n)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=(s,n,i,a,c,l,d)=>{if(!s)return null;const u=c??e.name??s?.name??e.iuid??"document",h=l??s?.iuid??e.iuid??null,f=!1!==d?.includeData,p=f?this.sanitizeReadData(n,u).value:void 0,y={name:u,iuid:h,object:s,data:f?this.normalizeReadData(p,s?.mimetype):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):(console.debug("cardFS.read received",y),this.invokeReadHandlerNext(r,y)),o=!0,y};if(i)try{if(s){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(n,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,s=t.object?.data_hash,n=void 0!==e&&void 0!==s&&e===s;l(t.object,t.data,!1,!0,r,t.object?.iuid,{includeData:!n,isDirty:!n})}else l(t.object,t.data,!1,!0,r,t.object?.iuid)}catch(s){const n=s instanceof Error?s:new Error(String(s)),c=this.getCardFsErrorCode(n);if(c===Ze.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(n.message),{code:c})}if(c===Ze.NOT_FOUND||c===Ze.NO_PERMISSION){const e={code:c,message:n.message};t&&this.fsReadRequests.has(t)?this.failFsReadRequest(t,e):this.invokeReadHandlerError(r,e)}else console.warn("cardFS.read fresh fetch failed",s)}if(!o)throw new Error(`cardFS.read fallback could not locate ${c}`)}async cardFSWriteFallback(e,t,r,s){if(!this.shouldUseCardFsFallback())throw new Error("cardFS.write fallback is disabled because parent supports card_fs");const n=this.getCardIuid();if(!n)throw new Error("cardFS.write fallback failed: card not initialized");console.debug("cardFS.write fallback invoked for target",e);try{const i=this.normalizeWriteData(t,r);await this.upsertDocumentViaApi(n,e,i,r);const a=await this.fetchDocumentPayload(n,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 s&&this.fsWriteRequests.has(s)?this.handleFsWriteSuccess(s,o):console.debug("cardFS.write response",o),o}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,s=r&&Object.values(Ze).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:s})}}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");console.debug("cardFS.delete fallback invoked for target",e);try{const r=this.ensureCardFsCache(),s=await this.fetchDocumentMetadataByTarget(t,e).catch((()=>null)),n=s?.iuid??e.iuid??null,i=s?.name??e.name??null;if(!n)return e.name&&await(r?.deleteByName(e.name)),{name:i,iuid:null,deleted:!1};const a=await fetch(`/api/v1/documents/${n}/`,{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(n,i??void 0));return{name:i??n,iuid:n,deleted:404!==a.status}}catch(e){const t=e instanceof Error?e:new Error(String(e)),r=t?.code??t?.error_code,s=r&&Object.values(Ze).includes(r)?r:this.getCardFsErrorCode(t);throw Object.assign(new Error(t.message),{code:s})}}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(),s=this.formatFolderPath(e),n=s??"/";try{const e=await this.fetchFolderListing(t,s);return r&&(await r.cacheFolderListing(s,{folder_name:e.folder_name??n,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??n,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(s));if(t){return{documents:Array.isArray(t.data?.results)?t.data.results:[],folder_name:t.folder_name??n,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(Ze).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),s="boolean"==typeof e?.is_complete?e.is_complete:!r,n="boolean"!=typeof e?.is_dirty||e.is_dirty;return{...e,documents:t,is_stale:r,is_complete:s,is_dirty:n}}getCardFsErrorCode(e){if(!e)return Ze.UNKNOWN;const t=e?.status??e?.statusCode;if(0===t)return Ze.NO_INTERNET;if(401===t||403===t)return Ze.NO_PERMISSION;if(404===t)return Ze.NOT_FOUND;if(500===t)return Ze.SERVER_ERROR;const r="string"==typeof e?.message?e.message.toLowerCase():"";return r.includes("not found")?Ze.NOT_FOUND:r.includes("permission")||r.includes("unauthorized")||r.includes("forbidden")?Ze.NO_PERMISSION:r.includes("network")||r.includes("failed to fetch")||r.includes("offline")?Ze.NO_INTERNET:Ze.UNKNOWN}isBinaryReadPayload(e){if((e?.file_type??e?.object?.file_type??e?.object?.fileType)===Qe.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 s=await r.json().catch((()=>null)),n=this.normalizeDocumentsResponse(s);return n.find((e=>e?.name===t))??n[0]??null}async fetchFolderListing(e,t){const r=t?`?name=${encodeURIComponent(t)}`:"",s=await fetch(`/api/v1/documents/with_card/${e}/${r}`,{method:"GET",headers:this.authHeader()});if(!s.ok){const e=await s.text().catch((()=>"list failed"));throw new Error(`cardFS.list failed: ${e}`)}const n=await s.json().catch((()=>null));return{documents:this.normalizeDocumentsResponse(n),folder_name:t,folder_iuid:void 0,last_index:n?.last_index??n?.last_page??null,last_page:n?.last_page??null}}async fetchDocumentPayload(e,t){const r="string"==typeof t?{name:t}:t,s=await this.fetchDocumentMetadataByTarget(e,r);if(!s){const e=r.name?`"${r.name}"`:r.iuid?`iuid ${r.iuid}`:"document";throw new Error(`cardFS document not found: ${e}`)}return{object:s,data:await this.fetchDocumentData(s)}}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 s=r.headers.get("Content-Type")||"";return s.includes("application/json")?r.json():s.startsWith("text/")?r.text():r.arrayBuffer()}async buildFileFormData(e,t,r){let s;if(t instanceof File)s=t;else if("undefined"!=typeof Blob&&t instanceof Blob)s=new File([t],e,{type:t.type||"application/octet-stream"});else{const n=r===Qe.TEXT?"text/plain":r===Qe.JSON?"application/json":"application/octet-stream";s=new File([t],e,{type:n})}const n=new FormData;return n.append("file",s),n}async upsertDocumentViaApi(e,t,r,s){if(t.iuid){let e=t.name;if(!e){const r=await this.fetchDocumentMetadataByIuid(t.iuid).catch((()=>null));e=r?.name??t.iuid}const n=await this.buildFileFormData(e??t.iuid??"document",r,s),i=await fetch(`/api/v1/documents/${t.iuid}/`,{method:"PUT",headers:this.authHeader(),body:n});if(!i.ok){const e=await i.text().catch((()=>"update failed"));throw new Error(`cardFS.write update failed: ${e}`)}return}const n=await this.buildFileFormData(t.name??t.iuid??"document",r,s),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:n});if(!e.ok){const t=await e.text().catch((()=>"update failed"));throw new Error(`cardFS.write update failed: ${t}`)}return}if(n.append("parent_iuid",e),n.append("attached_to_iuid",e),!t.name)throw new Error('cardFS.write failed: "name" missing');n.append("filename",t.name);const a=await fetch("/api/v1/documents/",{method:"POST",headers:this.authHeader(),body:n});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 s={message:this.formatErrorMessage(t),error_code:e,data:r??null};this.handler&&this.safeInvoke("onError",this.handler,s)}setFileDirty(e){this.sendMessage(ze.FILE_DIRTY,e)}getUsername(e){const t=e?.name;return t&&Object.values(t).some((e=>e))?$e(t):""}attachUserFullName(e){return e&&"object"==typeof e?{...e,getFullName(){return $e(this?.name)}}:e}}return st.FS_RESPONSE_TIMEOUT_MS=3e4,st.FS_READ_RETENTION_MS=15e3,st.CARD_FS_ACK_TIMEOUT_MS=15e3,st.MAX_CONSOLE_ARG_CHARS=2e3,st.MAX_CONSOLE_LOG_ENTRIES=100,st.MAX_CONSOLE_STRING_PREVIEW_CHARS=200,st.DEFAULT_ROLE_PERMISSIONS="r",t})()));
|
|
2
2
|
//# sourceMappingURL=index.js.map
|