@tinycloud/web-sdk 3.12.0-beta.5 → 3.12.0-beta.7
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/README.md +29 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/modules/tcw.d.ts +4 -18
- package/dist/openkey-signing-key.d.ts +51 -0
- package/dist/replica.cjs +1 -1
- package/dist/replica.mjs +1 -1
- package/package.json +6 -5
package/dist/modules/tcw.d.ts
CHANGED
|
@@ -223,8 +223,6 @@ export declare class TinyCloudWeb {
|
|
|
223
223
|
private signOutCount;
|
|
224
224
|
/** The signer set with `setRuntimePermissionSigner`, with the session it was set for. */
|
|
225
225
|
private runtimeSigner?;
|
|
226
|
-
/** Set when this instance's session was established through the configured OpenKey client; bound to that session like `runtimeSigner`. */
|
|
227
|
-
private openkeySession?;
|
|
228
226
|
private signOutInFlight;
|
|
229
227
|
private persistedRestoreBlocked;
|
|
230
228
|
private signOutCleanupFailed;
|
|
@@ -528,24 +526,12 @@ export declare class TinyCloudWeb {
|
|
|
528
526
|
requestPermissions(additional: PermissionEntry[], options?: RequestPermissionsOptions): Promise<RequestPermissionsResult>;
|
|
529
527
|
/**
|
|
530
528
|
* Signs the SIWE of a runtime permission grant. Precedence: the signer set with `setRuntimePermissionSigner`, then
|
|
531
|
-
* the OpenKey client
|
|
532
|
-
*
|
|
533
|
-
* `
|
|
529
|
+
* the configured OpenKey client's byte-exact `signMessage` (an OpenKey session's wallet provider does not implement
|
|
530
|
+
* `personal_sign`), signing with the keyId of the connected account after connecting the client first when it is not
|
|
531
|
+
* connected; a missing or ambiguous key throws `OpenKeySigningKeyError`. Without an OpenKey client or a session account,
|
|
532
|
+
* undefined: the connected wallet signs. Only `requestPermissions` calls this; sign-in and session setup never do.
|
|
534
533
|
*/
|
|
535
534
|
private runtimeMessageSigner;
|
|
536
|
-
/**
|
|
537
|
-
* Whether the OpenKey client may sign a runtime grant: always, unless there is POSITIVE evidence that it is not connected. It may sign when
|
|
538
|
-
* this instance's session was established through it (and is still the live session), or when its in-memory `lastAuth` is set (`connect()` ran
|
|
539
|
-
* on this client, for example because the app connected it after a restore), or when it exposes no `lastAuth` at all (a client shape this SDK
|
|
540
|
-
* does not know: today's behaviour, fail open). `lastAuth` is read here because nothing public says it: `@openkey/sdk` 0.12.2 declares
|
|
541
|
-
* `lastAuth = null`, sets it in `connect()` and clears it in `signOut()`; 0.9.0 declares it and sets it in `connect()` but has no `signOut`.
|
|
542
|
-
* `getSessionToken()` always answers null in 0.12.2 and `isConnected()` reads the OpenKey cookie, which can be true when `connect()` never ran
|
|
543
|
-
* on this page. web-sdk documents `@openkey/sdk` >= 0.12.2, so 0.12.2 is the lowest version this was checked against. The clean fix is
|
|
544
|
-
* `signMessage()` rejecting when not connected, in `@openkey/sdk`. Trade-off: an app that connects through a DIFFERENT OpenKey instance than
|
|
545
|
-
* `config.openkey.client`, or restores after an authorize-only sign-in, must call `openkey.connect()` on the configured client or
|
|
546
|
-
* `setRuntimePermissionSigner`.
|
|
547
|
-
*/
|
|
548
|
-
private openkeyClientMaySign;
|
|
549
535
|
/**
|
|
550
536
|
* Sets the signer for runtime permission grants (`requestPermissions`, and the panel's "allow" buttons), or clears
|
|
551
537
|
* it with no argument. For apps whose sign-in is not the SDK's OpenKey flow, for example a restored session whose
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why the SDK did not ask OpenKey to sign.
|
|
3
|
+
*
|
|
4
|
+
* - `OPENKEY_KEY_MISSING`: there is no OpenKey key to sign with. The client is not connected and cannot connect, or its
|
|
5
|
+
* `connect()` answered without a `keyId`.
|
|
6
|
+
* - `OPENKEY_KEY_AMBIGUOUS`: the connected OpenKey key cannot be tied to the session's account: its address is another
|
|
7
|
+
* account's, or it reports none.
|
|
8
|
+
* - `OPENKEY_CONNECTED_RETRY`: popup mode only. The client was not connected, so the SDK connected it. The user needed longer in
|
|
9
|
+
* that popup than the click's user activation lasts, so a sign popup opened right after would be blocked by the browser.
|
|
10
|
+
* Nothing was signed. The client is now connected: ask the user to click Allow again, which signs with the connected key
|
|
11
|
+
* in one popup. Iframe and redirect mode connect and sign in one go and never throw this.
|
|
12
|
+
*
|
|
13
|
+
* None of these opens a sign dialog: the SDK never sends `signMessage` without the keyId of the connected account.
|
|
14
|
+
* Connect the configured client as the session's account (`await openkey.connect()`), or sign runtime grants with
|
|
15
|
+
* `TinyCloudWeb.setRuntimePermissionSigner`.
|
|
16
|
+
*/
|
|
17
|
+
export type OpenKeySigningKeyErrorCode = "OPENKEY_KEY_MISSING" | "OPENKEY_KEY_AMBIGUOUS" | "OPENKEY_CONNECTED_RETRY";
|
|
18
|
+
/**
|
|
19
|
+
* Thrown by `TinyCloudWeb.requestPermissions` (and the panel's "allow" buttons, which call it) when the runtime grant
|
|
20
|
+
* must be signed through the configured OpenKey client but no single connected key can be named, or when the SDK just
|
|
21
|
+
* connected the client in popup mode and the user must click again.
|
|
22
|
+
* `code` is an {@link OpenKeySigningKeyErrorCode}; `name` is `"OpenKeySigningKeyError"`.
|
|
23
|
+
*/
|
|
24
|
+
export declare class OpenKeySigningKeyError extends Error {
|
|
25
|
+
readonly code: OpenKeySigningKeyErrorCode;
|
|
26
|
+
readonly name = "OpenKeySigningKeyError";
|
|
27
|
+
constructor(code: OpenKeySigningKeyErrorCode, message: string);
|
|
28
|
+
}
|
|
29
|
+
/** What `@openkey/sdk`'s `connect()` answers (and keeps in `lastAuth`) that this SDK reads. */
|
|
30
|
+
export interface OpenKeyAuthLike {
|
|
31
|
+
readonly keyId?: unknown;
|
|
32
|
+
readonly address?: unknown;
|
|
33
|
+
}
|
|
34
|
+
/** The parts of an `@openkey/sdk` client the key lookup reads. `lastAuth` is set by `connect()` and cleared by `signOut()`; nothing public says whether the client is connected. */
|
|
35
|
+
export interface OpenKeyConnection {
|
|
36
|
+
readonly lastAuth?: OpenKeyAuthLike | null;
|
|
37
|
+
connect?(opts: {
|
|
38
|
+
mode: "iframe" | "popup" | "redirect";
|
|
39
|
+
}): Promise<OpenKeyAuthLike | null | undefined>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The keyId OpenKey must sign with for `account`: the connected key (`lastAuth`; a getter that throws reads as not
|
|
43
|
+
* connected), else the key `client.connect()` returns, after connecting it first. The key's address must be `account`,
|
|
44
|
+
* case-insensitively. `assertCurrent` runs right after `connect()` and throws when the session ended or changed while the
|
|
45
|
+
* dialog was open.
|
|
46
|
+
*
|
|
47
|
+
* @throws {OpenKeySigningKeyError} no key, a key that is not `account`'s, or (popup mode) a client that was just connected.
|
|
48
|
+
* Whatever `connect()` rejects with (the user closing the dialog) propagates unchanged.
|
|
49
|
+
*/
|
|
50
|
+
export declare function resolveOpenKeySigningKey(client: OpenKeyConnection, account: string, mode: "iframe" | "popup" | "redirect", assertCurrent: () => void): Promise<string>;
|
|
51
|
+
//# sourceMappingURL=openkey-signing-key.d.ts.map
|
package/dist/replica.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var e,t,r={727(e){e.exports=require("@tinycloud/web-sdk")},284(e){e.exports=require("@tinycloud/web-sdk/replica-gated")},913(e){e.exports=import("@tinycloud/replica/kv-storage")},435(e){e.exports=import("@tinycloud/replica/profile-gate")},60(e,t,r){r.r(t),r.d(t,{AUTHORITY_EXPIRY_MARGIN_MS:()=>S,assertRenewalParent:()=>C,assertValidReplicationConfig:()=>c,augmentSignInEntriesWithReplication:()=>f,createReplicationAuthority:()=>x,eraseReplicaLocalCopy:()=>v,establishReplicaSessionStamp:()=>b,hasUnrestrictedGetCoverage:()=>p,mintNodeReplicationGrant:()=>O,replicationScopeFromSignedSession:()=>N,reportReplicaDenial:()=>h,restoreReplicaSessionStamp:()=>R,ucanAttCovers:()=>I,ucanAttUnconstrainedFor:()=>k,verifiedOwnerConsentAnchor:()=>_});var n=r(727);const i=require("@tinycloud/replica");function s(e,t){return"/"===e||t.startsWith(e)}function a(e){const t="string"==typeof e&&e.length>0&&!e.startsWith("/")&&!e.includes("//")&&e.endsWith("/");if("/"!==e&&!t){const t="string"==typeof e?e.replace(/^\/+/,"").replace(/\/+$/,""):"",r=t.length>0&&!t.includes("//")?` Use ${JSON.stringify(`${t}/`)}.`:' Use "/" or a slash-terminated folder path such as "notes/".';throw new TypeError(`Replication prefix must be "/" or a non-empty slash-terminated folder path without empty segments.${r}`)}}var o=r(191);function c(e){if(void 0!==e?.syncScope&&"prefixes"!==e.syncScope)throw new TypeError('replication.syncScope must be "prefixes"');if(void 0!==e?.contentFetch&&"eager"!==e.contentFetch&&"lazy"!==e.contentFetch)throw new TypeError('replication.contentFetch must be "eager" or "lazy"');if(void 0===e||!e.enabled)return;if(void 0===e.storage||null===e.storage)throw new TypeError("replication.enabled requires replication.storage");if(!Array.isArray(e.prefixes)||0===e.prefixes.length)throw new TypeError("replication.prefixes must be a non-empty array");const t=e.grantTtlMs;if(void 0!==t&&(!Number.isFinite(t)||t<=0||t>6048e5))throw new TypeError("replication.grantTtlMs must be a positive number of milliseconds no greater than 604800000");for(const t of e.prefixes)try{a(t)}catch(e){throw new TypeError(e instanceof Error?e.message:String(e))}for(const[t,r]of e.prefixes.entries()){for(const n of e.prefixes.slice(t+1))if(s(r,n)||s(n,r))throw new TypeError(`replication.prefixes must not overlap: ${JSON.stringify(r)} and ${JSON.stringify(n)}`);if(("/"===r||"vault"===r.split("/",1)[0])&&!0!==e.allowSecrets)throw new TypeError(`replication prefix ${JSON.stringify(r)} overlaps the vault namespace; pass allowSecrets to opt in`)}}var l=n.__replicaKV.GET,u=n.__replicaKV.SYNC,d="tinycloud.kv";function p(e,t,r){return(0,n.__replicaIsCapabilitySubset)([{service:d,space:t,path:r,actions:[l]}],[...e]).subset}function f(e){const t=[],r=e.replication;if(void 0===r)return t;const n=[];for(const t of r.prefixes){a(t);const i="/"===t?"":t;(0,o.requiresSecretsOptIn)(e.primarySpaceId,t)&&!0!==r.allowSecrets||p(e.entries,e.primarySpaceId,i)&&n.push(i)}if("prefixes"!==r.syncScope&&n.length===r.prefixes.length&&n.length>0&&p(e.entries,e.primarySpaceId,""))return[{service:d,space:e.primarySpaceId,path:"",actions:[l,u]}];for(const r of n)t.push({service:d,space:e.primarySpaceId,path:r,actions:[l,u]});return t}var y=i.parseUcanGrant;function h(e,t,r,n){if("denied"!==e.status&&"deleted"!==e.status&&"marker"!==e.status)return;const i={type:"replication.lifecycle",at:(new Date).toISOString(),reason:t,action:"denied"===e.status?"denied":"deleted"===e.status?"database_deleted":"marker_set",..."denied"===e.status?{partitions:e.intents}:{},..."marker"===e.status?{code:e.code}:{}};try{r?.(i)}catch{}const{type:s,...a}=i;try{n?.emit(s,a)}catch{}}var g=[150,450];async function v(e,t,r,n){if("indexeddb"!==e?.kind||void 0===e.eraseLocalCopy)return;let i={status:"failed",code:"STORAGE_ERROR",marker:!1};for(let t=0;t<=g.length;t++){t>0&&await new Promise(e=>setTimeout(e,g[t-1]));try{i=await e.eraseLocalCopy({signal:AbortSignal.timeout(3e3)})}catch{i={status:"failed",code:"STORAGE_ERROR",marker:!1}}if("failed"!==i.status)break}const s="marker"===r||"unguarded"===r,a="erased"===i.status?{ok:!0}:{ok:!1,retryNow:"failed"===i.status};if("erased"===i.status||"refused"===i.status&&!s)return{outcome:i,purge:a};const o="failed"===i.status&&i.marker,c={type:"replica.purge.failed",trigger:t,reason:o?"logout_pending":"gate_unavailable",code:i.code,retryNow:"failed"===i.status};for(const e of n)try{e(c)}catch(e){console.error('Error in "replica.purge.failed" handler:',e)}return o?{outcome:i,purge:a,logoutPending:o}:{outcome:i,purge:a}}var E=n.__replicaKV.GET,m=n.__replicaKV.SYNC,w="tinycloud.kv";function _(e,t,r){if("string"!=typeof e.siwe||"string"!=typeof e.signature||"string"!=typeof e.address||"number"!=typeof e.chainId)return null;try{const i=t.validatePersistedSession?.({delegationHeader:e.delegationHeader,delegationCid:e.delegationCid,spaceId:e.spaceId,jwk:e.jwk,address:e.address,chainId:e.chainId,siwe:e.siwe,signature:e.signature});if(!i||!Number.isSafeInteger(Date.parse(i.expiresAt??"")))return null;const s=new n.__replicaSiweMessage(e.siwe).issuedAt;if("string"!=typeof s)return null;const a=Date.parse(s);if(!Number.isSafeInteger(a)||a<0)return null;const o=r(i).filter(t=>t.space===e.spaceId&&"kv"===t.service).map(e=>({...e,service:"tinycloud.kv"}));return o.some(t=>(0,n.__replicaIsCapabilitySubset)([{service:"tinycloud.kv",space:e.spaceId,path:t.path,actions:[n.__replicaKV.GET,n.__replicaKV.SYNC]}],o).subset)?{at:a,source:"siwe"}:null}catch{return null}}function b(e,t,r){if("indexeddb"===e.kind&&"indexeddb"===e.lifecycle?.kind)return e.lifecycle.establishSessionStamp(t,{consentAnchor:r});if("sqlite"===e.kind&&"file"===e.lifecycle?.kind)return e.lifecycle.establishSessionStamp(t,{consentAnchor:r});throw Object.assign(new Error("Replica sign-in requires its platform lifecycle gate."),{code:"REPLICA_GATED",gate:"gate_unavailable"})}function R(e,t,r){if("indexeddb"===e.kind&&"indexeddb"===e.lifecycle?.kind)return e.lifecycle.restoreSessionStamp(t,r);if("sqlite"===e.kind&&"file"===e.lifecycle?.kind)return e.lifecycle.restoreSessionStamp(t,r);throw Object.assign(new Error("Replica restore requires its platform lifecycle gate."),{code:"REPLICA_GATED",gate:"gate_unavailable"})}function T(e,t){return[{service:w,space:e,path:"/"===t?"":t,actions:[E,m]}]}function A(e){if(null==e)return!0;if("object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length)return!0;if(!Array.isArray(e))return!1;try{return(0,n.__replicaCanonicalizeRecapCaveats)(e)===(0,n.__replicaCanonicalizeRecapCaveats)(void 0)}catch{return!1}}function P(e,t){for(const r of[`${t}/kv`,`tinycloud://${t}/kv`])if(e===r||e===`${r}/`)return"/";for(const r of[`${t}/kv/`,`tinycloud://${t}/kv/`])if(e.startsWith(r))return e.slice(r.length)}function I(e,t,r,i,s){for(const[a,o]of Object.entries(e)){const e=P(a,t);if(void 0!==e)for(const[a,c]of Object.entries(o))if((0,n.__replicaActionContains)(a,i)&&(0,n.__replicaIsCapabilitySubset)([{service:w,space:t,path:r,actions:[i]}],[{service:w,space:t,path:e,actions:[a]}]).subset&&(!0===s?.ignoreCaveats||A(c)))return!0}return!1}function k(e,t,r){return I(e,t,r,E)&&I(e,t,r,m)}async function O(e,t,r,i,s){if(r?.renewalOnly&&!i)throw new Error("replication renewal lost its owner session");const a=r?.renewalOnly?{expiry:r.expiryMs,onPrepared:async e=>{C(e.delegationHeader.Authorization,i)}}:void 0===r?.expiryMs?void 0:{expiry:r.expiryMs},o=await s.delegateTo((0,n.__replicaPrincipalDid)(e),t,a);return{ucan:o.delegation.delegationHeader.Authorization,expiresAt:o.delegation.expiry.getTime()}}var S=6e4;function N(e){let t;try{t=y(e.delegationHeader.Authorization)}catch{return}const r=e=>e.split("#",1)[0];if(t.cid===e.delegationCid&&r(t.audience)===r(e.verificationMethod))for(const r of Object.keys(t.att)){const t=r.match(/^(?:tinycloud:\/\/)?(.+?)\/kv(?:\/|$)/)?.[1];if(t!==e.persistedSpace)continue;const i=(0,n.__replicaParseSpaceUri)(t);if(i?.owner&&i.address&&i.chainId)return{space:t,principal:i.owner}}}function C(e,t){const r=y(e);if(r.issuer!==t.verificationMethod.split("#",1)[0]||1!==r.prf.length||r.prf[0]!==t.delegationCid)throw Object.assign(new Error("replication renewal requires the bound owner session parent"),{refused:"NOT_COVERED"})}function x(e){const t=e.replicationSession();let r=null;try{const n=t&&e.verifiedConsentAnchor?.(t);n&&Number.isFinite(n.at)&&"first_install"!==n.source&&(r={at:n.at,source:n.source})}catch{}const n=()=>{const r=e.replicationSession();return void 0!==r&&r===t?r:void 0},i=(t,r)=>{const n=e.planDelegation(t,void 0===r?void 0:{expiry:r});return"refused"in n?n:{path:n.path,parentCid:n.parentCid,expiresAt:n.expiresAt}},s=e=>e.split("#",1)[0],a=e=>{const t=y(e.delegationHeader.Authorization);if(t.cid===e.delegationCid&&s(t.audience)===s(e.verificationMethod))return t},o={get sessionOnly(){const e=n();return void 0===e||void 0===e.siwe},consentAnchor:()=>n()?r:null,get canRenew(){const e=n();return"siwe"===r?.source&&void 0!==e&&void 0!==e.siwe},sessionGrant(t){const i=n();if(void 0===i)return{refused:"SESSION_EXPIRING"};if(null===r&&void 0!==i.siwe)return{refused:"NOT_COVERED"};const s=i.siwe?e.siweExpiration(i.siwe)?.getTime():void 0;if(void 0!==s&&s<=Date.now()+S)return{refused:"SESSION_EXPIRING"};let o;try{const e=a(i);if(!e)return{refused:"NOT_COVERED"};o=e}catch{return{refused:"NOT_COVERED"}}const c=null===o.expiresAt?void 0:1e3*o.expiresAt;return void 0===c||c<=Date.now()+S?{refused:"SESSION_EXPIRING"}:I(o.att,i.spaceId,t,E,{ignoreCaveats:!0})&&I(o.att,i.spaceId,t,m,{ignoreCaveats:!0})?k(o.att,i.spaceId,t)?{ucan:o.jwt,device:{did:i.verificationMethod,jwk:i.jwk}}:{refused:"CAVEATED_AUTHORITY"}:{refused:"NOT_COVERED"}},plan(e){const t=n();if(void 0===t)return{refused:"SESSION_EXPIRING"};if(null===r)return{refused:"NOT_COVERED"};const s=this.sessionGrant(e);if(!("refused"in s)){const e=a(t);return e&&null!==e.expiresAt?{path:"session",parentCid:t.delegationCid,expiresAt:1e3*e.expiresAt}:{refused:"NOT_COVERED"}}return o.sessionOnly?s:i(T(t.spaceId,e))},async mint(t,s,a,o){const c=n();if(void 0===c)throw new Error("replication mint without the bound session");if(void 0===c.siwe)throw new Error("compact delegate sessions cannot mint device grants");if("siwe"!==r?.source)throw new Error("replication mint requires verified owner consent");const l=T(c.spaceId,s),u=i(l,o?.expiryMs);if("refused"in u)throw Object.assign(new Error(`replication authority refused the mint: ${u.refused}`),{refused:u.refused});if(o?.renewalOnly&&"session"!==u.path)throw Object.assign(new Error("replication renewal requires a session parent"),{refused:"NOT_COVERED"});a.throwIfAborted();const d=await new Promise((r,n)=>{const i=()=>n(a.reason??new Error("replication mint aborted"));a.addEventListener("abort",i,{once:!0}),e.mintDelegation(t,l,o).then(e=>{a.removeEventListener("abort",i),r(e)},e=>{a.removeEventListener("abort",i),n(e instanceof Error?e:new Error(String(e)))})});return{ucan:d.ucan,parentCid:u.parentCid,expiresAt:d.expiresAt}}};return o}},230(e,t,r){r.r(t),r.d(t,{ReplicationRuntime:()=>s});var n=r(727),i={now:()=>Date.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),()=>clearTimeout(r)}},s=class{constructor(e,t=i){this.options=e,this.clock=t,this.pending=new Map,this.attached=new Map,this.previous=Promise.resolve(),this.binding=Promise.resolve(),this.generation=0,this.bindingActive=!1,this.pendingPurgeSet=!1,this.closed=!1,this.control={status:async()=>(await this.binding,this.gatedReason?this.options.prefixes.map(e=>({prefix:e,state:"gated",gate:this.gatedReason,errorCode:"REPLICA_GATED",pending:{inFlight:0,committed:0,ambiguous:0},pinned:[],lagMs:null})):this.current?this.current.status():[]),sync:async e=>{if(await this.binding,this.gatedReason)throw Object.assign(new Error("Replica restore is gated."),{code:"REPLICA_GATED",gate:this.gatedReason});this.purgedGeneration!==this.generation&&this.current&&await this.current.sync(e)},purge:e=>{if(this.bindingActive){this.pendingPurge=e,this.pendingPurgeSet=!0;const t=this.current??this.lastController;return t&&(this.pendingPurgeResult=t.purge(e),this.purgedGeneration=this.generation),this.binding.then(()=>this.pendingPurgeResult??{purged:[],failed:[]})}const t=this.current??this.lastController;return t?(this.purgedGeneration=this.generation,t.purge(e)):Promise.resolve({purged:[],failed:[]})},clearPending:async()=>{if(await this.binding,this.current)return this.current.clearPending();const e=this.lastPending;return e?e.update(e=>{const t=e.records.length;return e.records=e.records.filter(e=>"committed"===e.state||"in_flight"===e.state&&this.clock.now()-Date.parse(e.at)<=6e5),t-e.records.length}):0},close:async()=>{this.closed=!0,this.unbind(),await this.binding.catch(()=>{}),await this.previous}}}loadServices(){return this.services??(this.services=Promise.resolve().then(r.bind(r,191)))}detachAll(){for(const e of this.attached.keys())e.setReadThrough(null);this.attached.clear()}bindGatedNetworkOnly(e,t){if(this.closed||!this.options.enabled)return Promise.resolve();const r=this.unbind(),n=this.generation;return this.purgedGeneration=void 0,this.pendingPurge=void 0,this.pendingPurgeResult=void 0,this.pending.clear(),this.lastController=void 0,this.lastPending=void 0,this.lastIdentity=void 0,this.gatedReason=e.gate,this.primarySpace=e.session.spaceId,this.binding=r.then(async()=>{let r;try{({createGatedNetworkReadThrough:r}=await t())}catch{return}if(n!==this.generation||this.closed||"function"!=typeof r)return;const i=r({space:e.session.spaceId,prefixes:this.options.prefixes,now:()=>this.clock.now(),emit:t=>{if(n!==this.generation||this.closed||this.gated!==i)return;try{this.options.onEvent?.(t)}catch{}const{type:r,...s}=t;try{e.context.emit(r,s)}catch{}}});this.gated=i;for(const t of e.primaryKV)this.attach(t.space,t.kv)}),this.binding}bind(e){if(this.closed||!this.options.enabled)return Promise.resolve();this.gated=void 0,this.gatedReason=void 0,this.bindingActive=!0;const t=++this.generation;this.purgedGeneration=void 0,this.unsubscribeConsentExpired?.(),this.unsubscribeConsentExpired=void 0;const{context:r,session:i}=e,s=e=>{try{this.options.onEvent?.(e)}catch{}const{type:t,...n}=e;r.emit(t,n)},a=this.current;this.current=void 0;for(const e of this.attached.keys())e.setReadThrough(null);this.primarySpace=i.spaceId;const o=a?a.close().catch(()=>{}):Promise.resolve();this.previous=this.previous.then(()=>o);const c=this.previous;this.binding=this.loadServices().then(a=>{if(t!==this.generation||this.closed)return;let o;try{o=a.canonicalReplicationIdentity({host:r.hosts[0],space:i.spaceId,principal:e.principal??(0,n.__replicaPkhDid)(e.address,e.chainId)})}catch{for(const e of this.options.prefixes)s({type:"replication.state",at:new Date(this.clock.now()).toISOString(),space:i.spaceId,replica:e,state:"unavailable",code:"CONFIG_INVALID"});return}const l=a.replicationIdentityKey(o);let u=this.pending.get(l);const d=e.stamp;if(!u||u.stamp?.incarnation!==d?.incarnation||u.stamp?.lifecycleEpoch!==d?.lifecycleEpoch){const e=this.options.storage.pendingWrites?.(o,{stamp:d});if(!e&&this.options.storage.lifecycle)throw Object.assign(new Error("Gated replication requires a stamped pending store"),{code:"REPLICA_GATED",gate:"gate_unavailable"});u={stamp:d,store:e??a.createMemoryPendingStore(o)},this.pending.set(l,u)}const p=u.store;this.lastPending=p;const f=a.createKVReplication({options:(y=this.options,{...y,syncIntervalMs:y.syncIntervalMs??6e4,maxStalenessMs:y.maxStalenessMs??12e4,staleSyncTimeoutMs:y.staleSyncTimeoutMs??5e3,allowSecrets:!0===y.allowSecrets,contentFetch:y.contentFetch??"eager",verify:!0===y.verify}),mode:this.options.mode??"background",storage:this.options.storage,identity:o,session:{id:i.delegationCid,did:i.verificationMethod,space:i.spaceId},stamp:e.stamp,authority:e.authority,pending:p,scheduler:this.clock,emit:s,fetch:r.fetch,nodeFeatures:e.nodeFeatures,previous:c});var y;this.current=f,this.unsubscribeConsentExpired=this.options.storage.lifecycle?.subscribeConsentExpired?.(e=>f.observeConsentExpired(e)),this.lastController=f,this.lastIdentity=o;for(const[e,t]of this.attached)e.setReadThrough(t===this.primarySpace?f:null);for(const t of e.primaryKV)this.attach(t.space,t.kv);this.pendingPurgeSet&&(this.pendingPurgeResult=f.purge(this.pendingPurge),this.purgedGeneration=t,this.pendingPurge=void 0,this.pendingPurgeSet=!1)}).finally(()=>{t===this.generation&&(this.bindingActive=!1)});for(const e of this.attached.keys())e.setReadThroughReady?.(this.binding);return this.binding}attach(e,t){this.attached.set(t,e),t.setReadThrough(e===this.primarySpace?this.current??this.gated??null:null);const r=this.generation;return this.binding.then(()=>{r!==this.generation||this.closed||this.attached.get(t)!==e||t.setReadThrough(e===this.primarySpace?this.current??this.gated??null:null)})}unbind(){this.generation++,this.bindingActive=!1,this.pendingPurgeSet=!1,this.unsubscribeConsentExpired?.(),this.unsubscribeConsentExpired=void 0;const e=this.current;this.current=void 0,this.gated=void 0,this.gatedReason=void 0,this.primarySpace=void 0,this.detachAll();const t=this.binding.then(()=>e?.close()).catch(()=>{});return this.previous=this.previous.then(()=>t),this.previous}get boundIdentity(){return this.lastIdentity}}},191(e,t,r){r.r(t),r.d(t,{CLEAR_PENDING_WARNING:()=>F,canonicalReplicationIdentity:()=>$,createKVReplication:()=>Oe,createMemoryPendingStore:()=>Ce,kvPrefixCovers:()=>W,replicationIdentityKey:()=>B,requiresSecretsOptIn:()=>H});var n=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function i(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function s(e){return e.slice(10,e.indexOf("/"))}function a(e){return e.slice(e.indexOf("/")+1)}function o(e){const t={};for(const r of n)s(r.urn)===e&&(t[i(a(r.urn))]=r.urn);return t}var c=o("kv"),l={...o("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},u=(o("duckdb"),o("capabilities")),d=(o("hooks"),o("encryption")),p=o("space"),f=n,y="applications",h="account",g="applications/",v="secrets",E="default",m="public",w="agents",_="tinycloud.encryption",b=d.NETWORK_CREATE,R=[E,y,h,v,m,w],T={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:E,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:E,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:E,path:"",actions:["read","write"]}]},A={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:y,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:y,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:y,path:"",actions:["read","write"]}]},P={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:h,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:h,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:h,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:h,path:"account",actions:["read","write","schema"]}]},I={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:v,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:v,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:v,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:v,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:v,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:v,path:"",actions:["read"],skipPrefix:!0}]},k={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:m,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:m,path:"",actions:["get","list","metadata"]}]},O={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:w,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:w,path:"",actions:["get","put","del","list","metadata"]}]},S={[E]:T,[y]:A,[h]:P,[v]:I,[m]:k,[w]:O};function N(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function C(e,t,r){return!0===r||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function x(e,t,r){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const r=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,n="read"===r||"get"===r?c.GET:"write"===r||"put"===r?c.PUT:"delete"===r||"del"===r?c.DEL:"list"===r?c.LIST:"metadata"===r?c.METADATA:void 0;if(void 0===n)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const i=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${i}`,actions:[n],skipPrefix:!0}})}(e).flatMap(e=>x(e,t,r));const n=!0===e.skipPrefix||e.service===_;return[{service:e.service,space:e.service===_?"encryption":e.space??r,path:C(t,e.path,n),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function D(e){const t=new Set(e.filter(e=>e.service!==_).map(e=>e.space));return function(e){const t=new Map;for(const r of e){const e=`${r.service}\0${r.space}\0${r.path}`,n=t.get(e);if(n)for(const e of r.actions)n.actions.includes(e)||n.actions.push(e);else t.set(e,{...r,actions:[...r.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[u.READ]}))])}function M(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const r=t.includeAccountRegistryPermissions??!0,n=e.map(N),i=n.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??y;return(e.permissions??[]).flatMap(e=>x(e,t,r))});r&&i.push(...G.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of n){const t=s.get(e.app_id)??[];t.push(N(e)),s.set(e.app_id,t)}return{manifests:n,resources:D(i),delegationTargets:[],registryRecords:r?[...s.entries()].map(([e,t])=>({key:`${g}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:n.some(e=>e.includePublicSpace??!0)}}([S[e]],{includeAccountRegistryPermissions:!1})}R.map(e=>({name:e,manifest:S[e],persistedAsApplication:e===v}));var G=Object.freeze([{service:"tinycloud.kv",space:h,path:g,actions:[c.GET,c.PUT,c.LIST]},{service:"tinycloud.kv",space:h,path:"spaces/",actions:[c.GET,c.PUT,c.LIST]},{service:"tinycloud.kv",space:h,path:"system/bootstrap/complete",actions:[c.GET,c.PUT]},{service:"tinycloud.delegation",space:h,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:h,path:"account",actions:[l.READ,l.WRITE,l.SCHEMA]},{service:"tinycloud.capabilities",space:h,path:"",actions:[u.READ]}]),L=M(E),U={...L,resources:[...L.resources,...G.map(e=>({...e,actions:[...e.actions]}))]},q=Object.freeze(Object.fromEntries(R.map(e=>[e,e===E?U:M(e)]))),j=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[b]}]);Object.freeze(R.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:q[e].resources,...e===h?{rawAbilities:j}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[p.HOST]}]));var F="Clearing pending writes surrenders read-your-writes protection for the cleared keys. If a write whose record was cleared had an unknown outcome or never finished, it may commit now or later; this device can serve an older value until the next sync after that commit, as it would for a write from another device.",V=/^(tinycloud:pkh:eip155:\d+:)([^:]+)(:.+)$/,X=/^(did:pkh:eip155:\d+:)([^:]+)$/;function $(e){if(!e||"string"!=typeof e.host||"string"!=typeof e.space||"string"!=typeof e.principal)throw new TypeError("Replication identity host, space, and principal must be strings");const t=/^https?:\/\/([^/?#]*)/i.exec(e.host)?.[1];let r;try{r=new URL(e.host)}catch{throw new TypeError("Replication identity host must be an absolute HTTP(S) URL")}if(!t||t.includes("@")||e.host.includes("?")||e.host.includes("#")||r.username||r.password)throw new TypeError("Replication identity host must be HTTP(S) without credentials, query, or fragment");const n=V.exec(e.space),i=X.exec(e.principal);if(!n||!i)throw new TypeError("Replication identity requires a full TinyCloud space id and a pkh principal DID");return{host:`${r.origin}${r.pathname.replace(/\/+$/,"")}`,space:`${n[1]}${n[2].toLowerCase()}${n[3]}`,principal:`${i[1]}${i[2].toLowerCase()}`}}function B(e){const t=$(e);return`tc-replication/v1\n${t.host}\n${t.space}\n${t.principal}`}function W(e,t){return"/"===e||t.startsWith(e)}function K(e,t){return""===e||t===e||t.startsWith(e.endsWith("/")?e:`${e}/`)}function H(e,t){return"/"===t||!("secrets"!==e&&!e.endsWith(":secrets"))||"vault"===t.split("/",1)[0]}var z={NODE_NOT_RESPONDING:!0,PARTIAL_NODE_WRITE:!0,NODE_IDENTITY_MISMATCH:!0,RESOURCE_NOT_ROUTED:!0,DECRYPTION_DEPENDENCY_UNAVAILABLE:!0,registry_unavailable:!0,node_not_found:!0,node_registry_entry_exists:!0};var Y="NETWORK_ERROR",J="TIMEOUT",Q="ABORTED",Z="INVALID_INPUT",ee="KV_NOT_FOUND";function te(e){return{ok:!0,data:e}}function re(e){return{ok:!1,error:e}}function ne(e,t,r,n){return{code:e,message:t,service:r,cause:n?.cause,meta:n?.meta}}var ie=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function se(e,t,r){return void 0===t?{code:J,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:J,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function ae(e,t,r=Y){const n=function(e){if("object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"string"==typeof e.code&&"string"==typeof e.message&&(t=e.code,Object.prototype.hasOwnProperty.call(z,t))){const t="meta"in e?e.meta:void 0;let r="object"!=typeof t||null===t||Array.isArray(t)?void 0:t;return"NODE_NOT_RESPONDING"===e.code&&"hosts"in e&&Array.isArray(e.hosts)?r={...r,hosts:e.hosts}:"PARTIAL_NODE_WRITE"===e.code&&"succeeded"in e&&Array.isArray(e.succeeded)&&"failed"in e&&Array.isArray(e.failed)&&(r={...r,succeeded:e.succeeded,failed:e.failed}),{code:e.code,message:e.message,...e instanceof Error?{cause:e}:{},...r?{meta:r}:{}}}var t}(t);return n?{...n,service:e}:t instanceof Error?function(e){return e instanceof ie||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}(t)?se(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:Q,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?se(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}new Set(f.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),new Set(f.map(({service:e})=>e.slice(10)));var oe=new Set(["AUTH_REQUIRED",Z,"AUTH_UNAUTHORIZED","KV_PRECONDITION_FAILED","STORAGE_QUOTA_EXCEEDED","STORAGE_LIMIT_REACHED"]);function ce(e){return{v:2,identity:{...e},committedEpoch:0,seq:0,records:[]}}function le(e,t,r,n=100){return e.records.filter(e=>W(t,e.key)&&("in_flight"===e.state||"ambiguous"===e.state)).sort((e,t)=>e.seq-t.seq).slice(0,n).map(e=>({key:e.key,state:e.state,op:e.op,since:e.at,...e.code?{code:e.code}:{},likelyOrphaned:"in_flight"===e.state&&r-Date.parse(e.at)>6e5}))}function ue(e,t,r,n){if(n)return e;const i=(new TextDecoder).decode(e);if(r)return i;if(t?.includes("application/json"))return JSON.parse(i);if(t?.startsWith("text/"))return i;if(i)try{return JSON.parse(i)}catch{return i}}var de=new TextEncoder,pe=new TextDecoder("utf-8",{fatal:!0});function fe(e,t){const r=de.encode(e),n=de.encode(t);for(let e=0;e<Math.min(r.length,n.length);e++)if(r[e]!==n[e])return r[e]-n[e];return r.length-n.length}function ye(e,t,r){const n=de.encode(JSON.stringify({v:1,space:e,path:t,last:r}));let i="";for(let e=0;e<n.length;e+=32768)i+=String.fromCharCode(...n.subarray(e,e+32768));return`tcr1.${btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function he(e){try{const t=e.slice(5).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t+"=".repeat((4-t.length%4)%4)),n=Uint8Array.from(r,e=>e.charCodeAt(0)),i=JSON.parse(pe.decode(n));return 1===i?.v&&"string"==typeof i.space&&"string"==typeof i.path&&"string"==typeof i.last?i:null}catch{return null}}function ge(){return re(ne(Z,"Local list cursor cannot be served; restart without the cursor","kv",{meta:{replication:"cursor_restart"}}))}function ve(e,t){return e.find(e=>W(e,t))}var Ee=864e5,me=Ee,we=7*Ee,_e=7*Ee,be=Number.NEGATIVE_INFINITY,Re=({now:e,grantTtlMs:t,consentDeadline:r})=>Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(r)?Math.min(Math.min(t,we),r-e):0,Te=3e3,Ae=Te,Pe=e=>new Date(e).toISOString(),Ie=e=>"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"REPLICA_UNAVAILABLE";function ke(e,t){if(t.aborted)return Promise.reject(t.reason??Object.assign(new Error("KV request was aborted"),{code:Q}));let r=()=>{};const n=new Promise((e,n)=>{const i=()=>n(t.reason??Object.assign(new Error("KV request was aborted"),{code:Q}));t.addEventListener("abort",i,{once:!0}),r=()=>t.removeEventListener("abort",i)});return Promise.race([e,n]).finally(r)}function Oe(e){const{options:t,mode:r,storage:n,identity:i,session:s,authority:a,pending:o,scheduler:c}=e,l=t=>function(e,t,r){try{e({...r,at:new Date(t.now()).toISOString()})}catch{}}(e.emit,c,t),u=new Map,d=new Set;let p=!1,f=!1,y=!1,h=e.previous,g=!1;const v=new Set;let E=!1,m=null;try{w=a.consentAnchor?.()??null,_=c.now(),m=null!==w&&Number.isFinite(w.at)&&Number.isFinite(_)?w.at>_?{at:_,source:w.source}:w:null,"first_install"===m?.source&&(m=null)}catch{E=!0}var w,_;const b={grantTtlMs:t.grantTtlMs??me,consentAnchor:m},R=void 0===t.maxBytes&&void 0===t.minFreeBytes?void 0:{maxBytes:t.maxBytes,minFreeBytes:t.minFreeBytes},T=null===m?null:(e=>Number.isFinite(e.at)?e.at+_e:be)(m);let A,P=null;function I(){if("indexeddb"!==n.kind||!e.stamp)return null;try{const t=n.lifecycle?.consentDeadline(e.stamp);return"number"==typeof t&&Number.isFinite(t)?t:null}catch{return null}}function k(){if(null===T)return null;if("indexeddb"!==n.kind)return T;const e=I();return null===e?null:Math.min(T,e)}const O=new Set;let S=!1;function N(){const t=n.lifecycle;if(!t)return"indexeddb"===n.kind||E||void 0!==e.stamp?{status:"gated",gate:"gate_unavailable"}:{status:"allow"};if(!e.stamp)return{status:"gated",gate:"not_established"};if(S)return{status:"gated",gate:"stamp_stale"};try{const r=t.checkDelivery(e.stamp);if("consent_expired"===r.status&&x(),"allow"!==r.status)return r;if("indexeddb"===n.kind){const e=I();if(null===e)return{status:"gated",gate:"gate_unavailable"};const t=c.now();if(!Number.isFinite(t))return{status:"gated",gate:"gate_unavailable"};if(t>=e)return x(),{status:"consent_expired",code:"CONSENT_EXPIRED"}}return E?{status:"gated",gate:"gate_unavailable"}:r}catch{return{status:"gated",gate:"gate_unavailable"}}}function C(){if(S||p||f)return!1;A?.(),A=void 0,S=!0;for(const e of u.values()){e.renewalTimer?.(),e.renewalTimer=void 0,e.mintAbort?.abort();const t=e.handle?.replicaId;t&&!O.has(t)&&(O.add(t),l({type:"replication.grant",replicaId:t,action:"consent_deadline_reached",code:"CONSENT_EXPIRED"}))}return!0}function x(){const e=n.lifecycle;e&&C()&&e.deny({reason:"consent_expired",principal:i.principal}).then(e=>l({type:"replication.lifecycle",action:"denied"===e.status?"denied":"stale"===e.status?"deny_stale":"deleted"===e.status?"database_deleted":"marker"===e.status?"marker_set":"unguarded",reason:"consent_expired"}),()=>l({type:"replication.lifecycle",action:"deny_failed",reason:"consent_expired"}))}function D(e){return Object.assign(new Error("consent_expired"===e.status?"Replica consent expired":"Replica session is gated"),{code:"consent_expired"===e.status?e.code:"REPLICA_GATED",..."gated"===e.status?{gate:e.gate}:{}})}function M(e){return"CONSENT_EXPIRED"===e||"GRANT_EXPIRED"===e?"grant_expired":"REPLICA_GATED"===e?"replica_gated":"replica_error"}function G(e,t,r){if(!(r?.unconstrained&&t.replicaId&&"number"==typeof r.effectiveExpiresAt&&Number.isFinite(r.effectiveExpiresAt)&&(null===r.expiresAt||r.effectiveExpiresAt<r.expiresAt)))return;const n=`${r.cid}:${r.effectiveExpiresAt}`;e.reportedCappedCid!==n&&(e.reportedCappedCid=n,l({type:"replication.grant",replicaId:t.replicaId,action:"capped",effectiveExpiresAt:Pe(r.effectiveExpiresAt)}))}const L=e=>t.prefixes.find(t=>W(t,e));function U(e,t){if("GRANT_REVOKED"!==Ie(t))return;const r=u.get(e)??{};r.authorityRevoked=!0,r.reason="grant_revoked",r.lastError="GRANT_REVOKED",u.set(e,r)}function q(e){const t=u.get(e)??{},r="REPLICATION_ROOT_UNSUPPORTED"!==t.lastError;t.reason="replica_unavailable",t.lastError="REPLICATION_ROOT_UNSUPPORTED",u.set(e,t),r&&l({type:"replication.state",space:s.space,replica:e,state:"unavailable",code:"REPLICATION_ROOT_UNSUPPORTED"})}function j(e){return q(e),Object.assign(new Error("This node doesn't support whole-space sync yet."),{code:"REPLICATION_ROOT_UNSUPPORTED"})}function F(e){try{if(!0!==a.sessionOnly)return;const t=a.sessionGrant(e);return"refused"in t?t.refused:void 0}catch{return"NOT_COVERED"}}async function V(o){const d=N();if("allow"!==d.status)throw D(d);if(p||f)throw Object.assign(new Error("Replication controller is closed"),{code:"REPLICA_CLOSED"});let y=u.get(o);if(y?.handle)return y.handle;if(y?.opening)return y.opening;if(y??(y={}),u.set(o,y),y.unsupported)throw Object.assign(new Error("Replication runtime is unsupported"),{code:"RUNTIME_UNSUPPORTED"});if(void 0!==y.retryAt&&c.now()<y.retryAt)throw Object.assign(new Error("Replica open is backing off"),{code:y.lastError??"REPLICA_UNAVAILABLE"});if(H(s.space,o)&&!t.allowSecrets){const e="SECRETS_OPT_IN_REQUIRED"!==y.lastError;throw y.reason="replica_unavailable",y.lastError="SECRETS_OPT_IN_REQUIRED",e&&l({type:"replication.state",space:s.space,replica:o,state:"unavailable",code:"SECRETS_OPT_IN_REQUIRED"}),Object.assign(new Error("Replication requires allowSecrets for this space or prefix"),{code:"SECRETS_OPT_IN_REQUIRED"})}y.opening=(async()=>{h&&(await h,h=void 0);const u=N();if("allow"!==u.status)throw D(u);const d=!0===a.sessionOnly,g=a.sessionGrant(o),v="refused"in g?void 0:g,E=d?void 0:a.plan(o);let w,_;"refused"in g&&(w=g.refused),E&&"refused"in E&&(w??(w=E.refused)),e.stamp&&null===m&&!d&&(w="REPLICA_GATED"),v&&(_=v.device,y.strategy="session");const A={identity:i,space:s.space,prefix:o,allowSecrets:t.allowSecrets,grantPolicy:b,...R?{quota:R}:{},...t.contentFetch?{contentFetch:t.contentFetch}:{},...e.stamp?{stamp:e.stamp}:{},..._?{device:_}:{},...e.fetch?{fetch:e.fetch}:{},onPeerCommit:e=>{p||f||void 0===y.handle||l({type:"replication.sync",space:s.space,replica:o,trigger:"peer",origin:"peer",outcome:"ok",durationMs:0,lagMs:null,...void 0===e.changes?{}:{changes:e.changes},...void 0===e.coverage?{}:{coverage:e.coverage}})}};if("/"===o&&void 0!==e.nodeFeatures&&!e.nodeFeatures.includes("kv-sync-root"))throw j(o);const P=await n.open(A);y.handle=P;const O=N();if("allow"!==O.status)throw D(O);l({type:"replication.state",space:s.space,replica:o,state:"opened"});const S=d||!E||"refused"in E?void 0:E;let C,x=S||v?await P.grant():void 0;if(x&&!function(t,r){if(!t?.unconstrained)return!1;if(!e.stamp)return!0;if(!r&&null===m)return!1;const i=c.now(),s="indexeddb"===n.kind?I():T??t.consentDeadline;return"active"===t.state&&"number"==typeof t.installedAt&&Number.isFinite(t.installedAt)&&"number"==typeof t.effectiveExpiresAt&&Number.isFinite(t.effectiveExpiresAt)&&"number"==typeof t.consentDeadline&&Number.isFinite(t.consentDeadline)&&"number"==typeof s&&Number.isFinite(s)&&Number.isFinite(i)&&i>=t.installedAt&&(null===t.expiresAt||"number"==typeof t.expiresAt&&Number.isFinite(t.expiresAt)&&i<t.expiresAt)&&i<Math.min(t.effectiveExpiresAt,t.consentDeadline,s)}(x,d)&&(x.unconstrained&&(w=null!==m||d?"GRANT_EXPIRED":"REPLICA_GATED"),x=void 0),v&&null!==m){const e=N();if("allow"!==e.status)throw D(e);x=await P.installGrant(v.ucan)}else if(S){if(!x||!x.unconstrained||x.parentCid!==S.parentCid||null!==x.expiresAt&&S.expiresAt>x.expiresAt+3e5){const e=k(),t=Re({now:c.now(),grantTtlMs:b.grantTtlMs,consentDeadline:e??Number.NaN});if(t>0)try{const e=new AbortController;y.mintAbort=e;const r=await a.mint(P.deviceDid,o,e.signal,{expiryMs:t}),n=N();if("allow"!==n.status)throw D(n);x=await P.installGrant(r.ucan),y.strategy="minted",C=t}catch(e){if("CONSENT_EXPIRED"===Ie(e)||"REPLICA_GATED"===Ie(e)||!x?.unconstrained)throw e}finally{y.mintAbort=void 0}}x?.unconstrained&&(y.strategy??(y.strategy="installed"),y.reason=void 0)}else(v||d)&&x?.unconstrained&&(y.strategy="installed");const M=N();if("allow"!==M.status)throw D(M);if(G(y,P,x),void 0!==C&&(y.reportedExpired=!1),void 0!==C&&P.replicaId&&l({type:"replication.grant",replicaId:P.replicaId,action:"minted",expiryMs:C}),x?.unconstrained?l({type:"replication.state",space:s.space,replica:o,state:"grant_installed",strategy:y.strategy}):(y.reason="grant_missing",y.lastError=w??"SESSION_LACKS_SYNC",l({type:"replication.state",space:s.space,replica:o,state:"grant_missing",code:y.lastError})),p||f)throw await P.close(),Object.assign(new Error("Replication controller is closed"),{code:"REPLICA_CLOSED"});return x?.unconstrained&&await $(o,P,x,S),"background"===r&&"grant_missing"!==y.reason&&(z(o,"start").catch(()=>{}),B(o)),P})();try{return await y.opening}catch(e){const t=Ie(e);throw"CONSENT_EXPIRED"===t&&x(),U(o,e),"REPLICA_GATED"===t||"CONSENT_EXPIRED"===t?y.reason=M(t):"GRANT_REVOKED"!==t&&(y.reason="replica_unavailable"),y.lastError=t,y.failures=(y.failures??0)+1,"RUNTIME_UNSUPPORTED"===t?y.unsupported=!0:"REPLICA_CLOSED"!==t&&"REPLICATION_ROOT_UNSUPPORTED"!==t&&"REPLICA_GATED"!==t&&"CONSENT_EXPIRED"!==t&&(y.retryAt=c.now()+Math.min(3e5,5e3*2**Math.min(y.failures-1,6))),y.handle?.close().catch(()=>{}),y.handle=void 0,e}finally{y.opening=void 0}}function X(e,t,r,n){const i=u.get(e);if(i?.renewalTimer?.(),i&&(i.renewalTimer=void 0),!i||p||f||"session"!==n.path||!a.canRenew)return;const{installedAt:s,effectiveExpiresAt:o}=r,l=k();if(!("number"==typeof s&&Number.isFinite(s)&&"number"==typeof o&&Number.isFinite(o)&&o>s&&null!==l))return;const d=s+.75*(o-s),y=c.now();Number.isFinite(y)&&d<l&&!(y>d)&&(i.renewalTimer=c.setTimeout(()=>{i.renewalTimer=void 0,$(e,t).catch(()=>{})},Math.max(0,Math.floor(d)+1-y)))}async function $(e,t,r,n){const i=u.get(e);if(!i||i.handle!==t||p||f||!a.canRenew)return;if(i.renewing)return i.renewing;if("allow"!==N().status)return;const s=r??await t.grant();if(!s?.unconstrained)return;const{installedAt:o,effectiveExpiresAt:d}=s,y=k();if("number"!=typeof o||!Number.isFinite(o)||"number"!=typeof d||!Number.isFinite(d)||null===y)return;const h=c.now();if(!(({now:e,installedAt:t,effectiveExpiresAt:r,consentDeadline:n})=>!!(Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(r)&&Number.isFinite(n))&&e<n&&r-e<.25*(r-t))({now:h,installedAt:o,effectiveExpiresAt:d,consentDeadline:y}))return void(n&&X(e,t,s,n));let g=n;try{if(!g){const r=a.plan(e);if("refused"in r)return void(t.replicaId&&l({type:"replication.grant",replicaId:t.replicaId,action:"renewal_refused",code:r.refused}));g=r}}catch{return void(t.replicaId&&l({type:"replication.grant",replicaId:t.replicaId,action:"renewal_deferred"}))}if("session"!==g?.path)return void(t.replicaId&&i.reportedRenewalUnqualifiedCid!==s.cid&&(i.reportedRenewalUnqualifiedCid=s.cid,l({type:"replication.grant",replicaId:t.replicaId,action:"renewal_deferred"})));const v=Re({now:h,grantTtlMs:b.grantTtlMs,consentDeadline:y});if(!(v>0))return;i.renewalTimer?.(),i.renewalTimer=void 0;const E=new AbortController;i.mintAbort=E;const m=Promise.resolve().then(async()=>{const r=await a.mint(t.deviceDid,e,E.signal,{expiryMs:v,renewalOnly:!0}),n=N();if("allow"!==n.status)throw D(n);const s=await t.installGrant(r.ucan),o=N();if("allow"!==o.status)throw D(o);G(i,t,s),i.reportedExpired=!1,"grant_expired"===i.reason&&(i.reason=void 0),"GRANT_EXPIRED"===i.lastError&&(i.lastError=void 0),t.replicaId&&l({type:"replication.grant",replicaId:t.replicaId,action:"renewed",expiryMs:v}),"number"==typeof s.effectiveExpiresAt&&s.effectiveExpiresAt>d&&X(e,t,s,g)});i.renewing=m;try{await m}catch(e){const r=Ie(e);if("CONSENT_EXPIRED"===r||"REPLICA_GATED"===r)throw e;if(!p&&t.replicaId){const n="object"==typeof e&&null!==e&&"refused"in e&&"string"==typeof e.refused?e.refused:null;l({type:"replication.grant",replicaId:t.replicaId,action:n?"renewal_refused":"renewal_deferred",code:n??r})}}finally{i.renewing=void 0,i.mintAbort===E&&(i.mintAbort=void 0)}}function B(e){const n=u.get(e);!n||"background"!==r||p||f||(n.timer=c.setTimeout(()=>{n.timer=void 0,z(e,"interval").catch(()=>{}).finally(()=>B(e))},t.syncIntervalMs))}async function z(t,r,n,i){if("/"===t&&void 0!==e.nodeFeatures&&!e.nodeFeatures.includes("kv-sync-root"))throw j(t);const a=F(t);if(a)throw Object.assign(new Error("Current session does not cover replica sync"),{code:a});const d=await V(t),p=u.get(t);if(p.sync)return p.sync;const f=new AbortController,y=i??{};p.syncContext=y,p.abort=f;const h=()=>{y.abortCause??(y.abortCause="caller"),f.abort(n?.reason)};n?.addEventListener("abort",h,{once:!0});const g=c.now();let E;E=(async()=>{try{const e=(await o.read()).committedEpoch,n=N();if("allow"!==n.status)throw D(n);await $(t,d);const i=N();if("allow"!==i.status)throw D(i);const a=F(t);if(a)throw Object.assign(new Error("Current session does not cover replica sync"),{code:a});const u=await d.sync({signal:f.signal,syncStartEpoch:e}),p=N();if("allow"!==p.status)throw D(p);if("busy"===u.status)return l({type:"replication.sync",space:s.space,replica:t,trigger:r,outcome:"busy",durationMs:c.now()-g,lagMs:null}),u;v.add(t);const y=await o.read(),h=N();if("allow"!==h.status)throw D(h);const E=y.records.some(r=>"committed"===r.state&&null!==r.epoch&&r.epoch<=e&&W(t,r.key))?await o.update(r=>function(e,t,r){const n=e.records.length;return e.records=e.records.filter(e=>!("committed"===e.state&&null!==e.epoch&&e.epoch<=r&&W(t,e.key))),n-e.records.length}(r,t,e)):0,m=N();if("allow"!==m.status)throw D(m);return l({type:"replication.sync",space:s.space,replica:t,trigger:r,outcome:"ok",durationMs:c.now()-g,lagMs:null,pendingCleared:E,pages:u.pages,changes:u.changes,deleted:u.deleted,fetched:u.fetched,contentMissing:u.contentMissing,coverage:u.coverage}),u}catch(e){const n=Ie(e);throw p.lastError=n,U(t,e),"CONSENT_EXPIRED"===n&&x(),l({type:"replication.sync",space:s.space,replica:t,trigger:r,outcome:f.signal.aborted?"aborted":"error",class:"CONSENT_EXPIRED"===n||"REPLICA_GATED"===n?"lifecycle":"NETWORK_ERROR"===n||"TIMEOUT"===n?"offline":"node",code:n,durationMs:c.now()-g,lagMs:null}),e}finally{n?.removeEventListener("abort",h),p.abort=void 0}})(),p.sync=E;try{return await E}finally{p.sync===E&&(p.sync=void 0,p.syncContext=void 0)}}async function J(e,t){let r=()=>{};const n=t.then(e=>({settled:!0,result:e}),e=>({settled:!0,error:e})),i=new Promise(e=>{r=c.setTimeout(()=>e({settled:!1}),Te)});try{const t=await Promise.race([n,i]);return t.settled||l({type:"replication.sync",space:s.space,replica:e,trigger:"stale_read",outcome:"aborted",code:"DRAIN_TIMEOUT",durationMs:Te,lagMs:null}),t}finally{r()}}function Q(e){if("complete"!==e.coverage)throw Object.assign(new Error("Replica coverage changed before the local read"),{code:"COVERAGE_INCOMPLETE"});if("valid"!==e.authority){const t="expired"===e.authority?"GRANT_EXPIRED":"revoked"===e.authority?"GRANT_REVOKED":"GRANT_NOT_YET_VALID";throw Object.assign(new Error("Replica authority changed before the local read"),{code:t})}}function Z(e){return"COVERAGE_INCOMPLETE"===e?"coverage_incomplete":"GRANT_EXPIRED"===e?"grant_expired":"GRANT_REVOKED"===e?"grant_revoked":"GRANT_NOT_YET_VALID"===e?"grant_not_yet_valid":"replica_error"}function ie(e,t,r){if("error"in e){const n=Ie(e.error);return"NETWORK_ERROR"===n||t&&("ABORTED"===n||"TIMEOUT"===n)?{status:r,syncedBeforeRead:!1,syncError:"NETWORK_ERROR"===n?n:"TIMEOUT"}:{status:r,syncedBeforeRead:!1,syncError:n,failure:"error"}}return"busy"===e.result.status?{status:r,syncedBeforeRead:!1,failure:"busy"}:{status:r,syncedBeforeRead:!0}}async function se(e,n,i){let s=await n.status();const a=null===s.lastSyncAt?null:Date.parse(s.lastSyncAt),l=null===a||!Number.isFinite(a)||c.now()-a>t.maxStalenessMs;let d;try{d=await o.read()}catch(e){return{status:s,syncedBeforeRead:!1,syncError:Ie(e),failure:"error"}}const p=s.syncedThroughEpoch<d.committedEpoch,f=!o.durable&&!v.has(e);if((l||p||f)&&!i.aborted){const a="foreground"===r?new AbortController:void 0,o=u.get(e),l=!o?.sync,d=o?.syncContext??{},p=()=>{l&&(d.abortCause??(d.abortCause="caller")),a?.abort(i.reason)};a&&i.addEventListener("abort",p,{once:!0});let f=()=>{};const y=new Promise(e=>{f=c.setTimeout(()=>e({timeout:!0}),t.staleSyncTimeoutMs)});let h=()=>{};const g=new Promise(e=>{if(i.aborted)e({callerAborted:!0});else{const t=()=>e({callerAborted:!0});i.addEventListener("abort",t,{once:!0}),h=()=>i.removeEventListener("abort",t)}}),v=z(e,"stale_read",a?.signal,d),E=await Promise.race([v.then(e=>({result:e}),e=>({error:e})),y,g]);if(f(),h(),i.removeEventListener("abort",p),"callerAborted"in E)return a&&l&&(d.abortCause??(d.abortCause="caller"),a.abort(i.reason),await J(e,v)),{status:s,syncedBeforeRead:!1,syncError:Se(i)};if("timeout"in E){l&&(d.abortCause??(d.abortCause="timeout"),a?.abort(Object.assign(new Error("Stale-read sync timed out"),{code:"TIMEOUT"})));const t=a?await J(e,v):void 0;if(i.aborted)return{status:s,syncedBeforeRead:!1,syncError:Se(i)};if(t&&!t.settled)return{status:s,syncedBeforeRead:!1,syncError:"DRAIN_TIMEOUT",failure:"error"};try{s=await async function(e,t){let r=()=>{};const n=new Promise((e,t)=>{r=c.setTimeout(()=>t(Object.assign(new Error("Replica status refresh timed out"),{code:"STATUS_TIMEOUT"})),Ae)});try{return await ke(Promise.race([e.status(),n]),t)}finally{r()}}(n,i)}catch(e){return i.aborted?{status:s,syncedBeforeRead:!1,syncError:Se(i),failure:"error"}:{status:s,syncedBeforeRead:!1,syncError:Ie(e),failure:"error"}}const r="timeout"===d.abortCause;return ie(t?.settled?"result"in t?{result:t.result}:{error:t.error}:{error:Object.assign(new Error("Stale-read sync timed out"),{code:"TIMEOUT"})},r||!a,s)}return"error"in E?ie({error:E.error},!1,s):"busy"===E.result.status?{status:s,syncedBeforeRead:!1,failure:"busy"}:(s=await n.status(),{status:s,syncedBeforeRead:!0})}return{status:s,syncedBeforeRead:!1}}function de(e,t,r,n,i,a,o,d={}){null!==r&&"grant_expired"===i&&"CONSENT_EXPIRED"!==d.code&&function(e){const t=u.get(e);if(!t)return;t.reason="grant_expired",t.lastError="GRANT_EXPIRED";const r=t.handle?.replicaId;r&&!t.reportedExpired&&(t.reportedExpired=!0,l({type:"replication.grant",replicaId:r,action:"expired",code:"GRANT_EXPIRED"}))}(r),l({type:"replication.read",op:e,space:s.space,key:t,replica:r,source:n,reason:i,outcome:a,latencyMs:c.now()-o,stalenessMs:null,coverage:null,authority:null,...d})}async function pe(e,t,r,n,i,s,a={}){let o="error";try{const r=await e();return o=r.ok?"found":"get"!==t||"pending_write"!==i&&"not_covered"!==i||r.error.code!==ee?"error":"not_found",r}finally{de(t,r,n,"network",i,o,s,a)}}async function Ee(){if(!g){g=!0;try{const e=le(await o.read(),"",c.now());e.length>0&&l({type:"replication.state",space:s.space,state:"pinned",count:e.length,keys:e.map(e=>e.key)})}catch{l({type:"replication.state",space:s.space,state:"pending_store_error",code:"STORAGE_ERROR"})}}}function we(e){l({type:"replication.read",op:e.op,space:e.space,key:e.path,replica:null,source:"network",reason:"NETWORK_REQUESTED",outcome:e.outcome,latencyMs:e.latencyMs,stalenessMs:null,coverage:null,authority:null})}function Oe(){const e=[...d];for(const t of e)t.abort.abort(Object.assign(new Error("Replica status inspection cancelled"),{code:"ABORTED"}));return Promise.all(e.map(e=>e.settled)).then(()=>{})}function Ce(e){return t.prefixes.map(t=>({prefix:t,state:"gated",reason:"replica_gated",gate:"gated"===e.status?e.gate:"stamp_stale",errorCode:"consent_expired"===e.status?e.code:"REPLICA_GATED",pending:{inFlight:0,committed:0,ambiguous:0},pinned:[],lagMs:null,redacted:!0}))}return function(){const e=I();if(null===e||S||p)return;const t=c.now();Number.isFinite(t)&&(P===e&&A||(P=e,A?.(),A=c.setTimeout(()=>{A=void 0,N()},Math.max(0,e-t))))}(),{get:async function(e){const r=c.now(),n=L(e.path);if("network"===e.options?.source){let t="error";try{const r=await e.network();return t=r.ok?"found":r.error.code===ee?"not_found":"error",r}finally{we({op:"get",space:e.space,path:e.path,reason:"NETWORK_REQUESTED",outcome:t,latencyMs:c.now()-r})}}let i=!1;const s=async(t,n,s={})=>{try{return await pe(e.network,"get",e.path,t,n,r,s)}catch(e){throw i=!0,e}};if(void 0===n)return pe(e.network,"get",e.path,null,"not_covered",r);const a=N();if("allow"!==a.status)return s(n,"consent_expired"===a.status?"grant_expired":"replica_gated",{code:"consent_expired"===a.status?a.code:"REPLICA_GATED"});const d=F(n);if(d)return s(n,"grant_missing",{code:d});try{await ke(Ee(),e.signal)}catch{if(e.signal.aborted)return Ne(e.signal)}let p,f,y;try{p=await ke(V(n),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);"CONSENT_EXPIRED"===Ie(t)&&x();const r=Ie(t);return s(n,"RUNTIME_UNSUPPORTED"===r?"runtime_unsupported":"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}if("grant_missing"===u.get(n)?.reason){const e=u.get(n)?.lastError;return s(n,"GRANT_EXPIRED"===e?"grant_expired":"REPLICA_GATED"===e?"replica_gated":"grant_missing",{code:e})}try{f=await se(n,p,e.signal)}catch(t){if(U(n,t),"CONSENT_EXPIRED"===Ie(t)&&x(),e.signal.aborted)return Ne(e.signal);const r=Ie(t);return s(n,"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_error",{code:r})}if(e.signal.aborted)return Ne(e.signal);if(f.failure){const e="busy"===f.failure?"REPLICA_BUSY":f.syncError;return s(n,"GRANT_REVOKED"===e?"grant_revoked":"REPLICA_GATED"===e||"CONSENT_EXPIRED"===e||"GRANT_EXPIRED"===e?M(e):"stale",{code:e,syncedBeforeRead:f.syncedBeforeRead})}try{y=await ke(o.read(),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);const r=Ie(t);return s(n,"REPLICA_GATED"===r||"CONSENT_EXPIRED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}const h=y.records.find(t=>t.key===e.path);if(h)return s(n,"pending_write",{pendingState:h.state,syncedBeforeRead:f.syncedBeforeRead});if(!o.durable&&!v.has(n))return s(n,"REPLICA_UNPROVEN_SINCE_START");if(f.status.syncedThroughEpoch<y.committedEpoch)return s(n,"REPLICA_BEHIND_OWN_WRITES");if("valid"!==f.status.authority.state)return s(n,"expired"===f.status.authority.state?"grant_expired":"revoked"===f.status.authority.state?"grant_revoked":"grant_not_yet_valid");if("complete"!==f.status.coverage)return s(n,"coverage_incomplete");try{const i=await ke(p.get(e.path),e.signal),a=N();if("allow"!==a.status)throw D(a);const o=F(n);if(o)return await s(n,"grant_missing",{code:o});try{Q(i.meta)}catch(e){const t=Ie(e);return U(n,e),await s(n,Z(t),{code:t})}if("coverage_incomplete"===i.status||"not_covered"===i.status||"content_missing"===i.status)return await s(n,"content_missing"===i.status?"content_missing":"coverage_incomplete"===i.status?"coverage_incomplete":"not_covered");if("present"===i.status&&void 0!==e.options?.maxResponseBytes&&i.value.byteLength>e.options.maxResponseBytes)return await s(n,"unsupported_option");const u=function(e,t,r){if("present"===e.status){if(void 0!==r.maxResponseBytes&&e.value.byteLength>r.maxResponseBytes)return re(ne("KV_RESPONSE_TOO_LARGE",`KV value at key ${JSON.stringify(t)} exceeds the requested response limit`,"kv",{meta:{status:413}}));const n=Object.entries(e.metadata).find(([e])=>"content-type"===e.toLowerCase())?.[1],i=new Headers({etag:e.etag,"content-length":String(e.value.byteLength),"cache-control":"private, no-cache",...e.metadata,"x-tinycloud-source":"replica"});return te({data:ue(e.value,n,r.raw,r.binary),headers:{etag:e.etag,contentType:n,contentLength:e.value.byteLength,get:e=>i.get(e)}})}return"absent"===e.status||"deleted"===e.status?re(ne(ee,`Key not found: ${t}`,"kv")):re(ne(Y,"Local value is not available","kv"))}(i,e.path,e.options??{}),d="present"===i.status?"hit":i.status,y=null===f.status.lastSyncAt?null:Date.parse(f.status.lastSyncAt),h={syncedBeforeRead:f.syncedBeforeRead,coverage:i.meta.coverage,authority:i.meta.authority,stalenessMs:null===y?null:c.now()-y,...f.syncError?{syncError:f.syncError}:{}};return t.verify?await async function(e,t,r,n,i){const s=L(e.path)??null,a=t.ok,o=!t.ok&&t.error.code===ee,c=a?"found":o?"not_found":"error";try{const u=await ke(e.network(),e.signal);if(e.signal.aborted)return de("get",e.path,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const d=N();if("allow"!==d.status)return de("get",e.path,s,"network","consent_expired"===d.status?"grant_expired":"replica_gated",u.ok?"found":"error",n,{code:"consent_expired"===d.status?d.code:"REPLICA_GATED"}),u;const p=null===s?void 0:F(s);if(p)return de("get",e.path,s,"network","grant_missing",u.ok?"found":"error",n,{code:p}),u;if(!u.ok&&u.error.code!==ee)return de("get",e.path,s,"replica",r,c,n,{...i,code:u.error.code,verify:"error"}),t;const f=u.ok,y=!u.ok&&u.error.code===ee,h=t.ok?t.data.headers.etag??null:null,g=u.ok?u.data.headers.etag??null:null,v=a&&f?h===g:o&&y,E=v?"match":"diverged";return v||l({type:"replication.divergence",op:"get",space:e.space,key:e.path,replica:s??"",kind:a&&f?"value":o?"missing_local":"extra_local",localEtag:h,networkEtag:g,stalenessMs:"number"==typeof i.stalenessMs?i.stalenessMs:null}),de("get",e.path,s,"replica",r,c,n,{...i,verify:E}),t}catch(a){if(e.signal.aborted)return de("get",e.path,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const o=N();if("allow"!==o.status)return de("get",e.path,s,"network","consent_expired"===o.status?"grant_expired":"replica_gated","error",n,{code:"consent_expired"===o.status?o.code:"REPLICA_GATED"}),re(ae("kv",a));const l=null===s?void 0:F(s);return l?(de("get",e.path,s,"network","grant_missing","error",n,{code:l}),re(ae("kv",a))):(de("get",e.path,s,"replica",r,c,n,{...i,code:Ie(a),verify:"error"}),t)}}(e,u,d,r,h):(de("get",e.path,n,"replica",d,u.ok?"found":u.error.code===ee?"not_found":"error",r,h),u)}catch(t){if(i)throw t;return U(n,t),"CONSENT_EXPIRED"===Ie(t)&&x(),e.signal.aborted?Ne(e.signal):s(n,M(Ie(t)),{code:Ie(t)})}},list:async function(e){const r=c.now();if("network"===e.options?.source){let t="error";try{const r=await e.network();return t=r.ok?"found":"error",r}finally{we({op:"list",space:e.space,path:e.listPath,reason:"NETWORK_REQUESTED",outcome:t,latencyMs:c.now()-r})}}const n=e.options?.cursor,i=n?.startsWith("tcr1.")?he(n):null;if(n&&n.startsWith("tcr1.")&&!i)return de("list",e.listPath,null,"none","cursor_restart","error",r),ge();if(n&&!n.startsWith("tcr1."))return pe(e.network,"list",e.listPath,null,"network_cursor",r);const s=ve(t.prefixes,e.listPath);let a=!1;const d=async(t,n,i={})=>{try{return await pe(e.network,"list",e.listPath,t,n,r,i)}catch(e){throw a=!0,e}};if(void 0!==s&&!e.options?.raw){const t=N();if("allow"!==t.status)return i?(de("list",e.listPath,s,"none","cursor_restart","error",r),ge()):d(s,"consent_expired"===t.status?"grant_expired":"replica_gated",{code:"consent_expired"===t.status?t.code:"REPLICA_GATED"})}if(void 0!==s&&!e.options?.raw){const t=F(s);if(t)return i?(de("list",e.listPath,s,"none","cursor_restart","error",r),ge()):d(s,"grant_missing",{code:t})}try{await ke(Ee(),e.signal)}catch{if(e.signal.aborted)return Ne(e.signal)}const p=()=>(de("list",e.listPath,s??null,"none","cursor_restart","error",r),ge());if(n&&i&&(i.space!==e.space||i.path!==e.listPath))return p();if(void 0===s||e.options?.raw)return n&&i?p():pe(e.network,"list",e.listPath,s??null,void 0!==s?"unsupported_option":"not_covered",r);let f,y,h;try{f=await ke(V(s),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);if("CONSENT_EXPIRED"===Ie(t)&&x(),n&&i)return p();const r=Ie(t);return d(s,"RUNTIME_UNSUPPORTED"===r?"runtime_unsupported":"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}if("grant_missing"===u.get(s)?.reason){if(n&&i)return p();const e=u.get(s)?.lastError;return d(s,"GRANT_EXPIRED"===e?"grant_expired":"REPLICA_GATED"===e?"replica_gated":"grant_missing",{code:e})}try{y=await se(s,f,e.signal)}catch(t){if(U(s,t),"CONSENT_EXPIRED"===Ie(t)&&x(),e.signal.aborted)return Ne(e.signal);if(n&&i)return p();const r=Ie(t);return d(s,"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_error",{code:r})}if(e.signal.aborted)return Ne(e.signal);try{h=await ke(o.read(),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);if(n&&i)return p();const r=Ie(t);return d(s,"REPLICA_GATED"===r||"CONSENT_EXPIRED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}const g=h.records.find(t=>K(e.listPath,t.key)),E=y.status.syncedThroughEpoch<h.committedEpoch;if(n&&i&&(y.failure||g||E||"complete"!==y.status.coverage||"valid"!==y.status.authority.state||!o.durable&&!v.has(s)))return p();if(E)return d(s,"REPLICA_BEHIND_OWN_WRITES");if(y.failure){const e="busy"===y.failure?"REPLICA_BUSY":y.syncError;return d(s,"GRANT_REVOKED"===e?"grant_revoked":"REPLICA_GATED"===e||"CONSENT_EXPIRED"===e||"GRANT_EXPIRED"===e?M(e):"stale",{code:e})}if(g)return d(s,"pending_write",{pendingState:g.state});if(!o.durable&&!v.has(s))return d(s,"REPLICA_UNPROVEN_SINCE_START");if("complete"!==y.status.coverage||"valid"!==y.status.authority.state)return d(s,"complete"!==y.status.coverage?"coverage_incomplete":"expired"===y.status.authority.state?"grant_expired":"revoked"===y.status.authority.state?"grant_revoked":"grant_not_yet_valid");try{const a={list:t=>ke(f.list(t),e.signal)},u=await ke(function(e,t,r,n,i,s){const a=i?he(i)?.last:void 0,o=""!==r&&!r.endsWith("/")&&(void 0===a||fe(r,a)>0)?async function(e,t,r,n){if(void 0!==r&&fe(t,r)<=0)return!1;const i=await e.list({prefix:t,limit:1});return n(i.meta),i.keys[0]===t}(e,r,a,s):Promise.resolve(!1);return o.then(async i=>{const o=""===r?"":r.endsWith("/")?r:`${r}/`,c=void 0===n?void 0:n+1-(i?1:0),l=await e.list({prefix:o,after:a,limit:c});s(l.meta);let u=(i?[r]:[]).concat(l.keys);const d=void 0!==n&&u.length>n;return d&&(u=u.slice(0,n)),{keys:u,truncated:d,...d?{nextCursor:ye(t,r,u[u.length-1])}:{}}})}(a,e.space,e.listPath,e.options?.limit,n,Q),e.signal),h=await ke(o.read(),e.signal),g=h.records.find(t=>K(e.listPath,t.key));if(n&&i&&(g||y.status.syncedThroughEpoch<h.committedEpoch))return p();if(y.status.syncedThroughEpoch<h.committedEpoch)return await d(s,"REPLICA_BEHIND_OWN_WRITES");if(g)return await d(s,"pending_write",{pendingState:g.state});const v=N();if("allow"!==v.status)throw D(v);const E=F(s);if(E)return i?p():await d(s,"grant_missing",{code:E});const m={count:u.keys.length,syncedBeforeRead:y.syncedBeforeRead,stalenessMs:null===y.status.lastSyncAt?null:c.now()-Date.parse(y.status.lastSyncAt),...y.syncError?{syncError:y.syncError}:{}};return t.verify&&!n?await async function(e,r,n,i){const s=ve(t.prefixes,e.listPath)??null;try{const t=await ke(e.network(),e.signal);if(e.signal.aborted)return de("list",e.listPath,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const a=N();if("allow"!==a.status)return de("list",e.listPath,s,"network","consent_expired"===a.status?"grant_expired":"replica_gated",t.ok?"found":"error",n,{code:"consent_expired"===a.status?a.code:"REPLICA_GATED"}),t;const o=null===s?void 0:F(s);if(o)return de("list",e.listPath,s,"network","grant_missing",t.ok?"found":"error",n,{code:o}),t;if(!t.ok)return de("list",e.listPath,s,"replica","hit","found",n,{...i,code:t.error.code,verify:"error"}),te(r);const c=new Set(r.keys),u=new Set(t.data.keys),d=r.keys.filter(e=>!u.has(e)),p=t.data.keys.filter(e=>!c.has(e)),f=0===d.length&&0===p.length,y=f&&r.keys.every((e,r)=>e===t.data.keys[r]),h=y?"match":"diverged";return f&&y||l({type:"replication.divergence",op:"list",space:e.space,key:e.listPath,replica:s??"",kind:f?"order":"keys",...f?{}:{localOnly:d,networkOnly:p},stalenessMs:"number"==typeof i.stalenessMs?i.stalenessMs:null}),de("list",e.listPath,s,"replica","hit","found",n,{...i,verify:h}),te(r)}catch(t){if(e.signal.aborted)return de("list",e.listPath,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const a=N();if("allow"!==a.status)return de("list",e.listPath,s,"network","consent_expired"===a.status?"grant_expired":"replica_gated","error",n,{code:"consent_expired"===a.status?a.code:"REPLICA_GATED"}),re(ae("kv",t));const o=null===s?void 0:F(s);return o?(de("list",e.listPath,s,"network","grant_missing","error",n,{code:o}),re(ae("kv",t))):(de("list",e.listPath,s,"replica","hit","found",n,{...i,code:Ie(t),verify:"error"}),te(r))}}(e,u,r,m):(de("list",e.listPath,s,"replica","hit","found",r,m),te(u))}catch(t){if(a)throw t;if(e.signal.aborted)return Ne(e.signal);const r=Ie(t);if("CONSENT_EXPIRED"===r&&x(),U(s,t),n&&i)return p();const o="CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):Z(r);return d(s,o,{code:r})}},write:async function(e){const t=e.entries.flatMap(t=>void 0!==L(t.path)?[{key:t.path,op:"delete"===e.op?"delete":"put"}]:[]);if(0===t.length)return e.network();if("allow"!==N().status)return e.network();if(await Ee(),"allow"!==N().status)return e.network();const r=globalThis.crypto?.randomUUID?.()??`${c.now()}-${Math.random()}`;try{await o.update(e=>function(e,t,r,n){const i=r.map(({key:r,op:i})=>({opId:t,seq:++e.seq,key:r,op:i,state:"in_flight",epoch:null,at:n,settledAt:null}));return e.records.push(...i),i}(e,r,t,Pe(c.now())))}catch(t){return"REPLICA_GATED"===Ie(t)||"CONSENT_EXPIRED"===Ie(t)||"allow"!==N().status?e.network():re(ne("KV_WRITE_FAILED","Unable to persist pending KV write; request was not dispatched","kv",{cause:t instanceof Error?t:void 0,meta:{replication:"pending_store_unavailable",requestDispatched:!1}}))}const n=c.now();let i;try{i=await e.network()}catch(e){const t=ae("kv",e);i=re({...t,meta:{...t.meta,requestMayHaveDispatched:!0}})}const s=function(e,t,r={}){if(t.ok)return"committed";const{code:n,meta:i}=t.error;if("delete"===e&&n===ee)return!0===r.conditional?"failed":"committed";if(!1===i?.requestMayHaveDispatched)return"failed";if(oe.has(n))return"failed";if("batch-unconfirmed"===i?.outcome)return"ambiguous";const s="number"==typeof i?.status?i.status:void 0;return void 0!==s&&s>=400&&s<500?"failed":"ambiguous"}(e.op,i,{conditional:!0===e.conditional});let a;try{await o.update(e=>function(e,t,r,n,i){if("failed"===r)return void(e.records=e.records.filter(e=>e.opId!==t));const s=e.records.filter(e=>e.opId===t&&"in_flight"===e.state);if("committed"===r&&s.length>0){const t=++e.committedEpoch;for(const e of s)e.state="committed",e.epoch=t,e.settledAt=n;return}for(const e of s)e.state="ambiguous",e.settledAt=n,i&&(e.code=i)}(e,r,s,Pe(c.now()),i.ok?void 0:i.error.code))}catch(e){a=e}l({type:"replication.write",space:e.space,op:e.op,keys:t.map(e=>e.key),outcome:s,...i.ok?{}:{code:i.error.code},latencyMs:c.now()-n});const u=await o.read().catch(()=>{}),d=u?le(u,"",c.now()):[];return"ambiguous"===s&&l({type:"replication.state",space:e.space,state:"pinned",count:d.length,keys:d.map(e=>e.key)}),a&&l({type:"replication.state",space:e.space,state:"pending_store_error",code:"STORAGE_ERROR"}),i},observeNetworkRequested:we,observeConsentExpired:function(t){e.stamp&&t.incarnation===e.stamp.incarnation&&t.lifecycleEpoch===e.stamp.lifecycleEpoch&&C()&&l({type:"replication.lifecycle",action:"denied",reason:"consent_expired"})},status:async function(){const r=N();if("allow"!==r.status)return Ce(r);let l;try{l=o.readExisting?await o.readExisting():await o.read()}catch(e){const t=N();if("allow"!==t.status)return Ce(t);throw e}const f=N();if("allow"!==f.status)return Ce(f);const h=l??ce(i),g=await Promise.all(t.prefixes.map(async r=>{"/"!==r||void 0===e.nodeFeatures||e.nodeFeatures.includes("kv-sync-root")||q(r);const o=h.records.filter(e=>W(r,e.key)),l=u.get(r);let f;if(l?.handle)try{f=await l.handle.status()}catch{}let g={missing:!1};if(f||l?.opening||l?.authorityRevoked||(g=await async function(r){if(!n.inspectStatus||p||y)return{missing:!1};const o=a.sessionGrant(r),l="refused"in o?void 0:o.device,u={identity:i,space:s.space,prefix:r,allowSecrets:t.allowSecrets,...l?{device:l}:{},...e.fetch?{fetch:e.fetch}:{}},f=new AbortController,h=Promise.resolve().then(()=>n.inspectStatus(u,{signal:f.signal})),g=h.then(()=>{},()=>{}),v={abort:f,settled:g};d.add(v),g.then(()=>d.delete(v));let E=()=>{};const m=new Promise(e=>{E=c.setTimeout(()=>{f.abort(Object.assign(new Error("Replica status inspection timed out"),{code:"STATUS_TIMEOUT"})),e({timedOut:!0})},Ae)});try{const e=await Promise.race([h.then(e=>({local:e})),m]);return"timedOut"in e?{missing:!1,errorCode:"STATUS_TIMEOUT"}:{missing:void 0===e.local,...e.local?{local:e.local}:{}}}catch(e){return{missing:!1,errorCode:Ie(e)}}finally{E()}}(r)),f??(f=g.local),g.missing&&!l?.reason&&!l?.authorityRevoked&&!l?.opening&&!p)return;const v=f&&!("redacted"in f)?f:void 0,E=!0===l?.authorityRevoked||"revoked"===v?.authority.state,m=p?"closed":E?"revoked":"REPLICATION_ROOT_UNSUPPORTED"===l?.lastError||"grant_expired"===l?.reason?"unavailable":"grant_missing"===l?.reason?"grant_missing":"complete"===v?.coverage&&"valid"===v.authority.state?"ready":l?.reason||g.errorCode?"unavailable":"idle";return{prefix:r,state:m,...l?.reason?{reason:l.reason}:g.errorCode?{reason:"replica_unavailable"}:{},...g.errorCode??l?.lastError?{errorCode:g.errorCode??l?.lastError}:{},...f??{},...E?{authority:{state:"revoked",expiresAt:v?.authority.expiresAt??null}}:{},pending:{inFlight:o.filter(e=>"in_flight"===e.state).length,committed:o.filter(e=>"committed"===e.state).length,ambiguous:o.filter(e=>"ambiguous"===e.state).length},pinned:le(h,r,c.now()),lagMs:v?.lastSyncAt?c.now()-Date.parse(v.lastSyncAt):null}})),v=N();return"allow"!==v.status?Ce(v):g.filter(e=>void 0!==e)},sync:async function(e){const r=void 0!==e?.prefix?t.prefixes.filter(t=>t===e.prefix):t.prefixes;await Promise.all(r.map(t=>z(t,"manual",e?.signal).then(()=>{})))},purge:function(e){var r;f=!0,y=!0,A?.(),A=void 0;const p=d.size>0,h=Oe();for(const e of u.values())e.timer?.(),e.timer=void 0,e.renewalTimer?.(),e.renewalTimer=void 0,e.syncContext&&((r=e.syncContext).abortCause??(r.abortCause="purge")),e.abort?.abort(),e.mintAbort?.abort();return Promise.resolve().then(async()=>{const r={purged:[],failed:[]},d=e?.timeoutMs??5e3,f=async e=>{let t=()=>{};const r=new Promise((e,r)=>{t=c.setTimeout(()=>r(Object.assign(new Error("Replication cleanup timed out"),{code:"TIMEOUT"})),d)});try{return await Promise.race([e,r])}finally{t()}},y=Promise.all([...[...u.values()].flatMap(e=>[e.opening?.catch(()=>{}),e.sync?.catch(()=>{}),e.renewing?.catch(()=>{}),e.handle?.close().catch(()=>{})]),...p?[h]:[]]);let g;try{await f(y)}catch(e){g=Ie(e)}const E=t.prefixes.map(async e=>{try{if(g)throw Object.assign(new Error("Replica cleanup did not settle before purge"),{code:g});const t=a.sessionGrant(e),c=u.get(e)?.handle?.deviceDid??("refused"in t?void 0:t.device.did);await f(n.purge({identity:i,space:s.space,prefix:e,...c?{sessionDeviceDid:c}:{}})),await o.update(t=>function(e,t){const r=e.records.length;return e.records=e.records.filter(e=>!W(t,e.key)),r-e.records.length}(t,e)),u.delete(e),v.delete(e),r.purged.push(e),l({type:"replication.state",space:s.space,replica:e,state:"purged"})}catch(t){const n=Ie(t);r.failed.push({prefix:e,code:n}),l({type:"replication.state",space:s.space,replica:e,state:"purge_failed",code:n})}});return await Promise.all(E),r}).finally(()=>{y=!1})},clearPending:async function(){const e=await o.update(e=>function(e,t){const r=e.records.length;return e.records=e.records.filter(e=>"committed"===e.state||"in_flight"===e.state&&t-Date.parse(e.at)<=6e5),r-e.records.length}(e,c.now()));return l({type:"replication.state",space:s.space,state:"pending_cleared",count:e}),e},close:async function(){var e;if(p)return;p=!0,A?.(),A=void 0;const t=d.size>0,r=Oe();for(const[t,r]of u)r.timer?.(),r.timer=void 0,r.renewalTimer?.(),r.renewalTimer=void 0,r.mintAbort?.abort(),r.syncContext&&((e=r.syncContext).abortCause??(e.abortCause="close")),r.abort?.abort(),l({type:"replication.state",space:s.space,replica:t,state:"closed"});const n=Promise.all([...[...u.values()].map(async e=>{await(e.opening?.catch(()=>{})),await(e.renewing?.catch(()=>{})),await(e.sync?.catch(()=>{})),await(e.handle?.close().catch(()=>{}))}),...t?[r]:[]]);let i=()=>{},a=!1;n.then(()=>{a=!0,i()},()=>{a=!0,i()});const o=new Promise(e=>{queueMicrotask(()=>{a||(i=c.setTimeout(e,Te))})});try{await Promise.race([n,o])}finally{i()}}}}function Se(e){return ae("kv",e.reason).code===J||"object"==typeof e.reason&&null!==e.reason&&"code"in e.reason&&e.reason.code===J?J:Q}function Ne(e){const t=Se(e);return re(ne(t,t===J?"KV request timed out":"KV request was aborted","kv"))}function Ce(e){const t=$(e),r=B(t);let n=ce(t),i=Promise.resolve();return{identity:t,durable:!1,read:async()=>structuredClone(n),async update(e){let t,s;const a=new Promise((e,r)=>{t=e,s=r}),o=i.then(()=>{try{if(B(n.identity)!==r)throw Object.assign(new Error("Pending-store identity mismatch"),{code:"STORAGE_ERROR"});const i=structuredClone(n),s=e(i);n=i,t(s)}catch(e){s(e)}});return i=o.then(()=>{},()=>{}),a}}}}},n={};function i(e){var t=n[e];if(void 0!==t)return t.exports;var s=n[e]={exports:{}};return r[e](s,s.exports,i),s.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(r,n){if(1&n&&(r=this(r)),8&n)return r;if("object"==typeof r&&r){if(4&n&&r.__esModule)return r;if(16&n&&"function"==typeof r.then)return r}var s=Object.create(null);i.r(s);var a={};e=e||[null,t({}),t([]),t(t)];for(var o=2&n&&r;("object"==typeof o||"function"==typeof o)&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,i.d(s,a),s},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};i.r(s),i.d(s,{browserReplicaPlugin:()=>l,loadIndexedDbReplicaStorage:()=>o});var a=i(727);async function o(){const{indexedDbReplicaStorage:e}=await Promise.resolve().then(i.bind(i,913));return e}const c=i(60).assertValidReplicationConfig,l=Object.freeze({validateConfig:c,loaders:Object.freeze({validateConfig:c,runtime:()=>Promise.resolve().then(i.bind(i,230)),authority:()=>Promise.resolve().then(i.bind(i,60)),gatedNetwork:()=>Promise.resolve().then(i.t.bind(i,284,23)),gate:()=>Promise.resolve().then(i.bind(i,435))}),recover:async function(e,t){const r=e.storage,n="indexeddb"===r.kind?r.lifecycle:void 0;if("indexeddb"!==n?.kind)return e;const i=(t,r)=>{try{const n={type:"replication.lifecycle",at:(new Date).toISOString(),action:"unguarded",reason:"startup",gate:"gate_unavailable",code:t};void 0!==r&&(n.remaining=r),e.onEvent?.(n)}catch{}},s=e=>null!==e&&0===e.failed.length&&0===e.remaining,o=(e,t)=>{let r;return Promise.race([e.then(()=>{},()=>{}),new Promise(e=>{r=setTimeout(()=>{t?.abort(),e()},3e3)})]).finally(()=>clearTimeout(r))};let c,l=!1,u=0,d=0,p=void 0===t?"wallet_provider_required":"gate_unavailable";const f=async e=>{const t=await n.recover(e);return l=s(t),l||(c=void 0,u++),t},y=()=>{const e=new AbortController;return o(f({signal:e.signal}),e)};let h;const g=e=>{const t=e().catch(()=>{}).finally(()=>{h===t&&(h=void 0)});return h=t,t},v=new AbortController;let E,m=!1;const w=(async()=>n.recover({signal:v.signal}))().catch(()=>null).then(e=>E=e);g(async()=>{const e=await w;m&&(s(e)?await y():i(e?.failed[0]?.code??(e?"RECOVERY_INCOMPLETE":"STORAGE_ERROR"),e?.remaining))}),await o(w,v),m=void 0===E,E&&(l=s(E)),l||i(E?.failed[0]?.code??(m?"RECOVERY_TIMEOUT":"STORAGE_ERROR"),E?.remaining);const _=()=>Object.assign(new Error("Replica wallet or startup recovery is unavailable."),{code:"REPLICA_GATED",gate:l?p:"gate_unavailable"}),b=()=>Promise.reject(_()),R=()=>{throw _()},T=async e=>{const r=(0,a.__replicaParsePkhDid)(e)?.address,n=await(t?.getConnectedAddress().catch(()=>{}));return p=void 0===t?"wallet_provider_required":n?"principal_mismatch":"gate_unavailable",void 0!==r&&void 0!==n&&r.toLowerCase()===n.toLowerCase()},A=async()=>{const e=c;if(!l||!e)throw _();if(!await T(e)||c!==e)throw c=void 0,_()},P=async(e,t)=>{const r=++u;if(c=void 0,!l&&h&&await o(h),!l&&!h&&d<2&&(d++,await g(y)),!l||!await T(e)||r!==u)throw _();const n=await t();if(r!==u)throw _();if(c=e,await A(),r!==u)throw _();return n},I=(e,t,r)=>{if(r.has(t))return r.get(t);const n=Reflect.get(e,t,e);if("function"!=typeof n)return n;const i=n.bind(e);return r.set(t,i),i},k=new Map,O=new Proxy(n,{get(e,t){if("recover"===t)return f;if("establishSessionStamp"===t)return(...t)=>P(t[0],()=>e.establishSessionStamp(...t));if("restoreSessionStamp"===t)return(...t)=>P(t[0],()=>e.restoreSessionStamp(...t));if("deny"===t)return(...t)=>(u++,c=void 0,e.deny(...t));if(!l||!c){if("activationAllowed"===t)return()=>Promise.resolve(!1);if("checkDelivery"===t)return()=>({status:"gated",gate:l?p:"gate_unavailable"});if("deliverable"===t)return()=>!1;if("consentDeadline"===t)return()=>null}return I(e,t,k)}}),S=new Map,N=new Proxy(r,{get(e,t){if("lifecycle"===t)return O;if("open"===t)return async(...t)=>{await A();const r=await e.open(...t);try{await A()}catch(e){throw await r.close().catch(()=>{}),e}const n=new Map,i=async(...e)=>{await A();const t=await r.get(...e);return await A(),t},s=async(...e)=>{await A();const t=await r.list(...e);return await A(),t};return new Proxy(r,{get:(e,t)=>"get"===t?i:"list"===t?s:I(e,t,n)})};if(!l||!c){if("inspectStatus"===t)return b;if("pendingWrites"===t)return R}return I(e,t,S)}});return{...e,storage:N}}});module.exports=s})();
|
|
1
|
+
(()=>{"use strict";var e,t,r={727(e){e.exports=require("@tinycloud/web-sdk")},284(e){e.exports=require("@tinycloud/web-sdk/replica-gated")},913(e){e.exports=import("@tinycloud/replica/kv-storage")},435(e){e.exports=import("@tinycloud/replica/profile-gate")},60(e,t,r){r.r(t),r.d(t,{AUTHORITY_EXPIRY_MARGIN_MS:()=>S,assertRenewalParent:()=>C,assertValidReplicationConfig:()=>c,augmentSignInEntriesWithReplication:()=>f,createReplicationAuthority:()=>x,eraseReplicaLocalCopy:()=>v,establishReplicaSessionStamp:()=>b,hasUnrestrictedGetCoverage:()=>p,mintNodeReplicationGrant:()=>O,replicationScopeFromSignedSession:()=>N,reportReplicaDenial:()=>h,restoreReplicaSessionStamp:()=>R,ucanAttCovers:()=>I,ucanAttUnconstrainedFor:()=>k,verifiedOwnerConsentAnchor:()=>_});var n=r(727);const i=require("@tinycloud/replica");function s(e,t){return"/"===e||t.startsWith(e)}function a(e){const t="string"==typeof e&&e.length>0&&!e.startsWith("/")&&!e.includes("//")&&e.endsWith("/");if("/"!==e&&!t){const t="string"==typeof e?e.replace(/^\/+/,"").replace(/\/+$/,""):"",r=t.length>0&&!t.includes("//")?` Use ${JSON.stringify(`${t}/`)}.`:' Use "/" or a slash-terminated folder path such as "notes/".';throw new TypeError(`Replication prefix must be "/" or a non-empty slash-terminated folder path without empty segments.${r}`)}}var o=r(191);function c(e){if(void 0!==e?.syncScope&&"prefixes"!==e.syncScope)throw new TypeError('replication.syncScope must be "prefixes"');if(void 0!==e?.contentFetch&&"eager"!==e.contentFetch&&"lazy"!==e.contentFetch)throw new TypeError('replication.contentFetch must be "eager" or "lazy"');if(void 0===e||!e.enabled)return;if(void 0===e.storage||null===e.storage)throw new TypeError("replication.enabled requires replication.storage");if(!Array.isArray(e.prefixes)||0===e.prefixes.length)throw new TypeError("replication.prefixes must be a non-empty array");const t=e.grantTtlMs;if(void 0!==t&&(!Number.isFinite(t)||t<=0||t>6048e5))throw new TypeError("replication.grantTtlMs must be a positive number of milliseconds no greater than 604800000");for(const t of e.prefixes)try{a(t)}catch(e){throw new TypeError(e instanceof Error?e.message:String(e))}for(const[t,r]of e.prefixes.entries()){for(const n of e.prefixes.slice(t+1))if(s(r,n)||s(n,r))throw new TypeError(`replication.prefixes must not overlap: ${JSON.stringify(r)} and ${JSON.stringify(n)}`);if(("/"===r||"vault"===r.split("/",1)[0])&&!0!==e.allowSecrets)throw new TypeError(`replication prefix ${JSON.stringify(r)} overlaps the vault namespace; pass allowSecrets to opt in`)}}var l=n.__replicaKV.GET,u=n.__replicaKV.SYNC,d="tinycloud.kv";function p(e,t,r){return(0,n.__replicaIsCapabilitySubset)([{service:d,space:t,path:r,actions:[l]}],[...e]).subset}function f(e){const t=[],r=e.replication;if(void 0===r)return t;const n=[];for(const t of r.prefixes){a(t);const i="/"===t?"":t;(0,o.requiresSecretsOptIn)(e.primarySpaceId,t)&&!0!==r.allowSecrets||p(e.entries,e.primarySpaceId,i)&&n.push(i)}if("prefixes"!==r.syncScope&&n.length===r.prefixes.length&&n.length>0&&p(e.entries,e.primarySpaceId,""))return[{service:d,space:e.primarySpaceId,path:"",actions:[l,u]}];for(const r of n)t.push({service:d,space:e.primarySpaceId,path:r,actions:[l,u]});return t}var y=i.parseUcanGrant;function h(e,t,r,n){if("denied"!==e.status&&"deleted"!==e.status&&"marker"!==e.status)return;const i={type:"replication.lifecycle",at:(new Date).toISOString(),reason:t,action:"denied"===e.status?"denied":"deleted"===e.status?"database_deleted":"marker_set",..."denied"===e.status?{partitions:e.intents}:{},..."marker"===e.status?{code:e.code}:{}};try{r?.(i)}catch{}const{type:s,...a}=i;try{n?.emit(s,a)}catch{}}var g=[150,450];async function v(e,t,r,n){if("indexeddb"!==e?.kind||void 0===e.eraseLocalCopy)return;let i={status:"failed",code:"STORAGE_ERROR",marker:!1};for(let t=0;t<=g.length;t++){t>0&&await new Promise(e=>setTimeout(e,g[t-1]));try{i=await e.eraseLocalCopy({signal:AbortSignal.timeout(3e3)})}catch{i={status:"failed",code:"STORAGE_ERROR",marker:!1}}if("failed"!==i.status)break}const s="marker"===r||"unguarded"===r,a="erased"===i.status?{ok:!0}:{ok:!1,retryNow:"failed"===i.status};if("erased"===i.status||"refused"===i.status&&!s)return{outcome:i,purge:a};const o="failed"===i.status&&i.marker,c={type:"replica.purge.failed",trigger:t,reason:o?"logout_pending":"gate_unavailable",code:i.code,retryNow:"failed"===i.status};for(const e of n)try{e(c)}catch(e){console.error('Error in "replica.purge.failed" handler:',e)}return o?{outcome:i,purge:a,logoutPending:o}:{outcome:i,purge:a}}var E=n.__replicaKV.GET,m=n.__replicaKV.SYNC,w="tinycloud.kv";function _(e,t,r){if("string"!=typeof e.siwe||"string"!=typeof e.signature||"string"!=typeof e.address||"number"!=typeof e.chainId)return null;try{const i=t.validatePersistedSession?.({delegationHeader:e.delegationHeader,delegationCid:e.delegationCid,spaceId:e.spaceId,jwk:e.jwk,address:e.address,chainId:e.chainId,siwe:e.siwe,signature:e.signature});if(!i||!Number.isSafeInteger(Date.parse(i.expiresAt??"")))return null;const s=new n.__replicaSiweMessage(e.siwe).issuedAt;if("string"!=typeof s)return null;const a=Date.parse(s);if(!Number.isSafeInteger(a)||a<0)return null;const o=r(i).filter(t=>t.space===e.spaceId&&"kv"===t.service).map(e=>({...e,service:"tinycloud.kv"}));return o.some(t=>(0,n.__replicaIsCapabilitySubset)([{service:"tinycloud.kv",space:e.spaceId,path:t.path,actions:[n.__replicaKV.GET,n.__replicaKV.SYNC]}],o).subset)?{at:a,source:"siwe"}:null}catch{return null}}function b(e,t,r){if("indexeddb"===e.kind&&"indexeddb"===e.lifecycle?.kind)return e.lifecycle.establishSessionStamp(t,{consentAnchor:r});if("sqlite"===e.kind&&"file"===e.lifecycle?.kind)return e.lifecycle.establishSessionStamp(t,{consentAnchor:r});throw Object.assign(new Error("Replica sign-in requires its platform lifecycle gate."),{code:"REPLICA_GATED",gate:"gate_unavailable"})}function R(e,t,r){if("indexeddb"===e.kind&&"indexeddb"===e.lifecycle?.kind)return e.lifecycle.restoreSessionStamp(t,r);if("sqlite"===e.kind&&"file"===e.lifecycle?.kind)return e.lifecycle.restoreSessionStamp(t,r);throw Object.assign(new Error("Replica restore requires its platform lifecycle gate."),{code:"REPLICA_GATED",gate:"gate_unavailable"})}function T(e,t){return[{service:w,space:e,path:"/"===t?"":t,actions:[E,m]}]}function A(e){if(null==e)return!0;if("object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length)return!0;if(!Array.isArray(e))return!1;try{return(0,n.__replicaCanonicalizeRecapCaveats)(e)===(0,n.__replicaCanonicalizeRecapCaveats)(void 0)}catch{return!1}}function P(e,t){for(const r of[`${t}/kv`,`tinycloud://${t}/kv`])if(e===r||e===`${r}/`)return"/";for(const r of[`${t}/kv/`,`tinycloud://${t}/kv/`])if(e.startsWith(r))return e.slice(r.length)}function I(e,t,r,i,s){for(const[a,o]of Object.entries(e)){const e=P(a,t);if(void 0!==e)for(const[a,c]of Object.entries(o))if((0,n.__replicaActionContains)(a,i)&&(0,n.__replicaIsCapabilitySubset)([{service:w,space:t,path:r,actions:[i]}],[{service:w,space:t,path:e,actions:[a]}]).subset&&(!0===s?.ignoreCaveats||A(c)))return!0}return!1}function k(e,t,r){return I(e,t,r,E)&&I(e,t,r,m)}async function O(e,t,r,i,s){if(r?.renewalOnly&&!i)throw new Error("replication renewal lost its owner session");const a=r?.renewalOnly?{expiry:r.expiryMs,onPrepared:async e=>{C(e.delegationHeader.Authorization,i)}}:void 0===r?.expiryMs?void 0:{expiry:r.expiryMs},o=await s.delegateTo((0,n.__replicaPrincipalDid)(e),t,a);return{ucan:o.delegation.delegationHeader.Authorization,expiresAt:o.delegation.expiry.getTime()}}var S=6e4;function N(e){let t;try{t=y(e.delegationHeader.Authorization)}catch{return}const r=e=>e.split("#",1)[0];if(t.cid===e.delegationCid&&r(t.audience)===r(e.verificationMethod))for(const r of Object.keys(t.att)){const t=r.match(/^(?:tinycloud:\/\/)?(.+?)\/kv(?:\/|$)/)?.[1];if(t!==e.persistedSpace)continue;const i=(0,n.__replicaParseSpaceUri)(t);if(i?.owner&&i.address&&i.chainId)return{space:t,principal:i.owner}}}function C(e,t){const r=y(e);if(r.issuer!==t.verificationMethod.split("#",1)[0]||1!==r.prf.length||r.prf[0]!==t.delegationCid)throw Object.assign(new Error("replication renewal requires the bound owner session parent"),{refused:"NOT_COVERED"})}function x(e){const t=e.replicationSession();let r=null;try{const n=t&&e.verifiedConsentAnchor?.(t);n&&Number.isFinite(n.at)&&"first_install"!==n.source&&(r={at:n.at,source:n.source})}catch{}const n=()=>{const r=e.replicationSession();return void 0!==r&&r===t?r:void 0},i=(t,r)=>{const n=e.planDelegation(t,void 0===r?void 0:{expiry:r});return"refused"in n?n:{path:n.path,parentCid:n.parentCid,expiresAt:n.expiresAt}},s=e=>e.split("#",1)[0],a=e=>{const t=y(e.delegationHeader.Authorization);if(t.cid===e.delegationCid&&s(t.audience)===s(e.verificationMethod))return t},o={get sessionOnly(){const e=n();return void 0===e||void 0===e.siwe},consentAnchor:()=>n()?r:null,get canRenew(){const e=n();return"siwe"===r?.source&&void 0!==e&&void 0!==e.siwe},sessionGrant(t){const i=n();if(void 0===i)return{refused:"SESSION_EXPIRING"};if(null===r&&void 0!==i.siwe)return{refused:"NOT_COVERED"};const s=i.siwe?e.siweExpiration(i.siwe)?.getTime():void 0;if(void 0!==s&&s<=Date.now()+S)return{refused:"SESSION_EXPIRING"};let o;try{const e=a(i);if(!e)return{refused:"NOT_COVERED"};o=e}catch{return{refused:"NOT_COVERED"}}const c=null===o.expiresAt?void 0:1e3*o.expiresAt;return void 0===c||c<=Date.now()+S?{refused:"SESSION_EXPIRING"}:I(o.att,i.spaceId,t,E,{ignoreCaveats:!0})&&I(o.att,i.spaceId,t,m,{ignoreCaveats:!0})?k(o.att,i.spaceId,t)?{ucan:o.jwt,device:{did:i.verificationMethod,jwk:i.jwk}}:{refused:"CAVEATED_AUTHORITY"}:{refused:"NOT_COVERED"}},plan(e){const t=n();if(void 0===t)return{refused:"SESSION_EXPIRING"};if(null===r)return{refused:"NOT_COVERED"};const s=this.sessionGrant(e);if(!("refused"in s)){const e=a(t);return e&&null!==e.expiresAt?{path:"session",parentCid:t.delegationCid,expiresAt:1e3*e.expiresAt}:{refused:"NOT_COVERED"}}return o.sessionOnly?s:i(T(t.spaceId,e))},async mint(t,s,a,o){const c=n();if(void 0===c)throw new Error("replication mint without the bound session");if(void 0===c.siwe)throw new Error("compact delegate sessions cannot mint device grants");if("siwe"!==r?.source)throw new Error("replication mint requires verified owner consent");const l=T(c.spaceId,s),u=i(l,o?.expiryMs);if("refused"in u)throw Object.assign(new Error(`replication authority refused the mint: ${u.refused}`),{refused:u.refused});if(o?.renewalOnly&&"session"!==u.path)throw Object.assign(new Error("replication renewal requires a session parent"),{refused:"NOT_COVERED"});a.throwIfAborted();const d=await new Promise((r,n)=>{const i=()=>n(a.reason??new Error("replication mint aborted"));a.addEventListener("abort",i,{once:!0}),e.mintDelegation(t,l,o).then(e=>{a.removeEventListener("abort",i),r(e)},e=>{a.removeEventListener("abort",i),n(e instanceof Error?e:new Error(String(e)))})});return{ucan:d.ucan,parentCid:u.parentCid,expiresAt:d.expiresAt}}};return o}},230(e,t,r){r.r(t),r.d(t,{ReplicationRuntime:()=>s});var n=r(727),i={now:()=>Date.now(),setTimeout(e,t){const r=setTimeout(e,t);return r.unref?.(),()=>clearTimeout(r)}},s=class{constructor(e,t=i){this.options=e,this.clock=t,this.pending=new Map,this.attached=new Map,this.previous=Promise.resolve(),this.binding=Promise.resolve(),this.generation=0,this.bindingActive=!1,this.pendingPurgeSet=!1,this.closed=!1,this.control={status:async()=>(await this.binding,this.gatedReason?this.options.prefixes.map(e=>({prefix:e,state:"gated",gate:this.gatedReason,errorCode:"REPLICA_GATED",pending:{inFlight:0,committed:0,ambiguous:0},pinned:[],lagMs:null})):this.current?this.current.status():[]),sync:async e=>{if(await this.binding,this.gatedReason)throw Object.assign(new Error("Replica restore is gated."),{code:"REPLICA_GATED",gate:this.gatedReason});this.purgedGeneration!==this.generation&&this.current&&await this.current.sync(e)},purge:e=>{if(this.bindingActive){this.pendingPurge=e,this.pendingPurgeSet=!0;const t=this.current??this.lastController;return t&&(this.pendingPurgeResult=t.purge(e),this.purgedGeneration=this.generation),this.binding.then(()=>this.pendingPurgeResult??{purged:[],failed:[]})}const t=this.current??this.lastController;return t?(this.purgedGeneration=this.generation,t.purge(e)):Promise.resolve({purged:[],failed:[]})},clearPending:async()=>{if(await this.binding,this.current)return this.current.clearPending();const e=this.lastPending;return e?e.update(e=>{const t=e.records.length;return e.records=e.records.filter(e=>"committed"===e.state||"in_flight"===e.state&&this.clock.now()-Date.parse(e.at)<=6e5),t-e.records.length}):0},close:async()=>{this.closed=!0,this.unbind(),await this.binding.catch(()=>{}),await this.previous}}}loadServices(){return this.services??(this.services=Promise.resolve().then(r.bind(r,191)))}detachAll(){for(const e of this.attached.keys())e.setReadThrough(null);this.attached.clear()}bindGatedNetworkOnly(e,t){if(this.closed||!this.options.enabled)return Promise.resolve();const r=this.unbind(),n=this.generation;return this.purgedGeneration=void 0,this.pendingPurge=void 0,this.pendingPurgeResult=void 0,this.pending.clear(),this.lastController=void 0,this.lastPending=void 0,this.lastIdentity=void 0,this.gatedReason=e.gate,this.primarySpace=e.session.spaceId,this.binding=r.then(async()=>{let r;try{({createGatedNetworkReadThrough:r}=await t())}catch{return}if(n!==this.generation||this.closed||"function"!=typeof r)return;const i=r({space:e.session.spaceId,prefixes:this.options.prefixes,now:()=>this.clock.now(),emit:t=>{if(n!==this.generation||this.closed||this.gated!==i)return;try{this.options.onEvent?.(t)}catch{}const{type:r,...s}=t;try{e.context.emit(r,s)}catch{}}});this.gated=i;for(const t of e.primaryKV)this.attach(t.space,t.kv)}),this.binding}bind(e){if(this.closed||!this.options.enabled)return Promise.resolve();this.gated=void 0,this.gatedReason=void 0,this.bindingActive=!0;const t=++this.generation;this.purgedGeneration=void 0,this.unsubscribeConsentExpired?.(),this.unsubscribeConsentExpired=void 0;const{context:r,session:i}=e,s=e=>{try{this.options.onEvent?.(e)}catch{}const{type:t,...n}=e;r.emit(t,n)},a=this.current;this.current=void 0;for(const e of this.attached.keys())e.setReadThrough(null);this.primarySpace=i.spaceId;const o=a?a.close().catch(()=>{}):Promise.resolve();this.previous=this.previous.then(()=>o);const c=this.previous;this.binding=this.loadServices().then(a=>{if(t!==this.generation||this.closed)return;let o;try{o=a.canonicalReplicationIdentity({host:r.hosts[0],space:i.spaceId,principal:e.principal??(0,n.__replicaPkhDid)(e.address,e.chainId)})}catch{for(const e of this.options.prefixes)s({type:"replication.state",at:new Date(this.clock.now()).toISOString(),space:i.spaceId,replica:e,state:"unavailable",code:"CONFIG_INVALID"});return}const l=a.replicationIdentityKey(o);let u=this.pending.get(l);const d=e.stamp;if(!u||u.stamp?.incarnation!==d?.incarnation||u.stamp?.lifecycleEpoch!==d?.lifecycleEpoch){const e=this.options.storage.pendingWrites?.(o,{stamp:d});if(!e&&this.options.storage.lifecycle)throw Object.assign(new Error("Gated replication requires a stamped pending store"),{code:"REPLICA_GATED",gate:"gate_unavailable"});u={stamp:d,store:e??a.createMemoryPendingStore(o)},this.pending.set(l,u)}const p=u.store;this.lastPending=p;const f=a.createKVReplication({options:(y=this.options,{...y,syncIntervalMs:y.syncIntervalMs??6e4,maxStalenessMs:y.maxStalenessMs??12e4,staleSyncTimeoutMs:y.staleSyncTimeoutMs??5e3,allowSecrets:!0===y.allowSecrets,contentFetch:y.contentFetch??"eager",verify:!0===y.verify}),mode:this.options.mode??"background",storage:this.options.storage,identity:o,session:{id:i.delegationCid,did:i.verificationMethod,space:i.spaceId},stamp:e.stamp,authority:e.authority,pending:p,scheduler:this.clock,emit:s,fetch:r.fetch,nodeFeatures:e.nodeFeatures,previous:c});var y;this.current=f,this.unsubscribeConsentExpired=this.options.storage.lifecycle?.subscribeConsentExpired?.(e=>f.observeConsentExpired(e)),this.lastController=f,this.lastIdentity=o;for(const[e,t]of this.attached)e.setReadThrough(t===this.primarySpace?f:null);for(const t of e.primaryKV)this.attach(t.space,t.kv);this.pendingPurgeSet&&(this.pendingPurgeResult=f.purge(this.pendingPurge),this.purgedGeneration=t,this.pendingPurge=void 0,this.pendingPurgeSet=!1)}).finally(()=>{t===this.generation&&(this.bindingActive=!1)});for(const e of this.attached.keys())e.setReadThroughReady?.(this.binding);return this.binding}attach(e,t){this.attached.set(t,e),t.setReadThrough(e===this.primarySpace?this.current??this.gated??null:null);const r=this.generation;return this.binding.then(()=>{r!==this.generation||this.closed||this.attached.get(t)!==e||t.setReadThrough(e===this.primarySpace?this.current??this.gated??null:null)})}unbind(){this.generation++,this.bindingActive=!1,this.pendingPurgeSet=!1,this.unsubscribeConsentExpired?.(),this.unsubscribeConsentExpired=void 0;const e=this.current;this.current=void 0,this.gated=void 0,this.gatedReason=void 0,this.primarySpace=void 0,this.detachAll();const t=this.binding.then(()=>e?.close()).catch(()=>{});return this.previous=this.previous.then(()=>t),this.previous}get boundIdentity(){return this.lastIdentity}}},191(e,t,r){r.r(t),r.d(t,{CLEAR_PENDING_WARNING:()=>F,canonicalReplicationIdentity:()=>$,createKVReplication:()=>Oe,createMemoryPendingStore:()=>Ce,kvPrefixCovers:()=>W,replicationIdentityKey:()=>B,requiresSecretsOptIn:()=>H});var n=[{urn:"tinycloud.kv/get",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/list",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/metadata",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/put",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/del",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/delete",service:"tinycloud.kv",status:"deprecated-alias",aliasOf:"tinycloud.kv/del"},{urn:"tinycloud.kv/sync",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.kv/retain",service:"tinycloud.kv",status:"active"},{urn:"tinycloud.sql/read",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/select",service:"tinycloud.sql",status:"deprecated-alias",aliasOf:"tinycloud.sql/read"},{urn:"tinycloud.sql/write",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/schema",service:"tinycloud.sql",status:"active"},{urn:"tinycloud.sql/admin",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/schema"]},{urn:"tinycloud.sql/*",service:"tinycloud.sql",status:"active",implies:["tinycloud.sql/read","tinycloud.sql/write","tinycloud.sql/schema","tinycloud.sql/admin"]},{urn:"tinycloud.duckdb/read",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/write",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/admin",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/import",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/export",service:"tinycloud.duckdb",status:"active"},{urn:"tinycloud.duckdb/select",service:"tinycloud.duckdb",status:"deprecated-alias",aliasOf:"tinycloud.duckdb/read"},{urn:"tinycloud.duckdb/*",service:"tinycloud.duckdb",status:"active",implies:["tinycloud.duckdb/read","tinycloud.duckdb/write","tinycloud.duckdb/admin","tinycloud.duckdb/import","tinycloud.duckdb/export"]},{urn:"tinycloud.capabilities/read",service:"tinycloud.capabilities",status:"active"},{urn:"tinycloud.delegation/status",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.delegation/list",service:"tinycloud.delegation",status:"active"},{urn:"tinycloud.hooks/subscribe",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/register",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/list",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.hooks/unregister",service:"tinycloud.hooks",status:"active"},{urn:"tinycloud.encryption/decrypt",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.create",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.encryption/network.revoke",service:"tinycloud.encryption",status:"active"},{urn:"tinycloud.space/host",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/create",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/list",service:"tinycloud.space",status:"active"},{urn:"tinycloud.space/info",service:"tinycloud.space",status:"active"},{urn:"tinycloud.vfs/get",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/list",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/metadata",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/put",service:"tinycloud.vfs",status:"reserved"},{urn:"tinycloud.vfs/delete",service:"tinycloud.vfs",status:"reserved"}];function i(e){return"*"===e?"ALL":e.toUpperCase().replace(/[^A-Z0-9]/g,"_")}function s(e){return e.slice(10,e.indexOf("/"))}function a(e){return e.slice(e.indexOf("/")+1)}function o(e){const t={};for(const r of n)s(r.urn)===e&&(t[i(a(r.urn))]=r.urn);return t}var c=o("kv"),l={...o("sql"),EXECUTE:"tinycloud.sql/execute",EXPORT:"tinycloud.sql/export"},u=(o("duckdb"),o("capabilities")),d=(o("hooks"),o("encryption")),p=o("space"),f=n,y="applications",h="account",g="applications/",v="secrets",E="default",m="public",w="agents",_="tinycloud.encryption",b=d.NETWORK_CREATE,R=[E,y,h,v,m,w],T={app_id:"xyz.tinycloud.default",name:"TinyCloud Default Space",space:E,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:E,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:E,path:"",actions:["read","write"]}]},A={app_id:"xyz.tinycloud.applications",name:"TinyCloud Applications Space",space:y,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:y,path:"",actions:["get","put","del","list","metadata"]},{service:"tinycloud.sql",space:y,path:"",actions:["read","write"]}]},P={app_id:"xyz.tinycloud.account",name:"TinyCloud Account Registry",space:h,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:h,path:"applications/",actions:["get","put","list"]},{service:"tinycloud.kv",space:h,path:"spaces/",actions:["get","put","list"]},{service:"tinycloud.sql",space:h,path:"account",actions:["read","write","schema"]}]},I={app_id:"xyz.tinycloud.secrets",name:"TinyCloud Secrets",space:v,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.vault",space:v,path:"secrets/",actions:["read"],skipPrefix:!0},{service:"tinycloud.kv",space:v,path:"variables",actions:["list","metadata"],skipPrefix:!0},{service:"tinycloud.kv",space:v,path:"variables/",actions:["get","put","del","list","metadata"],skipPrefix:!0},{service:"tinycloud.sql",space:v,path:"default",actions:["read","write","schema"],skipPrefix:!0},{service:"tinycloud.capabilities",space:v,path:"",actions:["read"],skipPrefix:!0}]},k={app_id:"xyz.tinycloud.public",name:"TinyCloud Public Space",space:m,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:m,path:"",actions:["get","list","metadata"]}]},O={app_id:"xyz.tinycloud.agents",name:"TinyCloud Agents Space",space:w,prefix:"",defaults:!1,includePublicSpace:!1,permissions:[{service:"tinycloud.kv",space:w,path:"",actions:["get","put","del","list","metadata"]}]},S={[E]:T,[y]:A,[h]:P,[v]:I,[m]:k,[w]:O};function N(e){return{...e,permissions:e.permissions?.map(e=>({...e,actions:[...e.actions]}))}}function C(e,t,r){return!0===r||""===e||""===t?t:"/"===t?`${e}/`:`${e.endsWith("/")?e.slice(0,-1):e}/${t.startsWith("/")?t.slice(1):t}`}function x(e,t,r){if("tinycloud.vault"===e.service)return function(e){return e.actions.map(t=>{const r=t.startsWith("tinycloud.vault/")?t.slice(16):t.startsWith("tinycloud.kv/")?t.slice(13):t,n="read"===r||"get"===r?c.GET:"write"===r||"put"===r?c.PUT:"delete"===r||"del"===r?c.DEL:"list"===r?c.LIST:"metadata"===r?c.METADATA:void 0;if(void 0===n)throw new Error(`unknown vault action ${JSON.stringify(t)}`);const i=e.path.startsWith("/")?e.path.slice(1):e.path;return{...e,service:"tinycloud.kv",path:`vault/${i}`,actions:[n],skipPrefix:!0}})}(e).flatMap(e=>x(e,t,r));const n=!0===e.skipPrefix||e.service===_;return[{service:e.service,space:e.service===_?"encryption":e.space??r,path:C(t,e.path,n),actions:e.actions.map(t=>function(e,t){return t.includes("/")?t:`${e}/${t}`}(e.service,t)),...void 0!==e.description?{description:e.description}:{}}]}function D(e){const t=new Set(e.filter(e=>e.service!==_).map(e=>e.space));return function(e){const t=new Map;for(const r of e){const e=`${r.service}\0${r.space}\0${r.path}`,n=t.get(e);if(n)for(const e of r.actions)n.actions.includes(e)||n.actions.push(e);else t.set(e,{...r,actions:[...r.actions]})}return[...t.values()]}([...e,...[...t].map(e=>({service:"tinycloud.capabilities",space:e,path:"",actions:[u.READ]}))])}function M(e){return function(e,t={}){if(!Array.isArray(e)||0===e.length)throw new Error("composeManifestRequest requires at least one manifest");const r=t.includeAccountRegistryPermissions??!0,n=e.map(N),i=n.flatMap(e=>{const t=e.prefix??e.app_id,r=e.space??y;return(e.permissions??[]).flatMap(e=>x(e,t,r))});r&&i.push(...G.map(e=>({...e,actions:[...e.actions]})));const s=new Map;for(const e of n){const t=s.get(e.app_id)??[];t.push(N(e)),s.set(e.app_id,t)}return{manifests:n,resources:D(i),delegationTargets:[],registryRecords:r?[...s.entries()].map(([e,t])=>({key:`${g}${e}`,app_id:e,manifests:t})):[],expiryMs:2592e6,includePublicSpace:n.some(e=>e.includePublicSpace??!0)}}([S[e]],{includeAccountRegistryPermissions:!1})}R.map(e=>({name:e,manifest:S[e],persistedAsApplication:e===v}));var G=Object.freeze([{service:"tinycloud.kv",space:h,path:g,actions:[c.GET,c.PUT,c.LIST]},{service:"tinycloud.kv",space:h,path:"spaces/",actions:[c.GET,c.PUT,c.LIST]},{service:"tinycloud.kv",space:h,path:"system/bootstrap/complete",actions:[c.GET,c.PUT]},{service:"tinycloud.delegation",space:h,path:"",actions:["tinycloud.delegation/list"]},{service:"tinycloud.sql",space:h,path:"account",actions:[l.READ,l.WRITE,l.SCHEMA]},{service:"tinycloud.capabilities",space:h,path:"",actions:[u.READ]}]),L=M(E),U={...L,resources:[...L.resources,...G.map(e=>({...e,actions:[...e.actions]}))]},q=Object.freeze(Object.fromEntries(R.map(e=>[e,e===E?U:M(e)]))),j=Object.freeze([{service:"tinycloud.encryption",resource:"urn:tinycloud:encryption:{ownerDid}:default",actions:[b]}]);Object.freeze(R.flatMap(e=>[{kind:"session",service:"tinycloud.session",space:e,actions:["siwe"],resources:q[e].resources,...e===h?{rawAbilities:j}:{}},{kind:"space/host",service:"tinycloud.space",space:e,actions:[p.HOST]}]));var F="Clearing pending writes surrenders read-your-writes protection for the cleared keys. If a write whose record was cleared had an unknown outcome or never finished, it may commit now or later; this device can serve an older value until the next sync after that commit, as it would for a write from another device.",V=/^(tinycloud:pkh:eip155:\d+:)([^:]+)(:.+)$/,X=/^(did:pkh:eip155:\d+:)([^:]+)$/;function $(e){if(!e||"string"!=typeof e.host||"string"!=typeof e.space||"string"!=typeof e.principal)throw new TypeError("Replication identity host, space, and principal must be strings");const t=/^https?:\/\/([^/?#]*)/i.exec(e.host)?.[1];let r;try{r=new URL(e.host)}catch{throw new TypeError("Replication identity host must be an absolute HTTP(S) URL")}if(!t||t.includes("@")||e.host.includes("?")||e.host.includes("#")||r.username||r.password)throw new TypeError("Replication identity host must be HTTP(S) without credentials, query, or fragment");const n=V.exec(e.space),i=X.exec(e.principal);if(!n||!i)throw new TypeError("Replication identity requires a full TinyCloud space id and a pkh principal DID");return{host:`${r.origin}${r.pathname.replace(/\/+$/,"")}`,space:`${n[1]}${n[2].toLowerCase()}${n[3]}`,principal:`${i[1]}${i[2].toLowerCase()}`}}function B(e){const t=$(e);return`tc-replication/v1\n${t.host}\n${t.space}\n${t.principal}`}function W(e,t){return"/"===e||t.startsWith(e)}function K(e,t){return""===e||t===e||t.startsWith(e.endsWith("/")?e:`${e}/`)}function H(e,t){return"/"===t||!("secrets"!==e&&!e.endsWith(":secrets"))||"vault"===t.split("/",1)[0]}var z={NODE_NOT_RESPONDING:!0,PARTIAL_NODE_WRITE:!0,NODE_IDENTITY_MISMATCH:!0,RESOURCE_NOT_ROUTED:!0,DECRYPTION_DEPENDENCY_UNAVAILABLE:!0,registry_unavailable:!0,node_not_found:!0,node_registry_entry_exists:!0};var Y="NETWORK_ERROR",J="TIMEOUT",Q="ABORTED",Z="INVALID_INPUT",ee="KV_NOT_FOUND";function te(e){return{ok:!0,data:e}}function re(e){return{ok:!1,error:e}}function ne(e,t,r,n){return{code:e,message:t,service:r,cause:n?.cause,meta:n?.meta}}var ie=class extends Error{constructor(e){super(`Request timed out after ${e}ms.`),this.name="TimeoutError",this.timeoutMs=e}};function se(e,t,r){return void 0===t?{code:J,message:"Request timed out.",service:e,...void 0===r?{}:{cause:r}}:{code:J,message:`Request timed out after ${t}ms.`,service:e,...void 0===r?{}:{cause:r},meta:{timeoutMs:t}}}function ae(e,t,r=Y){const n=function(e){if("object"==typeof e&&null!==e&&"code"in e&&"message"in e&&"string"==typeof e.code&&"string"==typeof e.message&&(t=e.code,Object.prototype.hasOwnProperty.call(z,t))){const t="meta"in e?e.meta:void 0;let r="object"!=typeof t||null===t||Array.isArray(t)?void 0:t;return"NODE_NOT_RESPONDING"===e.code&&"hosts"in e&&Array.isArray(e.hosts)?r={...r,hosts:e.hosts}:"PARTIAL_NODE_WRITE"===e.code&&"succeeded"in e&&Array.isArray(e.succeeded)&&"failed"in e&&Array.isArray(e.failed)&&(r={...r,succeeded:e.succeeded,failed:e.failed}),{code:e.code,message:e.message,...e instanceof Error?{cause:e}:{},...r?{meta:r}:{}}}var t}(t);return n?{...n,service:e}:t instanceof Error?function(e){return e instanceof ie||e instanceof Error&&"TimeoutError"===e.name&&"number"==typeof e.timeoutMs}(t)?se(e,t.timeoutMs,t):"AbortError"===t.name?function(e){return{code:Q,message:"Request was aborted.",service:e}}(e):"TimeoutError"===t.name||t.message.toLowerCase().includes("timeout")?se(e):{code:r,message:t.message,service:e,cause:t}:{code:r,message:String(t),service:e}}new Set(f.map(({urn:e})=>e).filter(e=>!e.endsWith("/*"))),new Set(f.map(({service:e})=>e.slice(10)));var oe=new Set(["AUTH_REQUIRED",Z,"AUTH_UNAUTHORIZED","KV_PRECONDITION_FAILED","STORAGE_QUOTA_EXCEEDED","STORAGE_LIMIT_REACHED"]);function ce(e){return{v:2,identity:{...e},committedEpoch:0,seq:0,records:[]}}function le(e,t,r,n=100){return e.records.filter(e=>W(t,e.key)&&("in_flight"===e.state||"ambiguous"===e.state)).sort((e,t)=>e.seq-t.seq).slice(0,n).map(e=>({key:e.key,state:e.state,op:e.op,since:e.at,...e.code?{code:e.code}:{},likelyOrphaned:"in_flight"===e.state&&r-Date.parse(e.at)>6e5}))}function ue(e,t,r,n){if(n)return e;const i=(new TextDecoder).decode(e);if(r)return i;if(t?.includes("application/json"))return JSON.parse(i);if(t?.startsWith("text/"))return i;if(i)try{return JSON.parse(i)}catch{return i}}var de=new TextEncoder,pe=new TextDecoder("utf-8",{fatal:!0});function fe(e,t){const r=de.encode(e),n=de.encode(t);for(let e=0;e<Math.min(r.length,n.length);e++)if(r[e]!==n[e])return r[e]-n[e];return r.length-n.length}function ye(e,t,r){const n=de.encode(JSON.stringify({v:1,space:e,path:t,last:r}));let i="";for(let e=0;e<n.length;e+=32768)i+=String.fromCharCode(...n.subarray(e,e+32768));return`tcr1.${btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function he(e){try{const t=e.slice(5).replace(/-/g,"+").replace(/_/g,"/"),r=atob(t+"=".repeat((4-t.length%4)%4)),n=Uint8Array.from(r,e=>e.charCodeAt(0)),i=JSON.parse(pe.decode(n));return 1===i?.v&&"string"==typeof i.space&&"string"==typeof i.path&&"string"==typeof i.last?i:null}catch{return null}}function ge(){return re(ne(Z,"Local list cursor cannot be served; restart without the cursor","kv",{meta:{replication:"cursor_restart"}}))}function ve(e,t){return e.find(e=>W(e,t))}var Ee=864e5,me=Ee,we=7*Ee,_e=7*Ee,be=Number.NEGATIVE_INFINITY,Re=({now:e,grantTtlMs:t,consentDeadline:r})=>Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(r)?Math.min(Math.min(t,we),r-e):0,Te=3e3,Ae=Te,Pe=e=>new Date(e).toISOString(),Ie=e=>"object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:"REPLICA_UNAVAILABLE";function ke(e,t){if(t.aborted)return Promise.reject(t.reason??Object.assign(new Error("KV request was aborted"),{code:Q}));let r=()=>{};const n=new Promise((e,n)=>{const i=()=>n(t.reason??Object.assign(new Error("KV request was aborted"),{code:Q}));t.addEventListener("abort",i,{once:!0}),r=()=>t.removeEventListener("abort",i)});return Promise.race([e,n]).finally(r)}function Oe(e){const{options:t,mode:r,storage:n,identity:i,session:s,authority:a,pending:o,scheduler:c}=e,l=t=>function(e,t,r){try{e({...r,at:new Date(t.now()).toISOString()})}catch{}}(e.emit,c,t),u=new Map,d=new Set;let p=!1,f=!1,y=!1,h=e.previous,g=!1;const v=new Set;let E=!1,m=null;try{w=a.consentAnchor?.()??null,_=c.now(),m=null!==w&&Number.isFinite(w.at)&&Number.isFinite(_)?w.at>_?{at:_,source:w.source}:w:null,"first_install"===m?.source&&(m=null)}catch{E=!0}var w,_;const b={grantTtlMs:t.grantTtlMs??me,consentAnchor:m},R=void 0===t.maxBytes&&void 0===t.minFreeBytes?void 0:{maxBytes:t.maxBytes,minFreeBytes:t.minFreeBytes},T=null===m?null:(e=>Number.isFinite(e.at)?e.at+_e:be)(m);let A,P=null;function I(){if("indexeddb"!==n.kind||!e.stamp)return null;try{const t=n.lifecycle?.consentDeadline(e.stamp);return"number"==typeof t&&Number.isFinite(t)?t:null}catch{return null}}function k(){if(null===T)return null;if("indexeddb"!==n.kind)return T;const e=I();return null===e?null:Math.min(T,e)}const O=new Set;let S=!1;function N(){const t=n.lifecycle;if(!t)return"indexeddb"===n.kind||E||void 0!==e.stamp?{status:"gated",gate:"gate_unavailable"}:{status:"allow"};if(!e.stamp)return{status:"gated",gate:"not_established"};if(S)return{status:"gated",gate:"stamp_stale"};try{const r=t.checkDelivery(e.stamp);if("consent_expired"===r.status&&x(),"allow"!==r.status)return r;if("indexeddb"===n.kind){const e=I();if(null===e)return{status:"gated",gate:"gate_unavailable"};const t=c.now();if(!Number.isFinite(t))return{status:"gated",gate:"gate_unavailable"};if(t>=e)return x(),{status:"consent_expired",code:"CONSENT_EXPIRED"}}return E?{status:"gated",gate:"gate_unavailable"}:r}catch{return{status:"gated",gate:"gate_unavailable"}}}function C(){if(S||p||f)return!1;A?.(),A=void 0,S=!0;for(const e of u.values()){e.renewalTimer?.(),e.renewalTimer=void 0,e.mintAbort?.abort();const t=e.handle?.replicaId;t&&!O.has(t)&&(O.add(t),l({type:"replication.grant",replicaId:t,action:"consent_deadline_reached",code:"CONSENT_EXPIRED"}))}return!0}function x(){const e=n.lifecycle;e&&C()&&e.deny({reason:"consent_expired",principal:i.principal}).then(e=>l({type:"replication.lifecycle",action:"denied"===e.status?"denied":"stale"===e.status?"deny_stale":"deleted"===e.status?"database_deleted":"marker"===e.status?"marker_set":"unguarded",reason:"consent_expired"}),()=>l({type:"replication.lifecycle",action:"deny_failed",reason:"consent_expired"}))}function D(e){return Object.assign(new Error("consent_expired"===e.status?"Replica consent expired":"Replica session is gated"),{code:"consent_expired"===e.status?e.code:"REPLICA_GATED",..."gated"===e.status?{gate:e.gate}:{}})}function M(e){return"CONSENT_EXPIRED"===e||"GRANT_EXPIRED"===e?"grant_expired":"REPLICA_GATED"===e?"replica_gated":"replica_error"}function G(e,t,r){if(!(r?.unconstrained&&t.replicaId&&"number"==typeof r.effectiveExpiresAt&&Number.isFinite(r.effectiveExpiresAt)&&(null===r.expiresAt||r.effectiveExpiresAt<r.expiresAt)))return;const n=`${r.cid}:${r.effectiveExpiresAt}`;e.reportedCappedCid!==n&&(e.reportedCappedCid=n,l({type:"replication.grant",replicaId:t.replicaId,action:"capped",effectiveExpiresAt:Pe(r.effectiveExpiresAt)}))}const L=e=>t.prefixes.find(t=>W(t,e));function U(e,t){if("GRANT_REVOKED"!==Ie(t))return;const r=u.get(e)??{};r.authorityRevoked=!0,r.reason="grant_revoked",r.lastError="GRANT_REVOKED",u.set(e,r)}function q(e){const t=u.get(e)??{},r="REPLICATION_ROOT_UNSUPPORTED"!==t.lastError;t.reason="replica_unavailable",t.lastError="REPLICATION_ROOT_UNSUPPORTED",u.set(e,t),r&&l({type:"replication.state",space:s.space,replica:e,state:"unavailable",code:"REPLICATION_ROOT_UNSUPPORTED"})}function j(e){return q(e),Object.assign(new Error("This node doesn't support whole-space sync yet."),{code:"REPLICATION_ROOT_UNSUPPORTED"})}function F(e){try{if(!0!==a.sessionOnly)return;const t=a.sessionGrant(e);return"refused"in t?t.refused:void 0}catch{return"NOT_COVERED"}}async function V(o){const d=N();if("allow"!==d.status)throw D(d);if(p||f)throw Object.assign(new Error("Replication controller is closed"),{code:"REPLICA_CLOSED"});let y=u.get(o);if(y?.handle)return y.handle;if(y?.opening)return y.opening;if(y??(y={}),u.set(o,y),y.unsupported)throw Object.assign(new Error("Replication runtime is unsupported"),{code:"RUNTIME_UNSUPPORTED"});if(void 0!==y.retryAt&&c.now()<y.retryAt)throw Object.assign(new Error("Replica open is backing off"),{code:y.lastError??"REPLICA_UNAVAILABLE"});if(H(s.space,o)&&!t.allowSecrets){const e="SECRETS_OPT_IN_REQUIRED"!==y.lastError;throw y.reason="replica_unavailable",y.lastError="SECRETS_OPT_IN_REQUIRED",e&&l({type:"replication.state",space:s.space,replica:o,state:"unavailable",code:"SECRETS_OPT_IN_REQUIRED"}),Object.assign(new Error("Replication requires allowSecrets for this space or prefix"),{code:"SECRETS_OPT_IN_REQUIRED"})}y.opening=(async()=>{h&&(await h,h=void 0);const u=N();if("allow"!==u.status)throw D(u);const d=!0===a.sessionOnly,g=a.sessionGrant(o),v="refused"in g?void 0:g,E=d?void 0:a.plan(o);let w,_;"refused"in g&&(w=g.refused),E&&"refused"in E&&(w??(w=E.refused)),e.stamp&&null===m&&!d&&(w="REPLICA_GATED"),v&&(_=v.device,y.strategy="session");const A={identity:i,space:s.space,prefix:o,allowSecrets:t.allowSecrets,grantPolicy:b,...R?{quota:R}:{},...t.contentFetch?{contentFetch:t.contentFetch}:{},...e.stamp?{stamp:e.stamp}:{},..._?{device:_}:{},...e.fetch?{fetch:e.fetch}:{},onPeerCommit:e=>{p||f||void 0===y.handle||l({type:"replication.sync",space:s.space,replica:o,trigger:"peer",origin:"peer",outcome:"ok",durationMs:0,lagMs:null,...void 0===e.changes?{}:{changes:e.changes},...void 0===e.coverage?{}:{coverage:e.coverage}})}};if("/"===o&&void 0!==e.nodeFeatures&&!e.nodeFeatures.includes("kv-sync-root"))throw j(o);const P=await n.open(A);y.handle=P;const O=N();if("allow"!==O.status)throw D(O);l({type:"replication.state",space:s.space,replica:o,state:"opened"});const S=d||!E||"refused"in E?void 0:E;let C,x=S||v?await P.grant():void 0;if(x&&!function(t,r){if(!t?.unconstrained)return!1;if(!e.stamp)return!0;if(!r&&null===m)return!1;const i=c.now(),s="indexeddb"===n.kind?I():T??t.consentDeadline;return"active"===t.state&&"number"==typeof t.installedAt&&Number.isFinite(t.installedAt)&&"number"==typeof t.effectiveExpiresAt&&Number.isFinite(t.effectiveExpiresAt)&&"number"==typeof t.consentDeadline&&Number.isFinite(t.consentDeadline)&&"number"==typeof s&&Number.isFinite(s)&&Number.isFinite(i)&&i>=t.installedAt&&(null===t.expiresAt||"number"==typeof t.expiresAt&&Number.isFinite(t.expiresAt)&&i<t.expiresAt)&&i<Math.min(t.effectiveExpiresAt,t.consentDeadline,s)}(x,d)&&(x.unconstrained&&(w=null!==m||d?"GRANT_EXPIRED":"REPLICA_GATED"),x=void 0),v&&null!==m){const e=N();if("allow"!==e.status)throw D(e);x=await P.installGrant(v.ucan)}else if(S){if(!x||!x.unconstrained||x.parentCid!==S.parentCid||null!==x.expiresAt&&S.expiresAt>x.expiresAt+3e5){const e=k(),t=Re({now:c.now(),grantTtlMs:b.grantTtlMs,consentDeadline:e??Number.NaN});if(t>0)try{const e=new AbortController;y.mintAbort=e;const r=await a.mint(P.deviceDid,o,e.signal,{expiryMs:t}),n=N();if("allow"!==n.status)throw D(n);x=await P.installGrant(r.ucan),y.strategy="minted",C=t}catch(e){if("CONSENT_EXPIRED"===Ie(e)||"REPLICA_GATED"===Ie(e)||!x?.unconstrained)throw e}finally{y.mintAbort=void 0}}x?.unconstrained&&(y.strategy??(y.strategy="installed"),y.reason=void 0)}else(v||d)&&x?.unconstrained&&(y.strategy="installed");const M=N();if("allow"!==M.status)throw D(M);if(G(y,P,x),void 0!==C&&(y.reportedExpired=!1),void 0!==C&&P.replicaId&&l({type:"replication.grant",replicaId:P.replicaId,action:"minted",expiryMs:C}),x?.unconstrained?l({type:"replication.state",space:s.space,replica:o,state:"grant_installed",strategy:y.strategy}):(y.reason="grant_missing",y.lastError=w??"SESSION_LACKS_SYNC",l({type:"replication.state",space:s.space,replica:o,state:"grant_missing",code:y.lastError})),p||f)throw await P.close(),Object.assign(new Error("Replication controller is closed"),{code:"REPLICA_CLOSED"});return x?.unconstrained&&await $(o,P,x,S),"background"===r&&"grant_missing"!==y.reason&&(z(o,"start").catch(()=>{}),B(o)),P})();try{return await y.opening}catch(e){const t=Ie(e);throw"CONSENT_EXPIRED"===t&&x(),U(o,e),"REPLICA_GATED"===t||"CONSENT_EXPIRED"===t?y.reason=M(t):"GRANT_REVOKED"!==t&&(y.reason="replica_unavailable"),y.lastError=t,y.failures=(y.failures??0)+1,"RUNTIME_UNSUPPORTED"===t?y.unsupported=!0:"REPLICA_CLOSED"!==t&&"REPLICATION_ROOT_UNSUPPORTED"!==t&&"REPLICA_GATED"!==t&&"CONSENT_EXPIRED"!==t&&(y.retryAt=c.now()+Math.min(3e5,5e3*2**Math.min(y.failures-1,6))),y.handle?.close().catch(()=>{}),y.handle=void 0,e}finally{y.opening=void 0}}function X(e,t,r,n){const i=u.get(e);if(i?.renewalTimer?.(),i&&(i.renewalTimer=void 0),!i||p||f||"session"!==n.path||!a.canRenew)return;const{installedAt:s,effectiveExpiresAt:o}=r,l=k();if(!("number"==typeof s&&Number.isFinite(s)&&"number"==typeof o&&Number.isFinite(o)&&o>s&&null!==l))return;const d=s+.75*(o-s),y=c.now();Number.isFinite(y)&&d<l&&!(y>d)&&(i.renewalTimer=c.setTimeout(()=>{i.renewalTimer=void 0,$(e,t).catch(()=>{})},Math.max(0,Math.floor(d)+1-y)))}async function $(e,t,r,n){const i=u.get(e);if(!i||i.handle!==t||p||f||!a.canRenew)return;if(i.renewing)return i.renewing;if("allow"!==N().status)return;const s=r??await t.grant();if(!s?.unconstrained)return;const{installedAt:o,effectiveExpiresAt:d}=s,y=k();if("number"!=typeof o||!Number.isFinite(o)||"number"!=typeof d||!Number.isFinite(d)||null===y)return;const h=c.now();if(!(({now:e,installedAt:t,effectiveExpiresAt:r,consentDeadline:n})=>!!(Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(r)&&Number.isFinite(n))&&e<n&&r-e<.25*(r-t))({now:h,installedAt:o,effectiveExpiresAt:d,consentDeadline:y}))return void(n&&X(e,t,s,n));let g=n;try{if(!g){const r=a.plan(e);if("refused"in r)return void(t.replicaId&&l({type:"replication.grant",replicaId:t.replicaId,action:"renewal_refused",code:r.refused}));g=r}}catch{return void(t.replicaId&&l({type:"replication.grant",replicaId:t.replicaId,action:"renewal_deferred"}))}if("session"!==g?.path)return void(t.replicaId&&i.reportedRenewalUnqualifiedCid!==s.cid&&(i.reportedRenewalUnqualifiedCid=s.cid,l({type:"replication.grant",replicaId:t.replicaId,action:"renewal_deferred"})));const v=Re({now:h,grantTtlMs:b.grantTtlMs,consentDeadline:y});if(!(v>0))return;i.renewalTimer?.(),i.renewalTimer=void 0;const E=new AbortController;i.mintAbort=E;const m=Promise.resolve().then(async()=>{const r=await a.mint(t.deviceDid,e,E.signal,{expiryMs:v,renewalOnly:!0}),n=N();if("allow"!==n.status)throw D(n);const s=await t.installGrant(r.ucan),o=N();if("allow"!==o.status)throw D(o);G(i,t,s),i.reportedExpired=!1,"grant_expired"===i.reason&&(i.reason=void 0),"GRANT_EXPIRED"===i.lastError&&(i.lastError=void 0),t.replicaId&&l({type:"replication.grant",replicaId:t.replicaId,action:"renewed",expiryMs:v}),"number"==typeof s.effectiveExpiresAt&&s.effectiveExpiresAt>d&&X(e,t,s,g)});i.renewing=m;try{await m}catch(e){const r=Ie(e);if("CONSENT_EXPIRED"===r||"REPLICA_GATED"===r)throw e;if(!p&&t.replicaId){const n="object"==typeof e&&null!==e&&"refused"in e&&"string"==typeof e.refused?e.refused:null;l({type:"replication.grant",replicaId:t.replicaId,action:n?"renewal_refused":"renewal_deferred",code:n??r})}}finally{i.renewing=void 0,i.mintAbort===E&&(i.mintAbort=void 0)}}function B(e){const n=u.get(e);!n||"background"!==r||p||f||(n.timer=c.setTimeout(()=>{n.timer=void 0,z(e,"interval").catch(()=>{}).finally(()=>B(e))},t.syncIntervalMs))}async function z(t,r,n,i){if("/"===t&&void 0!==e.nodeFeatures&&!e.nodeFeatures.includes("kv-sync-root"))throw j(t);const a=F(t);if(a)throw Object.assign(new Error("Current session does not cover replica sync"),{code:a});const d=await V(t),p=u.get(t);if(p.sync)return p.sync;const f=new AbortController,y=i??{};p.syncContext=y,p.abort=f;const h=()=>{y.abortCause??(y.abortCause="caller"),f.abort(n?.reason)};n?.addEventListener("abort",h,{once:!0});const g=c.now();let E;E=(async()=>{try{const e=(await o.read()).committedEpoch,n=N();if("allow"!==n.status)throw D(n);await $(t,d);const i=N();if("allow"!==i.status)throw D(i);const a=F(t);if(a)throw Object.assign(new Error("Current session does not cover replica sync"),{code:a});const u=await d.sync({signal:f.signal,syncStartEpoch:e}),p=N();if("allow"!==p.status)throw D(p);if("busy"===u.status)return l({type:"replication.sync",space:s.space,replica:t,trigger:r,outcome:"busy",durationMs:c.now()-g,lagMs:null}),u;v.add(t);const y=await o.read(),h=N();if("allow"!==h.status)throw D(h);const E=y.records.some(r=>"committed"===r.state&&null!==r.epoch&&r.epoch<=e&&W(t,r.key))?await o.update(r=>function(e,t,r){const n=e.records.length;return e.records=e.records.filter(e=>!("committed"===e.state&&null!==e.epoch&&e.epoch<=r&&W(t,e.key))),n-e.records.length}(r,t,e)):0,m=N();if("allow"!==m.status)throw D(m);return l({type:"replication.sync",space:s.space,replica:t,trigger:r,outcome:"ok",durationMs:c.now()-g,lagMs:null,pendingCleared:E,pages:u.pages,changes:u.changes,deleted:u.deleted,fetched:u.fetched,contentMissing:u.contentMissing,coverage:u.coverage}),u}catch(e){const n=Ie(e);throw p.lastError=n,U(t,e),"CONSENT_EXPIRED"===n&&x(),l({type:"replication.sync",space:s.space,replica:t,trigger:r,outcome:f.signal.aborted?"aborted":"error",class:"CONSENT_EXPIRED"===n||"REPLICA_GATED"===n?"lifecycle":"NETWORK_ERROR"===n||"TIMEOUT"===n?"offline":"node",code:n,durationMs:c.now()-g,lagMs:null}),e}finally{n?.removeEventListener("abort",h),p.abort=void 0}})(),p.sync=E;try{return await E}finally{p.sync===E&&(p.sync=void 0,p.syncContext=void 0)}}async function J(e,t){let r=()=>{};const n=t.then(e=>({settled:!0,result:e}),e=>({settled:!0,error:e})),i=new Promise(e=>{r=c.setTimeout(()=>e({settled:!1}),Te)});try{const t=await Promise.race([n,i]);return t.settled||l({type:"replication.sync",space:s.space,replica:e,trigger:"stale_read",outcome:"aborted",code:"DRAIN_TIMEOUT",durationMs:Te,lagMs:null}),t}finally{r()}}function Q(e){if("complete"!==e.coverage)throw Object.assign(new Error("Replica coverage changed before the local read"),{code:"COVERAGE_INCOMPLETE"});if("valid"!==e.authority){const t="expired"===e.authority?"GRANT_EXPIRED":"revoked"===e.authority?"GRANT_REVOKED":"GRANT_NOT_YET_VALID";throw Object.assign(new Error("Replica authority changed before the local read"),{code:t})}}function Z(e){return"COVERAGE_INCOMPLETE"===e?"coverage_incomplete":"GRANT_EXPIRED"===e?"grant_expired":"GRANT_REVOKED"===e?"grant_revoked":"GRANT_NOT_YET_VALID"===e?"grant_not_yet_valid":"replica_error"}function ie(e,t,r){if("error"in e){const n=Ie(e.error);return"NETWORK_ERROR"===n||t&&("ABORTED"===n||"TIMEOUT"===n)?{status:r,syncedBeforeRead:!1,syncError:"NETWORK_ERROR"===n?n:"TIMEOUT"}:{status:r,syncedBeforeRead:!1,syncError:n,failure:"error"}}return"busy"===e.result.status?{status:r,syncedBeforeRead:!1,failure:"busy"}:{status:r,syncedBeforeRead:!0}}async function se(e,n,i){let s=await n.status();const a=null===s.lastSyncAt?null:Date.parse(s.lastSyncAt),l=null===a||!Number.isFinite(a)||c.now()-a>t.maxStalenessMs;let d;try{d=await o.read()}catch(e){return{status:s,syncedBeforeRead:!1,syncError:Ie(e),failure:"error"}}const p=s.syncedThroughEpoch<d.committedEpoch,f=!o.durable&&!v.has(e);if((l||p||f)&&!i.aborted){const a="foreground"===r?new AbortController:void 0,o=u.get(e),l=!o?.sync,d=o?.syncContext??{},p=()=>{l&&(d.abortCause??(d.abortCause="caller")),a?.abort(i.reason)};a&&i.addEventListener("abort",p,{once:!0});let f=()=>{};const y=new Promise(e=>{f=c.setTimeout(()=>e({timeout:!0}),t.staleSyncTimeoutMs)});let h=()=>{};const g=new Promise(e=>{if(i.aborted)e({callerAborted:!0});else{const t=()=>e({callerAborted:!0});i.addEventListener("abort",t,{once:!0}),h=()=>i.removeEventListener("abort",t)}}),v=z(e,"stale_read",a?.signal,d),E=await Promise.race([v.then(e=>({result:e}),e=>({error:e})),y,g]);if(f(),h(),i.removeEventListener("abort",p),"callerAborted"in E)return a&&l&&(d.abortCause??(d.abortCause="caller"),a.abort(i.reason),await J(e,v)),{status:s,syncedBeforeRead:!1,syncError:Se(i)};if("timeout"in E){l&&(d.abortCause??(d.abortCause="timeout"),a?.abort(Object.assign(new Error("Stale-read sync timed out"),{code:"TIMEOUT"})));const t=a?await J(e,v):void 0;if(i.aborted)return{status:s,syncedBeforeRead:!1,syncError:Se(i)};if(t&&!t.settled)return{status:s,syncedBeforeRead:!1,syncError:"DRAIN_TIMEOUT",failure:"error"};try{s=await async function(e,t){let r=()=>{};const n=new Promise((e,t)=>{r=c.setTimeout(()=>t(Object.assign(new Error("Replica status refresh timed out"),{code:"STATUS_TIMEOUT"})),Ae)});try{return await ke(Promise.race([e.status(),n]),t)}finally{r()}}(n,i)}catch(e){return i.aborted?{status:s,syncedBeforeRead:!1,syncError:Se(i),failure:"error"}:{status:s,syncedBeforeRead:!1,syncError:Ie(e),failure:"error"}}const r="timeout"===d.abortCause;return ie(t?.settled?"result"in t?{result:t.result}:{error:t.error}:{error:Object.assign(new Error("Stale-read sync timed out"),{code:"TIMEOUT"})},r||!a,s)}return"error"in E?ie({error:E.error},!1,s):"busy"===E.result.status?{status:s,syncedBeforeRead:!1,failure:"busy"}:(s=await n.status(),{status:s,syncedBeforeRead:!0})}return{status:s,syncedBeforeRead:!1}}function de(e,t,r,n,i,a,o,d={}){null!==r&&"grant_expired"===i&&"CONSENT_EXPIRED"!==d.code&&function(e){const t=u.get(e);if(!t)return;t.reason="grant_expired",t.lastError="GRANT_EXPIRED";const r=t.handle?.replicaId;r&&!t.reportedExpired&&(t.reportedExpired=!0,l({type:"replication.grant",replicaId:r,action:"expired",code:"GRANT_EXPIRED"}))}(r),l({type:"replication.read",op:e,space:s.space,key:t,replica:r,source:n,reason:i,outcome:a,latencyMs:c.now()-o,stalenessMs:null,coverage:null,authority:null,...d})}async function pe(e,t,r,n,i,s,a={}){let o="error";try{const r=await e();return o=r.ok?"found":"get"!==t||"pending_write"!==i&&"not_covered"!==i||r.error.code!==ee?"error":"not_found",r}finally{de(t,r,n,"network",i,o,s,a)}}async function Ee(){if(!g){g=!0;try{const e=le(await o.read(),"",c.now());e.length>0&&l({type:"replication.state",space:s.space,state:"pinned",count:e.length,keys:e.map(e=>e.key)})}catch{l({type:"replication.state",space:s.space,state:"pending_store_error",code:"STORAGE_ERROR"})}}}function we(e){l({type:"replication.read",op:e.op,space:e.space,key:e.path,replica:null,source:"network",reason:"NETWORK_REQUESTED",outcome:e.outcome,latencyMs:e.latencyMs,stalenessMs:null,coverage:null,authority:null})}function Oe(){const e=[...d];for(const t of e)t.abort.abort(Object.assign(new Error("Replica status inspection cancelled"),{code:"ABORTED"}));return Promise.all(e.map(e=>e.settled)).then(()=>{})}function Ce(e){return t.prefixes.map(t=>({prefix:t,state:"gated",reason:"replica_gated",gate:"gated"===e.status?e.gate:"stamp_stale",errorCode:"consent_expired"===e.status?e.code:"REPLICA_GATED",pending:{inFlight:0,committed:0,ambiguous:0},pinned:[],lagMs:null,redacted:!0}))}return function(){const e=I();if(null===e||S||p)return;const t=c.now();Number.isFinite(t)&&(P===e&&A||(P=e,A?.(),A=c.setTimeout(()=>{A=void 0,N()},Math.max(0,e-t))))}(),{get:async function(e){const r=c.now(),n=L(e.path);if("network"===e.options?.source){let t="error";try{const r=await e.network();return t=r.ok?"found":r.error.code===ee?"not_found":"error",r}finally{we({op:"get",space:e.space,path:e.path,reason:"NETWORK_REQUESTED",outcome:t,latencyMs:c.now()-r})}}let i=!1;const s=async(t,n,s={})=>{try{return await pe(e.network,"get",e.path,t,n,r,s)}catch(e){throw i=!0,e}};if(void 0===n)return pe(e.network,"get",e.path,null,"not_covered",r);const a=N();if("allow"!==a.status)return s(n,"consent_expired"===a.status?"grant_expired":"replica_gated",{code:"consent_expired"===a.status?a.code:"REPLICA_GATED"});const d=F(n);if(d)return s(n,"grant_missing",{code:d});try{await ke(Ee(),e.signal)}catch{if(e.signal.aborted)return Ne(e.signal)}let p,f,y;try{p=await ke(V(n),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);"CONSENT_EXPIRED"===Ie(t)&&x();const r=Ie(t);return s(n,"RUNTIME_UNSUPPORTED"===r?"runtime_unsupported":"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}if("grant_missing"===u.get(n)?.reason){const e=u.get(n)?.lastError;return s(n,"GRANT_EXPIRED"===e?"grant_expired":"REPLICA_GATED"===e?"replica_gated":"grant_missing",{code:e})}try{f=await se(n,p,e.signal)}catch(t){if(U(n,t),"CONSENT_EXPIRED"===Ie(t)&&x(),e.signal.aborted)return Ne(e.signal);const r=Ie(t);return s(n,"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_error",{code:r})}if(e.signal.aborted)return Ne(e.signal);if(f.failure){const e="busy"===f.failure?"REPLICA_BUSY":f.syncError;return s(n,"GRANT_REVOKED"===e?"grant_revoked":"REPLICA_GATED"===e||"CONSENT_EXPIRED"===e||"GRANT_EXPIRED"===e?M(e):"stale",{code:e,syncedBeforeRead:f.syncedBeforeRead})}try{y=await ke(o.read(),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);const r=Ie(t);return s(n,"REPLICA_GATED"===r||"CONSENT_EXPIRED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}const h=y.records.find(t=>t.key===e.path);if(h)return s(n,"pending_write",{pendingState:h.state,syncedBeforeRead:f.syncedBeforeRead});if(!o.durable&&!v.has(n))return s(n,"REPLICA_UNPROVEN_SINCE_START");if(f.status.syncedThroughEpoch<y.committedEpoch)return s(n,"REPLICA_BEHIND_OWN_WRITES");if("valid"!==f.status.authority.state)return s(n,"expired"===f.status.authority.state?"grant_expired":"revoked"===f.status.authority.state?"grant_revoked":"grant_not_yet_valid");if("complete"!==f.status.coverage)return s(n,"coverage_incomplete");try{const i=await ke(p.get(e.path),e.signal),a=N();if("allow"!==a.status)throw D(a);const o=F(n);if(o)return await s(n,"grant_missing",{code:o});try{Q(i.meta)}catch(e){const t=Ie(e);return U(n,e),await s(n,Z(t),{code:t})}if("coverage_incomplete"===i.status||"not_covered"===i.status||"content_missing"===i.status)return await s(n,"content_missing"===i.status?"content_missing":"coverage_incomplete"===i.status?"coverage_incomplete":"not_covered");if("present"===i.status&&void 0!==e.options?.maxResponseBytes&&i.value.byteLength>e.options.maxResponseBytes)return await s(n,"unsupported_option");const u=function(e,t,r){if("present"===e.status){if(void 0!==r.maxResponseBytes&&e.value.byteLength>r.maxResponseBytes)return re(ne("KV_RESPONSE_TOO_LARGE",`KV value at key ${JSON.stringify(t)} exceeds the requested response limit`,"kv",{meta:{status:413}}));const n=Object.entries(e.metadata).find(([e])=>"content-type"===e.toLowerCase())?.[1],i=new Headers({etag:e.etag,"content-length":String(e.value.byteLength),"cache-control":"private, no-cache",...e.metadata,"x-tinycloud-source":"replica"});return te({data:ue(e.value,n,r.raw,r.binary),headers:{etag:e.etag,contentType:n,contentLength:e.value.byteLength,get:e=>i.get(e)}})}return"absent"===e.status||"deleted"===e.status?re(ne(ee,`Key not found: ${t}`,"kv")):re(ne(Y,"Local value is not available","kv"))}(i,e.path,e.options??{}),d="present"===i.status?"hit":i.status,y=null===f.status.lastSyncAt?null:Date.parse(f.status.lastSyncAt),h={syncedBeforeRead:f.syncedBeforeRead,coverage:i.meta.coverage,authority:i.meta.authority,stalenessMs:null===y?null:c.now()-y,...f.syncError?{syncError:f.syncError}:{}};return t.verify?await async function(e,t,r,n,i){const s=L(e.path)??null,a=t.ok,o=!t.ok&&t.error.code===ee,c=a?"found":o?"not_found":"error";try{const u=await ke(e.network(),e.signal);if(e.signal.aborted)return de("get",e.path,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const d=N();if("allow"!==d.status)return de("get",e.path,s,"network","consent_expired"===d.status?"grant_expired":"replica_gated",u.ok?"found":"error",n,{code:"consent_expired"===d.status?d.code:"REPLICA_GATED"}),u;const p=null===s?void 0:F(s);if(p)return de("get",e.path,s,"network","grant_missing",u.ok?"found":"error",n,{code:p}),u;if(!u.ok&&u.error.code!==ee)return de("get",e.path,s,"replica",r,c,n,{...i,code:u.error.code,verify:"error"}),t;const f=u.ok,y=!u.ok&&u.error.code===ee,h=t.ok?t.data.headers.etag??null:null,g=u.ok?u.data.headers.etag??null:null,v=a&&f?h===g:o&&y,E=v?"match":"diverged";return v||l({type:"replication.divergence",op:"get",space:e.space,key:e.path,replica:s??"",kind:a&&f?"value":o?"missing_local":"extra_local",localEtag:h,networkEtag:g,stalenessMs:"number"==typeof i.stalenessMs?i.stalenessMs:null}),de("get",e.path,s,"replica",r,c,n,{...i,verify:E}),t}catch(a){if(e.signal.aborted)return de("get",e.path,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const o=N();if("allow"!==o.status)return de("get",e.path,s,"network","consent_expired"===o.status?"grant_expired":"replica_gated","error",n,{code:"consent_expired"===o.status?o.code:"REPLICA_GATED"}),re(ae("kv",a));const l=null===s?void 0:F(s);return l?(de("get",e.path,s,"network","grant_missing","error",n,{code:l}),re(ae("kv",a))):(de("get",e.path,s,"replica",r,c,n,{...i,code:Ie(a),verify:"error"}),t)}}(e,u,d,r,h):(de("get",e.path,n,"replica",d,u.ok?"found":u.error.code===ee?"not_found":"error",r,h),u)}catch(t){if(i)throw t;return U(n,t),"CONSENT_EXPIRED"===Ie(t)&&x(),e.signal.aborted?Ne(e.signal):s(n,M(Ie(t)),{code:Ie(t)})}},list:async function(e){const r=c.now();if("network"===e.options?.source){let t="error";try{const r=await e.network();return t=r.ok?"found":"error",r}finally{we({op:"list",space:e.space,path:e.listPath,reason:"NETWORK_REQUESTED",outcome:t,latencyMs:c.now()-r})}}const n=e.options?.cursor,i=n?.startsWith("tcr1.")?he(n):null;if(n&&n.startsWith("tcr1.")&&!i)return de("list",e.listPath,null,"none","cursor_restart","error",r),ge();if(n&&!n.startsWith("tcr1."))return pe(e.network,"list",e.listPath,null,"network_cursor",r);const s=ve(t.prefixes,e.listPath);let a=!1;const d=async(t,n,i={})=>{try{return await pe(e.network,"list",e.listPath,t,n,r,i)}catch(e){throw a=!0,e}};if(void 0!==s&&!e.options?.raw){const t=N();if("allow"!==t.status)return i?(de("list",e.listPath,s,"none","cursor_restart","error",r),ge()):d(s,"consent_expired"===t.status?"grant_expired":"replica_gated",{code:"consent_expired"===t.status?t.code:"REPLICA_GATED"})}if(void 0!==s&&!e.options?.raw){const t=F(s);if(t)return i?(de("list",e.listPath,s,"none","cursor_restart","error",r),ge()):d(s,"grant_missing",{code:t})}try{await ke(Ee(),e.signal)}catch{if(e.signal.aborted)return Ne(e.signal)}const p=()=>(de("list",e.listPath,s??null,"none","cursor_restart","error",r),ge());if(n&&i&&(i.space!==e.space||i.path!==e.listPath))return p();if(void 0===s||e.options?.raw)return n&&i?p():pe(e.network,"list",e.listPath,s??null,void 0!==s?"unsupported_option":"not_covered",r);let f,y,h;try{f=await ke(V(s),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);if("CONSENT_EXPIRED"===Ie(t)&&x(),n&&i)return p();const r=Ie(t);return d(s,"RUNTIME_UNSUPPORTED"===r?"runtime_unsupported":"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}if("grant_missing"===u.get(s)?.reason){if(n&&i)return p();const e=u.get(s)?.lastError;return d(s,"GRANT_EXPIRED"===e?"grant_expired":"REPLICA_GATED"===e?"replica_gated":"grant_missing",{code:e})}try{y=await se(s,f,e.signal)}catch(t){if(U(s,t),"CONSENT_EXPIRED"===Ie(t)&&x(),e.signal.aborted)return Ne(e.signal);if(n&&i)return p();const r=Ie(t);return d(s,"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_error",{code:r})}if(e.signal.aborted)return Ne(e.signal);try{h=await ke(o.read(),e.signal)}catch(t){if(e.signal.aborted)return Ne(e.signal);if(n&&i)return p();const r=Ie(t);return d(s,"REPLICA_GATED"===r||"CONSENT_EXPIRED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}const g=h.records.find(t=>K(e.listPath,t.key)),E=y.status.syncedThroughEpoch<h.committedEpoch;if(n&&i&&(y.failure||g||E||"complete"!==y.status.coverage||"valid"!==y.status.authority.state||!o.durable&&!v.has(s)))return p();if(E)return d(s,"REPLICA_BEHIND_OWN_WRITES");if(y.failure){const e="busy"===y.failure?"REPLICA_BUSY":y.syncError;return d(s,"GRANT_REVOKED"===e?"grant_revoked":"REPLICA_GATED"===e||"CONSENT_EXPIRED"===e||"GRANT_EXPIRED"===e?M(e):"stale",{code:e})}if(g)return d(s,"pending_write",{pendingState:g.state});if(!o.durable&&!v.has(s))return d(s,"REPLICA_UNPROVEN_SINCE_START");if("complete"!==y.status.coverage||"valid"!==y.status.authority.state)return d(s,"complete"!==y.status.coverage?"coverage_incomplete":"expired"===y.status.authority.state?"grant_expired":"revoked"===y.status.authority.state?"grant_revoked":"grant_not_yet_valid");try{const a={list:t=>ke(f.list(t),e.signal)},u=await ke(function(e,t,r,n,i,s){const a=i?he(i)?.last:void 0,o=""!==r&&!r.endsWith("/")&&(void 0===a||fe(r,a)>0)?async function(e,t,r,n){if(void 0!==r&&fe(t,r)<=0)return!1;const i=await e.list({prefix:t,limit:1});return n(i.meta),i.keys[0]===t}(e,r,a,s):Promise.resolve(!1);return o.then(async i=>{const o=""===r?"":r.endsWith("/")?r:`${r}/`,c=void 0===n?void 0:n+1-(i?1:0),l=await e.list({prefix:o,after:a,limit:c});s(l.meta);let u=(i?[r]:[]).concat(l.keys);const d=void 0!==n&&u.length>n;return d&&(u=u.slice(0,n)),{keys:u,truncated:d,...d?{nextCursor:ye(t,r,u[u.length-1])}:{}}})}(a,e.space,e.listPath,e.options?.limit,n,Q),e.signal),h=await ke(o.read(),e.signal),g=h.records.find(t=>K(e.listPath,t.key));if(n&&i&&(g||y.status.syncedThroughEpoch<h.committedEpoch))return p();if(y.status.syncedThroughEpoch<h.committedEpoch)return await d(s,"REPLICA_BEHIND_OWN_WRITES");if(g)return await d(s,"pending_write",{pendingState:g.state});const v=N();if("allow"!==v.status)throw D(v);const E=F(s);if(E)return i?p():await d(s,"grant_missing",{code:E});const m={count:u.keys.length,syncedBeforeRead:y.syncedBeforeRead,stalenessMs:null===y.status.lastSyncAt?null:c.now()-Date.parse(y.status.lastSyncAt),...y.syncError?{syncError:y.syncError}:{}};return t.verify&&!n?await async function(e,r,n,i){const s=ve(t.prefixes,e.listPath)??null;try{const t=await ke(e.network(),e.signal);if(e.signal.aborted)return de("list",e.listPath,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const a=N();if("allow"!==a.status)return de("list",e.listPath,s,"network","consent_expired"===a.status?"grant_expired":"replica_gated",t.ok?"found":"error",n,{code:"consent_expired"===a.status?a.code:"REPLICA_GATED"}),t;const o=null===s?void 0:F(s);if(o)return de("list",e.listPath,s,"network","grant_missing",t.ok?"found":"error",n,{code:o}),t;if(!t.ok)return de("list",e.listPath,s,"replica","hit","found",n,{...i,code:t.error.code,verify:"error"}),te(r);const c=new Set(r.keys),u=new Set(t.data.keys),d=r.keys.filter(e=>!u.has(e)),p=t.data.keys.filter(e=>!c.has(e)),f=0===d.length&&0===p.length,y=f&&r.keys.every((e,r)=>e===t.data.keys[r]),h=y?"match":"diverged";return f&&y||l({type:"replication.divergence",op:"list",space:e.space,key:e.listPath,replica:s??"",kind:f?"order":"keys",...f?{}:{localOnly:d,networkOnly:p},stalenessMs:"number"==typeof i.stalenessMs?i.stalenessMs:null}),de("list",e.listPath,s,"replica","hit","found",n,{...i,verify:h}),te(r)}catch(t){if(e.signal.aborted)return de("list",e.listPath,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const a=N();if("allow"!==a.status)return de("list",e.listPath,s,"network","consent_expired"===a.status?"grant_expired":"replica_gated","error",n,{code:"consent_expired"===a.status?a.code:"REPLICA_GATED"}),re(ae("kv",t));const o=null===s?void 0:F(s);return o?(de("list",e.listPath,s,"network","grant_missing","error",n,{code:o}),re(ae("kv",t))):(de("list",e.listPath,s,"replica","hit","found",n,{...i,code:Ie(t),verify:"error"}),te(r))}}(e,u,r,m):(de("list",e.listPath,s,"replica","hit","found",r,m),te(u))}catch(t){if(a)throw t;if(e.signal.aborted)return Ne(e.signal);const r=Ie(t);if("CONSENT_EXPIRED"===r&&x(),U(s,t),n&&i)return p();const o="CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):Z(r);return d(s,o,{code:r})}},write:async function(e){const t=e.entries.flatMap(t=>void 0!==L(t.path)?[{key:t.path,op:"delete"===e.op?"delete":"put"}]:[]);if(0===t.length)return e.network();if("allow"!==N().status)return e.network();if(await Ee(),"allow"!==N().status)return e.network();const r=globalThis.crypto?.randomUUID?.()??`${c.now()}-${Math.random()}`;try{await o.update(e=>function(e,t,r,n){const i=r.map(({key:r,op:i})=>({opId:t,seq:++e.seq,key:r,op:i,state:"in_flight",epoch:null,at:n,settledAt:null}));return e.records.push(...i),i}(e,r,t,Pe(c.now())))}catch(t){return"REPLICA_GATED"===Ie(t)||"CONSENT_EXPIRED"===Ie(t)||"allow"!==N().status?e.network():re(ne("KV_WRITE_FAILED","Unable to persist pending KV write; request was not dispatched","kv",{cause:t instanceof Error?t:void 0,meta:{replication:"pending_store_unavailable",requestDispatched:!1}}))}const n=c.now();let i;try{i=await e.network()}catch(e){const t=ae("kv",e);i=re({...t,meta:{...t.meta,requestMayHaveDispatched:!0}})}const s=function(e,t,r={}){if(t.ok)return"committed";const{code:n,meta:i}=t.error;if("delete"===e&&n===ee)return r.conditional?"failed":"committed";if(!1===i?.requestMayHaveDispatched||oe.has(n)||"NODE_BUSY"===n)return"failed";const s=i?.status;return"batch-unconfirmed"!==i?.outcome&&"number"==typeof s&&s>=400&&s<500?"failed":"ambiguous"}(e.op,i,{conditional:!0===e.conditional});let a;try{await o.update(e=>function(e,t,r,n,i){if("failed"===r)return void(e.records=e.records.filter(e=>e.opId!==t));const s=e.records.filter(e=>e.opId===t&&"in_flight"===e.state);if("committed"===r&&s.length>0){const t=++e.committedEpoch;for(const e of s)e.state="committed",e.epoch=t,e.settledAt=n;return}for(const e of s)e.state="ambiguous",e.settledAt=n,i&&(e.code=i)}(e,r,s,Pe(c.now()),i.ok?void 0:i.error.code))}catch(e){a=e}l({type:"replication.write",space:e.space,op:e.op,keys:t.map(e=>e.key),outcome:s,...i.ok?{}:{code:i.error.code},latencyMs:c.now()-n});const u=await o.read().catch(()=>{}),d=u?le(u,"",c.now()):[];return"ambiguous"===s&&l({type:"replication.state",space:e.space,state:"pinned",count:d.length,keys:d.map(e=>e.key)}),a&&l({type:"replication.state",space:e.space,state:"pending_store_error",code:"STORAGE_ERROR"}),i},observeNetworkRequested:we,observeConsentExpired:function(t){e.stamp&&t.incarnation===e.stamp.incarnation&&t.lifecycleEpoch===e.stamp.lifecycleEpoch&&C()&&l({type:"replication.lifecycle",action:"denied",reason:"consent_expired"})},status:async function(){const r=N();if("allow"!==r.status)return Ce(r);let l;try{l=o.readExisting?await o.readExisting():await o.read()}catch(e){const t=N();if("allow"!==t.status)return Ce(t);throw e}const f=N();if("allow"!==f.status)return Ce(f);const h=l??ce(i),g=await Promise.all(t.prefixes.map(async r=>{"/"!==r||void 0===e.nodeFeatures||e.nodeFeatures.includes("kv-sync-root")||q(r);const o=h.records.filter(e=>W(r,e.key)),l=u.get(r);let f;if(l?.handle)try{f=await l.handle.status()}catch{}let g={missing:!1};if(f||l?.opening||l?.authorityRevoked||(g=await async function(r){if(!n.inspectStatus||p||y)return{missing:!1};const o=a.sessionGrant(r),l="refused"in o?void 0:o.device,u={identity:i,space:s.space,prefix:r,allowSecrets:t.allowSecrets,...l?{device:l}:{},...e.fetch?{fetch:e.fetch}:{}},f=new AbortController,h=Promise.resolve().then(()=>n.inspectStatus(u,{signal:f.signal})),g=h.then(()=>{},()=>{}),v={abort:f,settled:g};d.add(v),g.then(()=>d.delete(v));let E=()=>{};const m=new Promise(e=>{E=c.setTimeout(()=>{f.abort(Object.assign(new Error("Replica status inspection timed out"),{code:"STATUS_TIMEOUT"})),e({timedOut:!0})},Ae)});try{const e=await Promise.race([h.then(e=>({local:e})),m]);return"timedOut"in e?{missing:!1,errorCode:"STATUS_TIMEOUT"}:{missing:void 0===e.local,...e.local?{local:e.local}:{}}}catch(e){return{missing:!1,errorCode:Ie(e)}}finally{E()}}(r)),f??(f=g.local),g.missing&&!l?.reason&&!l?.authorityRevoked&&!l?.opening&&!p)return;const v=f&&!("redacted"in f)?f:void 0,E=!0===l?.authorityRevoked||"revoked"===v?.authority.state,m=p?"closed":E?"revoked":"REPLICATION_ROOT_UNSUPPORTED"===l?.lastError||"grant_expired"===l?.reason?"unavailable":"grant_missing"===l?.reason?"grant_missing":"complete"===v?.coverage&&"valid"===v.authority.state?"ready":l?.reason||g.errorCode?"unavailable":"idle";return{prefix:r,state:m,...l?.reason?{reason:l.reason}:g.errorCode?{reason:"replica_unavailable"}:{},...g.errorCode??l?.lastError?{errorCode:g.errorCode??l?.lastError}:{},...f??{},...E?{authority:{state:"revoked",expiresAt:v?.authority.expiresAt??null}}:{},pending:{inFlight:o.filter(e=>"in_flight"===e.state).length,committed:o.filter(e=>"committed"===e.state).length,ambiguous:o.filter(e=>"ambiguous"===e.state).length},pinned:le(h,r,c.now()),lagMs:v?.lastSyncAt?c.now()-Date.parse(v.lastSyncAt):null}})),v=N();return"allow"!==v.status?Ce(v):g.filter(e=>void 0!==e)},sync:async function(e){const r=void 0!==e?.prefix?t.prefixes.filter(t=>t===e.prefix):t.prefixes;await Promise.all(r.map(t=>z(t,"manual",e?.signal).then(()=>{})))},purge:function(e){var r;f=!0,y=!0,A?.(),A=void 0;const p=d.size>0,h=Oe();for(const e of u.values())e.timer?.(),e.timer=void 0,e.renewalTimer?.(),e.renewalTimer=void 0,e.syncContext&&((r=e.syncContext).abortCause??(r.abortCause="purge")),e.abort?.abort(),e.mintAbort?.abort();return Promise.resolve().then(async()=>{const r={purged:[],failed:[]},d=e?.timeoutMs??5e3,f=async e=>{let t=()=>{};const r=new Promise((e,r)=>{t=c.setTimeout(()=>r(Object.assign(new Error("Replication cleanup timed out"),{code:"TIMEOUT"})),d)});try{return await Promise.race([e,r])}finally{t()}},y=Promise.all([...[...u.values()].flatMap(e=>[e.opening?.catch(()=>{}),e.sync?.catch(()=>{}),e.renewing?.catch(()=>{}),e.handle?.close().catch(()=>{})]),...p?[h]:[]]);let g;try{await f(y)}catch(e){g=Ie(e)}const E=t.prefixes.map(async e=>{try{if(g)throw Object.assign(new Error("Replica cleanup did not settle before purge"),{code:g});const t=a.sessionGrant(e),c=u.get(e)?.handle?.deviceDid??("refused"in t?void 0:t.device.did);await f(n.purge({identity:i,space:s.space,prefix:e,...c?{sessionDeviceDid:c}:{}})),await o.update(t=>function(e,t){const r=e.records.length;return e.records=e.records.filter(e=>!W(t,e.key)),r-e.records.length}(t,e)),u.delete(e),v.delete(e),r.purged.push(e),l({type:"replication.state",space:s.space,replica:e,state:"purged"})}catch(t){const n=Ie(t);r.failed.push({prefix:e,code:n}),l({type:"replication.state",space:s.space,replica:e,state:"purge_failed",code:n})}});return await Promise.all(E),r}).finally(()=>{y=!1})},clearPending:async function(){const e=await o.update(e=>function(e,t){const r=e.records.length;return e.records=e.records.filter(e=>"committed"===e.state||"in_flight"===e.state&&t-Date.parse(e.at)<=6e5),r-e.records.length}(e,c.now()));return l({type:"replication.state",space:s.space,state:"pending_cleared",count:e}),e},close:async function(){var e;if(p)return;p=!0,A?.(),A=void 0;const t=d.size>0,r=Oe();for(const[t,r]of u)r.timer?.(),r.timer=void 0,r.renewalTimer?.(),r.renewalTimer=void 0,r.mintAbort?.abort(),r.syncContext&&((e=r.syncContext).abortCause??(e.abortCause="close")),r.abort?.abort(),l({type:"replication.state",space:s.space,replica:t,state:"closed"});const n=Promise.all([...[...u.values()].map(async e=>{await(e.opening?.catch(()=>{})),await(e.renewing?.catch(()=>{})),await(e.sync?.catch(()=>{})),await(e.handle?.close().catch(()=>{}))}),...t?[r]:[]]);let i=()=>{},a=!1;n.then(()=>{a=!0,i()},()=>{a=!0,i()});const o=new Promise(e=>{queueMicrotask(()=>{a||(i=c.setTimeout(e,Te))})});try{await Promise.race([n,o])}finally{i()}}}}function Se(e){return ae("kv",e.reason).code===J||"object"==typeof e.reason&&null!==e.reason&&"code"in e.reason&&e.reason.code===J?J:Q}function Ne(e){const t=Se(e);return re(ne(t,t===J?"KV request timed out":"KV request was aborted","kv"))}function Ce(e){const t=$(e),r=B(t);let n=ce(t),i=Promise.resolve();return{identity:t,durable:!1,read:async()=>structuredClone(n),async update(e){let t,s;const a=new Promise((e,r)=>{t=e,s=r}),o=i.then(()=>{try{if(B(n.identity)!==r)throw Object.assign(new Error("Pending-store identity mismatch"),{code:"STORAGE_ERROR"});const i=structuredClone(n),s=e(i);n=i,t(s)}catch(e){s(e)}});return i=o.then(()=>{},()=>{}),a}}}}},n={};function i(e){var t=n[e];if(void 0!==t)return t.exports;var s=n[e]={exports:{}};return r[e](s,s.exports,i),s.exports}i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(r,n){if(1&n&&(r=this(r)),8&n)return r;if("object"==typeof r&&r){if(4&n&&r.__esModule)return r;if(16&n&&"function"==typeof r.then)return r}var s=Object.create(null);i.r(s);var a={};e=e||[null,t({}),t([]),t(t)];for(var o=2&n&&r;("object"==typeof o||"function"==typeof o)&&!~e.indexOf(o);o=t(o))Object.getOwnPropertyNames(o).forEach(e=>a[e]=()=>r[e]);return a.default=()=>r,i.d(s,a),s},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};i.r(s),i.d(s,{browserReplicaPlugin:()=>l,loadIndexedDbReplicaStorage:()=>o});var a=i(727);async function o(){const{indexedDbReplicaStorage:e}=await Promise.resolve().then(i.bind(i,913));return e}const c=i(60).assertValidReplicationConfig,l=Object.freeze({validateConfig:c,loaders:Object.freeze({validateConfig:c,runtime:()=>Promise.resolve().then(i.bind(i,230)),authority:()=>Promise.resolve().then(i.bind(i,60)),gatedNetwork:()=>Promise.resolve().then(i.t.bind(i,284,23)),gate:()=>Promise.resolve().then(i.bind(i,435))}),recover:async function(e,t){const r=e.storage,n="indexeddb"===r.kind?r.lifecycle:void 0;if("indexeddb"!==n?.kind)return e;const i=(t,r)=>{try{const n={type:"replication.lifecycle",at:(new Date).toISOString(),action:"unguarded",reason:"startup",gate:"gate_unavailable",code:t};void 0!==r&&(n.remaining=r),e.onEvent?.(n)}catch{}},s=e=>null!==e&&0===e.failed.length&&0===e.remaining,o=(e,t)=>{let r;return Promise.race([e.then(()=>{},()=>{}),new Promise(e=>{r=setTimeout(()=>{t?.abort(),e()},3e3)})]).finally(()=>clearTimeout(r))};let c,l=!1,u=0,d=0,p=void 0===t?"wallet_provider_required":"gate_unavailable";const f=async e=>{const t=await n.recover(e);return l=s(t),l||(c=void 0,u++),t},y=()=>{const e=new AbortController;return o(f({signal:e.signal}),e)};let h;const g=e=>{const t=e().catch(()=>{}).finally(()=>{h===t&&(h=void 0)});return h=t,t},v=new AbortController;let E,m=!1;const w=(async()=>n.recover({signal:v.signal}))().catch(()=>null).then(e=>E=e);g(async()=>{const e=await w;m&&(s(e)?await y():i(e?.failed[0]?.code??(e?"RECOVERY_INCOMPLETE":"STORAGE_ERROR"),e?.remaining))}),await o(w,v),m=void 0===E,E&&(l=s(E)),l||i(E?.failed[0]?.code??(m?"RECOVERY_TIMEOUT":"STORAGE_ERROR"),E?.remaining);const _=()=>Object.assign(new Error("Replica wallet or startup recovery is unavailable."),{code:"REPLICA_GATED",gate:l?p:"gate_unavailable"}),b=()=>Promise.reject(_()),R=()=>{throw _()},T=async e=>{const r=(0,a.__replicaParsePkhDid)(e)?.address,n=await(t?.getConnectedAddress().catch(()=>{}));return p=void 0===t?"wallet_provider_required":n?"principal_mismatch":"gate_unavailable",void 0!==r&&void 0!==n&&r.toLowerCase()===n.toLowerCase()},A=async()=>{const e=c;if(!l||!e)throw _();if(!await T(e)||c!==e)throw c=void 0,_()},P=async(e,t)=>{const r=++u;if(c=void 0,!l&&h&&await o(h),!l&&!h&&d<2&&(d++,await g(y)),!l||!await T(e)||r!==u)throw _();const n=await t();if(r!==u)throw _();if(c=e,await A(),r!==u)throw _();return n},I=(e,t,r)=>{if(r.has(t))return r.get(t);const n=Reflect.get(e,t,e);if("function"!=typeof n)return n;const i=n.bind(e);return r.set(t,i),i},k=new Map,O=new Proxy(n,{get(e,t){if("recover"===t)return f;if("establishSessionStamp"===t)return(...t)=>P(t[0],()=>e.establishSessionStamp(...t));if("restoreSessionStamp"===t)return(...t)=>P(t[0],()=>e.restoreSessionStamp(...t));if("deny"===t)return(...t)=>(u++,c=void 0,e.deny(...t));if(!l||!c){if("activationAllowed"===t)return()=>Promise.resolve(!1);if("checkDelivery"===t)return()=>({status:"gated",gate:l?p:"gate_unavailable"});if("deliverable"===t)return()=>!1;if("consentDeadline"===t)return()=>null}return I(e,t,k)}}),S=new Map,N=new Proxy(r,{get(e,t){if("lifecycle"===t)return O;if("open"===t)return async(...t)=>{await A();const r=await e.open(...t);try{await A()}catch(e){throw await r.close().catch(()=>{}),e}const n=new Map,i=async(...e)=>{await A();const t=await r.get(...e);return await A(),t},s=async(...e)=>{await A();const t=await r.list(...e);return await A(),t};return new Proxy(r,{get:(e,t)=>"get"===t?i:"list"===t?s:I(e,t,n)})};if(!l||!c){if("inspectStatus"===t)return b;if("pendingWrites"===t)return R}return I(e,t,S)}});return{...e,storage:N}}});module.exports=s})();
|