@enbox/agent 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs CHANGED
@@ -2057,7 +2057,7 @@ zone
2057
2057
  zoo`.split(`
2058
2058
  `);xs();xr();g();gy();g();gy();nx();_c();function Jve(t,e,r,n){YP(t);let i=tU({dkLen:32,asyncTick:10},n),{c:a,dkLen:o,asyncTick:s}=i;if(Fl(a),Fl(o),Fl(s),a<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=Gl(e),u=Gl(r),d=new Uint8Array(o),l=Yl.create(t,c),f=l._cloneInto().update(u);return{c:a,dkLen:o,asyncTick:s,DK:d,PRF:l,PRFSalt:f}}function Zve(t,e,r,n,i){return t.destroy(),e.destroy(),n&&n.destroy(),i.fill(0),r}async function AJ(t,e,r,n){let{c:i,dkLen:a,asyncTick:o,DK:s,PRF:c,PRFSalt:u}=Jve(t,e,r,n),d,l=new Uint8Array(4),f=$u(l),h=new Uint8Array(c.outputLen);for(let p=1,m=0;m<a;p++,m+=c.outputLen){let y=s.subarray(m,m+c.outputLen);f.setInt32(0,p,!1),(d=u._cloneInto(d)).update(l).digestInto(h),y.set(h.subarray(0,y.length)),await eU(i-1,o,()=>{c._cloneInto(d).update(h).digestInto(h);for(let w=0;w<y.length;w++)y[w]^=h[w]})}return Zve(c,u,s,d,h)}j0();cx();_c();g();function mm(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function mA(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Yve(...t){let e=a=>a,r=(a,o)=>s=>a(o(s)),n=t.map(a=>a.encode).reduceRight(r,e),i=t.map(a=>a.decode).reduce(r,e);return{encode:n,decode:i}}function Xve(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(r=>{if(r<0||r>=t.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${t.length})`);return t[r]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);let n=t.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${t}`);return n})}}}function Qve(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of e)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function ebe(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*t%8;)r.push(e);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of r)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let n=r.length;if(n*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if(!((n-1)*t%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function m8(t,e,r){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let n=0,i=[],a=Array.from(t);for(a.forEach(o=>{if(o<0||o>=e)throw new Error(`Wrong integer: ${o}`)});;){let o=0,s=!0;for(let c=n;c<a.length;c++){let u=a[c],d=e*o+u;if(!Number.isSafeInteger(d)||e*o/e!==o||d-u!==e*o)throw new Error("convertRadix: carry overflow");o=d%r;let l=Math.floor(d/r);if(a[c]=l,!Number.isSafeInteger(l)||l*r+o!==d)throw new Error("convertRadix: carry overflow");if(s)l?s=!1:n=c;else continue}if(i.push(o),s)break}for(let o=0;o<t.length-1&&t[o]===0;o++)i.push(0);return i.reverse()}var kJ=(t,e)=>e?kJ(e,t%e):t,yA=(t,e)=>t+(e-kJ(t,e));function y8(t,e,r,n){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(yA(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${yA(e,r)}`);let i=0,a=0,o=2**r-1,s=[];for(let c of t){if(c>=2**e)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(i=i<<e|c,a+e>32)throw new Error(`convertRadix2: carry overflow pos=${a} from=${e}`);for(a+=e;a>=r;a-=r)s.push((i>>a-r&o)>>>0);i&=2**a-1}if(i=i<<r-a&o,!n&&a>=e)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&a>0&&s.push(i>>>0),s}function tbe(t){return{encode:e=>{if(!mA(e))throw new Error("radix.encode input should be Uint8Array");return m8(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(m8(e,t,2**8))}}}function rbe(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(yA(8,t)>32||yA(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!mA(r))throw new Error("radix2.encode input should be Uint8Array");return y8(Array.from(r),8,t,!e)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(y8(r,t,8,e))}}}function nbe(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(r){if(!mA(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!mA(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=e(n).slice(0,t),a=r.slice(-t);for(let o=0;o<t;o++)if(i[o]!==a[o])throw new Error("Invalid checksum");return n}}}var w1={alphabet:Xve,chain:Yve,checksum:nbe,convertRadix:m8,convertRadix2:y8,radix:tbe,radix2:rbe,join:Qve,padding:ebe};var ibe=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function _J(t){if(typeof t!="string")throw new TypeError(`Invalid mnemonic type: ${typeof t}`);return t.normalize("NFKD")}function TJ(t){let e=_J(t),r=e.split(" ");if(![12,15,18,21,24].includes(r.length))throw new Error("Invalid mnemonic");return{nfkd:e,words:r}}function IJ(t){Ru(t,16,20,24,28,32)}function DJ(t,e=128){if(Fl(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return abe(Zp(e/8),t)}var obe=t=>{let e=8-t.length/4;return new Uint8Array([Jl(t)[0]>>e<<e])};function RJ(t){if(!Array.isArray(t)||t.length!==2048||typeof t[0]!="string")throw new Error("Wordlist: expected array of 2048 strings");return t.forEach(e=>{if(typeof e!="string")throw new Error(`Wordlist: non-string element: ${e}`)}),w1.chain(w1.checksum(1,obe),w1.radix2(11,!0),w1.alphabet(t))}function sbe(t,e){let{words:r}=TJ(t),n=RJ(e).decode(r);return IJ(n),n}function abe(t,e){return IJ(t),RJ(e).encode(t).join(ibe(e)?"\u3000":" ")}function CJ(t,e){try{sbe(t,e)}catch{return!1}return!0}var cbe=t=>_J(`mnemonic${t}`);function $J(t,e=""){return AJ(tf,TJ(t).nfkd,cbe(e),{c:2048,dkLen:64})}g();hn();g();xr();hn();g();xr();hn();function b1(t){return typeof t=="object"&&t!==null&&"alg"in t&&t.alg!==void 0&&"enc"in t&&t.enc!==void 0}var v1=class{static async decrypt({key:e,encryptedKey:r,joseHeader:n,crypto:i},a){let o=a?.minP2cCount??1e3;switch(n.alg){case"dir":{if(r!==void 0)throw new Ve(ze.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Ve(ze.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');return e}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof n.p2c!="number")throw new Ve(ze.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(n.p2c<o)throw new Ve(ze.InvalidJwe,`JOSE Header "p2c" (PBES2 Count) is ${n.p2c}, which is below the minimum of ${o}.`);if(typeof n.p2s!="string")throw new Ve(ze.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Ve(ze.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');if(r===void 0)throw new Ve(ze.InvalidJwe,'JWE "encrypted_key" is required when using "PBES2" (Key Encryption Mode).');let s;try{s=new Uint8Array([...he.string(n.alg).toUint8Array(),0,...he.base64Url(n.p2s).toUint8Array()])}catch{throw new Ve(ze.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let c=await i.deriveKey({algorithm:n.alg,baseKeyBytes:e,iterations:n.p2c,salt:s});if(!(c.alg&&["A128KW","A192KW","A256KW"].includes(c.alg)))throw new Ve(ze.AlgorithmNotSupported,`Unsupported Key Encryption Algorithm (alg) value: ${c.alg}`);return await i.unwrapKey({decryptionKey:c,wrappedKeyBytes:r,wrappedKeyAlgorithm:n.enc})}default:throw new Ve(ze.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${n.alg}`)}}static async encrypt({key:e,joseHeader:r,crypto:n}){let i,a;switch(r.alg){case"dir":{if(a!==void 0)throw new Ve(ze.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Ve(ze.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');i=e;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof r.p2c!="number")throw new Ve(ze.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(typeof r.p2s!="string")throw new Ve(ze.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Ve(ze.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');i=await n.generateKey({algorithm:r.enc});let o;try{o=new Uint8Array([...he.string(r.alg).toUint8Array(),0,...he.base64Url(r.p2s).toUint8Array()])}catch{throw new Ve(ze.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let s=await n.deriveKey({algorithm:r.alg,baseKeyBytes:e,iterations:r.p2c,salt:o});a=await n.wrapKey({encryptionKey:s,unwrappedKey:i});break}default:throw new Ve(ze.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${r.alg}`)}return{cek:i,encryptedKey:a}}};function g8(t,e){if(e!==void 0)try{if(typeof e!="string")throw new Error;return he.base64Url(e).toUint8Array()}catch{throw new Ve(ze.InvalidJwe,`Failed to decode the JWE Header parameter '${t}' from Base64 URL format to Uint8Array. Ensure the value is properly encoded in Base64 URL format without padding.`)}}var P1=class t{constructor(e){this.ciphertext="";Object.assign(this,e)}static async decrypt({jwe:e,key:r,keyManager:n=new hd,crypto:i=new Ss,options:a={}}){if(!z0(i))throw new Ve(ze.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!z0(n))throw new Ve(ze.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!e.protected&&!e.header&&!e.unprotected)throw new Ve(ze.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protected", "header", or "unprotected"');if(typeof e.ciphertext!="string")throw new Ve(ze.InvalidJwe,"JWE Ciphertext is missing or not a string.");let o;if(e.protected)try{o=he.base64Url(e.protected).toObject()}catch{throw new Error("JWE Protected Header is invalid")}if(BJ(o,e.header,e.unprotected))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "header", "protected", and "unprotected" objects.');let s={...o,...e.header,...e.unprotected};if(!b1(s))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');if(Array.isArray(a.allowedAlgValues)&&!a.allowedAlgValues.includes(s.alg))throw new Error(`"alg" (Algorithm) Header Parameter value not allowed: ${s.alg}`);if(Array.isArray(a.allowedEncValues)&&!a.allowedEncValues.includes(s.enc))throw new Error(`"enc" (Encryption Algorithm) Header Parameter value not allowed: ${s.enc}`);let c;try{let p=e.encrypted_key?he.base64Url(e.encrypted_key).toUint8Array():void 0;c=await v1.decrypt({key:r,encryptedKey:p,joseHeader:s,keyManager:n,crypto:i},{minP2cCount:a.minP2cCount})}catch(p){if(p instanceof Ve&&(p.code===ze.InvalidJwe||p.code===ze.AlgorithmNotSupported))throw p;c=typeof r=="string"?await n.generateKey({algorithm:s.enc}):await i.generateKey({algorithm:s.enc})}let u=g8("iv",e.iv),d=g8("tag",e.tag),l=d!==void 0?new Uint8Array([...he.base64Url(e.ciphertext).toUint8Array(),...d??[]]):he.base64Url(e.ciphertext).toUint8Array(),f=e.aad!==void 0?new Uint8Array([...he.string(e.protected??"").toUint8Array(),...he.string(".").toUint8Array(),...he.string(e.aad).toUint8Array()]):he.string(e.protected??"").toUint8Array();return{plaintext:typeof c=="string"?await n.decrypt({keyUri:c,data:l,iv:u,additionalData:f}):await i.decrypt({key:c,data:l,iv:u,additionalData:f}),protectedHeader:o,additionalAuthenticatedData:g8("aad",e.aad),sharedUnprotectedHeader:e.unprotected,unprotectedHeader:e.header}}static async encrypt({key:e,plaintext:r,additionalAuthenticatedData:n,protectedHeader:i,sharedUnprotectedHeader:a,unprotectedHeader:o,keyManager:s=new hd,crypto:c=new Ss}){if(!z0(c))throw new Ve(ze.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!z0(s))throw new Ve(ze.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!i&&!a&&!o)throw new Ve(ze.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protectedHeader", "sharedUnprotectedHeader", or "unprotectedHeader"');if(!(r instanceof Uint8Array))throw new Ve(ze.InvalidJwe,"Plaintext is missing or not a byte array.");if(BJ(i,a,o))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "protectedHeader", "sharedUnprotectedHeader", and "unprotectedHeader" objects.');let u={...i,...a,...o};if(!b1(u))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');let{cek:d,encryptedKey:l}=await v1.encrypt({key:e,joseHeader:u,keyManager:s,crypto:c}),f;switch(u.enc){case"A128GCM":case"A192GCM":case"A256GCM":f=Yr.randomBytes(12);break;default:f=new Uint8Array(0)}let h=i?he.object(i).toBase64Url():"",p,m;n?(m=he.uint8Array(n).toBase64Url(),p=he.string(h+"."+m).toUint8Array()):p=he.string(h).toUint8Array();let y=typeof d=="string"?await s.encrypt({keyUri:d,data:r,iv:f,additionalData:p}):await c.encrypt({key:d,data:r,iv:f,additionalData:p}),w=y.slice(0,-16),x=y.slice(-16),E=new t({ciphertext:he.uint8Array(w).toBase64Url()});return l&&(E.encrypted_key=he.uint8Array(l).toBase64Url()),i&&(E.protected=h),a&&(E.unprotected=a),o&&(E.header=o),f&&(E.iv=he.uint8Array(f).toBase64Url()),m&&(E.aad=m),x&&(E.tag=he.uint8Array(x).toBase64Url()),E}};function BJ(...t){let e=new Set,r=t.filter(Boolean);for(let n of r)for(let i in n){if(e.has(i))return!0;e.add(i)}return!1}var gl=class{static async decrypt({jwe:e,key:r,keyManager:n=new hd,crypto:i=new Ss,options:a={}}){if(typeof e!="string")throw new Ve(ze.InvalidJwe,"Invalid JWE format. JWE must be a string.");let{0:o,1:s,2:c,3:u,4:d,length:l}=e.split(".");if(l!==5)throw new Ve(ze.InvalidJwe,"Invalid JWE format. JWE must have 5 parts.");let f=await P1.decrypt({jwe:{ciphertext:u,encrypted_key:s||void 0,iv:c||void 0,protected:o,tag:d||void 0},key:r,keyManager:n,crypto:i,options:a});if(!b1(f.protectedHeader))throw new Ve(ze.InvalidJwe,"Decrypt operation failed due to missing or malformed JWE Protected Header");return{plaintext:f.plaintext,protectedHeader:f.protectedHeader}}static async encrypt({plaintext:e,protectedHeader:r,key:n,keyManager:i=new hd,crypto:a=new Ss,options:o={}}){let s=await P1.encrypt({plaintext:e,protectedHeader:r,key:n,keyManager:i,crypto:a,options:o});return[s.protected,s.encrypted_key,s.iv,s.ciphertext,s.tag].join(".")}};g();hn();hn();Mn();g();xr();hn();var ow=class extends dp{constructor(){super(...arguments);this.name="DwnKeyStore";this._recordProtocolDefinition=eJ;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"privateJwk",schema:this._recordProtocolDefinition.types.privateJwk.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Ce.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){let s;if(o.encryption){let{reply:c}=await r.dwn.processRequest({author:n,target:n,messageType:Ce.RecordsRead,messageParams:{filter:{recordId:o.recordId}},encryption:!0}),u=c;if(!u.entry?.data)throw new Error(`${this.name}: Failed to read encrypted key record: ${o.recordId}`);s=await my.consumeToJson({readableStream:u.entry.data})}else{if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);s=he.base64Url(o.encodedData).toObject()}if(eh(s)){let c=`${n}${Bi}${Qp}${s.kid}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},sw=class extends up{constructor(){super(...arguments);this.name="InMemoryKeyStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};var w8={"AES-GCM":{implementation:Ty,names:["A128GCM","A192GCM","A256GCM"]},"AES-KW":{implementation:Iy,names:["A128KW","A192KW","A256KW"]},Ed25519:{implementation:pd,names:["Ed25519"]},secp256k1:{implementation:Tc,names:["ES256K","secp256k1"]},secp256r1:{implementation:Tc,names:["ES256","secp256r1"]},"SHA-256":{implementation:rf,names:["SHA-256"]},X25519:{implementation:of,names:["X25519"]}},As=class{constructor({agent:e,keyStore:r}={}){this._algorithmInstances=new Map;this._agent=e,this._keyStore=r??new sw}get agent(){if(this._agent===void 0)throw new Error("LocalKeyManager: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}async decrypt({keyUri:e,...r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).decrypt({key:n,...r})}digest(e){throw new Error("Method not implemented.")}async encrypt({keyUri:e,...r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).encrypt({key:n,...r})}async exportKey({keyUri:e}){return await this.getPrivateKey({keyUri:e})}async generateKey({algorithm:e}){let r=this.getAlgorithmName({key:{alg:e}}),i=await this.getAlgorithm({algorithm:r}).generateKey({algorithm:e});i.kid??=await xt({jwk:i});let a=await this.getKeyUri({key:i});return await this._keyStore.set({id:a,data:i,agent:this.agent,preventDuplicates:!1,useCache:!0}),a}async getKeyUri({key:e}){let r=await xt({jwk:e});return`${Qp}${r}`}async getPublicKey({keyUri:e}){let r=await this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:r});return await this.getAlgorithm({algorithm:n}).getPublicKey({key:r})}async derivePublicKey({keyUri:e,derivationPath:r}){let n=await this.getX25519PrivateKeyBytes({keyUri:e}),i=await qo.derivePrivateKeyBytes(n,r),a=await Zt.bytesToPrivateKey({privateKeyBytes:i});return await Zt.getPublicKey({key:a})}async jweKeyUnwrap({keyUri:e,derivationPath:r,encryptedKey:n,ephemeralPublicKey:i}){let a=await this.getX25519PrivateKeyBytes({keyUri:e}),o=await qo.derivePrivateKeyBytes(a,r),s=await Zt.bytesToPrivateKey({privateKeyBytes:o});return Fi.ecdhEsUnwrapKey(s,i,n)}async derivePrivateKeyBytes({keyUri:e,derivationPath:r}){let n=await this.getX25519PrivateKeyBytes({keyUri:e});return qo.derivePrivateKeyBytes(n,r)}async importKey({key:e}){if(!eh(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let r=structuredClone(e);r.kid??=await xt({jwk:r});let n=await this.getKeyUri({key:r});return await this._keyStore.set({id:n,data:r,agent:this.agent,preventDuplicates:!0,useCache:!0}),n}async sign({keyUri:e,data:r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:r,key:n})}async unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:r,decryptionKeyUri:n}){let i=await this.getPrivateKey({keyUri:n}),a=this.getAlgorithmName({key:i});return await this.getAlgorithm({algorithm:a}).unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:r,decryptionKey:i})}async verify({key:e,signature:r,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:r,data:n})}async wrapKey({unwrappedKey:e,encryptionKeyUri:r}){let n=await this.getPrivateKey({keyUri:r}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).wrapKey({unwrappedKey:e,encryptionKey:n})}async deleteKey({keyUri:e}){if(!await this._keyStore.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`Key not found: ${e}`);await this._keyStore.delete({id:e,agent:this.agent})}getAlgorithm({algorithm:e}){let r=w8[e]?.implementation;if(!r)throw new Ve(ze.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({key:e}){let r=e.alg,n=e.crv;for(let i of Object.keys(w8)){let a=w8[i].names;if(r&&a.includes(r))return i;if(n&&a.includes(n))return i}throw new Ve(ze.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${r}, crv=${n}. Please check the documentation for the list of supported algorithms.`)}async getX25519PrivateKeyBytes({keyUri:e}){let r=await this.getPrivateKey({keyUri:e});return Zt.privateKeyToBytes({privateKey:r})}async getPrivateKey({keyUri:e}){try{let n=this.agent?.agentDid?.keyManager;if(n&&typeof n.exportKey=="function"){let i=await n.exportKey({keyUri:e});if(i&&eh(i))return i}}catch{}let r=await this._keyStore.get({id:e,agent:this.agent,useCache:!0});if(!r)throw new Error(`Key not found: ${e}`);return r}};function OJ(t){return typeof t!="string"||t.trim().length===0}function dbe(t){return typeof t=="object"&&t!==null&&"dateCreated"in t&&typeof t.dateCreated=="string"&&"size"in t&&typeof t.size=="number"&&"data"in t&&typeof t.data=="string"}function ube(t){return typeof t=="object"&&t!==null&&"initialized"in t&&typeof t.initialized=="boolean"&&"lastBackup"in t&&"lastRestore"in t}var ym=class{constructor({keyDerivationWorkFactor:e,store:r}={}){this.crypto=new Ss;this._keyDerivationWorkFactor=e??21e4,this._store=r??new zl}async backup(){if(this.isLocked()||await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the backup operation because the identity vault has not been initialized and unlocked. Please ensure the vault is properly initialized with a secure password before attempting to backup its contents.");let e={did:await this.getStoredDid(),contentEncryptionKey:await this.getStoredContentEncryptionKey(),status:await this.getStatus()},r=he.object(e).toBase64Url(),n={data:r,dateCreated:new Date().toISOString(),size:r.length};return await this.setStatus({lastBackup:n.dateCreated}),n}async changePassword({oldPassword:e,newPassword:r}){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the change password operation because the identity vault has not been initialized. Please ensure the vault is properly initialized with a secure password before trying again.");await this.lock();let n=await this.getStoredContentEncryptionKey(),i,a;try{let s;({plaintext:s,protectedHeader:i}=await gl.decrypt({jwe:n,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}})),a=he.uint8Array(s).toObject()}catch{throw new Error("HdIdentityVault: Unable to change the vault password due to an incorrectly entered old password.")}let o=await gl.encrypt({key:he.string(r).toUint8Array(),protectedHeader:i,plaintext:he.object(a).toUint8Array(),crypto:this.crypto,keyManager:new As});await this._store.set("contentEncryptionKey",o),this._contentEncryptionKey=a}async getDid(){if(this.isLocked())throw new Error("HdIdentityVault: Vault has not been initialized and unlocked.");let e=await this.getStoredDid(),{plaintext:r}=await gl.decrypt({jwe:e,key:this._contentEncryptionKey,crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}}),n=he.uint8Array(r).toObject();if(!im(n))throw new Error("HdIdentityVault: Unable to decode malformed DID in identity vault");return await Do.import({portableDid:n})}async getStatus(){let e=await this._store.get("vaultStatus");if(!e)return{initialized:!1,lastBackup:null,lastRestore:null};let r=he.string(e).toObject();if(!ube(r))throw new Error("HdIdentityVault: Invalid IdentityVaultStatus object in store");return r}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){if(await this.isInitialized())throw new Error("HdIdentityVault: Vault has already been initialized.");if(OJ(e))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2059
2059
  'valid, non-empty password.`);if(r&&OJ(r))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2060
- 'valid, non-empty password.`);if(r??=DJ(h8,128),!CJ(r,h8))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await $J(r),a=hA.fromMasterSeed(i),o=a.derive("m/44'/0'/0'/0'/0'"),s=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:o.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),c=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:o.publicKey,salt:"",info:"vault_unlock_salt",length:256}),u={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(c).toBase64Url()},d=await gl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:u,plaintext:he.object(s).toUint8Array(),crypto:this.crypto,keyManager:new As});await this._store.set("contentEncryptionKey",d);let l=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:l.privateKey}),h=a.derive("m/44'/0'/1708523827'/0'/1'"),p=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:h.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),w=new oA;await w.addPredefinedKeys({privateKeys:[f,p,y]});let x={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(x.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let k=await(await Ps.create({keyManager:w,options:x})).export(),T={alg:"dir",enc:"A256GCM",cty:"json"},D=await gl.encrypt({key:s,plaintext:he.object(k).toUint8Array(),protectedHeader:T,crypto:this.crypto,keyManager:new As});return await this._store.set("did",D),this._contentEncryptionKey=s,await this.setStatus({initialized:!0}),r}async isInitialized(){return this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:r}){if(!dbe(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let o=he.base64Url(e.data).toObject();await this._store.set("did",o.did),await this._store.set("contentEncryptionKey",o.contentEncryptionKey),await this.setStatus(o.status),await this.unlock({password:r})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let r=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await gl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:r,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=r??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),!0}};g();xs();g();xr();function lbe(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var aw=class extends dp{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=iA;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){return await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Ce.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let s=he.base64Url(o.encodedData).toObject();if(lbe(s)){let c=`${n}${Bi}${s.uri}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},cw=class extends up{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};function Wet(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&im(t.did)}var gm=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new cw}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:r="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:r,options:n,tenant:this.tenant,store:i}),o=new Qg({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:o.did.uri,data:o.metadata,agent:this.agent,tenant:o.metadata.tenant,preventDuplicates:!1,useCache:!0}),o}async export({didUri:e}){let r=await this.get({didUri:e});if(!r)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await r.export()}async get({didUri:e}){let r=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!r)return;let n=await this.agent.did.get({didUri:e,tenant:r.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new Qg({did:n,metadata:r})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let r=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!r)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new Qg({did:r,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let r=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(r.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:r}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(o=>o.id.endsWith("dwn"));if(a)a.serviceEndpoint=r;else{let o={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r};i.document.service?i.document.service.push(o):i.document.service=[o]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:r}){if(!r)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===r)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:r},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let r=await this.list();if(!(r.length<1))return e?r.find(n=>n.metadata.connectedDid===e):r.find(n=>n.metadata.connectedDid!==void 0)}};g();Mn();xr();var oc=class t{constructor({agent:e}={}){this._cachedPermissions=new vo.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:r,delegate:n,messageType:i,protocol:a,cached:o=!1}){let s=[e,r,i,a].join("~"),c=o?this._cachedPermissions.get(s):void 0;if(c)return c;let u=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),d=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},u,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(s,d),d}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:o=!1,checkRevoked:s=!0}){let c=a?{protocol:a}:void 0,u={author:e,target:r,messageType:Ce.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:ft.uri,protocolPath:ft.grantPath,tags:c}}},{reply:d}=o?await this.agent.sendDwnRequest(u):await this.agent.processDwnRequest(u);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let l=s?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:o,tags:c}):new Set,f=[];for(let h of d.entries){if(l.has(h.recordId))continue;let p=$r.parse(h);f.push({grant:p,message:h})}return f}async fetchRevokedGrantIds({author:e,target:r,grantor:n,remote:i,tags:a}){let o={author:e,target:r,messageType:Ce.RecordsQuery,messageParams:{filter:{author:n,protocol:ft.uri,protocolPath:ft.revocationPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${s.status.detail}`);let c=new Set;for(let u of s.entries)u.descriptor.parentId!==void 0&&c.add(u.descriptor.parentId);return c}async fetchRequests({author:e,target:r,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,o={author:e,target:r,messageType:Ce.RecordsQuery,messageParams:{filter:{protocol:ft.uri,protocolPath:ft.requestPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${s.status.detail}`);let c=[];for(let u of s.entries){let d=$d.parse(u);c.push({request:d,message:u})}return c}async isGrantRevoked({author:e,target:r,grantRecordId:n,remote:i=!1}){let a={author:e,target:r,messageType:Ce.RecordsRead,messageParams:{filter:{parentId:n,protocol:ft.uri,protocolPath:ft.revocationPath}}},{reply:o}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(o.status.code===404)return!1;if(o.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${o.status.detail}`)}async createGrant(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,o;ft.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},c=he.object(s).toUint8Array(),u={recipient:a.grantedTo,protocol:ft.uri,protocolPath:ft.grantPath,dataFormat:"application/json",tags:o},{reply:d,message:l}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Ce.RecordsWrite,messageParams:u,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...l,encodedData:he.uint8Array(c).toBase64Url()};return{grant:$r.parse(f),message:f}}async createRequest(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,o;ft.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={description:a.description,delegated:i,scope:a.scope},c=he.object(s).toUint8Array(),u={protocol:ft.uri,protocolPath:ft.requestPath,dataFormat:"application/json",tags:o},{reply:d,message:l}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Ce.RecordsWrite,messageParams:u,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...l,encodedData:he.uint8Array(c).toBase64Url()};return{request:$d.parse(f),message:f}}async createRevocation(e){let{author:r,store:n=!1,grant:i,description:a}=e,o={description:a},s=he.object(o).toUint8Array(),c;ft.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let u={parentContextId:i.id,protocol:ft.uri,protocolPath:ft.revocationPath,dataFormat:"application/json",tags:c},{reply:d,message:l}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Ce.RecordsWrite,messageParams:u,dataStream:new Blob([s])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...l,encodedData:he.uint8Array(s).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,r,n,i,a=!1){let o;for(let s of i){let{grant:c,message:u}=s;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:l,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,d,c,l,f,h)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:u};o||(o={grant:c,message:u})}}return o}static matchScopeFromGrant(e,r,n,i,a,o,s){if(i.grantee!==r||i.grantor!==e)return!1;let c=i.scope,u=c.interface+c.method;if(u===n||u===Ce.MessagesRead&&(n===Ce.MessagesSync||n===Ce.MessagesSubscribe))if(i8(n)){let l=c;if(l.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(l)||l.protocolPath!==void 0&&l.protocolPath===o||l.contextId!==void 0&&s?.startsWith(l.contextId))return!0}else{let l=c;return l.protocol===void 0?!0:l.protocol!==a?!1:this.isUnrestrictedProtocolScope(l)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();var dw=class{constructor({agent:e,syncEngine:r}){this._syncEngine=r,this._agent=e}get agent(){if(this._agent===void 0)throw new Error("AgentSyncApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._syncEngine.agent=e}get connectivityState(){return this._syncEngine.connectivityState}async registerIdentity(e){await this._syncEngine.registerIdentity(e)}async unregisterIdentity(e){await this._syncEngine.unregisterIdentity(e)}async getIdentityOptions(e){return await this._syncEngine.getIdentityOptions(e)}async updateIdentityOptions(e){await this._syncEngine.updateIdentityOptions(e)}sync(e){return this._syncEngine.sync(e)}startSync(e){return this._syncEngine.startSync(e)}stopSync(e){return this._syncEngine.stopSync(e)}};g();var zJ=Tn(aA(),1);Mn();import{Level as pbe}from"level";g();Mn();function jJ(t){let e=t.descriptor;return e.interface!==ge.Records||e.method!==me.Write?!1:e.dateCreated===e.messageTimestamp}function uw(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let d=0;d<t.length;d++){let l=t[d];e.set(d,l);let f=l.message.descriptor;if(f.interface===ge.Protocols&&f.method===me.Configure){let h=f.definition?.protocol;h&&r.set(h,d)}if(f.interface===ge.Records&&f.method===me.Write){let h=l.message.recordId;jJ(l.message)&&h&&n.set(h,d),f.protocol===ft.uri&&f.protocolPath===ft.grantPath&&h&&i.set(h,d)}}let a=new Map,o=new Array(t.length).fill(0),s=(d,l)=>{if(d===l)return;a.has(d)||a.set(d,new Set);let f=a.get(d);f.has(l)||(f.add(l),o[l]++)};for(let d=0;d<t.length;d++){let l=t[d].message.descriptor;if(l.interface===ge.Records){let h=l.protocol;h&&r.has(h)&&s(r.get(h),d)}if(l.interface===ge.Records&&l.parentId){let h=l.parentId;n.has(h)&&s(n.get(h),d)}if(l.interface===ge.Records&&l.method===me.Write){let h=t[d].message.recordId;h&&!jJ(t[d].message)&&n.has(h)&&s(n.get(h),d)}if(l.interface===ge.Records&&l.method===me.Delete){let h=l.recordId;h&&n.has(h)&&s(n.get(h),d)}let f=l.permissionGrantId;f&&i.has(f)&&s(i.get(f),d)}let c=[];for(let d=0;d<t.length;d++)o[d]===0&&c.push(d);let u=[];for(;c.length>0;){let d=c.shift();u.push(e.get(d));let l=a.get(d);if(l)for(let f of l)o[f]--,o[f]===0&&c.push(f)}if(u.length<t.length){let d=new Set(u);for(let l=0;l<t.length;l++){let f=e.get(l);d.has(f)||u.push(f)}}return u}g();Mn();function UJ(t){return t.status.code===202||t.status.code===204||t.status.code===409||t.entry?.message.descriptor.interface===ge.Records&&t.entry?.message.descriptor.method===me.Delete&&t.status.code===404}async function KJ(t){try{return await ve.getCid(t)}catch{return"unknown"}}async function NJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=await MJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}),c=uw(s),u=3,d=c;for(let l=0;l<=u&&d.length>0;l++){let f=[];for(let h of d){let p=await a.dwn.node.processMessage(t,h.message,{dataStream:h.dataStream});if(!UJ(p)){let m=await KJ(h.message);f.push(m)}}if(f.length>0){let h=await MJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:f,agent:a,permissionsApi:o});d=uw(h)}else d=[]}}async function MJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[],c;if(r)try{c=(await o.getPermissionForRequest({connectedDid:t,messageType:Ce.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(l){return console.error("SyncEngineLevel: pull - Error fetching MessagesRead permission grant for delegate DID",l),s}let u=10,d=0;for(;d<i.length;){let l=i.slice(d,d+u);d+=u;let f=await Promise.all(l.map(async h=>{let p=await a.processDwnRequest({store:!1,author:t,target:t,messageType:Ce.MessagesRead,granteeDid:r,messageParams:{messageCid:h,permissionGrantId:c}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,message:p.message})}catch(x){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${e}:`,x.message??x);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,w;return hl(y)&&y.data&&(w=y.data),{message:y.message,dataStream:w}}));for(let h of f)h&&s.push(h)}return s}async function v8({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[];for(let u of i){let d=await fbe({author:t,messageCid:u,delegateDid:r,protocol:n,agent:a,permissionsApi:o});d&&s.push(d)}let c=uw(s);for(let u of c)try{let d=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:u.dataStream,message:u.message});if(!UJ(d)){let l=await KJ(u.message);console.error(`SyncEngineLevel: push failed for ${l}: ${d.status.code} ${d.status.detail}`)}}catch(d){let l=d.message??d;throw new Error(`SyncEngineLevel: push to ${e} failed: ${l}`)}}async function fbe({author:t,delegateDid:e,protocol:r,messageCid:n,agent:i,permissionsApi:a}){let o;if(e)try{o=(await a.getPermissionForRequest({connectedDid:t,messageType:Ce.MessagesRead,delegateDid:e,protocol:r,cached:!0})).grant.id}catch(d){console.error("SyncEngineLevel: push - Error fetching MessagesRead permission grant for delegate DID",d);return}let{reply:s}=await i.dwn.processRequest({author:t,target:t,messageType:Ce.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:o}});if(s.status.code!==200||!s.entry)return;let c=s.entry,u={message:c.message};return hl(c)&&c.data&&(u.dataStream=c.data),u}var LJ=16,qJ="^",hbe=250,x1=class x1{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._syncMode="poll";this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._pendingPushCids=new Map;this._consecutiveFailures=0;this._agent=e,this._permissionsApi=new oc({agent:e}),this._db=n||new pbe(r??"DATA/AGENT/SYNC_STORE")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new oc({agent:e})}get connectivityState(){return this._connectivityState}async clear(){await this._permissionsApi.clear(),await this._db.clear()}async close(){await this._db.close()}async registerIdentity({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);r??={protocols:[]},await n.put(e,JSON.stringify(r))}async unregisterIdentity(e){let r=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await r.del(e)}async getIdentityOptions(e){let r=this._db.sublevel("registeredIdentities");try{let n=await r.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}}async updateIdentityOptions({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(r))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=await this.getSyncTargets(),n=new Set,i=!1;for(let a of r){let{did:o,delegateDid:s,dwnUrl:c,protocol:u}=a;if(!n.has(c))try{let d=await this.getLocalRoot(o,s,u),l=await this.getRemoteRoot(o,c,s,u);if(d===l)continue;let f=await this.walkTreeDiff({did:o,dwnUrl:c,delegateDid:s,protocol:u});(!e||e==="pull")&&f.onlyRemote.length>0&&await this.pullMessages({did:o,dwnUrl:c,delegateDid:s,protocol:u,messageCids:f.onlyRemote}),(!e||e==="push")&&f.onlyLocal.length>0&&await this.pushMessages({did:o,dwnUrl:c,delegateDid:s,protocol:u,messageCids:f.onlyLocal})}catch(d){n.add(c),i=!0,console.error(`SyncEngineLevel: Error syncing ${o} with ${c}`,d)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,zJ.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=r,r==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let r=async()=>{if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),x1.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||await this.sync()}async startLiveSync(e){try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=await this.getSyncTargets();for(let i of r)try{await this.openLivePullSubscription(i),await this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}async teardownLiveSync(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[]}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,o=this.buildCursorKey(r,i,a),s=await this.getCursor(o),c=a?[{protocol:a}]:[],u;if(n)try{u=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Ce.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{u=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Ce.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(h){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",h);return}}let d=async h=>{if(h.type==="eose"){await this.setCursor(o,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);await this.agent.dwn.node.processMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}await this.setCursor(o,h.cursor)}},f=(await this.agent.dwn.sendRequest({author:r,target:r,messageType:Ce.MessagesSubscribe,granteeDid:n,messageParams:{filters:c,cursor:s,permissionGrantId:u},subscriptionHandler:d})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await f.subscription.close()}}),this._connectivityState="online"}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,o=a?[{protocol:a}]:[],s;if(n)try{s=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Ce.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let c=l=>{if(l.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(l.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},hbe)},d=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Ce.MessagesSubscribe,granteeDid:n,messageParams:{filters:o,permissionGrantId:s},subscriptionHandler:c})).reply;if(d.status.code!==200||!d.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${d.status.code} ${d.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await d.subscription.close()}})}async flushPendingPushes(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:o,cids:s}=r;if(s.length!==0)try{await v8({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})}catch(c){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,c)}}}buildCursorKey(e,r,n){let i=`${e}${qJ}${r}`;return n?`${i}${qJ}${n}`:i}async getCursor(e){let r=this._db.sublevel("syncCursors");try{return await r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async setCursor(e,r){await this._db.sublevel("syncCursors").put(e,r)}extractDataStream(e){if(hl(e)&&e.data)return e.data}tryGetCidSync(e){let r;return ve.getCid(e).then(n=>{r=n}),r??e.messageCid??void 0}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await bf(),n=new Map;for(let i=0;i<=LJ;i++)n.set(i,hi(r[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}async getLocalRoot(e,r,n){let i=await this.getSyncPermissionGrantId(e,r,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Ce.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:i}})).reply.root??""}async getRemoteRoot(e,r,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Ce.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).root??""}async walkTreeDiff({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=[],o=[],s=await this.getSyncPermissionGrantId(e,n,i),c=async u=>{let[d,l]=await Promise.all([this.getLocalSubtreeHash(e,u,n,i,s),this.getRemoteSubtreeHash(e,r,u,n,i,s)]);if(d===l)return;let f=await this.getDefaultHashHex(u.length);if(l===f&&d!==f){let h=await this.getLocalLeaves(e,u,n,i,s);a.push(...h);return}if(d===f&&l!==f){let h=await this.getRemoteLeaves(e,r,u,n,i,s);o.push(...h);return}if(u.length>=LJ){let[h,p]=await Promise.all([this.getLocalLeaves(e,u,n,i,s),this.getRemoteLeaves(e,r,u,n,i,s)]),m=new Set(h),y=new Set(p);for(let w of h)y.has(w)||a.push(w);for(let w of p)m.has(w)||o.push(w);return}await Promise.all([c(u+"0"),c(u+"1")])};return await c(""),{onlyLocal:a,onlyRemote:o}}async getLocalSubtreeHash(e,r,n,i,a){return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Ce.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash??""}async getRemoteSubtreeHash(e,r,n,i,a,o){let s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Ce.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:o}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).hash??""}async getLocalLeaves(e,r,n,i,a){return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Ce.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries??[]}async getRemoteLeaves(e,r,n,i,a,o){let s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Ce.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:o}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return NJ({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return v8({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return uw(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch{i={protocols:[]}}let{protocols:a,delegateDid:o}=i,s=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(s.length!==0)for(let c of s)if(a.length===0)e.push({did:r,delegateDid:o,dwnUrl:c});else for(let u of a)e.push({did:r,delegateDid:o,dwnUrl:c,protocol:u})}return e}async getSyncPermissionGrantId(e,r,n){if(r)try{return(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Ce.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(i){console.error("SyncEngineLevel: Error fetching MessagesSync permission grant for delegate DID",i);return}}};x1.MAX_CONSECUTIVE_FAILURES=5,x1.MAX_BACKOFF_MULTIPLIER=4;var lw=x1;g();Mn();xs();xr();import{Level as kbe}from"level";g();g();g();xr();hn();g();g();var FJ=Tn(aA(),1);xr();var fw=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},gA=class{constructor({ttl:e="15m"}={}){this.cache=new vo.default({ttl:(0,FJ.default)(e)})}get(e){return fw(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return fw(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return fw(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return fw(this,void 0,void 0,function*(){this.cache.clear()})}open(){return fw(this,void 0,void 0,function*(){})}close(){return fw(this,void 0,void 0,function*(){})}};g();hn();Mn();g();var pw=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var hw;(function(t){t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.ParseError=-32700]="ParseError",t[t.TransportError=-32300]="TransportError",t[t.BadRequest=-50400]="BadRequest",t[t.Unauthorized=-50401]="Unauthorized",t[t.Forbidden=-50403]="Forbidden",t[t.Conflict=-50409]="Conflict",t[t.TooManyRequests=-50429]="TooManyRequests"})(hw||(hw={}));var mw=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),wA=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),GJ=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function wm(t){try{return JSON.parse(t)}catch{return null}}var b8=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},mbe=3,ybe=500,gbe=1e4,wbe=3e4,HJ=new Set([408,429,500,502,503,504]);function vbe(t,e){return t instanceof TypeError?!0:e?HJ.has(e.status):!1}function bbe(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function Pbe(t){let e=t.headers.get("retry-after");if(e===null)return;let r=Number(e);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var vA=class{constructor(e,r){var n,i,a;this.serverInfoCache=e??new gA,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:mbe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:ybe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:gbe}}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return b8(this,void 0,void 0,function*(){var r,n,i;let a=Yr.randomUuid(),o=mw(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),s={"dwn-request":JSON.stringify(o)},c={method:"POST",headers:s};e.data&&(s["content-type"]="application/octet-stream",c.body=e.data,c.duplex="half");let u=yield this.fetchWithRetry(e.dwnUrl,c);if(u.status===429){let h=parseInt((r=u.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new pw(h)}let d,l=u.headers.has("dwn-response");if(l){let h=wm(u.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=h}else{let h=yield u.text(),p=wm(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${u.status}`);d=p}if(d.error){let{code:h,message:p}=d.error;if(h===hw.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new pw(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=d.result;if(l){let h=new Uint8Array(yield u.arrayBuffer()),p=ar.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return b8(this,void 0,void 0,function*(){var r;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let o=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new pw(o)}if(a.ok){let o=yield a.json(),s={maxFileSize:o.maxFileSize,maxInFlight:o.maxInFlight,providerAuth:o.providerAuth,registrationRequirements:o.registrationRequirements,server:o.server,sdkVersion:o.sdkVersion,url:o.url,version:o.version,webSocketSupport:o.webSocketSupport};return this.serverInfoCache.set(e,s),s}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,r){return b8(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,o,s;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(wbe),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!HJ.has(p.status)||c===n)return p;s=p}catch(f){if(!vbe(f)||c===n)throw f;o=f}let u=s?Pbe(s):void 0,d=bbe(c,i,a),l=u!==void 0?Math.max(u,d):d;yield new Promise(f=>{setTimeout(f,l)})}if(s)return s;throw o})}};g();hn();var E1=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})};function P8(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var VJ=3e3,xbe=3e4,Ebe=1e3,Sbe=3e4,Abe=1/0,bA=class t{constructor(e,r,n,i){this.socket=e,this.responseTimeout=r,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return E1(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=VJ,responseTimeout:o=xbe}=n,s;try{s=yield t.createWebSocket(r,a)}catch(u){throw(i=n.onerror)===null||i===void 0||i.call(n,u),u}let c=new t(s,o,r,n);return c.wireSocket(s),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return E1(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=Yr.randomUuid());let a=o=>{let s=wm(P8(o.data));if(s.id===e.id)return this.messageHandlers.delete(e.id),r(s)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,r){return E1(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let u=wm(P8(c.data));u.id===n&&(u.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(u))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let o=yield this.request(e);return o.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:o}):{response:o,close:()=>E1(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=Yr.randomUuid(),n=wA(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),o=()=>{u(),n(a)},s=d=>{u(),i(d)},c=setTimeout(()=>{u(),a.close(),i(new Error("connect timed out"))},r),u=()=>{clearTimeout(c),a.removeEventListener("open",o),a.removeEventListener("error",s)};a.addEventListener("open",o),a.addEventListener("error",s)})}wireSocket(e){e.addEventListener("message",r=>{let n=wm(P8(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,o;if(this._isConnected=!1,this.closedByUser){(n=(r=this.options).onclose)===null||n===void 0||n.call(r);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((o=this.options.autoReconnect)!==null&&o!==void 0?o:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",r=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,r)})}rejectPendingRequests(){for(let[e,r]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:hw.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:Ebe,o=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:Sbe,s=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Abe,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:VJ,u=0,d=()=>E1(this,void 0,void 0,function*(){var l,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(u++,u>s){this.reconnecting=!1;return}(f=(l=this.options).onreconnecting)===null||f===void 0||f.call(l,u);let y=Math.min(a*Math.pow(2,u-1),o)*(.5+Math.random()*.5);if(yield new Promise(w=>setTimeout(w,y)),this.closedByUser){this.reconnecting=!1;return}try{let w=yield t.createWebSocket(this.url,c);this.socket=w,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(w),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield d()}});d()}};g();g();g();hn();g();hn();var yw=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},S1=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return yw(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:o,subscription:s}=e;return s?t.subscriptionRequest(i,a,o,s.handler,s.resubscribeFactory):t.processMessage(i,a,o)})}static createConnection(e){return yw(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield bA.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let o of n.values())o.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};t.connections.set(r,a),t.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,r,n){return yw(this,void 0,void 0,function*(){let i=Yr.randomUuid(),a=mw(i,"dwn.processMessage",{target:r,message:n}),{socket:o}=e,s=yield o.request(a),{error:c,result:u}=s;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return u.reply})}static subscriptionRequest(e,r,n,i,a){return yw(this,void 0,void 0,function*(){let o=Yr.randomUuid(),s=Yr.randomUuid(),c=wA(o,"rpc.subscribe.dwn.processMessage",{target:r,message:n},s),{socket:u,subscriptions:d}=e,{response:l,close:f}=yield u.subscribe(c,y=>{let{result:w,error:x}=y;if(x){let k=d.get(s);k&&k.subscription.close(),d.delete(s);return}let E=w.subscription;if(i(E),"cursor"in E&&E.cursor){let k=d.get(s);k&&(k.lastCursor=E.cursor),u.send(GJ(s,E.cursor))}}),{error:h,result:p}=l;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let y=()=>yw(this,void 0,void 0,function*(){d.delete(s),yield f()}),w={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(s,w),m.subscription.close=y}return m})}static resubscribeAll(e){return yw(this,void 0,void 0,function*(){let r=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of r)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield t.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};S1.connections=new Map;var A1=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},WJ;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(WJ||(WJ={}));var gw=class{constructor(e=[]){this.transportClients=new Map,e=[new x8,new E8,...e];for(let r of e)for(let n of r.transportProtocols)this.transportClients.set(n,r)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return A1(this,void 0,void 0,function*(){let r=new URL(e.url),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let r=new URL(e.dwnUrl),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return A1(this,void 0,void 0,function*(){let r=new URL(e),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},x8=class extends vA{sendDidRequest(e){return A1(this,void 0,void 0,function*(){let r=Yr.randomUuid(),n=mw(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let o=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(o.ok){if(a=yield o.json(),a.error){let{code:s,message:c}=a.error;throw new Error(`JSON RPC (${s}) - ${c}`)}}else throw new Error(`HTTP (${o.status}) - ${o.statusText}`)}catch(o){throw new Error(`Error encountered while processing response from ${e.url}: ${o.message}`)}return a.result})}},E8=class extends S1{sendDidRequest(e){return A1(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return A1(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var JJ=class t{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:r,permissionsApi:n,keyManager:i}=t.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=r,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await Ps.create({options:{publish:!0,gatewayUri:O.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:r}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:r,testDataLocation:n}){r??="memory",n??="__TESTDATA__";let i=L=>`${n}/${L}`,a=new Ss,o=new gw,s={keyStore:new ow,identityStore:new aw,didStore:new nw,clear:()=>{s.keyStore._protocolInitializedCache?.clear(),s.identityStore._protocolInitializedCache?.clear(),s.didStore._protocolInitializedCache?.clear()}},{agentVault:c,didApi:u,identityApi:d,keyManager:l,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:s}),m=new np({blockstoreLocation:i("DWN_DATASTORE")}),y=new ap({location:i("DWN_STATEINDEX")}),w=new sp,x=new op({location:i("DWN_RESUMABLETASKSTORE")}),E=new ip({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),k=await lp.createDwn({dataPath:n,dataStore:m,didResolver:u,stateIndex:y,eventLog:w,messageStore:E,resumableTaskStore:x}),T=new lp({dwn:k,localDwnStrategy:"off"}),D=new kbe(i("SYNC_STORE")),B=new lw({db:D}),C=new dw({syncEngine:B}),G=new e({agentVault:c,cryptoApi:a,didApi:u,dwnApi:T,identityApi:d,keyManager:l,permissionsApi:p,rpcClient:o,syncApi:C});return new t({agent:G,agentStores:r,didResolverCache:f,dwn:k,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:E,dwnResumableTaskStore:x,dwnStores:s,syncStore:D,vaultStore:h})}static useDiskStores({agent:e,testDataLocation:r,stores:n}){let i=m=>`${r}/${m}`,a=new hy({location:i("VAULT_STORE")}),o=new ym({keyDerivationWorkFactor:1,store:a}),{didStore:s,identityStore:c,keyStore:u}=n,d=new cp({location:i("DID_RESOLVERCACHE")}),l=new lm({agent:e,didMethods:[Ps,Ro],resolverCache:d,store:s}),f=new gm({agent:e,store:c}),h=new As({agent:e,keyStore:u}),p=new oc({agent:e});return{agentVault:o,didApi:l,didResolverCache:d,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new zl,n=new ym({keyDerivationWorkFactor:1,store:r}),i=new TS,a=new lm({agent:e,didMethods:[Ps,Ro],resolverCache:i,store:new iw}),o=new As({agent:e,keyStore:new sw}),s=new gm({agent:e,store:new cw}),c=new oc({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:s,keyManager:o,permissionsApi:c,vaultStore:r}}};g();hn();xs();g();xs();xr();hn();Mn();function _be({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return h1(t,"par");case"authorize":if(!r)throw new Error("authParam must be providied when building a token URL");return h1(t,`authorize/${r}.jwt`);case"callback":return h1(t,"callback");case"token":if(!n)throw new Error("tokenParam must be providied when building a token URL");return h1(t,`token/${n}.jwt`);default:throw new Error(`No matches for endpoint specified: ${e}`)}}async function Tbe(){let t=Yr.randomBytes(32),e=await Ou.digest({data:t}),r=he.uint8Array(e).toBase64Url();return{codeChallengeBytes:e,codeChallengeBase64Url:r}}async function Ibe(t){let e=Yr.randomBytes(16),r=Yr.randomBytes(16);return{...t,nonce:he.uint8Array(r).toBase64Url(),response_type:"id_token",response_mode:"direct_post",state:he.uint8Array(e).toBase64Url(),client_metadata:{subject_syntax_types_supported:["did:dht","did:jwk"]}}}async function Dbe({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=Yr.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),o=await gd.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),s=o.subarray(0,-16),c=o.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(s).toBase64Url(),he.uint8Array(c).toBase64Url()].join(".")}async function Rbe(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}async function Cbe({did:t,data:e}){let r=he.object({alg:"EdDSA",kid:t.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await t.getSigner()).sign({data:he.string(`${r}.${n}`).toUint8Array()}),o=he.uint8Array(a).toBase64Url();return`${r}.${n}.${o}`}async function ZJ({jwt:t}){let[e,r,n]=t.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error("OIDC: Object could not be verified due to missing 'kid' header value.");let{didDocument:a}=await Ro.resolve(i.kid.split("#")[0]);if(!a)throw new Error("OIDC: Object could not be verified due to Client DID resolution issue.");let{publicKeyJwk:o}=a.verificationMethod?.find(d=>d.id===i.kid)??{};if(!o)throw new Error("OIDC: Object could not be verified due to missing public key in DID document.");if(!await new pd().verify({key:o,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${r}`).toUint8Array()}))throw new Error("OIDC: Object failed verification due to invalid signature.");return he.base64Url(r).toObject()}var $be=async(t,e)=>{let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await YJ({jwe:n,encryption_key:e});return await ZJ({jwt:i})};async function YJ({jwe:t,encryption_key:e}){let[r,,n,i,a]=t.split("."),o=he.base64Url(e).toUint8Array(),c=he.base64Url(r).toUint8Array(),u=he.base64Url(n).toUint8Array(),d=he.base64Url(i).toUint8Array(),l=he.base64Url(a).toUint8Array(),f=new Uint8Array([...d,...l]),h=await gd.decryptRaw({data:f,keyBytes:o,nonce:u,additionalData:c});return he.uint8Array(h).toString()}async function Bbe(t,e,r){let[n,,i,a,o]=e.split("."),s=he.base64Url(n).toObject();if(!s.kid)throw new Error('JWE protected header is missing required "kid" property');let c=await Ro.resolve(s.kid.split("#")[0]),u=await is.deriveSharedKey(t,c.didDocument),d={...s,pin:r},l=he.object(d).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(o).toUint8Array(),m=new Uint8Array([...h,...p]),y=await gd.decryptRaw({data:m,keyBytes:u,nonce:f,additionalData:l});return he.uint8Array(y).toString()}async function Obe(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await Si.convertPublicKeyToX25519({publicKey:n}),o=await Si.convertPrivateKeyToX25519({privateKey:i}),s=await Zt.sharedSecret({privateKeyA:o,publicKeyB:a});return await Dy.deriveKeyBytes({baseKeyBytes:new Uint8Array(s),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function jbe({jwt:t,encryptionKey:e,delegateDidKeyId:r,randomPin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=Yr.randomBytes(24),o=he.object({...i,pin:n}).toUint8Array(),s=he.string(t).toUint8Array(),c=await gd.encryptRaw({data:s,keyBytes:e,nonce:a,additionalData:o}),u=c.subarray(0,-16),d=c.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(u).toBase64Url(),he.uint8Array(d).toBase64Url()].join(".")}function Mbe(t){return o8(t)?!0:t.interface===ge.Protocols&&t.method===me.Configure}async function Ube(t,e,r,n){let i=new oc({agent:r});Ni.log(`Creating permission grants for ${n.length} scopes given...`);let a=await Promise.all(n.map(s=>{let c=Mbe(s);return i.createGrant({delegated:c,store:!0,grantedTo:e.uri,scope:s,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})}));Ni.log(`Sending ${a.length} permission grants to remote DWN...`);let o=a.map(async s=>{let{encodedData:c,...u}=s.message,d=he.base64Url(c).toUint8Array(),{reply:l}=await r.sendDwnRequest({author:t,target:t,messageType:Ce.RecordsWrite,dataStream:new Blob([d]),rawMessage:u});if(l.status.code!==202&&l.status.code!==409)throw Ni.error(`Error sending RecordsWrite: ${l.status.detail}`),Ni.error(`RecordsWrite message: ${u}`),new Error(`Could not send the message. Error details: ${l.status.detail}`);return s.message});try{return await Promise.all(o)}catch(s){throw Ni.error(`Error during batch-send of permission grants: ${s}`),s}}async function Kbe(t,e,r){let n=await e.processDwnRequest({author:t,messageType:Ce.ProtocolsQuery,target:t,messageParams:{filter:{protocol:r.protocol}}});if(n.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${n.reply.status.detail}`);if(n.reply.entries===void 0||n.reply.entries.length===0){Ni.log(`Protocol does not exist, creating: ${r.protocol}`);let{reply:i,message:a}=await e.sendDwnRequest({author:t,target:t,messageType:Ce.ProtocolsConfigure,messageParams:{definition:r}});if(i.status.code!==202&&i.status.code!==409)throw new Error(`Could not send protocol: ${i.status.detail}`);await e.processDwnRequest({author:t,target:t,messageType:Ce.ProtocolsConfigure,rawMessage:a})}else{Ni.log(`Protocol already exists: ${r.protocol}`);let i=n.reply.entries[0],{reply:a}=await e.sendDwnRequest({author:t,target:t,messageType:Ce.ProtocolsConfigure,rawMessage:i});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`)}}async function Nbe(t,e,r,n){let i=await Ro.create(),a=await i.export(),o=e.permissionRequests.map(async p=>{let{protocolDefinition:m,permissionScopes:y}=p;if(!y.every(E=>"protocol"in E&&E.protocol===m.protocol))throw new Error("All permission scopes must match the protocol uri they are provided with.");return await Kbe(t,n,m),await is.createPermissionGrants(t,i,n,y)}),s=(await Promise.all(o)).flat();Ni.log("Generating auth response object...");let c=await is.createResponseObject({iss:t,sub:i.uri,aud:e.client_id,nonce:e.nonce,delegateGrants:s,delegatePortableDid:a});Ni.log("Signing auth response object...");let u=await is.signJwt({did:i,data:c}),d=await Ro.resolve(e.client_id),l=await is.deriveSharedKey(i,d?.didDocument);Ni.log("Encrypting auth response object...");let f=await is.encryptAuthResponse({jwt:u,encryptionKey:l,delegateDidKeyId:i.document.verificationMethod[0].id,randomPin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Ni.log(`Sending auth response object to Web5 Connect server: ${e.redirect_uri}`),await fetch(e.redirect_uri,{body:h,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var is={createAuthRequest:Ibe,encryptAuthRequest:Dbe,getAuthRequest:$be,decryptAuthRequest:YJ,createPermissionGrants:Ube,createResponseObject:Rbe,encryptAuthResponse:jbe,decryptAuthResponse:Bbe,deriveSharedKey:Obe,signJwt:Cbe,verifyJwt:ZJ,buildOidcUrl:_be,generateCodeChallenge:Tbe,submitAuthResponse:Nbe};xr();Mn();async function Lbe({displayName:t,connectServerUrl:e,walletUri:r,permissionRequests:n,onWalletUriReady:i,validatePin:a}){let o=await Ro.create(),s=Yr.randomBytes(32),c=is.buildOidcUrl({baseURL:e,endpoint:"callback"}),u=await is.createAuthRequest({client_id:o.uri,scope:"openid did:jwk",redirect_uri:c,permissionRequests:n,displayName:t}),d=await is.signJwt({did:o,data:u});if(!d)throw new Error("Unable to sign requestObject");let l=await is.encryptAuthRequest({jwt:d,encryptionKey:s}),f=new URLSearchParams({request:l}),h=is.buildOidcUrl({baseURL:e,endpoint:"pushedAuthorizationRequest"}),p=await fetch(h,{body:f,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)});if(!p.ok)throw new Error(`${p.status}: ${p.statusText}`);let m=await p.json();Ni.log(`Wallet URI: ${r}`);let y=new URL(r);y.searchParams.set("request_uri",m.request_uri),y.searchParams.set("encryption_key",he.uint8Array(s).toBase64Url()),i(y.toString());let w=is.buildOidcUrl({baseURL:e,endpoint:"token",tokenParam:u.state}),x=await XW(()=>fetch(w,{signal:AbortSignal.timeout(3e4)}));if(x){let E=await x?.text(),k=await a(),T=await is.decryptAuthResponse(o,E,k),D=await is.verifyJwt({jwt:T});return{delegateGrants:D.delegateGrants,delegatePortableDid:D.delegatePortableDid,connectedDid:D.iss}}}function qbe({definition:t,permissions:e}){let r=[];r.push({protocol:t.protocol,interface:ge.Protocols,method:me.Query}),r.push({protocol:t.protocol,interface:ge.Messages,method:me.Read});for(let n of e)switch(n){case"write":r.push({protocol:t.protocol,interface:ge.Records,method:me.Write});break;case"read":r.push({protocol:t.protocol,interface:ge.Records,method:me.Read});break;case"delete":r.push({protocol:t.protocol,interface:ge.Records,method:me.Delete});break;case"query":r.push({protocol:t.protocol,interface:ge.Records,method:me.Query});break;case"subscribe":r.push({protocol:t.protocol,interface:ge.Records,method:me.Subscribe});break;case"configure":r.push({protocol:t.protocol,interface:ge.Protocols,method:me.Configure});break}return{protocolDefinition:t,permissionScopes:r}}var ant={initClient:Lbe,createPermissionRequestForProtocol:qbe};g();xr();xs();var S8=class t{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:r,agentDid:n,agentVault:i,cryptoApi:a,didApi:o,dwnApi:s,identityApi:c,keyManager:u,permissionsApi:d,rpcClient:l,syncApi:f}={}){return i??=new ym({keyDerivationWorkFactor:21e4,store:new hy({location:`${e}/VAULT_STORE`})}),a??=new Ss,o??=new lm({didMethods:[Ps,Ro],resolverCache:new cp({location:`${e}/DID_RESOLVERCACHE`}),store:new nw}),s??=new lp({dwn:await lp.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"}),r&&s.setLocalDwnStrategy(r),c??=new gm({store:new aw}),u??=new As({keyStore:new ow}),d??=new oc,l??=new gw,f??=new dw({syncEngine:new lw({dataPath:e})}),new t({agentDid:n,agentVault:i,cryptoApi:a,didApi:o,dwnApi:s,keyManager:u,permissionsApi:d,identityApi:c,rpcClient:l,syncApi:f})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){return r=await this.vault.initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}),r}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}},knt=S8;export{Ss as AgentCryptoApi,lm as AgentDidApi,cp as AgentDidResolverCache,lp as AgentDwnApi,gm as AgentIdentityApi,oc as AgentPermissionsApi,dw as AgentSyncApi,QW as AnonymousDwnApi,Qg as BearerIdentity,Dve as DISCOVERY_DIR,Rve as DISCOVERY_FILENAME,gJ as DWN_PROTOCOL_SCHEME,wJ as DWN_REGISTER_PATH,Ave as DidInterface,Oa as DwnConstant,ci as DwnContentEncryptionAlgorithm,dp as DwnDataStore,zt as DwnDateSort,nw as DwnDidStore,cA as DwnDiscoveryFile,aw as DwnIdentityStore,Ce as DwnInterface,Mt as DwnKeyDerivationScheme,ow as DwnKeyStore,$r as DwnPermissionGrant,$d as DwnPermissionRequest,ft as DwnPermissionsProtocol,S8 as EnboxUserAgent,ym as HdIdentityVault,up as InMemoryDataStore,iw as InMemoryDidStore,cw as InMemoryIdentityStore,sw as InMemoryKeyStore,fm as LocalDwnDiscovery,As as LocalKeyManager,is as Oidc,JJ as PlatformAgentTestHarness,lw as SyncEngineLevel,ant as WalletConnect,knt as Web5UserAgent,nJ as buildContextKeyDecrypter,hQe as buildDwnDiscoveryRedirectUrl,fQe as buildDwnRegisterUrl,pm as buildEncryptionInput,oJ as buildKmsDecryptCallback,h1 as concatenateUrl,Ive as createNodeDiscoveryFileFs,yJ as decodeDwnDiscoveryPayload,lA as deriveContextEncryptionInput,c8 as detectNewParticipants,ic as dwnMessageConstructors,uJ as eagerSendContextKeyRecord,Ove as encodeDwnDiscoveryPayload,uA as encryptAndComputeCid,cJ as ensureKeyDeliveryProtocol,lJ as fetchContextKeyRecord,p1 as getDwnServiceEndpointUrls,g1 as getEncryptionKeyDeriver,yl as getEncryptionKeyInfo,hm as getKeyDecrypter,IYe as getPaginationCursor,_Ye as getRecordAuthor,vve as getRecordMessageCid,TYe as getRecordProtocolRole,DXe as getRootContextId,aJ as getRuleSetAtPath,s8 as hasRelationalReadAccess,rJ as isDidRequest,$ve as isDwnMessage,tu as isDwnRequest,lbe as isIdentityMetadata,Bve as isMessagesPermissionScope,a8 as isMultiPartyContext,Wet as isPortableIdentity,o8 as isRecordPermissionScope,i8 as isRecordsType,hl as isRecordsWrite,dA as ivLength,_ve as localDwnHostCandidates,kve as localDwnPortCandidates,Tve as localDwnServerName,sJ as maybeDecryptReply,y1 as normalizeBaseUrl,pQe as parseDwnRegisterUrl,XW as pollWithTtl,mQe as readDwnDiscoveryPayloadFromUrl,iJ as resolveKeyDecrypter,fJ as upgradeExternalRootRecord,dJ as writeContextKeyRecord};
2060
+ 'valid, non-empty password.`);if(r??=DJ(h8,128),!CJ(r,h8))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await $J(r),a=hA.fromMasterSeed(i),o=a.derive("m/44'/0'/0'/0'/0'"),s=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:o.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),c=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:o.publicKey,salt:"",info:"vault_unlock_salt",length:256}),u={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(c).toBase64Url()},d=await gl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:u,plaintext:he.object(s).toUint8Array(),crypto:this.crypto,keyManager:new As});await this._store.set("contentEncryptionKey",d);let l=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:l.privateKey}),h=a.derive("m/44'/0'/1708523827'/0'/1'"),p=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:h.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),w=new oA;await w.addPredefinedKeys({privateKeys:[f,p,y]});let x={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(x.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let k=await(await Ps.create({keyManager:w,options:x})).export(),T={alg:"dir",enc:"A256GCM",cty:"json"},D=await gl.encrypt({key:s,plaintext:he.object(k).toUint8Array(),protectedHeader:T,crypto:this.crypto,keyManager:new As});return await this._store.set("did",D),this._contentEncryptionKey=s,await this.setStatus({initialized:!0}),r}async isInitialized(){return this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:r}){if(!dbe(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let o=he.base64Url(e.data).toObject();await this._store.set("did",o.did),await this._store.set("contentEncryptionKey",o.contentEncryptionKey),await this.setStatus(o.status),await this.unlock({password:r})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let r=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await gl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new As,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:r,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=r??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),!0}};g();xs();g();xr();function lbe(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var aw=class extends dp{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=iA;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){return await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Ce.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let o of i.entries??[]){if(!o.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let s=he.base64Url(o.encodedData).toObject();if(lbe(s)){let c=`${n}${Bi}${s.uri}`;this._index.set(c,o.recordId),this._cache.set(o.recordId,s),a.push(s)}}return a}},cw=class extends up{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};function Wet(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&im(t.did)}var gm=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new cw}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:r="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:r,options:n,tenant:this.tenant,store:i}),o=new Qg({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:o.did.uri,data:o.metadata,agent:this.agent,tenant:o.metadata.tenant,preventDuplicates:!1,useCache:!0}),o}async export({didUri:e}){let r=await this.get({didUri:e});if(!r)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await r.export()}async get({didUri:e}){let r=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!r)return;let n=await this.agent.did.get({didUri:e,tenant:r.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new Qg({did:n,metadata:r})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let r=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!r)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new Qg({did:r,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let r=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(r.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:r}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(o=>o.id.endsWith("dwn"));if(a)a.serviceEndpoint=r;else{let o={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r};i.document.service?i.document.service.push(o):i.document.service=[o]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:r}){if(!r)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===r)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:r},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let r=await this.list();if(!(r.length<1))return e?r.find(n=>n.metadata.connectedDid===e):r.find(n=>n.metadata.connectedDid!==void 0)}};g();Mn();xr();var oc=class t{constructor({agent:e}={}){this._cachedPermissions=new vo.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:r,delegate:n,messageType:i,protocol:a,cached:o=!1}){let s=[e,r,i,a].join("~"),c=o?this._cachedPermissions.get(s):void 0;if(c)return c;let u=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),d=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},u,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(s,d),d}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:o=!1,checkRevoked:s=!0}){let c=a?{protocol:a}:void 0,u={author:e,target:r,messageType:Ce.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:ft.uri,protocolPath:ft.grantPath,tags:c}}},{reply:d}=o?await this.agent.sendDwnRequest(u):await this.agent.processDwnRequest(u);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let l=s?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:o,tags:c}):new Set,f=[];for(let h of d.entries){if(l.has(h.recordId))continue;let p=$r.parse(h);f.push({grant:p,message:h})}return f}async fetchRevokedGrantIds({author:e,target:r,grantor:n,remote:i,tags:a}){let o={author:e,target:r,messageType:Ce.RecordsQuery,messageParams:{filter:{author:n,protocol:ft.uri,protocolPath:ft.revocationPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${s.status.detail}`);let c=new Set;for(let u of s.entries)u.descriptor.parentId!==void 0&&c.add(u.descriptor.parentId);return c}async fetchRequests({author:e,target:r,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,o={author:e,target:r,messageType:Ce.RecordsQuery,messageParams:{filter:{protocol:ft.uri,protocolPath:ft.requestPath,tags:a}}},{reply:s}=i?await this.agent.sendDwnRequest(o):await this.agent.processDwnRequest(o);if(s.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${s.status.detail}`);let c=[];for(let u of s.entries){let d=$d.parse(u);c.push({request:d,message:u})}return c}async isGrantRevoked({author:e,target:r,grantRecordId:n,remote:i=!1}){let a={author:e,target:r,messageType:Ce.RecordsRead,messageParams:{filter:{parentId:n,protocol:ft.uri,protocolPath:ft.revocationPath}}},{reply:o}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(o.status.code===404)return!1;if(o.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${o.status.detail}`)}async createGrant(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,o;ft.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},c=he.object(s).toUint8Array(),u={recipient:a.grantedTo,protocol:ft.uri,protocolPath:ft.grantPath,dataFormat:"application/json",tags:o},{reply:d,message:l}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Ce.RecordsWrite,messageParams:u,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...l,encodedData:he.uint8Array(c).toBase64Url()};return{grant:$r.parse(f),message:f}}async createRequest(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,o;ft.hasProtocolScope(a.scope)&&(o={protocol:a.scope.protocol});let s={description:a.description,delegated:i,scope:a.scope},c=he.object(s).toUint8Array(),u={protocol:ft.uri,protocolPath:ft.requestPath,dataFormat:"application/json",tags:o},{reply:d,message:l}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Ce.RecordsWrite,messageParams:u,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...l,encodedData:he.uint8Array(c).toBase64Url()};return{request:$d.parse(f),message:f}}async createRevocation(e){let{author:r,store:n=!1,grant:i,description:a}=e,o={description:a},s=he.object(o).toUint8Array(),c;ft.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let u={parentContextId:i.id,protocol:ft.uri,protocolPath:ft.revocationPath,dataFormat:"application/json",tags:c},{reply:d,message:l}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Ce.RecordsWrite,messageParams:u,dataStream:new Blob([s])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...l,encodedData:he.uint8Array(s).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,r,n,i,a=!1){let o;for(let s of i){let{grant:c,message:u}=s;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:l,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,d,c,l,f,h)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:u};o||(o={grant:c,message:u})}}return o}static matchScopeFromGrant(e,r,n,i,a,o,s){if(i.grantee!==r||i.grantor!==e)return!1;let c=i.scope,u=c.interface+c.method;if(u===n||u===Ce.MessagesRead&&(n===Ce.MessagesSync||n===Ce.MessagesSubscribe))if(i8(n)){let l=c;if(l.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(l)||l.protocolPath!==void 0&&l.protocolPath===o||l.contextId!==void 0&&s?.startsWith(l.contextId))return!0}else{let l=c;return l.protocol===void 0?!0:l.protocol!==a?!1:this.isUnrestrictedProtocolScope(l)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();var dw=class{constructor({agent:e,syncEngine:r}){this._syncEngine=r,this._agent=e}get agent(){if(this._agent===void 0)throw new Error("AgentSyncApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._syncEngine.agent=e}get connectivityState(){return this._syncEngine.connectivityState}async registerIdentity(e){await this._syncEngine.registerIdentity(e)}async unregisterIdentity(e){await this._syncEngine.unregisterIdentity(e)}async getIdentityOptions(e){return await this._syncEngine.getIdentityOptions(e)}async updateIdentityOptions(e){await this._syncEngine.updateIdentityOptions(e)}sync(e){return this._syncEngine.sync(e)}startSync(e){return this._syncEngine.startSync(e)}stopSync(e){return this._syncEngine.stopSync(e)}};g();var zJ=Tn(aA(),1);Mn();import{Level as pbe}from"level";g();Mn();function jJ(t){let e=t.descriptor;return e.interface!==ge.Records||e.method!==me.Write?!1:e.dateCreated===e.messageTimestamp}function uw(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let d=0;d<t.length;d++){let l=t[d];e.set(d,l);let f=l.message.descriptor;if(f.interface===ge.Protocols&&f.method===me.Configure){let h=f.definition?.protocol;h&&r.set(h,d)}if(f.interface===ge.Records&&f.method===me.Write){let h=l.message.recordId;jJ(l.message)&&h&&n.set(h,d),f.protocol===ft.uri&&f.protocolPath===ft.grantPath&&h&&i.set(h,d)}}let a=new Map,o=new Array(t.length).fill(0),s=(d,l)=>{if(d===l)return;a.has(d)||a.set(d,new Set);let f=a.get(d);f.has(l)||(f.add(l),o[l]++)};for(let d=0;d<t.length;d++){let l=t[d].message.descriptor;if(l.interface===ge.Records){let h=l.protocol;h&&r.has(h)&&s(r.get(h),d)}if(l.interface===ge.Records&&l.parentId){let h=l.parentId;n.has(h)&&s(n.get(h),d)}if(l.interface===ge.Records&&l.method===me.Write){let h=t[d].message.recordId;h&&!jJ(t[d].message)&&n.has(h)&&s(n.get(h),d)}if(l.interface===ge.Records&&l.method===me.Delete){let h=l.recordId;h&&n.has(h)&&s(n.get(h),d)}let f=l.permissionGrantId;f&&i.has(f)&&s(i.get(f),d)}let c=[];for(let d=0;d<t.length;d++)o[d]===0&&c.push(d);let u=[];for(;c.length>0;){let d=c.shift();u.push(e.get(d));let l=a.get(d);if(l)for(let f of l)o[f]--,o[f]===0&&c.push(f)}if(u.length<t.length){let d=new Set(u);for(let l=0;l<t.length;l++){let f=e.get(l);d.has(f)||u.push(f)}}return u}g();Mn();function UJ(t){return t.status.code===202||t.status.code===204||t.status.code===409||t.entry?.message.descriptor.interface===ge.Records&&t.entry?.message.descriptor.method===me.Delete&&t.status.code===404}async function KJ(t){try{return await ve.getCid(t)}catch{return"unknown"}}async function NJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=await MJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}),c=uw(s),u=3,d=c;for(let l=0;l<=u&&d.length>0;l++){let f=[];for(let h of d){let p=await a.dwn.node.processMessage(t,h.message,{dataStream:h.dataStream});if(!UJ(p)){let m=await KJ(h.message);f.push(m)}}if(f.length>0){let h=await MJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:f,agent:a,permissionsApi:o});d=uw(h)}else d=[]}}async function MJ({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[],c;if(r)try{c=(await o.getPermissionForRequest({connectedDid:t,messageType:Ce.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(l){return console.error("SyncEngineLevel: pull - Error fetching MessagesRead permission grant for delegate DID",l),s}let u=10,d=0;for(;d<i.length;){let l=i.slice(d,d+u);d+=u;let f=await Promise.all(l.map(async h=>{let p=await a.processDwnRequest({store:!1,author:t,target:t,messageType:Ce.MessagesRead,granteeDid:r,messageParams:{messageCid:h,permissionGrantId:c}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,message:p.message})}catch(x){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${e}:`,x.message??x);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,w;return hl(y)&&y.data&&(w=y.data),{message:y.message,dataStream:w}}));for(let h of f)h&&s.push(h)}return s}async function v8({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:o}){let s=[];for(let u of i){let d=await fbe({author:t,messageCid:u,delegateDid:r,protocol:n,agent:a,permissionsApi:o});d&&s.push(d)}let c=uw(s);for(let u of c)try{let d=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:u.dataStream,message:u.message});if(!UJ(d)){let l=await KJ(u.message);console.error(`SyncEngineLevel: push failed for ${l}: ${d.status.code} ${d.status.detail}`)}}catch(d){let l=d.message??d;throw new Error(`SyncEngineLevel: push to ${e} failed: ${l}`)}}async function fbe({author:t,delegateDid:e,protocol:r,messageCid:n,agent:i,permissionsApi:a}){let o;if(e)try{o=(await a.getPermissionForRequest({connectedDid:t,messageType:Ce.MessagesRead,delegateDid:e,protocol:r,cached:!0})).grant.id}catch(d){console.error("SyncEngineLevel: push - Error fetching MessagesRead permission grant for delegate DID",d);return}let{reply:s}=await i.dwn.processRequest({author:t,target:t,messageType:Ce.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:o}});if(s.status.code!==200||!s.entry)return;let c=s.entry,u={message:c.message};return hl(c)&&c.data&&(u.dataStream=c.data),u}var LJ=16,qJ="^",hbe=250,x1=class x1{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._syncMode="poll";this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._pendingPushCids=new Map;this._consecutiveFailures=0;this._agent=e,this._permissionsApi=new oc({agent:e}),this._db=n||new pbe(r??"DATA/AGENT/SYNC_STORE")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new oc({agent:e})}get connectivityState(){return this._connectivityState}async clear(){await this._permissionsApi.clear(),await this._db.clear()}async close(){await this._db.close()}async registerIdentity({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);r??={protocols:[]},await n.put(e,JSON.stringify(r))}async unregisterIdentity(e){let r=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await r.del(e)}async getIdentityOptions(e){let r=this._db.sublevel("registeredIdentities");try{let n=await r.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}}async updateIdentityOptions({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(r))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=await this.getSyncTargets(),n=new Set,i=!1;for(let a of r){let{did:o,delegateDid:s,dwnUrl:c,protocol:u}=a;if(!n.has(c))try{let d=await this.getLocalRoot(o,s,u),l=await this.getRemoteRoot(o,c,s,u);if(d===l)continue;let f=await this.walkTreeDiff({did:o,dwnUrl:c,delegateDid:s,protocol:u});(!e||e==="pull")&&f.onlyRemote.length>0&&await this.pullMessages({did:o,dwnUrl:c,delegateDid:s,protocol:u,messageCids:f.onlyRemote}),(!e||e==="push")&&f.onlyLocal.length>0&&await this.pushMessages({did:o,dwnUrl:c,delegateDid:s,protocol:u,messageCids:f.onlyLocal})}catch(d){n.add(c),i=!0,console.error(`SyncEngineLevel: Error syncing ${o} with ${c}`,d)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,zJ.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=r,r==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let r=async()=>{if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),x1.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||await this.sync()}async startLiveSync(e){try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=await this.getSyncTargets();for(let i of r)try{await this.openLivePullSubscription(i),await this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}async teardownLiveSync(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[]}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,o=this.buildCursorKey(r,i,a),s=await this.getCursor(o),c=a?[{protocol:a}]:[],u;if(n)try{u=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Ce.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{u=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Ce.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(h){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",h);return}}let d=async h=>{if(h.type==="eose"){await this.setCursor(o,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);await this.agent.dwn.node.processMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}await this.setCursor(o,h.cursor)}},f=(await this.agent.dwn.sendRequest({author:r,target:r,messageType:Ce.MessagesSubscribe,granteeDid:n,messageParams:{filters:c,cursor:s,permissionGrantId:u},subscriptionHandler:d})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await f.subscription.close()}}),this._connectivityState="online"}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,o=a?[{protocol:a}]:[],s;if(n)try{s=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Ce.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let c=l=>{if(l.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(l.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},hbe)},d=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Ce.MessagesSubscribe,granteeDid:n,messageParams:{filters:o,permissionGrantId:s},subscriptionHandler:c})).reply;if(d.status.code!==200||!d.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${d.status.code} ${d.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await d.subscription.close()}})}async flushPendingPushes(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:o,cids:s}=r;if(s.length!==0)try{await v8({did:n,dwnUrl:i,delegateDid:a,protocol:o,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})}catch(c){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,c)}}}buildCursorKey(e,r,n){let i=`${e}${qJ}${r}`;return n?`${i}${qJ}${n}`:i}async getCursor(e){let r=this._db.sublevel("syncCursors");try{return await r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async setCursor(e,r){await this._db.sublevel("syncCursors").put(e,r)}extractDataStream(e){if(hl(e)&&e.data)return e.data}tryGetCidSync(e){let r;return ve.getCid(e).then(n=>{r=n}),r??e.messageCid??void 0}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await bf(),n=new Map;for(let i=0;i<=LJ;i++)n.set(i,hi(r[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}async getLocalRoot(e,r,n){let i=await this.getSyncPermissionGrantId(e,r,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Ce.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:i}})).reply.root??""}async getRemoteRoot(e,r,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Ce.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).root??""}async walkTreeDiff({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=[],o=[],s=await this.getSyncPermissionGrantId(e,n,i),c=async u=>{let[d,l]=await Promise.all([this.getLocalSubtreeHash(e,u,n,i,s),this.getRemoteSubtreeHash(e,r,u,n,i,s)]);if(d===l)return;let f=await this.getDefaultHashHex(u.length);if(l===f&&d!==f){let h=await this.getLocalLeaves(e,u,n,i,s);a.push(...h);return}if(d===f&&l!==f){let h=await this.getRemoteLeaves(e,r,u,n,i,s);o.push(...h);return}if(u.length>=LJ){let[h,p]=await Promise.all([this.getLocalLeaves(e,u,n,i,s),this.getRemoteLeaves(e,r,u,n,i,s)]),m=new Set(h),y=new Set(p);for(let w of h)y.has(w)||a.push(w);for(let w of p)m.has(w)||o.push(w);return}await Promise.all([c(u+"0"),c(u+"1")])};return await c(""),{onlyLocal:a,onlyRemote:o}}async getLocalSubtreeHash(e,r,n,i,a){return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Ce.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash??""}async getRemoteSubtreeHash(e,r,n,i,a,o){let s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Ce.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:o}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).hash??""}async getLocalLeaves(e,r,n,i,a){return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Ce.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries??[]}async getRemoteLeaves(e,r,n,i,a,o){let s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Ce.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:o}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return NJ({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return v8({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return uw(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch{i={protocols:[]}}let{protocols:a,delegateDid:o}=i,s=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(s.length!==0)for(let c of s)if(a.length===0)e.push({did:r,delegateDid:o,dwnUrl:c});else for(let u of a)e.push({did:r,delegateDid:o,dwnUrl:c,protocol:u})}return e}async getSyncPermissionGrantId(e,r,n){if(r)try{return(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Ce.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(i){console.error("SyncEngineLevel: Error fetching MessagesSync permission grant for delegate DID",i);return}}};x1.MAX_CONSECUTIVE_FAILURES=5,x1.MAX_BACKOFF_MULTIPLIER=4;var lw=x1;g();Mn();xs();xr();import{Level as kbe}from"level";g();g();g();xr();hn();g();g();var FJ=Tn(aA(),1);xr();var fw=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},gA=class{constructor({ttl:e="15m"}={}){this.cache=new vo.default({ttl:(0,FJ.default)(e)})}get(e){return fw(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return fw(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return fw(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return fw(this,void 0,void 0,function*(){this.cache.clear()})}open(){return fw(this,void 0,void 0,function*(){})}close(){return fw(this,void 0,void 0,function*(){})}};g();hn();Mn();g();var pw=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var hw;(function(t){t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.ParseError=-32700]="ParseError",t[t.TransportError=-32300]="TransportError",t[t.BadRequest=-50400]="BadRequest",t[t.Unauthorized=-50401]="Unauthorized",t[t.Forbidden=-50403]="Forbidden",t[t.Conflict=-50409]="Conflict",t[t.TooManyRequests=-50429]="TooManyRequests"})(hw||(hw={}));var mw=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),wA=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),GJ=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function wm(t){try{return JSON.parse(t)}catch{return null}}var b8=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},mbe=3,ybe=500,gbe=1e4,wbe=3e4,HJ=new Set([408,429,500,502,503,504]);function vbe(t,e){return t instanceof TypeError?!0:e?HJ.has(e.status):!1}function bbe(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function Pbe(t){let e=t.headers.get("retry-after");if(e===null)return;let r=Number(e);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var vA=class{constructor(e,r){var n,i,a;this.serverInfoCache=e??new gA,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:mbe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:ybe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:gbe}}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return b8(this,void 0,void 0,function*(){var r,n,i;let a=Yr.randomUuid(),o=mw(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),s={"dwn-request":JSON.stringify(o)},c={method:"POST",headers:s};e.data&&(s["content-type"]="application/octet-stream",c.body=e.data,c.duplex="half");let u=yield this.fetchWithRetry(e.dwnUrl,c);if(u.status===429){let h=parseInt((r=u.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new pw(h)}let d,l=u.headers.has("dwn-response");if(l){let h=wm(u.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=h}else{let h=yield u.text(),p=wm(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${u.status}`);d=p}if(d.error){let{code:h,message:p}=d.error;if(h===hw.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new pw(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=d.result;if(l){let h=new Uint8Array(yield u.arrayBuffer()),p=ar.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return b8(this,void 0,void 0,function*(){var r;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let o=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new pw(o)}if(a.ok){let o=yield a.json(),s={maxFileSize:o.maxFileSize,maxInFlight:o.maxInFlight,providerAuth:o.providerAuth,registrationRequirements:o.registrationRequirements,server:o.server,sdkVersion:o.sdkVersion,url:o.url,version:o.version,webSocketSupport:o.webSocketSupport};return this.serverInfoCache.set(e,s),s}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,r){return b8(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,o,s;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(wbe),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!HJ.has(p.status)||c===n)return p;s=p}catch(f){if(!vbe(f)||c===n)throw f;o=f}let u=s?Pbe(s):void 0,d=bbe(c,i,a),l=u!==void 0?Math.max(u,d):d;yield new Promise(f=>{setTimeout(f,l)})}if(s)return s;throw o})}};g();hn();var E1=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})};function P8(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var VJ=3e3,xbe=3e4,Ebe=1e3,Sbe=3e4,Abe=1/0,bA=class t{constructor(e,r,n,i){this.socket=e,this.responseTimeout=r,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return E1(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=VJ,responseTimeout:o=xbe}=n,s;try{s=yield t.createWebSocket(r,a)}catch(u){throw(i=n.onerror)===null||i===void 0||i.call(n,u),u}let c=new t(s,o,r,n);return c.wireSocket(s),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return E1(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=Yr.randomUuid());let a=o=>{let s=wm(P8(o.data));if(s.id===e.id)return this.messageHandlers.delete(e.id),r(s)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,r){return E1(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let u=wm(P8(c.data));u.id===n&&(u.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(u))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let o=yield this.request(e);return o.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:o}):{response:o,close:()=>E1(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=Yr.randomUuid(),n=wA(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),o=()=>{u(),n(a)},s=d=>{u(),i(d)},c=setTimeout(()=>{u(),a.close(),i(new Error("connect timed out"))},r),u=()=>{clearTimeout(c),a.removeEventListener("open",o),a.removeEventListener("error",s)};a.addEventListener("open",o),a.addEventListener("error",s)})}wireSocket(e){e.addEventListener("message",r=>{let n=wm(P8(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,o;if(this._isConnected=!1,this.closedByUser){(n=(r=this.options).onclose)===null||n===void 0||n.call(r);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((o=this.options.autoReconnect)!==null&&o!==void 0?o:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",r=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,r)})}rejectPendingRequests(){for(let[e,r]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:hw.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:Ebe,o=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:Sbe,s=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Abe,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:VJ,u=0,d=()=>E1(this,void 0,void 0,function*(){var l,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(u++,u>s){this.reconnecting=!1;return}(f=(l=this.options).onreconnecting)===null||f===void 0||f.call(l,u);let y=Math.min(a*Math.pow(2,u-1),o)*(.5+Math.random()*.5);if(yield new Promise(w=>setTimeout(w,y)),this.closedByUser){this.reconnecting=!1;return}try{let w=yield t.createWebSocket(this.url,c);this.socket=w,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(w),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield d()}});d()}};g();g();g();hn();g();hn();var yw=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},S1=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return yw(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:o,subscription:s}=e;return s?t.subscriptionRequest(i,a,o,s.handler,s.resubscribeFactory):t.processMessage(i,a,o)})}static createConnection(e){return yw(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield bA.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let o of n.values())o.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};t.connections.set(r,a),t.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,r,n){return yw(this,void 0,void 0,function*(){let i=Yr.randomUuid(),a=mw(i,"dwn.processMessage",{target:r,message:n}),{socket:o}=e,s=yield o.request(a),{error:c,result:u}=s;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return u.reply})}static subscriptionRequest(e,r,n,i,a){return yw(this,void 0,void 0,function*(){let o=Yr.randomUuid(),s=Yr.randomUuid(),c=wA(o,"rpc.subscribe.dwn.processMessage",{target:r,message:n},s),{socket:u,subscriptions:d}=e,{response:l,close:f}=yield u.subscribe(c,y=>{let{result:w,error:x}=y;if(x){let k=d.get(s);k&&k.subscription.close(),d.delete(s);return}let E=w.subscription;if(i(E),"cursor"in E&&E.cursor){let k=d.get(s);k&&(k.lastCursor=E.cursor),u.send(GJ(s,E.cursor))}}),{error:h,result:p}=l;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let y=()=>yw(this,void 0,void 0,function*(){d.delete(s),yield f()}),w={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(s,w),m.subscription.close=y}return m})}static resubscribeAll(e){return yw(this,void 0,void 0,function*(){let r=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of r)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield t.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};S1.connections=new Map;var A1=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function s(d){try{u(n.next(d))}catch(l){o(l)}}function c(d){try{u(n.throw(d))}catch(l){o(l)}}function u(d){d.done?a(d.value):i(d.value).then(s,c)}u((n=n.apply(t,e||[])).next())})},WJ;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(WJ||(WJ={}));var gw=class{constructor(e=[]){this.transportClients=new Map,e=[new x8,new E8,...e];for(let r of e)for(let n of r.transportProtocols)this.transportClients.set(n,r)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return A1(this,void 0,void 0,function*(){let r=new URL(e.url),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let r=new URL(e.dwnUrl),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return A1(this,void 0,void 0,function*(){let r=new URL(e),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},x8=class extends vA{sendDidRequest(e){return A1(this,void 0,void 0,function*(){let r=Yr.randomUuid(),n=mw(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let o=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(o.ok){if(a=yield o.json(),a.error){let{code:s,message:c}=a.error;throw new Error(`JSON RPC (${s}) - ${c}`)}}else throw new Error(`HTTP (${o.status}) - ${o.statusText}`)}catch(o){throw new Error(`Error encountered while processing response from ${e.url}: ${o.message}`)}return a.result})}},E8=class extends S1{sendDidRequest(e){return A1(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return A1(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var JJ=class t{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:r,permissionsApi:n,keyManager:i}=t.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=r,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await Ps.create({options:{publish:!0,gatewayUri:O.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:r}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:r,testDataLocation:n}){r??="memory",n??="__TESTDATA__";let i=L=>`${n}/${L}`,a=new Ss,o=new gw,s={keyStore:new ow,identityStore:new aw,didStore:new nw,clear:()=>{s.keyStore._protocolInitializedCache?.clear(),s.identityStore._protocolInitializedCache?.clear(),s.didStore._protocolInitializedCache?.clear()}},{agentVault:c,didApi:u,identityApi:d,keyManager:l,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:s}),m=new np({blockstoreLocation:i("DWN_DATASTORE")}),y=new ap({location:i("DWN_STATEINDEX")}),w=new sp,x=new op({location:i("DWN_RESUMABLETASKSTORE")}),E=new ip({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),k=await lp.createDwn({dataPath:n,dataStore:m,didResolver:u,stateIndex:y,eventLog:w,messageStore:E,resumableTaskStore:x}),T=new lp({dwn:k,localDwnStrategy:"off"}),D=new kbe(i("SYNC_STORE")),B=new lw({db:D}),C=new dw({syncEngine:B}),G=new e({agentVault:c,cryptoApi:a,didApi:u,dwnApi:T,identityApi:d,keyManager:l,permissionsApi:p,rpcClient:o,syncApi:C});return new t({agent:G,agentStores:r,didResolverCache:f,dwn:k,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:E,dwnResumableTaskStore:x,dwnStores:s,syncStore:D,vaultStore:h})}static useDiskStores({agent:e,testDataLocation:r,stores:n}){let i=m=>`${r}/${m}`,a=new hy({location:i("VAULT_STORE")}),o=new ym({keyDerivationWorkFactor:1,store:a}),{didStore:s,identityStore:c,keyStore:u}=n,d=new cp({location:i("DID_RESOLVERCACHE")}),l=new lm({agent:e,didMethods:[Ps,Ro],resolverCache:d,store:s}),f=new gm({agent:e,store:c}),h=new As({agent:e,keyStore:u}),p=new oc({agent:e});return{agentVault:o,didApi:l,didResolverCache:d,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new zl,n=new ym({keyDerivationWorkFactor:1,store:r}),i=new TS,a=new lm({agent:e,didMethods:[Ps,Ro],resolverCache:i,store:new iw}),o=new As({agent:e,keyStore:new sw}),s=new gm({agent:e,store:new cw}),c=new oc({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:s,keyManager:o,permissionsApi:c,vaultStore:r}}};g();hn();xs();g();xs();xr();hn();Mn();function _be({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return h1(t,"par");case"authorize":if(!r)throw new Error("authParam must be providied when building a token URL");return h1(t,`authorize/${r}.jwt`);case"callback":return h1(t,"callback");case"token":if(!n)throw new Error("tokenParam must be providied when building a token URL");return h1(t,`token/${n}.jwt`);default:throw new Error(`No matches for endpoint specified: ${e}`)}}async function Tbe(){let t=Yr.randomBytes(32),e=await Ou.digest({data:t}),r=he.uint8Array(e).toBase64Url();return{codeChallengeBytes:e,codeChallengeBase64Url:r}}async function Ibe(t){let e=Yr.randomBytes(16),r=Yr.randomBytes(16);return{...t,nonce:he.uint8Array(r).toBase64Url(),response_type:"id_token",response_mode:"direct_post",state:he.uint8Array(e).toBase64Url(),client_metadata:{subject_syntax_types_supported:["did:dht","did:jwk"]}}}async function Dbe({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=Yr.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),o=await gd.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),s=o.subarray(0,-16),c=o.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(s).toBase64Url(),he.uint8Array(c).toBase64Url()].join(".")}async function Rbe(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}async function Cbe({did:t,data:e}){let r=he.object({alg:"EdDSA",kid:t.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await t.getSigner()).sign({data:he.string(`${r}.${n}`).toUint8Array()}),o=he.uint8Array(a).toBase64Url();return`${r}.${n}.${o}`}async function ZJ({jwt:t}){let[e,r,n]=t.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error("OIDC: Object could not be verified due to missing 'kid' header value.");let{didDocument:a}=await Ro.resolve(i.kid.split("#")[0]);if(!a)throw new Error("OIDC: Object could not be verified due to Client DID resolution issue.");let{publicKeyJwk:o}=a.verificationMethod?.find(d=>d.id===i.kid)??{};if(!o)throw new Error("OIDC: Object could not be verified due to missing public key in DID document.");if(!await new pd().verify({key:o,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${r}`).toUint8Array()}))throw new Error("OIDC: Object failed verification due to invalid signature.");return he.base64Url(r).toObject()}var $be=async(t,e)=>{let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await YJ({jwe:n,encryption_key:e});return await ZJ({jwt:i})};async function YJ({jwe:t,encryption_key:e}){let[r,,n,i,a]=t.split("."),o=he.base64Url(e).toUint8Array(),c=he.base64Url(r).toUint8Array(),u=he.base64Url(n).toUint8Array(),d=he.base64Url(i).toUint8Array(),l=he.base64Url(a).toUint8Array(),f=new Uint8Array([...d,...l]),h=await gd.decryptRaw({data:f,keyBytes:o,nonce:u,additionalData:c});return he.uint8Array(h).toString()}async function Bbe(t,e,r){let[n,,i,a,o]=e.split("."),s=he.base64Url(n).toObject();if(!s.kid)throw new Error('JWE protected header is missing required "kid" property');let c=await Ro.resolve(s.kid.split("#")[0]),u=await is.deriveSharedKey(t,c.didDocument),d={...s,pin:r},l=he.object(d).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(o).toUint8Array(),m=new Uint8Array([...h,...p]),y=await gd.decryptRaw({data:m,keyBytes:u,nonce:f,additionalData:l});return he.uint8Array(y).toString()}async function Obe(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await Si.convertPublicKeyToX25519({publicKey:n}),o=await Si.convertPrivateKeyToX25519({privateKey:i}),s=await Zt.sharedSecret({privateKeyA:o,publicKeyB:a});return await Dy.deriveKeyBytes({baseKeyBytes:new Uint8Array(s),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function jbe({jwt:t,encryptionKey:e,delegateDidKeyId:r,randomPin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=Yr.randomBytes(24),o=he.object({...i,pin:n}).toUint8Array(),s=he.string(t).toUint8Array(),c=await gd.encryptRaw({data:s,keyBytes:e,nonce:a,additionalData:o}),u=c.subarray(0,-16),d=c.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(u).toBase64Url(),he.uint8Array(d).toBase64Url()].join(".")}function Mbe(t){return o8(t)?!0:t.interface===ge.Protocols&&t.method===me.Configure}async function Ube(t,e,r,n){let i=new oc({agent:r});Ni.log(`Creating permission grants for ${n.length} scopes given...`);let a=await Promise.all(n.map(s=>{let c=Mbe(s);return i.createGrant({delegated:c,store:!0,grantedTo:e.uri,scope:s,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})}));Ni.log(`Sending ${a.length} permission grants to remote DWN...`);let o=a.map(async s=>{let{encodedData:c,...u}=s.message,d=he.base64Url(c).toUint8Array(),{reply:l}=await r.sendDwnRequest({author:t,target:t,messageType:Ce.RecordsWrite,dataStream:new Blob([d]),rawMessage:u});if(l.status.code!==202&&l.status.code!==409)throw Ni.error(`Error sending RecordsWrite: ${l.status.detail}`),Ni.error(`RecordsWrite message: ${u}`),new Error(`Could not send the message. Error details: ${l.status.detail}`);return s.message});try{return await Promise.all(o)}catch(s){throw Ni.error(`Error during batch-send of permission grants: ${s}`),s}}async function Kbe(t,e,r){let n=await e.processDwnRequest({author:t,messageType:Ce.ProtocolsQuery,target:t,messageParams:{filter:{protocol:r.protocol}}});if(n.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${n.reply.status.detail}`);if(n.reply.entries===void 0||n.reply.entries.length===0){Ni.log(`Protocol does not exist, creating: ${r.protocol}`);let{reply:i,message:a}=await e.sendDwnRequest({author:t,target:t,messageType:Ce.ProtocolsConfigure,messageParams:{definition:r}});if(i.status.code!==202&&i.status.code!==409)throw new Error(`Could not send protocol: ${i.status.detail}`);await e.processDwnRequest({author:t,target:t,messageType:Ce.ProtocolsConfigure,rawMessage:a})}else{Ni.log(`Protocol already exists: ${r.protocol}`);let i=n.reply.entries[0],{reply:a}=await e.sendDwnRequest({author:t,target:t,messageType:Ce.ProtocolsConfigure,rawMessage:i});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`)}}async function Nbe(t,e,r,n){let i=await Ro.create(),a=await i.export(),o=e.permissionRequests.map(async p=>{let{protocolDefinition:m,permissionScopes:y}=p;if(!y.every(E=>"protocol"in E&&E.protocol===m.protocol))throw new Error("All permission scopes must match the protocol uri they are provided with.");return await Kbe(t,n,m),await is.createPermissionGrants(t,i,n,y)}),s=(await Promise.all(o)).flat();Ni.log("Generating auth response object...");let c=await is.createResponseObject({iss:t,sub:i.uri,aud:e.client_id,nonce:e.nonce,delegateGrants:s,delegatePortableDid:a});Ni.log("Signing auth response object...");let u=await is.signJwt({did:i,data:c}),d=await Ro.resolve(e.client_id),l=await is.deriveSharedKey(i,d?.didDocument);Ni.log("Encrypting auth response object...");let f=await is.encryptAuthResponse({jwt:u,encryptionKey:l,delegateDidKeyId:i.document.verificationMethod[0].id,randomPin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Ni.log(`Sending auth response object to Web5 Connect server: ${e.redirect_uri}`),await fetch(e.redirect_uri,{body:h,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var is={createAuthRequest:Ibe,encryptAuthRequest:Dbe,getAuthRequest:$be,decryptAuthRequest:YJ,createPermissionGrants:Ube,createResponseObject:Rbe,encryptAuthResponse:jbe,decryptAuthResponse:Bbe,deriveSharedKey:Obe,signJwt:Cbe,verifyJwt:ZJ,buildOidcUrl:_be,generateCodeChallenge:Tbe,submitAuthResponse:Nbe};xr();Mn();async function Lbe({displayName:t,connectServerUrl:e,walletUri:r,permissionRequests:n,onWalletUriReady:i,validatePin:a}){let o=await Ro.create(),s=Yr.randomBytes(32),c=is.buildOidcUrl({baseURL:e,endpoint:"callback"}),u=await is.createAuthRequest({client_id:o.uri,scope:"openid did:jwk",redirect_uri:c,permissionRequests:n,displayName:t}),d=await is.signJwt({did:o,data:u});if(!d)throw new Error("Unable to sign requestObject");let l=await is.encryptAuthRequest({jwt:d,encryptionKey:s}),f=is.buildOidcUrl({baseURL:e,endpoint:"pushedAuthorizationRequest"}),h=await fetch(f,{body:JSON.stringify({request:l}),method:"POST",headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(3e4)});if(!h.ok)throw new Error(`${h.status}: ${h.statusText}`);let p=await h.json();Ni.log(`Wallet URI: ${r}`);let m=new URL(r);m.searchParams.set("request_uri",p.request_uri),m.searchParams.set("encryption_key",he.uint8Array(s).toBase64Url()),i(m.toString());let y=is.buildOidcUrl({baseURL:e,endpoint:"token",tokenParam:u.state}),w=await XW(()=>fetch(y,{signal:AbortSignal.timeout(3e4)}));if(w){let x=await w?.text(),E=await a(),k=await is.decryptAuthResponse(o,x,E),T=await is.verifyJwt({jwt:k});return{delegateGrants:T.delegateGrants,delegatePortableDid:T.delegatePortableDid,connectedDid:T.iss}}}function qbe({definition:t,permissions:e}){let r=[];r.push({protocol:t.protocol,interface:ge.Protocols,method:me.Query}),r.push({protocol:t.protocol,interface:ge.Messages,method:me.Read});for(let n of e)switch(n){case"write":r.push({protocol:t.protocol,interface:ge.Records,method:me.Write});break;case"read":r.push({protocol:t.protocol,interface:ge.Records,method:me.Read});break;case"delete":r.push({protocol:t.protocol,interface:ge.Records,method:me.Delete});break;case"query":r.push({protocol:t.protocol,interface:ge.Records,method:me.Query});break;case"subscribe":r.push({protocol:t.protocol,interface:ge.Records,method:me.Subscribe});break;case"configure":r.push({protocol:t.protocol,interface:ge.Protocols,method:me.Configure});break}return{protocolDefinition:t,permissionScopes:r}}var ant={initClient:Lbe,createPermissionRequestForProtocol:qbe};g();xr();xs();var S8=class t{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:r,agentDid:n,agentVault:i,cryptoApi:a,didApi:o,dwnApi:s,identityApi:c,keyManager:u,permissionsApi:d,rpcClient:l,syncApi:f}={}){return i??=new ym({keyDerivationWorkFactor:21e4,store:new hy({location:`${e}/VAULT_STORE`})}),a??=new Ss,o??=new lm({didMethods:[Ps,Ro],resolverCache:new cp({location:`${e}/DID_RESOLVERCACHE`}),store:new nw}),s??=new lp({dwn:await lp.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"}),r&&s.setLocalDwnStrategy(r),c??=new gm({store:new aw}),u??=new As({keyStore:new ow}),d??=new oc,l??=new gw,f??=new dw({syncEngine:new lw({dataPath:e})}),new t({agentDid:n,agentVault:i,cryptoApi:a,didApi:o,dwnApi:s,keyManager:u,permissionsApi:d,identityApi:c,rpcClient:l,syncApi:f})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){return r=await this.vault.initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}),r}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}},knt=S8;export{Ss as AgentCryptoApi,lm as AgentDidApi,cp as AgentDidResolverCache,lp as AgentDwnApi,gm as AgentIdentityApi,oc as AgentPermissionsApi,dw as AgentSyncApi,QW as AnonymousDwnApi,Qg as BearerIdentity,Dve as DISCOVERY_DIR,Rve as DISCOVERY_FILENAME,gJ as DWN_PROTOCOL_SCHEME,wJ as DWN_REGISTER_PATH,Ave as DidInterface,Oa as DwnConstant,ci as DwnContentEncryptionAlgorithm,dp as DwnDataStore,zt as DwnDateSort,nw as DwnDidStore,cA as DwnDiscoveryFile,aw as DwnIdentityStore,Ce as DwnInterface,Mt as DwnKeyDerivationScheme,ow as DwnKeyStore,$r as DwnPermissionGrant,$d as DwnPermissionRequest,ft as DwnPermissionsProtocol,S8 as EnboxUserAgent,ym as HdIdentityVault,up as InMemoryDataStore,iw as InMemoryDidStore,cw as InMemoryIdentityStore,sw as InMemoryKeyStore,fm as LocalDwnDiscovery,As as LocalKeyManager,is as Oidc,JJ as PlatformAgentTestHarness,lw as SyncEngineLevel,ant as WalletConnect,knt as Web5UserAgent,nJ as buildContextKeyDecrypter,hQe as buildDwnDiscoveryRedirectUrl,fQe as buildDwnRegisterUrl,pm as buildEncryptionInput,oJ as buildKmsDecryptCallback,h1 as concatenateUrl,Ive as createNodeDiscoveryFileFs,yJ as decodeDwnDiscoveryPayload,lA as deriveContextEncryptionInput,c8 as detectNewParticipants,ic as dwnMessageConstructors,uJ as eagerSendContextKeyRecord,Ove as encodeDwnDiscoveryPayload,uA as encryptAndComputeCid,cJ as ensureKeyDeliveryProtocol,lJ as fetchContextKeyRecord,p1 as getDwnServiceEndpointUrls,g1 as getEncryptionKeyDeriver,yl as getEncryptionKeyInfo,hm as getKeyDecrypter,IYe as getPaginationCursor,_Ye as getRecordAuthor,vve as getRecordMessageCid,TYe as getRecordProtocolRole,DXe as getRootContextId,aJ as getRuleSetAtPath,s8 as hasRelationalReadAccess,rJ as isDidRequest,$ve as isDwnMessage,tu as isDwnRequest,lbe as isIdentityMetadata,Bve as isMessagesPermissionScope,a8 as isMultiPartyContext,Wet as isPortableIdentity,o8 as isRecordPermissionScope,i8 as isRecordsType,hl as isRecordsWrite,dA as ivLength,_ve as localDwnHostCandidates,kve as localDwnPortCandidates,Tve as localDwnServerName,sJ as maybeDecryptReply,y1 as normalizeBaseUrl,pQe as parseDwnRegisterUrl,XW as pollWithTtl,mQe as readDwnDiscoveryPayloadFromUrl,iJ as resolveKeyDecrypter,fJ as upgradeExternalRootRecord,dJ as writeContextKeyRecord};
2061
2061
  /*! Bundled license information:
2062
2062
 
2063
2063
  ieee754/index.js: