@paramms/chat-widget 1.6.2 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1417 @@
1
+ var Ue = Object.defineProperty;
2
+ var ve = (n, e, t) => e in n ? Ue(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var a = (n, e, t) => ve(n, typeof e != "symbol" ? e + "" : e, t);
4
+ function de(n, e) {
5
+ var d;
6
+ const t = n.trim().replace(/\/+$/, ""), i = (d = t.match(/^(https|http|wss|ws):\/\//)) == null ? void 0 : d[1], s = i ? i === "https" || i === "wss" : !0, r = (i ? t.slice(i.length + 3) : t).replace(/\/ws$/, ""), o = e ? e.trim().replace(/\/+$/, "") : `${s ? "https" : "http"}://${r}`;
7
+ return { wsUrl: `${s ? "wss" : "ws"}://${r}/ws`, httpBase: o };
8
+ }
9
+ function Se(n) {
10
+ return de(n).httpBase;
11
+ }
12
+ function be(n, e, t, i) {
13
+ const s = `beforeSeq=${t}&limit=${i}`;
14
+ return [
15
+ `${n}/conversations/${e}/messages?${s}`,
16
+ `${n}/conversations/${e}/history?${s}`
17
+ ];
18
+ }
19
+ async function ae(n, e, t, i, s = 20) {
20
+ let r, o = !1;
21
+ for (const h of be(n, e, i, s))
22
+ try {
23
+ const d = await fetch(h, { headers: { authorization: `Bearer ${t}` } });
24
+ if (o = !0, !d.ok) continue;
25
+ const U = await d.json();
26
+ return { messages: U.messages ?? [], hasMore: U.hasMore ?? !1 };
27
+ } catch (d) {
28
+ r = d;
29
+ }
30
+ return o ? console.error(`[chat-widget] history request to ${n} was rejected for conversation ${e}.`) : console.error(
31
+ `[chat-widget] could not load history from ${n} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,
32
+ r
33
+ ), null;
34
+ }
35
+ async function yt(n, e, t, i, s, r) {
36
+ const o = r ? r.replace(/\/+$/, "") : Se(n), h = await ae(o, t, e, Number.MAX_SAFE_INTEGER);
37
+ if (!h || (h.messages.length ? (i.apply({ type: "sync", conversationId: t, messages: h.messages }), i.apply({ type: "history", conversationId: t, messages: [], hasMore: h.hasMore }), s.render(i)) : i.apply({ type: "history", conversationId: t, messages: [], hasMore: !1 }), !h.hasMore)) return;
38
+ let d = !1;
39
+ const U = async () => {
40
+ if (d || !i.hasMoreHistory) return;
41
+ d = !0;
42
+ const I = i.messages()[0];
43
+ if (!I) {
44
+ d = !1;
45
+ return;
46
+ }
47
+ const v = await ae(o, t, e, I.seq);
48
+ v && (i.apply({ type: "history", conversationId: t, messages: v.messages, hasMore: v.hasMore }), s.render(i)), d = !1;
49
+ }, b = s.getScrollEl();
50
+ if (!b) return;
51
+ let x = !1;
52
+ setTimeout(() => {
53
+ x = !0;
54
+ }, 300);
55
+ const g = () => {
56
+ x && b.scrollTop < 80 && i.hasMoreHistory && !d && U();
57
+ };
58
+ b.addEventListener("scroll", g, { passive: !0 }), s.setScrollCleanup(() => b.removeEventListener("scroll", g));
59
+ }
60
+ const Ee = {
61
+ accent: "#6c5ce7",
62
+ accent2: "#4c6fff",
63
+ bg: "#f4f3fb",
64
+ card: "#fff",
65
+ tint: "#eeecfb",
66
+ line: "#e6e2f5",
67
+ ink: "#221d3a",
68
+ mut: "#8f8aa8",
69
+ onaccent: "#fff",
70
+ rowhover: "#e7e3f8",
71
+ shadow: "0 12px 32px rgba(108,92,231,.14)"
72
+ }, Be = {
73
+ accent: "#a99cf2",
74
+ accent2: "#6f8cff",
75
+ bg: "#221d3a",
76
+ card: "#2b2550",
77
+ tint: "#2f2853",
78
+ line: "#3a3363",
79
+ ink: "#eceafc",
80
+ mut: "#9b93c9",
81
+ onaccent: "#221d3a",
82
+ rowhover: "#39325e",
83
+ shadow: "0 12px 32px rgba(0,0,0,.4)"
84
+ }, Ie = "'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";
85
+ function fe(n, e) {
86
+ return Object.entries(e).map(([t, i]) => `--${n}-${t}:${i};`).join(" ");
87
+ }
88
+ function ke(n) {
89
+ return `${fe(n, Ee)} --${n}-fb:${Ie}; --${n}-fh:'Baloo 2',var(--${n}-fb);`;
90
+ }
91
+ function ce(n) {
92
+ return fe(n, Be);
93
+ }
94
+ const Te = `
95
+ .ocl { ${ke("ocl")}
96
+ display:flex; flex-direction:column; height:100%; background:var(--ocl-bg);
97
+ font-family:var(--ocl-fb); color:var(--ocl-ink); overflow:hidden; }
98
+ @media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] { ${ce("ocl")} } }
99
+ .ocl[data-theme="dark"] { ${ce("ocl")} }
100
+ .ocl-head { display:flex; align-items:center; padding:16px 16px 10px; background:var(--ocl-bg); }
101
+ .ocl-title { flex:1; display:flex; align-items:center; font-family:var(--ocl-fh); font-weight:700; font-size:18px; color:var(--ocl-ink); }
102
+ .ocl-retry { margin-top:14px; border:none; background:var(--ocl-accent); color:var(--ocl-onaccent); border-radius:20px; padding:8px 20px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; }
103
+ .ocl-search-wrap { padding:4px 12px 8px; background:var(--ocl-bg); }
104
+ .ocl-search { width:100%; box-sizing:border-box; border:none; background:var(--ocl-tint); border-radius:20px; padding:9px 14px; font:inherit; font-size:14px; outline:none; }
105
+ .ocl-body { flex:1; overflow-y:auto; }
106
+ .ocl-section { padding:10px 18px 4px; font-family:var(--ocl-fh); font-size:11px; font-weight:600; color:var(--ocl-mut); text-transform:uppercase; letter-spacing:.5px; background:transparent; }
107
+ .ocl-empty { padding:40px 20px; text-align:center; color:var(--ocl-mut); font-size:14px; }
108
+ .ocl-row { display:flex; align-items:center; gap:12px; padding:10px 12px; margin:6px 12px; background:var(--ocl-tint); border:none; width:calc(100% - 24px); box-sizing:border-box; border-radius:16px; text-align:left; cursor:pointer; transition:background .12s; }
109
+ .ocl-row:hover { background:var(--ocl-rowhover); }
110
+ .ocl-row.unread { background:var(--ocl-rowhover); }
111
+ .ocl-av { width:40px; height:40px; border-radius:50%; background:var(--ocl-accent); color:var(--ocl-onaccent); font-family:var(--ocl-fh); font-size:15px; font-weight:600; display:flex; align-items:center; justify-content:center; flex:none; }
112
+ .ocl-info { flex:1; min-width:0; }
113
+ .ocl-name { font-family:var(--ocl-fh); font-size:14px; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-bottom:2px; }
114
+ .ocl-row.unread .ocl-name { font-weight:700; }
115
+ .ocl-preview { font-size:11.5px; color:var(--ocl-mut); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
116
+ .ocl-row.unread .ocl-preview { color:var(--ocl-ink); }
117
+ .ocl-right { display:flex; flex-direction:column; align-items:flex-end; gap:4px; flex:none; }
118
+ .ocl-time { font-size:10px; color:var(--ocl-mut); }
119
+ .ocl-row.unread .ocl-time { color:var(--ocl-accent); font-weight:600; }
120
+ .ocl-badge { background:var(--ocl-accent); color:var(--ocl-onaccent); border-radius:999px; font-size:11px; font-weight:700; min-width:20px; height:20px; padding:0 5px; display:flex; align-items:center; justify-content:center; }
121
+ .ocl-status { font-size:10px; font-weight:600; padding:2px 8px; border-radius:20px; white-space:nowrap; }
122
+ .ocl-status.open { background:#dff3e6; color:#2f8a52; }
123
+ .ocl-status.waiting { background:var(--ocl-tint); color:var(--ocl-accent); border:1px solid var(--ocl-accent); }
124
+ .ocl-status.done { background:#eee; color:#777; }
125
+ .ocl[data-theme="dark"] .ocl-status.done { background:#39325e; color:#b3abd6; }
126
+ @media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] .ocl-status.done { background:#39325e; color:#b3abd6; } }
127
+ .ocl-spinner { padding:24px; text-align:center; color:var(--ocl-mut); font-size:13px; }
128
+ .ocl-compose { border:none; background:var(--ocl-accent); color:var(--ocl-onaccent); width:32px; height:32px; border-radius:50%; font-size:18px; line-height:1; cursor:pointer; box-shadow:var(--ocl-shadow); }
129
+ .ocl-compose:hover { filter:brightness(1.08); }
130
+ /* When the HOST overlays a ✕ (ChatApp's onClose / embed's inbox stack), it is
131
+ absolutely positioned at top-right and used to land straight on top of the ✎
132
+ compose button. Reserve the space instead of stacking them. */
133
+ .ocl-has-close .ocl-head { padding-right:52px; }
134
+ .ocl-start { margin-top:12px; border:none; background:var(--ocl-accent); color:var(--ocl-onaccent); border-radius:20px; padding:8px 18px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; }
135
+ /* Compact sizing keyed on the LIST'S OWN width (ResizeObserver toggles
136
+ * .ocl-compact below 400px) — covers phones and narrow desktop embeds alike.
137
+ * Search must be ≥16px in compact or iOS zooms the page on focus. */
138
+ .ocl-compact .ocl-row { padding:13px 14px; }
139
+ .ocl-compact .ocl-search { font-size:16px; }
140
+ .ocl-compact .ocl-compose { width:36px; height:36px; }
141
+ .ocl-row:focus-visible, .ocl button:focus-visible, .ocl input:focus-visible { outline:2px solid var(--ocl-accent); outline-offset:2px; border-radius:12px; }
142
+ `, _ = "oc_uid";
143
+ function Ae(n) {
144
+ try {
145
+ const e = document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));
146
+ return e ? decodeURIComponent(e[1]) : null;
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+ function $e(n, e) {
152
+ try {
153
+ const i = location.protocol === "https:" ? "; Secure" : "";
154
+ document.cookie = `${n}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`;
155
+ } catch {
156
+ }
157
+ }
158
+ function ze() {
159
+ return `g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
160
+ }
161
+ function Ce() {
162
+ let n = null;
163
+ try {
164
+ n = localStorage.getItem(_);
165
+ } catch {
166
+ }
167
+ n || (n = Ae(_));
168
+ const e = n ?? ze();
169
+ try {
170
+ localStorage.setItem(_, e);
171
+ } catch {
172
+ }
173
+ return $e(_, e), e;
174
+ }
175
+ function Le(n) {
176
+ const e = n.length;
177
+ let t = 0, i = 0;
178
+ for (; i < e; ) {
179
+ let s = n.charCodeAt(i++);
180
+ if (s & 4294967168)
181
+ if (!(s & 4294965248))
182
+ t += 2;
183
+ else {
184
+ if (s >= 55296 && s <= 56319 && i < e) {
185
+ const r = n.charCodeAt(i);
186
+ (r & 64512) === 56320 && (++i, s = ((s & 1023) << 10) + (r & 1023) + 65536);
187
+ }
188
+ s & 4294901760 ? t += 4 : t += 3;
189
+ }
190
+ else {
191
+ t++;
192
+ continue;
193
+ }
194
+ }
195
+ return t;
196
+ }
197
+ function Me(n, e, t) {
198
+ const i = n.length;
199
+ let s = t, r = 0;
200
+ for (; r < i; ) {
201
+ let o = n.charCodeAt(r++);
202
+ if (o & 4294967168)
203
+ if (!(o & 4294965248))
204
+ e[s++] = o >> 6 & 31 | 192;
205
+ else {
206
+ if (o >= 55296 && o <= 56319 && r < i) {
207
+ const h = n.charCodeAt(r);
208
+ (h & 64512) === 56320 && (++r, o = ((o & 1023) << 10) + (h & 1023) + 65536);
209
+ }
210
+ o & 4294901760 ? (e[s++] = o >> 18 & 7 | 240, e[s++] = o >> 12 & 63 | 128, e[s++] = o >> 6 & 63 | 128) : (e[s++] = o >> 12 & 15 | 224, e[s++] = o >> 6 & 63 | 128);
211
+ }
212
+ else {
213
+ e[s++] = o;
214
+ continue;
215
+ }
216
+ e[s++] = o & 63 | 128;
217
+ }
218
+ }
219
+ const De = new TextEncoder(), _e = 50;
220
+ function Re(n, e, t) {
221
+ De.encodeInto(n, e.subarray(t));
222
+ }
223
+ function Fe(n, e, t) {
224
+ n.length > _e ? Re(n, e, t) : Me(n, e, t);
225
+ }
226
+ const Pe = 4096;
227
+ function ue(n, e, t) {
228
+ let i = e;
229
+ const s = i + t, r = [];
230
+ let o = "";
231
+ for (; i < s; ) {
232
+ const h = n[i++];
233
+ if (!(h & 128))
234
+ r.push(h);
235
+ else if ((h & 224) === 192) {
236
+ const d = n[i++] & 63;
237
+ r.push((h & 31) << 6 | d);
238
+ } else if ((h & 240) === 224) {
239
+ const d = n[i++] & 63, U = n[i++] & 63;
240
+ r.push((h & 31) << 12 | d << 6 | U);
241
+ } else if ((h & 248) === 240) {
242
+ const d = n[i++] & 63, U = n[i++] & 63, b = n[i++] & 63;
243
+ let x = (h & 7) << 18 | d << 12 | U << 6 | b;
244
+ x > 65535 && (x -= 65536, r.push(x >>> 10 & 1023 | 55296), x = 56320 | x & 1023), r.push(x);
245
+ } else
246
+ r.push(h);
247
+ r.length >= Pe && (o += String.fromCharCode(...r), r.length = 0);
248
+ }
249
+ return r.length > 0 && (o += String.fromCharCode(...r)), o;
250
+ }
251
+ const Ne = new TextDecoder(), He = 200;
252
+ function Ke(n, e, t) {
253
+ const i = n.subarray(e, e + t);
254
+ return Ne.decode(i);
255
+ }
256
+ function We(n, e, t) {
257
+ return t > He ? Ke(n, e, t) : ue(n, e, t);
258
+ }
259
+ class R {
260
+ constructor(e, t) {
261
+ a(this, "type");
262
+ a(this, "data");
263
+ this.type = e, this.data = t;
264
+ }
265
+ }
266
+ class y extends Error {
267
+ constructor(e) {
268
+ super(e);
269
+ const t = Object.create(y.prototype);
270
+ Object.setPrototypeOf(this, t), Object.defineProperty(this, "name", {
271
+ configurable: !0,
272
+ enumerable: !1,
273
+ value: y.name
274
+ });
275
+ }
276
+ }
277
+ const z = 4294967295;
278
+ function Oe(n, e, t) {
279
+ const i = t / 4294967296, s = t;
280
+ n.setUint32(e, i), n.setUint32(e + 4, s);
281
+ }
282
+ function xe(n, e, t) {
283
+ const i = Math.floor(t / 4294967296), s = t;
284
+ n.setUint32(e, i), n.setUint32(e + 4, s);
285
+ }
286
+ function pe(n, e) {
287
+ const t = n.getInt32(e), i = n.getUint32(e + 4);
288
+ return t * 4294967296 + i;
289
+ }
290
+ function Ve(n, e) {
291
+ const t = n.getUint32(e), i = n.getUint32(e + 4);
292
+ return t * 4294967296 + i;
293
+ }
294
+ const Ye = -1, qe = 4294967296 - 1, Xe = 17179869184 - 1;
295
+ function Ge({ sec: n, nsec: e }) {
296
+ if (n >= 0 && e >= 0 && n <= Xe)
297
+ if (e === 0 && n <= qe) {
298
+ const t = new Uint8Array(4);
299
+ return new DataView(t.buffer).setUint32(0, n), t;
300
+ } else {
301
+ const t = n / 4294967296, i = n & 4294967295, s = new Uint8Array(8), r = new DataView(s.buffer);
302
+ return r.setUint32(0, e << 2 | t & 3), r.setUint32(4, i), s;
303
+ }
304
+ else {
305
+ const t = new Uint8Array(12), i = new DataView(t.buffer);
306
+ return i.setUint32(0, e), xe(i, 4, n), t;
307
+ }
308
+ }
309
+ function Je(n) {
310
+ const e = n.getTime(), t = Math.floor(e / 1e3), i = (e - t * 1e3) * 1e6, s = Math.floor(i / 1e9);
311
+ return {
312
+ sec: t + s,
313
+ nsec: i - s * 1e9
314
+ };
315
+ }
316
+ function Ze(n) {
317
+ if (n instanceof Date) {
318
+ const e = Je(n);
319
+ return Ge(e);
320
+ } else
321
+ return null;
322
+ }
323
+ function Qe(n) {
324
+ const e = new DataView(n.buffer, n.byteOffset, n.byteLength);
325
+ switch (n.byteLength) {
326
+ case 4:
327
+ return { sec: e.getUint32(0), nsec: 0 };
328
+ case 8: {
329
+ const t = e.getUint32(0), i = e.getUint32(4), s = (t & 3) * 4294967296 + i, r = t >>> 2;
330
+ return { sec: s, nsec: r };
331
+ }
332
+ case 12: {
333
+ const t = pe(e, 4), i = e.getUint32(0);
334
+ return { sec: t, nsec: i };
335
+ }
336
+ default:
337
+ throw new y(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`);
338
+ }
339
+ }
340
+ function je(n) {
341
+ const e = Qe(n);
342
+ return new Date(e.sec * 1e3 + e.nsec / 1e6);
343
+ }
344
+ const et = {
345
+ type: Ye,
346
+ encode: Ze,
347
+ decode: je
348
+ }, P = class P {
349
+ constructor() {
350
+ // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
351
+ // this will make type errors a lot more clear
352
+ // eslint-disable-next-line @typescript-eslint/naming-convention
353
+ a(this, "__brand");
354
+ // built-in extensions
355
+ a(this, "builtInEncoders", []);
356
+ a(this, "builtInDecoders", []);
357
+ // custom extensions
358
+ a(this, "encoders", []);
359
+ a(this, "decoders", []);
360
+ this.register(et);
361
+ }
362
+ register({ type: e, encode: t, decode: i }) {
363
+ if (e >= 0)
364
+ this.encoders[e] = t, this.decoders[e] = i;
365
+ else {
366
+ const s = -1 - e;
367
+ this.builtInEncoders[s] = t, this.builtInDecoders[s] = i;
368
+ }
369
+ }
370
+ tryToEncode(e, t) {
371
+ for (let i = 0; i < this.builtInEncoders.length; i++) {
372
+ const s = this.builtInEncoders[i];
373
+ if (s != null) {
374
+ const r = s(e, t);
375
+ if (r != null) {
376
+ const o = -1 - i;
377
+ return new R(o, r);
378
+ }
379
+ }
380
+ }
381
+ for (let i = 0; i < this.encoders.length; i++) {
382
+ const s = this.encoders[i];
383
+ if (s != null) {
384
+ const r = s(e, t);
385
+ if (r != null) {
386
+ const o = i;
387
+ return new R(o, r);
388
+ }
389
+ }
390
+ }
391
+ return e instanceof R ? e : null;
392
+ }
393
+ decode(e, t, i) {
394
+ const s = t < 0 ? this.builtInDecoders[-1 - t] : this.decoders[t];
395
+ return s ? s(e, t, i) : new R(t, e);
396
+ }
397
+ };
398
+ a(P, "defaultCodec", new P());
399
+ let F = P;
400
+ function tt(n) {
401
+ return n instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && n instanceof SharedArrayBuffer;
402
+ }
403
+ function W(n) {
404
+ return n instanceof Uint8Array ? n : ArrayBuffer.isView(n) ? new Uint8Array(n.buffer, n.byteOffset, n.byteLength) : tt(n) ? new Uint8Array(n) : Uint8Array.from(n);
405
+ }
406
+ const it = 100, st = 2048;
407
+ class V {
408
+ constructor(e) {
409
+ a(this, "extensionCodec");
410
+ a(this, "context");
411
+ a(this, "useBigInt64");
412
+ a(this, "maxDepth");
413
+ a(this, "initialBufferSize");
414
+ a(this, "sortKeys");
415
+ a(this, "forceFloat32");
416
+ a(this, "ignoreUndefined");
417
+ a(this, "forceIntegerToFloat");
418
+ a(this, "pos");
419
+ a(this, "view");
420
+ a(this, "bytes");
421
+ a(this, "entered", !1);
422
+ this.extensionCodec = (e == null ? void 0 : e.extensionCodec) ?? F.defaultCodec, this.context = e == null ? void 0 : e.context, this.useBigInt64 = (e == null ? void 0 : e.useBigInt64) ?? !1, this.maxDepth = (e == null ? void 0 : e.maxDepth) ?? it, this.initialBufferSize = (e == null ? void 0 : e.initialBufferSize) ?? st, this.sortKeys = (e == null ? void 0 : e.sortKeys) ?? !1, this.forceFloat32 = (e == null ? void 0 : e.forceFloat32) ?? !1, this.ignoreUndefined = (e == null ? void 0 : e.ignoreUndefined) ?? !1, this.forceIntegerToFloat = (e == null ? void 0 : e.forceIntegerToFloat) ?? !1, this.pos = 0, this.view = new DataView(new ArrayBuffer(this.initialBufferSize)), this.bytes = new Uint8Array(this.view.buffer);
423
+ }
424
+ clone() {
425
+ return new V({
426
+ extensionCodec: this.extensionCodec,
427
+ context: this.context,
428
+ useBigInt64: this.useBigInt64,
429
+ maxDepth: this.maxDepth,
430
+ initialBufferSize: this.initialBufferSize,
431
+ sortKeys: this.sortKeys,
432
+ forceFloat32: this.forceFloat32,
433
+ ignoreUndefined: this.ignoreUndefined,
434
+ forceIntegerToFloat: this.forceIntegerToFloat
435
+ });
436
+ }
437
+ reinitializeState() {
438
+ this.pos = 0;
439
+ }
440
+ /**
441
+ * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
442
+ *
443
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
444
+ */
445
+ encodeSharedRef(e) {
446
+ if (this.entered)
447
+ return this.clone().encodeSharedRef(e);
448
+ try {
449
+ return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.subarray(0, this.pos);
450
+ } finally {
451
+ this.entered = !1;
452
+ }
453
+ }
454
+ /**
455
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
456
+ */
457
+ encode(e) {
458
+ if (this.entered)
459
+ return this.clone().encode(e);
460
+ try {
461
+ return this.entered = !0, this.reinitializeState(), this.doEncode(e, 1), this.bytes.slice(0, this.pos);
462
+ } finally {
463
+ this.entered = !1;
464
+ }
465
+ }
466
+ doEncode(e, t) {
467
+ if (t > this.maxDepth)
468
+ throw new Error(`Too deep objects in depth ${t}`);
469
+ e == null ? this.encodeNil() : typeof e == "boolean" ? this.encodeBoolean(e) : typeof e == "number" ? this.forceIntegerToFloat ? this.encodeNumberAsFloat(e) : this.encodeNumber(e) : typeof e == "string" ? this.encodeString(e) : this.useBigInt64 && typeof e == "bigint" ? this.encodeBigInt64(e) : this.encodeObject(e, t);
470
+ }
471
+ ensureBufferSizeToWrite(e) {
472
+ const t = this.pos + e;
473
+ this.view.byteLength < t && this.resizeBuffer(t * 2);
474
+ }
475
+ resizeBuffer(e) {
476
+ const t = new ArrayBuffer(e), i = new Uint8Array(t), s = new DataView(t);
477
+ i.set(this.bytes), this.view = s, this.bytes = i;
478
+ }
479
+ encodeNil() {
480
+ this.writeU8(192);
481
+ }
482
+ encodeBoolean(e) {
483
+ e === !1 ? this.writeU8(194) : this.writeU8(195);
484
+ }
485
+ encodeNumber(e) {
486
+ !this.forceIntegerToFloat && Number.isSafeInteger(e) ? e >= 0 ? e < 128 ? this.writeU8(e) : e < 256 ? (this.writeU8(204), this.writeU8(e)) : e < 65536 ? (this.writeU8(205), this.writeU16(e)) : e < 4294967296 ? (this.writeU8(206), this.writeU32(e)) : this.useBigInt64 ? this.encodeNumberAsFloat(e) : (this.writeU8(207), this.writeU64(e)) : e >= -32 ? this.writeU8(224 | e + 32) : e >= -128 ? (this.writeU8(208), this.writeI8(e)) : e >= -32768 ? (this.writeU8(209), this.writeI16(e)) : e >= -2147483648 ? (this.writeU8(210), this.writeI32(e)) : this.useBigInt64 ? this.encodeNumberAsFloat(e) : (this.writeU8(211), this.writeI64(e)) : this.encodeNumberAsFloat(e);
487
+ }
488
+ encodeNumberAsFloat(e) {
489
+ this.forceFloat32 ? (this.writeU8(202), this.writeF32(e)) : (this.writeU8(203), this.writeF64(e));
490
+ }
491
+ encodeBigInt64(e) {
492
+ e >= BigInt(0) ? (this.writeU8(207), this.writeBigUint64(e)) : (this.writeU8(211), this.writeBigInt64(e));
493
+ }
494
+ writeStringHeader(e) {
495
+ if (e < 32)
496
+ this.writeU8(160 + e);
497
+ else if (e < 256)
498
+ this.writeU8(217), this.writeU8(e);
499
+ else if (e < 65536)
500
+ this.writeU8(218), this.writeU16(e);
501
+ else if (e < 4294967296)
502
+ this.writeU8(219), this.writeU32(e);
503
+ else
504
+ throw new Error(`Too long string: ${e} bytes in UTF-8`);
505
+ }
506
+ encodeString(e) {
507
+ const i = Le(e);
508
+ this.ensureBufferSizeToWrite(5 + i), this.writeStringHeader(i), Fe(e, this.bytes, this.pos), this.pos += i;
509
+ }
510
+ encodeObject(e, t) {
511
+ const i = this.extensionCodec.tryToEncode(e, this.context);
512
+ if (i != null)
513
+ this.encodeExtension(i);
514
+ else if (Array.isArray(e))
515
+ this.encodeArray(e, t);
516
+ else if (ArrayBuffer.isView(e))
517
+ this.encodeBinary(e);
518
+ else if (typeof e == "object")
519
+ this.encodeMap(e, t);
520
+ else
521
+ throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);
522
+ }
523
+ encodeBinary(e) {
524
+ const t = e.byteLength;
525
+ if (t < 256)
526
+ this.writeU8(196), this.writeU8(t);
527
+ else if (t < 65536)
528
+ this.writeU8(197), this.writeU16(t);
529
+ else if (t < 4294967296)
530
+ this.writeU8(198), this.writeU32(t);
531
+ else
532
+ throw new Error(`Too large binary: ${t}`);
533
+ const i = W(e);
534
+ this.writeU8a(i);
535
+ }
536
+ encodeArray(e, t) {
537
+ const i = e.length;
538
+ if (i < 16)
539
+ this.writeU8(144 + i);
540
+ else if (i < 65536)
541
+ this.writeU8(220), this.writeU16(i);
542
+ else if (i < 4294967296)
543
+ this.writeU8(221), this.writeU32(i);
544
+ else
545
+ throw new Error(`Too large array: ${i}`);
546
+ for (const s of e)
547
+ this.doEncode(s, t + 1);
548
+ }
549
+ countWithoutUndefined(e, t) {
550
+ let i = 0;
551
+ for (const s of t)
552
+ e[s] !== void 0 && i++;
553
+ return i;
554
+ }
555
+ encodeMap(e, t) {
556
+ const i = Object.keys(e);
557
+ this.sortKeys && i.sort();
558
+ const s = this.ignoreUndefined ? this.countWithoutUndefined(e, i) : i.length;
559
+ if (s < 16)
560
+ this.writeU8(128 + s);
561
+ else if (s < 65536)
562
+ this.writeU8(222), this.writeU16(s);
563
+ else if (s < 4294967296)
564
+ this.writeU8(223), this.writeU32(s);
565
+ else
566
+ throw new Error(`Too large map object: ${s}`);
567
+ for (const r of i) {
568
+ const o = e[r];
569
+ this.ignoreUndefined && o === void 0 || (this.encodeString(r), this.doEncode(o, t + 1));
570
+ }
571
+ }
572
+ encodeExtension(e) {
573
+ if (typeof e.data == "function") {
574
+ const i = e.data(this.pos + 6), s = i.length;
575
+ if (s >= 4294967296)
576
+ throw new Error(`Too large extension object: ${s}`);
577
+ this.writeU8(201), this.writeU32(s), this.writeI8(e.type), this.writeU8a(i);
578
+ return;
579
+ }
580
+ const t = e.data.length;
581
+ if (t === 1)
582
+ this.writeU8(212);
583
+ else if (t === 2)
584
+ this.writeU8(213);
585
+ else if (t === 4)
586
+ this.writeU8(214);
587
+ else if (t === 8)
588
+ this.writeU8(215);
589
+ else if (t === 16)
590
+ this.writeU8(216);
591
+ else if (t < 256)
592
+ this.writeU8(199), this.writeU8(t);
593
+ else if (t < 65536)
594
+ this.writeU8(200), this.writeU16(t);
595
+ else if (t < 4294967296)
596
+ this.writeU8(201), this.writeU32(t);
597
+ else
598
+ throw new Error(`Too large extension object: ${t}`);
599
+ this.writeI8(e.type), this.writeU8a(e.data);
600
+ }
601
+ writeU8(e) {
602
+ this.ensureBufferSizeToWrite(1), this.view.setUint8(this.pos, e), this.pos++;
603
+ }
604
+ writeU8a(e) {
605
+ const t = e.length;
606
+ this.ensureBufferSizeToWrite(t), this.bytes.set(e, this.pos), this.pos += t;
607
+ }
608
+ writeI8(e) {
609
+ this.ensureBufferSizeToWrite(1), this.view.setInt8(this.pos, e), this.pos++;
610
+ }
611
+ writeU16(e) {
612
+ this.ensureBufferSizeToWrite(2), this.view.setUint16(this.pos, e), this.pos += 2;
613
+ }
614
+ writeI16(e) {
615
+ this.ensureBufferSizeToWrite(2), this.view.setInt16(this.pos, e), this.pos += 2;
616
+ }
617
+ writeU32(e) {
618
+ this.ensureBufferSizeToWrite(4), this.view.setUint32(this.pos, e), this.pos += 4;
619
+ }
620
+ writeI32(e) {
621
+ this.ensureBufferSizeToWrite(4), this.view.setInt32(this.pos, e), this.pos += 4;
622
+ }
623
+ writeF32(e) {
624
+ this.ensureBufferSizeToWrite(4), this.view.setFloat32(this.pos, e), this.pos += 4;
625
+ }
626
+ writeF64(e) {
627
+ this.ensureBufferSizeToWrite(8), this.view.setFloat64(this.pos, e), this.pos += 8;
628
+ }
629
+ writeU64(e) {
630
+ this.ensureBufferSizeToWrite(8), Oe(this.view, this.pos, e), this.pos += 8;
631
+ }
632
+ writeI64(e) {
633
+ this.ensureBufferSizeToWrite(8), xe(this.view, this.pos, e), this.pos += 8;
634
+ }
635
+ writeBigUint64(e) {
636
+ this.ensureBufferSizeToWrite(8), this.view.setBigUint64(this.pos, e), this.pos += 8;
637
+ }
638
+ writeBigInt64(e) {
639
+ this.ensureBufferSizeToWrite(8), this.view.setBigInt64(this.pos, e), this.pos += 8;
640
+ }
641
+ }
642
+ function nt(n, e) {
643
+ return new V(e).encodeSharedRef(n);
644
+ }
645
+ function K(n) {
646
+ return `${n < 0 ? "-" : ""}0x${Math.abs(n).toString(16).padStart(2, "0")}`;
647
+ }
648
+ const rt = 16, ot = 16;
649
+ class at {
650
+ constructor(e = rt, t = ot) {
651
+ a(this, "hit", 0);
652
+ a(this, "miss", 0);
653
+ a(this, "caches");
654
+ a(this, "maxKeyLength");
655
+ a(this, "maxLengthPerKey");
656
+ this.maxKeyLength = e, this.maxLengthPerKey = t, this.caches = [];
657
+ for (let i = 0; i < this.maxKeyLength; i++)
658
+ this.caches.push([]);
659
+ }
660
+ canBeCached(e) {
661
+ return e > 0 && e <= this.maxKeyLength;
662
+ }
663
+ find(e, t, i) {
664
+ const s = this.caches[i - 1];
665
+ e: for (const r of s) {
666
+ const o = r.bytes;
667
+ for (let h = 0; h < i; h++)
668
+ if (o[h] !== e[t + h])
669
+ continue e;
670
+ return r.str;
671
+ }
672
+ return null;
673
+ }
674
+ store(e, t) {
675
+ const i = this.caches[e.length - 1], s = { bytes: e, str: t };
676
+ i.length >= this.maxLengthPerKey ? i[Math.random() * i.length | 0] = s : i.push(s);
677
+ }
678
+ decode(e, t, i) {
679
+ const s = this.find(e, t, i);
680
+ if (s != null)
681
+ return this.hit++, s;
682
+ this.miss++;
683
+ const r = ue(e, t, i), o = Uint8Array.prototype.slice.call(e, t, t + i);
684
+ return this.store(o, r), r;
685
+ }
686
+ }
687
+ const O = "array", L = "map_key", ge = "map_value", ct = (n) => {
688
+ if (typeof n == "string" || typeof n == "number")
689
+ return n;
690
+ throw new y("The type of key must be string or number but " + typeof n);
691
+ };
692
+ class ht {
693
+ constructor() {
694
+ a(this, "stack", []);
695
+ a(this, "stackHeadPosition", -1);
696
+ }
697
+ get length() {
698
+ return this.stackHeadPosition + 1;
699
+ }
700
+ top() {
701
+ return this.stack[this.stackHeadPosition];
702
+ }
703
+ pushArrayState(e) {
704
+ const t = this.getUninitializedStateFromPool();
705
+ t.type = O, t.position = 0, t.size = e, t.array = new Array(e);
706
+ }
707
+ pushMapState(e) {
708
+ const t = this.getUninitializedStateFromPool();
709
+ t.type = L, t.readCount = 0, t.size = e, t.map = {};
710
+ }
711
+ getUninitializedStateFromPool() {
712
+ if (this.stackHeadPosition++, this.stackHeadPosition === this.stack.length) {
713
+ const e = {
714
+ type: void 0,
715
+ size: 0,
716
+ array: void 0,
717
+ position: 0,
718
+ readCount: 0,
719
+ map: void 0,
720
+ key: null
721
+ };
722
+ this.stack.push(e);
723
+ }
724
+ return this.stack[this.stackHeadPosition];
725
+ }
726
+ release(e) {
727
+ if (this.stack[this.stackHeadPosition] !== e)
728
+ throw new Error("Invalid stack state. Released state is not on top of the stack.");
729
+ if (e.type === O) {
730
+ const i = e;
731
+ i.size = 0, i.array = void 0, i.position = 0, i.type = void 0;
732
+ }
733
+ if (e.type === L || e.type === ge) {
734
+ const i = e;
735
+ i.size = 0, i.map = void 0, i.readCount = 0, i.type = void 0;
736
+ }
737
+ this.stackHeadPosition--;
738
+ }
739
+ reset() {
740
+ this.stack.length = 0, this.stackHeadPosition = -1;
741
+ }
742
+ }
743
+ const C = -1, Y = new DataView(new ArrayBuffer(0)), lt = new Uint8Array(Y.buffer);
744
+ try {
745
+ Y.getInt8(0);
746
+ } catch (n) {
747
+ if (!(n instanceof RangeError))
748
+ throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
749
+ }
750
+ const he = new RangeError("Insufficient data"), dt = new at();
751
+ class q {
752
+ constructor(e) {
753
+ a(this, "extensionCodec");
754
+ a(this, "context");
755
+ a(this, "useBigInt64");
756
+ a(this, "rawStrings");
757
+ a(this, "maxStrLength");
758
+ a(this, "maxBinLength");
759
+ a(this, "maxArrayLength");
760
+ a(this, "maxMapLength");
761
+ a(this, "maxExtLength");
762
+ a(this, "keyDecoder");
763
+ a(this, "mapKeyConverter");
764
+ a(this, "totalPos", 0);
765
+ a(this, "pos", 0);
766
+ a(this, "view", Y);
767
+ a(this, "bytes", lt);
768
+ a(this, "headByte", C);
769
+ a(this, "stack", new ht());
770
+ a(this, "entered", !1);
771
+ this.extensionCodec = (e == null ? void 0 : e.extensionCodec) ?? F.defaultCodec, this.context = e == null ? void 0 : e.context, this.useBigInt64 = (e == null ? void 0 : e.useBigInt64) ?? !1, this.rawStrings = (e == null ? void 0 : e.rawStrings) ?? !1, this.maxStrLength = (e == null ? void 0 : e.maxStrLength) ?? z, this.maxBinLength = (e == null ? void 0 : e.maxBinLength) ?? z, this.maxArrayLength = (e == null ? void 0 : e.maxArrayLength) ?? z, this.maxMapLength = (e == null ? void 0 : e.maxMapLength) ?? z, this.maxExtLength = (e == null ? void 0 : e.maxExtLength) ?? z, this.keyDecoder = (e == null ? void 0 : e.keyDecoder) !== void 0 ? e.keyDecoder : dt, this.mapKeyConverter = (e == null ? void 0 : e.mapKeyConverter) ?? ct;
772
+ }
773
+ clone() {
774
+ return new q({
775
+ extensionCodec: this.extensionCodec,
776
+ context: this.context,
777
+ useBigInt64: this.useBigInt64,
778
+ rawStrings: this.rawStrings,
779
+ maxStrLength: this.maxStrLength,
780
+ maxBinLength: this.maxBinLength,
781
+ maxArrayLength: this.maxArrayLength,
782
+ maxMapLength: this.maxMapLength,
783
+ maxExtLength: this.maxExtLength,
784
+ keyDecoder: this.keyDecoder
785
+ });
786
+ }
787
+ reinitializeState() {
788
+ this.totalPos = 0, this.headByte = C, this.stack.reset();
789
+ }
790
+ setBuffer(e) {
791
+ const t = W(e);
792
+ this.bytes = t, this.view = new DataView(t.buffer, t.byteOffset, t.byteLength), this.pos = 0;
793
+ }
794
+ appendBuffer(e) {
795
+ if (this.headByte === C && !this.hasRemaining(1))
796
+ this.setBuffer(e);
797
+ else {
798
+ const t = this.bytes.subarray(this.pos), i = W(e), s = new Uint8Array(t.length + i.length);
799
+ s.set(t), s.set(i, t.length), this.setBuffer(s);
800
+ }
801
+ }
802
+ hasRemaining(e) {
803
+ return this.view.byteLength - this.pos >= e;
804
+ }
805
+ createExtraByteError(e) {
806
+ const { view: t, pos: i } = this;
807
+ return new RangeError(`Extra ${t.byteLength - i} of ${t.byteLength} byte(s) found at buffer[${e}]`);
808
+ }
809
+ /**
810
+ * @throws {@link DecodeError}
811
+ * @throws {@link RangeError}
812
+ */
813
+ decode(e) {
814
+ if (this.entered)
815
+ return this.clone().decode(e);
816
+ try {
817
+ this.entered = !0, this.reinitializeState(), this.setBuffer(e);
818
+ const t = this.doDecodeSync();
819
+ if (this.hasRemaining(1))
820
+ throw this.createExtraByteError(this.pos);
821
+ return t;
822
+ } finally {
823
+ this.entered = !1;
824
+ }
825
+ }
826
+ *decodeMulti(e) {
827
+ if (this.entered) {
828
+ yield* this.clone().decodeMulti(e);
829
+ return;
830
+ }
831
+ try {
832
+ for (this.entered = !0, this.reinitializeState(), this.setBuffer(e); this.hasRemaining(1); )
833
+ yield this.doDecodeSync();
834
+ } finally {
835
+ this.entered = !1;
836
+ }
837
+ }
838
+ async decodeAsync(e) {
839
+ if (this.entered)
840
+ return this.clone().decodeAsync(e);
841
+ try {
842
+ this.entered = !0;
843
+ let t = !1, i;
844
+ for await (const h of e) {
845
+ if (t)
846
+ throw this.entered = !1, this.createExtraByteError(this.totalPos);
847
+ this.appendBuffer(h);
848
+ try {
849
+ i = this.doDecodeSync(), t = !0;
850
+ } catch (d) {
851
+ if (!(d instanceof RangeError))
852
+ throw d;
853
+ }
854
+ this.totalPos += this.pos;
855
+ }
856
+ if (t) {
857
+ if (this.hasRemaining(1))
858
+ throw this.createExtraByteError(this.totalPos);
859
+ return i;
860
+ }
861
+ const { headByte: s, pos: r, totalPos: o } = this;
862
+ throw new RangeError(`Insufficient data in parsing ${K(s)} at ${o} (${r} in the current buffer)`);
863
+ } finally {
864
+ this.entered = !1;
865
+ }
866
+ }
867
+ decodeArrayStream(e) {
868
+ return this.decodeMultiAsync(e, !0);
869
+ }
870
+ decodeStream(e) {
871
+ return this.decodeMultiAsync(e, !1);
872
+ }
873
+ async *decodeMultiAsync(e, t) {
874
+ if (this.entered) {
875
+ yield* this.clone().decodeMultiAsync(e, t);
876
+ return;
877
+ }
878
+ try {
879
+ this.entered = !0;
880
+ let i = t, s = -1;
881
+ for await (const r of e) {
882
+ if (t && s === 0)
883
+ throw this.createExtraByteError(this.totalPos);
884
+ this.appendBuffer(r), i && (s = this.readArraySize(), i = !1, this.complete());
885
+ try {
886
+ for (; yield this.doDecodeSync(), --s !== 0; )
887
+ ;
888
+ } catch (o) {
889
+ if (!(o instanceof RangeError))
890
+ throw o;
891
+ }
892
+ this.totalPos += this.pos;
893
+ }
894
+ } finally {
895
+ this.entered = !1;
896
+ }
897
+ }
898
+ doDecodeSync() {
899
+ e: for (; ; ) {
900
+ const e = this.readHeadByte();
901
+ let t;
902
+ if (e >= 224)
903
+ t = e - 256;
904
+ else if (e < 192)
905
+ if (e < 128)
906
+ t = e;
907
+ else if (e < 144) {
908
+ const s = e - 128;
909
+ if (s !== 0) {
910
+ this.pushMapState(s), this.complete();
911
+ continue e;
912
+ } else
913
+ t = {};
914
+ } else if (e < 160) {
915
+ const s = e - 144;
916
+ if (s !== 0) {
917
+ this.pushArrayState(s), this.complete();
918
+ continue e;
919
+ } else
920
+ t = [];
921
+ } else {
922
+ const s = e - 160;
923
+ t = this.decodeString(s, 0);
924
+ }
925
+ else if (e === 192)
926
+ t = null;
927
+ else if (e === 194)
928
+ t = !1;
929
+ else if (e === 195)
930
+ t = !0;
931
+ else if (e === 202)
932
+ t = this.readF32();
933
+ else if (e === 203)
934
+ t = this.readF64();
935
+ else if (e === 204)
936
+ t = this.readU8();
937
+ else if (e === 205)
938
+ t = this.readU16();
939
+ else if (e === 206)
940
+ t = this.readU32();
941
+ else if (e === 207)
942
+ this.useBigInt64 ? t = this.readU64AsBigInt() : t = this.readU64();
943
+ else if (e === 208)
944
+ t = this.readI8();
945
+ else if (e === 209)
946
+ t = this.readI16();
947
+ else if (e === 210)
948
+ t = this.readI32();
949
+ else if (e === 211)
950
+ this.useBigInt64 ? t = this.readI64AsBigInt() : t = this.readI64();
951
+ else if (e === 217) {
952
+ const s = this.lookU8();
953
+ t = this.decodeString(s, 1);
954
+ } else if (e === 218) {
955
+ const s = this.lookU16();
956
+ t = this.decodeString(s, 2);
957
+ } else if (e === 219) {
958
+ const s = this.lookU32();
959
+ t = this.decodeString(s, 4);
960
+ } else if (e === 220) {
961
+ const s = this.readU16();
962
+ if (s !== 0) {
963
+ this.pushArrayState(s), this.complete();
964
+ continue e;
965
+ } else
966
+ t = [];
967
+ } else if (e === 221) {
968
+ const s = this.readU32();
969
+ if (s !== 0) {
970
+ this.pushArrayState(s), this.complete();
971
+ continue e;
972
+ } else
973
+ t = [];
974
+ } else if (e === 222) {
975
+ const s = this.readU16();
976
+ if (s !== 0) {
977
+ this.pushMapState(s), this.complete();
978
+ continue e;
979
+ } else
980
+ t = {};
981
+ } else if (e === 223) {
982
+ const s = this.readU32();
983
+ if (s !== 0) {
984
+ this.pushMapState(s), this.complete();
985
+ continue e;
986
+ } else
987
+ t = {};
988
+ } else if (e === 196) {
989
+ const s = this.lookU8();
990
+ t = this.decodeBinary(s, 1);
991
+ } else if (e === 197) {
992
+ const s = this.lookU16();
993
+ t = this.decodeBinary(s, 2);
994
+ } else if (e === 198) {
995
+ const s = this.lookU32();
996
+ t = this.decodeBinary(s, 4);
997
+ } else if (e === 212)
998
+ t = this.decodeExtension(1, 0);
999
+ else if (e === 213)
1000
+ t = this.decodeExtension(2, 0);
1001
+ else if (e === 214)
1002
+ t = this.decodeExtension(4, 0);
1003
+ else if (e === 215)
1004
+ t = this.decodeExtension(8, 0);
1005
+ else if (e === 216)
1006
+ t = this.decodeExtension(16, 0);
1007
+ else if (e === 199) {
1008
+ const s = this.lookU8();
1009
+ t = this.decodeExtension(s, 1);
1010
+ } else if (e === 200) {
1011
+ const s = this.lookU16();
1012
+ t = this.decodeExtension(s, 2);
1013
+ } else if (e === 201) {
1014
+ const s = this.lookU32();
1015
+ t = this.decodeExtension(s, 4);
1016
+ } else
1017
+ throw new y(`Unrecognized type byte: ${K(e)}`);
1018
+ this.complete();
1019
+ const i = this.stack;
1020
+ for (; i.length > 0; ) {
1021
+ const s = i.top();
1022
+ if (s.type === O)
1023
+ if (s.array[s.position] = t, s.position++, s.position === s.size)
1024
+ t = s.array, i.release(s);
1025
+ else
1026
+ continue e;
1027
+ else if (s.type === L) {
1028
+ if (t === "__proto__")
1029
+ throw new y("The key __proto__ is not allowed");
1030
+ s.key = this.mapKeyConverter(t), s.type = ge;
1031
+ continue e;
1032
+ } else if (s.map[s.key] = t, s.readCount++, s.readCount === s.size)
1033
+ t = s.map, i.release(s);
1034
+ else {
1035
+ s.key = null, s.type = L;
1036
+ continue e;
1037
+ }
1038
+ }
1039
+ return t;
1040
+ }
1041
+ }
1042
+ readHeadByte() {
1043
+ return this.headByte === C && (this.headByte = this.readU8()), this.headByte;
1044
+ }
1045
+ complete() {
1046
+ this.headByte = C;
1047
+ }
1048
+ readArraySize() {
1049
+ const e = this.readHeadByte();
1050
+ switch (e) {
1051
+ case 220:
1052
+ return this.readU16();
1053
+ case 221:
1054
+ return this.readU32();
1055
+ default: {
1056
+ if (e < 160)
1057
+ return e - 144;
1058
+ throw new y(`Unrecognized array type byte: ${K(e)}`);
1059
+ }
1060
+ }
1061
+ }
1062
+ pushMapState(e) {
1063
+ if (e > this.maxMapLength)
1064
+ throw new y(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);
1065
+ this.stack.pushMapState(e);
1066
+ }
1067
+ pushArrayState(e) {
1068
+ if (e > this.maxArrayLength)
1069
+ throw new y(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);
1070
+ this.stack.pushArrayState(e);
1071
+ }
1072
+ decodeString(e, t) {
1073
+ return !this.rawStrings || this.stateIsMapKey() ? this.decodeUtf8String(e, t) : this.decodeBinary(e, t);
1074
+ }
1075
+ /**
1076
+ * @throws {@link RangeError}
1077
+ */
1078
+ decodeUtf8String(e, t) {
1079
+ var r;
1080
+ if (e > this.maxStrLength)
1081
+ throw new y(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);
1082
+ if (this.bytes.byteLength < this.pos + t + e)
1083
+ throw he;
1084
+ const i = this.pos + t;
1085
+ let s;
1086
+ return this.stateIsMapKey() && ((r = this.keyDecoder) != null && r.canBeCached(e)) ? s = this.keyDecoder.decode(this.bytes, i, e) : s = We(this.bytes, i, e), this.pos += t + e, s;
1087
+ }
1088
+ stateIsMapKey() {
1089
+ return this.stack.length > 0 ? this.stack.top().type === L : !1;
1090
+ }
1091
+ /**
1092
+ * @throws {@link RangeError}
1093
+ */
1094
+ decodeBinary(e, t) {
1095
+ if (e > this.maxBinLength)
1096
+ throw new y(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);
1097
+ if (!this.hasRemaining(e + t))
1098
+ throw he;
1099
+ const i = this.pos + t, s = this.bytes.subarray(i, i + e);
1100
+ return this.pos += t + e, s;
1101
+ }
1102
+ decodeExtension(e, t) {
1103
+ if (e > this.maxExtLength)
1104
+ throw new y(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);
1105
+ const i = this.view.getInt8(this.pos + t), s = this.decodeBinary(
1106
+ e,
1107
+ t + 1
1108
+ /* extType */
1109
+ );
1110
+ return this.extensionCodec.decode(s, i, this.context);
1111
+ }
1112
+ lookU8() {
1113
+ return this.view.getUint8(this.pos);
1114
+ }
1115
+ lookU16() {
1116
+ return this.view.getUint16(this.pos);
1117
+ }
1118
+ lookU32() {
1119
+ return this.view.getUint32(this.pos);
1120
+ }
1121
+ readU8() {
1122
+ const e = this.view.getUint8(this.pos);
1123
+ return this.pos++, e;
1124
+ }
1125
+ readI8() {
1126
+ const e = this.view.getInt8(this.pos);
1127
+ return this.pos++, e;
1128
+ }
1129
+ readU16() {
1130
+ const e = this.view.getUint16(this.pos);
1131
+ return this.pos += 2, e;
1132
+ }
1133
+ readI16() {
1134
+ const e = this.view.getInt16(this.pos);
1135
+ return this.pos += 2, e;
1136
+ }
1137
+ readU32() {
1138
+ const e = this.view.getUint32(this.pos);
1139
+ return this.pos += 4, e;
1140
+ }
1141
+ readI32() {
1142
+ const e = this.view.getInt32(this.pos);
1143
+ return this.pos += 4, e;
1144
+ }
1145
+ readU64() {
1146
+ const e = Ve(this.view, this.pos);
1147
+ return this.pos += 8, e;
1148
+ }
1149
+ readI64() {
1150
+ const e = pe(this.view, this.pos);
1151
+ return this.pos += 8, e;
1152
+ }
1153
+ readU64AsBigInt() {
1154
+ const e = this.view.getBigUint64(this.pos);
1155
+ return this.pos += 8, e;
1156
+ }
1157
+ readI64AsBigInt() {
1158
+ const e = this.view.getBigInt64(this.pos);
1159
+ return this.pos += 8, e;
1160
+ }
1161
+ readF32() {
1162
+ const e = this.view.getFloat32(this.pos);
1163
+ return this.pos += 4, e;
1164
+ }
1165
+ readF64() {
1166
+ const e = this.view.getFloat64(this.pos);
1167
+ return this.pos += 8, e;
1168
+ }
1169
+ }
1170
+ function ft(n, e) {
1171
+ return new q(e).decode(n);
1172
+ }
1173
+ const ut = /* @__PURE__ */ new Set([
1174
+ "auth",
1175
+ "open",
1176
+ "send",
1177
+ "sync",
1178
+ "history",
1179
+ "read",
1180
+ "typing",
1181
+ "react",
1182
+ "edit",
1183
+ "delete",
1184
+ "invoke",
1185
+ "pubkey",
1186
+ "ping",
1187
+ "uploadPrekeys",
1188
+ "fetchPrekey",
1189
+ "assign",
1190
+ "tag",
1191
+ "note",
1192
+ "agent_status",
1193
+ "subscribe_inbox",
1194
+ "unsubscribe_inbox"
1195
+ ]);
1196
+ function mt(n) {
1197
+ return ut.has(n.type);
1198
+ }
1199
+ function le(n) {
1200
+ return nt(n);
1201
+ }
1202
+ function xt(n) {
1203
+ let e;
1204
+ try {
1205
+ e = ft(n);
1206
+ } catch {
1207
+ return null;
1208
+ }
1209
+ return typeof e != "object" || e === null || typeof e.type != "string" ? null : e;
1210
+ }
1211
+ function pt(n) {
1212
+ switch (n) {
1213
+ case "open":
1214
+ return { label: "Open", cls: "open" };
1215
+ case "awaiting_staff":
1216
+ return { label: "Waiting on you", cls: "waiting" };
1217
+ case "resolved":
1218
+ return { label: "Resolved", cls: "done" };
1219
+ case "closed":
1220
+ return { label: "Closed", cls: "done" };
1221
+ default:
1222
+ return null;
1223
+ }
1224
+ }
1225
+ function gt(n) {
1226
+ const e = Math.floor((Date.now() - n) / 1e3);
1227
+ if (e < 60) return "just now";
1228
+ if (e < 3600) return `${Math.floor(e / 60)}m`;
1229
+ if (e < 86400) return `${Math.floor(e / 3600)}h`;
1230
+ const t = Math.floor(e / 86400);
1231
+ if (t <= 7) return `${t}d`;
1232
+ try {
1233
+ return new Date(n).toLocaleDateString(void 0, { month: "short", day: "numeric" });
1234
+ } catch {
1235
+ return `${t}d`;
1236
+ }
1237
+ }
1238
+ function l(n, e, t) {
1239
+ const i = document.createElement(n);
1240
+ return e && (i.className = e), t !== void 0 && (i.textContent = t), i;
1241
+ }
1242
+ function Ut(n) {
1243
+ const e = n.token ?? n.userId ?? Ce(), { httpBase: t, wsUrl: i } = de(n.url, n.apiUrl), s = n.i18n ?? {}, r = n.accent ?? "#6c5ce7";
1244
+ if (!document.getElementById("ocl-styles")) {
1245
+ const c = document.createElement("style");
1246
+ c.id = "ocl-styles", c.textContent = Te, document.head.append(c);
1247
+ }
1248
+ if (n.webfont !== !1 && typeof document < "u" && !document.getElementById("ocw-webfont")) {
1249
+ const c = document.createElement("link");
1250
+ c.id = "ocw-webfont", c.rel = "stylesheet", c.href = "https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap", document.head.append(c);
1251
+ }
1252
+ const o = l("div", "ocl");
1253
+ o.style.setProperty("--ocl-accent", r), o.dataset.theme = n.theme ?? "light", n.reserveCloseSpace && o.classList.add("ocl-has-close");
1254
+ const h = l("div", "ocl-head"), d = s.title ?? "Your conversations", U = l("span", "ocl-title", d);
1255
+ if (U.setAttribute("aria-label", d), h.append(U), n.onNewChat) {
1256
+ const c = l("button", "ocl-compose", "✎");
1257
+ c.title = s.newChat ?? "New conversation", c.addEventListener("click", () => n.onNewChat()), h.append(c);
1258
+ }
1259
+ const b = l("div", "ocl-search-wrap"), x = l("input", "ocl-search");
1260
+ x.placeholder = s.search ?? "🔍 Search", x.type = "search", b.append(x);
1261
+ const g = l("div", "ocl-body");
1262
+ g.append(l("div", "ocl-spinner", "Loading…")), o.append(h, b, g), n.el.replaceChildren(o);
1263
+ const I = (c) => {
1264
+ o.classList.toggle("ocl-compact", c > 0 && c < 400);
1265
+ };
1266
+ I(o.clientWidth);
1267
+ let v = null;
1268
+ if (typeof ResizeObserver < "u" && (v = new ResizeObserver((c) => {
1269
+ var u;
1270
+ return I(((u = c[0]) == null ? void 0 : u.contentRect.width) ?? o.clientWidth);
1271
+ }), v.observe(o)), !n.profileId && !n.tenantId) throw new Error("[relay chatlist] provide profileId or tenantId");
1272
+ let X;
1273
+ const G = `ocl_seen_${n.profileId ?? `t_${n.tenantId}`}_${(n.userId ?? e).slice(-8)}`;
1274
+ let k = {};
1275
+ try {
1276
+ k = JSON.parse(localStorage.getItem(G) ?? "{}");
1277
+ } catch {
1278
+ }
1279
+ const we = () => {
1280
+ try {
1281
+ localStorage.setItem(G, JSON.stringify(k));
1282
+ } catch {
1283
+ }
1284
+ };
1285
+ let J = [], B = !1;
1286
+ const ye = async () => {
1287
+ const c = n.profileId ? `profileId=${encodeURIComponent(n.profileId)}${n.scope === "tenant" ? "&scope=tenant" : ""}` : `tenantId=${encodeURIComponent(n.tenantId)}`, u = `${t}/conversations/mine?${c}`, w = { authorization: `Bearer ${e}` };
1288
+ let S;
1289
+ try {
1290
+ S = await fetch(u, { headers: w });
1291
+ } catch {
1292
+ S = await fetch(u, { headers: w });
1293
+ }
1294
+ if (!S.ok) return [];
1295
+ const m = await S.json();
1296
+ return m.defaultProfileId && (X = m.defaultProfileId), (m.conversations ?? []).sort((E, f) => f.updatedAt - E.updatedAt);
1297
+ }, Z = (c, u) => {
1298
+ if (B) return;
1299
+ const w = u ? c.filter(
1300
+ (f) => Q(f).toLowerCase().includes(u) || (f.lastMessage ?? "").toLowerCase().includes(u)
1301
+ ) : c;
1302
+ if (g.replaceChildren(), !w.length) {
1303
+ const f = l("div", "ocl-empty", u ? "No results." : s.empty ?? "No conversations yet.");
1304
+ if (!u && n.onNewChat) {
1305
+ f.append(l("br"));
1306
+ const D = l("button", "ocl-start", s.newChat ?? "Start a conversation");
1307
+ D.addEventListener("click", () => n.onNewChat()), f.append(D);
1308
+ }
1309
+ g.append(f);
1310
+ return;
1311
+ }
1312
+ const S = (f) => (f.lastSeq ?? 0) > (k[f.id] ?? 0), m = w.filter(S), E = w.filter((f) => !S(f));
1313
+ if (m.length) {
1314
+ g.append(l("div", "ocl-section", `${s.unread ?? "Unread"} (${m.length})`));
1315
+ for (const f of m) g.append(j(f, S(f)));
1316
+ }
1317
+ if (E.length) {
1318
+ g.append(l("div", "ocl-section", m.length ? s.all ?? "All conversations" : ""));
1319
+ for (const f of E) g.append(j(f, !1));
1320
+ }
1321
+ }, Q = (c) => c.subjectTitle ?? (c.kind === "direct" ? c.peerId ?? "Direct message" : "General enquiry"), j = (c, u) => {
1322
+ var re;
1323
+ const w = Q(c), S = (((re = w.match(new RegExp("\\p{L}", "u"))) == null ? void 0 : re[0]) ?? w.trim()[0] ?? "?").toUpperCase(), m = c.lastSeq ?? 0, E = u ? Math.max(1, m - (k[c.id] ?? 0)) : 0, f = l("button", `ocl-row${u ? " unread" : ""}`), D = l("div", "ocl-av", S);
1324
+ f.append(D);
1325
+ const N = l("div", "ocl-info");
1326
+ N.append(l("div", "ocl-name", w));
1327
+ const me = {
1328
+ open: "Open",
1329
+ awaiting_staff: "Waiting for reply…",
1330
+ resolved: "Resolved ✓",
1331
+ closed: "Closed"
1332
+ };
1333
+ N.append(l("div", "ocl-preview", c.lastMessage ?? me[c.state] ?? c.state)), f.append(N);
1334
+ const $ = l("div", "ocl-right");
1335
+ $.append(l("div", "ocl-time", gt(c.updatedAt)));
1336
+ const H = pt(c.state);
1337
+ return H && $.append(l("div", `ocl-status ${H.cls}`, H.label)), E > 0 && $.append(l("div", "ocl-badge", String(E > 99 ? "99+" : E))), f.append($), f.addEventListener("click", () => {
1338
+ var oe;
1339
+ m > 0 && (k[c.id] = m, we()), f.classList.remove("unread"), (oe = $.querySelector(".ocl-badge")) == null || oe.remove(), n.onSelect(c);
1340
+ }), f;
1341
+ }, M = () => {
1342
+ B || ye().then((c) => {
1343
+ B || (J = c, Z(c, x.value.trim().toLowerCase()));
1344
+ }).catch((c) => {
1345
+ if (B) return;
1346
+ console.error(`[chat-widget] failed to load conversations from ${t}/conversations/mine — check the apiUrl/CORS config.`, c);
1347
+ const u = l("div", "ocl-empty", s.error ?? "Could not load conversations.");
1348
+ u.append(l("br"));
1349
+ const w = l("button", "ocl-retry", s.retry ?? "Retry");
1350
+ w.addEventListener("click", () => {
1351
+ g.replaceChildren(l("div", "ocl-spinner", "Loading…")), M();
1352
+ }), u.append(w), g.replaceChildren(u);
1353
+ });
1354
+ };
1355
+ x.addEventListener("input", () => Z(J, x.value.trim().toLowerCase())), M();
1356
+ let p = null, T, A, ee = 0, te = !1;
1357
+ const ie = () => {
1358
+ A || (A = setTimeout(() => {
1359
+ A = void 0, M();
1360
+ }, 300));
1361
+ }, se = () => {
1362
+ if (!B) {
1363
+ try {
1364
+ p = new WebSocket(i);
1365
+ } catch {
1366
+ ne();
1367
+ return;
1368
+ }
1369
+ p.binaryType = "arraybuffer", p.onopen = () => {
1370
+ ee = 0, p.send(le({ type: "auth", token: e })), p.send(le({ type: "subscribe_inbox" })), te && ie(), te = !0;
1371
+ }, p.onmessage = (c) => {
1372
+ const u = xt(new Uint8Array(c.data));
1373
+ u && u.type === "inbox_event" && ie();
1374
+ }, p.onclose = () => {
1375
+ p = null, ne();
1376
+ }, p.onerror = () => {
1377
+ try {
1378
+ p == null || p.close();
1379
+ } catch {
1380
+ }
1381
+ };
1382
+ }
1383
+ }, ne = () => {
1384
+ if (B || T) return;
1385
+ const c = Math.min(15e3, 500 * 2 ** ee++) + Math.random() * 250;
1386
+ T = setTimeout(() => {
1387
+ T = void 0, se();
1388
+ }, c);
1389
+ };
1390
+ return se(), {
1391
+ refresh: M,
1392
+ close() {
1393
+ B = !0, T && clearTimeout(T), A && clearTimeout(A), v == null || v.disconnect(), v = null;
1394
+ try {
1395
+ p == null || p.close();
1396
+ } catch {
1397
+ }
1398
+ p = null, n.el.replaceChildren();
1399
+ },
1400
+ defaultProfileId() {
1401
+ return n.profileId ?? X;
1402
+ }
1403
+ };
1404
+ }
1405
+ export {
1406
+ yt as a,
1407
+ ce as b,
1408
+ xt as d,
1409
+ le as e,
1410
+ Se as h,
1411
+ mt as i,
1412
+ ke as l,
1413
+ Ut as m,
1414
+ Ce as p,
1415
+ de as r
1416
+ };
1417
+ //# sourceMappingURL=chatlist2.js.map