@callimacus/thamyr-liquid 4.3.4 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.core.md CHANGED
@@ -3,6 +3,38 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [4.4.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.3.5...thamyr-core-v4.4.0) (2026-09-29)
7
+
8
+
9
+ ### Features
10
+
11
+ * **callimacus:** export additional action types from hooks for better type safety ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
12
+ * **ContentAPI:** implement getDocumentByGroupId method to retrieve documents based on language and group ID ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
13
+ * **hooks.ts:** enhance useProducts, useAnalytics, and useSitemap hooks with TypeScript interfaces and detailed documentation ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
14
+ * **react:** add eslint-config-xo-react for better React linting ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
15
+ * **react:** implement Callimacus store and hooks for state management ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
16
+ * **service.ts:** add polling transport option to socket connection for improved connectivity in restricted environments ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
17
+ * **service.ts:** add referrer to auth object for enhanced tracking and analytics ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
18
+ * **thamyr:** parity with the v2 wire, rounds without a message, acknowledged suggestions, receptors and block keys ([#784](https://github.com/callimacus/thamyr-sdk/issues/784)) ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
19
+
20
+
21
+ ### Bug Fixes
22
+
23
+ * **AnalyticsAPI.ts, Thamyr.ts:** remove array type from content parameter in trackEvent method for consistency and simplification ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
24
+ * **core/package.json:** update @solomei-ai/intent to version 1.9.2 for latest features and fixes ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
25
+ * **package.json:** remove redundant comma in scripts section to ensure JSON validity ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
26
+ * **package.json:** update @types/react to version 19.2.10 for improved type definitions chore(package.json): bump react and react-dom to version 19.2.4 for latest features and fixes ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
27
+ * **react:** ensure consistent export style across components ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
28
+ * **react:** remove obsolete global type declarations ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
29
+ * remove legacy-peer-deps from .npmrc and update registry configuration for scoped package ([fe22166](https://github.com/callimacus/thamyr-sdk/commit/fe221665c994723d546f972c9379cdf4b4eecbc8))
30
+
31
+ ## [4.3.5](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.3.4...thamyr-core-v4.3.5) (2026-09-29)
32
+
33
+
34
+ ### Bug Fixes
35
+
36
+ * **npm:** publish the five packages as @callimacus/* ([#791](https://github.com/callimacus/thamyr-sdk/issues/791)) ([7beae9a](https://github.com/callimacus/thamyr-sdk/commit/7beae9a15f713602aa73d0ddb8ae82d045a725c0))
37
+
6
38
  ## [4.3.4](https://github.com/solomei-ai/thamyr-sdk/compare/thamyr-core-v4.3.3...thamyr-core-v4.3.4) (2026-09-27)
7
39
 
8
40
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.4.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.3.5...thamyr-liquid-v4.4.0) (2026-09-29)
4
+
5
+
6
+ ### Miscellaneous Chores
7
+
8
+ * **thamyr-liquid:** Synchronize thamyr versions
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @callimacus/thamyr-core bumped from ^4.3.5 to ^4.4.0
16
+
17
+ ## [4.3.5](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.3.4...thamyr-liquid-v4.3.5) (2026-09-29)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * **npm:** publish the five packages as @callimacus/* ([#791](https://github.com/callimacus/thamyr-sdk/issues/791)) ([7beae9a](https://github.com/callimacus/thamyr-sdk/commit/7beae9a15f713602aa73d0ddb8ae82d045a725c0))
23
+
24
+
25
+ ### Dependencies
26
+
27
+ * The following workspace dependencies were updated
28
+ * dependencies
29
+ * @callimacus/thamyr-core bumped from ^4.3.4 to ^4.3.5
30
+
3
31
  ## [4.3.4](https://github.com/solomei-ai/thamyr-sdk/compare/thamyr-liquid-v4.3.3...thamyr-liquid-v4.3.4) (2026-09-27)
4
32
 
5
33
 
package/MIGRATION.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Thamyr SDK migration guide
2
2
 
3
- This file ships inside every `@callimacus/thamyr*` package; the same guide is published at [docs.callimacus.ai/thamyr-sdk/8-migration](https://docs.callimacus.ai/thamyr-sdk/8-migration) (Callimacus account required). It covers every break since 1.x; release-by-release detail is in `CHANGELOG.md` (this package) and, in the framework packages, `CHANGELOG.core.md` (the contract and types — in `@callimacus/thamyr-core` that is `CHANGELOG.md` itself).
3
+ This file ships inside every `@solomei-ai/thamyr*` package; the same guide is published at [docs.callimacus.ai/thamyr-sdk/8-migration](https://docs.callimacus.ai/thamyr-sdk/8-migration) (Callimacus account required). It covers every break since 1.x; release-by-release detail is in `CHANGELOG.md` (this package) and, in the framework packages, `CHANGELOG.core.md` (the contract and types — in `@solomei-ai/thamyr-core` that is `CHANGELOG.md` itself).
4
4
 
5
5
  **The wire protocol has not changed since v1.** Any major talks to the same server, so upgrading is an exercise you can schedule: bump, run your type checker, work through the errors. Every signature change is compile-time; three things are not — error handling, retries, and since 4.0.2 the constructor rejecting an empty or relative `endpoint` — so read [Error handling](#error-handling) and [`endpoint` must be an absolute URL](#endpoint-must-be-an-absolute-url-402) before you start.
6
6
 
@@ -8,7 +8,7 @@ This file ships inside every `@callimacus/thamyr*` package; the same guide is pu
8
8
 
9
9
  Sites still on 1.x (the last 1.x release is 1.8.2) cross three majors at once. Work through the errors in this order:
10
10
 
11
- 1. **`@callimacus/common` imports.** The package left the dependency tree in v2.0.0; every wire type and enum a client needs is exported by `@callimacus/thamyr`. One rewrite — see [`@callimacus/common` is no longer a dependency](#solomei-aicommon-is-no-longer-a-dependency). Imports from `@callimacus/thamyr-core` keep working (`@callimacus/thamyr` re-exports all of it), but declare the package or import from `@callimacus/thamyr` instead of relying on hoisting.
11
+ 1. **`@solomei-ai/common` imports.** The package left the dependency tree in v2.0.0; every wire type and enum a client needs is exported by `@solomei-ai/thamyr`. One rewrite — see [`@solomei-ai/common` is no longer a dependency](#solomei-aicommon-is-no-longer-a-dependency). Imports from `@solomei-ai/thamyr-core` keep working (`@solomei-ai/thamyr` re-exports all of it), but declare the package or import from `@solomei-ai/thamyr` instead of relying on hoisting.
12
12
  2. **`accessToken` → `clientId`** on the constructor / `useInitThamyr` — see [Initialization](#initialization-accesstoken--clientid).
13
13
  3. **Contract methods take one parameters object and resolve `{data, error, response}`; none of them rejects on HTTP status** (only `sitemap.getSitemap()` still does). Read [Error handling](#error-handling) before touching code that caught or retried — a `catch` on `err.status` silently stops running, and a retry-on-500 handler can loop. Signature-by-signature mapping under [New method signatures](#new-method-signatures-on-the-api-namespaces).
14
14
  4. **`language` is required** on `content.*` — v1 sent `'en'` when you omitted it. Pass `'en'` to keep behaviour identical, or your real locale to fix it.
@@ -16,10 +16,10 @@ Sites still on 1.x (the last 1.x release is 1.8.2) cross three majors at once. W
16
16
  6. **Protocol enums are `as const` objects.** Runtime values are unchanged; `Enum.member` in a type position becomes `typeof Enum.member` — see [Protocol enums](#protocol-enums-are-as-const-objects).
17
17
  7. **Salesforce `c_*` attributes and media extras are `unknown`** on `Basket`, on each `ProductItem` and on `Image.properties.cloudinary` — declare your shapes once, see [Custom attributes](#custom-attributes-are-unknown).
18
18
  8. **v4:** `skesis.*` takes a parameters object and resolves the envelope; `products.*` is deprecated but stays; `endpoint` must be an absolute URL; `Basket.basketId` is required — see [Migrating to v4](#migrating-to-v4).
19
- 9. **Ride-along:** `@callimacus/intent` moves to 2.1.2 or later — see [Intent SDK 2.1.2 rides along](#intent-sdk-212-rides-along).
19
+ 9. **Ride-along:** `@solomei-ai/intent` moves to 2.1.2 or later — see [Intent SDK 2.1.2 rides along](#intent-sdk-212-rides-along).
20
20
  10. **Deploy:** if your build copies `VITE_*` variables into `.env`, delete those lines — see [`endpoint` must be an absolute URL](#endpoint-must-be-an-absolute-url-402).
21
21
 
22
- Dependencies your build scripts only had transitively through `@callimacus/common` (a `zod` import in a script, for instance) disappear too — declare them yourself.
22
+ Dependencies your build scripts only had transitively through `@solomei-ai/common` (a `zod` import in a script, for instance) disappear too — declare them yourself.
23
23
 
24
24
  The call sites a storefront on 1.x most often has, v1 → v4 in one hop:
25
25
 
@@ -97,11 +97,11 @@ Reading code is unaffected by all of these; hand-written fixtures and mocks type
97
97
 
98
98
  ## Intent SDK 2.1.2 rides along
99
99
 
100
- `@callimacus/thamyr-core` 4 requires `@callimacus/intent` 2.1.2 or later, so npm upgrades a 2.0.x lock on the same install. If your site calls the Intent SDK directly, read its changelog entries for 2.1.0 (platform-free core, [#278](https://github.com/callimacus/intent-sdk/issues/278)) and 2.1.1 (hrefs that lead nowhere are dropped instead of forwarded, [#289](https://github.com/callimacus/intent-sdk/issues/289)), and verify the consent banner on staging: accepting sets the `intent_sid` cookie, revoking clears it. If your site declares its own `@callimacus/intent` dependency, bump its range to `^2.1.2` — or drop it and import `initIntent` / `setConsent` from `@callimacus/thamyr`, which re-exports the Intent SDK — and check that `npm ls @callimacus/intent` shows a single copy.
100
+ `@solomei-ai/thamyr-core` 4 requires `@solomei-ai/intent` 2.1.2 or later, so npm upgrades a 2.0.x lock on the same install. If your site calls the Intent SDK directly, read its changelog entries for 2.1.0 (platform-free core, [#278](https://github.com/solomei-ai/intent-sdk/issues/278)) and 2.1.1 (hrefs that lead nowhere are dropped instead of forwarded, [#289](https://github.com/solomei-ai/intent-sdk/issues/289)), and verify the consent banner on staging: accepting sets the `intent_sid` cookie, revoking clears it. If your site declares its own `@solomei-ai/intent` dependency, bump its range to `^2.1.2` — or drop it and import `initIntent` / `setConsent` from `@solomei-ai/thamyr`, which re-exports the Intent SDK — and check that `npm ls @solomei-ai/intent` shows a single copy.
101
101
 
102
102
  # Migrating to v3: cart becomes a contract namespace
103
103
 
104
- v3.0.0 (2026-08-07, [#725](https://github.com/callimacus/thamyr-sdk/issues/725)). The `cart` namespace joined the generated contract surface: methods take a flat parameters object and resolve `{data, error, response}` like the other contract namespaces, and the `CartAPI` class export is gone (the `Basket`/`ProductItem` types remain, now generated from Salesforce's own published schema). `useCart()` keeps its method names and positional arguments, but resolves the envelope instead of the bare basket:
104
+ v3.0.0 (2026-08-07, [#725](https://github.com/solomei-ai/thamyr-sdk/issues/725)). The `cart` namespace joined the generated contract surface: methods take a flat parameters object and resolve `{data, error, response}` like the other contract namespaces, and the `CartAPI` class export is gone (the `Basket`/`ProductItem` types remain, now generated from Salesforce's own published schema). `useCart()` keeps its method names and positional arguments, but resolves the envelope instead of the bare basket:
105
105
 
106
106
  | v1 / v2 | v3+ |
107
107
  | ---------------------------------------------- | ------------------------------------------------------------------ |
@@ -118,7 +118,7 @@ The `commerce-sdk-isomorphic` dependency left with `CartAPI`; non-SFCC consumers
118
118
  Salesforce `c_*` attributes on `Basket` **and on each `ProductItem` in `Basket.productItems`**, and extra keys on `Image.properties.cloudinary` (beyond its typed `publicId`, `cloudName` and `secureDistribution`), are typed `[key: string]: unknown` (v1: `any`). Every former `any` access is now TS18046 `'basket.c_x' is of type 'unknown'` (or TS2322 where the value lands in a typed slot) — typically in templates and components far from the SDK call. Declare your project's shapes once and cast at the boundary:
119
119
 
120
120
  ```ts
121
- import type {Basket, ProductItem} from '@callimacus/thamyr';
121
+ import type {Basket, ProductItem} from '@solomei-ai/thamyr';
122
122
 
123
123
  type MyItem = ProductItem & {c_image?: string; c_analytics?: {color?: {code: string}}};
124
124
  type MyBasket = Basket & {c_productsQuantity: number; productItems?: MyItem[]};
@@ -133,22 +133,22 @@ The product family is different: on `VariationGroup`, `MasterProduct`, `SetProdu
133
133
 
134
134
  v2 aligns the SDK's types and methods exactly with what the platform serves, and every surface deprecated during v1 is gone. The wire protocol is unchanged — a v1 SDK and a v2 SDK speak to the same server identically; everything below is compile-time.
135
135
 
136
- ## `@callimacus/common` is no longer a dependency
136
+ ## `@solomei-ai/common` is no longer a dependency
137
137
 
138
- v1 pulled `@callimacus/common` — and its server-side dependency tree (langchain, openai, mysql2, zod, uuid, …) — into every browser bundle, and many sites imported wire types from it directly without declaring it. v2 drops it, so those imports fail with `Cannot find module '@callimacus/common'` after the bump. Every type and enum a site takes from it is exported by `@callimacus/thamyr` (through `@callimacus/thamyr-core`), so the migration is a rename:
138
+ v1 pulled `@solomei-ai/common` — and its server-side dependency tree (langchain, openai, mysql2, zod, uuid, …) — into every browser bundle, and many sites imported wire types from it directly without declaring it. v2 drops it, so those imports fail with `Cannot find module '@solomei-ai/common'` after the bump. Every type and enum a site takes from it is exported by `@solomei-ai/thamyr` (through `@solomei-ai/thamyr-core`), so the migration is a rename:
139
139
 
140
140
  ```sh
141
141
  # macOS
142
- grep -rl '@callimacus/common' src | xargs sed -i '' 's#@callimacus/common#@callimacus/thamyr#g'
142
+ grep -rl '@solomei-ai/common' src | xargs sed -i '' 's#@solomei-ai/common#@solomei-ai/thamyr#g'
143
143
  # GNU
144
- grep -rl '@callimacus/common' src | xargs sed -i 's#@callimacus/common#@callimacus/thamyr#g'
144
+ grep -rl '@solomei-ai/common' src | xargs sed -i 's#@solomei-ai/common#@solomei-ai/thamyr#g'
145
145
  ```
146
146
 
147
147
  Then merge any duplicated import statements and run your type checker: a name it still cannot find was a server-side helper with no client equivalent (`Chapter.fromSLChapter`, `Story.fromSLStory`, `story.getHistoryMessages()`).
148
148
 
149
- Do **not** add `@callimacus/common` back as a dependency: its current majors (12.x) are a server-side package (mysql2, winston, openai, langchain) that is not kept in step with the SDK's wire types.
149
+ Do **not** add `@solomei-ai/common` back as a dependency: its current majors (12.x) are a server-side package (mysql2, winston, openai, langchain) that is not kept in step with the SDK's wire types.
150
150
 
151
- The wire types and enums a v1 site imported from `@callimacus/common`, all exported by `@callimacus/thamyr` 4.x — types: `Basket`, `BCProduct`, `Block`, `Chapter`, `CustomBlock`, `ErrorMessage`, `Gallery`, `GenericProduct`, `HomePage`, `Image`, `LegacyBlock`, `LocalizedEPArtwork`, `LocalizedEPChapter`, `MasterProduct`, `MasterProductWithVariationGroup`, `OptionItem`, `ProductItem`, `ProductMatch`, `RecommendationsResponse`, `SetProduct`, `SkesisItem`, `SkesisRelatedResponse`, `SkesisSimilarResponse`, `SLDocument`, `SLDocumentSection`, `SLInputEvent`, `Story`, `ThamyrResponse`, `Topic`, `TopicContentsPage`, `TopicSummary`, `Variant`, `VariationAttribute`, `VariationGroup`, `Video`, `WhisperPayload`. Values: `ChapterStatus`, `ClientEvents`, `GalleryMode`, `isCustomBlock`, `isMasterProduct`, `isSetProduct`, `ServerEvents`, `SLInputEventType`, `ThamyrResponseType`.
151
+ The wire types and enums a v1 site imported from `@solomei-ai/common`, all exported by `@solomei-ai/thamyr` 4.x — types: `Basket`, `BCProduct`, `Block`, `Chapter`, `CustomBlock`, `ErrorMessage`, `Gallery`, `GenericProduct`, `HomePage`, `Image`, `LegacyBlock`, `LocalizedEPArtwork`, `LocalizedEPChapter`, `MasterProduct`, `MasterProductWithVariationGroup`, `OptionItem`, `ProductItem`, `ProductMatch`, `RecommendationsResponse`, `SetProduct`, `SkesisItem`, `SkesisRelatedResponse`, `SkesisSimilarResponse`, `SLDocument`, `SLDocumentSection`, `SLInputEvent`, `Story`, `ThamyrResponse`, `Topic`, `TopicContentsPage`, `TopicSummary`, `Variant`, `VariationAttribute`, `VariationGroup`, `Video`, `WhisperPayload`. Values: `ChapterStatus`, `ClientEvents`, `GalleryMode`, `isCustomBlock`, `isMasterProduct`, `isSetProduct`, `ServerEvents`, `SLInputEventType`, `ThamyrResponseType`.
152
152
 
153
153
  ## Initialization: `accessToken` → `clientId`
154
154
 
@@ -232,7 +232,7 @@ Two consequences for code written against v1:
232
232
  - **Anything that keyed off `err.status` in a `catch` stops running** unless the call opts into throwing. Either read `error` and `response?.status` from the envelope, or keep the v1 contract with the option the generated client already has:
233
233
 
234
234
  ```ts
235
- import {ThamyrHttpError} from '@callimacus/thamyr';
235
+ import {ThamyrHttpError} from '@solomei-ai/thamyr';
236
236
 
237
237
  const {data: basket} = await thamyr.cart.getCart({throwOnError: true}); // Basket, or rejects
238
238
 
@@ -255,7 +255,7 @@ Two consequences for code written against v1:
255
255
  - `ThamyrResponse` gains the `story-reset` variant, `chapter-deleted` carries the deprecated `roundId` alias, custom blocks carry `name` and `metaJson`, and `ErrorMessage` gains optional `reason`.
256
256
  - Protocol enums (`SLInputEventType`, `ThamyrResponseType`, `ChapterStatus`, …) keep their members and values; comparisons and switches are unaffected — but they are `as const` objects now, not TypeScript `enum`s, which changes two idioms: see [below](#protocol-enums-are-as-const-objects).
257
257
  - New exports: the `isCustomBlock` block guard, the `CallimacusApi` client class and `createContractClient` (thamyr-core), and the full product family (`BCProduct`, `SetProduct`, `VariationGroup`, …).
258
- - `@callimacus/common` is no longer a dependency (nor `uuid`) — see [above](#solomei-aicommon-is-no-longer-a-dependency).
258
+ - `@solomei-ai/common` is no longer a dependency (nor `uuid`) — see [above](#solomei-aicommon-is-no-longer-a-dependency).
259
259
 
260
260
  ## Protocol enums are `as const` objects
261
261
 
@@ -10,7 +10,7 @@
10
10
  * Socket.IO v4.8.4
11
11
  * (c) 2014-2026 Guillermo Rauch
12
12
  * Released under the MIT License.
13
- */const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach(s=>{e[t[s]]=s});const s={type:"error",data:"parser error"},i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),n="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,c)=>i&&s instanceof Blob?o?c(s):a(s,c):n&&(s instanceof ArrayBuffer||r(s))?o?c(s):a(new Blob([s]),c):c(t[e]+(s||"")),a=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let h;const u="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)u["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const d="function"==typeof ArrayBuffer,l=(t,i)=>{if("string"!=typeof t)return{type:"message",data:f(t,i)};const n=t.charAt(0);return"b"===n?{type:"message",data:p(t.substring(1),i)}:e[n]?t.length>1?{type:e[n],data:t.substring(1)}:{type:e[n]}:s},p=(t,e)=>{if(d){const s=(t=>{let e,s,i,n,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),d=new Uint8Array(h);for(e=0;e<a;e+=4)s=u[t.charCodeAt(e)],i=u[t.charCodeAt(e+1)],n=u[t.charCodeAt(e+2)],r=u[t.charCodeAt(e+3)],d[c++]=s<<2|i>>4,d[c++]=(15&i)<<4|n>>2,d[c++]=(3&n)<<6|63&r;return h})(t);return f(s,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,y=String.fromCharCode(30);function m(){return new TransformStream({transform(t,e){!function(t,e){i&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):n&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):o(t,!1,t=>{h||(h=new TextEncoder),e(h.encode(t))})}(t,s=>{const i=s.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(n[0]|=128),e.enqueue(n),e.enqueue(s)})}})}let g;function b(t){return t.reduce((t,e)=>t+e.length,0)}function v(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let i=0;for(let n=0;n<e;n++)s[n]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),s}function w(t){if(t)return function(t){for(var e in w.prototype)t[e]=w.prototype[e];return t}(t)}w.prototype.on=w.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},w.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var s,i=this.t["$"+t];if(!i)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var n=0;n<i.length;n++)if((s=i[n])===e||s.fn===e){i.splice(n,1);break}return 0===i.length&&delete this.t["$"+t],this},w.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),s=this.t["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(s){i=0;for(var n=(s=s.slice(0)).length;i<n;++i)s[i].apply(this,e)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},w.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(t,...e){return e.reduce((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e),{})}const O=R.setTimeout,A=R.clearTimeout;function T(t,e){e.useNativeTimers?(t.setTimeoutFn=O.bind(R),t.clearTimeoutFn=A.bind(R)):(t.setTimeoutFn=R.setTimeout.bind(R),t.clearTimeoutFn=R.clearTimeout.bind(R))}function C(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class S extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class N extends w{constructor(t){super(),this.writable=!1,T(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new S(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=l(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this.i()+this.o()+this.opts.path+this.h(e)}i(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}o(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}h(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}class B extends N{constructor(){super(...arguments),this.u=!1}get name(){return"polling"}doOpen(){this.l()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.u||!this.writable){let t=0;this.u&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}l(){this.u=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(y),i=[];for(let t=0;t<s.length;t++){const n=l(s[t],e);if(i.push(n),"error"===n.type)break}return i})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this.u=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.l())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,i=new Array(s);let n=0;t.forEach((t,r)=>{o(t,!1,t=>{i[r]=t,++n===s&&e(i.join(y))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let x=!1;try{x="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const U=x;function I(){}class j extends B{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}let L=class t extends w{constructor(t,e,s){super(),this.createRequest=t,T(this,s),this.p=s,this.v=s.method||"GET",this.m=e,this.k=void 0!==s.data?s.data:null,this.A()}A(){var e;const s=E(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this.p.xd;const i=this.O=this.createRequest(s);try{i.open(this.v,this.m,!0);try{if(this.p.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&i.setRequestHeader(t,this.p.extraHeaders[t])}}catch(e){}if("POST"===this.v)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{i.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.p.cookieJar)||void 0===e||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(i.timeout=this.p.requestTimeout),i.onreadystatechange=()=>{var t;3===i.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof i.status?i.status:0)},0))},i.send(this.k)}catch(e){return void this.setTimeoutFn(()=>{this.j(e)},0)}"undefined"!=typeof document&&(this.B=t.requestsCount++,t.requests[this.B]=this)}j(t){this.emitReserved("error",t,this.O),this.C(!0)}C(e){if(void 0!==this.O&&null!==this.O){if(this.O.onreadystatechange=I,e)try{this.O.abort()}catch(e){}"undefined"!=typeof document&&delete t.requests[this.B],this.O=null}}_(){const t=this.O.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.C())}abort(){this.C()}};function D(){for(let t in L.requests)L.requests.hasOwnProperty(t)&&L.requests[t].abort()}L.requestsCount=0,L.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",D):"function"==typeof addEventListener&&addEventListener("onpagehide"in R?"pagehide":"unload",D,!1));const _=function(){const t=q({xdomain:!1});return t&&null!==t.responseType}();function q(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||U))return new XMLHttpRequest}catch(t){}if(!e)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const M="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class $ extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=M?{}:E(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws.T.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;o(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const V=R.WebSocket||R.MozWebSocket;const P={websocket:class extends ${createSocket(t,e,s){return M?new V(t,e,s):e?new V(t,e):new V(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this.N=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this.N.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.N.ready.then(()=>{this.N.createBidirectionalStream().then(t=>{const e=function(t,e){g||(g=new TextDecoder);const i=[];let n=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(i.push(a);;){if(0===n){if(b(i)<1)break;const t=v(i,1);o=!(128&~t[0]),r=127&t[0],n=r<126?3:126===r?1:2}else if(1===n){if(b(i)<2)break;const t=v(i,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),n=3}else if(2===n){if(b(i)<8)break;const t=v(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),o=e.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(s);break}r=o*Math.pow(2,32)+e.getUint32(4),n=3}else{if(b(i)<r)break;const t=v(i,r);c.enqueue(l(o?t:g.decode(t),e)),n=0}if(0===r||r>t){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),n=m();n.readable.pipeTo(t.writable),this.U=n.writable.getWriter();const r=()=>{i.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.U.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;this.U.write(s).then(()=>{i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends j{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=_&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new L(q,this.uri(),t)}}},F=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),i=t.indexOf("]");-1!=s&&-1!=i&&(t=t.substring(0,s)+t.substring(s,i).replace(/:/g,";")+t.substring(i,t.length));let n=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=n[o]||"";return-1!=s&&-1!=i&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(s[e]=i)}),s}(0,r.query),r}const z="function"==typeof addEventListener&&"function"==typeof removeEventListener,W=[];z&&addEventListener("offline",()=>{W.forEach(t=>t())},!1);class Y extends w{constructor(t,e={}){var s,i;if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this.P=0,this.D=[],this.M=-1,this.S=-1,this.L=-1,this.R=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=K(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=K(e.host).host);if(T(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),e.transportImplementations&&e.transports)throw new Error("specifying both 'transportImplementations' and 'transports' options is not supported");e.transportImplementations||(null===(s=e.transports)||void 0===s?void 0:s.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(i=e.transportImplementations)&&void 0!==i?i:e.transports).forEach(t=>{const e=t.prototype.name;this.transports.push(e),this.I[e]=t})):(this.transports=e.transports?[...e.transports]:["polling","websocket","webtransport"],this.I=P),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,i=s.length;t<i;t++){let i=s[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),z&&(this.opts.closeOnBeforeunload&&(this.F=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.F,!1)),"localhost"!==this.hostname&&(this.$=()=>{this.V("transport close",{description:"network connection lost"})},W.push(this.$))),this.opts.withCredentials&&(this.W=void 0),this.q()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this.I[t](s)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&Y.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.H.bind(this)).on("packet",this.X.bind(this)).on("error",this.j.bind(this)).on("close",t=>this.V("transport close",t))}J(t){let e=this.createTransport(t),s=!1;Y.priorWebsocketSuccess=!1;const i=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Y.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function n(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,n(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&n()}const h=()=>{e.removeListener("open",i),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",i),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onOpen(){if(this.readyState="open",Y.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this.D.length;t++)this.J(this.D[t])}X(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.G("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this.K();break;case"error":const e=new Error("server error");e.code=t.data,this.j(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.D=this.Y(t.upgrades),this.M=t.pingInterval,this.S=t.pingTimeout,this.L=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.K()}K(){this.clearTimeoutFn(this.Z);const t=this.M+this.S;this.R=Date.now()+t,this.Z=this.setTimeoutFn(()=>{this.V("ping timeout")},t),this.opts.autoUnref&&this.Z.unref()}H(){this.writeBuffer.splice(0,this.P),this.P=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.tt();this.transport.send(t),this.P=t.length,this.emitReserved("flush")}}tt(){if(!(this.L&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+="string"==typeof(e=i)?function(t){let e=0,s=0;for(let i=0,n=t.length;i<n;i++)e=t.charCodeAt(i),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(i++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.L)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,k(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this.G("message",t,e,s),this}send(t,e,s){return this.G("message",t,e,s),this}G(t,e,s,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof s&&(i=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:t,data:e,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}j(t){if(Y.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this.q();this.emitReserved("error",t),this.V("transport error",t)}V(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this.Z),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),z&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=W.indexOf(this.$);-1!==t&&W.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.P=0}}Y(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}Y.protocol=4;const J="function"==typeof ArrayBuffer,X=Object.prototype.toString,G="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===X.call(Blob),Z="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===X.call(File);function Q(t){return J&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||G&&t instanceof Blob||Z&&t instanceof File}function tt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(tt(t[e]))return!0;return!1}if(Q(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return tt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&tt(t[e]))return!0;return!1}function et(t){const e=[],s=t.data,i=t;return i.data=st(s,e),i.attachments=e.length,{packet:i,buffers:e}}function st(t,e,s){if(!t)return t;if(Q(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let i=0;i<t.length;i++)s[i]=st(t[i],e);return s}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!s)return st(t.toJSON(),e,!0);const i={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=st(t[s],e));return i}return t}function it(t,e){return t.data=nt(t.data,e),delete t.attachments,t}function nt(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=nt(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=nt(t[s],e));return t}const rt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ot;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(ot||(ot={}));class at extends w{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===ot.BINARY_EVENT;s||e.type===ot.BINARY_ACK?(e.type=s?ot.EVENT:ot.ACK,this.reconstructor=new ct(e)):super.emitReserved("decoded",e)}else{if(!Q(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===ot[s.type])throw new Error("unknown packet type "+s.type);if(s.type===ot.BINARY_EVENT||s.type===ot.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const n=t.substring(i,e);if(n!=Number(n)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(n);if(!ht(r)||r<1)throw new Error("Illegal attachments");if(r>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=r}if("/"===t.charAt(e+1)){const i=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(i,e)}else s.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!at.isPayloadValid(s.type,i))throw new Error("invalid payload");s.data=i}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ot.CONNECT:return ut(e);case ot.DISCONNECT:return void 0===e;case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);case ot.EVENT:case ot.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:case ot.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ct{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=it(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ht=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ut(t){return"[object Object]"===Object.prototype.toString.call(t)}var dt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return ot},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ot.EVENT&&t.type!==ot.ACK||!tt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ot.EVENT?ot.BINARY_EVENT:ot.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ot.BINARY_EVENT&&t.type!==ot.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=et(t),s=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(s),i}},Decoder:at,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||ht(e))&&function(t,e){switch(t){case ot.CONNECT:return void 0===e||ut(e);case ot.DISCONNECT:return void 0===e;case ot.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:return Array.isArray(e);case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);default:return!1}}(t.type,t.data);var e}});function lt(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ft extends w{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this.et=[],this.nt=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this.p=Object.assign({},s),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lt(t,"open",this.onopen.bind(this)),lt(t,"packet",this.onpacket.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io.ot||this.io.open(),"open"===this.io.ht&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,i,n;if(pt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this.p.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this.ct(e),this;const r={type:ot.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this.ut(t,s),r.id=t}const o=null===(i=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n.st());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}ut(t,e){var s;const i=null!==(s=this.flags.timeout)&&void 0!==s?s:this.p.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const n=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),r=(...t)=>{this.io.clearTimeoutFn(n),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((s,i)=>{const n=(t,e)=>t?i(t):s(e);n.withError=!0,e.push(n),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>(this.et[0],null!==t?s.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...i)),s.pending=!1,this.ft())),this.et.push(s),this.ft()}ft(t=!1){if(!this.connected||0===this.et.length)return;const e=this.et[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io.lt(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this.dt(t)}):this.dt(this.auth)}dt(t){this.packet({type:ot.CONNECT,data:this.yt?Object.assign({pid:this.yt,offset:this.bt},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this.wt()}wt(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ot.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ot.EVENT:case ot.BINARY_EVENT:this.onevent(t);break;case ot.ACK:case ot.BINARY_ACK:this.onack(t);break;case ot.DISCONNECT:this.ondisconnect();break;case ot.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this.gt&&this.gt.length){const e=this.gt.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this.yt&&t.length&&"string"==typeof t[t.length-1]&&(this.bt=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...i){s||(s=!0,e.packet({type:ot.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this.yt===e,this.yt=e,this.connected=!0,this.emitBuffered(),this.ft(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io.vt(this)}disconnect(){return this.connected&&this.packet({type:ot.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this.gt=this.gt||[],this.gt.push(t),this}prependAny(t){return this.gt=this.gt||[],this.gt.unshift(t),this}offAny(t){if(!this.gt)return this;if(t){const e=this.gt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.gt=[];return this}listenersAny(){return this.gt||[]}onAnyOutgoing(t){return this.kt=this.kt||[],this.kt.push(t),this}prependAnyOutgoing(t){return this.kt=this.kt||[],this.kt.unshift(t),this}offAnyOutgoing(t){if(!this.kt)return this;if(t){const e=this.kt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.kt=[];return this}listenersAnyOutgoing(){return this.kt||[]}notifyOutgoingListeners(t){if(this.kt&&this.kt.length){const e=this.kt.slice();for(const s of e)s.apply(this,t.data)}}}function yt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}yt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},yt.prototype.reset=function(){this.attempts=0},yt.prototype.setMin=function(t){this.ms=t},yt.prototype.setMax=function(t){this.max=t},yt.prototype.setJitter=function(t){this.jitter=t};class mt extends w{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,T(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new yt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const i=e.parser||dt;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this.rt=!1!==e.autoConnect,this.rt&&this.open()}reconnection(t){return arguments.length?(this.At=!!t,t||(this.skipReconnect=!0),this):this.At}reconnectionAttempts(t){return void 0===t?this.Et:(this.Et=t,this)}reconnectionDelay(t){var e;return void 0===t?this.Ot:(this.Ot=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._t:(this._t=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this.jt:(this.jt=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this.Bt=t,this):this.Bt}maybeReconnectOnOpen(){!this.ot&&this.At&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this.ht.indexOf("open"))return this;this.engine=new Y(this.uri,this.opts);const e=this.engine,s=this;this.ht="opening",this.skipReconnect=!1;const i=lt(e,"open",function(){s.onopen(),t&&t()}),n=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",n);if(!1!==this.Bt){const t=this.Bt,s=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(i),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lt(t,"ping",this.onping.bind(this)),lt(t,"data",this.ondata.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this)),lt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this.rt&&!s.active&&s.connect():(s=new ft(this,t,e),this.nsps[t]=s),s}vt(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this.xt()}lt(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}xt(){this.skipReconnect=!0,this.ot=!1,this.onclose("forced close")}disconnect(){return this.xt()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this.ht="closed",this.emitReserved("close",t,e),this.At&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this.ot||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this.Et)this.backoff.reset(),this.emitReserved("reconnect_failed"),this.ot=!1;else{const e=this.backoff.duration();this.ot=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t.ot=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gt={};function bt(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let i=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),i=K(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(s&&s.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=s.source,n=s.id,r=s.path,o=gt[n]&&r in gt[n].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(i,e):(gt[n]||(gt[n]=new mt(i,e)),a=gt[n]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(bt,{Manager:mt,Socket:ft,io:bt,connect:bt});
13
+ */const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach(s=>{e[t[s]]=s});const s={type:"error",data:"parser error"},i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),n="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,c)=>i&&s instanceof Blob?o?c(s):a(s,c):n&&(s instanceof ArrayBuffer||r(s))?o?c(s):a(new Blob([s]),c):c(t[e]+(s||"")),a=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let h;const u="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)u["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const d="function"==typeof ArrayBuffer,l=(t,i)=>{if("string"!=typeof t)return{type:"message",data:f(t,i)};const n=t.charAt(0);return"b"===n?{type:"message",data:p(t.substring(1),i)}:e[n]?t.length>1?{type:e[n],data:t.substring(1)}:{type:e[n]}:s},p=(t,e)=>{if(d){const s=(t=>{let e,s,i,n,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),d=new Uint8Array(h);for(e=0;e<a;e+=4)s=u[t.charCodeAt(e)],i=u[t.charCodeAt(e+1)],n=u[t.charCodeAt(e+2)],r=u[t.charCodeAt(e+3)],d[c++]=s<<2|i>>4,d[c++]=(15&i)<<4|n>>2,d[c++]=(3&n)<<6|63&r;return h})(t);return f(s,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,y=String.fromCharCode(30);function m(){return new TransformStream({transform(t,e){!function(t,e){i&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):n&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):o(t,!1,t=>{h||(h=new TextEncoder),e(h.encode(t))})}(t,s=>{const i=s.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const t=new DataView(n.buffer);t.setUint8(0,126),t.setUint16(1,i)}else{n=new Uint8Array(9);const t=new DataView(n.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(n[0]|=128),e.enqueue(n),e.enqueue(s)})}})}let g;function b(t){return t.reduce((t,e)=>t+e.length,0)}function v(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let i=0;for(let n=0;n<e;n++)s[n]=t[0][i++],i===t[0].length&&(t.shift(),i=0);return t.length&&i<t[0].length&&(t[0]=t[0].slice(i)),s}function w(t){if(t)return function(t){for(var e in w.prototype)t[e]=w.prototype[e];return t}(t)}w.prototype.on=w.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},w.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var s,i=this.t["$"+t];if(!i)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var n=0;n<i.length;n++)if((s=i[n])===e||s.fn===e){i.splice(n,1);break}return 0===i.length&&delete this.t["$"+t],this},w.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),s=this.t["$"+t],i=1;i<arguments.length;i++)e[i-1]=arguments[i];if(s){i=0;for(var n=(s=s.slice(0)).length;i<n;++i)s[i].apply(this,e)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},w.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(t,...e){return e.reduce((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e),{})}const O=R.setTimeout,A=R.clearTimeout;function T(t,e){e.useNativeTimers?(t.setTimeoutFn=O.bind(R),t.clearTimeoutFn=A.bind(R)):(t.setTimeoutFn=R.setTimeout.bind(R),t.clearTimeoutFn=R.clearTimeout.bind(R))}function C(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class S extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class N extends w{constructor(t){super(),this.writable=!1,T(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new S(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=l(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this.i()+this.o()+this.opts.path+this.h(e)}i(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}o(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}h(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}class B extends N{constructor(){super(...arguments),this.u=!1}get name(){return"polling"}doOpen(){this.l()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.u||!this.writable){let t=0;this.u&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}l(){this.u=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(y),i=[];for(let t=0;t<s.length;t++){const n=l(s[t],e);if(i.push(n),"error"===n.type)break}return i})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this.u=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.l())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,i=new Array(s);let n=0;t.forEach((t,r)=>{o(t,!1,t=>{i[r]=t,++n===s&&e(i.join(y))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let x=!1;try{x="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const U=x;function I(){}class j extends B{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}let L=class t extends w{constructor(t,e,s){super(),this.createRequest=t,T(this,s),this.p=s,this.v=s.method||"GET",this.m=e,this.k=void 0!==s.data?s.data:null,this.A()}A(){var e;const s=E(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this.p.xd;const i=this.O=this.createRequest(s);try{i.open(this.v,this.m,!0);try{if(this.p.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&i.setRequestHeader(t,this.p.extraHeaders[t])}}catch(e){}if("POST"===this.v)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{i.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.p.cookieJar)||void 0===e||e.addCookies(i),"withCredentials"in i&&(i.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(i.timeout=this.p.requestTimeout),i.onreadystatechange=()=>{var t;3===i.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof i.status?i.status:0)},0))},i.send(this.k)}catch(e){return void this.setTimeoutFn(()=>{this.j(e)},0)}"undefined"!=typeof document&&(this.B=t.requestsCount++,t.requests[this.B]=this)}j(t){this.emitReserved("error",t,this.O),this.C(!0)}C(e){if(void 0!==this.O&&null!==this.O){if(this.O.onreadystatechange=I,e)try{this.O.abort()}catch(e){}"undefined"!=typeof document&&delete t.requests[this.B],this.O=null}}_(){const t=this.O.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.C())}abort(){this.C()}};function D(){for(let t in L.requests)L.requests.hasOwnProperty(t)&&L.requests[t].abort()}L.requestsCount=0,L.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",D):"function"==typeof addEventListener&&addEventListener("onpagehide"in R?"pagehide":"unload",D,!1));const q=function(){const t=_({xdomain:!1});return t&&null!==t.responseType}();function _(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||U))return new XMLHttpRequest}catch(t){}if(!e)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const M="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class $ extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=M?{}:E(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws.T.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;o(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=C()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const V=R.WebSocket||R.MozWebSocket;const P={websocket:class extends ${createSocket(t,e,s){return M?new V(t,e,s):e?new V(t,e):new V(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this.N=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this.N.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.N.ready.then(()=>{this.N.createBidirectionalStream().then(t=>{const e=function(t,e){g||(g=new TextDecoder);const i=[];let n=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(i.push(a);;){if(0===n){if(b(i)<1)break;const t=v(i,1);o=!(128&~t[0]),r=127&t[0],n=r<126?3:126===r?1:2}else if(1===n){if(b(i)<2)break;const t=v(i,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),n=3}else if(2===n){if(b(i)<8)break;const t=v(i,8),e=new DataView(t.buffer,t.byteOffset,t.length),o=e.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(s);break}r=o*Math.pow(2,32)+e.getUint32(4),n=3}else{if(b(i)<r)break;const t=v(i,r);c.enqueue(l(o?t:g.decode(t),e)),n=0}if(0===r||r>t){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=t.readable.pipeThrough(e).getReader(),n=m();n.readable.pipeTo(t.writable),this.U=n.writable.getWriter();const r=()=>{i.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.U.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],i=e===t.length-1;this.U.write(s).then(()=>{i&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends j{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=q&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new L(_,this.uri(),t)}}},F=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),i=t.indexOf("]");-1!=s&&-1!=i&&(t=t.substring(0,s)+t.substring(s,i).replace(/:/g,";")+t.substring(i,t.length));let n=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=n[o]||"";return-1!=s&&-1!=i&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,i){e&&(s[e]=i)}),s}(0,r.query),r}const z="function"==typeof addEventListener&&"function"==typeof removeEventListener,W=[];z&&addEventListener("offline",()=>{W.forEach(t=>t())},!1);class Y extends w{constructor(t,e={}){var s,i;if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this.P=0,this.D=[],this.M=-1,this.S=-1,this.L=-1,this.R=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=K(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=K(e.host).host);if(T(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),e.transportImplementations&&e.transports)throw new Error("specifying both 'transportImplementations' and 'transports' options is not supported");e.transportImplementations||(null===(s=e.transports)||void 0===s?void 0:s.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(i=e.transportImplementations)&&void 0!==i?i:e.transports).forEach(t=>{const e=t.prototype.name;this.transports.push(e),this.I[e]=t})):(this.transports=e.transports?[...e.transports]:["polling","websocket","webtransport"],this.I=P),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,i=s.length;t<i;t++){let i=s[t].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}(this.opts.query)),z&&(this.opts.closeOnBeforeunload&&(this.F=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.F,!1)),"localhost"!==this.hostname&&(this.$=()=>{this.V("transport close",{description:"network connection lost"})},W.push(this.$))),this.opts.withCredentials&&(this.W=void 0),this.q()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this.I[t](s)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&Y.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.H.bind(this)).on("packet",this.X.bind(this)).on("error",this.j.bind(this)).on("close",t=>this.V("transport close",t))}J(t){let e=this.createTransport(t),s=!1;Y.priorWebsocketSuccess=!1;const i=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Y.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function n(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,n(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&n()}const h=()=>{e.removeListener("open",i),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",i),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onOpen(){if(this.readyState="open",Y.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this.D.length;t++)this.J(this.D[t])}X(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.G("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this.K();break;case"error":const e=new Error("server error");e.code=t.data,this.j(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.D=this.Y(t.upgrades),this.M=t.pingInterval,this.S=t.pingTimeout,this.L=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.K()}K(){this.clearTimeoutFn(this.Z);const t=this.M+this.S;this.R=Date.now()+t,this.Z=this.setTimeoutFn(()=>{this.V("ping timeout")},t),this.opts.autoUnref&&this.Z.unref()}H(){this.writeBuffer.splice(0,this.P),this.P=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.tt();this.transport.send(t),this.P=t.length,this.emitReserved("flush")}}tt(){if(!(this.L&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const i=this.writeBuffer[s].data;if(i&&(t+="string"==typeof(e=i)?function(t){let e=0,s=0;for(let i=0,n=t.length;i<n;i++)e=t.charCodeAt(i),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(i++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.L)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,k(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this.G("message",t,e,s),this}send(t,e,s){return this.G("message",t,e,s),this}G(t,e,s,i){if("function"==typeof e&&(i=e,e=void 0),"function"==typeof s&&(i=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const n={type:t,data:e,options:s};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}j(t){if(Y.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this.q();this.emitReserved("error",t),this.V("transport error",t)}V(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this.Z),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),z&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=W.indexOf(this.$);-1!==t&&W.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.P=0}}Y(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}Y.protocol=4;const J="function"==typeof ArrayBuffer,G=Object.prototype.toString,X="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===G.call(Blob),Z="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===G.call(File);function Q(t){return J&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||X&&t instanceof Blob||Z&&t instanceof File}function tt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(tt(t[e]))return!0;return!1}if(Q(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return tt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&tt(t[e]))return!0;return!1}function et(t){const e=[],s=t.data,i=t;return i.data=st(s,e),i.attachments=e.length,{packet:i,buffers:e}}function st(t,e,s){if(!t)return t;if(Q(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let i=0;i<t.length;i++)s[i]=st(t[i],e);return s}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!s)return st(t.toJSON(),e,!0);const i={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=st(t[s],e));return i}return t}function it(t,e){return t.data=nt(t.data,e),delete t.attachments,t}function nt(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=nt(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=nt(t[s],e));return t}const rt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ot;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(ot||(ot={}));class at extends w{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===ot.BINARY_EVENT;s||e.type===ot.BINARY_ACK?(e.type=s?ot.EVENT:ot.ACK,this.reconstructor=new ct(e)):super.emitReserved("decoded",e)}else{if(!Q(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===ot[s.type])throw new Error("unknown packet type "+s.type);if(s.type===ot.BINARY_EVENT||s.type===ot.BINARY_ACK){const i=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const n=t.substring(i,e);if(n!=Number(n)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(n);if(!ht(r)||r<1)throw new Error("Illegal attachments");if(r>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=r}if("/"===t.charAt(e+1)){const i=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(i,e)}else s.nsp="/";const i=t.charAt(e+1);if(""!==i&&Number(i)==i){const i=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(i,e+1))}if(t.charAt(++e)){const i=this.tryParse(t.substr(e));if(!at.isPayloadValid(s.type,i))throw new Error("invalid payload");s.data=i}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ot.CONNECT:return ut(e);case ot.DISCONNECT:return void 0===e;case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);case ot.EVENT:case ot.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:case ot.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ct{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=it(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ht=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ut(t){return"[object Object]"===Object.prototype.toString.call(t)}var dt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return ot},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ot.EVENT&&t.type!==ot.ACK||!tt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ot.EVENT?ot.BINARY_EVENT:ot.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ot.BINARY_EVENT&&t.type!==ot.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=et(t),s=this.encodeAsString(e.packet),i=e.buffers;return i.unshift(s),i}},Decoder:at,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||ht(e))&&function(t,e){switch(t){case ot.CONNECT:return void 0===e||ut(e);case ot.DISCONNECT:return void 0===e;case ot.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:return Array.isArray(e);case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);default:return!1}}(t.type,t.data);var e}});function lt(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ft extends w{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this.et=[],this.nt=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this.p=Object.assign({},s),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lt(t,"open",this.onopen.bind(this)),lt(t,"packet",this.onpacket.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io.ot||this.io.open(),"open"===this.io.ht&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,i,n;if(pt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this.p.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this.ct(e),this;const r={type:ot.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this.ut(t,s),r.id=t}const o=null===(i=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n.st());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}ut(t,e){var s;const i=null!==(s=this.flags.timeout)&&void 0!==s?s:this.p.ackTimeout;if(void 0===i)return void(this.acks[t]=e);const n=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},i),r=(...t)=>{this.io.clearTimeoutFn(n),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((s,i)=>{const n=(t,e)=>t?i(t):s(e);n.withError=!0,e.push(n),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...i)=>(this.et[0],null!==t?s.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...i)),s.pending=!1,this.ft())),this.et.push(s),this.ft()}ft(t=!1){if(!this.connected||0===this.et.length)return;const e=this.et[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io.lt(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this.dt(t)}):this.dt(this.auth)}dt(t){this.packet({type:ot.CONNECT,data:this.yt?Object.assign({pid:this.yt,offset:this.bt},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this.wt()}wt(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ot.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ot.EVENT:case ot.BINARY_EVENT:this.onevent(t);break;case ot.ACK:case ot.BINARY_ACK:this.onack(t);break;case ot.DISCONNECT:this.ondisconnect();break;case ot.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this.gt&&this.gt.length){const e=this.gt.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this.yt&&t.length&&"string"==typeof t[t.length-1]&&(this.bt=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...i){s||(s=!0,e.packet({type:ot.ACK,id:t,data:i}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this.yt===e,this.yt=e,this.connected=!0,this.emitBuffered(),this.ft(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io.vt(this)}disconnect(){return this.connected&&this.packet({type:ot.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this.gt=this.gt||[],this.gt.push(t),this}prependAny(t){return this.gt=this.gt||[],this.gt.unshift(t),this}offAny(t){if(!this.gt)return this;if(t){const e=this.gt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.gt=[];return this}listenersAny(){return this.gt||[]}onAnyOutgoing(t){return this.kt=this.kt||[],this.kt.push(t),this}prependAnyOutgoing(t){return this.kt=this.kt||[],this.kt.unshift(t),this}offAnyOutgoing(t){if(!this.kt)return this;if(t){const e=this.kt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.kt=[];return this}listenersAnyOutgoing(){return this.kt||[]}notifyOutgoingListeners(t){if(this.kt&&this.kt.length){const e=this.kt.slice();for(const s of e)s.apply(this,t.data)}}}function yt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}yt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},yt.prototype.reset=function(){this.attempts=0},yt.prototype.setMin=function(t){this.ms=t},yt.prototype.setMax=function(t){this.max=t},yt.prototype.setJitter=function(t){this.jitter=t};class mt extends w{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,T(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new yt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const i=e.parser||dt;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this.rt=!1!==e.autoConnect,this.rt&&this.open()}reconnection(t){return arguments.length?(this.At=!!t,t||(this.skipReconnect=!0),this):this.At}reconnectionAttempts(t){return void 0===t?this.Et:(this.Et=t,this)}reconnectionDelay(t){var e;return void 0===t?this.Ot:(this.Ot=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._t:(this._t=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this.jt:(this.jt=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this.Bt=t,this):this.Bt}maybeReconnectOnOpen(){!this.ot&&this.At&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this.ht.indexOf("open"))return this;this.engine=new Y(this.uri,this.opts);const e=this.engine,s=this;this.ht="opening",this.skipReconnect=!1;const i=lt(e,"open",function(){s.onopen(),t&&t()}),n=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",n);if(!1!==this.Bt){const t=this.Bt,s=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(i),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lt(t,"ping",this.onping.bind(this)),lt(t,"data",this.ondata.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this)),lt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this.rt&&!s.active&&s.connect():(s=new ft(this,t,e),this.nsps[t]=s),s}vt(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this.xt()}lt(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}xt(){this.skipReconnect=!0,this.ot=!1,this.onclose("forced close")}disconnect(){return this.xt()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this.ht="closed",this.emitReserved("close",t,e),this.At&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this.ot||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this.Et)this.backoff.reset(),this.emitReserved("reconnect_failed"),this.ot=!1;else{const e=this.backoff.duration();this.ot=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t.ot=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gt={};function bt(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let i=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),i=K(t)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+e,i.href=i.protocol+"://"+n+(s&&s.port===i.port?"":":"+i.port),i}(t,(e=e||{}).path||"/socket.io"),i=s.source,n=s.id,r=s.path,o=gt[n]&&r in gt[n].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(i,e):(gt[n]||(gt[n]=new mt(i,e)),a=gt[n]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(bt,{Manager:mt,Socket:ft,io:bt,connect:bt});
14
14
  /*!
15
15
  * Copyright © 2025–2026 Solomei AI SRL. All rights reserved.
16
16
  *
@@ -18,5 +18,5 @@
18
18
  * See LICENSE.md for the full terms.
19
19
  *
20
20
  */
21
- const vt="chapter-event",wt="error",kt="server-response",Rt="client-ready",Et="user-interaction",Ot=4,At={debug:0,info:1,warn:2,error:3,silent:4},Tt=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...t)=>{this.log("debug",...t)};info=(...t)=>{this.log("info",...t)};warn=(...t)=>{this.log("warn",...t)};error=(...t)=>{this.log("error",...t)};log(t,...e){if(!(this.config.enabled&&At[t]>=At[this.config.level]))return;const{prefix:s}=this.config,i=void 0===s||""===s?e:[s,...e];console[t](...i)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function Ct(){const t="undefined"==typeof crypto?void 0:crypto;if("function"==typeof t?.randomUUID)return t.randomUUID();const e=new Uint8Array(16);if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=[...e].map(t=>t.toString(16).padStart(2,"0"));return[s.slice(0,4).join(""),s.slice(4,6).join(""),s.slice(6,8).join(""),s.slice(8,10).join(""),s.slice(10,16).join("")].join("-")}var St,Nt;!function(t){t.GET_STORY="get-story",t.CREATE_ROUND="create-round",t.RESET_STORY="reset-story",t.BACK_FROM_ROUND="back-from-round",t.SHARE_STORY="share-story",t.GET_SHARED_STORY="get-shared-story"}(St||(St={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Nt||(Nt={}));const Bt={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class xt{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(t={}){const e=t.minVisibilityRatio??Bt.minVisibilityRatio;this.config={productSelector:t.productSelector??Bt.productSelector,blockSelector:t.blockSelector??Bt.blockSelector,maxTrackedElements:t.maxTrackedElements??Bt.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,e))}}rescanUi(){if(!this.canUseDom())return;let t,e;try{t=document.querySelectorAll(this.config.productSelector),e=document.querySelectorAll(this.config.blockSelector)}catch(t){return void Tt.warn("UI Observer: invalid selector, skipping rescan:",t)}const s=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),i=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),i=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[e]of t)this.elements.delete(e),this.elementRefs.delete(e)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const t=[...this.blocks].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[e]of t)this.blocks.delete(e),this.blockRefs.delete(e)}syncTrackedElement(t,e){const s=this.resolveElementId(t),i=this.resolveBlockId(t),n=this.createTrackingKey(s,i),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==n&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,n),this.elementRefs.set(n,t),this.elements.set(n,{id:s,blockId:i,trackingKey:n,...e})}syncTrackedBlock(t,e){const s=this.resolveTrackedBlockId(t),i=this.blockKeys.get(t),n=s;void 0!==i&&""!==i&&i!==n&&(this.blocks.delete(i),this.blockRefs.delete(i)),this.blockKeys.set(t,n),this.blockRefs.set(n,t),this.blocks.set(n,{id:s,...e})}resolveElementId(t){return[t.dataset.productId,t.dataset.productid,t.dataset.sku,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.productId??this.elements.size}`}resolveBlockId(t){let e;try{e=t.closest(this.config.blockSelector)??void 0}catch{return}return e instanceof HTMLElement?this.resolveTrackedBlockId(e):void 0}resolveTrackedBlockId(t){return[t.dataset.blockId,t.dataset.blockid,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.blockId??this.blocks.size}`}createTrackingKey(t,e){return void 0===e||""===e?t:`${t}::${e}`}normalizeRect(t){return{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,left:t.left,right:t.right,bottom:t.bottom}}calculateVisibilityRatio(t){const e=Math.max(0,Math.min(t.right,window.innerWidth)-Math.max(t.left,0))*Math.max(0,Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)),s=t.width*t.height;if(s<=0)return 0;const i=window.innerWidth*window.innerHeight,n=i>0?Math.min(s,i):s;return Math.min(1,Math.max(0,e/n))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const t=[],e=[],s=Date.now();for(const[e,s]of this.elements){const i=this.elementRefs.get(e);i?.isConnected?s.visibilityRatio<=0||t.push({blockId:s.blockId,element:{id:s.id,bounds:s.bounds,isVisible:s.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:s.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,s]of this.blocks){const i=this.blockRefs.get(t);i?.isConnected?s.visibilityRatio<this.config.minVisibilityRatio||e.push(s.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const i=t.slice(0,this.config.maxTrackedElements);return{timestamp:s,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...i.flatMap(t=>t.blockId??[])])],elements:i.map(t=>t.element)}}}class Ut{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=Bt;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{Tt.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Rt)}),this.socket.on("disconnect",()=>{Tt.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",t=>{this.updateConnectionStatus(!1);const e=function(t,e){return e?void 0:function(t){const{data:e}=t;if("object"!=typeof e||null===e)return;const{code:s,reason:i}=e;return"number"==typeof s?{code:s,..."string"==typeof i&&{reason:i}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(Tt.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(wt,t=>{Tt.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{Tt.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{Tt.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{Tt.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{Tt.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(kt,t=>{this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){Tt.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){Tt.error("Error in connection status listener:",t)}})}notifyRejection(t,e){this.notifyErrorListeners({code:t.code,message:e,...void 0!==t.reason&&{reason:t.reason}})}scheduleHandshakeRetry(t){if(!this.socket)return;if(this.clearHandshakeRetry(),!function(t,e){return t>=500&&e<3}(t,this.handshakeRetryAttempts))return void(t>=500&&(Tt.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:t,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const e=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,Tt.info(`Retrying Callimacus connection in ${e}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*e)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(t){this.errorListeners.forEach(e=>{try{e(t)}catch(t){Tt.error("Error in error listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return Tt.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new xt(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),s=new URL("thamyr",e).pathname;return{origin:e.origin,path:s}}connect(t="wss://localhost:4000",e,s){this.socket&&(Tt.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const i=this.socketEndpoint(t);let n;"undefined"!=typeof window&&void 0!==globalThis.location&&(n=globalThis.location.href);const r={...void 0!==n&&""!==n&&{referrer:n},...s};Tt.info("Connecting to Thamyr at",i),this.socket=bt(i.origin,{path:i.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth:r}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),Tt.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...Bt,enabled:!1});const e=t.enabled??(void 0!==t.productSelector||void 0!==t.blockSelector||void 0!==t.maxTrackedElements||void 0!==t.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...t,enabled:e},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new xt(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void Tt.error("Socket is not connected. Cannot send interaction.");if(t===St.BACK_FROM_ROUND&&void 0===e.chapterId)return void Tt.error("BACK_FROM_ROUND requires chapterId.");const s={type:t,payload:this.enrichPayloadWithUiContext(e)},i={id:Ct()};this.socket.emit(Et,{type:s.type,payload:s.payload},i.id)}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}}const It="https://api.callimacus.ai",jt="/cart/add.js",Lt="[callimacus]";class Dt extends Error{code;constructor(t,e,s){super(e,s),this.name="CallimacusError",this.code=t}}function _t(t){if(void 0===t||""===t)return{};try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e;console.warn(`${Lt} [data-callimacus-settings] must be a JSON object — using {}`)}catch(t){console.warn(`${Lt} [data-callimacus-settings] is not valid JSON — using {}`,t)}return{}}function qt(t,e){return void 0===t||""===t?e:t}function Mt(t){return`server_${t.code??"error"}`}function $t(t,e){t.dataset.callimacusState=e,t.setAttribute("aria-busy",String("loading"===e))}function Vt(t,e,s){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:s}))}function Pt(t){const{data:e}=t;return"object"!=typeof e||null===e?[]:Object.values(e)}function Ft(t){let e=t.language;try{Intl.NumberFormat.supportedLocalesOf(e)}catch{console.warn(`${Lt} invalid data-language "${e}" — formatting with "en"`),e="en"}const s=new Map;return Object.freeze({locale:e,currency:t.currency,settings:t.settings,picks(t){for(const e of Pt(t)){if(!Array.isArray(e))continue;const t=e.filter(t=>Boolean(t?.fields?.["shopify-handle"]));if(t.length>0)return t}return[]},text(t){for(const e of Pt(t)){if("string"==typeof e&&""!==e.trim())return e.trim();const t=e?.text;if("string"==typeof t&&""!==t.trim())return t.trim()}},money(i){const n="number"==typeof i?i:i?.amount;if("number"!=typeof n)return"";const r="object"==typeof i?i?.currency:void 0,o=void 0===r||""===r?t.currency??"USD":r;return function(t){if(!s.has(t))try{s.set(t,new Intl.NumberFormat(e,{style:"currency",currency:t}))}catch{console.warn(`${Lt} invalid currency code "${t}" — showing bare amounts`),s.set(t,void 0)}return s.get(t)}(o)?.format(n)??n.toFixed(2)},productUrl(e){const s=e?.fields?.["shopify-handle"];if(void 0===s||""===s)return;return`${t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl}/products/${s}`},imageUrl(t,{width:e=800,index:s=0}={}){const i=t?.fields?.images?.[s]?.url;return void 0===i||""===i?void 0:`${i.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields?.variantTree?.variants??[],s=e.find(t=>t.orderable)??e[0];return void 0===s?.id?void 0:String(s.id).split("/").pop()},async addToCart(e,s=1){let i;try{i=await fetch(t.cartAddUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({items:[{id:Number(e),quantity:s}]})})}catch(t){throw new Dt("cart_unreachable","Could not reach the cart",{cause:t})}const n=await i.json().catch(()=>(console.warn(`${Lt} cart response was not JSON (HTTP ${i.status})`),{}));if(!i.ok){const{description:t,message:e}=n??{};throw new Dt("cart_rejected",t??e??`Could not add to cart (HTTP ${i.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:n})),n}})}function Ht(t){return function(){const t=globalThis;return t.callimacusRenderers??=[],t.callimacusRenderers}().find(e=>{const s=e;return s?.type===t&&"function"==typeof s.render})}function Kt(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:s}=t,i={clientId:s.clientId,endpoint:qt(s.endpoint,It),language:qt(s.language,"en"),currency:""===s.currency?void 0:s.currency,rootUrl:qt(s.rootUrl,"/"),cartAddUrl:qt(s.cartAddUrl,jt),settings:_t(t.querySelector("[data-callimacus-settings]")?.textContent??void 0)};if("true"===s.designMode)return void $t(t,"design-mode");if(void 0===i.clientId||""===i.clientId)return $t(t,"error"),void console.warn(`${Lt} no client id — leaving your markup in place`);t.querySelector("[data-callimacus-output]")||console.warn(`${Lt} no [data-callimacus-output] inside this mount — rendered blocks will replace the mount element's entire contents`);const{clientId:n}=i,r=e.roundTimeoutMs??45e3,o=Ft(i),a=new Set;let c,h,u=!1;function d(){return c||(c=e.transport??new Ut,c.onError(t=>{h=`${Mt(t)}: ${t.message??""}`,u||console.warn(`${Lt} transport error between rounds — ${h}`)}),c.connect(i.endpoint,{Authorization:`Bearer ${n}`},{token:n}),c)}async function l(t){const e=d();return new Promise((s,n)=>{function o(){clearTimeout(c),u(),d()}const c=setTimeout(()=>{o();n(new Dt("timeout",`Callimacus did not answer in time${void 0===h?"":` (last transport error: ${h})`}`))},r),u=e.onServerResponse(e=>{if(e.type!==vt)return;const i=e.chapter;if(i?.status!==Ot||a.has(i.id))return;const n=i.inputEvent?.data?.value;"string"==typeof n&&n!==t||(a.add(i.id),o(),s(i))}),d=e.onError(t=>{o(),n(new Dt(Mt(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(St.CREATE_ROUND,{inputEvent:{type:"question",data:{value:t}},language:i.language})}catch(t){o(),n(new Dt("send_failed","Could not send the request",{cause:t}))}})}async function p(e){if(!u&&""!==e){u=!0,$t(t,"loading"),Vt(t,"callimacus:loading",{value:e});try{const s=await l(e),i=[...s.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:n,rendered:r}=function(t,e){const s=document.createDocumentFragment();let i=0;for(const n of t){const t=Ht(n.type);if(t)try{const r=t.render(n,e);r instanceof Node?(s.append(r),i++):null!=r&&console.error(`${Lt} renderer for ${n.type} returned a non-Node value — skipped`)}catch(t){console.error(`${Lt} renderer for ${n.type} threw`,t)}else console.info(`${Lt} no renderer for ${n.type} — skipped`)}return{fragment:s,rendered:i}}(i,o);if(0===r)return $t(t,"empty"),void Vt(t,"callimacus:empty",{chapter:s});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(n),$t(t,"ready"),Vt(t,"callimacus:ready",{chapter:s,blocks:i,rendered:r})}catch(e){$t(t,"error"),Vt(t,"callimacus:error",{error:e});const{code:s,message:i}=e instanceof Dt?e:{code:"error",message:String(e)};console.error(`${Lt} ${s}: ${i} — your markup is untouched`)}finally{u=!1}}}const f={ask:p,ctx:o,get state(){return t.dataset.callimacusState}};t.callimacus=f,Vt(t,"callimacus:mounted",f),void 0!==s.prompt&&""!==s.prompt&&p(s.prompt)}(t,e)}catch(e){$t(t,"error"),Vt(t,"callimacus:error",{error:e}),console.error(`${Lt} mount failed — your markup is untouched`,e)}}}function zt(t,e={}){for(const s of t.querySelectorAll("[data-callimacus]"))Kt(s,e)}function Wt(){document.addEventListener("shopify:section:load",t=>{t.target instanceof Element&&zt(t.target)}),zt(document)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Wt):Wt()}();
21
+ const vt="chapter-event",wt="error",kt="server-response",Rt="client-ready",Et="user-interaction",Ot=4,At={debug:0,info:1,warn:2,error:3,silent:4},Tt=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...t)=>{this.log("debug",...t)};info=(...t)=>{this.log("info",...t)};warn=(...t)=>{this.log("warn",...t)};error=(...t)=>{this.log("error",...t)};log(t,...e){if(!(this.config.enabled&&At[t]>=At[this.config.level]))return;const{prefix:s}=this.config,i=void 0===s||""===s?e:[s,...e];console[t](...i)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function Ct(){const t="undefined"==typeof crypto?void 0:crypto;if("function"==typeof t?.randomUUID)return t.randomUUID();const e=new Uint8Array(16);if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=[...e].map(t=>t.toString(16).padStart(2,"0"));return[s.slice(0,4).join(""),s.slice(4,6).join(""),s.slice(6,8).join(""),s.slice(8,10).join(""),s.slice(10,16).join("")].join("-")}var St,Nt;!function(t){t.GET_STORY="get-story",t.CREATE_ROUND="create-round",t.RESET_STORY="reset-story",t.BACK_FROM_ROUND="back-from-round",t.SHARE_STORY="share-story",t.GET_SHARED_STORY="get-shared-story",t.SUGGEST="suggest"}(St||(St={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Nt||(Nt={}));const Bt={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class xt{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(t={}){const e=t.minVisibilityRatio??Bt.minVisibilityRatio;this.config={productSelector:t.productSelector??Bt.productSelector,blockSelector:t.blockSelector??Bt.blockSelector,maxTrackedElements:t.maxTrackedElements??Bt.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,e))}}rescanUi(){if(!this.canUseDom())return;let t,e;try{t=document.querySelectorAll(this.config.productSelector),e=document.querySelectorAll(this.config.blockSelector)}catch(t){return void Tt.warn("UI Observer: invalid selector, skipping rescan:",t)}const s=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),i=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),i=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:i>=this.config.minVisibilityRatio,visibilityRatio:i,observedAt:s})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[e]of t)this.elements.delete(e),this.elementRefs.delete(e)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const t=[...this.blocks].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[e]of t)this.blocks.delete(e),this.blockRefs.delete(e)}syncTrackedElement(t,e){const s=this.resolveElementId(t),i=this.resolveBlockId(t),n=this.createTrackingKey(s,i),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==n&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,n),this.elementRefs.set(n,t),this.elements.set(n,{id:s,blockId:i,trackingKey:n,...e})}syncTrackedBlock(t,e){const s=this.resolveTrackedBlockId(t),i=this.blockKeys.get(t),n=s;void 0!==i&&""!==i&&i!==n&&(this.blocks.delete(i),this.blockRefs.delete(i)),this.blockKeys.set(t,n),this.blockRefs.set(n,t),this.blocks.set(n,{id:s,...e})}resolveElementId(t){return[t.dataset.productId,t.dataset.productid,t.dataset.sku,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.productId??this.elements.size}`}resolveBlockId(t){let e;try{e=t.closest(this.config.blockSelector)??void 0}catch{return}return e instanceof HTMLElement?this.resolveTrackedBlockId(e):void 0}resolveTrackedBlockId(t){return[t.dataset.blockId,t.dataset.blockid,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.blockId??this.blocks.size}`}createTrackingKey(t,e){return void 0===e||""===e?t:`${t}::${e}`}normalizeRect(t){return{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,left:t.left,right:t.right,bottom:t.bottom}}calculateVisibilityRatio(t){const e=Math.max(0,Math.min(t.right,window.innerWidth)-Math.max(t.left,0))*Math.max(0,Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)),s=t.width*t.height;if(s<=0)return 0;const i=window.innerWidth*window.innerHeight,n=i>0?Math.min(s,i):s;return Math.min(1,Math.max(0,e/n))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const t=[],e=[],s=Date.now();for(const[e,s]of this.elements){const i=this.elementRefs.get(e);i?.isConnected?s.visibilityRatio<=0||t.push({blockId:s.blockId,element:{id:s.id,bounds:s.bounds,isVisible:s.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:s.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,s]of this.blocks){const i=this.blockRefs.get(t);i?.isConnected?s.visibilityRatio<this.config.minVisibilityRatio||e.push(s.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const i=t.slice(0,this.config.maxTrackedElements);return{timestamp:s,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...i.flatMap(t=>t.blockId??[])])],elements:i.map(t=>t.element)}}}class Ut{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=Bt;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{Tt.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Rt)}),this.socket.on("disconnect",()=>{Tt.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",t=>{this.updateConnectionStatus(!1);const e=function(t,e){return e?void 0:function(t){const{data:e}=t;if("object"!=typeof e||null===e)return;const{code:s,reason:i}=e;return"number"==typeof s?{code:s,..."string"==typeof i&&{reason:i}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(Tt.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(wt,t=>{Tt.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{Tt.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{Tt.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{Tt.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{Tt.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(kt,t=>{this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){Tt.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){Tt.error("Error in connection status listener:",t)}})}notifyRejection(t,e){this.notifyErrorListeners({code:t.code,message:e,...void 0!==t.reason&&{reason:t.reason}})}scheduleHandshakeRetry(t){if(!this.socket)return;if(this.clearHandshakeRetry(),!function(t,e){return t>=500&&e<3}(t,this.handshakeRetryAttempts))return void(t>=500&&(Tt.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:t,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const e=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,Tt.info(`Retrying Callimacus connection in ${e}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*e)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(t){this.errorListeners.forEach(e=>{try{e(t)}catch(t){Tt.error("Error in error listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return Tt.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new xt(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),s=new URL("thamyr",e).pathname;return{origin:e.origin,path:s}}connect(t="wss://localhost:4000",e,s){this.socket&&(Tt.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const i=this.socketEndpoint(t);let n;"undefined"!=typeof window&&void 0!==globalThis.location&&(n=globalThis.location.href);const r={...void 0!==n&&""!==n&&{referrer:n},...s};Tt.info("Connecting to Thamyr at",i),this.socket=bt(i.origin,{path:i.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth:r}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),Tt.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...Bt,enabled:!1});const e=t.enabled??(void 0!==t.productSelector||void 0!==t.blockSelector||void 0!==t.maxTrackedElements||void 0!==t.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...t,enabled:e},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new xt(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void Tt.error("Socket is not connected. Cannot send interaction.");if(t===St.SUGGEST)return void Tt.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===St.BACK_FROM_ROUND&&void 0===e.chapterId)return void Tt.error("BACK_FROM_ROUND requires chapterId.");const s={type:t,payload:this.enrichPayloadWithUiContext(e)},i={id:Ct()};this.socket.emit(Et,{type:s.type,payload:s.payload},i.id)}async suggest(t,e={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(t){const e=t?.suggestions;return{suggestions:Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}}(await this.socket.timeout(e.timeoutMs??4e3).emitWithAck(Et,{type:St.SUGGEST,payload:t}))}catch(t){return Tt.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}}const It="https://api.callimacus.ai",jt="/cart/add.js",Lt="[callimacus]";class Dt extends Error{code;constructor(t,e,s){super(e,s),this.name="CallimacusError",this.code=t}}function qt(t){if(void 0===t||""===t)return{};try{const e=JSON.parse(t);if("object"==typeof e&&null!==e&&!Array.isArray(e))return e;console.warn(`${Lt} [data-callimacus-settings] must be a JSON object — using {}`)}catch(t){console.warn(`${Lt} [data-callimacus-settings] is not valid JSON — using {}`,t)}return{}}function _t(t,e){return void 0===t||""===t?e:t}function Mt(t){return`server_${t.code??"error"}`}function $t(t,e){t.dataset.callimacusState=e,t.setAttribute("aria-busy",String("loading"===e))}function Vt(t,e,s){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:s}))}function Pt(t){const{data:e}=t;return"object"!=typeof e||null===e?[]:Object.values(e)}function Ft(t){let e=t.language;try{Intl.NumberFormat.supportedLocalesOf(e)}catch{console.warn(`${Lt} invalid data-language "${e}" — formatting with "en"`),e="en"}const s=new Map;return Object.freeze({locale:e,currency:t.currency,settings:t.settings,picks(t){for(const e of Pt(t)){if(!Array.isArray(e))continue;const t=e.filter(t=>Boolean(t?.fields?.["shopify-handle"]));if(t.length>0)return t}return[]},text(t){for(const e of Pt(t)){if("string"==typeof e&&""!==e.trim())return e.trim();const t=e?.text;if("string"==typeof t&&""!==t.trim())return t.trim()}},money(i){const n="number"==typeof i?i:i?.amount;if("number"!=typeof n)return"";const r="object"==typeof i?i?.currency:void 0,o=void 0===r||""===r?t.currency??"USD":r;return function(t){if(!s.has(t))try{s.set(t,new Intl.NumberFormat(e,{style:"currency",currency:t}))}catch{console.warn(`${Lt} invalid currency code "${t}" — showing bare amounts`),s.set(t,void 0)}return s.get(t)}(o)?.format(n)??n.toFixed(2)},productUrl(e){const s=e?.fields?.["shopify-handle"];if(void 0===s||""===s)return;return`${t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl}/products/${s}`},imageUrl(t,{width:e=800,index:s=0}={}){const i=t?.fields?.images?.[s]?.url;return void 0===i||""===i?void 0:`${i.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields?.variantTree?.variants??[],s=e.find(t=>t.orderable)??e[0];return void 0===s?.id?void 0:String(s.id).split("/").pop()},async addToCart(e,s=1){let i;try{i=await fetch(t.cartAddUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({items:[{id:Number(e),quantity:s}]})})}catch(t){throw new Dt("cart_unreachable","Could not reach the cart",{cause:t})}const n=await i.json().catch(()=>(console.warn(`${Lt} cart response was not JSON (HTTP ${i.status})`),{}));if(!i.ok){const{description:t,message:e}=n??{};throw new Dt("cart_rejected",t??e??`Could not add to cart (HTTP ${i.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:n})),n}})}function Ht(t){return function(){const t=globalThis;return t.callimacusRenderers??=[],t.callimacusRenderers}().find(e=>{const s=e;return s?.type===t&&"function"==typeof s.render})}function Kt(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:s}=t,i={clientId:s.clientId,endpoint:_t(s.endpoint,It),language:_t(s.language,"en"),currency:""===s.currency?void 0:s.currency,rootUrl:_t(s.rootUrl,"/"),cartAddUrl:_t(s.cartAddUrl,jt),settings:qt(t.querySelector("[data-callimacus-settings]")?.textContent??void 0)};if("true"===s.designMode)return void $t(t,"design-mode");if(void 0===i.clientId||""===i.clientId)return $t(t,"error"),void console.warn(`${Lt} no client id — leaving your markup in place`);t.querySelector("[data-callimacus-output]")||console.warn(`${Lt} no [data-callimacus-output] inside this mount — rendered blocks will replace the mount element's entire contents`);const{clientId:n}=i,r=e.roundTimeoutMs??45e3,o=Ft(i),a=new Set;let c,h,u=!1;function d(){return c||(c=e.transport??new Ut,c.onError(t=>{h=`${Mt(t)}: ${t.message??""}`,u||console.warn(`${Lt} transport error between rounds — ${h}`)}),c.connect(i.endpoint,{Authorization:`Bearer ${n}`},{token:n}),c)}async function l(t){const e=d();return new Promise((s,n)=>{function o(){clearTimeout(c),u(),d()}const c=setTimeout(()=>{o();n(new Dt("timeout",`Callimacus did not answer in time${void 0===h?"":` (last transport error: ${h})`}`))},r),u=e.onServerResponse(e=>{if(e.type!==vt)return;const i=e.chapter;if(i?.status!==Ot||a.has(i.id))return;const n=i.inputEvent?.data?.value;"string"==typeof n&&n!==t||(a.add(i.id),o(),s(i))}),d=e.onError(t=>{o(),n(new Dt(Mt(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(St.CREATE_ROUND,{inputEvent:{type:"question",data:{value:t}},language:i.language})}catch(t){o(),n(new Dt("send_failed","Could not send the request",{cause:t}))}})}async function p(e){if(!u&&""!==e){u=!0,$t(t,"loading"),Vt(t,"callimacus:loading",{value:e});try{const s=await l(e),i=[...s.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:n,rendered:r}=function(t,e){const s=document.createDocumentFragment();let i=0;for(const n of t){const t=Ht(n.type);if(t)try{const r=t.render(n,e);r instanceof Node?(s.append(r),i++):null!=r&&console.error(`${Lt} renderer for ${n.type} returned a non-Node value — skipped`)}catch(t){console.error(`${Lt} renderer for ${n.type} threw`,t)}else console.info(`${Lt} no renderer for ${n.type} — skipped`)}return{fragment:s,rendered:i}}(i,o);if(0===r)return $t(t,"empty"),void Vt(t,"callimacus:empty",{chapter:s});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(n),$t(t,"ready"),Vt(t,"callimacus:ready",{chapter:s,blocks:i,rendered:r})}catch(e){$t(t,"error"),Vt(t,"callimacus:error",{error:e});const{code:s,message:i}=e instanceof Dt?e:{code:"error",message:String(e)};console.error(`${Lt} ${s}: ${i} — your markup is untouched`)}finally{u=!1}}}const f={ask:p,ctx:o,get state(){return t.dataset.callimacusState}};t.callimacus=f,Vt(t,"callimacus:mounted",f),void 0!==s.prompt&&""!==s.prompt&&p(s.prompt)}(t,e)}catch(e){$t(t,"error"),Vt(t,"callimacus:error",{error:e}),console.error(`${Lt} mount failed — your markup is untouched`,e)}}}function zt(t,e={}){for(const s of t.querySelectorAll("[data-callimacus]"))Kt(s,e)}function Wt(){document.addEventListener("shopify:section:load",t=>{t.target instanceof Element&&zt(t.target)}),zt(document)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Wt):Wt()}();
22
22
  //# sourceMappingURL=callimacus-runtime.min.js.map