@calimero-network/mero-js 24.5.0 → 24.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/create-context.js +17 -6
- package/dist/account/index.d.ts +1 -1
- package/dist/account/index.js +1 -1
- package/dist/account/session.d.ts +23 -1
- package/dist/account/session.js +96 -12
- package/dist/admin-api/admin-types.d.ts +2 -0
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +3 -3
- package/dist/index.cjs +78 -13
- package/dist/index.cjs.map +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +78 -13
- package/dist/index.mjs.map +3 -3
- package/dist/mero-js.d.ts +4 -1
- package/dist/mero-js.js +6 -1
- package/dist/token-store/index.d.ts +8 -0
- package/dist/transport/mero-client.d.ts +9 -0
- package/dist/transport/mero-client.js +13 -5
- package/package.json +1 -1
package/dist/index.browser.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function Gn(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 $n(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 _s=new Set(["token_reuse","token_revoked"]);function Gs(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=Gs(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:Zr(this.headers),bodyText:this.bodyText}}},ee=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 Zr(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function $s(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:Zr(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((A,v)=>{d[v]=A})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let A=n?.body;if(A!==void 0&&typeof A!="string"&&!(A 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:A}))}let g={method:l,headers:d},w=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!w||n?.body!==void 0&&w&&r===0)&&(g.body=n.body);let x;if(r>0&&o!==void 0){let A=n?.timeoutMs||this.transport.timeoutMs;if(A){let v=Date.now()-s,I=Math.max(0,A-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 A=await this.transport.getProof({method:g.method??"GET",path:$s(a),body:g.body});A&&(d["X-Calimero-Proof"]=A)}try{let A=await this.transport.fetch(a,g);if(!A.ok){let v=await this.getBodyText(A),I=new T(A.status,A.statusText,a,A.headers,v),P=A.headers.get("x-auth-error");if((A.status===401||A.status===403)&&P&&_s.has(P)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new ee(P,A.status,A.statusText,a,A.headers,v)}let j=n?.signal?.aborted===!0;if(A.status===401&&this.transport.refreshToken&&P==="token_expired"&&r<1&&!w&&!j)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 N=Date.now()-s;if(S-N<=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(A,n?.parse)}catch(A){throw A instanceof T||A instanceof Error&&A.message.includes("onTokenRefresh")?A:new T(0,"Network Error",a,new Headers,A instanceof Error?A.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($n(r)),n.length>0?Gn(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 Fe(t){return new je(t)}function Ae(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 Fe(e)}function wt(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 Fe(r)}function Kn(t){return typeof window<"u"?Ae(t):wt(t)}function Ks(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 Hs(t){let n=250*Math.pow(2,t-1),r=(Math.random()-.5)*.4*n;return Math.max(0,n+r)}async function At(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,!Ks(r,n-o))throw r;let a=Hs(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 Ls(t,e={}){return async(...n)=>At(()=>t(...n),e)}var ae=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 Ve=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 vu(t){let e=new Ve;return new ae(e)}function Cu(t){let e=new Ve;return new ae(e)}function Su(t){let e=new Ve;return new ae(e)}function eo(t,e){return new ae(t)}var O={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},ku={NONE:0,JOIN_ONLY:O.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:O.CAN_CREATE_CONTEXT|O.CAN_INVITE_MEMBERS|O.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:O.CAN_CREATE_CONTEXT|O.CAN_INVITE_MEMBERS|O.CAN_JOIN_OPEN_SUBGROUPS|O.CAN_CREATE_SUBGROUP|O.CAN_DELETE_SUBGROUP|O.CAN_MANAGE_VISIBILITY};function Iu(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(O,n))e|=O[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function Pu(t){return Object.keys(O).filter(e=>ce(t,O[e]))}function ce(t,e){let n=e>>>0;return(t&n)>>>0===n}function Hn(t,e){return(t|e)>>>0}function Tu(t,e){return(t&~e)>>>0}var qs={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 Bs(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 js(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 Ln(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 qn(t){let e=js(t),n;return e!==void 0?n=Bs(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:qs[n],message:Ln(t)}}function Fs(t){return t.status!=="failed"||!t.retryable}function Ou(t){return!Fs(t)}function Vs(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 Ws(t,e){let{kind:n,status:r}=qn(t),o=Vs(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 to(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=Ln(i,"Could not join. Check the invitation."),{reason:c,retryable:u}=Ws(i,s);return{status:"failed",namespaceId:n,message:s,reason:c,retryable:u}}var xt=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 Bn(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 no(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:Bn(t,n,"highWaterNonce"),windowWidth:Bn(t,n,"windowWidth")??0n},o=Bn(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 Js(t,e){let[n,r]=ro(t),[o,i]=ro(e),a=n.split("."),s=o.split("."),c=Math.max(a.length,s.length);for(let g=0;g<c;g++){let w=oo(a[g]??"0",s[g]??"0");if(w!==0)return w}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 w=oo(u[g],d[g]);if(w!==0)return w}return 0}function ro(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 oo(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 zs(t,e,n){return At(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 le=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 zs(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(a=>a.appVersion).filter(a=>typeof a=="string").sort((a,s)=>Js(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 to({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 xt(r,i):i}return no(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 xt(r,i):i}return no(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(ce(n,O.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=Hn(n,O.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(ce(r,O.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=Hn(r,O.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 Lu(t){return Array.from(new TextEncoder().encode(t),e=>e.toString(16).padStart(2,"0")).join("")}function Vu(t){return new le(Ae(t))}function Wu(t){return new le(wt(t))}function io(t){return new le(Kn(t))}function Rt(t,e){return new le(t)}function jn(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 Fn(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 so=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 F(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 E(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 te(t){let e=p(t,"deviceSecret",32),n=m(so,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 ao(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 ne(t){let e=p(t,"deviceSecret",32),n=m(so,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 Qs=new TextEncoder().encode("calimero.auth.request.v1"),Ys=new TextEncoder().encode("calimero.auth.request.body.v1");function co(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}async function Vn(t=new Uint8Array(0)){let e=typeof t=="string"?new TextEncoder().encode(t):t;return E(Ys,[e])}async function vt(t){let e=await te(t.signerSecret),n=await Vn(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,a=await E(Qs,[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(co(t.method),co(t.path),n,r,o,s))}function Ct(t){let e=F(t.credential,"credential"),n=F(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):m(new Uint8Array([1]),F(t.session,"session statement"));return f(m(e,r,n))}function Xs(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 St(t){let e=t.ttlSeconds??120,n=t.now??(()=>Math.floor(Date.now()/1e3));return async r=>{let o=n();return Ct({credential:t.credential,session:t.session,request:await vt({method:r.method,path:r.path,body:Xs(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 Wn(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 We=class{constructor(e){this.kind="node";this.canSubscribe=!0;this.httpClient=e.httpClient}async execute(e){let n=await Wn(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 Zs=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function lo(t){return t.type!==void 0&&Zs.has(t.type)}var ea=new Set(["token_reuse","token_revoked"]),ta=new Set([401,403]),na=1e4;function uo(t){let e=t.headers.get("x-auth-error");return!e||!ta.has(t.status)?null:ea.has(e)?e:null}var q=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=>{lo(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=uo(n),o=await n.text().catch(()=>{});throw r?new ee(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 ee)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")),na);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=uo(c),d=await c.text().catch(()=>{});return u?new ee(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 kt=class kt{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),kt.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()}};kt.MAX_BACKOFF_MS=3e4;var re=kt;function oe(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var Je=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=oe()){await Wn(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=oe()){return It(this.sse,e,n,r)}};function It(t,e,n,r=oe()){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 ra=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function po(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 xe(t,e="secret"){let n=p(t,e,32),r=m(ra,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 po(a)}return mo(o,i)}async function go(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 mo(t,n)}function mo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw po(r)}}}}async function k(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 xe(t,n);throw new Error(`${n} or signer is required`)}var oa=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),ia=6e4,ho=5*6e4,fo=1024,bo="mdma:enable-ha-namespace",wo="mdma:enable-ha-namespace-as-account";function yo(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var Jn=(t,e)=>{if(!/^[0-9a-fA-F]{64}$/.test(t))throw new Error(`${e} must be 64 hex characters`);return t.toLowerCase()};async function Ao(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=fo))throw new Error(`relayUrl must be a non-empty string of at most ${fo} characters`);let o=t.ttlMs??ia;if(!(o>0&&o<=ho))throw new Error(`ttlMs must be in (0, ${ho}]`);let i=Jn(t.namespaceId,"namespaceId"),a=Jn(t.accountId,"accountId"),s=Jn(t.salt,"salt"),c=await k(t.deviceSecret,t.signer,"deviceSecret"),u=(t.now??Date.now)(),d=Array.from(crypto.getRandomValues(new Uint8Array(16)),w=>w.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(oa,l));return{kind:"account",credential:t.credential,signed_payload:yo(l),signature:yo(g)}}async function sa(t){if(!t.subject)throw new Error("subject must be the cloud login email");return Ao(t,bo,t.subject)}async function zn(t){return Ao(t,wo,void 0,t.relayUrl)}var aa=new TextEncoder().encode("calimero.device.cert.v1"),ca=new TextEncoder().encode("calimero.account.genesis.v1"),la=new TextEncoder().encode("calimero.device.id.v1"),Re=2,ua=237;async function Qn(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 E(la,[n,e]);return f(m(e,r.subarray(0,16)))}async function Pt(t){return E(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 xo(t){return m(new Uint8Array([Re]),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 Ro(t){let e=await k(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await V(e.publicKey),o=0,i=await Pt({account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch}),a=await e.sign(i),s=xo({rootPublicKey:n,account:r,device:t.device,signPublicKey:t.signPublicKey,kemPublicKey:t.kemPublicKey,keyEpoch:o,deviceEpoch:t.deviceEpoch,signature:a});return f(s)}function Yn(t){let e=p(t,"credential",ua);if(e[0]!==Re)throw new Error(`this credential has account genesis version ${e[0]}, not ${Re} \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 Tt(t){let e=Yn(t),n=await V(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 Qn(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 ao(e.rootPublicKey,p(e.signature,"signature",64),await Pt(e)))throw new Error(`the root key of account ${e.account} did not sign this certificate`);return e}async function Dt(t){return V(f(await ne(t)))}async function V(t){return f(await E(ca,[m(new Uint8Array([Re]),p(t,"rootPublicKey",32))]))}var da=new TextEncoder().encode("calimero.device.scope.v1");async function Xn(t){return E(da,[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 vo(t){let e=await k(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await V(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 Xn({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([Re]),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 Zn=["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 pa=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),ga=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),ve=256,Co=ve/32,er=(ve+Co)/11;async function So(){let t=crypto.getRandomValues(new Uint8Array(ve/8));return Do(f(t),await Uo(t))}async function Eo(t){let e=No(t);return Do(f(await Oo(e)),e.join(" "))}async function tr(t){return p(t,"secret",32),{secret:t,publicKey:f(await ne(t)),accountId:await Dt(t)}}async function ko(){let t=crypto.getRandomValues(new Uint8Array(ve/8)),e=await Uo(t);return{...await Po(t),phrase:e}}async function Io(t){return Po(await Oo(No(t)))}async function Po(t){let e=await xe(f(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await V(e.publicKey),signer:e}}async function Y(t){let e=typeof t=="string"?await xe(t,"rootSecret"):t;return To(e)}async function Nt(t,e){return To(await k(t,e,"rootSecret"))}async function To(t){return{signer:t,publicKey:t.publicKey,accountId:await V(t.publicKey)}}async function ze(t){if(!t.nonce)throw new Error("nonce is required to sign an account link");let n=await(await k(t.rootSecret,t.signer,"rootSecret")).sign(m(pa,new TextEncoder().encode(t.nonce)));return Go(n)}async function Ut(t){if(!t.nonce)throw new Error("nonce is required to sign an account login");let n=await(await k(t.rootSecret,t.signer,"rootSecret")).sign(m(ga,new TextEncoder().encode(t.nonce)));return Go(n)}async function Do(t,e){return{...await tr(t),phrase:e}}function No(t){let e=t.normalize("NFKD").toLowerCase().trim().split(/\s+/),n=e[0]===""?0:e.length;if(n!==er)throw new Error(`recovery phrase must be ${er} words, got ${n}`);return e}async function Uo(t){let e=_o(t)+await Mo(t),n=[];for(let r=0;r<er;r+=1){let o=Number.parseInt(e.slice(r*11,r*11+11),2);n.push(Zn[o])}return n.join(" ")}async function Oo(t){let e="";for(let r of t){let o=Zn.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(ve/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(ve)!==await Mo(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function Mo(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return _o(e).slice(0,Co)}function _o(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Go(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var ma=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),Ot=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),ha=568;function fa(...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 nr(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 ya(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 ba(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 Mt(t){let e=await crypto.subtle.digest("SHA-256",fa(ma,new Uint8Array(32),t));return new Uint8Array(e)}function rr(t){let e=t.length>=Ot.length&&nr(t.subarray(0,Ot.length),Ot),n=e?Ot.length:ha;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 a=await i.json(),s=a.data??a;if(typeof s.quoteB64!="string")throw new Error("the relay returned no quote");let c=ba(s.boundPublicKey,"boundPublicKey"),u=ya(s.quoteB64),{reportData:d,mock:l}=rr(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 Mt(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(!nr(d.subarray(0,32),e))throw new Error("the quote does not carry our nonce: it was not made for this request");if(!nr(d.subarray(32,64),await Mt(c)))throw new Error("the quote does not bind the key the relay named: refusing it");return{nodeKey:f(c),mock:l}}var wa="Noise_NK_25519_AESGCM_SHA256",or=32,Aa=16,xa=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]),sr=class t{constructor(e){this.k=null;this.n=0;this.ck=e,this.h=e}static async initialize(){let e=new TextEncoder().encode(wa),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await va(m(this.h,e))}async mixKey(e){let[n,r]=await Ho(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:Ko(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:Ko(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return Ho(this.ck,new Uint8Array)}};async function Lo(t,e,n){let r=await sr.initialize();await r.mixHash(e),await r.mixHash(t);let o=await Ra(n);return await r.mixHash(o.publicKey),await r.mixKey(await $o(o.privateKey,t)),{message1:m(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<or+Aa)throw new Error("Noise: message 2 is too short");let s=a.slice(0,or);return await r.mixHash(s),await r.mixKey(await $o(o.privateKey,s)),{payload:await r.decryptAndHash(a.slice(or)),split:await r.split()}}}}async function Ra(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(xa,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ca(n.x)}}async function $o(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 Ko(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function va(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}async function ir(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 Ho(t,e){let n=await ir(t,e),r=await ir(n,new Uint8Array([1])),o=await ir(n,m(r,new Uint8Array([2])));return[r,o]}function Ca(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 Fo="/sealed/v2/handshake",Vo="/sealed/v2",Ye="application/vnd.calimero.sealed",ar=2,Sa=new TextEncoder().encode("calimero/sealed-http/v2"),Qe=16,Ea=1+Qe+8,ka=0,Ia=1,Pa=2,Ta=1+64*1024+16,Da=1024,Na=6e4,Ua="calimero.tee-attest.transport-key.v1",Oa=[101,204,205,304],Wo=new TextEncoder,Xe=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Ce=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Jo(t,e){let n=await crypto.subtle.digest("SHA-256",m(Wo.encode(Ua),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 Jo(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 Ze(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 Qo({baseUrl:t.baseUrl,transportPublicKey:()=>zo(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Qo(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 Bo(o,r,await qo(a))}catch(l){if(!(l instanceof Xe)||!i)throw l;return a=Promise.resolve().then(i),Bo(o,r,await qo(a))}},u=async()=>{let l=s??d(void 0),g=await l;if(Date.now()<g.renewAt)return[g,l];let w=d(l);return[await w,w]},d=l=>{if(s===l){let g=c();s=g,g.catch(()=>{s===g&&(s=void 0)})}return s};return async(l,g)=>{let w=new Request(l,g),x=new URL(w.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 A=[];w.headers.forEach((h,y)=>A.push([y,h]));let v={method:w.method,path:x.pathname.slice(n.length)+x.search,headers:A},I=new Uint8Array(await w.arrayBuffer()),P=async h=>{let{requestId:y,header:S,envelope:N}=await _a(h,v,I),_=await o(`${r}${Vo}`,{method:"POST",headers:{"content-type":Ye},body:N,signal:w.signal});if(_.headers.get("content-type")!==Ye)throw await Xo(_);return $a(_,h.responseKey,S,y)},[j,M]=await u();try{return await P(j)}catch(h){if(!(h instanceof Ce)||h.code!=="unknown_session")throw h;return P(await d(M))}}}async function qo(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Bo(t,e,n){try{return await jo(t,e,n)}catch(r){if(!(r instanceof Ce)||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 Lo(n,Sa),o=await t(`${e}${Fo}`,{method:"POST",headers:{"content-type":Ye},body:m(new Uint8Array([ar]),n,r.message1)});if(o.headers.get("content-type")!==Ye)throw await Xo(o);let i=await Ha(o,Da);return Ma(r,i)}async function Ma(t,e){if(e[0]!==ar)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!==Qe+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,Qe),a=new DataView(r.buffer,r.byteOffset).getUint32(Qe,!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-Na,header(u){let d=new Uint8Array(Ea);return d[0]=ar,d.set(i,1),new DataView(d.buffer).setBigUint64(1+Qe,BigInt(u),!1),d}}}async function _a(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:Yo(r,0),additionalData:o},t.requestKey,Ga(e,n));return{requestId:r,header:o,envelope:m(o,new Uint8Array(i))}}function Yo(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 Ga(t,e){let n=Wo.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),m(r,n,e)}async function $a(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=Ka(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:Yo(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!==ka)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(s.data));if(Oa.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===Ia?d.enqueue(l.data):l.kind===Pa?(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 Ka(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>Ta)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 Ha(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 Xo(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 Xe;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Ce(t.status,e,n,o)}var La=/^[0-9a-f]{96}$/,qa=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function cr(t){let e=Se(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((s,c)=>{let u=`allowedMeasurements[${c}]`;return qa.map(d=>Se([s?.[d]??""],`${u}.${d}`)[0]).join()}),r=[Se(t.allowedRtmr0??[],"allowedRtmr0"),Se(t.allowedRtmr1??[],"allowedRtmr1"),Se(t.allowedRtmr2??[],"allowedRtmr2"),Se(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=ja(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 w;try{w=t.dcapVerify(l,g,Math.floor(i()/1e3))}catch(I){throw new Error(`The quote did not verify: ${I?.message??String(I)}`)}if(w.status==="Revoked"||!o.includes(w.status))throw new Error(`The platform's TCB status is ${w.status}, which is not accepted`);let x=Ba(w.report),A=[x.mrTd,x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].map(I=>f(I));if(n.length>0&&!n.includes(A.join()))throw new Error(`The measurements (MRTD ${A[0]}, RTMR0-3 ${A.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(A[0]))throw new Error(`MRTD ${A[0]} is not an image this verifier trusts`);if([x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].forEach((I,P)=>{let j=r[P];if(j.length>0&&!j.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 Se(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!La.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Ba(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 ja(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 Fa=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function lr(t,{profile:e}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let n,r=t.map((o,i)=>{let a=o?.tag??`releases[${i}]`;if(o?.role!==void 0&&o.role!=="node")throw new Error(`${a} lists the measurements of a ${o.role}, not of a node image`);let s=o?.profiles?.[e];if(!s){let u=Object.keys(o?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${u})`)}let c=(s.allowed_tcb_statuses??["uptodate"]).map(u=>Va(u,a));return n=n===void 0?c:n.filter(u=>c.includes(u)),{mrtd:s.mrtd,rtmr0:s.rtmr0,rtmr1:s.rtmr1,rtmr2:s.rtmr2,rtmr3:s.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:n}}function Va(t,e){let n=Fa.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 Zo=[{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"]}],ei=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Wa="1.2.840.10045.2.1",Ja={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},za={"P-256":32,"P-384":48},Qa={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function ti(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 ke(t){let e=ti(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function G(t){let e=[];for(let n=t.start;n<t.end;){let r=ti(t.bytes,n,t.end);e.push(r),n=r.end}return e}function U(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function ie(t){return t.bytes.slice(t.start,t.end)}function Gt(t){return t.bytes.slice(t.offset,t.end)}function Ee(t){let e=ie(U(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 Ya(t){let e=new TextDecoder().decode(ie(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 ur(t){try{let[e,n,r,...o]=G(U(ke(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=G(U(e,48,"The signed part")),a=i[0]?.tag===160?1:0,[s,c,u,d,l,g,...w]=i.slice(a);U(s,2,"The serial number");let x=Ee(G(U(n,48,"The signature algorithm"))[0]);if(Ee(G(U(c,48,"The signature algorithm"))[0])!==x)throw new Error("it names two different signature algorithms");let v=Qa[x];if(!v)throw new Error(`it is signed with ${x}, not ECDSA with SHA-256 or SHA-384`);let[I,P]=G(U(d,48,"The validity")).map(Ya);if(P===void 0)throw new Error("its validity is incomplete");let[j,M]=G(U(g,48,"The public key"));U(M,3,"The public key");let[h,y]=G(U(j,48,"The key algorithm"));if(Ee(h)!==Wa)throw new Error("its key is not an elliptic-curve key");let S=Ja[Ee(y)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let N=new Map,_=w.find(Q=>Q.tag===163);if(_){let[Q]=G(_);for(let we of G(U(Q,48,"The extensions"))){let L=G(U(we,48,"An extension"));if(L.length===3)U(L[1],1,"An extension's critical flag");else if(L.length!==2)throw new Error("it has a malformed extension");let _n=Ee(L[0]);if(N.has(_n))throw new Error(`it has extension ${_n} twice`);N.set(_n,ie(U(L[L.length-1],4,"An extension value")))}}let Mn=ie(U(r,3,"The signature"));if(Mn[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:Gt(e),signatureHash:v,signature:Mn.slice(1),issuer:Gt(U(u,48,"The issuer")),subject:Gt(U(l,48,"The subject")),notBefore:I,notAfter:P,spki:Gt(g),curve:S,extensions:N}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function ni(t){return G(U(ke(t),48,"The list")).map(Ee)}function Xa(t,e){let n=za[e],r=G(U(ke(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=ie(U(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 $t(t,e,n,r,o){let i;try{i=Xa(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 W(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 dr(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 W(n[0][1],e)}var Za="2.5.29.17",ec="2.5.29.37",tc="1.3.6.1.5.5.7.3.3",nc="1.3.6.1.4.1.57264.1.8",rc="1.3.6.1.4.1.57264.1.1",oc=134,ic=12,sc=48,ac=new TextEncoder,Ie=t=>new TextDecoder().decode(t);async function ri(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:a}=dc(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=W(o,"The bundle signature"),u=dr(Ie(W(i,"The bundle certificate")),"The bundle certificate"),d=ur(u),l=ei.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=ac.encode(`{"body":${JSON.stringify(s.body)},"integratedTime":${s.integratedTime},"logID":${JSON.stringify(s.logID)},"logIndex":${s.logIndex}}`);if(!await $t(W(l.publicKey,"The Rekor key"),"P-256","SHA-256",W(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(!si(x,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${et(x)}, when the entry says it was logged`);let A=pc(s.body),v=f(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(A.hash!==v)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!pr(W(A.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let I=dr(Ie(W(A.publicKey,"The logged certificate")),"The logged certificate");if(!pr(I,u))throw new Error("The bundle's certificate is not the one Rekor logged");if(d.curve!=="P-256"||!await $t(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 cc(d,x),uc(d,n),{integratedTime:s.integratedTime}}async function cc(t,e){if(!ii(t,e))throw new Error(`The signing certificate was valid ${et(t.notBefore)} to ${et(t.notAfter)}, not at ${et(e)} when Rekor logged it`);let n=[];for(let r of Zo){let o=r.certChain.map(a=>ur(W(a,"A Fulcio certificate")));if(!await oi(t,o[0]))continue;let i=await lc(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 ${et(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function lc(t,e,n){if(!si(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!ii(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await oi(o,i))return`its certificate ${r} is not signed by the next`}}async function oi(t,e){return pr(t.issuer,e.subject)?$t(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function uc(t,e){let n=t.extensions.get(Za);if(!n)throw new Error("The signing certificate names no identity");let r=G(U(ke(n),sc,"The subject alternative name")),o=r.filter(u=>u.tag===oc).map(u=>Ie(ie(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(nc),a=t.extensions.get(rc),s=i?Ie(ie(U(ke(i),ic,"The OIDC issuer"))):a?Ie(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(ec);if(!c||!ni(c).includes(tc))throw new Error("The signing certificate is not for code signing")}function dc(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 pc(t){let e;try{e=JSON.parse(Ie(W(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 ii(t,e){return t.notBefore<=e&&e<=t.notAfter}function si(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function et(t){return new Date(t).toISOString()}function pr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var gr=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"}),gc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Kt="https://cloud.calimero.network";async function ci(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await ri(r,e,{identity:n.identity??gr.identity,issuer:n.issuer??gr.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=>gc.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 Ht(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 li(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 Lt(t,e={}){let n=await di(t,e.fetch??fetch);if(n===void 0)throw new Error(`${ui(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 ui(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function di(t,e){let n=ui(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 li(o)}function qt(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${tt(e,"version")}`}async function pi(t){let e=tt(t.minReleaseVersion,"minReleaseVersion"),n=tt(t.release?.version,"The release version"),r=await ci(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(hc(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return lr([r],{profile:t.profile})}function Bt(t){return tt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await pi({release:await t.release(),profile:t.profile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return cr({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function mc(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:a,...s}=t;r!==void 0&&tt(r,"releaseVersion");let c=a??((d,l)=>fetch(d,l));return Ze({baseUrl:e,verify:Bt({...s,release:async()=>{let d=r===void 0?await Lt(e,{fetch:c}):await di(e,c)??r;return typeof n=="function"?n({baseUrl:e,version:d,fetch:c}):Ht(qt(n??Kt,d),{fetch:c})}}),applicationId:o,applicationHash:i,fetch:c})}var gi=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function tt(t,e){let n=typeof t=="string"?gi.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 hc(t,e){let[n,r]=ai(t),[o,i]=ai(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)],w=l&&g?Math.sign(Number(u)-Number(d)):l!==g?l?-1:1:u<d?-1:u>d?1:0;if(w!==0)return w}return 0}function ai(t){let e=gi.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var fc=new TextEncoder().encode("calimero.warrant.v2"),yc=new TextEncoder().encode("calimero.warrant.intent.v1"),mi=64,hi=256;async function mr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return E(yc,[new TextEncoder().encode(t),n])}async function jt(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=hr(t.releaseVersion??""),s=se(t.accountHeads,"accountHeads"),c=se(t.governanceFloor,"governanceFloor"),u=await k(t.deviceSecret,t.signer,"deviceSecret"),d=p(u.publicKey,"signer.publicKey",32),l=new TextEncoder().encode(t.method),g=await mr(t.method,t.argsJson),w=C(t.nonce),x=C(t.notAfter),A=await E(fc,[e,n,d,r,o,i,a,l,g,C(s.length),...s,C(c.length),...c,w,x]),v=nt(await u.sign(A));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,w,x,v))}function nt(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 hr(t){let e=new TextEncoder().encode(t);return bc(e.length),e}function bc(t){if(t>hi)throw new Error(`releaseVersion is ${t} bytes, over the ${hi} a node accepts`)}function se(t,e){let n=t??[];if(n.length>mi)throw new Error(`${e} cites ${n.length} heads, over the ${mi} a node accepts`);return n.map((r,o)=>p(r,`${e}[${o}]`,32))}var wc=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Ac=new TextEncoder().encode("calimero.context-creation.init.v1"),Ft=256;async function fr(t){let e=new TextEncoder().encode(JSON.stringify(t));return E(Ac,[e])}async function xc(t){return E(wc,[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 Vt(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=fi(t.serviceName,"serviceName"),c=fi(t.name,"name"),u=se(t.accountHeads,"accountHeads"),d=se(t.governanceFloor,"governanceFloor"),l=await k(t.deviceSecret,t.signer,"deviceSecret"),g=p(l.publicKey,"signer.publicKey",32),w=await fr(t.initArgs),x=await xc({group:e,seed:n,authorAccount:r,deviceKey:g,executor:o,executorKey:i,applicationId:a,serviceName:s,name:c,initHash:w,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),A=nt(await l.sign(x));return{warrant:f(m(e,n,r,g,o,i,a,yi(s),yi(c),w,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),A)),seed:f(n)}}function bi(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 w=n.subarray(o,o+l);return o+=l,w},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 w=a(l);if(w>Ft)throw new Error(`${l} is ${w} bytes, over the ${Ft} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(w,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 fi(t,e){if(t===void 0)return null;let n=new TextEncoder().encode(t);if(n.length>Ft)throw new Error(`${e} is ${n.length} UTF-8 bytes, over the ${Ft} a node accepts`);return n}function yi(t){return t===null?new Uint8Array([0]):m(new Uint8Array([1]),R(t.length),t)}var Rc=new TextEncoder().encode("calimero.governance-warrant.v1"),vc=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Cc={group:0,root:1};async function yr(t){return E(vc,[new Uint8Array([br(t.kind)]),t.bytes])}async function Sc(t){return E(Rc,[t.scope,new Uint8Array([br(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 rt(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=se(t.accountHeads,"accountHeads"),a=se(t.governanceFloor,"governanceFloor"),s=br(t.op.kind),c=await k(t.deviceSecret,t.signer,"deviceSecret"),u=p(c.publicKey,"signer.publicKey",32),d=await yr(t.op),l=await Sc({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=nt(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 wi(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 w=n.subarray(o,o+l);return o+=l,w},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 br(t){let e=Cc[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Ec={Admin:0,Member:1,ReadOnly:2},$={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},ot={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},kc=new TextEncoder().encode("calimero.namespace.id.v1"),Ar=new Uint8Array(32),Wt=R(0);function xi(t){let e=Ec[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 Pe(t,e){return{kind:"group",bytes:m(D($.MemberAdded),p(t,"member",32),xi(e))}}function Jt(t){return{kind:"group",bytes:m(D($.MemberRemoved),p(t,"member",32),Ar,Wt)}}function it(t){return{kind:"group",bytes:m(D($.MemberLeft),p(t,"member",32),Ar,Wt)}}function zt(t,e){return{kind:"group",bytes:m(D($.MemberRoleSet),p(t,"member",32),xi(e))}}var Ic=new TextEncoder().encode("calimero.subgroup.id.v1");async function xr(t,e,n,r){return f(await E(Ic,[p(t,"admin",32),p(e,"parentId",32),new Uint8Array([n?1:0]),p(r,"salt",32)]))}function Ai(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 Qt(t){return{kind:"group",bytes:m(D($.TargetApplicationSet),Ar,p(t.applicationId,"applicationId",32),Ai(t.package,"package"),Ai(t.version,"version"))}}function Te(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(ce(t,O.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($.DefaultCapabilitiesSet),R(t))}}function Rr(t){return{kind:"root",bytes:m(D(ot.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 De(t){let e=t.salt??f(crypto.getRandomValues(new Uint8Array(32))),n=await xr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:Rr({...t,groupId:n,salt:e})}}function Yt(t,e){return{kind:"root",bytes:m(D(ot.GroupReparented),p(t,"childGroupId",32),p(e,"newParentId",32))}}function Xt(t){return{kind:"root",bytes:m(D(ot.GroupDeleted),p(t,"rootGroupId",32),Wt,Wt)}}async function Zt(t,e){return f(await E(kc,[p(t,"founder",32),p(e,"salt",32)]))}function en(t){let e=F(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(ot.NamespaceCreatedV2),p(t.founder,"founder",32),e,p(t.salt,"salt",32))}}function wr(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function vr(t){return t===void 0?D(0):m(D(1),wr(t))}function Cr(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])=>[wr(o),wr(r)]))}function Pc(t,e){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`${e} must be a u32 bit mask, got ${String(t)}`);if(ce(t,O.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 tn(t,e){return{kind:"group",bytes:m(D($.MemberCapabilitySet),p(t,"member",32),R(Pc(e,"capabilities")))}}function nn(t){return{kind:"group",bytes:m(D($.ContextDetached),p(t,"contextId",32))}}function rn(t){if(t!=="open"&&t!=="restricted")throw new Error(`mode must be open or restricted, got ${String(t)}`);return{kind:"group",bytes:m(D($.SubgroupVisibilitySet),D(t==="open"?0:1))}}function Ne(t={}){return{kind:"group",bytes:m(D($.GroupMetadataSet),vr(t.name),Cr(t.data))}}function on(t,e={}){return{kind:"group",bytes:m(D($.MemberMetadataSet),p(t,"member",32),vr(e.name),Cr(e.data))}}function sn(t,e={}){return{kind:"group",bytes:m(D($.ContextMetadataSet),p(t,"contextId",32),vr(e.name),Cr(e.data))}}function Ri(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 vi(t,e,n){return{kind:"group",bytes:m(D($.ContextCapabilityGranted),p(t,"contextId",32),p(e,"member",32),Ri(n))}}function Ci(t,e,n){return{kind:"group",bytes:m(D($.ContextCapabilityRevoked),p(t,"contextId",32),p(e,"member",32),Ri(n))}}function an(t){return{kind:"root",bytes:m(D(ot.MemberJoinedOpen),p(t.member,"member",32),p(t.groupId,"groupId",32),F(t.credential,"credential"))}}var cn=300,ue=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"}},Tc=t=>new Promise(e=>setTimeout(e,t));function Dc(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 J=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 k(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??"";hr(s);let c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??cn,l=await jt({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 ue(`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 ue(`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??cn,{warrant:c}=await Vt({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 ue(`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??cn,s=await rt({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 Zt(this.config.authorAccount,r),i=en({founder:this.config.authorAccount,credential:this.config.authorProof,salt:r}),a=e.defaultCapabilities===void 0?void 0:Te(e.defaultCapabilities),s=e.application?Qt(e.application):void 0,c=await this.authorSigner(),u=await this.config.nonces.next(),d=this.config.ttlSeconds??cn,l=await rt({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),w={namespaceId:g.groupId,salt:r,teeEnabled:g.teeEnabled??!1,...g.teeError?{teeError:g.teeError}:{}},x=w,A=v=>v instanceof Error?v.message:String(v);if(s)try{await this.govern({groupId:w.namespaceId,op:s}),x={...x,applicationSet:!0}}catch(v){x={...x,applicationSet:!1,applicationError:A(v)}}if(a)try{await this.govern({groupId:w.namespaceId,op:a}),x={...x,defaultCapabilitiesSet:!0}}catch(v){x={...x,defaultCapabilitiesSet:!1,defaultCapabilitiesError:A(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=Dc(a.headers);await Tc(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=Nc(c);throw new ue(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 Nc(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 de=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 Uc=new TextEncoder().encode("calimero.auth.login.v1"),Si={webOrigin:0,codeSigningId:1,cli:2};function Ei(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 Oc(t){return m(Uint8Array.from([Si[t.kind]]),Ei(t))}function Mc(t){let e=Uint8Array.from([Si[t.kind]]);if(t.kind==="cli")return e;let n=Ei(t);return m(e,R(n.length),n)}async function ln(t){let e=p(t.node,"node",32),n=p(t.challenge,"challenge",32),r=p(t.sessionKey,"sessionKey",32),o=await k(t.deviceSecret,t.signer,"deviceSecret"),i=p(o.publicKey,"signer.publicKey",32),a=C(t.issuedAt),s=C(t.expiresAt),c=await E(Uc,[e,Oc(t.audience),n,r,i,a,s]),u=await o.sign(c);return f(m(e,Mc(t.audience),n,r,i,a,s,u))}var _c=300;async function Sr(){let t=f(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:f(await ne(t)),secret:t}}async function Ue(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(g,w)=>{let x=new AbortController,A=setTimeout(()=>x.abort(),n),v;try{let P={...w,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(A)}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 Sr(),s=Math.floor(Date.now()/1e3),c=await ln({node:t.node,audience:t.audience,challenge:i,sessionKey:a.publicKey,issuedAt:s,expiresAt:s+(t.ttlSeconds??_c),signer:await k(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 Gc=3e4;function Me(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function $c(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 Oe=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-Gc>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Ue({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=$c(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new q({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new re({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var X=t=>new TextEncoder().encode(t),Kc=X("calimero.auth.request.v1"),Hc=X("calimero.auth.request.body.v1"),Er="X-Calimero-Proof",Lc=300;async function kr(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"?X(t.body):t.body,i=await E(Hc,[o]),a=Math.floor(t.now??Date.now()/1e3),s=a+(t.validForSeconds??Lc),c=await E(Kc,[X(e),X(n),i,C(a),C(s)]),u=await qc(c,t);if(u.length!==64)throw new Error(`the signer returned ${u.length} bytes, not a 64-byte signature`);let d=m(R(X(e).length),X(e),R(X(n).length),X(n),i,C(a),C(s),u),l=Bc(r,"credential");return f(m(l,new Uint8Array([0]),d))}async function qc(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 te(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function Bc(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 Ir(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 kr({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Er]:o}}}function jc(t){return new URL(t).pathname}var ki=new TextEncoder().encode("calimero/presence/1");async function Ii(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 Pr(t){return m(ki,p(t.contextId,"contextId",32),p(t.author,"author",32),C(t.seq),C(t.sentAtMs),await Ii(t.state))}var Fc=2500,st=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??Fc,this.now=e.now??Date.now}async set(e,n,r=oe()){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=oe()){return It(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 Pr({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 Pi(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 Ti(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 Vc(t,e){let n=e?.nodeKey;return n?new Oe({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:n,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??Me(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch,timeoutMs:e?.timeoutMs}):null}var pe=class{constructor(e){this.relayObserver=null;this.relayAdmin=null;this.proofAuthorizer=null;this.relayUrl=null;this.proofEvents=null;this.relayPresence=null;if(e.transport==="relay"){this.transport="relay",this.nodeClient=null;let o=e.relay instanceof J?e.relay:new J(e.relay);if(this.relayObserver=Vc(o,e.observe),this.rpcTransport=new de(o,this.relayObserver),this.relayUrl=o.relayUrl,e.proof&&(this.proofAuthorizer=Ir(e.proof)),e.session){let i=e.session;this.relayAdmin=io({baseUrl:o.relayUrl,getAuthToken:typeof i=="string"?async()=>i:i})}else if(this.proofAuthorizer){let i=this.proofAuthorizer;this.relayAdmin=Rt(Fe({fetch:(a,s)=>globalThis.fetch(a,s),baseUrl:o.relayUrl,authorizeRequest:i}),{baseUrl:o.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 Pi("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof de))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 q({baseUrl:this.relayUrl,authorize:this.proofAuthorizer})),this.proofEvents;throw Ti("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."):Ti("WebSocket events")}get ephemeral(){return this.nodeClient?this.nodeClient.ephemeral:(this.relayPresence??(this.relayPresence=new st({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw Pi("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 un(t){return new pe(t)}var Dr="calimero.delegated.connection",Nr="calimero.delegated.credential";function Ur(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(Dr);return t?JSON.parse(t):null}catch{return null}}function Ni(t){try{sessionStorage.setItem(Dr,JSON.stringify(t))}catch{}}function Ui(){try{sessionStorage.removeItem(Dr)}catch{}}function Oi(){let t=Ur();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(Nr);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function Mi(t){try{sessionStorage.setItem(Nr,JSON.stringify(t))}catch{}}function _i(){try{sessionStorage.removeItem(Nr)}catch{}}function Or(t){let e=pn(t);return{next:async()=>{let n=0n;try{n=Gi(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function pn(t){return`calimero.nonce.${t}`}function Gi(t){let e=localStorage.getItem(pn(t));if(e!==null)return BigInt(e);let n=`${pn(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 mn(t,e,n){try{Gi(t)<=n&&localStorage.setItem(pn(t),String(n+1n))}catch{}}var $i="calimero.delegated.relay-node-key.";function ge(t){return t.replace(/\/+$/,"")}function Mr(t,e){localStorage.setItem($i+ge(t),e.trim().toLowerCase())}function hn(t){try{let e=localStorage.getItem($i+ge(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function Ki(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Wc="locked-read-only",Jc="2.3.99",Tr;function zc(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 Ge=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 Di(t,e){try{return await e()}catch(n){throw n instanceof Ge?n:new Ge(t,n)}}function Qc(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new Ge(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function Yc(t,e){return Object.assign(async r=>{let o=await Di("loading the quote verifier",()=>(Tr??(Tr=import("@phala/dcap-qvl").then(i=>zc(i),i=>{throw Tr=void 0,i})),Tr));return Bt({dcapVerify:o,release:()=>Di("fetching the release the relay runs",async()=>Ht(qt(Kt,await Lt(t,{fetch:e})))),profile:Wc,minReleaseVersion:Jc})(r)},{includeCollateral:!0})}async function $e(t){let e=hn(t);if(e)return{kind:"learned",nodeKey:e};let n={failure:null},r=Qc(n);try{let o=Ki(t),{nodeKey:i}=await _t({relayUrl:t,allowMock:o,fetch:r,...o?{}:{verify:Yc(t,r)}});return Mr(t,i),{kind:"learned",nodeKey:i}}catch(o){return o instanceof Ge||n.failure?{kind:"unavailable",error:o}:{kind:"refused",error:o}}}async function fn(t){let e=await $e(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 gn=[1e3,2e3,5e3,1e4,3e4];function Xc(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 Hi(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await $e(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=gn[Math.min(r,gn.length-1)];console.warn(`[mero-js] could not reach what proves the relay's node key; retrying in ${i/1e3} s`,o.error),await Xc(i,n)}return null}function Zc(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}}function el(t,e){let n=null,r=null;return async()=>{let o=n?Zc(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Ue({nodeUrl:t.relayUrl,node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:Me()}).then(i=>(n=i.accessToken,n)).catch(i=>{console.warn("[mero-js] relay login failed",i),n=null}).finally(()=>{r=null})),r)}}var dn=new Map;function Li(){dn.clear()}function tl(t){return typeof t=="object"&&t!==null&&t.status===409}function nl(t,e){let n=t.rpc,r=ge(e),o=async i=>{let a=`${r}|${i.contextId}|${i.method}`;if(dn.get(a)!=="write")try{let{returns:s}=await t.admin.queryContext(i.contextId,{method:i.method,argsJson:i.argsJson??{}});return dn.set(a,"read"),{returns:s,transport:"relay"}}catch(s){tl(s)&&dn.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 rl(t){return new q({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 ol(t,e){let n=e.session?nl(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=rl(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 yn(t,e){if(!t.relayUrl)return null;let n=hn(t.relayUrl),r=un({transport:"relay",relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:Or(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?el({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return ol(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||Ki(t.relayUrl)})}var qi="calimero.delegated.relays.";function B(t){try{let e=localStorage.getItem(qi+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function _r(t,e){try{localStorage.setItem(qi+t,JSON.stringify(e))}catch{}}function me(t,e,n){let r=B(t),o=ge(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),_r(t,r)}function Bi(t,e){return B(t).contexts[e]??null}function bn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||ge(t.relayUrl)!==ge(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function Ke(t){let e=B(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(ge);return[...new Set(n)]}async function ji(t){let e=[],n=B(t.account);for(let r of Ke(t))try{if(!await fn(r))continue;let o=yn({...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 _r(t.account,n),e}async function Fi(t){var o,i;let e=[],n=new Set,r=B(t.account);for(let a of Ke(t))try{if(!await fn(a))continue;let s=yn({...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 _r(t.account,r),e}function An(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 at(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 il(t){return{getWarrantNonce:(e,n)=>t.client.getWarrantNonceAsAuthor(e,t.authorProof)}}var wn=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 sl(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??An(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 wn(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 Vi(t){if(!t.sessionToken&&!t.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=await k(t.deviceSecret,t.signer,"deviceSecret"),n=new K({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=cl(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),a=Gr(i);if(!a)throw new Error(ll(o,i));let s=new J({relayUrl:a.relayUrl,executorAccount:a.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??ul(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?Ze({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 pe({transport:"relay",relay:s,observe:{nodeKey:t.relayNodeKey??a.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function al(t){let{root:e,authorAccount:n,...r}=t,o=await k(r.deviceSecret,r.signer,"deviceSecret"),i=await Y(e),s=await new K({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return Vi({...r,deviceSecret:void 0,signer:o,sessionToken:s.sessionToken,authorAccount:n??i.accountId})}function cl(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 ll(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 ul(t){let e=`mero-js:warrant-nonce:${t}`;try{return at(e)}catch{return An(1)}}var dl=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Wi(t,e){p(e,"deviceSecret",32);let n=await te(e),r=m(dl,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return pl(o)}async function xn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Wi(t.nonce,e.deviceSecret)}}function pl(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var gl="https://cloud.calimero.network";function zi(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??gl);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",t.returnTo),e.toString()}function ml(t){throw window.location.assign(zi(t)),new Error("redirecting to the cloud to authorise this link")}function hl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Ji(),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:(Ji(),{grant:r,account:o})}function Ji(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function fl(t){let e=await Y(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 K({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,signer:e.signer})}var yl="enrol-device",bl="enrol-kem",wl="callback-url",Al="state";function Xi(t){Yi(t.devicePublicKey,"devicePublicKey"),Yi(t.kemPublicKey,"kemPublicKey"),Sl(t.returnTo),Cl(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(yl,t.devicePublicKey),e.searchParams.set(bl,t.kemPublicKey),e.searchParams.set(wl,t.returnTo),t.state&&e.searchParams.set(Al,t.state),e.toString()}function xl(t){throw window.location.assign(Xi(t)),new Error("redirecting to the wallet to approve this device")}function Rl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Qi(),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;Qi();let a=e.get("state");return{credential:r,account:o,device:i,...a?{state:a}:{}}}function Qi(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function vl(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 Tt(t.credential);if(e.signPublicKey!==he(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${he(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==he(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!==he(t.account))throw new Error(`the wallet reported account ${he(t.account)}, but the credential names ${e.account}`);if(e.device!==he(t.device))throw new Error(`the wallet reported device ${he(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function Yi(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function he(t){return t.trim().toLowerCase()}function Zi(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 Cl(t){Zi(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 Sl(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 pt(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 kl(t){let e=[];for(let n of t??[])try{let r=new URL(n);(r.protocol==="http:"||r.protocol==="https:")&&e.push(n.replace(/\/+$/,""))}catch{}return e}function Il(t,e){if(e.size===0)return!0;let n=pt(t.account);return n!==null&&e.has(n)}async function Rn(t){let e=t.cloud??new K({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){let[l]=kl(t.admitterAddrs);if(l){let g=(t.admitters??[]).map(pt).filter(w=>w!==null);return{ok:!0,relayUrl:l,admitUrl:`${l}/admin-api/namespaces/${t.namespaceId}/admit`,admitterAccount:g.length===1?g[0]:null,peerId:null,writable:!0,stale:!1,via:"invitation"}}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(pt).filter(l=>l!==null)),i=n.filter(l=>Il(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,via:"cloud"}}var vn=1440*60,Kr={Admin:0,Member:1,ReadOnly:2};function gt(t){let e=t.admitters??[];return m($r(t.inviter_identity,"inviter_identity"),$r(t.group_id,"group_id"),C(t.expiration_timestamp),$r(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>p(n,`admitters[${r}]`,32)))}async function Hr(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",gt(t)))}function Lr(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Cn(t){let e=await k(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=Lr(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,w)=>p(g,`admitters[${w}]`,32));let i=t.invitedRole??Kr.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??vn,vn);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 Hr(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 $r(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var qr=24,Pl=new TextEncoder().encode("calimero.namespace.v1"),Tl=0,es={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function ts(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 ns(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function Sn(t){let e=t.invitation,n=t.admitter_addrs??[];return m(gt(e),ns(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(ns),ts(t.application_id,"application_id"),ts(t.app_key,"app_key"))}async function En(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([es.MemberJoinedAt]),p(t.member,"member",32),Sn(t.invitation),C(o),n):m(new Uint8Array([es.MemberJoined]),p(t.member,"member",32),Sn(t.invitation),n),a=m(new Uint8Array([Tl]),i),s=await k(t.deviceSecret,t.signer,"deviceSecret"),c=p(s.publicKey,"signer.publicKey",32),u=m(new Uint8Array([qr]),p(t.namespaceId,"namespaceId",32),R(e.length),...e.map((g,w)=>p(g,`parentOpHashes[${w}]`,32)),c,C(t.nonce),a),d=await s.sign(m(Pl,u)),l=new Uint8Array([0]);return f(m(u,d,l))}function Dl(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 Nl(t){let e=at(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function rs(t){return t.replace(/\/+$/,"")}async function kn(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await En({namespaceId:t.namespaceId,member:e,invitation:t.invitation,credential:n,deviceSecret:r,nonce:await(t.deps?.nonce??Nl(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??`${rs(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:Dl(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:rs(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function In(t){let e=t.deps?.resolve??Rn,n=t.deps?.join??kn,r=null,o=t.nodeUrl,i;if(!o){let s=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,admitterAddrs:t.invitation.admitter_addrs,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 os(t,e,n,r){let i=await(r.bootstrap??In)({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&&me(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(bn(t,i.session)),{namespaceId:e}}function is(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 Br(t,e){let n=is(t),r=is(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 Ul(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 mt(t){return t.filter(e=>!e.yanked&&typeof e.appVersion=="string"&&e.appVersion.length>0).reduce((e,n)=>!e||Ul(n.appVersion,e.appVersion)?n:e,void 0)}async function ht(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 ss(t,e,n={}){let o=(await ht(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=mt(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 Br(e,s),signerId:s,version:a.appVersion}}function cs(t,e){return{next:async()=>Ol(t,e)}}function Ol(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 ls(t,e){let n=B(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 Ml(t){return!t||t.length===0?{}:JSON.parse(new TextDecoder().decode(Uint8Array.from(t)))}function Tn(t,e,n,r){return new J({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r})}async function ft(t,e,n={}){let r=ls(t,e.namespaceId),o=0n,i=await Tn(t,r,{next:async()=>o},n.fetch).createContext({groupId:e.groupId??e.namespaceId,applicationId:e.applicationId,serviceName:e.serviceName,seed:e.contextSeed,initArgs:Ml(e.initializationParams),name:e.name});return mn(r,i.contextId,o),me(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function ye(t,e,n={}){let r=ls(t,e.namespaceId);return Tn(t,r,cs(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function us(t,e,n={}){let{groupId:r}=await ye(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await De({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await ye(t,{namespaceId:e.namespaceId,group:r,op:Pe(i,"Member")},n);let{contextId:o}=await ft(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function Dn(t,e={},n={}){let o=Ke(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 _l(t,o,n.fetch),a=BigInt(Date.now()),s=await Tn(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(me(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 $l(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 _l(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(B(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 as(e),a=await Tn(t,e,cs(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 as(t){let e=await $e(t);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 (only a key from its operator, pinned with pinRelayNodeKey, can stand in)")}var Nn="link this account to your cloud user in the wallet so invitees can find this namespace",Pn={account_not_linked:Nn,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 Gl(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 $l(t,e,n,r,o){try{return await new K({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 fe)return{haEnabled:!1,haError:Nn};if(i instanceof z&&Pn[i.code]){let a=i.code==="ha_request_pending"?Gl(i):null,s=Pn[i.code];return{haEnabled:!1,haError:a?`${s} (waiting: ${a})`:s}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function He(t,e,n=globalThis.fetch){let r=mt(await ht(t,e,n));if(!r)throw new Error(`the registry lists no version of ${e}`);return r.appVersion}var ds="calimero.delegated.group-namespace.",jr=new Map;function ps(t){let e={};try{e=JSON.parse(localStorage.getItem(ds+t)??"{}")}catch{}return{...e,...jr.get(t)}}function yt(t,e,n){jr.set(t,{...jr.get(t),[e]:n});try{let r=ps(t);r[e]=n,localStorage.setItem(ds+t,JSON.stringify(r))}catch{}}function bt(t,e){return B(t.account).namespaces[e]?e:ps(t.account)[e]}function gs(t,e){let n=bt(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 Un(t,e,n){return ye(t,{namespaceId:gs(t,e),group:e,op:n})}async function On(t,e,n){let r=gs(t,e);return ye(t,{namespaceId:r,group:r,op:n})}var be=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Le=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"}},qe=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the namespace is not hosted in the cloud and has no relay in it, so an invitee with no node has no relay to be admitted through. Link this account to your cloud user in the wallet and enable HA for the namespace, then invite.`:`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"}},ms={listNamespaces:async()=>[],listNamespacesForApplication:async()=>[],getContexts:async()=>({contexts:[]})},Kl=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 Hl(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 hs(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??Un,a=e.govern?.root??On,s=e.createContext??ft,c=e.found??Dn,u=e.latestVersion??He,d=e.signInvitation??Cn,l=e.join,g=e.routing;async function w(h,y){if(!l)throw new be("joinNamespace without a join handler");return l(h,y.invitation)}let x=()=>{if(r===null)throw new Le("this call");return r};async function A(h){if(bt(n,h))return;let y=await x().getGroupInfo(h);yt(n.account,h,y.namespaceId??h)}let v=async(h,y,S)=>(await A(y),i(h,y,S)),I=async(h,y,S)=>(await A(y),a(h,y,S));async function P(h){try{return await I(n,h,an({member:n.account,groupId:h,credential:n.credential})),!0}catch(y){if(Hl(y))return!1;throw y}}async function j(h,y){let S=y??String(await x().getContextGroup(h)),{members:N}=await x().listGroupMembers(S);return N.some(_=>_.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 be("createNamespace without a packageName");let y=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:N,haError:_}=await c(n,{defaultCapabilities:231,application:{applicationId:h.applicationId,package:o.packageName,version:y}});return h.name&&await v(n,S,Ne({name:h.name})),{namespaceId:S,haEnabled:N,..._!==void 0?{haError:_}:{}}},async createGroupInNamespace(h,y={}){let{op:S}=await De({parentId:h,restricted:y.visibility==="restricted",admin:n.account}),{groupId:N}=await I(n,h,S);return yt(n.account,N,h),y.groupName&&await v(n,N,Ne({name:y.groupName})),{groupId:N}},async addGroupMembers(h,y){for(let S of y.members)await v(n,h,Pe(S.identity,S.role??"Member"))},async removeGroupMembers(h,y){for(let S of y.members)await v(n,h,Jt(S))},async setGroupMetadata(h,y){await v(n,h,Ne(y))},async setMemberMetadata(h,y,S){await v(n,h,on(y,S))},async setContextMetadata(h,y,S){await v(n,h,sn(y,S))},async setDefaultCapabilities(h,y){await v(n,h,Te(y.defaultCapabilities))},async setSubgroupVisibility(h,y){await v(n,h,rn(y.subgroupVisibility==="open"?"open":"restricted"))},async setMemberCapabilities(h,y,S){await v(n,h,tn(y,S.capabilities))},async deleteGroup(h){return await I(n,h,Xt(h)),{isDeleted:!0}},async reparentGroup(h,y){return await I(n,h,Yt(h,y.newParentId)),{reparented:!0}},async leaveGroup(h){await v(n,h,it(n.account))},async leaveNamespace(h){await v(n,h,it(n.account))},async getContextIdentitiesOwned(h){return{identities:await j(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:N}=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:N,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:y},S]=await Promise.all([x().listGroupMembers(h),x().getGroupInfo(h)]),N=y.filter(Q=>Q.role==="RelayTee").map(Q=>Q.identity.toLowerCase()),_;if(g){let Q=new Set(N.length>0?N:y.filter(L=>L.role==="Admin").map(L=>L.identity.toLowerCase())),we=null;try{we=(await g(h)).nodes}catch{}if(we!==null){if(we.length===0){if(N.length===0||!n.relayUrl)throw new qe(h,"not-hosted");_=[n.relayUrl]}else if(!we.some(L=>L.account!==null&&Q.has(L.account.toLowerCase())))throw new qe(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...N.length>0?{admitters:N}:{},..._?{admitterAddrs:_}:{},members:y,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:w,async updateMemberRole(h,y,S){await v(n,h,zt(y,S.role))},async joinSubgroupInheritance(h){return{groupId:h,memberPublicKey:n.account,wasInherited:await P(h)}},async detachContextFromGroup(h,y){await v(n,h,nn(y))}};return r===null?new Proxy({},{get(h,y){if(typeof y=="string")return y==="getNodeIdentity"?M.getNodeIdentity:y==="joinNamespace"?w:y in ms?ms[y]:async()=>{throw new Le(y)}}}):new Proxy(r,{get(h,y,S){return typeof y=="string"&&y in M?M[y]:typeof y=="string"&&Kl.has(y)?async()=>{throw new be(y)}:Reflect.get(h,y,S)}})}function fs(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??He;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 Ll="https://manager.cloud.calimero.network";function Fr(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function Vr(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function Gr(t){return t.find(e=>e.canExecute&&e.relayUrl!==null&&e.executorAccount!==null)??null}function ql(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 Bl=/^[0-9a-f]{64}$/;function jl(t){return typeof t=="string"&&Bl.test(t)?t:null}var z=class extends T{constructor(n,r,o,i,a,s){super(r,o,i,a,s);this.code=n;this.name="AccountHaRefusedError"}},fe=class extends z{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};fe.CODE="account_not_linked";var ct=class extends z{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};ct.CODE="account_linked_to_several_users";var lt=class extends z{constructor(){super(...arguments);this.name="HaRequestPendingError"}};lt.CODE="ha_request_pending";var ut=class extends z{constructor(){super(...arguments);this.name="UnknownRelayError"}};ut.CODE="unknown_relay";var dt=class extends z{constructor(){super(...arguments);this.name="RelayNotDialableError"}};dt.CODE="relay_not_dialable";var ys={409:[fe,ct,lt],422:[ut,dt]};function Fl(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 Vl="x-mdma-session-refresh",Wl="x-mdma-session-expires",K=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Ll).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 Y(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:Vr(r),canExecute:Fr(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:ql(r)}})}async findExecutingRelay(e){let n=await this.getNamespaceRelays(e);return Gr(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:Vr(r),canExecute:Fr(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 xn(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 xn(n,this.routingCredential)})).relays??[]).map(o=>({peerId:String(o.peer_id??""),relayUrl:o.relay_url??null,fresh:o.fresh===!0,executorAccount:jl(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:Vr(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:Fr(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 zn({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&&ys[i.status]){let a=Fl(i.bodyText),s=ys[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 Y(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":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 Nt(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,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(Vl);if(!n||!this.session)return;let r=e.headers.get(Wl),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 El(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 Jl(t){if(t)return typeof t=="function"?t:St(t)}var zl="mero-js:token-refresh";function Ql(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function Wr(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.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());let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=Jl(this.config.requestProof);this.httpClient=Ae({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.tokenStore?.setTokens(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=eo(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=Rt(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 We({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new q({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 Je({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new K(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 re({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:Wr(i,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}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){let n=Ql();return n?n.request(zl,e):e()}async performTokenRefreshLocked(e){let n=this.tokenStore?.getTokens()??null;if(n?.refresh_token&&(this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");try{let r=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token}),o=r.data.access_token;return this.tokenData={access_token:o,refresh_token:r.data.refresh_token,expires_at:Wr(o,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Token refresh failed: ${r instanceof Error?r.message:"Unknown error"}`)}}clearToken(){this.refreshPromise=null,this.tokenData=null,this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||Wr(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.tokenStore?.setTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return jn(e)}static buildAuthLoginUrl(e,n){return Fn(e,n)}};function Yl(t){return new _e(t)}var Jr=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Xl="mero-tokens",zr=class{constructor(e=Xl){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 Zl=new TextEncoder().encode("calimero.account.owner-op.v1"),eu=new TextEncoder().encode("calimero.account.owner-op.body.v1"),tu=new TextEncoder().encode("calimero.account.genesis.v1"),nu=2,Qr={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},Be={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},ws={AdminChanged:3,RootGuarded:12},ru={replica:0,relay:1},ou=new TextEncoder;function H(t){return new Uint8Array([t])}function As(t){let e=ou.encode(t);return m(R(e.length),e)}function Z(t){return m(R(t.length),...t.map(As))}function xs(t){return H(t?1:0)}function Rs(t){let e=ru[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return H(e)}function vs(t){return{kind:"transferOwnership",plane:"group",bytes:m(H(Be.TransferOwnership),p(t,"newOwner",32))}}function Cs(){return{kind:"groupDelete",plane:"group",bytes:H(Be.GroupDelete)}}function Ss(t){return{kind:"adminChanged",plane:"root",bytes:m(H(ws.AdminChanged),p(t,"newAdmin",32))}}function Es(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:m(H(Be.TeeAuthoringPolicySet),Z(t))}}function ks(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:m(H(Be.TeeAdmissionPolicySetV2),Z(t.allowedMrtd),Z(t.allowedRtmr0),Z(t.allowedRtmr1),Z(t.allowedRtmr2),Z(t.allowedRtmr3),Z(t.allowedTcbStatuses),xs(t.acceptMock),Rs(t.mode))}}function Is(t){let e=t.minReleaseVersion===void 0?H(0):m(H(1),As(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:m(H(Be.TeeReleaseAdmissionPolicySetV2),Z(t.allowedProfiles),e,Z(t.allowedTcbStatuses),xs(t.acceptMock),Rs(t.mode))}}async function Yr(t){return E(eu,[t])}async function Xr(t){return E(Zl,[p(t.account,"account",32),p(t.namespaceId,"namespaceId",32),p(t.groupId,"groupId",32),H(Ps(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function Ps(t){let e=Qr[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var bs=132;async function Ts(t){let e=await ne(t.rootSecret),n=m(H(nu),e),r=f(await E(tu,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let g=F(d,`chain[${l}]`);if(g.length!==bs)throw new Error(`chain[${l}] must be a ${bs}-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 Yr(t.op.bytes),s=await Xr({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:a,counter:t.counter,keyEpoch:o}),c=await te(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),H(Ps(t.op.kind)),a,C(t.counter),R(o),u))}function Ds(t,e){let n=t.plane==="group"?Be.RootGuarded:ws.RootGuarded;return m(H(n),t.bytes,F(e,"rootProof"))}var Ns=[2428,2429,2528,2529],iu="localhost",su=2e3;function Us(t){return`http://${iu}:${t}`}function Os(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function Ms(t,e={}){let{timeoutMs:n=su,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=Os(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 au(t={}){let{ports:e=Ns,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let a=Us(i);return await Ms(a,{timeoutMs:n,signal:r})?a:null}))).filter(i=>i!==null)}export{wo as ACCOUNT_HA_AUDIENCE,bo as ACCOUNT_OWNERSHIP_AUDIENCE,z as AccountHaRefusedError,ct as AccountLinkedToSeveralUsersError,fe as AccountNotLinkedError,le as AdminApiClient,ae as AuthApiClient,ee as AuthRevokedError,O as CAPABILITIES,ku as CAPABILITY_PRESETS,K as CloudClient,Ns as DEFAULT_LOCAL_NODE_PORTS,Kt as DEFAULT_RELEASE_MIRROR,Je as EphemeralClient,Fo as HANDSHAKE_PATH,Nn as HA_ACCOUNT_NOT_LINKED_MESSAGE,Pn as HA_REFUSAL_MESSAGES,T as HTTPError,lt as HaRequestPendingError,Kr as INVITED_ROLE,ue as IntentRefusedError,qe as InvitationNotClaimableError,zr as LocalStorageTokenStore,vn as MAX_INVITATION_VALIDITY_SECS,Jr as MemoryTokenStore,pe as MeroClient,_e as MeroJs,gr as NODE_RELEASE_SIGNER,Le as NoRelayError,be as NotForAccountError,Qr as OWNER_OP_KIND,ki as PRESENCE_DOMAIN,gn as RELAY_NODE_KEY_RETRY_MS,Er as REQUEST_PROOF_HEADER,J as RelayClient,dt as RelayNotDialableError,Oe as RelayObserver,st as RelayPresenceClient,de as RelayTransport,We as RpcClient,Et as RpcError,Ye as SEALED_CONTENT_TYPE,Vo as SEALED_PATH,qr as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Ce as SealedTransportError,q as SseClient,Xe as StaleTransportKeyError,ut as UnknownRelayError,wn as WarrantNonceExhaustedError,xt as WarrantNonceRouteUnavailableError,je as WebHttpClient,re as WsClient,Dt as accountForRoot,V as accountForRootPublicKey,Eo as accountRootFromPhrase,tr as accountRootFromSecret,Io as accountRootSignerFromPhrase,Ss as adminChangedOp,El as admitterAddrsFromNetworkStatus,Br as applicationIdForBundle,$e as attemptRelayNodeKey,Mt as attestKeyBinding,_t as attestRelayNodeKey,il as authorNonceLookup,ml as beginCloudLink,xl as beginDeviceEnrolment,In as bootstrapFromInvitation,Fn as buildAuthLoginUrl,yn as buildDelegatedClient,Zi as callbackIsForeign,Ct as callerProof,Iu as capMask,Pu as capNames,bn as carryExecutorAccount,qn as classifyError,_i as clearDelegatedCredential,Ui as clearDelegatedSession,zi as cloudLinkUrl,qt as cloudNodeReleaseUrl,Gn as combineSignals,Js as compareSemver,fl as completeCloudLink,vl as completeDeviceEnrolment,Vi as connectCloud,al as connectCloudWithAccount,vi as contextCapabilityGrantedOp,Ci as contextCapabilityRevokedOp,nn as contextDetachedOp,sn as contextMetadataSetOp,hs as createAccountAdmin,ko as createAccountRootSigner,io as createAdminApiClient,Rt as createAdminApiClientFromHttpClient,Ze as createAttestedSealedFetch,Su as createAuthApiClient,eo as createAuthApiClientFromHttpClient,Vu as createBrowserAdminApiClient,vu as createBrowserAuthApiClient,Ae as createBrowserHttpClient,ft as createDelegatedContext,us as createDelegatedPrivateContext,Fe as createHttpClient,at as createLocalStorageNonceSource,An as createMemoryNonceSource,un as createMeroClient,Yl as createMeroJs,fs as createNodeAdmin,Wu as createNodeAdminApiClient,Cu as createNodeAuthApiClient,wt as createNodeHttpClient,Ir as createProofAuthorizer,St as createProofSigner,cr as createQuoteVerifier,sl as createRecoveringNonceSource,Ls as createRetryableMethod,Qo as createSealedFetch,mc as createSignedReleaseSealedFetch,Bt as createSignedReleaseVerifier,$n as createTimeoutSignal,Kn as createUniversalHttpClient,xr as createdSubgroupId,fr as creationInitHash,Lr as defaultAdmitters,Me as defaultAudience,Te as defaultCapabilitiesSetOp,ye as delegatedGovernance,Pt as deviceCertPayload,Xi as deviceEnrolmentUrl,Xn as deviceScopePayload,au as discoverLocalNodes,gt as encodeGroupInvitation,Sn as encodeSignedInvitation,zo as fetchAttestedTransportKey,Ht as fetchNodeRelease,Lt as fetchNodeReleaseVersion,ht as fetchRegistryBundles,Li as forgetMethodKinds,Dn as foundDelegatedNamespace,Zt as foundedNamespaceId,So as generateAccountRoot,Sr as generateSessionKey,Un as governGroup,On as governRoot,yr as governanceOpHash,Rr as groupCreatedOp,Cs as groupDeleteOp,Xt as groupDeletedOp,Hr as groupInvitationHash,Ne as groupMetadataSetOp,Yt as groupReparentedOp,ce as hasCap,Lu as hexEncodeUtf8,mr as intentHash,Fs as isSettled,os as joinAsAccount,kn as joinWithNode,oe as jsonCodec,Ke as knownRelays,He as latestPublishedVersion,Hi as learnRelayNodeKey,ji as listDelegatedContexts,Fi as listDelegatedNamespaces,Us as localNodeUrl,Ue as login,mn as markContextNonceSpent,Pe as memberAddedOp,tn as memberCapabilitySetOp,an as memberJoinedOpenOp,it as memberLeftOp,on as memberMetadataSetOp,Jt as memberRemovedOp,zt as memberRoleSetOp,Qn as mintDeviceId,en as namespaceCreatedOp,bt as namespaceOfGroup,Os as nodeEndpoint,li as nodeReleaseVersionFromImage,pt as normaliseAccount,Yr as ownerOpDigest,Xr as ownerOpSigningPayload,jn as parseAuthCallback,bi as parseCreationWarrant,Yn as parseDeviceCredential,wi as parseGovernanceWarrant,no as parseWarrantNonce,Or as persistedNonces,Mr as pinRelayNodeKey,Pr as presenceStatementBytes,Ms as probeNodeHealth,hl as readCloudLinkCallback,Oi as readDelegatedCredential,Ur as readDelegatedSession,Rl as readEnrolmentCallback,hn as readPinnedRelayNodeKey,B as readRelayMap,to as redeemInvitation,Bi as relayForContext,yt as rememberGroupNamespace,me as rememberRelay,rr as reportDataOf,Vn as requestBodyHash,ss as resolveApplicationIdFromRegistry,Rn as resolveRelayFromInvitation,fn as resolveRelayNodeKey,Y as resolveRoot,Nt as resolveRootPair,Ds as rootGuardedOpBytes,xn as routingProofHeaders,Mi as saveDelegatedCredential,Ni as saveDelegatedSession,mt as selectLatestBundle,Ou as shouldRetain,zn as signAccountHaClaim,ze as signAccountLink,Ut as signAccountLogin,sa as signAccountOwnershipClaim,Vt as signCreationWarrant,Ro as signDeviceCert,vo as signDeviceScope,rt as signGovernanceWarrant,Cn as signGroupInvitation,ln as signLoginStatement,En as signMemberJoinOp,Ts as signOwnerOpProof,vt as signRequest,kr as signRequestProof,Wi as signRoutingChallenge,jt as signWarrant,jc as signedPath,go as signerFromCryptoKey,xe as signerFromSecret,Ii as stateHash,De as subgroupCreation,rn as subgroupVisibilitySetOp,It as subscribePresence,Qt as targetApplicationSetOp,ks as teeAdmissionPolicyOp,Es as teeAuthoringPolicyOp,Is as teeReleaseAdmissionPolicyOp,vs as transferOwnershipOp,Jo as transportKeyBinding,pi as trustSignedRelease,lr as trustedMeasurementsFromReleases,Tt as verifyDeviceCredential,ci as verifySignedNodeRelease,Hn as withCap,At as withRetry,Tu as withoutCap};
|
|
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 Hs=new Set(["token_reuse","token_revoked"]);function Ls(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=Ls(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:no(this.headers),bodyText:this.bodyText}}},te=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 no(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}function qs(t){try{return new URL(t).pathname}catch{let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}}var Ve=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:no(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((A,v)=>{d[v]=A})):d=u;let l=n?.method||"GET";if(this.transport.authorizeRequest){let A=n?.body;if(A!==void 0&&typeof A!="string"&&!(A 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:A}))}let g={method:l,headers:d},w=n?.body instanceof ReadableStream||typeof n?.body=="object"&&n?.body!==null&&"getReader"in n.body&&!(n.body instanceof Blob);(n?.body!==void 0&&!w||n?.body!==void 0&&w&&r===0)&&(g.body=n.body);let x;if(r>0&&o!==void 0){let A=n?.timeoutMs||this.transport.timeoutMs;if(A){let v=Date.now()-s,I=Math.max(0,A-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 A=await this.transport.getProof({method:g.method??"GET",path:qs(a),body:g.body});A&&(d["X-Calimero-Proof"]=A)}try{let A=await this.transport.fetch(a,g);if(!A.ok){let v=await this.getBodyText(A),I=new T(A.status,A.statusText,a,A.headers,v),P=A.headers.get("x-auth-error");if((A.status===401||A.status===403)&&P&&Hs.has(P)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new te(P,A.status,A.statusText,a,A.headers,v)}let j=n?.signal?.aborted===!0;if(A.status===401&&this.transport.refreshToken&&P==="token_expired"&&r<1&&!w&&!j)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 N=Date.now()-s;if(S-N<=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(A,n?.parse)}catch(A){throw A instanceof T||A instanceof Error&&A.message.includes("onTokenRefresh")?A:new T(0,"Network Error",a,new Headers,A instanceof Error?A.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 We(t){return new Ve(t)}function xe(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 We(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 We(r)}function Hn(t){return typeof window<"u"?xe(t):At(t)}function Bs(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 js(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,!Bs(r,n-o))throw r;let a=js(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 Fs(t,e={}){return async(...n)=>xt(()=>t(...n),e)}var ce=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 Je=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 Je;return new ce(e)}function Tu(t){let e=new Je;return new ce(e)}function Du(t){let e=new Je;return new ce(e)}function ro(t,e){return new ce(t)}var O={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},Uu={NONE:0,JOIN_ONLY:O.CAN_JOIN_OPEN_SUBGROUPS,CONTRIBUTOR:O.CAN_CREATE_CONTEXT|O.CAN_INVITE_MEMBERS|O.CAN_JOIN_OPEN_SUBGROUPS,COLLABORATOR:O.CAN_CREATE_CONTEXT|O.CAN_INVITE_MEMBERS|O.CAN_JOIN_OPEN_SUBGROUPS|O.CAN_CREATE_SUBGROUP|O.CAN_DELETE_SUBGROUP|O.CAN_MANAGE_VISIBILITY};function Ou(...t){let e=0;for(let n of t)if(typeof n=="number")e|=n;else if(Object.prototype.hasOwnProperty.call(O,n))e|=O[n];else throw new Error(`unknown capability: ${String(n)}`);return e>>>0}function Mu(t){return Object.keys(O).filter(e=>le(t,O[e]))}function le(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 Vs={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 Ws(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 Js(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=Js(t),n;return e!==void 0?n=Ws(e):t instanceof TypeError?n="unreachable":n="unknown",{kind:n,status:e,retryable:Vs[n],message:qn(t)}}function zs(t){return t.status!=="failed"||!t.retryable}function Hu(t){return!zs(t)}function Qs(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 Ys(t,e){let{kind:n,status:r}=Bn(t),o=Qs(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 oo(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}=Ys(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 io(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 Xs(t,e){let[n,r]=so(t),[o,i]=so(e),a=n.split("."),s=o.split("."),c=Math.max(a.length,s.length);for(let g=0;g<c;g++){let w=ao(a[g]??"0",s[g]??"0");if(w!==0)return w}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 w=ao(u[g],d[g]);if(w!==0)return w}return 0}function so(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 ao(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 Zs(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 ue=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 Zs(r.toString(),"versions",n)).json();return(Array.isArray(i)?i:[]).map(a=>a.appVersion).filter(a=>typeof a=="string").sort((a,s)=>Xs(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 oo({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 io(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 io(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(le(n,O.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:n};let r=Ln(n,O.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(le(r,O.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:r};let o=Ln(r,O.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 ue(xe(t))}function Zu(t){return new ue(At(t))}function co(t){return new ue(Hn(t))}function vt(t,e){return new ue(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 lo=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 F(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 ne(t){let e=p(t,"deviceSecret",32),n=m(lo,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 uo(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 re(t){let e=p(t,"deviceSecret",32),n=m(lo,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 ea=new TextEncoder().encode("calimero.auth.request.v1"),ta=new TextEncoder().encode("calimero.auth.request.body.v1");function po(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(ta,[e])}async function Ct(t){let e=await ne(t.signerSecret),n=await Wn(t.body),r=C(t.issuedAt),o=C(t.expiresAt),i=new TextEncoder,a=await k(ea,[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(po(t.method),po(t.path),n,r,o,s))}function St(t){let e=F(t.credential,"credential"),n=F(t.request,"request signature"),r=t.session===void 0?new Uint8Array([0]):m(new Uint8Array([1]),F(t.session,"session statement"));return f(m(e,r,n))}function na(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:na(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 ze=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 ra=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function go(t){return t.type!==void 0&&ra.has(t.type)}var oa=new Set(["token_reuse","token_revoked"]),ia=new Set([401,403]),sa=1e4;function mo(t){let e=t.headers.get("x-auth-error");return!e||!ia.has(t.status)?null:oa.has(e)?e:null}var q=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=>{go(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=mo(n),o=await n.text().catch(()=>{});throw r?new te(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 te)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")),sa);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=mo(c),d=await c.text().catch(()=>{});return u?new te(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 oe=It;function ie(){return{encode(t){return Array.from(new TextEncoder().encode(JSON.stringify(t)))},decode(t){return JSON.parse(new TextDecoder().decode(new Uint8Array(t)))}}}var Qe=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,n,r=ie()){await Jn(this.httpClient,"set_ephemeral",{contextId:e,state:r.encode(n)})}subscribe(e,n,r=ie()){return Pt(this.sse,e,n,r)}};function Pt(t,e,n,r=ie()){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 aa=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function ho(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 Re(t,e="secret"){let n=p(t,e,32),r=m(aa,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 ho(a)}return yo(o,i)}async function fo(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 yo(t,n)}function yo(t,e){return{publicKey:e,async sign(n){try{return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},t,n))}catch(r){throw ho(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 Re(t,n);throw new Error(`${n} or signer is required`)}var ca=new TextEncoder().encode("calimero.mdma.account-ownership-claim.v1\0"),la=6e4,bo=5*6e4,wo=1024,xo="mdma:enable-ha-namespace",Ro="mdma:enable-ha-namespace-as-account";function Ao(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 vo(t,e,n,r){if(r!==void 0&&!(r.length>0&&r.length<=wo))throw new Error(`relayUrl must be a non-empty string of at most ${wo} characters`);let o=t.ttlMs??la;if(!(o>0&&o<=bo))throw new Error(`ttlMs must be in (0, ${bo}]`);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)),w=>w.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(ca,l));return{kind:"account",credential:t.credential,signed_payload:Ao(l),signature:Ao(g)}}async function ua(t){if(!t.subject)throw new Error("subject must be the cloud login email");return vo(t,xo,t.subject)}async function Qn(t){return vo(t,Ro,void 0,t.relayUrl)}var da=new TextEncoder().encode("calimero.device.cert.v1"),pa=new TextEncoder().encode("calimero.account.genesis.v1"),ga=new TextEncoder().encode("calimero.device.id.v1"),ve=2,ma=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(ga,[n,e]);return f(m(e,r.subarray(0,16)))}async function Tt(t){return k(da,[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 Co(t){return m(new Uint8Array([ve]),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 So(t){let e=await E(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await V(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=Co({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",ma);if(e[0]!==ve)throw new Error(`this credential has account genesis version ${e[0]}, not ${ve} \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 V(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 uo(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 V(f(await re(t)))}async function V(t){return f(await k(pa,[m(new Uint8Array([ve]),p(t,"rootPublicKey",32))]))}var ha=new TextEncoder().encode("calimero.device.scope.v1");async function Zn(t){return k(ha,[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 ko(t){let e=await E(t.rootSecret,t.signer,"rootSecret"),n=p(e.publicKey,"signer.publicKey",32),r=await V(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([ve]),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 fa=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),ya=new TextEncoder().encode("calimero.mdma.account-login.v1\0"),Ce=256,Eo=Ce/32,tr=(Ce+Eo)/11;async function Io(){let t=crypto.getRandomValues(new Uint8Array(Ce/8));return Oo(f(t),await _o(t))}async function Po(t){let e=Mo(t);return Oo(f(await Go(e)),e.join(" "))}async function nr(t){return p(t,"secret",32),{secret:t,publicKey:f(await re(t)),accountId:await Nt(t)}}async function To(){let t=crypto.getRandomValues(new Uint8Array(Ce/8)),e=await _o(t);return{...await No(t),phrase:e}}async function Do(t){return No(await Go(Mo(t)))}async function No(t){let e=await Re(f(t),"rootSecret");return t.fill(0),{publicKey:e.publicKey,accountId:await V(e.publicKey),signer:e}}async function Y(t){let e=typeof t=="string"?await Re(t,"rootSecret"):t;return Uo(e)}async function Ut(t,e){return Uo(await E(t,e,"rootSecret"))}async function Uo(t){return{signer:t,publicKey:t.publicKey,accountId:await V(t.publicKey)}}async function Ye(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(fa,new TextEncoder().encode(t.nonce)));return Ho(n)}async function Ot(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(ya,new TextEncoder().encode(t.nonce)));return Ho(n)}async function Oo(t,e){return{...await nr(t),phrase:e}}function Mo(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 _o(t){let e=Ko(t)+await $o(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 Go(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(Ce/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(Ce)!==await $o(n))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return n}async function $o(t){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Ko(e).slice(0,Eo)}function Ko(t){let e="";for(let n of t)e+=n.toString(2).padStart(8,"0");return e}function Ho(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var ba=new TextEncoder().encode("calimero.tee-attest.key-binding.v1"),Mt=new TextEncoder().encode("MOCK_TDX_QUOTE_V1"),wa=568;function Aa(...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 xa(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 Ra(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",Aa(ba,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:wa;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=Ra(s.boundPublicKey,"boundPublicKey"),u=xa(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 va="Noise_NK_25519_AESGCM_SHA256",ir=32,Ca=16,Sa=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(va),n=new Uint8Array(32);return n.set(e),new t(n)}async mixHash(e){this.h=await Ea(m(this.h,e))}async mixKey(e){let[n,r]=await Bo(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:qo(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:qo(this.n),additionalData:this.h},this.k,e));return this.n+=1,await this.mixHash(e),n}split(){return Bo(this.ck,new Uint8Array)}};async function jo(t,e,n){let r=await ar.initialize();await r.mixHash(e),await r.mixHash(t);let o=await ka(n);return await r.mixHash(o.publicKey),await r.mixKey(await Lo(o.privateKey,t)),{message1:m(o.publicKey,await r.encryptAndHash(new Uint8Array)),async finish(a){if(a.length<ir+Ca)throw new Error("Noise: message 2 is too short");let s=a.slice(0,ir);return await r.mixHash(s),await r.mixKey(await Lo(o.privateKey,s)),{payload:await r.decryptAndHash(a.slice(ir)),split:await r.split()}}}}async function ka(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(Sa,t),{name:"X25519"},!0,["deriveBits"]),n=await crypto.subtle.exportKey("jwk",e);return{privateKey:e,publicKey:Ia(n.x)}}async function Lo(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 qo(t){let e=new Uint8Array(12);return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}async function Ea(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 Bo(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 Ia(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 Jo="/sealed/v2/handshake",zo="/sealed/v2",Ze="application/vnd.calimero.sealed",cr=2,Pa=new TextEncoder().encode("calimero/sealed-http/v2"),Xe=16,Ta=1+Xe+8,Da=0,Na=1,Ua=2,Oa=1+64*1024+16,Ma=1024,_a=6e4,Ga="calimero.tee-attest.transport-key.v1",$a=[101,204,205,304],Qo=new TextEncoder,et=class extends Error{constructor(){super("The node no longer holds the attested transport key; attest again for the current one");this.name="StaleTransportKeyError"}},Se=class extends Error{constructor(n,r,o,i){super(o);this.status=n;this.code=r;this.retryAfterMs=i;this.name="SealedTransportError"}};async function Yo(t,e){let n=await crypto.subtle.digest("SHA-256",m(Qo.encode(Ga),t,e));return new Uint8Array(n)}async function Xo(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 Yo(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 de(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 Zo({baseUrl:t.baseUrl,transportPublicKey:()=>Xo(r,t.verify,{applicationId:t.applicationId,applicationHash:t.applicationHash}),fetch:e})}function Zo(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 Vo(o,r,await Fo(a))}catch(l){if(!(l instanceof et)||!i)throw l;return a=Promise.resolve().then(i),Vo(o,r,await Fo(a))}},u=async()=>{let l=s??d(void 0),g=await l;if(Date.now()<g.renewAt)return[g,l];let w=d(l);return[await w,w]},d=l=>{if(s===l){let g=c();s=g,g.catch(()=>{s===g&&(s=void 0)})}return s};return async(l,g)=>{let w=new Request(l,g),x=new URL(w.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 A=[];w.headers.forEach((h,y)=>A.push([y,h]));let v={method:w.method,path:x.pathname.slice(n.length)+x.search,headers:A},I=new Uint8Array(await w.arrayBuffer()),P=async h=>{let{requestId:y,header:S,envelope:N}=await Ha(h,v,I),_=await o(`${r}${zo}`,{method:"POST",headers:{"content-type":Ze},body:N,signal:w.signal});if(_.headers.get("content-type")!==Ze)throw await ti(_);return qa(_,h.responseKey,S,y)},[j,M]=await u();try{return await P(j)}catch(h){if(!(h instanceof Se)||h.code!=="unknown_session")throw h;return P(await d(M))}}}async function Fo(t){let e=await t;if(e.length!==32)throw new Error("transportPublicKey must be 32 bytes");return e}async function Vo(t,e,n){try{return await Wo(t,e,n)}catch(r){if(!(r instanceof Se)||r.code!=="busy")throw r;return await new Promise(o=>setTimeout(o,r.retryAfterMs??1e3)),Wo(t,e,n)}}async function Wo(t,e,n){let r=await jo(n,Pa),o=await t(`${e}${Jo}`,{method:"POST",headers:{"content-type":Ze},body:m(new Uint8Array([cr]),n,r.message1)});if(o.headers.get("content-type")!==Ze)throw await ti(o);let i=await ja(o,Ma);return Ka(r,i)}async function Ka(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!==Xe+4)throw new Error("The handshake reply is malformed");let i=r.slice(0,Xe),a=new DataView(r.buffer,r.byteOffset).getUint32(Xe,!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-_a,header(u){let d=new Uint8Array(Ta);return d[0]=cr,d.set(i,1),new DataView(d.buffer).setBigUint64(1+Xe,BigInt(u),!1),d}}}async function Ha(t,e,n){let r=t.nextRequestId;t.nextRequestId+=1;let o=t.header(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:ei(r,0),additionalData:o},t.requestKey,La(e,n));return{requestId:r,header:o,envelope:m(o,new Uint8Array(i))}}function ei(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 La(t,e){let n=Qo.encode(JSON.stringify(t)),r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,n.length,!1),m(r,n,e)}async function qa(t,e,n,r){if(!t.body)throw new Error("The sealed response has no body");let o=Ba(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:ei(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!==Da)throw new Error("The sealed response is malformed");let c=JSON.parse(new TextDecoder().decode(s.data));if($a.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===Na?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 Ba(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>Oa)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 ja(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 ti(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 et;let r=Number(t.headers.get("retry-after")),o=Number.isFinite(r)&&r>0?Math.min(r,5)*1e3:void 0;return new Se(t.status,e,n,o)}var Fa=/^[0-9a-f]{96}$/,Va=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"];function lr(t){let e=ke(t.allowedMrtd??[],"allowedMrtd"),n=(t.allowedMeasurements??[]).map((s,c)=>{let u=`allowedMeasurements[${c}]`;return Va.map(d=>ke([s?.[d]??""],`${u}.${d}`)[0]).join()}),r=[ke(t.allowedRtmr0??[],"allowedRtmr0"),ke(t.allowedRtmr1??[],"allowedRtmr1"),ke(t.allowedRtmr2??[],"allowedRtmr2"),ke(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=Ja(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 w;try{w=t.dcapVerify(l,g,Math.floor(i()/1e3))}catch(I){throw new Error(`The quote did not verify: ${I?.message??String(I)}`)}if(w.status==="Revoked"||!o.includes(w.status))throw new Error(`The platform's TCB status is ${w.status}, which is not accepted`);let x=Wa(w.report),A=[x.mrTd,x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].map(I=>f(I));if(n.length>0&&!n.includes(A.join()))throw new Error(`The measurements (MRTD ${A[0]}, RTMR0-3 ${A.slice(1).join(", ")}) are not an image this verifier trusts`);if(e.length>0&&!e.includes(A[0]))throw new Error(`MRTD ${A[0]} is not an image this verifier trusts`);if([x.rtMr0,x.rtMr1,x.rtMr2,x.rtMr3].forEach((I,P)=>{let j=r[P];if(j.length>0&&!j.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 ke(t,e){return t.map(n=>{let r=n.trim().toLowerCase();if(!Fa.test(r))throw new Error(`${e} holds ${JSON.stringify(n)}, which is not a 48-byte hex measurement`);return r})}function Wa(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 Ja(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 za=["UpToDate","SWHardeningNeeded","ConfigurationNeeded","ConfigurationAndSWHardeningNeeded","OutOfDate","OutOfDateConfigurationNeeded"];function ur(t,{profile:e}){if(t.length===0)throw new Error("No release given, so no image would be trusted");let n,r=t.map((o,i)=>{let a=o?.tag??`releases[${i}]`;if(o?.role!==void 0&&o.role!=="node")throw new Error(`${a} lists the measurements of a ${o.role}, not of a node image`);let s=o?.profiles?.[e];if(!s){let u=Object.keys(o?.profiles??{}).join(", ")||"none";throw new Error(`${a} has no profile ${JSON.stringify(e)} (it has: ${u})`)}let c=(s.allowed_tcb_statuses??["uptodate"]).map(u=>Qa(u,a));return n=n===void 0?c:n.filter(u=>c.includes(u)),{mrtd:s.mrtd,rtmr0:s.rtmr0,rtmr1:s.rtmr1,rtmr2:s.rtmr2,rtmr3:s.rtmr3}});if(!n||n.length===0)throw new Error("The releases given accept no TCB status in common");return{allowedMeasurements:r,allowedTcbStatuses:n}}function Qa(t,e){let n=za.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 ni=[{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"]}],ri=[{baseUrl:"https://rekor.sigstore.dev",logId:"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d",publicKey:"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",validFor:{start:"2021-01-12T11:53:27Z"}}];var Ya="1.2.840.10045.2.1",Xa={"1.2.840.10045.3.1.7":"P-256","1.3.132.0.34":"P-384"},Za={"P-256":32,"P-384":48},ec={"1.2.840.10045.4.3.2":"SHA-256","1.2.840.10045.4.3.3":"SHA-384"};function oi(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 Ie(t){let e=oi(t,0,t.length);if(e.end!==t.length)throw new Error("it has trailing bytes");return e}function G(t){let e=[];for(let n=t.start;n<t.end;){let r=oi(t.bytes,n,t.end);e.push(r),n=r.end}return e}function U(t,e,n){if(!t||t.tag!==e)throw new Error(`${n} is not where it should be`);return t}function se(t){return t.bytes.slice(t.start,t.end)}function $t(t){return t.bytes.slice(t.offset,t.end)}function Ee(t){let e=se(U(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 tc(t){let e=new TextDecoder().decode(se(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 dr(t){try{let[e,n,r,...o]=G(U(Ie(t),48,"The certificate"));if(o.length>0)throw new Error("it has fields after its signature");let i=G(U(e,48,"The signed part")),a=i[0]?.tag===160?1:0,[s,c,u,d,l,g,...w]=i.slice(a);U(s,2,"The serial number");let x=Ee(G(U(n,48,"The signature algorithm"))[0]);if(Ee(G(U(c,48,"The signature algorithm"))[0])!==x)throw new Error("it names two different signature algorithms");let v=ec[x];if(!v)throw new Error(`it is signed with ${x}, not ECDSA with SHA-256 or SHA-384`);let[I,P]=G(U(d,48,"The validity")).map(tc);if(P===void 0)throw new Error("its validity is incomplete");let[j,M]=G(U(g,48,"The public key"));U(M,3,"The public key");let[h,y]=G(U(j,48,"The key algorithm"));if(Ee(h)!==Ya)throw new Error("its key is not an elliptic-curve key");let S=Xa[Ee(y)];if(!S)throw new Error("its key is on a curve other than P-256 or P-384");let N=new Map,_=w.find(Q=>Q.tag===163);if(_){let[Q]=G(_);for(let Ae of G(U(Q,48,"The extensions"))){let L=G(U(Ae,48,"An extension"));if(L.length===3)U(L[1],1,"An extension's critical flag");else if(L.length!==2)throw new Error("it has a malformed extension");let Gn=Ee(L[0]);if(N.has(Gn))throw new Error(`it has extension ${Gn} twice`);N.set(Gn,se(U(L[L.length-1],4,"An extension value")))}}let _n=se(U(r,3,"The signature"));if(_n[0]!==0)throw new Error("its signature is not a whole number of bytes");return{der:t,tbs:$t(e),signatureHash:v,signature:_n.slice(1),issuer:$t(U(u,48,"The issuer")),subject:$t(U(l,48,"The subject")),notBefore:I,notAfter:P,spki:$t(g),curve:S,extensions:N}}catch(e){throw new Error(`The certificate is malformed: ${e.message}`)}}function ii(t){return G(U(Ie(t),48,"The list")).map(Ee)}function nc(t,e){let n=Za[e],r=G(U(Ie(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=se(U(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=nc(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 W(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 pr(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 W(n[0][1],e)}var rc="2.5.29.17",oc="2.5.29.37",ic="1.3.6.1.5.5.7.3.3",sc="1.3.6.1.4.1.57264.1.8",ac="1.3.6.1.4.1.57264.1.1",cc=134,lc=12,uc=48,dc=new TextEncoder,Pe=t=>new TextDecoder().decode(t);async function si(t,e,n,r){let{base64Signature:o,cert:i,rekorBundle:a}=hc(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=W(o,"The bundle signature"),u=pr(Pe(W(i,"The bundle certificate")),"The bundle certificate"),d=dr(u),l=ri.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=dc.encode(`{"body":${JSON.stringify(s.body)},"integratedTime":${s.integratedTime},"logID":${JSON.stringify(s.logID)},"logIndex":${s.logIndex}}`);if(!await Kt(W(l.publicKey,"The Rekor key"),"P-256","SHA-256",W(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(!li(x,l.validFor))throw new Error(`Rekor log ${l.baseUrl} was not in use at ${tt(x)}, when the entry says it was logged`);let A=fc(s.body),v=f(new Uint8Array(await crypto.subtle.digest("SHA-256",t)));if(A.hash!==v)throw new Error("The file's SHA-256 is not the one Rekor logged: the file is not the one signed");if(!gr(W(A.signature,"The logged signature"),c))throw new Error("The bundle's signature is not the one Rekor logged");let I=pr(Pe(W(A.publicKey,"The logged certificate")),"The logged certificate");if(!gr(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 pc(d,x),mc(d,n),{integratedTime:s.integratedTime}}async function pc(t,e){if(!ci(t,e))throw new Error(`The signing certificate was valid ${tt(t.notBefore)} to ${tt(t.notAfter)}, not at ${tt(e)} when Rekor logged it`);let n=[];for(let r of ni){let o=r.certChain.map(a=>dr(W(a,"A Fulcio certificate")));if(!await ai(t,o[0]))continue;let i=await gc(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 ${tt(e)}: ${n.join("; ")}`:"The signing certificate was not issued by a Fulcio CA in the Sigstore trust root")}async function gc(t,e,n){if(!li(n,e))return"the trust root says it was not issuing certificates then";for(let[r,o]of t.entries()){if(!ci(o,n))return`its certificate ${r} was not valid then`;let i=t[r+1]??o;if(!await ai(o,i))return`its certificate ${r} is not signed by the next`}}async function ai(t,e){return gr(t.issuer,e.subject)?Kt(e.spki,e.curve,t.signatureHash,t.signature,t.tbs):!1}function mc(t,e){let n=t.extensions.get(rc);if(!n)throw new Error("The signing certificate names no identity");let r=G(U(Ie(n),uc,"The subject alternative name")),o=r.filter(u=>u.tag===cc).map(u=>Pe(se(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(sc),a=t.extensions.get(ac),s=i?Pe(se(U(Ie(i),lc,"The OIDC issuer"))):a?Pe(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(oc);if(!c||!ii(c).includes(ic))throw new Error("The signing certificate is not for code signing")}function hc(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 fc(t){let e;try{e=JSON.parse(Pe(W(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 ci(t,e){return t.notBefore<=e&&e<=t.notAfter}function li(t,e){return Date.parse(e.start)<=t&&(e.end===void 0||t<=Date.parse(e.end))}function tt(t){return new Date(t).toISOString()}function gr(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var mr=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"}),yc=["mrtd","rtmr0","rtmr1","rtmr2","rtmr3"],Ht="https://cloud.calimero.network";async function di(t,e,n={}){let r=typeof t=="string"?new TextEncoder().encode(t):t;await si(r,e,{identity:n.identity??mr.identity,issuer:n.issuer??mr.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=>yc.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 pi(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 mi(t,e.fetch??fetch);if(n===void 0)throw new Error(`${gi(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 gi(t){return`${t.replace(/\/+$/,"")}/admin-api/tee/info`}async function mi(t,e){let n=gi(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 pi(o)}function Bt(t,e){return`${t.replace(/\/+$/,"")}/api/tee/node-releases/${nt(e,"version")}`}async function hi(t){let e=nt(t.minReleaseVersion,"minReleaseVersion"),n=nt(t.release?.version,"The release version"),r=await di(t.release.publishedMrtds,t.release.bundle,{expectedVersion:n,identity:t.identity,issuer:t.issuer});if(wc(n,e)<0)throw new Error(`Release ${n} is older than the minimum trusted, ${e}`);return ur([r],{profile:t.profile})}function jt(t){return nt(t.minReleaseVersion,"minReleaseVersion"),Object.assign(async n=>{let r=await hi({release:await t.release(),profile:t.profile,minReleaseVersion:t.minReleaseVersion,identity:t.identity,issuer:t.issuer});return lr({dcapVerify:t.dcapVerify,fetchCollateral:t.fetchCollateral,now:t.now,...r})(n)},{includeCollateral:!0})}function bc(t){let{baseUrl:e,releaseSource:n,releaseVersion:r,applicationId:o,applicationHash:i,fetch:a,...s}=t;r!==void 0&&nt(r,"releaseVersion");let c=a??((d,l)=>fetch(d,l));return de({baseUrl:e,verify:jt({...s,release:async()=>{let d=r===void 0?await qt(e,{fetch:c}):await mi(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 fi=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function nt(t,e){let n=typeof t=="string"?fi.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 wc(t,e){let[n,r]=ui(t),[o,i]=ui(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)],w=l&&g?Math.sign(Number(u)-Number(d)):l!==g?l?-1:1:u<d?-1:u>d?1:0;if(w!==0)return w}return 0}function ui(t){let e=fi.exec(t);return[[Number(e[1]),Number(e[2]),Number(e[3])],e[4]]}var Ac=new TextEncoder().encode("calimero.warrant.v2"),xc=new TextEncoder().encode("calimero.warrant.intent.v1"),yi=64,bi=256;async function hr(t,e){let n=new TextEncoder().encode(JSON.stringify(e));return k(xc,[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=fr(t.releaseVersion??""),s=ae(t.accountHeads,"accountHeads"),c=ae(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 hr(t.method,t.argsJson),w=C(t.nonce),x=C(t.notAfter),A=await k(Ac,[e,n,d,r,o,i,a,l,g,C(s.length),...s,C(c.length),...c,w,x]),v=rt(await u.sign(A));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,w,x,v))}function rt(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 fr(t){let e=new TextEncoder().encode(t);return Rc(e.length),e}function Rc(t){if(t>bi)throw new Error(`releaseVersion is ${t} bytes, over the ${bi} a node accepts`)}function ae(t,e){let n=t??[];if(n.length>yi)throw new Error(`${e} cites ${n.length} heads, over the ${yi} a node accepts`);return n.map((r,o)=>p(r,`${e}[${o}]`,32))}var vc=new TextEncoder().encode("calimero.context-creation-warrant.v1"),Cc=new TextEncoder().encode("calimero.context-creation.init.v1"),Vt=256;async function yr(t){let e=new TextEncoder().encode(JSON.stringify(t));return k(Cc,[e])}async function Sc(t){return k(vc,[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=wi(t.serviceName,"serviceName"),c=wi(t.name,"name"),u=ae(t.accountHeads,"accountHeads"),d=ae(t.governanceFloor,"governanceFloor"),l=await E(t.deviceSecret,t.signer,"deviceSecret"),g=p(l.publicKey,"signer.publicKey",32),w=await yr(t.initArgs),x=await Sc({group:e,seed:n,authorAccount:r,deviceKey:g,executor:o,executorKey:i,applicationId:a,serviceName:s,name:c,initHash:w,accountHeads:u,governanceFloor:d,nonce:t.nonce,notAfter:t.notAfter}),A=rt(await l.sign(x));return{warrant:f(m(e,n,r,g,o,i,a,Ai(s),Ai(c),w,R(u.length),...u,R(d.length),...d,C(t.nonce),C(t.notAfter),A)),seed:f(n)}}function xi(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 w=n.subarray(o,o+l);return o+=l,w},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 w=a(l);if(w>Vt)throw new Error(`${l} is ${w} bytes, over the ${Vt} a node accepts`);return new TextDecoder("utf-8",{fatal:!0}).decode(i(w,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 wi(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 Ai(t){return t===null?new Uint8Array([0]):m(new Uint8Array([1]),R(t.length),t)}var kc=new TextEncoder().encode("calimero.governance-warrant.v1"),Ec=new TextEncoder().encode("calimero.governance-warrant.op.v1"),Ic={group:0,root:1};async function br(t){return k(Ec,[new Uint8Array([wr(t.kind)]),t.bytes])}async function Pc(t){return k(kc,[t.scope,new Uint8Array([wr(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 ot(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=ae(t.accountHeads,"accountHeads"),a=ae(t.governanceFloor,"governanceFloor"),s=wr(t.op.kind),c=await E(t.deviceSecret,t.signer,"deviceSecret"),u=p(c.publicKey,"signer.publicKey",32),d=await br(t.op),l=await Pc({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=rt(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 Ri(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 w=n.subarray(o,o+l);return o+=l,w},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 wr(t){let e=Ic[t];if(e===void 0)throw new Error(`op kind must be 'group' or 'root', got ${String(t)}`);return e}var Tc={Admin:0,Member:1,ReadOnly:2},$={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},it={GroupCreated:0,GroupReparented:1,GroupDeleted:2,MemberJoinedOpen:7,NamespaceCreatedV2:9},Dc=new TextEncoder().encode("calimero.namespace.id.v1"),xr=new Uint8Array(32),Jt=R(0);function Ci(t){let e=Tc[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 Te(t,e){return{kind:"group",bytes:m(D($.MemberAdded),p(t,"member",32),Ci(e))}}function zt(t){return{kind:"group",bytes:m(D($.MemberRemoved),p(t,"member",32),xr,Jt)}}function st(t){return{kind:"group",bytes:m(D($.MemberLeft),p(t,"member",32),xr,Jt)}}function Qt(t,e){return{kind:"group",bytes:m(D($.MemberRoleSet),p(t,"member",32),Ci(e))}}var Nc=new TextEncoder().encode("calimero.subgroup.id.v1");async function Rr(t,e,n,r){return f(await k(Nc,[p(t,"admin",32),p(e,"parentId",32),new Uint8Array([n?1:0]),p(r,"salt",32)]))}function vi(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($.TargetApplicationSet),xr,p(t.applicationId,"applicationId",32),vi(t.package,"package"),vi(t.version,"version"))}}function De(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new Error(`capabilities must be a u32 bit mask, got ${String(t)}`);if(le(t,O.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($.DefaultCapabilitiesSet),R(t))}}function vr(t){return{kind:"root",bytes:m(D(it.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 Ne(t){let e=t.salt??f(crypto.getRandomValues(new Uint8Array(32))),n=await Rr(t.admin,t.parentId,t.restricted,e);return{groupId:n,salt:e,op:vr({...t,groupId:n,salt:e})}}function Xt(t,e){return{kind:"root",bytes:m(D(it.GroupReparented),p(t,"childGroupId",32),p(e,"newParentId",32))}}function Zt(t){return{kind:"root",bytes:m(D(it.GroupDeleted),p(t,"rootGroupId",32),Jt,Jt)}}async function en(t,e){return f(await k(Dc,[p(t,"founder",32),p(e,"salt",32)]))}function tn(t){let e=F(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(it.NamespaceCreatedV2),p(t.founder,"founder",32),e,p(t.salt,"salt",32))}}function Ar(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function Cr(t){return t===void 0?D(0):m(D(1),Ar(t))}function Sr(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])=>[Ar(o),Ar(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(le(t,O.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($.MemberCapabilitySet),p(t,"member",32),R(Uc(e,"capabilities")))}}function rn(t){return{kind:"group",bytes:m(D($.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($.SubgroupVisibilitySet),D(t==="open"?0:1))}}function Ue(t={}){return{kind:"group",bytes:m(D($.GroupMetadataSet),Cr(t.name),Sr(t.data))}}function sn(t,e={}){return{kind:"group",bytes:m(D($.MemberMetadataSet),p(t,"member",32),Cr(e.name),Sr(e.data))}}function an(t,e={}){return{kind:"group",bytes:m(D($.ContextMetadataSet),p(t,"contextId",32),Cr(e.name),Sr(e.data))}}function Si(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 ki(t,e,n){return{kind:"group",bytes:m(D($.ContextCapabilityGranted),p(t,"contextId",32),p(e,"member",32),Si(n))}}function Ei(t,e,n){return{kind:"group",bytes:m(D($.ContextCapabilityRevoked),p(t,"contextId",32),p(e,"member",32),Si(n))}}function cn(t){return{kind:"root",bytes:m(D(it.MemberJoinedOpen),p(t.member,"member",32),p(t.groupId,"groupId",32),F(t.credential,"credential"))}}var ln=300,pe=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"}},Oc=t=>new Promise(e=>setTimeout(e,t));function Mc(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 J=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??"";fr(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 pe(`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 pe(`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 pe(`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 ot({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:De(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 ot({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),w={namespaceId:g.groupId,salt:r,teeEnabled:g.teeEnabled??!1,...g.teeError?{teeError:g.teeError}:{}},x=w,A=v=>v instanceof Error?v.message:String(v);if(s)try{await this.govern({groupId:w.namespaceId,op:s}),x={...x,applicationSet:!0}}catch(v){x={...x,applicationSet:!1,applicationError:A(v)}}if(a)try{await this.govern({groupId:w.namespaceId,op:a}),x={...x,defaultCapabilitiesSet:!0}}catch(v){x={...x,defaultCapabilitiesSet:!1,defaultCapabilitiesError:A(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=Mc(a.headers);await Oc(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=_c(c);throw new pe(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 _c(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 ge=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 Gc=new TextEncoder().encode("calimero.auth.login.v1"),Ii={webOrigin:0,codeSigningId:1,cli:2};function Pi(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 $c(t){return m(Uint8Array.from([Ii[t.kind]]),Pi(t))}function Kc(t){let e=Uint8Array.from([Ii[t.kind]]);if(t.kind==="cli")return e;let n=Pi(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(Gc,[e,$c(t.audience),n,r,i,a,s]),u=await o.sign(c);return f(m(e,Kc(t.audience),n,r,i,a,s,u))}var Hc=300;async function kr(){let t=f(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:f(await re(t)),secret:t}}async function Oe(t){let e=t.nodeUrl.replace(/\/+$/,""),n=t.timeoutMs??1e4,r=async(g,w)=>{let x=new AbortController,A=setTimeout(()=>x.abort(),n),v;try{let P={...w,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(A)}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 kr(),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??Hc),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 Lc=3e4;function _e(){let t=globalThis.location?.origin;return t?{kind:"webOrigin",origin:t}:{kind:"cli"}}function qc(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 Me=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-Lc>e?this.session.accessToken:(this.pending||(this.pending=this.loginNow().finally(()=>{this.pending=null})),(await this.pending).accessToken)}async loginNow(){let e=await Oe({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=qc(e.accessToken),e}get events(){return this.sseClient||(this.sseClient=new q({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.sseClient}get ws(){return this.wsClient||(this.wsClient=new oe({baseUrl:this.config.nodeUrl,getAuthToken:()=>this.accessToken()})),this.wsClient}close(){this.sseClient?.close(),this.wsClient?.close()}};var X=t=>new TextEncoder().encode(t),Bc=X("calimero.auth.request.v1"),jc=X("calimero.auth.request.body.v1"),Er="X-Calimero-Proof",Fc=300;async function Ir(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"?X(t.body):t.body,i=await k(jc,[o]),a=Math.floor(t.now??Date.now()/1e3),s=a+(t.validForSeconds??Fc),c=await k(Bc,[X(e),X(n),i,C(a),C(s)]),u=await Vc(c,t);if(u.length!==64)throw new Error(`the signer returned ${u.length} bytes, not a 64-byte signature`);let d=m(R(X(e).length),X(e),R(X(n).length),X(n),i,C(a),C(s),u),l=Wc(r,"credential");return f(m(l,new Uint8Array([0]),d))}async function Vc(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 ne(e.deviceSecret);return new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,t))}function Wc(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 Pr(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 Ir({method:e,path:n,body:r,credential:t.credential,deviceSecret:t.deviceSecret,signer:t.signer,validForSeconds:t.validForSeconds});return{[Er]:o}}}function Jc(t){return new URL(t).pathname}var Ti=new TextEncoder().encode("calimero/presence/1");async function Di(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 Tr(t){return m(Ti,p(t.contextId,"contextId",32),p(t.author,"author",32),C(t.seq),C(t.sentAtMs),await Di(t.state))}var zc=2500,at=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??zc,this.now=e.now??Date.now}async set(e,n,r=ie()){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=ie()){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 Tr({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 Ni(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 Qc(t,e,n){let r=e?.nodeKey;return r?new Me({nodeUrl:e?.nodeUrl??t.relayUrl,nodeKey:r,accountProof:e?.accountProof??t.authorProof,audience:e?.audience??_e(),signer:e?.signer?async()=>e.signer:()=>t.authorSigner(),clientName:e?.clientName,ttlSeconds:e?.ttlSeconds,fetch:e?.fetch??n,timeoutMs:e?.timeoutMs}):null}var me=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 J?e.relay:new J({...e.relay,fetch:e.relay.fetch??o});if(this.relayObserver=Qc(i,e.observe,o),this.rpcTransport=new ge(i,this.relayObserver),this.relayUrl=i.relayUrl,e.proof&&(this.proofAuthorizer=Pr(e.proof)),e.session){let a=e.session;this.relayAdmin=co({baseUrl:i.relayUrl,getAuthToken:typeof a=="string"?async()=>a:a,fetch:o})}else if(this.proofAuthorizer){let a=this.proofAuthorizer;this.relayAdmin=vt(We({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 Ge(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 Ni("node connection","it holds a signing key and a relay URL, not a node");return this.nodeClient}get relay(){if(!(this.rpcTransport instanceof ge))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 q({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 at({relay:this.relay,events:()=>this.events})),this.relayPresence)}get cloud(){if(!this.nodeClient)throw Ni("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 me(t)}var Ur="calimero.delegated.connection",Or="calimero.delegated.credential";function Mr(){if(typeof sessionStorage>"u")return null;try{let t=sessionStorage.getItem(Ur);return t?JSON.parse(t):null}catch{return null}}function Mi(t){try{sessionStorage.setItem(Ur,JSON.stringify(t))}catch{}}function _i(){try{sessionStorage.removeItem(Ur)}catch{}}function Gi(){let t=Mr();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(Or);if(!e)return null;let n=JSON.parse(e);return!n.account||!n.credential||!n.deviceSecret?null:n}catch{return null}}function $i(t){try{sessionStorage.setItem(Or,JSON.stringify(t))}catch{}}function Ki(){try{sessionStorage.removeItem(Or)}catch{}}function _r(t){let e=gn(t);return{next:async()=>{let n=0n;try{n=Hi(t)}catch{n=0n}try{localStorage.setItem(e,String(n+1n))}catch{}return n}}}function gn(t){return`calimero.nonce.${t}`}function Hi(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{Hi(t)<=n&&localStorage.setItem(gn(t),String(n+1n))}catch{}}var Li="calimero.delegated.relay-node-key.";function Z(t){return t.replace(/\/+$/,"")}function Gr(t,e){localStorage.setItem(Li+Z(t),e.trim().toLowerCase())}function fn(t){try{let e=localStorage.getItem(Li+Z(t));return e&&/^[0-9a-f]{64}$/.test(e)?e:null}catch{return null}}function $r(t){try{let{hostname:e}=new URL(t);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"}catch{return!1}}var Yc="locked-read-only",Xc="2.3.99",Dr;function Zc(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 $e=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 Oi(t,e){try{return await e()}catch(n){throw n instanceof $e?n:new $e(t,n)}}function el(t){return async(e,n)=>{let r;try{r=await globalThis.fetch(e,n)}catch(o){throw t.failure=o,new $e(`reaching ${String(e)}`,o)}return r.ok||(t.failure??(t.failure=new Error(`${String(e)} answered HTTP ${r.status}`))),r}}function qi(t,e){return Object.assign(async r=>{let o=await Oi("loading the quote verifier",()=>(Dr??(Dr=import("@phala/dcap-qvl").then(i=>Zc(i),i=>{throw Dr=void 0,i})),Dr));return jt({dcapVerify:o,release:()=>Oi("fetching the release the relay runs",async()=>Lt(Bt(Ht,await qt(t,{fetch:e})))),profile:Yc,minReleaseVersion:Xc})(r)},{includeCollateral:!0})}async function Ke(t,e={}){let n=e.fresh?null:fn(t);if(n)return{kind:"learned",nodeKey:n};let r={failure:null},o=el(r);try{let i=$r(t),{nodeKey:a}=await Gt({relayUrl:t,allowMock:i,fetch:o,...i?{}:{verify:qi(t,o)}});return Gr(t,a),{kind:"learned",nodeKey:a}}catch(i){return i instanceof $e||r.failure?{kind:"unavailable",error:i}:{kind:"refused",error:i}}}async function yn(t){let e=await Ke(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 tl(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 Bi(t,e={}){let{signal:n}=e;for(let r=0;!n?.aborted;r+=1){let o=await Ke(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 tl(i,n)}return null}function nl(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 Nr=new Map;function ji(){Nr.clear()}async function rl(t){if(t.status!==403)return!1;try{return(await t.clone().json()).error?.code==="sealed_route_unguarded"}catch{return!1}}function ol(t){return t.headers.has("authorization")||new URL(t.url).pathname.startsWith("/auth/")}function il(t){let e=(o,i)=>globalThis.fetch(o,i),n=de({baseUrl:t,verify:qi(t,e),fetch:e}),r=!1;return async(o,i)=>{let a=new Request(o,i);if(r&&ol(a))return e(a);let s=await n(a.clone());return await rl(s)?(r||(r=!0,console.warn(`[mero-js] ${Z(t)} cannot guard logged-in calls sealed (no forward_auth); they go over its TLS until it does`)),e(a)):s}}function He(t){if($r(t))return;let e=Z(t),n=Nr.get(e);return n||(n=il(t),Nr.set(e,n)),n}function sl(t,e){let n=null,r=null;return async()=>{let o=n?nl(n):null;return n&&(o===null||o-Date.now()>3e4)?n:(r||(r=Oe({nodeUrl:t.relayUrl,fetch:He(t.relayUrl),node:e,deviceSecret:t.deviceSecret,accountProof:t.credential,audience:_e()}).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 Fi(){pn.clear()}function al(t){return typeof t=="object"&&t!==null&&t.status===409}function cl(t,e){let n=t.rpc,r=Z(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){al(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 ll(t){return new q({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 ul(t,e){let n=e.session?cl(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=ll(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:He(t.relayUrl),relay:{relayUrl:t.relayUrl,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:_r(t.relayUrl)},proof:{credential:t.credential,deviceSecret:t.deviceSecret},session:n?sl({...t,relayUrl:t.relayUrl},n):void 0,observe:n?{nodeKey:n}:void 0});return ul(r,{relayUrl:t.relayUrl,session:n!==null,attested:n!==null||$r(t.relayUrl)})}var Vi="calimero.delegated.relays.";function B(t){try{let e=localStorage.getItem(Vi+t),n=e?JSON.parse(e):{};return{namespaces:n.namespaces??{},contexts:n.contexts??{}}}catch{return{namespaces:{},contexts:{}}}}function Kr(t,e){try{localStorage.setItem(Vi+t,JSON.stringify(e))}catch{}}function he(t,e,n){let r=B(t),o=Z(e);n.namespaceId&&(r.namespaces[n.namespaceId]=o),n.contextId&&(r.contexts[n.contextId]=o),Kr(t,r)}function Wi(t,e){return B(t).contexts[e]??null}function wn(t,e){return e.executorAccount||!t?.executorAccount||!t.relayUrl||!e.relayUrl||Z(t.relayUrl)!==Z(e.relayUrl)?e:{...e,executorAccount:t.executorAccount}}function Le(t){let e=B(t.account),n=[t.relayUrl,...Object.values(e.namespaces),...Object.values(e.contexts)].filter(r=>typeof r=="string"&&r.length>0).map(Z);return[...new Set(n)]}async function Ji(t){let e=[],n=B(t.account);for(let r of Le(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 Kr(t.account,n),e}async function zi(t){var o,i;let e=[],n=new Set,r=B(t.account);for(let a of Le(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 Kr(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 ct(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 dl(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 pl(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 Qi(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 K({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=ml(r,t.namespaceId),i=await n.getNamespaceRelays(o.namespaceId),a=Hr(i);if(!a)throw new Error(hl(o,i));let s=new J({relayUrl:a.relayUrl,executorAccount:a.executorAccount,authorAccount:t.authorAccount,authorProof:t.authorProof,signer:e,nonces:t.nonces??fl(e.publicKey),ttlSeconds:t.ttlSeconds,fetch:t.seal?de({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 me({transport:"relay",relay:s,observe:{nodeKey:t.relayNodeKey??a.nodeKey,audience:t.observeAudience,fetch:t.fetch,timeoutMs:t.timeoutMs}})}}async function gl(t){let{root:e,authorAccount:n,...r}=t,o=await E(r.deviceSecret,r.signer,"deviceSecret"),i=await Y(e),s=await new K({cloudBaseUrl:t.cloudBaseUrl,onSession:t.onSession,fetch:t.fetch,timeoutMs:t.timeoutMs}).signInWithAccount(i.signer);return Qi({...r,deviceSecret:void 0,signer:o,sessionToken:s.sessionToken,authorAccount:n??i.accountId})}function ml(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 hl(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 fl(t){let e=`mero-js:warrant-nonce:${t}`;try{return ct(e)}catch{return xn(1)}}var yl=new TextEncoder().encode("calimero.mdma.routing-read.v1\0");async function Yi(t,e){p(e,"deviceSecret",32);let n=await ne(e),r=m(yl,new TextEncoder().encode(t)),o=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},n,r));return bl(o)}async function Rn(t,e){return{"X-Calimero-Credential":e.credential,"X-Calimero-Nonce":t.nonce,"X-Calimero-Signature":await Yi(t.nonce,e.deviceSecret)}}function bl(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e)}var wl="https://cloud.calimero.network";function Zi(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??wl);return e.searchParams.set("link-account",t.accountId),e.searchParams.set("callback-url",t.returnTo),e.toString()}function Al(t){throw window.location.assign(Zi(t)),new Error("redirecting to the cloud to authorise this link")}function xl(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw Xi(),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:(Xi(),{grant:r,account:o})}function Xi(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Rl(t){let e=await Y(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 K({cloudBaseUrl:t.cloudBaseUrl,fetch:t.fetch}).linkAccountWithGrant({grant:t.grant,signer:e.signer})}var vl="enrol-device",Cl="enrol-kem",Sl="callback-url",kl="state";function ns(t){ts(t.devicePublicKey,"devicePublicKey"),ts(t.kemPublicKey,"kemPublicKey"),Dl(t.returnTo),Tl(t.returnTo);let e=new URL(t.walletUrl);return e.searchParams.set(vl,t.devicePublicKey),e.searchParams.set(Cl,t.kemPublicKey),e.searchParams.set(Sl,t.returnTo),t.state&&e.searchParams.set(kl,t.state),e.toString()}function El(t){throw window.location.assign(ns(t)),new Error("redirecting to the wallet to approve this device")}function Il(t=window.location){let e=new URLSearchParams(t.hash.replace(/^#/,"")),n=e.get("error");if(n)throw es(),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;es();let a=e.get("state");return{credential:r,account:o,device:i,...a?{state:a}:{}}}function es(){typeof history>"u"||!history.replaceState||history.replaceState(null,"",location.pathname+location.search)}async function Pl(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!==fe(t.devicePublicKey))throw new Error(`this credential certifies device key ${e.signPublicKey}, but this app holds ${fe(t.devicePublicKey)} \u2014 it would sign with a key the certificate does not cover`);if(t.kemPublicKey!==void 0&&e.kemPublicKey!==fe(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!==fe(t.account))throw new Error(`the wallet reported account ${fe(t.account)}, but the credential names ${e.account}`);if(e.device!==fe(t.device))throw new Error(`the wallet reported device ${fe(t.device)}, but the credential names ${e.device}`);return{credential:t.credential,account:e.account,device:e.device,certificate:e}}function ts(t,e){if(!/^[0-9a-f]{64}$/.test(t))throw new Error(`${e} must be 64 lowercase hex characters`)}function fe(t){return t.trim().toLowerCase()}function rs(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 Tl(t){rs(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 Dl(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 gt(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){let e=[];for(let n of t??[])try{let r=new URL(n);(r.protocol==="http:"||r.protocol==="https:")&&e.push(n.replace(/\/+$/,""))}catch{}return e}function Ol(t,e){if(e.size===0)return!0;let n=gt(t.account);return n!==null&&e.has(n)}async function vn(t){let e=t.cloud??new K({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){let[l]=Ul(t.admitterAddrs);if(l){let g=(t.admitters??[]).map(gt).filter(w=>w!==null);return{ok:!0,relayUrl:l,admitUrl:`${l}/admin-api/namespaces/${t.namespaceId}/admit`,admitterAccount:g.length===1?g[0]:null,peerId:null,writable:!0,stale:!1,via:"invitation"}}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(gt).filter(l=>l!==null)),i=n.filter(l=>Ol(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,via:"cloud"}}var Cn=1440*60,qr={Admin:0,Member:1,ReadOnly:2};function mt(t){let e=t.admitters??[];return m(Lr(t.inviter_identity,"inviter_identity"),Lr(t.group_id,"group_id"),C(t.expiration_timestamp),Lr(t.secret_salt,"secret_salt"),new Uint8Array([t.invited_role]),R(e.length),...e.map((n,r)=>p(n,`admitters[${r}]`,32)))}async function Br(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",mt(t)))}function jr(t){return[...new Set(t.filter(n=>n.role==="Admin").map(n=>n.identity.toLowerCase()))].sort()}async function Sn(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=jr(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,w)=>p(g,`admitters[${w}]`,32));let i=t.invitedRole??qr.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??Cn,Cn);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 Br(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 Lr(t,e){if(t.length!==32)throw new Error(`${e} must be 32 bytes, got ${t.length}`);return new Uint8Array(t)}var Fr=24,Ml=new TextEncoder().encode("calimero.namespace.v1"),_l=0,os={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreatedV2:9,MemberJoinedViaTeeAttestation:10};function is(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 ss(t){let e=new TextEncoder().encode(t);return m(R(e.length),e)}function kn(t){let e=t.invitation,n=t.admitter_addrs??[];return m(mt(e),ss(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(ss),is(t.application_id,"application_id"),is(t.app_key,"app_key"))}async function En(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([os.MemberJoinedAt]),p(t.member,"member",32),kn(t.invitation),C(o),n):m(new Uint8Array([os.MemberJoined]),p(t.member,"member",32),kn(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([Fr]),p(t.namespaceId,"namespaceId",32),R(e.length),...e.map((g,w)=>p(g,`parentOpHashes[${w}]`,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=ct(`calimero.delegated.joinnonce.${t}`);return()=>e.next()}function as(t){return t.replace(/\/+$/,"")}async function In(t){let{account:e,credential:n,deviceSecret:r}=t.credential,o;try{o=await En({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??`${as(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:as(t.nodeUrl),account:e,credential:n,deviceSecret:r}}}async function Pn(t){let e=t.deps?.resolve??vn,n=t.deps?.join??In,r=null,o=t.nodeUrl,i;if(!o){let s=await e({namespaceId:t.namespaceId,admitters:t.invitation.invitation.admitters,admitterAddrs:t.invitation.admitter_addrs,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 cs(t,e,n,r){let i=await(r.bootstrap??Pn)({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&&he(t.account,i.session.relayUrl,{namespaceId:e}),r.onJoined(wn(t,i.session)),{namespaceId:e}}function ls(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 Vr(t,e){let n=ls(t),r=ls(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 us(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 Vr(e,s),signerId:s,version:a.appVersion}}function ps(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 gs(t,e){let n=B(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 Dn(t,e,n,r){return new J({relayUrl:e,authorAccount:t.account,authorProof:t.credential,deviceSecret:t.deviceSecret,nonces:n,fetch:r??He(e)})}async function yt(t,e,n={}){let r=gs(t,e.namespaceId),o=0n,i=await Dn(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),he(t.account,r,{namespaceId:e.namespaceId,contextId:i.contextId}),{contextId:i.contextId}}async function be(t,e,n={}){let r=gs(t,e.namespaceId);return Dn(t,r,ps(r,e.group),n.fetch).govern({groupId:e.group,op:e.op})}async function ms(t,e,n={}){let{groupId:r}=await be(t,{namespaceId:e.namespaceId,group:e.namespaceId,op:(await Ne({parentId:e.namespaceId,restricted:!0,admin:t.account})).op},n);for(let i of e.members)await be(t,{namespaceId:e.namespaceId,group:r,op:Te(i,"Member")},n);let{contextId:o}=await yt(t,{...e,groupId:r},n);return{contextId:o,groupId:r}}async function Nn(t,e={},n={}){let o=Le(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 Dn(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(he(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 ds(e)};let o=Object.entries(B(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 ds(e),a=await Dn(t,e,ps(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 ds(t){let e=await Ke(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 invitees can find this namespace",Tn={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 K({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 ye)return{haEnabled:!1,haError:Un};if(i instanceof z&&Tn[i.code]){let a=i.code==="ha_request_pending"?Bl(i):null,s=Tn[i.code];return{haEnabled:!1,haError:a?`${s} (waiting: ${a})`:s}}return{haEnabled:!1,haError:i instanceof Error?i.message:String(i)}}}async function qe(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 hs="calimero.delegated.group-namespace.",Wr=new Map;function fs(t){let e={};try{e=JSON.parse(localStorage.getItem(hs+t)??"{}")}catch{}return{...e,...Wr.get(t)}}function bt(t,e,n){Wr.set(t,{...Wr.get(t),[e]:n});try{let r=fs(t);r[e]=n,localStorage.setItem(hs+t,JSON.stringify(r))}catch{}}function wt(t,e){return B(t.account).namespaces[e]?e:fs(t.account)[e]}function ys(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 On(t,e,n){return be(t,{namespaceId:ys(t,e),group:e,op:n})}async function Mn(t,e,n){let r=ys(t,e);return be(t,{namespaceId:r,group:r,op:n})}var we=class extends Error{constructor(n){super(`${n} is not available for an account: it needs a node`);this.method=n;this.name="NotForAccountError"}},Be=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"}},je=class extends Error{constructor(n,r){super(r==="not-hosted"?`nobody could claim an invitation to ${n} yet: the namespace is not hosted in the cloud and has no relay in it, so an invitee with no node has no relay to be admitted through. Link this account to your cloud user in the wallet and enable HA for the namespace, then invite.`:`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"}},bs={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 ws(t,e={}){let{session:n,read:r,app:o}=t,i=e.govern?.group??On,a=e.govern?.root??Mn,s=e.createContext??yt,c=e.found??Nn,u=e.latestVersion??qe,d=e.signInvitation??Sn,l=e.join,g=e.routing;async function w(h,y){if(!l)throw new we("joinNamespace without a join handler");return l(h,y.invitation)}let x=()=>{if(r===null)throw new Be("this call");return r};async function A(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 A(y),i(h,y,S)),I=async(h,y,S)=>(await A(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 j(h,y){let S=y??String(await x().getContextGroup(h)),{members:N}=await x().listGroupMembers(S);return N.some(_=>_.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 we("createNamespace without a packageName");let y=o.packageVersion??await u(o.registryUrl??"https://apps.calimero.network",o.packageName),{namespaceId:S,haEnabled:N,haError:_}=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:N,..._!==void 0?{haError:_}:{}}},async createGroupInNamespace(h,y={}){let{op:S}=await Ne({parentId:h,restricted:y.visibility==="restricted",admin:n.account}),{groupId:N}=await I(n,h,S);return bt(n.account,N,h),y.groupName&&await v(n,N,Ue({name:y.groupName})),{groupId:N}},async addGroupMembers(h,y){for(let S of y.members)await v(n,h,Te(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,De(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,st(n.account))},async leaveNamespace(h){await v(n,h,st(n.account))},async getContextIdentitiesOwned(h){return{identities:await j(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:N}=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:N,memberPublicKey:n.account,groupId:h.groupId}},async createNamespaceInvitation(h){let[{members:y},S]=await Promise.all([x().listGroupMembers(h),x().getGroupInfo(h)]),N=y.filter(Q=>Q.role==="RelayTee").map(Q=>Q.identity.toLowerCase()),_;if(g){let Q=new Set(N.length>0?N:y.filter(L=>L.role==="Admin").map(L=>L.identity.toLowerCase())),Ae=null;try{Ae=(await g(h)).nodes}catch{}if(Ae!==null){if(Ae.length===0){if(N.length===0||!n.relayUrl)throw new je(h,"not-hosted");_=[n.relayUrl]}else if(!Ae.some(L=>L.account!==null&&Q.has(L.account.toLowerCase())))throw new je(h,"no-named-node")}}return{invitation:await d({groupId:h,inviterAccount:n.account,deviceSecret:n.deviceSecret,...N.length>0?{admitters:N}:{},..._?{admitterAddrs:_}:{},members:y,applicationId:S.targetApplicationId,appKey:S.appKey})}},async syncGroup(h){return{groupId:h,synced:!0}},async syncContext(){},joinNamespace:w,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"?w:y in bs?bs[y]:async()=>{throw new Be(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 we(y)}:Reflect.get(h,y,S)}})}function As(t,e={}){let{admin:n,app:r}=t,o=e.latestVersion??qe;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 Jr(t,e){return typeof t.can_execute=="boolean"?t.can_execute:e}function zr(t){return typeof t.tee_role=="string"&&t.tee_role!==""?t.tee_role:null}function Hr(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 z=class extends T{constructor(n,r,o,i,a,s){super(r,o,i,a,s);this.code=n;this.name="AccountHaRefusedError"}},ye=class extends z{constructor(){super(...arguments);this.name="AccountNotLinkedError"}};ye.CODE="account_not_linked";var lt=class extends z{constructor(){super(...arguments);this.name="AccountLinkedToSeveralUsersError"}};lt.CODE="account_linked_to_several_users";var ut=class extends z{constructor(){super(...arguments);this.name="HaRequestPendingError"}};ut.CODE="ha_request_pending";var dt=class extends z{constructor(){super(...arguments);this.name="UnknownRelayError"}};dt.CODE="unknown_relay";var pt=class extends z{constructor(){super(...arguments);this.name="RelayNotDialableError"}};pt.CODE="relay_not_dialable";var xs={409:[ye,lt,ut],422:[dt,pt]};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",K=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 Y(e),{nonce:o}=await this.getAccountLoginChallenge();return this.submitAccountLogin({rootPublicKey:r,nonce:o,signature:await Ot({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:zr(r),canExecute:Jr(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 Hr(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:zr(r),canExecute:Jr(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:zr(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:Jr(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&&xs[i.status]){let a=Yl(i.bodyText),s=xs[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 Y(e),{nonce:i}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:o,rootPublicKey:r,nonce:i,signature:await Ye({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 Ut(e.rootSecret,e.signer),i=await this.request("POST","/api/cloud/accounts/link",{body:{grant:e.grant,root_public_key:r,signature:await Ye({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 Nl(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 Qr(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 Ge=class{constructor(e){this.tokenData=null;this.refreshPromise=null;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());let n=typeof window<"u"&&"__TAURI_INTERNALS__"in window,r=eu(this.config.requestProof);this.httpClient=xe({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.tokenStore?.setTokens(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=ro(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 ze({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new q({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 Qe({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new K(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 oe({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:Qr(i,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Authentication failed: ${r instanceof Error?r.message:"Unknown error"}`)}}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){let n=this.tokenStore?.getTokens()??null;if(n?.refresh_token&&(this.tokenData=n,e&&n.access_token!==e))return n;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");try{let r=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token}),o=r.data.access_token;return this.tokenData={access_token:o,refresh_token:r.data.refresh_token,expires_at:Qr(o,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(r){throw new Error(`Token refresh failed: ${r instanceof Error?r.message:"Unknown error"}`)}}clearToken(){this.refreshPromise=null,this.tokenData=null,this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let n=e.expires_at||Qr(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:n},this.tokenStore?.setTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){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 Ge(t)}var Yr=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},ou="mero-tokens",Xr=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,Zr={transferOwnership:0,adminChanged:1,groupDelete:2,teeAdmissionPolicy:3,teeAuthoringPolicy:4,teeReleaseAdmissionPolicy:5},Fe={GroupDelete:14,TransferOwnership:21,TeeAuthoringPolicySet:33,TeeAdmissionPolicySetV2:37,TeeReleaseAdmissionPolicySetV2:38,RootGuarded:42},vs={AdminChanged:3,RootGuarded:12},lu={replica:0,relay:1},uu=new TextEncoder;function H(t){return new Uint8Array([t])}function Cs(t){let e=uu.encode(t);return m(R(e.length),e)}function ee(t){return m(R(t.length),...t.map(Cs))}function Ss(t){return H(t?1:0)}function ks(t){let e=lu[t??"replica"];if(e===void 0)throw new Error(`mode must be replica or relay, got ${String(t)}`);return H(e)}function Es(t){return{kind:"transferOwnership",plane:"group",bytes:m(H(Fe.TransferOwnership),p(t,"newOwner",32))}}function Is(){return{kind:"groupDelete",plane:"group",bytes:H(Fe.GroupDelete)}}function Ps(t){return{kind:"adminChanged",plane:"root",bytes:m(H(vs.AdminChanged),p(t,"newAdmin",32))}}function Ts(t){return{kind:"teeAuthoringPolicy",plane:"group",bytes:m(H(Fe.TeeAuthoringPolicySet),ee(t))}}function Ds(t){return{kind:"teeAdmissionPolicy",plane:"group",bytes:m(H(Fe.TeeAdmissionPolicySetV2),ee(t.allowedMrtd),ee(t.allowedRtmr0),ee(t.allowedRtmr1),ee(t.allowedRtmr2),ee(t.allowedRtmr3),ee(t.allowedTcbStatuses),Ss(t.acceptMock),ks(t.mode))}}function Ns(t){let e=t.minReleaseVersion===void 0?H(0):m(H(1),Cs(t.minReleaseVersion));return{kind:"teeReleaseAdmissionPolicy",plane:"group",bytes:m(H(Fe.TeeReleaseAdmissionPolicySetV2),ee(t.allowedProfiles),e,ee(t.allowedTcbStatuses),Ss(t.acceptMock),ks(t.mode))}}async function eo(t){return k(su,[t])}async function to(t){return k(iu,[p(t.account,"account",32),p(t.namespaceId,"namespaceId",32),p(t.groupId,"groupId",32),H(Us(t.kind)),t.opDigest,C(t.counter),R(t.keyEpoch)])}function Us(t){let e=Zr[t];if(e===void 0)throw new Error(`unknown owner-op kind ${String(t)}`);return e}var Rs=132;async function Os(t){let e=await re(t.rootSecret),n=m(H(cu),e),r=f(await k(au,[n])),o=t.keyEpoch??0,i=(t.chain??[]).map((d,l)=>{let g=F(d,`chain[${l}]`);if(g.length!==Rs)throw new Error(`chain[${l}] must be a ${Rs}-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 eo(t.op.bytes),s=await to({account:r,namespaceId:t.namespaceId,groupId:t.groupId,kind:t.op.kind,opDigest:a,counter:t.counter,keyEpoch:o}),c=await ne(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),H(Us(t.op.kind)),a,C(t.counter),R(o),u))}function Ms(t,e){let n=t.plane==="group"?Fe.RootGuarded:vs.RootGuarded;return m(H(n),t.bytes,F(e,"rootProof"))}var _s=[2428,2429,2528,2529],du="localhost",pu=2e3;function Gs(t){return`http://${du}:${t}`}function $s(t,e){let n=t.endsWith("/")?t:`${t}/`;return new URL(e,n).toString()}async function Ks(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=$s(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=_s,timeoutMs:n,signal:r}=t;return(await Promise.all(e.map(async i=>{let a=Gs(i);return await Ks(a,{timeoutMs:n,signal:r})?a:null}))).filter(i=>i!==null)}export{Ro as ACCOUNT_HA_AUDIENCE,xo as ACCOUNT_OWNERSHIP_AUDIENCE,z as AccountHaRefusedError,lt as AccountLinkedToSeveralUsersError,ye as AccountNotLinkedError,ue as AdminApiClient,ce as AuthApiClient,te as AuthRevokedError,O as CAPABILITIES,Uu as CAPABILITY_PRESETS,K as CloudClient,_s as DEFAULT_LOCAL_NODE_PORTS,Ht as DEFAULT_RELEASE_MIRROR,Qe as EphemeralClient,Jo as HANDSHAKE_PATH,Un as HA_ACCOUNT_NOT_LINKED_MESSAGE,Tn as HA_REFUSAL_MESSAGES,T as HTTPError,ut as HaRequestPendingError,qr as INVITED_ROLE,pe as IntentRefusedError,je as InvitationNotClaimableError,Xr as LocalStorageTokenStore,Cn as MAX_INVITATION_VALIDITY_SECS,Yr as MemoryTokenStore,me as MeroClient,Ge as MeroJs,mr as NODE_RELEASE_SIGNER,Be as NoRelayError,we as NotForAccountError,Zr as OWNER_OP_KIND,Ti as PRESENCE_DOMAIN,mn as RELAY_NODE_KEY_RETRY_MS,Er as REQUEST_PROOF_HEADER,J as RelayClient,pt as RelayNotDialableError,Me as RelayObserver,at as RelayPresenceClient,ge as RelayTransport,ze as RpcClient,Et as RpcError,Ze as SEALED_CONTENT_TYPE,zo as SEALED_PATH,Fr as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,Se as SealedTransportError,q as SseClient,et as StaleTransportKeyError,dt as UnknownRelayError,An as WarrantNonceExhaustedError,Rt as WarrantNonceRouteUnavailableError,Ve as WebHttpClient,oe as WsClient,Nt as accountForRoot,V as accountForRootPublicKey,Po as accountRootFromPhrase,nr as accountRootFromSecret,Do as accountRootSignerFromPhrase,Ps as adminChangedOp,Nl as admitterAddrsFromNetworkStatus,Vr as applicationIdForBundle,Ke as attemptRelayNodeKey,_t as attestKeyBinding,Gt as attestRelayNodeKey,dl as authorNonceLookup,Al as beginCloudLink,El as beginDeviceEnrolment,Pn as bootstrapFromInvitation,Vn as buildAuthLoginUrl,bn as buildDelegatedClient,rs as callbackIsForeign,St as callerProof,Ou as capMask,Mu as capNames,wn as carryExecutorAccount,Bn as classifyError,Ki as clearDelegatedCredential,_i as clearDelegatedSession,Zi as cloudLinkUrl,Bt as cloudNodeReleaseUrl,$n as combineSignals,Xs as compareSemver,Rl as completeCloudLink,Pl as completeDeviceEnrolment,Qi as connectCloud,gl as connectCloudWithAccount,ki as contextCapabilityGrantedOp,Ei as contextCapabilityRevokedOp,rn as contextDetachedOp,an as contextMetadataSetOp,ws as createAccountAdmin,To as createAccountRootSigner,co as createAdminApiClient,vt as createAdminApiClientFromHttpClient,de as createAttestedSealedFetch,Du as createAuthApiClient,ro as createAuthApiClientFromHttpClient,Xu as createBrowserAdminApiClient,Pu as createBrowserAuthApiClient,xe as createBrowserHttpClient,yt as createDelegatedContext,ms as createDelegatedPrivateContext,We as createHttpClient,ct as createLocalStorageNonceSource,xn as createMemoryNonceSource,dn as createMeroClient,ru as createMeroJs,As as createNodeAdmin,Zu as createNodeAdminApiClient,Tu as createNodeAuthApiClient,At as createNodeHttpClient,Pr as createProofAuthorizer,kt as createProofSigner,lr as createQuoteVerifier,pl as createRecoveringNonceSource,Fs as createRetryableMethod,Zo as createSealedFetch,bc as createSignedReleaseSealedFetch,jt as createSignedReleaseVerifier,Kn as createTimeoutSignal,Hn as createUniversalHttpClient,Rr as createdSubgroupId,yr as creationInitHash,jr as defaultAdmitters,_e as defaultAudience,De as defaultCapabilitiesSetOp,be as delegatedGovernance,Tt as deviceCertPayload,ns as deviceEnrolmentUrl,Zn as deviceScopePayload,gu as discoverLocalNodes,mt as encodeGroupInvitation,kn as encodeSignedInvitation,Xo as fetchAttestedTransportKey,Lt as fetchNodeRelease,qt as fetchNodeReleaseVersion,ft as fetchRegistryBundles,Fi as forgetMethodKinds,ji as forgetRelaySealing,Nn as foundDelegatedNamespace,en as foundedNamespaceId,Io as generateAccountRoot,kr as generateSessionKey,On as governGroup,Mn as governRoot,br as governanceOpHash,vr as groupCreatedOp,Is as groupDeleteOp,Zt as groupDeletedOp,Br as groupInvitationHash,Ue as groupMetadataSetOp,Xt as groupReparentedOp,le as hasCap,Wu as hexEncodeUtf8,hr as intentHash,zs as isSettled,cs as joinAsAccount,In as joinWithNode,ie as jsonCodec,Le as knownRelays,qe as latestPublishedVersion,Bi as learnRelayNodeKey,Ji as listDelegatedContexts,zi as listDelegatedNamespaces,Gs as localNodeUrl,Oe as login,hn as markContextNonceSpent,Te as memberAddedOp,nn as memberCapabilitySetOp,cn as memberJoinedOpenOp,st as memberLeftOp,sn as memberMetadataSetOp,zt as memberRemovedOp,Qt as memberRoleSetOp,Yn as mintDeviceId,tn as namespaceCreatedOp,wt as namespaceOfGroup,$s as nodeEndpoint,pi as nodeReleaseVersionFromImage,gt as normaliseAccount,eo as ownerOpDigest,to as ownerOpSigningPayload,Fn as parseAuthCallback,xi as parseCreationWarrant,Xn as parseDeviceCredential,Ri as parseGovernanceWarrant,io as parseWarrantNonce,_r as persistedNonces,Gr as pinRelayNodeKey,Tr as presenceStatementBytes,Ks as probeNodeHealth,xl as readCloudLinkCallback,Gi as readDelegatedCredential,Mr as readDelegatedSession,Il as readEnrolmentCallback,fn as readPinnedRelayNodeKey,B as readRelayMap,oo as redeemInvitation,Wi as relayForContext,He as relayTransportFetch,bt as rememberGroupNamespace,he as rememberRelay,or as reportDataOf,Wn as requestBodyHash,us as resolveApplicationIdFromRegistry,vn as resolveRelayFromInvitation,yn as resolveRelayNodeKey,Y as resolveRoot,Ut as resolveRootPair,Ms as rootGuardedOpBytes,Rn as routingProofHeaders,$i as saveDelegatedCredential,Mi as saveDelegatedSession,ht as selectLatestBundle,Hu as shouldRetain,Qn as signAccountHaClaim,Ye as signAccountLink,Ot as signAccountLogin,ua as signAccountOwnershipClaim,Wt as signCreationWarrant,So as signDeviceCert,ko as signDeviceScope,ot as signGovernanceWarrant,Sn as signGroupInvitation,un as signLoginStatement,En as signMemberJoinOp,Os as signOwnerOpProof,Ct as signRequest,Ir as signRequestProof,Yi as signRoutingChallenge,Ft as signWarrant,Jc as signedPath,fo as signerFromCryptoKey,Re as signerFromSecret,Di as stateHash,Ne as subgroupCreation,on as subgroupVisibilitySetOp,Pt as subscribePresence,Yt as targetApplicationSetOp,Ds as teeAdmissionPolicyOp,Ts as teeAuthoringPolicyOp,Ns as teeReleaseAdmissionPolicyOp,Es as transferOwnershipOp,Yo as transportKeyBinding,hi as trustSignedRelease,ur as trustedMeasurementsFromReleases,Dt as verifyDeviceCredential,di as verifySignedNodeRelease,Ln as withCap,xt as withRetry,_u as withoutCap};
|
|
3
3
|
//# sourceMappingURL=index.browser.mjs.map
|