1var Bn=Object.defineProperty,Fn=Object.defineProperties,$n=Object.getOwnPropertyDescriptors,Ot=Object.getOwnPropertySymbols,Hi=Object.prototype.hasOwnProperty,Gi=Object.prototype.propertyIsEnumerable,Ji=t=>{throw TypeError(t)},gi=(t,e,i)=>e in t?Bn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,v=(t,e)=>{for(var i in e||(e={}))Hi.call(e,i)&&gi(t,i,e[i]);if(Ot)for(var i of Ot(e))Gi.call(e,i)&&gi(t,i,e[i]);return t},k=(t,e)=>Fn(t,$n(e)),ji=(t,e)=>{var i={};for(var n in t)Hi.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&Ot)for(var n of Ot(t))e.indexOf(n)<0&&Gi.call(t,n)&&(i[n]=t[n]);return i},ci=(t,e,i)=>e.has(t)||Ji("Cannot "+i),o=(t,e,i)=>(ci(t,e,"read from private field"),i?i.call(t):e.get(t)),f=(t,e,i)=>e.has(t)?Ji("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),y=(t,e,i,n)=>(ci(t,e,"write to private field"),e.set(t,i),i),Z=(t,e,i)=>(ci(t,e,"access private method"),i),l=(t,e,i)=>new Promise((n,r)=>{var s=h=>{try{a(i.next(h))}catch(u){r(u)}},c=h=>{try{a(i.throw(h))}catch(u){r(u)}},a=h=>h.done?n(h.value):Promise.resolve(h.value).then(s,c);a((i=i.apply(t,e)).next())});function bi(t){if(!t)return"";const e=[];for(const[i,n]of Object.entries(t))if(n){const r=typeof n=="string"?n:n.id;e.push(`${i}:${r}`)}return e.sort().join(",")}function Kn({subscriberId:t,subscriber:e}){return e?typeof e=="string"?{subscriberId:e}:e:t?{subscriberId:t}:{subscriberId:""}}function Dn({topicKey:t,subscriberId:e,contextKey:i}){const n=`tk_${t}:si_${e}`;return i&&i.length>0?`${n}:ctx_${i}`:n}var Yi=(t=>(t.READ="read",t.SEEN="seen",t.SNOOZED="snoozed",t.UNREAD="unread",t.UNSEEN="unseen",t.UNSNOOZED="unsnoozed",t))(Yi||{}),Xi=(t=>(t.GLOBAL="global",t.TEMPLATE="template",t))(Xi||{}),Qi=(t=>(t.IN_APP="in_app",t.EMAIL="email",t.SMS="sms",t.CHAT="chat",t.PUSH="push",t))(Qi||{}),Zi=(t=>(t.RECEIVED="notification_received",t.UNREAD="unread_count_changed",t.UNSEEN="unseen_count_changed",t))(Zi||{}),en=(t=>(t.HIGH="high",t.MEDIUM="medium",t.LOW="low",t.NONE="none",t))(en||{}),tn=(t=>(t.CRITICAL="critical",t.NON_CRITICAL="nonCritical",t.ALL="all",t))(tn||{}),_=class extends Error{constructor(t,e){super(t),this.originalError=e}},nn=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r,optimisticValue:s}=ie(n,{isRead:!0,readAt:new Date().toISOString(),isArchived:!1,archivedAt:void 0},{emitter:e,apiService:i});try{e.emit("notification.read.pending",{args:n,data:s});const c=yield i.read(r),a=new N(c,e,i);return e.emit("notification.read.resolved",{args:n,data:a}),{data:a}}catch(c){return e.emit("notification.read.resolved",{args:n,error:c}),{error:new _("Failed to read notification",c)}}}),rn=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r,optimisticValue:s}=ie(n,{isRead:!1,readAt:null,isArchived:!1,archivedAt:void 0},{emitter:e,apiService:i});try{e.emit("notification.unread.pending",{args:n,data:s});const c=yield i.unread(r),a=new N(c,e,i);return e.emit("notification.unread.resolved",{args:n,data:a}),{data:a}}catch(c){return e.emit("notification.unread.resolved",{args:n,error:c}),{error:new _("Failed to unread notification",c)}}}),sn=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r,optimisticValue:s}=ie(n,{isSeen:!0},{emitter:e,apiService:i});try{if(e.emit("notification.seen.pending",{args:n,data:s}),yield i.seen(r),!s)throw new Error("Failed to create optimistic value for notification");const c=new N(s,e,i);return e.emit("notification.seen.resolved",{args:n,data:c}),{data:c}}catch(c){return e.emit("notification.seen.resolved",{args:n,error:c}),{error:new _("Failed to mark notification as seen",c)}}}),on=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r,optimisticValue:s}=ie(n,{isArchived:!0,archivedAt:new Date().toISOString(),isRead:!0,readAt:new Date().toISOString()},{emitter:e,apiService:i});try{e.emit("notification.archive.pending",{args:n,data:s});const c=yield i.archive(r),a=new N(c,e,i);return e.emit("notification.archive.resolved",{args:n,data:a}),{data:a}}catch(c){return e.emit("notification.archive.resolved",{args:n,error:c}),{error:new _("Failed to archive notification",c)}}}),cn=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r,optimisticValue:s}=ie(n,{isArchived:!1,archivedAt:null,isRead:!0,readAt:new Date().toISOString()},{emitter:e,apiService:i});try{e.emit("notification.unarchive.pending",{args:n,data:s});const c=yield i.unarchive(r),a=new N(c,e,i);return e.emit("notification.unarchive.resolved",{args:n,data:a}),{data:a}}catch(c){return e.emit("notification.unarchive.resolved",{args:n,error:c}),{error:new _("Failed to unarchive notification",c)}}}),an=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r,optimisticValue:s}=ie(n,{isSnoozed:!0,snoozedUntil:n.snoozeUntil},{emitter:e,apiService:i});try{e.emit("notification.snooze.pending",{args:n,data:s});const c=yield i.snooze(r,n.snoozeUntil),a=new N(c,e,i);return e.emit("notification.snooze.resolved",{args:n,data:a}),{data:a}}catch(c){return e.emit("notification.snooze.resolved",{args:n,error:c}),{error:new _("Failed to snooze notification",c)}}}),hn=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r,optimisticValue:s}=ie(n,{isSnoozed:!1,snoozedUntil:null},{emitter:e,apiService:i});try{e.emit("notification.unsnooze.pending",{args:n,data:s});const c=yield i.unsnooze(r),a=new N(c,e,i);return e.emit("notification.unsnooze.resolved",{args:n,data:a}),{data:a}}catch(c){return e.emit("notification.unsnooze.resolved",{args:n,error:c}),{error:new _("Failed to unsnooze notification",c)}}}),Nt=t=>l(null,[t],function*({emitter:e,apiService:i,args:n,actionType:r}){const s=r==="primary"?{primaryAction:k(v({},"notification"in n?n.notification.primaryAction:{}),{isCompleted:!0})}:{secondaryAction:k(v({},"notification"in n?n.notification.secondaryAction:{}),{isCompleted:!0})},{notificationId:c,optimisticValue:a}=ie(n,s,{emitter:e,apiService:i});try{e.emit("notification.complete_action.pending",{args:n,data:a});const h=yield i.completeAction({actionType:r,notificationId:c}),u=new N(h,e,i);return e.emit("notification.complete_action.resolved",{args:n,data:u}),{data:u}}catch(h){return e.emit("notification.complete_action.resolved",{args:n,error:h}),{error:new _(`Failed to complete ${r} action on the notification`,h)}}}),It=t=>l(null,[t],function*({emitter:e,apiService:i,args:n,actionType:r}){const s=r==="primary"?{primaryAction:k(v({},"notification"in n?n.notification.primaryAction:{}),{isCompleted:!1})}:{secondaryAction:k(v({},"notification"in n?n.notification.secondaryAction:{}),{isCompleted:!1})},{notificationId:c,optimisticValue:a}=ie(n,s,{emitter:e,apiService:i});try{e.emit("notification.revert_action.pending",{args:n,data:a});const h=yield i.revertAction({actionType:r,notificationId:c}),u=new N(h,e,i);return e.emit("notification.revert_action.resolved",{args:n,data:u}),{data:u}}catch(h){return e.emit("notification.revert_action.resolved",{args:n,error:h}),{error:new _("Failed to fetch notifications",h)}}}),ie=(t,e,i)=>"notification"in t?{notificationId:t.notification.id,optimisticValue:new N(v(v({},t.notification),e),i.emitter,i.apiService)}:{notificationId:t.notificationId},qn=t=>l(null,[t],function*({emitter:e,inboxService:i,notificationsCache:n,tags:r,data:s}){try{const a=n.getUniqueNotifications({tags:r,data:s}).map(h=>new N(k(v({},h),{isRead:!0,readAt:new Date().toISOString(),isArchived:!1,archivedAt:void 0}),e,i));return e.emit("notifications.read_all.pending",{args:{tags:r,data:s},data:a}),yield i.readAll({tags:r,data:s}),e.emit("notifications.read_all.resolved",{args:{tags:r,data:s},data:a}),{}}catch(c){return e.emit("notifications.read_all.resolved",{args:{tags:r,data:s},error:c}),{error:new _("Failed to read all notifications",c)}}}),Si=t=>l(null,[t],function*({emitter:e,inboxService:i,notificationsCache:n,notificationIds:r,tags:s,data:c}){try{const a=n.getUniqueNotifications({tags:s,data:c}),u=(r&&r.length>0?a.filter(d=>r.includes(d.id)):a).map(d=>new N(k(v({},d),{isSeen:!0,firstSeenAt:d.firstSeenAt||new Date().toISOString()}),e,i));return e.emit("notifications.seen_all.pending",{args:{notificationIds:r,tags:s,data:c},data:u}),yield i.markAsSeen({notificationIds:r,tags:s,data:c}),e.emit("notifications.seen_all.resolved",{args:{notificationIds:r,tags:s,data:c},data:u}),{}}catch(a){return e.emit("notifications.seen_all.resolved",{args:{notificationIds:r,tags:s,data:c},error:a}),{error:new _("Failed to mark all notifications as seen",a)}}}),zn=t=>l(null,[t],function*({emitter:e,inboxService:i,notificationsCache:n,tags:r,data:s}){try{const a=n.getUniqueNotifications({tags:r,data:s}).map(h=>new N(k(v({},h),{isRead:!0,readAt:new Date().toISOString(),isArchived:!0,archivedAt:new Date().toISOString()}),e,i));return e.emit("notifications.archive_all.pending",{args:{tags:r,data:s},data:a}),yield i.archiveAll({tags:r,data:s}),e.emit("notifications.archive_all.resolved",{args:{tags:r,data:s},data:a}),{}}catch(c){return e.emit("notifications.archive_all.resolved",{args:{tags:r,data:s},error:c}),{error:new _("Failed to archive all notifications",c)}}}),Vn=t=>l(null,[t],function*({emitter:e,inboxService:i,notificationsCache:n,tags:r,data:s}){try{const a=n.getUniqueNotifications({tags:r,data:s,read:!0}).map(h=>new N(k(v({},h),{isArchived:!0,archivedAt:new Date().toISOString()}),e,i));return e.emit("notifications.archive_all_read.pending",{args:{tags:r,data:s},data:a}),yield i.archiveAllRead({tags:r,data:s}),e.emit("notifications.archive_all_read.resolved",{args:{tags:r,data:s},data:a}),{}}catch(c){return e.emit("notifications.archive_all_read.resolved",{args:{tags:r,data:s},error:c}),{error:new _("Failed to archive all read notifications",c)}}}),ln=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const{notificationId:r}=ie(n,{},{emitter:e,apiService:i});try{return e.emit("notification.delete.pending",{args:n}),yield i.delete(r),e.emit("notification.delete.resolved",{args:n}),{}}catch(s){return e.emit("notification.delete.resolved",{args:n,error:s}),{error:new _("Failed to delete notification",s)}}}),Hn=t=>l(null,[t],function*({emitter:e,inboxService:i,notificationsCache:n,tags:r,data:s}){try{const c=n.getUniqueNotifications({tags:r,data:s});return e.emit("notifications.delete_all.pending",{args:{tags:r,data:s},data:c}),yield i.deleteAll({tags:r,data:s}),e.emit("notifications.delete_all.resolved",{args:{tags:r,data:s}}),{}}catch(c){return e.emit("notifications.delete_all.resolved",{args:{tags:r,data:s},error:c}),{error:new _("Failed to delete all notifications",c)}}}),I,F,N=class{constructor(t,e,i){f(this,I),f(this,F),y(this,I,e),y(this,F,i),this.id=t.id,this.transactionId=t.transactionId,this.subject=t.subject,this.body=t.body,this.to=t.to,this.isRead=t.isRead,this.isSeen=t.isSeen,this.isArchived=t.isArchived,this.isSnoozed=t.isSnoozed,this.snoozedUntil=t.snoozedUntil,this.deliveredAt=t.deliveredAt,this.createdAt=t.createdAt,this.readAt=t.readAt,this.firstSeenAt=t.firstSeenAt,this.archivedAt=t.archivedAt,this.avatar=t.avatar,this.primaryAction=t.primaryAction,this.secondaryAction=t.secondaryAction,this.channelType=t.channelType,this.tags=t.tags,this.redirect=t.redirect,this.data=t.data,this.workflow=t.workflow,this.severity=t.severity}read(){return nn({emitter:o(this,I),apiService:o(this,F),args:{notification:this}})}unread(){return rn({emitter:o(this,I),apiService:o(this,F),args:{notification:this}})}seen(){return sn({emitter:o(this,I),apiService:o(this,F),args:{notification:this}})}archive(){return on({emitter:o(this,I),apiService:o(this,F),args:{notification:this}})}unarchive(){return cn({emitter:o(this,I),apiService:o(this,F),args:{notification:this}})}delete(){return ln({emitter:o(this,I),apiService:o(this,F),args:{notification:this}})}snooze(t){return an({emitter:o(this,I),apiService:o(this,F),args:{notification:this,snoozeUntil:t}})}unsnooze(){return hn({emitter:o(this,I),apiService:o(this,F),args:{notification:this}})}completePrimary(){if(!this.primaryAction)throw new Error("Primary action is not available");return Nt({emitter:o(this,I),apiService:o(this,F),args:{notification:this},actionType:"primary"})}completeSecondary(){if(!this.primaryAction)throw new Error("Secondary action is not available");return Nt({emitter:o(this,I),apiService:o(this,F),args:{notification:this},actionType:"secondary"})}revertPrimary(){if(!this.primaryAction)throw new Error("Primary action is not available");return It({emitter:o(this,I),apiService:o(this,F),args:{notification:this},actionType:"primary"})}revertSecondary(){if(!this.primaryAction)throw new Error("Secondary action is not available");return It({emitter:o(this,I),apiService:o(this,F),args:{notification:this},actionType:"secondary"})}on(t,e){const i=o(this,I).on(t,e);return()=>{i()}}off(t,e){o(this,I).off(t,e)}};I=new WeakMap;F=new WeakMap;function Gn({emitter:t,inboxService:e,notification:i}){return new N(i,t,e)}function Kt(t,e){return t&&e?"boldItalic":t?"bold":e?"italic":"text"}var Qs=t=>{const e=[];let i="",n=!1,r=!1,s=-2;for(let c=0;c<t.length;c+=1)if(t[c]==="\\"&&t[c+1]==="*")i+="*",c+=1;else if(t[c]==="*"&&t[c+1]==="*")i&&(e.push({type:Kt(n,r),content:i}),i=""),n=!n,s=c+1,c+=1;else if(t[c]==="*"){const a=c>0&&t[c-1]==="*",h=s===c-1;a&&!h?i+=t[c]:(i&&(e.push({type:Kt(n,r),content:i}),i=""),r=!r)}else i+=t[c];return i&&e.push({type:Kt(n,r),content:i}),e};function Jn(t){return{all:t=t||new Map,on:function(e,i){var n=t.get(e);n?n.push(i):t.set(e,[i])},off:function(e,i){var n=t.get(e);n&&(i?n.splice(n.indexOf(i)>>>0,1):t.set(e,[]))},emit:function(e,i){var n=t.get(e);n&&n.slice().map(function(r){r(i)}),(n=t.get("*"))&&n.slice().map(function(r){r(e,i)})}}}const Ut=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof globalThis<"u"&&globalThis,jn=(function(){try{new Ut.Event("")}catch{return!0}return!1})(),Yn=(function(){try{new Ut.EventTarget}catch{return!0}return!1})();jn&&(Ut.Event=(function(){function t(e,i){this.bubbles=!!i&&!!i.bubbles,this.cancelable=!!i&&!!i.cancelable,this.composed=!!i&&!!i.composed,this.type=e}return t})());Yn&&(Ut.EventTarget=(function(){function t(){this.__listeners=new Map}return t.prototype=Object.create(Object.prototype),t.prototype.addEventListener=function(e,i,n){if(arguments.length<2)throw new TypeError("TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only "+arguments.length+" present.");const r=this.__listeners,s=e.toString();r.has(s)||r.set(s,new Map);const c=r.get(s);c.has(i)||c.set(i,n)},t.prototype.removeEventListener=function(e,i,n){if(arguments.length<2)throw new TypeError("TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only "+arguments.length+" present.");const r=this.__listeners,s=e.toString();if(r.has(s)){const c=r.get(s);c.has(i)&&c.delete(i)}},t.prototype.dispatchEvent=function(e){if(!(e instanceof Event))throw new TypeError("Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'.");const i=e.type,r=this.__listeners.get(i);if(r)for(var s of r.entries()){const c=s[0],a=s[1];try{typeof c=="function"?c.call(this,e):c&&typeof c.handleEvent=="function"&&c.handleEvent(e)}catch(h){setTimeout(()=>{throw h})}a&&a.once&&r.delete(c)}return!0},t})());(!globalThis.EventTarget||!globalThis.Event)&&console.error(` 2 PartySocket requires a global 'EventTarget' class to be available! 3 You can polyfill this global by adding this to your code before any partysocket imports: 4 5 \`\`\` 6 import 'partysocket/event-target-polyfill'; 7 \`\`\` 8 Please file an issue at https://github.com/partykit/partykit if you're still having trouble. 9`);
9var un=class extends Event{message;error;constructor(t,e){super("error",e),this.message=t.message,this.error=t}},dn=class extends Event{code;reason;wasClean=!0;constructor(t=1e3,e="",i){super("close",i),this.code=t,this.reason=e}};const Dt={Event,ErrorEvent:un,CloseEvent:dn};function Xn(t,e){if(!t)throw new Error(e)}function Qn(t){return new t.constructor(t.type,t)}function Zn(t){return"data"in t?new MessageEvent(t.type,t):"code"in t||"reason"in t?new dn(t.code||1999,t.reason||"unknown reason",t):"error"in t?new un(t.error,t):new Event(t.type,t)}const er=typeof process<"u"&&typeof process.versions?.node<"u",tr=typeof navigator<"u"&&navigator.product==="ReactNative",Xe=er||tr?Zn:Qn,le={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:Number.POSITIVE_INFINITY,maxEnqueuedMessages:Number.POSITIVE_INFINITY};let ki=!1;var ir=class fe extends EventTarget{_ws;_retryCount=-1;_uptimeTimeout;_connectTimeout;_shouldReconnect=!0;_connectLock=!1;_binaryType="blob";_closeCalled=!1;_messageQueue=[];_debugLogger=console.log.bind(console);_url;_protocols;_options;constructor(e,i,n={}){super(),this._url=e,this._protocols=i,this._options=n,this._options.startClosed&&(this._shouldReconnect=!1),this._options.debugLogger&&(this._debugLogger=this._options.debugLogger),this._connect()}static get CONNECTING(){return 0}static get OPEN(){return 1}static get CLOSING(){return 2}static get CLOSED(){return 3}get CONNECTING(){return fe.CONNECTING}get OPEN(){return fe.OPEN}get CLOSING(){return fe.CLOSING}get CLOSED(){return fe.CLOSED}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return Math.max(this._retryCount,0)}get bufferedAmount(){return this._messageQueue.reduce((e,i)=>(typeof i=="string"?e+=i.length:i instanceof Blob?e+=i.size:e+=i.byteLength,e),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.startClosed?fe.CLOSED:fe.CONNECTING}get url(){return this._ws?this._ws.url:""}get shouldReconnect(){return this._shouldReconnect}onclose=null;onerror=null;onmessage=null;onopen=null;close(e=1e3,i){if(this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(e,i)}reconnect(e,i){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,i),this._connect())}send(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{const{maxEnqueuedMessages:i=le.maxEnqueuedMessages}=this._options;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}}_debug(...e){this._options.debug&&this._debugLogger("RWS>",...e)}_getNextDelay(){const{reconnectionDelayGrowFactor:e=le.reconnectionDelayGrowFactor,minReconnectionDelay:i=le.minReconnectionDelay,maxReconnectionDelay:n=le.maxReconnectionDelay}=this._options;let r=0;return this._retryCount>0&&(r=i*e**(this._retryCount-1),r>n&&(r=n)),this._debug("next delay",r),r}_wait(){return new Promise(e=>{setTimeout(e,this._getNextDelay())})}_getNextProtocols(e){if(!e)return Promise.resolve(null);if(typeof e=="string"||Array.isArray(e))return Promise.resolve(e);if(typeof e=="function"){const i=e();if(!i)return Promise.resolve(null);if(typeof i=="string"||Array.isArray(i))return Promise.resolve(i);if(i.then)return i}throw Error("Invalid protocols")}_getNextUrl(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){const i=e();if(typeof i=="string")return Promise.resolve(i);if(i.then)return i}throw Error("Invalid URL")}_connect(){if(this._connectLock||!this._shouldReconnect)return;this._connectLock=!0;
9const{maxRetries:e=le.maxRetries,connectionTimeout:i=le.connectionTimeout}=this._options;if(this._retryCount>=e){this._debug("max retries reached",this._retryCount,">=",e),this._connectLock=!1;return}this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),this._wait().then(()=>Promise.all([this._getNextUrl(this._url),this._getNextProtocols(this._protocols||null)])).then(([n,r])=>{if(this._closeCalled){this._connectLock=!1;return}!this._options.WebSocket&&typeof WebSocket>"u"&&!ki&&(console.error(`â¼ï¸ No WebSocket implementation available. You should define options.WebSocket. 10 11For example, if you're using node.js, run \`npm install ws\`, and then in your code: 12 13import PartySocket from 'partysocket'; 14import WS from 'ws'; 15 16const partysocket = new PartySocket({ 17 host: "127.0.0.1:1999", 18 room: "test-room", 19 WebSocket: WS 20}); 21 22`),ki=!0);const s=this._options.WebSocket||WebSocket;this._debug("connect",{url:n,protocols:r}),this._ws=r?new s(n,r):new s(n),this._ws.binaryType=this._binaryType,this._connectLock=!1,this._addListeners(),this._connectTimeout=setTimeout(()=>this._handleTimeout(),i)}).catch(n=>{this._connectLock=!1,this._handleError(new Dt.ErrorEvent(Error(n.message),this))})}_handleTimeout(){this._debug("timeout event"),this._handleError(new Dt.ErrorEvent(Error("TIMEOUT"),this))}_disconnect(e=1e3,i){if(this._clearTimeouts(),!!this._ws){this._removeListeners();try{(this._ws.readyState===this.OPEN||this._ws.readyState===this.CONNECTING)&&this._ws.close(e,i),this._handleClose(new Dt.CloseEvent(e,i,this))}catch{}}}_acceptOpen(){this._debug("accept open"),this._retryCount=0}_handleOpen=e=>{this._debug("open event");const{minUptime:i=le.minUptime}=this._options;clearTimeout(this._connectTimeout),this._uptimeTimeout=setTimeout(()=>this._acceptOpen(),i),Xn(this._ws,"WebSocket is not defined"),this._ws.binaryType=this._binaryType,this._messageQueue.forEach(n=>{this._ws?.send(n)}),this._messageQueue=[],this.onopen&&this.onopen(e),this.dispatchEvent(Xe(e))};_handleMessage=e=>{this._debug("message event"),this.onmessage&&this.onmessage(e),this.dispatchEvent(Xe(e))};_handleError=e=>{this._debug("error event",e.message),this._disconnect(void 0,e.message==="TIMEOUT"?"timeout":void 0),this.onerror&&this.onerror(e),this._debug("exec error listeners"),this.dispatchEvent(Xe(e)),this._connect()};_handleClose=e=>{this._debug("close event"),this._clearTimeouts(),this._shouldReconnect&&this._connect(),this.onclose&&this.onclose(e),this.dispatchEvent(Xe(e))};_removeListeners(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))}_addListeners(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))}_clearTimeouts(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)}};const te=Object.create(null);te.open="0";te.close="1";te.ping="2";te.pong="3";te.message="4";te.upgrade="5";te.noop="6";const rt=Object.create(null);Object.keys(te).forEach(t=>{rt[te[t]]=t});const Gt={type:"error",data:"parser error"},fn=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",pn=typeof ArrayBuffer=="function",yn=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,ai=({type:t,data:e},i,n)=>fn&&e instanceof Blob?i?n(e):Ei(e,n):pn&&(e instanceof ArrayBuffer||yn(e))?i?n(e):Ei(new Blob([e]),n):n(te[t]+(e||"")),Ei=(t,e)=>{const i=new FileReader;return i.onload=function(){const n=i.result.split(",")[1];e("b"+(n||""))},i.readAsDataURL(t)};function Ai(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let qt;function nr(t,e){if(fn&&t.data instanceof Blob)return t.data.arrayBuffer().then(Ai).then(e);if(pn&&(t.data instanceof ArrayBuffer||yn(t.data)))return e(Ai(t.data));ai(t,!1,i=>{qt||(qt=new TextEncoder),e(qt.encode(i))})}const Ci="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
22+/",De=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let t=0;t<Ci.length;t++)De[Ci.charCodeAt(t)]=t;const rr=t=>{let e=t.length*.75,i=t.length,n,r=0,s,c,a,h;t[t.length-1]==="="&&(e--,t[t.length-2]==="="&&e--);const u=new ArrayBuffer(e),d=new Uint8Array(u);for(n=0;n<i;n+=4)s=De[t.charCodeAt(n)],c=De[t.charCodeAt(n+1)],a=De[t.charCodeAt(n+2)],h=De[t.charCodeAt(n+3)],d[r++]=s<<2|c>>4,d[r++]=(c&15)<<4|a>>2,d[r++]=(a&3)<<6|h&63;return u},sr=typeof ArrayBuffer=="function",hi=(t,e)=>{if(typeof t!="string")return{type:"message",data:vn(t,e)};const i=t.charAt(0);return i==="b"?{type:"message",data:or(t.substring(1),e)}:rt[i]?t.length>1?{type:rt[i],data:t.substring(1)}:{type:rt[i]}:Gt},or=(t,e)=>{if(sr){const i=rr(t);return vn(i,e)}else return{base64:!0,data:t}},vn=(t,e)=>e==="blob"?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,mn="�",cr=(t,e)=>{const i=t.length,n=new Array(i);let r=0;t.forEach((s,c)=>{ai(s,!1,a=>{n[c]=a,++r===i&&e(n.join(mn))})})},ar=(t,e)=>{const i=t.split(mn),n=[];for(let r=0;r<i.length;r++){const s=hi(i[r],e);if(n.push(s),s.type==="error")break}return n};function hr(){return new TransformStream({transform(t,e){nr(t,i=>{const n=i.length;let r;if(n<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,n);else if(n<65536){r=new Uint8Array(3);const s=new DataView(r.buffer);s.setUint8(0,126),s.setUint16(1,n)}else{r=new Uint8Array(9);const s=new DataView(r.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(n))}t.data&&typeof t.data!="string"&&(r[0]|=128),e.enqueue(r),e.enqueue(i)})}})}let zt;function Qe(t){return t.reduce((e,i)=>e+i.length,0)}function Ze(t,e){if(t[0].length===e)return t.shift();const i=new Uint8Array(e);let n=0;for(let r=0;r<e;r++)i[r]=t[0][n++],n===t[0].length&&(t.shift(),n=0);return t.length&&n<t[0].length&&(t[0]=t[0].slice(n)),i}function lr(t,e){zt||(zt=new TextDecoder);const i=[];let n=0,r=-1,s=!1;return new TransformStream({transform(c,a){for(i.push(c);;){if(n===0){if(Qe(i)<1)break;const h=Ze(i,1);s=(h[0]&128)===128,r=h[0]&127,r<126?n=3:r===126?n=1:n=2}else if(n===1){if(Qe(i)<2)break;const h=Ze(i,2);r=new DataView(h.buffer,h.byteOffset,h.length).getUint16(0),n=3}else if(n===2){if(Qe(i)<8)break;const h=Ze(i,8),u=new DataView(h.buffer,h.byteOffset,h.length),d=u.getUint32(0);if(d>Math.pow(2,21)-1){a.enqueue(Gt);break}r=d*Math.pow(2,32)+u.getUint32(4),n=3}else{if(Qe(i)<r)break;const h=Ze(i,r);a.enqueue(hi(s?h:zt.decode(h),e)),n=0}if(r===0||r>t){a.enqueue(Gt);break}}}})}const _n=4;function T(t){if(t)return ur(t)}function ur(t){for(var e in T.prototype)t[e]=T.prototype[e];return t}T.prototype.on=T.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this};T.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this};T.prototype.off=T.prototype.removeListener=T.prototype.removeAllListeners=T.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var i=this._callbacks["$"+t];if(!i)return this;if(arguments.length==1)return delete this._callbacks["$"+t],this;for(var n,r=0;r<i.length;r++)if(n=i[r],n===e||n.fn===e){i.splice(r,1);break}return i.length===0&&delete this._callbacks["$"+t],this};T.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),i=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(i){i=i.slice(0);for(var n=0,r=i.length;n<r;++n)i[n].apply(this,e)}return this};T.prototype.emitReserved=T.prototype.emit;T.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]};T.prototype.hasListeners=function(t){return!!this.listeners(t).length};const q=typeof self<"u"?self:typeof window<"u"?window:Function("return this")();function wn(t,...e){return e.reduce((i,n)=>(t.hasOwnProperty(n)&&(i[n]=t[n]),i),{})}const dr=q.setTimeout,fr=q.clearTimeout;function Wt(t,e){e.useNativeTimers?(t.setTimeoutFn=dr.bind(q),t.clearTimeoutFn=fr.bind(q)):(t.setTimeoutFn=q.setTimeout.bind(q),t.clearTimeoutFn=q.clearTimeout.bind(q))}const pr=1.33;function yr(t){return typeof t=="string"?vr(t):Math.ceil((t.byteLength||t.size)*pr)}function vr(t){let e=0,i=0;for(let n=0,r=t.length;n<r;n++)e=t.charCodeAt(n),e<128?i+=1:e<2048?i+=2:e<55296||e>=57344?i+=3:(n++,i+=4);return i}function mr(t){let e="";for(let i in t)t.hasOwnProperty(i)&&(e.length&&(e+="&"),e+=encodeURIComponent(i)+"="+encodeURIComponent(t[i]));return e}function _r(t){let e={},i=t.split("&");for(let n=0,r=i.length;n<r;n++){let s=i[n].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}
22class wr extends Error{constructor(e,i,n){super(e),this.description=i,this.context=n,this.type="TransportError"}}class li extends T{constructor(e){super(),this.writable=!1,Wt(this,e),this.opts=e,this.query=e.query,this.socket=e.socket}onError(e,i,n){return super.emitReserved("error",new wr(e,i,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const i=hi(e,this.socket.binaryType);this.onPacket(i)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,i={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(i)}_hostname(){const e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&+(this.opts.port!==443)||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){const i=mr(e);return i.length?"?"+i:""}}const gn="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),Jt=64,gr={};let Ti=0,et=0,Oi;function Ni(t){let e="";do e=gn[t%Jt]+e,t=Math.floor(t/Jt);while(t>0);return e}function bn(){const t=Ni(+new Date);return t!==Oi?(Ti=0,Oi=t):t+"."+Ni(Ti++)}for(;et<Jt;et++)gr[gn[et]]=et;let Sn=!1;try{Sn=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const br=Sn;function kn(t){const e=t.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||br))return new XMLHttpRequest}catch{}if(!e)try{return new q[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}function Sr(){}const kr=(function(){return new kn({xdomain:!1}).responseType!=null})();class Er extends li{constructor(e){if(super(e),this.polling=!1,typeof location<"u"){const n=location.protocol==="https:";let r=location.port;r||(r=n?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}const i=e&&e.forceBase64;this.supportsBinary=kr&&!i,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const i=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let n=0;this.polling&&(n++,this.once("pollComplete",function(){--n||i()})),this.writable||(n++,this.once("drain",function(){--n||i()}))}else i()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){const i=n=>{if(this.readyState==="opening"&&n.type==="open"&&this.onOpen(),n.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(n)};ar(e,this.socket.binaryType).forEach(i),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};this.readyState==="open"?e():this.once("open",e)}write(e){this.writable=!1,cr(e,i=>{this.doWrite(i,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",i=this.query||{};return this.opts.timestampRequests!==!1&&(i[this.opts.timestampParam]=bn()),!this.supportsBinary&&!i.sid&&(i.b64=1),this.createUri(e,i)}request(e={}){return Object.assign(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new ee(this.uri(),e)}doWrite(e,i){const n=this.request({method:"POST",data:e});n.on("success",i),n.on("error",(r,s)=>{this.onError("xhr post error",r,s)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(i,n)=>{this.onError("xhr poll error",i,n)}),this.pollXhr=e}}class ee extends T{constructor(e,i){super(),Wt(this,i),this.opts=i,this.method=i.method||"GET",this.uri=e,this.data=i.data!==void 0?i.data:null,this.create()}create(){var e;const i=wn(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");i.xdomain=!!this.opts.xd;const n=this.xhr=new kn(i);try{n.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let r in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(r)&&n.setRequestHeader(r,this.opts.extraHeaders[r])}}catch{}if(this.method==="POST")try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{n.setRequestHeader("Accept","*/*")}catch{}(e=this.opts.cookieJar)===null||e===void 0||e.addCookies(n),"withCredentials"in n&&
22(n.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(n.timeout=this.opts.requestTimeout),n.onreadystatechange=()=>{var r;n.readyState===3&&((r=this.opts.cookieJar)===null||r===void 0||r.parseCookies(n)),n.readyState===4&&(n.status===200||n.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof n.status=="number"?n.status:0)},0))},n.send(this.data)}catch(r){this.setTimeoutFn(()=>{this.onError(r)},0);return}typeof document<"u"&&(this.index=ee.requestsCount++,ee.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=Sr,e)try{this.xhr.abort()}catch{}typeof document<"u"&&delete ee.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}ee.requestsCount=0;ee.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ii);else if(typeof addEventListener=="function"){const t="onpagehide"in q?"pagehide":"unload";addEventListener(t,Ii,!1)}}function Ii(){for(let t in ee.requests)ee.requests.hasOwnProperty(t)&&ee.requests[t].abort()}const ui=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,i)=>i(e,0),tt=q.WebSocket||q.MozWebSocket,xi=!0,Ar="arraybuffer",Ri=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Cr extends li{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),i=this.opts.protocols,n=Ri?{}:wn(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=xi&&!Ri?i?new tt(e,i):new tt(e):new tt(e,i,n)}catch(r){return this.emitReserved("error",r)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let i=0;i<e.length;i++){const n=e[i],r=i===e.length-1;ai(n,this.supportsBinary,s=>{const c={};try{xi&&this.ws.send(s)}catch{}r&&ui(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",i=this.query||{};return this.opts.timestampRequests&&(i[this.opts.timestampParam]=bn()),this.supportsBinary||(i.b64=1),this.createUri(e,i)}check(){return!!tt}}class Tr extends li{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(e=>{const i=lr(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(i).getReader(),r=hr();r.readable.pipeTo(e.writable),this.writer=r.writable.getWriter();const s=()=>{n.read().then(({done:a,value:h})=>{a||(this.onPacket(h),s())}).catch(a=>{})};s();const c={type:"open"};this.query.sid&&(c.data=`{"sid":"${this.query.sid}"}`),this.writer.write(c).then(()=>this.onOpen())})}))}write(e){this.writable=!1;for(let i=0;i<e.length;i++){const n=e[i],r=i===e.length-1;this.writer.write(n).then(()=>{r&&ui(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this.transport)===null||e===void 0||e.close()}}const Or={websocket:Cr,webtransport:Tr,polling:Er},Nr=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Ir=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function jt(t){if(t.length>2e3)throw"URI too long";const e=t,i=t.indexOf("["),n=t.indexOf("]");
22i!=-1&&n!=-1&&(t=t.substring(0,i)+t.substring(i,n).replace(/:/g,";")+t.substring(n,t.length));let r=Nr.exec(t||""),s={},c=14;for(;c--;)s[Ir[c]]=r[c]||"";return i!=-1&&n!=-1&&(s.source=e,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=xr(s,s.path),s.queryKey=Rr(s,s.query),s}function xr(t,e){const i=/\/{2,9}/g,n=e.replace(i,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&n.splice(0,1),e.slice(-1)=="/"&&n.splice(n.length-1,1),n}function Rr(t,e){const i={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,r,s){r&&(i[r]=s)}),i}let En=class ke extends T{constructor(e,i={}){super(),this.binaryType=Ar,this.writeBuffer=[],e&&typeof e=="object"&&(i=e,e=null),e?(e=jt(e),i.hostname=e.host,i.secure=e.protocol==="https"||e.protocol==="wss",i.port=e.port,e.query&&(i.query=e.query)):i.host&&(i.hostname=jt(i.host).host),Wt(this,i),this.secure=i.secure!=null?i.secure:typeof location<"u"&&location.protocol==="https:",i.hostname&&!i.port&&(i.port=this.secure?"443":"80"),this.hostname=i.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=i.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=i.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},i),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=_r(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const i=Object.assign({},this.opts.query);i.EIO=_n,i.transport=e,this.id&&(i.sid=this.id);const n=Object.assign({},this.opts,{query:i,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new Or[e](n)}open(){let e;if(this.opts.rememberUpgrade&&ke.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)e="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else e=this.transports[0];this.readyState="opening";try{e=this.createTransport(e)}catch{this.transports.shift(),this.open();return}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",i=>this.onClose("transport close",i))}probe(e){let i=this.createTransport(e),n=!1;ke.priorWebsocketSuccess=!1;const r=()=>{n||(i.send([{type:"ping",data:"probe"}]),i.once("packet",w=>{if(!n)if(w.type==="pong"&&w.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",i),!i)return;ke.priorWebsocketSuccess=i.name==="websocket",this.transport.pause(()=>{n||this.readyState!=="closed"&&(d(),this.setTransport(i),i.send([{type:"upgrade"}]),this.emitReserved("upgrade",i),i=null,this.upgrading=!1,this.flush())})}else{const m=new Error("probe error");m.transport=i.name,this.emitReserved("upgradeError",m)}}))};function s(){n||(n=!0,d(),i.close(),i=null)}const c=w=>{const m=new Error("probe error: "+w);m.transport=i.name,s(),this.emitReserved("upgradeError",m)};function a(){c("transport closed")}function h(){c("socket closed")}function u(w){i&&w.name!==i.name&&s()}const d=()=>{i.removeListener("open",r),i.removeListener("error",c),i.removeListener("close",a),this.off("close",h),this.off("upgrading",u)};i.once("open",r),i.once("error",c),i.once("close",a),this.once("close",h),this.once("upgrading",u),this.upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{n||i.open()},200):i.open()}onOpen(){if(this.readyState="open",ke.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let e=0;const i=this.upgrades.length;for(;e<i;e++)this.probe(this.upgrades[e])}}onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const i=new Error("server error");i.code=e.data,this.onError(i);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let i=1;for(let n=0;n<this.writeBuffer.length;n++){const r=this.writeBuffer[n].data;if(r&&(i+=yr(r)),n>0&&i>this.maxPayload)return this.writeBuffer.slice(0,n);i+=2}return this.writeBuffer}write(e,i,n){return this.sendPacket("message",e,i,n),this}send(e,i,n){return this.sendPacket("message",e,i,n),this}sendPacket(e,i,n,r){if(typeof i=="function"&&(r=i,i=void 0),typeof n=="function"&&(r=n,n=null),this.readyState==="closing"||this.readyState==="closed")return;n=n||{},n.compress=n.compress!==!1;const s={type:e,data:i,options:n};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},i=()=>{this.off("upgrade",i),this.off("upgradeError",i),e()},n=()=>{this.once("upgrade",i),this.once("upgradeError",i)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}onError(e){ke.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,i){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,i),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const i=[];let n=0;const r=e.length;for(;n<r;n++)~this.transports.indexOf(e[n])&&i.push(e[n]);return i}};En.protocol=_n;function Pr(t,e="",i){let n=t;i=i||typeof location<"u"&&location,t==null&&(t=i.protocol+"//"+i.host),typeof t=="string"&&(t.charAt(0)==="/"&&(t.charAt(1)==="/"?t=i.protocol+t:t=i.host+t),/^(https?|wss?):\/\//.test(t)||(typeof i<"u"?t=i.protocol+"//"+t:t="https://"+t),n=jt(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=n.host.indexOf(":")!==-1?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+e,n.href=n.protocol+"://"+s+(i&&i.port===n.port?"":":"+n.port),n}const Lr=typeof ArrayBuffer=="function",Ur=t=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,An=Object.prototype.toString,Wr=typeof Blob=="function"||typeof Blob<"u"&&An.call(Blob)==="[object BlobConstructor]",Mr=typeof File=="function"||typeof File<"u"&&An.call(File)==="[object FileConstructor]";function di(t){return Lr&&(t instanceof ArrayBuffer||Ur(t))||Wr&&t instanceof Blob||Mr&&t instanceof File}function st(t,e){if(!t||typeof t!="object")return!1;if(Array.isArray(t)){for(let i=0,n=t.length;i<n;i++)if(st(t[i]))return!0;return!1}if(di(t))return!0;
22if(t.toJSON&&typeof t.toJSON=="function"&&arguments.length===1)return st(t.toJSON(),!0);for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&st(t[i]))return!0;return!1}function Br(t){const e=[],i=t.data,n=t;return n.data=Yt(i,e),n.attachments=e.length,{packet:n,buffers:e}}function Yt(t,e){if(!t)return t;if(di(t)){const i={_placeholder:!0,num:e.length};return e.push(t),i}else if(Array.isArray(t)){const i=new Array(t.length);for(let n=0;n<t.length;n++)i[n]=Yt(t[n],e);return i}else if(typeof t=="object"&&!(t instanceof Date)){const i={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=Yt(t[n],e));return i}return t}function Fr(t,e){return t.data=Xt(t.data,e),delete t.attachments,t}function Xt(t,e){if(!t)return t;if(t&&t._placeholder===!0){if(typeof t.num=="number"&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}else if(Array.isArray(t))for(let i=0;i<t.length;i++)t[i]=Xt(t[i],e);else if(typeof t=="object")for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Xt(t[i],e));return t}const $r=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var b;(function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"})(b||(b={}));class Kr{constructor(e){this.replacer=e}encode(e){return(e.type===b.EVENT||e.type===b.ACK)&&st(e)?this.encodeAsBinary({type:e.type===b.EVENT?b.BINARY_EVENT:b.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let i=""+e.type;return(e.type===b.BINARY_EVENT||e.type===b.BINARY_ACK)&&(i+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(i+=e.nsp+","),e.id!=null&&(i+=e.id),e.data!=null&&(i+=JSON.stringify(e.data,this.replacer)),i}encodeAsBinary(e){const i=Br(e),n=this.encodeAsString(i.packet),r=i.buffers;return r.unshift(n),r}}class fi extends T{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let i;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");i=this.decodeString(e);const n=i.type===b.BINARY_EVENT;n||i.type===b.BINARY_ACK?(i.type=n?b.EVENT:b.ACK,this.reconstructor=new Dr(i),i.attachments===0&&super.emitReserved("decoded",i)):super.emitReserved("decoded",i)}else if(di(e)||e.base64)if(this.reconstructor)i=this.reconstructor.takeBinaryData(e),i&&(this.reconstructor=null,super.emitReserved("decoded",i));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let i=0;const n={type:Number(e.charAt(0))};if(b[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===b.BINARY_EVENT||n.type===b.BINARY_ACK){const s=i+1;for(;e.charAt(++i)!=="-"&&i!=e.length;);const c=e.substring(s,i);if(c!=Number(c)||e.charAt(i)!=="-")throw new Error("Illegal attachments");const a=Number(c);if(!qr(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=a}if(e.charAt(i+1)==="/"){const s=i+1;for(;++i&&!(e.charAt(i)===","||i===e.length););n.nsp=e.substring(s,i)}else n.nsp="/";const r=e.charAt(i+1);if(r!==""&&Number(r)==r){const s=i+1;for(;++i;){const c=e.charAt(i);if(c==null||Number(c)!=c){--i;break}if(i===e.length)break}n.id=Number(e.substring(s,i+1))}if(e.charAt(++i)){const s=this.tryParse(e.substr(i));if(fi.isPayloadValid(n.type,s))n.data=s;else throw new Error("invalid payload")}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,i){switch(e){case b.CONNECT:return Pi(i);case b.DISCONNECT:return i===void 0;case b.CONNECT_ERROR:return typeof i=="string"||Pi(i);case b.EVENT:case b.BINARY_EVENT:return Array.isArray(i)&&(typeof i[0]=="number"||typeof i[0]=="string"&&$r.indexOf(i[0])===-1);case b.ACK:case b.BINARY_ACK:return Array.isArray(i)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Dr{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const i=Fr(this.reconPack,this.buffers);return this.finishedReconstruction(),i}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const qr=Number.isInteger||function(t){return typeof t=="number"&&isFinite(t)&&Math.floor(t)===t};function Pi(t){return Object.prototype.toString.call(t)==="[object Object]"}const zr=Object.freeze(Object.defineProperty({__proto__:null,Decoder:fi,Encoder:Kr,get PacketType(){return b}},Symbol.toStringTag,{value:"Module"}));
22function H(t,e,i){return t.on(e,i),function(){t.off(e,i)}}const Vr=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});let Cn=class extends T{constructor(e,i,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=i,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[H(e,"open",this.onopen.bind(this)),H(e,"packet",this.onpacket.bind(this)),H(e,"error",this.onerror.bind(this)),H(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...i){if(Vr.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(i.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(i),this;const n={type:b.EVENT,data:i};if(n.options={},n.options.compress=this.flags.compress!==!1,typeof i[i.length-1]=="function"){const c=this.ids++,a=i.pop();this._registerAckCallback(c,a),n.id=c}const r=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!r||!this.connected)||(this.connected?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),this.flags={},this}_registerAckCallback(e,i){var n;const r=(n=this.flags.timeout)!==null&&n!==void 0?n:this._opts.ackTimeout;if(r===void 0){this.acks[e]=i;return}const s=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let c=0;c<this.sendBuffer.length;c++)this.sendBuffer[c].id===e&&this.sendBuffer.splice(c,1);i.call(this,new Error("operation has timed out"))},r);this.acks[e]=(...c)=>{this.io.clearTimeoutFn(s),i.apply(this,[null,...c])}}emitWithAck(e,...i){const n=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((r,s)=>{i.push((c,a)=>n?c?s(c):r(a):r(c)),this.emit(e,...i)})}_addToQueue(e){let i;typeof e[e.length-1]=="function"&&(i=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((r,...s)=>n!==this._queue[0]?void 0:(r!==null?n.tryCount>this._opts.retries&&(this._queue.shift(),i&&i(r)):(this._queue.shift(),i&&i(null,...s)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||this._queue.length===0)return;const i=this._queue[0];i.pending&&!e||(i.pending=!0,i.tryCount++,this.flags=i.flags,this.emit.apply(this,i.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:b.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,i){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,i)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case b.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case b.EVENT:case b.BINARY_EVENT:this.onevent(e);break;case b.ACK:case b.BINARY_ACK:this.onack(e);break;case b.DISCONNECT:this.ondisconnect();break;case b.CONNECT_ERROR:this.destroy();const n=new Error(e.data.message);n.data=e.data.data,this.emitReserved("connect_error",n);break}}onevent(e){const i=e.data||[];e.id!=null&&i.push(this.ack(e.id)),this.connected?this.emitEvent(i):this.receiveBuffer.push(Object.freeze(i))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const i=this._anyListeners.slice();for(const n of i)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){const i=this;let n=!1;
vendor: 5,752 bytes, line 22
22return function(...r){n||(n=!0,i.packet({type:b.ACK,id:e,data:r}))}}onack(e){const i=this.acks[e.id];typeof i=="function"&&(i.apply(this,e.data),delete this.acks[e.id])}onconnect(e,i){this.id=e,this.recovered=i&&this._pid===i,this._pid=i,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:b.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const i=this._anyListeners;for(let n=0;n<i.length;n++)if(e===i[n])return i.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const i=this._anyOutgoingListeners;for(let n=0;n<i.length;n++)if(e===i[n])return i.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const i=this._anyOutgoingListeners.slice();for(const n of i)n.apply(this,e.data)}}};function Oe(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Oe.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),i=Math.floor(e*this.jitter*t);t=(Math.floor(e*10)&1)==0?t-i:t+i}return Math.min(t,this.max)|0};Oe.prototype.reset=function(){this.attempts=0};Oe.prototype.setMin=function(t){this.ms=t};Oe.prototype.setMax=function(t){this.max=t};Oe.prototype.setJitter=function(t){this.jitter=t};class Qt extends T{constructor(e,i){var n;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(i=e,e=void 0),i=i||{},i.path=i.path||"/socket.io",this.opts=i,Wt(this,i),this.reconnection(i.reconnection!==!1),this.reconnectionAttempts(i.reconnectionAttempts||1/0),this.reconnectionDelay(i.reconnectionDelay||1e3),this.reconnectionDelayMax(i.reconnectionDelayMax||5e3),this.randomizationFactor((n=i.randomizationFactor)!==null&&n!==void 0?n:.5),this.backoff=new Oe({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(i.timeout==null?2e4:i.timeout),this._readyState="closed",this.uri=e;const r=i.parser||zr;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this._autoConnect=i.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var i;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(i=this.backoff)===null||i===void 0||i.setMin(e),this)}randomizationFactor(e){var i;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(i=this.backoff)===null||i===void 0||i.setJitter(e),this)}reconnectionDelayMax(e){var i;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(i=this.backoff)===null||i===void 0||i.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new En(this.uri,this.opts);const i=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=H(i,"open",function(){n.onopen(),e&&e()}),s=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},c=H(i,"error",s);if(this._timeout!==!1){const a=this._timeout,h=this.setTimeoutFn(()=>{r(),s(new Error("timeout")),i.close()},a);this.opts.autoUnref&&h.unref(),this.subs.push(()=>{this.clearTimeoutFn(h)})}return this.subs.push(r),this.subs.push(c),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(H(e,"ping",this.onping.bind(this)),H(e,"data",this.ondata.bind(this)),H(e,"error",this.onerror.bind(this)),H(e,"close",this.onclose.bind(this)),H(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(i){this.onclose("parse error",i)}}ondecoded(e){ui(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,i){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Cn(this,e,i),this.nsps[e]=n),n}_destroy(e){const i=Object.keys(this.nsps);for(const n of i)if(this.nsps[n].active)return;this._close()}_packet(e){const i=this.encoder.encode(e);for(let n=0;n<i.length;n++)this.engine.write(i[n],e.options)}
22cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,i){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,i),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const i=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(r=>{r?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",r)):e.onreconnect()}))},i);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const $e={};function ot(t,e){typeof t=="object"&&(e=t,t=void 0),e=e||{};const i=Pr(t,e.path||"/socket.io"),n=i.source,r=i.id,s=i.path,c=$e[r]&&s in $e[r].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||c;let h;return a?h=new Qt(n,e):($e[r]||($e[r]=new Qt(n,e)),h=$e[r]),i.query&&!e.query&&(e.query=i.queryKey),h.socket(i.path,e)}Object.assign(ot,{Manager:Qt,Socket:Cn,io:ot,connect:ot});var Hr=(t,e)=>t===e?!0:!t||!e||t.length!==e.length?!1:t.every((i,n)=>i===e[n]),Li=30,xt=100,Ui=200,O=class extends Error{constructor(t){super(t),this.name="TagsFilterValidationError"}};function Wi(t,e){if(t.length>e)throw new O(`At most ${e} tags are allowed in a single OR-group`);for(const i of t)if(typeof i!="string")throw new O("Tags must be strings");return t}function Gr(t){const e=Object.keys(t),i=Object.prototype.hasOwnProperty.call(t,"or"),n=Object.prototype.hasOwnProperty.call(t,"and");if(i&&n)throw new O('Tags filter cannot have both "or" and "and"');if(i){if(e.length!==1)throw new O("Invalid tags filter object");const r=t.or;if(!Array.isArray(r))throw new O('"or" must be an array of strings');return r.length===0?[]:[Wi(r,xt)]}if(n){if(e.length!==1)throw new O("Invalid tags filter object");const r=t.and;if(!Array.isArray(r))throw new O('"and" must be an array');if(r.length===0)return[];if(r.length>Li)throw new O(`At most ${Li} tag groups are allowed`);const s=[];let c=0;for(const a of r){if(typeof a!="object"||a===null||Array.isArray(a))throw new O('Eac
22h "and" entry must be an object { or: string[] }');if(Object.keys(a).length!==1||!Object.prototype.hasOwnProperty.call(a,"or"))throw new O('Each "and" entry must be { or: string[] }');const u=a.or;if(!Array.isArray(u))throw new O('"or" must be an array of strings');if(u.length===0)throw new O("Each tag group must be a non-empty array of strings");const d=Wi(u,xt);c+=d.length,s.push(d)}if(c>Ui)throw new O(`At most ${Ui} total tag values are allowed`);return s}throw new O('Tags filter object must have "or" or "and"')}function pi(t){if(t===void 0)return[];if(t===null)throw new O("Tags must be an array or object");if(typeof t=="object"&&!Array.isArray(t))return Gr(t);if(!Array.isArray(t))throw new O("Tags must be an array or object");if(t.length===0)return[];if(Array.isArray(t[0]))throw new O("Nested tag arrays are not supported; use { and: [{ or: string[] }, ...] } for multiple OR-groups");const e=t;if(e.length>xt)throw new O(`At most ${xt} tags are allowed in a single OR-group`);for(const i of e)if(typeof i!="string")throw new O("Tags must be strings");return[e]}function Mi(t){if(t===void 0)return"";const e=pi(t);if(e.length===0)return"";const i=Array.from(new Map(e.map(n=>{const r=Array.from(new Set(n)).sort((s,c)=>s.localeCompare(c));return[JSON.stringify(r),r]})).values()).sort((n,r)=>JSON.stringify(n).localeCompare(JSON.stringify(r)));return JSON.stringify(i)}var yi=(t,e)=>{try{return Mi(t)===Mi(e)}catch{return!1}},Tn=(t,e)=>{const i=Array.isArray(t)?t:t?[t]:[],n=Array.isArray(e)?e:e?[e]:[];return Hr(i,n)},On=(t,e)=>{if(!t&&!e)return!0;if(!t||!e)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}},Zt=(t,e)=>On(t.data,e.data)&&yi(t.tags,e.tags)&&t.read===e.read&&t.archived===e.archived&&t.snoozed===e.snoozed&&t.seen===e.seen&&Tn(t.severity,e.severity)&&t.createdGte===e.createdGte&&t.createdLte===e.createdLte;function Nn(t,e){return!e||Object.keys(e).length===0?!0:t?Object.entries(e).every(([i,n])=>{const r=t[i];if(r===void 0&&n!==void 0)return!1;if(Array.isArray(n))if(Array.isArray(r)){if(n.length!==r.length)return!1;const s=[...n].sort(),c=[...r].sort();return s.every((a,h)=>a===c[h])}else return n.includes(r);else return r===n}):!1}function Jr(t,e){let i;try{i=pi(e)}catch{return!1}return i.length===0?!0:!t||t.length===0?!1:i.every(n=>n.some(r=>t.includes(r)))}function jr(t,e){return!(e.read!==void 0&&t.isRead!==e.read||e.seen!==void 0&&t.isSeen!==e.seen||e.archived!==void 0&&t.isArchived!==e.archived||e.snoozed!==void 0&&t.isSnoozed!==e.snoozed)}function Yr(t,e,i){if(!e&&!i)return!0;const n=new Date(t).getTime();return!(e&&n<e||i&&n>i)}function Xr(t,e){return jr(t,e)&&Jr(t.tags,e.tags)&&Nn(t.data,e.data)&&Yr(t.createdAt,e.createdGte,e.createdLte)}var re,se,pe,ye,qe,Ne=class{constructor(t,e,i,n,r){f(this,re),f(this,se),f(this,pe),f(this,ye),f(this,qe,!1);var s;y(this,re,e),y(this,se,i),y(this,pe,n),y(this,ye,r),this.id=t.id,this.identifier=t.identifier,this.topicKey=t.topicKey,this.preferences=(s=t.preferences)==null?void 0:s.map(c=>new Ce(v({},c),o(this,re),o(this,se),o(this,pe),o(this,ye)))}update(t){return l(this,null,function*(){return In({emitter:o(this,re),apiService:o(this,se),cache:o(this,pe),useCache:o(this,ye),args:k(v({},t),{subscription:this})})})}updatePreference(t){return l(this,null,function*(){return o(this,qe)?{error:new _("Cannot update a deleted subscription",new Error("Subscription is stale"))}:xn({emitter:o(this,re),apiService:o(this,se),cache:o(this,pe),useCache:o(this,ye),args:k(v({},t),{subscriptionId:this.identifier})})})}bulkUpdatePreferences(t){return l(this,null,function*(){return o(this,qe)?{error:new _("Cannot bulk update a deleted subscription",new Error("Subscription is stale"))}:ts({emitter:o(this,re),apiService:o(this,se),cache:o(this,pe),useCache:o(this,ye),args:t.map(e=>k(v({},e),{subscriptionId:this.identifier}))})})}delete(){return l(this,null,function*(){return o(this,qe)?{error:new _("Cannot delete an already deleted subscription",new Error("Subscription is stale"))}:Rn({emitter:o(this,re),apiService:o(this,se),args:{subscription:this}})})}};re=new WeakMap;se=new WeakMap;pe=new WeakMap;ye=new WeakMap;qe=new WeakMap;var Qr=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,options:r,args:s}){try{const{useCache:c,refetch:a}=r;let h=c&&!a?n.getAll(s):void 0;return e.emit("subscriptions.list.pending",{args:s,data:h}
22),(!h||a)&&(h=(yield i.fetchSubscriptions(s.topicKey)).map(d=>new Ne(k(v({},d),{topicKey:s.topicKey}),e,i,n,c)),c&&(n.set(s,h),h=n.getAll(s))),e.emit("subscriptions.list.resolved",{args:s,data:h}),{data:h}}catch(c){return e.emit("subscriptions.list.resolved",{args:s,error:c}),{error:new _("Failed to fetch subscriptions",c)}}}),Zr=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,options:r,args:s}){try{const{useCache:c,refetch:a}=r;let h=c&&!a?n.get(s):void 0;if(e.emit("subscription.get.pending",{args:s,data:h}),!h||a){const u=yield i.getSubscription(s.topicKey,s.identifier,s.workflowIds,s.tags);if(!u)return e.emit("subscription.get.resolved",{args:s,data:null}),{data:null};h=new Ne(k(v({},u),{topicKey:s.topicKey}),e,i,n,c),c&&(n.setOne(s,h),h=n.get(s))}return e.emit("subscription.get.resolved",{args:s,data:h}),{data:h}}catch(c){return e.emit("subscription.get.resolved",{args:s,error:c}),{error:new _("Failed to fetch subscription",c)}}}),es=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,useCache:r,args:s}){var c;try{e.emit("subscription.create.pending",{args:s});const a=yield i.createSubscription({identifier:(c=s.identifier)!=null?c:"",name:s.name,topicKey:s.topicKey,topicName:s.topicName,preferences:s.preferences}),h=new Ne(k(v({},a),{topicKey:s.topicKey}),e,i,n,r);return e.emit("subscription.create.resolved",{args:s,data:h}),{data:h}}catch(a){return e.emit("subscription.create.resolved",{args:s,error:a}),{error:new _("Failed to create subscription",a)}}}),In=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,useCache:r,args:s}){const c="identifier"in s?s.identifier:s.subscription.identifier,a="topicKey"in s?s.topicKey:s.subscription.topicKey;try{e.emit("subscription.update.pending",{args:s});const h=yield i.updateSubscription({topicKey:a,identifier:c,name:s.name,preferences:s.preferences}),u=new Ne(k(v({},h),{topicKey:a}),e,i,n,r);return e.emit("subscription.update.resolved",{args:s,data:u}),{data:u}}catch(h){return e.emit("subscription.update.resolved",{args:s,error:h}),{error:new _("Failed to update subscription",h)}}}),xn=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,useCache:r,args:s}){var c,a;const h="workflowId"in s?s.workflowId:(a=(c=s.preference)==null?void 0:c.workflow)==null?void 0:a.id;try{e.emit("subscription.preference.update.pending",{args:s,data:"preference"in s?new Ce(v(v({},s.preference),typeof s.value=="boolean"?{enabled:s.value}:{condition:s.value}),e,i,n,r):void 0});const u=yield i.updateSubscriptionPreference(v({subscriptionIdentifier:s.subscriptionId,workflowId:h},typeof s.value=="boolean"?{enabled:s.value,email:s.value,sms:s.value,in_app:s.value,chat:s.value,push:s.value}:{condition:s.value})),d=new Ce(v({},u),e,i,n,r);return e.emit("subscription.preference.update.resolved",{args:s,data:d}),{data:d}}catch(u){return e.emit("subscription.preference.update.resolved",{args:s,error:u}),{error:new _("Failed to update subscription",u)}}}),ts=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,useCache:r,args:s}){try{const c=s.map(d=>"preference"in d?new Ce(v(v({},d.preference),typeof d.value=="boolean"?{enabled:d.value}:{condition:d.value}),e,i,n,r):void 0).filter(d=>d!==void 0);e.emit("subscription.preferences.bulk_update.pending",{args:s,data:c});const a=s.map(d=>{var w,m,p,M,B,S;return v({subscriptionIdentifier:d.subscriptionId,workflowId:"workflowId"in d?d.workflowId:(S=(B=(m=(w=d.preference)==null?void 0:w.workflow)==null?void 0:m.id)!=null?B:(M=(p=d.preference)==null?void 0:p.workflow)==null?void 0:M.identifier)!=null?S:""},typeof d.value=="boolean"?{enabled:d.value,email:d.value,sms:d.value,in_app:d.value,chat:d.value,push:d.value}:{condition:d.value})}),u=(yield i.bulkUpdateSubscriptionPreferences(a)).map(d=>new Ce(d,e,i,n,r));return e.emit("subscription.preferences.bulk_update.resolved",{args:s,data:u}),{data:u}}catch(c){return e.emit("subscription.preferences.bulk_update.resolved",{args:s,error:c}),{error:new _("Failed to bulk update subscription preferences",c)}}}),Rn=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){const r="identifier"in n?n.identifier:n.subscription.identifier,s="topicKey"in n?n.topicKey:n.subscription.topicKey;try{return e.emit("subscription.delete.pending",{args:n}),yield i.deleteSubscription({topicKey:s,identifier:r}),e.emit("subscription.delete.resolved",{args:n}),{data:void 0}}catch(c){return e.emit("subscription.delete.resolved",{args:n,error:c}),{error:new _("Failed to delete subscription",c)}}}),ct,at,ht,lt,Ce=class{constructor(t,e,i,n,r){f(this,ct),f(this,at),f(this,ht),f(this,lt);var s;y(this,ct,e),y(this,at,i),y(this,ht,n),y(this,lt,r),this.enabled=t.enabled,this.condition=(s=t.condition)!=null?s:void 0,this.workflow=t.workflow,this.subscriptionId=t.subscriptionId}update(t){return l(this,null,function*(){var e;return xn({emitter:o(this,ct),apiService:o(this,at),cache:o(this,ht),useCache:o(this,lt),args:{subscriptionId:this.subscriptionId,workflowId:(e=this.workflow)==null?void 0:e.id,value:t.value,preference:this}})})}};ct=new WeakMap;at=new WeakMap;ht=new WeakMap;lt=new WeakMap;var ve,ze,ae=class{constructor({inboxServiceInstance:t,eventEmitterInstance:e}){f(this,ve,[]),f(this,ze),this._emitter=e,this._inboxService=t,this._emitter.on("session.initialize.resolved",({error:i,data:n})=>{n?(this.onSessionSuccess(n),o(this,ve).forEach(r=>l(this,[r],function*({fn:s,resolve:c}){c(yield s())})),y(this,ve,[])):i&&(this.onSessionError(i),y(this,ze,i),o(this,ve).forEach(({resolve:r})=>{r({error:new _("Failed to initialize session, please contact the support",i)})}),y(this,ve,[]))})}onSessionSuccess(t){}onSessionError(t){}callWithSession(t){return l(this,null,function*(){return this._inboxService.isSessionInitialized?t():o(this,ze)?Promise.resolve({error:new _("Failed to initialize session, please contact the support",o(this,ze))}):new Promise((e,i)=>{o(this,ve).push({fn:t,resolve:e,reject:i})})})}};ve=new WeakMap;
22ze=new WeakMap;var J,Je=class{constructor(){f(this,J),y(this,J,new Map)}get(t){return o(this,J).get(t)}getValues(){return Array.from(o(this,J).values())}entries(){return Array.from(o(this,J).entries())}keys(){return Array.from(o(this,J).keys())}set(t,e){o(this,J).set(t,e)}remove(t){o(this,J).delete(t)}clear(){o(this,J).clear()}};J=new WeakMap;var ue=t=>`list:${t.topicKey}`,Bi=t=>t.split(":")[1],ne=t=>`item:${t.topicKey}:${t.identifier}`,L,E,ut,C,dt,is=class{constructor({emitterInstance:t,inboxServiceInstance:e,useCache:i}){f(this,L),f(this,E),f(this,ut),f(this,C),f(this,dt),this.handleCreate=n=>{const r=ue({topicKey:n.topicKey}),s=o(this,E).get(r);if(s){const c=[...s,n];o(this,E).set(r,c),o(this,L).emit("subscriptions.list.updated",{data:{topicKey:n.topicKey,subscriptions:c}})}o(this,C).set(ne({topicKey:n.topicKey,identifier:n.identifier}),n)},this.handleUpdate=n=>{const r=ue({topicKey:n.topicKey}),s=o(this,E).get(r);if(s){const c=s.map(a=>a.id===n.id?n:a);o(this,E).set(r,c),o(this,L).emit("subscriptions.list.updated",{data:{topicKey:n.topicKey,subscriptions:c}})}o(this,C).set(ne({topicKey:n.topicKey,identifier:n.identifier}),n)},this.handlePreferenceUpdate=n=>{this.updateSubscriptionPreferences([n])},this.handleBulkPreferenceUpdate=n=>{this.updateSubscriptionPreferences(n)},this.updateSubscriptionPreferences=n=>{var r;const s=new Map;for(const h of n){const u=(r=s.get(h.subscriptionId))!=null?r:[];u.push(h),s.set(h.subscriptionId,u)}const c=o(this,E).keys();for(const h of c){const u=o(this,E).get(h);if(!u)continue;let d=!1;const w=u.map(m=>{const p=s.get(m.identifier);return p?(d=!0,this.createUpdatedSubscription(m,p)):m});d&&(o(this,E).set(h,w),o(this,L).emit("subscriptions.list.updated",{data:{topicKey:Bi(h),subscriptions:w}}))}const a=o(this,C).keys();for(const h of a){const u=o(this,C).get(h);if(!u)continue;const d=s.get(u.identifier);if(d){const w=this.createUpdatedSubscription(u,d);o(this,C).set(h,w),o(this,L).emit("subscription.update.resolved",{args:{subscription:u},data:w})}}},this.createUpdatedSubscription=(n,r)=>{var s;const c=(s=n.preferences)==null?void 0:s.map(a=>{const h=r.find(u=>u.workflow.id===a.workflow.id);return h||a});return new Ne({id:n.id,identifier:n.identifier,topicKey:n.topicKey,preferences:c},o(this,L),o(this,dt),this,o(this,ut))},this.handleDelete=n=>{const r=ue({topicKey:n.topicKey}),s=o(this,E).get(r);if(s){const c=s.filter(a=>a.id!==n.id);o(this,E).set(r,c),o(this,L).emit("subscriptions.list.updated",{data:{topicKey:n.topicKey,subscriptions:c}})}o(this,C).remove(ne({topicKey:n.topicKey,identifier:n.identifier}))},this.handleDeleteByIdentifier=n=>{const r=o(this,E).keys();for(const c of r){const a=o(this,E).get(c);if(a){const h=a.find(u=>u.identifier===n);if(h){const u=a.filter(d=>d.identifier!==n);o(this,E).set(c,u),o(this,L).emit("subscriptions.list.updated",{data:{topicKey:Bi(c),subscriptions:u}}),o(this,C).remove(ne({topicKey:h.topicKey,identifier:h.identifier}));return}}}const s=o(this,C).keys();for(const c of s){const a=o(this,C).get(c);if(a&&a.identifier===n){o(this,C).remove(c);return}}},y(this,L,t),y(this,E,new Je),y(this,C,new Je),y(this,dt,e),y(this,ut,i),o(this,L).on("subscription.create.resolved",({data:n})=>{n&&this.handleCreate(n)}),o(this,L).on("subscription.update.resolved",({data:n})=>{n&&this.handleUpdate(n)}),o(this,L).on("subscription.delete.resolved",({args:n})=>{"subscription"in n?this.handleDelete(n.subscription):"identifier"in n&&this.handleDeleteByIdentifier(n.identifier)}),o(this,L).on("subscription.preference.update.pending",({data:n})=>{n&&this.handlePreferenceUpdate(n)}),o(this,L).on("subscription.preference.update.resolved",({data:n})=>{n&&this.handlePreferenceUpdate(n)}),o(this,L).on("subscription.preferences.bulk_update.resolved",({data:n})=>{n&&n.length>0&&this.handleBulkPreferenceUpdate(n)})}has(t){return o(this,E).get(ue(t))!==void 0}set(t,e){o(this,E).set(ue(t),e);for(const i of e)o(this,C).set(ne({topicKey:t.topicKey,identifier:i.identifier}),i)}setOne(t,e){o(this,C).set(ne(t),e)}getAll(t){return o(this,E).get(ue(t))}get(t){return o(this,C).get(ne(t))}invalidate(t){const e=ue({topicKey:t.topicKey}),i=o(this,E).get(e);if(i)for(const r of i)o(this,C).remove(ne({topicKey:t.topicKey,identifier:r.identifier}));o(this,E).remove(e);const n=o(this,C).keys();for(const r of n)r.startsWith(`item:${t.topicKey}:`)&&o(this,C).remove(r)}clearAll(){o(this,E).clear(),o(this,C).clear()}};L=new WeakMap;E=new WeakMap;ut=new WeakMap;C=new WeakMap;dt=new WeakMap;var me,ft,pt,ns=class extends ae{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:i,subscriber:n,contextKey:r}){super({eventEmitterInstance:i,inboxServiceInstance:e}),f(this,me),f(this,ft),f(this,pt),this.cache=new is({emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,useCache:t}),y(this,me,t),y(this,ft,n),y(this,pt,r)}list(t,e){return l(this,null,function*(){return this.callWithSession(()=>{var i;return Qr({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:k(v({},e),{useCache:(i=e?.useCache)!=null?i:o(this,me)}),args:t})})})}get(t,e){return l(this,null,function*(){return this.callWithSession(()=>{var i,n;return Zr({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,options:k(v({},e),{useCache:(i=e?.useCache)!=null?i:o(this,me)}),args:k(v({},t),{identifier:(n=t.identifier)!=null?n:Dn({topicKey:t.topicKey,subscriberId:o(this,ft).subscriberId,contextKey:o(this,pt)})})})})})}create(t){return l(this,null,function*(){return this.callWithSession(()=>es({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:o(this,me),args:t}))})}update(t){return l(this,null,function*(){return this.callWithSession(()=>In({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:o(this,me),args:t}))})}delete(t){return l(this,null,function*(){return this.callWithSession(()=>Rn({emitter:this._emitter,apiService:this._inboxService,args:t}))})}};me=new WeakMap;ft=new WeakMap;pt=new WeakMap;var rs="v1",ss="@novu/[email protected]",os=class{constructor(t={}){this.DEFAULT_BACKEND_URL=typeof window<"u"&&window.NOVU_LOCAL_BACKEND_URL||"https://api.novu.co";const{apiVersion:e=rs,apiUrl:i=this.DEFAULT_BACKEND_URL,headers:n={}}=t||{};this.apiVersion=e,this.apiUrl=`${i}/${e}`,this.headers=v({"Novu-API-Version":"2024-06-26","Novu-Client-Version":ss,"Content-Type":"application/json"},n)}setAuthorizationToken(t){this.headers.Authorization=`Bearer ${t}`}setKeylessHeader(t){var e;const i=t||typeof window<"u"&&((e=window.localStorage)==null?void 0:e.getItem("novu_keyless_application_identifier"));!i||!i.startsWith("pk_keyless_")||(this.headers["Novu-Application-Identifier"]=i)}setHeaders(t){this.headers=v(v({},this.headers),t)}get(t,e,i=!0){return l(this,null,function*(){return this.doFetch({path:t,searchParams:e,options:{method:"GET"},unwrapEnvelope:i})})}post(t,e,i){return l(this,null,function*(){return this.doFetch({path:t,options:{method:"POST",body:e,headers:i?.headers}})})}patch(t,e){return l(this,null,function*(){return this.doFetch({path:t,options:{method:"PATCH",body:e}})})}delete(t,e){return l(this,null,function*(){return this.doFetch({path:t,options:{method:"DELETE",body:e}})})}doFetch(t){return l(this,arguments,function*({path:e,searchParams:i,options:n,unwrapEnvelope:r=!0}){const s=cs(this.apiUrl,e,i?`?${i.toString()}`:""),c={method:n?.method||"GET",headers:v(v({},this.headers),n?.headers||{}),body:n?.body?JSON.stringify(n.body):void 0},a=yield fetch(s,c);if(!a.ok){const u=yield a.json();throw new Error(`${this.headers["Novu-Client-Version"]} error. Status: ${a.status}, Message: ${u.message}`)}if(a.status===204)return;const h=yield a.json();return r?h.data:h})}};function cs(...t){return t.reduce((e,i)=>(i&&e.push(i.replace(new RegExp("(?<!https?:)\\/+","g"),"/").replace(/^\/+|\/+$/g,"")),e),[]).join("/").replace(/\/\?/,"?")}var R="/inbox",P=`${R}/notifications`,as=`${R}/chat/oauth`,it=`${R}/channel-connections`,nt=`${R}/channel-endpoints`;function Fi(t){const e=new URLSearchParams;if(t.subscriberId&&e.append("subscriberId",t.subscriberId),t.integrationIdentifier&&e.append("integrationIdentifier",t.integrationIdentifier),t.connectionIdentifier&&e.append("connectionIdentifier",t.connectionIdentifier),t.channel&&e.append("channel",t.channel),t.providerId&&e.append("providerId",t.providerId),t.contextKeys!==void 0)if(t.contextKeys.length===0)e.append("contextKeys","");else for(const i of t.contextKeys)e.append("contextKeys",i);return t.limit&&e.append("limit",String(t.limit)),t.after&&e.append("after",t.after),t.before&&e.append("before",t.before),e.size?`?${e.toString()}`:""}function hs(t,e){if(e!==void 0){if(Array.isArray(e)){if(e.length===0)return;for(const i of e)t.append("tags[]",i);return}if("or"in e){if(e.or.length===0)return;for(const i of e.or)t.append("tags[]",i);return}if("and"in e){if(e.and.length===0)return;
22e.and.forEach((i,n)=>{for(const r of i.or)t.append(`tags[${n}][]`,r)})}}}var g,ls=class{constructor(t={}){this.isSessionInitialized=!1,f(this,g),y(this,g,new os(t))}initializeSession(t){return l(this,arguments,function*({applicationIdentifier:e,subscriberHash:i,contextHash:n,subscriber:r,defaultSchedule:s,context:c}){const a=yield o(this,g).post(`${R}/session`,{applicationIdentifier:e,subscriberHash:i,contextHash:n,subscriber:r,defaultSchedule:s,context:c});return o(this,g).setAuthorizationToken(a.token),o(this,g).setKeylessHeader(a.applicationIdentifier),this.isSessionInitialized=!0,a})}fetchNotifications({after:t,archived:e,limit:i=10,offset:n,read:r,tags:s,snoozed:c,seen:a,data:h,severity:u,createdGte:d,createdLte:w}){const m=new URLSearchParams(`limit=${i}`);if(t&&m.append("after",t),n&&m.append("offset",`${n}`),hs(m,s),r!==void 0&&m.append("read",`${r}`),e!==void 0&&m.append("archived",`${e}`),c!==void 0&&m.append("snoozed",`${c}`),a!==void 0&&m.append("seen",`${a}`),h!==void 0&&m.append("data",JSON.stringify(h)),u&&Array.isArray(u))for(const p of u)m.append("severity[]",p);else u&&m.append("severity",u);return d&&m.append("createdGte",`${d}`),w&&m.append("createdLte",`${w}`),o(this,g).get(P,m,!1)}count({filters:t}){return o(this,g).get(`${P}/count`,new URLSearchParams({filters:JSON.stringify(t)}),!1)}read(t){return o(this,g).patch(`${P}/${t}/read`)}unread(t){return o(this,g).patch(`${P}/${t}/unread`)}archive(t){return o(this,g).patch(`${P}/${t}/archive`)}unarchive(t){return o(this,g).patch(`${P}/${t}/unarchive`)}snooze(t,e){return o(this,g).patch(`${P}/${t}/snooze`,{snoozeUntil:e})}unsnooze(t){return o(this,g).patch(`${P}/${t}/unsnooze`)}readAll({tags:t,data:e}){return o(this,g).post(`${P}/read`,{tags:t,data:e?JSON.stringify(e):void 0})}archiveAll({tags:t,data:e}){return o(this,g).post(`${P}/archive`,{tags:t,data:e?JSON.stringify(e):void 0})}archiveAllRead({tags:t,data:e}){return o(this,g).post(`${P}/read-archive`,{tags:t,data:e?JSON.stringify(e):void 0})}delete(t){return o(this,g).delete(`${P}/${t}/delete`)}deleteAll({tags:t,data:e}){return o(this,g).post(`${P}/delete`,{tags:t,data:e?JSON.stringify(e):void 0})}markAsSeen({notificationIds:t,tags:e,data:i}){return o(this,g).post(`${P}/seen`,{notificationIds:t,tags:e,data:i?JSON.stringify(i):void 0})}seen(t){return this.markAsSeen({notificationIds:[t]})}completeAction({actionType:t,notificationId:e}){return o(this,g).patch(`${P}/${e}/complete`,{actionType:t})}revertAction({actionType:t,notificationId:e}){return o(this,g).patch(`${P}/${e}/revert`,{actionType:t})}fetchPreferences({tags:t,severity:e,criticality:i}){const n=new URLSearchParams;if(t)for(const s of t)n.append("tags[]",s);if(e&&Array.isArray(e))for(const s of e)n.append("severity[]",s);else e&&n.append("severity",e);i&&n.append("criticality",i);const r=n.size?`?${n.toString()}`:"";return o(this,g).get(`${R}/preferences${r}`)}bulkUpdatePreferences(t){return o(this,g).patch(`${R}/preferences/bulk`,{preferences:t})}updateGlobalPreferences(t){return o(this,g).patch(`${R}/preferences`,t)}updateWorkflowPreferences({workflowId:t,channels:e}){return o(this,g).patch(`${R}/preferences/${t}`,e)}fetchGlobalPreferences(){return o(this,g).get(`${R}/preferences/global`)}triggerHelloWorldEvent(){const t={name:"hello-world",to:{subscriberId:"keyless-subscriber-id"},payload:{subject:"Novu Keyless Environment",body:"You're using a keyless demo environment. For full access to Novu features and cloud integration, obtain your API key.",primaryActionText:"Obtain API Key",primaryActionUrl:"https://go.novu.co/keyless",secondaryActionText:"Explore Documentation",secondaryActionUrl:"https://go.novu.co/keyless-docs"}};return o(this,g).post("/inbox/events",t)}fetchSubscriptions(t){return o(this,g).get(`${R}/topics/${t}/subscriptions`)}getSubscription(t,e,i,n){const r=new URLSearchParams;if(i?.length)for(const c of i)r.append("workflowIds",c);if(n?.length)for(const c of n)r.append("tags",c);const s=r.size?`?${r.toString()}`:"";return o(this,g).get(`${R}/topics/${t}/subscriptions/${e}${s}`)}createSubscription({identifier:t,name:e,topicKey:i,topicName:n,preferences:r}){return o(this,g).post(`${R}/topics/${i}/subscriptions`,v(v({identifier:t,name:e},n&&{topic:{name:n}}),r!==void 0&&{preferences:r}))}updateSubscription({topicKey:t,identifier:e,name:i,preferences:n}){return o(this,g).patch(`${R}/topics/${t}/subscriptions/${e}`,v({name:i},n!==void 0&&{preferences:n}))}updateSubscriptionPreference({subscriptionIdentifier:t,workflowId:e,enabled:i,condition:n,email:r,sms:s,in_app:c,chat:a,push:h}){return o(this,g).patch(`${R}/subscriptions/${t}/preferences/${e}`,{enabled:i,condition:n,email:r,sms:s,in_app:c,chat:a,push:h})}bulkUpdateSubscriptionPreferences(t){return o(this,g).patch(`${R}/preferences/bulk`,{preferences:t})}deleteSubscription({topicKey:t,identifier:e}){return o(this,g).delete(`${R}/topics/${t}/subscriptions/${e}`)}generateChatOAuthUrl({integrationIdentifier:t,connectionIdentifier:e,subscriberId:i,context:n,scope:r,userScope:s,mode:c,connectionMode:a}){return o(this,g).post(as,{integrationIdentifier:t,connectionIdentifier:e,subscriberId:i,context:n,scope:r,userScope:s,mode:c,connectionMode:a})}listChannelConnections(t={}){const e=Fi(t);return o(this,g).get(`${it}${e}`,void 0,!1)}getChannelConnection(t){return o(this,g).get(`${it}/${t}`)}createChannelConnection({identifier:t,integrationIdentifier:e,subscriberId:i,context:n,workspace:r,auth:s}){return o(this,g).post(it,{identifier:t,integrationIdentifier:e,subscriberId:i,context:n,workspace:r,auth:s})}deleteChannelConnection(t){return o(this,g).delete(`${it}/${t}`)}listChannelEndpoints(t={}){const e=Fi(t);return o(this,g).get(`${nt}${e}`,void 0,!1)}getChannelEndpoint(t){return o(this,g).get(`${nt}/${t}`)}createChannelEndpoint({identifier:t,integrationIdentifier:e,connectionIdentifier:i,subscriberId:n,context:r,type:s,endpoint:c}){return o(this,g).post(nt,{identifier:t,integrationIdentifier:e,connectionIdentifier:i,subscriberId:n,context:r,type:s,endpoint:c})}deleteChannelEndpoint(t){return o(this,g).delete(`${nt}/${t}`)}};g=new WeakMap;var us=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{e.emit("channel-connection.oauth-url.pending",{args:n});const r=yield i.generateChatOAuthUrl(n);return e.emit("channel-connection.oauth-url.resolved",{args:n,data:r}),{data:r}}catch(r){return e.emit("channel-connection.oauth-url.resolved",{args:n,error:r}),{error:new _("Failed to generate chat OAuth URL",r)}}}),ds=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{e.emit("channel-connections.list.pending",{args:n});const s=(yield i.listChannelConnections(n)).data;return e.emit("channel-connections.list.resolved",{args:n,data:s}),{data:s}}catch(r){return e.emit("channel-connections.list.resolved",{args:n,error:r}),{error:new _("Failed to list channel connections",r)}}}),fs=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{e.emit("channel-connection.get.pending",{args:n});const r=yield i.getChannelConnection(n.identifier);return e.emit("channel-connection.get.resolved",{args:n,data:r}),{data:r}}catch(r){return e.emit("channel-connection.get.resolved",{args:n,error:r}),{error:new _("Failed to get channel connection",r)}}}),ps=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{return e.emit("channel-connection.delete.pending",{args:n}),yield i.deleteChannelConnection(n.identifier),e.emit("channel-connection.delete.resolved",{args:n}),{data:void 0}}catch(r){return e.emit("channel-connection.delete.resolved",{args:n,error:r}),{error:new _("Failed to delete channel connection",r)}}}),ys=class extends ae{constructor({inboxServiceInstance:t,eventEmitterInstance:e}){super({inboxServiceInstance:t,eventEmitterInstance:e})}generateOAuthUrl(t){return l(this,null,function*(){return this.callWithSession(()=>us({emitter:this._emitter,apiService:this._inboxService,args:t}))})}list(){return l(this,arguments,function*(t={}){return this.callWithSession(()=>ds({emitter:this._emitter,apiService:this._inboxService,args:t}))})}get(t){return l(this,null,function*(){return this.callWithSession(()=>fs({emitter:this._emitter,apiService:this._inboxService,args:t}))})}delete(t){return l(this,null,function*(){return this.callWithSession(()=>ps({emitter:this._emitter,apiService:this._inboxService,args:t}))})}},vs=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{e.emit("channel-endpoints.list.pending",{args:n});const s=(yield i.listChannelEndpoints(n)).data;return e.emit("channel-endpoints.list.resolved",{args:n,data:s}),{data:s}}catch(r){return e.emit("channel-endpoints.list.resolved",{args:n,error:r}),{error:new _("Failed to list channel endpoints",r)}}}),ms=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{e.emit("channel-endpoint.get.pending",{args:n});const r=yield i.getChannelEndpoint(n.identifier);return e.emit("channel-endpoint.get.resolved",{args:n,data:r}),{data:r}}catch(r){return e.emit("channel-endpoint.get.resolved",{args:n,error:r}),{error:new _("Failed to get channel endpoint",r)}}}),_s=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{e.emit("channel-endpoint.create.pending",{args:n});const r=yield i.createChannelEndpoint(n);return e.emit("channel-endpoint.create.resolved",{args:n,data:r}),{data:r}}catch(r){return e.emit("channel-endpoint.create.resolved",{args:n,error:r}),{error:new _("Failed to create channel endpoint",r)}}}),ws=t=>l(null,[t],function*({emitter:e,apiService:i,args:n}){try{return e.emit("channel-endpoint.delete.pending",{args:n}),yield i.deleteChannelEndpoint(n.identifier),e.emit("channel-endpoint.delete.resolved",{args:n}),{data:void 0}}catch(r){return e.emit("channel-endpoint.delete.resolved",{args:n,error:r}),{error:new _("Failed to delete channel endpoint",r)}}}),gs=class extends ae{constructor({inboxServiceInstance:t,eventEmitterInstance:e}){super({inboxServiceInstance:t,eventEmitterInstance:e})}list(){return l(this,arguments,function*(t={}){return this.callWithSession(()=>vs({emitter:this._emitter,apiService:this._inboxService,args:t}))})}get(t){return l(this,null,function*(){return this.callWithSession(()=>ms({emitter:this._emitter,apiService:this._inboxService,args:t}))})}create(t){return l(this,null,function*(){return this.callWithSession(()=>_s({emitter:this._emitter,apiService:this._inboxService,args:t}))})}delete(t){return l(this,null,function*(){return this.callWithSession(()=>ws({emitter:this._emitter,apiService:this._inboxService,args:t}))})}},Ee,bs=class{constructor(){f(this,Ee),y(this,Ee,Jn())}on(t,e){return o(this,Ee).on(t,e),()=>{this.off(t,e)}}off(t,e){o(this,Ee).off(t,e)}emit(t,e){o(this,Ee).emit(t,e)}};Ee=new WeakMap;var Pn=({tags:t,data:e,read:i,archived:n,snoozed:r,seen:s,severity:c,limit:a,offset:h,after:u,createdGte:d,createdLte:w})=>Object.entries({tags:t,data:e,read:i,archived:n,snoozed:r,seen:s,severity:c,limit:a,offset:h,after:u,createdGte:d,createdLte:w}).filter(([m,p])=>p!=null&&!(Array.isArray(p)&&p.length===0)).reduce((m,[p,M])=>(m[p]=M,m),{}),Ke=({tags:t,data:e,read:i,archived:n,snoozed:r,seen:s,severity:c,limit:a,offset:h,after:u,createdGte:d,createdLte:w})=>JSON.stringify(Pn({tags:t,data:e,read:i,archived:n,snoozed:r,seen:s,severity:c,limit:a,offset:h,after:u,createdGte:d,createdLte:w})),Ss=({tags:t,data:e,read:i,archived:n,snoozed:r,seen:s,severity:c,createdGte:a,createdLte:h})=>JSON.stringify(Pn({tags:t,data:e,read:i,archived:n,snoozed:r,seen:s,severity:c,createdGte:a,createdLte:h})),de=t=>JSON.parse(t),ks=["notification.read.pending","notification.read.resolved","notification.unread.pending","notification.unread.resolved","notification.complete_action.pending","notification.complete_action.resolved","notification.revert_action.pending","notification.revert_action.resolved","notifications.read_all.pending","notifications.read_all.resolved"],Es=["notification.archive.pending","notification.unarchive.pending","notification.snooze.pending","notification.unsnooze.pending","notification.delete.pending","notifications.archive_all.pending","notifications.archive_all_read.pending","notifications.delete_all.pending"],oe,yt,A,As=class{constructor({emitter:t,inboxService:e}){f(this,oe),f(this,yt),f(this,A),this.updateNotification=(i,n)=>{const r=o(this,A).get(i);if(!r)return!1;const s=r.notifications.findIndex(a=>a.id===n.id);if(s===-1)return!1;const c=[...r.notifications];return c[s]=n,o(this,A).set(i,k(v({},r),{notifications:c})),!0},this.removeNotification=(i,n)=>{const r=o(this,A).get(i);if(!r)return!1;const s=r.notifications.findIndex(a=>a.id===n.id);if(s===-1)return!1;const c=[...r.notifications];return c.splice(s,1),o(this,A).set(i,k(v({},r),{notifications:c})),!0},this.handleNotificationEvent=({remove:i}={remove:!1})=>n=>{const{data:r,args:s}=n;let c=[];if(r!=null)Array.isArray(r)&&r.every(h=>typeof h=="object"&&"id"in h)?c=r:typeof r=="object"&&"id"in r&&(c=[r]);
22else if(i&&s){if("notification"in s&&s.notification)c=[s.notification];else if("notificationId"in s&&s.notificationId){const h=[];o(this,A).keys().forEach(u=>{const d=o(this,A).get(u);if(d){const w=d.notifications.find(m=>m.id===s.notificationId);w&&h.push(w)}}),c=h}}if(c.length===0)return;const a=new Set;o(this,A).keys().forEach(h=>{c.forEach(u=>{let d=!1;i?d=this.removeNotification(h,u):d=this.updateNotification(h,u),d&&a.add(Ss(de(h)))})}),a.forEach(h=>{const u=this.getAggregated(de(h));o(this,oe).emit("notifications.list.updated",{data:u})})},y(this,oe,t),y(this,yt,e),ks.forEach(i=>{o(this,oe).on(i,this.handleNotificationEvent())}),Es.forEach(i=>{o(this,oe).on(i,this.handleNotificationEvent({remove:!0}))}),y(this,A,new Je)}getAggregated(t){return o(this,A).keys().filter(i=>{const n=de(i);return Zt(n,t)}).map(i=>o(this,A).get(i)).reduce((i,n)=>n?{hasMore:n.hasMore,filter:n.filter,notifications:[...i.notifications,...n.notifications]}:i,{hasMore:!1,filter:{},notifications:[]})}get(t){return o(this,A).get(Ke(t))}has(t){return o(this,A).get(Ke(t))!==void 0}set(t,e){o(this,A).set(Ke(t),e)}unshift(t,e){const i=Ke(t),n=o(this,A).get(i)||{hasMore:!1,filter:de(i),notifications:[]},r=Gn({notification:v({},e),emitter:o(this,oe),inboxService:o(this,yt)});this.update(t,k(v({},n),{notifications:[r,...n.notifications]}))}update(t,e){this.set(t,e);const i=this.getAggregated(de(Ke(t)));
22o(this,oe).emit("notifications.list.updated",{data:i})}getAll(t){if(this.has(t))return this.getAggregated({tags:t.tags,data:t.data,read:t.read,snoozed:t.snoozed,archived:t.archived,seen:t.seen,severity:t.severity,createdGte:t.createdGte,createdLte:t.createdLte})}getUniqueNotifications({tags:t,read:e,data:i}){const n=o(this,A).keys(),r=new Map;return n.forEach(s=>{const c=de(s);if(yi(t,c.tags)&&On(i,c.data)){const a=o(this,A).get(s);if(!a)return;a.notifications.filter(h=>typeof e>"u"||e===h.isRead).forEach(h=>{r.set(h.id,h)})}}),Array.from(r.values())}clear(t){o(this,A).keys().forEach(i=>{Zt(de(i),t)&&o(this,A).remove(i)})}clearAll(){o(this,A).clear()}};oe=new WeakMap;yt=new WeakMap;A=new WeakMap;var vt,Cs=class extends ae{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:i}){super({eventEmitterInstance:i,inboxServiceInstance:e}),f(this,vt),this.cache=new As({emitter:i,inboxService:e}),y(this,vt,t)}list(){return l(this,arguments,function*(t={}){var e=t,{limit:i=10}=e,n=ji(e,["limit"]);return this.callWithSession(()=>l(this,null,function*(){const r=v({limit:i},n);try{const s="useCache"in r?r.useCache:o(this,vt);let c=s?this.cache.getAll(r):void 0;if(this._emitter.emit("notifications.list.pending",{args:r,data:c}),!c){const a=yield this._inboxService.fetchNotifications(v({limit:i},n));c={hasMore:a.hasMore,filter:a.filter,notifications:a.data.map(h=>new N(h,this._emitter,this._inboxService))},s&&(this.cache.set(r,c),c=this.cache.getAll(r))}return this._emitter.emit("notifications.list.resolved",{args:r,data:c}),{data:c}}catch(s){return this._emitter.emit("notifications.list.resolved",{args:r,error:s}),{error:new _("Failed to fetch notifications",s)}}}))})}count(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){const e=t&&"filters"in t?t.filters:[v({},t)];try{this._emitter.emit("notifications.count.pending",{args:t});const i=yield this._inboxService.count({filters:e}),n=t&&"filters"in t?{counts:i.data}:i.data[0];return this._emitter.emit("notifications.count.resolved",{args:t,data:n}),{data:n}}catch(i){return this._emitter.emit("notifications.count.resolved",{args:t,error:i}),{error:new _("Failed to count notifications",i)}}}))})}read(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return nn({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unread(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return rn({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}seen(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return sn({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}archive(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return on({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unarchive(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return cn({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}delete(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return ln({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}snooze(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return an({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}unsnooze(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return hn({emitter:this._emitter,apiService:this._inboxService,args:t})}))})}completePrimary(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Nt({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"primary"})}))})}completeSecondary(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return Nt({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"secondary"})}))})}revertPrimary(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return It({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"primary"})}))})}revertSecondary(t){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){return It({emitter:this._emitter,apiService:this._inboxService,args:t,actionType:"secondary"})}))})}readAll(){return l(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>l(this,null,function*(){return qn({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}
22seenAll(){return l(this,arguments,function*(t={}){return this.callWithSession(()=>l(this,null,function*(){return"notificationIds"in t?Si({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,notificationIds:t.notificationIds}):Si({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:"tags"in t?t.tags:void 0,data:"data"in t?t.data:void 0})}))})}archiveAll(){return l(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>l(this,null,function*(){return zn({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}archiveAllRead(){return l(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>l(this,null,function*(){return Vn({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}deleteAll(){return l(this,arguments,function*({tags:t,data:e}={}){return this.callWithSession(()=>l(this,null,function*(){return Hn({emitter:this._emitter,inboxService:this._inboxService,notificationsCache:this.cache,tags:t,data:e})}))})}clearCache({filter:t}={}){if(t){this.cache.clear(t??{});return}this.cache.clearAll()}triggerHelloWorldEvent(){return l(this,null,function*(){return this._inboxService.triggerHelloWorldEvent()})}};vt=new WeakMap;var mt,_t,wt,gt,Rt=class{constructor(t,{emitterInstance:e,inboxServiceInstance:i,cache:n,useCache:r}){f(this,mt),f(this,_t),f(this,wt),f(this,gt),y(this,mt,e),y(this,_t,i),y(this,wt,n),y(this,gt,r),this.isEnabled=t.isEnabled,this.weeklySchedule=t.weeklySchedule}update(t){return l(this,null,function*(){var e;const i=!!t.weeklySchedule||!!this.weeklySchedule;return Un({emitter:o(this,mt),apiService:o(this,_t),cache:o(this,wt),useCache:o(this,gt),args:v({isEnabled:(e=t.isEnabled)!=null?e:this.isEnabled},i&&{weeklySchedule:v(v({},this.weeklySchedule),t.weeklySchedule)})})})}};mt=new WeakMap;_t=new WeakMap;wt=new WeakMap;gt=new WeakMap;var bt,St,kt,Et,At,Te=class{constructor(t,{emitterInstance:e,inboxServiceInstance:i,cache:n,scheduleCache:r,useCache:s}){f(this,bt),f(this,St),f(this,kt),f(this,Et),f(this,At),y(this,bt,e),y(this,St,i),y(this,kt,n),y(this,Et,r),y(this,At,s),this.level=t.level,this.enabled=t.enabled,this.channels=t.channels,this.workflow=t.workflow,this.schedule=new Rt(v({},t.schedule),{emitterInstance:e,inboxServiceInstance:i,cache:r,useCache:s})}update({channels:t,channelPreferences:e}){var i;return Ln({emitter:o(this,bt),apiService:o(this,St),cache:o(this,kt),scheduleCache:o(this,Et),useCache:o(this,At),args:{workflowId:(i=this.workflow)==null?void 0:i.id,channels:t||e,preference:this}})}};bt=new WeakMap;St=new WeakMap;kt=new WeakMap;Et=new WeakMap;At=new WeakMap;var Ln=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,scheduleCache:r,useCache:s,args:c}){var a;const{channels:h}=c,u="workflowId"in c?c.workflowId:(a=c.preference.workflow)==null?void 0:a.id;try{e.emit("preference.update.pending",{args:c,data:"preference"in c?new Te(k(v({},c.preference),{channels:v(v({},c.preference.channels),h)}),{emitterInstance:e,inboxServiceInstance:i,cache:n,scheduleCache:r,useCache:s}):void 0});let d;u?d=yield i.updateWorkflowPreferences({workflowId:u,channels:h}):(Os({emitter:e,apiService:i,cache:n,scheduleCache:r,useCache:s,args:c}),d=yield i.updateGlobalPreferences(h));const w=new Te(d,{emitterInstance:e,inboxServiceInstance:i,cache:n,scheduleCache:r,useCache:s});return e.emit("preference.update.resolved",{args:c,data:w}),{data:w}}catch(d){return e.emit("preference.update.resolved",{args:c,error:d}),{error:new _("Failed to update preference",d)}}}),Ts=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,scheduleCache:r,useCache:s,args:c}){if(c.find(h=>"preference"in h&&h.preference.level==="global"))return{error:new _("Global preference is not supported in bulk update","")};try{const h=c.map(m=>"preference"in m?new Te(k(v({},m.preference),{channels:v(v({},m.preference.channels),m.channels)}),{emitterInstance:e,inboxServiceInstance:i,cache:n,scheduleCache:r,useCache:s}):void 0).filter(m=>m!==void 0);e.emit("preferences.bulk_update.pending",{args:c,data:h});const u=c.map(m=>{var p,M,B,S;return v({workflowId:"workflowId"in m?m.workflowId:(S=(B=(p=m.preference.workflow)==null?void 0:p.id)!=null?B:(M=m.preference.workflow)==null?void 0:M.identifier)!=null?S:""},m.channels)}),w=(yield i.bulkUpdatePreferences(u)).map(m=>new Te(m,{emitterInstance:e,inboxServiceInstance:i,cache:n,scheduleCache:r,useCache:s}));return e.emit("preferences.bulk_update.resolved",{args:c,data:w}),{data:w}}catch(h){return e.emit("preferences.bulk_update.resolved",{args:c,error:h}),{error:new _("Failed to bulk update preferences",h)}}}),Os=({emitter:t,apiService:e,cache:i,scheduleCache:n,useCache:r,args:s})=>{const c=r?i?.getAll({}):void 0;c?.forEach(a=>{var h,u;if(a.level==="template"){const d=k(v({},a),{channels:Object.entries(a.channels).reduce((m,[p,M])=>{var B;const S=p;return m[S]=(B=s.channels[S])!=null?B:M,m},{})}),w="preference"in s?new Te(d,{emitterInstance:t,inboxServiceInstance:e,cache:i,scheduleCache:n,useCache:r}):void 0;w&&t.emit("preference.update.pending",{args:{workflowId:(u=(h=a.workflow)==null?void 0:h.id)!=null?u:"",channels:w.channels},data:w})}})},Un=t=>l(null,[t],function*({emitter:e,apiService:i,cache:n,useCache:r,args:s}){var c,a;try{const{isEnabled:h,weeklySchedule:u}=s,d=new Rt({isEnabled:h,weeklySchedule:u},{emitterInstance:e,inboxServiceInstance:i,cache:n,useCache:r});e.emit("preference.schedule.update.pending",{args:s,data:d});const w=yield i.updateGlobalPreferences({schedule:{isEnabled:h,weeklySchedule:u}}),m=new Rt({isEnabled:(c=w.schedule)==null?void 0:c.isEnabled,weeklySchedule:(a=w.schedule)==null?void 0:a.weeklySchedule},{emitterInstance:e,inboxServiceInstance:i,cache:n,useCache:r});return e.emit("preference.schedule.update.resolved",{args:s,data:m}),{data:m}}catch(h){return e.emit("preference.schedule.update.resolved",{args:s,error:h}),{error:new _("Failed to update preference",h)}}}),_e,Ns=class extends ae{constructor({cache:t,useCache:e,inboxServiceInstance:i,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:i}),f(this,_e),this.cache=t,y(this,_e,e)}get(){return l(this,null,function*(){return this.callWithSession(()=>l(this,null,function*(){var t,e;try{let i=o(this,_e)?this.cache.getAll():void 0;if(this._emitter.emit("preference.schedule.get.pending",{args:void 0,data:i}),!i){const n=yield this._inboxService.fetchGlobalPreferences();i=new Rt({isEnabled:(t=n?.schedule)==null?void 0:t.isEnabled,weeklySchedule:(e=n?.schedule)==null?void 0:e.weeklySchedule},{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,useCache:o(this,_e)}),o(this,_e)&&(this.cache.set(i),i=this.cache.getAll())}return this._emitter.emit("preference.schedule.get.resolved",{args:void 0,data:i}),{data:i}}catch(i){throw this._emitter.emit("preference.schedule.get.resolved",{args:void 0,error:i}),i}}))})}update(t){return l(this,null,function*(){return this.callWithSession(()=>Un({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,useCache:o(this,_e),args:t}))})}};_e=new WeakMap;var Is=["preference.update.pending","preference.update.resolved","preferences.bulk_update.pending","preferences.bulk_update.resolved"],xs=["preference.schedule.update.pending","preference.schedule.update.resolved"],Rs=({tags:t,severity:e})=>Object.entries({tags:t,severity:e}).reduce((i,[n,r])=>(r==null||Array.isArray(r)&&r.length===0||(i[n]=r),i),{}),Vt=({tags:t,severity:e})=>JSON.stringify(Rs({tags:t,severity:e})),we,x,Ps=class{constructor({emitterInstance:t}){f(this,we),f(this,x),this.updatePreference=(e,i)=>{const n=o(this,x).get(e);if(!n)return!1;const r=n.findIndex(c=>{var a,h;return((a=c.workflow)==null?void 0:a.id)===((h=i.workflow)==null?void 0:h.id)||c.level===i.level&&i.level==="global"});if(r===-1)return!1;const s=[...n];return s[r]=i,o(this,x).set(e,s),!0},this.updatePreferenceSchedule=(e,i)=>{const n=o(this,x).get(e);if(!n)return!1;const r=n.findIndex(c=>c.level==="global");if(r===-1)return!1;const s=[...n];return s[r].schedule=i,o(this,x).set(e,s),!0},this.handleScheduleEvent=({data:e})=>{var i;if(!e)return;const n=o(this,x).keys(),r=new Set;for(const s of n){const c=this.updatePreferenceSchedule(s,e),a=o(this,x).get(s);!c||!a||r.add(s)}for(const s of r)o(this,we).emit("preferences.list.updated",{data:(i=o(this,x).get(s))!=null?i:[]})},this.handlePreferenceEvent=({data:e})=>
22{if(!e)return;const i=Array.isArray(e)?e:[e],n=new Set;o(this,x).keys().forEach(r=>{i.forEach(s=>{const c=this.updatePreference(r,s),a=o(this,x).get(r);!c||!a||n.add(r)})}),n.forEach(r=>{var s;o(this,we).emit("preferences.list.updated",{data:(s=o(this,x).get(r))!=null?s:[]})})},y(this,we,t);for(const e of Is)o(this,we).on(e,this.handlePreferenceEvent);for(const e of xs)o(this,we).on(e,this.handleScheduleEvent);y(this,x,new Je)}has(t){return o(this,x).get(Vt(t))!==void 0}set(t,e){o(this,x).set(Vt(t),e)}getAll(t){if(this.has(t))return o(this,x).get(Vt(t))}clearAll(){o(this,x).clear()}};we=new WeakMap;x=new WeakMap;var Ls=["preference.schedule.update.pending","preference.schedule.update.resolved"],Ht=()=>"schedule",Ve,$,Us=class{constructor({emitterInstance:t}){f(this,Ve),f(this,$),this.updateScheduleInCache=(e,i)=>o(this,$).get(e)?(o(this,$).set(e,i),!0):!1,this.handleScheduleEvent=({data:e})=>{if(!e)return;const i=new Set,n=o(this,$).keys();for(const r of n){const s=this.updateScheduleInCache(r,e),c=o(this,$).get(r);!s||!c||i.add(r)}for(const r of i)o(this,Ve).emit("preference.schedule.get.updated",{data:o(this,$).get(r)})},y(this,Ve,t);for(const e of Ls)o(this,Ve).on(e,this.handleScheduleEvent);y(this,$,new Je)}has(){return o(this,$).get(Ht())!==void 0}set(t){o(this,$).set(Ht(),t)}getAll(){if(this.has())return o(this,$).get(Ht())}clearAll(){o(this,$).clear()}};Ve=new WeakMap;$=new WeakMap;var ce,Ws=class extends ae{constructor({useCache:t,inboxServiceInstance:e,eventEmitterInstance:i}){super({eventEmitterInstance:i,inboxServiceInstance:e}),f(this,ce),this.cache=new Ps({emitterInstance:this._emitter}),this.scheduleCache=new Us({emitterInstance:this._emitter}),y(this,ce,t),this.schedule=new Ns({cache:this.scheduleCache,useCache:t,inboxServiceInstance:e,eventEmitterInstance:i})}list(){return l(this,arguments,function*(t={}){return this.callWithSession(()=>l(this,null,function*(){var e;try{let i=o(this,ce)?this.cache.getAll(t):void 0;return this._emitter.emit("preferences.list.pending",{args:t,data:i}),i||(i=(yield this._inboxService.fetchPreferences({tags:t.tags,severity:t.severity,criticality:(e=t.criticality)!=null?e:"nonCritical"})).map(r=>new Te(r,{emitterInstance:this._emitter,inboxServiceInstance:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:o(this,ce)})),o(this,ce)&&(this.cache.set(t,i),i=this.cache.getAll(t))),this._emitter.emit("preferences.list.resolved",{args:t,data:i}),{data:i}}catch(i){throw this._emitter.emit("preferences.list.resolved",{args:t,error:i}),i}}))})}update(t){return l(this,null,function*(){return this.callWithSession(()=>Ln({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:o(this,ce),args:t}))})}bulkUpdate(t){return l(this,null,function*(){return this.callWithSession(()=>Ts({emitter:this._emitter,apiService:this._inboxService,cache:this.cache,scheduleCache:this.scheduleCache,useCache:o(this,ce),args:t}))})}};ce=new WeakMap;function Ms(){return typeof window<"u"}var Ae,Ct,U,Bs=class{constructor(t,e,i){f(this,Ae),f(this,Ct),f(this,U),y(this,Ae,i),y(this,Ct,e),y(this,U,t)}get applicationIdentifier(){return o(this,U).applicationIdentifier}get subscriberId(){var t;return(t=o(this,U).subscriber)==null?void 0:t.subscriberId}get context(){return o(this,U).context}get subscriberHash(){return o(this,U).subscriberHash}get contextHash(){return o(this,U).contextHash}get subscriber(){return o(this,U).subscriber}handleApplicationIdentifier(t,e){if(typeof window>"u"||!window.localStorage)return null;const i="novu_keyless_application_identifier";switch(t){case"get":return window.localStorage.getItem(i);case"store":return e&&window.localStorage.setItem(i,e),null;case"delete":return window.localStorage.removeItem(i),null;default:return null}}initialize(t){return l(this,null,function*(){var e,i,n,r,s,c;const a=((e=o(this,U).subscriber)==null?void 0:e.subscriberId)===((i=t?.subscriber)==null?void 0:i.subscriberId),h=JSON.stringify(o(this,U).context)===JSON.stringify(t?.context);if(!(a&&h))try{t&&y(this,U,t);const{subscriber:u,subscriberHash:d,contextHash:w,applicationIdentifier:m,defaultSchedule:p,context:M}=o(this,U);let B;Ms()&&(B=Intl.DateTimeFormat().resolvedOptions().timeZone);let S=m;if(S)this.handleApplicationIdentifier("delete");else{const Se=this.handleApplicationIdentifier("get");Se&&(S=Se)}o(this,Ae).emit("session.initialize.pending",{args:o(this,U)});const G=yield o(this,Ct).initializeSession({applicationIdentifier:S,subscriberHash:d,contextHash:w,subscriber:k(v({},u),{subscriberId:(n=u?.subscriberId)!=null?n:"",timezone:(r=u?.timezone)!=null?r:B}),defaultSchedule:p,context:M});(s=G?.applicationIdentifier)!=null&&s.startsWith("pk_keyless_")&&this.handleApplicationIdentifier("store",G.applicationIdentifier),(c=G?.applicationIdentifier)!=null&&c.startsWith("pk_keyless_")||this.handleApplicationIdentifier("delete"),o(this,Ae).emit("session.initialize.resolved",{args:o(this,U),data:G})}catch(u){o(this,Ae).emit("session.initialize.resolved",{args:o(this,U),error:u})}})}};Ae=new WeakMap;Ct=new WeakMap;U=new WeakMap;var Mt="wss://socket.novu.co",$i="notifications.notification_received",Ki="notifications.unseen_count_changed",Di="notifications.unread_count_changed",Fs=({_id:t,transactionId:e,content:i,read:n,seen:r,archived:s,snoozedUntil:c,deliveredAt:a,createdAt:h,lastReadDate:u,firstSeenDate:d,archivedAt:w,channel:m,subscriber:p,subject:M,avatar:B,cta:S,tags:G,data:Se,workflow:Bt,severity:Ft})=>{var Ie,xe,Re,Pe,Le,Ue,We,Me;const $t={id:p?._id,subscriberId:p?.subscriberId,firstName:p?.firstName,lastName:p?.lastName,avatar:p?.avatar,locale:p?.locale,data:p?.data,timezone:p?.timezone,email:p?.email,phone:p?.phone},z=(xe=(Ie=S.action)==null?void 0:Ie.buttons)==null?void 0:xe.find(he=>he.type==="primary"),V=(Pe=(Re=S.action)==null?void 0:Re.buttons)==null?void 0:Pe.find(he=>
22he.type==="secondary"),Be=(Ue=(Le=S.action)==null?void 0:Le.result)==null?void 0:Ue.type,Fe=(We=S.action)==null?void 0:We.status;return k(v(v({id:t,transactionId:e,subject:M,body:i,to:$t,isRead:n,isSeen:r,isArchived:s,isSnoozed:!!c},a&&{deliveredAt:a}),c&&{snoozedUntil:c}),{createdAt:h,readAt:u,firstSeenAt:d,archivedAt:w,avatar:B,primaryAction:z&&{label:z.content,isCompleted:Be==="primary"&&Fe==="done",redirect:z.url?{target:z.target,url:z.url}:void 0},secondaryAction:V&&{label:V.content,isCompleted:Be==="secondary"&&Fe==="done",redirect:V.url?{target:V.target,url:V.url}:void 0},channelType:m,tags:G,redirect:(Me=S.data)!=null&&Me.url?{url:S.data.url,target:S.data.target}:void 0,data:Se,workflow:Bt,severity:Ft})},He,Y,Q,je,Pt,ei,ti,ii,vi,ge,Wn,ni,ri,$s=class extends ae{constructor({socketUrl:t,socketOptions:e,inboxServiceInstance:i,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:i}),f(this,ge),f(this,He),f(this,Y),f(this,Q),f(this,je),f(this,Pt),f(this,ei,r=>{try{const s=JSON.parse(r.data);s.event==="notification_received"&&o(this,Y).emit($i,{result:new N(Fs(s.data.message),o(this,Y),this._inboxService)})}catch(s){console.log("error",s)}}),f(this,ti,r=>{try{const s=JSON.parse(r.data);s.event==="unseen_count_changed"&&o(this,Y).emit(Ki,{result:s.data.unseenCount})}catch{}}),f(this,ii,r=>{try{const s=JSON.parse(r.data);s.event==="unread_count_changed"&&o(this,Y).emit(Di,{result:s.data.counts})}catch{}}),f(this,vi,r=>{try{switch(JSON.parse(r.data).event){case"notification_received":o(this,ei).call(this,r);break;case"unseen_count_changed":o(this,ti).call(this,r);break;case"unread_count_changed":o(this,ii).call(this,r);break;default:}}catch{}}),y(this,Y,n),y(this,je,t??Mt),y(this,Pt,e)}onSessionSuccess({token:t}){y(this,He,t)}isSocketEvent(t){return t===$i||t===Ki||t===Di}connect(){return l(this,null,function*(){return o(this,He)?Z(this,ge,ni).call(this):this.callWithSession(Z(this,ge,ni).bind(this))})}disconnect(){return l(this,null,function*(){return o(this,Q)?Z(this,ge,ri).call(this):this.callWithSession(Z(this,ge,ri).bind(this))})}};He=new WeakMap;Y=new WeakMap;Q=new WeakMap;je=new WeakMap;Pt=new WeakMap;ei=new WeakMap;ti=new WeakMap;ii=new WeakMap;vi=new WeakMap;ge=new WeakSet;Wn=function(){return l(this,null,function*(){if(o(this,Q))return;const t={socketUrl:o(this,je)};o(this,Y).emit("socket.connect.pending",{args:t});const e=new URL(o(this,je));e.searchParams.set("token",o(this,He)),y(this,Q,new ir(e.toString(),void 0,o(this,Pt))),o(this,Q).addEventListener("open",()=>{o(this,Y).emit("socket.connect.resolved",{args:t})}),o(this,Q).addEventListener("error",i=>{o(this,Y).emit("socket.connect.resolved",{args:t,error:i})}),o(this,Q).addEventListener("message",o(this,vi))})};ni=function(){return l(this,null,function*(){try{return yield Z(this,ge,Wn).call(this),{}}catch(t){return{error:new _("Failed to initialize the PartySocket",t)}}})};ri=function(){return l(this,null,function*(){var t;try{return(t=o(this,Q))==null||t.close(),y(this,Q,void 0),{}}catch(e){return{error:new _("Failed to disconnect from the PartySocket",e)}}})};var Ks="https://ws.novu.co",qi="notifications.notification_received",zi="notifications.unseen_count_changed",Vi="notifications.unread_count_changed",Ds=({_id:t,transactionId:e,content:i,read:n,seen:r,archived:s,snoozedUntil:c,deliveredAt:a,createdAt:h,lastReadDate:u,firstSeenDate:d,archivedAt:w,channel:m,subscriber:p,subject:M,avatar:B,cta:S,tags:G,data:Se,workflow:Bt,severity:Ft})=>{var Ie,xe,Re,Pe,Le,Ue,We,Me;const $t={id:p?._id,subscriberId:p?.subscriberId,firstName:p?.firstName,lastName:p?.lastName,avatar:p?.avatar,locale:p?.locale,data:p?.data,timezone:p?.timezone,email:p?.email,phone:p?.phone},z=(xe=(Ie=S.action)==null?void 0:Ie.buttons)==null?void 0:xe.find(he=>he.type==="primary"),V=(Pe=(Re=S.action)==null?void 0:Re.buttons)==null?void 0:Pe.find(he=>he.type==="secondary"),Be=(Ue=(Le=S.action)==null?void 0:Le.result)==null?void 0:Ue.type,Fe=(We=S.action)==null?void 0:We.status;return k(v(v({id:t,transactionId:e,subject:M,body:i,to:$t,isRead:n,isSeen:r,isArchived:s,isSnoozed:!!c},a&&{deliveredAt:a}),c&&{snoozedUntil:c}),{createdAt:h,readAt:u,firstSeenAt:d,archivedAt:w,avatar:B,primaryAction:z&&{label:z.content,isCompleted:Be==="primary"&&Fe==="done",redirect:z.url?{target:z.target,url:z.url}:void 0},secondaryAction:V&&{label:V.content,isCompleted:Be==="secondary"&&Fe==="done",redirect:V.url?{target:V.target,url:V.url}:void 0},channelType:m,tags:G,redirect:(Me=S.data)!=null&&Me.url?{url:S.data.url,target:S.data.target}:void 0,data:Se,workflow:Bt,severity:Ft})},Ge,X,D,Ye,Lt,mi,_i,wi,be,Mn,si,oi,qs=class extends ae{constructor({socketUrl:t,socketOptions:e,inboxServiceInstance:i,eventEmitterInstance:n}){super({eventEmitterInstance:n,inboxServiceInstance:i}),f(this,be),f(this,Ge),f(this,X),f(this,D),f(this,Ye),f(this,Lt),f(this,mi,({message:r})=>{o(this,X).emit(qi,{result:new N(Ds(r),o(this,X),this._inboxService)})}),f(this,_i,({unseenCount:r})=>{o(this,X).emit(zi,{result:r})}),f(this,wi,({counts:r})=>{o(this,X).emit(Vi,{result:r})}),y(this,X,n),y(this,Ye,t??Ks),y(this,Lt,e)}onSessionSuccess({token:t}){y(this,Ge,t)}isSocketEvent(t){return t===qi||t===zi||t===Vi}connect(){return l(this,null,function*(){return o(this,Ge)?Z(this,be,si).call(this):this.callWithSession(Z(this,be,si).bind(this))})}disconnect(){return l(this,null,function*(){return o(this,D)?Z(this,be,oi).call(this):this.callWithSession(Z(this,be,oi).bind(this))})}};Ge=new WeakMap;X=new WeakMap;D=new WeakMap;Ye=new WeakMap;Lt=new WeakMap;mi=new WeakMap;_i=new WeakMap;wi=new WeakMap;
22be=new WeakSet;Mn=function(){return l(this,null,function*(){var t,e,i,n;if(o(this,D))return;const r={socketUrl:o(this,Ye)};o(this,X).emit("socket.connect.pending",{args:r}),y(this,D,ot(o(this,Ye),v({reconnectionDelayMax:1e4,transports:["websocket"],query:{token:`${o(this,Ge)}`}},(t=o(this,Lt))!=null?t:{}))),o(this,D).on("connect",()=>{o(this,X).emit("socket.connect.resolved",{args:r})}),o(this,D).on("connect_error",s=>{o(this,X).emit("socket.connect.resolved",{args:r,error:s})}),(e=o(this,D))==null||e.on("notification_received",o(this,mi)),(i=o(this,D))==null||i.on("unseen_count_changed",o(this,_i)),(n=o(this,D))==null||n.on("unread_count_changed",o(this,wi))})};si=function(){return l(this,null,function*(){try{return yield Z(this,be,Mn).call(this),{}}catch(t){return{error:new _("Failed to initialize the socket",t)}}})};oi=function(){return l(this,null,function*(){var t;try{return(t=o(this,D))==null||t.disconnect(),y(this,D,void 0),{}}catch(e){return{error:new _("Failed to disconnect from the socket",e)}}})};var zs=["wss://eu.socket.novu.co",Mt,"wss://socket.novu-staging.co","wss://socket-worker-local.cli-shortener.workers.dev"],Vs={"https://eu.ws.novu.co":"wss://eu.socket.novu.co","https://ws.novu.co":Mt,"https://dev.ws.novu.co":"wss://socket.novu-staging.co"},Hs={cloud:"partysocket","self-hosted":"socket.io"};function Gs(t){return t?Vs[t]||t:Mt}function Js(t){return!t||zs.includes(t)}function js(t,e){return e?Hs[e]:Js(t)?"partysocket":"socket.io"}function Ys({socketUrl:t,socketOptions:e,inboxServiceInstance:i,eventEmitterInstance:n}){const r=Gs(t),s=e||{},{socketType:c}=s,a=ji(s,["socketType"]);return js(r,c)==="partysocket"?new $s({socketUrl:r,socketOptions:a,inboxServiceInstance:i,eventEmitterInstance:n}):new qs({socketUrl:r,socketOptions:a,inboxServiceInstance:i,eventEmitterInstance:n})}var K,W,j,Tt,Xs=class{constructor(t){f(this,K),f(this,W),f(this,j),f(this,Tt);var e,i,n;y(this,Tt,t),y(this,j,new ls({apiUrl:t.apiUrl||t.backendUrl})),y(this,K,new bs);const r=Kn({subscriberId:t.subscriberId,subscriber:t.subscriber}),s=bi(t.context);y(this,W,new Bs({applicationIdentifier:t.applicationIdentifier||"",subscriberHash:t.subscriberHash,subscriber:r,defaultSchedule:t.defaultSchedule,context:t.context,contextHash:t.contextHash},o(this,j),o(this,K))),o(this,W).initialize(),this.notifications=new Cs({useCache:(e=t.useCache)!=null?e:!0,inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,K)}),this.preferences=new Ws({useCache:(i=t.useCache)!=null?i:!0,inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,K)}),this.subscriptions=new ns({subscriber:r,contextKey:s,useCache:(n=t.useCache)!=null?n:!0,inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,K)}),this.channelConnections=new ys({inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,K)}),this.channelEndpoints=new gs({inboxServiceInstance:o(this,j),eventEmitterInstance:o(this,K)}),this.socket=Ys({socketUrl:t.socketUrl,socketOptions:t.socketOptions,eventEmitterInstance:o(this,K),inboxServiceInstance:o(this,j)}),this.on=(c,a)=>{this.socket.isSocketEvent(c)&&this.socket.connect();const h=o(this,K).on(c,a);return()=>{h()}},this.off=(c,a)=>{o(this,K).off(c,a)}}get applicationIdentifier(){return o(this,W).applicationIdentifier}get subscriberId(){return o(this,W).subscriberId}get context(){return o(this,W).context}get options(){return o(this,Tt)}get contextKey(){return bi(o(this,W).context)}clearCache(){this.notifications.cache.clearAll(),this.preferences.cache.clearAll(),this.preferences.scheduleCache.clearAll(),this.subscriptions.cache.clearAll()}changeSubscriber(t){return l(this,null,function*(){yield o(this,W).initialize({applicationIdentifier:o(this,W).applicationIdentifier||"",subscriberHash:t.subscriberHash,subscriber:t.subscriber,context:o(this,W).context,contextHash:o(this,W).contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}changeContext(t){return l(this,null,function*(){const e=o(this,W).subscriber;if(!e)throw new Error("Cannot change context without an active subscriber");yield o(this,W).initialize({applicationIdentifier:o(this,W).applicationIdentifier||"",subscriberHash:o(this,W).subscriberHash,subscriber:e,context:t.context,contextHash:t.contextHash}),this.clearCache(),(yield this.socket.disconnect()).error||(yield this.socket.connect())})}};K=new WeakMap;W=new WeakMap;j=new WeakMap;Tt=new WeakMap;const eo=Object.freeze(Object.defineProperty({__proto__:null,ChannelType:Qi,NotificationStatus:Yi,Novu:Xs,NovuError:_,PreferenceLevel:Xi,SeverityLevelEnum:en,SubscriptionPreference:Ce,TopicSubscription:Ne,WebSocketEvent:Zi,WorkflowCriticalityEnum:tn,areSeveritiesEqual:Tn,areTagsEqual:yi,checkNotificationDataFilter:Nn,checkNotificationMatchesFilter:Xr,isSameFilter:Zt,normalizeTagGroups:pi},Symbol.toStringTag,{value:"Module"}));
22export{rs as D,Xs as N,f as _,Z as a,y as b,o as c,k as d,v as e,ji as f,l as g,Jr as h,Zt as i,Nn as j,Ms as k,Dn as l,eo as m,Qs as p};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.