@tinycloud/web-sdk 3.12.0-beta.2 → 3.12.0-beta.21

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,2 +1,2 @@
1
1
  /*! For license information please see encryption-keys.mjs.LICENSE.txt */
2
- class e extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const t="2.45.1";let n=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,i=`viem@${t}`;class r extends Error{constructor(e,s={}){const o=s.cause instanceof r?s.cause.details:s.cause?.message?s.cause.message:s.details,c=s.cause instanceof r&&s.cause.docsPath||s.docsPath,a=n?.({...s,docsPath:c});super([e||"An error occurred.","",...s.metaMessages?[...s.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...o?[`Details: ${o}`]:[],...i?[`Version: ${i}`]:[]].join("\n"),s.cause?{cause:s.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=o,this.docsPath=c,this.metaMessages=s.metaMessages,this.name=s.name??this.name,this.shortMessage=e,this.version=t}walk(e){return s(this,e)}}function s(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?s(e.cause,t):t?null:e}class o extends r{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function c(e,{strict:t=!0}={}){return!!e&&"string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x"))}class a extends r{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function d(e,{dir:t,size:n=32}={}){return"string"==typeof e?function(e,{dir:t,size:n=32}={}){if(null===n)return e;const i=e.replace("0x","");if(i.length>2*n)throw new a({size:Math.ceil(i.length/2),targetSize:n,type:"hex"});return`0x${i["right"===t?"padEnd":"padStart"](2*n,"0")}`}(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new a({size:e.length,targetSize:n,type:"bytes"});const i=new Uint8Array(n);for(let r=0;r<n;r++){const s="right"===t;i[s?r:n-r-1]=e[s?r:e.length-r-1]}return i}(e,{dir:t,size:n})}class u extends r{constructor({max:e,min:t,signed:n,size:i,value:r}){super(`Number "${r}" is not in safe ${i?`${8*i}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class l extends r{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function y(e){return c(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function p(e,{size:t}){if(y(e)>t)throw new l({givenSize:y(e),maxSize:t})}function h(e,t={}){const{signed:n,size:i}=t,r=BigInt(e);let s;i?s=n?(1n<<8n*BigInt(i)-1n)-1n:2n**(8n*BigInt(i))-1n:"number"==typeof e&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof s&&n?-s-1n:0;if(s&&r>s||r<o){const t="bigint"==typeof e?"n":"";throw new u({max:s?`${s}${t}`:void 0,min:`${o}${t}`,signed:n,size:i,value:`${e}${t}`})}const c=`0x${(n&&r<0?(1n<<BigInt(8*i))+BigInt(r):r).toString(16)}`;return i?d(c,{size:i}):c}const f=new TextEncoder;const w={zero:48,nine:57,A:65,F:70,a:97,f:102};function k(e){return e>=w.zero&&e<=w.nine?e-w.zero:e>=w.A&&e<=w.F?e-(w.A-10):e>=w.a&&e<=w.f?e-(w.a-10):void 0}function v(e,t={}){let n=e;t.size&&(p(n,{size:t.size}),n=d(n,{dir:"right",size:t.size}));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let e=0,t=0;e<s;e++){const n=k(i.charCodeAt(t++)),s=k(i.charCodeAt(t++));if(void 0===n||void 0===s)throw new r(`Invalid byte sequence ("${i[t-2]}${i[t-1]}" in "${i}").`);o[e]=16*n+s}return o}function g(e,t={}){const n=f.encode(e);return"number"==typeof t.size?(p(n,{size:t.size}),d(n,{dir:"right",size:t.size})):n}const m=BigInt(2**32-1),b=BigInt(32);function I(e,t=!1){return t?{h:Number(e&m),l:Number(e>>b&m)}:{h:0|Number(e>>b&m),l:0|Number(e&m)}}function E(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function N(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function S(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function $(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function _(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const A=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=_(e[t]);return e};function O(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),N(e),e}class P{}const x=BigInt(0),T=BigInt(1),D=BigInt(2),K=BigInt(7),z=BigInt(256),R=BigInt(113),L=[],C=[],V=[];for(let e=0,t=T,n=1,i=0;e<24;e++){[n,i]=[i,(2*n+3*i)%5],L.push(2*(5*i+n)),C.push((e+1)*(e+2)/2%64);let r=x;for(let e=0;e<7;e++)t=(t<<T^(t>>K)*R)%z,t&D&&(r^=T<<(T<<BigInt(e))-T);V.push(r)}const M=function(e,t=!1){const n=e.length;let i=new Uint32Array(n),r=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:o}=I(e[s],t);[i[s],r[s]]=[n,o]}return[i,r]}(V,!0),U=M[0],H=M[1],B=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),q=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class j extends P{constructor(e,t,n,i=!1,r=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=i,this.rounds=r,E(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var s;this.state=new Uint8Array(200),this.state32=(s=this.state,new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4)))}clone(){return this._cloneInto()}keccak(){A(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let i=24-t;i<24;i++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const i=(t+8)%10,r=(t+2)%10,s=n[r],o=n[r+1],c=B(s,o,1)^n[i],a=q(s,o,1)^n[i+1];for(let n=0;n<50;n+=10)e[t+n]^=c,e[t+n+1]^=a}let t=e[2],r=e[3];for(let n=0;n<24;n++){const i=C[n],s=B(t,r,i),o=q(t,r,i),c=L[n];t=e[c],r=e[c+1],e[c]=s,e[c+1]=o}for(let t=0;t<50;t+=10){for(let i=0;i<10;i++)n[i]=e[t+i];for(let i=0;i<10;i++)e[t+i]^=~n[(i+2)%10]&n[(i+4)%10]}e[0]^=U[i],e[1]^=H[i]}$(n)}(this.state32,this.rounds),A(this.state32),this.posOut=0,this.pos=0}update(e){S(this),N(e=O(e));const{blockLen:t,state:n}=this,i=e.length;for(let r=0;r<i;){const s=Math.min(t-this.pos,i-r);for(let t=0;t<s;t++)n[this.pos++]^=e[r++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:i}=this;e[n]^=t,128&t&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){S(this,!1),N(e),this.finish();const t=this.state,{blockLen:n}=this;for(let i=0,r=e.length;i<r;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,r-i);e.set(t.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return E(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){N(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,$(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:i,rounds:r,enableXOF:s}=this;return e||(e=new j(t,n,i,s,r)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=r,e.suffix=n,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}}const F=(e,t,n)=>function(e){const t=t=>e().update(O(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new j(t,e,n)),G=(()=>F(1,136,32))(),Y=new e(8192);function W(e,t){if(Y.has(`${e}.${t}`))return Y.get(`${e}.${t}`);const n=t?`${t}${e.toLowerCase()}`:e.substring(2).toLowerCase(),i=function(e){const t=G(c(e,{strict:!1})?function(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){return v(h(e,t))}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);return n[0]=Number(e),"number"==typeof t.size?(p(n,{size:t.size}),d(n,{size:t.size})):n}(e,t):c(e)?v(e,t):g(e,t)}(e):e);return t}(g(n)),r=(t?n.substring(`${t}0x`.length):n).split("");for(let e=0;e<40;e+=2)i[e>>1]>>4>=8&&r[e]&&(r[e]=r[e].toUpperCase()),(15&i[e>>1])>=8&&r[e+1]&&(r[e+1]=r[e+1].toUpperCase());const s=`0x${r.join("")}`;return Y.set(`${e}.${t}`,s),s}const J=/^0x[a-fA-F0-9]{40}$/,X=new e(8192);function Z(e,t){const{strict:n=!0}=t??{},i=`${e}.${n}`;if(X.has(i))return X.get(i);const r=!(!J.test(e)||e.toLowerCase()!==e&&n&&W(e)!==e);return X.set(i,r),r}var Q=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function ee(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function te(e){return e.slice(10,e.indexOf("/"))}function ne(e){return e.slice(e.indexOf("/")+1)}function ie(e){const t={};for(const n of Q)te(n.urn)===e&&(t[ee(ne(n.urn))]=n.urn);return t}var re=ie("kv"),se={...ie("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},oe=(ie("duckdb"),ie("capabilities")),ce=(ie("hooks"),ie("encryption")),ae=ie("space"),de="applications",ue="account",le="applications/",ye="secrets",pe="default",he="public",fe="agents",we="tinycloud.encryption",ke=ce.NETWORK_CREATE,ve=[pe,de,ue,ye,he,fe],ge={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:pe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:pe,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:pe,path:"",actions:["read","write"]}]},me={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:de,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:de,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:de,path:"",actions:["read","write"]}]},be={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:ue,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:ue,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:ue,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:ue,path:"account",actions:["read","write","schema"]}]},Ie={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:ye,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:ye,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:ye,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:ye,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:ye,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:ye,path:"",actions:["read"],skipPrefix:!0}]},Ee={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:he,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:he,path:"",actions:["get","list","metadata"]}]},Ne={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:fe,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:fe,path:"",actions:["get","put","del","list","metadata"]}]},Se={[pe]:ge,[de]:me,[ue]:be,[ye]:Ie,[he]:Ee,[fe]:Ne};function $e(e,t=1){return function(e){if(!Number.isSafeInteger(e)||e<=0)throw new Error(`Invalid EIP-155 chain ID: ${e}`)}(t),`did:pkh:eip155:${t}:${function(e){if(!Z(e,{strict:!1}))throw new Error(`Invalid EVM address: ${e}`);return function(e){if(!Z(e,{strict:!1}))throw new o({address:e});return W(e,void 0)}(e)}(e)}`}function _e(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function Ae(e,t,n){return!0===n||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function Oe(e,t,n){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const n=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,i="read"===n||"get"===n?re.GET:"write"===n||"put"===n?re.PUT:"delete"===n||"del"===n?re.DEL:"list"===n?re.LIST:"metadata"===n?re.METADATA:void 0;if(void 0===i)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const r=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${r}`,actions:[i],skipPrefix:!0}})}(e).flatMap(e=>Oe(e,t,n));const i=!0===e.skipPrefix||e.service===we;return[{service:e.service,space:e.service===we?"encryption":e.space??n,path:Ae(t,e.path,i),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function Pe(e){const t=new Set(e.filter(e=>e.service!==we).map(e=>e.space));return function(e){const t=new Map;for(const n of e){const e=`${n.service}\0${n.space}\0${n.path}`,i=t.get(e);if(i)for(const e of n.actions)i.actions.includes(e)||i.actions.push(e);else t.set(e,{...n,actions:[...n.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[oe.READ]}))])}function xe(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const n=t.includeAccountRegistryPermissions??!0,i=e.map(_e),r=i.flatMap(e=>{const t=e.prefix??e.app_id,n=e.space??de;return(e.permissions??[]).flatMap(e=>Oe(e,t,n))});n&&r.push(...Te.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of i){const t=s.get(e.app_id)??[];t.push(_e(e)),s.set(e.app_id,t)}return{manifests:i,resources:Pe(r),delegationTargets:[],registryRecords:n?[...s.entries()].map(([e,t])=>({key:`${le}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:i.some(e=>e.includePublicSpace??!0)}}([Se[e]],{includeAccountRegistryPermissions:!1})}ve.map(e=>({name:e,manifest:Se[e],persistedAsApplication:e===ye}));var Te=Object.freeze([{service:"tinycloud.kv",space:ue,path:le,actions:[re.GET,re.PUT,re.LIST]},{service:"tinycloud.kv",space:ue,path:"spaces/",actions:[re.GET,re.PUT,re.LIST]},{service:"tinycloud.kv",space:ue,path:"system/bootstrap/complete",actions:[re.GET,re.PUT]},{service:"tinycloud.delegation",space:ue,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:ue,path:"account",actions:[se.READ,se.WRITE,se.SCHEMA]},{service:"tinycloud.capabilities",space:ue,path:"",actions:[oe.READ]}]),De=xe(pe),Ke={...De,resources:[...De.resources,...Te.map(e=>({...e,actions:[...e.actions]}))]},ze=Object.freeze(Object.fromEntries(ve.map(e=>[e,e===pe?Ke:xe(e)]))),Re=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[ke]}]);function Le(e){return void 0===e?"":Ce(e)}function Ce(e){if(null===e)return"null";switch(typeof e){case"boolean":case"number":case"string":return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(Ce).join(",")}]`;const t=Object.keys(e).sort(),n=[];for(const i of t){const t=e[i];void 0!==t&&n.push(`${JSON.stringify(i)}:${Ce(t)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof e)}}Object.freeze(ve.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:ze[e].resources,...e===ue?{rawAbilities:Re}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[ae.HOST]}]));var Ve="0123456789abcdef";function Me(e){let t="";for(let n=0;n<e.length;n++){const i=e[n];t+=Ve[i>>4&15]+Ve[15&i]}return t}function Ue(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let i=0;i<e.length;i+=3){const r=e[i],s=i+1<e.length?e[i+1]:0,o=i+2<e.length?e[i+2]:0;n+=t[r>>2&63],n+=t[63&(r<<4|s>>4)],n+=i+1<e.length?t[63&(s<<2|o>>6)]:"=",n+=i+2<e.length?t[63&o]:"="}return n}function He(e){const t=e.replace(/[^A-Za-z0-9+/=]/g,""),n=t.length;if(n%4!=0)throw new Error("invalid base64 input");const i=n/4*3-(t.endsWith("==")?2:t.endsWith("=")?1:0),r=new Uint8Array(i),s={};for(let e=0;e<64;e++)s["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[e]]=e;let o=0;for(let e=0;e<n;e+=4){const n=s[t[e]]??0,c=s[t[e+1]]??0,a="="===t[e+2]?0:s[t[e+2]]??0,d=n<<2|c>>4,u=(15&c)<<4|a>>2,l=(3&a)<<6|("="===t[e+3]?0:s[t[e+3]]??0);o<i&&(r[o++]=d),o<i&&(r[o++]=u),o<i&&(r[o++]=l)}return r}function Be(e){return(new TextEncoder).encode(e)}function qe(e,t){return Me(e(Be(Le(t))))}var je="urn:tinycloud:encryption:",Fe=/^[a-z0-9][a-z0-9-]*$/,Ge=class extends Error{constructor(e){super(e),this.name="NetworkIdError"}};function Ye(e){if("string"!=typeof e||0===e.length)throw new Ge("networkId must be a non-empty string");if(!e.startsWith(je))throw new Ge(`networkId must start with ${je} (got ${JSON.stringify(e)})`);const t=e.slice(25),n=t.lastIndexOf(":");if(n<=0||n===t.length-1)throw new Ge(`networkId missing ownerDid or name segment (got ${JSON.stringify(e)})`);const i=t.slice(0,n),r=t.slice(n+1);if(!i.startsWith("did:"))throw new Ge(`networkId ownerDid must be a DID (got ${JSON.stringify(i)})`);const s=i.split(":");if(s.length<3||s.some(e=>0===e.length))throw new Ge(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(i)})`);if(!Fe.test(r))throw new Ge(`networkId name ${JSON.stringify(r)} must match ${Fe.source}`);return{networkId:e,ownerDid:i,name:r}}var We=je,Je="tinycloud.encryption.decrypt/v1",Xe="tinycloud.encryption.decrypt-result/v1",Ze="tinycloud.encryption/decrypt";function Qe(e){switch(e.code){case"NETWORK_NOT_FOUND":return e.message??`Network not found: ${e.networkId??e.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return e.message??`Network not active (state=${e.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return e.message;case"RESPONSE_SIGNATURE_INVALID":return e.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return e.message??`Node response binding mismatch on field ${JSON.stringify(e.field)}`;case"TRANSPORT_ERROR":return e.message??e.cause.message}}function et(e){return{...e,service:"encryption",message:Qe(e)}}var tt="[a-z0-9][a-z0-9._-]{0,63}",nt=new RegExp(`^${tt}(?:/${tt}){0,7}$`),it=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,rt=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,st="did:pkh:eip155:",ot="tinycloud.encryption/key.create",ct="tinycloud.encryption/key.block",at="tinycloud.encryption/key.unblock",dt=(Object.freeze([Ze,ot,ct,at]),class extends Error{constructor(e,t){super(t),this.name="EncryptionResourceError",this.code=e}});function ut(e){if(!e.startsWith(st))return e;const t=e.slice(15),n=t.indexOf(":"),i=-1===n?"":t.slice(0,n),r=-1===n?"":t.slice(n+1);if(!/^\d+$/.test(i)||!/^0x[a-fA-F0-9]{40}$/.test(r))throw new dt("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(e)})`);const s=BigInt(i);if(0n===s||s>18446744073709551615n)throw new dt("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(i)})`);const o=$e(r,1).slice(17);return`${st}${s}:${o}`}function lt(e){const t=ut(e);if(t!==e)throw new dt("non_canonical_owner",`owner DID is not canonical (expected ${t})`)}function yt(e,t){if(0===e.length)throw new dt("empty_path",`${t} must not be empty`);if((new TextEncoder).encode(e).length>255)throw new dt("path_too_long",`${t} exceeds 255 bytes`);if(!nt.test(e))throw new dt("bad_path",`${t} ${JSON.stringify(e)} must match ${nt.source}`);const n=e.split("/");if("apps"===n[0]&&n.length<("key path"===t?3:2))throw new dt("bad_path",`${t} ${JSON.stringify(e)} under apps/ needs ${"key path"===t?"apps/<id>/<name>":"apps/<id>/"}`)}function pt(e){if("string"!=typeof e||!e.startsWith(We))throw new dt("not_encryption_urn",`resource must start with ${We}`);const t=e.slice(25),n=rt.exec(t);if(null===n)throw new dt("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(e)})`);const i=n[1],r=n[2],s=n[3];if(void 0===s){const e=ut(i),t=`${We}${e}:${r}`;try{Ye(t)}catch(e){if(e instanceof Ge)throw new dt("bad_network",e.message);throw e}return{kind:"network",ownerDid:e,network:r,networkId:t}}if(!it.test(r))throw new dt("bad_network",`network ${JSON.stringify(r)} must match ${it.source}`);lt(i);const o=`${We}${i}:${r}`;if(s.endsWith("/")){const e=s.slice(0,-1);return yt(e,"prefix"),{kind:"prefix",ownerDid:i,network:r,networkId:o,prefix:e}}return yt(s,"key path"),{kind:"key",ownerDid:i,network:r,networkId:o,path:s}}function ht(e){let t="";for(const n of e){const e=n.codePointAt(0);t+=e>=32&&e<=126?n:`\\u{${e.toString(16).toUpperCase().padStart(4,"0")}}`}return t}function ft(e){const t="string"==typeof e?e:String(e),n=Array.from(t);return ht(n.length>120?`${n.slice(0,120).join("")}...`:t)}var wt=class extends Error{constructor(e,t,n={}){super(ht(t),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=e,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},kt=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),vt=Object.assign(Object.create(null),{key_deleted:!0}),gt=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function mt(e,t,n){const i=gt.exec(t.trim()),r=i?.[1]?.slice(0,64),s=i?.[2]?.trim(),o={status:e,...void 0===r?{}:{nodeCode:r},...void 0===s||0===s.length?{}:{detail:s}};if(void 0!==r){const e=kt[r];if(void 0!==e)return new wt(e,`${n}: ${r}`,o);if(!0===vt[r])return new wt("KEY_UNAVAILABLE",`${n}: key unavailable (${r})`,{...o,rawState:r})}return new wt("NODE_ERROR",`${n}: node responded ${e}`,o)}function bt(e){let t;try{t=pt(e)}catch(t){throw new wt("INVALID_KEY_TARGET",`not a valid encryption key resource: ${ft(t instanceof Error?t.message:t)}`,{cause:t,input:e})}if("key"!==t.kind)throw new wt("INVALID_KEY_TARGET",`a ${t.kind} resource cannot be an invocation target; an exact key is required`,{input:e});return t}function It(e){const t=bt(e.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path,action:e.action,bodyHash:qe(e.crypto.sha256,e.body)}}function Et(e){const t=bt(e.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:e.targetNode,networkId:t.networkId,keyPath:t.path}}var Nt={[Ze]:!0,[ot]:!0,[ct]:!0,[at]:!0};function St(e){return new wt("INVALID_RESPONSE",`node returned an invalid ${e}`)}function $t(e,t,n){const i="object"==typeof e&&null!==e?e:{};if("string"!=typeof i.alg||"number"!=typeof i.keyVersion||!Number.isInteger(i.keyVersion)||"string"!=typeof i.publicEncryptionKey||0===i.publicEncryptionKey.length)throw St("key descriptor");if(i.networkId!==t||i.keyPath!==n)throw new wt("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:t,keyPath:n,alg:i.alg,keyVersion:i.keyVersion,publicEncryptionKey:i.publicEncryptionKey}}function _t(e,t,n){const i=$t(e,t,n),r=e;if("string"!=typeof r.state||"string"!=typeof r.kind)throw St("key descriptor (state/kind missing)");return{...i,state:r.state,kind:r.kind,..."string"==typeof r.createdAt?{createdAt:r.createdAt}:{},..."string"==typeof r.updatedAt?{updatedAt:r.updatedAt}:{}}}function At(e){return e.startsWith("apps/")}var Ot=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],Pt=class{constructor(e){this.config=e}networkFor(e){return e?.networkId??this.config.defaultNetworkId()}keyUrn(e,t){try{return function(e,t){const n=function(e){let t;try{t=Ye(e)}catch(e){if(e instanceof Ge)throw new dt("bad_network",e.message);throw e}return lt(t.ownerDid),t.networkId}(e);yt(t,"key path");const i=`${n}/${t}`;return function(e,t){if(pt(e).networkId!==t)throw new dt("malformed",`built resource does not round-trip (got ${JSON.stringify(e)})`)}(i,n),i}(e,t)}catch(n){throw new wt("INVALID_KEY_TARGET",ft(n instanceof Error?n.message:n),{cause:n,input:`${e}/${t}`})}}requireNode(){if(void 0===this.nodeId){const e=this.readNodeInfo();this.nodeId=e,e.catch(()=>{this.nodeId===e&&(this.nodeId=void 0)})}return this.nodeId}refreshNodeInfo(){this.nodeId=void 0}async readNodeInfo(){const e=await this.config.fetch(`${this.config.host}/info`);if(!e.ok)throw mt(e.status,await xt(e),"failed to read node info");const t=await e.json();if(!function(e){const t=e?.features;return Array.isArray(t)&&t.includes("encryption-named-keys-v1")}(t))throw new wt("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof t.nodeId||0===t.nodeId.length)throw St("/info response (nodeId missing)");return t.nodeId}keysUrl(e,t){return`${this.config.host}/encryption/networks/${e}/keys/${t}`}async getPublicKey(e,t){const n=this.networkFor(t);this.keyUrn(n,e),await this.requireNode();const i=await this.config.fetch(this.keysUrl(n,e),{method:"GET"});if(!i.ok)throw mt(i.status,await xt(i),"failed to read key");return $t(await i.json(),n,e)}async describeKey(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);return null===i?null:_t(i,n,e)}async describePublic(e,t){const n=this.networkFor(t),i=await this.describeBody(e,t);if(null===i)throw new wt("KEY_NOT_FOUND",`key ${ft(e)} does not exist`,{status:404});return $t(i,n,e)}async describeBody(e,t){const n=this.networkFor(t),i=this.keyUrn(n,e),r=t?.ability??Ze;if(!0!==Nt[r])throw new wt("INVALID_KEY_TARGET",`${ft(r)} cannot describe a key`,{input:r});const s=await this.requireNode(),o=await this.config.signInvocation({targetNode:s,resource:i,action:r,facts:Et({targetNode:s,keyResource:i})}),c=await this.config.fetch(this.keysUrl(n,e),{method:"GET",headers:{Authorization:o.authorization}});if(404===c.status){const e=mt(404,await xt(c),"failed to describe key");if("KEY_NOT_FOUND"===e.code)return null;throw e}if(!c.ok)throw mt(c.status,await xt(c),"failed to describe key");return c.json()}async admin(e,t,n,i){const r=this.networkFor(i),s=this.keyUrn(r,n),o="keys"===e?{keyPath:n,deletable:At(n)}:{keyPath:n},c=await this.requireNode(),a=await this.config.signInvocation({targetNode:c,resource:s,action:t,facts:It({crypto:this.config.crypto,targetNode:c,keyResource:s,action:t,body:o})}),d=await this.config.fetch(`${this.config.host}/encryption/networks/${r}/${e}`,{method:"POST",headers:{Authorization:a.authorization,"Content-Type":"application/json"},body:Le(o)});if(!d.ok)throw mt(d.status,await xt(d),`failed to ${t}`);return _t(function(e){const t="object"==typeof e&&null!==e?e:{};return"object"==typeof t.descriptor&&null!==t.descriptor?t.descriptor:e}(await d.json()),r,n)}createKey(e,t){return this.admin("keys",ot,e,t)}blockKey(e,t){return this.admin("key-actions/block",ct,e,t)}unblockKey(e,t){return this.admin("key-actions/unblock",at,e,t)}async ensureKey(e,t){const n=()=>this.describeKey(e,{...t,ability:ot});let i=await n();if(null===i)try{i=await this.createKey(e,t)}catch(t){if(!(t instanceof wt)||"KEY_EXISTS"!==t.code)throw t;if(i=await n(),null===i)throw new wt("KEY_NOT_FOUND",`key ${ft(e)} reported as existing but could not be read back`)}return function(e,t){if("blocked"===e.state)throw new wt("KEY_BLOCKED",`key ${ft(e.keyPath)} is blocked`,{rawState:e.state});if("active"!==e.state)throw new wt("KEY_UNAVAILABLE",`key ${ft(e.keyPath)} is unavailable (state ${ft(e.state)})`,{rawState:e.state});if(e.kind!==t)throw new wt("KEY_KIND_MISMATCH",`key ${ft(e.keyPath)} exists with kind ${ft(e.kind)}, not ${t}`,{kind:e.kind});return e}(i,At(e)?"deletable":"deterministic")}async encrypt(e,t,n){const i=At(e)?await this.describePublic(e,n):await this.getPublicKey(e,n),{crypto:r}=this.config,s=r.randomBytes(32),o=r.authEncrypt(s,t,n?.aad),c=Ue(r.sealToNetworkKey(He(i.publicEncryptionKey),s));return{v:2,networkId:i.networkId,keyPath:i.keyPath,alg:i.alg??"x25519-aes256gcm/v1",keyVersion:i.keyVersion,encryptedSymmetricKey:c,encryptedSymmetricKeyHash:qe(r.sha256,c),ciphertext:Ue(o),...void 0!==n?.aad?{aad:Ue(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(e){const t="object"==typeof e&&null!==e?e:{};if(1===t.v&&void 0===t.keyPath)return this.decryptRoot(t);if(2===t.v&&"string"==typeof t.keyPath)return this.decryptKey(this.validateKeyEnvelope(t));throw new wt("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(e){const t=[];for(const n of e)try{t.push({ok:!0,data:await this.decrypt(n)})}catch(e){t.push({ok:!1,error:e instanceof wt?e:new wt("DECRYPT_FAILED","decrypt failed",{cause:e})})}return t}async decryptRoot(e){if(void 0===this.config.decryptRoot)throw new wt("DECRYPT_FAILED","no root-key decrypt path is configured");const t=await this.config.decryptRoot(e);if(!t.ok)throw new wt("DECRYPT_FAILED",ft(t.error.message),{cause:t.error});return t.data}validateKeyEnvelope(e){for(const t of Ot)if("string"!=typeof e[t]||0===e[t].length)throw new wt("INVALID_ENVELOPE",`envelope.${t} must be a non-empty string`);if("number"!=typeof e.keyVersion||!Number.isInteger(e.keyVersion))throw new wt("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof e.networkId)throw new wt("INVALID_ENVELOPE","envelope.networkId must be a string");try{Ye(e.networkId)}catch(e){throw new wt("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:e})}if(qe(this.config.crypto.sha256,e.encryptedSymmetricKey)!==e.encryptedSymmetricKeyHash)throw new wt("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");return e}async decryptKey(e){const{crypto:t}=this.config,n=this.keyUrn(e.networkId,e.keyPath),i=await this.requireNode(),r=function(e){const t=e.crypto.randomBytes(32);return e.crypto.x25519FromSeed(t)}({crypto:t}),s=Ue(r.publicKey),o=qe(t.sha256,s),c={type:Je,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,alg:e.alg,keyVersion:e.keyVersion,encryptedSymmetricKey:e.encryptedSymmetricKey,encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKey:s,receiverPublicKeyHash:o},a=Le(c),d={type:Je,targetNode:i,networkId:e.networkId,keyPath:e.keyPath,bodyHash:qe(t.sha256,c),encryptedSymmetricKeyHash:e.encryptedSymmetricKeyHash,receiverPublicKeyHash:o,alg:e.alg,keyVersion:e.keyVersion},u=await this.config.signInvocation({targetNode:i,resource:n,action:Ze,facts:d}),l=await this.config.fetch(`${this.config.host}/invoke`,{method:"POST",headers:{Authorization:u.authorization,"Content-Type":"application/json"},body:a});if(!l.ok)throw mt(l.status,await xt(l),"failed to decrypt");const y=function(e){const{crypto:t,request:n,facts:i,invocationCid:r,requestBodyHash:s,response:o}=e;if(o.type!==Xe)return{ok:!1,error:et({code:"INVALID_RESPONSE",message:`response.type must be ${Xe}`})};if(o.targetNode!==n.targetNode)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(o.networkId!==n.networkId)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(o.nodeId!==n.targetNode)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if(o.alg!==n.alg)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(o.keyVersion!==n.keyVersion)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(o.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(o.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(o.invocationCid!==r)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=Me(t.sha256(Be(`${r}${s}`)));if(o.requestHash!==c)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(i.encryptedSymmetricKeyHash!==o.encryptedSymmetricKeyHash||i.receiverPublicKeyHash!==o.receiverPublicKeyHash||i.networkId!==o.networkId||i.targetNode!==o.targetNode||i.alg!==o.alg||i.keyVersion!==o.keyVersion)return{ok:!1,error:et({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(e){const{nodeSignature:t,...n}=e;return Le(n)}(o)),d=He(o.nodeSignature);return t.verifyNodeSignature(o.nodeId,a,d)?{ok:!0,data:o}:{ok:!1,error:et({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:t,request:c,facts:d,invocationCid:u.invocationCid,requestBodyHash:d.bodyHash,response:await l.json()});if(!y.ok)throw new wt("INVALID_RESPONSE",ft(y.error.message),{cause:y.error});const p=function(e,t,n){const i=He(n.wrappedKey);return e.openWithReceiverKey(t,i)}(t,r.privateKey,y.data);try{return t.authDecrypt(p,He(e.ciphertext),void 0!==e.aad?He(e.aad):void 0)}catch(e){throw new wt("DECRYPT_FAILED","local decryption failed",{cause:e})}}};async function xt(e){try{return await e.text()}catch{return""}}function Tt(e,t={}){const n=e;for(const e of["signRawNetworkAuthorization","createEncryptionCrypto"])if("function"!=typeof n[e])throw new wt("NODE_HOOK_MISSING",`TinyCloudNode.${e} is not available; named keys cannot sign invocations`);const i=n,r=e.hosts[0];if(void 0===r)throw new Error("TinyCloud node host has not been resolved");const s={host:r,crypto:i.createEncryptionCrypto(),fetch:t.fetch??globalThis.fetch.bind(globalThis),defaultNetworkId:()=>t.networkId??e.getDefaultEncryptionNetworkId(),signInvocation:e=>i.signRawNetworkAuthorization({targetNode:e.targetNode,networkId:e.resource,action:e.action,facts:e.facts}),decryptRoot:t=>{const n=e.session?.delegationCid;return void 0===n?Promise.reject(new Error("Not signed in. Call signIn() first.")):e.encryption.decryptEnvelope(t,{proofs:[n]})}};return new Pt(s)}export{Tt as createNamedKeyClient};
2
+ var t={};function e(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function n(t,...n){if(!e(t))throw new Error("Uint8Array expected");if(n.length>0&&!n.includes(t.length))throw new Error("Uint8Array expected of length "+n+", got length="+t.length)}function r(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function i(t,e){n(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function o(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function s(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function c(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}t.d=(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},t.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);const a=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function u(t){if("string"==typeof t)t=function(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}(t);else{if(!e(t))throw new Error("Uint8Array expected, got "+typeof t);t=h(t)}return t}const d=(t,e)=>{function r(r,...i){if(n(r),!a)throw new Error("Non little-endian hardware is not yet supported");if(void 0!==t.nonceLength){const e=i[0];if(!e)throw new Error("nonce / iv required");t.varSizeNonce?n(e):n(e,t.nonceLength)}const o=t.tagLength;o&&void 0!==i[1]&&n(i[1]);const s=e(r,...i),c=(t,e)=>{if(void 0!==e){if(2!==t)throw new Error("cipher output not supported");n(e)}};let u=!1;return{encrypt(t,e){if(u)throw new Error("cannot encrypt() twice with same key + nonce");return u=!0,n(t),c(s.encrypt.length,e),s.encrypt(t,e)},decrypt(t,e){if(n(t),o&&t.length<o)throw new Error("invalid ciphertext length: smaller than tagLength="+o);return c(s.decrypt.length,e),s.decrypt(t,e)}}}return Object.assign(r,t),r};function f(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,s,r),t.setUint32(e+u,c,r)}function l(t){return t.byteOffset%4==0}function h(t){return Uint8Array.from(t)}const y=16,p=new Uint8Array(16),w=o(p),g=(t,e,n,r)=>({s3:n<<31|r>>>1,s2:e<<31|n>>>1,s1:t<<31|e>>>1,s0:t>>>1^225<<24&-(1&r)}),b=t=>(t>>>0&255)<<24|(t>>>8&255)<<16|(t>>>16&255)<<8|t>>>24&255;class m{constructor(t,e){this.blockLen=y,this.outputLen=y,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,n(t=u(t),16);const r=c(t);let i=r.getUint32(0,!1),o=r.getUint32(4,!1),s=r.getUint32(8,!1),a=r.getUint32(12,!1);const d=[];for(let t=0;t<128;t++)d.push({s0:b(i),s1:b(o),s2:b(s),s3:b(a)}),({s0:i,s1:o,s2:s,s3:a}=g(i,o,s,a));const f=(l=e||1024)>65536?8:l>1024?4:2;var l;if(![1,2,4,8].includes(f))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=f;const h=128/f,p=this.windowSize=2**f,w=[];for(let t=0;t<h;t++)for(let e=0;e<p;e++){let n=0,r=0,i=0,o=0;for(let s=0;s<f;s++){if(!(e>>>f-s-1&1))continue;const{s0:c,s1:a,s2:u,s3:l}=d[f*t+s];n^=c,r^=a,i^=u,o^=l}w.push({s0:n,s1:r,s2:i,s3:o})}this.t=w}_updateBlock(t,e,n,r){t^=this.s0,e^=this.s1,n^=this.s2,r^=this.s3;const{W:i,t:o,windowSize:s}=this;let c=0,a=0,u=0,d=0;const f=(1<<i)-1;let l=0;for(const h of[t,e,n,r])for(let t=0;t<4;t++){const e=h>>>8*t&255;for(let t=8/i-1;t>=0;t--){const n=e>>>i*t&f,{s0:r,s1:h,s2:y,s3:p}=o[l*s+n];c^=r,a^=h,u^=y,d^=p,l+=1}}this.s0=c,this.s1=a,this.s2=u,this.s3=d}update(t){r(this),n(t=u(t));const e=o(t),i=Math.floor(t.length/y),c=t.length%y;for(let t=0;t<i;t++)this._updateBlock(e[4*t+0],e[4*t+1],e[4*t+2],e[4*t+3]);return c&&(p.set(t.subarray(i*y)),this._updateBlock(w[0],w[1],w[2],w[3]),s(w)),this}destroy(){const{t}=this;for(const e of t)e.s0=0,e.s1=0,e.s2=0,e.s3=0}digestInto(t){r(this),i(t,this),this.finished=!0;const{s0:e,s1:n,s2:s,s3:c}=this,a=o(t);return a[0]=e,a[1]=n,a[2]=s,a[3]=c,t}digest(){const t=new Uint8Array(y);return this.digestInto(t),this.destroy(),t}}class v extends m{constructor(t,e){n(t=u(t));const r=function(t){t.reverse();const e=1&t[15];let n=0;for(let e=0;e<t.length;e++){const r=t[e];t[e]=r>>>1|n,n=(1&r)<<7}return t[0]^=225&-e,t}(h(t));super(r,e),s(r)}update(t){t=u(t),r(this);const e=o(t),n=t.length%y,i=Math.floor(t.length/y);for(let t=0;t<i;t++)this._updateBlock(b(e[4*t+3]),b(e[4*t+2]),b(e[4*t+1]),b(e[4*t+0]));return n&&(p.set(t.subarray(i*y)),this._updateBlock(b(w[3]),b(w[2]),b(w[1]),b(w[0])),s(w)),this}digestInto(t){r(this),i(t,this),this.finished=!0;const{s0:e,s1:n,s2:s,s3:c}=this,a=o(t);return a[0]=e,a[1]=n,a[2]=s,a[3]=c,t.reverse()}}function k(t){const e=(e,n)=>t(n,e.length).update(u(e)).digest(),n=t(new Uint8Array(16),0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=(e,n)=>t(e,n),e}const E=k((t,e)=>new m(t,e)),I=(k((t,e)=>new v(t,e)),16),x=new Uint8Array(I);function A(t){return t<<1^283&-(t>>7)}function N(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(1&e),t=A(t);return n}const B=t=>t<<24|t>>>8,S=t=>t<<8|t>>>24;function O(t,e){if(256!==t.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map((n,r)=>e(t[r])),r=n.map(S),i=r.map(S),o=i.map(S),s=new Uint32Array(65536),c=new Uint32Array(65536),a=new Uint16Array(65536);for(let e=0;e<256;e++)for(let u=0;u<256;u++){const d=256*e+u;s[d]=n[e]^r[u],c[d]=i[e]^o[u],a[d]=t[e]<<8|t[u]}return{sbox:t,sbox2:a,T0:n,T1:r,T2:i,T3:o,T01:s,T23:c}}const _=O((()=>{const t=new Uint8Array(256);for(let e=0,n=1;e<256;e++,n^=A(n))t[e]=n;const e=new Uint8Array(256);e[0]=99;for(let n=0;n<255;n++){let r=t[255-n];r|=r<<8,e[t[n]]=255&(r^r>>4^r>>5^r>>6^r>>7^99)}return s(t),e})(),t=>N(t,3)<<24|t<<16|t<<8|N(t,2)),P=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=A(n))t[e]=n;return t})();function $(t,e,n,r,i,o){return t[n<<8&65280|r>>>8&255]^e[i>>>8&65280|o>>>24&255]}function U(t,e,n,r,i){return t[255&e|65280&n]|t[r>>>16&255|i>>>16&65280]<<16}function R(t,e,n,r,i){const{sbox2:o,T01:s,T23:c}=_;let a=0;e^=t[a++],n^=t[a++],r^=t[a++],i^=t[a++];const u=t.length/4-2;for(let o=0;o<u;o++){const o=t[a++]^$(s,c,e,n,r,i),u=t[a++]^$(s,c,n,r,i,e),d=t[a++]^$(s,c,r,i,e,n),f=t[a++]^$(s,c,i,e,n,r);e=o,n=u,r=d,i=f}return{s0:t[a++]^U(o,e,n,r,i),s1:t[a++]^U(o,n,r,i,e),s2:t[a++]^U(o,r,i,e,n),s3:t[a++]^U(o,i,e,n,r)}}function L(t,e,r,i,a){n(r,I),n(i),a=function(t,e,n=!0){if(void 0===e)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(n&&!l(e))throw new Error("invalid output, must be aligned");return e}(i.length,a);const u=r,d=o(u),f=c(u),h=o(i),y=o(a),p=e?0:12,w=i.length;let g=f.getUint32(p,e),{s0:b,s1:m,s2:v,s3:k}=R(t,d[0],d[1],d[2],d[3]);for(let n=0;n+4<=h.length;n+=4)y[n+0]=h[n+0]^b,y[n+1]=h[n+1]^m,y[n+2]=h[n+2]^v,y[n+3]=h[n+3]^k,g=g+1>>>0,f.setUint32(p,g,e),({s0:b,s1:m,s2:v,s3:k}=R(t,d[0],d[1],d[2],d[3]));const E=I*Math.floor(h.length/4);if(E<w){const t=new Uint32Array([b,m,v,k]),e=(x=t,new Uint8Array(x.buffer,x.byteOffset,x.byteLength));for(let t=E,n=0;t<w;t++,n++)a[t]=i[t]^e[n];s(t)}var x;return a}function T(t,e,n,r,i){const o=i?i.length:0,a=t.create(n,r.length+o);i&&a.update(i);const u=function(t,e,n){!function(t){if("boolean"!=typeof t)throw new Error(`boolean expected, not ${t}`)}(n);const r=new Uint8Array(16),i=c(r);return f(i,0,BigInt(e),n),f(i,8,BigInt(t),n),r}(8*r.length,8*o,e);a.update(r),a.update(u);const d=a.digest();return s(u),d}const K=d({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(t,e,r){if(e.length<8)throw new Error("aes/gcm: invalid nonce length");function i(t,e,n){const i=T(E,!1,t,n,r);for(let t=0;t<e.length;t++)i[t]^=e[t];return i}function a(){const r=function(t){n(t);const e=t.length;if(![16,24,32].includes(e))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+e);const{sbox2:r}=_,i=[];l(t)||i.push(t=h(t));const c=o(t),a=c.length,u=t=>U(r,t,t,t,t),d=new Uint32Array(e+28);d.set(c);for(let t=a;t<d.length;t++){let e=d[t-1];t%a===0?e=u(B(e))^P[t/a-1]:a>6&&t%a===4&&(e=u(e)),d[t]=d[t-a]^e}return s(...i),d}(t),i=x.slice(),a=x.slice();if(L(r,!1,a,a,i),12===e.length)a.set(e);else{const t=x.slice();f(c(t),8,BigInt(8*e.length),!1);const n=E.create(i).update(e).update(t);n.digestInto(a),n.destroy()}return{xk:r,authKey:i,counter:a,tagMask:L(r,!1,a,x)}}return{encrypt(t){const{xk:e,authKey:n,counter:r,tagMask:o}=a(),c=new Uint8Array(t.length+16),u=[e,n,r,o];l(t)||u.push(t=h(t)),L(e,!1,r,t,c.subarray(0,t.length));const d=i(n,o,c.subarray(0,c.length-16));return u.push(d),c.set(d,t.length),s(...u),c},decrypt(t){const{xk:e,authKey:n,counter:r,tagMask:o}=a(),c=[e,n,o,r];l(t)||c.push(t=h(t));const u=t.subarray(0,-16),d=t.subarray(-16),f=i(n,o,u);if(c.push(f),!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(f,d))throw new Error("aes/gcm: invalid ghash tag");const y=L(e,!1,r,u);return s(...c),y}}}),D=()=>"undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:"undefined"!=typeof self&&self.crypto?self.crypto:void 0,V={web:D(),node:void 0,getRandomValues:function(t){const e=D();if(e&&e.getRandomValues)return e.getRandomValues(t);for(let e=0;e<t.length;e++)t[e]=Math.floor(256*Math.random());return t}};function C(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name}function z(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function H(t,...e){if(!C(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function q(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.createHasher");z(t.outputLen),z(t.blockLen)}function F(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function M(t,e){H(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function j(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function G(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function W(t,e){return t<<32-e|t>>>e}function Y(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Z=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?t=>t:function(t){for(let e=0;e<t.length;e++)t[e]=Y(t[e]);return t},X=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),J=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Q(t){if(H(t),X)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=J[t[n]];return e}function tt(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function et(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);if(X)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let e=0,i=0;e<n;e++,i+=2){const n=tt(t.charCodeAt(i)),o=tt(t.charCodeAt(i+1));if(void 0===n||void 0===o){const e=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+e+'" at index '+i)}r[e]=16*n+o}return r}function nt(t){if("string"!=typeof t)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(t))}function rt(t){return"string"==typeof t&&(t=nt(t)),H(t),t}function it(...t){let e=0;for(let n=0;n<t.length;n++){const r=t[n];H(r),e+=r.length}const n=new Uint8Array(e);for(let e=0,r=0;e<t.length;e++){const i=t[e];n.set(i,r),r+=i.length}return n}class ot{}function st(t){const e=e=>t().update(rt(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function ct(t=32){if(V&&"function"==typeof V.getRandomValues)return V.getRandomValues(new Uint8Array(t));if(V&&"function"==typeof V.randomBytes)return Uint8Array.from(V.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function at(t,e,n){return t&e^~t&n}function ut(t,e,n){return t&e^t&n^e&n}class dt extends ot{constructor(t,e,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(t),this.view=G(this.buffer)}update(t){F(this),H(t=rt(t));const{view:e,buffer:n,blockLen:r}=this,i=t.length;for(let o=0;o<i;){const s=Math.min(r-this.pos,i-o);if(s===r){const e=G(t);for(;r<=i-o;o+=r)this.process(e,o);continue}n.set(t.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){F(this),M(t,this),this.finished=!0;const{buffer:e,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;e[o++]=128,j(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let t=o;t<r;t++)e[t]=0;!function(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const i=BigInt(32),o=BigInt(4294967295),s=Number(n>>i&o),c=Number(n&o),a=r?4:0,u=r?0:4;t.setUint32(e+a,s,r),t.setUint32(e+u,c,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const s=G(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const a=c/4,u=this.get();if(a>u.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;t<a;t++)s.setUint32(4*t,u[t],i)}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:e,buffer:n,length:r,finished:i,destroyed:o,pos:s}=this;return t.destroyed=o,t.finished=i,t.length=r,t.pos=s,r%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const ft=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ht=BigInt(2**32-1),yt=BigInt(32);function pt(t,e=!1){return e?{h:Number(t&ht),l:Number(t>>yt&ht)}:{h:0|Number(t>>yt&ht),l:0|Number(t&ht)}}function wt(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){const{h:n,l:s}=pt(t[o],e);[r[o],i[o]]=[n,s]}return[r,i]}const gt=(t,e,n)=>t>>>n,bt=(t,e,n)=>t<<32-n|e>>>n,mt=(t,e,n)=>t>>>n|e<<32-n,vt=(t,e,n)=>t<<32-n|e>>>n,kt=(t,e,n)=>t<<64-n|e>>>n-32,Et=(t,e,n)=>t>>>n-32|e<<64-n;function It(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:0|i}}const xt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),At=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Nt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Bt=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,St=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Ot=(t,e,n,r,i,o)=>e+n+r+i+o+(t/2**32|0)|0,_t=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pt=new Uint32Array(64);class $t extends dt{constructor(t=32){super(64,t,8,!1),this.A=0|ft[0],this.B=0|ft[1],this.C=0|ft[2],this.D=0|ft[3],this.E=0|ft[4],this.F=0|ft[5],this.G=0|ft[6],this.H=0|ft[7]}get(){const{A:t,B:e,C:n,D:r,E:i,F:o,G:s,H:c}=this;return[t,e,n,r,i,o,s,c]}set(t,e,n,r,i,o,s,c){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|o,this.G=0|s,this.H=0|c}process(t,e){for(let n=0;n<16;n++,e+=4)Pt[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=Pt[t-15],n=Pt[t-2],r=W(e,7)^W(e,18)^e>>>3,i=W(n,17)^W(n,19)^n>>>10;Pt[t]=i+Pt[t-7]+r+Pt[t-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:c,G:a,H:u}=this;for(let t=0;t<64;t++){const e=u+(W(s,6)^W(s,11)^W(s,25))+at(s,c,a)+_t[t]+Pt[t]|0,d=(W(n,2)^W(n,13)^W(n,22))+ut(n,r,i)|0;u=a,a=c,c=s,s=o+e|0,o=i,i=r,r=n,n=e+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,c=c+this.F|0,a=a+this.G|0,u=u+this.H|0,this.set(n,r,i,o,s,c,a,u)}roundClean(){j(Pt)}destroy(){this.set(0,0,0,0,0,0,0,0),j(this.buffer)}}const Ut=(()=>wt(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))))(),Rt=(()=>Ut[0])(),Lt=(()=>Ut[1])(),Tt=new Uint32Array(80),Kt=new Uint32Array(80);class Dt extends dt{constructor(t=64){super(128,t,16,!1),this.Ah=0|lt[0],this.Al=0|lt[1],this.Bh=0|lt[2],this.Bl=0|lt[3],this.Ch=0|lt[4],this.Cl=0|lt[5],this.Dh=0|lt[6],this.Dl=0|lt[7],this.Eh=0|lt[8],this.El=0|lt[9],this.Fh=0|lt[10],this.Fl=0|lt[11],this.Gh=0|lt[12],this.Gl=0|lt[13],this.Hh=0|lt[14],this.Hl=0|lt[15]}get(){const{Ah:t,Al:e,Bh:n,Bl:r,Ch:i,Cl:o,Dh:s,Dl:c,Eh:a,El:u,Fh:d,Fl:f,Gh:l,Gl:h,Hh:y,Hl:p}=this;return[t,e,n,r,i,o,s,c,a,u,d,f,l,h,y,p]}set(t,e,n,r,i,o,s,c,a,u,d,f,l,h,y,p){this.Ah=0|t,this.Al=0|e,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|o,this.Dh=0|s,this.Dl=0|c,this.Eh=0|a,this.El=0|u,this.Fh=0|d,this.Fl=0|f,this.Gh=0|l,this.Gl=0|h,this.Hh=0|y,this.Hl=0|p}process(t,e){for(let n=0;n<16;n++,e+=4)Tt[n]=t.getUint32(e),Kt[n]=t.getUint32(e+=4);for(let t=16;t<80;t++){const e=0|Tt[t-15],n=0|Kt[t-15],r=mt(e,n,1)^mt(e,n,8)^gt(e,0,7),i=vt(e,n,1)^vt(e,n,8)^bt(e,n,7),o=0|Tt[t-2],s=0|Kt[t-2],c=mt(o,s,19)^kt(o,s,61)^gt(o,0,6),a=vt(o,s,19)^Et(o,s,61)^bt(o,s,6),u=Nt(i,a,Kt[t-7],Kt[t-16]),d=Bt(u,r,c,Tt[t-7],Tt[t-16]);Tt[t]=0|d,Kt[t]=0|u}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:s,Cl:c,Dh:a,Dl:u,Eh:d,El:f,Fh:l,Fl:h,Gh:y,Gl:p,Hh:w,Hl:g}=this;for(let t=0;t<80;t++){const e=mt(d,f,14)^mt(d,f,18)^kt(d,f,41),b=vt(d,f,14)^vt(d,f,18)^Et(d,f,41),m=d&l^~d&y,v=St(g,b,f&h^~f&p,Lt[t],Kt[t]),k=Ot(v,w,e,m,Rt[t],Tt[t]),E=0|v,I=mt(n,r,28)^kt(n,r,34)^kt(n,r,39),x=vt(n,r,28)^Et(n,r,34)^Et(n,r,39),A=n&i^n&s^i&s,N=r&o^r&c^o&c;w=0|y,g=0|p,y=0|l,p=0|h,l=0|d,h=0|f,({h:d,l:f}=It(0|a,0|u,0|k,0|E)),a=0|s,u=0|c,s=0|i,c=0|o,i=0|n,o=0|r;const B=xt(E,x,N);n=At(B,k,I,A),r=0|B}({h:n,l:r}=It(0|this.Ah,0|this.Al,0|n,0|r)),({h:i,l:o}=It(0|this.Bh,0|this.Bl,0|i,0|o)),({h:s,l:c}=It(0|this.Ch,0|this.Cl,0|s,0|c)),({h:a,l:u}=It(0|this.Dh,0|this.Dl,0|a,0|u)),({h:d,l:f}=It(0|this.Eh,0|this.El,0|d,0|f)),({h:l,l:h}=It(0|this.Fh,0|this.Fl,0|l,0|h)),({h:y,l:p}=It(0|this.Gh,0|this.Gl,0|y,0|p)),({h:w,l:g}=It(0|this.Hh,0|this.Hl,0|w,0|g)),this.set(n,r,i,o,s,c,a,u,d,f,l,h,y,p,w,g)}roundClean(){j(Tt,Kt)}destroy(){j(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Vt=st(()=>new $t),Ct=st(()=>new Dt),zt=BigInt(0),Ht=BigInt(1);function qt(t,e=""){if("boolean"!=typeof t)throw new Error((e&&`"${e}"`)+"expected boolean, got type="+typeof t);return t}function Ft(t,e,n=""){const r=C(t),i=t?.length,o=void 0!==e;if(!r||o&&i!==e)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(o?` of length ${e}`:"")+", got "+(r?`length=${i}`:"type="+typeof t));return t}function Mt(t){if("string"!=typeof t)throw new Error("hex string expected, got "+typeof t);return""===t?zt:BigInt("0x"+t)}function jt(t){return H(t),Mt(Q(Uint8Array.from(t).reverse()))}function Gt(t,e){return et(t.toString(16).padStart(2*e,"0"))}function Wt(t,e){return Gt(t,e).reverse()}function Yt(t,e,n){let r;if("string"==typeof e)try{r=et(e)}catch(e){throw new Error(t+" must be hex string or Uint8Array, cause: "+e)}else{if(!C(e))throw new Error(t+" must be hex string or Uint8Array");r=Uint8Array.from(e)}const i=r.length;if("number"==typeof n&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function Zt(t){return Uint8Array.from(t)}const Xt=t=>"bigint"==typeof t&&zt<=t;function Jt(t,e,n,r){if(!function(t,e,n){return Xt(t)&&Xt(e)&&Xt(n)&&e<=t&&t<n}(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}const Qt=t=>(Ht<<BigInt(t))-Ht;function te(t,e,n={}){if(!t||"object"!=typeof t)throw new Error("expected valid options object");function r(e,n,r){const i=t[e];if(r&&void 0===i)return;const o=typeof i;if(o!==n||null===i)throw new Error(`param "${e}" is invalid: expected ${n}, got ${o}`)}Object.entries(e).forEach(([t,e])=>r(t,e,!1)),Object.entries(n).forEach(([t,e])=>r(t,e,!0))}const ee=()=>{throw new Error("not implemented")};function ne(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(void 0!==i)return i;const o=t(n,...r);return e.set(n,o),o}}const re=BigInt(0),ie=BigInt(1),oe=BigInt(2),se=BigInt(3),ce=BigInt(4),ae=BigInt(5),ue=BigInt(7),de=BigInt(8),fe=BigInt(9),le=BigInt(16);function he(t,e){const n=t%e;return n>=re?n:e+n}function ye(t,e,n){let r=t;for(;e-- >re;)r*=r,r%=n;return r}function pe(t,e){if(t===re)throw new Error("invert: expected non-zero number");if(e<=re)throw new Error("invert: expected positive modulus, got "+e);let n=he(t,e),r=e,i=re,o=ie,s=ie,c=re;for(;n!==re;){const t=r/n,e=r%n,a=i-s*t,u=o-c*t;r=n,n=e,i=s,o=c,s=a,c=u}if(r!==ie)throw new Error("invert: does not exist");return he(i,e)}function we(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function ge(t,e){const n=(t.ORDER+ie)/ce,r=t.pow(e,n);return we(t,r,e),r}function be(t,e){const n=(t.ORDER-ae)/de,r=t.mul(e,oe),i=t.pow(r,n),o=t.mul(e,i),s=t.mul(t.mul(o,oe),i),c=t.mul(o,t.sub(s,t.ONE));return we(t,c,e),c}function me(t){if(t<se)throw new Error("sqrt is not defined for small field");let e=t-ie,n=0;for(;e%oe===re;)e/=oe,n++;let r=oe;const i=xe(t);for(;1===Ie(i,r);)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===n)return ge;let o=i.pow(r,e);const s=(e+ie)/oe;return function(t,r){if(t.is0(r))return r;if(1!==Ie(t,r))throw new Error("Cannot find square root");let i=n,c=t.mul(t.ONE,o),a=t.pow(r,e),u=t.pow(r,s);for(;!t.eql(a,t.ONE);){if(t.is0(a))return t.ZERO;let e=1,n=t.sqr(a);for(;!t.eql(n,t.ONE);)if(e++,n=t.sqr(n),e===i)throw new Error("Cannot find square root");const r=ie<<BigInt(i-e-1),o=t.pow(c,r);i=e,c=t.sqr(o),a=t.mul(a,c),u=t.mul(u,o)}return u}}const ve=(t,e)=>(he(t,e)&ie)===ie,ke=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ee(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((e,n,i)=>t.is0(n)?e:(r[i]=e,t.mul(e,n)),t.ONE),o=t.inv(i);return e.reduceRight((e,n,i)=>t.is0(n)?e:(r[i]=t.mul(e,r[i]),t.mul(e,n)),o),r}function Ie(t,e){const n=(t.ORDER-ie)/oe,r=t.pow(e,n),i=t.eql(r,t.ONE),o=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function xe(t,e,n=!1,r={}){if(t<=re)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s,c=!1;if("object"==typeof e&&null!=e){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const t=e;t.BITS&&(i=t.BITS),t.sqrt&&(o=t.sqrt),"boolean"==typeof t.isLE&&(n=t.isLE),"boolean"==typeof t.modFromBytes&&(c=t.modFromBytes),s=t.allowedLengths}else"number"==typeof e&&(i=e),r.sqrt&&(o=r.sqrt);const{nBitLength:a,nByteLength:u}=function(t,e){void 0!==e&&z(e);const n=void 0!==e?e:t.toString(2).length;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d;const f=Object.freeze({ORDER:t,isLE:n,BITS:a,BYTES:u,MASK:Qt(a),ZERO:re,ONE:ie,allowedLengths:s,create:e=>he(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("invalid field element: expected bigint, got "+typeof e);return re<=e&&e<t},is0:t=>t===re,isValidNot0:t=>!f.is0(t)&&f.isValid(t),isOdd:t=>(t&ie)===ie,neg:e=>he(-e,t),eql:(t,e)=>t===e,sqr:e=>he(e*e,t),add:(e,n)=>he(e+n,t),sub:(e,n)=>he(e-n,t),mul:(e,n)=>he(e*n,t),pow:(t,e)=>function(t,e,n){if(n<re)throw new Error("invalid exponent, negatives unsupported");if(n===re)return t.ONE;if(n===ie)return e;let r=t.ONE,i=e;for(;n>re;)n&ie&&(r=t.mul(r,i)),i=t.sqr(i),n>>=ie;return r}(f,t,e),div:(e,n)=>he(e*pe(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>pe(e,t),sqrt:o||(e=>{return d||(d=(n=t)%ce===se?ge:n%de===ae?be:n%le===fe?function(t){const e=xe(t),n=me(t),r=n(e,e.neg(e.ONE)),i=n(e,r),o=n(e,e.neg(r)),s=(t+ue)/le;return(t,e)=>{let n=t.pow(e,s),c=t.mul(n,r);const a=t.mul(n,i),u=t.mul(n,o),d=t.eql(t.sqr(c),e),f=t.eql(t.sqr(a),e);n=t.cmov(n,c,d),c=t.cmov(u,a,f);const l=t.eql(t.sqr(c),e),h=t.cmov(n,c,l);return we(t,h,e),h}}(n):me(n)),d(f,e);var n}),toBytes:t=>n?Wt(t,u):Gt(t,u),fromBytes:(e,r=!0)=>{if(s){if(!s.includes(e.length)||e.length>u)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);const t=new Uint8Array(u);t.set(e,n?0:t.length-e.length),e=t}if(e.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+e.length);let i=n?jt(e):function(t){return Mt(Q(t))}(e);if(c&&(i=he(i,t)),!r&&!f.isValid(i))throw new Error("invalid field element: outside of range 0..ORDER");return i},invertBatch:t=>Ee(f,t),cmov:(t,e,n)=>n?e:t});return Object.freeze(f)}const Ae=BigInt(0),Ne=BigInt(1);function Be(t,e){const n=e.negate();return t?n:e}function Se(t,e){const n=Ee(t.Fp,e.map(t=>t.Z));return e.map((e,r)=>t.fromAffine(e.toAffine(n[r])))}function Oe(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function _e(t,e){Oe(t,e);const n=2**t;return{windows:Math.ceil(e/t)+1,windowSize:2**(t-1),mask:Qt(t),maxNumber:n,shiftBy:BigInt(t)}}function Pe(t,e,n){const{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=n;let c=Number(t&i),a=t>>s;c>r&&(c-=o,a+=Ne);const u=e*r;return{nextN:a,offset:u+Math.abs(c)-1,isZero:0===c,isNeg:c<0,isNegF:e%2!=0,offsetF:u}}const $e=new WeakMap,Ue=new WeakMap;function Re(t){return Ue.get(t)||1}function Le(t){if(t!==Ae)throw new Error("invalid wNAF")}class Te{constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let r=t;for(;e>Ae;)e&Ne&&(n=n.add(r)),r=r.double(),e>>=Ne;return n}precomputeWindow(t,e){const{windows:n,windowSize:r}=_e(e,this.bits),i=[];let o=t,s=o;for(let t=0;t<n;t++){s=o,i.push(s);for(let t=1;t<r;t++)s=s.add(o),i.push(s);o=s.double()}return i}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let r=this.ZERO,i=this.BASE;const o=_e(t,this.bits);for(let t=0;t<o.windows;t++){const{nextN:s,offset:c,isZero:a,isNeg:u,isNegF:d,offsetF:f}=Pe(n,t,o);n=s,a?i=i.add(Be(d,e[f])):r=r.add(Be(u,e[c]))}return Le(n),{p:r,f:i}}wNAFUnsafe(t,e,n,r=this.ZERO){const i=_e(t,this.bits);for(let t=0;t<i.windows&&n!==Ae;t++){const{nextN:o,offset:s,isZero:c,isNeg:a}=Pe(n,t,i);if(n=o,!c){const t=e[s];r=r.add(a?t.negate():t)}}return Le(n),r}getPrecomputes(t,e,n){let r=$e.get(e);return r||(r=this.precomputeWindow(e,t),1!==t&&("function"==typeof n&&(r=n(r)),$e.set(e,r))),r}cached(t,e,n){const r=Re(t);return this.wNAF(r,this.getPrecomputes(r,t,n),e)}unsafe(t,e,n,r){const i=Re(t);return 1===i?this._unsafeLadder(t,e,r):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),e,r)}createCache(t,e){Oe(e,this.bits),Ue.set(t,e),$e.delete(t)}hasCache(t){return 1!==Re(t)}}function Ke(t,e,n,r){(function(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})})(n,t),function(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}(r,e);const i=n.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,c=function(t){let e;for(e=0;t>zt;t>>=Ht,e+=1);return e}(BigInt(i));let a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);const u=Qt(a),d=new Array(Number(u)+1).fill(s);let f=s;for(let t=Math.floor((e.BITS-1)/a)*a;t>=0;t-=a){d.fill(s);for(let e=0;e<o;e++){const i=r[e],o=Number(i>>BigInt(t)&u);d[o]=d[o].add(n[e])}let e=s;for(let t=d.length-1,n=s;t>0;t--)n=n.add(d[t]),e=e.add(n);if(f=f.add(e),0!==t)for(let t=0;t<a;t++)f=f.double()}return f}function De(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return function(t){te(t,ke.reduce((t,e)=>(t[e]="function",t),{ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"}))}(e),e}return xe(t,{isLE:n})}const Ve=BigInt(0),Ce=BigInt(1),ze=BigInt(2),He=BigInt(8);class qe{constructor(t){this.ep=t}static fromBytes(t){ee()}static fromHex(t){ee()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return Q(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,e){return this.init(this.ep.precompute(t,e))}toRawBytes(){return this.toBytes()}}function Fe(t){const{CURVE:e,curveOpts:n,hash:r,eddsaOpts:i}=function(t){const e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n={Fp:t.Fp,Fn:xe(e.n,t.nBitLength,!0),uvRatio:t.uvRatio},r={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:n,hash:t.hash,eddsaOpts:r}}(t);return function(t,e){const n=e.Point;return Object.assign({},e,{ExtendedPoint:n,CURVE:t,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}(t,function(t,e,n={}){if("function"!=typeof e)throw new Error('"hash" function param is required');te(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:o,Fn:s}=t,c=n.randomBytes||ct,a=n.adjustScalarBytes||(t=>t),u=n.domain||((t,e,n)=>{if(qt(n,"phflag"),e.length||n)throw new Error("Contexts/pre-hash are not supported");return t});function d(t){return s.create(jt(t))}function f(t){const{head:n,prefix:r,scalar:o}=function(t){const n=w.secretKey;t=Yt("private key",t,n);const r=Yt("hashed private key",e(t),2*n),i=a(r.slice(0,n));return{head:i,prefix:r.slice(n,2*n),scalar:d(i)}}(t),s=i.multiply(o),c=s.toBytes();return{head:n,prefix:r,scalar:o,point:s,pointBytes:c}}function l(t){return f(t).pointBytes}function h(t=Uint8Array.of(),...n){const i=it(...n);return d(e(u(i,Yt("context",t),!!r)))}const y={zip215:!0},p=o.BYTES,w={secretKey:p,publicKey:p,signature:2*p,seed:p};function g(t=c(w.seed)){return Ft(t,w.seed,"seed")}const b={getExtendedPublicKey:f,randomSecretKey:g,isValidSecretKey:function(t){return C(t)&&t.length===s.BYTES},isValidPublicKey:function(e,n){try{return!!t.fromBytes(e,n)}catch(t){return!1}},toMontgomery(e){const{y:n}=t.fromBytes(e),r=w.publicKey,i=32===r;if(!i&&57!==r)throw new Error("only defined for 25519 and 448");const s=i?o.div(Ce+n,Ce-n):o.div(n-Ce,n+Ce);return o.toBytes(s)},toMontgomerySecret(t){const n=w.secretKey;Ft(t,n);const r=e(t.subarray(0,n));return a(r).subarray(0,n)},randomPrivateKey:g,precompute:(e=8,n=t.BASE)=>n.precompute(e,!1)};return Object.freeze({keygen:function(t){const e=b.randomSecretKey(t);return{secretKey:e,publicKey:l(e)}},getPublicKey:l,sign:function(t,e,n={}){t=Yt("message",t),r&&(t=r(t));const{prefix:o,scalar:c,pointBytes:a}=f(e),u=h(n.context,o,t),d=i.multiply(u).toBytes(),l=h(n.context,d,a,t),y=s.create(u+l*c);if(!s.isValid(y))throw new Error("sign failed: invalid s");return Ft(it(d,s.toBytes(y)),w.signature,"result")},verify:function(e,n,o,s=y){const{context:c,zip215:a}=s,u=w.signature;e=Yt("signature",e,u),n=Yt("message",n),o=Yt("publicKey",o,w.publicKey),void 0!==a&&qt(a,"zip215"),r&&(n=r(n));const d=u/2,f=e.subarray(0,d),l=jt(e.subarray(d,u));let p,g,b;try{p=t.fromBytes(o,a),g=t.fromBytes(f,a),b=i.multiplyUnsafe(l)}catch(t){return!1}if(!a&&p.isSmallOrder())return!1;const m=h(c,g.toBytes(),p.toBytes(),n);return g.add(p.multiplyUnsafe(m)).subtract(b).clearCofactor().is0()},utils:b,Point:t,lengths:w})}(function(t,e={}){const n=function(t,e,n={},r){if(void 0===r&&(r="edwards"===t),!e||"object"!=typeof e)throw new Error(`expected valid ${t} CURVE object`);for(const t of["p","n","h"]){const n=e[t];if(!("bigint"==typeof n&&n>Ae))throw new Error(`CURVE.${t} must be positive bigint`)}const i=De(e.p,n.Fp,r),o=De(e.n,n.Fn,r),s=["Gx","Gy","a","weierstrass"===t?"b":"d"];for(const t of s)if(!i.isValid(e[t]))throw new Error(`CURVE.${t} must be valid field element of CURVE.Fp`);return{CURVE:e=Object.freeze(Object.assign({},e)),Fp:i,Fn:o}}("edwards",t,e,e.FpFnLE),{Fp:r,Fn:i}=n;let o=n.CURVE;const{h:s}=o;te(e,{},{uvRatio:"function"});const c=ze<<BigInt(8*i.BYTES)-Ce,a=t=>r.create(t),u=e.uvRatio||((t,e)=>{try{return{isValid:!0,value:r.sqrt(r.div(t,e))}}catch(t){return{isValid:!1,value:Ve}}});if(!function(t,e,n,r){const i=t.sqr(n),o=t.sqr(r),s=t.add(t.mul(e.a,i),o),c=t.add(t.ONE,t.mul(e.d,t.mul(i,o)));return t.eql(s,c)}(r,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function d(t,e,n=!1){return Jt("coordinate "+t,e,n?Ce:Ve,c),e}function f(t){if(!(t instanceof y))throw new Error("ExtendedPoint expected")}const l=ne((t,e)=>{const{X:n,Y:i,Z:o}=t,s=t.is0();null==e&&(e=s?He:r.inv(o));const c=a(n*e),u=a(i*e),d=r.mul(o,e);if(s)return{x:Ve,y:Ce};if(d!==Ce)throw new Error("invZ was invalid");return{x:c,y:u}}),h=ne(t=>{const{a:e,d:n}=o;if(t.is0())throw new Error("bad point: ZERO");const{X:r,Y:i,Z:s,T:c}=t,u=a(r*r),d=a(i*i),f=a(s*s),l=a(f*f),h=a(u*e);if(a(f*a(h+d))!==a(l+a(n*a(u*d))))throw new Error("bad point: equation left != right (1)");if(a(r*i)!==a(s*c))throw new Error("bad point: equation left != right (2)");return!0});class y{constructor(t,e,n,r){this.X=d("x",t),this.Y=d("y",e),this.Z=d("z",n,!0),this.T=d("t",r),Object.freeze(this)}static CURVE(){return o}static fromAffine(t){if(t instanceof y)throw new Error("extended point not allowed");const{x:e,y:n}=t||{};return d("x",e),d("y",n),new y(e,n,Ce,a(e*n))}static fromBytes(t,e=!1){const n=r.BYTES,{a:i,d:s}=o;t=Zt(Ft(t,n,"point")),qt(e,"zip215");const d=Zt(t),f=t[n-1];d[n-1]=-129&f;const l=jt(d),h=e?c:r.ORDER;Jt("point.y",l,Ve,h);const p=a(l*l),w=a(p-Ce),g=a(s*p-i);let{isValid:b,value:m}=u(w,g);if(!b)throw new Error("bad point: invalid y coordinate");const v=(m&Ce)===Ce,k=!!(128&f);if(!e&&m===Ve&&k)throw new Error("bad point: x=0 and x_0=1");return k!==v&&(m=a(-m)),y.fromAffine({x:m,y:l})}static fromHex(t,e=!1){return y.fromBytes(Yt("point",t),e)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(t=8,e=!0){return p.createCache(this,t),e||this.multiply(ze),this}assertValidity(){h(this)}equals(t){f(t);const{X:e,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=t,c=a(e*s),u=a(i*r),d=a(n*s),l=a(o*r);return c===u&&d===l}is0(){return this.equals(y.ZERO)}negate(){return new y(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:t}=o,{X:e,Y:n,Z:r}=this,i=a(e*e),s=a(n*n),c=a(ze*a(r*r)),u=a(t*i),d=e+n,f=a(a(d*d)-i-s),l=u+s,h=l-c,p=u-s,w=a(f*h),g=a(l*p),b=a(f*p),m=a(h*l);return new y(w,g,m,b)}add(t){f(t);const{a:e,d:n}=o,{X:r,Y:i,Z:s,T:c}=this,{X:u,Y:d,Z:l,T:h}=t,p=a(r*u),w=a(i*d),g=a(c*n*h),b=a(s*l),m=a((r+i)*(u+d)-p-w),v=b-g,k=b+g,E=a(w-e*p),I=a(m*v),x=a(k*E),A=a(m*E),N=a(v*k);return new y(I,x,N,A)}subtract(t){return this.add(t.negate())}multiply(t){if(!i.isValidNot0(t))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:e,f:n}=p.cached(this,t,t=>Se(y,t));return Se(y,[e,n])[0]}multiplyUnsafe(t,e=y.ZERO){if(!i.isValid(t))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return t===Ve?y.ZERO:this.is0()||t===Ce?this:p.unsafe(this,t,t=>Se(y,t),e)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return p.unsafe(this,o.n).is0()}toAffine(t){return l(this,t)}clearCofactor(){return s===Ce?this:this.multiplyUnsafe(s)}toBytes(){const{x:t,y:e}=this.toAffine(),n=r.toBytes(e);return n[n.length-1]|=t&Ce?128:0,n}toHex(){return Q(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(t){return Se(y,t)}static msm(t,e){return Ke(y,i,t,e)}_setWindowSize(t){this.precompute(t)}toRawBytes(){return this.toBytes()}}y.BASE=new y(o.Gx,o.Gy,Ce,a(o.Gx*o.Gy)),y.ZERO=new y(Ve,Ce,Ce,Ve),y.Fp=r,y.Fn=i;const p=new Te(y,i.BITS);return y.BASE.precompute(8),y}(e,n),r,i))}nt("HashToScalar-");const Me=BigInt(0),je=BigInt(1),Ge=BigInt(2);const We=BigInt(0),Ye=BigInt(1),Ze=BigInt(2),Xe=BigInt(3),Je=BigInt(5),Qe=BigInt(8),tn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),en=(()=>({p:tn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Qe,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")}))();function nn(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),o=tn,s=t*t%o*t%o,c=ye(s,Ze,o)*s%o,a=ye(c,Ye,o)*t%o,u=ye(a,Je,o)*a%o,d=ye(u,e,o)*u%o,f=ye(d,n,o)*d%o,l=ye(f,r,o)*f%o,h=ye(l,i,o)*l%o,y=ye(h,i,o)*l%o,p=ye(y,e,o)*u%o;return{pow_p_5_8:ye(p,Ze,o)*t%o,b2:s}}function rn(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const on=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function sn(t,e){const n=tn,r=he(e*e*e,n),i=he(r*r*e,n);let o=he(t*r*nn(t*i).pow_p_5_8,n);const s=he(e*o*o,n),c=o,a=he(o*on,n),u=s===t,d=s===he(-t,n),f=s===he(-t*on,n);return u&&(o=c),(d||f)&&(o=a),ve(o,n)&&(o=he(-o,n)),{isValid:u||d,value:o}}const cn=(()=>xe(en.p,{isLE:!0}))(),an=(()=>xe(en.n,{isLE:!0}))(),un=(()=>({...en,Fp:cn,hash:Ct,adjustScalarBytes:rn,uvRatio:sn}))(),dn=(()=>Fe(un))(),fn=(()=>{const t=cn.ORDER;return function(t){const e=(te(n=t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...n}));var n;const{P:r,type:i,adjustScalarBytes:o,powPminus2:s,randomBytes:c}=e,a="x25519"===i;if(!a&&"x448"!==i)throw new Error("invalid type");const u=c||ct,d=a?255:448,f=a?32:56,l=a?BigInt(9):BigInt(5),h=a?BigInt(121665):BigInt(39081),y=a?Ge**BigInt(254):Ge**BigInt(447),p=a?BigInt(8)*Ge**BigInt(251)-je:BigInt(4)*Ge**BigInt(445)-je,w=y+p+je,g=t=>he(t,r),b=m(l);function m(t){return Wt(g(t),f)}function v(t,e){const n=function(t,e){Jt("u",t,Me,r),Jt("scalar",e,y,w);const n=e,i=t;let o=je,c=Me,a=t,u=je,f=Me;for(let t=BigInt(d-1);t>=Me;t--){const e=n>>t&je;f^=e,({x_2:o,x_3:a}=E(f,o,a)),({x_2:c,x_3:u}=E(f,c,u)),f=e;const r=o+c,s=g(r*r),d=o-c,l=g(d*d),y=s-l,p=a+u,w=g((a-u)*r),b=g(p*d),m=w+b,v=w-b;a=g(m*m),u=g(i*g(v*v)),o=g(s*l),c=g(y*(s+g(h*y)))}({x_2:o,x_3:a}=E(f,o,a)),({x_2:c,x_3:u}=E(f,c,u));const l=s(c);return g(o*l)}(function(t){const e=Yt("u coordinate",t,f);return a&&(e[31]&=127),g(jt(e))}(e),function(t){return jt(o(Yt("scalar",t,f)))}(t));if(n===Me)throw new Error("invalid private or public key received");return m(n)}function k(t){return v(t,b)}function E(t,e,n){const r=g(t*(e-n));return{x_2:e=g(e-r),x_3:n=g(n+r)}}const I={secretKey:f,publicKey:f,seed:f},x=(t=u(f))=>(H(t,I.seed),t);return{keygen:function(t){const e=x(t);return{secretKey:e,publicKey:k(e)}},getSharedSecret:(t,e)=>v(t,e),getPublicKey:t=>k(t),scalarMult:v,scalarMultBase:k,utils:{randomSecretKey:x,randomPrivateKey:x},GuBytes:b.slice(),lengths:I}}({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=nn(e);return he(ye(n,Xe,t)*r,t)},adjustScalarBytes:rn})})(),ln=on,hn=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),yn=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),pn=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),wn=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),gn=t=>sn(Ye,t),bn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),mn=t=>dn.Point.Fp.create(jt(t)&bn);function vn(t){const{d:e}=en,n=tn,r=t=>cn.create(t),i=r(ln*t*t),o=r((i+Ye)*pn);let s=BigInt(-1);const c=r((s-e*i)*r(i+e));let{isValid:a,value:u}=sn(o,c),d=r(u*t);ve(d,n)||(d=r(-d)),a||(u=d),a||(s=i);const f=r(s*(i-Ye)*wn-c),l=u*u,h=r((u+u)*c),y=r(f*hn),p=r(Ye-l),w=r(Ye+l);return new dn.Point(r(h*w),r(p*y),r(y*w),r(h*p))}class kn extends qe{constructor(t){super(t)}static fromAffine(t){return new kn(dn.Point.fromAffine(t))}assertSame(t){if(!(t instanceof kn))throw new Error("RistrettoPoint expected")}init(t){return new kn(t)}static hashToCurve(t){return function(t){H(t,64);const e=vn(mn(t.subarray(0,32))),n=vn(mn(t.subarray(32,64)));return new kn(e.add(n))}(Yt("ristrettoHash",t,64))}static fromBytes(t){H(t,32);const{a:e,d:n}=en,r=tn,i=t=>cn.create(t),o=mn(t);if(!function(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}(cn.toBytes(o),t)||ve(o,r))throw new Error("invalid ristretto255 encoding 1");const s=i(o*o),c=i(Ye+e*s),a=i(Ye-e*s),u=i(c*c),d=i(a*a),f=i(e*n*u-d),{isValid:l,value:h}=gn(i(f*d)),y=i(h*a),p=i(h*y*f);let w=i((o+o)*y);ve(w,r)&&(w=i(-w));const g=i(c*p),b=i(w*g);if(!l||ve(b,r)||g===We)throw new Error("invalid ristretto255 encoding 2");return new kn(new dn.Point(w,g,Ye,b))}static fromHex(t){return kn.fromBytes(Yt("ristrettoHex",t,32))}static msm(t,e){return Ke(kn,dn.Point.Fn,t,e)}toBytes(){let{X:t,Y:e,Z:n,T:r}=this.ep;const i=tn,o=t=>cn.create(t),s=o(o(n+e)*o(n-e)),c=o(t*e),a=o(c*c),{value:u}=gn(o(s*a)),d=o(u*s),f=o(u*c),l=o(d*f*r);let h;if(ve(r*l,i)){let n=o(e*ln),r=o(t*ln);t=n,e=r,h=o(d*yn)}else h=f;ve(t*l,i)&&(e=o(-e));let y=o((n-e)*h);return ve(y,i)&&(y=o(-y)),cn.toBytes(y)}equals(t){this.assertSame(t);const{X:e,Y:n}=this.ep,{X:r,Y:i}=t.ep,o=t=>cn.create(t),s=o(e*i)===o(n*r),c=o(n*i)===o(e*r);return s||c}is0(){return this.equals(kn.ZERO)}}kn.BASE=(()=>new kn(dn.Point.BASE))(),kn.ZERO=(()=>new kn(dn.Point.ZERO))(),kn.Fp=(()=>cn)(),kn.Fn=(()=>an)();class En extends ot{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,q(t);const n=rt(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?t.create().update(n).digest():n);for(let t=0;t<i.length;t++)i[t]^=54;this.iHash.update(i),this.oHash=t.create();for(let t=0;t<i.length;t++)i[t]^=106;this.oHash.update(i),j(i)}update(t){return F(this),this.iHash.update(t),this}digestInto(t){F(this),H(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:e,iHash:n,finished:r,destroyed:i,blockLen:o,outputLen:s}=this;return t.finished=r,t.destroyed=i,t.blockLen=o,t.outputLen=s,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const In=(t,e,n)=>new En(t,e).update(n).digest();In.create=(t,e)=>new En(t,e);const xn=Uint8Array.from([0]),An=Uint8Array.of(),Nn=(t,e,n,r,i)=>function(t,e,n,r=32){q(t),z(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/i);void 0===n&&(n=An);const s=new Uint8Array(o*i),c=In.create(t,e),a=c._cloneInto(),u=new Uint8Array(c.outputLen);for(let t=0;t<o;t++)xn[0]=t+1,a.update(0===t?An:u).update(n).update(xn).digestInto(u),s.set(u,i*t),c._cloneInto(a);return c.destroy(),a.destroy(),j(u,xn),s.slice(0,r)}(t,function(t,e,n){return q(t),void 0===n&&(n=new Uint8Array(t.outputLen)),In(t,rt(n),rt(e))}(t,e,n),r,i),Bn=Vt;class Sn extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const e=super.get(t);return super.has(t)&&void 0!==e&&(this.delete(t),super.set(t,e)),e}set(t,e){if(super.set(t,e),this.maxSize&&this.size>this.maxSize){const t=this.keys().next().value;t&&this.delete(t)}return this}}const On="2.45.1";let _n=({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,Pn=`viem@${On}`;class $n extends Error{constructor(t,e={}){const n=e.cause instanceof $n?e.cause.details:e.cause?.message?e.cause.message:e.details,r=e.cause instanceof $n&&e.cause.docsPath||e.docsPath,i=_n?.({...e,docsPath:r});super([t||"An error occurred.","",...e.metaMessages?[...e.metaMessages,""]:[],...i?[`Docs: ${i}`]:[],...n?[`Details: ${n}`]:[],...Pn?[`Version: ${Pn}`]:[]].join("\n"),e.cause?{cause:e.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=r,this.metaMessages=e.metaMessages,this.name=e.name??this.name,this.shortMessage=t,this.version=On}walk(t){return Un(this,t)}}function Un(t,e){return e?.(t)?t:t&&"object"==typeof t&&"cause"in t&&void 0!==t.cause?Un(t.cause,e):e?null:t}class Rn extends $n{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}function Ln(t,{strict:e=!0}={}){return!!t&&"string"==typeof t&&(e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x"))}class Tn extends $n{constructor({size:t,targetSize:e,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${e}).`,{name:"SizeExceedsPaddingSizeError"})}}function Kn(t,{dir:e,size:n=32}={}){return"string"==typeof t?function(t,{dir:e,size:n=32}={}){if(null===n)return t;const r=t.replace("0x","");if(r.length>2*n)throw new Tn({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r["right"===e?"padEnd":"padStart"](2*n,"0")}`}(t,{dir:e,size:n}):function(t,{dir:e,size:n=32}={}){if(null===n)return t;if(t.length>n)throw new Tn({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const o="right"===e;r[o?i:n-i-1]=t[o?i:t.length-i-1]}return r}(t,{dir:e,size:n})}class Dn extends $n{constructor({max:t,min:e,signed:n,size:r,value:i}){super(`Number "${i}" is not in safe ${r?`${8*r}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${e} to ${t})`:`(above ${e})`}`,{name:"IntegerOutOfRangeError"})}}class Vn extends $n{constructor({givenSize:t,maxSize:e}){super(`Size cannot exceed ${e} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}function Cn(t){return Ln(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}function zn(t,{size:e}){if(Cn(t)>e)throw new Vn({givenSize:Cn(t),maxSize:e})}function Hn(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let o;r?o=n?(1n<<8n*BigInt(r)-1n)-1n:2n**(8n*BigInt(r))-1n:"number"==typeof t&&(o=BigInt(Number.MAX_SAFE_INTEGER));const s="bigint"==typeof o&&n?-o-1n:0;if(o&&i>o||i<s){const e="bigint"==typeof t?"n":"";throw new Dn({max:o?`${o}${e}`:void 0,min:`${s}${e}`,signed:n,size:r,value:`${t}${e}`})}const c=`0x${(n&&i<0?(1n<<BigInt(8*r))+BigInt(i):i).toString(16)}`;return r?Kn(c,{size:r}):c}const qn=new TextEncoder;const Fn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Mn(t){return t>=Fn.zero&&t<=Fn.nine?t-Fn.zero:t>=Fn.A&&t<=Fn.F?t-(Fn.A-10):t>=Fn.a&&t<=Fn.f?t-(Fn.a-10):void 0}function jn(t,e={}){let n=t;e.size&&(zn(n,{size:e.size}),n=Kn(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,o=new Uint8Array(i);for(let t=0,e=0;t<i;t++){const n=Mn(r.charCodeAt(e++)),i=Mn(r.charCodeAt(e++));if(void 0===n||void 0===i)throw new $n(`Invalid byte sequence ("${r[e-2]}${r[e-1]}" in "${r}").`);o[t]=16*n+i}return o}function Gn(t,e={}){const n=qn.encode(t);return"number"==typeof e.size?(zn(n,{size:e.size}),Kn(n,{dir:"right",size:e.size})):n}const Wn=BigInt(0),Yn=BigInt(1),Zn=BigInt(2),Xn=BigInt(7),Jn=BigInt(256),Qn=BigInt(113),tr=[],er=[],nr=[];for(let t=0,e=Yn,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],tr.push(2*(5*r+n)),er.push((t+1)*(t+2)/2%64);let i=Wn;for(let t=0;t<7;t++)e=(e<<Yn^(e>>Xn)*Qn)%Jn,e&Zn&&(i^=Yn<<(Yn<<BigInt(t))-Yn);nr.push(i)}const rr=wt(nr,!0),ir=rr[0],or=rr[1],sr=(t,e,n)=>n>32?((t,e,n)=>e<<n-32|t>>>64-n)(t,e,n):((t,e,n)=>t<<n|e>>>32-n)(t,e,n),cr=(t,e,n)=>n>32?((t,e,n)=>t<<n-32|e>>>64-n)(t,e,n):((t,e,n)=>e<<n|t>>>32-n)(t,e,n);class ar extends ot{constructor(t,e,n,r=!1,i=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=t,this.suffix=e,this.outputLen=n,this.enableXOF=r,this.rounds=i,z(n),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");var o;this.state=new Uint8Array(200),this.state32=(o=this.state,new Uint32Array(o.buffer,o.byteOffset,Math.floor(o.byteLength/4)))}clone(){return this._cloneInto()}keccak(){Z(this.state32),function(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let e=0;e<10;e++)n[e]=t[e]^t[e+10]^t[e+20]^t[e+30]^t[e+40];for(let e=0;e<10;e+=2){const r=(e+8)%10,i=(e+2)%10,o=n[i],s=n[i+1],c=sr(o,s,1)^n[r],a=cr(o,s,1)^n[r+1];for(let n=0;n<50;n+=10)t[e+n]^=c,t[e+n+1]^=a}let e=t[2],i=t[3];for(let n=0;n<24;n++){const r=er[n],o=sr(e,i,r),s=cr(e,i,r),c=tr[n];e=t[c],i=t[c+1],t[c]=o,t[c+1]=s}for(let e=0;e<50;e+=10){for(let r=0;r<10;r++)n[r]=t[e+r];for(let r=0;r<10;r++)t[e+r]^=~n[(r+2)%10]&n[(r+4)%10]}t[0]^=ir[r],t[1]^=or[r]}j(n)}(this.state32,this.rounds),Z(this.state32),this.posOut=0,this.pos=0}update(t){F(this),H(t=rt(t));const{blockLen:e,state:n}=this,r=t.length;for(let i=0;i<r;){const o=Math.min(e-this.pos,r-i);for(let e=0;e<o;e++)n[this.pos++]^=t[i++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:n,blockLen:r}=this;t[n]^=e,128&e&&n===r-1&&this.keccak(),t[r-1]^=128,this.keccak()}writeInto(t){F(this,!1),H(t),this.finish();const e=this.state,{blockLen:n}=this;for(let r=0,i=t.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);t.set(e.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return z(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(M(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,j(this.state)}_cloneInto(t){const{blockLen:e,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return t||(t=new ar(e,n,r,o,i)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=i,t.suffix=n,t.outputLen=r,t.enableXOF=o,t.destroyed=this.destroyed,t}}const ur=(()=>{return t=1,e=136,n=32,st(()=>new ar(e,t,n));var t,e,n})(),dr=new Sn(8192);function fr(t,e){if(dr.has(`${t}.${e}`))return dr.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=function(t){const e=ur(Ln(t,{strict:!1})?function(t,e={}){return"number"==typeof t||"bigint"==typeof t?function(t,e){return jn(Hn(t,e))}(t,e):"boolean"==typeof t?function(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),"number"==typeof e.size?(zn(n,{size:e.size}),Kn(n,{size:e.size})):n}(t,e):Ln(t)?jn(t,e):Gn(t,e)}(t):t);return e}(Gn(n)),i=(e?n.substring(`${e}0x`.length):n).split("");for(let t=0;t<40;t+=2)r[t>>1]>>4>=8&&i[t]&&(i[t]=i[t].toUpperCase()),(15&r[t>>1])>=8&&i[t+1]&&(i[t+1]=i[t+1].toUpperCase());const o=`0x${i.join("")}`;return dr.set(`${t}.${e}`,o),o}const lr=/^0x[a-fA-F0-9]{40}$/,hr=new Sn(8192);function yr(t,e){const{strict:n=!0}=e??{},r=`${t}.${n}`;if(hr.has(r))return hr.get(r);const i=!(!lr.test(t)||t.toLowerCase()!==t&&n&&fr(t)!==t);return hr.set(r,i),i}var pr=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function wr(t){return"*"===t?"ALL":t.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function gr(t){return t.slice(10,t.indexOf("/"))}function br(t){return t.slice(t.indexOf("/")+1)}function mr(t){const e={};for(const n of pr)gr(n.urn)===t&&(e[wr(br(n.urn))]=n.urn);return e}var vr=mr("kv"),kr={...mr("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},Er=(mr("duckdb"),mr("capabilities")),Ir=(mr("hooks"),mr("encryption")),xr=mr("space"),Ar="applications",Nr="account",Br="applications/",Sr="secrets",Or="default",_r="public",Pr="agents",$r="tinycloud.encryption",Ur=Ir.NETWORK_CREATE,Rr=[Or,Ar,Nr,Sr,_r,Pr],Lr={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:Or,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Or,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:Or,path:"",actions:["read","write"]}]},Tr={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:Ar,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Ar,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:Ar,path:"",actions:["read","write"]}]},Kr={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:Nr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Nr,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:Nr,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:Nr,path:"account",actions:["read","write","schema"]}]},Dr={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:Sr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:Sr,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:Sr,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:Sr,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:Sr,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:Sr,path:"",actions:["read"],skipPrefix:!0}]},Vr={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:_r,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:_r,path:"",actions:["get","list","metadata"]}]},Cr={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:Pr,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:Pr,path:"",actions:["get","put","del","list","metadata"]}]},zr={[Or]:Lr,[Ar]:Tr,[Nr]:Kr,[Sr]:Dr,[_r]:Vr,[Pr]:Cr};function Hr(t,e=1){return function(t){if(!Number.isSafeInteger(t)||t<=0)throw new Error(`Invalid EIP-155 chain ID: ${t}`)}(e),`did:pkh:eip155:${e}:${function(t){if(!yr(t,{strict:!1}))throw new Error(`Invalid EVM address: ${t}`);return function(t){if(!yr(t,{strict:!1}))throw new Rn({address:t});return fr(t,void 0)}(t)}(t)}`}function qr(t){return{...t,permissions:t.permissions?.map(t=>({...t,actions:[...t.actions]}))}}function Fr(t,e,n){return!0===n||""===t||""===e?e:"/"===e?`${t}/`:`${t.endsWith("/")?t.slice(0,-1):t}/${e.startsWith("/")?e.slice(1):e}`}function Mr(t,e,n){if("tinycloud.vault"===t.service)return function(t){return t.actions.map(e=>{const n=e.startsWith("tinycloud.vault/")?e.slice(16):e.startsWith("tinycloud.kv/")?e.slice(13):e,r="read"===n||"get"===n?vr.GET:"write"===n||"put"===n?vr.PUT:"delete"===n||"del"===n?vr.DEL:"list"===n?vr.LIST:"metadata"===n?vr.METADATA:void 0;if(void 0===r)throw new Error(`unknown vault action ${JSON.stringify(e)}`);const i=t.path.startsWith("/")?t.path.slice(1):t.path;return{...t,service:"tinycloud.kv",path:`vault/${i}`,actions:[r],skipPrefix:!0}})}(t).flatMap(t=>Mr(t,e,n));const r=!0===t.skipPrefix||t.service===$r;return[{service:t.service,space:t.service===$r?"encryption":t.space??n,path:Fr(e,t.path,r),actions:t.actions.map(e=>function(t,e){return e.includes("/")?e:`${t}/${e}`}(t.service,e)),...void 0!==t.description?{description:t.description}:{}}]}function jr(t){const e=new Set(t.filter(t=>t.service!==$r).map(t=>t.space));return function(t){const e=new Map;for(const n of t){const t=`${n.service}\0${n.space}\0${n.path}`,r=e.get(t);if(r)for(const t of n.actions)r.actions.includes(t)||r.actions.push(t);else e.set(t,{...n,actions:[...n.actions]})}return[...e.values()]}([...t,...[...e].map(t=>({service:"tinycloud.capabilities",space:t,path:"",actions:[Er.READ]}))])}function Gr(t){return function(t,e={}){if(!Array.isArray(t)||0===t.length)throw new Error("composeManifestRequest requires at least one manifest");const n=e.includeAccountRegistryPermissions??!0,r=t.map(qr),i=r.flatMap(t=>{const e=t.prefix??t.app_id,n=t.space??Ar;return(t.permissions??[]).flatMap(t=>Mr(t,e,n))});n&&i.push(...Wr.map(t=>({...t,actions:[...t.actions]})));const o=new Map;for(const t of r){const e=o.get(t.app_id)??[];e.push(qr(t)),o.set(t.app_id,e)}return{manifests:r,resources:jr(i),delegationTargets:[],registryRecords:n?[...o.entries()].map(([t,e])=>({key:`${Br}${t}`,app_id:t,manifests:e})):[],expiryMs:2592e6,includePublicSpace:r.some(t=>t.includePublicSpace??!0)}}([zr[t]],{includeAccountRegistryPermissions:!1})}Rr.map(t=>({name:t,manifest:zr[t],persistedAsApplication:t===Sr}));var Wr=Object.freeze([{service:"tinycloud.kv",space:Nr,path:Br,actions:[vr.GET,vr.PUT,vr.LIST]},{service:"tinycloud.kv",space:Nr,path:"spaces/",actions:[vr.GET,vr.PUT,vr.LIST]},{service:"tinycloud.kv",space:Nr,path:"system/bootstrap/complete",actions:[vr.GET,vr.PUT]},{service:"tinycloud.delegation",space:Nr,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:Nr,path:"account",actions:[kr.READ,kr.WRITE,kr.SCHEMA]},{service:"tinycloud.capabilities",space:Nr,path:"",actions:[Er.READ]}]),Yr=Gr(Or),Zr={...Yr,resources:[...Yr.resources,...Wr.map(t=>({...t,actions:[...t.actions]}))]},Xr=Object.freeze(Object.fromEntries(Rr.map(t=>[t,t===Or?Zr:Gr(t)]))),Jr=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[Ur]}]);function Qr(t){return void 0===t?"":ti(t)}function ti(t){if(null===t)return"null";switch(typeof t){case"boolean":case"number":case"string":return JSON.stringify(t);case"object":{if(Array.isArray(t))return`[${t.map(ti).join(",")}]`;const e=Object.keys(t).sort(),n=[];for(const r of e){const e=t[r];void 0!==e&&n.push(`${JSON.stringify(r)}:${ti(e)}`)}return`{${n.join(",")}}`}default:throw new TypeError("canonicalize: unsupported value type "+typeof t)}}Object.freeze(Rr.flatMap(t=>[{kind:"session",service:"tinycloud.session",space:t,actions:["siwe"],resources:Xr[t].resources,...t===Nr?{rawAbilities:Jr}:{}},{kind:"space/host",service:"tinycloud.space",space:t,actions:[xr.HOST]}]));var ei="0123456789abcdef";function ni(t){let e="";for(let n=0;n<t.length;n++){const r=t[n];e+=ei[r>>4&15]+ei[15&r]}return e}function ri(t){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n="";for(let r=0;r<t.length;r+=3){const i=t[r],o=r+1<t.length?t[r+1]:0,s=r+2<t.length?t[r+2]:0;n+=e[i>>2&63],n+=e[63&(i<<4|o>>4)],n+=r+1<t.length?e[63&(o<<2|s>>6)]:"=",n+=r+2<t.length?e[63&s]:"="}return n}function ii(t){const e=t.replace(/[^A-Za-z0-9+/=]/g,""),n=e.length;if(n%4!=0)throw new Error("invalid base64 input");const r=n/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0),i=new Uint8Array(r),o={};for(let t=0;t<64;t++)o["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[t]]=t;let s=0;for(let t=0;t<n;t+=4){const n=o[e[t]]??0,c=o[e[t+1]]??0,a="="===e[t+2]?0:o[e[t+2]]??0,u=n<<2|c>>4,d=(15&c)<<4|a>>2,f=(3&a)<<6|("="===e[t+3]?0:o[e[t+3]]??0);s<r&&(i[s++]=u),s<r&&(i[s++]=d),s<r&&(i[s++]=f)}return i}function oi(t){return(new TextEncoder).encode(t)}function si(t,e){return ni(t(oi(Qr(e))))}var ci="urn:tinycloud:encryption:",ai=/^[a-z0-9][a-z0-9-]*$/,ui=class extends Error{constructor(t){super(t),this.name="NetworkIdError"}};function di(t){if("string"!=typeof t||0===t.length)throw new ui("networkId must be a non-empty string");if(!t.startsWith(ci))throw new ui(`networkId must start with ${ci} (got ${JSON.stringify(t)})`);const e=t.slice(25),n=e.lastIndexOf(":");if(n<=0||n===e.length-1)throw new ui(`networkId missing ownerDid or name segment (got ${JSON.stringify(t)})`);const r=e.slice(0,n),i=e.slice(n+1);if(!r.startsWith("did:"))throw new ui(`networkId ownerDid must be a DID (got ${JSON.stringify(r)})`);const o=r.split(":");if(o.length<3||o.some(t=>0===t.length))throw new ui(`networkId ownerDid is not a well-formed DID (got ${JSON.stringify(r)})`);if(!ai.test(i))throw new ui(`networkId name ${JSON.stringify(i)} must match ${ai.source}`);return{networkId:t,ownerDid:r,name:i}}var fi=ci,li="tinycloud.encryption.decrypt/v1",hi="tinycloud.encryption.decrypt-result/v1",yi="tinycloud.encryption/decrypt";function pi(t){switch(t.code){case"NETWORK_NOT_FOUND":return t.message??`Network not found: ${t.networkId??t.name??"<unknown>"}`;case"NETWORK_NOT_ACTIVE":return t.message??`Network not active (state=${t.state})`;case"INVALID_NETWORK_ID":case"INVALID_ENVELOPE":case"DECRYPT_DENIED":case"INVALID_RESPONSE":case"INVALID_INPUT":return t.message;case"RESPONSE_SIGNATURE_INVALID":return t.message??"Node response signature failed to verify";case"RESPONSE_BINDING_MISMATCH":return t.message??`Node response binding mismatch on field ${JSON.stringify(t.field)}`;case"TRANSPORT_ERROR":return t.message??t.cause.message;default:return t.message??t.code}}function wi(t){return{...t,service:"encryption",message:pi(t)}}var gi="x25519-hkdf-aes256gcm/v2",bi=oi("TCW2"),mi=oi("tinycloud.encryption.key-wrap/v2");function vi(...t){const e=new Uint8Array(t.reduce((t,e)=>t+e.length,0));let n=0;for(const r of t)e.set(r,n),n+=r.length;return e}function ki(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return 0===n}function Ei(t){if("string"!=typeof t)throw new Error("Invalid key wrap encoding");const e=ii(t);if(32!==e.length||ri(e)!==t)throw new Error("Invalid key wrap encoding");return e}function Ii(t){for(let e=0;e<t.length;e++){const n=t.charCodeAt(e);if(n>=55296&&n<=56319){const n=t.charCodeAt(++e);if(!(n>=56320&&n<=57343))return!1}else if(n>=56320&&n<=57343)return!1}return!0}function xi(t){if("network-key"!==t.purpose&&"receiver-key"!==t.purpose||"string"!=typeof t.networkId||"string"!=typeof t.keyPath||!Ii(t.networkId)||!Ii(t.keyPath)||!Number.isSafeInteger(t.keyVersion)||t.keyVersion<=0||!t.metadata||"object"!=typeof t.metadata||Array.isArray(t.metadata)||Object.entries(t.metadata).some(([t,e])=>!Ii(t)||"string"!=typeof e||!Ii(e)))throw new Error("Invalid key wrap context");if(""!==t.networkId){const e=function(t){const e=t.lastIndexOf(":"),n=t.slice(e+1),r=n.indexOf("/"),i=-1===r?n:n.slice(0,r),o=di(-1===r?t:`${t.slice(0,e+1)}${i}`);if(-1===r)return o;const s=n.slice(r+1),c=s.split("/"),a=s.endsWith("/");if(0===s.length||/[\u0000-\u001f\u007f\\]/.test(s)||c.some((t,e)=>"."===t||".."===t||0===t.length&&!(a&&e===c.length-1)))throw new ui(`encryption resource has an invalid keyPath (got ${JSON.stringify(t)})`);return{...o,keyPath:s}}(""===t.keyPath?t.networkId:`${t.networkId}/${t.keyPath}`);if(e.networkId!==t.networkId||(e.keyPath??"")!==t.keyPath||t.keyPath.endsWith("/"))throw new Error("Invalid key wrap resource")}}function Ai(t){return t.length>=4&&bi.every((e,n)=>t[n]===e)}function Ni(t){if(!Ai(t)||t.length<8)throw new Error("Invalid v2 key wrap frame");const e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(4);if(0===e||e>65536||t.length<8+e+12+16)throw new Error("Invalid v2 key wrap length");const n=t.subarray(8,8+e),r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n)),i=["v","alg","kdf","aead","salt","ephemeralPublicKey","recipientPublicKey","purpose","networkId","keyPath","keyVersion","metadata"].sort();if(!r||"object"!=typeof r||Array.isArray(r)||Object.keys(r).sort().join(",")!==i.join(",")||2!==r.v||r.alg!==gi||"hkdf-sha256"!==r.kdf||"aes-256-gcm"!==r.aead)throw new Error("Invalid v2 key wrap header");if(xi(r),Ei(r.salt),Ei(r.ephemeralPublicKey),Ei(r.recipientPublicKey),!ki(n,oi(Qr({...r}))))throw new Error("Non-canonical v2 key wrap header");const o=8+e;return{header:r,aad:t.subarray(0,o),nonce:t.subarray(o,o+12),ciphertext:t.subarray(o+12)}}function Bi(t,e){xi(e);for(const n of["purpose","networkId","keyPath","keyVersion"])if(t[n]!==e[n])throw new Error("Key wrap context mismatch");if(Qr(t.metadata)!==Qr(e.metadata))throw new Error("Key wrap metadata mismatch")}function Si(t,e,n=!1){if("x25519-aes256gcm/v1"!==e&&e!==gi)throw new Error("Unsupported key wrap algorithm");if(n&&e!==gi)throw new Error("V2 network key wrap required");if(Ai(t)!==(e===gi))throw new Error("Key wrap algorithm mismatch");e===gi&&Ni(t)}function Oi(t,e=!1){const n=ii(t.encryptedSymmetricKey);Si(n,t.alg,e),t.alg===gi&&Bi(Ni(n).header,{purpose:"network-key",networkId:t.networkId,keyPath:t.keyPath??"",keyVersion:t.keyVersion,metadata:t.metadata??{}})}var _i="[a-z0-9][a-z0-9._-]{0,63}",Pi=new RegExp(`^${_i}(?:/${_i}){0,7}$`),$i=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ui=/^(did:[a-z0-9]+:[A-Za-z0-9._:-]+):([^:/]+)(?:\/(.*))?$/s,Ri="did:pkh:eip155:",Li="tinycloud.encryption/key.create",Ti="tinycloud.encryption/key.block",Ki="tinycloud.encryption/key.unblock",Di=(Object.freeze([yi,Li,Ti,Ki]),class extends Error{constructor(t,e){super(e),this.name="EncryptionResourceError",this.code=t}});function Vi(t){if(!t.startsWith(Ri))return t;const e=t.slice(15),n=e.indexOf(":"),r=-1===n?"":e.slice(0,n),i=-1===n?"":e.slice(n+1);if(!/^\d+$/.test(r)||!/^0x[a-fA-F0-9]{40}$/.test(i))throw new Di("bad_owner",`owner DID is not a valid did:pkh:eip155 (got ${JSON.stringify(t)})`);const o=BigInt(r);if(0n===o||o>18446744073709551615n)throw new Di("bad_owner",`did:pkh:eip155 chain id must be a positive u64 (got ${JSON.stringify(r)})`);const s=Hr(i,1).slice(17);return`${Ri}${o}:${s}`}function Ci(t){const e=Vi(t);if(e!==t)throw new Di("non_canonical_owner",`owner DID is not canonical (expected ${e})`)}function zi(t,e){if(0===t.length)throw new Di("empty_path",`${e} must not be empty`);if((new TextEncoder).encode(t).length>255)throw new Di("path_too_long",`${e} exceeds 255 bytes`);if(!Pi.test(t))throw new Di("bad_path",`${e} ${JSON.stringify(t)} must match ${Pi.source}`);const n=t.split("/");if("apps"===n[0]&&n.length<("key path"===e?3:2))throw new Di("bad_path",`${e} ${JSON.stringify(t)} under apps/ needs ${"key path"===e?"apps/<id>/<name>":"apps/<id>/"}`)}function Hi(t){if("string"!=typeof t||!t.startsWith(fi))throw new Di("not_encryption_urn",`resource must start with ${fi}`);const e=t.slice(25),n=Ui.exec(e);if(null===n)throw new Di("malformed",`resource is not <ownerDid>:<network>[/<path>] (got ${JSON.stringify(t)})`);const r=n[1],i=n[2],o=n[3];if(void 0===o){const t=Vi(r),e=`${fi}${t}:${i}`;try{di(e)}catch(t){if(t instanceof ui)throw new Di("bad_network",t.message);throw t}return{kind:"network",ownerDid:t,network:i,networkId:e}}if(!$i.test(i))throw new Di("bad_network",`network ${JSON.stringify(i)} must match ${$i.source}`);Ci(r);const s=`${fi}${r}:${i}`;if(o.endsWith("/")){const t=o.slice(0,-1);return zi(t,"prefix"),{kind:"prefix",ownerDid:r,network:i,networkId:s,prefix:t}}return zi(o,"key path"),{kind:"key",ownerDid:r,network:i,networkId:s,path:o}}function qi(t){let e="";for(const n of t){const t=n.codePointAt(0);e+=t>=32&&t<=126?n:`\\u{${t.toString(16).toUpperCase().padStart(4,"0")}}`}return e}function Fi(t){const e="string"==typeof t?t:String(t),n=Array.from(e);return qi(n.length>120?`${n.slice(0,120).join("")}...`:e)}var Mi=class extends Error{constructor(t,e,n={}){super(qi(e),void 0===n.cause?void 0:{cause:n.cause}),this.name="NamedKeyError",this.code=t,void 0!==n.status&&(this.status=n.status),void 0!==n.nodeCode&&(this.nodeCode=n.nodeCode),void 0!==n.detail&&(this.detail=n.detail),void 0!==n.rawState&&(this.rawState=n.rawState),void 0!==n.kind&&(this.kind=n.kind),void 0!==n.input&&(this.input=n.input)}},ji=Object.assign(Object.create(null),{key_blocked:"KEY_BLOCKED",key_not_found:"KEY_NOT_FOUND",key_exists:"KEY_EXISTS",network_not_found:"NETWORK_NOT_FOUND",network_not_active:"NETWORK_NOT_ACTIVE",key_limit_exceeded:"KEY_LIMIT_EXCEEDED",deletable_unavailable:"DELETABLE_UNAVAILABLE",key_not_deletable:"KEY_NOT_DELETABLE",key_path_invalid:"KEY_PATH_INVALID",key_unwrap_failed:"KEY_UNWRAP_FAILED",receiver_key_invalid:"RECEIVER_KEY_INVALID"}),Gi=Object.assign(Object.create(null),{key_deleted:!0}),Wi=/^([a-z][a-z0-9_]*):\s?([\s\S]*)$/;function Yi(t,e,n){const r=Wi.exec(e.trim()),i=r?.[1]?.slice(0,64),o=r?.[2]?.trim(),s={status:t,...void 0===i?{}:{nodeCode:i},...void 0===o||0===o.length?{}:{detail:o}};if(void 0!==i){const t=ji[i];if(void 0!==t)return new Mi(t,`${n}: ${i}`,s);if(!0===Gi[i])return new Mi("KEY_UNAVAILABLE",`${n}: key unavailable (${i})`,{...s,rawState:i})}return new Mi("NODE_ERROR",`${n}: node responded ${t}`,s)}function Zi(t){let e;try{e=Hi(t)}catch(e){throw new Mi("INVALID_KEY_TARGET",`not a valid encryption key resource: ${Fi(e instanceof Error?e.message:e)}`,{cause:e,input:t})}if("key"!==e.kind)throw new Mi("INVALID_KEY_TARGET",`a ${e.kind} resource cannot be an invocation target; an exact key is required`,{input:t});return e}function Xi(t){const e=Zi(t.keyResource);return{type:"tinycloud.encryption.key-admin/v1",targetNode:t.targetNode,networkId:e.networkId,keyPath:e.path,action:t.action,bodyHash:si(t.crypto.sha256,t.body)}}function Ji(t){const e=Zi(t.keyResource);return{type:"tinycloud.encryption.key-describe/v1",targetNode:t.targetNode,networkId:e.networkId,keyPath:e.path}}var Qi={[yi]:!0,[Li]:!0,[Ti]:!0,[Ki]:!0};function to(t){return new Mi("INVALID_RESPONSE",`node returned an invalid ${t}`)}function eo(t,e,n){const r="object"==typeof t&&null!==t?t:{};if("string"!=typeof r.alg||"number"!=typeof r.keyVersion||!Number.isInteger(r.keyVersion)||"string"!=typeof r.publicEncryptionKey||0===r.publicEncryptionKey.length)throw to("key descriptor");if(r.networkId!==e||r.keyPath!==n)throw new Mi("INVALID_RESPONSE","node returned a descriptor for a different network or key");return{networkId:e,keyPath:n,alg:r.alg,keyVersion:r.keyVersion,publicEncryptionKey:r.publicEncryptionKey}}function no(t,e,n){const r=eo(t,e,n),i=t;if("string"!=typeof i.state||"string"!=typeof i.kind)throw to("key descriptor (state/kind missing)");return{...r,state:i.state,kind:i.kind,..."string"==typeof i.createdAt?{createdAt:i.createdAt}:{},..."string"==typeof i.updatedAt?{updatedAt:i.updatedAt}:{}}}function ro(t){return t.startsWith("apps/")}var io=["alg","encryptedSymmetricKey","encryptedSymmetricKeyHash","ciphertext"],oo=class{constructor(t){this.config=t}networkFor(t){return t?.networkId??this.config.defaultNetworkId()}keyUrn(t,e){try{return function(t,e){const n=function(t){let e;try{e=di(t)}catch(t){if(t instanceof ui)throw new Di("bad_network",t.message);throw t}return Ci(e.ownerDid),e.networkId}(t);zi(e,"key path");const r=`${n}/${e}`;return function(t,e){if(Hi(t).networkId!==e)throw new Di("malformed",`built resource does not round-trip (got ${JSON.stringify(t)})`)}(r,n),r}(t,e)}catch(n){throw new Mi("INVALID_KEY_TARGET",Fi(n instanceof Error?n.message:n),{cause:n,input:`${t}/${e}`})}}requireNode(){if(void 0===this.nodeId){const t=this.readNodeInfo();this.nodeId=t,t.catch(()=>{this.nodeId===t&&(this.nodeId=void 0)})}return this.nodeId}refreshNodeInfo(){this.nodeId=void 0}async readNodeInfo(){const t=await this.config.fetch(`${this.config.host}/info`);if(!t.ok)throw Yi(t.status,await so(t),"failed to read node info");const e=await t.json();if(!function(t){const e=t?.features;return Array.isArray(e)&&e.includes("encryption-named-keys-v1")}(e))throw new Mi("NAMED_KEYS_UNSUPPORTED","this node does not support named encryption keys");if("string"!=typeof e.nodeId||0===e.nodeId.length)throw to("/info response (nodeId missing)");return e.nodeId}keysUrl(t,e){return`${this.config.host}/encryption/networks/${t}/keys/${e}`}async getPublicKey(t,e){const n=this.networkFor(e);this.keyUrn(n,t),await this.requireNode();const r=await this.config.fetch(this.keysUrl(n,t),{method:"GET"});if(!r.ok)throw Yi(r.status,await so(r),"failed to read key");return eo(await r.json(),n,t)}async describeKey(t,e){const n=this.networkFor(e),r=await this.describeBody(t,e);return null===r?null:no(r,n,t)}async describePublic(t,e){const n=this.networkFor(e),r=await this.describeBody(t,e);if(null===r)throw new Mi("KEY_NOT_FOUND",`key ${Fi(t)} does not exist`,{status:404});return eo(r,n,t)}async describeBody(t,e){const n=this.networkFor(e),r=this.keyUrn(n,t),i=e?.ability??yi;if(!0!==Qi[i])throw new Mi("INVALID_KEY_TARGET",`${Fi(i)} cannot describe a key`,{input:i});const o=await this.requireNode(),s=await this.config.signInvocation({targetNode:o,resource:r,action:i,facts:Ji({targetNode:o,keyResource:r})}),c=await this.config.fetch(this.keysUrl(n,t),{method:"GET",headers:{Authorization:s.authorization}});if(404===c.status){const t=Yi(404,await so(c),"failed to describe key");if("KEY_NOT_FOUND"===t.code)return null;throw t}if(!c.ok)throw Yi(c.status,await so(c),"failed to describe key");return c.json()}async admin(t,e,n,r){const i=this.networkFor(r),o=this.keyUrn(i,n),s="keys"===t?{keyPath:n,deletable:ro(n)}:{keyPath:n},c=await this.requireNode(),a=await this.config.signInvocation({targetNode:c,resource:o,action:e,facts:Xi({crypto:this.config.crypto,targetNode:c,keyResource:o,action:e,body:s})}),u=await this.config.fetch(`${this.config.host}/encryption/networks/${i}/${t}`,{method:"POST",headers:{Authorization:a.authorization,"Content-Type":"application/json"},body:Qr(s)});if(!u.ok)throw Yi(u.status,await so(u),`failed to ${e}`);return no(function(t){const e="object"==typeof t&&null!==t?t:{};return"object"==typeof e.descriptor&&null!==e.descriptor?e.descriptor:t}(await u.json()),i,n)}createKey(t,e){return this.admin("keys",Li,t,e)}blockKey(t,e){return this.admin("key-actions/block",Ti,t,e)}unblockKey(t,e){return this.admin("key-actions/unblock",Ki,t,e)}async ensureKey(t,e){const n=()=>this.describeKey(t,{...e,ability:Li});let r=await n();if(null===r)try{r=await this.createKey(t,e)}catch(e){if(!(e instanceof Mi)||"KEY_EXISTS"!==e.code)throw e;if(r=await n(),null===r)throw new Mi("KEY_NOT_FOUND",`key ${Fi(t)} reported as existing but could not be read back`)}return function(t,e){if("blocked"===t.state)throw new Mi("KEY_BLOCKED",`key ${Fi(t.keyPath)} is blocked`,{rawState:t.state});if("active"!==t.state)throw new Mi("KEY_UNAVAILABLE",`key ${Fi(t.keyPath)} is unavailable (state ${Fi(t.state)})`,{rawState:t.state});if(t.kind!==e)throw new Mi("KEY_KIND_MISMATCH",`key ${Fi(t.keyPath)} exists with kind ${Fi(t.kind)}, not ${e}`,{kind:t.kind});return t}(r,ro(t)?"deletable":"deterministic")}async encrypt(t,e,n){const r=ro(t)?await this.describePublic(t,n):await this.getPublicKey(t,n),{crypto:i}=this.config,o=i.randomBytes(32),s=i.authEncrypt(o,e,n?.aad),c=n?.keyWrapV2??this.config.keyWrapV2??!1,a=ii(r.publicEncryptionKey),u=c?function(t,e,n){if(xi(n),32!==t.length)throw new Error("Invalid recipient public key");const r=ct(32),i=fn.getPublicKey(r),o=ct(32),s=oi(Qr({...{...n,v:2,alg:gi,kdf:"hkdf-sha256",aead:"aes-256-gcm",salt:ri(o),ephemeralPublicKey:ri(i),recipientPublicKey:ri(t)}}));if(s.length>65536)throw new Error("Key wrap header too large");const c=new Uint8Array(8);c.set(bi),new DataView(c.buffer).setUint32(4,s.length);const a=vi(c,s),u=ct(12);let d;try{const n=fn.getSharedSecret(r,t);try{if(n.every(t=>0===t))throw new Error("Invalid key agreement");d=Nn(Bn,n,o,vi(mi,i,t),32)}finally{n.fill(0)}return vi(a,u,K(d,u,a).encrypt(e))}finally{r.fill(0),d?.fill(0)}}(a,o,{purpose:"network-key",networkId:r.networkId,keyPath:r.keyPath,keyVersion:r.keyVersion,metadata:n?.metadata??{}}):i.sealToNetworkKey(a,o),d=ri(u);return{v:2,networkId:r.networkId,keyPath:r.keyPath,alg:c?gi:"x25519-aes256gcm/v1",keyVersion:r.keyVersion,encryptedSymmetricKey:d,encryptedSymmetricKeyHash:si(i.sha256,d),ciphertext:ri(s),...void 0!==n?.aad?{aad:ri(n.aad)}:{},...void 0!==n?.metadata?{metadata:n.metadata}:{}}}async decrypt(t){const e="object"==typeof t&&null!==t?t:{};if(1===e.v&&void 0===e.keyPath)return this.decryptRoot(e);if(2===e.v&&"string"==typeof e.keyPath)return this.decryptKey(this.validateKeyEnvelope(e));throw new Mi("INVALID_ENVELOPE","envelope must be v1 without keyPath or v2 with keyPath")}async decryptMany(t){const e=[];for(const n of t)try{e.push({ok:!0,data:await this.decrypt(n)})}catch(t){e.push({ok:!1,error:t instanceof Mi?t:new Mi("DECRYPT_FAILED","decrypt failed",{cause:t})})}return e}async decryptRoot(t){if(this.config.requireKeyWrapV2)try{Oi(t,!0)}catch(t){throw new Mi("INVALID_ENVELOPE","Envelope key wrap context is invalid",{cause:t})}if(void 0===this.config.decryptRoot)throw new Mi("DECRYPT_FAILED","no root-key decrypt path is configured");const e=await this.config.decryptRoot(t);if(!e.ok)throw new Mi("DECRYPT_FAILED",Fi(e.error.message),{cause:e.error});return e.data}validateKeyEnvelope(t){for(const e of io)if("string"!=typeof t[e]||0===t[e].length)throw new Mi("INVALID_ENVELOPE",`envelope.${e} must be a non-empty string`);if("number"!=typeof t.keyVersion||!Number.isInteger(t.keyVersion))throw new Mi("INVALID_ENVELOPE","envelope.keyVersion must be an integer");if("string"!=typeof t.networkId)throw new Mi("INVALID_ENVELOPE","envelope.networkId must be a string");try{di(t.networkId)}catch(t){throw new Mi("INVALID_ENVELOPE","envelope.networkId is malformed",{cause:t})}if(si(this.config.crypto.sha256,t.encryptedSymmetricKey)!==t.encryptedSymmetricKeyHash)throw new Mi("INVALID_ENVELOPE","envelope.encryptedSymmetricKeyHash does not match encryptedSymmetricKey");try{Oi(t,this.config.requireKeyWrapV2??!1)}catch(t){throw new Mi("INVALID_ENVELOPE","Envelope key wrap context is invalid",{cause:t})}return t}async decryptKey(t){const{crypto:e}=this.config,n=this.keyUrn(t.networkId,t.keyPath),r=await this.requireNode(),i=function(t){const e=t.crypto.randomBytes(32);return t.crypto.x25519FromSeed(e)}({crypto:e}),o=ri(i.publicKey),s=si(e.sha256,o),c={type:li,targetNode:r,networkId:t.networkId,keyPath:t.keyPath,alg:t.alg,keyVersion:t.keyVersion,encryptedSymmetricKey:t.encryptedSymmetricKey,encryptedSymmetricKeyHash:t.encryptedSymmetricKeyHash,receiverPublicKey:o,receiverPublicKeyHash:s},a=Qr(c),u={type:li,targetNode:r,networkId:t.networkId,keyPath:t.keyPath,bodyHash:si(e.sha256,c),encryptedSymmetricKeyHash:t.encryptedSymmetricKeyHash,receiverPublicKeyHash:s,alg:t.alg,keyVersion:t.keyVersion},d=await this.config.signInvocation({targetNode:r,resource:n,action:yi,facts:u}),f=await this.config.fetch(`${this.config.host}/invoke`,{method:"POST",headers:{Authorization:d.authorization,"Content-Type":"application/json"},body:a});if(!f.ok)throw Yi(f.status,await so(f),"failed to decrypt");const l=function(t){const{crypto:e,request:n,facts:r,invocationCid:i,requestBodyHash:o,response:s}=t;if(s.type!==hi)return{ok:!1,error:wi({code:"INVALID_RESPONSE",message:`response.type must be ${hi}`})};if(s.targetNode!==n.targetNode)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"targetNode"})};if(s.networkId!==n.networkId)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"networkId"})};if(s.nodeId!==n.targetNode)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"nodeId"})};if("x25519-aes256gcm/v1"!==s.alg&&s.alg!==gi)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"alg"})};if(s.keyVersion!==n.keyVersion)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"keyVersion"})};if(s.encryptedSymmetricKeyHash!==n.encryptedSymmetricKeyHash)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"encryptedSymmetricKeyHash"})};if(s.receiverPublicKeyHash!==n.receiverPublicKeyHash)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"receiverPublicKeyHash"})};if(s.invocationCid!==i)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"invocationCid"})};const c=ni(e.sha256(oi(`${i}${o}`)));if(s.requestHash!==c)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"requestHash"})};if(r.encryptedSymmetricKeyHash!==s.encryptedSymmetricKeyHash||r.receiverPublicKeyHash!==s.receiverPublicKeyHash||r.networkId!==s.networkId||r.targetNode!==s.targetNode||r.alg!==n.alg||r.keyVersion!==s.keyVersion)return{ok:!1,error:wi({code:"RESPONSE_BINDING_MISMATCH",field:"facts"})};const a=(new TextEncoder).encode(function(t){const{nodeSignature:e,...n}=t;return Qr(n)}(s)),u=ii(s.nodeSignature);return e.verifyNodeSignature(s.nodeId,a,u)?{ok:!0,data:s}:{ok:!1,error:wi({code:"RESPONSE_SIGNATURE_INVALID"})}}({crypto:e,request:c,facts:u,invocationCid:d.invocationCid,requestBodyHash:u.bodyHash,response:await f.json()});if(!l.ok)throw new Mi("INVALID_RESPONSE",Fi(l.error.message),{cause:l.error});const h=function(t,e,n,r){const i=ii(n.wrappedKey);if(Si(i,n.alg),n.alg===gi){if(!r)throw new Error("V2 response requires expected key context");return function(t,e,n){const{header:r,aad:i,nonce:o,ciphertext:s}=Ni(e);Bi(r,n);const c=fn.getPublicKey(t);if(!ki(c,Ei(r.recipientPublicKey)))throw new Error("Key wrap recipient mismatch");const a=function(t,e,n,r){const i=fn.getSharedSecret(t,e);if(i.every(t=>0===t))throw new Error("Invalid key agreement");try{return Nn(Bn,i,r,vi(mi,e,n),32)}finally{i.fill(0)}}(t,Ei(r.ephemeralPublicKey),c,Ei(r.salt));try{return K(a,o,i).decrypt(s)}finally{a.fill(0)}}(e,i,r)}return t.openWithReceiverKey(e,i)}(e,i.privateKey,l.data,{purpose:"receiver-key",networkId:c.networkId,keyPath:c.keyPath,keyVersion:c.keyVersion,metadata:{}});try{return e.authDecrypt(h,ii(t.ciphertext),void 0!==t.aad?ii(t.aad):void 0)}catch(t){throw new Mi("DECRYPT_FAILED","local decryption failed",{cause:t})}}};async function so(t){try{return await t.text()}catch{return""}}function co(t,e={}){const n=t;for(const t of["signRawNetworkAuthorization","createEncryptionCrypto"])if("function"!=typeof n[t])throw new Mi("NODE_HOOK_MISSING",`TinyCloudNode.${t} is not available; named keys cannot sign invocations`);const r=n,i=t.hosts[0];if(void 0===i)throw new Error("TinyCloud node host has not been resolved");const o={keyWrapV2:e.keyWrapV2??r.config?.keyWrapV2??!1,requireKeyWrapV2:e.requireKeyWrapV2??r.config?.requireKeyWrapV2??!1,host:i,crypto:r.createEncryptionCrypto(),fetch:e.fetch??globalThis.fetch.bind(globalThis),defaultNetworkId:()=>e.networkId??t.getDefaultEncryptionNetworkId(),signInvocation:t=>r.signRawNetworkAuthorization({targetNode:t.targetNode,networkId:t.resource,action:t.action,facts:t.facts}),decryptRoot:e=>{const n=t.session?.delegationCid;return void 0===n?Promise.reject(new Error("Not signed in. Call signIn() first.")):t.encryption.decryptEnvelope(e,{proofs:[n]})}};return new oo(o)}export{co as createNamedKeyClient};
@@ -1 +1,5 @@
1
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
2
+
3
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
4
+
1
5
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */