@calimero-network/mero-js 19.5.0 → 19.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.
@@ -1,3 +1,3 @@
1
- function ee(s){let e=s.filter(Boolean);if(e.length===0)return;let t=AbortSignal;if(typeof t.any=="function")try{return t.any(e)}catch{}let n=new AbortController,r=i=>{n.abort(i.target.reason);for(let o of e)o.removeEventListener("abort",r)};for(let i of e){if(i.aborted)return AbortSignal.abort(i.reason);i.addEventListener("abort",r,{once:!0})}return n.signal}function te(s){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(s);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},s),e.signal}var Be=new Set(["token_reuse","token_revoked"]);function Je(s){if(s)try{let e=JSON.parse(s)?.error;if(typeof e=="string"&&e.trim()!=="")return e;let t=e?.message;if(typeof t=="string"&&t.trim()!=="")return t}catch{}}var b=class extends Error{constructor(t,n,r,i,o){let a=Je(o);super(a?`HTTP ${t} ${n}: ${a}`:`HTTP ${t} ${n}`);this.status=t;this.statusText=n;this.url=r;this.headers=i;this.bodyText=o;this.name="HTTPError"}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:Ce(this.headers),bodyText:this.bodyText}}},M=class extends b{constructor(t,n,r,i,o,a){super(n,r,i,o,a);this.reason=t;this.name="AuthRevokedError";this.message=`Authentication revoked (${t}): HTTP ${n} ${r}`}};function Ce(s){let e={};return s.forEach((t,n)=>{e[n]=t}),e}var H=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,n){return this.request(e,{...n,method:"POST",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...n?.headers}})}async put(e,t,n){return this.request(e,{...n,method:"PUT",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...n?.headers}})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}async patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...n?.headers}})}async head(e,t){let n=await this.makeRequest(e,{...t,method:"HEAD",parse:"response"});return{headers:Ce(n.headers),status:n.status}}async request(e,t){return this.makeRequest(e,t)}async makeRequest(e,t,n=0,r){let o=this.buildUrl(e),a=r??Date.now(),p=this.createAbortSignal(t),l=await this.buildHeaders(t?.headers),m;l instanceof Headers?(m={},l.forEach((u,T)=>{m[T]=u})):m=l;let h={method:t?.method||"GET",headers:m},g=t?.body instanceof ReadableStream||typeof t?.body=="object"&&t?.body!==null&&"getReader"in t.body&&!(t.body instanceof Blob);(t?.body!==void 0&&!g||t?.body!==void 0&&g&&n===0)&&(h.body=t.body);let y;if(n>0&&r!==void 0){let u=t?.timeoutMs||this.transport.timeoutMs;if(u){let T=Date.now()-a,P=Math.max(0,u-T);y=this.createAbortSignal({...t,timeoutMs:P})}else y=this.createAbortSignal(t)}else y=p;y&&(h.signal=y),this.transport.credentials!==void 0&&(h.credentials=this.transport.credentials),t?.mode!==void 0&&(h.mode=t.mode),t?.cache!==void 0&&(h.cache=t.cache),t?.redirect!==void 0&&(h.redirect=t.redirect),t?.referrer!==void 0&&(h.referrer=t.referrer),t?.referrerPolicy!==void 0&&(h.referrerPolicy=t.referrerPolicy),t?.integrity!==void 0&&(h.integrity=t.integrity),t?.keepalive!==void 0&&(h.keepalive=t.keepalive);try{let u=await this.transport.fetch(o,h);if(!u.ok){let T=await this.getBodyText(u),P=new b(u.status,u.statusText,o,u.headers,T),v=u.headers.get("x-auth-error");if((u.status===401||u.status===403)&&v&&Be.has(v)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new M(v,u.status,u.statusText,o,u.headers,T)}let G=t?.signal?.aborted===!0;if(u.status===401&&this.transport.refreshToken&&v==="token_expired"&&n<1&&!g&&!G)try{let A=this.refreshTokenPromise;A||(A=this.transport.refreshToken(),this.refreshTokenPromise=A);let Z=await A;if(!Z||Z.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 j=this.onTokenRefreshPromise;j||(j=this.transport.onTokenRefresh(Z),this.onTokenRefreshPromise=j),await j,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let be=t?.timeoutMs||this.transport.timeoutMs;if(be&&r!==void 0){let We=Date.now()-a;if(be-We<=0)throw P}return this.makeRequest(e,t,n+1,a)}catch(A){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,A instanceof Error&&A.message.includes("onTokenRefresh")?A:P}throw P}return this.parseResponse(u,t?.parse)}catch(u){throw u instanceof b||u instanceof Error&&u.message.includes("onTokenRefresh")?u:new b(0,"Network Error",o,new Headers,u instanceof Error?u.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let t=this.transport.baseUrl;return e.startsWith("/")?`${t.endsWith("/")?t.slice(0,-1):t}${e}`:`${t.endsWith("/")?t:`${t}/`}${e}`}createAbortSignal(e){let t=[];this.transport.defaultAbortSignal&&t.push(this.transport.defaultAbortSignal),e?.signal&&t.push(e.signal);let n=e?.timeoutMs||this.transport.timeoutMs;return n&&t.push(te(n)),t.length>0?ee(t):void 0}async buildHeaders(e){let t={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let n=await this.transport.getAuthToken();n&&n.trim()!==""&&(t.Authorization=`Bearer ${n}`)}catch{}return e&&(e instanceof Headers?e.forEach((n,r)=>{t[r]=n}):Array.isArray(e)?e.forEach(([n,r])=>{t[n]=r}):Object.assign(t,e)),t}async parseResponse(e,t){switch(t){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let n=await e.text();if(!n)return null;try{return JSON.parse(n)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${n.slice(0,200)}`)}}}}async getBodyText(e){try{let t=await e.text();return t.length>65536?t.slice(0,65536)+"...":t}catch{return""}}};function ne(s){return new H(s)}function _(s){let e={fetch:(t,n)=>globalThis.fetch(t,n),baseUrl:s.baseUrl,getAuthToken:s.getAuthToken,onTokenRefresh:s.onTokenRefresh,refreshToken:s.refreshToken,onAuthRevoked:s.onAuthRevoked,defaultHeaders:s.defaultHeaders,timeoutMs:s.timeoutMs,credentials:s.credentials,defaultAbortSignal:s.defaultAbortSignal};return ne(e)}function K(s){let e=s.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 n={fetch:e===globalThis.fetch?(r,i)=>globalThis.fetch(r,i):(r,i)=>e(r,i),baseUrl:s.baseUrl,getAuthToken:s.getAuthToken,onTokenRefresh:s.onTokenRefresh,refreshToken:s.refreshToken,onAuthRevoked:s.onAuthRevoked,defaultHeaders:s.defaultHeaders,timeoutMs:s.timeoutMs,credentials:s.credentials,defaultAbortSignal:s.defaultAbortSignal};return ne(n)}function se(s){return typeof window<"u"?_(s):K(s)}function Ve(s,e){if(e<=0)return!1;let n=s?.name;if(n==="TimeoutError")return!0;if(n==="AbortError")return!1;let r=s;if("status"in r&&typeof r.status=="number"){let i=r.status;return i>=500||i===429}return n==="TypeError"}function Fe(s){let t=250*Math.pow(2,s-1),n=(Math.random()-.5)*.4*t;return Math.max(0,t+n)}async function W(s,e={}){let{attempts:t=3}=e,n;for(let r=1;r<=t;r++)try{return await s(r)}catch(i){if(n=i,!Ve(n,t-r))throw n;let o=Fe(r),l=n.headers?.get?.("Retry-After");if(l){let m=parseInt(l,10);if(!isNaN(m))o=Math.max(o,m*1e3);else{let h=new Date(l);if(!isNaN(h.getTime())){let g=Math.max(0,h.getTime()-Date.now());o=Math.max(o,Math.min(g,6e4))}}}await new Promise(m=>setTimeout(m,o))}throw n||new Error("Retry failed without error")}function ze(s,e={}){return async(...t)=>W(()=>s(...t),e)}var D=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 t=await this.validateTokenGet(e);return{valid:t.status===200,headers:t.headers,status:t.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let t=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:t.status,headers:t.headers}}async revokeTokens(e){let t=await this.httpClient.post("/admin/revoke",e);if(!t.data)throw new Error("Revoke tokens response data is null");return t.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 t=await this.httpClient.post("/admin/keys",e);if(!t.data)throw new Error("Create root key response data is null");return t.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,t){return this.httpClient.delete(`/admin/keys/${e}/clients/${t}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${e}/permissions`)}async updateKeyPermissions(e,t){return this.httpClient.put(`/admin/keys/${e}/permissions`,{add:t.add,remove:t.remove})}};var $=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 Wt(s){let e=new $;return new D(e)}function Bt(s){let e=new $;return new D(e)}function Jt(s){let e=new $;return new D(e)}function Re(s,e){return new D(s)}function c(s){return s?.data}function Xe(s,e){let[t,n]=Ae(s),[r,i]=Ae(e),o=t.split("."),a=r.split("."),p=Math.max(o.length,a.length);for(let g=0;g<p;g++){let y=we(o[g]??"0",a[g]??"0");if(y!==0)return y}if(n===void 0&&i===void 0)return 0;if(n===void 0)return 1;if(i===void 0)return-1;let l=n.split("."),m=i.split("."),h=Math.max(l.length,m.length);for(let g=0;g<h;g++){if(g>=l.length)return-1;if(g>=m.length)return 1;let y=we(l[g],m[g]);if(y!==0)return y}return 0}function Ae(s){let e=s.split("+",1)[0],t=e.indexOf("-");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function we(s,e){let t=/^\d+$/.test(s),n=/^\d+$/.test(e);if(t&&n){let r=Number(s)-Number(e);return r<0?-1:r>0?1:0}return t?-1:n?1:s<e?-1:s>e?1:0}async function Qe(s,e,t){return W(async()=>{let n=await fetch(s,{signal:AbortSignal.timeout(1e4)});if(!n.ok){let r=new Error(`registry ${e} fetch failed (${n.status}) for ${t}`);throw r.status=n.status,r}return n},{attempts:3})}var I=class{constructor(e){this.httpClient=e}async healthCheck(){return c(await this.httpClient.get("/admin-api/health"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return c(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,t){let n=new URL("/api/v2/bundles",new URL(e).origin);n.searchParams.set("package",t);let i=await(await Qe(n.toString(),"versions",t)).json();return(Array.isArray(i)?i:[]).map(o=>o.appVersion).filter(o=>typeof o=="string").sort((o,a)=>Xe(a,o))}async installDevApplication(e){return c(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return c(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return c(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return c(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return c(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,t){let n=t?`?service_name=${encodeURIComponent(t)}`:"";return c(await this.httpClient.get(`/admin-api/applications/${e}/abi${n}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let t=await this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/versions`);return t?.data??t}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/latest`)}async createContext(e){let t={...e,initializationParams:e.initializationParams??[]};return c(await this.httpClient.post("/admin-api/contexts",t))}async deleteContext(e){return c(await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return c(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return c(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return c(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return c(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){let t=e?`/admin-api/contexts/sync/${e}`:"/admin-api/contexts/sync";await this.httpClient.post(t,{})}async resyncContext(e,t={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,t)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return c(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,t){await this.httpClient.post(`/admin-api/contexts/${e}/application`,t)}async getContextsWithExecutorsForApplication(e){let t=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${e}`);return Array.isArray(t)?t:t?.contexts??t?.data??[]}async uploadBlob(e){let t=new URLSearchParams;e.hash&&t.set("hash",e.hash),e.contextId&&t.set("context_id",e.contextId);let n=t.toString(),r=n?`/admin-api/blobs?${n}`:"/admin-api/blobs",i=c(await this.httpClient.request(r,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:i.blob_id,size:i.size}}async deleteBlob(e){let t=await this.httpClient.delete(`/admin-api/blobs/${e}`);return{blobId:t.blob_id,deleted:t.deleted}}async listBlobs(){return{blobs:c(await this.httpClient.get("/admin-api/blobs")).blobs.map(t=>({blobId:t.blob_id,size:t.size}))}}blobPath(e,t){if(!t?.contextId)return`/admin-api/blobs/${e}`;let n=new URLSearchParams({context_id:t.contextId});return`/admin-api/blobs/${e}?${n.toString()}`}async getBlob(e,t){return this.httpClient.get(this.blobPath(e,t),{parse:"arrayBuffer"})}async getBlobInfo(e,t){let{headers:n}=await this.httpClient.head(this.blobPath(e,t)),r=Number(n["content-length"]);return{blobId:n["x-blob-id"]??e,size:Number.isFinite(r)?r:0,hash:n["x-blob-hash"],mimeType:n["x-blob-mime-type"],source:n["x-blob-source"]}}async createContextAlias(e){return c(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return c(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return c(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return c(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return c(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return c(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return c(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return c(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return c(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return c(await this.httpClient.post(`/admin-api/alias/lookup/device/${encodeURIComponent(e)}`,{}))}async deleteDeviceAlias(e){return c(await this.httpClient.post(`/admin-api/alias/delete/device/${encodeURIComponent(e)}`,{}))}async listDeviceAliases(){return c(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return c(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return c(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return c(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let t=await this.getNodeIdentity();return{namespaceId:e,publicKey:t.publicKey,account:t.accountId}}async performIntent(e,t){return c(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,t))}async getIntentRelay(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/intents`))}async listNamespacesForApplication(e){return c(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return c(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return c(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,t??{}))}async admitJoin(e,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/admit`,t,{timeoutMs:65e3}))}async joinNamespace(e,t){let n=c(await this.httpClient.post(`/admin-api/namespaces/${e}/join`,t,{timeoutMs:65e3}));return n&&n.namespaceId===void 0&&n.groupId!==void 0?{...n,namespaceId:n.groupId}:n}async createGroupInNamespace(e,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,t??{}))}async listNamespaceGroups(e){return c(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async initAccountPairing(e){return c(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return c(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,t){return c(await this.httpClient.post(`/admin-api/account/devices/${e}/relink`,t??{}))}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,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/account/revoke`,t))}async getGroupInfo(e){return c(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 c(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/members`);if(!Array.isArray(t?.members)){let n=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${n}: missing or non-array \`members\` field`)}return t}async listGroupContexts(e){return c(await this.httpClient.get(`/admin-api/groups/${e}/contexts`))}async addGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members`,t)}async removeGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members/remove`,t)}async updateMemberRole(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/role`,n)}async getMemberCapabilities(e,t){return c(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/capabilities`))}async setMemberCapabilities(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/capabilities`,n)}async setDefaultCapabilities(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/default-capabilities`,t)}async setSubgroupVisibility(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/subgroup-visibility`,t)}async setTeeAdmissionPolicy(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-admission-policy`,t)}async getTeeAdmissionPolicy(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/settings/tee-admission-policy`);return t.data??t}async setGroupMetadata(e,t){await this.httpClient.put(`/admin-api/groups/${e}/metadata`,t)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${e}/metadata`))?.data??null}async setMemberMetadata(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/metadata`,n)}async getMemberMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/metadata`))?.data??null}async setContextMetadata(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/contexts/${t}/metadata`,n)}async getContextMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/contexts/${t}/metadata`))?.data??null}async syncGroup(e){return c(await this.httpClient.post(`/admin-api/groups/${e}/sync`,{}))}async upgradeGroup(e,t){return c(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,t))}async getGroupUpgradeStatus(e){return c(await this.httpClient.get(`/admin-api/groups/${e}/upgrade/status`))}async getMigrationStatus(e){let t=encodeURIComponent(e);return this.httpClient.get(`/admin-api/groups/${t}/migration-status`)}async getCascadeStatus(e){let t=encodeURIComponent(e);return c(await this.httpClient.get(`/admin-api/groups/${t}/cascade-status`))}async retryGroupUpgrade(e){return c(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,{}))}async reparentGroup(e,t){let n=await this.httpClient.post(`/admin-api/groups/${e}/reparent`,t);return n?.data??n}async listSubgroups(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/subgroups`);return t.subgroups??t.data??[]}async detachContextFromGroup(e,t){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${t}/remove`,{})}async createGroupInvitation(e,t){return c(await this.httpClient.post(`/admin-api/groups/${e}/invite`,t??{}))}async joinGroup(e){return c(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return c(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return c(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return c(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return c(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 getCertificate(){return this.httpClient.get("/admin-api/certificate",{parse:"text"})}async createGroup(e){return c(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,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-ownership-proof`,t)}async issueNamespaceOwnershipProof(e,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-namespace-ownership-proof`,t)}async setMemberAutoFollow(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/auto-follow`,n)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,{})}};function en(s){return new I(_(s))}function tn(s){return new I(K(s))}function nn(s){return new I(se(s))}function xe(s,e){return new I(s)}function re(s){try{let e=s.indexOf("#");if(e===-1)return null;let t=s.substring(e+1),n=new URLSearchParams(t),r=n.get("access_token");return r?{accessToken:r,refreshToken:n.get("refresh_token")??"",applicationId:n.get("application_id")??"",contextId:n.get("context_id")??"",contextIdentity:n.get("context_identity")??"",nodeUrl:n.get("node_url")??""}:null}catch{return null}}function ie(s,e){let t=new URLSearchParams;return t.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&t.set("permissions",e.permissions.join(",")),t.set("mode",e.mode),e.packageName&&(t.set("package-name",e.packageName),e.packageVersion&&t.set("package-version",e.packageVersion),e.registryUrl&&t.set("registry-url",e.registryUrl)),`${s.replace(/\/+$/,"")}/auth/login?${t.toString()}`}var B=class extends Error{constructor(e,t,n,r){super(t),this.name="RpcError",this.code=e,this.data=n,this.type=r}};async function oe(s,e,t){let n=await s.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:t});if(n.error){let r=n.error;throw new B(r.code??-1,r.message??r.type??"RPC error",r.data,r.type)}return n.result}var q=class{constructor(e){this.httpClient=e.httpClient}async execute(e){let t=await oe(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return t&&"output"in t?t.output:t}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 Ye=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function ve(s){return s.type!==void 0&&Ye.has(s.type)}var Ze=new Set(["token_reuse","token_revoked"]),U=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.closed=!1;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken,this.reconnectDelayMs=e.reconnectDelayMs??3e3}on(e,t){let n=e;if(n in this.listeners){let r=this.listeners[n];r.includes(t)||r.push(t)}}off(e,t){let n=e;if(n in this.listeners){let r=this.listeners[n],i=r.indexOf(t);i!==-1&&r.splice(i,1)}}onAppVersionChanged(e){let t=n=>{if(n.type!=="AppVersionChanged")return;let r=n.data;e({contextId:n.contextId,fromVersion:r?.fromVersion,toVersion:r?.toVersion})};return this.on("event",t),()=>this.off("event",t)}onMigrationEvent(e){let t=n=>{ve(n)&&e(n)};return this.on("event",t),()=>this.off("event",t)}emit(e,t){let n=e;if(n in this.listeners)for(let r of this.listeners[n])try{r(t)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=await this.getAuthToken(),t=`${this.baseUrl}/sse`,n=await fetch(t,{headers:{Authorization:`Bearer ${e}`,Accept:"text/event-stream"},signal:this.abortController.signal});if(!n.ok){let r=n.headers.get("x-auth-error"),i=await n.text().catch(()=>{});throw n.status===401&&r&&Ze.has(r)?new M(r,n.status,n.statusText,t,n.headers,i):new b(n.status,n.statusText,t,n.headers,i)}if(!n.body)throw new Error("SSE response has no body");this.readStream(n.body).catch(r=>{if(this.closed)return;let i=r instanceof Error?r:new Error(String(r));this.emit("error",i),this.scheduleReconnect()})}catch(e){if(this.closed)return;let t=e instanceof Error?e:new Error(String(e));this.emit("error",t),this.scheduleReconnect()}}}async readStream(e){let t=e.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:i,value:o}=await t.read();if(i)break;r+=n.decode(o,{stream:!0});let a=r.split(`
2
- `);r=a.pop()??"";for(let p of a)if(p.startsWith("data:")){let l=p.slice(5).trim();l&&this.handleMessage(l)}}if(r+=n.decode(),r.startsWith("data:")){let i=r.slice(5).trim();i&&this.handleMessage(i)}}catch(i){if(this.closed)return;let o=i instanceof Error?i:new Error(String(i));this.emit("error",o)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let t=JSON.parse(e);if(t.type==="connect"&&t.session_id){this.sessionId=t.session_id,this.emit("connect",t.session_id),(this.subscribedContextIds.size>0||this.subscribedGroupIds.size>0)&&this.sendSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]});return}if(!t.result)return;let n=t.result.data;if(Array.isArray(n))try{let r=new Uint8Array(n),i=new TextDecoder().decode(r);n=JSON.parse(i)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:n});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:n})}catch{}}async subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,n=(t.contextIds??[]).filter(i=>!this.subscribedContextIds.has(i)),r=(t.groupIds??[]).filter(i=>!this.subscribedGroupIds.has(i));for(let i of t.contextIds??[])this.subscribedContextIds.add(i);for(let i of t.groupIds??[])this.subscribedGroupIds.add(i);(n.length>0||r.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:n,groupIds:r})}async unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,n=(t.contextIds??[]).filter(i=>this.subscribedContextIds.has(i)),r=(t.groupIds??[]).filter(i=>this.subscribedGroupIds.has(i));for(let i of t.contextIds??[])this.subscribedContextIds.delete(i);for(let i of t.groupIds??[])this.subscribedGroupIds.delete(i);(n.length>0||r.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:n,groupIds:r})}async sendSubscription(e,t){try{let n=await this.getAuthToken(),r={};t.contextIds&&t.contextIds.length>0&&(r.contextIds=t.contextIds),t.groupIds&&t.groupIds.length>0&&(r.groupIds=t.groupIds);let i=await fetch(`${this.baseUrl}/sse/subscription`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({id:this.sessionId,method:e,params:r})});i.ok||this.emit("error",new Error(`SSE ${e} failed: ${i.status}`))}catch(n){this.emit("error",n instanceof Error?n:new Error(`SSE ${e} failed`))}}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 J=class J{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,t){let n=e;if(n in this.listeners){let r=this.listeners[n];r.includes(t)||r.push(t)}}off(e,t){let n=e;if(n in this.listeners){let r=this.listeners[n],i=r.indexOf(t);i!==-1&&r.splice(i,1)}}emit(e,t){let n=e;if(n in this.listeners)for(let r of this.listeners[n])try{r(t)}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 t=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${t}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=n=>{this.handleMessage(n.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 t=e instanceof Error?e:new Error(String(e));this.emit("error",t),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);if(!t.result)return;let n=t.result.data;if(Array.isArray(n))try{let r=new Uint8Array(n),i=new TextDecoder().decode(r);n=JSON.parse(i)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:n});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:n})}catch{}}subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let n of t.contextIds??[])this.subscribedContextIds.add(n);for(let n of t.groupIds??[])this.subscribedGroupIds.add(n);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.groupIds??[])})}unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let n of t.contextIds??[])this.subscribedContextIds.delete(n);for(let n of t.groupIds??[])this.subscribedGroupIds.delete(n);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.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,t){let n={};return e.length>0&&(n.contextIds=e),t.length>0&&(n.groupIds=t),n}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),J.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()}};J.MAX_BACKOFF_MS=3e4;var N=J;function V(){return{encode(s){return Array.from(new TextEncoder().encode(JSON.stringify(s)))},decode(s){return JSON.parse(new TextDecoder().decode(new Uint8Array(s)))}}}var L=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,t,n=V()){await oe(this.httpClient,"set_ephemeral",{contextId:e,state:n.encode(t)})}subscribe(e,t,n=V()){let r=i=>{let o=i;if(o.type!=="Ephemeral"||o.contextId!==e)return;let a=o.data;if(!a?.author)return;let p=!!a.removed,l={author:a.author,state:p||a.state===void 0?void 0:n.decode(a.state),removed:p};a.ageMs!==void 0&&(l.ageMs=a.ageMs),t(l)};return this.sse.on("event",r),this.sse.connect().catch(()=>{}),this.sse.subscribe([e]).catch(()=>{}),()=>{this.sse.off("event",r)}}};var et="https://cloud.calimero.network",tt="x-mdma-session-refresh",nt="x-mdma-session-expires",E=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||et).replace(/\/+$/,""),this.onSession=e.onSession;let t=e.fetch;this.fetchImpl=t?(n,r)=>t(n,r):(n,r)=>globalThis.fetch(n,r),this.timeoutMs=e.timeoutMs??1e4,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let t=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(t)}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(t=>({namespaceId:String(t.namespace_id??t.group_id??""),groupId:String(t.group_id??t.namespace_id??""),haStatus:String(t.ha_status??"none"),haEnabledAt:t.ha_enabled_at??null,contexts:Array.isArray(t.contexts)?t.contexts:[],fleetReplicas:t.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/relays`)).relays??[]).map(n=>({peerId:String(n.peer_id??""),relayUrl:n.relay_url??null,executorAccount:n.executor_account??null,status:String(n.status??""),authorshipReady:n.authorship_ready===!0,lastSeenAt:n.last_seen_at??null,confirmedAt:n.confirmed_at??null}))}async findExecutingRelay(e){return(await this.getNamespaceRelays(e)).find(n=>n.authorshipReady&&n.relayUrl!==null&&n.executorAccount!==null)??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(t=>({peerId:String(t.peer_id??""),relayUrl:t.relay_url??null,executorAccount:t.executor_account??null,canExecute:t.can_execute===!0,namespaces:(Array.isArray(t.namespaces)?t.namespaces:[]).map(n=>{let r=n;return{namespaceId:String(r.namespace_id??""),status:String(r.status??""),authorshipReady:r.authorship_ready===!0,fresh:r.fresh===!0,confirmedAt:r.confirmed_at??null,lastSeenAt:r.last_seen_at??null}})}))}async claimNamespace(e,t){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:t}})}async enableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:{}})}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 t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${t.toString()}`)}disableHA(e){let t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${t.toString()}`)}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,t,n={}){if(!n.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let r={Accept:"application/json"};n.body!==void 0&&(r["Content-Type"]="application/json"),!n.anonymous&&this.session&&(r.Authorization=`Bearer ${this.session.sessionToken}`);let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:r,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:i.signal})}catch(p){throw new b(0,p instanceof Error?p.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,p instanceof Error?p.message:String(p))}finally{clearTimeout(o)}if(this.adoptRollingRefresh(a),!a.ok){let p=await a.text().catch(()=>{});throw new b(a.status,a.statusText,`${this.baseUrl}${t}`,a.headers,p)}if(!(n.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let t=e.headers.get(tt);if(!t||!this.session)return;let n=e.headers.get(nt),r=Number(n);this.session={sessionToken:t,expiresAt:Number.isFinite(r)&&r>0?r:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};var st="mero-js:token-refresh";function rt(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function ae(s,e){try{let t=s.split(".");if(t.length===3){let n=t[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let r=JSON.parse(atob(n));if(typeof r.exp=="number")return r.exp*1e3}}catch{}return e}var F=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 t=typeof window<"u"&&"__TAURI_INTERNALS__"in window;this.httpClient=_({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async n=>{this.tokenData&&(this.tokenData.access_token=n,this.tokenStore?.setTokens(this.tokenData))},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(t?"omit":void 0)}),this.authClient=Re(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=xe(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 q({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new U({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new L({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new E(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 N({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let t=e||this.config.credentials;if(!t)throw new Error("No credentials provided for authentication");try{let n={auth_method:"user_password",public_key:t.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:t.username,password:t.password}},r=await this.authClient.generateTokens(n),i=r.data.access_token;return this.tokenData={access_token:i,refresh_token:r.data.refresh_token,expires_at:ae(i,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(n){throw new Error(`Authentication failed: ${n instanceof Error?n.message:"Unknown error"}`)}}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,t=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=t;try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}withRefreshLock(e){let t=rt();return t?t.request(st,e):e()}async performTokenRefreshLocked(e){let t=this.tokenStore?.getTokens()??null;if(t?.refresh_token&&(this.tokenData=t,e&&t.access_token!==e))return t;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");try{let n=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token}),r=n.data.access_token;return this.tokenData={access_token:r,refresh_token:n.data.refresh_token,expires_at:ae(r,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(n){throw new Error(`Token refresh failed: ${n instanceof Error?n.message:"Unknown error"}`)}}clearToken(){this.refreshPromise=null,this.tokenData=null,this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let t=e.expires_at||ae(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:t},this.tokenStore?.setTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return re(e)}static buildAuthLoginUrl(e,t){return ie(e,t)}};function it(s){return new F(s)}var ce=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},ot="mero-tokens",pe=class{constructor(e=ot){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let t=JSON.parse(e);return t&&t.access_token&&t.refresh_token?{access_token:t.access_token,refresh_token:t.refresh_token,expires_at:typeof t.expires_at=="number"?t.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 ke=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function C(s){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,s,!0),e}function R(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}function d(s,e,t){let n=s.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${n.length}`);let r=new Uint8Array(t);for(let i=0;i<t;i+=1)r[i]=Number.parseInt(n.slice(i*2,i*2+2),16);return r}function w(s){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(s),!0),e}function f(...s){let e=new Uint8Array(s.reduce((n,r)=>n+r.length,0)),t=0;for(let n of s)e.set(n,t),t+=n.length;return e}async function k(s,e){let t=[w(s.length),s];for(let n of e)t.push(w(n.length),n);return new Uint8Array(await crypto.subtle.digest("SHA-256",f(...t)))}async function S(s){let e=d(s,"deviceSecret",32),t=f(ke,e);try{return await crypto.subtle.importKey("pkcs8",t,{name:"Ed25519"},!1,["sign"])}catch(n){let r=n instanceof Error?`: ${n.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`"+r)}}async function x(s){let e=d(s,"deviceSecret",32),t=f(ke,e),n=await crypto.subtle.importKey("pkcs8",t,{name:"Ed25519"},!0,["sign"]),i=(await crypto.subtle.exportKey("jwk",n)).x;return Uint8Array.from(atob(i.replace(/-/g,"+").replace(/_/g,"/")),o=>o.charCodeAt(0))}var at=new TextEncoder().encode("calimero.warrant.v2"),ct=new TextEncoder().encode("calimero.warrant.intent.v1"),Te=64,pt="00".repeat(32);async function le(s,e){let t=new TextEncoder().encode(JSON.stringify(e));return k(ct,[new TextEncoder().encode(s),t])}async function z(s){let e=d(s.context,"context",32),t=d(s.authorAccount,"authorAccount",32),n=d(s.executor,"executor",32),r=d(s.appVersion??pt,"appVersion",32),i=Se(s.accountHeads,"accountHeads"),o=Se(s.governanceFloor,"governanceFloor"),a=await S(s.deviceSecret),p=await x(s.deviceSecret),l=new TextEncoder().encode(s.method),m=await le(s.method,s.argsJson),h=w(s.nonce),g=w(s.notAfter),y=await k(at,[e,t,p,n,r,l,m,w(i.length),...i,w(o.length),...o,h,g]),u=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},a,y));return R(f(e,t,p,n,r,C(l.length),l,m,C(i.length),...i,C(o.length),...o,h,g,u))}function Se(s,e){let t=s??[];if(t.length>Te)throw new Error(`${e} cites ${t.length} heads, over the ${Te} a node accepts`);return t.map((n,r)=>d(n,`${e}[${r}]`,32))}var lt=300,X=class extends Error{constructor(t,n,r){super(`relay refused the intent (HTTP ${r}): ${t}`);this.reason=t;this.retryable=n;this.status=r;this.name="IntentRefusedError"}},O=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,""),this.executorAccount=e.executorAccount;let t=e.fetch;this.fetchImpl=t?(n,r)=>t(n,r):(n,r)=>globalThis.fetch(n,r),this.timeoutMs=e.timeoutMs??1e4}async describe(e){let t=await this.json("GET",`/admin-api/contexts/${encodeURIComponent(e)}/intents`);return this.executorAccount=t.data.executorAccount,t.data}async execute(e,t,n={}){let r=this.executorAccount??(await this.describe(e)).executorAccount,i=await this.config.nonces.next(),o=this.config.ttlSeconds??lt,a=await z({context:e,authorAccount:this.config.authorAccount,executor:r,method:t,argsJson:n,nonce:i,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(o),deviceSecret:this.config.deviceSecret}),p=await this.json("POST",`/admin-api/contexts/${encodeURIComponent(e)}/intents`,{method:t,argsJson:n,warrant:a,authorProof:this.config.authorProof});return{rootHash:p.data.rootHash,returns:p.data.returns??null}}async json(e,t,n){let r={Accept:"application/json"};n!==void 0&&(r["Content-Type"]="application/json");let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:r,body:n===void 0?void 0:JSON.stringify(n),signal:i.signal})}catch(p){throw new b(0,p instanceof Error?p.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,p instanceof Error?p.message:String(p))}finally{clearTimeout(o)}if(!a.ok){let p=await a.text().catch(()=>"");if(a.status===400||a.status===403){let l=ut(p);throw new X(l,/nonce/i.test(l),a.status)}throw new b(a.status,a.statusText,`${this.baseUrl}${t}`,a.headers,p)}return await a.json()}};function ut(s){if(!s)return"no reason given";try{let e=JSON.parse(s);for(let t of[e.error,e.message])if(typeof t=="string"&&t)return t}catch{}return s}function ue(s=1){let e=BigInt(s);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let t=e;return e+=1n,Promise.resolve(t)}}}function de(s,e){let t=e??globalThis.localStorage;if(!t)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");return{next(){let n=t.getItem(s),r=0n;if(n!==null&&n!=="")try{let o=BigInt(n);o>0n&&(r=o)}catch{r=0n}let i=r+1n;return t.setItem(s,i.toString()),Promise.resolve(i)}}}async function dt(s){if(!s.sessionToken&&!s.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=new E({cloudBaseUrl:s.cloudBaseUrl,sessionToken:s.sessionToken,onSession:s.onSession,fetch:s.fetch,timeoutMs:s.timeoutMs});!s.sessionToken&&s.googleIdToken&&await e.signInWithGoogle(s.googleIdToken);let t=await e.getMyNamespaces(),n=ht(t,s.namespaceId),r=await e.getNamespaceRelays(n.namespaceId),i=r.find(a=>a.authorshipReady&&a.relayUrl!==null&&a.executorAccount!==null)??null;if(!i)throw new Error(mt(n,r));let o=new O({relayUrl:i.relayUrl,executorAccount:i.executorAccount,authorAccount:s.authorAccount,authorProof:s.authorProof,deviceSecret:s.deviceSecret,nonces:s.nonces??await gt(s.deviceSecret),ttlSeconds:s.ttlSeconds,fetch:s.fetch,timeoutMs:s.timeoutMs});return{cloud:e,relay:o,namespaceId:n.namespaceId,namespace:n,relayInfo:i,execute:(a,p,l)=>o.execute(a,p,l)}}function ht(s,e){if(e){let t=s.find(n=>n.namespaceId===e);if(!t)throw new Error(`this account owns no namespace ${e}; it owns: ${s.map(n=>n.namespaceId).join(", ")||"(none)"}`);return t}if(s.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(s.length>1)throw new Error(`this account owns ${s.length} namespaces \u2014 pass namespaceId to say which: ${s.map(t=>t.namespaceId).join(", ")}`);return s[0]}function mt(s,e){if(e.length===0)return s.haStatus==="enabled"?`namespace ${s.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${s.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let t=e.filter(n=>!n.authorshipReady);return t.length===e.length?`every relay on namespace ${s.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${t.map(n=>n.executorAccount??n.peerId).join(", ")||"the relay account"}`:`namespace ${s.namespaceId} has ${e.length} relay(s), but none reported both a URL and an executor account yet \u2014 retry shortly`}async function gt(s){let e=`mero-js:warrant-nonce:${R(await x(s))}`;try{return de(e)}catch{return ue(1)}}var ft=new TextEncoder().encode("calimero.device.cert.v1"),Pe=new TextEncoder().encode("calimero.account.genesis.v1"),yt=new TextEncoder().encode("calimero.device.id.v1"),he=2;async function De(s,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let t=d(s,"account",32);return R(await k(yt,[t,e]))}async function me(s){return k(ft,[d(s.account,"account",32),d(s.device,"device",32),d(s.signPublicKey,"signPublicKey",32),d(s.kemPublicKey,"kemPublicKey",32),C(s.keyEpoch),C(s.deviceEpoch)])}function Ie(s){return f(new Uint8Array([he]),s.rootPublicKey,C(0),d(s.account,"account",32),d(s.device,"device",32),d(s.signPublicKey,"signPublicKey",32),d(s.kemPublicKey,"kemPublicKey",32),C(s.keyEpoch),C(s.deviceEpoch),s.signature)}async function Ee(s){let e=await x(s.rootSecret),t=R(await k(Pe,[f(new Uint8Array([he]),e)])),n=0,r=await me({account:t,device:s.device,signPublicKey:s.signPublicKey,kemPublicKey:s.kemPublicKey,keyEpoch:n,deviceEpoch:s.deviceEpoch}),i=await S(s.rootSecret),o=new Uint8Array(await crypto.subtle.sign("Ed25519",i,r)),a=Ie({rootPublicKey:e,account:t,device:s.device,signPublicKey:s.signPublicKey,kemPublicKey:s.kemPublicKey,keyEpoch:n,deviceEpoch:s.deviceEpoch,signature:o});return R(a)}async function Me(s){let e=await x(s);return R(await k(Pe,[f(new Uint8Array([he]),e)]))}var fe=8,bt=new TextEncoder().encode("calimero.namespace.v1"),Ct=0,_e={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreated:9,MemberJoinedViaTeeAttestation:10};function ge(s,e){if(s.length!==32)throw new Error(`${e} must be 32 bytes, got ${s.length}`);return new Uint8Array(s)}function Ue(s,e){if(s==null)return new Uint8Array([0]);if(s.length!==32)throw new Error(`${e} must be 32 bytes, got ${s.length}`);return f(new Uint8Array([1]),new Uint8Array(s))}function Ne(s){let e=new TextEncoder().encode(s);return f(C(e.length),e)}function Q(s){let e=s.invitation,t=e.admitters??[],n=s.admitter_addrs??[];return f(ge(e.inviter_identity,"inviter_identity"),ge(e.group_id,"group_id"),w(e.expiration_timestamp),ge(e.secret_salt,"secret_salt"),new Uint8Array([e.invited_role]),C(t.length),...t.map((r,i)=>d(r,`admitters[${i}]`,32)),Ne(s.inviter_signature),s.inviter_account?f(new Uint8Array([1]),d(s.inviter_account,"inviter_account",32)):new Uint8Array([0]),C(n.length),...n.map(Ne),Ue(s.application_id,"application_id"),Ue(s.app_key,"app_key"))}async function Ge(s){let e=s.parentOpHashes??[],t=d(s.credential,"credential",s.credential.length/2),n=BigInt(s.invitation.invitation.expiration_timestamp??0)!==0n,r=s.joinedAt??BigInt(Math.floor(Date.now()/1e3)),i=n?f(new Uint8Array([_e.MemberJoinedAt]),d(s.member,"member",32),Q(s.invitation),w(r),t):f(new Uint8Array([_e.MemberJoined]),d(s.member,"member",32),Q(s.invitation),t),o=f(new Uint8Array([Ct]),i),a=await S(s.deviceSecret),p=await x(s.deviceSecret),l=f(new Uint8Array([fe]),d(s.namespaceId,"namespaceId",32),C(e.length),...e.map((g,y)=>d(g,`parentOpHashes[${y}]`,32)),p,w(s.nonce),o),m=new Uint8Array(await crypto.subtle.sign("Ed25519",a,f(bt,l))),h=new Uint8Array([0]);return R(f(l,m,h))}var Rt=new TextEncoder().encode("calimero.auth.login.v1"),He={webOrigin:0,codeSigningId:1,cli:2};function $e(s){let e=new TextEncoder;switch(s.kind){case"webOrigin":return e.encode(s.origin);case"codeSigningId":return e.encode(s.id);case"cli":return new Uint8Array(0)}}function At(s){return f(Uint8Array.from([He[s.kind]]),$e(s))}function wt(s){let e=Uint8Array.from([He[s.kind]]);if(s.kind==="cli")return e;let t=$e(s);return f(e,C(t.length),t)}async function Y(s){let e=d(s.node,"node",32),t=d(s.challenge,"challenge",32),n=d(s.sessionKey,"sessionKey",32),r=await S(s.deviceSecret),i=await x(s.deviceSecret),o=w(s.issuedAt),a=w(s.expiresAt),p=await k(Rt,[e,At(s.audience),t,n,i,o,a]),l=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},r,p));return R(f(e,wt(s.audience),t,n,i,o,a,l))}var xt=300;async function ye(){let s=R(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:R(await x(s)),secret:s}}function vt(s){switch(s.kind){case"webOrigin":return s.origin;case"codeSigningId":return s.id;case"cli":return"cli"}}async function qe(s){let e=s.nodeUrl.replace(/\/+$/,""),t=s.fetch??globalThis.fetch,n=s.timeoutMs??1e4,r=async(y,u)=>{let T=new AbortController,P=setTimeout(()=>T.abort(),n),v;try{v=await t(`${e}${y}`,{...u,signal:T.signal})}catch(A){throw new b(0,A instanceof Error?A.name:"NetworkError",`${e}${y}`,new Headers,A instanceof Error?A.message:String(A))}finally{clearTimeout(P)}let G=await v.text().catch(()=>"");if(!v.ok)throw new b(v.status,v.statusText,`${e}${y}`,v.headers,G);return G?JSON.parse(G):{}},i=await r("/auth/challenge",{method:"GET",headers:{Accept:"application/json"}}),o=i.challenge??i.data?.challenge;if(!o)throw new Error("the node issued no challenge");let a=await ye(),p=Math.floor(Date.now()/1e3),l=await Y({node:s.node,audience:s.audience,challenge:o,sessionKey:a.publicKey,issuedAt:p,expiresAt:p+(s.ttlSeconds??xt),deviceSecret:s.deviceSecret}),m=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:s.clientName??vt(s.audience),timestamp:p,provider_data:{challenge:o,login_statement:l,account_proof:s.accountProof}})}),h=m.access_token??m.data?.access_token,g=m.refresh_token??m.data?.refresh_token;if(!h)throw new Error("the node minted no session");return{accessToken:h,refreshToken:g??"",sessionKey:a.publicKey,sessionSecret:a.secret}}var gs={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};function fs(s,e){let t=e>>>0;return(s&t)>>>0===t}function ys(s,e){return(s|e)>>>0}function bs(s,e){return(s&~e)>>>0}var Le=[2428,2429,2528,2529],kt="localhost",Tt=2e3;function Oe(s){return`http://${kt}:${s}`}function je(s,e){let t=s.endsWith("/")?s:`${s}/`;return new URL(e,t).toString()}async function Ke(s,e={}){let{timeoutMs:t=Tt,signal:n}=e;if(n?.aborted)return!1;let r=new AbortController,i=()=>r.abort(),o=n;o&&o.addEventListener("abort",i,{once:!0});let a=setTimeout(()=>r.abort(),t);try{let p=je(s,"admin-api/health"),l=await fetch(p,{method:"GET",signal:r.signal});if(!l.ok)return!1;try{let m=await l.json(),h=m?.data?.status!==void 0?m?.data?.status:m?.status;return h===void 0?!0:typeof h=="string"&&h.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),o&&o.removeEventListener("abort",i)}}async function St(s={}){let{ports:e=Le,timeoutMs:t,signal:n}=s;return(await Promise.all(e.map(async i=>{let o=Oe(i);return await Ke(o,{timeoutMs:t,signal:n})?o:null}))).filter(i=>i!==null)}export{I as AdminApiClient,D as AuthApiClient,M as AuthRevokedError,gs as CAPABILITIES,E as CloudClient,Le as DEFAULT_LOCAL_NODE_PORTS,L as EphemeralClient,b as HTTPError,X as IntentRefusedError,pe as LocalStorageTokenStore,ce as MemoryTokenStore,F as MeroJs,O as RelayClient,q as RpcClient,B as RpcError,fe as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,U as SseClient,H as WebHttpClient,N as WsClient,Me as accountForRoot,ie as buildAuthLoginUrl,ee as combineSignals,Xe as compareSemver,dt as connectCloud,nn as createAdminApiClient,xe as createAdminApiClientFromHttpClient,Jt as createAuthApiClient,Re as createAuthApiClientFromHttpClient,en as createBrowserAdminApiClient,Wt as createBrowserAuthApiClient,_ as createBrowserHttpClient,ne as createHttpClient,de as createLocalStorageNonceSource,ue as createMemoryNonceSource,it as createMeroJs,tn as createNodeAdminApiClient,Bt as createNodeAuthApiClient,K as createNodeHttpClient,ze as createRetryableMethod,te as createTimeoutSignal,se as createUniversalHttpClient,me as deviceCertPayload,St as discoverLocalNodes,Q as encodeSignedInvitation,ye as generateSessionKey,fs as hasCap,le as intentHash,V as jsonCodec,Oe as localNodeUrl,qe as login,De as mintDeviceId,je as nodeEndpoint,re as parseAuthCallback,Ke as probeNodeHealth,Ee as signDeviceCert,Y as signLoginStatement,Ge as signMemberJoinOp,z as signWarrant,ys as withCap,W as withRetry,bs as withoutCap};
1
+ function oe(r){let e=r.filter(Boolean);if(e.length===0)return;let t=AbortSignal;if(typeof t.any=="function")try{return t.any(e)}catch{}let n=new AbortController,s=o=>{n.abort(o.target.reason);for(let i of e)i.removeEventListener("abort",s)};for(let o of e){if(o.aborted)return AbortSignal.abort(o.reason);o.addEventListener("abort",s,{once:!0})}return n.signal}function ie(r){if(typeof AbortSignal.timeout=="function")return AbortSignal.timeout(r);let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("Timeout","TimeoutError"))},r),e.signal}var ot=new Set(["token_reuse","token_revoked"]);function it(r){if(r)try{let e=JSON.parse(r)?.error;if(typeof e=="string"&&e.trim()!=="")return e;let t=e?.message;if(typeof t=="string"&&t.trim()!=="")return t}catch{}}var w=class extends Error{constructor(t,n,s,o,i){let a=it(i);super(a?`HTTP ${t} ${n}: ${a}`:`HTTP ${t} ${n}`);this.status=t;this.statusText=n;this.url=s;this.headers=o;this.bodyText=i;this.name="HTTPError"}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:Se(this.headers),bodyText:this.bodyText}}},_=class extends w{constructor(t,n,s,o,i,a){super(n,s,o,i,a);this.reason=t;this.name="AuthRevokedError";this.message=`Authentication revoked (${t}): HTTP ${n} ${s}`}};function Se(r){let e={};return r.forEach((t,n)=>{e[n]=t}),e}var G=class{constructor(e){this.transport=e;this.refreshTokenPromise=null;this.onTokenRefreshPromise=null}async get(e,t){return this.request(e,{...t,method:"GET"})}async post(e,t,n){return this.request(e,{...n,method:"POST",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...n?.headers}})}async put(e,t,n){return this.request(e,{...n,method:"PUT",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...n?.headers}})}async delete(e,t){return this.request(e,{...t,method:"DELETE"})}async patch(e,t,n){return this.request(e,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0,headers:{"Content-Type":"application/json",...n?.headers}})}async head(e,t){let n=await this.makeRequest(e,{...t,method:"HEAD",parse:"response"});return{headers:Se(n.headers),status:n.status}}async request(e,t){return this.makeRequest(e,t)}async makeRequest(e,t,n=0,s){let i=this.buildUrl(e),a=s??Date.now(),l=this.createAbortSignal(t),u=await this.buildHeaders(t?.headers),h;u instanceof Headers?(h={},u.forEach((d,P)=>{h[P]=d})):h=u;let m={method:t?.method||"GET",headers:h},f=t?.body instanceof ReadableStream||typeof t?.body=="object"&&t?.body!==null&&"getReader"in t.body&&!(t.body instanceof Blob);(t?.body!==void 0&&!f||t?.body!==void 0&&f&&n===0)&&(m.body=t.body);let b;if(n>0&&s!==void 0){let d=t?.timeoutMs||this.transport.timeoutMs;if(d){let P=Date.now()-a,S=Math.max(0,d-P);b=this.createAbortSignal({...t,timeoutMs:S})}else b=this.createAbortSignal(t)}else b=l;b&&(m.signal=b),this.transport.credentials!==void 0&&(m.credentials=this.transport.credentials),t?.mode!==void 0&&(m.mode=t.mode),t?.cache!==void 0&&(m.cache=t.cache),t?.redirect!==void 0&&(m.redirect=t.redirect),t?.referrer!==void 0&&(m.referrer=t.referrer),t?.referrerPolicy!==void 0&&(m.referrerPolicy=t.referrerPolicy),t?.integrity!==void 0&&(m.integrity=t.integrity),t?.keepalive!==void 0&&(m.keepalive=t.keepalive);try{let d=await this.transport.fetch(i,m);if(!d.ok){let P=await this.getBodyText(d),S=new w(d.status,d.statusText,i,d.headers,P),k=d.headers.get("x-auth-error");if((d.status===401||d.status===403)&&k&&ot.has(k)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new _(k,d.status,d.statusText,i,d.headers,P)}let H=t?.signal?.aborted===!0;if(d.status===401&&this.transport.refreshToken&&k==="token_expired"&&n<1&&!f&&!H)try{let A=this.refreshTokenPromise;A||(A=this.transport.refreshToken(),this.refreshTokenPromise=A);let se=await A;if(!se||se.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 W=this.onTokenRefreshPromise;W||(W=this.transport.onTokenRefresh(se),this.onTokenRefreshPromise=W),await W,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let Pe=t?.timeoutMs||this.transport.timeoutMs;if(Pe&&s!==void 0){let st=Date.now()-a;if(Pe-st<=0)throw S}return this.makeRequest(e,t,n+1,a)}catch(A){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,A instanceof Error&&A.message.includes("onTokenRefresh")?A:S}throw S}return this.parseResponse(d,t?.parse)}catch(d){throw d instanceof w||d instanceof Error&&d.message.includes("onTokenRefresh")?d:new w(0,"Network Error",i,new Headers,d instanceof Error?d.message:"Unknown error")}}buildUrl(e){if(e.startsWith("http://")||e.startsWith("https://"))return e;let t=this.transport.baseUrl;return e.startsWith("/")?`${t.endsWith("/")?t.slice(0,-1):t}${e}`:`${t.endsWith("/")?t:`${t}/`}${e}`}createAbortSignal(e){let t=[];this.transport.defaultAbortSignal&&t.push(this.transport.defaultAbortSignal),e?.signal&&t.push(e.signal);let n=e?.timeoutMs||this.transport.timeoutMs;return n&&t.push(ie(n)),t.length>0?oe(t):void 0}async buildHeaders(e){let t={...this.transport.defaultHeaders};if(this.transport.getAuthToken)try{let n=await this.transport.getAuthToken();n&&n.trim()!==""&&(t.Authorization=`Bearer ${n}`)}catch{}return e&&(e instanceof Headers?e.forEach((n,s)=>{t[s]=n}):Array.isArray(e)?e.forEach(([n,s])=>{t[n]=s}):Object.assign(t,e)),t}async parseResponse(e,t){switch(t){case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();case"response":return e;default:{let n=await e.text();if(!n)return null;try{return JSON.parse(n)}catch{throw new Error(`Expected a JSON response (status ${e.status}) but body was not JSON: ${n.slice(0,200)}`)}}}}async getBodyText(e){try{let t=await e.text();return t.length>65536?t.slice(0,65536)+"...":t}catch{return""}}};function ae(r){return new G(r)}function M(r){let e={fetch:(t,n)=>globalThis.fetch(t,n),baseUrl:r.baseUrl,getAuthToken:r.getAuthToken,onTokenRefresh:r.onTokenRefresh,refreshToken:r.refreshToken,onAuthRevoked:r.onAuthRevoked,defaultHeaders:r.defaultHeaders,timeoutMs:r.timeoutMs,credentials:r.credentials,defaultAbortSignal:r.defaultAbortSignal};return ae(e)}function J(r){let e=r.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 n={fetch:e===globalThis.fetch?(s,o)=>globalThis.fetch(s,o):(s,o)=>e(s,o),baseUrl:r.baseUrl,getAuthToken:r.getAuthToken,onTokenRefresh:r.onTokenRefresh,refreshToken:r.refreshToken,onAuthRevoked:r.onAuthRevoked,defaultHeaders:r.defaultHeaders,timeoutMs:r.timeoutMs,credentials:r.credentials,defaultAbortSignal:r.defaultAbortSignal};return ae(n)}function ce(r){return typeof window<"u"?M(r):J(r)}function at(r,e){if(e<=0)return!1;let n=r?.name;if(n==="TimeoutError")return!0;if(n==="AbortError")return!1;let s=r;if("status"in s&&typeof s.status=="number"){let o=s.status;return o>=500||o===429}return n==="TypeError"}function ct(r){let t=250*Math.pow(2,r-1),n=(Math.random()-.5)*.4*t;return Math.max(0,t+n)}async function V(r,e={}){let{attempts:t=3}=e,n;for(let s=1;s<=t;s++)try{return await r(s)}catch(o){if(n=o,!at(n,t-s))throw n;let i=ct(s),u=n.headers?.get?.("Retry-After");if(u){let h=parseInt(u,10);if(!isNaN(h))i=Math.max(i,h*1e3);else{let m=new Date(u);if(!isNaN(m.getTime())){let f=Math.max(0,m.getTime()-Date.now());i=Math.max(i,Math.min(f,6e4))}}}await new Promise(h=>setTimeout(h,i))}throw n||new Error("Retry failed without error")}function lt(r,e={}){return async(...t)=>V(()=>r(...t),e)}var I=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 t=await this.validateTokenGet(e);return{valid:t.status===200,headers:t.headers,status:t.status}}catch{return{valid:!1,headers:{},status:401}}}async validateTokenGet(e){let t=await this.httpClient.head("/auth/validate",{headers:{Authorization:`Bearer ${e}`}});return{status:t.status,headers:t.headers}}async revokeTokens(e){let t=await this.httpClient.post("/admin/revoke",e);if(!t.data)throw new Error("Revoke tokens response data is null");return t.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 t=await this.httpClient.post("/admin/keys",e);if(!t.data)throw new Error("Create root key response data is null");return t.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,t){return this.httpClient.delete(`/admin/keys/${e}/clients/${t}`)}async getKeyPermissions(e){return this.httpClient.get(`/admin/keys/${e}/permissions`)}async updateKeyPermissions(e,t){return this.httpClient.put(`/admin/keys/${e}/permissions`,{add:t.add,remove:t.remove})}};var $=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 un(r){let e=new $;return new I(e)}function pn(r){let e=new $;return new I(e)}function dn(r){let e=new $;return new I(e)}function Ie(r,e){return new I(r)}var L={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};function le(r,e){let t=e>>>0;return(r&t)>>>0===t}function ue(r,e){return(r|e)>>>0}function hn(r,e){return(r&~e)>>>0}function c(r){return r?.data}function ut(r,e){let[t,n]=De(r),[s,o]=De(e),i=t.split("."),a=s.split("."),l=Math.max(i.length,a.length);for(let f=0;f<l;f++){let b=Ee(i[f]??"0",a[f]??"0");if(b!==0)return b}if(n===void 0&&o===void 0)return 0;if(n===void 0)return 1;if(o===void 0)return-1;let u=n.split("."),h=o.split("."),m=Math.max(u.length,h.length);for(let f=0;f<m;f++){if(f>=u.length)return-1;if(f>=h.length)return 1;let b=Ee(u[f],h[f]);if(b!==0)return b}return 0}function De(r){let e=r.split("+",1)[0],t=e.indexOf("-");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function Ee(r,e){let t=/^\d+$/.test(r),n=/^\d+$/.test(e);if(t&&n){let s=Number(r)-Number(e);return s<0?-1:s>0?1:0}return t?-1:n?1:r<e?-1:r>e?1:0}async function pt(r,e,t){return V(async()=>{let n=await fetch(r,{signal:AbortSignal.timeout(1e4)});if(!n.ok){let s=new Error(`registry ${e} fetch failed (${n.status}) for ${t}`);throw s.status=n.status,s}return n},{attempts:3})}var D=class{constructor(e){this.httpClient=e}async healthCheck(){return c(await this.httpClient.get("/admin-api/health"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return c(await this.httpClient.post("/admin-api/install-application",e))}async getRegistryVersions(e,t){let n=new URL("/api/v2/bundles",new URL(e).origin);n.searchParams.set("package",t);let o=await(await pt(n.toString(),"versions",t)).json();return(Array.isArray(o)?o:[]).map(i=>i.appVersion).filter(i=>typeof i=="string").sort((i,a)=>ut(a,i))}async installDevApplication(e){return c(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return c(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return c(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return c(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return c(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,t){let n=t?`?service_name=${encodeURIComponent(t)}`:"";return c(await this.httpClient.get(`/admin-api/applications/${e}/abi${n}`))}async listPackages(){let e=await this.httpClient.get("/admin-api/packages");return e?.data??e}async listPackageVersions(e){let t=await this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/versions`);return t?.data??t}async getLatestPackageVersion(e){return this.httpClient.get(`/admin-api/packages/${encodeURIComponent(e)}/latest`)}async createContext(e){let t={...e,initializationParams:e.initializationParams??[]};return c(await this.httpClient.post("/admin-api/contexts",t))}async deleteContext(e){return c(await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return c(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return c(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return c(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return c(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){let t=e?`/admin-api/contexts/sync/${e}`:"/admin-api/contexts/sync";await this.httpClient.post(t,{})}async resyncContext(e,t={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,t)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return c(await this.httpClient.post("/admin-api/contexts/invite-specialized-node",e))}async updateContextApplication(e,t){await this.httpClient.post(`/admin-api/contexts/${e}/application`,t)}async getContextsWithExecutorsForApplication(e){let t=await this.httpClient.get(`/admin-api/contexts/with-executors/for-application/${e}`);return Array.isArray(t)?t:t?.contexts??t?.data??[]}async uploadBlob(e){let t=new URLSearchParams;e.hash&&t.set("hash",e.hash),e.contextId&&t.set("context_id",e.contextId);let n=t.toString(),s=n?`/admin-api/blobs?${n}`:"/admin-api/blobs",o=c(await this.httpClient.request(s,{method:"PUT",body:e.data,headers:{"Content-Type":"application/octet-stream"}}));return{blobId:o.blob_id,size:o.size}}async deleteBlob(e){let t=await this.httpClient.delete(`/admin-api/blobs/${e}`);return{blobId:t.blob_id,deleted:t.deleted}}async listBlobs(){return{blobs:c(await this.httpClient.get("/admin-api/blobs")).blobs.map(t=>({blobId:t.blob_id,size:t.size}))}}blobPath(e,t){if(!t?.contextId)return`/admin-api/blobs/${e}`;let n=new URLSearchParams({context_id:t.contextId});return`/admin-api/blobs/${e}?${n.toString()}`}async getBlob(e,t){return this.httpClient.get(this.blobPath(e,t),{parse:"arrayBuffer"})}async getBlobInfo(e,t){let{headers:n}=await this.httpClient.head(this.blobPath(e,t)),s=Number(n["content-length"]);return{blobId:n["x-blob-id"]??e,size:Number.isFinite(s)?s:0,hash:n["x-blob-hash"],mimeType:n["x-blob-mime-type"],source:n["x-blob-source"]}}async createContextAlias(e){return c(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return c(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return c(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return c(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return c(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return c(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return c(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return c(await this.httpClient.get("/admin-api/alias/list/application"))}async createDeviceAlias(e){return c(await this.httpClient.post("/admin-api/alias/create/device",{alias:e.alias,deviceId:e.deviceId}))}async lookupDeviceAlias(e){return c(await this.httpClient.post(`/admin-api/alias/lookup/device/${encodeURIComponent(e)}`,{}))}async deleteDeviceAlias(e){return c(await this.httpClient.post(`/admin-api/alias/delete/device/${encodeURIComponent(e)}`,{}))}async listDeviceAliases(){return c(await this.httpClient.get("/admin-api/alias/list/device"))}async listNamespaces(){return c(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return c(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return c(await this.httpClient.get("/admin-api/identity"))}async getNamespaceIdentity(e){let t=await this.getNodeIdentity();return{namespaceId:e,publicKey:t.publicKey,account:t.accountId}}async performIntent(e,t){return c(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,t))}async getIntentRelay(e){return c(await this.httpClient.get(`/admin-api/contexts/${e}/intents`))}async listNamespacesForApplication(e){return c(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return c(await this.httpClient.post("/admin-api/namespaces",e))}async deleteNamespace(e){return c(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,t??{}))}async admitJoin(e,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/admit`,t,{timeoutMs:65e3}))}async joinNamespace(e,t){let n=c(await this.httpClient.post(`/admin-api/namespaces/${e}/join`,t,{timeoutMs:65e3}));return n&&n.namespaceId===void 0&&n.groupId!==void 0?{...n,namespaceId:n.groupId}:n}async createGroupInNamespace(e,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,t??{}))}async listNamespaceGroups(e){return c(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async initAccountPairing(e){return c(await this.httpClient.post("/admin-api/account/pair-init",e))}async completeAccountPairing(e){return c(await this.httpClient.post("/admin-api/account/pair-complete",e))}async relinkAccountDevice(e,t){return c(await this.httpClient.post(`/admin-api/account/devices/${e}/relink`,t??{}))}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,t){return c(await this.httpClient.post(`/admin-api/namespaces/${e}/account/revoke`,t))}async getGroupInfo(e){return c(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 c(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:"{}",headers:{"Content-Type":"application/json"}}))}async listGroupMembers(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/members`);if(!Array.isArray(t?.members)){let n=String(e).replace(/[\r\n\t\s]/g,"").slice(0,64);throw new Error(`Invalid listGroupMembers response for group ${n}: missing or non-array \`members\` field`)}return t}async listGroupContexts(e){return c(await this.httpClient.get(`/admin-api/groups/${e}/contexts`))}async addGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members`,t)}async removeGroupMembers(e,t){await this.httpClient.post(`/admin-api/groups/${e}/members/remove`,t)}async updateMemberRole(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/role`,n)}async getMemberCapabilities(e,t){return c(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/capabilities`))}async setMemberCapabilities(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/capabilities`,n)}async setDefaultCapabilities(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/default-capabilities`,t)}async openToDelegatedExecution(e){let t=await this.getDefaultCapabilities(e);if(le(t,L.CAN_AUTHOR_ON_BEHALF))return{changed:!1,defaultCapabilities:t};let n=ue(t,L.CAN_AUTHOR_ON_BEHALF);return await this.setDefaultCapabilities(e,{defaultCapabilities:n}),{changed:!0,defaultCapabilities:n}}async grantAuthorship(e,t){let{capabilities:n}=await this.getMemberCapabilities(e,t);if(le(n,L.CAN_AUTHOR_ON_BEHALF))return{changed:!1,capabilities:n};let s=ue(n,L.CAN_AUTHOR_ON_BEHALF);return await this.setMemberCapabilities(e,t,{capabilities:s}),{changed:!0,capabilities:s}}async setSubgroupVisibility(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/subgroup-visibility`,t)}async setTeeAdmissionPolicy(e,t){await this.httpClient.put(`/admin-api/groups/${e}/settings/tee-admission-policy`,t)}async getTeeAdmissionPolicy(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/settings/tee-admission-policy`);return t.data??t}async setGroupMetadata(e,t){await this.httpClient.put(`/admin-api/groups/${e}/metadata`,t)}async getGroupMetadata(e){return(await this.httpClient.get(`/admin-api/groups/${e}/metadata`))?.data??null}async setMemberMetadata(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/metadata`,n)}async getMemberMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/members/${t}/metadata`))?.data??null}async setContextMetadata(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/contexts/${t}/metadata`,n)}async getContextMetadata(e,t){return(await this.httpClient.get(`/admin-api/groups/${e}/contexts/${t}/metadata`))?.data??null}async syncGroup(e){return c(await this.httpClient.post(`/admin-api/groups/${e}/sync`,{}))}async upgradeGroup(e,t){return c(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,t))}async getGroupUpgradeStatus(e){return c(await this.httpClient.get(`/admin-api/groups/${e}/upgrade/status`))}async getMigrationStatus(e){let t=encodeURIComponent(e);return this.httpClient.get(`/admin-api/groups/${t}/migration-status`)}async getCascadeStatus(e){let t=encodeURIComponent(e);return c(await this.httpClient.get(`/admin-api/groups/${t}/cascade-status`))}async retryGroupUpgrade(e){return c(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,{}))}async reparentGroup(e,t){let n=await this.httpClient.post(`/admin-api/groups/${e}/reparent`,t);return n?.data??n}async listSubgroups(e){let t=await this.httpClient.get(`/admin-api/groups/${e}/subgroups`);return t.subgroups??t.data??[]}async detachContextFromGroup(e,t){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${t}/remove`,{})}async createGroupInvitation(e,t){return c(await this.httpClient.post(`/admin-api/groups/${e}/invite`,t??{}))}async joinGroup(e){return c(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return c(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return c(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return c(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return c(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 getCertificate(){return this.httpClient.get("/admin-api/certificate",{parse:"text"})}async createGroup(e){return c(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,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-ownership-proof`,t)}async issueNamespaceOwnershipProof(e,t){return this.httpClient.post(`/admin-api/groups/${e}/issue-namespace-ownership-proof`,t)}async setMemberAutoFollow(e,t,n){await this.httpClient.put(`/admin-api/groups/${e}/members/${t}/auto-follow`,n)}async abortMigration(e){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,{})}};function vn(r){return new D(M(r))}function kn(r){return new D(J(r))}function xn(r){return new D(ce(r))}function _e(r,e){return new D(r)}function pe(r){try{let e=r.indexOf("#");if(e===-1)return null;let t=r.substring(e+1),n=new URLSearchParams(t),s=n.get("access_token");return s?{accessToken:s,refreshToken:n.get("refresh_token")??"",applicationId:n.get("application_id")??"",contextId:n.get("context_id")??"",contextIdentity:n.get("context_identity")??"",nodeUrl:n.get("node_url")??""}:null}catch{return null}}function de(r,e){let t=new URLSearchParams;return t.set("callback-url",e.callbackUrl),e.permissions&&e.permissions.length>0&&t.set("permissions",e.permissions.join(",")),t.set("mode",e.mode),e.packageName&&(t.set("package-name",e.packageName),e.packageVersion&&t.set("package-version",e.packageVersion),e.registryUrl&&t.set("registry-url",e.registryUrl)),`${r.replace(/\/+$/,"")}/auth/login?${t.toString()}`}var F=class extends Error{constructor(e,t,n,s){super(t),this.name="RpcError",this.code=e,this.data=n,this.type=s}};async function me(r,e,t){let n=await r.post("/jsonrpc",{jsonrpc:"2.0",id:1,method:e,params:t});if(n.error){let s=n.error;throw new F(s.code??-1,s.message??s.type??"RPC error",s.data,s.type)}return n.result}var q=class{constructor(e){this.httpClient=e.httpClient}async execute(e){let t=await me(this.httpClient,"execute",{contextId:e.contextId,method:e.method,argsJson:e.argsJson??{}});return t&&"output"in t?t.output:t}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 dt=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function Me(r){return r.type!==void 0&&dt.has(r.type)}var mt=new Set(["token_reuse","token_revoked"]),N=class{constructor(e){this.sessionId=null;this.abortController=null;this.reconnectTimer=null;this.subscribedContextIds=new Set;this.subscribedGroupIds=new Set;this.closed=!1;this.listeners={connect:[],event:[],error:[]};this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.getAuthToken=e.getAuthToken,this.reconnectDelayMs=e.reconnectDelayMs??3e3}on(e,t){let n=e;if(n in this.listeners){let s=this.listeners[n];s.includes(t)||s.push(t)}}off(e,t){let n=e;if(n in this.listeners){let s=this.listeners[n],o=s.indexOf(t);o!==-1&&s.splice(o,1)}}onAppVersionChanged(e){let t=n=>{if(n.type!=="AppVersionChanged")return;let s=n.data;e({contextId:n.contextId,fromVersion:s?.fromVersion,toVersion:s?.toVersion})};return this.on("event",t),()=>this.off("event",t)}onMigrationEvent(e){let t=n=>{Me(n)&&e(n)};return this.on("event",t),()=>this.off("event",t)}emit(e,t){let n=e;if(n in this.listeners)for(let s of this.listeners[n])try{s(t)}catch{}}async connect(){if(!(this.abortController&&!this.closed)){this.closed=!1,this.abortController=new AbortController;try{let e=await this.getAuthToken(),t=`${this.baseUrl}/sse`,n=await fetch(t,{headers:{Authorization:`Bearer ${e}`,Accept:"text/event-stream"},signal:this.abortController.signal});if(!n.ok){let s=n.headers.get("x-auth-error"),o=await n.text().catch(()=>{});throw n.status===401&&s&&mt.has(s)?new _(s,n.status,n.statusText,t,n.headers,o):new w(n.status,n.statusText,t,n.headers,o)}if(!n.body)throw new Error("SSE response has no body");this.readStream(n.body).catch(s=>{if(this.closed)return;let o=s instanceof Error?s:new Error(String(s));this.emit("error",o),this.scheduleReconnect()})}catch(e){if(this.closed)return;let t=e instanceof Error?e:new Error(String(e));this.emit("error",t),this.scheduleReconnect()}}}async readStream(e){let t=e.getReader(),n=new TextDecoder,s="";try{for(;;){let{done:o,value:i}=await t.read();if(o)break;s+=n.decode(i,{stream:!0});let a=s.split(`
2
+ `);s=a.pop()??"";for(let l of a)if(l.startsWith("data:")){let u=l.slice(5).trim();u&&this.handleMessage(u)}}if(s+=n.decode(),s.startsWith("data:")){let o=s.slice(5).trim();o&&this.handleMessage(o)}}catch(o){if(this.closed)return;let i=o instanceof Error?o:new Error(String(o));this.emit("error",i)}this.closed||this.scheduleReconnect()}handleMessage(e){try{let t=JSON.parse(e);if(t.type==="connect"&&t.session_id){this.sessionId=t.session_id,this.emit("connect",t.session_id),(this.subscribedContextIds.size>0||this.subscribedGroupIds.size>0)&&this.sendSubscription("subscribe",{contextIds:[...this.subscribedContextIds],groupIds:[...this.subscribedGroupIds]});return}if(!t.result)return;let n=t.result.data;if(Array.isArray(n))try{let s=new Uint8Array(n),o=new TextDecoder().decode(s);n=JSON.parse(o)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:n});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:n})}catch{}}async subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,n=(t.contextIds??[]).filter(o=>!this.subscribedContextIds.has(o)),s=(t.groupIds??[]).filter(o=>!this.subscribedGroupIds.has(o));for(let o of t.contextIds??[])this.subscribedContextIds.add(o);for(let o of t.groupIds??[])this.subscribedGroupIds.add(o);(n.length>0||s.length>0)&&this.sessionId&&await this.sendSubscription("subscribe",{contextIds:n,groupIds:s})}async unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e,n=(t.contextIds??[]).filter(o=>this.subscribedContextIds.has(o)),s=(t.groupIds??[]).filter(o=>this.subscribedGroupIds.has(o));for(let o of t.contextIds??[])this.subscribedContextIds.delete(o);for(let o of t.groupIds??[])this.subscribedGroupIds.delete(o);(n.length>0||s.length>0)&&this.sessionId&&await this.sendSubscription("unsubscribe",{contextIds:n,groupIds:s})}async sendSubscription(e,t){try{let n=await this.getAuthToken(),s={};t.contextIds&&t.contextIds.length>0&&(s.contextIds=t.contextIds),t.groupIds&&t.groupIds.length>0&&(s.groupIds=t.groupIds);let o=await fetch(`${this.baseUrl}/sse/subscription`,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"},body:JSON.stringify({id:this.sessionId,method:e,params:s})});o.ok||this.emit("error",new Error(`SSE ${e} failed: ${o.status}`))}catch(n){this.emit("error",n instanceof Error?n:new Error(`SSE ${e} failed`))}}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 z=class z{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,t){let n=e;if(n in this.listeners){let s=this.listeners[n];s.includes(t)||s.push(t)}}off(e,t){let n=e;if(n in this.listeners){let s=this.listeners[n],o=s.indexOf(t);o!==-1&&s.splice(o,1)}}emit(e,t){let n=e;if(n in this.listeners)for(let s of this.listeners[n])try{s(t)}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 t=this.baseUrl.replace(/^http/,"ws");this.ws=new WebSocket(`${t}/ws?token=${encodeURIComponent(e)}`),this.ws.onopen=()=>{this.reconnectAttempt=0,this.emit("connect"),this.resubscribeAfterReconnect()},this.ws.onmessage=n=>{this.handleMessage(n.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 t=e instanceof Error?e:new Error(String(e));this.emit("error",t),this.scheduleReconnect()}}}handleMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);if(!t.result)return;let n=t.result.data;if(Array.isArray(n))try{let s=new Uint8Array(n),o=new TextDecoder().decode(s);n=JSON.parse(o)}catch{}if(t.result.contextId){this.emit("event",{contextId:t.result.contextId,type:t.result.type,data:n});return}t.result.groupId&&this.emit("event",{groupId:t.result.groupId,type:t.result.type,data:n})}catch{}}subscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let n of t.contextIds??[])this.subscribedContextIds.add(n);for(let n of t.groupIds??[])this.subscribedGroupIds.add(n);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"subscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.groupIds??[])})}unsubscribe(e){let t=Array.isArray(e)?{contextIds:e}:e;for(let n of t.contextIds??[])this.subscribedContextIds.delete(n);for(let n of t.groupIds??[])this.subscribedGroupIds.delete(n);this.ws&&this.ws.readyState===1&&this.sendMessage({id:null,method:"unsubscribe",params:this.buildSubscriptionParams(t.contextIds??[],t.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,t){let n={};return e.length>0&&(n.contextIds=e),t.length>0&&(n.groupIds=t),n}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),z.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()}};z.MAX_BACKOFF_MS=3e4;var U=z;function X(){return{encode(r){return Array.from(new TextEncoder().encode(JSON.stringify(r)))},decode(r){return JSON.parse(new TextDecoder().decode(new Uint8Array(r)))}}}var O=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,t,n=X()){await me(this.httpClient,"set_ephemeral",{contextId:e,state:n.encode(t)})}subscribe(e,t,n=X()){let s=o=>{let i=o;if(i.type!=="Ephemeral"||i.contextId!==e)return;let a=i.data;if(!a?.author)return;let l=!!a.removed,u={author:a.author,state:l||a.state===void 0?void 0:n.decode(a.state),removed:l};a.ageMs!==void 0&&(u.ageMs=a.ageMs),t(u)};return this.sse.on("event",s),this.sse.connect().catch(()=>{}),this.sse.subscribe([e]).catch(()=>{}),()=>{this.sse.off("event",s)}}};var Ne=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function C(r){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,r,!0),e}function y(r){return Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}function p(r,e,t){let n=r.trim();if(!/^[0-9a-fA-F]*$/.test(n)||n.length!==t*2)throw new Error(`${e} must be ${t*2} hex characters, got ${n.length}`);let s=new Uint8Array(t);for(let o=0;o<t;o+=1)s[o]=Number.parseInt(n.slice(o*2,o*2+2),16);return s}function v(r){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(r),!0),e}function g(...r){let e=new Uint8Array(r.reduce((n,s)=>n+s.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}async function x(r,e){let t=[v(r.length),r];for(let n of e)t.push(v(n.length),n);return new Uint8Array(await crypto.subtle.digest("SHA-256",g(...t)))}async function T(r){let e=p(r,"deviceSecret",32),t=g(Ne,e);try{return await crypto.subtle.importKey("pkcs8",t,{name:"Ed25519"},!1,["sign"])}catch(n){let s=n instanceof Error?`: ${n.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`"+s)}}async function R(r){let e=p(r,"deviceSecret",32),t=g(Ne,e),n=await crypto.subtle.importKey("pkcs8",t,{name:"Ed25519"},!0,["sign"]),o=(await crypto.subtle.exportKey("jwk",n)).x;return Uint8Array.from(atob(o.replace(/-/g,"+").replace(/_/g,"/")),i=>i.charCodeAt(0))}var ht=new TextEncoder().encode("calimero.device.cert.v1"),Ue=new TextEncoder().encode("calimero.account.genesis.v1"),gt=new TextEncoder().encode("calimero.device.id.v1"),he=2;async function He(r,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let t=p(r,"account",32);return y(await x(gt,[t,e]))}async function ge(r){return x(ht,[p(r.account,"account",32),p(r.device,"device",32),p(r.signPublicKey,"signPublicKey",32),p(r.kemPublicKey,"kemPublicKey",32),C(r.keyEpoch),C(r.deviceEpoch)])}function Ge(r){return g(new Uint8Array([he]),r.rootPublicKey,C(0),p(r.account,"account",32),p(r.device,"device",32),p(r.signPublicKey,"signPublicKey",32),p(r.kemPublicKey,"kemPublicKey",32),C(r.keyEpoch),C(r.deviceEpoch),r.signature)}async function $e(r){let e=await R(r.rootSecret),t=y(await x(Ue,[g(new Uint8Array([he]),e)])),n=0,s=await ge({account:t,device:r.device,signPublicKey:r.signPublicKey,kemPublicKey:r.kemPublicKey,keyEpoch:n,deviceEpoch:r.deviceEpoch}),o=await T(r.rootSecret),i=new Uint8Array(await crypto.subtle.sign("Ed25519",o,s)),a=Ge({rootPublicKey:e,account:t,device:r.device,signPublicKey:r.signPublicKey,kemPublicKey:r.kemPublicKey,keyEpoch:n,deviceEpoch:r.deviceEpoch,signature:i});return y(a)}async function Q(r){let e=await R(r);return y(await x(Ue,[g(new Uint8Array([he]),e)]))}var fe=["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 ft=new TextEncoder().encode("calimero.mdma.account-link.v1\0"),j=256,Le=j/32,ye=(j+Le)/11;async function qe(){let r=crypto.getRandomValues(new Uint8Array(j/8));return je(y(r),await bt(r))}async function Oe(r){let e=yt(r);return je(y(await wt(e)),e.join(" "))}async function K(r){return p(r,"secret",32),{secret:r,publicKey:y(await R(r)),accountId:await Q(r)}}async function Y(r){if(!r.nonce)throw new Error("nonce is required to sign an account link");let e=await T(r.rootSecret),t=new Uint8Array(await crypto.subtle.sign("Ed25519",e,g(ft,new TextEncoder().encode(r.nonce))));return Ct(t)}async function je(r,e){return{...await K(r),phrase:e}}function yt(r){let e=r.normalize("NFKD").toLowerCase().trim().split(/\s+/),t=e[0]===""?0:e.length;if(t!==ye)throw new Error(`recovery phrase must be ${ye} words, got ${t}`);return e}async function bt(r){let e=Be(r)+await Ke(r),t=[];for(let n=0;n<ye;n+=1){let s=Number.parseInt(e.slice(n*11,n*11+11),2);t.push(fe[s])}return t.join(" ")}async function wt(r){let e="";for(let n of r){let s=fe.indexOf(n);if(s<0)throw new Error(`"${n}" is not a word in the recovery phrase list`);e+=s.toString(2).padStart(11,"0")}let t=new Uint8Array(j/8);for(let n=0;n<t.length;n+=1)t[n]=Number.parseInt(e.slice(n*8,n*8+8),2);if(e.slice(j)!==await Ke(t))throw new Error("recovery phrase checksum failed \u2014 check for a mistyped or transposed word");return t}async function Ke(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return Be(e).slice(0,Le)}function Be(r){let e="";for(let t of r)e+=t.toString(2).padStart(8,"0");return e}function Ct(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Rt="https://cloud.calimero.network",At="x-mdma-session-refresh",vt="x-mdma-session-expires",E=class{constructor(e={}){this.session=null;this.baseUrl=(e.cloudBaseUrl||Rt).replace(/\/+$/,""),this.onSession=e.onSession;let t=e.fetch;this.fetchImpl=t?(n,s)=>t(n,s):(n,s)=>globalThis.fetch(n,s),this.timeoutMs=e.timeoutMs??1e4,e.sessionToken&&(this.session={sessionToken:e.sessionToken,expiresAt:0,user:{email:""}})}getSession(){return this.session}isSignedIn(){return this.session!==null}async signInWithGoogle(e){let t=await this.request("POST","/api/auth/google",{body:{id_token:e},anonymous:!0});return this.adoptSession(t)}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(t=>({namespaceId:String(t.namespace_id??t.group_id??""),groupId:String(t.group_id??t.namespace_id??""),haStatus:String(t.ha_status??"none"),haEnabledAt:t.ha_enabled_at??null,contexts:Array.isArray(t.contexts)?t.contexts:[],fleetReplicas:t.fleet_replicas}))}async getNamespaceRelays(e){return((await this.request("GET",`/api/cloud/me/namespaces/${encodeURIComponent(e)}/relays`)).relays??[]).map(n=>({peerId:String(n.peer_id??""),relayUrl:n.relay_url??null,executorAccount:n.executor_account??null,status:String(n.status??""),authorshipReady:n.authorship_ready===!0,lastSeenAt:n.last_seen_at??null,confirmedAt:n.confirmed_at??null}))}async findExecutingRelay(e){return(await this.getNamespaceRelays(e)).find(n=>n.authorshipReady&&n.relayUrl!==null&&n.executorAccount!==null)??null}async getNamespaceRouting(e){let t=await this.request("GET",`/api/cloud/namespaces/${encodeURIComponent(e)}/admitters`,{anonymous:!0});return{namespaceId:String(t.namespace_id??e),nodes:(t.admitters??[]).map(n=>({peerId:String(n.peer_id??""),account:n.account??null,relayUrl:n.relay_url??null,admitUrl:n.admit_url??null,status:String(n.status??""),fresh:n.fresh===!0,canAdmit:n.can_admit===!0,authorshipReady:n.authorship_ready===!0,canExecute:n.can_execute===!0})),servable:t.servable===!0,writable:t.writable===!0}}async findAdmitter(e,t){let{nodes:n}=await this.getNamespaceRouting(e),s=t&&t.length>0?new Set(t.map(o=>o.toLowerCase())):null;return n.find(o=>o.canAdmit&&(s===null||o.account!==null&&s.has(o.account.toLowerCase())))??null}async getMyMachines(){return((await this.request("GET","/api/cloud/me/machines")).machines??[]).map(t=>({peerId:String(t.peer_id??""),relayUrl:t.relay_url??null,executorAccount:t.executor_account??null,canExecute:t.can_execute===!0,namespaces:(Array.isArray(t.namespaces)?t.namespaces:[]).map(n=>{let s=n;return{namespaceId:String(s.namespace_id??""),status:String(s.status??""),authorshipReady:s.authorship_ready===!0,fresh:s.fresh===!0,confirmedAt:s.confirmed_at??null,lastSeenAt:s.last_seen_at??null}})}))}async claimNamespace(e,t){await this.request("POST","/api/cloud/namespaces/claim",{body:{namespace_id:e,ownership_proof:t}})}async enableNamespaceHa(e){return this.request("POST",`/api/cloud/namespaces/${encodeURIComponent(e)}/enable-ha`,{body:{}})}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 t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/enable-ha?${t.toString()}`)}disableHA(e){let t=new URLSearchParams({group_id:e.groupId,context_id:e.contextId});e.redirectUrl&&t.set("redirect_url",e.redirectUrl),window.open(`${this.baseUrl}/disable-ha?${t.toString()}`)}async linkAccount(e){let t=await K(e),{nonce:n}=await this.getAccountLinkChallenge();return this.submitAccountLink({accountId:t.accountId,rootPublicKey:t.publicKey,nonce:n,signature:await Y({rootSecret:e,nonce:n})})}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 t=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(t.account_id??e.accountId),linkedAt:t.linked_at??null,alreadyLinked:t.already_linked===!0}}async getMyAccounts(){let e=await this.request("GET","/api/cloud/me/accounts");return{accounts:(e.accounts??[]).map(t=>({accountId:String(t.account_id??""),linkedAt:t.linked_at??null,hasRecoveryEnvelope:t.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,t,n={}){if(!n.anonymous&&!this.session)throw new Error("Not signed in to Calimero Cloud: call signInWithGoogle() or construct the client with a sessionToken");let s={Accept:"application/json"};n.body!==void 0&&(s["Content-Type"]="application/json"),!n.anonymous&&this.session&&(s.Authorization=`Bearer ${this.session.sessionToken}`);let o=new AbortController,i=setTimeout(()=>o.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:s,body:n.body===void 0?void 0:JSON.stringify(n.body),signal:o.signal})}catch(l){throw new w(0,l instanceof Error?l.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,l instanceof Error?l.message:String(l))}finally{clearTimeout(i)}if(this.adoptRollingRefresh(a),!a.ok){let l=await a.text().catch(()=>{});throw new w(a.status,a.statusText,`${this.baseUrl}${t}`,a.headers,l)}if(!(n.parse==="none"||a.status===204))return await a.json()}adoptRollingRefresh(e){let t=e.headers.get(At);if(!t||!this.session)return;let n=e.headers.get(vt),s=Number(n);this.session={sessionToken:t,expiresAt:Number.isFinite(s)&&s>0?s:this.session.expiresAt,user:this.session.user},this.notifySession(this.session)}};var kt="mero-js:token-refresh";function xt(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function be(r,e){try{let t=r.split(".");if(t.length===3){let n=t[1].replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4;)n+="=";let s=JSON.parse(atob(n));if(typeof s.exp=="number")return s.exp*1e3}}catch{}return e}var Z=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 t=typeof window<"u"&&"__TAURI_INTERNALS__"in window;this.httpClient=M({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",refreshToken:async()=>(await this.performTokenRefresh()).access_token,onTokenRefresh:async n=>{this.tokenData&&(this.tokenData.access_token=n,this.tokenStore?.setTokens(this.tokenData))},onAuthRevoked:async()=>{this.clearToken();try{await this.config.onAuthRevoked?.()}catch{}},timeoutMs:this.config.timeoutMs,credentials:this.config.requestCredentials??(t?"omit":void 0)}),this.authClient=Ie(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=_e(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 q({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new N({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new O({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}get cloud(){return this.cloudClient||(this.cloudClient=new E(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 U({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.wsClient}async authenticate(e){let t=e||this.config.credentials;if(!t)throw new Error("No credentials provided for authentication");try{let n={auth_method:"user_password",public_key:t.username,client_name:"mero-js-sdk",permissions:["admin"],timestamp:Math.floor(Date.now()/1e3),provider_data:{username:t.username,password:t.password}},s=await this.authClient.generateTokens(n),o=s.data.access_token;return this.tokenData={access_token:o,refresh_token:s.data.refresh_token,expires_at:be(o,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(n){throw new Error(`Authentication failed: ${n instanceof Error?n.message:"Unknown error"}`)}}async getValidToken(){return this.tokenData}async performTokenRefresh(){if(this.refreshPromise)return this.refreshPromise;let e=this.tokenData?.access_token,t=this.withRefreshLock(()=>this.performTokenRefreshLocked(e));this.refreshPromise=t;try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}withRefreshLock(e){let t=xt();return t?t.request(kt,e):e()}async performTokenRefreshLocked(e){let t=this.tokenStore?.getTokens()??null;if(t?.refresh_token&&(this.tokenData=t,e&&t.access_token!==e))return t;if(!this.tokenData?.refresh_token)throw new Error("No refresh token available");try{let n=await this.authClient.refreshToken({access_token:this.tokenData.access_token,refresh_token:this.tokenData.refresh_token}),s=n.data.access_token;return this.tokenData={access_token:s,refresh_token:n.data.refresh_token,expires_at:be(s,Date.now()+36e5)},this.tokenStore?.setTokens(this.tokenData),this.tokenData}catch(n){throw new Error(`Token refresh failed: ${n instanceof Error?n.message:"Unknown error"}`)}}clearToken(){this.refreshPromise=null,this.tokenData=null,this.tokenStore?.clear()}isAuthenticated(){return this.tokenData!==null}setTokenData(e){let t=e.expires_at||be(e.access_token,Date.now()+36e5);this.tokenData={...e,expires_at:t},this.tokenStore?.setTokens(this.tokenData)}getTokenData(){return this.tokenData}close(){this.sseClient?.close(),this.wsClient?.close()}static parseAuthCallback(e){return pe(e)}static buildAuthLoginUrl(e,t){return de(e,t)}};function Tt(r){return new Z(r)}var we=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},Pt="mero-tokens",Ce=class{constructor(e=Pt){this.key=e}getTokens(){try{if(typeof localStorage>"u")return null;let e=localStorage.getItem(this.key);if(!e)return null;let t=JSON.parse(e);return t&&t.access_token&&t.refresh_token?{access_token:t.access_token,refresh_token:t.refresh_token,expires_at:typeof t.expires_at=="number"?t.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 St=new TextEncoder().encode("calimero.warrant.v2"),It=new TextEncoder().encode("calimero.warrant.intent.v1"),We=64,Dt="00".repeat(32);async function Re(r,e){let t=new TextEncoder().encode(JSON.stringify(e));return x(It,[new TextEncoder().encode(r),t])}async function ee(r){let e=p(r.context,"context",32),t=p(r.authorAccount,"authorAccount",32),n=p(r.executor,"executor",32),s=p(r.appVersion??Dt,"appVersion",32),o=Je(r.accountHeads,"accountHeads"),i=Je(r.governanceFloor,"governanceFloor"),a=await T(r.deviceSecret),l=await R(r.deviceSecret),u=new TextEncoder().encode(r.method),h=await Re(r.method,r.argsJson),m=v(r.nonce),f=v(r.notAfter),b=await x(St,[e,t,l,n,s,u,h,v(o.length),...o,v(i.length),...i,m,f]),d=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},a,b));return y(g(e,t,l,n,s,C(u.length),u,h,C(o.length),...o,C(i.length),...i,m,f,d))}function Je(r,e){let t=r??[];if(t.length>We)throw new Error(`${e} cites ${t.length} heads, over the ${We} a node accepts`);return t.map((n,s)=>p(n,`${e}[${s}]`,32))}var Et=300,te=class extends Error{constructor(t,n,s){super(`relay refused the intent (HTTP ${s}): ${t}`);this.reason=t;this.retryable=n;this.status=s;this.name="IntentRefusedError"}},B=class{constructor(e){this.config=e,this.baseUrl=e.relayUrl.replace(/\/+$/,""),this.executorAccount=e.executorAccount;let t=e.fetch;this.fetchImpl=t?(n,s)=>t(n,s):(n,s)=>globalThis.fetch(n,s),this.timeoutMs=e.timeoutMs??1e4}async describe(e){let t=await this.json("GET",`/admin-api/contexts/${encodeURIComponent(e)}/intents`);return this.executorAccount=t.data.executorAccount,t.data}async execute(e,t,n={}){let s=this.executorAccount??(await this.describe(e)).executorAccount,o=await this.config.nonces.next(),i=this.config.ttlSeconds??Et,a=await ee({context:e,authorAccount:this.config.authorAccount,executor:s,method:t,argsJson:n,nonce:o,notAfter:BigInt(Math.floor(Date.now()/1e3))+BigInt(i),deviceSecret:this.config.deviceSecret}),l=await this.json("POST",`/admin-api/contexts/${encodeURIComponent(e)}/intents`,{method:t,argsJson:n,warrant:a,authorProof:this.config.authorProof});return{rootHash:l.data.rootHash,returns:l.data.returns??null}}async json(e,t,n){let s={Accept:"application/json"};n!==void 0&&(s["Content-Type"]="application/json");let o=new AbortController,i=setTimeout(()=>o.abort(),this.timeoutMs),a;try{a=await this.fetchImpl(`${this.baseUrl}${t}`,{method:e,headers:s,body:n===void 0?void 0:JSON.stringify(n),signal:o.signal})}catch(l){throw new w(0,l instanceof Error?l.name:"NetworkError",`${this.baseUrl}${t}`,new Headers,l instanceof Error?l.message:String(l))}finally{clearTimeout(i)}if(!a.ok){let l=await a.text().catch(()=>"");if(a.status===400||a.status===403){let u=_t(l);throw new te(u,/nonce/i.test(u),a.status)}throw new w(a.status,a.statusText,`${this.baseUrl}${t}`,a.headers,l)}return await a.json()}};function _t(r){if(!r)return"no reason given";try{let e=JSON.parse(r);for(let t of[e.error,e.message])if(typeof t=="string"&&t)return t}catch{}return r}function Ae(r=1){let e=BigInt(r);if(e<1n)throw new Error("nonce sequence starts at 1");return{next(){let t=e;return e+=1n,Promise.resolve(t)}}}function ve(r,e){let t=e??globalThis.localStorage;if(!t)throw new Error("no localStorage in this runtime: pass a storage implementation, or use createMemoryNonceSource for a process that owns its whole sequence");return{next(){let n=t.getItem(r),s=0n;if(n!==null&&n!=="")try{let i=BigInt(n);i>0n&&(s=i)}catch{s=0n}let o=s+1n;return t.setItem(r,o.toString()),Promise.resolve(o)}}}async function Mt(r){if(!r.sessionToken&&!r.googleIdToken)throw new Error("connectCloud needs either a sessionToken or a googleIdToken");let e=new E({cloudBaseUrl:r.cloudBaseUrl,sessionToken:r.sessionToken,onSession:r.onSession,fetch:r.fetch,timeoutMs:r.timeoutMs});!r.sessionToken&&r.googleIdToken&&await e.signInWithGoogle(r.googleIdToken);let t=await e.getMyNamespaces(),n=Nt(t,r.namespaceId),s=await e.getNamespaceRelays(n.namespaceId),o=s.find(a=>a.authorshipReady&&a.relayUrl!==null&&a.executorAccount!==null)??null;if(!o)throw new Error(Ut(n,s));let i=new B({relayUrl:o.relayUrl,executorAccount:o.executorAccount,authorAccount:r.authorAccount,authorProof:r.authorProof,deviceSecret:r.deviceSecret,nonces:r.nonces??await Ht(r.deviceSecret),ttlSeconds:r.ttlSeconds,fetch:r.fetch,timeoutMs:r.timeoutMs});return{cloud:e,relay:i,namespaceId:n.namespaceId,namespace:n,relayInfo:o,execute:(a,l,u)=>i.execute(a,l,u)}}function Nt(r,e){if(e){let t=r.find(n=>n.namespaceId===e);if(!t)throw new Error(`this account owns no namespace ${e}; it owns: ${r.map(n=>n.namespaceId).join(", ")||"(none)"}`);return t}if(r.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(r.length>1)throw new Error(`this account owns ${r.length} namespaces \u2014 pass namespaceId to say which: ${r.map(t=>t.namespaceId).join(", ")}`);return r[0]}function Ut(r,e){if(e.length===0)return r.haStatus==="enabled"?`namespace ${r.namespaceId} has HA enabled but no relay has been assigned to it yet \u2014 retry shortly`:`namespace ${r.namespaceId} has no relays: enable HA on it in the cloud to have an attested node assigned`;let t=e.filter(n=>!n.authorshipReady);return t.length===e.length?`every relay on namespace ${r.namespaceId} is waiting for the authorship grant: an admin of the namespace must grant CAN_AUTHOR_ON_BEHALF to ${t.map(n=>n.executorAccount??n.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 ${r.namespaceId} has ${e.length} relay(s), but none reported both a URL and an executor account yet \u2014 retry shortly`}async function Ht(r){let e=`mero-js:warrant-nonce:${y(await R(r))}`;try{return ve(e)}catch{return Ae(1)}}var xe=8,Gt=new TextEncoder().encode("calimero.namespace.v1"),$t=0,Ve={GroupCreated:0,GroupReparented:1,GroupDeleted:2,AdminChanged:3,PolicyUpdated:4,MemberJoined:5,KeyDelivery:6,MemberJoinedOpen:7,MemberJoinedAt:8,NamespaceCreated:9,MemberJoinedViaTeeAttestation:10};function ke(r,e){if(r.length!==32)throw new Error(`${e} must be 32 bytes, got ${r.length}`);return new Uint8Array(r)}function Fe(r,e){if(r==null)return new Uint8Array([0]);if(r.length!==32)throw new Error(`${e} must be 32 bytes, got ${r.length}`);return g(new Uint8Array([1]),new Uint8Array(r))}function ze(r){let e=new TextEncoder().encode(r);return g(C(e.length),e)}function ne(r){let e=r.invitation,t=e.admitters??[],n=r.admitter_addrs??[];return g(ke(e.inviter_identity,"inviter_identity"),ke(e.group_id,"group_id"),v(e.expiration_timestamp),ke(e.secret_salt,"secret_salt"),new Uint8Array([e.invited_role]),C(t.length),...t.map((s,o)=>p(s,`admitters[${o}]`,32)),ze(r.inviter_signature),r.inviter_account?g(new Uint8Array([1]),p(r.inviter_account,"inviter_account",32)):new Uint8Array([0]),C(n.length),...n.map(ze),Fe(r.application_id,"application_id"),Fe(r.app_key,"app_key"))}async function Xe(r){let e=r.parentOpHashes??[],t=p(r.credential,"credential",r.credential.length/2),n=BigInt(r.invitation.invitation.expiration_timestamp??0)!==0n,s=r.joinedAt??BigInt(Math.floor(Date.now()/1e3)),o=n?g(new Uint8Array([Ve.MemberJoinedAt]),p(r.member,"member",32),ne(r.invitation),v(s),t):g(new Uint8Array([Ve.MemberJoined]),p(r.member,"member",32),ne(r.invitation),t),i=g(new Uint8Array([$t]),o),a=await T(r.deviceSecret),l=await R(r.deviceSecret),u=g(new Uint8Array([xe]),p(r.namespaceId,"namespaceId",32),C(e.length),...e.map((f,b)=>p(f,`parentOpHashes[${b}]`,32)),l,v(r.nonce),i),h=new Uint8Array(await crypto.subtle.sign("Ed25519",a,g(Gt,u))),m=new Uint8Array([0]);return y(g(u,h,m))}var Lt=new TextEncoder().encode("calimero.auth.login.v1"),Qe={webOrigin:0,codeSigningId:1,cli:2};function Ye(r){let e=new TextEncoder;switch(r.kind){case"webOrigin":return e.encode(r.origin);case"codeSigningId":return e.encode(r.id);case"cli":return new Uint8Array(0)}}function qt(r){return g(Uint8Array.from([Qe[r.kind]]),Ye(r))}function Ot(r){let e=Uint8Array.from([Qe[r.kind]]);if(r.kind==="cli")return e;let t=Ye(r);return g(e,C(t.length),t)}async function re(r){let e=p(r.node,"node",32),t=p(r.challenge,"challenge",32),n=p(r.sessionKey,"sessionKey",32),s=await T(r.deviceSecret),o=await R(r.deviceSecret),i=v(r.issuedAt),a=v(r.expiresAt),l=await x(Lt,[e,qt(r.audience),t,n,o,i,a]),u=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},s,l));return y(g(e,Ot(r.audience),t,n,o,i,a,u))}var jt=300;async function Te(){let r=y(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:y(await R(r)),secret:r}}function Kt(r){switch(r.kind){case"webOrigin":return r.origin;case"codeSigningId":return r.id;case"cli":return"cli"}}async function Ze(r){let e=r.nodeUrl.replace(/\/+$/,""),t=r.fetch??globalThis.fetch,n=r.timeoutMs??1e4,s=async(b,d)=>{let P=new AbortController,S=setTimeout(()=>P.abort(),n),k;try{k=await t(`${e}${b}`,{...d,signal:P.signal})}catch(A){throw new w(0,A instanceof Error?A.name:"NetworkError",`${e}${b}`,new Headers,A instanceof Error?A.message:String(A))}finally{clearTimeout(S)}let H=await k.text().catch(()=>"");if(!k.ok)throw new w(k.status,k.statusText,`${e}${b}`,k.headers,H);return H?JSON.parse(H):{}},o=await s("/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 Te(),l=Math.floor(Date.now()/1e3),u=await re({node:r.node,audience:r.audience,challenge:i,sessionKey:a.publicKey,issuedAt:l,expiresAt:l+(r.ttlSeconds??jt),deviceSecret:r.deviceSecret}),h=await s("/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:r.clientName??Kt(r.audience),timestamp:l,provider_data:{challenge:i,login_statement:u,account_proof:r.accountProof}})}),m=h.access_token??h.data?.access_token,f=h.refresh_token??h.data?.refresh_token;if(!m)throw new Error("the node minted no session");return{accessToken:m,refreshToken:f??"",sessionKey:a.publicKey,sessionSecret:a.secret}}var et=[2428,2429,2528,2529],Bt="localhost",Wt=2e3;function tt(r){return`http://${Bt}:${r}`}function nt(r,e){let t=r.endsWith("/")?r:`${r}/`;return new URL(e,t).toString()}async function rt(r,e={}){let{timeoutMs:t=Wt,signal:n}=e;if(n?.aborted)return!1;let s=new AbortController,o=()=>s.abort(),i=n;i&&i.addEventListener("abort",o,{once:!0});let a=setTimeout(()=>s.abort(),t);try{let l=nt(r,"admin-api/health"),u=await fetch(l,{method:"GET",signal:s.signal});if(!u.ok)return!1;try{let h=await u.json(),m=h?.data?.status!==void 0?h?.data?.status:h?.status;return m===void 0?!0:typeof m=="string"&&m.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(a),i&&i.removeEventListener("abort",o)}}async function Jt(r={}){let{ports:e=et,timeoutMs:t,signal:n}=r;return(await Promise.all(e.map(async o=>{let i=tt(o);return await rt(i,{timeoutMs:t,signal:n})?i:null}))).filter(o=>o!==null)}export{D as AdminApiClient,I as AuthApiClient,_ as AuthRevokedError,L as CAPABILITIES,E as CloudClient,et as DEFAULT_LOCAL_NODE_PORTS,O as EphemeralClient,w as HTTPError,te as IntentRefusedError,Ce as LocalStorageTokenStore,we as MemoryTokenStore,Z as MeroJs,B as RelayClient,q as RpcClient,F as RpcError,xe as SIGNED_NAMESPACE_OP_SCHEMA_VERSION,N as SseClient,G as WebHttpClient,U as WsClient,Q as accountForRoot,Oe as accountRootFromPhrase,K as accountRootFromSecret,de as buildAuthLoginUrl,oe as combineSignals,ut as compareSemver,Mt as connectCloud,xn as createAdminApiClient,_e as createAdminApiClientFromHttpClient,dn as createAuthApiClient,Ie as createAuthApiClientFromHttpClient,vn as createBrowserAdminApiClient,un as createBrowserAuthApiClient,M as createBrowserHttpClient,ae as createHttpClient,ve as createLocalStorageNonceSource,Ae as createMemoryNonceSource,Tt as createMeroJs,kn as createNodeAdminApiClient,pn as createNodeAuthApiClient,J as createNodeHttpClient,lt as createRetryableMethod,ie as createTimeoutSignal,ce as createUniversalHttpClient,ge as deviceCertPayload,Jt as discoverLocalNodes,ne as encodeSignedInvitation,qe as generateAccountRoot,Te as generateSessionKey,le as hasCap,Re as intentHash,X as jsonCodec,tt as localNodeUrl,Ze as login,He as mintDeviceId,nt as nodeEndpoint,pe as parseAuthCallback,rt as probeNodeHealth,Y as signAccountLink,$e as signDeviceCert,re as signLoginStatement,Xe as signMemberJoinOp,ee as signWarrant,ue as withCap,V as withRetry,hn as withoutCap};
3
3
  //# sourceMappingURL=index.browser.mjs.map