@enbox/api 0.5.10 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs CHANGED
@@ -2055,7 +2055,7 @@ zebra
2055
2055
  zero
2056
2056
  zone
2057
2057
  zoo`.split(`
2058
- `);Fo();Kt();y();y();rn();y();Kt();rn();y();Kt();rn();y();rn();rn();Jn();y();Kt();rn();y();Fo();y();Kt();y();Jn();Kt();var Cc=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Yz=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},fi=class t{get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}constructor({agent:e}={}){this._cachedPermissions=new Kl.default({ttl:60*1e3}),this._agent=e}getPermissionForRequest(e){return Cc(this,arguments,void 0,function*({connectedDid:r,delegateDid:n,delegate:i,messageType:a,protocol:s,cached:o=!1}){let d=[r,n,a,s].join("~"),u=o?this._cachedPermissions.get(d):void 0;if(u)return u;let c=yield this.fetchGrants({author:n,target:n,grantor:r,grantee:n}),l=yield t.matchGrantFromArray(r,n,{messageType:a,protocol:s},c,i);if(!l)throw new Error(`CachedPermissions: No permissions found for ${a}: ${s}`);return this._cachedPermissions.set(d,l),l})}fetchGrants(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantee:i,grantor:a,protocol:s,remote:o=!1,checkRevoked:d=!0}){let u=s?{protocol:s}:void 0,c={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:a,recipient:i,protocol:zt.uri,protocolPath:zt.grantPath,tags:u}}},{reply:l}=o?yield this.agent.sendDwnRequest(c):yield this.agent.processDwnRequest(c);if(l.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${l.status.detail}`);let f=d?yield this.fetchRevokedGrantIds({author:r,target:n,grantor:a,remote:o,tags:u}):new Set,h=[];for(let p of l.entries){if(f.has(p.recordId))continue;let m=dr.parse(p);h.push({grant:m,message:p})}return h})}fetchRevokedGrantIds(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantor:i,remote:a,tags:s}){let o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:i,protocol:zt.uri,protocolPath:zt.revocationPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${d.status.detail}`);let u=new Set;for(let c of d.entries)c.descriptor.parentId!==void 0&&u.add(c.descriptor.parentId);return u})}fetchRequests(e){return Cc(this,arguments,void 0,function*({author:r,target:n,protocol:i,remote:a=!1}){let s=i?{protocol:i}:void 0,o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{protocol:zt.uri,protocolPath:zt.requestPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${d.status.detail}`);let u=[];for(let c of d.entries){let l=Ia.parse(c);u.push({request:l,message:c})}return u})}isGrantRevoked(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantRecordId:i,remote:a=!1}){let s={author:r,target:n,messageType:Te.RecordsRead,messageParams:{filter:{parentId:i,protocol:zt.uri,protocolPath:zt.revocationPath}}},{reply:o}=a?yield this.agent.sendDwnRequest(s):yield this.agent.processDwnRequest(s);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}`)})}createGrant(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={recipient:a.grantedTo,protocol:zt.uri,protocolPath:zt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{grant:dr.parse(f),message:f}})}createRequest(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={protocol:zt.uri,protocolPath:zt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{request:Ia.parse(f),message:f}})}createRevocation(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=Ue.object(s).toUint8Array(),d;zt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let u={parentContextId:i.id,protocol:zt.uri,protocolPath:zt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(o).toBase64Url()})}})}clear(){return Cc(this,void 0,void 0,function*(){this._cachedPermissions.clear()})}static matchGrantFromArray(e,r,n,i){return Cc(this,arguments,void 0,function*(a,s,o,d,u=!1){let c;for(let l of d){let{grant:f,message:h}=l;if(u===!0&&f.delegated!==!0)continue;let{messageType:p,protocol:m,protocolPath:g,contextId:_}=o;if(this.matchScopeFromGrant(a,s,p,f,m,g,_)){if(f.scope.interface+f.scope.method===p)return{grant:f,message:h};c||(c={grant:f,message:h})}}return c})}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,u=d.interface+d.method;if(u===n||u===Te.MessagesRead&&(n===Te.MessagesSync||n===Te.MessagesSubscribe))if(YI(n)){let l=d;if(l.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(l)||l.protocolPath!==void 0&&l.protocolPath===s||l.contextId!==void 0&&o?.startsWith(l.contextId))return!0}else{let l=d;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}};y();var s7=wn(pP(),1);Jn();import{Level as Xfe}from"level";y();Jn();function Qz(t){let e=t.descriptor;return e.interface!==Ge.Records||e.method!==ze.Write?!1:e.dateCreated===e.messageTimestamp}function Em(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let l=0;l<t.length;l++){let f=t[l];r.set(l,f);let h=f.message.descriptor;if(h.interface===Ge.Protocols&&h.method===ze.Configure){let p=(e=h.definition)===null||e===void 0?void 0:e.protocol;p&&n.set(p,l)}if(h.interface===Ge.Records&&h.method===ze.Write){let p=f.message.recordId;Qz(f.message)&&p&&i.set(p,l),h.protocol===zt.uri&&h.protocolPath===zt.grantPath&&p&&a.set(p,l)}}let s=new Map,o=new Array(t.length).fill(0),d=(l,f)=>{if(l===f)return;s.has(l)||s.set(l,new Set);let h=s.get(l);h.has(f)||(h.add(f),o[f]++)};for(let l=0;l<t.length;l++){let f=t[l].message.descriptor;if(f.interface===Ge.Records){let p=f.protocol;p&&n.has(p)&&d(n.get(p),l)}if(f.interface===Ge.Records&&f.parentId){let p=f.parentId;i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Write){let p=t[l].message.recordId;p&&!Qz(t[l].message)&&i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Delete){let p=f.recordId;p&&i.has(p)&&d(i.get(p),l)}let h=f.permissionGrantId;h&&a.has(h)&&d(a.get(h),l)}let u=[];for(let l=0;l<t.length;l++)o[l]===0&&u.push(l);let c=[];for(;u.length>0;){let l=u.shift();c.push(r.get(l));let f=s.get(l);if(f)for(let h of f)o[h]--,o[h]===0&&u.push(h)}if(c.length<t.length){let l=new Set(c);for(let f=0;f<t.length;f++){let h=r.get(f);l.has(h)||c.push(h)}}return c}y();Jn();var tp=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Jfe=1048576;function e7(t){var e,r;return t.status.code===202||t.status.code===204||t.status.code===409||((e=t.entry)===null||e===void 0?void 0:e.message.descriptor.interface)===Ge.Records&&((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.method)===ze.Delete&&t.status.code===404}function t7(t){return tp(this,void 0,void 0,function*(){try{return yield Se.getCid(t)}catch{return"unknown"}})}function r7(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:d}){let u=[];if(s)for(let m of s){if(!m.message)continue;let g={message:m.message};if(m.encodedData){let _=ke.base64UrlToBytes(m.encodedData);g.bufferedData=_,g.dataStream=new ReadableStream({start(v){v.enqueue(_),v.close()}})}u.push(g)}let c=a.length>0?yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:d}):[],l=[...u,...c],f=Em(l);yield Zfe(f);let h=3,p=f;for(let m=0;m<=h&&p.length>0;m++){let g=[];for(let _ of p){let v=_.bufferedData?new ReadableStream({start(T){T.enqueue(_.bufferedData),T.close()}}):_.dataStream,E=yield o.dwn.processRawMessage(e,_.message,{dataStream:v});e7(E)||g.push(_)}if(g.length>0){let _=[],v=[];for(let E of g)if(E.bufferedData||!E.dataStream)v.push(E);else{let T=yield t7(E.message);_.push(T)}if(_.length>0){let E=yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:_,agent:o,permissionsApi:d});v.push(...E)}p=Em(v)}else p=[]}})}function Zfe(t){return tp(this,void 0,void 0,function*(){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:d,value:u}=yield a.read();if(d)break;if(n+=u.byteLength,n>Jfe){i=!0;break}r.push(u)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}})}function Xz(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let d=[],u;if(n)try{u=(yield o.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id}catch(f){return console.error("SyncEngineLevel: pull - Error fetching MessagesRead permission grant for delegate DID",f),d}let c=4,l=0;for(;l<a.length;){let f=a.slice(l,l+c);l+=c;let h=yield Promise.all(f.map(p=>tp(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Te.MessagesRead,granteeDid:n,messageParams:{messageCid:p,permissionGrantId:u}}),v;try{v=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${p} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(v.status.code!==200||!(!((g=v.entry)===null||g===void 0)&&g.message))return;let E=v.entry,T;return vm(E)&&E.data&&(T=E.data),{message:E.message,dataStream:T}})));for(let p of h)p&&d.push(p)}return d})}function QI(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var d;let u=[];for(let l of a){let f=yield Yfe({author:e,messageCid:l,delegateDid:n,protocol:i,agent:s,permissionsApi:o});f&&u.push(f)}let c=Em(u);for(let l of c)try{let f=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:l.dataStream,message:l.message});if(!e7(f)){let h=yield t7(l.message);console.error(`SyncEngineLevel: push failed for ${h}: ${f.status.code} ${f.status.detail}`)}}catch(f){let h=(d=f.message)!==null&&d!==void 0?d:f;throw new Error(`SyncEngineLevel: push to ${r} failed: ${h}`)}})}function Yfe(t){return tp(this,arguments,void 0,function*({author:e,delegateDid:r,protocol:n,messageCid:i,agent:a,permissionsApi:s}){let o;if(r)try{o=(yield s.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(l){console.error("SyncEngineLevel: push - Error fetching MessagesRead permission grant for delegate DID",l);return}let{reply:d}=yield a.dwn.processRequest({author:e,target:e,messageType:Te.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(d.status.code!==200||!d.entry)return;let u=d.entry,c={message:u.message};return vm(u)&&u.data&&(c.dataStream=u.data),c})}var Rt=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Qfe=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(s){return new Promise(function(o,d){s=t[a](s),i(o,d,s.done,s.value)})}}function i(a,s,o,d){Promise.resolve(d).then(function(u){a({value:u,done:o})},s)}},n7=16,i7=8,epe=4,XI=class{constructor(e){this._waiting=[],this._permits=e}acquire(){return Rt(this,void 0,void 0,function*(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})})}release(){let e=this._waiting.shift();e?e():this._permits++}run(e){return Rt(this,void 0,void 0,function*(){yield this.acquire();try{return yield e()}finally{this.release()}})}},o7="^",tpe=250,Sm=class t{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 fi({agent:e}),this._db=n||new Xfe(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 fi({agent:e})}get connectivityState(){return this._connectivityState}clear(){return Rt(this,void 0,void 0,function*(){yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return Rt(this,void 0,void 0,function*(){yield this._db.close()})}registerIdentity(e){return Rt(this,arguments,void 0,function*({did:r,options:n}){let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);n??(n={protocols:[]}),yield i.put(r,JSON.stringify(n))})}unregisterIdentity(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(e)))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);yield r.del(e)})}getIdentityOptions(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");try{let n=yield 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}.`)}})}updateIdentityOptions(e){return Rt(this,arguments,void 0,function*({did:r,options:n}){let i=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(r)))throw new Error(`SyncEngineLevel: Identity with DID ${r} is not registered.`);yield i.put(r,JSON.stringify(n))})}sync(e){return Rt(this,void 0,void 0,function*(){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=yield this.getSyncTargets(),n=new Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:u}=a;if(!n.has(d))try{let c=yield this.getLocalRoot(s,o,u),l=yield this.getRemoteRoot(s,d,o,u);if(c===l)continue;let f=yield this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:u});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);yield this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&(yield this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:f.onlyLocal}))}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}})}startSync(e){return Rt(this,void 0,void 0,function*(){var r,n;let i=(r=e.mode)!==null&&r!==void 0?r:"poll",a=(n=e.interval)!==null&&n!==void 0?n:i==="live"?"5m":"2m",s=(0,s7.default)(a);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&(yield this.teardownLiveSync()),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=i,i==="live"?yield this.startLiveSync(s):yield this.startPollSync(s)})}stopSync(){return Rt(this,arguments,void 0,function*(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,yield new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),yield this.teardownLiveSync()})}startPollSync(e){return Rt(this,void 0,void 0,function*(){let r=()=>Rt(this,void 0,void 0,function*(){if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),t.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||(yield this.sync())})}startLiveSync(e){return Rt(this,void 0,void 0,function*(){try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();for(let i of r)try{yield this.openLivePullSubscription(i),yield this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=()=>Rt(this,void 0,void 0,function*(){if(!this._syncLock)try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}});this._syncIntervalId=setInterval(n,e)})}teardownLiveSync(){return Rt(this,void 0,void 0,function*(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.clear();for(let e of this._liveSubscriptions)try{yield e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{yield e.close()}catch{}this._localSubscriptions=[]})}openLivePullSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=yield this.getCursor(s),d=a?[{protocol:a}]:[],u;if(n)try{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(p){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",p);return}}let c=h=>Rt(this,void 0,void 0,function*(){if(h.type==="eose"){yield this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);yield this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}yield this.setCursor(s,h.cursor)}}),f=(yield this.agent.dwn.sendRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:u},subscriptionHandler:c})).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:()=>Rt(this,void 0,void 0,function*(){yield f.subscription.close()})}),this._connectivityState="online"})}openLocalPushSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;if(n)try{o=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let d=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()},tpe)},c=(yield this.agent.dwn.processRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:()=>Rt(this,void 0,void 0,function*(){yield c.subscription.close()})})})}flushPendingPushes(){return Rt(this,void 0,void 0,function*(){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:s,cids:o}=r;if(o.length!==0)try{yield QI({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}})}buildCursorKey(e,r,n){let i=`${e}${o7}${r}`;return n?`${i}${o7}${n}`:i}getCursor(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{return yield r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}setCursor(e,r){return Rt(this,void 0,void 0,function*(){yield this._db.sublevel("syncCursors").put(e,r)})}extractDataStream(e){if(vm(e)&&e.data)return e.data}tryGetCidSync(e){var r;let n;return Se.getCid(e).then(i=>{n=i}),(r=n??e.messageCid)!==null&&r!==void 0?r:void 0}getDefaultHashHex(e){return Rt(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield Ng(),i=new Map;for(let a=0;a<=n7;a++)i.set(a,md(n[a]));this._defaultHashHex=i}return(r=this._defaultHashHex.get(e))!==null&&r!==void 0?r:""})}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}getLocalRoot(e,r,n){return Rt(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let u=n!==void 0?yield a.getProtocolRoot(e,n):yield a.getRoot(e);return md(u)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return Rt(this,void 0,void 0,function*(){var a;let s=yield this.getSyncPermissionGrantId(e,n,i),o=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:s}});return(a=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).root)!==null&&a!==void 0?a:""})}walkTreeDiff(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){let s=[],o=[],d=yield this.getSyncPermissionGrantId(r,i,a),u=new XI(epe),c=l=>Rt(this,void 0,void 0,function*(){let[f,h]=yield Promise.all([this.getLocalSubtreeHash(r,l,i,a,d),u.run(()=>this.getRemoteSubtreeHash(r,n,l,i,a,d))]);if(f===h)return;let p=yield this.getDefaultHashHex(l.length);if(h===p&&f!==p){let m=yield this.getLocalLeaves(r,l,i,a,d);s.push(...m);return}if(f===p&&h!==p){let m=yield u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d));o.push(...m);return}if(l.length>=n7){let[m,g]=yield Promise.all([this.getLocalLeaves(r,l,i,a,d),u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d))]),_=new Set(m),v=new Set(g);for(let E of m)v.has(E)||s.push(E);for(let E of g)_.has(E)||o.push(E);return}yield Promise.all([c(l+"0"),c(l+"1")])});return yield c(""),{onlyLocal:s,onlyRemote:o}})}diffWithRemote(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let d=yield this.collectLocalSubtreeHashes(r,a,i7),u=yield this.getSyncPermissionGrantId(r,i,a),c=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:d,depth:i7,permissionGrantId:u}}),l=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:c.message});if(l.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${l.status.code}: ${l.status.detail}`);let f=yield this.getSyncPermissionGrantId(r,i,a),h=[];for(let p of(s=l.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,p,i,a,f);h.push(...m)}return{onlyRemote:(o=l.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:h}})}collectLocalSubtreeHashes(e,r,n){return Rt(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(d,u)=>Rt(this,void 0,void 0,function*(){let c;if(s){let l=t.parseBitPrefix(d),f=r!==void 0?yield s.getProtocolSubtreeHash(e,r,l):yield s.getSubtreeHash(e,l);c=md(f)}else c=yield this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(u>=n){i[d]=c;return}yield Promise.all([o(d+"0",u+1),o(d+"1",u+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r),l=i!==void 0?yield o.getProtocolSubtreeHash(e,i,c):yield o.getSubtreeHash(e,c);return md(l)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getRemoteSubtreeHash(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).hash)!==null&&o!==void 0?o:""})}getLocalLeaves(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r);return i!==void 0?yield o.getProtocolLeaves(e,i,c):yield o.getLeaves(e,c)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}getRemoteLeaves(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).entries)!==null&&o!==void 0?o:[]})}pullMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){return r7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi})})}pushMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return QI({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Em(e)}getSyncTargets(){return Rt(this,void 0,void 0,function*(){var e,r,n,i;let a=[];try{for(var s=!0,o=Qfe(this._db.sublevel("registeredIdentities").iterator()),d;d=yield o.next(),e=d.done,!e;s=!0){i=d.value,s=!1;let[u,c]=i,l;try{l=JSON.parse(c)}catch{l={protocols:[]}}let{protocols:f,delegateDid:h}=l,p=yield this.agent.dwn.getDwnEndpointUrlsForTarget(u);if(p.length!==0)for(let m of p)if(f.length===0)a.push({did:u,delegateDid:h,dwnUrl:m});else for(let g of f)a.push({did:u,delegateDid:h,dwnUrl:m,protocol:g})}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return a})}getSyncPermissionGrantId(e,r,n){return Rt(this,void 0,void 0,function*(){if(r)try{return(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(i){console.error("SyncEngineLevel: Error fetching MessagesSync permission grant for delegate DID",i);return}})}};Sm.MAX_CONSECUTIVE_FAILURES=5;Sm.MAX_BACKOFF_MULTIPLIER=4;y();Jn();Fo();Kt();import{Level as VWe}from"level";y();y();y();Kt();rn();y();y();var a7=wn(pP(),1);Kt();var Tm=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},mP=class{constructor({ttl:e="15m"}={}){this.cache=new Kl.default({ttl:(0,a7.default)(e)})}get(e){return Tm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Tm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Tm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Tm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Tm(this,void 0,void 0,function*(){})}close(){return Tm(this,void 0,void 0,function*(){})}};y();rn();Jn();y();var km=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Am;(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"})(Am||(Am={}));var Dm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),yP=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),c7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function rp(t){try{return JSON.parse(t)}catch{return null}}var eR=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},rpe=3,npe=500,ipe=1e4,ope=3e4,d7=new Set([408,429,500,502,503,504]);function spe(t,e){return t instanceof TypeError?!0:e?d7.has(e.status):!1}function ape(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function cpe(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 gP=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new mP,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rpe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:npe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ipe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return eR(this,void 0,void 0,function*(){var r,n,i;let a=gi.randomUuid(),s=Dm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Hi.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let u=yield this.fetchWithRetry(e.dwnUrl,d);if(u.status===429){let h=parseInt((r=u.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new km(h)}let c,l=u.headers.has("dwn-response");if(l){let h=rp(u.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield u.text(),p=rp(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${u.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===Am.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new km(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(l){let h=new Uint8Array(yield u.arrayBuffer()),p=Hi.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return eR(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 s=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new km(s)}if(a.ok){let s=yield a.json(),o={maxFileSize:s.maxFileSize,maxInFlight:s.maxInFlight,providerAuth:s.providerAuth,registrationRequirements:s.registrationRequirements,server:s.server,sdkVersion:s.sdkVersion,url:s.url,version:s.version,webSocketSupport:s.webSocketSupport};return this.serverInfoCache.set(e,o),o}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 eR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(ope),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!d7.has(p.status)||d===n)return p;o=p}catch(f){if(!spe(f)||d===n)throw f;s=f}let u=o?cpe(o):void 0,c=ape(d,i,a),l=u!==void 0?Math.max(u,c):c;yield new Promise(f=>{setTimeout(f,l)})}if(o)return o;throw s})}};y();rn();var g0=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})};function tR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var u7=3e3,dpe=3e4,upe=1e3,lpe=3e4,fpe=1/0,wP=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 g0(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=u7,responseTimeout:s=dpe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(u){throw(i=n.onerror)===null||i===void 0||i.call(n,u),u}let d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return g0(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gi.randomUuid());let a=s=>{let o=rp(tR(s.data));if(o.id===e.id)return this.messageHandlers.delete(e.id),r(o)};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 g0(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=d=>{let u=rp(tR(d.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 s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>g0(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gi.randomUuid(),n=yP(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),s=()=>{u(),n(a)},o=c=>{u(),i(c)},d=setTimeout(()=>{u(),a.close(),i(new Error("connect timed out"))},r),u=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=rp(tR(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,s;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),((s=this.options.autoReconnect)!==null&&s!==void 0?s:!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:Am.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:upe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:lpe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fpe,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:u7,u=0,c=()=>g0(this,void 0,void 0,function*(){var l,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(u++,u>o){this.reconnecting=!1;return}(f=(l=this.options).onreconnecting)===null||f===void 0||f.call(l,u);let g=Math.min(a*Math.pow(2,u-1),s)*(.5+Math.random()*.5);if(yield new Promise(_=>setTimeout(_,g)),this.closedByUser){this.reconnecting=!1;return}try{let _=yield t.createWebSocket(this.url,d);this.socket=_,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(_),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};y();y();y();rn();y();rn();var Im=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},w0=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return Im(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 d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return Im(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield wP.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let s of n.values())s.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 Im(this,void 0,void 0,function*(){let i=gi.randomUuid(),a=Dm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:u}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return u.reply})}static subscriptionRequest(e,r,n,i,a){return Im(this,void 0,void 0,function*(){let s=gi.randomUuid(),o=gi.randomUuid(),d=yP(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:u,subscriptions:c}=e,{response:l,close:f}=yield u.subscribe(d,g=>{let{result:_,error:v}=g;if(v){let T=c.get(o);T&&T.subscription.close(),c.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let T=c.get(o);T&&(T.lastCursor=E.cursor),u.send(c7(o,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 g=()=>Im(this,void 0,void 0,function*(){c.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return Im(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{}})}};w0.connections=new Map;var v0=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},l7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(l7||(l7={}));var Rm=class{constructor(e=[]){this.transportClients=new Map,e=[new rR,new nR,...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 v0(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 v0(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)})}},rR=class extends gP{sendDidRequest(e){return v0(this,void 0,void 0,function*(){let r=gi.randomUuid(),n=Dm(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 s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},nR=class extends w0{sendDidRequest(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Fo();Kt();rn();Jn();y();Kt();Fo();var vP=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:y0.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:y0.Resolve});return n}};y();y();Kt();var b0=class{constructor(e){let{rawMessage:r,initialWrite:n,encodedData:i,data:a,remoteOrigin:s,anonymousDwn:o}=e;this._anonymousDwn=o,this._remoteOrigin=s;try{this._author=Wo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Wo(n)??this._author:this._author}catch{this._creator=this._author}this._descriptor=r.descriptor,this._recordId=r.recordId,this._contextId=r.contextId,this._initialWrite=n,this._authorization=r.authorization,this._attestation=r.attestation,this._encryption=r.encryption,i&&(this._encodedData=new Blob([Ue.base64Url(i).toUint8Array()],{type:this.dataFormat})),a&&(this._readableStream=a)}get id(){return this._recordId}get contextId(){return this._contextId}get dateCreated(){return this._descriptor.dateCreated}get parentId(){return this._descriptor.parentId}get protocol(){return this._descriptor.protocol}get protocolPath(){return this._descriptor.protocolPath}get recipient(){return this._descriptor.recipient}get schema(){return this._descriptor.schema}get dataFormat(){return this._descriptor.dataFormat}get dataCid(){return this._descriptor.dataCid}get dataSize(){return this._descriptor.dataSize}get datePublished(){return this._descriptor.datePublished}get published(){return this._descriptor.published}get tags(){return this._descriptor.tags}get author(){return this._author}get creator(){return this._creator}get timestamp(){return this._descriptor.messageTimestamp}get encryption(){return this._encryption}get authorization(){return this._authorization}get attestation(){return this._attestation}get initialWrite(){return this._initialWrite}get remoteOrigin(){return this._remoteOrigin}get data(){let e=this;return{async blob(){return new Blob([await Co.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Co.consumeToBytes({readableStream:await this.stream()})},async json(){return await Co.consumeToJson({readableStream:await this.stream()})},async text(){return await Co.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Co.fromBlob(e._encodedData);if(e._readableStream){let n=e._readableStream;return e._readableStream=void 0,n}else return await e.readRecordData()},then(n,i){return this.stream().then(n,i)},catch(n){return this.stream().catch(n)}}}toJSON(){return{attestation:this.attestation,author:this.author,authorization:this.authorization,contextId:this.contextId,dataCid:this.dataCid,dataFormat:this.dataFormat,dataSize:this.dataSize,dateCreated:this.dateCreated,datePublished:this.datePublished,encryption:this.encryption,parentId:this.parentId,protocol:this.protocol,protocolPath:this.protocolPath,published:this.published,recipient:this.recipient,recordId:this.id,schema:this.schema,tags:this.tags,timestamp:this.timestamp}}toString(){let e=`ReadOnlyRecord: {
2058
+ `);Fo();Kt();y();y();rn();y();Kt();rn();y();Kt();rn();y();rn();rn();Jn();y();Kt();rn();y();Fo();y();Kt();y();Jn();Kt();var Cc=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Yz=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},fi=class t{get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}constructor({agent:e}={}){this._cachedPermissions=new Kl.default({ttl:60*1e3}),this._agent=e}getPermissionForRequest(e){return Cc(this,arguments,void 0,function*({connectedDid:r,delegateDid:n,delegate:i,messageType:a,protocol:s,cached:o=!1}){let d=[r,n,a,s].join("~"),u=o?this._cachedPermissions.get(d):void 0;if(u)return u;let c=yield this.fetchGrants({author:n,target:n,grantor:r,grantee:n}),l=yield t.matchGrantFromArray(r,n,{messageType:a,protocol:s},c,i);if(!l)throw new Error(`CachedPermissions: No permissions found for ${a}: ${s}`);return this._cachedPermissions.set(d,l),l})}fetchGrants(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantee:i,grantor:a,protocol:s,remote:o=!1,checkRevoked:d=!0}){let u=s?{protocol:s}:void 0,c={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:a,recipient:i,protocol:zt.uri,protocolPath:zt.grantPath,tags:u}}},{reply:l}=o?yield this.agent.sendDwnRequest(c):yield this.agent.processDwnRequest(c);if(l.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${l.status.detail}`);let f=d?yield this.fetchRevokedGrantIds({author:r,target:n,grantor:a,remote:o,tags:u}):new Set,h=[];for(let p of l.entries){if(f.has(p.recordId))continue;let m=dr.parse(p);h.push({grant:m,message:p})}return h})}fetchRevokedGrantIds(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantor:i,remote:a,tags:s}){let o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:i,protocol:zt.uri,protocolPath:zt.revocationPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${d.status.detail}`);let u=new Set;for(let c of d.entries)c.descriptor.parentId!==void 0&&u.add(c.descriptor.parentId);return u})}fetchRequests(e){return Cc(this,arguments,void 0,function*({author:r,target:n,protocol:i,remote:a=!1}){let s=i?{protocol:i}:void 0,o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{protocol:zt.uri,protocolPath:zt.requestPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${d.status.detail}`);let u=[];for(let c of d.entries){let l=Ia.parse(c);u.push({request:l,message:c})}return u})}isGrantRevoked(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantRecordId:i,remote:a=!1}){let s={author:r,target:n,messageType:Te.RecordsRead,messageParams:{filter:{parentId:i,protocol:zt.uri,protocolPath:zt.revocationPath}}},{reply:o}=a?yield this.agent.sendDwnRequest(s):yield this.agent.processDwnRequest(s);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}`)})}createGrant(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={recipient:a.grantedTo,protocol:zt.uri,protocolPath:zt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{grant:dr.parse(f),message:f}})}createRequest(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={protocol:zt.uri,protocolPath:zt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{request:Ia.parse(f),message:f}})}createRevocation(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=Ue.object(s).toUint8Array(),d;zt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let u={parentContextId:i.id,protocol:zt.uri,protocolPath:zt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(o).toBase64Url()})}})}clear(){return Cc(this,void 0,void 0,function*(){this._cachedPermissions.clear()})}static matchGrantFromArray(e,r,n,i){return Cc(this,arguments,void 0,function*(a,s,o,d,u=!1){let c;for(let l of d){let{grant:f,message:h}=l;if(u===!0&&f.delegated!==!0)continue;let{messageType:p,protocol:m,protocolPath:g,contextId:_}=o;if(this.matchScopeFromGrant(a,s,p,f,m,g,_)){if(f.scope.interface+f.scope.method===p)return{grant:f,message:h};c||(c={grant:f,message:h})}}return c})}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,u=d.interface+d.method;if(u===n||u===Te.MessagesRead&&(n===Te.MessagesSync||n===Te.MessagesSubscribe))if(YI(n)){let l=d;if(l.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(l)||l.protocolPath!==void 0&&l.protocolPath===s||l.contextId!==void 0&&o?.startsWith(l.contextId))return!0}else{let l=d;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}};y();var s7=wn(pP(),1);Jn();import{Level as Xfe}from"level";y();Jn();function Qz(t){let e=t.descriptor;return e.interface!==Ge.Records||e.method!==ze.Write?!1:e.dateCreated===e.messageTimestamp}function Em(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let l=0;l<t.length;l++){let f=t[l];r.set(l,f);let h=f.message.descriptor;if(h.interface===Ge.Protocols&&h.method===ze.Configure){let p=(e=h.definition)===null||e===void 0?void 0:e.protocol;p&&n.set(p,l)}if(h.interface===Ge.Records&&h.method===ze.Write){let p=f.message.recordId;Qz(f.message)&&p&&i.set(p,l),h.protocol===zt.uri&&h.protocolPath===zt.grantPath&&p&&a.set(p,l)}}let s=new Map,o=new Array(t.length).fill(0),d=(l,f)=>{if(l===f)return;s.has(l)||s.set(l,new Set);let h=s.get(l);h.has(f)||(h.add(f),o[f]++)};for(let l=0;l<t.length;l++){let f=t[l].message.descriptor;if(f.interface===Ge.Records){let p=f.protocol;p&&n.has(p)&&d(n.get(p),l)}if(f.interface===Ge.Records&&f.parentId){let p=f.parentId;i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Write){let p=t[l].message.recordId;p&&!Qz(t[l].message)&&i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Delete){let p=f.recordId;p&&i.has(p)&&d(i.get(p),l)}let h=f.permissionGrantId;h&&a.has(h)&&d(a.get(h),l)}let u=[];for(let l=0;l<t.length;l++)o[l]===0&&u.push(l);let c=[];for(;u.length>0;){let l=u.shift();c.push(r.get(l));let f=s.get(l);if(f)for(let h of f)o[h]--,o[h]===0&&u.push(h)}if(c.length<t.length){let l=new Set(c);for(let f=0;f<t.length;f++){let h=r.get(f);l.has(h)||c.push(h)}}return c}y();Jn();var tp=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Jfe=1048576;function e7(t){var e,r;return t.status.code===202||t.status.code===204||t.status.code===409||((e=t.entry)===null||e===void 0?void 0:e.message.descriptor.interface)===Ge.Records&&((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.method)===ze.Delete&&t.status.code===404}function t7(t){return tp(this,void 0,void 0,function*(){try{return yield Se.getCid(t)}catch{return"unknown"}})}function r7(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:d}){let u=[];if(s)for(let m of s){if(!m.message)continue;let g={message:m.message};if(m.encodedData){let _=ke.base64UrlToBytes(m.encodedData);g.bufferedData=_,g.dataStream=new ReadableStream({start(v){v.enqueue(_),v.close()}})}u.push(g)}let c=a.length>0?yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:d}):[],l=[...u,...c],f=Em(l);yield Zfe(f);let h=3,p=f;for(let m=0;m<=h&&p.length>0;m++){let g=[];for(let _ of p){let v=_.bufferedData?new ReadableStream({start(T){T.enqueue(_.bufferedData),T.close()}}):_.dataStream,E=yield o.dwn.processRawMessage(e,_.message,{dataStream:v});e7(E)||g.push(_)}if(g.length>0){let _=[],v=[];for(let E of g)if(E.bufferedData||!E.dataStream)v.push(E);else{let T=yield t7(E.message);_.push(T)}if(_.length>0){let E=yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:_,agent:o,permissionsApi:d});v.push(...E)}p=Em(v)}else p=[]}})}function Zfe(t){return tp(this,void 0,void 0,function*(){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:d,value:u}=yield a.read();if(d)break;if(n+=u.byteLength,n>Jfe){i=!0;break}r.push(u)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}})}function Xz(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let d=[],u;n&&(u=(yield o.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id);let c=4,l=0;for(;l<a.length;){let f=a.slice(l,l+c);l+=c;let h=yield Promise.all(f.map(p=>tp(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Te.MessagesRead,granteeDid:n,messageParams:{messageCid:p,permissionGrantId:u}}),v;try{v=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${p} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(v.status.code!==200||!(!((g=v.entry)===null||g===void 0)&&g.message))return;let E=v.entry,T;return vm(E)&&E.data&&(T=E.data),{message:E.message,dataStream:T}})));for(let p of h)p&&d.push(p)}return d})}function QI(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var d;let u=[];for(let l of a){let f=yield Yfe({author:e,messageCid:l,delegateDid:n,protocol:i,agent:s,permissionsApi:o});f&&u.push(f)}let c=Em(u);for(let l of c)try{let f=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:l.dataStream,message:l.message});if(!e7(f)){let h=yield t7(l.message);console.error(`SyncEngineLevel: push failed for ${h}: ${f.status.code} ${f.status.detail}`)}}catch(f){let h=(d=f.message)!==null&&d!==void 0?d:f;throw new Error(`SyncEngineLevel: push to ${r} failed: ${h}`)}})}function Yfe(t){return tp(this,arguments,void 0,function*({author:e,delegateDid:r,protocol:n,messageCid:i,agent:a,permissionsApi:s}){let o;r&&(o=(yield s.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let{reply:d}=yield a.dwn.processRequest({author:e,target:e,messageType:Te.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(d.status.code!==200||!d.entry)return;let u=d.entry,c={message:u.message};return vm(u)&&u.data&&(c.dataStream=u.data),c})}var Rt=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Qfe=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(s){return new Promise(function(o,d){s=t[a](s),i(o,d,s.done,s.value)})}}function i(a,s,o,d){Promise.resolve(d).then(function(u){a({value:u,done:o})},s)}},n7=16,i7=8,epe=4,XI=class{constructor(e){this._waiting=[],this._permits=e}acquire(){return Rt(this,void 0,void 0,function*(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})})}release(){let e=this._waiting.shift();e?e():this._permits++}run(e){return Rt(this,void 0,void 0,function*(){yield this.acquire();try{return yield e()}finally{this.release()}})}},o7="^",tpe=250,Sm=class t{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 fi({agent:e}),this._db=n||new Xfe(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 fi({agent:e})}get connectivityState(){return this._connectivityState}clear(){return Rt(this,void 0,void 0,function*(){yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return Rt(this,void 0,void 0,function*(){yield this._db.close()})}registerIdentity(e){return Rt(this,arguments,void 0,function*({did:r,options:n}){let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);n??(n={protocols:[]}),yield i.put(r,JSON.stringify(n))})}unregisterIdentity(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(e)))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);yield r.del(e)})}getIdentityOptions(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");try{let n=yield 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}.`)}})}updateIdentityOptions(e){return Rt(this,arguments,void 0,function*({did:r,options:n}){let i=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(r)))throw new Error(`SyncEngineLevel: Identity with DID ${r} is not registered.`);yield i.put(r,JSON.stringify(n))})}sync(e){return Rt(this,void 0,void 0,function*(){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=yield this.getSyncTargets(),n=new Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:u}=a;if(!n.has(d))try{let c=yield this.getLocalRoot(s,o,u),l=yield this.getRemoteRoot(s,d,o,u);if(c===l)continue;let f=yield this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:u});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);yield this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&(yield this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:f.onlyLocal}))}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}})}startSync(e){return Rt(this,void 0,void 0,function*(){var r,n;let i=(r=e.mode)!==null&&r!==void 0?r:"poll",a=(n=e.interval)!==null&&n!==void 0?n:i==="live"?"5m":"2m",s=(0,s7.default)(a);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&(yield this.teardownLiveSync()),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=i,i==="live"?yield this.startLiveSync(s):yield this.startPollSync(s)})}stopSync(){return Rt(this,arguments,void 0,function*(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,yield new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),yield this.teardownLiveSync()})}startPollSync(e){return Rt(this,void 0,void 0,function*(){let r=()=>Rt(this,void 0,void 0,function*(){if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),t.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||(yield this.sync())})}startLiveSync(e){return Rt(this,void 0,void 0,function*(){try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();for(let i of r)try{yield this.openLivePullSubscription(i),yield this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=()=>Rt(this,void 0,void 0,function*(){if(!this._syncLock)try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}});this._syncIntervalId=setInterval(n,e)})}teardownLiveSync(){return Rt(this,void 0,void 0,function*(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.clear();for(let e of this._liveSubscriptions)try{yield e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{yield e.close()}catch{}this._localSubscriptions=[]})}openLivePullSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=yield this.getCursor(s),d=a?[{protocol:a}]:[],u;if(n)try{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(p){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",p);return}}let c=h=>Rt(this,void 0,void 0,function*(){if(h.type==="eose"){yield this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);yield this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}yield this.setCursor(s,h.cursor)}}),f=(yield this.agent.dwn.sendRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:u},subscriptionHandler:c})).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:()=>Rt(this,void 0,void 0,function*(){yield f.subscription.close()})}),this._connectivityState="online"})}openLocalPushSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;if(n)try{o=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let d=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()},tpe)},c=(yield this.agent.dwn.processRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:()=>Rt(this,void 0,void 0,function*(){yield c.subscription.close()})})})}flushPendingPushes(){return Rt(this,void 0,void 0,function*(){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:s,cids:o}=r;if(o.length!==0)try{yield QI({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}})}buildCursorKey(e,r,n){let i=`${e}${o7}${r}`;return n?`${i}${o7}${n}`:i}getCursor(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{return yield r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}setCursor(e,r){return Rt(this,void 0,void 0,function*(){yield this._db.sublevel("syncCursors").put(e,r)})}extractDataStream(e){if(vm(e)&&e.data)return e.data}tryGetCidSync(e){var r;let n;return Se.getCid(e).then(i=>{n=i}),(r=n??e.messageCid)!==null&&r!==void 0?r:void 0}getDefaultHashHex(e){return Rt(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield Ng(),i=new Map;for(let a=0;a<=n7;a++)i.set(a,md(n[a]));this._defaultHashHex=i}return(r=this._defaultHashHex.get(e))!==null&&r!==void 0?r:""})}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}getLocalRoot(e,r,n){return Rt(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let u=n!==void 0?yield a.getProtocolRoot(e,n):yield a.getRoot(e);return md(u)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return Rt(this,void 0,void 0,function*(){var a;let s=yield this.getSyncPermissionGrantId(e,n,i),o=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:s}});return(a=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).root)!==null&&a!==void 0?a:""})}walkTreeDiff(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){let s=[],o=[],d=yield this.getSyncPermissionGrantId(r,i,a),u=new XI(epe),c=l=>Rt(this,void 0,void 0,function*(){let[f,h]=yield Promise.all([this.getLocalSubtreeHash(r,l,i,a,d),u.run(()=>this.getRemoteSubtreeHash(r,n,l,i,a,d))]);if(f===h)return;let p=yield this.getDefaultHashHex(l.length);if(h===p&&f!==p){let m=yield this.getLocalLeaves(r,l,i,a,d);s.push(...m);return}if(f===p&&h!==p){let m=yield u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d));o.push(...m);return}if(l.length>=n7){let[m,g]=yield Promise.all([this.getLocalLeaves(r,l,i,a,d),u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d))]),_=new Set(m),v=new Set(g);for(let E of m)v.has(E)||s.push(E);for(let E of g)_.has(E)||o.push(E);return}yield Promise.all([c(l+"0"),c(l+"1")])});return yield c(""),{onlyLocal:s,onlyRemote:o}})}diffWithRemote(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let d=yield this.collectLocalSubtreeHashes(r,a,i7),u=yield this.getSyncPermissionGrantId(r,i,a),c=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:d,depth:i7,permissionGrantId:u}}),l=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:c.message});if(l.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${l.status.code}: ${l.status.detail}`);let f=yield this.getSyncPermissionGrantId(r,i,a),h=[];for(let p of(s=l.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,p,i,a,f);h.push(...m)}return{onlyRemote:(o=l.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:h}})}collectLocalSubtreeHashes(e,r,n){return Rt(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(d,u)=>Rt(this,void 0,void 0,function*(){let c;if(s){let l=t.parseBitPrefix(d),f=r!==void 0?yield s.getProtocolSubtreeHash(e,r,l):yield s.getSubtreeHash(e,l);c=md(f)}else c=yield this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(u>=n){i[d]=c;return}yield Promise.all([o(d+"0",u+1),o(d+"1",u+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r),l=i!==void 0?yield o.getProtocolSubtreeHash(e,i,c):yield o.getSubtreeHash(e,c);return md(l)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getRemoteSubtreeHash(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).hash)!==null&&o!==void 0?o:""})}getLocalLeaves(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r);return i!==void 0?yield o.getProtocolLeaves(e,i,c):yield o.getLeaves(e,c)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}getRemoteLeaves(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).entries)!==null&&o!==void 0?o:[]})}pullMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){return r7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi})})}pushMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return QI({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Em(e)}getSyncTargets(){return Rt(this,void 0,void 0,function*(){var e,r,n,i;let a=[];try{for(var s=!0,o=Qfe(this._db.sublevel("registeredIdentities").iterator()),d;d=yield o.next(),e=d.done,!e;s=!0){i=d.value,s=!1;let[u,c]=i,l;try{l=JSON.parse(c)}catch{l={protocols:[]}}let{protocols:f,delegateDid:h}=l,p=yield this.agent.dwn.getDwnEndpointUrlsForTarget(u);if(p.length!==0)for(let m of p)if(f.length===0)a.push({did:u,delegateDid:h,dwnUrl:m});else for(let g of f)a.push({did:u,delegateDid:h,dwnUrl:m,protocol:g})}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return a})}getSyncPermissionGrantId(e,r,n){return Rt(this,void 0,void 0,function*(){return r?(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0})}};Sm.MAX_CONSECUTIVE_FAILURES=5;Sm.MAX_BACKOFF_MULTIPLIER=4;y();Jn();Fo();Kt();import{Level as VWe}from"level";y();y();y();Kt();rn();y();y();var a7=wn(pP(),1);Kt();var Tm=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},mP=class{constructor({ttl:e="15m"}={}){this.cache=new Kl.default({ttl:(0,a7.default)(e)})}get(e){return Tm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Tm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Tm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Tm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Tm(this,void 0,void 0,function*(){})}close(){return Tm(this,void 0,void 0,function*(){})}};y();rn();Jn();y();var km=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Am;(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"})(Am||(Am={}));var Dm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),yP=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),c7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function rp(t){try{return JSON.parse(t)}catch{return null}}var eR=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},rpe=3,npe=500,ipe=1e4,ope=3e4,d7=new Set([408,429,500,502,503,504]);function spe(t,e){return t instanceof TypeError?!0:e?d7.has(e.status):!1}function ape(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function cpe(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 gP=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new mP,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rpe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:npe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ipe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return eR(this,void 0,void 0,function*(){var r,n,i;let a=gi.randomUuid(),s=Dm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Hi.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let u=yield this.fetchWithRetry(e.dwnUrl,d);if(u.status===429){let h=parseInt((r=u.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new km(h)}let c,l=u.headers.has("dwn-response");if(l){let h=rp(u.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield u.text(),p=rp(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${u.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===Am.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new km(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(l){let h=new Uint8Array(yield u.arrayBuffer()),p=Hi.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return eR(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 s=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new km(s)}if(a.ok){let s=yield a.json(),o={maxFileSize:s.maxFileSize,maxInFlight:s.maxInFlight,providerAuth:s.providerAuth,registrationRequirements:s.registrationRequirements,server:s.server,sdkVersion:s.sdkVersion,url:s.url,version:s.version,webSocketSupport:s.webSocketSupport};return this.serverInfoCache.set(e,o),o}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 eR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(ope),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!d7.has(p.status)||d===n)return p;o=p}catch(f){if(!spe(f)||d===n)throw f;s=f}let u=o?cpe(o):void 0,c=ape(d,i,a),l=u!==void 0?Math.max(u,c):c;yield new Promise(f=>{setTimeout(f,l)})}if(o)return o;throw s})}};y();rn();var g0=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})};function tR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var u7=3e3,dpe=3e4,upe=1e3,lpe=3e4,fpe=1/0,wP=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 g0(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=u7,responseTimeout:s=dpe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(u){throw(i=n.onerror)===null||i===void 0||i.call(n,u),u}let d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return g0(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gi.randomUuid());let a=s=>{let o=rp(tR(s.data));if(o.id===e.id)return this.messageHandlers.delete(e.id),r(o)};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 g0(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=d=>{let u=rp(tR(d.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 s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>g0(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gi.randomUuid(),n=yP(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),s=()=>{u(),n(a)},o=c=>{u(),i(c)},d=setTimeout(()=>{u(),a.close(),i(new Error("connect timed out"))},r),u=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=rp(tR(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,s;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),((s=this.options.autoReconnect)!==null&&s!==void 0?s:!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:Am.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:upe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:lpe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fpe,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:u7,u=0,c=()=>g0(this,void 0,void 0,function*(){var l,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(u++,u>o){this.reconnecting=!1;return}(f=(l=this.options).onreconnecting)===null||f===void 0||f.call(l,u);let g=Math.min(a*Math.pow(2,u-1),s)*(.5+Math.random()*.5);if(yield new Promise(_=>setTimeout(_,g)),this.closedByUser){this.reconnecting=!1;return}try{let _=yield t.createWebSocket(this.url,d);this.socket=_,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(_),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};y();y();y();rn();y();rn();var Im=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},w0=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return Im(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 d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return Im(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield wP.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let s of n.values())s.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 Im(this,void 0,void 0,function*(){let i=gi.randomUuid(),a=Dm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:u}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return u.reply})}static subscriptionRequest(e,r,n,i,a){return Im(this,void 0,void 0,function*(){let s=gi.randomUuid(),o=gi.randomUuid(),d=yP(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:u,subscriptions:c}=e,{response:l,close:f}=yield u.subscribe(d,g=>{let{result:_,error:v}=g;if(v){let T=c.get(o);T&&T.subscription.close(),c.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let T=c.get(o);T&&(T.lastCursor=E.cursor),u.send(c7(o,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 g=()=>Im(this,void 0,void 0,function*(){c.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return Im(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{}})}};w0.connections=new Map;var v0=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},l7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(l7||(l7={}));var Rm=class{constructor(e=[]){this.transportClients=new Map,e=[new rR,new nR,...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 v0(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 v0(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)})}},rR=class extends gP{sendDidRequest(e){return v0(this,void 0,void 0,function*(){let r=gi.randomUuid(),n=Dm(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 s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},nR=class extends w0{sendDidRequest(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Fo();Kt();rn();Jn();y();Kt();Fo();var vP=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:y0.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:y0.Resolve});return n}};y();y();Kt();var b0=class{constructor(e){let{rawMessage:r,initialWrite:n,encodedData:i,data:a,remoteOrigin:s,anonymousDwn:o}=e;this._anonymousDwn=o,this._remoteOrigin=s;try{this._author=Wo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Wo(n)??this._author:this._author}catch{this._creator=this._author}this._descriptor=r.descriptor,this._recordId=r.recordId,this._contextId=r.contextId,this._initialWrite=n,this._authorization=r.authorization,this._attestation=r.attestation,this._encryption=r.encryption,i&&(this._encodedData=new Blob([Ue.base64Url(i).toUint8Array()],{type:this.dataFormat})),a&&(this._readableStream=a)}get id(){return this._recordId}get contextId(){return this._contextId}get dateCreated(){return this._descriptor.dateCreated}get parentId(){return this._descriptor.parentId}get protocol(){return this._descriptor.protocol}get protocolPath(){return this._descriptor.protocolPath}get recipient(){return this._descriptor.recipient}get schema(){return this._descriptor.schema}get dataFormat(){return this._descriptor.dataFormat}get dataCid(){return this._descriptor.dataCid}get dataSize(){return this._descriptor.dataSize}get datePublished(){return this._descriptor.datePublished}get published(){return this._descriptor.published}get tags(){return this._descriptor.tags}get author(){return this._author}get creator(){return this._creator}get timestamp(){return this._descriptor.messageTimestamp}get encryption(){return this._encryption}get authorization(){return this._authorization}get attestation(){return this._attestation}get initialWrite(){return this._initialWrite}get remoteOrigin(){return this._remoteOrigin}get data(){let e=this;return{async blob(){return new Blob([await Co.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Co.consumeToBytes({readableStream:await this.stream()})},async json(){return await Co.consumeToJson({readableStream:await this.stream()})},async text(){return await Co.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Co.fromBlob(e._encodedData);if(e._readableStream){let n=e._readableStream;return e._readableStream=void 0,n}else return await e.readRecordData()},then(n,i){return this.stream().then(n,i)},catch(n){return this.stream().catch(n)}}}toJSON(){return{attestation:this.attestation,author:this.author,authorization:this.authorization,contextId:this.contextId,dataCid:this.dataCid,dataFormat:this.dataFormat,dataSize:this.dataSize,dateCreated:this.dateCreated,datePublished:this.datePublished,encryption:this.encryption,parentId:this.parentId,protocol:this.protocol,protocolPath:this.protocolPath,published:this.published,recipient:this.recipient,recordId:this.id,schema:this.schema,tags:this.tags,timestamp:this.timestamp}}toString(){let e=`ReadOnlyRecord: {
2059
2059
  `;return e+=` ID: ${this.id}
2060
2060
  `,e+=this.contextId?` Context ID: ${this.contextId}
2061
2061
  `:"",e+=this.protocol?` Protocol: ${this.protocol}
@@ -2076,7 +2076,7 @@ zoo`.split(`
2076
2076
  `),e+=` Deleted: ${this.deleted}
2077
2077
  `,e+=` Created: ${this.dateCreated}
2078
2078
  `,e+=` Timestamp: ${this.timestamp}
2079
- `,e+="}",e}async paginationCursor(e){return ZI(Te.RecordsWrite,this.rawMessage)?zz(this.rawMessage,e):void 0}async update({timestamp:e,data:r,encryption:n,protocolRole:i,store:a=!0,...s}){if(this.deleted)throw new Error("Record: Cannot revive a deleted record.");let o=n??this._encryption!==void 0,{parentId:d,...u}=this._recordsWriteDescriptor,c=d?this._contextId.split("/").slice(0,-1).join("/"):void 0,l={...u,...s,parentContextId:c,protocolRole:i??this._protocolRole,messageTimestamp:e,recordId:this._recordId};(b3(l.tags)||l.tags===null)&&delete l.tags;let f;r!==void 0&&(delete l.dataCid,delete l.dataSize,{dataBlob:f}=P0(r,l.dataFormat));let h=new Set(["data","dataCid","dataFormat","dataSize","datePublished","messageTimestamp","published","tags"]);ol.verifyPermittedMutation(Object.keys(s),h),s.published===!1&&l.datePublished!==void 0&&delete l.datePublished;let p={author:this._connectedDid,dataStream:f,messageParams:{...l},messageType:Te.RecordsWrite,target:this._connectedDid,store:a,encryption:o||void 0};await this.applyDelegateGrant(p);let m=await this._agent.processDwnRequest(p),{message:g,reply:{status:_}}=m;if(!(200<=_.code&&_.code<=299))return{status:_,record:this};let v=this._initialWrite??{...this.rawMessage},E=new ol(this._agent,{author:this._author,connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:i??this._protocolRole,initialWrite:v,encodedData:r!==void 0?f:this._encodedData,...g},this._permissionsApi),T=g;return this._descriptor=T.descriptor,this._attestation=T.attestation,this._authorization=T.authorization,this._encryption=T.encryption,this._contextId=T.contextId,this._initialWrite=v,this._protocolRole=i??this._protocolRole,this._encodedData=r!==void 0?f:this._encodedData,this._readableStream=void 0,this._rawMessageDirty=!0,{status:_,record:E}}async delete(e){let{store:r=!0,signAsOwner:n,timestamp:i,prune:a=!1}=e||{},s=n&&this._delegateDid===void 0,o=n&&this._delegateDid!==void 0;if(this.deleted&&!this._initialWrite)throw new Error("Record: Record is in an invalid state, initial write is missing.");this._initialWrite||(this._initialWrite={...this.rawMessage}),await this.processInitialWriteIfNeeded({store:r,signAsOwner:n});let d={messageType:Te.RecordsDelete,author:this._connectedDid,target:this._connectedDid,signAsOwner:s,signAsOwnerDelegate:o,store:r},u=e?.protocolRole?Lz(this.rawMessage)!==e.protocolRole:!1;this.deleted&&!u?d.rawMessage=this.rawMessage:d.messageParams={prune:a,recordId:this._recordId,messageTimestamp:i,protocolRole:e?.protocolRole??this._protocolRole},await this.applyDelegateGrant(d);let c=await this._agent.processDwnRequest(d),{message:l,reply:{status:f}}=c;if(f.code!==202)return{status:f,record:this};let h=this._initialWrite,p=new ol(this._agent,{author:Wo(l),connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:e?.protocolRole??this._protocolRole,initialWrite:h,...l},this._permissionsApi),m=l;return this._descriptor=m.descriptor,this._authorization=m.authorization,this._protocolRole=e?.protocolRole??this._protocolRole,this._encodedData=void 0,this._readableStream=void 0,this._rawMessageDirty=!0,{status:f,record:p}}async processInitialWriteIfNeeded({store:e,signAsOwner:r}){if(this.initialWrite&&(r&&!this._initialWriteSigned||e&&!this._initialWriteStored)){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0,a={messageType:Te.RecordsWrite,rawMessage:this.initialWrite,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e};await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:d}}=s,u=o;200<=d.code&&d.code<=299&&(e&&(this._initialWriteStored=!0),r&&(this._initialWriteSigned=!0,this.initialWrite.authorization=u.authorization))}}async processRecord({store:e,signAsOwner:r}){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0;await this.processInitialWriteIfNeeded({store:e,signAsOwner:r});let a;this.deleted?a={messageType:Te.RecordsDelete,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e}:a={messageType:Te.RecordsWrite,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,dataStream:await this.data.blob(),signAsOwner:n,signAsOwnerDelegate:i,store:e},await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:d}}=s,u=o;return 200<=d.code&&d.code<=299&&r&&(this._authorization=u.authorization,this._rawMessageDirty=!0),{status:d}}async readRecordData({target:e,isRemote:r}){let n={author:this._connectedDid,messageParams:{filter:{recordId:this.id},protocolRole:this._protocolRole},messageType:Te.RecordsRead,target:e,...this._encryption?{encryption:!0}:{}};if(this._delegateDid)try{await this.applyDelegateGrant(n)}catch{n.author=this._delegateDid}let i=r?this._agent.sendDwnRequest(n):this._agent.processDwnRequest(n);try{let{reply:{status:a,entry:s}}=await i;if(a.code!==200)throw new Error(`${a.code}: ${a.detail}`);return s.data}catch(a){throw new Error(`Error encountered while attempting to read data: ${a.message}`)}}async applyDelegateGrant(e){if(!this._delegateDid)return;let{message:r}=await this._permissionsApi.getPermissionForRequest({connectedDid:this._connectedDid,delegateDid:this._delegateDid,protocol:this.protocol,delegate:!0,cached:!0,messageType:e.messageType});e.messageParams={...e.messageParams,delegatedGrant:r},e.granteeDid=this._delegateDid}static verifyPermittedMutation(e,r){for(let n of e)if(!r.has(n))throw new Error(`${n} is an immutable property. Its value cannot be changed.`)}isRecordsDeleteDescriptor(e){return e.interface+e.method===Te.RecordsDelete}};ol._sendCache=x0;var jd=ol;var iR=class extends CustomEvent{constructor(e){super(e.type,{detail:e})}},xP=class extends EventTarget{constructor(r){super();this._closed=!1;this._connected=!0;let{agent:n,connectedDid:i,cursor:a,delegateDid:s,protocolRole:o,remoteOrigin:d,permissionsApi:u,initialEntries:c,subscription:l}=r;this._subscription=l,this.cursor=a,this.records=c.map(f=>new jd(n,{author:Wo(f),connectedDid:i,remoteOrigin:d,delegateDid:s,protocolRole:o,...f},u)),this._knownRecords=new Map;for(let f of this.records)this._knownRecords.set(f.id,f.timestamp)}get isConnected(){return this._connected}handleEvent(r){if(this._closed)return;let n;if(r.deleted)n="delete",this._knownRecords.delete(r.id);else{let a=this._knownRecords.get(r.id);if(a!==void 0){if(r.timestamp<=a)return;n="update"}else n="create";this._knownRecords.set(r.id,r.timestamp)}let i={type:n,record:r};this.dispatchEvent(new iR(i)),this.dispatchEvent(new CustomEvent("change",{detail:i}))}handleLifecycleEvent(r,n){this._closed||(r==="disconnected"?this._connected=!1:r==="reconnected"&&(this._connected=!0),this.dispatchEvent(new CustomEvent(r,{detail:n})))}on(r,n){let i=a=>{let s=a.detail;r==="change"?n(s):r==="create"||r==="update"||r==="delete"?n(s.record):r==="reconnecting"?n(s):n()};return this.addEventListener(r,i),()=>{this.removeEventListener(r,i)}}async close(){this._closed||(this._closed=!0,await this._subscription.close())}};y();Kt();y();Kt();var PP=class t{constructor(e,r){this._permissions=e,this._connectedDid=r.connectedDid,this._message=r.message}get author(){return Wo(this._message)}static async parse({connectedDid:e,agent:r,message:n}){let i=new fi({agent:r});return new t(i,{connectedDid:e,message:n})}get agent(){return this._permissions.agent}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Ue.base64Url(r).toUint8Array()]),a={messageType:Te.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Ue.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}};var np=class t{constructor({api:e,connectedDid:r,message:n,grant:i}){this._permissions=e,this._connectedDid=r,this._message=n,this._grant=i}static parse(e){let r=dr.parse(e.message),n=new fi({agent:e.agent});return new t({...e,grant:r,api:n})}get agent(){return this._permissions.agent}get id(){return this._grant.id}get grantor(){return this._grant.grantor}get grantee(){return this._grant.grantee}get dateGranted(){return this._grant.dateGranted}get description(){return this._grant.description}get requestId(){return this._grant.requestId}get dateExpires(){return this._grant.dateExpires}get delegated(){return this._grant.delegated}get scope(){return this._grant.scope}get conditions(){return this._grant.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Ue.base64Url(r).toUint8Array()]),a={messageType:Te.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Ue.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:!0,author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async import(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Ue.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:e,author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,signAsOwner:!0,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async revoke(e=!0){let r=await this._permissions.createRevocation({store:e,author:this._connectedDid,grant:this._grant});return PP.parse({connectedDid:this._connectedDid,agent:this.agent,message:r.message})}isRevoked(e=!1){return this._permissions.isGrantRevoked({author:this._connectedDid,target:this.grantor,grantRecordId:this.id,remote:e})}toJSON(){return{id:this.id,grantor:this.grantor,grantee:this.grantee,dateGranted:this.dateGranted,description:this.description,requestId:this.requestId,dateExpires:this.dateExpires,delegated:this.delegated,scope:this.scope,conditions:this.conditions}}};y();Kt();var _0=class t{constructor({api:e,connectedDid:r,message:n,request:i}){this._permissions=e,this._connectedDid=r,this._request=i,this._message=n}static parse({connectedDid:e,agent:r,message:n}){let i=Ia.parse(n),a=new fi({agent:r});return new t({api:a,connectedDid:e,message:n,request:i})}get agent(){return this._permissions.agent}get id(){return this._request.id}get requester(){return this._request.requester}get description(){return this._request.description}get delegated(){return this._request.delegated}get scope(){return this._request.scope}get conditions(){return this._request.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Ue.base64Url(r).toUint8Array()]),a={messageType:Te.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(){let{encodedData:e,...r}=this.rawMessage,n=new Blob([Ue.base64Url(e).toUint8Array()]),{reply:i,message:a}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,rawMessage:r,dataStream:n});return this._message={...a,encodedData:e},{status:i.status}}async grant(e,r=!0){let{message:n}=await this._permissions.createGrant({requestId:this.id,grantedTo:this.requester,scope:this.scope,delegated:this.delegated,author:this._connectedDid,store:r,dateExpires:e});return np.parse({connectedDid:this._connectedDid,agent:this.agent,message:n})}toJSON(){return this._request}};y();var E0=class{constructor(e,r,n){this._agent=e,this._metadata=n,this._protocolsConfigureMessage=r}get definition(){return this._protocolsConfigureMessage.descriptor.definition}toJSON(){return this._protocolsConfigureMessage}async send(e){let{reply:r}=await this._agent.sendDwnRequest({author:this._metadata.author,messageCid:this._metadata.messageCid,messageType:Te.ProtocolsConfigure,target:e});return{status:r.status}}};var _P=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid,this.delegateDid=e.delegateDid,this.permissionsApi=new fi({agent:this.agent})}get isDelegate(){return this.delegateDid!==void 0}get permissions(){return{request:async e=>{let{message:r}=await this.permissionsApi.createRequest({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return _0.parse(n)},grant:async e=>{let{message:r}=await this.permissionsApi.createGrant({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return np.parse(n)},queryRequests:async(e={})=>{let{from:r,...n}=e,i=await this.permissionsApi.fetchRequests({...n,author:this.delegateDid??this.connectedDid,target:r??this.delegateDid??this.connectedDid,remote:r!==void 0}),a=[];for(let s of i){let o={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:s.message};a.push(_0.parse(o))}return a},queryGrants:async(e={})=>{let{from:r,...n}=e,i=r!==void 0,a=this.delegateDid??this.connectedDid,s=r??this.delegateDid??this.connectedDid,o=await this.permissionsApi.fetchGrants({...n,author:a,target:s,remote:i}),d=[];for(let u of o){let c={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:u.message};d.push(np.parse(c))}return d}}}get protocols(){return{configure:async e=>{let{encryption:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Te.ProtocolsConfigure,target:this.connectedDid,encryption:r};if(this.delegateDid){let{message:c}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.definition.protocol,delegate:!0,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,delegatedGrant:c},i.granteeDid=this.delegateDid}let a=await this.agent.processDwnRequest(i),{message:s,messageCid:o,reply:{status:d}}=a,u={status:d};if(d.code<300){let c={author:this.connectedDid,messageCid:o};u.protocol=new E0(this.agent,s,c)}return u},query:async e=>{let{from:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Te.ProtocolsQuery,target:r||this.connectedDid};if(this.delegateDid)try{let{grant:{id:c}}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter.protocol,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,permissionGrantId:c},i.granteeDid=this.delegateDid}catch{i.author=this.delegateDid}let a;r?a=await this.agent.sendDwnRequest(i):a=await this.agent.processDwnRequest(i);let s=a.reply,{entries:o=[],status:d}=s;return{protocols:o.map(c=>{let l={author:this.connectedDid};return new E0(this.agent,c,l)}),status:d}}}}get records(){return{delete:async e=>{let{from:r,protocol:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Te.RecordsDelete,target:r||this.connectedDid};if(this.delegateDid){let{message:d}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:d},a.granteeDid=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let{reply:{status:o}}=s;return{status:o}},query:async e=>{let{from:r,encryption:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Te.RecordsQuery,target:r||this.connectedDid,encryption:n};if(this.delegateDid)try{let{message:f}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:i.filter?.protocol,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:f},a.granteeDid=this.delegateDid}catch{a.author=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let o=s.reply,{entries:d=[],status:u,cursor:c}=o;return{records:d.map(f=>{let h={author:Wo(f),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,protocolRole:a.messageParams.protocolRole,...f};return new jd(this.agent,h,this.permissionsApi)}),status:u,cursor:c}},read:async e=>{let{from:r,protocol:n,encryption:i,...a}=e,s={author:this.connectedDid,messageParams:a,messageType:Te.RecordsRead,target:r||this.connectedDid,encryption:i};if(this.delegateDid)try{let{message:l}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:s.messageType});s.messageParams={...s.messageParams,delegatedGrant:l},s.granteeDid=this.delegateDid}catch{s.author=this.delegateDid}let o;r?o=await this.agent.sendDwnRequest(s):o=await this.agent.processDwnRequest(s);let{reply:{entry:d,status:u}}=o,c;if(200<=u.code&&u.code<=299){let l={author:Wo(d.recordsWrite),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,data:d.data,initialWrite:d.initialWrite,...d.recordsWrite};c=new jd(this.agent,l,this.permissionsApi)}return{record:c,status:u}},subscribe:async e=>{let{from:r,...n}=e,i,a=r,s=n.protocolRole,o=m=>{if(m.type==="eose"){i?.handleLifecycleEvent("eose");return}if(m.type==="disconnected"){i?.handleLifecycleEvent("disconnected");return}if(m.type==="reconnected"){i?.handleLifecycleEvent("reconnected");return}if(m.type==="reconnecting"){i?.handleLifecycleEvent("reconnecting",{attempt:m.attempt});return}let{message:g,initialWrite:_}=m.event,v=new jd(this.agent,{...g,author:Wo(g),connectedDid:this.connectedDid,remoteOrigin:a,initialWrite:_,protocolRole:s,delegateDid:this.delegateDid},this.permissionsApi);i?.handleEvent(v)},d={author:this.connectedDid,messageParams:n,messageType:Te.RecordsSubscribe,target:r||this.connectedDid,subscriptionHandler:o};if(this.delegateDid)try{let{message:m}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter?.protocol,delegate:!0,cached:!0,messageType:d.messageType});d.messageParams={...d.messageParams,delegatedGrant:m},d.granteeDid=this.delegateDid}catch{d.author=this.delegateDid}let u;r?u=await this.agent.sendDwnRequest(d):u=await this.agent.processDwnRequest(d);let c=u.reply,{status:l,subscription:f,entries:h=[],cursor:p}=c;return f&&(i=new xP({agent:this.agent,connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocolRole:s,remoteOrigin:a,permissionsApi:this.permissionsApi,initialEntries:h,cursor:p,subscription:f})),{status:l,liveQuery:i}},write:async e=>{let{data:r,store:n,encryption:i,...a}=e,{dataBlob:s,dataFormat:o}=P0(r,a.dataFormat),d={...a,dataFormat:o},u={store:n,messageType:Te.RecordsWrite,messageParams:d,author:this.connectedDid,target:this.connectedDid,dataStream:s,encryption:i};if(this.delegateDid){let{message:p}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:d.protocol,delegate:!0,cached:!0,messageType:u.messageType});u.messageParams={...u.messageParams,delegatedGrant:p},u.granteeDid=this.delegateDid}let c=await this.agent.processDwnRequest(u),{message:l,reply:{status:f}}=c,h;if(200<=f.code&&f.code<=299){let p={author:this.connectedDid,connectedDid:this.connectedDid,encodedData:s,delegateDid:this.delegateDid,...l};h=new jd(this.agent,p,this.permissionsApi)}return{record:h,status:f}}}}};y();y();y();var $c=class t{constructor(e){this._record=e}get rawRecord(){return this._record}get data(){let e=this._record.data;return{blob:()=>e.blob(),bytes:()=>e.bytes(),json:()=>e.json(),text:()=>e.text(),stream:()=>e.stream(),then:e.then.bind(e),catch:e.catch.bind(e)}}async update(e){let{status:r,record:n}=await this._record.update(e);return{status:r,record:new t(n)}}async delete(e){let{status:r,record:n}=await this._record.delete(e);return{status:r,record:new t(n)}}async store(e=!1){return this._record.store(e)}async import(e=!0){return this._record.import(e)}async send(e){return this._record.send(e)}toJSON(){return this._record.toJSON()}toString(){return this._record.toString()}async paginationCursor(e){return this._record.paginationCursor(e)}get id(){return this._record.id}get contextId(){return this._record.contextId}get dateCreated(){return this._record.dateCreated}get parentId(){return this._record.parentId}get protocol(){return this._record.protocol}get protocolPath(){return this._record.protocolPath}get recipient(){return this._record.recipient}get schema(){return this._record.schema}get dataFormat(){return this._record.dataFormat}get dataCid(){return this._record.dataCid}get dataSize(){return this._record.dataSize}get datePublished(){return this._record.datePublished}get published(){return this._record.published}get tags(){return this._record.tags}get author(){return this._record.author}get creator(){return this._record.creator}get timestamp(){return this._record.timestamp}get encryption(){return this._record.encryption}get authorization(){return this._record.authorization}get attestation(){return this._record.attestation}get protocolRole(){return this._record.protocolRole}get deleted(){return this._record.deleted}get initialWrite(){return this._record.initialWrite}get rawMessage(){return this._record.rawMessage}};var EP=class{constructor(e){this._liveQuery=e}get rawLiveQuery(){return this._liveQuery}get records(){return this._typedRecords||(this._typedRecords=this._liveQuery.records.map(e=>new $c(e))),this._typedRecords}get cursor(){return this._liveQuery.cursor}get isConnected(){return this._liveQuery.isConnected}on(e,r){return e==="disconnected"?this._liveQuery.on("disconnected",r):e==="reconnected"?this._liveQuery.on("reconnected",r):e==="eose"?this._liveQuery.on("eose",r):e==="reconnecting"?this._liveQuery.on("reconnecting",r):e==="change"?this._liveQuery.on("change",n=>{r({type:n.type,record:new $c(n.record)})}):this._liveQuery.on(e,n=>{r(new $c(n))})}async close(){return this._liveQuery.close()}};var TP=class{constructor(e,r){this._configured=!1;this._ensureReadyPromise=null;this._dwn=e,this._definition=r.definition,this._validPaths=y7(this._definition.structure)}get protocol(){return this._definition.protocol}get definition(){return this._definition}async configure(e){let{protocols:r}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(r.length>0){let a=r[0];if(m7(a.definition,this._definition))return this._configured=!0,{status:{code:200,detail:"OK"},protocol:a}}let n=!this._dwn.isDelegate&&Object.values(this._definition.types).some(a=>a?.encryptionRequired===!0),i=await this._dwn.protocols.configure({definition:this._definition,encryption:e?.encryption??(n||void 0)});return i.status.code===202&&(this._configured=!0),i}get isConfigured(){return this._configured}_assertValidPath(e){if(!this._validPaths.has(e))throw new Error(`TypedEnbox: invalid protocol path '${e}'. Valid paths are: ${[...this._validPaths].join(", ")}.`)}async _ensureReady(e){if(this._configured){this._assertValidPath(e);return}this._ensureReadyPromise===null&&(this._ensureReadyPromise=this._autoConfigureOnce()),await this._ensureReadyPromise,this._assertValidPath(e)}async _autoConfigureOnce(){let{protocols:e}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(e.length>0){let i=e[0];if(m7(i.definition,this._definition)){this._configured=!0;return}console.warn(`TypedEnbox: installed protocol '${this._definition.protocol}' differs from the provided definition. Call configure() to update it.`),this._configured=!0;return}let r=!this._dwn.isDelegate&&Object.values(this._definition.types).some(i=>i?.encryptionRequired===!0);(await this._dwn.protocols.configure({definition:this._definition,encryption:r||void 0})).status.code===202&&(this._configured=!0)}get records(){if(this._records!==void 0)return this._records;let e={create:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=!this._dwn.isDelegate&&s?.encryptionRequired===!0?!0:void 0,{status:d,record:u}=await this._dwn.records.write({data:n.data,store:n.store,encryption:n.encryption??o,parentContextId:n.parentContextId,published:n.published,datePublished:n.datePublished,recipient:n.recipient,protocolRole:n.protocolRole,tags:n.tags,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{},dataFormat:n.dataFormat??s?.dataFormats?.[0]});return{status:d,record:u?new $c(u):void 0}},query:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=oR(n?.filter),d=!this._dwn.isDelegate&&s?.encryptionRequired===!0?!0:void 0,{status:u,records:c,cursor:l}=await this._dwn.records.query({from:n?.from,encryption:n?.encryption??d,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{}},dateSort:n?.dateSort,pagination:n?.pagination,protocolRole:n?.protocolRole});return{status:u,records:c.map(f=>new $c(f)),cursor:l}},read:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=oR(n.filter),d=!this._dwn.isDelegate&&s?.encryptionRequired===!0?!0:void 0,{status:u,record:c}=await this._dwn.records.read({from:n.from,encryption:n.encryption??d,protocol:this._definition.protocol,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{}}});return{status:u,record:c?new $c(c):void 0}},delete:async(r,n)=>(await this._ensureReady(S0(r)),this._dwn.records.delete({from:n.from,protocol:this._definition.protocol,recordId:n.recordId})),subscribe:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=oR(n?.filter),{status:d,liveQuery:u}=await this._dwn.records.subscribe({from:n?.from,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{}},protocolRole:n?.protocolRole});return{status:d,liveQuery:u?new EP(u):void 0}}};return this._records=e,e}};function oR(t){if(!t)return;let{parentContextId:e,...r}=t;return e!==void 0&&r.parentId===void 0&&(r.parentId=e),r}function m7(t,e){return kP(t)===kP(e)}function S0(t){return t.replace(/^\/+|\/+$/g,"")}function SP(t){let e=t.split("/");return e[e.length-1]}function y7(t,e=""){let r=new Set;for(let n of Object.keys(t)){if(n.startsWith("$"))continue;let i=e?`${e}/${n}`:n;r.add(i);let a=t[n];if(a!==null&&typeof a=="object")for(let s of y7(a,i))r.add(s)}return r}function kP(t){return t==null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>kP(n)).join(",")+"]":"{"+Object.keys(t).sort().map(n=>JSON.stringify(n)+":"+kP(t[n])).join(",")+"}"}y();var AP=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(){throw new Error("Not implemented.")}};var g7=class t{constructor({agent:e,connectedDid:r,delegateDid:n}){this._typedInstances=new Map;this.agent=e,this.did=new vP({agent:e,connectedDid:r}),this._dwn=new _P({agent:e,connectedDid:r,delegateDid:n}),this.vc=new AP({agent:e,connectedDid:r})}using(e){let r=e.definition.protocol,n=this._typedInstances.get(r);if(n)return n;let i=new TP(this._dwn,e);return this._typedInstances.set(r,i),i}async disconnect(e){"sync"in this.agent&&typeof this.agent.sync?.stopSync=="function"&&await this.agent.sync.stopSync(e),this._typedInstances.clear()}static anonymous(e){let r=new s0({didResolvers:e?.didResolvers??[tl,Jf,qx,kI],cache:new Lx}),n=new Rm,i=new lP({didResolver:r,rpcClient:n});return{dwn:new bP(i)}}static connect(e){if("session"in e){let{session:r}=e;return new t({agent:r.agent,connectedDid:r.did,delegateDid:r.delegateDid})}return new t(e)}};y();y();y();function w7(t){return t.code===400&&t.detail.includes("record limit")}function Ppe(t,e){let r=e.split("/"),n=t.structure;for(let a of r){if(!n||typeof n!="object")return!1;n=n[a]}if(!n||typeof n!="object")return!1;let i=n.$recordLimit;return i!==void 0&&typeof i=="object"&&i!==null&&i.max===1}function _pe(t,e){let r=e.split("/"),n=t.structure;for(let i of r){if(!n||typeof n!="object")return[];n=n[i]}return!n||typeof n!="object"?[]:Object.keys(n).filter(i=>!i.startsWith("$"))}function Epe(t,e){return{async create(r){let{status:n,record:i}=await t.records.create(e,r);return{status:n,record:i}},async query(r){let{status:n,records:i,cursor:a}=await t.records.query(e,r);return{status:n,records:i,cursor:a}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r){let{liveQuery:n}=await t.records.subscribe(e,r);return n}}}function Spe(t,e){return{async set(r){let n=await t.records.create(e,r);if(w7(n.status)){let{records:i}=await t.records.query(e);if(i.length>0){let{status:a,record:s}=await i[0].update({data:r.data,...r.tags!==void 0?{tags:r.tags}:{}});return{status:a,record:s}}}return{status:n.status,record:n.record}},async get(){let{records:r}=await t.records.query(e);return r.length>0?r[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function Tpe(t,e){return{async create(r,n){let{status:i,record:a}=await t.records.create(e,{...n,parentContextId:r});return{status:i,record:a}},async query(r,n){let{status:i,records:a,cursor:s}=await t.records.query(e,{...n,filter:{...n?.filter,contextId:r}});return{status:i,records:a,cursor:s}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r,n){let{liveQuery:i}=await t.records.subscribe(e,{...n,filter:{...n?.filter,contextId:r}});return i}}}function kpe(t,e){return{async set(r,n){let i=await t.records.create(e,{...n,parentContextId:r});if(w7(i.status)){let{records:a}=await t.records.query(e,{filter:{contextId:r}});if(a.length>0){let{status:s,record:o}=await a[0].update({data:n.data,...n.tags!==void 0?{tags:n.tags}:{}});return{status:s,record:o}}}return{status:i.status,record:i.record}},async get(r){let{records:n}=await t.records.query(e,{filter:{contextId:r}});return n.length>0?n[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function v7(t,e,r,n){let i=Ppe(e,r),a;n?a=i?kpe(t,r):Tpe(t,r):a=i?Spe(t,r):Epe(t,r);let s=_pe(e,r),o={};return new Proxy(a,{get(d,u){if(typeof u=="string"){if(u in d)return d[u];if(s.includes(u))return u in o||(o[u]=v7(t,e,`${r}/${u}`,!0)),o[u]}}})}function MJe(t){let e=t.definition,r=Object.keys(e.structure).filter(a=>!a.startsWith("$")),n={};return new Proxy({},{get(a,s){if(typeof s=="string"){if(s==="configure")return async o=>await t.configure(o);if(r.includes(s))return s in n||(n[s]=v7(t,e,s,!1)),n[s]}}})}y();export{vP as DidApi,bP as DwnReaderApi,g7 as Enbox,xP as LiveQuery,np as PermissionGrant,PP as PermissionGrantRevocation,_0 as PermissionRequest,E0 as Protocol,b0 as ReadOnlyRecord,jd as Record,iR as RecordChangeEvent,TP as TypedEnbox,EP as TypedLiveQuery,$c as TypedRecord,AP as VcApi,h7 as createRecordData,Npe as defineProtocol,f7 as isOk,MJe as repository,p7 as utils};
2079
+ `,e+="}",e}async paginationCursor(e){return ZI(Te.RecordsWrite,this.rawMessage)?zz(this.rawMessage,e):void 0}async update({timestamp:e,data:r,encryption:n,protocolRole:i,store:a=!0,...s}){if(this.deleted)throw new Error("Record: Cannot revive a deleted record.");let o=n??this._encryption!==void 0,{parentId:d,...u}=this._recordsWriteDescriptor,c=d?this._contextId.split("/").slice(0,-1).join("/"):void 0,l={...u,...s,parentContextId:c,protocolRole:i??this._protocolRole,messageTimestamp:e,recordId:this._recordId};(b3(l.tags)||l.tags===null)&&delete l.tags;let f;r!==void 0&&(delete l.dataCid,delete l.dataSize,{dataBlob:f}=P0(r,l.dataFormat));let h=new Set(["data","dataCid","dataFormat","dataSize","datePublished","messageTimestamp","published","tags"]);ol.verifyPermittedMutation(Object.keys(s),h),s.published===!1&&l.datePublished!==void 0&&delete l.datePublished;let p={author:this._connectedDid,dataStream:f,messageParams:{...l},messageType:Te.RecordsWrite,target:this._connectedDid,store:a,encryption:o||void 0};await this.applyDelegateGrant(p);let m=await this._agent.processDwnRequest(p),{message:g,reply:{status:_}}=m;if(!(200<=_.code&&_.code<=299))return{status:_,record:this};let v=this._initialWrite??{...this.rawMessage},E=new ol(this._agent,{author:this._author,connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:i??this._protocolRole,initialWrite:v,encodedData:r!==void 0?f:this._encodedData,...g},this._permissionsApi),T=g;return this._descriptor=T.descriptor,this._attestation=T.attestation,this._authorization=T.authorization,this._encryption=T.encryption,this._contextId=T.contextId,this._initialWrite=v,this._protocolRole=i??this._protocolRole,this._encodedData=r!==void 0?f:this._encodedData,this._readableStream=void 0,this._rawMessageDirty=!0,{status:_,record:E}}async delete(e){let{store:r=!0,signAsOwner:n,timestamp:i,prune:a=!1}=e||{},s=n&&this._delegateDid===void 0,o=n&&this._delegateDid!==void 0;if(this.deleted&&!this._initialWrite)throw new Error("Record: Record is in an invalid state, initial write is missing.");this._initialWrite||(this._initialWrite={...this.rawMessage}),await this.processInitialWriteIfNeeded({store:r,signAsOwner:n});let d={messageType:Te.RecordsDelete,author:this._connectedDid,target:this._connectedDid,signAsOwner:s,signAsOwnerDelegate:o,store:r},u=e?.protocolRole?Lz(this.rawMessage)!==e.protocolRole:!1;this.deleted&&!u?d.rawMessage=this.rawMessage:d.messageParams={prune:a,recordId:this._recordId,messageTimestamp:i,protocolRole:e?.protocolRole??this._protocolRole},await this.applyDelegateGrant(d);let c=await this._agent.processDwnRequest(d),{message:l,reply:{status:f}}=c;if(f.code!==202)return{status:f,record:this};let h=this._initialWrite,p=new ol(this._agent,{author:Wo(l),connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:e?.protocolRole??this._protocolRole,initialWrite:h,...l},this._permissionsApi),m=l;return this._descriptor=m.descriptor,this._authorization=m.authorization,this._protocolRole=e?.protocolRole??this._protocolRole,this._encodedData=void 0,this._readableStream=void 0,this._rawMessageDirty=!0,{status:f,record:p}}async processInitialWriteIfNeeded({store:e,signAsOwner:r}){if(this.initialWrite&&(r&&!this._initialWriteSigned||e&&!this._initialWriteStored)){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0,a={messageType:Te.RecordsWrite,rawMessage:this.initialWrite,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e};await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:d}}=s,u=o;200<=d.code&&d.code<=299&&(e&&(this._initialWriteStored=!0),r&&(this._initialWriteSigned=!0,this.initialWrite.authorization=u.authorization))}}async processRecord({store:e,signAsOwner:r}){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0;await this.processInitialWriteIfNeeded({store:e,signAsOwner:r});let a;this.deleted?a={messageType:Te.RecordsDelete,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e}:a={messageType:Te.RecordsWrite,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,dataStream:await this.data.blob(),signAsOwner:n,signAsOwnerDelegate:i,store:e},await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:d}}=s,u=o;return 200<=d.code&&d.code<=299&&r&&(this._authorization=u.authorization,this._rawMessageDirty=!0),{status:d}}async readRecordData({target:e,isRemote:r}){let n={author:this._connectedDid,messageParams:{filter:{recordId:this.id},protocolRole:this._protocolRole},messageType:Te.RecordsRead,target:e,...this._encryption?{encryption:!0}:{}};if(this._delegateDid)try{await this.applyDelegateGrant(n)}catch{n.author=this._delegateDid}let i=r?this._agent.sendDwnRequest(n):this._agent.processDwnRequest(n);try{let{reply:{status:a,entry:s}}=await i;if(a.code!==200)throw new Error(`${a.code}: ${a.detail}`);return s.data}catch(a){throw new Error(`Error encountered while attempting to read data: ${a.message}`)}}async applyDelegateGrant(e){if(!this._delegateDid)return;let{message:r}=await this._permissionsApi.getPermissionForRequest({connectedDid:this._connectedDid,delegateDid:this._delegateDid,protocol:this.protocol,delegate:!0,cached:!0,messageType:e.messageType});e.messageParams={...e.messageParams,delegatedGrant:r},e.granteeDid=this._delegateDid}static verifyPermittedMutation(e,r){for(let n of e)if(!r.has(n))throw new Error(`${n} is an immutable property. Its value cannot be changed.`)}isRecordsDeleteDescriptor(e){return e.interface+e.method===Te.RecordsDelete}};ol._sendCache=x0;var jd=ol;var iR=class extends CustomEvent{constructor(e){super(e.type,{detail:e})}},xP=class extends EventTarget{constructor(r){super();this._closed=!1;this._connected=!0;let{agent:n,connectedDid:i,cursor:a,delegateDid:s,protocolRole:o,remoteOrigin:d,permissionsApi:u,initialEntries:c,subscription:l}=r;this._subscription=l,this.cursor=a,this.records=c.map(f=>new jd(n,{author:Wo(f),connectedDid:i,remoteOrigin:d,delegateDid:s,protocolRole:o,...f},u)),this._knownRecords=new Map;for(let f of this.records)this._knownRecords.set(f.id,f.timestamp)}get isConnected(){return this._connected}handleEvent(r){if(this._closed)return;let n;if(r.deleted)n="delete",this._knownRecords.delete(r.id);else{let a=this._knownRecords.get(r.id);if(a!==void 0){if(r.timestamp<=a)return;n="update"}else n="create";this._knownRecords.set(r.id,r.timestamp)}let i={type:n,record:r};this.dispatchEvent(new iR(i)),this.dispatchEvent(new CustomEvent("change",{detail:i}))}handleLifecycleEvent(r,n){this._closed||(r==="disconnected"?this._connected=!1:r==="reconnected"&&(this._connected=!0),this.dispatchEvent(new CustomEvent(r,{detail:n})))}on(r,n){let i=a=>{let s=a.detail;r==="change"?n(s):r==="create"||r==="update"||r==="delete"?n(s.record):r==="reconnecting"?n(s):n()};return this.addEventListener(r,i),()=>{this.removeEventListener(r,i)}}async close(){this._closed||(this._closed=!0,await this._subscription.close())}};y();Kt();y();Kt();var PP=class t{constructor(e,r){this._permissions=e,this._connectedDid=r.connectedDid,this._message=r.message}get author(){return Wo(this._message)}static async parse({connectedDid:e,agent:r,message:n}){let i=new fi({agent:r});return new t(i,{connectedDid:e,message:n})}get agent(){return this._permissions.agent}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Ue.base64Url(r).toUint8Array()]),a={messageType:Te.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Ue.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}};var np=class t{constructor({api:e,connectedDid:r,message:n,grant:i}){this._permissions=e,this._connectedDid=r,this._message=n,this._grant=i}static parse(e){let r=dr.parse(e.message),n=new fi({agent:e.agent});return new t({...e,grant:r,api:n})}get agent(){return this._permissions.agent}get id(){return this._grant.id}get grantor(){return this._grant.grantor}get grantee(){return this._grant.grantee}get dateGranted(){return this._grant.dateGranted}get description(){return this._grant.description}get requestId(){return this._grant.requestId}get dateExpires(){return this._grant.dateExpires}get delegated(){return this._grant.delegated}get scope(){return this._grant.scope}get conditions(){return this._grant.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Ue.base64Url(r).toUint8Array()]),a={messageType:Te.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Ue.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:!0,author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async import(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Ue.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:e,author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,signAsOwner:!0,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async revoke(e=!0){let r=await this._permissions.createRevocation({store:e,author:this._connectedDid,grant:this._grant});return PP.parse({connectedDid:this._connectedDid,agent:this.agent,message:r.message})}isRevoked(e=!1){return this._permissions.isGrantRevoked({author:this._connectedDid,target:this.grantor,grantRecordId:this.id,remote:e})}toJSON(){return{id:this.id,grantor:this.grantor,grantee:this.grantee,dateGranted:this.dateGranted,description:this.description,requestId:this.requestId,dateExpires:this.dateExpires,delegated:this.delegated,scope:this.scope,conditions:this.conditions}}};y();Kt();var _0=class t{constructor({api:e,connectedDid:r,message:n,request:i}){this._permissions=e,this._connectedDid=r,this._request=i,this._message=n}static parse({connectedDid:e,agent:r,message:n}){let i=Ia.parse(n),a=new fi({agent:r});return new t({api:a,connectedDid:e,message:n,request:i})}get agent(){return this._permissions.agent}get id(){return this._request.id}get requester(){return this._request.requester}get description(){return this._request.description}get delegated(){return this._request.delegated}get scope(){return this._request.scope}get conditions(){return this._request.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Ue.base64Url(r).toUint8Array()]),a={messageType:Te.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(){let{encodedData:e,...r}=this.rawMessage,n=new Blob([Ue.base64Url(e).toUint8Array()]),{reply:i,message:a}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Te.RecordsWrite,rawMessage:r,dataStream:n});return this._message={...a,encodedData:e},{status:i.status}}async grant(e,r=!0){let{message:n}=await this._permissions.createGrant({requestId:this.id,grantedTo:this.requester,scope:this.scope,delegated:this.delegated,author:this._connectedDid,store:r,dateExpires:e});return np.parse({connectedDid:this._connectedDid,agent:this.agent,message:n})}toJSON(){return this._request}};y();var E0=class{constructor(e,r,n){this._agent=e,this._metadata=n,this._protocolsConfigureMessage=r}get definition(){return this._protocolsConfigureMessage.descriptor.definition}toJSON(){return this._protocolsConfigureMessage}async send(e){let{reply:r}=await this._agent.sendDwnRequest({author:this._metadata.author,messageCid:this._metadata.messageCid,messageType:Te.ProtocolsConfigure,target:e});return{status:r.status}}};var _P=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid,this.delegateDid=e.delegateDid,this.permissionsApi=new fi({agent:this.agent})}get isDelegate(){return this.delegateDid!==void 0}get permissions(){return{request:async e=>{let{message:r}=await this.permissionsApi.createRequest({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return _0.parse(n)},grant:async e=>{let{message:r}=await this.permissionsApi.createGrant({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return np.parse(n)},queryRequests:async(e={})=>{let{from:r,...n}=e,i=await this.permissionsApi.fetchRequests({...n,author:this.delegateDid??this.connectedDid,target:r??this.delegateDid??this.connectedDid,remote:r!==void 0}),a=[];for(let s of i){let o={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:s.message};a.push(_0.parse(o))}return a},queryGrants:async(e={})=>{let{from:r,...n}=e,i=r!==void 0,a=this.delegateDid??this.connectedDid,s=r??this.delegateDid??this.connectedDid,o=await this.permissionsApi.fetchGrants({...n,author:a,target:s,remote:i}),d=[];for(let u of o){let c={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:u.message};d.push(np.parse(c))}return d}}}get protocols(){return{configure:async e=>{let{encryption:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Te.ProtocolsConfigure,target:this.connectedDid,encryption:r};if(this.delegateDid){let{message:c}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.definition.protocol,delegate:!0,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,delegatedGrant:c},i.granteeDid=this.delegateDid}let a=await this.agent.processDwnRequest(i),{message:s,messageCid:o,reply:{status:d}}=a,u={status:d};if(d.code<300){let c={author:this.connectedDid,messageCid:o};u.protocol=new E0(this.agent,s,c)}return u},query:async e=>{let{from:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Te.ProtocolsQuery,target:r||this.connectedDid};if(this.delegateDid)try{let{grant:{id:c}}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter.protocol,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,permissionGrantId:c},i.granteeDid=this.delegateDid}catch{i.author=this.delegateDid}let a;r?a=await this.agent.sendDwnRequest(i):a=await this.agent.processDwnRequest(i);let s=a.reply,{entries:o=[],status:d}=s;return{protocols:o.map(c=>{let l={author:this.connectedDid};return new E0(this.agent,c,l)}),status:d}}}}get records(){return{delete:async e=>{let{from:r,protocol:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Te.RecordsDelete,target:r||this.connectedDid};if(this.delegateDid){let{message:d}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:d},a.granteeDid=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let{reply:{status:o}}=s;return{status:o}},query:async e=>{let{from:r,encryption:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Te.RecordsQuery,target:r||this.connectedDid,encryption:n};if(this.delegateDid)try{let{message:f}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:i.filter?.protocol,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:f},a.granteeDid=this.delegateDid}catch{a.author=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let o=s.reply,{entries:d=[],status:u,cursor:c}=o;return{records:d.map(f=>{let h={author:Wo(f),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,protocolRole:a.messageParams.protocolRole,...f};return new jd(this.agent,h,this.permissionsApi)}),status:u,cursor:c}},read:async e=>{let{from:r,protocol:n,encryption:i,...a}=e,s={author:this.connectedDid,messageParams:a,messageType:Te.RecordsRead,target:r||this.connectedDid,encryption:i};if(this.delegateDid)try{let{message:l}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:s.messageType});s.messageParams={...s.messageParams,delegatedGrant:l},s.granteeDid=this.delegateDid}catch{s.author=this.delegateDid}let o;r?o=await this.agent.sendDwnRequest(s):o=await this.agent.processDwnRequest(s);let{reply:{entry:d,status:u}}=o,c;if(200<=u.code&&u.code<=299){let l={author:Wo(d.recordsWrite),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,data:d.data,initialWrite:d.initialWrite,...d.recordsWrite};c=new jd(this.agent,l,this.permissionsApi)}return{record:c,status:u}},subscribe:async e=>{let{from:r,...n}=e,i,a=r,s=n.protocolRole,o=m=>{if(m.type==="eose"){i?.handleLifecycleEvent("eose");return}if(m.type==="disconnected"){i?.handleLifecycleEvent("disconnected");return}if(m.type==="reconnected"){i?.handleLifecycleEvent("reconnected");return}if(m.type==="reconnecting"){i?.handleLifecycleEvent("reconnecting",{attempt:m.attempt});return}let{message:g,initialWrite:_}=m.event,v=new jd(this.agent,{...g,author:Wo(g),connectedDid:this.connectedDid,remoteOrigin:a,initialWrite:_,protocolRole:s,delegateDid:this.delegateDid},this.permissionsApi);i?.handleEvent(v)},d={author:this.connectedDid,messageParams:n,messageType:Te.RecordsSubscribe,target:r||this.connectedDid,subscriptionHandler:o};if(this.delegateDid)try{let{message:m}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter?.protocol,delegate:!0,cached:!0,messageType:d.messageType});d.messageParams={...d.messageParams,delegatedGrant:m},d.granteeDid=this.delegateDid}catch{d.author=this.delegateDid}let u;r?u=await this.agent.sendDwnRequest(d):u=await this.agent.processDwnRequest(d);let c=u.reply,{status:l,subscription:f,entries:h=[],cursor:p}=c;return f&&(i=new xP({agent:this.agent,connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocolRole:s,remoteOrigin:a,permissionsApi:this.permissionsApi,initialEntries:h,cursor:p,subscription:f})),{status:l,liveQuery:i}},write:async e=>{let{data:r,store:n,encryption:i,...a}=e,{dataBlob:s,dataFormat:o}=P0(r,a.dataFormat),d={...a,dataFormat:o},u={store:n,messageType:Te.RecordsWrite,messageParams:d,author:this.connectedDid,target:this.connectedDid,dataStream:s,encryption:i};if(this.delegateDid){let{message:p}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:d.protocol,delegate:!0,cached:!0,messageType:u.messageType});u.messageParams={...u.messageParams,delegatedGrant:p},u.granteeDid=this.delegateDid}let c=await this.agent.processDwnRequest(u),{message:l,reply:{status:f}}=c,h;if(200<=f.code&&f.code<=299){let p={author:this.connectedDid,connectedDid:this.connectedDid,encodedData:s,delegateDid:this.delegateDid,...l};h=new jd(this.agent,p,this.permissionsApi)}return{record:h,status:f}}}}};y();y();y();var $c=class t{constructor(e){this._record=e}get rawRecord(){return this._record}get data(){let e=this._record.data;return{blob:()=>e.blob(),bytes:()=>e.bytes(),json:()=>e.json(),text:()=>e.text(),stream:()=>e.stream(),then:e.then.bind(e),catch:e.catch.bind(e)}}async update(e){let{status:r,record:n}=await this._record.update(e);return{status:r,record:new t(n)}}async delete(e){let{status:r,record:n}=await this._record.delete(e);return{status:r,record:new t(n)}}async store(e=!1){return this._record.store(e)}async import(e=!0){return this._record.import(e)}async send(e){return this._record.send(e)}toJSON(){return this._record.toJSON()}toString(){return this._record.toString()}async paginationCursor(e){return this._record.paginationCursor(e)}get id(){return this._record.id}get contextId(){return this._record.contextId}get dateCreated(){return this._record.dateCreated}get parentId(){return this._record.parentId}get protocol(){return this._record.protocol}get protocolPath(){return this._record.protocolPath}get recipient(){return this._record.recipient}get schema(){return this._record.schema}get dataFormat(){return this._record.dataFormat}get dataCid(){return this._record.dataCid}get dataSize(){return this._record.dataSize}get datePublished(){return this._record.datePublished}get published(){return this._record.published}get tags(){return this._record.tags}get author(){return this._record.author}get creator(){return this._record.creator}get timestamp(){return this._record.timestamp}get encryption(){return this._record.encryption}get authorization(){return this._record.authorization}get attestation(){return this._record.attestation}get protocolRole(){return this._record.protocolRole}get deleted(){return this._record.deleted}get initialWrite(){return this._record.initialWrite}get rawMessage(){return this._record.rawMessage}};var EP=class{constructor(e){this._liveQuery=e}get rawLiveQuery(){return this._liveQuery}get records(){return this._typedRecords||(this._typedRecords=this._liveQuery.records.map(e=>new $c(e))),this._typedRecords}get cursor(){return this._liveQuery.cursor}get isConnected(){return this._liveQuery.isConnected}on(e,r){return e==="disconnected"?this._liveQuery.on("disconnected",r):e==="reconnected"?this._liveQuery.on("reconnected",r):e==="eose"?this._liveQuery.on("eose",r):e==="reconnecting"?this._liveQuery.on("reconnecting",r):e==="change"?this._liveQuery.on("change",n=>{r({type:n.type,record:new $c(n.record)})}):this._liveQuery.on(e,n=>{r(new $c(n))})}async close(){return this._liveQuery.close()}};var TP=class{constructor(e,r){this._configured=!1;this._ensureReadyPromise=null;this._dwn=e,this._definition=r.definition,this._validPaths=y7(this._definition.structure)}get protocol(){return this._definition.protocol}get definition(){return this._definition}async configure(e){let{protocols:r}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(r.length>0){let a=r[0];if(m7(a.definition,this._definition))return this._configured=!0,{status:{code:200,detail:"OK"},protocol:a}}let n=!this._dwn.isDelegate&&Object.values(this._definition.types).some(a=>a?.encryptionRequired===!0),i=await this._dwn.protocols.configure({definition:this._definition,encryption:e?.encryption??(n||void 0)});return i.status.code===202&&(this._configured=!0),i}get isConfigured(){return this._configured}async subscribe(e){await this._autoConfigureOnce();let{liveQuery:r}=await this._dwn.records.subscribe({from:e?.from,filter:{protocol:this._definition.protocol}});return r}_assertValidPath(e){if(!this._validPaths.has(e))throw new Error(`TypedEnbox: invalid protocol path '${e}'. Valid paths are: ${[...this._validPaths].join(", ")}.`)}async _ensureReady(e){if(this._configured){this._assertValidPath(e);return}this._ensureReadyPromise===null&&(this._ensureReadyPromise=this._autoConfigureOnce()),await this._ensureReadyPromise,this._assertValidPath(e)}async _autoConfigureOnce(){let{protocols:e}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(e.length>0){let i=e[0];if(m7(i.definition,this._definition)){this._configured=!0;return}console.warn(`TypedEnbox: installed protocol '${this._definition.protocol}' differs from the provided definition. Call configure() to update it.`),this._configured=!0;return}let r=!this._dwn.isDelegate&&Object.values(this._definition.types).some(i=>i?.encryptionRequired===!0);(await this._dwn.protocols.configure({definition:this._definition,encryption:r||void 0})).status.code===202&&(this._configured=!0)}get records(){if(this._records!==void 0)return this._records;let e={create:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=!this._dwn.isDelegate&&s?.encryptionRequired===!0?!0:void 0,{status:d,record:u}=await this._dwn.records.write({data:n.data,store:n.store,encryption:n.encryption??o,parentContextId:n.parentContextId,published:n.published,datePublished:n.datePublished,recipient:n.recipient,protocolRole:n.protocolRole,tags:n.tags,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{},dataFormat:n.dataFormat??s?.dataFormats?.[0]});return{status:d,record:u?new $c(u):void 0}},query:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=oR(n?.filter),d=!this._dwn.isDelegate&&s?.encryptionRequired===!0?!0:void 0,{status:u,records:c,cursor:l}=await this._dwn.records.query({from:n?.from,encryption:n?.encryption??d,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{}},dateSort:n?.dateSort,pagination:n?.pagination,protocolRole:n?.protocolRole});return{status:u,records:c.map(f=>new $c(f)),cursor:l}},read:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=oR(n.filter),d=!this._dwn.isDelegate&&s?.encryptionRequired===!0?!0:void 0,{status:u,record:c}=await this._dwn.records.read({from:n.from,encryption:n.encryption??d,protocol:this._definition.protocol,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{}}});return{status:u,record:c?new $c(c):void 0}},delete:async(r,n)=>(await this._ensureReady(S0(r)),this._dwn.records.delete({from:n.from,protocol:this._definition.protocol,recordId:n.recordId})),subscribe:async(r,n)=>{let i=S0(r);await this._ensureReady(i);let a=SP(i),s=this._definition.types[a],o=oR(n?.filter),{status:d,liveQuery:u}=await this._dwn.records.subscribe({from:n?.from,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema!==void 0?{schema:s.schema}:{}},protocolRole:n?.protocolRole});return{status:d,liveQuery:u?new EP(u):void 0}}};return this._records=e,e}};function oR(t){if(!t)return;let{parentContextId:e,...r}=t;return e!==void 0&&r.parentId===void 0&&(r.parentId=e),r}function m7(t,e){return kP(t)===kP(e)}function S0(t){return t.replace(/^\/+|\/+$/g,"")}function SP(t){let e=t.split("/");return e[e.length-1]}function y7(t,e=""){let r=new Set;for(let n of Object.keys(t)){if(n.startsWith("$"))continue;let i=e?`${e}/${n}`:n;r.add(i);let a=t[n];if(a!==null&&typeof a=="object")for(let s of y7(a,i))r.add(s)}return r}function kP(t){return t==null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>kP(n)).join(",")+"]":"{"+Object.keys(t).sort().map(n=>JSON.stringify(n)+":"+kP(t[n])).join(",")+"}"}y();var AP=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(){throw new Error("Not implemented.")}};var g7=class t{constructor({agent:e,connectedDid:r,delegateDid:n}){this._typedInstances=new Map;this.agent=e,this.did=new vP({agent:e,connectedDid:r}),this._dwn=new _P({agent:e,connectedDid:r,delegateDid:n}),this.vc=new AP({agent:e,connectedDid:r})}using(e){let r=e.definition.protocol,n=this._typedInstances.get(r);if(n)return n;let i=new TP(this._dwn,e);return this._typedInstances.set(r,i),i}async disconnect(e){"sync"in this.agent&&typeof this.agent.sync?.stopSync=="function"&&await this.agent.sync.stopSync(e),this._typedInstances.clear()}static anonymous(e){let r=new s0({didResolvers:e?.didResolvers??[tl,Jf,qx,kI],cache:new Lx}),n=new Rm,i=new lP({didResolver:r,rpcClient:n});return{dwn:new bP(i)}}static connect(e){if("session"in e){let{session:r}=e;return new t({agent:r.agent,connectedDid:r.did,delegateDid:r.delegateDid})}return new t(e)}};y();y();y();function w7(t){return t.code===400&&t.detail.includes("record limit")}function Ppe(t,e){let r=e.split("/"),n=t.structure;for(let a of r){if(!n||typeof n!="object")return!1;n=n[a]}if(!n||typeof n!="object")return!1;let i=n.$recordLimit;return i!==void 0&&typeof i=="object"&&i!==null&&i.max===1}function _pe(t,e){let r=e.split("/"),n=t.structure;for(let i of r){if(!n||typeof n!="object")return[];n=n[i]}return!n||typeof n!="object"?[]:Object.keys(n).filter(i=>!i.startsWith("$"))}function Epe(t,e){return{async create(r){let{status:n,record:i}=await t.records.create(e,r);return{status:n,record:i}},async query(r){let{status:n,records:i,cursor:a}=await t.records.query(e,r);return{status:n,records:i,cursor:a}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r){let{liveQuery:n}=await t.records.subscribe(e,r);return n}}}function Spe(t,e){return{async set(r){let n=await t.records.create(e,r);if(w7(n.status)){let{records:i}=await t.records.query(e);if(i.length>0){let{status:a,record:s}=await i[0].update({data:r.data,...r.tags!==void 0?{tags:r.tags}:{}});return{status:a,record:s}}}return{status:n.status,record:n.record}},async get(){let{records:r}=await t.records.query(e);return r.length>0?r[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function Tpe(t,e){return{async create(r,n){let{status:i,record:a}=await t.records.create(e,{...n,parentContextId:r});return{status:i,record:a}},async query(r,n){let{status:i,records:a,cursor:s}=await t.records.query(e,{...n,filter:{...n?.filter,contextId:r}});return{status:i,records:a,cursor:s}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r,n){let{liveQuery:i}=await t.records.subscribe(e,{...n,filter:{...n?.filter,contextId:r}});return i}}}function kpe(t,e){return{async set(r,n){let i=await t.records.create(e,{...n,parentContextId:r});if(w7(i.status)){let{records:a}=await t.records.query(e,{filter:{contextId:r}});if(a.length>0){let{status:s,record:o}=await a[0].update({data:n.data,...n.tags!==void 0?{tags:n.tags}:{}});return{status:s,record:o}}}return{status:i.status,record:i.record}},async get(r){let{records:n}=await t.records.query(e,{filter:{contextId:r}});return n.length>0?n[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function v7(t,e,r,n){let i=Ppe(e,r),a;n?a=i?kpe(t,r):Tpe(t,r):a=i?Spe(t,r):Epe(t,r);let s=_pe(e,r),o={};return new Proxy(a,{get(d,u){if(typeof u=="string"){if(u in d)return d[u];if(s.includes(u))return u in o||(o[u]=v7(t,e,`${r}/${u}`,!0)),o[u]}}})}function MJe(t){let e=t.definition,r=Object.keys(e.structure).filter(a=>!a.startsWith("$")),n={};return new Proxy({},{get(a,s){if(typeof s=="string"){if(s==="configure")return async o=>await t.configure(o);if(r.includes(s))return s in n||(n[s]=v7(t,e,s,!1)),n[s]}}})}y();export{vP as DidApi,bP as DwnReaderApi,g7 as Enbox,xP as LiveQuery,np as PermissionGrant,PP as PermissionGrantRevocation,_0 as PermissionRequest,E0 as Protocol,b0 as ReadOnlyRecord,jd as Record,iR as RecordChangeEvent,TP as TypedEnbox,EP as TypedLiveQuery,$c as TypedRecord,AP as VcApi,h7 as createRecordData,Npe as defineProtocol,f7 as isOk,MJe as repository,p7 as utils};
2080
2080
  /*! Bundled license information:
2081
2081
 
2082
2082
  ieee754/index.js: