@wishknish/knishio-client-js 1.0.0 → 1.1.0

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.
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("jssha");c=s(c,1);let l=require("@urql/core"),u=require("graphql-ws"),d=require("wonka");typeof self>`u`&&(global.self=global);var f=class{static toHex(e,t){let n=(e,t)=>{let n=t?[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`A`,`B`,`C`,`D`,`E`,`F`]:[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`];return n[Math.floor(e/16)]+n[e%16]},r=Object.assign({grouping:0,rowlength:0,uppercase:!1},t||{}),i=``,a=0,o=0;for(let t=0;t<e.length&&(i+=n(e[t],r.uppercase),t!==e.length-1);++t)r.grouping>0&&++a===r.grouping&&(a=0,r.rowlength>0&&++o===r.rowlength?(o=0,i+=`
2
- `):i+=` `);return i}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,``);t.length%2==1&&(t=`0${t}`);let n=new Uint8Array(Math.floor(t.length/2)),r=-1;for(let e=0;e<t.length;++e){let i=t[e],a=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`].indexOf(i);if(a===-1)throw Error(`unexpected character`);r===-1?r=16*a:(n[Math.floor(e/2)]=r+a,r=-1)}return n}};String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,``)}),String.prototype.toCamelCase||(String.prototype.toCamelCase=function(){return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,(e,t)=>t.toUpperCase())}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)});function p(e,t){let n=Math.ceil(e.length/t),r=[];for(let i=0,a=0;i<n;++i,a+=t)r[i]=e.substr(a,t);return r}function m(e=256,t=`abcdef0123456789`){let n=new Uint8Array(e);crypto.getRandomValues(n);let r=``;for(let i=0;i<e;i++)r+=t.charAt(n[i]%t.length);return r}function h(e,t,n,r,i){if(r||=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~\`!@#$%^&*()-_=+[{]}\\|;:'",<.>/?¿¡`,i||=r,t>r.length||n>i.length)return console.warn(`Strings::charsetBaseConvert() - Can't convert`,e,`to base`,n,`greater than symbol table length. src-table:`,r.length,`dest-table:`,i.length),!1;let a=BigInt(0);for(let n=0;n<e.length;n++)a=a*BigInt(t)+BigInt(r.indexOf(e.charAt(n)));let o=``;for(;a>0;){let e=a%BigInt(n);o=i.charAt(Number(e))+o,a/=BigInt(n)}return o||`0`}function g(e){return f.toHex(e,{})}function _(e){return f.toUint8Array(e)}function v(e){let t=_(e);if(typeof Buffer<`u`)return Buffer.from(t).toString(`base64`);let n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));return btoa(n)}function y(e){if(typeof Buffer<`u`)return g(new Uint8Array(Buffer.from(e,`base64`)));let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return g(n)}function b(e){return/^[A-F0-9]+$/i.test(e)}function ee(e){return(typeof e==`number`||typeof e==`string`&&e.trim()!==``)&&!isNaN(e)}var x=class{static normalizeMeta(e){if(Array.isArray(e))return e.map(e=>({key:e.key,value:e.value==null?null:String(e.value)}));let t=[];for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let r=e[n];t.push({key:n,value:r==null?null:String(r)})}return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(let n of e)t[n.key]=n.value;else t=e;return t}};function te(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ne(e,t){let n,r,i,a=[Array,Date,Number,String,Boolean],o=Object.prototype.toString;for(t||=[],n=0;n<t.length;n+=2)e===t[n]&&(r=t[n+1]);if(!r&&e&&typeof e==`object`){for(r={},n=0;n<a.length;n++)o.call(e)===o.call(i=new a[n](e))&&(r=n?i:[]);for(n in t.push(e,r),e)t.hasOwnProperty.call(e,n)&&(r[n]=ne(e[n],t))}return r||e}function re(...e){return[].concat(...e.map((t,n)=>{let r=e.slice(0);r.splice(n,1);let i=[...new Set([].concat(...r))];return t.filter(e=>!i.includes(e))}))}function S(...e){return e.reduce((e,t)=>e.filter(e=>t.includes(e)))}var ie=class e{constructor(t={},n={}){this.policy=e.normalizePolicy(t),this.fillDefault(n)}static normalizePolicy(e={}){let t={};for(let[n,r]of Object.entries(e))if(r!==null&&[`read`,`write`].includes(n)){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]=i}return t}fillDefault(e={}){let t=Array.from(this.policy).filter(e=>e.action===`read`),n=Array.from(this.policy).filter(e=>e.action===`write`);for(let[r,i]of Object.entries({read:t,write:n})){let t=i.map(e=>e.key);this.policy[r]||(this.policy[r]={});for(let n of re(e,t))this.policy[r][n]||(this.policy[r][n]=r===`write`&&![`characters`,`pubkey`].includes(n)?[`self`]:[`all`])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}},C=class{constructor(e=[]){this.meta=x.normalizeMeta(e)}merge(e){return this.meta=Array.from(new Set([...this.meta,...x.normalizeMeta(e)])),this}addContext(e=null){return this}setAtomWallet(e){let t={};return e.tokenUnits&&e.tokenUnits.length&&(t.tokenUnits=JSON.stringify(e.getTokenUnitsData())),e.tradeRates&&e.tradeRates.length&&(t.tradeRates=JSON.stringify(e.tradeRates)),Object.keys(t).length>0&&this.merge(t),this}setMetaWallet(e){return this.merge({walletTokenSlug:e.token,walletBundleHash:e.bundle,walletAddress:e.address,walletPosition:e.position,walletBatchId:e.batchId,walletPubkey:e.pubkey,walletCharacters:e.characters}),this}setShadowWalletClaim(e){return this.merge({shadowWalletClaim:e*1}),this}setSigningWallet(e){return this.merge({signingWallet:JSON.stringify({tokenSlug:e.token,bundleHash:e.bundle,address:e.address,position:e.position,pubkey:e.pubkey,characters:e.characters})}),this}addPolicy(e){let t=new ie(e,Object.keys(this.meta));return this.merge({policy:t.toJson()}),this}get(){return this.meta}},w=class extends TypeError{constructor(e=null,t=null,n=null){if(super(e,t,n),e===null)throw new this(`Unknown ${this.constructor.name}`);this.name=`BaseException`}toString(){return`${this.name}: ${this.message}.\nStack:\n${this.stack}`}},T=class extends w{constructor(e=`The molecule does not contain atoms`,t=null,n=null){super(e,t,n),this.name=`AtomsMissingException`}},ae=class e{static create(e){let t={};for(let n of Object.keys(e))Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return new this(t)}static structure(t){switch(Object.prototype.toString.call(t)){case`[object Array]`:{let n=[];for(let r in t)n.push(e.isStructure(t[r])?e.structure(t[r]):t[r]);return n}case`[object Object]`:{let n=[],r=Object.keys(t).sort((e,t)=>e===t?0:e<t?-1:1);for(let i of r)if(Object.prototype.hasOwnProperty.call(t,i)){let r={};r[i]=e.isStructure(t[i])?e.structure(t[i]):t[i],n.push(r)}if(n.length>0)return n;break}}return t}static isStructure(e){return[`[object Object]`,`[object Array]`].includes(Object.prototype.toString.call(e))}view(){return e.structure(this)}},oe={4:class extends ae{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:r=null,value:i=null,batchId:a=null,metaType:o=null,metaId:s=null,meta:c=null,index:l=null,createdAt:u=null,version:d=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=r,this.value=i,this.batchId=a,this.metaType=o,this.metaId=s,this.meta=c,this.index=l,this.createdAt=u,this.version=d}}},E=class e{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:r=null,value:i=null,batchId:a=null,metaType:o=null,metaId:s=null,meta:c=null,otsFragment:l=null,index:u=null,version:d=null}){this.position=e,this.walletAddress=t,this.isotope=n,this.token=r,this.value=i===null?null:String(i),this.batchId=a,this.metaType=o,this.metaId=s,this.meta=c?x.normalizeMeta(c):[],this.index=u,this.otsFragment=l,this.createdAt=String(+new Date),d!==null&&Object.prototype.hasOwnProperty.call(oe,d)&&(this.version=String(d))}static getHashableProps(){return[`position`,`walletAddress`,`isotope`,`token`,`value`,`batchId`,`metaType`,`metaId`,`meta`,`createdAt`]}static getUnclaimedProps(){return[`otsFragment`]}static create({isotope:t,wallet:n=null,value:r=null,metaType:i=null,metaId:a=null,meta:o=null,batchId:s=null}){return o||=new C,o instanceof C||(o=new C(o)),n&&(o.setAtomWallet(n),s||=n.batchId),new e({position:n?n.position:null,walletAddress:n?n.address:null,isotope:t,token:n?n.token:null,value:r,batchId:s,metaType:i,metaId:a,meta:o.get()})}static jsonToObject(t){let n=Object.assign(new e({}),JSON.parse(t)),r=Object.keys(new e({}));for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&!r.includes(e)&&delete n[e];return n}toJSON(e={}){let{includeOtsFragments:t=!0,validateFields:n=!1}=e;try{if(n){for(let e of[`position`,`walletAddress`,`isotope`,`token`])if(!this[e])throw Error(`Required field '${e}' is missing or empty`)}let e={position:this.position??``,walletAddress:this.walletAddress??``,isotope:this.isotope,token:this.token??``,value:this.value,batchId:this.batchId,metaType:this.metaType,metaId:this.metaId,meta:this.meta||[],index:this.index,createdAt:this.createdAt,version:this.version};return t&&this.otsFragment&&(e.otsFragment=this.otsFragment),e}catch(e){throw Error(`Atom serialization failed: ${e.message}`)}}static fromJSON(t,n={}){let{validateStructure:r=!0,strictMode:i=!1}=n;try{let n=typeof t==`string`?JSON.parse(t):t;if(i||r){for(let e of[`position`,`walletAddress`,`isotope`,`token`])if(!n[e])throw Error(`Required field '${e}' is missing or empty`)}let a=new e({position:n.position,walletAddress:n.walletAddress,isotope:n.isotope,token:n.token,value:n.value,batchId:n.batchId,metaType:n.metaType,metaId:n.metaId,meta:n.meta,index:n.index,version:n.version});return n.otsFragment&&(a.otsFragment=n.otsFragment),n.createdAt&&(a.createdAt=n.createdAt),a}catch(e){throw Error(`Atom deserialization failed: ${e.message}`)}}static hashAtoms({atoms:t,output:n=`base17`}){let r=new c.default(`SHAKE256`,`TEXT`),i=e.sortAtoms(t);if(i.length===0)throw new T;if(i.map(t=>{if(!(t instanceof e))throw new T;return t}),i.every(e=>e.version&&Object.prototype.hasOwnProperty.call(oe,e.version)))r.update(JSON.stringify(i.map(e=>oe[e.version].create(e).view())));else{let e=String(t.length),n=[];for(let t of i)n.push(e),n=n.concat(t.getHashableValues());for(let e of n)r.update(e)}switch(n){case`hex`:return r.getHash(`HEX`,{outputLen:256});case`array`:return r.getHash(`ARRAYBUFFER`,{outputLen:256});default:return h(r.getHash(`HEX`,{outputLen:256}),16,17,`0123456789abcdef`,`0123456789abcdefg`).padStart(64,`0`)}}static jsonSerialization(t,n){if(!e.getUnclaimedProps().includes(t))return n}static sortAtoms(e){let t=[...e];return t.sort((e,t)=>e.index<t.index?-1:1),t}aggregatedMeta(){return x.aggregateMeta(this.meta)}getHashableValues(){let t=[];for(let n of e.getHashableProps()){let e=this[n];if(e!==null||[`position`,`walletAddress`].includes(n)){if(n===`meta`)for(let n of e)n.value!==void 0&&n.value!==null&&(t.push(String(n.key)),t.push(String(n.value)));else t.push(e===null?``:String(e))}}return t}};function se(e=null,t=2048){if(e){let n=new c.default(`SHAKE256`,`TEXT`);return n.update(e),n.getHash(`HEX`,{outputLen:t*4})}return m(t)}function D(e,t=null){let n=new c.default(`SHAKE256`,`TEXT`);return n.update(e),n.getHash(`HEX`,{outputLen:256})}function ce(e,t){let n=new c.default(`SHAKE256`,`TEXT`);return n.update(e),n.getHash(`HEX`,{outputLen:t})}function le({molecularHash:e=null,index:t=null}){return e!==null&&t!==null?D(String(e)+String(t),`generateBatchId`):m(64)}var ue=class e{constructor(e,t,n){this.id=e,this.name=t,this.metas=n||{}}static createFromGraphQL(t){let n=t.metas||{};return n.length&&(n=JSON.parse(n),n||={}),new e(t.id,t.name,n)}static createFromDB(t){return new e(t[0],t[1],t.length>2?t[2]:{})}getFragmentZone(){return this.metas.fragmentZone||null}getFusedTokenUnits(){return this.metas.fusedTokenUnits||null}toData(){return[this.id,this.name,this.metas]}toGraphQLResponse(){return{id:this.id,name:this.name,metas:JSON.stringify(this.metas)}}},de=class extends w{constructor(e=`Attempting to create a wallet with no credentials (secret or bundle hash)`,t=null,n=null){super(e,t,n),this.name=`WalletCredentialException`}},fe=BigInt(2**32-1),pe=BigInt(32);function me(e,t=!1){return t?{h:Number(e&fe),l:Number(e>>pe&fe)}:{h:Number(e>>pe&fe)|0,l:Number(e&fe)|0}}function he(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=me(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}function ge(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var _e=e=>e?`"${e}" `:``;function O(e,t=``){if(typeof e!=`number`)throw TypeError(_e(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(_e(t)+`expected integer >= 0, got `+e);return e}function ve(e,t=``){if(typeof e!=`boolean`)throw TypeError(_e(t)+`expected boolean, got type=`+typeof e);return e}function k(e,t,n=``){if(ge(e)&&(t===void 0||e.length===t))return e;t!==void 0&&O(t,`length`);let r=ge(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=_e(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var ye=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)},be=(e,t)=>{ye(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,`__proto__`))throw TypeError(`"${t}.__proto__" is not allowed`)};function xe(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Se(e,t){k(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Ce(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function we(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Te=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ee(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function De(e){for(let t=0;t<e.length;t++)e[t]=Ee(e[t]);return e}var Oe=Te?e=>e:De;function ke(e,t,n=`opts`){return be(e,`defaults`),t!==void 0&&be(t,n),Object.assign(Object.create(null),e,t)}function Ae(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=ke({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function je(e=32){O(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Me=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),Ne=BigInt(0),Pe=BigInt(1),Fe=BigInt(2),Ie=BigInt(7),Le=BigInt(256),Re=BigInt(113),ze=[],Be=[],Ve=[];for(let e=0,t=Pe,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ze.push(2*(5*r+n)),Be.push((e+1)*(e+2)/2%64);let i=Ne;for(let e=0;e<7;e++)t=(t<<Pe^(t>>Ie)*Re)%Le,t&Fe&&(i^=Pe<<(Pe<<BigInt(e))-Pe);Ve.push(i)}var He=he(Ve,!0),Ue=He[0],We=He[1],Ge=(e,t,n)=>e<<n|t>>>32-n,Ke=(e,t,n)=>t<<n|e>>>32-n,qe=(e,t,n)=>t<<n-32|e>>>64-n,Je=(e,t,n)=>e<<n-32|t>>>64-n,Ye=(e,t,n)=>n>32?qe(e,t,n):Ge(e,t,n),Xe=(e,t,n)=>n>32?Je(e,t,n):Ke(e,t,n),Ze=new Uint32Array(10);function Qe(e,t=24){if(!(e instanceof Uint32Array))throw TypeError(`"s" expected Uint32Array(50), got type=`+typeof e);if(e.length!==50)throw RangeError(`"s" expected Uint32Array(50), got length=`+e.length);if(O(t,`rounds`),t<1||t>24)throw Error(`"rounds" expected integer 1..24`);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)Ze[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let n=(t+8)%10,r=(t+2)%10,i=Ze[r],a=Ze[r+1],o=Ye(i,a,1)^Ze[n],s=Xe(i,a,1)^Ze[n+1];for(let n=0;n<50;n+=10)e[t+n]^=o,e[t+n+1]^=s}let t=e[2],r=e[3];for(let n=0;n<24;n++){let i=Be[n],a=Ye(t,r,i),o=Xe(t,r,i),s=ze[n];t=e[s],r=e[s+1],e[s]=a,e[s+1]=o}for(let t=0;t<50;t+=10){let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3];e[t]^=~e[t+2]&e[t+4],e[t+1]^=~e[t+3]&e[t+5],e[t+2]^=~e[t+4]&e[t+6],e[t+3]^=~e[t+5]&e[t+7],e[t+4]^=~e[t+6]&e[t+8],e[t+5]^=~e[t+7]&e[t+9],e[t+6]^=~e[t+8]&n,e[t+7]^=~e[t+9]&r,e[t+8]^=~n&i,e[t+9]^=~r&a}e[0]^=Ue[n],e[1]^=We[n]}we(Ze)}var $e=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,n,r=!1,i=24){if(O(e,`blockLen`),O(t,`suffix`),O(i,`rounds`),ve(r,`enableXOF`),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.canXOF=r,this.rounds=i,O(n,`outputLen`),!(0<e&&e<200))throw Error(`"blockLen" must be 1..199`);this.state=new Uint8Array(200),this.state32=Ce(this.state)}clone(){return this._cloneInto()}keccak(){Oe(this.state32),Qe(this.state32,this.rounds),Oe(this.state32),this.posOut=0,this.pos=0}update(e){xe(this),k(e);let{blockLen:t,state:n,state32:r}=this,i=e.length,a=t%4==0&&e.byteOffset%4==0,o=t/4,s=a&&i>=t?Ce(e):void 0;for(let a=0;a<i;){if(s!==void 0&&this.pos===0&&a%4==0&&i-a>=t){for(let e=0,t=a/4;e<o;e++)r[e]^=s[t+e];a+=t,this.pos=t,this.keccak();continue}let c=Math.min(t-this.pos,i-a);for(let t=0;t<c;t++)n[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){xe(this,!1),k(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a}return e}xofInto(e){if(!this.enableXOF)throw Error(`XOF is not enabled`);return this.writeInto(e)}xof(e){return O(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Se(e,this),this.finished)throw Error(`digest() was already called`);this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,we(this.state)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:i,rounds:a,enableXOF:o}=this;return t||=new e(n,r,i,o,a),t.blockLen=n,t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=a,t.suffix=r,t.outputLen=i,t.enableXOF=o,t.canXOF=this.canXOF,t.destroyed=this.destroyed,t}},et=(e,t,n,r={})=>Ae(()=>new $e(t,e,n),r),tt=et(6,136,32,Me(8)),nt=et(6,72,64,Me(10)),rt=(e,t,n,r={})=>Ae((r={})=>(r=ke({},r),new $e(t,e,r.dkLen===void 0?n:r.dkLen,!0)),r),it=rt(31,168,16,Me(11)),at=rt(31,136,32,Me(12));function ot(e,t=`object`){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`);return e}function st(e,t={},n={},r=`object`){ot(e,r),ot(t,`fields`),ot(n,`optFields`);function i(t,n,i){let a=r===`object`?`param "${String(t)}"`:`"${r}.${String(t)}"`,o=e[t];if(!Object.hasOwn(e,t)&&(i?o!==void 0:n!==`function`))throw TypeError(`${a} is invalid: expected own property`);if(i&&o===void 0)return;let s=typeof o;if(s!==n||o===null)throw TypeError(`${a} is invalid: expected ${n}, got ${s}`)}let a=(e,t)=>Object.entries(e).forEach(([e,n])=>i(e,n,t));a(t,!1),a(n,!0)}function ct(e,t=`n`){if(typeof e!=`number`)throw TypeError(`wrong u32 integer "${t}": expected number, got type=${typeof e}`);if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw RangeError(`wrong u32 integer "${t}": expected 0..4294967295, got ${e}`);return e}function lt(e){return ct(e,`x`),!(e&e-1)&&e!==0}function ut(e,t){if(ct(e),typeof t!=`number`)throw TypeError(`"bits" expected number, got type=`+typeof t);if(!Number.isSafeInteger(t)||t<0||t>32)throw Error(`expected integer 0 <= bits <= 32, got ${t}`);let n=0;for(let r=0;r<t;r++,e>>>=1)n=n<<1|e&1;return n>>>0}function dt(e){return ct(e),31-Math.clz32(e)}function ft(e){if(!e||typeof e!=`object`||typeof e.length!=`number`)throw TypeError(`"values" expected array-like, got type=`+typeof e);let t=e.length;if(!lt(t))throw Error(`expected positive power-of-two length, got `+t);let n=dt(t);for(let r=0;r<t;r++){let t=ut(r,n);if(r<t){let n=e[r];e[r]=e[t],e[t]=n}}return e}var pt=(e,t)=>{st(t,{N:`number`,roots:`object`,dit:`boolean`},{invertButterflies:`boolean`,skipStages:`number`,brp:`boolean`},`coreOpts`);let{N:n,roots:r,dit:i,invertButterflies:a=!1,skipStages:o=0,brp:s=!0}=t;ct(n,`coreOpts.N`);let c=dt(n);if(!lt(n))throw Error(`FFT: Polynomial size should be power of two`);ct(o,`coreOpts.skipStages`);let l=c===0?0:c-1;if(o>l)throw Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(r.length!==n)throw Error(`FFT: wrong roots length: expected ${n}, got ${r.length}`);let u=i!==a;return t=>{if(t.length!==n)throw Error(`FFT: wrong Polynomial length`);i&&s&&ft(t);for(let s=0,l=1;s<c-o;s++){let d=i?s+1+o:c-s,f=1<<d,p=f>>1,m=n>>d;for(let o=0;o<n;o+=f)for(let s=0,c=l++;s<p;s++){let l=a?i?n-c:c:s*m,d=o+s,f=o+s+p,h=r[l],g=t[f],_=t[d];if(u){let n=e.mul(g,h);t[d]=e.add(_,n),t[f]=e.sub(_,n)}else a?(t[d]=e.add(g,_),t[f]=e.mul(e.sub(g,_),h)):(t[d]=e.add(_,g),t[f]=e.mul(e.sub(_,g),h))}}return!i&&s&&ft(t),t}},A=k,mt=je;function ht(e,t,n=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}function gt(e,t){if(e=k(e),t=k(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function _t(e){return new Uint8Array(k(e))}function vt(e,...t){let n=e=>typeof e==`number`?e:e.bytesLen,r=t.reduce((e,t)=>e+n(t),0);return{bytesLen:r,encode:i=>{let a=new Uint8Array(r);for(let r=0,o=0;r<t.length;r++){let s=t[r],c=n(s),l=typeof s==`number`?i[r]:s.encode(i[r]);k(l,c,e),a.set(l,o),typeof s!=`number`&&l.fill(0),o+=c}return a},decode:i=>{k(i,r,e);let a=[];for(let e of t){let t=n(e),r=i.subarray(0,t);a.push(typeof e==`number`?r:e.decode(r)),i=i.subarray(t)}return a}}}function yt(e,t){let n=e,r=t*n.bytesLen;return{bytesLen:r,encode:e=>{let i=ht(e,`u`);if(i.length!==t)throw RangeError(`vecCoder.encode: wrong length=${i.length}. Expected: ${t}`);let a=new Uint8Array(r);for(let e=0,t=0;e<i.length;e++){let r=n.encode(i[e]);a.set(r,t),r.fill(0),t+=r.length}return a},decode:e=>{k(e,r);let t=[];for(let r=0;r<e.length;r+=n.bytesLen)t.push(n.decode(e.subarray(r,r+n.bytesLen)));return t}}}function j(...e){for(let t of e)if(Array.isArray(t))for(let e of t)e.fill(0);else t.fill(0)}function bt(e){if(O(e,`bits`),e>32)throw RangeError(`"bits" expected <= 32, got `+e);return e===32?4294967295:~(-1<<e)>>>0}var xt=e=>{let{newPoly:t,N:n,Q:r,F:i,ROOT_OF_UNITY:a,brvBits:o,isKyber:s}=e,c=(e,t=r)=>{let n=e%t|0;return(n>=0?n|0:t+n|0)|0},l=(e,t=r)=>{let n=c(e,t)|0;return(n>t>>1?n-t|0:n)|0};function u(){let e=t(n);for(let t=0;t<n;t++){let n=ut(t,o),i=BigInt(a)**BigInt(n)%BigInt(r);e[t]=Number(i)|0}return e}let d=u(),f=e=>{throw Error(`not implemented`)},p=s?{add:(e,t)=>{let n=e+t|0;return n>=r?n-r|0:n},sub:(e,t)=>{let n=e-t|0;return n<0?n+r|0:n},mul:(e,t)=>c((e|0)*(t|0))|0,inv:f}:{add:(e,t)=>c((e|0)+(t|0))|0,sub:(e,t)=>c((e|0)-(t|0))|0,mul:(e,t)=>c((e|0)*(t|0))|0,inv:f},m={N:n,roots:d,invertButterflies:!0,skipStages:+!!s,brp:!1},h=pt(p,{dit:!1,...m}),g=pt(p,{dit:!0,...m}),_={encode:e=>h(e),decode:e=>{g(e);for(let t=0;t<e.length;t++)e[t]=c(i*e[t]);return e}};return{mod:c,smod:l,nttZetas:d,NTT:{encode:e=>_.encode(e),decode:e=>_.decode(e)},bitsCoder:(e,r)=>{for(let t=0,r=0;t<n;t++)r+=e,r>32&&bt(r),r%=8;let i=bt(e),a=n/8*e;return{bytesLen:a,encode:t=>{let n=t,o=new Uint8Array(a);for(let t=0,a=0,s=0,c=0;t<n.length;t++)for(a|=(r.encode(n[t])&i)<<s,s+=e;s>=8;s-=8,a>>=8)o[c++]=a&255;return o},decode:a=>{let o=t(n);for(let t=0,n=0,s=0,c=0;t<a.length;t++)for(n|=a[t]<<s,s+=8;s>=e;s-=e,n>>=e)o[c++]=r.decode(n&i);return o}}}}},St=(e=>(t,n)=>{n||=e.blockLen;let r=new Uint8Array(t.length+2);r.set(t);let i=t.length,a=new Uint8Array(n),o=e.create({}),s=0,c=0;return{stats:()=>({calls:s,xofs:c}),get:(t,n)=>(r[i+0]=t,r[i+1]=n,o.destroy(),o=e.create({}).update(r),s++,()=>(c++,o.xofInto(a))),clean:()=>{o.destroy(),j(a,r)}}})(it),M=256,N=3329,P=xt({N:M,Q:N,F:3303,ROOT_OF_UNITY:17,newPoly:e=>new Uint16Array(e),brvBits:7,isKyber:!0}),Ct=Object.freeze({512:Object.freeze({N:M,Q:N,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:M,Q:N,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:M,Q:N,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),wt=e=>{if(e>=12)return{encode:e=>e,decode:e=>e>=N?e-N:e};let t=2**(e-1);return{encode:t=>((t<<e)+N/2)/N,decode:n=>n*N+t>>>e}},Tt=e=>P.bitsCoder(e,e===12?{encode:e=>e,decode:e=>e>=N?e-N:e}:{encode:e=>e,decode:e=>e}),Et=e=>e===12?Tt(12):P.bitsCoder(e,wt(e));function F(e,t){let n=e,r=t;for(let e=0;e<M;e++){let t=n[e]+r[e];n[e]=t>=N?t-N:t}}function Dt(e,t){let n=e,r=t;for(let e=0;e<M;e++){let t=n[e]-r[e];n[e]=t<0?t+N:t}}function Ot(e,t,n,r,i){return{c0:P.mod(P.mod(t*r)*i+e*n),c1:P.mod(e*r+t*n)}}function kt(e,t){let n=e,r=t;for(let e=0;e<M/2;e++){let t=P.nttZetas[64+(e>>1)];e&1&&(t=-t);let{c0:i,c1:a}=Ot(n[2*e+0],n[2*e+1],r[2*e+0],r[2*e+1],t);n[2*e+0]=i,n[2*e+1]=a}return n}function At(e){let t=e,n=new Uint16Array(M);for(let e=0;e<M;){let r=t();if(r.length%3)throw Error(`SampleNTT: unaligned block`);for(let t=0;e<M&&t+3<=r.length;t+=3){let i=(r[t+0]>>0|r[t+1]<<8)&4095,a=(r[t+1]>>4|r[t+2]<<4)&4095;i<N&&(n[e++]=i),e<M&&a<N&&(n[e++]=a)}}return n}var jt=(e,t)=>{let n=new Uint16Array(M),r=Ce(e);Oe(r);let i=0;for(let e=0,a=0,o=0,s=0;e<r.length;e++){let c=r[e];for(let e=0;e<32;e++)o+=c&1,c>>=1,i+=1,i===t?(s=o,o=0):i===2*t&&(n[a++]=P.mod(s-o),o=0,i=0)}if(Oe(r),i)throw Error(`sampleCBD: leftover bits: ${i}`);return n};function Mt(e,t,n,r){return jt(e(r*M/4,t,n),r)}var Nt=e=>{let{K:t,PRF:n,XOF:r,HASH512:i,ETA1:a,ETA2:o,du:s,dv:c}=e,l=Et(1),u=Et(c),d=Et(s),f=vt(`publicKey`,yt(Et(12),t),32),p=yt(Et(12),t),m=vt(`ciphertext`,yt(d,t),u),h=vt(`seed`,32,32),g=(e,r,i,s)=>{let c=[];for(let e=0;e<t;e++)c.push(P.NTT.encode(Mt(n,s,e,a)));let u=new Uint16Array(M),d=[];for(let i=0;i<t;i++){let a=Mt(n,s,t+i,o),l=new Uint16Array(M);for(let e=0;e<t;e++)F(l,kt(r(i,e),c[e]));F(a,P.NTT.decode(l)),d.push(a),F(u,kt(e[i],c[i])),j(l)}let f=Mt(n,s,2*t,o);F(f,P.NTT.decode(u));let p=l.decode(i);return F(p,f),j(e,c,u,f),m.encode([d,p])};return{secretCoder:p,lengths:{secretKey:p.bytesLen,publicKey:f.bytesLen,cipherText:m.bytesLen},keygen:e=>{A(e,32,`seed`);let o=new Uint8Array(33);o.set(e),o[32]=t;let s=i(o),[c,l]=h.decode(s),u=[],d=[];for(let e=0;e<t;e++)u.push(P.NTT.encode(Mt(n,l,e,a)));let m=r(c);for(let e=0;e<t;e++){let r=P.NTT.encode(Mt(n,l,t+e,a));for(let n=0;n<t;n++)F(r,kt(At(m.get(n,e)),u[n]));d.push(r)}m.clean();let g={publicKey:f.encode([d,c]),secretKey:p.encode(u)};return j(c,l,u,d,o,s),g},encrypt:(e,t,n)=>{let[i,a]=f.decode(e),o=r(a),s=g(i,(e,t)=>At(o.get(e,t)),t,n);return o.clean(),s},prepare:e=>{let[n,i]=f.decode(e),a=r(i),o=[];for(let e=0;e<t;e++)for(let n=0;n<t;n++)o.push(At(a.get(e,n)));return a.clean(),{encrypt:(e,r)=>g(n.map(e=>e.slice()),(e,n)=>o[e*t+n].slice(),e,r),clean:()=>j(n,o)}},decrypt:(e,n)=>{let[r,i]=m.decode(e),a=p.decode(n),o=new Uint16Array(M);for(let e=0;e<t;e++)F(o,kt(a[e],P.NTT.encode(r[e])));Dt(i,P.NTT.decode(o));let s=l.encode(i);return j(o,a,r,i),s}}};function Pt(e){let t=e,n=Nt(t),{HASH256:r,HASH512:i,KDF:a}=t,{secretCoder:o,lengths:s}=n,c=vt(`secretKey`,s.secretKey,s.publicKey,32,32),l=(e,n)=>{let r=e.subarray(0,384*t.K),i=o.encode(o.decode(_t(r))),a=gt(i,r);if(j(i),!a)throw Error(`ML-KEM.${n}: wrong publicKey modulus`)},u=Object.freeze({...s,seed:64,msg:32,msgRand:32,secretKey:c.bytesLen});return Object.freeze({info:Object.freeze({type:`ml-kem`}),lengths:u,keygen:e=>{let t=e===void 0,i=t?mt(64):e,a,o;try{A(i,64,`seed`);let e=n.keygen(i.subarray(0,32)),t=e.publicKey;return a=e.secretKey,o=r(t),{publicKey:t,secretKey:c.encode([a,t,o,i.subarray(32)])}}finally{a!==void 0&&j(a),o!==void 0&&j(o),t&&j(i)}},getPublicKey:e=>{let[t,n,r,i]=c.decode(e);return Uint8Array.from(n)},encapsulate:(e,t)=>{let a=t===void 0,o=a?mt(32):t,c;try{return A(e,s.publicKey,`publicKey`),A(o,32,`message`),l(e,`encapsulate`),c=i.create().update(o).update(r(e)).digest(),{cipherText:n.encrypt(e,o,c.subarray(32,64)),sharedSecret:c.subarray(0,32)}}finally{c!==void 0&&j(c.subarray(32)),a&&j(o)}},decapsulate:(e,t)=>{A(t,c.bytesLen,`secretKey`),A(e,s.cipherText,`cipherText`);let o=c.bytesLen-96,l=o+32;if(!gt(r(t.subarray(o/2,l)),t.subarray(l,l+32)))throw Error(`invalid secretKey: hash check failed`);let[u,d,f,p]=c.decode(t),m=n.decrypt(e,u),h=i.create().update(m).update(f).digest(),g=h.subarray(0,32),_=n.encrypt(d,m,h.subarray(32,64)),v=gt(e,_),y=a.create({dkLen:32}).update(p).update(e).digest();return j(m,_,h.subarray(32),v?y:g),v?g:y},prepare:e=>{A(e,s.publicKey,`publicKey`),l(e,`prepare`);let t=_t(e),o=r(t),u=n.prepare(t);return Object.freeze({publicKey:t,encapsulate:e=>{let t=e===void 0,n=t?mt(32):e,r;try{return A(n,32,`message`),r=i.create().update(n).update(o).digest(),{cipherText:u.encrypt(n,r.subarray(32,64)),sharedSecret:r.subarray(0,32)}}finally{r!==void 0&&j(r.subarray(32)),t&&j(n)}},decapsulate:(e,r)=>{A(r,c.bytesLen,`secretKey`),A(e,s.cipherText,`cipherText`);let[l,d,f,p]=c.decode(r);if(!gt(d,t)||!gt(f,o))throw Error(`ML-KEM.decapsulate: secretKey does not match prepared publicKey`);let m=n.decrypt(e,l),h=i.create().update(m).update(o).digest(),g=h.subarray(0,32),_=u.encrypt(m,h.subarray(32,64)),v=gt(e,_),y=a.create({dkLen:32}).update(p).update(e).digest();return j(m,_,h.subarray(32),v?y:g),v?g:y},clean:u.clean})}})}function Ft(e,t,n){return at.create({dkLen:e}).update(t).update(new Uint8Array([n])).digest()}var It={HASH256:tt,HASH512:nt,KDF:at,XOF:St,PRF:Ft},Lt=e=>Pt({...It,...e}),Rt=Lt(Ct[768]),zt={1024:{kem:Lt(Ct[1024]),pkBytes:1568,skBytes:3168,ctBytes:1568},768:{kem:Rt,pkBytes:1184,skBytes:2400,ctBytes:1088}},Bt=1024,I=class e{constructor({secret:t=null,bundle:n=null,token:r=`USER`,address:i=null,position:a=null,batchId:o=null,characters:s=null,mlKemParameterSet:c=Bt}){let l=Number(c);if(!zt[l])throw Error(`KnishIO: unsupported ML-KEM parameter set ${c}; expected 1024 or 768.`);this.mlKemParameterSet=l,this.token=r,this.balance=`0`,this.molecules={},this.key=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.tradeRates={},this.address=i,this.position=a,this.bundle=n,this.batchId=o,this.characters=s,t&&(this.bundle=this.bundle||D(t,`Wallet::constructor`),this.position=this.position||e.generatePosition(),this.key=e.generateKey({secret:t,token:this.token,position:this.position}),this.address=this.address||e.generateAddress(this.key),this.characters=this.characters||`BASE64`,this.initializeMLKEM())}static create({secret:t=null,bundle:n=null,token:r,batchId:i=null,characters:a=null,mlKemParameterSet:o=Bt}){let s=null;if(!t&&!n)throw new de;return t&&!n&&(s=e.generatePosition(),n=D(t,`Wallet::create`)),new e({secret:t,bundle:n,token:r,position:s,batchId:i,characters:a,mlKemParameterSet:o})}static isBundleHash(e){return typeof e==`string`&&e.length===64&&b(e)}static getTokenUnits(e){let t=[];return e.forEach(e=>{t.push(ue.createFromDB(e))}),t}static generateKey({secret:e,token:t,position:n}){if(!e)throw new de(`Wallet::generateKey() - Secret is required!`);if(!n)throw new de(`Wallet::generateKey() - Position is required!`);let r=b(e)?e:ce(e,1024),i=b(n)?n:ce(n,256),a=BigInt(`0x${r}`)+BigInt(`0x${i}`),o=new c.default(`SHAKE256`,`TEXT`);o.update(a.toString(16)),t&&o.update(t);let s=new c.default(`SHAKE256`,`TEXT`);return s.update(o.getHash(`HEX`,{outputLen:8192})),s.getHash(`HEX`,{outputLen:8192})}static generateAddress(e){let t=p(e,128),n=new c.default(`SHAKE256`,`TEXT`);for(let e in t){let r=t[e];for(let e=1;e<=16;e++){let e=new c.default(`SHAKE256`,`TEXT`);e.update(r),r=e.getHash(`HEX`,{outputLen:512})}n.update(r)}let r=new c.default(`SHAKE256`,`TEXT`);return r.update(n.getHash(`HEX`,{outputLen:8192})),r.getHash(`HEX`,{outputLen:256})}static generatePosition(e=64){return m(e,`abcdef0123456789`)}_deriveMlKemKeypair(e){let t=zt[e];if(!t)throw Error(`KnishIO: unsupported ML-KEM parameter set ${e}; expected 1024 or 768.`);if(!this.key)return null;let n=se(this.key,128),r=new Uint8Array(64);for(let e=0;e<64;e++)r[e]=parseInt(n.substr(e*2,2),16);let{publicKey:i,secretKey:a}=t.kem.keygen(r);return{pubkey:this.serializeKey(i),privkey:a,params:t}}initializeMLKEM(){let e=this._deriveMlKemKeypair(this.mlKemParameterSet);e&&(this.pubkey=e.pubkey,this.privkey=e.privkey)}serializeKey(e){if(typeof Buffer<`u`)return Buffer.from(e).toString(`base64`);let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}deserializeKey(e){if(typeof Buffer<`u`)return new Uint8Array(Buffer.from(e,`base64`));let t=atob(e);return new Uint8Array(t.length).map((e,n)=>t.charCodeAt(n))}static mlKemParameterSetFromPubkey(e){if(!e)return null;let t;try{t=typeof Buffer<`u`?Buffer.from(e,`base64`).length:atob(e).length}catch{return null}for(let[e,n]of Object.entries(zt))if(n.pkBytes===t)return Number(e);return null}balanceAsNumber(){return Number(this.balance)}balanceAsBigInt(){let e=String(this.balance),t=e.includes(`.`)?e.split(`.`)[0]:e;return BigInt(t||`0`)}setBalanceBigInt(e){this.balance=e.toString()}setBalanceNumber(e){this.balance=String(e)}getTokenUnitsData(){let e=[];return this.tokenUnits.forEach(t=>{e.push(t.toData())}),e}splitUnits(e,t,n=null){if(e.length===0)return;let r=[],i=[];this.tokenUnits.forEach(t=>{e.includes(t.id)?r.push(t):i.push(t)}),this.tokenUnits=r,n!==null&&(n.tokenUnits=r),t.tokenUnits=i}splitUnitsMulti(e,t,n){let r=new Set;e.forEach(e=>{e.forEach(e=>r.add(e))}),r.size!==0&&(t.forEach((t,n)=>{let r=e[n];t.tokenUnits=this.tokenUnits.filter(e=>r.includes(e.id))}),n.tokenUnits=this.tokenUnits.filter(e=>!r.has(e.id)),this.tokenUnits=this.tokenUnits.filter(e=>r.has(e.id)))}createRemainder(t){let n=e.create({secret:t,token:this.token,characters:this.characters});return n.initBatchId({sourceWallet:this,isRemainder:!0}),n}isShadow(){return(this.position===void 0||this.position===null)&&(this.address===void 0||this.address===null)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:le({}))}async encryptMessage(e,t){let n=JSON.stringify(e),r=new TextEncoder().encode(n),i=this.deserializeKey(t),a=zt[this.mlKemParameterSet];if(i.length!==a.pkBytes)throw Error(`KnishIO: cannot ML-KEM-encrypt — recipient public key is ${i.length} bytes, expected ${a.pkBytes} (ML-KEM-${this.mlKemParameterSet}). The peer is not running ML-KEM-${this.mlKemParameterSet}; upgrade the peer, or step this client back to the other parameter set.`);let{cipherText:o,sharedSecret:s}=a.kem.encapsulate(i),c=await this.encryptWithSharedSecret(r,s);return{cipherText:this.serializeKey(o),encryptedMessage:this.serializeKey(c)}}async decryptMessage(e){let t=await this._mlkemDecryptToString(e);return t===null?null:JSON.parse(t)}async _mlkemDecryptToString(e){let{cipherText:t,encryptedMessage:n}=e,r=this.deserializeKey(t),i=zt[this.mlKemParameterSet],a=this.mlKemParameterSet===1024?768:1024,o=i,s=this.privkey;if(r.length!==i.ctBytes){if(r.length!==zt[a].ctBytes)return console.error(`Wallet::decryptMessage() - Ciphertext length mismatch: got ${r.length}, expected ${i.ctBytes}`),null;let e=this._deriveMlKemKeypair(a);if(!e)return console.error(`Wallet::decryptMessage() - cannot derive the ML-KEM-${a} identity: wallet has no key`),null;o=e.params,s=e.privkey}let c;try{c=o.kem.decapsulate(r,s)}catch(e){return console.error(`Wallet::decryptMessage() - Decapsulation failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),null}let l;try{l=this.deserializeKey(n)}catch(e){return console.warn(`Wallet::decryptMessage() - Deserialization failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),console.info(`Wallet::decryptMessage() - our shared secret`,c),null}let u;try{u=await this.decryptWithSharedSecret(l,c)}catch(e){return console.warn(`Wallet::decryptMessage() - Decryption failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),console.info(`Wallet::decryptMessage() - our shared secret`,c),console.info(`Wallet::decryptMessage() - deserialized encrypted message`,l),null}try{return new TextDecoder().decode(u)}catch(e){return console.warn(`Wallet::decryptMessage() - Decoding failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),console.info(`Wallet::decryptMessage() - our shared secret`,c),console.info(`Wallet::decryptMessage() - deserialized encrypted message`,l),console.info(`Wallet::decryptMessage() - decrypted Uint8Array`,u),null}}hashShare(e){let t=ce(e,64),n=Uint8Array.from(t.match(/.{2}/g).map(e=>parseInt(e,16)));return this.serializeKey(n)}async encryptStringML(e,t){let n=await this.encryptMessage(e,t);return JSON.stringify({[this.hashShare(t)]:n})}async decryptMyMessageML(e){let t=e[this.hashShare(this.pubkey)];if(!t){let n=this.mlKemParameterSet===1024?768:1024,r=this._deriveMlKemKeypair(n);r&&(t=e[this.hashShare(r.pubkey)])}return t?this._mlkemDecryptToString(t):null}async encryptWithSharedSecret(e,t){let n=crypto.getRandomValues(new Uint8Array(12)),r={name:`AES-GCM`,iv:n},i=await crypto.subtle.importKey(`raw`,t,{name:`AES-GCM`},!1,[`encrypt`]),a=await crypto.subtle.encrypt(r,i,e),o=new Uint8Array(n.length+a.byteLength);return o.set(n),o.set(new Uint8Array(a),n.length),o}async decryptWithSharedSecret(e,t){let n={name:`AES-GCM`,iv:e.slice(0,12)},r=await crypto.subtle.importKey(`raw`,t,{name:`AES-GCM`},!1,[`decrypt`]),i=await crypto.subtle.decrypt(n,r,e.slice(12));return new Uint8Array(i)}},Vt=class extends w{constructor(e=`There is an atom without an index`,t=null,n=null){super(e,t,n),this.name=`AtomIndexException`}},Ht=class extends w{constructor(e=`The molecular hash does not match`,t=null,n=null){super(e,t,n),this.name=`MolecularHashMismatchException`}},Ut=class extends w{constructor(e=`The molecular hash is missing`,t=null,n=null){super(e,t,n),this.name=`MolecularHashMissingException`}},Wt=class extends w{constructor(e=``,t=null,n=null){super(e,t,n),this.name=`PolicyInvalidException`}},Gt=class extends w{constructor(e=`OTS malformed`,t=null,n=null){super(e,t,n),this.name=`SignatureMalformedException`}},Kt=class extends w{constructor(e=`One-time signature (OTS) does not match!`,t=null,n=null){super(e,t,n),this.name=`SignatureMismatchException`}},L=class extends w{constructor(e=`Insufficient balance to make transfer`,t=null,n=null){super(e,t,n),this.name=`TransferBalanceException`}},qt=class extends w{constructor(e=`Token transfer atoms are malformed`,t=null,n=null){super(e,t,n),this.name=`TransferMalformedException`}},Jt=class extends w{constructor(e=`Token slugs for wallets in transfer do not match!`,t=null,n=null){super(e,t,n),this.name=`TransferMismatchedException`}},Yt=class extends w{constructor(e=`Invalid remainder provided`,t=null,n=null){super(e,t,n),this.name=`TransferRemainderException`}},Xt=class extends w{constructor(e=`Sender and recipient(s) cannot be the same`,t=null,n=null){super(e,t,n),this.name=`TransferToSelfException`}},Zt=class extends w{constructor(e=`Token transfer atoms are unbalanced`,t=null,n=null){super(e,t,n),this.name=`TransferUnbalancedException`}},R=class extends w{constructor(e=`Empty meta data.`,t=null,n=null){super(e,t,n),this.name=`MetaMissingException`}},z=class extends w{constructor(e=`Wrong type of token for this isotope`,t=null,n=null){super(e,t,n),this.name=`WrongTokenTypeException`}},Qt=class extends w{constructor(e=`Incorrect BatchId`,t=null,n=null){super(e,t,n),this.name=`BatchIdException`}},$t=class{constructor(e={}){for(let t in e)this[`__${t}`]=e[t]}static toObject(e){return new this(e)}toJSON(){let e={};for(let t of Object.keys(this))t.substring(0,2)===`__`&&(e[t.substring(2,t.length)]=this[t]);return e}},en=class extends w{constructor(e=`An incorrect argument!`,t=null,n=null){super(e,t,n),this.name=`RuleArgumentException`}},B=class extends w{constructor(e=`Code exception`,t=null,n=null){super(e,t,n),this.name=`CodeException`}},tn=class e{constructor({action:e,metaType:t=null,metaId:n=null,meta:r=null,address:i=null,token:a=null,amount:o=null,comparison:s=null}){if(r&&(this.meta=r),!e)throw new en(`Callback structure violated, missing mandatory "action" parameter.`);this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=i,this.__token=a,this.__amount=o,this.__comparison=s}set comparison(e){this.__comparison=e}set amount(e){if(!ee(e))throw new B(`Parameter amount should be a string containing numbers`);this.__amount=e}set token(e){this.__token=e}set address(e){this.__address=e}set meta(e){this.__meta=e instanceof $t?e:$t.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(t){let n=new e({action:t.action});return t.metaType&&(n.metaType=t.metaType),t.metaId&&(n.metaId=t.metaId),t.meta&&(n.meta=t.meta),t.address&&(n.address=t.address),t.token&&(n.token=t.token),t.amount&&(n.amount=t.amount),t.comparison&&(n.comparison=t.comparison),n}toJSON(){let e={action:this.__action};return this.__metaType&&(e.metaType=this.__metaType),this.__metaId&&(e.metaId=this.__metaId),this.__meta&&(e.meta=this.__meta),this.__address&&(e.address=this.__address),this.__token&&(e.token=this.__token),this.__amount&&(e.amount=this.__amount),this.__comparison&&(e.comparison=this.__comparison),e}isReject(){return this._is(`reject`)}isMeta(){return S(Object.keys(this.toJSON()),[`action`,`metaId`,`metaType`,`meta`]).length===4&&this._is(`meta`)}isCollect(){return S(Object.keys(this.toJSON()),[`action`,`address`,`token`,`amount`,`comparison`]).length===5&&this._is(`collect`)}isBuffer(){return S(Object.keys(this.toJSON()),[`action`,`address`,`token`,`amount`,`comparison`]).length===5&&this._is(`buffer`)}isRemit(){return S(Object.keys(this.toJSON()),[`action`,`token`,`amount`]).length===3&&this._is(`remit`)}isBurn(){return S(Object.keys(this.toJSON()),[`action`,`token`,`amount`,`comparison`]).length===4&&this._is(`burn`)}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}},nn=class{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(e=>!e))throw new en(`Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!`);this.__key=e,this.__value=t,this.__comparison=n}static toObject(e){return new this({key:e.key,value:e.value,comparison:e.comparison})}toJSON(){return{key:this.__key,value:this.__value,comparison:this.__comparison}}},rn=class e{constructor({condition:e=[],callback:t=[]}){for(let t of e)if(!(t instanceof nn))throw new en;for(let e of t)if(!(e instanceof tn))throw new en;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof nn?e:nn.toObject(e))}set callback(e){this.__callback.push(e instanceof tn?e:tn.toObject(e))}static toObject(t){if(!t.condition)throw new R(`Rule::toObject() - Incorrect rule format! There is no condition field.`);if(!t.callback)throw new R(`Rule::toObject() - Incorrect rule format! There is no callback field.`);let n=new e({});for(let e of t.condition)n.comparison=e;for(let e of t.callback)n.callback=e;return n}toJSON(){return{condition:this.__condition,callback:this.__callback}}},V=class{static __init(e,t){this.arr=String(t).split(`.`),this.key=this.arr.shift();let n=Number(this.key);Number.isInteger(n)&&(this.key=n),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!Array.isArray(e)&&!(e instanceof Object)?!1:e[this.key]!==void 0}static has(e,t){return this.__init(e,t),this.__next?this.__nextKey===0||this.has(e[this.key],this.arr.join(`.`)):!1}static get(e,t,n=null){return this.__init(e,t),this.__next?this.__nextKey===0?e[this.key]:this.get(e[this.key],this.arr.join(`.`),n):n}static set(e,t,n){let r=t.split(`.`),i=e,a=r.length-1;for(let e=0;e<a;e++){let t=r[e],n=Number(t),a=Number.isInteger(n);(a?n:t in i)||(i[a?n:t]=r[e+1].match(/^\d+$/)?[]:{}),i=i[a?n:t]}let o=r[a],s=Number(o);return i[Number.isInteger(s)?s:o]=n,e}},an=class e{constructor(e){if(e.molecularHash===null)throw new Ut;if(!e.atoms.length)throw new T;for(let t of e.atoms)if(t.index===null)throw new Vt;this.molecule=e}verify(e){return this.molecularHash()&&this.ots()&&this.batchId()&&this.continuId()&&this.isotopeM()&&this.isotopeT()&&this.isotopeC()&&this.isotopeU()&&this.isotopeI()&&this.isotopeR()&&this.isotopeP()&&this.isotopeA()&&this.isotopeB()&&this.isotopeF()&&this.isotopeV(e)}continuId(){if(this.molecule.atoms[0].token===`USER`&&this.molecule.getIsotopes(`I`).length<1)throw new T(`Check::continuId() - Molecule is missing required ContinuID Atom!`);return!0}batchId(){if(this.molecule.atoms.length>0){let e=this.molecule.atoms[0];if(e.isotope===`V`&&e.batchId!==null){let t=this.molecule.getIsotopes(`V`),n=t[t.length-1];if(e.batchId!==n.batchId)throw new Qt;for(let e of t)if(e.batchId===null)throw new Qt}return!0}throw new Qt}isotopeI(){for(let e of this.molecule.getIsotopes(`I`)){if(e.token!==`USER`)throw new z(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new Vt(`Check::isotopeI() - Isotope "${e.isotope}" Atoms must have a non-zero index!`)}return!0}isotopeU(){for(let e of this.molecule.getIsotopes(`U`)){if(e.token!==`AUTH`)throw new z(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new Vt(`Check::isotopeU() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeM(){let e=[`readPolicy`,`writePolicy`];for(let t of this.molecule.getIsotopes(`M`)){if(t.meta.length<1)throw new R;if(t.token!==`USER`)throw new z(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);let n=x.aggregateMeta(t.meta);for(let t of e){let r=n[t];if(r){r=JSON.parse(r);for(let[t,i]of Object.entries(r))if(!e.includes(t)){if(!Object.keys(n).includes(t))throw new Wt(`${t} is missing from the meta.`);for(let e of i)if(!I.isBundleHash(e)&&![`all`,`self`].includes(e))throw new Wt(`${e} does not correspond to the format of the policy.`)}}}}return!0}isotopeC(){for(let e of this.molecule.getIsotopes(`C`)){if(e.token!==`USER`)throw new z(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new Vt(`Check::isotopeC() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeT(){for(let e of this.molecule.getIsotopes(`T`)){let t=e.aggregatedMeta();if(String(e.metaType).toLowerCase()===`wallet`){for(let e of[`position`,`bundle`])if(!Object.prototype.hasOwnProperty.call(t,e)||!t[e])throw new R(`Check::isotopeT() - Required meta field "${e}" is missing!`)}for(let e of[`token`])if(!Object.prototype.hasOwnProperty.call(t,e)||!t[e])throw new R(`Check::isotopeT() - Required meta field "${e}" is missing!`);if(e.token!==`USER`)throw new z(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new Vt(`Check::isotopeT() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeR(){for(let e of this.molecule.getIsotopes(`R`)){let t=e.aggregatedMeta();if(t.policy){let e=JSON.parse(t.policy);if(!Object.keys(e).every(e=>[`read`,`write`].includes(e)))throw new R(`Check::isotopeR() - Mixing rules with politics!`)}if(t.rule){let e=JSON.parse(t.rule);if(!Array.isArray(e))throw new R(`Check::isotopeR() - Incorrect rule format!`);for(let t of e)rn.toObject(t);if(e.length<1)throw new R(`Check::isotopeR() - No rules!`)}}return!0}isotopeP(){for(let e of this.molecule.getIsotopes(`P`)){if(e.token!==`USER`)throw new z(`Check::isotopeP() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);let t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,`peerHost`)||!t.peerHost)throw new R(`Check::isotopeP() - Required meta field "peerHost" is missing!`)}return!0}isotopeA(){for(let e of this.molecule.getIsotopes(`A`)){if(e.token!==`USER`)throw new z(`Check::isotopeA() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(!e.metaType)throw new R(`Check::isotopeA() - Required field "metaType" is missing!`);if(!e.metaId)throw new R(`Check::isotopeA() - Required field "metaId" is missing!`);let t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,`action`)||!t.action)throw new R(`Check::isotopeA() - Required meta field "action" is missing!`)}return!0}isotopeB(){let e=this.molecule.getIsotopes(`B`);if(e.length===0)return!0;for(let t of e){if(!t.metaType||t.metaType!==`walletBundle`)throw new R(`Check::isotopeB() - B-isotope atoms must have metaType "walletBundle"!`);if(!t.metaId)throw new R(`Check::isotopeB() - B-isotope atoms must have a metaId!`);let e=Number(t.value);if(Number.isNaN(e))throw new qt(`Check::isotopeB() - B-isotope atom value is not a valid number!`)}let t=this.molecule.getIsotopes(`V`);if(t.length>0){let n=0;for(let r of[...t,...e]){let e=Number(r.value);Number.isNaN(e)||(n+=e)}if(n!==0)throw new Zt(`Check::isotopeB() - V+B atom values do not balance to zero!`)}return!0}isotopeF(){let e=this.molecule.getIsotopes(`F`);if(e.length===0)return!0;for(let t of e){if(!t.metaType||t.metaType!==`walletBundle`)throw new R(`Check::isotopeF() - F-isotope atoms must have metaType "walletBundle"!`);if(!t.metaId)throw new R(`Check::isotopeF() - F-isotope atoms must have a metaId!`);let e=Number(t.value);if(Number.isNaN(e))throw new qt(`Check::isotopeF() - F-isotope atom value is not a valid number!`);if(e<0)throw new qt(`Check::isotopeF() - F-isotope atom value must not be negative!`)}let t=this.molecule.getIsotopes(`V`);if(t.length>0){let n=0;for(let r of[...t,...e]){let e=Number(r.value);Number.isNaN(e)||(n+=e)}if(n!==0)throw new Zt(`Check::isotopeF() - V+F atom values do not balance to zero!`)}return!0}isotopeV(e=null){let t=this.molecule.getIsotopes(`V`);if(t.length===0)return!0;let n=this.molecule.getIsotopes(`B`).length>0||this.molecule.getIsotopes(`F`).length>0,r=this.molecule.atoms[0];if(!n&&r.isotope===`V`&&t.length===2){let e=t[t.length-1];if(r.token!==e.token)throw new Jt;if(e.value<0)throw new qt;if(Number(r.value)+Number(e.value)!==0)throw new Zt;return!0}let i=0,a=0;for(let e in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,e)){let t=this.molecule.atoms[e];if(t.isotope!==`V`)continue;if(a=t.value*1,Number.isNaN(a))throw TypeError(`Invalid isotope "V" values`);if(t.token!==r.token)throw new Jt;if(e>0){if(a<0)throw new qt;if(t.walletAddress===r.walletAddress)throw new Xt}i+=a}if(!n&&i!==0)throw new Zt;if(e){if(a=r.value*1,Number.isNaN(a))throw TypeError(`Invalid isotope "V" values`);let t=Number(e.balance)+a;if(t<0)throw new L;if(!n&&t!==i)throw new Yt}else if(a!==0)throw new Yt;return!0}molecularHash(){if(this.molecule.molecularHash!==E.hashAtoms({atoms:this.molecule.atoms}))throw new Ht;return!0}ots(){let e=this.molecule.normalizedHash(),t=this.molecule.atoms.map(e=>e.otsFragment).reduce((e,t)=>e+t);if(t.length!==2048&&(t=y(t),t.length!==2048))throw new Gt;let n=p(t,128),r=``;for(let t in n){let i=n[t];for(let n=0,r=8+e[t];n<r;n++)i=new c.default(`SHAKE256`,`TEXT`).update(i).getHash(`HEX`,{outputLen:512});r+=i}let i=new c.default(`SHAKE256`,`TEXT`);i.update(r);let a=i.getHash(`HEX`,{outputLen:8192}),o=new c.default(`SHAKE256`,`TEXT`);o.update(a);let s=o.getHash(`HEX`,{outputLen:256}),l=this.molecule.atoms[0],u=l.walletAddress,d=V.get(l.aggregatedMeta(),`signingWallet`);if(d&&(u=V.get(JSON.parse(d),`address`)),s!==u)throw new Kt;return!0}static fromServerData({molecularHash:e,bundleHash:t,cellSlug:n=null,status:r=null,createdAt:i=null,atoms:a=[]}){let o=a.map(e=>{let t=[];if(e.metasJson)try{let n=JSON.parse(e.metasJson);Array.isArray(n)?t=n:n&&typeof n==`object`&&(t=Object.entries(n).map(([e,t])=>({key:e,value:t})))}catch{t=[]}return{position:e.position||null,walletAddress:e.walletAddress||null,isotope:e.isotope||null,token:e.tokenSlug||e.token||null,value:e.value==null?null:String(e.value),batchId:e.batchId||null,metaType:e.metaType||null,metaId:e.metaId||null,meta:t,index:e.index==null?null:e.index,otsFragment:e.otsFragment||null,createdAt:e.createdAt||null}});return cn.fromJSON({molecularHash:e,bundle:t,cellSlug:n,status:r,createdAt:i,atoms:o})}static verifyFromServerData(t){try{let n=e.fromServerData(t);return new e(n).verify(),{molecularHash:t.molecularHash,verified:!0,error:null}}catch(e){return{molecularHash:t.molecularHash||null,verified:!1,error:e.message||String(e)}}}},on=class extends w{constructor(e=`Insufficient balance for requested transfer`,t=null,n=null){super(e,t,n),this.name=`BalanceInsufficientException`}},sn=class extends w{constructor(e=`Amount cannot be negative!`,t=null,n=null){super(e,t,n),this.name=`NegativeAmountException`}},cn=class e{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:r=null,cellSlug:i=null,version:a=null,continuIdPosition:o=null,mlKemParameterSet:s=null}){this.mlKemParameterSet=s||n&&n.mlKemParameterSet||1024,this.status=null,this.molecularHash=null,this.createdAt=String(+new Date),this.cellSlugOrigin=this.cellSlug=i,this.secret=e,this.bundle=t,this.sourceWallet=n,this.continuIdPosition=o,this.atoms=[],this.parentHashes=[],a!==null&&Object.prototype.hasOwnProperty.call(oe,a)&&(this.version=String(a)),(r||n)&&(this.remainderWallet=r||I.create({secret:e,bundle:t,token:n.token,batchId:n.batchId,characters:n.characters,mlKemParameterSet:this.mlKemParameterSet}))}withParentHashes(e){return this.parentHashes=Array.isArray(e)?[...e]:[],this}get cellSlugDelimiter(){return`.`}static isotopeFilter(e,t){return Array.isArray(e)||(e=[e]),t.filter(t=>e.includes(t.isotope))}static generateNextAtomIndex(e){return e.length}static jsonToObject(t){let n=Object.assign(new e({}),JSON.parse(t)),r=Object.keys(new e({}));if(!Array.isArray(n.atoms))throw new T;for(let e in Object.keys(n.atoms)){n.atoms[e]=E.jsonToObject(JSON.stringify(n.atoms[e]));for(let t of[`position`,`walletAddress`,`isotope`])if(n.atoms[e].isotope.toLowerCase()!==`r`&&(n.atoms[e][t]===void 0||n.atoms[e][t]===null))throw new T(`MolecularStructure::jsonToObject() - Required Atom properties are missing!`)}for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&!r.includes(e)&&delete n[e];return n.atoms=E.sortAtoms(n.atoms),n}static enumerate(e){let t={0:-8,1:-7,2:-6,3:-5,4:-4,5:-3,6:-2,7:-1,8:0,9:1,a:2,b:3,c:4,d:5,e:6,f:7,g:8},n=[],r=e.toLowerCase().split(``);for(let e=0,i=r.length;e<i;++e){let i=r[e];t[i]!==void 0&&(n[e]=t[i])}return n}static normalize(e){let t=e.reduce((e,t)=>e+t),n=t<0;for(;t<0||t>0;)for(let r of Object.keys(e))if((n?e[r]<8:e[r]>-8)&&(n?(++e[r],++t):(--e[r],--t),t===0))break;return e}getIsotopes(t){return e.isotopeFilter(t,this.atoms)}generateIndex(){return e.generateNextAtomIndex(this.atoms)}fill(e){for(let t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,e.index=this.generateIndex(),e.version=this.version,this.atoms.push(e),this.atoms=E.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!==`USER`)&&(this.remainderWallet=I.create({secret:this.secret,bundle:this.bundle,mlKemParameterSet:this.mlKemParameterSet}));let e={};return this.continuIdPosition?e.previousPosition=this.continuIdPosition:this.sourceWallet&&this.sourceWallet.position&&(e.previousPosition=this.sourceWallet.position),this.remainderWallet.pubkey&&(e.pubkey=this.remainderWallet.pubkey),this.remainderWallet.characters&&(e.characters=this.remainderWallet.characters),this.addAtom(E.create({isotope:`I`,wallet:this.remainderWallet,metaType:`walletBundle`,metaId:this.remainderWallet.bundle,meta:new C(e)})),this}addPolicyAtom({metaType:e,metaId:t,meta:n={},policy:r={}}){let i=new C(n);return i.addPolicy(r),this.addAtom(E.create({wallet:this.sourceWallet,isotope:`R`,metaType:e,metaId:t,meta:i})),this}fuseToken(e,t){let n=e.length;if(this.sourceWallet.balance-n<0)throw new on;return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-n})),this.addAtom(E.create({isotope:`F`,wallet:t,value:1,metaType:`walletBundle`,metaId:t.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new sn(`Molecule::burnToken() - Amount to burn must be positive!`);if(this.sourceWallet.balance-e<0)throw new on;let n=new I({bundle:`0000000000000000000000000000000000000000000000000000000000000000`,token:this.sourceWallet.token,mlKemParameterSet:this.mlKemParameterSet});return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(E.create({isotope:`V`,wallet:n,value:e,metaType:`walletBundle`,metaId:n.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-e,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}replenishToken({amount:e,units:t=[]}){if(e<0)throw new sn(`Molecule::replenishToken() - Amount to replenish must be positive!`);if(t.length){t=I.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(let e of t)this.remainderWallet.tokenUnits.push(e);this.remainderWallet.balance=String(this.remainderWallet.tokenUnits.length),this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=String(this.sourceWallet.tokenUnits.length)}else this.remainderWallet.balance=String(Number(this.sourceWallet.balance)+e),this.sourceWallet.balance=String(e);return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:Number(this.sourceWallet.balance)})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:Number(this.remainderWallet.balance),metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new on;return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(E.create({isotope:`V`,wallet:e,value:t,metaType:`walletBundle`,metaId:e.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initValues({recipientWallets:e,amounts:t}){let n=t.reduce((e,t)=>e+Number(t),0);if(this.sourceWallet.balance-n<0)throw new on;return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),e.forEach((e,n)=>{this.addAtom(E.create({isotope:`V`,wallet:e,value:t[n],metaType:`walletBundle`,metaId:e.bundle}))}),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initDepositBuffer({amount:e,tradeRates:t}){if(this.sourceWallet.balance-e<0)throw new on;let n=I.create({secret:this.secret,bundle:this.bundle,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,mlKemParameterSet:this.mlKemParameterSet});return n.tradeRates=t,this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(E.create({isotope:`B`,wallet:n,value:e,metaType:`walletBundle`,metaId:this.sourceWallet.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-e,metaType:`walletBundle`,metaId:this.sourceWallet.bundle})),this}initWithdrawBuffer({recipients:e,signingWallet:t=null}){let n=0;for(let t of Object.values(e||{}))n+=t;if(this.sourceWallet.balance-n<0)throw new on;let r=new C;t&&r.setSigningWallet(t),this.addAtom(E.create({isotope:`B`,wallet:this.sourceWallet,value:-this.sourceWallet.balance,meta:r,metaType:`walletBundle`,metaId:this.sourceWallet.bundle}));for(let[t,n]of Object.entries(e||{}))this.addAtom(new E({isotope:`V`,token:this.sourceWallet.token,value:n,batchId:this.sourceWallet.batchId?le({}):null,metaType:`walletBundle`,metaId:t}));return this.addAtom(E.create({isotope:`B`,wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initTokenCreation({recipientWallet:e,amount:t,meta:n}){let r=new C(n);return r.setMetaWallet(e),this.addAtom(E.create({isotope:`C`,wallet:this.sourceWallet,value:t,metaType:`token`,metaId:e.token,meta:r,batchId:e.batchId})),this.addContinuIdAtom(),this}createRule({metaType:e,metaId:t,rule:n,policy:r={}}){let i=[];for(let e of n)i.push(e instanceof rn?e:rn.toObject(e));let a=new C({rule:JSON.stringify(i)});return a.addPolicy(r),this.addAtom(E.create({isotope:`R`,wallet:this.sourceWallet,metaType:e,metaId:t,meta:a})),this.addContinuIdAtom(),this}initWalletCreation(e,t=null){t||=new C,t.setMetaWallet(e);let n=E.create({isotope:`C`,wallet:this.sourceWallet,metaType:`wallet`,metaId:e.address,meta:t,batchId:e.batchId});return this.addAtom(n),this.addContinuIdAtom(),this}initShadowWalletClaim(e){let t=new C().setShadowWalletClaim(!0);return this.initWalletCreation(e,t)}initIdentifierCreation({type:e,contact:t,code:n}){let r={code:n,hash:D(t.trim(),`Molecule::initIdentifierCreation`)};return this.addAtom(E.create({isotope:`C`,wallet:this.sourceWallet,metaType:`identifier`,metaId:e,meta:new C(r)})),this.addContinuIdAtom(),this}initMeta({meta:e,metaType:t,metaId:n,policy:r}){return this.addAtom(E.create({isotope:`M`,wallet:this.sourceWallet,metaType:t,metaId:n,meta:new C(e)})),r&&Object.keys(r).length>0&&this.addPolicyAtom({metaType:t,metaId:n,meta:e,policy:r}),this.addContinuIdAtom(),this}initPeering({host:e}){return this.addAtom(E.create({isotope:`P`,wallet:this.sourceWallet,metaType:`walletBundle`,metaId:this.bundle,meta:new C({peerHost:e})})),this.addContinuIdAtom(),this}initAppendRequest({metaType:e,metaId:t,action:n,meta:r={}}){return this.addAtom(E.create({isotope:`A`,wallet:this.sourceWallet,metaType:e,metaId:t,meta:new C({action:n,...r})})),this.addContinuIdAtom(),this}initTokenRequest({token:e,amount:t,metaType:n,metaId:r,meta:i={},batchId:a=null}){return i.token=e,i.amount=String(t),this.addAtom(E.create({isotope:`T`,wallet:this.sourceWallet,value:t,metaType:n,metaId:r,meta:new C(i),batchId:a})),this.addContinuIdAtom(),this}initAuthorization({meta:e}){return this.addAtom(E.create({isotope:`U`,wallet:this.sourceWallet,meta:new C(e)})),this.addContinuIdAtom(),this}sign({bundle:e=null,anonymous:t=!1,compressed:n=!0}={}){if(this.atoms.length===0||this.atoms.filter(e=>!(e instanceof E)).length!==0)throw new T;!t&&!this.bundle&&(this.bundle=e||D(this.secret,`Molecule::sign`)),this.molecularHash=E.hashAtoms({atoms:this.atoms});let r=this.atoms[0],i=r.position,a=V.get(r.aggregatedMeta(),`signingWallet`);if(a&&(i=V.get(JSON.parse(a),`position`)),!i)throw new Gt(`Signing wallet must have a position!`);let o=p(I.generateKey({secret:this.secret,token:r.token,position:r.position}),128),s=this.normalizedHash(),l=``;for(let e in o){let t=o[e];for(let n=0,r=8-s[e];n<r;n++)t=new c.default(`SHAKE256`,`TEXT`).update(t).getHash(`HEX`,{outputLen:512});l+=t}n&&(l=v(l));let u=p(l,Math.ceil(l.length/this.atoms.length)),d=null;for(let e=0,t=u.length;e<t;e++)this.atoms[e].otsFragment=u[e],d=this.atoms[e].position;return d}signSync(e={}){return this.sign(e)}cellSlugBase(){return(this.cellSlug||``).split(this.cellSlugDelimiter)[0]}toJSON(e={}){let{includeValidationContext:t=!1,includeOtsFragments:n=!0}=e;try{let e={status:this.status,molecularHash:this.molecularHash,createdAt:this.createdAt,cellSlug:this.cellSlug,bundle:this.bundle,atoms:this.atoms.map(e=>e.toJSON({includeOtsFragments:n}))};return this.parentHashes&&this.parentHashes.length>0&&(e.parentHashes=this.parentHashes),t&&(e.cellSlugOrigin=this.cellSlugOrigin,e.version=this.version,this.sourceWallet&&(e.sourceWallet={address:this.sourceWallet.address,position:this.sourceWallet.position,token:this.sourceWallet.token,balance:this.sourceWallet.balance||`0`,bundle:this.sourceWallet.bundle,batchId:this.sourceWallet.batchId||null,characters:this.sourceWallet.characters||`BASE64`,pubkey:this.sourceWallet.pubkey||null,tokenUnits:this.sourceWallet.tokenUnits||[],tradeRates:this.sourceWallet.tradeRates||{},molecules:this.sourceWallet.molecules||{}}),this.remainderWallet&&(e.remainderWallet={address:this.remainderWallet.address,position:this.remainderWallet.position,token:this.remainderWallet.token,balance:this.remainderWallet.balance||`0`,bundle:this.remainderWallet.bundle,batchId:this.remainderWallet.batchId||null,characters:this.remainderWallet.characters||`BASE64`,pubkey:this.remainderWallet.pubkey||null,tokenUnits:this.remainderWallet.tokenUnits||[],tradeRates:this.remainderWallet.tradeRates||{},molecules:this.remainderWallet.molecules||{}})),e}catch(e){throw Error(`Molecule serialization failed: ${e.message}`)}}static fromJSON(t,n={}){let{includeValidationContext:r=!1,validateStructure:i=!0}=n;try{let n=typeof t==`string`?JSON.parse(t):t;if(i&&(!n.molecularHash||!Array.isArray(n.atoms)))throw Error(`Invalid molecule data: missing molecularHash or atoms array`);let a=new e({secret:null,bundle:n.bundle||null,cellSlug:n.cellSlug||null,version:n.version||null});return a.status=n.status,a.molecularHash=n.molecularHash,a.createdAt=n.createdAt||String(+new Date),a.cellSlugOrigin=n.cellSlugOrigin,a.parentHashes=Array.isArray(n.parentHashes)?[...n.parentHashes]:[],Array.isArray(n.atoms)&&(a.atoms=n.atoms.map((e,t)=>{try{return E.fromJSON(e)}catch(e){throw Error(`Failed to reconstruct atom ${t}: ${e.message}`)}})),r&&(n.sourceWallet&&(a.sourceWallet=new I({secret:null,token:n.sourceWallet.token,position:n.sourceWallet.position,bundle:n.sourceWallet.bundle,batchId:n.sourceWallet.batchId,characters:n.sourceWallet.characters,mlKemParameterSet:a.mlKemParameterSet}),a.sourceWallet.balance=String(n.sourceWallet.balance==null?0:n.sourceWallet.balance),a.sourceWallet.address=n.sourceWallet.address,n.sourceWallet.pubkey&&(a.sourceWallet.pubkey=n.sourceWallet.pubkey),a.sourceWallet.tokenUnits=n.sourceWallet.tokenUnits||[],a.sourceWallet.tradeRates=n.sourceWallet.tradeRates||{},a.sourceWallet.molecules=n.sourceWallet.molecules||{}),n.remainderWallet&&(a.remainderWallet=new I({secret:null,token:n.remainderWallet.token,position:n.remainderWallet.position,bundle:n.remainderWallet.bundle,batchId:n.remainderWallet.batchId,characters:n.remainderWallet.characters,mlKemParameterSet:a.mlKemParameterSet}),a.remainderWallet.balance=String(n.remainderWallet.balance==null?0:n.remainderWallet.balance),a.remainderWallet.address=n.remainderWallet.address,n.remainderWallet.pubkey&&(a.remainderWallet.pubkey=n.remainderWallet.pubkey),a.remainderWallet.tokenUnits=n.remainderWallet.tokenUnits||[],a.remainderWallet.tradeRates=n.remainderWallet.tradeRates||{},a.remainderWallet.molecules=n.remainderWallet.molecules||{})),a}catch(e){throw Error(`Molecule deserialization failed: ${e.message}`)}}check(e=null){return new an(this).verify(e)}normalizedHash(){return e.normalize(e.enumerate(this.molecularHash))}},ln=class e{constructor({token:e,expiresAt:t,encrypt:n,pubkey:r}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=r,this.$__encrypt=n}static create(t,n){let r=new e(t);return r.setWallet(n),r}static resolveMlKemParameterSet(e){let t=e.wallet&&e.wallet.mlKemParameterSet;return t?Number(t):I.mlKemParameterSetFromPubkey(e.pubkey)||768}static restore(t,n){let r=new I({secret:n,token:`AUTH`,position:t.wallet.position,characters:t.wallet.characters,mlKemParameterSet:e.resolveMlKemParameterSet(t)});return e.create({token:t.token,expiresAt:t.expiresAt,pubkey:t.pubkey,encrypt:t.encrypt},r)}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters,mlKemParameterSet:this.$__wallet.mlKemParameterSet}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return this.$__expiresAt*1e3-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}},H=class e extends w{constructor(e=`Secret storage operation failed`,t=null,n=null){super(e,t,n),this.name=`SecretStorageException`}static notFound(t){return new e(`Secret not found for bundle: ${t}`)}static decryptionFailed(t=`Invalid passphrase or corrupted ciphertext`){return new e(`Failed to decrypt master secret: ${t}`)}static unavailable(t,n=`Hardware or API not accessible`){return new e(`Secret storage provider '${t}' is unavailable: ${n}`)}},un=new TextEncoder;function U(e){if(e instanceof Uint8Array)e.fill(0);else if(Array.isArray(e))for(let t=0;t<e.length;t++)e[t]=0}async function dn(e,t){try{return await t(e)}finally{U(e)}}async function fn(e,t){let n=un.encode(e);try{return await t(e)}finally{U(n)}}function pn(e,t){let n=typeof e==`string`?un.encode(e):e,r=typeof t==`string`?un.encode(t):t,i=n.length===r.length?0:1,a=Math.min(n.length,r.length);for(let e=0;e<a;e++)i|=(n[e]??0)^(r[e]??0);return typeof e==`string`&&U(n),typeof t==`string`&&U(r),i===0}var mn=class{constructor(){this.providerType=`memory`,this.secrets=new Map}isHardwareBacked(){return!1}async isAvailable(){return!0}async storeSecret(e,t,n={}){if(!e)throw new H(`Bundle hash cannot be empty`);if(!t)throw new H(`Secret cannot be empty`);let r={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:this.providerType};this.secrets.set(e,{secret:t,metadata:r})}async retrieveSecret(e){let t=this.secrets.get(e);return t?t.secret:null}async deleteSecret(e){return this.secrets.delete(e)}async hasSecret(e){return this.secrets.has(e)}async listSecrets(){return Array.from(this.secrets.values()).map(e=>({...e.metadata}))}async withSecret(e,t){let n=this.secrets.get(e);if(!n)throw H.notFound(e);return fn(n.secret,t)}clear(){this.secrets.clear()}},hn=10**18,gn=class e{static val(e){return Math.abs(e*hn)<1?0:e}static cmp(t,n,r=!1){let i=e.val(t)*hn,a=e.val(n)*hn;return Math.abs(i-a)<1?0:i>a?1:-1}static equal(t,n){return e.cmp(t,n)===0}},W=class extends w{constructor(e=`GraphQL did not provide a valid response.`,t=null,n=null){super(e,t,n),this.name=`InvalidResponseException`}},_n=class extends w{constructor(e=`Authorization token missing or invalid.`,t=null,n=null){super(e,t,n),this.name=`UnauthenticatedException`}},G=class{constructor({query:e,json:t,dataKey:n=null}){if(this.dataKey=n,this.errorKey=`exception`,this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,this.$__response===void 0||this.$__response===null)throw new W;if(V.has(this.$__response,this.errorKey)){let e=V.get(this.$__response,this.errorKey);throw String(e).includes(`Unauthenticated`)?new _n:new W}if(this.$__response.errors&&Array.isArray(this.$__response.errors)&&this.$__response.errors.length>0){let e=this.$__response.errors[0].message||`Unknown GraphQL error`;throw e.includes(`Unauthenticated`)?new _n:new W(`GraphQL Error: ${e}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new W(`Response has no data field`);if(!V.has(this.response(),this.dataKey))throw new W(`Missing expected field: ${this.dataKey}`);return V.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){return!this.$__response?.errors?.length}error(){return this.$__response?.errors?.length?this.$__response.errors[0].message||`Unknown error`:null}reason(){return this.error()}toValidationResult(){return this.success()&&this.payload()!==null?{success:!0,data:this.payload(),warnings:[]}:{success:!1,error:{message:this.reason()||`Unknown error`,context:this.constructor.name,details:this.$__response?.errors||[]}}}onSuccess(e){if(this.success()&&this.payload()!==null)try{e(this.payload())}catch(e){console.warn(`Response.onSuccess callback failed:`,e)}return this}onFailure(e){if(!this.success())try{e(this.reason()||`Unknown error`)}catch(e){console.warn(`Response.onFailure callback failed:`,e)}return this}debug(e=null){let t=e?`[${e}]`:`[${this.constructor.name}]`;return this.success()?console.debug(`${t} Success:`,{payload:this.payload(),query:this.$__query?.constructor?.name,dataKey:this.dataKey}):console.debug(`${t} Failure:`,{error:this.reason(),errors:this.$__response?.errors,rawData:this.$__response}),this}toPromise(){return this.success()&&this.payload()!==null?Promise.resolve(this.payload()):Promise.reject(Error(this.reason()||`Unknown error`))}map(e){if(this.success()&&this.payload()!==null)try{let t=e(this.payload()),n=Object.create(Object.getPrototypeOf(this));return Object.assign(n,this),n.$__payload=t,n}catch(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this),t.$__response={errors:[{message:`Mapping failed: ${e.message}`}]},t}return this}},K=class{constructor(e,t){this.client=e,this.knishIOClient=t,this.$__variables=null,this.$__query=null,this.$__response=null,this.$__request=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new G({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new B(`Query::createQuery() - Node URI was not initialized for this client instance!`);if(this.$__query===null)throw new B(`Query::createQuery() - GraphQL subscription was not initialized!`);return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null,context:t={}}){this.$__request=this.createQuery({variables:e});let n={...t,...this.createQueryContext()};try{let e=await this.client.query({...this.$__request,context:n});return this.$__response=await this.createResponseRaw(e),this.$__response}catch(e){if(e.name===`AbortError`)return this.knishIOClient.log(`warn`,`Query was cancelled`),new G({query:this,json:{data:null,errors:[{message:`Query was cancelled`}]}});throw e}}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}createQueryContext(){return{}}},vn=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ContinuId`})}payload(){let e=null,t=this.data();return t&&(e=new I({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=String(t.amount==null?0:t.amount)),e}},yn=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query ($bundle: String!) {
2
+ `):i+=` `);return i}static toUint8Array(e){let t=e.toLowerCase().replace(/\s/g,``);t.length%2==1&&(t=`0${t}`);let n=new Uint8Array(Math.floor(t.length/2)),r=-1;for(let e=0;e<t.length;++e){let i=t[e],a=[`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`a`,`b`,`c`,`d`,`e`,`f`].indexOf(i);if(a===-1)throw Error(`unexpected character`);r===-1?r=16*a:(n[Math.floor(e/2)]=r+a,r=-1)}return n}};String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,``)}),String.prototype.toCamelCase||(String.prototype.toCamelCase=function(){return this.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g,(e,t)=>t.toUpperCase())}),String.prototype.toSnakeCase||(String.prototype.toSnakeCase=function(){return this.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)});function p(e,t){let n=Math.ceil(e.length/t),r=[];for(let i=0,a=0;i<n;++i,a+=t)r[i]=e.substr(a,t);return r}function m(e=256,t=`abcdef0123456789`){let n=new Uint8Array(e);crypto.getRandomValues(n);let r=``;for(let i=0;i<e;i++)r+=t.charAt(n[i]%t.length);return r}function h(e,t,n,r,i){if(r||=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~\`!@#$%^&*()-_=+[{]}\\|;:'",<.>/?¿¡`,i||=r,t>r.length||n>i.length)return console.warn(`Strings::charsetBaseConvert() - Can't convert`,e,`to base`,n,`greater than symbol table length. src-table:`,r.length,`dest-table:`,i.length),!1;let a=BigInt(0);for(let n=0;n<e.length;n++)a=a*BigInt(t)+BigInt(r.indexOf(e.charAt(n)));let o=``;for(;a>0;){let e=a%BigInt(n);o=i.charAt(Number(e))+o,a/=BigInt(n)}return o||`0`}function g(e){return f.toHex(e,{})}function _(e){return f.toUint8Array(e)}function v(e){let t=_(e);if(typeof Buffer<`u`)return Buffer.from(t).toString(`base64`);let n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));return btoa(n)}function y(e){if(typeof Buffer<`u`)return g(new Uint8Array(Buffer.from(e,`base64`)));let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return g(n)}function b(e){return/^[A-F0-9]+$/i.test(e)}function ee(e){return(typeof e==`number`||typeof e==`string`&&e.trim()!==``)&&!isNaN(e)}var x=class{static normalizeMeta(e){if(Array.isArray(e))return e.map(e=>({key:e.key,value:e.value==null?null:String(e.value)}));let t=[];for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let r=e[n];t.push({key:n,value:r==null?null:String(r)})}return t}static aggregateMeta(e){let t={};if(Array.isArray(e))for(let n of e)t[n.key]=n.value;else t=e;return t}};function te(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function ne(e,t){let n,r,i,a=[Array,Date,Number,String,Boolean],o=Object.prototype.toString;for(t||=[],n=0;n<t.length;n+=2)e===t[n]&&(r=t[n+1]);if(!r&&e&&typeof e==`object`){for(r={},n=0;n<a.length;n++)o.call(e)===o.call(i=new a[n](e))&&(r=n?i:[]);for(n in t.push(e,r),e)t.hasOwnProperty.call(e,n)&&(r[n]=ne(e[n],t))}return r||e}function re(...e){return[].concat(...e.map((t,n)=>{let r=e.slice(0);r.splice(n,1);let i=[...new Set([].concat(...r))];return t.filter(e=>!i.includes(e))}))}function S(...e){return e.reduce((e,t)=>e.filter(e=>t.includes(e)))}var ie=class e{constructor(t={},n={}){this.policy=e.normalizePolicy(t),this.fillDefault(n)}static normalizePolicy(e={}){let t={};for(let[n,r]of Object.entries(e))if(r!==null&&[`read`,`write`].includes(n)){t[n]={};for(let[e,i]of Object.entries(r))t[n][e]=i}return t}fillDefault(e={}){let t=Array.from(this.policy).filter(e=>e.action===`read`),n=Array.from(this.policy).filter(e=>e.action===`write`);for(let[r,i]of Object.entries({read:t,write:n})){let t=i.map(e=>e.key);this.policy[r]||(this.policy[r]={});for(let n of re(e,t))this.policy[r][n]||(this.policy[r][n]=r===`write`&&![`characters`,`pubkey`].includes(n)?[`self`]:[`all`])}}get(){return this.policy}toJson(){return JSON.stringify(this.get())}},C=class{constructor(e=[]){this.meta=x.normalizeMeta(e)}merge(e){return this.meta=Array.from(new Set([...this.meta,...x.normalizeMeta(e)])),this}addContext(e=null){return this}setAtomWallet(e){let t={};return e.tokenUnits&&e.tokenUnits.length&&(t.tokenUnits=JSON.stringify(e.getTokenUnitsData())),e.tradeRates&&e.tradeRates.length&&(t.tradeRates=JSON.stringify(e.tradeRates)),Object.keys(t).length>0&&this.merge(t),this}setMetaWallet(e){return this.merge({walletTokenSlug:e.token,walletBundleHash:e.bundle,walletAddress:e.address,walletPosition:e.position,walletBatchId:e.batchId,walletPubkey:e.pubkey,walletCharacters:e.characters}),this}setShadowWalletClaim(e){return this.merge({shadowWalletClaim:e*1}),this}setSigningWallet(e){return this.merge({signingWallet:JSON.stringify({tokenSlug:e.token,bundleHash:e.bundle,address:e.address,position:e.position,pubkey:e.pubkey,characters:e.characters})}),this}addPolicy(e){let t=new ie(e,Object.keys(this.meta));return this.merge({policy:t.toJson()}),this}get(){return this.meta}},w=class extends TypeError{constructor(e=null,t=null,n=null){if(super(e,t,n),e===null)throw new this(`Unknown ${this.constructor.name}`);this.name=`BaseException`}toString(){return`${this.name}: ${this.message}.\nStack:\n${this.stack}`}},T=class extends w{constructor(e=`The molecule does not contain atoms`,t=null,n=null){super(e,t,n),this.name=`AtomsMissingException`}},ae=class e{static create(e){let t={};for(let n of Object.keys(e))Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return new this(t)}static structure(t){switch(Object.prototype.toString.call(t)){case`[object Array]`:{let n=[];for(let r in t)n.push(e.isStructure(t[r])?e.structure(t[r]):t[r]);return n}case`[object Object]`:{let n=[],r=Object.keys(t).sort((e,t)=>e===t?0:e<t?-1:1);for(let i of r)if(Object.prototype.hasOwnProperty.call(t,i)){let r={};r[i]=e.isStructure(t[i])?e.structure(t[i]):t[i],n.push(r)}if(n.length>0)return n;break}}return t}static isStructure(e){return[`[object Object]`,`[object Array]`].includes(Object.prototype.toString.call(e))}view(){return e.structure(this)}},oe={4:class extends ae{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:r=null,value:i=null,batchId:a=null,metaType:o=null,metaId:s=null,meta:c=null,index:l=null,createdAt:u=null,version:d=null}){super(),this.position=e,this.walletAddress=t,this.isotope=n,this.token=r,this.value=i,this.batchId=a,this.metaType=o,this.metaId=s,this.meta=c,this.index=l,this.createdAt=u,this.version=d}}},E=class e{constructor({position:e=null,walletAddress:t=null,isotope:n=null,token:r=null,value:i=null,batchId:a=null,metaType:o=null,metaId:s=null,meta:c=null,otsFragment:l=null,index:u=null,version:d=null}){this.position=e,this.walletAddress=t,this.isotope=n,this.token=r,this.value=i===null?null:String(i),this.batchId=a,this.metaType=o,this.metaId=s,this.meta=c?x.normalizeMeta(c):[],this.index=u,this.otsFragment=l,this.createdAt=String(+new Date),d!==null&&Object.prototype.hasOwnProperty.call(oe,d)&&(this.version=String(d))}static getHashableProps(){return[`position`,`walletAddress`,`isotope`,`token`,`value`,`batchId`,`metaType`,`metaId`,`meta`,`createdAt`]}static getUnclaimedProps(){return[`otsFragment`]}static create({isotope:t,wallet:n=null,value:r=null,metaType:i=null,metaId:a=null,meta:o=null,batchId:s=null}){return o||=new C,o instanceof C||(o=new C(o)),n&&(o.setAtomWallet(n),s||=n.batchId),new e({position:n?n.position:null,walletAddress:n?n.address:null,isotope:t,token:n?n.token:null,value:r,batchId:s,metaType:i,metaId:a,meta:o.get()})}static jsonToObject(t){let n=Object.assign(new e({}),JSON.parse(t)),r=Object.keys(new e({}));for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&!r.includes(e)&&delete n[e];return n}toJSON(e={}){let{includeOtsFragments:t=!0,validateFields:n=!1}=e;try{if(n){for(let e of[`position`,`walletAddress`,`isotope`,`token`])if(!this[e])throw Error(`Required field '${e}' is missing or empty`)}let e={position:this.position??``,walletAddress:this.walletAddress??``,isotope:this.isotope,token:this.token??``,value:this.value,batchId:this.batchId,metaType:this.metaType,metaId:this.metaId,meta:this.meta||[],index:this.index,createdAt:this.createdAt,version:this.version};return t&&this.otsFragment&&(e.otsFragment=this.otsFragment),e}catch(e){throw Error(`Atom serialization failed: ${e.message}`)}}static fromJSON(t,n={}){let{validateStructure:r=!0,strictMode:i=!1}=n;try{let n=typeof t==`string`?JSON.parse(t):t;if(i||r){for(let e of[`position`,`walletAddress`,`isotope`,`token`])if(!n[e])throw Error(`Required field '${e}' is missing or empty`)}let a=new e({position:n.position,walletAddress:n.walletAddress,isotope:n.isotope,token:n.token,value:n.value,batchId:n.batchId,metaType:n.metaType,metaId:n.metaId,meta:n.meta,index:n.index,version:n.version});return n.otsFragment&&(a.otsFragment=n.otsFragment),n.createdAt&&(a.createdAt=n.createdAt),a}catch(e){throw Error(`Atom deserialization failed: ${e.message}`)}}static hashAtoms({atoms:t,output:n=`base17`}){let r=new c.default(`SHAKE256`,`TEXT`),i=e.sortAtoms(t);if(i.length===0)throw new T;if(i.map(t=>{if(!(t instanceof e))throw new T;return t}),i.every(e=>e.version&&Object.prototype.hasOwnProperty.call(oe,e.version)))r.update(JSON.stringify(i.map(e=>oe[e.version].create(e).view())));else{let e=String(t.length),n=[];for(let t of i)n.push(e),n=n.concat(t.getHashableValues());for(let e of n)r.update(e)}switch(n){case`hex`:return r.getHash(`HEX`,{outputLen:256});case`array`:return r.getHash(`ARRAYBUFFER`,{outputLen:256});default:return h(r.getHash(`HEX`,{outputLen:256}),16,17,`0123456789abcdef`,`0123456789abcdefg`).padStart(64,`0`)}}static jsonSerialization(t,n){if(!e.getUnclaimedProps().includes(t))return n}static sortAtoms(e){let t=[...e];return t.sort((e,t)=>e.index<t.index?-1:1),t}aggregatedMeta(){return x.aggregateMeta(this.meta)}getHashableValues(){let t=[];for(let n of e.getHashableProps()){let e=this[n];if(e!==null||[`position`,`walletAddress`].includes(n)){if(n===`meta`)for(let n of e)n.value!==void 0&&n.value!==null&&(t.push(String(n.key)),t.push(String(n.value)));else t.push(e===null?``:String(e))}}return t}};function se(e=null,t=2048){if(e){let n=new c.default(`SHAKE256`,`TEXT`);return n.update(e),n.getHash(`HEX`,{outputLen:t*4})}return m(t)}function ce(e,t=null){let n=new c.default(`SHAKE256`,`TEXT`);return n.update(e),n.getHash(`HEX`,{outputLen:256})}function le(e,t){let n=new c.default(`SHAKE256`,`TEXT`);return n.update(e),n.getHash(`HEX`,{outputLen:t})}function ue({molecularHash:e=null,index:t=null}){return e!==null&&t!==null?ce(String(e)+String(t),`generateBatchId`):m(64)}var de=class e{constructor(e,t,n){this.id=e,this.name=t,this.metas=n||{}}static createFromGraphQL(t){let n=t.metas||{};return n.length&&(n=JSON.parse(n),n||={}),new e(t.id,t.name,n)}static createFromDB(t){return new e(t[0],t[1],t.length>2?t[2]:{})}getFragmentZone(){return this.metas.fragmentZone||null}getFusedTokenUnits(){return this.metas.fusedTokenUnits||null}toData(){return[this.id,this.name,this.metas]}toGraphQLResponse(){return{id:this.id,name:this.name,metas:JSON.stringify(this.metas)}}},fe=class extends w{constructor(e=`Attempting to create a wallet with no credentials (secret or bundle hash)`,t=null,n=null){super(e,t,n),this.name=`WalletCredentialException`}},pe=BigInt(2**32-1),me=BigInt(32);function he(e,t=!1){return t?{h:Number(e&pe),l:Number(e>>me&pe)}:{h:Number(e>>me&pe)|0,l:Number(e&pe)|0}}function ge(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=he(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}function _e(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}var ve=e=>e?`"${e}" `:``;function D(e,t=``){if(typeof e!=`number`)throw TypeError(ve(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ve(t)+`expected integer >= 0, got `+e);return e}function ye(e,t=``){if(typeof e!=`boolean`)throw TypeError(ve(t)+`expected boolean, got type=`+typeof e);return e}function O(e,t,n=``){if(_e(e)&&(t===void 0||e.length===t))return e;t!==void 0&&D(t,`length`);let r=_e(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ve(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}var be=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)},xe=(e,t)=>{be(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,`__proto__`))throw TypeError(`"${t}.__proto__" is not allowed`)};function Se(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Ce(e,t){O(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function we(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Te(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}var Ee=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function De(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function Oe(e){for(let t=0;t<e.length;t++)e[t]=De(e[t]);return e}var ke=Ee?e=>e:Oe;function Ae(e,t,n=`opts`){return xe(e,`defaults`),t!==void 0&&xe(t,n),Object.assign(Object.create(null),e,t)}function je(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=Ae({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function Me(e=32){D(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var Ne=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),Pe=BigInt(0),Fe=BigInt(1),Ie=BigInt(2),Le=BigInt(7),Re=BigInt(256),ze=BigInt(113),Be=[],Ve=[],He=[];for(let e=0,t=Fe,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Be.push(2*(5*r+n)),Ve.push((e+1)*(e+2)/2%64);let i=Pe;for(let e=0;e<7;e++)t=(t<<Fe^(t>>Le)*ze)%Re,t&Ie&&(i^=Fe<<(Fe<<BigInt(e))-Fe);He.push(i)}var Ue=ge(He,!0),We=Ue[0],Ge=Ue[1],Ke=(e,t,n)=>e<<n|t>>>32-n,qe=(e,t,n)=>t<<n|e>>>32-n,Je=(e,t,n)=>t<<n-32|e>>>64-n,Ye=(e,t,n)=>e<<n-32|t>>>64-n,Xe=(e,t,n)=>n>32?Je(e,t,n):Ke(e,t,n),Ze=(e,t,n)=>n>32?Ye(e,t,n):qe(e,t,n),Qe=new Uint32Array(10);function $e(e,t=24){if(!(e instanceof Uint32Array))throw TypeError(`"s" expected Uint32Array(50), got type=`+typeof e);if(e.length!==50)throw RangeError(`"s" expected Uint32Array(50), got length=`+e.length);if(D(t,`rounds`),t<1||t>24)throw Error(`"rounds" expected integer 1..24`);for(let n=24-t;n<24;n++){for(let t=0;t<10;t++)Qe[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){let n=(t+8)%10,r=(t+2)%10,i=Qe[r],a=Qe[r+1],o=Xe(i,a,1)^Qe[n],s=Ze(i,a,1)^Qe[n+1];for(let n=0;n<50;n+=10)e[t+n]^=o,e[t+n+1]^=s}let t=e[2],r=e[3];for(let n=0;n<24;n++){let i=Ve[n],a=Xe(t,r,i),o=Ze(t,r,i),s=Be[n];t=e[s],r=e[s+1],e[s]=a,e[s+1]=o}for(let t=0;t<50;t+=10){let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3];e[t]^=~e[t+2]&e[t+4],e[t+1]^=~e[t+3]&e[t+5],e[t+2]^=~e[t+4]&e[t+6],e[t+3]^=~e[t+5]&e[t+7],e[t+4]^=~e[t+6]&e[t+8],e[t+5]^=~e[t+7]&e[t+9],e[t+6]^=~e[t+8]&n,e[t+7]^=~e[t+9]&r,e[t+8]^=~n&i,e[t+9]^=~r&a}e[0]^=We[n],e[1]^=Ge[n]}Te(Qe)}var et=class e{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;canXOF;enableXOF=!1;rounds;constructor(e,t,n,r=!1,i=24){if(D(e,`blockLen`),D(t,`suffix`),D(i,`rounds`),ye(r,`enableXOF`),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.canXOF=r,this.rounds=i,D(n,`outputLen`),!(0<e&&e<200))throw Error(`"blockLen" must be 1..199`);this.state=new Uint8Array(200),this.state32=we(this.state)}clone(){return this._cloneInto()}keccak(){ke(this.state32),$e(this.state32,this.rounds),ke(this.state32),this.posOut=0,this.pos=0}update(e){Se(this),O(e);let{blockLen:t,state:n,state32:r}=this,i=e.length,a=t%4==0&&e.byteOffset%4==0,o=t/4,s=a&&i>=t?we(e):void 0;for(let a=0;a<i;){if(s!==void 0&&this.pos===0&&a%4==0&&i-a>=t){for(let e=0,t=a/4;e<o;e++)r[e]^=s[t+e];a+=t,this.pos=t,this.keccak();continue}let c=Math.min(t-this.pos,i-a);for(let t=0;t<c;t++)n[this.pos++]^=e[a++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,t&128&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Se(this,!1),O(e),this.finish();let t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();let a=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+a),r),this.posOut+=a,r+=a}return e}xofInto(e){if(!this.enableXOF)throw Error(`XOF is not enabled`);return this.writeInto(e)}xof(e){return D(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ce(e,this),this.finished)throw Error(`digest() was already called`);this.writeInto(e.length===this.outputLen?e:e.subarray(0,this.outputLen)),this.destroy()}digest(){let e=new Uint8Array(this.outputLen);return this.digestInto(e),e}destroy(){this.destroyed=!0,Te(this.state)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:i,rounds:a,enableXOF:o}=this;return t||=new e(n,r,i,o,a),t.blockLen=n,t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=a,t.suffix=r,t.outputLen=i,t.enableXOF=o,t.canXOF=this.canXOF,t.destroyed=this.destroyed,t}},tt=(e,t,n,r={})=>je(()=>new et(t,e,n),r),nt=tt(6,136,32,Ne(8)),rt=tt(6,72,64,Ne(10)),it=(e,t,n,r={})=>je((r={})=>(r=Ae({},r),new et(t,e,r.dkLen===void 0?n:r.dkLen,!0)),r),at=it(31,168,16,Ne(11)),ot=it(31,136,32,Ne(12));function st(e,t=`object`){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`);return e}function ct(e,t={},n={},r=`object`){st(e,r),st(t,`fields`),st(n,`optFields`);function i(t,n,i){let a=r===`object`?`param "${String(t)}"`:`"${r}.${String(t)}"`,o=e[t];if(!Object.hasOwn(e,t)&&(i?o!==void 0:n!==`function`))throw TypeError(`${a} is invalid: expected own property`);if(i&&o===void 0)return;let s=typeof o;if(s!==n||o===null)throw TypeError(`${a} is invalid: expected ${n}, got ${s}`)}let a=(e,t)=>Object.entries(e).forEach(([e,n])=>i(e,n,t));a(t,!1),a(n,!0)}function lt(e,t=`n`){if(typeof e!=`number`)throw TypeError(`wrong u32 integer "${t}": expected number, got type=${typeof e}`);if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw RangeError(`wrong u32 integer "${t}": expected 0..4294967295, got ${e}`);return e}function ut(e){return lt(e,`x`),!(e&e-1)&&e!==0}function dt(e,t){if(lt(e),typeof t!=`number`)throw TypeError(`"bits" expected number, got type=`+typeof t);if(!Number.isSafeInteger(t)||t<0||t>32)throw Error(`expected integer 0 <= bits <= 32, got ${t}`);let n=0;for(let r=0;r<t;r++,e>>>=1)n=n<<1|e&1;return n>>>0}function ft(e){return lt(e),31-Math.clz32(e)}function pt(e){if(!e||typeof e!=`object`||typeof e.length!=`number`)throw TypeError(`"values" expected array-like, got type=`+typeof e);let t=e.length;if(!ut(t))throw Error(`expected positive power-of-two length, got `+t);let n=ft(t);for(let r=0;r<t;r++){let t=dt(r,n);if(r<t){let n=e[r];e[r]=e[t],e[t]=n}}return e}var mt=(e,t)=>{ct(t,{N:`number`,roots:`object`,dit:`boolean`},{invertButterflies:`boolean`,skipStages:`number`,brp:`boolean`},`coreOpts`);let{N:n,roots:r,dit:i,invertButterflies:a=!1,skipStages:o=0,brp:s=!0}=t;lt(n,`coreOpts.N`);let c=ft(n);if(!ut(n))throw Error(`FFT: Polynomial size should be power of two`);lt(o,`coreOpts.skipStages`);let l=c===0?0:c-1;if(o>l)throw Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${l}`);if(r.length!==n)throw Error(`FFT: wrong roots length: expected ${n}, got ${r.length}`);let u=i!==a;return t=>{if(t.length!==n)throw Error(`FFT: wrong Polynomial length`);i&&s&&pt(t);for(let s=0,l=1;s<c-o;s++){let d=i?s+1+o:c-s,f=1<<d,p=f>>1,m=n>>d;for(let o=0;o<n;o+=f)for(let s=0,c=l++;s<p;s++){let l=a?i?n-c:c:s*m,d=o+s,f=o+s+p,h=r[l],g=t[f],_=t[d];if(u){let n=e.mul(g,h);t[d]=e.add(_,n),t[f]=e.sub(_,n)}else a?(t[d]=e.add(g,_),t[f]=e.mul(e.sub(g,_),h)):(t[d]=e.add(_,g),t[f]=e.mul(e.sub(_,g),h))}}return!i&&s&&pt(t),t}},k=O,ht=Me;function gt(e,t,n=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}function _t(e,t){if(e=O(e),t=O(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function vt(e){return new Uint8Array(O(e))}function yt(e,...t){let n=e=>typeof e==`number`?e:e.bytesLen,r=t.reduce((e,t)=>e+n(t),0);return{bytesLen:r,encode:i=>{let a=new Uint8Array(r);for(let r=0,o=0;r<t.length;r++){let s=t[r],c=n(s),l=typeof s==`number`?i[r]:s.encode(i[r]);O(l,c,e),a.set(l,o),typeof s!=`number`&&l.fill(0),o+=c}return a},decode:i=>{O(i,r,e);let a=[];for(let e of t){let t=n(e),r=i.subarray(0,t);a.push(typeof e==`number`?r:e.decode(r)),i=i.subarray(t)}return a}}}function bt(e,t){let n=e,r=t*n.bytesLen;return{bytesLen:r,encode:e=>{let i=gt(e,`u`);if(i.length!==t)throw RangeError(`vecCoder.encode: wrong length=${i.length}. Expected: ${t}`);let a=new Uint8Array(r);for(let e=0,t=0;e<i.length;e++){let r=n.encode(i[e]);a.set(r,t),r.fill(0),t+=r.length}return a},decode:e=>{O(e,r);let t=[];for(let r=0;r<e.length;r+=n.bytesLen)t.push(n.decode(e.subarray(r,r+n.bytesLen)));return t}}}function A(...e){for(let t of e)if(Array.isArray(t))for(let e of t)e.fill(0);else t.fill(0)}function xt(e){if(D(e,`bits`),e>32)throw RangeError(`"bits" expected <= 32, got `+e);return e===32?4294967295:~(-1<<e)>>>0}var St=e=>{let{newPoly:t,N:n,Q:r,F:i,ROOT_OF_UNITY:a,brvBits:o,isKyber:s}=e,c=(e,t=r)=>{let n=e%t|0;return(n>=0?n|0:t+n|0)|0},l=(e,t=r)=>{let n=c(e,t)|0;return(n>t>>1?n-t|0:n)|0};function u(){let e=t(n);for(let t=0;t<n;t++){let n=dt(t,o),i=BigInt(a)**BigInt(n)%BigInt(r);e[t]=Number(i)|0}return e}let d=u(),f=e=>{throw Error(`not implemented`)},p=s?{add:(e,t)=>{let n=e+t|0;return n>=r?n-r|0:n},sub:(e,t)=>{let n=e-t|0;return n<0?n+r|0:n},mul:(e,t)=>c((e|0)*(t|0))|0,inv:f}:{add:(e,t)=>c((e|0)+(t|0))|0,sub:(e,t)=>c((e|0)-(t|0))|0,mul:(e,t)=>c((e|0)*(t|0))|0,inv:f},m={N:n,roots:d,invertButterflies:!0,skipStages:+!!s,brp:!1},h=mt(p,{dit:!1,...m}),g=mt(p,{dit:!0,...m}),_={encode:e=>h(e),decode:e=>{g(e);for(let t=0;t<e.length;t++)e[t]=c(i*e[t]);return e}};return{mod:c,smod:l,nttZetas:d,NTT:{encode:e=>_.encode(e),decode:e=>_.decode(e)},bitsCoder:(e,r)=>{for(let t=0,r=0;t<n;t++)r+=e,r>32&&xt(r),r%=8;let i=xt(e),a=n/8*e;return{bytesLen:a,encode:t=>{let n=t,o=new Uint8Array(a);for(let t=0,a=0,s=0,c=0;t<n.length;t++)for(a|=(r.encode(n[t])&i)<<s,s+=e;s>=8;s-=8,a>>=8)o[c++]=a&255;return o},decode:a=>{let o=t(n);for(let t=0,n=0,s=0,c=0;t<a.length;t++)for(n|=a[t]<<s,s+=8;s>=e;s-=e,n>>=e)o[c++]=r.decode(n&i);return o}}}}},Ct=(e=>(t,n)=>{n||=e.blockLen;let r=new Uint8Array(t.length+2);r.set(t);let i=t.length,a=new Uint8Array(n),o=e.create({}),s=0,c=0;return{stats:()=>({calls:s,xofs:c}),get:(t,n)=>(r[i+0]=t,r[i+1]=n,o.destroy(),o=e.create({}).update(r),s++,()=>(c++,o.xofInto(a))),clean:()=>{o.destroy(),A(a,r)}}})(at),j=256,M=3329,N=St({N:j,Q:M,F:3303,ROOT_OF_UNITY:17,newPoly:e=>new Uint16Array(e),brvBits:7,isKyber:!0}),wt=Object.freeze({512:Object.freeze({N:j,Q:M,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128}),768:Object.freeze({N:j,Q:M,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192}),1024:Object.freeze({N:j,Q:M,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256})}),Tt=e=>{if(e>=12)return{encode:e=>e,decode:e=>e>=M?e-M:e};let t=2**(e-1);return{encode:t=>((t<<e)+M/2)/M,decode:n=>n*M+t>>>e}},Et=e=>N.bitsCoder(e,e===12?{encode:e=>e,decode:e=>e>=M?e-M:e}:{encode:e=>e,decode:e=>e}),Dt=e=>e===12?Et(12):N.bitsCoder(e,Tt(e));function Ot(e,t){let n=e,r=t;for(let e=0;e<j;e++){let t=n[e]+r[e];n[e]=t>=M?t-M:t}}function kt(e,t){let n=e,r=t;for(let e=0;e<j;e++){let t=n[e]-r[e];n[e]=t<0?t+M:t}}function At(e,t,n,r,i){return{c0:N.mod(N.mod(t*r)*i+e*n),c1:N.mod(e*r+t*n)}}function jt(e,t){let n=e,r=t;for(let e=0;e<j/2;e++){let t=N.nttZetas[64+(e>>1)];e&1&&(t=-t);let{c0:i,c1:a}=At(n[2*e+0],n[2*e+1],r[2*e+0],r[2*e+1],t);n[2*e+0]=i,n[2*e+1]=a}return n}function Mt(e){let t=e,n=new Uint16Array(j);for(let e=0;e<j;){let r=t();if(r.length%3)throw Error(`SampleNTT: unaligned block`);for(let t=0;e<j&&t+3<=r.length;t+=3){let i=(r[t+0]>>0|r[t+1]<<8)&4095,a=(r[t+1]>>4|r[t+2]<<4)&4095;i<M&&(n[e++]=i),e<j&&a<M&&(n[e++]=a)}}return n}var Nt=(e,t)=>{let n=new Uint16Array(j),r=we(e);ke(r);let i=0;for(let e=0,a=0,o=0,s=0;e<r.length;e++){let c=r[e];for(let e=0;e<32;e++)o+=c&1,c>>=1,i+=1,i===t?(s=o,o=0):i===2*t&&(n[a++]=N.mod(s-o),o=0,i=0)}if(ke(r),i)throw Error(`sampleCBD: leftover bits: ${i}`);return n};function Pt(e,t,n,r){return Nt(e(r*j/4,t,n),r)}var Ft=e=>{let{K:t,PRF:n,XOF:r,HASH512:i,ETA1:a,ETA2:o,du:s,dv:c}=e,l=Dt(1),u=Dt(c),d=Dt(s),f=yt(`publicKey`,bt(Dt(12),t),32),p=bt(Dt(12),t),m=yt(`ciphertext`,bt(d,t),u),h=yt(`seed`,32,32),g=(e,r,i,s)=>{let c=[];for(let e=0;e<t;e++)c.push(N.NTT.encode(Pt(n,s,e,a)));let u=new Uint16Array(j),d=[];for(let i=0;i<t;i++){let a=Pt(n,s,t+i,o),l=new Uint16Array(j);for(let e=0;e<t;e++)Ot(l,jt(r(i,e),c[e]));Ot(a,N.NTT.decode(l)),d.push(a),Ot(u,jt(e[i],c[i])),A(l)}let f=Pt(n,s,2*t,o);Ot(f,N.NTT.decode(u));let p=l.decode(i);return Ot(p,f),A(e,c,u,f),m.encode([d,p])};return{secretCoder:p,lengths:{secretKey:p.bytesLen,publicKey:f.bytesLen,cipherText:m.bytesLen},keygen:e=>{k(e,32,`seed`);let o=new Uint8Array(33);o.set(e),o[32]=t;let s=i(o),[c,l]=h.decode(s),u=[],d=[];for(let e=0;e<t;e++)u.push(N.NTT.encode(Pt(n,l,e,a)));let m=r(c);for(let e=0;e<t;e++){let r=N.NTT.encode(Pt(n,l,t+e,a));for(let n=0;n<t;n++)Ot(r,jt(Mt(m.get(n,e)),u[n]));d.push(r)}m.clean();let g={publicKey:f.encode([d,c]),secretKey:p.encode(u)};return A(c,l,u,d,o,s),g},encrypt:(e,t,n)=>{let[i,a]=f.decode(e),o=r(a),s=g(i,(e,t)=>Mt(o.get(e,t)),t,n);return o.clean(),s},prepare:e=>{let[n,i]=f.decode(e),a=r(i),o=[];for(let e=0;e<t;e++)for(let n=0;n<t;n++)o.push(Mt(a.get(e,n)));return a.clean(),{encrypt:(e,r)=>g(n.map(e=>e.slice()),(e,n)=>o[e*t+n].slice(),e,r),clean:()=>A(n,o)}},decrypt:(e,n)=>{let[r,i]=m.decode(e),a=p.decode(n),o=new Uint16Array(j);for(let e=0;e<t;e++)Ot(o,jt(a[e],N.NTT.encode(r[e])));kt(i,N.NTT.decode(o));let s=l.encode(i);return A(o,a,r,i),s}}};function It(e){let t=e,n=Ft(t),{HASH256:r,HASH512:i,KDF:a}=t,{secretCoder:o,lengths:s}=n,c=yt(`secretKey`,s.secretKey,s.publicKey,32,32),l=(e,n)=>{let r=e.subarray(0,384*t.K),i=o.encode(o.decode(vt(r))),a=_t(i,r);if(A(i),!a)throw Error(`ML-KEM.${n}: wrong publicKey modulus`)},u=Object.freeze({...s,seed:64,msg:32,msgRand:32,secretKey:c.bytesLen});return Object.freeze({info:Object.freeze({type:`ml-kem`}),lengths:u,keygen:e=>{let t=e===void 0,i=t?ht(64):e,a,o;try{k(i,64,`seed`);let e=n.keygen(i.subarray(0,32)),t=e.publicKey;return a=e.secretKey,o=r(t),{publicKey:t,secretKey:c.encode([a,t,o,i.subarray(32)])}}finally{a!==void 0&&A(a),o!==void 0&&A(o),t&&A(i)}},getPublicKey:e=>{let[t,n,r,i]=c.decode(e);return Uint8Array.from(n)},encapsulate:(e,t)=>{let a=t===void 0,o=a?ht(32):t,c;try{return k(e,s.publicKey,`publicKey`),k(o,32,`message`),l(e,`encapsulate`),c=i.create().update(o).update(r(e)).digest(),{cipherText:n.encrypt(e,o,c.subarray(32,64)),sharedSecret:c.subarray(0,32)}}finally{c!==void 0&&A(c.subarray(32)),a&&A(o)}},decapsulate:(e,t)=>{k(t,c.bytesLen,`secretKey`),k(e,s.cipherText,`cipherText`);let o=c.bytesLen-96,l=o+32;if(!_t(r(t.subarray(o/2,l)),t.subarray(l,l+32)))throw Error(`invalid secretKey: hash check failed`);let[u,d,f,p]=c.decode(t),m=n.decrypt(e,u),h=i.create().update(m).update(f).digest(),g=h.subarray(0,32),_=n.encrypt(d,m,h.subarray(32,64)),v=_t(e,_),y=a.create({dkLen:32}).update(p).update(e).digest();return A(m,_,h.subarray(32),v?y:g),v?g:y},prepare:e=>{k(e,s.publicKey,`publicKey`),l(e,`prepare`);let t=vt(e),o=r(t),u=n.prepare(t);return Object.freeze({publicKey:t,encapsulate:e=>{let t=e===void 0,n=t?ht(32):e,r;try{return k(n,32,`message`),r=i.create().update(n).update(o).digest(),{cipherText:u.encrypt(n,r.subarray(32,64)),sharedSecret:r.subarray(0,32)}}finally{r!==void 0&&A(r.subarray(32)),t&&A(n)}},decapsulate:(e,r)=>{k(r,c.bytesLen,`secretKey`),k(e,s.cipherText,`cipherText`);let[l,d,f,p]=c.decode(r);if(!_t(d,t)||!_t(f,o))throw Error(`ML-KEM.decapsulate: secretKey does not match prepared publicKey`);let m=n.decrypt(e,l),h=i.create().update(m).update(o).digest(),g=h.subarray(0,32),_=u.encrypt(m,h.subarray(32,64)),v=_t(e,_),y=a.create({dkLen:32}).update(p).update(e).digest();return A(m,_,h.subarray(32),v?y:g),v?g:y},clean:u.clean})}})}function Lt(e,t,n){return ot.create({dkLen:e}).update(t).update(new Uint8Array([n])).digest()}var Rt={HASH256:nt,HASH512:rt,KDF:ot,XOF:Ct,PRF:Lt},zt=e=>It({...Rt,...e}),Bt=zt(wt[768]),Vt={1024:{kem:zt(wt[1024]),pkBytes:1568,skBytes:3168,ctBytes:1568},768:{kem:Bt,pkBytes:1184,skBytes:2400,ctBytes:1088}},Ht=1024,P=class e{constructor({secret:t=null,bundle:n=null,token:r=`USER`,address:i=null,position:a=null,batchId:o=null,characters:s=null,mlKemParameterSet:c=Ht}){let l=Number(c);if(!Vt[l])throw Error(`KnishIO: unsupported ML-KEM parameter set ${c}; expected 1024 or 768.`);this.mlKemParameterSet=l,this.token=r,this.balance=`0`,this.molecules={},this.key=null,this.privkey=null,this.pubkey=null,this.tokenUnits=[],this.tradeRates={},this.address=i,this.position=a,this.bundle=n,this.batchId=o,this.characters=s,t&&(this.bundle=this.bundle||ce(t,`Wallet::constructor`),this.position=this.position||e.generatePosition(),this.key=e.generateKey({secret:t,token:this.token,position:this.position}),this.address=this.address||e.generateAddress(this.key),this.characters=this.characters||`BASE64`,this.initializeMLKEM())}static create({secret:t=null,bundle:n=null,token:r,batchId:i=null,characters:a=null,mlKemParameterSet:o=Ht}){let s=null;if(!t&&!n)throw new fe;return t&&!n&&(s=e.generatePosition(),n=ce(t,`Wallet::create`)),new e({secret:t,bundle:n,token:r,position:s,batchId:i,characters:a,mlKemParameterSet:o})}static isBundleHash(e){return typeof e==`string`&&e.length===64&&b(e)}static getTokenUnits(e){let t=[];return e.forEach(e=>{t.push(de.createFromDB(e))}),t}static generateKey({secret:e,token:t,position:n}){if(!e)throw new fe(`Wallet::generateKey() - Secret is required!`);if(!n)throw new fe(`Wallet::generateKey() - Position is required!`);let r=b(e)?e:le(e,1024),i=b(n)?n:le(n,256),a=BigInt(`0x${r}`)+BigInt(`0x${i}`),o=new c.default(`SHAKE256`,`TEXT`);o.update(a.toString(16)),t&&o.update(t);let s=new c.default(`SHAKE256`,`TEXT`);return s.update(o.getHash(`HEX`,{outputLen:8192})),s.getHash(`HEX`,{outputLen:8192})}static generateAddress(e){let t=p(e,128),n=new c.default(`SHAKE256`,`TEXT`);for(let e in t){let r=t[e];for(let e=1;e<=16;e++){let e=new c.default(`SHAKE256`,`TEXT`);e.update(r),r=e.getHash(`HEX`,{outputLen:512})}n.update(r)}let r=new c.default(`SHAKE256`,`TEXT`);return r.update(n.getHash(`HEX`,{outputLen:8192})),r.getHash(`HEX`,{outputLen:256})}static generatePosition(e=64){return m(e,`abcdef0123456789`)}_deriveMlKemKeypair(e){let t=Vt[e];if(!t)throw Error(`KnishIO: unsupported ML-KEM parameter set ${e}; expected 1024 or 768.`);if(!this.key)return null;let n=se(this.key,128),r=new Uint8Array(64);for(let e=0;e<64;e++)r[e]=parseInt(n.substr(e*2,2),16);let{publicKey:i,secretKey:a}=t.kem.keygen(r);return{pubkey:this.serializeKey(i),privkey:a,params:t}}initializeMLKEM(){let e=this._deriveMlKemKeypair(this.mlKemParameterSet);e&&(this.pubkey=e.pubkey,this.privkey=e.privkey)}serializeKey(e){if(typeof Buffer<`u`)return Buffer.from(e).toString(`base64`);let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}deserializeKey(e){if(typeof Buffer<`u`)return new Uint8Array(Buffer.from(e,`base64`));let t=atob(e);return new Uint8Array(t.length).map((e,n)=>t.charCodeAt(n))}static mlKemParameterSetFromPubkey(e){if(!e)return null;let t;try{t=typeof Buffer<`u`?Buffer.from(e,`base64`).length:atob(e).length}catch{return null}for(let[e,n]of Object.entries(Vt))if(n.pkBytes===t)return Number(e);return null}balanceAsNumber(){return Number(this.balance)}balanceAsBigInt(){let e=String(this.balance),t=e.includes(`.`)?e.split(`.`)[0]:e;return BigInt(t||`0`)}setBalanceBigInt(e){this.balance=e.toString()}setBalanceNumber(e){this.balance=String(e)}getTokenUnitsData(){let e=[];return this.tokenUnits.forEach(t=>{e.push(t.toData())}),e}splitUnits(e,t,n=null){if(e.length===0)return;let r=[],i=[];this.tokenUnits.forEach(t=>{e.includes(t.id)?r.push(t):i.push(t)}),this.tokenUnits=r,n!==null&&(n.tokenUnits=r),t.tokenUnits=i}splitUnitsMulti(e,t,n){let r=new Set;e.forEach(e=>{e.forEach(e=>r.add(e))}),r.size!==0&&(t.forEach((t,n)=>{let r=e[n];t.tokenUnits=this.tokenUnits.filter(e=>r.includes(e.id))}),n.tokenUnits=this.tokenUnits.filter(e=>!r.has(e.id)),this.tokenUnits=this.tokenUnits.filter(e=>r.has(e.id)))}createRemainder(t){let n=e.create({secret:t,token:this.token,characters:this.characters});return n.initBatchId({sourceWallet:this,isRemainder:!0}),n}isShadow(){return(this.position===void 0||this.position===null)&&(this.address===void 0||this.address===null)}initBatchId({sourceWallet:e,isRemainder:t=!1}){e.batchId&&(this.batchId=t?e.batchId:ue({}))}async encryptMessage(e,t){let n=JSON.stringify(e),r=new TextEncoder().encode(n),i=this.deserializeKey(t),a=Vt[this.mlKemParameterSet];if(i.length!==a.pkBytes)throw Error(`KnishIO: cannot ML-KEM-encrypt — recipient public key is ${i.length} bytes, expected ${a.pkBytes} (ML-KEM-${this.mlKemParameterSet}). The peer is not running ML-KEM-${this.mlKemParameterSet}; upgrade the peer, or step this client back to the other parameter set.`);let{cipherText:o,sharedSecret:s}=a.kem.encapsulate(i),c=await this.encryptWithSharedSecret(r,s);return{cipherText:this.serializeKey(o),encryptedMessage:this.serializeKey(c)}}async decryptMessage(e){let t=await this._mlkemDecryptToString(e);return t===null?null:JSON.parse(t)}async _mlkemDecryptToString(e){let{cipherText:t,encryptedMessage:n}=e,r=this.deserializeKey(t),i=Vt[this.mlKemParameterSet],a=this.mlKemParameterSet===1024?768:1024,o=i,s=this.privkey;if(r.length!==i.ctBytes){if(r.length!==Vt[a].ctBytes)return console.error(`Wallet::decryptMessage() - Ciphertext length mismatch: got ${r.length}, expected ${i.ctBytes}`),null;let e=this._deriveMlKemKeypair(a);if(!e)return console.error(`Wallet::decryptMessage() - cannot derive the ML-KEM-${a} identity: wallet has no key`),null;o=e.params,s=e.privkey}let c;try{c=o.kem.decapsulate(r,s)}catch(e){return console.error(`Wallet::decryptMessage() - Decapsulation failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),null}let l;try{l=this.deserializeKey(n)}catch(e){return console.warn(`Wallet::decryptMessage() - Deserialization failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),console.info(`Wallet::decryptMessage() - our shared secret`,c),null}let u;try{u=await this.decryptWithSharedSecret(l,c)}catch(e){return console.warn(`Wallet::decryptMessage() - Decryption failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),console.info(`Wallet::decryptMessage() - our shared secret`,c),console.info(`Wallet::decryptMessage() - deserialized encrypted message`,l),null}try{return new TextDecoder().decode(u)}catch(e){return console.warn(`Wallet::decryptMessage() - Decoding failed`,e),console.info(`Wallet::decryptMessage() - my public key`,this.pubkey),console.info(`Wallet::decryptMessage() - our shared secret`,c),console.info(`Wallet::decryptMessage() - deserialized encrypted message`,l),console.info(`Wallet::decryptMessage() - decrypted Uint8Array`,u),null}}hashShare(e){let t=le(e,64),n=Uint8Array.from(t.match(/.{2}/g).map(e=>parseInt(e,16)));return this.serializeKey(n)}async encryptStringML(e,t){let n=await this.encryptMessage(e,t);return JSON.stringify({[this.hashShare(t)]:n})}async decryptMyMessageML(e){let t=e[this.hashShare(this.pubkey)];if(!t){let n=this.mlKemParameterSet===1024?768:1024,r=this._deriveMlKemKeypair(n);r&&(t=e[this.hashShare(r.pubkey)])}return t?this._mlkemDecryptToString(t):null}async encryptWithSharedSecret(e,t){let n=crypto.getRandomValues(new Uint8Array(12)),r={name:`AES-GCM`,iv:n},i=await crypto.subtle.importKey(`raw`,t,{name:`AES-GCM`},!1,[`encrypt`]),a=await crypto.subtle.encrypt(r,i,e),o=new Uint8Array(n.length+a.byteLength);return o.set(n),o.set(new Uint8Array(a),n.length),o}async decryptWithSharedSecret(e,t){let n={name:`AES-GCM`,iv:e.slice(0,12)},r=await crypto.subtle.importKey(`raw`,t,{name:`AES-GCM`},!1,[`decrypt`]),i=await crypto.subtle.decrypt(n,r,e.slice(12));return new Uint8Array(i)}},Ut=class extends w{constructor(e=`There is an atom without an index`,t=null,n=null){super(e,t,n),this.name=`AtomIndexException`}},Wt=class extends w{constructor(e=`The molecular hash does not match`,t=null,n=null){super(e,t,n),this.name=`MolecularHashMismatchException`}},Gt=class extends w{constructor(e=`The molecular hash is missing`,t=null,n=null){super(e,t,n),this.name=`MolecularHashMissingException`}},Kt=class extends w{constructor(e=``,t=null,n=null){super(e,t,n),this.name=`PolicyInvalidException`}},qt=class extends w{constructor(e=`OTS malformed`,t=null,n=null){super(e,t,n),this.name=`SignatureMalformedException`}},Jt=class extends w{constructor(e=`One-time signature (OTS) does not match!`,t=null,n=null){super(e,t,n),this.name=`SignatureMismatchException`}},F=class extends w{constructor(e=`Insufficient balance to make transfer`,t=null,n=null){super(e,t,n),this.name=`TransferBalanceException`}},Yt=class extends w{constructor(e=`Token transfer atoms are malformed`,t=null,n=null){super(e,t,n),this.name=`TransferMalformedException`}},Xt=class extends w{constructor(e=`Token slugs for wallets in transfer do not match!`,t=null,n=null){super(e,t,n),this.name=`TransferMismatchedException`}},Zt=class extends w{constructor(e=`Invalid remainder provided`,t=null,n=null){super(e,t,n),this.name=`TransferRemainderException`}},Qt=class extends w{constructor(e=`Sender and recipient(s) cannot be the same`,t=null,n=null){super(e,t,n),this.name=`TransferToSelfException`}},$t=class extends w{constructor(e=`Token transfer atoms are unbalanced`,t=null,n=null){super(e,t,n),this.name=`TransferUnbalancedException`}},I=class extends w{constructor(e=`Empty meta data.`,t=null,n=null){super(e,t,n),this.name=`MetaMissingException`}},en=class extends w{constructor(e=`Wrong type of token for this isotope`,t=null,n=null){super(e,t,n),this.name=`WrongTokenTypeException`}},tn=class extends w{constructor(e=`Incorrect BatchId`,t=null,n=null){super(e,t,n),this.name=`BatchIdException`}},nn=class{constructor(e={}){for(let t in e)this[`__${t}`]=e[t]}static toObject(e){return new this(e)}toJSON(){let e={};for(let t of Object.keys(this))t.substring(0,2)===`__`&&(e[t.substring(2,t.length)]=this[t]);return e}},rn=class extends w{constructor(e=`An incorrect argument!`,t=null,n=null){super(e,t,n),this.name=`RuleArgumentException`}},L=class extends w{constructor(e=`Code exception`,t=null,n=null){super(e,t,n),this.name=`CodeException`}},an=class e{constructor({action:e,metaType:t=null,metaId:n=null,meta:r=null,address:i=null,token:a=null,amount:o=null,comparison:s=null}){if(r&&(this.meta=r),!e)throw new rn(`Callback structure violated, missing mandatory "action" parameter.`);this.__metaId=n,this.__metaType=t,this.__action=e,this.__address=i,this.__token=a,this.__amount=o,this.__comparison=s}set comparison(e){this.__comparison=e}set amount(e){if(!ee(e))throw new L(`Parameter amount should be a string containing numbers`);this.__amount=e}set token(e){this.__token=e}set address(e){this.__address=e}set meta(e){this.__meta=e instanceof nn?e:nn.toObject(e)}set metaType(e){this.__metaType=e}set metaId(e){this.__metaId=e}static toObject(t){let n=new e({action:t.action});return t.metaType&&(n.metaType=t.metaType),t.metaId&&(n.metaId=t.metaId),t.meta&&(n.meta=t.meta),t.address&&(n.address=t.address),t.token&&(n.token=t.token),t.amount&&(n.amount=t.amount),t.comparison&&(n.comparison=t.comparison),n}toJSON(){let e={action:this.__action};return this.__metaType&&(e.metaType=this.__metaType),this.__metaId&&(e.metaId=this.__metaId),this.__meta&&(e.meta=this.__meta),this.__address&&(e.address=this.__address),this.__token&&(e.token=this.__token),this.__amount&&(e.amount=this.__amount),this.__comparison&&(e.comparison=this.__comparison),e}isReject(){return this._is(`reject`)}isMeta(){return S(Object.keys(this.toJSON()),[`action`,`metaId`,`metaType`,`meta`]).length===4&&this._is(`meta`)}isCollect(){return S(Object.keys(this.toJSON()),[`action`,`address`,`token`,`amount`,`comparison`]).length===5&&this._is(`collect`)}isBuffer(){return S(Object.keys(this.toJSON()),[`action`,`address`,`token`,`amount`,`comparison`]).length===5&&this._is(`buffer`)}isRemit(){return S(Object.keys(this.toJSON()),[`action`,`token`,`amount`]).length===3&&this._is(`remit`)}isBurn(){return S(Object.keys(this.toJSON()),[`action`,`token`,`amount`,`comparison`]).length===4&&this._is(`burn`)}_is(e){return this.__action.toLowerCase()===e.toLowerCase()}},on=class{constructor({key:e,value:t,comparison:n}){if([e,t,n].some(e=>!e))throw new rn(`Condition::constructor( { key, value, comparison } ) - not all class parameters are initialised!`);this.__key=e,this.__value=t,this.__comparison=n}static toObject(e){return new this({key:e.key,value:e.value,comparison:e.comparison})}toJSON(){return{key:this.__key,value:this.__value,comparison:this.__comparison}}},sn=class e{constructor({condition:e=[],callback:t=[]}){for(let t of e)if(!(t instanceof on))throw new rn;for(let e of t)if(!(e instanceof an))throw new rn;this.__condition=e,this.__callback=t}set comparison(e){this.__condition.push(e instanceof on?e:on.toObject(e))}set callback(e){this.__callback.push(e instanceof an?e:an.toObject(e))}static toObject(t){if(!t.condition)throw new I(`Rule::toObject() - Incorrect rule format! There is no condition field.`);if(!t.callback)throw new I(`Rule::toObject() - Incorrect rule format! There is no callback field.`);let n=new e({});for(let e of t.condition)n.comparison=e;for(let e of t.callback)n.callback=e;return n}toJSON(){return{condition:this.__condition,callback:this.__callback}}},R=class{static __init(e,t){this.arr=String(t).split(`.`),this.key=this.arr.shift();let n=Number(this.key);Number.isInteger(n)&&(this.key=n),this.__nextKey=this.arr.length,this.__next=this.__tic(e)}static __tic(e){return!Array.isArray(e)&&!(e instanceof Object)?!1:e[this.key]!==void 0}static has(e,t){return this.__init(e,t),this.__next?this.__nextKey===0||this.has(e[this.key],this.arr.join(`.`)):!1}static get(e,t,n=null){return this.__init(e,t),this.__next?this.__nextKey===0?e[this.key]:this.get(e[this.key],this.arr.join(`.`),n):n}static set(e,t,n){let r=t.split(`.`),i=e,a=r.length-1;for(let e=0;e<a;e++){let t=r[e],n=Number(t),a=Number.isInteger(n);(a?n:t in i)||(i[a?n:t]=r[e+1].match(/^\d+$/)?[]:{}),i=i[a?n:t]}let o=r[a],s=Number(o);return i[Number.isInteger(s)?s:o]=n,e}},cn=class e{constructor(e){if(e.molecularHash===null)throw new Gt;if(!e.atoms.length)throw new T;for(let t of e.atoms)if(t.index===null)throw new Ut;this.molecule=e}verify(e){return this.molecularHash()&&this.ots()&&this.batchId()&&this.continuId()&&this.isotopeM()&&this.isotopeT()&&this.isotopeC()&&this.isotopeU()&&this.isotopeI()&&this.isotopeR()&&this.isotopeP()&&this.isotopeA()&&this.isotopeB()&&this.isotopeF()&&this.isotopeV(e)}continuId(){if(this.molecule.atoms[0].token===`USER`&&this.molecule.getIsotopes(`I`).length<1)throw new T(`Check::continuId() - Molecule is missing required ContinuID Atom!`);return!0}batchId(){if(this.molecule.atoms.length>0){let e=this.molecule.atoms[0];if(e.isotope===`V`&&e.batchId!==null){let t=this.molecule.getIsotopes(`V`),n=t[t.length-1];if(e.batchId!==n.batchId)throw new tn;for(let e of t)if(e.batchId===null)throw new tn}return!0}throw new tn}isotopeI(){for(let e of this.molecule.getIsotopes(`I`)){if(e.token!==`USER`)throw new en(`Check::isotopeI() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index===0)throw new Ut(`Check::isotopeI() - Isotope "${e.isotope}" Atoms must have a non-zero index!`)}return!0}isotopeU(){for(let e of this.molecule.getIsotopes(`U`)){if(e.token!==`AUTH`)throw new en(`Check::isotopeU() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new Ut(`Check::isotopeU() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeM(){let e=[`readPolicy`,`writePolicy`];for(let t of this.molecule.getIsotopes(`M`)){if(t.meta.length<1)throw new I;if(t.token!==`USER`)throw new en(`Check::isotopeM() - "${t.token}" is not a valid Token slug for "${t.isotope}" isotope Atoms!`);let n=x.aggregateMeta(t.meta);for(let t of e){let r=n[t];if(r){r=JSON.parse(r);for(let[t,i]of Object.entries(r))if(!e.includes(t)){if(!Object.keys(n).includes(t))throw new Kt(`${t} is missing from the meta.`);for(let e of i)if(!P.isBundleHash(e)&&![`all`,`self`].includes(e))throw new Kt(`${e} does not correspond to the format of the policy.`)}}}}return!0}isotopeC(){for(let e of this.molecule.getIsotopes(`C`)){if(e.token!==`USER`)throw new en(`Check::isotopeC() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new Ut(`Check::isotopeC() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeT(){for(let e of this.molecule.getIsotopes(`T`)){let t=e.aggregatedMeta();if(String(e.metaType).toLowerCase()===`wallet`){for(let e of[`position`,`bundle`])if(!Object.prototype.hasOwnProperty.call(t,e)||!t[e])throw new I(`Check::isotopeT() - Required meta field "${e}" is missing!`)}for(let e of[`token`])if(!Object.prototype.hasOwnProperty.call(t,e)||!t[e])throw new I(`Check::isotopeT() - Required meta field "${e}" is missing!`);if(e.token!==`USER`)throw new en(`Check::isotopeT() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(e.index!==0)throw new Ut(`Check::isotopeT() - Isotope "${e.isotope}" Atoms must have an index equal to 0!`)}return!0}isotopeR(){for(let e of this.molecule.getIsotopes(`R`)){let t=e.aggregatedMeta();if(t.policy){let e=JSON.parse(t.policy);if(!Object.keys(e).every(e=>[`read`,`write`].includes(e)))throw new I(`Check::isotopeR() - Mixing rules with politics!`)}if(t.rule){let e=JSON.parse(t.rule);if(!Array.isArray(e))throw new I(`Check::isotopeR() - Incorrect rule format!`);for(let t of e)sn.toObject(t);if(e.length<1)throw new I(`Check::isotopeR() - No rules!`)}}return!0}isotopeP(){for(let e of this.molecule.getIsotopes(`P`)){if(e.token!==`USER`)throw new en(`Check::isotopeP() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);let t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,`peerHost`)||!t.peerHost)throw new I(`Check::isotopeP() - Required meta field "peerHost" is missing!`)}return!0}isotopeA(){for(let e of this.molecule.getIsotopes(`A`)){if(e.token!==`USER`)throw new en(`Check::isotopeA() - "${e.token}" is not a valid Token slug for "${e.isotope}" isotope Atoms!`);if(!e.metaType)throw new I(`Check::isotopeA() - Required field "metaType" is missing!`);if(!e.metaId)throw new I(`Check::isotopeA() - Required field "metaId" is missing!`);let t=e.aggregatedMeta();if(!Object.prototype.hasOwnProperty.call(t,`action`)||!t.action)throw new I(`Check::isotopeA() - Required meta field "action" is missing!`)}return!0}isotopeB(){let e=this.molecule.getIsotopes(`B`);if(e.length===0)return!0;for(let t of e){if(!t.metaType||t.metaType!==`walletBundle`)throw new I(`Check::isotopeB() - B-isotope atoms must have metaType "walletBundle"!`);if(!t.metaId)throw new I(`Check::isotopeB() - B-isotope atoms must have a metaId!`);let e=Number(t.value);if(Number.isNaN(e))throw new Yt(`Check::isotopeB() - B-isotope atom value is not a valid number!`)}let t=this.molecule.getIsotopes(`V`);if(t.length>0){let n=0;for(let r of[...t,...e]){let e=Number(r.value);Number.isNaN(e)||(n+=e)}if(n!==0)throw new $t(`Check::isotopeB() - V+B atom values do not balance to zero!`)}return!0}isotopeF(){let e=this.molecule.getIsotopes(`F`);if(e.length===0)return!0;for(let t of e){if(!t.metaType||t.metaType!==`walletBundle`)throw new I(`Check::isotopeF() - F-isotope atoms must have metaType "walletBundle"!`);if(!t.metaId)throw new I(`Check::isotopeF() - F-isotope atoms must have a metaId!`);let e=Number(t.value);if(Number.isNaN(e))throw new Yt(`Check::isotopeF() - F-isotope atom value is not a valid number!`);if(e<0)throw new Yt(`Check::isotopeF() - F-isotope atom value must not be negative!`)}let t=this.molecule.getIsotopes(`V`);if(t.length>0){let n=0;for(let r of[...t,...e]){let e=Number(r.value);Number.isNaN(e)||(n+=e)}if(n!==0)throw new $t(`Check::isotopeF() - V+F atom values do not balance to zero!`)}return!0}isotopeV(e=null){let t=this.molecule.getIsotopes(`V`);if(t.length===0)return!0;let n=this.molecule.getIsotopes(`B`).length>0||this.molecule.getIsotopes(`F`).length>0,r=this.molecule.atoms[0];if(!n&&r.isotope===`V`&&t.length===2){let e=t[t.length-1];if(r.token!==e.token)throw new Xt;if(e.value<0)throw new Yt;if(Number(r.value)+Number(e.value)!==0)throw new $t;return!0}let i=0,a=0;for(let e in this.molecule.atoms)if(Object.prototype.hasOwnProperty.call(this.molecule.atoms,e)){let t=this.molecule.atoms[e];if(t.isotope!==`V`)continue;if(a=t.value*1,Number.isNaN(a))throw TypeError(`Invalid isotope "V" values`);if(t.token!==r.token)throw new Xt;if(e>0){if(a<0)throw new Yt;if(t.walletAddress===r.walletAddress)throw new Qt}i+=a}if(!n&&i!==0)throw new $t;if(e){if(a=r.value*1,Number.isNaN(a))throw TypeError(`Invalid isotope "V" values`);let t=Number(e.balance)+a;if(t<0)throw new F;if(!n&&t!==i)throw new Zt}else if(a!==0)throw new Zt;return!0}molecularHash(){if(this.molecule.molecularHash!==E.hashAtoms({atoms:this.molecule.atoms}))throw new Wt;return!0}ots(){let e=this.molecule.normalizedHash(),t=this.molecule.atoms.map(e=>e.otsFragment).reduce((e,t)=>e+t);if(t.length!==2048&&(t=y(t),t.length!==2048))throw new qt;let n=p(t,128),r=``;for(let t in n){let i=n[t];for(let n=0,r=8+e[t];n<r;n++)i=new c.default(`SHAKE256`,`TEXT`).update(i).getHash(`HEX`,{outputLen:512});r+=i}let i=new c.default(`SHAKE256`,`TEXT`);i.update(r);let a=i.getHash(`HEX`,{outputLen:8192}),o=new c.default(`SHAKE256`,`TEXT`);o.update(a);let s=o.getHash(`HEX`,{outputLen:256}),l=this.molecule.atoms[0],u=l.walletAddress,d=R.get(l.aggregatedMeta(),`signingWallet`);if(d&&(u=R.get(JSON.parse(d),`address`)),s!==u)throw new Jt;return!0}static fromServerData({molecularHash:e,bundleHash:t,cellSlug:n=null,status:r=null,createdAt:i=null,atoms:a=[]}){let o=a.map(e=>{let t=[];if(e.metasJson)try{let n=JSON.parse(e.metasJson);Array.isArray(n)?t=n:n&&typeof n==`object`&&(t=Object.entries(n).map(([e,t])=>({key:e,value:t})))}catch{t=[]}return{position:e.position||null,walletAddress:e.walletAddress||null,isotope:e.isotope||null,token:e.tokenSlug||e.token||null,value:e.value==null?null:String(e.value),batchId:e.batchId||null,metaType:e.metaType||null,metaId:e.metaId||null,meta:t,index:e.index==null?null:e.index,otsFragment:e.otsFragment||null,createdAt:e.createdAt||null}});return dn.fromJSON({molecularHash:e,bundle:t,cellSlug:n,status:r,createdAt:i,atoms:o})}static verifyFromServerData(t){try{let n=e.fromServerData(t);return new e(n).verify(),{molecularHash:t.molecularHash,verified:!0,error:null}}catch(e){return{molecularHash:t.molecularHash||null,verified:!1,error:e.message||String(e)}}}},ln=class extends w{constructor(e=`Insufficient balance for requested transfer`,t=null,n=null){super(e,t,n),this.name=`BalanceInsufficientException`}},un=class extends w{constructor(e=`Amount cannot be negative!`,t=null,n=null){super(e,t,n),this.name=`NegativeAmountException`}},dn=class e{constructor({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:r=null,cellSlug:i=null,version:a=null,continuIdPosition:o=null,mlKemParameterSet:s=null}){this.mlKemParameterSet=s||n&&n.mlKemParameterSet||1024,this.status=null,this.molecularHash=null,this.createdAt=String(+new Date),this.cellSlugOrigin=this.cellSlug=i,this.secret=e,this.bundle=t,this.sourceWallet=n,this.continuIdPosition=o,this.atoms=[],this.parentHashes=[],a!==null&&Object.prototype.hasOwnProperty.call(oe,a)&&(this.version=String(a)),(r||n)&&(this.remainderWallet=r||P.create({secret:e,bundle:t,token:n.token,batchId:n.batchId,characters:n.characters,mlKemParameterSet:this.mlKemParameterSet}))}withParentHashes(e){return this.parentHashes=Array.isArray(e)?[...e]:[],this}get cellSlugDelimiter(){return`.`}static isotopeFilter(e,t){return Array.isArray(e)||(e=[e]),t.filter(t=>e.includes(t.isotope))}static generateNextAtomIndex(e){return e.length}static jsonToObject(t){let n=Object.assign(new e({}),JSON.parse(t)),r=Object.keys(new e({}));if(!Array.isArray(n.atoms))throw new T;for(let e in Object.keys(n.atoms)){n.atoms[e]=E.jsonToObject(JSON.stringify(n.atoms[e]));for(let t of[`position`,`walletAddress`,`isotope`])if(n.atoms[e].isotope.toLowerCase()!==`r`&&(n.atoms[e][t]===void 0||n.atoms[e][t]===null))throw new T(`MolecularStructure::jsonToObject() - Required Atom properties are missing!`)}for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&!r.includes(e)&&delete n[e];return n.atoms=E.sortAtoms(n.atoms),n}static enumerate(e){let t={0:-8,1:-7,2:-6,3:-5,4:-4,5:-3,6:-2,7:-1,8:0,9:1,a:2,b:3,c:4,d:5,e:6,f:7,g:8},n=[],r=e.toLowerCase().split(``);for(let e=0,i=r.length;e<i;++e){let i=r[e];t[i]!==void 0&&(n[e]=t[i])}return n}static normalize(e){let t=e.reduce((e,t)=>e+t),n=t<0;for(;t<0||t>0;)for(let r of Object.keys(e))if((n?e[r]<8:e[r]>-8)&&(n?(++e[r],++t):(--e[r],--t),t===0))break;return e}getIsotopes(t){return e.isotopeFilter(t,this.atoms)}generateIndex(){return e.generateNextAtomIndex(this.atoms)}fill(e){for(let t in Object.keys(e))this[t]=e[t]}addAtom(e){return this.molecularHash=null,e.index=this.generateIndex(),e.version=this.version,this.atoms.push(e),this.atoms=E.sortAtoms(this.atoms),this}addContinuIdAtom(){(!this.remainderWallet||this.remainderWallet.token!==`USER`)&&(this.remainderWallet=P.create({secret:this.secret,bundle:this.bundle,mlKemParameterSet:this.mlKemParameterSet}));let e={};return this.continuIdPosition?e.previousPosition=this.continuIdPosition:this.sourceWallet&&this.sourceWallet.position&&(e.previousPosition=this.sourceWallet.position),this.remainderWallet.pubkey&&(e.pubkey=this.remainderWallet.pubkey),this.remainderWallet.characters&&(e.characters=this.remainderWallet.characters),this.addAtom(E.create({isotope:`I`,wallet:this.remainderWallet,metaType:`walletBundle`,metaId:this.remainderWallet.bundle,meta:new C(e)})),this}addPolicyAtom({metaType:e,metaId:t,meta:n={},policy:r={}}){let i=new C(n);return i.addPolicy(r),this.addAtom(E.create({wallet:this.sourceWallet,isotope:`R`,metaType:e,metaId:t,meta:i})),this}fuseToken(e,t){let n=e.length;if(this.sourceWallet.balance-n<0)throw new ln;return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-n})),this.addAtom(E.create({isotope:`F`,wallet:t,value:1,metaType:`walletBundle`,metaId:t.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}burnToken({amount:e,walletBundle:t=null}){if(e<0)throw new un(`Molecule::burnToken() - Amount to burn must be positive!`);if(this.sourceWallet.balance-e<0)throw new ln;let n=new P({bundle:`0000000000000000000000000000000000000000000000000000000000000000`,token:this.sourceWallet.token,mlKemParameterSet:this.mlKemParameterSet});return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(E.create({isotope:`V`,wallet:n,value:e,metaType:`walletBundle`,metaId:n.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-e,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}replenishToken({amount:e,units:t=[]}){if(e<0)throw new un(`Molecule::replenishToken() - Amount to replenish must be positive!`);if(t.length){t=P.getTokenUnits(t),this.remainderWallet.tokenUnits=this.sourceWallet.tokenUnits;for(let e of t)this.remainderWallet.tokenUnits.push(e);this.remainderWallet.balance=String(this.remainderWallet.tokenUnits.length),this.sourceWallet.tokenUnits=t,this.sourceWallet.balance=String(this.sourceWallet.tokenUnits.length)}else this.remainderWallet.balance=String(Number(this.sourceWallet.balance)+e),this.sourceWallet.balance=String(e);return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:Number(this.sourceWallet.balance)})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:Number(this.remainderWallet.balance),metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initValue({recipientWallet:e,amount:t}){if(this.sourceWallet.balance-t<0)throw new ln;return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(E.create({isotope:`V`,wallet:e,value:t,metaType:`walletBundle`,metaId:e.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-t,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initValues({recipientWallets:e,amounts:t}){let n=t.reduce((e,t)=>e+Number(t),0);if(this.sourceWallet.balance-n<0)throw new ln;return this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),e.forEach((e,n)=>{this.addAtom(E.create({isotope:`V`,wallet:e,value:t[n],metaType:`walletBundle`,metaId:e.bundle}))}),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initDepositBuffer({amount:e,tradeRates:t}){if(this.sourceWallet.balance-e<0)throw new ln;let n=P.create({secret:this.secret,bundle:this.bundle,token:this.sourceWallet.token,batchId:this.sourceWallet.batchId,mlKemParameterSet:this.mlKemParameterSet});return n.tradeRates=t,this.addAtom(E.create({isotope:`V`,wallet:this.sourceWallet,value:-this.sourceWallet.balance})),this.addAtom(E.create({isotope:`B`,wallet:n,value:e,metaType:`walletBundle`,metaId:this.sourceWallet.bundle})),this.addAtom(E.create({isotope:`V`,wallet:this.remainderWallet,value:this.sourceWallet.balance-e,metaType:`walletBundle`,metaId:this.sourceWallet.bundle})),this}initWithdrawBuffer({recipients:e,signingWallet:t=null}){let n=0;for(let t of Object.values(e||{}))n+=t;if(this.sourceWallet.balance-n<0)throw new ln;let r=new C;t&&r.setSigningWallet(t),this.addAtom(E.create({isotope:`B`,wallet:this.sourceWallet,value:-this.sourceWallet.balance,meta:r,metaType:`walletBundle`,metaId:this.sourceWallet.bundle}));for(let[t,n]of Object.entries(e||{}))this.addAtom(new E({isotope:`V`,token:this.sourceWallet.token,value:n,batchId:this.sourceWallet.batchId?ue({}):null,metaType:`walletBundle`,metaId:t}));return this.addAtom(E.create({isotope:`B`,wallet:this.remainderWallet,value:this.sourceWallet.balance-n,metaType:`walletBundle`,metaId:this.remainderWallet.bundle})),this}initTokenCreation({recipientWallet:e,amount:t,meta:n}){let r=new C(n);return r.setMetaWallet(e),this.addAtom(E.create({isotope:`C`,wallet:this.sourceWallet,value:t,metaType:`token`,metaId:e.token,meta:r,batchId:e.batchId})),this.addContinuIdAtom(),this}createRule({metaType:e,metaId:t,rule:n,policy:r={}}){let i=[];for(let e of n)i.push(e instanceof sn?e:sn.toObject(e));let a=new C({rule:JSON.stringify(i)});return a.addPolicy(r),this.addAtom(E.create({isotope:`R`,wallet:this.sourceWallet,metaType:e,metaId:t,meta:a})),this.addContinuIdAtom(),this}initWalletCreation(e,t=null){t||=new C,t.setMetaWallet(e);let n=E.create({isotope:`C`,wallet:this.sourceWallet,metaType:`wallet`,metaId:e.address,meta:t,batchId:e.batchId});return this.addAtom(n),this.addContinuIdAtom(),this}initShadowWalletClaim(e){let t=new C().setShadowWalletClaim(!0);return this.initWalletCreation(e,t)}initIdentifierCreation({type:e,contact:t,code:n}){let r={code:n,hash:ce(t.trim(),`Molecule::initIdentifierCreation`)};return this.addAtom(E.create({isotope:`C`,wallet:this.sourceWallet,metaType:`identifier`,metaId:e,meta:new C(r)})),this.addContinuIdAtom(),this}initMeta({meta:e,metaType:t,metaId:n,policy:r}){return this.addAtom(E.create({isotope:`M`,wallet:this.sourceWallet,metaType:t,metaId:n,meta:new C(e)})),r&&Object.keys(r).length>0&&this.addPolicyAtom({metaType:t,metaId:n,meta:e,policy:r}),this.addContinuIdAtom(),this}initPeering({host:e}){return this.addAtom(E.create({isotope:`P`,wallet:this.sourceWallet,metaType:`walletBundle`,metaId:this.bundle,meta:new C({peerHost:e})})),this.addContinuIdAtom(),this}initAppendRequest({metaType:e,metaId:t,action:n,meta:r={}}){return this.addAtom(E.create({isotope:`A`,wallet:this.sourceWallet,metaType:e,metaId:t,meta:new C({action:n,...r})})),this.addContinuIdAtom(),this}initTokenRequest({token:e,amount:t,metaType:n,metaId:r,meta:i={},batchId:a=null}){return i.token=e,i.amount=String(t),this.addAtom(E.create({isotope:`T`,wallet:this.sourceWallet,value:t,metaType:n,metaId:r,meta:new C(i),batchId:a})),this.addContinuIdAtom(),this}initAuthorization({meta:e}){return this.addAtom(E.create({isotope:`U`,wallet:this.sourceWallet,meta:new C(e)})),this.addContinuIdAtom(),this}sign({bundle:e=null,anonymous:t=!1,compressed:n=!0}={}){if(this.atoms.length===0||this.atoms.filter(e=>!(e instanceof E)).length!==0)throw new T;!t&&!this.bundle&&(this.bundle=e||ce(this.secret,`Molecule::sign`)),this.molecularHash=E.hashAtoms({atoms:this.atoms});let r=this.atoms[0],i=r.position,a=R.get(r.aggregatedMeta(),`signingWallet`);if(a&&(i=R.get(JSON.parse(a),`position`)),!i)throw new qt(`Signing wallet must have a position!`);let o=p(P.generateKey({secret:this.secret,token:r.token,position:r.position}),128),s=this.normalizedHash(),l=``;for(let e in o){let t=o[e];for(let n=0,r=8-s[e];n<r;n++)t=new c.default(`SHAKE256`,`TEXT`).update(t).getHash(`HEX`,{outputLen:512});l+=t}n&&(l=v(l));let u=p(l,Math.ceil(l.length/this.atoms.length)),d=null;for(let e=0,t=u.length;e<t;e++)this.atoms[e].otsFragment=u[e],d=this.atoms[e].position;return d}signSync(e={}){return this.sign(e)}cellSlugBase(){return(this.cellSlug||``).split(this.cellSlugDelimiter)[0]}toJSON(e={}){let{includeValidationContext:t=!1,includeOtsFragments:n=!0}=e;try{let e={status:this.status,molecularHash:this.molecularHash,createdAt:this.createdAt,cellSlug:this.cellSlug,bundle:this.bundle,atoms:this.atoms.map(e=>e.toJSON({includeOtsFragments:n}))};return this.parentHashes&&this.parentHashes.length>0&&(e.parentHashes=this.parentHashes),t&&(e.cellSlugOrigin=this.cellSlugOrigin,e.version=this.version,this.sourceWallet&&(e.sourceWallet={address:this.sourceWallet.address,position:this.sourceWallet.position,token:this.sourceWallet.token,balance:this.sourceWallet.balance||`0`,bundle:this.sourceWallet.bundle,batchId:this.sourceWallet.batchId||null,characters:this.sourceWallet.characters||`BASE64`,pubkey:this.sourceWallet.pubkey||null,tokenUnits:this.sourceWallet.tokenUnits||[],tradeRates:this.sourceWallet.tradeRates||{},molecules:this.sourceWallet.molecules||{}}),this.remainderWallet&&(e.remainderWallet={address:this.remainderWallet.address,position:this.remainderWallet.position,token:this.remainderWallet.token,balance:this.remainderWallet.balance||`0`,bundle:this.remainderWallet.bundle,batchId:this.remainderWallet.batchId||null,characters:this.remainderWallet.characters||`BASE64`,pubkey:this.remainderWallet.pubkey||null,tokenUnits:this.remainderWallet.tokenUnits||[],tradeRates:this.remainderWallet.tradeRates||{},molecules:this.remainderWallet.molecules||{}})),e}catch(e){throw Error(`Molecule serialization failed: ${e.message}`)}}static fromJSON(t,n={}){let{includeValidationContext:r=!1,validateStructure:i=!0}=n;try{let n=typeof t==`string`?JSON.parse(t):t;if(i&&(!n.molecularHash||!Array.isArray(n.atoms)))throw Error(`Invalid molecule data: missing molecularHash or atoms array`);let a=new e({secret:null,bundle:n.bundle||null,cellSlug:n.cellSlug||null,version:n.version||null});return a.status=n.status,a.molecularHash=n.molecularHash,a.createdAt=n.createdAt||String(+new Date),a.cellSlugOrigin=n.cellSlugOrigin,a.parentHashes=Array.isArray(n.parentHashes)?[...n.parentHashes]:[],Array.isArray(n.atoms)&&(a.atoms=n.atoms.map((e,t)=>{try{return E.fromJSON(e)}catch(e){throw Error(`Failed to reconstruct atom ${t}: ${e.message}`)}})),r&&(n.sourceWallet&&(a.sourceWallet=new P({secret:null,token:n.sourceWallet.token,position:n.sourceWallet.position,bundle:n.sourceWallet.bundle,batchId:n.sourceWallet.batchId,characters:n.sourceWallet.characters,mlKemParameterSet:a.mlKemParameterSet}),a.sourceWallet.balance=String(n.sourceWallet.balance==null?0:n.sourceWallet.balance),a.sourceWallet.address=n.sourceWallet.address,n.sourceWallet.pubkey&&(a.sourceWallet.pubkey=n.sourceWallet.pubkey),a.sourceWallet.tokenUnits=n.sourceWallet.tokenUnits||[],a.sourceWallet.tradeRates=n.sourceWallet.tradeRates||{},a.sourceWallet.molecules=n.sourceWallet.molecules||{}),n.remainderWallet&&(a.remainderWallet=new P({secret:null,token:n.remainderWallet.token,position:n.remainderWallet.position,bundle:n.remainderWallet.bundle,batchId:n.remainderWallet.batchId,characters:n.remainderWallet.characters,mlKemParameterSet:a.mlKemParameterSet}),a.remainderWallet.balance=String(n.remainderWallet.balance==null?0:n.remainderWallet.balance),a.remainderWallet.address=n.remainderWallet.address,n.remainderWallet.pubkey&&(a.remainderWallet.pubkey=n.remainderWallet.pubkey),a.remainderWallet.tokenUnits=n.remainderWallet.tokenUnits||[],a.remainderWallet.tradeRates=n.remainderWallet.tradeRates||{},a.remainderWallet.molecules=n.remainderWallet.molecules||{})),a}catch(e){throw Error(`Molecule deserialization failed: ${e.message}`)}}check(e=null){return new cn(this).verify(e)}normalizedHash(){return e.normalize(e.enumerate(this.molecularHash))}},fn=class e{constructor({token:e,expiresAt:t,encrypt:n,pubkey:r}){this.$__token=e,this.$__expiresAt=t,this.$__pubkey=r,this.$__encrypt=n}static create(t,n){let r=new e(t);return r.setWallet(n),r}static resolveMlKemParameterSet(e){let t=e.wallet&&e.wallet.mlKemParameterSet;return t?Number(t):P.mlKemParameterSetFromPubkey(e.pubkey)||768}static restore(t,n){let r=new P({secret:n,token:`AUTH`,position:t.wallet.position,characters:t.wallet.characters,mlKemParameterSet:e.resolveMlKemParameterSet(t)});return e.create({token:t.token,expiresAt:t.expiresAt,pubkey:t.pubkey,encrypt:t.encrypt},r)}setWallet(e){this.$__wallet=e}getWallet(){return this.$__wallet}getSnapshot(){return{token:this.$__token,expiresAt:this.$__expiresAt,pubkey:this.$__pubkey,encrypt:this.$__encrypt,wallet:{position:this.$__wallet.position,characters:this.$__wallet.characters,mlKemParameterSet:this.$__wallet.mlKemParameterSet}}}getToken(){return this.$__token}getPubkey(){return this.$__pubkey}getExpireInterval(){return this.$__expiresAt*1e3-Date.now()}isExpired(){return!this.$__expiresAt||this.getExpireInterval()<0}getAuthData(){return{token:this.getToken(),pubkey:this.getPubkey(),wallet:this.getWallet()}}},z=class e extends w{constructor(e=`Secret storage operation failed`,t=null,n=null){super(e,t,n),this.name=`SecretStorageException`}static notFound(t){return new e(`Secret not found for bundle: ${t}`)}static decryptionFailed(t=`Invalid passphrase or corrupted ciphertext`){return new e(`Failed to decrypt master secret: ${t}`)}static unavailable(t,n=`Hardware or API not accessible`){return new e(`Secret storage provider '${t}' is unavailable: ${n}`)}static validationError(t){return new e(t)}},pn=new TextEncoder;function B(e){if(e instanceof Uint8Array)e.fill(0);else if(Array.isArray(e))for(let t=0;t<e.length;t++)e[t]=0}async function mn(e,t){try{return await t(e)}finally{B(e)}}async function hn(e,t){let n=pn.encode(e);try{return await t(e)}finally{B(n)}}function gn(e,t){let n=typeof e==`string`?pn.encode(e):e,r=typeof t==`string`?pn.encode(t):t,i=n.length===r.length?0:1,a=Math.min(n.length,r.length);for(let e=0;e<a;e++)i|=(n[e]??0)^(r[e]??0);return typeof e==`string`&&B(n),typeof t==`string`&&B(r),i===0}var _n=`AES-GCM`,vn=1e5,yn=`knishio:secret:`,V=`knishio:recovery:`,bn=12,xn=16,Sn=new TextEncoder;function H(e){let t=``,n=e.byteLength;for(let r=0;r<n;r++){let n=e[r];n!==void 0&&(t+=String.fromCharCode(n))}return btoa(t)}function U(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r}async function Cn(e,t,n=vn){if(globalThis.crypto===void 0||globalThis.crypto.subtle===void 0)throw new z(`WebCrypto API is not available`);let r=Sn.encode(e);try{let e=await globalThis.crypto.subtle.importKey(`raw`,r,`PBKDF2`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`PBKDF2`,salt:t,iterations:n,hash:`SHA-256`},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}finally{B(r)}}async function W(e,t,n){if(globalThis.crypto===void 0||globalThis.crypto.subtle===void 0)throw new z(`WebCrypto API is not available`);let r=new Uint8Array(xn),i=new Uint8Array(bn);globalThis.crypto.getRandomValues(r),globalThis.crypto.getRandomValues(i);let a=await Cn(t,r,vn),o=Sn.encode(e);try{let e=await globalThis.crypto.subtle.encrypt({name:_n,iv:i},a,o);return{version:1,ciphertext:H(new Uint8Array(e)),iv:H(i),salt:H(r),algorithm:_n,iterations:vn,metadata:n}}finally{B(o)}}async function G(e,t){if(globalThis.crypto===void 0||globalThis.crypto.subtle===void 0)throw new z(`WebCrypto API is not available`);let n=U(e.salt),r=U(e.iv),i=U(e.ciphertext),a=await Cn(t,n,e.iterations??1e5),o=await globalThis.crypto.subtle.decrypt({name:_n,iv:r},a,i);return new Uint8Array(o)}var wn=class{constructor(){this.providerType=`memory`,this.secrets=new Map,this.recoverySecrets=new Map}isHardwareBacked(){return!1}async isAvailable(){return!0}async storeSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Secret cannot be empty`);let r={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:this.providerType};if(this.secrets.set(e,{secret:t,metadata:r}),n.recoveryPassphrase){let r={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:`webcrypto-aes-gcm`},i=await W(t,n.recoveryPassphrase,r);this.recoverySecrets.set(e,JSON.stringify(i))}}async retrieveSecret(e){let t=this.secrets.get(e);return t?t.secret:null}async deleteSecret(e){return this.recoverySecrets.delete(e),this.secrets.delete(e)}async hasSecret(e){return this.secrets.has(e)}async listSecrets(){return Array.from(this.secrets.values()).map(e=>({...e.metadata}))}async withSecret(e,t){let n=this.secrets.get(e);if(!n)throw z.notFound(e);return hn(n.secret,t)}clear(){this.secrets.clear(),this.recoverySecrets.clear()}async recoverSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Recovery passphrase cannot be empty`);let r=this.recoverySecrets.get(e);if(!r)throw z.notFound(e);let i;try{i=JSON.parse(r)}catch{throw z.decryptionFailed(`Corrupted recovery payload format`)}let a;try{a=await G(i,t)}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}let o;try{o=new TextDecoder().decode(a)}finally{B(a)}await this.storeSecret(e,o,{...n,recoveryPassphrase:t})}},Tn=10**18,En=class e{static val(e){return Math.abs(e*Tn)<1?0:e}static cmp(t,n,r=!1){let i=e.val(t)*Tn,a=e.val(n)*Tn;return Math.abs(i-a)<1?0:i>a?1:-1}static equal(t,n){return e.cmp(t,n)===0}},K=class extends w{constructor(e=`GraphQL did not provide a valid response.`,t=null,n=null){super(e,t,n),this.name=`InvalidResponseException`}},Dn=class extends w{constructor(e=`Authorization token missing or invalid.`,t=null,n=null){super(e,t,n),this.name=`UnauthenticatedException`}},q=class{constructor({query:e,json:t,dataKey:n=null}){if(this.dataKey=n,this.errorKey=`exception`,this.$__payload=null,this.$__query=e,this.$__originResponse=t,this.$__response=t,this.$__response===void 0||this.$__response===null)throw new K;if(R.has(this.$__response,this.errorKey)){let e=R.get(this.$__response,this.errorKey);throw String(e).includes(`Unauthenticated`)?new Dn:new K}if(this.$__response.errors&&Array.isArray(this.$__response.errors)&&this.$__response.errors.length>0){let e=this.$__response.errors[0].message||`Unknown GraphQL error`;throw e.includes(`Unauthenticated`)?new Dn:new K(`GraphQL Error: ${e}`)}this.init()}init(){}data(){if(!this.dataKey)return this.response();if(!this.response().data)throw new K(`Response has no data field`);if(!R.has(this.response(),this.dataKey))throw new K(`Missing expected field: ${this.dataKey}`);return R.get(this.response(),this.dataKey)}response(){return this.$__response}payload(){return null}query(){return this.$__query}status(){return null}success(){return!this.$__response?.errors?.length}error(){return this.$__response?.errors?.length?this.$__response.errors[0].message||`Unknown error`:null}reason(){return this.error()}toValidationResult(){return this.success()&&this.payload()!==null?{success:!0,data:this.payload(),warnings:[]}:{success:!1,error:{message:this.reason()||`Unknown error`,context:this.constructor.name,details:this.$__response?.errors||[]}}}onSuccess(e){if(this.success()&&this.payload()!==null)try{e(this.payload())}catch(e){console.warn(`Response.onSuccess callback failed:`,e)}return this}onFailure(e){if(!this.success())try{e(this.reason()||`Unknown error`)}catch(e){console.warn(`Response.onFailure callback failed:`,e)}return this}debug(e=null){let t=e?`[${e}]`:`[${this.constructor.name}]`;return this.success()?console.debug(`${t} Success:`,{payload:this.payload(),query:this.$__query?.constructor?.name,dataKey:this.dataKey}):console.debug(`${t} Failure:`,{error:this.reason(),errors:this.$__response?.errors,rawData:this.$__response}),this}toPromise(){return this.success()&&this.payload()!==null?Promise.resolve(this.payload()):Promise.reject(Error(this.reason()||`Unknown error`))}map(e){if(this.success()&&this.payload()!==null)try{let t=e(this.payload()),n=Object.create(Object.getPrototypeOf(this));return Object.assign(n,this),n.$__payload=t,n}catch(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this),t.$__response={errors:[{message:`Mapping failed: ${e.message}`}]},t}return this}},J=class{constructor(e,t){this.client=e,this.knishIOClient=t,this.$__variables=null,this.$__query=null,this.$__response=null,this.$__request=null}response(){return this.$__response}async createResponseRaw(e){return this.createResponse(e)}createResponse(e){return new q({query:this,json:e})}createQuery({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new L(`Query::createQuery() - Node URI was not initialized for this client instance!`);if(this.$__query===null)throw new L(`Query::createQuery() - GraphQL subscription was not initialized!`);return{query:this.$__query,variables:this.variables()}}async execute({variables:e=null,context:t={}}){this.$__request=this.createQuery({variables:e});let n={...t,...this.createQueryContext()};try{let e=await this.client.query({...this.$__request,context:n});return this.$__response=await this.createResponseRaw(e),this.$__response}catch(e){if(e.name===`AbortError`)return this.knishIOClient.log(`warn`,`Query was cancelled`),new q({query:this,json:{data:null,errors:[{message:`Query was cancelled`}]}});throw e}}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}createQueryContext(){return{}}},On=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ContinuId`})}payload(){let e=null,t=this.data();return t&&(e=new P({secret:null,token:t.tokenSlug}),e.address=t.address,e.position=t.position,e.bundle=t.bundleHash,e.batchId=t.batchId,e.characters=t.characters,e.pubkey=t.pubkey,e.balance=String(t.amount==null?0:t.amount)),e}},kn=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query ($bundle: String!) {
3
3
  ContinuId(bundle: $bundle) {
4
4
  address,
5
5
  bundleHash,
@@ -11,7 +11,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
11
11
  amount,
12
12
  createdAt
13
13
  }
14
- }`}createQueryContext(){return{requestPolicy:`network-only`}}createResponse(e){return new vn({query:this,json:e})}},bn=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.WalletBundle`})}payload(){let e=this.data();if(!e||e.length===0)return null;let t={};return e.forEach(e=>{e.metas=x.aggregateMeta(e.metas),t[e.bundleHash]=e}),t}},xn=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $bundleHashes: [ String! ] ) {
14
+ }`}createQueryContext(){return{requestPolicy:`network-only`}}createResponse(e){return new On({query:this,json:e})}},An=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.WalletBundle`})}payload(){let e=this.data();if(!e||e.length===0)return null;let t={};return e.forEach(e=>{e.metas=x.aggregateMeta(e.metas),t[e.bundleHash]=e}),t}},jn=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $bundleHashes: [ String! ] ) {
15
15
  WalletBundle( bundleHashes: $bundleHashes ) {
16
16
  bundleHash,
17
17
  metas {
@@ -23,7 +23,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
23
23
  },
24
24
  createdAt
25
25
  }
26
- }`}createResponse(e){return new bn({query:this,json:e})}},Sn=class e extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.Wallet`})}static toClientWallet({data:e,secret:t=null}){let n;if(e.position===null||e.position===void 0?n=I.create({bundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(n=new I({secret:t,token:e.tokenSlug,position:e.position,batchId:e.batchId,characters:e.characters}),n.address=e.address,n.bundle=e.bundleHash),e.token&&(n.tokenName=e.token.name,n.tokenAmount=e.token.amount,n.tokenSupply=e.token.supply,n.tokenFungibility=e.token.fungibility),e.tokenUnits.length)for(let t of e.tokenUnits)n.tokenUnits.push(ue.createFromGraphQL(t));if(e.tradeRates.length)for(let t of e.tradeRates)n.tradeRates[t.tokenSlug]=t.amount;return n.balance=String(e.amount==null?0:e.amount),n.pubkey=e.pubkey,n.createdAt=e.createdAt,n}getWallets(t=null){let n=this.data();if(!n)return null;let r=[];for(let i of n)r.push(e.toClientWallet({data:i,secret:t}));return r}payload(){return this.getWallets()}},Cn=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $bundleHash: String, $token: String ) {
26
+ }`}createResponse(e){return new An({query:this,json:e})}},Mn=class e extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.Wallet`})}static toClientWallet({data:e,secret:t=null}){let n;if(e.position===null||e.position===void 0?n=P.create({bundle:e.bundleHash,token:e.tokenSlug,batchId:e.batchId,characters:e.characters}):(n=new P({secret:t,token:e.tokenSlug,position:e.position,batchId:e.batchId,characters:e.characters}),n.address=e.address,n.bundle=e.bundleHash),e.token&&(n.tokenName=e.token.name,n.tokenAmount=e.token.amount,n.tokenSupply=e.token.supply,n.tokenFungibility=e.token.fungibility),e.tokenUnits.length)for(let t of e.tokenUnits)n.tokenUnits.push(de.createFromGraphQL(t));if(e.tradeRates.length)for(let t of e.tradeRates)n.tradeRates[t.tokenSlug]=t.amount;return n.balance=String(e.amount==null?0:e.amount),n.pubkey=e.pubkey,n.createdAt=e.createdAt,n}getWallets(t=null){let n=this.data();if(!n)return null;let r=[];for(let i of n)r.push(e.toClientWallet({data:i,secret:t}));return r}payload(){return this.getWallets()}},Nn=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $bundleHash: String, $token: String ) {
27
27
  Wallet( bundleHash: $bundleHash, token: $token ) {
28
28
  address,
29
29
  bundleHash,
@@ -50,7 +50,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
50
50
  amount
51
51
  }
52
52
  }
53
- }`}createResponse(e){return new Sn({query:this,json:e})}},wn=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.Balance`})}payload(){let e=this.data();return Array.isArray(e)&&(e=e.length>0?e[0]:null),!e||!e.bundleHash||!e.tokenSlug?null:Sn.toClientWallet({data:e})}},Tn=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $address: String, $bundleHash: String, $type: String, $token: String, $position: String ) {
53
+ }`}createResponse(e){return new Mn({query:this,json:e})}},Pn=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.Balance`})}payload(){let e=this.data();return Array.isArray(e)&&(e=e.length>0?e[0]:null),!e||!e.bundleHash||!e.tokenSlug?null:Mn.toClientWallet({data:e})}},Fn=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $address: String, $bundleHash: String, $type: String, $token: String, $position: String ) {
54
54
  Balance( address: $address, bundleHash: $bundleHash, type: $type, token: $token, position: $position ) {
55
55
  address,
56
56
  bundleHash,
@@ -72,7 +72,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
72
72
  amount
73
73
  }
74
74
  }
75
- }`}createResponse(e){return new wn({query:this,json:e})}},En=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.MetaType`})}payload(){let e=this.data();if(!e||e.length===0)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}},Dn=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $queryArgs: QueryArgs, $countBy: String, $cellSlug: String ) {
75
+ }`}createResponse(e){return new Pn({query:this,json:e})}},In=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.MetaType`})}payload(){let e=this.data();if(!e||e.length===0)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}},Ln=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $metaType: String, $metaTypes: [ String! ], $metaId: String, $metaIds: [ String! ], $key: String, $keys: [ String! ], $value: String, $values: [ String! ], $count: String, $latest: Boolean, $filter: [ MetaFilter! ], $queryArgs: QueryArgs, $countBy: String, $cellSlug: String ) {
76
76
  MetaType( metaType: $metaType, metaTypes: $metaTypes, metaId: $metaId, metaIds: $metaIds, key: $key, keys: $keys, value: $value, values: $values, count: $count, filter: $filter, queryArgs: $queryArgs, countBy: $countBy, cellSlug: $cellSlug ) {
77
77
  metaType,
78
78
  instanceCount {
@@ -96,7 +96,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
96
96
  total
97
97
  }
98
98
  }
99
- }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:r=null,latest:i=null,filter:a=null,queryArgs:o=null,count:s=null,countBy:c=null,cellSlug:l=null}){let u={};return e&&(u[typeof e==`string`?`metaType`:`metaTypes`]=e),t&&(u[typeof t==`string`?`metaId`:`metaIds`]=t),n&&(u[typeof n==`string`?`key`:`keys`]=n),r&&(u[typeof r==`string`?`value`:`values`]=r),u.latest=i===!0,a&&(u.filter=a),o&&((o.limit===void 0||o.limit===0)&&(o.limit=`*`),u.queryArgs=o),s&&(u.count=s),c&&(u.countBy=c),l&&(u.cellSlug=l),u}createResponse(e){return new En({query:this,json:e})}},On=class e extends K{constructor(t,n){super(t,n),this.$__query=l.gql`query( $batchId: String ) {
99
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:r=null,latest:i=null,filter:a=null,queryArgs:o=null,count:s=null,countBy:c=null,cellSlug:l=null}){let u={};return e&&(u[typeof e==`string`?`metaType`:`metaTypes`]=e),t&&(u[typeof t==`string`?`metaId`:`metaIds`]=t),n&&(u[typeof n==`string`?`key`:`keys`]=n),r&&(u[typeof r==`string`?`value`:`values`]=r),u.latest=i===!0,a&&(u.filter=a),o&&((o.limit===void 0||o.limit===0)&&(o.limit=`*`),u.queryArgs=o),s&&(u.count=s),c&&(u.countBy=c),l&&(u.cellSlug=l),u}createResponse(e){return new In({query:this,json:e})}},Rn=class e extends J{constructor(t,n){super(t,n),this.$__query=l.gql`query( $batchId: String ) {
100
100
  Batch( batchId: $batchId ) {
101
101
  ${e.getFields()},
102
102
  children {
@@ -152,11 +152,11 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
152
152
  throughMetas {
153
153
  key,
154
154
  value
155
- }`}createResponse(e){let t=new G({query:this,json:e});return t.dataKey=`data.Batch`,t}},kn=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $batchId: String ) {
155
+ }`}createResponse(e){let t=new q({query:this,json:e});return t.dataKey=`data.Batch`,t}},zn=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $batchId: String ) {
156
156
  BatchHistory( batchId: $batchId ) {
157
- ${On.getFields()}
157
+ ${Rn.getFields()}
158
158
  }
159
- }`}createResponse(e){let t=new G({query:this,json:e});return t.dataKey=`data.BatchHistory`,t}},q=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ProposeMolecule`}),this.$__clientMolecule=e.molecule()}init(){let e=V.get(this.data(),`payload`);try{this.$__payload=Object.prototype.toString.call(e)===`[object String]`?JSON.parse(e):e}catch{this.$__payload=null}}clientMolecule(){return this.$__clientMolecule}molecule(){let e=this.data();if(!e)return null;let t=new cn({});return t.molecularHash=V.get(e,`molecularHash`),t.status=V.get(e,`status`),t.createdAt=V.get(e,`createdAt`),t}success(){return this.status()===`accepted`}status(){return V.get(this.data(),`status`,`rejected`)}reason(){return V.get(this.data(),`reason`,`Invalid response from server`)}payload(){return this.$__payload}},An=class extends K{createQuery({variables:e=null}){let t=super.createQuery({variables:e});return t.mutation=t.query,delete t.query,t}async execute({variables:e={},context:t={}}){this.$__request=this.createQuery({variables:e});let n={...t,...this.createQueryContext()};try{let e={...this.$__request,context:n},t=await this.client.mutate(e);return this.$__response=await this.createResponseRaw(t),this.$__response}catch(e){if(e.name===`AbortError`)return this.knishIOClient.log(`warn`,`Mutation was cancelled`),new G({query:this,json:{data:null,errors:[{message:`Mutation was cancelled`}]}});throw e}}createQueryContext(){return{}}},J=class extends An{constructor(e,t,n){super(e,t),this.$__molecule=n,this.$__remainderWallet=null,this.$__query=l.gql`mutation( $molecule: MoleculeInput! ) {
159
+ }`}createResponse(e){let t=new q({query:this,json:e});return t.dataKey=`data.BatchHistory`,t}},Y=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ProposeMolecule`}),this.$__clientMolecule=e.molecule()}init(){let e=R.get(this.data(),`payload`);try{this.$__payload=Object.prototype.toString.call(e)===`[object String]`?JSON.parse(e):e}catch{this.$__payload=null}}clientMolecule(){return this.$__clientMolecule}molecule(){let e=this.data();if(!e)return null;let t=new dn({});return t.molecularHash=R.get(e,`molecularHash`),t.status=R.get(e,`status`),t.createdAt=R.get(e,`createdAt`),t}success(){return this.status()===`accepted`}status(){return R.get(this.data(),`status`,`rejected`)}reason(){return R.get(this.data(),`reason`,`Invalid response from server`)}payload(){return this.$__payload}},Bn=class extends J{createQuery({variables:e=null}){let t=super.createQuery({variables:e});return t.mutation=t.query,delete t.query,t}async execute({variables:e={},context:t={}}){this.$__request=this.createQuery({variables:e});let n={...t,...this.createQueryContext()};try{let e={...this.$__request,context:n},t=await this.client.mutate(e);return this.$__response=await this.createResponseRaw(t),this.$__response}catch(e){if(e.name===`AbortError`)return this.knishIOClient.log(`warn`,`Mutation was cancelled`),new q({query:this,json:{data:null,errors:[{message:`Mutation was cancelled`}]}});throw e}}createQueryContext(){return{}}},X=class extends Bn{constructor(e,t,n){super(e,t),this.$__molecule=n,this.$__remainderWallet=null,this.$__query=l.gql`mutation( $molecule: MoleculeInput! ) {
160
160
  ProposeMolecule( molecule: $molecule ) {
161
161
  molecularHash,
162
162
  height,
@@ -169,7 +169,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
169
169
  processedAt,
170
170
  broadcastedAt,
171
171
  }
172
- }`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new q({query:this,json:e})}async execute({variables:e=null}){return e||={},e.molecule=this.molecule(),super.execute({variables:e})}remainderWallet(){return this.$__remainderWallet}molecule(){return this.$__molecule}},jn=class extends q{payloadKey(e){if(!V.has(this.payload(),e))throw new W(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return V.get(this.payload(),e)}token(){return this.payloadKey(`token`)}time(){return this.payloadKey(`time`)}expiresAt(){try{let e=this.payloadKey(`expiresAt`);if(e)return Number(e)}catch{}let e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}encrypt(){return this.payloadKey(`encrypt`)}pubKey(){return this.payloadKey(`key`)}},Mn=class extends J{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new jn({query:this,json:e})}},Nn=class extends q{},Pn=class extends J{fillMolecule({recipientWallet:e,amount:t,meta:n=null}){this.$__molecule.initTokenCreation({recipientWallet:e,amount:t,meta:n||{}}),this.$__molecule.sign({bundle:e.bundle}),this.$__molecule.check()}createResponse(e){return new Nn({query:this,json:e})}},Fn=class extends q{},In=class extends J{fillMolecule({token:e,amount:t,metaType:n,metaId:r,meta:i=null,batchId:a=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:n,metaId:r,meta:i||{},batchId:a}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Fn({query:this,json:e})}},Ln=class extends q{payload(){let e={reason:null,status:null},t=this.data();return e.reason=t.reason===void 0?`Invalid response from server`:t.reason,e.status=t.status===void 0?`rejected`:t.status,e}},Rn=class extends J{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}fillMoleculeMulti({recipientWallets:e,amounts:t}){this.$__molecule.initValues({recipientWallets:e,amounts:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new Ln({query:this,json:e})}},zn=class extends q{},Bn=class extends J{fillMolecule({type:e,contact:t,code:n}){this.$__molecule.initIdentifierCreation({type:e,contact:t,code:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new zn({query:this,json:e})}},Vn=class extends q{},Hn=class extends J{fillMolecule({token:e,batchId:t=null}){let n=I.create({secret:this.$__molecule.secret,bundle:this.$__molecule.bundle,token:e,batchId:t});this.$__molecule.initShadowWalletClaim(n),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Vn({query:this,json:e})}},Un=class extends q{},Wn=class extends J{fillMolecule({metaType:e,metaId:t,meta:n,policy:r}){this.$__molecule.initMeta({meta:n,metaType:e,metaId:t,policy:r}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Un({query:this,json:e})}},Gn=class extends q{},Kn=class extends J{fillMolecule({host:e}){this.$__molecule.initPeering({host:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Gn({query:this,json:e})}},qn=class extends q{},Jn=class extends J{fillMolecule({metaType:e,metaId:t,action:n,meta:r={}}){this.$__molecule.initAppendRequest({metaType:e,metaId:t,action:n,meta:r}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new qn({query:this,json:e})}},Yn=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.LinkIdentifier`})}success(){return V.get(this.data(),`set`)}message(){return V.get(this.data(),`message`)}},Xn=class extends An{constructor(e,t){super(e,t),this.$__query=l.gql`mutation( $bundle: String!, $type: String!, $content: String! ) {
172
+ }`}compiledVariables(e){return{...super.compiledVariables(e),molecule:this.molecule()}}createResponse(e){return new Y({query:this,json:e})}async execute({variables:e=null}){return e||={},e.molecule=this.molecule(),super.execute({variables:e})}remainderWallet(){return this.$__remainderWallet}molecule(){return this.$__molecule}},Vn=class extends Y{payloadKey(e){if(!R.has(this.payload(),e))throw new K(`ResponseRequestAuthorization::payloadKey() - '${e}' key was not found in the payload!`);return R.get(this.payload(),e)}token(){return this.payloadKey(`token`)}time(){return this.payloadKey(`time`)}expiresAt(){try{let e=this.payloadKey(`expiresAt`);if(e)return Number(e)}catch{}let e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}encrypt(){return this.payloadKey(`encrypt`)}pubKey(){return this.payloadKey(`key`)}},Hn=class extends X{fillMolecule({meta:e}){this.$__molecule.initAuthorization({meta:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Vn({query:this,json:e})}},Un=class extends Y{},Wn=class extends X{fillMolecule({recipientWallet:e,amount:t,meta:n=null}){this.$__molecule.initTokenCreation({recipientWallet:e,amount:t,meta:n||{}}),this.$__molecule.sign({bundle:e.bundle}),this.$__molecule.check()}createResponse(e){return new Un({query:this,json:e})}},Gn=class extends Y{},Kn=class extends X{fillMolecule({token:e,amount:t,metaType:n,metaId:r,meta:i=null,batchId:a=null}){this.$__molecule.initTokenRequest({token:e,amount:t,metaType:n,metaId:r,meta:i||{},batchId:a}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Gn({query:this,json:e})}},qn=class extends Y{payload(){let e={reason:null,status:null},t=this.data();return e.reason=t.reason===void 0?`Invalid response from server`:t.reason,e.status=t.status===void 0?`rejected`:t.status,e}},Jn=class extends X{fillMolecule({recipientWallet:e,amount:t}){this.$__molecule.initValue({recipientWallet:e,amount:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}fillMoleculeMulti({recipientWallets:e,amounts:t}){this.$__molecule.initValues({recipientWallets:e,amounts:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}createResponse(e){return new qn({query:this,json:e})}},Yn=class extends Y{},Xn=class extends X{fillMolecule({type:e,contact:t,code:n}){this.$__molecule.initIdentifierCreation({type:e,contact:t,code:n}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Yn({query:this,json:e})}},Zn=class extends Y{},Qn=class extends X{fillMolecule({token:e,batchId:t=null}){let n=P.create({secret:this.$__molecule.secret,bundle:this.$__molecule.bundle,token:e,batchId:t});this.$__molecule.initShadowWalletClaim(n),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Zn({query:this,json:e})}},$n=class extends Y{},er=class extends X{fillMolecule({metaType:e,metaId:t,meta:n,policy:r}){this.$__molecule.initMeta({meta:n,metaType:e,metaId:t,policy:r}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new $n({query:this,json:e})}},tr=class extends Y{},nr=class extends X{fillMolecule({host:e}){this.$__molecule.initPeering({host:e}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new tr({query:this,json:e})}},rr=class extends Y{},ir=class extends X{fillMolecule({metaType:e,metaId:t,action:n,meta:r={}}){this.$__molecule.initAppendRequest({metaType:e,metaId:t,action:n,meta:r}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new rr({query:this,json:e})}},ar=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.LinkIdentifier`})}success(){return R.get(this.data(),`set`)}message(){return R.get(this.data(),`message`)}},or=class extends Bn{constructor(e,t){super(e,t),this.$__query=l.gql`mutation( $bundle: String!, $type: String!, $content: String! ) {
173
173
  LinkIdentifier( bundle: $bundle, type: $type, content: $content ) {
174
174
  type,
175
175
  bundle,
@@ -177,13 +177,13 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
177
177
  set,
178
178
  message
179
179
  }
180
- }`}createResponse(e){return new Yn({query:this,json:e})}},Zn=class extends q{},Qn=class extends J{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Zn({query:this,json:e})}},$n=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.AccessToken`})}reason(){return`Invalid response from server`}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!V.has(this.payload(),e))throw new W(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return V.get(this.payload(),e)}token(){return this.payloadKey(`token`)}time(){return this.payloadKey(`time`)}expiresAt(){try{let e=this.payloadKey(`expiresAt`);if(e)return Number(e)}catch{}let e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}pubKey(){return this.payloadKey(`key`)}encrypt(){return this.payloadKey(`encrypt`)}},er=class extends An{constructor(e,t){super(e,t),this.$__query=l.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
180
+ }`}createResponse(e){return new ar({query:this,json:e})}},sr=class extends Y{},cr=class extends X{fillMolecule(e){this.$__molecule.initWalletCreation(e),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new sr({query:this,json:e})}},lr=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.AccessToken`})}reason(){return`Invalid response from server`}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!R.has(this.payload(),e))throw new K(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return R.get(this.payload(),e)}token(){return this.payloadKey(`token`)}time(){return this.payloadKey(`time`)}expiresAt(){try{let e=this.payloadKey(`expiresAt`);if(e)return Number(e)}catch{}let e=Number(this.time());return e>=1577836800?e:Math.floor(Date.now()/1e3)+Math.floor(e/1e3)}pubKey(){return this.payloadKey(`key`)}encrypt(){return this.payloadKey(`encrypt`)}},ur=class extends Bn{constructor(e,t){super(e,t),this.$__query=l.gql`mutation( $cellSlug: String, $pubkey: String, $encrypt: Boolean ) {
181
181
  AccessToken( cellSlug: $cellSlug, pubkey: $pubkey, encrypt: $encrypt ) {
182
182
  token,
183
183
  pubkey,
184
184
  expiresAt
185
185
  }
186
- }`}createResponse(e){return new $n({query:this,json:e})}},tr=class extends w{constructor(e=`The shadow wallet does not exist`,t=null,n=null){super(e,t,n),this.name=`WalletShadowException`}},nr=class extends w{constructor(e=`Stackable tokens with unit IDs cannot have decimal places!`,t=null,n=null){super(e,t,n),this.name=`StackableUnitDecimalsException`}},rr=class extends w{constructor(e=`Stackable tokens with unit IDs cannot have an amount!`,t=null,n=null){super(e,t,n),this.name=`StackableUnitAmountException`}},ir=class{constructor(e){this.client=e,this.$__variables=null,this.$__subscribe=null}createSubscribe({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new B(`Subscribe::createSubscribe() - Node URI was not initialized for this client instance!`);if(this.$__subscribe===null)throw new B(`Subscribe::createSubscribe() - GraphQL subscription was not initialized!`);return{query:this.$__subscribe,variables:this.variables(),fetchPolicy:`no-cache`}}async execute({variables:e=null,closure:t}){if(!t)throw new B(`${this.constructor.name}::execute() - closure parameter is required!`);return this.$__request=this.createSubscribe({variables:e}),this.client.subscribe(this.$__request,t)}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}},ar=class extends ir{constructor(e){super(e),this.$__subscribe=l.gql`
186
+ }`}createResponse(e){return new lr({query:this,json:e})}},dr=class extends w{constructor(e=`The shadow wallet does not exist`,t=null,n=null){super(e,t,n),this.name=`WalletShadowException`}},fr=class extends w{constructor(e=`Stackable tokens with unit IDs cannot have decimal places!`,t=null,n=null){super(e,t,n),this.name=`StackableUnitDecimalsException`}},pr=class extends w{constructor(e=`Stackable tokens with unit IDs cannot have an amount!`,t=null,n=null){super(e,t,n),this.name=`StackableUnitAmountException`}},mr=class{constructor(e){this.client=e,this.$__variables=null,this.$__subscribe=null}createSubscribe({variables:e=null}){if(this.$__variables=this.compiledVariables(e),!this.uri())throw new L(`Subscribe::createSubscribe() - Node URI was not initialized for this client instance!`);if(this.$__subscribe===null)throw new L(`Subscribe::createSubscribe() - GraphQL subscription was not initialized!`);return{query:this.$__subscribe,variables:this.variables(),fetchPolicy:`no-cache`}}async execute({variables:e=null,closure:t}){if(!t)throw new L(`${this.constructor.name}::execute() - closure parameter is required!`);return this.$__request=this.createSubscribe({variables:e}),this.client.subscribe(this.$__request,t)}compiledVariables(e=null){return e||{}}uri(){return this.client.getUri()}variables(){return this.$__variables}},hr=class extends mr{constructor(e){super(e),this.$__subscribe=l.gql`
187
187
  subscription onCreateMolecule ( $bundle: String! ) {
188
188
  CreateMolecule( bundle: $bundle ) {
189
189
  molecularHash,
@@ -228,7 +228,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
228
228
  }
229
229
  }
230
230
  }
231
- `}},or=class extends ir{constructor(e){super(e),this.$__subscribe=l.gql`
231
+ `}},gr=class extends mr{constructor(e){super(e),this.$__subscribe=l.gql`
232
232
  subscription onWalletStatus ( $bundle: String!, $token: String! ) {
233
233
  WalletStatus( bundle: $bundle, token: $token ) {
234
234
  bundle,
@@ -237,7 +237,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
237
237
  balance,
238
238
  }
239
239
  }
240
- `}},sr=class extends ir{constructor(e){super(e),this.$__subscribe=l.gql`
240
+ `}},_r=class extends mr{constructor(e){super(e),this.$__subscribe=l.gql`
241
241
  subscription onActiveWallet ( $bundle: String! ) {
242
242
  ActiveWallet( bundle: $bundle ) {
243
243
  address,
@@ -275,7 +275,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
275
275
  }
276
276
  }
277
277
  }
278
- `}},cr=class extends ir{constructor(e){super(e),this.$__subscribe=l.gql`
278
+ `}},vr=class extends mr{constructor(e){super(e),this.$__subscribe=l.gql`
279
279
  subscription onActiveUser ( $metaType: String!, $metaId: String! ) {
280
280
  ActiveUser( metaType: $metaType, metaId: $metaId ) {
281
281
  bundleHash,
@@ -285,7 +285,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
285
285
  createdAt,
286
286
  updatedAt
287
287
  }
288
- }`}},lr=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ActiveSession`})}},ur=class extends An{constructor(e,t){super(e,t),this.$__query=l.gql`mutation(
288
+ }`}},yr=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ActiveSession`})}},br=class extends Bn{constructor(e,t){super(e,t),this.$__query=l.gql`mutation(
289
289
  $bundleHash: String!,
290
290
  $metaType: String!,
291
291
  $metaId: String!,
@@ -313,7 +313,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
313
313
  createdAt,
314
314
  updatedAt
315
315
  }
316
- }`}createResponse(e){return new lr({query:this,json:e})}},dr=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ActiveUser`})}payload(){let e=this.data();if(!e)return null;let t=[];for(let n of e){let e={...n};e.jsonData&&=JSON.parse(e.jsonData),e.createdAt&&=new Date(e.createdAt),e.updatedAt&&=new Date(e.updatedAt),t.push(e)}return t}},fr=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
316
+ }`}createResponse(e){return new yr({query:this,json:e})}},xr=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.ActiveUser`})}payload(){let e=this.data();if(!e)return null;let t=[];for(let n of e){let e={...n};e.jsonData&&=JSON.parse(e.jsonData),e.createdAt&&=new Date(e.createdAt),e.updatedAt&&=new Date(e.updatedAt),t.push(e)}return t}},Sr=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query ActiveUserQuery ($bundleHash:String, $metaType: String, $metaId: String) {
317
317
  ActiveUser (bundleHash: $bundleHash, metaType: $metaType, metaId: $metaId) {
318
318
  bundleHash,
319
319
  metaType,
@@ -322,7 +322,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
322
322
  createdAt,
323
323
  updatedAt
324
324
  }
325
- }`}createResponse(e){return new dr({query:this,json:e})}},pr=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
325
+ }`}createResponse(e){return new xr({query:this,json:e})}},Cr=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $slug: String, $slugs: [ String! ], $limit: Int, $order: String ) {
326
326
  Token( slug: $slug, slugs: $slugs, limit: $limit, order: $order ) {
327
327
  slug,
328
328
  name,
@@ -332,7 +332,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
332
332
  amount,
333
333
  icon,
334
334
  }
335
- }`}createResponse(e){return new G({query:this,json:e,dataKey:`data.Token`})}},mr=class extends w{constructor(e=`Authorization attempt rejected by ledger.`,t=null,n=null){super(e,t,n),this.name=`AuthorizationRejectedException`}},hr=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.Atom`})}payload(){let e=this.data();if(!e)return null;let t={instances:[],instanceCount:{},paginatorInfo:{}};if(e.instances){t.instances=e.instances;for(let e in t.instances){let n=t.instances[e];n.metasJson&&(t.instances[e].metas=JSON.parse(n.metasJson))}}return e.instanceCount&&(t.instanceCount=e.instanceCount),e.paginatorInfo&&(t.paginatorInfo=e.paginatorInfo),t}metas(){let e=this.payload(),t=[];if(e&&e.instances)for(let n of e.instances)n.metasJson&&t.push(JSON.parse(n.metasJson));return t}},gr=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query(
335
+ }`}createResponse(e){return new q({query:this,json:e,dataKey:`data.Token`})}},wr=class extends w{constructor(e=`Authorization attempt rejected by ledger.`,t=null,n=null){super(e,t,n),this.name=`AuthorizationRejectedException`}},Tr=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.Atom`})}payload(){let e=this.data();if(!e)return null;let t={instances:[],instanceCount:{},paginatorInfo:{}};if(e.instances){t.instances=e.instances;for(let e in t.instances){let n=t.instances[e];n.metasJson&&(t.instances[e].metas=JSON.parse(n.metasJson))}}return e.instanceCount&&(t.instanceCount=e.instanceCount),e.paginatorInfo&&(t.paginatorInfo=e.paginatorInfo),t}metas(){let e=this.payload(),t=[];if(e&&e.instances)for(let n of e.instances)n.metasJson&&t.push(JSON.parse(n.metasJson));return t}},Er=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query(
336
336
  $molecularHashes: [String!],
337
337
  $bundleHashes: [String!],
338
338
  $positions:[String!],
@@ -388,7 +388,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
388
388
  total
389
389
  }
390
390
  }
391
- }`}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:r,positions:i,position:a,walletAddresses:o,walletAddress:s,isotopes:c,isotope:l,tokenSlugs:u,tokenSlug:d,cellSlugs:f,cellSlug:p,batchIds:m,batchId:h,values:g,value:_,metaTypes:v,metaType:y,metaIds:b,metaId:ee,indexes:x,index:te,filter:ne,latest:re,queryArgs:S}){return t&&(e||=[],e.push(t)),r&&(n||=[],n.push(r)),a&&(i||=[],i.push(a)),s&&(o||=[],o.push(s)),l&&(c||=[],c.push(l)),d&&(u||=[],u.push(d)),p&&(f||=[],f.push(p)),h&&(m||=[],m.push(h)),_&&(g||=[],g.push(_)),y&&(v||=[],v.push(y)),ee&&(b||=[],b.push(ee)),te&&(x||=[],x.push(te)),{molecularHashes:e,bundleHashes:n,positions:i,walletAddresses:o,isotopes:c,tokenSlugs:u,cellSlugs:f,batchIds:m,values:g,metaTypes:v,metaIds:b,indexes:x,filter:ne,latest:re,queryArgs:S}}createResponse(e){return new hr({query:this,json:e})}},_r=class extends G{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey=`data.Policy`,this.init()}payload(){let e=this.data();return e&&e.callback?JSON.parse(e.callback):null}},vr=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $metaType: String, $metaId: String, ) {
391
+ }`}static createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:r,positions:i,position:a,walletAddresses:o,walletAddress:s,isotopes:c,isotope:l,tokenSlugs:u,tokenSlug:d,cellSlugs:f,cellSlug:p,batchIds:m,batchId:h,values:g,value:_,metaTypes:v,metaType:y,metaIds:b,metaId:ee,indexes:x,index:te,filter:ne,latest:re,queryArgs:S}){return t&&(e||=[],e.push(t)),r&&(n||=[],n.push(r)),a&&(i||=[],i.push(a)),s&&(o||=[],o.push(s)),l&&(c||=[],c.push(l)),d&&(u||=[],u.push(d)),p&&(f||=[],f.push(p)),h&&(m||=[],m.push(h)),_&&(g||=[],g.push(_)),y&&(v||=[],v.push(y)),ee&&(b||=[],b.push(ee)),te&&(x||=[],x.push(te)),{molecularHashes:e,bundleHashes:n,positions:i,walletAddresses:o,isotopes:c,tokenSlugs:u,cellSlugs:f,batchIds:m,values:g,metaTypes:v,metaIds:b,indexes:x,filter:ne,latest:re,queryArgs:S}}createResponse(e){return new Tr({query:this,json:e})}},Dr=class extends q{constructor({query:e,json:t}){super({query:e,json:t}),this.dataKey=`data.Policy`,this.init()}payload(){let e=this.data();return e&&e.callback?JSON.parse(e.callback):null}},Or=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $metaType: String, $metaId: String, ) {
392
392
  Policy( metaType: $metaType, metaId: $metaId ) {
393
393
  molecularHash,
394
394
  position,
@@ -399,7 +399,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
399
399
  rule,
400
400
  createdAt
401
401
  }
402
- }`}createResponse(e){return new _r({query:this,json:e})}},yr=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.MetaTypeViaAtom`})}payload(){let e=this.data();if(!e||e.length===0)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}},br=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
402
+ }`}createResponse(e){return new Dr({query:this,json:e})}},kr=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.MetaTypeViaAtom`})}payload(){let e=this.data();if(!e||e.length===0)return null;let t={instances:{},instanceCount:{},paginatorInfo:{}},n=e.pop();return n.instances&&(t.instances=n.instances),n.instanceCount&&(t.instanceCount=n.instanceCount),n.paginatorInfo&&(t.paginatorInfo=n.paginatorInfo),t}},Ar=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
403
403
  MetaTypeViaAtom(
404
404
  metaTypes: $metaTypes
405
405
  metaIds: $metaIds
@@ -432,7 +432,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
432
432
  total
433
433
  }
434
434
  }
435
- }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:r=null,keys:i=null,values:a=null,atomValues:o=null,latest:s=null,filter:c=null,queryArgs:l=null,countBy:u=null,cellSlug:d=null}){let f={};return o&&(f.atomValues=o),i&&(f.keys=i),a&&(f.values=a),e&&(f.metaTypes=typeof e==`string`?[e]:e),t&&(f.metaIds=typeof t==`string`?[t]:t),d&&(f.cellSlugs=typeof d==`string`?[d]:d),u&&(f.countBy=u),c&&(f.filter=c),n&&r&&(f.filter=f.filter||[],f.filter.push({key:n,value:r,comparison:`=`})),f.latest=s===!0,l&&((l.limit===void 0||l.limit===0)&&(l.limit=`*`),f.queryArgs=l),f}createResponse(e){return new yr({query:this,json:e})}},xr=class e extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.MetaTypeViaAtom`})}static extractMetasFromMolecule(e,t,n){if(!e||!e.atoms)return[];let r=[];for(let i of e.atoms){if(i.metaType!==t||i.metaId!==n||!i.metasJson)continue;let a;try{if(a=JSON.parse(i.metasJson),!Array.isArray(a))continue}catch{continue}for(let t of a)r.push({molecularHash:e.molecularHash,position:i.position,key:t.key,value:t.value,createdAt:i.createdAt})}return r}payload(){let t=this.data();if(!t||t.length===0)return null;let n={instances:{},instanceCount:{},paginatorInfo:{}},r=t.pop();return r.instances&&(n.instances=r.instances.map(t=>{let n=t.metas;return(!n||n.length===0)&&(n=e.extractMetasFromMolecule(t.molecule,t.metaType,t.metaId)),{...t,metas:n}})),r.instanceCount&&(n.instanceCount=r.instanceCount),r.paginatorInfo&&(n.paginatorInfo=r.paginatorInfo),n}verifyIntegrity(){let e=[],t=this.data();if(!t||t.length===0)return{verified:!0,molecules:e};let n=t[t.length-1]?.instances||[];for(let t of n)t.molecule&&e.push(an.verifyFromServerData(t.molecule));return{verified:e.length===0||e.every(e=>e.verified),molecules:e}}},Sr=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
435
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:r=null,keys:i=null,values:a=null,atomValues:o=null,latest:s=null,filter:c=null,queryArgs:l=null,countBy:u=null,cellSlug:d=null}){let f={};return o&&(f.atomValues=o),i&&(f.keys=i),a&&(f.values=a),e&&(f.metaTypes=typeof e==`string`?[e]:e),t&&(f.metaIds=typeof t==`string`?[t]:t),d&&(f.cellSlugs=typeof d==`string`?[d]:d),u&&(f.countBy=u),c&&(f.filter=c),n&&r&&(f.filter=f.filter||[],f.filter.push({key:n,value:r,comparison:`=`})),f.latest=s===!0,l&&((l.limit===void 0||l.limit===0)&&(l.limit=`*`),f.queryArgs=l),f}createResponse(e){return new kr({query:this,json:e})}},jr=class e extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.MetaTypeViaAtom`})}static extractMetasFromMolecule(e,t,n){if(!e||!e.atoms)return[];let r=[];for(let i of e.atoms){if(i.metaType!==t||i.metaId!==n||!i.metasJson)continue;let a;try{if(a=JSON.parse(i.metasJson),!Array.isArray(a))continue}catch{continue}for(let t of a)r.push({molecularHash:e.molecularHash,position:i.position,key:t.key,value:t.value,createdAt:i.createdAt})}return r}payload(){let t=this.data();if(!t||t.length===0)return null;let n={instances:{},instanceCount:{},paginatorInfo:{}},r=t.pop();return r.instances&&(n.instances=r.instances.map(t=>{let n=t.metas;return(!n||n.length===0)&&(n=e.extractMetasFromMolecule(t.molecule,t.metaType,t.metaId)),{...t,metas:n}})),r.instanceCount&&(n.instanceCount=r.instanceCount),r.paginatorInfo&&(n.paginatorInfo=r.paginatorInfo),n}verifyIntegrity(){let e=[],t=this.data();if(!t||t.length===0)return{verified:!0,molecules:e};let n=t[t.length-1]?.instances||[];for(let t of n)t.molecule&&e.push(cn.verifyFromServerData(t.molecule));return{verified:e.length===0||e.every(e=>e.verified),molecules:e}}},Mr=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query ($metaTypes: [String!], $metaIds: [String!], $values: [String!], $keys: [String!], $latest: Boolean, $filter: [MetaFilter!], $queryArgs: QueryArgs, $countBy: String, $atomValues: [String!], $cellSlugs: [String!] ) {
436
436
  MetaTypeViaAtom(
437
437
  metaTypes: $metaTypes
438
438
  metaIds: $metaIds
@@ -486,7 +486,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
486
486
  total
487
487
  }
488
488
  }
489
- }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:r=null,keys:i=null,values:a=null,atomValues:o=null,latest:s=null,filter:c=null,queryArgs:l=null,countBy:u=null,cellSlug:d=null}){let f={};return o&&(f.atomValues=o),i&&(f.keys=i),a&&(f.values=a),e&&(f.metaTypes=typeof e==`string`?[e]:e),t&&(f.metaIds=typeof t==`string`?[t]:t),d&&(f.cellSlugs=typeof d==`string`?[d]:d),u&&(f.countBy=u),c&&(f.filter=c),n&&r&&(f.filter=f.filter||[],f.filter.push({key:n,value:r,comparison:`=`})),f.latest=s===!0,l&&((l.limit===void 0||l.limit===0)&&(l.limit=`*`),f.queryArgs=l),f}createResponse(e){return new xr({query:this,json:e})}},Cr=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.embeddingStatus`})}payload(){let e=this.data();return!e||!Array.isArray(e)||e.length===0?null:e}},wr=class extends K{constructor(e,t){super(e,t),this.$__query=l.gql`query( $metaType: String, $metaId: String, $instances: [EmbeddingStatusInput!] ) {
489
+ }`}static createVariables({metaType:e=null,metaId:t=null,key:n=null,value:r=null,keys:i=null,values:a=null,atomValues:o=null,latest:s=null,filter:c=null,queryArgs:l=null,countBy:u=null,cellSlug:d=null}){let f={};return o&&(f.atomValues=o),i&&(f.keys=i),a&&(f.values=a),e&&(f.metaTypes=typeof e==`string`?[e]:e),t&&(f.metaIds=typeof t==`string`?[t]:t),d&&(f.cellSlugs=typeof d==`string`?[d]:d),u&&(f.countBy=u),c&&(f.filter=c),n&&r&&(f.filter=f.filter||[],f.filter.push({key:n,value:r,comparison:`=`})),f.latest=s===!0,l&&((l.limit===void 0||l.limit===0)&&(l.limit=`*`),f.queryArgs=l),f}createResponse(e){return new jr({query:this,json:e})}},Nr=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.embeddingStatus`})}payload(){let e=this.data();return!e||!Array.isArray(e)||e.length===0?null:e}},Pr=class extends J{constructor(e,t){super(e,t),this.$__query=l.gql`query( $metaType: String, $metaId: String, $instances: [EmbeddingStatusInput!] ) {
490
490
  embeddingStatus( metaType: $metaType, metaId: $metaId, instances: $instances ) {
491
491
  metaType,
492
492
  metaId,
@@ -496,7 +496,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
496
496
  embeddedAt,
497
497
  model
498
498
  }
499
- }`}static createVariables({metaType:e=null,metaId:t=null,instances:n=null}){let r={};return n&&n.length>0&&(r.instances=n),e&&(r.metaType=e),t&&(r.metaId=t),r}createResponse(e){return new Cr({query:this,json:e})}},Tr=class extends q{},Er=class extends J{fillMolecule({metaType:e,metaId:t,rule:n,policy:r}){this.$__molecule.createRule({metaType:e,metaId:t,rule:n,policy:r}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Tr({query:this,json:e})}},Dr=class extends J{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}},Or=class extends J{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}},kr=2592e5,Ar=`thumbmark`,jr=`https://api.thumbmarkjs.com`,Mr={exclude:[],include:[],stabilize:[`private`,`iframe`],logging:!0,timeout:5e3,cache_api_call:!0,cache_lifetime_in_ms:0,performance:!1,experimental:!1,simple_request:!1,property_name_factory:e=>`${Ar}_${e}`},Nr={...Mr},Pr={private:[{exclude:[`canvas`],browsers:[`firefox`,`safari>=17`,`brave`]},{exclude:[`audio`],browsers:[`samsungbrowser`,`safari`]},{exclude:[`fonts`],browsers:[`firefox`]},{exclude:[`audio.sampleHash`,`hardware.deviceMemory`,`header.acceptLanguage.q`,`system.hardwareConcurrency`,`plugins`],browsers:[`brave`]},{exclude:[`tls.extensions`],browsers:[`firefox`,`chrome`,`safari`]},{exclude:[`header.acceptLanguage`],browsers:[`edge`,`chrome`]}],iframe:[{exclude:[`system.applePayVersion`,`system.cookieEnabled`],browsers:[`safari`]},{exclude:[`permissions`]}],vpn:[{exclude:[`ip`]}],always:[{exclude:[`speech`],browsers:[`brave`,`firefox`]}]},Fr=typeof window<`u`?window.OfflineAudioContext||window.webkitOfflineAudioContext:null;function Ir(e){let t=0;for(let n=0;n<e.length;++n)t+=Math.abs(e[n]);return t}function Lr(e,t,n){if(e.length===1)return e[0];if(e.length===3){let r=e[0].data,i=e[1].data,a=e[2].data,o=new Uint8ClampedArray(r.length);for(let e=0;e<r.length;e++){let t=r[e],n=i[e],s=a[e];o[e]=t===n||t===s?t:n===s?n:t}return new ImageData(o,t,n)}let r=[];for(let t=0;t<e[0].data.length;t++){let n=[];for(let r=0;r<e.length;r++)n.push(e[r].data[t]);r.push(Rr(n))}let i=new Uint8ClampedArray(r);return new ImageData(i,t,n)}function Rr(e){if(e.length===0)return 0;let t={};for(let n of e)t[n]=(t[n]||0)+1;let n=e[0];for(let e in t)t[e]>t[n]&&(n=parseInt(e,10));return n}function zr(e){return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),(e^=e>>>16)>>>0}var Y=new Uint32Array([597399067,2869860233,951274213,2716044179]);function X(e,t){return e<<t|e>>>32-t}function Z(e,t=0){if(t=t?0|t:0,typeof e==`string`&&(e=function(e){if(typeof TextEncoder<`u`)return new TextEncoder().encode(e).buffer;let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<55296||r>=57344?t.push(224|r>>12,128|r>>6&63,128|63&r):(n++,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}return new Uint8Array(t).buffer}(e)),!(e instanceof ArrayBuffer))throw TypeError(`Expected key to be ArrayBuffer or string`);let n=new Uint32Array([t,t,t,t]);(function(e,t){let n=e.byteLength/16|0,r=new Uint32Array(e,0,4*n);for(let e=0;e<n;e++){let n=r.subarray(4*e,4*(e+1));n[0]=Math.imul(n[0],Y[0]),n[0]=X(n[0],15),n[0]=Math.imul(n[0],Y[1]),t[0]^=n[0],t[0]=X(t[0],19),t[0]+=t[1],t[0]=Math.imul(t[0],5)+1444728091,n[1]=Math.imul(n[1],Y[1]),n[1]=X(n[1],16),n[1]=Math.imul(n[1],Y[2]),t[1]^=n[1],t[1]=X(t[1],17),t[1]+=t[2],t[1]=Math.imul(t[1],5)+197830471,n[2]=Math.imul(n[2],Y[2]),n[2]=X(n[2],17),n[2]=Math.imul(n[2],Y[3]),t[2]^=n[2],t[2]=X(t[2],15),t[2]+=t[3],t[2]=Math.imul(t[2],5)+2530024501,n[3]=Math.imul(n[3],Y[3]),n[3]=X(n[3],18),n[3]=Math.imul(n[3],Y[0]),t[3]^=n[3],t[3]=X(t[3],13),t[3]+=t[0],t[3]=Math.imul(t[3],5)+850148119}})(e,n),function(e,t){let n=e.byteLength/16|0,r=e.byteLength%16,i=new Uint32Array(4),a=new Uint8Array(e,16*n,r);switch(r){case 15:i[3]^=a[14]<<16;case 14:i[3]^=a[13]<<8;case 13:i[3]^=a[12],i[3]=Math.imul(i[3],Y[3]),i[3]=X(i[3],18),i[3]=Math.imul(i[3],Y[0]),t[3]^=i[3];case 12:i[2]^=a[11]<<24;case 11:i[2]^=a[10]<<16;case 10:i[2]^=a[9]<<8;case 9:i[2]^=a[8],i[2]=Math.imul(i[2],Y[2]),i[2]=X(i[2],17),i[2]=Math.imul(i[2],Y[3]),t[2]^=i[2];case 8:i[1]^=a[7]<<24;case 7:i[1]^=a[6]<<16;case 6:i[1]^=a[5]<<8;case 5:i[1]^=a[4],i[1]=Math.imul(i[1],Y[1]),i[1]=X(i[1],16),i[1]=Math.imul(i[1],Y[2]),t[1]^=i[1];case 4:i[0]^=a[3]<<24;case 3:i[0]^=a[2]<<16;case 2:i[0]^=a[1]<<8;case 1:i[0]^=a[0],i[0]=Math.imul(i[0],Y[0]),i[0]=X(i[0],15),i[0]=Math.imul(i[0],Y[1]),t[0]^=i[0]}}(e,n),function(e,t){t[0]^=e.byteLength,t[1]^=e.byteLength,t[2]^=e.byteLength,t[3]^=e.byteLength,t[0]=t[0]+t[1]|0,t[0]=t[0]+t[2]|0,t[0]=t[0]+t[3]|0,t[1]=t[1]+t[0]|0,t[2]=t[2]+t[0]|0,t[3]=t[3]+t[0]|0,t[0]=zr(t[0]),t[1]=zr(t[1]),t[2]=zr(t[2]),t[3]=zr(t[3]),t[0]=t[0]+t[1]|0,t[0]=t[0]+t[2]|0,t[0]=t[0]+t[3]|0,t[1]=t[1]+t[0]|0,t[2]=t[2]+t[0]|0,t[3]=t[3]+t[0]|0}(e,n);let r=new Uint8Array(n.buffer);return Array.from(r).map((e=>e.toString(16).padStart(2,`0`))).join(``)}var Br=280;function Vr(e,t){return new Promise((n=>setTimeout(n,e,t)))}var Hr=`Arial.Arial Black.Arial Narrow.Arial Rounded MT.Arimo.Archivo.Barlow.Bebas Neue.Bitter.Bookman.Calibri.Cabin.Candara.Century.Century Gothic.Comic Sans MS.Constantia.Courier.Courier New.Crimson Text.DM Mono.DM Sans.DM Serif Display.DM Serif Text.Dosis.Droid Sans.Exo.Fira Code.Fira Sans.Franklin Gothic Medium.Garamond.Geneva.Georgia.Gill Sans.Helvetica.Impact.Inconsolata.Indie Flower.Inter.Josefin Sans.Karla.Lato.Lexend.Lucida Bright.Lucida Console.Lucida Sans Unicode.Manrope.Merriweather.Merriweather Sans.Montserrat.Myriad.Noto Sans.Nunito.Nunito Sans.Open Sans.Optima.Orbitron.Oswald.Pacifico.Palatino.Perpetua.PT Sans.PT Serif.Poppins.Prompt.Public Sans.Quicksand.Rajdhani.Recursive.Roboto.Roboto Condensed.Rockwell.Rubik.Segoe Print.Segoe Script.Segoe UI.Sora.Source Sans Pro.Space Mono.Tahoma.Taviraj.Times.Times New Roman.Titillium Web.Trebuchet MS.Ubuntu.Varela Round.Verdana.Work Sans`.split(`.`),Ur=[`monospace`,`sans-serif`,`serif`];function Wr(e,t){return e.font=`72px ${t}`,e.measureText(`WwMmLli0Oo`).width}function Gr(){let e=document.createElement(`canvas`),t=e.getContext(`webgl`)??e.getContext(`experimental-webgl`);if(t&&`getParameter`in t)try{let e=(t.getParameter(t.VENDOR)||``).toString(),n=(t.getParameter(t.RENDERER)||``).toString(),r={vendor:e,renderer:n,version:(t.getParameter(t.VERSION)||``).toString(),shadingLanguageVersion:(t.getParameter(t.SHADING_LANGUAGE_VERSION)||``).toString()};if(!n.length||!e.length){let e=t.getExtension(`WEBGL_debug_renderer_info`);if(e){let n=(t.getParameter(e.UNMASKED_VENDOR_WEBGL)||``).toString(),i=(t.getParameter(e.UNMASKED_RENDERER_WEBGL)||``).toString();n&&(r.vendorUnmasked=n),i&&(r.rendererUnmasked=i)}}return r}catch{}return`undefined`}function Kr(){let e=new Float32Array(1),t=new Uint8Array(e.buffer);return e[0]=1/0,e[0]-=e[0],t[3]}var qr=(e,t,n,r)=>{let i=(n-t)/r,a=0;for(let n=0;n<r;n++)a+=e(t+(n+.5)*i);return a*i};function Jr(e,t){let n={};return t.forEach((t=>{let r=function(e){if(e.length===0)return null;let t={};e.forEach((e=>{let n=String(e);t[n]=(t[n]||0)+1}));let n=e[0],r=1;return Object.keys(t).forEach((e=>{t[e]>r&&(n=e,r=t[e])})),n}(e.map((e=>t in e?e[t]:void 0)).filter((e=>e!==void 0)));r&&(n[t]=r)})),n}var Yr=`accelerometer.accessibility.accessibility-events.ambient-light-sensor.background-fetch.background-sync.bluetooth.camera.clipboard-read.clipboard-write.device-info.display-capture.gyroscope.geolocation.local-fonts.magnetometer.microphone.midi.nfc.notifications.payment-handler.persistent-storage.push.speaker.storage-access.top-level-storage-access.window-management.query`.split(`.`),Xr=new Map;function Zr(){if(typeof navigator>`u`)return{name:`unknown`,version:`unknown`};let e=!!navigator.brave,t=(e?`B|`:`N|`)+navigator.userAgent,n=Xr.get(t);if(n)return n;let r=[{name:`Brave`,detect:()=>e}],i;for(let e of r)if(e.detect()){let n=Qr(navigator.userAgent);return i={name:e.name,version:n.version},Xr.set(t,i),i}return i=Qr(navigator.userAgent),Xr.set(t,i),i}function Qr(e){var t,n;let r=[/(?<name>SamsungBrowser)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>EdgA|EdgiOS|Edg)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>OPR|OPX)\/(?<version>\d+(?:\.\d+)+)/,/Opera[\s\/](?<version>\d+(?:\.\d+)+)/,/Opera Mini\/(?<version>\d+(?:\.\d+)+)/,/Opera Mobi\/(?<version>\d+(?:\.\d+)+)/,/(?<name>Vivaldi)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>CriOS)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>FxiOS)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>Chrome|Chromium)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>Firefox|Waterfox|Iceweasel|IceCat)\/(?<version>\d+(?:\.\d+)+)/,/Version\/(?<version1>[\d.]+).*Safari\/[\d.]+|(?<name>Safari)\/(?<version2>[\d.]+)/,/(?<name>MSIE|Trident|IEMobile).+?(?<version>\d+(?:\.\d+)+)/,/(?<name>[A-Za-z]+)\/(?<version>\d+(?:\.\d+)+)/],i={edg:`Edge`,edga:`Edge`,edgios:`Edge`,opr:`Opera`,opx:`Opera`,crios:`Chrome`,fxios:`Firefox`,samsung:`SamsungBrowser`,vivaldi:`Vivaldi`};for(let a of r){let r=e.match(a);if(r){let e=r.groups?.name,o=r.groups?.version||r.groups?.version1||r.groups?.version2;if(e||!((t=r.groups)!=null&&t.version1)&&!((n=r.groups)!=null&&n.version2)||(e=`Safari`),!e&&a.source.includes(`Opera Mini`)&&(e=`Opera Mini`),!e&&a.source.includes(`Opera Mobi`)&&(e=`Opera Mobi`),!e&&a.source.includes(`Opera`)&&(e=`Opera`),!e&&r[1]&&(e=r[1]),!o&&r[2]&&(o=r[2]),e)return{name:i[e.toLowerCase()]||e,version:o||`unknown`}}}return{name:`unknown`,version:`unknown`}}function $r(){if(typeof navigator>`u`||!navigator.userAgent)return!1;let e=navigator.userAgent;return/Mobi|Android|iPhone|iPod|IEMobile|Opera Mini|Opera Mobi|webOS|BlackBerry|Windows Phone/i.test(e)&&!/iPad/i.test(e)}function ei(){let e=[],t={"prefers-contrast":[`high`,`more`,`low`,`less`,`forced`,`no-preference`],"any-hover":[`hover`,`none`],"any-pointer":[`none`,`coarse`,`fine`],pointer:[`none`,`coarse`,`fine`],hover:[`hover`,`none`],update:[`fast`,`slow`],"inverted-colors":[`inverted`,`none`],"prefers-reduced-motion":[`reduce`,`no-preference`],"prefers-reduced-transparency":[`reduce`,`no-preference`],scripting:[`none`,`initial-only`,`enabled`],"forced-colors":[`active`,`none`]};return Object.keys(t).forEach((n=>{t[n].forEach((t=>{matchMedia(`(${n}: ${t})`).matches&&e.push(`${n}: ${t}`)}))})),e}function ti(){if(window.location.protocol===`https:`&&typeof window.ApplePaySession==`function`)try{let e=window.ApplePaySession.supportsVersion;for(let t=15;t>0;t--)if(e(t))return t}catch{return 0}return 0}var ni=Zr().name===`SamsungBrowser`?3:1,ri=Zr().name!==`Brave`,ii=137,ai=(()=>{let e=new Float32Array(548),t=2*Math.PI/ii;for(let n=0;n<ii;n++){let r=n*t;e[4*n]=0,e[4*n+1]=0,e[4*n+2]=100*Math.cos(r),e[4*n+3]=50*Math.sin(r)}return e})(),oi=null;function si(){try{if(typeof document>`u`)return null;let e=document.createElement(`canvas`);e.width=200,e.height=100;let t=e.getContext(`webgl`);if(!t)return null;e.addEventListener(`webglcontextlost`,(e=>{e.preventDefault(),oi=null}),{once:!0});let n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER);if(!n||!r||(t.shaderSource(n,`
499
+ }`}static createVariables({metaType:e=null,metaId:t=null,instances:n=null}){let r={};return n&&n.length>0&&(r.instances=n),e&&(r.metaType=e),t&&(r.metaId=t),r}createResponse(e){return new Nr({query:this,json:e})}},Fr=class extends Y{},Ir=class extends X{fillMolecule({metaType:e,metaId:t,rule:n,policy:r}){this.$__molecule.createRule({metaType:e,metaId:t,rule:n,policy:r}),this.$__molecule.sign({}),this.$__molecule.check()}createResponse(e){return new Fr({query:this,json:e})}},Lr=class extends X{fillMolecule({amount:e,tradeRates:t}){this.$__molecule.initDepositBuffer({amount:e,tradeRates:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}},Rr=class extends X{fillMolecule({recipients:e,signingWallet:t}){this.$__molecule.initWithdrawBuffer({recipients:e,signingWallet:t}),this.$__molecule.sign({}),this.$__molecule.check(this.$__molecule.sourceWallet)}},zr=2592e5,Br=`thumbmark`,Vr=`https://api.thumbmarkjs.com`,Hr={exclude:[],include:[],stabilize:[`private`,`iframe`],logging:!0,timeout:5e3,cache_api_call:!0,cache_lifetime_in_ms:0,performance:!1,experimental:!1,simple_request:!1,property_name_factory:e=>`${Br}_${e}`},Ur={...Hr},Wr={private:[{exclude:[`canvas`],browsers:[`firefox`,`safari>=17`,`brave`]},{exclude:[`audio`],browsers:[`samsungbrowser`,`safari`]},{exclude:[`fonts`],browsers:[`firefox`]},{exclude:[`audio.sampleHash`,`hardware.deviceMemory`,`header.acceptLanguage.q`,`system.hardwareConcurrency`,`plugins`],browsers:[`brave`]},{exclude:[`tls.extensions`],browsers:[`firefox`,`chrome`,`safari`]},{exclude:[`header.acceptLanguage`],browsers:[`edge`,`chrome`]}],iframe:[{exclude:[`system.applePayVersion`,`system.cookieEnabled`],browsers:[`safari`]},{exclude:[`permissions`]}],vpn:[{exclude:[`ip`]}],always:[{exclude:[`speech`],browsers:[`brave`,`firefox`]}]},Gr=typeof window<`u`?window.OfflineAudioContext||window.webkitOfflineAudioContext:null;function Kr(e){let t=0;for(let n=0;n<e.length;++n)t+=Math.abs(e[n]);return t}function qr(e,t,n){if(e.length===1)return e[0];if(e.length===3){let r=e[0].data,i=e[1].data,a=e[2].data,o=new Uint8ClampedArray(r.length);for(let e=0;e<r.length;e++){let t=r[e],n=i[e],s=a[e];o[e]=t===n||t===s?t:n===s?n:t}return new ImageData(o,t,n)}let r=[];for(let t=0;t<e[0].data.length;t++){let n=[];for(let r=0;r<e.length;r++)n.push(e[r].data[t]);r.push(Jr(n))}let i=new Uint8ClampedArray(r);return new ImageData(i,t,n)}function Jr(e){if(e.length===0)return 0;let t={};for(let n of e)t[n]=(t[n]||0)+1;let n=e[0];for(let e in t)t[e]>t[n]&&(n=parseInt(e,10));return n}function Yr(e){return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),(e^=e>>>16)>>>0}var Z=new Uint32Array([597399067,2869860233,951274213,2716044179]);function Q(e,t){return e<<t|e>>>32-t}function $(e,t=0){if(t=t?0|t:0,typeof e==`string`&&(e=function(e){if(typeof TextEncoder<`u`)return new TextEncoder().encode(e).buffer;let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);r<128?t.push(r):r<2048?t.push(192|r>>6,128|63&r):r<55296||r>=57344?t.push(224|r>>12,128|r>>6&63,128|63&r):(n++,r=65536+((1023&r)<<10|1023&e.charCodeAt(n)),t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|63&r))}return new Uint8Array(t).buffer}(e)),!(e instanceof ArrayBuffer))throw TypeError(`Expected key to be ArrayBuffer or string`);let n=new Uint32Array([t,t,t,t]);(function(e,t){let n=e.byteLength/16|0,r=new Uint32Array(e,0,4*n);for(let e=0;e<n;e++){let n=r.subarray(4*e,4*(e+1));n[0]=Math.imul(n[0],Z[0]),n[0]=Q(n[0],15),n[0]=Math.imul(n[0],Z[1]),t[0]^=n[0],t[0]=Q(t[0],19),t[0]+=t[1],t[0]=Math.imul(t[0],5)+1444728091,n[1]=Math.imul(n[1],Z[1]),n[1]=Q(n[1],16),n[1]=Math.imul(n[1],Z[2]),t[1]^=n[1],t[1]=Q(t[1],17),t[1]+=t[2],t[1]=Math.imul(t[1],5)+197830471,n[2]=Math.imul(n[2],Z[2]),n[2]=Q(n[2],17),n[2]=Math.imul(n[2],Z[3]),t[2]^=n[2],t[2]=Q(t[2],15),t[2]+=t[3],t[2]=Math.imul(t[2],5)+2530024501,n[3]=Math.imul(n[3],Z[3]),n[3]=Q(n[3],18),n[3]=Math.imul(n[3],Z[0]),t[3]^=n[3],t[3]=Q(t[3],13),t[3]+=t[0],t[3]=Math.imul(t[3],5)+850148119}})(e,n),function(e,t){let n=e.byteLength/16|0,r=e.byteLength%16,i=new Uint32Array(4),a=new Uint8Array(e,16*n,r);switch(r){case 15:i[3]^=a[14]<<16;case 14:i[3]^=a[13]<<8;case 13:i[3]^=a[12],i[3]=Math.imul(i[3],Z[3]),i[3]=Q(i[3],18),i[3]=Math.imul(i[3],Z[0]),t[3]^=i[3];case 12:i[2]^=a[11]<<24;case 11:i[2]^=a[10]<<16;case 10:i[2]^=a[9]<<8;case 9:i[2]^=a[8],i[2]=Math.imul(i[2],Z[2]),i[2]=Q(i[2],17),i[2]=Math.imul(i[2],Z[3]),t[2]^=i[2];case 8:i[1]^=a[7]<<24;case 7:i[1]^=a[6]<<16;case 6:i[1]^=a[5]<<8;case 5:i[1]^=a[4],i[1]=Math.imul(i[1],Z[1]),i[1]=Q(i[1],16),i[1]=Math.imul(i[1],Z[2]),t[1]^=i[1];case 4:i[0]^=a[3]<<24;case 3:i[0]^=a[2]<<16;case 2:i[0]^=a[1]<<8;case 1:i[0]^=a[0],i[0]=Math.imul(i[0],Z[0]),i[0]=Q(i[0],15),i[0]=Math.imul(i[0],Z[1]),t[0]^=i[0]}}(e,n),function(e,t){t[0]^=e.byteLength,t[1]^=e.byteLength,t[2]^=e.byteLength,t[3]^=e.byteLength,t[0]=t[0]+t[1]|0,t[0]=t[0]+t[2]|0,t[0]=t[0]+t[3]|0,t[1]=t[1]+t[0]|0,t[2]=t[2]+t[0]|0,t[3]=t[3]+t[0]|0,t[0]=Yr(t[0]),t[1]=Yr(t[1]),t[2]=Yr(t[2]),t[3]=Yr(t[3]),t[0]=t[0]+t[1]|0,t[0]=t[0]+t[2]|0,t[0]=t[0]+t[3]|0,t[1]=t[1]+t[0]|0,t[2]=t[2]+t[0]|0,t[3]=t[3]+t[0]|0}(e,n);let r=new Uint8Array(n.buffer);return Array.from(r).map((e=>e.toString(16).padStart(2,`0`))).join(``)}var Xr=280;function Zr(e,t){return new Promise((n=>setTimeout(n,e,t)))}var Qr=`Arial.Arial Black.Arial Narrow.Arial Rounded MT.Arimo.Archivo.Barlow.Bebas Neue.Bitter.Bookman.Calibri.Cabin.Candara.Century.Century Gothic.Comic Sans MS.Constantia.Courier.Courier New.Crimson Text.DM Mono.DM Sans.DM Serif Display.DM Serif Text.Dosis.Droid Sans.Exo.Fira Code.Fira Sans.Franklin Gothic Medium.Garamond.Geneva.Georgia.Gill Sans.Helvetica.Impact.Inconsolata.Indie Flower.Inter.Josefin Sans.Karla.Lato.Lexend.Lucida Bright.Lucida Console.Lucida Sans Unicode.Manrope.Merriweather.Merriweather Sans.Montserrat.Myriad.Noto Sans.Nunito.Nunito Sans.Open Sans.Optima.Orbitron.Oswald.Pacifico.Palatino.Perpetua.PT Sans.PT Serif.Poppins.Prompt.Public Sans.Quicksand.Rajdhani.Recursive.Roboto.Roboto Condensed.Rockwell.Rubik.Segoe Print.Segoe Script.Segoe UI.Sora.Source Sans Pro.Space Mono.Tahoma.Taviraj.Times.Times New Roman.Titillium Web.Trebuchet MS.Ubuntu.Varela Round.Verdana.Work Sans`.split(`.`),$r=[`monospace`,`sans-serif`,`serif`];function ei(e,t){return e.font=`72px ${t}`,e.measureText(`WwMmLli0Oo`).width}function ti(){let e=document.createElement(`canvas`),t=e.getContext(`webgl`)??e.getContext(`experimental-webgl`);if(t&&`getParameter`in t)try{let e=(t.getParameter(t.VENDOR)||``).toString(),n=(t.getParameter(t.RENDERER)||``).toString(),r={vendor:e,renderer:n,version:(t.getParameter(t.VERSION)||``).toString(),shadingLanguageVersion:(t.getParameter(t.SHADING_LANGUAGE_VERSION)||``).toString()};if(!n.length||!e.length){let e=t.getExtension(`WEBGL_debug_renderer_info`);if(e){let n=(t.getParameter(e.UNMASKED_VENDOR_WEBGL)||``).toString(),i=(t.getParameter(e.UNMASKED_RENDERER_WEBGL)||``).toString();n&&(r.vendorUnmasked=n),i&&(r.rendererUnmasked=i)}}return r}catch{}return`undefined`}function ni(){let e=new Float32Array(1),t=new Uint8Array(e.buffer);return e[0]=1/0,e[0]-=e[0],t[3]}var ri=(e,t,n,r)=>{let i=(n-t)/r,a=0;for(let n=0;n<r;n++)a+=e(t+(n+.5)*i);return a*i};function ii(e,t){let n={};return t.forEach((t=>{let r=function(e){if(e.length===0)return null;let t={};e.forEach((e=>{let n=String(e);t[n]=(t[n]||0)+1}));let n=e[0],r=1;return Object.keys(t).forEach((e=>{t[e]>r&&(n=e,r=t[e])})),n}(e.map((e=>t in e?e[t]:void 0)).filter((e=>e!==void 0)));r&&(n[t]=r)})),n}var ai=`accelerometer.accessibility.accessibility-events.ambient-light-sensor.background-fetch.background-sync.bluetooth.camera.clipboard-read.clipboard-write.device-info.display-capture.gyroscope.geolocation.local-fonts.magnetometer.microphone.midi.nfc.notifications.payment-handler.persistent-storage.push.speaker.storage-access.top-level-storage-access.window-management.query`.split(`.`),oi=new Map;function si(){if(typeof navigator>`u`)return{name:`unknown`,version:`unknown`};let e=!!navigator.brave,t=(e?`B|`:`N|`)+navigator.userAgent,n=oi.get(t);if(n)return n;let r=[{name:`Brave`,detect:()=>e}],i;for(let e of r)if(e.detect()){let n=ci(navigator.userAgent);return i={name:e.name,version:n.version},oi.set(t,i),i}return i=ci(navigator.userAgent),oi.set(t,i),i}function ci(e){var t,n;let r=[/(?<name>SamsungBrowser)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>EdgA|EdgiOS|Edg)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>OPR|OPX)\/(?<version>\d+(?:\.\d+)+)/,/Opera[\s\/](?<version>\d+(?:\.\d+)+)/,/Opera Mini\/(?<version>\d+(?:\.\d+)+)/,/Opera Mobi\/(?<version>\d+(?:\.\d+)+)/,/(?<name>Vivaldi)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>CriOS)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>FxiOS)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>Chrome|Chromium)\/(?<version>\d+(?:\.\d+)+)/,/(?<name>Firefox|Waterfox|Iceweasel|IceCat)\/(?<version>\d+(?:\.\d+)+)/,/Version\/(?<version1>[\d.]+).*Safari\/[\d.]+|(?<name>Safari)\/(?<version2>[\d.]+)/,/(?<name>MSIE|Trident|IEMobile).+?(?<version>\d+(?:\.\d+)+)/,/(?<name>[A-Za-z]+)\/(?<version>\d+(?:\.\d+)+)/],i={edg:`Edge`,edga:`Edge`,edgios:`Edge`,opr:`Opera`,opx:`Opera`,crios:`Chrome`,fxios:`Firefox`,samsung:`SamsungBrowser`,vivaldi:`Vivaldi`};for(let a of r){let r=e.match(a);if(r){let e=r.groups?.name,o=r.groups?.version||r.groups?.version1||r.groups?.version2;if(e||!((t=r.groups)!=null&&t.version1)&&!((n=r.groups)!=null&&n.version2)||(e=`Safari`),!e&&a.source.includes(`Opera Mini`)&&(e=`Opera Mini`),!e&&a.source.includes(`Opera Mobi`)&&(e=`Opera Mobi`),!e&&a.source.includes(`Opera`)&&(e=`Opera`),!e&&r[1]&&(e=r[1]),!o&&r[2]&&(o=r[2]),e)return{name:i[e.toLowerCase()]||e,version:o||`unknown`}}}return{name:`unknown`,version:`unknown`}}function li(){if(typeof navigator>`u`||!navigator.userAgent)return!1;let e=navigator.userAgent;return/Mobi|Android|iPhone|iPod|IEMobile|Opera Mini|Opera Mobi|webOS|BlackBerry|Windows Phone/i.test(e)&&!/iPad/i.test(e)}function ui(){let e=[],t={"prefers-contrast":[`high`,`more`,`low`,`less`,`forced`,`no-preference`],"any-hover":[`hover`,`none`],"any-pointer":[`none`,`coarse`,`fine`],pointer:[`none`,`coarse`,`fine`],hover:[`hover`,`none`],update:[`fast`,`slow`],"inverted-colors":[`inverted`,`none`],"prefers-reduced-motion":[`reduce`,`no-preference`],"prefers-reduced-transparency":[`reduce`,`no-preference`],scripting:[`none`,`initial-only`,`enabled`],"forced-colors":[`active`,`none`]};return Object.keys(t).forEach((n=>{t[n].forEach((t=>{matchMedia(`(${n}: ${t})`).matches&&e.push(`${n}: ${t}`)}))})),e}function di(){if(window.location.protocol===`https:`&&typeof window.ApplePaySession==`function`)try{let e=window.ApplePaySession.supportsVersion;for(let t=15;t>0;t--)if(e(t))return t}catch{return 0}return 0}var fi=si().name===`SamsungBrowser`?3:1,pi=si().name!==`Brave`,mi=137,hi=(()=>{let e=new Float32Array(548),t=2*Math.PI/mi;for(let n=0;n<mi;n++){let r=n*t;e[4*n]=0,e[4*n+1]=0,e[4*n+2]=100*Math.cos(r),e[4*n+3]=50*Math.sin(r)}return e})(),gi=null;function _i(){try{if(typeof document>`u`)return null;let e=document.createElement(`canvas`);e.width=200,e.height=100;let t=e.getContext(`webgl`);if(!t)return null;e.addEventListener(`webglcontextlost`,(e=>{e.preventDefault(),gi=null}),{once:!0});let n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER);if(!n||!r||(t.shaderSource(n,`
500
500
  attribute vec2 position;
501
501
  void main() {
502
502
  gl_Position = vec4(position, 0.0, 1.0);
@@ -506,5 +506,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
506
506
  void main() {
507
507
  gl_FragColor = vec4(0.812, 0.195, 0.553, 0.921); // Set line color
508
508
  }
509
- `),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)))return null;let i=t.createProgram();if(!i||(t.attachShader(i,n),t.attachShader(i,r),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)))return null;let a=t.createBuffer();return a?(t.bindBuffer(t.ARRAY_BUFFER,a),t.bufferData(t.ARRAY_BUFFER,ai,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),{canvas:e,gl:t,program:i,buffer:a}):null}catch{return null}}function Q(e){let t=new Set;return function e(n){if(n&&n.toJSON&&typeof n.toJSON==`function`&&(n=n.toJSON()),n===void 0)return;if(typeof n==`number`)return isFinite(n)?``+n:`null`;if(typeof n!=`object`)return JSON.stringify(n);let r,i;if(Array.isArray(n)){for(i=`[`,r=0;r<n.length;r++)r&&(i+=`,`),i+=e(n[r])||`null`;return i+`]`}if(n===null)return`null`;if(t.has(n))throw TypeError(`Converting circular structure to JSON`);t.add(n);let a=Object.keys(n).sort();for(i=``,r=0;r<a.length;r++){let t=a[r],o=e(n[t]);o&&(i&&(i+=`,`),i+=JSON.stringify(t)+`:`+o)}return t.delete(n),`{`+i+`}`}(e)||``}var ci={audio:async function(){return Fr?async function(){return new Promise(((e,t)=>{try{let t=new Fr(1,5e3,44100),n=t.createBufferSource(),r=t.createOscillator();r.frequency.value=1e3;let i=t.createDynamicsCompressor(),a;i.threshold.value=-50,i.knee.value=40,i.ratio.value=12,i.attack.value=0,i.release.value=.2,r.connect(i),i.connect(t.destination),r.start(),t.oncomplete=r=>{a=r.renderedBuffer.getChannelData(0),e({sampleHash:Ir(a),maxChannels:t.destination.maxChannelCount,channelCountMode:n.channelCountMode})},t.startRendering()}catch(e){t(e)}}))}():null},canvas:async function(){return new Promise((e=>{let t=Array.from({length:3},(()=>function(){let e=document.createElement(`canvas`),t=e.getContext(`2d`);if(!t)return null;e.width=Br,e.height=20;let n=t.createLinearGradient(0,0,e.width,e.height);n.addColorStop(0,`red`),n.addColorStop(1/6,`orange`),n.addColorStop(2/6,`yellow`),n.addColorStop(.5,`green`),n.addColorStop(4/6,`blue`),n.addColorStop(5/6,`indigo`),n.addColorStop(1,`violet`),t.fillStyle=n,t.fillRect(0,0,e.width,e.height);let r=`Random Text WMwmil10Oo`;return t.font=`23.123px Arial`,t.fillStyle=`black`,t.fillText(r,-5,15),t.fillStyle=`rgba(0, 0, 255, 0.5)`,t.fillText(r,-3.3,17.7),t.beginPath(),t.moveTo(0,0),t.lineTo(2*e.width/7,e.height),t.strokeStyle=`white`,t.lineWidth=2,t.stroke(),t.getImageData(0,0,e.width,e.height)}())).filter((e=>e!==null));t.length===0?e(null):e({commonPixelsHash:Z(Lr(t,Br,20).data.toString()).toString()})}))},fonts:async function(e){return new Promise((e=>{try{(async function(e){for(;!document.body;)await Vr(50);let t=document.createElement(`iframe`);t.setAttribute(`frameBorder`,`0`);let n=t.style;n.setProperty(`position`,`fixed`),n.setProperty(`display`,`block`,`important`),n.setProperty(`visibility`,`visible`),n.setProperty(`border`,`0`),n.setProperty(`opacity`,`0`),t.src=`about:blank`,document.body.appendChild(t);let r=t.contentDocument||t.contentWindow?.document;if(!r)throw Error(`Iframe document is not accessible`);e({iframe:r}),setTimeout((()=>{document.body.removeChild(t)}),0)})((async({iframe:t})=>{let n=t.createElement(`canvas`).getContext(`2d`);if(!n)return void e(null);let r=Ur.map((e=>Wr(n,e))),i={};Hr.forEach((e=>{let t=Wr(n,e);r.includes(t)||(i[e]=t)})),e(i)}))}catch{e(null)}}))},hardware:function(){return new Promise(((e,t)=>{let n=navigator.deviceMemory===void 0?0:navigator.deviceMemory,r=window.performance&&window.performance.memory?window.performance.memory:0;e({videocard:Gr(),architecture:Kr(),deviceMemory:n.toString()||`undefined`,jsHeapSizeLimit:r.jsHeapSizeLimit||0})}))},locales:function(){return new Promise((e=>{e({languages:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}))},math:function(){return new Promise((e=>{e({acos:Math.acos(.5),asin:qr(Math.asin,-1,1,97),cos:qr(Math.cos,0,Math.PI,97),largeCos:Math.cos(0x56bc75e2d63100000),largeSin:Math.sin(0x56bc75e2d63100000),largeTan:Math.tan(0x56bc75e2d63100000),sin:qr(Math.sin,-Math.PI,Math.PI,97),tan:qr(Math.tan,0,2*Math.PI,97)})}))},permissions:async function(e){let t=e?.permissions_to_check||Yr;return Jr(await Promise.all(Array.from({length:3},(()=>async function(e){let t={};for(let n of e)try{t[n]=(await navigator.permissions.query({name:n})).state.toString()}catch{}return t}(t)))),t)},plugins:async function(){let e=[];if(navigator.plugins)for(let t=0;t<navigator.plugins.length;t++){let n=navigator.plugins[t];e.push([n.name,n.filename,n.description].join(`|`))}return new Promise((t=>{t({plugins:e})}))},screen:function(){return new Promise((e=>{if(typeof matchMedia>`u`||typeof screen>`u`)return void e(null);let t={is_touchscreen:navigator.maxTouchPoints>0,maxTouchPoints:navigator.maxTouchPoints,colorDepth:screen.colorDepth,mediaMatches:ei()};$r()&&navigator.maxTouchPoints>0&&(t.resolution=function(){let e=window.screen.width,t=window.screen.height;return`${Math.max(e,t).toString()}x${Math.min(e,t).toString()}`}()),e(t)}))},system:function(){return new Promise((e=>{let t=Zr();e({platform:window.navigator.platform,productSub:navigator.productSub,product:navigator.product,useragent:navigator.userAgent,hardwareConcurrency:navigator.hardwareConcurrency,browser:{name:t.name,version:t.version},mobile:$r(),applePayVersion:ti(),cookieEnabled:window.navigator.cookieEnabled})}))},webgl:async function(){let e=ri?(oi||=si(),oi):si();if(!e)return{webgl:`unsupported`};try{return{commonPixelsHash:Z(Lr(Array.from({length:ni},(()=>function(e){let{canvas:t,gl:n,program:r,buffer:i}=e;try{n.useProgram(r),n.bindBuffer(n.ARRAY_BUFFER,i);let e=n.getAttribLocation(r,`position`);n.enableVertexAttribArray(e),n.vertexAttribPointer(e,2,n.FLOAT,!1,0,0),n.viewport(0,0,t.width,t.height),n.clearColor(0,0,0,1),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.LINES,0,274);let a=new Uint8ClampedArray(t.width*t.height*4);return n.readPixels(0,0,t.width,t.height,n.RGBA,n.UNSIGNED_BYTE,a),new ImageData(a,t.width,t.height)}catch{return oi=null,new ImageData(1,1)}finally{n.bindBuffer(n.ARRAY_BUFFER,null),n.useProgram(null),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0)}}(e))),e.canvas.width,e.canvas.height).data.toString()).toString()}}catch{return{webgl:`unsupported`}}},webrtc:async function(e){return new Promise((e=>{let t;try{let n=window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection;if(!n)return void e({supported:!1,error:`WebRTC not supported`});t=new n({iceCandidatePoolSize:1,iceServers:[]});let r=t;r.createDataChannel(``),(async()=>{try{let t=await r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});await r.setLocalDescription(t);let n=t.sdp||``,i=[...new Set((n.match(/extmap:\d+ [^\n\r]+/g)||[]).map((e=>e.replace(/extmap:\d+ /,``))))].sort(),a=e=>{let t=n.match(RegExp(`m=${e} [^\\s]+ [^\\s]+ ([^\\n\\r]+)`));return t?t[1].split(` `):[]},o=(e,t)=>t.map((t=>{let r=RegExp(`(rtpmap|fmtp|rtcp-fb):${t} (.+)`,`g`),i=[...n.matchAll(r)];if(!i.length)return null;let a={};return i.forEach((t=>{let[n,r,i]=t,o=i.split(`/`);r===`rtpmap`?(a.mimeType=`${e}/${o[0]}`,a.clockRate=+o[1],e===`audio`&&(a.channels=+o[2]||1)):r===`rtcp-fb`?(a.feedbackSupport=a.feedbackSupport||[],a.feedbackSupport.push(i)):r===`fmtp`&&(a.sdpFmtpLine=i)})),a})).filter(Boolean),s=o(`audio`,a(`audio`)),c=o(`video`,a(`video`)),l={audio:{count:s.length,hash:Z(Q(s))},video:{count:c.length,hash:Z(Q(c))},extensionsHash:Z(Q(i))};r.close();let u={supported:!0,...l,candidateType:`host`};e({details:u,hash:Z(Q(u))})}catch(t){r.close(),e({supported:!0,error:`WebRTC offer failed: ${t.message}`})}})()}catch(n){t?.close(),e({supported:!1,error:`WebRTC error: ${n.message}`})}}))},speech:async function(){return new Promise((e=>{try{if(typeof window>`u`||!window.speechSynthesis||typeof window.speechSynthesis.getVoices!=`function`)return void e({supported:!1,error:`Speech Synthesis API not supported`});let t=!1,n=null,r=r=>{if(!t){t=!0,n&&clearTimeout(n);try{let t=r.map((e=>{let t=e=>e.replace(/\\/g,`\\\\`).replace(/,/g,`\\,`);return[t(e.voiceURI||``),t(e.name||``),t(e.lang||``),e.localService?`1`:`0`,e.default?`1`:`0`].join(`,`)}));t.sort();let n={voiceCount:r.length,voicesHash:Z(Q(t))};e({details:n,hash:Z(Q(n))})}catch(t){e({supported:!0,error:`Voice processing failed: ${t.message}`})}}},i=window.speechSynthesis.getVoices();if(i.length>0)return void r(i);n=setTimeout((()=>{let e=window.speechSynthesis.getVoices();r(e)}),800);let a=()=>{window.speechSynthesis.removeEventListener(`voiceschanged`,a);let e=window.speechSynthesis.getVoices();r(e)};window.speechSynthesis.addEventListener(`voiceschanged`,a)}catch(t){e({supported:!1,error:`Speech Synthesis error: ${t.message}`})}}))}},li={},ui={timeout:`true`};function di(e,t){var n;let r=Zr();if(r.name===`unknown`&&t){let e=t.system?.browser;e!=null&&e.name&&(r={name:String(e.name),version:String(e.version||`unknown`)})}let i=r.name.toLowerCase(),a=parseInt(r.version.split(`.`)[0]||`0`,10),o=Array.isArray(e?.exclude)?[...e.exclude]:[],s=[...new Set([...e?.stabilize||[],`always`])];for(let e of s){let t=Pr[e];if(t)for(let e of t)`browsers`in e&&!((n=e.browsers)!=null&&n.some((e=>{let t=e.match(/(.+?)(>=)(\d+)/);return t?i===t[1]&&a>=+t[3]:i===e})))||o.push(...e.exclude)}return o}function fi(e,t){let n=di(t,e),r=Array.isArray(t?.include)?t.include:[];return function e(t,i=``){let a={};for(let[o,s]of Object.entries(t)){let t=i?`${i}.${o}`:o;if(typeof s!=`object`||Array.isArray(s)||s===null){let e=n.some((e=>t.startsWith(e))),i=r.some((e=>t.startsWith(e)));e&&!i||(a[o]=s)}else{let n=e(s,t);Object.keys(n).length>0&&(a[o]=n)}}return a}(e)}var pi=`https://experimental.thumbmarkjs.com/experimental.min.js`,mi=131072;function $(e,t){let n={target:`request`,type:e};return t&&(n.message=t.slice(0,200)),{schema:0,payload_id:`none`,signals:{},errors:[n]}}function hi(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function gi(e){return e instanceof Error?e.message:void 0}async function _i(){try{return await function(e,t){let n,r=new Promise((e=>{n=setTimeout((()=>e(null)),t)}));return Promise.race([e,r]).finally((()=>clearTimeout(n)))}(async function(){let e,t;try{let t=await fetch(pi,{method:`GET`});if(!t.ok)return $(`http`,`HTTP ${t.status}`);e=await t.text()}catch(e){return $(`fetch`,gi(e))}if(!e)return $(`empty`);if(e.length>mi)return $(`oversized`,`${e.length} chars`);try{let n=eval;t=await Promise.resolve(n(e))}catch(e){return $(function(e){return e instanceof SyntaxError?`syntax`:e instanceof EvalError?`eval_blocked`:`threw`}(e),gi(e))}return function(e){return!!hi(e)&&!(typeof e.schema!=`number`||e.schema<1)&&typeof e.payload_id==`string`&&hi(e.signals)}(t)?{...t,errors:Array.isArray(t.errors)?t.errors:[]}:$(`malformed`)}(),2e3)??$(`timeout`,`exceeded 2000ms`)}catch(e){return $(`threw`,gi(e))}}var vi=`visitor_id`;function yi(e){return e.storage_property_name?e.storage_property_name:e.property_name_factory(vi)}var bi=`${Ar}_${vi}`;function xi(e,t){try{localStorage.setItem(yi(t),e)}catch{}}var Si=`cache`;function Ci(e){try{let t=localStorage.getItem(e.property_name_factory(Si));return JSON.parse(t)||{}}catch{}return{}}function wi(e){return e.cache_lifetime_in_ms>kr?Date.now()+kr:Date.now()+e.cache_lifetime_in_ms}var Ti=class extends Error{constructor(e){super(`HTTP error! status: ${e}`),this.status=e}},Ei=null,Di=null;async function Oi(e,t,n,r){let i=n.simple_request?{"Content-Type":`text/plain`}:{"x-api-key":n.api_key,Authorization:`custom-authorized`,"Content-Type":`application/json`},a=await fetch(e,{method:`POST`,headers:i,body:JSON.stringify(t)});if(!a.ok)throw new Ti(a.status);let o=await a.json();return o.visitorId&&o.visitorId!==r&&xi(o.visitorId,n),Di=o,function(e,t){e.cache_api_call&&e.cache_lifetime_in_ms&&(function(e,t){let n={...Ci(e),...t};try{localStorage.setItem(e.property_name_factory(Si),JSON.stringify(n))}catch{}})(e,{apiResponseExpiry:wi(e),apiResponse:t})}(n,o),o}var ki=(e,t)=>{if(e.cache_api_call){if(Di)return Promise.resolve(Di);let t=function(e){let t=Ci(e);if(t&&t.apiResponse&&t.apiResponseExpiry&&Date.now()<=t.apiResponseExpiry)return t.apiResponse}(e);if(t)return Promise.resolve(t);if(Ei)return Ei}let n=e.api_endpoint||jr,r;try{let e=new URL(n);r=e.pathname!==`/`||n.endsWith(`/`)?n:`${e.origin}/thumbmark`}catch{r=`${n}/thumbmark`}let i=function(e){try{let t=yi(e),n=localStorage.getItem(t);return n||t===bi||(n=localStorage.getItem(bi),n&&xi(n,e)),n}catch{return null}}(e),{api_key:a,...o}=e,s={components:t,options:o,clientHash:Z(Q(t)),version:`1.11.0`};if(i&&(s.visitorId=i),e.metadata){let t=typeof e.metadata==`function`?e.metadata():e.metadata;t&&((typeof t==`string`?t.length:JSON.stringify(t).length)>1e3?console.error(`ThumbmarkJS: Metadata exceeds 1000 characters. Skipping metadata.`):s.metadata=t)}let c=e.timeout||5e3,l=async function(e,t,n,r){for(let i=0;i<3;i++){i>0&&await new Promise((e=>setTimeout(e,200*i)));try{return await Oi(e,t,n,r)}catch(e){if(e instanceof Ti||i===2)throw e}}throw Error(`Unreachable`)}(r,s,e,i).finally((()=>{Ei=null})),u=new Promise((t=>{setTimeout((()=>{t(Ci(e)?.apiResponse||{info:{timed_out:!0},...i&&{visitorId:i}})}),c)}));return Ei=Promise.race([l,u]),Ei};async function Ai(e,t={}){var n;if(typeof document>`u`||typeof window>`u`)return{thumbmark:``,components:{},info:{},version:`1.11.0`,error:[{type:`fatal`,message:`Browser environment required`}]};try{let r={...Mr,...e},i=[],a=r.logging&&!sessionStorage.getItem(`_tmjs_l`)&&Math.random()<1e-4,{elapsed:o,resolvedComponents:s,errors:c,pipelineTimings:l}=await ji({...ci,...li,...t},r);i.push(...c);let u=r.api_key||r.simple_request?ki(r,s):null,d=null;if(u)try{d=await u}catch(e){if(e instanceof Ti&&e.status===403)return{error:[{type:`api_unauthorized`,message:`Invalid API key or quota exceeded`}],components:{},info:{},version:`1.11.0`,thumbmark:``};i.push({type:e instanceof Ti?`api_error`:`network_error`,message:e instanceof Error?e.message:String(e)})}(n=d?.info)!=null&&n.timed_out&&i.push({type:`api_timeout`,message:`API request timed out`});let f=performance.now(),p=fi(d?.components||{},r),m=performance.now()-f,h={...s,...p},g=d?.info||{uniqueness:{score:`api only`}},_,v=0,y=0;if(d?.thumbmark)_=d.thumbmark;else{let e=performance.now(),t=Q(h);v=performance.now()-e;let n=performance.now();_=Z(t),y=performance.now()-n}a&&async function(e,t,n,r=[]){let i=`${jr}/log`;sessionStorage.setItem(`_tmjs_l`,`1`);let a={thumbmark:e,components:t,experimental:await _i(),version:`1.11.0`,options:n,path:(window==null?void 0:window.location)?.pathname,...r.length>0&&{errors:r}};try{await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)})}catch{}}(_,h,r,i).catch((()=>{}));let b={"_pipeline.dispatch":l[`_pipeline.dispatch`],"_pipeline.resolve":l[`_pipeline.resolve`],"_pipeline.filter":l[`_pipeline.filter`]+m,"_pipeline.stringify":v,"_pipeline.hash":y,"_pipeline.assembly":0},ee={...o,...l,...b},x=r.performance?{elapsed:ee}:{},te=performance.now(),ne={...d?.visitorId&&{visitorId:d.visitorId},thumbmark:_,components:h,info:g,version:`1.11.0`,...x,...i.length>0&&{error:i},...d?.requestId&&{requestId:d.requestId},...d?.metadata&&{metadata:d.metadata}};return ee[`_pipeline.assembly`]=performance.now()-te,ne}catch(e){return{thumbmark:``,components:{},info:{},version:`1.11.0`,error:[{type:`fatal`,message:e instanceof Error?e.message:String(e)}]}}}async function ji(e,t){let n={...Mr,...t},r=di(n).filter((e=>!e.includes(`.`))),i=Object.entries(e).filter((([e])=>!(n?.exclude)?.includes(e))).filter((([e])=>!r.includes(e))).filter((([e])=>(n?.include)?.some((e=>e.includes(`.`)))?(n?.include)?.some((t=>t.startsWith(e))):n?.include?.length===0||(n?.include)?.includes(e))),a=i.map((([e])=>e)),o={},s=performance.now(),c=i.map((([e,n])=>{let r=performance.now(),i=n(t);return o[`_dispatch.${e}`]=performance.now()-r,i})),l=performance.now()-s,u=performance.now(),d=await function(e,t,n){return Promise.all(e.map((e=>{let r=performance.now(),i,a=e.then((e=>(i!==void 0&&clearTimeout(i),{value:e,elapsed:performance.now()-r}))).catch((e=>(i!==void 0&&clearTimeout(i),{value:n,elapsed:performance.now()-r,error:e instanceof Error?e.message:String(e)}))),o=new Promise((e=>{i=setTimeout((()=>{e({value:n,elapsed:performance.now()-r,error:`timeout`})}),t)}));return Promise.race([a,o])})))}(c,n?.timeout||5e3,ui),f=performance.now()-u,p={},m={},h=[];d.forEach(((e,t)=>{let n=a[t];p[n]=e.elapsed??0,e.error===`timeout`?h.push({type:`component_timeout`,message:`Component '${n}' timed out`,component:n}):e.error&&h.push({type:`component_error`,message:e.error,component:n}),e.value!=null&&(m[n]=e.value)}));let g=performance.now();return{elapsed:p,resolvedComponents:fi(m,n),errors:h,pipelineTimings:{"_pipeline.dispatch":l,"_pipeline.resolve":f,"_pipeline.filter":performance.now()-g,...o}}}async function Mi(){return(await Ai(Nr)).components}async function Ni(e){try{let t=await Ai(Nr);return e?{hash:t.thumbmark.toString(),data:t.components}:t.thumbmark.toString()}catch(e){throw e}}var Pi=`query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }`;function Fi(e){let t=(e||``).match(/\b(query|mutation|subscription)\b/i),n=t?t[1].toLowerCase():`query`,r=(e||``).indexOf(`{`),i=r>=0?e.slice(r+1).match(/[A-Za-z_][A-Za-z0-9_]*/):null;return{type:n,name:i?i[0]:``}}var Ii=class{constructor({serverUri:e,socket:t=null,encrypt:n=!1}){this.$__client=this.createUrqlClient({serverUri:e,socket:t,encrypt:n}),this.$__authToken=``,this.$__pubkey=null,this.$__wallet=null,this.serverUri=e,this.soketi=t,this.cipherLink=!!n,this.$__subscriptionManager=new Map}createUrqlClient({serverUri:e,socket:t,encrypt:n}){let r=[l.cacheExchange,l.fetchExchange];if(t&&t.socketUri){let e=(0,u.createClient)({url:t.socketUri,connectionParams:()=>({authToken:this.$__authToken})});r.push((0,l.subscriptionExchange)({forwardSubscription:t=>({subscribe:n=>({unsubscribe:e.subscribe(t,n)})})}))}return(0,l.createClient)({url:e,exchanges:r,preferGetMethod:!1,...n?{fetch:(e,t)=>this.cipherFetch(e,t)}:{},fetchOptions:()=>({headers:{"X-Auth-Token":this.$__authToken},signal:AbortSignal.timeout(6e4)})})}shouldEncrypt(e){let t;try{t=JSON.parse(e)}catch{return!1}let{type:n,name:r}=Fi(t.query);return!(n===`query`&&(r===`__schema`||r===`ContinuId`)||n===`mutation`&&r===`AccessToken`||n===`mutation`&&r===`ProposeMolecule`&&(t.variables&&t.variables.molecule&&t.variables.molecule.atoms&&t.variables.molecule.atoms[0]&&t.variables.molecule.atoms[0].isotope)===`U`)}async cipherFetch(e,t){let n=this.getWallet(),r=this.getPubKey(),i=!1,a=t;if(n&&r&&t&&typeof t.body==`string`&&this.shouldEncrypt(t.body)){let e=await n.encryptStringML(t.body,r);a={...t,body:JSON.stringify({query:Pi,variables:{Hash:e}})},i=!0}let o=await fetch(e,a);if(!i)return o;let s=await o.text(),c={status:o.status,statusText:o.statusText,headers:o.headers},l;try{l=JSON.parse(s)}catch{return new Response(s,c)}let u=l&&l.data&&l.data.CipherHash&&l.data.CipherHash.hash;if(typeof u!=`string`)return new Response(s,c);let d=await n.decryptMyMessageML(JSON.parse(u));return new Response(d??s,c)}setAuthData({token:e,pubkey:t,wallet:n}){this.$__authToken=e,this.$__pubkey=t,this.$__wallet=n,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}buildRequestOptions(e){if(!e)return;let t={};e.requestPolicy&&(t.requestPolicy=e.requestPolicy);let n=e.fetchOptions&&e.fetchOptions.signal;if(n){let e=typeof AbortSignal<`u`&&typeof AbortSignal.any==`function`?AbortSignal.any([n,AbortSignal.timeout(6e4)]):n;t.fetchOptions={headers:{"X-Auth-Token":this.$__authToken},signal:e}}return Object.keys(t).length?t:void 0}async query(e){let{query:t,variables:n,context:r}=e,i=this.buildRequestOptions(r),a=await this.$__client.query(t,n||{},i).toPromise();return this.formatResponse(a)}async mutate(e){let{mutation:t,variables:n,context:r}=e,i=this.buildRequestOptions(r),a=await this.$__client.mutation(t,n||{},i).toPromise();return this.formatResponse(a)}subscribe(e,t){let{query:n,variables:r,operationName:i}=e,a=(0,d.pipe)(this.$__client.subscription(n,r),(0,d.map)(e=>{t(this.formatResponse(e))}),(0,d.subscribe)(()=>{}));return this.$__subscriptionManager.set(i,a),{unsubscribe:()=>this.unsubscribe(i)}}formatResponse(e){return{data:e.data,errors:e.error?[e.error]:void 0}}socketDisconnect(){this.soketi&&this.unsubscribeAll()}unsubscribe(e){let t=this.$__subscriptionManager.get(e);t&&(t.unsubscribe(),this.$__subscriptionManager.delete(e))}unsubscribeAll(){this.$__subscriptionManager.forEach((e,t)=>{this.unsubscribe(t)})}unsubscribeFromChannel(e){this.unsubscribe(e)}setEncryption(e=!1){this.cipherLink=e,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:e})}getAuthToken(){return this.$__authToken}getPubKey(){return this.$__pubkey}getWallet(){return this.$__wallet}getServerUri(){return this.serverUri}getSocketUri(){return this.soketi?this.soketi.socketUri:null}getUri(){return this.serverUri}setUri(e){this.serverUri=e,this.$__client=this.createUrqlClient({serverUri:e,socket:this.soketi,encrypt:!!this.cipherLink})}setSocketUri({socketUri:e,appKey:t}){this.soketi={socketUri:e,appKey:t},this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}},Li=class{constructor({uri:e,cellSlug:t=null,client:n=null,socket:r=null,serverSdkVersion:i=3,logging:a=!1,defaultRequestPolicy:o=null,secretStorage:s=null,mlKemParameterSet:c=1024}){this.initialize({uri:e,cellSlug:t,socket:r,client:n,serverSdkVersion:i,logging:a,defaultRequestPolicy:o,secretStorage:s,mlKemParameterSet:c})}initialize({uri:e,cellSlug:t=null,socket:n=null,client:r=null,serverSdkVersion:i=3,logging:a=!1,defaultRequestPolicy:o=null,secretStorage:s=null,mlKemParameterSet:c=1024}){this.reset(),this.$__secretStorage=s,this.$__logging=a,this.$__defaultRequestPolicy=o,this.setMlKemParameterSet(c),this.$__authTokenObjects={},this.$__authInProcess=!1,this.abortControllers=new Map,this.setUri(e),t&&this.setCellSlug(t);for(let e in this.$__uris){let t=this.$__uris[e];this.$__authTokenObjects[t]=null}this.log(`info`,`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${i}...`),this.$__client=r||new Ii({socket:{socketUri:null,appKey:`knishio`,...n||{}},serverUri:this.getRandomUri()}),this.$__serverSdkVersion=i}getMlKemParameterSet(){return this.$__mlKemParameterSet||1024}setMlKemParameterSet(e){let t=Number(e);if(![1024,768].includes(t))throw Error(`KnishIO: unsupported ML-KEM parameter set ${e}; expected 1024 or 768.`);return this.$__mlKemParameterSet=t,this}getRandomUri(){let e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.$__encrypt!==e&&(this.log(`info`,`KnishIOClient::switchEncryption() - Forcing encryption ${e?`on`:`off`} to match node...`),this.$__encrypt=e,this.$__client.setEncryption(e),!0)}deinitialize(){this.log(`info`,`KnishIOClient::deinitialize() - Clearing the Knish.IO client session...`),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new B(`KnishIOClient::subscribe() - Socket client not initialized!`);return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}getDefaultRequestPolicy(){return this.$__defaultRequestPolicy||null}setDefaultRequestPolicy(e){this.$__defaultRequestPolicy=e}reset(){this.$__secret=``,this.$__bundle=``,this.$__secretStorage=null,this.remainderWallet=null,this.$__capabilityCache={},this.$__defaultRequestPolicy=null}getCellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}setUri(e){if(this.$__uris=typeof e==`object`?e:[e],this.$__client){let e=this.getRandomUri();this.$__client.setUri(e)}}setSocketUri(e){this.$__client&&typeof this.$__client.setSocketUri==`function`&&this.$__client.setSocketUri({socketUri:e,appKey:`knishio`})}getUri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){let e=this.getRandomUri();this.$__client.setUri(e);let t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).catch(e=>{this.log(`warn`,`KnishIOClient::client() - Background authorization failed: ${e.message}`)})}return this.$__client}hasSecret(){return!!this.$__secret&&this.$__secret.length>0||!!this.$__secretStorage&&!!this.$__bundle&&this.$__bundle.length>0}setSecret(e){if(this.$__secret=e,this.$__bundle=this.hashSecret(e,`setSecret`),this.$__secretStorage)this.$__secretStorage.storeSecret(this.$__bundle,e);else{let t=new mn;t.storeSecret(this.$__bundle,e),this.$__secretStorage=t}}hashSecret(e,t=null){return this.log(`info`,`KnishIOClient::hashSecret(${t?`source: ${t}`:``}) - Computing wallet bundle from secret...`),D(e)}getSecret(){if(!this.hasSecret())throw new _n(`KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?`);return this.$__secret}setSecretStorage(e,t=null){this.$__secretStorage=e,t&&(this.$__bundle=t)}getSecretStorage(){return this.$__secretStorage}async retrieveSecret(e={}){return this.$__secret&&this.$__secret.length>0?this.$__secret:this.$__secretStorage&&this.$__bundle&&this.$__bundle.length>0?await this.$__secretStorage.retrieveSecret(this.$__bundle,e):null}hasBundle(){return!!this.$__bundle}getBundle(){if(!this.hasBundle())throw new _n(`KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?`);return this.$__bundle}getFingerprint(){return Ni()}getFingerprintData(){return Mi()}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=I.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new I({secret:this.getSecret(),mlKemParameterSet:this.getMlKemParameterSet()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:r=null}){this.log(`info`,`KnishIOClient::createMolecule() - Creating a new molecule...`),e||(this.$__secret&&this.$__secret.length>0?e=this.getSecret():this.$__secretStorage&&this.$__bundle&&this.$__bundle.length>0&&(e=await this.$__secretStorage.retrieveSecret(this.$__bundle))),e||=this.getSecret(),t||=this.getBundle();let i=null;if(n&&n.token!==`USER`){if(this.lastMoleculeQuery&&this.getRemainderWallet()&&this.getRemainderWallet().token===`USER`&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success())i=this.getRemainderWallet().position;else{let e=await this.getSourceWallet();i=e?e.position:null}}return!n&&this.lastMoleculeQuery&&this.getRemainderWallet().token===`USER`&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(n=this.getRemainderWallet()),n===null&&(n=await this.getSourceWallet()),this.remainderWallet=r||I.create({secret:e,bundle:t,token:`USER`,batchId:n.batchId,characters:n.characters,mlKemParameterSet:this.getMlKemParameterSet()}),new cn({secret:e,bundle:t,sourceWallet:n,remainderWallet:this.getRemainderWallet(),cellSlug:this.getCellSlug(),version:this.getServerSdkVersion(),continuIdPosition:i,mlKemParameterSet:this.getMlKemParameterSet()})}createQuery(e){return new e(this.client(),this)}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.log(`info`,`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);let n=t||await this.createMolecule({}),r=new e(this.client(),this,n);if(!(r instanceof J))throw new B(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=r,r}async executeQuery(e,t=null,n={}){if(this.$__authToken&&this.$__authToken.isExpired()&&!this.$__authInProcess){this.log(`info`,`KnishIOClient::executeQuery() - Access token is expired. Getting new one...`);let e=this.$__secret||await this.retrieveSecret()||``;await this.requestAuthToken({secret:e,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt})}let r=new AbortController,i=JSON.stringify({query:e.$__query,variables:t});this.abortControllers.set(i,r);try{let a={...n};this.$__defaultRequestPolicy&&!a.requestPolicy&&(a.requestPolicy=this.$__defaultRequestPolicy);let o=await e.execute({variables:t,context:{fetchOptions:{signal:r.signal},...a}});return this.abortControllers.delete(i),o}catch(e){if(e.name===`AbortError`)this.log(`warn`,`Query was cancelled`);else throw e}}cancelQuery(e,t=null){let n=JSON.stringify({query:e.$__query,variables:t}),r=this.abortControllers.get(n);r&&(r.abort(),this.abortControllers.delete(n))}cancelAllQueries(){for(let e of this.abortControllers.values())e.abort();this.abortControllers.clear()}async queryBalance({token:e,bundle:t=null,type:n=`regular`}){let r=this.createQuery(Tn);return this.executeQuery(r,{bundleHash:t||this.getBundle(),token:e,type:n})}async querySourceWallet({token:e,amount:t,type:n=`regular`}){let r=(await this.queryBalance({token:e,type:n})).payload();if(r===null||gn.cmp(r.balance,t)<0)throw new L;if(!r.position||!r.address)throw new L(`Source wallet can not be a shadow wallet.`);return r}async subscribeCreateMolecule({bundle:e,closure:t}){return await this.createSubscribe(ar).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:n}){if(!t)throw new B(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(or).execute({variables:{bundle:e||this.getBundle(),token:t},closure:n})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(sr).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:n}){return this.createSubscribe(cr).execute({variables:{metaType:e,metaId:t},closure:n})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:n=null,value:r=null,latest:i=!0,fields:a=null,filter:o=null,queryArgs:s=null,count:c=null,countBy:l=null,throughAtom:u=!0,throughMolecule:d=!1,values:f=null,keys:p=null,atomValues:m=null,requestPolicy:h=null}){this.log(`info`,`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);let g,_;return d?(g=this.createQuery(Sr),_=Sr.createVariables({metaType:e,metaId:t,key:n,value:r,latest:i,filter:o,queryArgs:s,countBy:l,values:f,keys:p,atomValues:m,cellSlug:this.getCellSlug()})):u?(g=this.createQuery(br),_=br.createVariables({metaType:e,metaId:t,key:n,value:r,latest:i,filter:o,queryArgs:s,countBy:l,values:f,keys:p,atomValues:m,cellSlug:this.getCellSlug()})):(g=this.createQuery(Dn),_=Dn.createVariables({metaType:e,metaId:t,key:n,value:r,latest:i,filter:o,queryArgs:s,count:c,countBy:l,cellSlug:this.getCellSlug()})),this.executeQuery(g,_,h?{requestPolicy:h}:{})}async queryMetaVerified(e){let t=await this.queryMeta(e),n=t.payload();return n&&(n.integrity=t.verifyIntegrity()),t}async hasQueryField(e){let t=`${this.getUri()}::${e}`;if(typeof this.$__capabilityCache[t]==`boolean`)return this.$__capabilityCache[t];try{let n=((await this.$__client.query({query:`{ __schema { queryType { fields { name } } } }`,variables:{}}))?.data?.__schema?.queryType?.fields||[]).some(t=>t.name===e);return this.$__capabilityCache[t]=n,n}catch(n){return this.log(`warn`,`KnishIOClient::hasQueryField() - Capability probe for '${e}' failed: ${n.message}`),this.$__capabilityCache[t]=!1,!1}}async queryEmbeddingStatus({metaType:e=null,metaId:t=null,instances:n=null}){if(this.log(`info`,`KnishIOClient::queryEmbeddingStatus() - Checking embedding status for metaType: ${e||`(bulk)`}...`),!await this.hasQueryField(`embeddingStatus`))return this.log(`warn`,`KnishIOClient::queryEmbeddingStatus() - Server does not support embeddingStatus query. Returning null.`),null;let r=this.createQuery(wr),i=wr.createVariables({metaType:e,metaId:t,instances:n});return this.executeQuery(r,i)}async queryBatch({batchId:e}){this.log(`info`,`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);let t=this.createQuery(On);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.log(`info`,`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);let t=this.createQuery(kn);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:r,positions:i,position:a,walletAddresses:o,walletAddress:s,isotopes:c,isotope:l,tokenSlugs:u,tokenSlug:d,cellSlugs:f,cellSlug:p,batchIds:m,batchId:h,values:g,value:_,metaTypes:v,metaType:y,metaIds:b,metaId:ee,indexes:x,index:te,filter:ne,latest:re,queryArgs:S={limit:15,offset:1}}){this.log(`info`,`KnishIOClient::queryAtom() - Querying atom instances`);let ie=this.createQuery(gr);return await this.executeQuery(ie,gr.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:r,positions:i,position:a,walletAddresses:o,walletAddress:s,isotopes:c,isotope:l,tokenSlugs:u,tokenSlug:d,cellSlugs:f,cellSlug:p,batchIds:m,batchId:h,values:g,value:_,metaTypes:v,metaType:y,metaIds:b,metaId:ee,indexes:x,index:te,filter:ne,latest:re,queryArgs:S}))}async createWallet({token:e}){let t=new I({secret:this.getSecret(),token:e,mlKemParameterSet:this.getMlKemParameterSet()}),n=await this.createMoleculeMutation({mutationClass:Qn});return n.fillMolecule(t),await this.executeQuery(n)}async queryActiveSession({bundleHash:e,metaType:t,metaId:n}){let r=this.createQuery(fr);return await this.executeQuery(r,{bundleHash:e,metaType:t,metaId:n})}async activeSession({bundle:e,metaType:t,metaId:n,ipAddress:r,browser:i,osCpu:a,resolution:o,timeZone:s,json:c={}}){let l=this.createQuery(ur);return await this.executeQuery(l,{bundleHash:e,metaType:t,metaId:n,ipAddress:r,browser:i,osCpu:a,resolution:o,timeZone:s,json:JSON.stringify(c)})}async createToken({token:e,amount:t=null,meta:n=null,batchId:r=null,units:i=[]}){let a=V.get(n||{},`fungibility`);if(a===`stackable`&&(n.batchId=r||le({})),[`nonfungible`,`stackable`].includes(a)&&i.length>0){if(V.get(n||{},`decimals`)>0)throw new nr;if(t>0)throw new rr;t=i.length,n.splittable=1,n.decimals=0,n.tokenUnits=JSON.stringify(i)}let o=new I({secret:this.getSecret(),bundle:this.getBundle(),token:e,batchId:r,mlKemParameterSet:this.getMlKemParameterSet()}),s=await this.createMoleculeMutation({mutationClass:Pn});return s.fillMolecule({recipientWallet:o,amount:t,meta:n||{}}),await this.executeQuery(s)}async createRule({metaType:e,metaId:t,rule:n,policy:r={}}){let i=await this.createMoleculeMutation({mutationClass:Er,molecule:await this.createMolecule({secret:this.getSecret()})});return i.fillMolecule({metaType:e,metaId:t,rule:n,policy:r}),await this.executeQuery(i)}async createMeta({metaType:e,metaId:t,meta:n=null,policy:r={}}){let i=await this.createMoleculeMutation({mutationClass:Wn,molecule:await this.createMolecule({secret:this.getSecret()})}),a=n||{};return i.fillMolecule({metaType:e,metaId:t,meta:a,policy:r}),await this.executeQuery(i)}async registerPeer({host:e}){let t=await this.createMoleculeMutation({mutationClass:Kn,molecule:await this.createMolecule({secret:this.getSecret()})});return t.fillMolecule({host:e}),await this.executeQuery(t)}async appendRequest({metaType:e,metaId:t,action:n,meta:r={}}){let i=await this.createMoleculeMutation({mutationClass:Jn,molecule:await this.createMolecule({secret:this.getSecret()})});return i.fillMolecule({metaType:e,metaId:t,action:n,meta:r}),await this.executeQuery(i)}async createIdentifier({type:e,contact:t,code:n}){let r=await this.createMoleculeMutation({mutationClass:Bn});return r.fillMolecule({type:e,contact:t,code:n}),await this.executeQuery(r)}async linkIdentifier({type:e,contact:t}){let n=this.createQuery(Xn);return await this.executeQuery(n,{bundle:this.getBundle(),type:e,content:t})}async createPolicy({metaType:e,metaId:t,policy:n={}}){let r=await this.createMolecule({});r.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:n}),r.addContinuIdAtom(),r.sign({bundle:this.getBundle()}),r.check();let i=await this.createMoleculeMutation({mutationClass:J,molecule:r});return await this.executeQuery(i)}async queryPolicy({metaType:e,metaId:t}){let n=this.createQuery(vr);return await this.executeQuery(n,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:n=!0}){this.log(`info`,`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:``}...`);let r=this.createQuery(Cn);return this.executeQuery(r,{bundleHash:e||this.getBundle(),token:t,unspent:n}).then(e=>e.payload())}queryBundle({bundle:e=null,fields:t=null,raw:n=!1}){this.log(`info`,`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:``}...`),e||=this.getBundle(),typeof e==`string`&&(e=[e]);let r=this.createQuery(xn);return this.executeQuery(r,{bundleHashes:e}).then(e=>n?e:e.payload())}async queryContinuId({bundle:e}){let t=this.createQuery(yn);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:n=null,units:r=[],meta:i=null,batchId:a=null}){let o,s;i||={};let c=this.createQuery(pr),l=await this.executeQuery(c,{slug:e}),u=V.get(l.data(),`0.fungibility`)===`stackable`;if(!u&&a!==null)throw new Qt(`Expected Batch ID = null for non-stackable tokens.`);if(u&&a===null&&(a=le({})),r.length>0){if(n>0)throw new rr;n=r.length,i.tokenUnits=JSON.stringify(r)}t?(Object.prototype.toString.call(t)===`[object String]`&&(I.isBundleHash(t)?(o=`walletBundle`,s=t):t=I.create({secret:t,token:e,mlKemParameterSet:this.getMlKemParameterSet()})),t instanceof I&&(o=`wallet`,i.position=t.position,i.bundle=t.bundle,s=t.address)):(o=`walletBundle`,s=this.getBundle());let d=await this.createMoleculeMutation({mutationClass:In});return d.fillMolecule({token:e,amount:n,metaType:o,metaId:s,meta:i,batchId:a}),await this.executeQuery(d)}async claimShadowWallet({token:e,batchId:t=null,molecule:n=null}){let r=await this.createMoleculeMutation({mutationClass:Hn,molecule:n});return r.fillMolecule({token:e,batchId:t}),await this.executeQuery(r)}async claimShadowWallets({token:e}){let t=await this.queryWallets({token:e});if(!t||!Array.isArray(t))throw new tr;t.forEach(e=>{if(!e.isShadow())throw new tr});let n=[];for(let r of t)n.push(await this.claimShadowWallet({token:e,batchId:r.batchId}));return n}async transferToken({bundleHash:e,token:t,amount:n=null,units:r=[],batchId:i=null,sourceWallet:a=null}){if(r.length>0){if(n>0)throw new rr;n=r.length}if(a===null&&(a=await this.querySourceWallet({token:t,amount:n})),a===null||gn.cmp(a.balance,n)<0)throw new L;let o=I.create({bundle:e,token:t,mlKemParameterSet:this.getMlKemParameterSet()});i===null?o.initBatchId({sourceWallet:a}):o.batchId=i;let s=a.createRemainder(this.getSecret());a.splitUnits(r,s,o);let c=await this.createMolecule({sourceWallet:a,remainderWallet:s}),l=await this.createMoleculeMutation({mutationClass:Rn,molecule:c});return l.fillMolecule({recipientWallet:o,amount:n}),await this.executeQuery(l)}async transferTokens({token:e,recipients:t,sourceWallet:n=null}){let r=t.map(e=>{let t=e.units||[];if(t.length>0){if(e.amount>0)throw new rr;return t.length}return e.amount||0}),i=r.reduce((e,t)=>e+t,0);if(n===null&&(n=await this.querySourceWallet({token:e,amount:i})),n===null||gn.cmp(n.balance,i)<0)throw new L;let a=t.map(t=>{let r=I.create({bundle:t.bundleHash,token:e,mlKemParameterSet:this.getMlKemParameterSet()});return t.batchId!==void 0&&t.batchId!==null?r.batchId=t.batchId:r.initBatchId({sourceWallet:n}),r}),o=n.createRemainder(this.getSecret());n.splitUnitsMulti(t.map(e=>e.units||[]),a,o);let s=await this.createMolecule({sourceWallet:n,remainderWallet:o}),c=await this.createMoleculeMutation({mutationClass:Rn,molecule:s});return c.fillMoleculeMulti({recipientWallets:a,amounts:r}),await this.executeQuery(c)}async depositBufferToken({tokenSlug:e,amount:t,tradeRates:n,sourceWallet:r=null}){r===null&&(r=await this.querySourceWallet({token:e,amount:t}));let i=r.createRemainder(this.getSecret()),a=await this.createMolecule({sourceWallet:r,remainderWallet:i}),o=await this.createMoleculeMutation({mutationClass:Dr,molecule:a});return o.fillMolecule({amount:t,tradeRates:n}),await this.executeQuery(o)}async withdrawBufferToken({tokenSlug:e,amount:t,sourceWallet:n=null,signingWallet:r=null}){n===null&&(n=await this.querySourceWallet({token:e,amount:t,type:`buffer`}));let i=n,a=await this.createMolecule({sourceWallet:n,remainderWallet:i}),o=await this.createMoleculeMutation({mutationClass:Or,molecule:a}),s={};return s[this.getBundle()]=t,o.fillMolecule({recipients:s,signingWallet:r}),await this.executeQuery(o)}async burnTokens({token:e,amount:t=null,units:n=[],sourceWallet:r=null}){r===null&&(r=await this.querySourceWallet({token:e,amount:t}));let i=r.createRemainder(this.getSecret());if(n.length>0){if(t>0)throw new rr;t=n.length,r.splitUnits(n,i)}let a=await this.createMolecule({sourceWallet:r,remainderWallet:i});a.burnToken({amount:t}),a.sign({bundle:this.getBundle()}),a.check(r);let o=await this.createMoleculeMutation({mutationClass:J,molecule:a});return this.executeQuery(o)}async replenishToken({token:e,amount:t=null,units:n=[],sourceWallet:r=null}){if(r===null&&(r=(await this.queryBalance({token:e})).payload()),!r)throw new L(`Source wallet is missing or invalid.`);let i=r.createRemainder(this.getSecret()),a=await this.createMolecule({sourceWallet:r,remainderWallet:i});a.replenishToken({amount:t,units:n}),a.sign({bundle:this.getBundle()}),a.check();let o=await this.createMoleculeMutation({mutationClass:J,molecule:a});return this.executeQuery(o)}async fuseToken({bundleHash:e,tokenSlug:t,newTokenUnit:n,fusedTokenUnitIds:r,sourceWallet:i=null}){if(i===null&&(i=(await this.queryBalance({token:t})).payload()),i===null)throw new L(`Source wallet is missing or invalid.`);if(!i.tokenUnits||!i.tokenUnits.length)throw new L(`Source wallet does not have token units.`);if(!r.length)throw new L(`Fused token unit list is empty.`);let a=[];i.tokenUnits.forEach(e=>{a.push(e.id)}),r.forEach(e=>{if(!a.includes(e))throw new L(`Fused token unit ID = ${e} does not found in the source wallet.`)});let o=I.create({bundle:e,token:t,mlKemParameterSet:this.getMlKemParameterSet()});o.initBatchId({sourceWallet:i});let s=i.createRemainder(this.getSecret());i.splitUnits(r,s),typeof n==`string`&&(n=new ue(n,n,{})),n.metas.fusedTokenUnits=i.getTokenUnitsData(),o.tokenUnits=[n];let c=await this.createMolecule({sourceWallet:i,remainderWallet:s});c.fuseToken(i.tokenUnits,o),c.sign({bundle:this.getBundle()}),c.check();let l=await this.createMoleculeMutation({mutationClass:J,molecule:c});return this.executeQuery(l)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);let n=new I({secret:se(await this.getFingerprint()),token:`AUTH`,mlKemParameterSet:this.getMlKemParameterSet()}),r=await this.createQuery(er),i={cellSlug:e,pubkey:n.pubkey,encrypt:t},a=await r.execute({variables:i});if(a.success()){let e=ln.create({token:a.token(),expiresAt:a.expiresAt(),pubkey:a.pubKey(),encrypt:a.encrypt()},n);this.setAuthToken(e)}else throw new mr(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${a.reason()}`);return a}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);let n=new I({secret:e,token:`AUTH`,mlKemParameterSet:this.getMlKemParameterSet()}),r=await this.createMolecule({secret:e,sourceWallet:n}),i=await this.createMoleculeMutation({mutationClass:Mn,molecule:r}),a={encrypt:t?`true`:`false`};n.pubkey&&(a.walletPubkey=n.pubkey),i.fillMolecule({meta:a});let o=await i.execute({});if(o.success()){let e=ln.create({token:o.token(),expiresAt:o.expiresAt(),pubkey:o.pubKey(),encrypt:o.encrypt()},n);this.setAuthToken(e)}else throw new mr(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${o.reason()}`);return o}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:n=null,encrypt:r=!1}){if(this.$__serverSdkVersion<3)return this.log(`warn`,`KnishIOClient::authorize() - Server SDK version does not require an authorization...`),null;e===null&&t&&(e=se(t)),n&&this.setCellSlug(n),e===null&&this.$__secretStorage&&this.$__bundle&&(e=await this.$__secretStorage.retrieveSecret(this.$__bundle)),this.$__authInProcess=!0;let i;return i=e?await this.requestProfileAuthToken({secret:e,encrypt:r}):await this.requestGuestAuthToken({cellSlug:n,encrypt:r}),this.log(`info`,`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(r),this.$__authInProcess=!1,i}setAuthToken(e){if(!e){this.log(`info`,`KnishIOClient::setAuthToken() - authToken object is empty.`);return}this.$__authTokenObjects[this.getUri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e}getAuthToken(){return this.$__authToken}log(e,t){if(this.$__logging)switch(e){case`info`:console.info(t);break;case`warn`:console.warn(t);break;case`error`:console.error(t);break;default:console.log(t)}}},Ri=class extends G{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.AccessToken`})}reason(){return`Invalid response from server`}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!V.has(this.payload(),e))throw new W(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return V.get(this.payload(),e)}token(){return this.payloadKey(`token`)}time(){return this.payloadKey(`time`)}},zi=class{constructor(){this.store=new Map}getItem(e){return this.store.get(e)??null}setItem(e,t){this.store.set(e,t)}removeItem(e){return this.store.delete(e)}keys(){return Array.from(this.store.keys())}};function Bi(e){let t=``,n=e.byteLength;for(let r=0;r<n;r++){let n=e[r];n!==void 0&&(t+=String.fromCharCode(n))}return btoa(t)}function Vi(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r}var Hi=new TextEncoder,Ui=new TextDecoder,Wi=`knishio:secret:`,Gi=1e5,Ki=class{constructor(e={}){this.providerType=`webcrypto-aes-gcm`,this.backend=e.backend||new zi,this.defaultPassphrase=e.defaultPassphrase,this.hardwareBacked=e.hardwareBacked||!1}isHardwareBacked(){return this.hardwareBacked}async isAvailable(){return globalThis.crypto!==void 0&&globalThis.crypto.subtle!==void 0}async deriveKey(e,t,n=Gi){if(!await this.isAvailable())throw H.unavailable(this.providerType,`WebCrypto API is not available`);let r=Hi.encode(e);try{let e=await globalThis.crypto.subtle.importKey(`raw`,r,`PBKDF2`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`PBKDF2`,salt:t,iterations:n,hash:`SHA-256`},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}finally{U(r)}}async storeSecret(e,t,n={}){if(!e)throw new H(`Bundle hash cannot be empty`);if(!t)throw new H(`Secret cannot be empty`);let r=n.passphrase||this.defaultPassphrase;if(!r)throw new H(`Passphrase required for envelope encryption`);let i=new Uint8Array(16),a=new Uint8Array(12);globalThis.crypto.getRandomValues(i),globalThis.crypto.getRandomValues(a);let o=await this.deriveKey(r,i,Gi),s=Hi.encode(t);try{let t=await globalThis.crypto.subtle.encrypt({name:`AES-GCM`,iv:a},o,s),r=Bi(new Uint8Array(t)),c={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:this.hardwareBacked,providerType:this.providerType},l={version:1,ciphertext:r,iv:Bi(a),salt:Bi(i),algorithm:`AES-GCM`,iterations:Gi,metadata:c};await this.backend.setItem(`${Wi}${e}`,JSON.stringify(l))}catch(e){throw new H(`Encryption failed: ${e instanceof Error?e.message:String(e)}`)}finally{U(s)}}async retrieveSecret(e,t={}){let n=await this.backend.getItem(`${Wi}${e}`);if(!n)return null;let r;try{r=JSON.parse(n)}catch{throw H.decryptionFailed(`Corrupted payload format`)}let i=t.passphrase||this.defaultPassphrase;if(!i)throw new H(`Passphrase required for secret decryption`);let a=Vi(r.salt),o=Vi(r.iv),s=Vi(r.ciphertext);try{let e=await this.deriveKey(i,a,r.iterations||Gi),t=await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:o},e,s),n=new Uint8Array(t);try{return Ui.decode(n)}finally{U(n)}}catch(e){let t=e instanceof Error?e.message:String(e);throw H.decryptionFailed(t)}}async deleteSecret(e){let t=`${Wi}${e}`;return await this.backend.removeItem(t)!==!1}async hasSecret(e){return await this.backend.getItem(`${Wi}${e}`)!==null}async listSecrets(){let e=(await this.backend.keys()).filter(e=>e.startsWith(Wi)),t=[];for(let n of e){let e=await this.backend.getItem(n);if(e)try{let n=JSON.parse(e);n.metadata&&t.push(n.metadata)}catch{}}return t}async withSecret(e,t,n={}){let r=await this.backend.getItem(`${Wi}${e}`);if(!r)throw H.notFound(e);let i;try{i=JSON.parse(r)}catch{throw H.decryptionFailed(`Corrupted payload format`)}let a=n.passphrase||this.defaultPassphrase;if(!a)throw new H(`Passphrase required for secret decryption`);let o=Vi(i.salt),s=Vi(i.iv),c=Vi(i.ciphertext);try{let e=await this.deriveKey(a,o,i.iterations||Gi),n=await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:s},e,c);return await dn(new Uint8Array(n),async e=>await t(Ui.decode(e)))}catch(e){if(e instanceof H)throw e;let t=e instanceof Error?e.message:String(e);throw H.decryptionFailed(t)}}};function qi(e={}){return e.type===`memory`?new mn:globalThis.crypto!==void 0&&globalThis.crypto.subtle!==void 0?new Ki({backend:e.backend,defaultPassphrase:e.defaultPassphrase,hardwareBacked:e.hardwareBacked}):new mn}exports.Atom=E,exports.AtomIndexException=Vt,exports.AtomMeta=C,exports.AtomsMissingException=T,exports.AuthToken=ln,exports.AuthorizationRejectedException=mr,exports.BalanceInsufficientException=on,exports.BatchIdException=Qt,exports.CheckMolecule=an,exports.CodeException=B,exports.Decimal=gn,exports.Dot=V,exports.InvalidResponseException=W,exports.KnishIOClient=Li,exports.MemorySecretStorageProvider=mn,exports.MemoryStorageBackend=zi,exports.Meta=x,exports.MetaMissingException=R,exports.MolecularHashMismatchException=Ht,exports.MolecularHashMissingException=Ut,exports.Molecule=cn,exports.Mutation=An,exports.MutationActiveSession=ur,exports.MutationAppendRequest=Jn,exports.MutationClaimShadowWallet=Hn,exports.MutationCreateIdentifier=Bn,exports.MutationCreateMeta=Wn,exports.MutationCreateRule=Er,exports.MutationCreateToken=Pn,exports.MutationCreateWallet=Qn,exports.MutationDepositBufferToken=Dr,exports.MutationLinkIdentifier=Xn,exports.MutationPeering=Kn,exports.MutationProposeMolecule=J,exports.MutationRequestAuthorization=Mn,exports.MutationRequestAuthorizationGuest=er,exports.MutationRequestTokens=In,exports.MutationTransferTokens=Rn,exports.MutationWithdrawBufferToken=Or,exports.NegativeAmountException=sn,exports.PolicyInvalidException=Wt,exports.PolicyMeta=ie,exports.Query=K,exports.QueryActiveSession=fr,exports.QueryAtom=gr,exports.QueryBalance=Tn,exports.QueryBatch=On,exports.QueryBatchHistory=kn,exports.QueryContinuId=yn,exports.QueryEmbeddingStatus=wr,exports.QueryMetaType=Dn,exports.QueryMetaTypeViaAtom=br,exports.QueryMetaTypeViaMolecule=Sr,exports.QueryPolicy=vr,exports.QueryToken=pr,exports.QueryWalletBundle=xn,exports.QueryWalletList=Cn,exports.Response=G,exports.ResponseActiveSession=lr,exports.ResponseAppendRequest=qn,exports.ResponseAtom=hr,exports.ResponseAuthorizationGuest=Ri,exports.ResponseBalance=wn,exports.ResponseClaimShadowWallet=Vn,exports.ResponseContinuId=vn,exports.ResponseCreateIdentifier=zn,exports.ResponseCreateMeta=Un,exports.ResponseCreateRule=Tr,exports.ResponseCreateToken=Nn,exports.ResponseCreateWallet=Zn,exports.ResponseEmbeddingStatus=Cr,exports.ResponseLinkIdentifier=Yn,exports.ResponseMetaType=En,exports.ResponseMetaTypeViaAtom=yr,exports.ResponseMetaTypeViaMolecule=xr,exports.ResponsePeering=Gn,exports.ResponsePolicy=_r,exports.ResponseProposeMolecule=q,exports.ResponseQueryActiveSession=dr,exports.ResponseRequestAuthorization=jn,exports.ResponseRequestAuthorizationGuest=$n,exports.ResponseRequestTokens=Fn,exports.ResponseTransferTokens=Ln,exports.ResponseWalletBundle=bn,exports.ResponseWalletList=Sn,exports.SecretStorageException=H,exports.SignatureMalformedException=Gt,exports.SignatureMismatchException=Kt,exports.StackableUnitAmountException=rr,exports.StackableUnitDecimalsException=nr,exports.TokenUnit=ue,exports.TransferBalanceException=L,exports.TransferMalformedException=qt,exports.TransferMismatchedException=Jt,exports.TransferRemainderException=Yt,exports.TransferToSelfException=Xt,exports.TransferUnbalancedException=Zt,exports.UnauthenticatedException=_n,exports.Wallet=I,exports.WalletShadowException=tr,exports.WebCryptoSecretStorageProvider=Ki,exports.WrongTokenTypeException=z,exports.base64ToHex=y,exports.bufferToHexString=g,exports.charsetBaseConvert=h,exports.chunkArray=te,exports.chunkSubstr=p,exports.constantTimeCompare=pn,exports.createDefaultSecretStorage=qi,exports.deepCloning=ne,exports.diff=re,exports.generateBatchId=le,exports.generateBundleHash=D,exports.generateSecret=se,exports.hexStringToBuffer=_,exports.hexToBase64=v,exports.intersect=S,exports.isHex=b,exports.isNumeric=ee,exports.randomString=m,exports.shake256=ce,exports.withSecureBytes=dn,exports.withSecureString=fn,exports.zeroizeBytes=U;
509
+ `),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS)))return null;let i=t.createProgram();if(!i||(t.attachShader(i,n),t.attachShader(i,r),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)))return null;let a=t.createBuffer();return a?(t.bindBuffer(t.ARRAY_BUFFER,a),t.bufferData(t.ARRAY_BUFFER,hi,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,null),{canvas:e,gl:t,program:i,buffer:a}):null}catch{return null}}function vi(e){let t=new Set;return function e(n){if(n&&n.toJSON&&typeof n.toJSON==`function`&&(n=n.toJSON()),n===void 0)return;if(typeof n==`number`)return isFinite(n)?``+n:`null`;if(typeof n!=`object`)return JSON.stringify(n);let r,i;if(Array.isArray(n)){for(i=`[`,r=0;r<n.length;r++)r&&(i+=`,`),i+=e(n[r])||`null`;return i+`]`}if(n===null)return`null`;if(t.has(n))throw TypeError(`Converting circular structure to JSON`);t.add(n);let a=Object.keys(n).sort();for(i=``,r=0;r<a.length;r++){let t=a[r],o=e(n[t]);o&&(i&&(i+=`,`),i+=JSON.stringify(t)+`:`+o)}return t.delete(n),`{`+i+`}`}(e)||``}var yi={audio:async function(){return Gr?async function(){return new Promise(((e,t)=>{try{let t=new Gr(1,5e3,44100),n=t.createBufferSource(),r=t.createOscillator();r.frequency.value=1e3;let i=t.createDynamicsCompressor(),a;i.threshold.value=-50,i.knee.value=40,i.ratio.value=12,i.attack.value=0,i.release.value=.2,r.connect(i),i.connect(t.destination),r.start(),t.oncomplete=r=>{a=r.renderedBuffer.getChannelData(0),e({sampleHash:Kr(a),maxChannels:t.destination.maxChannelCount,channelCountMode:n.channelCountMode})},t.startRendering()}catch(e){t(e)}}))}():null},canvas:async function(){return new Promise((e=>{let t=Array.from({length:3},(()=>function(){let e=document.createElement(`canvas`),t=e.getContext(`2d`);if(!t)return null;e.width=Xr,e.height=20;let n=t.createLinearGradient(0,0,e.width,e.height);n.addColorStop(0,`red`),n.addColorStop(1/6,`orange`),n.addColorStop(2/6,`yellow`),n.addColorStop(.5,`green`),n.addColorStop(4/6,`blue`),n.addColorStop(5/6,`indigo`),n.addColorStop(1,`violet`),t.fillStyle=n,t.fillRect(0,0,e.width,e.height);let r=`Random Text WMwmil10Oo`;return t.font=`23.123px Arial`,t.fillStyle=`black`,t.fillText(r,-5,15),t.fillStyle=`rgba(0, 0, 255, 0.5)`,t.fillText(r,-3.3,17.7),t.beginPath(),t.moveTo(0,0),t.lineTo(2*e.width/7,e.height),t.strokeStyle=`white`,t.lineWidth=2,t.stroke(),t.getImageData(0,0,e.width,e.height)}())).filter((e=>e!==null));t.length===0?e(null):e({commonPixelsHash:$(qr(t,Xr,20).data.toString()).toString()})}))},fonts:async function(e){return new Promise((e=>{try{(async function(e){for(;!document.body;)await Zr(50);let t=document.createElement(`iframe`);t.setAttribute(`frameBorder`,`0`);let n=t.style;n.setProperty(`position`,`fixed`),n.setProperty(`display`,`block`,`important`),n.setProperty(`visibility`,`visible`),n.setProperty(`border`,`0`),n.setProperty(`opacity`,`0`),t.src=`about:blank`,document.body.appendChild(t);let r=t.contentDocument||t.contentWindow?.document;if(!r)throw Error(`Iframe document is not accessible`);e({iframe:r}),setTimeout((()=>{document.body.removeChild(t)}),0)})((async({iframe:t})=>{let n=t.createElement(`canvas`).getContext(`2d`);if(!n)return void e(null);let r=$r.map((e=>ei(n,e))),i={};Qr.forEach((e=>{let t=ei(n,e);r.includes(t)||(i[e]=t)})),e(i)}))}catch{e(null)}}))},hardware:function(){return new Promise(((e,t)=>{let n=navigator.deviceMemory===void 0?0:navigator.deviceMemory,r=window.performance&&window.performance.memory?window.performance.memory:0;e({videocard:ti(),architecture:ni(),deviceMemory:n.toString()||`undefined`,jsHeapSizeLimit:r.jsHeapSizeLimit||0})}))},locales:function(){return new Promise((e=>{e({languages:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})}))},math:function(){return new Promise((e=>{e({acos:Math.acos(.5),asin:ri(Math.asin,-1,1,97),cos:ri(Math.cos,0,Math.PI,97),largeCos:Math.cos(0x56bc75e2d63100000),largeSin:Math.sin(0x56bc75e2d63100000),largeTan:Math.tan(0x56bc75e2d63100000),sin:ri(Math.sin,-Math.PI,Math.PI,97),tan:ri(Math.tan,0,2*Math.PI,97)})}))},permissions:async function(e){let t=e?.permissions_to_check||ai;return ii(await Promise.all(Array.from({length:3},(()=>async function(e){let t={};for(let n of e)try{t[n]=(await navigator.permissions.query({name:n})).state.toString()}catch{}return t}(t)))),t)},plugins:async function(){let e=[];if(navigator.plugins)for(let t=0;t<navigator.plugins.length;t++){let n=navigator.plugins[t];e.push([n.name,n.filename,n.description].join(`|`))}return new Promise((t=>{t({plugins:e})}))},screen:function(){return new Promise((e=>{if(typeof matchMedia>`u`||typeof screen>`u`)return void e(null);let t={is_touchscreen:navigator.maxTouchPoints>0,maxTouchPoints:navigator.maxTouchPoints,colorDepth:screen.colorDepth,mediaMatches:ui()};li()&&navigator.maxTouchPoints>0&&(t.resolution=function(){let e=window.screen.width,t=window.screen.height;return`${Math.max(e,t).toString()}x${Math.min(e,t).toString()}`}()),e(t)}))},system:function(){return new Promise((e=>{let t=si();e({platform:window.navigator.platform,productSub:navigator.productSub,product:navigator.product,useragent:navigator.userAgent,hardwareConcurrency:navigator.hardwareConcurrency,browser:{name:t.name,version:t.version},mobile:li(),applePayVersion:di(),cookieEnabled:window.navigator.cookieEnabled})}))},webgl:async function(){let e=pi?(gi||=_i(),gi):_i();if(!e)return{webgl:`unsupported`};try{return{commonPixelsHash:$(qr(Array.from({length:fi},(()=>function(e){let{canvas:t,gl:n,program:r,buffer:i}=e;try{n.useProgram(r),n.bindBuffer(n.ARRAY_BUFFER,i);let e=n.getAttribLocation(r,`position`);n.enableVertexAttribArray(e),n.vertexAttribPointer(e,2,n.FLOAT,!1,0,0),n.viewport(0,0,t.width,t.height),n.clearColor(0,0,0,1),n.clear(n.COLOR_BUFFER_BIT),n.drawArrays(n.LINES,0,274);let a=new Uint8ClampedArray(t.width*t.height*4);return n.readPixels(0,0,t.width,t.height,n.RGBA,n.UNSIGNED_BYTE,a),new ImageData(a,t.width,t.height)}catch{return gi=null,new ImageData(1,1)}finally{n.bindBuffer(n.ARRAY_BUFFER,null),n.useProgram(null),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0)}}(e))),e.canvas.width,e.canvas.height).data.toString()).toString()}}catch{return{webgl:`unsupported`}}},webrtc:async function(e){return new Promise((e=>{let t;try{let n=window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection;if(!n)return void e({supported:!1,error:`WebRTC not supported`});t=new n({iceCandidatePoolSize:1,iceServers:[]});let r=t;r.createDataChannel(``),(async()=>{try{let t=await r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});await r.setLocalDescription(t);let n=t.sdp||``,i=[...new Set((n.match(/extmap:\d+ [^\n\r]+/g)||[]).map((e=>e.replace(/extmap:\d+ /,``))))].sort(),a=e=>{let t=n.match(RegExp(`m=${e} [^\\s]+ [^\\s]+ ([^\\n\\r]+)`));return t?t[1].split(` `):[]},o=(e,t)=>t.map((t=>{let r=RegExp(`(rtpmap|fmtp|rtcp-fb):${t} (.+)`,`g`),i=[...n.matchAll(r)];if(!i.length)return null;let a={};return i.forEach((t=>{let[n,r,i]=t,o=i.split(`/`);r===`rtpmap`?(a.mimeType=`${e}/${o[0]}`,a.clockRate=+o[1],e===`audio`&&(a.channels=+o[2]||1)):r===`rtcp-fb`?(a.feedbackSupport=a.feedbackSupport||[],a.feedbackSupport.push(i)):r===`fmtp`&&(a.sdpFmtpLine=i)})),a})).filter(Boolean),s=o(`audio`,a(`audio`)),c=o(`video`,a(`video`)),l={audio:{count:s.length,hash:$(vi(s))},video:{count:c.length,hash:$(vi(c))},extensionsHash:$(vi(i))};r.close();let u={supported:!0,...l,candidateType:`host`};e({details:u,hash:$(vi(u))})}catch(t){r.close(),e({supported:!0,error:`WebRTC offer failed: ${t.message}`})}})()}catch(n){t?.close(),e({supported:!1,error:`WebRTC error: ${n.message}`})}}))},speech:async function(){return new Promise((e=>{try{if(typeof window>`u`||!window.speechSynthesis||typeof window.speechSynthesis.getVoices!=`function`)return void e({supported:!1,error:`Speech Synthesis API not supported`});let t=!1,n=null,r=r=>{if(!t){t=!0,n&&clearTimeout(n);try{let t=r.map((e=>{let t=e=>e.replace(/\\/g,`\\\\`).replace(/,/g,`\\,`);return[t(e.voiceURI||``),t(e.name||``),t(e.lang||``),e.localService?`1`:`0`,e.default?`1`:`0`].join(`,`)}));t.sort();let n={voiceCount:r.length,voicesHash:$(vi(t))};e({details:n,hash:$(vi(n))})}catch(t){e({supported:!0,error:`Voice processing failed: ${t.message}`})}}},i=window.speechSynthesis.getVoices();if(i.length>0)return void r(i);n=setTimeout((()=>{let e=window.speechSynthesis.getVoices();r(e)}),800);let a=()=>{window.speechSynthesis.removeEventListener(`voiceschanged`,a);let e=window.speechSynthesis.getVoices();r(e)};window.speechSynthesis.addEventListener(`voiceschanged`,a)}catch(t){e({supported:!1,error:`Speech Synthesis error: ${t.message}`})}}))}},bi={},xi={timeout:`true`};function Si(e,t){var n;let r=si();if(r.name===`unknown`&&t){let e=t.system?.browser;e!=null&&e.name&&(r={name:String(e.name),version:String(e.version||`unknown`)})}let i=r.name.toLowerCase(),a=parseInt(r.version.split(`.`)[0]||`0`,10),o=Array.isArray(e?.exclude)?[...e.exclude]:[],s=[...new Set([...e?.stabilize||[],`always`])];for(let e of s){let t=Wr[e];if(t)for(let e of t)`browsers`in e&&!((n=e.browsers)!=null&&n.some((e=>{let t=e.match(/(.+?)(>=)(\d+)/);return t?i===t[1]&&a>=+t[3]:i===e})))||o.push(...e.exclude)}return o}function Ci(e,t){let n=Si(t,e),r=Array.isArray(t?.include)?t.include:[];return function e(t,i=``){let a={};for(let[o,s]of Object.entries(t)){let t=i?`${i}.${o}`:o;if(typeof s!=`object`||Array.isArray(s)||s===null){let e=n.some((e=>t.startsWith(e))),i=r.some((e=>t.startsWith(e)));e&&!i||(a[o]=s)}else{let n=e(s,t);Object.keys(n).length>0&&(a[o]=n)}}return a}(e)}var wi=`https://experimental.thumbmarkjs.com/experimental.min.js`,Ti=131072;function Ei(e,t){let n={target:`request`,type:e};return t&&(n.message=t.slice(0,200)),{schema:0,payload_id:`none`,signals:{},errors:[n]}}function Di(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Oi(e){return e instanceof Error?e.message:void 0}async function ki(){try{return await function(e,t){let n,r=new Promise((e=>{n=setTimeout((()=>e(null)),t)}));return Promise.race([e,r]).finally((()=>clearTimeout(n)))}(async function(){let e,t;try{let t=await fetch(wi,{method:`GET`});if(!t.ok)return Ei(`http`,`HTTP ${t.status}`);e=await t.text()}catch(e){return Ei(`fetch`,Oi(e))}if(!e)return Ei(`empty`);if(e.length>Ti)return Ei(`oversized`,`${e.length} chars`);try{let n=eval;t=await Promise.resolve(n(e))}catch(e){return Ei(function(e){return e instanceof SyntaxError?`syntax`:e instanceof EvalError?`eval_blocked`:`threw`}(e),Oi(e))}return function(e){return!!Di(e)&&!(typeof e.schema!=`number`||e.schema<1)&&typeof e.payload_id==`string`&&Di(e.signals)}(t)?{...t,errors:Array.isArray(t.errors)?t.errors:[]}:Ei(`malformed`)}(),2e3)??Ei(`timeout`,`exceeded 2000ms`)}catch(e){return Ei(`threw`,Oi(e))}}var Ai=`visitor_id`;function ji(e){return e.storage_property_name?e.storage_property_name:e.property_name_factory(Ai)}var Mi=`${Br}_${Ai}`;function Ni(e,t){try{localStorage.setItem(ji(t),e)}catch{}}var Pi=`cache`;function Fi(e){try{let t=localStorage.getItem(e.property_name_factory(Pi));return JSON.parse(t)||{}}catch{}return{}}function Ii(e){return e.cache_lifetime_in_ms>zr?Date.now()+zr:Date.now()+e.cache_lifetime_in_ms}var Li=class extends Error{constructor(e){super(`HTTP error! status: ${e}`),this.status=e}},Ri=null,zi=null;async function Bi(e,t,n,r){let i=n.simple_request?{"Content-Type":`text/plain`}:{"x-api-key":n.api_key,Authorization:`custom-authorized`,"Content-Type":`application/json`},a=await fetch(e,{method:`POST`,headers:i,body:JSON.stringify(t)});if(!a.ok)throw new Li(a.status);let o=await a.json();return o.visitorId&&o.visitorId!==r&&Ni(o.visitorId,n),zi=o,function(e,t){e.cache_api_call&&e.cache_lifetime_in_ms&&(function(e,t){let n={...Fi(e),...t};try{localStorage.setItem(e.property_name_factory(Pi),JSON.stringify(n))}catch{}})(e,{apiResponseExpiry:Ii(e),apiResponse:t})}(n,o),o}var Vi=(e,t)=>{if(e.cache_api_call){if(zi)return Promise.resolve(zi);let t=function(e){let t=Fi(e);if(t&&t.apiResponse&&t.apiResponseExpiry&&Date.now()<=t.apiResponseExpiry)return t.apiResponse}(e);if(t)return Promise.resolve(t);if(Ri)return Ri}let n=e.api_endpoint||Vr,r;try{let e=new URL(n);r=e.pathname!==`/`||n.endsWith(`/`)?n:`${e.origin}/thumbmark`}catch{r=`${n}/thumbmark`}let i=function(e){try{let t=ji(e),n=localStorage.getItem(t);return n||t===Mi||(n=localStorage.getItem(Mi),n&&Ni(n,e)),n}catch{return null}}(e),{api_key:a,...o}=e,s={components:t,options:o,clientHash:$(vi(t)),version:`1.11.0`};if(i&&(s.visitorId=i),e.metadata){let t=typeof e.metadata==`function`?e.metadata():e.metadata;t&&((typeof t==`string`?t.length:JSON.stringify(t).length)>1e3?console.error(`ThumbmarkJS: Metadata exceeds 1000 characters. Skipping metadata.`):s.metadata=t)}let c=e.timeout||5e3,l=async function(e,t,n,r){for(let i=0;i<3;i++){i>0&&await new Promise((e=>setTimeout(e,200*i)));try{return await Bi(e,t,n,r)}catch(e){if(e instanceof Li||i===2)throw e}}throw Error(`Unreachable`)}(r,s,e,i).finally((()=>{Ri=null})),u=new Promise((t=>{setTimeout((()=>{t(Fi(e)?.apiResponse||{info:{timed_out:!0},...i&&{visitorId:i}})}),c)}));return Ri=Promise.race([l,u]),Ri};async function Hi(e,t={}){var n;if(typeof document>`u`||typeof window>`u`)return{thumbmark:``,components:{},info:{},version:`1.11.0`,error:[{type:`fatal`,message:`Browser environment required`}]};try{let r={...Hr,...e},i=[],a=r.logging&&!sessionStorage.getItem(`_tmjs_l`)&&Math.random()<1e-4,{elapsed:o,resolvedComponents:s,errors:c,pipelineTimings:l}=await Ui({...yi,...bi,...t},r);i.push(...c);let u=r.api_key||r.simple_request?Vi(r,s):null,d=null;if(u)try{d=await u}catch(e){if(e instanceof Li&&e.status===403)return{error:[{type:`api_unauthorized`,message:`Invalid API key or quota exceeded`}],components:{},info:{},version:`1.11.0`,thumbmark:``};i.push({type:e instanceof Li?`api_error`:`network_error`,message:e instanceof Error?e.message:String(e)})}(n=d?.info)!=null&&n.timed_out&&i.push({type:`api_timeout`,message:`API request timed out`});let f=performance.now(),p=Ci(d?.components||{},r),m=performance.now()-f,h={...s,...p},g=d?.info||{uniqueness:{score:`api only`}},_,v=0,y=0;if(d?.thumbmark)_=d.thumbmark;else{let e=performance.now(),t=vi(h);v=performance.now()-e;let n=performance.now();_=$(t),y=performance.now()-n}a&&async function(e,t,n,r=[]){let i=`${Vr}/log`;sessionStorage.setItem(`_tmjs_l`,`1`);let a={thumbmark:e,components:t,experimental:await ki(),version:`1.11.0`,options:n,path:(window==null?void 0:window.location)?.pathname,...r.length>0&&{errors:r}};try{await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)})}catch{}}(_,h,r,i).catch((()=>{}));let b={"_pipeline.dispatch":l[`_pipeline.dispatch`],"_pipeline.resolve":l[`_pipeline.resolve`],"_pipeline.filter":l[`_pipeline.filter`]+m,"_pipeline.stringify":v,"_pipeline.hash":y,"_pipeline.assembly":0},ee={...o,...l,...b},x=r.performance?{elapsed:ee}:{},te=performance.now(),ne={...d?.visitorId&&{visitorId:d.visitorId},thumbmark:_,components:h,info:g,version:`1.11.0`,...x,...i.length>0&&{error:i},...d?.requestId&&{requestId:d.requestId},...d?.metadata&&{metadata:d.metadata}};return ee[`_pipeline.assembly`]=performance.now()-te,ne}catch(e){return{thumbmark:``,components:{},info:{},version:`1.11.0`,error:[{type:`fatal`,message:e instanceof Error?e.message:String(e)}]}}}async function Ui(e,t){let n={...Hr,...t},r=Si(n).filter((e=>!e.includes(`.`))),i=Object.entries(e).filter((([e])=>!(n?.exclude)?.includes(e))).filter((([e])=>!r.includes(e))).filter((([e])=>(n?.include)?.some((e=>e.includes(`.`)))?(n?.include)?.some((t=>t.startsWith(e))):n?.include?.length===0||(n?.include)?.includes(e))),a=i.map((([e])=>e)),o={},s=performance.now(),c=i.map((([e,n])=>{let r=performance.now(),i=n(t);return o[`_dispatch.${e}`]=performance.now()-r,i})),l=performance.now()-s,u=performance.now(),d=await function(e,t,n){return Promise.all(e.map((e=>{let r=performance.now(),i,a=e.then((e=>(i!==void 0&&clearTimeout(i),{value:e,elapsed:performance.now()-r}))).catch((e=>(i!==void 0&&clearTimeout(i),{value:n,elapsed:performance.now()-r,error:e instanceof Error?e.message:String(e)}))),o=new Promise((e=>{i=setTimeout((()=>{e({value:n,elapsed:performance.now()-r,error:`timeout`})}),t)}));return Promise.race([a,o])})))}(c,n?.timeout||5e3,xi),f=performance.now()-u,p={},m={},h=[];d.forEach(((e,t)=>{let n=a[t];p[n]=e.elapsed??0,e.error===`timeout`?h.push({type:`component_timeout`,message:`Component '${n}' timed out`,component:n}):e.error&&h.push({type:`component_error`,message:e.error,component:n}),e.value!=null&&(m[n]=e.value)}));let g=performance.now();return{elapsed:p,resolvedComponents:Ci(m,n),errors:h,pipelineTimings:{"_pipeline.dispatch":l,"_pipeline.resolve":f,"_pipeline.filter":performance.now()-g,...o}}}async function Wi(){return(await Hi(Ur)).components}async function Gi(e){try{let t=await Hi(Ur);return e?{hash:t.thumbmark.toString(),data:t.components}:t.thumbmark.toString()}catch(e){throw e}}var Ki=`query ( $Hash: String! ) { CipherHash ( Hash: $Hash ) { hash } }`;function qi(e){let t=(e||``).match(/\b(query|mutation|subscription)\b/i),n=t?t[1].toLowerCase():`query`,r=(e||``).indexOf(`{`),i=r>=0?e.slice(r+1).match(/[A-Za-z_][A-Za-z0-9_]*/):null;return{type:n,name:i?i[0]:``}}var Ji=class{constructor({serverUri:e,socket:t=null,encrypt:n=!1}){this.$__client=this.createUrqlClient({serverUri:e,socket:t,encrypt:n}),this.$__authToken=``,this.$__pubkey=null,this.$__wallet=null,this.serverUri=e,this.soketi=t,this.cipherLink=!!n,this.$__subscriptionManager=new Map}createUrqlClient({serverUri:e,socket:t,encrypt:n}){let r=[l.cacheExchange,l.fetchExchange];if(t&&t.socketUri){let e=(0,u.createClient)({url:t.socketUri,connectionParams:()=>({authToken:this.$__authToken})});r.push((0,l.subscriptionExchange)({forwardSubscription:t=>({subscribe:n=>({unsubscribe:e.subscribe(t,n)})})}))}return(0,l.createClient)({url:e,exchanges:r,preferGetMethod:!1,...n?{fetch:(e,t)=>this.cipherFetch(e,t)}:{},fetchOptions:()=>({headers:{"X-Auth-Token":this.$__authToken},signal:AbortSignal.timeout(6e4)})})}shouldEncrypt(e){let t;try{t=JSON.parse(e)}catch{return!1}let{type:n,name:r}=qi(t.query);return!(n===`query`&&(r===`__schema`||r===`ContinuId`)||n===`mutation`&&r===`AccessToken`||n===`mutation`&&r===`ProposeMolecule`&&(t.variables&&t.variables.molecule&&t.variables.molecule.atoms&&t.variables.molecule.atoms[0]&&t.variables.molecule.atoms[0].isotope)===`U`)}async cipherFetch(e,t){let n=this.getWallet(),r=this.getPubKey(),i=!1,a=t;if(n&&r&&t&&typeof t.body==`string`&&this.shouldEncrypt(t.body)){let e=await n.encryptStringML(t.body,r);a={...t,body:JSON.stringify({query:Ki,variables:{Hash:e}})},i=!0}let o=await fetch(e,a);if(!i)return o;let s=await o.text(),c={status:o.status,statusText:o.statusText,headers:o.headers},l;try{l=JSON.parse(s)}catch{return new Response(s,c)}let u=l&&l.data&&l.data.CipherHash&&l.data.CipherHash.hash;if(typeof u!=`string`)return new Response(s,c);let d=await n.decryptMyMessageML(JSON.parse(u));return new Response(d??s,c)}setAuthData({token:e,pubkey:t,wallet:n}){this.$__authToken=e,this.$__pubkey=t,this.$__wallet=n,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}buildRequestOptions(e){if(!e)return;let t={};e.requestPolicy&&(t.requestPolicy=e.requestPolicy);let n=e.fetchOptions&&e.fetchOptions.signal;if(n){let e=typeof AbortSignal<`u`&&typeof AbortSignal.any==`function`?AbortSignal.any([n,AbortSignal.timeout(6e4)]):n;t.fetchOptions={headers:{"X-Auth-Token":this.$__authToken},signal:e}}return Object.keys(t).length?t:void 0}async query(e){let{query:t,variables:n,context:r}=e,i=this.buildRequestOptions(r),a=await this.$__client.query(t,n||{},i).toPromise();return this.formatResponse(a)}async mutate(e){let{mutation:t,variables:n,context:r}=e,i=this.buildRequestOptions(r),a=await this.$__client.mutation(t,n||{},i).toPromise();return this.formatResponse(a)}subscribe(e,t){let{query:n,variables:r,operationName:i}=e,a=(0,d.pipe)(this.$__client.subscription(n,r),(0,d.map)(e=>{t(this.formatResponse(e))}),(0,d.subscribe)(()=>{}));return this.$__subscriptionManager.set(i,a),{unsubscribe:()=>this.unsubscribe(i)}}formatResponse(e){return{data:e.data,errors:e.error?[e.error]:void 0}}socketDisconnect(){this.soketi&&this.unsubscribeAll()}unsubscribe(e){let t=this.$__subscriptionManager.get(e);t&&(t.unsubscribe(),this.$__subscriptionManager.delete(e))}unsubscribeAll(){this.$__subscriptionManager.forEach((e,t)=>{this.unsubscribe(t)})}unsubscribeFromChannel(e){this.unsubscribe(e)}setEncryption(e=!1){this.cipherLink=e,this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:e})}getAuthToken(){return this.$__authToken}getPubKey(){return this.$__pubkey}getWallet(){return this.$__wallet}getServerUri(){return this.serverUri}getSocketUri(){return this.soketi?this.soketi.socketUri:null}getUri(){return this.serverUri}setUri(e){this.serverUri=e,this.$__client=this.createUrqlClient({serverUri:e,socket:this.soketi,encrypt:!!this.cipherLink})}setSocketUri({socketUri:e,appKey:t}){this.soketi={socketUri:e,appKey:t},this.$__client=this.createUrqlClient({serverUri:this.serverUri,socket:this.soketi,encrypt:!!this.cipherLink})}},Yi=class{constructor({uri:e,cellSlug:t=null,client:n=null,socket:r=null,serverSdkVersion:i=3,logging:a=!1,defaultRequestPolicy:o=null,secretStorage:s=null,mlKemParameterSet:c=1024}){this.initialize({uri:e,cellSlug:t,socket:r,client:n,serverSdkVersion:i,logging:a,defaultRequestPolicy:o,secretStorage:s,mlKemParameterSet:c})}initialize({uri:e,cellSlug:t=null,socket:n=null,client:r=null,serverSdkVersion:i=3,logging:a=!1,defaultRequestPolicy:o=null,secretStorage:s=null,mlKemParameterSet:c=1024}){this.reset(),this.$__secretStorage=s,this.$__logging=a,this.$__defaultRequestPolicy=o,this.setMlKemParameterSet(c),this.$__authTokenObjects={},this.$__authInProcess=!1,this.abortControllers=new Map,this.setUri(e),t&&this.setCellSlug(t);for(let e in this.$__uris){let t=this.$__uris[e];this.$__authTokenObjects[t]=null}this.log(`info`,`KnishIOClient::initialize() - Initializing new Knish.IO client session for SDK version ${i}...`),this.$__client=r||new Ji({socket:{socketUri:null,appKey:`knishio`,...n||{}},serverUri:this.getRandomUri()}),this.$__serverSdkVersion=i}getMlKemParameterSet(){return this.$__mlKemParameterSet||1024}setMlKemParameterSet(e){let t=Number(e);if(![1024,768].includes(t))throw Error(`KnishIO: unsupported ML-KEM parameter set ${e}; expected 1024 or 768.`);return this.$__mlKemParameterSet=t,this}getRandomUri(){let e=Math.floor(Math.random()*this.$__uris.length);return this.$__uris[e]}switchEncryption(e){return this.$__encrypt!==e&&(this.log(`info`,`KnishIOClient::switchEncryption() - Forcing encryption ${e?`on`:`off`} to match node...`),this.$__encrypt=e,this.$__client.setEncryption(e),!0)}deinitialize(){this.log(`info`,`KnishIOClient::deinitialize() - Clearing the Knish.IO client session...`),this.reset()}subscribe(){if(!this.client().getSocketUri())throw new L(`KnishIOClient::subscribe() - Socket client not initialized!`);return this.client()}getServerSdkVersion(){return this.$__serverSdkVersion}getDefaultRequestPolicy(){return this.$__defaultRequestPolicy||null}setDefaultRequestPolicy(e){this.$__defaultRequestPolicy=e}reset(){this.$__secret=``,this.$__bundle=``,this.$__secretStorage=null,this.remainderWallet=null,this.$__capabilityCache={},this.$__defaultRequestPolicy=null}getCellSlug(){return this.$__cellSlug||null}setCellSlug(e){this.$__cellSlug=e}setUri(e){if(this.$__uris=typeof e==`object`?e:[e],this.$__client){let e=this.getRandomUri();this.$__client.setUri(e)}}setSocketUri(e){this.$__client&&typeof this.$__client.setSocketUri==`function`&&this.$__client.setSocketUri({socketUri:e,appKey:`knishio`})}getUri(){return this.$__client.getUri()}client(){if(!this.$__authInProcess){let e=this.getRandomUri();this.$__client.setUri(e);let t=this.$__authTokenObjects[e];t?this.$__client.setAuthData(t.getAuthData()):this.requestAuthToken({secret:this.$__secret,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt}).catch(e=>{this.log(`warn`,`KnishIOClient::client() - Background authorization failed: ${e.message}`)})}return this.$__client}hasSecret(){return!!this.$__secret&&this.$__secret.length>0||!!this.$__secretStorage&&!!this.$__bundle&&this.$__bundle.length>0}setSecret(e){if(this.$__secret=e,this.$__bundle=this.hashSecret(e,`setSecret`),this.$__secretStorage)this.$__secretStorage.storeSecret(this.$__bundle,e);else{let t=new wn;t.storeSecret(this.$__bundle,e),this.$__secretStorage=t}}hashSecret(e,t=null){return this.log(`info`,`KnishIOClient::hashSecret(${t?`source: ${t}`:``}) - Computing wallet bundle from secret...`),ce(e)}getSecret(){if(!this.hasSecret())throw new Dn(`KnishIOClient::getSecret() - Unable to find a stored secret! Have you set a secret?`);return this.$__secret}setSecretStorage(e,t=null){this.$__secretStorage=e,t&&(this.$__bundle=t)}getSecretStorage(){return this.$__secretStorage}async retrieveSecret(e={}){return this.$__secret&&this.$__secret.length>0?this.$__secret:this.$__secretStorage&&this.$__bundle&&this.$__bundle.length>0?await this.$__secretStorage.retrieveSecret(this.$__bundle,e):null}hasBundle(){return!!this.$__bundle}getBundle(){if(!this.hasBundle())throw new Dn(`KnishIOClient::getBundle() - Unable to find a stored bundle! Have you set a secret?`);return this.$__bundle}getFingerprint(){return Gi()}getFingerprintData(){return Wi()}async getSourceWallet(){let e=(await this.queryContinuId({bundle:this.getBundle()})).payload();return e?e.key=P.generateKey({secret:this.getSecret(),token:e.token,position:e.position}):e=new P({secret:this.getSecret(),mlKemParameterSet:this.getMlKemParameterSet()}),e}getRemainderWallet(){return this.remainderWallet}async createMolecule({secret:e=null,bundle:t=null,sourceWallet:n=null,remainderWallet:r=null}){this.log(`info`,`KnishIOClient::createMolecule() - Creating a new molecule...`),e||(this.$__secret&&this.$__secret.length>0?e=this.getSecret():this.$__secretStorage&&this.$__bundle&&this.$__bundle.length>0&&(e=await this.$__secretStorage.retrieveSecret(this.$__bundle))),e||=this.getSecret(),t||=this.getBundle();let i=null;if(n&&n.token!==`USER`){if(this.lastMoleculeQuery&&this.getRemainderWallet()&&this.getRemainderWallet().token===`USER`&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success())i=this.getRemainderWallet().position;else{let e=await this.getSourceWallet();i=e?e.position:null}}return!n&&this.lastMoleculeQuery&&this.getRemainderWallet().token===`USER`&&this.lastMoleculeQuery.response()&&this.lastMoleculeQuery.response().success()&&(n=this.getRemainderWallet()),n===null&&(n=await this.getSourceWallet()),this.remainderWallet=r||P.create({secret:e,bundle:t,token:`USER`,batchId:n.batchId,characters:n.characters,mlKemParameterSet:this.getMlKemParameterSet()}),new dn({secret:e,bundle:t,sourceWallet:n,remainderWallet:this.getRemainderWallet(),cellSlug:this.getCellSlug(),version:this.getServerSdkVersion(),continuIdPosition:i,mlKemParameterSet:this.getMlKemParameterSet()})}createQuery(e){return new e(this.client(),this)}createSubscribe(e){return new e(this.subscribe())}async createMoleculeMutation({mutationClass:e,molecule:t=null}){this.log(`info`,`KnishIOClient::createMoleculeQuery() - Creating a new ${e.name} query...`);let n=t||await this.createMolecule({}),r=new e(this.client(),this,n);if(!(r instanceof X))throw new L(`${this.constructor.name}::createMoleculeMutation() - This method only accepts MutationProposeMolecule!`);return this.lastMoleculeQuery=r,r}async executeQuery(e,t=null,n={}){if(this.$__authToken&&this.$__authToken.isExpired()&&!this.$__authInProcess){this.log(`info`,`KnishIOClient::executeQuery() - Access token is expired. Getting new one...`);let e=this.$__secret||await this.retrieveSecret()||``;await this.requestAuthToken({secret:e,cellSlug:this.$__cellSlug,encrypt:this.$__encrypt})}let r=new AbortController,i=JSON.stringify({query:e.$__query,variables:t});this.abortControllers.set(i,r);try{let a={...n};this.$__defaultRequestPolicy&&!a.requestPolicy&&(a.requestPolicy=this.$__defaultRequestPolicy);let o=await e.execute({variables:t,context:{fetchOptions:{signal:r.signal},...a}});return this.abortControllers.delete(i),o}catch(e){if(e.name===`AbortError`)this.log(`warn`,`Query was cancelled`);else throw e}}cancelQuery(e,t=null){let n=JSON.stringify({query:e.$__query,variables:t}),r=this.abortControllers.get(n);r&&(r.abort(),this.abortControllers.delete(n))}cancelAllQueries(){for(let e of this.abortControllers.values())e.abort();this.abortControllers.clear()}async queryBalance({token:e,bundle:t=null,type:n=`regular`}){let r=this.createQuery(Fn);return this.executeQuery(r,{bundleHash:t||this.getBundle(),token:e,type:n})}async querySourceWallet({token:e,amount:t,type:n=`regular`}){let r=(await this.queryBalance({token:e,type:n})).payload();if(r===null||En.cmp(r.balance,t)<0)throw new F;if(!r.position||!r.address)throw new F(`Source wallet can not be a shadow wallet.`);return r}async subscribeCreateMolecule({bundle:e,closure:t}){return await this.createSubscribe(hr).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeWalletStatus({bundle:e,token:t,closure:n}){if(!t)throw new L(`${this.constructor.name}::subscribeWalletStatus() - Token parameter is required!`);return this.createSubscribe(gr).execute({variables:{bundle:e||this.getBundle(),token:t},closure:n})}subscribeActiveWallet({bundle:e,closure:t}){return this.createSubscribe(_r).execute({variables:{bundle:e||this.getBundle()},closure:t})}subscribeActiveSession({metaType:e,metaId:t,closure:n}){return this.createSubscribe(vr).execute({variables:{metaType:e,metaId:t},closure:n})}unsubscribe(e){this.subscribe().unsubscribe(e)}unsubscribeAll(){this.subscribe().unsubscribeAll()}queryMeta({metaType:e,metaId:t=null,key:n=null,value:r=null,latest:i=!0,fields:a=null,filter:o=null,queryArgs:s=null,count:c=null,countBy:l=null,throughAtom:u=!0,throughMolecule:d=!1,values:f=null,keys:p=null,atomValues:m=null,requestPolicy:h=null}){this.log(`info`,`KnishIOClient::queryMeta() - Querying metaType: ${e}, metaId: ${t}...`);let g,_;return d?(g=this.createQuery(Mr),_=Mr.createVariables({metaType:e,metaId:t,key:n,value:r,latest:i,filter:o,queryArgs:s,countBy:l,values:f,keys:p,atomValues:m,cellSlug:this.getCellSlug()})):u?(g=this.createQuery(Ar),_=Ar.createVariables({metaType:e,metaId:t,key:n,value:r,latest:i,filter:o,queryArgs:s,countBy:l,values:f,keys:p,atomValues:m,cellSlug:this.getCellSlug()})):(g=this.createQuery(Ln),_=Ln.createVariables({metaType:e,metaId:t,key:n,value:r,latest:i,filter:o,queryArgs:s,count:c,countBy:l,cellSlug:this.getCellSlug()})),this.executeQuery(g,_,h?{requestPolicy:h}:{})}async queryMetaVerified(e){let t=await this.queryMeta(e),n=t.payload();return n&&(n.integrity=t.verifyIntegrity()),t}async hasQueryField(e){let t=`${this.getUri()}::${e}`;if(typeof this.$__capabilityCache[t]==`boolean`)return this.$__capabilityCache[t];try{let n=((await this.$__client.query({query:`{ __schema { queryType { fields { name } } } }`,variables:{}}))?.data?.__schema?.queryType?.fields||[]).some(t=>t.name===e);return this.$__capabilityCache[t]=n,n}catch(n){return this.log(`warn`,`KnishIOClient::hasQueryField() - Capability probe for '${e}' failed: ${n.message}`),this.$__capabilityCache[t]=!1,!1}}async queryEmbeddingStatus({metaType:e=null,metaId:t=null,instances:n=null}){if(this.log(`info`,`KnishIOClient::queryEmbeddingStatus() - Checking embedding status for metaType: ${e||`(bulk)`}...`),!await this.hasQueryField(`embeddingStatus`))return this.log(`warn`,`KnishIOClient::queryEmbeddingStatus() - Server does not support embeddingStatus query. Returning null.`),null;let r=this.createQuery(Pr),i=Pr.createVariables({metaType:e,metaId:t,instances:n});return this.executeQuery(r,i)}async queryBatch({batchId:e}){this.log(`info`,`KnishIOClient::queryBatch() - Querying cascading meta instances for batchId: ${e}...`);let t=this.createQuery(Rn);return await this.executeQuery(t,{batchId:e})}async queryBatchHistory({batchId:e}){this.log(`info`,`KnishIOClient::queryBatchHistory() - Querying cascading meta instances for batchId: ${e}...`);let t=this.createQuery(zn);return await this.executeQuery(t,{batchId:e})}async queryAtom({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:r,positions:i,position:a,walletAddresses:o,walletAddress:s,isotopes:c,isotope:l,tokenSlugs:u,tokenSlug:d,cellSlugs:f,cellSlug:p,batchIds:m,batchId:h,values:g,value:_,metaTypes:v,metaType:y,metaIds:b,metaId:ee,indexes:x,index:te,filter:ne,latest:re,queryArgs:S={limit:15,offset:1}}){this.log(`info`,`KnishIOClient::queryAtom() - Querying atom instances`);let ie=this.createQuery(Er);return await this.executeQuery(ie,Er.createVariables({molecularHashes:e,molecularHash:t,bundleHashes:n,bundleHash:r,positions:i,position:a,walletAddresses:o,walletAddress:s,isotopes:c,isotope:l,tokenSlugs:u,tokenSlug:d,cellSlugs:f,cellSlug:p,batchIds:m,batchId:h,values:g,value:_,metaTypes:v,metaType:y,metaIds:b,metaId:ee,indexes:x,index:te,filter:ne,latest:re,queryArgs:S}))}async createWallet({token:e}){let t=new P({secret:this.getSecret(),token:e,mlKemParameterSet:this.getMlKemParameterSet()}),n=await this.createMoleculeMutation({mutationClass:cr});return n.fillMolecule(t),await this.executeQuery(n)}async queryActiveSession({bundleHash:e,metaType:t,metaId:n}){let r=this.createQuery(Sr);return await this.executeQuery(r,{bundleHash:e,metaType:t,metaId:n})}async activeSession({bundle:e,metaType:t,metaId:n,ipAddress:r,browser:i,osCpu:a,resolution:o,timeZone:s,json:c={}}){let l=this.createQuery(br);return await this.executeQuery(l,{bundleHash:e,metaType:t,metaId:n,ipAddress:r,browser:i,osCpu:a,resolution:o,timeZone:s,json:JSON.stringify(c)})}async createToken({token:e,amount:t=null,meta:n=null,batchId:r=null,units:i=[]}){let a=R.get(n||{},`fungibility`);if(a===`stackable`&&(n.batchId=r||ue({})),[`nonfungible`,`stackable`].includes(a)&&i.length>0){if(R.get(n||{},`decimals`)>0)throw new fr;if(t>0)throw new pr;t=i.length,n.splittable=1,n.decimals=0,n.tokenUnits=JSON.stringify(i)}let o=new P({secret:this.getSecret(),bundle:this.getBundle(),token:e,batchId:r,mlKemParameterSet:this.getMlKemParameterSet()}),s=await this.createMoleculeMutation({mutationClass:Wn});return s.fillMolecule({recipientWallet:o,amount:t,meta:n||{}}),await this.executeQuery(s)}async createRule({metaType:e,metaId:t,rule:n,policy:r={}}){let i=await this.createMoleculeMutation({mutationClass:Ir,molecule:await this.createMolecule({secret:this.getSecret()})});return i.fillMolecule({metaType:e,metaId:t,rule:n,policy:r}),await this.executeQuery(i)}async createMeta({metaType:e,metaId:t,meta:n=null,policy:r={}}){let i=await this.createMoleculeMutation({mutationClass:er,molecule:await this.createMolecule({secret:this.getSecret()})}),a=n||{};return i.fillMolecule({metaType:e,metaId:t,meta:a,policy:r}),await this.executeQuery(i)}async registerPeer({host:e}){let t=await this.createMoleculeMutation({mutationClass:nr,molecule:await this.createMolecule({secret:this.getSecret()})});return t.fillMolecule({host:e}),await this.executeQuery(t)}async appendRequest({metaType:e,metaId:t,action:n,meta:r={}}){let i=await this.createMoleculeMutation({mutationClass:ir,molecule:await this.createMolecule({secret:this.getSecret()})});return i.fillMolecule({metaType:e,metaId:t,action:n,meta:r}),await this.executeQuery(i)}async createIdentifier({type:e,contact:t,code:n}){let r=await this.createMoleculeMutation({mutationClass:Xn});return r.fillMolecule({type:e,contact:t,code:n}),await this.executeQuery(r)}async linkIdentifier({type:e,contact:t}){let n=this.createQuery(or);return await this.executeQuery(n,{bundle:this.getBundle(),type:e,content:t})}async createPolicy({metaType:e,metaId:t,policy:n={}}){let r=await this.createMolecule({});r.addPolicyAtom({metaType:e,metaId:t,meta:{},policy:n}),r.addContinuIdAtom(),r.sign({bundle:this.getBundle()}),r.check();let i=await this.createMoleculeMutation({mutationClass:X,molecule:r});return await this.executeQuery(i)}async queryPolicy({metaType:e,metaId:t}){let n=this.createQuery(Or);return await this.executeQuery(n,{metaType:e,metaId:t})}queryWallets({bundle:e=null,token:t=null,unspent:n=!0}){this.log(`info`,`KnishIOClient::queryWallets() - Querying wallets${e?` for ${e}`:``}...`);let r=this.createQuery(Nn);return this.executeQuery(r,{bundleHash:e||this.getBundle(),token:t,unspent:n}).then(e=>e.payload())}queryBundle({bundle:e=null,fields:t=null,raw:n=!1}){this.log(`info`,`KnishIOClient::queryBundle() - Querying wallet bundle metadata${e?` for ${e}`:``}...`),e||=this.getBundle(),typeof e==`string`&&(e=[e]);let r=this.createQuery(jn);return this.executeQuery(r,{bundleHashes:e}).then(e=>n?e:e.payload())}async queryContinuId({bundle:e}){let t=this.createQuery(kn);return this.executeQuery(t,{bundle:e})}async requestTokens({token:e,to:t,amount:n=null,units:r=[],meta:i=null,batchId:a=null}){let o,s;i||={};let c=this.createQuery(Cr),l=await this.executeQuery(c,{slug:e}),u=R.get(l.data(),`0.fungibility`)===`stackable`;if(!u&&a!==null)throw new tn(`Expected Batch ID = null for non-stackable tokens.`);if(u&&a===null&&(a=ue({})),r.length>0){if(n>0)throw new pr;n=r.length,i.tokenUnits=JSON.stringify(r)}t?(Object.prototype.toString.call(t)===`[object String]`&&(P.isBundleHash(t)?(o=`walletBundle`,s=t):t=P.create({secret:t,token:e,mlKemParameterSet:this.getMlKemParameterSet()})),t instanceof P&&(o=`wallet`,i.position=t.position,i.bundle=t.bundle,s=t.address)):(o=`walletBundle`,s=this.getBundle());let d=await this.createMoleculeMutation({mutationClass:Kn});return d.fillMolecule({token:e,amount:n,metaType:o,metaId:s,meta:i,batchId:a}),await this.executeQuery(d)}async claimShadowWallet({token:e,batchId:t=null,molecule:n=null}){let r=await this.createMoleculeMutation({mutationClass:Qn,molecule:n});return r.fillMolecule({token:e,batchId:t}),await this.executeQuery(r)}async claimShadowWallets({token:e}){let t=await this.queryWallets({token:e});if(!t||!Array.isArray(t))throw new dr;t.forEach(e=>{if(!e.isShadow())throw new dr});let n=[];for(let r of t)n.push(await this.claimShadowWallet({token:e,batchId:r.batchId}));return n}async transferToken({bundleHash:e,token:t,amount:n=null,units:r=[],batchId:i=null,sourceWallet:a=null}){if(r.length>0){if(n>0)throw new pr;n=r.length}if(a===null&&(a=await this.querySourceWallet({token:t,amount:n})),a===null||En.cmp(a.balance,n)<0)throw new F;let o=P.create({bundle:e,token:t,mlKemParameterSet:this.getMlKemParameterSet()});i===null?o.initBatchId({sourceWallet:a}):o.batchId=i;let s=a.createRemainder(this.getSecret());a.splitUnits(r,s,o);let c=await this.createMolecule({sourceWallet:a,remainderWallet:s}),l=await this.createMoleculeMutation({mutationClass:Jn,molecule:c});return l.fillMolecule({recipientWallet:o,amount:n}),await this.executeQuery(l)}async transferTokens({token:e,recipients:t,sourceWallet:n=null}){let r=t.map(e=>{let t=e.units||[];if(t.length>0){if(e.amount>0)throw new pr;return t.length}return e.amount||0}),i=r.reduce((e,t)=>e+t,0);if(n===null&&(n=await this.querySourceWallet({token:e,amount:i})),n===null||En.cmp(n.balance,i)<0)throw new F;let a=t.map(t=>{let r=P.create({bundle:t.bundleHash,token:e,mlKemParameterSet:this.getMlKemParameterSet()});return t.batchId!==void 0&&t.batchId!==null?r.batchId=t.batchId:r.initBatchId({sourceWallet:n}),r}),o=n.createRemainder(this.getSecret());n.splitUnitsMulti(t.map(e=>e.units||[]),a,o);let s=await this.createMolecule({sourceWallet:n,remainderWallet:o}),c=await this.createMoleculeMutation({mutationClass:Jn,molecule:s});return c.fillMoleculeMulti({recipientWallets:a,amounts:r}),await this.executeQuery(c)}async depositBufferToken({tokenSlug:e,amount:t,tradeRates:n,sourceWallet:r=null}){r===null&&(r=await this.querySourceWallet({token:e,amount:t}));let i=r.createRemainder(this.getSecret()),a=await this.createMolecule({sourceWallet:r,remainderWallet:i}),o=await this.createMoleculeMutation({mutationClass:Lr,molecule:a});return o.fillMolecule({amount:t,tradeRates:n}),await this.executeQuery(o)}async withdrawBufferToken({tokenSlug:e,amount:t,sourceWallet:n=null,signingWallet:r=null}){n===null&&(n=await this.querySourceWallet({token:e,amount:t,type:`buffer`}));let i=n,a=await this.createMolecule({sourceWallet:n,remainderWallet:i}),o=await this.createMoleculeMutation({mutationClass:Rr,molecule:a}),s={};return s[this.getBundle()]=t,o.fillMolecule({recipients:s,signingWallet:r}),await this.executeQuery(o)}async burnTokens({token:e,amount:t=null,units:n=[],sourceWallet:r=null}){r===null&&(r=await this.querySourceWallet({token:e,amount:t}));let i=r.createRemainder(this.getSecret());if(n.length>0){if(t>0)throw new pr;t=n.length,r.splitUnits(n,i)}let a=await this.createMolecule({sourceWallet:r,remainderWallet:i});a.burnToken({amount:t}),a.sign({bundle:this.getBundle()}),a.check(r);let o=await this.createMoleculeMutation({mutationClass:X,molecule:a});return this.executeQuery(o)}async replenishToken({token:e,amount:t=null,units:n=[],sourceWallet:r=null}){if(r===null&&(r=(await this.queryBalance({token:e})).payload()),!r)throw new F(`Source wallet is missing or invalid.`);let i=r.createRemainder(this.getSecret()),a=await this.createMolecule({sourceWallet:r,remainderWallet:i});a.replenishToken({amount:t,units:n}),a.sign({bundle:this.getBundle()}),a.check();let o=await this.createMoleculeMutation({mutationClass:X,molecule:a});return this.executeQuery(o)}async fuseToken({bundleHash:e,tokenSlug:t,newTokenUnit:n,fusedTokenUnitIds:r,sourceWallet:i=null}){if(i===null&&(i=(await this.queryBalance({token:t})).payload()),i===null)throw new F(`Source wallet is missing or invalid.`);if(!i.tokenUnits||!i.tokenUnits.length)throw new F(`Source wallet does not have token units.`);if(!r.length)throw new F(`Fused token unit list is empty.`);let a=[];i.tokenUnits.forEach(e=>{a.push(e.id)}),r.forEach(e=>{if(!a.includes(e))throw new F(`Fused token unit ID = ${e} does not found in the source wallet.`)});let o=P.create({bundle:e,token:t,mlKemParameterSet:this.getMlKemParameterSet()});o.initBatchId({sourceWallet:i});let s=i.createRemainder(this.getSecret());i.splitUnits(r,s),typeof n==`string`&&(n=new de(n,n,{})),n.metas.fusedTokenUnits=i.getTokenUnitsData(),o.tokenUnits=[n];let c=await this.createMolecule({sourceWallet:i,remainderWallet:s});c.fuseToken(i.tokenUnits,o),c.sign({bundle:this.getBundle()}),c.check();let l=await this.createMoleculeMutation({mutationClass:X,molecule:c});return this.executeQuery(l)}async requestGuestAuthToken({cellSlug:e,encrypt:t}){this.setCellSlug(e);let n=new P({secret:se(await this.getFingerprint()),token:`AUTH`,mlKemParameterSet:this.getMlKemParameterSet()}),r=await this.createQuery(ur),i={cellSlug:e,pubkey:n.pubkey,encrypt:t},a=await r.execute({variables:i});if(a.success()){let e=fn.create({token:a.token(),expiresAt:a.expiresAt(),pubkey:a.pubKey(),encrypt:a.encrypt()},n);this.setAuthToken(e)}else throw new wr(`KnishIOClient::requestGuestAuthToken() - Authorization attempt rejected by ledger. Reason: ${a.reason()}`);return a}async requestProfileAuthToken({secret:e,encrypt:t}){this.setSecret(e);let n=new P({secret:e,token:`AUTH`,mlKemParameterSet:this.getMlKemParameterSet()}),r=await this.createMolecule({secret:e,sourceWallet:n}),i=await this.createMoleculeMutation({mutationClass:Hn,molecule:r}),a={encrypt:t?`true`:`false`};n.pubkey&&(a.walletPubkey=n.pubkey),i.fillMolecule({meta:a});let o=await i.execute({});if(o.success()){let e=fn.create({token:o.token(),expiresAt:o.expiresAt(),pubkey:o.pubKey(),encrypt:o.encrypt()},n);this.setAuthToken(e)}else throw new wr(`KnishIOClient::requestProfileAuthToken() - Authorization attempt rejected by ledger. Reason: ${o.reason()}`);return o}async requestAuthToken({secret:e=null,seed:t=null,cellSlug:n=null,encrypt:r=!1}){if(this.$__serverSdkVersion<3)return this.log(`warn`,`KnishIOClient::authorize() - Server SDK version does not require an authorization...`),null;e===null&&t&&(e=se(t)),n&&this.setCellSlug(n),e===null&&this.$__secretStorage&&this.$__bundle&&(e=await this.$__secretStorage.retrieveSecret(this.$__bundle)),this.$__authInProcess=!0;let i;return i=e?await this.requestProfileAuthToken({secret:e,encrypt:r}):await this.requestGuestAuthToken({cellSlug:n,encrypt:r}),this.log(`info`,`KnishIOClient::authorize() - Successfully retrieved auth token ${this.$__authToken.getToken()}...`),this.switchEncryption(r),this.$__authInProcess=!1,i}setAuthToken(e){if(!e){this.log(`info`,`KnishIOClient::setAuthToken() - authToken object is empty.`);return}this.$__authTokenObjects[this.getUri()]=e,this.client().setAuthData(e.getAuthData()),this.$__authToken=e}getAuthToken(){return this.$__authToken}log(e,t){if(this.$__logging)switch(e){case`info`:console.info(t);break;case`warn`:console.warn(t);break;case`error`:console.error(t);break;default:console.log(t)}}},Xi=class extends q{constructor({query:e,json:t}){super({query:e,json:t,dataKey:`data.AccessToken`})}reason(){return`Invalid response from server`}success(){return this.payload()!==null}payload(){return this.data()}payloadKey(e){if(!R.has(this.payload(),e))throw new K(`ResponseAuthorizationGuest::payloadKey() - '${e}' key is not found in the payload!`);return R.get(this.payload(),e)}token(){return this.payloadKey(`token`)}time(){return this.payloadKey(`time`)}},Zi=class{constructor(){this.store=new Map}getItem(e){return this.store.get(e)??null}setItem(e,t){this.store.set(e,t)}removeItem(e){return this.store.delete(e)}keys(){return Array.from(this.store.keys())}},Qi=new TextDecoder,$i=yn,ea=class{constructor(e={}){this.providerType=`webcrypto-aes-gcm`,this.backend=e.backend||new Zi,this.defaultPassphrase=e.defaultPassphrase}isHardwareBacked(){return!1}async isAvailable(){return globalThis.crypto!==void 0&&globalThis.crypto.subtle!==void 0}async deriveKey(e,t,n=vn){if(!await this.isAvailable())throw z.unavailable(this.providerType,`WebCrypto API is not available`);return await Cn(e,t,n)}async storeSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Secret cannot be empty`);let r=n.passphrase||this.defaultPassphrase;if(!r)throw new z(`Passphrase required for envelope encryption`);if(!await this.isAvailable())throw z.unavailable(this.providerType,`WebCrypto API is not available`);try{let i=await W(t,r,{bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:this.providerType});if(await this.backend.setItem(`${$i}${e}`,JSON.stringify(i)),n.recoveryPassphrase){let r={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:`webcrypto-aes-gcm`},i=await W(t,n.recoveryPassphrase,r);await this.backend.setItem(`${V}${e}`,JSON.stringify(i))}}catch(e){throw e instanceof z?e:new z(`Encryption failed: ${e instanceof Error?e.message:String(e)}`)}}async retrieveSecret(e,t={}){let n=await this.backend.getItem(`${$i}${e}`);if(!n)return null;let r;try{r=JSON.parse(n)}catch{throw z.decryptionFailed(`Corrupted payload format`)}let i=t.passphrase||this.defaultPassphrase;if(!i)throw new z(`Passphrase required for secret decryption`);if(!await this.isAvailable())throw z.unavailable(this.providerType,`WebCrypto API is not available`);try{let e=await G(r,i);try{return Qi.decode(e)}finally{B(e)}}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}}async deleteSecret(e){let t=`${$i}${e}`,n=`${V}${e}`,r=await this.backend.removeItem(t);return await this.backend.removeItem(n),r!==!1}async hasSecret(e){return await this.backend.getItem(`${$i}${e}`)!==null}async listSecrets(){let e=(await this.backend.keys()).filter(e=>e.startsWith($i)&&!e.startsWith(`knishio:recovery:`)),t=[];for(let n of e){let e=await this.backend.getItem(n);if(e)try{let n=JSON.parse(e);n.metadata&&t.push(n.metadata)}catch{}}return t}async withSecret(e,t,n={}){let r=await this.backend.getItem(`${$i}${e}`);if(!r)throw z.notFound(e);let i;try{i=JSON.parse(r)}catch{throw z.decryptionFailed(`Corrupted payload format`)}let a=n.passphrase||this.defaultPassphrase;if(!a)throw new z(`Passphrase required for secret decryption`);if(!await this.isAvailable())throw z.unavailable(this.providerType,`WebCrypto API is not available`);try{return await mn(await G(i,a),async e=>await t(Qi.decode(e)))}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}}async recoverSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Recovery passphrase cannot be empty`);let r=await this.backend.getItem(`${V}${e}`);if(!r)throw z.notFound(e);let i;try{i=JSON.parse(r)}catch{throw z.decryptionFailed(`Corrupted recovery payload format`)}let a;try{a=await G(i,t)}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}let o;try{o=Qi.decode(a)}finally{B(a)}let s=n.passphrase||this.defaultPassphrase||t;await this.storeSecret(e,o,{...n,passphrase:s,recoveryPassphrase:t})}},ta=class{constructor(e){if(!e)throw new z(`Storage file path cannot be empty`);this.filePath=e,this.store=new Map,this.loaded=!1}async getFs(){try{return{fs:await import(`node:fs/promises`),path:await import(`node:path`)}}catch{throw z.unavailable(`file-storage`,`FileStorageBackend is only supported in Node.js environments with node:fs access`)}}async ensureLoaded(){if(this.loaded)return this.store;let{fs:e}=await this.getFs();try{let t=await e.readFile(this.filePath,`utf8`),n;try{n=JSON.parse(t)}catch{throw z.decryptionFailed(`Corrupted storage file format`)}n&&typeof n==`object`&&(this.store=new Map(Object.entries(n).map(([e,t])=>[e,String(t)])))}catch(e){if(e instanceof z)throw e;if(e?.code!==`ENOENT`)throw new z(`Failed to read storage file: ${e instanceof Error?e.message:String(e)}`);this.store=new Map}return this.loaded=!0,this.store}async persist(){let{fs:e,path:t}=await this.getFs(),n=t.dirname(this.filePath);n&&n!==`.`&&await e.mkdir(n,{recursive:!0});let r=`${this.filePath}.tmp.${Date.now()}_${Math.random().toString(36).slice(2)}`,i=JSON.stringify(Object.fromEntries(this.store),null,2);try{if(await e.writeFile(r,i,{mode:384,encoding:`utf8`}),typeof process<`u`&&process.platform!==`win32`)try{await e.chmod(r,384)}catch{}await e.rename(r,this.filePath)}catch(t){try{await e.unlink(r)}catch{}throw new z(`Failed to persist storage file: ${t instanceof Error?t.message:String(t)}`)}}async getItem(e){return await this.ensureLoaded(),this.store.get(e)??null}async setItem(e,t){await this.ensureLoaded(),this.store.set(e,t),await this.persist()}async removeItem(e){await this.ensureLoaded();let t=this.store.delete(e);return t&&await this.persist(),t}async keys(){return await this.ensureLoaded(),Array.from(this.store.keys())}},na=class{constructor(e,t=`knishio:`){if(e)this.storage=e;else if(typeof globalThis<`u`&&globalThis.localStorage)this.storage=globalThis.localStorage;else throw z.unavailable(`web-storage`,`WebStorageBackend requires a Storage object or global localStorage`);this.prefix=t}getItem(e){return this.storage.getItem(e)}setItem(e,t){this.storage.setItem(e,t)}removeItem(e){let t=this.storage.getItem(e)!==null;return this.storage.removeItem(e),t}keys(){let e=[],t=this.storage.length;for(let n=0;n<t;n++){let t=this.storage.key(n);t!==null&&(!this.prefix||t.startsWith(this.prefix))&&e.push(t)}return e}},ra=`knishio:secret-storage:webauthn-prf:v1`,ia=`knishio:secret-storage:kek:v1`,aa=yn,oa=12,sa=new TextEncoder,ca=new TextDecoder;function la(e){return H(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function ua(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);for(;t.length%4!=0;)t+=`=`;return U(t)}function da(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}async function fa(){let e=await globalThis.crypto.subtle.digest(`SHA-256`,sa.encode(ra));return new Uint8Array(e)}async function pa(e,t){let n=await globalThis.crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await globalThis.crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:t,info:sa.encode(ia)},n,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}var ma=class{constructor(e){this.providerType=`webauthn-prf`,this.backend=e.backend,this.rp=e.rp,this.user=e.user,this.credentialsContainer=e.credentials,this.alias=e.alias||`default`,this.cachedPassphrase=void 0}get credentials(){if(this.credentialsContainer)return this.credentialsContainer;if(globalThis.navigator!==void 0&&globalThis.navigator.credentials)return globalThis.navigator.credentials;throw z.unavailable(this.providerType,`WebAuthn credentials container is not available`)}get recordKey(){return`knishio:webauthn-prf:${this.alias}`}isHardwareBacked(){return!1}async isAvailable(){let e=globalThis.crypto!==void 0&&globalThis.crypto.subtle!==void 0,t=!!(this.credentialsContainer||globalThis.navigator!==void 0&&globalThis.navigator.credentials&&globalThis.PublicKeyCredential!==void 0);return e&&t}async enroll(){if(await this.backend.getItem(this.recordKey))return;if(!await this.isAvailable())throw z.unavailable(this.providerType,`WebAuthn PRF is not available`);let e=new Uint8Array(32);globalThis.crypto.getRandomValues(e);let t=await this.credentials.create({publicKey:{rp:this.rp,user:{id:this.user.id,name:this.user.name,displayName:this.user.displayName},challenge:e,pubKeyCredParams:[{type:`public-key`,alg:-7},{type:`public-key`,alg:-257}],authenticatorSelection:{residentKey:`required`,userVerification:`required`},extensions:{prf:{}}}});if(!t)throw z.unavailable(this.providerType,`Authenticator creation returned null`);if((t.getClientExtensionResults?.())?.prf?.enabled!==!0)throw z.unavailable(this.providerType,`authenticator does not support the PRF extension`);let n=new Uint8Array(t.rawId),r=await fa(),i=new Uint8Array(32);globalThis.crypto.getRandomValues(i);let a;try{a=await this.credentials.get({publicKey:{challenge:i,rpId:this.rp.id,allowCredentials:[{type:`public-key`,id:n}],userVerification:`required`,extensions:{prf:{eval:{first:r}}}}})}catch(e){throw e?.name===`NotAllowedError`?z.unavailable(this.providerType,`authenticator refused or credential missing`):e}if(!a)throw z.unavailable(this.providerType,`authenticator refused or credential missing`);let o=(a?.getClientExtensionResults?.())?.prf?.results?.first;if(!o)throw z.unavailable(this.providerType,`authenticator returned no PRF result`);let s=await pa(da(o),r),c=new Uint8Array(32);globalThis.crypto.getRandomValues(c);let l=H(c),u=new Uint8Array(oa);globalThis.crypto.getRandomValues(u);let d=sa.encode(l);try{let e=await globalThis.crypto.subtle.encrypt({name:`AES-GCM`,iv:u},s,d),t={version:1,credentialId:la(n),iv:H(u),ciphertext:H(new Uint8Array(e))};await this.backend.setItem(this.recordKey,JSON.stringify(t)),this.cachedPassphrase=l}finally{B(d),B(c)}}async unlock(){if(this.cachedPassphrase)return this.cachedPassphrase;let e=await this.backend.getItem(this.recordKey);if(!e)throw z.unavailable(this.providerType,`no enrolled credential; call enroll() first`);let t;try{t=JSON.parse(e)}catch{throw z.decryptionFailed(`Corrupted PRF record format`)}let n=ua(t.credentialId),r=await fa(),i=new Uint8Array(32);globalThis.crypto.getRandomValues(i);let a;try{a=await this.credentials.get({publicKey:{challenge:i,rpId:this.rp.id,allowCredentials:[{type:`public-key`,id:n}],userVerification:`required`,extensions:{prf:{eval:{first:r}}}}})}catch(e){throw e?.name===`NotAllowedError`?z.unavailable(this.providerType,`authenticator refused or credential missing`):e}if(!a)throw z.unavailable(this.providerType,`authenticator refused or credential missing`);let o=(a?.getClientExtensionResults?.())?.prf?.results?.first;if(!o)throw z.unavailable(this.providerType,`authenticator returned no PRF result`);let s=await pa(da(o),r),c=U(t.iv),l=U(t.ciphertext);try{let e=await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:c},s,l),t=new Uint8Array(e);try{return this.cachedPassphrase=ca.decode(t),this.cachedPassphrase}finally{B(t)}}catch{throw z.decryptionFailed(`wrapped device passphrase failed authentication under the enrolled credential`)}}lock(){this.cachedPassphrase=void 0}async unenroll(){this.lock(),await this.backend.removeItem(this.recordKey)}async storeSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Secret cannot be empty`);if(n.passphrase)throw new z(`WebAuthnPrfSecretStorageProvider derives its passphrase from the authenticator; options.passphrase is not accepted`);if(!n.recoveryPassphrase&&!n.allowUnrecoverable)throw z.validationError(`Recovery passphrase required for non-exportable hardware key unless allowUnrecoverable is true`);let r=await W(t,await this.unlock(),{bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:this.providerType});if(await this.backend.setItem(`${aa}${e}`,JSON.stringify(r)),n.recoveryPassphrase){let r={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:`webcrypto-aes-gcm`},i=await W(t,n.recoveryPassphrase,r);await this.backend.setItem(`${V}${e}`,JSON.stringify(i))}}async retrieveSecret(e,t={}){if(t.passphrase)throw new z(`WebAuthnPrfSecretStorageProvider derives its passphrase from the authenticator; options.passphrase is not accepted`);let n=await this.backend.getItem(`${aa}${e}`);if(!n)return null;let r;try{r=JSON.parse(n)}catch{throw z.decryptionFailed(`Corrupted payload format`)}let i=await this.unlock();try{let e=await G(r,i);try{return ca.decode(e)}finally{B(e)}}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}}async withSecret(e,t,n={}){if(n.passphrase)throw new z(`WebAuthnPrfSecretStorageProvider derives its passphrase from the authenticator; options.passphrase is not accepted`);let r=await this.backend.getItem(`${aa}${e}`);if(!r)throw z.notFound(e);let i;try{i=JSON.parse(r)}catch{throw z.decryptionFailed(`Corrupted payload format`)}let a=await this.unlock();try{return await mn(await G(i,a),async e=>await t(ca.decode(e)))}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}}async deleteSecret(e){let t=`${aa}${e}`,n=`${V}${e}`,r=await this.backend.removeItem(t);return await this.backend.removeItem(n),r!==!1}async hasSecret(e){return await this.backend.getItem(`${aa}${e}`)!==null}async listSecrets(){let e=(await this.backend.keys()).filter(e=>e.startsWith(aa)&&!e.startsWith(`knishio:recovery:`)),t=[];for(let n of e){let e=await this.backend.getItem(n);if(e)try{let n=JSON.parse(e);n.metadata&&t.push(n.metadata)}catch{}}return t}async recoverSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Recovery passphrase cannot be empty`);let r=await this.backend.getItem(`${V}${e}`);if(!r)throw z.notFound(e);let i;try{i=JSON.parse(r)}catch{throw z.decryptionFailed(`Corrupted recovery payload format`)}let a;try{a=await G(i,t)}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}let o;try{o=ca.decode(a)}finally{B(a)}await this.storeSecret(e,o,{...n,recoveryPassphrase:t})}},ha=yn,ga=12,_a=new TextEncoder,va=new TextDecoder,ya=class{constructor(){this.keys=new Map}async get(e){return this.keys.get(e)}async put(e,t){this.keys.set(e,t)}async delete(e){return this.keys.delete(e)}},ba=class{constructor(e=`knishio-secret-storage`){this.dbName=e,this.storeName=`keys`}async getDb(){if(globalThis.indexedDB===void 0)throw z.unavailable(`webcrypto-nonextractable`,`IndexedDB is not available`);return new Promise((e,t)=>{let n=globalThis.indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)})}async get(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(this.storeName,`readonly`).objectStore(this.storeName).get(e);i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error)})}async put(e,t){let n=await this.getDb();return new Promise((r,i)=>{let a=n.transaction(this.storeName,`readwrite`).objectStore(this.storeName).put(t,e);a.onsuccess=()=>r(),a.onerror=()=>i(a.error)})}async delete(e){let t=await this.getDb();return new Promise((n,r)=>{let i=t.transaction(this.storeName,`readwrite`).objectStore(this.storeName).delete(e);i.onsuccess=()=>n(!0),i.onerror=()=>r(i.error)})}},xa=class{constructor(e){this.providerType=`webcrypto-nonextractable`,this.backend=e.backend,this.keyStore=e.keyStore||new ba,this.alias=e.alias||`default`,this.cachedPassphrase=void 0}get recordKey(){return`knishio:kek:webcrypto-nonextractable:${this.alias}`}get kekStoreKey(){return`knishio:kek:${this.alias}`}isHardwareBacked(){return!1}async isAvailable(){return globalThis.crypto!==void 0&&globalThis.crypto.subtle!==void 0}async unlock(){if(this.cachedPassphrase)return this.cachedPassphrase;if(!await this.isAvailable())throw z.unavailable(this.providerType,`WebCrypto API is not available`);let e=await this.backend.getItem(this.recordKey);if(!e){let e=await this.keyStore.get(this.kekStoreKey);e||(e=await globalThis.crypto.subtle.generateKey({name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]),await this.keyStore.put(this.kekStoreKey,e));let t=new Uint8Array(32);globalThis.crypto.getRandomValues(t);let n=H(t),r=new Uint8Array(ga);globalThis.crypto.getRandomValues(r);let i=_a.encode(n);try{let t=await globalThis.crypto.subtle.encrypt({name:`AES-GCM`,iv:r},e,i),a={version:1,iv:H(r),ciphertext:H(new Uint8Array(t))};return await this.backend.setItem(this.recordKey,JSON.stringify(a)),this.cachedPassphrase=n,n}finally{B(i),B(t)}}let t;try{t=JSON.parse(e)}catch{throw z.decryptionFailed(`Corrupted key record format`)}let n=await this.keyStore.get(this.kekStoreKey);if(!n)throw z.unavailable(this.providerType,`no non-extractable key found for alias '${this.alias}'`);let r=U(t.iv),i=U(t.ciphertext);try{let e=await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:r},n,i),t=new Uint8Array(e);try{return this.cachedPassphrase=va.decode(t),this.cachedPassphrase}finally{B(t)}}catch{throw z.decryptionFailed(`wrapped device passphrase failed authentication under non-extractable key`)}}lock(){this.cachedPassphrase=void 0}async unenroll(){this.lock(),await this.backend.removeItem(this.recordKey),await this.keyStore.delete(this.kekStoreKey)}async storeSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Secret cannot be empty`);if(n.passphrase)throw new z(`NonExtractableKeySecretStorageProvider derives its passphrase from the non-extractable device key; options.passphrase is not accepted`);if(!n.recoveryPassphrase&&!n.allowUnrecoverable)throw z.validationError(`Recovery passphrase required for non-exportable hardware key unless allowUnrecoverable is true`);let r=await W(t,await this.unlock(),{bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:this.providerType});if(await this.backend.setItem(`${ha}${e}`,JSON.stringify(r)),n.recoveryPassphrase){let r={bundleHash:e,label:n.label,createdAt:Date.now(),hardwareBacked:!1,providerType:`webcrypto-aes-gcm`},i=await W(t,n.recoveryPassphrase,r);await this.backend.setItem(`${V}${e}`,JSON.stringify(i))}}async retrieveSecret(e,t={}){if(t.passphrase)throw new z(`NonExtractableKeySecretStorageProvider derives its passphrase from the non-extractable device key; options.passphrase is not accepted`);let n=await this.backend.getItem(`${ha}${e}`);if(!n)return null;let r;try{r=JSON.parse(n)}catch{throw z.decryptionFailed(`Corrupted payload format`)}let i=await this.unlock();try{let e=await G(r,i);try{return va.decode(e)}finally{B(e)}}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}}async withSecret(e,t,n={}){if(n.passphrase)throw new z(`NonExtractableKeySecretStorageProvider derives its passphrase from the non-extractable device key; options.passphrase is not accepted`);let r=await this.backend.getItem(`${ha}${e}`);if(!r)throw z.notFound(e);let i;try{i=JSON.parse(r)}catch{throw z.decryptionFailed(`Corrupted payload format`)}let a=await this.unlock();try{return await mn(await G(i,a),async e=>await t(va.decode(e)))}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}}async deleteSecret(e){let t=`${ha}${e}`,n=`${V}${e}`,r=await this.backend.removeItem(t);return await this.backend.removeItem(n),r!==!1}async hasSecret(e){return await this.backend.getItem(`${ha}${e}`)!==null}async listSecrets(){let e=(await this.backend.keys()).filter(e=>e.startsWith(ha)&&!e.startsWith(`knishio:recovery:`)),t=[];for(let n of e){let e=await this.backend.getItem(n);if(e)try{let n=JSON.parse(e);n.metadata&&t.push(n.metadata)}catch{}}return t}async recoverSecret(e,t,n={}){if(!e)throw new z(`Bundle hash cannot be empty`);if(!t)throw new z(`Recovery passphrase cannot be empty`);let r=await this.backend.getItem(`${V}${e}`);if(!r)throw z.notFound(e);let i;try{i=JSON.parse(r)}catch{throw z.decryptionFailed(`Corrupted recovery payload format`)}let a;try{a=await G(i,t)}catch(e){if(e instanceof z)throw e;let t=e instanceof Error?e.message:String(e);throw z.decryptionFailed(t)}let o;try{o=va.decode(a)}finally{B(a)}await this.storeSecret(e,o,{...n,recoveryPassphrase:t})}};function Sa(e={}){return e.type===`memory`?new wn:globalThis.crypto!==void 0&&globalThis.crypto.subtle!==void 0?new ea({backend:e.backend,defaultPassphrase:e.defaultPassphrase}):new wn}exports.Atom=E,exports.AtomIndexException=Ut,exports.AtomMeta=C,exports.AtomsMissingException=T,exports.AuthToken=fn,exports.AuthorizationRejectedException=wr,exports.BalanceInsufficientException=ln,exports.BatchIdException=tn,exports.CheckMolecule=cn,exports.CodeException=L,exports.Decimal=En,exports.Dot=R,exports.FileStorageBackend=ta,exports.IndexedDbKeyStore=ba,exports.InvalidResponseException=K,exports.KnishIOClient=Yi,exports.MemoryKeyStore=ya,exports.MemorySecretStorageProvider=wn,exports.MemoryStorageBackend=Zi,exports.Meta=x,exports.MetaMissingException=I,exports.MolecularHashMismatchException=Wt,exports.MolecularHashMissingException=Gt,exports.Molecule=dn,exports.Mutation=Bn,exports.MutationActiveSession=br,exports.MutationAppendRequest=ir,exports.MutationClaimShadowWallet=Qn,exports.MutationCreateIdentifier=Xn,exports.MutationCreateMeta=er,exports.MutationCreateRule=Ir,exports.MutationCreateToken=Wn,exports.MutationCreateWallet=cr,exports.MutationDepositBufferToken=Lr,exports.MutationLinkIdentifier=or,exports.MutationPeering=nr,exports.MutationProposeMolecule=X,exports.MutationRequestAuthorization=Hn,exports.MutationRequestAuthorizationGuest=ur,exports.MutationRequestTokens=Kn,exports.MutationTransferTokens=Jn,exports.MutationWithdrawBufferToken=Rr,exports.NegativeAmountException=un,exports.NonExtractableKeySecretStorageProvider=xa,exports.PolicyInvalidException=Kt,exports.PolicyMeta=ie,exports.Query=J,exports.QueryActiveSession=Sr,exports.QueryAtom=Er,exports.QueryBalance=Fn,exports.QueryBatch=Rn,exports.QueryBatchHistory=zn,exports.QueryContinuId=kn,exports.QueryEmbeddingStatus=Pr,exports.QueryMetaType=Ln,exports.QueryMetaTypeViaAtom=Ar,exports.QueryMetaTypeViaMolecule=Mr,exports.QueryPolicy=Or,exports.QueryToken=Cr,exports.QueryWalletBundle=jn,exports.QueryWalletList=Nn,exports.RECOVERY_KEY_PREFIX=V,exports.Response=q,exports.ResponseActiveSession=yr,exports.ResponseAppendRequest=rr,exports.ResponseAtom=Tr,exports.ResponseAuthorizationGuest=Xi,exports.ResponseBalance=Pn,exports.ResponseClaimShadowWallet=Zn,exports.ResponseContinuId=On,exports.ResponseCreateIdentifier=Yn,exports.ResponseCreateMeta=$n,exports.ResponseCreateRule=Fr,exports.ResponseCreateToken=Un,exports.ResponseCreateWallet=sr,exports.ResponseEmbeddingStatus=Nr,exports.ResponseLinkIdentifier=ar,exports.ResponseMetaType=In,exports.ResponseMetaTypeViaAtom=kr,exports.ResponseMetaTypeViaMolecule=jr,exports.ResponsePeering=tr,exports.ResponsePolicy=Dr,exports.ResponseProposeMolecule=Y,exports.ResponseQueryActiveSession=xr,exports.ResponseRequestAuthorization=Vn,exports.ResponseRequestAuthorizationGuest=lr,exports.ResponseRequestTokens=Gn,exports.ResponseTransferTokens=qn,exports.ResponseWalletBundle=An,exports.ResponseWalletList=Mn,exports.SECRET_KEY_PREFIX=yn,exports.SecretStorageException=z,exports.SignatureMalformedException=qt,exports.SignatureMismatchException=Jt,exports.StackableUnitAmountException=pr,exports.StackableUnitDecimalsException=fr,exports.TokenUnit=de,exports.TransferBalanceException=F,exports.TransferMalformedException=Yt,exports.TransferMismatchedException=Xt,exports.TransferRemainderException=Zt,exports.TransferToSelfException=Qt,exports.TransferUnbalancedException=$t,exports.UnauthenticatedException=Dn,exports.Wallet=P,exports.WalletShadowException=dr,exports.WebAuthnPrfSecretStorageProvider=ma,exports.WebCryptoSecretStorageProvider=ea,exports.WebStorageBackend=na,exports.WrongTokenTypeException=en,exports.base64ToHex=y,exports.bufferToHexString=g,exports.charsetBaseConvert=h,exports.chunkArray=te,exports.chunkSubstr=p,exports.constantTimeCompare=gn,exports.createDefaultSecretStorage=Sa,exports.deepCloning=ne,exports.diff=re,exports.generateBatchId=ue,exports.generateBundleHash=ce,exports.generateSecret=se,exports.hexStringToBuffer=_,exports.hexToBase64=v,exports.intersect=S,exports.isHex=b,exports.isNumeric=ee,exports.openEnvelope=G,exports.randomString=m,exports.sealEnvelope=W,exports.shake256=le,exports.withSecureBytes=mn,exports.withSecureString=hn,exports.zeroizeBytes=B;
510
510
  //# sourceMappingURL=client.cjs.js.map