@calimero-network/mero-js 25.0.3 → 25.0.4

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,3 +1,3 @@
1
- function $n(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let a of e)a.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function Kn(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var Ls=new Set(["token_reuse","token_revoked"]);function qs(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var T=class extends Error{constructor(n,r,o,i,a){let s=qs(a)??(n===0&&a?.trim()?a.trim():void 0);super(s?`HTTP ${n} ${r}: ${s}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=a;this.name="HTTPError";this.explanation=s}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:ro(this.headers),bodyText:this.bodyText}}},ne=class extends T{constructor(n,r,o,i,a,s){super(r,o,i,a,s);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function ro(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Bs(t){try{return new URL(t).pathname}catch{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}}var We=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:ro(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let a=this.buildUrl(e),s=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((w,v)=>{d[v]=w})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let w=n?.body;if(w!==void 0&&typeof w!="string"&&!(w instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:new URL(a).pathname,body:w}))}let g={method:l,headers:d},A=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!A||n?.body!==void 0&&A&&r===0)&&(g.body=n.body);let x;if(r>0&&o!==void 0){let w=n?.timeoutMs||this.transport.timeoutMs;if(w){let v=Date.now()-s,I=Math.max(0,w-v);x=this.createAbortSignal({...n,timeoutMs:I})}else x=this.createAbortSignal(n)}else x=c;if(x&&(g.signal=x),this.transport.credentials!==void 0&&(g.credentials=this.transport.credentials),n?.mode!==void 0&&(g.mode=n.mode),n?.cache!==void 0&&(g.cache=n.cache),n?.redirect!==void 0&&(g.redirect=n.redirect),n?.referrer!==void 0&&(g.referrer=n.referrer),n?.referrerPolicy!==void 0&&(g.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(g.integrity=n.integrity),n?.keepalive!==void 0&&(g.keepalive=n.keepalive),this.transport.getProof){let w=await this.transport.getProof({method:g.method??"GET",path:Bs(a),body:g.body});w&&(d["X-Calimero-Proof"]=w)}try{let w=await this.transport.fetch(a,g);if(!w.ok){let v=await this.getBodyText(w),I=new T(w.status,w.statusText,a,w.headers,v),P=w.headers.get("x-auth-error");if((w.status===401||w.status===403)&&P&&Ls.has(P)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new ne(P,w.status,w.statusText,a,w.headers,v)}let B=n?.signal?.aborted===!0;if(w.status===401&&this.transport.refreshToken&&P==="token_expired"&&r<1&&!A&&!B)try{let M=this.refreshTokenPromise;M||(M=this.transport.refreshToken(),this.refreshTokenPromise=M);let h=await M;if(!h||h.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let y=this.onTokenRefreshPromise;y||(y=this.transport.onTokenRefresh(h),this.onTokenRefreshPromise=y),await y,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let S=n?.timeoutMs||this.transport.timeoutMs;if(S&&o!==void 0){let O=Date.now()-s;if(S-O<=0)throw I}return this.makeRequest(e,n,r+1,s)}catch(M){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,M instanceof Error&&M.message.includes("onTokenRefresh")?M:I}throw I}return this.parseResponse(w,n?.parse)}catch(w){throw w instanceof T||w instanceof Error&&w.message.includes("onTokenRefresh")?w:new T(0,"Network Error",a,new Headers,w instanceof Error?w.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(Kn(r)),n.length>0?$n(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function Je(t){return new We(t)}function Re(t){let e={fetch:(n,r)=>t.fetch?t.fetch(n,r):globalThis.fetch(n,r),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return Je(e)}function At(t){let e=t.fetch??globalThis.fetch;if(!e)throw new Error("No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support.");let r={fetch:e===globalThis.fetch?(o,i)=>globalThis.fetch(o,i):(o,i)=>e(o,i),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return Je(r)}function Hn(t){return typeof window<"u"?Re(t):At(t)}function js(t,e){if(e<=0)return!1;let r=t?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=t;if("status"in o&&typeof o.status=="number"){let i=o.status;return i>=500||i===429}return r==="TypeError"}function Fs(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function xt(t,e={}){let{attempts:n=3}=e,r;for(let o=1;o<=n;o++)try{return await t(o)}catch(i){if(r=i,!js(r,n-o))throw r;let a=Fs(o),u=r.headers?.get?.("Retry-After");if(u){let d=parseInt(u,10);if(!isNaN(d))a=Math.max(a,d*1e3);else{let l=new Date(u);if(!isNaN(l.getTime())){let g=Math.max(0,l.getTime()-Date.now());a=Math.max(a,Math.min(g,6e4))}}}await new Promise(d=>setTimeout(d,a))}throw r||new Error("Retry failed without error")}function Vs(t,e={}){return async(...n)=>xt(()=>t(...n),e)}var le=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${e}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${e}/clients/${n}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${e}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${e}/permissions`,{add:n.add,remove:n.remove})}};var ze=class{async get(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async post(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async put(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async delete(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async patch(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async head(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async request(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}};function Pu(t){let e=new ze;return new le(e)}function Tu(t){let e=new ze;return new le(e)}function Du(t){let e=new ze;return new le(e)}function oo(t,e){return new le(t)}var U={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},Ou={NONE:0,JOIN_ONLY:U.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:U.CAN_CREATE_CONTEXT|U.CAN_INVITE_MEMBERS|U.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:U.CAN_CREATE_CONTEXT|U.CAN_INVITE_MEMBERS|U.CAN_JOIN_OPEN_SUBGROUPS|U.CAN_CREATE_SUBGROUP|U.CAN_DELETE_SUBGROUP|U.CAN_MANAGE_VISIBILITY};function Uu(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(U,n))e|=U[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function Mu(t){return Object.keys(U).filter(e=>ue(t,U[e]))}function ue(t,e){let n=e>>>0;return(t&n)>>>0===n}function Ln(t,e){return(t|e)>>>0}function _u(t,e){return(t&~e)>>>0}var Ws={invalid:!1,unauthorized:!0,forbidden:!1,"not-found":!0,conflict:!1,gone:!1,"too-large":!1,"rate-limited":!0,unavailable:!0,server:!0,unreachable:!0,unknown:!0};function Js(t){switch(t){case 0:return"unreachable";case 400:return"invalid";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 409:return"conflict";case 410:return"gone";case 413:return"too-large";case 429:return"rate-limited";case 503:case 504:return"unavailable"}return t>=500&&t<600?"server":t>=400&&t<500?"invalid":"unknown"}function zs(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function qn(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function Bn(t){let e=zs(t),n;return e!==void 0?n=Js(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:Ws[n],message:qn(t)}}function Qs(t){return t.status!=="failed"||!t.retryable}function Hu(t){return!Qs(t)}function Ys(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":null}function Xs(t,e){let{kind:n,status:r}=Bn(t),o=Ys(e);return r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function io(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let a=null;try{a=(await e.memberships()).includes(n)}catch{a=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(a===!0)return{status:"already-member",namespaceId:n,teamName:o};let s=qn(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=Xs(i,s);return{status:"failed",namespaceId:n,message:s,reason:c,retryable:u}}var Rt=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function jn(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function so(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:jn(t,n,"highWaterNonce"),windowWidth:jn(t,n,"windowWidth")??0n},o=jn(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function b(t){return t?.data}function Zs(t,e){let[n,r]=ao(t),[o,i]=ao(e),a=n.split("."),s=o.split("."),c=Math.max(a.length,s.length);for(let g=0;g<c;g++){let A=co(a[g]??"0",s[g]??"0");if(A!==0)return A}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let g=0;g<l;g++){if(g>=u.length)return-1;if(g>=d.length)return 1;let A=co(u[g],d[g]);if(A!==0)return A}return 0}function ao(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function co(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function ea(t,e,n){return xt(async()=>{let r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${n}`);throw o.status=r.status,o}return r},{attempts:3})}var de=class{constructor(e){this.httpClient=e}async healthCheck(){return b(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return b(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return b(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,n){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",n);let i=await(await ea(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(a=>a.appVersion).filter(a=>typeof a=="string").sort((a,s)=>Zs(s,a))}async installDevApplication(e){return b(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return b(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return b(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return b(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return b(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return b(await this.httpClient.get(`/admin-api/applications/${e}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return b(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return b(await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return b(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return b(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return b(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return b(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${e}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,n)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return b(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${e}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${e}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=b(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${e}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:b(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${e}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${e}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return b(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return b(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return b(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return b(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return b(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return b(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return b(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return b(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return b(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return b(await this.httpClient.post(`/admin-api/alias/lookup/device/${encodeURIComponent(e)}`,{}))}async deleteDeviceAlias(e){return b(await this.httpClient.post(`/admin-api/alias/delete/device/${encodeURIComponent(e)}`,{}))}async listDeviceAliases(){return b(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return b(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return b(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return b(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}async performIntent(e,n){return b(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,n))}async queryContext(e,n){return b(await this.httpClient.post(`/admin-api/contexts/${e}/query`,n))}async getIntentRelay(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/intents`))}async listNamespacesForApplication(e){return b(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return b(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return b(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,n??{}))}async admitJoin(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=b(await this.httpClient.post(`/admin-api/namespaces/${e}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return io({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(a=>a.namespaceId)})}async createGroupInNamespace(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,n??{}))}async listNamespaceGroups(e){return b(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async initAccountPairing(e){return b(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return b(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return b(await this.httpClient.post(`/admin-api/account/devices/${e}/relink`,n??{}))}async rescopeAccountDevice(e,n){return b(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/scope`,n))}async signWithAccountRoot(e){return b(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return b(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/account/revoke`,n))}async linkAccountDevice(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/account/link-device`,n))}async getGroupInfo(e){return b(await this.httpClient.get(`/admin-api/groups/${e}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return b(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${e}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${encodeURIComponent(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async getWarrantNonce(e,n){let r=`/admin-api/contexts/${encodeURIComponent(e)}/warrant-nonce/${encodeURIComponent(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof T&&i.status===404?new Rt(r,i):i}return so(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${encodeURIComponent(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof T&&i.status===404?new Rt(r,i):i}return so(o)}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${e}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return b(await this.httpClient.post(`/admin-api/groups/${e}/accounts/${n}/seal`,r))}async listGroupContexts(e){return b(await this.httpClient.get(`/admin-api/groups/${e}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${e}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${e}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/role`,r)}async getMemberCapabilities(e,n){return b(await this.httpClient.get(`/admin-api/groups/${e}/members/${n}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(ue(n,U.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=Ln(n,U.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(ue(r,U.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=Ln(r,U.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${e}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${e}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${e}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${e}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${e}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${e}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${e}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${e}/members/${n}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/contexts/${n}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${e}/contexts/${n}/metadata`))?.data??null}async syncGroup(e){return b(await this.httpClient.post(`/admin-api/groups/${e}/sync`,{}))}async upgradeGroup(e,n){return b(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,n))}async getGroupUpgradeStatus(e){return b(await this.httpClient.get(`/admin-api/groups/${e}/upgrade/status`))}async getMigrationStatus(e){let n=encodeURIComponent(e);return this.httpClient.get(`/admin-api/groups/${n}/migration-status`)}async getCascadeStatus(e){let n=encodeURIComponent(e);return b(await this.httpClient.get(`/admin-api/groups/${n}/cascade-status`))}async retryGroupUpgrade(e){return b(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${e}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${e}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${n}/remove`,{})}async createGroupInvitation(e,n){return b(await this.httpClient.post(`/admin-api/groups/${e}/invite`,n??{}))}async joinGroup(e){return b(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return b(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return b(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return b(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return b(await this.httpClient.post("/admin-api/tee/verify-quote",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return b(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${e}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${e}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${e}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${e}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${e}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,{})}};function Wu(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function Xu(t){return new de(Re(t))}function Zu(t){return new de(At(t))}function lo(t){return new de(Hn(t))}function vt(t,e){return new de(t)}function Fn(t){try{let e=t.indexOf("#");if(e===-1)return null;let n=t.substring(e+1),r=new URLSearchParams(n),o=r.get("access_token");return o?{accessToken:o,refreshToken:r.get("refresh_token")??"",applicationId:r.get("application_id")??"",contextId:r.get("context_id")??"",contextIdentity:r.get("context_identity")??"",nodeUrl:r.get("node_url")??""}:null}catch{return null}}function Vn(t,e){let n=new URLSearchParams;return n.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&n.set("permissions",e.permissions.join(",")),n.set("mode",e.mode),e.packageName&&(n.set("package-name",e.packageName),e.packageVersion&&n.set("package-version",e.packageVersion),e.registryUrl&&n.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${n.toString()}`}var uo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function f(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function p(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function j(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function C(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function m(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function k(t,e){let n=[C(t.length),t];for(let r of e)n.push(C(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",m(...n)))}async function re(t){let e=p(t,"deviceSecret",32),n=m(uo,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function po(t,e,n){let r=await crypto.subtle.importKey("raw",p(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function oe(t){let e=p(t,"deviceSecret",32),n=m(uo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),a=>a.charCodeAt(0))}var ta=new TextEncoder().encode("calimero.auth.request.v1"),na=new TextEncoder().encode("calimero.auth.request.body.v1");function go(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}async function Wn(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return k(na,[e])}async function Ct(t){let e=await re(t.signerSecret),n=await Wn(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,a=await k(ta,[i.encode(t.method),i.encode(t.path),n,r,o]),s=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,a));return f(m(go(t.method),go(t.path),n,r,o,s))}function St(t){let e=j(t.credential,"credential"),n=j(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):m(new Uint8Array([1]),j(t.session,"session statement"));return f(m(e,r,n))}function ra(t){if(t==null)return new Uint8Array(0);if(typeof t=="string"||t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error(`a request-carried proof cannot commit to a ${t?.constructor?.name??typeof t} body: pass a string or bytes, or use a session for this call`)}function kt(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return St({credential:t.credential,session:t.session,request:await Ct({method:r.method,path:r.path,body:ra(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var Et=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Jn(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new Et(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var Qe=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Jn(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var oa=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function mo(t){return t.type!==void 0&&oa.has(t.type)}var ia=new Set(["token_reuse","token_revoked"]),sa=new Set([401,403]),aa=1e4;function ho(t){let e=t.headers.get("x-auth-error");return!e||!sa.has(t.status)?null:ia.has(e)?e:null}var L=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{mo(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=`${this.baseUrl}/sse`,n=await this.fetchImpl(e,{headers:{...await this.authorize({method:"GET",path:new URL(e).pathname}),Accept:"text/event-stream"},signal:this.abortController.signal});if(!n.ok){let r=ho(n),o=await n.text().catch(()=>{});throw r?new ne(r,n.status,n.statusText,e,n.headers,o):new T(n.status,n.statusText,e,n.headers,o)}if(!n.body)throw new Error("SSE response has no body");this.readStream(n.body).catch(r=>{if(this.closed)return;let o=r instanceof Error?r:new Error(String(r));this.emit("error",o),this.scheduleReconnect()})}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));if(this.emit("error",n),n instanceof ne)return;this.scheduleReconnect()}}}async readStream(e){let n=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:i,value:a}=await n.read();if(i)break;o+=r.decode(a,{stream:!0});let s=o.split(`
2
- `);o=s.pop()??"";for(let c of s)if(c.startsWith("data:")){let u=c.slice(5).trim();u&&this.handleMessage(u)}}if(o+=r.decode(),o.startsWith("data:")){let i=o.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let a=i instanceof Error?i:new Error(String(i));this.emit("error",a)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),aa);try{let i={};n.contextIds&&n.contextIds.length>0&&(i.contextIds=n.contextIds),n.groupIds&&n.groupIds.length>0&&(i.groupIds=n.groupIds);let a=`${this.baseUrl}/sse/subscription`,s=JSON.stringify({id:this.sessionId,method:e,params:i}),c=await this.fetchImpl(a,{method:"POST",headers:{...await this.authorize({method:"POST",path:new URL(a).pathname,body:s}),"Content-Type":"application/json"},body:s,signal:r.signal});if(!c.ok){let u=ho(c),d=await c.text().catch(()=>{});return u?new ne(u,c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d):new T(c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var It=class It{constructor(e){this.ws=null;this.closed=!1;this.reconnectAttempt=0;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.ws&&(this.ws.readyState===0||this.ws.readyState===1))){this.closed=!1;try{let e=await this.getAuthToken();if(!e)throw new Error("No authentication token available for WebSocket connection");let n=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${n}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=r=>{this.handleMessage(r.data)},this.ws.onerror=()=>{this.emit("error",new Error("WebSocket error"))},this.ws.onclose=()=>{this.closed||this.scheduleReconnect()}}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));this.emit("error",n),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.add(r);for(let r of n.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.delete(r);for(let r of n.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}resubscribeAfterReconnect(){this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0||this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams([...this.subscribedContextIds],[...this.subscribedGroupIds])})}buildSubscriptionParams(e,n){let r={};return e.length>0&&(r.contextIds=e),n.length>0&&(r.groupIds=n),r}sendMessage(e){this.ws&&this.ws.readyState===1&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.closed)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),It.MAX_BACKOFF_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}close(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};It.MAX_BACKOFF_MS=3e4;var ie=It;function se(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var Ye=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=se()){await Jn(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=se()){return Pt(this.sse,e,n,r)}};function Pt(t,e,n,r=se()){let o=i=>{let a=i;if(a.type!=="Ephemeral"||a.contextId!==e)return;let s=a.data;if(!s?.author)return;let c=!!s.removed,u={author:s.author,state:c||s.state===void 0?void 0:r.decode(s.state),removed:c};s.ageMs!==void 0&&(u.ageMs=s.ageMs),s.account!==void 0&&(u.account=s.account),n(u)};if(t.on("event",o),t.isSubscribed?.(e))for(let i of t.presenceSeed?.(e)??[])o({contextId:e,type:"Ephemeral",data:i});return t.connect().catch(()=>{}),t.subscribe([e]).catch(()=>{}),()=>{t.off("event",o)}}var ca=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function fo(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function ve(t,e="secret"){let n=p(t,e,32),r=m(ca,n),o,i;try{let a=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),s=await crypto.subtle.exportKey("jwk",a);i=f(Uint8Array.from(atob(s.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(a){throw fo(a)}return bo(o,i)}async function yo(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")p(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=f(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return bo(t,n)}function bo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw fo(r)}}}}async function E(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return ve(t,n);throw new Error(`${n} or signer is required`)}var la=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),ua=6e4,wo=5*6e4,Ao=1024,Ro="mdma:enable-ha-namespace",vo="mdma:enable-ha-namespace-as-account";function xo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var zn=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function Co(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=Ao))throw new Error(`relayUrl must be a non-empty string of at most ${Ao} characters`);let o=t.ttlMs??ua;if(!(o>0&&o<=wo))throw new Error(`ttlMs must be in (0, ${wo}]`);let i=zn(t.namespaceId,"namespaceId"),a=zn(t.accountId,"accountId"),s=zn(t.salt,"salt"),c=await E(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),A=>A.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:a,salt:s,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),g=await c.sign(m(la,l));return{kind:"account",credential:t.credential,signed_payload:xo(l),signature:xo(g)}}async function da(t){if(!t.subject)throw new Error("subject must be the cloud login email");return Co(t,Ro,t.subject)}async function Qn(t){return Co(t,vo,void 0,t.relayUrl)}var pa=new TextEncoder().encode("calimero.device.cert.v1"),ga=new TextEncoder().encode("calimero.account.genesis.v1"),ma=new TextEncoder().encode("calimero.device.id.v1"),Ce=2,ha=237;async function Yn(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=p(t,"account",32),r=await k(ma,[n,e]);return f(m(e,r.subarray(0,16)))}async function Tt(t){return k(pa,[p(t.account,"account",32),p(t.device,"device",32),p(t.signPublicKey,"signPublicKey",32),p(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function So(t){return m(new Uint8Array([Ce]),t.rootPublicKey,R(0),p(t.account,"account",32),p(t.device,"device",32),p(t.signPublicKey,"signPublicKey",32),p(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function ko(t){let e=await E(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await F(e.publicKey),o=0,i=await Tt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),a=await e.sign(i),s=So({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:a});return f(s)}function Xn(t){let e=p(t,"credential",ha);if(e[0]!==Ce)throw new Error(`this credential has account genesis version ${e[0]}, not ${Ce} \u2014 it names a different account than its root key derives here, and core would refuse it`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(33,!0);if(r!==0)throw new Error(`this credential carries a ${r}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`);let o=(i,a)=>f(e.subarray(i,i+a));return{rootPublicKey:o(1,32),account:o(37,32),device:o(69,32),signPublicKey:o(101,32),kemPublicKey:o(133,32),keyEpoch:n.getUint32(165,!0),deviceEpoch:n.getUint32(169,!0),signature:o(173,64)}}async function Dt(t){let e=Xn(t),n=await F(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=p(e.device,"device",32).subarray(0,16);if(await Yn(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await po(e.rootPublicKey,p(e.signature,"signature",64),await Tt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Nt(t){return F(f(await oe(t)))}async function F(t){return f(await k(ga,[m(new Uint8Array([Ce]),p(t,"rootPublicKey",32))]))}var fa=new TextEncoder().encode("calimero.device.scope.v1");async function Zn(t){return k(fa,[p(t.account,"account",32),p(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>p(e,`applications[${n}]`,32))])}async function Eo(t){let e=await E(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await F(f(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let a=0,s=await Zn({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:a}),c=await e.sign(s);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return f(m(new Uint8Array([Ce]),n,R(0),p(r,"account",32),p(t.device,"device",32),R(o.length),...o.map((u,d)=>p(u,`applications[${d}]`,32)),R(i),R(a),c))}var er=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var ya=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),ba=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Se=256,Io=Se/32,tr=(Se+Io)/11;async function Po(){let t=crypto.getRandomValues(new Uint8Array(Se/8));return Mo(f(t),await Go(t))}async function To(t){let e=_o(t);return Mo(f(await $o(e)),e.join(" "))}async function nr(t){return p(t,"secret",32),{secret:t,publicKey:f(await oe(t)),accountId:await Nt(t)}}async function Do(){let t=crypto.getRandomValues(new Uint8Array(Se/8)),e=await Go(t);return{...await Oo(t),phrase:e}}async function No(t){return Oo(await $o(_o(t)))}async function Oo(t){let e=await ve(f(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await F(e.publicKey),signer:e}}async function z(t){let e=typeof t=="string"?await ve(t,"rootSecret"):t;return Uo(e)}async function Ot(t,e){return Uo(await E(t,e,"rootSecret"))}async function Uo(t){return{signer:t,publicKey:t.publicKey,accountId:await F(t.publicKey)}}async function Xe(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await E(t.rootSecret,t.signer,"rootSecret")).sign(m(ya,new TextEncoder().encode(t.nonce)));return Lo(n)}async function Ut(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await E(t.rootSecret,t.signer,"rootSecret")).sign(m(ba,new TextEncoder().encode(t.nonce)));return Lo(n)}async function Mo(t,e){return{...await nr(t),phrase:e}}function _o(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==tr)throw new Error(`recovery phrase must be ${tr} words, got ${n}`);return e}async function Go(t){let e=Ho(t)+await Ko(t),n=[];for(let r=0;r<tr;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(er[o])}return n.join(" ")}async function $o(t){let e="";for(let r of t){let o=er.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(Se/8);for(let r=0;r<n.length;r+=1)n[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(Se)!==await Ko(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function Ko(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Ho(e).slice(0,Io)}function Ho(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Lo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var wa=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),Mt=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Aa=568;function xa(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function rr(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function Ra(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function va(t,e){if(typeof t!="string"||!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);let n=new Uint8Array(32);for(let r=0;r<32;r+=1)n[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return n}async function _t(t){let e=await crypto.subtle.digest("SHA-256",xa(wa,new Uint8Array(32),t));return new Uint8Array(e)}function or(t){let e=t.length>=Mt.length&&rr(t.subarray(0,Mt.length),Mt),n=e?Mt.length:Aa;if(t.length<n+64)throw new Error(`the quote is too short to carry report data (${t.length} bytes)`);return{reportData:t.slice(n,n+64),mock:e}}async function Gt(t){let e=crypto.getRandomValues(new Uint8Array(32)),n=`${t.relayUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r=JSON.stringify({nonce:f(e),bindNodeKey:!0,...t.verify?.includeCollateral?{includeCollateral:!0}:{}}),o={method:"POST",headers:{"Content-Type":"application/json"},body:r},i=t.fetch?await t.fetch(n,o):await globalThis.fetch(n,o);if(!i.ok){let g=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${g?`: ${g}`:""}`)}let a=await i.json(),s=a.data??a;if(typeof s.quoteB64!="string")throw new Error("the relay returned no quote");let c=va(s.boundPublicKey,"boundPublicKey"),u=Ra(s.quoteB64),{reportData:d,mock:l}=or(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:s.quoteB64,nonce:f(e),reportDataSuffix:f(await _t(c)),...s.collateral?{collateral:s.collateral}:{}}))throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request")}else if(t.verifyQuote)await t.verifyQuote(u);else throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");if(!rr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!rr(d.subarray(32,64),await _t(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:f(c),mock:l}}var Ca="Noise_NK_25519_AESGCM_SHA256",ir=32,Sa=16,ka=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),ar=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Ca),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await Ia(m(this.h,e))}async mixKey(e){let[n,r]=await jo(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Bo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Bo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return jo(this.ck,new Uint8Array)}};async function Fo(t,e,n){let r=await ar.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ea(n);return await r.mixHash(o.publicKey),await r.mixKey(await qo(o.privateKey,t)),{message1:m(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<ir+Sa)throw new Error("Noise: message 2 is too short");let s=a.slice(0,ir);return await r.mixHash(s),await r.mixKey(await qo(o.privateKey,s)),{payload:await r.decryptAndHash(a.slice(ir)),split:await r.split()}}}}async function Ea(t){if(!t){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",m(ka,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Pa(n.x)}}async function qo(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function Bo(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Ia(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function sr(t,e){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function jo(t,e){let n=await sr(t,e),r=await sr(n,new Uint8Array([1])),o=await sr(n,m(r,new Uint8Array([2])));return[r,o]}function Pa(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var zo="/sealed/v2/handshake",Qo="/sealed/v2",et="application/vnd.calimero.sealed",cr=2,Ta=new TextEncoder().encode("calimero/sealed-http/v2"),Ze=16,Da=1+Ze+8,Na=0,Oa=1,Ua=2,Ma=1+64*1024+16,_a=1024,Ga=6e4,$a="calimero.tee-attest.transport-key.v1",Ka=[101,204,205,304],Yo=new TextEncoder,tt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},ke=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Xo(t,e){let n=await crypto.subtle.digest("SHA-256",m(Yo.encode($a),t,e));return new Uint8Array(n)}async function Zo(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=f(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=p(o.transportPublicKey,"transportPublicKey",32),a=n.applicationHash?p(n.applicationHash,"applicationHash",32):new Uint8Array(32),s=f(await Xo(a,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:s,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function pe(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let a=await i.json();if(!a.data)throw new Error("The attestation response is malformed");return a.data}};return ei({baseUrl:t.baseUrl,transportPublicKey:()=>Zo(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function ei(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,g)=>fetch(l,g)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,a=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);a.catch(()=>{});let s,c=async()=>{try{return await Wo(o,r,await Vo(a))}catch(l){if(!(l instanceof tt)||!i)throw l;return a=Promise.resolve().then(i),Wo(o,r,await Vo(a))}},u=async()=>{let l=s??d(void 0),g=await l;if(Date.now()<g.renewAt)return[g,l];let A=d(l);return[await A,A]},d=l=>{if(s===l){let g=c();s=g,g.catch(()=>{s===g&&(s=void 0)})}return s};return async(l,g)=>{let A=new Request(l,g),x=new URL(A.url);if(x.origin!==e.origin||!x.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${x.href} outside the sealed node at ${t.baseUrl}`);let w=[];A.headers.forEach((h,y)=>w.push([y,h]));let v={method:A.method,path:x.pathname.slice(n.length)+x.search,headers:w},I=new Uint8Array(await A.arrayBuffer()),P=async h=>{let{requestId:y,header:S,envelope:O}=await La(h,v,I),H=await o(`${r}${Qo}`,{method:"POST",headers:{"content-type":et},body:O,signal:A.signal});if(H.headers.get("content-type")!==et)throw await ni(H);return Ba(H,h.responseKey,S,y)},[B,M]=await u();try{return await P(B)}catch(h){if(!(h instanceof ke)||h.code!=="unknown_session")throw h;return P(await d(M))}}}async function Vo(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Wo(t,e,n){try{return await Jo(t,e,n)}catch(r){if(!(r instanceof ke)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Jo(t,e,n)}}async function Jo(t,e,n){let r=await Fo(n,Ta),o=await t(`${e}${zo}`,{method:"POST",headers:{"content-type":et},body:m(new Uint8Array([cr]),n,r.message1)});if(o.headers.get("content-type")!==et)throw await ni(o);let i=await Fa(o,_a);return Ha(r,i)}async function Ha(t,e){if(e[0]!==cr)throw new Error("The handshake reply is malformed");let n;try{n=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:r,split:o}=n;if(r.length!==Ze+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,Ze),a=new DataView(r.buffer,r.byteOffset).getUint32(Ze,!1),[s,c]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:s,responseKey:c,nextRequestId:1,renewAt:Date.now()+a*1e3-Ga,header(u){let d=new Uint8Array(Da);return d[0]=cr,d.set(i,1),new DataView(d.buffer).setBigUint64(1+Ze,BigInt(u),!1),d}}}async function La(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:ti(r,0),additionalData:o},t.requestKey,qa(e,n));return{requestId:r,header:o,envelope:m(o,new Uint8Array(i))}}function ti(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function qa(t,e){let n=Yo.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),m(r,n,e)}async function Ba(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=ja(t.body.getReader()),i=0,a=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:ti(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},s=await a();if(!s||s.kind!==Na)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(s.data));if(Ka.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await a();l?l.kind===Oa?d.enqueue(l.data):l.kind===Ua?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function ja(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=m(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Ma)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await n(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>t.cancel()}}async function Fa(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=m(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function ni(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new tt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new ke(t.status,e,n,o)}var Va=/^[0-9a-f]{96}$/,Wa=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function ur(t){let e=Ee(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((s,c)=>{let u=`allowedMeasurements[${c}]`;return Wa.map(d=>Ee([s?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Ee(t.allowedRtmr0??[],"allowedRtmr0"),Ee(t.allowedRtmr1??[],"allowedRtmr1"),Ee(t.allowedRtmr2??[],"allowedRtmr2"),Ee(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&n.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(n.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(r.slice(1).some(s=>s.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let o=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:s,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=za(s),g=d??await t.fetchCollateral?.(l);if(!g)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let A;try{A=t.dcapVerify(l,g,Math.floor(i()/1e3))}catch(I){throw new Error(`The quote did not verify: ${I?.message??String(I)}`)}if(A.status==="Revoked"||!o.includes(A.status))throw new Error(`The platform's TCB status is ${A.status}, which is not accepted`);let x=Ja(A.report);if(x.tdAttributes?.length!==8||(x.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let w=[x.mrTd,x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].map(I=>f(I));if(n.length>0&&!n.includes(w.join()))throw new Error(`The measurements (MRTD ${w[0]}, RTMR0-3 ${w.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(w[0]))throw new Error(`MRTD ${w[0]} is not an image this verifier trusts`);if([x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].forEach((I,P)=>{let B=r[P];if(B.length>0&&!B.includes(f(I)))throw new Error(`RTMR${P} ${f(I)} is not one this verifier trusts`)}),f(x.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Ee(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!Va.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Ja(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function za(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}var Qa=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],lr="locked-read-only";function dr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,a)=>{let s=i?.tag??`releases[${a}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${s} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${s} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==lr&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(lr)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>Ya(d,s));return r=r===void 0?u:r.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function Ya(t,e){let n=Qa.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var ri=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],oi=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Xa="1.2.840.10045.2.1",Za={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},ec={"P-256":32,"P-384":48},tc={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function ii(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let s=o&127;if(s===0||s>4||i+s>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<s;c+=1)o=o*256+t[i+c];i+=s}let a=i+o;if(a>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:a}}function Pe(t){let e=ii(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function _(t){let e=[];for(let n=t.start;n<t.end;){let r=ii(t.bytes,n,t.end);e.push(r),n=r.end}return e}function N(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ae(t){return t.bytes.slice(t.start,t.end)}function $t(t){return t.bytes.slice(t.offset,t.end)}function Ie(t){let e=ae(N(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let a of e)r=r*128+(a&127),a&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function nc(t){let e=new TextDecoder().decode(ae(t)),n=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(o[1]);n&&(i+=i<50?2e3:1900);let[a,s,c,u,d]=o.slice(2).map(Number);return Date.UTC(i,a-1,s,c,u,d)}function pr(t){try{let[e,n,r,...o]=_(N(Pe(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=_(N(e,48,"The signed part")),a=i[0]?.tag===160?1:0,[s,c,u,d,l,g,...A]=i.slice(a);N(s,2,"The serial number");let x=Ie(_(N(n,48,"The signature algorithm"))[0]);if(Ie(_(N(c,48,"The signature algorithm"))[0])!==x)throw new Error("it names two different signature algorithms");let v=tc[x];if(!v)throw new Error(`it is signed with ${x}, not ECDSA with SHA-256 or SHA-384`);let[I,P]=_(N(d,48,"The validity")).map(nc);if(P===void 0)throw new Error("its validity is incomplete");let[B,M]=_(N(g,48,"The public key"));N(M,3,"The public key");let[h,y]=_(N(B,48,"The key algorithm"));if(Ie(h)!==Xa)throw new Error("its key is not an elliptic-curve key");let S=Za[Ie(y)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let O=new Map,H=A.find(ee=>ee.tag===163);if(H){let[ee]=_(H);for(let te of _(N(ee,48,"The extensions"))){let xe=_(N(te,48,"An extension"));if(xe.length===3)N(xe[1],1,"An extension's critical flag");else if(xe.length!==2)throw new Error("it has a malformed extension");let Gn=Ie(xe[0]);if(O.has(Gn))throw new Error(`it has extension ${Gn} twice`);O.set(Gn,ae(N(xe[xe.length-1],4,"An extension value")))}}let Z=ae(N(r,3,"The signature"));if(Z[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:$t(e),signatureHash:v,signature:Z.slice(1),issuer:$t(N(u,48,"The issuer")),subject:$t(N(l,48,"The subject")),notBefore:I,notAfter:P,spki:$t(g),curve:S,extensions:O}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function si(t){return _(N(Pe(t),48,"The list")).map(Ie)}function rc(t,e){let n=ec[e],r=_(N(Pe(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,a)=>{let s=ae(N(i,2,"The signature"));if(s.length===0||s[0]&128)throw new Error("The signature is not an ECDSA signature");for(;s.length>1&&s[0]===0;)s=s.subarray(1);if(s.length>n)throw new Error("The signature is not an ECDSA signature");o.set(s,a*n+n-s.length)}),o}async function Kt(t,e,n,r,o){let i;try{i=rc(r,e)}catch{return!1}let a=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:n},a,i,o)}function V(t,e){let n=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}function gr(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return V(n[0][1],e)}var oc="2.5.29.17",ic="2.5.29.37",sc="1.3.6.1.5.5.7.3.3",ac="1.3.6.1.4.1.57264.1.8",cc="1.3.6.1.4.1.57264.1.1",lc=134,uc=12,dc=48,pc=new TextEncoder,Te=t=>new TextDecoder().decode(t);async function ai(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:a}=fc(e),s=a.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=V(o,"The bundle signature"),u=gr(Te(V(i,"The bundle certificate")),"The bundle certificate"),d=pr(u),l=oi.find(P=>P.logId===s.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${s.logID}, which the Sigstore trust root does not know`);let g=pc.encode(`{"body":${JSON.stringify(s.body)},"integratedTime":${s.integratedTime},"logID":${JSON.stringify(s.logID)},"logIndex":${s.logIndex}}`);if(!await Kt(V(l.publicKey,"The Rekor key"),"P-256","SHA-256",V(a.SignedEntryTimestamp,"The signed entry timestamp"),g))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let x=s.integratedTime*1e3;if(!ui(x,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${nt(x)}, when the entry says it was logged`);let w=yc(s.body),v=f(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(w.hash!==v)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!mr(V(w.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let I=gr(Te(V(w.publicKey,"The logged certificate")),"The logged certificate");if(!mr(I,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await Kt(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await gc(d,x),hc(d,n),{integratedTime:s.integratedTime}}async function gc(t,e){if(!li(t,e))throw new Error(`The signing certificate was valid ${nt(t.notBefore)} to ${nt(t.notAfter)}, not at ${nt(e)} when Rekor logged it`);let n=[];for(let r of ri){let o=r.certChain.map(a=>pr(V(a,"A Fulcio certificate")));if(!await ci(t,o[0]))continue;let i=await mc(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${nt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function mc(t,e,n){if(!ui(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!li(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await ci(o,i))return`its certificate ${r} is not signed by the next`}}async function ci(t,e){return mr(t.issuer,e.subject)?Kt(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function hc(t,e){let n=t.extensions.get(oc);if(!n)throw new Error("The signing certificate names no identity");let r=_(N(Pe(n),dc,"The subject alternative name")),o=r.filter(u=>u.tag===lc).map(u=>Te(ae(u)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let i=t.extensions.get(ac),a=t.extensions.get(cc),s=i?Te(ae(N(Pe(i),uc,"The OIDC issuer"))):a?Te(a):void 0;if(s!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${s===void 0?"missing":JSON.stringify(s)}, not ${e.issuer}`);let c=t.extensions.get(ic);if(!c||!si(c).includes(sc))throw new Error("The signing certificate is not for code signing")}function fc(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let n=e,r=n?.rekorBundle?.Payload;if(!(typeof n?.base64Signature=="string"&&typeof n.cert=="string"&&typeof n.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return n}function yc(t){let e;try{e=JSON.parse(Te(V(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function li(t,e){return t.notBefore<=e&&e<=t.notAfter}function ui(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function nt(t){return new Date(t).toISOString()}function mr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var hr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),bc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Ht="https://cloud.calimero.network";async function pi(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await ai(r,e,{identity:n.identity??hr.identity,issuer:n.issuer??hr.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),a=s=>bc.every(c=>/^[0-9a-f]{96}$/i.test(String(s?.[c])));if(typeof o.tag!="string"||i.length===0||!i.every(a))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(n.expectedVersion!==void 0&&o.tag!==n.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${n.expectedVersion}`);return o}async function Lt(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function gi(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function qt(t,e={}){let n=await hi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${mi(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function mi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function hi(t,e){let n=mi(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(a=>a?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return gi(o)}function Bt(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${rt(e,"version")}`}async function fi(t){let e=rt(t.minReleaseVersion,"minReleaseVersion"),n=rt(t.release?.version,"The release version"),r=await pi(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(Ac(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return dr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function jt(t){return rt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await fi({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return ur({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function wc(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:a,...s}=t;r!==void 0&&rt(r,"releaseVersion");let c=a??((d,l)=>fetch(d,l));return pe({baseUrl:e,verify:jt({...s,release:async()=>{let d=r===void 0?await qt(e,{fetch:c}):await hi(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):Lt(Bt(n??Ht,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var yi=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function rt(t,e){let n=typeof t=="string"?yi.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function Ac(t,e){let[n,r]=di(t),[o,i]=di(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let a=r.split("."),s=i.split(".");for(let c=0;c<Math.max(a.length,s.length);c+=1){let[u,d]=[a[c],s[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,g]=[/^\d+$/.test(u),/^\d+$/.test(d)],A=l&&g?Math.sign(Number(u)-Number(d)):l!==g?l?-1:1:u<d?-1:u>d?1:0;if(A!==0)return A}return 0}function di(t){let e=yi.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var xc=new TextEncoder().encode("calimero.warrant.v2"),Rc=new TextEncoder().encode("calimero.warrant.intent.v1"),bi=64,wi=256;async function fr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(Rc,[new TextEncoder().encode(t),n])}async function Ft(t){let e=p(t.context,"context",32),n=p(t.authorAccount,"authorAccount",32),r=p(t.executor,"executor",32),o=p(t.executorKey,"executorKey",32),i=p(t.releaseBytecodeId,"releaseBytecodeId",32),a=yr(t.releaseVersion??""),s=ce(t.accountHeads,"accountHeads"),c=ce(t.governanceFloor,"governanceFloor"),u=await E(t.deviceSecret,t.signer,"deviceSecret"),d=p(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),g=await fr(t.method,t.argsJson),A=C(t.nonce),x=C(t.notAfter),w=await k(xc,[e,n,d,r,o,i,a,l,g,C(s.length),...s,C(c.length),...c,A,x]),v=ot(await u.sign(w));return f(m(e,n,d,r,o,i,R(a.length),a,R(l.length),l,g,R(s.length),...s,R(c.length),...c,A,x,v))}function ot(t){if(!(t instanceof Uint8Array)||t.length!==64){let e=t instanceof Uint8Array?`${t.length} bytes`:typeof t;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return t}function yr(t){let e=new TextEncoder().encode(t);return vc(e.length),e}function vc(t){if(t>wi)throw new Error(`releaseVersion is ${t} bytes, over the ${wi} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>bi)throw new Error(`${e} cites ${n.length} heads, over the ${bi} a node accepts`);return n.map((r,o)=>p(r,`${e}[${o}]`,32))}var Cc=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Sc=new TextEncoder().encode("calimero.context-creation.init.v1"),Vt=256;async function br(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(Sc,[e])}async function kc(t){return k(Cc,[t.group,t.seed,t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.applicationId,new Uint8Array([t.serviceName===null?0:1]),t.serviceName??new Uint8Array(0),new Uint8Array([t.name===null?0:1]),t.name??new Uint8Array(0),t.initHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function Wt(t){let e=p(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):p(t.seed,"seed",32),r=p(t.authorAccount,"authorAccount",32),o=p(t.executor,"executor",32),i=p(t.executorKey,"executorKey",32),a=p(t.applicationId,"applicationId",32),s=Ai(t.serviceName,"serviceName"),c=Ai(t.name,"name"),u=ce(t.accountHeads,"accountHeads"),d=ce(t.governanceFloor,"governanceFloor"),l=await E(t.deviceSecret,t.signer,"deviceSecret"),g=p(l.publicKey,"signer.publicKey",32),A=await br(t.initArgs),x=await kc({group:e,seed:n,authorAccount:r,deviceKey:g,executor:o,executorKey:i,applicationId:a,serviceName:s,name:c,initHash:A,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),w=ot(await l.sign(x));return{warrant:f(m(e,n,r,g,o,i,a,xi(s),xi(c),A,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),w)),seed:f(n)}}function Ri(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,g)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${g} (${n.length} bytes)`);let A=n.subarray(o,o+l);return o+=l,A},a=l=>r.getUint32(i(4,l).byteOffset,!0),s=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let g=i(1,l)[0];if(g===0)return null;if(g!==1)throw new Error(`${l} has option tag ${g}, expected 0 or 1`);let A=a(l);if(A>Vt)throw new Error(`${l} is ${A} bytes, over the ${Vt} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(A,l))},u=l=>{let g=a(l);if(g>64)throw new Error(`${l} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>f(i(32,l)))},d={group:f(i(32,"group")),seed:f(i(32,"seed")),authorAccount:f(i(32,"authorAccount")),deviceKey:f(i(32,"deviceKey")),executor:f(i(32,"executor")),executorKey:f(i(32,"executorKey")),applicationId:f(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:f(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:s("nonce"),notAfter:s("notAfter"),signature:f(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Ai(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>Vt)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${Vt} a node accepts`);return n}function xi(t){return t===null?new Uint8Array([0]):m(new Uint8Array([1]),R(t.length),t)}var Ec=new TextEncoder().encode("calimero.governance-warrant.v1"),Ic=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Pc={group:0,root:1};async function wr(t){return k(Ic,[new Uint8Array([Ar(t.kind)]),t.bytes])}async function Tc(t){return k(Ec,[t.scope,new Uint8Array([Ar(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function it(t){let e=p(t.scope,"scope",32),n=p(t.authorAccount,"authorAccount",32),r=p(t.executor,"executor",32),o=p(t.executorKey,"executorKey",32),i=ce(t.accountHeads,"accountHeads"),a=ce(t.governanceFloor,"governanceFloor"),s=Ar(t.op.kind),c=await E(t.deviceSecret,t.signer,"deviceSecret"),u=p(c.publicKey,"signer.publicKey",32),d=await wr(t.op),l=await Tc({scope:e,kind:t.op.kind,authorAccount:n,deviceKey:u,executor:r,executorKey:o,opHash:d,accountHeads:i,governanceFloor:a,nonce:t.nonce,notAfter:t.notAfter}),g=ot(await c.sign(l));return f(m(e,new Uint8Array([s]),n,u,r,o,d,R(i.length),...i,R(a.length),...a,C(t.nonce),C(t.notAfter),g))}function vi(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,g)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${g} (${n.length} bytes)`);let A=n.subarray(o,o+l);return o+=l,A},a=l=>r.getUint32(i(4,l).byteOffset,!0),s=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let g=a(l);if(g>64)throw new Error(`${l} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>f(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:f(i(32,"scope")),kind:u(),authorAccount:f(i(32,"authorAccount")),deviceKey:f(i(32,"deviceKey")),executor:f(i(32,"executor")),executorKey:f(i(32,"executorKey")),opHash:f(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:s("nonce"),notAfter:s("notAfter"),signature:f(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Ar(t){let e=Pc[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Dc={Admin:0,Member:1,ReadOnly:2},G={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},st={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Nc=new TextEncoder().encode("calimero.namespace.id.v1"),Rr=new Uint8Array(32),Jt=R(0);function Si(t){let e=Dc[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function D(t){return new Uint8Array([t])}function De(t,e){return{kind:"group",bytes:m(D(G.MemberAdded),p(t,"member",32),Si(e))}}function zt(t){return{kind:"group",bytes:m(D(G.MemberRemoved),p(t,"member",32),Rr,Jt)}}function at(t){return{kind:"group",bytes:m(D(G.MemberLeft),p(t,"member",32),Rr,Jt)}}function Qt(t,e){return{kind:"group",bytes:m(D(G.MemberRoleSet),p(t,"member",32),Si(e))}}var Oc=new TextEncoder().encode("calimero.subgroup.id.v1");async function vr(t,e,n,r){return f(await k(Oc,[p(t,"admin",32),p(e,"parentId",32),new Uint8Array([n?1:0]),p(r,"salt",32)]))}function Ci(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return m(R(n.length),n)}function Yt(t){return{kind:"group",bytes:m(D(G.TargetApplicationSet),Rr,p(t.applicationId,"applicationId",32),Ci(t.package,"package"),Ci(t.version,"version"))}}function Ne(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ue(t,U.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:m(D(G.DefaultCapabilitiesSet),R(t))}}function Cr(t){return{kind:"root",bytes:m(D(st.GroupCreated),p(t.groupId,"groupId",32),p(t.parentId,"parentId",32),D(t.restricted?1:0),p(t.admin,"admin",32),p(t.salt,"salt",32))}}async function Oe(t){let e=t.salt??f(crypto.getRandomValues(new Uint8Array(32))),n=await vr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Cr({...t,groupId:n,salt:e})}}function Xt(t,e){return{kind:"root",bytes:m(D(st.GroupReparented),p(t,"childGroupId",32),p(e,"newParentId",32))}}function Zt(t){return{kind:"root",bytes:m(D(st.GroupDeleted),p(t,"rootGroupId",32),Jt,Jt)}}async function en(t,e){return f(await k(Nc,[p(t,"founder",32),p(e,"salt",32)]))}function tn(t){let e=j(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:m(D(st.NamespaceCreatedV2),p(t.founder,"founder",32),e,p(t.salt,"salt",32))}}function xr(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function Sr(t){return t===void 0?D(0):m(D(1),xr(t))}function kr(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return m(R(n.length),...n.flatMap(([,r,o])=>[xr(o),xr(r)]))}function Uc(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(ue(t,U.CAN_AUTHOR_ON_BEHALF))throw new Error(`${e} may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it`);return t}function nn(t,e){return{kind:"group",bytes:m(D(G.MemberCapabilitySet),p(t,"member",32),R(Uc(e,"capabilities")))}}function rn(t){return{kind:"group",bytes:m(D(G.ContextDetached),p(t,"contextId",32))}}function on(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:m(D(G.SubgroupVisibilitySet),D(t==="open"?0:1))}}function Ue(t={}){return{kind:"group",bytes:m(D(G.GroupMetadataSet),Sr(t.name),kr(t.data))}}function sn(t,e={}){return{kind:"group",bytes:m(D(G.MemberMetadataSet),p(t,"member",32),Sr(e.name),kr(e.data))}}function an(t,e={}){return{kind:"group",bytes:m(D(G.ContextMetadataSet),p(t,"contextId",32),Sr(e.name),kr(e.data))}}function ki(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return D(t)}function Ei(t,e,n){return{kind:"group",bytes:m(D(G.ContextCapabilityGranted),p(t,"contextId",32),p(e,"member",32),ki(n))}}function Ii(t,e,n){return{kind:"group",bytes:m(D(G.ContextCapabilityRevoked),p(t,"contextId",32),p(e,"member",32),ki(n))}}function cn(t){return{kind:"root",bytes:m(D(st.MemberJoinedOpen),p(t.member,"member",32),p(t.groupId,"groupId",32),j(t.credential,"credential"))}}var ln=300,ge=class extends Error{constructor(n,r,o){super(`relay refused the intent (HTTP ${o}): ${n}`);this.reason=n;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},Mc=t=>new Promise(e=>setTimeout(e,t));function _c(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var W=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return E(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${encodeURIComponent(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),a=f(p(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),s=o.releaseVersion??"";yr(s);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??ln,l=await Ft({context:e,authorAccount:this.config.authorAccount,executor:i.executorAccount,executorKey:i.executorKey,releaseBytecodeId:a,releaseVersion:s,method:n,argsJson:r,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),g=await this.json("POST",`/admin-api/contexts/${encodeURIComponent(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:g.data.rootHash,returns:g.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${encodeURIComponent(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new ge(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new ge(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),a=await this.config.nonces.next(),s=this.config.ttlSeconds??ln,{warrant:c}=await Wt({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:a,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),signer:i}),u=await this.json("POST",`/admin-api/groups/${encodeURIComponent(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new ge(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),a=this.config.ttlSeconds??ln,s=await it({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:o});return{groupId:(await this.postGovernance(e.groupId,e.op,s)).groupId}}async foundNamespace(e){if(!e?.executor)throw new Error("foundNamespace needs the relay's account and signing key: pass executor (checked before signing, no nonce was spent)");let n=this.checkedExecutor(e.executor),r=e.salt?f(p(e.salt,"salt",32)):f(crypto.getRandomValues(new Uint8Array(32))),o=await en(this.config.authorAccount,r),i=tn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),a=e.defaultCapabilities===void 0?void 0:Ne(e.defaultCapabilities),s=e.application?Yt(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??ln,l=await it({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),g=await this.postGovernance(o,i,l),A={namespaceId:g.groupId,salt:r,teeEnabled:g.teeEnabled??!1,...g.teeError?{teeError:g.teeError}:{}},x=A,w=v=>v instanceof Error?v.message:String(v);if(s)try{await this.govern({groupId:A.namespaceId,op:s}),x={...x,applicationSet:!0}}catch(v){x={...x,applicationSet:!1,applicationError:w(v)}}if(a)try{await this.govern({groupId:A.namespaceId,op:a}),x={...x,defaultCapabilitiesSet:!0}}catch(v){x={...x,defaultCapabilitiesSet:!1,defaultCapabilitiesError:w(v)}}return x}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${encodeURIComponent(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:f(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:f(p(e.executorAccount??"","the relay's executorAccount",32)),executorKey:f(p(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(a){if(!(a instanceof T&&a.status===429)||i>=this.rateLimitRetries)throw a;let c=_c(a.headers);await Mc(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs),s;try{s=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new T(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(a)}if(!s.ok){let c=await s.text().catch(()=>"");if(s.status===400||s.status===403){let u=Gc(c);throw new ge(u,/nonce/i.test(u),s.status)}throw new T(s.status,s.statusText,`${this.baseUrl}${n}`,s.headers,c)}if(s.status!==204)return await s.json()}};function Gc(t){if(!t)return"no reason given";try{let e=JSON.parse(t);for(let n of[e.error,e.message])if(typeof n=="string"&&n)return n}catch{}return t}var me=class{constructor(e,n=null){this.relay=e;this.observer=n;this.kind="relay"}get canSubscribe(){return this.observer!==null}get events(){return this.observer}get client(){return this.relay}async execute(e){let{returns:n}=await this.executeWithMetadata(e);return n}async executeWithMetadata(e){let n=await this.relay.execute(e.contextId,e.method,e.argsJson??{});return{returns:n.returns,transport:"relay",rootHash:n.rootHash}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var $c=new TextEncoder().encode("calimero.auth.login.v1"),Pi={webOrigin:0,codeSigningId:1,cli:2};function Ti(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function Kc(t){return m(Uint8Array.from([Pi[t.kind]]),Ti(t))}function Hc(t){let e=Uint8Array.from([Pi[t.kind]]);if(t.kind==="cli")return e;let n=Ti(t);return m(e,R(n.length),n)}async function un(t){let e=p(t.node,"node",32),n=p(t.challenge,"challenge",32),r=p(t.sessionKey,"sessionKey",32),o=await E(t.deviceSecret,t.signer,"deviceSecret"),i=p(o.publicKey,"signer.publicKey",32),a=C(t.issuedAt),s=C(t.expiresAt),c=await k($c,[e,Kc(t.audience),n,r,i,a,s]),u=await o.sign(c);return f(m(e,Hc(t.audience),n,r,i,a,s,u))}var Lc=300;async function Er(){let t=f(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:f(await oe(t)),secret:t}}async function Me(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(g,A)=>{let x=new AbortController,w=setTimeout(()=>x.abort(),n),v;try{let P={...A,signal:x.signal};v=t.fetch?await t.fetch(`${e}${g}`,P):await globalThis.fetch(`${e}${g}`,P)}catch(P){throw new T(0,P instanceof Error?P.name:"NetworkError",`${e}${g}`,new Headers,P instanceof Error?P.message:String(P))}finally{clearTimeout(w)}let I=await v.text().catch(()=>"");if(!v.ok)throw new T(v.status,v.statusText,`${e}${g}`,v.headers,I);return I?JSON.parse(I):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let a=await Er(),s=Math.floor(Date.now()/1e3),c=await un({node:t.node,audience:t.audience,challenge:i,sessionKey:a.publicKey,issuedAt:s,expiresAt:s+(t.ttlSeconds??Lc),signer:await E(t.deviceSecret,t.signer,"deviceSecret")}),u=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:a.publicKey,client_name:t.clientName??e,timestamp:s,provider_data:{challenge:i,login_statement:c,account_proof:t.accountProof}})}),d=u.access_token??u.data?.access_token,l=u.refresh_token??u.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:l??"",sessionKey:a.publicKey,sessionSecret:a.secret}}var qc=3e4;function Ge(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Bc(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));return typeof r.exp=="number"?r.exp*1e3:null}catch{return null}}var _e=class{constructor(e){this.session=null;this.sessionExpiresAt=null;this.pending=null;this.sseClient=null;this.wsClient=null;this.config=e}get nodeKey(){return this.config.nodeKey}async accessToken(){let e=Date.now();return this.session&&this.sessionExpiresAt!==null&&this.sessionExpiresAt-qc>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Me({nodeUrl:this.config.nodeUrl,node:this.config.nodeKey,signer:await this.config.signer(),accountProof:this.config.accountProof,audience:this.config.audience,clientName:this.config.clientName,ttlSeconds:this.config.ttlSeconds,fetch:this.config.fetch,timeoutMs:this.config.timeoutMs});return this.session=e,this.sessionExpiresAt=Bc(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new L({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new ie({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var Q=t=>new TextEncoder().encode(t),jc=Q("calimero.auth.request.v1"),Fc=Q("calimero.auth.request.body.v1"),Ir="X-Calimero-Proof",Vc=300;async function Pr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);if(n.includes("?"))throw new Error(`the path must carry no query string, got ${JSON.stringify(n)} \u2014 a query is excluded from the signature on purpose, because a proxy may rewrite one. Anything that must be bound belongs in the body.`);let o=t.body===void 0?new Uint8Array:typeof t.body=="string"?Q(t.body):t.body,i=await k(Fc,[o]),a=Math.floor(t.now??Date.now()/1e3),s=a+(t.validForSeconds??Vc),c=await k(jc,[Q(e),Q(n),i,C(a),C(s)]),u=await Wc(c,t);if(u.length!==64)throw new Error(`the signer returned ${u.length} bytes, not a 64-byte signature`);let d=m(R(Q(e).length),Q(e),R(Q(n).length),Q(n),i,C(a),C(s),u),l=Jc(r,"credential");return f(m(l,new Uint8Array([0]),d))}async function Wc(t,e){if(e.signer)return e.signer.sign(t);if(!e.deviceSecret)throw new Error("signRequestProof needs either `deviceSecret` or `signer`");let n=await re(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function Jc(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} is not an even-length hex string`);return p(n,e,n.length/2)}function Tr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await Pr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Ir]:o}}}function zc(t){return new URL(t).pathname}var Di=new TextEncoder().encode("calimero/presence/1");async function Ni(t){let e=t===null?new Uint8Array([0]):m(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function Dr(t){return m(Di,p(t.contextId,"contextId",32),p(t.author,"author",32),C(t.seq),C(t.sentAtMs),await Ni(t.state))}var Qc=2500,ct=class{constructor(e){this.timers=new Map;this.lastSeq=new Map;this.refused=new Set;this.generation=new Map;this.relay=e.relay,this.events=e.events,this.heartbeatMs=e.heartbeatMs??Qc,this.now=e.now??Date.now}async set(e,n,r=se()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=se()){return Pt(this.events(),e,n,r)}close(){for(let e of new Set([...this.timers.keys(),...this.generation.keys()]))this.bump(e)}bump(e){this.stop(e);let n=(this.generation.get(e)??0)+1;return this.generation.set(e,n),n}stop(e){let n=this.timers.get(e);n!==void 0&&clearInterval(n),this.timers.delete(e)}nextSeq(e){let n=Math.max(this.now(),(this.lastSeq.get(e)??0)+1);return this.lastSeq.set(e,n),n}async send(e,n){if(this.refused.has(e))return;let r=await this.relay.authorSigner(),o=this.nextSeq(e),i=this.now(),a=await Dr({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),s=f(await r.sign(a));try{await this.relay.presenceIntent(e,{state:n===null?null:f(n),seq:o,sentAtMs:i,signature:s,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function Oi(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function Ui(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function Yc(t,e,n){let r=e?.nodeKey;return r?new _e({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??Ge(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var he=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof W?e.relay:new W({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=Yc(i,e.observe,o),this.rpcTransport=new me(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=Tr(e.proof)),e.session){let a=e.session;this.relayAdmin=lo({baseUrl:i.relayUrl,getAuthToken:typeof a=="string"?async()=>a:a,fetch:o})}else if(this.proofAuthorizer){let a=this.proofAuthorizer;this.relayAdmin=vt(Je({fetch:(s,c)=>o?o(s,c):globalThis.fetch(s,c),baseUrl:i.relayUrl,authorizeRequest:a}),{baseUrl:i.relayUrl})}return}this.transport="node";let{transport:n,...r}=e;this.nodeClient=new $e(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw Oi("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof me))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new L({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw Ui("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):Ui("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new ct({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw Oi("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function dn(t){return new he(t)}var Ur="calimero.delegated.connection",Mr="calimero.delegated.credential";function _r(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(Ur);return t?JSON.parse(t):null}catch{return null}}function _i(t){try{sessionStorage.setItem(Ur,JSON.stringify(t))}catch{}}function Gi(){try{sessionStorage.removeItem(Ur)}catch{}}function $i(){let t=_r();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(Mr);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function Ki(t){try{sessionStorage.setItem(Mr,JSON.stringify(t))}catch{}}function Hi(){try{sessionStorage.removeItem(Mr)}catch{}}function Gr(t){let e=gn(t);return{next:async()=>{let n=0n;try{n=Li(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function gn(t){return`calimero.nonce.${t}`}function Li(t){let e=localStorage.getItem(gn(t));if(e!==null)return BigInt(e);let n=`${gn(t)}.`,r=0n;for(let o=0;o<localStorage.length;o++){let i=localStorage.key(o);if(!i?.startsWith(n))continue;let a=BigInt(localStorage.getItem(i)??"0");a>r&&(r=a)}return r}function hn(t,e,n){try{Li(t)<=n&&localStorage.setItem(gn(t),String(n+1n))}catch{}}var qi="calimero.delegated.relay-node-key.";function Y(t){return t.replace(/\/+$/,"")}function $r(t,e){localStorage.setItem(qi+Y(t),e.trim().toLowerCase())}function fn(t){try{let e=localStorage.getItem(qi+Y(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function Kr(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Xc="locked-read-only",Zc="2.3.99",Nr;function el(t){let e=t,n=typeof e.verify=="function"?e.verify:e.default?.verify;if(typeof n!="function")throw new TypeError("@phala/dcap-qvl loaded without a verify function");return n}var Ke=class extends Error{constructor(n,r){super(`${n}: ${r instanceof Error?r.message:String(r)}`);this.step=n;this.cause=r;this.name="RelayKeyTransportError"}};async function Mi(t,e){try{return await e()}catch(n){throw n instanceof Ke?n:new Ke(t,n)}}function tl(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new Ke(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function Bi(t,e){return Object.assign(async r=>{let o=await Mi("loading the quote verifier",()=>(Nr??(Nr=import("@phala/dcap-qvl").then(i=>el(i),i=>{throw Nr=void 0,i})),Nr));return jt({dcapVerify:o,release:()=>Mi("fetching the release the relay runs",async()=>Lt(Bt(Ht,await qt(t,{fetch:e})))),profile:Xc,minReleaseVersion:Zc})(r)},{includeCollateral:!0})}async function He(t,e={}){let n=e.fresh?null:fn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=tl(r);try{let i=Kr(t),{nodeKey:a}=await Gt({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:Bi(t,o)}});return $r(t,a),{kind:"learned",nodeKey:a}}catch(i){return i instanceof Ke||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function yn(t){let e=await He(t);return e.kind==="learned"?e.nodeKey:(console.warn("[mero-js] could not learn the relay node key from its attestation",e.error),null)}var mn=[1e3,2e3,5e3,1e4,3e4];function nl(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function ji(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await He(t);if(o.kind==="learned")return o.nodeKey;if(o.kind==="refused")return console.warn("[mero-js] refusing the relay's attestation; its node key stays unknown",o.error),null;let i=mn[Math.min(r,mn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await nl(i,n)}return null}function rl(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var Or=new Map;function Fi(){Or.clear()}async function ol(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function il(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function sl(t){let e=(o,i)=>globalThis.fetch(o,i),n=pe({baseUrl:t,verify:Bi(t,e),fetch:e}),r=!1;return async(o,i)=>{let a=new Request(o,i);if(r&&il(a))return e(a);let s=await n(a.clone());return await ol(s)?(r||(r=!0,console.warn(`[mero-js] ${Y(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(a)):s}}function Le(t){if(Kr(t))return;let e=Y(t),n=Or.get(e);return n||(n=sl(t),Or.set(e,n)),n}function al(t,e){let n=null,r=null;return async()=>{let o=n?rl(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Me({nodeUrl:t.relayUrl,fetch:Le(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:Ge()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var pn=new Map;function Vi(){pn.clear()}function cl(t){return typeof t=="object"&&t!==null&&t.status===409}function ll(t,e){let n=t.rpc,r=Y(e),o=async i=>{let a=`${r}|${i.contextId}|${i.method}`;if(pn.get(a)!=="write")try{let{returns:s}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return pn.set(a,"read"),{returns:s,transport:"relay"}}catch(s){cl(s)&&pn.set(a,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function ul(t){return new L({baseUrl:t,authorize:async()=>({}),fetch:(e,n)=>new Promise((r,o)=>{let i=()=>o(Object.assign(new Error("the stream was closed before the relay was attested"),{name:"AbortError"}));if(n?.signal?.aborted)return i();n?.signal?.addEventListener("abort",i,{once:!0})})})}function dl(t,e){let n=e.session?ll(t,e.relayUrl):null,r=null;return new Proxy(t,{get(o,i){if(i==="rpc"&&n)return n;if(!e.attested){if(i==="canSubscribe")return!1;if(i==="events")return r??(r=ul(e.relayUrl));if(i==="close")return()=>{r?.close(),o.close()}}let a=Reflect.get(o,i,o);return typeof a=="function"?a.bind(o):a}})}function bn(t,e){if(!t.relayUrl)return null;let n=fn(t.relayUrl),r=dn({transport:"relay",fetch:Le(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:Gr(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?al({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return dl(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||Kr(t.relayUrl)})}var Wi="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(Wi+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function Hr(t,e){try{localStorage.setItem(Wi+t,JSON.stringify(e))}catch{}}function fe(t,e,n){let r=q(t),o=Y(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),Hr(t,r)}function Ji(t,e){return q(t).contexts[e]??null}function wn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||Y(t.relayUrl)!==Y(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function qe(t){let e=q(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(Y);return[...new Set(n)]}async function zi(t){let e=[],n=q(t.account);for(let r of qe(t))try{if(!await yn(r))continue;let o=bn({...t,relayUrl:r},null);if(!o)continue;let{contexts:i}=await o.admin.getContexts();for(let a of i??[])e.push({...a,relayUrl:r}),n.contexts[a.id]=r}catch(o){console.warn(`[mero-js] could not list contexts on ${r}`,o)}return Hr(t.account,n),e}async function Qi(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let a of qe(t))try{if(!await yn(a))continue;let s=bn({...t,relayUrl:a},null);if(!s)continue;for(let c of await s.admin.listNamespaces())n.has(c.namespaceId)||(n.add(c.namespaceId),e.push({...c,relayUrl:a}),(o=r.namespaces)[i=c.namespaceId]??(o[i]=a))}catch(s){console.warn(`[mero-js] could not list namespaces on ${a}`,s)}return Hr(t.account,r),e}function xn(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function lt(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}function pl(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var An=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function gl(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??xn(1),r=t.onLookupFailure??"throw",o=null,i=null,a=async()=>{let s=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of s){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new An(t.contextId,t.authorDeviceKey);if(c===null){let d=s.find(g=>g.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=a().finally(()=>{i=null})),await i);let s=await n.next(),c=o!==null&&o>s?o:s;return o=c+1n,c},async advanceTo(s){(o===null||s>o)&&(o=s),await n.advanceTo?.(s)}}}async function Yi(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await E(t.deviceSecret,t.signer,"deviceSecret"),n=new $({cloudBaseUrl:t.cloudBaseUrl,sessionToken:t.sessionToken,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs});!t.sessionToken&&t.googleIdToken&&await n.signInWithGoogle(t.googleIdToken);let r=await n.getMyNamespaces(),o=hl(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),a=Lr(i);if(!a)throw new Error(fl(o,i));let s=new W({relayUrl:a.relayUrl,executorAccount:a.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??yl(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?pe({baseUrl:a.relayUrl,verify:t.seal,fetch:t.fetch}):t.fetch,timeoutMs:t.timeoutMs});return{cloud:n,relay:s,namespaceId:o.namespaceId,namespace:o,relayInfo:a,execute:(c,u,d)=>s.execute(c,u,d),client:new he({transport:"relay",relay:s,observe:{nodeKey:t.relayNodeKey??a.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function ml(t){let{root:e,authorAccount:n,...r}=t,o=await E(r.deviceSecret,r.signer,"deviceSecret"),i=await z(e),s=await new $({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return Yi({...r,deviceSecret:void 0,signer:o,sessionToken:s.sessionToken,authorAccount:n??i.accountId})}function hl(t,e){if(e){let n=t.find(r=>r.namespaceId===e);if(!n)throw new Error(`this account owns no namespace ${e}; it owns: ${t.map(r=>r.namespaceId).join(", ")||"(none)"}`);return n}if(t.length===0)throw new Error("this account owns no namespaces in the cloud: claim one first, then enable HA on it so a relay is assigned");if(t.length>1)throw new Error(`this account owns ${t.length} namespaces \u2014 pass namespaceId to say which: ${t.map(n=>n.namespaceId).join(", ")}`);return t[0]}function fl(t,e){if(e.length===0)return t.haStatus==="enabled"?`namespace ${t.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${t.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let n=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(n.length===e.length)return`every node on namespace ${t.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;let r=e.filter(o=>o.teeRole===null&&!o.authorshipReady);return r.length>0&&r.length+n.length===e.length?`every relay on namespace ${t.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${r.map(o=>o.executorAccount??o.peerId).join(", ")||"the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`:`namespace ${t.namespaceId} has ${e.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`}function yl(t){let e=`mero-js:warrant-nonce:${t}`;try{return lt(e)}catch{return xn(1)}}var bl=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Xi(t,e){p(e,"deviceSecret",32);let n=await re(e),r=m(bl,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return wl(o)}async function Rn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Xi(t.nonce,e.deviceSecret)}}function wl(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Al="https://cloud.calimero.network";function es(t){if(!/^[0-9a-f]{64}$/.test(t.accountId))throw new Error("accountId must be 64 lowercase hex characters");let e=new URL(t.cloudWebUrl??Al);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",t.returnTo),e.toString()}function xl(t){throw window.location.assign(es(t)),new Error("redirecting to the cloud to authorise this link")}function Rl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Zi(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");return!r||!o?null:(Zi(),{grant:r,account:o})}function Zi(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function vl(t){let e=await z(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new $({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,signer:e.signer})}var Cl="enrol-device",Sl="enrol-kem",kl="callback-url",El="state";function rs(t){ns(t.devicePublicKey,"devicePublicKey"),ns(t.kemPublicKey,"kemPublicKey"),Nl(t.returnTo),Dl(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(Cl,t.devicePublicKey),e.searchParams.set(Sl,t.kemPublicKey),e.searchParams.set(kl,t.returnTo),t.state&&e.searchParams.set(El,t.state),e.toString()}function Il(t){throw window.location.assign(rs(t)),new Error("redirecting to the wallet to approve this device")}function Pl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw ts(),new Error(n==="denied"||n==="cancelled"?"the device was not approved at the wallet":`the wallet refused this enrolment: ${n}`);let r=e.get("credential"),o=e.get("account"),i=e.get("device");if(!r||!o||!i)return null;ts();let a=e.get("state");return{credential:r,account:o,device:i,...a?{state:a}:{}}}function ts(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Tl(t){if(t.expectState!==void 0&&t.expectState!==t.state)throw new Error("this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent");let e=await Dt(t.credential);if(e.signPublicKey!==ye(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${ye(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==ye(t.kemPublicKey))throw new Error(`this credential names delivery key ${e.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`);if(e.account!==ye(t.account))throw new Error(`the wallet reported account ${ye(t.account)}, but the credential names ${e.account}`);if(e.device!==ye(t.device))throw new Error(`the wallet reported device ${ye(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function ns(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function ye(t){return t.trim().toLowerCase()}function os(t,e){let n=e??(typeof window>"u"?void 0:window.location.origin);if(!n)return!1;try{return new URL(t).origin!==n}catch{return!1}}function Dl(t){os(t)&&console.warn(`[calimero] enrolling a device but sending the credential to ${new URL(t).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`)}function Nl(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function vn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function Ul(t,e){if(e.size===0)return!0;let n=vn(t.account);return n!==null&&e.has(n)}async function Cn(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let l=await e.getNamespaceRouting(t.namespaceId);n=l.nodes,r=l.servable}catch(l){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${l instanceof Error?l.message:String(l)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(vn).filter(l=>l!==null)),i=n.filter(l=>Ul(l,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let a=i.filter(l=>l.canAdmit),s=a.length>0?a:i,c=a.length===0||!r,u=s.filter(l=>typeof l.relayUrl=="string"&&l.relayUrl.length>0);if(u.length===0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let d=u.find(l=>l.canExecute)??u.find(l=>l.fresh)??u[0];return{ok:!0,relayUrl:d.relayUrl,admitUrl:d.admitUrl??`${d.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${t.namespaceId}/admit`,admitterAccount:d.account,peerId:d.peerId,writable:d.canExecute,stale:!d.fresh||c}}var Sn=1440*60,Br={Admin:0,Member:1,ReadOnly:2};function mt(t){let e=t.admitters??[];return m(qr(t.inviter_identity,"inviter_identity"),qr(t.group_id,"group_id"),C(t.expiration_timestamp),qr(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>p(n,`admitters[${r}]`,32)))}async function jr(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",mt(t)))}function Fr(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function kn(t){let e=await E(t.deviceSecret,t.signer,"deviceSecret"),n=p(e.publicKey,"signer.publicKey",32),r=p(t.groupId,"groupId",32);p(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(g=>g.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=Fr(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((g,A)=>p(g,`admitters[${A}]`,32));let i=t.invitedRole??Br.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let a=t.now??Math.floor(Date.now()/1e3),s=Math.min(t.validForSecs??Sn,Sn);if(!Number.isInteger(s)||s<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:a+s,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await jr(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:f(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(p(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(p(t.appKey,"appKey",32))),l}function qr(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var Vr=24,Ml=new TextEncoder().encode("calimero.namespace.v1"),_l=0,is={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function ss(t,e){if(t==null)return new Uint8Array([0]);if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return m(new Uint8Array([1]),new Uint8Array(t))}function as(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function En(t){let e=t.invitation,n=t.admitter_addrs??[];return m(mt(e),as(t.inviter_signature),t.inviter_account?m(new Uint8Array([1]),p(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(as),ss(t.application_id,"application_id"),ss(t.app_key,"app_key"))}async function In(t){let e=t.parentOpHashes??[],n=p(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?m(new Uint8Array([is.MemberJoinedAt]),p(t.member,"member",32),En(t.invitation),C(o),n):m(new Uint8Array([is.MemberJoined]),p(t.member,"member",32),En(t.invitation),n),a=m(new Uint8Array([_l]),i),s=await E(t.deviceSecret,t.signer,"deviceSecret"),c=p(s.publicKey,"signer.publicKey",32),u=m(new Uint8Array([Vr]),p(t.namespaceId,"namespaceId",32),R(e.length),...e.map((g,A)=>p(g,`parentOpHashes[${A}]`,32)),c,C(t.nonce),a),d=await s.sign(m(Ml,u)),l=new Uint8Array([0]);return f(m(u,d,l))}function Gl(t,e){let n=e?`: ${e}`:"";switch(t){case 400:return`The node refused the join as malformed (400)${n}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;case 403:return`The node refused to carry this join (403)${n}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;case 409:return`That node holds no device of its own, so it cannot endorse anyone (409)${n}. Another admitter from the same invitation would work.`;default:return`The join was not published (HTTP ${t})${n}.`}}function $l(t){let e=lt(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function cs(t){return t.replace(/\/+$/,"")}async function Pn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await In({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??$l(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},a=t.admitUrl??`${cs(t.nodeUrl)}/admin-api/namespaces/${t.namespaceId}/admit`,s=t.deps?.fetch??fetch,c;try{c=await s(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Gl(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:cs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Tn(t){let e=t.deps?.resolve??Cn,n=t.deps?.join??Pn,r=null,o=t.nodeUrl,i;if(!o){let s=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(s.ok===!1)return s;r=s,o=s.relayUrl,i=s.admitUrl}let a=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return a.ok===!1?a:{ok:!0,published:a.published,relay:r,session:a.session}}async function ls(t,e,n,r){let i=await(r.bootstrap??Tn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&fe(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(wn(t,i.session)),{namespaceId:e}}function us(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function Wr(t,e){let n=us(t),r=us(e),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length);let i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i),a=>a.toString(16).padStart(2,"0")).join("")}function Kl(t,e){let[n,r]=[t,e].map(o=>o.split(/[.-]/).map(i=>Number.parseInt(i,10)||0));for(let o=0;o<Math.max(n.length,r.length);o++)if((n[o]??0)!==(r[o]??0))return(n[o]??0)>(r[o]??0);return!1}function ht(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Kl(n.appVersion,e.appVersion)?n:e,void 0)}async function ft(t,e,n=globalThis.fetch){let r=`${t.replace(/\/+$/,"")}/api/v2/bundles?package=${encodeURIComponent(e)}`,o=await n(r,{headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`the registry has no ${e} (HTTP ${o.status})`);let i=await o.json();return Array.isArray(i)?i:[]}async function ds(t,e,n={}){let o=(await ft(t,e,n.fetch)).filter(c=>!c.yanked),i=[...new Set(o.map(c=>c.signerId).filter(c=>typeof c=="string"&&c.length>0))];if(i.length>1)throw new Error(`the registry lists ${e} under more than one publisher (${i.join(", ")}): refusing to guess which application it is`);let a=ht(o);if(!a)throw new Error(`the registry lists no version of ${e}`);let s=a.signerId;if(!s)throw new Error(`the registry names no publisher for ${e} ${a.appVersion}`);return{applicationId:await Wr(e,s),signerId:s,version:a.appVersion}}function gs(t,e){return{next:async()=>Hl(t,e)}}function Hl(t,e){let n=`calimero.governance-nonce.${t}.${e}`,r=0n;try{r=BigInt(localStorage.getItem(n)??"0")}catch{}let o=[r+1n,BigInt(Date.now())].reduce((i,a)=>i>a?i:a);try{localStorage.setItem(n,String(o))}catch{}return o}function ms(t,e){let n=q(t.account).namespaces[e]??t.relayUrl;if(!n)throw new Error("no relay is known for this namespace, so there is nowhere to send this");return n.replace(/\/+$/,"")}function Ll(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Nn(t,e,n,r){return new W({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??Le(e)})}async function yt(t,e,n={}){let r=ms(t,e.namespaceId),o=0n,i=await Nn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Ll(e.initializationParams),name:e.name});return hn(r,i.contextId,o),fe(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function we(t,e,n={}){let r=ms(t,e.namespaceId);return Nn(t,r,gs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function hs(t,e,n={}){let{groupId:r}=await we(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Oe({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await we(t,{namespaceId:e.namespaceId,group:r,op:De(i,"Member")},n);let{contextId:o}=await yt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function On(t,e={},n={}){let o=qe(t).map(u=>u.replace(/\/+$/,""))[0];if(!o)throw new Error("no relay is known for this account, so there is nowhere to found a namespace");let i=await ql(t,o,n.fetch),a=BigInt(Date.now()),s=await Nn(t,o,{next:async()=>a++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${s.namespaceId}`,String(a))}catch{}if(fe(t.account,o,{namespaceId:s.namespaceId}),e.application&&s.applicationSet!==!0)throw new Error(`founded ${s.namespaceId} but could not give it its application: ${s.applicationError??"unknown reason"}`);let c=s.teeEnabled?await jl(t,s.namespaceId,s.salt,o,n):{haEnabled:!1,haError:`the relay did not attest the founding, so no fleet node could be admitted for HA${s.teeError?`: ${s.teeError}`:""}`};return{namespaceId:s.namespaceId,teeEnabled:s.teeEnabled,...c}}async function ql(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await ps(e)};let o=Object.entries(q(t.account).namespaces).find(([,s])=>s.replace(/\/+$/,"")===e)?.[0];if(!o)throw new Error("the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)");let i=await ps(e),a=await Nn(t,e,gs(e,o),n).describeGovernance(o);if(a.executorKey?.toLowerCase()!==i)throw new Error(`the relay's discovery names signing key ${a.executorKey}, not the relay's node key ${i}: refusing to found through it`);return{executorAccount:a.executorAccount,executorKey:i}}async function ps(t){let e=await He(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var Un="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",Dn={account_not_linked:Un,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Bl(t){try{let e=JSON.parse(t.bodyText??""),n=e?.detail?.namespace_id??e?.namespace_id;return typeof n=="string"&&/^[0-9a-f]{64}$/i.test(n)?n.toLowerCase():null}catch{return null}}async function jl(t,e,n,r,o){try{return await new $({cloudBaseUrl:o.cloudBaseUrl,fetch:o.fetch}).enableHaAsAccount({namespaceId:e,salt:n,accountId:t.account,credential:t.credential,deviceSecret:t.deviceSecret,relayUrl:r}),{haEnabled:!0}}catch(i){if(i instanceof be)return{haEnabled:!1,haError:Un};if(i instanceof J&&Dn[i.code]){let a=i.code==="ha_request_pending"?Bl(i):null,s=Dn[i.code];return{haEnabled:!1,haError:a?`${s} (waiting: ${a})`:s}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function Be(t,e,n=globalThis.fetch){let r=ht(await ft(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var fs="calimero.delegated.group-namespace.",Jr=new Map;function ys(t){let e={};try{e=JSON.parse(localStorage.getItem(fs+t)??"{}")}catch{}return{...e,...Jr.get(t)}}function bt(t,e,n){Jr.set(t,{...Jr.get(t),[e]:n});try{let r=ys(t);r[e]=n,localStorage.setItem(fs+t,JSON.stringify(r))}catch{}}function wt(t,e){return q(t.account).namespaces[e]?e:ys(t.account)[e]}function bs(t,e){let n=wt(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function Mn(t,e,n){return we(t,{namespaceId:bs(t,e),group:e,op:n})}async function _n(t,e,n){let r=bs(t,e);return we(t,{namespaceId:r,group:r,op:n})}var Ae=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},je=class extends Error{constructor(n){super(`${n} needs a relay, and this account has none yet: join from an invitation first`);this.method=n;this.name="NoRelayError"}},Fe=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the cloud lists no node holding the namespace, so an invitee with no node of their own has no relay to be admitted through.`:`nobody could claim an invitation to ${n}: the cloud routes to none of the relays or admins it would name as admitters`);this.namespaceId=n;this.reason=r;this.name="InvitationNotClaimableError"}},ws={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Fl=new Set(["upgradeGroup","retryGroupUpgrade","abortMigration","installApplication","installDevApplication","uninstallApplication","generateContextIdentity","deleteContext","leaveContext","createContextAlias","createApplicationAlias","createDeviceAlias","deleteContextAlias","deleteApplicationAlias","deleteDeviceAlias","lookupContextAlias","lookupApplicationAlias","lookupDeviceAlias","listContextAliases","listApplicationAliases","listDeviceAliases","deleteNamespace","createGroupInvitation","joinGroup","setTeeAdmissionPolicy","getTeeAdmissionPolicy","deleteBlob","listAccountDevices","revokeAccountDevice"]);function Vl(t){if(!(t instanceof Error))return!1;let e=t.status;return(e===void 0||e===409)&&/signer [0-9a-f]+ is a direct member/i.test(t.message)}function As(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??Mn,a=e.govern?.root??_n,s=e.createContext??yt,c=e.found??On,u=e.latestVersion??Be,d=e.signInvitation??kn,l=e.join,g=e.routing;async function A(h,y){if(!l)throw new Ae("joinNamespace without a join handler");return l(h,y.invitation)}let x=()=>{if(r===null)throw new je("this call");return r};async function w(h){if(wt(n,h))return;let y=await x().getGroupInfo(h);bt(n.account,h,y.namespaceId??h)}let v=async(h,y,S)=>(await w(y),i(h,y,S)),I=async(h,y,S)=>(await w(y),a(h,y,S));async function P(h){try{return await I(n,h,cn({member:n.account,groupId:h,credential:n.credential})),!0}catch(y){if(Vl(y))return!1;throw y}}async function B(h,y){let S=y??String(await x().getContextGroup(h)),{members:O}=await x().listGroupMembers(S);return O.some(H=>H.identity.toLowerCase()===n.account.toLowerCase())}let M={async listNamespacesForApplication(h){return(await x().listNamespaces()).filter(y=>y.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Ae("createNamespace without a packageName");let y=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:O,haError:H}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:y}});return h.name&&await v(n,S,Ue({name:h.name})),{namespaceId:S,haEnabled:O,...H!==void 0?{haError:H}:{}}},async createGroupInNamespace(h,y={}){let{op:S}=await Oe({parentId:h,restricted:y.visibility==="restricted",admin:n.account}),{groupId:O}=await I(n,h,S);return bt(n.account,O,h),y.groupName&&await v(n,O,Ue({name:y.groupName})),{groupId:O}},async addGroupMembers(h,y){for(let S of y.members)await v(n,h,De(S.identity,S.role??"Member"))},async removeGroupMembers(h,y){for(let S of y.members)await v(n,h,zt(S))},async setGroupMetadata(h,y){await v(n,h,Ue(y))},async setMemberMetadata(h,y,S){await v(n,h,sn(y,S))},async setContextMetadata(h,y,S){await v(n,h,an(y,S))},async setDefaultCapabilities(h,y){await v(n,h,Ne(y.defaultCapabilities))},async setSubgroupVisibility(h,y){await v(n,h,on(y.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,y,S){await v(n,h,nn(y,S.capabilities))},async deleteGroup(h){return await I(n,h,Zt(h)),{isDeleted:!0}},async reparentGroup(h,y){return await I(n,h,Xt(h,y.newParentId)),{reparented:!0}},async leaveGroup(h){await v(n,h,at(n.account))},async leaveNamespace(h){await v(n,h,at(n.account))},async getContextIdentitiesOwned(h){return{identities:await B(h)?[n.account]:[]}},async joinContext(h){return await P(String(await x().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let S=(await x().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:O}=await s(n,{namespaceId:S,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:O,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:y},S]=await Promise.all([x().listGroupMembers(h),x().getGroupInfo(h)]),O=y.filter(Z=>Z.role==="RelayTee").map(Z=>Z.identity.toLowerCase());if(g){let Z=new Set(O.length>0?O:y.filter(te=>te.role==="Admin").map(te=>te.identity.toLowerCase())),ee=null;try{ee=(await g(h)).nodes}catch{}if(ee!==null){if(ee.length===0)throw new Fe(h,"not-hosted");if(!ee.some(te=>te.account!==null&&Z.has(te.account.toLowerCase())))throw new Fe(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...O.length>0?{admitters:O}:{},members:y,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:A,async updateMemberRole(h,y,S){await v(n,h,Qt(y,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await P(h)}},async detachContextFromGroup(h,y){await v(n,h,rn(y))}};return r===null?new Proxy({},{get(h,y){if(typeof y=="string")return y==="getNodeIdentity"?M.getNodeIdentity:y==="joinNamespace"?A:y in ws?ws[y]:async()=>{throw new je(y)}}}):new Proxy(r,{get(h,y,S){return typeof y=="string"&&y in M?M[y]:typeof y=="string"&&Fl.has(y)?async()=>{throw new Ae(y)}:Reflect.get(h,y,S)}})}function xs(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??Be;async function i(s){let{apps:c}=await n.listApplications();if(c.some(l=>l.id===s))return;if(!r.packageName)throw new Error(`application ${s} is not installed on this node, and no packageName is set to install it`);let u=r.packageVersion??await o(r.registryUrl??"https://apps.calimero.network",r.packageName),{applicationId:d}=await n.installApplication({package:r.packageName,version:u});if(d!==s)throw new Error(`installed ${r.packageName}@${u} as ${d}, not ${s}`)}let a={async createNamespace(s){return await i(s.applicationId),n.createNamespace(s)}};return new Proxy(n,{get(s,c,u){return typeof c=="string"&&c in a?a[c]:Reflect.get(s,c,u)}})}var Wl="https://manager.cloud.calimero.network";function zr(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function Qr(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function Lr(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function Jl(t){let e=t.join;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(typeof n.state!="string")return null;let r=Array.isArray(n.refusals)?n.refusals.filter(o=>!!o&&typeof o=="object").map(o=>({peer:String(o.peer??""),reason:String(o.reason??"")})):[];return{state:n.state,attempts:typeof n.attempts=="number"?n.attempts:0,refusals:r,error:typeof n.error=="string"?n.error:null,reportedAt:typeof n.reported_at=="string"?n.reported_at:null}}var zl=/^[0-9a-f]{64}$/;function Ql(t){return typeof t=="string"&&zl.test(t)?t:null}var J=class extends T{constructor(n,r,o,i,a,s){super(r,o,i,a,s);this.code=n;this.name="AccountHaRefusedError"}},be=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};be.CODE="account_not_linked";var ut=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};ut.CODE="account_linked_to_several_users";var dt=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};dt.CODE="ha_request_pending";var pt=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};pt.CODE="unknown_relay";var gt=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};gt.CODE="relay_not_dialable";var Rs={409:[be,ut,dt],422:[pt,gt]};function Yl(t){if(t)try{let e=JSON.parse(t);if(typeof e?.error=="string")return e.error;if(typeof e?.detail=="string")return e.detail;let n=e?.detail?.error;if(typeof n=="string")return n}catch{}}var Xl="x-mdma-session-refresh",Zl="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Wl).replace(/\/+$/,""),this.onSession=e.onSession;let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.routingCredential=e.routingCredential,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let n=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(n)}async signInWithAccount(e){let{signer:n,publicKey:r}=await z(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await Ut({signer:n,nonce:o})})}async getAccountLoginChallenge(){let e=await this.request("GET","/api/auth/account/challenge",{anonymous:!0});return{nonce:e.nonce,expiresAtMs:e.expires_at_ms}}async submitAccountLogin(e){let n=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(n)}async refreshSession(){let e=await this.request("POST","/api/auth/refresh");return this.adoptSession(e)}async signOut(){try{this.session&&await this.request("POST","/api/auth/logout",{parse:"none"})}finally{this.session=null,this.notifySession(null)}}async getMyNamespaces(){return(await this.request("GET","/api/cloud/me/namespaces")).map(n=>({namespaceId:String(n.namespace_id??n.group_id??""),groupId:String(n.group_id??n.namespace_id??""),haStatus:String(n.ha_status??"none"),haEnabledAt:n.ha_enabled_at??null,contexts:Array.isArray(n.contexts)?n.contexts:[],fleetReplicas:n.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:a,teeRole:Qr(r),canExecute:zr(r,a&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:Jl(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return Lr(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,a=r.fresh===!0,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:a,canAdmit:r.can_admit===!0,authorshipReady:s,teeRole:Qr(r),canExecute:zr(r,s&&i!==null&&o!==null&&a)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return Rn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/relays`,{anonymous:!0,headers:await Rn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:Ql(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(a=>{let s=a;return{namespaceId:String(s.namespace_id??""),status:String(s.status??""),authorshipReady:s.authorship_ready===!0,teeRole:Qr(s),fresh:s.fresh===!0,confirmedAt:s.confirmed_at??null,lastSeenAt:s.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:zr(n,r!==null&&o!==null&&i.some(a=>a.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await Qn({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${encodeURIComponent(r)}/namespaces/${encodeURIComponent(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof T&&Rs[i.status]){let a=Yl(i.bodyText),s=Rs[i.status].find(c=>c.CODE===a);if(s&&a)throw new s(a,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await z(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await Xe({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":e.callbackUrl});return{url:`${n}/?${r.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r;try{r=new URL(n).hash}catch{return{}}let o=new URLSearchParams(r.replace(/^#/,"")),i=o.get("grant"),a=o.get("account"),s=o.get("error"),c={};return i&&(c.grant=i),a&&(c.accountId=a),s&&(c.error=s),c}async linkAccountWithGrant(e){let{signer:n,publicKey:r,accountId:o}=await Ot(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await Xe({signer:n,nonce:e.grant})},anonymous:!0});return{accountId:String(i.account_id??o),linkedAt:i.linked_at??null,alreadyLinked:i.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs),s;try{s=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new T(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(a)}if(this.adoptRollingRefresh(s),!s.ok){let c=await s.text().catch(()=>{});throw new T(s.status,s.statusText,`${this.baseUrl}${n}`,s.headers,c)}if(!(r.parse==="none"||s.status===204))return await s.json()}adoptRollingRefresh(e){let n=e.headers.get(Xl);if(!n||!this.session)return;let r=e.headers.get(Zl),o=Number(r);this.session={sessionToken:n,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function Ol(t){let e=t&&typeof t=="object"?t.data??t:void 0;if(!e||typeof e!="object")return[];let n=e.localPeerId,r=e.externalAddrs;if(typeof n!="string"||!n||!Array.isArray(r))return[];let o=`/p2p/${n}`,i=[];for(let a of r){if(typeof a!="string")continue;let s=a.trim();if(!s.startsWith("/"))continue;let c=s.endsWith(o)?s:`${s}${o}`;i.includes(c)||i.push(c)}return i}function eu(t){if(t)return typeof t=="function"?t:kt(t)}var tu="mero-js:token-refresh";function nu(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function Yr(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var $e=class{constructor(e){this.tokenData=null;this.refreshPromise=null;this.storeHoldsTokens=!1;this.tokenGeneration=0;this.onStorage=()=>{this.signedOutElsewhere()&&this.dropLocalTokens()};this.rpcClient=null;this.sseClient=null;this.wsClient=null;this.wsWarned=!1;this.config={timeoutMs:1e4,...e},this.tokenStore=e.tokenStore??null,this.tokenStore&&(this.tokenData=this.tokenStore.getTokens(),this.storeHoldsTokens=this.tokenData!==null,typeof window<"u"&&window.addEventListener("storage",this.onStorage));let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=eu(this.config.requestProof);this.httpClient=Re({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getProof:r,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async o=>{this.tokenData&&(this.tokenData.access_token=o,this.persistTokens(this.tokenData))},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(n?"omit":void 0)}),this.authClient=oo(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=vt(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs})}get auth(){return this.authClient}get admin(){return this.adminClient}get rpc(){return this.rpcClient||(this.rpcClient=new Qe({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new L({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new Ye({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new $(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new ie({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:Yr(i,Date.now()+36e5)},this.persistTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(e){this.tokenStore&&(this.tokenStore.setTokens(e),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=nu();return n?n.request(tu,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.tokenStore?.getTokens()??null;if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let a=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let s=a.data.access_token;return this.tokenData={access_token:s,refresh_token:a.data.refresh_token,expires_at:Yr(s,Date.now()+36e5)},this.persistTokens(this.tokenData),this.tokenData}catch(a){throw new Error(`Token refresh failed: ${a instanceof Error?a.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||Yr(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return Fn(e)}static buildAuthLoginUrl(e,n){return Vn(e,n)}};function ru(t){return new $e(t)}var Xr=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},ou="mero-tokens",Zr=class{constructor(e=ou){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let n=JSON.parse(e);return n&&n.access_token&&n.refresh_token?{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:typeof n.expires_at=="number"?n.expires_at:Date.now()+36e5}:null}catch{return null}}setTokens(e){try{if(typeof localStorage>"u")return;localStorage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{if(typeof localStorage>"u")return;localStorage.removeItem(this.key)}catch{}}};var iu=new TextEncoder().encode("calimero.account.owner-op.v1"),su=new TextEncoder().encode("calimero.account.owner-op.body.v1"),au=new TextEncoder().encode("calimero.account.genesis.v1"),cu=2,eo={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},Ve={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},Cs={AdminChanged:3,RootGuarded:12},lu={replica:0,relay:1},uu=new TextEncoder;function K(t){return new Uint8Array([t])}function Ss(t){let e=uu.encode(t);return m(R(e.length),e)}function X(t){return m(R(t.length),...t.map(Ss))}function ks(t){return K(t?1:0)}function Es(t){let e=lu[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return K(e)}function Is(t){return{kind:"transferOwnership",plane:"group",bytes:m(K(Ve.TransferOwnership),p(t,"newOwner",32))}}function Ps(){return{kind:"groupDelete",plane:"group",bytes:K(Ve.GroupDelete)}}function Ts(t){return{kind:"adminChanged",plane:"root",bytes:m(K(Cs.AdminChanged),p(t,"newAdmin",32))}}function Ds(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:m(K(Ve.TeeAuthoringPolicySet),X(t))}}function Ns(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:m(K(Ve.TeeAdmissionPolicySetV2),X(t.allowedMrtd),X(t.allowedRtmr0),X(t.allowedRtmr1),X(t.allowedRtmr2),X(t.allowedRtmr3),X(t.allowedTcbStatuses),ks(t.acceptMock),Es(t.mode))}}function Os(t){let e=t.minReleaseVersion===void 0?K(0):m(K(1),Ss(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:m(K(Ve.TeeReleaseAdmissionPolicySetV2),X(t.allowedProfiles),e,X(t.allowedTcbStatuses),ks(t.acceptMock),Es(t.mode))}}async function to(t){return k(su,[t])}async function no(t){return k(iu,[p(t.account,"account",32),p(t.namespaceId,"namespaceId",32),p(t.groupId,"groupId",32),K(Us(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function Us(t){let e=eo[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var vs=132;async function Ms(t){let e=await oe(t.rootSecret),n=m(K(cu),e),r=f(await k(au,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let g=j(d,`chain[${l}]`);if(g.length!==vs)throw new Error(`chain[${l}] must be a ${vs}-byte RootKeyHandoff, got ${g.length}`);return g});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let a=await to(t.op.bytes),s=await no({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:a,counter:t.counter,keyEpoch:o}),c=await re(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,s));return f(m(n,R(i.length),...i,p(r,"account",32),p(t.namespaceId,"namespaceId",32),p(t.groupId,"groupId",32),K(Us(t.op.kind)),a,C(t.counter),R(o),u))}function _s(t,e){let n=t.plane==="group"?Ve.RootGuarded:Cs.RootGuarded;return m(K(n),t.bytes,j(e,"rootProof"))}var Gs=[2428,2429,2528,2529],du="localhost",pu=2e3;function $s(t){return`http://${du}:${t}`}function Ks(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function Hs(t,e={}){let{timeoutMs:n=pu,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,i=()=>o.abort(),a=r;a&&a.addEventListener("abort",i,{once:!0});let s=setTimeout(()=>o.abort(),n);try{let c=Ks(t,"admin-api/health"),u=await fetch(c,{method:"GET",signal:o.signal});if(!u.ok)return!1;try{let d=await u.json(),l=d?.data?.status!==void 0?d?.data?.status:d?.status;return l===void 0?!0:typeof l=="string"&&l.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(s),a&&a.removeEventListener("abort",i)}}async function gu(t={}){let{ports:e=Gs,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let a=$s(i);return await Hs(a,{timeoutMs:n,signal:r})?a:null}))).filter(i=>i!==null)}export{vo as ACCOUNT_HA_AUDIENCE,Ro as ACCOUNT_OWNERSHIP_AUDIENCE,J as AccountHaRefusedError,ut as AccountLinkedToSeveralUsersError,be as AccountNotLinkedError,de as AdminApiClient,le as AuthApiClient,ne as AuthRevokedError,U as CAPABILITIES,Ou as CAPABILITY_PRESETS,$ as CloudClient,Gs as DEFAULT_LOCAL_NODE_PORTS,Ht as DEFAULT_RELEASE_MIRROR,Ye as EphemeralClient,zo as HANDSHAKE_PATH,Un as HA_ACCOUNT_NOT_LINKED_MESSAGE,Dn as HA_REFUSAL_MESSAGES,T as HTTPError,dt as HaRequestPendingError,Br as INVITED_ROLE,ge as IntentRefusedError,Fe as InvitationNotClaimableError,Zr as LocalStorageTokenStore,Sn as MAX_INVITATION_VALIDITY_SECS,Xr as MemoryTokenStore,he as MeroClient,$e as MeroJs,hr as NODE_RELEASE_SIGNER,je as NoRelayError,Ae as NotForAccountError,eo as OWNER_OP_KIND,Di as PRESENCE_DOMAIN,lr as PRODUCTION_PROFILE,mn as RELAY_NODE_KEY_RETRY_MS,Ir as REQUEST_PROOF_HEADER,W as RelayClient,gt as RelayNotDialableError,_e as RelayObserver,ct as RelayPresenceClient,me as RelayTransport,Qe as RpcClient,Et as RpcError,et as SEALED_CONTENT_TYPE,Qo as SEALED_PATH,Vr as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,ke as SealedTransportError,L as SseClient,tt as StaleTransportKeyError,pt as UnknownRelayError,An as WarrantNonceExhaustedError,Rt as WarrantNonceRouteUnavailableError,We as WebHttpClient,ie as WsClient,Nt as accountForRoot,F as accountForRootPublicKey,To as accountRootFromPhrase,nr as accountRootFromSecret,No as accountRootSignerFromPhrase,Ts as adminChangedOp,Ol as admitterAddrsFromNetworkStatus,Wr as applicationIdForBundle,He as attemptRelayNodeKey,_t as attestKeyBinding,Gt as attestRelayNodeKey,pl as authorNonceLookup,xl as beginCloudLink,Il as beginDeviceEnrolment,Tn as bootstrapFromInvitation,Vn as buildAuthLoginUrl,bn as buildDelegatedClient,os as callbackIsForeign,St as callerProof,Uu as capMask,Mu as capNames,wn as carryExecutorAccount,Bn as classifyError,Hi as clearDelegatedCredential,Gi as clearDelegatedSession,es as cloudLinkUrl,Bt as cloudNodeReleaseUrl,$n as combineSignals,Zs as compareSemver,vl as completeCloudLink,Tl as completeDeviceEnrolment,Yi as connectCloud,ml as connectCloudWithAccount,Ei as contextCapabilityGrantedOp,Ii as contextCapabilityRevokedOp,rn as contextDetachedOp,an as contextMetadataSetOp,As as createAccountAdmin,Do as createAccountRootSigner,lo as createAdminApiClient,vt as createAdminApiClientFromHttpClient,pe as createAttestedSealedFetch,Du as createAuthApiClient,oo as createAuthApiClientFromHttpClient,Xu as createBrowserAdminApiClient,Pu as createBrowserAuthApiClient,Re as createBrowserHttpClient,yt as createDelegatedContext,hs as createDelegatedPrivateContext,Je as createHttpClient,lt as createLocalStorageNonceSource,xn as createMemoryNonceSource,dn as createMeroClient,ru as createMeroJs,xs as createNodeAdmin,Zu as createNodeAdminApiClient,Tu as createNodeAuthApiClient,At as createNodeHttpClient,Tr as createProofAuthorizer,kt as createProofSigner,ur as createQuoteVerifier,gl as createRecoveringNonceSource,Vs as createRetryableMethod,ei as createSealedFetch,wc as createSignedReleaseSealedFetch,jt as createSignedReleaseVerifier,Kn as createTimeoutSignal,Hn as createUniversalHttpClient,vr as createdSubgroupId,br as creationInitHash,Fr as defaultAdmitters,Ge as defaultAudience,Ne as defaultCapabilitiesSetOp,we as delegatedGovernance,Tt as deviceCertPayload,rs as deviceEnrolmentUrl,Zn as deviceScopePayload,gu as discoverLocalNodes,mt as encodeGroupInvitation,En as encodeSignedInvitation,Zo as fetchAttestedTransportKey,Lt as fetchNodeRelease,qt as fetchNodeReleaseVersion,ft as fetchRegistryBundles,Vi as forgetMethodKinds,Fi as forgetRelaySealing,On as foundDelegatedNamespace,en as foundedNamespaceId,Po as generateAccountRoot,Er as generateSessionKey,Mn as governGroup,_n as governRoot,wr as governanceOpHash,Cr as groupCreatedOp,Ps as groupDeleteOp,Zt as groupDeletedOp,jr as groupInvitationHash,Ue as groupMetadataSetOp,Xt as groupReparentedOp,ue as hasCap,Wu as hexEncodeUtf8,fr as intentHash,Qs as isSettled,ls as joinAsAccount,Pn as joinWithNode,se as jsonCodec,qe as knownRelays,Be as latestPublishedVersion,ji as learnRelayNodeKey,zi as listDelegatedContexts,Qi as listDelegatedNamespaces,$s as localNodeUrl,Me as login,hn as markContextNonceSpent,De as memberAddedOp,nn as memberCapabilitySetOp,cn as memberJoinedOpenOp,at as memberLeftOp,sn as memberMetadataSetOp,zt as memberRemovedOp,Qt as memberRoleSetOp,Yn as mintDeviceId,tn as namespaceCreatedOp,wt as namespaceOfGroup,Ks as nodeEndpoint,gi as nodeReleaseVersionFromImage,vn as normaliseAccount,to as ownerOpDigest,no as ownerOpSigningPayload,Fn as parseAuthCallback,Ri as parseCreationWarrant,Xn as parseDeviceCredential,vi as parseGovernanceWarrant,so as parseWarrantNonce,Gr as persistedNonces,$r as pinRelayNodeKey,Dr as presenceStatementBytes,Hs as probeNodeHealth,Rl as readCloudLinkCallback,$i as readDelegatedCredential,_r as readDelegatedSession,Pl as readEnrolmentCallback,fn as readPinnedRelayNodeKey,q as readRelayMap,io as redeemInvitation,Ji as relayForContext,Le as relayTransportFetch,bt as rememberGroupNamespace,fe as rememberRelay,or as reportDataOf,Wn as requestBodyHash,ds as resolveApplicationIdFromRegistry,Cn as resolveRelayFromInvitation,yn as resolveRelayNodeKey,z as resolveRoot,Ot as resolveRootPair,_s as rootGuardedOpBytes,Rn as routingProofHeaders,Ki as saveDelegatedCredential,_i as saveDelegatedSession,ht as selectLatestBundle,Hu as shouldRetain,Qn as signAccountHaClaim,Xe as signAccountLink,Ut as signAccountLogin,da as signAccountOwnershipClaim,Wt as signCreationWarrant,ko as signDeviceCert,Eo as signDeviceScope,it as signGovernanceWarrant,kn as signGroupInvitation,un as signLoginStatement,In as signMemberJoinOp,Ms as signOwnerOpProof,Ct as signRequest,Pr as signRequestProof,Xi as signRoutingChallenge,Ft as signWarrant,zc as signedPath,yo as signerFromCryptoKey,ve as signerFromSecret,Ni as stateHash,Oe as subgroupCreation,on as subgroupVisibilitySetOp,Pt as subscribePresence,Yt as targetApplicationSetOp,Ns as teeAdmissionPolicyOp,Ds as teeAuthoringPolicyOp,Os as teeReleaseAdmissionPolicyOp,Is as transferOwnershipOp,Xo as transportKeyBinding,fi as trustSignedRelease,dr as trustedMeasurementsFromReleases,Dt as verifyDeviceCredential,pi as verifySignedNodeRelease,Ln as withCap,xt as withRetry,_u as withoutCap};
1
+ function Ln(t){let e=t.filter(Boolean);if(e.length===0)return;let n=AbortSignal;if(typeof n.any=="function")try{return n.any(e)}catch{}let r=new AbortController,o=i=>{r.abort(i.target.reason);for(let s of e)s.removeEventListener("abort",o)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",o,{once:!0})}return r.signal}function Hn(t){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(t);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},t),e.signal}var zs=new Set(["token_reuse","token_revoked"]);function Qs(t){if(t)try{let e=JSON.parse(t),n=e?.error;if(typeof n=="string"&&n.trim()!=="")return n;let r=n?.message;if(typeof r=="string"&&r.trim()!=="")return r;let o=e?.detail;if(typeof o=="string"&&o.trim()!=="")return o}catch{}}var T=class extends Error{constructor(n,r,o,i,s){let a=Qs(s)??(n===0&&s?.trim()?s.trim():void 0);super(a?`HTTP ${n} ${r}: ${a}`:`HTTP ${n} ${r}`);this.status=n;this.statusText=r;this.url=o;this.headers=i;this.bodyText=s;this.name="HTTPError";this.explanation=a}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:co(this.headers),bodyText:this.bodyText}}},ne=class extends T{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.reason=n;this.name="AuthRevokedError";this.message=`Authentication revoked (${n}): HTTP ${r} ${o}`}};function co(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function Ys(t){try{return new URL(t).pathname}catch{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}}var Je=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,n){return this.request(e,{...n,method:"GET"})}async post(e,n,r){return this.request(e,{...r,method:"POST",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async put(e,n,r){return this.request(e,{...r,method:"PUT",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async delete(e,n){return this.request(e,{...n,method:"DELETE"})}async patch(e,n,r){return this.request(e,{...r,method:"PATCH",body:n?JSON.stringify(n):void 0,headers:{"Content-Type":"application/json",...r?.headers}})}async head(e,n){let r=await this.makeRequest(e,{...n,method:"HEAD",parse:"response"});return{headers:co(r.headers),status:r.status}}async request(e,n){return this.makeRequest(e,n)}async makeRequest(e,n,r=0,o){let s=this.buildUrl(e),a=o??Date.now(),c=this.createAbortSignal(n),u=await this.buildHeaders(n?.headers),d;u instanceof Headers?(d={},u.forEach((w,v)=>{d[v]=w})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let w=n?.body;if(w!==void 0&&typeof w!="string"&&!(w instanceof Uint8Array))throw new Error("this transport authorizes each request against its body, so the body must be a string or Uint8Array \u2014 a stream cannot be signed, because the signature would have to read bytes the request then cannot send.");Object.assign(d,await this.transport.authorizeRequest({method:l,path:new URL(s).pathname,body:w}))}let g={method:l,headers:d},A=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!A||n?.body!==void 0&&A&&r===0)&&(g.body=n.body);let x;if(r>0&&o!==void 0){let w=n?.timeoutMs||this.transport.timeoutMs;if(w){let v=Date.now()-a,I=Math.max(0,w-v);x=this.createAbortSignal({...n,timeoutMs:I})}else x=this.createAbortSignal(n)}else x=c;if(x&&(g.signal=x),this.transport.credentials!==void 0&&(g.credentials=this.transport.credentials),n?.mode!==void 0&&(g.mode=n.mode),n?.cache!==void 0&&(g.cache=n.cache),n?.redirect!==void 0&&(g.redirect=n.redirect),n?.referrer!==void 0&&(g.referrer=n.referrer),n?.referrerPolicy!==void 0&&(g.referrerPolicy=n.referrerPolicy),n?.integrity!==void 0&&(g.integrity=n.integrity),n?.keepalive!==void 0&&(g.keepalive=n.keepalive),this.transport.getProof){let w=await this.transport.getProof({method:g.method??"GET",path:Ys(s),body:g.body});w&&(d["X-Calimero-Proof"]=w)}try{let w=await this.transport.fetch(s,g);if(!w.ok){let v=await this.getBodyText(w),I=new T(w.status,w.statusText,s,w.headers,v),P=w.headers.get("x-auth-error");if((w.status===401||w.status===403)&&P&&zs.has(P)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new ne(P,w.status,w.statusText,s,w.headers,v)}let B=n?.signal?.aborted===!0;if(w.status===401&&this.transport.refreshToken&&P==="token_expired"&&r<1&&!A&&!B)try{let M=this.refreshTokenPromise;M||(M=this.transport.refreshToken(),this.refreshTokenPromise=M);let h=await M;if(!h||h.trim()==="")throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("Refresh token returned empty token");if(!this.transport.onTokenRefresh)throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,new Error("onTokenRefresh callback is required when refreshToken is provided. The callback must update the token storage so getAuthToken() returns the new token.");let y=this.onTokenRefreshPromise;y||(y=this.transport.onTokenRefresh(h),this.onTokenRefreshPromise=y),await y,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let S=n?.timeoutMs||this.transport.timeoutMs;if(S&&o!==void 0){let O=Date.now()-a;if(S-O<=0)throw I}return this.makeRequest(e,n,r+1,a)}catch(M){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,M instanceof Error&&M.message.includes("onTokenRefresh")?M:I}throw I}return this.parseResponse(w,n?.parse)}catch(w){throw w instanceof T||w instanceof Error&&w.message.includes("onTokenRefresh")?w:new T(0,"Network Error",s,new Headers,w instanceof Error?w.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let n=this.transport.baseUrl;return e.startsWith("/")?`${n.endsWith("/")?n.slice(0,-1):n}${e}`:`${n.endsWith("/")?n:`${n}/`}${e}`}createAbortSignal(e){let n=[];this.transport.defaultAbortSignal&&n.push(this.transport.defaultAbortSignal),e?.signal&&n.push(e.signal);let r=e?.timeoutMs||this.transport.timeoutMs;return r&&n.push(Hn(r)),n.length>0?Ln(n):void 0}async buildHeaders(e){let n={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let r=await this.transport.getAuthToken();r&&r.trim()!==""&&(n.Authorization=`Bearer ${r}`)}catch{}return e&&(e instanceof Headers?e.forEach((r,o)=>{n[o]=r}):Array.isArray(e)?e.forEach(([r,o])=>{n[r]=o}):Object.assign(n,e)),n}async parseResponse(e,n){switch(n){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let r=await e.text();if(!r)return null;try{return JSON.parse(r)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${r.slice(0,200)}`)}}}}async getBodyText(e){try{let n=await e.text();return n.length>65536?n.slice(0,65536)+"...":n}catch{return""}}};function ze(t){return new Je(t)}function Re(t){let e={fetch:(n,r)=>t.fetch?t.fetch(n,r):globalThis.fetch(n,r),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return ze(e)}function xt(t){let e=t.fetch??globalThis.fetch;if(!e)throw new Error("No fetch implementation available. Please provide a fetch implementation (e.g., undici.fetch) or use Node.js 18+ which has native fetch support.");let r={fetch:e===globalThis.fetch?(o,i)=>globalThis.fetch(o,i):(o,i)=>e(o,i),baseUrl:t.baseUrl,getAuthToken:t.getAuthToken,getProof:t.getProof,onTokenRefresh:t.onTokenRefresh,refreshToken:t.refreshToken,onAuthRevoked:t.onAuthRevoked,defaultHeaders:t.defaultHeaders,timeoutMs:t.timeoutMs,credentials:t.credentials,defaultAbortSignal:t.defaultAbortSignal};return ze(r)}function qn(t){return typeof window<"u"?Re(t):xt(t)}function Xs(t,e){if(e<=0)return!1;let r=t?.name;if(r==="TimeoutError")return!0;if(r==="AbortError")return!1;let o=t;if("status"in o&&typeof o.status=="number"){let i=o.status;return i>=500||i===429}return r==="TypeError"}function Zs(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function Rt(t,e={}){let{attempts:n=3}=e,r;for(let o=1;o<=n;o++)try{return await t(o)}catch(i){if(r=i,!Xs(r,n-o))throw r;let s=Zs(o),u=r.headers?.get?.("Retry-After");if(u){let d=parseInt(u,10);if(!isNaN(d))s=Math.max(s,d*1e3);else{let l=new Date(u);if(!isNaN(l.getTime())){let g=Math.max(0,l.getTime()-Date.now());s=Math.max(s,Math.min(g,6e4))}}}await new Promise(d=>setTimeout(d,s))}throw r||new Error("Retry failed without error")}function ea(t,e={}){return async(...n)=>Rt(()=>t(...n),e)}var le=class{constructor(e){this.httpClient=e}async getHealth(){let e=await this.httpClient.get("/auth/health");if(!e.data)throw new Error("Health response data is null");return e.data}async getIdentity(){let e=await this.httpClient.get("/admin/identity");if(!e.data)throw new Error("Identity response data is null");return e.data}async getProviders(){let e=await this.httpClient.get("/auth/providers");if(!e.data)throw new Error("Providers response data is null");return e.data}async getLoginPage(){return this.httpClient.get("/auth/login",{parse:"text"})}async generateTokens(e){return this.httpClient.post("/auth/token",e)}async refreshToken(e){return this.httpClient.post("/auth/refresh",e)}async generateMockTokens(e){return this.httpClient.post("/auth/mock-token",e)}async validateToken(e){try{let n=await this.validateTokenGet(e);return{valid:n.status===200,headers:n.headers,status:n.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let n=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:n.status,headers:n.headers}}async revokeTokens(e){let n=await this.httpClient.post("/admin/revoke",e);if(!n.data)throw new Error("Revoke tokens response data is null");return n.data}async listRootKeys(){let e=await this.httpClient.get("/admin/keys");if(!e.data)throw new Error("Root keys response data is null");return e.data}async createRootKey(e){let n=await this.httpClient.post("/admin/keys",e);if(!n.data)throw new Error("Create root key response data is null");return n.data}async deleteRootKey(e){return this.httpClient.delete(`/admin/keys/${e}`)}async listClientKeys(){let e=await this.httpClient.get("/admin/keys/clients");if(!e.data)throw new Error("Client keys response data is null");return e.data}async generateClientKey(e){return this.httpClient.post("/admin/client-key",e)}async deleteClientKey(e,n){return this.httpClient.delete(`/admin/keys/${e}/clients/${n}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${e}/permissions`)}async updateKeyPermissions(e,n){return this.httpClient.put(`/admin/keys/${e}/permissions`,{add:n.add,remove:n.remove})}};var Qe=class{async get(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async post(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async put(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async delete(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async patch(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async head(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}async request(){throw new Error("HTTP client not implemented - use createAuthApiClientFromHttpClient with a real HTTP client")}};function _u(t){let e=new Qe;return new le(e)}function Gu(t){let e=new Qe;return new le(e)}function $u(t){let e=new Qe;return new le(e)}function lo(t,e){return new le(t)}var U={CAN_CREATE_CONTEXT:1,CAN_INVITE_MEMBERS:2,CAN_JOIN_OPEN_SUBGROUPS:4,MANAGE_MEMBERS:8,MANAGE_APPLICATION:16,CAN_CREATE_SUBGROUP:32,CAN_DELETE_SUBGROUP:64,CAN_MANAGE_VISIBILITY:128,CAN_MANAGE_METADATA:256,CAN_AUTHOR_ON_BEHALF:512},Lu={NONE:0,JOIN_ONLY:U.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:U.CAN_CREATE_CONTEXT|U.CAN_INVITE_MEMBERS|U.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:U.CAN_CREATE_CONTEXT|U.CAN_INVITE_MEMBERS|U.CAN_JOIN_OPEN_SUBGROUPS|U.CAN_CREATE_SUBGROUP|U.CAN_DELETE_SUBGROUP|U.CAN_MANAGE_VISIBILITY};function Hu(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(U,n))e|=U[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function qu(t){return Object.keys(U).filter(e=>ue(t,U[e]))}function ue(t,e){let n=e>>>0;return(t&n)>>>0===n}function Bn(t,e){return(t|e)>>>0}function Bu(t,e){return(t&~e)>>>0}var ta={invalid:!1,unauthorized:!0,forbidden:!1,"not-found":!0,conflict:!1,gone:!1,"too-large":!1,"rate-limited":!0,unavailable:!0,server:!0,unreachable:!0,unknown:!0};function na(t){switch(t){case 0:return"unreachable";case 400:return"invalid";case 401:return"unauthorized";case 403:return"forbidden";case 404:return"not-found";case 409:return"conflict";case 410:return"gone";case 413:return"too-large";case 429:return"rate-limited";case 503:case 504:return"unavailable"}return t>=500&&t<600?"server":t>=400&&t<500?"invalid":"unknown"}function ra(t){if(!t||typeof t!="object")return;let e=t;for(let n of[e.status,e.response?.status,e.statusCode])if(typeof n=="number"&&Number.isFinite(n))return n}function jn(t,e="Request failed"){if(typeof t=="string")return t.trim()||e;if(!t||typeof t!="object")return e;let n=t;for(let r of[n.explanation,n.response?.data?.error,n.response?.data?.message,n.data?.message,n.error,n.message])if(typeof r=="string"&&r.trim())return r;return e}function Fn(t){let e=ra(t),n;return e!==void 0?n=na(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:ta[n],message:jn(t)}}function oa(t){return t.status!=="failed"||!t.retryable}function Wu(t){return!oa(t)}function ia(t){let e=t.toLowerCase();return e.includes("invitation has expired")||e.includes("invitation expired")||/\binvitation for group .+? expired at \d+/.test(e)?"expired":e.includes("malformed")||e.includes("does not match namespace_id")||e.includes("invalid invitation")||/\binvitation for group .+? is invalid:/.test(e)?"invalid":null}function sa(t,e){let{kind:n,status:r}=Fn(t),o=ia(e);return r===401?{reason:"signed-out",retryable:!0}:r===400?{reason:o??"invalid",retryable:!1}:r===410?{reason:"expired",retryable:!1}:r===403?{reason:"refused",retryable:!1}:r===409?{reason:o??"refused",retryable:!1}:n==="unavailable"?{reason:"no-one-online",retryable:!0}:n==="unreachable"?{reason:"node-unreachable",retryable:!0}:o?{reason:o,retryable:!1}:{reason:"unknown",retryable:!0}}async function uo(t,e){let{namespaceId:n,invitation:r,teamName:o}=t,i=null;try{await e.join(n,r)}catch(d){i=d}let s=null;try{s=(await e.memberships()).includes(n)}catch{s=null}if(i===null)return{status:"joined",namespaceId:n,teamName:o};if(s===!0)return{status:"already-member",namespaceId:n,teamName:o};let a=jn(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=sa(i,a);return{status:"failed",namespaceId:n,message:a,reason:c,retryable:u}}var vt=class extends Error{constructor(n,r){super(`this node does not serve warrant-nonce discovery (404 on ${n}); it predates the route, so a client must fall back to its own nonce counter`);this.path=n;this.cause=r;this.name="WarrantNonceRouteUnavailableError"}};function Vn(t,e,n){let r=e[n];if(r==null)return;let o=new RegExp(`"${n}"\\s*:\\s*(\\d+)`).exec(t);if(o)return BigInt(o[1]);if(typeof r=="string"&&/^\d+$/.test(r))return BigInt(r);throw new Error(`warrant-nonce response field \`${n}\` is not a u64: ${JSON.stringify(r)}`)}function po(t){let n=JSON.parse(t)?.data;if(!n||typeof n!="object")throw new Error(`warrant-nonce response had no \`data\`: ${t.slice(0,200)}`);let r={contextId:String(n.contextId??""),authorDeviceKey:String(n.authorDeviceKey??""),seen:n.seen===!0,highWaterNonce:Vn(t,n,"highWaterNonce"),windowWidth:Vn(t,n,"windowWidth")??0n},o=Vn(t,n,"nextNonce");return o===void 0?{...r,kind:"exhausted",seen:!0,highWaterNonce:r.highWaterNonce??0xffffffffffffffffn}:{...r,kind:"open",nextNonce:o}}function b(t){return t?.data}function aa(t,e){let[n,r]=go(t),[o,i]=go(e),s=n.split("."),a=o.split("."),c=Math.max(s.length,a.length);for(let g=0;g<c;g++){let A=mo(s[g]??"0",a[g]??"0");if(A!==0)return A}if(r===void 0&&i===void 0)return 0;if(r===void 0)return 1;if(i===void 0)return-1;let u=r.split("."),d=i.split("."),l=Math.max(u.length,d.length);for(let g=0;g<l;g++){if(g>=u.length)return-1;if(g>=d.length)return 1;let A=mo(u[g],d[g]);if(A!==0)return A}return 0}function go(t){let e=t.split("+",1)[0],n=e.indexOf("-");return n===-1?[e,void 0]:[e.slice(0,n),e.slice(n+1)]}function mo(t,e){let n=/^\d+$/.test(t),r=/^\d+$/.test(e);if(n&&r){let o=Number(t)-Number(e);return o<0?-1:o>0?1:0}return n?-1:r?1:t<e?-1:t>e?1:0}async function ca(t,e,n){return Rt(async()=>{let r=await fetch(t,{signal:AbortSignal.timeout(1e4)});if(!r.ok){let o=new Error(`registry ${e} fetch failed (${r.status}) for ${n}`);throw o.status=r.status,o}return r},{attempts:3})}var de=class{constructor(e){this.httpClient=e}async healthCheck(){return b(await this.httpClient.get("/admin-api/health"))}async readinessCheck(){return b(await this.httpClient.get("/admin-api/ready"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return b(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,n){let r=new URL("/api/v2/bundles",new URL(e).origin);r.searchParams.set("package",n);let i=await(await ca(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(s=>s.appVersion).filter(s=>typeof s=="string").sort((s,a)=>aa(a,s))}async installDevApplication(e){return b(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return b(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return b(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return b(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return b(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,n){let r=n?`?service_name=${encodeURIComponent(n)}`:"";return b(await this.httpClient.get(`/admin-api/applications/${e}/abi${r}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let n=await this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/versions`);return n?.data??n}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/latest`)}async createContext(e){let n={...e,initializationParams:e.initializationParams??[]};return b(await this.httpClient.post("/admin-api/contexts",n))}async deleteContext(e){return b(await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return b(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return b(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return b(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return b(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){let n=e?`/admin-api/contexts/sync/${e}`:"/admin-api/contexts/sync";await this.httpClient.post(n,{})}async resyncContext(e,n={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,n)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return b(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,n){await this.httpClient.post(`/admin-api/contexts/${e}/application`,n)}async getContextsWithExecutorsForApplication(e){let n=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${e}`);return Array.isArray(n)?n:n?.contexts??n?.data??[]}async uploadBlob(e){let n=new URLSearchParams;e.hash&&n.set("hash",e.hash),e.contextId&&n.set("context_id",e.contextId);let r=n.toString(),o=r?`/admin-api/blobs?${r}`:"/admin-api/blobs",i=b(await this.httpClient.request(o,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let n=await this.httpClient.delete(`/admin-api/blobs/${e}`);return{blobId:n.blob_id,deleted:n.deleted}}async listBlobs(){return{blobs:b(await this.httpClient.get("/admin-api/blobs")).blobs.map(n=>({blobId:n.blob_id,size:n.size}))}}blobPath(e,n){if(!n?.contextId)return`/admin-api/blobs/${e}`;let r=new URLSearchParams({context_id:n.contextId});return`/admin-api/blobs/${e}?${r.toString()}`}async getBlob(e,n){return this.httpClient.get(this.blobPath(e,n),{parse:"arrayBuffer"})}async getBlobInfo(e,n){let{headers:r}=await this.httpClient.head(this.blobPath(e,n)),o=Number(r["content-length"]);return{blobId:r["x-blob-id"]??e,size:Number.isFinite(o)?o:0,hash:r["x-blob-hash"],mimeType:r["x-blob-mime-type"],source:r["x-blob-source"]}}async createContextAlias(e){return b(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return b(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return b(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return b(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return b(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return b(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return b(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return b(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return b(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return b(await this.httpClient.post(`/admin-api/alias/lookup/device/${encodeURIComponent(e)}`,{}))}async deleteDeviceAlias(e){return b(await this.httpClient.post(`/admin-api/alias/delete/device/${encodeURIComponent(e)}`,{}))}async listDeviceAliases(){return b(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return b(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return b(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return b(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let n=await this.getNodeIdentity();return{namespaceId:e,publicKey:n.publicKey,account:n.accountId}}async performIntent(e,n){return b(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,n))}async queryContext(e,n){return b(await this.httpClient.post(`/admin-api/contexts/${e}/query`,n))}async getIntentRelay(e){return b(await this.httpClient.get(`/admin-api/contexts/${e}/intents`))}async listNamespacesForApplication(e){return b(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return b(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return b(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,n??{}))}async admitJoin(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/admit`,n,{timeoutMs:65e3}))}async joinNamespace(e,n){let r=b(await this.httpClient.post(`/admin-api/namespaces/${e}/join`,n,{timeoutMs:65e3}));return r&&r.namespaceId===void 0&&r.groupId!==void 0?{...r,namespaceId:r.groupId}:r}async redeemInvitation(e,n,r={}){let{groupName:o,teamName:i}=r;return uo({namespaceId:e,invitation:n,teamName:i},{join:async()=>{await this.joinNamespace(e,o===void 0?{invitation:n}:{invitation:n,groupName:o})},memberships:async()=>(await this.listNamespaces()??[]).map(s=>s.namespaceId)})}async createGroupInNamespace(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,n??{}))}async listNamespaceGroups(e){return b(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async initAccountPairing(e){return b(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return b(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,n){return b(await this.httpClient.post(`/admin-api/account/devices/${e}/relink`,n??{}))}async rescopeAccountDevice(e,n){return b(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/scope`,n))}async signWithAccountRoot(e){return b(await this.httpClient.post("/admin-api/account/sign-with-root",e))}async labelAccountDevice(e,n){return b(await this.httpClient.put(`/admin-api/account/devices/${encodeURIComponent(e)}/label`,n))}async listAccountDevices(){return(await this.httpClient.get("/admin-api/account/devices")).devices}async listAccountApplications(){return(await this.httpClient.get("/admin-api/account/applications")).applications}async revokeAccountDevice(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/account/revoke`,n))}async linkAccountDevice(e,n){return b(await this.httpClient.post(`/admin-api/namespaces/${e}/account/link-device`,n))}async getGroupInfo(e){return b(await this.httpClient.get(`/admin-api/groups/${e}`))}async getDefaultCapabilities(e){return(await this.getGroupInfo(e)).defaultCapabilities}async getSubgroupVisibility(e){return(await this.getGroupInfo(e)).subgroupVisibility}async deleteGroup(e){return b(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let n=await this.httpClient.get(`/admin-api/groups/${e}/members`);if(!Array.isArray(n?.members)){let r=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${r}: missing or non-array \`members\` field`)}return n}async listGroupMemberDevices(e,n){let r=new URLSearchParams;n?.offset!==void 0&&r.set("offset",String(n.offset)),n?.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${encodeURIComponent(e)}/member-devices`;return(await this.httpClient.get(o?`${i}?${o}`:i)).members}async getWarrantNonce(e,n){let r=`/admin-api/contexts/${encodeURIComponent(e)}/warrant-nonce/${encodeURIComponent(n)}`,o;try{o=await this.httpClient.get(r,{parse:"text"})}catch(i){throw i instanceof T&&i.status===404?new vt(r,i):i}return po(o)}async getWarrantNonceAsAuthor(e,n){let r=`/admin-api/contexts/${encodeURIComponent(e)}/warrant-nonce`,o;try{o=await this.httpClient.post(r,{authorProof:n},{parse:"text"})}catch(i){throw i instanceof T&&i.status===404?new vt(r,i):i}return po(o)}async listMemberDevices(e,n={}){let r=new URLSearchParams;n.offset!==void 0&&r.set("offset",String(n.offset)),n.limit!==void 0&&r.set("limit",String(n.limit));let o=r.toString(),i=`/admin-api/groups/${e}/member-devices${o?`?${o}`:""}`;return this.httpClient.get(i)}async sealToAccount(e,n,r){return b(await this.httpClient.post(`/admin-api/groups/${e}/accounts/${n}/seal`,r))}async listGroupContexts(e){return b(await this.httpClient.get(`/admin-api/groups/${e}/contexts`))}async addGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${e}/members`,n)}async removeGroupMembers(e,n){await this.httpClient.post(`/admin-api/groups/${e}/members/remove`,n)}async updateMemberRole(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/role`,r)}async getMemberCapabilities(e,n){return b(await this.httpClient.get(`/admin-api/groups/${e}/members/${n}/capabilities`))}async setMemberCapabilities(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/capabilities`,r)}async setDefaultCapabilities(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/default-capabilities`,n)}async openToDelegatedExecution(e){let n=await this.getDefaultCapabilities(e);if(ue(n,U.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=Bn(n,U.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:r}),{changed:!0,defaultCapabilities:r}}async grantAuthorship(e,n){let{capabilities:r}=await this.getMemberCapabilities(e,n);if(ue(r,U.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=Bn(r,U.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,n,{capabilities:o}),{changed:!0,capabilities:o}}async setSubgroupVisibility(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/subgroup-visibility`,n)}async setTeeAdmissionPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-admission-policy`,n)}async getTeeAdmissionPolicy(e){let n=await this.httpClient.get(`/admin-api/groups/${e}/settings/tee-admission-policy`);return n.data??n}async setTeeAuthoringPolicy(e,n){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-authoring-policy`,n)}async disableTeeAuthoringPolicy(e,n={}){let r=`/admin-api/groups/${e}/settings/tee-authoring-policy`;if(n.rootProof===void 0){await this.httpClient.delete(r);return}await this.httpClient.request(r,{method:"DELETE",body:JSON.stringify({rootProof:n.rootProof}),headers:{"Content-Type":"application/json"}})}async transferOwnership(e,n){await this.httpClient.post(`/admin-api/groups/${e}/transfer-ownership`,n)}async changeNamespaceAdmin(e,n){await this.httpClient.post(`/admin-api/namespaces/${e}/admin`,n)}async ownerDeleteGroup(e,n={}){await this.httpClient.post(`/admin-api/groups/${e}/owner-delete`,n)}async setGroupMetadata(e,n){await this.httpClient.put(`/admin-api/groups/${e}/metadata`,n)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${e}/metadata`))?.data??null}async setMemberMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/metadata`,r)}async getMemberMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${e}/members/${n}/metadata`))?.data??null}async setContextMetadata(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/contexts/${n}/metadata`,r)}async getContextMetadata(e,n){return(await this.httpClient.get(`/admin-api/groups/${e}/contexts/${n}/metadata`))?.data??null}async syncGroup(e){return b(await this.httpClient.post(`/admin-api/groups/${e}/sync`,{}))}async upgradeGroup(e,n){return b(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,n))}async getGroupUpgradeStatus(e){return b(await this.httpClient.get(`/admin-api/groups/${e}/upgrade/status`))}async getMigrationStatus(e){let n=encodeURIComponent(e);return this.httpClient.get(`/admin-api/groups/${n}/migration-status`)}async getCascadeStatus(e){let n=encodeURIComponent(e);return b(await this.httpClient.get(`/admin-api/groups/${n}/cascade-status`))}async retryGroupUpgrade(e){return b(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,{}))}async reparentGroup(e,n){let r=await this.httpClient.post(`/admin-api/groups/${e}/reparent`,n);return r?.data??r}async listSubgroups(e){let n=await this.httpClient.get(`/admin-api/groups/${e}/subgroups`);return n.subgroups??n.data??[]}async detachContextFromGroup(e,n){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${n}/remove`,{})}async createGroupInvitation(e,n){return b(await this.httpClient.post(`/admin-api/groups/${e}/invite`,n??{}))}async joinGroup(e){return b(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return b(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return b(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return b(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return b(await this.httpClient.post("/admin-api/tee/verify-quote",e))}async getPeersCount(){return this.httpClient.get("/admin-api/peers")}async getNetworkStatus(){return this.httpClient.get("/admin-api/network/status")}async getUsage(){return this.httpClient.get("/admin-api/usage")}async createGroup(e){return b(await this.httpClient.post("/admin-api/groups",e))}async leaveGroup(e){await this.httpClient.post(`/admin-api/groups/${e}/leave`,{})}async leaveContext(e){await this.httpClient.post(`/admin-api/contexts/${e}/leave`,{})}async leaveNamespace(e){await this.httpClient.post(`/admin-api/namespaces/${e}/leave`,{})}async issueOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${e}/issue-ownership-proof`,n)}async issueNamespaceOwnershipProof(e,n){return this.httpClient.post(`/admin-api/groups/${e}/issue-namespace-ownership-proof`,n)}async setMemberAutoFollow(e,n,r){await this.httpClient.put(`/admin-api/groups/${e}/members/${n}/auto-follow`,r)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,{})}};function ed(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function id(t){return new de(Re(t))}function sd(t){return new de(xt(t))}function ho(t){return new de(qn(t))}function Ct(t,e){return new de(t)}function Wn(t){try{let e=t.indexOf("#");if(e===-1)return null;let n=t.substring(e+1),r=new URLSearchParams(n),o=r.get("access_token");return o?{accessToken:o,refreshToken:r.get("refresh_token")??"",applicationId:r.get("application_id")??"",contextId:r.get("context_id")??"",contextIdentity:r.get("context_identity")??"",nodeUrl:r.get("node_url")??""}:null}catch{return null}}function Jn(t,e){let n=new URLSearchParams;return n.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&n.set("permissions",e.permissions.join(",")),n.set("mode",e.mode),e.packageName&&(n.set("package-name",e.packageName),e.packageVersion&&n.set("package-version",e.packageVersion),e.registryUrl&&n.set("registry-url",e.registryUrl)),`${t.replace(/\/+$/,"")}/auth/login?${n.toString()}`}var fo=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function R(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),e}function f(t){return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function p(t,e,n){let r=t.trim();if(!/^[0-9a-fA-F]*$/.test(r)||r.length!==n*2)throw new Error(`${e} must be ${n*2} hex characters, got ${r.length}`);let o=new Uint8Array(n);for(let i=0;i<n;i+=1)o[i]=Number.parseInt(r.slice(i*2,i*2+2),16);return o}function j(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} must be an even number of hex characters`);let r=new Uint8Array(n.length/2);for(let o=0;o<r.length;o+=1)r[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return r}function C(t){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(t),!0),e}function m(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}async function k(t,e){let n=[C(t.length),t];for(let r of e)n.push(C(r.length),r);return new Uint8Array(await crypto.subtle.digest("SHA-256",m(...n)))}async function re(t){let e=p(t,"deviceSecret",32),n=m(fo,e);try{return await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!1,["sign"])}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("this runtime has no WebCrypto Ed25519, so a warrant cannot be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; otherwise mint the warrant with `merod account warrant`"+o)}}async function yo(t,e,n){let r=await crypto.subtle.importKey("raw",p(t,"publicKey",32),{name:"Ed25519"},!1,["verify"]);return crypto.subtle.verify({name:"Ed25519"},r,e,n)}async function oe(t){let e=p(t,"deviceSecret",32),n=m(fo,e),r=await crypto.subtle.importKey("pkcs8",n,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",r)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),s=>s.charCodeAt(0))}var la=new TextEncoder().encode("calimero.auth.request.v1"),ua=new TextEncoder().encode("calimero.auth.request.body.v1");function bo(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}async function zn(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return k(ua,[e])}async function St(t){let e=await re(t.signerSecret),n=await zn(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,s=await k(la,[i.encode(t.method),i.encode(t.path),n,r,o]),a=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},e,s));return f(m(bo(t.method),bo(t.path),n,r,o,a))}function kt(t){let e=j(t.credential,"credential"),n=j(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):m(new Uint8Array([1]),j(t.session,"session statement"));return f(m(e,r,n))}function da(t){if(t==null)return new Uint8Array(0);if(typeof t=="string"||t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error(`a request-carried proof cannot commit to a ${t?.constructor?.name??typeof t} body: pass a string or bytes, or use a session for this call`)}function Et(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return kt({credential:t.credential,session:t.session,request:await St({method:r.method,path:r.path,body:da(r.body),issuedAt:o,expiresAt:o+e,signerSecret:t.signerSecret})})}}var It=class extends Error{constructor(e,n,r,o){super(n),this.name="RpcError",this.code=e,this.data=r,this.type=o}};async function Qn(t,e,n){let r=await t.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:n});if(r.error){let o=r.error;throw new It(o.code??-1,o.message??o.type??"RPC error",o.data,o.type)}return r.result}var Ye=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Qn(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return n&&"output"in n?n.output:n}async executeWithMetadata(e){return{returns:await this.execute(e),transport:"node"}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var pa=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function wo(t){return t.type!==void 0&&pa.has(t.type)}var ga=new Set(["token_reuse","token_revoked"]),ma=new Set([401,403]),ha=1e4;function Ao(t){let e=t.headers.get("x-auth-error");return!e||!ma.has(t.status)?null:ga.has(e)?e:null}var H=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.presence=new Map;this.closed=!1;this.listeners={connect:[],event:[],error:[]};if(this.baseUrl=e.baseUrl.replace(/\/+$/,""),e.authorize)this.authorize=e.authorize;else if(e.getAuthToken){let n=e.getAuthToken;this.authorize=async()=>({Authorization:`Bearer ${await n()}`})}else throw new Error("SseClient needs either `getAuthToken` or `authorize`");this.reconnectDelayMs=e.reconnectDelayMs??3e3,this.fetchImpl=(n,r)=>e.fetch?e.fetch(n,r):globalThis.fetch(n,r)}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}onAppVersionChanged(e){let n=r=>{if(r.type!=="AppVersionChanged")return;let o=r.data;e({contextId:r.contextId,fromVersion:o?.fromVersion,toVersion:o?.toVersion})};return this.on("event",n),()=>this.off("event",n)}onMigrationEvent(e){let n=r=>{wo(r)&&e(r)};return this.on("event",n),()=>this.off("event",n)}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=`${this.baseUrl}/sse`,n=await this.fetchImpl(e,{headers:{...await this.authorize({method:"GET",path:new URL(e).pathname}),Accept:"text/event-stream"},signal:this.abortController.signal});if(!n.ok){let r=Ao(n),o=await n.text().catch(()=>{});throw r?new ne(r,n.status,n.statusText,e,n.headers,o):new T(n.status,n.statusText,e,n.headers,o)}if(!n.body)throw new Error("SSE response has no body");this.readStream(n.body).catch(r=>{if(this.closed)return;let o=r instanceof Error?r:new Error(String(r));this.emit("error",o),this.scheduleReconnect()})}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));if(this.emit("error",n),n instanceof ne)return;this.scheduleReconnect()}}}async readStream(e){let n=e.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:i,value:s}=await n.read();if(i)break;o+=r.decode(s,{stream:!0});let a=o.split(`
2
+ `);o=a.pop()??"";for(let c of a)if(c.startsWith("data:")){let u=c.slice(5).trim();u&&this.handleMessage(u)}}if(o+=r.decode(),o.startsWith("data:")){let i=o.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let s=i instanceof Error?i:new Error(String(i));this.emit("error",s)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let n=JSON.parse(e);if(n.type==="connect"&&n.session_id){let o=n.session_id;if(this.sessionId=o,this.presence.clear(),this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0){this.emit("connect",o);return}this.postSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]}).then(i=>{this.closed||this.sessionId!==o||(this.emit("connect",o),i&&this.emit("error",i))});return}if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){n.result.type==="Ephemeral"&&this.notePresence(n.result.contextId,r),this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}async subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.add(i);for(let i of n.groupIds??[])this.subscribedGroupIds.add(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:r,groupIds:o})}isSubscribed(e){return this.subscribedContextIds.has(e)}presenceSeed(e){let n=Date.now();return[...this.presence.get(e)?.values()??[]].map(({data:r,at:o})=>({...r,ageMs:(typeof r.ageMs=="number"?r.ageMs:0)+(n-o)}))}notePresence(e,n){if(!this.subscribedContextIds.has(e))return;let r=n;if(!r||typeof r.author!="string")return;let o=this.presence.get(e);o||this.presence.set(e,o=new Map),r.removed?o.delete(r.author):o.set(r.author,{data:r,at:Date.now()})}async unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e,r=(n.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),o=(n.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of n.contextIds??[])this.subscribedContextIds.delete(i),this.presence.delete(i);for(let i of n.groupIds??[])this.subscribedGroupIds.delete(i);(r.length>0||o.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:r,groupIds:o})}async sendSubscription(e,n){let r=await this.postSubscription(e,n);r&&this.emit("error",r)}async postSubscription(e,n){let r=new AbortController,o=setTimeout(()=>r.abort(new DOMException(`SSE ${e} timed out`,"TimeoutError")),ha);try{let i={};n.contextIds&&n.contextIds.length>0&&(i.contextIds=n.contextIds),n.groupIds&&n.groupIds.length>0&&(i.groupIds=n.groupIds);let s=`${this.baseUrl}/sse/subscription`,a=JSON.stringify({id:this.sessionId,method:e,params:i}),c=await this.fetchImpl(s,{method:"POST",headers:{...await this.authorize({method:"POST",path:new URL(s).pathname,body:a}),"Content-Type":"application/json"},body:a,signal:r.signal});if(!c.ok){let u=Ao(c),d=await c.text().catch(()=>{});return u?new ne(u,c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d):new T(c.status,c.statusText,`${this.baseUrl}/sse/subscription`,c.headers,d)}return null}catch(i){return i instanceof Error?i:new Error(`SSE ${e} failed`)}finally{clearTimeout(o)}}forceReconnect(){this.abortController&&(this.abortController.abort(),this.abortController=null),this.sessionId=null,this.connect()}scheduleReconnect(){this.closed||(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.forceReconnect()},this.reconnectDelayMs))}close(){this.closed=!0,this.abortController&&(this.abortController.abort(),this.abortController=null),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.sessionId=null,this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};var Pt=class Pt{constructor(e){this.ws=null;this.closed=!1;this.reconnectAttempt=0;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken}on(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r];o.includes(n)||o.push(n)}}off(e,n){let r=e;if(r in this.listeners){let o=this.listeners[r],i=o.indexOf(n);i!==-1&&o.splice(i,1)}}emit(e,n){let r=e;if(r in this.listeners)for(let o of this.listeners[r])try{o(n)}catch{}}async connect(){if(!(this.ws&&(this.ws.readyState===0||this.ws.readyState===1))){this.closed=!1;try{let e=await this.getAuthToken();if(!e)throw new Error("No authentication token available for WebSocket connection");let n=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${n}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=r=>{this.handleMessage(r.data)},this.ws.onerror=()=>{this.emit("error",new Error("WebSocket error"))},this.ws.onclose=()=>{this.closed||this.scheduleReconnect()}}catch(e){if(this.closed)return;let n=e instanceof Error?e:new Error(String(e));this.emit("error",n),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let n=JSON.parse(e);if(!n.result)return;let r=n.result.data;if(Array.isArray(r))try{let o=new Uint8Array(r),i=new TextDecoder().decode(o);r=JSON.parse(i)}catch{}if(n.result.contextId){this.emit("event",{contextId:n.result.contextId,type:n.result.type,data:r});return}n.result.groupId&&this.emit("event",{groupId:n.result.groupId,type:n.result.type,data:r})}catch{}}subscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.add(r);for(let r of n.groupIds??[])this.subscribedGroupIds.add(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}unsubscribe(e){let n=Array.isArray(e)?{contextIds:e}:e;for(let r of n.contextIds??[])this.subscribedContextIds.delete(r);for(let r of n.groupIds??[])this.subscribedGroupIds.delete(r);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(n.contextIds??[],n.groupIds??[])})}resubscribeAfterReconnect(){this.subscribedContextIds.size===0&&this.subscribedGroupIds.size===0||this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams([...this.subscribedContextIds],[...this.subscribedGroupIds])})}buildSubscriptionParams(e,n){let r={};return e.length>0&&(r.contextIds=e),n.length>0&&(r.groupIds=n),r}sendMessage(e){this.ws&&this.ws.readyState===1&&this.ws.send(JSON.stringify(e))}scheduleReconnect(){if(this.closed)return;this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=Math.min(1e3*Math.pow(2,this.reconnectAttempt),Pt.MAX_BACKOFF_MS);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},e)}close(){this.closed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscribedContextIds.clear(),this.subscribedGroupIds.clear()}};Pt.MAX_BACKOFF_MS=3e4;var ie=Pt;function se(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var Xe=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=se()){await Qn(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=se()){return Tt(this.sse,e,n,r)}};function Tt(t,e,n,r=se()){let o=i=>{let s=i;if(s.type!=="Ephemeral"||s.contextId!==e)return;let a=s.data;if(!a?.author)return;let c=!!a.removed,u={author:a.author,state:c||a.state===void 0?void 0:r.decode(a.state),removed:c};a.ageMs!==void 0&&(u.ageMs=a.ageMs),a.account!==void 0&&(u.account=a.account),n(u)};if(t.on("event",o),t.isSubscribed?.(e))for(let i of t.presenceSeed?.(e)??[])o({contextId:e,type:"Ephemeral",data:i});return t.connect().catch(()=>{}),t.subscribe([e]).catch(()=>{}),()=>{t.off("event",o)}}var fa=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function xo(t){let e=t instanceof Error?`: ${t.message}`:"";return new Error("this runtime has no WebCrypto Ed25519, so nothing can be signed here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it"+e)}async function ve(t,e="secret"){let n=p(t,e,32),r=m(fa,n),o,i;try{let s=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!0,["sign"]),a=await crypto.subtle.exportKey("jwk",s);i=f(Uint8Array.from(atob(a.x.replace(/-/g,"+").replace(/_/g,"/")),c=>c.charCodeAt(0))),o=await crypto.subtle.importKey("pkcs8",r,{name:"Ed25519"},!1,["sign"])}catch(s){throw xo(s)}return vo(o,i)}async function Ro(t,e){if(t.type!=="private")throw new Error(`signerFromCryptoKey needs the private half of the pair, got a ${t.type} key`);if(!t.usages.includes("sign"))throw new Error("this CryptoKey cannot sign: generate it with usages ['sign', 'verify']");let n;if(typeof e=="string")p(e,"publicKey",32),n=e.trim().toLowerCase();else try{n=f(new Uint8Array(await crypto.subtle.exportKey("raw",e)))}catch(r){let o=r instanceof Error?`: ${r.message}`:"";throw new Error("could not read the public half of this key pair; pass the public key as 64 hex instead"+o)}return vo(t,n)}function vo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw xo(r)}}}}async function E(t,e,n){if(e&&t!==void 0)throw new Error(`pass either ${n} or signer, not both \u2014 they may name different keys`);if(e)return e;if(t!==void 0)return ve(t,n);throw new Error(`${n} or signer is required`)}var ya=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),ba=6e4,Co=5*6e4,So=1024,Eo="mdma:enable-ha-namespace",Io="mdma:enable-ha-namespace-as-account";function ko(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Yn=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function Po(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=So))throw new Error(`relayUrl must be a non-empty string of at most ${So} characters`);let o=t.ttlMs??ba;if(!(o>0&&o<=Co))throw new Error(`ttlMs must be in (0, ${Co}]`);let i=Yn(t.namespaceId,"namespaceId"),s=Yn(t.accountId,"accountId"),a=Yn(t.salt,"salt"),c=await E(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),A=>A.toString(16).padStart(2,"0")).join(""),l=new TextEncoder().encode(JSON.stringify({v:1,audience:e,group_id:i,account_id:s,salt:a,...n===void 0?{}:{subject:n},nonce:d,issued_at_ms:u,expires_at_ms:u+o,...r===void 0?{}:{relay_url:r}})),g=await c.sign(m(ya,l));return{kind:"account",credential:t.credential,signed_payload:ko(l),signature:ko(g)}}async function wa(t){if(!t.subject)throw new Error("subject must be the cloud login email");return Po(t,Eo,t.subject)}async function Xn(t){return Po(t,Io,void 0,t.relayUrl)}var Aa=new TextEncoder().encode("calimero.device.cert.v1"),xa=new TextEncoder().encode("calimero.account.genesis.v1"),Ra=new TextEncoder().encode("calimero.device.id.v1"),Ce=2,va=237;async function Zn(t,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let n=p(t,"account",32),r=await k(Ra,[n,e]);return f(m(e,r.subarray(0,16)))}async function Dt(t){return k(Aa,[p(t.account,"account",32),p(t.device,"device",32),p(t.signPublicKey,"signPublicKey",32),p(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch)])}function To(t){return m(new Uint8Array([Ce]),t.rootPublicKey,R(0),p(t.account,"account",32),p(t.device,"device",32),p(t.signPublicKey,"signPublicKey",32),p(t.kemPublicKey,"kemPublicKey",32),R(t.keyEpoch),R(t.deviceEpoch),t.signature)}async function Do(t){let e=await E(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await F(e.publicKey),o=0,i=await Dt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),s=await e.sign(i),a=To({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:s});return f(a)}function er(t){let e=p(t,"credential",va);if(e[0]!==Ce)throw new Error(`this credential has account genesis version ${e[0]}, not ${Ce} \u2014 it names a different account than its root key derives here, and core would refuse it`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint32(33,!0);if(r!==0)throw new Error(`this credential carries a ${r}-handoff root chain, which this SDK cannot verify yet \u2014 the signing root is not the genesis root, so checking it means walking the chain`);let o=(i,s)=>f(e.subarray(i,i+s));return{rootPublicKey:o(1,32),account:o(37,32),device:o(69,32),signPublicKey:o(101,32),kemPublicKey:o(133,32),keyEpoch:n.getUint32(165,!0),deviceEpoch:n.getUint32(169,!0),signature:o(173,64)}}async function Nt(t){let e=er(t),n=await F(e.rootPublicKey);if(n!==e.account)throw new Error(`this credential names account ${e.account}, but its root key derives ${n} \u2014 the certificate was re-pointed at another account`);let r=p(e.device,"device",32).subarray(0,16);if(await Zn(e.account,r)!==e.device)throw new Error(`this credential names device ${e.device}, which was not minted for account ${e.account}; core refuses it`);if(!await yo(e.rootPublicKey,p(e.signature,"signature",64),await Dt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Ot(t){return F(f(await oe(t)))}async function F(t){return f(await k(xa,[m(new Uint8Array([Ce]),p(t,"rootPublicKey",32))]))}var Ca=new TextEncoder().encode("calimero.device.scope.v1");async function tr(t){return k(Ca,[p(t.account,"account",32),p(t.device,"device",32),R(t.scopeEpoch),R(t.keyEpoch),...t.applications.map((e,n)=>p(e,`applications[${n}]`,32))])}async function No(t){let e=await E(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await F(f(n)),o=t.applications??[],i=t.scopeEpoch??0;if(!Number.isInteger(i)||i<0||i>4294967295)throw new Error(`scopeEpoch must be a u32, got ${i}`);let s=0,a=await tr({account:r,device:t.device,applications:o,scopeEpoch:i,keyEpoch:s}),c=await e.sign(a);if(c.length!==64)throw new Error(`signer returned ${c.length} bytes, expected a 64-byte Ed25519 signature`);return f(m(new Uint8Array([Ce]),n,R(0),p(r,"account",32),p(t.device,"device",32),R(o.length),...o.map((u,d)=>p(u,`applications[${d}]`,32)),R(i),R(s),c))}var nr=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"];var Sa=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),ka=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Se=256,Oo=Se/32,rr=(Se+Oo)/11;async function Uo(){let t=crypto.getRandomValues(new Uint8Array(Se/8));return Lo(f(t),await qo(t))}async function Mo(t){let e=Ho(t);return Lo(f(await Bo(e)),e.join(" "))}async function or(t){return p(t,"secret",32),{secret:t,publicKey:f(await oe(t)),accountId:await Ot(t)}}async function _o(){let t=crypto.getRandomValues(new Uint8Array(Se/8)),e=await qo(t);return{...await $o(t),phrase:e}}async function Go(t){return $o(await Bo(Ho(t)))}async function $o(t){let e=await ve(f(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await F(e.publicKey),signer:e}}async function z(t){let e=typeof t=="string"?await ve(t,"rootSecret"):t;return Ko(e)}async function Ut(t,e){return Ko(await E(t,e,"rootSecret"))}async function Ko(t){return{signer:t,publicKey:t.publicKey,accountId:await F(t.publicKey)}}async function Ze(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await E(t.rootSecret,t.signer,"rootSecret")).sign(m(Sa,new TextEncoder().encode(t.nonce)));return Vo(n)}async function Mt(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await E(t.rootSecret,t.signer,"rootSecret")).sign(m(ka,new TextEncoder().encode(t.nonce)));return Vo(n)}async function Lo(t,e){return{...await or(t),phrase:e}}function Ho(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==rr)throw new Error(`recovery phrase must be ${rr} words, got ${n}`);return e}async function qo(t){let e=Fo(t)+await jo(t),n=[];for(let r=0;r<rr;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(nr[o])}return n.join(" ")}async function Bo(t){let e="";for(let r of t){let o=nr.indexOf(r);if(o<0)throw new Error(`"${r}" is not a word in the recovery phrase list`);e+=o.toString(2).padStart(11,"0")}let n=new Uint8Array(Se/8);for(let r=0;r<n.length;r+=1)n[r]=Number.parseInt(e.slice(r*8,r*8+8),2);if(e.slice(Se)!==await jo(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function jo(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Fo(e).slice(0,Oo)}function Fo(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Vo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Ea=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),_t=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),Ia=568;function Pa(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.length,0)),n=0;for(let r of t)e.set(r,n),n+=r.length;return e}function ir(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r+=1)n|=t[r]^e[r];return n===0}function Ta(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Da(t,e){if(typeof t!="string"||!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);let n=new Uint8Array(32);for(let r=0;r<32;r+=1)n[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return n}async function Gt(t){let e=await crypto.subtle.digest("SHA-256",Pa(Ea,new Uint8Array(32),t));return new Uint8Array(e)}function sr(t){let e=t.length>=_t.length&&ir(t.subarray(0,_t.length),_t),n=e?_t.length:Ia;if(t.length<n+64)throw new Error(`the quote is too short to carry report data (${t.length} bytes)`);return{reportData:t.slice(n,n+64),mock:e}}async function $t(t){let e=crypto.getRandomValues(new Uint8Array(32)),n=`${t.relayUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r=JSON.stringify({nonce:f(e),bindNodeKey:!0,...t.verify?.includeCollateral?{includeCollateral:!0}:{}}),o={method:"POST",headers:{"Content-Type":"application/json"},body:r},i=t.fetch?await t.fetch(n,o):await globalThis.fetch(n,o);if(!i.ok){let g=await i.text().catch(()=>"");throw new Error(`the relay would not attest (HTTP ${i.status})${g?`: ${g}`:""}`)}let s=await i.json(),a=s.data??s;if(typeof a.quoteB64!="string")throw new Error("the relay returned no quote");let c=Da(a.boundPublicKey,"boundPublicKey"),u=Ta(a.quoteB64),{reportData:d,mock:l}=sr(u);if(l){if(!t.allowMock)throw new Error("the relay answered with a MOCK quote, which proves nothing about the hardware")}else if(t.verify){if(!await t.verify({quoteB64:a.quoteB64,nonce:f(e),reportDataSuffix:f(await Gt(c)),...a.collateral?{collateral:a.collateral}:{}}))throw new Error("the relay's quote did not verify: not a trusted image, or not bound to this request")}else if(t.verifyQuote)await t.verifyQuote(u);else throw new Error("a real TDX quote needs a verify (or verifyQuote) to check its signature and measurements");if(!ir(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!ir(d.subarray(32,64),await Gt(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:f(c),mock:l}}var Na="Noise_NK_25519_AESGCM_SHA256",ar=32,Oa=16,Ua=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),lr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(Na),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await _a(m(this.h,e))}async mixKey(e){let[n,r]=await zo(this.ck,e);this.ck=n,this.k=await crypto.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt","decrypt"]),this.n=0}async encryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Jo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(n),n}async decryptAndHash(e){if(!this.k)throw new Error("Noise: no cipher key yet");let n=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Jo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return zo(this.ck,new Uint8Array)}};async function Qo(t,e,n){let r=await lr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ma(n);return await r.mixHash(o.publicKey),await r.mixKey(await Wo(o.privateKey,t)),{message1:m(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(s){if(s.length<ar+Oa)throw new Error("Noise: message 2 is too short");let a=s.slice(0,ar);return await r.mixHash(a),await r.mixKey(await Wo(o.privateKey,a)),{payload:await r.decryptAndHash(s.slice(ar)),split:await r.split()}}}}async function Ma(t){if(!t){let r;try{r=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"])}catch(i){throw new Error(`Sealed transport needs WebCrypto with X25519, which this runtime lacks (${i?.name??"no crypto.subtle"}). Current browsers and Node have it; in React Native, install react-native-quick-crypto as the global crypto.`)}let o=new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey));return{privateKey:r.privateKey,publicKey:o}}let e=await crypto.subtle.importKey("pkcs8",m(Ua,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ga(n.x)}}async function Wo(t,e){let n=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:n},t,256))}function Jo(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function _a(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function cr(t,e){let n=await crypto.subtle.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await crypto.subtle.sign("HMAC",n,e))}async function zo(t,e){let n=await cr(t,e),r=await cr(n,new Uint8Array([1])),o=await cr(n,m(r,new Uint8Array([2])));return[r,o]}function Ga(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}var ei="/sealed/v2/handshake",ti="/sealed/v2",tt="application/vnd.calimero.sealed",ur=2,$a=new TextEncoder().encode("calimero/sealed-http/v2"),et=16,Ka=1+et+8,La=0,Ha=1,qa=2,Ba=1+64*1024+16,ja=1024,Fa=6e4,Va="calimero.tee-attest.transport-key.v1",Wa=[101,204,205,304],ni=new TextEncoder,nt=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},ke=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function ri(t,e){let n=await crypto.subtle.digest("SHA-256",m(ni.encode(Va),t,e));return new Uint8Array(n)}async function oi(t,e,n={}){if(n.applicationId===void 0!=(n.applicationHash===void 0))throw new Error("applicationId and applicationHash are given together or not at all");let r=f(crypto.getRandomValues(new Uint8Array(32))),o=await t.teeAttest({nonce:r,applicationId:n.applicationId,bindTransportKey:!0,...e.includeCollateral?{includeCollateral:!0}:{}});if(!o.transportPublicKey)throw new Error("The node did not report a transport key; it predates sealed transport");let i=p(o.transportPublicKey,"transportPublicKey",32),s=n.applicationHash?p(n.applicationHash,"applicationHash",32):new Uint8Array(32),a=f(await ri(s,i));if(!await e({quoteB64:o.quoteB64,nonce:r,reportDataSuffix:a,collateral:o.collateral}))throw new Error("The attestation did not verify, so its transport key is not trusted");return i}function pe(t){let e=t.fetch??((o,i)=>fetch(o,i)),n=`${t.baseUrl.replace(/\/+$/,"")}/admin-api/tee/attest`,r={async teeAttest(o){let i=await e(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)});if(!i.ok)throw new Error(`The node refused to attest: HTTP ${i.status}`);let s=await i.json();if(!s.data)throw new Error("The attestation response is malformed");return s.data}};return ii({baseUrl:t.baseUrl,transportPublicKey:()=>oi(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function ii(t){let e=new URL(t.baseUrl),n=e.pathname.replace(/\/+$/,""),r=`${e.origin}${n}`,o=t.fetch??((l,g)=>fetch(l,g)),i=typeof t.transportPublicKey=="function"?t.transportPublicKey:void 0,s=i?Promise.resolve().then(i):Promise.resolve(t.transportPublicKey);s.catch(()=>{});let a,c=async()=>{try{return await Xo(o,r,await Yo(s))}catch(l){if(!(l instanceof nt)||!i)throw l;return s=Promise.resolve().then(i),Xo(o,r,await Yo(s))}},u=async()=>{let l=a??d(void 0),g=await l;if(Date.now()<g.renewAt)return[g,l];let A=d(l);return[await A,A]},d=l=>{if(a===l){let g=c();a=g,g.catch(()=>{a===g&&(a=void 0)})}return a};return async(l,g)=>{let A=new Request(l,g),x=new URL(A.url);if(x.origin!==e.origin||!x.pathname.startsWith(`${n}/`))throw new Error(`Refusing to send ${x.href} outside the sealed node at ${t.baseUrl}`);let w=[];A.headers.forEach((h,y)=>w.push([y,h]));let v={method:A.method,path:x.pathname.slice(n.length)+x.search,headers:w},I=new Uint8Array(await A.arrayBuffer()),P=async h=>{let{requestId:y,header:S,envelope:O}=await za(h,v,I),L=await o(`${r}${ti}`,{method:"POST",headers:{"content-type":tt},body:O,signal:A.signal});if(L.headers.get("content-type")!==tt)throw await ai(L);return Ya(L,h.responseKey,S,y)},[B,M]=await u();try{return await P(B)}catch(h){if(!(h instanceof ke)||h.code!=="unknown_session")throw h;return P(await d(M))}}}async function Yo(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Xo(t,e,n){try{return await Zo(t,e,n)}catch(r){if(!(r instanceof ke)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Zo(t,e,n)}}async function Zo(t,e,n){let r=await Qo(n,$a),o=await t(`${e}${ei}`,{method:"POST",headers:{"content-type":tt},body:m(new Uint8Array([ur]),n,r.message1)});if(o.headers.get("content-type")!==tt)throw await ai(o);let i=await Za(o,ja);return Ja(r,i)}async function Ja(t,e){if(e[0]!==ur)throw new Error("The handshake reply is malformed");let n;try{n=await t.finish(e.slice(1))}catch{throw new Error("The handshake reply did not open: it did not come from the attested node")}let{payload:r,split:o}=n;if(r.length!==et+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,et),s=new DataView(r.buffer,r.byteOffset).getUint32(et,!1),[a,c]=await Promise.all([crypto.subtle.importKey("raw",o[0],"AES-GCM",!1,["encrypt"]),crypto.subtle.importKey("raw",o[1],"AES-GCM",!1,["decrypt"])]);return o[0].fill(0),o[1].fill(0),{requestKey:a,responseKey:c,nextRequestId:1,renewAt:Date.now()+s*1e3-Fa,header(u){let d=new Uint8Array(Ka);return d[0]=ur,d.set(i,1),new DataView(d.buffer).setBigUint64(1+et,BigInt(u),!1),d}}}async function za(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:si(r,0),additionalData:o},t.requestKey,Qa(e,n));return{requestId:r,header:o,envelope:m(o,new Uint8Array(i))}}function si(t,e){let n=new Uint8Array(12),r=new DataView(n.buffer);return r.setBigUint64(0,BigInt(t),!1),r.setUint32(8,e,!1),n}function Qa(t,e){let n=ni.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),m(r,n,e)}async function Ya(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=Xa(t.body.getReader()),i=0,s=async()=>{let d=await o.next();if(!d)return null;let l;try{l=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:si(r,i),additionalData:n},e,d))}catch{throw new Error("A sealed response frame did not open: it was not sealed by the attested node")}return i+=1,{kind:l[0],data:l.slice(1)}},a=await s();if(!a||a.kind!==La)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(a.data));if(Wa.includes(c.status))return await o.cancel(),new Response(null,{status:c.status,headers:c.headers});let u=new ReadableStream({async pull(d){try{let l=await s();l?l.kind===Ha?d.enqueue(l.data):l.kind===qa?(d.close(),await o.cancel()):d.error(new Error("The sealed response is malformed")):d.error(new Error("The sealed response was cut short"))}catch(l){d.error(l)}},cancel(){return o.cancel()}});return new Response(u,{status:c.status,headers:c.headers})}function Xa(t){let e=new Uint8Array,n=async r=>{for(;e.length<r;){let{done:o,value:i}=await t.read();if(o)return!1;e=m(e,i)}return!0};return{async next(){if(!await n(4))return null;let r=new DataView(e.buffer,e.byteOffset).getUint32(0,!1);if(r>Ba)throw await t.cancel(),new Error("The sealed response is malformed: a frame is larger than the node sends");if(!await n(4+r))return null;let o=e.slice(4,4+r);return e=e.slice(4+r),o},cancel:()=>t.cancel()}}async function Za(t,e){if(!t.body)return new Uint8Array;let n=t.body.getReader(),r=new Uint8Array;for(;;){let{done:o,value:i}=await n.read();if(o)return r;if(r=m(r,i),r.length>e)throw await n.cancel(),new Error("The handshake reply is malformed: it is too long")}}async function ai(t){let e,n=`Sealed request refused: HTTP ${t.status}`;try{let i=await t.json();e=i?.error?.code,i?.error?.message&&(n=`Sealed request refused: ${i.error.message}`)}catch{}if(e==="stale_transport_key")return new nt;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new ke(t.status,e,n,o)}var ec=/^[0-9a-f]{96}$/,tc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function pr(t){let e=Ee(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((a,c)=>{let u=`allowedMeasurements[${c}]`;return tc.map(d=>Ee([a?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Ee(t.allowedRtmr0??[],"allowedRtmr0"),Ee(t.allowedRtmr1??[],"allowedRtmr1"),Ee(t.allowedRtmr2??[],"allowedRtmr2"),Ee(t.allowedRtmr3??[],"allowedRtmr3")];if(t.allowedMeasurements!==void 0&&n.length===0)throw new Error("allowedMeasurements is empty, so no quote would ever be accepted");if(n.length===0){if(e.length===0)throw new Error("No image is trusted: give allowedMeasurements, or allowedMrtd with allowedRtmr1-3");if(r.slice(1).some(a=>a.length===0))throw new Error("allowedMrtd alone does not name an image: the MRTD measures the TD firmware, which images share, and the image is in RTMR1-3. Give allowedMeasurements, or allowedRtmr1-3 too")}let o=t.allowedTcbStatuses??["UpToDate"],i=t.now??Date.now;return Object.assign(async({quoteB64:a,nonce:c,reportDataSuffix:u,collateral:d})=>{let l=rc(a),g=d??await t.fetchCollateral?.(l);if(!g)throw new Error("The node sent no collateral for its quote, and no fetchCollateral was given to get it");let A;try{A=t.dcapVerify(l,g,Math.floor(i()/1e3))}catch(I){throw new Error(`The quote did not verify: ${I?.message??String(I)}`)}if(A.status==="Revoked"||!o.includes(A.status))throw new Error(`The platform's TCB status is ${A.status}, which is not accepted`);let x=nc(A.report);if(x.tdAttributes?.length!==8||(x.tdAttributes[0]&1)!==0)throw new Error("The quote is from a debug TD, or its TD attributes cannot be read");let w=[x.mrTd,x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].map(I=>f(I));if(n.length>0&&!n.includes(w.join()))throw new Error(`The measurements (MRTD ${w[0]}, RTMR0-3 ${w.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(w[0]))throw new Error(`MRTD ${w[0]} is not an image this verifier trusts`);if([x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].forEach((I,P)=>{let B=r[P];if(B.length>0&&!B.includes(f(I)))throw new Error(`RTMR${P} ${f(I)} is not one this verifier trusts`)}),f(x.reportData)!==`${c}${u}`.toLowerCase())throw new Error("The quote does not commit to this nonce and binding");return!0},{includeCollateral:!0})}function Ee(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!ec.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function nc(t){let e=t.data;if(t.type==="td10"&&e)return e;if(t.type==="td15"&&e?.base)return e.base;throw new Error(`The quote is a ${t.type} quote, not a TDX one`)}function rc(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}var oc=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"],dr="locked-read-only";function gr(t,{profile:e,allowDebugProfile:n=!1}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let r,o=t.map((i,s)=>{let a=i?.tag??`releases[${s}]`;if(i?.role!==void 0&&i.role!=="node")throw new Error(`${a} lists the measurements of a ${i.role}, not of a node image`);let c=i?.profiles?.[e];if(!c){let d=Object.keys(i?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${d})`)}if(e!==dr&&!n)throw new Error(`${JSON.stringify(e)} is not a production profile: its image is readable by whoever operates the node. Trust ${JSON.stringify(dr)}, or pass allowDebugProfile to test`);let u=(c.allowed_tcb_statuses??["uptodate"]).map(d=>ic(d,a));return r=r===void 0?u:r.filter(d=>u.includes(d)),{mrtd:c.mrtd,rtmr0:c.rtmr0,rtmr1:c.rtmr1,rtmr2:c.rtmr2,rtmr3:c.rtmr3}});if(!r||r.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:o,allowedTcbStatuses:r}}function ic(t,e){let n=oc.find(r=>r.toLowerCase()===String(t).toLowerCase());if(!n)throw new Error(`${e} accepts TCB status ${JSON.stringify(t)}, which this verifier does not know`);return n}var ci=[{uri:"https://fulcio.sigstore.dev",validFor:{start:"2021-03-07T03:20:29Z",end:"2022-12-31T23:59:59.999Z"},certChain:["MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="]},{uri:"https://fulcio.sigstore.dev",validFor:{start:"2022-04-13T20:06:15Z"},certChain:["MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow=","MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"]}],li=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var sc="1.2.840.10045.2.1",ac={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},cc={"P-256":32,"P-384":48},lc={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function ui(t,e,n){if(e+2>n)throw new Error("it is truncated");let r=t[e];if((r&31)===31)throw new Error("it uses a tag this parser does not read");let o=t[e+1],i=e+2;if(o&128){let a=o&127;if(a===0||a>4||i+a>n)throw new Error("it has a length this parser does not read");o=0;for(let c=0;c<a;c+=1)o=o*256+t[i+c];i+=a}let s=i+o;if(s>n)throw new Error("it is truncated");return{tag:r,bytes:t,offset:e,start:i,end:s}}function Pe(t){let e=ui(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function _(t){let e=[];for(let n=t.start;n<t.end;){let r=ui(t.bytes,n,t.end);e.push(r),n=r.end}return e}function N(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ae(t){return t.bytes.slice(t.start,t.end)}function Kt(t){return t.bytes.slice(t.offset,t.end)}function Ie(t){let e=ae(N(t,6,"An object identifier"));if(e.length===0||e[e.length-1]&128)throw new Error("it has a malformed object identifier");let n=[],r=0;for(let s of e)r=r*128+(s&127),s&128||(n.push(r),r=0);let o=n.shift();return[...o<80?[Math.floor(o/40),o%40]:[2,o-80],...n].join(".")}function uc(t){let e=new TextDecoder().decode(ae(t)),n=t.tag===23?/^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,r=t.tag===24?/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(e):null,o=n??r;if(!o)throw new Error(`it holds the time ${JSON.stringify(e)}, which is not one a certificate may hold`);let i=Number(o[1]);n&&(i+=i<50?2e3:1900);let[s,a,c,u,d]=o.slice(2).map(Number);return Date.UTC(i,s-1,a,c,u,d)}function mr(t){try{let[e,n,r,...o]=_(N(Pe(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=_(N(e,48,"The signed part")),s=i[0]?.tag===160?1:0,[a,c,u,d,l,g,...A]=i.slice(s);N(a,2,"The serial number");let x=Ie(_(N(n,48,"The signature algorithm"))[0]);if(Ie(_(N(c,48,"The signature algorithm"))[0])!==x)throw new Error("it names two different signature algorithms");let v=lc[x];if(!v)throw new Error(`it is signed with ${x}, not ECDSA with SHA-256 or SHA-384`);let[I,P]=_(N(d,48,"The validity")).map(uc);if(P===void 0)throw new Error("its validity is incomplete");let[B,M]=_(N(g,48,"The public key"));N(M,3,"The public key");let[h,y]=_(N(B,48,"The key algorithm"));if(Ie(h)!==sc)throw new Error("its key is not an elliptic-curve key");let S=ac[Ie(y)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let O=new Map,L=A.find(ee=>ee.tag===163);if(L){let[ee]=_(L);for(let te of _(N(ee,48,"The extensions"))){let xe=_(N(te,48,"An extension"));if(xe.length===3)N(xe[1],1,"An extension's critical flag");else if(xe.length!==2)throw new Error("it has a malformed extension");let Kn=Ie(xe[0]);if(O.has(Kn))throw new Error(`it has extension ${Kn} twice`);O.set(Kn,ae(N(xe[xe.length-1],4,"An extension value")))}}let Z=ae(N(r,3,"The signature"));if(Z[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:Kt(e),signatureHash:v,signature:Z.slice(1),issuer:Kt(N(u,48,"The issuer")),subject:Kt(N(l,48,"The subject")),notBefore:I,notAfter:P,spki:Kt(g),curve:S,extensions:O}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function di(t){return _(N(Pe(t),48,"The list")).map(Ie)}function dc(t,e){let n=cc[e],r=_(N(Pe(t),48,"The signature"));if(r.length!==2)throw new Error("The signature is not an ECDSA signature");let o=new Uint8Array(n*2);return r.forEach((i,s)=>{let a=ae(N(i,2,"The signature"));if(a.length===0||a[0]&128)throw new Error("The signature is not an ECDSA signature");for(;a.length>1&&a[0]===0;)a=a.subarray(1);if(a.length>n)throw new Error("The signature is not an ECDSA signature");o.set(a,s*n+n-a.length)}),o}async function Lt(t,e,n,r,o){let i;try{i=dc(r,e)}catch{return!1}let s=await crypto.subtle.importKey("spki",t,{name:"ECDSA",namedCurve:e},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:n},s,i,o)}function V(t,e){let n=t.replace(/\s+/g,"");if(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0)throw new Error(`${e} is not base64`);let r=atob(n),o=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)o[i]=r.charCodeAt(i);return o}function hr(t,e){let n=[...t.matchAll(/-----BEGIN CERTIFICATE-----([^-]*)-----END CERTIFICATE-----/g)];if(n.length!==1||t.replace(n[0][0],"").trim()!=="")throw new Error(`${e} is not exactly one PEM certificate`);return V(n[0][1],e)}var pc="2.5.29.17",gc="2.5.29.37",mc="1.3.6.1.5.5.7.3.3",hc="1.3.6.1.4.1.57264.1.8",fc="1.3.6.1.4.1.57264.1.1",yc=134,bc=12,wc=48,Ac=new TextEncoder,Te=t=>new TextDecoder().decode(t);async function pi(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:s}=Cc(e),a=s.Payload;if(r!==void 0&&r.trim()!==o.trim())throw new Error("The detached signature is not the one in the bundle");let c=V(o,"The bundle signature"),u=hr(Te(V(i,"The bundle certificate")),"The bundle certificate"),d=mr(u),l=li.find(P=>P.logId===a.logID.toLowerCase());if(!l)throw new Error(`The bundle names Rekor log ${a.logID}, which the Sigstore trust root does not know`);let g=Ac.encode(`{"body":${JSON.stringify(a.body)},"integratedTime":${a.integratedTime},"logID":${JSON.stringify(a.logID)},"logIndex":${a.logIndex}}`);if(!await Lt(V(l.publicKey,"The Rekor key"),"P-256","SHA-256",V(s.SignedEntryTimestamp,"The signed entry timestamp"),g))throw new Error("Rekor's signed entry timestamp does not verify: the log entry, its time or its index was altered");let x=a.integratedTime*1e3;if(!hi(x,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${rt(x)}, when the entry says it was logged`);let w=Sc(a.body),v=f(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(w.hash!==v)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!fr(V(w.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let I=hr(Te(V(w.publicKey,"The logged certificate")),"The logged certificate");if(!fr(I,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await Lt(d.spki,"P-256","SHA-256",c,t))throw new Error("The signature over the file does not verify with the bundle's certificate");return await xc(d,x),vc(d,n),{integratedTime:a.integratedTime}}async function xc(t,e){if(!mi(t,e))throw new Error(`The signing certificate was valid ${rt(t.notBefore)} to ${rt(t.notAfter)}, not at ${rt(e)} when Rekor logged it`);let n=[];for(let r of ci){let o=r.certChain.map(s=>mr(V(s,"A Fulcio certificate")));if(!await gi(t,o[0]))continue;let i=await Rc(o,r.validFor,e);if(!i)return;n.push(`${r.uri} (valid from ${r.validFor.start}): ${i}`)}throw new Error(n.length>0?`The signing certificate's CA is not trusted at ${rt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function Rc(t,e,n){if(!hi(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!mi(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await gi(o,i))return`its certificate ${r} is not signed by the next`}}async function gi(t,e){return fr(t.issuer,e.subject)?Lt(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function vc(t,e){let n=t.extensions.get(pc);if(!n)throw new Error("The signing certificate names no identity");let r=_(N(Pe(n),wc,"The subject alternative name")),o=r.filter(u=>u.tag===yc).map(u=>Te(ae(u)));if(o.length!==1||r.length!==1||o[0]!==e.identity)throw new Error(`The release was signed by ${JSON.stringify(o.length===1?o[0]:o)}, not by ${e.identity}`);let i=t.extensions.get(hc),s=t.extensions.get(fc),a=i?Te(ae(N(Pe(i),bc,"The OIDC issuer"))):s?Te(s):void 0;if(a!==e.issuer)throw new Error(`The signing certificate's OIDC issuer is ${a===void 0?"missing":JSON.stringify(a)}, not ${e.issuer}`);let c=t.extensions.get(gc);if(!c||!di(c).includes(mc))throw new Error("The signing certificate is not for code signing")}function Cc(t){let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{throw new Error("The bundle is not JSON")}let n=e,r=n?.rekorBundle?.Payload;if(!(typeof n?.base64Signature=="string"&&typeof n.cert=="string"&&typeof n.rekorBundle?.SignedEntryTimestamp=="string"&&typeof r?.body=="string"&&typeof r.logID=="string"&&/^[0-9a-fA-F]{64}$/.test(r.logID)&&Number.isSafeInteger(r.integratedTime)&&r.integratedTime>=0&&Number.isSafeInteger(r.logIndex)&&r.logIndex>=0))throw new Error("The bundle is not a cosign bundle with a Rekor entry");return n}function Sc(t){let e;try{e=JSON.parse(Te(V(t,"The logged entry")))}catch{throw new Error("The logged entry is not JSON")}let n=e?.spec?.data?.hash,r=e?.spec?.signature;if(e?.kind!=="hashedrekord"||n?.algorithm!=="sha256"||typeof n.value!="string"||typeof r?.content!="string"||typeof r.publicKey?.content!="string")throw new Error("The logged entry is not a SHA-256 hashedrekord");return{hash:n.value.toLowerCase(),signature:r.content,publicKey:r.publicKey.content}}function mi(t,e){return t.notBefore<=e&&e<=t.notAfter}function hi(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function rt(t){return new Date(t).toISOString()}function fr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var yr=Object.freeze({identity:"https://github.com/calimero-network/mero-tee/.github/workflows/release-node-image-gcp.yaml@refs/heads/master",issuer:"https://token.actions.githubusercontent.com"}),kc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Ht="https://cloud.calimero.network";async function yi(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await pi(r,e,{identity:n.identity??yr.identity,issuer:n.issuer??yr.issuer},n.signature);let o;try{o=JSON.parse(new TextDecoder().decode(r))}catch{throw new Error("The signed release is not JSON")}if(o?.role!=="node")throw new Error(`The signed release is a ${JSON.stringify(o?.role)} release, not a node one`);let i=Object.values(o.profiles??{}),s=a=>kc.every(c=>/^[0-9a-f]{96}$/i.test(String(a?.[c])));if(typeof o.tag!="string"||i.length===0||!i.every(s))throw new Error("The signed file is not a release's published-mrtds.json: it lists no measured profiles");if(n.expectedVersion!==void 0&&o.tag!==n.expectedVersion)throw new Error(`The signed release is ${o.tag}, not ${n.expectedVersion}`);return o}async function qt(t,e={}){let n=await(e.fetch??fetch)(t,{headers:{accept:"application/json"}});if(!n.ok)throw new Error(`Fetching the node release from ${t} failed: HTTP ${n.status}`);let r;try{r=(await n.json())?.data}catch{throw new Error(`${t} did not answer with JSON`)}if(typeof r?.version!="string"||typeof r.publishedMrtds!="string"||typeof r.bundle!="string")throw new Error(`${t} did not answer with a signed node release`);return{version:r.version,publishedMrtds:r.publishedMrtds,bundle:r.bundle}}function bi(t){let e=/^merotee-.+-(\d+)-(\d+)-(\d+)$/.exec(t);if(!e)throw new Error(`${JSON.stringify(t)} is not the image of a mero-tee node release`);return`${Number(e[1])}.${Number(e[2])}.${Number(e[3])}`}async function Bt(t,e={}){let n=await Ai(t,e.fetch??fetch);if(n===void 0)throw new Error(`${wi(t)} was refused unsealed: the node requires sealing and is too old to name its release before a session exists. Name the release it runs yourself (createSignedReleaseSealedFetch's \`releaseVersion\`), or upgrade the node`);return n}function wi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function Ai(t,e){let n=wi(t),r=await e(n,{headers:{accept:"application/json"}});if(r.status===403&&await r.json().then(s=>s?.error?.code).catch(()=>{})==="sealed_required")return;if(!r.ok)throw new Error(`Fetching ${n} failed: HTTP ${r.status}`);let o;try{o=(await r.json())?.data?.osImage}catch{throw new Error(`${n} did not answer with JSON`)}if(typeof o!="string")throw new Error(`${n} did not name the node's image`);return bi(o)}function jt(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${ot(e,"version")}`}async function xi(t){let e=ot(t.minReleaseVersion,"minReleaseVersion"),n=ot(t.release?.version,"The release version"),r=await yi(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(Ic(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return gr([r],{profile:t.profile,allowDebugProfile:t.allowDebugProfile})}function Ft(t){return ot(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await xi({release:await t.release(),profile:t.profile,allowDebugProfile:t.allowDebugProfile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return pr({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function Ec(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:s,...a}=t;r!==void 0&&ot(r,"releaseVersion");let c=s??((d,l)=>fetch(d,l));return pe({baseUrl:e,verify:Ft({...a,release:async()=>{let d=r===void 0?await Bt(e,{fetch:c}):await Ai(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):qt(jt(n??Ht,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var Ri=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function ot(t,e){let n=typeof t=="string"?Ri.exec(t):null,r=n?.[4];if(!n||r!==void 0&&r.split(".").some(o=>o===""))throw new Error(`${e} is ${JSON.stringify(t)}, not a release version like 2.3.87`);return t}function Ic(t,e){let[n,r]=fi(t),[o,i]=fi(e);for(let c=0;c<3;c+=1)if(n[c]!==o[c])return n[c]<o[c]?-1:1;if(r===void 0||i===void 0)return r===i?0:r===void 0?1:-1;let s=r.split("."),a=i.split(".");for(let c=0;c<Math.max(s.length,a.length);c+=1){let[u,d]=[s[c],a[c]];if(u===void 0||d===void 0)return u===void 0?-1:1;let[l,g]=[/^\d+$/.test(u),/^\d+$/.test(d)],A=l&&g?Math.sign(Number(u)-Number(d)):l!==g?l?-1:1:u<d?-1:u>d?1:0;if(A!==0)return A}return 0}function fi(t){let e=Ri.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Pc=new TextEncoder().encode("calimero.warrant.v2"),Tc=new TextEncoder().encode("calimero.warrant.intent.v1"),vi=64,Ci=256;async function br(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(Tc,[new TextEncoder().encode(t),n])}async function Vt(t){let e=p(t.context,"context",32),n=p(t.authorAccount,"authorAccount",32),r=p(t.executor,"executor",32),o=p(t.executorKey,"executorKey",32),i=p(t.releaseBytecodeId,"releaseBytecodeId",32),s=wr(t.releaseVersion??""),a=ce(t.accountHeads,"accountHeads"),c=ce(t.governanceFloor,"governanceFloor"),u=await E(t.deviceSecret,t.signer,"deviceSecret"),d=p(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),g=await br(t.method,t.argsJson),A=C(t.nonce),x=C(t.notAfter),w=await k(Pc,[e,n,d,r,o,i,s,l,g,C(a.length),...a,C(c.length),...c,A,x]),v=it(await u.sign(w));return f(m(e,n,d,r,o,i,R(s.length),s,R(l.length),l,g,R(a.length),...a,R(c.length),...c,A,x,v))}function it(t){if(!(t instanceof Uint8Array)||t.length!==64){let e=t instanceof Uint8Array?`${t.length} bytes`:typeof t;throw new Error(`signer returned ${e}, expected a 64-byte Ed25519 signature`)}return t}function wr(t){let e=new TextEncoder().encode(t);return Dc(e.length),e}function Dc(t){if(t>Ci)throw new Error(`releaseVersion is ${t} bytes, over the ${Ci} a node accepts`)}function ce(t,e){let n=t??[];if(n.length>vi)throw new Error(`${e} cites ${n.length} heads, over the ${vi} a node accepts`);return n.map((r,o)=>p(r,`${e}[${o}]`,32))}var Nc=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Oc=new TextEncoder().encode("calimero.context-creation.init.v1"),Wt=256;async function Ar(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(Oc,[e])}async function Uc(t){return k(Nc,[t.group,t.seed,t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.applicationId,new Uint8Array([t.serviceName===null?0:1]),t.serviceName??new Uint8Array(0),new Uint8Array([t.name===null?0:1]),t.name??new Uint8Array(0),t.initHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function Jt(t){let e=p(t.group,"group",32),n=t.seed===void 0?crypto.getRandomValues(new Uint8Array(32)):p(t.seed,"seed",32),r=p(t.authorAccount,"authorAccount",32),o=p(t.executor,"executor",32),i=p(t.executorKey,"executorKey",32),s=p(t.applicationId,"applicationId",32),a=Si(t.serviceName,"serviceName"),c=Si(t.name,"name"),u=ce(t.accountHeads,"accountHeads"),d=ce(t.governanceFloor,"governanceFloor"),l=await E(t.deviceSecret,t.signer,"deviceSecret"),g=p(l.publicKey,"signer.publicKey",32),A=await Ar(t.initArgs),x=await Uc({group:e,seed:n,authorAccount:r,deviceKey:g,executor:o,executorKey:i,applicationId:s,serviceName:a,name:c,initHash:A,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),w=it(await l.sign(x));return{warrant:f(m(e,n,r,g,o,i,s,ki(a),ki(c),A,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),w)),seed:f(n)}}function Ei(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("creation warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,g)=>{if(o+l>n.length)throw new Error(`creation warrant ends inside ${g} (${n.length} bytes)`);let A=n.subarray(o,o+l);return o+=l,A},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let g=i(1,l)[0];if(g===0)return null;if(g!==1)throw new Error(`${l} has option tag ${g}, expected 0 or 1`);let A=s(l);if(A>Wt)throw new Error(`${l} is ${A} bytes, over the ${Wt} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(A,l))},u=l=>{let g=s(l);if(g>64)throw new Error(`${l} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>f(i(32,l)))},d={group:f(i(32,"group")),seed:f(i(32,"seed")),authorAccount:f(i(32,"authorAccount")),deviceKey:f(i(32,"deviceKey")),executor:f(i(32,"executor")),executorKey:f(i(32,"executorKey")),applicationId:f(i(32,"applicationId")),serviceName:c("serviceName"),name:c("name"),initHash:f(i(32,"initHash")),accountHeads:u("accountHeads"),governanceFloor:u("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:f(i(64,"signature"))};if(o!==n.length)throw new Error(`creation warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Si(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>Wt)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${Wt} a node accepts`);return n}function ki(t){return t===null?new Uint8Array([0]):m(new Uint8Array([1]),R(t.length),t)}var Mc=new TextEncoder().encode("calimero.governance-warrant.v1"),_c=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Gc={group:0,root:1};async function xr(t){return k(_c,[new Uint8Array([Rr(t.kind)]),t.bytes])}async function $c(t){return k(Mc,[t.scope,new Uint8Array([Rr(t.kind)]),t.authorAccount,t.deviceKey,t.executor,t.executorKey,t.opHash,C(t.accountHeads.length),...t.accountHeads,C(t.governanceFloor.length),...t.governanceFloor,C(t.nonce),C(t.notAfter)])}async function st(t){let e=p(t.scope,"scope",32),n=p(t.authorAccount,"authorAccount",32),r=p(t.executor,"executor",32),o=p(t.executorKey,"executorKey",32),i=ce(t.accountHeads,"accountHeads"),s=ce(t.governanceFloor,"governanceFloor"),a=Rr(t.op.kind),c=await E(t.deviceSecret,t.signer,"deviceSecret"),u=p(c.publicKey,"signer.publicKey",32),d=await xr(t.op),l=await $c({scope:e,kind:t.op.kind,authorAccount:n,deviceKey:u,executor:r,executorKey:o,opHash:d,accountHeads:i,governanceFloor:s,nonce:t.nonce,notAfter:t.notAfter}),g=it(await c.sign(l));return f(m(e,new Uint8Array([a]),n,u,r,o,d,R(i.length),...i,R(s.length),...s,C(t.nonce),C(t.notAfter),g))}function Ii(t){let e=t.trim();if(!/^[0-9a-fA-F]*$/.test(e)||e.length%2!==0)throw new Error("governance warrant must be an even number of hex characters");let n=new Uint8Array(e.length/2);for(let l=0;l<n.length;l+=1)n[l]=Number.parseInt(e.slice(l*2,l*2+2),16);let r=new DataView(n.buffer),o=0,i=(l,g)=>{if(o+l>n.length)throw new Error(`governance warrant ends inside ${g} (${n.length} bytes)`);let A=n.subarray(o,o+l);return o+=l,A},s=l=>r.getUint32(i(4,l).byteOffset,!0),a=l=>r.getBigUint64(i(8,l).byteOffset,!0),c=l=>{let g=s(l);if(g>64)throw new Error(`${l} cites ${g} heads, over the 64 a node accepts`);return Array.from({length:g},()=>f(i(32,l)))},u=()=>{let l=i(1,"kind")[0];if(l===0)return"group";if(l===1)return"root";throw new Error(`governance warrant has kind ${l}, expected 0 (group) or 1 (root)`)},d={scope:f(i(32,"scope")),kind:u(),authorAccount:f(i(32,"authorAccount")),deviceKey:f(i(32,"deviceKey")),executor:f(i(32,"executor")),executorKey:f(i(32,"executorKey")),opHash:f(i(32,"opHash")),accountHeads:c("accountHeads"),governanceFloor:c("governanceFloor"),nonce:a("nonce"),notAfter:a("notAfter"),signature:f(i(64,"signature"))};if(o!==n.length)throw new Error(`governance warrant is ${n.length} bytes but its fields account for ${o}`);return d}function Rr(t){let e=Gc[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Kc={Admin:0,Member:1,ReadOnly:2},G={MemberAdded:1,MemberRemoved:2,MemberLeft:3,MemberRoleSet:4,MemberCapabilitySet:5,DefaultCapabilitiesSet:6,TargetApplicationSet:7,ContextDetached:9,SubgroupVisibilitySet:10,GroupMetadataSet:11,MemberMetadataSet:12,ContextMetadataSet:13,ContextCapabilityGranted:16,ContextCapabilityRevoked:17},at={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Lc=new TextEncoder().encode("calimero.namespace.id.v1"),Cr=new Uint8Array(32),zt=R(0);function Ti(t){let e=Kc[t];if(e===void 0)throw new Error(`role must be Admin, Member or ReadOnly, got ${String(t)}`);return new Uint8Array([e])}function D(t){return new Uint8Array([t])}function De(t,e){return{kind:"group",bytes:m(D(G.MemberAdded),p(t,"member",32),Ti(e))}}function Qt(t){return{kind:"group",bytes:m(D(G.MemberRemoved),p(t,"member",32),Cr,zt)}}function ct(t){return{kind:"group",bytes:m(D(G.MemberLeft),p(t,"member",32),Cr,zt)}}function Yt(t,e){return{kind:"group",bytes:m(D(G.MemberRoleSet),p(t,"member",32),Ti(e))}}var Hc=new TextEncoder().encode("calimero.subgroup.id.v1");async function Sr(t,e,n,r){return f(await k(Hc,[p(t,"admin",32),p(e,"parentId",32),new Uint8Array([n?1:0]),p(r,"salt",32)]))}function Pi(t,e){if(t.length===0)throw new Error(`${e} must not be empty`);let n=new TextEncoder().encode(t);return m(R(n.length),n)}function Xt(t){return{kind:"group",bytes:m(D(G.TargetApplicationSet),Cr,p(t.applicationId,"applicationId",32),Pi(t.package,"package"),Pi(t.version,"version"))}}function Ne(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ue(t,U.CAN_AUTHOR_ON_BEHALF))throw new Error("capabilities may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it");return{kind:"group",bytes:m(D(G.DefaultCapabilitiesSet),R(t))}}function kr(t){return{kind:"root",bytes:m(D(at.GroupCreated),p(t.groupId,"groupId",32),p(t.parentId,"parentId",32),D(t.restricted?1:0),p(t.admin,"admin",32),p(t.salt,"salt",32))}}async function Oe(t){let e=t.salt??f(crypto.getRandomValues(new Uint8Array(32))),n=await Sr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:kr({...t,groupId:n,salt:e})}}function Zt(t,e){return{kind:"root",bytes:m(D(at.GroupReparented),p(t,"childGroupId",32),p(e,"newParentId",32))}}function en(t){return{kind:"root",bytes:m(D(at.GroupDeleted),p(t,"rootGroupId",32),zt,zt)}}async function tn(t,e){return f(await k(Lc,[p(t,"founder",32),p(e,"salt",32)]))}function nn(t){let e=j(t.credential,"credential");if(e.length===0)throw new Error("credential must be the founder's AccountProof<DeviceCert>, got nothing");return{kind:"root",bytes:m(D(at.NamespaceCreatedV2),p(t.founder,"founder",32),e,p(t.salt,"salt",32))}}function vr(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function Er(t){return t===void 0?D(0):m(D(1),vr(t))}function Ir(t={}){let e=new TextEncoder,n=Object.entries(t).map(([r,o])=>[e.encode(r),o,r]).sort(([r],[o])=>{for(let i=0;i<Math.min(r.length,o.length);i++)if(r[i]!==o[i])return r[i]-o[i];return r.length-o.length});return m(R(n.length),...n.flatMap(([,r,o])=>[vr(o),vr(r)]))}function qc(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(ue(t,U.CAN_AUTHOR_ON_BEHALF))throw new Error(`${e} may not include CAN_AUTHOR_ON_BEHALF (512): a relay never carries a change to it`);return t}function rn(t,e){return{kind:"group",bytes:m(D(G.MemberCapabilitySet),p(t,"member",32),R(qc(e,"capabilities")))}}function on(t){return{kind:"group",bytes:m(D(G.ContextDetached),p(t,"contextId",32))}}function sn(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:m(D(G.SubgroupVisibilitySet),D(t==="open"?0:1))}}function Ue(t={}){return{kind:"group",bytes:m(D(G.GroupMetadataSet),Er(t.name),Ir(t.data))}}function an(t,e={}){return{kind:"group",bytes:m(D(G.MemberMetadataSet),p(t,"member",32),Er(e.name),Ir(e.data))}}function cn(t,e={}){return{kind:"group",bytes:m(D(G.ContextMetadataSet),p(t,"contextId",32),Er(e.name),Ir(e.data))}}function Di(t){if(!Number.isInteger(t)||t<1||t>255)throw new Error(`capability must be a non-zero u8, got ${String(t)}`);return D(t)}function Ni(t,e,n){return{kind:"group",bytes:m(D(G.ContextCapabilityGranted),p(t,"contextId",32),p(e,"member",32),Di(n))}}function Oi(t,e,n){return{kind:"group",bytes:m(D(G.ContextCapabilityRevoked),p(t,"contextId",32),p(e,"member",32),Di(n))}}function ln(t){return{kind:"root",bytes:m(D(at.MemberJoinedOpen),p(t.member,"member",32),p(t.groupId,"groupId",32),j(t.credential,"credential"))}}var un=300,ge=class extends Error{constructor(n,r,o){super(`relay refused the intent (HTTP ${o}): ${n}`);this.reason=n;this.retryable=r;this.status=o;this.name="IntentRefusedError"}},Bc=t=>new Promise(e=>setTimeout(e,t));function jc(t){let e=t?.get?.("Retry-After");if(!e)return null;let n=Number.parseInt(e,10);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(0,r-Date.now()):null}var W=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,"");let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.rateLimitRetries=e.rateLimitRetries??3}get relayUrl(){return this.baseUrl}get authorAccount(){return this.config.authorAccount}get authorProof(){return this.config.authorProof}async authorSigner(){return E(this.config.deviceSecret,this.config.signer,"deviceSecret")}async describe(e){return(await this.json("GET",`/admin-api/contexts/${encodeURIComponent(e)}/intents`)).data}async execute(e,n,r={}){let o=await this.describe(e),i=this.checkedExecutor(o),s=f(p(o.releaseBytecodeId??"","the relay's releaseBytecodeId",32)),a=o.releaseVersion??"";wr(a);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??un,l=await Vt({context:e,authorAccount:this.config.authorAccount,executor:i.executorAccount,executorKey:i.executorKey,releaseBytecodeId:s,releaseVersion:a,method:n,argsJson:r,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),g=await this.json("POST",`/admin-api/contexts/${encodeURIComponent(e)}/intents`,{method:n,argsJson:r,warrant:l,authorProof:this.config.authorProof});return{rootHash:g.data.rootHash,returns:g.data.returns??null}}async presenceIntent(e,n){await this.jsonOnce("POST",`/admin-api/contexts/${encodeURIComponent(e)}/presence-intents`,n)}async describeCreation(e,n={}){let r=n.author?`?author=${encodeURIComponent(n.author)}`:"";return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/context-intents${r}`)).data}async createContext(e){let n=await this.describeCreation(e.groupId,{author:this.config.authorAccount});if(!n.canCreateOnBehalf)throw new ge(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing \u2014 no nonce was spent)`,!1,403);if(n.authorMayCreate===!1)throw new ge(`the author (${this.config.authorAccount}) may not create contexts in group ${n.groupId}; it needs CAN_CREATE_CONTEXT or admin (checked before signing \u2014 no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=e.initArgs??{},i=await this.authorSigner(),s=await this.config.nonces.next(),a=this.config.ttlSeconds??un,{warrant:c}=await Jt({group:e.groupId,seed:e.seed,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,applicationId:e.applicationId,serviceName:e.serviceName,name:e.name,initArgs:o,nonce:s,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(a),signer:i}),u=await this.json("POST",`/admin-api/groups/${encodeURIComponent(e.groupId)}/context-intents`,{warrant:c,authorProof:this.config.authorProof,initArgs:o});return{contextId:u.data.contextId,groupId:u.data.groupId,memberPublicKey:u.data.memberPublicKey}}async describeGovernance(e){return(await this.json("GET",`/admin-api/groups/${encodeURIComponent(e)}/governance-intents`)).data}async govern(e){let n=await this.describeGovernance(e.groupId);if(!n.canActOnBehalf)throw new ge(`the relay (${n.executorAccount}) has no standing to act for members of group ${n.groupId}; an admin must admit it as a relay or grant it CAN_AUTHOR_ON_BEHALF (checked before signing, no nonce was spent)`,!1,403);let r=this.checkedExecutor(n),o=await this.authorSigner(),i=await this.config.nonces.next(),s=this.config.ttlSeconds??un,a=await st({scope:e.groupId,op:e.op,authorAccount:this.config.authorAccount,executor:r.executorAccount,executorKey:r.executorKey,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(s),signer:o});return{groupId:(await this.postGovernance(e.groupId,e.op,a)).groupId}}async foundNamespace(e){if(!e?.executor)throw new Error("foundNamespace needs the relay's account and signing key: pass executor (checked before signing, no nonce was spent)");let n=this.checkedExecutor(e.executor),r=e.salt?f(p(e.salt,"salt",32)):f(crypto.getRandomValues(new Uint8Array(32))),o=await tn(this.config.authorAccount,r),i=nn({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),s=e.defaultCapabilities===void 0?void 0:Ne(e.defaultCapabilities),a=e.application?Xt(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??un,l=await st({scope:o,op:i,authorAccount:this.config.authorAccount,executor:n.executorAccount,executorKey:n.executorKey,nonce:u,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(d),signer:c}),g=await this.postGovernance(o,i,l),A={namespaceId:g.groupId,salt:r,teeEnabled:g.teeEnabled??!1,...g.teeError?{teeError:g.teeError}:{}},x=A,w=v=>v instanceof Error?v.message:String(v);if(a)try{await this.govern({groupId:A.namespaceId,op:a}),x={...x,applicationSet:!0}}catch(v){x={...x,applicationSet:!1,applicationError:w(v)}}if(s)try{await this.govern({groupId:A.namespaceId,op:s}),x={...x,defaultCapabilitiesSet:!0}}catch(v){x={...x,defaultCapabilitiesSet:!1,defaultCapabilitiesError:w(v)}}return x}async postGovernance(e,n,r){return(await this.json("POST",`/admin-api/groups/${encodeURIComponent(e)}/governance-intents`,{warrant:r,authorProof:this.config.authorProof,op:f(n.bytes)})).data}checkedExecutor(e){let n={executorAccount:f(p(e.executorAccount??"","the relay's executorAccount",32)),executorKey:f(p(e.executorKey??"","the relay's executorKey",32))},r=this.config.executorAccount;if(r&&r.toLowerCase()!==n.executorAccount)throw new Error(`configured executorAccount ${r} is not the relay's account ${n.executorAccount}; a warrant naming it would be unspendable`);return n}async json(e,n,r){let o=250;for(let i=0;;i+=1)try{return await this.jsonOnce(e,n,r)}catch(s){if(!(s instanceof T&&s.status===429)||i>=this.rateLimitRetries)throw s;let c=jc(s.headers);await Bc(c??o),o*=2}}async jsonOnce(e,n,r){let o={Accept:"application/json"};r!==void 0&&(o["Content-Type"]="application/json");let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r===void 0?void 0:JSON.stringify(r),signal:i.signal})}catch(c){throw new T(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(!a.ok){let c=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=Fc(c);throw new ge(u,/nonce/i.test(u),a.status)}throw new T(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(a.status!==204)return await a.json()}};function Fc(t){if(!t)return"no reason given";try{let e=JSON.parse(t);for(let n of[e.error,e.message])if(typeof n=="string"&&n)return n}catch{}return t}var me=class{constructor(e,n=null){this.relay=e;this.observer=n;this.kind="relay"}get canSubscribe(){return this.observer!==null}get events(){return this.observer}get client(){return this.relay}async execute(e){let{returns:n}=await this.executeWithMetadata(e);return n}async executeWithMetadata(e){let n=await this.relay.execute(e.contextId,e.method,e.argsJson??{});return{returns:n.returns,transport:"relay",rootHash:n.rootHash}}async migrateMyEntries(e){return this.execute({contextId:e,method:"migrate_my_entries"})}async countMyPending(e){return this.execute({contextId:e,method:"count_my_pending"})}};var Vc=new TextEncoder().encode("calimero.auth.login.v1"),Ui={webOrigin:0,codeSigningId:1,cli:2};function Mi(t){let e=new TextEncoder;switch(t.kind){case"webOrigin":return e.encode(t.origin);case"codeSigningId":return e.encode(t.id);case"cli":return new Uint8Array(0)}}function Wc(t){return m(Uint8Array.from([Ui[t.kind]]),Mi(t))}function Jc(t){let e=Uint8Array.from([Ui[t.kind]]);if(t.kind==="cli")return e;let n=Mi(t);return m(e,R(n.length),n)}async function dn(t){let e=p(t.node,"node",32),n=p(t.challenge,"challenge",32),r=p(t.sessionKey,"sessionKey",32),o=await E(t.deviceSecret,t.signer,"deviceSecret"),i=p(o.publicKey,"signer.publicKey",32),s=C(t.issuedAt),a=C(t.expiresAt),c=await k(Vc,[e,Wc(t.audience),n,r,i,s,a]),u=await o.sign(c);return f(m(e,Jc(t.audience),n,r,i,s,a,u))}var zc=300;async function Pr(){let t=f(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:f(await oe(t)),secret:t}}async function Me(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(g,A)=>{let x=new AbortController,w=setTimeout(()=>x.abort(),n),v;try{let P={...A,signal:x.signal};v=t.fetch?await t.fetch(`${e}${g}`,P):await globalThis.fetch(`${e}${g}`,P)}catch(P){throw new T(0,P instanceof Error?P.name:"NetworkError",`${e}${g}`,new Headers,P instanceof Error?P.message:String(P))}finally{clearTimeout(w)}let I=await v.text().catch(()=>"");if(!v.ok)throw new T(v.status,v.statusText,`${e}${g}`,v.headers,I);return I?JSON.parse(I):{}},o=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),i=o.challenge??o.data?.challenge;if(!i)throw new Error("the node issued no challenge");let s=await Pr(),a=Math.floor(Date.now()/1e3),c=await dn({node:t.node,audience:t.audience,challenge:i,sessionKey:s.publicKey,issuedAt:a,expiresAt:a+(t.ttlSeconds??zc),signer:await E(t.deviceSecret,t.signer,"deviceSecret")}),u=await r("/auth/token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({auth_method:"account_proof",public_key:s.publicKey,client_name:t.clientName??e,timestamp:a,provider_data:{challenge:i,login_statement:c,account_proof:t.accountProof}})}),d=u.access_token??u.data?.access_token,l=u.refresh_token??u.data?.refresh_token;if(!d)throw new Error("the node minted no session");return{accessToken:d,refreshToken:l??"",sessionKey:s.publicKey,sessionSecret:s.secret}}var Qc=3e4;function Ge(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function Yc(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));return typeof r.exp=="number"?r.exp*1e3:null}catch{return null}}var _e=class{constructor(e){this.session=null;this.sessionExpiresAt=null;this.pending=null;this.sseClient=null;this.wsClient=null;this.config=e}get nodeKey(){return this.config.nodeKey}async accessToken(){let e=Date.now();return this.session&&this.sessionExpiresAt!==null&&this.sessionExpiresAt-Qc>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Me({nodeUrl:this.config.nodeUrl,node:this.config.nodeKey,signer:await this.config.signer(),accountProof:this.config.accountProof,audience:this.config.audience,clientName:this.config.clientName,ttlSeconds:this.config.ttlSeconds,fetch:this.config.fetch,timeoutMs:this.config.timeoutMs});return this.session=e,this.sessionExpiresAt=Yc(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new H({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new ie({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var Q=t=>new TextEncoder().encode(t),Xc=Q("calimero.auth.request.v1"),Zc=Q("calimero.auth.request.body.v1"),Tr="X-Calimero-Proof",el=300;async function Dr(t){let{method:e,path:n,credential:r}=t;if(!e)throw new Error("signRequestProof needs the method the request will use");if(!n.startsWith("/"))throw new Error(`signRequestProof needs a path, got ${JSON.stringify(n)}`);if(n.includes("?"))throw new Error(`the path must carry no query string, got ${JSON.stringify(n)} \u2014 a query is excluded from the signature on purpose, because a proxy may rewrite one. Anything that must be bound belongs in the body.`);let o=t.body===void 0?new Uint8Array:typeof t.body=="string"?Q(t.body):t.body,i=await k(Zc,[o]),s=Math.floor(t.now??Date.now()/1e3),a=s+(t.validForSeconds??el),c=await k(Xc,[Q(e),Q(n),i,C(s),C(a)]),u=await tl(c,t);if(u.length!==64)throw new Error(`the signer returned ${u.length} bytes, not a 64-byte signature`);let d=m(R(Q(e).length),Q(e),R(Q(n).length),Q(n),i,C(s),C(a),u),l=nl(r,"credential");return f(m(l,new Uint8Array([0]),d))}async function tl(t,e){if(e.signer)return e.signer.sign(t);if(!e.deviceSecret)throw new Error("signRequestProof needs either `deviceSecret` or `signer`");let n=await re(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function nl(t,e){let n=t.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length%2!==0)throw new Error(`${e} is not an even-length hex string`);return p(n,e,n.length/2)}function Nr(t){if(!t.credential)throw new Error("a proof authorizer needs the `credential` from signDeviceCert");if(!t.deviceSecret&&!t.signer)throw new Error("a proof authorizer needs either `deviceSecret` or `signer`");return async({method:e,path:n,body:r})=>{let o=await Dr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Tr]:o}}}function rl(t){return new URL(t).pathname}var _i=new TextEncoder().encode("calimero/presence/1");async function Gi(t){let e=t===null?new Uint8Array([0]):m(new Uint8Array([1]),R(t.length),t);return new Uint8Array(await crypto.subtle.digest("SHA-256",e))}async function Or(t){return m(_i,p(t.contextId,"contextId",32),p(t.author,"author",32),C(t.seq),C(t.sentAtMs),await Gi(t.state))}var ol=2500,lt=class{constructor(e){this.timers=new Map;this.lastSeq=new Map;this.refused=new Set;this.generation=new Map;this.relay=e.relay,this.events=e.events,this.heartbeatMs=e.heartbeatMs??ol,this.now=e.now??Date.now}async set(e,n,r=se()){let o=this.bump(e);this.refused.delete(e);let i=n===null?null:new Uint8Array(r.encode(n));await this.send(e,i),!(i===null||this.refused.has(e))&&this.generation.get(e)===o&&this.timers.set(e,setInterval(()=>{this.send(e,i).catch(()=>{})},this.heartbeatMs))}subscribe(e,n,r=se()){return Tt(this.events(),e,n,r)}close(){for(let e of new Set([...this.timers.keys(),...this.generation.keys()]))this.bump(e)}bump(e){this.stop(e);let n=(this.generation.get(e)??0)+1;return this.generation.set(e,n),n}stop(e){let n=this.timers.get(e);n!==void 0&&clearInterval(n),this.timers.delete(e)}nextSeq(e){let n=Math.max(this.now(),(this.lastSeq.get(e)??0)+1);return this.lastSeq.set(e,n),n}async send(e,n){if(this.refused.has(e))return;let r=await this.relay.authorSigner(),o=this.nextSeq(e),i=this.now(),s=await Or({contextId:e,author:r.publicKey,seq:BigInt(o),sentAtMs:BigInt(i),state:n}),a=f(await r.sign(s));try{await this.relay.presenceIntent(e,{state:n===null?null:f(n),seq:o,sentAtMs:i,signature:a,authorProof:this.relay.authorProof})}catch(c){let u=c.status;if(u===void 0||u===0||u===429||u>=500)return;throw this.refused.add(e),this.stop(e),c}}};function $i(t,e){return new Error(`this client was constructed with the relay transport, which has no ${t}: ${e}. Construct a node client (createMeroClient({ baseUrl })) for that surface \u2014 nothing here will silently connect to a node you did not choose.`)}function Ki(t){return new Error(`this relay-transport client cannot open ${t}: it was given no relay node key. A relay is an ordinary node and does serve /sse and /ws \u2014 but the login statement must be signed against the node's device signing key, learned out of band (never read from the node, and never derived from its peerId). Pass it as \`observe: { nodeKey }\`. For a cloud-hosted relay the cloud does not publish it yet \u2014 see mdma #312.`)}function il(t,e,n){let r=e?.nodeKey;return r?new _e({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??Ge(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var he=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayFetch=void 0;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.fetch;this.relayFetch=o;let i=e.relay instanceof W?e.relay:new W({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=il(i,e.observe,o),this.rpcTransport=new me(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=Nr(e.proof)),e.session){let s=e.session;this.relayAdmin=ho({baseUrl:i.relayUrl,getAuthToken:typeof s=="string"?async()=>s:s,fetch:o})}else if(this.proofAuthorizer){let s=this.proofAuthorizer;this.relayAdmin=Ct(ze({fetch:(a,c)=>o?o(a,c):globalThis.fetch(a,c),baseUrl:i.relayUrl,authorizeRequest:s}),{baseUrl:i.relayUrl})}return}this.transport="node";let{transport:n,...r}=e;this.nodeClient=new $e(r),this.rpcTransport=this.nodeClient.rpc}get rpc(){return this.rpcTransport}get canSubscribe(){return this.rpcTransport.canSubscribe||this.proofAuthorizer!==null}get node(){if(!this.nodeClient)throw $i("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof me))throw new Error("this client was constructed with the node transport and has no relay");return this.rpcTransport.client}get admin(){if(this.nodeClient)return this.nodeClient.admin;if(this.relayAdmin)return this.relayAdmin;throw new Error("this relay-transport client has no admin surface because it was given neither a `proof` nor a `session`. A warrant authorises one intent and is not a credential for reading. The caller-scoped reads (getContexts, listNamespaces) want one of the other two: pass `proof: { credential, deviceSecret }` \u2014 the device cert you already hold, which needs no login and no node key \u2014 or a `session` minted with `login()`. Context STATE reads work through execute/query either way.")}get auth(){return this.node.auth}get events(){if(this.nodeClient)return this.nodeClient.events;if(this.relayObserver)return this.relayObserver.events;if(this.proofAuthorizer&&this.relayUrl)return this.proofEvents??(this.proofEvents=new H({baseUrl:this.relayUrl,authorize:this.proofAuthorizer,fetch:this.relayFetch})),this.proofEvents;throw Ki("SSE events")}get ws(){if(this.nodeClient)return this.nodeClient.ws;if(this.relayObserver)return this.relayObserver.ws;throw this.proofAuthorizer?new Error("this client authenticates with a request proof, which cannot open a WebSocket from a browser: `WebSocket` cannot set the X-Calimero-Proof header, and core's guard reads the proof from a header only (the ?token= query parameter is the session equivalent and has no proof counterpart). Use `client.events` \u2014 SSE is fetch-based, carries the header, and is the recommended transport anyway."):Ki("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new lt({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw $i("bundled cloud client","a relay client is built from a cloud connection rather than owning one \u2014 reach it through the `cloud` field that `connectCloud` returns, or construct a `CloudClient` directly");return this.nodeClient.cloud}close(){this.nodeClient?.close(),this.relayObserver?.close(),this.proofEvents?.close()}};function pn(t){return new he(t)}var _r="calimero.delegated.connection",Gr="calimero.delegated.credential";function $r(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(_r);return t?JSON.parse(t):null}catch{return null}}function Hi(t){try{sessionStorage.setItem(_r,JSON.stringify(t))}catch{}}function qi(){try{sessionStorage.removeItem(_r)}catch{}}function Bi(){let t=$r();if(t){let{account:e,credential:n,deviceSecret:r}=t;return{account:e,credential:n,deviceSecret:r}}if(typeof sessionStorage>"u")return null;try{let e=sessionStorage.getItem(Gr);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function ji(t){try{sessionStorage.setItem(Gr,JSON.stringify(t))}catch{}}function Fi(){try{sessionStorage.removeItem(Gr)}catch{}}function Kr(t){let e=mn(t);return{next:async()=>{let n=0n;try{n=Vi(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function mn(t){return`calimero.nonce.${t}`}function Vi(t){let e=localStorage.getItem(mn(t));if(e!==null)return BigInt(e);let n=`${mn(t)}.`,r=0n;for(let o=0;o<localStorage.length;o++){let i=localStorage.key(o);if(!i?.startsWith(n))continue;let s=BigInt(localStorage.getItem(i)??"0");s>r&&(r=s)}return r}function fn(t,e,n){try{Vi(t)<=n&&localStorage.setItem(mn(t),String(n+1n))}catch{}}var Wi="calimero.delegated.relay-node-key.";function Y(t){return t.replace(/\/+$/,"")}function Lr(t,e){localStorage.setItem(Wi+Y(t),e.trim().toLowerCase())}function yn(t){try{let e=localStorage.getItem(Wi+Y(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function Hr(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var sl="locked-read-only",al="2.3.99",Ur;function cl(t){let e=t,n=typeof e.verify=="function"?e.verify:e.default?.verify;if(typeof n!="function")throw new TypeError("@phala/dcap-qvl loaded without a verify function");return n}var Ke=class extends Error{constructor(n,r){super(`${n}: ${r instanceof Error?r.message:String(r)}`);this.step=n;this.cause=r;this.name="RelayKeyTransportError"}};async function Li(t,e){try{return await e()}catch(n){throw n instanceof Ke?n:new Ke(t,n)}}function ll(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new Ke(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function Ji(t,e){return Object.assign(async r=>{let o=await Li("loading the quote verifier",()=>(Ur??(Ur=import("@phala/dcap-qvl").then(i=>cl(i),i=>{throw Ur=void 0,i})),Ur));return Ft({dcapVerify:o,release:()=>Li("fetching the release the relay runs",async()=>qt(jt(Ht,await Bt(t,{fetch:e})))),profile:sl,minReleaseVersion:al})(r)},{includeCollateral:!0})}async function Le(t,e={}){let n=e.fresh?null:yn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=ll(r);try{let i=Hr(t),{nodeKey:s}=await $t({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:Ji(t,o)}});return Lr(t,s),{kind:"learned",nodeKey:s}}catch(i){return i instanceof Ke||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function bn(t){let e=await Le(t);return e.kind==="learned"?e.nodeKey:(console.warn("[mero-js] could not learn the relay node key from its attestation",e.error),null)}var hn=[1e3,2e3,5e3,1e4,3e4];function ul(t,e){return new Promise(n=>{if(e?.aborted)return n();let r=setTimeout(o,t);function o(){clearTimeout(r),e?.removeEventListener("abort",o),n()}e?.addEventListener("abort",o)})}async function zi(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await Le(t);if(o.kind==="learned")return o.nodeKey;if(o.kind==="refused")return console.warn("[mero-js] refusing the relay's attestation; its node key stays unknown",o.error),null;let i=hn[Math.min(r,hn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await ul(i,n)}return null}function dl(t){try{let e=JSON.parse(atob(t.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));return typeof e.exp=="number"?e.exp*1e3:null}catch{return null}}var Mr=new Map;function Qi(){Mr.clear()}async function pl(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function gl(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function ml(t){let e=(o,i)=>globalThis.fetch(o,i),n=pe({baseUrl:t,verify:Ji(t,e),fetch:e}),r=!1;return async(o,i)=>{let s=new Request(o,i);if(r&&gl(s))return e(s);let a=await n(s.clone());return await pl(a)?(r||(r=!0,console.warn(`[mero-js] ${Y(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(s)):a}}function He(t){if(Hr(t))return;let e=Y(t),n=Mr.get(e);return n||(n=ml(t),Mr.set(e,n)),n}function hl(t,e){let n=null,r=null;return async()=>{let o=n?dl(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Me({nodeUrl:t.relayUrl,fetch:He(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:Ge()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var gn=new Map;function Yi(){gn.clear()}function fl(t){return typeof t=="object"&&t!==null&&t.status===409}function yl(t,e){let n=t.rpc,r=Y(e),o=async i=>{let s=`${r}|${i.contextId}|${i.method}`;if(gn.get(s)!=="write")try{let{returns:a}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return gn.set(s,"read"),{returns:a,transport:"relay"}}catch(a){fl(a)&&gn.set(s,"write")}return n.executeWithMetadata(i)};return{get kind(){return n.kind},get canSubscribe(){return n.canSubscribe},execute:async i=>(await o(i)).returns,executeWithMetadata:o,migrateMyEntries:i=>n.migrateMyEntries(i),countMyPending:i=>n.countMyPending(i)}}function bl(t){return new H({baseUrl:t,authorize:async()=>({}),fetch:(e,n)=>new Promise((r,o)=>{let i=()=>o(Object.assign(new Error("the stream was closed before the relay was attested"),{name:"AbortError"}));if(n?.signal?.aborted)return i();n?.signal?.addEventListener("abort",i,{once:!0})})})}function wl(t,e){let n=e.session?yl(t,e.relayUrl):null,r=null;return new Proxy(t,{get(o,i){if(i==="rpc"&&n)return n;if(!e.attested){if(i==="canSubscribe")return!1;if(i==="events")return r??(r=bl(e.relayUrl));if(i==="close")return()=>{r?.close(),o.close()}}let s=Reflect.get(o,i,o);return typeof s=="function"?s.bind(o):s}})}function wn(t,e){if(!t.relayUrl)return null;let n=yn(t.relayUrl),r=pn({transport:"relay",fetch:He(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:Kr(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?hl({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return wl(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||Hr(t.relayUrl)})}var Xi="calimero.delegated.relays.";function q(t){try{let e=localStorage.getItem(Xi+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function qr(t,e){try{localStorage.setItem(Xi+t,JSON.stringify(e))}catch{}}function fe(t,e,n){let r=q(t),o=Y(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),qr(t,r)}function Zi(t,e){return q(t).contexts[e]??null}function An(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||Y(t.relayUrl)!==Y(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function qe(t){let e=q(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(Y);return[...new Set(n)]}async function es(t){let e=[],n=q(t.account);for(let r of qe(t))try{if(!await bn(r))continue;let o=wn({...t,relayUrl:r},null);if(!o)continue;let{contexts:i}=await o.admin.getContexts();for(let s of i??[])e.push({...s,relayUrl:r}),n.contexts[s.id]=r}catch(o){console.warn(`[mero-js] could not list contexts on ${r}`,o)}return qr(t.account,n),e}async function ts(t){var o,i;let e=[],n=new Set,r=q(t.account);for(let s of qe(t))try{if(!await bn(s))continue;let a=wn({...t,relayUrl:s},null);if(!a)continue;for(let c of await a.admin.listNamespaces())n.has(c.namespaceId)||(n.add(c.namespaceId),e.push({...c,relayUrl:s}),(o=r.namespaces)[i=c.namespaceId]??(o[i]=s))}catch(a){console.warn(`[mero-js] could not list namespaces on ${s}`,a)}return qr(t.account,r),e}function Rn(t=1){let e=BigInt(t);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let n=e;return e+=1n,Promise.resolve(n)},advanceTo(n){return n>e&&(e=n),Promise.resolve()}}}function ut(t,e){let n=e??globalThis.localStorage;if(!n)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");let r=()=>{let o=n.getItem(t);if(o===null||o==="")return 0n;try{let i=BigInt(o);return i>0n?i:0n}catch{return 0n}};return{next(){let o=r()+1n;return n.setItem(t,o.toString()),Promise.resolve(o)},advanceTo(o){let i=o>0n?o-1n:0n;return i>r()&&n.setItem(t,i.toString()),Promise.resolve()}}}function Al(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var xn=class extends Error{constructor(n,r){super(`author device ${r} has spent every nonce in context ${n}; it must re-key to write again`);this.contextId=n;this.authorDeviceKey=r;this.name="WarrantNonceExhaustedError"}};function xl(t){let e=Array.isArray(t.lookups)?t.lookups:[t.lookups];if(e.length===0)throw new Error("a recovering nonce source needs at least one node to ask");let n=t.local??Rn(1),r=t.onLookupFailure??"throw",o=null,i=null,s=async()=>{let a=await Promise.allSettled(e.map(d=>d.getWarrantNonce(t.contextId,t.authorDeviceKey))),c=null,u=!1;for(let d of a){if(d.status!=="fulfilled")continue;let l=d.value;if(l.kind==="exhausted"){u=!0;continue}(c===null||l.nextNonce>c)&&(c=l.nextNonce)}if(c===null&&u)throw new xn(t.contextId,t.authorDeviceKey);if(c===null){let d=a.find(g=>g.status==="rejected"),l=d&&d.status==="rejected"?d.reason:void 0;if(r==="local"){o=0n;return}throw l instanceof Error?l:new Error(`no node could answer where the warrant-nonce sequence stands: ${String(l)}`)}o=c,await n.advanceTo?.(c)};return{async next(){o===null&&(i??(i=s().finally(()=>{i=null})),await i);let a=await n.next(),c=o!==null&&o>a?o:a;return o=c+1n,c},async advanceTo(a){(o===null||a>o)&&(o=a),await n.advanceTo?.(a)}}}async function ns(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await E(t.deviceSecret,t.signer,"deviceSecret"),n=new $({cloudBaseUrl:t.cloudBaseUrl,sessionToken:t.sessionToken,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs});!t.sessionToken&&t.googleIdToken&&await n.signInWithGoogle(t.googleIdToken);let r=await n.getMyNamespaces(),o=vl(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),s=Br(i);if(!s)throw new Error(Cl(o,i));let a=new W({relayUrl:s.relayUrl,executorAccount:s.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??Sl(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?pe({baseUrl:s.relayUrl,verify:t.seal,fetch:t.fetch}):t.fetch,timeoutMs:t.timeoutMs});return{cloud:n,relay:a,namespaceId:o.namespaceId,namespace:o,relayInfo:s,execute:(c,u,d)=>a.execute(c,u,d),client:new he({transport:"relay",relay:a,observe:{nodeKey:t.relayNodeKey??s.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function Rl(t){let{root:e,authorAccount:n,...r}=t,o=await E(r.deviceSecret,r.signer,"deviceSecret"),i=await z(e),a=await new $({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return ns({...r,deviceSecret:void 0,signer:o,sessionToken:a.sessionToken,authorAccount:n??i.accountId})}function vl(t,e){if(e){let n=t.find(r=>r.namespaceId===e);if(!n)throw new Error(`this account owns no namespace ${e}; it owns: ${t.map(r=>r.namespaceId).join(", ")||"(none)"}`);return n}if(t.length===0)throw new Error("this account owns no namespaces in the cloud: claim one first, then enable HA on it so a relay is assigned");if(t.length>1)throw new Error(`this account owns ${t.length} namespaces \u2014 pass namespaceId to say which: ${t.map(n=>n.namespaceId).join(", ")}`);return t[0]}function Cl(t,e){if(e.length===0)return t.haStatus==="enabled"?`namespace ${t.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${t.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let n=e.filter(o=>o.teeRole!==null&&o.teeRole!=="RelayTee");if(n.length===e.length)return`every node on namespace ${t.namespaceId} is a read-only TEE replica (ReadOnlyTee), which never relays delegated writes: an admin of the namespace must set its TEE admission policy with mode: 'relay' \u2014 AdminClient.setTeeAdmissionPolicy(namespaceId, { ..., mode: 'relay' }) \u2014 so fleet nodes are admitted as RelayTee`;let r=e.filter(o=>o.teeRole===null&&!o.authorshipReady);return r.length>0&&r.length+n.length===e.length?`every relay on namespace ${t.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${r.map(o=>o.executorAccount??o.peerId).join(", ")||"the relay account"} \u2014 with AdminClient.grantAuthorship(namespaceId, account) for these relays, and AdminClient.openToDelegatedExecution(namespaceId) so relays assigned later need no further op`:`namespace ${t.namespaceId} has ${e.length} relay(s), but none is ready to relay yet (a URL, an executor account and a recent heartbeat) \u2014 retry shortly`}function Sl(t){let e=`mero-js:warrant-nonce:${t}`;try{return ut(e)}catch{return Rn(1)}}var kl=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function rs(t,e){p(e,"deviceSecret",32);let n=await re(e),r=m(kl,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return El(o)}async function vn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await rs(t.nonce,e.deviceSecret)}}function El(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var os="calimero.cloud.link.pending",jr="link_state";var Fr=/^[0-9a-f]{64}$/;function is(t){try{let e=localStorage.getItem(os),n=e?JSON.parse(e):{};return Object.fromEntries(Object.entries(n).filter(([,r])=>r&&typeof r.expiresAt=="number"&&r.expiresAt>t))}catch{return{}}}function ss(t){try{localStorage.setItem(os,JSON.stringify(t))}catch{}}function Cn(t,e){if(!Fr.test(t))throw new Error("accountId must be 64 lowercase hex characters");let n=new URL(e),r=Date.now(),o=is(r),i=crypto.getRandomValues(new Uint8Array(16)),s=Array.from(i,a=>a.toString(16).padStart(2,"0")).join("");return o[s]={account:t,expiresAt:r+6e5},ss(Object.fromEntries(Object.entries(o).slice(-20))),n.searchParams.set(jr,s),n.toString()}function Be(t){let e=new URLSearchParams(t).get(jr),n=is(Date.now());if(!e||!Object.prototype.hasOwnProperty.call(n,e))return null;let r=n[e];return delete n[e],ss(n),r}function as(t){let e=new URLSearchParams(t);e.delete(jr);let n=e.toString();return n?`?${n}`:""}var Il="https://cloud.calimero.network";function cs(t){let e=new URL(t.cloudWebUrl??Il);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",Cn(t.accountId,t.returnTo)),e.toString()}function Pl(t){throw window.location.assign(cs(t)),new Error("redirecting to the cloud to authorise this link")}function Tl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Be(t.search??""),Vr(),new Error(n==="denied"?"the account link was declined at the cloud":`the cloud refused this link: ${n}`);let r=e.get("grant"),o=e.get("account");if(!r||!o)return null;if(Be(t.search??"")?.account!==o)throw Vr(),new Error("this account link answers a request this browser did not make - start the link again from here");return Vr(),{grant:r,account:o}}function Vr(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+as(location.search))}async function Dl(t){let e=await z(t.root);if(e.accountId!==t.account)throw new Error(`this grant is for account ${t.account}, but the root here derives ${e.accountId} \u2014 it was minted for a different account`);return new $({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,signer:e.signer})}var Nl="enrol-device",Ol="enrol-kem",Ul="callback-url",Ml="state";function ds(t){us(t.devicePublicKey,"devicePublicKey"),us(t.kemPublicKey,"kemPublicKey"),Ll(t.returnTo),Kl(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(Nl,t.devicePublicKey),e.searchParams.set(Ol,t.kemPublicKey),e.searchParams.set(Ul,t.returnTo),t.state&&e.searchParams.set(Ml,t.state),e.toString()}function _l(t){throw window.location.assign(ds(t)),new Error("redirecting to the wallet to approve this device")}function Gl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw ls(),new Error(n==="denied"||n==="cancelled"?"the device was not approved at the wallet":`the wallet refused this enrolment: ${n}`);let r=e.get("credential"),o=e.get("account"),i=e.get("device");if(!r||!o||!i)return null;ls();let s=e.get("state");return{credential:r,account:o,device:i,...s?{state:s}:{}}}function ls(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function $l(t){if(t.expectState!==void 0&&t.expectState!==t.state)throw new Error("this enrolment answers a request this app did not make \u2014 the state it carries is not the one sent");let e=await Nt(t.credential);if(e.signPublicKey!==ye(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${ye(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==ye(t.kemPublicKey))throw new Error(`this credential names delivery key ${e.kemPublicKey}, not the one this app asked about \u2014 group keys would be sealed to somebody else`);if(e.account!==ye(t.account))throw new Error(`the wallet reported account ${ye(t.account)}, but the credential names ${e.account}`);if(e.device!==ye(t.device))throw new Error(`the wallet reported device ${ye(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function us(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function ye(t){return t.trim().toLowerCase()}function ps(t,e){let n=e??(typeof window>"u"?void 0:window.location.origin);if(!n)return!1;try{return new URL(t).origin!==n}catch{return!1}}function Kl(t){ps(t)&&console.warn(`[calimero] enrolling a device but sending the credential to ${new URL(t).origin}, which is not this page's origin. Legitimate when deliberate; worth a second look otherwise.`)}function Ll(t){let e;try{e=new URL(t)}catch{throw new Error(`returnTo must be an absolute URL, got ${t}`)}let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new Error(`returnTo must be https:, or http: on localhost \u2014 got ${e.protocol}//${e.hostname}`)}function Sn(t){if(!t)return null;let e=t.trim().toLowerCase(),n=e.startsWith("0x")?e.slice(2):e;return n.length>0?n:null}function ql(t,e){if(e.size===0)return!0;let n=Sn(t.account);return n!==null&&e.has(n)}async function kn(t){let e=t.cloud??new $({cloudBaseUrl:t.cloudBaseUrl,routingCredential:{credential:t.credential,deviceSecret:t.deviceSecret}}),n,r;try{let l=await e.getNamespaceRouting(t.namespaceId);n=l.nodes,r=l.servable}catch(l){return{ok:!1,step:"admitters-lookup",reason:`The cloud could not be asked which nodes serve namespace ${t.namespaceId}: ${l instanceof Error?l.message:String(l)}. Nothing is known about the invitation yet \u2014 this is the lookup failing, not the invitation.`}}if(n.length===0)return{ok:!1,step:"no-nodes",reason:"The cloud lists no nodes serving this namespace, so there is no hosted node to be admitted through. The namespace has no fleet assignment \u2014 whoever invited you is running their own node, and admission has to go through a node the cloud routes to."};let o=new Set((t.admitters??[]).map(Sn).filter(l=>l!==null)),i=n.filter(l=>ql(l,o));if(i.length===0)return{ok:!1,step:"not-invited",reason:`${n.length} node${n.length===1?"":"s"} serve this namespace, but your invitation names none of them. The signed admitter list is a snapshot from when the invitation was minted, so a node assigned since is healthy and will still refuse the claim. Ask for a fresh invitation.`};let s=i.filter(l=>l.canAdmit),a=s.length>0?s:i,c=s.length===0||!r,u=a.filter(l=>typeof l.relayUrl=="string"&&l.relayUrl.length>0);if(u.length===0)return{ok:!1,step:"no-relay-url",reason:"A node your invitation names can admit you, but the cloud knows no address for it yet, so there would be nothing to connect through afterwards. Try again shortly."};let d=u.find(l=>l.canExecute)??u.find(l=>l.fresh)??u[0];return{ok:!0,relayUrl:d.relayUrl,admitUrl:d.admitUrl??`${d.relayUrl.replace(/\/+$/,"")}/admin-api/namespaces/${t.namespaceId}/admit`,admitterAccount:d.account,peerId:d.peerId,writable:d.canExecute,stale:!d.fresh||c}}var En=1440*60,Jr={Admin:0,Member:1,ReadOnly:2};function ht(t){let e=t.admitters??[];return m(Wr(t.inviter_identity,"inviter_identity"),Wr(t.group_id,"group_id"),C(t.expiration_timestamp),Wr(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>p(n,`admitters[${r}]`,32)))}async function zr(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",ht(t)))}function Qr(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function In(t){let e=await E(t.deviceSecret,t.signer,"deviceSecret"),n=p(e.publicKey,"signer.publicKey",32),r=p(t.groupId,"groupId",32);p(t.inviterAccount,"inviterAccount",32);let o=[...t.admitters??[]].map(g=>g.trim().toLowerCase());if(o.length===0){if(!t.members)throw new Error("name the admitters, or pass the group members to default them to its admins: an invitation with no admitters is claimable by broadcast");if(o=Qr(t.members),o.length===0)throw new Error("the member list names no admin, so there is nobody to default the admitters to")}o.forEach((g,A)=>p(g,`admitters[${A}]`,32));let i=t.invitedRole??Jr.Member;if(![0,1,2].includes(i))throw new Error(`invitedRole must be 0 (Admin), 1 (Member) or 2 (ReadOnly), got ${i}`);let s=t.now??Math.floor(Date.now()/1e3),a=Math.min(t.validForSecs??En,En);if(!Number.isInteger(a)||a<=0)throw new Error(`validForSecs must be a positive whole number, got ${t.validForSecs}`);let c=t.nonce??crypto.getRandomValues(new Uint8Array(32));if(c.length!==32)throw new Error(`nonce must be 32 bytes, got ${c.length}`);let u={inviter_identity:Array.from(n),group_id:Array.from(r),expiration_timestamp:s+a,secret_salt:Array.from(c),invited_role:i,admitters:o},d=await e.sign(await zr(u));if(d.length!==64)throw new Error(`signer returned ${d.length} bytes, expected a 64-byte Ed25519 signature`);let l={invitation:u,inviter_signature:f(d),inviter_account:t.inviterAccount.trim().toLowerCase()};return t.admitterAddrs?.length&&(l.admitter_addrs=[...t.admitterAddrs]),t.applicationId&&(l.application_id=Array.from(p(t.applicationId,"applicationId",32))),t.appKey&&(l.app_key=Array.from(p(t.appKey,"appKey",32))),l}function Wr(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var Yr=24,Bl=new TextEncoder().encode("calimero.namespace.v1"),jl=0,gs={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function ms(t,e){if(t==null)return new Uint8Array([0]);if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return m(new Uint8Array([1]),new Uint8Array(t))}function hs(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function Pn(t){let e=t.invitation,n=t.admitter_addrs??[];return m(ht(e),hs(t.inviter_signature),t.inviter_account?m(new Uint8Array([1]),p(t.inviter_account,"inviter_account",32)):new Uint8Array([0]),R(n.length),...n.map(hs),ms(t.application_id,"application_id"),ms(t.app_key,"app_key"))}async function Tn(t){let e=t.parentOpHashes??[],n=p(t.credential,"credential",t.credential.length/2),r=BigInt(t.invitation.invitation.expiration_timestamp??0)!==0n,o=t.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=r?m(new Uint8Array([gs.MemberJoinedAt]),p(t.member,"member",32),Pn(t.invitation),C(o),n):m(new Uint8Array([gs.MemberJoined]),p(t.member,"member",32),Pn(t.invitation),n),s=m(new Uint8Array([jl]),i),a=await E(t.deviceSecret,t.signer,"deviceSecret"),c=p(a.publicKey,"signer.publicKey",32),u=m(new Uint8Array([Yr]),p(t.namespaceId,"namespaceId",32),R(e.length),...e.map((g,A)=>p(g,`parentOpHashes[${A}]`,32)),c,C(t.nonce),s),d=await a.sign(m(Bl,u)),l=new Uint8Array([0]);return f(m(u,d,l))}function Fl(t,e){let n=e?`: ${e}`:"";switch(t){case 400:return`The node refused the join as malformed (400)${n}. The signature covers the invitation exactly as sent, so an edited or re-serialised invitation fails here \u2014 as does a namespace id that is not the invitation's own group.`;case 403:return`The node refused to carry this join (403)${n}. Either it is not in the invitation's signed admitters list \u2014 being live and listed by the cloud is not the same thing \u2014 or the invitation itself was rejected as expired or not the inviter\u2019s to issue.`;case 409:return`That node holds no device of its own, so it cannot endorse anyone (409)${n}. Another admitter from the same invitation would work.`;default:return`The join was not published (HTTP ${t})${n}.`}}function Vl(t){let e=ut(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function fs(t){return t.replace(/\/+$/,"")}async function Dn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await Tn({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Vl(e))()})}catch(l){return{ok:!1,step:"sign",reason:`The join op could not be signed, so nothing was sent: ${l instanceof Error?l.message:String(l)}`}}let i={invitation:t.invitation,signedOp:o},s=t.admitUrl??`${fs(t.nodeUrl)}/admin-api/namespaces/${t.namespaceId}/admit`,a=t.deps?.fetch??fetch,c;try{c=await a(s,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)})}catch(l){return{ok:!1,step:"admit",reason:`The admitter at ${t.nodeUrl} could not be reached: ${l instanceof Error?l.message:String(l)}. The invitation is untouched \u2014 this is the node being unreachable, not a refusal.`}}let u=await c.text();if(!c.ok)return{ok:!1,step:"admit",status:c.status,reason:Fl(c.status,u)};let d=!1;try{d=(u?JSON.parse(u):{}).data?.published===!0}catch{d=!1}return{ok:!0,published:d,session:{relayUrl:fs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Nn(t){let e=t.deps?.resolve??kn,n=t.deps?.join??Dn,r=null,o=t.nodeUrl,i;if(!o){let a=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,credential:t.credential.credential,deviceSecret:t.credential.deviceSecret,cloudBaseUrl:t.cloudBaseUrl});if(a.ok===!1)return a;r=a,o=a.relayUrl,i=a.admitUrl}let s=await n({nodeUrl:o,admitUrl:i,namespaceId:t.namespaceId,invitation:t.invitation,credential:t.credential,deps:{fetch:t.deps?.fetch,nonce:t.deps?.nonce}});return s.ok===!1?s:{ok:!0,published:s.published,relay:r,session:s.session}}async function ys(t,e,n,r){let i=await(r.bootstrap??Nn)({namespaceId:e,invitation:n,credential:{account:t.account,credential:t.credential,deviceSecret:t.deviceSecret},cloudBaseUrl:r.cloudBaseUrl});if(i.ok===!1)throw Object.assign(new Error(i.reason),{step:i.step,...i.status!==void 0?{status:i.status}:{}});return i.session.relayUrl&&fe(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(An(t,i.session)),{namespaceId:e}}function bs(t){let e=new TextEncoder().encode(t),n=new Uint8Array(4+e.length);return new DataView(n.buffer).setUint32(0,e.length,!0),n.set(e,4),n}async function Xr(t,e){let n=bs(t),r=bs(e),o=new Uint8Array(n.length+r.length);o.set(n,0),o.set(r,n.length);let i=await crypto.subtle.digest("SHA-256",o);return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}function Wl(t,e){let[n,r]=[t,e].map(o=>o.split(/[.-]/).map(i=>Number.parseInt(i,10)||0));for(let o=0;o<Math.max(n.length,r.length);o++)if((n[o]??0)!==(r[o]??0))return(n[o]??0)>(r[o]??0);return!1}function ft(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Wl(n.appVersion,e.appVersion)?n:e,void 0)}async function yt(t,e,n=globalThis.fetch){let r=`${t.replace(/\/+$/,"")}/api/v2/bundles?package=${encodeURIComponent(e)}`,o=await n(r,{headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`the registry has no ${e} (HTTP ${o.status})`);let i=await o.json();return Array.isArray(i)?i:[]}async function ws(t,e,n={}){let o=(await yt(t,e,n.fetch)).filter(c=>!c.yanked),i=[...new Set(o.map(c=>c.signerId).filter(c=>typeof c=="string"&&c.length>0))];if(i.length>1)throw new Error(`the registry lists ${e} under more than one publisher (${i.join(", ")}): refusing to guess which application it is`);let s=ft(o);if(!s)throw new Error(`the registry lists no version of ${e}`);let a=s.signerId;if(!a)throw new Error(`the registry names no publisher for ${e} ${s.appVersion}`);return{applicationId:await Xr(e,a),signerId:a,version:s.appVersion}}function xs(t,e){return{next:async()=>Jl(t,e)}}function Jl(t,e){let n=`calimero.governance-nonce.${t}.${e}`,r=0n;try{r=BigInt(localStorage.getItem(n)??"0")}catch{}let o=[r+1n,BigInt(Date.now())].reduce((i,s)=>i>s?i:s);try{localStorage.setItem(n,String(o))}catch{}return o}function Rs(t,e){let n=q(t.account).namespaces[e]??t.relayUrl;if(!n)throw new Error("no relay is known for this namespace, so there is nowhere to send this");return n.replace(/\/+$/,"")}function zl(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Un(t,e,n,r){return new W({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??He(e)})}async function bt(t,e,n={}){let r=Rs(t,e.namespaceId),o=0n,i=await Un(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:zl(e.initializationParams),name:e.name});return fn(r,i.contextId,o),fe(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function we(t,e,n={}){let r=Rs(t,e.namespaceId);return Un(t,r,xs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function vs(t,e,n={}){let{groupId:r}=await we(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Oe({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await we(t,{namespaceId:e.namespaceId,group:r,op:De(i,"Member")},n);let{contextId:o}=await bt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function Mn(t,e={},n={}){let o=qe(t).map(u=>u.replace(/\/+$/,""))[0];if(!o)throw new Error("no relay is known for this account, so there is nowhere to found a namespace");let i=await Ql(t,o,n.fetch),s=BigInt(Date.now()),a=await Un(t,o,{next:async()=>s++},n.fetch).foundNamespace({executor:i,...e.defaultCapabilities!==void 0?{defaultCapabilities:e.defaultCapabilities}:{},...e.application?{application:e.application}:{}});try{localStorage.setItem(`calimero.governance-nonce.${o}.${a.namespaceId}`,String(s))}catch{}if(fe(t.account,o,{namespaceId:a.namespaceId}),e.application&&a.applicationSet!==!0)throw new Error(`founded ${a.namespaceId} but could not give it its application: ${a.applicationError??"unknown reason"}`);let c=a.teeEnabled?await Xl(t,a.namespaceId,a.salt,o,n):{haEnabled:!1,haError:`the relay did not attest the founding, so no fleet node could be admitted for HA${a.teeError?`: ${a.teeError}`:""}`};return{namespaceId:a.namespaceId,teeEnabled:a.teeEnabled,...c}}async function Ql(t,e,n){let r=t.executorAccount&&t.relayUrl?.replace(/\/+$/,"")===e?t.executorAccount:null;if(r)return{executorAccount:r,executorKey:await As(e)};let o=Object.entries(q(t.account).namespaces).find(([,a])=>a.replace(/\/+$/,"")===e)?.[0];if(!o)throw new Error("the executor account of this relay is not known: join a namespace on it first, or connect with the relay's executor account (the cloud shows it beside the relay)");let i=await As(e),s=await Un(t,e,xs(e,o),n).describeGovernance(o);if(s.executorKey?.toLowerCase()!==i)throw new Error(`the relay's discovery names signing key ${s.executorKey}, not the relay's node key ${i}: refusing to found through it`);return{executorAccount:s.executorAccount,executorKey:i}}async function As(t){let e=await Le(t,{fresh:!0});if(e.kind==="learned")return e.nodeKey;throw new Error(e.kind==="unavailable"?"the relay's signing key could not be learned: its attestation did not answer, try again":"the relay's attestation was refused, so founding through it is not possible: it is not a signed locked-read-only release")}var _n="link this account to your cloud user in the wallet so the cloud can host this namespace on its fleet",On={account_not_linked:_n,account_linked_to_several_users:"this account is linked to more than one cloud user, so the cloud cannot tell whose plan hosts the namespace: unlink it from all but one in the wallet",ha_request_pending:"another namespace of this account is still waiting to be hosted; the cloud hosts one new namespace at a time without a cloud sign-in. Sign in to the cloud and turn off hosting for the waiting namespace, or wait until it is hosted",unknown_relay:"the cloud does not run the relay this namespace was founded on, so it cannot host it",relay_not_dialable:"the relay this namespace was founded on has not reported its address to the cloud yet; try enabling hosting again shortly"};function Yl(t){try{let e=JSON.parse(t.bodyText??""),n=e?.detail?.namespace_id??e?.namespace_id;return typeof n=="string"&&/^[0-9a-f]{64}$/i.test(n)?n.toLowerCase():null}catch{return null}}async function Xl(t,e,n,r,o){try{return await new $({cloudBaseUrl:o.cloudBaseUrl,fetch:o.fetch}).enableHaAsAccount({namespaceId:e,salt:n,accountId:t.account,credential:t.credential,deviceSecret:t.deviceSecret,relayUrl:r}),{haEnabled:!0}}catch(i){if(i instanceof be)return{haEnabled:!1,haError:_n};if(i instanceof J&&On[i.code]){let s=i.code==="ha_request_pending"?Yl(i):null,a=On[i.code];return{haEnabled:!1,haError:s?`${a} (waiting: ${s})`:a}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function je(t,e,n=globalThis.fetch){let r=ft(await yt(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var Cs="calimero.delegated.group-namespace.",Zr=new Map;function Ss(t){let e={};try{e=JSON.parse(localStorage.getItem(Cs+t)??"{}")}catch{}return{...e,...Zr.get(t)}}function wt(t,e,n){Zr.set(t,{...Zr.get(t),[e]:n});try{let r=Ss(t);r[e]=n,localStorage.setItem(Cs+t,JSON.stringify(r))}catch{}}function At(t,e){return q(t.account).namespaces[e]?e:Ss(t.account)[e]}function ks(t,e){let n=At(t,e);if(!n)throw new Error(`the namespace of group ${e} is not known to this account: it can manage only groups in namespaces it joined or subgroups it created`);return n}async function Gn(t,e,n){return we(t,{namespaceId:ks(t,e),group:e,op:n})}async function $n(t,e,n){let r=ks(t,e);return we(t,{namespaceId:r,group:r,op:n})}var Ae=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Fe=class extends Error{constructor(n){super(`${n} needs a relay, and this account has none yet: join from an invitation first`);this.method=n;this.name="NoRelayError"}},Ve=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the cloud lists no node holding the namespace, so an invitee with no node of their own has no relay to be admitted through.`:`nobody could claim an invitation to ${n}: the cloud routes to none of the relays or admins it would name as admitters`);this.namespaceId=n;this.reason=r;this.name="InvitationNotClaimableError"}},Es={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Zl=new Set(["upgradeGroup","retryGroupUpgrade","abortMigration","installApplication","installDevApplication","uninstallApplication","generateContextIdentity","deleteContext","leaveContext","createContextAlias","createApplicationAlias","createDeviceAlias","deleteContextAlias","deleteApplicationAlias","deleteDeviceAlias","lookupContextAlias","lookupApplicationAlias","lookupDeviceAlias","listContextAliases","listApplicationAliases","listDeviceAliases","deleteNamespace","createGroupInvitation","joinGroup","setTeeAdmissionPolicy","getTeeAdmissionPolicy","deleteBlob","listAccountDevices","revokeAccountDevice"]);function eu(t){if(!(t instanceof Error))return!1;let e=t.status;return(e===void 0||e===409)&&/signer [0-9a-f]+ is a direct member/i.test(t.message)}function Is(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??Gn,s=e.govern?.root??$n,a=e.createContext??bt,c=e.found??Mn,u=e.latestVersion??je,d=e.signInvitation??In,l=e.join,g=e.routing;async function A(h,y){if(!l)throw new Ae("joinNamespace without a join handler");return l(h,y.invitation)}let x=()=>{if(r===null)throw new Fe("this call");return r};async function w(h){if(At(n,h))return;let y=await x().getGroupInfo(h);wt(n.account,h,y.namespaceId??h)}let v=async(h,y,S)=>(await w(y),i(h,y,S)),I=async(h,y,S)=>(await w(y),s(h,y,S));async function P(h){try{return await I(n,h,ln({member:n.account,groupId:h,credential:n.credential})),!0}catch(y){if(eu(y))return!1;throw y}}async function B(h,y){let S=y??String(await x().getContextGroup(h)),{members:O}=await x().listGroupMembers(S);return O.some(L=>L.identity.toLowerCase()===n.account.toLowerCase())}let M={async listNamespacesForApplication(h){return(await x().listNamespaces()).filter(y=>y.targetApplicationId===h)},async getNodeIdentity(){return{accountId:n.account,deviceId:null,publicKey:"",deviceCertified:!0}},async createNamespace(h){if(!o.packageName)throw new Ae("createNamespace without a packageName");let y=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:O,haError:L}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:y}});return h.name&&await v(n,S,Ue({name:h.name})),{namespaceId:S,haEnabled:O,...L!==void 0?{haError:L}:{}}},async createGroupInNamespace(h,y={}){let{op:S}=await Oe({parentId:h,restricted:y.visibility==="restricted",admin:n.account}),{groupId:O}=await I(n,h,S);return wt(n.account,O,h),y.groupName&&await v(n,O,Ue({name:y.groupName})),{groupId:O}},async addGroupMembers(h,y){for(let S of y.members)await v(n,h,De(S.identity,S.role??"Member"))},async removeGroupMembers(h,y){for(let S of y.members)await v(n,h,Qt(S))},async setGroupMetadata(h,y){await v(n,h,Ue(y))},async setMemberMetadata(h,y,S){await v(n,h,an(y,S))},async setContextMetadata(h,y,S){await v(n,h,cn(y,S))},async setDefaultCapabilities(h,y){await v(n,h,Ne(y.defaultCapabilities))},async setSubgroupVisibility(h,y){await v(n,h,sn(y.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,y,S){await v(n,h,rn(y,S.capabilities))},async deleteGroup(h){return await I(n,h,en(h)),{isDeleted:!0}},async reparentGroup(h,y){return await I(n,h,Zt(h,y.newParentId)),{reparented:!0}},async leaveGroup(h){await v(n,h,ct(n.account))},async leaveNamespace(h){await v(n,h,ct(n.account))},async getContextIdentitiesOwned(h){return{identities:await B(h)?[n.account]:[]}},async joinContext(h){return await P(String(await x().getContextGroup(h))),{contextId:h,memberPublicKey:n.account}},async createContext(h){let S=(await x().getGroupInfo(h.groupId)).namespaceId??h.groupId,{contextId:O}=await a(n,{namespaceId:S,groupId:h.groupId,applicationId:h.applicationId,serviceName:h.serviceName,contextSeed:h.contextSeed,name:h.name,initializationParams:h.initializationParams});return{contextId:O,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:y},S]=await Promise.all([x().listGroupMembers(h),x().getGroupInfo(h)]),O=y.filter(Z=>Z.role==="RelayTee").map(Z=>Z.identity.toLowerCase());if(g){let Z=new Set(O.length>0?O:y.filter(te=>te.role==="Admin").map(te=>te.identity.toLowerCase())),ee=null;try{ee=(await g(h)).nodes}catch{}if(ee!==null){if(ee.length===0)throw new Ve(h,"not-hosted");if(!ee.some(te=>te.account!==null&&Z.has(te.account.toLowerCase())))throw new Ve(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...O.length>0?{admitters:O}:{},members:y,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:A,async updateMemberRole(h,y,S){await v(n,h,Yt(y,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await P(h)}},async detachContextFromGroup(h,y){await v(n,h,on(y))}};return r===null?new Proxy({},{get(h,y){if(typeof y=="string")return y==="getNodeIdentity"?M.getNodeIdentity:y==="joinNamespace"?A:y in Es?Es[y]:async()=>{throw new Fe(y)}}}):new Proxy(r,{get(h,y,S){return typeof y=="string"&&y in M?M[y]:typeof y=="string"&&Zl.has(y)?async()=>{throw new Ae(y)}:Reflect.get(h,y,S)}})}function Ps(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??je;async function i(a){let{apps:c}=await n.listApplications();if(c.some(l=>l.id===a))return;if(!r.packageName)throw new Error(`application ${a} is not installed on this node, and no packageName is set to install it`);let u=r.packageVersion??await o(r.registryUrl??"https://apps.calimero.network",r.packageName),{applicationId:d}=await n.installApplication({package:r.packageName,version:u});if(d!==a)throw new Error(`installed ${r.packageName}@${u} as ${d}, not ${a}`)}let s={async createNamespace(a){return await i(a.applicationId),n.createNamespace(a)}};return new Proxy(n,{get(a,c,u){return typeof c=="string"&&c in s?s[c]:Reflect.get(a,c,u)}})}var tu="https://manager.cloud.calimero.network";function eo(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function to(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function Br(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function nu(t){let e=t.join;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(typeof n.state!="string")return null;let r=Array.isArray(n.refusals)?n.refusals.filter(o=>!!o&&typeof o=="object").map(o=>({peer:String(o.peer??""),reason:String(o.reason??"")})):[];return{state:n.state,attempts:typeof n.attempts=="number"?n.attempts:0,refusals:r,error:typeof n.error=="string"?n.error:null,reportedAt:typeof n.reported_at=="string"?n.reported_at:null}}function ru(t){return typeof t=="string"&&Fr.test(t)?t:null}var J=class extends T{constructor(n,r,o,i,s,a){super(r,o,i,s,a);this.code=n;this.name="AccountHaRefusedError"}},be=class extends J{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};be.CODE="account_not_linked";var dt=class extends J{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};dt.CODE="account_linked_to_several_users";var pt=class extends J{constructor(){super(...arguments);this.name="HaRequestPendingError"}};pt.CODE="ha_request_pending";var gt=class extends J{constructor(){super(...arguments);this.name="UnknownRelayError"}};gt.CODE="unknown_relay";var mt=class extends J{constructor(){super(...arguments);this.name="RelayNotDialableError"}};mt.CODE="relay_not_dialable";var Ts={409:[be,dt,pt],422:[gt,mt]};function ou(t){if(t)try{let e=JSON.parse(t);if(typeof e?.error=="string")return e.error;if(typeof e?.detail=="string")return e.detail;let n=e?.detail?.error;if(typeof n=="string")return n}catch{}}var iu="x-mdma-session-refresh",su="x-mdma-session-expires",$=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||tu).replace(/\/+$/,""),this.onSession=e.onSession;let n=e.fetch;this.fetchImpl=n?(r,o)=>n(r,o):(r,o)=>globalThis.fetch(r,o),this.timeoutMs=e.timeoutMs??1e4,this.routingCredential=e.routingCredential,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let n=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(n)}async signInWithAccount(e){let{signer:n,publicKey:r}=await z(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await Mt({signer:n,nonce:o})})}async getAccountLoginChallenge(){let e=await this.request("GET","/api/auth/account/challenge",{anonymous:!0});return{nonce:e.nonce,expiresAtMs:e.expires_at_ms}}async submitAccountLogin(e){let n=await this.request("POST","/api/auth/account",{body:{root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature},anonymous:!0});return this.adoptSession(n)}async refreshSession(){let e=await this.request("POST","/api/auth/refresh");return this.adoptSession(e)}async signOut(){try{this.session&&await this.request("POST","/api/auth/logout",{parse:"none"})}finally{this.session=null,this.notifySession(null)}}async getMyNamespaces(){return(await this.request("GET","/api/cloud/me/namespaces")).map(n=>({namespaceId:String(n.namespace_id??n.group_id??""),groupId:String(n.group_id??n.namespace_id??""),haStatus:String(n.ha_status??"none"),haEnabledAt:n.ha_enabled_at??null,contexts:Array.isArray(n.contexts)?n.contexts:[],fleetReplicas:n.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/relays`)).relays??[]).map(r=>{let o=r.relay_url??null,i=r.executor_account??null,s=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),relayUrl:o,executorAccount:i,nodeKey:r.node_key??r.node_public_key??null,status:String(r.status??""),authorshipReady:s,teeRole:to(r),canExecute:eo(r,s&&o!==null&&i!==null),lastSeenAt:r.last_seen_at??null,confirmedAt:r.confirmed_at??null,admission:typeof r.admission=="string"?r.admission:null,admissionHint:typeof r.admission_hint=="string"?r.admission_hint:null,join:nu(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return Br(n)}async getNamespaceRouting(e){let n=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/admitters`,{anonymous:!0,headers:await this.routingProof(e)});return{namespaceId:String(n.namespace_id??e),nodes:(n.admitters??[]).map(r=>{let o=r.account??null,i=r.relay_url??null,s=r.fresh===!0,a=r.authorship_ready===!0;return{peerId:String(r.peer_id??""),account:o,relayUrl:i,admitUrl:r.admit_url??null,status:String(r.status??""),fresh:s,canAdmit:r.can_admit===!0,authorshipReady:a,teeRole:to(r),canExecute:eo(r,a&&i!==null&&o!==null&&s)}}),servable:n.servable===!0,writable:n.writable===!0}}async getRoutingChallenge(e){let n=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{namespaceId:String(n.namespace_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async routingProof(e){if(!this.routingCredential)return;let n=await this.getRoutingChallenge(e);return vn(n,this.routingCredential)}async getAccountRelaysChallenge(e){let n=await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/challenge`,{anonymous:!0});return{accountId:String(n.account_id??e),nonce:String(n.nonce??""),expiresAtMs:Number(n.expires_at_ms??0)}}async getAccountRelays(e){if(!this.routingCredential)throw new Error("getAccountRelays needs a routingCredential: construct the client with the device certificate and its signing secret, since this read is proven by the device, not by a session.");let n=await this.getAccountRelaysChallenge(e);return((await this.request("GET",`/api/cloud/accounts/${encodeURIComponent(e)}/relays`,{anonymous:!0,headers:await vn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:ru(o.executor_account),assigned:o.assigned===!0}))}async findAdmitter(e,n){let{nodes:r}=await this.getNamespaceRouting(e),o=n&&n.length>0?new Set(n.map(i=>i.toLowerCase())):null;return r.find(i=>i.canAdmit&&(o===null||i.account!==null&&o.has(i.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(n=>{let r=n.relay_url??null,o=n.executor_account??null,i=(Array.isArray(n.namespaces)?n.namespaces:[]).map(s=>{let a=s;return{namespaceId:String(a.namespace_id??""),status:String(a.status??""),authorshipReady:a.authorship_ready===!0,teeRole:to(a),fresh:a.fresh===!0,confirmedAt:a.confirmed_at??null,lastSeenAt:a.last_seen_at??null}});return{peerId:String(n.peer_id??""),relayUrl:r,executorAccount:o,canExecute:eo(n,r!==null&&o!==null&&i.some(s=>s.authorshipReady)),namespaces:i}})}async claimNamespace(e,n){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:n}})}async enableNamespaceHa(e,n={}){let r=n.admitterAddrs===void 0?{}:{admitter_addrs:[...n.admitterAddrs]};return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:r})}async enableFoundedNamespaceHa(e,n){return this.request("POST",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:{groups:[],ownership_proof:n}})}async enableHaAsAccount(e){let n=await Xn({namespaceId:e.namespaceId,accountId:e.accountId,salt:e.salt,credential:e.credential,deviceSecret:e.deviceSecret,signer:e.signer,ttlMs:e.ttlMs,relayUrl:e.relayUrl}),r=e.accountId.toLowerCase(),o=e.namespaceId.toLowerCase();try{return await this.request("POST",`/api/cloud/accounts/${encodeURIComponent(r)}/namespaces/${encodeURIComponent(o)}/enable-ha`,{body:{ownership_proof:n},anonymous:!0})}catch(i){if(i instanceof T&&Ts[i.status]){let s=ou(i.bodyText),a=Ts[i.status].find(c=>c.CODE===s);if(a&&s)throw new a(s,i.status,i.statusText,i.url,i.headers,i.bodyText)}throw i}}async disableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/disable-ha`,{body:{}})}async getMyNode(){return(await this.request("GET","/api/cloud/me/node")).node??null}enableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${n.toString()}`)}disableHA(e){let n=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&n.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${n.toString()}`)}async linkAccount(e){let{signer:n,publicKey:r,accountId:o}=await z(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await Ze({signer:n,nonce:i})})}async getAccountLinkChallenge(){let e=await this.request("GET","/api/cloud/me/accounts/challenge");return{nonce:e.nonce,expiresAtMs:e.expires_at_ms??null}}async submitAccountLink(e){let n=await this.request("POST","/api/cloud/me/accounts",{body:{account_id:e.accountId,root_public_key:e.rootPublicKey,nonce:e.nonce,signature:e.signature}});return{accountId:String(n.account_id??e.accountId),linkedAt:n.linked_at??null,alreadyLinked:n.already_linked===!0}}static accountLinkHandoff(e){let n=e.portalUrl.replace(/\/+$/,""),r=new URLSearchParams({"link-account":e.accountId,"callback-url":Cn(e.accountId,e.callbackUrl)});return{url:`${n}/?${r.toString()}`,accountId:e.accountId}}static readAccountLinkCallback(e){let n=e??(typeof window>"u"?"":window.location.href);if(!n)return{};let r,o;try{({hash:r,search:o}=new URL(n))}catch{return{}}let i=new URLSearchParams(r.replace(/^#/,"")),s=i.get("grant"),a=i.get("account"),c=i.get("error"),u={};return c&&Be(o),s&&Be(o)?.account!==a?{error:"unexpected_callback"}:(s&&(u.grant=s),a&&(u.accountId=a),c&&(u.error=c),u)}async linkAccountWithGrant(e){let{signer:n,publicKey:r,accountId:o}=await Ut(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await Ze({signer:n,nonce:e.grant})},anonymous:!0});return{accountId:String(i.account_id??o),linkedAt:i.linked_at??null,alreadyLinked:i.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(n=>({accountId:String(n.account_id??""),linkedAt:n.linked_at??null,hasRecoveryEnvelope:n.has_recovery_envelope===!0})),limit:e.limit??null}}adoptSession(e){return this.session={sessionToken:e.session_token,expiresAt:e.expires_at,user:e.user},this.notifySession(this.session),this.session}async notifySession(e){try{await this.onSession?.(e)}catch{}}async request(e,n,r={}){if(!r.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let o={...r.headers,Accept:"application/json"};r.body!==void 0&&(o["Content-Type"]="application/json"),!r.anonymous&&this.session&&(o.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,s=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:o,body:r.body===void 0?void 0:JSON.stringify(r.body),signal:i.signal})}catch(c){throw new T(0,c instanceof Error?c.name:"NetworkError",`${this.baseUrl}${n}`,new Headers,c instanceof Error?c.message:String(c))}finally{clearTimeout(s)}if(this.adoptRollingRefresh(a),!a.ok){let c=await a.text().catch(()=>{});throw new T(a.status,a.statusText,`${this.baseUrl}${n}`,a.headers,c)}if(!(r.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let n=e.headers.get(iu);if(!n||!this.session)return;let r=e.headers.get(su),o=Number(r);this.session={sessionToken:n,expiresAt:Number.isFinite(o)&&o>0?o:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};function Hl(t){let e=t&&typeof t=="object"?t.data??t:void 0;if(!e||typeof e!="object")return[];let n=e.localPeerId,r=e.externalAddrs;if(typeof n!="string"||!n||!Array.isArray(r))return[];let o=`/p2p/${n}`,i=[];for(let s of r){if(typeof s!="string")continue;let a=s.trim();if(!a.startsWith("/"))continue;let c=a.endsWith(o)?a:`${a}${o}`;i.includes(c)||i.push(c)}return i}function au(t){if(t)return typeof t=="function"?t:Et(t)}var cu="mero-js:token-refresh";function lu(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function no(t,e){try{let n=t.split(".");if(n.length===3){let r=n[1].replace(/-/g,"+").replace(/_/g,"/");for(;r.length%4;)r+="=";let o=JSON.parse(atob(r));if(typeof o.exp=="number")return o.exp*1e3}}catch{}return e}var $e=class{constructor(e){this.tokenData=null;this.refreshPromise=null;this.storeHoldsTokens=!1;this.tokenGeneration=0;this.onStorage=()=>{this.signedOutElsewhere()&&this.dropLocalTokens()};this.rpcClient=null;this.sseClient=null;this.wsClient=null;this.wsWarned=!1;this.config={timeoutMs:1e4,...e},this.tokenStore=e.tokenStore??null,this.tokenStore&&(this.tokenData=this.tokenStore.getTokens(),this.storeHoldsTokens=this.tokenData!==null,typeof window<"u"&&window.addEventListener("storage",this.onStorage));let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=au(this.config.requestProof);this.httpClient=Re({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getProof:r,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async o=>{this.tokenData&&(this.tokenData.access_token=o,this.persistTokens(this.tokenData))},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(n?"omit":void 0)}),this.authClient=lo(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=Ct(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs})}get auth(){return this.authClient}get admin(){return this.adminClient}get rpc(){return this.rpcClient||(this.rpcClient=new Ye({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new H({baseUrl:this.config.baseUrl,fetch:this.config.fetch,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new Xe({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new $(this.config.cloud??{})),this.cloudClient}get ws(){return this.wsWarned||(this.wsWarned=!0,console.warn("[mero-js] WsClient is experimental. Use mero.events (SSE) for production.")),this.wsClient||(this.wsClient=new ie({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let n=e||this.config.credentials;if(!n)throw new Error("No credentials provided for authentication");try{let r={auth_method:"user_password",public_key:n.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:n.username,password:n.password}},o=await this.authClient.generateTokens(r),i=o.data.access_token;return this.tokenData={access_token:i,refresh_token:o.data.refresh_token,expires_at:no(i,Date.now()+36e5)},this.persistTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}persistTokens(e){this.tokenStore&&(this.tokenStore.setTokens(e),this.storeHoldsTokens=this.tokenStore.getTokens()!==null)}signedOutElsewhere(){return this.storeHoldsTokens&&!this.tokenStore?.getTokens()}dropLocalTokens(){this.tokenGeneration++,this.refreshPromise=null,this.tokenData=null,this.storeHoldsTokens=!1}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,n=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=n;try{return await n}finally{this.refreshPromise===n&&(this.refreshPromise=null)}}withRefreshLock(e){if(this.tokenStore?.withLock)return this.tokenStore.withLock(e);let n=lu();return n?n.request(cu,e):e()}async performTokenRefreshLocked(e){if(this.signedOutElsewhere())throw this.dropLocalTokens(),new Error("Signed out in another tab");let n=this.tokenStore?.getTokens()??null;if(n?.refresh_token&&(this.storeHoldsTokens=!0,this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");let r=this.tokenGeneration,o=this.tokenData.access_token,i=this.tokenStore?.getTokens()?.access_token===o;try{let s=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token});if(r!==this.tokenGeneration)throw new Error("Signed out during token refresh");if(i&&this.tokenStore?.getTokens()?.access_token!==o)throw this.tokenData=this.tokenStore?.getTokens()??null,this.storeHoldsTokens=this.tokenData!==null,new Error("Signed out during token refresh");let a=s.data.access_token;return this.tokenData={access_token:a,refresh_token:s.data.refresh_token,expires_at:no(a,Date.now()+36e5)},this.persistTokens(this.tokenData),this.tokenData}catch(s){throw new Error(`Token refresh failed: ${s instanceof Error?s.message:"Unknown error"}`)}}clearToken(){this.dropLocalTokens(),this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||no(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.persistTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){typeof window<"u"&&window.removeEventListener("storage",this.onStorage),this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return Wn(e)}static buildAuthLoginUrl(e,n){return Jn(e,n)}};function uu(t){return new $e(t)}var ro=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},du="mero-tokens",oo=class{constructor(e=du){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let n=JSON.parse(e);return n&&n.access_token&&n.refresh_token?{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:typeof n.expires_at=="number"?n.expires_at:Date.now()+36e5}:null}catch{return null}}setTokens(e){try{if(typeof localStorage>"u")return;localStorage.setItem(this.key,JSON.stringify(e))}catch{}}clear(){try{if(typeof localStorage>"u")return;localStorage.removeItem(this.key)}catch{}}};var pu=new TextEncoder().encode("calimero.account.owner-op.v1"),gu=new TextEncoder().encode("calimero.account.owner-op.body.v1"),mu=new TextEncoder().encode("calimero.account.genesis.v1"),hu=2,io={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},We={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},Ns={AdminChanged:3,RootGuarded:12},fu={replica:0,relay:1},yu=new TextEncoder;function K(t){return new Uint8Array([t])}function Os(t){let e=yu.encode(t);return m(R(e.length),e)}function X(t){return m(R(t.length),...t.map(Os))}function Us(t){return K(t?1:0)}function Ms(t){let e=fu[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return K(e)}function _s(t){return{kind:"transferOwnership",plane:"group",bytes:m(K(We.TransferOwnership),p(t,"newOwner",32))}}function Gs(){return{kind:"groupDelete",plane:"group",bytes:K(We.GroupDelete)}}function $s(t){return{kind:"adminChanged",plane:"root",bytes:m(K(Ns.AdminChanged),p(t,"newAdmin",32))}}function Ks(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:m(K(We.TeeAuthoringPolicySet),X(t))}}function Ls(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:m(K(We.TeeAdmissionPolicySetV2),X(t.allowedMrtd),X(t.allowedRtmr0),X(t.allowedRtmr1),X(t.allowedRtmr2),X(t.allowedRtmr3),X(t.allowedTcbStatuses),Us(t.acceptMock),Ms(t.mode))}}function Hs(t){let e=t.minReleaseVersion===void 0?K(0):m(K(1),Os(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:m(K(We.TeeReleaseAdmissionPolicySetV2),X(t.allowedProfiles),e,X(t.allowedTcbStatuses),Us(t.acceptMock),Ms(t.mode))}}async function so(t){return k(gu,[t])}async function ao(t){return k(pu,[p(t.account,"account",32),p(t.namespaceId,"namespaceId",32),p(t.groupId,"groupId",32),K(qs(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function qs(t){let e=io[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var Ds=132;async function Bs(t){let e=await oe(t.rootSecret),n=m(K(hu),e),r=f(await k(mu,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let g=j(d,`chain[${l}]`);if(g.length!==Ds)throw new Error(`chain[${l}] must be a ${Ds}-byte RootKeyHandoff, got ${g.length}`);return g});if(o>i.length)throw new Error(`keyEpoch ${o} needs ${o} handoffs in chain, got ${i.length}`);let s=await so(t.op.bytes),a=await ao({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:s,counter:t.counter,keyEpoch:o}),c=await re(t.rootSecret),u=new Uint8Array(await crypto.subtle.sign("Ed25519",c,a));return f(m(n,R(i.length),...i,p(r,"account",32),p(t.namespaceId,"namespaceId",32),p(t.groupId,"groupId",32),K(qs(t.op.kind)),s,C(t.counter),R(o),u))}function js(t,e){let n=t.plane==="group"?We.RootGuarded:Ns.RootGuarded;return m(K(n),t.bytes,j(e,"rootProof"))}var Fs=[2428,2429,2528,2529],bu="localhost",wu=2e3;function Vs(t){return`http://${bu}:${t}`}function Ws(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function Js(t,e={}){let{timeoutMs:n=wu,signal:r}=e;if(r?.aborted)return!1;let o=new AbortController,i=()=>o.abort(),s=r;s&&s.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>o.abort(),n);try{let c=Ws(t,"admin-api/health"),u=await fetch(c,{method:"GET",signal:o.signal});if(!u.ok)return!1;try{let d=await u.json(),l=d?.data?.status!==void 0?d?.data?.status:d?.status;return l===void 0?!0:typeof l=="string"&&l.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),s&&s.removeEventListener("abort",i)}}async function Au(t={}){let{ports:e=Fs,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let s=Vs(i);return await Js(s,{timeoutMs:n,signal:r})?s:null}))).filter(i=>i!==null)}export{Io as ACCOUNT_HA_AUDIENCE,Eo as ACCOUNT_OWNERSHIP_AUDIENCE,J as AccountHaRefusedError,dt as AccountLinkedToSeveralUsersError,be as AccountNotLinkedError,de as AdminApiClient,le as AuthApiClient,ne as AuthRevokedError,U as CAPABILITIES,Lu as CAPABILITY_PRESETS,$ as CloudClient,Fs as DEFAULT_LOCAL_NODE_PORTS,Ht as DEFAULT_RELEASE_MIRROR,Xe as EphemeralClient,ei as HANDSHAKE_PATH,_n as HA_ACCOUNT_NOT_LINKED_MESSAGE,On as HA_REFUSAL_MESSAGES,T as HTTPError,pt as HaRequestPendingError,Jr as INVITED_ROLE,ge as IntentRefusedError,Ve as InvitationNotClaimableError,oo as LocalStorageTokenStore,En as MAX_INVITATION_VALIDITY_SECS,ro as MemoryTokenStore,he as MeroClient,$e as MeroJs,yr as NODE_RELEASE_SIGNER,Fe as NoRelayError,Ae as NotForAccountError,io as OWNER_OP_KIND,_i as PRESENCE_DOMAIN,dr as PRODUCTION_PROFILE,hn as RELAY_NODE_KEY_RETRY_MS,Tr as REQUEST_PROOF_HEADER,W as RelayClient,mt as RelayNotDialableError,_e as RelayObserver,lt as RelayPresenceClient,me as RelayTransport,Ye as RpcClient,It as RpcError,tt as SEALED_CONTENT_TYPE,ti as SEALED_PATH,Yr as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,ke as SealedTransportError,H as SseClient,nt as StaleTransportKeyError,gt as UnknownRelayError,xn as WarrantNonceExhaustedError,vt as WarrantNonceRouteUnavailableError,Je as WebHttpClient,ie as WsClient,Ot as accountForRoot,F as accountForRootPublicKey,Mo as accountRootFromPhrase,or as accountRootFromSecret,Go as accountRootSignerFromPhrase,$s as adminChangedOp,Hl as admitterAddrsFromNetworkStatus,Xr as applicationIdForBundle,Le as attemptRelayNodeKey,Gt as attestKeyBinding,$t as attestRelayNodeKey,Al as authorNonceLookup,Pl as beginCloudLink,_l as beginDeviceEnrolment,Nn as bootstrapFromInvitation,Jn as buildAuthLoginUrl,wn as buildDelegatedClient,ps as callbackIsForeign,kt as callerProof,Hu as capMask,qu as capNames,An as carryExecutorAccount,Fn as classifyError,Fi as clearDelegatedCredential,qi as clearDelegatedSession,cs as cloudLinkUrl,jt as cloudNodeReleaseUrl,Ln as combineSignals,aa as compareSemver,Dl as completeCloudLink,$l as completeDeviceEnrolment,ns as connectCloud,Rl as connectCloudWithAccount,Ni as contextCapabilityGrantedOp,Oi as contextCapabilityRevokedOp,on as contextDetachedOp,cn as contextMetadataSetOp,Is as createAccountAdmin,_o as createAccountRootSigner,ho as createAdminApiClient,Ct as createAdminApiClientFromHttpClient,pe as createAttestedSealedFetch,$u as createAuthApiClient,lo as createAuthApiClientFromHttpClient,id as createBrowserAdminApiClient,_u as createBrowserAuthApiClient,Re as createBrowserHttpClient,bt as createDelegatedContext,vs as createDelegatedPrivateContext,ze as createHttpClient,ut as createLocalStorageNonceSource,Rn as createMemoryNonceSource,pn as createMeroClient,uu as createMeroJs,Ps as createNodeAdmin,sd as createNodeAdminApiClient,Gu as createNodeAuthApiClient,xt as createNodeHttpClient,Nr as createProofAuthorizer,Et as createProofSigner,pr as createQuoteVerifier,xl as createRecoveringNonceSource,ea as createRetryableMethod,ii as createSealedFetch,Ec as createSignedReleaseSealedFetch,Ft as createSignedReleaseVerifier,Hn as createTimeoutSignal,qn as createUniversalHttpClient,Sr as createdSubgroupId,Ar as creationInitHash,Qr as defaultAdmitters,Ge as defaultAudience,Ne as defaultCapabilitiesSetOp,we as delegatedGovernance,Dt as deviceCertPayload,ds as deviceEnrolmentUrl,tr as deviceScopePayload,Au as discoverLocalNodes,ht as encodeGroupInvitation,Pn as encodeSignedInvitation,oi as fetchAttestedTransportKey,qt as fetchNodeRelease,Bt as fetchNodeReleaseVersion,yt as fetchRegistryBundles,Yi as forgetMethodKinds,Qi as forgetRelaySealing,Mn as foundDelegatedNamespace,tn as foundedNamespaceId,Uo as generateAccountRoot,Pr as generateSessionKey,Gn as governGroup,$n as governRoot,xr as governanceOpHash,kr as groupCreatedOp,Gs as groupDeleteOp,en as groupDeletedOp,zr as groupInvitationHash,Ue as groupMetadataSetOp,Zt as groupReparentedOp,ue as hasCap,ed as hexEncodeUtf8,br as intentHash,oa as isSettled,ys as joinAsAccount,Dn as joinWithNode,se as jsonCodec,qe as knownRelays,je as latestPublishedVersion,zi as learnRelayNodeKey,es as listDelegatedContexts,ts as listDelegatedNamespaces,Vs as localNodeUrl,Me as login,fn as markContextNonceSpent,De as memberAddedOp,rn as memberCapabilitySetOp,ln as memberJoinedOpenOp,ct as memberLeftOp,an as memberMetadataSetOp,Qt as memberRemovedOp,Yt as memberRoleSetOp,Zn as mintDeviceId,nn as namespaceCreatedOp,At as namespaceOfGroup,Ws as nodeEndpoint,bi as nodeReleaseVersionFromImage,Sn as normaliseAccount,so as ownerOpDigest,ao as ownerOpSigningPayload,Wn as parseAuthCallback,Ei as parseCreationWarrant,er as parseDeviceCredential,Ii as parseGovernanceWarrant,po as parseWarrantNonce,Kr as persistedNonces,Lr as pinRelayNodeKey,Or as presenceStatementBytes,Js as probeNodeHealth,Tl as readCloudLinkCallback,Bi as readDelegatedCredential,$r as readDelegatedSession,Gl as readEnrolmentCallback,yn as readPinnedRelayNodeKey,q as readRelayMap,uo as redeemInvitation,Zi as relayForContext,He as relayTransportFetch,wt as rememberGroupNamespace,fe as rememberRelay,sr as reportDataOf,zn as requestBodyHash,ws as resolveApplicationIdFromRegistry,kn as resolveRelayFromInvitation,bn as resolveRelayNodeKey,z as resolveRoot,Ut as resolveRootPair,js as rootGuardedOpBytes,vn as routingProofHeaders,ji as saveDelegatedCredential,Hi as saveDelegatedSession,ft as selectLatestBundle,Wu as shouldRetain,Xn as signAccountHaClaim,Ze as signAccountLink,Mt as signAccountLogin,wa as signAccountOwnershipClaim,Jt as signCreationWarrant,Do as signDeviceCert,No as signDeviceScope,st as signGovernanceWarrant,In as signGroupInvitation,dn as signLoginStatement,Tn as signMemberJoinOp,Bs as signOwnerOpProof,St as signRequest,Dr as signRequestProof,rs as signRoutingChallenge,Vt as signWarrant,rl as signedPath,Ro as signerFromCryptoKey,ve as signerFromSecret,Gi as stateHash,Oe as subgroupCreation,sn as subgroupVisibilitySetOp,Tt as subscribePresence,Xt as targetApplicationSetOp,Ls as teeAdmissionPolicyOp,Ks as teeAuthoringPolicyOp,Hs as teeReleaseAdmissionPolicyOp,_s as transferOwnershipOp,ri as transportKeyBinding,xi as trustSignedRelease,gr as trustedMeasurementsFromReleases,Nt as verifyDeviceCredential,yi as verifySignedNodeRelease,Bn as withCap,Rt as withRetry,Bu as withoutCap};
3
3
  //# sourceMappingURL=index.browser.mjs.map