@calimero-network/mero-js 14.0.0 → 15.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/crypto/internal.d.ts +30 -0
- package/dist/crypto/internal.js +93 -0
- package/dist/device-cert/device-cert.d.ts +68 -0
- package/dist/device-cert/device-cert.js +110 -0
- package/dist/device-cert/index.d.ts +2 -0
- package/dist/device-cert/index.js +2 -0
- package/dist/index.browser.mjs +2 -2
- package/dist/index.browser.mjs.map +4 -4
- package/dist/index.cjs +105 -116
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -2
- package/dist/index.mjs +105 -116
- package/dist/index.mjs.map +4 -4
- package/dist/warrant/warrant.d.ts +1 -0
- package/dist/warrant/warrant.js +1 -79
- package/package.json +1 -1
- package/dist/account/index.d.ts +0 -43
- package/dist/account/index.js +0 -139
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte-level primitives shared by everything in this package that signs.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `warrant/warrant.ts` when the device-cert signer arrived and
|
|
5
|
+
* needed the same `domainHash`, hex handling and ed25519 import. Keeping one
|
|
6
|
+
* copy is the point: these have to stay byte-identical with core, and two
|
|
7
|
+
* copies drifting apart is exactly the failure the byte-parity e2e exists to
|
|
8
|
+
* catch. Internal — not exported from the package root.
|
|
9
|
+
*/
|
|
10
|
+
/** Little-endian u32, for borsh fixed-width fields and epoch counters. */
|
|
11
|
+
export declare function u32le(value: number): Uint8Array;
|
|
12
|
+
export declare function hex(bytes: Uint8Array): string;
|
|
13
|
+
export declare function fromHex(value: string, label: string, expectedBytes: number): Uint8Array;
|
|
14
|
+
export declare function u64le(value: number | bigint): Uint8Array;
|
|
15
|
+
export declare function concat(...parts: Uint8Array[]): Uint8Array;
|
|
16
|
+
/**
|
|
17
|
+
* core's `domain_hash`: SHA-256 over the length-prefixed domain, then each
|
|
18
|
+
* length-prefixed part. The lengths are what stop two different field splits from
|
|
19
|
+
* hashing alike.
|
|
20
|
+
*/
|
|
21
|
+
export declare function domainHash(domain: Uint8Array, parts: Uint8Array[]): Promise<Uint8Array>;
|
|
22
|
+
export declare function importSigningKey(secretHex: string): Promise<CryptoKey>;
|
|
23
|
+
/**
|
|
24
|
+
* The public half of an ed25519 seed.
|
|
25
|
+
*
|
|
26
|
+
* Derived rather than taken as an argument, for the reason core does the same: a
|
|
27
|
+
* caller able to name a key it does not hold could produce a warrant it cannot
|
|
28
|
+
* sign, and the field would stop meaning "who authorised this".
|
|
29
|
+
*/
|
|
30
|
+
export declare function derivePublicKey(secretHex: string): Promise<Uint8Array>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Byte-level primitives shared by everything in this package that signs.
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `warrant/warrant.ts` when the device-cert signer arrived and
|
|
5
|
+
* needed the same `domainHash`, hex handling and ed25519 import. Keeping one
|
|
6
|
+
* copy is the point: these have to stay byte-identical with core, and two
|
|
7
|
+
* copies drifting apart is exactly the failure the byte-parity e2e exists to
|
|
8
|
+
* catch. Internal — not exported from the package root.
|
|
9
|
+
*/
|
|
10
|
+
const PKCS8_ED25519_PREFIX = new Uint8Array([
|
|
11
|
+
0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04,
|
|
12
|
+
0x22, 0x04, 0x20,
|
|
13
|
+
]);
|
|
14
|
+
/** Little-endian u32, for borsh fixed-width fields and epoch counters. */
|
|
15
|
+
export function u32le(value) {
|
|
16
|
+
const out = new Uint8Array(4);
|
|
17
|
+
new DataView(out.buffer).setUint32(0, value, true);
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
export function hex(bytes) {
|
|
21
|
+
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
22
|
+
}
|
|
23
|
+
export function fromHex(value, label, expectedBytes) {
|
|
24
|
+
const clean = value.trim();
|
|
25
|
+
if (!/^[0-9a-fA-F]*$/.test(clean) || clean.length !== expectedBytes * 2) {
|
|
26
|
+
throw new Error(`${label} must be ${expectedBytes * 2} hex characters, got ${clean.length}`);
|
|
27
|
+
}
|
|
28
|
+
// Indexed rather than `match(/../g)!`: the length is already validated above,
|
|
29
|
+
// so the assertion would only be telling the compiler what the guard proved,
|
|
30
|
+
// and this needs no assertion at all.
|
|
31
|
+
const bytes = new Uint8Array(expectedBytes);
|
|
32
|
+
for (let i = 0; i < expectedBytes; i += 1) {
|
|
33
|
+
bytes[i] = Number.parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
|
34
|
+
}
|
|
35
|
+
return bytes;
|
|
36
|
+
}
|
|
37
|
+
export function u64le(value) {
|
|
38
|
+
const out = new Uint8Array(8);
|
|
39
|
+
new DataView(out.buffer).setBigUint64(0, BigInt(value), true);
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
export function concat(...parts) {
|
|
43
|
+
const out = new Uint8Array(parts.reduce((total, p) => total + p.length, 0));
|
|
44
|
+
let offset = 0;
|
|
45
|
+
for (const part of parts) {
|
|
46
|
+
out.set(part, offset);
|
|
47
|
+
offset += part.length;
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* core's `domain_hash`: SHA-256 over the length-prefixed domain, then each
|
|
53
|
+
* length-prefixed part. The lengths are what stop two different field splits from
|
|
54
|
+
* hashing alike.
|
|
55
|
+
*/
|
|
56
|
+
export async function domainHash(domain, parts) {
|
|
57
|
+
const chunks = [u64le(domain.length), domain];
|
|
58
|
+
for (const part of parts) {
|
|
59
|
+
chunks.push(u64le(part.length), part);
|
|
60
|
+
}
|
|
61
|
+
return new Uint8Array(await crypto.subtle.digest('SHA-256', concat(...chunks)));
|
|
62
|
+
}
|
|
63
|
+
export async function importSigningKey(secretHex) {
|
|
64
|
+
const seed = fromHex(secretHex, 'deviceSecret', 32);
|
|
65
|
+
const pkcs8 = concat(PKCS8_ED25519_PREFIX, seed);
|
|
66
|
+
try {
|
|
67
|
+
return await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, false, ['sign']);
|
|
68
|
+
}
|
|
69
|
+
catch (cause) {
|
|
70
|
+
// The original message is folded in rather than passed as `cause`: this
|
|
71
|
+
// package targets ES2020, where `Error` has no `cause` option.
|
|
72
|
+
const detail = cause instanceof Error ? `: ${cause.message}` : '';
|
|
73
|
+
throw new Error('this runtime has no WebCrypto Ed25519, so a warrant cannot be signed ' +
|
|
74
|
+
'here. Node 18.4+, Safari 17+, Firefox 129+ and Chrome 137+ have it; ' +
|
|
75
|
+
'otherwise mint the warrant with `merod account warrant`' +
|
|
76
|
+
detail);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The public half of an ed25519 seed.
|
|
81
|
+
*
|
|
82
|
+
* Derived rather than taken as an argument, for the reason core does the same: a
|
|
83
|
+
* caller able to name a key it does not hold could produce a warrant it cannot
|
|
84
|
+
* sign, and the field would stop meaning "who authorised this".
|
|
85
|
+
*/
|
|
86
|
+
export async function derivePublicKey(secretHex) {
|
|
87
|
+
const seed = fromHex(secretHex, 'deviceSecret', 32);
|
|
88
|
+
const pkcs8 = concat(PKCS8_ED25519_PREFIX, seed);
|
|
89
|
+
const key = await crypto.subtle.importKey('pkcs8', pkcs8, { name: 'Ed25519' }, true, ['sign']);
|
|
90
|
+
const jwk = await crypto.subtle.exportKey('jwk', key);
|
|
91
|
+
const raw = jwk.x;
|
|
92
|
+
return Uint8Array.from(atob(raw.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
|
|
93
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** What a root certifies about one device. */
|
|
2
|
+
export interface DeviceCertInput {
|
|
3
|
+
/** The account root's signing secret, 64 hex. Signs the certificate. */
|
|
4
|
+
rootSecret: string;
|
|
5
|
+
/** The device being certified, 64 hex — see {@link mintDeviceId}. */
|
|
6
|
+
device: string;
|
|
7
|
+
/** The key that device signs with, 64 hex. */
|
|
8
|
+
signPublicKey: string;
|
|
9
|
+
/** The key the group key is delivered to, 64 hex (X25519). */
|
|
10
|
+
kemPublicKey: string;
|
|
11
|
+
/**
|
|
12
|
+
* Must strictly exceed any epoch already folded for this device.
|
|
13
|
+
*
|
|
14
|
+
* The projection refuses a link that does not advance it, so a re-issued
|
|
15
|
+
* certificate reusing an epoch is inert rather than a rollback.
|
|
16
|
+
*/
|
|
17
|
+
deviceEpoch: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Mint a device id: `H(DEVICE_ID_DOMAIN, account ‖ nonce)`.
|
|
21
|
+
*
|
|
22
|
+
* Derived from the account and a fresh nonce rather than from the device's keys,
|
|
23
|
+
* so rotating a keypair keeps the replica identity — and with it the counter
|
|
24
|
+
* slots and HLC lineage — intact.
|
|
25
|
+
*/
|
|
26
|
+
export declare function mintDeviceId(account: string, nonce: Uint8Array): Promise<string>;
|
|
27
|
+
/**
|
|
28
|
+
* The 32 bytes a root signs to certify a device.
|
|
29
|
+
*
|
|
30
|
+
* Both keys are covered, so neither the signing key nor the delivery key can be
|
|
31
|
+
* substituted into a certificate that otherwise verifies — which is what stops a
|
|
32
|
+
* relay carrying someone's credential from making itself the reader.
|
|
33
|
+
*/
|
|
34
|
+
export declare function deviceCertPayload(input: {
|
|
35
|
+
account: string;
|
|
36
|
+
device: string;
|
|
37
|
+
signPublicKey: string;
|
|
38
|
+
kemPublicKey: string;
|
|
39
|
+
keyEpoch: number;
|
|
40
|
+
deviceEpoch: number;
|
|
41
|
+
}): Promise<Uint8Array>;
|
|
42
|
+
/**
|
|
43
|
+
* Certify a device, returning the hex credential `merod account sign-cert`
|
|
44
|
+
* prints — a borsh-encoded `AccountProof<DeviceCert>`.
|
|
45
|
+
*
|
|
46
|
+
* The layout, field for field, is core's:
|
|
47
|
+
*
|
|
48
|
+
* ```
|
|
49
|
+
* AccountProof { genesis: AccountGenesis, chain: Vec<RootKeyHandoff>, statement: DeviceCert }
|
|
50
|
+
* AccountGenesis { version: u8, root_sign_pk: [u8; 32] }
|
|
51
|
+
* chain → u32-LE count, then that many handoffs
|
|
52
|
+
* DeviceCert { account, device, sign_pk, kem_pk: [u8; 32] x4,
|
|
53
|
+
* key_epoch: u32, device_epoch: u32, signature: [u8; 64] }
|
|
54
|
+
* ```
|
|
55
|
+
*
|
|
56
|
+
* Borsh for plain fixed-width data is concatenation; the only variable part is
|
|
57
|
+
* the chain's length prefix. `chain` is empty here for the same reason it is in
|
|
58
|
+
* `sign-cert`: a root that has never been handed off signs directly, and a
|
|
59
|
+
* handoff chain is only needed once it has.
|
|
60
|
+
*
|
|
61
|
+
* `keyEpoch` is 0 for the same reason — it names the root epoch that signed, and
|
|
62
|
+
* an un-rotated root is at 0. Re-signing after a handoff is a separate flow that
|
|
63
|
+
* needs the chain, so this deliberately does not take it as an argument rather
|
|
64
|
+
* than accepting a value it would then have to ignore.
|
|
65
|
+
*/
|
|
66
|
+
export declare function signDeviceCert(input: DeviceCertInput): Promise<string>;
|
|
67
|
+
/** The account this root owns — the content address of its genesis. */
|
|
68
|
+
export declare function accountForRoot(rootSecret: string): Promise<string>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minting and certifying a device offline, with a key that never reaches a node.
|
|
3
|
+
*
|
|
4
|
+
* This is the second half of the keyholder story. `signWarrant` lets an account
|
|
5
|
+
* with no node *write*; this lets one exist in the first place — an account root
|
|
6
|
+
* certifies a device, and the resulting credential is what a joiner presents.
|
|
7
|
+
*
|
|
8
|
+
* As with the warrant signer, the risk is that this reproduces core's encoding
|
|
9
|
+
* and has to keep doing so. The answer is the same: a golden vector here, and an
|
|
10
|
+
* e2e that diffs this output against `merod account sign-cert` byte for byte.
|
|
11
|
+
*
|
|
12
|
+
* Everything below is derived from core:
|
|
13
|
+
*
|
|
14
|
+
* - `DeviceCert::signing_payload` — `crates/account/src/device.rs`
|
|
15
|
+
* - `DeviceId::mint` — `crates/primitives/src/identity.rs`
|
|
16
|
+
* - `AccountProof` / `AccountGenesis` borsh layout — `crates/account/src/{signed,account}.rs`
|
|
17
|
+
*/
|
|
18
|
+
import { concat, derivePublicKey, domainHash, fromHex, hex, importSigningKey, u32le, } from '../crypto/internal.js';
|
|
19
|
+
const CERT_DOMAIN = new TextEncoder().encode('calimero.device.cert.v1');
|
|
20
|
+
const ACCOUNT_ID_DOMAIN = new TextEncoder().encode('calimero.account.genesis.v1');
|
|
21
|
+
const DEVICE_ID_DOMAIN = new TextEncoder().encode('calimero.device.id.v1');
|
|
22
|
+
/** `AccountGenesis::version`, which the credential's borsh encoding leads with. */
|
|
23
|
+
const ACCOUNT_GENESIS_VERSION = 1;
|
|
24
|
+
/**
|
|
25
|
+
* Mint a device id: `H(DEVICE_ID_DOMAIN, account ‖ nonce)`.
|
|
26
|
+
*
|
|
27
|
+
* Derived from the account and a fresh nonce rather than from the device's keys,
|
|
28
|
+
* so rotating a keypair keeps the replica identity — and with it the counter
|
|
29
|
+
* slots and HLC lineage — intact.
|
|
30
|
+
*/
|
|
31
|
+
export async function mintDeviceId(account, nonce) {
|
|
32
|
+
if (nonce.length !== 16) {
|
|
33
|
+
throw new Error(`nonce must be 16 bytes, got ${nonce.length}`);
|
|
34
|
+
}
|
|
35
|
+
const accountBytes = fromHex(account, 'account', 32);
|
|
36
|
+
return hex(await domainHash(DEVICE_ID_DOMAIN, [accountBytes, nonce]));
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The 32 bytes a root signs to certify a device.
|
|
40
|
+
*
|
|
41
|
+
* Both keys are covered, so neither the signing key nor the delivery key can be
|
|
42
|
+
* substituted into a certificate that otherwise verifies — which is what stops a
|
|
43
|
+
* relay carrying someone's credential from making itself the reader.
|
|
44
|
+
*/
|
|
45
|
+
export async function deviceCertPayload(input) {
|
|
46
|
+
return domainHash(CERT_DOMAIN, [
|
|
47
|
+
fromHex(input.account, 'account', 32),
|
|
48
|
+
fromHex(input.device, 'device', 32),
|
|
49
|
+
fromHex(input.signPublicKey, 'signPublicKey', 32),
|
|
50
|
+
fromHex(input.kemPublicKey, 'kemPublicKey', 32),
|
|
51
|
+
u32le(input.keyEpoch),
|
|
52
|
+
u32le(input.deviceEpoch),
|
|
53
|
+
]);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Certify a device, returning the hex credential `merod account sign-cert`
|
|
57
|
+
* prints — a borsh-encoded `AccountProof<DeviceCert>`.
|
|
58
|
+
*
|
|
59
|
+
* The layout, field for field, is core's:
|
|
60
|
+
*
|
|
61
|
+
* ```
|
|
62
|
+
* AccountProof { genesis: AccountGenesis, chain: Vec<RootKeyHandoff>, statement: DeviceCert }
|
|
63
|
+
* AccountGenesis { version: u8, root_sign_pk: [u8; 32] }
|
|
64
|
+
* chain → u32-LE count, then that many handoffs
|
|
65
|
+
* DeviceCert { account, device, sign_pk, kem_pk: [u8; 32] x4,
|
|
66
|
+
* key_epoch: u32, device_epoch: u32, signature: [u8; 64] }
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* Borsh for plain fixed-width data is concatenation; the only variable part is
|
|
70
|
+
* the chain's length prefix. `chain` is empty here for the same reason it is in
|
|
71
|
+
* `sign-cert`: a root that has never been handed off signs directly, and a
|
|
72
|
+
* handoff chain is only needed once it has.
|
|
73
|
+
*
|
|
74
|
+
* `keyEpoch` is 0 for the same reason — it names the root epoch that signed, and
|
|
75
|
+
* an un-rotated root is at 0. Re-signing after a handoff is a separate flow that
|
|
76
|
+
* needs the chain, so this deliberately does not take it as an argument rather
|
|
77
|
+
* than accepting a value it would then have to ignore.
|
|
78
|
+
*/
|
|
79
|
+
export async function signDeviceCert(input) {
|
|
80
|
+
const rootPublicKey = await derivePublicKey(input.rootSecret);
|
|
81
|
+
const account = hex(await domainHash(ACCOUNT_ID_DOMAIN, [
|
|
82
|
+
concat(new Uint8Array([ACCOUNT_GENESIS_VERSION]), rootPublicKey),
|
|
83
|
+
]));
|
|
84
|
+
const keyEpoch = 0;
|
|
85
|
+
const payload = await deviceCertPayload({
|
|
86
|
+
account,
|
|
87
|
+
device: input.device,
|
|
88
|
+
signPublicKey: input.signPublicKey,
|
|
89
|
+
kemPublicKey: input.kemPublicKey,
|
|
90
|
+
keyEpoch,
|
|
91
|
+
deviceEpoch: input.deviceEpoch,
|
|
92
|
+
});
|
|
93
|
+
const key = await importSigningKey(input.rootSecret);
|
|
94
|
+
const signature = new Uint8Array(await crypto.subtle.sign('Ed25519', key, payload));
|
|
95
|
+
const credential = concat(
|
|
96
|
+
// AccountGenesis
|
|
97
|
+
new Uint8Array([ACCOUNT_GENESIS_VERSION]), rootPublicKey,
|
|
98
|
+
// chain: Vec<RootKeyHandoff>, empty
|
|
99
|
+
u32le(0),
|
|
100
|
+
// DeviceCert
|
|
101
|
+
fromHex(account, 'account', 32), fromHex(input.device, 'device', 32), fromHex(input.signPublicKey, 'signPublicKey', 32), fromHex(input.kemPublicKey, 'kemPublicKey', 32), u32le(keyEpoch), u32le(input.deviceEpoch), signature);
|
|
102
|
+
return hex(credential);
|
|
103
|
+
}
|
|
104
|
+
/** The account this root owns — the content address of its genesis. */
|
|
105
|
+
export async function accountForRoot(rootSecret) {
|
|
106
|
+
const rootPublicKey = await derivePublicKey(rootSecret);
|
|
107
|
+
return hex(await domainHash(ACCOUNT_ID_DOMAIN, [
|
|
108
|
+
concat(new Uint8Array([ACCOUNT_GENESIS_VERSION]), rootPublicKey),
|
|
109
|
+
]));
|
|
110
|
+
}
|
package/dist/index.browser.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
function j(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 a of e)a.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 B(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 Re=new Set(["token_reuse","token_revoked"]);function we(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 f=class extends Error{constructor(t,n,r,i,a){let p=we(a);super(p?`HTTP ${t} ${n}: ${p}`:`HTTP ${t} ${n}`);this.status=t;this.statusText=n;this.url=r;this.headers=i;this.bodyText=a;this.name="HTTPError"}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:re(this.headers),bodyText:this.bodyText}}},w=class extends f{constructor(t,n,r,i,a,p){super(n,r,i,a,p);this.reason=t;this.name="AuthRevokedError";this.message=`Authentication revoked (${t}): HTTP ${n} ${r}`}};function re(s){let e={};return s.forEach((t,n)=>{e[n]=t}),e}var v=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:re(n.headers),status:n.status}}async request(e,t){return this.makeRequest(e,t)}async makeRequest(e,t,n=0,r){let a=this.buildUrl(e),p=r??Date.now(),h=this.createAbortSignal(t),l=await this.buildHeaders(t?.headers),u;l instanceof Headers?(u={},l.forEach((c,R)=>{u[R]=c})):u=l;let d={method:t?.method||"GET",headers:u},m=t?.body instanceof ReadableStream||typeof t?.body=="object"&&t?.body!==null&&"getReader"in t.body&&!(t.body instanceof Blob);(t?.body!==void 0&&!m||t?.body!==void 0&&m&&n===0)&&(d.body=t.body);let g;if(n>0&&r!==void 0){let c=t?.timeoutMs||this.transport.timeoutMs;if(c){let R=Date.now()-p,T=Math.max(0,c-R);g=this.createAbortSignal({...t,timeoutMs:T})}else g=this.createAbortSignal(t)}else g=h;g&&(d.signal=g),this.transport.credentials!==void 0&&(d.credentials=this.transport.credentials),t?.mode!==void 0&&(d.mode=t.mode),t?.cache!==void 0&&(d.cache=t.cache),t?.redirect!==void 0&&(d.redirect=t.redirect),t?.referrer!==void 0&&(d.referrer=t.referrer),t?.referrerPolicy!==void 0&&(d.referrerPolicy=t.referrerPolicy),t?.integrity!==void 0&&(d.integrity=t.integrity),t?.keepalive!==void 0&&(d.keepalive=t.keepalive);try{let c=await this.transport.fetch(a,d);if(!c.ok){let R=await this.getBodyText(c),T=new f(c.status,c.statusText,a,c.headers,R),E=c.headers.get("x-auth-error");if((c.status===401||c.status===403)&&E&&Re.has(E)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new w(E,c.status,c.statusText,a,c.headers,R)}let Ce=t?.signal?.aborted===!0;if(c.status===401&&this.transport.refreshToken&&E==="token_expired"&&n<1&&!m&&!Ce)try{let y=this.refreshTokenPromise;y||(y=this.transport.refreshToken(),this.refreshTokenPromise=y);let O=await y;if(!O||O.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 M=this.onTokenRefreshPromise;M||(M=this.transport.onTokenRefresh(O),this.onTokenRefreshPromise=M),await M,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let se=t?.timeoutMs||this.transport.timeoutMs;if(se&&r!==void 0){let be=Date.now()-p;if(se-be<=0)throw T}return this.makeRequest(e,t,n+1,p)}catch(y){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,y instanceof Error&&y.message.includes("onTokenRefresh")?y:T}throw T}return this.parseResponse(c,t?.parse)}catch(c){throw c instanceof f||c instanceof Error&&c.message.includes("onTokenRefresh")?c:new f(0,"Network Error",a,new Headers,c instanceof Error?c.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(B(n)),t.length>0?j(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 V(s){return new v(s)}function A(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 V(e)}function G(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 V(n)}function J(s){return typeof window<"u"?A(s):G(s)}function Ae(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 ke(s){let t=250*Math.pow(2,s-1),n=(Math.random()-.5)*.4*t;return Math.max(0,t+n)}async function U(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,!Ae(n,t-r))throw n;let a=ke(r),l=n.headers?.get?.("Retry-After");if(l){let u=parseInt(l,10);if(!isNaN(u))a=Math.max(a,u*1e3);else{let d=new Date(l);if(!isNaN(d.getTime())){let m=Math.max(0,d.getTime()-Date.now());a=Math.max(a,Math.min(m,6e4))}}}await new Promise(u=>setTimeout(u,a))}throw n||new Error("Retry failed without error")}function xe(s,e={}){return async(...t)=>U(()=>s(...t),e)}var C=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 D=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 pt(s){let e=new D;return new C(e)}function ct(s){let e=new D;return new C(e)}function lt(s){let e=new D;return new C(e)}function ie(s,e){return new C(s)}function o(s){return s?.data}function Te(s,e){let[t,n]=oe(s),[r,i]=oe(e),a=t.split("."),p=r.split("."),h=Math.max(a.length,p.length);for(let m=0;m<h;m++){let g=ae(a[m]??"0",p[m]??"0");if(g!==0)return g}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("."),u=i.split("."),d=Math.max(l.length,u.length);for(let m=0;m<d;m++){if(m>=l.length)return-1;if(m>=u.length)return 1;let g=ae(l[m],u[m]);if(g!==0)return g}return 0}function oe(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 ae(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 pe(s,e,t){return U(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 b=class{constructor(e){this.httpClient=e}async healthCheck(){return o(await this.httpClient.get("/admin-api/health"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return o(await this.httpClient.post("/admin-api/install-application",e))}async installFromRegistry(e,t,n){let r=new URL(e).origin,i=new URL(`/api/v2/bundles/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,r).toString(),p=await(await pe(i,"manifest",`${t}@${n}`)).json(),h=encodeURIComponent(p.package),l=encodeURIComponent(p.appVersion),u=`${r}/artifacts/${h}/${l}/${h}-${l}.mpk`;return this.installApplication({url:u,package:p.package,version:p.appVersion,metadata:[]})}async getRegistryVersions(e,t){let n=new URL("/api/v2/bundles",new URL(e).origin);n.searchParams.set("package",t);let i=await(await pe(n.toString(),"versions",t)).json();return(Array.isArray(i)?i:[]).map(a=>a.appVersion).filter(a=>typeof a=="string").sort((a,p)=>Te(p,a))}async installDevApplication(e){return o(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return o(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return o(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return o(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return o(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,t){let n=t?`?service_name=${encodeURIComponent(t)}`:"";return o(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 o(await this.httpClient.post("/admin-api/contexts",t))}async deleteContext(e,t){return o(t?await this.httpClient.request(`/admin-api/contexts/${e}`,{method:"DELETE",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}}):await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return o(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return o(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return o(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return o(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){await this.httpClient.post(`/admin-api/contexts/sync/${e??""}`,{})}async resyncContext(e,t={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,t)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return o(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=o(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:o(await this.httpClient.get("/admin-api/blobs")).blobs.map(t=>({blobId:t.blob_id,size:t.size}))}}async getBlob(e){return this.httpClient.get(`/admin-api/blobs/${e}`,{parse:"arrayBuffer"})}async getBlobInfo(e){let{headers:t}=await this.httpClient.head(`/admin-api/blobs/${e}`),n=Number(t["content-length"]);return{blobId:t["x-blob-id"]??e,size:Number.isFinite(n)?n:0,hash:t["x-blob-hash"],mimeType:t["x-blob-mime-type"]}}async createContextAlias(e){return o(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return o(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return o(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return o(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return o(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return o(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return o(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return o(await this.httpClient.get("/admin-api/alias/list/application"))}async listNamespaces(){return o(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return o(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return o(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 o(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,t))}async listNamespacesForApplication(e){return o(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return o(await this.httpClient.post("/admin-api/namespaces",{upgradePolicy:"LazyOnAccess",...e}))}async deleteNamespace(e,t){return o(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:JSON.stringify(t??{}),headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,t){return o(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,t??{}))}async joinNamespace(e,t){let n=o(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 o(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,t??{}))}async listNamespaceGroups(e){return o(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async getGroupInfo(e){return o(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,t){return o(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:JSON.stringify(t??{}),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 o(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 o(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,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/sync`,t??{}))}async upgradeGroup(e,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,t))}async getGroupUpgradeStatus(e){return o(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 o(await this.httpClient.get(`/admin-api/groups/${t}/cascade-status`))}async retryGroupUpgrade(e,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,t??{}))}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,n){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${t}/remove`,n??{})}async createGroupInvitation(e,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/invite`,t??{}))}async joinGroup(e){return o(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return o(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return o(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return o(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return o(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 o(await this.httpClient.post("/admin-api/groups",{upgradePolicy:"LazyOnAccess",...e}))}async leaveGroup(e,t){await this.httpClient.post(`/admin-api/groups/${e}/leave`,t??{})}async leaveContext(e,t){await this.httpClient.post(`/admin-api/contexts/${e}/leave`,t??{})}async leaveNamespace(e,t){await this.httpClient.post(`/admin-api/namespaces/${e}/leave`,t??{})}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,t){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,t??{})}};function Ct(s){return new b(A(s))}function bt(s){return new b(G(s))}function Rt(s){return new b(J(s))}function ce(s,e){return new b(s)}function K(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 F(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 H=class extends Error{constructor(e,t,n,r){super(t),this.name="RpcError",this.code=e,this.data=n,this.type=r}};async function z(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 H(r.code??-1,r.message??r.type??"RPC error",r.data,r.type)}return n.result}var P=class{constructor(e){this.httpClient=e.httpClient}async execute(e){let t=await z(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 ve=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function le(s){return s.type!==void 0&&ve.has(s.type)}var De=new Set(["token_reuse","token_revoked"]),k=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=>{le(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&&De.has(r)?new w(r,n.status,n.statusText,t,n.headers,i):new f(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:a}=await t.read();if(i)break;r+=n.decode(a,{stream:!0});let p=r.split(`
|
|
2
|
-
`);r=p.pop()??"";for(let h of p)if(h.startsWith("data:")){let l=h.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 a=i instanceof Error?i:new Error(String(i));this.emit("error",a)}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 N=class N{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),N.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()}};N.MAX_BACKOFF_MS=3e4;var x=N;function $(){return{encode(s){return Array.from(new TextEncoder().encode(JSON.stringify(s)))},decode(s){return JSON.parse(new TextDecoder().decode(new Uint8Array(s)))}}}var S=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,t,n=$()){await z(this.httpClient,"set_ephemeral",{contextId:e,state:n.encode(t)})}subscribe(e,t,n=$()){let r=i=>{let a=i;if(a.type!=="Ephemeral"||a.contextId!==e)return;let p=a.data;if(!p?.author)return;let h=!!p.removed,l={author:p.author,state:h||p.state===void 0?void 0:n.decode(p.state),removed:h};p.ageMs!==void 0&&(l.ageMs=p.ageMs),t(l)};return this.sse.on("event",r),this.sse.connect().catch(()=>{}),this.sse.subscribe([e]).catch(()=>{}),()=>{this.sse.off("event",r)}}};var Pe="mero-js:token-refresh";function Se(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function X(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 _=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=A({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=ce(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 P({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new k({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new S({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}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 x({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:X(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=Se();return t?t.request(Pe,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:X(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||X(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 K(e)}static buildAuthLoginUrl(e,t){return F(e,t)}};function Ie(s){return new _(s)}var q="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Y=/^[0-9a-f]{64}$/i;function Ee(s){if(s.length===0)return"";let e=[0];for(let n of s){let r=n;for(let i=0;i<e.length;i++)r+=e[i]<<8,e[i]=r%58,r=r/58|0;for(;r>0;)e.push(r%58),r=r/58|0}let t="";for(let n of s){if(n!==0)break;t+=q[0]}for(let n=e.length-1;n>=0;n--)t+=q[e[n]];return t}function Me(s){if(s.length===0)return null;let e=[0];for(let n of s){let r=q.indexOf(n);if(r<0)return null;let i=r;for(let a=0;a<e.length;a++)i+=e[a]*58,e[a]=i&255,i>>=8;for(;i>0;)e.push(i&255),i>>=8}let t=0;for(let n of s){if(n!==q[0])break;t++}return Uint8Array.from([...new Array(t).fill(0),...e.reverse()])}function Ge(s){let e="";for(let t of s)e+=t.toString(16).padStart(2,"0");return e}function Ue(s){let e=new Uint8Array(s.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(s.slice(t*2,t*2+2),16);return e}function Q(s){let e=(s??"").trim();if(!e)return"";if(Y.test(e))return e.toLowerCase();let t=Me(e);return!t||t.length!==32?e:Ge(t)}function He(s){let e=(s??"").trim();return e?Y.test(e)?Ee(Ue(e)):e:""}function Ne(s,e){let t=Q(s),n=Q(e);return Y.test(t)&&t===n}var Z=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},$e="mero-tokens",ee=class{constructor(e=$e){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 te=class{constructor(e={}){this.baseUrl=(e.cloudBaseUrl||"https://cloud.calimero.network").replace(/\/+$/,"")}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()}`)}};var _e=new TextEncoder().encode("calimero.warrant.v1"),qe=new TextEncoder().encode("calimero.warrant.intent.v1"),ue=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function Le(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}function I(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 L(s){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(s),!0),e}function W(...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 de(s,e){let t=[L(s.length),s];for(let n of e)t.push(L(n.length),n);return new Uint8Array(await crypto.subtle.digest("SHA-256",W(...t)))}async function ne(s,e){let t=new TextEncoder().encode(JSON.stringify(e));return de(qe,[new TextEncoder().encode(s),t])}async function We(s){let e=I(s,"deviceSecret",32),t=W(ue,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 he(s){let e=I(s.context,"context",32),t=I(s.authorAccount,"authorAccount",32),n=I(s.executor,"executor",32),r=await We(s.deviceSecret),i=await Oe(s.deviceSecret),a=await ne(s.method,s.argsJson),p=L(s.nonce),h=L(s.notAfter),l=await de(_e,[e,t,i,n,a,p,h]),u=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},r,l));return Le(W(e,t,i,n,a,p,h,u))}async function Oe(s){let e=I(s,"deviceSecret",32),t=W(ue,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,"/")),a=>a.charCodeAt(0))}var Zt={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};function en(s,e){let t=e>>>0;return(s&t)>>>0===t}function tn(s,e){return(s|e)>>>0}function nn(s,e){return(s&~e)>>>0}var me=[2428,2429,2528,2529],je="localhost",Be=2e3;function ge(s){return`http://${je}:${s}`}function fe(s,e){let t=s.endsWith("/")?s:`${s}/`;return new URL(e,t).toString()}async function ye(s,e={}){let{timeoutMs:t=Be,signal:n}=e;if(n?.aborted)return!1;let r=new AbortController,i=()=>r.abort(),a=n;a&&a.addEventListener("abort",i,{once:!0});let p=setTimeout(()=>r.abort(),t);try{let h=fe(s,"admin-api/health"),l=await fetch(h,{method:"GET",signal:r.signal});if(!l.ok)return!1;try{let u=await l.json(),d=u?.data?.status!==void 0?u?.data?.status:u?.status;return d===void 0?!0:typeof d=="string"&&d.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(p),a&&a.removeEventListener("abort",i)}}async function Ve(s={}){let{ports:e=me,timeoutMs:t,signal:n}=s;return(await Promise.all(e.map(async i=>{let a=ge(i);return await ye(a,{timeoutMs:t,signal:n})?a:null}))).filter(i=>i!==null)}export{b as AdminApiClient,C as AuthApiClient,w as AuthRevokedError,Zt as CAPABILITIES,te as CloudClient,me as DEFAULT_LOCAL_NODE_PORTS,S as EphemeralClient,f as HTTPError,ee as LocalStorageTokenStore,Z as MemoryTokenStore,_ as MeroJs,P as RpcClient,H as RpcError,k as SseClient,v as WebHttpClient,x as WsClient,F as buildAuthLoginUrl,j as combineSignals,Te as compareSemver,Rt as createAdminApiClient,ce as createAdminApiClientFromHttpClient,lt as createAuthApiClient,ie as createAuthApiClientFromHttpClient,Ct as createBrowserAdminApiClient,pt as createBrowserAuthApiClient,A as createBrowserHttpClient,V as createHttpClient,Ie as createMeroJs,bt as createNodeAdminApiClient,ct as createNodeAuthApiClient,G as createNodeHttpClient,xe as createRetryableMethod,B as createTimeoutSignal,J as createUniversalHttpClient,Ve as discoverLocalNodes,en as hasCap,ne as intentHash,$ as jsonCodec,ge as localNodeUrl,fe as nodeEndpoint,K as parseAuthCallback,ye as probeNodeHealth,Ne as sameAccount,he as signWarrant,He as toAccountBase58,Q as toAccountHex,tn as withCap,U as withRetry,nn as withoutCap};
|
|
1
|
+
function J(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 a of e)a.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 F(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 De=new Set(["token_reuse","token_revoked"]);function Pe(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 y=class extends Error{constructor(t,n,r,i,a){let p=Pe(a);super(p?`HTTP ${t} ${n}: ${p}`:`HTTP ${t} ${n}`);this.status=t;this.statusText=n;this.url=r;this.headers=i;this.bodyText=a;this.name="HTTPError"}toJSON(){return{status:this.status,statusText:this.statusText,url:this.url,headers:pe(this.headers),bodyText:this.bodyText}}},v=class extends y{constructor(t,n,r,i,a,p){super(n,r,i,a,p);this.reason=t;this.name="AuthRevokedError";this.message=`Authentication revoked (${t}): HTTP ${n} ${r}`}};function pe(s){let e={};return s.forEach((t,n)=>{e[n]=t}),e}var E=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:pe(n.headers),status:n.status}}async request(e,t){return this.makeRequest(e,t)}async makeRequest(e,t,n=0,r){let a=this.buildUrl(e),p=r??Date.now(),h=this.createAbortSignal(t),l=await this.buildHeaders(t?.headers),u;l instanceof Headers?(u={},l.forEach((c,A)=>{u[A]=c})):u=l;let d={method:t?.method||"GET",headers:u},m=t?.body instanceof ReadableStream||typeof t?.body=="object"&&t?.body!==null&&"getReader"in t.body&&!(t.body instanceof Blob);(t?.body!==void 0&&!m||t?.body!==void 0&&m&&n===0)&&(d.body=t.body);let f;if(n>0&&r!==void 0){let c=t?.timeoutMs||this.transport.timeoutMs;if(c){let A=Date.now()-p,I=Math.max(0,c-A);f=this.createAbortSignal({...t,timeoutMs:I})}else f=this.createAbortSignal(t)}else f=h;f&&(d.signal=f),this.transport.credentials!==void 0&&(d.credentials=this.transport.credentials),t?.mode!==void 0&&(d.mode=t.mode),t?.cache!==void 0&&(d.cache=t.cache),t?.redirect!==void 0&&(d.redirect=t.redirect),t?.referrer!==void 0&&(d.referrer=t.referrer),t?.referrerPolicy!==void 0&&(d.referrerPolicy=t.referrerPolicy),t?.integrity!==void 0&&(d.integrity=t.integrity),t?.keepalive!==void 0&&(d.keepalive=t.keepalive);try{let c=await this.transport.fetch(a,d);if(!c.ok){let A=await this.getBodyText(c),I=new y(c.status,c.statusText,a,c.headers,A),$=c.headers.get("x-auth-error");if((c.status===401||c.status===403)&&$&&De.has($)){if(this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,this.transport.onAuthRevoked)try{await this.transport.onAuthRevoked()}catch{}throw new v($,c.status,c.statusText,a,c.headers,A)}let ve=t?.signal?.aborted===!0;if(c.status===401&&this.transport.refreshToken&&$==="token_expired"&&n<1&&!m&&!ve)try{let C=this.refreshTokenPromise;C||(C=this.transport.refreshToken(),this.refreshTokenPromise=C);let B=await C;if(!B||B.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 _=this.onTokenRefreshPromise;_||(_=this.transport.onTokenRefresh(B),this.onTokenRefreshPromise=_),await _,this.refreshTokenPromise=null,this.onTokenRefreshPromise=null;let ae=t?.timeoutMs||this.transport.timeoutMs;if(ae&&r!==void 0){let Te=Date.now()-p;if(ae-Te<=0)throw I}return this.makeRequest(e,t,n+1,p)}catch(C){throw this.refreshTokenPromise=null,this.onTokenRefreshPromise=null,C instanceof Error&&C.message.includes("onTokenRefresh")?C:I}throw I}return this.parseResponse(c,t?.parse)}catch(c){throw c instanceof y||c instanceof Error&&c.message.includes("onTokenRefresh")?c:new y(0,"Network Error",a,new Headers,c instanceof Error?c.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(F(n)),t.length>0?J(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 z(s){return new E(s)}function T(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 z(e)}function q(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 z(n)}function Q(s){return typeof window<"u"?T(s):q(s)}function Se(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 Ie(s){let t=250*Math.pow(2,s-1),n=(Math.random()-.5)*.4*t;return Math.max(0,t+n)}async function L(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,!Se(n,t-r))throw n;let a=Ie(r),l=n.headers?.get?.("Retry-After");if(l){let u=parseInt(l,10);if(!isNaN(u))a=Math.max(a,u*1e3);else{let d=new Date(l);if(!isNaN(d.getTime())){let m=Math.max(0,d.getTime()-Date.now());a=Math.max(a,Math.min(m,6e4))}}}await new Promise(u=>setTimeout(u,a))}throw n||new Error("Retry failed without error")}function Ee(s,e={}){return async(...t)=>L(()=>s(...t),e)}var w=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 M=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 pt(s){let e=new M;return new w(e)}function ct(s){let e=new M;return new w(e)}function lt(s){let e=new M;return new w(e)}function ce(s,e){return new w(s)}function o(s){return s?.data}function Me(s,e){let[t,n]=le(s),[r,i]=le(e),a=t.split("."),p=r.split("."),h=Math.max(a.length,p.length);for(let m=0;m<h;m++){let f=ue(a[m]??"0",p[m]??"0");if(f!==0)return f}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("."),u=i.split("."),d=Math.max(l.length,u.length);for(let m=0;m<d;m++){if(m>=l.length)return-1;if(m>=u.length)return 1;let f=ue(l[m],u[m]);if(f!==0)return f}return 0}function le(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 ue(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 de(s,e,t){return L(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 k=class{constructor(e){this.httpClient=e}async healthCheck(){return o(await this.httpClient.get("/admin-api/health"))}async isAuthed(){return this.httpClient.get("/admin-api/is-authed")}async installApplication(e){return o(await this.httpClient.post("/admin-api/install-application",e))}async installFromRegistry(e,t,n){let r=new URL(e).origin,i=new URL(`/api/v2/bundles/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,r).toString(),p=await(await de(i,"manifest",`${t}@${n}`)).json(),h=encodeURIComponent(p.package),l=encodeURIComponent(p.appVersion),u=`${r}/artifacts/${h}/${l}/${h}-${l}.mpk`;return this.installApplication({url:u,package:p.package,version:p.appVersion,metadata:[]})}async getRegistryVersions(e,t){let n=new URL("/api/v2/bundles",new URL(e).origin);n.searchParams.set("package",t);let i=await(await de(n.toString(),"versions",t)).json();return(Array.isArray(i)?i:[]).map(a=>a.appVersion).filter(a=>typeof a=="string").sort((a,p)=>Me(p,a))}async installDevApplication(e){return o(await this.httpClient.post("/admin-api/install-dev-application",e))}async uninstallApplication(e){return o(await this.httpClient.delete(`/admin-api/applications/${e}`))}async listApplications(){return o(await this.httpClient.get("/admin-api/applications"))}async getApplication(e){return o(await this.httpClient.get(`/admin-api/applications/${e}`))}async listApplicationVersions(e){return o(await this.httpClient.get(`/admin-api/applications/${e}/versions`))}async getApplicationAbi(e,t){let n=t?`?service_name=${encodeURIComponent(t)}`:"";return o(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 o(await this.httpClient.post("/admin-api/contexts",t))}async deleteContext(e,t){return o(t?await this.httpClient.request(`/admin-api/contexts/${e}`,{method:"DELETE",body:JSON.stringify(t),headers:{"Content-Type":"application/json"}}):await this.httpClient.delete(`/admin-api/contexts/${e}`))}async getContexts(){return o(await this.httpClient.get("/admin-api/contexts"))}async getContext(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}`))}async getContextsForApplication(e){return o(await this.httpClient.get(`/admin-api/contexts/for-application/${e}`))}async generateContextIdentity(){return o(await this.httpClient.post("/admin-api/identity/context",{}))}async getContextIdentities(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/identities`))}async getContextIdentitiesOwned(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/identities-owned`))}async joinContext(e){return o(await this.httpClient.post(`/admin-api/contexts/${e}/join`,{}))}async getContextGroup(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/group`))}async getContextStorage(e){return o(await this.httpClient.get(`/admin-api/contexts/${e}/storage`))}async syncContext(e){await this.httpClient.post(`/admin-api/contexts/sync/${e??""}`,{})}async resyncContext(e,t={}){return await this.httpClient.post(`/admin-api/contexts/${e}/resync`,t)??{contextId:e,resyncStarted:!0}}async inviteSpecializedNode(e){return o(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=o(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:o(await this.httpClient.get("/admin-api/blobs")).blobs.map(t=>({blobId:t.blob_id,size:t.size}))}}async getBlob(e){return this.httpClient.get(`/admin-api/blobs/${e}`,{parse:"arrayBuffer"})}async getBlobInfo(e){let{headers:t}=await this.httpClient.head(`/admin-api/blobs/${e}`),n=Number(t["content-length"]);return{blobId:t["x-blob-id"]??e,size:Number.isFinite(n)?n:0,hash:t["x-blob-hash"],mimeType:t["x-blob-mime-type"]}}async createContextAlias(e){return o(await this.httpClient.post("/admin-api/alias/create/context",{alias:e.alias,contextId:e.contextId}))}async createApplicationAlias(e){return o(await this.httpClient.post("/admin-api/alias/create/application",{alias:e.alias,applicationId:e.applicationId}))}async lookupContextAlias(e){return o(await this.httpClient.post(`/admin-api/alias/lookup/context/${encodeURIComponent(e)}`,{}))}async lookupApplicationAlias(e){return o(await this.httpClient.post(`/admin-api/alias/lookup/application/${encodeURIComponent(e)}`,{}))}async deleteContextAlias(e){return o(await this.httpClient.post(`/admin-api/alias/delete/context/${encodeURIComponent(e)}`,{}))}async deleteApplicationAlias(e){return o(await this.httpClient.post(`/admin-api/alias/delete/application/${encodeURIComponent(e)}`,{}))}async listContextAliases(){return o(await this.httpClient.get("/admin-api/alias/list/context"))}async listApplicationAliases(){return o(await this.httpClient.get("/admin-api/alias/list/application"))}async listNamespaces(){return o(await this.httpClient.get("/admin-api/namespaces"))}async getNamespace(e){return o(await this.httpClient.get(`/admin-api/namespaces/${e}`))}async getNodeIdentity(){return o(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 o(await this.httpClient.post(`/admin-api/contexts/${e}/intents`,t))}async listNamespacesForApplication(e){return o(await this.httpClient.get(`/admin-api/namespaces/for-application/${e}`))}async createNamespace(e){return o(await this.httpClient.post("/admin-api/namespaces",{upgradePolicy:"LazyOnAccess",...e}))}async deleteNamespace(e,t){return o(await this.httpClient.request(`/admin-api/namespaces/${e}`,{method:"DELETE",body:JSON.stringify(t??{}),headers:{"Content-Type":"application/json"}}))}async createNamespaceInvitation(e,t){return o(await this.httpClient.post(`/admin-api/namespaces/${e}/invite`,t??{}))}async joinNamespace(e,t){let n=o(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 o(await this.httpClient.post(`/admin-api/namespaces/${e}/groups`,t??{}))}async listNamespaceGroups(e){return o(await this.httpClient.get(`/admin-api/namespaces/${e}/groups`))}async getGroupInfo(e){return o(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,t){return o(await this.httpClient.request(`/admin-api/groups/${e}`,{method:"DELETE",body:JSON.stringify(t??{}),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 o(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 o(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,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/sync`,t??{}))}async upgradeGroup(e,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/upgrade`,t))}async getGroupUpgradeStatus(e){return o(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 o(await this.httpClient.get(`/admin-api/groups/${t}/cascade-status`))}async retryGroupUpgrade(e,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/upgrade/retry`,t??{}))}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,n){await this.httpClient.post(`/admin-api/groups/${e}/contexts/${t}/remove`,n??{})}async createGroupInvitation(e,t){return o(await this.httpClient.post(`/admin-api/groups/${e}/invite`,t??{}))}async joinGroup(e){return o(await this.httpClient.post("/admin-api/groups/join",e))}async joinSubgroupInheritance(e){return o(await this.httpClient.post(`/admin-api/groups/${e}/join-via-inheritance`,{}))}async getTeeInfo(){return o(await this.httpClient.get("/admin-api/tee/info"))}async teeAttest(e){return o(await this.httpClient.post("/admin-api/tee/attest",e))}async teeVerifyQuote(e){return o(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 o(await this.httpClient.post("/admin-api/groups",{upgradePolicy:"LazyOnAccess",...e}))}async leaveGroup(e,t){await this.httpClient.post(`/admin-api/groups/${e}/leave`,t??{})}async leaveContext(e,t){await this.httpClient.post(`/admin-api/contexts/${e}/leave`,t??{})}async leaveNamespace(e,t){await this.httpClient.post(`/admin-api/namespaces/${e}/leave`,t??{})}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,t){return this.httpClient.post(`/admin-api/groups/${e}/migration/abort`,t??{})}};function bt(s){return new k(T(s))}function Ct(s){return new k(q(s))}function Rt(s){return new k(Q(s))}function he(s,e){return new k(s)}function X(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 Y(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 O=class extends Error{constructor(e,t,n,r){super(t),this.name="RpcError",this.code=e,this.data=n,this.type=r}};async function Z(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 O(r.code??-1,r.message??r.type??"RPC error",r.data,r.type)}return n.result}var G=class{constructor(e){this.httpClient=e.httpClient}async execute(e){let t=await Z(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 Ge=new Set(["MigrationStarted","MigrationProgress","CascadeProgress","MigrationCompleted"]);function me(s){return s.type!==void 0&&Ge.has(s.type)}var Ue=new Set(["token_reuse","token_revoked"]),D=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=>{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 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&&Ue.has(r)?new v(r,n.status,n.statusText,t,n.headers,i):new y(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:a}=await t.read();if(i)break;r+=n.decode(a,{stream:!0});let p=r.split(`
|
|
2
|
+
`);r=p.pop()??"";for(let h of p)if(h.startsWith("data:")){let l=h.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 a=i instanceof Error?i:new Error(String(i));this.emit("error",a)}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 W=class W{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),W.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()}};W.MAX_BACKOFF_MS=3e4;var P=W;function j(){return{encode(s){return Array.from(new TextEncoder().encode(JSON.stringify(s)))},decode(s){return JSON.parse(new TextDecoder().decode(new Uint8Array(s)))}}}var U=class{constructor(e){this.httpClient=e.httpClient,this.sse=e.sse}async set(e,t,n=j()){await Z(this.httpClient,"set_ephemeral",{contextId:e,state:n.encode(t)})}subscribe(e,t,n=j()){let r=i=>{let a=i;if(a.type!=="Ephemeral"||a.contextId!==e)return;let p=a.data;if(!p?.author)return;let h=!!p.removed,l={author:p.author,state:h||p.state===void 0?void 0:n.decode(p.state),removed:h};p.ageMs!==void 0&&(l.ageMs=p.ageMs),t(l)};return this.sse.on("event",r),this.sse.connect().catch(()=>{}),this.sse.subscribe([e]).catch(()=>{}),()=>{this.sse.off("event",r)}}};var He="mero-js:token-refresh";function Ne(){let e=globalThis.navigator?.locks;return e&&typeof e.request=="function"?e:null}function ee(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 K=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=T({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=ce(this.httpClient,{baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||"",timeoutMs:this.config.timeoutMs}),this.adminClient=he(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 G({httpClient:this.httpClient})),this.rpcClient}get events(){return this.sseClient||(this.sseClient=new D({baseUrl:this.config.baseUrl,getAuthToken:async()=>(await this.getValidToken())?.access_token||""})),this.sseClient}get ephemeral(){return this.ephemeralClient||(this.ephemeralClient=new U({httpClient:this.httpClient,sse:this.events})),this.ephemeralClient}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 P({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:ee(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=Ne();return t?t.request(He,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:ee(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||ee(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 X(e)}static buildAuthLoginUrl(e,t){return Y(e,t)}};function $e(s){return new K(s)}var te=class{constructor(){this.tokens=null}getTokens(){return this.tokens}setTokens(e){this.tokens=e}clear(){this.tokens=null}},_e="mero-tokens",ne=class{constructor(e=_e){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 se=class{constructor(e={}){this.baseUrl=(e.cloudBaseUrl||"https://cloud.calimero.network").replace(/\/+$/,"")}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()}`)}};var ge=new Uint8Array([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]);function S(s){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,s,!0),e}function x(s){return Array.from(s,e=>e.toString(16).padStart(2,"0")).join("")}function g(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 H(s){let e=new Uint8Array(8);return new DataView(e.buffer).setBigUint64(0,BigInt(s),!0),e}function b(...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 R(s,e){let t=[H(s.length),s];for(let n of e)t.push(H(n.length),n);return new Uint8Array(await crypto.subtle.digest("SHA-256",b(...t)))}async function V(s){let e=g(s,"deviceSecret",32),t=b(ge,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 N(s){let e=g(s,"deviceSecret",32),t=b(ge,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,"/")),a=>a.charCodeAt(0))}var qe=new TextEncoder().encode("calimero.warrant.v1"),Le=new TextEncoder().encode("calimero.warrant.intent.v1");async function re(s,e){let t=new TextEncoder().encode(JSON.stringify(e));return R(Le,[new TextEncoder().encode(s),t])}async function fe(s){let e=g(s.context,"context",32),t=g(s.authorAccount,"authorAccount",32),n=g(s.executor,"executor",32),r=await V(s.deviceSecret),i=await N(s.deviceSecret),a=await re(s.method,s.argsJson),p=H(s.nonce),h=H(s.notAfter),l=await R(qe,[e,t,i,n,a,p,h]),u=new Uint8Array(await crypto.subtle.sign({name:"Ed25519"},r,l));return x(b(e,t,i,n,a,p,h,u))}var Oe=new TextEncoder().encode("calimero.device.cert.v1"),ye=new TextEncoder().encode("calimero.account.genesis.v1"),We=new TextEncoder().encode("calimero.device.id.v1"),ie=1;async function be(s,e){if(e.length!==16)throw new Error(`nonce must be 16 bytes, got ${e.length}`);let t=g(s,"account",32);return x(await R(We,[t,e]))}async function oe(s){return R(Oe,[g(s.account,"account",32),g(s.device,"device",32),g(s.signPublicKey,"signPublicKey",32),g(s.kemPublicKey,"kemPublicKey",32),S(s.keyEpoch),S(s.deviceEpoch)])}async function Ce(s){let e=await N(s.rootSecret),t=x(await R(ye,[b(new Uint8Array([ie]),e)])),n=0,r=await oe({account:t,device:s.device,signPublicKey:s.signPublicKey,kemPublicKey:s.kemPublicKey,keyEpoch:n,deviceEpoch:s.deviceEpoch}),i=await V(s.rootSecret),a=new Uint8Array(await crypto.subtle.sign("Ed25519",i,r)),p=b(new Uint8Array([ie]),e,S(0),g(t,"account",32),g(s.device,"device",32),g(s.signPublicKey,"signPublicKey",32),g(s.kemPublicKey,"kemPublicKey",32),S(n),S(s.deviceEpoch),a);return x(p)}async function Re(s){let e=await N(s);return x(await R(ye,[b(new Uint8Array([ie]),e)]))}var rn={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};function on(s,e){let t=e>>>0;return(s&t)>>>0===t}function an(s,e){return(s|e)>>>0}function pn(s,e){return(s&~e)>>>0}var we=[2428,2429,2528,2529],je="localhost",Ke=2e3;function ke(s){return`http://${je}:${s}`}function xe(s,e){let t=s.endsWith("/")?s:`${s}/`;return new URL(e,t).toString()}async function Ae(s,e={}){let{timeoutMs:t=Ke,signal:n}=e;if(n?.aborted)return!1;let r=new AbortController,i=()=>r.abort(),a=n;a&&a.addEventListener("abort",i,{once:!0});let p=setTimeout(()=>r.abort(),t);try{let h=xe(s,"admin-api/health"),l=await fetch(h,{method:"GET",signal:r.signal});if(!l.ok)return!1;try{let u=await l.json(),d=u?.data?.status!==void 0?u?.data?.status:u?.status;return d===void 0?!0:typeof d=="string"&&d.toLowerCase()==="alive"}catch{return!0}}catch{return!1}finally{clearTimeout(p),a&&a.removeEventListener("abort",i)}}async function Ve(s={}){let{ports:e=we,timeoutMs:t,signal:n}=s;return(await Promise.all(e.map(async i=>{let a=ke(i);return await Ae(a,{timeoutMs:t,signal:n})?a:null}))).filter(i=>i!==null)}export{k as AdminApiClient,w as AuthApiClient,v as AuthRevokedError,rn as CAPABILITIES,se as CloudClient,we as DEFAULT_LOCAL_NODE_PORTS,U as EphemeralClient,y as HTTPError,ne as LocalStorageTokenStore,te as MemoryTokenStore,K as MeroJs,G as RpcClient,O as RpcError,D as SseClient,E as WebHttpClient,P as WsClient,Re as accountForRoot,Y as buildAuthLoginUrl,J as combineSignals,Me as compareSemver,Rt as createAdminApiClient,he as createAdminApiClientFromHttpClient,lt as createAuthApiClient,ce as createAuthApiClientFromHttpClient,bt as createBrowserAdminApiClient,pt as createBrowserAuthApiClient,T as createBrowserHttpClient,z as createHttpClient,$e as createMeroJs,Ct as createNodeAdminApiClient,ct as createNodeAuthApiClient,q as createNodeHttpClient,Ee as createRetryableMethod,F as createTimeoutSignal,Q as createUniversalHttpClient,oe as deviceCertPayload,Ve as discoverLocalNodes,on as hasCap,re as intentHash,j as jsonCodec,ke as localNodeUrl,be as mintDeviceId,xe as nodeEndpoint,X as parseAuthCallback,Ae as probeNodeHealth,Ce as signDeviceCert,fe as signWarrant,an as withCap,L as withRetry,pn as withoutCap};
|
|
3
3
|
//# sourceMappingURL=index.browser.mjs.map
|