@nyaruka/temba-components 0.169.0 → 0.170.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/locales/es.js +1 -0
  3. package/dist/locales/es.js.map +1 -1
  4. package/dist/locales/fr.js +1 -0
  5. package/dist/locales/fr.js.map +1 -1
  6. package/dist/locales/pt.js +1 -0
  7. package/dist/locales/pt.js.map +1 -1
  8. package/dist/temba-components.js +501 -173
  9. package/dist/temba-components.js.map +1 -1
  10. package/package.json +1 -1
  11. package/src/display/Button.ts +14 -2
  12. package/src/display/Chat.ts +43 -24
  13. package/src/display/Dropdown.ts +11 -7
  14. package/src/display/Label.ts +18 -3
  15. package/src/display/Options.ts +27 -14
  16. package/src/display/TembaDate.ts +9 -2
  17. package/src/form/Compose.ts +37 -28
  18. package/src/form/select/Select.ts +15 -2
  19. package/src/interfaces.ts +13 -3
  20. package/src/list/BroadcastList.ts +20 -7
  21. package/src/list/ContactList.ts +113 -9
  22. package/src/list/ContentList.ts +380 -21
  23. package/src/list/ContentMenu.ts +12 -6
  24. package/src/list/FieldList.ts +8 -1
  25. package/src/list/TembaList.ts +99 -29
  26. package/src/list/TicketList.ts +87 -18
  27. package/src/live/CampaignEvents.ts +31 -11
  28. package/src/live/ContactChat.ts +36 -7
  29. package/src/live/ContactTimeline.ts +46 -24
  30. package/src/locales/es.ts +1 -0
  31. package/src/locales/fr.ts +1 -0
  32. package/src/locales/pt.ts +1 -0
  33. package/src/simulator/Simulator.ts +1 -0
  34. package/src/styles/designTokens.ts +57 -17
  35. package/src/styles/pillVariants.ts +42 -10
  36. package/static/css/design-system.css +47 -12
  37. package/static/css/temba-components.css +31 -9
  38. package/xliff/es.xlf +3 -0
  39. package/xliff/fr.xlf +3 -0
  40. package/xliff/pt.xlf +3 -0
@@ -61,16 +61,21 @@ const Ze=1,Ye=2,Xe=t=>(...e)=>({_$litDirective$:t,values:e});let Qe=class{constr
61
61
  Fallback matches the design-system.css default so component-
62
62
  only test harnesses pick up the same brand colour. */
63
63
  --accent: rgb(var(--primary-rgb, 73, 127, 206));
64
- --accent-50: color-mix(in srgb, var(--accent) 6%, white);
65
- --accent-100: color-mix(in srgb, var(--accent) 16%, white);
66
- --accent-200: color-mix(in srgb, var(--accent) 32%, white);
67
- --accent-300: color-mix(in srgb, var(--accent) 60%, white);
64
+ /* Static ramp values are pre-mixed from the default anchor for
65
+ browsers without color-mix() (pre-Chrome 111, e.g. the last
66
+ Chrome available on Windows 7/8.1). The @supports block below
67
+ re-derives them from --accent so host re-theming still works
68
+ where color-mix() is available. */
69
+ --accent-50: #f4f7fc;
70
+ --accent-100: #e2ebf7;
71
+ --accent-200: #c5d6ef;
72
+ --accent-300: #92b2e2;
68
73
  --accent-400: var(--accent);
69
- --accent-500: color-mix(in srgb, var(--accent) 90%, black);
70
- --accent-600: color-mix(in srgb, var(--accent) 80%, black);
71
- --accent-700: color-mix(in srgb, var(--accent) 65%, black);
72
- --accent-800: color-mix(in srgb, var(--accent) 50%, black);
73
- --accent-900: color-mix(in srgb, var(--accent) 35%, black);
74
+ --accent-500: #4272b9;
75
+ --accent-600: #3a66a5;
76
+ --accent-700: #2f5386;
77
+ --accent-800: #244067;
78
+ --accent-900: #1a2c48;
74
79
 
75
80
  /* neutrals */
76
81
  --bg: #f6f7f9;
@@ -165,14 +170,19 @@ const Ze=1,Ye=2,Xe=t=>(...e)=>({_$litDirective$:t,values:e});let Qe=class{constr
165
170
  error state (e.g. the dropdown popup) reference --focus-muted
166
171
  / --focus-halo directly to skip that override. */
167
172
  --focus: rgb(var(--focus-rgb, 91, 156, 229));
168
- --focus-50: color-mix(in srgb, var(--focus) 12%, white);
169
- --focus-100: color-mix(in srgb, var(--focus) 24%, white);
170
- --focus-200: color-mix(in srgb, var(--focus) 40%, white);
171
- --focus-300: color-mix(in srgb, var(--focus) 60%, white);
172
- --focus-600: color-mix(in srgb, var(--focus) 60%, black);
173
- --focus-700: color-mix(in srgb, var(--focus) 45%, black);
174
- --focus-muted: color-mix(in srgb, var(--focus) 60%, white);
175
- --focus-halo: 0 0 0 3px color-mix(in srgb, var(--focus) 30%, transparent);
173
+ /* Static values pre-mixed from the default focus hue for browsers
174
+ without color-mix(); re-derived in the @supports block below. */
175
+ --focus-50: #ebf3fc;
176
+ --focus-100: #d8e7f9;
177
+ --focus-200: #bdd7f5;
178
+ --focus-300: #9dc4ef;
179
+ --focus-600: #375e89;
180
+ --focus-700: #294667;
181
+ --focus-muted: #9dc4ef;
182
+ /* The halo is a translucent wash, so unlike the opaque ramp steps
183
+ it can keep tracking the theme without color-mix() — rgba(var())
184
+ substitution works wherever custom properties do. */
185
+ --focus-halo: 0 0 0 3px rgba(var(--focus-rgb, 91, 156, 229), 0.3);
176
186
  --color-focus: var(--focus-muted);
177
187
  --widget-box-shadow-focused: var(--focus-halo);
178
188
 
@@ -201,6 +211,36 @@ const Ze=1,Ye=2,Xe=t=>(...e)=>({_$litDirective$:t,values:e});let Qe=class{constr
201
211
  --temba-select-selected-font-size: 13.5px;
202
212
  --temba-select-min-height: var(--input-h);
203
213
  }
214
+
215
+ /* Where color-mix() is supported, derive the accent / focus ramps
216
+ from their anchors so host pages can re-theme by overriding just
217
+ --primary-rgb / --focus-rgb. Browsers without color-mix() keep the
218
+ static pre-mixed values above. Note the static values can't act as
219
+ per-declaration fallbacks — a custom property is never invalid at
220
+ parse time, so the last declaration always wins — hence the
221
+ @supports gate. */
222
+ @supports (color: color-mix(in srgb, red, red)) {
223
+ :host {
224
+ --accent-50: color-mix(in srgb, var(--accent) 6%, white);
225
+ --accent-100: color-mix(in srgb, var(--accent) 16%, white);
226
+ --accent-200: color-mix(in srgb, var(--accent) 32%, white);
227
+ --accent-300: color-mix(in srgb, var(--accent) 60%, white);
228
+ --accent-500: color-mix(in srgb, var(--accent) 90%, black);
229
+ --accent-600: color-mix(in srgb, var(--accent) 80%, black);
230
+ --accent-700: color-mix(in srgb, var(--accent) 65%, black);
231
+ --accent-800: color-mix(in srgb, var(--accent) 50%, black);
232
+ --accent-900: color-mix(in srgb, var(--accent) 35%, black);
233
+
234
+ --focus-50: color-mix(in srgb, var(--focus) 12%, white);
235
+ --focus-100: color-mix(in srgb, var(--focus) 24%, white);
236
+ --focus-200: color-mix(in srgb, var(--focus) 40%, white);
237
+ --focus-300: color-mix(in srgb, var(--focus) 60%, white);
238
+ --focus-600: color-mix(in srgb, var(--focus) 60%, black);
239
+ --focus-700: color-mix(in srgb, var(--focus) 45%, black);
240
+ --focus-muted: color-mix(in srgb, var(--focus) 60%, white);
241
+ --focus-halo: 0 0 0 3px color-mix(in srgb, var(--focus) 30%, transparent);
242
+ }
243
+ }
204
244
  `;class zo extends Ke{get value(){return this._value}set value(t){this._value=t}constructor(){super(),this.name="",this._value="",this.inputRoot=this,this.disabled=!1,this.hideErrors=!1,this.internals=this.attachInternals()}static get styles(){return d`
205
245
  ${Mo}
206
246
 
@@ -698,7 +738,7 @@ const Oo=t=>t??Z,Lo="important",Ro=" !"+Lo,No=Xe(class extends Qe{constructor(t)
698
738
  >
699
739
  <slot></slot>
700
740
  </div>
701
- `}}function Ho(t,e,i,o){return new(i||(i=Promise))(function(e,s){function n(t){try{a(o.next(t))}catch(t){s(t)}}function r(t){try{a(o.throw(t))}catch(t){s(t)}}function a(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(t){t(o)})).then(n,r)}a((o=o.apply(t,[])).next())})}function Vo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}i([ft({type:Boolean})],jo.prototype,"textarea",void 0),i([ft({type:String})],jo.prototype,"placeholder",void 0),i([ft({type:Boolean})],jo.prototype,"password",void 0),i([ft({type:Number})],jo.prototype,"maxlength",void 0),i([ft({type:Boolean})],jo.prototype,"clearable",void 0),i([ft({type:Boolean})],jo.prototype,"gsm",void 0),i([ft({type:String})],jo.prototype,"counter",void 0),i([ft({type:Boolean})],jo.prototype,"loading",void 0),i([ft({type:Boolean})],jo.prototype,"submitOnEnter",void 0),i([ft()],jo.prototype,"onBlur",void 0),i([ft({type:Boolean})],jo.prototype,"autogrow",void 0),i([ft({type:String})],jo.prototype,"type",void 0),i([ft({type:String})],jo.prototype,"flavor",void 0),function(t){t.DayFirst="day_first",t.MonthFirst="month_first",t.YearFirst="year_first"}(Bo||(Bo={})),function(t){t.CampaignEvent="campaign_event",t.ScheduledBroadcast="scheduled_broadcast",t.ScheduledTrigger="scheduled_trigger",t.SentBroadcast="sent_broadcast"}(Uo||(Uo={})),function(t){t.Open="open",t.Closed="closed"}(qo||(qo={})),function(t){t.Loaded="temba-loaded",t.Loading="temba-loading",t.Canceled="temba-canceled",t.CursorChanged="temba-cursor-changed",t.Refreshed="temba-refreshed",t.Selection="temba-selection",t.ButtonClicked="temba-button-clicked",t.DialogHidden="temba-dialog-hidden",t.ScrollThreshold="temba-scroll-threshold",t.ScrollThresholdBottom="temba-scroll-threshold-bottom",t.ContentChanged="temba-content-changed",t.ContextChanged="temba-context-changed",t.FetchComplete="temba-fetch-complete",t.MessageSent="temba-message-sent",t.Submitted="temba-submitted",t.Redirected="temba-redirected",t.NoPath="temba-no-path",t.StoreUpdated="temba-store-updated",t.Ready="temba-ready",t.OrderChanged="temba-order-changed",t.DragStart="temba-drag-start",t.DragStop="temba-drag-stop",t.DragExternal="temba-drag-external",t.DragInternal="temba-drag-internal",t.Resized="temba-resized",t.DetailsChanged="temba-details-changed",t.Error="temba-error",t.Interrupt="temba-interrupt",t.Opened="temba-opened",t.NotificationReceived="temba-notification",t.TicketUpdated="temba-ticket-updated",t.Moved="temba-moved",t.DateRangeChanged="temba-date-range-changed",t.NodeDeleted="temba-node-deleted",t.StickyNoteDeleted="temba-sticky-note-deleted",t.ActionEditRequested="temba-action-edit-requested",t.AddActionRequested="temba-add-action-requested",t.ActionSaved="temba-action-saved",t.ActionEditCanceled="temba-action-edit-canceled",t.NodeEditRequested="temba-node-edit-requested",t.NodeSaved="temba-node-saved",t.NodeEditCancelled="temba-node-edit-cancelled",t.FollowSimulation="temba-follow-simulation",t.ContactClicked="temba-contact-clicked",t.FlowClicked="temba-flow-clicked",t.GroupClicked="temba-group-clicked",t.ShowIssue="temba-show-issue",t.SizeChanged="temba-size-changed",t.IssueSelected="temba-issue-selected",t.IssuesClosed="temba-issues-closed",t.IssuesTabClicked="temba-issues-tab-clicked",t.RevisionViewed="temba-revision-viewed",t.RevisionCancelled="temba-revision-cancelled",t.RevisionReverted="temba-revision-reverted",t.RevisionsClosed="temba-revisions-closed",t.RowClick="temba-row-click",t.SelectionChange="temba-selection-change",t.BulkAction="temba-bulk-action",t.LabelCreate="temba-label-create",t.HistoryChange="temba-history-change"}(Wo||(Wo={})),"function"==typeof SuppressedError&&SuppressedError;var Go,Ko={exports:{}};var Zo,Yo,Xo,Qo,Jo,ts,es,is,os,ss=function(){if(Go)return Ko.exports;Go=1;var t,e="object"==typeof Reflect?Reflect:null,i=e&&"function"==typeof e.apply?e.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)};t=e&&"function"==typeof e.ownKeys?e.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var o=Number.isNaN||function(t){return t!=t};function s(){s.init.call(this)}Ko.exports=s,Ko.exports.once=function(t,e){return new Promise(function(i,o){function s(i){t.removeListener(e,n),o(i)}function n(){"function"==typeof t.removeListener&&t.removeListener("error",s),i([].slice.call(arguments))}m(t,e,n,{once:!0}),"error"!==e&&function(t,e,i){"function"==typeof t.on&&m(t,"error",e,i)}(t,s,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var n=10;function r(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}function a(t){return void 0===t._maxListeners?s.defaultMaxListeners:t._maxListeners}function l(t,e,i,o){var s,n,l,d;if(r(i),void 0===(n=t._events)?(n=t._events=Object.create(null),t._eventsCount=0):(void 0!==n.newListener&&(t.emit("newListener",e,i.listener?i.listener:i),n=t._events),l=n[e]),void 0===l)l=n[e]=i,++t._eventsCount;else if("function"==typeof l?l=n[e]=o?[i,l]:[l,i]:o?l.unshift(i):l.push(i),(s=a(t))>0&&l.length>s&&!l.warned){l.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+l.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=l.length,d=c,console&&console.warn&&console.warn(d)}return t}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function c(t,e,i){var o={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},s=d.bind(o);return s.listener=i,o.wrapFn=s,s}function h(t,e,i){var o=t._events;if(void 0===o)return[];var s=o[e];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}(s):p(s,s.length)}function u(t){var e=this._events;if(void 0!==e){var i=e[t];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(t,e){for(var i=new Array(e),o=0;o<e;++o)i[o]=t[o];return i}function m(t,e,i,o){if("function"==typeof t.on)o.once?t.once(e,i):t.on(e,i);else{if("function"!=typeof t.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t);t.addEventListener(e,function s(n){o.once&&t.removeEventListener(e,s),i(n)})}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return n},set:function(t){if("number"!=typeof t||t<0||o(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");n=t}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||o(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(t){for(var e=[],o=1;o<arguments.length;o++)e.push(arguments[o]);var s="error"===t,n=this._events;if(void 0!==n)s=s&&void 0===n.error;else if(!s)return!1;if(s){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var l=n[t];if(void 0===l)return!1;if("function"==typeof l)i(l,this,e);else{var d=l.length,c=p(l,d);for(o=0;o<d;++o)i(c[o],this,e)}return!0},s.prototype.addListener=function(t,e){return l(this,t,e,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(t,e){return l(this,t,e,!0)},s.prototype.once=function(t,e){return r(e),this.on(t,c(this,t,e)),this},s.prototype.prependOnceListener=function(t,e){return r(e),this.prependListener(t,c(this,t,e)),this},s.prototype.removeListener=function(t,e){var i,o,s,n,a;if(r(e),void 0===(o=this._events))return this;if(void 0===(i=o[t]))return this;if(i===e||i.listener===e)0===--this._eventsCount?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,i.listener||e));else if("function"!=typeof i){for(s=-1,n=i.length-1;n>=0;n--)if(i[n]===e||i[n].listener===e){a=i[n].listener,s=n;break}if(s<0)return this;0===s?i.shift():function(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}(i,s),1===i.length&&(o[t]=i[0]),void 0!==o.removeListener&&this.emit("removeListener",t,a||e)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(t){var e,i,o;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[t]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[t]),this;if(0===arguments.length){var s,n=Object.keys(i);for(o=0;o<n.length;++o)"removeListener"!==(s=n[o])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(e=i[t]))this.removeListener(t,e);else if(void 0!==e)for(o=e.length-1;o>=0;o--)this.removeListener(t,e[o]);return this},s.prototype.listeners=function(t){return h(this,t,!0)},s.prototype.rawListeners=function(t){return h(this,t,!1)},s.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):u.call(t,e)},s.prototype.listenerCount=u,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]},Ko.exports}(),ns=Vo(ss);function rs(t){return null!=t&&"function"==typeof t}function as(t,e,i){t>31&&(t=31);const o=function(t,e){return Math.floor(Math.random()*(e-t+1)+t)}(0,Math.min(i,e*Math.pow(2,t)));return Math.min(i,e+o)}function ls(t){return Math.min(1e3*t,2147483647)}!function(t){t[t.timeout=1]="timeout",t[t.transportClosed=2]="transportClosed",t[t.clientDisconnected=3]="clientDisconnected",t[t.clientClosed=4]="clientClosed",t[t.clientConnectToken=5]="clientConnectToken",t[t.clientRefreshToken=6]="clientRefreshToken",t[t.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",t[t.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",t[t.subscriptionRefreshToken=9]="subscriptionRefreshToken",t[t.transportWriteError=10]="transportWriteError",t[t.connectionClosed=11]="connectionClosed",t[t.badConfiguration=12]="badConfiguration",t[t.subscriptionGetState=13]="subscriptionGetState",t[t.sharedPollGetSignature=14]="sharedPollGetSignature"}(Zo||(Zo={})),function(t){t[t.connectCalled=0]="connectCalled",t[t.transportClosed=1]="transportClosed",t[t.noPing=2]="noPing",t[t.subscribeTimeout=3]="subscribeTimeout",t[t.unsubscribeError=4]="unsubscribeError"}(Yo||(Yo={})),function(t){t[t.disconnectCalled=0]="disconnectCalled",t[t.unauthorized=1]="unauthorized",t[t.badProtocol=2]="badProtocol",t[t.messageSizeLimit=3]="messageSizeLimit",t[t.stateInvalidated=3014]="stateInvalidated"}(Xo||(Xo={})),function(t){t[t.subscribeCalled=0]="subscribeCalled",t[t.transportClosed=1]="transportClosed"}(Qo||(Qo={})),function(t){t[t.unsubscribeCalled=0]="unsubscribeCalled",t[t.unauthorized=1]="unauthorized",t[t.clientClosed=2]="clientClosed",t[t.stateInvalidated=2502]="stateInvalidated"}(Jo||(Jo={})),function(t){t[t.channelCompaction=1]="channelCompaction",t[t.rejectUnrecovered=2]="rejectUnrecovered"}(ts||(ts={})),function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected"}(es||(es={})),function(t){t.Unsubscribed="unsubscribed",t.Subscribing="subscribing",t.Subscribed="subscribed"}(is||(is={})),function(t){t[t.Live=0]="Live",t[t.Stream=1]="Stream",t[t.State=2]="State"}(os||(os={}));class ds extends ns{constructor(t,e,i){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this._getState=null,this._map=!1,this._mapPresenceType=1,this._mapPhase=null,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPageSize=0,this._mapUnrecoverableStrategy="from_scratch",this._debounceMs=0,this._debouncePending=new Map,this._sharedPoll=!1,this._sharedPollEpoch="",this._sharedPollTrackedItems=new Map,this._sharedPollGetSignature=null,this._sharedPollSignatureRefreshTimeout=null,this._sharedPollSignatureRefreshAttempts=0,this._sharedPollTrackRetryTimeout=null,this._sharedPollTrackRetryAttempts=0,this._sharedPollReplayRetryTimeout=null,this._sharedPollReplayRetryAttempts=0,this._sharedPollSignatures=[],this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1,this.channel=e,this.state=is.Unsubscribed,this._centrifuge=t,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValueMap=new Map,this._unsubPromise=Promise.resolve(),this._deltaNumPubs=0,this._deltaNumFull=0,this._deltaNumDelta=0,this._deltaBytesReceived=0,this._deltaBytesDecoded=0,this._setOptions(i),this.type=this._sharedPoll?"shared_poll":this._map?"map":"stream",this._centrifuge._debugEnabled?(this.on("state",t=>{this._debug("subscription state",e,t.oldState,"->",t.newState)}),this.on("error",t=>{this._debug("subscription error",e,t)})):this.on("error",function(){Function.prototype()})}ready(t){return this.state===is.Unsubscribed?Promise.reject({code:Zo.subscriptionUnsubscribed,message:this.state}):this.state===is.Subscribed?Promise.resolve():new Promise((e,i)=>{const o={resolve:e,reject:i};t&&(o.timeout=setTimeout(function(){i({code:Zo.timeout,message:"timeout"})},t)),this._promises[this._nextPromiseId()]=o})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(Qo.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(Jo.unsubscribeCalled,"unsubscribe called",!0)}_debouncedPublish(t,e,i){const o=this._debouncePending.get(t);if(o)return o.data=e,o.dirty=!0,Promise.resolve({});const s={data:e,dirty:!1,timer:null};s.timer=setTimeout(()=>{const e=this._debouncePending.get(t);if(!e||!e.dirty)return void this._debouncePending.delete(t);e.dirty=!1;const o=e.data;(i?this._centrifuge.mapPublish(this.channel,t,o):this._centrifuge.publish(this.channel,o)).catch(()=>{}),e.timer=setTimeout(()=>{const e=this._debouncePending.get(t);e&&e.dirty?(this._debouncePending.delete(t),this._debouncedPublish(t,e.data,i)):this._debouncePending.delete(t)},this._debounceMs)},this._debounceMs),this._debouncePending.set(t,s);return i?this._centrifuge.mapPublish(this.channel,t,e):this._centrifuge.publish(this.channel,e)}_cancelDebounce(t){const e=this._debouncePending.get(t);e&&(clearTimeout(e.timer),this._debouncePending.delete(t))}_cancelAllDebounce(){for(const[,t]of this._debouncePending)clearTimeout(t.timer);this._debouncePending.clear()}presence(){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}setTagsFilter(t){if(t&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=t,this._map&&(this._recover=!1,this._offset=null,this._epoch=null)}setData(t){this._data=t}deltaStats(){const t=this._deltaBytesDecoded;return{numPublications:this._deltaNumPubs,numFullPayloads:this._deltaNumFull,numDeltaPayloads:this._deltaNumDelta,bytesReceived:this._deltaBytesReceived,bytesDecoded:t,compressionRatio:t>0?1-this._deltaBytesReceived/t:0}}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:Zo.subscriptionUnsubscribed,message:this.state}):new Promise((t,e)=>{const i=this._centrifuge._config.timeout,o=setTimeout(()=>{e({code:Zo.timeout,message:"timeout"})},i);this._promises[this._nextPromiseId()]={timeout:o,resolve:t,reject:e}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return!0===this._recover}_isUnsubscribed(){return this.state===is.Unsubscribed}_isSubscribing(){return this.state===is.Subscribing}_isSubscribed(){return this.state===is.Subscribed}_setState(t){if(this.state!==t){const e=this.state;return this.state=t,this.emit("state",{newState:t,oldState:e,channel:this.channel}),!0}return!1}_usesToken(){return""!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout(),this._clearSharedPollSignatureRefresh(),this._clearSharedPollTrackRetry(),this._clearSharedPollReplayRetry(),this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1}_invalidateState(){this._token="",this._prevValueMap=new Map,this._map?(this._offset=null,this._epoch=null,this._recover=!1,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPhase=null):(this._offset=0,this._epoch="_")}_setSubscribed(t){if(!this._isSubscribing())return;if(this._clearSubscribingState(),t.id&&(this._id=t.id),t.recoverable&&(this._recover=!0,this._offset=t.offset||0,this._epoch=t.epoch||""),t.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,t.publish_debounce&&(this._debounceMs=t.publish_debounce),this._sharedPoll){const e=t.epoch||"";if(""!==this._sharedPollEpoch&&this._sharedPollEpoch!==e)for(const t of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(t,0);this._sharedPollEpoch=e}this._setState(is.Subscribed);const e=this._centrifuge._getSubscribeContext(this.channel,t);this.emit("subscribed",e),this._resolvePromises();const i=t.publications;if(i&&i.length>0)for(const t in i)i.hasOwnProperty(t)&&this._handlePublication(i[t]);!0===t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl)))}_setSubscribing(t,e){return Ho(this,0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._id=0,this._setState(is.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:t,reason:e}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield this._unsubPromise),this._isSubscribing()&&this._subscribe())})}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._map?(this._mapSubscribe(),null):this._getState&&null===this._offset?(this._loadStreamState(),null):this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():(this._getSubscriptionToken().then(t=>this._handleTokenResponse(t)).catch(t=>this._handleTokenError(t)),null)):(this._debug("delay subscribe on",this.channel,"till connected"),null)}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(){return this._getData?(this._getDataAndSubscribe(this._token),null):this._sendSubscribe(this._token)}_loadStreamState(){this._isSubscribing()?this._getState().then(t=>{this._isSubscribing()?(this._offset=t.offset,this._epoch=t.epoch,this._recover=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():this._getSubscriptionToken().then(t=>this._handleTokenResponse(t)).catch(t=>this._handleTokenError(t))):this._inflight=!1}).catch(t=>{this._isSubscribing()?(this._inflight=!1,this._subscribeError({code:Zo.subscriptionGetState,message:(null==t?void 0:t.toString())||"getState failed",temporary:!0})):this._inflight=!1}):this._inflight=!1}_getDataAndSubscribe(t){this._getData?this._getData({channel:this.channel}).then(e=>{this._isSubscribing()?(this._data=e,this._sendSubscribe(t)):this._inflight=!1}).catch(t=>this._handleGetDataError(t)):this._inflight=!1}_handleGetDataError(t){if(this._isSubscribing()){if(t instanceof Cs)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:Zo.badConfiguration,message:(null==t?void 0:t.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_handleTokenResponse(t){if(this._isSubscribing()){if(!t)return this._inflight=!1,void this._failUnauthorized();this._token=t,this._getData?this._getDataAndSubscribe(t):this._sendSubscribe(t)}else this._inflight=!1}_handleTokenError(t){if(this._isSubscribing()){if(t instanceof Cs)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:Zo.subscriptionSubscribeToken,message:(null==t?void 0:t.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_sendSubscribe(t){if(!this._isTransportOpen())return this._inflight=!1,null;const e=this._buildSubscribeCommand(t);return this._centrifuge._call(e).then(t=>{this._inflight=!1;const e=t.reply.subscribe;this._handleSubscribeResponse(e),t.next&&t.next()},t=>{this._inflight=!1,this._handleSubscribeError(t.error),t.next&&t.next()}),e}_buildSubscribeCommand(t){const e={channel:this.channel};if(t&&(e.token=t),this._data&&(e.data=this._data),this._sharedPoll)return e.type=4,this._delta&&(e.delta=this._delta),{subscribe:e};if(this._positioned&&(e.positioned=!0),this._recoverable&&(e.recoverable=!0),this._joinLeave&&(e.join_leave=!0),e.flag=ts.channelCompaction,this._getState&&(e.flag|=ts.rejectUnrecovered),this._needRecover()){e.recover=!0;const t=this._getOffset();t&&(e.offset=t);const i=this._getEpoch();i&&(e.epoch=i)}return this._delta&&(e.delta=this._delta),this._tagsFilter&&(e.tf=this._tagsFilter),{subscribe:e}}_debug(...t){this._centrifuge._debug(...t)}_handleSubscribeError(t){if(this._isSubscribing()){if(t.code!==Zo.timeout)return 112===t.code&&this._getState?(this._offset=null,this._epoch=null,this._recover=!1,this._prevValueMap=new Map,void this._scheduleResubscribe()):void this._subscribeError(t);this._centrifuge._disconnect(Yo.subscribeTimeout,"subscribe timeout",!0)}}_handleSubscribeResponse(t){this._isSubscribing()&&(this._setSubscribed(t),this._sharedPoll&&this._sharedPollReplayTrack())}_setUnsubscribed(t,e,i){if(this._isUnsubscribed())return Promise.resolve();let o=Promise.resolve();return this._isSubscribed()?(i&&(o=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&i&&(o=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._id=0,this._sharedPollEpoch="",this._sharedPollSignatures=[],this._sharedPollTrackedItems.clear(),this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshTargetMs=null,this._cancelAllDebounce(),this._setState(is.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:t,reason:e}),this._rejectPromises({code:Zo.subscriptionUnsubscribed,message:this.state}),o}_handlePublication(t){if(this._delta&&this._delta_negotiated){const e=(this._map||this._sharedPoll)&&t.key||"",{newData:i,newPrevValue:o,isDelta:s,wireBytes:n,fullBytes:r}=this._centrifuge._codec.applyDeltaIfNeeded(t,this._prevValueMap.get(e));t.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=n,this._deltaBytesDecoded+=r,s?this._deltaNumDelta++:this._deltaNumFull++,t.removed?this._prevValueMap.delete(e):this._prevValueMap.set(e,o)}let e;if(this._sharedPoll){if(t.key&&!this._sharedPollTrackedItems.has(t.key))return;t.key&&(t.removed?this._sharedPollTrackedItems.delete(t.key):t.version&&this._sharedPollTrackedItems.set(t.key,t.version)),e=this._getSharedPollUpdateContext(t)}else e=this._map?this._getMapUpdateContext(t):this._centrifuge._getPublicationContext(this.channel,t);this.emit("publication",e),(this._map||this._sharedPoll)&&this.emit("update",e),t.offset&&(this._offset=t.offset),t.epoch&&(this._epoch=t.epoch)}_seedDeltaTracking(t){if(this._delta&&t.key)if("string"==typeof t.data){const e=t.data;t.removed?this._prevValueMap.delete(t.key):this._prevValueMap.set(t.key,(new TextEncoder).encode(e));const i=e.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=i,this._deltaBytesDecoded+=i,t.data=JSON.parse(e)}else if(t.data instanceof Uint8Array){t.removed?this._prevValueMap.delete(t.key):this._prevValueMap.set(t.key,t.data);const e=t.data.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=e,this._deltaBytesDecoded+=e}}_handleJoin(t){const e=this._centrifuge._getJoinLeaveContext(t.info);this.emit("join",{channel:this.channel,info:e})}_handleLeave(t){const e=this._centrifuge._getJoinLeaveContext(t.info);this.emit("leave",{channel:this.channel,info:e})}_resolvePromises(){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].resolve(),delete this._promises[t])}_rejectPromises(t){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].reject(t),delete this._promises[e])}_scheduleResubscribe(){if(!this._isSubscribing())return void this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);const t=this,e=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){t._isSubscribing()&&t._subscribe()},e),this._debug("resubscribe scheduled after "+e,this.channel)}_subscribeError(t){if(this._isSubscribing())if(t.code<100||109===t.code||!0===t.temporary){109===t.code&&(this._token="");const e={channel:this.channel,type:"subscribe",error:t};this._centrifuge.state===es.Connected&&this.emit("error",e),this._scheduleResubscribe()}else this._setUnsubscribed(t.code,t.message,!1)}_getResubscribeDelay(){const t=as(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,t}_setOptions(t){if(t){if(t.since&&(this._offset=t.since.offset||0,this._epoch=t.since.epoch||"",this._recover=!0),t.data&&(this._data=t.data),t.getData&&(this._getData=t.getData),void 0!==t.minResubscribeDelay&&(this._minResubscribeDelay=t.minResubscribeDelay),void 0!==t.maxResubscribeDelay&&(this._maxResubscribeDelay=t.maxResubscribeDelay),t.token&&(this._token=t.token),t.getToken&&(this._getToken=t.getToken),!0===t.positioned&&(this._positioned=!0),!0===t.recoverable&&(this._recoverable=!0),!0===t.joinLeave&&(this._joinLeave=!0),t.delta){if("fossil"!==t.delta)throw new Error("unsupported delta format");this._delta=t.delta}if(t.tagsFilter&&(this._tagsFilter=t.tagsFilter),this._tagsFilter&&this._delta)throw new Error("cannot use delta and tagsFilter together");t.getState&&(this._getState=t.getState,this._recover=!0),!0===t.map&&(this._map=!0),void 0!==t.mapPageSize&&(this._mapPageSize=t.mapPageSize),void 0!==t.mapPresenceType&&(this._mapPresenceType=t.mapPresenceType,this._map=!0),t.mapUnrecoverableStrategy&&(this._mapUnrecoverableStrategy=t.mapUnrecoverableStrategy),!0===t.sharedPoll&&(this._sharedPoll=!0),t.sharedPollGetSignature&&(this._sharedPollGetSignature=t.sharedPollGetSignature)}}_getOffset(){const t=this._offset;return null!==t?t:0}_getEpoch(){const t=this._epoch;return null!==t?t:""}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);const t={channel:this.channel},e=this._getToken;return null===e?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:Zo.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new Cs(""))):e(t)}_refresh(){this._clearRefreshTimeout();const t=this;this._getSubscriptionToken().then(function(e){if(!t._isSubscribed())return;if(!e)return void t._failUnauthorized();t._token=e;const i={sub_refresh:{channel:t.channel,token:e}};t._centrifuge._call(i).then(e=>{const i=e.reply.sub_refresh;t._refreshResponse(i),e.next&&e.next()},e=>{t._refreshError(e.error),e.next&&e.next()})}).catch(function(e){e instanceof Cs?t._failUnauthorized():(t.emit("error",{type:"refreshToken",channel:t.channel,error:{code:Zo.subscriptionRefreshToken,message:void 0!==e?e.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay()))})}_refreshResponse(t){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),!0===t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl))))}_refreshError(t){this._isSubscribed()&&(t.code<100||!0===t.temporary?(this.emit("error",{type:"refresh",channel:this.channel,error:t}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._setUnsubscribed(t.code,t.message,!0))}_getRefreshRetryDelay(){return as(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(Jo.unauthorized,"unauthorized",!0)}_sendTrackRequest(t,e){if(0===t.length)return Promise.resolve();const i=[];let o=[],s=100;if(e&&e.length>0)for(const t of e)s+=t.length+4;for(const e of t){let t=100;for(const i of e.items)t+=i.key.length+16;o.length>0&&s+t>6e4&&(i.push(o),o=[],s=100),o.push(e),s+=t}o.length>0&&i.push(o);const n=(t,e)=>new Promise((i,o)=>{const s={channel:this.channel,type:1,track:t.map(t=>({signature:t.signature,items:t.items.map(t=>t.version>0?t:{key:t.key})}))};e&&e.length>0&&(s.untrack=e);const n={sub_refresh:s};this._centrifuge._call(n).then(t=>{this._handleTrackResponse(t.reply.sub_refresh),t.next&&t.next(),i()},t=>{t.next&&t.next(),o(t.error)})});return i.reduce((t,i,o)=>t.then(()=>n(i,0===o?e:void 0)),Promise.resolve())}_sendUntrackRequest(t){return new Promise((e,i)=>{const o={sub_refresh:{channel:this.channel,type:2,untrack:t}};this._centrifuge._call(o).then(t=>{t.next&&t.next(),e()},t=>{t.next&&t.next(),i(t.error)})})}_handleTrackResponse(t){if(this._clearSharedPollTrackRetry(),t&&t.items&&t.items.length>0)for(const e of t.items)this._handlePublication(e);if(t&&!0===t.expires&&t.ttl>0){const e=Date.now()+1e3*t.ttl;this._maybeScheduleSharedPollSignatureRefresh(e)}}_maybeScheduleSharedPollSignatureRefresh(t){if(null===t)return this._sharedPollSignatureRefreshTargetMs=null,void this._clearSharedPollSignatureRefresh();this._isSubscribed()&&(null!==this._sharedPollSignatureRefreshTargetMs&&t>=this._sharedPollSignatureRefreshTargetMs||(this._sharedPollSignatureRefreshTargetMs=t,this._clearSharedPollSignatureRefresh(),this._sharedPollSignatureRefreshTimeout=setTimeout(()=>this._sharedPollRefreshSignature(),Math.max(0,t-Date.now()))))}_clearSharedPollSignatureRefresh(){null!==this._sharedPollSignatureRefreshTimeout&&(clearTimeout(this._sharedPollSignatureRefreshTimeout),this._sharedPollSignatureRefreshTimeout=null),this._sharedPollSignatureRefreshAttempts=0}_clearSharedPollTrackRetry(){null!==this._sharedPollTrackRetryTimeout&&(clearTimeout(this._sharedPollTrackRetryTimeout),this._sharedPollTrackRetryTimeout=null),this._sharedPollTrackRetryAttempts=0}_clearSharedPollReplayRetry(){null!==this._sharedPollReplayRetryTimeout&&(clearTimeout(this._sharedPollReplayRetryTimeout),this._sharedPollReplayRetryTimeout=null),this._sharedPollReplayRetryAttempts=0}_handleTrackError(t){this._isSubscribed()&&(this.emit("error",{type:"track",channel:this.channel,error:t}),109!==t.code?(t.code<100||!0===t.temporary)&&(this._sharedPollTrackRetryTimeout=setTimeout(()=>this._sharedPollReplayTrack(),as(this._sharedPollTrackRetryAttempts++,1e3,15e3))):this._sharedPollRefreshSignature())}_sharedPollRefreshSignature(){if(this._clearSharedPollSignatureRefresh(),!this._isSubscribed())return;if(!this._sharedPollGetSignature)return;if(0===this._sharedPollTrackedItems.size)return;if(this._sharedPollSignatureRefreshInFlight)return;this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!0;const t=Array.from(this._sharedPollTrackedItems.keys()),e=this;this._sharedPollGetSignature({keys:t}).then(i=>{if(e._sharedPollSignatureRefreshInFlight=!1,!e._isSubscribed())return;e._sharedPollSignatureRefreshAttempts=0;const o=new Set(i.keys),s=[];for(const i of t)o.has(i)||(e._sharedPollTrackedItems.delete(i),s.push(i),e.emit("update",{channel:e.channel,key:i,data:null,removed:!0}));s.length>0&&e._sendUntrackRequest(s).catch(t=>{e.emit("error",{type:"untrack",channel:e.channel,error:t})});const n=[];for(const t of i.keys){const i=e._sharedPollTrackedItems.get(t);void 0!==i&&n.push({key:t,version:i})}const r=new Set(i.keys),a=e._sharedPollSignatures.filter(t=>t.keys.some(t=>e._sharedPollTrackedItems.has(t)&&!r.has(t)));e._sharedPollSignatures=n.length>0?[{keys:i.keys,signature:i.signature},...a]:a,0!==n.length&&e._sendTrackRequest([{items:n,signature:i.signature}]).catch(t=>{e._handleTrackError(t)})}).catch(t=>{e._sharedPollSignatureRefreshInFlight=!1,e.emit("error",{type:"signatureRefresh",channel:e.channel,error:{code:Zo.sharedPollGetSignature,message:void 0!==t?t.toString():""}}),e._sharedPollSignatureRefreshTimeout=setTimeout(()=>e._sharedPollRefreshSignature(),as(e._sharedPollSignatureRefreshAttempts++,5e3,3e4))})}_sharedPollReplayTrack(){if(!this._isSubscribed())return;if(0===this._sharedPollTrackedItems.size&&0===this._sharedPollSignatures.length)return;const t=new Set,e=[],i=[];for(const o of this._sharedPollSignatures){const s=o.keys.map(t=>{var e;return{key:t,version:null!==(e=this._sharedPollTrackedItems.get(t))&&void 0!==e?e:0}});e.push({items:s,signature:o.signature});for(const e of o.keys)this._sharedPollTrackedItems.has(e)?t.add(e):i.push(e)}e.length>0&&this._sendTrackRequest(e,i).catch(t=>{this._handleTrackError(t)});const o=[];for(const e of this._sharedPollTrackedItems.keys())t.has(e)||o.push(e);if(0===o.length)return;if(!this._sharedPollGetSignature)return void this.emit("error",{type:"track",channel:this.channel,error:{code:Zo.sharedPollGetSignature,message:"getSignature callback required for tracked keys without an explicit signature"}});const s=this;this._sharedPollGetSignature({keys:o}).then(t=>{if(!s._isSubscribed())return;s._clearSharedPollReplayRetry();const e=new Set(t.keys),i=[];for(const t of o)e.has(t)||(s._sharedPollTrackedItems.delete(t),i.push(t),s.emit("update",{channel:s.channel,key:t,data:null,removed:!0}));i.length>0&&s._sendUntrackRequest(i).catch(t=>{s.emit("error",{type:"untrack",channel:s.channel,error:t})});const n=[];for(const e of t.keys){const t=s._sharedPollTrackedItems.get(e);void 0!==t&&n.push({key:e,version:t})}0!==n.length&&(s._sharedPollSignatures.push({keys:t.keys,signature:t.signature}),s._sendTrackRequest([{items:n,signature:t.signature}]).catch(t=>{s._handleTrackError(t)}))}).catch(t=>{s.emit("error",{type:"signatureRefresh",channel:s.channel,error:{code:Zo.sharedPollGetSignature,message:void 0!==t?t.toString():""}}),s._sharedPollReplayRetryTimeout=setTimeout(()=>s._sharedPollReplayTrack(),as(s._sharedPollReplayRetryAttempts++,5e3,3e4))})}_mapSubscribe(){if(this._debug("starting map subscribe on",this.channel),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._recover&&null!==this._offset&&null!==this._epoch||(this._prevValueMap=new Map),this._mapPhase=os.State,this._recover&&null!==this._offset&&null!==this._epoch)return this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=os.Stream,void this._fetchStream();this._canSubscribeWithoutGettingToken()?this._fetchSnapshot():this._getSubscriptionToken().then(t=>{if(this._isSubscribing()){if(!t)return this._inflight=!1,void this._failUnauthorized();this._token=t,this._fetchSnapshot()}else this._inflight=!1}).catch(t=>this._handleTokenError(t))}_fetchSnapshot(t){if(!this._isSubscribing()||!this._isTransportOpen())return void(this._inflight=!1);const e=this._buildMapSubscribeCommand(os.State,t);this._debug("map subscribe: fetching snapshot page",t?`cursor=${t}`:"initial"),this._centrifuge._call(e).then(t=>{const e=t.reply.subscribe;this._handleMapStateResponse(e),t.next&&t.next()},t=>{this._handleMapSubscribeError(t.error),t.next&&t.next()})}_handleMapStateResponse(t){if(this._isSubscribing()){if(!t.phase)return this._debug("map subscribe: server forced LIVE transition during state pagination"),void this._handleMapLiveResponse(t);if(!this._epoch&&t.epoch&&(this._epoch=t.epoch,this._offset=t.offset||0),this._epoch&&t.epoch&&this._epoch!==t.epoch)return this._debug("map subscribe: epoch changed during snapshot pagination, restarting"),this._mapStateBuffer=[],this._mapCursor="",this._epoch=null,this._offset=null,this._prevValueMap=new Map,void this._fetchSnapshot();if(t.state&&t.state.length>0)for(const e of t.state)this._seedDeltaTracking(e),this._mapStateBuffer.push(this._getMapUpdateContext(e));if(t.cursor)return this._mapCursor=t.cursor,void this._fetchSnapshot(this._mapCursor);this._transitionFromSnapshot()}else this._inflight=!1}_transitionFromSnapshot(){this._debug("map subscribe: snapshot complete, transitioning to stream phase"),this._mapPhase=os.Stream,this._fetchStream()}_fetchStream(){if(!this._isSubscribing()||!this._isTransportOpen())return void(this._inflight=!1);const t=this._buildMapSubscribeCommand(os.Stream);this._debug("map subscribe: fetching stream from offset",this._offset),this._centrifuge._call(t).then(t=>{const e=t.reply.subscribe;this._handleMapStreamResponse(e),t.next&&t.next()},t=>{this._handleMapSubscribeError(t.error),t.next&&t.next()})}_handleMapStreamResponse(t){if(this._isSubscribing()){if(!t.phase)return this._debug("map subscribe: server forced LIVE transition during stream"),void this._handleMapLiveResponse(t);if(this._epoch&&t.epoch&&this._epoch!==t.epoch)return this._debug("map subscribe: epoch changed during stream, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._mapPhase=os.State,void this._fetchSnapshot();if(t.publications&&t.publications.length>0)for(const e of t.publications)this._seedDeltaTracking(e),this._mapStreamBuffer.push(this._getMapUpdateContext(e));void 0!==t.offset&&(this._offset=t.offset),this._fetchStream()}else this._inflight=!1}_handleMapLiveResponse(t){if(!this._isSubscribing())return void(this._inflight=!1);if(this._inflight=!1,this._epoch&&t.epoch&&this._epoch!==t.epoch)return this._debug("map subscribe: epoch changed during live transition, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._inflight=!0,this._mapPhase=os.State,void this._fetchSnapshot();if(t.state&&t.state.length>0)for(const e of t.state)this._seedDeltaTracking(e),this._mapStateBuffer.push(this._getMapUpdateContext(e));if(t.publications&&t.publications.length>0)for(const e of t.publications){if(this._delta&&t.delta){const t=e.key||"",{newData:i,newPrevValue:o,isDelta:s,wireBytes:n,fullBytes:r}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(t));e.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=n,this._deltaBytesDecoded+=r,s?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(t):this._prevValueMap.set(t,o)}else this._delta&&e.key&&(e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,e.data));this._mapStreamBuffer.push(this._getMapUpdateContext(e))}this._offset=t.offset||0,this._epoch=t.epoch||"",this._clearSubscribingState(),t.id&&(this._id=t.id),this._recover=!0===t.recoverable,t.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,t.publish_debounce&&(this._debounceMs=t.publish_debounce),this._setState(is.Subscribed);const e=this._centrifuge._getSubscribeContext(this.channel,t);if(e.state=this._mapStateBuffer,this.emit("subscribed",e),this._resolvePromises(),!e.recovered){if(this._mapStreamBuffer.length>0){const t=new Map;for(const e of this._mapStateBuffer)t.set(e.key,e);for(const e of this._mapStreamBuffer)e.removed?t.delete(e.key):t.set(e.key,e);this._mapStateBuffer=Array.from(t.values()),this._mapStreamBuffer=[]}this.emit("sync",{entries:this._mapStateBuffer})}for(const t of this._mapStreamBuffer)this.emit("publication",t),this.emit("update",t);this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,!0===t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl)))}_handleMapSubscribeError(t){if(this._inflight=!1,this._isSubscribing())if(t.code!==Zo.timeout){if(this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,this._prevValueMap=new Map,112===t.code&&"from_scratch"===this._mapUnrecoverableStrategy)return this._debug("map subscribe: unrecoverable position, restarting from scratch"),this._offset=null,this._epoch=null,this._recover=!1,void this._scheduleResubscribe();this._subscribeError(t)}else this._centrifuge._disconnect(Yo.subscribeTimeout,"subscribe timeout",!0)}_buildMapSubscribeCommand(t,e){const i={channel:this.channel,type:this._mapPresenceType||1,phase:t};return this._token&&(i.token=this._token),this._tagsFilter&&(i.tf=this._tagsFilter),this._delta&&(i.delta=this._delta),i.flag=ts.channelCompaction,t===os.State&&(this._mapPageSize>0&&(i.limit=this._mapPageSize),e&&(i.cursor=e),this._epoch?(i.offset=this._offset,i.epoch=this._epoch):this._data&&(i.data=this._data)),t===os.Stream&&(this._mapPageSize>0&&(i.limit=this._mapPageSize),i.offset=this._offset,i.epoch=this._epoch,this._recover&&(i.recover=!0,0===this._mapStreamBuffer.length&&this._data&&(i.data=this._data))),{subscribe:i}}_getMapUpdateContext(t){const e={channel:this.channel,data:t.data,key:t.key||""};return!0===t.removed&&(e.removed=!0),void 0!==t.offset&&(e.offset=t.offset),t.info&&(e.info=this._centrifuge._getJoinLeaveContext(t.info)),t.tags&&(e.tags=t.tags),e}_getSharedPollUpdateContext(t){const e={channel:this.channel,key:t.key||"",data:t.data};return!0===t.removed&&(e.removed=!0),void 0!==t.version&&(e.version=t.version),e}}class cs extends ds{publish(t){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish("",t,!1):this._centrifuge.publish(this.channel,t)})}history(t){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,t)})}}class hs extends ds{publish(t,e){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish(t,e,!0):this._centrifuge.mapPublish(this.channel,t,e)})}remove(t){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._cancelDebounce(t),this._centrifuge.mapRemove(this.channel,t)})}}class us extends ds{track(t,e){if(0===t.length)return;let i;const o=e;if("string"==typeof t[0]){i=t.map(t=>({key:t,version:0}))}else i=t;for(const t of i){const e=this._sharedPollTrackedItems.get(t.key);(void 0===e||t.version>e)&&this._sharedPollTrackedItems.set(t.key,t.version)}if(void 0!==o)return this._sharedPollSignatures.push({keys:i.map(t=>t.key),signature:o}),void(this._isSubscribed()&&this._sendTrackRequest([{items:i,signature:o}]).catch(t=>{this._handleTrackError(t)}));if(!this._sharedPollGetSignature)return void this.emit("error",{type:"track",channel:this.channel,error:{code:Zo.sharedPollGetSignature,message:"getSignature callback required for track(keys)"}});if(!this._isSubscribed())return;const s=i.map(t=>t.key);this._sharedPollGetSignature({keys:s}).then(t=>{if(!this._isSubscribed())return;const e=new Set(t.keys),i=[];for(const t of s)e.has(t)||(this._sharedPollTrackedItems.delete(t),i.push(t),this.emit("update",{channel:this.channel,key:t,data:null,removed:!0}));i.length>0&&this._sendUntrackRequest(i).catch(t=>{this.emit("error",{type:"untrack",channel:this.channel,error:t})});const o=[];for(const e of t.keys){const t=this._sharedPollTrackedItems.get(e);void 0!==t&&o.push({key:e,version:t})}0!==o.length&&(this._sharedPollSignatures.push({keys:t.keys,signature:t.signature}),this._sendTrackRequest([{items:o,signature:t.signature}]).catch(t=>{this._handleTrackError(t)}))}).catch(t=>{this.emit("error",{type:"track",channel:this.channel,error:{code:Zo.sharedPollGetSignature,message:void 0!==t?t.toString():"getSignature failed"}})})}untrack(t){for(const e of t)this._sharedPollTrackedItems.delete(e);this._sharedPollSignatures=this._sharedPollSignatures.filter(t=>t.keys.some(t=>this._sharedPollTrackedItems.has(t))),this._isSubscribed()&&this._sendUntrackRequest(t).catch(t=>{this.emit("error",{type:"untrack",channel:this.channel,error:t})})}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}}class ps{constructor(t,e){this.endpoint=t,this.options=e,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return null!==this.options.sockjs}initialize(t,e){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=t=>{e.onError(t)},this._transport.onclose=t=>{e.onClose(t)},this._transport.onmessage=t=>{e.onMessage(t.data)}}close(){this._transport.close()}send(t){this._transport.send(t)}}class ms{constructor(t,e){this.endpoint=t,this.options=e,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return void 0!==this.options.websocket&&null!==this.options.websocket}initialize(t,e){let i="";"protobuf"===t&&(i="centrifuge-protobuf"),this._transport=""!==i?new this.options.websocket(this.endpoint,i):new this.options.websocket(this.endpoint),"protobuf"===t&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=t=>{e.onError(t)},this._transport.onclose=t=>{e.onClose(t)},this._transport.onmessage=t=>{e.onMessage(t.data)}}close(){this._transport.close()}send(t){this._transport.send(t)}}class gs{constructor(t,e){this.endpoint=t,this.options=e,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(t){if(!t.ok)throw new Error(t.status);return t}_fetchEventTarget(t,e,i){const o=new EventTarget;return(0,t.options.fetch)(e,i).then(t._handleErrors).then(e=>{o.dispatchEvent(new Event("open"));let i="",s=0,n=new Uint8Array;const r=e.body.getReader();return new t.options.readableStream({start:e=>function a(){return r.read().then(({done:r,value:l})=>{if(r)return o.dispatchEvent(new Event("close")),void e.close();try{if("json"===t._protocol)for(i+=t._utf8decoder.decode(l);s<i.length;)if("\n"===i[s]){const t=i.substring(0,s);o.dispatchEvent(new MessageEvent("message",{data:t})),i=i.substring(s+1),s=0}else++s;else{const e=new Uint8Array(n.length+l.length);for(e.set(n),e.set(l,n.length),n=e;;){const e=t.options.decoder.decodeReply(n);if(e.ok){const t=n.slice(0,e.pos);o.dispatchEvent(new MessageEvent("message",{data:t})),n=n.slice(e.pos);continue}break}}}catch(t){return o.dispatchEvent(new Event("error",{detail:t})),o.dispatchEvent(new Event("close")),void e.close()}a()}).catch(function(t){o.dispatchEvent(new Event("error",{detail:t})),o.dispatchEvent(new Event("close")),e.close()})}()})}).catch(t=>{o.dispatchEvent(new Event("error",{detail:t})),o.dispatchEvent(new Event("close"))}),o}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&"undefined"!=typeof TextDecoder&&"undefined"!=typeof AbortController&&"undefined"!=typeof EventTarget&&"undefined"!=typeof Event&&"undefined"!=typeof MessageEvent&&"undefined"!=typeof Error}initialize(t,e,i){let o,s;this._protocol=t,this._abortController=new AbortController,"json"===t?(o={Accept:"application/json","Content-Type":"application/json"},s=i):(o={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},s=i);const n={method:"POST",headers:o,body:s,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},r=this._fetchEventTarget(this,this.endpoint,n);r.addEventListener("open",()=>{e.onOpen()}),r.addEventListener("error",t=>{this._abortController.abort(),e.onError(t)}),r.addEventListener("close",()=>{this._abortController.abort(),e.onClose({code:4,reason:"connection closed"})}),r.addEventListener("message",t=>{e.onMessage(t.data)})}close(){this._abortController.abort()}send(t,e,i){let o,s;const n={session:e,node:i,data:t};"json"===this._protocol?(o={"Content-Type":"application/json"},s=JSON.stringify(n)):(o={"Content-Type":"application/octet-stream"},s=this.options.encoder.encodeEmulationRequest(n));const r={method:"POST",headers:o,body:s,mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,r)}}class fs{constructor(t,e){this.endpoint=t,this.options=e,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(t,e,i){let o;o=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),o.searchParams.append("cf_connect",i);const s=new this.options.eventsource(o.toString(),{});this._transport=s;s.onopen=function(){e.onOpen()},s.onerror=function(t){s.close(),e.onError(t),e.onClose({code:4,reason:"connection closed"})},s.onmessage=function(t){e.onMessage(t.data)},this._onClose=function(){e.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(t,e,i){const o={session:e,node:i,data:t},s={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,s)}}class vs{constructor(t,e){this.endpoint=t,this.options=e,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"webtransport"}subName(){return"webtransport"}emulation(){return!1}supported(){return void 0!==this.options.webtransport&&null!==this.options.webtransport}initialize(t,e){return Ho(this,0,void 0,function*(){let i;i=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),"protobuf"===t&&i.searchParams.append("cf_protocol","protobuf"),this._protocol=t;const o=new EventTarget;this._transport=new this.options.webtransport(i.toString()),this._transport.closed.then(()=>{e.onClose({code:4,reason:"connection closed"})}).catch(()=>{e.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch(t){return void this.close()}let s;try{s=yield this._transport.createBidirectionalStream()}catch(t){return void this.close()}this._stream=s,this._writer=this._stream.writable.getWriter(),o.addEventListener("close",()=>{e.onClose({code:4,reason:"connection closed"})}),o.addEventListener("message",t=>{e.onMessage(t.data)}),this._startReading(o),e.onOpen()})}_startReading(t){return Ho(this,0,void 0,function*(){const e=this._stream.readable.getReader();let i="",o=0,s=new Uint8Array;try{for(;;){const{done:n,value:r}=yield e.read();if(r.length>0)if("json"===this._protocol)for(i+=this._utf8decoder.decode(r);o<i.length;)if("\n"===i[o]){const e=i.substring(0,o);t.dispatchEvent(new MessageEvent("message",{data:e})),i=i.substring(o+1),o=0}else++o;else{const e=new Uint8Array(s.length+r.length);for(e.set(s),e.set(r,s.length),s=e;;){const e=this.options.decoder.decodeReply(s);if(e.ok){const i=s.slice(0,e.pos);t.dispatchEvent(new MessageEvent("message",{data:i})),s=s.slice(e.pos);continue}break}}if(n)break}}catch(e){t.dispatchEvent(new Event("close"))}})}close(){return Ho(this,0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(t){}})}send(t){return Ho(this,0,void 0,function*(){let e;e="json"===this._protocol?(new TextEncoder).encode(t+"\n"):t;try{yield this._writer.write(e)}catch(t){this.close()}})}}const bs=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class ys{constructor(t){this.a=t,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const t=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return t}getChar(){return String.fromCharCode(this.getByte())}getInt(){let t,e=0;for(;this.haveBytes()&&(t=bs[127&this.getByte()])>=0;)e=(e<<6)+t;return this.pos--,e>>>0}}class xs{constructor(){this.a=[]}toByteArray(t){return Array.isArray(t)?this.a:new Uint8Array(this.a)}putArray(t,e,i){for(let o=e;o<i;o++)this.a.push(t[o])}}function ws(t){let e=0,i=0,o=0,s=0,n=0,r=t.length;for(;r>=16;)e=e+t[n+0]|0,i=i+t[n+1]|0,o=o+t[n+2]|0,s=s+t[n+3]|0,e=e+t[n+4]|0,i=i+t[n+5]|0,o=o+t[n+6]|0,s=s+t[n+7]|0,e=e+t[n+8]|0,i=i+t[n+9]|0,o=o+t[n+10]|0,s=s+t[n+11]|0,e=e+t[n+12]|0,i=i+t[n+13]|0,o=o+t[n+14]|0,s=s+t[n+15]|0,n+=16,r-=16;for(;r>=4;)e=e+t[n+0]|0,i=i+t[n+1]|0,o=o+t[n+2]|0,s=s+t[n+3]|0,n+=4,r-=4;switch(s=((s+(o<<8)|0)+(i<<16)|0)+(e<<24)|0,r){case 3:s=s+(t[n+2]<<8)|0;case 2:s=s+(t[n+1]<<16)|0;case 1:s=s+(t[n+0]<<24)|0}return s>>>0}class _s{name(){return"json"}encodeCommands(t){return t.map(t=>JSON.stringify(t)).join("\n")}decodeReplies(t){return t.trim().split("\n").map(t=>JSON.parse(t))}applyDeltaIfNeeded(t,e){let i,o,s;if(t.delta){s=!0;const n=function(t,e){let i=0;const o=new ys(e),s=t.length,n=e.length,r=o.getInt();if("\n"!==o.getChar())throw new Error("size integer not terminated by '\\n'");const a=new xs;for(;o.haveBytes();){const e=o.getInt();let l;switch(o.getChar()){case"@":if(l=o.getInt(),o.haveBytes()&&","!==o.getChar())throw new Error("copy command not terminated by ','");if(i+=e,i>r)throw new Error("copy exceeds output file size");if(l+e>s)throw new Error("copy extends past end of input");a.putArray(t,l,l+e);break;case":":if(i+=e,i>r)throw new Error("insert command gives an output larger than predicted");if(e>n)throw new Error("insert count exceeds size of delta");a.putArray(o.a,o.pos,o.pos+e),o.pos+=e;break;case";":{const o=a.toByteArray(t);if(e!==ws(o))throw new Error("bad checksum");if(i!==r)throw new Error("generated size does not match predicted size");return o}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}(e,(new TextEncoder).encode(t.data));i=JSON.parse((new TextDecoder).decode(n)),o=n}else s=!1,i=JSON.parse(t.data),o=(new TextEncoder).encode(t.data);return{newData:i,newPrevValue:o,isDelta:s,wireBytes:t.data.length,fullBytes:o.length}}}const ks={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class Cs extends Error{constructor(t){super(t),this.name=this.constructor.name}}class Ss extends ns{constructor(t,e){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=es.Disconnected,this._transportIsOpen=!1,this._endpoint=t,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new _s,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},ks),e),this._configure(),this._debugEnabled?(this.on("state",t=>{this._debug("client state",t.oldState,"->",t.newState)}),this.on("error",t=>{this._debug("client error",t)})):this.on("error",function(){Function.prototype()})}newSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new cs(this,t,e);return this._subs[t]=i,i}newMapSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new hs(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,tagsFilter:null==e?void 0:e.tagsFilter,map:!0,mapPageSize:null==e?void 0:e.pageSize,mapUnrecoverableStrategy:null==e?void 0:e.unrecoverableStrategy});return this._subs[t]=i,i}newMapClientsSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new hs(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,tagsFilter:null==e?void 0:e.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:null==e?void 0:e.pageSize,mapUnrecoverableStrategy:null==e?void 0:e.unrecoverableStrategy});return this._subs[t]=i,i}newMapUsersSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new hs(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,tagsFilter:null==e?void 0:e.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:null==e?void 0:e.pageSize,mapUnrecoverableStrategy:null==e?void 0:e.unrecoverableStrategy});return this._subs[t]=i,i}newSharedPollSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new us(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,sharedPoll:!0,sharedPollGetSignature:null==e?void 0:e.getSignature});return this._subs[t]=i,i}getSubscription(t){return this._getSub(t)}getMapSubscription(t){return this._getSub(t)}getSharedPollSubscription(t){return this._getSub(t)}removeSubscription(t){t&&(t.state!==is.Unsubscribed&&t.unsubscribe(),this._removeSubscription(t))}removeMapSubscription(t){this.removeSubscription(t)}removeSharedPollSubscription(t){this.removeSubscription(t)}subscriptions(){return this._subs}mapSubscriptions(){const t={};for(const[e,i]of Object.entries(this._subs))"map"===i.type&&(t[e]=i);return t}sharedPollSubscriptions(){const t={};for(const[e,i]of Object.entries(this._subs))"shared_poll"===i.type&&(t[e]=i);return t}ready(t){return Ho(this,0,void 0,function*(){switch(this.state){case es.Disconnected:throw{code:Zo.clientDisconnected,message:"client disconnected"};case es.Connected:return;default:return new Promise((e,i)=>{const o={resolve:e,reject:i};t&&(o.timeout=setTimeout(()=>{i({code:Zo.timeout,message:"timeout"})},t)),this._promises[this._nextPromiseId()]=o})}})}connect(){this._isConnected()?this._debug("connect called when already connected"):this._isConnecting()?this._debug("connect called when already connecting"):(this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(Xo.disconnectCalled,"disconnect called",!1)}setToken(t){this._token=t}setData(t){this._data=t}setHeaders(t){this._config.headers=t}send(t){return Ho(this,0,void 0,function*(){const e={send:{data:t}};yield this._methodCall();if(!this._transportSendCommands([e]))throw this._createErrorObject(Zo.transportWriteError,"transport write error")})}rpc(t,e){return Ho(this,0,void 0,function*(){const i={rpc:{method:t,data:e}};yield this._methodCall();return{data:(yield this._callPromise(i,t=>t.rpc)).data}})}publish(t,e){return Ho(this,0,void 0,function*(){const i={publish:{channel:t,data:e}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapPublish(t,e,i){return Ho(this,0,void 0,function*(){const o={publish:{channel:t,type:1,key:e,data:i}};return yield this._methodCall(),yield this._callPromise(o,()=>({})),{}})}mapRemove(t,e){return Ho(this,0,void 0,function*(){const i={publish:{channel:t,type:1,key:e,removed:!0}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}history(t,e){return Ho(this,0,void 0,function*(){const i={history:this._getHistoryRequest(t,e)};yield this._methodCall();const o=yield this._callPromise(i,t=>t.history),s=[];if(o.publications)for(let e=0;e<o.publications.length;e++)s.push(this._getPublicationContext(t,o.publications[e]));return{publications:s,epoch:o.epoch||"",offset:o.offset||0}})}presence(t){return Ho(this,0,void 0,function*(){const e={presence:{channel:t}};yield this._methodCall();const i=(yield this._callPromise(e,t=>t.presence)).presence;for(const t in i)if(Object.prototype.hasOwnProperty.call(i,t)){const e=i[t],o=e.conn_info,s=e.chan_info;o&&(e.connInfo=o),s&&(e.chanInfo=s)}return{clients:i}})}presenceStats(t){return Ho(this,0,void 0,function*(){const e={presence_stats:{channel:t}};yield this._methodCall();const i=yield this._callPromise(e,t=>t.presence_stats);return{numUsers:i.num_users,numClients:i.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const t=this;Promise.resolve().then(function(){Promise.resolve().then(function(){t._batching=!1,t._flush()})})}_debug(...t){this._debugEnabled&&function(t,e){if(globalThis.console){const i=globalThis.console[t];rs(i)&&i.apply(globalThis.console,e)}}("debug",t)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new _s,this._formatOverride(),(!0===this._config.debug||"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),"string"==typeof this._endpoint);else{if(!Array.isArray(this._endpoint))throw new Error("unsupported url configuration type: only string or array of objects are supported");this._transports=this._endpoint,this._emulation=!0;for(const t in this._transports)if(this._transports.hasOwnProperty(t)){const e=this._transports[t];if(!e.endpoint||!e.transport)throw new Error("malformed transport configuration");const i=e.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(i)<0)throw new Error("unsupported transport name: "+i)}}}_setState(t){if(this.state!==t){this._reconnecting=!1;const e=this.state;return this.state=t,this.emit("state",{newState:t,oldState:e}),!0}return!1}_isDisconnected(){return this.state===es.Disconnected}_isConnecting(){return this.state===es.Connecting}_isConnected(){return this.state===es.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let t=null;null!==this._config.networkEventTarget?t=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(t=globalThis),t&&(t.addEventListener("offline",()=>{this._debug("offline event triggered"),this.state!==es.Connected&&this.state!==es.Connecting||(this._disconnect(Yo.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),t.addEventListener("online",()=>{this._debug("online event triggered"),this.state===es.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const t=as(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,t}_clearOutgoingRequests(){for(const t in this._callbacks)if(this._callbacks.hasOwnProperty(t)){const e=this._callbacks[t];clearTimeout(e.timeout);const i=e.errback;if(!i)continue;i({error:this._createErrorObject(Zo.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const e=this._subs[t];e.state===is.Subscribed&&e._setSubscribing(Qo.transportClosed,"transport closed")}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&this.emit("subscribing",{channel:t})}_handleWriteError(t){for(const e of t){const t=e.id;if(!(t in this._callbacks))continue;const i=this._callbacks[t];clearTimeout(this._callbacks[t].timeout),delete this._callbacks[t];(0,i.errback)({error:this._createErrorObject(Zo.transportWriteError,"transport write error")})}}_transportSendCommands(t){if(!t.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(t),this._session,this._node)}catch(e){return this._debug("error writing commands",e),this._handleWriteError(t),!1}return!0}_initializeTransport(){let t;null!==this._config.websocket?t=this._config.websocket:"function"!=typeof globalThis.WebSocket&&"object"!=typeof globalThis.WebSocket||(t=globalThis.WebSocket);let e=null;null!==this._config.sockjs?e=this._config.sockjs:void 0!==globalThis.SockJS&&(e=globalThis.SockJS);let i=null;null!==this._config.eventsource?i=this._config.eventsource:void 0!==globalThis.EventSource&&(i=globalThis.EventSource);let o=null;null!==this._config.fetch?o=this._config.fetch:void 0!==globalThis.fetch&&(o=globalThis.fetch);let s=null;if(null!==this._config.readableStream?s=this._config.readableStream:void 0!==globalThis.ReadableStream&&(s=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let n=0;for(;;){if(n>=this._transports.length)throw new Error("no supported transport found");const r=this._transports[this._currentTransportIndex],a=r.transport,l=r.endpoint;if("websocket"===a){if(this._debug("trying websocket transport"),this._transport=new ms(l,{websocket:t}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,n++;continue}}else if("webtransport"===a){if(this._debug("trying webtransport transport"),this._transport=new vs(l,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,n++;continue}}else if("http_stream"===a){if(this._debug("trying http_stream transport"),this._transport=new gs(l,{fetch:o,readableStream:s,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,n++;continue}}else if("sse"===a){if(this._debug("trying sse transport"),this._transport=new fs(l,{eventsource:i,fetch:o,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,n++;continue}}else{if("sockjs"!==a)throw new Error("unknown transport "+a);if(this._debug("trying sockjs"),this._transport=new ps(l,{sockjs:e,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,n++;continue}}break}}else{if(n=this._endpoint,r="http",0===n.lastIndexOf(r,0))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new ms(this._endpoint,{websocket:t}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}var n,r;const a=this,l=this._transport,d=this._nextTransportId();a._debug("id of transport",d);let c=!1;const h=[];if(this._transport.emulation()){const t=a._sendConnect(!0);h.push(t)}this._setNetworkEvents();const u=this._codec.encodeCommands(h);let p;this._transportClosed=!1,p=setTimeout(function(){l.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(p&&(clearTimeout(p),p=null),a._transportId!=d)return a._debug("open callback from non-actual transport"),void l.close();c=!0,a._debug(l.subName(),"transport open"),l.emulation()||(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(t){a._transportId==d?a._debug("transport level error",t):a._debug("error callback from non-actual transport")},onClose:function(t){if(p&&(clearTimeout(p),p=null),a._transportId!=d)return void a._debug("close callback from non-actual transport");a._debug(l.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let e="connection closed",i=!0,o=0;if(t&&"code"in t&&t.code&&(o=t.code),t&&t.reason)try{const o=JSON.parse(t.reason);e=o.reason,i=o.reconnect}catch(s){e=t.reason,(o>=3500&&o<4e3||o>=4500&&o<5e3)&&(i=!1)}o<3e3?(1009===o?(o=Xo.messageSizeLimit,e="message size limit exceeded",i=!1):(o=Yo.transportClosed,e="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!c&&a.emit("error",{type:"transport",error:{code:Zo.transportClosed,message:"transport closed"},transport:l.name()}),a._reconnecting=!1,a._disconnect(o,e,i)},onMessage:function(t){a._dataReceived(t)}},u),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(t){const e=this._constructConnectCommand(),i=this;return this._call(e,t).then(t=>{const e=t.reply.connect;i._connectResponse(e),t.next&&t.next()},t=>{i._connectError(t.error),t.next&&t.next()}),e}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting())return void this._debug("stop reconnecting: client not in connecting state");if(this._reconnecting)return void this._debug("reconnect already in progress, return from reconnect routine");if(!1===this._transportClosed)return void this._debug("waiting for transport close");this._reconnecting=!0;const t=""===this._token;if(!(this._refreshRequired||t&&null!==this._config.getToken))return void(this._config.getData?this._config.getData().then(t=>{this._isConnecting()&&(this._data=t,this._initializeTransport())}).catch(t=>this._handleGetDataError(t)):this._initializeTransport());const e=this;this._getToken().then(function(t){e._isConnecting()&&(null!=t&&null!=t?(e._token=t,e._debug("connection token refreshed"),e._config.getData?e._config.getData().then(function(t){e._isConnecting()&&(e._data=t,e._initializeTransport())}).catch(t=>e._handleGetDataError(t)):e._initializeTransport()):e._failUnauthorized())}).catch(function(t){if(!e._isConnecting())return;if(t instanceof Cs)return void e._failUnauthorized();e.emit("error",{type:"connectToken",error:{code:Zo.clientConnectToken,message:void 0!==t?t.toString():""}});const i=e._getReconnectDelay();e._debug("error on getting connection token, reconnect after "+i+" milliseconds",t),e._reconnecting=!1,e._reconnectTimeout=setTimeout(()=>{e._startReconnecting()},i)})}_handleGetDataError(t){if(t instanceof Cs)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:Zo.badConfiguration,message:(null==t?void 0:t.toString())||""}});const e=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+e+" milliseconds",t),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},e)}_connectError(t){this.state===es.Connecting&&(109===t.code&&(this._refreshRequired=!0),t.code<100||!0===t.temporary||109===t.code?(this.emit("error",{type:"connect",error:t}),this._debug("closing transport due to connect error"),this._disconnect(t.code,t.message,!0)):this._disconnect(t.code,t.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let t=!1;!this._emulation||this._transportWasOpen||this._triedAllTransports||(t=!0);let e=this._getReconnectDelay();t&&(e=0),this._debug("reconnect after "+e+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},e)}_constructConnectCommand(){const t={};this._token&&(t.token=this._token),this._data&&(t.data=this._data),this._config.name&&(t.name=this._config.name),this._config.version&&(t.version=this._config.version),Object.keys(this._config.headers).length>0&&(t.headers=this._config.headers);const e={};let i=!1;for(const t in this._serverSubs)if(this._serverSubs.hasOwnProperty(t)&&this._serverSubs[t].recoverable){i=!0;const o={recover:!0};this._serverSubs[t].offset&&(o.offset=this._serverSubs[t].offset),this._serverSubs[t].epoch&&(o.epoch=this._serverSubs[t].epoch),e[t]=o}return i&&(t.subs=e),{connect:t}}_getHistoryRequest(t,e){const i={channel:t};return void 0!==e&&(e.since&&(i.since={offset:e.since.offset},e.since.epoch&&(i.since.epoch=e.since.epoch)),void 0!==e.limit&&(i.limit=e.limit),!0===e.reverse&&(i.reverse=!0)),i}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((t,e)=>{const i=setTimeout(function(){e({code:Zo.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:i,resolve:t,reject:e}})}_callPromise(t,e){return new Promise((i,o)=>{this._call(t,!1).then(t=>{var o;const s=e(t.reply);i(s),null===(o=t.next)||void 0===o||o.call(t)},t=>{var e;o(t.error),null===(e=t.next)||void 0===e||e.call(t)})})}_dataReceived(t){this._serverPing>0&&this._waitServerPing();const e=this._codec.decodeReplies(t);this._dispatchPromise=this._dispatchPromise.then(()=>{let t;this._dispatchPromise=new Promise(e=>{t=e}),this._dispatchSynchronized(e,t)})}_dispatchSynchronized(t,e){let i=Promise.resolve();for(const e in t)t.hasOwnProperty(e)&&(i=i.then(()=>this._dispatchReply(t[e])));i=i.then(()=>{e()})}_dispatchReply(t){let e;const i=new Promise(t=>{e=t});if(null==t)return this._debug("dispatch: got undefined or null reply"),e(),i;const o=t.id;return o&&o>0?this._handleReply(t,e):t.push?this._handlePush(t.push,e):this._handleServerPing(e),i}_call(t,e){return new Promise((i,o)=>{t.id=this._nextCommandId(),this._registerCall(t.id,i,o),e||this._addCommand(t)})}_startConnecting(){this._debug("start connecting"),this._setState(es.Connecting)&&this.emit("connecting",{code:Yo.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(t,e,i){if(t===Xo.stateInvalidated){this._token="",this._refreshRequired=!0;for(const t in this._subs)this._subs.hasOwnProperty(t)&&this._subs[t]._invalidateState()}if(this._isDisconnected())return;this._transportIsOpen=!1;const o=this.state;this._reconnecting=!1;const s={code:t,reason:e};let n=!1;if(i?n=this._setState(es.Connecting):(n=this._setState(es.Disconnected),this._rejectPromises({code:Zo.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),o===es.Connecting&&this._clearReconnectTimeout(),o===es.Connected&&this._clearConnectedState(),n&&(this._isConnecting()?this.emit("connecting",s):this.emit("disconnected",s)),this._transport){this._debug("closing existing transport");const t=this._transport;this._transport=null,t.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Xo.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:Zo.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new Cs("")))}_refresh(){const t=this._client,e=this;this._getToken().then(function(i){if(t!==e._client)return;if(!i)return void e._failUnauthorized();if(e._token=i,e._debug("connection token refreshed"),!e._isConnected())return;const o={refresh:{token:e._token}};e._call(o,!1).then(t=>{const i=t.reply.refresh;e._refreshResponse(i),t.next&&t.next()},t=>{e._refreshError(t.error),t.next&&t.next()})}).catch(function(t){e._isConnected()&&(t instanceof Cs?e._failUnauthorized():(e.emit("error",{type:"refreshToken",error:{code:Zo.clientRefreshToken,message:void 0!==t?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay())))})}_refreshError(t){t.code<100||!0===t.temporary?(this.emit("error",{type:"refresh",error:t}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(t.code,t.message,!1)}_getRefreshRetryDelay(){return as(0,5e3,1e4)}_refreshResponse(t){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),t.expires&&(this._client=t.client,this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl)))}_removeSubscription(t){null!==t&&delete this._subs[t.channel]}_unsubscribe(t){if(!this._transportIsOpen)return Promise.resolve();const e={unsubscribe:{channel:t.channel}},i=this,o=new Promise((t,o)=>{this._call(e,!1).then(e=>{t(),e.next&&e.next()},e=>{t(),e.next&&e.next(),i._disconnect(Yo.unsubscribeError,"unsubscribe error",!0)})});return o}_getSub(t,e){if(e&&e>0){for(const t in this._subs)if(this._subs.hasOwnProperty(t)){const i=this._subs[t];if(i._id===e)return i}return null}const i=this._subs[t];return i||null}_isServerSub(t){return void 0!==this._serverSubs[t]}_sendSubscribeCommands(){const t=[];for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const i=this._subs[e];if(!0!==i._inflight&&i.state===is.Subscribing){const e=i._subscribe();e&&t.push(e)}}return t}_connectResponse(t){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=t.client,this._setState(es.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl))),this._session=t.session,this._node=t.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const e={client:t.client,transport:this._transport.subName()};t.data&&(e.data=t.data),this.emit("connected",e),this._resolvePromises(),this._processServerSubs(t.subs||{}),t.ping&&t.ping>0?(this._serverPing=1e3*t.ping,this._sendPong=!0===t.pong,this._waitServerPing()):this._serverPing=0}_processServerSubs(t){for(const e in t){if(!t.hasOwnProperty(e))continue;const i=t[e];this._serverSubs[e]={offset:i.offset,epoch:i.epoch,recoverable:i.recoverable||!1};const o=this._getSubscribeContext(e,i);this.emit("subscribed",o)}for(const e in t){if(!t.hasOwnProperty(e))continue;const i=t[e];if(i.recovered){const t=i.publications;if(t&&t.length>0)for(const i in t)t.hasOwnProperty(i)&&this._handlePublication(e,t[i])}}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&(t[e]||(this.emit("unsubscribed",{channel:e}),delete this._serverSubs[e]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Yo.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(t,e){const i={channel:t,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};e.recovered&&(i.recovered=!0),e.positioned&&(i.positioned=!0),e.recoverable&&(i.recoverable=!0),e.was_recovering&&(i.wasRecovering=!0);let o="";"epoch"in e&&(o=e.epoch);let s=0;return"offset"in e&&(s=e.offset),(i.positioned||i.recoverable)&&(i.streamPosition={offset:s,epoch:o}),Array.isArray(e.publications)&&e.publications.length>0&&(i.hasRecoveredPublications=!0),e.data&&(i.data=e.data),i}_handleReply(t,e){const i=t.id;if(!(i in this._callbacks))return void e();const o=this._callbacks[i];if(clearTimeout(this._callbacks[i].timeout),delete this._callbacks[i],"error"in(s=t)&&null!==s.error){const i=o.errback;if(!i)return void e();i({error:{code:t.error.code,message:t.error.message||"",temporary:t.error.temporary||!1},next:e})}else{const i=o.callback;if(!i)return;i({reply:t,next:e})}var s}_handleJoin(t,e,i){const o=this._getSub(t,i);if(o)o._handleJoin(e);else if(t&&this._isServerSub(t)){const i={channel:t,info:this._getJoinLeaveContext(e.info)};this.emit("join",i)}}_handleLeave(t,e,i){const o=this._getSub(t,i);if(o)o._handleLeave(e);else if(t&&this._isServerSub(t)){const i={channel:t,info:this._getJoinLeaveContext(e.info)};this.emit("leave",i)}}_handleUnsubscribe(t,e){const i=this._getSub(t,0);i||!t?e.code<2500?i._setUnsubscribed(e.code,e.reason,!1):(e.code===Jo.stateInvalidated&&i._invalidateState(),i._setSubscribing(e.code,e.reason)):this._isServerSub(t)&&(delete this._serverSubs[t],this.emit("unsubscribed",{channel:t}))}_handleSubscribe(t,e){this._serverSubs[t]={offset:e.offset,epoch:e.epoch,recoverable:e.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(t,e))}_handleDisconnect(t){const e=t.code;let i=!0;(e>=3500&&e<4e3||e>=4500&&e<5e3)&&(i=!1),this._disconnect(e,t.reason,i)}_getPublicationContext(t,e){const i={channel:t,data:e.data};return e.offset&&(i.offset=e.offset),e.info&&(i.info=this._getJoinLeaveContext(e.info)),e.tags&&(i.tags=e.tags),i}_getJoinLeaveContext(t){const e={client:t.client,user:t.user},i=t.conn_info;i&&(e.connInfo=i);const o=t.chan_info;return o&&(e.chanInfo=o),e}_handlePublication(t,e,i){const o=this._getSub(t,i);if(o)o._handlePublication(e);else if(t&&this._isServerSub(t)){const i=this._getPublicationContext(t,e);this.emit("publication",i),void 0!==e.offset&&(this._serverSubs[t].offset=e.offset)}}_handleMessage(t){this.emit("message",{data:t.data})}_handleServerPing(t){if(this._sendPong){const t={};this._transportSendCommands([t])}t()}_handlePush(t,e){const i=t.channel,o=t.id;t.pub?this._handlePublication(i,t.pub,o):t.message?this._handleMessage(t.message):t.join?this._handleJoin(i,t.join,o):t.leave?this._handleLeave(i,t.leave,o):t.unsubscribe?this._handleUnsubscribe(i,t.unsubscribe):t.subscribe?this._handleSubscribe(i,t.subscribe):t.disconnect&&this._handleDisconnect(t.disconnect),e()}_flush(){const t=this._commands.slice(0);this._commands=[],this._transportSendCommands(t)}_createErrorObject(t,e,i){const o={code:t,message:e};return i&&(o.temporary=!0),o}_registerCall(t,e,i){this._callbacks[t]={callback:e,errback:i,timeout:null},this._callbacks[t].timeout=setTimeout(()=>{delete this._callbacks[t],rs(i)&&i({error:this._createErrorObject(Zo.timeout,"timeout")})},this._config.timeout)}_addCommand(t){this._batching?this._commands.push(t):this._transportSendCommands([t])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].resolve(),delete this._promises[t])}_rejectPromises(t){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].reject(t),delete this._promises[e])}}Ss.SubscriptionState=is,Ss.State=es,Ss.UnauthorizedError=Cs;class $s{constructor(t){this.socket=null,this.channels=new Map,this.createSocket=t||(()=>{const t="https:"===window.location.protocol?"wss":"ws",e=new Ss(`${t}://${window.location.host}/ws/connect`);return e.connect(),e})}publish(t,e){this.socket||(this.socket=this.createSocket());const i=this.channels.get(t);return(i?i.sub.publish(e):this.socket.publish(t,e)).then(()=>{})}subscribe(t,e,i){this.socket||(this.socket=this.createSocket());let o=this.channels.get(t);o||(o={sub:this.socket.getSubscription(t)||this.socket.newSubscription(t),count:0},this.channels.set(t,o),o.sub.subscribe()),o.count++;const s=o.sub,n=t=>e(t.data);s.on("publication",n);let r=null;i&&(r=()=>i(),s.on("subscribed",r),s.state===is.Subscribed&&window.setTimeout(()=>r&&r(),0));let a=!0;return{unsubscribe:()=>{a&&(a=!1,s.off("publication",n),r&&(s.off("subscribed",r),r=null),o.count--,0===o.count&&(this.channels.delete(t),s.unsubscribe(),this.socket.removeSubscription(s)))}}}}const Ts=()=>{const t=window;return t.sockets||(t.sockets=new $s),t.sockets};Ts();const Es=(t,e,i)=>Ts().subscribe(t,e,i),As=(t,e)=>Ts().publish(t,e);let Ds=null;const Ms=[],zs=(t,e)=>((t,e,i)=>{if(Ds)return Es(t(Ds),e,i);const o={resolveChannel:t,onPublication:e,onSubscribed:i,sub:null,cancelled:!1};return Ms.push(o),{unsubscribe:()=>{o.cancelled=!0,o.sub&&(o.sub.unsubscribe(),o.sub=null)}}})(t=>`notifications:${t.org}:${t.user}`,e=>t(e),e),Ps=(t,e,i,o)=>Es(e?`history:${t}:${e}`:`history:${t}`,i,o);
741
+ `}}function Ho(t,e,i,o){return new(i||(i=Promise))(function(e,s){function n(t){try{a(o.next(t))}catch(t){s(t)}}function r(t){try{a(o.throw(t))}catch(t){s(t)}}function a(t){var o;t.done?e(t.value):(o=t.value,o instanceof i?o:new i(function(t){t(o)})).then(n,r)}a((o=o.apply(t,[])).next())})}function Vo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}i([ft({type:Boolean})],jo.prototype,"textarea",void 0),i([ft({type:String})],jo.prototype,"placeholder",void 0),i([ft({type:Boolean})],jo.prototype,"password",void 0),i([ft({type:Number})],jo.prototype,"maxlength",void 0),i([ft({type:Boolean})],jo.prototype,"clearable",void 0),i([ft({type:Boolean})],jo.prototype,"gsm",void 0),i([ft({type:String})],jo.prototype,"counter",void 0),i([ft({type:Boolean})],jo.prototype,"loading",void 0),i([ft({type:Boolean})],jo.prototype,"submitOnEnter",void 0),i([ft()],jo.prototype,"onBlur",void 0),i([ft({type:Boolean})],jo.prototype,"autogrow",void 0),i([ft({type:String})],jo.prototype,"type",void 0),i([ft({type:String})],jo.prototype,"flavor",void 0),function(t){t.DayFirst="day_first",t.MonthFirst="month_first",t.YearFirst="year_first"}(Bo||(Bo={})),function(t){t.CampaignEvent="campaign_event",t.ScheduledBroadcast="scheduled_broadcast",t.ScheduledTrigger="scheduled_trigger",t.SentBroadcast="sent_broadcast"}(Uo||(Uo={})),function(t){t.Open="open",t.Closed="closed"}(qo||(qo={})),function(t){t.Loaded="temba-loaded",t.Loading="temba-loading",t.Canceled="temba-canceled",t.CursorChanged="temba-cursor-changed",t.Refreshed="temba-refreshed",t.Selection="temba-selection",t.ButtonClicked="temba-button-clicked",t.DialogHidden="temba-dialog-hidden",t.ScrollThreshold="temba-scroll-threshold",t.ScrollThresholdBottom="temba-scroll-threshold-bottom",t.ContentChanged="temba-content-changed",t.ContextChanged="temba-context-changed",t.FetchComplete="temba-fetch-complete",t.MessageSent="temba-message-sent",t.Submitted="temba-submitted",t.Redirected="temba-redirected",t.NoPath="temba-no-path",t.StoreUpdated="temba-store-updated",t.Ready="temba-ready",t.OrderChanged="temba-order-changed",t.ColumnOrderChanged="temba-column-order-changed",t.DragStart="temba-drag-start",t.DragStop="temba-drag-stop",t.DragExternal="temba-drag-external",t.DragInternal="temba-drag-internal",t.Resized="temba-resized",t.DetailsChanged="temba-details-changed",t.Error="temba-error",t.Interrupt="temba-interrupt",t.Opened="temba-opened",t.NotificationReceived="temba-notification",t.TicketUpdated="temba-ticket-updated",t.Moved="temba-moved",t.DateRangeChanged="temba-date-range-changed",t.NodeDeleted="temba-node-deleted",t.StickyNoteDeleted="temba-sticky-note-deleted",t.ActionEditRequested="temba-action-edit-requested",t.AddActionRequested="temba-add-action-requested",t.ActionSaved="temba-action-saved",t.ActionEditCanceled="temba-action-edit-canceled",t.NodeEditRequested="temba-node-edit-requested",t.NodeSaved="temba-node-saved",t.NodeEditCancelled="temba-node-edit-cancelled",t.FollowSimulation="temba-follow-simulation",t.ContactClicked="temba-contact-clicked",t.FlowClicked="temba-flow-clicked",t.GroupClicked="temba-group-clicked",t.ShowIssue="temba-show-issue",t.SizeChanged="temba-size-changed",t.IssueSelected="temba-issue-selected",t.IssuesClosed="temba-issues-closed",t.IssuesTabClicked="temba-issues-tab-clicked",t.RevisionViewed="temba-revision-viewed",t.RevisionCancelled="temba-revision-cancelled",t.RevisionReverted="temba-revision-reverted",t.RevisionsClosed="temba-revisions-closed",t.RowClick="temba-row-click",t.SelectionChange="temba-selection-change",t.BulkAction="temba-bulk-action",t.LabelCreate="temba-label-create",t.HistoryChange="temba-history-change"}(Wo||(Wo={})),"function"==typeof SuppressedError&&SuppressedError;var Go,Ko={exports:{}};var Zo,Yo,Xo,Qo,Jo,ts,es,is,os,ss=function(){if(Go)return Ko.exports;Go=1;var t,e="object"==typeof Reflect?Reflect:null,i=e&&"function"==typeof e.apply?e.apply:function(t,e,i){return Function.prototype.apply.call(t,e,i)};t=e&&"function"==typeof e.ownKeys?e.ownKeys:Object.getOwnPropertySymbols?function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:function(t){return Object.getOwnPropertyNames(t)};var o=Number.isNaN||function(t){return t!=t};function s(){s.init.call(this)}Ko.exports=s,Ko.exports.once=function(t,e){return new Promise(function(i,o){function s(i){t.removeListener(e,n),o(i)}function n(){"function"==typeof t.removeListener&&t.removeListener("error",s),i([].slice.call(arguments))}m(t,e,n,{once:!0}),"error"!==e&&function(t,e,i){"function"==typeof t.on&&m(t,"error",e,i)}(t,s,{once:!0})})},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var n=10;function r(t){if("function"!=typeof t)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}function a(t){return void 0===t._maxListeners?s.defaultMaxListeners:t._maxListeners}function l(t,e,i,o){var s,n,l,d;if(r(i),void 0===(n=t._events)?(n=t._events=Object.create(null),t._eventsCount=0):(void 0!==n.newListener&&(t.emit("newListener",e,i.listener?i.listener:i),n=t._events),l=n[e]),void 0===l)l=n[e]=i,++t._eventsCount;else if("function"==typeof l?l=n[e]=o?[i,l]:[l,i]:o?l.unshift(i):l.push(i),(s=a(t))>0&&l.length>s&&!l.warned){l.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+l.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=l.length,d=c,console&&console.warn&&console.warn(d)}return t}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function c(t,e,i){var o={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},s=d.bind(o);return s.listener=i,o.wrapFn=s,s}function h(t,e,i){var o=t._events;if(void 0===o)return[];var s=o[e];return void 0===s?[]:"function"==typeof s?i?[s.listener||s]:[s]:i?function(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}(s):p(s,s.length)}function u(t){var e=this._events;if(void 0!==e){var i=e[t];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(t,e){for(var i=new Array(e),o=0;o<e;++o)i[o]=t[o];return i}function m(t,e,i,o){if("function"==typeof t.on)o.once?t.once(e,i):t.on(e,i);else{if("function"!=typeof t.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t);t.addEventListener(e,function s(n){o.once&&t.removeEventListener(e,s),i(n)})}}return Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return n},set:function(t){if("number"!=typeof t||t<0||o(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");n=t}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||o(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this},s.prototype.getMaxListeners=function(){return a(this)},s.prototype.emit=function(t){for(var e=[],o=1;o<arguments.length;o++)e.push(arguments[o]);var s="error"===t,n=this._events;if(void 0!==n)s=s&&void 0===n.error;else if(!s)return!1;if(s){var r;if(e.length>0&&(r=e[0]),r instanceof Error)throw r;var a=new Error("Unhandled error."+(r?" ("+r.message+")":""));throw a.context=r,a}var l=n[t];if(void 0===l)return!1;if("function"==typeof l)i(l,this,e);else{var d=l.length,c=p(l,d);for(o=0;o<d;++o)i(c[o],this,e)}return!0},s.prototype.addListener=function(t,e){return l(this,t,e,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(t,e){return l(this,t,e,!0)},s.prototype.once=function(t,e){return r(e),this.on(t,c(this,t,e)),this},s.prototype.prependOnceListener=function(t,e){return r(e),this.prependListener(t,c(this,t,e)),this},s.prototype.removeListener=function(t,e){var i,o,s,n,a;if(r(e),void 0===(o=this._events))return this;if(void 0===(i=o[t]))return this;if(i===e||i.listener===e)0===--this._eventsCount?this._events=Object.create(null):(delete o[t],o.removeListener&&this.emit("removeListener",t,i.listener||e));else if("function"!=typeof i){for(s=-1,n=i.length-1;n>=0;n--)if(i[n]===e||i[n].listener===e){a=i[n].listener,s=n;break}if(s<0)return this;0===s?i.shift():function(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}(i,s),1===i.length&&(o[t]=i[0]),void 0!==o.removeListener&&this.emit("removeListener",t,a||e)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(t){var e,i,o;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[t]&&(0===--this._eventsCount?this._events=Object.create(null):delete i[t]),this;if(0===arguments.length){var s,n=Object.keys(i);for(o=0;o<n.length;++o)"removeListener"!==(s=n[o])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(e=i[t]))this.removeListener(t,e);else if(void 0!==e)for(o=e.length-1;o>=0;o--)this.removeListener(t,e[o]);return this},s.prototype.listeners=function(t){return h(this,t,!0)},s.prototype.rawListeners=function(t){return h(this,t,!1)},s.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):u.call(t,e)},s.prototype.listenerCount=u,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]},Ko.exports}(),ns=Vo(ss);function rs(t){return null!=t&&"function"==typeof t}function as(t,e,i){t>31&&(t=31);const o=function(t,e){return Math.floor(Math.random()*(e-t+1)+t)}(0,Math.min(i,e*Math.pow(2,t)));return Math.min(i,e+o)}function ls(t){return Math.min(1e3*t,2147483647)}!function(t){t[t.timeout=1]="timeout",t[t.transportClosed=2]="transportClosed",t[t.clientDisconnected=3]="clientDisconnected",t[t.clientClosed=4]="clientClosed",t[t.clientConnectToken=5]="clientConnectToken",t[t.clientRefreshToken=6]="clientRefreshToken",t[t.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",t[t.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",t[t.subscriptionRefreshToken=9]="subscriptionRefreshToken",t[t.transportWriteError=10]="transportWriteError",t[t.connectionClosed=11]="connectionClosed",t[t.badConfiguration=12]="badConfiguration",t[t.subscriptionGetState=13]="subscriptionGetState",t[t.sharedPollGetSignature=14]="sharedPollGetSignature"}(Zo||(Zo={})),function(t){t[t.connectCalled=0]="connectCalled",t[t.transportClosed=1]="transportClosed",t[t.noPing=2]="noPing",t[t.subscribeTimeout=3]="subscribeTimeout",t[t.unsubscribeError=4]="unsubscribeError"}(Yo||(Yo={})),function(t){t[t.disconnectCalled=0]="disconnectCalled",t[t.unauthorized=1]="unauthorized",t[t.badProtocol=2]="badProtocol",t[t.messageSizeLimit=3]="messageSizeLimit",t[t.stateInvalidated=3014]="stateInvalidated"}(Xo||(Xo={})),function(t){t[t.subscribeCalled=0]="subscribeCalled",t[t.transportClosed=1]="transportClosed"}(Qo||(Qo={})),function(t){t[t.unsubscribeCalled=0]="unsubscribeCalled",t[t.unauthorized=1]="unauthorized",t[t.clientClosed=2]="clientClosed",t[t.stateInvalidated=2502]="stateInvalidated"}(Jo||(Jo={})),function(t){t[t.channelCompaction=1]="channelCompaction",t[t.rejectUnrecovered=2]="rejectUnrecovered"}(ts||(ts={})),function(t){t.Disconnected="disconnected",t.Connecting="connecting",t.Connected="connected"}(es||(es={})),function(t){t.Unsubscribed="unsubscribed",t.Subscribing="subscribing",t.Subscribed="subscribed"}(is||(is={})),function(t){t[t.Live=0]="Live",t[t.Stream=1]="Stream",t[t.State=2]="State"}(os||(os={}));class ds extends ns{constructor(t,e,i){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this._getState=null,this._map=!1,this._mapPresenceType=1,this._mapPhase=null,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPageSize=0,this._mapUnrecoverableStrategy="from_scratch",this._debounceMs=0,this._debouncePending=new Map,this._sharedPoll=!1,this._sharedPollEpoch="",this._sharedPollTrackedItems=new Map,this._sharedPollGetSignature=null,this._sharedPollSignatureRefreshTimeout=null,this._sharedPollSignatureRefreshAttempts=0,this._sharedPollTrackRetryTimeout=null,this._sharedPollTrackRetryAttempts=0,this._sharedPollReplayRetryTimeout=null,this._sharedPollReplayRetryAttempts=0,this._sharedPollSignatures=[],this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1,this.channel=e,this.state=is.Unsubscribed,this._centrifuge=t,this._token="",this._getToken=null,this._data=null,this._getData=null,this._recover=!1,this._offset=null,this._epoch=null,this._id=0,this._recoverable=!1,this._positioned=!1,this._joinLeave=!1,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=!1,this._refreshTimeout=null,this._delta="",this._delta_negotiated=!1,this._tagsFilter=null,this._prevValueMap=new Map,this._unsubPromise=Promise.resolve(),this._deltaNumPubs=0,this._deltaNumFull=0,this._deltaNumDelta=0,this._deltaBytesReceived=0,this._deltaBytesDecoded=0,this._setOptions(i),this.type=this._sharedPoll?"shared_poll":this._map?"map":"stream",this._centrifuge._debugEnabled?(this.on("state",t=>{this._debug("subscription state",e,t.oldState,"->",t.newState)}),this.on("error",t=>{this._debug("subscription error",e,t)})):this.on("error",function(){Function.prototype()})}ready(t){return this.state===is.Unsubscribed?Promise.reject({code:Zo.subscriptionUnsubscribed,message:this.state}):this.state===is.Subscribed?Promise.resolve():new Promise((e,i)=>{const o={resolve:e,reject:i};t&&(o.timeout=setTimeout(function(){i({code:Zo.timeout,message:"timeout"})},t)),this._promises[this._nextPromiseId()]=o})}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(Qo.subscribeCalled,"subscribe called"))}unsubscribe(){this._unsubPromise=this._setUnsubscribed(Jo.unsubscribeCalled,"unsubscribe called",!0)}_debouncedPublish(t,e,i){const o=this._debouncePending.get(t);if(o)return o.data=e,o.dirty=!0,Promise.resolve({});const s={data:e,dirty:!1,timer:null};s.timer=setTimeout(()=>{const e=this._debouncePending.get(t);if(!e||!e.dirty)return void this._debouncePending.delete(t);e.dirty=!1;const o=e.data;(i?this._centrifuge.mapPublish(this.channel,t,o):this._centrifuge.publish(this.channel,o)).catch(()=>{}),e.timer=setTimeout(()=>{const e=this._debouncePending.get(t);e&&e.dirty?(this._debouncePending.delete(t),this._debouncedPublish(t,e.data,i)):this._debouncePending.delete(t)},this._debounceMs)},this._debounceMs),this._debouncePending.set(t,s);return i?this._centrifuge.mapPublish(this.channel,t,e):this._centrifuge.publish(this.channel,e)}_cancelDebounce(t){const e=this._debouncePending.get(t);e&&(clearTimeout(e.timer),this._debouncePending.delete(t))}_cancelAllDebounce(){for(const[,t]of this._debouncePending)clearTimeout(t.timer);this._debouncePending.clear()}presence(){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presence(this.channel)})}presenceStats(){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.presenceStats(this.channel)})}setTagsFilter(t){if(t&&this._delta)throw new Error("cannot use delta and tagsFilter together");this._tagsFilter=t,this._map&&(this._recover=!1,this._offset=null,this._epoch=null)}setData(t){this._data=t}deltaStats(){const t=this._deltaBytesDecoded;return{numPublications:this._deltaNumPubs,numFullPayloads:this._deltaNumFull,numDeltaPayloads:this._deltaNumDelta,bytesReceived:this._deltaBytesReceived,bytesDecoded:t,compressionRatio:t>0?1-this._deltaBytesReceived/t:0}}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:Zo.subscriptionUnsubscribed,message:this.state}):new Promise((t,e)=>{const i=this._centrifuge._config.timeout,o=setTimeout(()=>{e({code:Zo.timeout,message:"timeout"})},i);this._promises[this._nextPromiseId()]={timeout:o,resolve:t,reject:e}})}_nextPromiseId(){return++this._promiseId}_needRecover(){return!0===this._recover}_isUnsubscribed(){return this.state===is.Unsubscribed}_isSubscribing(){return this.state===is.Subscribing}_isSubscribed(){return this.state===is.Subscribed}_setState(t){if(this.state!==t){const e=this.state;return this.state=t,this.emit("state",{newState:t,oldState:e,channel:this.channel}),!0}return!1}_usesToken(){return""!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout(),this._clearSharedPollSignatureRefresh(),this._clearSharedPollTrackRetry(),this._clearSharedPollReplayRetry(),this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!1}_invalidateState(){this._token="",this._prevValueMap=new Map,this._map?(this._offset=null,this._epoch=null,this._recover=!1,this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._mapPhase=null):(this._offset=0,this._epoch="_")}_setSubscribed(t){if(!this._isSubscribing())return;if(this._clearSubscribingState(),t.id&&(this._id=t.id),t.recoverable&&(this._recover=!0,this._offset=t.offset||0,this._epoch=t.epoch||""),t.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,t.publish_debounce&&(this._debounceMs=t.publish_debounce),this._sharedPoll){const e=t.epoch||"";if(""!==this._sharedPollEpoch&&this._sharedPollEpoch!==e)for(const t of this._sharedPollTrackedItems.keys())this._sharedPollTrackedItems.set(t,0);this._sharedPollEpoch=e}this._setState(is.Subscribed);const e=this._centrifuge._getSubscribeContext(this.channel,t);this.emit("subscribed",e),this._resolvePromises();const i=t.publications;if(i&&i.length>0)for(const t in i)i.hasOwnProperty(t)&&this._handlePublication(i[t]);!0===t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl)))}_setSubscribing(t,e){return Ho(this,0,void 0,function*(){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._id=0,this._setState(is.Subscribing)&&this.emit("subscribing",{channel:this.channel,code:t,reason:e}),this._centrifuge._transport&&this._centrifuge._transport.emulation()&&(yield this._unsubPromise),this._isSubscribing()&&this._subscribe())})}_subscribe(){return this._debug("subscribing on",this.channel),this._isTransportOpen()?this._inflight?null:(this._inflight=!0,this._map?(this._mapSubscribe(),null):this._getState&&null===this._offset?(this._loadStreamState(),null):this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():(this._getSubscriptionToken().then(t=>this._handleTokenResponse(t)).catch(t=>this._handleTokenError(t)),null)):(this._debug("delay subscribe on",this.channel,"till connected"),null)}_isTransportOpen(){return this._centrifuge._transportIsOpen}_canSubscribeWithoutGettingToken(){return!this._usesToken()||!!this._token}_subscribeWithoutToken(){return this._getData?(this._getDataAndSubscribe(this._token),null):this._sendSubscribe(this._token)}_loadStreamState(){this._isSubscribing()?this._getState().then(t=>{this._isSubscribing()?(this._offset=t.offset,this._epoch=t.epoch,this._recover=!0,this._canSubscribeWithoutGettingToken()?this._subscribeWithoutToken():this._getSubscriptionToken().then(t=>this._handleTokenResponse(t)).catch(t=>this._handleTokenError(t))):this._inflight=!1}).catch(t=>{this._isSubscribing()?(this._inflight=!1,this._subscribeError({code:Zo.subscriptionGetState,message:(null==t?void 0:t.toString())||"getState failed",temporary:!0})):this._inflight=!1}):this._inflight=!1}_getDataAndSubscribe(t){this._getData?this._getData({channel:this.channel}).then(e=>{this._isSubscribing()?(this._data=e,this._sendSubscribe(t)):this._inflight=!1}).catch(t=>this._handleGetDataError(t)):this._inflight=!1}_handleGetDataError(t){if(this._isSubscribing()){if(t instanceof Cs)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeData",channel:this.channel,error:{code:Zo.badConfiguration,message:(null==t?void 0:t.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_handleTokenResponse(t){if(this._isSubscribing()){if(!t)return this._inflight=!1,void this._failUnauthorized();this._token=t,this._getData?this._getDataAndSubscribe(t):this._sendSubscribe(t)}else this._inflight=!1}_handleTokenError(t){if(this._isSubscribing()){if(t instanceof Cs)return this._inflight=!1,void this._failUnauthorized();this.emit("error",{type:"subscribeToken",channel:this.channel,error:{code:Zo.subscriptionSubscribeToken,message:(null==t?void 0:t.toString())||""}}),this._inflight=!1,this._scheduleResubscribe()}else this._inflight=!1}_sendSubscribe(t){if(!this._isTransportOpen())return this._inflight=!1,null;const e=this._buildSubscribeCommand(t);return this._centrifuge._call(e).then(t=>{this._inflight=!1;const e=t.reply.subscribe;this._handleSubscribeResponse(e),t.next&&t.next()},t=>{this._inflight=!1,this._handleSubscribeError(t.error),t.next&&t.next()}),e}_buildSubscribeCommand(t){const e={channel:this.channel};if(t&&(e.token=t),this._data&&(e.data=this._data),this._sharedPoll)return e.type=4,this._delta&&(e.delta=this._delta),{subscribe:e};if(this._positioned&&(e.positioned=!0),this._recoverable&&(e.recoverable=!0),this._joinLeave&&(e.join_leave=!0),e.flag=ts.channelCompaction,this._getState&&(e.flag|=ts.rejectUnrecovered),this._needRecover()){e.recover=!0;const t=this._getOffset();t&&(e.offset=t);const i=this._getEpoch();i&&(e.epoch=i)}return this._delta&&(e.delta=this._delta),this._tagsFilter&&(e.tf=this._tagsFilter),{subscribe:e}}_debug(...t){this._centrifuge._debug(...t)}_handleSubscribeError(t){if(this._isSubscribing()){if(t.code!==Zo.timeout)return 112===t.code&&this._getState?(this._offset=null,this._epoch=null,this._recover=!1,this._prevValueMap=new Map,void this._scheduleResubscribe()):void this._subscribeError(t);this._centrifuge._disconnect(Yo.subscribeTimeout,"subscribe timeout",!0)}}_handleSubscribeResponse(t){this._isSubscribing()&&(this._setSubscribed(t),this._sharedPoll&&this._sharedPollReplayTrack())}_setUnsubscribed(t,e,i){if(this._isUnsubscribed())return Promise.resolve();let o=Promise.resolve();return this._isSubscribed()?(i&&(o=this._centrifuge._unsubscribe(this)),this._clearSubscribedState()):this._isSubscribing()&&(this._inflight&&i&&(o=this._centrifuge._unsubscribe(this)),this._clearSubscribingState()),this._inflight=!1,this._id=0,this._sharedPollEpoch="",this._sharedPollSignatures=[],this._sharedPollTrackedItems.clear(),this._sharedPollSignatureRefreshInFlight=!1,this._sharedPollSignatureRefreshTargetMs=null,this._cancelAllDebounce(),this._setState(is.Unsubscribed)&&this.emit("unsubscribed",{channel:this.channel,code:t,reason:e}),this._rejectPromises({code:Zo.subscriptionUnsubscribed,message:this.state}),o}_handlePublication(t){if(this._delta&&this._delta_negotiated){const e=(this._map||this._sharedPoll)&&t.key||"",{newData:i,newPrevValue:o,isDelta:s,wireBytes:n,fullBytes:r}=this._centrifuge._codec.applyDeltaIfNeeded(t,this._prevValueMap.get(e));t.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=n,this._deltaBytesDecoded+=r,s?this._deltaNumDelta++:this._deltaNumFull++,t.removed?this._prevValueMap.delete(e):this._prevValueMap.set(e,o)}let e;if(this._sharedPoll){if(t.key&&!this._sharedPollTrackedItems.has(t.key))return;t.key&&(t.removed?this._sharedPollTrackedItems.delete(t.key):t.version&&this._sharedPollTrackedItems.set(t.key,t.version)),e=this._getSharedPollUpdateContext(t)}else e=this._map?this._getMapUpdateContext(t):this._centrifuge._getPublicationContext(this.channel,t);this.emit("publication",e),(this._map||this._sharedPoll)&&this.emit("update",e),t.offset&&(this._offset=t.offset),t.epoch&&(this._epoch=t.epoch)}_seedDeltaTracking(t){if(this._delta&&t.key)if("string"==typeof t.data){const e=t.data;t.removed?this._prevValueMap.delete(t.key):this._prevValueMap.set(t.key,(new TextEncoder).encode(e));const i=e.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=i,this._deltaBytesDecoded+=i,t.data=JSON.parse(e)}else if(t.data instanceof Uint8Array){t.removed?this._prevValueMap.delete(t.key):this._prevValueMap.set(t.key,t.data);const e=t.data.length;this._deltaNumPubs++,this._deltaNumFull++,this._deltaBytesReceived+=e,this._deltaBytesDecoded+=e}}_handleJoin(t){const e=this._centrifuge._getJoinLeaveContext(t.info);this.emit("join",{channel:this.channel,info:e})}_handleLeave(t){const e=this._centrifuge._getJoinLeaveContext(t.info);this.emit("leave",{channel:this.channel,info:e})}_resolvePromises(){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].resolve(),delete this._promises[t])}_rejectPromises(t){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].reject(t),delete this._promises[e])}_scheduleResubscribe(){if(!this._isSubscribing())return void this._debug("not in subscribing state, skip resubscribe scheduling",this.channel);const t=this,e=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout(function(){t._isSubscribing()&&t._subscribe()},e),this._debug("resubscribe scheduled after "+e,this.channel)}_subscribeError(t){if(this._isSubscribing())if(t.code<100||109===t.code||!0===t.temporary){109===t.code&&(this._token="");const e={channel:this.channel,type:"subscribe",error:t};this._centrifuge.state===es.Connected&&this.emit("error",e),this._scheduleResubscribe()}else this._setUnsubscribed(t.code,t.message,!1)}_getResubscribeDelay(){const t=as(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,t}_setOptions(t){if(t){if(t.since&&(this._offset=t.since.offset||0,this._epoch=t.since.epoch||"",this._recover=!0),t.data&&(this._data=t.data),t.getData&&(this._getData=t.getData),void 0!==t.minResubscribeDelay&&(this._minResubscribeDelay=t.minResubscribeDelay),void 0!==t.maxResubscribeDelay&&(this._maxResubscribeDelay=t.maxResubscribeDelay),t.token&&(this._token=t.token),t.getToken&&(this._getToken=t.getToken),!0===t.positioned&&(this._positioned=!0),!0===t.recoverable&&(this._recoverable=!0),!0===t.joinLeave&&(this._joinLeave=!0),t.delta){if("fossil"!==t.delta)throw new Error("unsupported delta format");this._delta=t.delta}if(t.tagsFilter&&(this._tagsFilter=t.tagsFilter),this._tagsFilter&&this._delta)throw new Error("cannot use delta and tagsFilter together");t.getState&&(this._getState=t.getState,this._recover=!0),!0===t.map&&(this._map=!0),void 0!==t.mapPageSize&&(this._mapPageSize=t.mapPageSize),void 0!==t.mapPresenceType&&(this._mapPresenceType=t.mapPresenceType,this._map=!0),t.mapUnrecoverableStrategy&&(this._mapUnrecoverableStrategy=t.mapUnrecoverableStrategy),!0===t.sharedPoll&&(this._sharedPoll=!0),t.sharedPollGetSignature&&(this._sharedPollGetSignature=t.sharedPollGetSignature)}}_getOffset(){const t=this._offset;return null!==t?t:0}_getEpoch(){const t=this._epoch;return null!==t?t:""}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._debug("get subscription token for channel",this.channel);const t={channel:this.channel},e=this._getToken;return null===e?(this.emit("error",{type:"configuration",channel:this.channel,error:{code:Zo.badConfiguration,message:"provide a function to get channel subscription token"}}),Promise.reject(new Cs(""))):e(t)}_refresh(){this._clearRefreshTimeout();const t=this;this._getSubscriptionToken().then(function(e){if(!t._isSubscribed())return;if(!e)return void t._failUnauthorized();t._token=e;const i={sub_refresh:{channel:t.channel,token:e}};t._centrifuge._call(i).then(e=>{const i=e.reply.sub_refresh;t._refreshResponse(i),e.next&&e.next()},e=>{t._refreshError(e.error),e.next&&e.next()})}).catch(function(e){e instanceof Cs?t._failUnauthorized():(t.emit("error",{type:"refreshToken",channel:t.channel,error:{code:Zo.subscriptionRefreshToken,message:void 0!==e?e.toString():""}}),t._refreshTimeout=setTimeout(()=>t._refresh(),t._getRefreshRetryDelay()))})}_refreshResponse(t){this._isSubscribed()&&(this._debug("subscription token refreshed, channel",this.channel),this._clearRefreshTimeout(),!0===t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl))))}_refreshError(t){this._isSubscribed()&&(t.code<100||!0===t.temporary?(this.emit("error",{type:"refresh",channel:this.channel,error:t}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._setUnsubscribed(t.code,t.message,!0))}_getRefreshRetryDelay(){return as(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(Jo.unauthorized,"unauthorized",!0)}_sendTrackRequest(t,e){if(0===t.length)return Promise.resolve();const i=[];let o=[],s=100;if(e&&e.length>0)for(const t of e)s+=t.length+4;for(const e of t){let t=100;for(const i of e.items)t+=i.key.length+16;o.length>0&&s+t>6e4&&(i.push(o),o=[],s=100),o.push(e),s+=t}o.length>0&&i.push(o);const n=(t,e)=>new Promise((i,o)=>{const s={channel:this.channel,type:1,track:t.map(t=>({signature:t.signature,items:t.items.map(t=>t.version>0?t:{key:t.key})}))};e&&e.length>0&&(s.untrack=e);const n={sub_refresh:s};this._centrifuge._call(n).then(t=>{this._handleTrackResponse(t.reply.sub_refresh),t.next&&t.next(),i()},t=>{t.next&&t.next(),o(t.error)})});return i.reduce((t,i,o)=>t.then(()=>n(i,0===o?e:void 0)),Promise.resolve())}_sendUntrackRequest(t){return new Promise((e,i)=>{const o={sub_refresh:{channel:this.channel,type:2,untrack:t}};this._centrifuge._call(o).then(t=>{t.next&&t.next(),e()},t=>{t.next&&t.next(),i(t.error)})})}_handleTrackResponse(t){if(this._clearSharedPollTrackRetry(),t&&t.items&&t.items.length>0)for(const e of t.items)this._handlePublication(e);if(t&&!0===t.expires&&t.ttl>0){const e=Date.now()+1e3*t.ttl;this._maybeScheduleSharedPollSignatureRefresh(e)}}_maybeScheduleSharedPollSignatureRefresh(t){if(null===t)return this._sharedPollSignatureRefreshTargetMs=null,void this._clearSharedPollSignatureRefresh();this._isSubscribed()&&(null!==this._sharedPollSignatureRefreshTargetMs&&t>=this._sharedPollSignatureRefreshTargetMs||(this._sharedPollSignatureRefreshTargetMs=t,this._clearSharedPollSignatureRefresh(),this._sharedPollSignatureRefreshTimeout=setTimeout(()=>this._sharedPollRefreshSignature(),Math.max(0,t-Date.now()))))}_clearSharedPollSignatureRefresh(){null!==this._sharedPollSignatureRefreshTimeout&&(clearTimeout(this._sharedPollSignatureRefreshTimeout),this._sharedPollSignatureRefreshTimeout=null),this._sharedPollSignatureRefreshAttempts=0}_clearSharedPollTrackRetry(){null!==this._sharedPollTrackRetryTimeout&&(clearTimeout(this._sharedPollTrackRetryTimeout),this._sharedPollTrackRetryTimeout=null),this._sharedPollTrackRetryAttempts=0}_clearSharedPollReplayRetry(){null!==this._sharedPollReplayRetryTimeout&&(clearTimeout(this._sharedPollReplayRetryTimeout),this._sharedPollReplayRetryTimeout=null),this._sharedPollReplayRetryAttempts=0}_handleTrackError(t){this._isSubscribed()&&(this.emit("error",{type:"track",channel:this.channel,error:t}),109!==t.code?(t.code<100||!0===t.temporary)&&(this._sharedPollTrackRetryTimeout=setTimeout(()=>this._sharedPollReplayTrack(),as(this._sharedPollTrackRetryAttempts++,1e3,15e3))):this._sharedPollRefreshSignature())}_sharedPollRefreshSignature(){if(this._clearSharedPollSignatureRefresh(),!this._isSubscribed())return;if(!this._sharedPollGetSignature)return;if(0===this._sharedPollTrackedItems.size)return;if(this._sharedPollSignatureRefreshInFlight)return;this._sharedPollSignatureRefreshTargetMs=null,this._sharedPollSignatureRefreshInFlight=!0;const t=Array.from(this._sharedPollTrackedItems.keys()),e=this;this._sharedPollGetSignature({keys:t}).then(i=>{if(e._sharedPollSignatureRefreshInFlight=!1,!e._isSubscribed())return;e._sharedPollSignatureRefreshAttempts=0;const o=new Set(i.keys),s=[];for(const i of t)o.has(i)||(e._sharedPollTrackedItems.delete(i),s.push(i),e.emit("update",{channel:e.channel,key:i,data:null,removed:!0}));s.length>0&&e._sendUntrackRequest(s).catch(t=>{e.emit("error",{type:"untrack",channel:e.channel,error:t})});const n=[];for(const t of i.keys){const i=e._sharedPollTrackedItems.get(t);void 0!==i&&n.push({key:t,version:i})}const r=new Set(i.keys),a=e._sharedPollSignatures.filter(t=>t.keys.some(t=>e._sharedPollTrackedItems.has(t)&&!r.has(t)));e._sharedPollSignatures=n.length>0?[{keys:i.keys,signature:i.signature},...a]:a,0!==n.length&&e._sendTrackRequest([{items:n,signature:i.signature}]).catch(t=>{e._handleTrackError(t)})}).catch(t=>{e._sharedPollSignatureRefreshInFlight=!1,e.emit("error",{type:"signatureRefresh",channel:e.channel,error:{code:Zo.sharedPollGetSignature,message:void 0!==t?t.toString():""}}),e._sharedPollSignatureRefreshTimeout=setTimeout(()=>e._sharedPollRefreshSignature(),as(e._sharedPollSignatureRefreshAttempts++,5e3,3e4))})}_sharedPollReplayTrack(){if(!this._isSubscribed())return;if(0===this._sharedPollTrackedItems.size&&0===this._sharedPollSignatures.length)return;const t=new Set,e=[],i=[];for(const o of this._sharedPollSignatures){const s=o.keys.map(t=>{var e;return{key:t,version:null!==(e=this._sharedPollTrackedItems.get(t))&&void 0!==e?e:0}});e.push({items:s,signature:o.signature});for(const e of o.keys)this._sharedPollTrackedItems.has(e)?t.add(e):i.push(e)}e.length>0&&this._sendTrackRequest(e,i).catch(t=>{this._handleTrackError(t)});const o=[];for(const e of this._sharedPollTrackedItems.keys())t.has(e)||o.push(e);if(0===o.length)return;if(!this._sharedPollGetSignature)return void this.emit("error",{type:"track",channel:this.channel,error:{code:Zo.sharedPollGetSignature,message:"getSignature callback required for tracked keys without an explicit signature"}});const s=this;this._sharedPollGetSignature({keys:o}).then(t=>{if(!s._isSubscribed())return;s._clearSharedPollReplayRetry();const e=new Set(t.keys),i=[];for(const t of o)e.has(t)||(s._sharedPollTrackedItems.delete(t),i.push(t),s.emit("update",{channel:s.channel,key:t,data:null,removed:!0}));i.length>0&&s._sendUntrackRequest(i).catch(t=>{s.emit("error",{type:"untrack",channel:s.channel,error:t})});const n=[];for(const e of t.keys){const t=s._sharedPollTrackedItems.get(e);void 0!==t&&n.push({key:e,version:t})}0!==n.length&&(s._sharedPollSignatures.push({keys:t.keys,signature:t.signature}),s._sendTrackRequest([{items:n,signature:t.signature}]).catch(t=>{s._handleTrackError(t)}))}).catch(t=>{s.emit("error",{type:"signatureRefresh",channel:s.channel,error:{code:Zo.sharedPollGetSignature,message:void 0!==t?t.toString():""}}),s._sharedPollReplayRetryTimeout=setTimeout(()=>s._sharedPollReplayTrack(),as(s._sharedPollReplayRetryAttempts++,5e3,3e4))})}_mapSubscribe(){if(this._debug("starting map subscribe on",this.channel),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapCursor="",this._recover&&null!==this._offset&&null!==this._epoch||(this._prevValueMap=new Map),this._mapPhase=os.State,this._recover&&null!==this._offset&&null!==this._epoch)return this._debug("map subscribe: recovering from position, skipping to stream phase"),this._mapPhase=os.Stream,void this._fetchStream();this._canSubscribeWithoutGettingToken()?this._fetchSnapshot():this._getSubscriptionToken().then(t=>{if(this._isSubscribing()){if(!t)return this._inflight=!1,void this._failUnauthorized();this._token=t,this._fetchSnapshot()}else this._inflight=!1}).catch(t=>this._handleTokenError(t))}_fetchSnapshot(t){if(!this._isSubscribing()||!this._isTransportOpen())return void(this._inflight=!1);const e=this._buildMapSubscribeCommand(os.State,t);this._debug("map subscribe: fetching snapshot page",t?`cursor=${t}`:"initial"),this._centrifuge._call(e).then(t=>{const e=t.reply.subscribe;this._handleMapStateResponse(e),t.next&&t.next()},t=>{this._handleMapSubscribeError(t.error),t.next&&t.next()})}_handleMapStateResponse(t){if(this._isSubscribing()){if(!t.phase)return this._debug("map subscribe: server forced LIVE transition during state pagination"),void this._handleMapLiveResponse(t);if(!this._epoch&&t.epoch&&(this._epoch=t.epoch,this._offset=t.offset||0),this._epoch&&t.epoch&&this._epoch!==t.epoch)return this._debug("map subscribe: epoch changed during snapshot pagination, restarting"),this._mapStateBuffer=[],this._mapCursor="",this._epoch=null,this._offset=null,this._prevValueMap=new Map,void this._fetchSnapshot();if(t.state&&t.state.length>0)for(const e of t.state)this._seedDeltaTracking(e),this._mapStateBuffer.push(this._getMapUpdateContext(e));if(t.cursor)return this._mapCursor=t.cursor,void this._fetchSnapshot(this._mapCursor);this._transitionFromSnapshot()}else this._inflight=!1}_transitionFromSnapshot(){this._debug("map subscribe: snapshot complete, transitioning to stream phase"),this._mapPhase=os.Stream,this._fetchStream()}_fetchStream(){if(!this._isSubscribing()||!this._isTransportOpen())return void(this._inflight=!1);const t=this._buildMapSubscribeCommand(os.Stream);this._debug("map subscribe: fetching stream from offset",this._offset),this._centrifuge._call(t).then(t=>{const e=t.reply.subscribe;this._handleMapStreamResponse(e),t.next&&t.next()},t=>{this._handleMapSubscribeError(t.error),t.next&&t.next()})}_handleMapStreamResponse(t){if(this._isSubscribing()){if(!t.phase)return this._debug("map subscribe: server forced LIVE transition during stream"),void this._handleMapLiveResponse(t);if(this._epoch&&t.epoch&&this._epoch!==t.epoch)return this._debug("map subscribe: epoch changed during stream, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._mapPhase=os.State,void this._fetchSnapshot();if(t.publications&&t.publications.length>0)for(const e of t.publications)this._seedDeltaTracking(e),this._mapStreamBuffer.push(this._getMapUpdateContext(e));void 0!==t.offset&&(this._offset=t.offset),this._fetchStream()}else this._inflight=!1}_handleMapLiveResponse(t){if(!this._isSubscribing())return void(this._inflight=!1);if(this._inflight=!1,this._epoch&&t.epoch&&this._epoch!==t.epoch)return this._debug("map subscribe: epoch changed during live transition, restarting"),this._mapStateBuffer=[],this._mapStreamBuffer=[],this._epoch=null,this._offset=null,this._prevValueMap=new Map,this._inflight=!0,this._mapPhase=os.State,void this._fetchSnapshot();if(t.state&&t.state.length>0)for(const e of t.state)this._seedDeltaTracking(e),this._mapStateBuffer.push(this._getMapUpdateContext(e));if(t.publications&&t.publications.length>0)for(const e of t.publications){if(this._delta&&t.delta){const t=e.key||"",{newData:i,newPrevValue:o,isDelta:s,wireBytes:n,fullBytes:r}=this._centrifuge._codec.applyDeltaIfNeeded(e,this._prevValueMap.get(t));e.data=i,this._deltaNumPubs++,this._deltaBytesReceived+=n,this._deltaBytesDecoded+=r,s?this._deltaNumDelta++:this._deltaNumFull++,e.removed?this._prevValueMap.delete(t):this._prevValueMap.set(t,o)}else this._delta&&e.key&&(e.removed?this._prevValueMap.delete(e.key):this._prevValueMap.set(e.key,e.data));this._mapStreamBuffer.push(this._getMapUpdateContext(e))}this._offset=t.offset||0,this._epoch=t.epoch||"",this._clearSubscribingState(),t.id&&(this._id=t.id),this._recover=!0===t.recoverable,t.delta?this._delta_negotiated=!0:this._delta_negotiated=!1,t.publish_debounce&&(this._debounceMs=t.publish_debounce),this._setState(is.Subscribed);const e=this._centrifuge._getSubscribeContext(this.channel,t);if(e.state=this._mapStateBuffer,this.emit("subscribed",e),this._resolvePromises(),!e.recovered){if(this._mapStreamBuffer.length>0){const t=new Map;for(const e of this._mapStateBuffer)t.set(e.key,e);for(const e of this._mapStreamBuffer)e.removed?t.delete(e.key):t.set(e.key,e);this._mapStateBuffer=Array.from(t.values()),this._mapStreamBuffer=[]}this.emit("sync",{entries:this._mapStateBuffer})}for(const t of this._mapStreamBuffer)this.emit("publication",t),this.emit("update",t);this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,!0===t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl)))}_handleMapSubscribeError(t){if(this._inflight=!1,this._isSubscribing())if(t.code!==Zo.timeout){if(this._mapStateBuffer=[],this._mapStreamBuffer=[],this._mapPhase=null,this._prevValueMap=new Map,112===t.code&&"from_scratch"===this._mapUnrecoverableStrategy)return this._debug("map subscribe: unrecoverable position, restarting from scratch"),this._offset=null,this._epoch=null,this._recover=!1,void this._scheduleResubscribe();this._subscribeError(t)}else this._centrifuge._disconnect(Yo.subscribeTimeout,"subscribe timeout",!0)}_buildMapSubscribeCommand(t,e){const i={channel:this.channel,type:this._mapPresenceType||1,phase:t};return this._token&&(i.token=this._token),this._tagsFilter&&(i.tf=this._tagsFilter),this._delta&&(i.delta=this._delta),i.flag=ts.channelCompaction,t===os.State&&(this._mapPageSize>0&&(i.limit=this._mapPageSize),e&&(i.cursor=e),this._epoch?(i.offset=this._offset,i.epoch=this._epoch):this._data&&(i.data=this._data)),t===os.Stream&&(this._mapPageSize>0&&(i.limit=this._mapPageSize),i.offset=this._offset,i.epoch=this._epoch,this._recover&&(i.recover=!0,0===this._mapStreamBuffer.length&&this._data&&(i.data=this._data))),{subscribe:i}}_getMapUpdateContext(t){const e={channel:this.channel,data:t.data,key:t.key||""};return!0===t.removed&&(e.removed=!0),void 0!==t.offset&&(e.offset=t.offset),t.info&&(e.info=this._centrifuge._getJoinLeaveContext(t.info)),t.tags&&(e.tags=t.tags),e}_getSharedPollUpdateContext(t){const e={channel:this.channel,key:t.key||"",data:t.data};return!0===t.removed&&(e.removed=!0),void 0!==t.version&&(e.version=t.version),e}}class cs extends ds{publish(t){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish("",t,!1):this._centrifuge.publish(this.channel,t)})}history(t){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._centrifuge.history(this.channel,t)})}}class hs extends ds{publish(t,e){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._debounceMs>0?this._debouncedPublish(t,e,!0):this._centrifuge.mapPublish(this.channel,t,e)})}remove(t){return Ho(this,0,void 0,function*(){return yield this._methodCall(),this._cancelDebounce(t),this._centrifuge.mapRemove(this.channel,t)})}}class us extends ds{track(t,e){if(0===t.length)return;let i;const o=e;if("string"==typeof t[0]){i=t.map(t=>({key:t,version:0}))}else i=t;for(const t of i){const e=this._sharedPollTrackedItems.get(t.key);(void 0===e||t.version>e)&&this._sharedPollTrackedItems.set(t.key,t.version)}if(void 0!==o)return this._sharedPollSignatures.push({keys:i.map(t=>t.key),signature:o}),void(this._isSubscribed()&&this._sendTrackRequest([{items:i,signature:o}]).catch(t=>{this._handleTrackError(t)}));if(!this._sharedPollGetSignature)return void this.emit("error",{type:"track",channel:this.channel,error:{code:Zo.sharedPollGetSignature,message:"getSignature callback required for track(keys)"}});if(!this._isSubscribed())return;const s=i.map(t=>t.key);this._sharedPollGetSignature({keys:s}).then(t=>{if(!this._isSubscribed())return;const e=new Set(t.keys),i=[];for(const t of s)e.has(t)||(this._sharedPollTrackedItems.delete(t),i.push(t),this.emit("update",{channel:this.channel,key:t,data:null,removed:!0}));i.length>0&&this._sendUntrackRequest(i).catch(t=>{this.emit("error",{type:"untrack",channel:this.channel,error:t})});const o=[];for(const e of t.keys){const t=this._sharedPollTrackedItems.get(e);void 0!==t&&o.push({key:e,version:t})}0!==o.length&&(this._sharedPollSignatures.push({keys:t.keys,signature:t.signature}),this._sendTrackRequest([{items:o,signature:t.signature}]).catch(t=>{this._handleTrackError(t)}))}).catch(t=>{this.emit("error",{type:"track",channel:this.channel,error:{code:Zo.sharedPollGetSignature,message:void 0!==t?t.toString():"getSignature failed"}})})}untrack(t){for(const e of t)this._sharedPollTrackedItems.delete(e);this._sharedPollSignatures=this._sharedPollSignatures.filter(t=>t.keys.some(t=>this._sharedPollTrackedItems.has(t))),this._isSubscribed()&&this._sendUntrackRequest(t).catch(t=>{this.emit("error",{type:"untrack",channel:this.channel,error:t})})}trackedKeys(){return new Set(this._sharedPollTrackedItems.keys())}}class ps{constructor(t,e){this.endpoint=t,this.options=e,this._transport=null}name(){return"sockjs"}subName(){return"sockjs-"+this._transport.transport}emulation(){return!1}supported(){return null!==this.options.sockjs}initialize(t,e){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=t=>{e.onError(t)},this._transport.onclose=t=>{e.onClose(t)},this._transport.onmessage=t=>{e.onMessage(t.data)}}close(){this._transport.close()}send(t){this._transport.send(t)}}class ms{constructor(t,e){this.endpoint=t,this.options=e,this._transport=null}name(){return"websocket"}subName(){return"websocket"}emulation(){return!1}supported(){return void 0!==this.options.websocket&&null!==this.options.websocket}initialize(t,e){let i="";"protobuf"===t&&(i="centrifuge-protobuf"),this._transport=""!==i?new this.options.websocket(this.endpoint,i):new this.options.websocket(this.endpoint),"protobuf"===t&&(this._transport.binaryType="arraybuffer"),this._transport.onopen=()=>{e.onOpen()},this._transport.onerror=t=>{e.onError(t)},this._transport.onclose=t=>{e.onClose(t)},this._transport.onmessage=t=>{e.onMessage(t.data)}}close(){this._transport.close()}send(t){this._transport.send(t)}}class gs{constructor(t,e){this.endpoint=t,this.options=e,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"http_stream"}subName(){return"http_stream"}emulation(){return!0}_handleErrors(t){if(!t.ok)throw new Error(t.status);return t}_fetchEventTarget(t,e,i){const o=new EventTarget;return(0,t.options.fetch)(e,i).then(t._handleErrors).then(e=>{o.dispatchEvent(new Event("open"));let i="",s=0,n=new Uint8Array;const r=e.body.getReader();return new t.options.readableStream({start:e=>function a(){return r.read().then(({done:r,value:l})=>{if(r)return o.dispatchEvent(new Event("close")),void e.close();try{if("json"===t._protocol)for(i+=t._utf8decoder.decode(l);s<i.length;)if("\n"===i[s]){const t=i.substring(0,s);o.dispatchEvent(new MessageEvent("message",{data:t})),i=i.substring(s+1),s=0}else++s;else{const e=new Uint8Array(n.length+l.length);for(e.set(n),e.set(l,n.length),n=e;;){const e=t.options.decoder.decodeReply(n);if(e.ok){const t=n.slice(0,e.pos);o.dispatchEvent(new MessageEvent("message",{data:t})),n=n.slice(e.pos);continue}break}}}catch(t){return o.dispatchEvent(new Event("error",{detail:t})),o.dispatchEvent(new Event("close")),void e.close()}a()}).catch(function(t){o.dispatchEvent(new Event("error",{detail:t})),o.dispatchEvent(new Event("close")),e.close()})}()})}).catch(t=>{o.dispatchEvent(new Event("error",{detail:t})),o.dispatchEvent(new Event("close"))}),o}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&"undefined"!=typeof TextDecoder&&"undefined"!=typeof AbortController&&"undefined"!=typeof EventTarget&&"undefined"!=typeof Event&&"undefined"!=typeof MessageEvent&&"undefined"!=typeof Error}initialize(t,e,i){let o,s;this._protocol=t,this._abortController=new AbortController,"json"===t?(o={Accept:"application/json","Content-Type":"application/json"},s=i):(o={Accept:"application/octet-stream","Content-Type":"application/octet-stream"},s=i);const n={method:"POST",headers:o,body:s,mode:"cors",credentials:"same-origin",signal:this._abortController.signal},r=this._fetchEventTarget(this,this.endpoint,n);r.addEventListener("open",()=>{e.onOpen()}),r.addEventListener("error",t=>{this._abortController.abort(),e.onError(t)}),r.addEventListener("close",()=>{this._abortController.abort(),e.onClose({code:4,reason:"connection closed"})}),r.addEventListener("message",t=>{e.onMessage(t.data)})}close(){this._abortController.abort()}send(t,e,i){let o,s;const n={session:e,node:i,data:t};"json"===this._protocol?(o={"Content-Type":"application/json"},s=JSON.stringify(n)):(o={"Content-Type":"application/octet-stream"},s=this.options.encoder.encodeEmulationRequest(n));const r={method:"POST",headers:o,body:s,mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,r)}}class fs{constructor(t,e){this.endpoint=t,this.options=e,this._protocol="json",this._transport=null,this._onClose=null}name(){return"sse"}subName(){return"sse"}emulation(){return!0}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(t,e,i){let o;o=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),o.searchParams.append("cf_connect",i);const s=new this.options.eventsource(o.toString(),{});this._transport=s;s.onopen=function(){e.onOpen()},s.onerror=function(t){s.close(),e.onError(t),e.onClose({code:4,reason:"connection closed"})},s.onmessage=function(t){e.onMessage(t.data)},this._onClose=function(){e.onClose({code:4,reason:"connection closed"})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(t,e,i){const o={session:e,node:i,data:t},s={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),mode:"cors",credentials:"same-origin"};(0,this.options.fetch)(this.options.emulationEndpoint,s)}}class vs{constructor(t,e){this.endpoint=t,this.options=e,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol="json"}name(){return"webtransport"}subName(){return"webtransport"}emulation(){return!1}supported(){return void 0!==this.options.webtransport&&null!==this.options.webtransport}initialize(t,e){return Ho(this,0,void 0,function*(){let i;i=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),"protobuf"===t&&i.searchParams.append("cf_protocol","protobuf"),this._protocol=t;const o=new EventTarget;this._transport=new this.options.webtransport(i.toString()),this._transport.closed.then(()=>{e.onClose({code:4,reason:"connection closed"})}).catch(()=>{e.onClose({code:4,reason:"connection closed"})});try{yield this._transport.ready}catch(t){return void this.close()}let s;try{s=yield this._transport.createBidirectionalStream()}catch(t){return void this.close()}this._stream=s,this._writer=this._stream.writable.getWriter(),o.addEventListener("close",()=>{e.onClose({code:4,reason:"connection closed"})}),o.addEventListener("message",t=>{e.onMessage(t.data)}),this._startReading(o),e.onOpen()})}_startReading(t){return Ho(this,0,void 0,function*(){const e=this._stream.readable.getReader();let i="",o=0,s=new Uint8Array;try{for(;;){const{done:n,value:r}=yield e.read();if(r.length>0)if("json"===this._protocol)for(i+=this._utf8decoder.decode(r);o<i.length;)if("\n"===i[o]){const e=i.substring(0,o);t.dispatchEvent(new MessageEvent("message",{data:e})),i=i.substring(o+1),o=0}else++o;else{const e=new Uint8Array(s.length+r.length);for(e.set(s),e.set(r,s.length),s=e;;){const e=this.options.decoder.decodeReply(s);if(e.ok){const i=s.slice(0,e.pos);t.dispatchEvent(new MessageEvent("message",{data:i})),s=s.slice(e.pos);continue}break}}if(n)break}}catch(e){t.dispatchEvent(new Event("close"))}})}close(){return Ho(this,0,void 0,function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(t){}})}send(t){return Ho(this,0,void 0,function*(){let e;e="json"===this._protocol?(new TextEncoder).encode(t+"\n"):t;try{yield this._writer.write(e)}catch(t){this.close()}})}}const bs=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,36,-1,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,-1,-1,-1,63,-1];class ys{constructor(t){this.a=t,this.pos=0}haveBytes(){return this.pos<this.a.length}getByte(){const t=this.a[this.pos];if(this.pos++,this.pos>this.a.length)throw new RangeError("out of bounds");return t}getChar(){return String.fromCharCode(this.getByte())}getInt(){let t,e=0;for(;this.haveBytes()&&(t=bs[127&this.getByte()])>=0;)e=(e<<6)+t;return this.pos--,e>>>0}}class xs{constructor(){this.a=[]}toByteArray(t){return Array.isArray(t)?this.a:new Uint8Array(this.a)}putArray(t,e,i){for(let o=e;o<i;o++)this.a.push(t[o])}}function ws(t){let e=0,i=0,o=0,s=0,n=0,r=t.length;for(;r>=16;)e=e+t[n+0]|0,i=i+t[n+1]|0,o=o+t[n+2]|0,s=s+t[n+3]|0,e=e+t[n+4]|0,i=i+t[n+5]|0,o=o+t[n+6]|0,s=s+t[n+7]|0,e=e+t[n+8]|0,i=i+t[n+9]|0,o=o+t[n+10]|0,s=s+t[n+11]|0,e=e+t[n+12]|0,i=i+t[n+13]|0,o=o+t[n+14]|0,s=s+t[n+15]|0,n+=16,r-=16;for(;r>=4;)e=e+t[n+0]|0,i=i+t[n+1]|0,o=o+t[n+2]|0,s=s+t[n+3]|0,n+=4,r-=4;switch(s=((s+(o<<8)|0)+(i<<16)|0)+(e<<24)|0,r){case 3:s=s+(t[n+2]<<8)|0;case 2:s=s+(t[n+1]<<16)|0;case 1:s=s+(t[n+0]<<24)|0}return s>>>0}class _s{name(){return"json"}encodeCommands(t){return t.map(t=>JSON.stringify(t)).join("\n")}decodeReplies(t){return t.trim().split("\n").map(t=>JSON.parse(t))}applyDeltaIfNeeded(t,e){let i,o,s;if(t.delta){s=!0;const n=function(t,e){let i=0;const o=new ys(e),s=t.length,n=e.length,r=o.getInt();if("\n"!==o.getChar())throw new Error("size integer not terminated by '\\n'");const a=new xs;for(;o.haveBytes();){const e=o.getInt();let l;switch(o.getChar()){case"@":if(l=o.getInt(),o.haveBytes()&&","!==o.getChar())throw new Error("copy command not terminated by ','");if(i+=e,i>r)throw new Error("copy exceeds output file size");if(l+e>s)throw new Error("copy extends past end of input");a.putArray(t,l,l+e);break;case":":if(i+=e,i>r)throw new Error("insert command gives an output larger than predicted");if(e>n)throw new Error("insert count exceeds size of delta");a.putArray(o.a,o.pos,o.pos+e),o.pos+=e;break;case";":{const o=a.toByteArray(t);if(e!==ws(o))throw new Error("bad checksum");if(i!==r)throw new Error("generated size does not match predicted size");return o}default:throw new Error("unknown delta operator")}}throw new Error("unterminated delta")}(e,(new TextEncoder).encode(t.data));i=JSON.parse((new TextDecoder).decode(n)),o=n}else s=!1,i=JSON.parse(t.data),o=(new TextEncoder).encode(t.data);return{newData:i,newPrevValue:o,isDelta:s,wireBytes:t.data.length,fullBytes:o.length}}}const ks={headers:{},token:"",getToken:null,data:null,getData:null,debug:!1,name:"js",version:"",fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:"/emulation",minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class Cs extends Error{constructor(t){super(t),this.name=this.constructor.name}}class Ss extends ns{constructor(t,e){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=es.Disconnected,this._transportIsOpen=!1,this._endpoint=t,this._emulation=!1,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=!1,this._transportWasOpen=!1,this._transport=null,this._transportId=0,this._deviceWentOffline=!1,this._transportClosed=!0,this._codec=new _s,this._reconnecting=!1,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session="",this._node="",this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=!1,this._refreshRequired=!1,this._refreshTimeout=null,this._callbacks={},this._token="",this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=!1,this._promises={},this._promiseId=0,this._debugEnabled=!1,this._networkEventsSet=!1,this._config=Object.assign(Object.assign({},ks),e),this._configure(),this._debugEnabled?(this.on("state",t=>{this._debug("client state",t.oldState,"->",t.newState)}),this.on("error",t=>{this._debug("client error",t)})):this.on("error",function(){Function.prototype()})}newSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new cs(this,t,e);return this._subs[t]=i,i}newMapSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new hs(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,tagsFilter:null==e?void 0:e.tagsFilter,map:!0,mapPageSize:null==e?void 0:e.pageSize,mapUnrecoverableStrategy:null==e?void 0:e.unrecoverableStrategy});return this._subs[t]=i,i}newMapClientsSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new hs(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,tagsFilter:null==e?void 0:e.tagsFilter,map:!0,mapPresenceType:2,mapPageSize:null==e?void 0:e.pageSize,mapUnrecoverableStrategy:null==e?void 0:e.unrecoverableStrategy});return this._subs[t]=i,i}newMapUsersSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new hs(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,tagsFilter:null==e?void 0:e.tagsFilter,map:!0,mapPresenceType:3,mapPageSize:null==e?void 0:e.pageSize,mapUnrecoverableStrategy:null==e?void 0:e.unrecoverableStrategy});return this._subs[t]=i,i}newSharedPollSubscription(t,e){if(null!==this.getSubscription(t))throw new Error("Subscription to the channel "+t+" already exists");const i=new us(this,t,{token:null==e?void 0:e.token,getToken:null==e?void 0:e.getToken,data:null==e?void 0:e.data,minResubscribeDelay:null==e?void 0:e.minResubscribeDelay,maxResubscribeDelay:null==e?void 0:e.maxResubscribeDelay,delta:null==e?void 0:e.delta,sharedPoll:!0,sharedPollGetSignature:null==e?void 0:e.getSignature});return this._subs[t]=i,i}getSubscription(t){return this._getSub(t)}getMapSubscription(t){return this._getSub(t)}getSharedPollSubscription(t){return this._getSub(t)}removeSubscription(t){t&&(t.state!==is.Unsubscribed&&t.unsubscribe(),this._removeSubscription(t))}removeMapSubscription(t){this.removeSubscription(t)}removeSharedPollSubscription(t){this.removeSubscription(t)}subscriptions(){return this._subs}mapSubscriptions(){const t={};for(const[e,i]of Object.entries(this._subs))"map"===i.type&&(t[e]=i);return t}sharedPollSubscriptions(){const t={};for(const[e,i]of Object.entries(this._subs))"shared_poll"===i.type&&(t[e]=i);return t}ready(t){return Ho(this,0,void 0,function*(){switch(this.state){case es.Disconnected:throw{code:Zo.clientDisconnected,message:"client disconnected"};case es.Connected:return;default:return new Promise((e,i)=>{const o={resolve:e,reject:i};t&&(o.timeout=setTimeout(()=>{i({code:Zo.timeout,message:"timeout"})},t)),this._promises[this._nextPromiseId()]=o})}})}connect(){this._isConnected()?this._debug("connect called when already connected"):this._isConnecting()?this._debug("connect called when already connecting"):(this._debug("connect called"),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(Xo.disconnectCalled,"disconnect called",!1)}setToken(t){this._token=t}setData(t){this._data=t}setHeaders(t){this._config.headers=t}send(t){return Ho(this,0,void 0,function*(){const e={send:{data:t}};yield this._methodCall();if(!this._transportSendCommands([e]))throw this._createErrorObject(Zo.transportWriteError,"transport write error")})}rpc(t,e){return Ho(this,0,void 0,function*(){const i={rpc:{method:t,data:e}};yield this._methodCall();return{data:(yield this._callPromise(i,t=>t.rpc)).data}})}publish(t,e){return Ho(this,0,void 0,function*(){const i={publish:{channel:t,data:e}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}mapPublish(t,e,i){return Ho(this,0,void 0,function*(){const o={publish:{channel:t,type:1,key:e,data:i}};return yield this._methodCall(),yield this._callPromise(o,()=>({})),{}})}mapRemove(t,e){return Ho(this,0,void 0,function*(){const i={publish:{channel:t,type:1,key:e,removed:!0}};return yield this._methodCall(),yield this._callPromise(i,()=>({})),{}})}history(t,e){return Ho(this,0,void 0,function*(){const i={history:this._getHistoryRequest(t,e)};yield this._methodCall();const o=yield this._callPromise(i,t=>t.history),s=[];if(o.publications)for(let e=0;e<o.publications.length;e++)s.push(this._getPublicationContext(t,o.publications[e]));return{publications:s,epoch:o.epoch||"",offset:o.offset||0}})}presence(t){return Ho(this,0,void 0,function*(){const e={presence:{channel:t}};yield this._methodCall();const i=(yield this._callPromise(e,t=>t.presence)).presence;for(const t in i)if(Object.prototype.hasOwnProperty.call(i,t)){const e=i[t],o=e.conn_info,s=e.chan_info;o&&(e.connInfo=o),s&&(e.chanInfo=s)}return{clients:i}})}presenceStats(t){return Ho(this,0,void 0,function*(){const e={presence_stats:{channel:t}};yield this._methodCall();const i=yield this._callPromise(e,t=>t.presence_stats);return{numUsers:i.num_users,numClients:i.num_clients}})}startBatching(){this._batching=!0}stopBatching(){const t=this;Promise.resolve().then(function(){Promise.resolve().then(function(){t._batching=!1,t._flush()})})}_debug(...t){this._debugEnabled&&function(t,e){if(globalThis.console){const i=globalThis.console[t];rs(i)&&i.apply(globalThis.console,e)}}("debug",t)}_codecName(){return this._codec.name()}_formatOverride(){}_configure(){if(!("Promise"in globalThis))throw new Error("Promise polyfill required");if(!this._endpoint)throw new Error("endpoint configuration required");if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new _s,this._formatOverride(),(!0===this._config.debug||"undefined"!=typeof localStorage&&"function"==typeof localStorage.getItem&&localStorage.getItem("centrifuge.debug"))&&(this._debugEnabled=!0),this._debug("config",this._config),"string"==typeof this._endpoint);else{if(!Array.isArray(this._endpoint))throw new Error("unsupported url configuration type: only string or array of objects are supported");this._transports=this._endpoint,this._emulation=!0;for(const t in this._transports)if(this._transports.hasOwnProperty(t)){const e=this._transports[t];if(!e.endpoint||!e.transport)throw new Error("malformed transport configuration");const i=e.transport;if(["websocket","http_stream","sse","sockjs","webtransport"].indexOf(i)<0)throw new Error("unsupported transport name: "+i)}}}_setState(t){if(this.state!==t){this._reconnecting=!1;const e=this.state;return this.state=t,this.emit("state",{newState:t,oldState:e}),!0}return!1}_isDisconnected(){return this.state===es.Disconnected}_isConnecting(){return this.state===es.Connecting}_isConnected(){return this.state===es.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(this._networkEventsSet)return;let t=null;null!==this._config.networkEventTarget?t=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(t=globalThis),t&&(t.addEventListener("offline",()=>{this._debug("offline event triggered"),this.state!==es.Connected&&this.state!==es.Connecting||(this._disconnect(Yo.transportClosed,"transport closed",!0),this._deviceWentOffline=!0)}),t.addEventListener("online",()=>{this._debug("online event triggered"),this.state===es.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=!1,this._transportClosed=!0),this._clearReconnectTimeout(),this._startReconnecting())}),this._networkEventsSet=!0)}_getReconnectDelay(){const t=as(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,t}_clearOutgoingRequests(){for(const t in this._callbacks)if(this._callbacks.hasOwnProperty(t)){const e=this._callbacks[t];clearTimeout(e.timeout);const i=e.errback;if(!i)continue;i({error:this._createErrorObject(Zo.connectionClosed,"connection closed")})}this._callbacks={}}_clearConnectedState(){this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout();for(const t in this._subs){if(!this._subs.hasOwnProperty(t))continue;const e=this._subs[t];e.state===is.Subscribed&&e._setSubscribing(Qo.transportClosed,"transport closed")}for(const t in this._serverSubs)this._serverSubs.hasOwnProperty(t)&&this.emit("subscribing",{channel:t})}_handleWriteError(t){for(const e of t){const t=e.id;if(!(t in this._callbacks))continue;const i=this._callbacks[t];clearTimeout(this._callbacks[t].timeout),delete this._callbacks[t];(0,i.errback)({error:this._createErrorObject(Zo.transportWriteError,"transport write error")})}}_transportSendCommands(t){if(!t.length)return!0;if(!this._transport)return!1;try{this._transport.send(this._codec.encodeCommands(t),this._session,this._node)}catch(e){return this._debug("error writing commands",e),this._handleWriteError(t),!1}return!0}_initializeTransport(){let t;null!==this._config.websocket?t=this._config.websocket:"function"!=typeof globalThis.WebSocket&&"object"!=typeof globalThis.WebSocket||(t=globalThis.WebSocket);let e=null;null!==this._config.sockjs?e=this._config.sockjs:void 0!==globalThis.SockJS&&(e=globalThis.SockJS);let i=null;null!==this._config.eventsource?i=this._config.eventsource:void 0!==globalThis.EventSource&&(i=globalThis.EventSource);let o=null;null!==this._config.fetch?o=this._config.fetch:void 0!==globalThis.fetch&&(o=globalThis.fetch);let s=null;if(null!==this._config.readableStream?s=this._config.readableStream:void 0!==globalThis.ReadableStream&&(s=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=!0,this._currentTransportIndex=0);let n=0;for(;;){if(n>=this._transports.length)throw new Error("no supported transport found");const r=this._transports[this._currentTransportIndex],a=r.transport,l=r.endpoint;if("websocket"===a){if(this._debug("trying websocket transport"),this._transport=new ms(l,{websocket:t}),!this._transport.supported()){this._debug("websocket transport not available"),this._currentTransportIndex++,n++;continue}}else if("webtransport"===a){if(this._debug("trying webtransport transport"),this._transport=new vs(l,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("webtransport transport not available"),this._currentTransportIndex++,n++;continue}}else if("http_stream"===a){if(this._debug("trying http_stream transport"),this._transport=new gs(l,{fetch:o,readableStream:s,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug("http_stream transport not available"),this._currentTransportIndex++,n++;continue}}else if("sse"===a){if(this._debug("trying sse transport"),this._transport=new fs(l,{eventsource:i,fetch:o,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug("sse transport not available"),this._currentTransportIndex++,n++;continue}}else{if("sockjs"!==a)throw new Error("unknown transport "+a);if(this._debug("trying sockjs"),this._transport=new ps(l,{sockjs:e,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug("sockjs transport not available"),this._currentTransportIndex++,n++;continue}}break}}else{if(n=this._endpoint,r="http",0===n.lastIndexOf(r,0))throw new Error("Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport");if(this._debug("client will use websocket"),this._transport=new ms(this._endpoint,{websocket:t}),!this._transport.supported())throw new Error("WebSocket constructor not found, make sure it is available globally or passed as a dependency in Centrifuge options")}var n,r;const a=this,l=this._transport,d=this._nextTransportId();a._debug("id of transport",d);let c=!1;const h=[];if(this._transport.emulation()){const t=a._sendConnect(!0);h.push(t)}this._setNetworkEvents();const u=this._codec.encodeCommands(h);let p;this._transportClosed=!1,p=setTimeout(function(){l.close()},this._config.timeout),this._transport.initialize(this._codecName(),{onOpen:function(){if(p&&(clearTimeout(p),p=null),a._transportId!=d)return a._debug("open callback from non-actual transport"),void l.close();c=!0,a._debug(l.subName(),"transport open"),l.emulation()||(a._transportIsOpen=!0,a._transportWasOpen=!0,a.startBatching(),a._sendConnect(!1),a._sendSubscribeCommands(),a.stopBatching(),a.emit("__centrifuge_debug:connect_frame_sent",{}))},onError:function(t){a._transportId==d?a._debug("transport level error",t):a._debug("error callback from non-actual transport")},onClose:function(t){if(p&&(clearTimeout(p),p=null),a._transportId!=d)return void a._debug("close callback from non-actual transport");a._debug(l.subName(),"transport closed"),a._transportClosed=!0,a._transportIsOpen=!1;let e="connection closed",i=!0,o=0;if(t&&"code"in t&&t.code&&(o=t.code),t&&t.reason)try{const o=JSON.parse(t.reason);e=o.reason,i=o.reconnect}catch(s){e=t.reason,(o>=3500&&o<4e3||o>=4500&&o<5e3)&&(i=!1)}o<3e3?(1009===o?(o=Xo.messageSizeLimit,e="message size limit exceeded",i=!1):(o=Yo.transportClosed,e="transport closed"),a._emulation&&!a._transportWasOpen&&(a._currentTransportIndex++,a._currentTransportIndex>=a._transports.length&&(a._triedAllTransports=!0,a._currentTransportIndex=0))):a._transportWasOpen=!0,a._isConnecting()&&!c&&a.emit("error",{type:"transport",error:{code:Zo.transportClosed,message:"transport closed"},transport:l.name()}),a._reconnecting=!1,a._disconnect(o,e,i)},onMessage:function(t){a._dataReceived(t)}},u),a.emit("__centrifuge_debug:transport_initialized",{})}_sendConnect(t){const e=this._constructConnectCommand(),i=this;return this._call(e,t).then(t=>{const e=t.reply.connect;i._connectResponse(e),t.next&&t.next()},t=>{i._connectError(t.error),t.next&&t.next()}),e}_startReconnecting(){if(this._debug("start reconnecting"),!this._isConnecting())return void this._debug("stop reconnecting: client not in connecting state");if(this._reconnecting)return void this._debug("reconnect already in progress, return from reconnect routine");if(!1===this._transportClosed)return void this._debug("waiting for transport close");this._reconnecting=!0;const t=""===this._token;if(!(this._refreshRequired||t&&null!==this._config.getToken))return void(this._config.getData?this._config.getData().then(t=>{this._isConnecting()&&(this._data=t,this._initializeTransport())}).catch(t=>this._handleGetDataError(t)):this._initializeTransport());const e=this;this._getToken().then(function(t){e._isConnecting()&&(null!=t&&null!=t?(e._token=t,e._debug("connection token refreshed"),e._config.getData?e._config.getData().then(function(t){e._isConnecting()&&(e._data=t,e._initializeTransport())}).catch(t=>e._handleGetDataError(t)):e._initializeTransport()):e._failUnauthorized())}).catch(function(t){if(!e._isConnecting())return;if(t instanceof Cs)return void e._failUnauthorized();e.emit("error",{type:"connectToken",error:{code:Zo.clientConnectToken,message:void 0!==t?t.toString():""}});const i=e._getReconnectDelay();e._debug("error on getting connection token, reconnect after "+i+" milliseconds",t),e._reconnecting=!1,e._reconnectTimeout=setTimeout(()=>{e._startReconnecting()},i)})}_handleGetDataError(t){if(t instanceof Cs)return void this._failUnauthorized();this.emit("error",{type:"connectData",error:{code:Zo.badConfiguration,message:(null==t?void 0:t.toString())||""}});const e=this._getReconnectDelay();this._debug("error on getting connect data, reconnect after "+e+" milliseconds",t),this._reconnecting=!1,this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},e)}_connectError(t){this.state===es.Connecting&&(109===t.code&&(this._refreshRequired=!0),t.code<100||!0===t.temporary||109===t.code?(this.emit("error",{type:"connect",error:t}),this._debug("closing transport due to connect error"),this._disconnect(t.code,t.message,!0)):this._disconnect(t.code,t.message,!1))}_scheduleReconnect(){if(!this._isConnecting())return;let t=!1;!this._emulation||this._transportWasOpen||this._triedAllTransports||(t=!0);let e=this._getReconnectDelay();t&&(e=0),this._debug("reconnect after "+e+" milliseconds"),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout(()=>{this._startReconnecting()},e)}_constructConnectCommand(){const t={};this._token&&(t.token=this._token),this._data&&(t.data=this._data),this._config.name&&(t.name=this._config.name),this._config.version&&(t.version=this._config.version),Object.keys(this._config.headers).length>0&&(t.headers=this._config.headers);const e={};let i=!1;for(const t in this._serverSubs)if(this._serverSubs.hasOwnProperty(t)&&this._serverSubs[t].recoverable){i=!0;const o={recover:!0};this._serverSubs[t].offset&&(o.offset=this._serverSubs[t].offset),this._serverSubs[t].epoch&&(o.epoch=this._serverSubs[t].epoch),e[t]=o}return i&&(t.subs=e),{connect:t}}_getHistoryRequest(t,e){const i={channel:t};return void 0!==e&&(e.since&&(i.since={offset:e.since.offset},e.since.epoch&&(i.since.epoch=e.since.epoch)),void 0!==e.limit&&(i.limit=e.limit),!0===e.reverse&&(i.reverse=!0)),i}_methodCall(){return this._isConnected()?Promise.resolve():new Promise((t,e)=>{const i=setTimeout(function(){e({code:Zo.timeout,message:"timeout"})},this._config.timeout);this._promises[this._nextPromiseId()]={timeout:i,resolve:t,reject:e}})}_callPromise(t,e){return new Promise((i,o)=>{this._call(t,!1).then(t=>{var o;const s=e(t.reply);i(s),null===(o=t.next)||void 0===o||o.call(t)},t=>{var e;o(t.error),null===(e=t.next)||void 0===e||e.call(t)})})}_dataReceived(t){this._serverPing>0&&this._waitServerPing();const e=this._codec.decodeReplies(t);this._dispatchPromise=this._dispatchPromise.then(()=>{let t;this._dispatchPromise=new Promise(e=>{t=e}),this._dispatchSynchronized(e,t)})}_dispatchSynchronized(t,e){let i=Promise.resolve();for(const e in t)t.hasOwnProperty(e)&&(i=i.then(()=>this._dispatchReply(t[e])));i=i.then(()=>{e()})}_dispatchReply(t){let e;const i=new Promise(t=>{e=t});if(null==t)return this._debug("dispatch: got undefined or null reply"),e(),i;const o=t.id;return o&&o>0?this._handleReply(t,e):t.push?this._handlePush(t.push,e):this._handleServerPing(e),i}_call(t,e){return new Promise((i,o)=>{t.id=this._nextCommandId(),this._registerCall(t.id,i,o),e||this._addCommand(t)})}_startConnecting(){this._debug("start connecting"),this._setState(es.Connecting)&&this.emit("connecting",{code:Yo.connectCalled,reason:"connect called"}),this._client=null,this._startReconnecting()}_disconnect(t,e,i){if(t===Xo.stateInvalidated){this._token="",this._refreshRequired=!0;for(const t in this._subs)this._subs.hasOwnProperty(t)&&this._subs[t]._invalidateState()}if(this._isDisconnected())return;this._transportIsOpen=!1;const o=this.state;this._reconnecting=!1;const s={code:t,reason:e};let n=!1;if(i?n=this._setState(es.Connecting):(n=this._setState(es.Disconnected),this._rejectPromises({code:Zo.clientDisconnected,message:"disconnected"})),this._clearOutgoingRequests(),o===es.Connecting&&this._clearReconnectTimeout(),o===es.Connected&&this._clearConnectedState(),n&&(this._isConnecting()?this.emit("connecting",s):this.emit("disconnected",s)),this._transport){this._debug("closing existing transport");const t=this._transport;this._transport=null,t.close(),this._transportClosed=!0,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}_failUnauthorized(){this._disconnect(Xo.unauthorized,"unauthorized",!1)}_getToken(){return this._debug("get connection token"),this._config.getToken?this._config.getToken({}):(this.emit("error",{type:"configuration",error:{code:Zo.badConfiguration,message:"token expired but no getToken function set in the configuration"}}),Promise.reject(new Cs("")))}_refresh(){const t=this._client,e=this;this._getToken().then(function(i){if(t!==e._client)return;if(!i)return void e._failUnauthorized();if(e._token=i,e._debug("connection token refreshed"),!e._isConnected())return;const o={refresh:{token:e._token}};e._call(o,!1).then(t=>{const i=t.reply.refresh;e._refreshResponse(i),t.next&&t.next()},t=>{e._refreshError(t.error),t.next&&t.next()})}).catch(function(t){e._isConnected()&&(t instanceof Cs?e._failUnauthorized():(e.emit("error",{type:"refreshToken",error:{code:Zo.clientRefreshToken,message:void 0!==t?t.toString():""}}),e._refreshTimeout=setTimeout(()=>e._refresh(),e._getRefreshRetryDelay())))})}_refreshError(t){t.code<100||!0===t.temporary?(this.emit("error",{type:"refresh",error:t}),this._refreshTimeout=setTimeout(()=>this._refresh(),this._getRefreshRetryDelay())):this._disconnect(t.code,t.message,!1)}_getRefreshRetryDelay(){return as(0,5e3,1e4)}_refreshResponse(t){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),t.expires&&(this._client=t.client,this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl)))}_removeSubscription(t){null!==t&&delete this._subs[t.channel]}_unsubscribe(t){if(!this._transportIsOpen)return Promise.resolve();const e={unsubscribe:{channel:t.channel}},i=this,o=new Promise((t,o)=>{this._call(e,!1).then(e=>{t(),e.next&&e.next()},e=>{t(),e.next&&e.next(),i._disconnect(Yo.unsubscribeError,"unsubscribe error",!0)})});return o}_getSub(t,e){if(e&&e>0){for(const t in this._subs)if(this._subs.hasOwnProperty(t)){const i=this._subs[t];if(i._id===e)return i}return null}const i=this._subs[t];return i||null}_isServerSub(t){return void 0!==this._serverSubs[t]}_sendSubscribeCommands(){const t=[];for(const e in this._subs){if(!this._subs.hasOwnProperty(e))continue;const i=this._subs[e];if(!0!==i._inflight&&i.state===is.Subscribing){const e=i._subscribe();e&&t.push(e)}}return t}_connectResponse(t){if(this._transportIsOpen=!0,this._transportWasOpen=!0,this._reconnectAttempts=0,this._refreshRequired=!1,this._isConnected())return;this._client=t.client,this._setState(es.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),t.expires&&(this._refreshTimeout=setTimeout(()=>this._refresh(),ls(t.ttl))),this._session=t.session,this._node=t.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();const e={client:t.client,transport:this._transport.subName()};t.data&&(e.data=t.data),this.emit("connected",e),this._resolvePromises(),this._processServerSubs(t.subs||{}),t.ping&&t.ping>0?(this._serverPing=1e3*t.ping,this._sendPong=!0===t.pong,this._waitServerPing()):this._serverPing=0}_processServerSubs(t){for(const e in t){if(!t.hasOwnProperty(e))continue;const i=t[e];this._serverSubs[e]={offset:i.offset,epoch:i.epoch,recoverable:i.recoverable||!1};const o=this._getSubscribeContext(e,i);this.emit("subscribed",o)}for(const e in t){if(!t.hasOwnProperty(e))continue;const i=t[e];if(i.recovered){const t=i.publications;if(t&&t.length>0)for(const i in t)t.hasOwnProperty(i)&&this._handlePublication(e,t[i])}}for(const e in this._serverSubs)this._serverSubs.hasOwnProperty(e)&&(t[e]||(this.emit("unsubscribed",{channel:e}),delete this._serverSubs[e]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout(()=>{this._isConnected()&&this._disconnect(Yo.noPing,"no ping",!0)},this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(t,e){const i={channel:t,positioned:!1,recoverable:!1,wasRecovering:!1,recovered:!1,hasRecoveredPublications:!1};e.recovered&&(i.recovered=!0),e.positioned&&(i.positioned=!0),e.recoverable&&(i.recoverable=!0),e.was_recovering&&(i.wasRecovering=!0);let o="";"epoch"in e&&(o=e.epoch);let s=0;return"offset"in e&&(s=e.offset),(i.positioned||i.recoverable)&&(i.streamPosition={offset:s,epoch:o}),Array.isArray(e.publications)&&e.publications.length>0&&(i.hasRecoveredPublications=!0),e.data&&(i.data=e.data),i}_handleReply(t,e){const i=t.id;if(!(i in this._callbacks))return void e();const o=this._callbacks[i];if(clearTimeout(this._callbacks[i].timeout),delete this._callbacks[i],"error"in(s=t)&&null!==s.error){const i=o.errback;if(!i)return void e();i({error:{code:t.error.code,message:t.error.message||"",temporary:t.error.temporary||!1},next:e})}else{const i=o.callback;if(!i)return;i({reply:t,next:e})}var s}_handleJoin(t,e,i){const o=this._getSub(t,i);if(o)o._handleJoin(e);else if(t&&this._isServerSub(t)){const i={channel:t,info:this._getJoinLeaveContext(e.info)};this.emit("join",i)}}_handleLeave(t,e,i){const o=this._getSub(t,i);if(o)o._handleLeave(e);else if(t&&this._isServerSub(t)){const i={channel:t,info:this._getJoinLeaveContext(e.info)};this.emit("leave",i)}}_handleUnsubscribe(t,e){const i=this._getSub(t,0);i||!t?e.code<2500?i._setUnsubscribed(e.code,e.reason,!1):(e.code===Jo.stateInvalidated&&i._invalidateState(),i._setSubscribing(e.code,e.reason)):this._isServerSub(t)&&(delete this._serverSubs[t],this.emit("unsubscribed",{channel:t}))}_handleSubscribe(t,e){this._serverSubs[t]={offset:e.offset,epoch:e.epoch,recoverable:e.recoverable||!1},this.emit("subscribed",this._getSubscribeContext(t,e))}_handleDisconnect(t){const e=t.code;let i=!0;(e>=3500&&e<4e3||e>=4500&&e<5e3)&&(i=!1),this._disconnect(e,t.reason,i)}_getPublicationContext(t,e){const i={channel:t,data:e.data};return e.offset&&(i.offset=e.offset),e.info&&(i.info=this._getJoinLeaveContext(e.info)),e.tags&&(i.tags=e.tags),i}_getJoinLeaveContext(t){const e={client:t.client,user:t.user},i=t.conn_info;i&&(e.connInfo=i);const o=t.chan_info;return o&&(e.chanInfo=o),e}_handlePublication(t,e,i){const o=this._getSub(t,i);if(o)o._handlePublication(e);else if(t&&this._isServerSub(t)){const i=this._getPublicationContext(t,e);this.emit("publication",i),void 0!==e.offset&&(this._serverSubs[t].offset=e.offset)}}_handleMessage(t){this.emit("message",{data:t.data})}_handleServerPing(t){if(this._sendPong){const t={};this._transportSendCommands([t])}t()}_handlePush(t,e){const i=t.channel,o=t.id;t.pub?this._handlePublication(i,t.pub,o):t.message?this._handleMessage(t.message):t.join?this._handleJoin(i,t.join,o):t.leave?this._handleLeave(i,t.leave,o):t.unsubscribe?this._handleUnsubscribe(i,t.unsubscribe):t.subscribe?this._handleSubscribe(i,t.subscribe):t.disconnect&&this._handleDisconnect(t.disconnect),e()}_flush(){const t=this._commands.slice(0);this._commands=[],this._transportSendCommands(t)}_createErrorObject(t,e,i){const o={code:t,message:e};return i&&(o.temporary=!0),o}_registerCall(t,e,i){this._callbacks[t]={callback:e,errback:i,timeout:null},this._callbacks[t].timeout=setTimeout(()=>{delete this._callbacks[t],rs(i)&&i({error:this._createErrorObject(Zo.timeout,"timeout")})},this._config.timeout)}_addCommand(t){this._batching?this._commands.push(t):this._transportSendCommands([t])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(const t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].resolve(),delete this._promises[t])}_rejectPromises(t){for(const e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].reject(t),delete this._promises[e])}}Ss.SubscriptionState=is,Ss.State=es,Ss.UnauthorizedError=Cs;class $s{constructor(t){this.socket=null,this.channels=new Map,this.createSocket=t||(()=>{const t="https:"===window.location.protocol?"wss":"ws",e=new Ss(`${t}://${window.location.host}/ws/connect`);return e.connect(),e})}publish(t,e){this.socket||(this.socket=this.createSocket());const i=this.channels.get(t);return(i?i.sub.publish(e):this.socket.publish(t,e)).then(()=>{})}subscribe(t,e,i){this.socket||(this.socket=this.createSocket());let o=this.channels.get(t);o||(o={sub:this.socket.getSubscription(t)||this.socket.newSubscription(t),count:0},this.channels.set(t,o),o.sub.subscribe()),o.count++;const s=o.sub,n=t=>e(t.data);s.on("publication",n);let r=null;i&&(r=()=>i(),s.on("subscribed",r),s.state===is.Subscribed&&window.setTimeout(()=>r&&r(),0));let a=!0;return{unsubscribe:()=>{a&&(a=!1,s.off("publication",n),r&&(s.off("subscribed",r),r=null),o.count--,0===o.count&&(this.channels.delete(t),s.unsubscribe(),this.socket.removeSubscription(s)))}}}}const Ts=()=>{const t=window;return t.sockets||(t.sockets=new $s),t.sockets};Ts();const Es=(t,e,i)=>Ts().subscribe(t,e,i),As=(t,e)=>Ts().publish(t,e);let Ds=null;const Ms=[],zs=(t,e)=>((t,e,i)=>{if(Ds)return Es(t(Ds),e,i);const o={resolveChannel:t,onPublication:e,onSubscribed:i,sub:null,cancelled:!1};return Ms.push(o),{unsubscribe:()=>{o.cancelled=!0,o.sub&&(o.sub.unsubscribe(),o.sub=null)}}})(t=>`notifications:${t.org}:${t.user}`,e=>t(e),e),Ps=(t,e,i,o)=>Es(e?`history:${t}:${e}`:`history:${t}`,i,o);
702
742
  /**
703
743
  * tiny-lru
704
744
  *
@@ -1068,14 +1108,15 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1068
1108
  <div class=${o} style=${No(e)}>
1069
1109
  <div class="options-scroll" @scroll=${this.handleInnerScroll}>
1070
1110
  <div class="${s}" style=${No(i)}>
1071
- ${n.length>0?n.map((t,e)=>G`<div
1072
- data-option-index="${e}"
1073
- @mousemove=${this.handleMouseMove}
1074
- @mousedown=${this.handleOptionClick}
1075
- class="option ${e!==this.cursorIndex||this.internalFocusDisabled?"":"focused"}"
1076
- >
1077
- ${this.resolvedRenderOption(t,e===this.cursorIndex)}
1078
- </div>`):this.visible&&this.showEmptyMessage?G`<div
1111
+ ${n.length>0?n.map((t,e)=>G`${this.renderDivider?this.renderDivider(e>0?n[e-1]:null,t):null}
1112
+ <div
1113
+ data-option-index="${e}"
1114
+ @mousemove=${this.handleMouseMove}
1115
+ @mousedown=${this.handleOptionClick}
1116
+ class="option ${e!==this.cursorIndex||this.internalFocusDisabled?"":"focused"}"
1117
+ >
1118
+ ${this.resolvedRenderOption(t,e===this.cursorIndex)}
1119
+ </div>`):this.visible&&this.showEmptyMessage?G`<div
1079
1120
  class="option no-options"
1080
1121
  style="color: var(--color-text-dark-secondary); cursor: default;"
1081
1122
  >
@@ -1090,7 +1131,7 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1090
1131
  <temba-loading></temba-loading>
1091
1132
  </div>
1092
1133
  </div>
1093
- `}}i([ft({type:Number})],Pc.prototype,"top",void 0),i([ft({type:Number})],Pc.prototype,"left",void 0),i([ft({type:Number})],Pc.prototype,"width",void 0),i([ft({type:Number,attribute:"min-width"})],Pc.prototype,"minWidth",void 0),i([ft({type:Number,attribute:"static-width"})],Pc.prototype,"staticWidth",void 0),i([ft({type:Boolean,attribute:"anchor-right"})],Pc.prototype,"anchorRight",void 0),i([ft({type:Number})],Pc.prototype,"marginHorizontal",void 0),i([ft({type:Number})],Pc.prototype,"marginVertical",void 0),i([ft({type:Object})],Pc.prototype,"anchorTo",void 0),i([ft({type:Boolean})],Pc.prototype,"visible",void 0),i([ft({type:Boolean})],Pc.prototype,"block",void 0),i([ft({type:Boolean})],Pc.prototype,"cursorHover",void 0),i([ft({type:Boolean})],Pc.prototype,"cursorSelection",void 0),i([ft({type:Number})],Pc.prototype,"scrollPct",void 0),i([ft({type:Number})],Pc.prototype,"cursorIndex",void 0),i([ft({type:Boolean})],Pc.prototype,"internalFocusDisabled",void 0),i([ft({type:Array})],Pc.prototype,"options",void 0),i([ft({type:Array})],Pc.prototype,"tempOptions",void 0),i([ft({type:Boolean})],Pc.prototype,"poppedTop",void 0),i([ft({type:Boolean})],Pc.prototype,"spaceSelect",void 0),i([ft({type:String})],Pc.prototype,"nameKey",void 0),i([ft({type:Boolean})],Pc.prototype,"loading",void 0),i([ft({type:Boolean})],Pc.prototype,"collapsed",void 0),i([ft({type:Boolean})],Pc.prototype,"hideShadow",void 0),i([ft({attribute:!1})],Pc.prototype,"getName",void 0),i([ft({attribute:!1})],Pc.prototype,"renderInputOption",void 0),i([ft({attribute:!1})],Pc.prototype,"renderOption",void 0),i([ft({attribute:!1})],Pc.prototype,"renderOptionName",void 0),i([ft({attribute:!1})],Pc.prototype,"renderOptionDetail",void 0),i([ft({type:Number})],Pc.prototype,"scrollHeight",void 0),i([ft({type:Boolean})],Pc.prototype,"triggerScroll",void 0),i([ft({type:Boolean})],Pc.prototype,"showEmptyMessage",void 0);class Ic extends Ke{static get styles(){return d`
1134
+ `}}i([ft({type:Number})],Pc.prototype,"top",void 0),i([ft({type:Number})],Pc.prototype,"left",void 0),i([ft({type:Number})],Pc.prototype,"width",void 0),i([ft({type:Number,attribute:"min-width"})],Pc.prototype,"minWidth",void 0),i([ft({type:Number,attribute:"static-width"})],Pc.prototype,"staticWidth",void 0),i([ft({type:Boolean,attribute:"anchor-right"})],Pc.prototype,"anchorRight",void 0),i([ft({type:Number})],Pc.prototype,"marginHorizontal",void 0),i([ft({type:Number})],Pc.prototype,"marginVertical",void 0),i([ft({type:Object})],Pc.prototype,"anchorTo",void 0),i([ft({type:Boolean})],Pc.prototype,"visible",void 0),i([ft({type:Boolean})],Pc.prototype,"block",void 0),i([ft({type:Boolean})],Pc.prototype,"cursorHover",void 0),i([ft({type:Boolean})],Pc.prototype,"cursorSelection",void 0),i([ft({type:Number})],Pc.prototype,"scrollPct",void 0),i([ft({type:Number})],Pc.prototype,"cursorIndex",void 0),i([ft({type:Boolean})],Pc.prototype,"internalFocusDisabled",void 0),i([ft({type:Array})],Pc.prototype,"options",void 0),i([ft({type:Array})],Pc.prototype,"tempOptions",void 0),i([ft({type:Boolean})],Pc.prototype,"poppedTop",void 0),i([ft({type:Boolean})],Pc.prototype,"spaceSelect",void 0),i([ft({type:String})],Pc.prototype,"nameKey",void 0),i([ft({type:Boolean})],Pc.prototype,"loading",void 0),i([ft({type:Boolean})],Pc.prototype,"collapsed",void 0),i([ft({type:Boolean})],Pc.prototype,"hideShadow",void 0),i([ft({attribute:!1})],Pc.prototype,"getName",void 0),i([ft({attribute:!1})],Pc.prototype,"renderInputOption",void 0),i([ft({attribute:!1})],Pc.prototype,"renderOption",void 0),i([ft({attribute:!1})],Pc.prototype,"renderDivider",void 0),i([ft({attribute:!1})],Pc.prototype,"renderOptionName",void 0),i([ft({attribute:!1})],Pc.prototype,"renderOptionDetail",void 0),i([ft({type:Number})],Pc.prototype,"scrollHeight",void 0),i([ft({type:Boolean})],Pc.prototype,"triggerScroll",void 0),i([ft({type:Boolean})],Pc.prototype,"showEmptyMessage",void 0);class Ic extends Ke{static get styles(){return d`
1094
1135
  :host {
1095
1136
  margin: auto;
1096
1137
  }
@@ -1254,10 +1295,14 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1254
1295
  border-color: var(--pill-border, var(--border));
1255
1296
  --icon-color: var(--text-2);
1256
1297
  }
1298
+ /* Anchor-derived variants carry static pre-mixed bg/border values
1299
+ for browsers without color-mix() (pre-Chrome 111); the @supports
1300
+ block at the bottom re-derives them from the anchors so host
1301
+ re-theming still works where color-mix() is available. */
1257
1302
  .pill-flow {
1258
- background: color-mix(in srgb, var(--flow) 12%, white);
1303
+ background: #e3f4e9;
1259
1304
  color: var(--flow);
1260
- border-color: color-mix(in srgb, var(--flow) 25%, white);
1305
+ border-color: #c5e8d2;
1261
1306
  --icon-color: var(--flow);
1262
1307
  }
1263
1308
  /* Recipient color — shared by contacts and groups. Anchored to
@@ -1265,27 +1310,27 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1265
1310
  identity even when the host page re-themes via --primary-rgb. */
1266
1311
  .pill-contact,
1267
1312
  .pill-group {
1268
- background: color-mix(in srgb, var(--recipient) 12%, white);
1313
+ background: #e5eef6;
1269
1314
  color: var(--recipient);
1270
- border-color: color-mix(in srgb, var(--recipient) 25%, white);
1315
+ border-color: #cadbec;
1271
1316
  --icon-color: var(--recipient);
1272
1317
  }
1273
1318
  .pill-channel {
1274
- background: color-mix(in srgb, var(--channel) 12%, white);
1319
+ background: #ede4f5;
1275
1320
  color: var(--channel);
1276
- border-color: color-mix(in srgb, var(--channel) 25%, white);
1321
+ border-color: #dac8e9;
1277
1322
  --icon-color: var(--channel);
1278
1323
  }
1279
1324
  .pill-topic {
1280
- background: color-mix(in srgb, var(--topic) 12%, white);
1325
+ background: #faefe1;
1281
1326
  color: var(--topic);
1282
- border-color: color-mix(in srgb, var(--topic) 25%, white);
1327
+ border-color: #f6ddc1;
1283
1328
  --icon-color: var(--topic);
1284
1329
  }
1285
1330
  .pill-campaign {
1286
- background: color-mix(in srgb, var(--campaign) 12%, white);
1331
+ background: #e1f2f6;
1287
1332
  color: var(--campaign);
1288
- border-color: color-mix(in srgb, var(--campaign) 25%, white);
1333
+ border-color: #c1e4ec;
1289
1334
  --icon-color: var(--campaign);
1290
1335
  }
1291
1336
  .pill-field {
@@ -1325,6 +1370,34 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1325
1370
  border-color: var(--pill-border, var(--border));
1326
1371
  --icon-color: var(--text-2);
1327
1372
  }
1373
+
1374
+ /* Anchor-derived bg/border for browsers with color-mix(). These
1375
+ can't be simple same-rule fallbacks: a declaration containing
1376
+ var() isn't dropped at parse time, it goes invalid at
1377
+ computed-value time and takes the earlier declaration with it. */
1378
+ @supports (color: color-mix(in srgb, red, red)) {
1379
+ .pill-flow {
1380
+ background: color-mix(in srgb, var(--flow) 12%, white);
1381
+ border-color: color-mix(in srgb, var(--flow) 25%, white);
1382
+ }
1383
+ .pill-contact,
1384
+ .pill-group {
1385
+ background: color-mix(in srgb, var(--recipient) 12%, white);
1386
+ border-color: color-mix(in srgb, var(--recipient) 25%, white);
1387
+ }
1388
+ .pill-channel {
1389
+ background: color-mix(in srgb, var(--channel) 12%, white);
1390
+ border-color: color-mix(in srgb, var(--channel) 25%, white);
1391
+ }
1392
+ .pill-topic {
1393
+ background: color-mix(in srgb, var(--topic) 12%, white);
1394
+ border-color: color-mix(in srgb, var(--topic) 25%, white);
1395
+ }
1396
+ .pill-campaign {
1397
+ background: color-mix(in srgb, var(--campaign) 12%, white);
1398
+ border-color: color-mix(in srgb, var(--campaign) 25%, white);
1399
+ }
1400
+ }
1328
1401
  `,$h=[{pattern:/\/groups(\.json|\/|\?|$)/,type:"group"},{pattern:/\/contacts(\.json|\/|\?|$)/,type:"contact"},{pattern:/\/labels(\.json|\/|\?|$)/,type:"label"},{pattern:/\/flows(\.json|\/|\?|$)/,type:"flow"},{pattern:/\/fields(\.json|\/|\?|$)/,type:"field"},{pattern:/\/topics(\.json|\/|\?|$)/,type:"topic"}];class Th extends zo{static get styles(){return d`
1329
1402
  ${super.styles}
1330
1403
  ${Sh}
@@ -1614,14 +1687,27 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
1614
1687
  margin: 0;
1615
1688
  border: 0;
1616
1689
  border-radius: 999px;
1617
- background: color-mix(in oklab, currentColor 25%, transparent);
1690
+ /* Neutral wash first for browsers without color-mix(); the
1691
+ currentColor-tinted version below needs the @supports gate
1692
+ because currentColor keeps the declaration valid until
1693
+ computed-value time. */
1694
+ background: rgba(0, 0, 0, 0.12);
1618
1695
  color: inherit;
1619
1696
  opacity: 0.8;
1620
1697
  --icon-color: currentColor;
1621
1698
  }
1622
1699
  .multi .remove-item:hover {
1623
1700
  opacity: 1;
1624
- background: color-mix(in oklab, currentColor 45%, transparent);
1701
+ background: rgba(0, 0, 0, 0.22);
1702
+ }
1703
+
1704
+ @supports (color: color-mix(in srgb, red, red)) {
1705
+ .multi .remove-item {
1706
+ background: color-mix(in oklab, currentColor 25%, transparent);
1707
+ }
1708
+ .multi .remove-item:hover {
1709
+ background: color-mix(in oklab, currentColor 45%, transparent);
1710
+ }
1625
1711
  }
1626
1712
 
1627
1713
  input {
@@ -2518,9 +2604,11 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
2518
2604
  background: var(--success, #16a34a);
2519
2605
  color: #fff;
2520
2606
  }
2607
+ /* Hover darkening: static pre-mixed values first for browsers
2608
+ without color-mix(), re-derived from the token below. */
2521
2609
  .attention-button:hover,
2522
2610
  .affirmative:hover {
2523
- background: color-mix(in srgb, var(--success, #16a34a) 88%, black);
2611
+ background: #138f41;
2524
2612
  }
2525
2613
 
2526
2614
  /* DS .btn-danger — flat danger fill (no lift). */
@@ -2529,7 +2617,17 @@ class nd{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._re
2529
2617
  color: #fff;
2530
2618
  }
2531
2619
  .destructive-button:hover {
2532
- background: color-mix(in srgb, var(--danger, #d03f3f) 88%, black);
2620
+ background: #b73737;
2621
+ }
2622
+
2623
+ @supports (color: color-mix(in srgb, red, red)) {
2624
+ .attention-button:hover,
2625
+ .affirmative:hover {
2626
+ background: color-mix(in srgb, var(--success, #16a34a) 88%, black);
2627
+ }
2628
+ .destructive-button:hover {
2629
+ background: color-mix(in srgb, var(--danger, #d03f3f) 88%, black);
2630
+ }
2533
2631
  }
2534
2632
 
2535
2633
  /* DS .btn-ghost — text-only, hover fills with sunken */
@@ -3234,19 +3332,15 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
3234
3332
  same theme vars the flat fills used — color-mix keeps host
3235
3333
  re-theming working — with a whisper of shadow for depth and
3236
3334
  a hairline border mixed just darker than the fill so bubbles
3237
- hold their edge against the background. */
3335
+ hold their edge against the background. Base rules carry flat
3336
+ fills and pre-mixed borders for browsers without color-mix()
3337
+ (pre-Chrome 111); the @supports block below layers the
3338
+ gradients on top. */
3238
3339
  .bubble {
3239
3340
  padding: 10px 14px;
3240
- background: linear-gradient(
3241
- 180deg,
3242
- color-mix(in srgb, var(--color-chat-in, #e5e5ea) 62%, white) 0%,
3243
- var(--color-chat-in, #e5e5ea) 100%
3244
- );
3341
+ background: var(--color-chat-in, #e5e5ea);
3245
3342
  border-radius: 18px;
3246
- border: var(
3247
- --chat-border-in,
3248
- 1px solid color-mix(in srgb, var(--color-chat-in, #e5e5ea) 93%, black)
3249
- );
3343
+ border: var(--chat-border-in, 1px solid #d5d5da);
3250
3344
  box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06);
3251
3345
  }
3252
3346
 
@@ -3266,20 +3360,40 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
3266
3360
  }
3267
3361
 
3268
3362
  .incoming .bubble {
3269
- background: linear-gradient(
3270
- 180deg,
3271
- color-mix(in srgb, var(--color-chat-out, #007aff) 90%, white) 0%,
3272
- var(--color-chat-out, #007aff) 58%,
3273
- color-mix(in srgb, var(--color-chat-out, #007aff) 95%, black) 100%
3274
- );
3275
- border: var(
3276
- --chat-border-out,
3277
- 1px solid
3278
- color-mix(in srgb, var(--color-chat-out, #007aff) 90%, black)
3279
- );
3363
+ background: var(--color-chat-out, #007aff);
3364
+ border: var(--chat-border-out, 1px solid #006ee6);
3280
3365
  color: white;
3281
3366
  }
3282
3367
 
3368
+ @supports (color: color-mix(in srgb, red, red)) {
3369
+ .bubble {
3370
+ background: linear-gradient(
3371
+ 180deg,
3372
+ color-mix(in srgb, var(--color-chat-in, #e5e5ea) 62%, white) 0%,
3373
+ var(--color-chat-in, #e5e5ea) 100%
3374
+ );
3375
+ border: var(
3376
+ --chat-border-in,
3377
+ 1px solid
3378
+ color-mix(in srgb, var(--color-chat-in, #e5e5ea) 93%, black)
3379
+ );
3380
+ }
3381
+
3382
+ .incoming .bubble {
3383
+ background: linear-gradient(
3384
+ 180deg,
3385
+ color-mix(in srgb, var(--color-chat-out, #007aff) 90%, white) 0%,
3386
+ var(--color-chat-out, #007aff) 58%,
3387
+ color-mix(in srgb, var(--color-chat-out, #007aff) 95%, black) 100%
3388
+ );
3389
+ border: var(
3390
+ --chat-border-out,
3391
+ 1px solid
3392
+ color-mix(in srgb, var(--color-chat-out, #007aff) 90%, black)
3393
+ );
3394
+ }
3395
+ }
3396
+
3283
3397
  .incoming .latest .bubble {
3284
3398
  border-bottom-right-radius: 4px;
3285
3399
  }
@@ -3289,8 +3403,11 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
3289
3403
  }
3290
3404
 
3291
3405
  /* Notes get the same top-lit gradient treatment as message
3292
- bubbles, derived from their sticky-note yellow. */
3406
+ bubbles, derived from their sticky-note yellow. The flat fill
3407
+ first is the fallback for browsers without color-mix() — all
3408
+ literals here, so the invalid gradient drops at parse time. */
3293
3409
  .note .bubble {
3410
+ background: #fffac3;
3294
3411
  background: linear-gradient(
3295
3412
  180deg,
3296
3413
  color-mix(in srgb, #fffac3 62%, white) 0%,
@@ -4048,10 +4165,18 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4048
4165
 
4049
4166
  /* While the contact is in a flow the compose outline carries the
4050
4167
  flow hue: resting border matches the flow pill border, focus
4051
- goes solid flow green */
4168
+ goes solid flow green. The pre-mixed static comes first — a
4169
+ custom property can't fall back per-declaration, so the
4170
+ derived version needs the @supports gate. */
4052
4171
  .in-flow .compose {
4053
- --compose-border: 1px solid
4054
- color-mix(in srgb, var(--flow, #16a34a) 25%, white);
4172
+ --compose-border: 1px solid #c5e8d2;
4173
+ }
4174
+
4175
+ @supports (color: color-mix(in srgb, red, red)) {
4176
+ .in-flow .compose {
4177
+ --compose-border: 1px solid
4178
+ color-mix(in srgb, var(--flow, #16a34a) 25%, white);
4179
+ }
4055
4180
  }
4056
4181
 
4057
4182
  .in-flow .compose temba-compose {
@@ -4367,10 +4492,18 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4367
4492
  status-area grey. Fallbacks match the --flow design token for
4368
4493
  pages without tokens. */
4369
4494
  .in-flow .contact-status {
4370
- background: color-mix(in srgb, var(--flow, #16a34a) 12%, white);
4495
+ /* pre-mixed statics first for browsers without color-mix() */
4496
+ background: #e3f4e9;
4371
4497
  color: var(--flow, #16a34a);
4372
4498
  --icon-color: var(--flow, #16a34a);
4373
- border-top-color: color-mix(in srgb, var(--flow, #16a34a) 25%, white);
4499
+ border-top-color: #c5e8d2;
4500
+ }
4501
+
4502
+ @supports (color: color-mix(in srgb, red, red)) {
4503
+ .in-flow .contact-status {
4504
+ background: color-mix(in srgb, var(--flow, #16a34a) 12%, white);
4505
+ border-top-color: color-mix(in srgb, var(--flow, #16a34a) 25%, white);
4506
+ }
4374
4507
  }
4375
4508
 
4376
4509
  /* compact the interrupt button to the row's caption scale */
@@ -4438,7 +4571,14 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4438
4571
  }
4439
4572
 
4440
4573
  .in-flow .chat-box {
4441
- background: color-mix(in srgb, var(--flow, #16a34a) 12%, white);
4574
+ /* pre-mixed static first for browsers without color-mix() */
4575
+ background: #e3f4e9;
4576
+ }
4577
+
4578
+ @supports (color: color-mix(in srgb, red, red)) {
4579
+ .in-flow .chat-box {
4580
+ background: color-mix(in srgb, var(--flow, #16a34a) 12%, white);
4581
+ }
4442
4582
  }
4443
4583
 
4444
4584
  .ticket-controls {
@@ -4487,7 +4627,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4487
4627
  temba-button {
4488
4628
  --button-border: 1px solid #ddd;
4489
4629
  }
4490
- `}set showMessageLogsAfter(t){const e=this._showMessageLogsAfter;this._showMessageLogsAfter=t?new Date(t):null,this.requestUpdate("showMessageLogsAfter",e)}get showMessageLogsAfter(){return this._showMessageLogsAfter}constructor(){super(),this.watchTypes=null,this.contactsEndpoint="/api/v2/contacts.json",this.currentNote="",this.showDetails=!0,this.currentTicket=null,this.currentContact=null,this.agent="",this.userUuid="",this.blockFetching=!1,this.showInterrupt=!1,this.disableAssign=!1,this.disableReply=!1,this.showSearch=!1,this.avatar=kd,this._showMessageLogsAfter=null,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchFocused=!1,this.searchClosing=!1,this.searchNoResults=!1,this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.subscriptions=new Map,this.fetchingMissed=!1,this.lastIncomingMsgOn=null,this.lastIncomingMsgExternalId=null,this.typingChannel=null,this.typingPulse=null,this.typingDisabled=!1,this.stateRefresh=null,this.lastSearchedQuery="",this.searchGeneration=0,this.blockFetchingNewer=!1,this.fetchingNewer=!1}willUpdate(t){if(super.willUpdate(t),t.has("data")&&(this.currentContact=this.data),t.has("currentContact")&&this.currentContact){const e=t.get("currentContact");this.currentContact.uuid!==(null==e?void 0:e.uuid)&&(this.blockFetching=!1,this.errorMessage=null)}}firstUpdated(t){super.firstUpdated(t)}connectedCallback(){super.connectedCallback(),this.chat=this.shadowRoot.querySelector("temba-chat"),this.updateSubscriptions(),this.stateRefresh=window.setInterval(()=>this.requestUpdate(),6e4)}disconnectedCallback(){super.disconnectedCallback(),this.stopTyping(),this.unsubscribeAll(),window.clearInterval(this.stateRefresh),this.stateRefresh=null}updated(t){var e;super.updated(t),(t.has("currentContact")||t.has("currentTicket"))&&this.updateSubscriptions(),t.has("currentContact")&&this.currentContact&&(this.chat=this.shadowRoot.querySelector("temba-chat"),this.currentContact.uuid!==(null===(e=t.get("currentContact"))||void 0===e?void 0:e.uuid)?this.reset():this.fetchMissedEvents(),this.fetchPreviousMessages())}unsubscribeAll(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions.clear()}updateSubscriptions(){const t=new Map;if(this.isConnected&&this.currentContact){const e=this.currentContact.uuid;t.set(e,{contact:e,ticket:null});const i=this.contact&&this.contact!==e;this.currentTicket&&!i&&t.set(`${e}:${this.currentTicket.uuid}`,{contact:e,ticket:this.currentTicket.uuid})}this.subscriptions.forEach((e,i)=>{t.has(i)||(e.unsubscribe(),this.subscriptions.delete(i))}),t.forEach((t,e)=>{this.subscriptions.has(e)||this.subscriptions.set(e,Ps(t.contact,t.ticket,t=>this.handleSocketEvent(t),()=>this.fetchMissedEvents()))})}handleSocketEvent(t){if(!this.currentContact)return;if(t.type===Kh.CONTACT_LAST_SEEN_CHANGED||t.type===Kh.CONTACT_FLOW_CHANGED)return void this.handleContactStateEvent(t);if(!this.chat||this.searchMode)return;if("typing_started"===t.type||"typing_stopped"===t.type)return void this.handleTypingEvent(t);const e=this.createMessages({events:[t],next:null});e.length>0&&this.chat.addMessages(e,null,!0)}handleContactStateEvent(t){const e=this.currentContact;if(t.type===Kh.CONTACT_LAST_SEEN_CHANGED){const i=t.last_seen_on;(!e.last_seen_on||new Date(i)>new Date(e.last_seen_on))&&(e.last_seen_on=i)}else e.flow=t.flow||null;this.requestUpdate()}getLastSeen(){var t;const e=null===(t=this.currentContact)||void 0===t?void 0:t.last_seen_on;if(!e||!this.store)return null;const i=Ql.fromISO(e);return Ql.now().diff(i,"minutes").minutes<60?null:{duration:this.store.getShortDuration(i),title:i.toLocaleString(Ql.DATETIME_SHORT)}}handleTypingEvent(t){t._user&&this.userUuid&&t._user.uuid===this.userUuid||(t.created_on=new Date(t.created_on),this.resolveUserAvatar(t),"typing_started"===t.type?this.chat.setTyping(t):this.chat.clearTyping(t))}handleComposeChanged(t){const e=Object.values(t.detail||{}).some(t=>{var e;return null===(e=null==t?void 0:t.text)||void 0===e?void 0:e.trim()});e?this.startTyping():this.stopTyping()}getTypingPayload(t){const e={type:t};return this.lastIncomingMsgExternalId&&(e.msg_external_id=this.lastIncomingMsgExternalId),e}startTyping(){this.typingDisabled||this.typingPulse||!this.currentContact||(this.typingChannel=`history:${this.currentContact.uuid}`,this.sendTypingPulse(),this.typingPulse=window.setInterval(()=>this.sendTypingPulse(),4e3))}sendTypingPulse(){if(!this.typingChannel)return;const t=this.typingChannel;As(t,this.getTypingPayload("typing_started")).catch(e=>{!(null==e?void 0:e.temporary)&&this.isCurrentTypingChannel(t)&&(this.typingDisabled=!0,this.clearTypingPulse())})}isCurrentTypingChannel(t){var e;return t===`history:${null===(e=this.currentContact)||void 0===e?void 0:e.uuid}`}clearTypingPulse(){this.typingPulse&&(window.clearInterval(this.typingPulse),this.typingPulse=null),this.typingChannel=null}stopTyping(){if(!this.typingPulse)return;const t=this.typingChannel;this.clearTypingPulse(),As(t,this.getTypingPayload("typing_stopped")).catch(e=>{!(null==e?void 0:e.temporary)&&this.isCurrentTypingChannel(t)&&(this.typingDisabled=!0)})}reset(){this.chat&&this.chat.reset(),this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.fetchingMissed=!1,this.stopTyping(),this.typingDisabled=!1,this.lastIncomingMsgOn=null,this.lastIncomingMsgExternalId=null;const t=this.shadowRoot.querySelector("temba-compose");t&&t.reset()}handleSearchToggle(){this.searchMode?this.handleSearchClose():(this.searchMode=!0,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,window.setTimeout(()=>{const t=this.shadowRoot.querySelector(".search-input");t&&t.focus()},50))}restoreUnsearchedView(){const t=this.chat;t&&(t.searchHighlight=null,t.highlightMessageUuid=null,t.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages())}handleSearchClose(){this.searchGeneration++,this.searchClosing=!0,window.setTimeout(()=>{this.searchClosing=!1,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,this.lastSearchedQuery="",this.restoreUnsearchedView()},150)}handleSearchInput(t){const e=t.target;if(this.searchQuery=e.value,this.searchQuery.trim()!==this.lastSearchedQuery){const t=""!==this.lastSearchedQuery;this.searchGeneration++,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1,this.lastSearchedQuery="",t&&this.restoreUnsearchedView()}}handleSearchKeydown(t){if("Enter"===t.key){t.preventDefault();this.searchQuery.trim()!==this.lastSearchedQuery?this.executeSearch():t.shiftKey?this.handleSearchPrev():this.handleSearchNext()}else"Escape"===t.key&&(this.handleSearchClose(),t.preventDefault())}executeSearch(){const t=this.searchQuery.trim();if(!t||!this.currentContact||this.searchLoading)return;this.searchGeneration++,this.searchLoading=!0,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1,this.lastSearchedQuery=t,this.chat&&(this.chat.searchHighlight=null,this.chat.highlightMessageUuid=null,this.chat.reset());const e=`/contact/chat_search/${this.currentContact.uuid}/?text=${encodeURIComponent(t)}`;fe(e).then(e=>{this.searchLoading=!1,this.lastSearchedQuery===t&&this.searchMode&&(this.searchResults=(e.json.results||[]).sort((t,e)=>e.uuid.toLowerCase().localeCompare(t.uuid.toLowerCase())),this.searchResults.length>0?(this.searchNoResults=!1,this.searchIndex=0,this.navigateToResult(0)):(this.searchNoResults=!0,this.searchIndex=-1))}).catch(()=>{this.searchLoading=!1,this.lastSearchedQuery===t&&this.searchMode&&(this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1)})}navigateToResult(t){var e,i;if(t<0||t>=this.searchResults.length)return;this.searchIndex=t;const o=this.searchResults[t];if(!this.chat)return;const s=this.getEndpoint();if(!s)return;const n=this.searchGeneration,r=()=>n!==this.searchGeneration;this.chat.searchHighlight=this.lastSearchedQuery;const a=ju(s,null===(e=this.currentTicket)||void 0===e?void 0:e.uuid,o.uuid,null),l=ju(s,null===(i=this.currentTicket)||void 0===i?void 0:i.uuid,null,o.uuid);this.chat.style.opacity="0",window.setTimeout(()=>{if(r())return void(this.chat.style.opacity="1");this.chat.style.visibility="hidden",this.chat.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null;const t={...o,created_on:new Date(o.created_on)};let e=!1;Promise.all([a,l]).then(([i,s])=>{if(r())return;const n=this.createMessages(s);n.reverse();const a=this.createMessages(i);a.reverse();const l={events:[t],next:null},d=this.createMessages(l);if(d.reverse(),i.next)this.beforeUUID=i.next;else if(a.length>0){const t=i.events[i.events.length-1];this.beforeUUID=t.uuid}else{this.blockFetching=!0;const t=[...n,...d];if(t.length>0){const e=t[t.length-1];this.chat.setEndOfHistory(new Date(e.created_on))}}const c=[...a,...d,...n];this.chat.loadMessages(c),e=!0,this.chat.updateComplete.then(()=>{window.setTimeout(()=>{var t,e;if(!this.chat)return;if(r())return this.chat.style.visibility="visible",void(this.chat.style.opacity="1");this.chat.highlightMessageUuid=o.uuid;const i=null===(t=this.chat.shadowRoot)||void 0===t?void 0:t.querySelector(".scroll"),s=null===(e=this.chat.shadowRoot)||void 0===e?void 0:e.querySelector(`.row[data-uuid="${o.uuid}"]`);if(i&&s){const t=i.getBoundingClientRect(),e=s.getBoundingClientRect(),o=e.top+e.height/2-(t.top+t.height/2);i.scrollTop=i.scrollTop+o}else i&&(i.scrollTop=0);window.setTimeout(()=>{this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="0",window.setTimeout(()=>{this.chat&&(this.chat.style.opacity="1")},16))},16)},16)})}).catch(()=>{r()||(this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages())}).finally(()=>{!e&&this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="1")})},120)}handleSearchPrev(){if(0===this.searchResults.length)return;const t=this.searchIndex<=0?this.searchResults.length-1:this.searchIndex-1;this.navigateToResult(t)}handleSearchNext(){if(0===this.searchResults.length)return;const t=this.searchIndex>=this.searchResults.length-1?0:this.searchIndex+1;this.navigateToResult(t)}handleInterrupt(){this.fireCustomEvent(Wo.Interrupt,{contact:this.currentContact})}handleRetry(){this.shadowRoot.querySelector("temba-compose").triggerSend()}handleSend(t){this.errorMessage=null;const e=t.currentTarget,i=t.detail.langValues.und,o={contact:this.currentContact.uuid},s=i.text;s&&s.length>0&&(o.text=s);const n=i.attachments;if(n&&n.length>0){const t=n.map(t=>t.uuid);o.attachments=t}this.currentTicket&&(o.ticket=this.currentTicket.uuid);const r="Send failed, please try again.";ke(`/contact/chat/${this.currentContact.uuid}/`,o).then(t=>{if(t.status<400){const i=t.json.event;i.created_on=new Date(i.created_on),this.resolveUserAvatar(i),this.chat.addMessages([i],null,!0),e.reset(),this.fireCustomEvent(Wo.MessageSent,{msg:o,response:t})}else this.errorMessage=r}).catch(()=>{this.errorMessage=r})}getEndpoint(){return this.contact?`/contact/chat/${this.contact}/`:null}prerender(t){const e=du(t,!1);e&&(t._rendered={html:e,type:Ou.Inline})}resolveUserAvatar(t){for(const e of[t._user,t.assignee])e&&e.uuid&&this.store&&(e.avatar?this.store.setUserAvatar(e.uuid,e.avatar):e.avatar=this.store.getUserAvatar(e.uuid))}createMessages(t){if(t.events){const e=[];return t.events.forEach(t=>{var i;this.resolveUserAvatar(t),(!this.afterUUID||t.uuid.toLowerCase()>this.afterUUID.toLowerCase())&&(this.afterUUID=t.uuid),t.created_on=new Date(t.created_on),"msg_received"===t.type&&(!this.lastIncomingMsgOn||t.created_on>this.lastIncomingMsgOn)&&(this.lastIncomingMsgOn=t.created_on,this.lastIncomingMsgExternalId=(null===(i=t.msg)||void 0===i?void 0:i.external_id)||null),"msg_created"===t.type||"msg_received"===t.type||"ivr_created"===t.type||"ticket_note_added"===t.type?e.push(t):(this.prerender(t),t._rendered&&e.push(t))}),e.filter(t=>!!t)}return[]}fetchMissedEvents(){var t;if(this.fetchingMissed||this.searchMode)return;const e=this.chat;if(this.currentContact&&this.afterUUID){this.fetchingMissed=!0;const i=this.getEndpoint();if(!i)return void(this.fetchingMissed=!1);const o=this.currentContact.uuid,s=null===(t=this.currentTicket)||void 0===t?void 0:t.uuid;ju(i,s,null,this.afterUUID).then(t=>{var i,n;if(this.fetchingMissed=!1,this.searchMode||o!==(null===(i=this.currentContact)||void 0===i?void 0:i.uuid)||s!==(null===(n=this.currentTicket)||void 0===n?void 0:n.uuid))return;const r=this.createMessages(t);r.reverse(),e.addMessages(r,null,!0)})}}fetchPreviousMessages(){var t;const e=this.chat,i=this;if(e&&!e.fetching&&!i.blockFetching&&(e.fetching=!0,this.currentContact)){const o=this.getEndpoint();if(!o)return;if(!this.beforeUUID&&!this.afterUUID){const t=Jt();this.beforeUUID=t,this.afterUUID=t}ju(o,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,this.beforeUUID,null).then(t=>{const o=this.createMessages(t);if(o.reverse(),0===o.length)i.blockFetching=!0;else if(t.next)this.beforeUUID=t.next;else if(i.blockFetching=!0,t.events&&t.events.length>0){const i=t.events[t.events.length-1];e.setEndOfHistory(new Date(i.created_on))}e.addMessages(o)})}}fetchComplete(){this.chat&&(this.chat.fetching=!1),this.fetchingNewer=!1}fetchNewerMessages(){var t;if(!this.searchMode||!this.afterUUID||!this.chat||this.fetchingNewer||this.blockFetchingNewer)return;this.fetchingNewer=!0;const e=this.getEndpoint();e?ju(e,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,null,this.afterUUID).then(t=>{if(!this.chat)return void(this.fetchingNewer=!1);const e=this.createMessages(t);if(e.reverse(),0===e.length)return this.blockFetchingNewer=!0,void(this.fetchingNewer=!1);this.chat.addMessages(e,null,!0,!0)}).catch(()=>{this.fetchingNewer=!1}):this.fetchingNewer=!1}getTembaCompose(){return this.currentTicket?this.currentContact&&"active"!==this.currentContact.status||this.currentTicket.closed_on?null:!this.disableReply||this.currentTicket.assignee&&this.currentTicket.assignee.email===this.agent?this.getCompose():null:this.currentContact&&"active"!==this.currentContact.status?null:this.getCompose()}getCompose(){return G`<div class="chat-box">
4630
+ `}set showMessageLogsAfter(t){const e=this._showMessageLogsAfter;this._showMessageLogsAfter=t?new Date(t):null,this.requestUpdate("showMessageLogsAfter",e)}get showMessageLogsAfter(){return this._showMessageLogsAfter}constructor(){super(),this.watchTypes=null,this.contactsEndpoint="/api/v2/contacts.json",this.currentNote="",this.showDetails=!0,this.currentTicket=null,this.currentContact=null,this.agent="",this.userUuid="",this.blockFetching=!1,this.showInterrupt=!1,this.disableAssign=!1,this.disableReply=!1,this.showSearch=!1,this.avatar=kd,this._showMessageLogsAfter=null,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchFocused=!1,this.searchClosing=!1,this.searchNoResults=!1,this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.subscriptions=new Map,this.fetchingMissed=!1,this.lastIncomingMsgOn=null,this.lastIncomingMsgExternalId=null,this.typingChannel=null,this.typingPulse=null,this.typingDisabled=!1,this.stateRefresh=null,this.lastSearchedQuery="",this.searchGeneration=0,this.blockFetchingNewer=!1,this.fetchingNewer=!1}willUpdate(t){if(super.willUpdate(t),t.has("data")&&(this.currentContact=this.data),t.has("currentContact")&&this.currentContact){const e=t.get("currentContact");this.currentContact.uuid!==(null==e?void 0:e.uuid)&&(this.blockFetching=!1,this.errorMessage=null)}}firstUpdated(t){super.firstUpdated(t)}connectedCallback(){super.connectedCallback(),this.chat=this.shadowRoot.querySelector("temba-chat"),this.updateSubscriptions(),this.stateRefresh=window.setInterval(()=>this.requestUpdate(),6e4)}disconnectedCallback(){super.disconnectedCallback(),this.stopTyping(),this.unsubscribeAll(),window.clearInterval(this.stateRefresh),this.stateRefresh=null}updated(t){var e;super.updated(t),(t.has("currentContact")||t.has("currentTicket"))&&this.updateSubscriptions(),t.has("currentContact")&&this.currentContact&&(this.chat=this.shadowRoot.querySelector("temba-chat"),this.currentContact.uuid!==(null===(e=t.get("currentContact"))||void 0===e?void 0:e.uuid)?this.reset():this.fetchMissedEvents(),this.fetchPreviousMessages())}unsubscribeAll(){this.subscriptions.forEach(t=>t.unsubscribe()),this.subscriptions.clear()}updateSubscriptions(){const t=new Map;if(this.isConnected&&this.currentContact){const e=this.currentContact.uuid;t.set(e,{contact:e,ticket:null});const i=this.contact&&this.contact!==e;this.currentTicket&&!i&&t.set(`${e}:${this.currentTicket.uuid}`,{contact:e,ticket:this.currentTicket.uuid})}this.subscriptions.forEach((e,i)=>{t.has(i)||(e.unsubscribe(),this.subscriptions.delete(i))}),t.forEach((t,e)=>{this.subscriptions.has(e)||this.subscriptions.set(e,Ps(t.contact,t.ticket,t=>this.handleSocketEvent(t),()=>this.fetchMissedEvents()))})}handleSocketEvent(t){if(!this.currentContact)return;if(t.type===Kh.CONTACT_LAST_SEEN_CHANGED||t.type===Kh.CONTACT_FLOW_CHANGED)return void this.handleContactStateEvent(t);if(!this.chat||this.searchMode)return;if("typing_started"===t.type||"typing_stopped"===t.type)return void this.handleTypingEvent(t);const e=this.createMessages({events:[t],next:null});e.length>0&&this.chat.addMessages(e,null,!0)}handleContactStateEvent(t){const e=this.currentContact;if(t.type===Kh.CONTACT_LAST_SEEN_CHANGED){const i=t.last_seen_on;(!e.last_seen_on||new Date(i)>new Date(e.last_seen_on))&&(e.last_seen_on=i)}else e.flow=t.flow||null;this.requestUpdate()}getLastSeen(){var t;const e=null===(t=this.currentContact)||void 0===t?void 0:t.last_seen_on;if(!e||!this.store)return null;const i=Ql.fromISO(e);if(!i.isValid||i.year<=1)return null;return Ql.now().diff(i,"minutes").minutes<60?null:{duration:this.store.getShortDuration(i),title:i.toLocaleString(Ql.DATETIME_SHORT)}}handleTypingEvent(t){t._user&&this.userUuid&&t._user.uuid===this.userUuid||(t.created_on=new Date(t.created_on),this.resolveUserAvatar(t),"typing_started"===t.type?this.chat.setTyping(t):this.chat.clearTyping(t))}handleComposeChanged(t){const e=Object.values(t.detail||{}).some(t=>{var e;return null===(e=null==t?void 0:t.text)||void 0===e?void 0:e.trim()});e?this.startTyping():this.stopTyping()}getTypingPayload(t){const e={type:t};return this.lastIncomingMsgExternalId&&(e.msg_external_id=this.lastIncomingMsgExternalId),e}startTyping(){this.typingDisabled||this.typingPulse||!this.currentContact||(this.typingChannel=`history:${this.currentContact.uuid}`,this.sendTypingPulse(),this.typingPulse=window.setInterval(()=>this.sendTypingPulse(),4e3))}sendTypingPulse(){if(!this.typingChannel)return;const t=this.typingChannel;As(t,this.getTypingPayload("typing_started")).catch(e=>{!(null==e?void 0:e.temporary)&&this.isCurrentTypingChannel(t)&&(this.typingDisabled=!0,this.clearTypingPulse())})}isCurrentTypingChannel(t){var e;return t===`history:${null===(e=this.currentContact)||void 0===e?void 0:e.uuid}`}clearTypingPulse(){this.typingPulse&&(window.clearInterval(this.typingPulse),this.typingPulse=null),this.typingChannel=null}stopTyping(){if(!this.typingPulse)return;const t=this.typingChannel;this.clearTypingPulse(),As(t,this.getTypingPayload("typing_stopped")).catch(e=>{!(null==e?void 0:e.temporary)&&this.isCurrentTypingChannel(t)&&(this.typingDisabled=!0)})}reset(){this.chat&&this.chat.reset(),this.ticket=null,this.beforeUUID=null,this.afterUUID=null,this.fetchingMissed=!1,this.stopTyping(),this.typingDisabled=!1,this.lastIncomingMsgOn=null,this.lastIncomingMsgExternalId=null;const t=this.shadowRoot.querySelector("temba-compose");t&&t.reset()}handleSearchToggle(){this.searchMode?this.handleSearchClose():(this.searchMode=!0,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,window.setTimeout(()=>{const t=this.shadowRoot.querySelector(".search-input");t&&t.focus()},50))}restoreUnsearchedView(){const t=this.chat;t&&(t.searchHighlight=null,t.highlightMessageUuid=null,t.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages())}handleSearchClose(){this.searchGeneration++,this.searchClosing=!0,window.setTimeout(()=>{this.searchClosing=!1,this.searchMode=!1,this.searchQuery="",this.searchResults=[],this.searchIndex=-1,this.searchLoading=!1,this.searchNoResults=!1,this.lastSearchedQuery="",this.restoreUnsearchedView()},150)}handleSearchInput(t){const e=t.target;if(this.searchQuery=e.value,this.searchQuery.trim()!==this.lastSearchedQuery){const t=""!==this.lastSearchedQuery;this.searchGeneration++,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1,this.lastSearchedQuery="",t&&this.restoreUnsearchedView()}}handleSearchKeydown(t){if("Enter"===t.key){t.preventDefault();this.searchQuery.trim()!==this.lastSearchedQuery?this.executeSearch():t.shiftKey?this.handleSearchPrev():this.handleSearchNext()}else"Escape"===t.key&&(this.handleSearchClose(),t.preventDefault())}executeSearch(){const t=this.searchQuery.trim();if(!t||!this.currentContact||this.searchLoading)return;this.searchGeneration++,this.searchLoading=!0,this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1,this.lastSearchedQuery=t,this.chat&&(this.chat.searchHighlight=null,this.chat.highlightMessageUuid=null,this.chat.reset());const e=`/contact/chat_search/${this.currentContact.uuid}/?text=${encodeURIComponent(t)}`;fe(e).then(e=>{this.searchLoading=!1,this.lastSearchedQuery===t&&this.searchMode&&(this.searchResults=(e.json.results||[]).sort((t,e)=>e.uuid.toLowerCase().localeCompare(t.uuid.toLowerCase())),this.searchResults.length>0?(this.searchNoResults=!1,this.searchIndex=0,this.navigateToResult(0)):(this.searchNoResults=!0,this.searchIndex=-1))}).catch(()=>{this.searchLoading=!1,this.lastSearchedQuery===t&&this.searchMode&&(this.searchResults=[],this.searchIndex=-1,this.searchNoResults=!1)})}navigateToResult(t){var e,i;if(t<0||t>=this.searchResults.length)return;this.searchIndex=t;const o=this.searchResults[t];if(!this.chat)return;const s=this.getEndpoint();if(!s)return;const n=this.searchGeneration,r=()=>n!==this.searchGeneration;this.chat.searchHighlight=this.lastSearchedQuery;const a=ju(s,null===(e=this.currentTicket)||void 0===e?void 0:e.uuid,o.uuid,null),l=ju(s,null===(i=this.currentTicket)||void 0===i?void 0:i.uuid,null,o.uuid);this.chat.style.opacity="0",window.setTimeout(()=>{if(r())return void(this.chat.style.opacity="1");this.chat.style.visibility="hidden",this.chat.reset(),this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null;const t={...o,created_on:new Date(o.created_on)};let e=!1;Promise.all([a,l]).then(([i,s])=>{if(r())return;const n=this.createMessages(s);n.reverse();const a=this.createMessages(i);a.reverse();const l={events:[t],next:null},d=this.createMessages(l);if(d.reverse(),i.next)this.beforeUUID=i.next;else if(a.length>0){const t=i.events[i.events.length-1];this.beforeUUID=t.uuid}else{this.blockFetching=!0;const t=[...n,...d];if(t.length>0){const e=t[t.length-1];this.chat.setEndOfHistory(new Date(e.created_on))}}const c=[...a,...d,...n];this.chat.loadMessages(c),e=!0,this.chat.updateComplete.then(()=>{window.setTimeout(()=>{var t,e;if(!this.chat)return;if(r())return this.chat.style.visibility="visible",void(this.chat.style.opacity="1");this.chat.highlightMessageUuid=o.uuid;const i=null===(t=this.chat.shadowRoot)||void 0===t?void 0:t.querySelector(".scroll"),s=null===(e=this.chat.shadowRoot)||void 0===e?void 0:e.querySelector(`.row[data-uuid="${o.uuid}"]`);if(i&&s){const t=i.getBoundingClientRect(),e=s.getBoundingClientRect(),o=e.top+e.height/2-(t.top+t.height/2);i.scrollTop=i.scrollTop+o}else i&&(i.scrollTop=0);window.setTimeout(()=>{this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="0",window.setTimeout(()=>{this.chat&&(this.chat.style.opacity="1")},16))},16)},16)})}).catch(()=>{r()||(this.blockFetching=!1,this.blockFetchingNewer=!1,this.fetchingNewer=!1,this.beforeUUID=null,this.afterUUID=null,this.fetchPreviousMessages())}).finally(()=>{!e&&this.chat&&(this.chat.style.visibility="visible",this.chat.style.opacity="1")})},120)}handleSearchPrev(){if(0===this.searchResults.length)return;const t=this.searchIndex<=0?this.searchResults.length-1:this.searchIndex-1;this.navigateToResult(t)}handleSearchNext(){if(0===this.searchResults.length)return;const t=this.searchIndex>=this.searchResults.length-1?0:this.searchIndex+1;this.navigateToResult(t)}handleInterrupt(){this.fireCustomEvent(Wo.Interrupt,{contact:this.currentContact})}handleRetry(){this.shadowRoot.querySelector("temba-compose").triggerSend()}handleSend(t){this.errorMessage=null;const e=t.currentTarget,i=t.detail.langValues.und,o={contact:this.currentContact.uuid},s=i.text;s&&s.length>0&&(o.text=s);const n=i.attachments;if(n&&n.length>0){const t=n.map(t=>t.uuid);o.attachments=t}this.currentTicket&&(o.ticket=this.currentTicket.uuid);const r="Send failed, please try again.";ke(`/contact/chat/${this.currentContact.uuid}/`,o).then(t=>{if(t.status<400){const i=t.json.event;i.created_on=new Date(i.created_on),this.resolveUserAvatar(i),this.chat.addMessages([i],null,!0),e.reset(),this.fireCustomEvent(Wo.MessageSent,{msg:o,response:t})}else this.errorMessage=r}).catch(()=>{this.errorMessage=r})}getEndpoint(){return this.contact?`/contact/chat/${this.contact}/`:null}prerender(t){const e=du(t,!1);e&&(t._rendered={html:e,type:Ou.Inline})}resolveUserAvatar(t){for(const e of[t._user,t.assignee])e&&e.uuid&&this.store&&(e.avatar?this.store.setUserAvatar(e.uuid,e.avatar):e.avatar=this.store.getUserAvatar(e.uuid))}createMessages(t){if(t.events){const e=[];return t.events.forEach(t=>{var i;this.resolveUserAvatar(t),(!this.afterUUID||t.uuid.toLowerCase()>this.afterUUID.toLowerCase())&&(this.afterUUID=t.uuid),t.created_on=new Date(t.created_on),"msg_received"===t.type&&(!this.lastIncomingMsgOn||t.created_on>this.lastIncomingMsgOn)&&(this.lastIncomingMsgOn=t.created_on,this.lastIncomingMsgExternalId=(null===(i=t.msg)||void 0===i?void 0:i.external_id)||null),"msg_created"===t.type||"msg_received"===t.type||"ivr_created"===t.type||"ticket_note_added"===t.type?e.push(t):(this.prerender(t),t._rendered&&e.push(t))}),e.filter(t=>!!t)}return[]}fetchMissedEvents(){var t;if(this.fetchingMissed||this.searchMode)return;const e=this.chat;if(this.currentContact&&this.afterUUID){this.fetchingMissed=!0;const i=this.getEndpoint();if(!i)return void(this.fetchingMissed=!1);const o=this.currentContact.uuid,s=null===(t=this.currentTicket)||void 0===t?void 0:t.uuid;ju(i,s,null,this.afterUUID).then(t=>{var i,n;if(this.fetchingMissed=!1,this.searchMode||o!==(null===(i=this.currentContact)||void 0===i?void 0:i.uuid)||s!==(null===(n=this.currentTicket)||void 0===n?void 0:n.uuid))return;const r=this.createMessages(t);r.reverse(),e.addMessages(r,null,!0)})}}fetchPreviousMessages(){var t;const e=this.chat,i=this;if(e&&!e.fetching&&!i.blockFetching&&(e.fetching=!0,this.currentContact)){const o=this.getEndpoint();if(!o)return;if(!this.beforeUUID&&!this.afterUUID){const t=Jt();this.beforeUUID=t,this.afterUUID=t}ju(o,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,this.beforeUUID,null).then(t=>{const o=this.createMessages(t);if(o.reverse(),0===o.length)i.blockFetching=!0;else if(t.next)this.beforeUUID=t.next;else if(i.blockFetching=!0,t.events&&t.events.length>0){const i=t.events[t.events.length-1];e.setEndOfHistory(new Date(i.created_on))}e.addMessages(o)})}}fetchComplete(){this.chat&&(this.chat.fetching=!1),this.fetchingNewer=!1}fetchNewerMessages(){var t;if(!this.searchMode||!this.afterUUID||!this.chat||this.fetchingNewer||this.blockFetchingNewer)return;this.fetchingNewer=!0;const e=this.getEndpoint();e?ju(e,null===(t=this.currentTicket)||void 0===t?void 0:t.uuid,null,this.afterUUID).then(t=>{if(!this.chat)return void(this.fetchingNewer=!1);const e=this.createMessages(t);if(e.reverse(),0===e.length)return this.blockFetchingNewer=!0,void(this.fetchingNewer=!1);this.chat.addMessages(e,null,!0,!0)}).catch(()=>{this.fetchingNewer=!1}):this.fetchingNewer=!1}getTembaCompose(){return this.currentTicket?this.currentContact&&"active"!==this.currentContact.status||this.currentTicket.closed_on?null:!this.disableReply||this.currentTicket.assignee&&this.currentTicket.assignee.email===this.agent?this.getCompose():null:this.currentContact&&"active"!==this.currentContact.status?null:this.getCompose()}getCompose(){return G`<div class="chat-box">
4491
4631
  <div class="compose">
4492
4632
  <temba-compose
4493
4633
  attachments
@@ -4658,7 +4798,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4658
4798
  width: 100%;
4659
4799
  flex-grow: 1;
4660
4800
  }
4661
- `}constructor(){super(),this.items=[],this.cursorIndex=-1,this.tabIndex=1,this.valueKey="id",this.loading=!1,this.paused=!1,this.internalFocusDisabled=!1,this.refreshKey="0",this.reverseRefresh=!0,this.pollingEnabled=!0,this.nextPage=null,this.pages=0,this.pending=[],this.refreshInterval=null,this.store=document.querySelector("temba-store"),this.handleSelection.bind(this)}reset(){this.selected=null,this.nextPage=null,this.cursorIndex=-1,this.mostRecentItem=null,this.items=[]}connectedCallback(){super.connectedCallback(),this.pollingEnabled&&(this.refreshInterval=setInterval(()=>{this.paused||(this.refreshKey="default_"+(new Date).getTime())},1e4))}disconnectedCallback(){super.disconnectedCallback(),clearInterval(this.refreshInterval)}willUpdate(t){super.willUpdate(t),t.has("cursorIndex")&&this.cursorIndex>-1&&(this.selected=this.items[this.cursorIndex]),t.has("endpoint")&&this.endpoint&&(this.loading=!0,this.reset())}updated(t){super.updated(t),t.has("endpoint")&&this.endpoint&&this.fetchItems(),t.has("loading")&&(this.loading||this.fireCustomEvent(Wo.FetchComplete)),t.has("refreshKey")&&!t.has("endpoint")&&this.refreshTop(),t.has("mostRecentItem")&&this.mostRecentItem&&this.fireCustomEvent(Wo.Refreshed),t.has("cursorIndex")&&this.cursorIndex>-1&&this.handleSelected(this.selected),t.has("items")}handleSelected(t){const e=new Event("change",{bubbles:!0});this.dispatchEvent(e)}getValue(t){if(!t)return null;const e=this.valueKey.split(".");let i=t;for(;e.length>0;){i=i[e.shift()]}return i}setSelection(t){const e=this.items.findIndex(e=>this.getValue(e)===t);this.cursorIndex=e,this.selected=this.items[e];const i=new Event("change",{bubbles:!0});this.dispatchEvent(i)}getItemIndex(t){return this.items.findIndex(e=>this.getValue(e)===t)}removeItem(t){const e=this.getItemIndex(t);this.items.splice(e,1),this.items=[...this.items],this.cursorIndex===e&&(this.cursorIndex=-1),this.requestUpdate("cursorIndex"),this.requestUpdate("items")}getSelection(){return this.selected}clearSelection(){this.cursorIndex=-1,this.selected=null,this.value=null}refresh(){this.refreshKey="requested_"+(new Date).getTime()}setEndpoint(t,e=null){this.endpoint=t,this.nextSelection=e}getRefreshEndpoint(){return this.endpoint}sanitizeResults(t){return Promise.resolve(t)}async refreshTop(){if(!this.getRefreshEndpoint())return;for(;this.pending.length>0;){this.pending.pop().abort()}const t=new AbortController;this.pending.push(t);const e=this.items[this.cursorIndex];try{const i=await be(this.getRefreshEndpoint(),t),o=await this.sanitizeResults(i.results),s=[...this.items];if(o){o.forEach(t=>{this.sanitizeOption&&this.sanitizeOption(t);const e=this.getValue(t),i=s.findIndex(t=>this.getValue(t)===e);i>-1&&s.splice(i,1)});let t=o;this.reverseRefresh&&(t=o.reverse());const i=[...t,...s],n=i[0];if(this.mostRecentItem&&JSON.stringify(this.mostRecentItem)===JSON.stringify(n)||(this.mostRecentItem=n),e){const t=i[this.cursorIndex],o=this.getValue(e);if(o!==this.getValue(t)){const t=i.findIndex(t=>this.getValue(t)===o);this.cursorIndex=t,window.setTimeout(()=>{const t=this.shadowRoot.querySelector("temba-options");if(t){const e=t.shadowRoot.querySelector(".option.focused");e&&e.scrollIntoView({block:"end",inline:"nearest"})}},0)}}this.items=i}}catch(t){this.paused=!0}}async fetchItems(){for(;this.pending.length>0;){this.pending.pop().abort()}let t=this.endpoint,e=this.pages||1,i=0,o=null,s=[];for(;e>0&&t;){const n=new AbortController;this.pending.push(n);try{const r=await be(t,n),a=await this.sanitizeResults(r.results);this.sanitizeOption&&a.forEach(this.sanitizeOption),a&&(s=s.concat(a)),o=r.next,t=o,e--,i++}catch(t){return this.reset(),this.paused=!0,void(this.loading=!1)}this.nextPage=o}this.pages=i;const n=s[0];this.mostRecentItem&&JSON.stringify(this.mostRecentItem)===JSON.stringify(n)||(this.mostRecentItem=n);const r=s[this.cursorIndex];if(!this.nextSelection&&this.selected&&r&&this.getValue(r)!==this.getValue(this.selected)){const t=s.findIndex(t=>this.getValue(t)===this.getValue(this.selected));t>-1?this.cursorIndex=t:0===this.cursorIndex?this.requestUpdate("cursorIndex"):this.cursorIndex=0}if(this.items=s,this.loading=!1,this.pending=[],this.nextSelection?(this.setSelection(this.nextSelection),this.nextSelection=!1):-1!==this.cursorIndex||this.isMobile()||(this.cursorIndex=0),this.value)this.setSelection(this.value),this.value=null;else if(this.isMobile()&&!this.selected){this.cursorIndex=-1,this.value=null,this.selected=null;const t=new Event("change",{bubbles:!0});this.dispatchEvent(t)}return Promise.resolve()}handleScrollThreshold(){this.nextPage&&!this.loading&&(this.loading=!0,be(this.nextPage).then(t=>{this.sanitizeResults(t.results).then(e=>{this.sanitizeOption&&e.forEach(this.sanitizeOption),this.items=[...this.items,...e],this.nextPage=t.next,this.pages++,this.loading=!1})}))}renderHeader(){return null}renderFooter(){return null}getListStyle(){return""}handleSelection(t){let e=t.detail.index;const i=t.detail.selected;-1===e&&(e=0),this.selected=i,this.cursorIndex=e,t.stopPropagation(),t.preventDefault()}render(){return G`
4801
+ `}constructor(){super(),this.items=[],this.cursorIndex=-1,this.tabIndex=1,this.valueKey="id",this.loading=!1,this.paused=!1,this.internalFocusDisabled=!1,this.refreshKey="0",this.reverseRefresh=!0,this.compareItems=null,this.pollingEnabled=!0,this.nextPage=null,this.pages=0,this.pending=[],this.refreshInterval=null,this.store=document.querySelector("temba-store"),this.handleSelection.bind(this)}reset(){this.selected=null,this.nextPage=null,this.cursorIndex=-1,this.mostRecentItem=null,this.items=[]}connectedCallback(){super.connectedCallback(),this.pollingEnabled&&(this.refreshInterval=setInterval(()=>{this.paused||(this.refreshKey="default_"+(new Date).getTime())},1e4))}disconnectedCallback(){super.disconnectedCallback(),clearInterval(this.refreshInterval)}willUpdate(t){super.willUpdate(t),t.has("cursorIndex")&&this.cursorIndex>-1&&(this.selected=this.items[this.cursorIndex]),t.has("endpoint")&&this.endpoint&&(this.loading=!0,this.reset())}updated(t){super.updated(t),t.has("endpoint")&&this.endpoint&&this.fetchItems(),t.has("loading")&&(this.loading||this.fireCustomEvent(Wo.FetchComplete)),t.has("refreshKey")&&!t.has("endpoint")&&this.refreshTop(),t.has("mostRecentItem")&&this.mostRecentItem&&this.fireCustomEvent(Wo.Refreshed),t.has("cursorIndex")&&this.cursorIndex>-1&&this.handleSelected(this.selected),t.has("items")}handleSelected(t){const e=new Event("change",{bubbles:!0});this.dispatchEvent(e)}getValue(t){if(!t)return null;const e=this.valueKey.split(".");let i=t;for(;e.length>0;){i=i[e.shift()]}return i}setSelection(t){const e=this.items.findIndex(e=>this.getValue(e)===t);this.cursorIndex=e,this.selected=this.items[e];const i=new Event("change",{bubbles:!0});this.dispatchEvent(i)}getItemIndex(t){return this.items.findIndex(e=>this.getValue(e)===t)}removeItem(t){const e=this.getItemIndex(t);this.items.splice(e,1),this.items=[...this.items],this.cursorIndex===e&&(this.cursorIndex=-1),this.requestUpdate("cursorIndex"),this.requestUpdate("items")}getSelection(){return this.selected}clearSelection(){this.cursorIndex=-1,this.selected=null,this.value=null}refresh(){this.refreshKey="requested_"+(new Date).getTime()}setEndpoint(t,e=null){this.endpoint=t,this.nextSelection=e}getRefreshEndpoint(){return this.endpoint}sanitizeResults(t){return Promise.resolve(t)}findRepinnedCursorIndex(t,e){if(!t)return null;const i=this.getValue(t);return i===this.getValue(e[this.cursorIndex])?null:e.findIndex(t=>this.getValue(t)===i)}async refreshTop(){if(!this.getRefreshEndpoint())return;for(;this.pending.length>0;){this.pending.pop().abort()}const t=new AbortController;this.pending.push(t);const e=this.items[this.cursorIndex];try{const i=await be(this.getRefreshEndpoint(),t),o=await this.sanitizeResults(i.results),s=[...this.items];if(o){o.forEach(t=>{this.sanitizeOption&&this.sanitizeOption(t);const e=this.getValue(t),i=s.findIndex(t=>this.getValue(t)===e);i>-1&&s.splice(i,1)});let t=o;this.reverseRefresh&&(t=o.reverse());const i=[...t,...s],n=i[0];this.compareItems&&i.sort(this.compareItems),this.mostRecentItem&&JSON.stringify(this.mostRecentItem)===JSON.stringify(n)||(this.mostRecentItem=n);const r=this.findRepinnedCursorIndex(e,i);null!==r&&r>-1&&(this.cursorIndex=r,window.setTimeout(()=>{const t=this.shadowRoot.querySelector("temba-options");if(t){const e=t.shadowRoot.querySelector(".option.focused");e&&e.scrollIntoView({block:"end",inline:"nearest"})}},0)),this.items=i}}catch(t){this.paused=!0}}async fetchItems(){for(;this.pending.length>0;){this.pending.pop().abort()}let t=this.endpoint,e=this.pages||1,i=0,o=null,s=[];for(;e>0&&t;){const n=new AbortController;this.pending.push(n);try{const r=await be(t,n),a=await this.sanitizeResults(r.results);this.sanitizeOption&&a.forEach(this.sanitizeOption),a&&(s=s.concat(a)),o=r.next,t=o,e--,i++}catch(t){return this.reset(),this.paused=!0,void(this.loading=!1)}this.nextPage=o}this.pages=i;const n=s[0];this.mostRecentItem&&JSON.stringify(this.mostRecentItem)===JSON.stringify(n)||(this.mostRecentItem=n);const r=s[this.cursorIndex];if(!this.nextSelection&&this.selected&&r&&this.getValue(r)!==this.getValue(this.selected)){const t=s.findIndex(t=>this.getValue(t)===this.getValue(this.selected));t>-1?this.cursorIndex=t:0===this.cursorIndex?this.requestUpdate("cursorIndex"):this.cursorIndex=0}if(this.items=s,this.loading=!1,this.pending=[],this.nextSelection?(this.setSelection(this.nextSelection),this.nextSelection=!1):-1!==this.cursorIndex||this.isMobile()||(this.cursorIndex=0),this.value)this.setSelection(this.value),this.value=null;else if(this.isMobile()&&!this.selected){this.cursorIndex=-1,this.value=null,this.selected=null;const t=new Event("change",{bubbles:!0});this.dispatchEvent(t)}return Promise.resolve()}handleScrollThreshold(){this.nextPage&&!this.loading&&(this.loading=!0,be(this.nextPage).then(t=>this.sanitizeResults(t.results).then(e=>{this.sanitizeOption&&e.forEach(this.sanitizeOption);const i=this.items[this.cursorIndex],o=new Set(this.items.map(t=>this.getValue(t))),s=(e||[]).filter(t=>{const e=this.getValue(t);return!o.has(e)&&(o.add(e),!0)}),n=[...this.items,...s];this.compareItems&&n.sort(this.compareItems);const r=this.findRepinnedCursorIndex(i,n);null!==r&&r>-1&&(this.cursorIndex=r),this.items=n,this.nextPage=t.next,this.pages++,this.loading=!1})).catch(()=>{this.loading=!1}))}renderHeader(){return null}renderFooter(){return null}getListStyle(){return""}handleSelection(t){let e=t.detail.index;const i=t.detail.selected;-1===e&&(e=0),this.selected=i,this.cursorIndex=e,t.stopPropagation(),t.preventDefault()}render(){return G`
4662
4802
  ${this.renderHeader()}
4663
4803
  <temba-options
4664
4804
  style="${this.getListStyle()}"
@@ -4670,6 +4810,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4670
4810
  ?loading=${this.loading}
4671
4811
  ?internalFocusDisabled=${this.internalFocusDisabled}
4672
4812
  .renderOption=${this.renderOption}
4813
+ .renderDivider=${this.renderDivider}
4673
4814
  .renderOptionDetail=${this.renderOptionDetail}
4674
4815
  @temba-scroll-threshold=${this.handleScrollThreshold}
4675
4816
  @temba-selection=${this.handleSelection.bind(this)}
@@ -4679,9 +4820,40 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4679
4820
  <slot></slot>
4680
4821
  </temba-options>
4681
4822
  ${this.renderFooter()}
4682
- `}}i([ft({type:Array,attribute:!1})],Vu.prototype,"items",void 0),i([ft({type:Object,attribute:!1})],Vu.prototype,"selected",void 0),i([ft({type:Number})],Vu.prototype,"cursorIndex",void 0),i([ft({type:String})],Vu.prototype,"endpoint",void 0),i([ft({type:String})],Vu.prototype,"nextSelection",void 0),i([ft({type:Number})],Vu.prototype,"tabIndex",void 0),i([ft({type:String})],Vu.prototype,"valueKey",void 0),i([ft({type:String})],Vu.prototype,"value",void 0),i([ft({type:Boolean})],Vu.prototype,"loading",void 0),i([ft({type:Boolean})],Vu.prototype,"collapsed",void 0),i([ft({type:Boolean})],Vu.prototype,"hideShadow",void 0),i([ft({type:Boolean})],Vu.prototype,"paused",void 0),i([ft({type:Boolean})],Vu.prototype,"internalFocusDisabled",void 0),i([ft({attribute:!1})],Vu.prototype,"getNextRefresh",void 0),i([ft({attribute:!1})],Vu.prototype,"sanitizeOption",void 0),i([ft({attribute:!1})],Vu.prototype,"renderOption",void 0),i([ft({attribute:!1})],Vu.prototype,"renderOptionDetail",void 0),i([ft({attribute:!1,type:Object})],Vu.prototype,"mostRecentItem",void 0),i([ft({type:String})],Vu.prototype,"refreshKey",void 0);class Gu extends Vu{getRefreshEndpoint(){if(this.items.length>0){const t=this.items[0].ticket.last_activity_on,e=this.endpoint.includes("?")?"&":"?";return this.endpoint+e+"after="+1e3*new Date(t).getTime()}return this.endpoint}sanitizeResults(t){return new Promise(e=>{const i=t;this.store.resolveUsers(i,["ticket.assignee"]).then(()=>{e(i)})})}constructor(){super(),this.agent="",this.valueKey="ticket.uuid",this.renderOption=t=>G`
4823
+ `}}i([ft({type:Array,attribute:!1})],Vu.prototype,"items",void 0),i([ft({type:Object,attribute:!1})],Vu.prototype,"selected",void 0),i([ft({type:Number})],Vu.prototype,"cursorIndex",void 0),i([ft({type:String})],Vu.prototype,"endpoint",void 0),i([ft({type:String})],Vu.prototype,"nextSelection",void 0),i([ft({type:Number})],Vu.prototype,"tabIndex",void 0),i([ft({type:String})],Vu.prototype,"valueKey",void 0),i([ft({type:String})],Vu.prototype,"value",void 0),i([ft({type:Boolean})],Vu.prototype,"loading",void 0),i([ft({type:Boolean})],Vu.prototype,"collapsed",void 0),i([ft({type:Boolean})],Vu.prototype,"hideShadow",void 0),i([ft({type:Boolean})],Vu.prototype,"paused",void 0),i([ft({type:Boolean})],Vu.prototype,"internalFocusDisabled",void 0),i([ft({attribute:!1})],Vu.prototype,"getNextRefresh",void 0),i([ft({attribute:!1})],Vu.prototype,"sanitizeOption",void 0),i([ft({attribute:!1})],Vu.prototype,"renderOption",void 0),i([ft({attribute:!1})],Vu.prototype,"renderDivider",void 0),i([ft({attribute:!1})],Vu.prototype,"renderOptionDetail",void 0),i([ft({attribute:!1,type:Object})],Vu.prototype,"mostRecentItem",void 0),i([ft({type:String})],Vu.prototype,"refreshKey",void 0);class Gu extends Vu{getRefreshEndpoint(){const t=this.items.reduce((t,e)=>{const i=new Date(e.ticket.last_activity_on).getTime();return isNaN(i)?t:Math.max(t,i)},0);if(t>0){const e=this.endpoint.includes("?")?"&":"?";return this.endpoint+e+"after="+1e3*t}return this.endpoint}sanitizeResults(t){return new Promise(e=>{const i=t;this.store.resolveUsers(i,["ticket.assignee"]).then(()=>{e(i)})})}constructor(){super(),this.agent="",this.valueKey="ticket.uuid",this.compareItems=(t,e)=>{const i=!!t.ticket.closed_on;return i!==!!e.ticket.closed_on?i?1:-1:new Date(e.ticket.last_activity_on).getTime()-new Date(t.ticket.last_activity_on).getTime()},this.renderDivider=(t,e)=>{if(!e.ticket.closed_on||t&&t.ticket.closed_on)return null;const i=od("Closed");return G`
4683
4824
  <div
4684
- style="align-items:center; margin-top: 0.1em; margin-bottom: 0.1em"
4825
+ role="separator"
4826
+ aria-label=${i}
4827
+ style="display:flex; align-items:center; gap:0.6em; padding:0.9em var(--pad) 0.2em var(--pad);"
4828
+ >
4829
+ <div
4830
+ style="font-size:0.7em; font-weight:500; letter-spacing:0.08em; text-transform:uppercase; color:var(--text-4);"
4831
+ >
4832
+ ${i}
4833
+ </div>
4834
+ <div
4835
+ style="flex-grow:1; height:1px; background:var(--color-widget-border);"
4836
+ ></div>
4837
+ </div>
4838
+ `},this.renderOption=(t,e)=>t.ticket.closed_on?G`
4839
+ <div
4840
+ style="display:flex; align-items:baseline; margin-top:0.1em; margin-bottom:0.1em; ${e?"":"color:var(--text-3);"}"
4841
+ >
4842
+ <div
4843
+ style="flex:1; min-width:0; font-weight:400; line-height:1.6; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"
4844
+ >
4845
+ ${t.name}
4846
+ </div>
4847
+ <div style="font-size:0.8em; margin-left:0.75em;">
4848
+ <temba-date
4849
+ value=${t.ticket.closed_on}
4850
+ display="duration"
4851
+ ></temba-date>
4852
+ </div>
4853
+ </div>
4854
+ `:G`
4855
+ <div
4856
+ style="align-items:center; margin-top: 0.1em; margin-bottom: 0.1em;"
4685
4857
  >
4686
4858
  <div
4687
4859
  style="display:flex; align-items: flex-start;border:0px solid red;"
@@ -4692,7 +4864,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4692
4864
  >
4693
4865
  ${t.name}
4694
4866
  </div>
4695
- ${t.ticket.closed_on?null:t.last_msg?G`
4867
+ ${t.last_msg?G`
4696
4868
  <div
4697
4869
  style="font-size: 0.9em; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;"
4698
4870
  >
@@ -4716,7 +4888,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4716
4888
  style="margin-right: -5px; margin-top: 0px;display:flex;flex-direction:column;align-items:flex-end;max-width:60px;min-width:30px;border:0px solid green;text-align:right"
4717
4889
  >
4718
4890
  <div>
4719
- ${!t.ticket.closed_on&&t.ticket.assignee?G`<temba-user
4891
+ ${t.ticket.assignee?G`<temba-user
4720
4892
  name=${t.ticket.assignee.name}
4721
4893
  email=${t.ticket.assignee.email}
4722
4894
  avatar=${t.ticket.assignee.avatar}
@@ -4728,7 +4900,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
4728
4900
 
4729
4901
  <div style="font-size:0.8em;text-align:right;border:0px solid red;">
4730
4902
  <temba-date
4731
- value=${t.ticket.closed_on||t.ticket.last_activity_on}
4903
+ value=${t.ticket.last_activity_on}
4732
4904
  display="duration"
4733
4905
  ></temba-date>
4734
4906
  </div>
@@ -6701,9 +6873,6 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
6701
6873
  text-decoration: underline;
6702
6874
  }
6703
6875
  `}handleClick(t){window.goto(t)}render(){return G`<slot href="${this.href}" @click="${this.handleClick}"></slot>`}}i([ft({type:String})],np.prototype,"href",void 0);class rp extends Ke{static get styles(){return d`
6704
- :host {
6705
- }
6706
-
6707
6876
  .wrapper {
6708
6877
  position: relative;
6709
6878
  }
@@ -6717,9 +6886,6 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
6717
6886
  overflow: auto;
6718
6887
  }
6719
6888
 
6720
- .dropdown:focus {
6721
- }
6722
-
6723
6889
  .dropdown.dormant {
6724
6890
  height: 0;
6725
6891
  overflow: hidden;
@@ -6727,7 +6893,16 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
6727
6893
 
6728
6894
  .dropdown {
6729
6895
  position: fixed;
6730
- z-index: 2;
6896
+ /* open popups sit above floating windows (simulator, 5000) and
6897
+ other page chrome, but below dialogs and toasts (10000);
6898
+ temba-content-menu mirrors this value on its temba-dropdown
6899
+ flex item (see ContentMenu.ts) */
6900
+ z-index: 9000;
6901
+ /* the dormant (height: 0) rule is applied 250ms after close, so
6902
+ until then this stays a laid-out, invisible fixed box at
6903
+ z-index 9000 over whatever it was covering — ignore pointer
6904
+ events unless we're actually open */
6905
+ pointer-events: none;
6731
6906
  padding: 0;
6732
6907
  opacity: 0;
6733
6908
  border-radius: calc(var(--curvature) * 1.5);
@@ -6759,6 +6934,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
6759
6934
 
6760
6935
  .open .dropdown {
6761
6936
  opacity: 1;
6937
+ pointer-events: auto;
6762
6938
  transform: translateY(0.5em) scale(1);
6763
6939
  }
6764
6940
 
@@ -7117,7 +7293,10 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
7117
7293
  dark variant shade), so flow stays bluish, group stays purplish,
7118
7294
  etc. — no grey wash. */
7119
7295
  .label[class*='pill-'].clickable .mask:hover {
7120
- background: color-mix(in oklab, currentColor 10%, transparent);
7296
+ /* Neutral wash first for browsers without color-mix() the
7297
+ currentColor mix can't fall back per-declaration because
7298
+ currentColor keeps it valid until computed-value time. */
7299
+ background: rgba(0, 0, 0, 0.06);
7121
7300
  }
7122
7301
  .label[class*='pill-'] temba-icon {
7123
7302
  margin-right: 0;
@@ -7138,14 +7317,26 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
7138
7317
  margin: 0;
7139
7318
  border: 0;
7140
7319
  border-radius: 999px;
7141
- background: color-mix(in oklab, currentColor 25%, transparent);
7320
+ background: rgba(0, 0, 0, 0.12);
7142
7321
  color: inherit;
7143
7322
  opacity: 0.8;
7144
7323
  --icon-color: currentColor;
7145
7324
  }
7146
7325
  .label[class*='pill-'] .remove:hover {
7147
7326
  opacity: 1;
7148
- background: color-mix(in oklab, currentColor 45%, transparent);
7327
+ background: rgba(0, 0, 0, 0.22);
7328
+ }
7329
+
7330
+ @supports (color: color-mix(in srgb, red, red)) {
7331
+ .label[class*='pill-'].clickable .mask:hover {
7332
+ background: color-mix(in oklab, currentColor 10%, transparent);
7333
+ }
7334
+ .label[class*='pill-'] .remove {
7335
+ background: color-mix(in oklab, currentColor 25%, transparent);
7336
+ }
7337
+ .label[class*='pill-'] .remove:hover {
7338
+ background: color-mix(in oklab, currentColor 45%, transparent);
7339
+ }
7149
7340
  }
7150
7341
 
7151
7342
  /* When a removable X is present, tighten the mask's left padding
@@ -7808,24 +7999,36 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
7808
7999
  padding: 0.05em 0.65em;
7809
8000
  border-radius: 999px;
7810
8001
  white-space: nowrap;
7811
- background: color-mix(
7812
- in srgb,
7813
- var(--pill-hue) 12%,
7814
- var(--color-widget-bg, #fff)
7815
- );
7816
- border: 1px solid
7817
- color-mix(in srgb, var(--pill-hue) 25%, var(--color-widget-bg, #fff));
8002
+ /* plain bg / neutral border for browsers without color-mix();
8003
+ the hue-tinted versions live in the @supports block below */
8004
+ background: var(--color-widget-bg, #fff);
8005
+ border: 1px solid var(--pill-hue);
7818
8006
  color: var(--pill-hue);
7819
8007
  cursor: pointer;
7820
8008
  transition: background 100ms ease-in-out;
7821
8009
  }
7822
8010
 
7823
- .campaign-pill:hover {
7824
- background: color-mix(
7825
- in srgb,
7826
- var(--pill-hue) 22%,
7827
- var(--color-widget-bg, #fff)
7828
- );
8011
+ @supports (color: color-mix(in srgb, red, red)) {
8012
+ .campaign-pill {
8013
+ background: color-mix(
8014
+ in srgb,
8015
+ var(--pill-hue) 12%,
8016
+ var(--color-widget-bg, #fff)
8017
+ );
8018
+ border: 1px solid
8019
+ color-mix(
8020
+ in srgb,
8021
+ var(--pill-hue) 25%,
8022
+ var(--color-widget-bg, #fff)
8023
+ );
8024
+ }
8025
+ .campaign-pill:hover {
8026
+ background: color-mix(
8027
+ in srgb,
8028
+ var(--pill-hue) 22%,
8029
+ var(--color-widget-bg, #fff)
8030
+ );
8031
+ }
7829
8032
  }
7830
8033
 
7831
8034
  .campaign-pill:focus-visible {
@@ -7908,24 +8111,34 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
7908
8111
  }
7909
8112
 
7910
8113
  /* past events are filled with a lighter tint of the same hue and keep
7911
- the solid border - they're settled, whether real or projected */
8114
+ the solid border - they're settled, whether real or projected.
8115
+ Plain widget bg first for browsers without color-mix(). */
7912
8116
  .dot.past {
7913
- background: color-mix(
7914
- in srgb,
7915
- var(--dot-color) 25%,
7916
- var(--color-widget-bg, #fff)
7917
- );
8117
+ background: var(--color-widget-bg, #fff);
7918
8118
  }
7919
8119
 
7920
8120
  /* future events haven't occurred yet - signal that with a dotted
7921
8121
  border and the faintest tint of the hue inside */
7922
8122
  .dot.future {
7923
8123
  border-style: dotted;
7924
- background: color-mix(
7925
- in srgb,
7926
- var(--dot-color) 8%,
7927
- var(--color-widget-bg, #fff)
7928
- );
8124
+ background: var(--color-widget-bg, #fff);
8125
+ }
8126
+
8127
+ @supports (color: color-mix(in srgb, red, red)) {
8128
+ .dot.past {
8129
+ background: color-mix(
8130
+ in srgb,
8131
+ var(--dot-color) 25%,
8132
+ var(--color-widget-bg, #fff)
8133
+ );
8134
+ }
8135
+ .dot.future {
8136
+ background: color-mix(
8137
+ in srgb,
8138
+ var(--dot-color) 8%,
8139
+ var(--color-widget-bg, #fff)
8140
+ );
8141
+ }
7929
8142
  }
7930
8143
 
7931
8144
  /* the now dot and label both paint with the SPA content background
@@ -8386,11 +8599,20 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
8386
8599
  justify-content: center;
8387
8600
  /* icons inside the dot take the dot's hue */
8388
8601
  --icon-color: var(--dot-color);
8389
- background: color-mix(
8390
- in srgb,
8391
- var(--dot-color) 12%,
8392
- var(--color-widget-bg, #fff)
8393
- );
8602
+ /* plain widget bg for browsers without color-mix(); the tinted
8603
+ fill below needs the @supports gate since var() keeps an
8604
+ invalid declaration alive until computed-value time */
8605
+ background: var(--color-widget-bg, #fff);
8606
+ }
8607
+
8608
+ @supports (color: color-mix(in srgb, red, red)) {
8609
+ .dot {
8610
+ background: color-mix(
8611
+ in srgb,
8612
+ var(--dot-color) 12%,
8613
+ var(--color-widget-bg, #fff)
8614
+ );
8615
+ }
8394
8616
  }
8395
8617
 
8396
8618
  /* the anchor marks the field's date itself - painted with the widget
@@ -8583,7 +8805,8 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
8583
8805
 
8584
8806
  .menu-button.destructive:hover {
8585
8807
  border-color: #dc2626;
8586
- background: color-mix(in srgb, #dc2626 6%, var(--surface, #fff));
8808
+ /* pre-mixed fallback for browsers without color-mix() */
8809
+ background: #fdf2f2;
8587
8810
  }
8588
8811
 
8589
8812
  /* the event's action, contained with a leading type label. Children
@@ -8594,16 +8817,26 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
8594
8817
  align-items: flex-start;
8595
8818
  gap: 0.6em;
8596
8819
  padding: 0.9em 1em 1em;
8597
- background: color-mix(
8598
- in srgb,
8599
- var(--sunken, #f1f3f5) 45%,
8600
- var(--surface, #fff)
8601
- );
8820
+ /* pre-mixed fallback for browsers without color-mix() */
8821
+ background: #f9fafa;
8602
8822
  border: 1px solid var(--border, #e4e7ec);
8603
8823
  border-radius: var(--r);
8604
8824
  line-height: 1.5;
8605
8825
  }
8606
8826
 
8827
+ @supports (color: color-mix(in srgb, red, red)) {
8828
+ .menu-button.destructive:hover {
8829
+ background: color-mix(in srgb, #dc2626 6%, var(--surface, #fff));
8830
+ }
8831
+ .detail-action {
8832
+ background: color-mix(
8833
+ in srgb,
8834
+ var(--sunken, #f1f3f5) 45%,
8835
+ var(--surface, #fff)
8836
+ );
8837
+ }
8838
+ }
8839
+
8607
8840
  /* the close (✕) in the header's upper right - the square
8608
8841
  hover-wash button treatment (the pager buttons'), sitting
8609
8842
  just outboard of the action buttons */
@@ -9419,15 +9652,23 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
9419
9652
  </div>
9420
9653
  </div>
9421
9654
  `:null}}i([ft({type:String,attribute:"priority-endpoint"})],$p.prototype,"priorityEndpoint",void 0),i([ft({type:Object,attribute:!1})],$p.prototype,"featuredFields",void 0),i([ft({type:Object,attribute:!1})],$p.prototype,"otherFieldKeys",void 0),i([ft({type:String})],$p.prototype,"query",void 0);const Tp={"X-Temba-Content-Menu":"1","X-Temba-Spa":"1"};var Ep;!function(t){t.LINK="link",t.JS="js",t.URL_POST="url_post",t.MODAX="modax",t.DIVIDER="divider"}(Ep||(Ep={}));class Ap extends Ke{constructor(){super(...arguments),this.buttons=[],this.items=[]}static get styles(){return d`
9422
- :host {
9423
- tabindex: 0;
9424
- z-index: 5000;
9425
- }
9426
9655
  .container {
9427
9656
  display: flex;
9428
9657
  align-items: center;
9429
9658
  }
9430
9659
 
9660
+ temba-dropdown {
9661
+ /* as a flex item of .container this z-index takes effect and
9662
+ creates a stacking context — keep it in sync with the popup's
9663
+ z-index inside temba-dropdown (9000) so the open menu clears
9664
+ floating windows like the simulator (5000). This also keeps
9665
+ the closed toggle above those windows, intentionally: the
9666
+ menu has to stay clickable when a floating window overlaps
9667
+ the header. Scoped here rather than on :host so the action
9668
+ buttons rendered alongside keep their normal stacking. */
9669
+ z-index: 9000;
9670
+ }
9671
+
9431
9672
  .button_item,
9432
9673
  .primary_button_item {
9433
9674
  margin-left: 1rem;
@@ -9453,7 +9694,6 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
9453
9694
  color: rgb(45, 45, 45);
9454
9695
  z-index: 50;
9455
9696
  min-width: 200px;
9456
- tabindex: 0;
9457
9697
  }
9458
9698
 
9459
9699
  .divider {
@@ -9467,7 +9707,6 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
9467
9707
  font-size: 1.1rem;
9468
9708
  cursor: pointer;
9469
9709
  font-weight: 400;
9470
- tabindex: 0;
9471
9710
  }
9472
9711
 
9473
9712
  .item:hover {
@@ -9501,7 +9740,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
9501
9740
  .date {
9502
9741
  display: inline;
9503
9742
  }
9504
- `}connectedCallback(){super.connectedCallback(),this.store=document.querySelector("temba-store")}willUpdate(t){super.willUpdate(t),t.has("value")&&(this.datetime=Ql.fromISO(this.value))}render(){if(this.datetime&&this.store){this.datetime.setLocale(this.store.getLocale());let t="";if(this.display===Dp.timedate){const e=Math.abs(this.datetime.diffNow().milliseconds/1e3/60/60),i=this.datetime.get("day");t=e<24&&i==Ql.now().get("day")?this.datetime.toLocaleString(Dp.time):e<8760?this.datetime.toFormat(Dp.day):this.datetime.toLocaleString(Dp.date)}else if(this.display===Dp.relative){if(Math.abs(this.datetime.diffNow().milliseconds/1e3/60)<1)return G`<span
9743
+ `}connectedCallback(){super.connectedCallback(),this.store=document.querySelector("temba-store")}willUpdate(t){super.willUpdate(t),t.has("value")&&(this.datetime=Ql.fromISO(this.value))}render(){if(this.datetime&&!(this.datetime.isValid&&this.datetime.year>1))return Z;if(this.datetime&&this.store){this.datetime.setLocale(this.store.getLocale());let t="";if(this.display===Dp.timedate){const e=Math.abs(this.datetime.diffNow().milliseconds/1e3/60/60),i=this.datetime.get("day");t=e<24&&i==Ql.now().get("day")?this.datetime.toLocaleString(Dp.time):e<8760?this.datetime.toFormat(Dp.day):this.datetime.toLocaleString(Dp.date)}else if(this.display===Dp.relative){if(Math.abs(this.datetime.diffNow().milliseconds/1e3/60)<1)return G`<span
9505
9744
  class="date"
9506
9745
  title="${this.datetime.toLocaleString(Dp.datetime)}"
9507
9746
  >just now</span
@@ -9637,7 +9876,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
9637
9876
  <span>${t.name}</span>
9638
9877
  ${i}
9639
9878
  </div>
9640
- `},this.handleHostKeyDown=t=>{if("Escape"===t.key&&this.showShortcuts)return t.preventDefault(),t.stopPropagation(),void(this.showShortcuts=!1);if("Enter"===t.key&&!t.shiftKey){if(t.isComposing||229===t.keyCode)return;if(this.showShortcuts)return;const e=this.getMessageEditor();if(!(t.eventPhase!==Event.CAPTURING_PHASE||e&&t.composedPath().includes(e)))return;if(e){const t=e.getRichEditor();if(t&&t.hasVisibleOptions())return}t.preventDefault(),t.stopImmediatePropagation(),this.triggerSend()}}}isBaseLanguage(){return"und"==this.currentLanguage||this.currentLanguage==this.languages[0].iso}hasTranslation(t){var e;const i=null===(e=this.langValues)||void 0===e?void 0:e[t];return!!i&&!!(i.text&&i.text.trim().length>0||i.attachments&&i.attachments.length>0||i.quick_replies&&i.quick_replies.length>0)}getSortedLanguages(){if(0===this.languages.length)return[];const[t,...e]=this.languages,i=[...e].sort((t,e)=>{const i=this.hasTranslation(t.iso);return i!==this.hasTranslation(e.iso)?i?-1:1:0});return[t,...i]}willUpdate(t){var e,i;if(super.willUpdate(t),t.has("languages")&&this.languages.length>0&&(this.currentLanguage=this.languages[0].iso),t.has("value")&&(this.langValues=this.getDeserializedValue()||{},this.variables=(null===(e=this.langValues[this.currentLanguage])||void 0===e?void 0:e.variables)||[],this.template=(null===(i=this.langValues[this.currentLanguage])||void 0===i?void 0:i.template)||null),t.has("currentLanguage")&&this.langValues){let t={text:"",attachments:[],quick_replies:[]};this.currentLanguage in this.langValues&&(t=this.langValues[this.currentLanguage]),this.currentText=t.text||"",this.initialText=t.text||"",this.currentAttachments=t.attachments||[],this.currentQuickReplies=(t.quick_replies||[]).map(t=>({name:t,value:t})),this.currentOptin=t.optin?[t.optin]:[]}if(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies")||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))){this.checkIfEmpty();const t=this.currentText?this.currentText.trim():"";t||(this.currentAttachments||[]).length>0||this.currentQuickReplies.length>0||this.currentOptin.length>0||this.variables.length>0?this.langValues[this.currentLanguage]={text:t,attachments:this.currentAttachments,quick_replies:this.currentQuickReplies.map(t=>t.value),optin:this.currentOptin.length>0?this.currentOptin[0]:null,template:this.currentTemplate?this.currentTemplate.uuid:null,variables:this.variables,locale:this.locale}:delete this.langValues[this.currentLanguage],this.setValue(this.langValues)}}connectedCallback(){super.connectedCallback(),this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),this.addEventListener("keydown",this.handleHostKeyDown,!0),this.addEventListener("keydown",this.handleHostKeyDown)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("keydown",this.handleHostKeyDown,!0),this.removeEventListener("keydown",this.handleHostKeyDown)}handleShortcutIconClick(){this.showShortcuts?this.showShortcuts=!1:(this.shortcutFilter="",this.shortcutViaIcon=!0,this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.filter="",t.showSearch=!0,t.updateComplete.then(()=>{t.focusSearch()}))}))}firstUpdated(t){super.firstUpdated(t),this.setFocusOnEditor()}updated(t){if(super.updated(t),t.has("currentLanguage")&&this.langValues){this.setFocusOnEditor();const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){const t=this.initialText,i=this.currentLanguage;e.value=t;const o=e.inputElement;o&&window.setTimeout(()=>{this.currentLanguage===i&&ph(o,t.length)},0)}}}(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies"))||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))&&this.fireCustomEvent(Wo.ContentChanged,this.langValues)}handleLoading(t){this.uploading=t.detail.loading}handleAttachmentsChanged(t){t.detail&&t.detail.attachments&&(this.currentAttachments=t.detail.attachments),this.requestUpdate()}setFocusOnEditor(){const t=this.getMessageEditor();t&&window.setTimeout(()=>{t.focus()},0)}reset(){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){e.getTextInput().updateValue(""),e.fireEvent("change")}this.initialText="",this.currentText="",this.currentQuickReplies=[],this.currentAttachments=[],this.showShortcuts=!1}}handleQuickReplyChange(){this.requestUpdate("currentQuickReplies")}handleOptInChange(t){this.currentOptin=t.target.values,this.requestUpdate("currentOptin")}handleEditorChange(t){const e=t.target.getRichEditor();if(e&&(this.currentText=e.value||"",this.hasPendingText=this.currentText.length>0,this.lastCaretPosition=e.getCaretPosition(),this.shortcuts)){const t=this.currentText,i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1,s=t.substring(o,i);s.startsWith("/")?(this.showShortcuts||(this.shortcutViaIcon=!1),this.shortcutFilter=s.substring(1),this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.showSearch=!1,t.filter=this.shortcutFilter)})):this.showShortcuts=!1}}checkIfEmpty(){const t=0===this.currentText.trim().length,e=0===this.currentAttachments.length;this.attachments?this.empty=t&&e:this.empty=t}handleKeyDown(t){if("Backspace"===t.key&&this.shortcuts&&this.showShortcuts){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){const t=e.getText(),i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1;"/"===t.substring(o,i)&&(this.showShortcuts=!1)}}}}triggerSend(){this.checkIfEmpty(),this.empty||this.fireCustomEvent(Wo.Submitted,{langValues:this.langValues})}handleLanguageChange(t){const e=t.target;this.currentLanguage=e.values[0].iso}getShortcutOverlayStyle(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".container");if(!e)return"";const i=e.getBoundingClientRect(),o=window.innerHeight-i.top,s=i.top-16;return`left: ${i.left}px; bottom: ${o}px; width: ${i.width}px; max-height: ${s}px;`}getMessageEditor(){return this.shadowRoot.querySelector("temba-message-editor")}handleShortcutSelection(t){this.activeShortcut=t.detail.selected;const e=this.getMessageEditor();if(!e)return;const i=e.getRichEditor();if(!i)return;const o=i.getText(),s=i.getCaretPosition()||this.lastCaretPosition,n=o.lastIndexOf("\n",s-1)+1;let r=o.indexOf("\n",n);-1===r&&(r=o.length);let a,l;if(o.substring(n,r).startsWith("/")){const t=o.substring(0,n),e=o.substring(r);a=t+this.activeShortcut.text+e,l=n+this.activeShortcut.text.length}else a=o.substring(0,s)+this.activeShortcut.text+o.substring(s),l=s+this.activeShortcut.text.length;i.getTextInput().updateValue(a),i.fireEvent("change");const d=i.inputElement;d&&(d.focus(),ph(d,l)),this.showShortcuts=!1}handleTemplateChanged(t){var e;this.currentTemplate=t.detail.template,this.locale=null===(e=t.detail.translation)||void 0===e?void 0:e.locale,this.requestUpdate()}handleTemplateVariablesChanged(t){this.variables=[...t.detail.variables]}render(){return this.renderField()}renderWidget(){const t=this.optIns&&this.isBaseLanguage(),e=this.templates&&this.isBaseLanguage(),i=this.quickReplies||t||e;return G`
9879
+ `},this.handleHostKeyDownCapture=t=>{this.handleHostKeyDown(t,!0)},this.handleHostKeyDownBubble=t=>{this.handleHostKeyDown(t,!1)},this.handleHostKeyDown=(t,e)=>{if("Escape"===t.key&&this.showShortcuts)return t.preventDefault(),t.stopPropagation(),void(this.showShortcuts=!1);if("Enter"===t.key&&!t.shiftKey){if(t.isComposing||229===t.keyCode)return;if(this.showShortcuts)return;const i=this.getMessageEditor();if(e&&(!i||!t.composedPath().includes(i)))return;if(!e&&t.defaultPrevented)return;if(i){const t=i.getRichEditor();if(t&&t.hasVisibleOptions())return}t.preventDefault(),t.stopImmediatePropagation(),this.triggerSend()}}}isBaseLanguage(){return"und"==this.currentLanguage||this.currentLanguage==this.languages[0].iso}hasTranslation(t){var e;const i=null===(e=this.langValues)||void 0===e?void 0:e[t];return!!i&&!!(i.text&&i.text.trim().length>0||i.attachments&&i.attachments.length>0||i.quick_replies&&i.quick_replies.length>0)}getSortedLanguages(){if(0===this.languages.length)return[];const[t,...e]=this.languages,i=[...e].sort((t,e)=>{const i=this.hasTranslation(t.iso);return i!==this.hasTranslation(e.iso)?i?-1:1:0});return[t,...i]}willUpdate(t){var e,i;if(super.willUpdate(t),t.has("languages")&&this.languages.length>0&&(this.currentLanguage=this.languages[0].iso),t.has("value")&&(this.langValues=this.getDeserializedValue()||{},this.variables=(null===(e=this.langValues[this.currentLanguage])||void 0===e?void 0:e.variables)||[],this.template=(null===(i=this.langValues[this.currentLanguage])||void 0===i?void 0:i.template)||null),t.has("currentLanguage")&&this.langValues){let t={text:"",attachments:[],quick_replies:[]};this.currentLanguage in this.langValues&&(t=this.langValues[this.currentLanguage]),this.currentText=t.text||"",this.initialText=t.text||"",this.currentAttachments=t.attachments||[],this.currentQuickReplies=(t.quick_replies||[]).map(t=>{var e;return"string"==typeof t?t:null!==(e=t.text)&&void 0!==e?e:null}).filter(t=>null!==t).map(t=>({name:t,value:t})),this.currentOptin=t.optin?[t.optin]:[]}if(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies")||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))){this.checkIfEmpty();const t=this.currentText?this.currentText.trim():"";t||(this.currentAttachments||[]).length>0||this.currentQuickReplies.length>0||this.currentOptin.length>0||this.variables.length>0?this.langValues[this.currentLanguage]={text:t,attachments:this.currentAttachments,quick_replies:this.currentQuickReplies.map(t=>t.value),optin:this.currentOptin.length>0?this.currentOptin[0]:null,template:this.currentTemplate?this.currentTemplate.uuid:null,variables:this.variables,locale:this.locale}:delete this.langValues[this.currentLanguage],this.setValue(this.langValues)}}connectedCallback(){super.connectedCallback(),this.hasAttribute("tabindex")||this.setAttribute("tabindex","-1"),this.addEventListener("keydown",this.handleHostKeyDownCapture,!0),this.addEventListener("keydown",this.handleHostKeyDownBubble)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("keydown",this.handleHostKeyDownCapture,!0),this.removeEventListener("keydown",this.handleHostKeyDownBubble)}handleShortcutIconClick(){this.showShortcuts?this.showShortcuts=!1:(this.shortcutFilter="",this.shortcutViaIcon=!0,this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.filter="",t.showSearch=!0,t.updateComplete.then(()=>{t.focusSearch()}))}))}firstUpdated(t){super.firstUpdated(t),this.setFocusOnEditor()}updated(t){if(super.updated(t),t.has("currentLanguage")&&this.langValues){this.setFocusOnEditor();const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){const t=this.initialText,i=this.currentLanguage;e.value=t;const o=e.inputElement;o&&window.setTimeout(()=>{this.currentLanguage===i&&ph(o,t.length)},0)}}}(this.langValues&&(t.has("currentText")||t.has("currentAttachments")||t.has("currentQuickReplies"))||t.has("currentOptin")||t.has("currentTemplate")||t.has("variables"))&&this.fireCustomEvent(Wo.ContentChanged,this.langValues)}handleLoading(t){this.uploading=t.detail.loading}handleAttachmentsChanged(t){t.detail&&t.detail.attachments&&(this.currentAttachments=t.detail.attachments),this.requestUpdate()}setFocusOnEditor(){const t=this.getMessageEditor();t&&window.setTimeout(()=>{t.focus()},0)}reset(){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){e.getTextInput().updateValue(""),e.fireEvent("change")}this.initialText="",this.currentText="",this.currentQuickReplies=[],this.currentAttachments=[],this.showShortcuts=!1}}handleQuickReplyChange(){this.requestUpdate("currentQuickReplies")}handleOptInChange(t){this.currentOptin=t.target.values,this.requestUpdate("currentOptin")}handleEditorChange(t){const e=t.target.getRichEditor();if(e&&(this.currentText=e.value||"",this.hasPendingText=this.currentText.length>0,this.lastCaretPosition=e.getCaretPosition(),this.shortcuts)){const t=this.currentText,i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1,s=t.substring(o,i);s.startsWith("/")?(this.showShortcuts||(this.shortcutViaIcon=!1),this.shortcutFilter=s.substring(1),this.showShortcuts=!0,this.updateComplete.then(()=>{const t=this.shadowRoot.querySelector("temba-shortcuts");t&&(t.showSearch=!1,t.filter=this.shortcutFilter)})):this.showShortcuts=!1}}checkIfEmpty(){const t=0===this.currentText.trim().length,e=0===this.currentAttachments.length;this.attachments?this.empty=t&&e:this.empty=t}handleKeyDown(t){if("Backspace"===t.key&&this.shortcuts&&this.showShortcuts){const t=this.getMessageEditor();if(t){const e=t.getRichEditor();if(e){const t=e.getText(),i=e.getCaretPosition(),o=t.lastIndexOf("\n",i-1)+1;"/"===t.substring(o,i)&&(this.showShortcuts=!1)}}}}triggerSend(){this.checkIfEmpty(),this.empty||this.fireCustomEvent(Wo.Submitted,{langValues:this.langValues})}handleLanguageChange(t){const e=t.target;this.currentLanguage=e.values[0].iso}getShortcutOverlayStyle(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".container");if(!e)return"";const i=e.getBoundingClientRect(),o=window.innerHeight-i.top,s=i.top-16;return`left: ${i.left}px; bottom: ${o}px; width: ${i.width}px; max-height: ${s}px;`}getMessageEditor(){return this.shadowRoot.querySelector("temba-message-editor")}handleShortcutSelection(t){this.activeShortcut=t.detail.selected;const e=this.getMessageEditor();if(!e)return;const i=e.getRichEditor();if(!i)return;const o=i.getText(),s=i.getCaretPosition()||this.lastCaretPosition,n=o.lastIndexOf("\n",s-1)+1;let r=o.indexOf("\n",n);-1===r&&(r=o.length);let a,l;if(o.substring(n,r).startsWith("/")){const t=o.substring(0,n),e=o.substring(r);a=t+this.activeShortcut.text+e,l=n+this.activeShortcut.text.length}else a=o.substring(0,s)+this.activeShortcut.text+o.substring(s),l=s+this.activeShortcut.text.length;i.getTextInput().updateValue(a),i.fireEvent("change");const d=i.inputElement;d&&(d.focus(),ph(d,l)),this.showShortcuts=!1}handleTemplateChanged(t){var e;this.currentTemplate=t.detail.template,this.locale=null===(e=t.detail.translation)||void 0===e?void 0:e.locale,this.requestUpdate()}handleTemplateVariablesChanged(t){this.variables=[...t.detail.variables]}render(){return this.renderField()}renderWidget(){const t=this.optIns&&this.isBaseLanguage(),e=this.templates&&this.isBaseLanguage(),i=this.quickReplies||t||e;return G`
9641
9880
  <div>
9642
9881
  ${this.languages.length>1?G`<temba-select
9643
9882
  @change=${this.handleLanguageChange}
@@ -10187,24 +10426,33 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
10187
10426
  --sort-gutter: 16px;
10188
10427
  /* Selected-row wash — accent-50 on its own reads grey, so a
10189
10428
  touch of the accent-400 rail colour is mixed in to give
10190
- the selection a faint accent tint. */
10191
- --cl-selected: color-mix(
10192
- in oklab,
10193
- var(--accent-400) 9%,
10194
- var(--accent-50)
10195
- );
10429
+ the selection a faint accent tint. Statics pre-mixed from
10430
+ the default accent for browsers without color-mix(); the
10431
+ @supports block below re-derives them from the tokens. */
10432
+ --cl-selected: #e5ecf8;
10196
10433
  /* The dividers bracketing a selected row — the plain grey
10197
10434
  --border reads as a seam against the wash, so this is the
10198
10435
  same accent pushed a little further. */
10199
- --cl-selected-border: color-mix(
10200
- in oklab,
10201
- var(--accent-400) 24%,
10202
- var(--accent-50)
10203
- );
10436
+ --cl-selected-border: #cbdaf1;
10204
10437
  /* Tint shared by the frozen (pinned) columns and the header
10205
10438
  row, so the header reads as the same quiet sub-panel as the
10206
10439
  pinned section. */
10207
- --cl-pin-bg: color-mix(in oklab, var(--sunken) 35%, var(--surface));
10440
+ --cl-pin-bg: #fafbfc;
10441
+ }
10442
+ @supports (color: color-mix(in srgb, red, red)) {
10443
+ :host {
10444
+ --cl-selected: color-mix(
10445
+ in oklab,
10446
+ var(--accent-400) 9%,
10447
+ var(--accent-50)
10448
+ );
10449
+ --cl-selected-border: color-mix(
10450
+ in oklab,
10451
+ var(--accent-400) 24%,
10452
+ var(--accent-50)
10453
+ );
10454
+ --cl-pin-bg: color-mix(in oklab, var(--sunken) 35%, var(--surface));
10455
+ }
10208
10456
  }
10209
10457
  /* fillWindow — take the slack of a height-bounded flex-column
10210
10458
  parent so the table scrolls internally; min-height: 0 (set
@@ -10329,7 +10577,14 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
10329
10577
  color: var(--danger);
10330
10578
  }
10331
10579
  .bulk-action.destructive:hover {
10332
- background: color-mix(in oklab, var(--danger) 20%, white);
10580
+ /* pre-mixed fallback for browsers without color-mix() */
10581
+ background: #f6d9d9;
10582
+ }
10583
+
10584
+ @supports (color: color-mix(in srgb, red, red)) {
10585
+ .bulk-action.destructive:hover {
10586
+ background: color-mix(in oklab, var(--danger) 20%, white);
10587
+ }
10333
10588
  }
10334
10589
  .bulk-action temba-icon {
10335
10590
  --icon-color: currentColor;
@@ -10565,10 +10820,16 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
10565
10820
  within the panel padding so row dividers don't bleed full-
10566
10821
  width. */
10567
10822
  margin-right: -20px;
10568
- /* Contain the sticky header's z-index inside this frame so it
10569
- can't compete with the page header's content-menu dropdown
10570
- (also z-index 2), which otherwise paints under the table
10571
- header by DOM-order tie-break. */
10823
+ /* Keep the table's internal layering (sticky header, pinned
10824
+ columns and their hover/shadow layers, z-index 1-6) inside
10825
+ its own stacking context so those values can only order
10826
+ against each other and never interleave with page-level
10827
+ layers like floating windows or open dropdowns. Without it
10828
+ the frame is z-index auto, so the table's 1-6 would join the
10829
+ nearest ancestor stacking context — normally the root — and
10830
+ tie against page chrome using comparably small values. Note
10831
+ this also caps this list's own label dropdown, which renders
10832
+ inside the frame and so cannot escape it. */
10572
10833
  isolation: isolate;
10573
10834
  }
10574
10835
  .table-scroll {
@@ -10809,6 +11070,52 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
10809
11070
  cursor: col-resize !important;
10810
11071
  }
10811
11072
 
11073
+ /* Column reorder. A reorderable header is a drag surface: past a
11074
+ small pointer threshold the label lifts into a floating ghost,
11075
+ the origin column dims, and an accent insertion bar tracks the
11076
+ drop slot. touch-action: none lets the same drag work on touch
11077
+ — the 36px sticky header row is a negligible scroll-start
11078
+ surface, so claiming its gestures (including the vertical
11079
+ swipe that would otherwise scroll the list) costs little. */
11080
+ .head-cell.reorderable {
11081
+ touch-action: none;
11082
+ }
11083
+ /* Advertise the drag while idle. The th prefix out-specifies
11084
+ .head-cell.sortable's pointer cursor, which is declared later
11085
+ in this sheet and would otherwise win on a sortable column. */
11086
+ th.head-cell.reorderable {
11087
+ cursor: grab;
11088
+ }
11089
+ .head-cell.dragging {
11090
+ opacity: 0.35;
11091
+ }
11092
+ /* The insertion bar sits flush inside the boundary it marks
11093
+ rather than straddling it — an overhanging bar would be painted
11094
+ over by the neighbouring header cell, which is opaque and wins
11095
+ the stacking order. The header cell is the positioning context
11096
+ (it's position: sticky). */
11097
+ .head-cell.drop-before::before,
11098
+ .head-cell.drop-after::after {
11099
+ content: '';
11100
+ position: absolute;
11101
+ top: 4px;
11102
+ bottom: 4px;
11103
+ width: 3px;
11104
+ border-radius: 2px;
11105
+ background: var(--accent-400);
11106
+ z-index: 5;
11107
+ }
11108
+ .head-cell.drop-before::before {
11109
+ left: 0;
11110
+ }
11111
+ .head-cell.drop-after::after {
11112
+ right: 0;
11113
+ }
11114
+ :host([column-dragging]),
11115
+ :host([column-dragging]) * {
11116
+ cursor: grabbing !important;
11117
+ }
11118
+
10812
11119
  /* Pinned columns stay fixed against their edge while the rest
10813
11120
  of the table scrolls under them. The frozen-region look —
10814
11121
  the tint and the divider — only kicks in once the table
@@ -11219,7 +11526,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11219
11526
  background: var(--danger-bg);
11220
11527
  color: var(--danger);
11221
11528
  }
11222
- `}contentMenuEndpointWithSearch(){if(!this.contentMenuEndpoint)return this.contentMenuEndpoint;try{const t=new URL(this.contentMenuEndpoint,window.location.origin);return this.search?t.searchParams.set("search",this.search):t.searchParams.delete("search"),t.pathname+t.search}catch(t){return this.contentMenuEndpoint}}get hasCheckboxes(){return this.selectable&&this.bulkActions.length>0}constructor(){super(),this.contentMenuEndpoint="",this.columns=[],this.bulkActions=[],this.valueKey="uuid",this.pageSize=50,this.searchable=!0,this.selectable=!0,this.fixedLayout=!1,this.minTableWidth="",this.fillWindow=!1,this.urlState=!1,this.urlParamPrefix="",this.historyStateKey="",this.columnWidthSettings={},this.settingsEndpoint="",this.saveDelay=500,this.searchPlaceholder="Search",this.listTitle="",this.subtitle="",this.emptyMessage="Nothing to show",this.refreshKey="",this.actionEndpoint="",this.items=[],this.total=0,this.hasCount=!1,this.page=1,this.cursorMode=!1,this.nextCursor="",this.prevCursor="",this.currentUrl="",this.restoreUrl="",this.sort="",this.search="",this.loading=!1,this.searching=!1,this.searchError="",this.selectedIds=new Set,this.searchOpen=!1,this.searchDraft="",this.labelsByActionKey={},this.pendingLabel=null,this.bulkCollapsed=!1,this.bulkCollapseFrame=0,this.pending=null,this.previousBodyUserSelect="",this.columnWidths={},this.columnWidthSaveTimeout=null,this.suppressHeaderClick=!1,this.headerClickSuppressionTimeout=null,this.pinIndexByColumn=new Map,this.rightPinIndexByColumn=new Map,this.checkPinIndex=-1,this.lastPinIndex=-1,this.firstRightPinIndex=-1,this.spacerAfterIndex=-1,this.reservesIcon=!1,this.handleColumnResizeMove=t=>{if(!this.columnResize)return;t.preventDefault();const e=this.columnResize,i=e.startWidth+t.clientX-e.startX;e.nativeFloor&&(i<=e.minWidth||e.minWidth>=Bp.MAX_COLUMN_WIDTH)?this.restoreColumnWidth(e.key,e.initialSavedWidth):this.setColumnWidth(e.key,i,e.minWidth),e.changed=this.columnWidths[e.key]!==e.initialSavedWidth},this.stopColumnResize=t=>{if(!this.columnResize)return;const{changed:e,handle:i}=this.columnResize;i.classList.remove("resizing"),this.columnResize=void 0,document.body.style.userSelect=this.previousBodyUserSelect,this.toggleAttribute("column-resizing",!1),window.removeEventListener("pointermove",this.handleColumnResizeMove),window.removeEventListener("pointerup",this.stopColumnResize),window.removeEventListener("pointercancel",this.stopColumnResize),"pointerup"===(null==t?void 0:t.type)&&(this.suppressHeaderClick=!0,clearTimeout(this.headerClickSuppressionTimeout),this.headerClickSuppressionTimeout=setTimeout(()=>{this.suppressHeaderClick=!1,this.headerClickSuppressionTimeout=null},0)),e&&this.scheduleColumnWidthSave()}}willUpdate(t){var e;if(super.willUpdate(t),t.has("columnWidthSettings")||t.has("historyStateKey")||t.has("columns")){const i=null===(e=this.columnWidthSettings)||void 0===e?void 0:e[this.historyStateKey],o={};i&&"object"==typeof i&&Object.entries(i).forEach(([t,e])=>{if("number"==typeof e&&Number.isFinite(e)){const i=this.columns.find(e=>e.key===t);o[t]=this.clampColumnWidth(e,i?this.minimumColumnWidth(i):Bp.MIN_COLUMN_WIDTH)}});const s=t.has("columnWidthSettings")||t.has("historyStateKey")?{}:this.columnWidths;this.columnWidths={...o,...s}}}connectedCallback(){super.connectedCallback(),this.urlState?(this.readUrlState(),this.popstateHandler=()=>{this.readUrlState(),this.fetchPage()},window.addEventListener("popstate",this.popstateHandler)):this.historyStateKey&&(this.readHistoryState(),this.popstateHandler=()=>{this.readHistoryState();const t=this.restoreUrl;this.restoreUrl="",this.fetchPage(t||void 0)},window.addEventListener("popstate",this.popstateHandler)),this.resizeHandler=()=>{this.syncScrollAffordance(),this.updateBulkCollapse()},window.addEventListener("resize",this.resizeHandler),document.fonts&&document.fonts.ready&&document.fonts.ready.then(()=>{this.measurePinOffsets(),this.syncScrollAffordance()})}disconnectedCallback(){if(this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),this.resizeHandler&&window.removeEventListener("resize",this.resizeHandler),this.stopColumnResize(),this.columnWidthSaveTimeout&&(clearTimeout(this.columnWidthSaveTimeout),this.columnWidthSaveTimeout=null,this.saveColumnWidths()),this.headerClickSuppressionTimeout&&(clearTimeout(this.headerClickSuppressionTimeout),this.headerClickSuppressionTimeout=null),this.bulkCollapseFrame&&(cancelAnimationFrame(this.bulkCollapseFrame),this.bulkCollapseFrame=0),this.pending){const t=this.pending;this.pending=null,t.abort()}super.disconnectedCallback()}updated(t){if(super.updated(t),(t.has("endpoint")||t.has("refreshKey"))&&this.endpoint){const t=this.restoreUrl;this.restoreUrl="",this.fetchPage(t||void 0)}this.measurePinOffsets(),this.syncScrollAffordance(),this.updateBulkCollapse()}updateBulkCollapse(){this.measureBulkCollapse(),this.bulkCollapseFrame&&cancelAnimationFrame(this.bulkCollapseFrame),this.bulkCollapseFrame=requestAnimationFrame(()=>{this.bulkCollapseFrame=0,this.measureBulkCollapse()})}measureBulkCollapse(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".bulk-bar");if(!e)return;e.classList.add("measuring"),e.classList.remove("collapsed");const i=e.scrollWidth>e.clientWidth+1;e.classList.toggle("collapsed",this.bulkCollapsed),e.offsetWidth,e.classList.remove("measuring"),i!==this.bulkCollapsed&&(this.bulkCollapsed=i)}readUrlState(){const t=new URLSearchParams(window.location.search),e=t=>this.urlParamPrefix?`${this.urlParamPrefix}_${t}`:t,i=this.search;this.search=t.get(e("search"))||"",this.sort=t.get(e("sort"))||"";const o=parseInt(t.get(e("page"))||"1",10);this.page=isNaN(o)||o<1?1:o,this.search?(this.searchOpen=!0,this.searchDraft=this.search):i&&(this.searchOpen=!1,this.searchDraft="")}writeUrlState(t=!1){if(this.bubbleHistoryState(t),!this.urlState)return;const e=this.buildBrowserUrl();t?window.history.replaceState({},"",e):window.history.pushState({},"",e)}buildBrowserUrl(){const t=new URLSearchParams(window.location.search),e=t=>this.urlParamPrefix?`${this.urlParamPrefix}_${t}`:t,i=(e,i)=>{i?t.set(e,i):t.delete(e)};i(e("search"),this.search),i(e("sort"),this.sort),i(e("page"),this.page>1?String(this.page):"");const o=t.toString();return window.location.pathname+(o?"?"+o:"")}readHistoryState(){const t=this.historyStateKey;if(!t)return;const e=window.history.state||{};if(!(t in e))return this.restoreUrl="",void this.readUrlState();const i=e[t]||{},o=this.search;this.search="string"==typeof i.search?i.search:"",this.sort="string"==typeof i.sort?i.sort:"";const s=parseInt(i.page,10);this.page=isNaN(s)||s<1?1:s,this.restoreUrl="string"==typeof i.url?i.url:"",this.search?(this.searchOpen=!0,this.searchDraft=this.search):o&&(this.searchOpen=!1,this.searchDraft="")}bubbleHistoryState(t){if(!this.historyStateKey)return;const e={page:this.page,sort:this.sort,search:this.search};this.cursorMode&&this.currentUrl&&(e.url=this.currentUrl),this.fireCustomEvent(Wo.HistoryChange,{key:this.historyStateKey,state:e,replace:t,url:this.buildBrowserUrl()})}buildRequestUrl(){const t=new URL(this.endpoint,window.location.origin);return this.search&&t.searchParams.set("search",this.search),this.sort&&t.searchParams.set("sort",this.sort),this.page>1&&t.searchParams.set("page",String(this.page)),50!==this.pageSize&&t.searchParams.set("page_size",String(this.pageSize)),t.pathname+t.search}detectCursorMode(t){const e=t=>{if(!t)return!1;try{return new URL(t,window.location.origin).searchParams.has("cursor")}catch(t){return!1}};return!(!e(t.next)&&!e(t.previous))||null==t.count}toRequestUrl(t){try{const e=new URL(t,window.location.origin);return e.origin!==window.location.origin?"":e.pathname+e.search}catch(t){return""}}async fetchPage(t){var e;if(!this.endpoint)return;this.pending&&this.pending.abort();const i=new AbortController;this.pending=i,this.loading=!0,this.searchError="";const o=this.searching,s=t||this.buildRequestUrl();this.currentUrl=s;try{const t=(await fe(s,i)).json||{};this.searchError="string"==typeof t.error?t.error:"",this.items=t.results||[],this.nextCursor=t.next?this.toRequestUrl(t.next):"",this.prevCursor=t.previous?this.toRequestUrl(t.previous):"",this.cursorMode=this.detectCursorMode(t),this.hasCount=null!=t.count,this.total=null!==(e=t.count)&&void 0!==e?e:this.items.length,this.cursorMode&&!this.prevCursor&&1!==this.page&&(this.page=1,this.writeUrlState(!0));const n=new Set(this.items.map(t=>this.rowId(t))),r=new Set;this.selectedIds.forEach(t=>{n.has(t)&&r.add(t)}),this.selectedIds=r,o&&"string"==typeof t.query&&(this.search=t.query,this.searchDraft=t.query,this.writeUrlState(!0))}catch(t){"AbortError"!==(null==t?void 0:t.name)&&console.error("ContentList fetch failed",t)}finally{this.pending===i&&(this.pending=null,this.loading=!1,this.searching=!1,o&&this.searchOpen&&this.updateComplete.then(()=>this.focusSearchEnd()),this.fireCustomEvent(Wo.FetchComplete))}}focusSearchEnd(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".searchbar input");if(!e)return;e.focus();const i=e.value.length;e.setSelectionRange(i,i)}refresh(){this.labelsByActionKey={},this.fetchPage(this.currentUrl||void 0)}rowId(t){const e=null==t?void 0:t[this.valueKey];return null!=e?String(e):JSON.stringify(t)}renderCell(t,e){const i=null==t?void 0:t[e.key];return null==i?"":String(i)}getRowHref(t){return null}handleSearchInput(t){this.searchDraft=t.target.value||""}handleSearchKey(t){"Enter"===t.key?(t.preventDefault(),this.commitSearch()):"Escape"===t.key&&(t.preventDefault(),this.toggleSearch())}commitSearch(){this.search!==this.searchDraft&&(this.search=this.searchDraft,this.page=1,this.searching=!0,this.fetchPage(),this.writeUrlState())}handleSortClick(t){t.sortable&&(this.sort===t.key?this.sort="-"+t.key:this.sort==="-"+t.key?this.sort="":this.sort=t.key,this.page=1,this.fetchPage(),this.writeUrlState())}handleColumnHeaderClick(t,e){if(this.suppressHeaderClick)return t.preventDefault(),t.stopPropagation(),this.suppressHeaderClick=!1,clearTimeout(this.headerClickSuppressionTimeout),void(this.headerClickSuppressionTimeout=null);this.handleSortClick(e)}handleRowClick(t,e){if(e.composedPath().some(t=>{var e,i;return null===(i=null===(e=null==t?void 0:t.classList)||void 0===e?void 0:e.contains)||void 0===i?void 0:i.call(e,"check-cell")}))return;this.fireCustomEvent(Wo.RowClick,{item:t});const i=this.getRowHref(t);if(i&&this.isSafeHref(i)){if(e.metaKey||e.ctrlKey)return void window.open(i,"_blank");this.fireCustomEvent(Wo.Redirected,{url:i})}}isSafeHref(t){if("string"!=typeof t||0===t.length)return!1;if(t.startsWith("//"))return!1;if(t.startsWith("/"))return!0;try{return new URL(t,window.location.origin).origin===window.location.origin}catch(t){return!1}}handleRowToggle(t){const e=this.rowId(t),i=new Set(this.selectedIds);i.has(e)?i.delete(e):i.add(e),this.selectedIds=i,this.fireCustomEvent(Wo.SelectionChange,{ids:Array.from(i)})}handleSelectAll(){const t=this.items.map(t=>this.rowId(t)),e=t.length>0&&t.every(t=>this.selectedIds.has(t));this.selectedIds=e?new Set:new Set(t),this.fireCustomEvent(Wo.SelectionChange,{ids:Array.from(this.selectedIds)})}async handleBulkAction(t){if(t.confirm&&!window.confirm(t.confirm))return;const e=Array.from(this.selectedIds);if(this.actionEndpoint&&!t.clientOnly){const i=new URLSearchParams;i.append("action",t.key),e.forEach(t=>i.append("objects",t));try{await _e(this.actionEndpoint,i),await this.fetchPage(this.currentUrl||void 0),this.recheckSelection(e),this.fireCustomEvent(Wo.BulkAction,{action:t.key,ids:e})}catch(t){console.error("bulk action POST failed",t)}}else this.fireCustomEvent(Wo.BulkAction,{action:t.key,ids:e})}handlePage(t){if(this.cursorMode){const e=t>0?this.nextCursor:this.prevCursor;return void(e&&(this.page=Math.max(1,this.page+t),this.fetchPage(e),this.writeUrlState()))}const e=Math.max(1,Math.ceil(this.total/this.pageSize)),i=Math.min(e,Math.max(1,this.page+t));i!==this.page&&(this.page=i,this.fetchPage(),this.writeUrlState())}renderTitlebar(){const t=this.subtitle||this.querySelector('[slot="subtitle"]');return G`
11529
+ `}contentMenuEndpointWithSearch(){if(!this.contentMenuEndpoint)return this.contentMenuEndpoint;try{const t=new URL(this.contentMenuEndpoint,window.location.origin);return this.search?t.searchParams.set("search",this.search):t.searchParams.delete("search"),t.pathname+t.search}catch(t){return this.contentMenuEndpoint}}get hasCheckboxes(){return this.selectable&&this.bulkActions.length>0}constructor(){super(),this.contentMenuEndpoint="",this.columns=[],this.bulkActions=[],this.valueKey="uuid",this.pageSize=50,this.searchable=!0,this.selectable=!0,this.fixedLayout=!1,this.minTableWidth="",this.fillWindow=!1,this.urlState=!1,this.urlParamPrefix="",this.historyStateKey="",this.columnWidthSettings={},this.settingsEndpoint="",this.saveDelay=500,this.searchPlaceholder="Search",this.listTitle="",this.subtitle="",this.emptyMessage="Nothing to show",this.refreshKey="",this.actionEndpoint="",this.items=[],this.total=0,this.hasCount=!1,this.page=1,this.cursorMode=!1,this.nextCursor="",this.prevCursor="",this.currentUrl="",this.restoreUrl="",this.sort="",this.search="",this.loading=!1,this.searching=!1,this.searchError="",this.selectedIds=new Set,this.searchOpen=!1,this.searchDraft="",this.labelsByActionKey={},this.pendingLabel=null,this.bulkCollapsed=!1,this.bulkCollapseFrame=0,this.pending=null,this.previousBodyUserSelect="",this.previousBodyUserSelectDrag="",this.draggingColumnKey="",this.columnDropSlot=-1,this.columnWidths={},this.columnWidthSaveTimeout=null,this.suppressHeaderClick=!1,this.headerClickSuppressionTimeout=null,this.pinIndexByColumn=new Map,this.rightPinIndexByColumn=new Map,this.checkPinIndex=-1,this.lastPinIndex=-1,this.firstRightPinIndex=-1,this.spacerAfterIndex=-1,this.reservesIcon=!1,this.handleColumnResizeMove=t=>{if(!this.columnResize)return;t.preventDefault();const e=this.columnResize,i=e.startWidth+t.clientX-e.startX;e.nativeFloor&&(i<=e.minWidth||e.minWidth>=Bp.MAX_COLUMN_WIDTH)?this.restoreColumnWidth(e.key,e.initialSavedWidth):this.setColumnWidth(e.key,i,e.minWidth),e.changed=this.columnWidths[e.key]!==e.initialSavedWidth},this.stopColumnResize=t=>{if(!this.columnResize)return;const{changed:e,handle:i}=this.columnResize;i.classList.remove("resizing"),this.columnResize=void 0,document.body.style.userSelect=this.previousBodyUserSelect,this.toggleAttribute("column-resizing",!1),window.removeEventListener("pointermove",this.handleColumnResizeMove),window.removeEventListener("pointerup",this.stopColumnResize),window.removeEventListener("pointercancel",this.stopColumnResize),"pointerup"===(null==t?void 0:t.type)&&(this.suppressHeaderClick=!0,clearTimeout(this.headerClickSuppressionTimeout),this.headerClickSuppressionTimeout=setTimeout(()=>{this.suppressHeaderClick=!1,this.headerClickSuppressionTimeout=null},0)),e&&this.scheduleColumnWidthSave()},this.handleColumnDragMove=t=>{const e=this.columnDrag;if(e&&t.pointerId===e.pointerId){if(!e.started){if(Math.abs(t.clientX-e.startX)<Bp.DRAG_DEAD_ZONE)return;e.started=!0;try{e.header.setPointerCapture(e.pointerId)}catch(t){}e.ghost=this.createColumnDragGhost(e.header),this.draggingColumnKey=e.key,this.previousBodyUserSelectDrag=document.body.style.userSelect,document.body.style.userSelect="none",this.toggleAttribute("column-dragging",!0)}t.preventDefault(),e.ghost&&(e.ghost.style.left=t.clientX-e.grabOffsetX+"px"),this.columnDropSlot=this.computeColumnDropSlot(t.clientX)}},this.stopColumnDrag=t=>{const e=this.columnDrag;if(!e)return;if(t instanceof PointerEvent&&t.pointerId!==e.pointerId)return;const i=this.columnDropSlot;if(this.teardownColumnDrag(),!e.started)return;"pointerup"===(null==t?void 0:t.type)&&(this.suppressHeaderClick=!0,clearTimeout(this.headerClickSuppressionTimeout),this.headerClickSuppressionTimeout=setTimeout(()=>{this.suppressHeaderClick=!1,this.headerClickSuppressionTimeout=null},0));const o=this.columns.findIndex(t=>t.key===e.key);if(-1===o||i<0)return;const s=i>o?i-1:i;if(s===o)return;const n=[...this.columns],[r]=n.splice(o,1);n.splice(s,0,r),this.columns=n,this.fireCustomEvent(Wo.ColumnOrderChanged,{keys:n.map(t=>t.key),from:o,to:s}),this.onColumnOrderChanged(n)},this.cancelColumnDrag=t=>{const e=this.columnDrag;e&&(t instanceof PointerEvent&&t.pointerId!==e.pointerId||this.teardownColumnDrag())}}willUpdate(t){var e;if(super.willUpdate(t),t.has("columnWidthSettings")||t.has("historyStateKey")||t.has("columns")){const i=null===(e=this.columnWidthSettings)||void 0===e?void 0:e[this.historyStateKey],o={};i&&"object"==typeof i&&Object.entries(i).forEach(([t,e])=>{if("number"==typeof e&&Number.isFinite(e)){const i=this.columns.find(e=>e.key===t);o[t]=this.clampColumnWidth(e,i?this.minimumColumnWidth(i):Bp.MIN_COLUMN_WIDTH)}});const s=t.has("columnWidthSettings")||t.has("historyStateKey")?{}:this.columnWidths;this.columnWidths={...o,...s}}}connectedCallback(){super.connectedCallback(),this.urlState?(this.readUrlState(),this.popstateHandler=()=>{this.readUrlState(),this.fetchPage()},window.addEventListener("popstate",this.popstateHandler)):this.historyStateKey&&(this.readHistoryState(),this.popstateHandler=()=>{this.readHistoryState();const t=this.restoreUrl;this.restoreUrl="",this.fetchPage(t||void 0)},window.addEventListener("popstate",this.popstateHandler)),this.resizeHandler=()=>{this.syncScrollAffordance(),this.updateBulkCollapse()},window.addEventListener("resize",this.resizeHandler),document.fonts&&document.fonts.ready&&document.fonts.ready.then(()=>{this.measurePinOffsets(),this.syncScrollAffordance()})}disconnectedCallback(){if(this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),this.resizeHandler&&window.removeEventListener("resize",this.resizeHandler),this.stopColumnResize(),this.cancelColumnDrag(),this.columnWidthSaveTimeout&&(clearTimeout(this.columnWidthSaveTimeout),this.columnWidthSaveTimeout=null,this.saveColumnWidths()),this.headerClickSuppressionTimeout&&(clearTimeout(this.headerClickSuppressionTimeout),this.headerClickSuppressionTimeout=null),this.bulkCollapseFrame&&(cancelAnimationFrame(this.bulkCollapseFrame),this.bulkCollapseFrame=0),this.pending){const t=this.pending;this.pending=null,t.abort()}super.disconnectedCallback()}updated(t){if(super.updated(t),(t.has("endpoint")||t.has("refreshKey"))&&this.endpoint){const t=this.restoreUrl;this.restoreUrl="",this.fetchPage(t||void 0)}this.measurePinOffsets(),this.syncScrollAffordance(),this.updateBulkCollapse()}updateBulkCollapse(){this.measureBulkCollapse(),this.bulkCollapseFrame&&cancelAnimationFrame(this.bulkCollapseFrame),this.bulkCollapseFrame=requestAnimationFrame(()=>{this.bulkCollapseFrame=0,this.measureBulkCollapse()})}measureBulkCollapse(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".bulk-bar");if(!e)return;e.classList.add("measuring"),e.classList.remove("collapsed");const i=e.scrollWidth>e.clientWidth+1;e.classList.toggle("collapsed",this.bulkCollapsed),e.offsetWidth,e.classList.remove("measuring"),i!==this.bulkCollapsed&&(this.bulkCollapsed=i)}readUrlState(){const t=new URLSearchParams(window.location.search),e=t=>this.urlParamPrefix?`${this.urlParamPrefix}_${t}`:t,i=this.search;this.search=t.get(e("search"))||"",this.sort=t.get(e("sort"))||"";const o=parseInt(t.get(e("page"))||"1",10);this.page=isNaN(o)||o<1?1:o,this.search?(this.searchOpen=!0,this.searchDraft=this.search):i&&(this.searchOpen=!1,this.searchDraft="")}writeUrlState(t=!1){if(this.bubbleHistoryState(t),!this.urlState)return;const e=this.buildBrowserUrl();t?window.history.replaceState({},"",e):window.history.pushState({},"",e)}buildBrowserUrl(){const t=new URLSearchParams(window.location.search),e=t=>this.urlParamPrefix?`${this.urlParamPrefix}_${t}`:t,i=(e,i)=>{i?t.set(e,i):t.delete(e)};i(e("search"),this.search),i(e("sort"),this.sort),i(e("page"),this.page>1?String(this.page):"");const o=t.toString();return window.location.pathname+(o?"?"+o:"")}readHistoryState(){const t=this.historyStateKey;if(!t)return;const e=window.history.state||{};if(!(t in e))return this.restoreUrl="",void this.readUrlState();const i=e[t]||{},o=this.search;this.search="string"==typeof i.search?i.search:"",this.sort="string"==typeof i.sort?i.sort:"";const s=parseInt(i.page,10);this.page=isNaN(s)||s<1?1:s,this.restoreUrl="string"==typeof i.url?i.url:"",this.search?(this.searchOpen=!0,this.searchDraft=this.search):o&&(this.searchOpen=!1,this.searchDraft="")}bubbleHistoryState(t){if(!this.historyStateKey)return;const e={page:this.page,sort:this.sort,search:this.search};this.cursorMode&&this.currentUrl&&(e.url=this.currentUrl),this.fireCustomEvent(Wo.HistoryChange,{key:this.historyStateKey,state:e,replace:t,url:this.buildBrowserUrl()})}buildRequestUrl(){const t=new URL(this.endpoint,window.location.origin);return this.search&&t.searchParams.set("search",this.search),this.sort&&t.searchParams.set("sort",this.sort),this.page>1&&t.searchParams.set("page",String(this.page)),50!==this.pageSize&&t.searchParams.set("page_size",String(this.pageSize)),t.pathname+t.search}detectCursorMode(t){const e=t=>{if(!t)return!1;try{return new URL(t,window.location.origin).searchParams.has("cursor")}catch(t){return!1}};return!(!e(t.next)&&!e(t.previous))||null==t.count}toRequestUrl(t){try{const e=new URL(t,window.location.origin);return e.origin!==window.location.origin?"":e.pathname+e.search}catch(t){return""}}async fetchPage(t){var e;if(!this.endpoint)return;this.pending&&this.pending.abort();const i=new AbortController;this.pending=i,this.loading=!0,this.searchError="";const o=this.searching,s=t||this.buildRequestUrl();this.currentUrl=s;try{const t=(await fe(s,i)).json||{};this.searchError="string"==typeof t.error?t.error:"",this.items=t.results||[],this.nextCursor=t.next?this.toRequestUrl(t.next):"",this.prevCursor=t.previous?this.toRequestUrl(t.previous):"",this.cursorMode=this.detectCursorMode(t),this.hasCount=null!=t.count,this.total=null!==(e=t.count)&&void 0!==e?e:this.items.length,this.cursorMode&&!this.prevCursor&&1!==this.page&&(this.page=1,this.writeUrlState(!0));const n=new Set(this.items.map(t=>this.rowId(t))),r=new Set;this.selectedIds.forEach(t=>{n.has(t)&&r.add(t)}),this.selectedIds=r,o&&"string"==typeof t.query&&(this.search=t.query,this.searchDraft=t.query,this.writeUrlState(!0))}catch(t){"AbortError"!==(null==t?void 0:t.name)&&console.error("ContentList fetch failed",t)}finally{this.pending===i&&(this.pending=null,this.loading=!1,this.searching=!1,o&&this.searchOpen&&this.updateComplete.then(()=>this.focusSearchEnd()),this.fireCustomEvent(Wo.FetchComplete))}}focusSearchEnd(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".searchbar input");if(!e)return;e.focus();const i=e.value.length;e.setSelectionRange(i,i)}refresh(){this.labelsByActionKey={},this.fetchPage(this.currentUrl||void 0)}rowId(t){const e=null==t?void 0:t[this.valueKey];return null!=e?String(e):JSON.stringify(t)}renderCell(t,e){const i=null==t?void 0:t[e.key];return null==i?"":String(i)}getRowHref(t){return null}handleSearchInput(t){this.searchDraft=t.target.value||""}handleSearchKey(t){"Enter"===t.key?(t.preventDefault(),this.commitSearch()):"Escape"===t.key&&(t.preventDefault(),this.toggleSearch())}commitSearch(){this.search!==this.searchDraft&&(this.search=this.searchDraft,this.page=1,this.searching=!0,this.fetchPage(),this.writeUrlState())}handleSortClick(t){t.sortable&&(this.sort===t.key?this.sort="-"+t.key:this.sort==="-"+t.key?this.sort="":this.sort=t.key,this.page=1,this.fetchPage(),this.writeUrlState())}handleColumnHeaderClick(t,e){if(this.suppressHeaderClick)return t.preventDefault(),t.stopPropagation(),this.suppressHeaderClick=!1,clearTimeout(this.headerClickSuppressionTimeout),void(this.headerClickSuppressionTimeout=null);this.handleSortClick(e)}handleRowClick(t,e){if(e.composedPath().some(t=>{var e,i;return null===(i=null===(e=null==t?void 0:t.classList)||void 0===e?void 0:e.contains)||void 0===i?void 0:i.call(e,"check-cell")}))return;this.fireCustomEvent(Wo.RowClick,{item:t});const i=this.getRowHref(t);if(i&&this.isSafeHref(i)){if(e.metaKey||e.ctrlKey)return void window.open(i,"_blank");this.fireCustomEvent(Wo.Redirected,{url:i})}}isSafeHref(t){if("string"!=typeof t||0===t.length)return!1;if(t.startsWith("//"))return!1;if(t.startsWith("/"))return!0;try{return new URL(t,window.location.origin).origin===window.location.origin}catch(t){return!1}}handleRowToggle(t){const e=this.rowId(t),i=new Set(this.selectedIds);i.has(e)?i.delete(e):i.add(e),this.selectedIds=i,this.fireCustomEvent(Wo.SelectionChange,{ids:Array.from(i)})}handleSelectAll(){const t=this.items.map(t=>this.rowId(t)),e=t.length>0&&t.every(t=>this.selectedIds.has(t));this.selectedIds=e?new Set:new Set(t),this.fireCustomEvent(Wo.SelectionChange,{ids:Array.from(this.selectedIds)})}async handleBulkAction(t){if(t.confirm&&!window.confirm(t.confirm))return;const e=Array.from(this.selectedIds);if(this.actionEndpoint&&!t.clientOnly){const i=new URLSearchParams;i.append("action",t.key),e.forEach(t=>i.append("objects",t));try{await _e(this.actionEndpoint,i),await this.fetchPage(this.currentUrl||void 0),this.recheckSelection(e),this.fireCustomEvent(Wo.BulkAction,{action:t.key,ids:e})}catch(t){console.error("bulk action POST failed",t)}}else this.fireCustomEvent(Wo.BulkAction,{action:t.key,ids:e})}handlePage(t){if(this.cursorMode){const e=t>0?this.nextCursor:this.prevCursor;return void(e&&(this.page=Math.max(1,this.page+t),this.fetchPage(e),this.writeUrlState()))}const e=Math.max(1,Math.ceil(this.total/this.pageSize)),i=Math.min(e,Math.max(1,this.page+t));i!==this.page&&(this.page=i,this.fetchPage(),this.writeUrlState())}renderTitlebar(){const t=this.subtitle||this.querySelector('[slot="subtitle"]');return G`
11223
11530
  <temba-page-header
11224
11531
  content-menu-endpoint=${this.contentMenuEndpointWithSearch()}
11225
11532
  >
@@ -11322,7 +11629,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11322
11629
  ></temba-checkbox>
11323
11630
  <span class="lbl-name">${t.name}</span>
11324
11631
  </div>
11325
- `}async handleLabelDropdownOpened(t){var e;if(!this.labelsByActionKey[t.key]&&t.labelsEndpoint)try{const i=((null===(e=(await fe(t.labelsEndpoint)).json)||void 0===e?void 0:e.results)||[]).slice().sort((t,e)=>String(t.name||"").localeCompare(String(e.name||"")));this.labelsByActionKey={...this.labelsByActionKey,[t.key]:i}}catch(e){this.labelsByActionKey={...this.labelsByActionKey,[t.key]:[]},console.error("failed to fetch labels",e)}}computeLabelState(t,e="labels"){const i=this.items.filter(t=>this.selectedIds.has(this.rowId(t)));if(0===i.length)return"none";const o=i.filter(i=>(i[e]||[]).some(e=>e.uuid===t));return 0===o.length?"none":o.length===i.length?"all":"some"}async toggleLabel(t,e){if(null!==this.pendingLabel)return;const i="all"!==e,o=Array.from(this.selectedIds);this.pendingLabel=t.uuid;try{if(this.actionEndpoint){const e=new URLSearchParams;e.append("action","label"),e.append("label",t.uuid),i||e.append("add","false"),o.forEach(t=>e.append("objects",t));try{await _e(this.actionEndpoint,e),await this.fetchPage(this.currentUrl||void 0),this.recheckSelection(o),this.fireCustomEvent(Wo.BulkAction,{action:"label",ids:o,label:t.uuid,add:i})}catch(t){console.error("label toggle POST failed",t)}}else this.fireCustomEvent(Wo.BulkAction,{action:"label",ids:o,label:t.uuid,add:i})}finally{this.pendingLabel=null}}recheckSelection(t){const e=new Set(this.items.map(t=>this.rowId(t)));this.selectedIds=new Set(t.filter(t=>e.has(t)))}toggleSearch(){this.searchOpen=!this.searchOpen,this.searchOpen?(this.searchDraft=this.search,this.updateComplete.then(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".searchbar input");null==e||e.focus()})):this.search?this.clearSearch():this.searchDraft=""}clearSearch(){this.searchDraft="",this.search&&(this.search="",this.page=1,this.searching=!1,this.fetchPage(),this.writeUrlState())}renderStatusPill(t,e){return G`<span class="status-pill status-${t}">${e}</span>`}getRowIcon(t){return null}isLeftPinned(t){return!0===t.pinned||"left"===t.pinned}isRightPinned(t){return"right"===t.pinned}computePinLayout(){this.reservesIcon=this.items.some(t=>null!==this.getRowIcon(t)),this.pinIndexByColumn=new Map,this.rightPinIndexByColumn=new Map,this.checkPinIndex=-1,this.lastPinIndex=-1,this.firstRightPinIndex=-1,this.spacerAfterIndex=-1;let t=0;for(let e=this.columns.length-1;e>=0&&this.isRightPinned(this.columns[e]);e--)this.rightPinIndexByColumn.set(this.columns[e],t++);this.firstRightPinIndex=t-1;const e=this.columns.filter(t=>this.isLeftPinned(t)).length;if(0===e)return;let i=0;this.hasCheckboxes&&(this.checkPinIndex=i++),this.columns.forEach(t=>{this.isLeftPinned(t)&&this.pinIndexByColumn.set(t,i++)}),this.lastPinIndex=i-1,this.spacerAfterIndex=this.columns.some(t=>t.grow)?-1:e-1}pinClass(t){return t<0?"":t===this.lastPinIndex?"pinned pin-last":"pinned"}pinStyle(t){return t<0?"":`left: var(--cl-pin-${t}, 0px);`}columnPinClass(t){const e=this.pinIndexByColumn.get(t);if(null!=e)return this.pinClass(e);const i=this.rightPinIndexByColumn.get(t);return null!=i?i===this.firstRightPinIndex?"pinned pin-right pin-first":"pinned pin-right":""}columnPinStyle(t){const e=this.pinIndexByColumn.get(t);if(null!=e)return`left: var(--cl-pin-${e}, 0px);`;const i=this.rightPinIndexByColumn.get(t);return null!=i?`right: var(--cl-rpin-${i}, 0px);`:""}cellWidthStyle(t){const e=this.savedColumnWidth(t);if(this.fixedLayout)return"";if(null!=e)return`width: ${e}px;`;if(t.width)return`width: ${t.width};`;const i=[];return t.minWidth&&i.push(`min-width: ${t.minWidth};`),t.grow||i.push(`max-width: ${t.maxWidth||"320px"};`),i.join(" ")}columnWidthPixels(t,e){if(!t||!t.trim().endsWith("px"))return e;const i=Number.parseFloat(t);return Number.isFinite(i)?i:e}clampColumnWidth(t,e=Bp.MIN_COLUMN_WIDTH){const i=Math.min(e,Bp.MAX_COLUMN_WIDTH);return Math.round(Math.min(Math.max(t,i),Bp.MAX_COLUMN_WIDTH))}isColumnResizable(t){return!0===t.resizable&&!t.grow}savedColumnWidth(t){return this.isColumnResizable(t)?this.columnWidths[t.key]:void 0}effectiveColumnWidth(t){var e;return null!==(e=this.savedColumnWidth(t))&&void 0!==e?e:this.columnWidthPixels(t.width,Bp.MIN_COLUMN_WIDTH)}minimumColumnWidth(t){var e;return this.columnWidthPixels(null!==(e=t.resizeMinWidth)&&void 0!==e?e:t.minWidth,Bp.MIN_COLUMN_WIDTH)}maximumColumnWidth(t){return this.columnWidthPixels(t.maxWidth,Bp.MAX_COLUMN_WIDTH)}hasPrescribedColumnWidth(t){return null!=this.savedColumnWidth(t)||null!=t.width}hasColumnWidthSlackSink(){return this.columns.some(t=>t.grow)||this.spacerAfterIndex>=0}usesNativeWidthFloor(t,e,i){return!this.hasColumnWidthSlackSink()&&this.hasPrescribedColumnWidth(t)&&e>i+1}setColumnWidth(t,e,i=Bp.MIN_COLUMN_WIDTH){const o=this.clampColumnWidth(e,i);return this.columnWidths[t]===o||(this.columnWidths={...this.columnWidths,[t]:o},this.requestUpdate()),o}restoreColumnWidth(t,e){if(this.columnWidths[t]===e)return;const i={...this.columnWidths};null==e?delete i[t]:i[t]=e,this.columnWidths=i,this.requestUpdate()}renderedColumnWidth(t,e){if(!t)return this.effectiveColumnWidth(e);const i=getComputedStyle(t),o=Number.parseFloat(i.paddingLeft)+Number.parseFloat(i.paddingRight),s=t.getBoundingClientRect().width-o;return Number.isFinite(s)&&s>0?s:this.effectiveColumnWidth(e)}scheduleColumnWidthSave(){this.settingsEndpoint&&this.historyStateKey&&(clearTimeout(this.columnWidthSaveTimeout),this.columnWidthSaveTimeout=setTimeout(()=>{this.columnWidthSaveTimeout=null,this.saveColumnWidths()},this.saveDelay))}saveColumnWidths(){this.settingsEndpoint&&this.historyStateKey&&ke(this.settingsEndpoint,{list_columns:{[this.historyStateKey]:this.columnWidths}}).catch(()=>{})}startColumnResize(t,e){if("mouse"===t.pointerType&&0!==t.button)return;this.stopColumnResize(),t.preventDefault(),t.stopPropagation();const i=t.currentTarget;try{i.setPointerCapture(t.pointerId)}catch(t){}const o=this.resizeHeaderForHandle(i),s=this.effectiveColumnWidth(e),n=this.renderedColumnWidth(o,e),r=this.minimumRenderedColumnWidth(o,e),a=this.usesNativeWidthFloor(e,n,s);this.columnResize={key:e.key,startX:t.clientX,startWidth:n,minWidth:a?n:r,nativeFloor:a,initialSavedWidth:this.columnWidths[e.key],changed:!1,handle:i},i.setAttribute("aria-valuemin",`${Math.round(a?n:r)}`),i.classList.add("resizing"),this.previousBodyUserSelect=document.body.style.userSelect,document.body.style.userSelect="none",this.toggleAttribute("column-resizing",!0),window.addEventListener("pointermove",this.handleColumnResizeMove),window.addEventListener("pointerup",this.stopColumnResize),window.addEventListener("pointercancel",this.stopColumnResize)}handleColumnResizeKeydown(t,e){if("ArrowLeft"!==t.key&&"ArrowRight"!==t.key)return;t.preventDefault(),t.stopPropagation();const i=t.currentTarget,o=this.resizeHeaderForHandle(i),s=this.effectiveColumnWidth(e),n=this.renderedColumnWidth(o,e),r=this.minimumRenderedColumnWidth(o,e),a=this.usesNativeWidthFloor(e,n,s),l="ArrowRight"===t.key?1:-1;if(a&&(l<0||n>=Bp.MAX_COLUMN_WIDTH))return void i.setAttribute("aria-valuenow",`${Math.round(n)}`);const d=this.setColumnWidth(e.key,n+l*(t.shiftKey?25:10),a?n:r);i.setAttribute("aria-valuemin",`${Math.round(a?n:r)}`),i.setAttribute("aria-valuenow",`${d}`),this.scheduleColumnWidthSave()}handleColumnResizeFocus(t,e){const i=t.currentTarget,o=this.resizeHeaderForHandle(i);i.setAttribute("aria-valuenow",`${Math.round(this.renderedColumnWidth(o,e))}`)}intrinsicWidth(t){const e=t.getAttribute("style");t.style.width="max-content",t.style.minWidth="0",t.style.maxWidth="none",t.style.position="absolute";const i=t.getBoundingClientRect().width;return null==e?t.removeAttribute("style"):t.setAttribute("style",e),i}minimumRenderedColumnWidth(t,e){const i=this.minimumColumnWidth(e),o=null==t?void 0:t.querySelector(".head-inner");return o?Math.max(i,this.headerContentWidth(o)):i}headerContentWidth(t){return Math.ceil(Array.from(t.children).reduce((t,e)=>t+e.getBoundingClientRect().width,0))}handleColumnAutoFit(t,e){var i;t.preventDefault(),t.stopPropagation();const o=t.currentTarget,s=this.resizeHeaderForHandle(o);if(!s)return;const n=[],r=s.querySelector(".head-inner");r&&n.push(this.headerContentWidth(r));const a=s.cellIndex;null===(i=this.shadowRoot)||void 0===i||i.querySelectorAll("tr.row").forEach(t=>{const e=t.cells.item(a),i=null==e?void 0:e.querySelector(".cell-inner");if(!i)return;let o=this.intrinsicWidth(i);const s=e.querySelector(".lead-icon");if(s){const t=getComputedStyle(s);o+=s.offsetWidth+Number.parseFloat(t.marginRight||"0")}n.push(o)});const l=this.minimumRenderedColumnWidth(s,e),d=Math.max(this.maximumColumnWidth(e),l),c=n.length?Math.max(...n):l,h=this.setColumnWidth(e.key,Math.min(Math.max(c,l),d),l);o.setAttribute("aria-valuenow",`${h}`),this.scheduleColumnWidthSave()}resizeHeaderForHandle(t){const e=t.parentElement;return t.classList.contains("leading")?null==e?void 0:e.previousElementSibling:e}measurePinOffsets(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("tr.header");if(!e)return;const i=Array.from(e.children);let o=0,s=0;for(const t of i){if(!t.classList.contains("pinned"))break;if(t.classList.contains("pin-right"))break;this.style.setProperty(`--cl-pin-${s}`,`${o}px`),o+=t.offsetWidth,s++}let n=0,r=0;for(let t=i.length-1;t>=0&&i[t].classList.contains("pin-right");t--)this.style.setProperty(`--cl-rpin-${r}`,`${n}px`),n+=i[t].offsetWidth,r++;this.style.setProperty("--cl-rpin-total",`${n}px`)}syncScrollAffordance(){var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".table-frame"),o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".table-scroll");if(!i||!o)return;const s=o.scrollWidth-o.clientWidth;i.classList.toggle("overflowing",s>1),i.classList.toggle("scrolled",o.scrollLeft>1),i.classList.toggle("can-scroll-right",o.scrollLeft<s-1),i.classList.toggle("scrolled-down",o.scrollTop>1),this.style.setProperty("--cl-scrollbar-w",o.offsetWidth-o.clientWidth+"px");const n=o.querySelector("table"),r=n?Math.min(o.clientHeight,n.offsetHeight):o.clientHeight;this.style.setProperty("--cl-rows-height",`${r}px`);const a=o.querySelector("tr.header");a&&this.style.setProperty("--cl-header-height",`${a.offsetHeight}px`);const l=i.getBoundingClientRect(),d=o.querySelector("tr.row td.lead-cell .lead-icon")||o.querySelector("tr.row td.cell .cell-inner")||o.querySelector("tr.header th.head-cell .head-inner");d&&this.style.setProperty("--cl-firstcol-left",d.getBoundingClientRect().left-l.left+"px")}renderHeader(){const t=this.items.map(t=>this.rowId(t)),e=t.length>0&&t.every(t=>this.selectedIds.has(t)),i=!e&&this.selectedIds.size>0;return G`
11632
+ `}async handleLabelDropdownOpened(t){var e;if(!this.labelsByActionKey[t.key]&&t.labelsEndpoint)try{const i=((null===(e=(await fe(t.labelsEndpoint)).json)||void 0===e?void 0:e.results)||[]).slice().sort((t,e)=>String(t.name||"").localeCompare(String(e.name||"")));this.labelsByActionKey={...this.labelsByActionKey,[t.key]:i}}catch(e){this.labelsByActionKey={...this.labelsByActionKey,[t.key]:[]},console.error("failed to fetch labels",e)}}computeLabelState(t,e="labels"){const i=this.items.filter(t=>this.selectedIds.has(this.rowId(t)));if(0===i.length)return"none";const o=i.filter(i=>(i[e]||[]).some(e=>e.uuid===t));return 0===o.length?"none":o.length===i.length?"all":"some"}async toggleLabel(t,e){if(null!==this.pendingLabel)return;const i="all"!==e,o=Array.from(this.selectedIds);this.pendingLabel=t.uuid;try{if(this.actionEndpoint){const e=new URLSearchParams;e.append("action","label"),e.append("label",t.uuid),i||e.append("add","false"),o.forEach(t=>e.append("objects",t));try{await _e(this.actionEndpoint,e),await this.fetchPage(this.currentUrl||void 0),this.recheckSelection(o),this.fireCustomEvent(Wo.BulkAction,{action:"label",ids:o,label:t.uuid,add:i})}catch(t){console.error("label toggle POST failed",t)}}else this.fireCustomEvent(Wo.BulkAction,{action:"label",ids:o,label:t.uuid,add:i})}finally{this.pendingLabel=null}}recheckSelection(t){const e=new Set(this.items.map(t=>this.rowId(t)));this.selectedIds=new Set(t.filter(t=>e.has(t)))}toggleSearch(){this.searchOpen=!this.searchOpen,this.searchOpen?(this.searchDraft=this.search,this.updateComplete.then(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".searchbar input");null==e||e.focus()})):this.search?this.clearSearch():this.searchDraft=""}clearSearch(){this.searchDraft="",this.search&&(this.search="",this.page=1,this.searching=!1,this.fetchPage(),this.writeUrlState())}renderStatusPill(t,e){return G`<span class="status-pill status-${t}">${e}</span>`}getRowIcon(t){return null}isLeftPinned(t){return!0===t.pinned||"left"===t.pinned}isRightPinned(t){return"right"===t.pinned}computePinLayout(){this.reservesIcon=this.items.some(t=>null!==this.getRowIcon(t)),this.pinIndexByColumn=new Map,this.rightPinIndexByColumn=new Map,this.checkPinIndex=-1,this.lastPinIndex=-1,this.firstRightPinIndex=-1,this.spacerAfterIndex=-1;let t=0;for(let e=this.columns.length-1;e>=0&&this.isRightPinned(this.columns[e]);e--)this.rightPinIndexByColumn.set(this.columns[e],t++);this.firstRightPinIndex=t-1;const e=this.columns.filter(t=>this.isLeftPinned(t)).length;if(0===e)return;let i=0;this.hasCheckboxes&&(this.checkPinIndex=i++),this.columns.forEach(t=>{this.isLeftPinned(t)&&this.pinIndexByColumn.set(t,i++)}),this.lastPinIndex=i-1,this.spacerAfterIndex=this.columns.some(t=>t.grow)?-1:e-1}pinClass(t){return t<0?"":t===this.lastPinIndex?"pinned pin-last":"pinned"}pinStyle(t){return t<0?"":`left: var(--cl-pin-${t}, 0px);`}columnPinClass(t){const e=this.pinIndexByColumn.get(t);if(null!=e)return this.pinClass(e);const i=this.rightPinIndexByColumn.get(t);return null!=i?i===this.firstRightPinIndex?"pinned pin-right pin-first":"pinned pin-right":""}columnPinStyle(t){const e=this.pinIndexByColumn.get(t);if(null!=e)return`left: var(--cl-pin-${e}, 0px);`;const i=this.rightPinIndexByColumn.get(t);return null!=i?`right: var(--cl-rpin-${i}, 0px);`:""}cellWidthStyle(t){const e=this.savedColumnWidth(t);if(this.fixedLayout)return"";if(null!=e)return`width: ${e}px;`;if(t.width)return`width: ${t.width};`;const i=[];return t.minWidth&&i.push(`min-width: ${t.minWidth};`),t.grow||i.push(`max-width: ${t.maxWidth||"320px"};`),i.join(" ")}columnWidthPixels(t,e){if(!t||!t.trim().endsWith("px"))return e;const i=Number.parseFloat(t);return Number.isFinite(i)?i:e}clampColumnWidth(t,e=Bp.MIN_COLUMN_WIDTH){const i=Math.min(e,Bp.MAX_COLUMN_WIDTH);return Math.round(Math.min(Math.max(t,i),Bp.MAX_COLUMN_WIDTH))}isColumnResizable(t){return!0===t.resizable&&!t.grow}savedColumnWidth(t){return this.isColumnResizable(t)?this.columnWidths[t.key]:void 0}effectiveColumnWidth(t){var e;return null!==(e=this.savedColumnWidth(t))&&void 0!==e?e:this.columnWidthPixels(t.width,Bp.MIN_COLUMN_WIDTH)}minimumColumnWidth(t){var e;return this.columnWidthPixels(null!==(e=t.resizeMinWidth)&&void 0!==e?e:t.minWidth,Bp.MIN_COLUMN_WIDTH)}maximumColumnWidth(t){return this.columnWidthPixels(t.maxWidth,Bp.MAX_COLUMN_WIDTH)}hasPrescribedColumnWidth(t){return null!=this.savedColumnWidth(t)||null!=t.width}hasColumnWidthSlackSink(){return this.columns.some(t=>t.grow)||this.spacerAfterIndex>=0}usesNativeWidthFloor(t,e,i){return!this.hasColumnWidthSlackSink()&&this.hasPrescribedColumnWidth(t)&&e>i+1}setColumnWidth(t,e,i=Bp.MIN_COLUMN_WIDTH){const o=this.clampColumnWidth(e,i);return this.columnWidths[t]===o||(this.columnWidths={...this.columnWidths,[t]:o},this.requestUpdate()),o}restoreColumnWidth(t,e){if(this.columnWidths[t]===e)return;const i={...this.columnWidths};null==e?delete i[t]:i[t]=e,this.columnWidths=i,this.requestUpdate()}renderedColumnWidth(t,e){if(!t)return this.effectiveColumnWidth(e);const i=getComputedStyle(t),o=Number.parseFloat(i.paddingLeft)+Number.parseFloat(i.paddingRight),s=t.getBoundingClientRect().width-o;return Number.isFinite(s)&&s>0?s:this.effectiveColumnWidth(e)}scheduleColumnWidthSave(){this.settingsEndpoint&&this.historyStateKey&&(clearTimeout(this.columnWidthSaveTimeout),this.columnWidthSaveTimeout=setTimeout(()=>{this.columnWidthSaveTimeout=null,this.saveColumnWidths()},this.saveDelay))}saveColumnWidths(){this.settingsEndpoint&&this.historyStateKey&&ke(this.settingsEndpoint,{list_columns:{[this.historyStateKey]:this.columnWidths}}).catch(()=>{})}startColumnResize(t,e){if("mouse"===t.pointerType&&0!==t.button)return;this.stopColumnResize(),this.cancelColumnDrag(),t.preventDefault(),t.stopPropagation();const i=t.currentTarget;try{i.setPointerCapture(t.pointerId)}catch(t){}const o=this.resizeHeaderForHandle(i),s=this.effectiveColumnWidth(e),n=this.renderedColumnWidth(o,e),r=this.minimumRenderedColumnWidth(o,e),a=this.usesNativeWidthFloor(e,n,s);this.columnResize={key:e.key,startX:t.clientX,startWidth:n,minWidth:a?n:r,nativeFloor:a,initialSavedWidth:this.columnWidths[e.key],changed:!1,handle:i},i.setAttribute("aria-valuemin",`${Math.round(a?n:r)}`),i.classList.add("resizing"),this.previousBodyUserSelect=document.body.style.userSelect,document.body.style.userSelect="none",this.toggleAttribute("column-resizing",!0),window.addEventListener("pointermove",this.handleColumnResizeMove),window.addEventListener("pointerup",this.stopColumnResize),window.addEventListener("pointercancel",this.stopColumnResize)}reorderableRange(){const t=this.columns.findIndex(t=>t.reorderable);if(-1===t)return null;let e=t;for(;e+1<this.columns.length&&this.columns[e+1].reorderable;)e++;return e>t?[t,e]:null}headerCellForColumn(t){var e;return null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(`th.head-cell[data-key="${CSS.escape(t)}"]`)}startColumnDrag(t,e){if("mouse"===t.pointerType&&0!==t.button)return;if(this.columnResize||this.columnDrag)return;const i=t.currentTarget;this.columnDrag={key:e.key,pointerId:t.pointerId,startX:t.clientX,grabOffsetX:t.clientX-i.getBoundingClientRect().left,started:!1,header:i},window.addEventListener("pointermove",this.handleColumnDragMove),window.addEventListener("pointerup",this.stopColumnDrag),window.addEventListener("pointercancel",this.cancelColumnDrag)}computeColumnDropSlot(t){const e=this.reorderableRange();if(!e)return-1;const[i,o]=e;let s=i;for(let e=i;e<=o;e++){const i=this.headerCellForColumn(this.columns[e].key);if(!i)continue;const o=i.getBoundingClientRect();t>o.left+o.width/2&&(s=e+1)}return s}teardownColumnDrag(){var t;const e=this.columnDrag;this.columnDrag=void 0,this.columnDropSlot=-1,this.draggingColumnKey="",window.removeEventListener("pointermove",this.handleColumnDragMove),window.removeEventListener("pointerup",this.stopColumnDrag),window.removeEventListener("pointercancel",this.cancelColumnDrag),(null==e?void 0:e.started)&&(document.body.style.userSelect=this.previousBodyUserSelectDrag,this.toggleAttribute("column-dragging",!1)),null===(t=null==e?void 0:e.ghost)||void 0===t||t.remove()}onColumnOrderChanged(t){}createColumnDragGhost(t){var e,i,o;const s=t.getBoundingClientRect(),n=getComputedStyle(t),r=document.createElement("div");return r.className="column-drag-ghost",r.setAttribute("aria-hidden","true"),r.textContent=null!==(o=null===(i=null===(e=t.querySelector(".label"))||void 0===e?void 0:e.textContent)||void 0===i?void 0:i.trim())&&void 0!==o?o:"",Object.assign(r.style,{position:"fixed",top:`${s.top}px`,left:`${s.left}px`,height:`${s.height}px`,minWidth:`${s.width}px`,display:"flex",alignItems:"center",boxSizing:"border-box",padding:"0 8px",font:n.font,letterSpacing:n.letterSpacing,textTransform:n.textTransform,color:n.color,background:"var(--surface, #fff)",border:"1px solid var(--border, #e4e7ec)",borderRadius:"var(--curvature, 6px)",boxShadow:"var(--shadow-1, 0 2px 6px rgba(0, 0, 0, 0.12))",pointerEvents:"none",whiteSpace:"nowrap",zIndex:"10000"}),document.body.appendChild(r),r}handleColumnResizeKeydown(t,e){if("ArrowLeft"!==t.key&&"ArrowRight"!==t.key)return;t.preventDefault(),t.stopPropagation();const i=t.currentTarget,o=this.resizeHeaderForHandle(i),s=this.effectiveColumnWidth(e),n=this.renderedColumnWidth(o,e),r=this.minimumRenderedColumnWidth(o,e),a=this.usesNativeWidthFloor(e,n,s),l="ArrowRight"===t.key?1:-1;if(a&&(l<0||n>=Bp.MAX_COLUMN_WIDTH))return void i.setAttribute("aria-valuenow",`${Math.round(n)}`);const d=this.setColumnWidth(e.key,n+l*(t.shiftKey?25:10),a?n:r);i.setAttribute("aria-valuemin",`${Math.round(a?n:r)}`),i.setAttribute("aria-valuenow",`${d}`),this.scheduleColumnWidthSave()}handleColumnResizeFocus(t,e){const i=t.currentTarget,o=this.resizeHeaderForHandle(i);i.setAttribute("aria-valuenow",`${Math.round(this.renderedColumnWidth(o,e))}`)}intrinsicWidth(t){const e=t.getAttribute("style");t.style.width="max-content",t.style.minWidth="0",t.style.maxWidth="none",t.style.position="absolute";const i=t.getBoundingClientRect().width;return null==e?t.removeAttribute("style"):t.setAttribute("style",e),i}minimumRenderedColumnWidth(t,e){const i=this.minimumColumnWidth(e),o=null==t?void 0:t.querySelector(".head-inner");return o?Math.max(i,this.headerContentWidth(o)):i}headerContentWidth(t){return Math.ceil(Array.from(t.children).reduce((t,e)=>t+e.getBoundingClientRect().width,0))}handleColumnAutoFit(t,e){var i;t.preventDefault(),t.stopPropagation();const o=t.currentTarget,s=this.resizeHeaderForHandle(o);if(!s)return;const n=[],r=s.querySelector(".head-inner");r&&n.push(this.headerContentWidth(r));const a=s.cellIndex;null===(i=this.shadowRoot)||void 0===i||i.querySelectorAll("tr.row").forEach(t=>{const e=t.cells.item(a),i=null==e?void 0:e.querySelector(".cell-inner");if(!i)return;let o=this.intrinsicWidth(i);const s=e.querySelector(".lead-icon");if(s){const t=getComputedStyle(s);o+=s.offsetWidth+Number.parseFloat(t.marginRight||"0")}n.push(o)});const l=this.minimumRenderedColumnWidth(s,e),d=Math.max(this.maximumColumnWidth(e),l),c=n.length?Math.max(...n):l,h=this.setColumnWidth(e.key,Math.min(Math.max(c,l),d),l);o.setAttribute("aria-valuenow",`${h}`),this.scheduleColumnWidthSave()}resizeHeaderForHandle(t){const e=t.parentElement;return t.classList.contains("leading")?null==e?void 0:e.previousElementSibling:e}measurePinOffsets(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector("tr.header");if(!e)return;const i=Array.from(e.children);let o=0,s=0;for(const t of i){if(!t.classList.contains("pinned"))break;if(t.classList.contains("pin-right"))break;this.style.setProperty(`--cl-pin-${s}`,`${o}px`),o+=t.offsetWidth,s++}let n=0,r=0;for(let t=i.length-1;t>=0&&i[t].classList.contains("pin-right");t--)this.style.setProperty(`--cl-rpin-${r}`,`${n}px`),n+=i[t].offsetWidth,r++;this.style.setProperty("--cl-rpin-total",`${n}px`)}syncScrollAffordance(){var t,e;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".table-frame"),o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".table-scroll");if(!i||!o)return;const s=o.scrollWidth-o.clientWidth;i.classList.toggle("overflowing",s>1),i.classList.toggle("scrolled",o.scrollLeft>1),i.classList.toggle("can-scroll-right",o.scrollLeft<s-1),i.classList.toggle("scrolled-down",o.scrollTop>1),this.style.setProperty("--cl-scrollbar-w",o.offsetWidth-o.clientWidth+"px");const n=o.querySelector("table"),r=n?Math.min(o.clientHeight,n.offsetHeight):o.clientHeight;this.style.setProperty("--cl-rows-height",`${r}px`);const a=o.querySelector("tr.header");a&&this.style.setProperty("--cl-header-height",`${a.offsetHeight}px`);const l=i.getBoundingClientRect(),d=o.querySelector("tr.row td.lead-cell .lead-icon")||o.querySelector("tr.row td.cell .cell-inner")||o.querySelector("tr.header th.head-cell .head-inner");d&&this.style.setProperty("--cl-firstcol-left",d.getBoundingClientRect().left-l.left+"px")}renderHeader(){const t=this.items.map(t=>this.rowId(t)),e=t.length>0&&t.every(t=>this.selectedIds.has(t)),i=!e&&this.selectedIds.size>0,o=this.reorderableRange(),s=this.draggingColumnKey?this.columns.findIndex(t=>t.key===this.draggingColumnKey):-1;return G`
11326
11633
  <thead>
11327
11634
  <tr class="header">
11328
11635
  ${this.hasCheckboxes?G`
@@ -11340,7 +11647,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11340
11647
  </div>
11341
11648
  </th>
11342
11649
  `:null}
11343
- ${this.columns.map((t,e)=>{const i=this.columns[e-1],o=!i||this.isLeftPinned(i)||this.isRightPinned(i)||this.spacerAfterIndex===e-1?void 0:i,s=e===this.columns.length-1||this.isLeftPinned(t)||this.isRightPinned(t),n=e===this.columns.length-1;return G`${this.renderHeaderCell(t,o,s,n)}${e===this.spacerAfterIndex?G`<th class="spacer">
11650
+ ${this.columns.map((t,e)=>{const i=this.columns[e-1],n=!i||this.isLeftPinned(i)||this.isRightPinned(i)||this.spacerAfterIndex===e-1?void 0:i,r=e===this.columns.length-1||this.isLeftPinned(t)||this.isRightPinned(t),a=e===this.columns.length-1;return G`${this.renderHeaderCell(t,e,o,s,n,r,a)}${e===this.spacerAfterIndex?G`<th class="spacer">
11344
11651
  ${this.isLeftPinned(t)||this.isRightPinned(t)?null:this.renderResizeHandle(t,!0)}
11345
11652
  </th>`:null}`})}
11346
11653
  </tr>
@@ -11359,25 +11666,27 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11359
11666
  @focus=${e=>this.handleColumnResizeFocus(e,t)}
11360
11667
  @click=${t=>t.stopPropagation()}
11361
11668
  @dblclick=${e=>this.handleColumnAutoFit(e,t)}
11362
- ></span>`:null}renderHeaderCell(t,e,i=!1,o=!1){var s;const n=this.sort===t.key||this.sort==="-"+t.key,r=this.sort==="-"+t.key,a=`head-cell ${t.align||""} ${t.sortable?"sortable":""} ${n?"active":""} ${t.grow?"grow":""} ${this.columnPinClass(t)}`,l=G`<span class="label"
11363
- >${null!==(s=t.label)&&void 0!==s?s:t.key}</span
11364
- >`,d=t.sortable?G`<span class="sort-slot"
11669
+ ></span>`:null}renderHeaderCell(t,e,i,o,s,n=!1,r=!1){var a;const l=this.sort===t.key||this.sort==="-"+t.key,d=this.sort==="-"+t.key,c=!!(t.reorderable&&i&&e>=i[0]&&e<=i[1]),h=this.draggingColumnKey===t.key,u=-1===o?-1:this.columnDropSlot,p=u===o||u===o+1,m=!p&&u===e&&c,g=!p&&!!i&&u===i[1]+1&&e===i[1],f=`head-cell ${t.align||""} ${t.sortable?"sortable":""} ${l?"active":""} ${t.grow?"grow":""} ${c?"reorderable":""} ${h?"dragging":""} ${m?"drop-before":""} ${g?"drop-after":""} ${this.columnPinClass(t)}`,v=G`<span class="label"
11670
+ >${null!==(a=t.label)&&void 0!==a?a:t.key}</span
11671
+ >`,b=t.sortable?G`<span class="sort-slot"
11365
11672
  ><temba-icon
11366
11673
  class="sort-icon"
11367
- name=${n?r?Po.sort_down:Po.sort_up:Po.sort}
11674
+ name=${l?d?Po.sort_down:Po.sort_up:Po.sort}
11368
11675
  size="0.85"
11369
11676
  ></temba-icon
11370
- ></span>`:null,c=this.savedColumnWidth(t),h=this.fixedLayout?null!=c?`width: ${c}px;`:t.width?`width: ${t.width};`:"":"";return G`
11677
+ ></span>`:null,y=this.savedColumnWidth(t),x=this.fixedLayout?null!=y?`width: ${y}px;`:t.width?`width: ${t.width};`:"":"";return G`
11371
11678
  <th
11372
- class=${a}
11373
- style="${this.columnPinStyle(t)} ${h}"
11679
+ class=${f}
11680
+ data-key=${t.key}
11681
+ style="${this.columnPinStyle(t)} ${x}"
11374
11682
  @click=${t.sortable?e=>this.handleColumnHeaderClick(e,t):null}
11683
+ @pointerdown=${c?e=>this.startColumnDrag(e,t):null}
11375
11684
  >
11376
- ${this.renderResizeHandle(e,!0)}
11685
+ ${this.renderResizeHandle(s,!0)}
11377
11686
  <div class="head-inner" style=${this.cellWidthStyle(t)}>
11378
- ${"right"===t.align?G`${d}${l}`:G`${l}${d}`}
11687
+ ${"right"===t.align?G`${b}${v}`:G`${v}${b}`}
11379
11688
  </div>
11380
- ${i?this.renderResizeHandle(t,!1,o):null}
11689
+ ${n?this.renderResizeHandle(t,!1,r):null}
11381
11690
  </th>
11382
11691
  `}renderRow(t){const e=this.rowId(t),i=this.selectedIds.has(e),o=this.getRowHref(t);return G`
11383
11692
  <tr
@@ -11468,7 +11777,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11468
11777
  <div class="scroll-shadow"></div>
11469
11778
  </div>
11470
11779
  </div>
11471
- `}}Bp.MIN_COLUMN_WIDTH=80,Bp.MAX_COLUMN_WIDTH=600,i([ft({type:String})],Bp.prototype,"endpoint",void 0),i([ft({type:String,attribute:"content-menu-endpoint"})],Bp.prototype,"contentMenuEndpoint",void 0),i([ft({type:Array,attribute:!1})],Bp.prototype,"columns",void 0),i([ft({type:Array,attribute:!1})],Bp.prototype,"bulkActions",void 0),i([ft({type:String})],Bp.prototype,"valueKey",void 0),i([ft({type:Number})],Bp.prototype,"pageSize",void 0),i([ft({type:Boolean})],Bp.prototype,"searchable",void 0),i([ft({type:Boolean})],Bp.prototype,"selectable",void 0),i([ft({type:Boolean,attribute:"fixed-layout"})],Bp.prototype,"fixedLayout",void 0),i([ft({type:String,attribute:"min-table-width"})],Bp.prototype,"minTableWidth",void 0),i([ft({type:Boolean,attribute:"fill-window"})],Bp.prototype,"fillWindow",void 0),i([ft({type:Boolean})],Bp.prototype,"urlState",void 0),i([ft({type:String})],Bp.prototype,"urlParamPrefix",void 0),i([ft({type:String,attribute:"history-state-key"})],Bp.prototype,"historyStateKey",void 0),i([ft({type:Object,attribute:"column-width-settings"})],Bp.prototype,"columnWidthSettings",void 0),i([ft({type:String,attribute:"settings-endpoint"})],Bp.prototype,"settingsEndpoint",void 0),i([ft({type:String})],Bp.prototype,"searchPlaceholder",void 0),i([ft({type:String,attribute:"list-title"})],Bp.prototype,"listTitle",void 0),i([ft({type:String})],Bp.prototype,"subtitle",void 0),i([ft({type:String})],Bp.prototype,"emptyMessage",void 0),i([ft({type:String})],Bp.prototype,"refreshKey",void 0),i([ft({type:String,attribute:"action-endpoint"})],Bp.prototype,"actionEndpoint",void 0),i([vt()],Bp.prototype,"items",void 0),i([vt()],Bp.prototype,"total",void 0),i([vt()],Bp.prototype,"hasCount",void 0),i([vt()],Bp.prototype,"page",void 0),i([vt()],Bp.prototype,"cursorMode",void 0),i([vt()],Bp.prototype,"nextCursor",void 0),i([vt()],Bp.prototype,"prevCursor",void 0),i([vt()],Bp.prototype,"sort",void 0),i([vt()],Bp.prototype,"search",void 0),i([vt()],Bp.prototype,"loading",void 0),i([vt()],Bp.prototype,"searching",void 0),i([vt()],Bp.prototype,"searchError",void 0),i([vt()],Bp.prototype,"selectedIds",void 0),i([vt()],Bp.prototype,"searchOpen",void 0),i([vt()],Bp.prototype,"searchDraft",void 0),i([vt()],Bp.prototype,"labelsByActionKey",void 0),i([vt()],Bp.prototype,"pendingLabel",void 0),i([vt()],Bp.prototype,"bulkCollapsed",void 0);const Up={"X-Temba-Content-Menu":"1","X-Temba-Spa":"1"};class qp extends Ke{constructor(){super(...arguments),this.headerTitle="",this.subtitle="",this.contentMenuEndpoint="",this.hideMenu=!1,this.buttons=[],this.items=[],this.pendingMenu=null}static get styles(){return d`
11780
+ `}}Bp.DRAG_DEAD_ZONE=5,Bp.MIN_COLUMN_WIDTH=80,Bp.MAX_COLUMN_WIDTH=600,i([ft({type:String})],Bp.prototype,"endpoint",void 0),i([ft({type:String,attribute:"content-menu-endpoint"})],Bp.prototype,"contentMenuEndpoint",void 0),i([ft({type:Array,attribute:!1})],Bp.prototype,"columns",void 0),i([ft({type:Array,attribute:!1})],Bp.prototype,"bulkActions",void 0),i([ft({type:String})],Bp.prototype,"valueKey",void 0),i([ft({type:Number})],Bp.prototype,"pageSize",void 0),i([ft({type:Boolean})],Bp.prototype,"searchable",void 0),i([ft({type:Boolean})],Bp.prototype,"selectable",void 0),i([ft({type:Boolean,attribute:"fixed-layout"})],Bp.prototype,"fixedLayout",void 0),i([ft({type:String,attribute:"min-table-width"})],Bp.prototype,"minTableWidth",void 0),i([ft({type:Boolean,attribute:"fill-window"})],Bp.prototype,"fillWindow",void 0),i([ft({type:Boolean})],Bp.prototype,"urlState",void 0),i([ft({type:String})],Bp.prototype,"urlParamPrefix",void 0),i([ft({type:String,attribute:"history-state-key"})],Bp.prototype,"historyStateKey",void 0),i([ft({type:Object,attribute:"column-width-settings"})],Bp.prototype,"columnWidthSettings",void 0),i([ft({type:String,attribute:"settings-endpoint"})],Bp.prototype,"settingsEndpoint",void 0),i([ft({type:String})],Bp.prototype,"searchPlaceholder",void 0),i([ft({type:String,attribute:"list-title"})],Bp.prototype,"listTitle",void 0),i([ft({type:String})],Bp.prototype,"subtitle",void 0),i([ft({type:String})],Bp.prototype,"emptyMessage",void 0),i([ft({type:String})],Bp.prototype,"refreshKey",void 0),i([ft({type:String,attribute:"action-endpoint"})],Bp.prototype,"actionEndpoint",void 0),i([vt()],Bp.prototype,"items",void 0),i([vt()],Bp.prototype,"total",void 0),i([vt()],Bp.prototype,"hasCount",void 0),i([vt()],Bp.prototype,"page",void 0),i([vt()],Bp.prototype,"cursorMode",void 0),i([vt()],Bp.prototype,"nextCursor",void 0),i([vt()],Bp.prototype,"prevCursor",void 0),i([vt()],Bp.prototype,"sort",void 0),i([vt()],Bp.prototype,"search",void 0),i([vt()],Bp.prototype,"loading",void 0),i([vt()],Bp.prototype,"searching",void 0),i([vt()],Bp.prototype,"searchError",void 0),i([vt()],Bp.prototype,"selectedIds",void 0),i([vt()],Bp.prototype,"searchOpen",void 0),i([vt()],Bp.prototype,"searchDraft",void 0),i([vt()],Bp.prototype,"labelsByActionKey",void 0),i([vt()],Bp.prototype,"pendingLabel",void 0),i([vt()],Bp.prototype,"bulkCollapsed",void 0),i([vt()],Bp.prototype,"draggingColumnKey",void 0),i([vt()],Bp.prototype,"columnDropSlot",void 0);const Up={"X-Temba-Content-Menu":"1","X-Temba-Spa":"1"};class qp extends Ke{constructor(){super(...arguments),this.headerTitle="",this.subtitle="",this.contentMenuEndpoint="",this.hideMenu=!1,this.buttons=[],this.items=[],this.pendingMenu=null}static get styles(){return d`
11472
11781
  ${Mo}
11473
11782
 
11474
11783
  :host {
@@ -11676,7 +11985,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11676
11985
  color: var(--text-3);
11677
11986
  font-size: 12.5px;
11678
11987
  }
11679
- `}constructor(){super(),this.fieldsEndpoint="/api/v2/fields.json",this.anon=!1,this.featuredFields=[],this.valueKey="uuid",this.emptyMessage="No contacts",this.searchPlaceholder="Search contacts",this.columns=this.buildColumns(),this.bulkActions=[{key:"send",label:"Send",icon:Po.compose},{key:"flow",label:"Start flow",icon:Po.flow},{key:"label",label:"Group",icon:Po.group,labelsEndpoint:"/api/v2/groups.json?manual_only=1",labelsKey:"groups"},{key:"archive",label:"Archive",icon:Po.archive},{key:"delete",label:"Delete",icon:Po.delete,destructive:!0}]}connectedCallback(){super.connectedCallback(),this.loadFields()}disconnectedCallback(){this.pendingFieldsController&&(this.pendingFieldsController.abort(),this.pendingFieldsController=void 0),super.disconnectedCallback()}willUpdate(t){super.willUpdate(t),t.has("anon")&&(this.columns=this.buildColumns())}updated(t){super.updated(t),t.has("fieldsEndpoint")&&this.fieldsEndpoint&&this.loadFields()}async loadFields(){var t;if(!this.fieldsEndpoint)return;this.pendingFieldsController&&this.pendingFieldsController.abort();const e=new AbortController;this.pendingFieldsController=e;try{const i=await fe(this.fieldsEndpoint,e);if(this.pendingFieldsController!==e)return;const o=(null===(t=i.json)||void 0===t?void 0:t.results)||[];this.featuredFields=o.filter(t=>t.featured).sort((t,e)=>{var i,o;return(null!==(i=e.priority)&&void 0!==i?i:0)-(null!==(o=t.priority)&&void 0!==o?o:0)}),this.columns=this.buildColumns()}catch(t){"AbortError"!==(null==t?void 0:t.name)&&console.error("failed to fetch contact fields",t)}finally{this.pendingFieldsController===e&&(this.pendingFieldsController=void 0)}}buildColumns(){const t=(this.featuredFields||[]).map(t=>({key:Wp+t.key,label:t.name||t.label||t.key,sortable:!0,resizeMinWidth:"40px",maxWidth:"200px",resizable:!0}));return[{key:"name",label:"Name",minWidth:"150px",maxWidth:"260px",pinned:!0,resizable:!0},this.anon?{key:"ref",label:"Ref",minWidth:"120px",maxWidth:"190px",resizable:!0}:{key:"urn",label:"URN",minWidth:"120px",maxWidth:"190px",resizable:!0},...t,{key:"last_seen_on",label:"Last seen",sortable:!0,minWidth:"96px",maxWidth:"150px",align:"right",resizable:!0},{key:"created_on",label:"Created on",sortable:!0,minWidth:"96px",align:"right",grow:!0}]}getRowIcon(t){return Po.contact}getRowHref(t){return(null==t?void 0:t.uuid)?`/contact/read/${t.uuid}/`:null}renderCell(t,e){var i;if(e.key.startsWith(Wp)){const o=e.key.substring(6),s=null===(i=t.fields)||void 0===i?void 0:i[o];if(null==s||""===s)return jp;if(this.isLocationField(o)){const t=String(s);return G`<span title=${t}>${this.locationLeaf(t)}</span>`}if(this.isDateField(o))return G`<temba-date value=${s} display="timedate"></temba-date>`;const n=String(s);return G`<span title=${n}>${n}</span>`}switch(e.key){case"name":return G`<span class="contact-name" title=${t.name||""}
11988
+ `}constructor(){super(),this.fieldsEndpoint="/api/v2/fields.json",this.priorityEndpoint="",this.anon=!1,this.featuredFields=[],this.valueKey="uuid",this.emptyMessage="No contacts",this.searchPlaceholder="Search contacts",this.columns=this.buildColumns(),this.bulkActions=[{key:"send",label:"Send",icon:Po.compose},{key:"flow",label:"Start flow",icon:Po.flow},{key:"label",label:"Group",icon:Po.group,labelsEndpoint:"/api/v2/groups.json?manual_only=1",labelsKey:"groups"},{key:"archive",label:"Archive",icon:Po.archive},{key:"delete",label:"Delete",icon:Po.delete,destructive:!0}]}connectedCallback(){super.connectedCallback(),this.loadFields()}disconnectedCallback(){this.pendingFieldsController&&(this.pendingFieldsController.abort(),this.pendingFieldsController=void 0),super.disconnectedCallback()}willUpdate(t){super.willUpdate(t),(t.has("anon")||t.has("priorityEndpoint"))&&(this.columns=this.buildColumns())}updated(t){super.updated(t),t.has("fieldsEndpoint")&&this.fieldsEndpoint&&this.loadFields()}async loadFields(){var t,e;if(!this.fieldsEndpoint)return;this.pendingFieldsController&&this.pendingFieldsController.abort();const i=new AbortController;this.pendingFieldsController=i;try{const o=[],s=new Set;let n=this.fieldsEndpoint;for(let r=0;n&&r<20&&!s.has(n);r++){s.add(n);const r=await fe(n,i);if(this.pendingFieldsController!==i)return;o.push(...(null===(t=r.json)||void 0===t?void 0:t.results)||[]),n=(null===(e=r.json)||void 0===e?void 0:e.next)||""}this.featuredFields=o.filter(t=>t.featured).sort((t,e)=>{var i,o;return(null!==(i=e.priority)&&void 0!==i?i:0)-(null!==(o=t.priority)&&void 0!==o?o:0)}),this.columns=this.buildColumns()}catch(t){"AbortError"!==(null==t?void 0:t.name)&&console.error("failed to fetch contact fields",t)}finally{this.pendingFieldsController===i&&(this.pendingFieldsController=void 0)}}buildColumns(){const t=(this.featuredFields||[]).map(t=>({key:Wp+t.key,label:t.name||t.label||t.key,sortable:!0,resizeMinWidth:"40px",maxWidth:"200px",resizable:!0,reorderable:!!this.priorityEndpoint}));return[{key:"name",label:"Name",minWidth:"150px",maxWidth:"260px",pinned:!0,resizable:!0},this.anon?{key:"ref",label:"Ref",minWidth:"120px",maxWidth:"190px",resizable:!0}:{key:"urn",label:"URN",minWidth:"120px",maxWidth:"190px",resizable:!0},...t,{key:"last_seen_on",label:"Last seen",sortable:!0,minWidth:"96px",maxWidth:"150px",align:"right",resizable:!0},{key:"created_on",label:"Created on",sortable:!0,minWidth:"96px",align:"right",grow:!0}]}onColumnOrderChanged(t){this.pendingFieldsController&&(this.pendingFieldsController.abort(),this.pendingFieldsController=void 0);const e=t.filter(t=>t.key.startsWith(Wp)).map(t=>t.key.substring(6));this.featuredFields=e.map(t=>(this.featuredFields||[]).find(e=>e.key===t)).filter(Boolean),this.priorityEndpoint&&ke(this.priorityEndpoint,{featured:e}).then(t=>{if(t.status<200||t.status>=300)throw t}).catch(t=>{console.warn("failed to save featured field order",t),this.isConnected&&this.loadFields()}).finally(()=>{var t;null===(t=Mc())||void 0===t||t.refreshFields().catch(()=>{})})}getRowIcon(t){return Po.contact}getRowHref(t){return(null==t?void 0:t.uuid)?`/contact/read/${t.uuid}/`:null}renderCell(t,e){var i;if(e.key.startsWith(Wp)){const o=e.key.substring(6),s=null===(i=t.fields)||void 0===i?void 0:i[o];if(null==s||""===s)return jp;if(this.isLocationField(o)){const t=String(s);return G`<span title=${t}>${this.locationLeaf(t)}</span>`}if(this.isDateField(o))return G`<temba-date value=${s} display="timedate"></temba-date>`;const n=String(s);return G`<span title=${n}>${n}</span>`}switch(e.key){case"name":return G`<span class="contact-name" title=${t.name||""}
11680
11989
  >${t.name||jp}</span
11681
11990
  >`;case"urn":return G`<span class="contact-urn"
11682
11991
  >${this.primaryUrn(t)||jp}</span
@@ -11688,7 +11997,7 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11688
11997
  ></temba-date>`:jp;case"created_on":return t.created_on?G`<temba-date
11689
11998
  value=${t.created_on}
11690
11999
  display="timedate"
11691
- ></temba-date>`:jp;default:return super.renderCell(t,e)}}isDateField(t){const e=(this.featuredFields||[]).find(e=>e.key===t),i=null==e?void 0:e.value_type;return"datetime"===i||"date"===i}isLocationField(t){const e=(this.featuredFields||[]).find(e=>e.key===t),i=null==e?void 0:e.value_type;return"state"===i||"district"===i||"ward"===i}locationLeaf(t){const e=t.split(">");return e[e.length-1].trim()}primaryUrn(t){const e=t;if(e.urn)return"string"==typeof e.urn?e.urn:e.urn.display||"";if(Array.isArray(e.urns)&&e.urns.length>0){const t=e.urns[0];return"string"==typeof t?t.split(":")[1]||t:(null==t?void 0:t.display)||(null==t?void 0:t.path)||""}return""}}i([ft({type:String,attribute:"fields-endpoint"})],Hp.prototype,"fieldsEndpoint",void 0),i([ft({type:Boolean})],Hp.prototype,"anon",void 0),i([vt()],Hp.prototype,"featuredFields",void 0);const Vp={text:"Text",numeric:"Number",number:"Number",datetime:"Date & Time",state:"State",ward:"Ward",district:"District"},Gp=t=>Vp[t.value_type]||t.value_type||"",Kp=(t,e)=>{if(!e)return!0;return[t.label,t.key,Gp(t)].join(" ").toLowerCase().indexOf(e.toLowerCase())>-1};class Zp extends Gh{constructor(){super(...arguments),this.headerTitle="",this.contentMenuEndpoint="",this.detailEndpoint="",this.otherFieldKeys=[],this.query="",this.searchOpen=!1,this.detailField=null,this.detail=null,this.prepareGhost=t=>{t.style.margin="0",t.style.boxSizing="border-box",t.style.background="var(--surface, #fff)",t.style.border="1px solid var(--border, #e4e7ec)",t.style.borderRadius="var(--curvature, 6px)",t.style.boxShadow="var(--shadow-1, 0 2px 6px rgba(0, 0, 0, 0.12))"},this.handleDetailClosed=()=>{this.detailField=null}}static get styles(){return d`
12000
+ ></temba-date>`:jp;default:return super.renderCell(t,e)}}isDateField(t){const e=(this.featuredFields||[]).find(e=>e.key===t),i=null==e?void 0:e.value_type;return"datetime"===i||"date"===i}isLocationField(t){const e=(this.featuredFields||[]).find(e=>e.key===t),i=null==e?void 0:e.value_type;return"state"===i||"district"===i||"ward"===i}locationLeaf(t){const e=t.split(">");return e[e.length-1].trim()}primaryUrn(t){const e=t;if(e.urn)return"string"==typeof e.urn?e.urn:e.urn.display||"";if(Array.isArray(e.urns)&&e.urns.length>0){const t=e.urns[0];return"string"==typeof t?t.split(":")[1]||t:(null==t?void 0:t.display)||(null==t?void 0:t.path)||""}return""}}i([ft({type:String,attribute:"fields-endpoint"})],Hp.prototype,"fieldsEndpoint",void 0),i([ft({type:String,attribute:"priority-endpoint"})],Hp.prototype,"priorityEndpoint",void 0),i([ft({type:Boolean})],Hp.prototype,"anon",void 0),i([vt()],Hp.prototype,"featuredFields",void 0);const Vp={text:"Text",numeric:"Number",number:"Number",datetime:"Date & Time",state:"State",ward:"Ward",district:"District"},Gp=t=>Vp[t.value_type]||t.value_type||"",Kp=(t,e)=>{if(!e)return!0;return[t.label,t.key,Gp(t)].join(" ").toLowerCase().indexOf(e.toLowerCase())>-1};class Zp extends Gh{constructor(){super(...arguments),this.headerTitle="",this.contentMenuEndpoint="",this.detailEndpoint="",this.otherFieldKeys=[],this.query="",this.searchOpen=!1,this.detailField=null,this.detail=null,this.prepareGhost=t=>{t.style.margin="0",t.style.boxSizing="border-box",t.style.background="var(--surface, #fff)",t.style.border="1px solid var(--border, #e4e7ec)",t.style.borderRadius="var(--curvature, 6px)",t.style.boxShadow="var(--shadow-1, 0 2px 6px rgba(0, 0, 0, 0.12))"},this.handleDetailClosed=()=>{this.detailField=null}}static get styles(){return d`
11692
12001
  ${Mo}
11693
12002
 
11694
12003
  :host {
@@ -11963,7 +12272,14 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
11963
12272
 
11964
12273
  .menu-button.destructive:hover {
11965
12274
  border-color: #dc2626;
11966
- background: color-mix(in srgb, #dc2626 6%, var(--surface, #fff));
12275
+ /* pre-mixed fallback for browsers without color-mix() */
12276
+ background: #fdf2f2;
12277
+ }
12278
+
12279
+ @supports (color: color-mix(in srgb, red, red)) {
12280
+ .menu-button.destructive:hover {
12281
+ background: color-mix(in srgb, #dc2626 6%, var(--surface, #fff));
12282
+ }
11967
12283
  }
11968
12284
 
11969
12285
  .detail-body {
@@ -12534,7 +12850,8 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
12534
12850
  }
12535
12851
  .menu-button.destructive:hover {
12536
12852
  border-color: #dc2626;
12537
- background: color-mix(in srgb, #dc2626 6%, var(--surface, #fff));
12853
+ /* pre-mixed fallback for browsers without color-mix() */
12854
+ background: #fdf2f2;
12538
12855
  }
12539
12856
  .detail-body {
12540
12857
  display: flex;
@@ -12579,15 +12896,25 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
12579
12896
  align-items: flex-start;
12580
12897
  gap: 0.6em;
12581
12898
  padding: 0.9em 1em 1em;
12582
- background: color-mix(
12583
- in srgb,
12584
- var(--sunken, #f1f3f5) 45%,
12585
- var(--surface, #fff)
12586
- );
12899
+ /* pre-mixed fallback for browsers without color-mix() */
12900
+ background: #f9fafa;
12587
12901
  border: 1px solid var(--border, #e4e7ec);
12588
12902
  border-radius: var(--r);
12589
12903
  line-height: 1.5;
12590
12904
  }
12905
+
12906
+ @supports (color: color-mix(in srgb, red, red)) {
12907
+ .menu-button.destructive:hover {
12908
+ background: color-mix(in srgb, #dc2626 6%, var(--surface, #fff));
12909
+ }
12910
+ .detail-message {
12911
+ background: color-mix(
12912
+ in srgb,
12913
+ var(--sunken, #f1f3f5) 45%,
12914
+ var(--surface, #fff)
12915
+ );
12916
+ }
12917
+ }
12591
12918
  .detail-message temba-expression-highlight {
12592
12919
  align-self: stretch;
12593
12920
  white-space: pre-wrap;
@@ -12808,9 +13135,9 @@ const{I:Su}=lt,$u=t=>t,Tu=()=>document.createComment(""),Eu=(t,e,i)=>{const o=t.
12808
13135
  `)}
12809
13136
  </div>`:null}
12810
13137
  ${(null===(e=s.quick_replies)||void 0===e?void 0:e.length)?G`<div class="detail-pills">
12811
- ${s.quick_replies.map(t=>G`<temba-label type="neutral"
12812
- >${t}</temba-label
12813
- >`)}
13138
+ ${s.quick_replies.map(t=>{var e;return G`<temba-label type="neutral"
13139
+ >${"string"==typeof t?t:null!==(e=t.text)&&void 0!==e?e:t.type}</temba-label
13140
+ >`})}
12814
13141
  </div>`:null}
12815
13142
  ${this.renderContentPills(s)}
12816
13143
  </div>
@@ -13972,7 +14299,7 @@ background: #ccc;
13972
14299
  ${this.renderUploader()}
13973
14300
  </div>
13974
14301
  </div>
13975
- </div>`}}i([ft({type:String,attribute:!1})],hm.prototype,"endpoint",void 0),i([ft({type:Boolean})],hm.prototype,"pendingDrop",void 0),i([ft({type:Boolean})],hm.prototype,"ignoreDrops",void 0),i([ft({type:String})],hm.prototype,"icon",void 0),i([ft({type:String})],hm.prototype,"accept",void 0),i([ft({type:Number})],hm.prototype,"max",void 0),i([ft({type:Array})],hm.prototype,"attachments",void 0),i([ft({type:Boolean,attribute:!1})],hm.prototype,"uploading",void 0);let um="dev";try{um="0.169.0"}catch(t){}const pm=um,mm=[{type:"has_any_word",name:"has any of the words",operands:1},{type:"has_all_words",name:"has all of the words",operands:1},{type:"has_phrase",name:"has the phrase",operands:1},{type:"has_only_phrase",name:"has only the phrase",operands:1},{type:"has_beginning",name:"starts with",operands:1},{type:"has_text",name:"has some text",operands:0,categoryName:"Has Text"},{type:"has_number",name:"has a number",operands:0,categoryName:"Has Number"},{type:"has_number_between",name:"has a number between",operands:2},{type:"has_number_lt",name:"has a number below",operands:1},{type:"has_number_lte",name:"has a number at or below",operands:1},{type:"has_number_eq",name:"has a number equal to",operands:1},{type:"has_number_gte",name:"has a number at or above",operands:1},{type:"has_number_gt",name:"has a number above",operands:1},{type:"has_date",name:"has a date",operands:0,categoryName:"Has Date"},{type:"has_date_lt",name:"has a date before",operands:1},{type:"has_date_eq",name:"has a date equal to",operands:1},{type:"has_date_gt",name:"has a date after",operands:1},{type:"has_time",name:"has a time",operands:0,categoryName:"Has Time"},{type:"has_phone",name:"has a phone number",operands:0,categoryName:"Has Phone"},{type:"has_email",name:"has an email",operands:0,categoryName:"Has Email"},{type:"has_state",name:"has state",operands:0,categoryName:"Has State",filter:"locations"},{type:"has_district",name:"has district",operands:1,categoryName:"Has District",filter:"locations"},{type:"has_ward",name:"has ward",operands:2,categoryName:"Has Ward",filter:"locations"},{type:"has_group",name:"is in the group",operands:1,visibility:"hidden"},{type:"has_category",name:"has the category",operands:0,visibility:"hidden"},{type:"has_error",name:"has an error",operands:0,categoryName:"Has Error",visibility:"hidden"},{type:"has_value",name:"is not empty",operands:0,categoryName:"Not Empty",visibility:"hidden"},{type:"has_pattern",name:"matches regex",operands:1}],gm=t=>mm.filter(e=>"hidden"!==e.visibility&&(!e.filter||!!t&&t.includes(e.filter))),fm=new Set(["has_beginning","has_number","has_number_between","has_number_lt","has_number_lte","has_number_eq","has_number_gte","has_number_gt","has_pattern"]),vm=t=>mm.find(e=>e.type===t),bm=t=>t.map(t=>({value:t.type,name:t.name})),ym={type:"text",required:!1,maxLength:64,placeholder:"(optional)",helpText:"The name to use to reference this result in the flow"},xm={type:"checkbox",label:"Require rules to be localized",helpText:"Each language must specify its own rules for this node"},wm={type:"checkbox",label:"Require categories to be localized",helpText:t=>{var e;const i=null===(e=t.result_name)||void 0===e?void 0:e.trim();if(i){return`Only enable if you plan to use @results.${i.toLowerCase().replace(/\s+/g,"_")}.category_localized`}return"Only enable if you plan to use category_localized in your expressions for this result"},conditions:{visible:t=>!!t.result_name}},_m={label:"Save Result",localizable:!1,items:["result_name"],collapsed:t=>!(t._isNew&&t.result_name),getValueCount:t=>!!t.result_name},km={type:"accordion",multi:!0,sections:[_m,{label:"Localization",localizable:!1,items:["localizeRules","localizeCategories"],collapsed:!0,getValueCount:t=>!(!t.localizeRules&&!t.localizeCategories)}]},Cm={type:"accordion",multi:!0,sections:[_m]},Sm={type:"accordion",multi:!0,sections:[_m,{label:"Localization",localizable:!1,items:["localizeCategories"],collapsed:!0,getValueCount:t=>!!t.localizeCategories}]};function $m(t,e){var i,o;const s=(null===(i=t.router)||void 0===i?void 0:i.categories)||[],n={};s.forEach(t=>{const i=t.uuid,o=e[i];n[i]={originalName:t.name,localizedName:o&&o.name?Array.isArray(o.name)?o.name[0]||"":o.name:""}});const r=(null===(o=t.router)||void 0===o?void 0:o.cases)||[],a={};return r.forEach(t=>{var i,o;if(!(null===(i=t.arguments)||void 0===i?void 0:i.length)||!t.arguments.some(t=>t))return;const s=e[t.uuid],n=(null===(o=vm(t.type))||void 0===o?void 0:o.name)||t.type;a[t.uuid]={operatorName:n,originalArguments:[...t.arguments],localizedArguments:(null==s?void 0:s.arguments)?[...s.arguments]:t.arguments.map(()=>"")}}),{categories:n,rules:a}}function Tm(t,e){const i={};return t.categories&&Object.keys(t.categories).forEach(e=>{var o,s;const n=t.categories[e],r=(null===(o=n.localizedName)||void 0===o?void 0:o.trim())||"",a=(null===(s=n.originalName)||void 0===s?void 0:s.trim())||"";r&&r!==a&&(i[e]={name:[r]})}),t.rules&&Object.keys(t.rules).forEach(e=>{const o=t.rules[e],s=o.localizedArguments||[],n=o.originalArguments||[],r=s.some((t,e)=>(null==t?void 0:t.trim())&&t.trim()!==(n[e]||""));r&&(i[e]={arguments:s.map(t=>(null==t?void 0:t.trim())||"")})}),i}function Em(t,e,i,o=[]){const s=[],n=[],r=[];return t.forEach(t=>{const a=ae(e,t.name),l=a?i.find(t=>t.uuid===a.exit_uuid):null,d=(null==l?void 0:l.uuid)||Xt(),c=(null==a?void 0:a.uuid)||Xt();if(s.push({uuid:c,name:t.name,exit_uuid:d}),n.push({uuid:d,destination_uuid:(null==l?void 0:l.destination_uuid)||null}),t.case){const e=t.case.arguments[0],i=o.find(t=>{var i;return(null===(i=t.arguments)||void 0===i?void 0:i[0])===e});r.push({uuid:(null==i?void 0:i.uuid)||Xt(),type:t.case.type,arguments:t.case.arguments,category_uuid:c})}}),{categories:s,exits:n,cases:r}}function Am(t,e,i,o,s){const n=s.some(t=>re(t,"Other"))?null:ae(i,"Other"),r=n?o.find(t=>t.uuid===n.exit_uuid):null,a=(null==r?void 0:r.uuid)||Xt(),l=(null==n?void 0:n.uuid)||Xt();return t.push({uuid:l,name:"Other",exit_uuid:a}),e.push({uuid:a,destination_uuid:(null==r?void 0:r.destination_uuid)||null}),l}function Dm(t){return e=>{const i={};return t(e,i),{valid:0===Object.keys(i).length,errors:i}}}function Mm(t){const e=t.filter(t=>"contact"===t.type||!t.type&&!t.expression&&t.id),i=t.filter(t=>"group"===t.type),o=t.filter(t=>"expression"===t.type||t.expression);if(e.length>100)return"You can only add up to 100 contacts";if(i.length>100)return"You can only add up to 100 groups";if(o.length>100)return"You can only add up to 100 expressions";const s=o.some(t=>{const e=t.value||t.name||t.id||"";return"string"==typeof e&&e.length>1e3});return s?"Expressions must be no more than 1000 characters":null}function zm(t){const e=t.some(t=>"string"==typeof t&&t.length>1e4);return e?"Template variables must be no more than 10000 characters":null}function Pm(t){return t.toLocalizationFormData?t.toLocalizationFormData:"categories"===t.localizable?$m:Array.isArray(t.localizable)?(e=t.localizable,(t,i)=>{const o={uuid:t.uuid};return e.forEach(t=>{const e=i[t];o[t]=Array.isArray(e)&&e[0]||""}),o}):void 0;var e}function Im(t){return t.fromLocalizationFormData?t.fromLocalizationFormData:"categories"===t.localizable?Tm:Array.isArray(t.localizable)?(e=t.localizable,(t,i)=>{const o={};return e.forEach(e=>{const s=t[e];s&&""!==s.trim()&&s!==i[e]&&(o[e]=[s])}),o}):void 0;var e}const Om="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform);function Lm(t){return 0!==t.button||!(!Om||!t.ctrlKey)}function Rm(t){if(t.dependency){const e=t.dependency.name||t.dependency.key;return`Cannot find a ${t.dependency.type} for ${e}`}return t.description}function Nm(t){const e=20*Math.round(t/20);return Math.max(e,0)}const Fm="font-family:SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;font-size:0.95em",Bm={[Zc.ExpressionPrefix]:`color:${gh.expression};font-weight:600;${Fm}`,[Zc.Identifier]:`color:${gh.expression};${Fm}`,[Zc.FunctionName]:`color:${gh.fn};font-weight:900;${Fm}`,[Zc.StringLiteral]:`color:${gh.string};${Fm}`,[Zc.NumberLiteral]:`color:${gh.number};${Fm}`,[Zc.Keyword]:`color:${gh.keyword};${Fm}`,[Zc.Operator]:`color:${gh.operator};${Fm}`,[Zc.ContextRef]:`color:${gh.expression};${Fm}`,[Zc.Separator]:`color:${gh.operator};${Fm}`,[Zc.Arrow]:`color:${gh.operator};${Fm}`,[Zc.Bracket]:`color:${gh.operator};${Fm}`,[Zc.Paren]:`color:${gh.paren};${Fm}`,[Zc.Whitespace]:Fm},Um=[[/claude|anthropic/i,"anthropic"],[/gpt|openai|o1|o3|o4/i,"openai"],[/gemini|google/i,"gemini"],[/azure|microsoft/i,"azure"],[/deepseek/i,"deepseek"]],qm=(t,e=!1)=>{const i=eh(t||"",e?Uc:Bc),o=[];for(const t of i){const e=!!Bm[t.type],i=o[o.length-1];i&&i.isExpr===e?i.tokens.push(t):o.push({isExpr:e,tokens:[t]})}const s=t=>{const e=Bm[t.type];if(!e){const e=t.text.split("\n");return G`${e.map((t,e)=>G`${e>0?G`<br />`:null}${t}`)}`}const i=t.text.split("\n");return G`${i.map((t,i)=>G`${i>0?G`<br />`:null}${t?G`<span style="${e}">${t}</span>`:null}`)}`};return G`${o.map(t=>{const e=G`${t.tokens.map(s)}`;return t.isExpr?G`<span style="hyphens:none">${e}</span>`:e})}`},Wm=(t,e,i=3)=>G`<div
14302
+ </div>`}}i([ft({type:String,attribute:!1})],hm.prototype,"endpoint",void 0),i([ft({type:Boolean})],hm.prototype,"pendingDrop",void 0),i([ft({type:Boolean})],hm.prototype,"ignoreDrops",void 0),i([ft({type:String})],hm.prototype,"icon",void 0),i([ft({type:String})],hm.prototype,"accept",void 0),i([ft({type:Number})],hm.prototype,"max",void 0),i([ft({type:Array})],hm.prototype,"attachments",void 0),i([ft({type:Boolean,attribute:!1})],hm.prototype,"uploading",void 0);let um="dev";try{um="0.170.1"}catch(t){}const pm=um,mm=[{type:"has_any_word",name:"has any of the words",operands:1},{type:"has_all_words",name:"has all of the words",operands:1},{type:"has_phrase",name:"has the phrase",operands:1},{type:"has_only_phrase",name:"has only the phrase",operands:1},{type:"has_beginning",name:"starts with",operands:1},{type:"has_text",name:"has some text",operands:0,categoryName:"Has Text"},{type:"has_number",name:"has a number",operands:0,categoryName:"Has Number"},{type:"has_number_between",name:"has a number between",operands:2},{type:"has_number_lt",name:"has a number below",operands:1},{type:"has_number_lte",name:"has a number at or below",operands:1},{type:"has_number_eq",name:"has a number equal to",operands:1},{type:"has_number_gte",name:"has a number at or above",operands:1},{type:"has_number_gt",name:"has a number above",operands:1},{type:"has_date",name:"has a date",operands:0,categoryName:"Has Date"},{type:"has_date_lt",name:"has a date before",operands:1},{type:"has_date_eq",name:"has a date equal to",operands:1},{type:"has_date_gt",name:"has a date after",operands:1},{type:"has_time",name:"has a time",operands:0,categoryName:"Has Time"},{type:"has_phone",name:"has a phone number",operands:0,categoryName:"Has Phone"},{type:"has_email",name:"has an email",operands:0,categoryName:"Has Email"},{type:"has_state",name:"has state",operands:0,categoryName:"Has State",filter:"locations"},{type:"has_district",name:"has district",operands:1,categoryName:"Has District",filter:"locations"},{type:"has_ward",name:"has ward",operands:2,categoryName:"Has Ward",filter:"locations"},{type:"has_group",name:"is in the group",operands:1,visibility:"hidden"},{type:"has_category",name:"has the category",operands:0,visibility:"hidden"},{type:"has_error",name:"has an error",operands:0,categoryName:"Has Error",visibility:"hidden"},{type:"has_value",name:"is not empty",operands:0,categoryName:"Not Empty",visibility:"hidden"},{type:"has_pattern",name:"matches regex",operands:1}],gm=t=>mm.filter(e=>"hidden"!==e.visibility&&(!e.filter||!!t&&t.includes(e.filter))),fm=new Set(["has_beginning","has_number","has_number_between","has_number_lt","has_number_lte","has_number_eq","has_number_gte","has_number_gt","has_pattern"]),vm=t=>mm.find(e=>e.type===t),bm=t=>t.map(t=>({value:t.type,name:t.name})),ym={type:"text",required:!1,maxLength:64,placeholder:"(optional)",helpText:"The name to use to reference this result in the flow"},xm={type:"checkbox",label:"Require rules to be localized",helpText:"Each language must specify its own rules for this node"},wm={type:"checkbox",label:"Require categories to be localized",helpText:t=>{var e;const i=null===(e=t.result_name)||void 0===e?void 0:e.trim();if(i){return`Only enable if you plan to use @results.${i.toLowerCase().replace(/\s+/g,"_")}.category_localized`}return"Only enable if you plan to use category_localized in your expressions for this result"},conditions:{visible:t=>!!t.result_name}},_m={label:"Save Result",localizable:!1,items:["result_name"],collapsed:t=>!(t._isNew&&t.result_name),getValueCount:t=>!!t.result_name},km={type:"accordion",multi:!0,sections:[_m,{label:"Localization",localizable:!1,items:["localizeRules","localizeCategories"],collapsed:!0,getValueCount:t=>!(!t.localizeRules&&!t.localizeCategories)}]},Cm={type:"accordion",multi:!0,sections:[_m]},Sm={type:"accordion",multi:!0,sections:[_m,{label:"Localization",localizable:!1,items:["localizeCategories"],collapsed:!0,getValueCount:t=>!!t.localizeCategories}]};function $m(t,e){var i,o;const s=(null===(i=t.router)||void 0===i?void 0:i.categories)||[],n={};s.forEach(t=>{const i=t.uuid,o=e[i];n[i]={originalName:t.name,localizedName:o&&o.name?Array.isArray(o.name)?o.name[0]||"":o.name:""}});const r=(null===(o=t.router)||void 0===o?void 0:o.cases)||[],a={};return r.forEach(t=>{var i,o;if(!(null===(i=t.arguments)||void 0===i?void 0:i.length)||!t.arguments.some(t=>t))return;const s=e[t.uuid],n=(null===(o=vm(t.type))||void 0===o?void 0:o.name)||t.type;a[t.uuid]={operatorName:n,originalArguments:[...t.arguments],localizedArguments:(null==s?void 0:s.arguments)?[...s.arguments]:t.arguments.map(()=>"")}}),{categories:n,rules:a}}function Tm(t,e){const i={};return t.categories&&Object.keys(t.categories).forEach(e=>{var o,s;const n=t.categories[e],r=(null===(o=n.localizedName)||void 0===o?void 0:o.trim())||"",a=(null===(s=n.originalName)||void 0===s?void 0:s.trim())||"";r&&r!==a&&(i[e]={name:[r]})}),t.rules&&Object.keys(t.rules).forEach(e=>{const o=t.rules[e],s=o.localizedArguments||[],n=o.originalArguments||[],r=s.some((t,e)=>(null==t?void 0:t.trim())&&t.trim()!==(n[e]||""));r&&(i[e]={arguments:s.map(t=>(null==t?void 0:t.trim())||"")})}),i}function Em(t,e,i,o=[]){const s=[],n=[],r=[];return t.forEach(t=>{const a=ae(e,t.name),l=a?i.find(t=>t.uuid===a.exit_uuid):null,d=(null==l?void 0:l.uuid)||Xt(),c=(null==a?void 0:a.uuid)||Xt();if(s.push({uuid:c,name:t.name,exit_uuid:d}),n.push({uuid:d,destination_uuid:(null==l?void 0:l.destination_uuid)||null}),t.case){const e=t.case.arguments[0],i=o.find(t=>{var i;return(null===(i=t.arguments)||void 0===i?void 0:i[0])===e});r.push({uuid:(null==i?void 0:i.uuid)||Xt(),type:t.case.type,arguments:t.case.arguments,category_uuid:c})}}),{categories:s,exits:n,cases:r}}function Am(t,e,i,o,s){const n=s.some(t=>re(t,"Other"))?null:ae(i,"Other"),r=n?o.find(t=>t.uuid===n.exit_uuid):null,a=(null==r?void 0:r.uuid)||Xt(),l=(null==n?void 0:n.uuid)||Xt();return t.push({uuid:l,name:"Other",exit_uuid:a}),e.push({uuid:a,destination_uuid:(null==r?void 0:r.destination_uuid)||null}),l}function Dm(t){return e=>{const i={};return t(e,i),{valid:0===Object.keys(i).length,errors:i}}}function Mm(t){const e=t.filter(t=>"contact"===t.type||!t.type&&!t.expression&&t.id),i=t.filter(t=>"group"===t.type),o=t.filter(t=>"expression"===t.type||t.expression);if(e.length>100)return"You can only add up to 100 contacts";if(i.length>100)return"You can only add up to 100 groups";if(o.length>100)return"You can only add up to 100 expressions";const s=o.some(t=>{const e=t.value||t.name||t.id||"";return"string"==typeof e&&e.length>1e3});return s?"Expressions must be no more than 1000 characters":null}function zm(t){const e=t.some(t=>"string"==typeof t&&t.length>1e4);return e?"Template variables must be no more than 10000 characters":null}function Pm(t){return t.toLocalizationFormData?t.toLocalizationFormData:"categories"===t.localizable?$m:Array.isArray(t.localizable)?(e=t.localizable,(t,i)=>{const o={uuid:t.uuid};return e.forEach(t=>{const e=i[t];o[t]=Array.isArray(e)&&e[0]||""}),o}):void 0;var e}function Im(t){return t.fromLocalizationFormData?t.fromLocalizationFormData:"categories"===t.localizable?Tm:Array.isArray(t.localizable)?(e=t.localizable,(t,i)=>{const o={};return e.forEach(e=>{const s=t[e];s&&""!==s.trim()&&s!==i[e]&&(o[e]=[s])}),o}):void 0;var e}const Om="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform);function Lm(t){return 0!==t.button||!(!Om||!t.ctrlKey)}function Rm(t){if(t.dependency){const e=t.dependency.name||t.dependency.key;return`Cannot find a ${t.dependency.type} for ${e}`}return t.description}function Nm(t){const e=20*Math.round(t/20);return Math.max(e,0)}const Fm="font-family:SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;font-size:0.95em",Bm={[Zc.ExpressionPrefix]:`color:${gh.expression};font-weight:600;${Fm}`,[Zc.Identifier]:`color:${gh.expression};${Fm}`,[Zc.FunctionName]:`color:${gh.fn};font-weight:900;${Fm}`,[Zc.StringLiteral]:`color:${gh.string};${Fm}`,[Zc.NumberLiteral]:`color:${gh.number};${Fm}`,[Zc.Keyword]:`color:${gh.keyword};${Fm}`,[Zc.Operator]:`color:${gh.operator};${Fm}`,[Zc.ContextRef]:`color:${gh.expression};${Fm}`,[Zc.Separator]:`color:${gh.operator};${Fm}`,[Zc.Arrow]:`color:${gh.operator};${Fm}`,[Zc.Bracket]:`color:${gh.operator};${Fm}`,[Zc.Paren]:`color:${gh.paren};${Fm}`,[Zc.Whitespace]:Fm},Um=[[/claude|anthropic/i,"anthropic"],[/gpt|openai|o1|o3|o4/i,"openai"],[/gemini|google/i,"gemini"],[/azure|microsoft/i,"azure"],[/deepseek/i,"deepseek"]],qm=(t,e=!1)=>{const i=eh(t||"",e?Uc:Bc),o=[];for(const t of i){const e=!!Bm[t.type],i=o[o.length-1];i&&i.isExpr===e?i.tokens.push(t):o.push({isExpr:e,tokens:[t]})}const s=t=>{const e=Bm[t.type];if(!e){const e=t.text.split("\n");return G`${e.map((t,e)=>G`${e>0?G`<br />`:null}${t}`)}`}const i=t.text.split("\n");return G`${i.map((t,i)=>G`${i>0?G`<br />`:null}${t?G`<span style="${e}">${t}</span>`:null}`)}`};return G`${o.map(t=>{const e=G`${t.tokens.map(s)}`;return t.isExpr?G`<span style="hyphens:none">${e}</span>`:e})}`},Wm=(t,e,i=3)=>G`<div
13976
14303
  style="display: -webkit-box; -webkit-line-clamp: ${i}; -webkit-box-orient: vertical; overflow: hidden; word-wrap: break-word; overflow-wrap: break-word; hyphens: auto;"
13977
14304
  title="${e}"
13978
14305
  >
@@ -20289,6 +20616,7 @@ const _S=(t,e)=>{const i=t._$AN;if(void 0===i)return!1;for(const t of i)t._$AO?.
20289
20616
  }
20290
20617
  .message-input input {
20291
20618
  flex: 1;
20619
+ min-width: 0;
20292
20620
  border: 1px solid #c6c6c857;
20293
20621
  border-radius: 20px;
20294
20622
  padding: 8px 15px;