@enbox/api 0.6.23 → 0.6.24

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
- `);Ho();jt();y();y();nn();y();jt();nn();y();jt();nn();y();nn();nn();Nn();y();jt();nn();y();Ho();y();jt();y();y();var k7=wn(xx(),1);Nn();import{Level as Rhe}from"level";y();var She=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function khe(t){let e=[],r=[];for(let n of t)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?r.push(n.messageCid):e.push(n):r.push(n.messageCid);return{prefetched:e,needsFetchCids:r}}var Ex=class{constructor(e){this._deps=e}reconcile(e,r){return She(this,void 0,void 0,function*(){var n;let{did:i,dwnUrl:a,delegateDid:s,protocol:o}=e,c=r?.direction,l=(n=r?.verifyConvergence)!==null&&n!==void 0?n:!1,d=this._deps.shouldContinue,u=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=yield this._deps.getRemoteRoot(i,a,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let p=!1,h=!1,m;if(u!==f){let w=yield this._deps.diffWithRemote(e);if(d&&!d())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:u,remoteRoot:f};if((!c||c==="pull")&&w.onlyRemote.length>0){let{prefetched:E,needsFetchCids:k}=khe(w.onlyRemote);if(yield this._deps.pullMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:k,prefetched:E}),d&&!d())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:u,remoteRoot:f};p=!0}if((!c||c==="push")&&w.onlyLocal.length>0){if(m=yield this._deps.pushMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:w.onlyLocal}),d&&!d())return{aborted:!0,changed:!0,didPull:p,didPush:!0,localRoot:u,remoteRoot:f,pushResult:m};h=!0}}if(!l)return{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let g=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let _=yield this._deps.getRemoteRoot(i,a,s,o);return d&&!d()?{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m}:{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,postLocalRoot:g,postRemoteRoot:_,converged:g===_,pushResult:m}})}};y();Nn();function b7(t){let e=t.descriptor;return e.interface!==Le.Records||e.method!==Ue.Write?!1:e.dateCreated===e.messageTimestamp}function Am(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let u=0;u<t.length;u++){let f=t[u];r.set(u,f);let p=f.message.descriptor;if(p.interface===Le.Protocols&&p.method===Ue.Configure){let h=(e=p.definition)===null||e===void 0?void 0:e.protocol;h&&n.set(h,u)}if(p.interface===Le.Records&&p.method===Ue.Write){let h=f.message.recordId;b7(f.message)&&h&&i.set(h,u),p.protocol===Et.uri&&p.protocolPath===Et.grantPath&&h&&a.set(h,u)}}let s=new Map,o=new Array(t.length).fill(0),c=(u,f)=>{if(u===f)return;s.has(u)||s.set(u,new Set);let p=s.get(u);p.has(f)||(p.add(f),o[f]++)};for(let u=0;u<t.length;u++){let f=t[u].message.descriptor;if(f.interface===Le.Records){let h=f.protocol;h&&n.has(h)&&c(n.get(h),u)}if(f.interface===Le.Records&&f.parentId){let h=f.parentId;i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Write){let h=t[u].message.recordId;h&&!b7(t[u].message)&&i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Delete){let h=f.recordId;h&&i.has(h)&&c(i.get(h),u)}let p=f.permissionGrantId;p&&a.has(p)&&c(a.get(p),u)}let l=[];for(let u=0;u<t.length;u++)o[u]===0&&l.push(u);let d=[];for(;l.length>0;){let u=l.shift();d.push(r.get(u));let f=s.get(u);if(f)for(let p of f)o[p]--,o[p]===0&&l.push(p)}if(d.length<t.length){let u=new Set(d);for(let f=0;f<t.length;f++){let p=r.get(f);u.has(p)||d.push(p)}}return d}y();var Sx="^";function P7(t,e,r){return`${t}${Sx}${e}${Sx}${r}`}function xv(t,e,r){let n=`${t}${Sx}${e}`;return r?`${n}${Sx}${r}`:n}y();Nn();var ah=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},The=1048576;function x7(t,e){var r,n;return t.status.code===202||t.status.code===204||t.status.code===409||t.status.code===404&&(e?.descriptor.interface===Le.Records&&e?.descriptor.method===Ue.Delete||((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.interface)===Le.Records&&((n=t.entry)===null||n===void 0?void 0:n.message.descriptor.method)===Ue.Delete)}function Dhe(t){return t.status.code===400||t.status.code===401||t.status.code===403}function mR(t){return ah(this,void 0,void 0,function*(){try{return yield be.getCid(t)}catch{return"unknown"}})}function _7(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:c}){let l=[];if(s)for(let g of s){if(!g.message)continue;let _={message:g.message};if(g.encodedData){let w=ke.base64UrlToBytes(g.encodedData);_.bufferedData=w,_.dataStream=new ReadableStream({start(E){E.enqueue(w),E.close()}})}l.push(_)}let d=a.length>0?yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:c}):[],u=[...l,...d],f=Am(u);yield Ihe(f);let p=3,h=f;for(let g=0;g<=p&&h.length>0;g++){let _=[];for(let w of h){let E=w.bufferedData?new ReadableStream({start(D){D.enqueue(w.bufferedData),D.close()}}):w.dataStream,k=yield o.dwn.processRawMessage(e,w.message,{dataStream:E});x7(k)||_.push(w)}if(_.length>0){let w=[],E=[];for(let k of _)if(k.bufferedData||!k.dataStream)E.push(k);else{let D=yield mR(k.message);w.push(D)}if(w.length>0){let k=yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:w,agent:o,permissionsApi:c});E.push(...k)}h=Am(E)}else h=[]}let m=[];for(let g of h){let _=yield mR(g.message);m.push(_)}return m})}function Ihe(t){return ah(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:c,value:l}=yield a.read();if(c)break;if(n+=l.byteLength,n>The){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let c of r)s.set(c,o),o+=c.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(c){c.enqueue(s),c.close()}})}})}function kx(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let c=[],l;n&&(l=(yield o.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id);let d=4,u=0;for(;u<a.length;){let f=a.slice(u,u+d);u+=d;let p=yield Promise.all(f.map(h=>ah(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Se.MessagesRead,granteeDid:n,messageParams:{messageCid:h,permissionGrantId:l}}),w;try{w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(w.status.code!==200||!(!((g=w.entry)===null||g===void 0)&&g.message))return;let E=w.entry,k;return oh(E)&&E.data&&(k=E.data),{message:E.message,dataStream:k}})));for(let h of p)h&&c.push(h)}return c})}function yR(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var c,l,d;let u=[],f=[],p=[],h=[];for(let g of a){let _=yield Ahe({author:e,messageCid:g,delegateDid:n,protocol:i,agent:s,permissionsApi:o});_?h.push(_):f.push(g)}let m=Am(h);for(let g of m){let _=yield mR(g.message);try{let w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:g.dataStream,message:g.message});x7(w,g.message)?u.push(_):Dhe(w)?(w.status.code===400&&(!((c=w.status.detail)===null||c===void 0)&&c.includes("record limit"))?console.debug(`SyncEngineLevel: singleton already exists on remote, skipping push for ${_}`):console.warn(`SyncEngineLevel: push permanently failed for ${_}: ${w.status.code} ${w.status.detail}`),p.push({cid:_,statusCode:w.status.code,detail:(l=w.status.detail)!==null&&l!==void 0?l:""})):(console.error(`SyncEngineLevel: push failed for ${_}: ${w.status.code} ${w.status.detail}`),f.push(_))}catch(w){console.error(`SyncEngineLevel: push error for ${_}: ${(d=w.message)!==null&&d!==void 0?d:w}`),f.push(_)}}return{succeeded:u,failed:f,permanentlyFailed:p}})}function Ahe(t){return ah(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:Se.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let{reply:c}=yield a.dwn.processRequest({author:e,target:e,messageType:Se.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(c.status.code!==200||!c.entry)return;let l=c.entry,d={message:l.message};return oh(l)&&l.data&&(d.dataStream=l.data),d})}var He=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Rm=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,c){s=t[a](s),i(o,c,s.done,s.value)})}}function i(a,s,o,c){Promise.resolve(c).then(function(l){a({value:l,done:o})},s)}},Che=16,E7=8,$he=100;function S7(t,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let r=t.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=r.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=t.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var oa=class t{static validateSyncIdentityOptions(e){if(!e||!("protocols"in e))throw new Error("SyncEngineLevel: options.protocols is required \u2014 pass 'all' for a full replica or a non-empty protocol list.");if(e.protocols!=="all"&&!Array.isArray(e.protocols))throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty string array.");if(Array.isArray(e.protocols)&&e.protocols.length===0)throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty array of protocol URIs. An empty array is ambiguous.")}constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1,this._activeLinks=new Map,this._linkRuntimes=new Map,this._syncMode="poll",this._engineGeneration=0,this._liveSubscriptions=[],this._localSubscriptions=[],this._connectivityState="unknown",this._eventListeners=new Set,this._pushRuntimes=new Map,this._recentlyPulledCids=new Map,this._closureContexts=new Map,this._syncTargetsCacheGeneration=0,this._consecutiveFailures=0,this._degradedPollTimers=new Map,this._repairAttempts=new Map,this._activeRepairs=new Map,this._repairRetryTimers=new Map,this._repairContext=new Map,this._reconcileTimers=new Map,this._reconcileInFlight=new Map,this._agent=e,this._permissionsApi=new Xn({agent:e}),this._db=n||new Rhe(r??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new zi(this._db)),this._ledger}get _deadLetters(){return this._db.sublevel("deadLetters")}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 Xn({agent:e}),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++}get hasActiveSubscriptions(){return this._liveSubscriptions.length>0||this._localSubscriptions.length>0}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,r=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(r=!0);return e?"online":r?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let r of this._eventListeners)try{r(e)}catch{}}clear(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0,yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),yield this._db.close()})}registerIdentity(e){return He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(n);let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);yield i.put(r,JSON.stringify(n)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,this._syncMode==="live"&&(yield this.addIdentityToLiveSync(r,n))})}unregisterIdentity(e){return He(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.`);this._syncMode==="live"&&(yield this.removeIdentityFromLiveSync(e)),yield r.del(e),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++})}getIdentityOptions(e){return He(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 He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(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)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.ledger.updateDelegateDid(r,n.delegateDid),this._syncMode==="live"&&this.hasActiveLinksForDid(r)&&(yield this.removeIdentityFromLiveSync(r),yield this.addIdentityToLiveSync(r,n))})}sync(e){return He(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 Map;for(let o of r){let c=n.get(o.dwnUrl);c||(c=[],n.set(o.dwnUrl,c)),c.push(o)}let i=0,a=0,s=yield Promise.allSettled([...n.entries()].map(o=>He(this,[o],void 0,function*([c,l]){for(let d of l){let{did:u,delegateDid:f,protocol:p}=d;try{yield this.createLinkReconciler().reconcile({did:u,dwnUrl:c,delegateDid:f,protocol:p},{direction:e})}catch(h){a++,console.error(`SyncEngineLevel: Error syncing ${u} with ${c}`,h);return}}i++})));for(let o of s)o.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):r.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}})}startSync(e){return He(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,k7.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 He(this,arguments,void 0,function*(e=2e3){this._engineGeneration++;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),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0})}startPollSync(e){return He(this,void 0,void 0,function*(){let r=this._engineGeneration,n=()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==r||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(s){console.error("SyncEngineLevel: Error during sync operation",s)}let i=Math.min(Math.pow(2,this._consecutiveFailures),t.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===r&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))});this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||(yield this.sync())})}startLiveSync(e){return He(this,void 0,void 0,function*(){this.startBrowserConnectivityListeners();try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();yield Promise.allSettled(r.map(i=>this.initializeLinkTarget(i)));let n=()=>He(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)})}getOrCreateRuntime(e){let r=this._linkRuntimes.get(e);return r||(r={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,r)),r}drainCommittedPull(e){let r=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!r||!n)return 0;let i=0;for(;;){let a=r.inflight.get(r.nextCommitOrdinal);if(!a?.committed)break;zi.commitContiguousToken(n.pull,a.token),zi.setReceivedToken(n.pull,a.token),r.inflight.delete(r.nextCommitOrdinal),r.nextCommitOrdinal++,i++}return i}transitionToRepairing(e,r,n){return He(this,void 0,void 0,function*(){let i=r.status,a=r.connectivity;r.connectivity="offline",yield this.ledger.setStatus(r,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let s=this._linkRuntimes.get(e);s&&(s.inflight.clear(),s.nextCommitOrdinal=s.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})})}scheduleRepairRetry(e){var r;let n=this._activeLinks.get(e);if(!n||n.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let i=(r=this._repairAttempts.get(e))!==null&&r!==void 0?r:1,a=t.REPAIR_BACKOFF_MS,s=a[Math.min(i-1,a.length-1)],o=this._engineGeneration,c=setTimeout(()=>He(this,void 0,void 0,function*(){if(this._repairRetryTimers.delete(e),this._engineGeneration!==o)return;let l=this._activeLinks.get(e);if(l?.status==="repairing")try{yield this.repairLink(e)}catch{l.status==="repairing"&&this.scheduleRepairRetry(e)}}),s);this._repairRetryTimers.set(e,c)}repairLink(e){let r=this._activeRepairs.get(e);if(r)return r;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}doRepairLink(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=this._activeLinks.get(e);if(!s)return;let o=this._engineGeneration,c=()=>this._activeLinks.get(e)!==s,{tenantDid:l,remoteEndpoint:d,delegateDid:u,protocol:f}=s;this.emitEvent({type:"repair:started",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:((r=this._repairAttempts.get(e))!==null&&r!==void 0?r:0)+1});let p=((n=this._repairAttempts.get(e))!==null&&n!==void 0?n:0)+1;if(this._repairAttempts.set(e,p),yield this.closeLinkSubscriptions(s),this._engineGeneration!==o||c())return;let h=this.getOrCreateRuntime(e);h.inflight.clear(),h.nextDeliveryOrdinal=0,h.nextCommitOrdinal=0;try{if((yield this.createLinkReconciler(()=>this._engineGeneration===o&&!c()).reconcile({did:l,dwnUrl:d,delegateDid:u,protocol:f})).aborted)return;let g=this._repairContext.get(e),_=(i=g?.resumeToken)!==null&&i!==void 0?i:s.pull.contiguousAppliedToken;if(zi.resetCheckpoint(s.pull,_),yield this.ledger.saveLink(s),this._engineGeneration!==o||c()||(s.needsReconcile=!0,yield this.ledger.saveLink(s),this._engineGeneration!==o||c()))return;let w={did:l,dwnUrl:d,delegateDid:u,protocol:f,linkKey:e};try{yield this.openLivePullSubscription(w)}catch(D){if(D.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${l} -> ${d}, resetting to start fresh`),zi.resetCheckpoint(s.pull),yield this.ledger.saveLink(s),this._engineGeneration!==o||c())return;yield this.openLivePullSubscription(w)}else throw D}if(this._engineGeneration!==o||c())return;try{yield this.openLocalPushSubscription(w)}catch(D){let R=this._liveSubscriptions.find(U=>U.linkKey===e);if(R){try{yield R.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(U=>U!==R)}throw D}if(this._engineGeneration!==o||c())return;this._repairContext.delete(e),this._repairAttempts.delete(e);let E=this._repairRetryTimers.get(e);E&&(clearTimeout(E),this._repairRetryTimers.delete(e));let k=s.connectivity;s.connectivity="online",yield this.ledger.setStatus(s,"live"),this.clearDeadLettersForLink(l,d,f),this.emitEvent({type:"repair:completed",tenantDid:l,remoteEndpoint:d,protocol:f}),k!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:k,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:"repairing",to:"live"})}catch(m){if(this._engineGeneration!==o||c())return;if(console.error(`SyncEngineLevel: Repair failed for ${l} -> ${d} (attempt ${p})`,m),this.emitEvent({type:"repair:failed",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:p,error:String((a=m.message)!==null&&a!==void 0?a:m)}),p>=t.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${l} -> ${d}, entering degraded_poll`),yield this.enterDegradedPoll(e);return}throw m}})}closeLinkSubscriptions(e){return He(this,void 0,void 0,function*(){let{tenantDid:r,remoteEndpoint:n}=e,i=this.buildLinkKey(r,n,e.scopeId),a=this._liveSubscriptions.find(o=>o.linkKey===i);if(a){try{yield a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(o=>o!==a)}let s=this._localSubscriptions.find(o=>o.linkKey===i);if(s){try{yield s.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(o=>o!==s)}})}enterDegradedPoll(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r)return;r.connectivity="offline";let n=r.status;yield this.ledger.setStatus(r,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,s=new Uint32Array(1),o;do crypto.getRandomValues(s),o=s[0]&16383;while(o>=a);let c=a+o,l=this._engineGeneration,d=setInterval(()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==l){clearInterval(d),this._degradedPollTimers.delete(e);return}let u=this._activeLinks.get(e);if(u?.status!=="degraded_poll"){clearInterval(d),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),yield this.ledger.setStatus(u,"repairing"),yield this.repairLink(e),u.status==="live"&&(clearInterval(d),this._degradedPollTimers.delete(e))}catch{this._activeLinks.get(e)===u&&(yield this.ledger.setStatus(u,"degraded_poll"))}}),c);this._degradedPollTimers.set(e,d)})}startBrowserConnectivityListeners(){if(this.stopBrowserConnectivityListeners(),typeof globalThis.addEventListener!="function")return;let e=this._engineGeneration;this._onOnline=()=>{this._engineGeneration===e&&(console.info("SyncEngineLevel: browser online \u2014 triggering immediate integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-online sync failed",r)}))},this._onOffline=()=>{if(this._engineGeneration===e){console.info("SyncEngineLevel: browser offline"),this._connectivityState="offline";for(let r of this._activeLinks.values()){let n=r.connectivity;n!=="offline"&&(r.connectivity="offline",this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"offline"}))}}},this._onVisibilityChange=()=>{this._engineGeneration===e&&(typeof document>"u"||document.visibilityState!=="visible"||(console.info("SyncEngineLevel: page became visible \u2014 triggering integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-visibility sync failed",r)})))},globalThis.addEventListener("online",this._onOnline),globalThis.addEventListener("offline",this._onOffline),typeof document<"u"&&document.addEventListener("visibilitychange",this._onVisibilityChange)}stopBrowserConnectivityListeners(){this._onOnline&&(globalThis.removeEventListener("online",this._onOnline),this._onOnline=void 0),this._onOffline&&(globalThis.removeEventListener("offline",this._onOffline),this._onOffline=void 0),this._onVisibilityChange&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0)}teardownLiveSync(){return He(this,void 0,void 0,function*(){this.stopBrowserConnectivityListeners(),this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.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=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()})}initializeLinkTarget(e){return He(this,void 0,void 0,function*(){var r;let n;try{let i=e.protocol?{kind:"protocol",protocol:e.protocol}:{kind:"full"};n=yield this.ledger.getOrCreateLink({tenantDid:e.did,remoteEndpoint:e.dwnUrl,scope:i,delegateDid:e.delegateDid,protocol:e.protocol});let a=this.buildLinkKey(e.did,e.dwnUrl,n.scopeId);if(!n.pull.contiguousAppliedToken){let o=xv(e.did,e.dwnUrl,e.protocol),c=yield this.getCursor(o);c&&(zi.resetCheckpoint(n.pull,c),yield this.ledger.saveLink(n),yield this.deleteLegacyCursor(o))}this._activeLinks.set(a,n);let s=Object.assign(Object.assign({},e),{linkKey:a});yield this.openLivePullSubscription(s);try{yield this.openLocalPushSubscription(s)}catch(o){let c=this._liveSubscriptions.find(l=>l.linkKey===a);if(c){try{yield c.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(l=>l!==c)}throw o}this.emitEvent({type:"link:status-change",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,from:"initializing",to:"live"}),yield this.ledger.setStatus(n,"live"),n.needsReconcile&&this.scheduleReconcile(a,1e3)}catch(i){let a=n?this.buildLinkKey(e.did,e.dwnUrl,n.scopeId):xv(e.did,e.dwnUrl,e.protocol);if(i.isProgressGap&&n){console.warn(`SyncEngineLevel: ProgressGap detected for ${e.did} -> ${e.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,reason:"ProgressGap"}),yield this.transitionToRepairing(a,n,{resumeToken:(r=i.gapInfo)===null||r===void 0?void 0:r.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${e.did} -> ${e.dwnUrl}`,i),this._activeLinks.delete(a),this._linkRuntimes.delete(a),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}})}isLinkKeyForDid(e,r){return e.startsWith(r+"^")||e.startsWith(r+"_")}hasActiveLinksForDid(e){for(let r of this._activeLinks.keys())if(this.isLinkKeyForDid(r,e))return!0;return!1}addIdentityToLiveSync(e,r){return He(this,void 0,void 0,function*(){let{protocols:n,delegateDid:i}=r,a=yield this.agent.dwn.getDwnEndpointUrlsForTarget(e);if(a.length===0)return;let s=[];for(let o of a)if(n==="all")s.push({did:e,delegateDid:i,dwnUrl:o});else for(let c of n)s.push({did:e,delegateDid:i,dwnUrl:o,protocol:c});yield Promise.allSettled(s.map(o=>this.initializeLinkTarget(o)))})}removeIdentityFromLiveSync(e){return He(this,void 0,void 0,function*(){for(let r of this._liveSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(r=>r.did!==e);for(let r of this._localSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(r=>r.did!==e);for(let[r,n]of this._pushRuntimes)n.did===e&&(n.timer&&clearTimeout(n.timer),this._pushRuntimes.delete(r));for(let[r,n]of this._degradedPollTimers)this.isLinkKeyForDid(r,e)&&(clearInterval(n),this._degradedPollTimers.delete(r));for(let r of this._repairAttempts.keys())this.isLinkKeyForDid(r,e)&&this._repairAttempts.delete(r);for(let r of this._activeRepairs.keys())this.isLinkKeyForDid(r,e)&&this._activeRepairs.delete(r);for(let r of this._repairContext.keys())this.isLinkKeyForDid(r,e)&&this._repairContext.delete(r);for(let[r,n]of this._repairRetryTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._repairRetryTimers.delete(r));for(let[r,n]of this._reconcileTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._reconcileTimers.delete(r));for(let r of this._reconcileInFlight.keys())this.isLinkKeyForDid(r,e)&&this._reconcileInFlight.delete(r);for(let r of this._activeLinks.keys())this.isLinkKeyForDid(r,e)&&(this._activeLinks.delete(r),this._linkRuntimes.delete(r));this._closureContexts.delete(e)})}openLivePullSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=e.linkKey,c=this._activeLinks.get(o),l=c?.pull.contiguousAppliedToken;l&&(!l.streamId||!l.messageCid||!l.epoch||!l.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${n} -> ${a}`),l=void 0,c&&(zi.resetCheckpoint(c.pull),yield this.ledger.saveLink(c)));let d=c?.scope.kind==="protocol"?(r=c.scope.protocolPathPrefixes)===null||r===void 0?void 0:r[0]:void 0,u=s?[Object.assign({protocol:s},d?{protocolPathPrefix:d}:{})]:[],f;i&&(f=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let p=this._engineGeneration,h=c,m=()=>this._engineGeneration!==p||!this._activeLinks.has(o)||h!==void 0&&this._activeLinks.get(o)!==h,g=C=>He(this,void 0,void 0,function*(){var F;if(!m()){if(C.type==="eose"){if(c){if(c.status!=="live"&&c.status!=="initializing")return;if(!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o),m())return;yield this.ledger.saveLink(c)}if(c){let L=c.connectivity;c.connectivity="online",L!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:L,to:"online"}),c.needsReconcile&&this.scheduleReconcile(o,500)}else this._connectivityState="online";return}if(C.type==="event"){let L=C.event;if(c&&c.status!=="live"&&c.status!=="initializing")return;if(c&&!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(c&&!S7(L.message,c.scope)){m()||(zi.setReceivedToken(c.pull,C.cursor),zi.commitContiguousToken(c.pull,C.cursor),yield this.ledger.saveLink(c));return}let j=c?this.getOrCreateRuntime(o):void 0,V=j?j.nextDeliveryOrdinal++:-1;j&&j.inflight.set(V,{ordinal:V,token:C.cursor,committed:!1});try{let ee=this.extractDataStream(L);if(!ee&&oh(L)&&L.message.descriptor.dataCid){let x=yield be.getCid(L.message),P=yield kx({did:n,dwnUrl:a,delegateDid:i,protocol:s,messageCids:[x],agent:this.agent,permissionsApi:this._permissionsApi});P.length>0&&P[0].dataStream&&(ee=P[0].dataStream)}if(yield this.agent.dwn.processRawMessage(n,L.message,{dataStream:ee}),m())return;let A=this._closureContexts.get(n);if(A&&s7(A,L.message),c?.scope.kind==="protocol"){let x=this.agent.dwn.node.storage.messageStore,P=this._closureContexts.get(n);P||(P=wx(n,void 0,{isDelegateSession:!!i}),this._closureContexts.set(n,P));let b=yield dR(L.message,x,c.scope,P);if(m())return;if(!b.complete){let S=b.failure.code,I=b.failure.detail;console.warn(`SyncEngineLevel: Closure incomplete for ${n} -> ${a}: ${S} \u2014 ${I}`);let M=yield be.getCid(L.message);this.recordDeadLetter({messageCid:M,tenantDid:n,remoteEndpoint:a,protocol:s,category:"closure",errorCode:S,errorDetail:I}),m()||(yield this.transitionToRepairing(o,c));return}}let O=yield be.getCid(L.message);if(this._recentlyPulledCids.set(`${O}|${a}`,Date.now()+t.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),this.clearFailedMessage(O,a).catch(()=>{}),c&&j&&c.status==="live"&&!m()){let x=j.inflight.get(V);x&&(x.committed=!0),zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o)>0&&(yield this.ledger.saveLink(c),c.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:c.tenantDid,remoteEndpoint:c.remoteEndpoint,protocol:c.protocol,position:c.pull.contiguousAppliedToken.position,messageCid:c.pull.contiguousAppliedToken.messageCid})),j.inflight.size>sR&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${n} -> ${a}, transitioning to repairing`),yield this.transitionToRepairing(o,c))}}catch(ee){console.error(`SyncEngineLevel: Error processing live-pull event for ${n}`,ee);try{let A=yield be.getCid(L.message);this.recordDeadLetter({messageCid:A,tenantDid:n,remoteEndpoint:a,protocol:s,category:"pull-processing",errorDetail:(F=ee.message)!==null&&F!==void 0?F:String(ee)})}catch{}c&&!m()&&(yield this.transitionToRepairing(o,c))}}}}),_={store:!1,author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:u,cursor:l,permissionGrantId:f}},{message:w}=yield this.agent.dwn.processRequest(_);if(!w)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${a}`);let E=C=>He(this,void 0,void 0,function*(){var F;let L=(F=C??c?.pull.contiguousAppliedToken)!==null&&F!==void 0?F:l;L&&(!L.streamId||!L.messageCid||!L.epoch||!L.position)&&(L=void 0);let j=Object.assign(Object.assign({},_),{messageParams:Object.assign(Object.assign({},_.messageParams),{cursor:L})}),{message:V}=yield this.agent.dwn.processRequest(j);if(!V)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${a}`);return V}),k=new URL(a);k.protocol=k.protocol==="http:"?"ws:":"wss:";let D=k.toString(),R=yield this.agent.rpc.sendDwnRequest({dwnUrl:D,targetDid:n,message:w,subscription:{handler:g,resubscribeFactory:E}});if(R.status.code===410){let C=new Error(`SyncEngineLevel: ProgressGap for ${n} -> ${a}: ${R.status.detail}`);throw C.isProgressGap=!0,C.gapInfo=R.error,C}if(R.status.code!==200||!R.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${n} -> ${a}: ${R.status.code} ${R.status.detail}`);this._liveSubscriptions.push({linkKey:o,did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield R.subscription.close()})});let U=this._activeLinks.get(o);if(U){let C=U.connectivity;U.connectivity="online",C!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:C,to:"online"})}})}openLocalPushSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=s?[{protocol:s}]:[],c;i&&(c=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let l=this._engineGeneration,d=this._activeLinks.get(e.linkKey),u=()=>this._engineGeneration!==l||!this._activeLinks.has(e.linkKey)||d!==void 0&&this._activeLinks.get(e.linkKey)!==d,f=m=>He(this,void 0,void 0,function*(){if(u()||m.type!=="event")return;let g=e.linkKey,_=this._activeLinks.get(g);if(_&&!S7(m.event.message,_.scope))return;let w=g,E=yield be.getCid(m.event.message);if(E===void 0||u()||this.isRecentlyPulled(E,a))return;let k=this.getOrCreatePushRuntime(w,{did:n,dwnUrl:a,delegateDid:i,protocol:s});k.entries.push({cid:E}),!k.flushing&&!k.timer&&this.flushPendingPushesForLink(w)}),h=(yield this.agent.dwn.processRequest({author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:o,permissionGrantId:c},subscriptionHandler:f})).reply;if(h.status.code!==200||!h.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${n}: ${h.status.code} ${h.status.detail}`);this._localSubscriptions.push({linkKey:(r=e.linkKey)!==null&&r!==void 0?r:xv(n,a,s),did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield h.subscription.close()})})})}flushPendingPushes(){return He(this,void 0,void 0,function*(){yield Promise.all([...this._pushRuntimes.keys()].map(e=>He(this,void 0,void 0,function*(){yield this.flushPendingPushesForLink(e)})))})}flushPendingPushesForLink(e){return He(this,void 0,void 0,function*(){var r,n;if(!this._activeLinks.has(e))return;let i=this._pushRuntimes.get(e);if(!i)return;let a=this._activeLinks.get(e),s=()=>!this._activeLinks.has(e)||a!==void 0&&this._activeLinks.get(e)!==a,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f}=i;if(i.entries=[],u.length===0){!i.timer&&!i.flushing&&f===0&&this._pushRuntimes.delete(e);return}let p=u.map(h=>h.cid);i.flushing=!0;try{let h=yield yR({did:o,dwnUrl:c,delegateDid:l,protocol:d,messageCids:p,agent:this.agent,permissionsApi:this._permissionsApi});if(s())return;for(let m of h.succeeded)this.clearFailedMessage(m,c).catch(()=>{});for(let m of h.permanentlyFailed)yield this.recordDeadLetter({messageCid:m.cid,tenantDid:o,remoteEndpoint:c,protocol:d,category:"push-permanent",errorCode:String((r=m.statusCode)!==null&&r!==void 0?r:""),errorDetail:(n=m.detail)!==null&&n!==void 0?n:"permanent push failure"});if(h.failed.length>0){if(s())return;let m=new Set(h.failed),g=u.filter(_=>m.has(_.cid));this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:g,retryCount:f+1})}else i.retryCount=0,!i.timer&&i.entries.length===0&&this._pushRuntimes.delete(e)}catch(h){if(s())return;console.error(`SyncEngineLevel: Push batch failed for ${o} -> ${c}`,h),this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f+1})}finally{i.flushing=!1;let h=this._pushRuntimes.get(e);h&&h.entries.length>0&&!h.timer&&(h.timer=setTimeout(()=>{h.timer=void 0,this.flushPendingPushesForLink(e)},$he))}})}requeueOrReconcile(e,r){var n;let i=t.PUSH_RETRY_BACKOFF_MS.length,a=this.getOrCreatePushRuntime(e,r);if(r.retryCount>=i){for(let c of r.entries)this.recordDeadLetter({messageCid:c.cid,tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,category:"push-exhausted",errorDetail:`push retries exhausted after ${i} attempts`});a.timer&&clearTimeout(a.timer),this._pushRuntimes.delete(e);let o=this._activeLinks.get(e);o&&!o.needsReconcile&&(o.needsReconcile=!0,this.ledger.saveLink(o).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}a.entries.push(...r.entries),a.retryCount=r.retryCount;let s=(n=t.PUSH_RETRY_BACKOFF_MS[r.retryCount])!==null&&n!==void 0?n:2e3;a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{a.timer=void 0,this.flushPendingPushesForLink(e)},s)}createLinkReconciler(e){return new Ex({getLocalRoot:(r,n,i)=>He(this,void 0,void 0,function*(){return this.getLocalRoot(r,n,i)}),getRemoteRoot:(r,n,i,a)=>He(this,void 0,void 0,function*(){return this.getRemoteRoot(r,n,i,a)}),diffWithRemote:r=>He(this,void 0,void 0,function*(){return this.diffWithRemote(r)}),pullMessages:r=>He(this,void 0,void 0,function*(){return this.pullMessages(r)}),pushMessages:r=>He(this,void 0,void 0,function*(){return this.pushMessages(r)}),shouldContinue:e})}scheduleReconcile(e,r=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this._activeLinks.has(e)&&this.reconcileLink(e).catch(()=>{})},r);this._reconcileTimers.set(e,i)}reconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._reconcileInFlight.get(e);if(r)return r;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n})}doReconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r||r.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=()=>this._activeLinks.get(e)!==r,{tenantDid:a,remoteEndpoint:s,delegateDid:o,protocol:c}=r;try{let l=yield this.createLinkReconciler(()=>this._engineGeneration===n&&!i()).reconcile({did:a,dwnUrl:s,delegateDid:o,protocol:c},{verifyConvergence:!0});if(l.aborted||i())return;l.converged?(yield this.ledger.clearNeedsReconcile(r),this.clearDeadLettersForLink(a,s,c),this.emitEvent({type:"reconcile:completed",tenantDid:a,remoteEndpoint:s,protocol:c})):i()||this.scheduleReconcile(e,5e3)}catch(l){if(i())return;console.error(`SyncEngineLevel: Reconciliation failed for ${a} -> ${s}`,l),this.scheduleReconcile(e,5e3)}})}getOrCreatePushRuntime(e,r){let n=this._pushRuntimes.get(e);return n||(n=Object.assign(Object.assign({},r),{entries:[],retryCount:0}),this._pushRuntimes.set(e,n)),n}buildLinkKey(e,r,n){return n?P7(e,r,n):xv(e,r)}getCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{let n=yield r.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}yield this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}deleteLegacyCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{yield r.del(e)}catch{}})}extractDataStream(e){if(!oh(e))return;let r=e.message.encodedData;if(r){delete e.message.encodedData;let n=ke.base64UrlToBytes(r);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}getDefaultHashHex(e){return He(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield zg(),i=new Map;for(let a=0;a<=Che;a++)i.set(a,Pd(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 He(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let l=n===void 0?yield a.getRoot(e):yield a.getProtocolRoot(e,n);return Pd(l)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return He(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:Se.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:""})}diffWithRemote(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let c=yield this.collectLocalSubtreeHashes(r,a,E7),l=yield this.getSyncPermissionGrantId(r,i,a),d=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Se.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:c,depth:E7,permissionGrantId:l}}),u=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:d.message});if(u.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${u.status.code}: ${u.status.detail}`);let f=l,p=[];for(let h of(s=u.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,h,i,a,f);p.push(...m)}return{onlyRemote:(o=u.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:p}})}collectLocalSubtreeHashes(e,r,n){return He(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(c,l)=>He(this,void 0,void 0,function*(){let d;if(s){let u=t.parseBitPrefix(c),f=r===void 0?yield s.getSubtreeHash(e,u):yield s.getProtocolSubtreeHash(e,r,u);d=Pd(f)}else d=yield this.getLocalSubtreeHash(e,c,void 0,r);if(d!==a){if(l>=n){i[c]=d;return}yield Promise.all([o(c+"0",l+1),o(c+"1",l+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r),u=i===void 0?yield o.getSubtreeHash(e,d):yield o.getProtocolSubtreeHash(e,i,d);return Pd(u)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getLocalLeaves(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r);return i===void 0?yield o.getLeaves(e,d):yield o.getProtocolLeaves(e,i,d)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}pullMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){let c=yield _7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi});for(let l of c)yield this.recordDeadLetter({messageCid:l,tenantDid:r,remoteEndpoint:n,protocol:a,category:"pull-processing",errorDetail:"pull processing failed after retry passes exhausted"})})}evictExpiredEchoEntries(){let e=Date.now();for(let[r,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(r);if(this._recentlyPulledCids.size>t.ECHO_SUPPRESS_MAX_ENTRIES){let r=this._recentlyPulledCids.size-t.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=r)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,r){let n=`${e}|${r}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}pushMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return yR({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Am(e)}clearDeadLettersForLink(e,r,n){return He(this,void 0,void 0,function*(){var i,a,s,o;let c=[];try{try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;let[f,p]=o,h=JSON.parse(p);h.tenantDid===e&&h.remoteEndpoint===r&&h.protocol===n&&c.push({type:"del",key:f})}}catch(f){a={error:f}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(a)throw a.error}}c.length>0&&(yield this._deadLetters.batch(c))}catch(f){if(f.code!=="LEVEL_DATABASE_NOT_OPEN")throw f}})}static deadLetterKey(e,r){return r?`${e}|${r}`:e}recordDeadLetter(e){return He(this,void 0,void 0,function*(){let r=Object.assign(Object.assign({},e),{failedAt:new Date().toISOString()}),n=t.deadLetterKey(e.messageCid,e.remoteEndpoint);try{yield this._deadLetters.put(n,JSON.stringify(r))}catch(i){if(i.code!=="LEVEL_DATABASE_NOT_OPEN")throw i}})}getFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[,d]=a,u=JSON.parse(d);(!e||u.tenantDid===e)&&s.push(u)}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}return s.sort((d,u)=>u.failedAt.localeCompare(d.failedAt)),s})}clearFailedMessage(e,r){return He(this,void 0,void 0,function*(){var n,i,a,s;if(r){let f=t.deadLetterKey(e,r);try{return yield this._deadLetters.get(f),yield this._deadLetters.del(f),!0}catch(p){if(p.code==="LEVEL_NOT_FOUND")return!1;throw p}}let o=!1,c=[];try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),n=u.done,!n;l=!0){s=u.value,l=!1;let[f,p]=s;JSON.parse(p).messageCid===e&&(c.push({type:"del",key:f}),o=!0)}}catch(f){i={error:f}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(i)throw i.error}}return c.length>0&&(yield this._deadLetters.batch(c)),o})}clearAllFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;if(!e){yield this._deadLetters.clear();return}let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[d,u]=a;JSON.parse(u).tenantDid===e&&s.push({type:"del",key:d})}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}s.length>0&&(yield this._deadLetters.batch(s))})}getSyncHealth(){return He(this,void 0,void 0,function*(){var e,r,n,i;let a=0;try{for(var s=!0,o=Rm(this._deadLetters.iterator()),c;c=yield o.next(),e=c.done,!e;s=!0){i=c.value,s=!1;let u=i;a++}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}let l=0,d=yield this.ledger.getAllLinks();for(let u of d)(u.status==="repairing"||u.status==="degraded_poll")&&l++;return{connectivity:this.connectivityState,failedMessageCount:a,degradedLinkCount:l}})}getSyncTargets(){return He(this,void 0,void 0,function*(){var e,r,n,i;if(this._syncTargetsCache&&Date.now()-this._syncTargetsCache.timestamp<t.SYNC_TARGETS_CACHE_TTL_MS)return this._syncTargetsCache.targets;let a=this._syncTargetsCacheGeneration,s=[],o=!1,c=!1;try{for(var l=!0,d=Rm(this._db.sublevel("registeredIdentities").iterator()),u;u=yield d.next(),e=u.done,!e;l=!0){i=u.value,l=!1;let[p,h]=i;o=!0;let m;try{m=JSON.parse(h)}catch(E){console.warn(`SyncEngineLevel: Corrupt sync options for ${p}, skipping identity:`,E);continue}let{protocols:g,delegateDid:_}=m,w=yield this.agent.dwn.getDwnEndpointUrlsForTarget(p);if(w.length===0){c=!0;continue}for(let E of w)if(g==="all")s.push({did:p,delegateDid:_,dwnUrl:E});else for(let k of g)s.push({did:p,delegateDid:_,dwnUrl:E,protocol:k})}}catch(p){r={error:p}}finally{try{!l&&!e&&(n=d.return)&&(yield n.call(d))}finally{if(r)throw r.error}}let f=o&&!c;return s.length>0&&f&&this._syncTargetsCacheGeneration===a&&(this._syncTargetsCache={targets:s,timestamp:Date.now()}),s})}getSyncPermissionGrantId(e,r,n){return He(this,void 0,void 0,function*(){return r?(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0})}};oa.ECHO_SUPPRESS_TTL_MS=6e4;oa.ECHO_SUPPRESS_MAX_ENTRIES=1e4;oa.SYNC_TARGETS_CACHE_TTL_MS=3e4;oa.MAX_CONSECUTIVE_FAILURES=5;oa.MAX_BACKOFF_MULTIPLIER=4;oa.MAX_REPAIR_ATTEMPTS=3;oa.REPAIR_BACKOFF_MS=[1e3,3e3,1e4];oa.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];y();Nn();Ho();jt();import{Level as rVe}from"level";y();y();y();jt();nn();y();y();var T7=wn(xx(),1);jt();var Cm=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Tx=class{constructor({ttl:e="15m"}={}){this.cache=new Gu.default({ttl:(0,T7.default)(e)})}get(e){return Cm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Cm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Cm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Cm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Cm(this,void 0,void 0,function*(){})}close(){return Cm(this,void 0,void 0,function*(){})}};y();nn();Nn();y();var $m=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Om;(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"})(Om||(Om={}));var Bm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),Dx=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),D7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function ch(t){try{return JSON.parse(t)}catch{return null}}var gR=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ohe=3,Bhe=500,jhe=1e4,Mhe=3e4,I7=new Set([408,429,500,502,503,504]);function Nhe(t,e){return t instanceof TypeError?!0:e?I7.has(e.status):!1}function Uhe(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=Math.floor(n/2);return i+crypto.getRandomValues(new Uint32Array(1))[0]%(i||1)}function Khe(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 Ix=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new Tx,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:Ohe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:Bhe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:jhe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return gR(this,void 0,void 0,function*(){var r,n,i;let a=vi.randomUuid(),s=Bm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},c={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let p=e.data;if(p instanceof ReadableStream)if(t.isBunRuntime()){let h=yield Zi.toBytes(p);p=new Blob([h],{type:"application/octet-stream"})}else c.duplex="half";c.body=p}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let p=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new $m(p)}let d,u=l.headers.has("dwn-response");if(u){let p=ch(l.headers.get("dwn-response"));if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=p}else{let p=yield l.text(),h=ch(p);if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=h}if(d.error){let{code:p,message:h}=d.error;if(p===Om.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new $m(m)}throw new Error(`(${p}) - ${h}`)}let{reply:f}=d.result;if(u){let p=new Uint8Array(yield l.arrayBuffer()),h=Zi.fromBytes(p);f.record?f.record.data=h:f.entry&&(f.entry.data=h)}return f})}getServerInfo(e){return gR(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 $m(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 gR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Mhe),p=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),h=yield fetch(e,p);if(!I7.has(h.status)||c===n)return h;o=h}catch(f){if(!Nhe(f)||c===n)throw f;s=f}let l=o?Khe(o):void 0,d=Uhe(c,i,a),u=l===void 0?d:Math.max(l,d);yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};y();nn();var _v=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function wR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var A7=3e3,Lhe=3e4,qhe=1e3,zhe=3e4,Fhe=1/0,Ghe=3e4,Whe=1e4,Ax=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._awaitingPong=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return _v(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=A7,responseTimeout:s=Lhe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new t(o,s,r,n);return c.wireSocket(o),c.startHeartbeat(),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.stopHeartbeat(),this.socket.close()}request(e){return _v(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=vi.randomUuid());let a=s=>{let o=ch(wR(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 _v(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=ch(wR(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};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:()=>_v(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=vi.randomUuid(),n=Dx(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=()=>{l(),n(a)},o=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(c),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=ch(wR(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.stopHeartbeat(),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:Om.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}startHeartbeat(){var e,r;this.stopHeartbeat();let n=(e=this.options.heartbeatInterval)!==null&&e!==void 0?e:Ghe;if(n<=0)return;let i=(r=this.options.heartbeatTimeout)!==null&&r!==void 0?r:Whe;this._heartbeatInterval=setInterval(()=>{if(!this._isConnected||this._awaitingPong)return;this._awaitingPong=!0;let a=`hb-${Date.now()}`,s={jsonrpc:"2.0",id:a,method:"rpc.ping"};this.messageHandlers.set(a,()=>{this._awaitingPong=!1,this.messageHandlers.delete(a),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0)});try{this.send(s)}catch{this.messageHandlers.delete(a),this._awaitingPong=!1;return}this._heartbeatTimeout=setTimeout(()=>{if(this._heartbeatTimeout=void 0,this.messageHandlers.delete(a),this._awaitingPong=!1,!this.closedByUser&&this._isConnected){console.warn("JsonRpcSocket: heartbeat timeout \u2014 closing dead connection"),this._isConnected=!1;try{this.socket.close()}catch{}}},i)},n)}stopHeartbeat(){this._heartbeatInterval&&(clearInterval(this._heartbeatInterval),this._heartbeatInterval=void 0),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0),this._awaitingPong=!1}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:qhe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:zhe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Fhe,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:A7,l=0,d=()=>_v(this,void 0,void 0,function*(){var u,f,p,h;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let m=Math.min(a*Math.pow(2,l-1),s),g=Math.floor(m/2),_=g+crypto.getRandomValues(new Uint32Array(1))[0]%(g||1);if(yield new Promise(w=>setTimeout(w,_)),this.closedByUser){this.reconnecting=!1;return}try{let w=yield t.createWebSocket(this.url,c);this.socket=w,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(w),this.startHeartbeat(),(h=(p=this.options).onreconnected)===null||h===void 0||h.call(p)}catch{yield d()}});d()}};y();y();y();nn();y();nn();var jm=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ev=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return jm(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return jm(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield Ax.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 jm(this,void 0,void 0,function*(){let i=vi.randomUuid(),a=Bm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:c,result:l}=o;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return jm(this,void 0,void 0,function*(){let s=vi.randomUuid(),o=vi.randomUuid(),c=Dx(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,g=>{let{result:_,error:w}=g;if(w){let k=d.get(o);k&&k.subscription.close(),d.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let k=d.get(o);k&&(k.lastCursor=E.cursor),l.send(D7(o,E.cursor))}}),{error:p,result:h}=u;if(p)throw new Error(`could not subscribe via jsonrpc socket: ${p.message}`);let{reply:m}=h;if(m.subscription&&f){let g=()=>jm(this,void 0,void 0,function*(){d.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return jm(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{}})}};Ev.connections=new Map;var Sv=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},R7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(R7||(R7={}));var Mm=class{constructor(e=[]){this.transportClients=new Map,e=[new vR,new bR,...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 Sv(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 Sv(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)})}},vR=class extends Ix{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){let r=vi.randomUuid(),n=Bm(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:c}=a.error;throw new Error(`JSON RPC (${o}) - ${c}`)}}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})}},bR=class extends Ev{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Ho();jt();nn();Nn();y();jt();Ho();var Rx=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:Pv.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:Pv.Resolve});return n}};y();y();jt();var kv=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=Jo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Jo(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([Me.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 Bo.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Bo.consumeToBytes({readableStream:await this.stream()})},async json(){return await Bo.consumeToJson({readableStream:await this.stream()})},async text(){return await Bo.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Bo.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
+ `);Ho();jt();y();y();nn();y();jt();nn();y();jt();nn();y();nn();nn();Nn();y();jt();nn();y();Ho();y();jt();y();y();var k7=wn(xx(),1);Nn();import{Level as Rhe}from"level";y();var She=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function khe(t){let e=[],r=[];for(let n of t)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?r.push(n.messageCid):e.push(n):r.push(n.messageCid);return{prefetched:e,needsFetchCids:r}}var Ex=class{constructor(e){this._deps=e}reconcile(e,r){return She(this,void 0,void 0,function*(){var n;let{did:i,dwnUrl:a,delegateDid:s,protocol:o}=e,c=r?.direction,l=(n=r?.verifyConvergence)!==null&&n!==void 0?n:!1,d=this._deps.shouldContinue,u=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=yield this._deps.getRemoteRoot(i,a,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let p=!1,h=!1,m;if(u!==f){let w=yield this._deps.diffWithRemote(e);if(d&&!d())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:u,remoteRoot:f};if((!c||c==="pull")&&w.onlyRemote.length>0){let{prefetched:E,needsFetchCids:k}=khe(w.onlyRemote);if(yield this._deps.pullMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:k,prefetched:E}),d&&!d())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:u,remoteRoot:f};p=!0}if((!c||c==="push")&&w.onlyLocal.length>0){if(m=yield this._deps.pushMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:w.onlyLocal}),d&&!d())return{aborted:!0,changed:!0,didPull:p,didPush:!0,localRoot:u,remoteRoot:f,pushResult:m};h=!0}}if(!l)return{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let g=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let _=yield this._deps.getRemoteRoot(i,a,s,o);return d&&!d()?{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m}:{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,postLocalRoot:g,postRemoteRoot:_,converged:g===_,pushResult:m}})}};y();Nn();function b7(t){let e=t.descriptor;return e.interface!==Le.Records||e.method!==Ue.Write?!1:e.dateCreated===e.messageTimestamp}function Am(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let u=0;u<t.length;u++){let f=t[u];r.set(u,f);let p=f.message.descriptor;if(p.interface===Le.Protocols&&p.method===Ue.Configure){let h=(e=p.definition)===null||e===void 0?void 0:e.protocol;h&&n.set(h,u)}if(p.interface===Le.Records&&p.method===Ue.Write){let h=f.message.recordId;b7(f.message)&&h&&i.set(h,u),p.protocol===Et.uri&&p.protocolPath===Et.grantPath&&h&&a.set(h,u)}}let s=new Map,o=new Array(t.length).fill(0),c=(u,f)=>{if(u===f)return;s.has(u)||s.set(u,new Set);let p=s.get(u);p.has(f)||(p.add(f),o[f]++)};for(let u=0;u<t.length;u++){let f=t[u].message.descriptor;if(f.interface===Le.Records){let h=f.protocol;h&&n.has(h)&&c(n.get(h),u)}if(f.interface===Le.Records&&f.parentId){let h=f.parentId;i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Write){let h=t[u].message.recordId;h&&!b7(t[u].message)&&i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Delete){let h=f.recordId;h&&i.has(h)&&c(i.get(h),u)}let p=f.permissionGrantId;p&&a.has(p)&&c(a.get(p),u)}let l=[];for(let u=0;u<t.length;u++)o[u]===0&&l.push(u);let d=[];for(;l.length>0;){let u=l.shift();d.push(r.get(u));let f=s.get(u);if(f)for(let p of f)o[p]--,o[p]===0&&l.push(p)}if(d.length<t.length){let u=new Set(d);for(let f=0;f<t.length;f++){let p=r.get(f);u.has(p)||d.push(p)}}return d}y();var Sx="^";function P7(t,e,r){return`${t}${Sx}${e}${Sx}${r}`}function xv(t,e,r){let n=`${t}${Sx}${e}`;return r?`${n}${Sx}${r}`:n}y();Nn();var ah=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},The=1048576;function x7(t,e){var r,n;return t.status.code===202||t.status.code===204||t.status.code===409||t.status.code===404&&(e?.descriptor.interface===Le.Records&&e?.descriptor.method===Ue.Delete||((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.interface)===Le.Records&&((n=t.entry)===null||n===void 0?void 0:n.message.descriptor.method)===Ue.Delete)}function Dhe(t){return t.status.code===400||t.status.code===401||t.status.code===403}function mR(t){return ah(this,void 0,void 0,function*(){try{return yield be.getCid(t)}catch{return"unknown"}})}function _7(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:c}){let l=[];if(s)for(let g of s){if(!g.message)continue;let _={message:g.message};if(g.encodedData){let w=ke.base64UrlToBytes(g.encodedData);_.bufferedData=w,_.dataStream=new ReadableStream({start(E){E.enqueue(w),E.close()}})}l.push(_)}let d=a.length>0?yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:c}):[],u=[...l,...d],f=Am(u);yield Ihe(f);let p=3,h=f;for(let g=0;g<=p&&h.length>0;g++){let _=[];for(let w of h){let E=w.bufferedData?new ReadableStream({start(D){D.enqueue(w.bufferedData),D.close()}}):w.dataStream,k=yield o.dwn.processRawMessage(e,w.message,{dataStream:E});x7(k)||_.push(w)}if(_.length>0){let w=[],E=[];for(let k of _)if(k.bufferedData||!k.dataStream)E.push(k);else{let D=yield mR(k.message);w.push(D)}if(w.length>0){let k=yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:w,agent:o,permissionsApi:c});E.push(...k)}h=Am(E)}else h=[]}let m=[];for(let g of h){let _=yield mR(g.message);m.push(_)}return m})}function Ihe(t){return ah(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:c,value:l}=yield a.read();if(c)break;if(n+=l.byteLength,n>The){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let c of r)s.set(c,o),o+=c.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(c){c.enqueue(s),c.close()}})}})}function kx(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let c=[],l;n&&(l=(yield o.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id);let d=4,u=0;for(;u<a.length;){let f=a.slice(u,u+d);u+=d;let p=yield Promise.all(f.map(h=>ah(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Se.MessagesRead,granteeDid:n,messageParams:{messageCid:h,permissionGrantId:l}}),w;try{w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(w.status.code!==200||!(!((g=w.entry)===null||g===void 0)&&g.message))return;let E=w.entry,k;return oh(E)&&E.data&&(k=E.data),{message:E.message,dataStream:k}})));for(let h of p)h&&c.push(h)}return c})}function yR(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var c,l,d;let u=[],f=[],p=[],h=[];for(let g of a){let _=yield Ahe({author:e,messageCid:g,delegateDid:n,protocol:i,agent:s,permissionsApi:o});_?h.push(_):f.push(g)}let m=Am(h);for(let g of m){let _=yield mR(g.message);try{let w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:g.dataStream,message:g.message});x7(w,g.message)?u.push(_):Dhe(w)?(w.status.code===400&&(!((c=w.status.detail)===null||c===void 0)&&c.includes("record limit"))?console.debug(`SyncEngineLevel: singleton already exists on remote, skipping push for ${_}`):console.warn(`SyncEngineLevel: push permanently failed for ${_}: ${w.status.code} ${w.status.detail}`),p.push({cid:_,statusCode:w.status.code,detail:(l=w.status.detail)!==null&&l!==void 0?l:""})):(console.error(`SyncEngineLevel: push failed for ${_}: ${w.status.code} ${w.status.detail}`),f.push(_))}catch(w){console.error(`SyncEngineLevel: push error for ${_}: ${(d=w.message)!==null&&d!==void 0?d:w}`),f.push(_)}}return{succeeded:u,failed:f,permanentlyFailed:p}})}function Ahe(t){return ah(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:Se.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let{reply:c}=yield a.dwn.processRequest({author:e,target:e,messageType:Se.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(c.status.code!==200||!c.entry)return;let l=c.entry,d={message:l.message};return oh(l)&&l.data&&(d.dataStream=l.data),d})}var He=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Rm=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,c){s=t[a](s),i(o,c,s.done,s.value)})}}function i(a,s,o,c){Promise.resolve(c).then(function(l){a({value:l,done:o})},s)}},Che=16,E7=8,$he=100;function S7(t,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let r=t.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=r.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=t.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var oa=class t{static validateSyncIdentityOptions(e){if(!e||!("protocols"in e))throw new Error("SyncEngineLevel: options.protocols is required \u2014 pass 'all' for a full replica or a non-empty protocol list.");if(e.protocols!=="all"&&!Array.isArray(e.protocols))throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty string array.");if(Array.isArray(e.protocols)&&e.protocols.length===0)throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty array of protocol URIs. An empty array is ambiguous.")}constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1,this._activeLinks=new Map,this._linkRuntimes=new Map,this._syncMode="poll",this._engineGeneration=0,this._liveSubscriptions=[],this._localSubscriptions=[],this._connectivityState="unknown",this._eventListeners=new Set,this._pushRuntimes=new Map,this._recentlyPulledCids=new Map,this._closureContexts=new Map,this._syncTargetsCacheGeneration=0,this._consecutiveFailures=0,this._degradedPollTimers=new Map,this._repairAttempts=new Map,this._activeRepairs=new Map,this._repairRetryTimers=new Map,this._repairContext=new Map,this._reconcileTimers=new Map,this._reconcileInFlight=new Map,this._agent=e,this._permissionsApi=new Xn({agent:e}),this._db=n||new Rhe(r??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new zi(this._db)),this._ledger}get _deadLetters(){return this._db.sublevel("deadLetters")}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 Xn({agent:e}),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++}get hasActiveSubscriptions(){return this._liveSubscriptions.length>0||this._localSubscriptions.length>0}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,r=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(r=!0);return e?"online":r?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let r of this._eventListeners)try{r(e)}catch{}}clear(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0,yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),yield this._db.close()})}registerIdentity(e){return He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(n);let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);yield i.put(r,JSON.stringify(n)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,this._syncMode==="live"&&(yield this.addIdentityToLiveSync(r,n))})}unregisterIdentity(e){return He(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.`);this._syncMode==="live"&&(yield this.removeIdentityFromLiveSync(e)),yield r.del(e),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++})}getIdentityOptions(e){return He(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 He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(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)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.ledger.updateDelegateDid(r,n.delegateDid),this._syncMode==="live"&&this.hasActiveLinksForDid(r)&&(yield this.removeIdentityFromLiveSync(r),yield this.addIdentityToLiveSync(r,n))})}sync(e){return He(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 Map;for(let o of r){let c=n.get(o.dwnUrl);c||(c=[],n.set(o.dwnUrl,c)),c.push(o)}let i=0,a=0,s=yield Promise.allSettled([...n.entries()].map(o=>He(this,[o],void 0,function*([c,l]){for(let d of l){let{did:u,delegateDid:f,protocol:p}=d;try{yield this.createLinkReconciler().reconcile({did:u,dwnUrl:c,delegateDid:f,protocol:p},{direction:e})}catch(h){a++,console.error(`SyncEngineLevel: Error syncing ${u} with ${c}`,h);return}}i++})));for(let o of s)o.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):r.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}})}startSync(e){return He(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,k7.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 He(this,arguments,void 0,function*(e=2e3){this._engineGeneration++;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),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0})}startPollSync(e){return He(this,void 0,void 0,function*(){let r=this._engineGeneration,n=()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==r||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(s){console.error("SyncEngineLevel: Error during sync operation",s)}let i=Math.min(Math.pow(2,this._consecutiveFailures),t.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===r&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))});this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||(yield this.sync())})}startLiveSync(e){return He(this,void 0,void 0,function*(){this.startBrowserConnectivityListeners();try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();yield Promise.allSettled(r.map(i=>this.initializeLinkTarget(i)));let n=()=>He(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)})}getOrCreateRuntime(e){let r=this._linkRuntimes.get(e);return r||(r={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,r)),r}drainCommittedPull(e){let r=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!r||!n)return 0;let i=0;for(;;){let a=r.inflight.get(r.nextCommitOrdinal);if(!a?.committed)break;zi.commitContiguousToken(n.pull,a.token),zi.setReceivedToken(n.pull,a.token),r.inflight.delete(r.nextCommitOrdinal),r.nextCommitOrdinal++,i++}return i}transitionToRepairing(e,r,n){return He(this,void 0,void 0,function*(){let i=r.status,a=r.connectivity;r.connectivity="offline",yield this.ledger.setStatus(r,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let s=this._linkRuntimes.get(e);s&&(s.inflight.clear(),s.nextCommitOrdinal=s.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})})}scheduleRepairRetry(e){var r;let n=this._activeLinks.get(e);if(!n||n.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let i=(r=this._repairAttempts.get(e))!==null&&r!==void 0?r:1,a=t.REPAIR_BACKOFF_MS,s=a[Math.min(i-1,a.length-1)],o=this._engineGeneration,c=setTimeout(()=>He(this,void 0,void 0,function*(){if(this._repairRetryTimers.delete(e),this._engineGeneration!==o)return;let l=this._activeLinks.get(e);if(l?.status==="repairing")try{yield this.repairLink(e)}catch{l.status==="repairing"&&this.scheduleRepairRetry(e)}}),s);this._repairRetryTimers.set(e,c)}repairLink(e){let r=this._activeRepairs.get(e);if(r)return r;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}doRepairLink(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=this._activeLinks.get(e);if(!s)return;let o=this._engineGeneration,c=()=>this._activeLinks.get(e)!==s,{tenantDid:l,remoteEndpoint:d,delegateDid:u,protocol:f}=s;this.emitEvent({type:"repair:started",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:((r=this._repairAttempts.get(e))!==null&&r!==void 0?r:0)+1});let p=((n=this._repairAttempts.get(e))!==null&&n!==void 0?n:0)+1;if(this._repairAttempts.set(e,p),yield this.closeLinkSubscriptions(s),this._engineGeneration!==o||c())return;let h=this.getOrCreateRuntime(e);h.inflight.clear(),h.nextDeliveryOrdinal=0,h.nextCommitOrdinal=0;try{if((yield this.createLinkReconciler(()=>this._engineGeneration===o&&!c()).reconcile({did:l,dwnUrl:d,delegateDid:u,protocol:f})).aborted)return;let g=this._repairContext.get(e),_=(i=g?.resumeToken)!==null&&i!==void 0?i:s.pull.contiguousAppliedToken;if(zi.resetCheckpoint(s.pull,_),yield this.ledger.saveLink(s),this._engineGeneration!==o||c()||(s.needsReconcile=!0,yield this.ledger.saveLink(s),this._engineGeneration!==o||c()))return;let w={did:l,dwnUrl:d,delegateDid:u,protocol:f,linkKey:e};try{yield this.openLivePullSubscription(w)}catch(D){if(D.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${l} -> ${d}, resetting to start fresh`),zi.resetCheckpoint(s.pull),yield this.ledger.saveLink(s),this._engineGeneration!==o||c())return;yield this.openLivePullSubscription(w)}else throw D}if(this._engineGeneration!==o||c())return;try{yield this.openLocalPushSubscription(w)}catch(D){let R=this._liveSubscriptions.find(U=>U.linkKey===e);if(R){try{yield R.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(U=>U!==R)}throw D}if(this._engineGeneration!==o||c())return;this._repairContext.delete(e),this._repairAttempts.delete(e);let E=this._repairRetryTimers.get(e);E&&(clearTimeout(E),this._repairRetryTimers.delete(e));let k=s.connectivity;s.connectivity="online",yield this.ledger.setStatus(s,"live"),this.clearDeadLettersForLink(l,d,f),this.emitEvent({type:"repair:completed",tenantDid:l,remoteEndpoint:d,protocol:f}),k!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:k,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:"repairing",to:"live"})}catch(m){if(this._engineGeneration!==o||c())return;if(console.error(`SyncEngineLevel: Repair failed for ${l} -> ${d} (attempt ${p})`,m),this.emitEvent({type:"repair:failed",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:p,error:String((a=m.message)!==null&&a!==void 0?a:m)}),p>=t.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${l} -> ${d}, entering degraded_poll`),yield this.enterDegradedPoll(e);return}throw m}})}closeLinkSubscriptions(e){return He(this,void 0,void 0,function*(){let{tenantDid:r,remoteEndpoint:n}=e,i=this.buildLinkKey(r,n,e.scopeId),a=this._liveSubscriptions.find(o=>o.linkKey===i);if(a){try{yield a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(o=>o!==a)}let s=this._localSubscriptions.find(o=>o.linkKey===i);if(s){try{yield s.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(o=>o!==s)}})}enterDegradedPoll(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r)return;r.connectivity="offline";let n=r.status;yield this.ledger.setStatus(r,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,s=new Uint32Array(1),o;do crypto.getRandomValues(s),o=s[0]&16383;while(o>=a);let c=a+o,l=this._engineGeneration,d=setInterval(()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==l){clearInterval(d),this._degradedPollTimers.delete(e);return}let u=this._activeLinks.get(e);if(u?.status!=="degraded_poll"){clearInterval(d),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),yield this.ledger.setStatus(u,"repairing"),yield this.repairLink(e),u.status==="live"&&(clearInterval(d),this._degradedPollTimers.delete(e))}catch{this._activeLinks.get(e)===u&&(yield this.ledger.setStatus(u,"degraded_poll"))}}),c);this._degradedPollTimers.set(e,d)})}startBrowserConnectivityListeners(){if(this.stopBrowserConnectivityListeners(),typeof globalThis.addEventListener!="function")return;let e=this._engineGeneration;this._onOnline=()=>{this._engineGeneration===e&&(console.info("SyncEngineLevel: browser online \u2014 triggering immediate integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-online sync failed",r)}))},this._onOffline=()=>{if(this._engineGeneration===e){console.info("SyncEngineLevel: browser offline"),this._connectivityState="offline";for(let r of this._activeLinks.values()){let n=r.connectivity;n!=="offline"&&(r.connectivity="offline",this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"offline"}))}}},this._onVisibilityChange=()=>{this._engineGeneration===e&&(typeof document>"u"||document.visibilityState!=="visible"||(console.info("SyncEngineLevel: page became visible \u2014 triggering integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-visibility sync failed",r)})))},globalThis.addEventListener("online",this._onOnline),globalThis.addEventListener("offline",this._onOffline),typeof document<"u"&&document.addEventListener("visibilitychange",this._onVisibilityChange)}stopBrowserConnectivityListeners(){this._onOnline&&(globalThis.removeEventListener("online",this._onOnline),this._onOnline=void 0),this._onOffline&&(globalThis.removeEventListener("offline",this._onOffline),this._onOffline=void 0),this._onVisibilityChange&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0)}teardownLiveSync(){return He(this,void 0,void 0,function*(){this.stopBrowserConnectivityListeners(),this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.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=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()})}initializeLinkTarget(e){return He(this,void 0,void 0,function*(){var r;let n;try{let i=e.protocol?{kind:"protocol",protocol:e.protocol}:{kind:"full"};n=yield this.ledger.getOrCreateLink({tenantDid:e.did,remoteEndpoint:e.dwnUrl,scope:i,delegateDid:e.delegateDid,protocol:e.protocol});let a=this.buildLinkKey(e.did,e.dwnUrl,n.scopeId);if(!n.pull.contiguousAppliedToken){let o=xv(e.did,e.dwnUrl,e.protocol),c=yield this.getCursor(o);c&&(zi.resetCheckpoint(n.pull,c),yield this.ledger.saveLink(n),yield this.deleteLegacyCursor(o))}this._activeLinks.set(a,n);let s=Object.assign(Object.assign({},e),{linkKey:a});yield this.openLivePullSubscription(s);try{yield this.openLocalPushSubscription(s)}catch(o){let c=this._liveSubscriptions.find(l=>l.linkKey===a);if(c){try{yield c.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(l=>l!==c)}throw o}this.emitEvent({type:"link:status-change",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,from:"initializing",to:"live"}),yield this.ledger.setStatus(n,"live"),n.needsReconcile&&this.scheduleReconcile(a,1e3)}catch(i){let a=n?this.buildLinkKey(e.did,e.dwnUrl,n.scopeId):xv(e.did,e.dwnUrl,e.protocol);if(i.isProgressGap&&n){console.warn(`SyncEngineLevel: ProgressGap detected for ${e.did} -> ${e.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,reason:"ProgressGap"}),yield this.transitionToRepairing(a,n,{resumeToken:(r=i.gapInfo)===null||r===void 0?void 0:r.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${e.did} -> ${e.dwnUrl}`,i),this._activeLinks.delete(a),this._linkRuntimes.delete(a),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}})}isLinkKeyForDid(e,r){return e.startsWith(r+"^")||e.startsWith(r+"_")}hasActiveLinksForDid(e){for(let r of this._activeLinks.keys())if(this.isLinkKeyForDid(r,e))return!0;return!1}addIdentityToLiveSync(e,r){return He(this,void 0,void 0,function*(){let{protocols:n,delegateDid:i}=r,a=yield this.agent.dwn.getDwnEndpointUrlsForTarget(e);if(a.length===0)return;let s=[];for(let o of a)if(n==="all")s.push({did:e,delegateDid:i,dwnUrl:o});else for(let c of n)s.push({did:e,delegateDid:i,dwnUrl:o,protocol:c});yield Promise.allSettled(s.map(o=>this.initializeLinkTarget(o)))})}removeIdentityFromLiveSync(e){return He(this,void 0,void 0,function*(){for(let r of this._liveSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(r=>r.did!==e);for(let r of this._localSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(r=>r.did!==e);for(let[r,n]of this._pushRuntimes)n.did===e&&(n.timer&&clearTimeout(n.timer),this._pushRuntimes.delete(r));for(let[r,n]of this._degradedPollTimers)this.isLinkKeyForDid(r,e)&&(clearInterval(n),this._degradedPollTimers.delete(r));for(let r of this._repairAttempts.keys())this.isLinkKeyForDid(r,e)&&this._repairAttempts.delete(r);for(let r of this._activeRepairs.keys())this.isLinkKeyForDid(r,e)&&this._activeRepairs.delete(r);for(let r of this._repairContext.keys())this.isLinkKeyForDid(r,e)&&this._repairContext.delete(r);for(let[r,n]of this._repairRetryTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._repairRetryTimers.delete(r));for(let[r,n]of this._reconcileTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._reconcileTimers.delete(r));for(let r of this._reconcileInFlight.keys())this.isLinkKeyForDid(r,e)&&this._reconcileInFlight.delete(r);for(let r of this._activeLinks.keys())this.isLinkKeyForDid(r,e)&&(this._activeLinks.delete(r),this._linkRuntimes.delete(r));this._closureContexts.delete(e)})}openLivePullSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=e.linkKey,c=this._activeLinks.get(o),l=c?.pull.contiguousAppliedToken;l&&(!l.streamId||!l.messageCid||!l.epoch||!l.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${n} -> ${a}`),l=void 0,c&&(zi.resetCheckpoint(c.pull),yield this.ledger.saveLink(c)));let d=c?.scope.kind==="protocol"?(r=c.scope.protocolPathPrefixes)===null||r===void 0?void 0:r[0]:void 0,u=s?[Object.assign({protocol:s},d?{protocolPathPrefix:d}:{})]:[],f;i&&(f=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let p=this._engineGeneration,h=c,m=()=>this._engineGeneration!==p||!this._activeLinks.has(o)||h!==void 0&&this._activeLinks.get(o)!==h,g=C=>He(this,void 0,void 0,function*(){var F;if(!m()){if(C.type==="eose"){if(c){if(c.status!=="live"&&c.status!=="initializing")return;if(!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o),m())return;yield this.ledger.saveLink(c)}if(c){let L=c.connectivity;c.connectivity="online",L!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:L,to:"online"}),c.needsReconcile&&this.scheduleReconcile(o,500)}else this._connectivityState="online";return}if(C.type==="event"){let L=C.event;if(c&&c.status!=="live"&&c.status!=="initializing")return;if(c&&!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(c&&!S7(L.message,c.scope)){m()||(zi.setReceivedToken(c.pull,C.cursor),zi.commitContiguousToken(c.pull,C.cursor),yield this.ledger.saveLink(c));return}let j=c?this.getOrCreateRuntime(o):void 0,V=j?j.nextDeliveryOrdinal++:-1;j&&j.inflight.set(V,{ordinal:V,token:C.cursor,committed:!1});try{let ee=this.extractDataStream(L);if(!ee&&oh(L)&&L.message.descriptor.dataCid){let x=yield be.getCid(L.message),P=yield kx({did:n,dwnUrl:a,delegateDid:i,protocol:s,messageCids:[x],agent:this.agent,permissionsApi:this._permissionsApi});P.length>0&&P[0].dataStream&&(ee=P[0].dataStream)}if(yield this.agent.dwn.processRawMessage(n,L.message,{dataStream:ee}),m())return;let A=this._closureContexts.get(n);if(A&&s7(A,L.message),c?.scope.kind==="protocol"){let x=this.agent.dwn.node.storage.messageStore,P=this._closureContexts.get(n);P||(P=wx(n,void 0,{isDelegateSession:!!i}),this._closureContexts.set(n,P));let b=yield dR(L.message,x,c.scope,P);if(m())return;if(!b.complete){let S=b.failure.code,I=b.failure.detail;console.warn(`SyncEngineLevel: Closure incomplete for ${n} -> ${a}: ${S} \u2014 ${I}`);let M=yield be.getCid(L.message);this.recordDeadLetter({messageCid:M,tenantDid:n,remoteEndpoint:a,protocol:s,category:"closure",errorCode:S,errorDetail:I}),m()||(yield this.transitionToRepairing(o,c));return}}let O=yield be.getCid(L.message);if(this._recentlyPulledCids.set(`${O}|${a}`,Date.now()+t.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),this.clearFailedMessage(O,a).catch(()=>{}),c&&j&&c.status==="live"&&!m()){let x=j.inflight.get(V);x&&(x.committed=!0),zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o)>0&&(yield this.ledger.saveLink(c),c.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:c.tenantDid,remoteEndpoint:c.remoteEndpoint,protocol:c.protocol,position:c.pull.contiguousAppliedToken.position,messageCid:c.pull.contiguousAppliedToken.messageCid})),j.inflight.size>sR&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${n} -> ${a}, transitioning to repairing`),yield this.transitionToRepairing(o,c))}}catch(ee){console.error(`SyncEngineLevel: Error processing live-pull event for ${n}`,ee);try{let A=yield be.getCid(L.message);this.recordDeadLetter({messageCid:A,tenantDid:n,remoteEndpoint:a,protocol:s,category:"pull-processing",errorDetail:(F=ee.message)!==null&&F!==void 0?F:String(ee)})}catch{}c&&!m()&&(yield this.transitionToRepairing(o,c))}}}}),_={store:!1,author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:u,cursor:l,permissionGrantId:f}},{message:w}=yield this.agent.dwn.processRequest(_);if(!w)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${a}`);let E=C=>He(this,void 0,void 0,function*(){var F;let L=(F=C??c?.pull.contiguousAppliedToken)!==null&&F!==void 0?F:l;L&&(!L.streamId||!L.messageCid||!L.epoch||!L.position)&&(L=void 0);let j=Object.assign(Object.assign({},_),{messageParams:Object.assign(Object.assign({},_.messageParams),{cursor:L})}),{message:V}=yield this.agent.dwn.processRequest(j);if(!V)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${a}`);return V}),k=new URL(a);k.protocol=k.protocol==="http:"?"ws:":"wss:";let D=k.toString(),R=yield this.agent.rpc.sendDwnRequest({dwnUrl:D,targetDid:n,message:w,subscription:{handler:g,resubscribeFactory:E}});if(R.status.code===410){let C=new Error(`SyncEngineLevel: ProgressGap for ${n} -> ${a}: ${R.status.detail}`);throw C.isProgressGap=!0,C.gapInfo=R.error,C}if(R.status.code!==200||!R.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${n} -> ${a}: ${R.status.code} ${R.status.detail}`);this._liveSubscriptions.push({linkKey:o,did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield R.subscription.close()})});let U=this._activeLinks.get(o);if(U){let C=U.connectivity;U.connectivity="online",C!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:C,to:"online"})}})}openLocalPushSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=s?[{protocol:s}]:[],c;i&&(c=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let l=this._engineGeneration,d=this._activeLinks.get(e.linkKey),u=()=>this._engineGeneration!==l||!this._activeLinks.has(e.linkKey)||d!==void 0&&this._activeLinks.get(e.linkKey)!==d,f=m=>He(this,void 0,void 0,function*(){if(u()||m.type!=="event")return;let g=e.linkKey,_=this._activeLinks.get(g);if(_&&!S7(m.event.message,_.scope))return;let w=g,E=yield be.getCid(m.event.message);if(E===void 0||u()||this.isRecentlyPulled(E,a))return;let k=this.getOrCreatePushRuntime(w,{did:n,dwnUrl:a,delegateDid:i,protocol:s});k.entries.push({cid:E}),!k.flushing&&!k.timer&&this.flushPendingPushesForLink(w)}),h=(yield this.agent.dwn.processRequest({author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:o,permissionGrantId:c},subscriptionHandler:f})).reply;if(h.status.code!==200||!h.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${n}: ${h.status.code} ${h.status.detail}`);this._localSubscriptions.push({linkKey:(r=e.linkKey)!==null&&r!==void 0?r:xv(n,a,s),did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield h.subscription.close()})})})}flushPendingPushes(){return He(this,void 0,void 0,function*(){yield Promise.all([...this._pushRuntimes.keys()].map(e=>He(this,void 0,void 0,function*(){yield this.flushPendingPushesForLink(e)})))})}flushPendingPushesForLink(e){return He(this,void 0,void 0,function*(){var r,n;if(!this._activeLinks.has(e))return;let i=this._pushRuntimes.get(e);if(!i)return;let a=this._activeLinks.get(e),s=()=>!this._activeLinks.has(e)||a!==void 0&&this._activeLinks.get(e)!==a,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f}=i;if(i.entries=[],u.length===0){!i.timer&&!i.flushing&&f===0&&this._pushRuntimes.delete(e);return}let p=u.map(h=>h.cid);i.flushing=!0;try{let h=yield yR({did:o,dwnUrl:c,delegateDid:l,protocol:d,messageCids:p,agent:this.agent,permissionsApi:this._permissionsApi});if(s())return;for(let m of h.succeeded)this.clearFailedMessage(m,c).catch(()=>{});for(let m of h.permanentlyFailed)yield this.recordDeadLetter({messageCid:m.cid,tenantDid:o,remoteEndpoint:c,protocol:d,category:"push-permanent",errorCode:String((r=m.statusCode)!==null&&r!==void 0?r:""),errorDetail:(n=m.detail)!==null&&n!==void 0?n:"permanent push failure"});if(h.failed.length>0){if(s())return;let m=new Set(h.failed),g=u.filter(_=>m.has(_.cid));this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:g,retryCount:f+1})}else i.retryCount=0,!i.timer&&i.entries.length===0&&this._pushRuntimes.delete(e)}catch(h){if(s())return;console.error(`SyncEngineLevel: Push batch failed for ${o} -> ${c}`,h),this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f+1})}finally{i.flushing=!1;let h=this._pushRuntimes.get(e);h&&h.entries.length>0&&!h.timer&&(h.timer=setTimeout(()=>{h.timer=void 0,this.flushPendingPushesForLink(e)},$he))}})}requeueOrReconcile(e,r){var n;let i=t.PUSH_RETRY_BACKOFF_MS.length,a=this.getOrCreatePushRuntime(e,r);if(r.retryCount>=i){for(let c of r.entries)this.recordDeadLetter({messageCid:c.cid,tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,category:"push-exhausted",errorDetail:`push retries exhausted after ${i} attempts`});a.timer&&clearTimeout(a.timer),this._pushRuntimes.delete(e);let o=this._activeLinks.get(e);o&&!o.needsReconcile&&(o.needsReconcile=!0,this.ledger.saveLink(o).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}a.entries.push(...r.entries),a.retryCount=r.retryCount;let s=(n=t.PUSH_RETRY_BACKOFF_MS[r.retryCount])!==null&&n!==void 0?n:2e3;a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{a.timer=void 0,this.flushPendingPushesForLink(e)},s)}createLinkReconciler(e){return new Ex({getLocalRoot:(r,n,i)=>He(this,void 0,void 0,function*(){return this.getLocalRoot(r,n,i)}),getRemoteRoot:(r,n,i,a)=>He(this,void 0,void 0,function*(){return this.getRemoteRoot(r,n,i,a)}),diffWithRemote:r=>He(this,void 0,void 0,function*(){return this.diffWithRemote(r)}),pullMessages:r=>He(this,void 0,void 0,function*(){return this.pullMessages(r)}),pushMessages:r=>He(this,void 0,void 0,function*(){return this.pushMessages(r)}),shouldContinue:e})}scheduleReconcile(e,r=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this._activeLinks.has(e)&&this.reconcileLink(e).catch(()=>{})},r);this._reconcileTimers.set(e,i)}reconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._reconcileInFlight.get(e);if(r)return r;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n})}doReconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r||r.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=()=>this._activeLinks.get(e)!==r,{tenantDid:a,remoteEndpoint:s,delegateDid:o,protocol:c}=r;try{let l=yield this.createLinkReconciler(()=>this._engineGeneration===n&&!i()).reconcile({did:a,dwnUrl:s,delegateDid:o,protocol:c},{verifyConvergence:!0});if(l.aborted||i())return;l.converged?(yield this.ledger.clearNeedsReconcile(r),this.clearDeadLettersForLink(a,s,c),this.emitEvent({type:"reconcile:completed",tenantDid:a,remoteEndpoint:s,protocol:c})):i()||this.scheduleReconcile(e,5e3)}catch(l){if(i())return;console.error(`SyncEngineLevel: Reconciliation failed for ${a} -> ${s}`,l),this.scheduleReconcile(e,5e3)}})}getOrCreatePushRuntime(e,r){let n=this._pushRuntimes.get(e);return n||(n=Object.assign(Object.assign({},r),{entries:[],retryCount:0}),this._pushRuntimes.set(e,n)),n}buildLinkKey(e,r,n){return n?P7(e,r,n):xv(e,r)}getCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{let n=yield r.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}yield this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}deleteLegacyCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{yield r.del(e)}catch{}})}extractDataStream(e){if(!oh(e))return;let r=e.message.encodedData;if(r){delete e.message.encodedData;let n=ke.base64UrlToBytes(r);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}getDefaultHashHex(e){return He(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield zg(),i=new Map;for(let a=0;a<=Che;a++)i.set(a,Pd(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 He(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let l=n===void 0?yield a.getRoot(e):yield a.getProtocolRoot(e,n);return Pd(l)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return He(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:Se.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:""})}diffWithRemote(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let c=yield this.collectLocalSubtreeHashes(r,a,E7),l=yield this.getSyncPermissionGrantId(r,i,a),d=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Se.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:c,depth:E7,permissionGrantId:l}}),u=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:d.message});if(u.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${u.status.code}: ${u.status.detail}`);let f=l,p=[];for(let h of(s=u.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,h,i,a,f);p.push(...m)}return{onlyRemote:(o=u.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:p}})}collectLocalSubtreeHashes(e,r,n){return He(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(c,l)=>He(this,void 0,void 0,function*(){let d;if(s){let u=t.parseBitPrefix(c),f=r===void 0?yield s.getSubtreeHash(e,u):yield s.getProtocolSubtreeHash(e,r,u);d=Pd(f)}else d=yield this.getLocalSubtreeHash(e,c,void 0,r);if(d!==a){if(l>=n){i[c]=d;return}yield Promise.all([o(c+"0",l+1),o(c+"1",l+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r),u=i===void 0?yield o.getSubtreeHash(e,d):yield o.getProtocolSubtreeHash(e,i,d);return Pd(u)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getLocalLeaves(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r);return i===void 0?yield o.getLeaves(e,d):yield o.getProtocolLeaves(e,i,d)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}pullMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){let c=yield _7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi});for(let l of c)yield this.recordDeadLetter({messageCid:l,tenantDid:r,remoteEndpoint:n,protocol:a,category:"pull-processing",errorDetail:"pull processing failed after retry passes exhausted"})})}evictExpiredEchoEntries(){let e=Date.now();for(let[r,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(r);if(this._recentlyPulledCids.size>t.ECHO_SUPPRESS_MAX_ENTRIES){let r=this._recentlyPulledCids.size-t.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=r)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,r){let n=`${e}|${r}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}pushMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return yR({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Am(e)}clearDeadLettersForLink(e,r,n){return He(this,void 0,void 0,function*(){var i,a,s,o;let c=[];try{try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;let[f,p]=o,h=JSON.parse(p);h.tenantDid===e&&h.remoteEndpoint===r&&h.protocol===n&&c.push({type:"del",key:f})}}catch(f){a={error:f}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(a)throw a.error}}c.length>0&&(yield this._deadLetters.batch(c))}catch(f){if(f.code!=="LEVEL_DATABASE_NOT_OPEN")throw f}})}static deadLetterKey(e,r){return r?`${e}|${r}`:e}recordDeadLetter(e){return He(this,void 0,void 0,function*(){let r=Object.assign(Object.assign({},e),{failedAt:new Date().toISOString()}),n=t.deadLetterKey(e.messageCid,e.remoteEndpoint);try{yield this._deadLetters.put(n,JSON.stringify(r))}catch(i){if(i.code!=="LEVEL_DATABASE_NOT_OPEN")throw i}})}getFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[,d]=a,u=JSON.parse(d);(!e||u.tenantDid===e)&&s.push(u)}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}return s.sort((d,u)=>u.failedAt.localeCompare(d.failedAt)),s})}clearFailedMessage(e,r){return He(this,void 0,void 0,function*(){var n,i,a,s;if(r){let f=t.deadLetterKey(e,r);try{return yield this._deadLetters.get(f),yield this._deadLetters.del(f),!0}catch(p){if(p.code==="LEVEL_NOT_FOUND")return!1;throw p}}let o=!1,c=[];try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),n=u.done,!n;l=!0){s=u.value,l=!1;let[f,p]=s;JSON.parse(p).messageCid===e&&(c.push({type:"del",key:f}),o=!0)}}catch(f){i={error:f}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(i)throw i.error}}return c.length>0&&(yield this._deadLetters.batch(c)),o})}clearAllFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;if(!e){yield this._deadLetters.clear();return}let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[d,u]=a;JSON.parse(u).tenantDid===e&&s.push({type:"del",key:d})}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}s.length>0&&(yield this._deadLetters.batch(s))})}getSyncHealth(){return He(this,void 0,void 0,function*(){var e,r,n,i;let a=0;try{for(var s=!0,o=Rm(this._deadLetters.iterator()),c;c=yield o.next(),e=c.done,!e;s=!0){i=c.value,s=!1;let u=i;a++}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}let l=0,d=yield this.ledger.getAllLinks();for(let u of d)(u.status==="repairing"||u.status==="degraded_poll")&&l++;return{connectivity:this.connectivityState,failedMessageCount:a,degradedLinkCount:l}})}getSyncTargets(){return He(this,void 0,void 0,function*(){var e,r,n,i;if(this._syncTargetsCache&&Date.now()-this._syncTargetsCache.timestamp<t.SYNC_TARGETS_CACHE_TTL_MS)return this._syncTargetsCache.targets;let a=this._syncTargetsCacheGeneration,s=[],o=!1,c=!1;try{for(var l=!0,d=Rm(this._db.sublevel("registeredIdentities").iterator()),u;u=yield d.next(),e=u.done,!e;l=!0){i=u.value,l=!1;let[p,h]=i;o=!0;let m;try{m=JSON.parse(h)}catch(E){console.warn(`SyncEngineLevel: Corrupt sync options for ${p}, skipping identity:`,E);continue}let{protocols:g,delegateDid:_}=m,w=yield this.agent.dwn.getDwnEndpointUrlsForTarget(p);if(w.length===0){c=!0;continue}for(let E of w)if(g==="all")s.push({did:p,delegateDid:_,dwnUrl:E});else for(let k of g)s.push({did:p,delegateDid:_,dwnUrl:E,protocol:k})}}catch(p){r={error:p}}finally{try{!l&&!e&&(n=d.return)&&(yield n.call(d))}finally{if(r)throw r.error}}let f=o&&!c;return s.length>0&&f&&this._syncTargetsCacheGeneration===a&&(this._syncTargetsCache={targets:s,timestamp:Date.now()}),s})}getSyncPermissionGrantId(e,r,n){return He(this,void 0,void 0,function*(){return r?(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0})}};oa.ECHO_SUPPRESS_TTL_MS=6e4;oa.ECHO_SUPPRESS_MAX_ENTRIES=1e4;oa.SYNC_TARGETS_CACHE_TTL_MS=3e4;oa.MAX_CONSECUTIVE_FAILURES=5;oa.MAX_BACKOFF_MULTIPLIER=4;oa.MAX_REPAIR_ATTEMPTS=3;oa.REPAIR_BACKOFF_MS=[1e3,3e3,1e4];oa.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];y();Nn();Ho();jt();import{Level as rVe}from"level";y();y();y();jt();nn();y();y();var T7=wn(xx(),1);jt();var Cm=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Tx=class{constructor({ttl:e="15m"}={}){this.cache=new Gu.default({ttl:(0,T7.default)(e)})}get(e){return Cm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Cm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Cm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Cm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Cm(this,void 0,void 0,function*(){})}close(){return Cm(this,void 0,void 0,function*(){})}};y();nn();Nn();y();var $m=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Om;(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"})(Om||(Om={}));var Bm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),Dx=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),D7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function ch(t){try{return JSON.parse(t)}catch{return null}}var gR=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ohe=3,Bhe=500,jhe=1e4,Mhe=3e4,I7=new Set([408,429,500,502,503,504]);function Nhe(t,e){return t instanceof TypeError?!0:e?I7.has(e.status):!1}function Uhe(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=Math.floor(n/2);return i+crypto.getRandomValues(new Uint32Array(1))[0]%(i||1)}function Khe(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 Ix=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new Tx,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:Ohe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:Bhe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:jhe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return gR(this,void 0,void 0,function*(){var r,n,i;let a=vi.randomUuid(),s=Bm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},c=Object.assign({method:"POST",headers:o},e.signal?{signal:e.signal}:{});if(e.data){o["content-type"]="application/octet-stream";let p=e.data;if(p instanceof ReadableStream)if(t.isBunRuntime()){let h=yield Zi.toBytes(p);p=new Blob([h],{type:"application/octet-stream"})}else c.duplex="half";c.body=p}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let p=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new $m(p)}let d,u=l.headers.has("dwn-response");if(u){let p=ch(l.headers.get("dwn-response"));if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=p}else{let p=yield l.text(),h=ch(p);if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=h}if(d.error){let{code:p,message:h}=d.error;if(p===Om.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new $m(m)}throw new Error(`(${p}) - ${h}`)}let{reply:f}=d.result;if(u){let p=new Uint8Array(yield l.arrayBuffer()),h=Zi.fromBytes(p);f.record?f.record.data=h:f.entry&&(f.entry.data=h)}return f})}getServerInfo(e){return gR(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 $m(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 gR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Mhe),p=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),h=yield fetch(e,p);if(!I7.has(h.status)||c===n)return h;o=h}catch(f){if(!Nhe(f)||c===n)throw f;s=f}let l=o?Khe(o):void 0,d=Uhe(c,i,a),u=l===void 0?d:Math.max(l,d);yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};y();nn();var _v=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function wR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var A7=3e3,Lhe=3e4,qhe=1e3,zhe=3e4,Fhe=1/0,Ghe=3e4,Whe=1e4,Ax=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._awaitingPong=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return _v(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=A7,responseTimeout:s=Lhe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new t(o,s,r,n);return c.wireSocket(o),c.startHeartbeat(),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.stopHeartbeat(),this.socket.close()}request(e){return _v(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=vi.randomUuid());let a=s=>{let o=ch(wR(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 _v(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=ch(wR(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};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:()=>_v(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=vi.randomUuid(),n=Dx(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=()=>{l(),n(a)},o=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(c),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=ch(wR(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.stopHeartbeat(),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:Om.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}startHeartbeat(){var e,r;this.stopHeartbeat();let n=(e=this.options.heartbeatInterval)!==null&&e!==void 0?e:Ghe;if(n<=0)return;let i=(r=this.options.heartbeatTimeout)!==null&&r!==void 0?r:Whe;this._heartbeatInterval=setInterval(()=>{if(!this._isConnected||this._awaitingPong)return;this._awaitingPong=!0;let a=`hb-${Date.now()}`,s={jsonrpc:"2.0",id:a,method:"rpc.ping"};this.messageHandlers.set(a,()=>{this._awaitingPong=!1,this.messageHandlers.delete(a),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0)});try{this.send(s)}catch{this.messageHandlers.delete(a),this._awaitingPong=!1;return}this._heartbeatTimeout=setTimeout(()=>{if(this._heartbeatTimeout=void 0,this.messageHandlers.delete(a),this._awaitingPong=!1,!this.closedByUser&&this._isConnected){console.warn("JsonRpcSocket: heartbeat timeout \u2014 closing dead connection"),this._isConnected=!1;try{this.socket.close()}catch{}}},i)},n)}stopHeartbeat(){this._heartbeatInterval&&(clearInterval(this._heartbeatInterval),this._heartbeatInterval=void 0),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0),this._awaitingPong=!1}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:qhe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:zhe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Fhe,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:A7,l=0,d=()=>_v(this,void 0,void 0,function*(){var u,f,p,h;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let m=Math.min(a*Math.pow(2,l-1),s),g=Math.floor(m/2),_=g+crypto.getRandomValues(new Uint32Array(1))[0]%(g||1);if(yield new Promise(w=>setTimeout(w,_)),this.closedByUser){this.reconnecting=!1;return}try{let w=yield t.createWebSocket(this.url,c);this.socket=w,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(w),this.startHeartbeat(),(h=(p=this.options).onreconnected)===null||h===void 0||h.call(p)}catch{yield d()}});d()}};y();y();y();nn();y();nn();var jm=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ev=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return jm(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return jm(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield Ax.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 jm(this,void 0,void 0,function*(){let i=vi.randomUuid(),a=Bm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:c,result:l}=o;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return jm(this,void 0,void 0,function*(){let s=vi.randomUuid(),o=vi.randomUuid(),c=Dx(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,g=>{let{result:_,error:w}=g;if(w){let k=d.get(o);k&&k.subscription.close(),d.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let k=d.get(o);k&&(k.lastCursor=E.cursor),l.send(D7(o,E.cursor))}}),{error:p,result:h}=u;if(p)throw new Error(`could not subscribe via jsonrpc socket: ${p.message}`);let{reply:m}=h;if(m.subscription&&f){let g=()=>jm(this,void 0,void 0,function*(){d.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return jm(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{}})}};Ev.connections=new Map;var Sv=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(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},R7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(R7||(R7={}));var Mm=class{constructor(e=[]){this.transportClients=new Map,e=[new vR,new bR,...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 Sv(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 Sv(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)})}},vR=class extends Ix{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){let r=vi.randomUuid(),n=Bm(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:c}=a.error;throw new Error(`JSON RPC (${o}) - ${c}`)}}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})}},bR=class extends Ev{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Ho();jt();nn();Nn();y();jt();Ho();var Rx=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:Pv.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:Pv.Resolve});return n}};y();y();jt();var kv=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=Jo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Jo(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([Me.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 Bo.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Bo.consumeToBytes({readableStream:await this.stream()})},async json(){return await Bo.consumeToJson({readableStream:await this.stream()})},async text(){return await Bo.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Bo.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}