@tinycloud/web-sdk 3.12.0-beta.9 โ 3.13.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -8
- package/dist/adapters/BrowserSessionStorage.d.ts +13 -3
- package/dist/adapters/BrowserWasmBindings.d.ts +2 -0
- package/dist/delegations-issued.cjs +2 -1
- package/dist/delegations-issued.cjs.LICENSE.txt +5 -0
- package/dist/delegations-issued.mjs +2 -1
- package/dist/delegations-issued.mjs.LICENSE.txt +5 -0
- package/dist/delegations-renewal-entry.d.ts +3 -0
- package/dist/delegations-renewal.cjs +2 -0
- package/dist/delegations-renewal.cjs.LICENSE.txt +21 -0
- package/dist/delegations-renewal.mjs +2 -0
- package/dist/delegations-renewal.mjs.LICENSE.txt +21 -0
- package/dist/encryption-keys.cjs +1 -1
- package/dist/encryption-keys.cjs.LICENSE.txt +4 -0
- package/dist/encryption-keys.mjs +1 -1
- package/dist/encryption-keys.mjs.LICENSE.txt +4 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.LICENSE.txt +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.LICENSE.txt +2 -0
- package/dist/modals.cjs +1 -1
- package/dist/modals.mjs +1 -1
- package/dist/modules/Storage/tinycloud/module.d.ts +1 -0
- package/dist/modules/Storage/tinycloud/types.schema.d.ts +10 -10
- package/dist/modules/requestPermissionsCore.d.ts +0 -7
- package/dist/modules/restoreAccount.d.ts +13 -0
- package/dist/modules/runtimeGrantPersistence.d.ts +4 -2
- package/dist/modules/tcw.d.ts +27 -6
- package/dist/panel.cjs +1 -1
- package/dist/panel.mjs +1 -1
- package/dist/registry-verdict-cache-entry.d.ts +2 -0
- package/dist/registry-verdict-cache.cjs +1 -0
- package/dist/registry-verdict-cache.mjs +1 -0
- package/dist/replica.cjs +1 -1
- package/dist/replica.mjs +1 -1
- package/dist/share-placement-core-bridge.d.ts +2 -0
- package/dist/share-placement-core.d.ts +13 -0
- package/dist/share-placement-entry.d.ts +2 -0
- package/dist/share-placement.cjs +2 -0
- package/dist/share-placement.cjs.LICENSE.txt +3 -0
- package/dist/share-placement.mjs +2 -0
- package/dist/share-placement.mjs.LICENSE.txt +3 -0
- package/dist/space-hosting-entry.d.ts +1 -1
- package/dist/space-hosting.cjs +1 -1
- package/dist/space-hosting.mjs +1 -1
- package/dist/ui/pending.d.ts +1 -1
- package/dist/ui/strings.d.ts +2 -0
- package/package.json +7 -7
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{createRegistryVerdictCache:()=>xe});var r=Object.defineProperty,n=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},a=(e,t,n)=>((e,t,n)=>t in e?r(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);function i(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}n({},{base10:()=>b}),new Uint8Array(0);var o=class{constructor(e,t,r){a(this,"name"),a(this,"prefix"),a(this,"baseEncode"),this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},s=class{constructor(e,t,r){a(this,"name"),a(this,"prefix"),a(this,"baseDecode"),a(this,"prefixCodePoint"),this.name=e,this.prefix=t;const n=t.codePointAt(0);if(void 0===n)throw new Error("Invalid prefix character");this.prefixCodePoint=n,this.baseDecode=r}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return h(this,e)}},c=class{constructor(e){a(this,"decoders"),this.decoders=e}or(e){return h(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function h(e,t){return new c({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var d=class{constructor(e,t,r,n){a(this,"name"),a(this,"prefix"),a(this,"baseEncode"),a(this,"baseDecode"),a(this,"encoder"),a(this,"decoder"),this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new o(e,t,r),this.decoder=new s(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function u({name:e,prefix:t,encode:r,decode:n}){return new d(e,t,r,n)}function f({name:e,prefix:t,alphabet:r}){const{encode:n,decode:a}=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var a=0;a<e.length;a++){var i=e.charAt(a),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=a}var s=e.length,c=e.charAt(0),h=Math.log(s)/Math.log(256),d=Math.log(256)/Math.log(s);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,a=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*h+1>>>0,o=new Uint8Array(i);e[t];){var d=r[e.charCodeAt(t)];if(255===d)return;for(var u=0,f=i-1;(0!==d||u<a)&&-1!==f;f--,u++)d+=s*o[f]>>>0,o[f]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");a=u,t++}if(" "!==e[t]){for(var p=i-a;p!==i&&0===o[p];)p++;for(var b=new Uint8Array(n+(i-p)),l=n;p!==i;)b[l++]=o[p++];return b}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,a=0,i=t.length;a!==i&&0===t[a];)a++,r++;for(var o=(i-a)*d+1>>>0,h=new Uint8Array(o);a!==i;){for(var u=t[a],f=0,p=o-1;(0!==u||f<n)&&-1!==p;p--,f++)u+=256*h[p]>>>0,h[p]=u%s>>>0,u=u/s>>>0;if(0!==u)throw new Error("Non-zero carry");n=f,a++}for(var b=o-n;b!==o&&0===h[b];)b++;for(var l=c.repeat(r);b<o;++b)l+=e.charAt(h[b]);return l},decodeUnsafe:u,decode:function(e){var r=u(e);if(r)return r;throw new Error(`Non-${t} character`)}}}(r,e);return u({prefix:t,name:e,encode:n,decode:e=>i(a(e))})}function p({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const a=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return u({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],a=(1<<r)-1;let i="",o=0,s=0;for(let n=0;n<e.length;++n)for(s=s<<8|e[n],o+=8;o>r;)o-=r,i+=t[a&s>>o];if(0!==o&&(i+=t[a&s<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){let a=e.length;for(;"="===e[a-1];)--a;const i=new Uint8Array(a*r/8|0);let o=0,s=0,c=0;for(let h=0;h<a;++h){const a=t[e[h]];if(void 0===a)throw new SyntaxError(`Non-${n} character`);s=s<<r|a,o+=r,o>=8&&(o-=8,i[c++]=255&s>>o)}if(o>=r||255&s<<8-o)throw new SyntaxError("Unexpected end of data");return i}(t,a,r,e)})}var b=f({prefix:"9",name:"base10",alphabet:"0123456789"});n({},{base16:()=>l,base16upper:()=>g});var l=p({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),g=p({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});n({},{base2:()=>w});var w=p({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});n({},{base256emoji:()=>v});var y=Array.from("๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ"),m=y.reduce((e,t,r)=>(e[r]=t,e),[]),x=y.reduce((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]),v=u({prefix:"๐",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+m[t],"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=x[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}});n({},{base32:()=>A,base32hex:()=>C,base32hexpad:()=>S,base32hexpadupper:()=>D,base32hexupper:()=>L,base32pad:()=>U,base32padupper:()=>P,base32upper:()=>E,base32z:()=>M});var A=p({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),E=p({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),U=p({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),P=p({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),C=p({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),L=p({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),S=p({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),D=p({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),M=p({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});n({},{base36:()=>k,base36upper:()=>T});var k=f({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),T=f({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});n({},{base58btc:()=>q,base58flickr:()=>j});var q=f({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),j=f({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});n({},{base64:()=>$,base64pad:()=>O,base64url:()=>I,base64urlpad:()=>N});var $=p({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),O=p({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),I=p({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),N=p({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});n({},{base8:()=>R});var R=p({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});n({},{identity:()=>z});var z=u({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});n((new TextEncoder,new TextDecoder,{}),{identity:()=>se});var B=128,V=-128,F=Math.pow(2,31),J=128,H=127,Z=Math.pow(2,7),K=Math.pow(2,14),G=Math.pow(2,21),Q=Math.pow(2,28),W=Math.pow(2,35),Y=Math.pow(2,42),X=Math.pow(2,49),_=Math.pow(2,56),ee=Math.pow(2,63),te={encode:function e(t,r,n){r=r||[];for(var a=n=n||0;t>=F;)r[n++]=255&t|B,t/=128;for(;t&V;)r[n++]=255&t|B,t>>>=7;return r[n]=0|t,e.bytes=n-a+1,r},decode:function e(t,r){var n,a=0,i=0,o=r=r||0,s=t.length;do{if(o>=s)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],a+=i<28?(n&H)<<i:(n&H)*Math.pow(2,i),i+=7}while(n>=J);return e.bytes=o-r,a},encodingLength:function(e){return e<Z?1:e<K?2:e<G?3:e<Q?4:e<W?5:e<Y?6:e<X?7:e<_?8:e<ee?9:10}};function re(e,t,r=0){return te.encode(e,t,r),t}function ne(e){return te.encodingLength(e)}function ae(e,t){const r=t.byteLength,n=ne(e),a=n+ne(r),i=new Uint8Array(a+r);return re(e,i,0),re(r,i,n),i.set(t,a),new ie(e,r,t,i)}var ie=class{constructor(e,t,r,n){a(this,"code"),a(this,"size"),a(this,"digest"),a(this,"bytes"),this.code=e,this.size=t,this.digest=r,this.bytes=n}},oe=i,se={code:0,name:"identity",encode:oe,digest:function(e,t){if(null!=t?.truncate&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return ae(0,oe(e))}};function ce({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:a}){return new he(e,t,r,n,a)}n({},{sha256:()=>fe,sha512:()=>pe});var he=class{constructor(e,t,r,n,i){a(this,"name"),a(this,"code"),a(this,"encode"),a(this,"minDigestLength"),a(this,"maxDigestLength"),this.name=e,this.code=t,this.encode=r,this.minDigestLength=n??20,this.maxDigestLength=i}digest(e,t){if(null!=t?.truncate){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(null!=this.maxDigestLength&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?de(r,this.code,t?.truncate):r.then(e=>de(e,this.code,t?.truncate))}throw Error("Unknown type, must be binary type")}};function de(e,t,r){if(null!=r&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return ae(t,e)}function ue(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var fe=ce({name:"sha2-256",code:18,encode:ue("SHA-256")}),pe=ce({name:"sha2-512",code:19,encode:ue("SHA-512")});Symbol.toStringTag;var be="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])",le=(new RegExp(`^${be}(\\.${be}){3}$`),"[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?");new RegExp(`^${le}(\\.${le})*$`);var ge=6e4,we=6e4,ye=256;function me(e){const t=[["?","query"],["#","fragment"],["@","credentials"],["\\","backslash"]].filter(([t])=>e.includes(t)).map(([,e])=>e);if(/\s/.test(e)&&t.push("whitespace"),t.length)throw new TypeError(`A registry URL used with a verdict cache must not contain a query, fragment, credentials, backslash or whitespace (found: ${t.join(", ")})`);try{const t=new URL(e);return t.origin+t.pathname.replace(/\/$/,"")}catch{return e}}function xe(){return function(e={}){const t=e.now??(()=>performance.now()),r=new Map,n=(e,t)=>JSON.stringify([me(e),t]);return{async get(a,i){const o=n(a.registryUrl,a.subject);if("absent-reads"===e.mode&&!0!==a.dataRead)return r.delete(o),i();const s=r.get(o);if(s&&t()<s.expiresAt){const t=await s.verdict;if("unavailable"===t.status||("registered"!==t.status||"absent-reads"!==e.mode)&&await async function(e,t){try{const n=(r=e.subject).startsWith("did:pkh:")?r.slice(r.lastIndexOf(":")+1):r,a=await async function(e,t){if(!e)return;if(e.getRegistration)return e.getRegistration(t);const r=await e.get(t);return void 0===r?void 0:{sequence:r,kind:"unknown"}}(e.sequenceStore,n),i=await(e.cacheStore?.get(n));return"unregistered"===t.status?void 0===a&&void 0===i&&!(e.cacheStore&&await e.cacheStore.getRevision(n)>0):!("registered"!==t.status||t.offline||e.sequenceStore&&(!a||"legacy-v1"===a.kind||a.sequence!==t.sequence)||e.cacheStore&&i?.sequence!==t.sequence)}catch{return!1}var r}(a,t))return t;r.get(o)===s&&r.delete(o)}const c={verdict:i(),expiresAt:Number.POSITIVE_INFINITY};return((e,n)=>{const a=t();for(const[e,t]of r)t.expiresAt<=a&&r.delete(e);for(;r.size>=ye;)r.delete(r.keys().next().value);r.set(e,n)})(o,c),c.verdict.then(n=>{if(r.get(o)!==c)return;const a="unavailable"===n.status||n.offline?void 0:"registered"===n.status?"absent-reads"===e.mode?void 0:ge:we;void 0===a?r.delete(o):(c.settled=n,c.expiresAt=t()+a)},()=>{r.get(o)===c&&r.delete(o)}),c.verdict},invalidate(e,t){/[?#@\\\s]/.test(e)||r.delete(n(e,t))}}}({mode:"absent-reads"})}module.exports=t})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.defineProperty,t=(t,r)=>{for(var n in r)e(t,n,{get:r[n],enumerable:!0})},r=(t,r,n)=>((t,r,n)=>r in t?e(t,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[r]=n)(t,"symbol"!=typeof r?r+"":r,n);function n(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}t({},{base10:()=>f}),new Uint8Array(0);var a=class{constructor(e,t,n){r(this,"name"),r(this,"prefix"),r(this,"baseEncode"),this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},i=class{constructor(e,t,n){r(this,"name"),r(this,"prefix"),r(this,"baseDecode"),r(this,"prefixCodePoint"),this.name=e,this.prefix=t;const a=t.codePointAt(0);if(void 0===a)throw new Error("Invalid prefix character");this.prefixCodePoint=a,this.baseDecode=n}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return s(this,e)}},o=class{constructor(e){r(this,"decoders"),this.decoders=e}or(e){return s(this,e)}decode(e){const t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function s(e,t){return new o({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var c=class{constructor(e,t,n,o){r(this,"name"),r(this,"prefix"),r(this,"baseEncode"),r(this,"baseDecode"),r(this,"encoder"),r(this,"decoder"),this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new a(e,t,n),this.decoder=new i(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function h({name:e,prefix:t,encode:r,decode:n}){return new c(e,t,r,n)}function d({name:e,prefix:t,alphabet:r}){const{encode:a,decode:i}=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var a=0;a<e.length;a++){var i=e.charAt(a),o=i.charCodeAt(0);if(255!==r[o])throw new TypeError(i+" is ambiguous");r[o]=a}var s=e.length,c=e.charAt(0),h=Math.log(s)/Math.log(256),d=Math.log(256)/Math.log(s);function u(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,a=0;e[t]===c;)n++,t++;for(var i=(e.length-t)*h+1>>>0,o=new Uint8Array(i);e[t];){var d=r[e.charCodeAt(t)];if(255===d)return;for(var u=0,f=i-1;(0!==d||u<a)&&-1!==f;f--,u++)d+=s*o[f]>>>0,o[f]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");a=u,t++}if(" "!==e[t]){for(var p=i-a;p!==i&&0===o[p];)p++;for(var b=new Uint8Array(n+(i-p)),l=n;p!==i;)b[l++]=o[p++];return b}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,a=0,i=t.length;a!==i&&0===t[a];)a++,r++;for(var o=(i-a)*d+1>>>0,h=new Uint8Array(o);a!==i;){for(var u=t[a],f=0,p=o-1;(0!==u||f<n)&&-1!==p;p--,f++)u+=256*h[p]>>>0,h[p]=u%s>>>0,u=u/s>>>0;if(0!==u)throw new Error("Non-zero carry");n=f,a++}for(var b=o-n;b!==o&&0===h[b];)b++;for(var l=c.repeat(r);b<o;++b)l+=e.charAt(h[b]);return l},decodeUnsafe:u,decode:function(e){var r=u(e);if(r)return r;throw new Error(`Non-${t} character`)}}}(r,e);return h({prefix:t,name:e,encode:a,decode:e=>n(i(e))})}function u({name:e,prefix:t,bitsPerChar:r,alphabet:n}){const a=function(e){const t={};for(let r=0;r<e.length;++r)t[e[r]]=r;return t}(n);return h({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],a=(1<<r)-1;let i="",o=0,s=0;for(let n=0;n<e.length;++n)for(s=s<<8|e[n],o+=8;o>r;)o-=r,i+=t[a&s>>o];if(0!==o&&(i+=t[a&s<<r-o]),n)for(;i.length*r&7;)i+="=";return i}(e,n,r),decode:t=>function(e,t,r,n){let a=e.length;for(;"="===e[a-1];)--a;const i=new Uint8Array(a*r/8|0);let o=0,s=0,c=0;for(let h=0;h<a;++h){const a=t[e[h]];if(void 0===a)throw new SyntaxError(`Non-${n} character`);s=s<<r|a,o+=r,o>=8&&(o-=8,i[c++]=255&s>>o)}if(o>=r||255&s<<8-o)throw new SyntaxError("Unexpected end of data");return i}(t,a,r,e)})}var f=d({prefix:"9",name:"base10",alphabet:"0123456789"});t({},{base16:()=>p,base16upper:()=>b});var p=u({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),b=u({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});t({},{base2:()=>l});var l=u({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});t({},{base256emoji:()=>m});var g=Array.from("๐๐ชโ๐ฐ๐๐๐๐๐๐๐๐๐๐๐๐๐โ๐ป๐ฅ๐พ๐ฟ๐โค๐๐คฃ๐๐๐๐ญ๐๐๐
๐๐๐ฅ๐ฅฐ๐๐๐๐ข๐ค๐๐๐ช๐โบ๐๐ค๐๐๐๐๐น๐คฆ๐๐โโจ๐คท๐ฑ๐๐ธ๐๐๐๐๐๐๐๐๐คฉ๐๐๐ค๐๐ฏ๐๐๐ถ๐๐คญโฃ๐๐๐๐ช๐๐ฅ๐๐๐ฉ๐ก๐คช๐๐ฅณ๐ฅ๐คค๐๐๐ณโ๐๐๐ด๐๐ฌ๐๐๐ท๐ป๐โญโ
๐ฅบ๐๐๐ค๐ฆโ๐ฃ๐๐โน๐๐๐ โ๐๐บ๐๐ป๐๐๐๐๐น๐ฃ๐ซ๐๐๐ต๐ค๐๐ด๐ค๐ผ๐ซโฝ๐คโ๐๐คซ๐๐ฎ๐๐ป๐๐ถ๐๐ฒ๐ฟ๐งก๐โก๐๐โโ๐๐ฐ๐คจ๐ถ๐ค๐ถ๐ฐ๐๐ข๐ค๐๐จ๐จ๐คฌโ๐๐บ๐ค๐๐๐ฑ๐๐ถ๐ฅดโถโกโ๐๐ธโฌ๐จ๐๐ฆ๐ท๐บโ ๐
๐๐ต๐๐คฒ๐ค ๐คง๐๐ต๐
๐ง๐พ๐๐๐ค๐๐คฏ๐ทโ๐ง๐ฏ๐๐๐ค๐๐โ๐ด๐ฃ๐ธ๐๐๐ฅ๐คข๐
๐ก๐ฉ๐๐ธ๐ป๐ค๐คฎ๐ผ๐ฅต๐ฉ๐๐๐ผ๐๐ฃ๐ฅ"),w=g.reduce((e,t,r)=>(e[r]=t,e),[]),y=g.reduce((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e},[]),m=h({prefix:"๐",name:"base256emoji",encode:function(e){return e.reduce((e,t)=>e+w[t],"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=y[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}});t({},{base32:()=>x,base32hex:()=>U,base32hexpad:()=>P,base32hexpadupper:()=>L,base32hexupper:()=>C,base32pad:()=>A,base32padupper:()=>E,base32upper:()=>v,base32z:()=>D});var x=u({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),v=u({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),A=u({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),E=u({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),U=u({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),C=u({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),P=u({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),L=u({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),D=u({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});t({},{base36:()=>M,base36upper:()=>S});var M=d({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),S=d({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});t({},{base58btc:()=>k,base58flickr:()=>q});var k=d({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),q=d({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});t({},{base64:()=>T,base64pad:()=>$,base64url:()=>I,base64urlpad:()=>N});var T=u({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$=u({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),I=u({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),N=u({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});t({},{base8:()=>R});var R=u({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});t({},{identity:()=>z});var z=h({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)});t((new TextEncoder,new TextDecoder,{}),{identity:()=>ie});var j=128,O=-128,B=Math.pow(2,31),V=128,F=127,J=Math.pow(2,7),H=Math.pow(2,14),Z=Math.pow(2,21),K=Math.pow(2,28),G=Math.pow(2,35),Q=Math.pow(2,42),W=Math.pow(2,49),Y=Math.pow(2,56),X=Math.pow(2,63),_={encode:function e(t,r,n){r=r||[];for(var a=n=n||0;t>=B;)r[n++]=255&t|j,t/=128;for(;t&O;)r[n++]=255&t|j,t>>>=7;return r[n]=0|t,e.bytes=n-a+1,r},decode:function e(t,r){var n,a=0,i=0,o=r=r||0,s=t.length;do{if(o>=s)throw e.bytes=0,new RangeError("Could not decode varint");n=t[o++],a+=i<28?(n&F)<<i:(n&F)*Math.pow(2,i),i+=7}while(n>=V);return e.bytes=o-r,a},encodingLength:function(e){return e<J?1:e<H?2:e<Z?3:e<K?4:e<G?5:e<Q?6:e<W?7:e<Y?8:e<X?9:10}};function ee(e,t,r=0){return _.encode(e,t,r),t}function te(e){return _.encodingLength(e)}function re(e,t){const r=t.byteLength,n=te(e),a=n+te(r),i=new Uint8Array(a+r);return ee(e,i,0),ee(r,i,n),i.set(t,a),new ne(e,r,t,i)}var ne=class{constructor(e,t,n,a){r(this,"code"),r(this,"size"),r(this,"digest"),r(this,"bytes"),this.code=e,this.size=t,this.digest=n,this.bytes=a}},ae=n,ie={code:0,name:"identity",encode:ae,digest:function(e,t){if(null!=t?.truncate&&t.truncate!==e.byteLength){if(t.truncate<0||t.truncate>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,t.truncate)}return re(0,ae(e))}};function oe({name:e,code:t,encode:r,minDigestLength:n,maxDigestLength:a}){return new se(e,t,r,n,a)}t({},{sha256:()=>de,sha512:()=>ue});var se=class{constructor(e,t,n,a,i){r(this,"name"),r(this,"code"),r(this,"encode"),r(this,"minDigestLength"),r(this,"maxDigestLength"),this.name=e,this.code=t,this.encode=n,this.minDigestLength=a??20,this.maxDigestLength=i}digest(e,t){if(null!=t?.truncate){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(null!=this.maxDigestLength&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ce(r,this.code,t?.truncate):r.then(e=>ce(e,this.code,t?.truncate))}throw Error("Unknown type, must be binary type")}};function ce(e,t,r){if(null!=r&&r!==e.byteLength){if(r>e.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${e.byteLength}`);e=e.subarray(0,r)}return re(t,e)}function he(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}var de=oe({name:"sha2-256",code:18,encode:he("SHA-256")}),ue=oe({name:"sha2-512",code:19,encode:he("SHA-512")});Symbol.toStringTag;var fe="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])",pe=(new RegExp(`^${fe}(\\.${fe}){3}$`),"[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?");function be(e){const t=[["?","query"],["#","fragment"],["@","credentials"],["\\","backslash"]].filter(([t])=>e.includes(t)).map(([,e])=>e);if(/\s/.test(e)&&t.push("whitespace"),t.length)throw new TypeError(`A registry URL used with a verdict cache must not contain a query, fragment, credentials, backslash or whitespace (found: ${t.join(", ")})`);try{const t=new URL(e);return t.origin+t.pathname.replace(/\/$/,"")}catch{return e}}function le(){return function(e={}){const t=e.now??(()=>performance.now()),r=new Map,n=(e,t)=>JSON.stringify([be(e),t]);return{async get(a,i){const o=n(a.registryUrl,a.subject);if("absent-reads"===e.mode&&!0!==a.dataRead)return r.delete(o),i();const s=r.get(o);if(s&&t()<s.expiresAt){const t=await s.verdict;if("unavailable"===t.status||("registered"!==t.status||"absent-reads"!==e.mode)&&await async function(e,t){try{const n=(r=e.subject).startsWith("did:pkh:")?r.slice(r.lastIndexOf(":")+1):r,a=await async function(e,t){if(!e)return;if(e.getRegistration)return e.getRegistration(t);const r=await e.get(t);return void 0===r?void 0:{sequence:r,kind:"unknown"}}(e.sequenceStore,n),i=await(e.cacheStore?.get(n));return"unregistered"===t.status?void 0===a&&void 0===i&&!(e.cacheStore&&await e.cacheStore.getRevision(n)>0):!("registered"!==t.status||t.offline||e.sequenceStore&&(!a||"legacy-v1"===a.kind||a.sequence!==t.sequence)||e.cacheStore&&i?.sequence!==t.sequence)}catch{return!1}var r}(a,t))return t;r.get(o)===s&&r.delete(o)}const c={verdict:i(),expiresAt:Number.POSITIVE_INFINITY};return((e,n)=>{const a=t();for(const[e,t]of r)t.expiresAt<=a&&r.delete(e);for(;r.size>=256;)r.delete(r.keys().next().value);r.set(e,n)})(o,c),c.verdict.then(n=>{if(r.get(o)!==c)return;const a="unavailable"===n.status||n.offline||"registered"===n.status&&"absent-reads"===e.mode?void 0:6e4;void 0===a?r.delete(o):(c.settled=n,c.expiresAt=t()+a)},()=>{r.get(o)===c&&r.delete(o)}),c.verdict},invalidate(e,t){/[?#@\\\s]/.test(e)||r.delete(n(e,t))}}}({mode:"absent-reads"})}new RegExp(`^${pe}(\\.${pe})*$`);export{le as createRegistryVerdictCache};
|
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 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})();
|
|
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,d=n.__replicaKV.SYNC,u="tinycloud.kv";function p(e,t,r){return(0,n.__replicaIsCapabilitySubset)([{service:u,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:u,space:e.primarySpaceId,path:"",actions:[l,d]}];for(const r of n)t.push({service:u,space:e.primarySpaceId,path:r,actions:[l,d]});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),d=i(l,o?.expiryMs);if("refused"in d)throw Object.assign(new Error(`replication authority refused the mint: ${d.refused}`),{refused:d.refused});if(o?.renewalOnly&&"session"!==d.path)throw Object.assign(new Error("replication renewal requires a session parent"),{refused:"NOT_COVERED"});a.throwIfAborted();const u=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:u.ucan,parentCid:d.parentCid,expiresAt:u.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 d=this.pending.get(l);const u=e.stamp;if(!d||d.stamp?.incarnation!==u?.incarnation||d.stamp?.lifecycleEpoch!==u?.lifecycleEpoch){const e=this.options.storage.pendingWrites?.(o,{stamp:u});if(!e&&this.options.storage.lifecycle)throw Object.assign(new Error("Gated replication requires a stamped pending store"),{code:"REPLICA_GATED",gate:"gate_unavailable"});d={stamp:u,store:e??a.createMemoryPendingStore(o)},this.pending.set(l,d)}const p=d.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:()=>z});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"},d=(o("duckdb"),o("capabilities")),u=(o("hooks"),o("encryption")),p=o("space"),f=n;["tinychat-4jq","share-2fz","tinycloud-secrets","openkey-tinycloud-demo"].map(e=>new RegExp(`^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)?${e}\\.pages\\.dev$`));var y="applications",h="account",g="applications/",v="secrets",E="default",m="public",w="agents",_="tinycloud.encryption",b=u.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:[d.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:[d.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 z(e,t){return"/"===t||!("secrets"!==e&&!e.endsWith(":secrets"))||"vault"===t.split("/",1)[0]}var H={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(H,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 de(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 ue=new TextEncoder,pe=new TextDecoder("utf-8",{fatal:!0});function fe(e,t){const r=ue.encode(e),n=ue.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=ue.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),d=new Map,u=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 d.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=d.get(e)??{};r.authorityRevoked=!0,r.reason="grant_revoked",r.lastError="GRANT_REVOKED",d.set(e,r)}function q(e){const t=d.get(e)??{},r="REPLICATION_ROOT_UNSUPPORTED"!==t.lastError;t.reason="replica_unavailable",t.lastError="REPLICATION_ROOT_UNSUPPORTED",d.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 u=N();if("allow"!==u.status)throw D(u);if(p||f)throw Object.assign(new Error("Replication controller is closed"),{code:"REPLICA_CLOSED"});let y=d.get(o);if(y?.handle)return y.handle;if(y?.opening)return y.opening;if(y??(y={}),d.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(z(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 d=N();if("allow"!==d.status)throw D(d);const u=!0===a.sessionOnly,g=a.sessionGrant(o),v="refused"in g?void 0:g,E=u?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&&!u&&(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=u||!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,u)&&(x.unconstrained&&(w=null!==m||u?"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||u)&&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&&(H(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=d.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 u=s+.75*(o-s),y=c.now();Number.isFinite(y)&&u<l&&!(y>u)&&(i.renewalTimer=c.setTimeout(()=>{i.renewalTimer=void 0,$(e,t).catch(()=>{})},Math.max(0,Math.floor(u)+1-y)))}async function $(e,t,r,n){const i=d.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:u}=s,y=k();if("number"!=typeof o||!Number.isFinite(o)||"number"!=typeof u||!Number.isFinite(u)||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:u,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>u&&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=d.get(e);!n||"background"!==r||p||f||(n.timer=c.setTimeout(()=>{n.timer=void 0,H(e,"interval").catch(()=>{}).finally(()=>B(e))},t.syncIntervalMs))}async function H(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 u=await V(t),p=d.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,u);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 d=await u.sync({signal:f.signal,syncStartEpoch:e}),p=N();if("allow"!==p.status)throw D(p);if("busy"===d.status)return l({type:"replication.sync",space:s.space,replica:t,trigger:r,outcome:"busy",durationMs:c.now()-g,lagMs:null}),d;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:d.pages,changes:d.changes,deleted:d.deleted,fetched:d.fetched,contentMissing:d.contentMissing,coverage:d.coverage}),d}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 u;try{u=await o.read()}catch(e){return{status:s,syncedBeforeRead:!1,syncError:Ie(e),failure:"error"}}const p=s.syncedThroughEpoch<u.committedEpoch,f=!o.durable&&!v.has(e);if((l||p||f)&&!i.aborted){const a="foreground"===r?new AbortController:void 0,o=d.get(e),l=!o?.sync,u=o?.syncContext??{},p=()=>{l&&(u.abortCause??(u.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=H(e,"stale_read",a?.signal,u),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&&(u.abortCause??(u.abortCause="caller"),a.abort(i.reason),await J(e,v)),{status:s,syncedBeforeRead:!1,syncError:Se(i)};if("timeout"in E){l&&(u.abortCause??(u.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"===u.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 ue(e,t,r,n,i,a,o,u={}){null!==r&&"grant_expired"===i&&"CONSENT_EXPIRED"!==u.code&&function(e){const t=d.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,...u})}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{ue(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=[...u];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 u=F(n);if(u)return s(n,"grant_missing",{code:u});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"===d.get(n)?.reason){const e=d.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 d=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:de(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??{}),u="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 d=await ke(e.network(),e.signal);if(e.signal.aborted)return ue("get",e.path,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const u=N();if("allow"!==u.status)return ue("get",e.path,s,"network","consent_expired"===u.status?"grant_expired":"replica_gated",d.ok?"found":"error",n,{code:"consent_expired"===u.status?u.code:"REPLICA_GATED"}),d;const p=null===s?void 0:F(s);if(p)return ue("get",e.path,s,"network","grant_missing",d.ok?"found":"error",n,{code:p}),d;if(!d.ok&&d.error.code!==ee)return ue("get",e.path,s,"replica",r,c,n,{...i,code:d.error.code,verify:"error"}),t;const f=d.ok,y=!d.ok&&d.error.code===ee,h=t.ok?t.data.headers.etag??null:null,g=d.ok?d.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}),ue("get",e.path,s,"replica",r,c,n,{...i,verify:E}),t}catch(a){if(e.signal.aborted)return ue("get",e.path,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const o=N();if("allow"!==o.status)return ue("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?(ue("get",e.path,s,"network","grant_missing","error",n,{code:l}),re(ae("kv",a))):(ue("get",e.path,s,"replica",r,c,n,{...i,code:Ie(a),verify:"error"}),t)}}(e,d,u,r,h):(ue("get",e.path,n,"replica",u,d.ok?"found":d.error.code===ee?"not_found":"error",r,h),d)}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 ue("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 u=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?(ue("list",e.listPath,s,"none","cursor_restart","error",r),ge()):u(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?(ue("list",e.listPath,s,"none","cursor_restart","error",r),ge()):u(s,"grant_missing",{code:t})}try{await ke(Ee(),e.signal)}catch{if(e.signal.aborted)return Ne(e.signal)}const p=()=>(ue("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 u(s,"RUNTIME_UNSUPPORTED"===r?"runtime_unsupported":"CONSENT_EXPIRED"===r||"REPLICA_GATED"===r||"GRANT_EXPIRED"===r?M(r):"replica_unavailable",{code:r})}if("grant_missing"===d.get(s)?.reason){if(n&&i)return p();const e=d.get(s)?.lastError;return u(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 u(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 u(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 u(s,"REPLICA_BEHIND_OWN_WRITES");if(y.failure){const e="busy"===y.failure?"REPLICA_BUSY":y.syncError;return u(s,"GRANT_REVOKED"===e?"grant_revoked":"REPLICA_GATED"===e||"CONSENT_EXPIRED"===e||"GRANT_EXPIRED"===e?M(e):"stale",{code:e})}if(g)return u(s,"pending_write",{pendingState:g.state});if(!o.durable&&!v.has(s))return u(s,"REPLICA_UNPROVEN_SINCE_START");if("complete"!==y.status.coverage||"valid"!==y.status.authority.state)return u(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)},d=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 d=(i?[r]:[]).concat(l.keys);const u=void 0!==n&&d.length>n;return u&&(d=d.slice(0,n)),{keys:d,truncated:u,...u?{nextCursor:ye(t,r,d[d.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 u(s,"REPLICA_BEHIND_OWN_WRITES");if(g)return await u(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 u(s,"grant_missing",{code:E});const m={count:d.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 ue("list",e.listPath,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const a=N();if("allow"!==a.status)return ue("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 ue("list",e.listPath,s,"network","grant_missing",t.ok?"found":"error",n,{code:o}),t;if(!t.ok)return ue("list",e.listPath,s,"replica","hit","found",n,{...i,code:t.error.code,verify:"error"}),te(r);const c=new Set(r.keys),d=new Set(t.data.keys),u=r.keys.filter(e=>!d.has(e)),p=t.data.keys.filter(e=>!c.has(e)),f=0===u.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:u,networkOnly:p},stalenessMs:"number"==typeof i.stalenessMs?i.stalenessMs:null}),ue("list",e.listPath,s,"replica","hit","found",n,{...i,verify:h}),te(r)}catch(t){if(e.signal.aborted)return ue("list",e.listPath,s,"none","aborted","error",n,{...i,verify:"aborted"}),Ne(e.signal);const a=N();if("allow"!==a.status)return ue("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?(ue("list",e.listPath,s,"network","grant_missing","error",n,{code:o}),re(ae("kv",t))):(ue("list",e.listPath,s,"replica","hit","found",n,{...i,code:Ie(t),verify:"error"}),te(r))}}(e,d,r,m):(ue("list",e.listPath,s,"replica","hit","found",r,m),te(d))}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 u(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 d=await o.read().catch(()=>{}),u=d?le(d,"",c.now()):[];return"ambiguous"===s&&l({type:"replication.state",space:e.space,state:"pinned",count:u.length,keys:u.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=d.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,d={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(d,{signal:f.signal})),g=h.then(()=>{},()=>{}),v={abort:f,settled:g};u.add(v),g.then(()=>u.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=>H(t,"manual",e?.signal).then(()=>{})))},purge:function(e){var r;f=!0,y=!0,A?.(),A=void 0;const p=u.size>0,h=Oe();for(const e of d.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:[]},u=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"})),u)});try{return await Promise.race([e,r])}finally{t()}},y=Promise.all([...[...d.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=d.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)),d.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=u.size>0,r=Oe();for(const[t,r]of d)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([...[...d.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,d=0,u=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,d++),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=++d;if(c=void 0,!l&&h&&await o(h),!l&&!h&&u<2&&(u++,await g(y)),!l||!await T(e)||r!==d)throw _();const n=await t();if(r!==d)throw _();if(c=e,await A(),r!==d)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)=>(d++,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})();
|