@rtc-agent/component 0.2.8-rc.2 → 0.2.8-rc.3

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.
@@ -8,7 +8,7 @@ var LN=Object.defineProperty;var jN=(ea,Ci,qa)=>Ci in ea?LN(ea,Ci,{enumerable:!0
8
8
  `):r=e;try{yield this._writer.write(r)}catch{this.close()}})}}const iE=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class aE{constructor(e){this.a=e,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const e=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return e}getChar(){return String.fromCharCode(this.getByte())}getInt(){let e=0,r;for(;this.haveBytes()&&(r=iE[127&this.getByte()])>=0;)e=(e<<6)+r;return this.pos--,e>>>0}}class oE{constructor(){this.a=[]}toByteArray(e){return Array.isArray(e)?this.a:new Uint8Array(this.a)}putArray(e,r,n){for(let i=r;i<n;i++)this.a.push(e[i])}}function lE(t){let e=0,r=0,n=0,i=0,o=0,a=t.length;for(;a>=16;)e=e+t[o+0]|0,r=r+t[o+1]|0,n=n+t[o+2]|0,i=i+t[o+3]|0,e=e+t[o+4]|0,r=r+t[o+5]|0,n=n+t[o+6]|0,i=i+t[o+7]|0,e=e+t[o+8]|0,r=r+t[o+9]|0,n=n+t[o+10]|0,i=i+t[o+11]|0,e=e+t[o+12]|0,r=r+t[o+13]|0,n=n+t[o+14]|0,i=i+t[o+15]|0,o+=16,a-=16;for(;a>=4;)e=e+t[o+0]|0,r=r+t[o+1]|0,n=n+t[o+2]|0,i=i+t[o+3]|0,o+=4,a-=4;switch(i=((i+(n<<8)|0)+(r<<16)|0)+(e<<24)|0,a){case 3:i=i+(t[o+2]<<8)|0;case 2:i=i+(t[o+1]<<16)|0;case 1:i=i+(t[o+0]<<24)|0}return i>>>0}function cE(t,e){let r=0;const n=new aE(e),i=t.length,o=e.length,a=n.getInt();if(n.getChar()!==`
9
9
  `)throw new Error("size integer not terminated by '\\n'");const u=new oE;for(;n.haveBytes();){const f=n.getInt();let d;switch(n.getChar()){case"@":if(d=n.getInt(),n.haveBytes()&&n.getChar()!==",")throw new Error("copy command not terminated by ','");if(r+=f,r>a)throw new Error("copy exceeds output file size");if(d+f>i)throw new Error("copy extends past end of input");u.putArray(t,d,d+f);break;case":":if(r+=f,r>a)throw new Error("insert command gives an output larger than predicted");if(f>o)throw new Error("insert count exceeds size of delta");u.putArray(n.a,n.pos,n.pos+f),n.pos+=f;break;case";":{const h=u.toByteArray(t);if(f!==lE(h))throw new Error("bad checksum");if(r!==a)throw new Error("generated size does not match predicted size");return h}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}class Hy{name(){return"json"}encodeCommands(e){return e.map(r=>JSON.stringify(r)).join(`
10
10
  `)}decodeReplies(e){return e.trim().split(`
11
- `).map(r=>JSON.parse(r))}applyDeltaIfNeeded(e,r){let n,i,o,a;if(e.delta){a=!0;const u=new TextEncoder().encode(e.data),f=cE(r,u);n=JSON.parse(new TextDecoder().decode(f)),i=f,o=u.length}else a=!1,n=JSON.parse(e.data),i=new TextEncoder().encode(e.data),o=i.length;return{newData:n,newPrevValue:i,isDelta:a,wireBytes:o,fullBytes:i.length}}}const uE={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class Oi extends Error{constructor(e){super(e),this.name=this.constructor.name}}class Ul extends Wy{constructor(e,r){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Mr.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new Hy,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},uE),r),this._configure(),this._debugEnabled?(this.on("state",n=>{this._debug("client state",n.oldState,"->",n.newState)}),this.on("error",n=>{this._debug("client error",n)})):this.on("error",function(){Function.prototype()})}newSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new ZT(this,e,r);return this._subs[e]=n,n}newMapSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qf(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapClientsSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qf(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapUsersSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qf(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newSharedPollSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new eE(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,sharedPoll:!0,sharedPollGetSignature:r==null?void 0:r.getSignature});return this._subs[e]=n,n}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==pn.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="map"&&(e[r]=n);return e}sharedPollSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="shared_poll"&&(e[r]=n);return e}ready(e){return jr(this,void 0,void 0,function*(){switch(this.state){case Mr.Disconnected:throw{code:pr.clientDisconnected,message:"client disconnected"};case Mr.Connected:return;default:return new Promise((r,n)=>{const i={resolve:r,reject:n};e&&(i.timeout=setTimeout(()=>{n({code:pr.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(Ka.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return jr(this,void 0,void 0,function*(){const r={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([r]))throw this._createErrorObject(pr.transportWriteError,"transport write error")})}rpc(e,r){return jr(this,void 0,void 0,function*(){const n={rpc:{method:e,data:r}};return yield this._methodCall(),{data:(yield this._callPromise(n,o=>o.rpc)).data}})}publish(e,r){return jr(this,void 0,void 0,function*(){const n={publish:{channel:e,data:r}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}mapPublish(e,r,n){return jr(this,void 0,void 0,function*(){const i={publish:{channel:e,type:1,key:r,data:n}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapRemove(e,r){return jr(this,void 0,void 0,function*(){const n={publish:{channel:e,type:1,key:r,removed:!0}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}history(e,r){return jr(this,void 0,void 0,function*(){const n={history:this._getHistoryRequest(e,r)};yield this._methodCall();const i=yield this._callPromise(n,a=>a.history),o=[];if(i.publications)for(let a=0;a<i.publications.length;a++)o.push(this._getPublicationContext(e,i.publications[a]));return{publications:o,epoch:i.epoch||"",offset:i.offset||0}})}presence(e){return jr(this,void 0,void 0,function*(){const r={presence:{channel:e}};yield this._methodCall();const i=(yield this._callPromise(r,o=>o.presence)).presence;for(const o in i)if(Object.prototype.hasOwnProperty.call(i,o)){const a=i[o],u=a.conn_info,f=a.chan_info;u&&(a.connInfo=u),f&&(a.chanInfo=f)}return{clients:i}})}presenceStats(e){return jr(this,void 0,void 0,function*(){const r={presence_stats:{channel:e}};yield this._methodCall();const n=yield this._callPromise(r,i=>i.presence_stats);return{numUsers:n.num_users,numClients:n.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&JT("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new Hy,this._formatOverride(),(this._config.debug===!0||QT("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const r=this._transports[e];if(!r.endpoint||!r.transport)throw new Error("malformed transport configuration");const n=r.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(n)<0)throw new Error("unsupported transport name: "+n)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;const r=this.state;return this.state=e,this.emit("state",{newState:e,oldState:r}),!0}return!1}_isDisconnected(){return this.state===Mr.Disconnected}_isConnecting(){return this.state===Mr.Connecting}_isConnected(){return this.state===Mr.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state===Mr.Connected||this.state===Mr.Connecting)&&(this._disconnect(Ii.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Mr.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=ua(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const r=this._callbacks[e];clearTimeout(r.timeout);const n=r.errback;if(!n)continue;n({error:this._createErrorObject(pr.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const r=this._subs[e];r.state===pn.Subscribed&&r._setSubscribing($l.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const r of e){const n=r.id;if(!(n in this._callbacks))continue;const i=this._callbacks[n];clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n];const o=i.errback;o({error:this._createErrorObject(pr.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(r){return this._debug("error writing commands",r),this._handleWriteError(e),!1}return!0}_advanceTransportIndex(){this._currentTransportIndex++,this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0)}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let r=null;this._config.sockjs!==null?r=this._config.sockjs:typeof globalThis.SockJS<"u"&&(r=globalThis.SockJS);let n=null;this._config.eventsource!==null?n=this._config.eventsource:typeof globalThis.EventSource<"u"&&(n=globalThis.EventSource);let i=null;this._config.fetch!==null?i=this._config.fetch:typeof globalThis.fetch<"u"&&(i=globalThis.fetch);let o=null;if(this._config.readableStream!==null?o=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(o=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let S=0;for(;;){if(S>=this._transports.length)throw new Error("no supported transport found");const O=this._transports[this._currentTransportIndex],x=O.transport,w=O.endpoint;if(x==="websocket"){if(this._debug("trying websocket transport"),this._transport=new Gy(w,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new sE(w,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new rE(w,{fetch:i,readableStream:o,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="sse"){if(this._debug("trying sse transport"),this._transport=new nE(w,{eventsource:n,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="sockjs"){if(this._debug("trying sockjs"),this._transport=new tE(w,{sockjs:r,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._advanceTransportIndex(),S++;continue}}else throw new Error("unknown transport "+x);break}}else{if(zT(this._endpoint,"http"))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new Gy(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}const a=this,u=this._transport,f=this._nextTransportId();a._debug("id of transport",f);let d=!1;const h=[];if(this._transport.emulation()){const S=a._sendConnect(!0);h.push(S)}this._setNetworkEvents();const m=this._codec.encodeCommands(h);this._transportClosed=!1;let b;b=setTimeout(function(){u.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(b&&(clearTimeout(b),b=null),a._transportId!=f){a._debug("open callback from non-actual transport"),u.close();return}d=!0,a._debug(u.subName(),"transport open"),!u.emulation()&&(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(S){if(a._transportId!=f){a._debug("error callback from non-actual transport");return}a._debug("transport level error",S)},onClose:function(S){if(b&&(clearTimeout(b),b=null),a._transportId!=f){a._debug("close callback from non-actual transport");return}a._debug(u.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let O="connection closed",x=!0,w=0;if(S&&"code"in S&&S.code&&(w=S.code),S&&S.reason)try{const C=JSON.parse(S.reason);O=C.reason,x=C.reconnect}catch{O=S.reason,(w>=3500&&w<4e3||w>=4500&&w<5e3)&&(x=!1)}w<3e3?(w===1009?(w=Ka.messageSizeLimit,O="message size limit exceeded",x=!1):(w=Ii.transportClosed,O="transport closed"),a._emulation&&!a._transportWasOpen&&a._advanceTransportIndex()):a._transportWasOpen=!0,a._isConnecting()&&!d&&a.emit("error",{type:"transport",error:{code:pr.transportClosed,message:"transport closed"},transport:u.name()}),a._reconnecting=!1,a._disconnect(w,O,x)},onMessage:function(S){a._dataReceived(S)}},m),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const r=this._constructConnectCommand(),n=this;return this._call(r,e).then(i=>{const o=i.reply.connect;n._connectResponse(o),i.next&&i.next()},i=>{n._connectError(i.error),i.next&&i.next()}),r}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;const e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(i=>{this._isConnecting()&&(this._data=i,this._initializeTransport())}).catch(i=>this._handleGetDataError(i)):this._initializeTransport();return}const n=this;this._getToken().then(function(i){if(n._isConnecting()){if(i==null||i==null){n._failUnauthorized();return}n._token=i,n._debug("connection token refreshed"),n._config.getData?n._config.getData().then(function(o){n._isConnecting()&&(n._data=o,n._initializeTransport())}).catch(o=>n._handleGetDataError(o)):n._initializeTransport()}}).catch(function(i){if(!n._isConnecting())return;if(i instanceof Oi){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:pr.clientConnectToken,message:i!==void 0?i.toString():""}});const o=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+o+" milliseconds",i),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},o)})}_handleGetDataError(e){if(e instanceof Oi){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:pr.badConfiguration,message:(e==null?void 0:e.toString())||""}});const r=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+r+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_connectError(e){this.state===Mr.Connecting&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let r=this._getReconnectDelay();e&&(r=0),this._debug("reconnect after "+r+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const r={};let n=!1;for(const i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){n=!0;const o={recover:!0};this._serverSubs[i].offset&&(o.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(o.epoch=this._serverSubs[i].epoch),r[i]=o}return n&&(e.subs=r),{connect:e}}_getHistoryRequest(e,r){const n={channel:e};return r!==void 0&&(r.since&&(n.since={offset:r.since.offset},r.since.epoch&&(n.since.epoch=r.since.epoch)),r.limit!==void 0&&(n.limit=r.limit),r.reverse===!0&&(n.reverse=!0)),n}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,r)=>{const n=setTimeout(function(){r({code:pr.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:r}})}_callPromise(e,r){return new Promise((n,i)=>{this._call(e,!1).then(o=>{var a;const u=r(o.reply);n(u),(a=o.next)===null||a===void 0||a.call(o)},o=>{var a;i(o.error),(a=o.next)===null||a===void 0||a.call(o)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const r=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let n;this._dispatchPromise=new Promise(i=>{n=i}),this._dispatchSynchronized(r,n)})}_dispatchSynchronized(e,r){let n=Promise.resolve();for(const i in e)e.hasOwnProperty(i)&&(n=n.then(()=>this._dispatchReply(e[i])));n.then(()=>{r()})}_dispatchReply(e){let r;const n=new Promise(o=>{r=o});if(e==null)return this._debug("dispatch: got undefined or null reply"),r(),n;const i=e.id;return i&&i>0?this._handleReply(e,r):e.push?this._handlePush(e.push,r):this._handleServerPing(r),n}_call(e,r){return new Promise((n,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,n,i),r||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(Mr.Connecting)&&this.emit("connecting",{code:Ii.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,r,n){if(e===Ka.stateInvalidated){this._token="",this._refreshRequired=!0;for(const u in this._subs)this._subs.hasOwnProperty(u)&&this._subs[u]._invalidateState();for(const u in this._serverSubs)this._serverSubs.hasOwnProperty(u)&&(this._serverSubs[u].offset=0,this._serverSubs[u].epoch="_")}if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const o={code:e,reason:r};let a;if(n?a=this._setState(Mr.Connecting):(a=this._setState(Mr.Disconnected),this._rejectPromises({code:pr.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===Mr.Connecting&&this._clearReconnectTimeout(),i===Mr.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",o):this.emit("disconnected",o)),this._transport){this._debug("closing existing transport");const u=this._transport;this._transport=null,u.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Ka.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:pr.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new Oi("")))}_refresh(){const e=this._client,r=this;this._getToken().then(function(n){if(e!==r._client)return;if(!n){r._failUnauthorized();return}if(r._token=n,r._debug("connection token refreshed"),!r._isConnected())return;const i={refresh:{token:r._token}};r._call(i,!1).then(o=>{const a=o.reply.refresh;r._refreshResponse(a),o.next&&o.next()},o=>{r._refreshError(o.error),o.next&&o.next()})}).catch(function(n){if(r._isConnected()){if(n instanceof Oi){r._failUnauthorized();return}r.emit("error",{type:"refreshToken",error:{code:pr.clientRefreshToken,message:n!==void 0?n.toString():""}}),r._refreshTimeout=setTimeout(()=>r._refresh(),r._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return ua(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),jo(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const n={unsubscribe:{channel:e.channel}},i=this;return new Promise((a,u)=>{this._call(n,!1).then(f=>{a(),f.next&&f.next()},f=>{a(),f.next&&f.next(),i._disconnect(Ii.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,r){if(r&&r>0){for(const i in this._subs)if(this._subs.hasOwnProperty(i)){const o=this._subs[i];if(o._id===r)return o}return null}const n=this._subs[e];return n||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const r in this._subs){if(!this._subs.hasOwnProperty(r))continue;const n=this._subs[r];if(n._inflight!==!0&&n.state===pn.Subscribing){const i=n._subscribe();i&&e.push(i)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(Mr.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),jo(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const r={client:e.client,transport:this._transport.subName()};e.data&&(r.data=e.data),this.emit("connected",r),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];this._serverSubs[r]={offset:n.offset,epoch:n.epoch,recoverable:n.recoverable||!1};const i=this._getSubscribeContext(r,n);this.emit("subscribed",i)}for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];if(n.recovered){const i=n.publications;if(i&&i.length>0)for(const o in i)i.hasOwnProperty(o)&&this._handlePublication(r,i[o])}}for(const r in this._serverSubs)this._serverSubs.hasOwnProperty(r)&&(e[r]||(this.emit("unsubscribed",{channel:r}),delete this._serverSubs[r]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Ii.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,r){const n={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};r.recovered&&(n.recovered=!0),r.positioned&&(n.positioned=!0),r.recoverable&&(n.recoverable=!0),r.was_recovering&&(n.wasRecovering=!0);let i="";"epoch"in r&&(i=r.epoch);let o=0;return"offset"in r&&(o=r.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:o,epoch:i}),Array.isArray(r.publications)&&r.publications.length>0&&(n.hasRecoveredPublications=!0),r.data&&(n.data=r.data),n}_handleReply(e,r){const n=e.id;if(!(n in this._callbacks)){r();return}const i=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],XT(e)){const o=i.errback;if(!o){r();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};o({error:a,next:r})}else{const o=i.callback;if(!o)return;o({reply:e,next:r})}}_handleJoin(e,r,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("join",o)}return}i._handleJoin(r)}_handleLeave(e,r,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("leave",o)}return}i._handleLeave(r)}_handleUnsubscribe(e,r){const n=this._getSub(e,0);if(!n&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}r.code<2500?n._setUnsubscribed(r.code,r.reason,!1):(r.code===Ro.stateInvalidated&&n._invalidateState(),n._setSubscribing(r.code,r.reason))}_handleSubscribe(e,r){this._serverSubs[e]={offset:r.offset,epoch:r.epoch,recoverable:r.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,r))}_handleDisconnect(e){const r=e.code;let n=!0;(r>=3500&&r<4e3||r>=4500&&r<5e3)&&(n=!1),this._disconnect(r,e.reason,n)}_getPublicationContext(e,r){const n={channel:e,data:r.data};return r.offset&&(n.offset=r.offset),r.info&&(n.info=this._getJoinLeaveContext(r.info)),r.tags&&(n.tags=r.tags),n}_getJoinLeaveContext(e){const r={client:e.client,user:e.user},n=e.conn_info;n&&(r.connInfo=n);const i=e.chan_info;return i&&(r.chanInfo=i),r}_handlePublication(e,r,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const o=this._getPublicationContext(e,r);this.emit("publication",o),r.offset!==void 0&&(this._serverSubs[e].offset=r.offset)}return}i._handlePublication(r)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const r={};this._transportSendCommands([r])}e()}_handlePush(e,r){const n=e.channel,i=e.id;e.pub?this._handlePublication(n,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(n,e.join,i):e.leave?this._handleLeave(n,e.leave,i):e.unsubscribe?this._handleUnsubscribe(n,e.unsubscribe):e.subscribe?this._handleSubscribe(n,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),r()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,r,n){const i={code:e,message:r};return n&&(i.temporary=!0),i}_registerCall(e,r,n){this._callbacks[e]={callback:r,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],$f(n)&&n({error:this._createErrorObject(pr.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const r in this._promises)this._promises.hasOwnProperty(r)&&(this._promises[r].timeout&&clearTimeout(this._promises[r].timeout),this._promises[r].reject(e),delete this._promises[r])}}Ul.SubscriptionState=pn,Ul.State=Mr,Ul.UnauthorizedError=Oi;const Ln={SessionList:"v1.session.list",SessionGet:"v1.session.get",SessionClose:"v1.session.close",SessionOpen:"v1.session.open",SessionUpdate:"v1.session.update",SessionFork:"v1.session.fork",SessionCompact:"v1.session.compact",MessageSend:"v1.message.send",MessageList:"v1.message.list",TurnList:"v1.turn.list",TurnStop:"v1.turn.stop",RtcList:"v1.rtc.list",RtcUpdateStatus:"v1.rtc.update_status",RtcSubmitResult:"v1.rtc.submit_result"},zy={debug:0,info:1,warn:2,error:3};let fE="debug";function Bs(t){const e=r=>zy[r]>=zy[fE];return{debug(...r){e("debug")&&console.debug(`[${t}]`,...r)},info(...r){e("info")&&console.info(`[${t}]`,...r)},warn(...r){e("warn")&&console.warn(`[${t}]`,...r)},error(...r){e("error")&&console.error(`[${t}]`,...r)}}}const sr=Bs("RTCAgentClient");class pE extends Error{constructor(e,r,n){super(`Gap fill timeout after ${n}ms: channel=${e}, target=${r}`),this.channel=e,this.targetOffset=r,this.elapsedMs=n,this.name="GapFillTimeoutError"}}const $a=class $a{constructor(e){Bt(this,"options");Bt(this,"centrifuge",null);Bt(this,"connectionState","disconnected");Bt(this,"listeners",new Map);Bt(this,"shouldReconnect",!0);Bt(this,"wasConnected",!1);Bt(this,"applyUpdatesQueue",null);Bt(this,"subscriptions",new Map);Bt(this,"epochCache",new Map);Bt(this,"_reconnectTimer");Bt(this,"gapFillTasks",new Map);Bt(this,"isGapFillProcessing",!1);Bt(this,"_gapFillAbortControllers",new Map);Bt(this,"pendingUpdates",[]);Bt(this,"isUpdateProcessing",!1);Bt(this,"lastOffsetCache",new Map);this.options=e}async connect(){if(sr.debug("connect() called, current state:",this.connectionState),this.connectionState==="connected"||this.connectionState==="connecting"){sr.debug("connect() early return, already",this.connectionState);return}this.shouldReconnect=!0,this.setConnectionState("connecting"),this.centrifuge=new Ul(this.options.endpoint,{getToken:async()=>{var r;const e=await this.options.getToken();if(this._isTokenExpired(e)&&this.options.onTokenExpired){if(await this.options.onTokenExpired()==="relogin")throw this.shouldReconnect=!1,(r=this.centrifuge)==null||r.disconnect(),this.setConnectionState("disconnected","token expired, relogin required"),new Error("Token expired, user needs to re-login");return this.options.getToken()}return e}}),this.centrifuge.on("connecting",e=>{var n;if(!this.shouldReconnect){(n=this.centrifuge)==null||n.disconnect();return}const r=this.wasConnected?"reconnecting":"connecting";this.setConnectionState(r,e==null?void 0:e.reason)}),this.centrifuge.on("connected",()=>{sr.debug("centrifuge connected, setting state to connected"),this.wasConnected=!0,this.setConnectionState("connected"),this.subscribeChannels()}),this.centrifuge.on("disconnected",e=>{if(sr.debug("[GAP_FILL_DEBUG] centrifuge disconnected, reason:",e==null?void 0:e.reason,"| code:",e==null?void 0:e.code,"| wasConnected:",this.wasConnected,"| shouldReconnect:",this.shouldReconnect,"| activeGapFills:",this.gapFillTasks.size),(e==null?void 0:e.reason)==="invalid token"&&this.options.onTokenExpired){const r=this.centrifuge;this.centrifuge=null,r==null||r.disconnect(),this.handleInvalidToken()}(e==null?void 0:e.reason)==="message size limit exceeded"&&(sr.warn("message size limit exceeded, will retry connection after delay"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.connectionState==="disconnected"&&(sr.debug("attempting reconnect after message size limit error"),this.reconnect().catch(r=>{sr.error("reconnect failed:",r)}))},$a.RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS)),this.setConnectionState("disconnected",e==null?void 0:e.reason)}),this.centrifuge.on("error",e=>{var r;sr.error("centrifuge error:",e==null?void 0:e.error),this.emit("error",new Error(((r=e==null?void 0:e.error)==null?void 0:r.message)??"centrifuge error"))}),sr.debug("calling centrifuge.connect() synchronously"),this.centrifuge.connect(),sr.debug("centrifuge.connect() returned, state:",this.connectionState,"(WebSocket not yet established)")}disconnect(){var e;this.shouldReconnect=!1,this.wasConnected=!1,this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0),this._gapFillAbortControllers.forEach(r=>r.abort()),this._gapFillAbortControllers.clear(),this.gapFillTasks.clear(),this.isGapFillProcessing=!1,this.isUpdateProcessing=!1,(e=this.centrifuge)==null||e.disconnect(),this.centrifuge=null,this.subscriptions.clear(),this.pendingUpdates.length=0,this.lastOffsetCache.clear(),this.setConnectionState("disconnected")}async reconnect(){this.disconnect(),await this.connect()}getConnectionState(){return this.connectionState}getUserId(){return this.options.userId}async listSessions(e,r){return this.rpc(Ln.SessionList,{cursor:e,limit:r})}async getSession(e){return this.rpc(Ln.SessionGet,{session_id:e})}async closeSession(e){return this.rpc(Ln.SessionClose,{session_id:e})}async openSession(e){return this.rpc(Ln.SessionOpen,{session_id:e})}async compactSession(e){return this.rpc(Ln.SessionCompact,e)}async updateSession(e){return this.rpc(Ln.SessionUpdate,e)}async sendMessage(e){return this.rpc(Ln.MessageSend,e)}async forkSession(e){return this.rpc(Ln.SessionFork,e)}async stopTurn(e){return this.rpc(Ln.TurnStop,{session_id:e})}async listMessages(e,r,n){return this.rpc(Ln.MessageList,{session_id:e,cursor:r,limit:n})}async listTurns(e,r,n){return this.rpc(Ln.TurnList,{session_id:e,cursor:r,limit:n})}async listRtc(e,r,n){return this.rpc(Ln.RtcList,{session_id:e,cursor:r,limit:n})}async updateRtcStatus(e,r){return this.rpc(Ln.RtcUpdateStatus,{rtc_id:e,status:r})}async submitRtcResult(e,r,n,i){return this.rpc(Ln.RtcSubmitResult,{rtc_id:e,success:r,result:n,error:i})}async applyUpdates(e,r){let n=this.applyUpdatesQueue;const i=(async()=>{if(n&&await n,r)await r();else for(const o of e)await this.processUpdate(o)})();this.applyUpdatesQueue=i;try{await i}finally{this.applyUpdatesQueue===i&&(this.applyUpdatesQueue=null)}}async processUpdate(e){var n,i,o,a,u,f;const r=`topic:u=${this.options.userId}`;if(e.offset>0){const d=await((i=(n=this.options).getLastOffset)==null?void 0:i.call(n,r)),h=d==null?void 0:d.offset,m=(d==null?void 0:d.epoch)??this.epochCache.get(r)??"";if(h!==void 0&&e.offset<=h){sr.debug(`Skipping duplicate/expired message: offset=${e.offset}, lastOffset=${h}`);return}if(h!==void 0&&e.offset>h+1){this.scheduleGapFill(r,e.offset,m),await this.waitForGapFill(r,e.offset-1);const b=await((a=(o=this.options).getLastOffset)==null?void 0:a.call(o,r)),S=b==null?void 0:b.offset,O=b==null?void 0:b.epoch,x=this.epochCache.get(r)??"";if(S===void 0||S!==e.offset-1)throw new Error(`[RTCAgentClient] Offset gap fill failed: expected ${e.offset-1}, got ${S}. Rejecting update ${e.offset} to maintain strict +1 continuity.`);if(O!==void 0&&O!==x)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill: expected '${x}', got '${O}'. Rejecting update ${e.offset} to prevent data corruption.`)}}if(this.options.onPublication){const d={channel:`topic:u=${this.options.userId}`,offset:e.offset,data:e};await this.options.onPublication(d)}if(e.offset>0){const d=this.epochCache.get(r)??"";await((f=(u=this.options).updateOffset)==null?void 0:f.call(u,r,e.offset,d))}}async waitForGapFill(e,r){var f,d;const o=Date.now(),a=new AbortController,u=`${e}:${r}`;this._gapFillAbortControllers.set(u,a);try{for(;Date.now()-o<3e4;){if(a.signal.aborted)throw new Error(`Gap fill aborted for channel ${e}`);const m=await((d=(f=this.options).getLastOffset)==null?void 0:d.call(f,e));if(((m==null?void 0:m.offset)??0)>=r)return;if(a.signal.aborted)throw new Error(`Gap fill aborted for channel ${e}`);if(!this.gapFillTasks.has(e)&&!this.isGapFillProcessing)return;await new Promise((S,O)=>{const x=setTimeout(S,100);a.signal.addEventListener("abort",()=>{clearTimeout(x),O(new Error(`Gap fill aborted for channel ${e}`))},{once:!0})})}const h=Date.now()-o;throw new pE(e,r,h)}finally{this._gapFillAbortControllers.get(u)===a&&this._gapFillAbortControllers.delete(u)}}on(e,r){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(r),()=>{n.delete(r)}}scheduleUpdate(e){const r=`topic:u=${this.options.userId}`;if(e.offset>0){const n=this.lastOffsetCache.get(r);if(n!==void 0&&e.offset<=n){sr.debug(`scheduleUpdate: skip expired offset=${e.offset}, lastOffset=${n}`);return}}if(e.offset>0&&this.pendingUpdates.some(n=>n.offset===e.offset)){sr.debug(`scheduleUpdate: skip duplicate in buffer offset=${e.offset}`);return}this.pendingUpdates.push(e),this.processUpdateQueue()}async processUpdateQueue(){var e;if(!this.isUpdateProcessing){this.isUpdateProcessing=!0;try{for(;this.pendingUpdates.length>0;){const r=this.pendingUpdates.shift();try{if(await this.applyUpdates([r]),r.offset>0){const n=`topic:u=${this.options.userId}`;this.lastOffsetCache.set(n,r.offset)}}catch(n){sr.error(`processUpdateQueue failed for offset ${r.offset}:`,n),this.emit("error",n instanceof Error?n:new Error(String(n))),this.shouldReconnect&&((e=this.centrifuge)==null||e.disconnect(),this.setConnectionState("disconnected","update processing failed"),this.emit("syncRequired",{reason:"gap_fill_failed",lastKnownOffset:r.offset-1,serverOffset:r.offset}),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.connectionState==="disconnected"&&(sr.debug("attempting reconnect after update processing failure"),this.reconnect().catch(i=>sr.error("reconnect failed:",i)))},$a.RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS));break}}}finally{this.isUpdateProcessing=!1}}}scheduleGapFill(e,r,n){const i=this.gapFillTasks.get(e);i?(i.targetOffset=Math.max(i.targetOffset,r),i.epoch=n,sr.debug(`[GAP_FILL_DEBUG] scheduleGapFill merged: channel=${e}, targetOffset=${i.targetOffset}, isProcessing=${this.isGapFillProcessing}`)):(this.gapFillTasks.set(e,{targetOffset:r,epoch:n}),this.processGapFillQueue())}async processGapFillQueue(){if(!this.isGapFillProcessing){this.isGapFillProcessing=!0;try{for(;this.gapFillTasks.size>0;){const[e,{targetOffset:r,epoch:n}]=this.gapFillTasks.entries().next().value;await this.runGapFill(e,r,n);const i=this.gapFillTasks.get(e);i&&i.targetOffset<=r&&this.gapFillTasks.delete(e)}}finally{this.isGapFillProcessing=!1}}}async runGapFill(e,r,n){var O,x,w,C,T,_,E,D,B,I,R,Z,z;const i=this.subscriptions.get(e);if(!i){sr.warn(`runGapFill: subscription not found for channel ${e}`);return}sr.debug(`[GAP_FILL_DEBUG] runGapFill started: channel=${e}, targetOffset=${r}, connectionState=${this.connectionState}, centrifuge=${!!this.centrifuge}, subState=${i.state}`);const o=10,a=1e4,u=100,f=await((x=(O=this.options).getLastOffset)==null?void 0:x.call(O,e)),d=(f==null?void 0:f.offset)??0,h=r-d;console.log(`[BulkUpdate] runGapFill: gapSize=${h}, threshold=${u}`),h>u&&(console.log("[BulkUpdate] runGapFill: calling onGapFillStart"),(C=(w=this.options).onGapFillStart)==null||C.call(w),(_=(T=this.options).suspendUIUpdates)==null||_.call(T));let m=[],b=[],S=d;try{for(;S<r-1;){for(m=[],b=[];m.length<a&&S<r-1;){const N=r-S-1,U=Math.min(o,N);if(U<=0)break;const ne={since:{offset:S,epoch:n},limit:U,reverse:!1};sr.debug(`[GAP_FILL_DEBUG] Calling sub.history(): offset=${S}, limit=${U}, connectionState=${this.connectionState}, hasCentrifuge=${!!this.centrifuge}, subState=${i.state}`);const xe=(await i.history(ne)).publications;if(xe.length===0)break;const Ce=xe[0].offset??0;if(Ce!==S+1)throw new Error(`Gap fill missing messages: expected first offset ${S+1}, got ${Ce}`);for(let le=1;le<xe.length;le++){const ce=xe[le-1].offset??0,K=xe[le].offset??0;if(K!==ce+1)throw new Error(`Gap fill non-continuous: offset jumped from ${ce} to ${K}`)}for(const le of xe){const ce=le.data,K=le.offset??0;(ce==null?void 0:ce.type)==="gap"?b.push(K):m.push(le.data)}if(S=xe[xe.length-1].offset??S,xe.length<U)break}await this.flushGapFillBuffer(e,m,b,n)}}catch(N){if(m.length>0||b.length>0){sr.debug(`[GAP_FILL_DEBUG] Network error, flushing buffer before error handling: ${m.length} updates, ${b.length} gap offsets`);try{await this.flushGapFillBuffer(e,m,b,n)}catch(U){sr.error("[GAP_FILL_DEBUG] Failed to flush buffer on error:",U)}}sr.error(`[GAP_FILL_DEBUG] runGapFill failed for channel ${e}:`,N,`| connectionState=${this.connectionState}`,`| hasCentrifuge=${!!this.centrifuge}`,`| targetOffset=${r}`,`| epoch=${n}`),this.emit("error",N instanceof Error?N:new Error(String(N))),this.emit("syncRequired",{reason:"gap_fill_failed",lastKnownOffset:(B=await((D=(E=this.options).getLastOffset)==null?void 0:D.call(E,e)))==null?void 0:B.offset,serverOffset:r})}finally{h>u&&(console.log("[BulkUpdate] runGapFill: calling resumeUIUpdates and onGapFillEnd"),(R=(I=this.options).resumeUIUpdates)==null||R.call(I),(z=(Z=this.options).onGapFillEnd)==null||z.call(Z))}}deduplicateUpdates(e){var o;const r=new Map;for(const a of e)for(let u=0;u<a.items.length;u++){const f=a.items[u],d=(o=a.data_list)==null?void 0:o[u];if(!d)continue;const h=`${f.entity}:${f.entity_id}`,m=r.get(h);(!m||a.offset<m.offset)&&r.set(h,{item:f,data:d,offset:a.offset})}const n=[],i=Array.from(r.values()).sort((a,u)=>a.offset-u.offset);for(const{item:a,data:u,offset:f}of i)n.push({id:"",items:[a],data_list:[u],offset:f});return n}async flushGapFillBuffer(e,r,n,i){var o,a,u,f,d,h,m,b;if(r.length>0){const S=this.deduplicateUpdates(r);(a=(o=this.options).suspendUIUpdates)==null||a.call(o);try{if(this.options.onPublications){const w=S.map(C=>({channel:e,offset:C.offset,data:C}));await this.options.onPublications(w)}else for(const w of S)if(this.options.onPublication){const C={channel:e,offset:w.offset,data:w};await this.options.onPublication(C)}const O=[...n,...r.map(w=>w.offset)],x=Math.max(...O);await((f=(u=this.options).updateOffset)==null?void 0:f.call(u,e,x,i))}finally{(h=(d=this.options).resumeUIUpdates)==null||h.call(d)}}else if(n.length>0){const S=Math.max(...n);await((b=(m=this.options).updateOffset)==null?void 0:b.call(m,e,S,i))}}emit(e,r){const n=this.listeners.get(e);if(n)for(const i of n)try{i(r)}catch(o){sr.error(`listener for '${e}' threw:`,o)}}setConnectionState(e,r){var i,o;if(sr.debug("[GAP_FILL_DEBUG] setConnectionState:",e,"reason:",r,"| previous:",this.connectionState,"| timestamp:",new Date().toISOString()),this.connectionState===e)return;this.connectionState=e;const n={state:e,reason:r};this.emit("connection",n),(o=(i=this.options).onConnectionStateChange)==null||o.call(i,n)}async handleInvalidToken(){var e;if(!this.options.onTokenExpired){sr.warn("invalid token but no onTokenExpired callback provided");return}try{await this.options.onTokenExpired()==="relogin"?(this.shouldReconnect=!1,(e=this.centrifuge)==null||e.disconnect(),this.setConnectionState("disconnected","token expired, relogin required")):(sr.debug("token refreshed, attempting to reconnect"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.reconnect().catch(n=>{sr.error("reconnect after token refresh failed:",n)})},$a.RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS))}catch(r){sr.error("handleInvalidToken failed:",r)}}_isTokenExpired(e){try{const r=e.split(".");if(r.length!==3)return sr.debug("_isTokenExpired: token does not have 3 parts, treating as not expired"),!1;const n=JSON.parse(atob(r[1]));if(typeof n.exp!="number")return sr.debug("_isTokenExpired: payload.exp is not a number, treating as not expired"),!1;const i=n.exp*1e3<Date.now();return sr.debug("_isTokenExpired: exp=",n.exp,"expired=",i),i}catch(r){return sr.debug("_isTokenExpired: failed to parse JWT, treating as not expired:",r),!1}}async rpc(e,r){if(!this.centrifuge)throw new Error("RTCAgentClient not connected");if(this.connectionState!=="connected")throw new Error(`Cannot call RPC '${e}': connection state is ${this.connectionState}`);try{return(await this.centrifuge.rpc(e,r)).data}catch(n){throw sr.error(`RPC '${e}' failed:`,n),n}}subscribeChannels(){var i,o;if(!this.centrifuge||!this.options.userId)return;const e=this.options.userId,r=`topic:u=${e}`;if(!this.subscriptions.has(r)){const a=this.centrifuge.newSubscription(r);this.subscriptions.set(r,a),a.on("publication",u=>{this.scheduleUpdate(u.data)}),a.on("subscribed",async u=>{var f,d,h,m,b,S,O,x;if(sr.debug(`[GAP_FILL_DEBUG] Subscription 'subscribed' event: channel=${r}, serverOffset=${(f=u.streamPosition)==null?void 0:f.offset}, epoch=${(d=u.streamPosition)==null?void 0:d.epoch}, connectionState=${this.connectionState}`),u.streamPosition){const w=u.streamPosition.epoch,C=u.streamPosition.offset;this.epochCache.set(r,w);const T=await((m=(h=this.options).getLastOffset)==null?void 0:m.call(h,r));let _;T&&T.epoch!==w?(sr.warn(`Epoch changed: '${T.epoch}' -> '${w}', resetting offset to 0`),await((S=(b=this.options).updateOffset)==null?void 0:S.call(b,r,0,w)),_=0):_=T==null?void 0:T.offset,_===void 0?(await((x=(O=this.options).updateOffset)==null?void 0:x.call(O,r,C,w)),_=C):C<=_||this.scheduleGapFill(r,C+1,w),_!==void 0&&this.lastOffsetCache.set(r,_)}})}(i=this.subscriptions.get(r))==null||i.subscribe();const n=`live:u=${e}`;if(!this.subscriptions.has(n)){const a=this.centrifuge.newSubscription(n);this.subscriptions.set(n,a),a.on("publication",u=>{const f={channel:n,data:u.data};this.handlePublication(f,a)})}(o=this.subscriptions.get(n))==null||o.subscribe()}async handlePublication(e,r){if(this.options.onPublication)try{await this.options.onPublication(e)}catch(n){throw sr.error(`onPublication threw for channel '${e.channel}':`,n),r.unsubscribe(),n}}};Bt($a,"RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS",3e3),Bt($a,"RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS",1e3);let Vf=$a;var Rs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Jy={exports:{}};(function(t,e){((r,n)=>{t.exports=n()})(Rs,function(){var r=function(v,P){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(j,V){j.__proto__=V}:function(j,V){for(var re in V)Object.prototype.hasOwnProperty.call(V,re)&&(j[re]=V[re])}))(v,P)},n=function(){return(n=Object.assign||function(v){for(var P,j=1,V=arguments.length;j<V;j++)for(var re in P=arguments[j])Object.prototype.hasOwnProperty.call(P,re)&&(v[re]=P[re]);return v}).apply(this,arguments)};function i(v,P,j){for(var V,re=0,pe=P.length;re<pe;re++)!V&&re in P||((V=V||Array.prototype.slice.call(P,0,re))[re]=P[re]);return v.concat(V||Array.prototype.slice.call(P))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Rs,a=Object.keys,u=Array.isArray;function f(v,P){return typeof P=="object"&&a(P).forEach(function(j){v[j]=P[j]}),v}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var d=Object.getPrototypeOf,h={}.hasOwnProperty;function m(v,P){return h.call(v,P)}function b(v,P){typeof P=="function"&&(P=P(d(v))),(typeof Reflect>"u"?a:Reflect.ownKeys)(P).forEach(function(j){O(v,j,P[j])})}var S=Object.defineProperty;function O(v,P,j,V){S(v,P,f(j&&m(j,"get")&&typeof j.get=="function"?{get:j.get,set:j.set,configurable:!0}:{value:j,configurable:!0,writable:!0},V))}function x(v){return{from:function(P){return v.prototype=Object.create(P.prototype),O(v.prototype,"constructor",v),{extend:b.bind(null,v.prototype)}}}}var w=Object.getOwnPropertyDescriptor,C=[].slice;function T(v,P,j){return C.call(v,P,j)}function _(v,P){return P(v)}function E(v){if(!v)throw new Error("Assertion Failed")}function D(v){o.setImmediate?setImmediate(v):setTimeout(v,0)}function B(v,P){if(typeof P=="string"&&m(v,P))return v[P];if(!P)return v;if(typeof P!="string"){for(var j=[],V=0,re=P.length;V<re;++V){var pe=B(v,P[V]);j.push(pe)}return j}var Te,Ne=P.indexOf(".");return Ne===-1||(Te=v[P.substr(0,Ne)])==null?void 0:B(Te,P.substr(Ne+1))}function I(v,P,j){if(v&&P!==void 0&&!("isFrozen"in Object&&Object.isFrozen(v)))if(typeof P!="string"&&"length"in P){E(typeof j!="string"&&"length"in j);for(var V=0,re=P.length;V<re;++V)I(v,P[V],j[V])}else{var pe=P.indexOf(".");if(pe!==-1){var Te=P.substr(0,pe),pe=P.substr(pe+1);if(pe==="")j===void 0?u(v)&&!isNaN(parseInt(Te))?v.splice(Te,1):delete v[Te]:v[Te]=j;else{var Ne=v[Te];if(!Ne||!m(v,Te)){if(j===void 0)return;Ne=v[Te]={}}I(Ne,pe,j)}}else j===void 0?u(v)&&!isNaN(parseInt(P))?v.splice(P,1):delete v[P]:v[P]=j}}function R(v){var P,j={};for(P in v)m(v,P)&&(j[P]=v[P]);return j}var Z=[].concat;function z(v){return Z.apply([],v)}var ae="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(z([8,16,32,64].map(function(v){return["Int","Uint","Float"].map(function(P){return P+v+"Array"})}))).filter(function(v){return o[v]}),N=new Set(ae.map(function(v){return o[v]})),U=null;function ne(v){return U=new WeakMap,v=function P(j){if(!j||typeof j!="object")return j;var V=U.get(j);if(V)return V;if(u(j)){V=[],U.set(j,V);for(var re=0,pe=j.length;re<pe;++re)V.push(P(j[re]))}else if(N.has(j.constructor))V=j;else{var Te,Ne=d(j);for(Te in V=Ne===Object.prototype?{}:Object.create(Ne),U.set(j,V),j)m(j,Te)&&(V[Te]=P(j[Te]))}return V}(v),U=null,v}var me={}.toString;function xe(v){return me.call(v).slice(8,-1)}var Ce=typeof Symbol<"u"?Symbol.iterator:"@@iterator",le=typeof Ce=="symbol"?function(v){var P;return v!=null&&(P=v[Ce])&&P.apply(v)}:function(){return null};function ce(v,P){P=v.indexOf(P),0<=P&&v.splice(P,1)}var K={};function Y(v){var P,j,V,re;if(arguments.length===1){if(u(v))return v.slice();if(this===K&&typeof v=="string")return[v];if(re=le(v))for(j=[];!(V=re.next()).done;)j.push(V.value);else{if(v==null)return[v];if(typeof(P=v.length)!="number")return[v];for(j=new Array(P);P--;)j[P]=v[P]}}else for(P=arguments.length,j=new Array(P);P--;)j[P]=arguments[P];return j}var he=typeof Symbol<"u"?function(v){return v[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ae=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],oe=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ae),q={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function M(v,P){this.name=v,this.message=P}function J(v,P){return v+". Errors: "+Object.keys(P).map(function(j){return P[j].toString()}).filter(function(j,V,re){return re.indexOf(j)===V}).join(`
11
+ `).map(r=>JSON.parse(r))}applyDeltaIfNeeded(e,r){let n,i,o,a;if(e.delta){a=!0;const u=new TextEncoder().encode(e.data),f=cE(r,u);n=JSON.parse(new TextDecoder().decode(f)),i=f,o=u.length}else a=!1,n=JSON.parse(e.data),i=new TextEncoder().encode(e.data),o=i.length;return{newData:n,newPrevValue:i,isDelta:a,wireBytes:o,fullBytes:i.length}}}const uE={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class Oi extends Error{constructor(e){super(e),this.name=this.constructor.name}}class Ul extends Wy{constructor(e,r){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=Mr.Disconnected,this._transportIsOpen=!1,this._endpoint=e,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new Hy,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},uE),r),this._configure(),this._debugEnabled?(this.on("state",n=>{this._debug("client state",n.oldState,"->",n.newState)}),this.on("error",n=>{this._debug("client error",n)})):this.on("error",function(){Function.prototype()})}newSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new ZT(this,e,r);return this._subs[e]=n,n}newMapSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qf(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapClientsSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qf(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newMapUsersSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new qf(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,tagsFilter:r==null?void 0:r.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:r==null?void 0:r.pageSize,mapUnrecoverableStrategy:r==null?void 0:r.unrecoverableStrategy});return this._subs[e]=n,n}newSharedPollSubscription(e,r){if(this.getSubscription(e)!==null)throw new Error("Subscription to the channel "+e+" already exists");const n=new eE(this,e,{token:r==null?void 0:r.token,getToken:r==null?void 0:r.getToken,data:r==null?void 0:r.data,minResubscribeDelay:r==null?void 0:r.minResubscribeDelay,maxResubscribeDelay:r==null?void 0:r.maxResubscribeDelay,delta:r==null?void 0:r.delta,sharedPoll:!0,sharedPollGetSignature:r==null?void 0:r.getSignature});return this._subs[e]=n,n}getSubscription(e){return this._getSub(e)}getMapSubscription(e){return this._getSub(e)}getSharedPollSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==pn.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}removeMapSubscription(e){this.removeSubscription(e)}removeSharedPollSubscription(e){this.removeSubscription(e)}subscriptions(){return this._subs}mapSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="map"&&(e[r]=n);return e}sharedPollSubscriptions(){const e={};for(const[r,n]of Object.entries(this._subs))n.type==="shared_poll"&&(e[r]=n);return e}ready(e){return jr(this,void 0,void 0,function*(){switch(this.state){case Mr.Disconnected:throw{code:pr.clientDisconnected,message:"client disconnected"};case Mr.Connected:return;default:return new Promise((r,n)=>{const i={resolve:r,reject:n};e&&(i.timeout=setTimeout(()=>{n({code:pr.timeout,message:"timeout"})},e)),this._promises[this._nextPromiseId()]=i})}})}connect(){if(this._isConnected()){this._debug("connect called when already connected");return}if(this._isConnecting()){this._debug("connect called when already connecting");return}this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting()}disconnect(){this._disconnect(Ka.disconnectCalled,"disconnect called",!1)}setToken(e){this._token=e}setData(e){this._data=e}setHeaders(e){this._config.headers=e}send(e){return jr(this,void 0,void 0,function*(){const r={send:{data:e}};if(yield this._methodCall(),!this._transportSendCommands([r]))throw this._createErrorObject(pr.transportWriteError,"transport write error")})}rpc(e,r){return jr(this,void 0,void 0,function*(){const n={rpc:{method:e,data:r}};return yield this._methodCall(),{data:(yield this._callPromise(n,o=>o.rpc)).data}})}publish(e,r){return jr(this,void 0,void 0,function*(){const n={publish:{channel:e,data:r}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}mapPublish(e,r,n){return jr(this,void 0,void 0,function*(){const i={publish:{channel:e,type:1,key:r,data:n}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapRemove(e,r){return jr(this,void 0,void 0,function*(){const n={publish:{channel:e,type:1,key:r,removed:!0}};return yield this._methodCall(),yield this._callPromise(n,()=>({})),{}})}history(e,r){return jr(this,void 0,void 0,function*(){const n={history:this._getHistoryRequest(e,r)};yield this._methodCall();const i=yield this._callPromise(n,a=>a.history),o=[];if(i.publications)for(let a=0;a<i.publications.length;a++)o.push(this._getPublicationContext(e,i.publications[a]));return{publications:o,epoch:i.epoch||"",offset:i.offset||0}})}presence(e){return jr(this,void 0,void 0,function*(){const r={presence:{channel:e}};yield this._methodCall();const i=(yield this._callPromise(r,o=>o.presence)).presence;for(const o in i)if(Object.prototype.hasOwnProperty.call(i,o)){const a=i[o],u=a.conn_info,f=a.chan_info;u&&(a.connInfo=u),f&&(a.chanInfo=f)}return{clients:i}})}presenceStats(e){return jr(this,void 0,void 0,function*(){const r={presence_stats:{channel:e}};yield this._methodCall();const n=yield this._callPromise(r,i=>i.presence_stats);return{numUsers:n.num_users,numClients:n.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const e=this;Promise.resolve().then(function(){Promise.resolve().then(function(){e._batching=!1,e._flush()})})}_debug(...e){this._debugEnabled&&JT("debug",e)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(this._config.token!==null&&(this._token=this._config.token),this._config.data!==null&&(this._data=this._config.data),this._codec=new Hy,this._formatOverride(),(this._config.debug===!0||QT("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),typeof this._endpoint!="string")if(Array.isArray(this._endpoint)){this._transports=this._endpoint,this._emulation=!0;for(const e in this._transports)if(this._transports.hasOwnProperty(e)){const r=this._transports[e];if(!r.endpoint||!r.transport)throw new Error("malformed transport configuration");const n=r.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(n)<0)throw new Error("unsupported transport name: "+n)}}else throw new Error("unsupported url configuration type: only string or array of objects are supported")}_setState(e){if(this.state!==e){this._reconnecting=!1;const r=this.state;return this.state=e,this.emit("state",{newState:e,oldState:r}),!0}return!1}_isDisconnected(){return this.state===Mr.Disconnected}_isConnecting(){return this.state===Mr.Connecting}_isConnected(){return this.state===Mr.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let e=null;this._config.networkEventTarget!==null?e=this._config.networkEventTarget:typeof globalThis.addEventListener<"u"&&(e=globalThis),e&&(e.addEventListener("offline",()=>{this._debug("offline event triggered"),(this.state===Mr.Connected||this.state===Mr.Connecting)&&(this._disconnect(Ii.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),e.addEventListener("online",()=>{this._debug("online event triggered"),this.state===Mr.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const e=ua(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(const e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){const r=this._callbacks[e];clearTimeout(r.timeout);const n=r.errback;if(!n)continue;n({error:this._createErrorObject(pr.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const r=this._subs[e];r.state===pn.Subscribed&&r._setSubscribing($l.transportClosed,"transport closed")}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&this.emit("subscribing",{channel:e})}_handleWriteError(e){for(const r of e){const n=r.id;if(!(n in this._callbacks))continue;const i=this._callbacks[n];clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n];const o=i.errback;o({error:this._createErrorObject(pr.transportWriteError,"transport write error")})}}_transportSendCommands(e){if(!e.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(r){return this._debug("error writing commands",r),this._handleWriteError(e),!1}return!0}_advanceTransportIndex(){this._currentTransportIndex++,this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0)}_initializeTransport(){let e;this._config.websocket!==null?e=this._config.websocket:typeof globalThis.WebSocket!="function"&&typeof globalThis.WebSocket!="object"||(e=globalThis.WebSocket);let r=null;this._config.sockjs!==null?r=this._config.sockjs:typeof globalThis.SockJS<"u"&&(r=globalThis.SockJS);let n=null;this._config.eventsource!==null?n=this._config.eventsource:typeof globalThis.EventSource<"u"&&(n=globalThis.EventSource);let i=null;this._config.fetch!==null?i=this._config.fetch:typeof globalThis.fetch<"u"&&(i=globalThis.fetch);let o=null;if(this._config.readableStream!==null?o=this._config.readableStream:typeof globalThis.ReadableStream<"u"&&(o=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let S=0;for(;;){if(S>=this._transports.length)throw new Error("no supported transport found");const O=this._transports[this._currentTransportIndex],x=O.transport,w=O.endpoint;if(x==="websocket"){if(this._debug("trying websocket transport"),this._transport=new Gy(w,{websocket:e}),!this._transport.supported()){this._debug("websocket transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="webtransport"){if(this._debug("trying webtransport transport"),this._transport=new sE(w,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="http_stream"){if(this._debug("trying http_stream transport"),this._transport=new rE(w,{fetch:i,readableStream:o,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="sse"){if(this._debug("trying sse transport"),this._transport=new nE(w,{eventsource:n,fetch:i,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._advanceTransportIndex(),S++;continue}}else if(x==="sockjs"){if(this._debug("trying sockjs"),this._transport=new tE(w,{sockjs:r,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._advanceTransportIndex(),S++;continue}}else throw new Error("unknown transport "+x);break}}else{if(zT(this._endpoint,"http"))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new Gy(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}const a=this,u=this._transport,f=this._nextTransportId();a._debug("id of transport",f);let d=!1;const h=[];if(this._transport.emulation()){const S=a._sendConnect(!0);h.push(S)}this._setNetworkEvents();const m=this._codec.encodeCommands(h);this._transportClosed=!1;let b;b=setTimeout(function(){u.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(b&&(clearTimeout(b),b=null),a._transportId!=f){a._debug("open callback from non-actual transport"),u.close();return}d=!0,a._debug(u.subName(),"transport open"),!u.emulation()&&(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(S){if(a._transportId!=f){a._debug("error callback from non-actual transport");return}a._debug("transport level error",S)},onClose:function(S){if(b&&(clearTimeout(b),b=null),a._transportId!=f){a._debug("close callback from non-actual transport");return}a._debug(u.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let O="connection closed",x=!0,w=0;if(S&&"code"in S&&S.code&&(w=S.code),S&&S.reason)try{const C=JSON.parse(S.reason);O=C.reason,x=C.reconnect}catch{O=S.reason,(w>=3500&&w<4e3||w>=4500&&w<5e3)&&(x=!1)}w<3e3?(w===1009?(w=Ka.messageSizeLimit,O="message size limit exceeded",x=!1):(w=Ii.transportClosed,O="transport closed"),a._emulation&&!a._transportWasOpen&&a._advanceTransportIndex()):a._transportWasOpen=!0,a._isConnecting()&&!d&&a.emit("error",{type:"transport",error:{code:pr.transportClosed,message:"transport closed"},transport:u.name()}),a._reconnecting=!1,a._disconnect(w,O,x)},onMessage:function(S){a._dataReceived(S)}},m),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(e){const r=this._constructConnectCommand(),n=this;return this._call(r,e).then(i=>{const o=i.reply.connect;n._connectResponse(o),i.next&&i.next()},i=>{n._connectError(i.error),i.next&&i.next()}),r}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting()){this._debug("stop reconnecting: client not in connecting state");return}if(this._reconnecting){this._debug("reconnect already in progress, return from reconnect routine");return}if(this._transportClosed===!1){this._debug("waiting for transport close");return}this._reconnecting=!0;const e=this._token==="";if(!(this._refreshRequired||e&&this._config.getToken!==null)){this._config.getData?this._config.getData().then(i=>{this._isConnecting()&&(this._data=i,this._initializeTransport())}).catch(i=>this._handleGetDataError(i)):this._initializeTransport();return}const n=this;this._getToken().then(function(i){if(n._isConnecting()){if(i==null||i==null){n._failUnauthorized();return}n._token=i,n._debug("connection token refreshed"),n._config.getData?n._config.getData().then(function(o){n._isConnecting()&&(n._data=o,n._initializeTransport())}).catch(o=>n._handleGetDataError(o)):n._initializeTransport()}}).catch(function(i){if(!n._isConnecting())return;if(i instanceof Oi){n._failUnauthorized();return}n.emit("error",{type:"connectToken",error:{code:pr.clientConnectToken,message:i!==void 0?i.toString():""}});const o=n._getReconnectDelay();n._debug("error on getting connection token, reconnect after "+o+" milliseconds",i),n._reconnecting=!1,n._reconnectTimeout=setTimeout(()=>{n._startReconnecting()},o)})}_handleGetDataError(e){if(e instanceof Oi){this._failUnauthorized();return}this.emit("error",{type:"connectData",error:{code:pr.badConfiguration,message:(e==null?void 0:e.toString())||""}});const r=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+r+" milliseconds",e),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_connectError(e){this.state===Mr.Connecting&&(e.code===109&&(this._refreshRequired=!0),e.code<100||e.temporary===!0||e.code===109?(this.emit("error",{type:"connect",error:e}),this._debug("closing transport due to connect error"),this._disconnect(e.code,e.message,!0)):this._disconnect(e.code,e.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let e=!1;this._emulation&&!this._transportWasOpen&&!this._triedAllTransports&&(e=!0);let r=this._getReconnectDelay();e&&(r=0),this._debug("reconnect after "+r+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},r)}_constructConnectCommand(){const e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version),Object.keys(this._config.headers).length>0&&(e.headers=this._config.headers);const r={};let n=!1;for(const i in this._serverSubs)if(this._serverSubs.hasOwnProperty(i)&&this._serverSubs[i].recoverable){n=!0;const o={recover:!0};this._serverSubs[i].offset&&(o.offset=this._serverSubs[i].offset),this._serverSubs[i].epoch&&(o.epoch=this._serverSubs[i].epoch),r[i]=o}return n&&(e.subs=r),{connect:e}}_getHistoryRequest(e,r){const n={channel:e};return r!==void 0&&(r.since&&(n.since={offset:r.since.offset},r.since.epoch&&(n.since.epoch=r.since.epoch)),r.limit!==void 0&&(n.limit=r.limit),r.reverse===!0&&(n.reverse=!0)),n}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((e,r)=>{const n=setTimeout(function(){r({code:pr.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:n,resolve:e,reject:r}})}_callPromise(e,r){return new Promise((n,i)=>{this._call(e,!1).then(o=>{var a;const u=r(o.reply);n(u),(a=o.next)===null||a===void 0||a.call(o)},o=>{var a;i(o.error),(a=o.next)===null||a===void 0||a.call(o)})})}_dataReceived(e){this._serverPing>0&&this._waitServerPing();const r=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then(()=>{let n;this._dispatchPromise=new Promise(i=>{n=i}),this._dispatchSynchronized(r,n)})}_dispatchSynchronized(e,r){let n=Promise.resolve();for(const i in e)e.hasOwnProperty(i)&&(n=n.then(()=>this._dispatchReply(e[i])));n.then(()=>{r()})}_dispatchReply(e){let r;const n=new Promise(o=>{r=o});if(e==null)return this._debug("dispatch: got undefined or null reply"),r(),n;const i=e.id;return i&&i>0?this._handleReply(e,r):e.push?this._handlePush(e.push,r):this._handleServerPing(r),n}_call(e,r){return new Promise((n,i)=>{e.id=this._nextCommandId(),this._registerCall(e.id,n,i),r||this._addCommand(e)})}_startConnecting(){this._debug("start connecting"),this._setState(Mr.Connecting)&&this.emit("connecting",{code:Ii.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(e,r,n){if(e===Ka.stateInvalidated){this._token="",this._refreshRequired=!0;for(const u in this._subs)this._subs.hasOwnProperty(u)&&this._subs[u]._invalidateState();for(const u in this._serverSubs)this._serverSubs.hasOwnProperty(u)&&(this._serverSubs[u].offset=0,this._serverSubs[u].epoch="_")}if(this._isDisconnected())return;this._transportIsOpen=!1;const i=this.state;this._reconnecting=!1;const o={code:e,reason:r};let a;if(n?a=this._setState(Mr.Connecting):(a=this._setState(Mr.Disconnected),this._rejectPromises({code:pr.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),i===Mr.Connecting&&this._clearReconnectTimeout(),i===Mr.Connected&&this._clearConnectedState(),a&&(this._isConnecting()?this.emit("connecting",o):this.emit("disconnected",o)),this._transport){this._debug("closing existing transport");const u=this._transport;this._transport=null,u.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Ka.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:pr.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new Oi("")))}_refresh(){const e=this._client,r=this;this._getToken().then(function(n){if(e!==r._client)return;if(!n){r._failUnauthorized();return}if(r._token=n,r._debug("connection token refreshed"),!r._isConnected())return;const i={refresh:{token:r._token}};r._call(i,!1).then(o=>{const a=o.reply.refresh;r._refreshResponse(a),o.next&&o.next()},o=>{r._refreshError(o.error),o.next&&o.next()})}).catch(function(n){if(r._isConnected()){if(n instanceof Oi){r._failUnauthorized();return}r.emit("error",{type:"refreshToken",error:{code:pr.clientRefreshToken,message:n!==void 0?n.toString():""}}),r._refreshTimeout=setTimeout(()=>r._refresh(),r._getRefreshRetryDelay())}})}_refreshError(e){e.code<100||e.temporary===!0?(this.emit("error",{type:"refresh",error:e}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,!1)}_getRefreshRetryDelay(){return ua(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout(()=>this._refresh(),jo(e.ttl)))}_removeSubscription(e){e!==null&&delete this._subs[e.channel]}_unsubscribe(e){if(!this._transportIsOpen)return Promise.resolve();const n={unsubscribe:{channel:e.channel}},i=this;return new Promise((a,u)=>{this._call(n,!1).then(f=>{a(),f.next&&f.next()},f=>{a(),f.next&&f.next(),i._disconnect(Ii.unsubscribeError,"unsubscribe error",!0)})})}_getSub(e,r){if(r&&r>0){for(const i in this._subs)if(this._subs.hasOwnProperty(i)){const o=this._subs[i];if(o._id===r)return o}return null}const n=this._subs[e];return n||null}_isServerSub(e){return this._serverSubs[e]!==void 0}_sendSubscribeCommands(){const e=[];for(const r in this._subs){if(!this._subs.hasOwnProperty(r))continue;const n=this._subs[r];if(n._inflight!==!0&&n.state===pn.Subscribing){const i=n._subscribe();i&&e.push(i)}}return e}_connectResponse(e){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=e.client,this._setState(Mr.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),jo(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const r={client:e.client,transport:this._transport.subName()};e.data&&(r.data=e.data),this.emit("connected",r),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=e.ping*1e3,this._sendPong=e.pong===!0,this._waitServerPing()):this._serverPing=0}_processServerSubs(e){for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];this._serverSubs[r]={offset:n.offset,epoch:n.epoch,recoverable:n.recoverable||!1};const i=this._getSubscribeContext(r,n);this.emit("subscribed",i)}for(const r in e){if(!e.hasOwnProperty(r))continue;const n=e[r];if(n.recovered){const i=n.publications;if(i&&i.length>0)for(const o in i)i.hasOwnProperty(o)&&this._handlePublication(r,i[o])}}for(const r in this._serverSubs)this._serverSubs.hasOwnProperty(r)&&(e[r]||(this.emit("unsubscribed",{channel:r}),delete this._serverSubs[r]))}_clearRefreshTimeout(){this._refreshTimeout!==null&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){this._reconnectTimeout!==null&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){this._serverPingTimeout!==null&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){this._config.maxServerPingDelay!==0&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Ii.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,r){const n={channel:e,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};r.recovered&&(n.recovered=!0),r.positioned&&(n.positioned=!0),r.recoverable&&(n.recoverable=!0),r.was_recovering&&(n.wasRecovering=!0);let i="";"epoch"in r&&(i=r.epoch);let o=0;return"offset"in r&&(o=r.offset),(n.positioned||n.recoverable)&&(n.streamPosition={offset:o,epoch:i}),Array.isArray(r.publications)&&r.publications.length>0&&(n.hasRecoveredPublications=!0),r.data&&(n.data=r.data),n}_handleReply(e,r){const n=e.id;if(!(n in this._callbacks)){r();return}const i=this._callbacks[n];if(clearTimeout(this._callbacks[n].timeout),delete this._callbacks[n],XT(e)){const o=i.errback;if(!o){r();return}const a={code:e.error.code,message:e.error.message||"",temporary:e.error.temporary||!1};o({error:a,next:r})}else{const o=i.callback;if(!o)return;o({reply:e,next:r})}}_handleJoin(e,r,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("join",o)}return}i._handleJoin(r)}_handleLeave(e,r,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const o={channel:e,info:this._getJoinLeaveContext(r.info)};this.emit("leave",o)}return}i._handleLeave(r)}_handleUnsubscribe(e,r){const n=this._getSub(e,0);if(!n&&e){this._isServerSub(e)&&(delete this._serverSubs[e],this.emit("unsubscribed",{channel:e}));return}r.code<2500?n._setUnsubscribed(r.code,r.reason,!1):(r.code===Ro.stateInvalidated&&n._invalidateState(),n._setSubscribing(r.code,r.reason))}_handleSubscribe(e,r){this._serverSubs[e]={offset:r.offset,epoch:r.epoch,recoverable:r.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(e,r))}_handleDisconnect(e){const r=e.code;let n=!0;(r>=3500&&r<4e3||r>=4500&&r<5e3)&&(n=!1),this._disconnect(r,e.reason,n)}_getPublicationContext(e,r){const n={channel:e,data:r.data};return r.offset&&(n.offset=r.offset),r.info&&(n.info=this._getJoinLeaveContext(r.info)),r.tags&&(n.tags=r.tags),n}_getJoinLeaveContext(e){const r={client:e.client,user:e.user},n=e.conn_info;n&&(r.connInfo=n);const i=e.chan_info;return i&&(r.chanInfo=i),r}_handlePublication(e,r,n){const i=this._getSub(e,n);if(!i){if(e&&this._isServerSub(e)){const o=this._getPublicationContext(e,r);this.emit("publication",o),r.offset!==void 0&&(this._serverSubs[e].offset=r.offset)}return}i._handlePublication(r)}_handleMessage(e){this.emit("message",{data:e.data})}_handleServerPing(e){if(this._sendPong){const r={};this._transportSendCommands([r])}e()}_handlePush(e,r){const n=e.channel,i=e.id;e.pub?this._handlePublication(n,e.pub,i):e.message?this._handleMessage(e.message):e.join?this._handleJoin(n,e.join,i):e.leave?this._handleLeave(n,e.leave,i):e.unsubscribe?this._handleUnsubscribe(n,e.unsubscribe):e.subscribe?this._handleSubscribe(n,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),r()}_flush(){const e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,r,n){const i={code:e,message:r};return n&&(i.temporary=!0),i}_registerCall(e,r,n){this._callbacks[e]={callback:r,errback:n,timeout:null},this._callbacks[e].timeout=setTimeout(()=>{delete this._callbacks[e],$f(n)&&n({error:this._createErrorObject(pr.timeout,"timeout")})},this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(const r in this._promises)this._promises.hasOwnProperty(r)&&(this._promises[r].timeout&&clearTimeout(this._promises[r].timeout),this._promises[r].reject(e),delete this._promises[r])}}Ul.SubscriptionState=pn,Ul.State=Mr,Ul.UnauthorizedError=Oi;const Ln={SessionList:"v1.session.list",SessionGet:"v1.session.get",SessionClose:"v1.session.close",SessionOpen:"v1.session.open",SessionUpdate:"v1.session.update",SessionFork:"v1.session.fork",SessionCompact:"v1.session.compact",MessageSend:"v1.message.send",MessageList:"v1.message.list",TurnList:"v1.turn.list",TurnStop:"v1.turn.stop",RtcList:"v1.rtc.list",RtcUpdateStatus:"v1.rtc.update_status",RtcSubmitResult:"v1.rtc.submit_result"},zy={debug:0,info:1,warn:2,error:3};let fE="debug";function Bs(t){const e=r=>zy[r]>=zy[fE];return{debug(...r){e("debug")&&console.debug(`[${t}]`,...r)},info(...r){e("info")&&console.info(`[${t}]`,...r)},warn(...r){e("warn")&&console.warn(`[${t}]`,...r)},error(...r){e("error")&&console.error(`[${t}]`,...r)}}}const sr=Bs("RTCAgentClient");class pE extends Error{constructor(e,r,n){super(`Gap fill timeout after ${n}ms: channel=${e}, target=${r}`),this.channel=e,this.targetOffset=r,this.elapsedMs=n,this.name="GapFillTimeoutError"}}const $a=class $a{constructor(e){Bt(this,"options");Bt(this,"centrifuge",null);Bt(this,"connectionState","disconnected");Bt(this,"listeners",new Map);Bt(this,"shouldReconnect",!0);Bt(this,"wasConnected",!1);Bt(this,"applyUpdatesQueue",null);Bt(this,"subscriptions",new Map);Bt(this,"epochCache",new Map);Bt(this,"_reconnectTimer");Bt(this,"gapFillTasks",new Map);Bt(this,"isGapFillProcessing",!1);Bt(this,"_gapFillAbortControllers",new Map);Bt(this,"pendingUpdates",[]);Bt(this,"isUpdateProcessing",!1);Bt(this,"lastOffsetCache",new Map);this.options=e}async connect(){if(sr.debug("connect() called, current state:",this.connectionState),this.connectionState==="connected"||this.connectionState==="connecting"){sr.debug("connect() early return, already",this.connectionState);return}this.shouldReconnect=!0,this.setConnectionState("connecting"),this.centrifuge=new Ul(this.options.endpoint,{getToken:async()=>{var r;const e=await this.options.getToken();if(this._isTokenExpired(e)&&this.options.onTokenExpired){if(await this.options.onTokenExpired()==="relogin")throw this.shouldReconnect=!1,(r=this.centrifuge)==null||r.disconnect(),this.setConnectionState("disconnected","token expired, relogin required"),new Error("Token expired, user needs to re-login");return this.options.getToken()}return e}}),this.centrifuge.on("connecting",e=>{var n;if(!this.shouldReconnect){(n=this.centrifuge)==null||n.disconnect();return}const r=this.wasConnected?"reconnecting":"connecting";this.setConnectionState(r,e==null?void 0:e.reason)}),this.centrifuge.on("connected",()=>{sr.debug("centrifuge connected, setting state to connected"),this.wasConnected=!0,this.setConnectionState("connected"),this.subscribeChannels()}),this.centrifuge.on("disconnected",e=>{if(sr.debug("[GAP_FILL_DEBUG] centrifuge disconnected, reason:",e==null?void 0:e.reason,"| code:",e==null?void 0:e.code,"| wasConnected:",this.wasConnected,"| shouldReconnect:",this.shouldReconnect,"| activeGapFills:",this.gapFillTasks.size),(e==null?void 0:e.reason)==="invalid token"&&this.options.onTokenExpired){const r=this.centrifuge;this.centrifuge=null,r==null||r.disconnect(),this.handleInvalidToken()}(e==null?void 0:e.reason)==="message size limit exceeded"&&(sr.warn("message size limit exceeded, will retry connection after delay"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.connectionState==="disconnected"&&(sr.debug("attempting reconnect after message size limit error"),this.reconnect().catch(r=>{sr.error("reconnect failed:",r)}))},$a.RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS)),this.setConnectionState("disconnected",e==null?void 0:e.reason)}),this.centrifuge.on("error",e=>{var r;sr.error("centrifuge error:",e==null?void 0:e.error),this.emit("error",new Error(((r=e==null?void 0:e.error)==null?void 0:r.message)??"centrifuge error"))}),sr.debug("calling centrifuge.connect() synchronously"),this.centrifuge.connect(),sr.debug("centrifuge.connect() returned, state:",this.connectionState,"(WebSocket not yet established)")}disconnect(){var e;this.shouldReconnect=!1,this.wasConnected=!1,this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=void 0),this._gapFillAbortControllers.forEach(r=>r.abort()),this._gapFillAbortControllers.clear(),this.gapFillTasks.clear(),this.isGapFillProcessing=!1,this.isUpdateProcessing=!1,(e=this.centrifuge)==null||e.disconnect(),this.centrifuge=null,this.subscriptions.clear(),this.pendingUpdates.length=0,this.lastOffsetCache.clear(),this.setConnectionState("disconnected")}async reconnect(){this.disconnect(),await this.connect()}getConnectionState(){return this.connectionState}getUserId(){return this.options.userId}async listSessions(e,r){return this.rpc(Ln.SessionList,{cursor:e,limit:r})}async getSession(e){return this.rpc(Ln.SessionGet,{session_id:e})}async closeSession(e){return this.rpc(Ln.SessionClose,{session_id:e})}async openSession(e){return this.rpc(Ln.SessionOpen,{session_id:e})}async compactSession(e){return this.rpc(Ln.SessionCompact,e)}async updateSession(e){return this.rpc(Ln.SessionUpdate,e)}async sendMessage(e){return this.rpc(Ln.MessageSend,e)}async forkSession(e){return this.rpc(Ln.SessionFork,e)}async stopTurn(e){return this.rpc(Ln.TurnStop,{session_id:e})}async listMessages(e,r,n){return this.rpc(Ln.MessageList,{session_id:e,cursor:r,limit:n})}async listTurns(e,r,n){return this.rpc(Ln.TurnList,{session_id:e,cursor:r,limit:n})}async listRtc(e,r,n){return this.rpc(Ln.RtcList,{session_id:e,cursor:r,limit:n})}async updateRtcStatus(e,r){return this.rpc(Ln.RtcUpdateStatus,{rtc_id:e,status:r})}async submitRtcResult(e,r,n,i){return this.rpc(Ln.RtcSubmitResult,{rtc_id:e,success:r,result:n,error:i})}async applyUpdates(e,r){let n=this.applyUpdatesQueue;const i=(async()=>{if(n&&await n,r)await r();else for(const o of e)await this.processUpdate(o)})();this.applyUpdatesQueue=i;try{await i}finally{this.applyUpdatesQueue===i&&(this.applyUpdatesQueue=null)}}async processUpdate(e){var n,i,o,a,u,f;const r=`topic:u=${this.options.userId}`;if(e.offset>0){const d=await((i=(n=this.options).getLastOffset)==null?void 0:i.call(n,r)),h=d==null?void 0:d.offset,m=(d==null?void 0:d.epoch)??this.epochCache.get(r)??"";if(h!==void 0&&e.offset<=h){sr.debug(`Skipping duplicate/expired message: offset=${e.offset}, lastOffset=${h}`);return}if(h!==void 0&&e.offset>h+1){this.scheduleGapFill(r,e.offset,m),await this.waitForGapFill(r,e.offset-1);const b=await((a=(o=this.options).getLastOffset)==null?void 0:a.call(o,r)),S=b==null?void 0:b.offset,O=b==null?void 0:b.epoch,x=this.epochCache.get(r)??"";if(S===void 0||S!==e.offset-1)throw new Error(`[RTCAgentClient] Offset gap fill failed: expected ${e.offset-1}, got ${S}. Rejecting update ${e.offset} to maintain strict +1 continuity.`);if(O!==void 0&&O!==x)throw new Error(`[RTCAgentClient] Epoch mismatch after gap fill: expected '${x}', got '${O}'. Rejecting update ${e.offset} to prevent data corruption.`)}}if(this.options.onPublication){const d={channel:`topic:u=${this.options.userId}`,offset:e.offset,data:e};await this.options.onPublication(d)}if(e.offset>0){const d=this.epochCache.get(r)??"";await((f=(u=this.options).updateOffset)==null?void 0:f.call(u,r,e.offset,d))}}async waitForGapFill(e,r){var f,d;const o=Date.now(),a=new AbortController,u=`${e}:${r}`;this._gapFillAbortControllers.set(u,a);try{for(;Date.now()-o<3e4;){if(a.signal.aborted)throw new Error(`Gap fill aborted for channel ${e}`);const m=await((d=(f=this.options).getLastOffset)==null?void 0:d.call(f,e));if(((m==null?void 0:m.offset)??0)>=r)return;if(a.signal.aborted)throw new Error(`Gap fill aborted for channel ${e}`);if(!this.gapFillTasks.has(e)&&!this.isGapFillProcessing)return;await new Promise((S,O)=>{const x=setTimeout(S,100);a.signal.addEventListener("abort",()=>{clearTimeout(x),O(new Error(`Gap fill aborted for channel ${e}`))},{once:!0})})}const h=Date.now()-o;throw new pE(e,r,h)}finally{this._gapFillAbortControllers.get(u)===a&&this._gapFillAbortControllers.delete(u)}}on(e,r){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(r),()=>{n.delete(r)}}scheduleUpdate(e){const r=`topic:u=${this.options.userId}`;if(e.offset>0){const n=this.lastOffsetCache.get(r);if(n!==void 0&&e.offset<=n){sr.debug(`scheduleUpdate: skip expired offset=${e.offset}, lastOffset=${n}`);return}}if(e.offset>0&&this.pendingUpdates.some(n=>n.offset===e.offset)){sr.debug(`scheduleUpdate: skip duplicate in buffer offset=${e.offset}`);return}this.pendingUpdates.push(e),this.processUpdateQueue()}async processUpdateQueue(){var e;if(!this.isUpdateProcessing){this.isUpdateProcessing=!0;try{for(;this.pendingUpdates.length>0;){const r=this.pendingUpdates.shift();try{if(await this.applyUpdates([r]),r.offset>0){const n=`topic:u=${this.options.userId}`;this.lastOffsetCache.set(n,r.offset)}}catch(n){sr.error(`processUpdateQueue failed for offset ${r.offset}:`,n),this.emit("error",n instanceof Error?n:new Error(String(n))),this.shouldReconnect&&((e=this.centrifuge)==null||e.disconnect(),this.setConnectionState("disconnected","update processing failed"),this.emit("syncRequired",{reason:"gap_fill_failed",lastKnownOffset:r.offset-1,serverOffset:r.offset}),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.connectionState==="disconnected"&&(sr.debug("attempting reconnect after update processing failure"),this.reconnect().catch(i=>sr.error("reconnect failed:",i)))},$a.RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS));break}}}finally{this.isUpdateProcessing=!1}}}scheduleGapFill(e,r,n){const i=this.gapFillTasks.get(e);i?(i.targetOffset=Math.max(i.targetOffset,r),i.epoch=n,sr.debug(`[GAP_FILL_DEBUG] scheduleGapFill merged: channel=${e}, targetOffset=${i.targetOffset}, isProcessing=${this.isGapFillProcessing}`)):(this.gapFillTasks.set(e,{targetOffset:r,epoch:n}),this.processGapFillQueue())}async processGapFillQueue(){if(!this.isGapFillProcessing){this.isGapFillProcessing=!0;try{for(;this.gapFillTasks.size>0;){const[e,{targetOffset:r,epoch:n}]=this.gapFillTasks.entries().next().value;await this.runGapFill(e,r,n);const i=this.gapFillTasks.get(e);i&&i.targetOffset<=r&&this.gapFillTasks.delete(e)}}finally{this.isGapFillProcessing=!1}}}async runGapFill(e,r,n){var O,x,w,C,T,_,E,D,B,I,R,Z,z;const i=this.subscriptions.get(e);if(!i){sr.warn(`runGapFill: subscription not found for channel ${e}`);return}sr.debug(`[GAP_FILL_DEBUG] runGapFill started: channel=${e}, targetOffset=${r}, connectionState=${this.connectionState}, centrifuge=${!!this.centrifuge}, subState=${i.state}`);const o=10,a=1e4,u=100,f=await((x=(O=this.options).getLastOffset)==null?void 0:x.call(O,e)),d=(f==null?void 0:f.offset)??0,h=r-d;console.log(`[BulkUpdate] runGapFill: gapSize=${h}, threshold=${u}`),h>u&&(console.log("[BulkUpdate] runGapFill: calling onGapFillStart"),(C=(w=this.options).onGapFillStart)==null||C.call(w),(_=(T=this.options).suspendUIUpdates)==null||_.call(T));let m=[],b=[],S=d;try{for(;S<r-1;){for(m=[],b=[];m.length<a&&S<r-1;){const N=r-S-1,U=Math.min(o,N);if(U<=0)break;const ne={since:{offset:S,epoch:n},limit:U,reverse:!1};sr.debug(`[GAP_FILL_DEBUG] Calling sub.history(): offset=${S}, limit=${U}, connectionState=${this.connectionState}, hasCentrifuge=${!!this.centrifuge}, subState=${i.state}`);const xe=(await i.history(ne)).publications;if(xe.length===0)break;const Ce=xe[0].offset??0;if(Ce!==S+1)throw new Error(`Gap fill missing messages: expected first offset ${S+1}, got ${Ce}`);for(let le=1;le<xe.length;le++){const ce=xe[le-1].offset??0,K=xe[le].offset??0;if(K!==ce+1)throw new Error(`Gap fill non-continuous: offset jumped from ${ce} to ${K}`)}for(const le of xe){const ce=le.data,K=le.offset??0;(ce==null?void 0:ce.type)==="gap"?b.push(K):m.push(le.data)}if(S=xe[xe.length-1].offset??S,xe.length<U)break}await this.flushGapFillBuffer(e,m,b,n)}}catch(N){if(m.length>0||b.length>0){sr.debug(`[GAP_FILL_DEBUG] Network error, flushing buffer before error handling: ${m.length} updates, ${b.length} gap offsets`);try{await this.flushGapFillBuffer(e,m,b,n)}catch(U){sr.error("[GAP_FILL_DEBUG] Failed to flush buffer on error:",U)}}sr.error(`[GAP_FILL_DEBUG] runGapFill failed for channel ${e}:`,N,`| connectionState=${this.connectionState}`,`| hasCentrifuge=${!!this.centrifuge}`,`| targetOffset=${r}`,`| epoch=${n}`),this.emit("error",N instanceof Error?N:new Error(String(N))),this.emit("syncRequired",{reason:"gap_fill_failed",lastKnownOffset:(B=await((D=(E=this.options).getLastOffset)==null?void 0:D.call(E,e)))==null?void 0:B.offset,serverOffset:r})}finally{h>u&&(console.log("[BulkUpdate] runGapFill: calling resumeUIUpdates and onGapFillEnd"),(R=(I=this.options).resumeUIUpdates)==null||R.call(I),(z=(Z=this.options).onGapFillEnd)==null||z.call(Z))}}deduplicateUpdates(e){var o;const r=new Map;for(const a of e)for(let u=0;u<a.items.length;u++){const f=a.items[u],d=(o=a.data_list)==null?void 0:o[u];if(!d)continue;const h=`${f.entity}:${f.entity_id}`,m=r.get(h);m?(a.offset>m.last.offset&&(m.last={item:f,data:d,offset:a.offset}),a.offset<m.first.offset&&(m.first={item:f,data:d,offset:a.offset})):r.set(h,{first:{item:f,data:d,offset:a.offset},last:{item:f,data:d,offset:a.offset}})}const n=[];for(const{first:a,last:u}of r.values())n.push({id:"",items:[a.item],data_list:[a.data],offset:a.offset}),u.offset!==a.offset&&n.push({id:"",items:[u.item],data_list:[u.data],offset:u.offset});return n.sort((a,u)=>a.offset-u.offset)}async flushGapFillBuffer(e,r,n,i){var o,a,u,f,d,h,m,b;if(r.length>0){const S=this.deduplicateUpdates(r);(a=(o=this.options).suspendUIUpdates)==null||a.call(o);try{if(this.options.onPublications){const w=S.map(C=>({channel:e,offset:C.offset,data:C}));await this.options.onPublications(w)}else for(const w of S)if(this.options.onPublication){const C={channel:e,offset:w.offset,data:w};await this.options.onPublication(C)}const O=[...n,...r.map(w=>w.offset)],x=Math.max(...O);await((f=(u=this.options).updateOffset)==null?void 0:f.call(u,e,x,i))}finally{(h=(d=this.options).resumeUIUpdates)==null||h.call(d)}}else if(n.length>0){const S=Math.max(...n);await((b=(m=this.options).updateOffset)==null?void 0:b.call(m,e,S,i))}}emit(e,r){const n=this.listeners.get(e);if(n)for(const i of n)try{i(r)}catch(o){sr.error(`listener for '${e}' threw:`,o)}}setConnectionState(e,r){var i,o;if(sr.debug("[GAP_FILL_DEBUG] setConnectionState:",e,"reason:",r,"| previous:",this.connectionState,"| timestamp:",new Date().toISOString()),this.connectionState===e)return;this.connectionState=e;const n={state:e,reason:r};this.emit("connection",n),(o=(i=this.options).onConnectionStateChange)==null||o.call(i,n)}async handleInvalidToken(){var e;if(!this.options.onTokenExpired){sr.warn("invalid token but no onTokenExpired callback provided");return}try{await this.options.onTokenExpired()==="relogin"?(this.shouldReconnect=!1,(e=this.centrifuge)==null||e.disconnect(),this.setConnectionState("disconnected","token expired, relogin required")):(sr.debug("token refreshed, attempting to reconnect"),this._reconnectTimer=setTimeout(()=>{this._reconnectTimer=void 0,this.shouldReconnect&&this.reconnect().catch(n=>{sr.error("reconnect after token refresh failed:",n)})},$a.RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS))}catch(r){sr.error("handleInvalidToken failed:",r)}}_isTokenExpired(e){try{const r=e.split(".");if(r.length!==3)return sr.debug("_isTokenExpired: token does not have 3 parts, treating as not expired"),!1;const n=JSON.parse(atob(r[1]));if(typeof n.exp!="number")return sr.debug("_isTokenExpired: payload.exp is not a number, treating as not expired"),!1;const i=n.exp*1e3<Date.now();return sr.debug("_isTokenExpired: exp=",n.exp,"expired=",i),i}catch(r){return sr.debug("_isTokenExpired: failed to parse JWT, treating as not expired:",r),!1}}async rpc(e,r){if(!this.centrifuge)throw new Error("RTCAgentClient not connected");if(this.connectionState!=="connected")throw new Error(`Cannot call RPC '${e}': connection state is ${this.connectionState}`);try{return(await this.centrifuge.rpc(e,r)).data}catch(n){throw sr.error(`RPC '${e}' failed:`,n),n}}subscribeChannels(){var i,o;if(!this.centrifuge||!this.options.userId)return;const e=this.options.userId,r=`topic:u=${e}`;if(!this.subscriptions.has(r)){const a=this.centrifuge.newSubscription(r);this.subscriptions.set(r,a),a.on("publication",u=>{this.scheduleUpdate(u.data)}),a.on("subscribed",async u=>{var f,d,h,m,b,S,O,x;if(sr.debug(`[GAP_FILL_DEBUG] Subscription 'subscribed' event: channel=${r}, serverOffset=${(f=u.streamPosition)==null?void 0:f.offset}, epoch=${(d=u.streamPosition)==null?void 0:d.epoch}, connectionState=${this.connectionState}`),u.streamPosition){const w=u.streamPosition.epoch,C=u.streamPosition.offset;this.epochCache.set(r,w);const T=await((m=(h=this.options).getLastOffset)==null?void 0:m.call(h,r));let _;T&&T.epoch!==w?(sr.warn(`Epoch changed: '${T.epoch}' -> '${w}', resetting offset to 0`),await((S=(b=this.options).updateOffset)==null?void 0:S.call(b,r,0,w)),_=0):_=T==null?void 0:T.offset,_===void 0?(await((x=(O=this.options).updateOffset)==null?void 0:x.call(O,r,C,w)),_=C):C<=_||this.scheduleGapFill(r,C+1,w),_!==void 0&&this.lastOffsetCache.set(r,_)}})}(i=this.subscriptions.get(r))==null||i.subscribe();const n=`live:u=${e}`;if(!this.subscriptions.has(n)){const a=this.centrifuge.newSubscription(n);this.subscriptions.set(n,a),a.on("publication",u=>{const f={channel:n,data:u.data};this.handlePublication(f,a)})}(o=this.subscriptions.get(n))==null||o.subscribe()}async handlePublication(e,r){if(this.options.onPublication)try{await this.options.onPublication(e)}catch(n){throw sr.error(`onPublication threw for channel '${e.channel}':`,n),r.unsubscribe(),n}}};Bt($a,"RECONNECT_AFTER_SIZE_LIMIT_DELAY_MS",3e3),Bt($a,"RECONNECT_AFTER_TOKEN_REFRESH_DELAY_MS",1e3);let Vf=$a;var Rs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dE(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Jy={exports:{}};(function(t,e){((r,n)=>{t.exports=n()})(Rs,function(){var r=function(v,P){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(j,V){j.__proto__=V}:function(j,V){for(var re in V)Object.prototype.hasOwnProperty.call(V,re)&&(j[re]=V[re])}))(v,P)},n=function(){return(n=Object.assign||function(v){for(var P,j=1,V=arguments.length;j<V;j++)for(var re in P=arguments[j])Object.prototype.hasOwnProperty.call(P,re)&&(v[re]=P[re]);return v}).apply(this,arguments)};function i(v,P,j){for(var V,re=0,pe=P.length;re<pe;re++)!V&&re in P||((V=V||Array.prototype.slice.call(P,0,re))[re]=P[re]);return v.concat(V||Array.prototype.slice.call(P))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Rs,a=Object.keys,u=Array.isArray;function f(v,P){return typeof P=="object"&&a(P).forEach(function(j){v[j]=P[j]}),v}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var d=Object.getPrototypeOf,h={}.hasOwnProperty;function m(v,P){return h.call(v,P)}function b(v,P){typeof P=="function"&&(P=P(d(v))),(typeof Reflect>"u"?a:Reflect.ownKeys)(P).forEach(function(j){O(v,j,P[j])})}var S=Object.defineProperty;function O(v,P,j,V){S(v,P,f(j&&m(j,"get")&&typeof j.get=="function"?{get:j.get,set:j.set,configurable:!0}:{value:j,configurable:!0,writable:!0},V))}function x(v){return{from:function(P){return v.prototype=Object.create(P.prototype),O(v.prototype,"constructor",v),{extend:b.bind(null,v.prototype)}}}}var w=Object.getOwnPropertyDescriptor,C=[].slice;function T(v,P,j){return C.call(v,P,j)}function _(v,P){return P(v)}function E(v){if(!v)throw new Error("Assertion Failed")}function D(v){o.setImmediate?setImmediate(v):setTimeout(v,0)}function B(v,P){if(typeof P=="string"&&m(v,P))return v[P];if(!P)return v;if(typeof P!="string"){for(var j=[],V=0,re=P.length;V<re;++V){var pe=B(v,P[V]);j.push(pe)}return j}var Te,Ne=P.indexOf(".");return Ne===-1||(Te=v[P.substr(0,Ne)])==null?void 0:B(Te,P.substr(Ne+1))}function I(v,P,j){if(v&&P!==void 0&&!("isFrozen"in Object&&Object.isFrozen(v)))if(typeof P!="string"&&"length"in P){E(typeof j!="string"&&"length"in j);for(var V=0,re=P.length;V<re;++V)I(v,P[V],j[V])}else{var pe=P.indexOf(".");if(pe!==-1){var Te=P.substr(0,pe),pe=P.substr(pe+1);if(pe==="")j===void 0?u(v)&&!isNaN(parseInt(Te))?v.splice(Te,1):delete v[Te]:v[Te]=j;else{var Ne=v[Te];if(!Ne||!m(v,Te)){if(j===void 0)return;Ne=v[Te]={}}I(Ne,pe,j)}}else j===void 0?u(v)&&!isNaN(parseInt(P))?v.splice(P,1):delete v[P]:v[P]=j}}function R(v){var P,j={};for(P in v)m(v,P)&&(j[P]=v[P]);return j}var Z=[].concat;function z(v){return Z.apply([],v)}var ae="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(z([8,16,32,64].map(function(v){return["Int","Uint","Float"].map(function(P){return P+v+"Array"})}))).filter(function(v){return o[v]}),N=new Set(ae.map(function(v){return o[v]})),U=null;function ne(v){return U=new WeakMap,v=function P(j){if(!j||typeof j!="object")return j;var V=U.get(j);if(V)return V;if(u(j)){V=[],U.set(j,V);for(var re=0,pe=j.length;re<pe;++re)V.push(P(j[re]))}else if(N.has(j.constructor))V=j;else{var Te,Ne=d(j);for(Te in V=Ne===Object.prototype?{}:Object.create(Ne),U.set(j,V),j)m(j,Te)&&(V[Te]=P(j[Te]))}return V}(v),U=null,v}var me={}.toString;function xe(v){return me.call(v).slice(8,-1)}var Ce=typeof Symbol<"u"?Symbol.iterator:"@@iterator",le=typeof Ce=="symbol"?function(v){var P;return v!=null&&(P=v[Ce])&&P.apply(v)}:function(){return null};function ce(v,P){P=v.indexOf(P),0<=P&&v.splice(P,1)}var K={};function Y(v){var P,j,V,re;if(arguments.length===1){if(u(v))return v.slice();if(this===K&&typeof v=="string")return[v];if(re=le(v))for(j=[];!(V=re.next()).done;)j.push(V.value);else{if(v==null)return[v];if(typeof(P=v.length)!="number")return[v];for(j=new Array(P);P--;)j[P]=v[P]}}else for(P=arguments.length,j=new Array(P);P--;)j[P]=arguments[P];return j}var he=typeof Symbol<"u"?function(v){return v[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ae=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],oe=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ae),q={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function M(v,P){this.name=v,this.message=P}function J(v,P){return v+". Errors: "+Object.keys(P).map(function(j){return P[j].toString()}).filter(function(j,V,re){return re.indexOf(j)===V}).join(`
12
12
  `)}function ye(v,P,j,V){this.failures=P,this.failedKeys=V,this.successCount=j,this.message=J(v,P)}function Ie(v,P){this.name="BulkError",this.failures=Object.keys(P).map(function(j){return P[j]}),this.failuresByPos=P,this.message=J(v,this.failures)}x(M).from(Error).extend({toString:function(){return this.name+": "+this.message}}),x(ye).from(M),x(Ie).from(M);var Ee=oe.reduce(function(v,P){return v[P]=P+"Error",v},{}),De=M,je=oe.reduce(function(v,P){var j=P+"Error";function V(re,pe){this.name=j,re?typeof re=="string"?(this.message="".concat(re).concat(pe?`
13
13
  `+pe:""),this.inner=pe||null):typeof re=="object"&&(this.message="".concat(re.name," ").concat(re.message),this.inner=re):(this.message=q[P]||j,this.inner=null)}return x(V).from(De),v[P]=V,v},{}),Ve=(je.Syntax=SyntaxError,je.Type=TypeError,je.Range=RangeError,ae.reduce(function(v,P){return v[P+"Error"]=je[P],v},{}));ae=oe.reduce(function(v,P){return["Syntax","Type","Range"].indexOf(P)===-1&&(v[P+"Error"]=je[P]),v},{});function Ze(){}function ut(v){return v}function it(v,P){return v==null||v===ut?P:function(j){return P(v(j))}}function dt(v,P){return function(){v.apply(this,arguments),P.apply(this,arguments)}}function Ue(v,P){return v===Ze?P:function(){var j=v.apply(this,arguments),V=(j!==void 0&&(arguments[0]=j),this.onsuccess),re=this.onerror,pe=(this.onsuccess=null,this.onerror=null,P.apply(this,arguments));return V&&(this.onsuccess=this.onsuccess?dt(V,this.onsuccess):V),re&&(this.onerror=this.onerror?dt(re,this.onerror):re),pe!==void 0?pe:j}}function Le(v,P){return v===Ze?P:function(){v.apply(this,arguments);var j=this.onsuccess,V=this.onerror;this.onsuccess=this.onerror=null,P.apply(this,arguments),j&&(this.onsuccess=this.onsuccess?dt(j,this.onsuccess):j),V&&(this.onerror=this.onerror?dt(V,this.onerror):V)}}function $e(v,P){return v===Ze?P:function(re){var V=v.apply(this,arguments),re=(f(re,V),this.onsuccess),pe=this.onerror,Te=(this.onsuccess=null,this.onerror=null,P.apply(this,arguments));return re&&(this.onsuccess=this.onsuccess?dt(re,this.onsuccess):re),pe&&(this.onerror=this.onerror?dt(pe,this.onerror):pe),V===void 0?Te===void 0?void 0:Te:f(V,Te)}}function Me(v,P){return v===Ze?P:function(){return P.apply(this,arguments)!==!1&&v.apply(this,arguments)}}function gt(v,P){return v===Ze?P:function(){var j=v.apply(this,arguments);if(j&&typeof j.then=="function"){for(var V=this,re=arguments.length,pe=new Array(re);re--;)pe[re]=arguments[re];return j.then(function(){return P.apply(V,pe)})}return P.apply(this,arguments)}}ae.ModifyError=ye,ae.DexieError=M,ae.BulkError=Ie;var ht=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function _e(v){ht=v}var Se={},ie=100,ee=typeof Promise>"u"?[]:(oe=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[ee=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(ee),oe]:[oe,d(oe),oe]),oe=ee[0],Bn=ee[1],Bn=Bn&&Bn.then,W=oe&&oe.constructor,fe=!!ee[2],Re=function(v,P){te.push([v,P]),Ke&&(queueMicrotask(Ft),Ke=!1)},Fe=!0,Ke=!0,st=[],Pt=[],Mt=ut,pt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ze,pgp:!1,env:{},finalize:Ze},_t=pt,te=[],de=0,G=[];function be(v){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var P=this._PSD=_t;if(typeof v!="function"){if(v!==Se)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&rt(this,this._value)}else this._state=null,this._value=null,++P.ref,function j(V,re){try{re(function(pe){if(V._state===null){if(pe===V)throw new TypeError("A promise cannot be resolved with itself.");var Te=V._lib&&Kt();pe&&typeof pe.then=="function"?j(V,function(Ne,We){pe instanceof be?pe._then(Ne,We):pe.then(Ne,We)}):(V._state=!0,V._value=pe,yt(V)),Te&&Xt()}},rt.bind(null,V))}catch(pe){rt(V,pe)}}(this,v)}var et={get:function(){var v=_t,P=Lt;function j(V,re){var pe=this,Te=!v.global&&(v!==_t||P!==Lt),Ne=Te&&!Fr(),We=new be(function(at,Je){mt(pe,new ge(kn(V,v,Te,Ne),kn(re,v,Te,Ne),at,Je,v))});return this._consoleTask&&(We._consoleTask=this._consoleTask),We}return j.prototype=Se,j},set:function(v){O(this,"then",v&&v.prototype===Se?et:{get:function(){return v},set:et.set})}};function ge(v,P,j,V,re){this.onFulfilled=typeof v=="function"?v:null,this.onRejected=typeof P=="function"?P:null,this.resolve=j,this.reject=V,this.psd=re}function rt(v,P){var j,V;Pt.push(P),v._state===null&&(j=v._lib&&Kt(),P=Mt(P),v._state=!1,v._value=P,V=v,st.some(function(re){return re._value===V._value})||st.push(V),yt(v),j)&&Xt()}function yt(v){var P=v._listeners;v._listeners=[];for(var j=0,V=P.length;j<V;++j)mt(v,P[j]);var re=v._PSD;--re.ref||re.finalize(),de===0&&(++de,Re(function(){--de==0&&ur()},[]))}function mt(v,P){if(v._state===null)v._listeners.push(P);else{var j=v._state?P.onFulfilled:P.onRejected;if(j===null)return(v._state?P.resolve:P.reject)(v._value);++P.psd.ref,++de,Re(Rt,[j,v,P])}}function Rt(v,P,j){try{var V,re=P._value;!P._state&&Pt.length&&(Pt=[]),V=ht&&P._consoleTask?P._consoleTask.run(function(){return v(re)}):v(re),P._state||Pt.indexOf(re)!==-1||(pe=>{for(var Te=st.length;Te;)if(st[--Te]._value===pe._value)return st.splice(Te,1)})(P),j.resolve(V)}catch(pe){j.reject(pe)}finally{--de==0&&ur(),--j.psd.ref||j.psd.finalize()}}function Ft(){Rr(pt,function(){Kt()&&Xt()})}function Kt(){var v=Fe;return Ke=Fe=!1,v}function Xt(){var v,P,j;do for(;0<te.length;)for(v=te,te=[],j=v.length,P=0;P<j;++P){var V=v[P];V[0].apply(null,V[1])}while(0<te.length);Ke=Fe=!0}function ur(){for(var v=st,P=(st=[],v.forEach(function(V){V._PSD.onunhandled.call(null,V._value,V)}),G.slice(0)),j=P.length;j;)P[--j]()}function Pr(v){return new be(Se,!1,v)}function Gt(v,P){var j=_t;return function(){var V=Kt(),re=_t;try{return Hr(j,!0),v.apply(this,arguments)}catch(pe){P&&P(pe)}finally{Hr(re,!1),V&&Xt()}}}b(be.prototype,{then:et,_then:function(v,P){mt(this,new ge(null,null,v,P,_t))},catch:function(v){var P,j;return arguments.length===1?this.then(null,v):(P=v,j=arguments[1],typeof P=="function"?this.then(null,function(V){return(V instanceof P?j:Pr)(V)}):this.then(null,function(V){return(V&&V.name===P?j:Pr)(V)}))},finally:function(v){return this.then(function(P){return be.resolve(v()).then(function(){return P})},function(P){return be.resolve(v()).then(function(){return Pr(P)})})},timeout:function(v,P){var j=this;return v<1/0?new be(function(V,re){var pe=setTimeout(function(){return re(new je.Timeout(P))},v);j.then(V,re).finally(clearTimeout.bind(null,pe))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&O(be.prototype,Symbol.toStringTag,"Dexie.Promise"),pt.env=es(),b(be,{all:function(){var v=Y.apply(null,arguments).map($r);return new be(function(P,j){v.length===0&&P([]);var V=v.length;v.forEach(function(re,pe){return be.resolve(re).then(function(Te){v[pe]=Te,--V||P(v)},j)})})},resolve:function(v){return v instanceof be?v:v&&typeof v.then=="function"?new be(function(P,j){v.then(P,j)}):new be(Se,!0,v)},reject:Pr,race:function(){var v=Y.apply(null,arguments).map($r);return new be(function(P,j){v.map(function(V){return be.resolve(V).then(P,j)})})},PSD:{get:function(){return _t},set:function(v){return _t=v}},totalEchoes:{get:function(){return Lt}},newPSD:Gr,usePSD:Rr,scheduler:{get:function(){return Re},set:function(v){Re=v}},rejectionMapper:{get:function(){return Mt},set:function(v){Mt=v}},follow:function(v,P){return new be(function(j,V){return Gr(function(re,pe){var Te=_t;Te.unhandleds=[],Te.onunhandled=pe,Te.finalize=dt(function(){var Ne,We=this;Ne=function(){We.unhandleds.length===0?re():pe(We.unhandleds[0])},G.push(function at(){Ne(),G.splice(G.indexOf(at),1)}),++de,Re(function(){--de==0&&ur()},[])},Te.finalize),v()},P,j,V)})}}),W&&(W.allSettled&&O(be,"allSettled",function(){var v=Y.apply(null,arguments).map($r);return new be(function(P){v.length===0&&P([]);var j=v.length,V=new Array(j);v.forEach(function(re,pe){return be.resolve(re).then(function(Te){return V[pe]={status:"fulfilled",value:Te}},function(Te){return V[pe]={status:"rejected",reason:Te}}).then(function(){return--j||P(V)})})})}),W.any&&typeof AggregateError<"u"&&O(be,"any",function(){var v=Y.apply(null,arguments).map($r);return new be(function(P,j){v.length===0&&j(new AggregateError([]));var V=v.length,re=new Array(V);v.forEach(function(pe,Te){return be.resolve(pe).then(function(Ne){return P(Ne)},function(Ne){re[Te]=Ne,--V||j(new AggregateError(re))})})})}),W.withResolvers)&&(be.withResolvers=W.withResolvers);var nr={awaits:0,echoes:0,id:0},mn=0,gn=[],Er=0,Lt=0,ys=0;function Gr(v,Te,j,V){var re=_t,pe=Object.create(re),Te=(pe.parent=re,pe.ref=0,pe.global=!1,pe.id=++ys,pt.env,pe.env=fe?{Promise:be,PromiseProp:{value:be,configurable:!0,writable:!0},all:be.all,race:be.race,allSettled:be.allSettled,any:be.any,resolve:be.resolve,reject:be.reject}:{},Te&&f(pe,Te),++re.ref,pe.finalize=function(){--this.parent.ref||this.parent.finalize()},Rr(pe,v,j,V));return pe.ref===0&&pe.finalize(),Te}function an(){return nr.id||(nr.id=++mn),++nr.awaits,nr.echoes+=ie,nr.id}function Fr(){return!!nr.awaits&&(--nr.awaits==0&&(nr.id=0),nr.echoes=nr.awaits*ie,!0)}function $r(v){return nr.echoes&&v&&v.constructor===W?(an(),v.then(function(P){return Fr(),P},function(P){return Fr(),yr(P)})):v}function $n(){var v=gn[gn.length-1];gn.pop(),Hr(v,!1)}function Hr(v,P){var j,V,re=_t;(P?!nr.echoes||Er++&&v===_t:!Er||--Er&&v===_t)||queueMicrotask(P?(function(pe){++Lt,nr.echoes&&--nr.echoes!=0||(nr.echoes=nr.awaits=nr.id=0),gn.push(_t),Hr(pe,!0)}).bind(null,v):$n),v!==_t&&(_t=v,re===pt&&(pt.env=es()),fe)&&(j=pt.env.Promise,V=v.env,re.global||v.global)&&(Object.defineProperty(o,"Promise",V.PromiseProp),j.all=V.all,j.race=V.race,j.resolve=V.resolve,j.reject=V.reject,V.allSettled&&(j.allSettled=V.allSettled),V.any)&&(j.any=V.any)}function es(){var v=o.Promise;return fe?{Promise:v,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:v.all,race:v.race,allSettled:v.allSettled,any:v.any,resolve:v.resolve,reject:v.reject}:{}}function Rr(v,P,j,V,re){var pe=_t;try{return Hr(v,!0),P(j,V,re)}finally{Hr(pe,!1)}}function kn(v,P,j,V){return typeof v!="function"?v:function(){var re=_t;j&&an(),Hr(P,!0);try{return v.apply(this,arguments)}finally{Hr(re,!1),V&&queueMicrotask(Fr)}}}function ms(v){Promise===W&&nr.echoes===0?Er===0?v():enqueueNativeMicroTask(v):setTimeout(v,0)}(""+Bn).indexOf("[native code]")===-1&&(an=Fr=Ze);var yr=be.reject,on="￿",ln="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",bn="String expected.",zr="__dbnames",vn="readonly",qs="readwrite";function Dn(v,P){return v?P?function(){return v.apply(this,arguments)&&P.apply(this,arguments)}:v:P}var pi={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function gs(v){return typeof v!="string"||/\./.test(v)?function(P){return P}:function(P){return P[v]===void 0&&v in P&&delete(P=ne(P))[v],P}}function ts(){throw je.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function Jt(v,P){try{var j=Vs(v),V=Vs(P);if(j!==V)return j==="Array"?1:V==="Array"?-1:j==="binary"?1:V==="binary"?-1:j==="string"?1:V==="string"?-1:j==="Date"?1:V!=="Date"?NaN:-1;switch(j){case"number":case"Date":case"string":return P<v?1:v<P?-1:0;case"binary":for(var re=di(v),pe=di(P),Te=re.length,Ne=pe.length,We=Te<Ne?Te:Ne,at=0;at<We;++at)if(re[at]!==pe[at])return re[at]<pe[at]?-1:1;return Te===Ne?0:Te<Ne?-1:1;case"Array":for(var Je=v,Ge=P,ze=Je.length,nt=Ge.length,Xe=ze<nt?ze:nt,Ye=0;Ye<Xe;++Ye){var Qe=Jt(Je[Ye],Ge[Ye]);if(Qe!==0)return Qe}return ze===nt?0:ze<nt?-1:1}}catch{}return NaN}function Vs(v){var P=typeof v;return P=="object"&&(ArrayBuffer.isView(v)||(P=xe(v))==="ArrayBuffer")?"binary":P}function di(v){return v instanceof Uint8Array?v:ArrayBuffer.isView(v)?new Uint8Array(v.buffer,v.byteOffset,v.byteLength):new Uint8Array(v)}function Sn(v,P,j){var V=v.schema.yProps;return V?(P&&0<j.numFailures&&(P=P.filter(function(re,pe){return!j.failures[pe]})),Promise.all(V.map(function(re){return re=re.updatesTable,P?v.db.table(re).where("k").anyOf(P).delete():v.db.table(re).clear()})).then(function(){return j})):j}hi.prototype.execute=function(v){var P=this["@@propmod"];if(P.add!==void 0){var j=P.add;if(u(j))return i(i([],u(v)?v:[],!0),j).sort();if(typeof j=="number")return(Number(v)||0)+j;if(typeof j=="bigint")try{return BigInt(v)+j}catch{return BigInt(0)+j}throw new TypeError("Invalid term ".concat(j))}if(P.remove!==void 0){var V=P.remove;if(u(V))return u(v)?v.filter(function(re){return!V.includes(re)}).sort():[];if(typeof V=="number")return Number(v)-V;if(typeof V=="bigint")try{return BigInt(v)-V}catch{return BigInt(0)-V}throw new TypeError("Invalid subtrahend ".concat(V))}return j=(j=P.replacePrefix)==null?void 0:j[0],j&&typeof v=="string"&&v.startsWith(j)?P.replacePrefix[1]+v.substring(j.length):v};var wr=hi;function hi(v){this["@@propmod"]=v}function bs(v,P){for(var j=a(P),V=j.length,re=!1,pe=0;pe<V;++pe){var Te=j[pe],Ne=P[Te],We=B(v,Te);Ne instanceof wr?(I(v,Te,Ne.execute(We)),re=!0):We!==Ne&&(I(v,Te,Ne),re=!0)}return re}or.prototype._trans=function(v,P,j){var V=this._tx||_t.trans,re=this.name,pe=ht&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(v==="readonly"?"read":"write"," ").concat(this.name));function Te(at,Je,Ge){if(Ge.schema[re])return P(Ge.idbtrans,Ge);throw new je.NotFound("Table "+re+" not part of transaction")}var Ne=Kt();try{var We=V&&V.db._novip===this.db._novip?V===_t.trans?V._promise(v,Te,j):Gr(function(){return V._promise(v,Te,j)},{trans:V,transless:_t.transless||_t}):function at(Je,Ge,ze,nt){if(Je.idbdb&&(Je._state.openComplete||_t.letThrough||Je._vip)){var Xe=Je._createTransaction(Ge,ze,Je._dbSchema);try{Xe.create(),Je._state.PR1398_maxLoop=3}catch(Ye){return Ye.name===Ee.InvalidState&&Je.isOpen()&&0<--Je._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),Je.close({disableAutoOpen:!1}),Je.open().then(function(){return at(Je,Ge,ze,nt)})):yr(Ye)}return Xe._promise(Ge,function(Ye,Qe){return Gr(function(){return _t.trans=Xe,nt(Ye,Qe,Xe)})}).then(function(Ye){if(Ge==="readwrite")try{Xe.idbtrans.commit()}catch{}return Ge==="readonly"?Ye:Xe._completion.then(function(){return Ye})})}if(Je._state.openComplete)return yr(new je.DatabaseClosed(Je._state.dbOpenError));if(!Je._state.isBeingOpened){if(!Je._state.autoOpen)return yr(new je.DatabaseClosed);Je.open().catch(Ze)}return Je._state.dbReadyPromise.then(function(){return at(Je,Ge,ze,nt)})}(this.db,v,[this.name],Te);return pe&&(We._consoleTask=pe,We=We.catch(function(at){return console.trace(at),yr(at)})),We}finally{Ne&&Xt()}},or.prototype.get=function(v,P){var j=this;return v&&v.constructor===Object?this.where(v).first(P):v==null?yr(new je.Type("Invalid argument to Table.get()")):this._trans("readonly",function(V){return j.core.get({trans:V,key:v}).then(function(re){return j.hook.reading.fire(re)})}).then(P)},or.prototype.where=function(v){if(typeof v=="string")return new this.db.WhereClause(this,v);if(u(v))return new this.db.WhereClause(this,"[".concat(v.join("+"),"]"));var P=a(v);if(P.length===1)return this.where(P[0]).equals(v[P[0]]);var j=this.schema.indexes.concat(this.schema.primKey).filter(function(Ne){if(Ne.compound&&P.every(function(at){return 0<=Ne.keyPath.indexOf(at)})){for(var We=0;We<P.length;++We)if(P.indexOf(Ne.keyPath[We])===-1)return!1;return!0}return!1}).sort(function(Ne,We){return Ne.keyPath.length-We.keyPath.length})[0];if(j&&this.db._maxKey!==on)return Te=j.keyPath.slice(0,P.length),this.where(Te).equals(Te.map(function(Ne){return v[Ne]}));!j&&ht&&console.warn("The query ".concat(JSON.stringify(v)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(P.join("+"),"]"));var V=this.schema.idxByName;function re(Ne,We){return Jt(Ne,We)===0}var Te=P.reduce(function(Je,We){var at=Je[0],Je=Je[1],Ge=V[We],ze=v[We];return[at||Ge,at||!Ge?Dn(Je,Ge&&Ge.multi?function(nt){return nt=B(nt,We),u(nt)&&nt.some(function(Xe){return re(ze,Xe)})}:function(nt){return re(ze,B(nt,We))}):Je]},[null,null]),pe=Te[0],Te=Te[1];return pe?this.where(pe.name).equals(v[pe.keyPath]).filter(Te):j?this.filter(Te):this.where(P).equals("")},or.prototype.filter=function(v){return this.toCollection().and(v)},or.prototype.count=function(v){return this.toCollection().count(v)},or.prototype.offset=function(v){return this.toCollection().offset(v)},or.prototype.limit=function(v){return this.toCollection().limit(v)},or.prototype.each=function(v){return this.toCollection().each(v)},or.prototype.toArray=function(v){return this.toCollection().toArray(v)},or.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},or.prototype.orderBy=function(v){return new this.db.Collection(new this.db.WhereClause(this,u(v)?"[".concat(v.join("+"),"]"):v))},or.prototype.reverse=function(){return this.toCollection().reverse()},or.prototype.mapToClass=function(v){for(var P=this.db,j=this.name,V=((this.schema.mappedClass=v).prototype instanceof ts&&(v=(Te=>{var Ne=Je,We=Te;if(typeof We!="function"&&We!==null)throw new TypeError("Class extends value "+String(We)+" is not a constructor or null");function at(){this.constructor=Ne}function Je(){return Te!==null&&Te.apply(this,arguments)||this}return r(Ne,We),Ne.prototype=We===null?Object.create(We):(at.prototype=We.prototype,new at),Object.defineProperty(Je.prototype,"db",{get:function(){return P},enumerable:!1,configurable:!0}),Je.prototype.table=function(){return j},Je})(v)),new Set),re=v.prototype;re;re=d(re))Object.getOwnPropertyNames(re).forEach(function(Te){return V.add(Te)});function pe(Te){if(!Te)return Te;var Ne,We=Object.create(v.prototype);for(Ne in Te)if(!V.has(Ne))try{We[Ne]=Te[Ne]}catch{}return We}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=pe,this.hook("reading",pe),v},or.prototype.defineClass=function(){return this.mapToClass(function(v){f(this,v)})},or.prototype.add=function(v,P){var j=this,V=this.schema.primKey,re=V.auto,pe=V.keyPath,Te=v;return pe&&re&&(Te=gs(pe)(v)),this._trans("readwrite",function(Ne){return j.core.mutate({trans:Ne,type:"add",keys:P!=null?[P]:null,values:[Te]})}).then(function(Ne){return Ne.numFailures?be.reject(Ne.failures[0]):Ne.lastResult}).then(function(Ne){if(pe)try{I(v,pe,Ne)}catch{}return Ne})},or.prototype.upsert=function(v,P){var j=this,V=this.schema.primKey.keyPath;return this._trans("readwrite",function(re){return j.core.get({trans:re,key:v}).then(function(pe){var Te=pe??{};return bs(Te,P),V&&I(Te,V,v),j.core.mutate({trans:re,type:"put",values:[Te],keys:[v],upsert:!0,updates:{keys:[v],changeSpecs:[P]}}).then(function(Ne){return Ne.numFailures?be.reject(Ne.failures[0]):!!pe})})})},or.prototype.update=function(v,P){return typeof v!="object"||u(v)?this.where(":id").equals(v).modify(P):(v=B(v,this.schema.primKey.keyPath))===void 0?yr(new je.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(v).modify(P)},or.prototype.put=function(v,P){var j=this,V=this.schema.primKey,re=V.auto,pe=V.keyPath,Te=v;return pe&&re&&(Te=gs(pe)(v)),this._trans("readwrite",function(Ne){return j.core.mutate({trans:Ne,type:"put",values:[Te],keys:P!=null?[P]:null})}).then(function(Ne){return Ne.numFailures?be.reject(Ne.failures[0]):Ne.lastResult}).then(function(Ne){if(pe)try{I(v,pe,Ne)}catch{}return Ne})},or.prototype.delete=function(v){var P=this;return this._trans("readwrite",function(j){return P.core.mutate({trans:j,type:"delete",keys:[v]}).then(function(V){return Sn(P,[v],V)}).then(function(V){return V.numFailures?be.reject(V.failures[0]):void 0})})},or.prototype.clear=function(){var v=this;return this._trans("readwrite",function(P){return v.core.mutate({trans:P,type:"deleteRange",range:pi}).then(function(j){return Sn(v,null,j)})}).then(function(P){return P.numFailures?be.reject(P.failures[0]):void 0})},or.prototype.bulkGet=function(v){var P=this;return this._trans("readonly",function(j){return P.core.getMany({keys:v,trans:j}).then(function(V){return V.map(function(re){return P.hook.reading.fire(re)})})})},or.prototype.bulkAdd=function(v,P,j){var V=this,re=Array.isArray(P)?P:void 0,pe=(j=j||(re?void 0:P))?j.allKeys:void 0;return this._trans("readwrite",function(Te){var Ne=V.schema.primKey,at=Ne.auto,Ne=Ne.keyPath;if(Ne&&re)throw new je.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(re&&re.length!==v.length)throw new je.InvalidArgument("Arguments objects and keys must have the same length");var We=v.length,at=Ne&&at?v.map(gs(Ne)):v;return V.core.mutate({trans:Te,type:"add",keys:re,values:at,wantResults:pe}).then(function(Je){var Ge=Je.numFailures,ze=Je.failures;if(Ge===0)return pe?Je.results:Je.lastResult;throw new Ie("".concat(V.name,".bulkAdd(): ").concat(Ge," of ").concat(We," operations failed"),ze)})})},or.prototype.bulkPut=function(v,P,j){var V=this,re=Array.isArray(P)?P:void 0,pe=(j=j||(re?void 0:P))?j.allKeys:void 0;return this._trans("readwrite",function(Te){var Ne=V.schema.primKey,at=Ne.auto,Ne=Ne.keyPath;if(Ne&&re)throw new je.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(re&&re.length!==v.length)throw new je.InvalidArgument("Arguments objects and keys must have the same length");var We=v.length,at=Ne&&at?v.map(gs(Ne)):v;return V.core.mutate({trans:Te,type:"put",keys:re,values:at,wantResults:pe}).then(function(Je){var Ge=Je.numFailures,ze=Je.failures;if(Ge===0)return pe?Je.results:Je.lastResult;throw new Ie("".concat(V.name,".bulkPut(): ").concat(Ge," of ").concat(We," operations failed"),ze)})})},or.prototype.bulkUpdate=function(v){var P=this,j=this.core,V=v.map(function(Te){return Te.key}),re=v.map(function(Te){return Te.changes}),pe=[];return this._trans("readwrite",function(Te){return j.getMany({trans:Te,keys:V,cache:"clone"}).then(function(Ne){var We=[],at=[],Je=(v.forEach(function(Ge,ze){var nt=Ge.key,Xe=Ge.changes,Ye=Ne[ze];if(Ye){for(var Qe=0,lt=Object.keys(Xe);Qe<lt.length;Qe++){var ot=lt[Qe],ft=Xe[ot];if(ot===P.schema.primKey.keyPath){if(Jt(ft,nt)!==0)throw new je.Constraint("Cannot update primary key in bulkUpdate()")}else I(Ye,ot,ft)}pe.push(ze),We.push(nt),at.push(Ye)}}),We.length);return j.mutate({trans:Te,type:"put",keys:We,values:at,updates:{keys:V,changeSpecs:re}}).then(function(Ge){var ze=Ge.numFailures,nt=Ge.failures;if(ze===0)return Je;for(var Xe=0,Ye=Object.keys(nt);Xe<Ye.length;Xe++){var Qe,lt=Ye[Xe],ot=pe[Number(lt)];ot!=null&&(Qe=nt[lt],delete nt[lt],nt[ot]=Qe)}throw new Ie("".concat(P.name,".bulkUpdate(): ").concat(ze," of ").concat(Je," operations failed"),nt)})})})},or.prototype.bulkDelete=function(v){var P=this,j=v.length;return this._trans("readwrite",function(V){return P.core.mutate({trans:V,type:"delete",keys:v}).then(function(re){return Sn(P,v,re)})}).then(function(V){var re=V.numFailures,pe=V.failures;if(re===0)return V.lastResult;throw new Ie("".concat(P.name,".bulkDelete(): ").concat(re," of ").concat(j," operations failed"),pe)})};var yi=or;function or(){}function Tn(v){function P(Te,Ne){if(Ne){for(var We=arguments.length,at=new Array(We-1);--We;)at[We-1]=arguments[We];return j[Te].subscribe.apply(null,at),v}if(typeof Te=="string")return j[Te]}var j={};P.addEventType=pe;for(var V=1,re=arguments.length;V<re;++V)pe(arguments[V]);return P;function pe(Te,Ne,We){var at,Je;if(typeof Te!="object")return Ne=Ne||Me,Je={subscribers:[],fire:We=We||Ze,subscribe:function(Ge){Je.subscribers.indexOf(Ge)===-1&&(Je.subscribers.push(Ge),Je.fire=Ne(Je.fire,Ge))},unsubscribe:function(Ge){Je.subscribers=Je.subscribers.filter(function(ze){return ze!==Ge}),Je.fire=Je.subscribers.reduce(Ne,We)}},j[Te]=P[Te]=Je;a(at=Te).forEach(function(Ge){var ze=at[Ge];if(u(ze))pe(Ge,at[Ge][0],at[Ge][1]);else{if(ze!=="asap")throw new je.InvalidArgument("Invalid event config");var nt=pe(Ge,ut,function(){for(var Xe=arguments.length,Ye=new Array(Xe);Xe--;)Ye[Xe]=arguments[Xe];nt.subscribers.forEach(function(Qe){D(function(){Qe.apply(null,Ye)})})})}})}}function Un(v,P){return x(P).from({prototype:v}),P}function qn(v,P){return!(v.filter||v.algorithm||v.or)&&(P?v.justLimit:!v.replayFilter)}function Ks(v,P){v.filter=Dn(v.filter,P)}function rs(v,P,j){var V=v.replayFilter;v.replayFilter=V?function(){return Dn(V(),P())}:P,v.justLimit=j&&!V}function ns(v,P){if(v.isPrimKey)return P.primaryKey;var j=P.getIndexByKeyPath(v.index);if(j)return j;throw new je.Schema("KeyPath "+v.index+" on object store "+P.name+" is not indexed")}function Ws(v,P,j){var V=ns(v,P.schema);return P.openCursor({trans:j,values:!v.keysOnly,reverse:v.dir==="prev",unique:!!v.unique,query:{index:V,range:v.range}})}function En(v,P,j,V){var re,pe,Te=v.replayFilter?Dn(v.filter,v.replayFilter()):v.filter;return v.or?(re={},pe=function(Ne,We,at){var Je,Ge;Te&&!Te(We,at,function(ze){return We.stop(ze)},function(ze){return We.fail(ze)})||((Ge=""+(Je=We.primaryKey))=="[object ArrayBuffer]"&&(Ge=""+new Uint8Array(Je)),m(re,Ge))||(re[Ge]=!0,P(Ne,We,at))},Promise.all([v.or._iterate(pe,j),mi(Ws(v,V,j),v.algorithm,pe,!v.keysOnly&&v.valueMapper)])):mi(Ws(v,V,j),Dn(v.algorithm,Te),P,!v.keysOnly&&v.valueMapper)}function mi(v,P,j,V){var re=Gt(V?function(pe,Te,Ne){return j(V(pe),Te,Ne)}:j);return v.then(function(pe){if(pe)return pe.start(function(){var Te=function(){return pe.continue()};P&&!P(pe,function(Ne){return Te=Ne},function(Ne){pe.stop(Ne),Te=Ze},function(Ne){pe.fail(Ne),Te=Ze})||re(pe.value,pe,function(Ne){return Te=Ne}),Te()})})}er.prototype._read=function(v,P){var j=this._ctx;return j.error?j.table._trans(null,yr.bind(null,j.error)):j.table._trans("readonly",v).then(P)},er.prototype._write=function(v){var P=this._ctx;return P.error?P.table._trans(null,yr.bind(null,P.error)):P.table._trans("readwrite",v,"locked")},er.prototype._addAlgorithm=function(v){var P=this._ctx;P.algorithm=Dn(P.algorithm,v)},er.prototype._iterate=function(v,P){return En(this._ctx,v,P,this._ctx.table.core)},er.prototype.clone=function(v){var P=Object.create(this.constructor.prototype),j=Object.create(this._ctx);return v&&f(j,v),P._ctx=j,P},er.prototype.raw=function(){return this._ctx.valueMapper=null,this},er.prototype.each=function(v){var P=this._ctx;return this._read(function(j){return En(P,v,j,P.table.core)})},er.prototype.count=function(v){var P=this;return this._read(function(j){var V,re=P._ctx,pe=re.table.core;return qn(re,!0)?pe.count({trans:j,query:{index:ns(re,pe.schema),range:re.range}}).then(function(Te){return Math.min(Te,re.limit)}):(V=0,En(re,function(){return++V,!1},j,pe).then(function(){return V}))}).then(v)},er.prototype.sortBy=function(v,P){var j=v.split(".").reverse(),V=j[0],re=j.length-1;function pe(We,at){return at?pe(We[j[at]],at-1):We[V]}var Te=this._ctx.dir==="next"?1:-1;function Ne(We,at){return Jt(pe(We,re),pe(at,re))*Te}return this.toArray(function(We){return We.slice().sort(Ne)}).then(P)},er.prototype.toArray=function(v){var P=this;return this._read(function(j){var V,re,pe,Te=P._ctx;return qn(Te,!0)&&0<Te.limit?(V=Te.valueMapper,re=ns(Te,Te.table.core.schema),Te.table.core.query({trans:j,limit:Te.limit,values:!0,direction:Te.dir==="prev"?"prev":void 0,query:{index:re,range:Te.range}}).then(function(Ne){return Ne=Ne.result,V?Ne.map(V):Ne})):(pe=[],En(Te,function(Ne){return pe.push(Ne)},j,Te.table.core).then(function(){return pe}))},v)},er.prototype.offset=function(v){var P=this._ctx;return v<=0||(P.offset+=v,qn(P)?rs(P,function(){var j=v;return function(V,re){return j===0||(j===1?--j:re(function(){V.advance(j),j=0}),!1)}}):rs(P,function(){var j=v;return function(){return--j<0}})),this},er.prototype.limit=function(v){return this._ctx.limit=Math.min(this._ctx.limit,v),rs(this._ctx,function(){var P=v;return function(j,V,re){return--P<=0&&V(re),0<=P}},!0),this},er.prototype.until=function(v,P){return Ks(this._ctx,function(j,V,re){return!v(j.value)||(V(re),P)}),this},er.prototype.first=function(v){return this.limit(1).toArray(function(P){return P[0]}).then(v)},er.prototype.last=function(v){return this.reverse().first(v)},er.prototype.filter=function(v){var P;return Ks(this._ctx,function(j){return v(j.value)}),(P=this._ctx).isMatch=Dn(P.isMatch,v),this},er.prototype.and=function(v){return this.filter(v)},er.prototype.or=function(v){return new this.db.WhereClause(this._ctx.table,v,this)},er.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},er.prototype.desc=function(){return this.reverse()},er.prototype.eachKey=function(v){var P=this._ctx;return P.keysOnly=!P.isMatch,this.each(function(j,V){v(V.key,V)})},er.prototype.eachUniqueKey=function(v){return this._ctx.unique="unique",this.eachKey(v)},er.prototype.eachPrimaryKey=function(v){var P=this._ctx;return P.keysOnly=!P.isMatch,this.each(function(j,V){v(V.primaryKey,V)})},er.prototype.keys=function(v){var P=this._ctx,j=(P.keysOnly=!P.isMatch,[]);return this.each(function(V,re){j.push(re.key)}).then(function(){return j}).then(v)},er.prototype.primaryKeys=function(v){var P=this._ctx;if(qn(P,!0)&&0<P.limit)return this._read(function(V){var re=ns(P,P.table.core.schema);return P.table.core.query({trans:V,values:!1,limit:P.limit,direction:P.dir==="prev"?"prev":void 0,query:{index:re,range:P.range}})}).then(function(V){return V.result}).then(v);P.keysOnly=!P.isMatch;var j=[];return this.each(function(V,re){j.push(re.primaryKey)}).then(function(){return j}).then(v)},er.prototype.uniqueKeys=function(v){return this._ctx.unique="unique",this.keys(v)},er.prototype.firstKey=function(v){return this.limit(1).keys(function(P){return P[0]}).then(v)},er.prototype.lastKey=function(v){return this.reverse().firstKey(v)},er.prototype.distinct=function(){var v,P=this._ctx,P=P.index&&P.table.schema.idxByName[P.index];return P&&P.multi&&(v={},Ks(this._ctx,function(V){var V=V.primaryKey.toString(),re=m(v,V);return v[V]=!0,!re})),this},er.prototype.modify=function(v){var P=this,j=this._ctx;return this._write(function(V){function re(Ye,Qe){var lt=Qe.failures;ze+=Ye-Qe.numFailures;for(var ot=0,ft=a(lt);ot<ft.length;ot++){var bt=ft[ot];Ge.push(lt[bt])}}var pe=typeof v=="function"?v:function(Ye){return bs(Ye,v)},Te=j.table.core,Je=Te.schema.primaryKey,Ne=Je.outbound,We=Je.extractKey,at=200,Je=P.db._options.modifyChunkSize,Ge=(Je&&(at=typeof Je=="object"?Je[Te.name]||Je["*"]||200:Je),[]),ze=0,nt=[],Xe=v===gi;return P.clone().primaryKeys().then(function(Ye){function Qe(ot){var ft=Math.min(at,Ye.length-ot),bt=Ye.slice(ot,ot+ft);return(Xe?Promise.resolve([]):Te.getMany({trans:V,keys:bt,cache:"immutable"})).then(function(Et){var Ct=[],xt=[],Dt=Ne?[]:null,At=Xe?bt:[];if(!Xe)for(var jt=0;jt<ft;++jt){var St=Et[jt],Ut={value:ne(St),primKey:Ye[ot+jt]};pe.call(Ut,Ut.value,Ut)!==!1&&(Ut.value==null?At.push(Ye[ot+jt]):Ne||Jt(We(St),We(Ut.value))===0?(xt.push(Ut.value),Ne&&Dt.push(Ye[ot+jt])):(At.push(Ye[ot+jt]),Ct.push(Ut.value)))}return Promise.resolve(0<Ct.length&&Te.mutate({trans:V,type:"add",values:Ct}).then(function(qt){for(var Wt in qt.failures)At.splice(parseInt(Wt),1);re(Ct.length,qt)})).then(function(){return(0<xt.length||lt&&typeof v=="object")&&Te.mutate({trans:V,type:"put",keys:Dt,values:xt,criteria:lt,changeSpec:typeof v!="function"&&v,isAdditionalChunk:0<ot}).then(function(qt){return re(xt.length,qt)})}).then(function(){return(0<At.length||lt&&Xe)&&Te.mutate({trans:V,type:"delete",keys:At,criteria:lt,isAdditionalChunk:0<ot}).then(function(qt){return Sn(j.table,At,qt)}).then(function(qt){return re(At.length,qt)})}).then(function(){return Ye.length>ot+ft&&Qe(ot+at)})})}var lt=qn(j)&&j.limit===1/0&&(typeof v!="function"||Xe)&&{index:j.index,range:j.range};return Qe(0).then(function(){if(0<Ge.length)throw new ye("Error modifying one or more objects",Ge,ze,nt);return Ye.length})})})},er.prototype.delete=function(){var v=this._ctx,P=v.range;return!qn(v)||v.table.schema.yProps||!v.isPrimKey&&P.type!==3?this.modify(gi):this._write(function(j){var V=v.table.core.schema.primaryKey,re=P;return v.table.core.count({trans:j,query:{index:V,range:re}}).then(function(pe){return v.table.core.mutate({trans:j,type:"deleteRange",range:re}).then(function(We){var Ne=We.failures,We=We.numFailures;if(We)throw new ye("Could not delete some values",Object.keys(Ne).map(function(at){return Ne[at]}),pe-We);return pe-We})})})};var _n=er;function er(){}var gi=function(v,P){return P.value=null};function Hi(v,P){return v<P?-1:v===P?0:1}function vs(v,P){return P<v?-1:v===P?0:1}function Ir(v,P,j){return v=v instanceof Gs?new v.Collection(v):v,v._ctx.error=new(j||TypeError)(P),v}function Vn(v){return new v.Collection(v,function(){return bi("")}).limit(0)}function Ss(nt,P,j,V){var re,pe,Te,Ne,We,at,Je,Ge=j.length;if(!j.every(function(Ye){return typeof Ye=="string"}))return Ir(nt,bn);function ze(Ye){re=Ye==="next"?function(lt){return lt.toUpperCase()}:function(lt){return lt.toLowerCase()},pe=Ye==="next"?function(lt){return lt.toLowerCase()}:function(lt){return lt.toUpperCase()},Te=Ye==="next"?Hi:vs;var Qe=j.map(function(lt){return{lower:pe(lt),upper:re(lt)}}).sort(function(lt,ot){return Te(lt.lower,ot.lower)});Ne=Qe.map(function(lt){return lt.upper}),We=Qe.map(function(lt){return lt.lower}),Je=(at=Ye)==="next"?"":V}ze("next");var nt=new nt.Collection(nt,function(){return xn(Ne[0],We[Ge-1]+V)}),Xe=(nt._ondirectionchange=function(Ye){ze(Ye)},0);return nt._addAlgorithm(function(Ye,Qe,lt){var ot=Ye.key;if(typeof ot=="string"){var ft=pe(ot);if(P(ft,We,Xe))return!0;for(var bt=null,Et=Xe;Et<Ge;++Et){var Ct=((xt,Dt,At,jt,St,Ut)=>{for(var qt=Math.min(xt.length,jt.length),Wt=-1,Qt=0;Qt<qt;++Qt){var L=Dt[Qt];if(L!==jt[Qt])return St(xt[Qt],At[Qt])<0?xt.substr(0,Qt)+At[Qt]+At.substr(Qt+1):St(xt[Qt],jt[Qt])<0?xt.substr(0,Qt)+jt[Qt]+At.substr(Qt+1):0<=Wt?xt.substr(0,Wt)+Dt[Wt]+At.substr(Wt+1):null;St(xt[Qt],L)<0&&(Wt=Qt)}return qt<jt.length&&Ut==="next"?xt+At.substr(xt.length):qt<xt.length&&Ut==="prev"?xt.substr(0,At.length):Wt<0?null:xt.substr(0,Wt)+jt[Wt]+At.substr(Wt+1)})(ot,ft,Ne[Et],We[Et],Te,at);Ct===null&&bt===null?Xe=Et+1:(bt===null||0<Te(bt,Ct))&&(bt=Ct)}Qe(bt!==null?function(){Ye.continue(bt+Je)}:lt)}return!1}),nt}function xn(v,P,j,V){return{type:2,lower:v,upper:P,lowerOpen:j,upperOpen:V}}function bi(v){return{type:1,lower:v,upper:v}}Object.defineProperty(Sr.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),Sr.prototype.between=function(v,P,j,V){j=j!==!1,V=V===!0;try{return 0<this._cmp(v,P)||this._cmp(v,P)===0&&(j||V)&&(!j||!V)?Vn(this):new this.Collection(this,function(){return xn(v,P,!j,!V)})}catch{return Ir(this,ln)}},Sr.prototype.equals=function(v){return v==null?Ir(this,ln):new this.Collection(this,function(){return bi(v)})},Sr.prototype.above=function(v){return v==null?Ir(this,ln):new this.Collection(this,function(){return xn(v,void 0,!0)})},Sr.prototype.aboveOrEqual=function(v){return v==null?Ir(this,ln):new this.Collection(this,function(){return xn(v,void 0,!1)})},Sr.prototype.below=function(v){return v==null?Ir(this,ln):new this.Collection(this,function(){return xn(void 0,v,!1,!0)})},Sr.prototype.belowOrEqual=function(v){return v==null?Ir(this,ln):new this.Collection(this,function(){return xn(void 0,v)})},Sr.prototype.startsWith=function(v){return typeof v!="string"?Ir(this,bn):this.between(v,v+on,!0,!0)},Sr.prototype.startsWithIgnoreCase=function(v){return v===""?this.startsWith(v):Ss(this,function(P,j){return P.indexOf(j[0])===0},[v],on)},Sr.prototype.equalsIgnoreCase=function(v){return Ss(this,function(P,j){return P===j[0]},[v],"")},Sr.prototype.anyOfIgnoreCase=function(){var v=Y.apply(K,arguments);return v.length===0?Vn(this):Ss(this,function(P,j){return j.indexOf(P)!==-1},v,"")},Sr.prototype.startsWithAnyOfIgnoreCase=function(){var v=Y.apply(K,arguments);return v.length===0?Vn(this):Ss(this,function(P,j){return j.some(function(V){return P.indexOf(V)===0})},v,on)},Sr.prototype.anyOf=function(){var v,P,j=this,V=Y.apply(K,arguments),re=this._cmp;try{V.sort(re)}catch{return Ir(this,ln)}return V.length===0?Vn(this):((v=new this.Collection(this,function(){return xn(V[0],V[V.length-1])}))._ondirectionchange=function(pe){re=pe==="next"?j._ascending:j._descending,V.sort(re)},P=0,v._addAlgorithm(function(pe,Te,Ne){for(var We=pe.key;0<re(We,V[P]);)if(++P===V.length)return Te(Ne),!1;return re(We,V[P])===0||(Te(function(){pe.continue(V[P])}),!1)}),v)},Sr.prototype.notEqual=function(v){return this.inAnyRange([[-1/0,v],[v,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},Sr.prototype.noneOf=function(){var v=Y.apply(K,arguments);if(v.length===0)return new this.Collection(this);try{v.sort(this._ascending)}catch{return Ir(this,ln)}var P=v.reduce(function(j,V){return j?j.concat([[j[j.length-1][1],V]]):[[-1/0,V]]},null);return P.push([v[v.length-1],this.db._maxKey]),this.inAnyRange(P,{includeLowers:!1,includeUppers:!1})},Sr.prototype.inAnyRange=function(v,lt){var j=this,V=this._cmp,re=this._ascending,pe=this._descending,Te=this._min,Ne=this._max;if(v.length===0)return Vn(this);if(!v.every(function(ot){return ot[0]!==void 0&&ot[1]!==void 0&&re(ot[0],ot[1])<=0}))return Ir(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",je.InvalidArgument);var We=!lt||lt.includeLowers!==!1,at=lt&&lt.includeUppers===!0,Je,Ge=re;function ze(ot,ft){return Ge(ot[0],ft[0])}try{(Je=v.reduce(function(ot,ft){for(var bt=0,Et=ot.length;bt<Et;++bt){var Ct=ot[bt];if(V(ft[0],Ct[1])<0&&0<V(ft[1],Ct[0])){Ct[0]=Te(Ct[0],ft[0]),Ct[1]=Ne(Ct[1],ft[1]);break}}return bt===Et&&ot.push(ft),ot},[])).sort(ze)}catch{return Ir(this,ln)}var nt=0,Xe=at?function(ot){return 0<re(ot,Je[nt][1])}:function(ot){return 0<=re(ot,Je[nt][1])},Ye=We?function(ot){return 0<pe(ot,Je[nt][0])}:function(ot){return 0<=pe(ot,Je[nt][0])},Qe=Xe,lt=new this.Collection(this,function(){return xn(Je[0][0],Je[Je.length-1][1],!We,!at)});return lt._ondirectionchange=function(ot){Ge=ot==="next"?(Qe=Xe,re):(Qe=Ye,pe),Je.sort(ze)},lt._addAlgorithm(function(ot,ft,bt){for(var Et,Ct=ot.key;Qe(Ct);)if(++nt===Je.length)return ft(bt),!1;return!Xe(Et=Ct)&&!Ye(Et)||(j._cmp(Ct,Je[nt][1])===0||j._cmp(Ct,Je[nt][0])===0||ft(function(){Ge===re?ot.continue(Je[nt][0]):ot.continue(Je[nt][1])}),!1)}),lt},Sr.prototype.startsWithAnyOf=function(){var v=Y.apply(K,arguments);return v.every(function(P){return typeof P=="string"})?v.length===0?Vn(this):this.inAnyRange(v.map(function(P){return[P,P+on]})):Ir(this,"startsWithAnyOf() only works with strings")};var Gs=Sr;function Sr(){}function Or(v){return Gt(function(P){return Pn(P),v(P.target.error),!1})}function Pn(v){v.stopPropagation&&v.stopPropagation(),v.preventDefault&&v.preventDefault()}var Kn="storagemutated",Hs="x-storagemutated-1",en=Tn(null,Kn),zi=(Ur.prototype._lock=function(){return E(!_t.global),++this._reculock,this._reculock!==1||_t.global||(_t.lockOwnerFor=this),this},Ur.prototype._unlock=function(){if(E(!_t.global),--this._reculock==0)for(_t.global||(_t.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var v=this._blockedFuncs.shift();try{Rr(v[1],v[0])}catch{}}return this},Ur.prototype._locked=function(){return this._reculock&&_t.lockOwnerFor!==this},Ur.prototype.create=function(v){var P=this;if(this.mode){var j=this.db.idbdb,V=this.db._state.dbOpenError;if(E(!this.idbtrans),!v&&!j)switch(V&&V.name){case"DatabaseClosedError":throw new je.DatabaseClosed(V);case"MissingAPIError":throw new je.MissingAPI(V.message,V);default:throw new je.OpenFailed(V)}if(!this.active)throw new je.TransactionInactive;E(this._completion._state===null),(v=this.idbtrans=v||(this.db.core||j).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Gt(function(re){Pn(re),P._reject(v.error)}),v.onabort=Gt(function(re){Pn(re),P.active&&P._reject(new je.Abort(v.error)),P.active=!1,P.on("abort").fire(re)}),v.oncomplete=Gt(function(){P.active=!1,P._resolve(),"mutatedParts"in v&&en.storagemutated.fire(v.mutatedParts)})}return this},Ur.prototype._promise=function(v,P,j){var V,re=this;return v==="readwrite"&&this.mode!=="readwrite"?yr(new je.ReadOnly("Transaction is readonly")):this.active?this._locked()?new be(function(pe,Te){re._blockedFuncs.push([function(){re._promise(v,P,j).then(pe,Te)},_t])}):j?Gr(function(){var pe=new be(function(Te,Ne){re._lock();var We=P(Te,Ne,re);We&&We.then&&We.then(Te,Ne)});return pe.finally(function(){return re._unlock()}),pe._lib=!0,pe}):((V=new be(function(pe,Te){var Ne=P(pe,Te,re);Ne&&Ne.then&&Ne.then(pe,Te)}))._lib=!0,V):yr(new je.TransactionInactive)},Ur.prototype._root=function(){return this.parent?this.parent._root():this},Ur.prototype.waitFor=function(v){var P,j=this._root(),V=be.resolve(v),re=(j._waitingFor?j._waitingFor=j._waitingFor.then(function(){return V}):(j._waitingFor=V,j._waitingQueue=[],P=j.idbtrans.objectStore(j.storeNames[0]),function pe(){for(++j._spinCount;j._waitingQueue.length;)j._waitingQueue.shift()();j._waitingFor&&(P.get(-1/0).onsuccess=pe)}()),j._waitingFor);return new be(function(pe,Te){V.then(function(Ne){return j._waitingQueue.push(Gt(pe.bind(null,Ne)))},function(Ne){return j._waitingQueue.push(Gt(Te.bind(null,Ne)))}).finally(function(){j._waitingFor===re&&(j._waitingFor=null)})})},Ur.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new je.Abort))},Ur.prototype.table=function(v){var P=this._memoizedTables||(this._memoizedTables={});if(m(P,v))return P[v];var j=this.schema[v];if(j)return(j=new this.db.Table(v,j,this)).core=this.db.core.table(v),P[v]=j;throw new je.NotFound("Table "+v+" not part of transaction")},Ur);function Ur(){}function zs(v,P,j,V,re,pe,Te,Ne){return{name:v,keyPath:P,unique:j,multi:V,auto:re,compound:pe,src:(j&&!Te?"&":"")+(V?"*":"")+(re?"++":"")+Js(P),type:Ne}}function Js(v){return typeof v=="string"?v:v?"["+[].join.call(v,"+")+"]":""}function It(v,P,j){return{name:v,primKey:P,indexes:j,mappedClass:null,idxByName:(V=function(re){return[re.name,re]},j.reduce(function(re,pe,Te){return pe=V(pe,Te),pe&&(re[pe[0]]=pe[1]),re},{}))};var V}var ss=function(v){try{return v.only([[]]),ss=function(){return[[]]},[[]]}catch{return ss=function(){return on},on}};function Ts(v){return v==null?function(){}:typeof v=="string"?(P=v).split(".").length===1?function(j){return j[P]}:function(j){return B(j,P)}:function(j){return B(j,v)};var P}function vi(v){return[].slice.call(v)}var Ji=0;function is(v){return v==null?":id":typeof v=="string"?v:"[".concat(v.join("+"),"]")}function Yi(v,P,Te){function V(Qe){if(Qe.type===3)return null;if(Qe.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var nt=Qe.lower,Xe=Qe.upper,Ye=Qe.lowerOpen,Qe=Qe.upperOpen;return nt===void 0?Xe===void 0?null:P.upperBound(Xe,!!Qe):Xe===void 0?P.lowerBound(nt,!!Ye):P.bound(nt,Xe,!!Ye,!!Qe)}function re(ze){var nt,Xe,Ye=ze.name;return{name:Ye,schema:ze,mutate:function(Qe){var lt=Qe.trans,ot=Qe.type,ft=Qe.keys,bt=Qe.values,Et=Qe.range;return new Promise(function(Ct,xt){Ct=Gt(Ct);var Dt=lt.objectStore(Ye),At=Dt.keyPath==null,jt=ot==="put"||ot==="add";if(!jt&&ot!=="delete"&&ot!=="deleteRange")throw new Error("Invalid operation type: "+ot);var St,Ut=(ft||bt||{length:1}).length;if(ft&&bt&&ft.length!==bt.length)throw new Error("Given keys array must have same length as given values array.");if(Ut===0)return Ct({numFailures:0,failures:{},results:[],lastResult:void 0});function qt(tt){++L,Pn(tt)}var Wt=[],Qt=[],L=0;if(ot==="deleteRange"){if(Et.type===4)return Ct({numFailures:L,failures:Qt,results:[],lastResult:void 0});Et.type===3?Wt.push(St=Dt.clear()):Wt.push(St=Dt.delete(V(Et)))}else{var At=jt?At?[bt,ft]:[bt,null]:[ft,null],k=At[0],F=At[1];if(jt)for(var se=0;se<Ut;++se)Wt.push(St=F&&F[se]!==void 0?Dt[ot](k[se],F[se]):Dt[ot](k[se])),St.onerror=qt;else for(se=0;se<Ut;++se)Wt.push(St=Dt[ot](k[se])),St.onerror=qt}function ke(tt){tt=tt.target.result,Wt.forEach(function(Nt,fr){return Nt.error!=null&&(Qt[fr]=Nt.error)}),Ct({numFailures:L,failures:Qt,results:ot==="delete"?ft:Wt.map(function(Nt){return Nt.result}),lastResult:tt})}St.onerror=function(tt){qt(tt),ke(tt)},St.onsuccess=ke})},getMany:function(Qe){var lt=Qe.trans,ot=Qe.keys;return new Promise(function(ft,bt){ft=Gt(ft);for(var Et,Ct=lt.objectStore(Ye),xt=ot.length,Dt=new Array(xt),At=0,jt=0,St=function(Wt){Wt=Wt.target,Dt[Wt._pos]=Wt.result,++jt===At&&ft(Dt)},Ut=Or(bt),qt=0;qt<xt;++qt)ot[qt]!=null&&((Et=Ct.get(ot[qt]))._pos=qt,Et.onsuccess=St,Et.onerror=Ut,++At);At===0&&ft(Dt)})},get:function(Qe){var lt=Qe.trans,ot=Qe.key;return new Promise(function(ft,bt){ft=Gt(ft);var Et=lt.objectStore(Ye).get(ot);Et.onsuccess=function(Ct){return ft(Ct.target.result)},Et.onerror=Or(bt)})},query:(nt=We,Xe=at,function(Qe){return new Promise(function(lt,ot){lt=Gt(lt);var ft,bt,Et,Ct,Ut=Qe.trans,xt=Qe.values,Dt=Qe.limit,St=Qe.query,At=(At=Qe.direction)!=null?At:"next",jt=Dt===1/0?void 0:Dt,qt=St.index,St=St.range,Ut=Ut.objectStore(Ye),Ut=qt.isPrimaryKey?Ut:Ut.index(qt.name),qt=V(St);if(Dt===0)return lt({result:[]});Xe?(St={query:qt,count:jt,direction:At},(ft=xt?Ut.getAll(St):Ut.getAllKeys(St)).onsuccess=function(Wt){return lt({result:Wt.target.result})},ft.onerror=Or(ot)):nt&&At==="next"?((ft=xt?Ut.getAll(qt,jt):Ut.getAllKeys(qt,jt)).onsuccess=function(Wt){return lt({result:Wt.target.result})},ft.onerror=Or(ot)):(bt=0,Et=!xt&&"openKeyCursor"in Ut?Ut.openKeyCursor(qt,At):Ut.openCursor(qt,At),Ct=[],Et.onsuccess=function(){var Wt=Et.result;return!Wt||(Ct.push(xt?Wt.value:Wt.primaryKey),++bt===Dt)?lt({result:Ct}):void Wt.continue()},Et.onerror=Or(ot))})}),openCursor:function(Qe){var lt=Qe.trans,ot=Qe.values,ft=Qe.query,bt=Qe.reverse,Et=Qe.unique;return new Promise(function(Ct,xt){Ct=Gt(Ct);var jt=ft.index,Dt=ft.range,At=lt.objectStore(Ye),At=jt.isPrimaryKey?At:At.index(jt.name),jt=bt?Et?"prevunique":"prev":Et?"nextunique":"next",St=!ot&&"openKeyCursor"in At?At.openKeyCursor(V(Dt),jt):At.openCursor(V(Dt),jt);St.onerror=Or(xt),St.onsuccess=Gt(function(Ut){var qt,Wt,Qt,L,k=St.result;k?(k.___id=++Ji,k.done=!1,qt=k.continue.bind(k),Wt=(Wt=k.continuePrimaryKey)&&Wt.bind(k),Qt=k.advance.bind(k),L=function(){throw new Error("Cursor not stopped")},k.trans=lt,k.stop=k.continue=k.continuePrimaryKey=k.advance=function(){throw new Error("Cursor not started")},k.fail=Gt(xt),k.next=function(){var F=this,se=1;return this.start(function(){return se--?F.continue():F.stop()}).then(function(){return F})},k.start=function(F){function se(){if(St.result)try{F()}catch(tt){k.fail(tt)}else k.done=!0,k.start=function(){throw new Error("Cursor behind last entry")},k.stop()}var ke=new Promise(function(tt,Nt){tt=Gt(tt),St.onerror=Or(Nt),k.fail=Nt,k.stop=function(fr){k.stop=k.continue=k.continuePrimaryKey=k.advance=L,tt(fr)}});return St.onsuccess=Gt(function(tt){St.onsuccess=se,se()}),k.continue=qt,k.continuePrimaryKey=Wt,k.advance=Qt,se(),ke},Ct(k)):Ct(null)},xt)})},count:function(Qe){var lt=Qe.query,ot=Qe.trans,ft=lt.index,bt=lt.range;return new Promise(function(Et,Ct){var xt=ot.objectStore(Ye),xt=ft.isPrimaryKey?xt:xt.index(ft.name),Dt=V(bt),Dt=Dt?xt.count(Dt):xt.count();Dt.onsuccess=Gt(function(At){return Et(At.target.result)}),Dt.onerror=Or(Ct)})}}}pe=Te,Ne=vi((Te=v).objectStoreNames),Je=0<Ne.length?pe.objectStore(Ne[0]):{};var pe,Te={schema:{name:Te.name,tables:Ne.map(function(ze){return pe.objectStore(ze)}).map(function(ze){var nt=ze.keyPath,Xe=ze.autoIncrement,Qe=u(nt),Ye={},Qe={name:ze.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:nt==null,compound:Qe,keyPath:nt,autoIncrement:Xe,unique:!0,extractKey:Ts(nt)},indexes:vi(ze.indexNames).map(function(lt){return ze.index(lt)}).map(function(bt){var Et=bt.name,ot=bt.unique,ft=bt.multiEntry,bt=bt.keyPath,Et={name:Et,compound:u(bt),keyPath:bt,unique:ot,multiEntry:ft,extractKey:Ts(bt)};return Ye[is(bt)]=Et}),getIndexByKeyPath:function(lt){return Ye[is(lt)]}};return Ye[":id"]=Qe.primaryKey,nt!=null&&(Ye[is(nt)]=Qe.primaryKey),Qe})},hasGetAll:0<Ne.length&&"getAll"in Je&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in Je},Ne=Te.schema,We=Te.hasGetAll,at=Te.hasIdb3Features,Je=Ne.tables.map(re),Ge={};return Je.forEach(function(ze){return Ge[ze.name]=ze}),{stack:"dbcore",transaction:v.transaction.bind(v),table:function(ze){if(Ge[ze])return Ge[ze];throw new Error("Table '".concat(ze,"' not found"))},MIN_KEY:-1/0,MAX_KEY:ss(P),schema:Ne}}function Si(v,P,j,V){return j=j.IDBKeyRange,P=Yi(P,j,V),{dbcore:v.dbcore.reduce(function(re,pe){return pe=pe.create,n(n({},re),pe(re))},P)}}function Es(v,P){var j=P.db,j=Si(v._middlewares,j,v._deps,P);v.core=j.dbcore,v.tables.forEach(function(V){var re=V.name;v.core.schema.tables.some(function(pe){return pe.name===re})&&(V.core=v.core.table(re),v[re]instanceof v.Table)&&(v[re].core=V.core)})}function as(v,P,j,V){j.forEach(function(re){var pe=V[re];P.forEach(function(Te){var Ne=function We(at,Je){return w(at,Je)||(at=d(at))&&We(at,Je)}(Te,re);(!Ne||"value"in Ne&&Ne.value===void 0)&&(Te===v.Transaction.prototype||Te instanceof v.Transaction?O(Te,re,{get:function(){return this.table(re)},set:function(We){S(this,re,{value:We,writable:!0,configurable:!0,enumerable:!0})}}):Te[re]=new v.Table(re,pe))})})}function _s(v,P){P.forEach(function(j){for(var V in j)j[V]instanceof v.Table&&delete j[V]})}function Xi(v,P){return v._cfg.version-P._cfg.version}function Qi(v,P,j,V){var re=v._dbSchema,pe=(j.objectStoreNames.contains("$meta")&&!re.$meta&&(re.$meta=It("$meta",Ei("")[0],[]),v._storeNames.push("$meta")),v._createTransaction("readwrite",v._storeNames,re)),Te=(pe.create(j),pe._completion.catch(V),pe._reject.bind(pe)),Ne=_t.transless||_t;Gr(function(){if(_t.trans=pe,_t.transless=Ne,P!==0)return Es(v,j),at=P,((We=pe).storeNames.includes("$meta")?We.table("$meta").get("version").then(function(Je){return Je??at}):be.resolve(at)).then(function(Qe){var Ge=v,ze=Qe,nt=pe,Xe=j,Ye=[],Qe=Ge._versions,lt=Ge._dbSchema=ws(0,Ge.idbdb,Xe);return(Qe=Qe.filter(function(ot){return ot._cfg.version>=ze})).length===0?be.resolve():(Qe.forEach(function(ot){Ye.push(function(){var ft,bt,Et,Ct=lt,xt=ot._cfg.dbschema,Dt=(Wn(Ge,Ct,Xe),Wn(Ge,xt,Xe),lt=Ge._dbSchema=xt,xs(Ct,xt)),At=(Dt.add.forEach(function(jt){Ys(Xe,jt[0],jt[1].primKey,jt[1].indexes)}),Dt.change.forEach(function(jt){if(jt.recreate)throw new je.Upgrade("Not yet support for changing primary key");var St=Xe.objectStore(jt.name);jt.add.forEach(function(Ut){return Ps(St,Ut)}),jt.change.forEach(function(Ut){St.deleteIndex(Ut.name),Ps(St,Ut)}),jt.del.forEach(function(Ut){return St.deleteIndex(Ut)})}),ot._cfg.contentUpgrade);if(At&&ot._cfg.version>ze)return Es(Ge,Xe),nt._memoizedTables={},ft=R(xt),Dt.del.forEach(function(jt){ft[jt]=Ct[jt]}),_s(Ge,[Ge.Transaction.prototype]),as(Ge,[Ge.Transaction.prototype],a(ft),ft),nt.schema=ft,(bt=he(At))&&an(),xt=be.follow(function(){var jt;(Et=At(nt))&&bt&&(jt=Fr.bind(null,null),Et.then(jt,jt))}),Et&&typeof Et.then=="function"?be.resolve(Et):xt.then(function(){return Et})}),Ye.push(function(ft){var bt,Et,Ct=ot._cfg.dbschema;bt=Ct,Et=ft,[].slice.call(Et.db.objectStoreNames).forEach(function(xt){return bt[xt]==null&&Et.db.deleteObjectStore(xt)}),_s(Ge,[Ge.Transaction.prototype]),as(Ge,[Ge.Transaction.prototype],Ge._storeNames,Ge._dbSchema),nt.schema=Ge._dbSchema}),Ye.push(function(ft){Ge.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(Ge.idbdb.version/10)===ot._cfg.version?(Ge.idbdb.deleteObjectStore("$meta"),delete Ge._dbSchema.$meta,Ge._storeNames=Ge._storeNames.filter(function(bt){return bt!=="$meta"})):ft.objectStore("$meta").put(ot._cfg.version,"version"))})}),function ot(){return Ye.length?be.resolve(Ye.shift()(nt.idbtrans)).then(ot):be.resolve()}().then(function(){Xs(lt,Xe)}))}).catch(Te);var We,at;a(re).forEach(function(Je){Ys(j,Je,re[Je].primKey,re[Je].indexes)}),Es(v,j),be.follow(function(){return v.on.populate.fire(pe)}).catch(Te)})}function Ti(v,P){Xs(v._dbSchema,P),P.db.version%10!=0||P.objectStoreNames.contains("$meta")||P.db.createObjectStore("$meta").add(Math.ceil(P.db.version/10-1),"version");var j=ws(0,v.idbdb,P);Wn(v,v._dbSchema,P);for(var V=0,re=xs(j,v._dbSchema).change;V<re.length;V++){var pe=(Te=>{if(Te.change.length||Te.recreate)return console.warn("Unable to patch indexes of table ".concat(Te.name," because it has changes on the type of index or primary key.")),{value:void 0};var Ne=P.objectStore(Te.name);Te.add.forEach(function(We){ht&&console.debug("Dexie upgrade patch: Creating missing index ".concat(Te.name,".").concat(We.src)),Ps(Ne,We)})})(re[V]);if(typeof pe=="object")return pe.value}}function xs(v,P){var j,V={del:[],add:[],change:[]};for(j in v)P[j]||V.del.push(j);for(j in P){var re=v[j],pe=P[j];if(re){var Te={name:j,def:pe,recreate:!1,del:[],add:[],change:[]};if(""+(re.primKey.keyPath||"")!=""+(pe.primKey.keyPath||"")||re.primKey.auto!==pe.primKey.auto)Te.recreate=!0,V.change.push(Te);else{var Ne=re.idxByName,We=pe.idxByName,at=void 0;for(at in Ne)We[at]||Te.del.push(at);for(at in We){var Je=Ne[at],Ge=We[at];Je?Je.src!==Ge.src&&Te.change.push(Ge):Te.add.push(Ge)}(0<Te.del.length||0<Te.add.length||0<Te.change.length)&&V.change.push(Te)}}else V.add.push([j,pe])}return V}function Ys(v,P,j,V){var re=v.db.createObjectStore(P,j.keyPath?{keyPath:j.keyPath,autoIncrement:j.auto}:{autoIncrement:j.auto});V.forEach(function(pe){return Ps(re,pe)})}function Xs(v,P){a(v).forEach(function(j){P.db.objectStoreNames.contains(j)||(ht&&console.debug("Dexie: Creating missing table",j),Ys(P,j,v[j].primKey,v[j].indexes))})}function Ps(v,P){v.createIndex(P.name,P.keyPath,{unique:P.unique,multiEntry:P.multi})}function ws(v,P,j){var V={};return T(P.objectStoreNames,0).forEach(function(re){for(var pe=j.objectStore(re),Te=zs(Js(at=pe.keyPath),at||"",!0,!1,!!pe.autoIncrement,at&&typeof at!="string",!0),Ne=[],We=0;We<pe.indexNames.length;++We){var Je=pe.index(pe.indexNames[We]),at=Je.keyPath,Je=zs(Je.name,at,!!Je.unique,!!Je.multiEntry,!1,at&&typeof at!="string",!1);Ne.push(Je)}V[re]=It(re,Te,Ne)}),V}function Wn(v,P,j){for(var V=j.db.objectStoreNames,re=0;re<V.length;++re){var pe=V[re],Te=j.objectStore(pe);v._hasGetAll="getAll"in Te;for(var Ne=0;Ne<Te.indexNames.length;++Ne){var We,at=Te.indexNames[Ne],Je=Te.index(at).keyPath,Je=typeof Je=="string"?Je:"["+T(Je).join("+")+"]";P[pe]&&(We=P[pe].idxByName[Je])&&(We.name=at,delete P[pe].idxByName[Je],P[pe].idxByName[at]=We)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(v._hasGetAll=!1)}function Ei(v){return v.split(",").map(function(P,j){var re=P.split(":"),V=(V=re[1])==null?void 0:V.trim(),re=(P=re[0].trim()).replace(/([&*]|\+\+)/g,""),pe=/^\[/.test(re)?re.match(/^\[(.*)\]$/)[1].split("+"):re;return zs(re,pe||null,/\&/.test(P),/\*/.test(P),/\+\+/.test(P),u(pe),j===0,V)})}wn.prototype._createTableSchema=It,wn.prototype._parseIndexSyntax=Ei,wn.prototype._parseStoresSpec=function(v,P){var j=this;a(v).forEach(function(V){if(v[V]!==null){var re=j._parseIndexSyntax(v[V]),pe=re.shift();if(!pe)throw new je.Schema("Invalid schema for table "+V+": "+v[V]);if(pe.unique=!0,pe.multi)throw new je.Schema("Primary key cannot be multiEntry*");re.forEach(function(Te){if(Te.auto)throw new je.Schema("Only primary key can be marked as autoIncrement (++)");if(!Te.keyPath)throw new je.Schema("Index must have a name and cannot be an empty string")}),pe=j._createTableSchema(V,pe,re),P[V]=pe}})},wn.prototype.stores=function(j){var P=this.db,j=(this._cfg.storesSource=this._cfg.storesSource?f(this._cfg.storesSource,j):j,P._versions),V={},re={};return j.forEach(function(pe){f(V,pe._cfg.storesSource),re=pe._cfg.dbschema={},pe._parseStoresSpec(V,re)}),P._dbSchema=re,_s(P,[P._allTables,P,P.Transaction.prototype]),as(P,[P._allTables,P,P.Transaction.prototype,this._cfg.tables],a(re),re),P._storeNames=a(re),this},wn.prototype.upgrade=function(v){return this._cfg.contentUpgrade=gt(this._cfg.contentUpgrade||Ze,v),this};var Zi=wn;function wn(){}var os=(()=>{var v,P,j;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(v=new Set,P=new FinalizationRegistry(function(V){v.delete(V)}),{toArray:function(){return Array.from(v).map(function(V){return V.deref()}).filter(function(V){return V!==void 0})},add:function(V){var re=new WeakRef(V._novip);v.add(re),P.register(V._novip,re,re),v.size>V._options.maxConnections&&(re=v.values().next().value,v.delete(re),P.unregister(re))},remove:function(V){if(V)for(var re=v.values(),pe=re.next();!pe.done;){var Te=pe.value;if(Te.deref()===V._novip)return v.delete(Te),void P.unregister(Te);pe=re.next()}}}):(j=[],{toArray:function(){return j},add:function(V){j.push(V._novip)},remove:function(V){V&&(V=j.indexOf(V._novip))!==-1&&j.splice(V,1)}})})();function Qs(v,P){var j=v._dbNamesDB;return j||(j=v._dbNamesDB=new tn(zr,{addons:[],indexedDB:v,IDBKeyRange:P})).version(1).stores({dbnames:"name"}),j.table("dbnames")}function As(v){return v&&typeof v.databases=="function"}function Zs(v){return Gr(function(){return _t.letThrough=!0,v()})}function ei(v){return!("from"in v)}var _r=function(v,P){var j;if(!this)return j=new _r,v&&"d"in v&&f(j,v),j;f(this,arguments.length?{d:1,from:v,to:1<arguments.length?P:v}:{d:0})};function ls(v,P,j){var V=Jt(P,j);if(!isNaN(V)){if(0<V)throw RangeError();if(ei(v))return f(v,{from:P,to:j,d:1});var V=v.l,re=v.r;if(Jt(j,v.from)<0)return V?ls(V,P,j):v.l={from:P,to:j,d:1,l:null,r:null},H(v);if(0<Jt(P,v.to))return re?ls(re,P,j):v.r={from:P,to:j,d:1,l:null,r:null},H(v);Jt(P,v.from)<0&&(v.from=P,v.l=null,v.d=re?re.d+1:1),0<Jt(j,v.to)&&(v.to=j,v.r=null,v.d=v.l?v.l.d+1:1),P=!v.r,V&&!v.l&&cn(v,V),re&&P&&cn(v,re)}}function cn(v,P){ei(P)||function j(V,re){var pe=re.from,Te=re.l,Ne=re.r;ls(V,pe,re.to),Te&&j(V,Te),Ne&&j(V,Ne)}(v,P)}function ti(v,P){var j=Cs(P),V=j.next();if(!V.done)for(var re=V.value,pe=Cs(v),Te=pe.next(re.from),Ne=Te.value;!V.done&&!Te.done;){if(Jt(Ne.from,re.to)<=0&&0<=Jt(Ne.to,re.from))return!0;Jt(re.from,Ne.from)<0?re=(V=j.next(Ne.from)).value:Ne=(Te=pe.next(re.from)).value}return!1}function Cs(v){var P=ei(v)?null:{s:0,n:v};return{next:function(j){for(var V=0<arguments.length;P;)switch(P.s){case 0:if(P.s=1,V)for(;P.n.l&&Jt(j,P.n.from)<0;)P={up:P,n:P.n.l,s:1};else for(;P.n.l;)P={up:P,n:P.n.l,s:1};case 1:if(P.s=2,!V||Jt(j,P.n.to)<=0)return{value:P.n,done:!1};case 2:if(P.n.r){P.s=3,P={up:P,n:P.n.r,s:0};continue}case 3:P=P.up}return{done:!0}}}}function H(v){var P,j,V,re=(((re=v.r)==null?void 0:re.d)||0)-(((re=v.l)==null?void 0:re.d)||0),re=1<re?"r":re<-1?"l":"";re&&(P=re=="r"?"l":"r",j=n({},v),V=v[re],v.from=V.from,v.to=V.to,v[re]=V[re],j[re]=V[P],(v[P]=j).d=l(j)),v.d=l(v)}function l(j){var P=j.r,j=j.l;return(P?j?Math.max(P.d,j.d):P.d:j?j.d:0)+1}function s(v,P){return a(P).forEach(function(j){v[j]?cn(v[j],P[j]):v[j]=function V(re){var pe,Te,Ne={};for(pe in re)m(re,pe)&&(Te=re[pe],Ne[pe]=!Te||typeof Te!="object"||N.has(Te.constructor)?Te:V(Te));return Ne}(P[j])}),v}function c(v,P){return v.all||P.all||Object.keys(v).some(function(j){return P[j]&&ti(P[j],v[j])})}b(_r.prototype,((oe={add:function(v){return cn(this,v),this},addKey:function(v){return ls(this,v,v),this},addKeys:function(v){var P=this;return v.forEach(function(j){return ls(P,j,j)}),this},hasKey:function(v){var P=Cs(this).next(v).value;return P&&Jt(P.from,v)<=0&&0<=Jt(P.to,v)}})[Ce]=function(){return Cs(this)},oe));var y={},A={},Q=!1;function ue(v){s(A,v),Q||(Q=!0,setTimeout(function(){Q=!1,Pe(A,!(A={}))},0))}function Pe(v,P){P===void 0&&(P=!1);var j=new Set;if(v.all)for(var V=0,re=Object.values(y);V<re.length;V++)Be(Ne=re[V],v,j,P);else for(var pe in v){var Te,Ne,pe=/^idb\:\/\/(.*)\/(.*)\//.exec(pe);pe&&(Te=pe[1],pe=pe[2],Ne=y["idb://".concat(Te,"/").concat(pe)])&&Be(Ne,v,j,P)}j.forEach(function(We){return We()})}function Be(v,P,j,V){for(var re=[],pe=0,Te=Object.entries(v.queries.query);pe<Te.length;pe++){for(var Ne=Te[pe],We=Ne[0],at=[],Je=0,Ge=Ne[1];Je<Ge.length;Je++){var ze=Ge[Je];c(P,ze.obsSet)?ze.subscribers.forEach(function(Qe){return j.add(Qe)}):V&&at.push(ze)}V&&re.push([We,at])}if(V)for(var nt=0,Xe=re;nt<Xe.length;nt++){var Ye=Xe[nt],We=Ye[0],at=Ye[1];v.queries.query[We]=at}}function qe(v){var P=v._state,j=v._deps.indexedDB;if(P.isBeingOpened||v.idbdb)return P.dbReadyPromise.then(function(){return P.dbOpenError?yr(P.dbOpenError):v});P.isBeingOpened=!0,P.dbOpenError=null,P.openComplete=!1;var V=P.openCanceller,re=Math.round(10*v.verno),pe=!1;function Te(){if(P.openCanceller!==V)throw new je.DatabaseClosed("db.open() was cancelled")}function Ne(){return new be(function(ze,nt){if(Te(),!j)throw new je.MissingAPI;var Xe=v.name,Ye=P.autoSchema||!re?j.open(Xe):j.open(Xe,re);if(!Ye)throw new je.MissingAPI;Ye.onerror=Or(nt),Ye.onblocked=Gt(v._fireOnBlocked),Ye.onupgradeneeded=Gt(function(Qe){var lt;Je=Ye.transaction,P.autoSchema&&!v._options.allowEmptyDB?(Ye.onerror=Pn,Je.abort(),Ye.result.close(),(lt=j.deleteDatabase(Xe)).onsuccess=lt.onerror=Gt(function(){nt(new je.NoSuchDatabase("Database ".concat(Xe," doesnt exist")))})):(Je.onerror=Or(nt),lt=Qe.oldVersion>Math.pow(2,62)?0:Qe.oldVersion,Ge=lt<1,v.idbdb=Ye.result,pe&&Ti(v,Je),Qi(v,lt/10,Je,nt))},nt),Ye.onsuccess=Gt(function(){Je=null;var Qe,lt,ot,ft,bt,Et,Ct=v.idbdb=Ye.result,xt=T(Ct.objectStoreNames);if(0<xt.length)try{var Dt=Ct.transaction((bt=xt).length===1?bt[0]:bt,"readonly");if(P.autoSchema)Et=Ct,ft=Dt,(ot=v).verno=Et.version/10,ft=ot._dbSchema=ws(0,Et,ft),ot._storeNames=T(Et.objectStoreNames,0),as(ot,[ot._allTables],a(ft),ft);else if(Wn(v,v._dbSchema,Dt),lt=Dt,((lt=xs(ws(0,(Qe=v).idbdb,lt),Qe._dbSchema)).add.length||lt.change.some(function(At){return At.add.length||At.change.length}))&&!pe)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Ct.close(),re=Ct.version+1,pe=!0,ze(Ne());Es(v,Dt)}catch{}os.add(v),Ct.onversionchange=Gt(function(At){P.vcFired=!0,v.on("versionchange").fire(At)}),Ct.onclose=Gt(function(){v.close({disableAutoOpen:!1})}),Ge&&(xt=v._deps,bt=Xe,As(Et=xt.indexedDB)||bt===zr||Qs(Et,xt.IDBKeyRange).put({name:bt}).catch(Ze)),ze()},nt)}).catch(function(ze){switch(ze==null?void 0:ze.name){case"UnknownError":if(0<P.PR1398_maxLoop)return P.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),Ne();break;case"VersionError":if(0<re)return re=0,Ne()}return be.reject(ze)})}var We,at=P.dbReadyResolve,Je=null,Ge=!1;return be.race([V,(typeof navigator>"u"?be.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(ze){function nt(){return indexedDB.databases().finally(ze)}We=setInterval(nt,100),nt()}).finally(function(){return clearInterval(We)}):Promise.resolve()).then(Ne)]).then(function(){return Te(),P.onReadyBeingFired=[],be.resolve(Zs(function(){return v.on.ready.fire(v.vip)})).then(function ze(){var nt;if(0<P.onReadyBeingFired.length)return nt=P.onReadyBeingFired.reduce(gt,Ze),P.onReadyBeingFired=[],be.resolve(Zs(function(){return nt(v.vip)})).then(ze)})}).finally(function(){P.openCanceller===V&&(P.onReadyBeingFired=null,P.isBeingOpened=!1)}).catch(function(ze){P.dbOpenError=ze;try{Je&&Je.abort()}catch{}return V===P.openCanceller&&v._close(),yr(ze)}).finally(function(){P.openComplete=!0,at()}).then(function(){var ze;return Ge&&(ze={},v.tables.forEach(function(nt){nt.schema.indexes.forEach(function(Xe){Xe.name&&(ze["idb://".concat(v.name,"/").concat(nt.name,"/").concat(Xe.name)]=new _r(-1/0,[[[]]]))}),ze["idb://".concat(v.name,"/").concat(nt.name,"/")]=ze["idb://".concat(v.name,"/").concat(nt.name,"/:dels")]=new _r(-1/0,[[[]]])}),en(Kn).fire(ze),Pe(ze,!0)),v})}function ct(v){function P(pe){return v.next(pe)}var j=re(P),V=re(function(pe){return v.throw(pe)});function re(pe){return function(Ne){var Ne=pe(Ne),We=Ne.value;return Ne.done?We:We&&typeof We.then=="function"?We.then(j,V):u(We)?Promise.all(We).then(j,V):j(We)}}return re(P)()}function vt(v,P,j){for(var V=u(v)?v.slice():[v],re=0;re<j;++re)V.push(P);return V}var wt={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(v){return n(n({},v),{table:function(V){var j=v.table(V),V=j.schema,re=Object.create(null),pe=[];function Te(ze,nt,Xe){var ot=is(ze),Ye=re[ot]=re[ot]||[],Qe=ze==null?0:typeof ze=="string"?1:ze.length,lt=0<nt,ot=n(n({},Xe),{name:lt?"".concat(ot,"(virtual-from:").concat(Xe.name,")"):Xe.name,lowLevelIndex:Xe,isVirtual:lt,keyTail:nt,keyLength:Qe,extractKey:Ts(ze),unique:!lt&&Xe.unique});return Ye.push(ot),ot.isPrimaryKey||pe.push(ot),1<Qe&&Te(Qe===2?ze[0]:ze.slice(0,Qe-1),nt+1,Xe),Ye.sort(function(ft,bt){return ft.keyTail-bt.keyTail}),ot}var Ne=Te(V.primaryKey.keyPath,0,V.primaryKey);re[":id"]=[Ne];for(var We=0,at=V.indexes;We<at.length;We++){var Je=at[We];Te(Je.keyPath,0,Je)}function Ge(ze){var nt,Xe=ze.query.index;return Xe.isVirtual?n(n({},ze),{query:{index:Xe.lowLevelIndex,range:(nt=ze.query.range,Xe=Xe.keyTail,{type:nt.type===1?2:nt.type,lower:vt(nt.lower,nt.lowerOpen?v.MAX_KEY:v.MIN_KEY,Xe),lowerOpen:!0,upper:vt(nt.upper,nt.upperOpen?v.MIN_KEY:v.MAX_KEY,Xe),upperOpen:!0})}}):ze}return n(n({},j),{schema:n(n({},V),{primaryKey:Ne,indexes:pe,getIndexByKeyPath:function(ze){return(ze=re[is(ze)])&&ze[0]}}),count:function(ze){return j.count(Ge(ze))},query:function(ze){return j.query(Ge(ze))},openCursor:function(ze){var nt=ze.query.index,Xe=nt.keyTail,Ye=nt.keyLength;return nt.isVirtual?j.openCursor(Ge(ze)).then(function(lt){return lt&&Qe(lt)}):j.openCursor(ze);function Qe(lt){return Object.create(lt,{continue:{value:function(ot){ot!=null?lt.continue(vt(ot,ze.reverse?v.MAX_KEY:v.MIN_KEY,Xe)):ze.unique?lt.continue(lt.key.slice(0,Ye).concat(ze.reverse?v.MIN_KEY:v.MAX_KEY,Xe)):lt.continue()}},continuePrimaryKey:{value:function(ot,ft){lt.continuePrimaryKey(vt(ot,v.MAX_KEY,Xe),ft)}},primaryKey:{get:function(){return lt.primaryKey}},key:{get:function(){var ot=lt.key;return Ye===1?ot[0]:ot.slice(0,Ye)}},value:{get:function(){return lt.value}}})}}})}})}};function Ot(v,P,j,V){return j=j||{},V=V||"",a(v).forEach(function(re){var pe,Te,Ne;m(P,re)?(pe=v[re],Te=P[re],typeof pe=="object"&&typeof Te=="object"&&pe&&Te?(Ne=xe(pe))!==xe(Te)?j[V+re]=P[re]:Ne==="Object"?Ot(pe,Te,j,V+re+"."):pe!==Te&&(j[V+re]=P[re]):pe!==Te&&(j[V+re]=P[re])):j[V+re]=void 0}),a(P).forEach(function(re){m(v,re)||(j[V+re]=P[re])}),j}function Ht(v,P){return P.type==="delete"?P.keys:P.keys||P.values.map(v.extractKey)}var cr={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(v){return n(n({},v),{table:function(P){var j=v.table(P),V=j.schema.primaryKey;return n(n({},j),{mutate:function(re){var pe=_t.trans,Te=pe.table(P).hook,Ne=Te.deleting,We=Te.creating,at=Te.updating;switch(re.type){case"add":if(We.fire===Ze)break;return pe._promise("readwrite",function(){return Je(re)},!0);case"put":if(We.fire===Ze&&at.fire===Ze)break;return pe._promise("readwrite",function(){return Je(re)},!0);case"delete":if(Ne.fire===Ze)break;return pe._promise("readwrite",function(){return Je(re)},!0);case"deleteRange":if(Ne.fire===Ze)break;return pe._promise("readwrite",function(){return function Ge(ze,nt,Xe){return j.query({trans:ze,values:!1,query:{index:V,range:nt},limit:Xe}).then(function(Ye){var Qe=Ye.result;return Je({type:"delete",keys:Qe,trans:ze}).then(function(lt){return 0<lt.numFailures?Promise.reject(lt.failures[0]):Qe.length<Xe?{failures:[],numFailures:0,lastResult:void 0}:Ge(ze,n(n({},nt),{lower:Qe[Qe.length-1],lowerOpen:!0}),Xe)})})}(re.trans,re.range,1e4)},!0)}return j.mutate(re);function Je(Ge){var ze,nt,Xe,Ye=_t.trans,Qe=Ge.keys||Ht(V,Ge);if(Qe)return(Ge=Ge.type==="add"||Ge.type==="put"?n(n({},Ge),{keys:Qe}):n({},Ge)).type!=="delete"&&(Ge.values=i([],Ge.values)),Ge.keys&&(Ge.keys=i([],Ge.keys)),ze=j,Xe=Qe,((nt=Ge).type==="add"?Promise.resolve([]):ze.getMany({trans:nt.trans,keys:Xe,cache:"immutable"})).then(function(lt){var ot=Qe.map(function(ft,bt){var Et,Ct,xt,Dt=lt[bt],At={onerror:null,onsuccess:null};return Ge.type==="delete"?Ne.fire.call(At,ft,Dt,Ye):Ge.type==="add"||Dt===void 0?(Et=We.fire.call(At,ft,Ge.values[bt],Ye),ft==null&&Et!=null&&(Ge.keys[bt]=ft=Et,V.outbound||I(Ge.values[bt],V.keyPath,ft))):(Et=Ot(Dt,Ge.values[bt]),(Ct=at.fire.call(At,Et,ft,Dt,Ye))&&(xt=Ge.values[bt],Object.keys(Ct).forEach(function(jt){m(xt,jt)?xt[jt]=Ct[jt]:I(xt,jt,Ct[jt])}))),At});return j.mutate(Ge).then(function(ft){for(var bt=ft.failures,Et=ft.results,Ct=ft.numFailures,ft=ft.lastResult,xt=0;xt<Qe.length;++xt){var Dt=(Et||Qe)[xt],At=ot[xt];Dt==null?At.onerror&&At.onerror(bt[xt]):At.onsuccess&&At.onsuccess(Ge.type==="put"&&lt[xt]?Ge.values[xt]:Dt)}return{failures:bt,results:Et,numFailures:Ct,lastResult:ft}}).catch(function(ft){return ot.forEach(function(bt){return bt.onerror&&bt.onerror(ft)}),Promise.reject(ft)})});throw new Error("Keys missing")}}})}})}};function $t(v,P,j){try{if(!P||P.keys.length<v.length)return null;for(var V=[],re=0,pe=0;re<P.keys.length&&pe<v.length;++re)Jt(P.keys[re],v[pe])===0&&(V.push(j?ne(P.values[re]):P.values[re]),++pe);return V.length===v.length?V:null}catch{return null}}var lr={stack:"dbcore",level:-1,create:function(v){return{table:function(P){var j=v.table(P);return n(n({},j),{getMany:function(V){var re;return V.cache?(re=$t(V.keys,V.trans._cache,V.cache==="clone"))?be.resolve(re):j.getMany(V).then(function(pe){return V.trans._cache={keys:V.keys,values:V.cache==="clone"?ne(pe):pe},pe}):j.getMany(V)},mutate:function(V){return V.type!=="add"&&(V.trans._cache=null),j.mutate(V)}})}}}};function An(v,P){return v.trans.mode==="readonly"&&!!v.subscr&&!v.trans.explicit&&v.trans.db._options.cache!=="disabled"&&!P.schema.primaryKey.outbound}function un(v,P){switch(v){case"query":return P.values&&!P.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var _i={stack:"dbcore",level:0,name:"Observability",create:function(v){var P=v.schema.name,j=new _r(v.MIN_KEY,v.MAX_KEY);return n(n({},v),{transaction:function(V,re,pe){if(_t.subscr&&re!=="readonly")throw new je.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(_t.querier));return v.transaction(V,re,pe)},table:function(V){function re(Qe){var Ye,Qe=Qe.query;return[Ye=Qe.index,new _r((Ye=(Qe=Qe.range).lower)!=null?Ye:v.MIN_KEY,(Ye=Qe.upper)!=null?Ye:v.MAX_KEY)]}var pe=v.table(V),Te=pe.schema,Ne=Te.primaryKey,We=Te.indexes,at=Ne.extractKey,Je=Ne.outbound,Ge=Ne.autoIncrement&&We.filter(function(Xe){return Xe.compound&&Xe.keyPath.includes(Ne.keyPath)}),ze=n(n({},pe),{mutate:function(Xe){function Ye(St){return St="idb://".concat(P,"/").concat(V,"/").concat(St),bt[St]||(bt[St]=new _r)}var Qe,lt,ot,ft=Xe.trans,bt=Xe.mutatedParts||(Xe.mutatedParts={}),Et=Ye(""),Ct=Ye(":dels"),xt=Xe.type,At=Xe.type==="deleteRange"?[Xe.range]:Xe.type==="delete"?[Xe.keys]:Xe.values.length<50?[Ht(Ne,Xe).filter(function(St){return St}),Xe.values]:[],Dt=At[0],At=At[1],jt=Xe.trans._cache;return u(Dt)?(Et.addKeys(Dt),(xt=xt==="delete"||Dt.length===At.length?$t(Dt,jt):null)||Ct.addKeys(Dt),(xt||At)&&(Qe=Ye,lt=xt,ot=At,Te.indexes.forEach(function(St){var Ut=Qe(St.name||"");function qt(Qt){return Qt!=null?St.extractKey(Qt):null}function Wt(Qt){St.multiEntry&&u(Qt)?Qt.forEach(function(L){return Ut.addKey(L)}):Ut.addKey(Qt)}(lt||ot).forEach(function(Qt,F){var k=lt&&qt(lt[F]),F=ot&&qt(ot[F]);Jt(k,F)!==0&&(k!=null&&Wt(k),F!=null)&&Wt(F)})}))):Dt?(At={from:(jt=Dt.lower)!=null?jt:v.MIN_KEY,to:(xt=Dt.upper)!=null?xt:v.MAX_KEY},Ct.add(At),Et.add(At)):(Et.add(j),Ct.add(j),Te.indexes.forEach(function(St){return Ye(St.name).add(j)})),pe.mutate(Xe).then(function(St){return!Dt||Xe.type!=="add"&&Xe.type!=="put"||(Et.addKeys(St.results),Ge&&Ge.forEach(function(Ut){for(var qt=Xe.values.map(function(k){return Ut.extractKey(k)}),Wt=Ut.keyPath.findIndex(function(k){return k===Ne.keyPath}),Qt=0,L=St.results.length;Qt<L;++Qt)qt[Qt][Wt]=St.results[Qt];Ye(Ut.name).addKeys(qt)})),ft.mutatedParts=s(ft.mutatedParts||{},bt),St})}}),nt={get:function(Xe){return[Ne,new _r(Xe.key)]},getMany:function(Xe){return[Ne,new _r().addKeys(Xe.keys)]},count:re,query:re,openCursor:re};return a(nt).forEach(function(Xe){ze[Xe]=function(Ye){var Qe=_t.subscr,lt=!!Qe,ot=An(_t,pe)&&un(Xe,Ye)?Ye.obsSet={}:Qe;if(lt){var ft,Qe=function(At){return At="idb://".concat(P,"/").concat(V,"/").concat(At),ot[At]||(ot[At]=new _r)},bt=Qe(""),Et=Qe(":dels"),lt=nt[Xe](Ye),Ct=lt[0],lt=lt[1];if((Xe==="query"&&Ct.isPrimaryKey&&!Ye.values?Et:Qe(Ct.name||"")).add(lt),!Ct.isPrimaryKey){if(Xe!=="count")return ft=Xe==="query"&&Je&&Ye.values&&pe.query(n(n({},Ye),{values:!1})),pe[Xe].apply(this,arguments).then(function(At){if(Xe==="query"){if(Je&&Ye.values)return ft.then(function(qt){return qt=qt.result,bt.addKeys(qt),At});var jt=Ye.values?At.result.map(at):At.result;(Ye.values?bt:Et).addKeys(jt)}else{var St,Ut;if(Xe==="openCursor")return Ut=Ye.values,(St=At)&&Object.create(St,{key:{get:function(){return Et.addKey(St.primaryKey),St.key}},primaryKey:{get:function(){var qt=St.primaryKey;return Et.addKey(qt),qt}},value:{get:function(){return Ut&&bt.addKey(St.primaryKey),St.value}}})}return At});Et.add(j)}}return pe[Xe].apply(this,arguments)}}),ze}})}};function ri(v,P,j){var V;return j.numFailures===0?P:P.type==="deleteRange"||(V=P.keys?P.keys.length:"values"in P&&P.values?P.values.length:1,j.numFailures===V)?null:(V=n({},P),u(V.keys)&&(V.keys=V.keys.filter(function(re,pe){return!(pe in j.failures)})),"values"in V&&u(V.values)&&(V.values=V.values.filter(function(re,pe){return!(pe in j.failures)})),V)}function Is(v,P){return j=v,((V=P).lower===void 0||(V.lowerOpen?0<Jt(j,V.lower):0<=Jt(j,V.lower)))&&(j=v,(V=P).upper===void 0||(V.upperOpen?Jt(j,V.upper)<0:Jt(j,V.upper)<=0));var j,V}function ni(v,P,j,V,re,pe){var Te,Ne,We,at,Je,Ge,ze;return!j||j.length===0||(Te=P.query.index,Ne=Te.multiEntry,We=P.query.range,at=V.schema.primaryKey.extractKey,Je=Te.extractKey,Ge=(Te.lowLevelIndex||Te).extractKey,(V=j.reduce(function(nt,Xe){var Ye=nt,Qe=[];if(Xe.type==="add"||Xe.type==="put")for(var lt=new _r,ot=Xe.values.length-1;0<=ot;--ot){var ft,bt=Xe.values[ot],Et=at(bt);!lt.hasKey(Et)&&(ft=Je(bt),Ne&&u(ft)?ft.some(function(jt){return Is(jt,We)}):Is(ft,We))&&(lt.addKey(Et),Qe.push(bt))}switch(Xe.type){case"add":var Ct=new _r().addKeys(P.values?nt.map(function(St){return at(St)}):nt),Ye=nt.concat(P.values?Qe.filter(function(St){return St=at(St),!Ct.hasKey(St)&&(Ct.addKey(St),!0)}):Qe.map(function(St){return at(St)}).filter(function(St){return!Ct.hasKey(St)&&(Ct.addKey(St),!0)}));break;case"put":var xt=new _r().addKeys(Xe.values.map(function(St){return at(St)}));Ye=nt.filter(function(St){return!xt.hasKey(P.values?at(St):St)}).concat(P.values?Qe:Qe.map(function(St){return at(St)}));break;case"delete":var Dt=new _r().addKeys(Xe.keys);Ye=nt.filter(function(St){return!Dt.hasKey(P.values?at(St):St)});break;case"deleteRange":var At=Xe.range;Ye=nt.filter(function(St){return!Is(at(St),At)})}return Ye},v))===v)?v:(ze=function(nt,Xe){return Jt(Ge(nt),Ge(Xe))||Jt(at(nt),at(Xe))},V.sort(P.direction==="prev"||P.direction==="prevunique"?function(nt,Xe){return ze(Xe,nt)}:ze),P.limit&&P.limit<1/0&&(V.length>P.limit?V.length=P.limit:v.length===P.limit&&V.length<P.limit&&(re.dirty=!0)),pe?Object.freeze(V):V)}function si(v,P){return Jt(v.lower,P.lower)===0&&Jt(v.upper,P.upper)===0&&!!v.lowerOpen==!!P.lowerOpen&&!!v.upperOpen==!!P.upperOpen}function xi(v,P){return((j,V,re,pe)=>{if(j===void 0)return V!==void 0?-1:0;if(V===void 0)return 1;if((j=Jt(j,V))===0){if(re&&pe)return 0;if(re)return 1;if(pe)return-1}return j})(v.lower,P.lower,v.lowerOpen,P.lowerOpen)<=0&&0<=((j,V,re,pe)=>{if(j===void 0)return V!==void 0?1:0;if(V===void 0)return-1;if((j=Jt(j,V))===0){if(re&&pe)return 0;if(re)return-1;if(pe)return 1}return j})(v.upper,P.upper,v.upperOpen,P.upperOpen)}function Pi(v,P,j,V){v.subscribers.add(j),V.addEventListener("abort",function(){var re,pe;v.subscribers.delete(j),v.subscribers.size===0&&(re=v,pe=P,setTimeout(function(){re.subscribers.size===0&&ce(pe,re)},3e3))})}var wi={stack:"dbcore",level:0,name:"Cache",create:function(v){var P=v.schema.name;return n(n({},v),{transaction:function(j,V,re){var pe,Te,Ne=v.transaction(j,V,re);return V==="readwrite"&&(re=(pe=new AbortController).signal,Ne.addEventListener("abort",(Te=function(We){return function(){if(pe.abort(),V==="readwrite"){for(var at=new Set,Je=0,Ge=j;Je<Ge.length;Je++){var ze=Ge[Je],nt=y["idb://".concat(P,"/").concat(ze)];if(nt){var Xe=v.table(ze),Ye=nt.optimisticOps.filter(function(St){return St.trans===Ne});if(Ne._explicit&&We&&Ne.mutatedParts)for(var Qe=0,lt=Object.values(nt.queries.query);Qe<lt.length;Qe++)for(var ot=0,ft=(Ct=lt[Qe]).slice();ot<ft.length;ot++)c((xt=ft[ot]).obsSet,Ne.mutatedParts)&&(ce(Ct,xt),xt.subscribers.forEach(function(St){return at.add(St)}));else if(0<Ye.length){nt.optimisticOps=nt.optimisticOps.filter(function(St){return St.trans!==Ne});for(var bt=0,Et=Object.values(nt.queries.query);bt<Et.length;bt++)for(var Ct,xt,Dt,At=0,jt=(Ct=Et[bt]).slice();At<jt.length;At++)(xt=jt[At]).res!=null&&Ne.mutatedParts&&(We&&!xt.dirty?(Dt=Object.isFrozen(xt.res),Dt=ni(xt.res,xt.req,Ye,Xe,xt,Dt),xt.dirty?(ce(Ct,xt),xt.subscribers.forEach(function(St){return at.add(St)})):Dt!==xt.res&&(xt.res=Dt,xt.promise=be.resolve({result:Dt}))):(xt.dirty&&ce(Ct,xt),xt.subscribers.forEach(function(St){return at.add(St)})))}}}at.forEach(function(St){return St()})}}})(!1),{signal:re}),Ne.addEventListener("error",Te(!1),{signal:re}),Ne.addEventListener("complete",Te(!0),{signal:re})),Ne},table:function(j){var V=v.table(j),re=V.schema.primaryKey;return n(n({},V),{mutate:function(pe){var Te,Ne=_t.trans;return!re.outbound&&Ne.db._options.cache!=="disabled"&&!Ne.explicit&&Ne.idbtrans.mode==="readwrite"&&(Te=y["idb://".concat(P,"/").concat(j)])?(Ne=V.mutate(pe),pe.type!=="add"&&pe.type!=="put"||!(50<=pe.values.length||Ht(re,pe).some(function(We){return We==null}))?(Te.optimisticOps.push(pe),pe.mutatedParts&&ue(pe.mutatedParts),Ne.then(function(We){0<We.numFailures&&(ce(Te.optimisticOps,pe),(We=ri(0,pe,We))&&Te.optimisticOps.push(We),pe.mutatedParts)&&ue(pe.mutatedParts)}),Ne.catch(function(){ce(Te.optimisticOps,pe),pe.mutatedParts&&ue(pe.mutatedParts)})):Ne.then(function(We){var at=ri(0,n(n({},pe),{values:pe.values.map(function(Je,Ge){var ze;return We.failures[Ge]?Je:(I(ze=(ze=re.keyPath)!=null&&ze.includes(".")?ne(Je):n({},Je),re.keyPath,We.results[Ge]),ze)})}),We);Te.optimisticOps.push(at),queueMicrotask(function(){return pe.mutatedParts&&ue(pe.mutatedParts)})}),Ne):V.mutate(pe)},query:function(pe){var Te,Ne,We,at,Je,Ge,ze;return An(_t,V)&&un("query",pe)?(Te=((We=_t.trans)==null?void 0:We.db._options.cache)==="immutable",Ne=(We=_t).requery,We=We.signal,Ge=((nt,Xe,Ye,Qe)=>{var lt=y["idb://".concat(nt,"/").concat(Xe)];if(!lt)return[];if(!(nt=lt.queries[Ye]))return[null,!1,lt,null];var ot=nt[(Qe.query?Qe.query.index.name:null)||""];if(!ot)return[null,!1,lt,null];switch(Ye){case"query":var ft=(bt=Qe.direction)!=null?bt:"next",bt=ot.find(function(Et){var Ct;return Et.req.limit===Qe.limit&&Et.req.values===Qe.values&&((Ct=Et.req.direction)!=null?Ct:"next")===ft&&si(Et.req.query.range,Qe.query.range)});return bt?[bt,!0,lt,ot]:[ot.find(function(Et){var Ct;return("limit"in Et.req?Et.req.limit:1/0)>=Qe.limit&&((Ct=Et.req.direction)!=null?Ct:"next")===ft&&(!Qe.values||Et.req.values)&&xi(Et.req.query.range,Qe.query.range)}),!1,lt,ot];case"count":return bt=ot.find(function(Et){return si(Et.req.query.range,Qe.query.range)}),[bt,!!bt,lt,ot]}})(P,j,"query",pe),ze=Ge[0],at=Ge[2],Je=Ge[3],ze&&Ge[1]?ze.obsSet=pe.obsSet:(Ge=V.query(pe).then(function(nt){var Xe=nt.result;if(ze&&(ze.res=Xe),Te){for(var Ye=0,Qe=Xe.length;Ye<Qe;++Ye)Object.freeze(Xe[Ye]);Object.freeze(Xe)}return nt}).catch(function(nt){return Je&&ze&&ce(Je,ze),Promise.reject(nt)}),ze={obsSet:pe.obsSet,promise:Ge,subscribers:new Set,type:"query",req:pe,dirty:!1},Je?Je.push(ze):(Je=[ze],(at=at||(y["idb://".concat(P,"/").concat(j)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[pe.query.index.name||""]=Je)),Pi(ze,Je,Ne,We),ze.promise.then(function(nt){return nt=ni(nt.result,pe,at==null?void 0:at.optimisticOps,V,ze,Te),{result:Te?nt:ne(nt)}})):V.query(pe)}})}})}};function cs(v,P){return new Proxy(v,{get:function(j,V,re){return V==="db"?P:Reflect.get(j,V,re)}})}mr.prototype.version=function(v){if(isNaN(v)||v<.1)throw new je.Type("Given version is not a positive number");if(v=Math.round(10*v)/10,this.idbdb||this._state.isBeingOpened)throw new je.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,v);var P=this._versions,j=P.filter(function(V){return V._cfg.version===v})[0];return j||(j=new this.Version(v),P.push(j),P.sort(Xi),j.stores({}),this._state.autoSchema=!1),j},mr.prototype._whenReady=function(v){var P=this;return this.idbdb&&(this._state.openComplete||_t.letThrough||this._vip)?v():new be(function(j,V){if(P._state.openComplete)return V(new je.DatabaseClosed(P._state.dbOpenError));if(!P._state.isBeingOpened){if(!P._state.autoOpen)return void V(new je.DatabaseClosed);P.open().catch(Ze)}P._state.dbReadyPromise.then(j,V)}).then(v)},mr.prototype.use=function(re){var P=re.stack,j=re.create,V=re.level,re=re.name,pe=(re&&this.unuse({stack:P,name:re}),this._middlewares[P]||(this._middlewares[P]=[]));return pe.push({stack:P,create:j,level:V??10,name:re}),pe.sort(function(Te,Ne){return Te.level-Ne.level}),this},mr.prototype.unuse=function(v){var P=v.stack,j=v.name,V=v.create;return P&&this._middlewares[P]&&(this._middlewares[P]=this._middlewares[P].filter(function(re){return V?re.create!==V:!!j&&re.name!==j})),this},mr.prototype.open=function(){var v=this;return Rr(pt,function(){return qe(v)})},mr.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var v=this._state;if(os.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}v.isBeingOpened||(v.dbReadyPromise=new be(function(P){v.dbReadyResolve=P}),v.openCanceller=new be(function(P,j){v.cancelOpen=j}))},mr.prototype.close=function(P){var P=(P===void 0?{disableAutoOpen:!0}:P).disableAutoOpen,j=this._state;P?(j.isBeingOpened&&j.cancelOpen(new je.DatabaseClosed),this._close(),j.autoOpen=!1,j.dbOpenError=new je.DatabaseClosed):(this._close(),j.autoOpen=this._options.autoOpen||j.isBeingOpened,j.openComplete=!1,j.dbOpenError=null)},mr.prototype.delete=function(v){var P=this,j=(v===void 0&&(v={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),V=this._state;return new be(function(re,pe){function Te(){P.close(v);var Ne=P._deps.indexedDB.deleteDatabase(P.name);Ne.onsuccess=Gt(function(){var We,at,Je;We=P._deps,at=P.name,As(Je=We.indexedDB)||at===zr||Qs(Je,We.IDBKeyRange).delete(at).catch(Ze),re()}),Ne.onerror=Or(pe),Ne.onblocked=P._fireOnBlocked}if(j)throw new je.InvalidArgument("Invalid closeOptions argument to db.delete()");V.isBeingOpened?V.dbReadyPromise.then(Te):Te()})},mr.prototype.backendDB=function(){return this.idbdb},mr.prototype.isOpen=function(){return this.idbdb!==null},mr.prototype.hasBeenClosed=function(){var v=this._state.dbOpenError;return v&&v.name==="DatabaseClosed"},mr.prototype.hasFailed=function(){return this._state.dbOpenError!==null},mr.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(mr.prototype,"tables",{get:function(){var v=this;return a(this._allTables).map(function(P){return v._allTables[P]})},enumerable:!1,configurable:!0}),mr.prototype.transaction=function(){var v=(function(P,j,V){var re=arguments.length;if(re<2)throw new je.InvalidArgument("Too few arguments");for(var pe=new Array(re-1);--re;)pe[re-1]=arguments[re];return V=pe.pop(),[P,z(pe),V]}).apply(this,arguments);return this._transaction.apply(this,v)},mr.prototype._transaction=function(v,P,j){var V,re,pe=this,Te=_t.trans,Ne=(Te&&Te.db===this&&v.indexOf("!")===-1||(Te=null),v.indexOf("?")!==-1);v=v.replace("!","").replace("?","");try{if(re=P.map(function(at){if(at=at instanceof pe.Table?at.name:at,typeof at!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return at}),v=="r"||v===vn)V=vn;else{if(v!="rw"&&v!=qs)throw new je.InvalidArgument("Invalid transaction mode: "+v);V=qs}if(Te){if(Te.mode===vn&&V===qs){if(!Ne)throw new je.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");Te=null}Te&&re.forEach(function(at){if(Te&&Te.storeNames.indexOf(at)===-1){if(!Ne)throw new je.SubTransaction("Table "+at+" not included in parent transaction.");Te=null}}),Ne&&Te&&!Te.active&&(Te=null)}}catch(at){return Te?Te._promise(null,function(Je,Ge){Ge(at)}):yr(at)}var We=(function at(Je,Ge,ze,nt,Xe){return be.resolve().then(function(){var ot=_t.transless||_t,Ye=Je._createTransaction(Ge,ze,Je._dbSchema,nt),ot=(Ye.explicit=!0,{trans:Ye,transless:ot});if(nt)Ye.idbtrans=nt.idbtrans;else try{Ye.create(),Ye.idbtrans._explicit=!0,Je._state.PR1398_maxLoop=3}catch(ft){return ft.name===Ee.InvalidState&&Je.isOpen()&&0<--Je._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),Je.close({disableAutoOpen:!1}),Je.open().then(function(){return at(Je,Ge,ze,null,Xe)})):yr(ft)}var Qe,lt=he(Xe),ot=(lt&&an(),be.follow(function(){var ft;(Qe=Xe.call(Ye,Ye))&&(lt?(ft=Fr.bind(null,null),Qe.then(ft,ft)):typeof Qe.next=="function"&&typeof Qe.throw=="function"&&(Qe=ct(Qe)))},ot));return(Qe&&typeof Qe.then=="function"?be.resolve(Qe).then(function(ft){return Ye.active?ft:yr(new je.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ot.then(function(){return Qe})).then(function(ft){return nt&&Ye._resolve(),Ye._completion.then(function(){return ft})}).catch(function(ft){return Ye._reject(ft),yr(ft)})})}).bind(null,this,V,re,Te,j);return Te?Te._promise(V,We,"lock"):_t.trans?Rr(_t.transless,function(){return pe._whenReady(We)}):this._whenReady(We)},mr.prototype.table=function(v){if(m(this._allTables,v))return this._allTables[v];throw new je.InvalidTable("Table ".concat(v," does not exist"))};var tn=mr;function mr(v,P){var j,V,re,pe,Te,Ne=this,We=(this._middlewares={},this.verno=0,mr.dependencies),We=(this._options=P=n({addons:mr.addons,autoOpen:!0,indexedDB:We.indexedDB,IDBKeyRange:We.IDBKeyRange,cache:"cloned",maxConnections:1e3},P),this._deps={indexedDB:P.indexedDB,IDBKeyRange:P.IDBKeyRange},P.addons),at=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Ze,dbReadyPromise:null,cancelOpen:Ze,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:P.autoOpen}),Je=(at.dbReadyPromise=new be(function(Ge){at.dbReadyResolve=Ge}),at.openCanceller=new be(function(Ge,ze){at.cancelOpen=ze}),this._state=at,this.name=v,this.on=Tn(this,"populate","blocked","versionchange","close",{ready:[gt,Ze]}),this.once=function(Ge,ze){var nt=function(){for(var Xe=[],Ye=0;Ye<arguments.length;Ye++)Xe[Ye]=arguments[Ye];Ne.on(Ge).unsubscribe(nt),ze.apply(Ne,Xe)};return Ne.on(Ge,nt)},this.on.ready.subscribe=_(this.on.ready.subscribe,function(Ge){return function(ze,nt){mr.vip(function(){var Xe,Ye=Ne._state;Ye.openComplete?(Ye.dbOpenError||be.resolve().then(ze),nt&&Ge(ze)):Ye.onReadyBeingFired?(Ye.onReadyBeingFired.push(ze),nt&&Ge(ze)):(Ge(ze),Xe=Ne,nt||Ge(function Qe(){Xe.on.ready.unsubscribe(ze),Xe.on.ready.unsubscribe(Qe)}))})}}),this.Collection=(j=this,Un(_n.prototype,function(Qe,Ye){this.db=j;var nt=pi,Xe=null;if(Ye)try{nt=Ye()}catch(ot){Xe=ot}var Ye=Qe._ctx,Qe=Ye.table,lt=Qe.hook.reading.fire;this._ctx={table:Qe,index:Ye.index,isPrimKey:!Ye.index||Qe.schema.primKey.keyPath&&Ye.index===Qe.schema.primKey.name,range:nt,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:Xe,or:Ye.or,valueMapper:lt!==ut?lt:null}})),this.Table=(V=this,Un(yi.prototype,function(Ge,ze,nt){this.db=V,this._tx=nt,this.name=Ge,this.schema=ze,this.hook=V._allTables[Ge]?V._allTables[Ge].hook:Tn(null,{creating:[Ue,Ze],reading:[it,ut],updating:[$e,Ze],deleting:[Le,Ze]})})),this.Transaction=(re=this,Un(zi.prototype,function(Ge,ze,nt,Xe,Ye){var Qe=this;Ge!=="readonly"&&ze.forEach(function(lt){lt=(lt=nt[lt])==null?void 0:lt.yProps,lt&&(ze=ze.concat(lt.map(function(ot){return ot.updatesTable})))}),this.db=re,this.mode=Ge,this.storeNames=ze,this.schema=nt,this.chromeTransactionDurability=Xe,this.idbtrans=null,this.on=Tn(this,"complete","error","abort"),this.parent=Ye||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new be(function(lt,ot){Qe._resolve=lt,Qe._reject=ot}),this._completion.then(function(){Qe.active=!1,Qe.on.complete.fire()},function(lt){var ot=Qe.active;return Qe.active=!1,Qe.on.error.fire(lt),Qe.parent?Qe.parent._reject(lt):ot&&Qe.idbtrans&&Qe.idbtrans.abort(),yr(lt)})})),this.Version=(pe=this,Un(Zi.prototype,function(Ge){this.db=pe,this._cfg={version:Ge,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(Te=this,Un(Gs.prototype,function(Ge,ze,nt){if(this.db=Te,this._ctx={table:Ge,index:ze===":id"?null:ze,or:nt},this._cmp=this._ascending=Jt,this._descending=function(Xe,Ye){return Jt(Ye,Xe)},this._max=function(Xe,Ye){return 0<Jt(Xe,Ye)?Xe:Ye},this._min=function(Xe,Ye){return Jt(Xe,Ye)<0?Xe:Ye},this._IDBKeyRange=Te._deps.IDBKeyRange,!this._IDBKeyRange)throw new je.MissingAPI})),this.on("versionchange",function(Ge){0<Ge.newVersion?console.warn("Another connection wants to upgrade database '".concat(Ne.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(Ne.name,"'. Closing db now to resume the delete request.")),Ne.close({disableAutoOpen:!1})}),this.on("blocked",function(Ge){!Ge.newVersion||Ge.newVersion<Ge.oldVersion?console.warn("Dexie.delete('".concat(Ne.name,"') was blocked")):console.warn("Upgrade '".concat(Ne.name,"' blocked by other connection holding version ").concat(Ge.oldVersion/10))}),this._maxKey=ss(P.IDBKeyRange),this._createTransaction=function(Ge,ze,nt,Xe){return new Ne.Transaction(Ge,ze,nt,Ne._options.chromeTransactionDurability,Xe)},this._fireOnBlocked=function(Ge){Ne.on("blocked").fire(Ge),os.toArray().filter(function(ze){return ze.name===Ne.name&&ze!==Ne&&!ze._state.vcFired}).map(function(ze){return ze.on("versionchange").fire(Ge)})},this.use(lr),this.use(wi),this.use(_i),this.use(wt),this.use(cr),new Proxy(this,{get:function(Ge,ze,nt){var Xe;return ze==="_vip"||(ze==="table"?function(Ye){return cs(Ne.table(Ye),Je)}:(Xe=Reflect.get(Ge,ze,nt))instanceof yi?cs(Xe,Je):ze==="tables"?Xe.map(function(Ye){return cs(Ye,Je)}):ze==="_createTransaction"?function(){return cs(Xe.apply(this,arguments),Je)}:Xe)}}));this.vip=Je,We.forEach(function(Ge){return Ge(Ne)})}var us,Bn=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",Ai=(Os.prototype.subscribe=function(v,P,j){return this._subscribe(v&&typeof v!="function"?v:{next:v,error:P,complete:j})},Os.prototype[Bn]=function(){return this},Os);function Os(v){this._subscribe=v}try{us={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{us={indexedDB:null,IDBKeyRange:null}}function ii(v){var P,j=!1,V=new Ai(function(re){var pe=he(v),Te,Ne=!1,We={},at={},Je={get closed(){return Ne},unsubscribe:function(){Ne||(Ne=!0,Te&&Te.abort(),Ge&&en.storagemutated.unsubscribe(Xe))}},Ge=(re.start&&re.start(Je),!1),ze=function(){return ms(Ye)};function nt(){return c(at,We)}var Xe=function(Qe){s(We,Qe),nt()&&ze()},Ye=function(){var Qe,lt,ot;!Ne&&us.indexedDB&&(We={},Qe={},Te&&Te.abort(),Te=new AbortController,ot=(ft=>{var bt=Kt();try{pe&&an();var Et=Gr(v,ft);return Et=pe?Et.finally(Fr):Et}finally{bt&&Xt()}})(lt={subscr:Qe,signal:Te.signal,requery:ze,querier:v,trans:null}),Ge||(en.storagemutated.subscribe(Xe),Ge=!0),Promise.resolve(ot).then(function(ft){j=!0,P=ft,Ne||lt.signal.aborted||(nt()||(at=Qe,nt())?ze():(We={},ms(function(){return!Ne&&re.next&&re.next(ft)})))},function(ft){j=!1,["DatabaseClosedError","AbortError"].includes(ft==null?void 0:ft.name)||Ne||ms(function(){Ne||re.error&&re.error(ft)})}))};return setTimeout(ze,0),Je});return V.hasValue=function(){return j},V.getValue=function(){return P},V}var Cn=tn;function Ns(v){var P=fn;try{fn=!0,en.storagemutated.fire(v),Pe(v,!0)}finally{fn=P}}b(Cn,n(n({},ae),{delete:function(v){return new Cn(v,{addons:[]}).delete()},exists:function(v){return new Cn(v,{addons:[]}).open().then(function(P){return P.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(v){try{return P=Cn.dependencies,j=P.indexedDB,P=P.IDBKeyRange,(As(j)?Promise.resolve(j.databases()).then(function(V){return V.map(function(re){return re.name}).filter(function(re){return re!==zr})}):Qs(j,P).toCollection().primaryKeys()).then(v)}catch{return yr(new je.MissingAPI)}var P,j},defineClass:function(){return function(v){f(this,v)}},ignoreTransaction:function(v){return _t.trans?Rr(_t.transless||pt,v):v()},vip:Zs,async:function(v){return function(){try{var P=ct(v.apply(this,arguments));return P&&typeof P.then=="function"?P:be.resolve(P)}catch(j){return yr(j)}}},spawn:function(v,P,j){try{var V=ct(v.apply(j,P||[]));return V&&typeof V.then=="function"?V:be.resolve(V)}catch(re){return yr(re)}},currentTransaction:{get:function(){return _t.trans||null}},waitFor:function(v,P){return v=be.resolve(typeof v=="function"?Cn.ignoreTransaction(v):v).timeout(P||6e4),_t.trans?_t.trans.waitFor(v):v},Promise:be,debug:{get:function(){return ht},set:function(v){_e(v)}},derive:x,extend:f,props:b,override:_,Events:Tn,on:en,liveQuery:ii,extendObservabilitySet:s,getByKeyPath:B,setByKeyPath:I,delByKeyPath:function(v,P){typeof P=="string"?I(v,P,void 0):"length"in P&&[].map.call(P,function(j){I(v,j,void 0)})},shallowClone:R,deepClone:ne,getObjectDiff:Ot,cmp:Jt,asap:D,minKey:-1/0,addons:[],connections:{get:os.toArray},errnames:Ee,dependencies:us,cache:y,semVer:"4.4.5",version:"4.4.5".split(".").map(function(v){return parseInt(v)}).reduce(function(v,P,j){return v+P/Math.pow(10,2*j)})})),Cn.maxKey=ss(Cn.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(en(Kn,function(v){fn||(v=new CustomEvent(Hs,{detail:v}),fn=!0,dispatchEvent(v),fn=!1)}),addEventListener(Hs,function(v){v=v.detail,fn||Ns(v)}));var Rn,fn=!1,ai=function(){};return typeof BroadcastChannel<"u"&&((ai=function(){(Rn=new BroadcastChannel(Hs)).onmessage=function(v){return v.data&&Ns(v.data)}})(),typeof Rn.unref=="function"&&Rn.unref(),en(Kn,function(v){fn||Rn.postMessage(v)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(v){if(!tn.disableBfCache&&v.persisted){ht&&console.debug("Dexie: handling persisted pagehide"),Rn!=null&&Rn.close();for(var P=0,j=os.toArray();P<j.length;P++)j[P].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(v){!tn.disableBfCache&&v.persisted&&(ht&&console.debug("Dexie: handling persisted pageshow"),ai(),Ns({all:new _r(-1/0,[[]])}))})),be.rejectionMapper=function(v,P){return!v||v instanceof M||v instanceof TypeError||v instanceof SyntaxError||!v.name||!Ve[v.name]?v:(P=new Ve[v.name](P||v.message,v),"stack"in v&&O(P,"stack",{get:function(){return this.inner.stack}}),P)},_e(ht),n(tn,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:tn,Entity:ts,PropModification:wr,RangeSet:_r,add:function(v){return new wr({add:v})},cmp:Jt,default:tn,liveQuery:ii,mergeRanges:cn,rangesOverlap:ti,remove:function(v){return new wr({remove:v})},replacePrefix:function(v,P){return new wr({replacePrefix:[v,P]})}}),{default:tn}),tn})})(Jy);var hE=Jy.exports,Kf=dE(hE);const Yy=Symbol.for("Dexie"),fa=globalThis[Yy]||(globalThis[Yy]=Kf);if(Kf.semVer!==fa.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Kf.semVer} and ${fa.semVer}`);const{liveQuery:MN,mergeRanges:FN,rangesOverlap:$N,RangeSet:UN,cmp:qN,Entity:VN,PropModification:KN,replacePrefix:WN,add:GN,remove:HN,DexieYProvider:zN}=fa,Wa=Bs("Database");class yE extends fa{constructor(r){if(!r)throw new Error("[RTCAgentDatabase] databaseName must not be empty");Wa.info("Initializing database:",r);super(r);Bt(this,"sessions");Bt(this,"turns");Bt(this,"messages");Bt(this,"rtcs");Bt(this,"offsets");Bt(this,"fileSystemEntries");Bt(this,"debugHistory");this.version(1).stores({sessions:"id, &client_id, sync_status, owner_ref_id, status",turns:"id, &client_id, sync_status, session_id, status",messages:"id, &client_id, sync_status, session_id, turn_id, global_offset",rtcs:"id, &client_id, sync_status, session_id, turn_id, status",offsets:"channel"}),this.version(2).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status",offsets:"channel"}).upgrade(async n=>{Wa.info("Migrating database from v1 to v2: switching to client_id as primary key");const i=n.table("sessions"),o=await i.toArray();await i.clear();const a=new Map;for(const u of o){const f=u,d=f.id,m=f.client_id||d||crypto.randomUUID();d&&a.set(d,m);const b={...f};b.client_id=m,b.server_id=d,delete b.id,await i.add(b)}for(const u of["turns","messages","rtcs"]){const f=n.table(u),d=await f.toArray();await f.clear();for(const h of d){const m=h,b=m.id,S=m.client_id,O=m.session_id,x={...m};if(x.client_id=S||b||crypto.randomUUID(),x.server_id=b,delete x.id,O){const w=a.get(O);x.session_client_id=w||O}else x.session_client_id="";delete x.session_id,await f.add(x)}}}),this.version(3).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status",offsets:"channel"}),this.version(4).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status",offsets:"channel"}),this.version(5).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status, offset",offsets:"channel"}),this.version(6).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status, offset",offsets:"channel",fileSystemEntries:"path, type, metadata.group, *metadata.tags"}),this.version(7).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at, device_id",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status, offset",offsets:"channel",fileSystemEntries:"path, type, metadata.group, *metadata.tags"}),this.version(8).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at, device_id",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status, offset, session_device_id",offsets:"channel",fileSystemEntries:"path, type, metadata.group, *metadata.tags"}).upgrade(async n=>{const i=await n.table("rtcs").toArray();for(const o of i)if(o.session_client_id&&!o.session_device_id){const a=await n.table("sessions").get(o.session_client_id);a!=null&&a.device_id&&await n.table("rtcs").update(o.client_id,{session_device_id:a.device_id})}}),this.version(9).stores({sessions:"client_id, server_id, sync_status, owner_ref_id, status, updated_at, device_id",turns:"client_id, server_id, sync_status, session_client_id, status",messages:"client_id, server_id, sync_status, session_client_id, turn_id, global_offset, created_at",rtcs:"client_id, server_id, sync_status, session_client_id, turn_id, status, offset, session_device_id",offsets:"channel",fileSystemEntries:"path, type, metadata.group, *metadata.tags",debugHistory:"id, function_name, timestamp"}),this.version(10).stores({debugHistory:"id, function_name, timestamp, [function_name+timestamp]"})}}let oi=null,Mo=null;function zt(t){if(t===void 0){if(oi)return oi;throw new Error("[RTCAgentDatabase] getDatabase() called without a name before any database was initialized. Pass a databaseName.")}if(!t)throw new Error("[RTCAgentDatabase] databaseName must not be empty");const e=t;return(!oi||Mo!==e)&&(oi&&(Wa.info("Closing previous database instance:",Mo),oi.close()),Wa.info("Creating new database instance:",e),oi=new yE(e),Mo=e),oi}async function mE(){oi&&(Wa.info("Closing database:",Mo),oi.close(),oi=null,Mo=null)}async function gE(){Wa.warn("flushAll: clearing all database tables");const t=zt(),e=[t.sessions,t.turns,t.messages,t.rtcs,t.offsets,t.fileSystemEntries,t.debugHistory];await t.transaction("rw",e,async()=>{await t.sessions.clear(),await t.turns.clear(),await t.messages.clear(),await t.rtcs.clear(),await t.offsets.clear(),await t.fileSystemEntries.clear(),await t.debugHistory.clear()})}const pa=Bs("OffsetManager");class bE{constructor(){Bt(this,"cache",new Map)}async getPosition(e){const r=this.cache.get(e);if(r!==void 0)return pa.debug("getPosition (cache hit):",e,"offset:",r.offset,"epoch:",r.epoch),{offset:r.offset,epoch:r.epoch};const i=await zt().offsets.get(e);if(!i){pa.debug("getPosition (no record):",e);return}const o={offset:i.offset,epoch:i.epoch};return this.cache.set(e,o),pa.debug("getPosition (loaded from DB):",e,"offset:",i.offset,"epoch:",i.epoch),{offset:o.offset,epoch:o.epoch}}async updatePosition(e,r,n){pa.debug("updatePosition:",e,"offset:",r,"epoch:",n);const i=this.cache.get(e);this.cache.set(e,{offset:r,epoch:n});const o=zt(),a={channel:e,offset:r,epoch:n,updatedAt:Date.now()};try{await o.offsets.put(a)}catch(u){throw i!==void 0?this.cache.set(e,i):this.cache.delete(e),u}}async clearPosition(e){pa.debug("clearPosition:",e),this.cache.delete(e),await zt().offsets.delete(e)}async clearAll(){pa.info("clearAll: clearing all offset records"),this.cache.clear(),await zt().offsets.clear()}async reset(){pa.info("reset: resetting all offsets"),await this.clearAll()}async warmCache(e){return this.getPosition(e)}isCached(e){return this.cache.has(e)}getCacheSize(){return this.cache.size}invalidateCache(e){this.cache.delete(e)}invalidateAllCache(){this.cache.clear()}}let Wf=null;function Xy(){return Wf||(Wf=new bE),Wf}const Ls=Bs("UIUpdateBus"),Bo=class Bo{constructor(){Bt(this,"entityListeners",new Map);Bt(this,"wildcardListeners",new Set);Bt(this,"bulkUpdateListeners",new Set);Bt(this,"gapFillListeners",new Set);Bt(this,"_processingChains",new Map);Bt(this,"_listenerCounter",0);Bt(this,"_listenerIds",new WeakMap);Bt(this,"_suspended",!1);Bt(this,"_suspendDepth",0);Bt(this,"_suspendSafetyTimer");Bt(this,"_suspendedEvents",[]);Bt(this,"_suspendedEntities",new Set)}_getListenerId(e){let r=this._listenerIds.get(e);return r===void 0&&(r=++this._listenerCounter,this._listenerIds.set(e,r)),r}_getChainKey(e,r,n){return`${e}:${r}:${this._getListenerId(n)}`}_dispatchToListener(e,r){const n=this._getChainKey(r.entity,r.entityId,e),o=(this._processingChains.get(n)??Promise.resolve()).then(()=>this._withTimeout(e(r),Bo.CHAIN_TIMEOUT_MS,n)).catch(a=>{Ls.error("listener error:",a)});this._processingChains.set(n,o),o.finally(()=>{this._processingChains.get(n)===o&&this._processingChains.delete(n)})}async _withTimeout(e,r,n){if(!e)return;let i;const o=new Promise((a,u)=>{i=setTimeout(()=>{u(new Error(`Listener chain timeout after ${r}ms for ${n}`))},r)});try{return await Promise.race([e,o])}finally{clearTimeout(i)}}subscribe(e,r){if(typeof e=="function")return this.wildcardListeners.add(e),()=>{this.wildcardListeners.delete(e)};const n=e,i=r;let o=this.entityListeners.get(n);return o||(o=new Set,this.entityListeners.set(n,o)),o.add(i),()=>{o.delete(i),o.size===0&&this.entityListeners.delete(n)}}publish(e){if(this._suspended){this._suspendedEvents.push(e),this._suspendedEntities.add(e.entity);return}for(const n of this.wildcardListeners)this._dispatchToListener(n,e);const r=this.entityListeners.get(e.entity);if(r)for(const n of r)this._dispatchToListener(n,e)}suspend(){this._suspendDepth++,this._suspendDepth===1&&(this._suspended=!0,this._suspendSafetyTimer=setTimeout(()=>{Ls.error("UIUpdateBus suspend exceeded safety timeout, forcing resume"),this._forceResume()},Bo.MAX_SUSPEND_MS)),Ls.debug(`suspend: depth=${this._suspendDepth}`)}resume(){if(this._suspendDepth===0){Ls.warn("resume called without matching suspend, ignoring");return}this._suspendDepth--,this._suspendDepth===0&&(this._suspended=!1,this._suspendSafetyTimer&&(clearTimeout(this._suspendSafetyTimer),this._suspendSafetyTimer=void 0),this._flushSuspendedEvents()),Ls.debug(`resume: depth=${this._suspendDepth}`)}_forceResume(){this._suspendDepth=0,this._suspended=!1,this._suspendSafetyTimer&&(clearTimeout(this._suspendSafetyTimer),this._suspendSafetyTimer=void 0),this._flushSuspendedEvents(),Ls.warn("Force resumed after safety timeout")}_flushSuspendedEvents(){const e=this._suspendedEvents.length;if(e>0){const r={entities:new Set(this._suspendedEntities),eventCount:e};for(const n of this.bulkUpdateListeners)try{n(r)}catch(i){Ls.error("bulk update listener error:",i)}this._suspendedEvents=[],this._suspendedEntities.clear()}}onBulkUpdate(e){return this.bulkUpdateListeners.add(e),()=>{this.bulkUpdateListeners.delete(e)}}emitGapFillStart(){Ls.debug("[BulkUpdate] UIUpdateBus.emitGapFillStart() called");for(const e of this.gapFillListeners)try{e(!0)}catch(r){Ls.error("gap fill listener error:",r)}}emitGapFillEnd(){Ls.debug("[BulkUpdate] UIUpdateBus.emitGapFillEnd() called");for(const e of this.gapFillListeners)try{e(!1)}catch(r){Ls.error("gap fill listener error:",r)}}onGapFillState(e){return this.gapFillListeners.add(e),()=>{this.gapFillListeners.delete(e)}}clear(){this.entityListeners.clear(),this.wildcardListeners.clear(),this.bulkUpdateListeners.clear(),this.gapFillListeners.clear(),this._processingChains.clear(),this._suspended=!1,this._suspendDepth=0,this._suspendSafetyTimer&&(clearTimeout(this._suspendSafetyTimer),this._suspendSafetyTimer=void 0),this._suspendedEvents=[],this._suspendedEntities.clear()}};Bt(Bo,"MAX_SUSPEND_MS",3e4),Bt(Bo,"CHAIN_TIMEOUT_MS",1e4);let Gf=Bo,Hf=null;function Ga(){return Hf||(Hf=new Gf),Hf}function vE(t=new Date){const e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0"),i=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),a=String(t.getSeconds()).padStart(2,"0"),u=String(t.getMilliseconds()).padStart(3,"0"),f=-t.getTimezoneOffset(),d=String(Math.floor(Math.abs(f)/60)).padStart(2,"0"),h=String(Math.abs(f)%60).padStart(2,"0"),m=f>=0?"+":"-";return`${e}-${r}-${n}T${i}:${o}:${a}.${u}${m}${d}:${h}`}function Gn(){return vE(new Date)}const Qy=["Date","RegExp","String","Number"],Zy=Object.getOwnPropertyNames(globalThis.Temporal||{});function em(t,e,r={cyclesFix:!0},n=[]){var u,f;let i=[];const o=Array.isArray(t);for(const d in t){const h=t[d],m=o?+d:d;if(!(d in e)){i.push({type:"REMOVE",path:[m],oldValue:h});continue}const b=e[d],S=typeof h=="object"&&typeof b=="object"&&Array.isArray(h)===Array.isArray(b),O=S&&h?(f=(u=Object.getPrototypeOf(h))==null?void 0:u.constructor)==null?void 0:f.name:void 0;if(h&&b&&S&&!Qy.includes(O)&&!Zy.includes(O)&&(!r.cyclesFix||!n.includes(h))){r.cyclesFix&&n.push(h);const x=em(h,b,r,n);r.cyclesFix&&n.pop();for(const w of x)w.path.unshift(m),i.push(w)}else Object.is(h,b)||Zy.includes(O)&&String(h)===String(b)||Qy.includes(O)&&(isNaN(h)?h+""==b+"":+h==+b)||i.push({path:[m],type:"CHANGE",value:b,oldValue:h})}const a=Array.isArray(e);for(const d in e)d in t||i.push({type:"CREATE",path:[a?+d:d],value:e[d]});return i}const gr=Bs("EntityRepository");function tm(t,e){return!t||!e||t===e?!1:t==="completed"||t==="failed"?e==="streaming"||e==="pending":!1}function SE(t){return t.join(".")}function da(t,e,r,n,i){const o=Ga(),a=rm(i),u=n?rm(n):void 0;if(!u){for(const[d,h]of Object.entries(a))o.publish({entity:t,action:e,entityId:r,field:d,oldValue:void 0,newValue:h});return}const f=em(u,a);for(const d of f)o.publish({entity:t,action:e,entityId:r,field:SE(d.path),oldValue:d.oldValue,newValue:d.value})}function rm(t){try{return JSON.parse(JSON.stringify(t))}catch{return gr.warn("safeClone: failed to clone object, returning empty object"),{}}}class TE{constructor(e){Bt(this,"deviceId");if(!e)throw new Error("[EntityRepository] deviceId is required, got empty value");this.deviceId=e}async upsertSession(e,r="synced",n){const i=zt(),o=Gn();return i.transaction("rw",i.sessions,async()=>{let a;e.client_id&&(a=await i.sessions.where("client_id").equals(e.client_id).first()),gr.debug("upsertSession:",a?"UPDATE":"CREATE","client_id:",e.client_id,"title:",e.title);let u,f;if(a){const d={...a},h={...a,...e,sync_status:n!=null&&n.preserveSyncStatus?a.sync_status:r,server_id:e.server_id||a.server_id};await i.sessions.put(h),u={before:d,after:h},f="updated",gr.debug("upsertSession: After update - title:",h.title)}else{const d={...e,client_id:e.client_id||"",owner_kind:e.owner_kind||"",owner_ref_id:e.owner_ref_id||"",status:e.status||"active",created_at:e.created_at||o,updated_at:e.updated_at||o,sync_status:e.sync_status||r,pending_turn_count:e.pending_turn_count??0,running_turn_count:e.running_turn_count??0,agent_prompt:e.agent_prompt||""};await i.sessions.put(d),u={before:void 0,after:d},f="created",gr.debug("upsertSession: After create - title:",d.title)}return n!=null&&n.silent||da("session",f,u.after.client_id,u.before,u.after),u})}async getClientSession(e){return zt().sessions.get(e)}async getSessionByServerId(e){return zt().sessions.where("server_id").equals(e).first()}async getMessageByServerId(e){return zt().messages.where("server_id").equals(e).first()}async listSessions(e,r=1e4){const o=await zt().sessions.orderBy("updated_at").reverse().toArray(),a=o.filter(u=>!u.deleted_at);if(gr.debug(`listSessions: total=${o.length}, active=${a.length}, deleted=${o.length-a.length}`),a.length>1e3&&gr.warn(`listSessions: ${a.length} active sessions detected. Consider implementing virtual scrolling in the UI layer if performance degrades.`),e){const u=a.findIndex(f=>f.client_id===e);return u===-1?(gr.warn(`listSessions: cursor ${e} not found, returning from start`),a.slice(0,r)):a.slice(u+1,u+1+r)}return a.slice(0,r)}async softDeleteSession(e){if(!await this.getClientSession(e))throw new Error(`[EntityRepository] softDeleteSession: session not found: ${e}`);const n=Gn();gr.debug(`softDeleteSession: setting deleted_at=${n} for ${e}`);const i=await this.upsertSession({client_id:e,deleted_at:n,updated_at:n},"pending");return gr.debug(`softDeleteSession: after upsert, deleted_at=${i.after.deleted_at}`),i}async upsertTurn(e,r="synced",n){const i=zt(),o=Gn();return i.transaction("rw",i.turns,async()=>{let a;e.client_id&&(a=await i.turns.where("client_id").equals(e.client_id).first());let u,f;if(a){const d={...a},h={...a,...e,sync_status:n!=null&&n.preserveSyncStatus?a.sync_status:r,server_id:e.server_id||a.server_id};await i.turns.put(h),u={before:d,after:h},f="updated"}else{const d={client_id:e.client_id||"",server_id:e.server_id,session_client_id:e.session_client_id||"",status:e.status||"pending",created_at:e.created_at||o,sync_status:e.sync_status||r};await i.turns.put(d),u={before:void 0,after:d},f="created"}return n!=null&&n.silent||(gr.debug("[EntityRepository] Emitting turn UI update:",f,u.after.client_id,"session:",u.after.session_client_id),da("turn",f,u.after.client_id,u.before,u.after)),u})}async getClientTurn(e){return zt().turns.get(e)}async countActiveTurns(e){const r=zt(),n=r.turns.where("session_client_id").equals(e),[i,o]=await Promise.all([n.filter(a=>a.status==="pending").count(),r.turns.where("session_client_id").equals(e).filter(a=>a.status==="running").count()]);return{pending:i,running:o}}async upsertMessage(e,r="synced",n){const i=zt(),o=Gn();return i.transaction("rw",i.messages,async()=>{let a;e.client_id&&(a=await i.messages.where("client_id").equals(e.client_id).first());let u,f;if(a){const d={...a};if(tm(a.streaming_status,e.streaming_status))return gr.debug("upsertMessage: skip streaming regression","client_id:",e.client_id,"existing:",a.streaming_status,"incoming:",e.streaming_status),{before:d,after:a};const h={...a,...e,sync_status:n!=null&&n.preserveSyncStatus?a.sync_status:r,server_id:e.server_id||a.server_id};await i.messages.put(h),u={before:d,after:h},f="updated"}else{const d={client_id:e.client_id||"",server_id:e.server_id,session_client_id:e.session_client_id||"",turn_id:e.turn_id,global_offset:e.global_offset||0,turn_offset:e.turn_offset,role:e.role||"user",content:e.content,streaming_status:e.streaming_status||"pending",creator_kind:e.creator_kind||"user",creator_ref_id:e.creator_ref_id||"",created_at:e.created_at||o,updated_at:e.updated_at||o,sync_status:e.sync_status||r,parent_client_id:e.parent_client_id};await i.messages.put(d),u={before:void 0,after:d},f="created"}return n!=null&&n.silent||da("message",f,u.after.client_id,u.before,u.after),u})}async getClientMessage(e){return zt().messages.get(e)}async listMessagesBySession(e,r,n=50,i="backward"){const u=await zt().messages.where("session_client_id").equals(e).toArray(),f=h=>`${new Date(h.created_at).getTime()}|${h.client_id}`;u.sort((h,m)=>f(h).localeCompare(f(m)));let d=null;if(r&&(d=r),i==="backward"){let h=u;return d&&(h=u.filter(b=>f(b)<d)),h.slice(-n)}return d?u.filter(m=>f(m)>d).slice(0,n):u.slice(0,n)}async upsertRtc(e,r="synced",n){const i=zt(),o=Gn();return i.transaction("rw",i.rtcs,async()=>{let a;e.client_id&&(a=await i.rtcs.where("client_id").equals(e.client_id).first());let u,f;if(a){const d={...a},h={...a,...e,sync_status:n!=null&&n.preserveSyncStatus?a.sync_status:r,server_id:e.server_id||a.server_id};await i.rtcs.put(h),u={before:d,after:h},f="updated"}else{const d={client_id:e.client_id||"",server_id:e.server_id,session_client_id:e.session_client_id||"",session_device_id:e.session_device_id,turn_id:e.turn_id||"",offset:e.offset||0,tool_name:e.tool_name||"",parameters:e.parameters,status:e.status||"pending",result:e.result,error_message:e.error_message,created_at:e.created_at||o,updated_at:e.updated_at||o,sync_status:e.sync_status||r};await i.rtcs.put(d),u={before:void 0,after:d},f="created"}return n!=null&&n.silent||da("rtc",f,u.after.client_id,u.before,u.after),u})}async getClientRtc(e){return zt().rtcs.get(e)}async getNextRtcToProcess(e){const r=zt(),n=f=>e?f.session_client_id===e:!0,i=f=>f.session_device_id?f.session_device_id===this.deviceId:!0,a=(await r.rtcs.where("sync_status").equals("failed").sortBy("offset")).find(f=>n(f)&&i(f));return a||(await r.rtcs.filter(f=>f.status==="pending").sortBy("offset")).find(f=>n(f)&&i(f))}async listRtcBySession(e,r,n=50){const a=(await zt().rtcs.where("session_client_id").equals(e).toArray()).sort((f,d)=>f.offset-d.offset),u=r||0;return a.slice(u,u+n)}async applyUpdate(e){return this.applyUpdates([e])}async applyUpdates(e){if(!e||e.length===0)return;if(e.length===1)return this.applyUpdateOriginal(e[0]);const r=zt(),n=performance.now();let i=0;for(const b of e)i+=b.items.length;const{upserts:o,deletes:a}=this.groupItemsByEntity(e);if(this.isBatchEmpty(o,a)){gr.debug("[applyUpdates] Empty batch, skipping");return}gr.info(`[applyUpdates] Processing ${e.length} updates, ${i} items`);const u=await this.loadRequiredSessionMap(o),f=this.prepareEntitiesForBatch(o,u);await this.resolveParentMessageIds(f.messages),await this.resolveDeleteClientIds(a,u);const d=this.getTablesToLock(o,a),h=new Map;let m={sessions:[],turns:[],messages:[],rtcs:[]};try{await r.transaction("rw",d,async()=>{const S=await this.bulkGetExisting(f);this.collectBeforeSnapshots(h,S),m=this.mergeWithExisting(f,S),m.sessions.length>0&&await r.sessions.bulkPut(m.sessions),m.turns.length>0&&await r.turns.bulkPut(m.turns),m.messages.length>0&&await r.messages.bulkPut(m.messages),m.rtcs.length>0&&await r.rtcs.bulkPut(m.rtcs),a.sessions.length>0&&await r.sessions.bulkDelete(a.sessions),a.turns.length>0&&await r.turns.bulkDelete(a.turns),a.messages.length>0&&await r.messages.bulkDelete(a.messages),a.rtcs.length>0&&await r.rtcs.bulkDelete(a.rtcs),await this.writebackTurnCountsInTx(m.turns)});const b=performance.now()-n;gr.info(`[applyUpdates] Transaction completed in ${b.toFixed(1)}ms: ${m.sessions.length} sessions, ${m.turns.length} turns, ${m.messages.length} messages, ${m.rtcs.length} rtcs, ${a.sessions.length+a.turns.length+a.messages.length+a.rtcs.length} deletes`),this.emitBatchUIUpdates(h,m,a)}catch(b){const S=performance.now()-n;throw gr.error(`[applyUpdates] Transaction failed after ${S.toFixed(1)}ms:`,b),b}}groupItemsByEntity(e){var o,a;const r=new Map,n={sessions:[],turns:[],messages:[],rtcs:[],_pendingDeleteServerIds:new Map};for(const u of e)for(let f=0;f<u.items.length;f++){const d=u.items[f];if(d.action==="deleted"){const S=(o=u.data_list)==null?void 0:o[f],O=S==null?void 0:S.client_id;O?this.pushDelete(n,d.entity,O):(n._pendingDeleteServerIds.has(d.entity)||n._pendingDeleteServerIds.set(d.entity,[]),n._pendingDeleteServerIds.get(d.entity).push(d.entity_id));continue}const h=(a=u.data_list)==null?void 0:a[f];if(!h)continue;const m=h,b=m.client_id||m.id;b&&(r.has(d.entity)||r.set(d.entity,new Map),r.get(d.entity).set(b,{item:d,data:h}))}const i=new Map;for(const[u,f]of r)i.set(u,[...f.values()]);return{upserts:i,deletes:n}}isBatchEmpty(e,r){for(const n of e.values())if(n.length>0)return!1;return r.sessions.length===0&&r.turns.length===0&&r.messages.length===0&&r.rtcs.length===0&&r._pendingDeleteServerIds.size===0}pushDelete(e,r,n){switch(r){case"session":e.sessions.push(n);break;case"turn":e.turns.push(n);break;case"message":e.messages.push(n);break;case"rtc":e.rtcs.push(n);break;default:gr.info(`Unsupported entity type for batch delete: ${r}`)}}async loadRequiredSessionMap(e){const r=zt(),n=new Set;for(const u of["turn","message","rtc"]){const f=e.get(u)??[];for(const{data:d}of f){const h=d;h.session_id&&n.add(h.session_id)}}const i=new Map,o=e.get("session")??[];for(const{data:u}of o){const f=u,d=f.id,h=f.client_id||d,m={server_id:d,client_id:h,...f};d&&i.set(d,m),i.set(h,m)}const a=[...n].filter(u=>!i.has(u));if(a.length>0){const u=await r.sessions.where("server_id").anyOf(a).toArray();for(const f of u)i.set(f.server_id,f),i.set(f.client_id,f)}return i}resolveSessionClientId(e,r){const n=r.get(e);return n?n.client_id:(gr.warn(`Session ${e} not found in map, using server_id as client_id`),e)}prepareEntitiesForBatch(e,r){const n={sessions:[],turns:[],messages:[],rtcs:[]},i=Gn();for(const{data:o}of e.get("session")??[]){const a=o,u=a.id,f=a.client_id||u,d={owner_kind:"",owner_ref_id:"",status:"active",created_at:i,updated_at:i,pending_turn_count:0,running_turn_count:0,agent_prompt:"",...a,server_id:u,client_id:f,sync_status:"synced"};delete d.id,n.sessions.push(d)}for(const{data:o}of e.get("turn")??[]){const a=o,u=a.id,f=a.client_id||u,d=a.session_id,h={session_client_id:"",status:"pending",created_at:i,...a,server_id:u,client_id:f,sync_status:"synced"};d&&(h.session_client_id=this.resolveSessionClientId(d,r)),delete h.id,delete h.session_id,n.turns.push(h)}for(const{data:o}of e.get("message")??[]){const a=o,u=a.id,f=a.client_id||u,d=a.session_id,h=a.parent_message_id,m={session_client_id:"",role:"user",content:"",turn_id:"",turn_offset:0,streaming_status:"pending",creator_kind:"user",creator_ref_id:"",global_offset:0,created_at:i,updated_at:i,...a,server_id:u,client_id:f,sync_status:"synced"};d&&(m.session_client_id=this.resolveSessionClientId(d,r)),delete m.id,delete m.session_id,h&&(m._pending_parent_server_id=h),delete m.parent_message_id,n.messages.push(m)}for(const{data:o}of e.get("rtc")??[]){const a=o,u=a.id,f=a.client_id||u,d=a.session_id;let h,m;if(d){const S=r.get(d);S?(h=S.client_id,m=S.device_id):(gr.warn(`RTC ${f} references unknown session ${d}`),h=d)}const b={session_client_id:"",turn_id:"",offset:0,tool_name:"",status:"pending",parameters:void 0,result:void 0,error_message:void 0,completed_at:void 0,created_at:i,updated_at:i,...a,server_id:u,client_id:f,session_device_id:m,sync_status:"pending"};h&&(b.session_client_id=h),delete b.id,delete b.session_id,n.rtcs.push(b)}return n}async resolveParentMessageIds(e){if(e.length===0)return;const r=new Set;for(const a of e){const u=a._pending_parent_server_id;u&&r.add(u)}if(r.size===0)return;const n=new Map;for(const a of e){const u=a.server_id,f=a.client_id;u&&f&&r.has(u)&&n.set(u,f)}const i=[...r].filter(a=>!n.has(a)),o=new Map(n);if(i.length>0){const u=await zt().messages.where("server_id").anyOf(i).toArray();for(const f of u)o.set(f.server_id,f.client_id)}for(const a of e){const u=a._pending_parent_server_id;if(u){const f=o.get(u);f?a.parent_client_id=f:gr.warn(`[applyUpdates:message] parent message ${u} not found in DB or current batch`),delete a._pending_parent_server_id}}}async resolveDeleteClientIds(e,r){if(e._pendingDeleteServerIds.size===0)return;const n=zt();for(const[i,o]of e._pendingDeleteServerIds){if(o.length===0)continue;let a=[];switch(i){case"session":{for(const f of o){const d=r.get(f);d&&a.push(d.client_id)}const u=o.filter(f=>!r.has(f));if(u.length>0){const f=await n.sessions.where("server_id").anyOf(u).toArray();a.push(...f.map(d=>d.client_id))}break}case"turn":{a=(await n.turns.where("server_id").anyOf(o).toArray()).map(f=>f.client_id);break}case"message":{a=(await n.messages.where("server_id").anyOf(o).toArray()).map(f=>f.client_id);break}case"rtc":{a=(await n.rtcs.where("server_id").anyOf(o).toArray()).map(f=>f.client_id);break}}for(const u of a)this.pushDelete(e,i,u);a.length<o.length&&gr.warn(`[applyUpdates:delete] ${i}: ${o.length-a.length}/${o.length} server_ids could not be resolved to client_ids (records not found in local DB, will be silently skipped)`)}e._pendingDeleteServerIds.clear()}getTablesToLock(e,r){var o,a,u,f;const n=zt(),i=[];return((((o=e.get("session"))==null?void 0:o.length)??0)>0||r.sessions.length>0)&&i.push(n.sessions),((((a=e.get("turn"))==null?void 0:a.length)??0)>0||r.turns.length>0)&&i.push(n.turns),((((u=e.get("message"))==null?void 0:u.length)??0)>0||r.messages.length>0)&&i.push(n.messages),((((f=e.get("rtc"))==null?void 0:f.length)??0)>0||r.rtcs.length>0)&&i.push(n.rtcs),i}async bulkGetExisting(e){const r=zt(),n=e.sessions.map(b=>b.client_id).filter(Boolean),i=e.turns.map(b=>b.client_id).filter(Boolean),o=e.messages.map(b=>b.client_id).filter(Boolean),a=e.rtcs.map(b=>b.client_id).filter(Boolean),[u,f,d,h]=await Promise.all([n.length>0?r.sessions.bulkGet(n):[],i.length>0?r.turns.bulkGet(i):[],o.length>0?r.messages.bulkGet(o):[],a.length>0?r.rtcs.bulkGet(a):[]]),m=(b,S)=>{const O=new Map;return S.forEach((x,w)=>{x&&O.set(b[w],x)}),O};return{sessions:m(n,u),turns:m(i,f),messages:m(o,d),rtcs:m(a,h)}}collectBeforeSnapshots(e,r){for(const[n,i]of r.sessions)e.set(`session:${n}`,i);for(const[n,i]of r.turns)e.set(`turn:${n}`,i);for(const[n,i]of r.messages)e.set(`message:${n}`,i);for(const[n,i]of r.rtcs)e.set(`rtc:${n}`,i)}mergeWithExisting(e,r){const n=(o,a)=>o.map(u=>{const f=u.client_id,d=a.get(f);return d?{...d,...u}:u}),i=(o,a)=>o.map(u=>{const f=u.client_id,d=a.get(f);return d?tm(d.streaming_status,u.streaming_status)?(gr.debug("mergeMessages: skip streaming regression","client_id:",f,"existing:",d.streaming_status,"incoming:",u.streaming_status),d):{...d,...u}:u});return{sessions:n(e.sessions,r.sessions),turns:n(e.turns,r.turns),messages:i(e.messages,r.messages),rtcs:n(e.rtcs,r.rtcs)}}async writebackTurnCountsInTx(e){if(e.length===0)return;const r=zt(),n=new Set;for(const a of e)a.session_client_id&&n.add(a.session_client_id);if(n.size===0)return;const o=[...n].map(async a=>{await r.transaction("rw",r.sessions,r.turns,async()=>{const{pending:u,running:f}=await this.countActiveTurns(a),d=await r.sessions.get(a);d&&(d.pending_turn_count!==u||d.running_turn_count!==f)&&await r.sessions.update(a,{pending_turn_count:u,running_turn_count:f})})});await Promise.all(o)}emitBatchUIUpdates(e,r,n){const i=["sessions","turns","messages","rtcs"],o=["session","turn","message","rtc"];gr.debug("[EntityRepository] emitBatchUIUpdates: sessions:",r.sessions.length,"turns:",r.turns.length,"messages:",r.messages.length,"rtcs:",r.rtcs.length);for(let a=0;a<i.length;a++){const u=r[i[a]],f=o[a];for(const d of u){const h=d.client_id,m=`${f}:${h}`,b=e.get(m),S=b?"updated":"created";f==="turn"&&gr.debug("[EntityRepository] Emitting batch turn UI update:",S,h,"session:",d.session_client_id),da(f,S,h,b,d)}}for(let a=0;a<i.length;a++){const u=n[i[a]],f=o[a];for(const d of u){const h=`${f}:${d}`,m=e.get(h);da(f,"deleted",d,m,{})}}}async _resolveSessionClientId(e,r,n){const i=await this.getSessionByServerId(e);return i?i.client_id:(gr.warn(`${r} ${n} references unknown session ${e}`),e)}async applyUpdateOriginal(e){var r;for(let n=0;n<e.items.length;n++){const i=e.items[n],o=(r=e.data_list)==null?void 0:r[n];o&&await this.applyUpdateItem(i,o)}}async applyUpdateItem(e,r){switch(e.entity){case"session":{const n=r,i={...n,server_id:n.id,client_id:n.client_id||n.id};delete i.id,await this.upsertSession(i,"synced");break}case"turn":{const n=r,i={...n,server_id:n.id,client_id:n.client_id||n.id};delete i.id,n.session_id&&(i.session_client_id=await this._resolveSessionClientId(n.session_id,"Turn",n.client_id||n.id)),delete i.session_id,await this.upsertTurn(i,"synced");const o=i.session_client_id;if(o){const{pending:a,running:u}=await this.countActiveTurns(o);await this.upsertSession({client_id:o,pending_turn_count:a,running_turn_count:u},"synced",{silent:!0,preserveSyncStatus:!0}),da("session","updated",o,{},{pending_turn_count:a,running_turn_count:u})}break}case"message":{const n=r,i={...n,server_id:n.id,client_id:n.client_id||n.id};if(delete i.id,n.session_id&&(i.session_client_id=await this._resolveSessionClientId(n.session_id,"Message",n.client_id||n.id)),delete i.session_id,n.parent_message_id){const o=await this.getMessageByServerId(n.parent_message_id);o?i.parent_client_id=o.client_id:gr.warn(`[applyUpdateItem:message] Message ${n.client_id||n.id} references unknown parent ${n.parent_message_id}`)}delete i.parent_message_id,await this.upsertMessage(i,"synced");break}case"rtc":{const n=r;let i,o;if(n.session_id){const u=await this.getSessionByServerId(n.session_id);u?(i=u.client_id,o=u.device_id):(gr.warn(`RTC ${n.client_id||n.id} references unknown session ${n.session_id}`),i=n.session_id)}const a={...n,server_id:n.id,client_id:n.client_id||n.id,session_client_id:i||"",session_device_id:o};delete a.id,delete a.session_id,await this.upsertRtc(a,"pending");break}}}}let ql=null;function EE(t){if(ql){gr.warn("Already initialized, ignoring re-init");return}ql=new TE(t)}function _E(){if(!ql)throw new Error("[EntityRepository] Not initialized - call initEntityRepository(deviceId) first");return ql}const Ha=Bs("DebugHistoryRepository");function xE(t){return{id:t.id,function_name:t.functionName,params:t.params,success:t.success,duration_ms:t.durationMs,timestamp:t.timestamp,logs:JSON.stringify(t.logs),error_message:t.errorMessage,result:t.result!==void 0?JSON.stringify(t.result):void 0}}function PE(t){let e=[];try{e=JSON.parse(t.logs)}catch(n){Ha.warn("Failed to parse logs JSON for item",t.id,n)}let r;if(t.result!==void 0)try{r=JSON.parse(t.result)}catch(n){Ha.warn("Failed to parse result JSON for item",t.id,n),r=t.result}return{id:t.id,functionName:t.function_name,params:t.params,success:t.success,durationMs:t.duration_ms,timestamp:t.timestamp,logs:e,errorMessage:t.error_message,result:r}}let Fo=null;class wE{async add(e){const r=zt();Ha.debug("Adding debug history item:",e.id,e.functionName),await r.debugHistory.add(xE(e))}async query(e,r,n=20){const o=zt().debugHistory;Ha.debug("Query debug history:",{functionName:e,cursor:r,limit:n});const a=e?await o.where("function_name").equals(e).count():await o.count();let u;if(e){const m=await(r?(()=>{const[b]=r.split("|"),S=parseInt(b,10);return o.where("[function_name+timestamp]").between([e,fa.minKey],[e,S],!0,!0).reverse()})():o.where("[function_name+timestamp]").between([e,fa.minKey],[e,fa.maxKey],!0,!0).reverse()).toArray();if(r){const[b,S]=r.split("|"),O=parseInt(b,10);u=m.filter(x=>x.timestamp<O||x.timestamp===O&&x.id<S).slice(0,n)}else u=m.slice(0,n)}else if(r){const[h,m]=r.split("|"),b=parseInt(h,10);u=await o.where("timestamp").below(b).reverse().limit(n*2).toArray(),u=u.filter(S=>S.timestamp<b||S.timestamp===b&&S.id<m).slice(0,n)}else u=await o.orderBy("timestamp").reverse().limit(n).toArray();let f;if(u.length===n){const h=u[u.length-1];f=`${h.timestamp}|${h.id}`}return{items:u.map(PE),nextCursor:f,total:a}}async count(e){const n=zt().debugHistory;return e?n.where("function_name").equals(e).count():n.count()}async batchDelete(e){if(e.length===0)return;const r=zt();Ha.debug("Batch deleting debug history items:",e.length),await r.debugHistory.bulkDelete(e)}async clear(){const e=zt();Ha.debug("Clearing all debug history"),await e.debugHistory.clear()}}function nm(){return Fo||(Fo=new wE),Fo}function AE(){return Fo||nm()}const In=Bs("VirtualFS");class za extends Error{constructor(e,r){super(r),this.code=e,this.name="PathError"}}function Ni(t){if(!t||typeof t!="string")throw new za("EINVAL","Path must be a non-empty string");let e=t.startsWith("/")?t:"/"+t;const r=e.split("/").filter(n=>n&&n!==".");for(const n of r)if(n==="..")throw new za("EINVAL","Path traversal (..) is not allowed");return e="/"+r.join("/"),e==="/"?"/":e.replace(/\/$/,"")}function CE(t){const e=Ni(t),r=e.lastIndexOf("/");return e.substring(r+1)}function $o(t,e){const r="\0DOUBLESTAR\0",n="\0DOTSTAR\0",o=t.replace(/\*\*/g,r).replace(/[.+^${}()|[\]\\/+]/g,"\\$&").replace(new RegExp(r,"g"),n).replace(/\*/g,"[^\\/]*").replace(/\?/g,"[^\\/]").replace(new RegExp(n,"g"),".*");return new RegExp(`^${o}$`).test(e)}class IE{async read(e,r,n){const i=Ni(e);In.debug("read:",i,"offset:",r,"limit:",n);const a=await zt().fileSystemEntries.get(i);if(!a)throw In.debug("read: file not found:",i),new za("ENOENT",`File not found: ${i}`);let u=a.content;if(r!==void 0||n!==void 0){const f=u.split(`
14
14
  `),d=r!==void 0?Math.max(0,r-1):0,h=n!==void 0?d+n:f.length;u=f.slice(d,h).join(`