@tickean/checkout-js 0.1.0 → 0.2.11

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.
package/dist/index.mjs CHANGED
@@ -1,3 +1,21 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/types.ts
8
+ var TickeanError = class extends Error {
9
+ constructor(payload, status, requestId) {
10
+ super(payload.message);
11
+ this.name = "TickeanError";
12
+ this.code = payload.code;
13
+ this.details = payload.details;
14
+ this.status = status;
15
+ this.requestId = requestId;
16
+ }
17
+ };
18
+
1
19
  // src/demo.ts
2
20
  var demoEvent = {
3
21
  id: "evt_demo",
@@ -71,10 +89,26 @@ function createDemoTransport() {
71
89
  let unlocked = [];
72
90
  let purchaseId = "purchase_demo";
73
91
  let cartRef = "cart_demo";
92
+ let lastPayment = null;
93
+ let paymentConfirmed = false;
94
+ const publicEvent = () => ({
95
+ ...demoEvent,
96
+ shows: demoEvent.shows.map((show) => ({
97
+ ...show,
98
+ showOptions: [
99
+ ...show.showOptions.filter((o) => o.catalogVisibility !== "PROMO_GATED"),
100
+ ...unlocked.filter((u) => show.showOptions.some((o) => o.id === u.id))
101
+ ]
102
+ }))
103
+ });
74
104
  return {
75
105
  async request(path, init) {
76
106
  if (path === "/v1/checkout/sessions" && init.method === "POST") {
77
107
  sessionToken = `demo_${Date.now()}`;
108
+ buyer = null;
109
+ unlocked = [];
110
+ paymentConfirmed = false;
111
+ lastPayment = null;
78
112
  return {
79
113
  sessionId: "sess_demo",
80
114
  sessionToken,
@@ -93,25 +127,68 @@ function createDemoTransport() {
93
127
  discounts: true,
94
128
  transfer: true,
95
129
  onlinePayments: true
96
- }
130
+ },
131
+ phase: "browsing"
97
132
  };
98
133
  }
99
- if (path === "/v1/checkout/catalog") {
134
+ if (path === "/v1/checkout/recovery/exchange" && init.method === "POST") {
135
+ sessionToken = `demo_resume_${Date.now()}`;
136
+ buyer = {
137
+ id: "buyer_demo_resume",
138
+ name: "Demo Resume",
139
+ email: "resume@demo.tickean",
140
+ phone: "+5491100000000"
141
+ };
142
+ purchaseId = "";
143
+ lastPayment = null;
144
+ paymentConfirmed = false;
100
145
  return {
101
- ...demoEvent,
102
- shows: demoEvent.shows.map((show) => ({
103
- ...show,
104
- showOptions: [
105
- ...show.showOptions.filter(
106
- (o) => o.catalogVisibility !== "PROMO_GATED"
107
- ),
108
- ...unlocked.filter(
109
- (u) => show.showOptions.some((o) => o.id === u.id)
110
- )
111
- ]
112
- }))
146
+ sessionId: "sess_demo_resume",
147
+ sessionToken,
148
+ expiresAt: new Date(Date.now() + 36e5).toISOString(),
149
+ suggestedStep: "BUYER",
150
+ event: publicEvent(),
151
+ capabilities: {
152
+ tickets: true,
153
+ discounts: true,
154
+ transfer: true,
155
+ onlinePayments: true
156
+ },
157
+ cart: [{ showOptionId: "opt_day", amount: 1 }],
158
+ discountCode: null,
159
+ buyer,
160
+ buyerVerified: true,
161
+ purchase: null,
162
+ payment: null,
163
+ nextAction: { type: "none" },
164
+ shoppingCartReference: cartRef,
165
+ phase: "ready_to_purchase"
166
+ };
167
+ }
168
+ if (path === "/v1/checkout/session") {
169
+ return {
170
+ sessionId: "sess_demo",
171
+ sessionToken,
172
+ expiresAt: new Date(Date.now() + 36e5).toISOString(),
173
+ event: publicEvent(),
174
+ capabilities: {
175
+ tickets: true,
176
+ discounts: true,
177
+ transfer: true,
178
+ onlinePayments: true
179
+ },
180
+ status: "ACTIVE",
181
+ otpVerified: Boolean(buyer),
182
+ buyerId: buyer?.id || null,
183
+ purchaseId: purchaseId.startsWith("purchase_") ? purchaseId : null,
184
+ shoppingCartReference: cartRef,
185
+ nextAction: lastPayment?.nextAction || { type: "none" },
186
+ phase: paymentConfirmed ? "completed" : lastPayment ? "requires_action" : buyer ? "ready_to_purchase" : "browsing"
113
187
  };
114
188
  }
189
+ if (path === "/v1/checkout/catalog") {
190
+ return publicEvent();
191
+ }
115
192
  if (path === "/v1/checkout/quote" && init.method === "POST") {
116
193
  const body = init.body;
117
194
  if (body.discountCode?.toUpperCase() === "DEMO2X1") {
@@ -130,6 +207,20 @@ function createDemoTransport() {
130
207
  unlockedShowOptions: unlocked
131
208
  };
132
209
  }
210
+ if (path === "/v1/checkout/buyer/lookup" && init.method === "POST") {
211
+ const body = init.body;
212
+ const isNew = String(body.phone || "").replace(/\D/g, "").endsWith("0000");
213
+ if (isNew) return { exists: false };
214
+ return {
215
+ exists: true,
216
+ buyer: {
217
+ id: "buyer_demo",
218
+ phone: body.phone,
219
+ name: "Demo Buyer",
220
+ email: "demo@tickean.com"
221
+ }
222
+ };
223
+ }
133
224
  if (path === "/v1/checkout/otp/send") {
134
225
  return { sent: true };
135
226
  }
@@ -141,12 +232,13 @@ function createDemoTransport() {
141
232
  name: body.name || "Demo Buyer",
142
233
  email: body.email
143
234
  };
144
- return { verified: true, buyer };
235
+ return { verified: true, isNewBuyer: !body.name, buyer };
145
236
  }
146
237
  if (path === "/v1/checkout/purchases") {
147
238
  if (!buyer) {
148
- throw Object.assign(new Error("OTP required"), {
149
- code: "checkout_otp_required"
239
+ throw new TickeanError({
240
+ code: "checkout_otp_required",
241
+ message: "OTP required"
150
242
  });
151
243
  }
152
244
  const body = init.body;
@@ -171,47 +263,81 @@ function createDemoTransport() {
171
263
  };
172
264
  }
173
265
  if (path === "/v1/checkout/payments") {
174
- return {
175
- id: `pay_${Date.now()}`,
176
- paymentStatus: "PENDING",
177
- paymentMethod: init.body?.paymentMethod,
178
- paymentInstructions: {
179
- alias: "tickean.demo",
180
- cvu: "0000003100010000000001",
181
- amount: init.body?.amount
182
- },
183
- redirectUrl: void 0,
184
- returnUrl: null
266
+ const body = init.body;
267
+ const method = String(body?.paymentMethod || "TRANSFER").toUpperCase();
268
+ if (method === "TRANSFER") {
269
+ lastPayment = {
270
+ id: `pay_${Date.now()}`,
271
+ paymentStatus: "PENDING",
272
+ paymentMethod: method,
273
+ paymentInstructions: {
274
+ alias: "tickean.demo",
275
+ cvu: "0000003100010000000001",
276
+ amount: body?.amount
277
+ },
278
+ redirectUrl: void 0,
279
+ returnUrl: null,
280
+ nextAction: {
281
+ type: "display_instructions",
282
+ paymentInstructions: {
283
+ alias: "tickean.demo",
284
+ cvu: "0000003100010000000001",
285
+ amount: body?.amount
286
+ }
287
+ },
288
+ requiresAction: false
289
+ };
290
+ } else {
291
+ lastPayment = {
292
+ id: `pay_${Date.now()}`,
293
+ paymentStatus: "PENDING",
294
+ paymentMethod: method,
295
+ redirectUrl: "https://example.com/pay/demo",
296
+ returnUrl: null,
297
+ nextAction: {
298
+ type: "redirect",
299
+ url: "https://example.com/pay/demo"
300
+ },
301
+ requiresAction: true
302
+ };
303
+ }
304
+ return lastPayment;
305
+ }
306
+ if (path === "/v1/checkout/payments/confirm" && init.method === "POST") {
307
+ paymentConfirmed = true;
308
+ lastPayment = {
309
+ ...lastPayment || { id: `pay_${Date.now()}` },
310
+ paymentStatus: "COMPLETED",
311
+ nextAction: { type: "none" },
312
+ requiresAction: false
185
313
  };
314
+ return lastPayment;
186
315
  }
187
316
  if (path === "/v1/checkout/payments/status") {
188
317
  return {
189
- status: "PENDING",
318
+ status: paymentConfirmed ? "COMPLETED" : "PENDING",
319
+ requiresAction: Boolean(
320
+ lastPayment?.nextAction && lastPayment.nextAction.type !== "none" && !paymentConfirmed
321
+ ),
322
+ phase: paymentConfirmed ? "completed" : lastPayment ? "requires_action" : "browsing",
323
+ nextAction: lastPayment?.nextAction || { type: "none" },
324
+ payment: lastPayment,
190
325
  purchase: {
191
326
  id: purchaseId,
192
- status: "PENDING",
327
+ status: paymentConfirmed ? "COMPLETED" : "PENDING",
193
328
  totalPrice: 0,
194
329
  currency: "ARS",
195
330
  shoppingCartReference: cartRef
196
331
  }
197
332
  };
198
333
  }
199
- throw new Error(`Demo transport: unhandled ${init.method || "GET"} ${path}`);
334
+ throw new Error(
335
+ `Demo transport: unhandled ${init.method || "GET"} ${path}`
336
+ );
200
337
  }
201
338
  };
202
339
  }
203
340
 
204
- // src/types.ts
205
- var TickeanError = class extends Error {
206
- constructor(payload, status) {
207
- super(payload.message);
208
- this.name = "TickeanError";
209
- this.code = payload.code;
210
- this.details = payload.details;
211
- this.status = status;
212
- }
213
- };
214
-
215
341
  // src/http.ts
216
342
  function createHttpTransport(options) {
217
343
  const fetchImpl = options.fetchImpl || fetch;
@@ -224,6 +350,9 @@ function createHttpTransport(options) {
224
350
  if (init.sessionToken) {
225
351
  headers["X-Tickean-Checkout-Session"] = init.sessionToken;
226
352
  }
353
+ if (init.idempotencyKey) {
354
+ headers["Idempotency-Key"] = init.idempotencyKey;
355
+ }
227
356
  const response = await fetchImpl(
228
357
  `${options.apiBaseUrl.replace(/\/$/, "")}${path}`,
229
358
  {
@@ -233,6 +362,7 @@ function createHttpTransport(options) {
233
362
  credentials: "omit"
234
363
  }
235
364
  );
365
+ const requestId = response.headers.get("X-Request-Id") || response.headers.get("x-request-id") || void 0;
236
366
  const json = await response.json().catch(() => ({}));
237
367
  if (!response.ok) {
238
368
  const err = json?.error || {};
@@ -242,7 +372,8 @@ function createHttpTransport(options) {
242
372
  message: err.message || response.statusText || "Request failed",
243
373
  details: err.details
244
374
  },
245
- response.status
375
+ response.status,
376
+ requestId
246
377
  );
247
378
  }
248
379
  return json;
@@ -250,7 +381,7 @@ function createHttpTransport(options) {
250
381
  };
251
382
  }
252
383
 
253
- // src/index.ts
384
+ // src/client.ts
254
385
  function createTickean(options) {
255
386
  if (!options.publishableKey && !options.demo) {
256
387
  throw new TickeanError({
@@ -277,6 +408,9 @@ function createTickean(options) {
277
408
  get session() {
278
409
  return session;
279
410
  },
411
+ set session(value2) {
412
+ session = value2;
413
+ },
280
414
  async createSession(params) {
281
415
  session = await transport.request("/v1/checkout/sessions", {
282
416
  method: "POST",
@@ -284,6 +418,40 @@ function createTickean(options) {
284
418
  });
285
419
  return session;
286
420
  },
421
+ async exchangeRecovery(params) {
422
+ const result = await transport.request("/v1/checkout/recovery/exchange", {
423
+ method: "POST",
424
+ body: params
425
+ });
426
+ session = {
427
+ sessionId: result.sessionId,
428
+ sessionToken: result.sessionToken,
429
+ expiresAt: result.expiresAt,
430
+ event: result.event,
431
+ capabilities: result.capabilities || {},
432
+ shoppingCartReference: result.shoppingCartReference,
433
+ nextAction: result.nextAction,
434
+ phase: result.phase
435
+ };
436
+ return result;
437
+ },
438
+ async getSession() {
439
+ const active = requireSession();
440
+ const result = await transport.request(
441
+ "/v1/checkout/session",
442
+ {
443
+ sessionToken: active.sessionToken
444
+ }
445
+ );
446
+ session = {
447
+ ...active,
448
+ ...result,
449
+ sessionToken: active.sessionToken,
450
+ event: result.event || active.event,
451
+ capabilities: result.capabilities || active.capabilities || {}
452
+ };
453
+ return session;
454
+ },
287
455
  async getCatalog() {
288
456
  const active = requireSession();
289
457
  return transport.request("/v1/checkout/catalog", {
@@ -298,6 +466,14 @@ function createTickean(options) {
298
466
  sessionToken: active.sessionToken
299
467
  });
300
468
  },
469
+ async lookupBuyer(params) {
470
+ const active = requireSession();
471
+ return transport.request("/v1/checkout/buyer/lookup", {
472
+ method: "POST",
473
+ body: params,
474
+ sessionToken: active.sessionToken
475
+ });
476
+ },
301
477
  async sendOtp(params) {
302
478
  const active = requireSession();
303
479
  return transport.request("/v1/checkout/otp/send", {
@@ -316,18 +492,32 @@ function createTickean(options) {
316
492
  },
317
493
  async createPurchase(params) {
318
494
  const active = requireSession();
495
+ const { idempotencyKey, ...body } = params;
319
496
  return transport.request("/v1/checkout/purchases", {
320
497
  method: "POST",
321
- body: params,
322
- sessionToken: active.sessionToken
498
+ body,
499
+ sessionToken: active.sessionToken,
500
+ idempotencyKey
323
501
  });
324
502
  },
325
503
  async createPayment(params) {
326
504
  const active = requireSession();
505
+ const { idempotencyKey, ...body } = params;
327
506
  return transport.request("/v1/checkout/payments", {
328
507
  method: "POST",
329
- body: params,
330
- sessionToken: active.sessionToken
508
+ body,
509
+ sessionToken: active.sessionToken,
510
+ idempotencyKey
511
+ });
512
+ },
513
+ async confirmPayment(params) {
514
+ const active = requireSession();
515
+ const { idempotencyKey, ...body } = params || {};
516
+ return transport.request("/v1/checkout/payments/confirm", {
517
+ method: "POST",
518
+ body,
519
+ sessionToken: active.sessionToken,
520
+ idempotencyKey
331
521
  });
332
522
  },
333
523
  async getPaymentStatus() {
@@ -348,13 +538,17 @@ function createTickean(options) {
348
538
  });
349
539
  }
350
540
  const status = await this.getPaymentStatus();
351
- if (["COMPLETED", "CONFIRMED", "PAID"].includes(
541
+ if (["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
352
542
  String(status.status || "").toUpperCase()
353
- ) || ["COMPLETED", "CONFIRMED", "PAID"].includes(
543
+ ) || ["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
354
544
  String(status.purchase?.status || "").toUpperCase()
355
545
  )) {
356
546
  return status;
357
547
  }
548
+ const nextType = status.nextAction?.type;
549
+ if (status.nextAction && nextType && nextType !== "none" && nextType !== "display_instructions" && status.requiresAction) {
550
+ return status;
551
+ }
358
552
  await new Promise((resolve) => setTimeout(resolve, intervalMs));
359
553
  }
360
554
  throw new TickeanError({
@@ -364,7 +558,4368 @@ function createTickean(options) {
364
558
  }
365
559
  };
366
560
  }
561
+
562
+ // src/state.ts
563
+ function createInitialState(partial) {
564
+ return {
565
+ phase: "initializing",
566
+ session: null,
567
+ event: null,
568
+ cart: [],
569
+ discountCode: null,
570
+ quote: null,
571
+ isQuoting: false,
572
+ buyer: null,
573
+ buyerVerified: false,
574
+ otpSent: false,
575
+ purchase: null,
576
+ payment: null,
577
+ nextAction: { type: "none" },
578
+ error: null,
579
+ loading: true,
580
+ ...partial
581
+ };
582
+ }
583
+ function derivePhase(state) {
584
+ if (state.phase === "completed" || state.phase === "failed" || state.phase === "expired" || state.phase === "purchasing" || state.phase === "processing" || state.phase === "requires_action" || state.phase === "initializing") {
585
+ return state.phase;
586
+ }
587
+ if (state.isQuoting) return "quoting";
588
+ if (state.otpSent && !state.buyerVerified) return "verifying_buyer";
589
+ if (state.buyerVerified && state.cart.length > 0) return "ready_to_purchase";
590
+ return "browsing";
591
+ }
592
+ function checkoutReducer(state, action) {
593
+ switch (action.type) {
594
+ case "INIT_START":
595
+ return { ...state, loading: true, error: null, phase: "initializing" };
596
+ case "INIT_SUCCESS": {
597
+ const next = {
598
+ ...state,
599
+ loading: false,
600
+ error: null,
601
+ session: action.session,
602
+ event: action.event,
603
+ phase: "browsing"
604
+ };
605
+ return { ...next, phase: derivePhase(next) };
606
+ }
607
+ case "INIT_FAILURE":
608
+ return {
609
+ ...state,
610
+ loading: false,
611
+ error: action.error,
612
+ phase: "failed"
613
+ };
614
+ case "SET_CART": {
615
+ const next = { ...state, cart: action.cart, error: null };
616
+ return { ...next, phase: derivePhase(next) };
617
+ }
618
+ case "SET_DISCOUNT":
619
+ return { ...state, discountCode: action.discountCode };
620
+ case "QUOTE_START": {
621
+ const next = { ...state, isQuoting: true, error: null };
622
+ return { ...next, phase: "quoting" };
623
+ }
624
+ case "QUOTE_SUCCESS": {
625
+ const next = {
626
+ ...state,
627
+ isQuoting: false,
628
+ quote: action.quote
629
+ };
630
+ return { ...next, phase: derivePhase(next) };
631
+ }
632
+ case "QUOTE_FAILURE":
633
+ return {
634
+ ...state,
635
+ isQuoting: false,
636
+ error: action.error,
637
+ phase: derivePhase({ ...state, isQuoting: false })
638
+ };
639
+ case "OTP_SENT": {
640
+ const next = { ...state, otpSent: true, error: null };
641
+ return { ...next, phase: "verifying_buyer" };
642
+ }
643
+ case "OTP_VERIFIED": {
644
+ const next = {
645
+ ...state,
646
+ buyer: action.buyer,
647
+ buyerVerified: true,
648
+ otpSent: true,
649
+ error: null
650
+ };
651
+ return { ...next, phase: derivePhase(next) };
652
+ }
653
+ case "SET_EVENT":
654
+ return { ...state, event: action.event };
655
+ case "MERGE_UNLOCKED_OPTIONS": {
656
+ if (!state.event || !action.options.length) return state;
657
+ const shows = state.event.shows.map((show) => ({
658
+ ...show,
659
+ showOptions: [...show.showOptions]
660
+ }));
661
+ const byId = /* @__PURE__ */ new Map();
662
+ for (const show of shows) {
663
+ for (const opt of show.showOptions) byId.set(opt.id, opt);
664
+ }
665
+ for (const unlocked of action.options) {
666
+ if (byId.has(unlocked.id)) continue;
667
+ const showId = unlocked.showId;
668
+ let target = showId ? shows.find((s) => s.id === showId) : void 0;
669
+ if (!target) target = shows[0];
670
+ if (!target) continue;
671
+ const option = { ...unlocked };
672
+ target.showOptions.push(option);
673
+ byId.set(option.id, option);
674
+ }
675
+ return {
676
+ ...state,
677
+ event: { ...state.event, shows }
678
+ };
679
+ }
680
+ case "PURCHASE_START":
681
+ return { ...state, phase: "purchasing", error: null };
682
+ case "PURCHASE_SUCCESS": {
683
+ const requiresProviderAction = action.nextAction.type !== "none" && action.nextAction.type !== "display_instructions";
684
+ return {
685
+ ...state,
686
+ purchase: action.purchase,
687
+ payment: action.payment,
688
+ nextAction: action.nextAction,
689
+ phase: requiresProviderAction ? "requires_action" : "processing",
690
+ error: null
691
+ };
692
+ }
693
+ case "PURCHASE_FAILURE": {
694
+ const next = {
695
+ ...state,
696
+ error: action.error,
697
+ phase: "browsing"
698
+ };
699
+ return { ...next, phase: derivePhase(next) };
700
+ }
701
+ case "SET_NEXT_ACTION":
702
+ return {
703
+ ...state,
704
+ nextAction: action.nextAction,
705
+ payment: action.payment === void 0 ? state.payment : action.payment,
706
+ phase: action.nextAction.type !== "none" && action.nextAction.type !== "display_instructions" ? "requires_action" : state.phase === "requires_action" ? "processing" : state.phase
707
+ };
708
+ case "RESET_PAYMENT_FLOW": {
709
+ const next = {
710
+ ...state,
711
+ payment: null,
712
+ nextAction: { type: "none" },
713
+ error: null,
714
+ phase: "browsing"
715
+ };
716
+ return { ...next, phase: derivePhase(next) };
717
+ }
718
+ case "PROCESSING":
719
+ return { ...state, phase: "processing" };
720
+ case "COMPLETED":
721
+ return {
722
+ ...state,
723
+ phase: "completed",
724
+ purchase: action.purchase ?? state.purchase,
725
+ nextAction: { type: "none" },
726
+ error: null
727
+ };
728
+ case "FAILED":
729
+ return { ...state, phase: "failed", error: action.error };
730
+ case "EXPIRED":
731
+ return { ...state, phase: "expired" };
732
+ case "CLEAR_ERROR":
733
+ return { ...state, error: null };
734
+ case "REHYDRATE": {
735
+ const next = { ...state, ...action.partial };
736
+ return { ...next, phase: derivePhase(next) };
737
+ }
738
+ default:
739
+ return state;
740
+ }
741
+ }
742
+
743
+ // src/persistence.ts
744
+ function createMemoryPersistence() {
745
+ const store = /* @__PURE__ */ new Map();
746
+ return {
747
+ get(key) {
748
+ return store.get(key) ?? null;
749
+ },
750
+ set(key, value2) {
751
+ store.set(key, { ...value2 });
752
+ },
753
+ remove(key) {
754
+ store.delete(key);
755
+ }
756
+ };
757
+ }
758
+ function createSessionStoragePersistence(storage) {
759
+ const getStorage = () => {
760
+ if (storage) return storage;
761
+ try {
762
+ if (typeof sessionStorage !== "undefined") return sessionStorage;
763
+ } catch {
764
+ }
765
+ return null;
766
+ };
767
+ return {
768
+ get(key) {
769
+ const s = getStorage();
770
+ if (!s) return null;
771
+ try {
772
+ const raw = s.getItem(key);
773
+ if (!raw) return null;
774
+ return JSON.parse(raw);
775
+ } catch {
776
+ return null;
777
+ }
778
+ },
779
+ set(key, value2) {
780
+ const s = getStorage();
781
+ if (!s) return;
782
+ try {
783
+ const safe = {
784
+ sessionToken: value2.sessionToken,
785
+ eventSlug: value2.eventSlug,
786
+ cart: value2.cart,
787
+ discountCode: value2.discountCode,
788
+ phase: value2.phase,
789
+ buyerVerified: value2.buyerVerified,
790
+ purchaseId: value2.purchaseId
791
+ };
792
+ s.setItem(key, JSON.stringify(safe));
793
+ } catch {
794
+ }
795
+ },
796
+ remove(key) {
797
+ const s = getStorage();
798
+ if (!s) return;
799
+ try {
800
+ s.removeItem(key);
801
+ } catch {
802
+ }
803
+ }
804
+ };
805
+ }
806
+
807
+ // src/telemetry.ts
808
+ function createNoopTelemetry() {
809
+ return {
810
+ track() {
811
+ }
812
+ };
813
+ }
814
+ function createEventEmitterTelemetry(listeners = []) {
815
+ const subs = new Set(listeners);
816
+ return {
817
+ track(event) {
818
+ for (const listener of subs) {
819
+ try {
820
+ listener(event);
821
+ } catch {
822
+ }
823
+ }
824
+ },
825
+ subscribe(listener) {
826
+ subs.add(listener);
827
+ return () => {
828
+ subs.delete(listener);
829
+ };
830
+ }
831
+ };
832
+ }
833
+
834
+ // ../../node_modules/engine.io-parser/build/esm/commons.js
835
+ var PACKET_TYPES = /* @__PURE__ */ Object.create(null);
836
+ PACKET_TYPES["open"] = "0";
837
+ PACKET_TYPES["close"] = "1";
838
+ PACKET_TYPES["ping"] = "2";
839
+ PACKET_TYPES["pong"] = "3";
840
+ PACKET_TYPES["message"] = "4";
841
+ PACKET_TYPES["upgrade"] = "5";
842
+ PACKET_TYPES["noop"] = "6";
843
+ var PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
844
+ Object.keys(PACKET_TYPES).forEach((key) => {
845
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
846
+ });
847
+ var ERROR_PACKET = { type: "error", data: "parser error" };
848
+
849
+ // ../../node_modules/engine.io-parser/build/esm/encodePacket.browser.js
850
+ var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
851
+ var withNativeArrayBuffer = typeof ArrayBuffer === "function";
852
+ var isView = (obj) => {
853
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
854
+ };
855
+ var encodePacket = ({ type, data }, supportsBinary, callback) => {
856
+ if (withNativeBlob && data instanceof Blob) {
857
+ if (supportsBinary) {
858
+ return callback(data);
859
+ } else {
860
+ return encodeBlobAsBase64(data, callback);
861
+ }
862
+ } else if (withNativeArrayBuffer && (data instanceof ArrayBuffer || isView(data))) {
863
+ if (supportsBinary) {
864
+ return callback(data);
865
+ } else {
866
+ return encodeBlobAsBase64(new Blob([data]), callback);
867
+ }
868
+ }
869
+ return callback(PACKET_TYPES[type] + (data || ""));
870
+ };
871
+ var encodeBlobAsBase64 = (data, callback) => {
872
+ const fileReader = new FileReader();
873
+ fileReader.onload = function() {
874
+ const content = fileReader.result.split(",")[1];
875
+ callback("b" + (content || ""));
876
+ };
877
+ return fileReader.readAsDataURL(data);
878
+ };
879
+ function toArray(data) {
880
+ if (data instanceof Uint8Array) {
881
+ return data;
882
+ } else if (data instanceof ArrayBuffer) {
883
+ return new Uint8Array(data);
884
+ } else {
885
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
886
+ }
887
+ }
888
+ var TEXT_ENCODER;
889
+ function encodePacketToBinary(packet, callback) {
890
+ if (withNativeBlob && packet.data instanceof Blob) {
891
+ return packet.data.arrayBuffer().then(toArray).then(callback);
892
+ } else if (withNativeArrayBuffer && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
893
+ return callback(toArray(packet.data));
894
+ }
895
+ encodePacket(packet, false, (encoded) => {
896
+ if (!TEXT_ENCODER) {
897
+ TEXT_ENCODER = new TextEncoder();
898
+ }
899
+ callback(TEXT_ENCODER.encode(encoded));
900
+ });
901
+ }
902
+
903
+ // ../../node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js
904
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
905
+ var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
906
+ for (let i = 0; i < chars.length; i++) {
907
+ lookup[chars.charCodeAt(i)] = i;
908
+ }
909
+ var decode = (base64) => {
910
+ let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
911
+ if (base64[base64.length - 1] === "=") {
912
+ bufferLength--;
913
+ if (base64[base64.length - 2] === "=") {
914
+ bufferLength--;
915
+ }
916
+ }
917
+ const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
918
+ for (i = 0; i < len; i += 4) {
919
+ encoded1 = lookup[base64.charCodeAt(i)];
920
+ encoded2 = lookup[base64.charCodeAt(i + 1)];
921
+ encoded3 = lookup[base64.charCodeAt(i + 2)];
922
+ encoded4 = lookup[base64.charCodeAt(i + 3)];
923
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
924
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
925
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
926
+ }
927
+ return arraybuffer;
928
+ };
929
+
930
+ // ../../node_modules/engine.io-parser/build/esm/decodePacket.browser.js
931
+ var withNativeArrayBuffer2 = typeof ArrayBuffer === "function";
932
+ var decodePacket = (encodedPacket, binaryType) => {
933
+ if (typeof encodedPacket !== "string") {
934
+ return {
935
+ type: "message",
936
+ data: mapBinary(encodedPacket, binaryType)
937
+ };
938
+ }
939
+ const type = encodedPacket.charAt(0);
940
+ if (type === "b") {
941
+ return {
942
+ type: "message",
943
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
944
+ };
945
+ }
946
+ const packetType = PACKET_TYPES_REVERSE[type];
947
+ if (!packetType) {
948
+ return ERROR_PACKET;
949
+ }
950
+ return encodedPacket.length > 1 ? {
951
+ type: PACKET_TYPES_REVERSE[type],
952
+ data: encodedPacket.substring(1)
953
+ } : {
954
+ type: PACKET_TYPES_REVERSE[type]
955
+ };
956
+ };
957
+ var decodeBase64Packet = (data, binaryType) => {
958
+ if (withNativeArrayBuffer2) {
959
+ const decoded = decode(data);
960
+ return mapBinary(decoded, binaryType);
961
+ } else {
962
+ return { base64: true, data };
963
+ }
964
+ };
965
+ var mapBinary = (data, binaryType) => {
966
+ switch (binaryType) {
967
+ case "blob":
968
+ if (data instanceof Blob) {
969
+ return data;
970
+ } else {
971
+ return new Blob([data]);
972
+ }
973
+ case "arraybuffer":
974
+ default:
975
+ if (data instanceof ArrayBuffer) {
976
+ return data;
977
+ } else {
978
+ return data.buffer;
979
+ }
980
+ }
981
+ };
982
+
983
+ // ../../node_modules/engine.io-parser/build/esm/index.js
984
+ var SEPARATOR = String.fromCharCode(30);
985
+ var encodePayload = (packets, callback) => {
986
+ const length = packets.length;
987
+ const encodedPackets = new Array(length);
988
+ let count = 0;
989
+ packets.forEach((packet, i) => {
990
+ encodePacket(packet, false, (encodedPacket) => {
991
+ encodedPackets[i] = encodedPacket;
992
+ if (++count === length) {
993
+ callback(encodedPackets.join(SEPARATOR));
994
+ }
995
+ });
996
+ });
997
+ };
998
+ var decodePayload = (encodedPayload, binaryType) => {
999
+ const encodedPackets = encodedPayload.split(SEPARATOR);
1000
+ const packets = [];
1001
+ for (let i = 0; i < encodedPackets.length; i++) {
1002
+ const decodedPacket = decodePacket(encodedPackets[i], binaryType);
1003
+ packets.push(decodedPacket);
1004
+ if (decodedPacket.type === "error") {
1005
+ break;
1006
+ }
1007
+ }
1008
+ return packets;
1009
+ };
1010
+ function createPacketEncoderStream() {
1011
+ return new TransformStream({
1012
+ transform(packet, controller) {
1013
+ encodePacketToBinary(packet, (encodedPacket) => {
1014
+ const payloadLength = encodedPacket.length;
1015
+ let header;
1016
+ if (payloadLength < 126) {
1017
+ header = new Uint8Array(1);
1018
+ new DataView(header.buffer).setUint8(0, payloadLength);
1019
+ } else if (payloadLength < 65536) {
1020
+ header = new Uint8Array(3);
1021
+ const view = new DataView(header.buffer);
1022
+ view.setUint8(0, 126);
1023
+ view.setUint16(1, payloadLength);
1024
+ } else {
1025
+ header = new Uint8Array(9);
1026
+ const view = new DataView(header.buffer);
1027
+ view.setUint8(0, 127);
1028
+ view.setBigUint64(1, BigInt(payloadLength));
1029
+ }
1030
+ if (packet.data && typeof packet.data !== "string") {
1031
+ header[0] |= 128;
1032
+ }
1033
+ controller.enqueue(header);
1034
+ controller.enqueue(encodedPacket);
1035
+ });
1036
+ }
1037
+ });
1038
+ }
1039
+ var TEXT_DECODER;
1040
+ function totalLength(chunks) {
1041
+ return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
1042
+ }
1043
+ function concatChunks(chunks, size) {
1044
+ if (chunks[0].length === size) {
1045
+ return chunks.shift();
1046
+ }
1047
+ const buffer = new Uint8Array(size);
1048
+ let j = 0;
1049
+ for (let i = 0; i < size; i++) {
1050
+ buffer[i] = chunks[0][j++];
1051
+ if (j === chunks[0].length) {
1052
+ chunks.shift();
1053
+ j = 0;
1054
+ }
1055
+ }
1056
+ if (chunks.length && j < chunks[0].length) {
1057
+ chunks[0] = chunks[0].slice(j);
1058
+ }
1059
+ return buffer;
1060
+ }
1061
+ function createPacketDecoderStream(maxPayload, binaryType) {
1062
+ if (!TEXT_DECODER) {
1063
+ TEXT_DECODER = new TextDecoder();
1064
+ }
1065
+ const chunks = [];
1066
+ let state = 0;
1067
+ let expectedLength = -1;
1068
+ let isBinary2 = false;
1069
+ return new TransformStream({
1070
+ transform(chunk, controller) {
1071
+ chunks.push(chunk);
1072
+ while (true) {
1073
+ if (state === 0) {
1074
+ if (totalLength(chunks) < 1) {
1075
+ break;
1076
+ }
1077
+ const header = concatChunks(chunks, 1);
1078
+ isBinary2 = (header[0] & 128) === 128;
1079
+ expectedLength = header[0] & 127;
1080
+ if (expectedLength < 126) {
1081
+ state = 3;
1082
+ } else if (expectedLength === 126) {
1083
+ state = 1;
1084
+ } else {
1085
+ state = 2;
1086
+ }
1087
+ } else if (state === 1) {
1088
+ if (totalLength(chunks) < 2) {
1089
+ break;
1090
+ }
1091
+ const headerArray = concatChunks(chunks, 2);
1092
+ expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
1093
+ state = 3;
1094
+ } else if (state === 2) {
1095
+ if (totalLength(chunks) < 8) {
1096
+ break;
1097
+ }
1098
+ const headerArray = concatChunks(chunks, 8);
1099
+ const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
1100
+ const n = view.getUint32(0);
1101
+ if (n > Math.pow(2, 53 - 32) - 1) {
1102
+ controller.enqueue(ERROR_PACKET);
1103
+ break;
1104
+ }
1105
+ expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
1106
+ state = 3;
1107
+ } else {
1108
+ if (totalLength(chunks) < expectedLength) {
1109
+ break;
1110
+ }
1111
+ const data = concatChunks(chunks, expectedLength);
1112
+ controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
1113
+ state = 0;
1114
+ }
1115
+ if (expectedLength === 0 || expectedLength > maxPayload) {
1116
+ controller.enqueue(ERROR_PACKET);
1117
+ break;
1118
+ }
1119
+ }
1120
+ }
1121
+ });
1122
+ }
1123
+ var protocol = 4;
1124
+
1125
+ // ../../node_modules/@socket.io/component-emitter/lib/esm/index.js
1126
+ function Emitter(obj) {
1127
+ if (obj) return mixin(obj);
1128
+ }
1129
+ function mixin(obj) {
1130
+ for (var key in Emitter.prototype) {
1131
+ obj[key] = Emitter.prototype[key];
1132
+ }
1133
+ return obj;
1134
+ }
1135
+ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
1136
+ this._callbacks = this._callbacks || {};
1137
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
1138
+ return this;
1139
+ };
1140
+ Emitter.prototype.once = function(event, fn) {
1141
+ function on2() {
1142
+ this.off(event, on2);
1143
+ fn.apply(this, arguments);
1144
+ }
1145
+ on2.fn = fn;
1146
+ this.on(event, on2);
1147
+ return this;
1148
+ };
1149
+ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
1150
+ this._callbacks = this._callbacks || {};
1151
+ if (0 == arguments.length) {
1152
+ this._callbacks = {};
1153
+ return this;
1154
+ }
1155
+ var callbacks = this._callbacks["$" + event];
1156
+ if (!callbacks) return this;
1157
+ if (1 == arguments.length) {
1158
+ delete this._callbacks["$" + event];
1159
+ return this;
1160
+ }
1161
+ var cb;
1162
+ for (var i = 0; i < callbacks.length; i++) {
1163
+ cb = callbacks[i];
1164
+ if (cb === fn || cb.fn === fn) {
1165
+ callbacks.splice(i, 1);
1166
+ break;
1167
+ }
1168
+ }
1169
+ if (callbacks.length === 0) {
1170
+ delete this._callbacks["$" + event];
1171
+ }
1172
+ return this;
1173
+ };
1174
+ Emitter.prototype.emit = function(event) {
1175
+ this._callbacks = this._callbacks || {};
1176
+ var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
1177
+ for (var i = 1; i < arguments.length; i++) {
1178
+ args[i - 1] = arguments[i];
1179
+ }
1180
+ if (callbacks) {
1181
+ callbacks = callbacks.slice(0);
1182
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
1183
+ callbacks[i].apply(this, args);
1184
+ }
1185
+ }
1186
+ return this;
1187
+ };
1188
+ Emitter.prototype.emitReserved = Emitter.prototype.emit;
1189
+ Emitter.prototype.listeners = function(event) {
1190
+ this._callbacks = this._callbacks || {};
1191
+ return this._callbacks["$" + event] || [];
1192
+ };
1193
+ Emitter.prototype.hasListeners = function(event) {
1194
+ return !!this.listeners(event).length;
1195
+ };
1196
+
1197
+ // ../../node_modules/engine.io-client/build/esm/globals.js
1198
+ var nextTick = (() => {
1199
+ const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
1200
+ if (isPromiseAvailable) {
1201
+ return (cb) => Promise.resolve().then(cb);
1202
+ } else {
1203
+ return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
1204
+ }
1205
+ })();
1206
+ var globalThisShim = (() => {
1207
+ if (typeof self !== "undefined") {
1208
+ return self;
1209
+ } else if (typeof window !== "undefined") {
1210
+ return window;
1211
+ } else {
1212
+ return Function("return this")();
1213
+ }
1214
+ })();
1215
+ var defaultBinaryType = "arraybuffer";
1216
+ function createCookieJar() {
1217
+ }
1218
+
1219
+ // ../../node_modules/engine.io-client/build/esm/util.js
1220
+ function pick(obj, ...attr) {
1221
+ return attr.reduce((acc, k) => {
1222
+ if (obj.hasOwnProperty(k)) {
1223
+ acc[k] = obj[k];
1224
+ }
1225
+ return acc;
1226
+ }, {});
1227
+ }
1228
+ var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
1229
+ var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
1230
+ function installTimerFunctions(obj, opts) {
1231
+ if (opts.useNativeTimers) {
1232
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
1233
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
1234
+ } else {
1235
+ obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
1236
+ obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
1237
+ }
1238
+ }
1239
+ var BASE64_OVERHEAD = 1.33;
1240
+ function byteLength(obj) {
1241
+ if (typeof obj === "string") {
1242
+ return utf8Length(obj);
1243
+ }
1244
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
1245
+ }
1246
+ function utf8Length(str) {
1247
+ let c = 0, length = 0;
1248
+ for (let i = 0, l = str.length; i < l; i++) {
1249
+ c = str.charCodeAt(i);
1250
+ if (c < 128) {
1251
+ length += 1;
1252
+ } else if (c < 2048) {
1253
+ length += 2;
1254
+ } else if (c < 55296 || c >= 57344) {
1255
+ length += 3;
1256
+ } else {
1257
+ i++;
1258
+ length += 4;
1259
+ }
1260
+ }
1261
+ return length;
1262
+ }
1263
+ function randomString() {
1264
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
1265
+ }
1266
+
1267
+ // ../../node_modules/engine.io-client/build/esm/contrib/parseqs.js
1268
+ function encode(obj) {
1269
+ let str = "";
1270
+ for (let i in obj) {
1271
+ if (obj.hasOwnProperty(i)) {
1272
+ if (str.length)
1273
+ str += "&";
1274
+ str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
1275
+ }
1276
+ }
1277
+ return str;
1278
+ }
1279
+ function decode2(qs) {
1280
+ let qry = {};
1281
+ let pairs = qs.split("&");
1282
+ for (let i = 0, l = pairs.length; i < l; i++) {
1283
+ let pair = pairs[i].split("=");
1284
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
1285
+ }
1286
+ return qry;
1287
+ }
1288
+
1289
+ // ../../node_modules/engine.io-client/build/esm/transport.js
1290
+ var TransportError = class extends Error {
1291
+ constructor(reason, description, context) {
1292
+ super(reason);
1293
+ this.description = description;
1294
+ this.context = context;
1295
+ this.type = "TransportError";
1296
+ }
1297
+ };
1298
+ var Transport = class extends Emitter {
1299
+ /**
1300
+ * Transport abstract constructor.
1301
+ *
1302
+ * @param {Object} opts - options
1303
+ * @protected
1304
+ */
1305
+ constructor(opts) {
1306
+ super();
1307
+ this.writable = false;
1308
+ installTimerFunctions(this, opts);
1309
+ this.opts = opts;
1310
+ this.query = opts.query;
1311
+ this.socket = opts.socket;
1312
+ this.supportsBinary = !opts.forceBase64;
1313
+ }
1314
+ /**
1315
+ * Emits an error.
1316
+ *
1317
+ * @param {String} reason
1318
+ * @param description
1319
+ * @param context - the error context
1320
+ * @return {Transport} for chaining
1321
+ * @protected
1322
+ */
1323
+ onError(reason, description, context) {
1324
+ super.emitReserved("error", new TransportError(reason, description, context));
1325
+ return this;
1326
+ }
1327
+ /**
1328
+ * Opens the transport.
1329
+ */
1330
+ open() {
1331
+ this.readyState = "opening";
1332
+ this.doOpen();
1333
+ return this;
1334
+ }
1335
+ /**
1336
+ * Closes the transport.
1337
+ */
1338
+ close() {
1339
+ if (this.readyState === "opening" || this.readyState === "open") {
1340
+ this.doClose();
1341
+ this.onClose();
1342
+ }
1343
+ return this;
1344
+ }
1345
+ /**
1346
+ * Sends multiple packets.
1347
+ *
1348
+ * @param {Array} packets
1349
+ */
1350
+ send(packets) {
1351
+ if (this.readyState === "open") {
1352
+ this.write(packets);
1353
+ } else {
1354
+ }
1355
+ }
1356
+ /**
1357
+ * Called upon open
1358
+ *
1359
+ * @protected
1360
+ */
1361
+ onOpen() {
1362
+ this.readyState = "open";
1363
+ this.writable = true;
1364
+ super.emitReserved("open");
1365
+ }
1366
+ /**
1367
+ * Called with data.
1368
+ *
1369
+ * @param {String} data
1370
+ * @protected
1371
+ */
1372
+ onData(data) {
1373
+ const packet = decodePacket(data, this.socket.binaryType);
1374
+ this.onPacket(packet);
1375
+ }
1376
+ /**
1377
+ * Called with a decoded packet.
1378
+ *
1379
+ * @protected
1380
+ */
1381
+ onPacket(packet) {
1382
+ super.emitReserved("packet", packet);
1383
+ }
1384
+ /**
1385
+ * Called upon close.
1386
+ *
1387
+ * @protected
1388
+ */
1389
+ onClose(details) {
1390
+ this.readyState = "closed";
1391
+ super.emitReserved("close", details);
1392
+ }
1393
+ /**
1394
+ * Pauses the transport, in order not to lose packets during an upgrade.
1395
+ *
1396
+ * @param onPause
1397
+ */
1398
+ pause(onPause) {
1399
+ }
1400
+ createUri(schema, query = {}) {
1401
+ return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
1402
+ }
1403
+ _hostname() {
1404
+ const hostname = this.opts.hostname;
1405
+ return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
1406
+ }
1407
+ _port() {
1408
+ if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
1409
+ return ":" + this.opts.port;
1410
+ } else {
1411
+ return "";
1412
+ }
1413
+ }
1414
+ _query(query) {
1415
+ const encodedQuery = encode(query);
1416
+ return encodedQuery.length ? "?" + encodedQuery : "";
1417
+ }
1418
+ };
1419
+
1420
+ // ../../node_modules/engine.io-client/build/esm/transports/polling.js
1421
+ var Polling = class extends Transport {
1422
+ constructor() {
1423
+ super(...arguments);
1424
+ this._polling = false;
1425
+ }
1426
+ get name() {
1427
+ return "polling";
1428
+ }
1429
+ /**
1430
+ * Opens the socket (triggers polling). We write a PING message to determine
1431
+ * when the transport is open.
1432
+ *
1433
+ * @protected
1434
+ */
1435
+ doOpen() {
1436
+ this._poll();
1437
+ }
1438
+ /**
1439
+ * Pauses polling.
1440
+ *
1441
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
1442
+ * @package
1443
+ */
1444
+ pause(onPause) {
1445
+ this.readyState = "pausing";
1446
+ const pause = () => {
1447
+ this.readyState = "paused";
1448
+ onPause();
1449
+ };
1450
+ if (this._polling || !this.writable) {
1451
+ let total = 0;
1452
+ if (this._polling) {
1453
+ total++;
1454
+ this.once("pollComplete", function() {
1455
+ --total || pause();
1456
+ });
1457
+ }
1458
+ if (!this.writable) {
1459
+ total++;
1460
+ this.once("drain", function() {
1461
+ --total || pause();
1462
+ });
1463
+ }
1464
+ } else {
1465
+ pause();
1466
+ }
1467
+ }
1468
+ /**
1469
+ * Starts polling cycle.
1470
+ *
1471
+ * @private
1472
+ */
1473
+ _poll() {
1474
+ this._polling = true;
1475
+ this.doPoll();
1476
+ this.emitReserved("poll");
1477
+ }
1478
+ /**
1479
+ * Overloads onData to detect payloads.
1480
+ *
1481
+ * @protected
1482
+ */
1483
+ onData(data) {
1484
+ const callback = (packet) => {
1485
+ if ("opening" === this.readyState && packet.type === "open") {
1486
+ this.onOpen();
1487
+ }
1488
+ if ("close" === packet.type) {
1489
+ this.onClose({ description: "transport closed by the server" });
1490
+ return false;
1491
+ }
1492
+ this.onPacket(packet);
1493
+ };
1494
+ decodePayload(data, this.socket.binaryType).forEach(callback);
1495
+ if ("closed" !== this.readyState) {
1496
+ this._polling = false;
1497
+ this.emitReserved("pollComplete");
1498
+ if ("open" === this.readyState) {
1499
+ this._poll();
1500
+ } else {
1501
+ }
1502
+ }
1503
+ }
1504
+ /**
1505
+ * For polling, send a close packet.
1506
+ *
1507
+ * @protected
1508
+ */
1509
+ doClose() {
1510
+ const close = () => {
1511
+ this.write([{ type: "close" }]);
1512
+ };
1513
+ if ("open" === this.readyState) {
1514
+ close();
1515
+ } else {
1516
+ this.once("open", close);
1517
+ }
1518
+ }
1519
+ /**
1520
+ * Writes a packets payload.
1521
+ *
1522
+ * @param {Array} packets - data packets
1523
+ * @protected
1524
+ */
1525
+ write(packets) {
1526
+ this.writable = false;
1527
+ encodePayload(packets, (data) => {
1528
+ this.doWrite(data, () => {
1529
+ this.writable = true;
1530
+ this.emitReserved("drain");
1531
+ });
1532
+ });
1533
+ }
1534
+ /**
1535
+ * Generates uri for connection.
1536
+ *
1537
+ * @private
1538
+ */
1539
+ uri() {
1540
+ const schema = this.opts.secure ? "https" : "http";
1541
+ const query = this.query || {};
1542
+ if (false !== this.opts.timestampRequests) {
1543
+ query[this.opts.timestampParam] = randomString();
1544
+ }
1545
+ if (!this.supportsBinary && !query.sid) {
1546
+ query.b64 = 1;
1547
+ }
1548
+ return this.createUri(schema, query);
1549
+ }
1550
+ };
1551
+
1552
+ // ../../node_modules/engine.io-client/build/esm/contrib/has-cors.js
1553
+ var value = false;
1554
+ try {
1555
+ value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
1556
+ } catch (err) {
1557
+ }
1558
+ var hasCORS = value;
1559
+
1560
+ // ../../node_modules/engine.io-client/build/esm/transports/polling-xhr.js
1561
+ function empty() {
1562
+ }
1563
+ var BaseXHR = class extends Polling {
1564
+ /**
1565
+ * XHR Polling constructor.
1566
+ *
1567
+ * @param {Object} opts
1568
+ * @package
1569
+ */
1570
+ constructor(opts) {
1571
+ super(opts);
1572
+ if (typeof location !== "undefined") {
1573
+ const isSSL = "https:" === location.protocol;
1574
+ let port = location.port;
1575
+ if (!port) {
1576
+ port = isSSL ? "443" : "80";
1577
+ }
1578
+ this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
1579
+ }
1580
+ }
1581
+ /**
1582
+ * Sends data.
1583
+ *
1584
+ * @param {String} data - data to send.
1585
+ * @param {Function} fn - called upon flush.
1586
+ * @private
1587
+ */
1588
+ doWrite(data, fn) {
1589
+ const req = this.request({
1590
+ method: "POST",
1591
+ data
1592
+ });
1593
+ req.on("success", fn);
1594
+ req.on("error", (xhrStatus, context) => {
1595
+ this.onError("xhr post error", xhrStatus, context);
1596
+ });
1597
+ }
1598
+ /**
1599
+ * Starts a poll cycle.
1600
+ *
1601
+ * @private
1602
+ */
1603
+ doPoll() {
1604
+ const req = this.request();
1605
+ req.on("data", this.onData.bind(this));
1606
+ req.on("error", (xhrStatus, context) => {
1607
+ this.onError("xhr poll error", xhrStatus, context);
1608
+ });
1609
+ this.pollXhr = req;
1610
+ }
1611
+ };
1612
+ var Request = class _Request extends Emitter {
1613
+ /**
1614
+ * Request constructor
1615
+ *
1616
+ * @param {Object} options
1617
+ * @package
1618
+ */
1619
+ constructor(createRequest, uri, opts) {
1620
+ super();
1621
+ this.createRequest = createRequest;
1622
+ installTimerFunctions(this, opts);
1623
+ this._opts = opts;
1624
+ this._method = opts.method || "GET";
1625
+ this._uri = uri;
1626
+ this._data = void 0 !== opts.data ? opts.data : null;
1627
+ this._create();
1628
+ }
1629
+ /**
1630
+ * Creates the XHR object and sends the request.
1631
+ *
1632
+ * @private
1633
+ */
1634
+ _create() {
1635
+ var _a;
1636
+ const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
1637
+ opts.xdomain = !!this._opts.xd;
1638
+ const xhr = this._xhr = this.createRequest(opts);
1639
+ try {
1640
+ xhr.open(this._method, this._uri, true);
1641
+ try {
1642
+ if (this._opts.extraHeaders) {
1643
+ xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
1644
+ for (let i in this._opts.extraHeaders) {
1645
+ if (this._opts.extraHeaders.hasOwnProperty(i)) {
1646
+ xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
1647
+ }
1648
+ }
1649
+ }
1650
+ } catch (e) {
1651
+ }
1652
+ if ("POST" === this._method) {
1653
+ try {
1654
+ xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
1655
+ } catch (e) {
1656
+ }
1657
+ }
1658
+ try {
1659
+ xhr.setRequestHeader("Accept", "*/*");
1660
+ } catch (e) {
1661
+ }
1662
+ (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
1663
+ if ("withCredentials" in xhr) {
1664
+ xhr.withCredentials = this._opts.withCredentials;
1665
+ }
1666
+ if (this._opts.requestTimeout) {
1667
+ xhr.timeout = this._opts.requestTimeout;
1668
+ }
1669
+ xhr.onreadystatechange = () => {
1670
+ var _a2;
1671
+ if (xhr.readyState === 3) {
1672
+ (_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.parseCookies(
1673
+ // @ts-ignore
1674
+ xhr.getResponseHeader("set-cookie")
1675
+ );
1676
+ }
1677
+ if (4 !== xhr.readyState)
1678
+ return;
1679
+ if (200 === xhr.status || 1223 === xhr.status) {
1680
+ this._onLoad();
1681
+ } else {
1682
+ this.setTimeoutFn(() => {
1683
+ this._onError(typeof xhr.status === "number" ? xhr.status : 0);
1684
+ }, 0);
1685
+ }
1686
+ };
1687
+ xhr.send(this._data);
1688
+ } catch (e) {
1689
+ this.setTimeoutFn(() => {
1690
+ this._onError(e);
1691
+ }, 0);
1692
+ return;
1693
+ }
1694
+ if (typeof document !== "undefined") {
1695
+ this._index = _Request.requestsCount++;
1696
+ _Request.requests[this._index] = this;
1697
+ }
1698
+ }
1699
+ /**
1700
+ * Called upon error.
1701
+ *
1702
+ * @private
1703
+ */
1704
+ _onError(err) {
1705
+ this.emitReserved("error", err, this._xhr);
1706
+ this._cleanup(true);
1707
+ }
1708
+ /**
1709
+ * Cleans up house.
1710
+ *
1711
+ * @private
1712
+ */
1713
+ _cleanup(fromError) {
1714
+ if ("undefined" === typeof this._xhr || null === this._xhr) {
1715
+ return;
1716
+ }
1717
+ this._xhr.onreadystatechange = empty;
1718
+ if (fromError) {
1719
+ try {
1720
+ this._xhr.abort();
1721
+ } catch (e) {
1722
+ }
1723
+ }
1724
+ if (typeof document !== "undefined") {
1725
+ delete _Request.requests[this._index];
1726
+ }
1727
+ this._xhr = null;
1728
+ }
1729
+ /**
1730
+ * Called upon load.
1731
+ *
1732
+ * @private
1733
+ */
1734
+ _onLoad() {
1735
+ const data = this._xhr.responseText;
1736
+ if (data !== null) {
1737
+ this.emitReserved("data", data);
1738
+ this.emitReserved("success");
1739
+ this._cleanup();
1740
+ }
1741
+ }
1742
+ /**
1743
+ * Aborts the request.
1744
+ *
1745
+ * @package
1746
+ */
1747
+ abort() {
1748
+ this._cleanup();
1749
+ }
1750
+ };
1751
+ Request.requestsCount = 0;
1752
+ Request.requests = {};
1753
+ if (typeof document !== "undefined") {
1754
+ if (typeof attachEvent === "function") {
1755
+ attachEvent("onunload", unloadHandler);
1756
+ } else if (typeof addEventListener === "function") {
1757
+ const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
1758
+ addEventListener(terminationEvent, unloadHandler, false);
1759
+ }
1760
+ }
1761
+ function unloadHandler() {
1762
+ for (let i in Request.requests) {
1763
+ if (Request.requests.hasOwnProperty(i)) {
1764
+ Request.requests[i].abort();
1765
+ }
1766
+ }
1767
+ }
1768
+ var hasXHR2 = (function() {
1769
+ const xhr = newRequest({
1770
+ xdomain: false
1771
+ });
1772
+ return xhr && xhr.responseType !== null;
1773
+ })();
1774
+ var XHR = class extends BaseXHR {
1775
+ constructor(opts) {
1776
+ super(opts);
1777
+ const forceBase64 = opts && opts.forceBase64;
1778
+ this.supportsBinary = hasXHR2 && !forceBase64;
1779
+ }
1780
+ request(opts = {}) {
1781
+ Object.assign(opts, { xd: this.xd }, this.opts);
1782
+ return new Request(newRequest, this.uri(), opts);
1783
+ }
1784
+ };
1785
+ function newRequest(opts) {
1786
+ const xdomain = opts.xdomain;
1787
+ try {
1788
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
1789
+ return new XMLHttpRequest();
1790
+ }
1791
+ } catch (e) {
1792
+ }
1793
+ if (!xdomain) {
1794
+ try {
1795
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
1796
+ } catch (e) {
1797
+ }
1798
+ }
1799
+ }
1800
+
1801
+ // ../../node_modules/engine.io-client/build/esm/transports/websocket.js
1802
+ var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
1803
+ var BaseWS = class extends Transport {
1804
+ get name() {
1805
+ return "websocket";
1806
+ }
1807
+ doOpen() {
1808
+ const uri = this.uri();
1809
+ const protocols = this.opts.protocols;
1810
+ const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
1811
+ if (this.opts.extraHeaders) {
1812
+ opts.headers = this.opts.extraHeaders;
1813
+ }
1814
+ try {
1815
+ this.ws = this.createSocket(uri, protocols, opts);
1816
+ } catch (err) {
1817
+ return this.emitReserved("error", err);
1818
+ }
1819
+ this.ws.binaryType = this.socket.binaryType;
1820
+ this.addEventListeners();
1821
+ }
1822
+ /**
1823
+ * Adds event listeners to the socket
1824
+ *
1825
+ * @private
1826
+ */
1827
+ addEventListeners() {
1828
+ this.ws.onopen = () => {
1829
+ if (this.opts.autoUnref) {
1830
+ this.ws._socket.unref();
1831
+ }
1832
+ this.onOpen();
1833
+ };
1834
+ this.ws.onclose = (closeEvent) => this.onClose({
1835
+ description: "websocket connection closed",
1836
+ context: closeEvent
1837
+ });
1838
+ this.ws.onmessage = (ev) => this.onData(ev.data);
1839
+ this.ws.onerror = (e) => this.onError("websocket error", e);
1840
+ }
1841
+ write(packets) {
1842
+ this.writable = false;
1843
+ for (let i = 0; i < packets.length; i++) {
1844
+ const packet = packets[i];
1845
+ const lastPacket = i === packets.length - 1;
1846
+ encodePacket(packet, this.supportsBinary, (data) => {
1847
+ try {
1848
+ this.doWrite(packet, data);
1849
+ } catch (e) {
1850
+ }
1851
+ if (lastPacket) {
1852
+ nextTick(() => {
1853
+ this.writable = true;
1854
+ this.emitReserved("drain");
1855
+ }, this.setTimeoutFn);
1856
+ }
1857
+ });
1858
+ }
1859
+ }
1860
+ doClose() {
1861
+ if (typeof this.ws !== "undefined") {
1862
+ this.ws.onerror = () => {
1863
+ };
1864
+ this.ws.close();
1865
+ this.ws = null;
1866
+ }
1867
+ }
1868
+ /**
1869
+ * Generates uri for connection.
1870
+ *
1871
+ * @private
1872
+ */
1873
+ uri() {
1874
+ const schema = this.opts.secure ? "wss" : "ws";
1875
+ const query = this.query || {};
1876
+ if (this.opts.timestampRequests) {
1877
+ query[this.opts.timestampParam] = randomString();
1878
+ }
1879
+ if (!this.supportsBinary) {
1880
+ query.b64 = 1;
1881
+ }
1882
+ return this.createUri(schema, query);
1883
+ }
1884
+ };
1885
+ var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
1886
+ var WS = class extends BaseWS {
1887
+ createSocket(uri, protocols, opts) {
1888
+ return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
1889
+ }
1890
+ doWrite(_packet, data) {
1891
+ this.ws.send(data);
1892
+ }
1893
+ };
1894
+
1895
+ // ../../node_modules/engine.io-client/build/esm/transports/webtransport.js
1896
+ var WT = class extends Transport {
1897
+ get name() {
1898
+ return "webtransport";
1899
+ }
1900
+ doOpen() {
1901
+ try {
1902
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
1903
+ } catch (err) {
1904
+ return this.emitReserved("error", err);
1905
+ }
1906
+ this._transport.closed.then(() => {
1907
+ this.onClose();
1908
+ }).catch((err) => {
1909
+ this.onError("webtransport error", err);
1910
+ });
1911
+ this._transport.ready.then(() => {
1912
+ this._transport.createBidirectionalStream().then((stream) => {
1913
+ const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
1914
+ const reader = stream.readable.pipeThrough(decoderStream).getReader();
1915
+ const encoderStream = createPacketEncoderStream();
1916
+ encoderStream.readable.pipeTo(stream.writable);
1917
+ this._writer = encoderStream.writable.getWriter();
1918
+ const read = () => {
1919
+ reader.read().then(({ done, value: value2 }) => {
1920
+ if (done) {
1921
+ return;
1922
+ }
1923
+ this.onPacket(value2);
1924
+ read();
1925
+ }).catch((err) => {
1926
+ });
1927
+ };
1928
+ read();
1929
+ const packet = { type: "open" };
1930
+ if (this.query.sid) {
1931
+ packet.data = `{"sid":"${this.query.sid}"}`;
1932
+ }
1933
+ this._writer.write(packet).then(() => this.onOpen());
1934
+ });
1935
+ });
1936
+ }
1937
+ write(packets) {
1938
+ this.writable = false;
1939
+ for (let i = 0; i < packets.length; i++) {
1940
+ const packet = packets[i];
1941
+ const lastPacket = i === packets.length - 1;
1942
+ this._writer.write(packet).then(() => {
1943
+ if (lastPacket) {
1944
+ nextTick(() => {
1945
+ this.writable = true;
1946
+ this.emitReserved("drain");
1947
+ }, this.setTimeoutFn);
1948
+ }
1949
+ });
1950
+ }
1951
+ }
1952
+ doClose() {
1953
+ var _a;
1954
+ (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
1955
+ }
1956
+ };
1957
+
1958
+ // ../../node_modules/engine.io-client/build/esm/transports/index.js
1959
+ var transports = {
1960
+ websocket: WS,
1961
+ webtransport: WT,
1962
+ polling: XHR
1963
+ };
1964
+
1965
+ // ../../node_modules/engine.io-client/build/esm/contrib/parseuri.js
1966
+ var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
1967
+ var parts = [
1968
+ "source",
1969
+ "protocol",
1970
+ "authority",
1971
+ "userInfo",
1972
+ "user",
1973
+ "password",
1974
+ "host",
1975
+ "port",
1976
+ "relative",
1977
+ "path",
1978
+ "directory",
1979
+ "file",
1980
+ "query",
1981
+ "anchor"
1982
+ ];
1983
+ function parse(str) {
1984
+ if (str.length > 8e3) {
1985
+ throw "URI too long";
1986
+ }
1987
+ const src = str, b = str.indexOf("["), e = str.indexOf("]");
1988
+ if (b != -1 && e != -1) {
1989
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
1990
+ }
1991
+ let m = re.exec(str || ""), uri = {}, i = 14;
1992
+ while (i--) {
1993
+ uri[parts[i]] = m[i] || "";
1994
+ }
1995
+ if (b != -1 && e != -1) {
1996
+ uri.source = src;
1997
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
1998
+ uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
1999
+ uri.ipv6uri = true;
2000
+ }
2001
+ uri.pathNames = pathNames(uri, uri["path"]);
2002
+ uri.queryKey = queryKey(uri, uri["query"]);
2003
+ return uri;
2004
+ }
2005
+ function pathNames(obj, path) {
2006
+ const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
2007
+ if (path.slice(0, 1) == "/" || path.length === 0) {
2008
+ names.splice(0, 1);
2009
+ }
2010
+ if (path.slice(-1) == "/") {
2011
+ names.splice(names.length - 1, 1);
2012
+ }
2013
+ return names;
2014
+ }
2015
+ function queryKey(uri, query) {
2016
+ const data = {};
2017
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
2018
+ if ($1) {
2019
+ data[$1] = $2;
2020
+ }
2021
+ });
2022
+ return data;
2023
+ }
2024
+
2025
+ // ../../node_modules/engine.io-client/build/esm/socket.js
2026
+ var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
2027
+ var OFFLINE_EVENT_LISTENERS = [];
2028
+ if (withEventListeners) {
2029
+ addEventListener("offline", () => {
2030
+ OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
2031
+ }, false);
2032
+ }
2033
+ var SocketWithoutUpgrade = class _SocketWithoutUpgrade extends Emitter {
2034
+ /**
2035
+ * Socket constructor.
2036
+ *
2037
+ * @param {String|Object} uri - uri or options
2038
+ * @param {Object} opts - options
2039
+ */
2040
+ constructor(uri, opts) {
2041
+ super();
2042
+ this.binaryType = defaultBinaryType;
2043
+ this.writeBuffer = [];
2044
+ this._prevBufferLen = 0;
2045
+ this._pingInterval = -1;
2046
+ this._pingTimeout = -1;
2047
+ this._maxPayload = -1;
2048
+ this._pingTimeoutTime = Infinity;
2049
+ if (uri && "object" === typeof uri) {
2050
+ opts = uri;
2051
+ uri = null;
2052
+ }
2053
+ if (uri) {
2054
+ const parsedUri = parse(uri);
2055
+ opts.hostname = parsedUri.host;
2056
+ opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
2057
+ opts.port = parsedUri.port;
2058
+ if (parsedUri.query)
2059
+ opts.query = parsedUri.query;
2060
+ } else if (opts.host) {
2061
+ opts.hostname = parse(opts.host).host;
2062
+ }
2063
+ installTimerFunctions(this, opts);
2064
+ this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
2065
+ if (opts.hostname && !opts.port) {
2066
+ opts.port = this.secure ? "443" : "80";
2067
+ }
2068
+ this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
2069
+ this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
2070
+ this.transports = [];
2071
+ this._transportsByName = {};
2072
+ opts.transports.forEach((t) => {
2073
+ const transportName = t.prototype.name;
2074
+ this.transports.push(transportName);
2075
+ this._transportsByName[transportName] = t;
2076
+ });
2077
+ this.opts = Object.assign({
2078
+ path: "/engine.io",
2079
+ agent: false,
2080
+ withCredentials: false,
2081
+ upgrade: true,
2082
+ timestampParam: "t",
2083
+ rememberUpgrade: false,
2084
+ addTrailingSlash: true,
2085
+ rejectUnauthorized: true,
2086
+ perMessageDeflate: {
2087
+ threshold: 1024
2088
+ },
2089
+ transportOptions: {},
2090
+ closeOnBeforeunload: false
2091
+ }, opts);
2092
+ this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
2093
+ if (typeof this.opts.query === "string") {
2094
+ this.opts.query = decode2(this.opts.query);
2095
+ }
2096
+ if (withEventListeners) {
2097
+ if (this.opts.closeOnBeforeunload) {
2098
+ this._beforeunloadEventListener = () => {
2099
+ if (this.transport) {
2100
+ this.transport.removeAllListeners();
2101
+ this.transport.close();
2102
+ }
2103
+ };
2104
+ addEventListener("beforeunload", this._beforeunloadEventListener, false);
2105
+ }
2106
+ if (this.hostname !== "localhost") {
2107
+ this._offlineEventListener = () => {
2108
+ this._onClose("transport close", {
2109
+ description: "network connection lost"
2110
+ });
2111
+ };
2112
+ OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
2113
+ }
2114
+ }
2115
+ if (this.opts.withCredentials) {
2116
+ this._cookieJar = createCookieJar();
2117
+ }
2118
+ this._open();
2119
+ }
2120
+ /**
2121
+ * Creates transport of the given type.
2122
+ *
2123
+ * @param {String} name - transport name
2124
+ * @return {Transport}
2125
+ * @private
2126
+ */
2127
+ createTransport(name) {
2128
+ const query = Object.assign({}, this.opts.query);
2129
+ query.EIO = protocol;
2130
+ query.transport = name;
2131
+ if (this.id)
2132
+ query.sid = this.id;
2133
+ const opts = Object.assign({}, this.opts, {
2134
+ query,
2135
+ socket: this,
2136
+ hostname: this.hostname,
2137
+ secure: this.secure,
2138
+ port: this.port
2139
+ }, this.opts.transportOptions[name]);
2140
+ return new this._transportsByName[name](opts);
2141
+ }
2142
+ /**
2143
+ * Initializes transport to use and starts probe.
2144
+ *
2145
+ * @private
2146
+ */
2147
+ _open() {
2148
+ if (this.transports.length === 0) {
2149
+ this.setTimeoutFn(() => {
2150
+ this.emitReserved("error", "No transports available");
2151
+ }, 0);
2152
+ return;
2153
+ }
2154
+ const transportName = this.opts.rememberUpgrade && _SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
2155
+ this.readyState = "opening";
2156
+ const transport = this.createTransport(transportName);
2157
+ transport.open();
2158
+ this.setTransport(transport);
2159
+ }
2160
+ /**
2161
+ * Sets the current transport. Disables the existing one (if any).
2162
+ *
2163
+ * @private
2164
+ */
2165
+ setTransport(transport) {
2166
+ if (this.transport) {
2167
+ this.transport.removeAllListeners();
2168
+ }
2169
+ this.transport = transport;
2170
+ transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
2171
+ }
2172
+ /**
2173
+ * Called when connection is deemed open.
2174
+ *
2175
+ * @private
2176
+ */
2177
+ onOpen() {
2178
+ this.readyState = "open";
2179
+ _SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
2180
+ this.emitReserved("open");
2181
+ this.flush();
2182
+ }
2183
+ /**
2184
+ * Handles a packet.
2185
+ *
2186
+ * @private
2187
+ */
2188
+ _onPacket(packet) {
2189
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
2190
+ this.emitReserved("packet", packet);
2191
+ this.emitReserved("heartbeat");
2192
+ switch (packet.type) {
2193
+ case "open":
2194
+ this.onHandshake(JSON.parse(packet.data));
2195
+ break;
2196
+ case "ping":
2197
+ this._sendPacket("pong");
2198
+ this.emitReserved("ping");
2199
+ this.emitReserved("pong");
2200
+ this._resetPingTimeout();
2201
+ break;
2202
+ case "error":
2203
+ const err = new Error("server error");
2204
+ err.code = packet.data;
2205
+ this._onError(err);
2206
+ break;
2207
+ case "message":
2208
+ this.emitReserved("data", packet.data);
2209
+ this.emitReserved("message", packet.data);
2210
+ break;
2211
+ }
2212
+ } else {
2213
+ }
2214
+ }
2215
+ /**
2216
+ * Called upon handshake completion.
2217
+ *
2218
+ * @param {Object} data - handshake obj
2219
+ * @private
2220
+ */
2221
+ onHandshake(data) {
2222
+ this.emitReserved("handshake", data);
2223
+ this.id = data.sid;
2224
+ this.transport.query.sid = data.sid;
2225
+ this._pingInterval = data.pingInterval;
2226
+ this._pingTimeout = data.pingTimeout;
2227
+ this._maxPayload = data.maxPayload;
2228
+ this.onOpen();
2229
+ if ("closed" === this.readyState)
2230
+ return;
2231
+ this._resetPingTimeout();
2232
+ }
2233
+ /**
2234
+ * Sets and resets ping timeout timer based on server pings.
2235
+ *
2236
+ * @private
2237
+ */
2238
+ _resetPingTimeout() {
2239
+ this.clearTimeoutFn(this._pingTimeoutTimer);
2240
+ const delay = this._pingInterval + this._pingTimeout;
2241
+ this._pingTimeoutTime = Date.now() + delay;
2242
+ this._pingTimeoutTimer = this.setTimeoutFn(() => {
2243
+ this._onClose("ping timeout");
2244
+ }, delay);
2245
+ if (this.opts.autoUnref) {
2246
+ this._pingTimeoutTimer.unref();
2247
+ }
2248
+ }
2249
+ /**
2250
+ * Called on `drain` event
2251
+ *
2252
+ * @private
2253
+ */
2254
+ _onDrain() {
2255
+ this.writeBuffer.splice(0, this._prevBufferLen);
2256
+ this._prevBufferLen = 0;
2257
+ if (0 === this.writeBuffer.length) {
2258
+ this.emitReserved("drain");
2259
+ } else {
2260
+ this.flush();
2261
+ }
2262
+ }
2263
+ /**
2264
+ * Flush write buffers.
2265
+ *
2266
+ * @private
2267
+ */
2268
+ flush() {
2269
+ if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
2270
+ const packets = this._getWritablePackets();
2271
+ this.transport.send(packets);
2272
+ this._prevBufferLen = packets.length;
2273
+ this.emitReserved("flush");
2274
+ }
2275
+ }
2276
+ /**
2277
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
2278
+ * long-polling)
2279
+ *
2280
+ * @private
2281
+ */
2282
+ _getWritablePackets() {
2283
+ const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
2284
+ if (!shouldCheckPayloadSize) {
2285
+ return this.writeBuffer;
2286
+ }
2287
+ let payloadSize = 1;
2288
+ for (let i = 0; i < this.writeBuffer.length; i++) {
2289
+ const data = this.writeBuffer[i].data;
2290
+ if (data) {
2291
+ payloadSize += byteLength(data);
2292
+ }
2293
+ if (i > 0 && payloadSize > this._maxPayload) {
2294
+ return this.writeBuffer.slice(0, i);
2295
+ }
2296
+ payloadSize += 2;
2297
+ }
2298
+ return this.writeBuffer;
2299
+ }
2300
+ /**
2301
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
2302
+ *
2303
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
2304
+ * `write()` method then the message would not be buffered by the Socket.IO client.
2305
+ *
2306
+ * @return {boolean}
2307
+ * @private
2308
+ */
2309
+ /* private */
2310
+ _hasPingExpired() {
2311
+ if (!this._pingTimeoutTime)
2312
+ return true;
2313
+ const hasExpired = Date.now() > this._pingTimeoutTime;
2314
+ if (hasExpired) {
2315
+ this._pingTimeoutTime = 0;
2316
+ nextTick(() => {
2317
+ this._onClose("ping timeout");
2318
+ }, this.setTimeoutFn);
2319
+ }
2320
+ return hasExpired;
2321
+ }
2322
+ /**
2323
+ * Sends a message.
2324
+ *
2325
+ * @param {String} msg - message.
2326
+ * @param {Object} options.
2327
+ * @param {Function} fn - callback function.
2328
+ * @return {Socket} for chaining.
2329
+ */
2330
+ write(msg, options, fn) {
2331
+ this._sendPacket("message", msg, options, fn);
2332
+ return this;
2333
+ }
2334
+ /**
2335
+ * Sends a message. Alias of {@link Socket#write}.
2336
+ *
2337
+ * @param {String} msg - message.
2338
+ * @param {Object} options.
2339
+ * @param {Function} fn - callback function.
2340
+ * @return {Socket} for chaining.
2341
+ */
2342
+ send(msg, options, fn) {
2343
+ this._sendPacket("message", msg, options, fn);
2344
+ return this;
2345
+ }
2346
+ /**
2347
+ * Sends a packet.
2348
+ *
2349
+ * @param {String} type - packet type.
2350
+ * @param {String} data.
2351
+ * @param {Object} options.
2352
+ * @param {Function} fn - callback function.
2353
+ * @private
2354
+ */
2355
+ _sendPacket(type, data, options, fn) {
2356
+ if ("function" === typeof data) {
2357
+ fn = data;
2358
+ data = void 0;
2359
+ }
2360
+ if ("function" === typeof options) {
2361
+ fn = options;
2362
+ options = null;
2363
+ }
2364
+ if ("closing" === this.readyState || "closed" === this.readyState) {
2365
+ return;
2366
+ }
2367
+ options = options || {};
2368
+ options.compress = false !== options.compress;
2369
+ const packet = {
2370
+ type,
2371
+ data,
2372
+ options
2373
+ };
2374
+ this.emitReserved("packetCreate", packet);
2375
+ this.writeBuffer.push(packet);
2376
+ if (fn)
2377
+ this.once("flush", fn);
2378
+ this.flush();
2379
+ }
2380
+ /**
2381
+ * Closes the connection.
2382
+ */
2383
+ close() {
2384
+ const close = () => {
2385
+ this._onClose("forced close");
2386
+ this.transport.close();
2387
+ };
2388
+ const cleanupAndClose = () => {
2389
+ this.off("upgrade", cleanupAndClose);
2390
+ this.off("upgradeError", cleanupAndClose);
2391
+ close();
2392
+ };
2393
+ const waitForUpgrade = () => {
2394
+ this.once("upgrade", cleanupAndClose);
2395
+ this.once("upgradeError", cleanupAndClose);
2396
+ };
2397
+ if ("opening" === this.readyState || "open" === this.readyState) {
2398
+ this.readyState = "closing";
2399
+ if (this.writeBuffer.length) {
2400
+ this.once("drain", () => {
2401
+ if (this.upgrading) {
2402
+ waitForUpgrade();
2403
+ } else {
2404
+ close();
2405
+ }
2406
+ });
2407
+ } else if (this.upgrading) {
2408
+ waitForUpgrade();
2409
+ } else {
2410
+ close();
2411
+ }
2412
+ }
2413
+ return this;
2414
+ }
2415
+ /**
2416
+ * Called upon transport error
2417
+ *
2418
+ * @private
2419
+ */
2420
+ _onError(err) {
2421
+ _SocketWithoutUpgrade.priorWebsocketSuccess = false;
2422
+ if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
2423
+ this.transports.shift();
2424
+ return this._open();
2425
+ }
2426
+ this.emitReserved("error", err);
2427
+ this._onClose("transport error", err);
2428
+ }
2429
+ /**
2430
+ * Called upon transport close.
2431
+ *
2432
+ * @private
2433
+ */
2434
+ _onClose(reason, description) {
2435
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
2436
+ this.clearTimeoutFn(this._pingTimeoutTimer);
2437
+ this.transport.removeAllListeners("close");
2438
+ this.transport.close();
2439
+ this.transport.removeAllListeners();
2440
+ if (withEventListeners) {
2441
+ if (this._beforeunloadEventListener) {
2442
+ removeEventListener("beforeunload", this._beforeunloadEventListener, false);
2443
+ }
2444
+ if (this._offlineEventListener) {
2445
+ const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
2446
+ if (i !== -1) {
2447
+ OFFLINE_EVENT_LISTENERS.splice(i, 1);
2448
+ }
2449
+ }
2450
+ }
2451
+ this.readyState = "closed";
2452
+ this.id = null;
2453
+ this.emitReserved("close", reason, description);
2454
+ this.writeBuffer = [];
2455
+ this._prevBufferLen = 0;
2456
+ }
2457
+ }
2458
+ };
2459
+ SocketWithoutUpgrade.protocol = protocol;
2460
+ var SocketWithUpgrade = class extends SocketWithoutUpgrade {
2461
+ constructor() {
2462
+ super(...arguments);
2463
+ this._upgrades = [];
2464
+ }
2465
+ onOpen() {
2466
+ super.onOpen();
2467
+ if ("open" === this.readyState && this.opts.upgrade) {
2468
+ for (let i = 0; i < this._upgrades.length; i++) {
2469
+ this._probe(this._upgrades[i]);
2470
+ }
2471
+ }
2472
+ }
2473
+ /**
2474
+ * Probes a transport.
2475
+ *
2476
+ * @param {String} name - transport name
2477
+ * @private
2478
+ */
2479
+ _probe(name) {
2480
+ let transport = this.createTransport(name);
2481
+ let failed = false;
2482
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
2483
+ const onTransportOpen = () => {
2484
+ if (failed)
2485
+ return;
2486
+ transport.send([{ type: "ping", data: "probe" }]);
2487
+ transport.once("packet", (msg) => {
2488
+ if (failed)
2489
+ return;
2490
+ if ("pong" === msg.type && "probe" === msg.data) {
2491
+ this.upgrading = true;
2492
+ this.emitReserved("upgrading", transport);
2493
+ if (!transport)
2494
+ return;
2495
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
2496
+ this.transport.pause(() => {
2497
+ if (failed)
2498
+ return;
2499
+ if ("closed" === this.readyState)
2500
+ return;
2501
+ cleanup();
2502
+ this.setTransport(transport);
2503
+ transport.send([{ type: "upgrade" }]);
2504
+ this.emitReserved("upgrade", transport);
2505
+ transport = null;
2506
+ this.upgrading = false;
2507
+ this.flush();
2508
+ });
2509
+ } else {
2510
+ const err = new Error("probe error");
2511
+ err.transport = transport.name;
2512
+ this.emitReserved("upgradeError", err);
2513
+ }
2514
+ });
2515
+ };
2516
+ function freezeTransport() {
2517
+ if (failed)
2518
+ return;
2519
+ failed = true;
2520
+ cleanup();
2521
+ transport.close();
2522
+ transport = null;
2523
+ }
2524
+ const onerror = (err) => {
2525
+ const error = new Error("probe error: " + err);
2526
+ error.transport = transport.name;
2527
+ freezeTransport();
2528
+ this.emitReserved("upgradeError", error);
2529
+ };
2530
+ function onTransportClose() {
2531
+ onerror("transport closed");
2532
+ }
2533
+ function onclose() {
2534
+ onerror("socket closed");
2535
+ }
2536
+ function onupgrade(to) {
2537
+ if (transport && to.name !== transport.name) {
2538
+ freezeTransport();
2539
+ }
2540
+ }
2541
+ const cleanup = () => {
2542
+ transport.removeListener("open", onTransportOpen);
2543
+ transport.removeListener("error", onerror);
2544
+ transport.removeListener("close", onTransportClose);
2545
+ this.off("close", onclose);
2546
+ this.off("upgrading", onupgrade);
2547
+ };
2548
+ transport.once("open", onTransportOpen);
2549
+ transport.once("error", onerror);
2550
+ transport.once("close", onTransportClose);
2551
+ this.once("close", onclose);
2552
+ this.once("upgrading", onupgrade);
2553
+ if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
2554
+ this.setTimeoutFn(() => {
2555
+ if (!failed) {
2556
+ transport.open();
2557
+ }
2558
+ }, 200);
2559
+ } else {
2560
+ transport.open();
2561
+ }
2562
+ }
2563
+ onHandshake(data) {
2564
+ this._upgrades = this._filterUpgrades(data.upgrades);
2565
+ super.onHandshake(data);
2566
+ }
2567
+ /**
2568
+ * Filters upgrades, returning only those matching client transports.
2569
+ *
2570
+ * @param {Array} upgrades - server upgrades
2571
+ * @private
2572
+ */
2573
+ _filterUpgrades(upgrades) {
2574
+ const filteredUpgrades = [];
2575
+ for (let i = 0; i < upgrades.length; i++) {
2576
+ if (~this.transports.indexOf(upgrades[i]))
2577
+ filteredUpgrades.push(upgrades[i]);
2578
+ }
2579
+ return filteredUpgrades;
2580
+ }
2581
+ };
2582
+ var Socket = class extends SocketWithUpgrade {
2583
+ constructor(uri, opts = {}) {
2584
+ const isOptionsOnly = typeof uri === "object";
2585
+ const o = isOptionsOnly ? { ...uri } : { ...opts };
2586
+ if (!o.transports || o.transports && typeof o.transports[0] === "string") {
2587
+ o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t) => !!t);
2588
+ }
2589
+ super(isOptionsOnly ? o : uri, o);
2590
+ }
2591
+ };
2592
+
2593
+ // ../../node_modules/engine.io-client/build/esm/index.js
2594
+ var protocol2 = Socket.protocol;
2595
+
2596
+ // ../../node_modules/socket.io-client/build/esm/url.js
2597
+ function url(uri, path = "", loc) {
2598
+ let obj = uri;
2599
+ loc = loc || typeof location !== "undefined" && location;
2600
+ if (null == uri)
2601
+ uri = loc.protocol + "//" + loc.host;
2602
+ if (typeof uri === "string") {
2603
+ if ("/" === uri.charAt(0)) {
2604
+ if ("/" === uri.charAt(1)) {
2605
+ uri = loc.protocol + uri;
2606
+ } else {
2607
+ uri = loc.host + uri;
2608
+ }
2609
+ }
2610
+ if (!/^(https?|wss?):\/\//.test(uri)) {
2611
+ if ("undefined" !== typeof loc) {
2612
+ uri = loc.protocol + "//" + uri;
2613
+ } else {
2614
+ uri = "https://" + uri;
2615
+ }
2616
+ }
2617
+ obj = parse(uri);
2618
+ }
2619
+ if (!obj.port) {
2620
+ if (/^(http|ws)$/.test(obj.protocol)) {
2621
+ obj.port = "80";
2622
+ } else if (/^(http|ws)s$/.test(obj.protocol)) {
2623
+ obj.port = "443";
2624
+ }
2625
+ }
2626
+ obj.path = obj.path || "/";
2627
+ const ipv6 = obj.host.indexOf(":") !== -1;
2628
+ const host = ipv6 ? "[" + obj.host + "]" : obj.host;
2629
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
2630
+ obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
2631
+ return obj;
2632
+ }
2633
+
2634
+ // ../../node_modules/socket.io-parser/build/esm/index.js
2635
+ var esm_exports = {};
2636
+ __export(esm_exports, {
2637
+ Decoder: () => Decoder,
2638
+ Encoder: () => Encoder,
2639
+ PacketType: () => PacketType,
2640
+ isPacketValid: () => isPacketValid,
2641
+ protocol: () => protocol3
2642
+ });
2643
+
2644
+ // ../../node_modules/socket.io-parser/build/esm/is-binary.js
2645
+ var withNativeArrayBuffer3 = typeof ArrayBuffer === "function";
2646
+ var isView2 = (obj) => {
2647
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
2648
+ };
2649
+ var toString = Object.prototype.toString;
2650
+ var withNativeBlob2 = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
2651
+ var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
2652
+ function isBinary(obj) {
2653
+ return withNativeArrayBuffer3 && (obj instanceof ArrayBuffer || isView2(obj)) || withNativeBlob2 && obj instanceof Blob || withNativeFile && obj instanceof File;
2654
+ }
2655
+ function hasBinary(obj, toJSON) {
2656
+ if (!obj || typeof obj !== "object") {
2657
+ return false;
2658
+ }
2659
+ if (Array.isArray(obj)) {
2660
+ for (let i = 0, l = obj.length; i < l; i++) {
2661
+ if (hasBinary(obj[i])) {
2662
+ return true;
2663
+ }
2664
+ }
2665
+ return false;
2666
+ }
2667
+ if (isBinary(obj)) {
2668
+ return true;
2669
+ }
2670
+ if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
2671
+ return hasBinary(obj.toJSON(), true);
2672
+ }
2673
+ for (const key in obj) {
2674
+ if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
2675
+ return true;
2676
+ }
2677
+ }
2678
+ return false;
2679
+ }
2680
+
2681
+ // ../../node_modules/socket.io-parser/build/esm/binary.js
2682
+ function deconstructPacket(packet) {
2683
+ const buffers = [];
2684
+ const packetData = packet.data;
2685
+ const pack = packet;
2686
+ pack.data = _deconstructPacket(packetData, buffers);
2687
+ pack.attachments = buffers.length;
2688
+ return { packet: pack, buffers };
2689
+ }
2690
+ function _deconstructPacket(data, buffers, toJSON) {
2691
+ if (!data)
2692
+ return data;
2693
+ if (isBinary(data)) {
2694
+ const placeholder = { _placeholder: true, num: buffers.length };
2695
+ buffers.push(data);
2696
+ return placeholder;
2697
+ } else if (Array.isArray(data)) {
2698
+ const newData = new Array(data.length);
2699
+ for (let i = 0; i < data.length; i++) {
2700
+ newData[i] = _deconstructPacket(data[i], buffers);
2701
+ }
2702
+ return newData;
2703
+ } else if (typeof data === "object" && !(data instanceof Date)) {
2704
+ if (data.toJSON && typeof data.toJSON === "function" && !toJSON) {
2705
+ return _deconstructPacket(data.toJSON(), buffers, true);
2706
+ }
2707
+ const newData = {};
2708
+ for (const key in data) {
2709
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
2710
+ newData[key] = _deconstructPacket(data[key], buffers);
2711
+ }
2712
+ }
2713
+ return newData;
2714
+ }
2715
+ return data;
2716
+ }
2717
+ function reconstructPacket(packet, buffers) {
2718
+ packet.data = _reconstructPacket(packet.data, buffers);
2719
+ delete packet.attachments;
2720
+ return packet;
2721
+ }
2722
+ function _reconstructPacket(data, buffers) {
2723
+ if (!data)
2724
+ return data;
2725
+ if (data && data._placeholder === true) {
2726
+ const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
2727
+ if (isIndexValid) {
2728
+ return buffers[data.num];
2729
+ } else {
2730
+ throw new Error("illegal attachments");
2731
+ }
2732
+ } else if (Array.isArray(data)) {
2733
+ for (let i = 0; i < data.length; i++) {
2734
+ data[i] = _reconstructPacket(data[i], buffers);
2735
+ }
2736
+ } else if (typeof data === "object") {
2737
+ for (const key in data) {
2738
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
2739
+ data[key] = _reconstructPacket(data[key], buffers);
2740
+ }
2741
+ }
2742
+ }
2743
+ return data;
2744
+ }
2745
+
2746
+ // ../../node_modules/socket.io-parser/build/esm/index.js
2747
+ var RESERVED_EVENTS = [
2748
+ "connect",
2749
+ // used on the client side
2750
+ "connect_error",
2751
+ // used on the client side
2752
+ "disconnect",
2753
+ // used on both sides
2754
+ "disconnecting",
2755
+ // used on the server side
2756
+ "newListener",
2757
+ // used by the Node.js EventEmitter
2758
+ "removeListener"
2759
+ // used by the Node.js EventEmitter
2760
+ ];
2761
+ var protocol3 = 5;
2762
+ var PacketType;
2763
+ (function(PacketType2) {
2764
+ PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
2765
+ PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
2766
+ PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
2767
+ PacketType2[PacketType2["ACK"] = 3] = "ACK";
2768
+ PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
2769
+ PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
2770
+ PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_ACK";
2771
+ })(PacketType || (PacketType = {}));
2772
+ var Encoder = class {
2773
+ /**
2774
+ * Encoder constructor
2775
+ *
2776
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
2777
+ */
2778
+ constructor(replacer) {
2779
+ this.replacer = replacer;
2780
+ }
2781
+ /**
2782
+ * Encode a packet as a single string if non-binary, or as a
2783
+ * buffer sequence, depending on packet type.
2784
+ *
2785
+ * @param {Object} obj - packet object
2786
+ */
2787
+ encode(obj) {
2788
+ if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
2789
+ if (hasBinary(obj)) {
2790
+ return this.encodeAsBinary({
2791
+ type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
2792
+ nsp: obj.nsp,
2793
+ data: obj.data,
2794
+ id: obj.id
2795
+ });
2796
+ }
2797
+ }
2798
+ return [this.encodeAsString(obj)];
2799
+ }
2800
+ /**
2801
+ * Encode packet as string.
2802
+ */
2803
+ encodeAsString(obj) {
2804
+ let str = "" + obj.type;
2805
+ if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
2806
+ str += obj.attachments + "-";
2807
+ }
2808
+ if (obj.nsp && "/" !== obj.nsp) {
2809
+ str += obj.nsp + ",";
2810
+ }
2811
+ if (null != obj.id) {
2812
+ str += obj.id;
2813
+ }
2814
+ if (null != obj.data) {
2815
+ str += JSON.stringify(obj.data, this.replacer);
2816
+ }
2817
+ return str;
2818
+ }
2819
+ /**
2820
+ * Encode packet as 'buffer sequence' by removing blobs, and
2821
+ * deconstructing packet into object with placeholders and
2822
+ * a list of buffers.
2823
+ */
2824
+ encodeAsBinary(obj) {
2825
+ const deconstruction = deconstructPacket(obj);
2826
+ const pack = this.encodeAsString(deconstruction.packet);
2827
+ const buffers = deconstruction.buffers;
2828
+ buffers.unshift(pack);
2829
+ return buffers;
2830
+ }
2831
+ };
2832
+ var Decoder = class _Decoder extends Emitter {
2833
+ /**
2834
+ * Decoder constructor
2835
+ */
2836
+ constructor(opts) {
2837
+ super();
2838
+ this.opts = Object.assign({
2839
+ reviver: void 0,
2840
+ maxAttachments: 10
2841
+ }, typeof opts === "function" ? { reviver: opts } : opts);
2842
+ }
2843
+ /**
2844
+ * Decodes an encoded packet string into packet JSON.
2845
+ *
2846
+ * @param {String} obj - encoded packet
2847
+ */
2848
+ add(obj) {
2849
+ let packet;
2850
+ if (typeof obj === "string") {
2851
+ if (this.reconstructor) {
2852
+ throw new Error("got plaintext data when reconstructing a packet");
2853
+ }
2854
+ packet = this.decodeString(obj);
2855
+ const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
2856
+ if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
2857
+ packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
2858
+ this.reconstructor = new BinaryReconstructor(packet);
2859
+ } else {
2860
+ super.emitReserved("decoded", packet);
2861
+ }
2862
+ } else if (isBinary(obj) || obj.base64) {
2863
+ if (!this.reconstructor) {
2864
+ throw new Error("got binary data when not reconstructing a packet");
2865
+ } else {
2866
+ packet = this.reconstructor.takeBinaryData(obj);
2867
+ if (packet) {
2868
+ this.reconstructor = null;
2869
+ super.emitReserved("decoded", packet);
2870
+ }
2871
+ }
2872
+ } else {
2873
+ throw new Error("Unknown type: " + obj);
2874
+ }
2875
+ }
2876
+ /**
2877
+ * Decode a packet String (JSON data)
2878
+ *
2879
+ * @param {String} str
2880
+ * @return {Object} packet
2881
+ */
2882
+ decodeString(str) {
2883
+ let i = 0;
2884
+ const p = {
2885
+ type: Number(str.charAt(0))
2886
+ };
2887
+ if (PacketType[p.type] === void 0) {
2888
+ throw new Error("unknown packet type " + p.type);
2889
+ }
2890
+ if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
2891
+ const start = i + 1;
2892
+ while (str.charAt(++i) !== "-" && i != str.length) {
2893
+ }
2894
+ const buf = str.substring(start, i);
2895
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
2896
+ throw new Error("Illegal attachments");
2897
+ }
2898
+ const n = Number(buf);
2899
+ if (!isInteger(n) || n < 1) {
2900
+ throw new Error("Illegal attachments");
2901
+ } else if (n > this.opts.maxAttachments) {
2902
+ throw new Error("too many attachments");
2903
+ }
2904
+ p.attachments = n;
2905
+ }
2906
+ if ("/" === str.charAt(i + 1)) {
2907
+ const start = i + 1;
2908
+ while (++i) {
2909
+ const c = str.charAt(i);
2910
+ if ("," === c)
2911
+ break;
2912
+ if (i === str.length)
2913
+ break;
2914
+ }
2915
+ p.nsp = str.substring(start, i);
2916
+ } else {
2917
+ p.nsp = "/";
2918
+ }
2919
+ const next = str.charAt(i + 1);
2920
+ if ("" !== next && Number(next) == next) {
2921
+ const start = i + 1;
2922
+ while (++i) {
2923
+ const c = str.charAt(i);
2924
+ if (null == c || Number(c) != c) {
2925
+ --i;
2926
+ break;
2927
+ }
2928
+ if (i === str.length)
2929
+ break;
2930
+ }
2931
+ p.id = Number(str.substring(start, i + 1));
2932
+ }
2933
+ if (str.charAt(++i)) {
2934
+ const payload = this.tryParse(str.substr(i));
2935
+ if (_Decoder.isPayloadValid(p.type, payload)) {
2936
+ p.data = payload;
2937
+ } else {
2938
+ throw new Error("invalid payload");
2939
+ }
2940
+ }
2941
+ return p;
2942
+ }
2943
+ tryParse(str) {
2944
+ try {
2945
+ return JSON.parse(str, this.opts.reviver);
2946
+ } catch (e) {
2947
+ return false;
2948
+ }
2949
+ }
2950
+ static isPayloadValid(type, payload) {
2951
+ switch (type) {
2952
+ case PacketType.CONNECT:
2953
+ return isObject(payload);
2954
+ case PacketType.DISCONNECT:
2955
+ return payload === void 0;
2956
+ case PacketType.CONNECT_ERROR:
2957
+ return typeof payload === "string" || isObject(payload);
2958
+ case PacketType.EVENT:
2959
+ case PacketType.BINARY_EVENT:
2960
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2961
+ case PacketType.ACK:
2962
+ case PacketType.BINARY_ACK:
2963
+ return Array.isArray(payload);
2964
+ }
2965
+ }
2966
+ /**
2967
+ * Deallocates a parser's resources
2968
+ */
2969
+ destroy() {
2970
+ if (this.reconstructor) {
2971
+ this.reconstructor.finishedReconstruction();
2972
+ this.reconstructor = null;
2973
+ }
2974
+ }
2975
+ };
2976
+ var BinaryReconstructor = class {
2977
+ constructor(packet) {
2978
+ this.packet = packet;
2979
+ this.buffers = [];
2980
+ this.reconPack = packet;
2981
+ }
2982
+ /**
2983
+ * Method to be called when binary data received from connection
2984
+ * after a BINARY_EVENT packet.
2985
+ *
2986
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
2987
+ * @return {null | Object} returns null if more binary data is expected or
2988
+ * a reconstructed packet object if all buffers have been received.
2989
+ */
2990
+ takeBinaryData(binData) {
2991
+ this.buffers.push(binData);
2992
+ if (this.buffers.length === this.reconPack.attachments) {
2993
+ const packet = reconstructPacket(this.reconPack, this.buffers);
2994
+ this.finishedReconstruction();
2995
+ return packet;
2996
+ }
2997
+ return null;
2998
+ }
2999
+ /**
3000
+ * Cleans up binary packet reconstruction variables.
3001
+ */
3002
+ finishedReconstruction() {
3003
+ this.reconPack = null;
3004
+ this.buffers = [];
3005
+ }
3006
+ };
3007
+ function isNamespaceValid(nsp) {
3008
+ return typeof nsp === "string";
3009
+ }
3010
+ var isInteger = Number.isInteger || function(value2) {
3011
+ return typeof value2 === "number" && isFinite(value2) && Math.floor(value2) === value2;
3012
+ };
3013
+ function isAckIdValid(id) {
3014
+ return id === void 0 || isInteger(id);
3015
+ }
3016
+ function isObject(value2) {
3017
+ return Object.prototype.toString.call(value2) === "[object Object]";
3018
+ }
3019
+ function isDataValid(type, payload) {
3020
+ switch (type) {
3021
+ case PacketType.CONNECT:
3022
+ return payload === void 0 || isObject(payload);
3023
+ case PacketType.DISCONNECT:
3024
+ return payload === void 0;
3025
+ case PacketType.EVENT:
3026
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
3027
+ case PacketType.ACK:
3028
+ return Array.isArray(payload);
3029
+ case PacketType.CONNECT_ERROR:
3030
+ return typeof payload === "string" || isObject(payload);
3031
+ default:
3032
+ return false;
3033
+ }
3034
+ }
3035
+ function isPacketValid(packet) {
3036
+ return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
3037
+ }
3038
+
3039
+ // ../../node_modules/socket.io-client/build/esm/on.js
3040
+ function on(obj, ev, fn) {
3041
+ obj.on(ev, fn);
3042
+ return function subDestroy() {
3043
+ obj.off(ev, fn);
3044
+ };
3045
+ }
3046
+
3047
+ // ../../node_modules/socket.io-client/build/esm/socket.js
3048
+ var RESERVED_EVENTS2 = Object.freeze({
3049
+ connect: 1,
3050
+ connect_error: 1,
3051
+ disconnect: 1,
3052
+ disconnecting: 1,
3053
+ // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
3054
+ newListener: 1,
3055
+ removeListener: 1
3056
+ });
3057
+ var Socket2 = class extends Emitter {
3058
+ /**
3059
+ * `Socket` constructor.
3060
+ */
3061
+ constructor(io, nsp, opts) {
3062
+ super();
3063
+ this.connected = false;
3064
+ this.recovered = false;
3065
+ this.receiveBuffer = [];
3066
+ this.sendBuffer = [];
3067
+ this._queue = [];
3068
+ this._queueSeq = 0;
3069
+ this.ids = 0;
3070
+ this.acks = {};
3071
+ this.flags = {};
3072
+ this.io = io;
3073
+ this.nsp = nsp;
3074
+ if (opts && opts.auth) {
3075
+ this.auth = opts.auth;
3076
+ }
3077
+ this._opts = Object.assign({}, opts);
3078
+ if (this.io._autoConnect)
3079
+ this.open();
3080
+ }
3081
+ /**
3082
+ * Whether the socket is currently disconnected
3083
+ *
3084
+ * @example
3085
+ * const socket = io();
3086
+ *
3087
+ * socket.on("connect", () => {
3088
+ * console.log(socket.disconnected); // false
3089
+ * });
3090
+ *
3091
+ * socket.on("disconnect", () => {
3092
+ * console.log(socket.disconnected); // true
3093
+ * });
3094
+ */
3095
+ get disconnected() {
3096
+ return !this.connected;
3097
+ }
3098
+ /**
3099
+ * Subscribe to open, close and packet events
3100
+ *
3101
+ * @private
3102
+ */
3103
+ subEvents() {
3104
+ if (this.subs)
3105
+ return;
3106
+ const io = this.io;
3107
+ this.subs = [
3108
+ on(io, "open", this.onopen.bind(this)),
3109
+ on(io, "packet", this.onpacket.bind(this)),
3110
+ on(io, "error", this.onerror.bind(this)),
3111
+ on(io, "close", this.onclose.bind(this))
3112
+ ];
3113
+ }
3114
+ /**
3115
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
3116
+ *
3117
+ * @example
3118
+ * const socket = io();
3119
+ *
3120
+ * console.log(socket.active); // true
3121
+ *
3122
+ * socket.on("disconnect", (reason) => {
3123
+ * if (reason === "io server disconnect") {
3124
+ * // the disconnection was initiated by the server, you need to manually reconnect
3125
+ * console.log(socket.active); // false
3126
+ * }
3127
+ * // else the socket will automatically try to reconnect
3128
+ * console.log(socket.active); // true
3129
+ * });
3130
+ */
3131
+ get active() {
3132
+ return !!this.subs;
3133
+ }
3134
+ /**
3135
+ * "Opens" the socket.
3136
+ *
3137
+ * @example
3138
+ * const socket = io({
3139
+ * autoConnect: false
3140
+ * });
3141
+ *
3142
+ * socket.connect();
3143
+ */
3144
+ connect() {
3145
+ if (this.connected)
3146
+ return this;
3147
+ this.subEvents();
3148
+ if (!this.io["_reconnecting"])
3149
+ this.io.open();
3150
+ if ("open" === this.io._readyState)
3151
+ this.onopen();
3152
+ return this;
3153
+ }
3154
+ /**
3155
+ * Alias for {@link connect()}.
3156
+ */
3157
+ open() {
3158
+ return this.connect();
3159
+ }
3160
+ /**
3161
+ * Sends a `message` event.
3162
+ *
3163
+ * This method mimics the WebSocket.send() method.
3164
+ *
3165
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
3166
+ *
3167
+ * @example
3168
+ * socket.send("hello");
3169
+ *
3170
+ * // this is equivalent to
3171
+ * socket.emit("message", "hello");
3172
+ *
3173
+ * @return self
3174
+ */
3175
+ send(...args) {
3176
+ args.unshift("message");
3177
+ this.emit.apply(this, args);
3178
+ return this;
3179
+ }
3180
+ /**
3181
+ * Override `emit`.
3182
+ * If the event is in `events`, it's emitted normally.
3183
+ *
3184
+ * @example
3185
+ * socket.emit("hello", "world");
3186
+ *
3187
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
3188
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
3189
+ *
3190
+ * // with an acknowledgement from the server
3191
+ * socket.emit("hello", "world", (val) => {
3192
+ * // ...
3193
+ * });
3194
+ *
3195
+ * @return self
3196
+ */
3197
+ emit(ev, ...args) {
3198
+ var _a, _b, _c;
3199
+ if (RESERVED_EVENTS2.hasOwnProperty(ev)) {
3200
+ throw new Error('"' + ev.toString() + '" is a reserved event name');
3201
+ }
3202
+ args.unshift(ev);
3203
+ if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
3204
+ this._addToQueue(args);
3205
+ return this;
3206
+ }
3207
+ const packet = {
3208
+ type: PacketType.EVENT,
3209
+ data: args
3210
+ };
3211
+ packet.options = {};
3212
+ packet.options.compress = this.flags.compress !== false;
3213
+ if ("function" === typeof args[args.length - 1]) {
3214
+ const id = this.ids++;
3215
+ const ack = args.pop();
3216
+ this._registerAckCallback(id, ack);
3217
+ packet.id = id;
3218
+ }
3219
+ const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
3220
+ const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
3221
+ const discardPacket = this.flags.volatile && !isTransportWritable;
3222
+ if (discardPacket) {
3223
+ } else if (isConnected) {
3224
+ this.notifyOutgoingListeners(packet);
3225
+ this.packet(packet);
3226
+ } else {
3227
+ this.sendBuffer.push(packet);
3228
+ }
3229
+ this.flags = {};
3230
+ return this;
3231
+ }
3232
+ /**
3233
+ * @private
3234
+ */
3235
+ _registerAckCallback(id, ack) {
3236
+ var _a;
3237
+ const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
3238
+ if (timeout === void 0) {
3239
+ this.acks[id] = ack;
3240
+ return;
3241
+ }
3242
+ const timer = this.io.setTimeoutFn(() => {
3243
+ delete this.acks[id];
3244
+ for (let i = 0; i < this.sendBuffer.length; i++) {
3245
+ if (this.sendBuffer[i].id === id) {
3246
+ this.sendBuffer.splice(i, 1);
3247
+ }
3248
+ }
3249
+ ack.call(this, new Error("operation has timed out"));
3250
+ }, timeout);
3251
+ const fn = (...args) => {
3252
+ this.io.clearTimeoutFn(timer);
3253
+ ack.apply(this, args);
3254
+ };
3255
+ fn.withError = true;
3256
+ this.acks[id] = fn;
3257
+ }
3258
+ /**
3259
+ * Emits an event and waits for an acknowledgement
3260
+ *
3261
+ * @example
3262
+ * // without timeout
3263
+ * const response = await socket.emitWithAck("hello", "world");
3264
+ *
3265
+ * // with a specific timeout
3266
+ * try {
3267
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
3268
+ * } catch (err) {
3269
+ * // the server did not acknowledge the event in the given delay
3270
+ * }
3271
+ *
3272
+ * @return a Promise that will be fulfilled when the server acknowledges the event
3273
+ */
3274
+ emitWithAck(ev, ...args) {
3275
+ return new Promise((resolve, reject) => {
3276
+ const fn = (arg1, arg2) => {
3277
+ return arg1 ? reject(arg1) : resolve(arg2);
3278
+ };
3279
+ fn.withError = true;
3280
+ args.push(fn);
3281
+ this.emit(ev, ...args);
3282
+ });
3283
+ }
3284
+ /**
3285
+ * Add the packet to the queue.
3286
+ * @param args
3287
+ * @private
3288
+ */
3289
+ _addToQueue(args) {
3290
+ let ack;
3291
+ if (typeof args[args.length - 1] === "function") {
3292
+ ack = args.pop();
3293
+ }
3294
+ const packet = {
3295
+ id: this._queueSeq++,
3296
+ tryCount: 0,
3297
+ pending: false,
3298
+ args,
3299
+ flags: Object.assign({ fromQueue: true }, this.flags)
3300
+ };
3301
+ args.push((err, ...responseArgs) => {
3302
+ if (packet !== this._queue[0]) {
3303
+ }
3304
+ const hasError = err !== null;
3305
+ if (hasError) {
3306
+ if (packet.tryCount > this._opts.retries) {
3307
+ this._queue.shift();
3308
+ if (ack) {
3309
+ ack(err);
3310
+ }
3311
+ }
3312
+ } else {
3313
+ this._queue.shift();
3314
+ if (ack) {
3315
+ ack(null, ...responseArgs);
3316
+ }
3317
+ }
3318
+ packet.pending = false;
3319
+ return this._drainQueue();
3320
+ });
3321
+ this._queue.push(packet);
3322
+ this._drainQueue();
3323
+ }
3324
+ /**
3325
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
3326
+ * @param force - whether to resend a packet that has not been acknowledged yet
3327
+ *
3328
+ * @private
3329
+ */
3330
+ _drainQueue(force = false) {
3331
+ if (!this.connected || this._queue.length === 0) {
3332
+ return;
3333
+ }
3334
+ const packet = this._queue[0];
3335
+ if (packet.pending && !force) {
3336
+ return;
3337
+ }
3338
+ packet.pending = true;
3339
+ packet.tryCount++;
3340
+ this.flags = packet.flags;
3341
+ this.emit.apply(this, packet.args);
3342
+ }
3343
+ /**
3344
+ * Sends a packet.
3345
+ *
3346
+ * @param packet
3347
+ * @private
3348
+ */
3349
+ packet(packet) {
3350
+ packet.nsp = this.nsp;
3351
+ this.io._packet(packet);
3352
+ }
3353
+ /**
3354
+ * Called upon engine `open`.
3355
+ *
3356
+ * @private
3357
+ */
3358
+ onopen() {
3359
+ if (typeof this.auth == "function") {
3360
+ this.auth((data) => {
3361
+ this._sendConnectPacket(data);
3362
+ });
3363
+ } else {
3364
+ this._sendConnectPacket(this.auth);
3365
+ }
3366
+ }
3367
+ /**
3368
+ * Sends a CONNECT packet to initiate the Socket.IO session.
3369
+ *
3370
+ * @param data
3371
+ * @private
3372
+ */
3373
+ _sendConnectPacket(data) {
3374
+ this.packet({
3375
+ type: PacketType.CONNECT,
3376
+ data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
3377
+ });
3378
+ }
3379
+ /**
3380
+ * Called upon engine or manager `error`.
3381
+ *
3382
+ * @param err
3383
+ * @private
3384
+ */
3385
+ onerror(err) {
3386
+ if (!this.connected) {
3387
+ this.emitReserved("connect_error", err);
3388
+ }
3389
+ }
3390
+ /**
3391
+ * Called upon engine `close`.
3392
+ *
3393
+ * @param reason
3394
+ * @param description
3395
+ * @private
3396
+ */
3397
+ onclose(reason, description) {
3398
+ this.connected = false;
3399
+ delete this.id;
3400
+ this.emitReserved("disconnect", reason, description);
3401
+ this._clearAcks();
3402
+ }
3403
+ /**
3404
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
3405
+ * the server.
3406
+ *
3407
+ * @private
3408
+ */
3409
+ _clearAcks() {
3410
+ Object.keys(this.acks).forEach((id) => {
3411
+ const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
3412
+ if (!isBuffered) {
3413
+ const ack = this.acks[id];
3414
+ delete this.acks[id];
3415
+ if (ack.withError) {
3416
+ ack.call(this, new Error("socket has been disconnected"));
3417
+ }
3418
+ }
3419
+ });
3420
+ }
3421
+ /**
3422
+ * Called with socket packet.
3423
+ *
3424
+ * @param packet
3425
+ * @private
3426
+ */
3427
+ onpacket(packet) {
3428
+ const sameNamespace = packet.nsp === this.nsp;
3429
+ if (!sameNamespace)
3430
+ return;
3431
+ switch (packet.type) {
3432
+ case PacketType.CONNECT:
3433
+ if (packet.data && packet.data.sid) {
3434
+ this.onconnect(packet.data.sid, packet.data.pid);
3435
+ } else {
3436
+ this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
3437
+ }
3438
+ break;
3439
+ case PacketType.EVENT:
3440
+ case PacketType.BINARY_EVENT:
3441
+ this.onevent(packet);
3442
+ break;
3443
+ case PacketType.ACK:
3444
+ case PacketType.BINARY_ACK:
3445
+ this.onack(packet);
3446
+ break;
3447
+ case PacketType.DISCONNECT:
3448
+ this.ondisconnect();
3449
+ break;
3450
+ case PacketType.CONNECT_ERROR:
3451
+ this.destroy();
3452
+ const err = new Error(packet.data.message);
3453
+ err.data = packet.data.data;
3454
+ this.emitReserved("connect_error", err);
3455
+ break;
3456
+ }
3457
+ }
3458
+ /**
3459
+ * Called upon a server event.
3460
+ *
3461
+ * @param packet
3462
+ * @private
3463
+ */
3464
+ onevent(packet) {
3465
+ const args = packet.data || [];
3466
+ if (null != packet.id) {
3467
+ args.push(this.ack(packet.id));
3468
+ }
3469
+ if (this.connected) {
3470
+ this.emitEvent(args);
3471
+ } else {
3472
+ this.receiveBuffer.push(Object.freeze(args));
3473
+ }
3474
+ }
3475
+ emitEvent(args) {
3476
+ if (this._anyListeners && this._anyListeners.length) {
3477
+ const listeners = this._anyListeners.slice();
3478
+ for (const listener of listeners) {
3479
+ listener.apply(this, args);
3480
+ }
3481
+ }
3482
+ super.emit.apply(this, args);
3483
+ if (this._pid && args.length && typeof args[args.length - 1] === "string") {
3484
+ this._lastOffset = args[args.length - 1];
3485
+ }
3486
+ }
3487
+ /**
3488
+ * Produces an ack callback to emit with an event.
3489
+ *
3490
+ * @private
3491
+ */
3492
+ ack(id) {
3493
+ const self2 = this;
3494
+ let sent = false;
3495
+ return function(...args) {
3496
+ if (sent)
3497
+ return;
3498
+ sent = true;
3499
+ self2.packet({
3500
+ type: PacketType.ACK,
3501
+ id,
3502
+ data: args
3503
+ });
3504
+ };
3505
+ }
3506
+ /**
3507
+ * Called upon a server acknowledgement.
3508
+ *
3509
+ * @param packet
3510
+ * @private
3511
+ */
3512
+ onack(packet) {
3513
+ const ack = this.acks[packet.id];
3514
+ if (typeof ack !== "function") {
3515
+ return;
3516
+ }
3517
+ delete this.acks[packet.id];
3518
+ if (ack.withError) {
3519
+ packet.data.unshift(null);
3520
+ }
3521
+ ack.apply(this, packet.data);
3522
+ }
3523
+ /**
3524
+ * Called upon server connect.
3525
+ *
3526
+ * @private
3527
+ */
3528
+ onconnect(id, pid) {
3529
+ this.id = id;
3530
+ this.recovered = pid && this._pid === pid;
3531
+ this._pid = pid;
3532
+ this.connected = true;
3533
+ this.emitBuffered();
3534
+ this._drainQueue(true);
3535
+ this.emitReserved("connect");
3536
+ }
3537
+ /**
3538
+ * Emit buffered events (received and emitted).
3539
+ *
3540
+ * @private
3541
+ */
3542
+ emitBuffered() {
3543
+ this.receiveBuffer.forEach((args) => this.emitEvent(args));
3544
+ this.receiveBuffer = [];
3545
+ this.sendBuffer.forEach((packet) => {
3546
+ this.notifyOutgoingListeners(packet);
3547
+ this.packet(packet);
3548
+ });
3549
+ this.sendBuffer = [];
3550
+ }
3551
+ /**
3552
+ * Called upon server disconnect.
3553
+ *
3554
+ * @private
3555
+ */
3556
+ ondisconnect() {
3557
+ this.destroy();
3558
+ this.onclose("io server disconnect");
3559
+ }
3560
+ /**
3561
+ * Called upon forced client/server side disconnections,
3562
+ * this method ensures the manager stops tracking us and
3563
+ * that reconnections don't get triggered for this.
3564
+ *
3565
+ * @private
3566
+ */
3567
+ destroy() {
3568
+ if (this.subs) {
3569
+ this.subs.forEach((subDestroy) => subDestroy());
3570
+ this.subs = void 0;
3571
+ }
3572
+ this.io["_destroy"](this);
3573
+ }
3574
+ /**
3575
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
3576
+ *
3577
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
3578
+ *
3579
+ * @example
3580
+ * const socket = io();
3581
+ *
3582
+ * socket.on("disconnect", (reason) => {
3583
+ * // console.log(reason); prints "io client disconnect"
3584
+ * });
3585
+ *
3586
+ * socket.disconnect();
3587
+ *
3588
+ * @return self
3589
+ */
3590
+ disconnect() {
3591
+ if (this.connected) {
3592
+ this.packet({ type: PacketType.DISCONNECT });
3593
+ }
3594
+ this.destroy();
3595
+ if (this.connected) {
3596
+ this.onclose("io client disconnect");
3597
+ }
3598
+ return this;
3599
+ }
3600
+ /**
3601
+ * Alias for {@link disconnect()}.
3602
+ *
3603
+ * @return self
3604
+ */
3605
+ close() {
3606
+ return this.disconnect();
3607
+ }
3608
+ /**
3609
+ * Sets the compress flag.
3610
+ *
3611
+ * @example
3612
+ * socket.compress(false).emit("hello");
3613
+ *
3614
+ * @param compress - if `true`, compresses the sending data
3615
+ * @return self
3616
+ */
3617
+ compress(compress) {
3618
+ this.flags.compress = compress;
3619
+ return this;
3620
+ }
3621
+ /**
3622
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
3623
+ * ready to send messages.
3624
+ *
3625
+ * @example
3626
+ * socket.volatile.emit("hello"); // the server may or may not receive it
3627
+ *
3628
+ * @returns self
3629
+ */
3630
+ get volatile() {
3631
+ this.flags.volatile = true;
3632
+ return this;
3633
+ }
3634
+ /**
3635
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
3636
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
3637
+ *
3638
+ * @example
3639
+ * socket.timeout(5000).emit("my-event", (err) => {
3640
+ * if (err) {
3641
+ * // the server did not acknowledge the event in the given delay
3642
+ * }
3643
+ * });
3644
+ *
3645
+ * @returns self
3646
+ */
3647
+ timeout(timeout) {
3648
+ this.flags.timeout = timeout;
3649
+ return this;
3650
+ }
3651
+ /**
3652
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3653
+ * callback.
3654
+ *
3655
+ * @example
3656
+ * socket.onAny((event, ...args) => {
3657
+ * console.log(`got ${event}`);
3658
+ * });
3659
+ *
3660
+ * @param listener
3661
+ */
3662
+ onAny(listener) {
3663
+ this._anyListeners = this._anyListeners || [];
3664
+ this._anyListeners.push(listener);
3665
+ return this;
3666
+ }
3667
+ /**
3668
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3669
+ * callback. The listener is added to the beginning of the listeners array.
3670
+ *
3671
+ * @example
3672
+ * socket.prependAny((event, ...args) => {
3673
+ * console.log(`got event ${event}`);
3674
+ * });
3675
+ *
3676
+ * @param listener
3677
+ */
3678
+ prependAny(listener) {
3679
+ this._anyListeners = this._anyListeners || [];
3680
+ this._anyListeners.unshift(listener);
3681
+ return this;
3682
+ }
3683
+ /**
3684
+ * Removes the listener that will be fired when any event is emitted.
3685
+ *
3686
+ * @example
3687
+ * const catchAllListener = (event, ...args) => {
3688
+ * console.log(`got event ${event}`);
3689
+ * }
3690
+ *
3691
+ * socket.onAny(catchAllListener);
3692
+ *
3693
+ * // remove a specific listener
3694
+ * socket.offAny(catchAllListener);
3695
+ *
3696
+ * // or remove all listeners
3697
+ * socket.offAny();
3698
+ *
3699
+ * @param listener
3700
+ */
3701
+ offAny(listener) {
3702
+ if (!this._anyListeners) {
3703
+ return this;
3704
+ }
3705
+ if (listener) {
3706
+ const listeners = this._anyListeners;
3707
+ for (let i = 0; i < listeners.length; i++) {
3708
+ if (listener === listeners[i]) {
3709
+ listeners.splice(i, 1);
3710
+ return this;
3711
+ }
3712
+ }
3713
+ } else {
3714
+ this._anyListeners = [];
3715
+ }
3716
+ return this;
3717
+ }
3718
+ /**
3719
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3720
+ * e.g. to remove listeners.
3721
+ */
3722
+ listenersAny() {
3723
+ return this._anyListeners || [];
3724
+ }
3725
+ /**
3726
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3727
+ * callback.
3728
+ *
3729
+ * Note: acknowledgements sent to the server are not included.
3730
+ *
3731
+ * @example
3732
+ * socket.onAnyOutgoing((event, ...args) => {
3733
+ * console.log(`sent event ${event}`);
3734
+ * });
3735
+ *
3736
+ * @param listener
3737
+ */
3738
+ onAnyOutgoing(listener) {
3739
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3740
+ this._anyOutgoingListeners.push(listener);
3741
+ return this;
3742
+ }
3743
+ /**
3744
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3745
+ * callback. The listener is added to the beginning of the listeners array.
3746
+ *
3747
+ * Note: acknowledgements sent to the server are not included.
3748
+ *
3749
+ * @example
3750
+ * socket.prependAnyOutgoing((event, ...args) => {
3751
+ * console.log(`sent event ${event}`);
3752
+ * });
3753
+ *
3754
+ * @param listener
3755
+ */
3756
+ prependAnyOutgoing(listener) {
3757
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3758
+ this._anyOutgoingListeners.unshift(listener);
3759
+ return this;
3760
+ }
3761
+ /**
3762
+ * Removes the listener that will be fired when any event is emitted.
3763
+ *
3764
+ * @example
3765
+ * const catchAllListener = (event, ...args) => {
3766
+ * console.log(`sent event ${event}`);
3767
+ * }
3768
+ *
3769
+ * socket.onAnyOutgoing(catchAllListener);
3770
+ *
3771
+ * // remove a specific listener
3772
+ * socket.offAnyOutgoing(catchAllListener);
3773
+ *
3774
+ * // or remove all listeners
3775
+ * socket.offAnyOutgoing();
3776
+ *
3777
+ * @param [listener] - the catch-all listener (optional)
3778
+ */
3779
+ offAnyOutgoing(listener) {
3780
+ if (!this._anyOutgoingListeners) {
3781
+ return this;
3782
+ }
3783
+ if (listener) {
3784
+ const listeners = this._anyOutgoingListeners;
3785
+ for (let i = 0; i < listeners.length; i++) {
3786
+ if (listener === listeners[i]) {
3787
+ listeners.splice(i, 1);
3788
+ return this;
3789
+ }
3790
+ }
3791
+ } else {
3792
+ this._anyOutgoingListeners = [];
3793
+ }
3794
+ return this;
3795
+ }
3796
+ /**
3797
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3798
+ * e.g. to remove listeners.
3799
+ */
3800
+ listenersAnyOutgoing() {
3801
+ return this._anyOutgoingListeners || [];
3802
+ }
3803
+ /**
3804
+ * Notify the listeners for each packet sent
3805
+ *
3806
+ * @param packet
3807
+ *
3808
+ * @private
3809
+ */
3810
+ notifyOutgoingListeners(packet) {
3811
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
3812
+ const listeners = this._anyOutgoingListeners.slice();
3813
+ for (const listener of listeners) {
3814
+ listener.apply(this, packet.data);
3815
+ }
3816
+ }
3817
+ }
3818
+ };
3819
+
3820
+ // ../../node_modules/socket.io-client/build/esm/contrib/backo2.js
3821
+ function Backoff(opts) {
3822
+ opts = opts || {};
3823
+ this.ms = opts.min || 100;
3824
+ this.max = opts.max || 1e4;
3825
+ this.factor = opts.factor || 2;
3826
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
3827
+ this.attempts = 0;
3828
+ }
3829
+ Backoff.prototype.duration = function() {
3830
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
3831
+ if (this.jitter) {
3832
+ var rand = Math.random();
3833
+ var deviation = Math.floor(rand * this.jitter * ms);
3834
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
3835
+ }
3836
+ return Math.min(ms, this.max) | 0;
3837
+ };
3838
+ Backoff.prototype.reset = function() {
3839
+ this.attempts = 0;
3840
+ };
3841
+ Backoff.prototype.setMin = function(min) {
3842
+ this.ms = min;
3843
+ };
3844
+ Backoff.prototype.setMax = function(max) {
3845
+ this.max = max;
3846
+ };
3847
+ Backoff.prototype.setJitter = function(jitter) {
3848
+ this.jitter = jitter;
3849
+ };
3850
+
3851
+ // ../../node_modules/socket.io-client/build/esm/manager.js
3852
+ var Manager = class extends Emitter {
3853
+ constructor(uri, opts) {
3854
+ var _a;
3855
+ super();
3856
+ this.nsps = {};
3857
+ this.subs = [];
3858
+ if (uri && "object" === typeof uri) {
3859
+ opts = uri;
3860
+ uri = void 0;
3861
+ }
3862
+ opts = opts || {};
3863
+ opts.path = opts.path || "/socket.io";
3864
+ this.opts = opts;
3865
+ installTimerFunctions(this, opts);
3866
+ this.reconnection(opts.reconnection !== false);
3867
+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
3868
+ this.reconnectionDelay(opts.reconnectionDelay || 1e3);
3869
+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
3870
+ this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
3871
+ this.backoff = new Backoff({
3872
+ min: this.reconnectionDelay(),
3873
+ max: this.reconnectionDelayMax(),
3874
+ jitter: this.randomizationFactor()
3875
+ });
3876
+ this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
3877
+ this._readyState = "closed";
3878
+ this.uri = uri;
3879
+ const _parser = opts.parser || esm_exports;
3880
+ this.encoder = new _parser.Encoder();
3881
+ this.decoder = new _parser.Decoder();
3882
+ this._autoConnect = opts.autoConnect !== false;
3883
+ if (this._autoConnect)
3884
+ this.open();
3885
+ }
3886
+ reconnection(v) {
3887
+ if (!arguments.length)
3888
+ return this._reconnection;
3889
+ this._reconnection = !!v;
3890
+ if (!v) {
3891
+ this.skipReconnect = true;
3892
+ }
3893
+ return this;
3894
+ }
3895
+ reconnectionAttempts(v) {
3896
+ if (v === void 0)
3897
+ return this._reconnectionAttempts;
3898
+ this._reconnectionAttempts = v;
3899
+ return this;
3900
+ }
3901
+ reconnectionDelay(v) {
3902
+ var _a;
3903
+ if (v === void 0)
3904
+ return this._reconnectionDelay;
3905
+ this._reconnectionDelay = v;
3906
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
3907
+ return this;
3908
+ }
3909
+ randomizationFactor(v) {
3910
+ var _a;
3911
+ if (v === void 0)
3912
+ return this._randomizationFactor;
3913
+ this._randomizationFactor = v;
3914
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
3915
+ return this;
3916
+ }
3917
+ reconnectionDelayMax(v) {
3918
+ var _a;
3919
+ if (v === void 0)
3920
+ return this._reconnectionDelayMax;
3921
+ this._reconnectionDelayMax = v;
3922
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
3923
+ return this;
3924
+ }
3925
+ timeout(v) {
3926
+ if (!arguments.length)
3927
+ return this._timeout;
3928
+ this._timeout = v;
3929
+ return this;
3930
+ }
3931
+ /**
3932
+ * Starts trying to reconnect if reconnection is enabled and we have not
3933
+ * started reconnecting yet
3934
+ *
3935
+ * @private
3936
+ */
3937
+ maybeReconnectOnOpen() {
3938
+ if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
3939
+ this.reconnect();
3940
+ }
3941
+ }
3942
+ /**
3943
+ * Sets the current transport `socket`.
3944
+ *
3945
+ * @param {Function} fn - optional, callback
3946
+ * @return self
3947
+ * @public
3948
+ */
3949
+ open(fn) {
3950
+ if (~this._readyState.indexOf("open"))
3951
+ return this;
3952
+ this.engine = new Socket(this.uri, this.opts);
3953
+ const socket = this.engine;
3954
+ const self2 = this;
3955
+ this._readyState = "opening";
3956
+ this.skipReconnect = false;
3957
+ const openSubDestroy = on(socket, "open", function() {
3958
+ self2.onopen();
3959
+ fn && fn();
3960
+ });
3961
+ const onError = (err) => {
3962
+ this.cleanup();
3963
+ this._readyState = "closed";
3964
+ this.emitReserved("error", err);
3965
+ if (fn) {
3966
+ fn(err);
3967
+ } else {
3968
+ this.maybeReconnectOnOpen();
3969
+ }
3970
+ };
3971
+ const errorSub = on(socket, "error", onError);
3972
+ if (false !== this._timeout) {
3973
+ const timeout = this._timeout;
3974
+ const timer = this.setTimeoutFn(() => {
3975
+ openSubDestroy();
3976
+ onError(new Error("timeout"));
3977
+ socket.close();
3978
+ }, timeout);
3979
+ if (this.opts.autoUnref) {
3980
+ timer.unref();
3981
+ }
3982
+ this.subs.push(() => {
3983
+ this.clearTimeoutFn(timer);
3984
+ });
3985
+ }
3986
+ this.subs.push(openSubDestroy);
3987
+ this.subs.push(errorSub);
3988
+ return this;
3989
+ }
3990
+ /**
3991
+ * Alias for open()
3992
+ *
3993
+ * @return self
3994
+ * @public
3995
+ */
3996
+ connect(fn) {
3997
+ return this.open(fn);
3998
+ }
3999
+ /**
4000
+ * Called upon transport open.
4001
+ *
4002
+ * @private
4003
+ */
4004
+ onopen() {
4005
+ this.cleanup();
4006
+ this._readyState = "open";
4007
+ this.emitReserved("open");
4008
+ const socket = this.engine;
4009
+ this.subs.push(
4010
+ on(socket, "ping", this.onping.bind(this)),
4011
+ on(socket, "data", this.ondata.bind(this)),
4012
+ on(socket, "error", this.onerror.bind(this)),
4013
+ on(socket, "close", this.onclose.bind(this)),
4014
+ // @ts-ignore
4015
+ on(this.decoder, "decoded", this.ondecoded.bind(this))
4016
+ );
4017
+ }
4018
+ /**
4019
+ * Called upon a ping.
4020
+ *
4021
+ * @private
4022
+ */
4023
+ onping() {
4024
+ this.emitReserved("ping");
4025
+ }
4026
+ /**
4027
+ * Called with data.
4028
+ *
4029
+ * @private
4030
+ */
4031
+ ondata(data) {
4032
+ try {
4033
+ this.decoder.add(data);
4034
+ } catch (e) {
4035
+ this.onclose("parse error", e);
4036
+ }
4037
+ }
4038
+ /**
4039
+ * Called when parser fully decodes a packet.
4040
+ *
4041
+ * @private
4042
+ */
4043
+ ondecoded(packet) {
4044
+ nextTick(() => {
4045
+ this.emitReserved("packet", packet);
4046
+ }, this.setTimeoutFn);
4047
+ }
4048
+ /**
4049
+ * Called upon socket error.
4050
+ *
4051
+ * @private
4052
+ */
4053
+ onerror(err) {
4054
+ this.emitReserved("error", err);
4055
+ }
4056
+ /**
4057
+ * Creates a new socket for the given `nsp`.
4058
+ *
4059
+ * @return {Socket}
4060
+ * @public
4061
+ */
4062
+ socket(nsp, opts) {
4063
+ let socket = this.nsps[nsp];
4064
+ if (!socket) {
4065
+ socket = new Socket2(this, nsp, opts);
4066
+ this.nsps[nsp] = socket;
4067
+ } else if (this._autoConnect && !socket.active) {
4068
+ socket.connect();
4069
+ }
4070
+ return socket;
4071
+ }
4072
+ /**
4073
+ * Called upon a socket close.
4074
+ *
4075
+ * @param socket
4076
+ * @private
4077
+ */
4078
+ _destroy(socket) {
4079
+ const nsps = Object.keys(this.nsps);
4080
+ for (const nsp of nsps) {
4081
+ const socket2 = this.nsps[nsp];
4082
+ if (socket2.active) {
4083
+ return;
4084
+ }
4085
+ }
4086
+ this._close();
4087
+ }
4088
+ /**
4089
+ * Writes a packet.
4090
+ *
4091
+ * @param packet
4092
+ * @private
4093
+ */
4094
+ _packet(packet) {
4095
+ const encodedPackets = this.encoder.encode(packet);
4096
+ for (let i = 0; i < encodedPackets.length; i++) {
4097
+ this.engine.write(encodedPackets[i], packet.options);
4098
+ }
4099
+ }
4100
+ /**
4101
+ * Clean up transport subscriptions and packet buffer.
4102
+ *
4103
+ * @private
4104
+ */
4105
+ cleanup() {
4106
+ this.subs.forEach((subDestroy) => subDestroy());
4107
+ this.subs.length = 0;
4108
+ this.decoder.destroy();
4109
+ }
4110
+ /**
4111
+ * Close the current socket.
4112
+ *
4113
+ * @private
4114
+ */
4115
+ _close() {
4116
+ this.skipReconnect = true;
4117
+ this._reconnecting = false;
4118
+ this.onclose("forced close");
4119
+ }
4120
+ /**
4121
+ * Alias for close()
4122
+ *
4123
+ * @private
4124
+ */
4125
+ disconnect() {
4126
+ return this._close();
4127
+ }
4128
+ /**
4129
+ * Called when:
4130
+ *
4131
+ * - the low-level engine is closed
4132
+ * - the parser encountered a badly formatted packet
4133
+ * - all sockets are disconnected
4134
+ *
4135
+ * @private
4136
+ */
4137
+ onclose(reason, description) {
4138
+ var _a;
4139
+ this.cleanup();
4140
+ (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
4141
+ this.backoff.reset();
4142
+ this._readyState = "closed";
4143
+ this.emitReserved("close", reason, description);
4144
+ if (this._reconnection && !this.skipReconnect) {
4145
+ this.reconnect();
4146
+ }
4147
+ }
4148
+ /**
4149
+ * Attempt a reconnection.
4150
+ *
4151
+ * @private
4152
+ */
4153
+ reconnect() {
4154
+ if (this._reconnecting || this.skipReconnect)
4155
+ return this;
4156
+ const self2 = this;
4157
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
4158
+ this.backoff.reset();
4159
+ this.emitReserved("reconnect_failed");
4160
+ this._reconnecting = false;
4161
+ } else {
4162
+ const delay = this.backoff.duration();
4163
+ this._reconnecting = true;
4164
+ const timer = this.setTimeoutFn(() => {
4165
+ if (self2.skipReconnect)
4166
+ return;
4167
+ this.emitReserved("reconnect_attempt", self2.backoff.attempts);
4168
+ if (self2.skipReconnect)
4169
+ return;
4170
+ self2.open((err) => {
4171
+ if (err) {
4172
+ self2._reconnecting = false;
4173
+ self2.reconnect();
4174
+ this.emitReserved("reconnect_error", err);
4175
+ } else {
4176
+ self2.onreconnect();
4177
+ }
4178
+ });
4179
+ }, delay);
4180
+ if (this.opts.autoUnref) {
4181
+ timer.unref();
4182
+ }
4183
+ this.subs.push(() => {
4184
+ this.clearTimeoutFn(timer);
4185
+ });
4186
+ }
4187
+ }
4188
+ /**
4189
+ * Called upon successful reconnect.
4190
+ *
4191
+ * @private
4192
+ */
4193
+ onreconnect() {
4194
+ const attempt = this.backoff.attempts;
4195
+ this._reconnecting = false;
4196
+ this.backoff.reset();
4197
+ this.emitReserved("reconnect", attempt);
4198
+ }
4199
+ };
4200
+
4201
+ // ../../node_modules/socket.io-client/build/esm/index.js
4202
+ var cache = {};
4203
+ function lookup2(uri, opts) {
4204
+ if (typeof uri === "object") {
4205
+ opts = uri;
4206
+ uri = void 0;
4207
+ }
4208
+ opts = opts || {};
4209
+ const parsed = url(uri, opts.path || "/socket.io");
4210
+ const source = parsed.source;
4211
+ const id = parsed.id;
4212
+ const path = parsed.path;
4213
+ const sameNamespace = cache[id] && path in cache[id]["nsps"];
4214
+ const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
4215
+ let io;
4216
+ if (newConnection) {
4217
+ io = new Manager(source, opts);
4218
+ } else {
4219
+ if (!cache[id]) {
4220
+ cache[id] = new Manager(source, opts);
4221
+ }
4222
+ io = cache[id];
4223
+ }
4224
+ if (parsed.query && !opts.query) {
4225
+ opts.query = parsed.queryKey;
4226
+ }
4227
+ return io.socket(parsed.path, opts);
4228
+ }
4229
+ Object.assign(lookup2, {
4230
+ Manager,
4231
+ Socket: Socket2,
4232
+ io: lookup2,
4233
+ connect: lookup2
4234
+ });
4235
+
4236
+ // src/payment-socket.ts
4237
+ function idsMatch(eventId, expectedId) {
4238
+ if (!expectedId) return true;
4239
+ if (!eventId) return false;
4240
+ return String(eventId) === String(expectedId);
4241
+ }
4242
+ function isConfirmedStatus(status) {
4243
+ return ["COMPLETED", "CONFIRMED", "PAID", "SUCCESS", "OVERPAID"].includes(
4244
+ String(status || "").toUpperCase()
4245
+ );
4246
+ }
4247
+ function watchPaymentSocket(params) {
4248
+ const {
4249
+ apiBaseUrl,
4250
+ shoppingCartReference,
4251
+ purchaseId,
4252
+ signal,
4253
+ timeoutMs = 45 * 60 * 1e3
4254
+ } = params;
4255
+ let socket = null;
4256
+ let settled = false;
4257
+ let connected = false;
4258
+ let timer = null;
4259
+ let resolveFn = null;
4260
+ let rejectFn = null;
4261
+ const dispose = () => {
4262
+ if (timer) {
4263
+ clearTimeout(timer);
4264
+ timer = null;
4265
+ }
4266
+ signal?.removeEventListener("abort", onAbort);
4267
+ if (socket) {
4268
+ socket.removeAllListeners();
4269
+ socket.disconnect();
4270
+ socket = null;
4271
+ }
4272
+ };
4273
+ const settleResolve = (value2) => {
4274
+ if (settled) return;
4275
+ settled = true;
4276
+ dispose();
4277
+ resolveFn?.(value2);
4278
+ };
4279
+ const settleReject = (reason) => {
4280
+ if (settled) return;
4281
+ settled = true;
4282
+ dispose();
4283
+ rejectFn?.(reason);
4284
+ };
4285
+ const onAbort = () => {
4286
+ settleReject(new Error("checkout_aborted"));
4287
+ };
4288
+ const handleSnapshot = (payload) => {
4289
+ const eventPurchaseId = payload?.purchaseId || payload?.orderId;
4290
+ if (!idsMatch(eventPurchaseId ? String(eventPurchaseId) : void 0, purchaseId)) {
4291
+ return;
4292
+ }
4293
+ if (isConfirmedStatus(payload?.status)) {
4294
+ settleResolve({
4295
+ ...payload,
4296
+ status: String(payload.status || "SUCCESS").toUpperCase()
4297
+ });
4298
+ }
4299
+ };
4300
+ const promise = new Promise((resolve, reject) => {
4301
+ resolveFn = resolve;
4302
+ rejectFn = reject;
4303
+ if (signal?.aborted) {
4304
+ settleReject(new Error("checkout_aborted"));
4305
+ return;
4306
+ }
4307
+ signal?.addEventListener("abort", onAbort, { once: true });
4308
+ timer = setTimeout(() => {
4309
+ settleReject(new Error("checkout_payment_timeout"));
4310
+ }, timeoutMs);
4311
+ try {
4312
+ socket = lookup2(apiBaseUrl.replace(/\/+$/, ""), {
4313
+ withCredentials: true,
4314
+ reconnection: true,
4315
+ reconnectionAttempts: Infinity,
4316
+ reconnectionDelay: 1e3,
4317
+ reconnectionDelayMax: 1e4,
4318
+ timeout: 2e4,
4319
+ transports: ["websocket", "polling"]
4320
+ });
4321
+ } catch (err) {
4322
+ settleReject(err);
4323
+ return;
4324
+ }
4325
+ const joinRoom = () => {
4326
+ if (!socket?.connected) return;
4327
+ connected = true;
4328
+ socket.emit("payment:process", { shoppingCartReference });
4329
+ };
4330
+ socket.on("connect", joinRoom);
4331
+ socket.on("reconnect", joinRoom);
4332
+ socket.on("payment:confirmed", (payload) => {
4333
+ handleSnapshot({
4334
+ ...payload,
4335
+ status: payload?.status || "SUCCESS"
4336
+ });
4337
+ });
4338
+ socket.on("payment:status", (payload) => {
4339
+ handleSnapshot(payload);
4340
+ });
4341
+ socket.on("payment:processing", () => {
4342
+ });
4343
+ socket.on("payment:underpaid", () => {
4344
+ });
4345
+ socket.on("connect_error", () => {
4346
+ connected = false;
4347
+ });
4348
+ socket.on("disconnect", () => {
4349
+ connected = false;
4350
+ });
4351
+ if (socket.connected) joinRoom();
4352
+ });
4353
+ return {
4354
+ promise,
4355
+ dispose: () => {
4356
+ if (!settled) {
4357
+ settled = true;
4358
+ dispose();
4359
+ return;
4360
+ }
4361
+ dispose();
4362
+ },
4363
+ get connected() {
4364
+ return connected;
4365
+ }
4366
+ };
4367
+ }
4368
+
4369
+ // src/navigate.ts
4370
+ function navigateTopLevel(url2) {
4371
+ if (typeof window === "undefined" || !url2) return;
4372
+ try {
4373
+ const topWin = window.top;
4374
+ if (topWin && topWin !== window) {
4375
+ topWin.location.assign(url2);
4376
+ return;
4377
+ }
4378
+ } catch {
4379
+ }
4380
+ window.location.assign(url2);
4381
+ }
4382
+ function resolveRedirectUrl(params) {
4383
+ if (params.nextAction?.type === "redirect" && params.nextAction.url) {
4384
+ return params.nextAction.url;
4385
+ }
4386
+ return params.redirectUrl || params.initPoint || null;
4387
+ }
4388
+
4389
+ // src/controller.ts
4390
+ function generateIdempotencyKey() {
4391
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
4392
+ return crypto.randomUUID();
4393
+ }
4394
+ return `idem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
4395
+ }
4396
+ function toTickeanError(err) {
4397
+ if (err instanceof TickeanError) return err;
4398
+ const anyErr = err;
4399
+ return new TickeanError(
4400
+ {
4401
+ code: anyErr?.code || "checkout_unknown_error",
4402
+ message: anyErr?.message || "Unexpected checkout error",
4403
+ details: anyErr?.details
4404
+ },
4405
+ anyErr?.status
4406
+ );
4407
+ }
4408
+ function resolveShowIdFromCart(event, cart) {
4409
+ const optionId = cart.find((item) => item.showOptionId)?.showOptionId;
4410
+ if (!optionId || !event?.shows?.length) return null;
4411
+ for (const show of event.shows) {
4412
+ if ((show.showOptions || []).some((opt) => opt.id === optionId)) {
4413
+ return show.id;
4414
+ }
4415
+ }
4416
+ return null;
4417
+ }
4418
+ function createCheckoutController(options) {
4419
+ const client = createTickean(options);
4420
+ const telemetry = options.telemetry || createNoopTelemetry();
4421
+ const persistenceKey = options.persistenceKey || `tickean.checkout.${options.eventSlug}.${options.publishableKey || "demo"}`;
4422
+ const persistence = options.persistence === false ? null : options.persistence || (typeof sessionStorage !== "undefined" ? createSessionStoragePersistence() : createMemoryPersistence());
4423
+ let state = createInitialState();
4424
+ const listeners = /* @__PURE__ */ new Set();
4425
+ let quoteTimer = null;
4426
+ let activeSocketWatch = null;
4427
+ let watchAbort = null;
4428
+ let quoteGeneration = 0;
4429
+ const quoteDebounceMs = options.quoteDebounceMs ?? 300;
4430
+ let disposed = false;
4431
+ const emit = (name, properties) => {
4432
+ telemetry.track({ name, timestamp: Date.now(), properties });
4433
+ };
4434
+ const notify = () => {
4435
+ const snapshot = getSnapshot();
4436
+ for (const listener of listeners) {
4437
+ try {
4438
+ listener(snapshot);
4439
+ } catch {
4440
+ }
4441
+ }
4442
+ };
4443
+ const dispatch = (action) => {
4444
+ state = checkoutReducer(state, action);
4445
+ persist();
4446
+ notify();
4447
+ };
4448
+ const persist = () => {
4449
+ if (!persistence) return;
4450
+ persistence.set(persistenceKey, {
4451
+ sessionToken: state.session?.sessionToken,
4452
+ eventSlug: options.eventSlug,
4453
+ cart: state.cart,
4454
+ discountCode: state.discountCode,
4455
+ phase: state.phase,
4456
+ buyerVerified: state.buyerVerified,
4457
+ purchaseId: state.purchase?.id ?? null
4458
+ });
4459
+ };
4460
+ const getSnapshot = () => state;
4461
+ const subscribe = (listener) => {
4462
+ listeners.add(listener);
4463
+ return () => {
4464
+ listeners.delete(listener);
4465
+ };
4466
+ };
4467
+ const scheduleQuote = () => {
4468
+ if (quoteTimer) clearTimeout(quoteTimer);
4469
+ if (!state.session || state.cart.length === 0) {
4470
+ dispatch({
4471
+ type: "QUOTE_SUCCESS",
4472
+ quote: {
4473
+ valid: true,
4474
+ totalPrice: 0,
4475
+ pricingBreakdown: { subtotal: 0 }
4476
+ }
4477
+ });
4478
+ return;
4479
+ }
4480
+ const gen = ++quoteGeneration;
4481
+ quoteTimer = setTimeout(async () => {
4482
+ dispatch({ type: "QUOTE_START" });
4483
+ emit("checkout.quote.start", { items: state.cart.length });
4484
+ try {
4485
+ const quote = await client.quote({
4486
+ items: state.cart,
4487
+ discountCode: state.discountCode || void 0
4488
+ });
4489
+ if (disposed || gen !== quoteGeneration) return;
4490
+ dispatch({ type: "QUOTE_SUCCESS", quote });
4491
+ emit("checkout.quote.success", { totalPrice: quote.totalPrice });
4492
+ if ((quote.unlockedShowOptions || []).length > 0) {
4493
+ dispatch({
4494
+ type: "MERGE_UNLOCKED_OPTIONS",
4495
+ options: quote.unlockedShowOptions || []
4496
+ });
4497
+ }
4498
+ } catch (err) {
4499
+ if (disposed || gen !== quoteGeneration) return;
4500
+ const error = toTickeanError(err);
4501
+ dispatch({ type: "QUOTE_FAILURE", error });
4502
+ emit("checkout.quote.error", { code: error.code });
4503
+ }
4504
+ }, quoteDebounceMs);
4505
+ };
4506
+ const setCartItem = (showOptionId, amount) => {
4507
+ const next = state.cart.filter((item) => item.showOptionId !== showOptionId);
4508
+ if (amount > 0) next.push({ showOptionId, amount });
4509
+ dispatch({ type: "SET_CART", cart: next });
4510
+ emit("checkout.cart.change", { showOptionId, amount });
4511
+ scheduleQuote();
4512
+ };
4513
+ const setCart = (cart) => {
4514
+ dispatch({
4515
+ type: "SET_CART",
4516
+ cart: cart.filter((item) => item.amount > 0)
4517
+ });
4518
+ emit("checkout.cart.change", { count: cart.length });
4519
+ scheduleQuote();
4520
+ };
4521
+ const applyDiscountCode = async (code) => {
4522
+ const normalized = code.trim().toUpperCase();
4523
+ dispatch({ type: "SET_DISCOUNT", discountCode: normalized || null });
4524
+ if (!state.session) {
4525
+ throw new TickeanError({
4526
+ code: "checkout_session_required",
4527
+ message: "Session required"
4528
+ });
4529
+ }
4530
+ dispatch({ type: "QUOTE_START" });
4531
+ try {
4532
+ const quote = await client.quote({
4533
+ items: state.cart,
4534
+ discountCode: normalized || void 0
4535
+ });
4536
+ const unlocked = quote.unlockedShowOptions || [];
4537
+ const unlockedIds = quote.unlockedShowOptionIds || [];
4538
+ const unlockedAnything = unlocked.length > 0 || unlockedIds.length > 0;
4539
+ if (quote.valid === false && !unlockedAnything) {
4540
+ dispatch({ type: "SET_DISCOUNT", discountCode: null });
4541
+ const error = new TickeanError({
4542
+ code: "discount_invalid",
4543
+ message: quote.message || "Invalid discount code"
4544
+ });
4545
+ dispatch({ type: "QUOTE_FAILURE", error });
4546
+ throw error;
4547
+ }
4548
+ dispatch({ type: "QUOTE_SUCCESS", quote });
4549
+ emit("checkout.discount.applied", { code: normalized || null });
4550
+ if (unlocked.length > 0) {
4551
+ dispatch({
4552
+ type: "MERGE_UNLOCKED_OPTIONS",
4553
+ options: unlocked
4554
+ });
4555
+ }
4556
+ return quote;
4557
+ } catch (err) {
4558
+ const error = toTickeanError(err);
4559
+ if (error.code !== "discount_invalid") {
4560
+ dispatch({ type: "QUOTE_FAILURE", error });
4561
+ }
4562
+ throw error;
4563
+ }
4564
+ };
4565
+ const lookupBuyer = async (phone) => {
4566
+ const result = await client.lookupBuyer({ phone });
4567
+ emit("checkout.buyer.lookup", { exists: result.exists });
4568
+ return result;
4569
+ };
4570
+ const sendOtp = async (phone, channel) => {
4571
+ await client.sendOtp({ phone, channel });
4572
+ dispatch({ type: "OTP_SENT" });
4573
+ emit("checkout.otp.sent");
4574
+ };
4575
+ const verifyOtp = async (params) => {
4576
+ const result = await client.verifyOtp(params);
4577
+ const buyer = result.buyer || {
4578
+ id: "buyer",
4579
+ phone: params.phone,
4580
+ name: params.name,
4581
+ email: params.email
4582
+ };
4583
+ dispatch({ type: "OTP_VERIFIED", buyer });
4584
+ emit("checkout.otp.verified");
4585
+ };
4586
+ const stopPaymentWatchers = () => {
4587
+ watchAbort?.abort();
4588
+ watchAbort = null;
4589
+ activeSocketWatch?.dispose();
4590
+ activeSocketWatch = null;
4591
+ };
4592
+ const changePaymentMethod = () => {
4593
+ stopPaymentWatchers();
4594
+ dispatch({ type: "RESET_PAYMENT_FLOW" });
4595
+ emit("checkout.payment.method_change");
4596
+ };
4597
+ const purchaseAndPay = async (params) => {
4598
+ stopPaymentWatchers();
4599
+ dispatch({ type: "PURCHASE_START" });
4600
+ const idempotencyKey = params.idempotencyKey || generateIdempotencyKey();
4601
+ emit("checkout.purchase.start", { paymentMethod: params.paymentMethod });
4602
+ try {
4603
+ const showId = params.showId || resolveShowIdFromCart(state.event, state.cart) || void 0;
4604
+ const purchase = await client.createPurchase({
4605
+ items: state.cart,
4606
+ paymentMethod: params.paymentMethod,
4607
+ currency: params.currency,
4608
+ discountCode: params.discountCode ?? state.discountCode ?? void 0,
4609
+ expectedTotal: state.quote?.totalPrice,
4610
+ showId,
4611
+ idempotencyKey,
4612
+ attendees: params.attendees
4613
+ });
4614
+ const payment = await client.createPayment({
4615
+ orderId: purchase.purchase.id,
4616
+ paymentMethod: params.paymentMethod,
4617
+ currency: params.currency,
4618
+ amount: purchase.purchase.totalPrice,
4619
+ idempotencyKey: `${idempotencyKey}:payment`
4620
+ });
4621
+ const redirectUrl = resolveRedirectUrl({
4622
+ nextAction: payment.nextAction,
4623
+ redirectUrl: payment.redirectUrl,
4624
+ initPoint: payment.initPoint
4625
+ });
4626
+ const nextAction = payment.nextAction || (payment.paymentInstructions ? {
4627
+ type: "display_instructions",
4628
+ paymentInstructions: payment.paymentInstructions
4629
+ } : redirectUrl ? { type: "redirect", url: redirectUrl } : { type: "none" });
4630
+ dispatch({
4631
+ type: "PURCHASE_SUCCESS",
4632
+ purchase: purchase.purchase,
4633
+ payment,
4634
+ nextAction
4635
+ });
4636
+ emit("checkout.purchase.success", {
4637
+ purchaseId: purchase.purchase.id,
4638
+ nextActionType: nextAction.type
4639
+ });
4640
+ if (nextAction.type === "display_instructions") {
4641
+ void watchPayment({
4642
+ intervalMs: 1e4,
4643
+ timeoutMs: 45 * 60 * 1e3
4644
+ }).catch(() => {
4645
+ });
4646
+ }
4647
+ if (nextAction.type === "redirect" && nextAction.url) {
4648
+ navigateTopLevel(nextAction.url);
4649
+ }
4650
+ return { purchaseId: purchase.purchase.id, payment, nextAction };
4651
+ } catch (err) {
4652
+ const error = toTickeanError(err);
4653
+ dispatch({ type: "PURCHASE_FAILURE", error });
4654
+ emit("checkout.purchase.error", { code: error.code });
4655
+ throw error;
4656
+ }
4657
+ };
4658
+ const confirmPayment = async (params) => {
4659
+ const payment = await client.confirmPayment({
4660
+ ...params,
4661
+ idempotencyKey: params?.idempotencyKey || generateIdempotencyKey()
4662
+ });
4663
+ const nextAction = payment.nextAction || { type: "none" };
4664
+ dispatch({ type: "SET_NEXT_ACTION", nextAction, payment });
4665
+ emit("checkout.payment.confirmed", { nextActionType: nextAction.type });
4666
+ return payment;
4667
+ };
4668
+ const watchPayment = async (watchOptions) => {
4669
+ dispatch({ type: "PROCESSING" });
4670
+ emit("checkout.payment.watch.start");
4671
+ watchAbort?.abort();
4672
+ activeSocketWatch?.dispose();
4673
+ watchAbort = new AbortController();
4674
+ const localAbort = watchAbort;
4675
+ const onOuterAbort = () => localAbort.abort();
4676
+ watchOptions?.signal?.addEventListener("abort", onOuterAbort);
4677
+ const timeoutMs = watchOptions?.timeoutMs ?? 45 * 60 * 1e3;
4678
+ const cartRef = state.purchase?.shoppingCartReference;
4679
+ const purchaseId = state.purchase?.id;
4680
+ const apiBaseUrl = options.apiBaseUrl || "https://api.tickean.com";
4681
+ try {
4682
+ const status = await new Promise((resolve, reject) => {
4683
+ let settled = false;
4684
+ const finish = (fn) => {
4685
+ if (settled) return;
4686
+ settled = true;
4687
+ localAbort.abort();
4688
+ activeSocketWatch?.dispose();
4689
+ activeSocketWatch = null;
4690
+ fn();
4691
+ };
4692
+ if (!options.demo && cartRef) {
4693
+ activeSocketWatch = watchPaymentSocket({
4694
+ apiBaseUrl,
4695
+ shoppingCartReference: cartRef,
4696
+ purchaseId,
4697
+ signal: localAbort.signal,
4698
+ timeoutMs
4699
+ });
4700
+ emit("checkout.payment.socket.start", {
4701
+ shoppingCartReference: cartRef
4702
+ });
4703
+ void activeSocketWatch.promise.then(async (snap) => {
4704
+ emit("checkout.payment.socket.confirmed", {
4705
+ status: snap.status,
4706
+ purchaseId: snap.purchaseId || purchaseId
4707
+ });
4708
+ try {
4709
+ return await client.getPaymentStatus();
4710
+ } catch {
4711
+ return {
4712
+ status: snap.status || "SUCCESS",
4713
+ purchase: state.purchase ? { ...state.purchase, status: "COMPLETED" } : null,
4714
+ payment: state.payment,
4715
+ nextAction: { type: "none" },
4716
+ requiresAction: false
4717
+ };
4718
+ }
4719
+ }).then((result) => finish(() => resolve(result))).catch(() => {
4720
+ });
4721
+ }
4722
+ void client.watchPayment({
4723
+ intervalMs: watchOptions?.intervalMs ?? (cartRef ? 1e4 : 3e3),
4724
+ timeoutMs,
4725
+ signal: localAbort.signal
4726
+ }).then((result) => finish(() => resolve(result))).catch((err) => {
4727
+ if (!settled) finish(() => reject(err));
4728
+ });
4729
+ });
4730
+ if (["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
4731
+ String(status.status || "").toUpperCase()
4732
+ ) || ["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
4733
+ String(status.purchase?.status || "").toUpperCase()
4734
+ )) {
4735
+ dispatch({ type: "COMPLETED", purchase: status.purchase });
4736
+ emit("checkout.completed");
4737
+ } else if (status.nextAction && status.nextAction.type !== "none") {
4738
+ dispatch({
4739
+ type: "SET_NEXT_ACTION",
4740
+ nextAction: status.nextAction,
4741
+ payment: status.payment
4742
+ });
4743
+ }
4744
+ return status;
4745
+ } catch (err) {
4746
+ const error = toTickeanError(err);
4747
+ if (error.code !== "checkout_payment_timeout") {
4748
+ dispatch({ type: "FAILED", error });
4749
+ }
4750
+ emit("checkout.payment.watch.error", { code: error.code });
4751
+ throw error;
4752
+ } finally {
4753
+ watchOptions?.signal?.removeEventListener("abort", onOuterAbort);
4754
+ activeSocketWatch?.dispose();
4755
+ activeSocketWatch = null;
4756
+ if (watchAbort === localAbort) watchAbort = null;
4757
+ }
4758
+ };
4759
+ const refreshCatalog = async () => {
4760
+ const catalog = await client.getCatalog();
4761
+ dispatch({ type: "SET_EVENT", event: catalog });
4762
+ return catalog;
4763
+ };
4764
+ const initialize = async () => {
4765
+ dispatch({ type: "INIT_START" });
4766
+ emit("checkout.init.start", { eventSlug: options.eventSlug });
4767
+ try {
4768
+ const resumeCode = options.resumeCode?.trim();
4769
+ if (resumeCode) {
4770
+ const recovered = await client.exchangeRecovery({ code: resumeCode });
4771
+ const session2 = {
4772
+ sessionId: recovered.sessionId,
4773
+ sessionToken: recovered.sessionToken,
4774
+ expiresAt: recovered.expiresAt,
4775
+ event: recovered.event,
4776
+ capabilities: recovered.capabilities || {},
4777
+ shoppingCartReference: recovered.shoppingCartReference,
4778
+ nextAction: recovered.nextAction,
4779
+ phase: recovered.phase
4780
+ };
4781
+ dispatch({
4782
+ type: "INIT_SUCCESS",
4783
+ session: session2,
4784
+ event: recovered.event
4785
+ });
4786
+ dispatch({
4787
+ type: "REHYDRATE",
4788
+ partial: {
4789
+ cart: recovered.cart || [],
4790
+ discountCode: recovered.discountCode || null,
4791
+ buyer: recovered.buyer || null,
4792
+ buyerVerified: Boolean(recovered.buyerVerified || recovered.buyer),
4793
+ otpSent: Boolean(recovered.buyerVerified || recovered.buyer),
4794
+ purchase: recovered.purchase || null,
4795
+ payment: recovered.payment || null,
4796
+ nextAction: recovered.nextAction || { type: "none" },
4797
+ phase: recovered.phase === "completed" ? "completed" : recovered.phase === "processing" || recovered.suggestedStep === "PAYMENT_PENDING" ? "processing" : recovered.buyer ? "ready_to_purchase" : "browsing",
4798
+ loading: false,
4799
+ error: null
4800
+ }
4801
+ });
4802
+ if ((recovered.nextAction?.type === "display_instructions" || recovered.suggestedStep === "PAYMENT_PENDING") && recovered.purchase) {
4803
+ void watchPayment({
4804
+ intervalMs: 1e4,
4805
+ timeoutMs: 45 * 60 * 1e3
4806
+ }).catch(() => void 0);
4807
+ }
4808
+ persist();
4809
+ emit("checkout.init.success", {
4810
+ sessionId: session2.sessionId,
4811
+ resumed: true
4812
+ });
4813
+ return;
4814
+ }
4815
+ const stored = persistence?.get(persistenceKey);
4816
+ let session = null;
4817
+ if (stored?.sessionToken) {
4818
+ try {
4819
+ client.session = {
4820
+ sessionId: "",
4821
+ sessionToken: stored.sessionToken,
4822
+ expiresAt: "",
4823
+ event: {
4824
+ id: "",
4825
+ slug: options.eventSlug,
4826
+ title: "",
4827
+ shows: []
4828
+ },
4829
+ capabilities: {}
4830
+ };
4831
+ const resumed = await client.getSession();
4832
+ session = {
4833
+ ...resumed,
4834
+ sessionToken: stored.sessionToken,
4835
+ event: resumed.event
4836
+ };
4837
+ } catch {
4838
+ client.session = null;
4839
+ persistence?.remove(persistenceKey);
4840
+ }
4841
+ }
4842
+ if (!session) {
4843
+ session = await client.createSession({
4844
+ eventSlug: options.eventSlug,
4845
+ returnUrl: options.returnUrl
4846
+ });
4847
+ }
4848
+ dispatch({
4849
+ type: "INIT_SUCCESS",
4850
+ session,
4851
+ event: session.event
4852
+ });
4853
+ if (session.otpVerified || stored?.buyerVerified) {
4854
+ dispatch({
4855
+ type: "REHYDRATE",
4856
+ partial: {
4857
+ buyerVerified: true,
4858
+ otpSent: true,
4859
+ buyer: session.buyerId ? {
4860
+ id: String(session.buyerId),
4861
+ phone: ""
4862
+ } : void 0
4863
+ }
4864
+ });
4865
+ }
4866
+ if (stored?.cart?.length) {
4867
+ dispatch({ type: "SET_CART", cart: stored.cart });
4868
+ if (stored.discountCode) {
4869
+ dispatch({ type: "SET_DISCOUNT", discountCode: stored.discountCode });
4870
+ }
4871
+ scheduleQuote();
4872
+ }
4873
+ emit("checkout.init.success", { sessionId: session.sessionId });
4874
+ } catch (err) {
4875
+ const error = toTickeanError(err);
4876
+ dispatch({ type: "INIT_FAILURE", error });
4877
+ emit("checkout.init.error", { code: error.code });
4878
+ throw error;
4879
+ }
4880
+ };
4881
+ const dispose = () => {
4882
+ disposed = true;
4883
+ if (quoteTimer) clearTimeout(quoteTimer);
4884
+ watchAbort?.abort();
4885
+ activeSocketWatch?.dispose();
4886
+ activeSocketWatch = null;
4887
+ listeners.clear();
4888
+ };
4889
+ const ready = initialize().catch(() => {
4890
+ });
4891
+ return {
4892
+ client,
4893
+ ready,
4894
+ getSnapshot,
4895
+ subscribe,
4896
+ setCartItem,
4897
+ setCart,
4898
+ applyDiscountCode,
4899
+ lookupBuyer,
4900
+ sendOtp,
4901
+ verifyOtp,
4902
+ purchaseAndPay,
4903
+ changePaymentMethod,
4904
+ confirmPayment,
4905
+ watchPayment,
4906
+ refreshCatalog,
4907
+ dispose,
4908
+ /** @internal test helper */
4909
+ _dispatch: dispatch
4910
+ };
4911
+ }
367
4912
  export {
368
4913
  TickeanError,
369
- createTickean
4914
+ checkoutReducer,
4915
+ createCheckoutController,
4916
+ createEventEmitterTelemetry,
4917
+ createInitialState,
4918
+ createMemoryPersistence,
4919
+ createNoopTelemetry,
4920
+ createSessionStoragePersistence,
4921
+ createTickean,
4922
+ navigateTopLevel,
4923
+ resolveRedirectUrl,
4924
+ watchPaymentSocket
370
4925
  };