live-quiz 0.1.0

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,3391 @@
1
+ var Rt = Object.defineProperty;
2
+ var Tt = (s, e, t) => e in s ? Rt(s, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[e] = t;
3
+ var se = (s, e, t) => Tt(s, typeof e != "symbol" ? e + "" : e, t);
4
+ let $ = () => ({
5
+ emit(s, ...e) {
6
+ for (let t = this.events[s] || [], n = 0, i = t.length; n < i; n++)
7
+ t[n](...e);
8
+ },
9
+ events: {},
10
+ on(s, e) {
11
+ var t;
12
+ return ((t = this.events)[s] || (t[s] = [])).push(e), () => {
13
+ var n;
14
+ this.events[s] = (n = this.events[s]) == null ? void 0 : n.filter((i) => e !== i);
15
+ };
16
+ }
17
+ });
18
+ class J extends Error {
19
+ constructor(e, t) {
20
+ e instanceof Error ? (super(e.message), this.cause = e) : super(e), this.reason = t, this.name = "ReasonError";
21
+ }
22
+ }
23
+ class ht extends J {
24
+ constructor(e) {
25
+ super("Rejected", e), this.name = "SubscriptionRejectedError";
26
+ }
27
+ }
28
+ class Nt extends J {
29
+ constructor(e) {
30
+ super(e || "Timed out to receive subscription ack"), this.name = "SubscriptionTimeoutError";
31
+ }
32
+ }
33
+ class A extends J {
34
+ constructor(e, t) {
35
+ t ? super(e, t) : super("Disconnected", e), this.name = "DisconnectedError";
36
+ }
37
+ }
38
+ class At extends A {
39
+ constructor(e) {
40
+ super(e, "stale_connection"), this.name = "StaleConnectionError";
41
+ }
42
+ }
43
+ function dt(s) {
44
+ return s ? `{${Object.keys(s).sort().filter((t) => s[t] !== void 0).map((t) => {
45
+ let n = JSON.stringify(s[t]);
46
+ return `${JSON.stringify(t)}:${n}`;
47
+ }).join(",")}}` : "";
48
+ }
49
+ class Mt {
50
+ constructor(e) {
51
+ this.channel = e, this.listeners = [];
52
+ }
53
+ watch() {
54
+ this.listeners.push(
55
+ this.channel.on("presence", (e) => {
56
+ if (e.type === "info") {
57
+ this._state || (this._state = this.stateFromInfo(e));
58
+ return;
59
+ }
60
+ this._state && (e.type === "join" ? this._state[e.id] = e.info : e.type === "leave" && delete this._state[e.id]);
61
+ })
62
+ );
63
+ }
64
+ // Reset the state to make sure the fresh one is
65
+ // requested the next time info() is called
66
+ reset() {
67
+ delete this._state;
68
+ }
69
+ dispose() {
70
+ delete this._info, delete this._state, this.listeners.forEach((e) => e()), this.listeners.length = 0;
71
+ }
72
+ async join(e, t) {
73
+ if (!this._info)
74
+ return this._info = { id: String(e), info: t }, this.channel.perform("$presence:join", this._info);
75
+ }
76
+ async leave() {
77
+ if (!this._info) return;
78
+ let e = await this.channel.perform("$presence:leave");
79
+ return delete this._info, e;
80
+ }
81
+ async info() {
82
+ return this._state ? this._state : (this._promise || (this._promise = this._sync()), await this._promise, this._state);
83
+ }
84
+ async _sync() {
85
+ this.watch();
86
+ try {
87
+ let e = await this.channel.perform("$presence:info", {});
88
+ return this._state = this.stateFromInfo(e), this._state;
89
+ } finally {
90
+ delete this._promise;
91
+ }
92
+ }
93
+ stateFromInfo(e) {
94
+ return e.records ? e.records.reduce((t, { id: n, info: i }) => (t[n] = i, t), {}) : {};
95
+ }
96
+ }
97
+ const U = Symbol("state");
98
+ class ft {
99
+ // Unique channel identifier
100
+ // static identifier = ''
101
+ constructor(e = {}) {
102
+ this.emitter = $(), this.params = Object.freeze(e), this.presence = new Mt(this), this.initialConnect = !0, this[U] = "idle";
103
+ }
104
+ get identifier() {
105
+ return this._identifier ? this._identifier : (this._identifier = dt({
106
+ channel: this.channelId,
107
+ ...this.params
108
+ }), this._identifier);
109
+ }
110
+ get channelId() {
111
+ return this.constructor.identifier;
112
+ }
113
+ get state() {
114
+ return this[U];
115
+ }
116
+ attached(e) {
117
+ if (this.receiver) {
118
+ if (this.receiver !== e)
119
+ throw Error("Already connected to a different receiver");
120
+ return !1;
121
+ }
122
+ return this.receiver = e, !0;
123
+ }
124
+ connecting() {
125
+ this[U] = "connecting";
126
+ }
127
+ connected() {
128
+ if (this.state === "connected" || this.state === "closed") return;
129
+ this[U] = "connected";
130
+ let e = !1;
131
+ this.initialConnect ? (this.initialConnect = !1, this.emit("connect", { reconnect: !1, restored: e })) : this.emit("connect", { reconnect: !0, restored: e });
132
+ }
133
+ restored() {
134
+ if (this.state === "connected") throw Error("Already connected");
135
+ this[U] = "connected";
136
+ let e = !0, t = !0;
137
+ this.initialConnect = !1, this.emit("connect", { reconnect: t, restored: e });
138
+ }
139
+ disconnected(e) {
140
+ this.state === "disconnected" || this.state === "closed" || (this[U] = "disconnected", this.presence.reset(), this.emit("disconnect", e));
141
+ }
142
+ closed(e) {
143
+ this.state !== "closed" && (this[U] = "closed", delete this.receiver, this.initialConnect = !0, this.presence.dispose(), this.emit("close", e));
144
+ }
145
+ disconnect() {
146
+ this.state === "idle" || this.state === "closed" || this.receiver.unsubscribe(this);
147
+ }
148
+ async perform(e, t) {
149
+ if (this.state === "idle" || this.state === "closed")
150
+ throw Error("Channel is not subscribed");
151
+ return this.receiver.perform(this.identifier, e, t);
152
+ }
153
+ async send(e) {
154
+ return this.perform(void 0, e);
155
+ }
156
+ async whisper(e) {
157
+ try {
158
+ await this.perform("$whisper", e);
159
+ } catch (t) {
160
+ let n = this.receiver ? this.receiver.logger : null;
161
+ n && n.warn("whisper failed: ", t);
162
+ }
163
+ }
164
+ receive(e, t) {
165
+ this.emit("message", e, t);
166
+ }
167
+ on(e, t) {
168
+ return this.emitter.on(e, t);
169
+ }
170
+ once(e, t) {
171
+ let n = this.emitter.on(e, (...i) => {
172
+ n(), t(...i);
173
+ });
174
+ return n;
175
+ }
176
+ emit(e, ...t) {
177
+ return this.emitter.emit(e, ...t);
178
+ }
179
+ ensureSubscribed() {
180
+ return this.state === "connected" ? Promise.resolve() : this.state === "closed" ? Promise.reject(Error("Channel is unsubscribed")) : this.pendingSubscribe();
181
+ }
182
+ // This promise resolves when subscription is confirmed
183
+ // and rejects when rejected or closed.
184
+ // It ignores disconnect events.
185
+ pendingSubscribe() {
186
+ return this._pendingSubscribe ? this._pendingSubscribe : (this._pendingSubscribe = new Promise((e, t) => {
187
+ let n = [() => delete this._pendingSubscribe];
188
+ n.push(
189
+ this.on("connect", () => {
190
+ n.forEach((i) => i()), e();
191
+ })
192
+ ), n.push(
193
+ this.on("close", (i) => {
194
+ n.forEach((r) => r()), t(
195
+ i || new J(
196
+ "Channel was disconnected before subscribing",
197
+ "canceled"
198
+ )
199
+ );
200
+ })
201
+ );
202
+ }), this._pendingSubscribe);
203
+ }
204
+ }
205
+ class Bt {
206
+ constructor(e) {
207
+ this.id = e, this.intent = "unsubscribed", this.state = "idle", this.channels = [], this.disposed = !1, this._pendings = [];
208
+ }
209
+ add(e) {
210
+ this.channels.includes(e) || this.channels.push(e);
211
+ }
212
+ remove(e) {
213
+ let t = this.channels.indexOf(e);
214
+ t > -1 && this.channels.splice(t, 1);
215
+ }
216
+ notify(e, ...t) {
217
+ this.state = e === "restored" ? "connected" : e, t.length === 1 ? this.channels.forEach((n) => n[e](t[0])) : this.channels.forEach((n) => n[e]());
218
+ }
219
+ pending(e) {
220
+ this._checkIntent(e);
221
+ let t = this._pendings[0];
222
+ return !t || t.intent !== e ? Promise.resolve() : t.promise;
223
+ }
224
+ ensureResubscribed() {
225
+ this.disposed || (this.intent = void 0, this.ensureSubscribed());
226
+ }
227
+ ensureSubscribed() {
228
+ if (this.intent === "subscribed") return;
229
+ if (this.disposed) throw Error("Subscription is disposed");
230
+ this.intent = "subscribed", !this._mergeWithPending("unsubscribed") && this.subscriber(this);
231
+ }
232
+ maybeUnsubscribe() {
233
+ this.disposed || this.intent === "unsubscribed" || this.channels.length > 0 || (this.intent = "unsubscribed", this._mergeWithPending("subscribed")) || this.unsubscriber(this);
234
+ }
235
+ async acquire(e) {
236
+ this._checkIntent(e);
237
+ let t, i = {
238
+ promise: new Promise((o) => {
239
+ t = o;
240
+ }),
241
+ intent: e,
242
+ release: () => {
243
+ this._pendings.splice(this._pendings.indexOf(i), 1), t(i);
244
+ },
245
+ canceled: !1,
246
+ acquired: !1
247
+ }, r = this._pendingTop;
248
+ return this._pendings.push(i), r && await r.promise, this.gvl && await this.gvl.acquire(i, e), i.acquired = !0, i;
249
+ }
250
+ close(e) {
251
+ this.disposed = !0, this.intent = void 0, this.notify("closed", e);
252
+ }
253
+ _checkIntent(e) {
254
+ if (!(e === "unsubscribed" || e === "subscribed"))
255
+ throw Error(`Unknown subscription intent: ${e}`);
256
+ }
257
+ get _pendingTop() {
258
+ return this._pendings.length ? this._pendings[this._pendings.length - 1] : void 0;
259
+ }
260
+ _mergeWithPending(e) {
261
+ let t = this._pendingTop;
262
+ return !t || t.acquired || t.intent !== e ? !1 : (this._pendings.pop(), t.canceled = !0, !0);
263
+ }
264
+ }
265
+ class kt {
266
+ constructor() {
267
+ this.queue = [];
268
+ }
269
+ async acquire(e, t) {
270
+ t === "subscribed" && (this.queue.push(
271
+ e.promise.then(() => {
272
+ this.queue.splice(this.queue.indexOf(e), 1);
273
+ })
274
+ ), this.queue.length > 1 && await this.queue[this.queue.length - 2]);
275
+ }
276
+ }
277
+ class zt {
278
+ constructor(e) {
279
+ e.concurrentSubscribes === !1 && (this.glv = new kt()), this._subscriptions = {}, this._localToRemote = {};
280
+ }
281
+ all() {
282
+ return Object.values(this._subscriptions);
283
+ }
284
+ get(e) {
285
+ return this._subscriptions[e];
286
+ }
287
+ create(e, { subscribe: t, unsubscribe: n }) {
288
+ let i = this._subscriptions[e] = new Bt(e);
289
+ return i.remoteId = this._localToRemote[e], i.subscriber = t, i.unsubscriber = n, i.gvl = this.glv, i;
290
+ }
291
+ remove(e) {
292
+ delete this._subscriptions[e], delete this._localToRemote[e];
293
+ }
294
+ storeRemoteId(e, t) {
295
+ this._localToRemote[e] = t;
296
+ let n = this.get(e);
297
+ n && (n.remoteId = t);
298
+ }
299
+ }
300
+ class Lt {
301
+ constructor(e = {}) {
302
+ this.subscriptions = new zt(e), this._pendingMessages = [], this._remoteToLocal = {};
303
+ }
304
+ subscribe(e, t) {
305
+ this._remoteToLocal[t] = e, this.subscriptions.storeRemoteId(e, t), this.flush(t);
306
+ }
307
+ unsubscribe(e) {
308
+ let t = this.subscriptions.get(e);
309
+ if (!t) return;
310
+ let n = t.remoteId;
311
+ n && delete this._remoteToLocal[n], this.subscriptions.remove(e);
312
+ }
313
+ transmit(e, t, n) {
314
+ let i = this._remoteToLocal[e];
315
+ if (!i) {
316
+ this._pendingMessages.push([e, t, n]);
317
+ return;
318
+ }
319
+ let r = this.subscriptions.get(i);
320
+ r && r.channels.forEach((o) => {
321
+ o.receive(t, n);
322
+ });
323
+ }
324
+ notify(e, t, n) {
325
+ let i = this._remoteToLocal[e];
326
+ if (!i)
327
+ return;
328
+ let r = this.subscriptions.get(i);
329
+ r && r.channels.forEach((o) => o.emit(t, n));
330
+ }
331
+ close() {
332
+ this._pendingMessages.length = 0;
333
+ }
334
+ get size() {
335
+ return this.channels.length;
336
+ }
337
+ get channels() {
338
+ return this.subscriptions.all().flatMap((e) => e.channels);
339
+ }
340
+ flush(e) {
341
+ let t = [];
342
+ for (let n of this._pendingMessages)
343
+ n[0] === e ? this.transmit(n[0], n[1], n[2]) : t.push(n);
344
+ this._pendingMessages = t;
345
+ }
346
+ }
347
+ const Be = {
348
+ debug: 0,
349
+ info: 1,
350
+ warn: 2,
351
+ error: 3
352
+ };
353
+ class gt {
354
+ constructor(e) {
355
+ this.level = e || "warn";
356
+ }
357
+ log(e, t, n) {
358
+ Be[e] < Be[this.level] || this.writeLogEntry(e, t, n);
359
+ }
360
+ writeLogEntry() {
361
+ throw Error("Not implemented");
362
+ }
363
+ debug(e, t) {
364
+ this.log("debug", e, t);
365
+ }
366
+ info(e, t) {
367
+ this.log("info", e, t);
368
+ }
369
+ warn(e, t) {
370
+ this.log("warn", e, t);
371
+ }
372
+ error(e, t) {
373
+ this.log("error", e, t);
374
+ }
375
+ }
376
+ class H extends gt {
377
+ writeLogEntry() {
378
+ }
379
+ }
380
+ class Ut {
381
+ encode(e) {
382
+ return JSON.stringify(e);
383
+ }
384
+ decode(e) {
385
+ try {
386
+ return JSON.parse(e);
387
+ } catch {
388
+ }
389
+ }
390
+ }
391
+ let Dt = 0;
392
+ class pt {
393
+ constructor(e = {}) {
394
+ let { logger: t } = e;
395
+ this.logger = t || new H(), this.pendingSubscriptions = {}, this.pendingUnsubscriptions = {}, this.subscribeCooldownInterval = e.subscribeCooldownInterval || 250, this.subscribeRetryInterval = e.subscribeRetryInterval || 5e3;
396
+ }
397
+ attached(e) {
398
+ this.cable = e;
399
+ }
400
+ subscribe(e, t) {
401
+ let n = { channel: e };
402
+ t && Object.assign(n, t);
403
+ let i = dt(n);
404
+ if (this.pendingUnsubscriptions[i]) {
405
+ let o = this.subscribeCooldownInterval * 1.5;
406
+ return this.logger.debug(
407
+ `unsubscribed recently, cooldown for ${o}`,
408
+ i
409
+ ), new Promise((c) => {
410
+ setTimeout(() => {
411
+ c(this.subscribe(e, t));
412
+ }, o);
413
+ });
414
+ }
415
+ if (this.pendingSubscriptions[i])
416
+ return this.logger.warn("subscription is already pending, skipping", i), Promise.reject(Error("Already subscribing"));
417
+ let r = this.subscribeRetryInterval;
418
+ return new Promise((o, c) => {
419
+ let a = ++Dt;
420
+ this.pendingSubscriptions[i] = {
421
+ resolve: o,
422
+ reject: c,
423
+ id: a
424
+ }, this.cable.send(this.buildSubscribeRequest(i)), this.maybeRetrySubscribe(a, i, r);
425
+ });
426
+ }
427
+ buildSubscribeRequest(e) {
428
+ return {
429
+ command: "subscribe",
430
+ identifier: e
431
+ };
432
+ }
433
+ maybeRetrySubscribe(e, t, n) {
434
+ setTimeout(() => {
435
+ let i = this.pendingSubscriptions[t];
436
+ i && i.id === e && (this.logger.warn(
437
+ `no subscription ack received in ${n}ms, retrying subscribe`,
438
+ t
439
+ ), this.cable.send(this.buildSubscribeRequest(t)), this.maybeExpireSubscribe(e, t, n));
440
+ }, n);
441
+ }
442
+ maybeExpireSubscribe(e, t, n) {
443
+ setTimeout(() => {
444
+ let i = this.pendingSubscriptions[t];
445
+ i && i.id === e && (delete this.pendingSubscriptions[t], i.reject(
446
+ new Nt(
447
+ `Haven't received subscription ack in ${n * 2}ms for ${t}`
448
+ )
449
+ ));
450
+ }, n);
451
+ }
452
+ unsubscribe(e) {
453
+ return this.cable.send({
454
+ command: "unsubscribe",
455
+ identifier: e
456
+ }), this.pendingUnsubscriptions[e] = !0, setTimeout(() => {
457
+ delete this.pendingUnsubscriptions[e];
458
+ }, this.subscribeCooldownInterval), Promise.resolve();
459
+ }
460
+ perform(e, t, n) {
461
+ return t === "$whisper" ? this.whisper(e, n) : (n || (n = {}), n.action || (n.action = t), this.cable.send({
462
+ command: "message",
463
+ identifier: e,
464
+ data: JSON.stringify(n)
465
+ }), Promise.resolve());
466
+ }
467
+ whisper(e, t) {
468
+ return this.cable.send({
469
+ command: "whisper",
470
+ identifier: e,
471
+ data: t
472
+ }), Promise.resolve();
473
+ }
474
+ receive(e) {
475
+ if (typeof e != "object") {
476
+ this.logger.error("unsupported message format", { message: e });
477
+ return;
478
+ }
479
+ let { type: t, identifier: n, message: i, reason: r, reconnect: o } = e;
480
+ if (t === "ping")
481
+ return this.cable.keepalive(e.message);
482
+ if (this.cable.keepalive(), t === "welcome") {
483
+ let c = e.sid;
484
+ return c && this.cable.setSessionId(c), this.cable.connected();
485
+ }
486
+ if (t === "disconnect") {
487
+ let c = new A(r);
488
+ this.reset(c), o === !1 ? this.cable.closed(c) : this.cable.disconnected(c);
489
+ return;
490
+ }
491
+ if (t === "confirm_subscription") {
492
+ let c = this.pendingSubscriptions[n];
493
+ if (!c) {
494
+ this.logger.error("subscription not found, unsubscribing", {
495
+ type: t,
496
+ identifier: n
497
+ }), this.unsubscribe(n);
498
+ return;
499
+ }
500
+ return delete this.pendingSubscriptions[n], c.resolve(n);
501
+ }
502
+ if (t === "reject_subscription") {
503
+ let c = this.pendingSubscriptions[n];
504
+ return c ? (delete this.pendingSubscriptions[n], c.reject(new ht())) : this.logger.error("subscription not found", { type: t, identifier: n });
505
+ }
506
+ if (i)
507
+ return { identifier: n, message: i };
508
+ this.logger.warn(`unknown message type: ${t}`, { message: e });
509
+ }
510
+ reset(e) {
511
+ for (let t in this.pendingSubscriptions)
512
+ this.pendingSubscriptions[t].reject(e);
513
+ this.pendingSubscriptions = {};
514
+ }
515
+ recoverableClosure() {
516
+ return !1;
517
+ }
518
+ }
519
+ const ke = () => Date.now() / 1e3 | 0;
520
+ class Ft extends pt {
521
+ constructor(e = {}) {
522
+ super(e), this.streamsPositions = {}, this.subscriptionStreams = {}, this.pendingHistory = {}, this.pendingPresence = {}, this.presenceInfo = {}, this.restoreSince = e.historyTimestamp, this.disableSessionRecovery = e.disableSessionRecovery, this.restoreSince === void 0 && (this.restoreSince = ke()), this.sessionId = void 0, this.sendPongs = e.pongs;
523
+ }
524
+ reset(e) {
525
+ for (let t in this.pendingPresence)
526
+ this.pendingPresence[t].reject(e);
527
+ return this.pendingPresence = {}, super.reset();
528
+ }
529
+ receive(e) {
530
+ if (typeof e != "object") {
531
+ this.logger.error("unsupported message format", { message: e });
532
+ return;
533
+ }
534
+ let { type: t, identifier: n, message: i } = e;
535
+ if (t === "disconnect")
536
+ return delete this.sessionId, this.cable.setSessionId(""), super.receive(e);
537
+ if (t === "reject_subscription")
538
+ return super.receive(e);
539
+ if (t === "confirm_subscription")
540
+ return this.subscriptionStreams[n] || (this.subscriptionStreams[n] = /* @__PURE__ */ new Set()), super.receive(e);
541
+ if (t === "ping")
542
+ return this.restoreSince && (this.restoreSince = ke()), this.sendPongs && this.sendPong(), this.cable.keepalive(e.message);
543
+ if (this.cable.keepalive(), t === "confirm_history") {
544
+ this.logger.debug("history result received", e), this.cable.notify("history_received", n);
545
+ return;
546
+ }
547
+ if (t === "reject_history") {
548
+ this.logger.warn("failed to retrieve history", e), this.cable.notify("history_not_found", n);
549
+ return;
550
+ }
551
+ if (t === "welcome") {
552
+ if (this.disableSessionRecovery || (this.sessionId = e.sid, this.sessionId && this.cable.setSessionId(this.sessionId)), e.restored) {
553
+ let r = e.restored_ids || Object.keys(this.subscriptionStreams);
554
+ for (let o of r)
555
+ this.cable.send({
556
+ identifier: o,
557
+ command: "history",
558
+ history: this.historyRequestFor(o)
559
+ }), this.presenceInfo[o] && this.cable.send({
560
+ identifier: o,
561
+ command: "join",
562
+ presence: this.presenceInfo[o]
563
+ });
564
+ return this.cable.restored(r);
565
+ }
566
+ return this.cable.connected(this.sessionId);
567
+ }
568
+ if (t === "presence") {
569
+ let r = i.type;
570
+ if (r === "info") {
571
+ let o = this.pendingPresence[n];
572
+ o && (delete this.pendingPresence[n], o.resolve(i));
573
+ } else if (r === "error") {
574
+ let o = this.pendingPresence[n];
575
+ o && (delete this.pendingPresence[n], o.reject(new Error("failed to retrieve presence")));
576
+ }
577
+ return {
578
+ type: t,
579
+ identifier: n,
580
+ message: i
581
+ };
582
+ }
583
+ if (i) {
584
+ let r = this.trackStreamPosition(
585
+ n,
586
+ e.stream_id,
587
+ e.epoch,
588
+ e.offset
589
+ );
590
+ return { identifier: n, message: i, meta: r };
591
+ }
592
+ this.logger.warn(`unknown message type: ${t}`, { message: e });
593
+ }
594
+ perform(e, t, n) {
595
+ switch (t) {
596
+ case "$presence:join":
597
+ return this.join(e, n);
598
+ case "$presence:leave":
599
+ return this.leave(e, n);
600
+ case "$presence:info":
601
+ return this.presence(e, n);
602
+ }
603
+ return super.perform(e, t, n);
604
+ }
605
+ unsubscribe(e) {
606
+ return delete this.presenceInfo[e], super.unsubscribe(e);
607
+ }
608
+ buildSubscribeRequest(e) {
609
+ let t = super.buildSubscribeRequest(e), n = this.historyRequestFor(e);
610
+ n && (t.history = n, this.pendingHistory[e] = !0);
611
+ let i = this.presenceInfo[e];
612
+ return i && (t.presence = i), t;
613
+ }
614
+ // TODO: Which error can be non-recoverable?
615
+ recoverableClosure() {
616
+ return !!this.sessionId;
617
+ }
618
+ historyRequestFor(e) {
619
+ let t = {}, n = !1;
620
+ if (this.subscriptionStreams[e])
621
+ for (let i of this.subscriptionStreams[e]) {
622
+ let r = this.streamsPositions[i];
623
+ r && (n = !0, t[i] = r);
624
+ }
625
+ if (!(!n && !this.restoreSince))
626
+ return { since: this.restoreSince, streams: t };
627
+ }
628
+ trackStreamPosition(e, t, n, i) {
629
+ if (!(!t || !n))
630
+ return this.subscriptionStreams[e] || (this.subscriptionStreams[e] = /* @__PURE__ */ new Set()), this.subscriptionStreams[e].add(t), this.streamsPositions[t] = { epoch: n, offset: i }, { stream: t, epoch: n, offset: i };
631
+ }
632
+ // Send pongs asynchrounously—no need to block the main thread
633
+ async sendPong() {
634
+ await new Promise((e) => setTimeout(e, 0)), this.cable.state === "connected" && this.cable.send({ command: "pong" });
635
+ }
636
+ async join(e, t) {
637
+ return this.presenceInfo[e] = t, this.cable.send({
638
+ command: "join",
639
+ identifier: e,
640
+ presence: t
641
+ }), Promise.resolve();
642
+ }
643
+ async leave(e, t) {
644
+ return delete this.presenceInfo[e], this.cable.send({
645
+ command: "leave",
646
+ identifier: e,
647
+ presence: t
648
+ }), Promise.resolve();
649
+ }
650
+ presence(e, t) {
651
+ return this.pendingPresence[e] ? (this.logger.warn("presence is already pending, skipping", e), Promise.reject(Error("presence request is already pending"))) : new Promise((n, i) => {
652
+ this.pendingPresence[e] = {
653
+ resolve: n,
654
+ reject: i
655
+ }, this.cable.send({
656
+ command: "presence",
657
+ identifier: e,
658
+ data: t
659
+ });
660
+ });
661
+ }
662
+ }
663
+ class Ot extends J {
664
+ constructor() {
665
+ super("No connection", "closed"), this.name = "NoConnectionError";
666
+ }
667
+ }
668
+ class mt extends ft {
669
+ constructor(e, t) {
670
+ super(t), this.channelId = e;
671
+ }
672
+ set channelId(e) {
673
+ this._channelId = e;
674
+ }
675
+ get channelId() {
676
+ return this._channelId;
677
+ }
678
+ }
679
+ se(mt, "identifier", "__ghost__");
680
+ const jt = "$pubsub";
681
+ class Re extends ft {
682
+ async perform(e, t) {
683
+ if (e.startsWith("$"))
684
+ return super.perform(e, t);
685
+ throw Error("not implemented");
686
+ }
687
+ }
688
+ se(Re, "identifier", jt);
689
+ const D = Symbol("state");
690
+ class xt {
691
+ constructor({
692
+ transport: e,
693
+ protocol: t,
694
+ encoder: n,
695
+ logger: i,
696
+ lazy: r,
697
+ hubOptions: o,
698
+ performFailures: c,
699
+ transportConfigurator: a
700
+ }) {
701
+ this.emitter = $(), this.transport = e, this.encoder = n, this.logger = i || new H(), this.protocol = t, this.performFailures = c || "throw", this.protocol.attached(this), this.hub = new Lt(o || {}), this[D] = "idle", this.handleClose = this.handleClose.bind(this), this.handleIncoming = this.handleIncoming.bind(this), this.transportConfigurator = a, this.transport.on("close", this.handleClose), this.transport.on("data", this.handleIncoming), this.initialConnect = !0, this.recovering = !1, r === !1 && this.connect().catch(() => {
702
+ });
703
+ }
704
+ get state() {
705
+ return this[D];
706
+ }
707
+ async connect() {
708
+ if (this.state === "connected") return Promise.resolve();
709
+ if (this.state === "connecting")
710
+ return this.pendingConnect();
711
+ let e = this.state === "idle";
712
+ this[D] = "connecting";
713
+ let t = this.pendingConnect();
714
+ this.logger.debug("connecting");
715
+ try {
716
+ this.transportConfigurator && await this.transportConfigurator(this.transport, {
717
+ initial: e
718
+ }), await this.transport.open();
719
+ } catch (n) {
720
+ this.handleClose(n);
721
+ }
722
+ return t;
723
+ }
724
+ setSessionId(e) {
725
+ this.sessionId = e, this.transport.setParam("sid", e);
726
+ }
727
+ connected() {
728
+ if (this.state === "connected") return;
729
+ this.logger.info("connected"), this[D] = "connected", this.recovering && this.hub.subscriptions.all().forEach(
730
+ (t) => t.notify(
731
+ "disconnected",
732
+ new A("recovery_failed")
733
+ )
734
+ ), this.hub.subscriptions.all().forEach((t) => this._resubscribe(t));
735
+ let e = !1;
736
+ this.recovering = !1, this.initialConnect ? (this.initialConnect = !1, this.emit("connect", { reconnect: !1, restored: e })) : this.emit("connect", { reconnect: !0, restored: e });
737
+ }
738
+ restored(e) {
739
+ this.logger.info("connection recovered", { remoteIds: e }), this[D] = "connected", this.hub.subscriptions.all().forEach((i) => {
740
+ e && i.remoteId && e.includes(i.remoteId) ? i.notify("restored") : (i.notify(
741
+ "disconnected",
742
+ new A("recovery_failed")
743
+ ), this._resubscribe(i));
744
+ });
745
+ let t = !this.initialConnect, n = !0;
746
+ this.recovering = !1, this.initialConnect = !1, this.emit("connect", { reconnect: t, restored: n });
747
+ }
748
+ notify(e, t, n) {
749
+ t && typeof t != "string" && (n = t, t = void 0), t ? this.hub.notify(t, "info", { type: e, data: n }) : this.emit("info", { type: e, data: n });
750
+ }
751
+ handleClose(e) {
752
+ this.logger.debug("transport closed", { error: e }), this.disconnected(new A(e, "transport_closed"));
753
+ }
754
+ disconnected(e) {
755
+ (this.state === "connected" || this.state === "connecting") && (this.logger.info("disconnected", { reason: e }), this[D] = "disconnected", this.recovering = this.protocol.recoverableClosure(e), this.recovering ? this.hub.subscriptions.all().forEach((t) => t.notify("connecting")) : this.hub.subscriptions.all().forEach((t) => {
756
+ t.notify("disconnected", e);
757
+ }), this.protocol.reset(e), this.hub.close(), this.transport.close(), this.emit("disconnect", e));
758
+ }
759
+ closed(e) {
760
+ if (this.state === "closed" || this.state === "idle") return;
761
+ let t;
762
+ e && (t = e instanceof A ? e : new A(e, void 0)), this.logger.info("closed", { reason: e || "user" }), this[D] = "closed";
763
+ let n = t || new A("cable_closed");
764
+ this.hub.subscriptions.all().forEach((i) => i.notify("disconnected", n)), this.hub.close(), this.protocol.reset(), this.transport.close(), this.initialConnect = !0, this.emit("close", t);
765
+ }
766
+ disconnect() {
767
+ this.closed();
768
+ }
769
+ handleIncoming(e) {
770
+ if (this.state === "closed" || this.state === "idle")
771
+ return;
772
+ let t = this.encoder.decode(e);
773
+ if (t === void 0) {
774
+ this.logger.error("failed to decode message", { message: e });
775
+ return;
776
+ }
777
+ this.logger.debug("incoming data", t);
778
+ let n = this.protocol.receive(t);
779
+ if (n) {
780
+ this.logger.debug("processed incoming message", n);
781
+ let { type: i, identifier: r, message: o, meta: c } = n;
782
+ i ? this.hub.notify(r, i, o) : this.hub.transmit(r, o, c);
783
+ }
784
+ }
785
+ send(e) {
786
+ if (this.state === "closed")
787
+ throw Error("Cable is closed");
788
+ let t = this.encoder.encode(e);
789
+ if (t === void 0) {
790
+ this.logger.error("failed to encode message", { message: e });
791
+ return;
792
+ }
793
+ this.logger.debug("outgoing message", e), this.transport.send(t);
794
+ }
795
+ keepalive(e) {
796
+ this.emit("keepalive", e);
797
+ }
798
+ streamFrom(e) {
799
+ let t = new Re({ stream_name: e });
800
+ return this.subscribe(t);
801
+ }
802
+ streamFromSigned(e) {
803
+ let t = new Re({ signed_stream_name: e });
804
+ return this.subscribe(t);
805
+ }
806
+ subscribeTo(e, t) {
807
+ let n, i;
808
+ return typeof e == "string" && (i = e, e = mt), n = i ? new e(i, t) : new e(t), this.subscribe(n);
809
+ }
810
+ subscribe(e) {
811
+ if (!e.attached(this)) return e;
812
+ let t = e.identifier;
813
+ e.connecting();
814
+ let n = this.hub.subscriptions.get(t) || this.hub.subscriptions.create(t, {
815
+ subscribe: (i) => this._subscribe(i, e.channelId, e.params),
816
+ unsubscribe: (i) => this._unsubscribe(i)
817
+ });
818
+ return n.add(e), n.intent === "subscribed" && n.state === "connected" && e.connected(), n.ensureSubscribed(), e;
819
+ }
820
+ async _resubscribe(e) {
821
+ e.intent !== "subscribed" || !e.channels[0] || (e.notify("connecting"), e.ensureResubscribed());
822
+ }
823
+ async _subscribe(e, t, n) {
824
+ let i = e.id;
825
+ if (this.state === "idle" && this.connect().catch(() => {
826
+ }), this.state !== "connected") {
827
+ this.logger.debug("cancel subscribe, no connection", { identifier: i });
828
+ return;
829
+ }
830
+ this.logger.debug("acquiring subscribe lock", { identifier: i });
831
+ let r = await e.acquire("subscribed");
832
+ if (r.canceled) {
833
+ this.logger.debug("subscribe lock has been canceled", { identifier: i }), r.release();
834
+ return;
835
+ }
836
+ if (this.logger.debug("subscribe lock has been acquired", { identifier: i }), e.intent !== "subscribed") {
837
+ this.logger.debug("cancel subscribe request, already unsubscribed"), r.release();
838
+ return;
839
+ }
840
+ if (this.state !== "connected") {
841
+ this.logger.debug("cancel subscribe, no connection", { identifier: i }), r.release();
842
+ return;
843
+ }
844
+ if (e.state === "connected") {
845
+ this.logger.debug("already connected, skip subscribe command", {
846
+ identifier: i
847
+ }), e.notify("connected"), r.release();
848
+ return;
849
+ }
850
+ let o = {
851
+ identifier: t,
852
+ params: n
853
+ };
854
+ this.logger.debug("subscribing", o);
855
+ try {
856
+ let c = await this.protocol.subscribe(t, n);
857
+ this.hub.subscribe(i, c), this.logger.debug("subscribed", { ...o, remoteId: c }), e.notify("connected");
858
+ } catch (c) {
859
+ if (c) {
860
+ if (c instanceof ht && this.logger.warn("rejected", o), c instanceof A) {
861
+ this.logger.debug(
862
+ "disconnected during subscription; will retry on connect",
863
+ o
864
+ ), r.release();
865
+ return;
866
+ }
867
+ this.logger.error("failed to subscribe", {
868
+ error: c,
869
+ ...o
870
+ });
871
+ }
872
+ e.close(c), this.hub.unsubscribe(i);
873
+ }
874
+ r.release();
875
+ }
876
+ unsubscribe(e) {
877
+ let t = e.identifier, n = this.hub.subscriptions.get(t);
878
+ if (!n)
879
+ throw Error(`Subscription not found: ${t}`);
880
+ n.remove(e), e.closed(), n.maybeUnsubscribe();
881
+ }
882
+ async _unsubscribe(e) {
883
+ let t = e.id;
884
+ this.logger.debug("acquiring unsubscribe lock", { identifier: t });
885
+ let n = await e.acquire("unsubscribed");
886
+ if (n.canceled) {
887
+ this.logger.debug("unsubscribe lock has been canceled", { identifier: t }), n.release();
888
+ return;
889
+ }
890
+ if (this.logger.debug("unsubscribe lock has been acquired", { identifier: t }), e.intent !== "unsubscribed") {
891
+ this.logger.debug("cancel unsubscribe, no longer needed", {
892
+ identifier: t,
893
+ intent: e.intent
894
+ }), n.release();
895
+ return;
896
+ }
897
+ if (e.state === "disconnected" || e.state === "closed") {
898
+ this.logger.debug(
899
+ `already ${e.state} connected, skip unsubscribe command`,
900
+ { identifier: t }
901
+ ), n.release();
902
+ return;
903
+ }
904
+ let i = e.remoteId;
905
+ if (this.logger.debug("unsubscribing...", { remoteId: i }), this.state !== "connected") {
906
+ this.logger.debug("unsubscribe skipped (cable is not connected)", {
907
+ id: t
908
+ }), e.close(), this.hub.unsubscribe(t), n.release();
909
+ return;
910
+ }
911
+ try {
912
+ await this.protocol.unsubscribe(i), this.logger.debug("unsubscribed remotely", { id: t });
913
+ } catch (r) {
914
+ r && (r instanceof A ? this.logger.debug(
915
+ "cable disconnected during the unsubscribe command execution",
916
+ { id: t, error: r }
917
+ ) : this.logger.error("unsubscribe failed", {
918
+ id: t,
919
+ error: r
920
+ }));
921
+ }
922
+ e.intent === "unsubscribed" ? (e.close(), this.hub.unsubscribe(t)) : e.state = "closed", n.release();
923
+ }
924
+ async perform(e, t, n) {
925
+ if (this.performFailures === "throw")
926
+ return this._perform(e, t, n);
927
+ try {
928
+ return await this._perform(e, t, n);
929
+ } catch (i) {
930
+ this.performFailures === "warn" && this.logger.warn("perform failed", { error: i });
931
+ return;
932
+ }
933
+ }
934
+ async _perform(e, t, n) {
935
+ if (this.state === "connecting" && await this.pendingConnect(), this.state === "closed" || this.state === "disconnected")
936
+ throw new Ot();
937
+ let i = this.hub.subscriptions.get(e);
938
+ if (!i)
939
+ throw Error(`Subscription not found: ${e}`);
940
+ if (await i.pending("subscribed"), i.intent !== "subscribed")
941
+ throw Error(`Subscription is closed: ${e}`);
942
+ let r = i.remoteId, o = {
943
+ id: r,
944
+ action: t,
945
+ payload: n
946
+ };
947
+ this.logger.debug("perform", o);
948
+ try {
949
+ let c = await this.protocol.perform(r, t, n);
950
+ return c && this.logger.debug("perform result", {
951
+ message: c,
952
+ request: o
953
+ }), c;
954
+ } catch (c) {
955
+ throw this.logger.error("perform failed", {
956
+ error: c,
957
+ request: o
958
+ }), c;
959
+ }
960
+ }
961
+ on(e, t) {
962
+ return this.emitter.on(e, t);
963
+ }
964
+ once(e, t) {
965
+ let n = this.emitter.on(e, (...i) => {
966
+ n(), t(...i);
967
+ });
968
+ return n;
969
+ }
970
+ emit(e, ...t) {
971
+ return this.emitter.emit(e, ...t);
972
+ }
973
+ pendingConnect() {
974
+ return this._pendingConnect ? this._pendingConnect : (this._pendingConnect = new Promise((e, t) => {
975
+ let n = [() => delete this._pendingConnect];
976
+ n.push(
977
+ this.on("connect", () => {
978
+ n.forEach((i) => i()), e();
979
+ })
980
+ ), n.push(
981
+ this.on("close", (i) => {
982
+ n.forEach((r) => r()), t(i);
983
+ })
984
+ ), n.push(
985
+ this.on("disconnect", (i) => {
986
+ n.forEach((r) => r()), t(i);
987
+ })
988
+ );
989
+ }), this._pendingConnect);
990
+ }
991
+ }
992
+ const Qt = {
993
+ maxMissingPings: 2,
994
+ maxReconnectAttempts: 1 / 0
995
+ }, x = () => Date.now(), bt = (s, e) => {
996
+ e = e || {};
997
+ let { backoffRate: t, jitterRatio: n, maxInterval: i } = e;
998
+ return t = t || 2, n === void 0 && (n = 0.5), (r) => {
999
+ let o = s * t ** r, c = o * t, a = o + (c - o) * Math.random(), u = 2 * (Math.random() - 0.5) * n;
1000
+ return a = a * (1 + u), i && i < a && (a = i), a;
1001
+ };
1002
+ };
1003
+ let yt = class {
1004
+ constructor({ pingInterval: e, ...t }) {
1005
+ if (this.pingInterval = e, !this.pingInterval)
1006
+ throw Error(`Incorrect pingInterval is provided: ${e}`);
1007
+ if (t = Object.assign({}, Qt, t), this.strategy = t.reconnectStrategy, !this.strategy)
1008
+ throw Error("Reconnect strategy must be provided");
1009
+ this.maxMissingPings = t.maxMissingPings, this.maxReconnectAttempts = t.maxReconnectAttempts, this.logger = t.logger || new H(), this.state = "pending_connect", this.attempts = 0, this.disconnectedAt = x();
1010
+ }
1011
+ watch(e) {
1012
+ this.target = e, this.initListeners();
1013
+ }
1014
+ reconnectNow() {
1015
+ return this.state === "connected" || this.state === "pending_connect" || this.state === "closed" ? !1 : (this.cancelReconnect(), this.state = "pending_connect", this.target.connect().catch((e) => {
1016
+ this.logger.info("Failed at reconnecting: " + e);
1017
+ }), !0);
1018
+ }
1019
+ initListeners() {
1020
+ this.unbind = [], this.unbind.push(
1021
+ this.target.on("connect", () => {
1022
+ this.attempts = 0, this.pingedAt = x(), this.state = "connected", this.cancelReconnect(), this.startPolling();
1023
+ })
1024
+ ), this.unbind.push(
1025
+ this.target.on("disconnect", () => {
1026
+ this.disconnectedAt = x(), this.state = "disconnected", this.stopPolling(), this.scheduleReconnect();
1027
+ })
1028
+ ), this.unbind.push(
1029
+ this.target.on("close", () => {
1030
+ this.disconnectedAt = x(), this.state = "closed", this.cancelReconnect(), this.stopPolling();
1031
+ })
1032
+ ), this.unbind.push(
1033
+ this.target.on("keepalive", () => {
1034
+ this.pingedAt = x();
1035
+ })
1036
+ ), this.unbind.push(() => {
1037
+ this.cancelReconnect(), this.stopPolling();
1038
+ });
1039
+ }
1040
+ dispose() {
1041
+ delete this.target, this.unbind && this.unbind.forEach((e) => e()), delete this.unbind;
1042
+ }
1043
+ startPolling() {
1044
+ this.pollId && clearTimeout(this.pollId);
1045
+ let e = this.pingInterval + (Math.random() - 0.5) * this.pingInterval * 0.5;
1046
+ this.pollId = setTimeout(() => {
1047
+ this.checkStale(), this.state === "connected" && this.startPolling();
1048
+ }, e);
1049
+ }
1050
+ stopPolling() {
1051
+ this.pollId && clearTimeout(this.pollId);
1052
+ }
1053
+ checkStale() {
1054
+ let e = x() - this.pingedAt;
1055
+ e > this.maxMissingPings * this.pingInterval && (this.logger.warn(`Stale connection: ${e}ms without pings`), this.state = "pending_disconnect", this.target.disconnected(new At()));
1056
+ }
1057
+ scheduleReconnect() {
1058
+ if (this.attempts >= this.maxReconnectAttempts) {
1059
+ this.target.close();
1060
+ return;
1061
+ }
1062
+ let e = this.strategy(this.attempts);
1063
+ this.attempts++, this.logger.info(`Reconnecting in ${e}ms (${this.attempts} attempt)`), this.state = "pending_reconnect", this.reconnnectId = setTimeout(() => this.reconnectNow(), e);
1064
+ }
1065
+ cancelReconnect() {
1066
+ this.reconnnectId && (clearTimeout(this.reconnnectId), delete this.reconnnectId);
1067
+ }
1068
+ };
1069
+ class Gt {
1070
+ constructor(e, t = {}) {
1071
+ this.transports = e, this.transport = null, this.emitter = $(), this.unbind = [], this.logger = t.logger || new H();
1072
+ }
1073
+ displayName() {
1074
+ return "fallbacked transport";
1075
+ }
1076
+ async open() {
1077
+ for (let e = 0; e < this.transports.length; e++) {
1078
+ let t = this.transports[e];
1079
+ try {
1080
+ this.transport = t, this.resetListeners(), this.logger.debug(`Trying to connect via ${t.displayName()}`), await t.open(), this.logger.debug(`Connected via ${t.displayName()}`);
1081
+ return;
1082
+ } catch (n) {
1083
+ this.logger.debug(
1084
+ `Failed to connect via ${t.displayName()}: ${n.message}`
1085
+ );
1086
+ }
1087
+ }
1088
+ throw this.transport = null, this.resetListeners(), new Error("Couldn't connect via any available transport");
1089
+ }
1090
+ send(e) {
1091
+ if (!this.transport)
1092
+ throw new Error("No transport is open");
1093
+ this.transport.send(e);
1094
+ }
1095
+ async close() {
1096
+ if (!this.transport)
1097
+ throw new Error("No transport is open");
1098
+ await this.transport.close(), this.transport = null;
1099
+ }
1100
+ setURL() {
1101
+ throw new Error("Not implemented. Set URL for each transport separately");
1102
+ }
1103
+ setParam(e, t) {
1104
+ this.transports.forEach((n) => {
1105
+ n.setParam(e, t);
1106
+ });
1107
+ }
1108
+ setToken(e, t) {
1109
+ this.transports.forEach((n) => {
1110
+ n.setToken(e, t);
1111
+ });
1112
+ }
1113
+ on(e, t) {
1114
+ return this.emitter.on(e, t);
1115
+ }
1116
+ once(e, t) {
1117
+ let n = this.emitter.on(e, (...i) => {
1118
+ n(), t(...i);
1119
+ });
1120
+ return n;
1121
+ }
1122
+ get url() {
1123
+ return this.transport ? this.transport.url : "";
1124
+ }
1125
+ resetListeners() {
1126
+ this.unbind.forEach((e) => e()), this.unbind.length = 0, this.transport && this.unbind.push(
1127
+ this.transport.on("open", () => {
1128
+ this.emitter.emit("open");
1129
+ }),
1130
+ this.transport.on("data", (e) => {
1131
+ this.emitter.emit("data", e);
1132
+ }),
1133
+ this.transport.on("close", (e) => {
1134
+ this.emitter.emit("close", e);
1135
+ }),
1136
+ this.transport.on("error", (e) => {
1137
+ this.emitter.emit("error", e);
1138
+ })
1139
+ );
1140
+ }
1141
+ }
1142
+ class Vt {
1143
+ constructor(e, t = {}) {
1144
+ this.url = e;
1145
+ let n = t.websocketImplementation;
1146
+ if (n)
1147
+ this.Impl = n;
1148
+ else if (typeof WebSocket < "u")
1149
+ this.Impl = WebSocket;
1150
+ else
1151
+ throw new Error("No WebSocket support");
1152
+ this.connected = !1, this.emitter = $();
1153
+ let { format: i, subprotocol: r, authStrategy: o } = t;
1154
+ this.format = i || "text", this.connectionOptions = t.websocketOptions, this.authStrategy = o || "param", this.authProtocol = "", this.subprotocol = r;
1155
+ }
1156
+ displayName() {
1157
+ return "WebSocket(" + this.url + ")";
1158
+ }
1159
+ open() {
1160
+ let e = this.subprotocol;
1161
+ return this.authStrategy === "sub-protocol" && (e = [this.subprotocol, this.authProtocol]), this.connectionOptions ? this.ws = new this.Impl(this.url, e, this.connectionOptions) : this.ws = new this.Impl(this.url, e), this.ws.binaryType = "arraybuffer", this.initListeners(), new Promise((t, n) => {
1162
+ let i = [];
1163
+ i.push(
1164
+ this.once("open", () => {
1165
+ i.forEach((r) => r()), t();
1166
+ })
1167
+ ), i.push(
1168
+ this.once("close", () => {
1169
+ i.forEach((r) => r()), n(Error("WS connection closed"));
1170
+ })
1171
+ );
1172
+ });
1173
+ }
1174
+ setURL(e) {
1175
+ this.url = e;
1176
+ }
1177
+ setParam(e, t) {
1178
+ let n = new URL(this.url);
1179
+ n.searchParams.set(e, t);
1180
+ let i = `${n.protocol}//${n.host}${n.pathname}?${n.searchParams}`;
1181
+ this.setURL(i);
1182
+ }
1183
+ setToken(e, t = "jid") {
1184
+ if (this.authStrategy === "param")
1185
+ this.setParam(t, e);
1186
+ else if (this.authStrategy === "header") {
1187
+ this.connectionOptions = this.connectionOptions || {}, this.connectionOptions.headers = this.connectionOptions.headers || {};
1188
+ let n = `x-${t}`.toLowerCase();
1189
+ n = Object.keys(this.connectionOptions.headers).find(
1190
+ (r) => r.toLowerCase() === n
1191
+ ) || n, this.connectionOptions.headers[n] = e;
1192
+ } else if (this.authStrategy === "sub-protocol")
1193
+ this.authProtocol = `anycable-token.${e}`;
1194
+ else
1195
+ throw new Error("Unknown auth strategy: " + this.authStrategy);
1196
+ }
1197
+ send(e) {
1198
+ if (!this.ws || !this.connected)
1199
+ throw Error("WebSocket is not connected");
1200
+ this.ws.send(e);
1201
+ }
1202
+ close() {
1203
+ this.ws ? this.onclose() : this.connected = !1;
1204
+ }
1205
+ on(e, t) {
1206
+ return this.emitter.on(e, t);
1207
+ }
1208
+ once(e, t) {
1209
+ let n = this.emitter.on(e, (...i) => {
1210
+ n(), t(...i);
1211
+ });
1212
+ return n;
1213
+ }
1214
+ initListeners() {
1215
+ this.ws.onerror = (e) => {
1216
+ this.connected && this.emitter.emit("error", e.error || new Error("WS Error"));
1217
+ }, this.ws.onclose = () => {
1218
+ this.onclose();
1219
+ }, this.ws.onmessage = (e) => {
1220
+ let t = e.data;
1221
+ this.format === "binary" && (t = new Uint8Array(t)), this.emitter.emit("data", t);
1222
+ }, this.ws.onopen = () => {
1223
+ this.connected = !0, this.emitter.emit("open");
1224
+ };
1225
+ }
1226
+ onclose() {
1227
+ this.ws.onclose = void 0, this.ws.onmessage = void 0, this.ws.onopen = void 0, this.ws.close(), delete this.ws, this.connected = !1, this.emitter.emit("close");
1228
+ }
1229
+ }
1230
+ const wt = {
1231
+ protocol: "actioncable-v1-json",
1232
+ pingInterval: 3e3,
1233
+ maxReconnectAttempts: 1 / 0,
1234
+ maxMissingPings: 2,
1235
+ logLevel: "warn",
1236
+ lazy: !0
1237
+ };
1238
+ function Jt(s, e) {
1239
+ if (typeof s == "object" && typeof e > "u" && (e = s, s = void 0), e = e || {}, !s && !e.transport) throw Error("URL or transport must be specified");
1240
+ e = Object.assign({}, wt, e);
1241
+ let {
1242
+ protocol: t,
1243
+ websocketImplementation: n,
1244
+ websocketFormat: i,
1245
+ websocketOptions: r,
1246
+ websocketAuthStrategy: o,
1247
+ fallbacks: c,
1248
+ logLevel: a,
1249
+ logger: u,
1250
+ transport: l,
1251
+ encoder: d,
1252
+ lazy: f,
1253
+ monitor: h,
1254
+ pingInterval: E,
1255
+ reconnectStrategy: b,
1256
+ maxMissingPings: T,
1257
+ maxReconnectAttempts: w,
1258
+ subprotocol: P,
1259
+ tokenRefresher: _,
1260
+ historyTimestamp: v,
1261
+ protocolOptions: N,
1262
+ concurrentSubscribes: p,
1263
+ performFailures: I,
1264
+ transportConfigurator: C,
1265
+ auth: g
1266
+ } = e;
1267
+ if (u = u || new H(a), typeof t == "string") {
1268
+ P = P || t;
1269
+ let S = t.substring(0, t.lastIndexOf("-")), y = t.substring(t.lastIndexOf("-") + 1);
1270
+ if (N = N || {}, S === "actioncable-v1")
1271
+ t = new pt({ logger: u, ...N });
1272
+ else if (S === "actioncable-v1-ext")
1273
+ t = new Ft({
1274
+ logger: u,
1275
+ historyTimestamp: v,
1276
+ ...N
1277
+ });
1278
+ else
1279
+ throw Error(`Protocol is not supported yet: ${t}`);
1280
+ if (y === "json")
1281
+ d = d || new Ut(), i = i || "text";
1282
+ else if (y === "msgpack") {
1283
+ if (i = "binary", !d)
1284
+ throw Error(
1285
+ "Msgpack encoder must be specified explicitly. Use `@anycable/msgpack-encoder` package or build your own"
1286
+ );
1287
+ } else if (y === "protobuf") {
1288
+ if (i = i || "binary", !d)
1289
+ throw Error(
1290
+ "Protobuf encoder must be specified explicitly. Use `@anycable/protobuf-encoder` package or build your own"
1291
+ );
1292
+ } else
1293
+ throw Error(`Protocol is not supported yet: ${t}`);
1294
+ }
1295
+ if (!t) throw Error("Protocol must be specified");
1296
+ l = l || new Vt(s, {
1297
+ websocketImplementation: n,
1298
+ websocketOptions: r,
1299
+ subprotocol: P,
1300
+ authStrategy: o,
1301
+ format: i
1302
+ }), c && (l = new Gt([l, ...c], { logger: u })), g && g.token && l.setToken(g.token, g.param || "jid"), b = b || bt(E), h !== !1 && (h = h || new yt({
1303
+ pingInterval: E,
1304
+ reconnectStrategy: b,
1305
+ maxMissingPings: T,
1306
+ maxReconnectAttempts: w,
1307
+ logger: u
1308
+ }));
1309
+ let q = { concurrentSubscribes: p }, m = new xt({
1310
+ protocol: t,
1311
+ transport: l,
1312
+ encoder: d,
1313
+ logger: u,
1314
+ lazy: f,
1315
+ hubOptions: q,
1316
+ performFailures: I,
1317
+ transportConfigurator: C
1318
+ });
1319
+ return h && (h.watch(m), m.monitor = h), _ && Ht(m, async () => {
1320
+ try {
1321
+ await _(l);
1322
+ } catch (S) {
1323
+ return u.error("Failed to refresh authentication token: " + S), !1;
1324
+ }
1325
+ return m.connect().catch(() => {
1326
+ }), !0;
1327
+ }), m;
1328
+ }
1329
+ function Ht(s, e) {
1330
+ let t = !1;
1331
+ s.on("connect", () => t = !1), s.on("close", async (n) => {
1332
+ if (n) {
1333
+ if (t) {
1334
+ s.logger.warn("Token auto-refresh is disabled", n);
1335
+ return;
1336
+ }
1337
+ n.reason === "token_expired" && (t = !0, await e());
1338
+ }
1339
+ });
1340
+ }
1341
+ class Kt extends gt {
1342
+ writeLogEntry(e, t, n) {
1343
+ n ? console[e](t, n) : console[e](t);
1344
+ }
1345
+ }
1346
+ class Yt extends yt {
1347
+ watch(e) {
1348
+ super.watch(e), this.initActivityListeners();
1349
+ }
1350
+ initActivityListeners() {
1351
+ if (typeof document < "u" && typeof window < "u" && document.addEventListener && window.addEventListener) {
1352
+ let e = () => {
1353
+ document.hidden || this.reconnectNow() && this.logger.debug("Trigger reconnect due to visibility change");
1354
+ }, t = (i) => {
1355
+ this.reconnectNow() && this.logger.debug("Trigger reconnect", { event: i });
1356
+ }, n = () => this.disconnect(new A("page_frozen"));
1357
+ document.addEventListener("visibilitychange", e, !1), window.addEventListener("focus", t, !1), window.addEventListener("online", t, !1), window.addEventListener("resume", t, !1), window.addEventListener("freeze", n, !1), this.unbind.push(() => {
1358
+ document.removeEventListener("visibilitychange", e, !1), window.removeEventListener("focus", t, !1), window.removeEventListener("online", t, !1), window.removeEventListener("resume", t, !1), window.removeEventListener("freeze", n, !1);
1359
+ });
1360
+ }
1361
+ }
1362
+ disconnect(e) {
1363
+ this.state === "disconnected" || this.state === "closed" || (this.logger.info("Disconnecting", { reason: e.message }), this.cancelReconnect(), this.stopPolling(), this.state = "pending_disconnect", this.target.disconnected(e));
1364
+ }
1365
+ }
1366
+ const Wt = ["cable", "action-cable"], Zt = "/cable", X = (s, e) => {
1367
+ for (let t of Wt) {
1368
+ let n = s.head.querySelector(`meta[name='${t}-${e}']`);
1369
+ if (n)
1370
+ return n.getAttribute("content");
1371
+ }
1372
+ }, ze = (s) => s.match(/wss?:\/\//) ? s : typeof window < "u" ? `${window.location.protocol.replace("http", "ws")}//${window.location.host}${s}` : s, $t = () => {
1373
+ if (typeof document < "u" && document.head) {
1374
+ let s = X(document, "url");
1375
+ if (s)
1376
+ return ze(s);
1377
+ }
1378
+ return ze(Zt);
1379
+ }, Xt = () => {
1380
+ if (typeof document < "u" && document.head) {
1381
+ let s = X(document, "history-timestamp");
1382
+ if (s)
1383
+ return s | 0;
1384
+ }
1385
+ }, en = () => {
1386
+ if (typeof document < "u" && document.head)
1387
+ return X(document, "token");
1388
+ }, tn = () => {
1389
+ if (typeof document < "u" && document.head)
1390
+ return X(document, "token-param");
1391
+ };
1392
+ function nn(s, e) {
1393
+ typeof s == "object" && typeof e > "u" && (e = s, s = void 0), s = s || $t(), e = e || {}, e.historyTimestamp || (e.historyTimestamp = Xt());
1394
+ let t = en();
1395
+ if (t) {
1396
+ let u = tn();
1397
+ e.auth = Object.assign({ token: t, param: u }, e.auth || {});
1398
+ }
1399
+ e = Object.assign({}, wt, e);
1400
+ let {
1401
+ logLevel: n,
1402
+ logger: i,
1403
+ pingInterval: r,
1404
+ reconnectStrategy: o,
1405
+ maxMissingPings: c,
1406
+ maxReconnectAttempts: a
1407
+ } = e;
1408
+ return i = e.logger = e.logger || new Kt(n), o = e.reconnectStrategy = e.reconnectStrategy || bt(r), e.monitor !== !1 && (e.monitor = e.monitor || new Yt({
1409
+ pingInterval: r,
1410
+ reconnectStrategy: o,
1411
+ maxMissingPings: c,
1412
+ maxReconnectAttempts: a,
1413
+ logger: i
1414
+ })), Jt(s, e);
1415
+ }
1416
+ const sn = {
1417
+ answer: "/.netlify/functions/quiz-answer",
1418
+ sync: "/.netlify/functions/quiz-sync"
1419
+ };
1420
+ function rn(s) {
1421
+ if (typeof s != "object" || s === null) return !1;
1422
+ const e = s;
1423
+ return typeof e.sessionId == "string" && (e.activeQuizId === null || typeof e.activeQuizId == "string") && typeof e.results == "object" && e.results !== null;
1424
+ }
1425
+ function on(s) {
1426
+ if (typeof s != "object" || s === null) return !1;
1427
+ const e = s;
1428
+ return typeof e.quizId == "string" && typeof e.answer == "string" && typeof e.sessionId == "string";
1429
+ }
1430
+ class St {
1431
+ constructor(e) {
1432
+ this.resultsChannel = null, this.activeQuizId = null, this.results = {}, this.voters = {}, this.online = 0, this.submitted = {}, this.listeners = [], this.syncTimer = null, this.syncPending = !1, this.incomingSyncTimer = null, this.incomingSyncData = null, this.role = e.role, this.quizGroupId = e.quizGroupId, this.sessionId = e.sessionId || this.getOrCreateSessionId(), this.endpoints = { ...sn, ...e.endpoints };
1433
+ const t = e.role === "participant" ? 6e4 : 3e5;
1434
+ this.cable = nn(e.wsUrl, {
1435
+ protocol: "actioncable-v1-ext-json",
1436
+ protocolOptions: {
1437
+ historyTimestamp: Math.floor((Date.now() - t) / 1e3)
1438
+ }
1439
+ }), this.syncChannel = this.cable.streamFrom(
1440
+ `quiz:${e.quizGroupId}:sync`
1441
+ ), this.syncChannel.on("message", this.onSyncMessage.bind(this));
1442
+ const n = this.syncChannel.presence;
1443
+ if (typeof n.stateFromInfo == "function") {
1444
+ const i = n.stateFromInfo.bind(n);
1445
+ n.stateFromInfo = (r) => {
1446
+ if (!(r != null && r.records)) {
1447
+ if (r && typeof r == "object") {
1448
+ const { type: o, ...c } = r;
1449
+ return c;
1450
+ }
1451
+ return {};
1452
+ }
1453
+ return i(r);
1454
+ };
1455
+ }
1456
+ this.syncChannel.on("presence", this.onPresence.bind(this)), e.role === "participant" && this.syncChannel.presence.join(this.sessionId, { id: this.sessionId }), this.syncChannel.presence.info().then((i) => {
1457
+ i && (this.online = Object.keys(i).length, this.notifyStateChange());
1458
+ }).catch(() => {
1459
+ }), e.role === "presenter" && (this.resultsChannel = this.cable.streamFrom(
1460
+ `quiz:${e.quizGroupId}:results`
1461
+ ), this.resultsChannel.on("message", this.onResultsMessage.bind(this)), this.restoreState(), this.activeQuizId && this.sendSync()), e.role === "participant" && this.restoreSubmitted();
1462
+ }
1463
+ // ── Public API ──
1464
+ subscribe(e) {
1465
+ return this.listeners.push(e), e(this.getState()), () => {
1466
+ const t = this.listeners.indexOf(e);
1467
+ t !== -1 && this.listeners.splice(t, 1);
1468
+ };
1469
+ }
1470
+ getState() {
1471
+ return {
1472
+ activeQuizId: this.activeQuizId,
1473
+ results: structuredClone(this.results),
1474
+ online: this.online,
1475
+ submitted: { ...this.submitted }
1476
+ };
1477
+ }
1478
+ getQuizState(e) {
1479
+ return this.results[e] || { votes: {}, total: 0 };
1480
+ }
1481
+ hasVoted(e) {
1482
+ return e in this.submitted;
1483
+ }
1484
+ getVotedAnswer(e) {
1485
+ return this.submitted[e] ?? null;
1486
+ }
1487
+ /** Presenter: set the active quiz (called when slide enters viewport) */
1488
+ setActiveQuiz(e) {
1489
+ this.role === "presenter" && this.activeQuizId !== e && (this.activeQuizId = e, this.saveState(), this.sendSync());
1490
+ }
1491
+ /** Participant: submit an answer */
1492
+ async submitAnswer(e, t) {
1493
+ if (this.hasVoted(e)) return !1;
1494
+ try {
1495
+ const n = await fetch(this.endpoints.answer, {
1496
+ method: "POST",
1497
+ headers: { "Content-Type": "application/json" },
1498
+ body: JSON.stringify({
1499
+ quizId: e,
1500
+ answer: t,
1501
+ sessionId: this.sessionId,
1502
+ quizGroupId: this.quizGroupId
1503
+ })
1504
+ });
1505
+ return n.ok && (this.submitted[e] = t, this.saveSubmitted(), this.notifyStateChange()), n.ok;
1506
+ } catch {
1507
+ return !1;
1508
+ }
1509
+ }
1510
+ disconnect() {
1511
+ this.role === "participant" && this.syncChannel.presence.leave(), this.cable.disconnect();
1512
+ }
1513
+ // ── Message Handlers ──
1514
+ onSyncMessage(e) {
1515
+ const t = this.parse(e);
1516
+ rn(t) && t.sessionId !== this.sessionId && this.role === "participant" && this.applySyncThrottled(t);
1517
+ }
1518
+ applySyncThrottled(e) {
1519
+ if (this.incomingSyncTimer) {
1520
+ this.incomingSyncData = e;
1521
+ return;
1522
+ }
1523
+ this.applySync(e), this.incomingSyncData = null, this.incomingSyncTimer = setTimeout(() => {
1524
+ this.incomingSyncTimer = null, this.incomingSyncData && (this.applySync(this.incomingSyncData), this.incomingSyncData = null);
1525
+ }, 200);
1526
+ }
1527
+ applySync(e) {
1528
+ var t;
1529
+ this.activeQuizId = e.activeQuizId, this.results = e.results;
1530
+ for (const n of Object.keys(this.submitted))
1531
+ (((t = e.results[n]) == null ? void 0 : t.total) ?? 0) === 0 && this.clearVotedAnswer(n);
1532
+ this.notifyStateChange();
1533
+ }
1534
+ onResultsMessage(e) {
1535
+ if (this.role !== "presenter") return;
1536
+ const t = this.parse(e);
1537
+ if (!on(t) || t.sessionId === this.sessionId) return;
1538
+ const { quizId: n, answer: i, sessionId: r } = t;
1539
+ this.voters[n] || (this.voters[n] = /* @__PURE__ */ new Set()), !this.voters[n].has(r) && (this.voters[n].add(r), this.results[n] || (this.results[n] = { votes: {}, total: 0 }), this.results[n].votes[i] = (this.results[n].votes[i] || 0) + 1, this.results[n].total += 1, this.saveState(), this.notifyStateChange(), this.sendSyncThrottled());
1540
+ }
1541
+ async onPresence() {
1542
+ try {
1543
+ const e = await this.syncChannel.presence.info();
1544
+ e && (this.online = Object.keys(e).length, this.notifyStateChange(), this.role === "presenter" && this.activeQuizId && this.sendSyncThrottled());
1545
+ } catch {
1546
+ }
1547
+ }
1548
+ // ── Sync Broadcasting ──
1549
+ sendSyncThrottled() {
1550
+ if (this.syncTimer) {
1551
+ this.syncPending = !0;
1552
+ return;
1553
+ }
1554
+ this.sendSync(), this.syncTimer = setTimeout(() => {
1555
+ this.syncTimer = null, this.syncPending && (this.syncPending = !1, this.sendSync());
1556
+ }, 200);
1557
+ }
1558
+ async sendSync() {
1559
+ if (this.role === "presenter")
1560
+ try {
1561
+ await fetch(this.endpoints.sync, {
1562
+ method: "POST",
1563
+ headers: { "Content-Type": "application/json" },
1564
+ body: JSON.stringify({
1565
+ activeQuizId: this.activeQuizId,
1566
+ sessionId: this.sessionId,
1567
+ quizGroupId: this.quizGroupId,
1568
+ results: this.results
1569
+ })
1570
+ });
1571
+ } catch {
1572
+ }
1573
+ }
1574
+ // ── Persistence ──
1575
+ getOrCreateSessionId() {
1576
+ const e = `quiz-session-${this.quizGroupId}`;
1577
+ let t = sessionStorage.getItem(e);
1578
+ return t || (t = crypto.randomUUID(), sessionStorage.setItem(e, t)), t;
1579
+ }
1580
+ saveState() {
1581
+ if (this.role === "presenter")
1582
+ try {
1583
+ sessionStorage.setItem(
1584
+ `quiz-presenter-${this.quizGroupId}`,
1585
+ JSON.stringify({
1586
+ activeQuizId: this.activeQuizId,
1587
+ results: this.results,
1588
+ voters: Object.fromEntries(
1589
+ Object.entries(this.voters).map(([e, t]) => [e, [...t]])
1590
+ )
1591
+ })
1592
+ );
1593
+ } catch (e) {
1594
+ console.warn("[QuizManager] saveState failed:", e);
1595
+ }
1596
+ }
1597
+ restoreState() {
1598
+ try {
1599
+ const e = sessionStorage.getItem(
1600
+ `quiz-presenter-${this.quizGroupId}`
1601
+ );
1602
+ if (!e) return;
1603
+ const t = JSON.parse(e);
1604
+ if (t.activeQuizId && (this.activeQuizId = t.activeQuizId), t.results && (this.results = t.results), t.voters)
1605
+ for (const [n, i] of Object.entries(t.voters))
1606
+ this.voters[n] = new Set(i);
1607
+ } catch {
1608
+ }
1609
+ }
1610
+ saveSubmitted() {
1611
+ try {
1612
+ sessionStorage.setItem(
1613
+ `quiz-submitted-${this.quizGroupId}`,
1614
+ JSON.stringify(this.submitted)
1615
+ );
1616
+ } catch {
1617
+ }
1618
+ }
1619
+ restoreSubmitted() {
1620
+ try {
1621
+ const e = sessionStorage.getItem(
1622
+ `quiz-submitted-${this.quizGroupId}`
1623
+ );
1624
+ if (!e) return;
1625
+ this.submitted = JSON.parse(e);
1626
+ } catch {
1627
+ }
1628
+ }
1629
+ clearVotedAnswer(e) {
1630
+ delete this.submitted[e], this.saveSubmitted();
1631
+ }
1632
+ // ── Helpers ──
1633
+ notifyStateChange() {
1634
+ const e = this.getState();
1635
+ for (const t of this.listeners) t(e);
1636
+ }
1637
+ parse(e) {
1638
+ if (typeof e == "string")
1639
+ try {
1640
+ return JSON.parse(e);
1641
+ } catch {
1642
+ return {};
1643
+ }
1644
+ return e && typeof e == "object" ? e : {};
1645
+ }
1646
+ }
1647
+ const W = /* @__PURE__ */ new Map();
1648
+ function cn(s) {
1649
+ return W.has(s.quizGroupId) || W.set(
1650
+ s.quizGroupId,
1651
+ new St({ ...s, role: "presenter" })
1652
+ ), W.get(s.quizGroupId);
1653
+ }
1654
+ function an(s) {
1655
+ W.delete(s);
1656
+ }
1657
+ const Z = /* @__PURE__ */ new Map();
1658
+ function On(s) {
1659
+ return Z.has(s.quizGroupId) || Z.set(
1660
+ s.quizGroupId,
1661
+ new St({ ...s, role: "participant" })
1662
+ ), Z.get(s.quizGroupId);
1663
+ }
1664
+ function jn(s) {
1665
+ Z.delete(s);
1666
+ }
1667
+ function Le(s, e) {
1668
+ if (window.matchMedia(
1669
+ "(prefers-reduced-motion: reduce)"
1670
+ ).matches) {
1671
+ s.textContent = String(e);
1672
+ return;
1673
+ }
1674
+ const n = parseInt(s.textContent || "0", 10);
1675
+ if (n === e) return;
1676
+ const i = 300, r = performance.now(), o = n;
1677
+ function c(a) {
1678
+ const u = a - r, l = Math.min(u / i, 1), d = 1 - Math.pow(1 - l, 3), f = Math.round(o + (e - o) * d);
1679
+ s.textContent = String(f), l < 1 && requestAnimationFrame(c);
1680
+ }
1681
+ requestAnimationFrame(c);
1682
+ }
1683
+ function un(s) {
1684
+ return s && s.__esModule && Object.prototype.hasOwnProperty.call(s, "default") ? s.default : s;
1685
+ }
1686
+ var Q = {}, re, Ue;
1687
+ function ln() {
1688
+ return Ue || (Ue = 1, re = function() {
1689
+ return typeof Promise == "function" && Promise.prototype && Promise.prototype.then;
1690
+ }), re;
1691
+ }
1692
+ var oe = {}, L = {}, De;
1693
+ function F() {
1694
+ if (De) return L;
1695
+ De = 1;
1696
+ let s;
1697
+ const e = [
1698
+ 0,
1699
+ // Not used
1700
+ 26,
1701
+ 44,
1702
+ 70,
1703
+ 100,
1704
+ 134,
1705
+ 172,
1706
+ 196,
1707
+ 242,
1708
+ 292,
1709
+ 346,
1710
+ 404,
1711
+ 466,
1712
+ 532,
1713
+ 581,
1714
+ 655,
1715
+ 733,
1716
+ 815,
1717
+ 901,
1718
+ 991,
1719
+ 1085,
1720
+ 1156,
1721
+ 1258,
1722
+ 1364,
1723
+ 1474,
1724
+ 1588,
1725
+ 1706,
1726
+ 1828,
1727
+ 1921,
1728
+ 2051,
1729
+ 2185,
1730
+ 2323,
1731
+ 2465,
1732
+ 2611,
1733
+ 2761,
1734
+ 2876,
1735
+ 3034,
1736
+ 3196,
1737
+ 3362,
1738
+ 3532,
1739
+ 3706
1740
+ ];
1741
+ return L.getSymbolSize = function(n) {
1742
+ if (!n) throw new Error('"version" cannot be null or undefined');
1743
+ if (n < 1 || n > 40) throw new Error('"version" should be in range from 1 to 40');
1744
+ return n * 4 + 17;
1745
+ }, L.getSymbolTotalCodewords = function(n) {
1746
+ return e[n];
1747
+ }, L.getBCHDigit = function(t) {
1748
+ let n = 0;
1749
+ for (; t !== 0; )
1750
+ n++, t >>>= 1;
1751
+ return n;
1752
+ }, L.setToSJISFunction = function(n) {
1753
+ if (typeof n != "function")
1754
+ throw new Error('"toSJISFunc" is not a valid function.');
1755
+ s = n;
1756
+ }, L.isKanjiModeEnabled = function() {
1757
+ return typeof s < "u";
1758
+ }, L.toSJIS = function(n) {
1759
+ return s(n);
1760
+ }, L;
1761
+ }
1762
+ var ce = {}, Fe;
1763
+ function Te() {
1764
+ return Fe || (Fe = 1, (function(s) {
1765
+ s.L = { bit: 1 }, s.M = { bit: 0 }, s.Q = { bit: 3 }, s.H = { bit: 2 };
1766
+ function e(t) {
1767
+ if (typeof t != "string")
1768
+ throw new Error("Param is not a string");
1769
+ switch (t.toLowerCase()) {
1770
+ case "l":
1771
+ case "low":
1772
+ return s.L;
1773
+ case "m":
1774
+ case "medium":
1775
+ return s.M;
1776
+ case "q":
1777
+ case "quartile":
1778
+ return s.Q;
1779
+ case "h":
1780
+ case "high":
1781
+ return s.H;
1782
+ default:
1783
+ throw new Error("Unknown EC Level: " + t);
1784
+ }
1785
+ }
1786
+ s.isValid = function(n) {
1787
+ return n && typeof n.bit < "u" && n.bit >= 0 && n.bit < 4;
1788
+ }, s.from = function(n, i) {
1789
+ if (s.isValid(n))
1790
+ return n;
1791
+ try {
1792
+ return e(n);
1793
+ } catch {
1794
+ return i;
1795
+ }
1796
+ };
1797
+ })(ce)), ce;
1798
+ }
1799
+ var ae, Oe;
1800
+ function hn() {
1801
+ if (Oe) return ae;
1802
+ Oe = 1;
1803
+ function s() {
1804
+ this.buffer = [], this.length = 0;
1805
+ }
1806
+ return s.prototype = {
1807
+ get: function(e) {
1808
+ const t = Math.floor(e / 8);
1809
+ return (this.buffer[t] >>> 7 - e % 8 & 1) === 1;
1810
+ },
1811
+ put: function(e, t) {
1812
+ for (let n = 0; n < t; n++)
1813
+ this.putBit((e >>> t - n - 1 & 1) === 1);
1814
+ },
1815
+ getLengthInBits: function() {
1816
+ return this.length;
1817
+ },
1818
+ putBit: function(e) {
1819
+ const t = Math.floor(this.length / 8);
1820
+ this.buffer.length <= t && this.buffer.push(0), e && (this.buffer[t] |= 128 >>> this.length % 8), this.length++;
1821
+ }
1822
+ }, ae = s, ae;
1823
+ }
1824
+ var ue, je;
1825
+ function dn() {
1826
+ if (je) return ue;
1827
+ je = 1;
1828
+ function s(e) {
1829
+ if (!e || e < 1)
1830
+ throw new Error("BitMatrix size must be defined and greater than 0");
1831
+ this.size = e, this.data = new Uint8Array(e * e), this.reservedBit = new Uint8Array(e * e);
1832
+ }
1833
+ return s.prototype.set = function(e, t, n, i) {
1834
+ const r = e * this.size + t;
1835
+ this.data[r] = n, i && (this.reservedBit[r] = !0);
1836
+ }, s.prototype.get = function(e, t) {
1837
+ return this.data[e * this.size + t];
1838
+ }, s.prototype.xor = function(e, t, n) {
1839
+ this.data[e * this.size + t] ^= n;
1840
+ }, s.prototype.isReserved = function(e, t) {
1841
+ return this.reservedBit[e * this.size + t];
1842
+ }, ue = s, ue;
1843
+ }
1844
+ var le = {}, xe;
1845
+ function fn() {
1846
+ return xe || (xe = 1, (function(s) {
1847
+ const e = F().getSymbolSize;
1848
+ s.getRowColCoords = function(n) {
1849
+ if (n === 1) return [];
1850
+ const i = Math.floor(n / 7) + 2, r = e(n), o = r === 145 ? 26 : Math.ceil((r - 13) / (2 * i - 2)) * 2, c = [r - 7];
1851
+ for (let a = 1; a < i - 1; a++)
1852
+ c[a] = c[a - 1] - o;
1853
+ return c.push(6), c.reverse();
1854
+ }, s.getPositions = function(n) {
1855
+ const i = [], r = s.getRowColCoords(n), o = r.length;
1856
+ for (let c = 0; c < o; c++)
1857
+ for (let a = 0; a < o; a++)
1858
+ c === 0 && a === 0 || // top-left
1859
+ c === 0 && a === o - 1 || // bottom-left
1860
+ c === o - 1 && a === 0 || i.push([r[c], r[a]]);
1861
+ return i;
1862
+ };
1863
+ })(le)), le;
1864
+ }
1865
+ var he = {}, Qe;
1866
+ function gn() {
1867
+ if (Qe) return he;
1868
+ Qe = 1;
1869
+ const s = F().getSymbolSize, e = 7;
1870
+ return he.getPositions = function(n) {
1871
+ const i = s(n);
1872
+ return [
1873
+ // top-left
1874
+ [0, 0],
1875
+ // top-right
1876
+ [i - e, 0],
1877
+ // bottom-left
1878
+ [0, i - e]
1879
+ ];
1880
+ }, he;
1881
+ }
1882
+ var de = {}, Ge;
1883
+ function pn() {
1884
+ return Ge || (Ge = 1, (function(s) {
1885
+ s.Patterns = {
1886
+ PATTERN000: 0,
1887
+ PATTERN001: 1,
1888
+ PATTERN010: 2,
1889
+ PATTERN011: 3,
1890
+ PATTERN100: 4,
1891
+ PATTERN101: 5,
1892
+ PATTERN110: 6,
1893
+ PATTERN111: 7
1894
+ };
1895
+ const e = {
1896
+ N1: 3,
1897
+ N2: 3,
1898
+ N3: 40,
1899
+ N4: 10
1900
+ };
1901
+ s.isValid = function(i) {
1902
+ return i != null && i !== "" && !isNaN(i) && i >= 0 && i <= 7;
1903
+ }, s.from = function(i) {
1904
+ return s.isValid(i) ? parseInt(i, 10) : void 0;
1905
+ }, s.getPenaltyN1 = function(i) {
1906
+ const r = i.size;
1907
+ let o = 0, c = 0, a = 0, u = null, l = null;
1908
+ for (let d = 0; d < r; d++) {
1909
+ c = a = 0, u = l = null;
1910
+ for (let f = 0; f < r; f++) {
1911
+ let h = i.get(d, f);
1912
+ h === u ? c++ : (c >= 5 && (o += e.N1 + (c - 5)), u = h, c = 1), h = i.get(f, d), h === l ? a++ : (a >= 5 && (o += e.N1 + (a - 5)), l = h, a = 1);
1913
+ }
1914
+ c >= 5 && (o += e.N1 + (c - 5)), a >= 5 && (o += e.N1 + (a - 5));
1915
+ }
1916
+ return o;
1917
+ }, s.getPenaltyN2 = function(i) {
1918
+ const r = i.size;
1919
+ let o = 0;
1920
+ for (let c = 0; c < r - 1; c++)
1921
+ for (let a = 0; a < r - 1; a++) {
1922
+ const u = i.get(c, a) + i.get(c, a + 1) + i.get(c + 1, a) + i.get(c + 1, a + 1);
1923
+ (u === 4 || u === 0) && o++;
1924
+ }
1925
+ return o * e.N2;
1926
+ }, s.getPenaltyN3 = function(i) {
1927
+ const r = i.size;
1928
+ let o = 0, c = 0, a = 0;
1929
+ for (let u = 0; u < r; u++) {
1930
+ c = a = 0;
1931
+ for (let l = 0; l < r; l++)
1932
+ c = c << 1 & 2047 | i.get(u, l), l >= 10 && (c === 1488 || c === 93) && o++, a = a << 1 & 2047 | i.get(l, u), l >= 10 && (a === 1488 || a === 93) && o++;
1933
+ }
1934
+ return o * e.N3;
1935
+ }, s.getPenaltyN4 = function(i) {
1936
+ let r = 0;
1937
+ const o = i.data.length;
1938
+ for (let a = 0; a < o; a++) r += i.data[a];
1939
+ return Math.abs(Math.ceil(r * 100 / o / 5) - 10) * e.N4;
1940
+ };
1941
+ function t(n, i, r) {
1942
+ switch (n) {
1943
+ case s.Patterns.PATTERN000:
1944
+ return (i + r) % 2 === 0;
1945
+ case s.Patterns.PATTERN001:
1946
+ return i % 2 === 0;
1947
+ case s.Patterns.PATTERN010:
1948
+ return r % 3 === 0;
1949
+ case s.Patterns.PATTERN011:
1950
+ return (i + r) % 3 === 0;
1951
+ case s.Patterns.PATTERN100:
1952
+ return (Math.floor(i / 2) + Math.floor(r / 3)) % 2 === 0;
1953
+ case s.Patterns.PATTERN101:
1954
+ return i * r % 2 + i * r % 3 === 0;
1955
+ case s.Patterns.PATTERN110:
1956
+ return (i * r % 2 + i * r % 3) % 2 === 0;
1957
+ case s.Patterns.PATTERN111:
1958
+ return (i * r % 3 + (i + r) % 2) % 2 === 0;
1959
+ default:
1960
+ throw new Error("bad maskPattern:" + n);
1961
+ }
1962
+ }
1963
+ s.applyMask = function(i, r) {
1964
+ const o = r.size;
1965
+ for (let c = 0; c < o; c++)
1966
+ for (let a = 0; a < o; a++)
1967
+ r.isReserved(a, c) || r.xor(a, c, t(i, a, c));
1968
+ }, s.getBestMask = function(i, r) {
1969
+ const o = Object.keys(s.Patterns).length;
1970
+ let c = 0, a = 1 / 0;
1971
+ for (let u = 0; u < o; u++) {
1972
+ r(u), s.applyMask(u, i);
1973
+ const l = s.getPenaltyN1(i) + s.getPenaltyN2(i) + s.getPenaltyN3(i) + s.getPenaltyN4(i);
1974
+ s.applyMask(u, i), l < a && (a = l, c = u);
1975
+ }
1976
+ return c;
1977
+ };
1978
+ })(de)), de;
1979
+ }
1980
+ var Y = {}, Ve;
1981
+ function Et() {
1982
+ if (Ve) return Y;
1983
+ Ve = 1;
1984
+ const s = Te(), e = [
1985
+ // L M Q H
1986
+ 1,
1987
+ 1,
1988
+ 1,
1989
+ 1,
1990
+ 1,
1991
+ 1,
1992
+ 1,
1993
+ 1,
1994
+ 1,
1995
+ 1,
1996
+ 2,
1997
+ 2,
1998
+ 1,
1999
+ 2,
2000
+ 2,
2001
+ 4,
2002
+ 1,
2003
+ 2,
2004
+ 4,
2005
+ 4,
2006
+ 2,
2007
+ 4,
2008
+ 4,
2009
+ 4,
2010
+ 2,
2011
+ 4,
2012
+ 6,
2013
+ 5,
2014
+ 2,
2015
+ 4,
2016
+ 6,
2017
+ 6,
2018
+ 2,
2019
+ 5,
2020
+ 8,
2021
+ 8,
2022
+ 4,
2023
+ 5,
2024
+ 8,
2025
+ 8,
2026
+ 4,
2027
+ 5,
2028
+ 8,
2029
+ 11,
2030
+ 4,
2031
+ 8,
2032
+ 10,
2033
+ 11,
2034
+ 4,
2035
+ 9,
2036
+ 12,
2037
+ 16,
2038
+ 4,
2039
+ 9,
2040
+ 16,
2041
+ 16,
2042
+ 6,
2043
+ 10,
2044
+ 12,
2045
+ 18,
2046
+ 6,
2047
+ 10,
2048
+ 17,
2049
+ 16,
2050
+ 6,
2051
+ 11,
2052
+ 16,
2053
+ 19,
2054
+ 6,
2055
+ 13,
2056
+ 18,
2057
+ 21,
2058
+ 7,
2059
+ 14,
2060
+ 21,
2061
+ 25,
2062
+ 8,
2063
+ 16,
2064
+ 20,
2065
+ 25,
2066
+ 8,
2067
+ 17,
2068
+ 23,
2069
+ 25,
2070
+ 9,
2071
+ 17,
2072
+ 23,
2073
+ 34,
2074
+ 9,
2075
+ 18,
2076
+ 25,
2077
+ 30,
2078
+ 10,
2079
+ 20,
2080
+ 27,
2081
+ 32,
2082
+ 12,
2083
+ 21,
2084
+ 29,
2085
+ 35,
2086
+ 12,
2087
+ 23,
2088
+ 34,
2089
+ 37,
2090
+ 12,
2091
+ 25,
2092
+ 34,
2093
+ 40,
2094
+ 13,
2095
+ 26,
2096
+ 35,
2097
+ 42,
2098
+ 14,
2099
+ 28,
2100
+ 38,
2101
+ 45,
2102
+ 15,
2103
+ 29,
2104
+ 40,
2105
+ 48,
2106
+ 16,
2107
+ 31,
2108
+ 43,
2109
+ 51,
2110
+ 17,
2111
+ 33,
2112
+ 45,
2113
+ 54,
2114
+ 18,
2115
+ 35,
2116
+ 48,
2117
+ 57,
2118
+ 19,
2119
+ 37,
2120
+ 51,
2121
+ 60,
2122
+ 19,
2123
+ 38,
2124
+ 53,
2125
+ 63,
2126
+ 20,
2127
+ 40,
2128
+ 56,
2129
+ 66,
2130
+ 21,
2131
+ 43,
2132
+ 59,
2133
+ 70,
2134
+ 22,
2135
+ 45,
2136
+ 62,
2137
+ 74,
2138
+ 24,
2139
+ 47,
2140
+ 65,
2141
+ 77,
2142
+ 25,
2143
+ 49,
2144
+ 68,
2145
+ 81
2146
+ ], t = [
2147
+ // L M Q H
2148
+ 7,
2149
+ 10,
2150
+ 13,
2151
+ 17,
2152
+ 10,
2153
+ 16,
2154
+ 22,
2155
+ 28,
2156
+ 15,
2157
+ 26,
2158
+ 36,
2159
+ 44,
2160
+ 20,
2161
+ 36,
2162
+ 52,
2163
+ 64,
2164
+ 26,
2165
+ 48,
2166
+ 72,
2167
+ 88,
2168
+ 36,
2169
+ 64,
2170
+ 96,
2171
+ 112,
2172
+ 40,
2173
+ 72,
2174
+ 108,
2175
+ 130,
2176
+ 48,
2177
+ 88,
2178
+ 132,
2179
+ 156,
2180
+ 60,
2181
+ 110,
2182
+ 160,
2183
+ 192,
2184
+ 72,
2185
+ 130,
2186
+ 192,
2187
+ 224,
2188
+ 80,
2189
+ 150,
2190
+ 224,
2191
+ 264,
2192
+ 96,
2193
+ 176,
2194
+ 260,
2195
+ 308,
2196
+ 104,
2197
+ 198,
2198
+ 288,
2199
+ 352,
2200
+ 120,
2201
+ 216,
2202
+ 320,
2203
+ 384,
2204
+ 132,
2205
+ 240,
2206
+ 360,
2207
+ 432,
2208
+ 144,
2209
+ 280,
2210
+ 408,
2211
+ 480,
2212
+ 168,
2213
+ 308,
2214
+ 448,
2215
+ 532,
2216
+ 180,
2217
+ 338,
2218
+ 504,
2219
+ 588,
2220
+ 196,
2221
+ 364,
2222
+ 546,
2223
+ 650,
2224
+ 224,
2225
+ 416,
2226
+ 600,
2227
+ 700,
2228
+ 224,
2229
+ 442,
2230
+ 644,
2231
+ 750,
2232
+ 252,
2233
+ 476,
2234
+ 690,
2235
+ 816,
2236
+ 270,
2237
+ 504,
2238
+ 750,
2239
+ 900,
2240
+ 300,
2241
+ 560,
2242
+ 810,
2243
+ 960,
2244
+ 312,
2245
+ 588,
2246
+ 870,
2247
+ 1050,
2248
+ 336,
2249
+ 644,
2250
+ 952,
2251
+ 1110,
2252
+ 360,
2253
+ 700,
2254
+ 1020,
2255
+ 1200,
2256
+ 390,
2257
+ 728,
2258
+ 1050,
2259
+ 1260,
2260
+ 420,
2261
+ 784,
2262
+ 1140,
2263
+ 1350,
2264
+ 450,
2265
+ 812,
2266
+ 1200,
2267
+ 1440,
2268
+ 480,
2269
+ 868,
2270
+ 1290,
2271
+ 1530,
2272
+ 510,
2273
+ 924,
2274
+ 1350,
2275
+ 1620,
2276
+ 540,
2277
+ 980,
2278
+ 1440,
2279
+ 1710,
2280
+ 570,
2281
+ 1036,
2282
+ 1530,
2283
+ 1800,
2284
+ 570,
2285
+ 1064,
2286
+ 1590,
2287
+ 1890,
2288
+ 600,
2289
+ 1120,
2290
+ 1680,
2291
+ 1980,
2292
+ 630,
2293
+ 1204,
2294
+ 1770,
2295
+ 2100,
2296
+ 660,
2297
+ 1260,
2298
+ 1860,
2299
+ 2220,
2300
+ 720,
2301
+ 1316,
2302
+ 1950,
2303
+ 2310,
2304
+ 750,
2305
+ 1372,
2306
+ 2040,
2307
+ 2430
2308
+ ];
2309
+ return Y.getBlocksCount = function(i, r) {
2310
+ switch (r) {
2311
+ case s.L:
2312
+ return e[(i - 1) * 4 + 0];
2313
+ case s.M:
2314
+ return e[(i - 1) * 4 + 1];
2315
+ case s.Q:
2316
+ return e[(i - 1) * 4 + 2];
2317
+ case s.H:
2318
+ return e[(i - 1) * 4 + 3];
2319
+ default:
2320
+ return;
2321
+ }
2322
+ }, Y.getTotalCodewordsCount = function(i, r) {
2323
+ switch (r) {
2324
+ case s.L:
2325
+ return t[(i - 1) * 4 + 0];
2326
+ case s.M:
2327
+ return t[(i - 1) * 4 + 1];
2328
+ case s.Q:
2329
+ return t[(i - 1) * 4 + 2];
2330
+ case s.H:
2331
+ return t[(i - 1) * 4 + 3];
2332
+ default:
2333
+ return;
2334
+ }
2335
+ }, Y;
2336
+ }
2337
+ var fe = {}, V = {}, Je;
2338
+ function mn() {
2339
+ if (Je) return V;
2340
+ Je = 1;
2341
+ const s = new Uint8Array(512), e = new Uint8Array(256);
2342
+ return (function() {
2343
+ let n = 1;
2344
+ for (let i = 0; i < 255; i++)
2345
+ s[i] = n, e[n] = i, n <<= 1, n & 256 && (n ^= 285);
2346
+ for (let i = 255; i < 512; i++)
2347
+ s[i] = s[i - 255];
2348
+ })(), V.log = function(n) {
2349
+ if (n < 1) throw new Error("log(" + n + ")");
2350
+ return e[n];
2351
+ }, V.exp = function(n) {
2352
+ return s[n];
2353
+ }, V.mul = function(n, i) {
2354
+ return n === 0 || i === 0 ? 0 : s[e[n] + e[i]];
2355
+ }, V;
2356
+ }
2357
+ var He;
2358
+ function bn() {
2359
+ return He || (He = 1, (function(s) {
2360
+ const e = mn();
2361
+ s.mul = function(n, i) {
2362
+ const r = new Uint8Array(n.length + i.length - 1);
2363
+ for (let o = 0; o < n.length; o++)
2364
+ for (let c = 0; c < i.length; c++)
2365
+ r[o + c] ^= e.mul(n[o], i[c]);
2366
+ return r;
2367
+ }, s.mod = function(n, i) {
2368
+ let r = new Uint8Array(n);
2369
+ for (; r.length - i.length >= 0; ) {
2370
+ const o = r[0];
2371
+ for (let a = 0; a < i.length; a++)
2372
+ r[a] ^= e.mul(i[a], o);
2373
+ let c = 0;
2374
+ for (; c < r.length && r[c] === 0; ) c++;
2375
+ r = r.slice(c);
2376
+ }
2377
+ return r;
2378
+ }, s.generateECPolynomial = function(n) {
2379
+ let i = new Uint8Array([1]);
2380
+ for (let r = 0; r < n; r++)
2381
+ i = s.mul(i, new Uint8Array([1, e.exp(r)]));
2382
+ return i;
2383
+ };
2384
+ })(fe)), fe;
2385
+ }
2386
+ var ge, Ke;
2387
+ function yn() {
2388
+ if (Ke) return ge;
2389
+ Ke = 1;
2390
+ const s = bn();
2391
+ function e(t) {
2392
+ this.genPoly = void 0, this.degree = t, this.degree && this.initialize(this.degree);
2393
+ }
2394
+ return e.prototype.initialize = function(n) {
2395
+ this.degree = n, this.genPoly = s.generateECPolynomial(this.degree);
2396
+ }, e.prototype.encode = function(n) {
2397
+ if (!this.genPoly)
2398
+ throw new Error("Encoder not initialized");
2399
+ const i = new Uint8Array(n.length + this.degree);
2400
+ i.set(n);
2401
+ const r = s.mod(i, this.genPoly), o = this.degree - r.length;
2402
+ if (o > 0) {
2403
+ const c = new Uint8Array(this.degree);
2404
+ return c.set(r, o), c;
2405
+ }
2406
+ return r;
2407
+ }, ge = e, ge;
2408
+ }
2409
+ var pe = {}, me = {}, be = {}, Ye;
2410
+ function Ct() {
2411
+ return Ye || (Ye = 1, be.isValid = function(e) {
2412
+ return !isNaN(e) && e >= 1 && e <= 40;
2413
+ }), be;
2414
+ }
2415
+ var M = {}, We;
2416
+ function It() {
2417
+ if (We) return M;
2418
+ We = 1;
2419
+ const s = "[0-9]+", e = "[A-Z $%*+\\-./:]+";
2420
+ let t = "(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";
2421
+ t = t.replace(/u/g, "\\u");
2422
+ const n = "(?:(?![A-Z0-9 $%*+\\-./:]|" + t + `)(?:.|[\r
2423
+ ]))+`;
2424
+ M.KANJI = new RegExp(t, "g"), M.BYTE_KANJI = new RegExp("[^A-Z0-9 $%*+\\-./:]+", "g"), M.BYTE = new RegExp(n, "g"), M.NUMERIC = new RegExp(s, "g"), M.ALPHANUMERIC = new RegExp(e, "g");
2425
+ const i = new RegExp("^" + t + "$"), r = new RegExp("^" + s + "$"), o = new RegExp("^[A-Z0-9 $%*+\\-./:]+$");
2426
+ return M.testKanji = function(a) {
2427
+ return i.test(a);
2428
+ }, M.testNumeric = function(a) {
2429
+ return r.test(a);
2430
+ }, M.testAlphanumeric = function(a) {
2431
+ return o.test(a);
2432
+ }, M;
2433
+ }
2434
+ var Ze;
2435
+ function O() {
2436
+ return Ze || (Ze = 1, (function(s) {
2437
+ const e = Ct(), t = It();
2438
+ s.NUMERIC = {
2439
+ id: "Numeric",
2440
+ bit: 1,
2441
+ ccBits: [10, 12, 14]
2442
+ }, s.ALPHANUMERIC = {
2443
+ id: "Alphanumeric",
2444
+ bit: 2,
2445
+ ccBits: [9, 11, 13]
2446
+ }, s.BYTE = {
2447
+ id: "Byte",
2448
+ bit: 4,
2449
+ ccBits: [8, 16, 16]
2450
+ }, s.KANJI = {
2451
+ id: "Kanji",
2452
+ bit: 8,
2453
+ ccBits: [8, 10, 12]
2454
+ }, s.MIXED = {
2455
+ bit: -1
2456
+ }, s.getCharCountIndicator = function(r, o) {
2457
+ if (!r.ccBits) throw new Error("Invalid mode: " + r);
2458
+ if (!e.isValid(o))
2459
+ throw new Error("Invalid version: " + o);
2460
+ return o >= 1 && o < 10 ? r.ccBits[0] : o < 27 ? r.ccBits[1] : r.ccBits[2];
2461
+ }, s.getBestModeForData = function(r) {
2462
+ return t.testNumeric(r) ? s.NUMERIC : t.testAlphanumeric(r) ? s.ALPHANUMERIC : t.testKanji(r) ? s.KANJI : s.BYTE;
2463
+ }, s.toString = function(r) {
2464
+ if (r && r.id) return r.id;
2465
+ throw new Error("Invalid mode");
2466
+ }, s.isValid = function(r) {
2467
+ return r && r.bit && r.ccBits;
2468
+ };
2469
+ function n(i) {
2470
+ if (typeof i != "string")
2471
+ throw new Error("Param is not a string");
2472
+ switch (i.toLowerCase()) {
2473
+ case "numeric":
2474
+ return s.NUMERIC;
2475
+ case "alphanumeric":
2476
+ return s.ALPHANUMERIC;
2477
+ case "kanji":
2478
+ return s.KANJI;
2479
+ case "byte":
2480
+ return s.BYTE;
2481
+ default:
2482
+ throw new Error("Unknown mode: " + i);
2483
+ }
2484
+ }
2485
+ s.from = function(r, o) {
2486
+ if (s.isValid(r))
2487
+ return r;
2488
+ try {
2489
+ return n(r);
2490
+ } catch {
2491
+ return o;
2492
+ }
2493
+ };
2494
+ })(me)), me;
2495
+ }
2496
+ var $e;
2497
+ function wn() {
2498
+ return $e || ($e = 1, (function(s) {
2499
+ const e = F(), t = Et(), n = Te(), i = O(), r = Ct(), o = 7973, c = e.getBCHDigit(o);
2500
+ function a(f, h, E) {
2501
+ for (let b = 1; b <= 40; b++)
2502
+ if (h <= s.getCapacity(b, E, f))
2503
+ return b;
2504
+ }
2505
+ function u(f, h) {
2506
+ return i.getCharCountIndicator(f, h) + 4;
2507
+ }
2508
+ function l(f, h) {
2509
+ let E = 0;
2510
+ return f.forEach(function(b) {
2511
+ const T = u(b.mode, h);
2512
+ E += T + b.getBitsLength();
2513
+ }), E;
2514
+ }
2515
+ function d(f, h) {
2516
+ for (let E = 1; E <= 40; E++)
2517
+ if (l(f, E) <= s.getCapacity(E, h, i.MIXED))
2518
+ return E;
2519
+ }
2520
+ s.from = function(h, E) {
2521
+ return r.isValid(h) ? parseInt(h, 10) : E;
2522
+ }, s.getCapacity = function(h, E, b) {
2523
+ if (!r.isValid(h))
2524
+ throw new Error("Invalid QR Code version");
2525
+ typeof b > "u" && (b = i.BYTE);
2526
+ const T = e.getSymbolTotalCodewords(h), w = t.getTotalCodewordsCount(h, E), P = (T - w) * 8;
2527
+ if (b === i.MIXED) return P;
2528
+ const _ = P - u(b, h);
2529
+ switch (b) {
2530
+ case i.NUMERIC:
2531
+ return Math.floor(_ / 10 * 3);
2532
+ case i.ALPHANUMERIC:
2533
+ return Math.floor(_ / 11 * 2);
2534
+ case i.KANJI:
2535
+ return Math.floor(_ / 13);
2536
+ case i.BYTE:
2537
+ default:
2538
+ return Math.floor(_ / 8);
2539
+ }
2540
+ }, s.getBestVersionForData = function(h, E) {
2541
+ let b;
2542
+ const T = n.from(E, n.M);
2543
+ if (Array.isArray(h)) {
2544
+ if (h.length > 1)
2545
+ return d(h, T);
2546
+ if (h.length === 0)
2547
+ return 1;
2548
+ b = h[0];
2549
+ } else
2550
+ b = h;
2551
+ return a(b.mode, b.getLength(), T);
2552
+ }, s.getEncodedBits = function(h) {
2553
+ if (!r.isValid(h) || h < 7)
2554
+ throw new Error("Invalid QR Code version");
2555
+ let E = h << 12;
2556
+ for (; e.getBCHDigit(E) - c >= 0; )
2557
+ E ^= o << e.getBCHDigit(E) - c;
2558
+ return h << 12 | E;
2559
+ };
2560
+ })(pe)), pe;
2561
+ }
2562
+ var ye = {}, Xe;
2563
+ function Sn() {
2564
+ if (Xe) return ye;
2565
+ Xe = 1;
2566
+ const s = F(), e = 1335, t = 21522, n = s.getBCHDigit(e);
2567
+ return ye.getEncodedBits = function(r, o) {
2568
+ const c = r.bit << 3 | o;
2569
+ let a = c << 10;
2570
+ for (; s.getBCHDigit(a) - n >= 0; )
2571
+ a ^= e << s.getBCHDigit(a) - n;
2572
+ return (c << 10 | a) ^ t;
2573
+ }, ye;
2574
+ }
2575
+ var we = {}, Se, et;
2576
+ function En() {
2577
+ if (et) return Se;
2578
+ et = 1;
2579
+ const s = O();
2580
+ function e(t) {
2581
+ this.mode = s.NUMERIC, this.data = t.toString();
2582
+ }
2583
+ return e.getBitsLength = function(n) {
2584
+ return 10 * Math.floor(n / 3) + (n % 3 ? n % 3 * 3 + 1 : 0);
2585
+ }, e.prototype.getLength = function() {
2586
+ return this.data.length;
2587
+ }, e.prototype.getBitsLength = function() {
2588
+ return e.getBitsLength(this.data.length);
2589
+ }, e.prototype.write = function(n) {
2590
+ let i, r, o;
2591
+ for (i = 0; i + 3 <= this.data.length; i += 3)
2592
+ r = this.data.substr(i, 3), o = parseInt(r, 10), n.put(o, 10);
2593
+ const c = this.data.length - i;
2594
+ c > 0 && (r = this.data.substr(i), o = parseInt(r, 10), n.put(o, c * 3 + 1));
2595
+ }, Se = e, Se;
2596
+ }
2597
+ var Ee, tt;
2598
+ function Cn() {
2599
+ if (tt) return Ee;
2600
+ tt = 1;
2601
+ const s = O(), e = [
2602
+ "0",
2603
+ "1",
2604
+ "2",
2605
+ "3",
2606
+ "4",
2607
+ "5",
2608
+ "6",
2609
+ "7",
2610
+ "8",
2611
+ "9",
2612
+ "A",
2613
+ "B",
2614
+ "C",
2615
+ "D",
2616
+ "E",
2617
+ "F",
2618
+ "G",
2619
+ "H",
2620
+ "I",
2621
+ "J",
2622
+ "K",
2623
+ "L",
2624
+ "M",
2625
+ "N",
2626
+ "O",
2627
+ "P",
2628
+ "Q",
2629
+ "R",
2630
+ "S",
2631
+ "T",
2632
+ "U",
2633
+ "V",
2634
+ "W",
2635
+ "X",
2636
+ "Y",
2637
+ "Z",
2638
+ " ",
2639
+ "$",
2640
+ "%",
2641
+ "*",
2642
+ "+",
2643
+ "-",
2644
+ ".",
2645
+ "/",
2646
+ ":"
2647
+ ];
2648
+ function t(n) {
2649
+ this.mode = s.ALPHANUMERIC, this.data = n;
2650
+ }
2651
+ return t.getBitsLength = function(i) {
2652
+ return 11 * Math.floor(i / 2) + 6 * (i % 2);
2653
+ }, t.prototype.getLength = function() {
2654
+ return this.data.length;
2655
+ }, t.prototype.getBitsLength = function() {
2656
+ return t.getBitsLength(this.data.length);
2657
+ }, t.prototype.write = function(i) {
2658
+ let r;
2659
+ for (r = 0; r + 2 <= this.data.length; r += 2) {
2660
+ let o = e.indexOf(this.data[r]) * 45;
2661
+ o += e.indexOf(this.data[r + 1]), i.put(o, 11);
2662
+ }
2663
+ this.data.length % 2 && i.put(e.indexOf(this.data[r]), 6);
2664
+ }, Ee = t, Ee;
2665
+ }
2666
+ var Ce, nt;
2667
+ function In() {
2668
+ if (nt) return Ce;
2669
+ nt = 1;
2670
+ const s = O();
2671
+ function e(t) {
2672
+ this.mode = s.BYTE, typeof t == "string" ? this.data = new TextEncoder().encode(t) : this.data = new Uint8Array(t);
2673
+ }
2674
+ return e.getBitsLength = function(n) {
2675
+ return n * 8;
2676
+ }, e.prototype.getLength = function() {
2677
+ return this.data.length;
2678
+ }, e.prototype.getBitsLength = function() {
2679
+ return e.getBitsLength(this.data.length);
2680
+ }, e.prototype.write = function(t) {
2681
+ for (let n = 0, i = this.data.length; n < i; n++)
2682
+ t.put(this.data[n], 8);
2683
+ }, Ce = e, Ce;
2684
+ }
2685
+ var Ie, it;
2686
+ function vn() {
2687
+ if (it) return Ie;
2688
+ it = 1;
2689
+ const s = O(), e = F();
2690
+ function t(n) {
2691
+ this.mode = s.KANJI, this.data = n;
2692
+ }
2693
+ return t.getBitsLength = function(i) {
2694
+ return i * 13;
2695
+ }, t.prototype.getLength = function() {
2696
+ return this.data.length;
2697
+ }, t.prototype.getBitsLength = function() {
2698
+ return t.getBitsLength(this.data.length);
2699
+ }, t.prototype.write = function(n) {
2700
+ let i;
2701
+ for (i = 0; i < this.data.length; i++) {
2702
+ let r = e.toSJIS(this.data[i]);
2703
+ if (r >= 33088 && r <= 40956)
2704
+ r -= 33088;
2705
+ else if (r >= 57408 && r <= 60351)
2706
+ r -= 49472;
2707
+ else
2708
+ throw new Error(
2709
+ "Invalid SJIS character: " + this.data[i] + `
2710
+ Make sure your charset is UTF-8`
2711
+ );
2712
+ r = (r >>> 8 & 255) * 192 + (r & 255), n.put(r, 13);
2713
+ }
2714
+ }, Ie = t, Ie;
2715
+ }
2716
+ var ve = { exports: {} }, st;
2717
+ function qn() {
2718
+ return st || (st = 1, (function(s) {
2719
+ var e = {
2720
+ single_source_shortest_paths: function(t, n, i) {
2721
+ var r = {}, o = {};
2722
+ o[n] = 0;
2723
+ var c = e.PriorityQueue.make();
2724
+ c.push(n, 0);
2725
+ for (var a, u, l, d, f, h, E, b, T; !c.empty(); ) {
2726
+ a = c.pop(), u = a.value, d = a.cost, f = t[u] || {};
2727
+ for (l in f)
2728
+ f.hasOwnProperty(l) && (h = f[l], E = d + h, b = o[l], T = typeof o[l] > "u", (T || b > E) && (o[l] = E, c.push(l, E), r[l] = u));
2729
+ }
2730
+ if (typeof i < "u" && typeof o[i] > "u") {
2731
+ var w = ["Could not find a path from ", n, " to ", i, "."].join("");
2732
+ throw new Error(w);
2733
+ }
2734
+ return r;
2735
+ },
2736
+ extract_shortest_path_from_predecessor_list: function(t, n) {
2737
+ for (var i = [], r = n; r; )
2738
+ i.push(r), t[r], r = t[r];
2739
+ return i.reverse(), i;
2740
+ },
2741
+ find_path: function(t, n, i) {
2742
+ var r = e.single_source_shortest_paths(t, n, i);
2743
+ return e.extract_shortest_path_from_predecessor_list(
2744
+ r,
2745
+ i
2746
+ );
2747
+ },
2748
+ /**
2749
+ * A very naive priority queue implementation.
2750
+ */
2751
+ PriorityQueue: {
2752
+ make: function(t) {
2753
+ var n = e.PriorityQueue, i = {}, r;
2754
+ t = t || {};
2755
+ for (r in n)
2756
+ n.hasOwnProperty(r) && (i[r] = n[r]);
2757
+ return i.queue = [], i.sorter = t.sorter || n.default_sorter, i;
2758
+ },
2759
+ default_sorter: function(t, n) {
2760
+ return t.cost - n.cost;
2761
+ },
2762
+ /**
2763
+ * Add a new item to the queue and ensure the highest priority element
2764
+ * is at the front of the queue.
2765
+ */
2766
+ push: function(t, n) {
2767
+ var i = { value: t, cost: n };
2768
+ this.queue.push(i), this.queue.sort(this.sorter);
2769
+ },
2770
+ /**
2771
+ * Return the highest priority element in the queue.
2772
+ */
2773
+ pop: function() {
2774
+ return this.queue.shift();
2775
+ },
2776
+ empty: function() {
2777
+ return this.queue.length === 0;
2778
+ }
2779
+ }
2780
+ };
2781
+ s.exports = e;
2782
+ })(ve)), ve.exports;
2783
+ }
2784
+ var rt;
2785
+ function _n() {
2786
+ return rt || (rt = 1, (function(s) {
2787
+ const e = O(), t = En(), n = Cn(), i = In(), r = vn(), o = It(), c = F(), a = qn();
2788
+ function u(w) {
2789
+ return unescape(encodeURIComponent(w)).length;
2790
+ }
2791
+ function l(w, P, _) {
2792
+ const v = [];
2793
+ let N;
2794
+ for (; (N = w.exec(_)) !== null; )
2795
+ v.push({
2796
+ data: N[0],
2797
+ index: N.index,
2798
+ mode: P,
2799
+ length: N[0].length
2800
+ });
2801
+ return v;
2802
+ }
2803
+ function d(w) {
2804
+ const P = l(o.NUMERIC, e.NUMERIC, w), _ = l(o.ALPHANUMERIC, e.ALPHANUMERIC, w);
2805
+ let v, N;
2806
+ return c.isKanjiModeEnabled() ? (v = l(o.BYTE, e.BYTE, w), N = l(o.KANJI, e.KANJI, w)) : (v = l(o.BYTE_KANJI, e.BYTE, w), N = []), P.concat(_, v, N).sort(function(I, C) {
2807
+ return I.index - C.index;
2808
+ }).map(function(I) {
2809
+ return {
2810
+ data: I.data,
2811
+ mode: I.mode,
2812
+ length: I.length
2813
+ };
2814
+ });
2815
+ }
2816
+ function f(w, P) {
2817
+ switch (P) {
2818
+ case e.NUMERIC:
2819
+ return t.getBitsLength(w);
2820
+ case e.ALPHANUMERIC:
2821
+ return n.getBitsLength(w);
2822
+ case e.KANJI:
2823
+ return r.getBitsLength(w);
2824
+ case e.BYTE:
2825
+ return i.getBitsLength(w);
2826
+ }
2827
+ }
2828
+ function h(w) {
2829
+ return w.reduce(function(P, _) {
2830
+ const v = P.length - 1 >= 0 ? P[P.length - 1] : null;
2831
+ return v && v.mode === _.mode ? (P[P.length - 1].data += _.data, P) : (P.push(_), P);
2832
+ }, []);
2833
+ }
2834
+ function E(w) {
2835
+ const P = [];
2836
+ for (let _ = 0; _ < w.length; _++) {
2837
+ const v = w[_];
2838
+ switch (v.mode) {
2839
+ case e.NUMERIC:
2840
+ P.push([
2841
+ v,
2842
+ { data: v.data, mode: e.ALPHANUMERIC, length: v.length },
2843
+ { data: v.data, mode: e.BYTE, length: v.length }
2844
+ ]);
2845
+ break;
2846
+ case e.ALPHANUMERIC:
2847
+ P.push([
2848
+ v,
2849
+ { data: v.data, mode: e.BYTE, length: v.length }
2850
+ ]);
2851
+ break;
2852
+ case e.KANJI:
2853
+ P.push([
2854
+ v,
2855
+ { data: v.data, mode: e.BYTE, length: u(v.data) }
2856
+ ]);
2857
+ break;
2858
+ case e.BYTE:
2859
+ P.push([
2860
+ { data: v.data, mode: e.BYTE, length: u(v.data) }
2861
+ ]);
2862
+ }
2863
+ }
2864
+ return P;
2865
+ }
2866
+ function b(w, P) {
2867
+ const _ = {}, v = { start: {} };
2868
+ let N = ["start"];
2869
+ for (let p = 0; p < w.length; p++) {
2870
+ const I = w[p], C = [];
2871
+ for (let g = 0; g < I.length; g++) {
2872
+ const q = I[g], m = "" + p + g;
2873
+ C.push(m), _[m] = { node: q, lastCount: 0 }, v[m] = {};
2874
+ for (let S = 0; S < N.length; S++) {
2875
+ const y = N[S];
2876
+ _[y] && _[y].node.mode === q.mode ? (v[y][m] = f(_[y].lastCount + q.length, q.mode) - f(_[y].lastCount, q.mode), _[y].lastCount += q.length) : (_[y] && (_[y].lastCount = q.length), v[y][m] = f(q.length, q.mode) + 4 + e.getCharCountIndicator(q.mode, P));
2877
+ }
2878
+ }
2879
+ N = C;
2880
+ }
2881
+ for (let p = 0; p < N.length; p++)
2882
+ v[N[p]].end = 0;
2883
+ return { map: v, table: _ };
2884
+ }
2885
+ function T(w, P) {
2886
+ let _;
2887
+ const v = e.getBestModeForData(w);
2888
+ if (_ = e.from(P, v), _ !== e.BYTE && _.bit < v.bit)
2889
+ throw new Error('"' + w + '" cannot be encoded with mode ' + e.toString(_) + `.
2890
+ Suggested mode is: ` + e.toString(v));
2891
+ switch (_ === e.KANJI && !c.isKanjiModeEnabled() && (_ = e.BYTE), _) {
2892
+ case e.NUMERIC:
2893
+ return new t(w);
2894
+ case e.ALPHANUMERIC:
2895
+ return new n(w);
2896
+ case e.KANJI:
2897
+ return new r(w);
2898
+ case e.BYTE:
2899
+ return new i(w);
2900
+ }
2901
+ }
2902
+ s.fromArray = function(P) {
2903
+ return P.reduce(function(_, v) {
2904
+ return typeof v == "string" ? _.push(T(v, null)) : v.data && _.push(T(v.data, v.mode)), _;
2905
+ }, []);
2906
+ }, s.fromString = function(P, _) {
2907
+ const v = d(P, c.isKanjiModeEnabled()), N = E(v), p = b(N, _), I = a.find_path(p.map, "start", "end"), C = [];
2908
+ for (let g = 1; g < I.length - 1; g++)
2909
+ C.push(p.table[I[g]].node);
2910
+ return s.fromArray(h(C));
2911
+ }, s.rawSplit = function(P) {
2912
+ return s.fromArray(
2913
+ d(P, c.isKanjiModeEnabled())
2914
+ );
2915
+ };
2916
+ })(we)), we;
2917
+ }
2918
+ var ot;
2919
+ function Pn() {
2920
+ if (ot) return oe;
2921
+ ot = 1;
2922
+ const s = F(), e = Te(), t = hn(), n = dn(), i = fn(), r = gn(), o = pn(), c = Et(), a = yn(), u = wn(), l = Sn(), d = O(), f = _n();
2923
+ function h(p, I) {
2924
+ const C = p.size, g = r.getPositions(I);
2925
+ for (let q = 0; q < g.length; q++) {
2926
+ const m = g[q][0], S = g[q][1];
2927
+ for (let y = -1; y <= 7; y++)
2928
+ if (!(m + y <= -1 || C <= m + y))
2929
+ for (let R = -1; R <= 7; R++)
2930
+ S + R <= -1 || C <= S + R || (y >= 0 && y <= 6 && (R === 0 || R === 6) || R >= 0 && R <= 6 && (y === 0 || y === 6) || y >= 2 && y <= 4 && R >= 2 && R <= 4 ? p.set(m + y, S + R, !0, !0) : p.set(m + y, S + R, !1, !0));
2931
+ }
2932
+ }
2933
+ function E(p) {
2934
+ const I = p.size;
2935
+ for (let C = 8; C < I - 8; C++) {
2936
+ const g = C % 2 === 0;
2937
+ p.set(C, 6, g, !0), p.set(6, C, g, !0);
2938
+ }
2939
+ }
2940
+ function b(p, I) {
2941
+ const C = i.getPositions(I);
2942
+ for (let g = 0; g < C.length; g++) {
2943
+ const q = C[g][0], m = C[g][1];
2944
+ for (let S = -2; S <= 2; S++)
2945
+ for (let y = -2; y <= 2; y++)
2946
+ S === -2 || S === 2 || y === -2 || y === 2 || S === 0 && y === 0 ? p.set(q + S, m + y, !0, !0) : p.set(q + S, m + y, !1, !0);
2947
+ }
2948
+ }
2949
+ function T(p, I) {
2950
+ const C = p.size, g = u.getEncodedBits(I);
2951
+ let q, m, S;
2952
+ for (let y = 0; y < 18; y++)
2953
+ q = Math.floor(y / 3), m = y % 3 + C - 8 - 3, S = (g >> y & 1) === 1, p.set(q, m, S, !0), p.set(m, q, S, !0);
2954
+ }
2955
+ function w(p, I, C) {
2956
+ const g = p.size, q = l.getEncodedBits(I, C);
2957
+ let m, S;
2958
+ for (m = 0; m < 15; m++)
2959
+ S = (q >> m & 1) === 1, m < 6 ? p.set(m, 8, S, !0) : m < 8 ? p.set(m + 1, 8, S, !0) : p.set(g - 15 + m, 8, S, !0), m < 8 ? p.set(8, g - m - 1, S, !0) : m < 9 ? p.set(8, 15 - m - 1 + 1, S, !0) : p.set(8, 15 - m - 1, S, !0);
2960
+ p.set(g - 8, 8, 1, !0);
2961
+ }
2962
+ function P(p, I) {
2963
+ const C = p.size;
2964
+ let g = -1, q = C - 1, m = 7, S = 0;
2965
+ for (let y = C - 1; y > 0; y -= 2)
2966
+ for (y === 6 && y--; ; ) {
2967
+ for (let R = 0; R < 2; R++)
2968
+ if (!p.isReserved(q, y - R)) {
2969
+ let z = !1;
2970
+ S < I.length && (z = (I[S] >>> m & 1) === 1), p.set(q, y - R, z), m--, m === -1 && (S++, m = 7);
2971
+ }
2972
+ if (q += g, q < 0 || C <= q) {
2973
+ q -= g, g = -g;
2974
+ break;
2975
+ }
2976
+ }
2977
+ }
2978
+ function _(p, I, C) {
2979
+ const g = new t();
2980
+ C.forEach(function(R) {
2981
+ g.put(R.mode.bit, 4), g.put(R.getLength(), d.getCharCountIndicator(R.mode, p)), R.write(g);
2982
+ });
2983
+ const q = s.getSymbolTotalCodewords(p), m = c.getTotalCodewordsCount(p, I), S = (q - m) * 8;
2984
+ for (g.getLengthInBits() + 4 <= S && g.put(0, 4); g.getLengthInBits() % 8 !== 0; )
2985
+ g.putBit(0);
2986
+ const y = (S - g.getLengthInBits()) / 8;
2987
+ for (let R = 0; R < y; R++)
2988
+ g.put(R % 2 ? 17 : 236, 8);
2989
+ return v(g, p, I);
2990
+ }
2991
+ function v(p, I, C) {
2992
+ const g = s.getSymbolTotalCodewords(I), q = c.getTotalCodewordsCount(I, C), m = g - q, S = c.getBlocksCount(I, C), y = g % S, R = S - y, z = Math.floor(g / S), G = Math.floor(m / S), qt = G + 1, Ne = z - G, _t = new a(Ne);
2993
+ let ee = 0;
2994
+ const K = new Array(S), Ae = new Array(S);
2995
+ let te = 0;
2996
+ const Pt = new Uint8Array(p.buffer);
2997
+ for (let j = 0; j < S; j++) {
2998
+ const ie = j < R ? G : qt;
2999
+ K[j] = Pt.slice(ee, ee + ie), Ae[j] = _t.encode(K[j]), ee += ie, te = Math.max(te, ie);
3000
+ }
3001
+ const ne = new Uint8Array(g);
3002
+ let Me = 0, B, k;
3003
+ for (B = 0; B < te; B++)
3004
+ for (k = 0; k < S; k++)
3005
+ B < K[k].length && (ne[Me++] = K[k][B]);
3006
+ for (B = 0; B < Ne; B++)
3007
+ for (k = 0; k < S; k++)
3008
+ ne[Me++] = Ae[k][B];
3009
+ return ne;
3010
+ }
3011
+ function N(p, I, C, g) {
3012
+ let q;
3013
+ if (Array.isArray(p))
3014
+ q = f.fromArray(p);
3015
+ else if (typeof p == "string") {
3016
+ let z = I;
3017
+ if (!z) {
3018
+ const G = f.rawSplit(p);
3019
+ z = u.getBestVersionForData(G, C);
3020
+ }
3021
+ q = f.fromString(p, z || 40);
3022
+ } else
3023
+ throw new Error("Invalid data");
3024
+ const m = u.getBestVersionForData(q, C);
3025
+ if (!m)
3026
+ throw new Error("The amount of data is too big to be stored in a QR Code");
3027
+ if (!I)
3028
+ I = m;
3029
+ else if (I < m)
3030
+ throw new Error(
3031
+ `
3032
+ The chosen QR Code version cannot contain this amount of data.
3033
+ Minimum version required to store current data is: ` + m + `.
3034
+ `
3035
+ );
3036
+ const S = _(I, C, q), y = s.getSymbolSize(I), R = new n(y);
3037
+ return h(R, I), E(R), b(R, I), w(R, C, 0), I >= 7 && T(R, I), P(R, S), isNaN(g) && (g = o.getBestMask(
3038
+ R,
3039
+ w.bind(null, R, C)
3040
+ )), o.applyMask(g, R), w(R, C, g), {
3041
+ modules: R,
3042
+ version: I,
3043
+ errorCorrectionLevel: C,
3044
+ maskPattern: g,
3045
+ segments: q
3046
+ };
3047
+ }
3048
+ return oe.create = function(I, C) {
3049
+ if (typeof I > "u" || I === "")
3050
+ throw new Error("No input text");
3051
+ let g = e.M, q, m;
3052
+ return typeof C < "u" && (g = e.from(C.errorCorrectionLevel, e.M), q = u.from(C.version), m = o.from(C.maskPattern), C.toSJISFunc && s.setToSJISFunction(C.toSJISFunc)), N(I, q, g, m);
3053
+ }, oe;
3054
+ }
3055
+ var qe = {}, _e = {}, ct;
3056
+ function vt() {
3057
+ return ct || (ct = 1, (function(s) {
3058
+ function e(t) {
3059
+ if (typeof t == "number" && (t = t.toString()), typeof t != "string")
3060
+ throw new Error("Color should be defined as hex string");
3061
+ let n = t.slice().replace("#", "").split("");
3062
+ if (n.length < 3 || n.length === 5 || n.length > 8)
3063
+ throw new Error("Invalid hex color: " + t);
3064
+ (n.length === 3 || n.length === 4) && (n = Array.prototype.concat.apply([], n.map(function(r) {
3065
+ return [r, r];
3066
+ }))), n.length === 6 && n.push("F", "F");
3067
+ const i = parseInt(n.join(""), 16);
3068
+ return {
3069
+ r: i >> 24 & 255,
3070
+ g: i >> 16 & 255,
3071
+ b: i >> 8 & 255,
3072
+ a: i & 255,
3073
+ hex: "#" + n.slice(0, 6).join("")
3074
+ };
3075
+ }
3076
+ s.getOptions = function(n) {
3077
+ n || (n = {}), n.color || (n.color = {});
3078
+ const i = typeof n.margin > "u" || n.margin === null || n.margin < 0 ? 4 : n.margin, r = n.width && n.width >= 21 ? n.width : void 0, o = n.scale || 4;
3079
+ return {
3080
+ width: r,
3081
+ scale: r ? 4 : o,
3082
+ margin: i,
3083
+ color: {
3084
+ dark: e(n.color.dark || "#000000ff"),
3085
+ light: e(n.color.light || "#ffffffff")
3086
+ },
3087
+ type: n.type,
3088
+ rendererOpts: n.rendererOpts || {}
3089
+ };
3090
+ }, s.getScale = function(n, i) {
3091
+ return i.width && i.width >= n + i.margin * 2 ? i.width / (n + i.margin * 2) : i.scale;
3092
+ }, s.getImageWidth = function(n, i) {
3093
+ const r = s.getScale(n, i);
3094
+ return Math.floor((n + i.margin * 2) * r);
3095
+ }, s.qrToImageData = function(n, i, r) {
3096
+ const o = i.modules.size, c = i.modules.data, a = s.getScale(o, r), u = Math.floor((o + r.margin * 2) * a), l = r.margin * a, d = [r.color.light, r.color.dark];
3097
+ for (let f = 0; f < u; f++)
3098
+ for (let h = 0; h < u; h++) {
3099
+ let E = (f * u + h) * 4, b = r.color.light;
3100
+ if (f >= l && h >= l && f < u - l && h < u - l) {
3101
+ const T = Math.floor((f - l) / a), w = Math.floor((h - l) / a);
3102
+ b = d[c[T * o + w] ? 1 : 0];
3103
+ }
3104
+ n[E++] = b.r, n[E++] = b.g, n[E++] = b.b, n[E] = b.a;
3105
+ }
3106
+ };
3107
+ })(_e)), _e;
3108
+ }
3109
+ var at;
3110
+ function Rn() {
3111
+ return at || (at = 1, (function(s) {
3112
+ const e = vt();
3113
+ function t(i, r, o) {
3114
+ i.clearRect(0, 0, r.width, r.height), r.style || (r.style = {}), r.height = o, r.width = o, r.style.height = o + "px", r.style.width = o + "px";
3115
+ }
3116
+ function n() {
3117
+ try {
3118
+ return document.createElement("canvas");
3119
+ } catch {
3120
+ throw new Error("You need to specify a canvas element");
3121
+ }
3122
+ }
3123
+ s.render = function(r, o, c) {
3124
+ let a = c, u = o;
3125
+ typeof a > "u" && (!o || !o.getContext) && (a = o, o = void 0), o || (u = n()), a = e.getOptions(a);
3126
+ const l = e.getImageWidth(r.modules.size, a), d = u.getContext("2d"), f = d.createImageData(l, l);
3127
+ return e.qrToImageData(f.data, r, a), t(d, u, l), d.putImageData(f, 0, 0), u;
3128
+ }, s.renderToDataURL = function(r, o, c) {
3129
+ let a = c;
3130
+ typeof a > "u" && (!o || !o.getContext) && (a = o, o = void 0), a || (a = {});
3131
+ const u = s.render(r, o, a), l = a.type || "image/png", d = a.rendererOpts || {};
3132
+ return u.toDataURL(l, d.quality);
3133
+ };
3134
+ })(qe)), qe;
3135
+ }
3136
+ var Pe = {}, ut;
3137
+ function Tn() {
3138
+ if (ut) return Pe;
3139
+ ut = 1;
3140
+ const s = vt();
3141
+ function e(i, r) {
3142
+ const o = i.a / 255, c = r + '="' + i.hex + '"';
3143
+ return o < 1 ? c + " " + r + '-opacity="' + o.toFixed(2).slice(1) + '"' : c;
3144
+ }
3145
+ function t(i, r, o) {
3146
+ let c = i + r;
3147
+ return typeof o < "u" && (c += " " + o), c;
3148
+ }
3149
+ function n(i, r, o) {
3150
+ let c = "", a = 0, u = !1, l = 0;
3151
+ for (let d = 0; d < i.length; d++) {
3152
+ const f = Math.floor(d % r), h = Math.floor(d / r);
3153
+ !f && !u && (u = !0), i[d] ? (l++, d > 0 && f > 0 && i[d - 1] || (c += u ? t("M", f + o, 0.5 + h + o) : t("m", a, 0), a = 0, u = !1), f + 1 < r && i[d + 1] || (c += t("h", l), l = 0)) : a++;
3154
+ }
3155
+ return c;
3156
+ }
3157
+ return Pe.render = function(r, o, c) {
3158
+ const a = s.getOptions(o), u = r.modules.size, l = r.modules.data, d = u + a.margin * 2, f = a.color.light.a ? "<path " + e(a.color.light, "fill") + ' d="M0 0h' + d + "v" + d + 'H0z"/>' : "", h = "<path " + e(a.color.dark, "stroke") + ' d="' + n(l, u, a.margin) + '"/>', E = 'viewBox="0 0 ' + d + " " + d + '"', T = '<svg xmlns="http://www.w3.org/2000/svg" ' + (a.width ? 'width="' + a.width + '" height="' + a.width + '" ' : "") + E + ' shape-rendering="crispEdges">' + f + h + `</svg>
3159
+ `;
3160
+ return typeof c == "function" && c(null, T), T;
3161
+ }, Pe;
3162
+ }
3163
+ var lt;
3164
+ function Nn() {
3165
+ if (lt) return Q;
3166
+ lt = 1;
3167
+ const s = ln(), e = Pn(), t = Rn(), n = Tn();
3168
+ function i(r, o, c, a, u) {
3169
+ const l = [].slice.call(arguments, 1), d = l.length, f = typeof l[d - 1] == "function";
3170
+ if (!f && !s())
3171
+ throw new Error("Callback required as last argument");
3172
+ if (f) {
3173
+ if (d < 2)
3174
+ throw new Error("Too few arguments provided");
3175
+ d === 2 ? (u = c, c = o, o = a = void 0) : d === 3 && (o.getContext && typeof u > "u" ? (u = a, a = void 0) : (u = a, a = c, c = o, o = void 0));
3176
+ } else {
3177
+ if (d < 1)
3178
+ throw new Error("Too few arguments provided");
3179
+ return d === 1 ? (c = o, o = a = void 0) : d === 2 && !o.getContext && (a = c, c = o, o = void 0), new Promise(function(h, E) {
3180
+ try {
3181
+ const b = e.create(c, a);
3182
+ h(r(b, o, a));
3183
+ } catch (b) {
3184
+ E(b);
3185
+ }
3186
+ });
3187
+ }
3188
+ try {
3189
+ const h = e.create(c, a);
3190
+ u(null, r(h, o, a));
3191
+ } catch (h) {
3192
+ u(h);
3193
+ }
3194
+ }
3195
+ return Q.create = e.create, Q.toCanvas = i.bind(null, t.render), Q.toDataURL = i.bind(null, t.renderToDataURL), Q.toString = i.bind(null, function(r, o, c) {
3196
+ return n.render(r, c);
3197
+ }), Q;
3198
+ }
3199
+ var An = Nn();
3200
+ const Mn = /* @__PURE__ */ un(An);
3201
+ async function Bn(s, e = 240) {
3202
+ const t = await Mn.toDataURL(s, {
3203
+ width: e,
3204
+ margin: 1,
3205
+ color: { dark: "#ffffff", light: "#00000000" }
3206
+ }), n = document.createElement("img");
3207
+ return n.src = t, n.alt = `Scan to join: ${s}`, n.className = "lq-qr", n.width = e, n.height = e, n;
3208
+ }
3209
+ async function kn(s, e, t = "Pop quiz!") {
3210
+ const n = s.dataset.quizId, i = s.dataset.quizQuestion || "";
3211
+ let r = [];
3212
+ try {
3213
+ r = JSON.parse(s.dataset.quizOptions || "[]");
3214
+ } catch {
3215
+ console.warn(`[live-quiz] Invalid data-quiz-options on quiz "${n}"`);
3216
+ return;
3217
+ }
3218
+ const o = document.createElement("div");
3219
+ o.className = "lq-question";
3220
+ const c = document.createElement("h2");
3221
+ c.className = "lq-question__title", c.textContent = t, o.appendChild(c);
3222
+ const a = document.createElement("div");
3223
+ if (a.className = "lq-question__body", e) {
3224
+ const b = document.createElement("div");
3225
+ b.className = "lq-question__qr-side";
3226
+ const T = await Bn(e);
3227
+ b.appendChild(T);
3228
+ const w = document.createElement("p");
3229
+ w.className = "lq-question__url", w.textContent = e.replace(/^https?:\/\//, ""), b.appendChild(w), a.appendChild(b);
3230
+ }
3231
+ const u = document.createElement("div");
3232
+ u.className = "lq-question__content";
3233
+ const l = document.createElement("p");
3234
+ l.className = "lq-question__text", l.textContent = i, u.appendChild(l);
3235
+ const d = document.createElement("div");
3236
+ d.className = "lq-question__options";
3237
+ for (const b of r) {
3238
+ const T = document.createElement("div");
3239
+ T.className = "lq-question__option";
3240
+ const w = document.createElement("span");
3241
+ w.className = "lq-question__option-label", w.textContent = b.label;
3242
+ const P = document.createElement("span");
3243
+ P.className = "lq-question__option-text", P.textContent = b.text, T.appendChild(w), T.appendChild(P), d.appendChild(T);
3244
+ }
3245
+ u.appendChild(d);
3246
+ const f = document.createElement("div");
3247
+ f.className = "lq-question__counter";
3248
+ const h = document.createElement("span");
3249
+ h.className = "lq-online", h.dataset.lqQuiz = n, h.textContent = "0";
3250
+ const E = document.createElement("span");
3251
+ E.className = "lq-answered", E.dataset.lqQuiz = n, E.textContent = "0", f.append(h, " online · ", E, " answered"), u.appendChild(f), a.appendChild(u), o.appendChild(a), s.appendChild(o);
3252
+ }
3253
+ function zn(s) {
3254
+ const e = s.dataset.quizResults, t = s.dataset.quizQuestion || "";
3255
+ let n = [];
3256
+ try {
3257
+ n = JSON.parse(s.dataset.quizOptions || "[]");
3258
+ } catch {
3259
+ console.warn(`[live-quiz] Invalid data-quiz-options on results "${e}"`);
3260
+ return;
3261
+ }
3262
+ const i = document.createElement("div");
3263
+ if (i.className = "lq-results", i.dataset.lqQuiz = e, t) {
3264
+ const o = document.createElement("h2");
3265
+ o.className = "lq-results__title", o.textContent = t, i.appendChild(o);
3266
+ }
3267
+ const r = document.createElement("div");
3268
+ r.className = "lq-results__bars";
3269
+ for (const o of n) {
3270
+ const c = document.createElement("div");
3271
+ c.className = "lq-result-bar", o.correct && c.classList.add("lq-result-bar--correct"), c.dataset.option = o.label;
3272
+ const a = document.createElement("div");
3273
+ a.className = "lq-result-bar__label";
3274
+ const u = document.createElement("span");
3275
+ u.className = "lq-result-bar__letter", u.textContent = o.label;
3276
+ const l = document.createElement("span");
3277
+ l.className = "lq-result-bar__text", l.textContent = o.text, a.append(u, l);
3278
+ const d = document.createElement("div");
3279
+ d.className = "lq-result-bar__track";
3280
+ const f = document.createElement("div");
3281
+ f.className = "lq-result-bar__fill", f.style.width = "0%", d.appendChild(f);
3282
+ const h = document.createElement("div");
3283
+ h.className = "lq-result-bar__stats";
3284
+ const E = document.createElement("span");
3285
+ E.className = "lq-result-bar__pct", E.textContent = "0%";
3286
+ const b = document.createElement("span");
3287
+ b.className = "lq-result-bar__count", b.textContent = "0", h.append(E, b), c.append(a, d, h), r.appendChild(c);
3288
+ }
3289
+ i.appendChild(r), s.appendChild(i);
3290
+ }
3291
+ function Ln(s, e) {
3292
+ const t = s.querySelectorAll(".lq-result-bar"), n = e.total || 1;
3293
+ for (const i of t) {
3294
+ const r = i.dataset.option || "", o = e.votes[r] || 0, c = Math.round(o / n * 100), a = i.querySelector(".lq-result-bar__fill"), u = i.querySelector(".lq-result-bar__pct"), l = i.querySelector(".lq-result-bar__count");
3295
+ a && (a.style.width = `${c}%`), u && (u.textContent = `${c}%`), l && (l.textContent = String(o));
3296
+ }
3297
+ }
3298
+ function Un(s, e) {
3299
+ const t = window.matchMedia(
3300
+ "(prefers-reduced-motion: reduce)"
3301
+ ).matches, n = s.querySelectorAll(".lq-result-bar"), i = e.total || 1;
3302
+ let r = 0;
3303
+ for (const o of n) {
3304
+ const c = o.dataset.option || "", a = e.votes[c] || 0, u = Math.round(a / i * 100), l = o.querySelector(".lq-result-bar__fill"), d = o.querySelector(".lq-result-bar__pct"), f = o.querySelector(".lq-result-bar__count");
3305
+ l && (t ? l.style.width = `${u}%` : (l.style.transitionDelay = `${r * 0.15}s`, requestAnimationFrame(() => {
3306
+ l.style.width = `${u}%`;
3307
+ }))), d && (d.textContent = `${u}%`), f && (f.textContent = String(a)), r++;
3308
+ }
3309
+ }
3310
+ function xn() {
3311
+ let s = null, e, t = null, n = null;
3312
+ const i = /* @__PURE__ */ new Set();
3313
+ function r(c) {
3314
+ if (!t) return;
3315
+ const { currentSlide: a } = c, u = a.dataset.quizId;
3316
+ u && t.setActiveQuiz(u);
3317
+ const l = a.dataset.quizResults;
3318
+ if (l && !i.has(l)) {
3319
+ i.add(l);
3320
+ const d = a.querySelector(`[data-lq-quiz="${l}"]`);
3321
+ if (d) {
3322
+ const f = t.getQuizState(l);
3323
+ Un(d, f);
3324
+ }
3325
+ }
3326
+ }
3327
+ function o() {
3328
+ if (!t || !s) return;
3329
+ const c = t.getState(), a = s.getRevealElement();
3330
+ for (const u of a.querySelectorAll(".lq-online"))
3331
+ Le(u, c.online);
3332
+ for (const [u, l] of Object.entries(c.results)) {
3333
+ for (const d of a.querySelectorAll(
3334
+ `.lq-answered[data-lq-quiz="${u}"]`
3335
+ ))
3336
+ Le(d, l.total);
3337
+ if (i.has(u))
3338
+ for (const d of a.querySelectorAll(
3339
+ `.lq-results[data-lq-quiz="${u}"]`
3340
+ ))
3341
+ Ln(d, l);
3342
+ }
3343
+ }
3344
+ return {
3345
+ id: "live-quiz",
3346
+ init: async (c) => {
3347
+ if (s = c, e = s.getConfig().liveQuiz ?? {}, !e.wsUrl || !e.quizGroupId) {
3348
+ console.warn(
3349
+ "[live-quiz] Missing required config: wsUrl and quizGroupId. Pass them in Reveal.initialize({ liveQuiz: { wsUrl, quizGroupId } })."
3350
+ );
3351
+ return;
3352
+ }
3353
+ t = cn({
3354
+ wsUrl: e.wsUrl,
3355
+ quizGroupId: e.quizGroupId,
3356
+ endpoints: e.endpoints
3357
+ });
3358
+ const a = s.getRevealElement(), u = a.querySelectorAll(
3359
+ "section[data-quiz-id]"
3360
+ ), l = [];
3361
+ for (const d of u) {
3362
+ const f = kn(d, e.quizUrl, e.titleText).catch(
3363
+ (h) => console.warn("[live-quiz] Failed to render question slide:", h)
3364
+ );
3365
+ l.push(f);
3366
+ }
3367
+ for (const d of a.querySelectorAll(
3368
+ "section[data-quiz-results]"
3369
+ ))
3370
+ zn(d);
3371
+ await Promise.all(l), n = t.subscribe(o), s.on("slidechanged", r);
3372
+ },
3373
+ destroy: () => {
3374
+ if (!s) return;
3375
+ s.off("slidechanged", r), n && (n(), n = null), t && (an(e.quizGroupId), t.disconnect(), t = null);
3376
+ const c = s.getRevealElement();
3377
+ for (const a of c.querySelectorAll(".lq-question, .lq-results"))
3378
+ a.remove();
3379
+ i.clear(), s = null;
3380
+ }
3381
+ };
3382
+ }
3383
+ export {
3384
+ St as QuizManager,
3385
+ Le as animateCount,
3386
+ xn as default,
3387
+ On as getQuizParticipant,
3388
+ cn as getQuizPresenter,
3389
+ jn as removeQuizParticipant,
3390
+ an as removeQuizPresenter
3391
+ };