From da6a74284a19bdfa9b9756ce1cd19c354d09eba5 Mon Sep 17 00:00:00 2001 From: Sai Kumar Battinoju Date: Fri, 16 Aug 2024 13:24:49 +0530 Subject: [PATCH] feat: add support for different transport types --- ...ty-code-quality-and-bundle-size-checks.yml | 1 + nx.json | 4 + package-lock.json | 1103 +++++++++++++++-- package.json | 11 +- .../__fixtures__/msw.handlers.ts | 8 - .../src/types/HttpClient.ts | 74 +- .../src/types/LoadOptions.ts | 7 +- .../analytics-js-common/src/utilities/http.ts | 10 +- .../customConsentManager/index.test.ts | 2 +- .../deviceModeTransformation/index.test.ts | 28 +- .../__tests__/errorReporting/index.test.ts | 12 +- .../__tests__/errorReporting/utils.test.ts | 1 - .../__tests__/xhrQueue/index.test.ts | 28 +- .../__tests__/xhrQueue/utilities.test.ts | 59 +- .../src/deviceModeTransformation/index.ts | 6 +- .../src/errorReporting/index.ts | 4 +- .../src/fetchQueue/index.ts | 4 +- .../src/fetchQueue/utilities.ts | 6 +- .../src/xhrQueue/index.ts | 4 +- .../src/xhrQueue/utilities.ts | 6 +- .../analytics-js-service-worker/package.json | 4 +- packages/analytics-js/.size-limit.mjs | 40 +- .../analytics-js/__fixtures__/msw.handlers.ts | 8 - packages/analytics-js/__mocks__/cdnSDK.js.map | 1 + .../analytics-js/__tests__/browser.test.ts | 70 +- .../detection/adBlockers.test.ts | 18 +- .../components/core/Analytics.test.ts | 2 +- .../eventManager/EventManager.test.ts | 6 +- .../eventRepository/EventRepository.test.ts | 30 +- .../UserSessionManager.test.ts | 6 +- .../services/HttpClient/HttpClient.test.ts | 63 +- .../StoreManager/StoreManager.test.ts | 2 +- packages/analytics-js/package.json | 6 +- packages/analytics-js/project.json | 9 +- .../detection/adBlockers.ts | 9 +- .../components/configManager/ConfigManager.ts | 11 +- .../eventRepository/EventRepository.ts | 2 +- .../userSessionManager/UserSessionManager.ts | 8 +- .../analytics-js/src/constants/logMessages.ts | 21 +- .../analytics-js/src/constants/timeouts.ts | 4 +- .../src/services/HttpClient/HttpClient.ts | 126 +- .../src/services/HttpClient/beacon/index.ts | 16 + .../src/services/HttpClient/fetch/index.ts | 51 + .../HttpClient/fetch/requestHandler.ts | 0 .../src/services/HttpClient/index.ts | 6 - .../src/services/HttpClient/utils.ts | 17 + .../src/services/HttpClient/xhr/index.ts | 75 ++ .../HttpClient/xhr/xhrRequestHandler.ts | 137 -- .../HttpClient/xhr/xhrResponseHandler.ts | 25 - 49 files changed, 1613 insertions(+), 538 deletions(-) create mode 100644 packages/analytics-js/__mocks__/cdnSDK.js.map create mode 100644 packages/analytics-js/src/services/HttpClient/beacon/index.ts create mode 100644 packages/analytics-js/src/services/HttpClient/fetch/index.ts delete mode 100644 packages/analytics-js/src/services/HttpClient/fetch/requestHandler.ts create mode 100644 packages/analytics-js/src/services/HttpClient/utils.ts create mode 100644 packages/analytics-js/src/services/HttpClient/xhr/index.ts delete mode 100644 packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts delete mode 100644 packages/analytics-js/src/services/HttpClient/xhr/xhrResponseHandler.ts diff --git a/.github/workflows/security-code-quality-and-bundle-size-checks.yml b/.github/workflows/security-code-quality-and-bundle-size-checks.yml index d727e17524..0859623d33 100644 --- a/.github/workflows/security-code-quality-and-bundle-size-checks.yml +++ b/.github/workflows/security-code-quality-and-bundle-size-checks.yml @@ -61,6 +61,7 @@ jobs: - name: Execute code quality checks run: | + npm run check:circular npm run check:duplicates - name: Build the project diff --git a/nx.json b/nx.json index cfbb025dda..1a8efc4730 100644 --- a/nx.json +++ b/nx.json @@ -61,6 +61,10 @@ "inputs": ["default", "^production"], "cache": true }, + "build:browser:dev": { + "inputs": ["default", "^production"], + "cache": true + }, "check:size:json": { "inputs": [ "default", diff --git a/package-lock.json b/package-lock.json index 572d9c7eab..70a30ed08d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,7 +22,7 @@ "@segment/top-domain": "3.0.1", "@vespaiach/axios-fetch-adapter": "0.3.1", "assert": "2.1.0", - "axios": "1.7.3", + "axios": "1.7.4", "axios-retry": "4.5.0", "component-each": "0.2.6", "component-emitter": "2.0.0", @@ -80,10 +80,10 @@ "@size-limit/file": "11.1.4", "@size-limit/webpack": "11.1.4", "@swc-node/register": "1.10.9", - "@swc/core": "1.7.6", + "@swc/core": "1.7.11", "@types/component-emitter": "1.2.14", "@types/jest": "29.5.12", - "@types/node": "22.1.0", + "@types/node": "22.3.0", "@types/ramda": "0.30.1", "babel-plugin-transform-object-hasown": "1.1.0", "commitizen": "4.3.0", @@ -114,7 +114,8 @@ "jest-watch-typeahead": "2.2.2", "join-component": "1.1.0", "jscpd": "4.0.5", - "lint-staged": "15.2.8", + "lint-staged": "15.2.9", + "madge": "8.0.0", "msw": "2.3.5", "nx": "19.5.7", "patch-package": "8.0.0", @@ -125,7 +126,7 @@ "rollup-plugin-delete": "2.0.0", "rollup-plugin-dts": "6.1.1", "rollup-plugin-exclude-dependencies-from-bundle": "1.1.23", - "rollup-plugin-external-globals": "0.11.0", + "rollup-plugin-external-globals": "0.12.0", "rollup-plugin-filesize": "10.0.0", "rollup-plugin-generate-html-template": "1.7.0", "rollup-plugin-livereload": "2.0.5", @@ -2518,6 +2519,19 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@dependents/detective-less": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@dependents/detective-less/-/detective-less-5.0.0.tgz", + "integrity": "sha512-D/9dozteKcutI5OdxJd8rU+fL6XgaaRg60sPPJWkT33OCiRfkCu5wO5B/yXTaaL2e6EB0lcCBGe5E0XscZCvvQ==", + "dev": true, + "dependencies": { + "gonzales-pe": "^4.3.0", + "node-source-walk": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@digitalroute/cz-conventional-changelog-for-jira": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/@digitalroute/cz-conventional-changelog-for-jira/-/cz-conventional-changelog-for-jira-8.0.1.tgz", @@ -3753,9 +3767,9 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", + "integrity": "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==", "dev": true }, "node_modules/@jridgewell/trace-mapping": { @@ -6197,9 +6211,9 @@ } }, "node_modules/@swc/core": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.7.6.tgz", - "integrity": "sha512-FZxyao9eQks1MRmUshgsZTmlg/HB2oXK5fghkoWJm/1CU2q2kaJlVDll2as5j+rmWiwkp0Gidlq8wlXcEEAO+g==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.7.11.tgz", + "integrity": "sha512-AB+qc45UrJrDfbhPKcUXk+9z/NmFfYYwJT6G7/iur0fCse9kXjx45gi40+u/O2zgarG/30/zV6E3ps8fUvjh7g==", "dev": true, "hasInstallScript": true, "dependencies": { @@ -6214,16 +6228,16 @@ "url": "https://opencollective.com/swc" }, "optionalDependencies": { - "@swc/core-darwin-arm64": "1.7.6", - "@swc/core-darwin-x64": "1.7.6", - "@swc/core-linux-arm-gnueabihf": "1.7.6", - "@swc/core-linux-arm64-gnu": "1.7.6", - "@swc/core-linux-arm64-musl": "1.7.6", - "@swc/core-linux-x64-gnu": "1.7.6", - "@swc/core-linux-x64-musl": "1.7.6", - "@swc/core-win32-arm64-msvc": "1.7.6", - "@swc/core-win32-ia32-msvc": "1.7.6", - "@swc/core-win32-x64-msvc": "1.7.6" + "@swc/core-darwin-arm64": "1.7.11", + "@swc/core-darwin-x64": "1.7.11", + "@swc/core-linux-arm-gnueabihf": "1.7.11", + "@swc/core-linux-arm64-gnu": "1.7.11", + "@swc/core-linux-arm64-musl": "1.7.11", + "@swc/core-linux-x64-gnu": "1.7.11", + "@swc/core-linux-x64-musl": "1.7.11", + "@swc/core-win32-arm64-msvc": "1.7.11", + "@swc/core-win32-ia32-msvc": "1.7.11", + "@swc/core-win32-x64-msvc": "1.7.11" }, "peerDependencies": { "@swc/helpers": "*" @@ -6235,9 +6249,9 @@ } }, "node_modules/@swc/core-darwin-arm64": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.7.6.tgz", - "integrity": "sha512-6lYHey84ZzsdtC7UuPheM4Rm0Inzxm6Sb8U6dmKc4eCx8JL0LfWG4LC5RsdsrTxnjTsbriWlnhZBffh8ijUHIQ==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-darwin-arm64/-/core-darwin-arm64-1.7.11.tgz", + "integrity": "sha512-HRQv4qIeMBPThZ6Y/4yYW52rGsS6yrpusvuxLGyoFo45Y0y12/V2yXkOIA/0HIQyrqoUAxn1k4zQXpPaPNCmnw==", "cpu": [ "arm64" ], @@ -6251,9 +6265,9 @@ } }, "node_modules/@swc/core-darwin-x64": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.7.6.tgz", - "integrity": "sha512-Fyl+8aH9O5rpx4O7r2KnsPpoi32iWoKOYKiipeTbGjQ/E95tNPxbmsz4yqE8Ovldcga60IPJ5OKQA3HWRiuzdw==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-darwin-x64/-/core-darwin-x64-1.7.11.tgz", + "integrity": "sha512-vtMQj0F3oYwDu5yhO7SKDRg1XekRSi6/TbzHAbBXv+dBhlGGvcZZynT1H90EVFTv+7w7Sh+lOFvRv5Z4ZTcxow==", "cpu": [ "x64" ], @@ -6267,9 +6281,9 @@ } }, "node_modules/@swc/core-linux-arm-gnueabihf": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.7.6.tgz", - "integrity": "sha512-2WxYTqFaOx48GKC2cbO1/IntA+w+kfCFy436Ij7qRqqtV/WAvTM9TC1OmiFbqq436rSot52qYmX8fkwdB5UcLQ==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.7.11.tgz", + "integrity": "sha512-mHtzWKxhtyreI4CSxs+3+ENv8t/Qo35WFoYG66qHEgJz/Z2Lh6jv1E+MYgHdYwnpQHgHbdvAco7HsBu/Dt6xXw==", "cpu": [ "arm" ], @@ -6283,9 +6297,9 @@ } }, "node_modules/@swc/core-linux-arm64-gnu": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.7.6.tgz", - "integrity": "sha512-TBEGMSe0LhvPe4S7E68c7VzgT3OMu4VTmBLS7B2aHv4v8uZO92Khpp7L0WqgYU1y5eMjk+XLDLi4kokiNHv/Hg==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.7.11.tgz", + "integrity": "sha512-FRwe/x0GfXSQjGP2lIk+NO0pUFS/lI/RorCLBPiK808EVE9JTbh9DKCc/4Bbb4jgScAjNkrFCUVObQYl3YKmpA==", "cpu": [ "arm64" ], @@ -6299,9 +6313,9 @@ } }, "node_modules/@swc/core-linux-arm64-musl": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.7.6.tgz", - "integrity": "sha512-QI8QGL0HGT42tj7F1A+YAzhGkJjUcvvTfI1e2m704W0Enl2/UIK9v5D1zvQzYwusRyKuaQfbeBRYDh0NcLOGLg==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.7.11.tgz", + "integrity": "sha512-GY/rs0+GUq14Gbnza90KOrQd/9yHd5qQMii5jcSWcUCT5A8QTa8kiicsM2NxZeTJ69xlKmT7sLod5l99lki/2A==", "cpu": [ "arm64" ], @@ -6315,9 +6329,9 @@ } }, "node_modules/@swc/core-linux-x64-gnu": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.7.6.tgz", - "integrity": "sha512-61AYVzhjuNQAVIKKWOJu3H0/pFD28RYJGxnGg3YMhvRLRyuWNyY5Nyyj2WkKcz/ON+g38Arlz00NT1LDIViRLg==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.7.11.tgz", + "integrity": "sha512-QDkGRwSPmp2RBOlSs503IUXlWYlny8DyznTT0QuK0ML2RpDFlXWU94K/EZhS0RBEUkMY/W51OacM8P8aS/dkCg==", "cpu": [ "x64" ], @@ -6331,9 +6345,9 @@ } }, "node_modules/@swc/core-linux-x64-musl": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.7.6.tgz", - "integrity": "sha512-hQFznpfLK8XajfAAN9Cjs0w/aVmO7iu9VZvInyrTCRcPqxV5O+rvrhRxKvC1LRMZXr5M6JRSRtepp5w+TK4kAw==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.7.11.tgz", + "integrity": "sha512-SBEfKrXy6zQ6ksnyxw1FaCftrIH4fLfA81xNnKb7x/6iblv7Ko6H0aK3P5C86jyqF/82+ONl9C7ImGkUFQADig==", "cpu": [ "x64" ], @@ -6347,9 +6361,9 @@ } }, "node_modules/@swc/core-win32-arm64-msvc": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.7.6.tgz", - "integrity": "sha512-Aqsd9afykVMuekzjm4X4TDqwxmG4CrzoOSFe0hZrn9SMio72l5eAPnMtYoe5LsIqtjV8MNprLfXaNbjHjTegmA==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.7.11.tgz", + "integrity": "sha512-a2Y4xxEsLLYHJN7sMnw9+YQJDi3M1BxEr9hklfopPuGGnYLFNnx5CypH1l9ReijEfWjIAHNi7pq3m023lzW1Hg==", "cpu": [ "arm64" ], @@ -6363,9 +6377,9 @@ } }, "node_modules/@swc/core-win32-ia32-msvc": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.7.6.tgz", - "integrity": "sha512-9h0hYnOeRVNeQgHQTvD1Im67faNSSzBZ7Adtxyu9urNLfBTJilMllFd2QuGHlKW5+uaT6ZH7ZWDb+c/enx7Lcg==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.7.11.tgz", + "integrity": "sha512-ZbZFMwZO+j8ulhegJ7EhJ/QVZPoQ5qc30ylJQSxizizTJaen71Q7/13lXWc6ksuCKvg6dUKrp/TPgoxOOtSrFA==", "cpu": [ "ia32" ], @@ -6379,9 +6393,9 @@ } }, "node_modules/@swc/core-win32-x64-msvc": { - "version": "1.7.6", - "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.7.6.tgz", - "integrity": "sha512-izeoB8glCSe6IIDQmrVm6bvR9muk9TeKgmtY7b6l1BwL4BFnTUk4dMmpbntT90bEVQn3JPCaPtUG4HfL8VuyuA==", + "version": "1.7.11", + "resolved": "https://registry.npmjs.org/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.7.11.tgz", + "integrity": "sha512-IUohZedSJyDu/ReEBG/mqX6uG29uA7zZ9z6dIAF+p6eFxjXmh9MuHryyM+H8ebUyoq/Ad3rL+rUCksnuYNnI0w==", "cpu": [ "x64" ], @@ -6418,6 +6432,92 @@ "node": ">= 10" } }, + "node_modules/@ts-graphviz/adapter": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@ts-graphviz/adapter/-/adapter-2.0.3.tgz", + "integrity": "sha512-wHSN23UdLz4vuYUBZCzq2/tfLicwStSo3cUWnzvMNxG2ngcuYauQCQInv4CI5IObq+PFol28RVrG9Ffa9BuIRA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ts-graphviz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/ts-graphviz" + } + ], + "dependencies": { + "@ts-graphviz/common": "^2.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@ts-graphviz/ast": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@ts-graphviz/ast/-/ast-2.0.3.tgz", + "integrity": "sha512-NhOgJdOHGSn5h5ydsFreLIKFBwQ59drzZ6y0B98+KeEMqduv5hXxcQoDabw8yzeNe9B92AfR5OpUYthcdAsYgw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ts-graphviz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/ts-graphviz" + } + ], + "dependencies": { + "@ts-graphviz/common": "^2.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@ts-graphviz/common": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@ts-graphviz/common/-/common-2.1.2.tgz", + "integrity": "sha512-Wyh5fOZNYyNP1mymbcHg/9atWR33NhHWIDrNa4hfbel3v340YQ+q+LMwAuIPuPt1qXINvOEhkowO5dvJWqfnPA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ts-graphviz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/ts-graphviz" + } + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@ts-graphviz/core": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@ts-graphviz/core/-/core-2.0.3.tgz", + "integrity": "sha512-EZ+XlSwjdLtscoBOnA/Ba6QBrmoxAR73tJFjnWxaJQsZxWBQv6bLUrDgZUdXkXRAOSkRHn0uXY6Wq/3SsV2WtQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ts-graphviz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/ts-graphviz" + } + ], + "dependencies": { + "@ts-graphviz/ast": "^2.0.3", + "@ts-graphviz/common": "^2.1.2" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/@tsconfig/node10": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", @@ -6668,18 +6768,18 @@ } }, "node_modules/@types/node": { - "version": "22.1.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.1.0.tgz", - "integrity": "sha512-AOmuRF0R2/5j1knA3c6G3HOk523Ga+l+ZXltX8SF1+5oqcXijjfTd8fY3XRZqSihEu9XhtQnKYLmkFaoxgsJHw==", + "version": "22.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.3.0.tgz", + "integrity": "sha512-nrWpWVaDZuaVc5X84xJ0vNrLvomM205oQyLsRt7OHNZbSHslcWsvgFR7O7hire2ZonjLrWBbedmotmIlJDVd6g==", "dev": true, "dependencies": { - "undici-types": "~6.13.0" + "undici-types": "~6.18.2" } }, "node_modules/@types/node/node_modules/undici-types": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.13.0.tgz", - "integrity": "sha512-xtFJHudx8S2DSoujjMd1WeWvn7KKWFRESZTMeL1RptAYERu29D6jphMjjY+vn96jvN3kVPDNxU/E13VTaXj6jg==", + "version": "6.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.18.2.tgz", + "integrity": "sha512-5ruQbENj95yDYJNS3TvcaxPMshV7aizdv/hWYjGIKoANWKjhWNBsr2YEuYZKodQulB1b8l7ILOuDQep3afowQQ==", "dev": true }, "node_modules/@types/normalize-package-data": { @@ -6868,7 +6968,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.13.0.tgz", "integrity": "sha512-QWuwm9wcGMAuTsxP+qz6LBBd3Uq8I5Nv8xb0mk54jmNoCyDspnMvVsOxI6IsMmway5d1S9Su2+sCKv1st2l6eA==", "dev": true, - "peer": true, "engines": { "node": "^18.18.0 || >=20.0.0" }, @@ -6882,7 +6981,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.13.0.tgz", "integrity": "sha512-cAvBvUoobaoIcoqox1YatXOnSl3gx92rCZoMRPzMNisDiM12siGilSM4+dJAekuuHTibI2hVC2fYK79iSFvWjw==", "dev": true, - "peer": true, "dependencies": { "@typescript-eslint/types": "7.13.0", "@typescript-eslint/visitor-keys": "7.13.0", @@ -6911,7 +7009,6 @@ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.4.tgz", "integrity": "sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw==", "dev": true, - "peer": true, "dependencies": { "brace-expansion": "^2.0.1" }, @@ -6927,7 +7024,6 @@ "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.2.tgz", "integrity": "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w==", "dev": true, - "peer": true, "bin": { "semver": "bin/semver.js" }, @@ -6963,7 +7059,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.13.0.tgz", "integrity": "sha512-nxn+dozQx+MK61nn/JP+M4eCkHDSxSLDpgE3WcQo0+fkjEolnaB5jswvIKC4K56By8MMgIho7f1PVxERHEo8rw==", "dev": true, - "peer": true, "dependencies": { "@typescript-eslint/types": "7.13.0", "eslint-visitor-keys": "^3.4.3" @@ -6981,7 +7076,6 @@ "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", "dev": true, - "peer": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" }, @@ -7003,6 +7097,95 @@ "axios": ">=0.26.0" } }, + "node_modules/@vue/compiler-core": { + "version": "3.4.37", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.4.37.tgz", + "integrity": "sha512-ZDDT/KiLKuCRXyzWecNzC5vTcubGz4LECAtfGPENpo0nrmqJHwuWtRLxk/Sb9RAKtR9iFflFycbkjkY+W/PZUQ==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.24.7", + "@vue/shared": "3.4.37", + "entities": "^5.0.0", + "estree-walker": "^2.0.2", + "source-map-js": "^1.2.0" + } + }, + "node_modules/@vue/compiler-core/node_modules/entities": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-5.0.0.tgz", + "integrity": "sha512-BeJFvFRJddxobhvEdm5GqHzRV/X+ACeuw0/BuuxsCh1EUZcAIz8+kYmBp/LrQuloy6K1f3a0M7+IhmZ7QnkISA==", + "dev": true, + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/@vue/compiler-core/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "node_modules/@vue/compiler-dom": { + "version": "3.4.37", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.4.37.tgz", + "integrity": "sha512-rIiSmL3YrntvgYV84rekAtU/xfogMUJIclUMeIKEtVBFngOL3IeZHhsH3UaFEgB5iFGpj6IW+8YuM/2Up+vVag==", + "dev": true, + "dependencies": { + "@vue/compiler-core": "3.4.37", + "@vue/shared": "3.4.37" + } + }, + "node_modules/@vue/compiler-sfc": { + "version": "3.4.37", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.4.37.tgz", + "integrity": "sha512-vCfetdas40Wk9aK/WWf8XcVESffsbNkBQwS5t13Y/PcfqKfIwJX2gF+82th6dOpnpbptNMlMjAny80li7TaCIg==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.24.7", + "@vue/compiler-core": "3.4.37", + "@vue/compiler-dom": "3.4.37", + "@vue/compiler-ssr": "3.4.37", + "@vue/shared": "3.4.37", + "estree-walker": "^2.0.2", + "magic-string": "^0.30.10", + "postcss": "^8.4.40", + "source-map-js": "^1.2.0" + } + }, + "node_modules/@vue/compiler-sfc/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "node_modules/@vue/compiler-sfc/node_modules/magic-string": { + "version": "0.30.11", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.11.tgz", + "integrity": "sha512-+Wri9p0QHMy+545hKww7YAu5NyzF8iomPL/RQazugQ9+Ez4Ic3mERMd8ZTX5rfK944j+560ZJi8iAwgak1Ac7A==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0" + } + }, + "node_modules/@vue/compiler-ssr": { + "version": "3.4.37", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.4.37.tgz", + "integrity": "sha512-TyAgYBWrHlFrt4qpdACh8e9Ms6C/AZQ6A6xLJaWrCL8GCX5DxMzxyeFAEMfU/VFr4tylHm+a2NpfJpcd7+20XA==", + "dev": true, + "dependencies": { + "@vue/compiler-dom": "3.4.37", + "@vue/shared": "3.4.37" + } + }, + "node_modules/@vue/shared": { + "version": "3.4.37", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.4.37.tgz", + "integrity": "sha512-nIh8P2fc3DflG8+5Uw8PT/1i17ccFn0xxN/5oE9RfV5SVnd7G0XEFRwakrnNFE/jlS95fpGXDVG5zDETS26nmg==", + "dev": true + }, "node_modules/@webassemblyjs/ast": { "version": "1.12.1", "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.12.1.tgz", @@ -7413,6 +7596,12 @@ "node": ">=4" } }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true + }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", @@ -7426,6 +7615,12 @@ "node": ">= 8" } }, + "node_modules/app-module-path": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/app-module-path/-/app-module-path-2.2.0.tgz", + "integrity": "sha512-gkco+qxENJV+8vFcDiiFhuoSvRXb2a/QPqpSoWhVz829VNJfOTnELbBmPmNKFxf3xdNnw4DWCkzkDaavcX/1YQ==", + "dev": true + }, "node_modules/aproba": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", @@ -7704,6 +7899,15 @@ "@mdn/browser-compat-data": "^5.2.34" } }, + "node_modules/ast-module-types": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ast-module-types/-/ast-module-types-6.0.0.tgz", + "integrity": "sha512-LFRg7178Fw5R4FAEwZxVqiRI8IxSM+Ay2UBrHoCerXNme+kMMMfz7T3xDGV/c2fer87hcrtgJGsnSOfUrPK6ng==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/ast-types-flow": { "version": "0.0.8", "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", @@ -7756,9 +7960,9 @@ } }, "node_modules/axios": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.3.tgz", - "integrity": "sha512-Ar7ND9pU99eJ9GpoGQKhKf58GpUOgnzuaB7ueNQ5BMi0p+LZ5oaEnfF999fAArcTIBwXTCHAmGcHOZJaWPq9Nw==", + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.4.tgz", + "integrity": "sha512-DukmaFRnY6AzAALSH4J2M3k6PkaC+MfaAGdEERRWcC9q3/TWQwLpHR8ZRLKTdQ3aBDL64EdluRDjJqKw+BPZEw==", "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.0", @@ -10333,6 +10537,33 @@ "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", "dev": true }, + "node_modules/dependency-tree": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/dependency-tree/-/dependency-tree-11.0.1.tgz", + "integrity": "sha512-eCt7HSKIC9NxgIykG2DRq3Aewn9UhVS14MB3rEn6l/AsEI1FBg6ZGSlCU0SZ6Tjm2kkhj6/8c2pViinuyKELhg==", + "dev": true, + "dependencies": { + "commander": "^12.0.0", + "filing-cabinet": "^5.0.1", + "precinct": "^12.0.2", + "typescript": "^5.4.5" + }, + "bin": { + "dependency-tree": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/dependency-tree/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -10387,6 +10618,137 @@ "node": ">= 4.0.0" } }, + "node_modules/detective-amd": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/detective-amd/-/detective-amd-6.0.0.tgz", + "integrity": "sha512-NTqfYfwNsW7AQltKSEaWR66hGkTeD52Kz3eRQ+nfkA9ZFZt3iifRCWh+yZ/m6t3H42JFwVFTrml/D64R2PAIOA==", + "dev": true, + "dependencies": { + "ast-module-types": "^6.0.0", + "escodegen": "^2.1.0", + "get-amd-module-type": "^6.0.0", + "node-source-walk": "^7.0.0" + }, + "bin": { + "detective-amd": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/detective-cjs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/detective-cjs/-/detective-cjs-6.0.0.tgz", + "integrity": "sha512-R55jTS6Kkmy6ukdrbzY4x+I7KkXiuDPpFzUViFV/tm2PBGtTCjkh9ZmTuJc1SaziMHJOe636dtiZLEuzBL9drg==", + "dev": true, + "dependencies": { + "ast-module-types": "^6.0.0", + "node-source-walk": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/detective-es6": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/detective-es6/-/detective-es6-5.0.0.tgz", + "integrity": "sha512-NGTnzjvgeMW1khUSEXCzPDoraLenWbUjCFjwxReH+Ir+P6LGjYtaBbAvITWn2H0VSC+eM7/9LFOTAkrta6hNYg==", + "dev": true, + "dependencies": { + "node-source-walk": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/detective-postcss": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/detective-postcss/-/detective-postcss-7.0.0.tgz", + "integrity": "sha512-pSXA6dyqmBPBuERpoOKKTUUjQCZwZPLRbd1VdsTbt6W+m/+6ROl4BbE87yQBUtLoK7yX8pvXHdKyM/xNIW9F7A==", + "dev": true, + "dependencies": { + "is-url": "^1.2.4", + "postcss-values-parser": "^6.0.2" + }, + "engines": { + "node": "^14.0.0 || >=16.0.0" + }, + "peerDependencies": { + "postcss": "^8.4.38" + } + }, + "node_modules/detective-sass": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/detective-sass/-/detective-sass-6.0.0.tgz", + "integrity": "sha512-h5GCfFMkPm4ZUUfGHVPKNHKT8jV7cSmgK+s4dgQH4/dIUNh9/huR1fjEQrblOQNDalSU7k7g+tiW9LJ+nVEUhg==", + "dev": true, + "dependencies": { + "gonzales-pe": "^4.3.0", + "node-source-walk": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/detective-scss": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/detective-scss/-/detective-scss-5.0.0.tgz", + "integrity": "sha512-Y64HyMqntdsCh1qAH7ci95dk0nnpA29g319w/5d/oYcHolcGUVJbIhOirOFjfN1KnMAXAFm5FIkZ4l2EKFGgxg==", + "dev": true, + "dependencies": { + "gonzales-pe": "^4.3.0", + "node-source-walk": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/detective-stylus": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/detective-stylus/-/detective-stylus-5.0.0.tgz", + "integrity": "sha512-KMHOsPY6aq3196WteVhkY5FF+6Nnc/r7q741E+Gq+Ax9mhE2iwj8Hlw8pl+749hPDRDBHZ2WlgOjP+twIG61vQ==", + "dev": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/detective-typescript": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/detective-typescript/-/detective-typescript-13.0.0.tgz", + "integrity": "sha512-tcMYfiFWoUejSbvSblw90NDt76/4mNftYCX0SMnVRYzSXv8Fvo06hi4JOPdNvVNxRtCAKg3MJ3cBJh+ygEMH+A==", + "dev": true, + "dependencies": { + "@typescript-eslint/typescript-estree": "^7.6.0", + "ast-module-types": "^6.0.0", + "node-source-walk": "^7.0.0" + }, + "engines": { + "node": "^14.14.0 || >=16.0.0" + }, + "peerDependencies": { + "typescript": "^5.4.4" + } + }, + "node_modules/detective-vue2": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detective-vue2/-/detective-vue2-2.0.3.tgz", + "integrity": "sha512-AgWdSfVnft8uPGnUkdvE1EDadEENDCzoSRMt2xZfpxsjqVO617zGWXbB8TGIxHaqHz/nHa6lOSgAB8/dt0yEug==", + "dev": true, + "dependencies": { + "@vue/compiler-sfc": "^3.4.27", + "detective-es6": "^5.0.0", + "detective-sass": "^6.0.0", + "detective-scss": "^5.0.0", + "detective-stylus": "^5.0.0", + "detective-typescript": "^13.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "typescript": "^5.4.4" + } + }, "node_modules/diff": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", @@ -12199,6 +12561,40 @@ "node": ">= 0.4.0" } }, + "node_modules/filing-cabinet": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/filing-cabinet/-/filing-cabinet-5.0.2.tgz", + "integrity": "sha512-RZlFj8lzyu6jqtFBeXNqUjjNG6xm+gwXue3T70pRxw1W40kJwlgq0PSWAmh0nAnn5DHuBIecLXk9+1VKS9ICXA==", + "dev": true, + "dependencies": { + "app-module-path": "^2.2.0", + "commander": "^12.0.0", + "enhanced-resolve": "^5.16.0", + "module-definition": "^6.0.0", + "module-lookup-amd": "^9.0.1", + "resolve": "^1.22.8", + "resolve-dependency-path": "^4.0.0", + "sass-lookup": "^6.0.1", + "stylus-lookup": "^6.0.0", + "tsconfig-paths": "^4.2.0", + "typescript": "^5.4.4" + }, + "bin": { + "filing-cabinet": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/filing-cabinet/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", @@ -12521,6 +12917,19 @@ "node": ">=6.9.0" } }, + "node_modules/get-amd-module-type": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/get-amd-module-type/-/get-amd-module-type-6.0.0.tgz", + "integrity": "sha512-hFM7oivtlgJ3d6XWD6G47l8Wyh/C6vFw5G24Kk1Tbq85yh5gcM8Fne5/lFhiuxB+RT6+SI7I1ThB9lG4FBh3jw==", + "dev": true, + "dependencies": { + "ast-module-types": "^6.0.0", + "node-source-walk": "^7.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -12560,6 +12969,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-own-enumerable-property-symbols": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz", + "integrity": "sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g==", + "dev": true + }, "node_modules/get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", @@ -12872,9 +13287,24 @@ "node": ">= 6" } }, - "node_modules/gopd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", + "node_modules/gonzales-pe": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/gonzales-pe/-/gonzales-pe-4.3.0.tgz", + "integrity": "sha512-otgSPpUmdWJ43VXyiNgEYE4luzHCL2pz4wQ0OnDluC6Eg4Ko3Vexy/SrSynglw/eR+OhkzmqFCZa/OFa/RgAOQ==", + "dev": true, + "dependencies": { + "minimist": "^1.2.5" + }, + "bin": { + "gonzales": "bin/gonzales.js" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", "dependencies": { "get-intrinsic": "^1.1.3" @@ -14067,6 +14497,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-regexp/-/is-regexp-1.0.0.tgz", + "integrity": "sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-retry-allowed": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-2.2.0.tgz", @@ -14186,6 +14625,24 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-url": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", + "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==", + "dev": true + }, + "node_modules/is-url-superb": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-url-superb/-/is-url-superb-4.0.0.tgz", + "integrity": "sha512-GI+WjezhPPcbM+tqE9LnmsY5qqjwHzTvjJ36wxYX5ujNXefSUJ/T17r5bqDV8yLhcgB59KTPNOc9O9cmHTPWsA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-utf8": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", @@ -16884,9 +17341,9 @@ } }, "node_modules/lint-staged": { - "version": "15.2.8", - "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.2.8.tgz", - "integrity": "sha512-PUWFf2zQzsd9EFU+kM1d7UP+AZDbKFKuj+9JNVTBkhUFhbg4MAt6WfyMMwBfM4lYqd4D2Jwac5iuTu9rVj4zCQ==", + "version": "15.2.9", + "resolved": "https://registry.npmjs.org/lint-staged/-/lint-staged-15.2.9.tgz", + "integrity": "sha512-BZAt8Lk3sEnxw7tfxM7jeZlPRuT4M68O0/CwZhhaw6eeWu0Lz5eERE3m386InivXB64fp/mDID452h48tvKlRQ==", "dev": true, "dependencies": { "chalk": "~5.3.0", @@ -17526,6 +17983,146 @@ "yallist": "^3.0.2" } }, + "node_modules/madge": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/madge/-/madge-8.0.0.tgz", + "integrity": "sha512-9sSsi3TBPhmkTCIpVQF0SPiChj1L7Rq9kU2KDG1o6v2XH9cCw086MopjVCD+vuoL5v8S77DTbVopTO8OUiQpIw==", + "dev": true, + "dependencies": { + "chalk": "^4.1.2", + "commander": "^7.2.0", + "commondir": "^1.0.1", + "debug": "^4.3.4", + "dependency-tree": "^11.0.0", + "ora": "^5.4.1", + "pluralize": "^8.0.0", + "pretty-ms": "^7.0.1", + "rc": "^1.2.8", + "stream-to-array": "^2.3.0", + "ts-graphviz": "^2.1.2", + "walkdir": "^0.4.1" + }, + "bin": { + "madge": "bin/cli.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "individual", + "url": "https://www.paypal.me/pahen" + }, + "peerDependencies": { + "typescript": "^5.4.4" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/madge/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/madge/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/madge/node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/madge/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/madge/node_modules/commander": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", + "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "dev": true, + "engines": { + "node": ">= 10" + } + }, + "node_modules/madge/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/madge/node_modules/ora": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", + "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", + "dev": true, + "dependencies": { + "bl": "^4.1.0", + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.5.0", + "is-interactive": "^1.0.0", + "is-unicode-supported": "^0.1.0", + "log-symbols": "^4.1.0", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/madge/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/magic-string": { "version": "0.27.0", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.27.0.tgz", @@ -18175,6 +18772,49 @@ "node": ">=10" } }, + "node_modules/module-definition": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/module-definition/-/module-definition-6.0.0.tgz", + "integrity": "sha512-sEGP5nKEXU7fGSZUML/coJbrO+yQtxcppDAYWRE9ovWsTbFoUHB2qDUx564WUzDaBHXsD46JBbIK5WVTwCyu3w==", + "dev": true, + "dependencies": { + "ast-module-types": "^6.0.0", + "node-source-walk": "^7.0.0" + }, + "bin": { + "module-definition": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/module-lookup-amd": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/module-lookup-amd/-/module-lookup-amd-9.0.2.tgz", + "integrity": "sha512-p7PzSVEWiW9fHRX9oM+V4aV5B2nCVddVNv4DZ/JB6t9GsXY4E+ZVhPpnwUX7bbJyGeeVZqhS8q/JZ/H77IqPFA==", + "dev": true, + "dependencies": { + "commander": "^12.1.0", + "glob": "^7.2.3", + "requirejs": "^2.3.7", + "requirejs-config-file": "^4.0.0" + }, + "bin": { + "lookup-amd": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/module-lookup-amd/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/mri": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", @@ -18492,6 +19132,18 @@ "node": ">=12" } }, + "node_modules/node-source-walk": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/node-source-walk/-/node-source-walk-7.0.0.tgz", + "integrity": "sha512-1uiY543L+N7Og4yswvlm5NCKgPKDEXd9AUR9Jh3gen6oOeBsesr6LqhXom1er3eRzSUcVRWXzhv8tSNrIfGHKw==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.24.4" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/nopt": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/nopt/-/nopt-6.0.0.tgz", @@ -19558,6 +20210,15 @@ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", "dev": true }, + "node_modules/parse-ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-2.1.0.tgz", + "integrity": "sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, "node_modules/parse-passwd": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", @@ -19965,6 +20626,113 @@ "node": ">= 0.4" } }, + "node_modules/postcss": { + "version": "8.4.41", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.41.tgz", + "integrity": "sha512-TesUflQ0WKZqAvg52PWL6kHgLKP6xB6heTOdoYM0Wt2UHyxNa4K25EZZMgKns3BH1RLVbZCREPpLY0rhnNoHVQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.0.1", + "source-map-js": "^1.2.0" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-values-parser": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/postcss-values-parser/-/postcss-values-parser-6.0.2.tgz", + "integrity": "sha512-YLJpK0N1brcNJrs9WatuJFtHaV9q5aAOj+S4DI5S7jgHlRfm0PIbDCAFRYMQD5SHq7Fy6xsDhyutgS0QOAs0qw==", + "dev": true, + "dependencies": { + "color-name": "^1.1.4", + "is-url-superb": "^4.0.0", + "quote-unquote": "^1.0.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "postcss": "^8.2.9" + } + }, + "node_modules/postcss-values-parser/node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/postcss/node_modules/nanoid": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", + "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/precinct": { + "version": "12.1.2", + "resolved": "https://registry.npmjs.org/precinct/-/precinct-12.1.2.tgz", + "integrity": "sha512-x2qVN3oSOp3D05ihCd8XdkIPuEQsyte7PSxzLqiRgktu79S5Dr1I75/S+zAup8/0cwjoiJTQztE9h0/sWp9bJQ==", + "dev": true, + "dependencies": { + "@dependents/detective-less": "^5.0.0", + "commander": "^12.1.0", + "detective-amd": "^6.0.0", + "detective-cjs": "^6.0.0", + "detective-es6": "^5.0.0", + "detective-postcss": "^7.0.0", + "detective-sass": "^6.0.0", + "detective-scss": "^5.0.0", + "detective-stylus": "^5.0.0", + "detective-typescript": "^13.0.0", + "detective-vue2": "^2.0.3", + "module-definition": "^6.0.0", + "node-source-walk": "^7.0.0", + "postcss": "^8.4.40", + "typescript": "^5.5.4" + }, + "bin": { + "precinct": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/precinct/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -20015,6 +20783,21 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/pretty-ms": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-7.0.1.tgz", + "integrity": "sha512-973driJZvxiGOQ5ONsFhOF/DtzPMOMtgC11kCpUrPGMTgqp2q/1gwzCquocrN33is0VZ5GFHXZYMM9l6h67v2Q==", + "dev": true, + "dependencies": { + "parse-ms": "^2.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/proc-log": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/proc-log/-/proc-log-3.0.0.tgz", @@ -20395,6 +21178,12 @@ } ] }, + "node_modules/quote-unquote": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/quote-unquote/-/quote-unquote-1.0.0.tgz", + "integrity": "sha512-twwRO/ilhlG/FIgYeKGFqyHhoEhqgnKVkcmqMKi2r524gz3ZbDTcyFt38E9xjJI2vT+KbRNHVbnJ/e0I25Azwg==", + "dev": true + }, "node_modules/ramda": { "version": "0.30.1", "resolved": "https://registry.npmjs.org/ramda/-/ramda-0.30.1.tgz", @@ -21002,6 +21791,32 @@ "node": ">=0.10.0" } }, + "node_modules/requirejs": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/requirejs/-/requirejs-2.3.7.tgz", + "integrity": "sha512-DouTG8T1WanGok6Qjg2SXuCMzszOo0eHeH9hDZ5Y4x8Je+9JB38HdTLT4/VA8OaUhBa0JPVHJ0pyBkM1z+pDsw==", + "dev": true, + "bin": { + "r_js": "bin/r.js", + "r.js": "bin/r.js" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/requirejs-config-file": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/requirejs-config-file/-/requirejs-config-file-4.0.0.tgz", + "integrity": "sha512-jnIre8cbWOyvr8a5F2KuqBnY+SDA4NXr/hzEZJG79Mxm2WiFQz2dzhC8ibtPJS7zkmBEl1mxSwp5HhC1W4qpxw==", + "dev": true, + "dependencies": { + "esprima": "^4.0.0", + "stringify-object": "^3.2.1" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/requires-port": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", @@ -21037,6 +21852,15 @@ "node": ">=8" } }, + "node_modules/resolve-dependency-path": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-dependency-path/-/resolve-dependency-path-4.0.0.tgz", + "integrity": "sha512-hlY1SybBGm5aYN3PC4rp15MzsJLM1w+MEA/4KU3UBPfz4S0lL3FL6mgv7JgaA8a+ZTeEQAiF1a1BuN2nkqiIlg==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/resolve-dir": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", @@ -21332,9 +22156,9 @@ } }, "node_modules/rollup-plugin-external-globals": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-external-globals/-/rollup-plugin-external-globals-0.11.0.tgz", - "integrity": "sha512-LR+sH2WkgWMPxsA5o5rT7uW7BeWXSeygLe60QQi9qoN/ufaCuHDaVOIbndIkqDPnZt/wZugJh5DCzkZFdSWlLQ==", + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-external-globals/-/rollup-plugin-external-globals-0.12.0.tgz", + "integrity": "sha512-65Tqhh/f7hDY0qHmT4lYTVdDkY/BZU5bUQwS+SPvy6seSlACpcFRu2HzOmbLozXJS0/mOjwFyLlzJjlT2MTt8g==", "dev": true, "dependencies": { "@rollup/pluginutils": "^5.1.0", @@ -21685,6 +22509,30 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "dev": true }, + "node_modules/sass-lookup": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/sass-lookup/-/sass-lookup-6.0.1.tgz", + "integrity": "sha512-nl9Wxbj9RjEJA5SSV0hSDoU2zYGtE+ANaDS4OFUR7nYrquvBFvPKZZtQHe3lvnxCcylEDV00KUijjdMTUElcVQ==", + "dev": true, + "dependencies": { + "commander": "^12.0.0" + }, + "bin": { + "sass-lookup": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/sass-lookup/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -22400,6 +23248,15 @@ "node": ">=0.10.0" } }, + "node_modules/source-map-js": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.0.tgz", + "integrity": "sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/source-map-support": { "version": "0.5.19", "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz", @@ -22536,6 +23393,15 @@ "url": "https://jaywcjlove.github.io/#/sponsor" } }, + "node_modules/stream-to-array": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/stream-to-array/-/stream-to-array-2.3.0.tgz", + "integrity": "sha512-UsZtOYEn4tWU2RGLOXr/o/xjRBftZRlG3dEWoaHr8j4GuypJ3isitGbVyjQKAuMu+xbiop8q224TjiZWc4XTZA==", + "dev": true, + "dependencies": { + "any-promise": "^1.1.0" + } + }, "node_modules/strict-event-emitter": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/strict-event-emitter/-/strict-event-emitter-0.5.1.tgz", @@ -22728,6 +23594,29 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/stringify-object": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/stringify-object/-/stringify-object-3.3.0.tgz", + "integrity": "sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw==", + "dev": true, + "dependencies": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/stringify-object/node_modules/is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha512-l4RyHgRqGN4Y3+9JHVrNqO+tN0rV5My76uW5/nuO4K1b6vw5G8d/cmFjP9tRfEsdhZNt0IFdZuK/c2Vr4Nb+Qg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", @@ -22815,6 +23704,30 @@ "node": ">=4" } }, + "node_modules/stylus-lookup": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/stylus-lookup/-/stylus-lookup-6.0.0.tgz", + "integrity": "sha512-RaWKxAvPnIXrdby+UWCr1WRfa+lrPMSJPySte4Q6a+rWyjeJyFOLJxr5GrAVfcMCsfVlCuzTAJ/ysYT8p8do7Q==", + "dev": true, + "dependencies": { + "commander": "^12.0.0" + }, + "bin": { + "stylus-lookup": "bin/cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/stylus-lookup/node_modules/commander": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", + "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "dev": true, + "engines": { + "node": ">=18" + } + }, "node_modules/supports-color": { "version": "5.5.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", @@ -23199,6 +24112,31 @@ "typescript": ">=4.2.0" } }, + "node_modules/ts-graphviz": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ts-graphviz/-/ts-graphviz-2.1.2.tgz", + "integrity": "sha512-9GnOA3yiFaqZeHBEZXWa6kqc61FVhAhxQU5g3KLyGrhRr7OsDGRzs+1z35ctvD+hTTEhrBza6D41+qz+3qs7Zw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ts-graphviz" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/ts-graphviz" + } + ], + "dependencies": { + "@ts-graphviz/adapter": "^2.0.3", + "@ts-graphviz/ast": "^2.0.3", + "@ts-graphviz/common": "^2.1.2", + "@ts-graphviz/core": "^2.0.3" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/ts-jest": { "version": "29.2.4", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.2.4.tgz", @@ -23853,6 +24791,15 @@ "node": ">=14" } }, + "node_modules/walkdir": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/walkdir/-/walkdir-0.4.1.tgz", + "integrity": "sha512-3eBwRyEln6E1MSzcxcVpQIhRG8Q1jLvEqRmCZqS3dsfXEDR/AhOF4d+jHg1qvDCpYaVRZjENPQyrVxAkQqxPgQ==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/walker": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", @@ -24452,7 +25399,7 @@ "@rudderstack/analytics-js-common": "*", "@vespaiach/axios-fetch-adapter": "0.3.1", "assert": "2.1.0", - "axios": "1.7.3", + "axios": "1.7.4", "axios-retry": "4.5.0", "component-type": "2.0.0", "join-component": "1.1.0", @@ -24460,7 +25407,7 @@ }, "devDependencies": { "@types/ms": "0.7.34", - "@types/node": "22.1.0", + "@types/node": "22.3.0", "jest-date-mock": "1.0.10" } }, diff --git a/package.json b/package.json index 608c77da90..4ce901ec53 100644 --- a/package.json +++ b/package.json @@ -77,7 +77,7 @@ "@segment/top-domain": "3.0.1", "@vespaiach/axios-fetch-adapter": "0.3.1", "assert": "2.1.0", - "axios": "1.7.3", + "axios": "1.7.4", "axios-retry": "4.5.0", "component-each": "0.2.6", "component-emitter": "2.0.0", @@ -135,10 +135,10 @@ "@size-limit/file": "11.1.4", "@size-limit/webpack": "11.1.4", "@swc-node/register": "1.10.9", - "@swc/core": "1.7.6", + "@swc/core": "1.7.11", "@types/component-emitter": "1.2.14", "@types/jest": "29.5.12", - "@types/node": "22.1.0", + "@types/node": "22.3.0", "@types/ramda": "0.30.1", "babel-plugin-transform-object-hasown": "1.1.0", "commitizen": "4.3.0", @@ -169,7 +169,8 @@ "jest-watch-typeahead": "2.2.2", "join-component": "1.1.0", "jscpd": "4.0.5", - "lint-staged": "15.2.8", + "lint-staged": "15.2.9", + "madge": "8.0.0", "msw": "2.3.5", "nx": "19.5.7", "patch-package": "8.0.0", @@ -180,7 +181,7 @@ "rollup-plugin-delete": "2.0.0", "rollup-plugin-dts": "6.1.1", "rollup-plugin-exclude-dependencies-from-bundle": "1.1.23", - "rollup-plugin-external-globals": "0.11.0", + "rollup-plugin-external-globals": "0.12.0", "rollup-plugin-filesize": "10.0.0", "rollup-plugin-generate-html-template": "1.7.0", "rollup-plugin-livereload": "2.0.5", diff --git a/packages/analytics-js-common/__fixtures__/msw.handlers.ts b/packages/analytics-js-common/__fixtures__/msw.handlers.ts index 8c03392595..2bf5855c36 100644 --- a/packages/analytics-js-common/__fixtures__/msw.handlers.ts +++ b/packages/analytics-js-common/__fixtures__/msw.handlers.ts @@ -23,14 +23,6 @@ const handlers = [ }, }); }), - http.get(`${dummyDataplaneHost}/jsonSample`, () => { - return new HttpResponse(JSON.stringify({ json: 'sample' }), { - status: 200, - headers: { - 'Content-Type': 'application/json; charset=utf-8', - }, - }); - }), http.get(`${dummyDataplaneHost}/404ErrorSample`, () => { return new HttpResponse(null, { status: 404, diff --git a/packages/analytics-js-common/src/types/HttpClient.ts b/packages/analytics-js-common/src/types/HttpClient.ts index 3460850da0..08b8f4e887 100644 --- a/packages/analytics-js-common/src/types/HttpClient.ts +++ b/packages/analytics-js-common/src/types/HttpClient.ts @@ -1,46 +1,37 @@ import type { IErrorHandler } from './ErrorHandler'; import type { ILogger } from './Logger'; -export type XHRResponseDetails = { - response: string; - error?: Error; +export interface IHttpClientError extends Error { + status?: number; + statusText?: string; + responseBody?: string | null; +} + +export interface IResponseDetails { + response?: Response; + error?: IHttpClientError; url: string | URL; - xhr?: XMLHttpRequest; - options: IXHRRequestOptions; -}; + options: IRequestOptions; +} export type AsyncRequestCallback = ( - data?: T | string | undefined, - details?: XHRResponseDetails, + data: T | string | undefined | null, + details: IResponseDetails, ) => void; export interface IAsyncRequestConfig { url: string | URL; - options?: IXHRRequestOptions | IFetchRequestOptions | IBeaconRequestOptions; + options?: IRequestOptions; isRawResponse?: boolean; timeout?: number; callback?: AsyncRequestCallback; } -export interface IRequestOptions { - method: HTTPClientMethod; - headers?: Record; +export interface IBaseRequestOptions { sendRawData?: boolean; - withCredentials?: boolean; } -export interface IXHRRequestOptions extends IRequestOptions { - data?: Document | XMLHttpRequestBodyInit | null; -} - -export interface IFetchRequestOptions extends IRequestOptions { - data?: BodyInit | null; - keepalive?: boolean; -} - -export interface IBeaconRequestOptions extends IRequestOptions { - data?: BodyInit | null; -} +export type IRequestOptions = IXHRRequestOptions | IFetchRequestOptions | IBeaconRequestOptions; export type HTTPClientMethod = | 'GET' @@ -57,7 +48,40 @@ export interface IHttpClient { errorHandler?: IErrorHandler; logger?: ILogger; basicAuthHeader?: string; + transportFn: (url: string | URL, options: any) => Promise; getAsyncData(config: IAsyncRequestConfig): void; + request(config: IAsyncRequestConfig): void; setAuthHeader(value: string, noBto?: boolean): void; resetAuthHeader(): void; } + +export interface IXHRRequestOptions + extends Omit< + RequestInit, + | 'body' + | 'mode' + | 'cache' + | 'redirect' + | 'referrerPolicy' + | 'integrity' + | 'keepalive' + | 'method' + >, + IBaseRequestOptions { + withCredentials?: boolean; + body?: Document | XMLHttpRequestBodyInit | null; + timeout?: number; // timeout in milliseconds + method: HTTPClientMethod; +} + +export interface IFetchRequestOptions + extends Omit, + IBaseRequestOptions { + body?: BodyInit | null; + timeout?: number; // timeout in milliseconds + method: HTTPClientMethod; +} + +export interface IBeaconRequestOptions extends IBaseRequestOptions { + body?: BodyInit | null; +} diff --git a/packages/analytics-js-common/src/types/LoadOptions.ts b/packages/analytics-js-common/src/types/LoadOptions.ts index 25b559c3ec..7419282f10 100644 --- a/packages/analytics-js-common/src/types/LoadOptions.ts +++ b/packages/analytics-js-common/src/types/LoadOptions.ts @@ -46,7 +46,7 @@ export type BeaconQueueOpts = { flushQueueInterval?: number; }; -export type EventsTransportMode = 'xhr' | 'beacon'; +export type TransportType = 'fetch' | 'xhr' | 'beacon'; export type BatchOpts = { // Whether to enable batching @@ -143,8 +143,9 @@ export type LoadOptions = { dataPlaneEventsBufferTimeout?: number; storage?: StorageOpts; preConsent?: PreConsentOptions; - // transport mechanism to be used for sending batched requests - transportMode?: EventsTransportMode; // Unused for now. This will deprecate the useBeacon and beaconQueueOptions + // transport mechanism to be used for sending events + // This will deprecate the useBeacon and beaconQueueOptions + deliveryMethod?: TransportType; consentManagement?: ConsentManagementOptions; sameDomainCookiesOnly?: boolean; externalAnonymousIdCookieName?: string; diff --git a/packages/analytics-js-common/src/utilities/http.ts b/packages/analytics-js-common/src/utilities/http.ts index 8fecd37bab..f7b1eb9b70 100644 --- a/packages/analytics-js-common/src/utilities/http.ts +++ b/packages/analytics-js-common/src/utilities/http.ts @@ -1,11 +1,11 @@ -import type { XHRResponseDetails } from '../types/HttpClient'; +import type { IResponseDetails } from '../types/HttpClient'; -const isErrRetryable = (details?: XHRResponseDetails) => { +const isErrRetryable = (details: IResponseDetails) => { let isRetryableNWFailure = false; - if (details?.error && details?.xhr) { - const xhrStatus = details.xhr.status; + if (details.error?.status) { + const { status } = details.error; // same as in v1.1 - isRetryableNWFailure = xhrStatus === 429 || (xhrStatus >= 500 && xhrStatus < 600); + isRetryableNWFailure = status === 429 || (status >= 500 && status < 600); } return isRetryableNWFailure; }; diff --git a/packages/analytics-js-plugins/__tests__/customConsentManager/index.test.ts b/packages/analytics-js-plugins/__tests__/customConsentManager/index.test.ts index 340e9b2d81..9a59c7ddc9 100644 --- a/packages/analytics-js-plugins/__tests__/customConsentManager/index.test.ts +++ b/packages/analytics-js-plugins/__tests__/customConsentManager/index.test.ts @@ -255,7 +255,7 @@ describe('Plugin - CustomConsentManager', () => { ), ).toBe(true); - expect(mockErrorHandler.onError).toBeCalledWith( + expect(mockErrorHandler.onError).toHaveBeenCalledWith( new TypeError("Cannot read properties of null (reading 'includes')"), 'CustomConsentManagerPlugin', 'Failed to determine the consent status for the destination. Please check the destination configuration and try again.', diff --git a/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts b/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts index bdcc3c4f18..871e60a26d 100644 --- a/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts +++ b/packages/analytics-js-plugins/__tests__/deviceModeTransformation/index.test.ts @@ -8,7 +8,10 @@ import { defaultErrorHandler } from '@rudderstack/analytics-js/services/ErrorHan import { defaultLogger } from '@rudderstack/analytics-js/services/Logger'; import { StoreManager } from '@rudderstack/analytics-js/services/StoreManager'; import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event'; -import type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient'; +import type { + IHttpClient, + IResponseDetails, +} from '@rudderstack/analytics-js-common/types/HttpClient'; import { dummyDataplaneHost, dummyWriteKey, @@ -18,6 +21,7 @@ import { import { server } from '../../__fixtures__/msw.server'; import * as utils from '@rudderstack/analytics-js-plugins/deviceModeTransformation/utilities'; import { DeviceModeTransformation } from '@rudderstack/analytics-js-plugins/deviceModeTransformation'; +import { HttpClientError } from '@rudderstack/analytics-js/services/HttpClient/utils'; jest.mock('@rudderstack/analytics-js-common/utilities/uuId', () => ({ ...jest.requireActual('@rudderstack/analytics-js-common/utilities/uuId'), @@ -42,7 +46,7 @@ describe('Device mode transformation plugin', () => { }); }); - const httpClient = new HttpClient(); + const httpClient = new HttpClient('fetch'); afterAll(() => { server.close(); @@ -121,7 +125,7 @@ describe('Device mode transformation plugin', () => { DeviceModeTransformation().transformEvent?.enqueue(state, queue, event, destinations); - expect(addItemSpy).toBeCalledWith({ + expect(addItemSpy).toHaveBeenCalledWith({ token: authToken, destinationIds, event, @@ -132,7 +136,7 @@ describe('Device mode transformation plugin', () => { it('should process queue item on start', () => { const mockHttpClient = { - getAsyncData: ({ callback }) => { + request: ({ callback }) => { callback(true); }, setAuthHeader: jest.fn(), @@ -164,7 +168,7 @@ describe('Device mode transformation plugin', () => { // In actual implementation, this is done based on the state signals queue.start(); - expect(queueProcessCbSpy).toBeCalledWith( + expect(queueProcessCbSpy).toHaveBeenCalledWith( { token: authToken, destinationIds, @@ -184,8 +188,10 @@ describe('Device mode transformation plugin', () => { it('SendTransformedEventToDestinations function is called in case of successful transformation', () => { const mockHttpClient: IHttpClient = { - getAsyncData: ({ callback }) => { - callback?.(JSON.stringify(dmtSuccessResponse), { xhr: { status: 200 } }); + request: ({ callback }) => { + callback?.(JSON.stringify(dmtSuccessResponse), { + response: { status: 200 } as Response, + } as IResponseDetails); }, setAuthHeader: jest.fn(), }; @@ -218,7 +224,7 @@ describe('Device mode transformation plugin', () => { queue.start(); DeviceModeTransformation().transformEvent?.enqueue(state, queue, event, destinations); - expect(mockSendTransformedEventToDestinations).toBeCalledTimes(1); + expect(mockSendTransformedEventToDestinations).toHaveBeenCalledTimes(1); expect(mockSendTransformedEventToDestinations).toHaveBeenCalledWith( state, defaultPluginsManager, @@ -233,8 +239,8 @@ describe('Device mode transformation plugin', () => { }); it('SendTransformedEventToDestinations function should not be called in case of unsuccessful transformation', () => { const mockHttpClient: IHttpClient = { - getAsyncData: ({ callback }) => { - callback?.(false, { error: 'some error', xhr: { status: 502 } }); + request: ({ callback }) => { + callback?.(null, { error: new HttpClientError('some error', 502) } as IResponseDetails); }, setAuthHeader: jest.fn(), }; @@ -267,7 +273,7 @@ describe('Device mode transformation plugin', () => { queue.start(); DeviceModeTransformation().transformEvent?.enqueue(state, queue, event, destinations); - expect(mockSendTransformedEventToDestinations).not.toBeCalled(); + expect(mockSendTransformedEventToDestinations).not.toHaveBeenCalled(); // The element is requeued expect(queue.getStorageEntry('queue')).toStrictEqual([ { diff --git a/packages/analytics-js-plugins/__tests__/errorReporting/index.test.ts b/packages/analytics-js-plugins/__tests__/errorReporting/index.test.ts index f1cab14dca..f454546608 100644 --- a/packages/analytics-js-plugins/__tests__/errorReporting/index.test.ts +++ b/packages/analytics-js-plugins/__tests__/errorReporting/index.test.ts @@ -109,7 +109,7 @@ describe('Plugin - ErrorReporting', () => { metricsServiceUrl: signal('https://test.com'), }; const mockHttpClient = { - getAsyncData: jest.fn(), + request: jest.fn(), setAuthHeader: jest.fn(), } as unknown as IHttpClient; const newError = new Error(); @@ -133,7 +133,7 @@ describe('Plugin - ErrorReporting', () => { }, ); - expect(mockHttpClient.getAsyncData).not.toHaveBeenCalled(); + expect(mockHttpClient.request).not.toHaveBeenCalled(); }); it('should send data to metrics service on notify when httpClient is provided', () => { @@ -144,7 +144,7 @@ describe('Plugin - ErrorReporting', () => { metricsServiceUrl: signal('https://test.com'), }; const mockHttpClient = { - getAsyncData: jest.fn(), + request: jest.fn(), setAuthHeader: jest.fn(), } as unknown as IHttpClient; const newError = new Error(); @@ -168,12 +168,12 @@ describe('Plugin - ErrorReporting', () => { }, ); - expect(mockHttpClient.getAsyncData).toHaveBeenCalled(); + expect(mockHttpClient.request).toHaveBeenCalled(); }); it('should not notify if the error is not an SDK error', () => { const mockHttpClient = { - getAsyncData: jest.fn(), + request: jest.fn(), setAuthHeader: jest.fn(), } as unknown as IHttpClient; const newError = new Error(); @@ -197,7 +197,7 @@ describe('Plugin - ErrorReporting', () => { }, ); - expect(mockHttpClient.getAsyncData).not.toHaveBeenCalled(); + expect(mockHttpClient.request).not.toHaveBeenCalled(); }); it('should add a new breadcrumb', () => { diff --git a/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts b/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts index f6555bed2a..eb017e776d 100644 --- a/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts +++ b/packages/analytics-js-plugins/__tests__/errorReporting/utils.test.ts @@ -322,7 +322,6 @@ describe('Error Reporting utilities', () => { }; (window as any).RudderSnippetVersion = 'sample_snippet_version'; const enhancedError = getBugsnagErrorEvent(errorPayload, errorState, appState); - console.log(JSON.stringify(enhancedError)); const expectedOutcome = { notifier: { name: 'RudderStack JavaScript SDK Error Notifier', diff --git a/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts b/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts index d20a4f5053..f64176bc95 100644 --- a/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts +++ b/packages/analytics-js-plugins/__tests__/xhrQueue/index.test.ts @@ -10,9 +10,13 @@ import { defaultLogger } from '@rudderstack/analytics-js/services/Logger'; import { StoreManager } from '@rudderstack/analytics-js/services/StoreManager'; import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; -import type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient'; +import type { + IHttpClient, + IResponseDetails, +} from '@rudderstack/analytics-js-common/types/HttpClient'; import { XhrQueue } from '../../src/xhrQueue'; import { Schedule } from '../../src/utilities/retryQueue/Schedule'; +import { HttpClientError } from '@rudderstack/analytics-js/services/HttpClient/utils'; jest.mock('@rudderstack/analytics-js-common/utilities/timestamp', () => ({ ...jest.requireActual('@rudderstack/analytics-js-common/utilities/timestamp'), @@ -51,7 +55,7 @@ describe('XhrQueue', () => { }); }); - const httpClient = new HttpClient(); + const httpClient = new HttpClient('xhr'); it('should add itself to the loaded plugins list on initialized', () => { XhrQueue().initialize(state); @@ -91,7 +95,7 @@ describe('XhrQueue', () => { XhrQueue().dataplaneEventsQueue?.enqueue(state, queue, event); - expect(addItemSpy).toBeCalledWith({ + expect(addItemSpy).toHaveBeenCalledWith({ url: 'https://sampleurl.com/v1/track', headers: { AnonymousId: 'c2FtcGxlQW5vbklk', // Base64 encoded anonymousId @@ -104,7 +108,7 @@ describe('XhrQueue', () => { it('should process queue item on start', () => { const mockHttpClient = { - getAsyncData: ({ callback }) => { + request: ({ callback }) => { callback(true); }, setAuthHeader: jest.fn(), @@ -131,7 +135,7 @@ describe('XhrQueue', () => { // In actual implementation, this is done based on the state signals queue.start(); - expect(queueProcessCbSpy).toBeCalledWith( + expect(queueProcessCbSpy).toHaveBeenCalledWith( { url: 'https://sampleurl.com/v1/track', headers: { @@ -153,8 +157,8 @@ describe('XhrQueue', () => { it('should log error on retryable failure and requeue the item', () => { const mockHttpClient = { - getAsyncData: ({ callback }) => { - callback(false, { error: 'some error', xhr: { status: 429 } }); + request: ({ callback }) => { + callback(null, { error: new HttpClientError('some error', 429) } as IResponseDetails); }, setAuthHeader: jest.fn(), } as unknown as IHttpClient; @@ -191,7 +195,7 @@ describe('XhrQueue', () => { // In actual implementation, this is done based on the state signals queue.start(); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://sampleurl.com/v1/track. It/they will be retried.', ); @@ -229,7 +233,7 @@ describe('XhrQueue', () => { }); const mockHttpClient = { - getAsyncData: jest.fn(), + request: jest.fn(), setAuthHeader: jest.fn(), } as unknown as IHttpClient; @@ -279,7 +283,7 @@ describe('XhrQueue', () => { // In actual implementation, this is done based on the state signals queue.start(); - expect(queueProcessCbSpy).toBeCalledWith( + expect(queueProcessCbSpy).toHaveBeenCalledWith( [ { url: 'https://sampleurl.com/v1/track', @@ -302,7 +306,7 @@ describe('XhrQueue', () => { true, ); - expect(mockHttpClient.getAsyncData).toBeCalledWith({ + expect(mockHttpClient.request).toHaveBeenCalledWith({ url: 'https://sampleurl.com/v1/batch', options: { method: 'POST', @@ -310,7 +314,7 @@ describe('XhrQueue', () => { AnonymousId: 'c2FtcGxlQW5vbklk', // Base64 encoded anonymousId }, sendRawData: true, - data: '{"batch":[{"type":"track","event":"test","userId":"test","properties":{"test":"test"},"anonymousId":"sampleAnonId","messageId":"test","originalTimestamp":"test","sentAt":"sample_timestamp"},{"type":"track","event":"test2","userId":"test2","properties":{"test2":"test2"},"anonymousId":"sampleAnonId","messageId":"test2","originalTimestamp":"test2","sentAt":"sample_timestamp"}],"sentAt":"sample_timestamp"}', + body: '{"batch":[{"type":"track","event":"test","userId":"test","properties":{"test":"test"},"anonymousId":"sampleAnonId","messageId":"test","originalTimestamp":"test","sentAt":"sample_timestamp"},{"type":"track","event":"test2","userId":"test2","properties":{"test2":"test2"},"anonymousId":"sampleAnonId","messageId":"test2","originalTimestamp":"test2","sentAt":"sample_timestamp"}],"sentAt":"sample_timestamp"}', }, isRawResponse: true, timeout: 30000, diff --git a/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts b/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts index c72d7ba53b..054e9ce87c 100644 --- a/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts +++ b/packages/analytics-js-plugins/__tests__/xhrQueue/utilities.test.ts @@ -1,5 +1,5 @@ import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event'; -import type { XHRResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; +import type { IResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import { state, resetState } from '@rudderstack/analytics-js/state'; import { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp'; @@ -120,81 +120,100 @@ describe('xhrQueue Plugin Utilities', () => { it('should not log error if there is no error', () => { const details = { response: {}, - } as XHRResponseDetails; + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', false, 1, 10, mockLogger); - expect(mockLogger.error).not.toBeCalled(); + expect(mockLogger.error).not.toHaveBeenCalled(); }); it('should log an error for delivery failure', () => { const details = { error: {}, - } as XHRResponseDetails; + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', false, 1, 10, mockLogger); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://test.com/v1/page. The event(s) will be dropped.', ); }); it('should log an error for retryable network failure', () => { - const details = { - error: {}, - xhr: { + let details = { + error: { status: 429, }, - } as XHRResponseDetails; + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', true, 1, 10, mockLogger); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://test.com/v1/page. It/they will be retried. Retry attempt 1 of 10.', ); // Retryable error but it's the first attempt - details.xhr.status = 429; + details = { + error: { + status: 429, + }, + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', true, 0, 10, mockLogger); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://test.com/v1/page. It/they will be retried.', ); // 500 error - details.xhr.status = 500; + details = { + error: { + status: 500, + }, + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', true, 1, 10, mockLogger); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://test.com/v1/page. It/they will be retried. Retry attempt 1 of 10.', ); // 5xx error - details.xhr.status = 501; + details = { + error: { + status: 501, + }, + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', true, 1, 10, mockLogger); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://test.com/v1/page. It/they will be retried. Retry attempt 1 of 10.', ); // 600 error - details.xhr.status = 600; + details = { + error: { + status: 600, + }, + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', true, 1, 10, mockLogger); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://test.com/v1/page. The event(s) will be dropped.', ); // Retryable error but exhausted all tries - details.xhr.status = 520; + details = { + error: { + status: 520, + }, + } as IResponseDetails; logErrorOnFailure(details, 'https://test.com/v1/page', false, 10, 10, mockLogger); - expect(mockLogger.error).toBeCalledWith( + expect(mockLogger.error).toHaveBeenCalledWith( 'XhrQueuePlugin:: Failed to deliver event(s) to https://test.com/v1/page. Retries exhausted (10). The event(s) will be dropped.', ); }); diff --git a/packages/analytics-js-plugins/src/deviceModeTransformation/index.ts b/packages/analytics-js-plugins/src/deviceModeTransformation/index.ts index c82094fec6..bd943724f6 100644 --- a/packages/analytics-js-plugins/src/deviceModeTransformation/index.ts +++ b/packages/analytics-js-plugins/src/deviceModeTransformation/index.ts @@ -53,11 +53,11 @@ const DeviceModeTransformation = (): ExtensionPlugin => ({ ) => { const payload = createPayload(item.event, item.destinationIds, item.token); - httpClient.getAsyncData({ + httpClient.request({ url: `${state.lifecycle.activeDataplaneUrl.value}/transform`, options: { method: 'POST', - data: getDMTDeliveryPayload(payload) as string, + body: getDMTDeliveryPayload(payload) as string, sendRawData: true, }, isRawResponse: true, @@ -72,7 +72,7 @@ const DeviceModeTransformation = (): ExtensionPlugin => ({ pluginsManager, item.destinationIds, result, - details?.xhr?.status, + details.error?.status ?? details.response?.status, item.event, errorHandler, logger, diff --git a/packages/analytics-js-plugins/src/errorReporting/index.ts b/packages/analytics-js-plugins/src/errorReporting/index.ts index 61e7baa584..8e1284bff4 100644 --- a/packages/analytics-js-plugins/src/errorReporting/index.ts +++ b/packages/analytics-js-plugins/src/errorReporting/index.ts @@ -97,11 +97,11 @@ const ErrorReporting = (): ExtensionPlugin => ({ const bugsnagPayload = getBugsnagErrorEvent(errorPayload, errorState as ErrorState, state); // send it to metrics service - httpClient?.getAsyncData({ + httpClient?.request({ url: state.metrics.metricsServiceUrl.value as string, options: { method: 'POST', - data: getErrorDeliveryPayload(bugsnagPayload, state), + body: getErrorDeliveryPayload(bugsnagPayload, state), sendRawData: true, }, isRawResponse: true, diff --git a/packages/analytics-js-plugins/src/fetchQueue/index.ts b/packages/analytics-js-plugins/src/fetchQueue/index.ts index 78d4486171..346e870bc5 100644 --- a/packages/analytics-js-plugins/src/fetchQueue/index.ts +++ b/packages/analytics-js-plugins/src/fetchQueue/index.ts @@ -72,12 +72,12 @@ const FetchQueue = (): ExtensionPlugin => ({ logger, ); - httpClient.getAsyncData({ + httpClient.request({ url, options: { method: 'POST', headers, - data: data as string, + body: data as string, sendRawData: true, }, isRawResponse: true, diff --git a/packages/analytics-js-plugins/src/fetchQueue/utilities.ts b/packages/analytics-js-plugins/src/fetchQueue/utilities.ts index 9e4c13e234..f76f255125 100644 --- a/packages/analytics-js-plugins/src/fetchQueue/utilities.ts +++ b/packages/analytics-js-plugins/src/fetchQueue/utilities.ts @@ -1,6 +1,6 @@ import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object'; import type { QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions'; -import type { XHRResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; +import type { IResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState'; import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event'; @@ -41,14 +41,14 @@ const getDeliveryUrl = (dataplaneUrl: string, endpoint: string): string => { const getBatchDeliveryUrl = (dataplaneUrl: string): string => getDeliveryUrl(dataplaneUrl, 'batch'); const logErrorOnFailure = ( - details: XHRResponseDetails | undefined, + details: IResponseDetails, url: string, willBeRetried?: boolean, attemptNumber?: number, maxRetryAttempts?: number, logger?: ILogger, ) => { - if (checks.isUndefined(details?.error) || checks.isUndefined(logger)) { + if (checks.isUndefined(details.error) || checks.isUndefined(logger)) { return; } diff --git a/packages/analytics-js-plugins/src/xhrQueue/index.ts b/packages/analytics-js-plugins/src/xhrQueue/index.ts index 13978bc499..a43c88e50a 100644 --- a/packages/analytics-js-plugins/src/xhrQueue/index.ts +++ b/packages/analytics-js-plugins/src/xhrQueue/index.ts @@ -72,12 +72,12 @@ const XhrQueue = (): ExtensionPlugin => ({ logger, ); - httpClient.getAsyncData({ + httpClient.request({ url, options: { method: 'POST', headers, - data: data as string, + body: data as string, sendRawData: true, }, isRawResponse: true, diff --git a/packages/analytics-js-plugins/src/xhrQueue/utilities.ts b/packages/analytics-js-plugins/src/xhrQueue/utilities.ts index 67d4c3e581..ffa25b2b8e 100644 --- a/packages/analytics-js-plugins/src/xhrQueue/utilities.ts +++ b/packages/analytics-js-plugins/src/xhrQueue/utilities.ts @@ -1,6 +1,6 @@ import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object'; import type { QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions'; -import type { XHRResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; +import type { IResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState'; import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event'; @@ -37,14 +37,14 @@ const getDeliveryUrl = (dataplaneUrl: string, endpoint: string): string => { const getBatchDeliveryUrl = (dataplaneUrl: string): string => getDeliveryUrl(dataplaneUrl, 'batch'); const logErrorOnFailure = ( - details: XHRResponseDetails | undefined, + details: IResponseDetails, url: string, willBeRetried?: boolean, attemptNumber?: number, maxRetryAttempts?: number, logger?: ILogger, ) => { - if (checks.isUndefined(details?.error) || checks.isUndefined(logger)) { + if (checks.isUndefined(details.error) || checks.isUndefined(logger)) { return; } diff --git a/packages/analytics-js-service-worker/package.json b/packages/analytics-js-service-worker/package.json index 7150998f97..39fece58c0 100644 --- a/packages/analytics-js-service-worker/package.json +++ b/packages/analytics-js-service-worker/package.json @@ -93,7 +93,7 @@ "@rudderstack/analytics-js-common": "*", "@vespaiach/axios-fetch-adapter": "0.3.1", "assert": "2.1.0", - "axios": "1.7.3", + "axios": "1.7.4", "axios-retry": "4.5.0", "component-type": "2.0.0", "join-component": "1.1.0", @@ -101,7 +101,7 @@ }, "devDependencies": { "@types/ms": "0.7.34", - "@types/node": "22.1.0", + "@types/node": "22.3.0", "jest-date-mock": "1.0.10" }, "overrides": {}, diff --git a/packages/analytics-js/.size-limit.mjs b/packages/analytics-js/.size-limit.mjs index 3f1ab4c30f..b468ae54ad 100644 --- a/packages/analytics-js/.size-limit.mjs +++ b/packages/analytics-js/.size-limit.mjs @@ -7,118 +7,118 @@ export default [ name: 'Core - Legacy - NPM (ESM)', path: 'dist/npm/legacy/esm/index.mjs', import: '*', - limit: '47.5 KiB', + limit: '48.5 KiB', }, { name: 'Core - Legacy - NPM (CJS)', path: 'dist/npm/legacy/cjs/index.cjs', import: '*', - limit: '48 KiB', + limit: '49 KiB', }, { name: 'Core - Legacy - NPM (UMD)', path: 'dist/npm/legacy/umd/index.js', import: '*', - limit: '47.5 KiB', + limit: '48.5 KiB', }, { name: 'Core - Legacy - CDN', path: 'dist/cdn/legacy/iife/rsa.min.js', - limit: '48 KiB', + limit: '49 KiB', }, { name: 'Core - Modern - NPM (ESM)', path: 'dist/npm/modern/esm/index.mjs', import: '*', - limit: '24.5 KiB', + limit: '25.5 KiB', }, { name: 'Core - Modern - NPM (CJS)', path: 'dist/npm/modern/cjs/index.cjs', import: '*', - limit: '24.5 KiB', + limit: '25.5 KiB', }, { name: 'Core - Modern - NPM (UMD)', path: 'dist/npm/modern/umd/index.js', import: '*', - limit: '24.5 KiB', + limit: '25.5 KiB', }, { name: 'Core - Modern - CDN', path: 'dist/cdn/modern/iife/rsa.min.js', - limit: '24.5 KiB', + limit: '25.5 KiB', }, { name: 'Core (Bundled) - Legacy - NPM (ESM)', path: 'dist/npm/legacy/bundled/esm/index.mjs', import: '*', - limit: '47.5 KiB', + limit: '48.5 KiB', }, { name: 'Core (Bundled) - Legacy - NPM (CJS)', path: 'dist/npm/legacy/bundled/cjs/index.cjs', import: '*', - limit: '48 KiB', + limit: '49 KiB', }, { name: 'Core (Bundled) - Legacy - NPM (UMD)', path: 'dist/npm/legacy/bundled/umd/index.js', import: '*', - limit: '47.5 KiB', + limit: '48.5 KiB', }, { name: 'Core (Bundled) - Modern - NPM (ESM)', path: 'dist/npm/modern/bundled/esm/index.mjs', import: '*', - limit: '39 KiB', + limit: '40 KiB', }, { name: 'Core (Bundled) - Modern - NPM (CJS)', path: 'dist/npm/modern/bundled/cjs/index.cjs', import: '*', - limit: '39 KiB', + limit: '40 KiB', }, { name: 'Core (Bundled) - Modern - NPM (UMD)', path: 'dist/npm/modern/bundled/umd/index.js', import: '*', - limit: '39 KiB', + limit: '40 KiB', }, { name: 'Core (Content Script) - Legacy - NPM (ESM)', path: 'dist/npm/legacy/content-script/esm/index.mjs', import: '*', - limit: '47 KiB', + limit: '48 KiB', }, { name: 'Core (Content Script) - Legacy - NPM (CJS)', path: 'dist/npm/legacy/content-script/cjs/index.cjs', import: '*', - limit: '47.5 KiB', + limit: '48.5 KiB', }, { name: 'Core (Content Script) - Legacy - NPM (UMD)', path: 'dist/npm/legacy/content-script/umd/index.js', import: '*', - limit: '47 KiB', + limit: '48 KiB', }, { name: 'Core (Content Script) - Modern - NPM (ESM)', path: 'dist/npm/modern/content-script/esm/index.mjs', import: '*', - limit: '38.5 KiB', + limit: '39.5 KiB', }, { name: 'Core (Content Script) - Modern - NPM (CJS)', path: 'dist/npm/modern/content-script/cjs/index.cjs', import: '*', - limit: '38.5 KiB', + limit: '39.5 KiB', }, { name: 'Core (Content Script) - Modern - NPM (UMD)', path: 'dist/npm/modern/content-script/umd/index.js', import: '*', - limit: '38.5 KiB', + limit: '39.5 KiB', }, ]; diff --git a/packages/analytics-js/__fixtures__/msw.handlers.ts b/packages/analytics-js/__fixtures__/msw.handlers.ts index 38299ae4a2..6c8780096b 100644 --- a/packages/analytics-js/__fixtures__/msw.handlers.ts +++ b/packages/analytics-js/__fixtures__/msw.handlers.ts @@ -23,14 +23,6 @@ const handlers = [ }, }); }), - http.get(`${dummyDataplaneHost}/jsonSample`, () => { - return new HttpResponse(JSON.stringify({ json: 'sample' }), { - status: 200, - headers: { - 'Content-Type': 'application/json; charset=utf-8', - }, - }); - }), http.get(`${dummyDataplaneHost}/404ErrorSample`, () => { return new HttpResponse(null, { status: 404, diff --git a/packages/analytics-js/__mocks__/cdnSDK.js.map b/packages/analytics-js/__mocks__/cdnSDK.js.map new file mode 100644 index 0000000000..cf67f50f39 --- /dev/null +++ b/packages/analytics-js/__mocks__/cdnSDK.js.map @@ -0,0 +1 @@ +{"version":3,"file":"rsa.min.js","sources":["../../../../../../node_modules/ramda/es/internal/_isPlaceholder.js","../../../../../../node_modules/ramda/es/internal/_curry1.js","../../../../../../node_modules/ramda/es/internal/_curry2.js","../../../../../../node_modules/ramda/es/internal/_curry3.js","../../../../../../node_modules/ramda/es/internal/_has.js","../../../../../../node_modules/ramda/es/type.js","../../../../../../node_modules/ramda/es/internal/_isObject.js","../../../../../../node_modules/ramda/es/internal/_isInteger.js","../../../../../../node_modules/ramda/es/internal/_nth.js","../../../../../../node_modules/ramda/es/internal/_isString.js","../../../../../../node_modules/ramda/es/internal/_clone.js","../../../../../../node_modules/ramda/es/internal/_cloneRegExp.js","../../../../../../node_modules/ramda/es/clone.js","../../../../../../node_modules/ramda/es/internal/_path.js","../../../../../../node_modules/ramda/es/mergeWithKey.js","../../../../../../node_modules/ramda/es/mergeDeepWithKey.js","../../../../../../node_modules/ramda/es/mergeDeepWith.js","../../../../../../node_modules/ramda/es/path.js","../../../../../../node_modules/ramda/es/pickBy.js","../../../../../analytics-js-common/src/utilities/checks.ts","../../../../../analytics-js-common/src/utilities/object.ts","../../../../../analytics-js-common/src/utilities/string.ts","../../../../../analytics-js-common/src/utilities/eventMethodOverloads.ts","../../../../../analytics-js-common/src/constants/loggerContexts.ts","../../../../src/constants/app.ts","../../../../src/constants/queryParams.ts","../../../../src/constants/timeouts.ts","../../../../src/components/utilities/globals.ts","../../../../src/components/preloadBuffer/index.ts","../../../../../analytics-js-common/src/constants/logMessages.ts","../../../../../analytics-js-common/src/utilities/json.ts","../../../../../analytics-js-common/src/utilities/errors.ts","../../../../../analytics-js-common/src/services/ExternalSrcLoader/jsFileLoader.ts","../../../../../analytics-js-common/src/constants/htmlAttributes.ts","../../../../../analytics-js-common/src/services/ExternalSrcLoader/ExternalSrcLoader.ts","../../../../../analytics-js-common/src/constants/timeouts.ts","../../../../../../node_modules/@preact/signals-core/dist/signals-core.module.js","../../../../../analytics-js-common/src/services/BufferQueue/BufferQueue.ts","../../../../src/services/Logger/Logger.ts","../../../../../analytics-js-common/src/types/ErrorHandler.ts","../../../../../analytics-js-common/src/types/Storage.ts","../../../../src/constants/logMessages.ts","../../../../../analytics-js-common/src/constants/urls.ts","../../../../src/constants/urls.ts","../../../../src/components/configManager/constants.ts","../../../../src/state/slices/loadOptions.ts","../../../../src/components/userSessionManager/constants.ts","../../../../src/state/slices/session.ts","../../../../src/state/slices/capabilities.ts","../../../../src/state/slices/reporting.ts","../../../../src/state/slices/source.ts","../../../../src/state/slices/lifecycle.ts","../../../../src/state/slices/consents.ts","../../../../src/state/slices/metrics.ts","../../../../src/state/slices/context.ts","../../../../src/state/slices/nativeDestinations.ts","../../../../src/state/slices/eventBuffer.ts","../../../../src/state/slices/plugins.ts","../../../../src/state/slices/storage.ts","../../../../src/state/slices/serverCookies.ts","../../../../src/state/slices/dataPlaneEvents.ts","../../../../src/state/index.ts","../../../../src/services/PluginEngine/PluginEngine.ts","../../../../src/services/ErrorHandler/ErrorHandler.ts","../../../../src/services/ErrorHandler/processError.ts","../../../../src/services/ErrorHandler/constant.ts","../../../../../analytics-js-common/src/utilities/destinations.ts","../../../../src/components/pluginsManager/pluginNames.ts","../../../../../analytics-js-common/src/utilities/timestamp.ts","../../../../../analytics-js-common/src/constants/storages.ts","../../../../../analytics-js-common/src/utilities/url.ts","../../../../../../node_modules/@lukeed/uuid/secure/index.mjs","../../../../../../node_modules/@lukeed/csprng/browser/index.mjs","../../../../../../node_modules/@lukeed/uuid/dist/index.mjs","../../../../../analytics-js-common/src/utilities/crypto.ts","../../../../../analytics-js-common/src/utilities/uuId.ts","../../../../../analytics-js-common/src/utilities/http.ts","../../../../../analytics-js-cookies/src/constants/cookies.ts","../../../../../analytics-js-cookies/src/component-cookie/index.ts","../../../../../analytics-js-cookies/src/constants/logMessages.ts","../../../../../analytics-js-cookies/src/cookiesUtilities.ts","../../../../../analytics-js-plugins/src/utilities/eventsDelivery.ts","../../../../../analytics-js-plugins/src/utilities/constants.ts","../../../../../analytics-js-plugins/src/beaconQueue/constants.ts","../../../../../analytics-js-plugins/src/beaconQueue/utilities.ts","../../../../../analytics-js-plugins/src/beaconQueue/logMessages.ts","../../../../../analytics-js-common/src/constants/QueueStatuses.ts","../../../../../analytics-js-plugins/src/utilities/retryQueue/Schedule.ts","../../../../../analytics-js-plugins/src/utilities/retryQueue/constants.ts","../../../../../analytics-js-plugins/src/utilities/retryQueue/RetryQueue.ts","../../../../../analytics-js-common/src/utilities/page.ts","../../../../../analytics-js-plugins/src/utilities/retryQueue/logMessages.ts","../../../../../analytics-js-plugins/src/beaconQueue/index.ts","../../../../../analytics-js-plugins/src/bugsnag/constants.ts","../../../../../analytics-js-plugins/src/bugsnag/utils.ts","../../../../../analytics-js-plugins/src/bugsnag/logMessages.ts","../../../../../analytics-js-plugins/src/bugsnag/index.ts","../../../../../analytics-js-plugins/src/customConsentManager/index.ts","../../../../../analytics-js-plugins/src/customConsentManager/constants.ts","../../../../../analytics-js-plugins/src/customConsentManager/logMessages.ts","../../../../../analytics-js-common/src/constants/integrations/AdobeAnalytics/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Amplitude/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Appcues/constants.ts","../../../../../analytics-js-common/src/constants/integrations/BingAds/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Braze/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Bugsnag/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Chartbeat/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Clevertap/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Comscore/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Criteo/constants.ts","../../../../../analytics-js-common/src/constants/integrations/CustomerIO/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Drip/constants.ts","../../../../../analytics-js-common/src/constants/integrations/FacebookPixel/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Fullstory/constants.ts","../../../../../analytics-js-common/src/constants/integrations/GA/constants.ts","../../../../../analytics-js-common/src/constants/integrations/GA4/constants.ts","../../../../../analytics-js-common/src/constants/integrations/GA4_V2/constants.ts","../../../../../analytics-js-common/src/constants/integrations/GoogleAds/constants.ts","../../../../../analytics-js-common/src/constants/integrations/GoogleOptimize/constants.ts","../../../../../analytics-js-common/src/constants/integrations/GoogleTagManager/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Heap/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Hotjar/constants.ts","../../../../../analytics-js-common/src/constants/integrations/HubSpot/constants.ts","../../../../../analytics-js-common/src/constants/integrations/INTERCOM/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Keen/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Kissmetrics/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Klaviyo/constants.ts","../../../../../analytics-js-common/src/constants/integrations/LaunchDarkly/constants.ts","../../../../../analytics-js-common/src/constants/integrations/LinkedInInsightTag/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Lotame/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Lytics/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Mixpanel/constants.ts","../../../../../analytics-js-common/src/constants/integrations/MoEngage/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Optimizely/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Pendo/constants.ts","../../../../../analytics-js-common/src/constants/integrations/PinterestTag/constants.ts","../../../../../analytics-js-common/src/constants/integrations/PostAffiliatePro/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Posthog/constants.ts","../../../../../analytics-js-common/src/constants/integrations/ProfitWell/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Qualtrics/constants.ts","../../../../../analytics-js-common/src/constants/integrations/QuantumMetric/constants.ts","../../../../../analytics-js-common/src/constants/integrations/RedditPixel/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Sentry/constants.ts","../../../../../analytics-js-common/src/constants/integrations/SnapPixel/constants.ts","../../../../../analytics-js-common/src/constants/integrations/TVSquared/constants.ts","../../../../../analytics-js-common/src/constants/integrations/VWO/constants.ts","../../../../../analytics-js-common/src/constants/integrations/GA360/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Adroll/constants.ts","../../../../../analytics-js-common/src/constants/integrations/DCMFloodlight/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Matomo/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Vero/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Mouseflow/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Rockerbox/constants.ts","../../../../../analytics-js-common/src/constants/integrations/ConvertFlow/constants.ts","../../../../../analytics-js-common/src/constants/integrations/SnapEngage/constants.ts","../../../../../analytics-js-common/src/constants/integrations/LiveChat/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Shynet/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Woopra/constants.ts","../../../../../analytics-js-common/src/constants/integrations/RollBar/constants.ts","../../../../../analytics-js-common/src/constants/integrations/QuoraPixel/constants.ts","../../../../../analytics-js-common/src/constants/integrations/June/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Engage/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Iterable/constants.ts","../../../../../analytics-js-common/src/constants/integrations/YandexMetrica/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Refiner/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Qualaroo/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Podsights/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Axeptio/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Satismeter/constants.ts","../../../../../analytics-js-common/src/constants/integrations/MicrosoftClarity/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Sendinblue/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Olark/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Lemnisk/constants.ts","../../../../../analytics-js-common/src/constants/integrations/TiktokAds/constants.ts","../../../../../analytics-js-common/src/constants/integrations/ActiveCampaign/constants.js","../../../../../analytics-js-common/src/constants/integrations/Sprig/constants.ts","../../../../../analytics-js-common/src/constants/integrations/SpotifyPixel/constants.ts","../../../../../analytics-js-common/src/constants/integrations/CommandBar/constants.ts","../../../../../analytics-js-common/src/constants/integrations/Ninetailed/constants.ts","../../../../../analytics-js-common/src/constants/integrations/destDisplayNamesToFileNamesMap.ts","../../../../../analytics-js-common/src/constants/integrationsConfig.ts","../../../../../analytics-js-plugins/src/utilities/destination.ts","../../../../../analytics-js-plugins/src/deviceModeDestinations/constants.ts","../../../../../analytics-js-plugins/src/deviceModeDestinations/logMessages.ts","../../../../../analytics-js-plugins/src/deviceModeDestinations/utils.ts","../../../../../analytics-js-plugins/src/deviceModeDestinations/index.ts","../../../../../analytics-js-plugins/src/deviceModeTransformation/constants.ts","../../../../../analytics-js-plugins/src/deviceModeTransformation/logMessages.ts","../../../../../analytics-js-plugins/src/deviceModeTransformation/utilities.ts","../../../../../analytics-js-plugins/src/deviceModeTransformation/index.ts","../../../../../analytics-js-common/src/constants/errors.ts","../../../../../analytics-js-plugins/src/errorReporting/constants.ts","../../../../../analytics-js-plugins/src/errorReporting/utils.ts","../../../../../analytics-js-common/src/constants/metrics.ts","../../../../../../node_modules/error-stack-parser/error-stack-parser.js","../../../../../../node_modules/stackframe/stackframe.js","../../../../../analytics-js-plugins/src/errorReporting/event/utils.ts","../../../../../analytics-js-plugins/src/errorReporting/event/event.ts","../../../../../../node_modules/crypto-es/lib/core.js","../../../../../analytics-js-plugins/src/errorReporting/index.ts","../../../../../analytics-js-plugins/src/errorReporting/logMessages.ts","../../../../../analytics-js-plugins/src/externalAnonymousId/constants.ts","../../../../../analytics-js-plugins/src/externalAnonymousId/index.ts","../../../../../analytics-js-plugins/src/externalAnonymousId/util.ts","../../../../../analytics-js-plugins/src/googleLinker/userLib.ts","../../../../../analytics-js-plugins/src/googleLinker/base64Decoder.ts","../../../../../analytics-js-plugins/src/googleLinker/utils.ts","../../../../../analytics-js-plugins/src/googleLinker/crc32.ts","../../../../../analytics-js-plugins/src/googleLinker/index.ts","../../../../../analytics-js-plugins/src/ketchConsentManager/constants.ts","../../../../../analytics-js-plugins/src/ketchConsentManager/utils.ts","../../../../../analytics-js-plugins/src/ketchConsentManager/logMessages.ts","../../../../../analytics-js-plugins/src/ketchConsentManager/index.ts","../../../../../analytics-js-plugins/src/nativeDestinationQueue/constants.ts","../../../../../analytics-js-plugins/src/nativeDestinationQueue/utilities.ts","../../../../../analytics-js-plugins/src/nativeDestinationQueue/logMessages.ts","../../../../../analytics-js-plugins/src/nativeDestinationQueue/index.ts","../../../../../analytics-js-plugins/src/oneTrustConsentManager/constants.ts","../../../../../analytics-js-plugins/src/oneTrustConsentManager/index.ts","../../../../../analytics-js-plugins/src/oneTrustConsentManager/logMessages.ts","../../../../../analytics-js-plugins/src/storageEncryption/index.ts","../../../../../../node_modules/crypto-es/lib/md5.js","../../../../../../node_modules/crypto-es/lib/enc-base64.js","../../../../../../node_modules/crypto-es/lib/evpkdf.js","../../../../../../node_modules/crypto-es/lib/cipher-core.js","../../../../../../node_modules/crypto-es/lib/aes.js","../../../../../analytics-js-plugins/src/storageEncryptionLegacy/constants.ts","../../../../../analytics-js-plugins/src/storageEncryptionLegacy/legacyEncryptionUtils.ts","../../../../../analytics-js-plugins/src/storageEncryptionLegacy/index.ts","../../../../../analytics-js-plugins/src/storageMigrator/index.ts","../../../../../analytics-js-plugins/src/storageMigrator/constants.ts","../../../../../analytics-js-plugins/src/storageMigrator/logMessages.ts","../../../../../analytics-js-plugins/src/xhrQueue/constants.ts","../../../../../analytics-js-plugins/src/xhrQueue/utilities.ts","../../../../../analytics-js-plugins/src/xhrQueue/logMessages.ts","../../../../../analytics-js-plugins/src/xhrQueue/index.ts","../../../../../analytics-js-plugins/src/fetchQueue/constants.ts","../../../../../analytics-js-plugins/src/fetchQueue/utilities.ts","../../../../../analytics-js-plugins/src/fetchQueue/logMessages.ts","../../../../../analytics-js-plugins/src/fetchQueue/index.ts","../../../../src/components/pluginsManager/pluginsInventory.ts","../../../../src/components/pluginsManager/bundledBuildPluginImports.ts","../../../../src/components/pluginsManager/PluginsManager.ts","../../../../src/services/HttpClient/utils.ts","../../../../src/services/HttpClient/xhr/index.ts","../../../../src/services/HttpClient/fetch/index.ts","../../../../src/services/HttpClient/beacon/index.ts","../../../../src/services/HttpClient/HttpClient.ts","../../../../src/constants/storage.ts","../../../../src/services/StoreManager/types.ts","../../../../src/components/capabilitiesManager/detection/browser.ts","../../../../src/components/capabilitiesManager/detection/dom.ts","../../../../src/components/capabilitiesManager/detection/screen.ts","../../../../src/components/capabilitiesManager/detection/storage.ts","../../../../src/services/StoreManager/top-domain/index.ts","../../../../src/services/StoreManager/storages/defaultOptions.ts","../../../../src/services/StoreManager/storages/CookieStorage.ts","../../../../src/services/StoreManager/storages/InMemoryStorage.ts","../../../../../../node_modules/storejs/dist/store.js","../../../../src/services/StoreManager/storages/LocalStorage.ts","../../../../src/services/StoreManager/storages/sessionStorage.ts","../../../../src/services/StoreManager/storages/storageEngine.ts","../../../../src/services/StoreManager/Store.ts","../../../../src/services/StoreManager/StoreManager.ts","../../../../src/services/StoreManager/utils.ts","../../../../src/components/configManager/util/validate.ts","../../../../src/components/utilities/url.ts","../../../../../analytics-js-common/src/constants/consent.ts","../../../../src/components/utilities/consent.ts","../../../../src/components/configManager/util/commonUtil.ts","../../../../src/components/utilities/statsCollection.ts","../../../../../analytics-js-common/src/utilities/detect.ts","../../../../src/components/configManager/util/cdnPaths.ts","../../../../src/components/configManager/ConfigManager.ts","../../../../src/components/utilities/destinations.ts","../../../../src/components/utilities/page.ts","../../../../src/components/capabilitiesManager/polyfill/index.ts","../../../../src/components/capabilitiesManager/CapabilitiesManager.ts","../../../../../analytics-js-common/src/utilities/timezone.ts","../../../../src/components/capabilitiesManager/detection/clientHint.ts","../../../../src/components/capabilitiesManager/detection/adBlockers.ts","../../../../src/components/eventManager/constants.ts","../../../../src/components/utilities/number.ts","../../../../src/components/userSessionManager/utils.ts","../../../../src/components/eventManager/utilities.ts","../../../../src/components/eventManager/RudderEventFactory.ts","../../../../src/components/eventManager/EventManager.ts","../../../../src/components/userSessionManager/UserSessionManager.ts","../../../../src/components/pluginsManager/defaultPluginsList.ts","../../../../src/components/eventRepository/constants.ts","../../../../src/components/eventRepository/utils.ts","../../../../src/components/eventRepository/EventRepository.ts","../../../../src/components/core/utilities.ts","../../../../src/components/core/Analytics.ts","../../../../src/components/utilities/loadOptions.ts","../../../../src/app/RudderAnalytics.ts","../../../../src/browser.ts"],"sourcesContent":["export default function _isPlaceholder(a) {\n return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true;\n}","import _isPlaceholder from \"./_isPlaceholder.js\";\n\n/**\n * Optimized internal one-arity curry function.\n *\n * @private\n * @category Function\n * @param {Function} fn The function to curry.\n * @return {Function} The curried function.\n */\nexport default function _curry1(fn) {\n return function f1(a) {\n if (arguments.length === 0 || _isPlaceholder(a)) {\n return f1;\n } else {\n return fn.apply(this, arguments);\n }\n };\n}","import _curry1 from \"./_curry1.js\";\nimport _isPlaceholder from \"./_isPlaceholder.js\";\n\n/**\n * Optimized internal two-arity curry function.\n *\n * @private\n * @category Function\n * @param {Function} fn The function to curry.\n * @return {Function} The curried function.\n */\nexport default function _curry2(fn) {\n return function f2(a, b) {\n switch (arguments.length) {\n case 0:\n return f2;\n case 1:\n return _isPlaceholder(a) ? f2 : _curry1(function (_b) {\n return fn(a, _b);\n });\n default:\n return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) {\n return fn(_a, b);\n }) : _isPlaceholder(b) ? _curry1(function (_b) {\n return fn(a, _b);\n }) : fn(a, b);\n }\n };\n}","import _curry1 from \"./_curry1.js\";\nimport _curry2 from \"./_curry2.js\";\nimport _isPlaceholder from \"./_isPlaceholder.js\";\n\n/**\n * Optimized internal three-arity curry function.\n *\n * @private\n * @category Function\n * @param {Function} fn The function to curry.\n * @return {Function} The curried function.\n */\nexport default function _curry3(fn) {\n return function f3(a, b, c) {\n switch (arguments.length) {\n case 0:\n return f3;\n case 1:\n return _isPlaceholder(a) ? f3 : _curry2(function (_b, _c) {\n return fn(a, _b, _c);\n });\n case 2:\n return _isPlaceholder(a) && _isPlaceholder(b) ? f3 : _isPlaceholder(a) ? _curry2(function (_a, _c) {\n return fn(_a, b, _c);\n }) : _isPlaceholder(b) ? _curry2(function (_b, _c) {\n return fn(a, _b, _c);\n }) : _curry1(function (_c) {\n return fn(a, b, _c);\n });\n default:\n return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function (_a, _b) {\n return fn(_a, _b, c);\n }) : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function (_a, _c) {\n return fn(_a, b, _c);\n }) : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function (_b, _c) {\n return fn(a, _b, _c);\n }) : _isPlaceholder(a) ? _curry1(function (_a) {\n return fn(_a, b, c);\n }) : _isPlaceholder(b) ? _curry1(function (_b) {\n return fn(a, _b, c);\n }) : _isPlaceholder(c) ? _curry1(function (_c) {\n return fn(a, b, _c);\n }) : fn(a, b, c);\n }\n };\n}","export default function _has(prop, obj) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}","import _curry1 from \"./internal/_curry1.js\";\n\n/**\n * Gives a single-word string description of the (native) type of a value,\n * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not\n * attempt to distinguish user Object types any further, reporting them all as\n * 'Object'.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Type\n * @sig * -> String\n * @param {*} val The value to test\n * @return {String}\n * @example\n *\n * R.type({}); //=> \"Object\"\n * R.type(1); //=> \"Number\"\n * R.type(false); //=> \"Boolean\"\n * R.type('s'); //=> \"String\"\n * R.type(null); //=> \"Null\"\n * R.type([]); //=> \"Array\"\n * R.type(/[A-z]/); //=> \"RegExp\"\n * R.type(() => {}); //=> \"Function\"\n * R.type(async () => {}); //=> \"AsyncFunction\"\n * R.type(undefined); //=> \"Undefined\"\n * R.type(BigInt(123)); //=> \"BigInt\"\n */\nvar type = /*#__PURE__*/_curry1(function type(val) {\n return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1);\n});\nexport default type;","export default function _isObject(x) {\n return Object.prototype.toString.call(x) === '[object Object]';\n}","/**\n * Determine if the passed argument is an integer.\n *\n * @private\n * @param {*} n\n * @category Type\n * @return {Boolean}\n */\nexport default Number.isInteger || function _isInteger(n) {\n return n << 0 === n;\n};","import _isString from \"./_isString.js\";\nexport default function _nth(offset, list) {\n var idx = offset < 0 ? list.length + offset : offset;\n return _isString(list) ? list.charAt(idx) : list[idx];\n}","export default function _isString(x) {\n return Object.prototype.toString.call(x) === '[object String]';\n}","import _cloneRegExp from \"./_cloneRegExp.js\";\nimport type from \"../type.js\";\n\n/**\n * Copies an object.\n *\n * @private\n * @param {*} value The value to be copied\n * @param {Boolean} deep Whether or not to perform deep cloning.\n * @return {*} The copied value.\n */\nexport default function _clone(value, deep, map) {\n map || (map = new _ObjectMap());\n\n // this avoids the slower switch with a quick if decision removing some milliseconds in each run.\n if (_isPrimitive(value)) {\n return value;\n }\n var copy = function copy(copiedValue) {\n // Check for circular and same references on the object graph and return its corresponding clone.\n var cachedCopy = map.get(value);\n if (cachedCopy) {\n return cachedCopy;\n }\n map.set(value, copiedValue);\n for (var key in value) {\n if (Object.prototype.hasOwnProperty.call(value, key)) {\n copiedValue[key] = deep ? _clone(value[key], true, map) : value[key];\n }\n }\n return copiedValue;\n };\n switch (type(value)) {\n case 'Object':\n return copy(Object.create(Object.getPrototypeOf(value)));\n case 'Array':\n return copy(Array(value.length));\n case 'Date':\n return new Date(value.valueOf());\n case 'RegExp':\n return _cloneRegExp(value);\n case 'Int8Array':\n case 'Uint8Array':\n case 'Uint8ClampedArray':\n case 'Int16Array':\n case 'Uint16Array':\n case 'Int32Array':\n case 'Uint32Array':\n case 'Float32Array':\n case 'Float64Array':\n case 'BigInt64Array':\n case 'BigUint64Array':\n return value.slice();\n default:\n return value;\n }\n}\nfunction _isPrimitive(param) {\n var type = typeof param;\n return param == null || type != 'object' && type != 'function';\n}\nvar _ObjectMap = /*#__PURE__*/function () {\n function _ObjectMap() {\n this.map = {};\n this.length = 0;\n }\n _ObjectMap.prototype.set = function (key, value) {\n var hashedKey = this.hash(key);\n var bucket = this.map[hashedKey];\n if (!bucket) {\n this.map[hashedKey] = bucket = [];\n }\n bucket.push([key, value]);\n this.length += 1;\n };\n _ObjectMap.prototype.hash = function (key) {\n var hashedKey = [];\n for (var value in key) {\n hashedKey.push(Object.prototype.toString.call(key[value]));\n }\n return hashedKey.join();\n };\n _ObjectMap.prototype.get = function (key) {\n /**\n * depending on the number of objects to be cloned is faster to just iterate over the items in the map just because the hash function is so costly,\n * on my tests this number is 180, anything above that using the hash function is faster.\n */\n if (this.length <= 180) {\n for (var p in this.map) {\n var bucket = this.map[p];\n for (var i = 0; i < bucket.length; i += 1) {\n var element = bucket[i];\n if (element[0] === key) {\n return element[1];\n }\n }\n }\n return;\n }\n var hashedKey = this.hash(key);\n var bucket = this.map[hashedKey];\n if (!bucket) {\n return;\n }\n for (var i = 0; i < bucket.length; i += 1) {\n var element = bucket[i];\n if (element[0] === key) {\n return element[1];\n }\n }\n };\n return _ObjectMap;\n}();","export default function _cloneRegExp(pattern) {\n return new RegExp(pattern.source, pattern.flags ? pattern.flags : (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : '') + (pattern.dotAll ? 's' : ''));\n}","import _clone from \"./internal/_clone.js\";\nimport _curry1 from \"./internal/_curry1.js\";\n\n/**\n * Creates a deep copy of the source that can be used in place of the source\n * object without retaining any references to it.\n * The source object may contain (nested) `Array`s and `Object`s,\n * `Number`s, `String`s, `Boolean`s and `Date`s.\n * `Function`s are assigned by reference rather than copied.\n *\n * Dispatches to a `clone` method if present.\n *\n * Note that if the source object has multiple nodes that share a reference,\n * the returned object will have the same structure, but the references will\n * be pointed to the location within the cloned value.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Object\n * @sig {*} -> {*}\n * @param {*} value The object or array to clone\n * @return {*} A deeply cloned copy of `val`\n * @example\n *\n * const objects = [{}, {}, {}];\n * const objectsClone = R.clone(objects);\n * objects === objectsClone; //=> false\n * objects[0] === objectsClone[0]; //=> false\n */\nvar clone = /*#__PURE__*/_curry1(function clone(value) {\n return value != null && typeof value.clone === 'function' ? value.clone() : _clone(value, true);\n});\nexport default clone;","import _isInteger from \"./_isInteger.js\";\nimport _nth from \"./_nth.js\";\nexport default function _path(pathAr, obj) {\n var val = obj;\n for (var i = 0; i < pathAr.length; i += 1) {\n if (val == null) {\n return undefined;\n }\n var p = pathAr[i];\n if (_isInteger(p)) {\n val = _nth(p, val);\n } else {\n val = val[p];\n }\n }\n return val;\n}","import _curry3 from \"./internal/_curry3.js\";\nimport _has from \"./internal/_has.js\";\n\n/**\n * Creates a new object with the own properties of the two provided objects. If\n * a key exists in both objects, the provided function is applied to the key\n * and the values associated with the key in each object, with the result being\n * used as the value associated with the key in the returned object.\n *\n * @func\n * @memberOf R\n * @since v0.19.0\n * @category Object\n * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}\n * @param {Function} fn\n * @param {Object} l\n * @param {Object} r\n * @return {Object}\n * @see R.mergeDeepWithKey, R.merge, R.mergeWith\n * @example\n *\n * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r\n * R.mergeWithKey(concatValues,\n * { a: true, thing: 'foo', values: [10, 20] },\n * { b: true, thing: 'bar', values: [15, 35] });\n * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }\n * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }\n */\nvar mergeWithKey = /*#__PURE__*/_curry3(function mergeWithKey(fn, l, r) {\n var result = {};\n var k;\n l = l || {};\n r = r || {};\n for (k in l) {\n if (_has(k, l)) {\n result[k] = _has(k, r) ? fn(k, l[k], r[k]) : l[k];\n }\n }\n for (k in r) {\n if (_has(k, r) && !_has(k, result)) {\n result[k] = r[k];\n }\n }\n return result;\n});\nexport default mergeWithKey;","import _curry3 from \"./internal/_curry3.js\";\nimport _isObject from \"./internal/_isObject.js\";\nimport mergeWithKey from \"./mergeWithKey.js\";\n\n/**\n * Creates a new object with the own properties of the two provided objects.\n * If a key exists in both objects:\n * - and both associated values are also objects then the values will be\n * recursively merged.\n * - otherwise the provided function is applied to the key and associated values\n * using the resulting value as the new value associated with the key.\n * If a key only exists in one object, the value will be associated with the key\n * of the resulting object.\n *\n * @func\n * @memberOf R\n * @since v0.24.0\n * @category Object\n * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}\n * @param {Function} fn\n * @param {Object} lObj\n * @param {Object} rObj\n * @return {Object}\n * @see R.mergeWithKey, R.mergeDeepWith\n * @example\n *\n * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r\n * R.mergeDeepWithKey(concatValues,\n * { a: true, c: { thing: 'foo', values: [10, 20] }},\n * { b: true, c: { thing: 'bar', values: [15, 35] }});\n * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}\n */\nvar mergeDeepWithKey = /*#__PURE__*/_curry3(function mergeDeepWithKey(fn, lObj, rObj) {\n return mergeWithKey(function (k, lVal, rVal) {\n if (_isObject(lVal) && _isObject(rVal)) {\n return mergeDeepWithKey(fn, lVal, rVal);\n } else {\n return fn(k, lVal, rVal);\n }\n }, lObj, rObj);\n});\nexport default mergeDeepWithKey;","import _curry3 from \"./internal/_curry3.js\";\nimport mergeDeepWithKey from \"./mergeDeepWithKey.js\";\n\n/**\n * Creates a new object with the own properties of the two provided objects.\n * If a key exists in both objects:\n * - and both associated values are also objects then the values will be\n * recursively merged.\n * - otherwise the provided function is applied to associated values using the\n * resulting value as the new value associated with the key.\n * If a key only exists in one object, the value will be associated with the key\n * of the resulting object.\n *\n * @func\n * @memberOf R\n * @since v0.24.0\n * @category Object\n * @sig ((a, a) -> a) -> {a} -> {a} -> {a}\n * @param {Function} fn\n * @param {Object} lObj\n * @param {Object} rObj\n * @return {Object}\n * @see R.mergeWith, R.mergeDeepWithKey\n * @example\n *\n * R.mergeDeepWith(R.concat,\n * { a: true, c: { values: [10, 20] }},\n * { b: true, c: { values: [15, 35] }});\n * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}\n */\nvar mergeDeepWith = /*#__PURE__*/_curry3(function mergeDeepWith(fn, lObj, rObj) {\n return mergeDeepWithKey(function (k, lVal, rVal) {\n return fn(lVal, rVal);\n }, lObj, rObj);\n});\nexport default mergeDeepWith;","import _curry2 from \"./internal/_curry2.js\";\nimport _path from \"./internal/_path.js\";\n\n/**\n * Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.\n * For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.\n *\n * @func\n * @memberOf R\n * @since v0.2.0\n * @category Object\n * @typedefn Idx = String | Int | Symbol\n * @sig [Idx] -> {a} -> a | Undefined\n * @sig Idx = String | NonNegativeInt\n * @param {Array} path The path to use.\n * @param {Object} obj The object or array to retrieve the nested property from.\n * @return {*} The data at `path`.\n * @see R.prop, R.nth, R.assocPath, R.dissocPath\n * @example\n *\n * R.path(['a', 'b'], {a: {b: 2}}); //=> 2\n * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined\n * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1\n * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2\n * R.path([2], {'2': 2}); //=> 2\n * R.path([-2], {'-2': 'a'}); //=> undefined\n */\n\nvar path = /*#__PURE__*/_curry2(_path);\nexport default path;","import _curry2 from \"./internal/_curry2.js\";\n\n/**\n * Returns a partial copy of an object containing only the keys that satisfy\n * the supplied predicate.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Object\n * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}\n * @param {Function} pred A predicate to determine whether or not a key\n * should be included on the output object.\n * @param {Object} obj The object to copy from\n * @return {Object} A new object with only properties that satisfy `pred`\n * on it.\n * @see R.pick, R.filter\n * @example\n *\n * const isUpperCase = (val, key) => key.toUpperCase() === key;\n * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}\n */\nvar pickBy = /*#__PURE__*/_curry2(function pickBy(test, obj) {\n var result = {};\n for (var prop in obj) {\n if (test(obj[prop], prop, obj)) {\n result[prop] = obj[prop];\n }\n }\n return result;\n});\nexport default pickBy;","/**\n * A function to check given value is a function\n * @param value input value\n * @returns boolean\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nconst isFunction = (value: any): value is Function =>\n typeof value === 'function' && Boolean(value.constructor && value.call && value.apply);\n\n/**\n * A function to check given value is a string\n * @param value input value\n * @returns boolean\n */\nconst isString = (value: any): value is string => typeof value === 'string';\n\n/**\n * A function to check given value is null or not\n * @param value input value\n * @returns boolean\n */\nconst isNull = (value: any): value is null => value === null;\n\n/**\n * A function to check given value is undefined\n * @param value input value\n * @returns boolean\n */\nconst isUndefined = (value: any): value is undefined => typeof value === 'undefined';\n\n/**\n * A function to check given value is null or undefined\n * @param value input value\n * @returns boolean\n */\nconst isNullOrUndefined = (value: any): boolean => isNull(value) || isUndefined(value);\n\n/**\n * A function to check given value is defined\n * @param value input value\n * @returns boolean\n */\nconst isDefined = (value: any): boolean => !isUndefined(value);\n\n/**\n * A function to check given value is defined and not null\n * @param value input value\n * @returns boolean\n */\nconst isDefinedAndNotNull = (value: any): boolean => !isNullOrUndefined(value);\n\n/**\n * A function to check given value is defined and not null\n * @param value input value\n * @returns boolean\n */\nconst isDefinedNotNullAndNotEmptyString = (value: any): boolean =>\n isDefinedAndNotNull(value) && value !== '';\n\n/**\n * Determines if the input is an instance of Error\n * @param obj input value\n * @returns true if the input is an instance of Error and false otherwise\n */\nconst isTypeOfError = (obj: any): obj is Error => obj instanceof Error;\n\nexport {\n isFunction,\n isString,\n isNull,\n isUndefined,\n isNullOrUndefined,\n isTypeOfError,\n isDefined,\n isDefinedAndNotNull,\n isDefinedNotNullAndNotEmptyString,\n};\n","import { clone, mergeDeepWith, path, pickBy } from 'ramda';\nimport { isDefined, isDefinedAndNotNull, isNull } from './checks';\n\nconst getValueByPath = (obj: Record, keyPath: string): any => {\n const pathParts = keyPath.split('.');\n return path(pathParts, obj);\n};\n\nconst hasValueByPath = (obj: Record, path: string): boolean =>\n Boolean(getValueByPath(obj, path));\n\n/**\n * Checks if the input is an object literal or built-in object type and not null\n * @param value Input value\n * @returns true if the input is an object and not null\n */\nconst isObjectAndNotNull = (value: any): value is object =>\n !isNull(value) && typeof value === 'object' && !Array.isArray(value);\n\n/**\n * Checks if the input is an object literal and not null\n * @param value Input value\n * @returns true if the input is an object and not null\n */\nconst isObjectLiteralAndNotNull = (value?: T): value is T =>\n !isNull(value) && Object.prototype.toString.call(value) === '[object Object]';\n\nconst mergeDeepRightObjectArrays = (\n leftValue: any | any[],\n rightValue: any | any[],\n): any | any[] => {\n if (!Array.isArray(leftValue) || !Array.isArray(rightValue)) {\n return clone(rightValue);\n }\n\n const mergedArray = clone(leftValue);\n rightValue.forEach((value, index) => {\n mergedArray[index] =\n Array.isArray(value) || isObjectAndNotNull(value)\n ? // eslint-disable-next-line @typescript-eslint/no-use-before-define\n mergeDeepRight(mergedArray[index], value)\n : value;\n });\n return mergedArray;\n};\n\nconst mergeDeepRight = >(\n leftObject: Record,\n rightObject: Record,\n): T => mergeDeepWith(mergeDeepRightObjectArrays, leftObject, rightObject);\n\n/**\n Checks if the input is a non-empty object literal type and not undefined or null\n * @param value input any\n * @returns boolean\n */\nconst isNonEmptyObject = (value?: T): value is T =>\n isObjectLiteralAndNotNull(value) && Object.keys(value as any).length > 0;\n\n/**\n * A utility to recursively remove undefined values from an object\n * @param obj input object\n * @returns a new object\n */\nconst removeUndefinedValues = >(obj: T): T => {\n const result = pickBy(isDefined, obj) as Record;\n Object.keys(result).forEach(key => {\n const value = result[key];\n if (isObjectLiteralAndNotNull(value)) {\n result[key] = removeUndefinedValues(value);\n }\n });\n\n return result as T;\n};\n\n/**\n * A utility to recursively remove undefined and null values from an object\n * @param obj input object\n * @returns a new object\n */\nconst removeUndefinedAndNullValues = >(obj: T): T => {\n const result = pickBy(isDefinedAndNotNull, obj) as Record;\n Object.keys(result).forEach(key => {\n const value = result[key];\n if (isObjectLiteralAndNotNull(value)) {\n result[key] = removeUndefinedAndNullValues(value);\n }\n });\n\n return result as T;\n};\n\n/**\n * A utility to get all the values from an object\n * @param obj Input object\n * @returns an array of values from the input object\n */\nconst getObjectValues = >(obj: T): any[] => {\n const result: any[] = [];\n Object.keys(obj as Record).forEach(key => {\n result.push((obj as Record)[key]);\n });\n\n return result;\n};\n\nexport {\n getValueByPath,\n hasValueByPath,\n mergeDeepRightObjectArrays,\n mergeDeepRight,\n isObjectAndNotNull,\n isNonEmptyObject,\n isObjectLiteralAndNotNull,\n removeUndefinedValues,\n removeUndefinedAndNullValues,\n getObjectValues,\n};\n","import type { Nullable } from '../types/Nullable';\nimport { isNullOrUndefined, isString } from './checks';\n\n// TODO: see if bundle size is bumped up if we use ramda trim instead of custom\nconst trim = (value: string): string => value.replace(/^\\s+|\\s+$/gm, '');\n\nconst removeDoubleSpaces = (value: string): string => value.replace(/ {2,}/g, ' ');\n\nconst removeLeadingPeriod = (value: string): string => value.replace(/^\\.+/, '');\n\n/**\n * A function to convert values to string\n * @param val input value\n * @returns stringified value\n */\nconst tryStringify = (val?: any): Nullable | undefined => {\n let retVal = val;\n if (!isString(val) && !isNullOrUndefined(val)) {\n try {\n retVal = JSON.stringify(val);\n } catch (e) {\n retVal = null;\n }\n }\n return retVal;\n};\n\n// The following text encoding and decoding is done before base64 encoding to prevent\n// https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem\n\n/**\n * Converts a base64 encoded string to bytes array\n * @param base64Str base64 encoded string\n * @returns bytes array\n */\nconst base64ToBytes = (base64Str: string): Uint8Array => {\n const binString = (globalThis as typeof window).atob(base64Str);\n const bytes = binString.split('').map(char => char.charCodeAt(0));\n return new Uint8Array(bytes);\n};\n\n/**\n * Converts a bytes array to base64 encoded string\n * @param bytes bytes array to be converted to base64\n * @returns base64 encoded string\n */\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n const binString = Array.from(bytes, x => String.fromCodePoint(x)).join('');\n return (globalThis as typeof window).btoa(binString);\n};\n\n/**\n * Encodes a string to base64 even with unicode characters\n * @param value input string\n * @returns base64 encoded string\n */\nconst toBase64 = (value: string): string => bytesToBase64(new TextEncoder().encode(value));\n\n/**\n * Decodes a base64 encoded string\n * @param value base64 encoded string\n * @returns decoded string\n */\nconst fromBase64 = (value: string): string => new TextDecoder().decode(base64ToBytes(value));\n\nexport { trim, removeDoubleSpaces, tryStringify, toBase64, fromBase64, removeLeadingPeriod };\n","import { clone } from 'ramda';\nimport type { ApiObject } from '../types/ApiObject';\nimport type { ApiCallback, ApiOptions } from '../types/EventApi';\nimport type { Nullable } from '../types/Nullable';\nimport { isObjectLiteralAndNotNull, mergeDeepRight } from './object';\nimport { isDefined, isDefinedAndNotNull, isFunction, isNull, isString } from './checks';\nimport { tryStringify } from './string';\nimport type { IdentifyTraits } from '../types/traits';\n\nexport type PageCallOptions = {\n category?: string;\n name?: string;\n properties?: Nullable;\n options?: Nullable;\n callback?: ApiCallback;\n};\n\nexport type TrackCallOptions = {\n name: string;\n properties?: Nullable;\n options?: Nullable;\n callback?: ApiCallback;\n};\n\nexport type IdentifyCallOptions = {\n userId?: Nullable;\n traits?: Nullable;\n options?: Nullable;\n callback?: ApiCallback;\n};\n\nexport type AliasCallOptions = {\n to: string;\n from?: string;\n options?: Nullable;\n callback?: ApiCallback;\n};\n\nexport type GroupCallOptions = {\n groupId?: Nullable;\n traits?: Nullable;\n options?: Nullable;\n callback?: ApiCallback;\n};\n\n// TODO: is there any specific reason why we set the overloaded values to null instead of undefined?\n// if yes make them null instead of omitting in overloaded cases\n\n/*\n * Normalise the overloaded arguments of the page call facade\n */\nconst pageArgumentsToCallOptions = (\n category?: string | Nullable | ApiCallback,\n name?: string | Nullable | Nullable | ApiCallback,\n properties?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n): PageCallOptions => {\n const payload: PageCallOptions = {\n category: category as string,\n name: name as string,\n properties: properties as Nullable,\n options: options as Nullable,\n callback: undefined,\n };\n\n if (isFunction(callback)) {\n payload.callback = callback;\n }\n\n if (isFunction(options)) {\n payload.category = category as string;\n payload.name = name as string;\n payload.properties = properties as Nullable;\n payload.options = undefined;\n payload.callback = options;\n }\n\n if (isFunction(properties)) {\n payload.category = category as string;\n payload.name = name as string;\n payload.properties = undefined;\n payload.options = undefined;\n payload.callback = properties;\n }\n\n if (isFunction(name)) {\n payload.category = category as string;\n payload.name = undefined;\n payload.properties = undefined;\n payload.options = undefined;\n payload.callback = name;\n }\n\n if (isFunction(category)) {\n payload.category = undefined;\n payload.name = undefined;\n payload.properties = undefined;\n payload.options = undefined;\n payload.callback = category;\n }\n\n if (isObjectLiteralAndNotNull(category)) {\n payload.name = undefined;\n payload.category = undefined;\n payload.properties = category as Nullable;\n if (!isFunction(name)) {\n payload.options = name as Nullable;\n } else {\n payload.options = undefined;\n }\n } else if (isObjectLiteralAndNotNull(name)) {\n payload.name = undefined;\n payload.properties = name as Nullable;\n if (!isFunction(properties)) {\n payload.options = properties as Nullable;\n } else {\n payload.options = undefined;\n }\n }\n\n // if the category argument alone is provided b/w category and name,\n // use it as name and set category to undefined\n if (isString(category) && !isString(name)) {\n payload.category = undefined;\n payload.name = category;\n }\n\n // Rest of the code is just to clean up undefined values\n // and set some proper defaults\n // Also, to clone the incoming object type arguments\n if (!isDefined(payload.category)) {\n payload.category = undefined;\n }\n\n if (!isDefined(payload.name)) {\n payload.name = undefined;\n }\n\n payload.properties = payload.properties ? clone(payload.properties) : {};\n\n if (isDefined(payload.options)) {\n payload.options = clone(payload.options);\n } else {\n payload.options = undefined;\n }\n\n const nameForProperties = isString(payload.name) ? payload.name : payload.properties.name;\n const categoryForProperties = isString(payload.category)\n ? payload.category\n : payload.properties.category;\n\n // add name and category to properties\n payload.properties = mergeDeepRight(\n isObjectLiteralAndNotNull(payload.properties) ? payload.properties : {},\n {\n ...(nameForProperties && { name: nameForProperties }),\n ...(categoryForProperties && { category: categoryForProperties }),\n },\n );\n\n return payload;\n};\n\n/*\n * Normalise the overloaded arguments of the track call facade\n */\nconst trackArgumentsToCallOptions = (\n event: string,\n properties?: Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n): TrackCallOptions => {\n const payload: TrackCallOptions = {\n name: event,\n properties: properties as Nullable,\n options: options as Nullable,\n callback: undefined,\n };\n\n if (isFunction(callback)) {\n payload.callback = callback;\n }\n\n if (isFunction(options)) {\n payload.properties = properties as Nullable;\n payload.options = undefined;\n payload.callback = options;\n }\n\n if (isFunction(properties)) {\n payload.properties = undefined;\n payload.options = undefined;\n payload.callback = properties;\n }\n\n // Rest of the code is just to clean up undefined values\n // and set some proper defaults\n // Also, to clone the incoming object type arguments\n payload.properties = isDefinedAndNotNull(payload.properties) ? clone(payload.properties) : {};\n\n if (isDefined(payload.options)) {\n payload.options = clone(payload.options);\n } else {\n payload.options = undefined;\n }\n\n return payload;\n};\n\n/*\n * Normalise the overloaded arguments of the identify call facade\n */\nconst identifyArgumentsToCallOptions = (\n userId: string | number | Nullable,\n traits?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n): IdentifyCallOptions => {\n const payload: IdentifyCallOptions = {\n userId: userId as string,\n traits: traits as Nullable,\n options: options as Nullable,\n callback: undefined,\n };\n\n if (isFunction(callback)) {\n payload.callback = callback;\n }\n\n if (isFunction(options)) {\n payload.userId = userId as string;\n payload.traits = traits as Nullable;\n payload.options = undefined;\n payload.callback = options;\n }\n\n if (isFunction(traits)) {\n payload.userId = userId as string;\n payload.traits = undefined;\n payload.options = undefined;\n payload.callback = traits;\n }\n\n if (isObjectLiteralAndNotNull(userId) || isNull(userId)) {\n // Explicitly set null to prevent resetting the existing value\n // in the Analytics class\n payload.userId = null;\n payload.traits = userId as Nullable;\n if (!isFunction(traits)) {\n payload.options = traits as Nullable;\n } else {\n payload.options = undefined;\n }\n }\n\n // Rest of the code is just to clean up undefined values\n // and set some proper defaults\n // Also, to clone the incoming object type arguments\n payload.userId = tryStringify(payload.userId);\n\n if (isObjectLiteralAndNotNull(payload.traits)) {\n payload.traits = clone(payload.traits);\n } else {\n payload.traits = undefined;\n }\n\n if (isDefined(payload.options)) {\n payload.options = clone(payload.options);\n } else {\n payload.options = undefined;\n }\n\n return payload;\n};\n\n/*\n * Normalise the overloaded arguments of the alias call facade\n */\nconst aliasArgumentsToCallOptions = (\n to: string,\n from?: string | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n): AliasCallOptions => {\n const payload: AliasCallOptions = {\n to,\n from: from as string,\n options: options as Nullable,\n callback: undefined,\n };\n\n if (isFunction(callback)) {\n payload.callback = callback;\n }\n\n if (isFunction(options)) {\n payload.to = to;\n payload.from = from as string;\n payload.options = undefined;\n payload.callback = options;\n }\n\n if (isFunction(from)) {\n payload.to = to;\n payload.from = undefined;\n payload.options = undefined;\n payload.callback = from;\n } else if (isObjectLiteralAndNotNull(from) || isNull(from)) {\n payload.to = to;\n payload.from = undefined;\n payload.options = from as Nullable;\n }\n\n // Rest of the code is just to clean up undefined values\n // and set some proper defaults\n // Also, to clone the incoming object type arguments\n if (isDefined(payload.to)) {\n payload.to = tryStringify(payload.to) as typeof payload.to;\n }\n\n if (isDefined(payload.from)) {\n payload.from = tryStringify(payload.from) as typeof payload.from;\n } else {\n payload.from = undefined;\n }\n\n if (isDefined(payload.options)) {\n payload.options = clone(payload.options);\n } else {\n payload.options = undefined;\n }\n\n return payload;\n};\n\n/*\n * Normalise the overloaded arguments of the group call facade\n */\nconst groupArgumentsToCallOptions = (\n groupId: string | number | Nullable,\n traits?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n): GroupCallOptions => {\n const payload: GroupCallOptions = {\n groupId: groupId as string,\n traits: traits as Nullable,\n options: options as Nullable,\n callback: undefined,\n };\n\n if (isFunction(callback)) {\n payload.callback = callback;\n }\n\n if (isFunction(options)) {\n payload.groupId = groupId as string;\n payload.traits = traits as Nullable;\n payload.options = undefined;\n payload.callback = options;\n }\n\n if (isFunction(traits)) {\n payload.groupId = groupId as string;\n payload.traits = undefined;\n payload.options = undefined;\n payload.callback = traits;\n }\n\n if (isObjectLiteralAndNotNull(groupId) || isNull(groupId)) {\n // Explicitly set null to prevent resetting the existing value\n // in the Analytics class\n payload.groupId = null;\n payload.traits = groupId as Nullable;\n if (!isFunction(traits)) {\n payload.options = traits as Nullable;\n } else {\n payload.options = undefined;\n }\n }\n\n // Rest of the code is just to clean up undefined values\n // and set some proper defaults\n // Also, to clone the incoming object type arguments\n payload.groupId = tryStringify(payload.groupId);\n\n if (isObjectLiteralAndNotNull(payload.traits)) {\n payload.traits = clone(payload.traits);\n } else {\n payload.traits = undefined;\n }\n\n if (isDefined(payload.options)) {\n payload.options = clone(payload.options);\n } else {\n payload.options = undefined;\n }\n\n return payload;\n};\n\nexport {\n pageArgumentsToCallOptions,\n trackArgumentsToCallOptions,\n identifyArgumentsToCallOptions,\n aliasArgumentsToCallOptions,\n groupArgumentsToCallOptions,\n};\n","const CAPABILITIES_MANAGER = 'CapabilitiesManager';\nconst CONFIG_MANAGER = 'ConfigManager';\nconst EVENT_MANAGER = 'EventManager';\nconst PLUGINS_MANAGER = 'PluginsManager';\nconst USER_SESSION_MANAGER = 'UserSessionManager';\nconst ERROR_HANDLER = 'ErrorHandler';\nconst PLUGIN_ENGINE = 'PluginEngine';\nconst STORE_MANAGER = 'StoreManager';\nconst READY_API = 'readyApi';\nconst LOAD_CONFIGURATION = 'LoadConfiguration';\nconst EVENT_REPOSITORY = 'EventRepository';\nconst EXTERNAL_SRC_LOADER = 'ExternalSrcLoader';\nconst HTTP_CLIENT = 'HttpClient';\nconst RS_APP = 'RudderStackApplication';\nconst ANALYTICS_CORE = 'AnalyticsCore';\n\nexport {\n CAPABILITIES_MANAGER,\n CONFIG_MANAGER,\n EVENT_MANAGER,\n PLUGINS_MANAGER,\n USER_SESSION_MANAGER,\n ERROR_HANDLER,\n PLUGIN_ENGINE,\n STORE_MANAGER,\n READY_API,\n LOAD_CONFIGURATION,\n EVENT_REPOSITORY,\n EXTERNAL_SRC_LOADER,\n HTTP_CLIENT,\n RS_APP,\n ANALYTICS_CORE,\n};\n","const APP_NAME = 'RudderLabs JavaScript SDK';\nconst APP_VERSION = '__PACKAGE_VERSION__';\nconst APP_NAMESPACE = 'com.rudderlabs.javascript';\nconst MODULE_TYPE = '__MODULE_TYPE__';\nconst IS_LEGACY_BUILD = __IS_LEGACY_BUILD__;\nconst ADBLOCK_PAGE_CATEGORY = 'RudderJS-Initiated';\nconst ADBLOCK_PAGE_NAME = 'ad-block page request';\nconst ADBLOCK_PAGE_PATH = '/ad-blocked';\nconst GLOBAL_PRELOAD_BUFFER = 'preloadedEventsBuffer';\n\nconst CONSENT_TRACK_EVENT_NAME = 'Consent Management Interaction';\n\nexport {\n APP_NAME,\n APP_VERSION,\n APP_NAMESPACE,\n MODULE_TYPE,\n IS_LEGACY_BUILD,\n ADBLOCK_PAGE_CATEGORY,\n ADBLOCK_PAGE_NAME,\n ADBLOCK_PAGE_PATH,\n GLOBAL_PRELOAD_BUFFER,\n CONSENT_TRACK_EVENT_NAME,\n};\n","const QUERY_PARAM_TRAIT_PREFIX = 'ajs_trait_';\nconst QUERY_PARAM_PROPERTY_PREFIX = 'ajs_prop_';\nconst QUERY_PARAM_ANONYMOUS_ID_KEY = 'ajs_aid';\nconst QUERY_PARAM_USER_ID_KEY = 'ajs_uid';\nconst QUERY_PARAM_TRACK_EVENT_NAME_KEY = 'ajs_event';\n\nexport {\n QUERY_PARAM_TRAIT_PREFIX,\n QUERY_PARAM_PROPERTY_PREFIX,\n QUERY_PARAM_ANONYMOUS_ID_KEY,\n QUERY_PARAM_USER_ID_KEY,\n QUERY_PARAM_TRACK_EVENT_NAME_KEY,\n};\n","const DEFAULT_REQ_TIMEOUT_MS = 10 * 1000; // 10 seconds\nconst DEFAULT_COOKIE_MAX_AGE_MS = 31536000 * 1000; // 1 year\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst MIN_SESSION_TIMEOUT_MS = 10 * 1000; // 10 seconds\nconst DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS = 10 * 1000; // 10 seconds\nconst DEBOUNCED_TIMEOUT_MS = 250; // 250 milliseconds\n\nexport {\n DEFAULT_REQ_TIMEOUT_MS,\n DEFAULT_COOKIE_MAX_AGE_MS,\n DEFAULT_SESSION_TIMEOUT_MS,\n MIN_SESSION_TIMEOUT_MS,\n DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,\n DEBOUNCED_TIMEOUT_MS,\n};\n","import type { DebouncedFunction } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport { DEBOUNCED_TIMEOUT_MS } from '../../constants/timeouts';\nimport type { ExposedGlobals, IRudderStackGlobals } from '../../app/IRudderStackGlobals';\n\n/**\n * Create globally accessible RudderStackGlobals object\n */\nconst createExposedGlobals = (analyticsInstanceId = 'app') => {\n if (!(globalThis as typeof window).RudderStackGlobals) {\n (globalThis as typeof window).RudderStackGlobals = {} as IRudderStackGlobals;\n }\n\n if (!(globalThis as typeof window).RudderStackGlobals[analyticsInstanceId]) {\n (globalThis as typeof window).RudderStackGlobals[analyticsInstanceId] =\n {} as IRudderStackGlobals;\n }\n};\n\n/**\n * Add move values to globally accessible RudderStackGlobals object per analytics instance\n */\nconst setExposedGlobal = (keyName: string, value?: any, analyticsInstanceId = 'app') => {\n createExposedGlobals(analyticsInstanceId);\n ((globalThis as typeof window).RudderStackGlobals[analyticsInstanceId] as ExposedGlobals)[\n keyName\n ] = value;\n};\n\n/**\n * Get values from globally accessible RudderStackGlobals object by analytics instance\n */\nconst getExposedGlobal = (\n keyName: string,\n analyticsInstanceId = 'app',\n): Partial => {\n createExposedGlobals(analyticsInstanceId);\n return ((globalThis as typeof window).RudderStackGlobals[analyticsInstanceId] as ExposedGlobals)[\n keyName\n ];\n};\n\nfunction debounce(\n func: DebouncedFunction,\n thisArg: any,\n delay: number = DEBOUNCED_TIMEOUT_MS,\n): DebouncedFunction {\n let timeoutId: number;\n\n return (...args: any[]) => {\n (globalThis as typeof window).clearTimeout(timeoutId);\n\n timeoutId = (globalThis as typeof window).setTimeout(() => {\n func.apply(thisArg, args);\n }, delay);\n };\n}\n\nexport { createExposedGlobals, setExposedGlobal, getExposedGlobal, debounce };\n","import { isFunction } from '@rudderstack/analytics-js-common/utilities/checks';\nimport {\n aliasArgumentsToCallOptions,\n groupArgumentsToCallOptions,\n identifyArgumentsToCallOptions,\n pageArgumentsToCallOptions,\n trackArgumentsToCallOptions,\n} from '@rudderstack/analytics-js-common/utilities/eventMethodOverloads';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { clone } from 'ramda';\nimport type { PreloadedEventCall } from './types';\nimport {\n QUERY_PARAM_ANONYMOUS_ID_KEY,\n QUERY_PARAM_PROPERTY_PREFIX,\n QUERY_PARAM_TRACK_EVENT_NAME_KEY,\n QUERY_PARAM_TRAIT_PREFIX,\n QUERY_PARAM_USER_ID_KEY,\n} from '../../constants/queryParams';\nimport type { IAnalytics } from '../core/IAnalytics';\nimport { getExposedGlobal, setExposedGlobal } from '../utilities/globals';\nimport { GLOBAL_PRELOAD_BUFFER } from '../../constants/app';\n\n/**\n * Parse query string params into object values for keys that start with a defined prefix\n */\nconst getEventDataFromQueryString = (\n params: URLSearchParams,\n dataTypeNamePrefix: string,\n): Record> => {\n const data: Record> = {};\n\n params.forEach((value, key) => {\n if (key.startsWith(dataTypeNamePrefix)) {\n // remove prefix from key name\n const dataKey = key.substring(dataTypeNamePrefix.length);\n // add new key value pair in generated object\n data[dataKey] = params.get(key);\n }\n });\n\n return data;\n};\n\n/**\n * Parse query string into preload buffer events & push into existing array before any other events\n */\nconst retrieveEventsFromQueryString = (argumentsArray: PreloadedEventCall[] = []) => {\n // Mapping for trait and properties values based on key prefix\n const eventArgumentToQueryParamMap = {\n trait: QUERY_PARAM_TRAIT_PREFIX,\n properties: QUERY_PARAM_PROPERTY_PREFIX,\n };\n\n const queryObject = new URLSearchParams(globalThis.location.search);\n\n // Add track events with name and properties\n if (queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY)) {\n argumentsArray.unshift([\n 'track',\n queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY),\n getEventDataFromQueryString(queryObject, eventArgumentToQueryParamMap.properties),\n ]);\n }\n\n // Set userId and user traits\n if (queryObject.get(QUERY_PARAM_USER_ID_KEY)) {\n argumentsArray.unshift([\n 'identify',\n queryObject.get(QUERY_PARAM_USER_ID_KEY),\n getEventDataFromQueryString(queryObject, eventArgumentToQueryParamMap.trait),\n ]);\n }\n\n // Set anonymousID\n if (queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)) {\n argumentsArray.unshift(['setAnonymousId', queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)]);\n }\n};\n\n/**\n * Retrieve an existing buffered load method call and remove from the existing array\n */\nconst getPreloadedLoadEvent = (preloadedEventsArray: PreloadedEventCall[]): PreloadedEventCall => {\n const loadMethodName = 'load';\n let loadEvent: PreloadedEventCall = [];\n\n /**\n * Iterate the buffered API calls until we find load call and process it separately\n */\n let i = 0;\n while (i < preloadedEventsArray.length) {\n if (\n preloadedEventsArray[i] &&\n (preloadedEventsArray[i] as PreloadedEventCall)[0] === loadMethodName\n ) {\n loadEvent = clone(preloadedEventsArray[i] as PreloadedEventCall);\n preloadedEventsArray.splice(i, 1);\n break;\n }\n i += 1;\n }\n\n return loadEvent;\n};\n\n/**\n * Promote consent events to the top of the preloaded events array\n * @param preloadedEventsArray Preloaded events array\n * @returns None\n */\nconst promotePreloadedConsentEventsToTop = (preloadedEventsArray: PreloadedEventCall[]): void => {\n const consentMethodName = 'consent';\n const consentEvents = preloadedEventsArray.filter(\n bufferedEvent => bufferedEvent[0] === consentMethodName,\n );\n\n const nonConsentEvents = preloadedEventsArray.filter(\n bufferedEvent => bufferedEvent[0] !== consentMethodName,\n );\n\n // Remove all elements and add consent events first followed by non consent events\n // eslint-disable-next-line unicorn/no-useless-spread\n preloadedEventsArray.splice(\n 0,\n preloadedEventsArray.length,\n ...consentEvents,\n ...nonConsentEvents,\n );\n};\n\n/**\n * Retrieve any existing events that were triggered before SDK load and enqueue in buffer\n */\nconst retrievePreloadBufferEvents = (instance: IAnalytics) => {\n const preloadedEventsArray = (getExposedGlobal(GLOBAL_PRELOAD_BUFFER) ||\n []) as PreloadedEventCall[];\n\n // Get events that are pre-populated via query string params\n retrieveEventsFromQueryString(preloadedEventsArray);\n\n // Enqueue the non load events in the buffer of the global rudder analytics singleton\n if (preloadedEventsArray.length > 0) {\n instance.enqueuePreloadBufferEvents(preloadedEventsArray);\n setExposedGlobal(GLOBAL_PRELOAD_BUFFER, []);\n }\n};\n\nconst consumePreloadBufferedEvent = (event: any, analyticsInstance: IAnalytics) => {\n const methodName = event.shift();\n let callOptions;\n\n if (isFunction((analyticsInstance as any)[methodName])) {\n switch (methodName) {\n case 'page':\n callOptions = pageArgumentsToCallOptions(...(event as [any]));\n break;\n case 'track':\n callOptions = trackArgumentsToCallOptions(...(event as [any]));\n break;\n case 'identify':\n callOptions = identifyArgumentsToCallOptions(...(event as [any]));\n break;\n case 'alias':\n callOptions = aliasArgumentsToCallOptions(...(event as [any]));\n break;\n case 'group':\n callOptions = groupArgumentsToCallOptions(...(event as [any]));\n break;\n default:\n (analyticsInstance as any)[methodName](...event);\n break;\n }\n\n if (callOptions) {\n (analyticsInstance as any)[methodName](callOptions);\n }\n }\n};\n\nexport {\n getEventDataFromQueryString,\n retrieveEventsFromQueryString,\n getPreloadedLoadEvent,\n retrievePreloadBufferEvents,\n consumePreloadBufferedEvent,\n promotePreloadedConsentEventsToTop,\n};\n","const LOG_CONTEXT_SEPARATOR = ':: ';\n\nconst SCRIPT_ALREADY_EXISTS_ERROR = (id: string): string =>\n `A script with the id \"${id}\" is already loaded. Skipping the loading of this script to prevent conflicts.`;\n\nconst SCRIPT_LOAD_ERROR = (id: string, url: string): string =>\n `Failed to load the script with the id \"${id}\" from URL \"${url}\".`;\n\nconst SCRIPT_LOAD_TIMEOUT_ERROR = (id: string, url: string, timeout: number): string =>\n `A timeout of ${timeout} ms occurred while trying to load the script with id \"${id}\" from URL \"${url}\".`;\n\nconst CIRCULAR_REFERENCE_WARNING = (context: string, key: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}A circular reference has been detected in the object and the property \"${key}\" has been dropped from the output.`;\n\nconst JSON_STRINGIFY_WARNING = `Failed to convert the value to a JSON string.`;\n\nexport {\n LOG_CONTEXT_SEPARATOR,\n SCRIPT_ALREADY_EXISTS_ERROR,\n SCRIPT_LOAD_ERROR,\n SCRIPT_LOAD_TIMEOUT_ERROR,\n CIRCULAR_REFERENCE_WARNING,\n JSON_STRINGIFY_WARNING,\n};\n","import type { ILogger } from '../types/Logger';\nimport type { Nullable } from '../types/Nullable';\nimport { isNull, isNullOrUndefined } from './checks';\nimport { CIRCULAR_REFERENCE_WARNING, JSON_STRINGIFY_WARNING } from '../constants/logMessages';\n\nconst JSON_STRINGIFY = 'JSONStringify';\n\nconst getCircularReplacer = (\n excludeNull?: boolean,\n excludeKeys?: string[],\n logger?: ILogger,\n): ((key: string, value: any) => any) => {\n const ancestors: any[] = [];\n\n // Here we do not want to use arrow function to use \"this\" in function context\n // eslint-disable-next-line func-names\n return function (key, value): any {\n if (excludeKeys?.includes(key)) {\n return undefined;\n }\n\n if (excludeNull && isNullOrUndefined(value)) {\n return undefined;\n }\n\n if (typeof value !== 'object' || isNull(value)) {\n return value;\n }\n\n // `this` is the object that value is contained in, i.e., its direct parent.\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore-next-line\n while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) {\n ancestors.pop();\n }\n\n if (ancestors.includes(value)) {\n logger?.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY, key));\n return '[Circular Reference]';\n }\n\n ancestors.push(value);\n return value;\n };\n};\n\n/**\n * Utility method for JSON stringify object excluding null values & circular references\n *\n * @param {*} value input\n * @param {boolean} excludeNull if it should exclude nul or not\n * @param {function} logger optional logger methods for warning\n * @returns string\n */\nconst stringifyWithoutCircular = | any[] | number | string>(\n value?: Nullable,\n excludeNull?: boolean,\n excludeKeys?: string[],\n logger?: ILogger,\n): Nullable => {\n try {\n return JSON.stringify(value, getCircularReplacer(excludeNull, excludeKeys, logger));\n } catch (err) {\n logger?.warn(JSON_STRINGIFY_WARNING, err);\n return null;\n }\n};\n\nexport { stringifyWithoutCircular };\n","import { isTypeOfError } from './checks';\nimport { stringifyWithoutCircular } from './json';\n\n/**\n * Get mutated error with issue prepended to error message\n * @param err Original error\n * @param issue Issue to prepend to error message\n * @returns Instance of Error with message prepended with issue\n */\nconst getMutatedError = (err: any, issue: string): Error => {\n let finalError = err;\n if (!isTypeOfError(err)) {\n finalError = new Error(`${issue}: ${stringifyWithoutCircular(err as Record)}`);\n } else {\n (finalError as Error).message = `${issue}: ${err.message}`;\n }\n return finalError;\n};\n\nexport { getMutatedError };\n","import { getMutatedError } from '../../utilities/errors';\nimport { EXTERNAL_SOURCE_LOAD_ORIGIN } from '../../constants/htmlAttributes';\nimport {\n SCRIPT_ALREADY_EXISTS_ERROR,\n SCRIPT_LOAD_ERROR,\n SCRIPT_LOAD_TIMEOUT_ERROR,\n} from '../../constants/logMessages';\n\n/**\n * Create the DOM element to load a script marked as RS SDK originated\n *\n * @param {*} url The URL of the script to be loaded\n * @param {*} id ID for the script tag\n * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]\n * @param {*} onload callback to invoke onload [optional]\n * @param {*} onerror callback to invoke onerror [optional]\n * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]\n *\n * @returns HTMLScriptElement\n */\nconst createScriptElement = (\n url: string,\n id: string,\n async = true,\n onload: ((this: GlobalEventHandlers, ev: Event) => any) | null = null,\n onerror: OnErrorEventHandler = null,\n extraAttributes: Record = {},\n) => {\n const scriptElement = document.createElement('script');\n scriptElement.type = 'text/javascript';\n scriptElement.onload = onload;\n scriptElement.onerror = onerror;\n scriptElement.src = url;\n scriptElement.id = id;\n scriptElement.async = async;\n\n Object.keys(extraAttributes).forEach(attributeName => {\n scriptElement.setAttribute(attributeName, extraAttributes[attributeName] as string);\n });\n\n scriptElement.setAttribute('data-loader', EXTERNAL_SOURCE_LOAD_ORIGIN);\n\n return scriptElement;\n};\n\n/**\n * Add script DOM element to DOM\n *\n * @param {*} newScriptElement the script element to add\n *\n * @returns\n */\nconst insertScript = (newScriptElement: HTMLScriptElement) => {\n // First try to add it to the head\n const headElements = document.getElementsByTagName('head');\n if (headElements.length > 0) {\n headElements[0]?.insertBefore(newScriptElement, headElements[0]?.firstChild);\n return;\n }\n\n // Else wise add it before the first script tag\n const scriptElements = document.getElementsByTagName('script');\n if (scriptElements.length > 0 && scriptElements[0]?.parentNode) {\n scriptElements[0]?.parentNode.insertBefore(newScriptElement, scriptElements[0]);\n return;\n }\n\n // Create a new head element and add the script as fallback\n const headElement = document.createElement('head');\n headElement.appendChild(newScriptElement);\n\n const htmlElement = document.getElementsByTagName('html')[0];\n htmlElement?.insertBefore(headElement, htmlElement.firstChild);\n};\n\n/**\n * Loads external js file as a script html tag\n *\n * @param {*} url The URL of the script to be loaded\n * @param {*} id ID for the script tag\n * @param {*} timeout loading timeout\n * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]\n * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]\n *\n * @returns\n */\nconst jsFileLoader = (\n url: string,\n id: string,\n timeout: number,\n async = true,\n extraAttributes?: Record,\n): Promise =>\n new Promise((resolve, reject) => {\n const scriptExists = document.getElementById(id);\n if (scriptExists) {\n reject(new Error(SCRIPT_ALREADY_EXISTS_ERROR(id)));\n }\n\n try {\n let timeoutID: number;\n\n const onload = () => {\n (globalThis as typeof window).clearTimeout(timeoutID);\n resolve(id);\n };\n\n const onerror = () => {\n (globalThis as typeof window).clearTimeout(timeoutID);\n reject(new Error(SCRIPT_LOAD_ERROR(id, url)));\n };\n\n // Create the DOM element to load the script and add it to the DOM\n insertScript(createScriptElement(url, id, async, onload, onerror, extraAttributes));\n\n // Reject on timeout\n timeoutID = (globalThis as typeof window).setTimeout(() => {\n reject(new Error(SCRIPT_LOAD_TIMEOUT_ERROR(id, url, timeout)));\n }, timeout);\n } catch (err) {\n reject(getMutatedError(err, SCRIPT_LOAD_ERROR(id, url)));\n }\n });\n\nexport { jsFileLoader, insertScript, createScriptElement };\n","const EXTERNAL_SOURCE_LOAD_ORIGIN = 'RS_JS_SDK';\n\nexport { EXTERNAL_SOURCE_LOAD_ORIGIN };\n","import { EXTERNAL_SRC_LOADER } from '../../constants/loggerContexts';\nimport { DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS } from '../../constants/timeouts';\nimport { isFunction } from '../../utilities/checks';\nimport type { IErrorHandler } from '../../types/ErrorHandler';\nimport type { ILogger } from '../../types/Logger';\nimport type { IExternalSourceLoadConfig, IExternalSrcLoader } from './types';\nimport { jsFileLoader } from './jsFileLoader';\n\n/**\n * Service to load external resources/files\n */\nclass ExternalSrcLoader implements IExternalSrcLoader {\n errorHandler?: IErrorHandler;\n logger?: ILogger;\n hasErrorHandler = false;\n timeout: number;\n\n constructor(\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n timeout = DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS,\n ) {\n this.errorHandler = errorHandler;\n this.logger = logger;\n this.timeout = timeout;\n this.hasErrorHandler = Boolean(this.errorHandler);\n this.onError = this.onError.bind(this);\n }\n\n /**\n * Load external resource of type javascript\n */\n loadJSFile(config: IExternalSourceLoadConfig) {\n const { url, id, timeout, async, callback, extraAttributes } = config;\n const isFireAndForget = !isFunction(callback);\n\n jsFileLoader(url, id, timeout || this.timeout, async, extraAttributes)\n .then((id?: string) => {\n if (!isFireAndForget) {\n callback(id);\n }\n })\n .catch(err => {\n this.onError(err);\n if (!isFireAndForget) {\n callback();\n }\n });\n }\n\n /**\n * Handle errors\n */\n onError(error: unknown) {\n if (this.hasErrorHandler) {\n this.errorHandler?.onError(error, EXTERNAL_SRC_LOADER);\n } else {\n throw error;\n }\n }\n}\n\nexport { ExternalSrcLoader };\n","const DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS = 10 * 1000; // 10 seconds\n\nexport { DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS };\n","var i=Symbol.for(\"preact-signals\");function t(){if(!(s>1)){var i,t=!1;while(void 0!==h){var r=h;h=void 0;f++;while(void 0!==r){var o=r.o;r.o=void 0;r.f&=-3;if(!(8&r.f)&&c(r))try{r.c()}catch(r){if(!t){i=r;t=!0}}r=o}}f=0;s--;if(t)throw i}else s--}function r(i){if(s>0)return i();s++;try{return i()}finally{t()}}var o=void 0;function n(i){var t=o;o=void 0;try{return i()}finally{o=t}}var h=void 0,s=0,f=0,v=0;function e(i){if(void 0!==o){var t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t}return t}}}function u(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0}u.prototype.brand=i;u.prototype.h=function(){return!0};u.prototype.S=function(i){if(this.t!==i&&void 0===i.e){i.x=this.t;if(void 0!==this.t)this.t.e=i;this.t=i}};u.prototype.U=function(i){if(void 0!==this.t){var t=i.e,r=i.x;if(void 0!==t){t.x=r;i.e=void 0}if(void 0!==r){r.e=t;i.x=void 0}if(i===this.t)this.t=r}};u.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=o;o=void 0;try{i(r)}finally{o=n}})};u.prototype.valueOf=function(){return this.value};u.prototype.toString=function(){return this.value+\"\"};u.prototype.toJSON=function(){return this.value};u.prototype.peek=function(){var i=o;o=void 0;try{return this.value}finally{o=i}};Object.defineProperty(u.prototype,\"value\",{get:function(){var i=e(this);if(void 0!==i)i.i=this.i;return this.v},set:function(i){if(i!==this.v){if(f>100)throw new Error(\"Cycle detected\");this.v=i;this.i++;v++;s++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N()}finally{t()}}}});function d(i){return new u(i)}function c(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function a(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break}}}function l(i){var t=i.s,r=void 0;while(void 0!==t){var o=t.p;if(-1===t.i){t.S.U(t);if(void 0!==o)o.n=t.n;if(void 0!==t.n)t.n.p=o}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=o}i.s=r}function y(i){u.call(this,void 0);this.x=i;this.s=void 0;this.g=v-1;this.f=4}(y.prototype=new u).h=function(){this.f&=-3;if(1&this.f)return!1;if(32==(36&this.f))return!0;this.f&=-5;if(this.g===v)return!0;this.g=v;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return!0}var i=o;try{a(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++}}catch(i){this.v=i;this.f|=16;this.i++}o=i;l(this);this.f&=-2;return!0};y.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}u.prototype.S.call(this,i)};y.prototype.U=function(i){if(void 0!==this.t){u.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}}};y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N()}};Object.defineProperty(y.prototype,\"value\",{get:function(){if(1&this.f)throw new Error(\"Cycle detected\");var i=e(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v}});function w(i){return new y(i)}function _(i){var r=i.u;i.u=void 0;if(\"function\"==typeof r){s++;var n=o;o=void 0;try{r()}catch(t){i.f&=-2;i.f|=8;g(i);throw t}finally{o=n;t()}}}function g(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;_(i)}function p(i){if(o!==this)throw new Error(\"Out-of-order effect\");l(this);o=i;this.f&=-2;if(8&this.f)g(this);t()}function b(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32}b.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if(\"function\"==typeof t)this.u=t}finally{i()}};b.prototype.S=function(){if(1&this.f)throw new Error(\"Cycle detected\");this.f|=1;this.f&=-9;_(this);a(this);s++;var i=o;o=this;return p.bind(this,i)};b.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=h;h=this}};b.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this)};function E(i){var t=new b(i);try{t.c()}catch(i){t.d();throw i}return t.d.bind(t)}export{u as Signal,r as batch,w as computed,E as effect,d as signal,n as untracked};//# sourceMappingURL=signals-core.module.js.map\n","import type { Nullable } from '../../types/Nullable';\n\n/**\n * A buffer queue to serve as a store for any type of data\n */\nclass BufferQueue {\n items: T[];\n\n constructor() {\n this.items = [];\n }\n\n enqueue(item: T) {\n this.items.push(item);\n }\n\n dequeue(): Nullable | undefined {\n if (this.items.length === 0) {\n return null;\n }\n return this.items.shift();\n }\n\n isEmpty(): boolean {\n return this.items.length === 0;\n }\n\n size(): number {\n return this.items.length;\n }\n\n clear() {\n this.items = [];\n }\n}\n\nexport { BufferQueue };\n","import { isString, isUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { ILogger, LogLevel } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { LoggerProvider } from './types';\n\nconst LOG_LEVEL_MAP: Record = {\n LOG: 0,\n INFO: 1,\n DEBUG: 2,\n WARN: 3,\n ERROR: 4,\n NONE: 5,\n};\n\nconst DEFAULT_LOG_LEVEL = 'ERROR';\nconst LOG_MSG_PREFIX = 'RS SDK';\nconst LOG_MSG_PREFIX_STYLE = 'font-weight: bold; background: black; color: white;';\nconst LOG_MSG_STYLE = 'font-weight: normal;';\n\n/**\n * Service to log messages/data to output provider, default is console\n */\nclass Logger implements ILogger {\n minLogLevel: number;\n scope?: string;\n logProvider: LoggerProvider;\n\n constructor(minLogLevel: LogLevel = DEFAULT_LOG_LEVEL, scope = '', logProvider = console) {\n this.minLogLevel = LOG_LEVEL_MAP[minLogLevel];\n this.scope = scope;\n this.logProvider = logProvider;\n }\n\n log(...data: any[]) {\n this.outputLog('LOG', data);\n }\n\n info(...data: any[]) {\n this.outputLog('INFO', data);\n }\n\n debug(...data: any[]) {\n this.outputLog('DEBUG', data);\n }\n\n warn(...data: any[]) {\n this.outputLog('WARN', data);\n }\n\n error(...data: any[]) {\n this.outputLog('ERROR', data);\n }\n\n outputLog(logMethod: LogLevel, data: any[]) {\n if (this.minLogLevel <= LOG_LEVEL_MAP[logMethod]) {\n this.logProvider[\n logMethod.toLowerCase() as Exclude, Lowercase<'NONE'>>\n ]?.(...this.formatLogData(data));\n }\n }\n\n setScope(scopeVal: string) {\n this.scope = scopeVal || this.scope;\n }\n\n // TODO: should we allow to change the level via global variable on run time\n // to assist on the fly debugging?\n setMinLogLevel(logLevel: LogLevel) {\n this.minLogLevel = LOG_LEVEL_MAP[logLevel];\n if (isUndefined(this.minLogLevel)) {\n this.minLogLevel = LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];\n }\n }\n\n /**\n * Formats the console message using `scope` and styles\n */\n formatLogData(data: any[]) {\n if (Array.isArray(data) && data.length > 0) {\n // prefix SDK identifier\n let msg = `%c ${LOG_MSG_PREFIX}`;\n\n // format the log message using `scope`\n if (this.scope) {\n msg = `${msg} - ${this.scope}`;\n }\n\n // trim whitespaces for original message\n const originalMsg = isString(data[0]) ? data[0].trim() : '';\n\n // prepare the final message\n msg = `${msg} %c ${originalMsg}`;\n\n const styledLogArgs = [\n msg,\n LOG_MSG_PREFIX_STYLE, // add style for the prefix\n LOG_MSG_STYLE, // reset the style for the actual message\n ];\n\n // add first it if it was not a string msg\n if (!isString(data[0])) {\n styledLogArgs.push(data[0]);\n }\n\n // append rest of the original arguments\n styledLogArgs.push(...data.slice(1));\n return styledLogArgs;\n }\n\n return data;\n }\n}\n\nconst defaultLogger = new Logger();\n\nexport {\n Logger,\n DEFAULT_LOG_LEVEL,\n LOG_LEVEL_MAP,\n LOG_MSG_PREFIX,\n LOG_MSG_PREFIX_STYLE,\n LOG_MSG_STYLE,\n defaultLogger,\n};\n","import type { IPluginEngine } from './PluginEngine';\nimport type { ILogger } from './Logger';\nimport type { BufferQueue } from '../services/BufferQueue/BufferQueue';\nimport type { IHttpClient } from './HttpClient';\nimport type { IExternalSrcLoader } from '../services/ExternalSrcLoader/types';\n\nexport type SDKError = unknown | Error | ErrorEvent | Event | PromiseRejectionEvent;\n\nexport interface IErrorHandler {\n logger?: ILogger;\n pluginEngine?: IPluginEngine;\n errorBuffer: BufferQueue;\n init(httpClient: IHttpClient, externalSrcLoader: IExternalSrcLoader): void;\n onError(\n error: SDKError,\n context?: string,\n customMessage?: string,\n shouldAlwaysThrow?: boolean,\n errorType?: string,\n ): void;\n leaveBreadcrumb(breadcrumb: string): void;\n notifyError(error: Error, errorState: ErrorState): void;\n attachErrorListeners(): void;\n}\n\nexport type ErrorState = {\n severity: string;\n unhandled: boolean;\n severityReason: { type: string };\n};\n\nexport interface ErrorTarget extends Element {\n dataset?: { loader?: string; isnonnativesdk?: string };\n src?: string;\n}\n\nexport type PreLoadErrorData = {\n error: SDKError;\n errorState: ErrorState;\n};\n\nexport enum ErrorType {\n HANDLEDEXCEPTION = 'handledException',\n UNHANDLEDEXCEPTION = 'unhandledException',\n UNHANDLEDREJECTION = 'unhandledPromiseRejection',\n}\n","import type { UserSessionKey } from './UserSessionStorage';\n\nexport type StorageEncryptionVersion = 'legacy' | 'v3'; // default is v3\n\nexport type StorageType =\n | 'cookieStorage'\n | 'localStorage'\n | 'memoryStorage'\n | 'sessionStorage'\n | 'none';\n\nexport const SUPPORTED_STORAGE_TYPES = [\n 'localStorage',\n 'memoryStorage',\n 'cookieStorage',\n 'sessionStorage',\n 'none',\n];\n\nexport const DEFAULT_STORAGE_TYPE = 'cookieStorage';\n\nexport type StorageEncryption = {\n version: StorageEncryptionVersion;\n};\n\nexport type LoadOptionStorageEntry = {\n type: StorageType;\n};\n\nexport type StorageOpts = {\n encryption?: StorageEncryption;\n migrate?: boolean;\n type?: StorageType;\n cookie?: CookieOptions;\n entries?: {\n [key in UserSessionKey]?: LoadOptionStorageEntry;\n };\n};\n\nexport type CookieOptions = {\n maxage?: number;\n expires?: Date;\n path?: string;\n domain?: string;\n samesite?: string;\n secure?: boolean;\n};\n\nexport type CookieSameSite = 'Strict' | 'Lax' | 'None';\n","import type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport {\n type StorageType,\n SUPPORTED_STORAGE_TYPES,\n} from '@rudderstack/analytics-js-common/types/Storage';\nimport { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\nimport type {\n DeliveryType,\n StorageStrategy,\n} from '@rudderstack/analytics-js-common/types/LoadOptions';\n\n// CONSTANT\nconst SOURCE_CONFIG_OPTION_ERROR = `\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.`;\nconst DATA_PLANE_URL_ERROR = `Failed to load the SDK as the data plane URL could not be determined. Please check that the data plane URL is set correctly and try again.`;\nconst SOURCE_CONFIG_RESOLUTION_ERROR = `Unable to process/parse source configuration response.`;\nconst SOURCE_DISABLED_ERROR = `The source is disabled. Please enable the source in the dashboard to send events.`;\nconst PAYLOAD_PREP_ERROR = `Failed to prepare data for the request.`;\nconst EVENT_OBJECT_GENERATION_ERROR = `Failed to generate the event object.`;\nconst PLUGIN_EXT_POINT_MISSING_ERROR = `Failed to invoke plugin because the extension point name is missing.`;\nconst PLUGIN_EXT_POINT_INVALID_ERROR = `Failed to invoke plugin because the extension point name is invalid.`;\n\nconst COMPONENT_BASE_URL_ERROR = (component: string): string =>\n `Failed to load the SDK as the base URL for ${component} is not valid.`;\n\n// ERROR\nconst UNSUPPORTED_CONSENT_MANAGER_ERROR = (\n context: string,\n selectedConsentManager: string,\n consentManagersToPluginNameMap: Record,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The consent manager \"${selectedConsentManager}\" is not supported. Please choose one of the following supported consent managers: \"${Object.keys(\n consentManagersToPluginNameMap,\n )}\".`;\n\nconst REPORTING_PLUGIN_INIT_FAILURE_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to initialize the error reporting plugin.`;\n\nconst NOTIFY_FAILURE_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to notify the error.`;\n\nconst PLUGIN_NAME_MISSING_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Plugin name is missing.`;\n\nconst PLUGIN_ALREADY_EXISTS_ERROR = (context: string, pluginName: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Plugin \"${pluginName}\" already exists.`;\n\nconst PLUGIN_NOT_FOUND_ERROR = (context: string, pluginName: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Plugin \"${pluginName}\" not found.`;\n\nconst PLUGIN_ENGINE_BUG_ERROR = (context: string, pluginName: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Plugin \"${pluginName}\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.`;\n\nconst PLUGIN_DEPS_ERROR = (context: string, pluginName: string, notExistDeps: string[]): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Plugin \"${pluginName}\" could not be loaded because some of its dependencies \"${notExistDeps}\" do not exist.`;\n\nconst PLUGIN_INVOCATION_ERROR = (\n context: string,\n extPoint: string | undefined,\n pluginName: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to invoke the \"${extPoint}\" extension point of plugin \"${pluginName}\".`;\n\nconst STORAGE_UNAVAILABILITY_ERROR_PREFIX = (context: string, storageType: StorageType): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The \"${storageType}\" storage type is `;\n\nconst SOURCE_CONFIG_FETCH_ERROR = (reason: Error | undefined): string =>\n `Failed to fetch the source config. Reason: ${reason}`;\n\nconst WRITE_KEY_VALIDATION_ERROR = (writeKey?: string): string =>\n `The write key \"${writeKey}\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.`;\n\nconst DATA_PLANE_URL_VALIDATION_ERROR = (dataPlaneUrl: string | undefined): string =>\n `The data plane URL \"${dataPlaneUrl}\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.`;\n\nconst READY_API_CALLBACK_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The callback is not a function.`;\n\nconst DELIVERY_ERROR = (\n prefix: string,\n status: number,\n statusText: string,\n url: string | URL,\n e?: ProgressEvent | undefined,\n): string => `${prefix} with status ${status}: ${statusText} (${e?.type ?? ''}), for URL: ${url}.`;\n\nconst REQUEST_ERROR = (\n prefix: string,\n url: string | URL,\n timeout: number,\n e?: ProgressEvent | undefined,\n): string => `${prefix} due to timeout after ${timeout}ms or no connection (${e?.type ?? ''}) for URL: ${url}.`;\n\nconst XHR_SEND_ERROR = (prefix: string, url: string | URL): string => `${prefix} for URL: ${url}`;\n\nconst STORE_DATA_SAVE_ERROR = (key: string): string =>\n `Failed to save the value for \"${key}\" to storage`;\n\nconst STORE_DATA_FETCH_ERROR = (key: string): string =>\n `Failed to retrieve or parse data for \"${key}\" from storage`;\n\nconst DATA_SERVER_URL_INVALID_ERROR = (url: string) =>\n `The server side cookies functionality is disabled as the provided data server URL, \"${url}\" is invalid.`;\n\nconst DATA_SERVER_REQUEST_FAIL_ERROR = (status?: number) =>\n `The server responded with status ${status} while setting the cookies. As a fallback, the cookies will be set client side.`;\nconst FAILED_SETTING_COOKIE_FROM_SERVER_ERROR = (key: string) =>\n `The server failed to set the ${key} cookie. As a fallback, the cookies will be set client side.`;\nconst FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR = `Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.`;\n\n// WARNING\nconst STORAGE_TYPE_VALIDATION_WARNING = (\n context: string,\n storageType: any,\n defaultStorageType: StorageType,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The storage type \"${storageType}\" is not supported. Please choose one of the following supported types: \"${SUPPORTED_STORAGE_TYPES}\". The default type \"${defaultStorageType}\" will be used instead.`;\n\nconst UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING = (\n context: string,\n selectedErrorReportingProvider: string | undefined,\n errorReportingProvidersToPluginNameMap: Record,\n defaultProvider: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The error reporting provider \"${selectedErrorReportingProvider}\" is not supported. Please choose one of the following supported providers: \"${Object.keys(\n errorReportingProvidersToPluginNameMap,\n )}\". The default provider \"${defaultProvider}\" will be used instead.`;\n\nconst UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING = (\n context: string,\n selectedStorageEncryptionVersion: string | undefined,\n storageEncryptionVersionsToPluginNameMap: Record,\n defaultVersion: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The storage encryption version \"${selectedStorageEncryptionVersion}\" is not supported. Please choose one of the following supported versions: \"${Object.keys(\n storageEncryptionVersionsToPluginNameMap,\n )}\". The default version \"${defaultVersion}\" will be used instead.`;\n\nconst STORAGE_DATA_MIGRATION_OVERRIDE_WARNING = (\n context: string,\n storageEncryptionVersion: string | undefined,\n defaultVersion: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The storage data migration has been disabled because the configured storage encryption version (${storageEncryptionVersion}) is not the latest (${defaultVersion}). To enable storage data migration, please update the storage encryption version to the latest version.`;\n\nconst SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING = (\n context: string,\n providedCookieDomain: string | undefined,\n currentCookieDomain: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The provided cookie domain (${providedCookieDomain}) does not match the current webpage's domain (${currentCookieDomain}). Hence, the cookies will be set client-side.`;\n\nconst RESERVED_KEYWORD_WARNING = (\n context: string,\n property: string,\n parentKeyPath: string,\n reservedElements: string[],\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The \"${property}\" property defined under \"${parentKeyPath}\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (${reservedElements}).`;\n\nconst INVALID_CONTEXT_OBJECT_WARNING = (logContext: string): string =>\n `${logContext}${LOG_CONTEXT_SEPARATOR}Please make sure that the \"context\" property in the event API's \"options\" argument is a valid object literal with key-value pairs.`;\n\nconst UNSUPPORTED_BEACON_API_WARNING = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The Beacon API is not supported by your browser. The events will be sent using XHR instead.`;\n\nconst TIMEOUT_NOT_NUMBER_WARNING = (\n context: string,\n timeout: number | undefined,\n defaultValue: number,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The session timeout value \"${timeout}\" is not a number. The default timeout of ${defaultValue} ms will be used instead.`;\n\nconst TIMEOUT_ZERO_WARNING = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.`;\n\nconst TIMEOUT_NOT_RECOMMENDED_WARNING = (\n context: string,\n timeout: number,\n minTimeout: number,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The session timeout value ${timeout} ms is less than the recommended minimum of ${minTimeout} ms. Please consider increasing the timeout value to ensure optimal performance and reliability.`;\n\nconst INVALID_SESSION_ID_WARNING = (\n context: string,\n sessionId: number | undefined,\n minSessionIdLength: number,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The provided session ID (${sessionId}) is either invalid, not a positive integer, or not at least \"${minSessionIdLength}\" digits long. A new session ID will be auto-generated instead.`;\n\nconst STORAGE_QUOTA_EXCEEDED_WARNING = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.`;\n\nconst STORAGE_UNAVAILABLE_WARNING = (\n context: string,\n entry: string,\n selectedStorageType: string,\n finalStorageType: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The storage type \"${selectedStorageType}\" is not available for entry \"${entry}\". The SDK will initialize the entry with \"${finalStorageType}\" storage type instead.`;\n\nconst WRITE_KEY_NOT_A_STRING_ERROR = (context: string, writeKey: string | undefined): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The write key \"${writeKey}\" is not a string. Please check that the write key is correct and try again.`;\n\nconst EMPTY_GROUP_CALL_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The group() method must be called with at least one argument.`;\n\nconst READY_CALLBACK_INVOKE_ERROR = `Failed to invoke the ready callback`;\n\nconst API_CALLBACK_INVOKE_ERROR = `API Callback Invocation Failed`;\nconst NATIVE_DEST_PLUGIN_INITIALIZE_ERROR = `NativeDestinationQueuePlugin initialization failed`;\nconst DATAPLANE_PLUGIN_INITIALIZE_ERROR = `XhrQueuePlugin initialization failed`;\nconst DMT_PLUGIN_INITIALIZE_ERROR = `DeviceModeTransformationPlugin initialization failed`;\n\nconst NATIVE_DEST_PLUGIN_ENQUEUE_ERROR = `NativeDestinationQueuePlugin event enqueue failed`;\nconst DATAPLANE_PLUGIN_ENQUEUE_ERROR = `XhrQueuePlugin event enqueue failed`;\n\nconst INVALID_CONFIG_URL_WARNING = (context: string, configUrl: string | undefined): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The provided source config URL \"${configUrl}\" is invalid. Using the default source config URL instead.`;\n\nconst POLYFILL_SCRIPT_LOAD_ERROR = (scriptId: string, url: string): string =>\n `Failed to load the polyfill script with ID \"${scriptId}\" from URL ${url}.`;\n\nconst UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY = (\n context: string,\n selectedStrategy: StorageStrategy | undefined,\n defaultStrategy: StorageStrategy,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The pre-consent storage strategy \"${selectedStrategy}\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"${defaultStrategy}\" will be used instead.`;\n\nconst UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE = (\n context: string,\n selectedDeliveryType: DeliveryType | undefined,\n defaultDeliveryType: DeliveryType,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The pre-consent events delivery type \"${selectedDeliveryType}\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"${defaultDeliveryType}\" will be used instead.`;\n\nconst DEPRECATED_PLUGIN_WARNING = (context: string, pluginName: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}${pluginName} plugin is deprecated. Please exclude it from the load API options.`;\nconst generateMisconfiguredPluginsWarning = (\n context: string,\n configurationStatus: string,\n missingPlugins: PluginName[],\n shouldAddMissingPlugins: boolean,\n): string => {\n const isSinglePlugin = missingPlugins.length === 1;\n const pluginsString = isSinglePlugin\n ? ` '${missingPlugins[0]}' plugin was`\n : ` ['${missingPlugins.join(\"', '\")}'] plugins were`;\n const baseWarning = `${context}${LOG_CONTEXT_SEPARATOR}${configurationStatus}, but${pluginsString} not configured to load.`;\n if (shouldAddMissingPlugins) {\n return `${baseWarning} So, ${isSinglePlugin ? 'the plugin' : 'those plugins'} will be loaded automatically.`;\n }\n return `${baseWarning} Ignore if this was intentional. Otherwise, consider adding ${isSinglePlugin ? 'it' : 'them'} to the 'plugins' load API option.`;\n};\n\nconst INVALID_POLYFILL_URL_WARNING = (\n context: string,\n customPolyfillUrl: string | undefined,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The provided polyfill URL \"${customPolyfillUrl}\" is invalid. The default polyfill URL will be used instead.`;\n\n// DEBUG\n\nexport {\n UNSUPPORTED_CONSENT_MANAGER_ERROR,\n UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING,\n UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING,\n STORAGE_DATA_MIGRATION_OVERRIDE_WARNING,\n RESERVED_KEYWORD_WARNING,\n INVALID_CONTEXT_OBJECT_WARNING,\n UNSUPPORTED_BEACON_API_WARNING,\n TIMEOUT_NOT_NUMBER_WARNING,\n TIMEOUT_ZERO_WARNING,\n TIMEOUT_NOT_RECOMMENDED_WARNING,\n INVALID_SESSION_ID_WARNING,\n DEPRECATED_PLUGIN_WARNING,\n REPORTING_PLUGIN_INIT_FAILURE_ERROR,\n NOTIFY_FAILURE_ERROR,\n PLUGIN_NAME_MISSING_ERROR,\n PLUGIN_ALREADY_EXISTS_ERROR,\n PLUGIN_NOT_FOUND_ERROR,\n PLUGIN_ENGINE_BUG_ERROR,\n PLUGIN_DEPS_ERROR,\n PLUGIN_INVOCATION_ERROR,\n STORAGE_QUOTA_EXCEEDED_WARNING,\n STORAGE_UNAVAILABLE_WARNING,\n STORAGE_UNAVAILABILITY_ERROR_PREFIX,\n SOURCE_CONFIG_FETCH_ERROR,\n SOURCE_CONFIG_OPTION_ERROR,\n DATA_PLANE_URL_ERROR,\n WRITE_KEY_VALIDATION_ERROR,\n DATA_PLANE_URL_VALIDATION_ERROR,\n READY_API_CALLBACK_ERROR,\n DELIVERY_ERROR,\n REQUEST_ERROR,\n XHR_SEND_ERROR,\n PAYLOAD_PREP_ERROR,\n STORE_DATA_SAVE_ERROR,\n STORE_DATA_FETCH_ERROR,\n EVENT_OBJECT_GENERATION_ERROR,\n PLUGIN_EXT_POINT_MISSING_ERROR,\n PLUGIN_EXT_POINT_INVALID_ERROR,\n STORAGE_TYPE_VALIDATION_WARNING,\n WRITE_KEY_NOT_A_STRING_ERROR,\n EMPTY_GROUP_CALL_ERROR,\n READY_CALLBACK_INVOKE_ERROR,\n API_CALLBACK_INVOKE_ERROR,\n INVALID_CONFIG_URL_WARNING,\n POLYFILL_SCRIPT_LOAD_ERROR,\n UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY,\n UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE,\n SOURCE_CONFIG_RESOLUTION_ERROR,\n NATIVE_DEST_PLUGIN_INITIALIZE_ERROR,\n DATAPLANE_PLUGIN_INITIALIZE_ERROR,\n DMT_PLUGIN_INITIALIZE_ERROR,\n NATIVE_DEST_PLUGIN_ENQUEUE_ERROR,\n DATAPLANE_PLUGIN_ENQUEUE_ERROR,\n DATA_SERVER_URL_INVALID_ERROR,\n DATA_SERVER_REQUEST_FAIL_ERROR,\n FAILED_SETTING_COOKIE_FROM_SERVER_ERROR,\n FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR,\n generateMisconfiguredPluginsWarning,\n INVALID_POLYFILL_URL_WARNING,\n SOURCE_DISABLED_ERROR,\n COMPONENT_BASE_URL_ERROR,\n SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING,\n};\n","const CDN_INT_DIR = 'js-integrations';\nconst CDN_PLUGINS_DIR = 'plugins';\nconst URL_PATTERN = new RegExp(\n '^(https?:\\\\/\\\\/)' + // protocol\n '(' +\n '((([a-zA-Z\\\\d]([a-zA-Z\\\\d-]*[a-zA-Z\\\\d])*)\\\\.)+[a-zA-Z]{2,}|' + // domain name\n 'localhost|' + // localhost\n '((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)\\\\.){3}' + // OR IP (v4) address first 3 octets\n '(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?))' + // last octet of IP address\n ')' +\n '(\\\\:\\\\d+)?' + // port\n '(\\\\/[-a-zA-Z\\\\d%_.~+]*)*' + // path\n '(\\\\?[;&a-zA-Z\\\\d%_.~+=-]*)?' + // query string\n '(\\\\#[-a-zA-Z\\\\d_]*)?$', // fragment locator\n);\n\nexport { CDN_INT_DIR, CDN_PLUGINS_DIR, URL_PATTERN };\n","import { CDN_INT_DIR, CDN_PLUGINS_DIR } from '@rudderstack/analytics-js-common/constants/urls';\nimport { IS_LEGACY_BUILD } from './app';\n\nconst BUILD_TYPE = IS_LEGACY_BUILD ? 'legacy' : 'modern';\nconst SDK_CDN_BASE_URL = 'https://cdn.rudderlabs.com';\nconst CDN_ARCH_VERSION_DIR = 'v3';\nconst DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;\nconst PLUGINS_BASE_URL = `${SDK_CDN_BASE_URL}/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_PLUGINS_DIR}`;\nconst DEFAULT_CONFIG_BE_URL = 'https://api.rudderstack.com';\n\nexport {\n BUILD_TYPE,\n SDK_CDN_BASE_URL,\n CDN_ARCH_VERSION_DIR,\n DEST_SDK_BASE_URL,\n PLUGINS_BASE_URL,\n DEFAULT_CONFIG_BE_URL,\n};\n","import type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\n\nconst DEFAULT_STORAGE_ENCRYPTION_VERSION = 'v3';\nconst DEFAULT_DATA_PLANE_EVENTS_TRANSPORT = 'fetch';\n\nexport const ConsentManagersToPluginNameMap: Record = {\n oneTrust: 'OneTrustConsentManager',\n ketch: 'KetchConsentManager',\n custom: 'CustomConsentManager',\n};\n\nexport const StorageEncryptionVersionsToPluginNameMap: Record = {\n [DEFAULT_STORAGE_ENCRYPTION_VERSION]: 'StorageEncryption',\n legacy: 'StorageEncryptionLegacy',\n};\n\nexport const DataPlaneEventsTransportToPluginNameMap: Record = {\n [DEFAULT_DATA_PLANE_EVENTS_TRANSPORT]: 'FetchQueue',\n xhr: 'XhrQueue',\n beacon: 'BeaconQueue',\n};\n\nconst DEFAULT_DATA_SERVICE_ENDPOINT = 'rsaRequest';\nconst METRICS_SERVICE_ENDPOINT = 'rsaMetrics';\n\nexport {\n DEFAULT_STORAGE_ENCRYPTION_VERSION,\n DEFAULT_DATA_PLANE_EVENTS_TRANSPORT,\n DEFAULT_DATA_SERVICE_ENDPOINT,\n METRICS_SERVICE_ENDPOINT,\n};\n","import { signal } from '@preact/signals-core';\nimport { clone } from 'ramda';\nimport type { LoadOptions } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { LoadOptionsState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport {\n DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,\n DEFAULT_SESSION_TIMEOUT_MS,\n} from '../../constants/timeouts';\nimport { DEFAULT_CONFIG_BE_URL } from '../../constants/urls';\nimport { DEFAULT_STORAGE_ENCRYPTION_VERSION } from '../../components/configManager/constants';\n\nconst defaultLoadOptions: LoadOptions = {\n logLevel: 'ERROR',\n configUrl: DEFAULT_CONFIG_BE_URL,\n loadIntegration: true,\n sessions: {\n autoTrack: true,\n timeout: DEFAULT_SESSION_TIMEOUT_MS,\n },\n sameSiteCookie: 'Lax',\n polyfillIfRequired: true,\n integrations: { All: true },\n useBeacon: false,\n beaconQueueOptions: {},\n destinationsQueueOptions: {},\n queueOptions: {},\n lockIntegrationsVersion: false,\n lockPluginsVersion: false,\n uaChTrackLevel: 'none',\n plugins: [],\n useGlobalIntegrationsConfigInEvents: false,\n bufferDataPlaneEventsUntilReady: false,\n dataPlaneEventsBufferTimeout: DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,\n storage: {\n encryption: {\n version: DEFAULT_STORAGE_ENCRYPTION_VERSION,\n },\n migrate: true,\n },\n sendAdblockPageOptions: {},\n useServerSideCookies: false,\n};\n\nconst loadOptionsState: LoadOptionsState = signal(clone(defaultLoadOptions));\n\nexport { loadOptionsState };\n","import type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport type { SessionInfo } from '@rudderstack/analytics-js-common/types/Session';\n\nconst DEFAULT_USER_SESSION_VALUES = {\n userId: '',\n userTraits: {} as ApiObject,\n anonymousId: '',\n groupId: '',\n groupTraits: {} as ApiObject,\n initialReferrer: '',\n initialReferringDomain: '',\n sessionInfo: {} as SessionInfo,\n authToken: null,\n};\n\nconst SERVER_SIDE_COOKIES_DEBOUNCE_TIME = 10; // milliseconds\n\nexport { DEFAULT_USER_SESSION_VALUES, SERVER_SIDE_COOKIES_DEBOUNCE_TIME };\n","import { signal } from '@preact/signals-core';\nimport type { SessionState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { SessionInfo } from '@rudderstack/analytics-js-common/types/Session';\nimport { DEFAULT_USER_SESSION_VALUES } from '../../components/userSessionManager/constants';\nimport { DEFAULT_SESSION_TIMEOUT_MS } from '../../constants/timeouts';\n\nconst defaultSessionConfiguration: SessionInfo = {\n autoTrack: true,\n timeout: DEFAULT_SESSION_TIMEOUT_MS,\n};\n\nconst sessionState: SessionState = {\n userId: signal(DEFAULT_USER_SESSION_VALUES.userId),\n userTraits: signal(DEFAULT_USER_SESSION_VALUES.userTraits),\n anonymousId: signal(DEFAULT_USER_SESSION_VALUES.anonymousId),\n groupId: signal(DEFAULT_USER_SESSION_VALUES.groupId),\n groupTraits: signal(DEFAULT_USER_SESSION_VALUES.groupTraits),\n initialReferrer: signal(DEFAULT_USER_SESSION_VALUES.initialReferrer),\n initialReferringDomain: signal(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),\n sessionInfo: signal(DEFAULT_USER_SESSION_VALUES.sessionInfo),\n authToken: signal(DEFAULT_USER_SESSION_VALUES.authToken),\n};\n\nexport { sessionState, defaultSessionConfiguration };\n","import { signal } from '@preact/signals-core';\nimport type { CapabilitiesState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst capabilitiesState: CapabilitiesState = {\n isOnline: signal(true),\n storage: {\n isLocalStorageAvailable: signal(false),\n isCookieStorageAvailable: signal(false),\n isSessionStorageAvailable: signal(false),\n },\n isBeaconAvailable: signal(false),\n isLegacyDOM: signal(false),\n isUaCHAvailable: signal(false),\n isCryptoAvailable: signal(false),\n isIE11: signal(false),\n isAdBlocked: signal(false),\n};\n\nexport { capabilitiesState };\n","import { signal } from '@preact/signals-core';\nimport type { ReportingState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst reportingState: ReportingState = {\n isErrorReportingEnabled: signal(false),\n isMetricsReportingEnabled: signal(false),\n isErrorReportingPluginLoaded: signal(false),\n breadcrumbs: signal([]),\n};\n\nexport { reportingState };\n","import { signal } from '@preact/signals-core';\nimport type { SourceConfigState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst sourceConfigState: SourceConfigState = signal(undefined);\n\nexport { sourceConfigState };\n","import { signal } from '@preact/signals-core';\nimport type { LifecycleState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport { DEST_SDK_BASE_URL, PLUGINS_BASE_URL } from '../../constants/urls';\n\nconst lifecycleState: LifecycleState = {\n activeDataplaneUrl: signal(undefined),\n integrationsCDNPath: signal(DEST_SDK_BASE_URL),\n pluginsCDNPath: signal(PLUGINS_BASE_URL),\n sourceConfigUrl: signal(undefined),\n status: signal(undefined),\n initialized: signal(false),\n logLevel: signal('ERROR'),\n loaded: signal(false),\n readyCallbacks: signal([]),\n writeKey: signal(undefined),\n dataPlaneUrl: signal(undefined),\n};\n\nexport { lifecycleState };\n","import { signal } from '@preact/signals-core';\nimport type { ConsentsState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst consentsState: ConsentsState = {\n enabled: signal(false),\n initialized: signal(false),\n data: signal({}),\n activeConsentManagerPluginName: signal(undefined),\n preConsent: signal({ enabled: false }),\n postConsent: signal({}),\n resolutionStrategy: signal('and'),\n provider: signal(undefined),\n metadata: signal(undefined),\n};\n\nexport { consentsState };\n","import { signal } from '@preact/signals-core';\nimport type { MetricsState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst metricsState: MetricsState = {\n retries: signal(0),\n dropped: signal(0),\n sent: signal(0),\n queued: signal(0),\n triggered: signal(0),\n metricsServiceUrl: signal(undefined),\n};\n\nexport { metricsState };\n","import { signal } from '@preact/signals-core';\nimport type { ContextState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport { APP_NAME, APP_NAMESPACE, APP_VERSION, MODULE_TYPE } from '../../constants/app';\n\nconst contextState: ContextState = {\n app: signal({\n name: APP_NAME,\n namespace: APP_NAMESPACE,\n version: APP_VERSION,\n installType: MODULE_TYPE,\n }),\n traits: signal(null),\n library: signal({\n name: APP_NAME,\n version: APP_VERSION,\n snippetVersion: (globalThis as typeof window).RudderSnippetVersion,\n }),\n userAgent: signal(''),\n device: signal(null),\n network: signal(null),\n os: signal({\n name: '',\n version: '',\n }),\n locale: signal(null),\n screen: signal({\n density: 0,\n width: 0,\n height: 0,\n innerWidth: 0,\n innerHeight: 0,\n }),\n 'ua-ch': signal(undefined),\n timezone: signal(undefined),\n};\n\nexport { contextState };\n","import { signal } from '@preact/signals-core';\nimport type { NativeDestinationsState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst nativeDestinationsState: NativeDestinationsState = {\n configuredDestinations: signal([]),\n activeDestinations: signal([]),\n loadOnlyIntegrations: signal({}),\n failedDestinations: signal([]),\n loadIntegration: signal(true),\n initializedDestinations: signal([]),\n clientDestinationsReady: signal(false),\n integrationsConfig: signal({}),\n};\n\nexport { nativeDestinationsState };\n","import { signal } from '@preact/signals-core';\nimport type { EventBufferState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst eventBufferState: EventBufferState = {\n toBeProcessedArray: signal([]),\n readyCallbacksArray: signal([]),\n};\n\nexport { eventBufferState };\n","import { signal } from '@preact/signals-core';\nimport type { PluginsState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst pluginsState: PluginsState = {\n ready: signal(false),\n loadedPlugins: signal([]),\n failedPlugins: signal([]),\n pluginsToLoadFromConfig: signal([]),\n activePlugins: signal([]),\n totalPluginsToLoad: signal(0),\n};\n\nexport { pluginsState };\n","import { signal } from '@preact/signals-core';\nimport type { StorageState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst storageState: StorageState = {\n encryptionPluginName: signal(undefined),\n migrate: signal(false),\n type: signal(undefined),\n cookie: signal(undefined),\n entries: signal({}),\n trulyAnonymousTracking: signal(false),\n};\n\nexport { storageState };\n","import { signal } from '@preact/signals-core';\nimport type { ServerCookiesState } from '@rudderstack/analytics-js-common/types/ApplicationState';\n\nconst serverSideCookiesState: ServerCookiesState = {\n isEnabledServerSideCookies: signal(false),\n dataServiceUrl: signal(undefined),\n};\n\nexport { serverSideCookiesState };\n","import { signal } from '@preact/signals-core';\nimport type { DataPlaneEventsState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\n\nconst dataPlaneEventsState: DataPlaneEventsState = {\n eventsQueuePluginName: signal(undefined),\n deliveryEnabled: signal(true), // Delivery should always happen\n};\n\nexport { dataPlaneEventsState };\n","import { clone } from 'ramda';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport { loadOptionsState } from './slices/loadOptions';\nimport { sessionState } from './slices/session';\nimport { capabilitiesState } from './slices/capabilities';\nimport { reportingState } from './slices/reporting';\nimport { sourceConfigState } from './slices/source';\nimport { lifecycleState } from './slices/lifecycle';\nimport { consentsState } from './slices/consents';\nimport { metricsState } from './slices/metrics';\nimport { contextState } from './slices/context';\nimport { nativeDestinationsState } from './slices/nativeDestinations';\nimport { eventBufferState } from './slices/eventBuffer';\nimport { pluginsState } from './slices/plugins';\nimport { storageState } from './slices/storage';\nimport { serverSideCookiesState } from './slices/serverCookies';\nimport { dataPlaneEventsState } from './slices/dataPlaneEvents';\n\nconst defaultStateValues: ApplicationState = {\n capabilities: capabilitiesState,\n consents: consentsState,\n context: contextState,\n eventBuffer: eventBufferState,\n lifecycle: lifecycleState,\n loadOptions: loadOptionsState,\n metrics: metricsState,\n nativeDestinations: nativeDestinationsState,\n plugins: pluginsState,\n reporting: reportingState,\n session: sessionState,\n source: sourceConfigState,\n storage: storageState,\n serverCookies: serverSideCookiesState,\n dataPlaneEvents: dataPlaneEventsState,\n};\n\nconst state: ApplicationState = {\n ...clone(defaultStateValues),\n};\n\nconst resetState = () => {\n state.capabilities = clone(defaultStateValues.capabilities);\n state.consents = clone(defaultStateValues.consents);\n state.context = clone(defaultStateValues.context);\n state.eventBuffer = clone(defaultStateValues.eventBuffer);\n state.lifecycle = clone(defaultStateValues.lifecycle);\n state.loadOptions = clone(defaultStateValues.loadOptions);\n state.metrics = clone(defaultStateValues.metrics);\n state.nativeDestinations = clone(defaultStateValues.nativeDestinations);\n state.plugins = clone(defaultStateValues.plugins);\n state.reporting = clone(defaultStateValues.reporting);\n state.session = clone(defaultStateValues.session);\n state.source = clone(defaultStateValues.source);\n state.storage = clone(defaultStateValues.storage);\n state.serverCookies = clone(defaultStateValues.serverCookies);\n state.dataPlaneEvents = clone(defaultStateValues.dataPlaneEvents);\n};\n\nexport { state, resetState };\n","import { isFunction } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { getValueByPath, hasValueByPath } from '@rudderstack/analytics-js-common/utilities/object';\nimport type {\n ExtensionPlugin,\n IPluginEngine,\n PluginEngineConfig,\n} from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { PLUGIN_ENGINE } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { defaultLogger } from '../Logger';\nimport {\n PLUGIN_ALREADY_EXISTS_ERROR,\n PLUGIN_DEPS_ERROR,\n PLUGIN_ENGINE_BUG_ERROR,\n PLUGIN_EXT_POINT_INVALID_ERROR,\n PLUGIN_EXT_POINT_MISSING_ERROR,\n PLUGIN_INVOCATION_ERROR,\n PLUGIN_NAME_MISSING_ERROR,\n PLUGIN_NOT_FOUND_ERROR,\n} from '../../constants/logMessages';\n\n// TODO: create chained invoke to take the output frm first plugin and pass\n// to next or return the value if it is the last one instead of an array per\n// plugin that is the normal invoke\n// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods\nclass PluginEngine implements IPluginEngine {\n plugins: ExtensionPlugin[] = [];\n byName: Record = {};\n cache: Record = {};\n config: PluginEngineConfig = { throws: true };\n logger?: ILogger;\n\n constructor(options: PluginEngineConfig = {}, logger?: ILogger) {\n this.config = {\n throws: true,\n ...options,\n };\n\n this.logger = logger;\n }\n\n register(plugin: ExtensionPlugin, state?: Record) {\n if (!plugin.name) {\n const errorMessage = PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);\n if (this.config.throws) {\n throw new Error(errorMessage);\n } else {\n this.logger?.error(errorMessage, plugin);\n }\n }\n\n if (this.byName[plugin.name]) {\n const errorMessage = PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE, plugin.name);\n if (this.config.throws) {\n throw new Error(errorMessage);\n } else {\n this.logger?.error(errorMessage);\n }\n }\n\n this.cache = {};\n this.plugins = this.plugins.slice();\n let pos = this.plugins.length;\n\n this.plugins.forEach((pluginItem: ExtensionPlugin, index: number) => {\n if (pluginItem.deps?.includes(plugin.name)) {\n pos = Math.min(pos, index);\n }\n });\n\n this.plugins.splice(pos, 0, plugin);\n\n this.byName[plugin.name] = plugin;\n\n if (isFunction(plugin.initialize)) {\n plugin.initialize(state);\n }\n }\n\n unregister(name: string) {\n const plugin = this.byName[name];\n\n if (!plugin) {\n const errorMessage = PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE, name);\n if (this.config.throws) {\n throw new Error(errorMessage);\n } else {\n this.logger?.error(errorMessage);\n }\n }\n\n const index = this.plugins.indexOf(plugin as ExtensionPlugin);\n\n if (index === -1) {\n const errorMessage = PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE, name);\n if (this.config.throws) {\n throw new Error(errorMessage);\n } else {\n this.logger?.error(errorMessage);\n }\n }\n\n this.cache = {};\n delete this.byName[name];\n this.plugins = this.plugins.slice();\n this.plugins.splice(index, 1);\n }\n\n getPlugin(name: string): ExtensionPlugin | undefined {\n return this.byName[name];\n }\n\n getPlugins(extPoint?: string): ExtensionPlugin[] {\n const lifeCycleName = extPoint ?? '.';\n\n if (!this.cache[lifeCycleName]) {\n this.cache[lifeCycleName] = this.plugins.filter(plugin => {\n if (plugin.deps?.some(dependency => !this.byName[dependency])) {\n // If deps not exist, then not load it.\n const notExistDeps = plugin.deps.filter(dependency => !this.byName[dependency]);\n this.logger?.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE, plugin.name, notExistDeps));\n return false;\n }\n return lifeCycleName === '.' ? true : hasValueByPath(plugin, lifeCycleName);\n });\n }\n\n return this.cache[lifeCycleName] as ExtensionPlugin[];\n }\n\n // This method allows to process this.plugins so that it could\n // do some unified pre-process before application starts.\n processRawPlugins(callback: (plugins: ExtensionPlugin[]) => any) {\n callback(this.plugins);\n this.cache = {};\n }\n\n invoke(extPoint?: string, allowMultiple = true, ...args: any[]): Nullable[] {\n let extensionPointName = extPoint;\n\n if (!extensionPointName) {\n throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);\n }\n\n const noCall = extensionPointName.startsWith('!');\n const throws = this.config.throws ?? extensionPointName.endsWith('!');\n\n // eslint-disable-next-line unicorn/better-regex\n extensionPointName = extensionPointName.replace(/(^!|!$)/g, '');\n\n if (!extensionPointName) {\n throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);\n }\n\n const extensionPointNameParts = extensionPointName.split('.');\n extensionPointNameParts.pop();\n\n const pluginMethodPath = extensionPointNameParts.join('.');\n const pluginsToInvoke = allowMultiple\n ? this.getPlugins(extensionPointName)\n : [this.getPlugins(extensionPointName)[0] as ExtensionPlugin];\n\n return pluginsToInvoke.map(plugin => {\n const method = getValueByPath(plugin, extensionPointName as string);\n\n if (!isFunction(method) || noCall) {\n return method;\n }\n\n try {\n return method.apply(getValueByPath(plugin, pluginMethodPath), args);\n } catch (err) {\n // When a plugin failed, doesn't break the app\n if (throws) {\n throw err;\n } else {\n this.logger?.error(\n PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE, extensionPointName, plugin.name),\n err,\n );\n }\n }\n\n return null;\n });\n }\n\n invokeSingle(extPoint?: string, ...args: any[]): Nullable {\n return this.invoke(extPoint, false, ...args)[0];\n }\n\n invokeMultiple(extPoint?: string, ...args: any[]): Nullable[] {\n return this.invoke(extPoint, true, ...args);\n }\n}\n\nconst defaultPluginEngine = new PluginEngine({ throws: true }, defaultLogger);\n\nexport { PluginEngine, defaultPluginEngine };\n","import type { IPluginEngine } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport { removeDoubleSpaces } from '@rudderstack/analytics-js-common/utilities/string';\nimport { isTypeOfError } from '@rudderstack/analytics-js-common/utilities/checks';\nimport {\n ErrorType,\n type ErrorState,\n type IErrorHandler,\n type PreLoadErrorData,\n type SDKError,\n} from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { ERROR_HANDLER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\nimport { BufferQueue } from '@rudderstack/analytics-js-common/services/BufferQueue/BufferQueue';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types';\nimport {\n NOTIFY_FAILURE_ERROR,\n REPORTING_PLUGIN_INIT_FAILURE_ERROR,\n} from '../../constants/logMessages';\nimport { state } from '../../state';\nimport { defaultPluginEngine } from '../PluginEngine';\nimport { defaultLogger } from '../Logger';\nimport { getNormalizedErrorForUnhandledError, processError } from './processError';\n\n/**\n * A service to handle errors\n */\nclass ErrorHandler implements IErrorHandler {\n logger?: ILogger;\n pluginEngine?: IPluginEngine;\n httpClient?: IHttpClient;\n errReportingClient?: any;\n errorBuffer: BufferQueue;\n\n // If no logger is passed errors will be thrown as unhandled error\n constructor(logger?: ILogger, pluginEngine?: IPluginEngine) {\n this.logger = logger;\n this.pluginEngine = pluginEngine;\n this.errorBuffer = new BufferQueue();\n this.attachEffect();\n }\n\n attachEffect() {\n if (state.reporting.isErrorReportingPluginLoaded.value === true) {\n while (this.errorBuffer.size() > 0) {\n const errorToProcess = this.errorBuffer.dequeue();\n\n if (errorToProcess) {\n // send it to the plugin\n this.notifyError(errorToProcess.error, errorToProcess.errorState);\n }\n }\n }\n }\n\n attachErrorListeners() {\n if ('addEventListener' in (globalThis as typeof window)) {\n (globalThis as typeof window).addEventListener('error', (event: ErrorEvent | Event) => {\n this.onError(event, undefined, undefined, undefined, ErrorType.UNHANDLEDEXCEPTION);\n });\n\n (globalThis as typeof window).addEventListener(\n 'unhandledrejection',\n (event: PromiseRejectionEvent) => {\n this.onError(event, undefined, undefined, undefined, ErrorType.UNHANDLEDREJECTION);\n },\n );\n } else {\n this.logger?.debug(`Failed to attach global error listeners.`);\n }\n }\n\n init(httpClient: IHttpClient, externalSrcLoader: IExternalSrcLoader) {\n this.httpClient = httpClient;\n // Below lines are only kept for backward compatibility\n // TODO: Remove this in the next major release\n if (!this.pluginEngine) {\n return;\n }\n\n try {\n const extPoint = 'errorReporting.init';\n const errReportingInitVal = this.pluginEngine.invokeSingle(\n extPoint,\n state,\n this.pluginEngine,\n externalSrcLoader,\n this.logger,\n true,\n );\n if (errReportingInitVal instanceof Promise) {\n errReportingInitVal\n .then((client: any) => {\n this.errReportingClient = client;\n })\n .catch(err => {\n this.logger?.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER), err);\n });\n }\n } catch (err) {\n this.onError(err, ERROR_HANDLER);\n }\n }\n\n onError(\n error: SDKError,\n context = '',\n customMessage = '',\n shouldAlwaysThrow = false,\n errorType = ErrorType.HANDLEDEXCEPTION,\n ) {\n let normalizedError;\n let errorMessage;\n if (errorType === ErrorType.HANDLEDEXCEPTION) {\n errorMessage = processError(error);\n\n // If no error message after we normalize, then we swallow/ignore the errors\n if (!errorMessage) {\n return;\n }\n\n errorMessage = removeDoubleSpaces(\n `${context}${LOG_CONTEXT_SEPARATOR}${customMessage} ${errorMessage}`,\n );\n\n normalizedError = new Error(errorMessage);\n if (isTypeOfError(error)) {\n normalizedError = Object.create(error, {\n message: { value: errorMessage },\n });\n }\n } else {\n normalizedError = getNormalizedErrorForUnhandledError(error);\n }\n\n const isErrorReportingEnabled = state.reporting.isErrorReportingEnabled.value;\n const isErrorReportingPluginLoaded = state.reporting.isErrorReportingPluginLoaded.value;\n try {\n if (isErrorReportingEnabled) {\n const errorState: ErrorState = {\n severity: 'error',\n unhandled: errorType !== ErrorType.HANDLEDEXCEPTION,\n severityReason: { type: errorType },\n };\n\n if (!isErrorReportingPluginLoaded) {\n // buffer the error\n this.errorBuffer.enqueue({\n error: normalizedError,\n errorState,\n });\n } else if (normalizedError) {\n this.notifyError(normalizedError, errorState);\n }\n }\n } catch (e) {\n this.logger?.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER), e);\n }\n\n if (errorType === ErrorType.HANDLEDEXCEPTION) {\n if (this.logger) {\n this.logger.error(errorMessage);\n\n if (shouldAlwaysThrow) {\n throw normalizedError;\n }\n } else {\n throw normalizedError;\n }\n }\n }\n\n /**\n * Add breadcrumbs to add insight of a user's journey before an error\n * occurred and send to external error monitoring service via a plugin\n *\n * @param {string} breadcrumb breadcrumbs message\n */\n leaveBreadcrumb(breadcrumb: string) {\n if (this.pluginEngine) {\n try {\n this.pluginEngine.invokeSingle(\n 'errorReporting.breadcrumb',\n this.pluginEngine, // deprecated parameter\n this.errReportingClient, // deprecated parameter\n breadcrumb,\n this.logger,\n state,\n );\n } catch (err) {\n this.onError(err, ERROR_HANDLER, 'errorReporting.breadcrumb');\n }\n }\n }\n\n /**\n * Send handled errors to external error monitoring service via a plugin\n *\n * @param {Error} error Error instance from handled error\n */\n notifyError(error: SDKError, errorState: ErrorState) {\n if (this.pluginEngine && this.httpClient) {\n try {\n this.pluginEngine.invokeSingle(\n 'errorReporting.notify',\n this.pluginEngine, // deprecated parameter\n this.errReportingClient, // deprecated parameter\n error,\n state,\n this.logger,\n this.httpClient,\n errorState,\n );\n } catch (err) {\n // Not calling onError here as we don't want to go into infinite loop\n this.logger?.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER), err);\n }\n }\n }\n}\n\nconst defaultErrorHandler = new ErrorHandler(defaultLogger, defaultPluginEngine);\n\nexport { ErrorHandler, defaultErrorHandler };\n","import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport { isString } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { ErrorTarget, SDKError } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport { LOAD_ORIGIN } from './constant';\n\n/**\n * Utility method to normalise errors\n */\nconst processError = (error: SDKError): string => {\n let errorMessage;\n\n try {\n if (isString(error)) {\n errorMessage = error;\n } else if (error instanceof Error) {\n errorMessage = error.message;\n } else if (error instanceof ErrorEvent) {\n errorMessage = error.message;\n } else {\n errorMessage = (error as any).message\n ? (error as any).message\n : stringifyWithoutCircular(error as Record);\n }\n } catch (e) {\n errorMessage = `Unknown error: ${(e as Error).message}`;\n }\n\n return errorMessage;\n};\n\nconst getNormalizedErrorForUnhandledError = (error: SDKError): SDKError | undefined => {\n try {\n if (\n error instanceof Error ||\n error instanceof ErrorEvent ||\n (error instanceof PromiseRejectionEvent && error.reason)\n ) {\n return error;\n }\n // TODO: remove this block once all device mode integrations start using the v3 script loader module (TS)\n if (error instanceof Event) {\n const eventTarget = error.target as ErrorTarget;\n // Discard all the non-script loading errors\n if (eventTarget && eventTarget.localName !== 'script') {\n return undefined;\n }\n // Discard script errors that are not originated at SDK or from native SDKs\n if (\n eventTarget?.dataset &&\n (eventTarget.dataset.loader !== LOAD_ORIGIN ||\n eventTarget.dataset.isnonnativesdk !== 'true')\n ) {\n return undefined;\n }\n const errorMessage = `Error in loading a third-party script from URL ${eventTarget?.src} with ID ${eventTarget?.id}.`;\n return Object.create(error, {\n message: { value: errorMessage },\n });\n }\n return error;\n } catch (e) {\n return e;\n }\n};\n\nexport { processError, getNormalizedErrorForUnhandledError };\n","const LOAD_ORIGIN = 'RS_JS_SDK';\n\nexport { LOAD_ORIGIN };\n","import type { Destination } from '../types/Destination';\n\n/**\n * A function to filter and return non cloud mode destinations\n * @param destination\n *\n * @returns boolean\n */\nconst isNonCloudDestination = (destination: Destination): boolean =>\n Boolean(\n destination.config.connectionMode !== 'cloud' ||\n destination.config.useNativeSDKToSend === true || // this is the older flag for hybrid mode destinations\n destination.config.useNativeSDK === true,\n );\n\nconst isHybridModeDestination = (destination: Destination): boolean =>\n Boolean(\n destination.config.connectionMode === 'hybrid' ||\n destination.config.useNativeSDKToSend === true,\n );\n\n/**\n * A function to filter and return non cloud mode destinations\n * @param destinations\n *\n * @returns destinations\n */\nconst getNonCloudDestinations = (destinations: Destination[]): Destination[] | [] =>\n destinations.filter(isNonCloudDestination);\n\nexport { isNonCloudDestination, getNonCloudDestinations, isHybridModeDestination };\n","import type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\n\n/**\n * List of plugin names that are loaded as direct imports in all builds\n */\nconst localPluginNames: PluginName[] = [];\n\n/**\n * List of plugin names that are loaded as dynamic imports in modern builds\n */\nconst pluginNamesList: PluginName[] = [\n 'BeaconQueue',\n 'Bugsnag', // deprecated\n 'CustomConsentManager',\n 'DeviceModeDestinations',\n 'DeviceModeTransformation',\n 'ErrorReporting',\n 'ExternalAnonymousId',\n 'GoogleLinker',\n 'KetchConsentManager',\n 'NativeDestinationQueue',\n 'OneTrustConsentManager',\n 'StorageEncryption',\n 'StorageEncryptionLegacy',\n 'StorageMigrator',\n 'XhrQueue',\n 'FetchQueue',\n];\n\nconst deprecatedPluginsList = ['Bugsnag'];\n\nexport { localPluginNames, pluginNamesList, deprecatedPluginsList };\n","/**\n * To get the current timestamp in ISO string format\n * @returns ISO formatted timestamp string\n */\nconst getCurrentTimeFormatted = (): string => {\n const curDateTime = new Date().toISOString();\n return curDateTime;\n};\n\nexport { getCurrentTimeFormatted };\n","import type { StorageType } from '../types/Storage';\n\nconst COOKIE_STORAGE: StorageType = 'cookieStorage';\nconst LOCAL_STORAGE: StorageType = 'localStorage';\nconst SESSION_STORAGE: StorageType = 'sessionStorage';\nconst MEMORY_STORAGE: StorageType = 'memoryStorage';\nconst NO_STORAGE: StorageType = 'none';\n\nexport { COOKIE_STORAGE, LOCAL_STORAGE, SESSION_STORAGE, MEMORY_STORAGE, NO_STORAGE };\n","import { URL_PATTERN } from '../constants/urls';\nimport { isFunction, isString } from './checks';\n\nconst removeDuplicateSlashes = (str: string): string => str.replace(/\\/{2,}/g, '/');\n\n/**\n * Checks if provided url is valid or not\n * @param url\n * @returns true if `url` is valid and false otherwise\n */\nconst isValidURL = (url: string | undefined): url is string => {\n if (!isString(url)) {\n return false;\n }\n\n try {\n // If URL is supported by the browser, we can use it to validate the URL\n // Otherwise, we can at least check if the URL matches the pattern\n if (isFunction(globalThis.URL)) {\n // eslint-disable-next-line no-new\n new URL(url);\n }\n return URL_PATTERN.test(url);\n } catch (e) {\n return false;\n }\n};\n\nexport { removeDuplicateSlashes, isValidURL };\n","import { random } from '@lukeed/csprng';\n\nvar SIZE=4096, HEX=[], IDX=0, BUFFER;\n\nfor (; IDX < 256; IDX++) {\n\tHEX[IDX] = (IDX + 256).toString(16).substring(1);\n}\n\nexport function v4() {\n\tif (!BUFFER || ((IDX + 16) > SIZE)) {\n\t\tBUFFER = random(SIZE);\n\t\tIDX = 0;\n\t}\n\n\tvar i=0, tmp, out='';\n\tfor (; i < 16; i++) {\n\t\ttmp = BUFFER[IDX + i];\n\t\tif (i==6) out += HEX[tmp & 15 | 64];\n\t\telse if (i==8) out += HEX[tmp & 63 | 128];\n\t\telse out += HEX[tmp];\n\n\t\tif (i & 1 && i > 1 && i < 11) out += '-';\n\t}\n\n\tIDX += 16;\n\treturn out;\n}\n","export function random(len) {\n\treturn crypto.getRandomValues(new Uint8Array(len));\n}\n","var IDX=256, HEX=[], BUFFER;\nwhile (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1);\n\nexport function v4() {\n\tvar i=0, num, out='';\n\n\tif (!BUFFER || ((IDX + 16) > 256)) {\n\t\tBUFFER = Array(i=256);\n\t\twhile (i--) BUFFER[i] = 256 * Math.random() | 0;\n\t\ti = IDX = 0;\n\t}\n\n\tfor (; i < 16; i++) {\n\t\tnum = BUFFER[IDX + i];\n\t\tif (i==6) out += HEX[num & 15 | 64];\n\t\telse if (i==8) out += HEX[num & 63 | 128];\n\t\telse out += HEX[num];\n\n\t\tif (i & 1 && i > 1 && i < 11) out += '-';\n\t}\n\n\tIDX++;\n\treturn out;\n}\n","import { isFunction, isNullOrUndefined } from './checks';\n\nconst hasCrypto = (): boolean =>\n !isNullOrUndefined(globalThis.crypto) && isFunction(globalThis.crypto.getRandomValues);\n\nexport { hasCrypto };\n","import { v4 as uuidSecure } from '@lukeed/uuid/secure';\nimport { v4 as uuid } from '@lukeed/uuid';\nimport { hasCrypto } from './crypto';\n\nconst generateUUID = (): string => {\n if (hasCrypto()) {\n return uuidSecure();\n }\n\n return uuid();\n};\n\nexport { generateUUID };\n","import type { IResponseDetails } from '../types/HttpClient';\n\nconst isErrRetryable = (details: IResponseDetails) => {\n let isRetryableNWFailure = false;\n if (details.error?.status) {\n const { status } = details.error;\n // same as in v1.1\n isRetryableNWFailure = (status === 429 || (status >= 500 && status < 600));\n }\n return isRetryableNWFailure;\n};\n\nexport { isErrRetryable };\n","const userIdKey = 'rl_user_id';\nconst userTraitsKey = 'rl_trait';\nconst anonymousUserIdKey = 'rl_anonymous_id';\nconst groupIdKey = 'rl_group_id';\nconst groupTraitsKey = 'rl_group_trait';\nconst pageInitialReferrerKey = 'rl_page_init_referrer';\nconst pageInitialReferringDomainKey = 'rl_page_init_referring_domain';\nconst sessionInfoKey = 'rl_session';\nconst authTokenKey = 'rl_auth_token';\n\nconst COOKIE_KEYS = {\n userId: userIdKey,\n userTraits: userTraitsKey,\n anonymousId: anonymousUserIdKey,\n groupId: groupIdKey,\n groupTraits: groupTraitsKey,\n initialReferrer: pageInitialReferrerKey,\n initialReferringDomain: pageInitialReferringDomainKey,\n sessionInfo: sessionInfoKey,\n authToken: authTokenKey,\n};\n\nconst ENCRYPTION_PREFIX_V3 = 'RS_ENC_v3_';\n\nexport {\n COOKIE_KEYS,\n ENCRYPTION_PREFIX_V3,\n userIdKey,\n userTraitsKey,\n anonymousUserIdKey,\n groupIdKey,\n groupTraitsKey,\n pageInitialReferrerKey,\n pageInitialReferringDomainKey,\n sessionInfoKey,\n authTokenKey,\n};\n","import { isNull } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { CookieOptions } from '@rudderstack/analytics-js-common/types/Storage';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { COOKIE_DATA_ENCODING_ERROR } from '../constants/logMessages';\n\n/**\n * Encode.\n */\nconst encode = (value: any, logger?: ILogger): string | undefined => {\n try {\n return encodeURIComponent(value);\n } catch (err) {\n logger?.error(COOKIE_DATA_ENCODING_ERROR, err);\n return undefined;\n }\n};\n\n/**\n * Decode\n */\nconst decode = (value: string): string | undefined => {\n try {\n return decodeURIComponent(value);\n } catch (err) {\n // Do nothing as non-RS SDK cookies may not be URI encoded\n return undefined;\n }\n};\n\n/**\n * Parse cookie `str`\n */\nconst parse = (str: string): Record => {\n const obj: Record = {};\n const pairs = str.split(/\\s*;\\s*/);\n let pair;\n\n if (!pairs[0]) {\n return obj;\n }\n\n // TODO: Decode only the cookies that are needed by the SDK\n pairs.forEach(pairItem => {\n pair = pairItem.split('=');\n const keyName = pair[0] ? decode(pair[0]) : undefined;\n\n if (keyName) {\n obj[keyName] = pair[1] ? decode(pair[1]) : undefined;\n }\n });\n\n return obj;\n};\n\n/**\n * Set cookie `name` to `value`\n */\nconst set = (\n name?: string,\n value?: Nullable,\n optionsConfig?: CookieOptions,\n logger?: ILogger,\n) => {\n const options: CookieOptions = { ...(optionsConfig || {}) };\n let cookieString = `${encode(name, logger)}=${encode(value, logger)}`;\n\n if (isNull(value)) {\n options.maxage = -1;\n }\n\n if (options.maxage) {\n options.expires = new Date(+new Date() + options.maxage);\n }\n\n if (options.path) {\n cookieString += `; path=${options.path}`;\n }\n\n if (options.domain) {\n cookieString += `; domain=${options.domain}`;\n }\n\n if (options.expires) {\n cookieString += `; expires=${options.expires.toUTCString()}`;\n }\n\n if (options.samesite) {\n cookieString += `; samesite=${options.samesite}`;\n }\n\n if (options.secure) {\n cookieString += `; secure`;\n }\n\n globalThis.document.cookie = cookieString;\n};\n\n/**\n * Return all cookies\n */\nconst all = (): Record => {\n const cookieStringValue = globalThis.document.cookie;\n return parse(cookieStringValue);\n};\n\n/**\n * Get cookie `name`\n */\n\nconst get = (name: string): string => (all() as any)[name];\n\n/**\n * Set or get cookie `name` with `value` and `options` object\n */\n// eslint-disable-next-line func-names\nconst cookie = function (\n name?: string,\n value?: Nullable,\n options?: CookieOptions,\n logger?: ILogger,\n): void | any {\n switch (arguments.length) {\n case 4:\n case 3:\n case 2:\n return set(name, value, options, logger);\n case 1:\n if (name) {\n return get(name);\n }\n return all();\n default:\n return all();\n }\n};\n\nexport { cookie };\n","const COOKIE_DATA_ENCODING_ERROR = `Failed to encode the cookie data.`;\n\nexport { COOKIE_DATA_ENCODING_ERROR };\n","import { fromBase64, toBase64 } from '@rudderstack/analytics-js-common/utilities/string';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { isNull, isNullOrUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport { COOKIE_KEYS, ENCRYPTION_PREFIX_V3 } from './constants/cookies';\nimport { cookie } from './component-cookie';\n\nconst getEncryptedValueInternal = (\n value: string | ApiObject,\n encryptFn: (value: string) => string,\n debug: boolean,\n): Nullable => {\n const fallbackValue = null;\n try {\n const strValue = stringifyWithoutCircular(value, false);\n if (isNull(strValue)) {\n return null;\n }\n return encryptFn(strValue);\n } catch (err) {\n if (debug) {\n console.error('Error occurred during encryption: ', err);\n }\n return fallbackValue;\n }\n};\n\nconst getDecryptedValueInternal = (\n value: string,\n decryptFn: (value: string | undefined) => string | undefined,\n debug: boolean,\n): Nullable => {\n const fallbackValue = null;\n try {\n const decryptedVal = decryptFn(value);\n\n if (isNullOrUndefined(decryptedVal)) {\n return fallbackValue;\n }\n\n return JSON.parse(decryptedVal as string);\n } catch (err) {\n if (debug) {\n console.error('Error occurred during decryption: ', err);\n }\n return fallbackValue;\n }\n};\n\nconst encryptBrowser = (value: string): string => `${ENCRYPTION_PREFIX_V3}${toBase64(value)}`;\n\nconst decryptBrowser = (value: string | undefined): string | undefined => {\n if (value?.startsWith(ENCRYPTION_PREFIX_V3)) {\n return fromBase64(value.substring(ENCRYPTION_PREFIX_V3.length));\n }\n\n return value;\n};\n\nconst getEncryptedValueBrowser = (\n value: string | ApiObject,\n debug: boolean = false,\n): Nullable => getEncryptedValueInternal(value, encryptBrowser, debug);\n\nconst getDecryptedValueBrowser = (\n value: string,\n debug: boolean = false,\n): Nullable => getDecryptedValueInternal(value, decryptBrowser, debug);\n\nconst getDecryptedCookieBrowser = (\n cookieKey: string,\n debug: boolean = false,\n): Nullable => {\n if (Object.values(COOKIE_KEYS).includes(cookieKey)) {\n return getDecryptedValueBrowser(cookie(cookieKey), debug);\n }\n return null;\n};\n\nconst encrypt = (value: string): string =>\n `${ENCRYPTION_PREFIX_V3}${Buffer.from(value, 'utf-8').toString('base64')}`;\n\nconst decrypt = (value: string | undefined): string | undefined => {\n if (value?.startsWith(ENCRYPTION_PREFIX_V3)) {\n return Buffer.from(value.substring(ENCRYPTION_PREFIX_V3.length), 'base64').toString('utf-8');\n }\n\n return value;\n};\n\nconst getDecryptedValue = (value: string, debug: boolean = false): Nullable =>\n getDecryptedValueInternal(value, decrypt, debug);\n\nconst getEncryptedValue = (value: string | ApiObject, debug: boolean = false): Nullable =>\n getEncryptedValueInternal(value, encrypt, debug);\n\nexport {\n encryptBrowser,\n decryptBrowser,\n getDecryptedValueBrowser,\n getDecryptedCookieBrowser,\n getEncryptedValueBrowser,\n getDecryptedValue,\n getEncryptedValue,\n};\n","import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport { clone } from 'ramda';\nimport { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport { EVENT_PAYLOAD_SIZE_BYTES_LIMIT } from './constants';\nimport type { TransformationRequestPayload } from '../deviceModeTransformation/types';\n\nconst EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING = (\n context: string,\n payloadSize: number,\n sizeLimit: number,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The size of the event payload (${payloadSize} bytes) exceeds the maximum limit of ${sizeLimit} bytes. Events with large payloads may be dropped in the future. Please review your instrumentation to ensure that event payloads are within the size limit.`;\n\nconst EVENT_PAYLOAD_SIZE_VALIDATION_WARNING = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to validate event payload size. Please make sure that the event payload is within the size limit and is a valid JSON object.`;\n\nconst QUEUE_UTILITIES = 'QueueUtilities';\n\n/**\n * Utility to get the stringified event payload\n * @param event RudderEvent object\n * @param logger Logger instance\n * @returns stringified event payload. Empty string if error occurs.\n */\nconst getDeliveryPayload = (event: RudderEvent, logger?: ILogger): Nullable =>\n stringifyWithoutCircular(event, true, undefined, logger);\n\nconst getDMTDeliveryPayload = (\n dmtRequestPayload: TransformationRequestPayload,\n logger?: ILogger,\n): Nullable =>\n stringifyWithoutCircular(\n dmtRequestPayload,\n true,\n undefined,\n logger,\n );\n\n/**\n * Utility to validate final payload size before sending to server\n * @param event RudderEvent object\n * @param logger Logger instance\n */\nconst validateEventPayloadSize = (event: RudderEvent, logger?: ILogger) => {\n const payloadStr = getDeliveryPayload(event, logger);\n if (payloadStr) {\n const payloadSize = payloadStr.length;\n if (payloadSize > EVENT_PAYLOAD_SIZE_BYTES_LIMIT) {\n logger?.warn(\n EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(\n QUEUE_UTILITIES,\n payloadSize,\n EVENT_PAYLOAD_SIZE_BYTES_LIMIT,\n ),\n );\n }\n } else {\n logger?.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));\n }\n};\n\n/**\n * Mutates the event and return final event for delivery\n * Updates certain parameters like sentAt timestamp, integrations config etc.\n * @param event RudderEvent object\n * @returns Final event ready to be delivered\n */\nconst getFinalEventForDeliveryMutator = (event: RudderEvent, currentTime: string): RudderEvent => {\n const finalEvent = clone(event);\n\n // Update sentAt timestamp to the latest timestamp\n finalEvent.sentAt = currentTime;\n\n return finalEvent;\n};\n\nexport {\n getDeliveryPayload,\n validateEventPayloadSize,\n getFinalEventForDeliveryMutator,\n getDMTDeliveryPayload,\n};\n","const EVENT_PAYLOAD_SIZE_BYTES_LIMIT = 32 * 1024; // 32 KB\n\nexport { EVENT_PAYLOAD_SIZE_BYTES_LIMIT };\n","const DEFAULT_BEACON_QUEUE_MAX_SIZE = 10;\nconst DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes\n\n// Limit of the Beacon transfer mechanism on the browsers\nconst MAX_BATCH_PAYLOAD_SIZE_BYTES = 64 * 1024; // 64 KB\n\nconst DEFAULT_BEACON_QUEUE_OPTIONS = {\n maxItems: DEFAULT_BEACON_QUEUE_MAX_SIZE,\n flushQueueInterval: DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS,\n};\n\nconst REQUEST_TIMEOUT_MS = 10 * 1000; // 10 seconds\n\nconst DATA_PLANE_API_VERSION = 'v1';\n\nconst QUEUE_NAME = 'rudder_beacon';\n\nconst BEACON_QUEUE_PLUGIN = 'BeaconQueuePlugin';\n\nexport {\n MAX_BATCH_PAYLOAD_SIZE_BYTES,\n DEFAULT_BEACON_QUEUE_OPTIONS,\n REQUEST_TIMEOUT_MS,\n DATA_PLANE_API_VERSION,\n QUEUE_NAME,\n BEACON_QUEUE_PLUGIN,\n};\n","import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { BeaconQueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport { json, url } from '../shared-chunks/common';\nimport {\n BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR,\n BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR,\n} from './logMessages';\nimport {\n BEACON_QUEUE_PLUGIN,\n DATA_PLANE_API_VERSION,\n DEFAULT_BEACON_QUEUE_OPTIONS,\n} from './constants';\nimport type { BeaconBatchData } from './types';\n\n/**\n * Utility to get the stringified event payload as Blob\n * @param events RudderEvent object array\n * @param logger Logger instance\n * @returns stringified events payload as Blob, undefined if error occurs.\n */\nconst getBatchDeliveryPayload = (\n events: RudderEvent[],\n currentTime: string,\n logger?: ILogger,\n): Blob | undefined => {\n const data: BeaconBatchData = {\n batch: events,\n sentAt: currentTime,\n };\n\n try {\n const blobPayload = json.stringifyWithoutCircular(data, true);\n const blobOptions: BlobPropertyBag = { type: 'text/plain' };\n\n if (blobPayload) {\n return new Blob([blobPayload], blobOptions);\n }\n logger?.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));\n } catch (err) {\n logger?.error(BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN), err);\n }\n return undefined;\n};\n\nconst getNormalizedBeaconQueueOptions = (queueOpts: BeaconQueueOpts): BeaconQueueOpts =>\n mergeDeepRight(DEFAULT_BEACON_QUEUE_OPTIONS, queueOpts);\n\nconst getDeliveryUrl = (dataplaneUrl: string, writeKey: string): string => {\n const dpUrl = new URL(dataplaneUrl);\n return new URL(\n url.removeDuplicateSlashes(\n [\n dpUrl.pathname,\n '/',\n 'beacon',\n '/',\n DATA_PLANE_API_VERSION,\n '/',\n `batch?writeKey=${writeKey}`,\n ].join(''),\n ),\n dpUrl,\n ).href;\n};\n\nexport { getBatchDeliveryPayload, getDeliveryUrl, getNormalizedBeaconQueueOptions };\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst BEACON_PLUGIN_EVENTS_QUEUE_DEBUG = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Sending events to data plane.`;\n\nconst BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to convert events batch object to string.`;\n\nconst BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to convert events batch object to Blob.`;\n\nconst BEACON_QUEUE_SEND_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to send events batch data to the browser's beacon queue. The events will be dropped.`;\n\nconst BEACON_QUEUE_DELIVERY_ERROR = (url: string): string =>\n `Failed to send events batch data to the browser's beacon queue for URL ${url}.`;\n\nexport {\n BEACON_PLUGIN_EVENTS_QUEUE_DEBUG,\n BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR,\n BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR,\n BEACON_QUEUE_SEND_ERROR,\n BEACON_QUEUE_DELIVERY_ERROR,\n};\n","const QueueStatuses = {\n IN_PROGRESS: 'inProgress',\n QUEUE: 'queue',\n RECLAIM_START: 'reclaimStart',\n RECLAIM_END: 'reclaimEnd',\n ACK: 'ack',\n BATCH_QUEUE: 'batchQueue',\n};\n\nexport { QueueStatuses };\n","export type ScheduleTaskHandler = (\n id: string,\n callback: () => any,\n timeout: number,\n mode: ScheduleModes,\n) => any;\n\nexport type ScheduleClock = {\n setTimeout: (fn: ScheduleTaskHandler, ms: number) => number;\n clearTimeout: (id: number) => void;\n Date: DateConstructor;\n clockLateFactor: number;\n};\n\nexport const enum ScheduleModes {\n ASAP = 1,\n RESCHEDULE = 2,\n ABANDON = 3,\n}\n\nconst DEFAULT_CLOCK_LATE_FACTOR = 2;\n\nconst DEFAULT_CLOCK: ScheduleClock = {\n setTimeout(fn: ScheduleTaskHandler, ms: number): number {\n return (globalThis as typeof window).setTimeout(fn, ms);\n },\n clearTimeout(id: number) {\n return (globalThis as typeof window).clearTimeout(id);\n },\n Date: globalThis.Date,\n clockLateFactor: DEFAULT_CLOCK_LATE_FACTOR,\n};\n\nclass Schedule {\n tasks: Record;\n nextId;\n clock: ScheduleClock;\n\n constructor() {\n this.tasks = {};\n this.nextId = 1;\n this.clock = DEFAULT_CLOCK;\n }\n\n now(): number {\n return +new this.clock.Date();\n }\n\n run(task: () => any, timeout: number, mode?: ScheduleModes): string {\n const id = (this.nextId + 1).toString();\n\n this.tasks[id] = this.clock.setTimeout(\n this.handle(id, task, timeout, mode || ScheduleModes.ASAP),\n timeout,\n );\n\n return id;\n }\n\n handle(\n id: string,\n callback: () => any,\n timeout: number,\n mode: ScheduleModes,\n ): () => any | undefined {\n const start = this.now();\n\n return () => {\n delete this.tasks[id];\n const elapsedTimeoutTime =\n start + timeout * (this.clock.clockLateFactor || DEFAULT_CLOCK_LATE_FACTOR);\n const currentTime = this.now();\n const notCompletedOrTimedOut =\n mode >= ScheduleModes.RESCHEDULE && elapsedTimeoutTime < currentTime;\n\n if (notCompletedOrTimedOut) {\n if (mode === ScheduleModes.RESCHEDULE) {\n this.run(callback, timeout, mode);\n }\n\n return undefined;\n }\n\n return callback();\n };\n }\n\n cancel(id: string) {\n if (this.tasks[id]) {\n this.clock.clearTimeout(this.tasks[id] as number);\n delete this.tasks[id];\n }\n }\n\n cancelAll() {\n Object.values(this.tasks).forEach(this.clock.clearTimeout);\n this.tasks = {};\n }\n}\n\nexport { Schedule, DEFAULT_CLOCK, DEFAULT_CLOCK_LATE_FACTOR };\n","const DEFAULT_MIN_RETRY_DELAY_MS = 1000;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 30000;\nconst DEFAULT_BACKOFF_FACTOR = 2;\nconst DEFAULT_BACKOFF_JITTER = 0;\n\nconst DEFAULT_MAX_RETRY_ATTEMPTS = Infinity;\nconst DEFAULT_MAX_ITEMS = Infinity;\n\nconst DEFAULT_ACK_TIMER_MS = 1000;\nconst DEFAULT_RECLAIM_TIMER_MS = 3000;\nconst DEFAULT_RECLAIM_TIMEOUT_MS = 10000;\nconst DEFAULT_RECLAIM_WAIT_MS = 500;\nconst MIN_TIMER_SCALE_FACTOR = 1;\nconst MAX_TIMER_SCALE_FACTOR = 10;\n\nconst DEFAULT_MAX_BATCH_SIZE_BYTES = 512 * 1024; // 512 KB; this is also the max size of a batch\nconst DEFAULT_MAX_BATCH_ITEMS = 100;\nconst DEFAULT_BATCH_FLUSH_INTERVAL_MS = 60 * 1000; // 1 minutes\n\nexport {\n DEFAULT_MIN_RETRY_DELAY_MS,\n DEFAULT_MAX_RETRY_DELAY_MS,\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_BACKOFF_JITTER,\n DEFAULT_MAX_RETRY_ATTEMPTS,\n DEFAULT_MAX_ITEMS,\n DEFAULT_ACK_TIMER_MS,\n DEFAULT_RECLAIM_TIMER_MS,\n DEFAULT_RECLAIM_TIMEOUT_MS,\n DEFAULT_RECLAIM_WAIT_MS,\n DEFAULT_MAX_BATCH_SIZE_BYTES,\n DEFAULT_MAX_BATCH_ITEMS,\n DEFAULT_BATCH_FLUSH_INTERVAL_MS,\n MIN_TIMER_SCALE_FACTOR,\n MAX_TIMER_SCALE_FACTOR,\n};\n","import { isObjectLiteralAndNotNull } from '@rudderstack/analytics-js-common/utilities/object';\nimport { QueueStatuses } from '@rudderstack/analytics-js-common/constants/QueueStatuses';\nimport type { IStore, IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { BatchOpts, QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport {\n isDefined,\n isFunction,\n isNullOrUndefined,\n} from '@rudderstack/analytics-js-common/utilities/checks';\nimport { LOCAL_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId';\nimport { onPageLeave } from '@rudderstack/analytics-js-common/utilities/page';\nimport type {\n IQueue,\n QueueItem,\n QueueItemData,\n QueueBatchItemsSizeCalculatorCallback,\n QueueProcessCallback,\n} from '../../types/plugins';\nimport { Schedule, ScheduleModes } from './Schedule';\nimport { RETRY_QUEUE_ENTRY_REMOVE_ERROR, RETRY_QUEUE_PROCESS_ERROR } from './logMessages';\nimport type { QueueTimeouts, QueueBackoff, InProgressQueueItem } from './types';\nimport {\n DEFAULT_MAX_ITEMS,\n DEFAULT_MAX_RETRY_ATTEMPTS,\n DEFAULT_MAX_BATCH_SIZE_BYTES,\n DEFAULT_MAX_BATCH_ITEMS,\n DEFAULT_MIN_RETRY_DELAY_MS,\n DEFAULT_MAX_RETRY_DELAY_MS,\n DEFAULT_BACKOFF_FACTOR,\n DEFAULT_BACKOFF_JITTER,\n DEFAULT_ACK_TIMER_MS,\n DEFAULT_RECLAIM_TIMER_MS,\n DEFAULT_RECLAIM_TIMEOUT_MS,\n DEFAULT_RECLAIM_WAIT_MS,\n DEFAULT_BATCH_FLUSH_INTERVAL_MS,\n MIN_TIMER_SCALE_FACTOR,\n MAX_TIMER_SCALE_FACTOR,\n} from './constants';\n\nconst sortByTime = (a: QueueItem, b: QueueItem) => a.time - b.time;\n\nconst RETRY_QUEUE = 'RetryQueue';\n\n/**\n * Constructs a RetryQueue backed by localStorage\n *\n * @constructor\n * @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items\n * @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.\n * @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue\n */\nclass RetryQueue implements IQueue {\n name: string;\n id: string;\n processQueueCb: QueueProcessCallback;\n store: IStore;\n storeManager: IStoreManager;\n maxItems: number;\n timeouts: QueueTimeouts;\n scheduleTimeoutActive: boolean;\n maxAttempts: number;\n backoff: QueueBackoff;\n schedule: Schedule;\n processId: string;\n logger?: ILogger;\n batch: BatchOpts;\n flushBatchTaskId?: string;\n batchingInProgress?: boolean;\n batchSizeCalcCb?: QueueBatchItemsSizeCalculatorCallback;\n reclaimStartVal?: Nullable;\n reclaimEndVal?: Nullable;\n\n constructor(\n name: string,\n options: QueueOpts,\n queueProcessCb: QueueProcessCallback,\n storeManager: IStoreManager,\n storageType: StorageType = LOCAL_STORAGE,\n logger?: ILogger,\n queueBatchItemsSizeCalculatorCb?: QueueBatchItemsSizeCalculatorCallback,\n ) {\n this.storeManager = storeManager;\n this.logger = logger;\n this.name = name;\n this.id = generateUUID();\n\n this.processQueueCb = queueProcessCb;\n this.batchSizeCalcCb = queueBatchItemsSizeCalculatorCb;\n\n this.maxItems = options.maxItems || DEFAULT_MAX_ITEMS;\n this.maxAttempts = options.maxAttempts || DEFAULT_MAX_RETRY_ATTEMPTS;\n\n this.batch = { enabled: false };\n this.configureBatchMode(options);\n\n this.backoff = {\n minRetryDelay: options.minRetryDelay || DEFAULT_MIN_RETRY_DELAY_MS,\n maxRetryDelay: options.maxRetryDelay || DEFAULT_MAX_RETRY_DELAY_MS,\n factor: options.backoffFactor || DEFAULT_BACKOFF_FACTOR,\n jitter: options.backoffJitter || DEFAULT_BACKOFF_JITTER,\n };\n\n // Limit the timer scale factor to the minimum value\n let timerScaleFactor = Math.max(\n options.timerScaleFactor ?? MIN_TIMER_SCALE_FACTOR,\n MIN_TIMER_SCALE_FACTOR,\n );\n\n // Limit the timer scale factor to the maximum value\n timerScaleFactor = Math.min(timerScaleFactor, MAX_TIMER_SCALE_FACTOR);\n\n // painstakingly tuned. that's why they're not \"easily\" configurable\n this.timeouts = {\n ackTimer: Math.round(timerScaleFactor * DEFAULT_ACK_TIMER_MS),\n reclaimTimer: Math.round(timerScaleFactor * DEFAULT_RECLAIM_TIMER_MS),\n reclaimTimeout: Math.round(timerScaleFactor * DEFAULT_RECLAIM_TIMEOUT_MS),\n reclaimWait: Math.round(timerScaleFactor * DEFAULT_RECLAIM_WAIT_MS),\n };\n\n this.schedule = new Schedule();\n this.processId = '0';\n\n // Set up our empty queues\n this.store = this.storeManager.setStore({\n id: this.id,\n name: this.name,\n validKeys: QueueStatuses,\n type: storageType,\n });\n this.setDefaultQueueEntries();\n\n // bind recurring tasks for ease of use\n this.ack = this.ack.bind(this);\n this.checkReclaim = this.checkReclaim.bind(this);\n this.processHead = this.processHead.bind(this);\n this.flushBatch = this.flushBatch.bind(this);\n\n // Flush the queue on page leave\n this.flushBatchOnPageLeave();\n\n this.scheduleTimeoutActive = false;\n }\n\n private setDefaultQueueEntries() {\n this.setStorageEntry(QueueStatuses.IN_PROGRESS, {});\n this.setStorageEntry(QueueStatuses.QUEUE, []);\n this.setStorageEntry(QueueStatuses.BATCH_QUEUE, []);\n }\n\n configureBatchMode(options: QueueOpts) {\n this.batchingInProgress = false;\n\n if (!isObjectLiteralAndNotNull(options.batch)) {\n return;\n }\n\n const batchOptions = options.batch as BatchOpts;\n\n this.batch.enabled = batchOptions.enabled === true;\n if (this.batch.enabled) {\n // Set upper cap on the batch payload size\n this.batch.maxSize = Math.min(\n batchOptions.maxSize ?? DEFAULT_MAX_BATCH_SIZE_BYTES,\n DEFAULT_MAX_BATCH_SIZE_BYTES,\n );\n this.batch.maxItems = batchOptions.maxItems ?? DEFAULT_MAX_BATCH_ITEMS;\n this.batch.flushInterval = batchOptions.flushInterval ?? DEFAULT_BATCH_FLUSH_INTERVAL_MS;\n }\n }\n\n flushBatchOnPageLeave() {\n if (this.batch.enabled) {\n onPageLeave(this.flushBatch);\n }\n }\n\n getStorageEntry(\n name: string,\n ): Nullable[] | Record | number> {\n return this.store.get(name);\n }\n\n // TODO: fix the type of different queues to be the same if possible\n setStorageEntry(\n name: string,\n value?: Nullable[] | Record> | number,\n ) {\n if (isNullOrUndefined(value)) {\n this.store.remove(name);\n } else {\n this.store.set(name, value);\n }\n }\n\n /**\n * Stops processing the queue\n */\n stop() {\n this.schedule.cancelAll();\n this.scheduleTimeoutActive = false;\n }\n\n /**\n * Starts processing the queue\n */\n start() {\n if (this.scheduleTimeoutActive) {\n this.stop();\n }\n\n this.scheduleTimeoutActive = true;\n this.scheduleFlushBatch();\n this.ack();\n this.checkReclaim();\n this.processHead();\n }\n\n /**\n * Configures the timeout handler for flushing the batch queue\n */\n scheduleFlushBatch() {\n if (this.batch.enabled && this.batch?.flushInterval) {\n if (this.flushBatchTaskId) {\n this.schedule.cancel(this.flushBatchTaskId);\n }\n\n this.flushBatchTaskId = this.schedule.run(\n this.flushBatch,\n this.batch.flushInterval,\n ScheduleModes.ASAP,\n );\n }\n }\n\n /**\n * Flushes the batch queue\n */\n flushBatch() {\n if (!this.batchingInProgress) {\n this.batchingInProgress = true;\n let batchQueue =\n (this.getStorageEntry(QueueStatuses.BATCH_QUEUE) as Nullable) ?? [];\n if (batchQueue.length > 0) {\n batchQueue = batchQueue.slice(-batchQueue.length);\n\n const batchEntry = this.genQueueItem(batchQueue.map(queueItem => queueItem.item));\n\n this.setStorageEntry(QueueStatuses.BATCH_QUEUE, []);\n\n this.pushToMainQueue(batchEntry);\n }\n this.batchingInProgress = false;\n\n // Re-schedule the flush task\n this.scheduleFlushBatch();\n }\n }\n\n /**\n * Decides whether to retry. Overridable.\n *\n * @param {Object} item The item being processed\n * @param {Number} attemptNumber The attemptNumber (1 for first retry)\n * @return {Boolean} Whether to requeue the message\n */\n shouldRetry(item: QueueItemData, attemptNumber: number): boolean {\n return attemptNumber <= this.maxAttempts;\n }\n\n /**\n * Calculates the delay (in ms) for a retry attempt\n *\n * @param {Number} attemptNumber The attemptNumber (1 for first retry)\n * @return {Number} The delay in milliseconds to wait before attempting a retry\n */\n getDelay(attemptNumber: number): number {\n let ms = this.backoff.minRetryDelay * this.backoff.factor ** attemptNumber;\n\n if (this.backoff.jitter) {\n const rand = Math.random();\n const deviation = Math.floor(rand * this.backoff.jitter * ms);\n\n if (Math.floor(rand * 10) < 5) {\n ms -= deviation;\n } else {\n ms += deviation;\n }\n }\n\n return Number(Math.min(ms, this.backoff.maxRetryDelay).toPrecision(1));\n }\n\n enqueue(entry: QueueItem) {\n let curEntry: QueueItem | undefined;\n if (this.batch.enabled) {\n curEntry = this.handleNewItemForBatch(entry);\n } else {\n curEntry = entry;\n }\n\n // when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met\n if (curEntry) {\n this.pushToMainQueue(curEntry);\n }\n }\n\n /**\n * Handles a new item added to the retry queue when batching is enabled\n * @param entry New item added to the retry queue\n * @returns Undefined or batch entry object\n */\n handleNewItemForBatch(entry: QueueItem) {\n let curEntry: QueueItem | undefined;\n let batchQueue =\n (this.getStorageEntry(QueueStatuses.BATCH_QUEUE) as Nullable) ?? [];\n\n if (!this.batchingInProgress) {\n this.batchingInProgress = true;\n batchQueue = batchQueue.slice(-batchQueue.length);\n batchQueue.push(entry);\n\n const batchDispatchInfo = this.getBatchDispatchInfo(batchQueue);\n // if batch criteria is met, queue the batch events to the main queue and clear batch queue\n if (batchDispatchInfo.criteriaMet || batchDispatchInfo.criteriaExceeded) {\n let batchItems;\n if (batchDispatchInfo.criteriaExceeded) {\n batchItems = batchQueue.slice(0, batchQueue.length - 1).map(queueItem => queueItem.item);\n batchQueue = [entry];\n } else {\n batchItems = batchQueue.map(queueItem => queueItem.item);\n batchQueue = [];\n }\n\n // Don't make any batch request if there are no items\n if (batchItems.length > 0) {\n curEntry = this.genQueueItem(batchItems);\n }\n\n // re-attach the timeout handler\n this.scheduleFlushBatch();\n }\n this.batchingInProgress = false;\n } else {\n batchQueue.push(entry);\n }\n\n // update the batch queue\n this.setStorageEntry(QueueStatuses.BATCH_QUEUE, batchQueue);\n return curEntry;\n }\n\n pushToMainQueue(curEntry: QueueItem) {\n let queue =\n (this.getStorageEntry(QueueStatuses.QUEUE) as Nullable[]>) ?? [];\n\n queue = queue.slice(-(this.maxItems - 1));\n queue.push(curEntry);\n queue = queue.sort(sortByTime);\n\n this.setStorageEntry(QueueStatuses.QUEUE, queue);\n\n if (this.scheduleTimeoutActive) {\n this.processHead();\n }\n }\n\n /**\n * Adds an item to the queue\n *\n * @param {Object} itemData The item to process\n */\n addItem(itemData: QueueItemData) {\n this.enqueue(this.genQueueItem(itemData));\n }\n\n /**\n * Generates a queue item\n * @param itemData Queue item data\n * @returns Queue item\n */\n genQueueItem(itemData: QueueItemData): QueueItem {\n return {\n item: itemData,\n attemptNumber: 0,\n time: this.schedule.now(),\n id: generateUUID(),\n };\n }\n\n /**\n * Adds an item to the retry queue\n *\n * @param {Object} itemData The item to retry\n * @param {Number} attemptNumber The attempt number (1 for first retry)\n * @param {Error} [error] The error from previous attempt, if there was one\n * @param {String} [id] The id of the queued message used for tracking duplicate entries\n */\n requeue(itemData: QueueItemData, attemptNumber: number, error?: Error, id?: string) {\n if (this.shouldRetry(itemData, attemptNumber)) {\n this.enqueue({\n item: itemData,\n attemptNumber,\n time: this.schedule.now() + this.getDelay(attemptNumber),\n id: id ?? generateUUID(),\n });\n } else {\n // Discard item\n }\n }\n\n /**\n * Returns the information about whether the batch criteria is met or exceeded\n * @param batchItems Prospective batch items\n * @returns Batch dispatch info\n */\n getBatchDispatchInfo(batchItems: QueueItem[]) {\n let lengthCriteriaMet = false;\n let lengthCriteriaExceeded = false;\n const configuredBatchMaxItems = this.batch?.maxItems as number;\n if (isDefined(configuredBatchMaxItems)) {\n lengthCriteriaMet = batchItems.length === configuredBatchMaxItems;\n lengthCriteriaExceeded = batchItems.length > configuredBatchMaxItems;\n }\n\n if (lengthCriteriaMet || lengthCriteriaExceeded) {\n return {\n criteriaMet: lengthCriteriaMet,\n criteriaExceeded: lengthCriteriaExceeded,\n };\n }\n\n let sizeCriteriaMet = false;\n let sizeCriteriaExceeded = false;\n const configuredBatchMaxSize = this.batch?.maxSize as number;\n if (isDefined(configuredBatchMaxSize) && isDefined(this.batchSizeCalcCb)) {\n const curBatchSize = (this.batchSizeCalcCb as QueueBatchItemsSizeCalculatorCallback)(\n batchItems.map(queueItem => queueItem.item),\n );\n\n sizeCriteriaMet = curBatchSize === configuredBatchMaxSize;\n sizeCriteriaExceeded = curBatchSize > configuredBatchMaxSize;\n }\n\n return {\n criteriaMet: sizeCriteriaMet,\n criteriaExceeded: sizeCriteriaExceeded,\n };\n }\n\n processHead() {\n // cancel the scheduled task if it exists\n this.schedule.cancel(this.processId);\n\n // Pop the head off the queue\n let queue =\n (this.getStorageEntry(QueueStatuses.QUEUE) as Nullable[]>) ?? [];\n const inProgress =\n (this.getStorageEntry(QueueStatuses.IN_PROGRESS) as Nullable>) ?? {};\n const now = this.schedule.now();\n const toRun: InProgressQueueItem[] = [];\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const processItemCallback = (el: QueueItem, id: string) => (err?: Error, res?: any) => {\n const inProgress =\n (this.getStorageEntry(QueueStatuses.IN_PROGRESS) as Nullable>) ?? {};\n delete inProgress[id];\n\n this.setStorageEntry(QueueStatuses.IN_PROGRESS, inProgress);\n\n if (err) {\n this.requeue(el.item, el.attemptNumber + 1, err, el.id);\n }\n };\n\n const enqueueItem = (el: QueueItem, id: string) => {\n toRun.push({\n item: el.item,\n done: processItemCallback(el, id),\n attemptNumber: el.attemptNumber,\n });\n };\n\n let inProgressSize = Object.keys(inProgress).length;\n\n // eslint-disable-next-line no-plusplus\n while (\n queue.length > 0 &&\n (queue[0] as QueueItem).time <= now &&\n inProgressSize++ < this.maxItems\n ) {\n const el = queue.shift();\n if (el) {\n const id = generateUUID();\n\n // Save this to the in progress map\n inProgress[id] = {\n item: el.item,\n attemptNumber: el.attemptNumber,\n time: this.schedule.now(),\n };\n\n enqueueItem(el, id);\n }\n }\n\n this.setStorageEntry(QueueStatuses.QUEUE, queue);\n this.setStorageEntry(QueueStatuses.IN_PROGRESS, inProgress);\n\n toRun.forEach(el => {\n // TODO: handle processQueueCb timeout\n try {\n const willBeRetried = this.shouldRetry(el.item, el.attemptNumber + 1);\n this.processQueueCb(el.item, el.done, el.attemptNumber, this.maxAttempts, willBeRetried);\n } catch (err) {\n this.logger?.error(RETRY_QUEUE_PROCESS_ERROR(RETRY_QUEUE), err);\n }\n });\n\n // re-read the queue in case the process function finished immediately or added another item\n queue =\n (this.getStorageEntry(QueueStatuses.QUEUE) as Nullable[]>) ?? [];\n this.schedule.cancel(this.processId);\n\n if (queue.length > 0) {\n const nextProcessExecutionTime = (queue[0] as QueueItem).time - now;\n this.processId = this.schedule.run(\n this.processHead,\n nextProcessExecutionTime,\n ScheduleModes.ASAP,\n );\n }\n }\n\n // Ack continuously to prevent other tabs from claiming our queue\n ack() {\n this.setStorageEntry(QueueStatuses.ACK, this.schedule.now());\n\n if (this.reclaimStartVal != null) {\n this.reclaimStartVal = null;\n this.setStorageEntry(QueueStatuses.RECLAIM_START, null);\n }\n\n if (this.reclaimEndVal != null) {\n this.reclaimEndVal = null;\n this.setStorageEntry(QueueStatuses.RECLAIM_END, null);\n }\n\n this.schedule.run(this.ack, this.timeouts.ackTimer, ScheduleModes.ASAP);\n }\n\n reclaim(id: string) {\n const other = this.storeManager.setStore({\n id,\n name: this.name,\n validKeys: QueueStatuses,\n type: LOCAL_STORAGE,\n });\n const our = {\n queue: (this.getStorageEntry(QueueStatuses.QUEUE) ?? []) as QueueItem[],\n };\n const their = {\n inProgress: other.get(QueueStatuses.IN_PROGRESS) ?? {},\n batchQueue: other.get(QueueStatuses.BATCH_QUEUE) ?? [],\n queue: (other.get(QueueStatuses.QUEUE) ?? []) as QueueItem[],\n };\n const trackMessageIds: string[] = [];\n\n const addConcatQueue = (\n queue: QueueItem[] | Record | null,\n incrementAttemptNumberBy: number,\n ) => {\n const concatIterator = (el: QueueItem | Record) => {\n const id = el.id ?? generateUUID();\n\n if (trackMessageIds.includes(id)) {\n // duplicated event\n } else {\n our.queue.push({\n item: el.item,\n attemptNumber: el.attemptNumber + incrementAttemptNumberBy,\n time: this.schedule.now(),\n id,\n });\n trackMessageIds.push(id);\n }\n };\n\n if (Array.isArray(queue)) {\n queue.forEach(concatIterator);\n } else if (queue) {\n Object.values(queue).forEach(concatIterator);\n }\n };\n\n // add their queue to ours, resetting run-time to immediate and copying the attempt#\n addConcatQueue(their.queue, 0);\n\n // Process batch queue items\n if (this.batch.enabled) {\n their.batchQueue.forEach((el: QueueItem) => {\n const id = el.id ?? generateUUID();\n if (trackMessageIds.includes(id)) {\n // duplicated event\n } else {\n this.enqueue(el);\n trackMessageIds.push(id);\n }\n });\n } else {\n // if batching is not enabled in the current instance, add those items to the main queue directly\n addConcatQueue(their.batchQueue, 0);\n }\n\n // if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#\n addConcatQueue(their.inProgress, 1);\n\n our.queue = our.queue.sort(sortByTime);\n\n this.setStorageEntry(QueueStatuses.QUEUE, our.queue);\n\n // remove all keys one by on next tick to avoid NS_ERROR_STORAGE_BUSY error\n this.clearQueueEntries(other, 1);\n\n // process the new items we claimed\n this.processHead();\n }\n\n // eslint-disable-next-line class-methods-use-this\n clearQueueEntries(other: IStore, localStorageBackoff: number) {\n this.removeStorageEntry(other, 0, localStorageBackoff);\n }\n\n removeStorageEntry(store: IStore, entryIdx: number, backoff: number, attempt = 1) {\n const maxAttempts = 2;\n const queueEntryKeys = Object.keys(QueueStatuses);\n const entry = QueueStatuses[queueEntryKeys[entryIdx] as keyof typeof QueueStatuses];\n\n (globalThis as typeof window).setTimeout(() => {\n try {\n store.remove(entry);\n\n // clear the next entry\n if (entryIdx + 1 < queueEntryKeys.length) {\n this.removeStorageEntry(store, entryIdx + 1, backoff);\n }\n } catch (err) {\n const storageBusyErr = 'NS_ERROR_STORAGE_BUSY';\n const isLocalStorageBusy =\n (err as any).name === storageBusyErr ||\n (err as any).code === storageBusyErr ||\n (err as any).code === 0x80630001;\n\n if (isLocalStorageBusy && attempt < maxAttempts) {\n // Try clearing the same entry again with some extra delay\n this.removeStorageEntry(store, entryIdx, backoff + 40, attempt + 1);\n } else {\n this.logger?.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE, entry, attempt), err);\n }\n\n // clear the next entry after we've exhausted our attempts\n if (attempt === maxAttempts && entryIdx + 1 < queueEntryKeys.length) {\n this.removeStorageEntry(store, entryIdx + 1, backoff);\n }\n }\n }, backoff);\n }\n\n checkReclaim() {\n const createReclaimStartTask = (store: IStore) => () => {\n if (store.get(QueueStatuses.RECLAIM_END) !== this.id) {\n return;\n }\n\n if (store.get(QueueStatuses.RECLAIM_START) !== this.id) {\n return;\n }\n\n this.reclaim(store.id);\n };\n const createReclaimEndTask = (store: IStore) => () => {\n if (store.get(QueueStatuses.RECLAIM_START) !== this.id) {\n return;\n }\n\n store.set(QueueStatuses.RECLAIM_END, this.id);\n\n this.schedule.run(\n createReclaimStartTask(store),\n this.timeouts.reclaimWait,\n ScheduleModes.ABANDON,\n );\n };\n const tryReclaim = (store: IStore) => {\n store.set(QueueStatuses.RECLAIM_START, this.id);\n store.set(QueueStatuses.ACK, this.schedule.now());\n\n this.schedule.run(\n createReclaimEndTask(store),\n this.timeouts.reclaimWait,\n ScheduleModes.ABANDON,\n );\n };\n const findOtherQueues = (name: string): IStore[] => {\n const res: IStore[] = [];\n const storageEngine = this.store.getOriginalEngine();\n let storageKeys = [];\n // 'keys' API is not supported by all the core SDK versions\n // Hence, we need this backward compatibility check\n if (isFunction(storageEngine.keys)) {\n storageKeys = storageEngine.keys();\n } else {\n for (let i = 0; i < storageEngine.length; i++) {\n const key = storageEngine.key(i);\n if (key) {\n storageKeys.push(key);\n }\n }\n }\n\n storageKeys.forEach((k: string) => {\n const keyParts: string[] = k ? k.split('.') : [];\n\n if (\n keyParts.length >= 3 &&\n keyParts[0] === name &&\n keyParts[1] !== this.id &&\n keyParts[2] === QueueStatuses.ACK\n ) {\n res.push(\n this.storeManager.setStore({\n id: keyParts[1] as string,\n name,\n validKeys: QueueStatuses,\n type: LOCAL_STORAGE,\n }),\n );\n }\n });\n\n return res;\n };\n\n findOtherQueues(this.name).forEach(store => {\n if (this.schedule.now() - store.get(QueueStatuses.ACK) < this.timeouts.reclaimTimeout) {\n return;\n }\n\n tryReclaim(store);\n });\n\n this.schedule.run(this.checkReclaim, this.timeouts.reclaimTimer, ScheduleModes.RESCHEDULE);\n }\n\n clear() {\n this.schedule.cancelAll();\n this.setDefaultQueueEntries();\n }\n}\n\nexport { RetryQueue };\n","const onPageLeave = (callback: (...args: unknown[]) => void) => {\n // To ensure the callback is only called once even if more than one events\n // are fired at once.\n let pageLeft = false;\n\n function handleOnLeave() {\n if (pageLeft) {\n return;\n }\n\n pageLeft = true;\n\n callback();\n }\n\n // Catches the unloading of the page (e.g., closing the tab or navigating away).\n // Includes user actions like clicking a link, entering a new URL,\n // refreshing the page, or closing the browser tab\n // Note that 'pagehide' is not supported in IE.\n // So, this is a fallback.\n (globalThis as typeof window).addEventListener('beforeunload', handleOnLeave);\n\n // Catches the page being hidden, including scenarios like closing the tab.\n document.addEventListener('pagehide', handleOnLeave);\n\n // Catches visibility changes, such as switching tabs or minimizing the browser.\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') {\n handleOnLeave();\n } else {\n pageLeft = false;\n }\n });\n};\n\nexport { onPageLeave };\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst RETRY_QUEUE_PROCESS_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Process function threw an error.`;\n\nconst RETRY_QUEUE_ENTRY_REMOVE_ERROR = (context: string, entry: string, attempt: number): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to remove local storage entry \"${entry}\" (attempt: ${attempt}.`;\n\nexport { RETRY_QUEUE_PROCESS_ERROR, RETRY_QUEUE_ENTRY_REMOVE_ERROR };\n","/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type {\n BeaconQueueOpts,\n QueueOpts,\n} from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp';\nimport type { DoneCallback, IQueue } from '../types/plugins';\nimport {\n getNormalizedBeaconQueueOptions,\n getDeliveryUrl,\n getBatchDeliveryPayload,\n} from './utilities';\nimport { eventsDelivery, timestamp, storages } from '../shared-chunks/common';\nimport { BEACON_QUEUE_PLUGIN, MAX_BATCH_PAYLOAD_SIZE_BYTES, QUEUE_NAME } from './constants';\nimport type { BeaconQueueBatchItemData, BeaconQueueItemData } from './types';\nimport {\n BEACON_PLUGIN_EVENTS_QUEUE_DEBUG,\n BEACON_QUEUE_SEND_ERROR,\n BEACON_QUEUE_DELIVERY_ERROR,\n} from './logMessages';\nimport { RetryQueue } from '../utilities/retryQueue/RetryQueue';\n\nconst pluginName: PluginName = 'BeaconQueue';\n\nconst BeaconQueue = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n dataplaneEventsQueue: {\n /**\n * Initialize the queue for delivery\n * @param state Application state\n * @param httpClient http client instance\n * @param storeManager Store Manager instance\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns BeaconItemsQueue instance\n */\n init(\n state: ApplicationState,\n httpClient: IHttpClient,\n storeManager: IStoreManager,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): IQueue {\n const writeKey = state.lifecycle.writeKey.value as string;\n const dataplaneUrl = state.lifecycle.activeDataplaneUrl.value as string;\n const url = getDeliveryUrl(dataplaneUrl, writeKey);\n\n const finalQOpts: BeaconQueueOpts = getNormalizedBeaconQueueOptions(\n state.loadOptions.value.beaconQueueOptions ?? {},\n );\n\n const queueProcessCallback = (itemData: BeaconQueueBatchItemData, done: DoneCallback) => {\n logger?.debug(BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(BEACON_QUEUE_PLUGIN));\n const currentTime = getCurrentTimeFormatted();\n const finalEvents = itemData.map((queueItemData: BeaconQueueItemData) =>\n eventsDelivery.getFinalEventForDeliveryMutator(queueItemData.event, currentTime),\n );\n const data = getBatchDeliveryPayload(finalEvents, currentTime, logger);\n\n if (data) {\n try {\n const isEnqueuedInBeacon = navigator.sendBeacon(url, data);\n if (!isEnqueuedInBeacon) {\n logger?.error(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN));\n }\n\n done(null, isEnqueuedInBeacon);\n } catch (err) {\n errorHandler?.onError(err, BEACON_QUEUE_PLUGIN, BEACON_QUEUE_DELIVERY_ERROR(url));\n // Remove the item from queue\n done(null);\n }\n } else {\n // Mark the item as done so that it can be removed from the queue\n done(null);\n }\n };\n\n const eventsQueue = new RetryQueue(\n `${QUEUE_NAME}_${writeKey}`,\n {\n batch: {\n enabled: true,\n flushInterval: finalQOpts.flushQueueInterval,\n maxSize: MAX_BATCH_PAYLOAD_SIZE_BYTES, // set the hard limit\n maxItems: finalQOpts.maxItems,\n },\n } as QueueOpts,\n queueProcessCallback,\n storeManager,\n storages.LOCAL_STORAGE,\n logger,\n (itemData: BeaconQueueItemData[]): number => {\n const currentTime = getCurrentTimeFormatted();\n const events = itemData.map((queueItemData: BeaconQueueItemData) => queueItemData.event);\n // type casting to Blob as we know that the event has already been validated prior to enqueue\n return (getBatchDeliveryPayload(events, currentTime, logger) as Blob).size;\n },\n );\n\n return eventsQueue;\n },\n\n /**\n * Add event to the queue for delivery\n * @param state Application state\n * @param eventsQueue IQueue instance\n * @param event RudderEvent object\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns none\n */\n enqueue(\n state: ApplicationState,\n eventsQueue: IQueue,\n event: RudderEvent,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): void {\n // sentAt is only added here for the validation step\n // It'll be updated to the latest timestamp during actual delivery\n event.sentAt = timestamp.getCurrentTimeFormatted();\n eventsDelivery.validateEventPayloadSize(event, logger);\n\n eventsQueue.addItem({\n event,\n } as BeaconQueueItemData);\n },\n },\n});\n\nexport { BeaconQueue };\n\nexport default BeaconQueue;\n","const BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME = 'bugsnag'; // For version 6 and below\nconst BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME = 'Bugsnag';\nconst GLOBAL_LIBRARY_OBJECT_NAMES = [\n BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME,\n BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME,\n];\nconst BUGSNAG_CDN_URL = '__RS_BUGSNAG_SDK_URL__';\nconst ERROR_REPORT_PROVIDER_NAME_BUGSNAG = 'rs-bugsnag';\n// This API key token is parsed in the CI pipeline\nconst API_KEY = '__RS_BUGSNAG_API_KEY__';\nconst BUGSNAG_VALID_MAJOR_VERSION = '6';\nconst SDK_LOAD_POLL_INTERVAL_MS = 100; // ms\nconst MAX_WAIT_FOR_SDK_LOAD_MS = 100 * SDK_LOAD_POLL_INTERVAL_MS; // ms\n\n// Errors from the below scripts are NOT allowed to reach Bugsnag\nconst SDK_FILE_NAME_PREFIXES = (): string[] => [\n 'rsa', // Prefix for all the SDK scripts including plugins and module federated chunks\n];\n\nconst DEV_HOSTS = ['www.test-host.com', 'localhost', '127.0.0.1', '[::1]'];\n\n// List of keys to exclude from the metadata\n// Potential PII or sensitive data\nconst APP_STATE_EXCLUDE_KEYS = [\n 'userId',\n 'userTraits',\n 'groupId',\n 'groupTraits',\n 'anonymousId',\n 'config',\n 'instance', // destination instance objects\n 'eventBuffer', // pre-load event buffer (may contain PII)\n 'traits',\n];\n\nconst BUGSNAG_PLUGIN = 'BugsnagPlugin';\n\nexport {\n BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME,\n BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME,\n GLOBAL_LIBRARY_OBJECT_NAMES,\n BUGSNAG_CDN_URL,\n ERROR_REPORT_PROVIDER_NAME_BUGSNAG,\n API_KEY,\n BUGSNAG_VALID_MAJOR_VERSION,\n MAX_WAIT_FOR_SDK_LOAD_MS,\n SDK_FILE_NAME_PREFIXES,\n SDK_LOAD_POLL_INTERVAL_MS,\n DEV_HOSTS,\n APP_STATE_EXCLUDE_KEYS,\n BUGSNAG_PLUGIN,\n};\n","import type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { CDN_INT_DIR } from '@rudderstack/analytics-js-common/constants/urls';\nimport { json } from '../shared-chunks/common';\nimport type { BugsnagLib } from '../types/plugins';\nimport {\n BUGSNAG_SDK_LOAD_ERROR,\n BUGSNAG_SDK_LOAD_TIMEOUT_ERROR,\n FAILED_TO_FILTER_ERROR,\n} from './logMessages';\nimport {\n API_KEY,\n APP_STATE_EXCLUDE_KEYS,\n BUGSNAG_CDN_URL,\n BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME,\n BUGSNAG_PLUGIN,\n BUGSNAG_VALID_MAJOR_VERSION,\n DEV_HOSTS,\n ERROR_REPORT_PROVIDER_NAME_BUGSNAG,\n GLOBAL_LIBRARY_OBJECT_NAMES,\n MAX_WAIT_FOR_SDK_LOAD_MS,\n SDK_FILE_NAME_PREFIXES,\n SDK_LOAD_POLL_INTERVAL_MS,\n} from './constants';\n\nconst isValidVersion = (globalLibInstance: any) => {\n // For version 7\n // eslint-disable-next-line no-underscore-dangle\n let version = globalLibInstance?._client?._notifier?.version;\n\n // For versions older than 7\n if (!version) {\n const tempInstance = globalLibInstance({\n apiKey: API_KEY,\n releaseStage: 'version-test',\n // eslint-disable-next-line func-names, object-shorthand\n beforeSend: function () {\n return false;\n },\n });\n version = tempInstance.notifier?.version;\n }\n\n return version && version.charAt(0) === BUGSNAG_VALID_MAJOR_VERSION;\n};\n\nconst isRudderSDKError = (event: BugsnagLib.Report) => {\n const errorOrigin = event.stacktrace?.[0]?.file;\n\n if (!errorOrigin || typeof errorOrigin !== 'string') {\n return false;\n }\n\n // Prefix folder for all the destination SDK scripts\n const isDestinationIntegrationBundle = errorOrigin.includes(CDN_INT_DIR);\n const srcFileName = errorOrigin.substring(errorOrigin.lastIndexOf('/') + 1);\n\n return (\n isDestinationIntegrationBundle ||\n SDK_FILE_NAME_PREFIXES().some(\n prefix => srcFileName.startsWith(prefix) && srcFileName.endsWith('.js'),\n )\n );\n};\n\nconst getAppStateForMetadata = (state: ApplicationState): Record | undefined => {\n const stateStr = json.stringifyWithoutCircular(state, false, APP_STATE_EXCLUDE_KEYS);\n return stateStr !== null ? JSON.parse(stateStr) : undefined;\n};\n\nconst enhanceErrorEventMutator = (state: ApplicationState, event: BugsnagLib.Report): void => {\n event.updateMetaData('source', {\n snippetVersion: (globalThis as typeof window).RudderSnippetVersion,\n });\n event.updateMetaData('state', getAppStateForMetadata(state) ?? {});\n\n const { errorMessage } = event;\n // eslint-disable-next-line no-param-reassign\n event.context = errorMessage;\n\n // Hack for easily grouping the script load errors\n // on the dashboard\n if (errorMessage.includes('error in script loading')) {\n // eslint-disable-next-line no-param-reassign\n event.context = 'Script load failures';\n }\n\n // eslint-disable-next-line no-param-reassign\n event.severity = 'error';\n};\n\nconst onError =\n (state: ApplicationState, logger?: ILogger): BugsnagLib.BeforeSend =>\n (event: BugsnagLib.Report): boolean => {\n try {\n // Discard the event if it's not originated at the SDK\n if (!isRudderSDKError(event)) {\n return false;\n }\n\n enhanceErrorEventMutator(state, event);\n\n return true;\n } catch {\n logger?.error(FAILED_TO_FILTER_ERROR(BUGSNAG_PLUGIN));\n // Drop the error event if it couldn't be filtered as\n // it is most likely a non-SDK error\n return false;\n }\n };\n\nconst getReleaseStage = () => {\n const host = globalThis.location.hostname;\n return host && DEV_HOSTS.includes(host) ? 'development' : '__RS_BUGSNAG_RELEASE_STAGE__';\n};\n\nconst getGlobalBugsnagLibInstance = () => (globalThis as any)[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];\n\nconst getNewClient = (state: ApplicationState, logger?: ILogger): BugsnagLib.Client => {\n const globalBugsnagLibInstance = getGlobalBugsnagLibInstance();\n\n const clientConfig: BugsnagLib.IConfig = {\n apiKey: API_KEY,\n appVersion: state.context.app.value.version,\n metaData: {\n SDK: {\n name: 'JS',\n installType: state.context.app.value.installType,\n },\n },\n beforeSend: onError(state, logger),\n autoCaptureSessions: false, // auto capture sessions is disabled\n collectUserIp: false, // collecting user's IP is disabled\n // enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above\n maxEvents: 100,\n maxBreadcrumbs: 40,\n releaseStage: getReleaseStage(),\n user: {\n id: state.source.value?.id || state.lifecycle.writeKey.value,\n },\n logger,\n networkBreadcrumbsEnabled: false,\n };\n\n const client: BugsnagLib.Client = globalBugsnagLibInstance(clientConfig);\n\n return client;\n};\n\nconst isApiKeyValid = (apiKey: string): boolean => {\n const isAPIKeyValid = !(apiKey.startsWith('{{') || apiKey.endsWith('}}') || apiKey.length === 0);\n return isAPIKeyValid;\n};\n\nconst loadBugsnagSDK = (externalSrcLoader: IExternalSrcLoader, logger?: ILogger) => {\n const isNotLoaded = GLOBAL_LIBRARY_OBJECT_NAMES.every(\n globalKeyName => !(globalThis as any)[globalKeyName],\n );\n\n if (!isNotLoaded) {\n return;\n }\n\n externalSrcLoader.loadJSFile({\n url: BUGSNAG_CDN_URL,\n id: ERROR_REPORT_PROVIDER_NAME_BUGSNAG,\n callback: id => {\n if (!id) {\n logger?.error(BUGSNAG_SDK_LOAD_ERROR(BUGSNAG_PLUGIN));\n }\n },\n });\n};\n\nconst initBugsnagClient = (\n state: ApplicationState,\n promiseResolve: (value: BugsnagLib.Client) => void,\n promiseReject: (reason?: Error) => void,\n logger?: ILogger,\n time = 0,\n): void => {\n const globalBugsnagLibInstance = getGlobalBugsnagLibInstance();\n if (typeof globalBugsnagLibInstance === 'function') {\n if (isValidVersion(globalBugsnagLibInstance)) {\n const client = getNewClient(state, logger);\n promiseResolve(client);\n }\n } else if (time >= MAX_WAIT_FOR_SDK_LOAD_MS) {\n promiseReject(new Error(BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(MAX_WAIT_FOR_SDK_LOAD_MS)));\n } else {\n // Try to initialize the client after a delay\n (globalThis as typeof window).setTimeout(\n initBugsnagClient,\n SDK_LOAD_POLL_INTERVAL_MS,\n state,\n promiseResolve,\n promiseReject,\n logger,\n time + SDK_LOAD_POLL_INTERVAL_MS,\n );\n }\n};\n\nexport {\n isValidVersion,\n getNewClient,\n isApiKeyValid,\n loadBugsnagSDK,\n getGlobalBugsnagLibInstance,\n initBugsnagClient,\n getReleaseStage,\n isRudderSDKError,\n enhanceErrorEventMutator,\n onError,\n getAppStateForMetadata,\n};\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst BUGSNAG_API_KEY_VALIDATION_ERROR = (apiKey: string): string =>\n `The Bugsnag API key (${apiKey}) is invalid or not provided.`;\n\nconst BUGSNAG_SDK_LOAD_TIMEOUT_ERROR = (timeout: number): string =>\n `A timeout ${timeout} ms occurred while trying to load the Bugsnag SDK.`;\n\nconst BUGSNAG_SDK_LOAD_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to load the Bugsnag SDK.`;\n\nconst BUGSNAG_SDK_URL_ERROR = 'The Bugsnag SDK URL is invalid. Failed to load the Bugsnag SDK.';\n\nconst FAILED_TO_FILTER_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to filter the error.`;\n\nexport {\n BUGSNAG_API_KEY_VALIDATION_ERROR,\n BUGSNAG_SDK_LOAD_TIMEOUT_ERROR,\n BUGSNAG_SDK_LOAD_ERROR,\n BUGSNAG_SDK_URL_ERROR,\n FAILED_TO_FILTER_ERROR,\n};\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { BugsnagLib } from '../types/plugins';\nimport { BUGSNAG_API_KEY_VALIDATION_ERROR, BUGSNAG_SDK_URL_ERROR } from './logMessages';\nimport { API_KEY } from './constants';\nimport { initBugsnagClient, loadBugsnagSDK, isApiKeyValid } from './utils';\n\nconst pluginName: PluginName = 'Bugsnag';\n\nconst Bugsnag = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n errorReportingProvider: {\n init: (\n state: ApplicationState,\n externalSrcLoader: IExternalSrcLoader,\n logger?: ILogger,\n ): Promise =>\n new Promise((resolve, reject) => {\n // If API key token is not parsed or invalid, don't proceed to initialize the client\n if (!isApiKeyValid(API_KEY)) {\n reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));\n return;\n }\n\n // If SDK URL is empty, don't proceed to initialize the client\n // eslint-disable-next-line no-constant-condition\n if (!'__RS_BUGSNAG_SDK_URL__') {\n reject(new Error(BUGSNAG_SDK_URL_ERROR));\n return;\n }\n\n loadBugsnagSDK(externalSrcLoader, logger);\n\n initBugsnagClient(state, resolve, reject, logger);\n }),\n notify: (\n client: BugsnagLib.Client,\n error: Error,\n state: ApplicationState,\n logger?: ILogger,\n ): void => {\n client.notify(error);\n },\n breadcrumb: (client: BugsnagLib.Client, message: string, logger?: ILogger): void => {\n client?.leaveBreadcrumb(message);\n },\n },\n});\n\nexport { Bugsnag };\n\nexport default Bugsnag;\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { DestinationConfig } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { CUSTOM_CONSENT_MANAGER_PLUGIN } from './constants';\nimport { DESTINATION_CONSENT_STATUS_ERROR } from './logMessages';\n\nconst pluginName: PluginName = 'CustomConsentManager';\n\nconst CustomConsentManager = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n consentManager: {\n init(state: ApplicationState, logger?: ILogger): void {\n // Nothing to initialize\n },\n\n updateConsentsInfo(\n state: ApplicationState,\n storeManager?: IStoreManager,\n logger?: ILogger,\n ): void {\n // Nothing to update. Already provided by the user\n },\n\n isDestinationConsented(\n state: ApplicationState,\n destConfig: DestinationConfig,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): boolean {\n if (!state.consents.initialized.value) {\n return true;\n }\n\n const allowedConsentIds = state.consents.data.value.allowedConsentIds as string[];\n\n try {\n const { consentManagement } = destConfig;\n\n // If the destination does not have consent management config, events should be sent.\n if (!consentManagement) {\n return true;\n }\n\n // Get the corresponding consents for the destination\n const cmpConfig = consentManagement.find(c => c.provider === state.consents.provider.value);\n\n // If there are no consents configured for the destination for the current provider, events should be sent.\n if (!cmpConfig?.consents) {\n return true;\n }\n\n const configuredConsents = cmpConfig.consents.map(c => c.consent.trim()).filter(n => n);\n const resolutionStrategy =\n cmpConfig.resolutionStrategy ?? state.consents.resolutionStrategy.value;\n\n // match the configured consents with user provided consents as per\n // the configured resolution strategy\n const matchPredicate = (consent: string) => allowedConsentIds.includes(consent);\n switch (resolutionStrategy) {\n case 'or':\n return configuredConsents.some(matchPredicate) || configuredConsents.length === 0;\n case 'and':\n default:\n return configuredConsents.every(matchPredicate);\n }\n } catch (err) {\n errorHandler?.onError(err, CUSTOM_CONSENT_MANAGER_PLUGIN, DESTINATION_CONSENT_STATUS_ERROR);\n return true;\n }\n },\n },\n});\n\nexport { CustomConsentManager };\n\nexport default CustomConsentManager;\n","const CUSTOM_CONSENT_MANAGER_PLUGIN = 'CustomConsentManagerPlugin';\n\nexport { CUSTOM_CONSENT_MANAGER_PLUGIN };\n","const DESTINATION_CONSENT_STATUS_ERROR = `Failed to determine the consent status for the destination. Please check the destination configuration and try again.`;\n\nexport { DESTINATION_CONSENT_STATUS_ERROR };\n","const DIR_NAME = 'AdobeAnalytics';\nconst NAME = 'ADOBE_ANALYTICS';\nconst DISPLAY_NAME = 'Adobe Analytics';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n 'Adobe Analytics': NAME,\n ADOBEANALYTICS: NAME,\n 'ADOBE ANALYTICS': NAME,\n [NAME]: NAME,\n AdobeAnalytics: NAME,\n adobeanalytics: NAME,\n 'adobe analytics': NAME,\n 'Adobe analytics': NAME,\n 'adobe Analytics': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Amplitude';\nconst NAME = 'AM';\nconst DISPLAY_NAME = 'Amplitude';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n AMPLITUDE: NAME,\n Amplitude: NAME,\n am: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Appcues';\nconst NAME = 'APPCUES';\nconst DISPLAY_NAME = 'Appcues';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Appcues: NAME,\n 'App Cues': NAME,\n appcues: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'BingAds';\nconst NAME = 'BINGADS';\nconst DISPLAY_NAME = 'Bing Ads';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n BingAds: NAME,\n bingads: NAME,\n 'Bing Ads': NAME,\n 'Bing ads': NAME,\n 'bing Ads': NAME,\n 'bing ads': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Braze';\nconst NAME = 'BRAZE';\nconst DISPLAY_NAME = 'Braze';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Braze: NAME,\n braze: NAME,\n};\n\nconst BrazeOperationString =\n 'BrazeSdkMetadata DeviceProperties Card Card.prototype.dismissCard Card.prototype.removeAllSubscriptions Card.prototype.removeSubscription Card.prototype.subscribeToClickedEvent Card.prototype.subscribeToDismissedEvent Card.fromContentCardsJson Banner CaptionedImage ClassicCard ControlCard ContentCards ContentCards.prototype.getUnviewedCardCount Feed Feed.prototype.getUnreadCardCount ControlMessage InAppMessage InAppMessage.SlideFrom InAppMessage.ClickAction InAppMessage.DismissType InAppMessage.OpenTarget InAppMessage.ImageStyle InAppMessage.Orientation InAppMessage.TextAlignment InAppMessage.CropType InAppMessage.prototype.closeMessage InAppMessage.prototype.removeAllSubscriptions InAppMessage.prototype.removeSubscription InAppMessage.prototype.subscribeToClickedEvent InAppMessage.prototype.subscribeToDismissedEvent InAppMessage.fromJson FullScreenMessage ModalMessage HtmlMessage SlideUpMessage User User.Genders User.NotificationSubscriptionTypes User.prototype.addAlias User.prototype.addToCustomAttributeArray User.prototype.addToSubscriptionGroup User.prototype.getUserId User.prototype.incrementCustomUserAttribute User.prototype.removeFromCustomAttributeArray User.prototype.removeFromSubscriptionGroup User.prototype.setCountry User.prototype.setCustomLocationAttribute User.prototype.setCustomUserAttribute User.prototype.setDateOfBirth User.prototype.setEmail User.prototype.setEmailNotificationSubscriptionType User.prototype.setFirstName User.prototype.setGender User.prototype.setHomeCity User.prototype.setLanguage User.prototype.setLastKnownLocation User.prototype.setLastName User.prototype.setPhoneNumber User.prototype.setPushNotificationSubscriptionType InAppMessageButton InAppMessageButton.prototype.removeAllSubscriptions InAppMessageButton.prototype.removeSubscription InAppMessageButton.prototype.subscribeToClickedEvent automaticallyShowInAppMessages destroyFeed hideContentCards showContentCards showFeed showInAppMessage toggleContentCards toggleFeed changeUser destroy getDeviceId initialize isPushBlocked isPushPermissionGranted isPushSupported logCardClick logCardDismissal logCardImpressions logContentCardImpressions logContentCardsDisplayed logCustomEvent logFeedDisplayed logInAppMessageButtonClick logInAppMessageClick logInAppMessageHtmlClick logInAppMessageImpression logPurchase openSession requestPushPermission removeAllSubscriptions removeSubscription requestContentCardsRefresh requestFeedRefresh requestImmediateDataFlush enableSDK isDisabled setLogger setSdkAuthenticationSignature addSdkMetadata disableSDK subscribeToContentCardsUpdates subscribeToFeedUpdates subscribeToInAppMessage subscribeToSdkAuthenticationFailures toggleLogging unregisterPush wipeData handleBrazeAction';\n\nexport {\n NAME,\n CNameMapping,\n BrazeOperationString,\n DISPLAY_NAME_TO_DIR_NAME_MAP,\n DISPLAY_NAME,\n DIR_NAME,\n};\n","const DIR_NAME = 'Bugsnag';\nconst NAME = 'BUGSNAG';\nconst DISPLAY_NAME = 'Bugsnag';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n bugsnag: NAME,\n Bugsnag: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Chartbeat';\nconst NAME = 'CHARTBEAT';\nconst DISPLAY_NAME = 'Chartbeat';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Chartbeat: NAME,\n chartbeat: NAME,\n 'Chart Beat': NAME,\n 'chart beat': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Clevertap';\nconst NAME = 'CLEVERTAP';\nconst DISPLAY_NAME = 'CleverTap';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Clevertap: NAME,\n clevertap: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Comscore';\nconst NAME = 'COMSCORE';\nconst DISPLAY_NAME = 'Comscore';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Comscore: NAME,\n 'Com Score': NAME,\n 'com Score': NAME,\n 'com score': NAME,\n 'Com score': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Criteo';\nconst NAME = 'CRITEO';\nconst DISPLAY_NAME = 'Criteo';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\n\nconst CNameMapping = {\n [NAME]: NAME,\n Criteo: NAME,\n criteo: NAME,\n};\n\nconst supportedEvents = [\n 'product viewed',\n 'cart viewed',\n 'order completed',\n 'product list viewed',\n 'product added',\n];\n\nexport {\n NAME,\n CNameMapping,\n supportedEvents,\n DISPLAY_NAME_TO_DIR_NAME_MAP,\n DISPLAY_NAME,\n DIR_NAME,\n};\n","const DIR_NAME = 'CustomerIO';\nconst NAME = 'CUSTOMERIO';\nconst DISPLAY_NAME = 'Customer IO';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Customerio: NAME,\n 'Customer.io': NAME,\n 'CUSTOMER.IO': NAME,\n 'customer.io': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Drip';\nconst NAME = 'DRIP';\nconst DISPLAY_NAME = 'Drip';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Drip: NAME,\n drip: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'FacebookPixel';\nconst NAME = 'FACEBOOK_PIXEL';\nconst DISPLAY_NAME = 'Facebook Pixel';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'FB Pixel': NAME,\n 'Facebook Pixel': NAME,\n 'facebook pixel': NAME,\n fbpixel: NAME,\n FBPIXEL: NAME,\n FB_PIXEL: NAME,\n};\n\nconst traitsMapper = [\n {\n destKey: 'external_id',\n sourceKeys: ['userId', 'context.traits.userId', 'context.traits.id', 'anonymousId'],\n },\n {\n destKey: 'em',\n sourceKeys: 'context.traits.email',\n },\n {\n destKey: 'ph',\n sourceKeys: 'context.traits.phone',\n },\n {\n destKey: 'ge',\n sourceKeys: 'context.traits.gender',\n },\n {\n destKey: 'db',\n sourceKeys: 'context.traits.birthday',\n },\n {\n destKey: 'ln',\n sourceKeys: ['context.traits.lastname', 'context.traits.lastName', 'context.traits.last_name'],\n },\n {\n destKey: 'fn',\n sourceKeys: [\n 'context.traits.firstname',\n 'context.traits.firstName',\n 'context.traits.first_name',\n ],\n },\n {\n destKey: 'ct',\n sourceKeys: ['context.traits.address.city', 'context.traits.city'],\n },\n {\n destKey: 'st',\n sourceKeys: ['context.traits.address.state', 'context.traits.state'],\n },\n {\n destKey: 'zp',\n sourceKeys: ['context.traits.address.zip', 'context.traits.zip'],\n },\n {\n destKey: 'country',\n sourceKeys: ['context.traits.address.country', 'context.traits.country'],\n },\n];\n\nconst reserveTraits = [\n 'email',\n 'lastName',\n 'firstName',\n 'phone',\n 'external_id',\n 'city',\n 'birthday',\n 'gender',\n 'street',\n 'zip',\n 'country',\n];\n\nexport {\n traitsMapper,\n CNameMapping,\n NAME,\n reserveTraits,\n DISPLAY_NAME_TO_DIR_NAME_MAP,\n DISPLAY_NAME,\n DIR_NAME,\n};\n","const DIR_NAME = 'Fullstory';\nconst NAME = 'FULLSTORY';\nconst DISPLAY_NAME = 'Fullstory';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Fullstory: NAME,\n FullStory: NAME,\n 'full Story': NAME,\n 'Full Story': NAME,\n 'Full story': NAME,\n 'full story': NAME,\n fullstory: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'GA';\nconst NAME = 'GA';\nconst DISPLAY_NAME = 'Google Analytics';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Google Analytics': NAME,\n GoogleAnalytics: NAME,\n 'GOOGLE ANALYTICS': NAME,\n 'google analytics': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'GA4';\nconst NAME = 'GA4';\nconst DISPLAY_NAME = 'Google Analytics 4 (GA4)';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Google Analytics 4': NAME,\n 'Google analytics 4': NAME,\n 'google analytics 4': NAME,\n 'Google Analytics4': NAME,\n 'Google analytics4': NAME,\n 'google analytics4': NAME,\n 'Google Analytics 4 (GA4)': NAME,\n 'google analytics 4 (ga4)': NAME,\n GoogleAnalytics4: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'GA4_V2';\nconst NAME = 'GA4_V2';\nconst DISPLAY_NAME = 'Google Analytics 4 (GA4) V2';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Google Analytics 4 V2': NAME,\n 'Google analytics 4 V2': NAME,\n 'google analytics 4 V2': NAME,\n 'Google Analytics4 V2': NAME,\n 'Google analytics4 V2': NAME,\n 'google analytics4 V2': NAME,\n 'Google Analytics 4 (GA4) V2': NAME,\n 'google analytics 4 (ga4) V2': NAME,\n GoogleAnalytics4V2: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'GoogleAds';\nconst NAME = 'GOOGLEADS';\nconst DISPLAY_NAME = 'Google Ads';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Google Ads': NAME,\n GoogleAds: NAME,\n 'GOOGLE ADS': NAME,\n 'google ads': NAME,\n googleads: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'GoogleOptimize';\nconst NAME = 'GOOGLE_OPTIMIZE';\nconst DISPLAY_NAME = 'Google Optimize';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Google Optimize': NAME,\n GoogleOptimize: NAME,\n Googleoptimize: NAME,\n GOOGLEOPTIMIZE: NAME,\n 'google optimize': NAME,\n 'Google optimize': NAME,\n 'GOOGLE OPTIMIZE': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'GoogleTagManager';\nconst NAME = 'GTM';\nconst DISPLAY_NAME = 'Google Tag Manager';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Google Tag Manager': NAME,\n 'google tag manager': NAME,\n 'googletag manager': NAME,\n googletagmanager: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Heap';\nconst NAME = 'HEAP';\nconst DISPLAY_NAME = 'Heap.io';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Heap: NAME,\n heap: NAME,\n 'Heap.io': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Hotjar';\nconst NAME = 'HOTJAR';\nconst DISPLAY_NAME = 'Hotjar';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Hotjar: NAME,\n hotjar: NAME,\n 'Hot Jar': NAME,\n 'hot jar': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'HubSpot';\nconst NAME = 'HS';\nconst DISPLAY_NAME = 'HubSpot';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Hubspot: NAME,\n HUBSPOT: NAME,\n 'hub spot': NAME,\n 'Hub Spot': NAME,\n 'Hub spot': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'INTERCOM';\nconst NAME = 'INTERCOM';\nconst DISPLAY_NAME = 'Intercom';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Intercom: NAME,\n intercom: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Keen';\nconst NAME = 'KEEN';\nconst DISPLAY_NAME = 'Keen';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Keen: NAME,\n 'Keen.io': NAME,\n keen: NAME,\n 'keen.io': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Kissmetrics';\nconst NAME = 'KISSMETRICS';\nconst DISPLAY_NAME = 'Kiss Metrics';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Kissmetrics: NAME,\n kissmetrics: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Klaviyo';\nconst NAME = 'KLAVIYO';\nconst DISPLAY_NAME = 'Klaviyo';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Klaviyo: NAME,\n klaviyo: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'LaunchDarkly';\nconst NAME = 'LAUNCHDARKLY';\nconst DISPLAY_NAME = 'LaunchDarkly';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n LaunchDarkly: NAME,\n Launch_Darkly: NAME,\n 'Launch Darkly': NAME,\n launchDarkly: NAME,\n 'launch darkly': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'LinkedInInsightTag';\nconst NAME = 'LINKEDIN_INSIGHT_TAG';\nconst DISPLAY_NAME = 'Linkedin Insight Tag';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'LinkedIn Insight Tag': NAME,\n 'LinkedIn insight tag': NAME,\n 'linkedIn insight tag': NAME,\n Linkedin_insight_tag: NAME,\n LinkedinInsighttag: NAME,\n LinkedinInsightTag: NAME,\n LinkedInInsightTag: NAME,\n Linkedininsighttag: NAME,\n LINKEDININSIGHTTAG: NAME,\n linkedininsighttag: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Lotame';\nconst NAME = 'LOTAME';\nconst DISPLAY_NAME = 'Lotame';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Lotame: NAME,\n lotame: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Lytics';\nconst NAME = 'LYTICS';\nconst DISPLAY_NAME = 'Lytics';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Lytics: NAME,\n lytics: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Mixpanel';\nconst NAME = 'MP';\nconst DISPLAY_NAME = 'Mixpanel';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n MIXPANEL: NAME,\n Mixpanel: NAME,\n 'MIX PANEL': NAME,\n 'Mix panel': NAME,\n 'Mix Panel': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'MoEngage';\nconst NAME = 'MOENGAGE';\nconst DISPLAY_NAME = 'MoEngage';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n MoEngage: NAME,\n moengage: NAME,\n Moengage: NAME,\n 'Mo Engage': NAME,\n 'mo engage': NAME,\n 'Mo engage': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Optimizely';\nconst NAME = 'OPTIMIZELY';\nconst DISPLAY_NAME = 'Optimizely Web';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Optimizely: NAME,\n optimizely: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Pendo';\nconst NAME = 'PENDO';\nconst DISPLAY_NAME = 'Pendo';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Pendo: NAME,\n pendo: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'PinterestTag';\nconst NAME = 'PINTEREST_TAG';\nconst DISPLAY_NAME = 'Pinterest Tag';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n PinterestTag: NAME,\n Pinterest_Tag: NAME,\n PINTERESTTAG: NAME,\n pinterest: NAME,\n PinterestAds: NAME,\n Pinterest_Ads: NAME,\n Pinterest: NAME,\n 'Pinterest Tag': NAME,\n 'Pinterest tag': NAME,\n 'PINTEREST TAG': NAME,\n 'pinterest tag': NAME,\n 'Pinterest Ads': NAME,\n 'Pinterest ads': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'PostAffiliatePro';\nconst NAME = 'POST_AFFILIATE_PRO';\nconst DISPLAY_NAME = 'Post Affiliate Pro';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n PostAffiliatePro: NAME,\n Post_affiliate_pro: NAME,\n 'Post Affiliate Pro': NAME,\n 'Post affiliate pro': NAME,\n 'post affiliate pro': NAME,\n postaffiliatepro: NAME,\n POSTAFFILIATEPRO: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Posthog';\nconst NAME = 'POSTHOG';\nconst DISPLAY_NAME = 'PostHog';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n PostHog: NAME,\n Posthog: NAME,\n posthog: NAME,\n 'Post Hog': NAME,\n 'Post hog': NAME,\n 'post hog': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'ProfitWell';\nconst NAME = 'PROFITWELL';\nconst DISPLAY_NAME = 'ProfitWell';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n ProfitWell: NAME,\n profitwell: NAME,\n Profitwell: NAME,\n 'Profit Well': NAME,\n 'profit well': NAME,\n 'Profit well': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Qualtrics';\nconst NAME = 'QUALTRICS';\nconst DISPLAY_NAME = 'Qualtrics';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Qualtrics: NAME,\n qualtrics: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'QuantumMetric';\nconst NAME = 'QUANTUMMETRIC';\nconst DISPLAY_NAME = 'Quantum Metric';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Quantum Metric': NAME,\n 'quantum Metric': NAME,\n 'quantum metric': NAME,\n QuantumMetric: NAME,\n quantumMetric: NAME,\n quantummetric: NAME,\n Quantum_Metric: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'RedditPixel';\nconst NAME = 'REDDIT_PIXEL';\nconst DISPLAY_NAME = 'Reddit Pixel';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Reddit_Pixel: NAME,\n RedditPixel: NAME,\n REDDITPIXEL: NAME,\n redditpixel: NAME,\n 'Reddit Pixel': NAME,\n 'REDDIT PIXEL': NAME,\n 'reddit pixel': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Sentry';\nconst NAME = 'SENTRY';\nconst DISPLAY_NAME = 'Sentry';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n sentry: NAME,\n Sentry: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'SnapPixel';\nconst NAME = 'SNAP_PIXEL';\nconst DISPLAY_NAME = 'Snap Pixel';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Snap_Pixel: NAME,\n SnapPixel: NAME,\n SNAPPIXEL: NAME,\n snappixel: NAME,\n 'Snap Pixel': NAME,\n 'SNAP PIXEL': NAME,\n 'snap pixel': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'TVSquared';\nconst NAME = 'TVSQUARED';\nconst DISPLAY_NAME = 'TVSquared';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n TVSquared: NAME,\n tvsquared: NAME,\n tvSquared: NAME,\n TvSquared: NAME,\n Tvsquared: NAME,\n 'TV Squared': NAME,\n 'tv squared': NAME,\n 'tv Squared': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'VWO';\nconst NAME = 'VWO';\nconst DISPLAY_NAME = 'VWO';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n VisualWebsiteOptimizer: NAME,\n Visualwebsiteoptimizer: NAME,\n visualwebsiteoptimizer: NAME,\n vwo: NAME,\n 'Visual Website Optimizer': NAME,\n 'Visual website optimizer': NAME,\n 'visual website optimizer': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'GA360';\nconst NAME = 'GA360';\nconst DISPLAY_NAME = 'Google Analytics 360';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Google Analytics 360': NAME,\n 'Google analytics 360': NAME,\n 'google analytics 360': NAME,\n 'Google Analytics360': NAME,\n 'Google analytics360': NAME,\n 'google analytics360': NAME,\n GoogleAnalytics360: NAME,\n 'GA 360': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Adroll';\nconst NAME = 'ADROLL';\nconst DISPLAY_NAME = 'Adroll';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Adroll: NAME,\n 'Ad roll': NAME,\n 'ad roll': NAME,\n adroll: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'DCMFloodlight';\nconst NAME = 'DCM_FLOODLIGHT';\nconst DISPLAY_NAME = 'DCM Floodlight';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'DCM Floodlight': NAME,\n 'dcm floodlight': NAME,\n 'Dcm Floodlight': NAME,\n DCMFloodlight: NAME,\n dcmfloodlight: NAME,\n DcmFloodlight: NAME,\n dcm_floodlight: NAME,\n DCM_Floodlight: NAME,\n};\nconst GTAG = 'globalSiteTag';\n\nexport { NAME, CNameMapping, GTAG, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Matomo';\nconst NAME = 'MATOMO';\nconst DISPLAY_NAME = 'Matomo';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Matomo: NAME,\n matomo: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Vero';\nconst NAME = 'VERO';\nconst DISPLAY_NAME = 'Vero';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Vero: NAME,\n vero: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Mouseflow';\nconst NAME = 'MOUSEFLOW';\nconst DISPLAY_NAME = 'Mouseflow';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Mouseflow: NAME,\n mouseflow: NAME,\n mouseFlow: NAME,\n MouseFlow: NAME,\n 'Mouse flow': NAME,\n 'mouse flow': NAME,\n 'mouse Flow': NAME,\n 'Mouse Flow': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Rockerbox';\nconst NAME = 'ROCKERBOX';\nconst DISPLAY_NAME = 'Rockerbox';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Rockerbox: NAME,\n rockerbox: NAME,\n RockerBox: NAME,\n 'Rocker box': NAME,\n 'rocker box': NAME,\n 'Rocker Box': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'ConvertFlow';\nconst NAME = 'CONVERTFLOW';\nconst DISPLAY_NAME = 'ConvertFlow';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Convertflow: NAME,\n convertflow: NAME,\n convertFlow: NAME,\n ConvertFlow: NAME,\n 'Convert flow': NAME,\n 'convert flow': NAME,\n 'convert Flow': NAME,\n 'Convert Flow': NAME,\n 'CONVERT FLOW': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'SnapEngage';\nconst NAME = 'SNAPENGAGE';\nconst DISPLAY_NAME = 'SnapEngage';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n SnapEngage: NAME,\n Snap_Engage: NAME,\n snapengage: NAME,\n 'SNAP ENGAGE': NAME,\n 'Snap Engage': NAME,\n 'snap engage': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'LiveChat';\nconst NAME = 'LIVECHAT';\nconst DISPLAY_NAME = 'LiveChat';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n LiveChat: NAME,\n Live_Chat: NAME,\n livechat: NAME,\n 'LIVE CHAT': NAME,\n 'Live Chat': NAME,\n 'live chat': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Shynet';\nconst NAME = 'SHYNET';\nconst DISPLAY_NAME = 'Shynet';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n shynet: NAME,\n ShyNet: NAME,\n shyNet: NAME,\n Shynet: NAME,\n 'shy net': NAME,\n 'Shy Net': NAME,\n 'shy Net': NAME,\n 'Shy net': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Woopra';\nconst NAME = 'WOOPRA';\nconst DISPLAY_NAME = 'Woopra';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Woopra: NAME,\n woopra: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'RollBar';\nconst NAME = 'ROLLBAR';\nconst DISPLAY_NAME = 'RollBar';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n RollBar: NAME,\n Roll_Bar: NAME,\n rollbar: NAME,\n Rollbar: NAME,\n 'ROLL BAR': NAME,\n 'Roll Bar': NAME,\n 'roll bar': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'QuoraPixel';\nconst NAME = 'QUORA_PIXEL';\nconst DISPLAY_NAME = 'Quora Pixel';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Quora Pixel': NAME,\n 'Quora pixel': NAME,\n 'QUORA PIXEL': NAME,\n QuoraPixel: NAME,\n Quorapixel: NAME,\n QUORAPIXEL: NAME,\n Quora_Pixel: NAME,\n quora_pixel: NAME,\n Quora: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'June';\nconst NAME = 'JUNE';\nconst DISPLAY_NAME = 'June';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n June: NAME,\n june: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Engage';\nconst NAME = 'ENGAGE';\nconst DISPLAY_NAME = 'Engage';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Engage: NAME,\n engage: NAME,\n};\nconst identifyExcludeFields = [\n 'firstName',\n 'firstname',\n 'first_name',\n 'lastName',\n 'lastname',\n 'last_name',\n 'phone',\n];\nexport {\n NAME,\n CNameMapping,\n identifyExcludeFields,\n DISPLAY_NAME_TO_DIR_NAME_MAP,\n DISPLAY_NAME,\n DIR_NAME,\n};\n","const DIR_NAME = 'Iterable';\nconst NAME = 'ITERABLE';\nconst DISPLAY_NAME = 'Iterable';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Iterable: NAME,\n iterable: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'YandexMetrica';\nconst NAME = 'YANDEX_METRICA';\nconst DISPLAY_NAME = 'Yandex.Metrica';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Yandexmetrica: NAME,\n yandexmetrica: NAME,\n yandexMetrica: NAME,\n YandexMetrica: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Refiner';\nconst NAME = 'REFINER';\nconst DISPLAY_NAME = 'Refiner';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Refiner: NAME,\n refiner: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Qualaroo';\nconst NAME = 'QUALAROO';\nconst DISPLAY_NAME = 'Qualaroo';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Qualaroo: NAME,\n qualaroo: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Podsights';\nconst NAME = 'PODSIGHTS';\nconst DISPLAY_NAME = 'Podsights';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Podsights: NAME,\n PodSights: NAME,\n 'pod Sights': NAME,\n 'Pod Sights': NAME,\n 'pod sights': NAME,\n 'POD SIGHTS': NAME,\n 'Pod sights': NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Axeptio';\nconst NAME = 'AXEPTIO';\nconst DISPLAY_NAME = 'Axeptio';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Axeptio: NAME,\n axeptio: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Satismeter';\nconst NAME = 'SATISMETER';\nconst DISPLAY_NAME = 'Satismeter';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Satismeter: NAME,\n SatisMeter: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'MicrosoftClarity';\nconst NAME = 'MICROSOFT_CLARITY';\nconst DISPLAY_NAME = 'Microsoft Clarity';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Microsoft Clarity': NAME,\n 'Microsoft clarity': NAME,\n 'microsoft clarity': NAME,\n Microsoft_clarity: NAME,\n MicrosoftClarity: NAME,\n MICROSOFTCLARITY: NAME,\n microsoftclarity: NAME,\n microsoftClarity: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Sendinblue';\nconst NAME = 'SENDINBLUE';\nconst DISPLAY_NAME = 'Sendinblue';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Sendinblue: NAME,\n sendinblue: NAME,\n SendinBlue: NAME,\n};\n\nconst excludeReservedTraits = [\n 'firstName',\n 'firstname',\n 'first_name',\n 'lastName',\n 'lastname',\n 'last_name',\n 'phone',\n 'Phone',\n 'email',\n 'Email',\n 'E-mail',\n];\n\nconst excludePageProperties = ['url', 'title', 'path', 'referrer'];\n\nexport {\n NAME,\n CNameMapping,\n excludeReservedTraits,\n excludePageProperties,\n DISPLAY_NAME_TO_DIR_NAME_MAP,\n DISPLAY_NAME,\n DIR_NAME,\n};\n","const DIR_NAME = 'Olark';\nconst NAME = 'OLARK';\nconst DISPLAY_NAME = 'Olark';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Olark: NAME,\n olark: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Lemnisk';\nconst NAME = 'LEMNISK';\nconst DISPLAY_NAME = 'Lemnisk';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n LEMNISK_MARKETING_AUTOMATION: NAME,\n 'Lemnisk Marketing Automation': NAME,\n LemniskMarketingAutomation: NAME,\n lemniskmarketingautomation: NAME,\n lemniskMarketingAutomation: NAME,\n lemnisk: NAME,\n Lemnisk: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'TiktokAds';\nconst NAME = 'TIKTOK_ADS';\nconst DISPLAY_NAME = 'TikTok Ads';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n TiktokAds: NAME,\n 'Tiktok ads': NAME,\n 'Tiktok Ads': NAME,\n 'Tik Tok Ads': NAME,\n 'tik tok ads': NAME,\n tiktokads: NAME,\n};\nconst PARTNER_NAME = 'RudderStack';\n\nconst trackMapping = [\n {\n destKey: 'event_id',\n sourceKeys: ['properties.eventId', 'properties.event_id', 'messageId'],\n },\n {\n destKey: 'test_event_code',\n sourceKeys: 'testEventCode',\n },\n {\n destKey: 'contents',\n sourceKeys: 'properties.contents',\n },\n {\n destKey: 'content_category',\n sourceKeys: 'properties.category',\n },\n {\n destKey: 'status',\n sourceKeys: 'properties.status',\n },\n {\n destKey: 'content_name',\n sourceKeys: 'properties.name',\n },\n {\n destKey: 'content_id',\n sourceKeys: ['properties.product_id', 'properties.productId'],\n },\n {\n destKey: 'content_type',\n sourceKeys: ['properties.contentType', 'properties.content_type'],\n },\n {\n destKey: 'currency',\n sourceKeys: 'properties.currency',\n },\n {\n destKey: 'value',\n sourceKeys: 'properties.value',\n },\n {\n destKey: 'description',\n sourceKeys: 'properties.description',\n },\n {\n destKey: 'email',\n sourceKeys: ['context.traits.email', 'traits.email', 'properties.email'],\n },\n {\n destKey: 'phone',\n sourceKeys: ['context.traits.phone', 'traits.phone', 'properties.phone'],\n },\n];\nconst eventNameMapping = {\n 'product added to wishlist': 'AddToWishlist',\n 'product added': 'AddToCart',\n 'checkout started': 'InitiateCheckout',\n 'payment info entered': 'AddPaymentInfo',\n 'checkout step completed': 'CompletePayment',\n 'order completed': 'PlaceAnOrder',\n viewcontent: 'ViewContent',\n clickbutton: 'ClickButton',\n search: 'Search',\n contact: 'Contact',\n download: 'Download',\n submitform: 'SubmitForm',\n completeregistration: 'CompleteRegistration',\n subscribe: 'Subscribe',\n};\n\nexport {\n NAME,\n CNameMapping,\n PARTNER_NAME,\n trackMapping,\n eventNameMapping,\n DISPLAY_NAME_TO_DIR_NAME_MAP,\n DISPLAY_NAME,\n DIR_NAME,\n};\n","const DIR_NAME = 'ActiveCampaign';\nconst NAME = 'ACTIVE_CAMPAIGN';\nconst DISPLAY_NAME = 'Active Campaign';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n ActiveCampaign: NAME,\n 'Active Campaign': NAME,\n 'ACTIVE CAMPAIGN': NAME,\n [NAME]: NAME,\n activecampaign: NAME,\n 'active campaign': NAME,\n 'Active campaign': NAME,\n 'active Campaign': NAME,\n active_campaign: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Sprig';\nconst NAME = 'SPRIG';\nconst DISPLAY_NAME = 'Sprig';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Sprig: NAME,\n sprig: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'SpotifyPixel';\nconst NAME = 'SPOTIFYPIXEL';\nconst DISPLAY_NAME = 'Spotify Pixel';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Spotify Pixel': NAME,\n 'spotify pixel': NAME,\n SPOTIFY_PIXEL: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'CommandBar';\nconst NAME = 'COMMANDBAR';\nconst DISPLAY_NAME = 'CommandBar';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n 'Command Bar': NAME,\n Commandbar: NAME,\n COMMAND_BAR: NAME,\n commandbar: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","const DIR_NAME = 'Ninetailed';\nconst NAME = 'NINETAILED';\nconst DISPLAY_NAME = 'Ninetailed';\n\nconst DISPLAY_NAME_TO_DIR_NAME_MAP = { [DISPLAY_NAME]: DIR_NAME };\nconst CNameMapping = {\n [NAME]: NAME,\n Ninetailed: NAME,\n ninetailed: NAME,\n NineTailed: NAME,\n};\n\nexport { NAME, CNameMapping, DISPLAY_NAME_TO_DIR_NAME_MAP, DISPLAY_NAME, DIR_NAME };\n","// map of the destination display names to the destination directory names\nimport {\n HubSpotDisplayName,\n HubSpotDirectoryName,\n GADisplayName,\n GADirectoryName,\n HotjarDisplayName,\n HotjarDirectoryName,\n GoogleAdsDisplayName,\n GoogleAdsDirectoryName,\n VWODisplayName,\n VWODirectoryName,\n GoogleTagManagerDisplayName,\n GoogleTagManagerDirectoryName,\n BrazeDisplayName,\n BrazeDirectoryName,\n IntercomDisplayName,\n IntercomDirectoryName,\n KeenDisplayName,\n KeenDirectoryName,\n KissmetricsDisplayName,\n KissmetricsDirectoryName,\n CustomerIODisplayName,\n CustomerIODirectoryName,\n ChartbeatDisplayName,\n ChartbeatDirectoryName,\n ComscoreDisplayName,\n ComscoreDirectoryName,\n FacebookPixelDisplayName,\n FacebookPixelDirectoryName,\n LotameDisplayName,\n LotameDirectoryName,\n OptimizelyDisplayName,\n OptimizelyDirectoryName,\n BugsnagDisplayName,\n BugsnagDirectoryName,\n FullstoryDisplayName,\n FullstoryDirectoryName,\n TVSquaredDisplayName,\n TVSquaredDirectoryName,\n GA4DisplayName,\n GA4DirectoryName,\n GA4_V2DisplayName,\n GA4_V2DirectoryName,\n MoEngageDisplayName,\n MoEngageDirectoryName,\n AmplitudeDisplayName,\n AmplitudeDirectoryName,\n PendoDisplayName,\n PendoDirectoryName,\n LyticsDisplayName,\n LyticsDirectoryName,\n AppcuesDisplayName,\n AppcuesDirectoryName,\n PostHogDisplayName,\n PostHogDirectoryName,\n KlaviyoDisplayName,\n KlaviyoDirectoryName,\n CleverTapDisplayName,\n CleverTapDirectoryName,\n BingAdsDisplayName,\n BingAdsDirectoryName,\n PinterestTagDisplayName,\n PinterestTagDirectoryName,\n AdobeAnalyticsDisplayName,\n AdobeAnalyticsDirectoryName,\n LinkedInInsightTagDisplayName,\n LinkedInInsightTagDirectoryName,\n RedditPixelDisplayName,\n RedditPixelDirectoryName,\n DripDisplayName,\n DripDirectoryName,\n HeapDisplayName,\n HeapDirectoryName,\n CriteoDisplayName,\n CriteoDirectoryName,\n MixpanelDisplayName,\n MixpanelDirectoryName,\n QualtricsDisplayName,\n QualtricsDirectoryName,\n ProfitWellDisplayName,\n ProfitWellDirectoryName,\n SentryDisplayName,\n SentryDirectoryName,\n QuantumMetricDisplayName,\n QuantumMetricDirectoryName,\n SnapPixelDisplayName,\n SnapPixelDirectoryName,\n PostAffiliateProDisplayName,\n PostAffiliateProDirectoryName,\n GoogleOptimizeDisplayName,\n GoogleOptimizeDirectoryName,\n LaunchDarklyDisplayName,\n LaunchDarklyDirectoryName,\n GA360DisplayName,\n GA360DirectoryName,\n AdrollDisplayName,\n AdrollDirectoryName,\n DCMFloodlightDisplayName,\n DCMFloodlightDirectoryName,\n MatomoDisplayName,\n MatomoDirectoryName,\n VeroDisplayName,\n VeroDirectoryName,\n MouseflowDisplayName,\n MouseflowDirectoryName,\n RockerboxDisplayName,\n RockerboxDirectoryName,\n ConvertFlowDisplayName,\n ConvertFlowDirectoryName,\n SnapEngageDisplayName,\n SnapEngageDirectoryName,\n LiveChatDisplayName,\n LiveChatDirectoryName,\n ShynetDisplayName,\n ShynetDirectoryName,\n WoopraDisplayName,\n WoopraDirectoryName,\n RollBarDisplayName,\n RollBarDirectoryName,\n QuoraPixelDisplayName,\n QuoraPixelDirectoryName,\n JuneDisplayName,\n JuneDirectoryName,\n EngageDisplayName,\n EngageDirectoryName,\n IterableDisplayName,\n IterableDirectoryName,\n YandexMetricaDisplayName,\n YandexMetricaDirectoryName,\n RefinerDisplayName,\n RefinerDirectoryName,\n QualarooDisplayName,\n QualarooDirectoryName,\n PodsightsDisplayName,\n PodsightsDirectoryName,\n AxeptioDisplayName,\n AxeptioDirectoryName,\n SatismeterDisplayName,\n SatismeterDirectoryName,\n MicrosoftClarityDisplayName,\n MicrosoftClarityDirectoryName,\n SendinblueDisplayName,\n SendinblueDirectoryName,\n OlarkDisplayName,\n OlarkDirectoryName,\n LemniskDisplayName,\n LemniskDirectoryName,\n TiktokAdsDisplayName,\n TiktokAdsDirectoryName,\n ActiveCampaignDisplayName,\n ActiveCampaignDirectoryName,\n SprigDisplayName,\n SprigDirectoryName,\n SpotifyPixelDisplayName,\n SpotifyPixelDirectoryName,\n CommandBarDisplayName,\n CommandBarDirectoryName,\n NinetailedDisplayName,\n NinetailedDirectoryName,\n} from './destinationNames';\n\n// The destination directory name is used as the destination SDK file name in CDN\nconst destDisplayNamesToFileNamesMap: Record = {\n [HubSpotDisplayName]: HubSpotDirectoryName,\n [GADisplayName]: GADirectoryName,\n [HotjarDisplayName]: HotjarDirectoryName,\n [GoogleAdsDisplayName]: GoogleAdsDirectoryName,\n [VWODisplayName]: VWODirectoryName,\n [GoogleTagManagerDisplayName]: GoogleTagManagerDirectoryName,\n [BrazeDisplayName]: BrazeDirectoryName,\n [IntercomDisplayName]: IntercomDirectoryName,\n [KeenDisplayName]: KeenDirectoryName,\n [KissmetricsDisplayName]: KissmetricsDirectoryName,\n [CustomerIODisplayName]: CustomerIODirectoryName,\n [ChartbeatDisplayName]: ChartbeatDirectoryName,\n [ComscoreDisplayName]: ComscoreDirectoryName,\n [FacebookPixelDisplayName]: FacebookPixelDirectoryName,\n [LotameDisplayName]: LotameDirectoryName,\n [OptimizelyDisplayName]: OptimizelyDirectoryName,\n [BugsnagDisplayName]: BugsnagDirectoryName,\n [FullstoryDisplayName]: FullstoryDirectoryName,\n [TVSquaredDisplayName]: TVSquaredDirectoryName,\n [GA4DisplayName]: GA4DirectoryName,\n [GA4_V2DisplayName]: GA4_V2DirectoryName,\n [MoEngageDisplayName]: MoEngageDirectoryName,\n [AmplitudeDisplayName]: AmplitudeDirectoryName,\n [PendoDisplayName]: PendoDirectoryName,\n [LyticsDisplayName]: LyticsDirectoryName,\n [AppcuesDisplayName]: AppcuesDirectoryName,\n [PostHogDisplayName]: PostHogDirectoryName,\n [KlaviyoDisplayName]: KlaviyoDirectoryName,\n [CleverTapDisplayName]: CleverTapDirectoryName,\n [BingAdsDisplayName]: BingAdsDirectoryName,\n [PinterestTagDisplayName]: PinterestTagDirectoryName,\n [AdobeAnalyticsDisplayName]: AdobeAnalyticsDirectoryName,\n [LinkedInInsightTagDisplayName]: LinkedInInsightTagDirectoryName,\n [RedditPixelDisplayName]: RedditPixelDirectoryName,\n [DripDisplayName]: DripDirectoryName,\n [HeapDisplayName]: HeapDirectoryName,\n [CriteoDisplayName]: CriteoDirectoryName,\n [MixpanelDisplayName]: MixpanelDirectoryName,\n [QualtricsDisplayName]: QualtricsDirectoryName,\n [ProfitWellDisplayName]: ProfitWellDirectoryName,\n [SentryDisplayName]: SentryDirectoryName,\n [QuantumMetricDisplayName]: QuantumMetricDirectoryName,\n [SnapPixelDisplayName]: SnapPixelDirectoryName,\n [PostAffiliateProDisplayName]: PostAffiliateProDirectoryName,\n [GoogleOptimizeDisplayName]: GoogleOptimizeDirectoryName,\n [LaunchDarklyDisplayName]: LaunchDarklyDirectoryName,\n [GA360DisplayName]: GA360DirectoryName,\n [AdrollDisplayName]: AdrollDirectoryName,\n [DCMFloodlightDisplayName]: DCMFloodlightDirectoryName,\n [MatomoDisplayName]: MatomoDirectoryName,\n [VeroDisplayName]: VeroDirectoryName,\n [MouseflowDisplayName]: MouseflowDirectoryName,\n [RockerboxDisplayName]: RockerboxDirectoryName,\n [ConvertFlowDisplayName]: ConvertFlowDirectoryName,\n [SnapEngageDisplayName]: SnapEngageDirectoryName,\n [LiveChatDisplayName]: LiveChatDirectoryName,\n [ShynetDisplayName]: ShynetDirectoryName,\n [WoopraDisplayName]: WoopraDirectoryName,\n [RollBarDisplayName]: RollBarDirectoryName,\n [QuoraPixelDisplayName]: QuoraPixelDirectoryName,\n [JuneDisplayName]: JuneDirectoryName,\n [EngageDisplayName]: EngageDirectoryName,\n [IterableDisplayName]: IterableDirectoryName,\n [YandexMetricaDisplayName]: YandexMetricaDirectoryName,\n [RefinerDisplayName]: RefinerDirectoryName,\n [QualarooDisplayName]: QualarooDirectoryName,\n [PodsightsDisplayName]: PodsightsDirectoryName,\n [AxeptioDisplayName]: AxeptioDirectoryName,\n [SatismeterDisplayName]: SatismeterDirectoryName,\n [MicrosoftClarityDisplayName]: MicrosoftClarityDirectoryName,\n [SendinblueDisplayName]: SendinblueDirectoryName,\n [OlarkDisplayName]: OlarkDirectoryName,\n [LemniskDisplayName]: LemniskDirectoryName,\n [TiktokAdsDisplayName]: TiktokAdsDirectoryName,\n [ActiveCampaignDisplayName]: ActiveCampaignDirectoryName,\n [SprigDisplayName]: SprigDirectoryName,\n [SpotifyPixelDisplayName]: SpotifyPixelDirectoryName,\n [CommandBarDisplayName]: CommandBarDirectoryName,\n [NinetailedDisplayName]: NinetailedDirectoryName,\n};\n\nexport { destDisplayNamesToFileNamesMap };\n","const DEFAULT_INTEGRATIONS_CONFIG = {\n All: true,\n};\n\nexport { DEFAULT_INTEGRATIONS_CONFIG };\n","import type {\n DestinationIntgConfig,\n IntegrationOpts,\n} from '@rudderstack/analytics-js-common/types/Integration';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport { checks } from '../shared-chunks/common';\n\nconst isDestIntgConfigTruthy = (destIntgConfig: DestinationIntgConfig): boolean =>\n !checks.isUndefined(destIntgConfig) && Boolean(destIntgConfig) === true;\n\nconst isDestIntgConfigFalsy = (destIntgConfig: DestinationIntgConfig): boolean =>\n !checks.isUndefined(destIntgConfig) && Boolean(destIntgConfig) === false;\n\n/**\n * Filters the destinations that should not be loaded or forwarded events to based on the integration options (load or events API)\n * @param intgOpts Integration options object\n * @param destinations Destinations array\n * @returns Destinations array filtered based on the integration options\n */\nconst filterDestinations = (intgOpts: IntegrationOpts, destinations: Destination[]) => {\n const allOptVal = intgOpts.All ?? true;\n return destinations.filter(dest => {\n const destDisplayName = dest.displayName;\n let isDestEnabled;\n if (allOptVal) {\n isDestEnabled = true;\n if (isDestIntgConfigFalsy(intgOpts[destDisplayName])) {\n isDestEnabled = false;\n }\n } else {\n isDestEnabled = false;\n if (isDestIntgConfigTruthy(intgOpts[destDisplayName])) {\n isDestEnabled = true;\n }\n }\n return isDestEnabled;\n });\n};\n\nexport { isDestIntgConfigTruthy, isDestIntgConfigFalsy, filterDestinations };\n","const READY_CHECK_TIMEOUT_MS = 11 * 1000; // 11 seconds\nconst SCRIPT_LOAD_TIMEOUT_MS = 10 * 1000; // 10 seconds\n\nconst DEVICE_MODE_DESTINATIONS_PLUGIN = 'DeviceModeDestinationsPlugin';\n\nexport { READY_CHECK_TIMEOUT_MS, DEVICE_MODE_DESTINATIONS_PLUGIN, SCRIPT_LOAD_TIMEOUT_MS };\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst DESTINATION_NOT_SUPPORTED_ERROR = (destUserFriendlyId: string): string =>\n `Destination ${destUserFriendlyId} is not supported.`;\n\nconst DESTINATION_SDK_LOAD_ERROR = (context: string, destUserFriendlyId: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to load script for destination ${destUserFriendlyId}.`;\n\nconst DESTINATION_INIT_ERROR = (destUserFriendlyId: string): string =>\n `Failed to initialize destination ${destUserFriendlyId}.`;\n\nconst DESTINATION_INTEGRATIONS_DATA_ERROR = (destUserFriendlyId: string): string =>\n `Failed to get integrations data for destination ${destUserFriendlyId}.`;\n\nconst DESTINATION_READY_TIMEOUT_ERROR = (timeout: number, destUserFriendlyId: string): string =>\n `A timeout of ${timeout} ms occurred while trying to check the ready status for \"${destUserFriendlyId}\" destination.`;\n\nexport {\n DESTINATION_NOT_SUPPORTED_ERROR,\n DESTINATION_SDK_LOAD_ERROR,\n DESTINATION_INIT_ERROR,\n DESTINATION_INTEGRATIONS_DATA_ERROR,\n DESTINATION_READY_TIMEOUT_ERROR,\n};\n","/* eslint-disable no-param-reassign */\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { clone } from 'ramda';\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport type {\n Destination,\n DeviceModeDestination,\n} from '@rudderstack/analytics-js-common/types/Destination';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IRudderAnalytics } from '@rudderstack/analytics-js-common/types/IRudderAnalytics';\nimport type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport type { ApiCallback, ApiOptions } from '@rudderstack/analytics-js-common/types/EventApi';\nimport type { IntegrationOpts } from '@rudderstack/analytics-js-common/types/Integration';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { IdentifyTraits } from '@rudderstack/analytics-js-common/types/traits';\nimport type { AnonymousIdOptions } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport { checks } from '../shared-chunks/common';\nimport { eventMethodOverloads, destinations } from '../shared-chunks/deviceModeDestinations';\nimport type { DeviceModeDestinationsAnalyticsInstance } from './types';\nimport { DEVICE_MODE_DESTINATIONS_PLUGIN, READY_CHECK_TIMEOUT_MS } from './constants';\nimport {\n DESTINATION_INIT_ERROR,\n DESTINATION_INTEGRATIONS_DATA_ERROR,\n DESTINATION_READY_TIMEOUT_ERROR,\n} from './logMessages';\n\n/**\n * Determines if the destination SDK code is evaluated\n * @param destSDKIdentifier The name of the global globalThis object that contains the destination SDK\n * @param sdkTypeName The name of the destination SDK type\n * @param logger Logger instance\n * @returns true if the destination SDK code is evaluated, false otherwise\n */\nconst isDestinationSDKMounted = (\n destSDKIdentifier: string,\n sdkTypeName: string,\n logger?: ILogger,\n): boolean =>\n Boolean(\n (globalThis as any)[destSDKIdentifier] &&\n (globalThis as any)[destSDKIdentifier][sdkTypeName] &&\n (globalThis as any)[destSDKIdentifier][sdkTypeName].prototype &&\n typeof (globalThis as any)[destSDKIdentifier][sdkTypeName].prototype.constructor !==\n 'undefined',\n );\n\nconst wait = (time: number) =>\n new Promise(resolve => {\n (globalThis as typeof window).setTimeout(resolve, time);\n });\n\nconst createDestinationInstance = (\n destSDKIdentifier: string,\n sdkTypeName: string,\n dest: Destination,\n state: ApplicationState,\n): DeviceModeDestination => {\n const rAnalytics = (globalThis as any).rudderanalytics as IRudderAnalytics;\n const analytics = rAnalytics.getAnalyticsInstance(state.lifecycle.writeKey.value);\n\n const analyticsInstance: DeviceModeDestinationsAnalyticsInstance = {\n loadIntegration: state.nativeDestinations.loadIntegration.value,\n logLevel: state.lifecycle.logLevel.value,\n loadOnlyIntegrations:\n state.consents.postConsent.value?.integrations ??\n state.nativeDestinations.loadOnlyIntegrations.value,\n page: (\n category?: string | Nullable | ApiCallback,\n name?: string | Nullable | Nullable | ApiCallback,\n properties?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) =>\n analytics.page(\n eventMethodOverloads.pageArgumentsToCallOptions(\n category,\n name,\n properties,\n options,\n callback,\n ),\n ),\n track: (\n event: string,\n properties?: Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) =>\n analytics.track(\n eventMethodOverloads.trackArgumentsToCallOptions(event, properties, options, callback),\n ),\n identify: (\n userId: string | number | Nullable,\n traits?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) =>\n analytics.identify(\n eventMethodOverloads.identifyArgumentsToCallOptions(userId, traits, options, callback),\n ),\n alias: (\n to: string,\n from?: string | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) =>\n analytics.alias(\n eventMethodOverloads.aliasArgumentsToCallOptions(to, from, options, callback),\n ),\n group: (\n groupId: string | number | Nullable,\n traits?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) =>\n analytics.group(\n eventMethodOverloads.groupArgumentsToCallOptions(groupId, traits, options, callback),\n ),\n getAnonymousId: (options?: AnonymousIdOptions) => analytics.getAnonymousId(options),\n getUserId: () => analytics.getUserId(),\n getUserTraits: () => analytics.getUserTraits(),\n getGroupId: () => analytics.getGroupId(),\n getGroupTraits: () => analytics.getGroupTraits(),\n getSessionId: () => analytics.getSessionId(),\n };\n\n const deviceModeDestination: DeviceModeDestination = new (globalThis as any)[destSDKIdentifier][\n sdkTypeName\n ](clone(dest.config), analyticsInstance, {\n shouldApplyDeviceModeTransformation: dest.shouldApplyDeviceModeTransformation,\n propagateEventsUntransformedOnError: dest.propagateEventsUntransformedOnError,\n destinationId: dest.id,\n });\n\n return deviceModeDestination;\n};\n\nconst isDestinationReady = (dest: Destination) =>\n new Promise((resolve, reject) => {\n const instance = dest.instance as DeviceModeDestination;\n let handleNumber: number;\n const checkReady = () => {\n if (instance.isLoaded() && (!instance.isReady || instance.isReady())) {\n resolve(true);\n } else {\n handleNumber = globalThis.requestAnimationFrame(checkReady);\n }\n };\n checkReady();\n setTimeout(() => {\n globalThis.cancelAnimationFrame(handleNumber);\n reject(\n new Error(DESTINATION_READY_TIMEOUT_ERROR(READY_CHECK_TIMEOUT_MS, dest.userFriendlyId)),\n );\n }, READY_CHECK_TIMEOUT_MS);\n });\n\n/**\n * Extracts the integration config, if any, from the given destination\n * and merges it with the current integrations config\n * @param dest Destination object\n * @param curDestIntgConfig Current destinations integration config\n * @param logger Logger object\n * @returns Combined destinations integrations config\n */\nconst getCumulativeIntegrationsConfig = (\n dest: Destination,\n curDestIntgConfig: IntegrationOpts,\n errorHandler?: IErrorHandler,\n): IntegrationOpts => {\n let integrationsConfig: IntegrationOpts = curDestIntgConfig;\n if (checks.isFunction(dest.instance?.getDataForIntegrationsObject)) {\n try {\n integrationsConfig = mergeDeepRight(\n curDestIntgConfig,\n dest.instance?.getDataForIntegrationsObject(),\n );\n } catch (err) {\n errorHandler?.onError(\n err,\n DEVICE_MODE_DESTINATIONS_PLUGIN,\n DESTINATION_INTEGRATIONS_DATA_ERROR(dest.userFriendlyId),\n );\n }\n }\n return integrationsConfig;\n};\n\nconst initializeDestination = (\n dest: Destination,\n state: ApplicationState,\n destSDKIdentifier: string,\n sdkTypeName: string,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n) => {\n try {\n const initializedDestination = clone(dest);\n const destInstance = createDestinationInstance(destSDKIdentifier, sdkTypeName, dest, state);\n initializedDestination.instance = destInstance;\n\n destInstance.init();\n\n isDestinationReady(initializedDestination)\n .then(() => {\n // Collect the integrations data for the hybrid mode destinations\n if (destinations.isHybridModeDestination(initializedDestination)) {\n state.nativeDestinations.integrationsConfig.value = getCumulativeIntegrationsConfig(\n initializedDestination,\n state.nativeDestinations.integrationsConfig.value,\n errorHandler,\n );\n }\n\n state.nativeDestinations.initializedDestinations.value = [\n ...state.nativeDestinations.initializedDestinations.value,\n initializedDestination,\n ];\n })\n .catch(err => {\n state.nativeDestinations.failedDestinations.value = [\n ...state.nativeDestinations.failedDestinations.value,\n dest,\n ];\n\n // The error message is already formatted in the isDestinationReady function\n logger?.error(err);\n });\n } catch (err) {\n state.nativeDestinations.failedDestinations.value = [\n ...state.nativeDestinations.failedDestinations.value,\n dest,\n ];\n\n errorHandler?.onError(\n err,\n DEVICE_MODE_DESTINATIONS_PLUGIN,\n DESTINATION_INIT_ERROR(dest.userFriendlyId),\n );\n }\n};\n\nexport {\n isDestinationSDKMounted,\n wait,\n createDestinationInstance,\n isDestinationReady,\n getCumulativeIntegrationsConfig,\n initializeDestination,\n};\n","/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type {\n IPluginsManager,\n PluginName,\n} from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport { destDisplayNamesToFileNamesMap } from '@rudderstack/analytics-js-common/constants/integrations/destDisplayNamesToFileNamesMap';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport { clone } from 'ramda';\nimport { DEFAULT_INTEGRATIONS_CONFIG } from '@rudderstack/analytics-js-common/constants/integrationsConfig';\nimport { isDestinationSDKMounted, initializeDestination } from './utils';\nimport { DEVICE_MODE_DESTINATIONS_PLUGIN, SCRIPT_LOAD_TIMEOUT_MS } from './constants';\nimport { DESTINATION_NOT_SUPPORTED_ERROR, DESTINATION_SDK_LOAD_ERROR } from './logMessages';\nimport { destinationUtils } from '../shared-chunks/deviceModeDestinations';\n\nconst pluginName: PluginName = 'DeviceModeDestinations';\n\nconst DeviceModeDestinations = (): ExtensionPlugin => ({\n name: pluginName,\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n nativeDestinations: {\n setActiveDestinations(\n state: ApplicationState,\n pluginsManager: IPluginsManager,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): void {\n // Normalize the integration options from the load API call\n state.nativeDestinations.loadOnlyIntegrations.value =\n clone(state.loadOptions.value.integrations) ?? DEFAULT_INTEGRATIONS_CONFIG;\n\n state.nativeDestinations.loadIntegration.value = state.loadOptions.value\n .loadIntegration as boolean;\n\n // Filter destination that doesn't have mapping config-->Integration names\n const configSupportedDestinations =\n state.nativeDestinations.configuredDestinations.value.filter((configDest: Destination) => {\n if (destDisplayNamesToFileNamesMap[configDest.displayName]) {\n return true;\n }\n\n errorHandler?.onError(\n new Error(DESTINATION_NOT_SUPPORTED_ERROR(configDest.userFriendlyId)),\n DEVICE_MODE_DESTINATIONS_PLUGIN,\n );\n return false;\n });\n\n // Filter destinations that are disabled through load or consent API options\n const destinationsToLoad = destinationUtils.filterDestinations(\n state.consents.postConsent.value?.integrations ??\n state.nativeDestinations.loadOnlyIntegrations.value,\n configSupportedDestinations,\n );\n\n const consentedDestinations = destinationsToLoad.filter(\n dest =>\n // if consent manager is not configured, then default to load the destination\n pluginsManager.invokeSingle(\n `consentManager.isDestinationConsented`,\n state,\n dest.config,\n errorHandler,\n logger,\n ) ?? true,\n );\n\n state.nativeDestinations.activeDestinations.value = consentedDestinations;\n },\n\n load(\n state: ApplicationState,\n externalSrcLoader: IExternalSrcLoader,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n externalScriptOnLoad?: (id?: string) => unknown,\n ) {\n const integrationsCDNPath = state.lifecycle.integrationsCDNPath.value;\n const activeDestinations = state.nativeDestinations.activeDestinations.value;\n\n activeDestinations.forEach((dest: Destination) => {\n const sdkName = destDisplayNamesToFileNamesMap[dest.displayName];\n const destSDKIdentifier = `${sdkName}_RS`; // this is the name of the object loaded on the window\n\n const sdkTypeName = sdkName;\n if (sdkTypeName && !isDestinationSDKMounted(destSDKIdentifier, sdkTypeName, logger)) {\n const destSdkURL = `${integrationsCDNPath}/${sdkName}.min.js`;\n externalSrcLoader.loadJSFile({\n url: destSdkURL,\n id: dest.userFriendlyId,\n callback:\n externalScriptOnLoad ??\n ((id?: string) => {\n if (!id) {\n logger?.error(\n DESTINATION_SDK_LOAD_ERROR(\n DEVICE_MODE_DESTINATIONS_PLUGIN,\n dest.userFriendlyId,\n ),\n );\n state.nativeDestinations.failedDestinations.value = [\n ...state.nativeDestinations.failedDestinations.value,\n dest,\n ];\n } else {\n initializeDestination(\n dest,\n state,\n destSDKIdentifier,\n sdkTypeName,\n errorHandler,\n logger,\n );\n }\n }),\n timeout: SCRIPT_LOAD_TIMEOUT_MS,\n });\n } else if (sdkTypeName) {\n initializeDestination(dest, state, destSDKIdentifier, sdkTypeName, errorHandler, logger);\n } else {\n logger?.error(\n DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN, dest.displayName),\n );\n }\n });\n },\n },\n});\n\nexport { DeviceModeDestinations };\n\nexport default DeviceModeDestinations;\n","const DEFAULT_TRANSFORMATION_QUEUE_OPTIONS = {\n minRetryDelay: 500,\n backoffFactor: 2,\n maxAttempts: 3,\n};\n\nconst REQUEST_TIMEOUT_MS = 10 * 1000; // 10 seconds\n\nconst QUEUE_NAME = 'rudder';\nconst DMT_PLUGIN = 'DeviceModeTransformationPlugin';\n\nexport { DEFAULT_TRANSFORMATION_QUEUE_OPTIONS, REQUEST_TIMEOUT_MS, QUEUE_NAME, DMT_PLUGIN };\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR = (\n context: string,\n displayName: string,\n reason: string,\n action: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Event transformation unsuccessful for destination \"${displayName}\". Reason: ${reason}. ${action}.`;\n\nconst DMT_REQUEST_FAILED_ERROR = (\n context: string,\n displayName: string,\n status: number | undefined,\n action: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}[Destination: ${displayName}].Transformation request failed with status: ${status}. Retries exhausted. ${action}.`;\n\nconst DMT_EXCEPTION = (displayName: string): string => `[Destination:${displayName}].`;\nconst DMT_SERVER_ACCESS_DENIED_WARNING = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Transformation server access is denied. The configuration data seems to be out of sync. Sending untransformed event to the destination.`;\n\nexport {\n DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR,\n DMT_REQUEST_FAILED_ERROR,\n DMT_EXCEPTION,\n DMT_SERVER_ACCESS_DENIED_WARNING,\n};\n","import type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { isNonEmptyObject } from '@rudderstack/analytics-js-common/utilities/object';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { IPluginsManager } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type {\n TransformationRequestPayload,\n TransformationResponsePayload,\n TransformedBatch,\n TransformedEvent,\n TransformedPayload,\n} from './types';\nimport { DMT_PLUGIN } from './constants';\nimport {\n DMT_EXCEPTION,\n DMT_REQUEST_FAILED_ERROR,\n DMT_SERVER_ACCESS_DENIED_WARNING,\n DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR,\n} from './logMessages';\n\n/**\n * A helper function that will take rudderEvent and generate\n * a batch payload that will be sent to transformation server\n *\n */\nconst createPayload = (\n event: RudderEvent,\n destinationIds: string[],\n token: Nullable,\n): TransformationRequestPayload => {\n const orderNo = Date.now();\n const payload = {\n metadata: {\n 'Custom-Authorization': token,\n },\n batch: [\n {\n orderNo,\n destinationIds,\n event,\n },\n ],\n };\n return payload;\n};\n\nconst sendTransformedEventToDestinations = (\n state: ApplicationState,\n pluginsManager: IPluginsManager,\n destinationIds: string[],\n result: any,\n status: number | undefined,\n event: RudderEvent,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n) => {\n const NATIVE_DEST_EXT_POINT = 'destinationsEventsQueue.enqueueEventToDestination';\n const ACTION_TO_SEND_UNTRANSFORMED_EVENT = 'Sending untransformed event';\n const ACTION_TO_DROP_EVENT = 'Dropping the event';\n const destinations: Destination[] = state.nativeDestinations.initializedDestinations.value.filter(\n d => d && destinationIds.includes(d.id),\n );\n\n destinations.forEach(dest => {\n try {\n const eventsToSend: TransformedEvent[] = [];\n switch (status) {\n case 200: {\n const response: TransformationResponsePayload = JSON.parse(result);\n const destTransformedResult = response.transformedBatch.find(\n (e: TransformedBatch) => e.id === dest.id,\n );\n destTransformedResult?.payload.forEach((tEvent: TransformedPayload) => {\n if (tEvent.status === '200') {\n eventsToSend.push(tEvent.event);\n } else {\n let reason = 'Unknown';\n if (tEvent.status === '410') {\n reason = 'Transformation is not available';\n }\n\n let action = ACTION_TO_DROP_EVENT;\n if (dest.propagateEventsUntransformedOnError === true) {\n action = ACTION_TO_SEND_UNTRANSFORMED_EVENT;\n eventsToSend.push(event);\n logger?.warn(\n DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(\n DMT_PLUGIN,\n dest.displayName,\n reason,\n action,\n ),\n );\n } else {\n logger?.error(\n DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(\n DMT_PLUGIN,\n dest.displayName,\n reason,\n action,\n ),\n );\n }\n }\n });\n\n break;\n }\n // Transformation server access denied\n case 404: {\n logger?.warn(DMT_SERVER_ACCESS_DENIED_WARNING(DMT_PLUGIN));\n eventsToSend.push(event);\n break;\n }\n default: {\n if (dest.propagateEventsUntransformedOnError === true) {\n logger?.warn(\n DMT_REQUEST_FAILED_ERROR(\n DMT_PLUGIN,\n dest.displayName,\n status,\n ACTION_TO_SEND_UNTRANSFORMED_EVENT,\n ),\n );\n eventsToSend.push(event);\n } else {\n logger?.error(\n DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN, dest.displayName, status, ACTION_TO_DROP_EVENT),\n );\n }\n break;\n }\n }\n eventsToSend?.forEach((tEvent?: TransformedEvent) => {\n if (isNonEmptyObject(tEvent)) {\n pluginsManager.invokeSingle(\n NATIVE_DEST_EXT_POINT,\n state,\n tEvent,\n dest,\n errorHandler,\n logger,\n );\n }\n });\n } catch (e) {\n errorHandler?.onError(e, DMT_PLUGIN, DMT_EXCEPTION(dest.displayName));\n }\n });\n};\n\nexport { createPayload, sendTransformedEventToDestinations };\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type {\n IPluginsManager,\n PluginName,\n} from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport { MEMORY_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport { isErrRetryable } from '@rudderstack/analytics-js-common/utilities/http';\nimport { createPayload, sendTransformedEventToDestinations } from './utilities';\nimport { getDMTDeliveryPayload } from '../utilities/eventsDelivery';\nimport { DEFAULT_TRANSFORMATION_QUEUE_OPTIONS, QUEUE_NAME, REQUEST_TIMEOUT_MS } from './constants';\nimport { RetryQueue } from '../utilities/retryQueue/RetryQueue';\nimport type { DoneCallback, IQueue } from '../types/plugins';\nimport type { TransformationQueueItemData } from './types';\n\nconst pluginName: PluginName = 'DeviceModeTransformation';\n\nconst DeviceModeTransformation = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n transformEvent: {\n init(\n state: ApplicationState,\n pluginsManager: IPluginsManager,\n httpClient: IHttpClient,\n storeManager: IStoreManager,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ) {\n const writeKey = state.lifecycle.writeKey.value as string;\n httpClient.setAuthHeader(writeKey);\n\n const eventsQueue = new RetryQueue(\n // adding write key to the queue name to avoid conflicts\n `${QUEUE_NAME}_${writeKey}`,\n DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,\n (\n item: TransformationQueueItemData,\n done: DoneCallback,\n attemptNumber?: number,\n maxRetryAttempts?: number,\n ) => {\n const payload = createPayload(item.event, item.destinationIds, item.token);\n\n httpClient.request({\n url: `${state.lifecycle.activeDataplaneUrl.value}/transform`,\n options: {\n method: 'POST',\n body: getDMTDeliveryPayload(payload) as string,\n sendRawData: true,\n },\n isRawResponse: true,\n timeout: REQUEST_TIMEOUT_MS,\n callback: (result, details) => {\n // null means item will not be requeued\n const queueErrResp = isErrRetryable(details) ? details : null;\n\n if (!queueErrResp || attemptNumber === maxRetryAttempts) {\n sendTransformedEventToDestinations(\n state,\n pluginsManager,\n item.destinationIds,\n result,\n details.error?.status ?? details.response?.status,\n item.event,\n errorHandler,\n logger,\n );\n }\n\n done(queueErrResp, result);\n },\n });\n },\n storeManager,\n MEMORY_STORAGE,\n );\n\n return eventsQueue;\n },\n\n enqueue(\n state: ApplicationState,\n eventsQueue: IQueue,\n event: RudderEvent,\n destinations: Destination[],\n ) {\n const destinationIds = destinations.map(d => d.id);\n eventsQueue.addItem({\n event,\n destinationIds,\n token: state.session.authToken.value,\n } as TransformationQueueItemData);\n },\n },\n});\n\nexport { DeviceModeTransformation };\n\nexport default DeviceModeTransformation;\n","const FAILED_REQUEST_ERR_MSG_PREFIX = 'The request failed';\nconst ERROR_MESSAGES_TO_BE_FILTERED = [FAILED_REQUEST_ERR_MSG_PREFIX];\n\nexport { FAILED_REQUEST_ERR_MSG_PREFIX, ERROR_MESSAGES_TO_BE_FILTERED };\n","// Errors from the below scripts are NOT allowed to reach Bugsnag\nconst SDK_FILE_NAME_PREFIXES = (): string[] => [\n 'rsa', // Prefix for all the SDK scripts including plugins and module federated chunks\n];\n\nconst DEV_HOSTS = ['www.test-host.com', 'localhost', '127.0.0.1', '[::1]'];\n\n// List of keys to exclude from the metadata\n// Potential PII or sensitive data\nconst APP_STATE_EXCLUDE_KEYS = [\n 'userId',\n 'userTraits',\n 'groupId',\n 'groupTraits',\n 'anonymousId',\n 'config',\n 'instance', // destination instance objects\n 'eventBuffer', // pre-load event buffer (may contain PII)\n 'traits',\n];\nconst REQUEST_TIMEOUT_MS = 10 * 1000; // 10 seconds\nconst NOTIFIER_NAME = 'RudderStack JavaScript SDK Error Notifier';\nconst SDK_GITHUB_URL = 'https://github.com/rudderlabs/rudder-sdk-js';\nconst SOURCE_NAME = 'js';\nconst ERROR_REPORTING_PLUGIN = 'ErrorReportingPlugin';\n\nexport {\n SDK_FILE_NAME_PREFIXES,\n DEV_HOSTS,\n APP_STATE_EXCLUDE_KEYS,\n REQUEST_TIMEOUT_MS,\n NOTIFIER_NAME,\n SDK_GITHUB_URL,\n SOURCE_NAME,\n ERROR_REPORTING_PLUGIN,\n};\n","import type {\n ApplicationState,\n Breadcrumb,\n BreadcrumbMetaData,\n} from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport {\n ErrorType,\n type ErrorState,\n type SDKError,\n} from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport { CDN_INT_DIR } from '@rudderstack/analytics-js-common/constants/urls';\nimport { clone } from 'ramda';\nimport type {\n ErrorEventPayload,\n MetricServicePayload,\n} from '@rudderstack/analytics-js-common/types/Metrics';\nimport { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId';\nimport { METRICS_PAYLOAD_VERSION } from '@rudderstack/analytics-js-common/constants/metrics';\nimport { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport { ERROR_MESSAGES_TO_BE_FILTERED } from '@rudderstack/analytics-js-common/constants/errors';\nimport {\n APP_STATE_EXCLUDE_KEYS,\n DEV_HOSTS,\n SDK_FILE_NAME_PREFIXES,\n SDK_GITHUB_URL,\n NOTIFIER_NAME,\n SOURCE_NAME,\n} from './constants';\nimport { json } from '../shared-chunks/common';\nimport type { ErrorFormat } from './event/event';\n\nconst getConfigForPayloadCreation = (err: SDKError, errorType: string) => {\n switch (errorType) {\n case ErrorType.UNHANDLEDEXCEPTION: {\n const { error } = err as ErrorEvent;\n return {\n component: 'unhandledException handler',\n tolerateNonErrors: true,\n errorFramesToSkip: 1,\n normalizedError: error || err,\n };\n }\n case ErrorType.UNHANDLEDREJECTION: {\n const error = err as PromiseRejectionEvent;\n return {\n component: 'unhandledrejection handler',\n tolerateNonErrors: false,\n errorFramesToSkip: 1,\n normalizedError: error.reason,\n };\n }\n case ErrorType.HANDLEDEXCEPTION:\n default:\n return {\n component: 'notify()',\n tolerateNonErrors: true,\n errorFramesToSkip: 2,\n normalizedError: err,\n };\n }\n};\n\nconst createNewBreadcrumb = (message: string, metaData?: BreadcrumbMetaData): Breadcrumb => ({\n type: 'manual',\n name: message,\n timestamp: new Date(),\n metaData: metaData ?? {},\n});\n\nconst getReleaseStage = () => {\n const host = globalThis.location.hostname;\n return host && DEV_HOSTS.includes(host) ? 'development' : '__RS_BUGSNAG_RELEASE_STAGE__';\n};\n\nconst getAppStateForMetadata = (state: ApplicationState): Record => {\n const stateStr = json.stringifyWithoutCircular(state, false, APP_STATE_EXCLUDE_KEYS);\n return stateStr !== null ? JSON.parse(stateStr) : {};\n};\n\nconst getURLWithoutQueryString = () => {\n const url = globalThis.location.href.split('?');\n return url[0];\n};\n\nconst getErrorContext = (event: any) => {\n const { message } = event;\n let context = message;\n\n // Hack for easily grouping the script load errors\n // on the dashboard\n if (message.includes('Error in loading a third-party script')) {\n context = 'Script load failures';\n }\n return context;\n};\n\nconst getBugsnagErrorEvent = (\n payload: ErrorFormat,\n errorState: ErrorState,\n state: ApplicationState,\n): ErrorEventPayload => ({\n notifier: {\n name: NOTIFIER_NAME,\n version: state.context.app.value.version,\n url: SDK_GITHUB_URL,\n },\n events: [\n {\n payloadVersion: '5',\n exceptions: clone(payload.errors),\n severity: errorState.severity,\n unhandled: errorState.unhandled,\n severityReason: errorState.severityReason,\n app: {\n version: state.context.app.value.version,\n releaseStage: getReleaseStage(),\n },\n device: {\n locale: state.context.locale.value ?? undefined,\n userAgent: state.context.userAgent.value ?? undefined,\n time: new Date(),\n },\n request: {\n url: getURLWithoutQueryString() as string,\n clientIp: '[NOT COLLECTED]',\n },\n breadcrumbs: clone(state.reporting.breadcrumbs.value),\n context: getErrorContext(payload.errors[0]),\n metaData: {\n sdk: {\n name: 'JS',\n installType: state.context.app.value.installType,\n },\n state: getAppStateForMetadata(state) ?? {},\n source: {\n snippetVersion: (globalThis as typeof window).RudderSnippetVersion,\n },\n },\n user: {\n id: state.source.value?.id ?? (state.lifecycle.writeKey.value as string),\n },\n },\n ],\n});\n\n/**\n * A function to determine whether the error should be promoted to notify or not\n * @param {Error} error\n * @returns\n */\nconst isAllowedToBeNotified = (event: any) => {\n const errorMessage = event.message;\n if (errorMessage && typeof errorMessage === 'string') {\n return !ERROR_MESSAGES_TO_BE_FILTERED.some(e => errorMessage.includes(e));\n }\n return true;\n};\n\n/**\n * A function to determine if the error is from Rudder SDK\n * @param {Error} event\n * @returns\n */\nconst isRudderSDKError = (event: any) => {\n const errorOrigin = event.stacktrace?.[0]?.file;\n\n if (!errorOrigin || typeof errorOrigin !== 'string') {\n return false;\n }\n\n const srcFileName = errorOrigin.substring(errorOrigin.lastIndexOf('/') + 1);\n const paths = errorOrigin.split('/');\n // extract the parent folder name from the error origin file path\n // Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js\n const parentFolderName = paths[paths.length - 2];\n\n return (\n parentFolderName === CDN_INT_DIR ||\n SDK_FILE_NAME_PREFIXES().some(\n prefix => srcFileName.startsWith(prefix) && srcFileName.endsWith('.js'),\n )\n );\n};\n\nconst getErrorDeliveryPayload = (payload: ErrorEventPayload, state: ApplicationState): string => {\n const data = {\n version: METRICS_PAYLOAD_VERSION,\n message_id: generateUUID(),\n source: {\n name: SOURCE_NAME,\n sdk_version: state.context.app.value.version,\n write_key: state.lifecycle.writeKey.value as string,\n install_type: state.context.app.value.installType,\n },\n errors: payload,\n };\n return stringifyWithoutCircular(data) as string;\n};\n\nexport {\n getConfigForPayloadCreation,\n createNewBreadcrumb,\n getReleaseStage,\n getAppStateForMetadata,\n getBugsnagErrorEvent,\n getURLWithoutQueryString,\n isRudderSDKError,\n getErrorDeliveryPayload,\n getErrorContext,\n isAllowedToBeNotified,\n};\n","const METRICS_PAYLOAD_VERSION = '1';\n\nexport { METRICS_PAYLOAD_VERSION };\n","(function(root, factory) {\n 'use strict';\n // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.\n\n /* istanbul ignore next */\n if (typeof define === 'function' && define.amd) {\n define('error-stack-parser', ['stackframe'], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory(require('stackframe'));\n } else {\n root.ErrorStackParser = factory(root.StackFrame);\n }\n}(this, function ErrorStackParser(StackFrame) {\n 'use strict';\n\n var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\\S+:\\d+/;\n var CHROME_IE_STACK_REGEXP = /^\\s*at .*(\\S+:\\d+|\\(native\\))/m;\n var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\\[native code])?$/;\n\n return {\n /**\n * Given an Error object, extract the most information from it.\n *\n * @param {Error} error object\n * @return {Array} of StackFrames\n */\n parse: function ErrorStackParser$$parse(error) {\n if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') {\n return this.parseOpera(error);\n } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) {\n return this.parseV8OrIE(error);\n } else if (error.stack) {\n return this.parseFFOrSafari(error);\n } else {\n throw new Error('Cannot parse given Error object');\n }\n },\n\n // Separate line and column numbers from a string of the form: (URI:Line:Column)\n extractLocation: function ErrorStackParser$$extractLocation(urlLike) {\n // Fail-fast but return locations like \"(native)\"\n if (urlLike.indexOf(':') === -1) {\n return [urlLike];\n }\n\n var regExp = /(.+?)(?::(\\d+))?(?::(\\d+))?$/;\n var parts = regExp.exec(urlLike.replace(/[()]/g, ''));\n return [parts[1], parts[2] || undefined, parts[3] || undefined];\n },\n\n parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) {\n var filtered = error.stack.split('\\n').filter(function(line) {\n return !!line.match(CHROME_IE_STACK_REGEXP);\n }, this);\n\n return filtered.map(function(line) {\n if (line.indexOf('(eval ') > -1) {\n // Throw away eval information until we implement stacktrace.js/stackframe#8\n line = line.replace(/eval code/g, 'eval').replace(/(\\(eval at [^()]*)|(,.*$)/g, '');\n }\n var sanitizedLine = line.replace(/^\\s+/, '').replace(/\\(eval code/g, '(').replace(/^.*?\\s+/, '');\n\n // capture and preseve the parenthesized location \"(/foo/my bar.js:12:87)\" in\n // case it has spaces in it, as the string is split on \\s+ later on\n var location = sanitizedLine.match(/ (\\(.+\\)$)/);\n\n // remove the parenthesized location from the line, if it was matched\n sanitizedLine = location ? sanitizedLine.replace(location[0], '') : sanitizedLine;\n\n // if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine\n // because this line doesn't have function name\n var locationParts = this.extractLocation(location ? location[1] : sanitizedLine);\n var functionName = location && sanitizedLine || undefined;\n var fileName = ['eval', ''].indexOf(locationParts[0]) > -1 ? undefined : locationParts[0];\n\n return new StackFrame({\n functionName: functionName,\n fileName: fileName,\n lineNumber: locationParts[1],\n columnNumber: locationParts[2],\n source: line\n });\n }, this);\n },\n\n parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) {\n var filtered = error.stack.split('\\n').filter(function(line) {\n return !line.match(SAFARI_NATIVE_CODE_REGEXP);\n }, this);\n\n return filtered.map(function(line) {\n // Throw away eval information until we implement stacktrace.js/stackframe#8\n if (line.indexOf(' > eval') > -1) {\n line = line.replace(/ line (\\d+)(?: > eval line \\d+)* > eval:\\d+:\\d+/g, ':$1');\n }\n\n if (line.indexOf('@') === -1 && line.indexOf(':') === -1) {\n // Safari eval frames only have function names and nothing else\n return new StackFrame({\n functionName: line\n });\n } else {\n var functionNameRegex = /((.*\".+\"[^@]*)?[^@]*)(?:@)/;\n var matches = line.match(functionNameRegex);\n var functionName = matches && matches[1] ? matches[1] : undefined;\n var locationParts = this.extractLocation(line.replace(functionNameRegex, ''));\n\n return new StackFrame({\n functionName: functionName,\n fileName: locationParts[0],\n lineNumber: locationParts[1],\n columnNumber: locationParts[2],\n source: line\n });\n }\n }, this);\n },\n\n parseOpera: function ErrorStackParser$$parseOpera(e) {\n if (!e.stacktrace || (e.message.indexOf('\\n') > -1 &&\n e.message.split('\\n').length > e.stacktrace.split('\\n').length)) {\n return this.parseOpera9(e);\n } else if (!e.stack) {\n return this.parseOpera10(e);\n } else {\n return this.parseOpera11(e);\n }\n },\n\n parseOpera9: function ErrorStackParser$$parseOpera9(e) {\n var lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\n var lines = e.message.split('\\n');\n var result = [];\n\n for (var i = 2, len = lines.length; i < len; i += 2) {\n var match = lineRE.exec(lines[i]);\n if (match) {\n result.push(new StackFrame({\n fileName: match[2],\n lineNumber: match[1],\n source: lines[i]\n }));\n }\n }\n\n return result;\n },\n\n parseOpera10: function ErrorStackParser$$parseOpera10(e) {\n var lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\n var lines = e.stacktrace.split('\\n');\n var result = [];\n\n for (var i = 0, len = lines.length; i < len; i += 2) {\n var match = lineRE.exec(lines[i]);\n if (match) {\n result.push(\n new StackFrame({\n functionName: match[3] || undefined,\n fileName: match[2],\n lineNumber: match[1],\n source: lines[i]\n })\n );\n }\n }\n\n return result;\n },\n\n // Opera 10.65+ Error.stack very similar to FF/Safari\n parseOpera11: function ErrorStackParser$$parseOpera11(error) {\n var filtered = error.stack.split('\\n').filter(function(line) {\n return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/);\n }, this);\n\n return filtered.map(function(line) {\n var tokens = line.split('@');\n var locationParts = this.extractLocation(tokens.pop());\n var functionCall = (tokens.shift() || '');\n var functionName = functionCall\n .replace(//, '$2')\n .replace(/\\([^)]*\\)/g, '') || undefined;\n var argsRaw;\n if (functionCall.match(/\\(([^)]*)\\)/)) {\n argsRaw = functionCall.replace(/^[^(]+\\(([^)]*)\\)$/, '$1');\n }\n var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ?\n undefined : argsRaw.split(',');\n\n return new StackFrame({\n functionName: functionName,\n args: args,\n fileName: locationParts[0],\n lineNumber: locationParts[1],\n columnNumber: locationParts[2],\n source: line\n });\n }, this);\n }\n };\n}));\n","(function(root, factory) {\n 'use strict';\n // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers.\n\n /* istanbul ignore next */\n if (typeof define === 'function' && define.amd) {\n define('stackframe', [], factory);\n } else if (typeof exports === 'object') {\n module.exports = factory();\n } else {\n root.StackFrame = factory();\n }\n}(this, function() {\n 'use strict';\n function _isNumber(n) {\n return !isNaN(parseFloat(n)) && isFinite(n);\n }\n\n function _capitalize(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n }\n\n function _getter(p) {\n return function() {\n return this[p];\n };\n }\n\n var booleanProps = ['isConstructor', 'isEval', 'isNative', 'isToplevel'];\n var numericProps = ['columnNumber', 'lineNumber'];\n var stringProps = ['fileName', 'functionName', 'source'];\n var arrayProps = ['args'];\n var objectProps = ['evalOrigin'];\n\n var props = booleanProps.concat(numericProps, stringProps, arrayProps, objectProps);\n\n function StackFrame(obj) {\n if (!obj) return;\n for (var i = 0; i < props.length; i++) {\n if (obj[props[i]] !== undefined) {\n this['set' + _capitalize(props[i])](obj[props[i]]);\n }\n }\n }\n\n StackFrame.prototype = {\n getArgs: function() {\n return this.args;\n },\n setArgs: function(v) {\n if (Object.prototype.toString.call(v) !== '[object Array]') {\n throw new TypeError('Args must be an Array');\n }\n this.args = v;\n },\n\n getEvalOrigin: function() {\n return this.evalOrigin;\n },\n setEvalOrigin: function(v) {\n if (v instanceof StackFrame) {\n this.evalOrigin = v;\n } else if (v instanceof Object) {\n this.evalOrigin = new StackFrame(v);\n } else {\n throw new TypeError('Eval Origin must be an Object or StackFrame');\n }\n },\n\n toString: function() {\n var fileName = this.getFileName() || '';\n var lineNumber = this.getLineNumber() || '';\n var columnNumber = this.getColumnNumber() || '';\n var functionName = this.getFunctionName() || '';\n if (this.getIsEval()) {\n if (fileName) {\n return '[eval] (' + fileName + ':' + lineNumber + ':' + columnNumber + ')';\n }\n return '[eval]:' + lineNumber + ':' + columnNumber;\n }\n if (functionName) {\n return functionName + ' (' + fileName + ':' + lineNumber + ':' + columnNumber + ')';\n }\n return fileName + ':' + lineNumber + ':' + columnNumber;\n }\n };\n\n StackFrame.fromString = function StackFrame$$fromString(str) {\n var argsStartIndex = str.indexOf('(');\n var argsEndIndex = str.lastIndexOf(')');\n\n var functionName = str.substring(0, argsStartIndex);\n var args = str.substring(argsStartIndex + 1, argsEndIndex).split(',');\n var locationString = str.substring(argsEndIndex + 1);\n\n if (locationString.indexOf('@') === 0) {\n var parts = /@(.+?)(?::(\\d+))?(?::(\\d+))?$/.exec(locationString, '');\n var fileName = parts[1];\n var lineNumber = parts[2];\n var columnNumber = parts[3];\n }\n\n return new StackFrame({\n functionName: functionName,\n args: args || undefined,\n fileName: fileName,\n lineNumber: lineNumber || undefined,\n columnNumber: columnNumber || undefined\n });\n };\n\n for (var i = 0; i < booleanProps.length; i++) {\n StackFrame.prototype['get' + _capitalize(booleanProps[i])] = _getter(booleanProps[i]);\n StackFrame.prototype['set' + _capitalize(booleanProps[i])] = (function(p) {\n return function(v) {\n this[p] = Boolean(v);\n };\n })(booleanProps[i]);\n }\n\n for (var j = 0; j < numericProps.length; j++) {\n StackFrame.prototype['get' + _capitalize(numericProps[j])] = _getter(numericProps[j]);\n StackFrame.prototype['set' + _capitalize(numericProps[j])] = (function(p) {\n return function(v) {\n if (!_isNumber(v)) {\n throw new TypeError(p + ' must be a Number');\n }\n this[p] = Number(v);\n };\n })(numericProps[j]);\n }\n\n for (var k = 0; k < stringProps.length; k++) {\n StackFrame.prototype['get' + _capitalize(stringProps[k])] = _getter(stringProps[k]);\n StackFrame.prototype['set' + _capitalize(stringProps[k])] = (function(p) {\n return function(v) {\n this[p] = String(v);\n };\n })(stringProps[k]);\n }\n\n return StackFrame;\n}));\n","const hasStack = (err: any) =>\n !!err &&\n (!!err.stack || !!err.stacktrace || !!err['opera#sourceloc']) &&\n typeof (err.stack || err.stacktrace || err['opera#sourceloc']) === 'string' &&\n err.stack !== `${err.name}: ${err.message}`;\n\nconst isError = (value: any) => {\n switch (Object.prototype.toString.call(value)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n return true;\n default:\n return value instanceof Error;\n }\n};\n\nexport { hasStack, isError };\n","import type { ErrorState } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport ErrorStackParser from 'error-stack-parser';\nimport type { Exception, Stackframe } from '@rudderstack/analytics-js-common/types/Metrics';\nimport { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport type { FrameType, IErrorFormat } from '../types';\nimport { hasStack, isError } from './utils';\nimport { ERROR_REPORTING_PLUGIN } from '../constants';\n\nconst normaliseFunctionName = (name: string) =>\n /^global code$/i.test(name) ? 'global code' : name;\n\n// takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)\n// and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)\nconst formatStackframe = (frame: FrameType): Stackframe => {\n const f = {\n file: frame.fileName,\n method: normaliseFunctionName(frame.functionName),\n lineNumber: frame.lineNumber,\n columnNumber: frame.columnNumber,\n code: undefined,\n inProject: undefined,\n };\n // Some instances result in no file:\n // - calling notify() from chrome's terminal results in no file/method.\n // - non-error exception thrown from global code in FF\n // This adds one.\n if (f.lineNumber > -1 && !f.file && !f.method) {\n f.file = 'global code';\n }\n return f;\n};\n\nconst ensureString = (str: any) => (typeof str === 'string' ? str : '');\n\nfunction createBugsnagError(\n errorClass: string,\n errorMessage: string,\n stacktrace: any[],\n): Exception {\n return {\n errorClass: ensureString(errorClass),\n message: ensureString(errorMessage),\n type: 'browserjs',\n stacktrace: stacktrace.reduce((accum: Stackframe[], frame: FrameType) => {\n const f = formatStackframe(frame);\n // don't include a stackframe if none of its properties are defined\n try {\n if (JSON.stringify(f) === '{}') return accum;\n return accum.concat(f);\n } catch (e) {\n return accum;\n }\n }, []),\n };\n}\n\n// Helpers\n\nconst getStacktrace = (error: any, errorFramesToSkip: number) => {\n if (hasStack(error)) return ErrorStackParser.parse(error).slice(errorFramesToSkip);\n return [];\n};\n\nconst hasNecessaryFields = (error: any) =>\n (typeof error.name === 'string' || typeof error.errorClass === 'string') &&\n (typeof error.message === 'string' || typeof error.errorMessage === 'string');\n\nconst normaliseError = (maybeError: any, component: string, logger?: ILogger) => {\n let error;\n let internalFrames = 0;\n\n if (isError(maybeError)) {\n error = maybeError;\n } else if (typeof maybeError === 'object' && hasNecessaryFields(maybeError)) {\n error = new Error(maybeError.message || maybeError.errorMessage);\n error.name = maybeError.name || maybeError.errorClass;\n internalFrames += 1;\n } else {\n logger?.warn(\n `${ERROR_REPORTING_PLUGIN}:: ${component} received a non-error: ${stringifyWithoutCircular(error)}`,\n );\n error = undefined;\n }\n\n if (error && !hasStack(error)) {\n // in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here\n try {\n throw error;\n } catch (e) {\n if (hasStack(e)) {\n error = e;\n // if the error only got a stacktrace after we threw it here, we know it\n // will only have one extra internal frame from this function\n internalFrames = 1;\n }\n }\n }\n\n return [error, internalFrames];\n};\n\nclass ErrorFormat implements IErrorFormat {\n errors: Exception[];\n\n constructor(errorClass: string, errorMessage: string, stacktrace: any[]) {\n this.errors = [createBugsnagError(errorClass, errorMessage, stacktrace)];\n }\n static create(\n maybeError: any,\n tolerateNonErrors: boolean,\n handledState: ErrorState,\n component: string,\n errorFramesToSkip = 0,\n logger?: ILogger,\n ) {\n const [error, internalFrames] = normaliseError(maybeError, component, logger);\n if (!error) {\n return undefined;\n }\n let event;\n try {\n const stacktrace = getStacktrace(\n error,\n // if an error was created/throw in the normaliseError() function, we need to\n // tell the getStacktrace() function to skip the number of frames we know will\n // be from our own functions. This is added to the number of frames deep we\n // were told about\n internalFrames > 0 ? 1 + internalFrames + errorFramesToSkip : 0,\n );\n event = new ErrorFormat(error.name, error.message, stacktrace);\n } catch (e) {\n event = new ErrorFormat(error.name, error.message, []);\n }\n\n return event;\n }\n}\n\nexport { ErrorFormat };\n","/* eslint-disable no-use-before-define */\n\nconst crypto =\n (typeof globalThis != 'undefined' ? globalThis : void 0)?.crypto ||\n (typeof global != 'undefined' ? global : void 0)?.crypto ||\n (typeof window != 'undefined' ? window : void 0)?.crypto ||\n (typeof self != 'undefined' ? self : void 0)?.crypto ||\n (typeof frames != 'undefined' ? frames : void 0)?.[0]?.crypto;\n\nlet randomWordArray;\n\nif (crypto) {\n randomWordArray = (nBytes) => {\n const words = [];\n\n for (let i = 0, rcache; i < nBytes; i += 4) {\n words.push(crypto.getRandomValues(new Uint32Array(1))[0]);\n }\n\n return new WordArray(words, nBytes);\n }\n} else {\n // Because there is no global crypto property in this context, cryptographically unsafe Math.random() is used.\n\n randomWordArray = (nBytes) => {\n const words = [];\n \n const r = (m_w) => {\n let _m_w = m_w;\n let _m_z = 0x3ade68b1;\n const mask = 0xffffffff;\n \n return () => {\n _m_z = (0x9069 * (_m_z & 0xFFFF) + (_m_z >> 0x10)) & mask;\n _m_w = (0x4650 * (_m_w & 0xFFFF) + (_m_w >> 0x10)) & mask;\n let result = ((_m_z << 0x10) + _m_w) & mask;\n result /= 0x100000000;\n result += 0.5;\n return result * (Math.random() > 0.5 ? 1 : -1);\n };\n };\n \n for (let i = 0, rcache; i < nBytes; i += 4) {\n const _r = r((rcache || Math.random()) * 0x100000000);\n \n rcache = _r() * 0x3ade67b7;\n words.push((_r() * 0x100000000) | 0);\n }\n \n return new WordArray(words, nBytes);\n }\n}\n\n/**\n * Base class for inheritance.\n */\nexport class Base {\n /**\n * Extends this object and runs the init method.\n * Arguments to create() will be passed to init().\n *\n * @return {Object} The new object.\n *\n * @static\n *\n * @example\n *\n * var instance = MyType.create();\n */\n static create(...args) {\n return new this(...args);\n }\n\n /**\n * Copies properties into this object.\n *\n * @param {Object} properties The properties to mix in.\n *\n * @example\n *\n * MyType.mixIn({\n * field: 'value'\n * });\n */\n mixIn(properties) {\n return Object.assign(this, properties);\n }\n\n /**\n * Creates a copy of this object.\n *\n * @return {Object} The clone.\n *\n * @example\n *\n * var clone = instance.clone();\n */\n clone() {\n const clone = new this.constructor();\n Object.assign(clone, this);\n return clone;\n }\n}\n\n/**\n * An array of 32-bit words.\n *\n * @property {Array} words The array of 32-bit words.\n * @property {number} sigBytes The number of significant bytes in this word array.\n */\nexport class WordArray extends Base {\n /**\n * Initializes a newly created word array.\n *\n * @param {Array} words (Optional) An array of 32-bit words.\n * @param {number} sigBytes (Optional) The number of significant bytes in the words.\n *\n * @example\n *\n * var wordArray = CryptoJS.lib.WordArray.create();\n * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);\n * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);\n */\n constructor(words = [], sigBytes = words.length * 4) {\n super();\n\n let typedArray = words;\n // Convert buffers to uint8\n if (typedArray instanceof ArrayBuffer) {\n typedArray = new Uint8Array(typedArray);\n }\n\n // Convert other array views to uint8\n if (\n typedArray instanceof Int8Array\n || typedArray instanceof Uint8ClampedArray\n || typedArray instanceof Int16Array\n || typedArray instanceof Uint16Array\n || typedArray instanceof Int32Array\n || typedArray instanceof Uint32Array\n || typedArray instanceof Float32Array\n || typedArray instanceof Float64Array\n ) {\n typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);\n }\n\n // Handle Uint8Array\n if (typedArray instanceof Uint8Array) {\n // Shortcut\n const typedArrayByteLength = typedArray.byteLength;\n\n // Extract bytes\n const _words = [];\n for (let i = 0; i < typedArrayByteLength; i += 1) {\n _words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);\n }\n\n // Initialize this word array\n this.words = _words;\n this.sigBytes = typedArrayByteLength;\n } else {\n // Else call normal init\n this.words = words;\n this.sigBytes = sigBytes;\n }\n }\n\n /**\n * Creates a word array filled with random bytes.\n *\n * @param {number} nBytes The number of random bytes to generate.\n *\n * @return {WordArray} The random word array.\n *\n * @static\n *\n * @example\n *\n * var wordArray = CryptoJS.lib.WordArray.random(16);\n */\n static random = randomWordArray;\n\n /**\n * Converts this word array to a string.\n *\n * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex\n *\n * @return {string} The stringified word array.\n *\n * @example\n *\n * var string = wordArray + '';\n * var string = wordArray.toString();\n * var string = wordArray.toString(CryptoJS.enc.Utf8);\n */\n toString(encoder = Hex) {\n return encoder.stringify(this);\n }\n\n /**\n * Concatenates a word array to this word array.\n *\n * @param {WordArray} wordArray The word array to append.\n *\n * @return {WordArray} This word array.\n *\n * @example\n *\n * wordArray1.concat(wordArray2);\n */\n concat(wordArray) {\n // Shortcuts\n const thisWords = this.words;\n const thatWords = wordArray.words;\n const thisSigBytes = this.sigBytes;\n const thatSigBytes = wordArray.sigBytes;\n\n // Clamp excess bits\n this.clamp();\n\n // Concat\n if (thisSigBytes % 4) {\n // Copy one byte at a time\n for (let i = 0; i < thatSigBytes; i += 1) {\n const thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);\n }\n } else {\n // Copy one word at a time\n for (let i = 0; i < thatSigBytes; i += 4) {\n thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];\n }\n }\n this.sigBytes += thatSigBytes;\n\n // Chainable\n return this;\n }\n\n /**\n * Removes insignificant bits.\n *\n * @example\n *\n * wordArray.clamp();\n */\n clamp() {\n // Shortcuts\n const { words, sigBytes } = this;\n\n // Clamp\n words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);\n words.length = Math.ceil(sigBytes / 4);\n }\n\n /**\n * Creates a copy of this word array.\n *\n * @return {WordArray} The clone.\n *\n * @example\n *\n * var clone = wordArray.clone();\n */\n clone() {\n const clone = super.clone.call(this);\n clone.words = this.words.slice(0);\n\n return clone;\n }\n}\n\n/**\n * Hex encoding strategy.\n */\nexport const Hex = {\n /**\n * Converts a word array to a hex string.\n *\n * @param {WordArray} wordArray The word array.\n *\n * @return {string} The hex string.\n *\n * @static\n *\n * @example\n *\n * var hexString = CryptoJS.enc.Hex.stringify(wordArray);\n */\n stringify(wordArray) {\n // Shortcuts\n const { words, sigBytes } = wordArray;\n\n // Convert\n const hexChars = [];\n for (let i = 0; i < sigBytes; i += 1) {\n const bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n hexChars.push((bite >>> 4).toString(16));\n hexChars.push((bite & 0x0f).toString(16));\n }\n\n return hexChars.join('');\n },\n\n /**\n * Converts a hex string to a word array.\n *\n * @param {string} hexStr The hex string.\n *\n * @return {WordArray} The word array.\n *\n * @static\n *\n * @example\n *\n * var wordArray = CryptoJS.enc.Hex.parse(hexString);\n */\n parse(hexStr) {\n // Shortcut\n const hexStrLength = hexStr.length;\n\n // Convert\n const words = [];\n for (let i = 0; i < hexStrLength; i += 2) {\n words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);\n }\n\n return new WordArray(words, hexStrLength / 2);\n },\n};\n\n/**\n * Latin1 encoding strategy.\n */\nexport const Latin1 = {\n /**\n * Converts a word array to a Latin1 string.\n *\n * @param {WordArray} wordArray The word array.\n *\n * @return {string} The Latin1 string.\n *\n * @static\n *\n * @example\n *\n * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);\n */\n stringify(wordArray) {\n // Shortcuts\n const { words, sigBytes } = wordArray;\n\n // Convert\n const latin1Chars = [];\n for (let i = 0; i < sigBytes; i += 1) {\n const bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n latin1Chars.push(String.fromCharCode(bite));\n }\n\n return latin1Chars.join('');\n },\n\n /**\n * Converts a Latin1 string to a word array.\n *\n * @param {string} latin1Str The Latin1 string.\n *\n * @return {WordArray} The word array.\n *\n * @static\n *\n * @example\n *\n * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);\n */\n parse(latin1Str) {\n // Shortcut\n const latin1StrLength = latin1Str.length;\n\n // Convert\n const words = [];\n for (let i = 0; i < latin1StrLength; i += 1) {\n words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);\n }\n\n return new WordArray(words, latin1StrLength);\n },\n};\n\n/**\n * UTF-8 encoding strategy.\n */\nexport const Utf8 = {\n /**\n * Converts a word array to a UTF-8 string.\n *\n * @param {WordArray} wordArray The word array.\n *\n * @return {string} The UTF-8 string.\n *\n * @static\n *\n * @example\n *\n * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);\n */\n stringify(wordArray) {\n try {\n return decodeURIComponent(escape(Latin1.stringify(wordArray)));\n } catch (e) {\n throw new Error('Malformed UTF-8 data');\n }\n },\n\n /**\n * Converts a UTF-8 string to a word array.\n *\n * @param {string} utf8Str The UTF-8 string.\n *\n * @return {WordArray} The word array.\n *\n * @static\n *\n * @example\n *\n * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);\n */\n parse(utf8Str) {\n return Latin1.parse(unescape(encodeURIComponent(utf8Str)));\n },\n};\n\n/**\n * Abstract buffered block algorithm template.\n *\n * The property blockSize must be implemented in a concrete subtype.\n *\n * @property {number} _minBufferSize\n *\n * The number of blocks that should be kept unprocessed in the buffer. Default: 0\n */\nexport class BufferedBlockAlgorithm extends Base {\n constructor() {\n super();\n this._minBufferSize = 0;\n }\n\n /**\n * Resets this block algorithm's data buffer to its initial state.\n *\n * @example\n *\n * bufferedBlockAlgorithm.reset();\n */\n reset() {\n // Initial values\n this._data = new WordArray();\n this._nDataBytes = 0;\n }\n\n /**\n * Adds new data to this block algorithm's buffer.\n *\n * @param {WordArray|string} data\n *\n * The data to append. Strings are converted to a WordArray using UTF-8.\n *\n * @example\n *\n * bufferedBlockAlgorithm._append('data');\n * bufferedBlockAlgorithm._append(wordArray);\n */\n _append(data) {\n let m_data = data;\n\n // Convert string to WordArray, else assume WordArray already\n if (typeof m_data === 'string') {\n m_data = Utf8.parse(m_data);\n }\n\n // Append\n this._data.concat(m_data);\n this._nDataBytes += m_data.sigBytes;\n }\n\n /**\n * Processes available data blocks.\n *\n * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.\n *\n * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.\n *\n * @return {WordArray} The processed data.\n *\n * @example\n *\n * var processedData = bufferedBlockAlgorithm._process();\n * var processedData = bufferedBlockAlgorithm._process(!!'flush');\n */\n _process(doFlush) {\n let processedWords;\n\n // Shortcuts\n const { _data: data, blockSize } = this;\n const dataWords = data.words;\n const dataSigBytes = data.sigBytes;\n const blockSizeBytes = blockSize * 4;\n\n // Count blocks ready\n let nBlocksReady = dataSigBytes / blockSizeBytes;\n if (doFlush) {\n // Round up to include partial blocks\n nBlocksReady = Math.ceil(nBlocksReady);\n } else {\n // Round down to include only full blocks,\n // less the number of blocks that must remain in the buffer\n nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);\n }\n\n // Count words ready\n const nWordsReady = nBlocksReady * blockSize;\n\n // Count bytes ready\n const nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);\n\n // Process blocks\n if (nWordsReady) {\n for (let offset = 0; offset < nWordsReady; offset += blockSize) {\n // Perform concrete-algorithm logic\n this._doProcessBlock(dataWords, offset);\n }\n\n // Remove processed words\n processedWords = dataWords.splice(0, nWordsReady);\n data.sigBytes -= nBytesReady;\n }\n\n // Return processed words\n return new WordArray(processedWords, nBytesReady);\n }\n\n /**\n * Creates a copy of this object.\n *\n * @return {Object} The clone.\n *\n * @example\n *\n * var clone = bufferedBlockAlgorithm.clone();\n */\n clone() {\n const clone = super.clone.call(this);\n clone._data = this._data.clone();\n\n return clone;\n }\n}\n\n/**\n * Abstract hasher template.\n *\n * @property {number} blockSize\n *\n * The number of 32-bit words this hasher operates on. Default: 16 (512 bits)\n */\nexport class Hasher extends BufferedBlockAlgorithm {\n constructor(cfg) {\n super();\n\n this.blockSize = 512 / 32;\n\n /**\n * Configuration options.\n */\n this.cfg = Object.assign(new Base(), cfg);\n\n // Set initial values\n this.reset();\n }\n\n /**\n * Creates a shortcut function to a hasher's object interface.\n *\n * @param {Hasher} SubHasher The hasher to create a helper for.\n *\n * @return {Function} The shortcut function.\n *\n * @static\n *\n * @example\n *\n * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);\n */\n static _createHelper(SubHasher) {\n return (message, cfg) => new SubHasher(cfg).finalize(message);\n }\n\n /**\n * Creates a shortcut function to the HMAC's object interface.\n *\n * @param {Hasher} SubHasher The hasher to use in this HMAC helper.\n *\n * @return {Function} The shortcut function.\n *\n * @static\n *\n * @example\n *\n * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);\n */\n static _createHmacHelper(SubHasher) {\n return (message, key) => new HMAC(SubHasher, key).finalize(message);\n }\n\n /**\n * Resets this hasher to its initial state.\n *\n * @example\n *\n * hasher.reset();\n */\n reset() {\n // Reset data buffer\n super.reset.call(this);\n\n // Perform concrete-hasher logic\n this._doReset();\n }\n\n /**\n * Updates this hasher with a message.\n *\n * @param {WordArray|string} messageUpdate The message to append.\n *\n * @return {Hasher} This hasher.\n *\n * @example\n *\n * hasher.update('message');\n * hasher.update(wordArray);\n */\n update(messageUpdate) {\n // Append\n this._append(messageUpdate);\n\n // Update the hash\n this._process();\n\n // Chainable\n return this;\n }\n\n /**\n * Finalizes the hash computation.\n * Note that the finalize operation is effectively a destructive, read-once operation.\n *\n * @param {WordArray|string} messageUpdate (Optional) A final message update.\n *\n * @return {WordArray} The hash.\n *\n * @example\n *\n * var hash = hasher.finalize();\n * var hash = hasher.finalize('message');\n * var hash = hasher.finalize(wordArray);\n */\n finalize(messageUpdate) {\n // Final message update\n if (messageUpdate) {\n this._append(messageUpdate);\n }\n\n // Perform concrete-hasher logic\n const hash = this._doFinalize();\n\n return hash;\n }\n}\n\n/**\n * HMAC algorithm.\n */\nexport class HMAC extends Base {\n /**\n * Initializes a newly created HMAC.\n *\n * @param {Hasher} SubHasher The hash algorithm to use.\n * @param {WordArray|string} key The secret key.\n *\n * @example\n *\n * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);\n */\n constructor(SubHasher, key) {\n super();\n\n const hasher = new SubHasher();\n this._hasher = hasher;\n\n // Convert string to WordArray, else assume WordArray already\n let _key = key;\n if (typeof _key === 'string') {\n _key = Utf8.parse(_key);\n }\n\n // Shortcuts\n const hasherBlockSize = hasher.blockSize;\n const hasherBlockSizeBytes = hasherBlockSize * 4;\n\n // Allow arbitrary length keys\n if (_key.sigBytes > hasherBlockSizeBytes) {\n _key = hasher.finalize(key);\n }\n\n // Clamp excess bits\n _key.clamp();\n\n // Clone key for inner and outer pads\n const oKey = _key.clone();\n this._oKey = oKey;\n const iKey = _key.clone();\n this._iKey = iKey;\n\n // Shortcuts\n const oKeyWords = oKey.words;\n const iKeyWords = iKey.words;\n\n // XOR keys with pad constants\n for (let i = 0; i < hasherBlockSize; i += 1) {\n oKeyWords[i] ^= 0x5c5c5c5c;\n iKeyWords[i] ^= 0x36363636;\n }\n oKey.sigBytes = hasherBlockSizeBytes;\n iKey.sigBytes = hasherBlockSizeBytes;\n\n // Set initial values\n this.reset();\n }\n\n /**\n * Resets this HMAC to its initial state.\n *\n * @example\n *\n * hmacHasher.reset();\n */\n reset() {\n // Shortcut\n const hasher = this._hasher;\n\n // Reset\n hasher.reset();\n hasher.update(this._iKey);\n }\n\n /**\n * Updates this HMAC with a message.\n *\n * @param {WordArray|string} messageUpdate The message to append.\n *\n * @return {HMAC} This HMAC instance.\n *\n * @example\n *\n * hmacHasher.update('message');\n * hmacHasher.update(wordArray);\n */\n update(messageUpdate) {\n this._hasher.update(messageUpdate);\n\n // Chainable\n return this;\n }\n\n /**\n * Finalizes the HMAC computation.\n * Note that the finalize operation is effectively a destructive, read-once operation.\n *\n * @param {WordArray|string} messageUpdate (Optional) A final message update.\n *\n * @return {WordArray} The HMAC.\n *\n * @example\n *\n * var hmac = hmacHasher.finalize();\n * var hmac = hmacHasher.finalize('message');\n * var hmac = hmacHasher.finalize(wordArray);\n */\n finalize(messageUpdate) {\n // Shortcut\n const hasher = this._hasher;\n\n // Compute HMAC\n const innerHash = hasher.finalize(messageUpdate);\n hasher.reset();\n const hmac = hasher.finalize(this._oKey.clone().concat(innerHash));\n\n return hmac;\n }\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type {\n ApplicationState,\n BreadcrumbMetaData,\n} from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type {\n ExtensionPlugin,\n IPluginEngine,\n} from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { ErrorState, SDKError } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types';\nimport {\n createNewBreadcrumb,\n getConfigForPayloadCreation,\n isRudderSDKError,\n getBugsnagErrorEvent,\n getErrorDeliveryPayload,\n isAllowedToBeNotified,\n} from './utils';\nimport { REQUEST_TIMEOUT_MS } from './constants';\nimport { ErrorFormat } from './event/event';\nimport { INVALID_SOURCE_CONFIG_ERROR } from './logMessages';\n\nconst pluginName: PluginName = 'ErrorReporting';\n\nconst ErrorReporting = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n state.reporting.isErrorReportingPluginLoaded.value = true;\n if (state.reporting.breadcrumbs?.value) {\n state.reporting.breadcrumbs.value = [createNewBreadcrumb('Error Reporting Plugin Loaded')];\n }\n },\n errorReporting: {\n // This extension point is deprecated\n // TODO: Remove this in the next major release\n init: (\n state: ApplicationState,\n pluginEngine: IPluginEngine,\n externalSrcLoader: IExternalSrcLoader,\n logger?: ILogger,\n isInvokedFromLatestCore?: boolean,\n ) => {\n if (isInvokedFromLatestCore) {\n return undefined;\n }\n if (!state.source.value?.config || !state.source.value?.id) {\n return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));\n }\n\n return pluginEngine.invokeSingle(\n 'errorReportingProvider.init',\n state,\n externalSrcLoader,\n logger,\n );\n },\n notify: (\n pluginEngine: IPluginEngine, // Only kept for backward compatibility\n client: any, // Only kept for backward compatibility\n error: SDKError,\n state: ApplicationState,\n logger?: ILogger,\n httpClient?: IHttpClient,\n errorState?: ErrorState,\n ): void => {\n if (httpClient) {\n const { component, tolerateNonErrors, errorFramesToSkip, normalizedError } =\n getConfigForPayloadCreation(error, errorState?.severityReason.type as string);\n\n // Generate the error payload\n const errorPayload = ErrorFormat.create(\n normalizedError,\n tolerateNonErrors,\n errorState as ErrorState,\n component,\n errorFramesToSkip,\n logger,\n );\n\n if (!errorPayload || !isAllowedToBeNotified(errorPayload.errors[0])) {\n return;\n }\n\n // filter errors\n if (!isRudderSDKError(errorPayload.errors[0])) {\n return;\n }\n\n // enrich error payload\n const bugsnagPayload = getBugsnagErrorEvent(errorPayload, errorState as ErrorState, state);\n\n // send it to metrics service\n httpClient?.request({\n url: state.metrics.metricsServiceUrl.value as string,\n options: {\n method: 'POST',\n body: getErrorDeliveryPayload(bugsnagPayload, state),\n sendRawData: true,\n },\n isRawResponse: true,\n timeout: REQUEST_TIMEOUT_MS,\n callback: (result: any, details: any) => {\n // do nothing\n },\n });\n } else {\n pluginEngine.invokeSingle('errorReportingProvider.notify', client, error, state, logger);\n }\n },\n breadcrumb: (\n pluginEngine: IPluginEngine, // Only kept for backward compatibility\n client: any, // Only kept for backward compatibility\n message: string,\n logger?: ILogger, // Only kept for backward compatibility\n state?: ApplicationState,\n metaData?: BreadcrumbMetaData,\n ): void => {\n if (state) {\n state.reporting.breadcrumbs.value = [\n ...state.reporting.breadcrumbs.value,\n createNewBreadcrumb(message, metaData),\n ];\n } else {\n pluginEngine.invokeSingle('errorReportingProvider.breadcrumb', client, message, logger);\n }\n },\n },\n});\n\nexport { ErrorReporting };\n\nexport default ErrorReporting;\n","const INVALID_SOURCE_CONFIG_ERROR = `Invalid source configuration or source id.`;\n\nexport { INVALID_SOURCE_CONFIG_ERROR };\n","const externallyLoadedSessionStorageKeys = {\n segment: 'ajs_anonymous_id',\n};\n\nexport { externallyLoadedSessionStorageKeys };\n","/* eslint-disable no-param-reassign */\nimport type { IStorage } from '@rudderstack/analytics-js-common/types/Store';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { AnonymousIdOptions } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { getSegmentAnonymousId } from './util';\nimport { externallyLoadedSessionStorageKeys } from './constants';\n\nconst pluginName: PluginName = 'ExternalAnonymousId';\n\nconst ExternalAnonymousId = (): ExtensionPlugin => ({\n name: pluginName,\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n storage: {\n getAnonymousId(\n getStorageEngine: (type?: StorageType) => IStorage,\n options?: AnonymousIdOptions,\n ) {\n let anonymousId;\n if (options?.autoCapture?.enabled && options.autoCapture.source) {\n const source = options.autoCapture.source.toLowerCase();\n if (!Object.keys(externallyLoadedSessionStorageKeys).includes(source)) {\n return anonymousId;\n }\n\n // eslint-disable-next-line sonarjs/no-small-switch\n switch (source) {\n case 'segment':\n anonymousId = getSegmentAnonymousId(getStorageEngine);\n break;\n\n default:\n break;\n }\n }\n return anonymousId;\n },\n },\n});\n\nexport { ExternalAnonymousId };\n\nexport default ExternalAnonymousId;\n","import type { IStorage } from '@rudderstack/analytics-js-common/types/Store';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport { storages } from '../shared-chunks/common';\nimport { externallyLoadedSessionStorageKeys } from './constants';\n\nconst getSegmentAnonymousId = (getStorageEngine: (type?: StorageType) => IStorage) => {\n let anonymousId;\n /**\n * First check the local storage for anonymousId\n * Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify\n */\n const lsEngine = getStorageEngine(storages.LOCAL_STORAGE);\n if (lsEngine?.isEnabled) {\n anonymousId = lsEngine.getItem(externallyLoadedSessionStorageKeys.segment);\n }\n\n // If anonymousId is not present in local storage and find it in cookies\n const csEngine = getStorageEngine(storages.COOKIE_STORAGE);\n if (!anonymousId && csEngine?.isEnabled) {\n anonymousId = csEngine.getItem(externallyLoadedSessionStorageKeys.segment);\n }\n return anonymousId;\n};\n\nexport { getSegmentAnonymousId };\n","/**\n * An interface to fetch user device details.\n */\nconst USER_INTERFACE = {\n /**\n * @returns {string} user language\n */\n getUserLanguage: (): string => navigator?.language,\n\n /**\n * @returns {string} userAgent\n */\n getUserAgent: (): string => navigator?.userAgent,\n};\n\nexport { USER_INTERFACE };\n","/**\n * This is utility function for decoding from base 64 to utf8\n *\n * @param {string} str base64\n *\n * @returns {string} utf8\n */\nconst b64DecodeUnicode = (str: string): string =>\n // Going backwards: from bytestream, to percent-encoding, to original string.\n decodeURIComponent(\n globalThis\n .atob(str)\n .split('')\n .map(c => {\n const percentEncodingChar = `00${c.charCodeAt(0).toString(16)}`;\n return `%${percentEncodingChar.slice(-2)}`;\n })\n .join(''),\n );\n\n/**\n * This is utility function for decoding from base 64 to utf8\n *\n * @param {string} data\n *\n * @return {string}\n */\nconst decode = (data = ''): string => {\n const decodedData = data.endsWith('..') ? data.substring(0, data.length - 2) : data;\n return b64DecodeUnicode(decodedData);\n};\n\nexport { decode };\n","import type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { crc32 } from './crc32';\nimport { USER_INTERFACE } from './userLib';\nimport { decode } from './base64Decoder';\n\nconst KEY_VALIDATOR = /^[\\w.-]+$/;\nconst CHECKSUM_OFFSET_MAX_MIN = 1;\nconst VALID_VERSION = 1;\nconst DELIMITER = '*';\n\n/**\n * Parse the linker param value to version checksum and serializedParams\n *\n * @param {string} value\n *\n * @return {?Object}\n */\nconst parseLinkerParamValue = (value: string): Nullable> => {\n const parts = value.split(DELIMITER);\n const isEven = parts.length % 2 === 0;\n\n if (parts.length < 4 || !isEven) {\n // Format ***\n // Note: linker makes sure there's at least one pair of non empty key value\n // Make sure there is at least three delimiters.\n return null;\n }\n\n const version = Number(parts.shift());\n if (version !== VALID_VERSION) {\n return null;\n }\n\n const checksum = parts.shift();\n const serializedIds = parts.join(DELIMITER);\n\n return {\n checksum: checksum ?? '',\n serializedIds,\n };\n};\n\n/**\n * Deserialize the serializedIds and return keyValue pairs.\n *\n * @param {string} serializedIds\n *\n * @return {!Object}\n */\nconst deserialize = (serializedIds?: string): Record => {\n if (!serializedIds) {\n return {};\n }\n\n const keyValuePairs: Record = {};\n const params = serializedIds.split(DELIMITER);\n for (let i = 0; i < params.length; i += 2) {\n const key = params[i] as string;\n const valid = KEY_VALIDATOR.test(key);\n if (valid) {\n keyValuePairs[key] = decode(params[i + 1]);\n }\n }\n return keyValuePairs;\n};\n\n/**\n * Generates a semi-unique value for page visitor.\n *\n * @return {string}\n */\nconst getFingerprint = (userAgent: string, language: string): string => {\n const date = new Date();\n const timezone = date.getTimezoneOffset();\n return [userAgent, timezone, language].join(DELIMITER);\n};\n\n/**\n * Rounded time used to check if t2 - t1 is within our time tolerance.\n * Timestamp in minutes, floored.\n *\n * @return {number}\n */\nconst getMinSinceEpoch = (): number => Math.floor(Date.now() / 60000);\n\n/**\n * Create a unique checksum hashing the fingerprint and a few other values.\n *\n * @param {string} serializedIds\n * @param {number=} optOffsetMin\n * @param {string} userAgent\n * @param {string} language\n *\n * @return {string}\n */\nconst getCheckSum = (\n serializedIds: string,\n optOffsetMin: number,\n userAgent: string,\n language: string,\n): string => {\n const fingerprint = getFingerprint(userAgent, language);\n const offset = optOffsetMin || 0;\n const timestamp = getMinSinceEpoch() - offset;\n const crc = crc32([fingerprint, timestamp, serializedIds].join(DELIMITER));\n\n // Encoded to base36 for fewer bytes.\n return crc.toString(36);\n};\n\n/**\n * Check if the checksum is valid with time offset tolerance.\n *\n * @param {string} serializedIds\n * @param {string} checksum\n *\n * @return {boolean}\n */\nconst isCheckSumValid = (serializedIds: string, checksum: string): boolean => {\n const userAgent = USER_INTERFACE.getUserAgent();\n const language = USER_INTERFACE.getUserLanguage();\n\n for (let i = 0; i <= CHECKSUM_OFFSET_MAX_MIN; i += 1) {\n const calculateCheckSum = getCheckSum(serializedIds, i, userAgent, language);\n if (calculateCheckSum === checksum) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * AMP Linker Parser (works for Rudder, GA or any other linker created by following Google's linker standard.)\n *\n * @param {string} value\n *\n * @return {?Object}\n */\nconst parseLinker = (value: string): Nullable> => {\n const linkerObj = parseLinkerParamValue(value);\n\n if (!linkerObj) {\n return null;\n }\n\n const { checksum, serializedIds } = linkerObj;\n\n if (!serializedIds || !checksum || !isCheckSumValid(serializedIds, checksum)) {\n return null;\n }\n\n return deserialize(serializedIds);\n};\n\nexport { parseLinker };\n","/* eslint-disable no-bitwise */\n\n/**\n * generate crc table\n *\n * @params none\n * @returns array of CRC table\n */\n\nconst makeCRCTable = (): number[] => {\n const crcTable = [];\n let c;\n\n for (let n = 0; n < 256; n++) {\n c = n;\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n }\n crcTable[n] = c;\n }\n\n return crcTable;\n};\n\n/**\n * This is utility function for crc32 algorithm\n *\n * @param {string} str\n * @returns {number} crc32\n */\nconst crc32 = (str: string): number => {\n const crcTable = makeCRCTable();\n let crc = 0 ^ -1;\n\n for (let i = 0; i < str.length; i++) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xff];\n }\n\n return (crc ^ -1) >>> 0;\n};\n\nexport { crc32 };\n","/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { AMP_LINKER_ANONYMOUS_ID_KEY } from './constants';\nimport { parseLinker } from './utils';\n\nconst pluginName: PluginName = 'GoogleLinker';\n\nconst GoogleLinker = (): ExtensionPlugin => ({\n name: pluginName,\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n userSession: {\n anonymousIdGoogleLinker(rudderAmpLinkerParam?: Nullable): Nullable {\n if (!rudderAmpLinkerParam) {\n return null;\n }\n\n const parsedAnonymousIdObj = rudderAmpLinkerParam ? parseLinker(rudderAmpLinkerParam) : null;\n return parsedAnonymousIdObj ? parsedAnonymousIdObj[AMP_LINKER_ANONYMOUS_ID_KEY] : null;\n },\n },\n});\n\nexport { GoogleLinker };\n\nexport default GoogleLinker;\n","const KETCH_CONSENT_MANAGER_PLUGIN = 'KetchConsentManagerPlugin';\nconst KETCH_CONSENT_COOKIE_NAME_V1 = '_ketch_consent_v1_';\n\nexport { KETCH_CONSENT_MANAGER_PLUGIN, KETCH_CONSENT_COOKIE_NAME_V1 };\n","/* eslint-disable no-param-reassign */\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ConsentsInfo } from '@rudderstack/analytics-js-common/types/Consent';\nimport { isDefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { checks, storages, string } from '../shared-chunks/common';\nimport { KETCH_CONSENT_COOKIE_PARSE_ERROR, KETCH_CONSENT_COOKIE_READ_ERROR } from './logMessages';\nimport { KETCH_CONSENT_COOKIE_NAME_V1, KETCH_CONSENT_MANAGER_PLUGIN } from './constants';\nimport type { KetchConsentCookieData, KetchConsentData } from './types';\n\n/**\n * Gets the consent data from the Ketch's consent cookie\n * @param storeManager Store manager instance\n * @param logger Logger instance\n * @returns Consent data from the consent cookie\n */\nconst getKetchConsentData = (\n storeManager?: IStoreManager,\n logger?: ILogger,\n): KetchConsentData | undefined => {\n let rawConsentCookieData = null;\n try {\n // Create a data store instance to read the consent cookie\n const dataStore = storeManager?.setStore({\n id: KETCH_CONSENT_MANAGER_PLUGIN,\n name: KETCH_CONSENT_MANAGER_PLUGIN,\n type: storages.COOKIE_STORAGE,\n });\n rawConsentCookieData = dataStore?.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);\n } catch (err) {\n logger?.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN), err);\n return undefined;\n }\n\n if (checks.isNullOrUndefined(rawConsentCookieData)) {\n return undefined;\n }\n\n // Decode and parse the cookie data to JSON\n let consentCookieData: KetchConsentCookieData;\n try {\n consentCookieData = JSON.parse(string.fromBase64(rawConsentCookieData as string));\n } catch (err) {\n logger?.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN), err);\n return undefined;\n }\n\n if (!consentCookieData) {\n return undefined;\n }\n\n // Convert the cookie data to consent data\n const consentPurposes: KetchConsentData = {};\n Object.entries(consentCookieData).forEach(pEntry => {\n const purposeCode = pEntry[0];\n const purposeValue = pEntry[1];\n consentPurposes[purposeCode] = purposeValue?.status === 'granted';\n });\n return consentPurposes;\n};\n\n/**\n * Gets the consent data in the format expected by the application state\n * @param ketchConsentData Consent data derived from the consent cookie\n * @returns Consent data\n */\nconst getConsentData = (ketchConsentData?: KetchConsentData): ConsentsInfo => {\n const allowedConsentIds: string[] = [];\n const deniedConsentIds: string[] = [];\n if (ketchConsentData) {\n Object.entries(ketchConsentData).forEach(e => {\n const purposeCode = e[0];\n const isConsented = e[1];\n if (isConsented) {\n allowedConsentIds.push(purposeCode);\n } else {\n deniedConsentIds.push(purposeCode);\n }\n });\n }\n\n return { allowedConsentIds, deniedConsentIds };\n};\n\nconst updateConsentStateFromData = (\n state: ApplicationState,\n ketchConsentData: KetchConsentData,\n) => {\n const consentData = getConsentData(ketchConsentData);\n state.consents.initialized.value = isDefined(ketchConsentData);\n state.consents.data.value = consentData;\n};\n\nexport { getKetchConsentData, getConsentData, updateConsentStateFromData };\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst KETCH_CONSENT_COOKIE_READ_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to read the consent cookie.`;\n\nconst KETCH_CONSENT_COOKIE_PARSE_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to parse the consent cookie.`;\n\nconst DESTINATION_CONSENT_STATUS_ERROR = `Failed to determine the consent status for the destination. Please check the destination configuration and try again.`;\n\nexport {\n KETCH_CONSENT_COOKIE_READ_ERROR,\n KETCH_CONSENT_COOKIE_PARSE_ERROR,\n DESTINATION_CONSENT_STATUS_ERROR,\n};\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { DestinationConfig } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { checks } from '../shared-chunks/common';\nimport { DESTINATION_CONSENT_STATUS_ERROR } from './logMessages';\nimport { KETCH_CONSENT_MANAGER_PLUGIN } from './constants';\nimport type { KetchConsentData } from './types';\nimport { getKetchConsentData, updateConsentStateFromData } from './utils';\n\nconst pluginName: PluginName = 'KetchConsentManager';\n\nconst KetchConsentManager = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n consentManager: {\n init(state: ApplicationState, logger?: ILogger): void {\n // getKetchUserConsentedPurposes returns current ketch opted-in purposes\n // This will be helpful for debugging\n (globalThis as any).getKetchUserConsentedPurposes = () =>\n (state.consents.data.value.allowedConsentIds as string[])?.slice();\n\n // getKetchUserDeniedPurposes returns current ketch opted-out purposes\n // This will be helpful for debugging\n (globalThis as any).getKetchUserDeniedPurposes = () =>\n (state.consents.data.value.deniedConsentIds as string[])?.slice();\n\n // updateKetchConsent callback function to update current consent purpose state\n // this will be called from ketch rudderstack plugin\n (globalThis as any).updateKetchConsent = (ketchConsentData: KetchConsentData) => {\n updateConsentStateFromData(state, ketchConsentData);\n };\n },\n\n updateConsentsInfo(\n state: ApplicationState,\n storeManager?: IStoreManager,\n logger?: ILogger,\n ): void {\n // retrieve consent data and update the state\n let ketchConsentData;\n if (!checks.isUndefined((globalThis as any).ketchConsent)) {\n ketchConsentData = (globalThis as any).ketchConsent;\n } else {\n ketchConsentData = getKetchConsentData(storeManager, logger);\n }\n\n updateConsentStateFromData(state, ketchConsentData);\n },\n\n isDestinationConsented(\n state: ApplicationState,\n destConfig: DestinationConfig,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): boolean {\n if (!state.consents.initialized.value) {\n return true;\n }\n\n const allowedConsentIds = state.consents.data.value.allowedConsentIds as string[];\n\n try {\n const { ketchConsentPurposes, consentManagement } = destConfig;\n const matchPredicate = (consent: string) => allowedConsentIds.includes(consent);\n\n // Generic consent management\n if (consentManagement) {\n // Get the corresponding consents for the destination\n const cmpConsents = consentManagement.find(\n c => c.provider === state.consents.provider.value,\n )?.consents;\n\n // If there are no consents configured for the destination for the current provider, events should be sent.\n if (!cmpConsents) {\n return true;\n }\n\n const configuredConsents = cmpConsents.map(c => c.consent.trim()).filter(n => n);\n\n // match the configured consents with user provided consents as per\n // the configured resolution strategy\n switch (state.consents.resolutionStrategy.value) {\n case 'or':\n return configuredConsents.some(matchPredicate) || configuredConsents.length === 0;\n case 'and':\n default:\n return configuredConsents.every(matchPredicate);\n }\n\n // Legacy cookie consent management\n // TODO: To be removed once the source config API is updated to support generic consent management\n } else if (ketchConsentPurposes) {\n const configuredConsents = ketchConsentPurposes.map(p => p.purpose.trim()).filter(n => n);\n\n // Check if any of the destination's mapped ketch purposes are consented by the user in the browser.\n return configuredConsents.some(matchPredicate) || configuredConsents.length === 0;\n }\n\n // If there are no consents configured for the destination for the current provider, events should be sent.\n return true;\n } catch (err) {\n errorHandler?.onError(err, KETCH_CONSENT_MANAGER_PLUGIN, DESTINATION_CONSENT_STATUS_ERROR);\n return true;\n }\n },\n },\n});\n\nexport { KetchConsentManager };\n\nexport default KetchConsentManager;\n","const DEFAULT_QUEUE_OPTIONS = {\n maxItems: 100,\n};\n\nconst QUEUE_NAME = 'rudder_destinations_events';\n\nconst NATIVE_DESTINATION_QUEUE_PLUGIN = 'NativeDestinationQueuePlugin';\n\nexport { DEFAULT_QUEUE_OPTIONS, QUEUE_NAME, NATIVE_DESTINATION_QUEUE_PLUGIN };\n","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport type { DestinationsQueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { RudderEventType } from '../types/plugins';\nimport { DEFAULT_QUEUE_OPTIONS, NATIVE_DESTINATION_QUEUE_PLUGIN } from './constants';\nimport { DESTINATION_EVENT_FORWARDING_ERROR } from './logMessages';\n\nconst getNormalizedQueueOptions = (queueOpts: DestinationsQueueOpts): DestinationsQueueOpts =>\n mergeDeepRight(DEFAULT_QUEUE_OPTIONS, queueOpts);\n\nconst isValidEventName = (eventName: Nullable) =>\n eventName && typeof eventName === 'string';\n\nconst isEventDenyListed = (\n eventType: RudderEventType,\n eventName: Nullable,\n dest: Destination,\n) => {\n if (eventType !== 'track') {\n return false;\n }\n\n const { blacklistedEvents, whitelistedEvents, eventFilteringOption } = dest.config;\n\n switch (eventFilteringOption) {\n // Blacklist is chosen for filtering events\n case 'blacklistedEvents': {\n if (!isValidEventName(eventName)) {\n return false;\n }\n const trimmedEventName = (eventName as string).trim();\n if (Array.isArray(blacklistedEvents)) {\n return blacklistedEvents.some(eventObj => eventObj.eventName.trim() === trimmedEventName);\n }\n return false;\n }\n\n // Whitelist is chosen for filtering events\n case 'whitelistedEvents': {\n if (!isValidEventName(eventName)) {\n return true;\n }\n const trimmedEventName = (eventName as string).trim();\n if (Array.isArray(whitelistedEvents)) {\n return !whitelistedEvents.some(eventObj => eventObj.eventName.trim() === trimmedEventName);\n }\n return true;\n }\n\n case 'disable':\n default:\n return false;\n }\n};\n\nconst sendEventToDestination = (\n item: RudderEvent,\n dest: Destination,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n) => {\n const methodName = item.type.toString();\n try {\n // Destinations expect the event to be wrapped under the `message` key\n // This will remain until we update the destinations to accept the event directly\n dest.instance?.[methodName]?.({ message: item });\n } catch (err) {\n errorHandler?.onError(\n err,\n NATIVE_DESTINATION_QUEUE_PLUGIN,\n DESTINATION_EVENT_FORWARDING_ERROR(dest.userFriendlyId),\n );\n }\n};\n\nexport { getNormalizedQueueOptions, isEventDenyListed, sendEventToDestination };\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\n\nconst DESTINATION_EVENT_FILTERING_WARNING = (\n context: string,\n eventName: Nullable,\n destUserFriendlyId: string,\n): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}The \"${eventName}\" track event has been filtered for the \"${destUserFriendlyId}\" destination.`;\n\nconst DESTINATION_EVENT_FORWARDING_ERROR = (destUserFriendlyId: string): string =>\n `Failed to forward event to destination \"${destUserFriendlyId}\".`;\n\nexport { DESTINATION_EVENT_FILTERING_WARNING, DESTINATION_EVENT_FORWARDING_ERROR };\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type {\n IPluginsManager,\n PluginName,\n} from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport { clone } from 'ramda';\nimport { storages } from '../shared-chunks/common';\nimport type { DoneCallback, IQueue } from '../types/plugins';\nimport { RetryQueue } from '../utilities/retryQueue/RetryQueue';\nimport { getNormalizedQueueOptions, isEventDenyListed, sendEventToDestination } from './utilities';\nimport { NATIVE_DESTINATION_QUEUE_PLUGIN, QUEUE_NAME } from './constants';\nimport { DESTINATION_EVENT_FILTERING_WARNING } from './logMessages';\nimport { destinationUtils } from '../shared-chunks/deviceModeDestinations';\n\nconst pluginName: PluginName = 'NativeDestinationQueue';\n\nconst NativeDestinationQueue = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n destinationsEventsQueue: {\n /**\n * Initialize the queue for delivery to destinations\n * @param state Application state\n * @param pluginsManager PluginsManager instance\n * @param storeManager StoreManager instance\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns IQueue instance\n */\n init(\n state: ApplicationState,\n pluginsManager: IPluginsManager,\n storeManager: IStoreManager,\n dmtQueue: IQueue,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): IQueue {\n const finalQOpts = getNormalizedQueueOptions(\n state.loadOptions.value.destinationsQueueOptions as QueueOpts,\n );\n\n const writeKey = state.lifecycle.writeKey.value as string;\n const eventsQueue = new RetryQueue(\n // adding write key to the queue name to avoid conflicts\n `${QUEUE_NAME}_${writeKey}`,\n finalQOpts,\n (rudderEvent: RudderEvent, done: DoneCallback) => {\n const destinationsToSend = destinationUtils.filterDestinations(\n rudderEvent.integrations,\n state.nativeDestinations.initializedDestinations.value,\n );\n\n // list of destinations which are enable for DMT\n const destWithTransformationEnabled: Destination[] = [];\n const clonedRudderEvent = clone(rudderEvent);\n\n destinationsToSend.forEach((dest: Destination) => {\n try {\n const sendEvent = !isEventDenyListed(\n clonedRudderEvent.type,\n clonedRudderEvent.event,\n dest,\n );\n if (!sendEvent) {\n logger?.warn(\n DESTINATION_EVENT_FILTERING_WARNING(\n NATIVE_DESTINATION_QUEUE_PLUGIN,\n clonedRudderEvent.event,\n dest.userFriendlyId,\n ),\n );\n return;\n }\n\n if (dest.shouldApplyDeviceModeTransformation) {\n destWithTransformationEnabled.push(dest);\n } else {\n sendEventToDestination(clonedRudderEvent, dest, errorHandler, logger);\n }\n } catch (e) {\n errorHandler?.onError(e, NATIVE_DESTINATION_QUEUE_PLUGIN);\n }\n });\n if (destWithTransformationEnabled.length > 0) {\n pluginsManager.invokeSingle(\n 'transformEvent.enqueue',\n state,\n dmtQueue,\n clonedRudderEvent,\n destWithTransformationEnabled,\n errorHandler,\n logger,\n );\n }\n\n // Mark success always\n done(null);\n },\n storeManager,\n storages.MEMORY_STORAGE,\n );\n\n // TODO: This seems to not work as expected. Need to investigate\n // effect(() => {\n // if (state.nativeDestinations.clientDestinationsReady.value === true) {\n // eventsQueue.start();\n // }\n // });\n return eventsQueue;\n },\n\n /**\n * Add event to the queue for delivery to destinations\n * @param state Application state\n * @param eventsQueue IQueue instance\n * @param event RudderEvent object\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns none\n */\n enqueue(\n state: ApplicationState,\n eventsQueue: IQueue,\n event: RudderEvent,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): void {\n eventsQueue.addItem(event);\n },\n\n /**\n * This extension point is used to directly send the transformed event to the destination\n * @param state Application state\n * @param event RudderEvent Object\n * @param destination Destination Object\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n */\n enqueueEventToDestination(state, event, destination, errorHandler, logger) {\n sendEventToDestination(event, destination, errorHandler, logger);\n },\n },\n});\n\nexport { NativeDestinationQueue };\n\nexport default NativeDestinationQueue;\n","const ONETRUST_CONSENT_MANAGER_PLUGIN = 'OneTrustConsentManagerPlugin';\n\nexport { ONETRUST_CONSENT_MANAGER_PLUGIN };\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { DestinationConfig } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { DESTINATION_CONSENT_STATUS_ERROR, ONETRUST_ACCESS_ERROR } from './logMessages';\nimport { ONETRUST_CONSENT_MANAGER_PLUGIN } from './constants';\nimport type { OneTrustGroup } from './types';\n\nconst pluginName: PluginName = 'OneTrustConsentManager';\n\nconst OneTrustConsentManager = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n consentManager: {\n init(state: ApplicationState, logger?: ILogger): void {\n // Nothing to initialize\n },\n\n updateConsentsInfo(\n state: ApplicationState,\n storeManager?: IStoreManager,\n logger?: ILogger,\n ): void {\n if (!(globalThis as any).OneTrust || !(globalThis as any).OnetrustActiveGroups) {\n logger?.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));\n state.consents.initialized.value = false;\n return;\n }\n\n // Get the groups (cookie categorization), user has created in OneTrust account.\n const oneTrustAllGroupsInfo: OneTrustGroup[] = (globalThis as any).OneTrust.GetDomainData()\n .Groups;\n\n // OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with\n // the cookie categories Ids that the user has consented to.\n // Eg: ',C0001,C0003,'\n // We split it and save it as an array.\n const allowedConsentIds = (globalThis as any).OnetrustActiveGroups.split(',').filter(\n (n: string) => n,\n );\n\n const deniedConsentIds: string[] = [];\n oneTrustAllGroupsInfo.forEach(({ CustomGroupId }: OneTrustGroup) => {\n if (!allowedConsentIds.includes(CustomGroupId)) {\n deniedConsentIds.push(CustomGroupId);\n }\n });\n\n state.consents.initialized.value = true;\n state.consents.data.value = { allowedConsentIds, deniedConsentIds };\n },\n\n isDestinationConsented(\n state: ApplicationState,\n destConfig: DestinationConfig,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): boolean {\n if (!state.consents.initialized.value) {\n return true;\n }\n const allowedConsentIds = state.consents.data.value.allowedConsentIds as string[];\n\n try {\n // mapping of the destination with the consent group name\n const { oneTrustCookieCategories, consentManagement } = destConfig;\n\n const matchPredicate = (consent: string) => allowedConsentIds.includes(consent);\n\n // Generic consent management\n if (consentManagement) {\n // Get the corresponding consents for the destination\n const cmpConsents = consentManagement.find(\n c => c.provider === state.consents.provider.value,\n )?.consents;\n\n // If there are no consents configured for the destination for the current provider, events should be sent.\n if (!cmpConsents) {\n return true;\n }\n\n const configuredConsents = cmpConsents.map(c => c.consent.trim()).filter(n => n);\n\n // match the configured consents with user provided consents as per\n // the configured resolution strategy\n switch (state.consents.resolutionStrategy.value) {\n case 'or':\n return configuredConsents.some(matchPredicate) || configuredConsents.length === 0;\n case 'and':\n default:\n return configuredConsents.every(matchPredicate);\n }\n // Legacy cookie consent management\n // TODO: To be removed once the source config API is updated to support generic consent management\n } else if (oneTrustCookieCategories) {\n // Change the structure of oneTrustConsentGroup as an array and filter values if empty string\n // Eg:\n // [\"Performance Cookies\", \"Functional Cookies\"]\n const configuredConsents = oneTrustCookieCategories\n .map(c => c.oneTrustCookieCategory.trim())\n .filter(n => n);\n\n // Check if all the destination's mapped cookie categories are consented by the user in the browser.\n return configuredConsents.every(matchPredicate);\n }\n\n // If there are no consents configured for the destination for the current provider, events should be sent.\n return true;\n } catch (err) {\n errorHandler?.onError(\n err,\n ONETRUST_CONSENT_MANAGER_PLUGIN,\n DESTINATION_CONSENT_STATUS_ERROR,\n );\n return true;\n }\n },\n },\n});\n\nexport { OneTrustConsentManager };\n\nexport default OneTrustConsentManager;\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst ONETRUST_ACCESS_ERROR = (context: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to access OneTrust SDK resources. Please ensure that the OneTrust SDK is loaded successfully before RudderStack SDK.`;\n\nconst DESTINATION_CONSENT_STATUS_ERROR = `Failed to determine the consent status for the destination. Please check the destination configuration and try again.`;\n\nexport { ONETRUST_ACCESS_ERROR, DESTINATION_CONSENT_STATUS_ERROR };\n","/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { encrypt, decrypt } from '../shared-chunks/common';\n\nconst pluginName: PluginName = 'StorageEncryption';\n\nconst StorageEncryption = (): ExtensionPlugin => ({\n name: pluginName,\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n storage: {\n encrypt(value: any): string {\n return encrypt(value);\n },\n decrypt(value: string): string | undefined {\n return decrypt(value);\n },\n },\n});\n\nexport { StorageEncryption };\n\nexport default StorageEncryption;\n","import {\n WordArray,\n Hasher,\n} from './core.js';\n\n// Constants table\nconst T = [];\n\n// Compute constants\nfor (let i = 0; i < 64; i += 1) {\n T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;\n}\n\nconst FF = (a, b, c, d, x, s, t) => {\n const n = a + ((b & c) | (~b & d)) + x + t;\n return ((n << s) | (n >>> (32 - s))) + b;\n};\n\nconst GG = (a, b, c, d, x, s, t) => {\n const n = a + ((b & d) | (c & ~d)) + x + t;\n return ((n << s) | (n >>> (32 - s))) + b;\n};\n\nconst HH = (a, b, c, d, x, s, t) => {\n const n = a + (b ^ c ^ d) + x + t;\n return ((n << s) | (n >>> (32 - s))) + b;\n};\n\nconst II = (a, b, c, d, x, s, t) => {\n const n = a + (c ^ (b | ~d)) + x + t;\n return ((n << s) | (n >>> (32 - s))) + b;\n};\n\n/**\n * MD5 hash algorithm.\n */\nexport class MD5Algo extends Hasher {\n _doReset() {\n this._hash = new WordArray([\n 0x67452301,\n 0xefcdab89,\n 0x98badcfe,\n 0x10325476,\n ]);\n }\n\n _doProcessBlock(M, offset) {\n const _M = M;\n\n // Swap endian\n for (let i = 0; i < 16; i += 1) {\n // Shortcuts\n const offset_i = offset + i;\n const M_offset_i = M[offset_i];\n\n _M[offset_i] = (\n (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff)\n | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)\n );\n }\n\n // Shortcuts\n const H = this._hash.words;\n\n const M_offset_0 = _M[offset + 0];\n const M_offset_1 = _M[offset + 1];\n const M_offset_2 = _M[offset + 2];\n const M_offset_3 = _M[offset + 3];\n const M_offset_4 = _M[offset + 4];\n const M_offset_5 = _M[offset + 5];\n const M_offset_6 = _M[offset + 6];\n const M_offset_7 = _M[offset + 7];\n const M_offset_8 = _M[offset + 8];\n const M_offset_9 = _M[offset + 9];\n const M_offset_10 = _M[offset + 10];\n const M_offset_11 = _M[offset + 11];\n const M_offset_12 = _M[offset + 12];\n const M_offset_13 = _M[offset + 13];\n const M_offset_14 = _M[offset + 14];\n const M_offset_15 = _M[offset + 15];\n\n // Working varialbes\n let a = H[0];\n let b = H[1];\n let c = H[2];\n let d = H[3];\n\n // Computation\n a = FF(a, b, c, d, M_offset_0, 7, T[0]);\n d = FF(d, a, b, c, M_offset_1, 12, T[1]);\n c = FF(c, d, a, b, M_offset_2, 17, T[2]);\n b = FF(b, c, d, a, M_offset_3, 22, T[3]);\n a = FF(a, b, c, d, M_offset_4, 7, T[4]);\n d = FF(d, a, b, c, M_offset_5, 12, T[5]);\n c = FF(c, d, a, b, M_offset_6, 17, T[6]);\n b = FF(b, c, d, a, M_offset_7, 22, T[7]);\n a = FF(a, b, c, d, M_offset_8, 7, T[8]);\n d = FF(d, a, b, c, M_offset_9, 12, T[9]);\n c = FF(c, d, a, b, M_offset_10, 17, T[10]);\n b = FF(b, c, d, a, M_offset_11, 22, T[11]);\n a = FF(a, b, c, d, M_offset_12, 7, T[12]);\n d = FF(d, a, b, c, M_offset_13, 12, T[13]);\n c = FF(c, d, a, b, M_offset_14, 17, T[14]);\n b = FF(b, c, d, a, M_offset_15, 22, T[15]);\n\n a = GG(a, b, c, d, M_offset_1, 5, T[16]);\n d = GG(d, a, b, c, M_offset_6, 9, T[17]);\n c = GG(c, d, a, b, M_offset_11, 14, T[18]);\n b = GG(b, c, d, a, M_offset_0, 20, T[19]);\n a = GG(a, b, c, d, M_offset_5, 5, T[20]);\n d = GG(d, a, b, c, M_offset_10, 9, T[21]);\n c = GG(c, d, a, b, M_offset_15, 14, T[22]);\n b = GG(b, c, d, a, M_offset_4, 20, T[23]);\n a = GG(a, b, c, d, M_offset_9, 5, T[24]);\n d = GG(d, a, b, c, M_offset_14, 9, T[25]);\n c = GG(c, d, a, b, M_offset_3, 14, T[26]);\n b = GG(b, c, d, a, M_offset_8, 20, T[27]);\n a = GG(a, b, c, d, M_offset_13, 5, T[28]);\n d = GG(d, a, b, c, M_offset_2, 9, T[29]);\n c = GG(c, d, a, b, M_offset_7, 14, T[30]);\n b = GG(b, c, d, a, M_offset_12, 20, T[31]);\n\n a = HH(a, b, c, d, M_offset_5, 4, T[32]);\n d = HH(d, a, b, c, M_offset_8, 11, T[33]);\n c = HH(c, d, a, b, M_offset_11, 16, T[34]);\n b = HH(b, c, d, a, M_offset_14, 23, T[35]);\n a = HH(a, b, c, d, M_offset_1, 4, T[36]);\n d = HH(d, a, b, c, M_offset_4, 11, T[37]);\n c = HH(c, d, a, b, M_offset_7, 16, T[38]);\n b = HH(b, c, d, a, M_offset_10, 23, T[39]);\n a = HH(a, b, c, d, M_offset_13, 4, T[40]);\n d = HH(d, a, b, c, M_offset_0, 11, T[41]);\n c = HH(c, d, a, b, M_offset_3, 16, T[42]);\n b = HH(b, c, d, a, M_offset_6, 23, T[43]);\n a = HH(a, b, c, d, M_offset_9, 4, T[44]);\n d = HH(d, a, b, c, M_offset_12, 11, T[45]);\n c = HH(c, d, a, b, M_offset_15, 16, T[46]);\n b = HH(b, c, d, a, M_offset_2, 23, T[47]);\n\n a = II(a, b, c, d, M_offset_0, 6, T[48]);\n d = II(d, a, b, c, M_offset_7, 10, T[49]);\n c = II(c, d, a, b, M_offset_14, 15, T[50]);\n b = II(b, c, d, a, M_offset_5, 21, T[51]);\n a = II(a, b, c, d, M_offset_12, 6, T[52]);\n d = II(d, a, b, c, M_offset_3, 10, T[53]);\n c = II(c, d, a, b, M_offset_10, 15, T[54]);\n b = II(b, c, d, a, M_offset_1, 21, T[55]);\n a = II(a, b, c, d, M_offset_8, 6, T[56]);\n d = II(d, a, b, c, M_offset_15, 10, T[57]);\n c = II(c, d, a, b, M_offset_6, 15, T[58]);\n b = II(b, c, d, a, M_offset_13, 21, T[59]);\n a = II(a, b, c, d, M_offset_4, 6, T[60]);\n d = II(d, a, b, c, M_offset_11, 10, T[61]);\n c = II(c, d, a, b, M_offset_2, 15, T[62]);\n b = II(b, c, d, a, M_offset_9, 21, T[63]);\n\n // Intermediate hash value\n H[0] = (H[0] + a) | 0;\n H[1] = (H[1] + b) | 0;\n H[2] = (H[2] + c) | 0;\n H[3] = (H[3] + d) | 0;\n }\n /* eslint-ensable no-param-reassign */\n\n _doFinalize() {\n // Shortcuts\n const data = this._data;\n const dataWords = data.words;\n\n const nBitsTotal = this._nDataBytes * 8;\n const nBitsLeft = data.sigBytes * 8;\n\n // Add padding\n dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - (nBitsLeft % 32));\n\n const nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);\n const nBitsTotalL = nBitsTotal;\n dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (\n (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff)\n | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)\n );\n dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (\n (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff)\n | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)\n );\n\n data.sigBytes = (dataWords.length + 1) * 4;\n\n // Hash final blocks\n this._process();\n\n // Shortcuts\n const hash = this._hash;\n const H = hash.words;\n\n // Swap endian\n for (let i = 0; i < 4; i += 1) {\n // Shortcut\n const H_i = H[i];\n\n H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff)\n | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);\n }\n\n // Return final computed hash\n return hash;\n }\n\n clone() {\n const clone = super.clone.call(this);\n clone._hash = this._hash.clone();\n\n return clone;\n }\n}\n\n/**\n * Shortcut function to the hasher's object interface.\n *\n * @param {WordArray|string} message The message to hash.\n *\n * @return {WordArray} The hash.\n *\n * @static\n *\n * @example\n *\n * var hash = CryptoJS.MD5('message');\n * var hash = CryptoJS.MD5(wordArray);\n */\nexport const MD5 = Hasher._createHelper(MD5Algo);\n\n/**\n * Shortcut function to the HMAC's object interface.\n *\n * @param {WordArray|string} message The message to hash.\n * @param {WordArray|string} key The secret key.\n *\n * @return {WordArray} The HMAC.\n *\n * @static\n *\n * @example\n *\n * var hmac = CryptoJS.HmacMD5(message, key);\n */\nexport const HmacMD5 = Hasher._createHmacHelper(MD5Algo);\n","import {\n WordArray,\n} from './core.js';\n\nexport const parseLoop = (base64Str, base64StrLength, reverseMap) => {\n const words = [];\n let nBytes = 0;\n for (let i = 0; i < base64StrLength; i += 1) {\n if (i % 4) {\n const bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2);\n const bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2);\n const bitsCombined = bits1 | bits2;\n words[nBytes >>> 2] |= bitsCombined << (24 - (nBytes % 4) * 8);\n nBytes += 1;\n }\n }\n return WordArray.create(words, nBytes);\n};\n\n/**\n * Base64 encoding strategy.\n */\nexport const Base64 = {\n /**\n * Converts a word array to a Base64 string.\n *\n * @param {WordArray} wordArray The word array.\n *\n * @return {string} The Base64 string.\n *\n * @static\n *\n * @example\n *\n * const base64String = CryptoJS.enc.Base64.stringify(wordArray);\n */\n stringify(wordArray) {\n // Shortcuts\n const { words, sigBytes } = wordArray;\n const map = this._map;\n\n // Clamp excess bits\n wordArray.clamp();\n\n // Convert\n const base64Chars = [];\n for (let i = 0; i < sigBytes; i += 3) {\n const byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n const byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;\n const byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;\n\n const triplet = (byte1 << 16) | (byte2 << 8) | byte3;\n\n for (let j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j += 1) {\n base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));\n }\n }\n\n // Add padding\n const paddingChar = map.charAt(64);\n if (paddingChar) {\n while (base64Chars.length % 4) {\n base64Chars.push(paddingChar);\n }\n }\n\n return base64Chars.join('');\n },\n\n /**\n * Converts a Base64 string to a word array.\n *\n * @param {string} base64Str The Base64 string.\n *\n * @return {WordArray} The word array.\n *\n * @static\n *\n * @example\n *\n * const wordArray = CryptoJS.enc.Base64.parse(base64String);\n */\n parse(base64Str) {\n // Shortcuts\n let base64StrLength = base64Str.length;\n const map = this._map;\n let reverseMap = this._reverseMap;\n\n if (!reverseMap) {\n this._reverseMap = [];\n reverseMap = this._reverseMap;\n for (let j = 0; j < map.length; j += 1) {\n reverseMap[map.charCodeAt(j)] = j;\n }\n }\n\n // Ignore padding\n const paddingChar = map.charAt(64);\n if (paddingChar) {\n const paddingIndex = base64Str.indexOf(paddingChar);\n if (paddingIndex !== -1) {\n base64StrLength = paddingIndex;\n }\n }\n\n // Convert\n return parseLoop(base64Str, base64StrLength, reverseMap);\n },\n\n _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n};\n","import {\n Base,\n WordArray,\n} from './core.js';\nimport { MD5Algo } from './md5.js';\n\n/**\n * This key derivation function is meant to conform with EVP_BytesToKey.\n * www.openssl.org/docs/crypto/EVP_BytesToKey.html\n */\nexport class EvpKDFAlgo extends Base {\n /**\n * Initializes a newly created key derivation function.\n *\n * @param {Object} cfg (Optional) The configuration options to use for the derivation.\n *\n * @example\n *\n * const kdf = CryptoJS.algo.EvpKDF.create();\n * const kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });\n * const kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });\n */\n constructor(cfg) {\n super();\n\n /**\n * Configuration options.\n *\n * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)\n * @property {Hasher} hasher The hash algorithm to use. Default: MD5\n * @property {number} iterations The number of iterations to perform. Default: 1\n */\n this.cfg = Object.assign(\n new Base(),\n {\n keySize: 128 / 32,\n hasher: MD5Algo,\n iterations: 1,\n },\n cfg,\n );\n }\n\n /**\n * Derives a key from a password.\n *\n * @param {WordArray|string} password The password.\n * @param {WordArray|string} salt A salt.\n *\n * @return {WordArray} The derived key.\n *\n * @example\n *\n * const key = kdf.compute(password, salt);\n */\n compute(password, salt) {\n let block;\n\n // Shortcut\n const { cfg } = this;\n\n // Init hasher\n const hasher = cfg.hasher.create();\n\n // Initial values\n const derivedKey = WordArray.create();\n\n // Shortcuts\n const derivedKeyWords = derivedKey.words;\n const { keySize, iterations } = cfg;\n\n // Generate key\n while (derivedKeyWords.length < keySize) {\n if (block) {\n hasher.update(block);\n }\n block = hasher.update(password).finalize(salt);\n hasher.reset();\n\n // Iterations\n for (let i = 1; i < iterations; i += 1) {\n block = hasher.finalize(block);\n hasher.reset();\n }\n\n derivedKey.concat(block);\n }\n derivedKey.sigBytes = keySize * 4;\n\n return derivedKey;\n }\n}\n\n/**\n * Derives a key from a password.\n *\n * @param {WordArray|string} password The password.\n * @param {WordArray|string} salt A salt.\n * @param {Object} cfg (Optional) The configuration options to use for this computation.\n *\n * @return {WordArray} The derived key.\n *\n * @static\n *\n * @example\n *\n * var key = CryptoJS.EvpKDF(password, salt);\n * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });\n * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });\n */\nexport const EvpKDF = (password, salt, cfg) => EvpKDFAlgo.create(cfg).compute(password, salt);\n","/* eslint-disable no-use-before-define */\n\nimport {\n Base,\n WordArray,\n BufferedBlockAlgorithm,\n} from './core.js';\nimport { Base64 } from './enc-base64.js';\nimport { EvpKDFAlgo } from './evpkdf.js';\n\n// ObjectAssign polyfill\nconst ObjectAssign = typeof Object.assign !== \"function\" ? function (target) {\n if (target == null) {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n\n target = Object(target);\n\n for (let index = 1; index < arguments.length; index++) {\n const source = arguments[index];\n\n if (source != null) {\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n }\n\n return target;\n} : Object.assign;\n\n/**\n * Abstract base cipher template.\n *\n * @property {number} keySize This cipher's key size. Default: 4 (128 bits)\n * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)\n * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.\n * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.\n */\nexport class Cipher extends BufferedBlockAlgorithm {\n /**\n * Initializes a newly created cipher.\n *\n * @param {number} xformMode Either the encryption or decryption transormation mode constant.\n * @param {WordArray} key The key.\n * @param {Object} cfg (Optional) The configuration options to use for this operation.\n *\n * @example\n *\n * const cipher = CryptoJS.algo.AES.create(\n * CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }\n * );\n */\n constructor(xformMode, key, cfg) {\n super();\n\n /**\n * Configuration options.\n *\n * @property {WordArray} iv The IV to use for this operation.\n */\n this.cfg = ObjectAssign(new Base(), cfg);\n\n // Store transform mode and key\n this._xformMode = xformMode;\n this._key = key;\n\n // Set initial values\n this.reset();\n }\n\n /**\n * Creates this cipher in encryption mode.\n *\n * @param {WordArray} key The key.\n * @param {Object} cfg (Optional) The configuration options to use for this operation.\n *\n * @return {Cipher} A cipher instance.\n *\n * @static\n *\n * @example\n *\n * const cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });\n */\n static createEncryptor(key, cfg) {\n return this.create(this._ENC_XFORM_MODE, key, cfg);\n }\n\n /**\n * Creates this cipher in decryption mode.\n *\n * @param {WordArray} key The key.\n * @param {Object} cfg (Optional) The configuration options to use for this operation.\n *\n * @return {Cipher} A cipher instance.\n *\n * @static\n *\n * @example\n *\n * const cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });\n */\n static createDecryptor(key, cfg) {\n return this.create(this._DEC_XFORM_MODE, key, cfg);\n }\n\n /**\n * Creates shortcut functions to a cipher's object interface.\n *\n * @param {Cipher} cipher The cipher to create a helper for.\n *\n * @return {Object} An object with encrypt and decrypt shortcut functions.\n *\n * @static\n *\n * @example\n *\n * const AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);\n */\n static _createHelper(SubCipher) {\n const selectCipherStrategy = (key) => {\n if (typeof key === 'string') {\n return PasswordBasedCipher;\n }\n return SerializableCipher;\n };\n\n return {\n encrypt(message, key, cfg) {\n return selectCipherStrategy(key).encrypt(SubCipher, message, key, cfg);\n },\n\n decrypt(ciphertext, key, cfg) {\n return selectCipherStrategy(key).decrypt(SubCipher, ciphertext, key, cfg);\n },\n };\n }\n\n /**\n * Resets this cipher to its initial state.\n *\n * @example\n *\n * cipher.reset();\n */\n reset() {\n // Reset data buffer\n super.reset.call(this);\n\n // Perform concrete-cipher logic\n this._doReset();\n }\n\n /**\n * Adds data to be encrypted or decrypted.\n *\n * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.\n *\n * @return {WordArray} The data after processing.\n *\n * @example\n *\n * const encrypted = cipher.process('data');\n * const encrypted = cipher.process(wordArray);\n */\n process(dataUpdate) {\n // Append\n this._append(dataUpdate);\n\n // Process available blocks\n return this._process();\n }\n\n /**\n * Finalizes the encryption or decryption process.\n * Note that the finalize operation is effectively a destructive, read-once operation.\n *\n * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.\n *\n * @return {WordArray} The data after final processing.\n *\n * @example\n *\n * const encrypted = cipher.finalize();\n * const encrypted = cipher.finalize('data');\n * const encrypted = cipher.finalize(wordArray);\n */\n finalize(dataUpdate) {\n // Final data update\n if (dataUpdate) {\n this._append(dataUpdate);\n }\n\n // Perform concrete-cipher logic\n const finalProcessedData = this._doFinalize();\n\n return finalProcessedData;\n }\n}\nCipher._ENC_XFORM_MODE = 1;\nCipher._DEC_XFORM_MODE = 2;\nCipher.keySize = 128 / 32;\nCipher.ivSize = 128 / 32;\n\n/**\n * Abstract base stream cipher template.\n *\n * @property {number} blockSize\n *\n * The number of 32-bit words this cipher operates on. Default: 1 (32 bits)\n */\nexport class StreamCipher extends Cipher {\n constructor(...args) {\n super(...args);\n\n this.blockSize = 1;\n }\n\n _doFinalize() {\n // Process partial blocks\n const finalProcessedBlocks = this._process(!!'flush');\n\n return finalProcessedBlocks;\n }\n}\n\n/**\n * Abstract base block cipher mode template.\n */\nexport class BlockCipherMode extends Base {\n /**\n * Initializes a newly created mode.\n *\n * @param {Cipher} cipher A block cipher instance.\n * @param {Array} iv The IV words.\n *\n * @example\n *\n * const mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);\n */\n constructor(cipher, iv) {\n super();\n\n this._cipher = cipher;\n this._iv = iv;\n }\n\n /**\n * Creates this mode for encryption.\n *\n * @param {Cipher} cipher A block cipher instance.\n * @param {Array} iv The IV words.\n *\n * @static\n *\n * @example\n *\n * const mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);\n */\n static createEncryptor(cipher, iv) {\n return this.Encryptor.create(cipher, iv);\n }\n\n /**\n * Creates this mode for decryption.\n *\n * @param {Cipher} cipher A block cipher instance.\n * @param {Array} iv The IV words.\n *\n * @static\n *\n * @example\n *\n * const mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);\n */\n static createDecryptor(cipher, iv) {\n return this.Decryptor.create(cipher, iv);\n }\n}\n\nfunction xorBlock(words, offset, blockSize) {\n const _words = words;\n let block;\n\n // Shortcut\n const iv = this._iv;\n\n // Choose mixing block\n if (iv) {\n block = iv;\n\n // Remove IV for subsequent blocks\n this._iv = undefined;\n } else {\n block = this._prevBlock;\n }\n\n // XOR blocks\n for (let i = 0; i < blockSize; i += 1) {\n _words[offset + i] ^= block[i];\n }\n}\n\n/**\n * Cipher Block Chaining mode.\n */\n\n/**\n * Abstract base CBC mode.\n */\nexport class CBC extends BlockCipherMode {\n}\n/**\n * CBC encryptor.\n */\nCBC.Encryptor = class extends CBC {\n /**\n * Processes the data block at offset.\n *\n * @param {Array} words The data words to operate on.\n * @param {number} offset The offset where the block starts.\n *\n * @example\n *\n * mode.processBlock(data.words, offset);\n */\n processBlock(words, offset) {\n // Shortcuts\n const cipher = this._cipher;\n const { blockSize } = cipher;\n\n // XOR and encrypt\n xorBlock.call(this, words, offset, blockSize);\n cipher.encryptBlock(words, offset);\n\n // Remember this block to use with next block\n this._prevBlock = words.slice(offset, offset + blockSize);\n }\n};\n/**\n * CBC decryptor.\n */\nCBC.Decryptor = class extends CBC {\n /**\n * Processes the data block at offset.\n *\n * @param {Array} words The data words to operate on.\n * @param {number} offset The offset where the block starts.\n *\n * @example\n *\n * mode.processBlock(data.words, offset);\n */\n processBlock(words, offset) {\n // Shortcuts\n const cipher = this._cipher;\n const { blockSize } = cipher;\n\n // Remember this block to use with next block\n const thisBlock = words.slice(offset, offset + blockSize);\n\n // Decrypt and XOR\n cipher.decryptBlock(words, offset);\n xorBlock.call(this, words, offset, blockSize);\n\n // This block becomes the previous block\n this._prevBlock = thisBlock;\n }\n};\n\n/**\n * PKCS #5/7 padding strategy.\n */\nexport const Pkcs7 = {\n /**\n * Pads data using the algorithm defined in PKCS #5/7.\n *\n * @param {WordArray} data The data to pad.\n * @param {number} blockSize The multiple that the data should be padded to.\n *\n * @static\n *\n * @example\n *\n * CryptoJS.pad.Pkcs7.pad(wordArray, 4);\n */\n pad(data, blockSize) {\n // Shortcut\n const blockSizeBytes = blockSize * 4;\n\n // Count padding bytes\n const nPaddingBytes = blockSizeBytes - (data.sigBytes % blockSizeBytes);\n\n // Create padding word\n const paddingWord = (nPaddingBytes << 24)\n | (nPaddingBytes << 16)\n | (nPaddingBytes << 8)\n | nPaddingBytes;\n\n // Create padding\n const paddingWords = [];\n for (let i = 0; i < nPaddingBytes; i += 4) {\n paddingWords.push(paddingWord);\n }\n const padding = WordArray.create(paddingWords, nPaddingBytes);\n\n // Add padding\n data.concat(padding);\n },\n\n /**\n * Unpads data that had been padded using the algorithm defined in PKCS #5/7.\n *\n * @param {WordArray} data The data to unpad.\n *\n * @static\n *\n * @example\n *\n * CryptoJS.pad.Pkcs7.unpad(wordArray);\n */\n unpad(data) {\n const _data = data;\n\n // Get number of padding bytes from last byte\n const nPaddingBytes = _data.words[(_data.sigBytes - 1) >>> 2] & 0xff;\n\n // Remove padding\n _data.sigBytes -= nPaddingBytes;\n },\n};\n\n/**\n * Abstract base block cipher template.\n *\n * @property {number} blockSize\n *\n * The number of 32-bit words this cipher operates on. Default: 4 (128 bits)\n */\nexport class BlockCipher extends Cipher {\n constructor(xformMode, key, cfg) {\n /**\n * Configuration options.\n *\n * @property {Mode} mode The block mode to use. Default: CBC\n * @property {Padding} padding The padding strategy to use. Default: Pkcs7\n */\n super(xformMode, key, ObjectAssign(\n {\n mode: CBC,\n padding: Pkcs7,\n },\n cfg,\n ));\n\n this.blockSize = 128 / 32;\n }\n\n reset() {\n let modeCreator;\n\n // Reset cipher\n super.reset.call(this);\n\n // Shortcuts\n const { cfg } = this;\n const { iv, mode } = cfg;\n\n // Reset block mode\n if (this._xformMode === this.constructor._ENC_XFORM_MODE) {\n modeCreator = mode.createEncryptor;\n } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {\n modeCreator = mode.createDecryptor;\n // Keep at least one block in the buffer for unpadding\n this._minBufferSize = 1;\n }\n\n this._mode = modeCreator.call(mode, this, iv && iv.words);\n this._mode.__creator = modeCreator;\n }\n\n _doProcessBlock(words, offset) {\n this._mode.processBlock(words, offset);\n }\n\n _doFinalize() {\n let finalProcessedBlocks;\n\n // Shortcut\n const { padding } = this.cfg;\n\n // Finalize\n if (this._xformMode === this.constructor._ENC_XFORM_MODE) {\n // Pad data\n padding.pad(this._data, this.blockSize);\n\n // Process final blocks\n finalProcessedBlocks = this._process(!!'flush');\n } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {\n // Process final blocks\n finalProcessedBlocks = this._process(!!'flush');\n\n // Unpad data\n padding.unpad(finalProcessedBlocks);\n }\n\n return finalProcessedBlocks;\n }\n}\n\n/**\n * A collection of cipher parameters.\n *\n * @property {WordArray} ciphertext The raw ciphertext.\n * @property {WordArray} key The key to this ciphertext.\n * @property {WordArray} iv The IV used in the ciphering operation.\n * @property {WordArray} salt The salt used with a key derivation function.\n * @property {Cipher} algorithm The cipher algorithm.\n * @property {Mode} mode The block mode used in the ciphering operation.\n * @property {Padding} padding The padding scheme used in the ciphering operation.\n * @property {number} blockSize The block size of the cipher.\n * @property {Format} formatter\n * The default formatting strategy to convert this cipher params object to a string.\n */\nexport class CipherParams extends Base {\n /**\n * Initializes a newly created cipher params object.\n *\n * @param {Object} cipherParams An object with any of the possible cipher parameters.\n *\n * @example\n *\n * var cipherParams = CryptoJS.lib.CipherParams.create({\n * ciphertext: ciphertextWordArray,\n * key: keyWordArray,\n * iv: ivWordArray,\n * salt: saltWordArray,\n * algorithm: CryptoJS.algo.AES,\n * mode: CryptoJS.mode.CBC,\n * padding: CryptoJS.pad.PKCS7,\n * blockSize: 4,\n * formatter: CryptoJS.format.OpenSSL\n * });\n */\n constructor(cipherParams) {\n super();\n\n this.mixIn(cipherParams);\n }\n\n /**\n * Converts this cipher params object to a string.\n *\n * @param {Format} formatter (Optional) The formatting strategy to use.\n *\n * @return {string} The stringified cipher params.\n *\n * @throws Error If neither the formatter nor the default formatter is set.\n *\n * @example\n *\n * var string = cipherParams + '';\n * var string = cipherParams.toString();\n * var string = cipherParams.toString(CryptoJS.format.OpenSSL);\n */\n toString(formatter) {\n return (formatter || this.formatter).stringify(this);\n }\n}\n\n/**\n * OpenSSL formatting strategy.\n */\nexport const OpenSSLFormatter = {\n /**\n * Converts a cipher params object to an OpenSSL-compatible string.\n *\n * @param {CipherParams} cipherParams The cipher params object.\n *\n * @return {string} The OpenSSL-compatible string.\n *\n * @static\n *\n * @example\n *\n * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);\n */\n stringify(cipherParams) {\n let wordArray;\n\n // Shortcuts\n const { ciphertext, salt } = cipherParams;\n\n // Format\n if (salt) {\n wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);\n } else {\n wordArray = ciphertext;\n }\n\n return wordArray.toString(Base64);\n },\n\n /**\n * Converts an OpenSSL-compatible string to a cipher params object.\n *\n * @param {string} openSSLStr The OpenSSL-compatible string.\n *\n * @return {CipherParams} The cipher params object.\n *\n * @static\n *\n * @example\n *\n * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);\n */\n parse(openSSLStr) {\n let salt;\n\n // Parse base64\n const ciphertext = Base64.parse(openSSLStr);\n\n // Shortcut\n const ciphertextWords = ciphertext.words;\n\n // Test for salt\n if (ciphertextWords[0] === 0x53616c74 && ciphertextWords[1] === 0x65645f5f) {\n // Extract salt\n salt = WordArray.create(ciphertextWords.slice(2, 4));\n\n // Remove salt from ciphertext\n ciphertextWords.splice(0, 4);\n ciphertext.sigBytes -= 16;\n }\n\n return CipherParams.create({ ciphertext, salt });\n },\n};\n\n/**\n * A cipher wrapper that returns ciphertext as a serializable cipher params object.\n */\nexport class SerializableCipher extends Base {\n /**\n * Encrypts a message.\n *\n * @param {Cipher} cipher The cipher algorithm to use.\n * @param {WordArray|string} message The message to encrypt.\n * @param {WordArray} key The key.\n * @param {Object} cfg (Optional) The configuration options to use for this operation.\n *\n * @return {CipherParams} A cipher params object.\n *\n * @static\n *\n * @example\n *\n * var ciphertextParams = CryptoJS.lib.SerializableCipher\n * .encrypt(CryptoJS.algo.AES, message, key);\n * var ciphertextParams = CryptoJS.lib.SerializableCipher\n * .encrypt(CryptoJS.algo.AES, message, key, { iv: iv });\n * var ciphertextParams = CryptoJS.lib.SerializableCipher\n * .encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });\n */\n static encrypt(cipher, message, key, cfg) {\n // Apply config defaults\n const _cfg = ObjectAssign(new Base(), this.cfg, cfg);\n\n // Encrypt\n const encryptor = cipher.createEncryptor(key, _cfg);\n const ciphertext = encryptor.finalize(message);\n\n // Shortcut\n const cipherCfg = encryptor.cfg;\n\n // Create and return serializable cipher params\n return CipherParams.create({\n ciphertext,\n key,\n iv: cipherCfg.iv,\n algorithm: cipher,\n mode: cipherCfg.mode,\n padding: cipherCfg.padding,\n blockSize: encryptor.blockSize,\n formatter: _cfg.format,\n });\n }\n\n /**\n * Decrypts serialized ciphertext.\n *\n * @param {Cipher} cipher The cipher algorithm to use.\n * @param {CipherParams|string} ciphertext The ciphertext to decrypt.\n * @param {WordArray} key The key.\n * @param {Object} cfg (Optional) The configuration options to use for this operation.\n *\n * @return {WordArray} The plaintext.\n *\n * @static\n *\n * @example\n *\n * var plaintext = CryptoJS.lib.SerializableCipher\n * .decrypt(CryptoJS.algo.AES, formattedCiphertext, key,\n * { iv: iv, format: CryptoJS.format.OpenSSL });\n * var plaintext = CryptoJS.lib.SerializableCipher\n * .decrypt(CryptoJS.algo.AES, ciphertextParams, key,\n * { iv: iv, format: CryptoJS.format.OpenSSL });\n */\n static decrypt(cipher, ciphertext, key, cfg) {\n let _ciphertext = ciphertext;\n\n // Apply config defaults\n const _cfg = ObjectAssign(new Base(), this.cfg, cfg);\n\n // Convert string to CipherParams\n _ciphertext = this._parse(_ciphertext, _cfg.format);\n\n // Decrypt\n const plaintext = cipher.createDecryptor(key, _cfg).finalize(_ciphertext.ciphertext);\n\n return plaintext;\n }\n\n /**\n * Converts serialized ciphertext to CipherParams,\n * else assumed CipherParams already and returns ciphertext unchanged.\n *\n * @param {CipherParams|string} ciphertext The ciphertext.\n * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.\n *\n * @return {CipherParams} The unserialized ciphertext.\n *\n * @static\n *\n * @example\n *\n * var ciphertextParams = CryptoJS.lib.SerializableCipher\n * ._parse(ciphertextStringOrParams, format);\n */\n static _parse(ciphertext, format) {\n if (typeof ciphertext === 'string') {\n return format.parse(ciphertext, this);\n }\n return ciphertext;\n }\n}\n/**\n * Configuration options.\n *\n * @property {Formatter} format\n *\n * The formatting strategy to convert cipher param objects to and from a string.\n * Default: OpenSSL\n */\nSerializableCipher.cfg = ObjectAssign(\n new Base(),\n { format: OpenSSLFormatter },\n);\n\n/**\n * OpenSSL key derivation function.\n */\nexport const OpenSSLKdf = {\n /**\n * Derives a key and IV from a password.\n *\n * @param {string} password The password to derive from.\n * @param {number} keySize The size in words of the key to generate.\n * @param {number} ivSize The size in words of the IV to generate.\n * @param {WordArray|string} salt\n * (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.\n *\n * @return {CipherParams} A cipher params object with the key, IV, and salt.\n *\n * @static\n *\n * @example\n *\n * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);\n * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');\n */\n execute(password, keySize, ivSize, salt, hasher) {\n let _salt = salt;\n\n // Generate random salt\n if (!_salt) {\n _salt = WordArray.random(64 / 8);\n }\n\n // Derive key and IV\n let key;\n if (!hasher) {\n key = EvpKDFAlgo.create({ keySize: keySize + ivSize }).compute(password, _salt);\n } else {\n key = EvpKDFAlgo.create({ keySize: keySize + ivSize, hasher }).compute(password, _salt);\n }\n\n // Separate key and IV\n const iv = WordArray.create(key.words.slice(keySize), ivSize * 4);\n key.sigBytes = keySize * 4;\n\n // Return params\n return CipherParams.create({ key, iv, salt: _salt });\n },\n};\n\n/**\n * A serializable cipher wrapper that derives the key from a password,\n * and returns ciphertext as a serializable cipher params object.\n */\nexport class PasswordBasedCipher extends SerializableCipher {\n /**\n * Encrypts a message using a password.\n *\n * @param {Cipher} cipher The cipher algorithm to use.\n * @param {WordArray|string} message The message to encrypt.\n * @param {string} password The password.\n * @param {Object} cfg (Optional) The configuration options to use for this operation.\n *\n * @return {CipherParams} A cipher params object.\n *\n * @static\n *\n * @example\n *\n * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher\n * .encrypt(CryptoJS.algo.AES, message, 'password');\n * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher\n * .encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });\n */\n static encrypt(cipher, message, password, cfg) {\n // Apply config defaults\n const _cfg = ObjectAssign(new Base(), this.cfg, cfg);\n\n // Derive key and other params\n const derivedParams = _cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, _cfg.salt, _cfg.hasher);\n\n // Add IV to config\n _cfg.iv = derivedParams.iv;\n\n // Encrypt\n const ciphertext = SerializableCipher.encrypt\n .call(this, cipher, message, derivedParams.key, _cfg);\n\n // Mix in derived params\n ciphertext.mixIn(derivedParams);\n\n return ciphertext;\n }\n\n /**\n * Decrypts serialized ciphertext using a password.\n *\n * @param {Cipher} cipher The cipher algorithm to use.\n * @param {CipherParams|string} ciphertext The ciphertext to decrypt.\n * @param {string} password The password.\n * @param {Object} cfg (Optional) The configuration options to use for this operation.\n *\n * @return {WordArray} The plaintext.\n *\n * @static\n *\n * @example\n *\n * var plaintext = CryptoJS.lib.PasswordBasedCipher\n * .decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password',\n * { format: CryptoJS.format.OpenSSL });\n * var plaintext = CryptoJS.lib.PasswordBasedCipher\n * .decrypt(CryptoJS.algo.AES, ciphertextParams, 'password',\n * { format: CryptoJS.format.OpenSSL });\n */\n static decrypt(cipher, ciphertext, password, cfg) {\n let _ciphertext = ciphertext;\n\n // Apply config defaults\n const _cfg = ObjectAssign(new Base(), this.cfg, cfg);\n\n // Convert string to CipherParams\n _ciphertext = this._parse(_ciphertext, _cfg.format);\n\n // Derive key and other params\n const derivedParams = _cfg.kdf\n .execute(password, cipher.keySize, cipher.ivSize, _ciphertext.salt, _cfg.hasher);\n\n // Add IV to config\n _cfg.iv = derivedParams.iv;\n\n // Decrypt\n const plaintext = SerializableCipher.decrypt\n .call(this, cipher, _ciphertext, derivedParams.key, _cfg);\n\n return plaintext;\n }\n}\n/**\n * Configuration options.\n *\n * @property {KDF} kdf\n * The key derivation function to use to generate a key and IV from a password.\n * Default: OpenSSL\n */\nPasswordBasedCipher.cfg = ObjectAssign(SerializableCipher.cfg, { kdf: OpenSSLKdf });\n","import {\n BlockCipher,\n} from './cipher-core.js';\n\n// Lookup tables\nconst _SBOX = [];\nconst INV_SBOX = [];\nconst _SUB_MIX_0 = [];\nconst _SUB_MIX_1 = [];\nconst _SUB_MIX_2 = [];\nconst _SUB_MIX_3 = [];\nconst INV_SUB_MIX_0 = [];\nconst INV_SUB_MIX_1 = [];\nconst INV_SUB_MIX_2 = [];\nconst INV_SUB_MIX_3 = [];\n\n// Compute lookup tables\n\n// Compute double table\nconst d = [];\nfor (let i = 0; i < 256; i += 1) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n}\n\n// Walk GF(2^8)\nlet x = 0;\nlet xi = 0;\nfor (let i = 0; i < 256; i += 1) {\n // Compute sbox\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n _SBOX[x] = sx;\n INV_SBOX[sx] = x;\n\n // Compute multiplication\n const x2 = d[x];\n const x4 = d[x2];\n const x8 = d[x4];\n\n // Compute sub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n _SUB_MIX_0[x] = (t << 24) | (t >>> 8);\n _SUB_MIX_1[x] = (t << 16) | (t >>> 16);\n _SUB_MIX_2[x] = (t << 8) | (t >>> 24);\n _SUB_MIX_3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);\n INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);\n INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);\n INV_SUB_MIX_3[sx] = t;\n\n // Compute next counter\n if (!x) {\n xi = 1;\n x = xi;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n}\n\n// Precomputed Rcon lookup\nconst RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\n\n/**\n * AES block cipher algorithm.\n */\nexport class AESAlgo extends BlockCipher {\n _doReset() {\n let t;\n\n // Skip reset of nRounds has been set before and key did not change\n if (this._nRounds && this._keyPriorReset === this._key) {\n return;\n }\n\n // Shortcuts\n this._keyPriorReset = this._key;\n const key = this._keyPriorReset;\n const keyWords = key.words;\n const keySize = key.sigBytes / 4;\n\n // Compute number of rounds\n this._nRounds = keySize + 6;\n const nRounds = this._nRounds;\n\n // Compute number of key schedule rows\n const ksRows = (nRounds + 1) * 4;\n\n // Compute key schedule\n this._keySchedule = [];\n const keySchedule = this._keySchedule;\n for (let ksRow = 0; ksRow < ksRows; ksRow += 1) {\n if (ksRow < keySize) {\n keySchedule[ksRow] = keyWords[ksRow];\n } else {\n t = keySchedule[ksRow - 1];\n\n if (!(ksRow % keySize)) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t = (_SBOX[t >>> 24] << 24)\n | (_SBOX[(t >>> 16) & 0xff] << 16)\n | (_SBOX[(t >>> 8) & 0xff] << 8)\n | _SBOX[t & 0xff];\n\n // Mix Rcon\n t ^= RCON[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t = (_SBOX[t >>> 24] << 24)\n | (_SBOX[(t >>> 16) & 0xff] << 16)\n | (_SBOX[(t >>> 8) & 0xff] << 8)\n | _SBOX[t & 0xff];\n }\n\n keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;\n }\n }\n\n // Compute inv key schedule\n this._invKeySchedule = [];\n const invKeySchedule = this._invKeySchedule;\n for (let invKsRow = 0; invKsRow < ksRows; invKsRow += 1) {\n const ksRow = ksRows - invKsRow;\n\n if (invKsRow % 4) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] = INV_SUB_MIX_0[_SBOX[t >>> 24]]\n ^ INV_SUB_MIX_1[_SBOX[(t >>> 16) & 0xff]]\n ^ INV_SUB_MIX_2[_SBOX[(t >>> 8) & 0xff]]\n ^ INV_SUB_MIX_3[_SBOX[t & 0xff]];\n }\n }\n }\n\n encryptBlock(M, offset) {\n this._doCryptBlock(\n M, offset, this._keySchedule, _SUB_MIX_0, _SUB_MIX_1, _SUB_MIX_2, _SUB_MIX_3, _SBOX,\n );\n }\n\n decryptBlock(M, offset) {\n const _M = M;\n\n // Swap 2nd and 4th rows\n let t = _M[offset + 1];\n _M[offset + 1] = _M[offset + 3];\n _M[offset + 3] = t;\n\n this._doCryptBlock(\n _M,\n offset,\n this._invKeySchedule,\n INV_SUB_MIX_0,\n INV_SUB_MIX_1,\n INV_SUB_MIX_2,\n INV_SUB_MIX_3,\n INV_SBOX,\n );\n\n // Inv swap 2nd and 4th rows\n t = _M[offset + 1];\n _M[offset + 1] = _M[offset + 3];\n _M[offset + 3] = t;\n }\n\n _doCryptBlock(M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {\n const _M = M;\n\n // Shortcut\n const nRounds = this._nRounds;\n\n // Get input, add round key\n let s0 = _M[offset] ^ keySchedule[0];\n let s1 = _M[offset + 1] ^ keySchedule[1];\n let s2 = _M[offset + 2] ^ keySchedule[2];\n let s3 = _M[offset + 3] ^ keySchedule[3];\n\n // Key schedule row counter\n let ksRow = 4;\n\n // Rounds\n for (let round = 1; round < nRounds; round += 1) {\n // Shift rows, sub bytes, mix columns, add round key\n const t0 = SUB_MIX_0[s0 >>> 24]\n ^ SUB_MIX_1[(s1 >>> 16) & 0xff]\n ^ SUB_MIX_2[(s2 >>> 8) & 0xff]\n ^ SUB_MIX_3[s3 & 0xff]\n ^ keySchedule[ksRow];\n ksRow += 1;\n const t1 = SUB_MIX_0[s1 >>> 24]\n ^ SUB_MIX_1[(s2 >>> 16) & 0xff]\n ^ SUB_MIX_2[(s3 >>> 8) & 0xff]\n ^ SUB_MIX_3[s0 & 0xff]\n ^ keySchedule[ksRow];\n ksRow += 1;\n const t2 = SUB_MIX_0[s2 >>> 24]\n ^ SUB_MIX_1[(s3 >>> 16) & 0xff]\n ^ SUB_MIX_2[(s0 >>> 8) & 0xff]\n ^ SUB_MIX_3[s1 & 0xff]\n ^ keySchedule[ksRow];\n ksRow += 1;\n const t3 = SUB_MIX_0[s3 >>> 24]\n ^ SUB_MIX_1[(s0 >>> 16) & 0xff]\n ^ SUB_MIX_2[(s1 >>> 8) & 0xff]\n ^ SUB_MIX_3[s2 & 0xff]\n ^ keySchedule[ksRow];\n ksRow += 1;\n\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n }\n\n // Shift rows, sub bytes, add round key\n const t0 = (\n (SBOX[s0 >>> 24] << 24)\n | (SBOX[(s1 >>> 16) & 0xff] << 16)\n | (SBOX[(s2 >>> 8) & 0xff] << 8)\n | SBOX[s3 & 0xff]\n ) ^ keySchedule[ksRow];\n ksRow += 1;\n const t1 = (\n (SBOX[s1 >>> 24] << 24)\n | (SBOX[(s2 >>> 16) & 0xff] << 16)\n | (SBOX[(s3 >>> 8) & 0xff] << 8)\n | SBOX[s0 & 0xff]\n ) ^ keySchedule[ksRow];\n ksRow += 1;\n const t2 = (\n (SBOX[s2 >>> 24] << 24)\n | (SBOX[(s3 >>> 16) & 0xff] << 16)\n | (SBOX[(s0 >>> 8) & 0xff] << 8)\n | SBOX[s1 & 0xff]\n ) ^ keySchedule[ksRow];\n ksRow += 1;\n const t3 = (\n (SBOX[s3 >>> 24] << 24)\n | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]\n ) ^ keySchedule[ksRow];\n ksRow += 1;\n\n // Set output\n _M[offset] = t0;\n _M[offset + 1] = t1;\n _M[offset + 2] = t2;\n _M[offset + 3] = t3;\n }\n}\nAESAlgo.keySize = 256 / 32;\n\n/**\n * Shortcut functions to the cipher's object interface.\n *\n * @example\n *\n * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);\n * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);\n */\nexport const AES = BlockCipher._createHelper(AESAlgo);\n","export const ENCRYPTION_PREFIX_V1 = 'RudderEncrypt:';\nexport const ENCRYPTION_KEY_V1 = 'Rudder';\n","import { AES } from 'crypto-es/lib/aes';\nimport { Utf8 } from 'crypto-es/lib/core';\nimport { ENCRYPTION_PREFIX_V1, ENCRYPTION_KEY_V1 } from './constants';\n\nconst encrypt = (value: string): string =>\n `${ENCRYPTION_PREFIX_V1}${AES.encrypt(value, ENCRYPTION_KEY_V1).toString()}`;\n\nconst decrypt = (value: string): string => {\n if (value.startsWith(ENCRYPTION_PREFIX_V1)) {\n return AES.decrypt(value.substring(ENCRYPTION_PREFIX_V1.length), ENCRYPTION_KEY_V1).toString(\n Utf8,\n );\n }\n\n return value;\n};\n\nexport { encrypt, decrypt };\n","/* eslint-disable no-param-reassign */\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { decrypt, encrypt } from './legacyEncryptionUtils';\n\nconst pluginName: PluginName = 'StorageEncryptionLegacy';\n\nconst StorageEncryptionLegacy = (): ExtensionPlugin => ({\n name: pluginName,\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n storage: {\n encrypt(value: any): string {\n return encrypt(value);\n },\n decrypt(value: string): string {\n return decrypt(value);\n },\n },\n});\n\nexport { StorageEncryptionLegacy };\n\nexport default StorageEncryptionLegacy;\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { IStorage } from '@rudderstack/analytics-js-common/types/Store';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { checks, decrypt } from '../shared-chunks/common';\nimport { decrypt as decryptLegacy } from '../storageEncryptionLegacy/legacyEncryptionUtils';\nimport { STORAGE_MIGRATION_ERROR } from './logMessages';\nimport { STORAGE_MIGRATOR_PLUGIN } from './constants';\n\nconst pluginName: PluginName = 'StorageMigrator';\n\nconst StorageMigrator = (): ExtensionPlugin => ({\n name: pluginName,\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n storage: {\n migrate(\n key: string,\n storageEngine: IStorage,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): Nullable {\n try {\n const storedVal = storageEngine.getItem(key);\n if (checks.isNullOrUndefined(storedVal)) {\n return null;\n }\n\n let decryptedVal: string | undefined = decryptLegacy(storedVal as string);\n\n // The value is not encrypted using legacy encryption\n // Try latest\n if (decryptedVal === storedVal) {\n decryptedVal = decrypt(storedVal);\n }\n\n if (checks.isNullOrUndefined(decryptedVal)) {\n return null;\n }\n\n // storejs that is used in localstorage engine already deserializes json strings but swallows errors\n return JSON.parse(decryptedVal as string);\n } catch (err) {\n errorHandler?.onError(err, STORAGE_MIGRATOR_PLUGIN, STORAGE_MIGRATION_ERROR(key));\n return null;\n }\n },\n },\n});\n\nexport { StorageMigrator };\n\nexport default StorageMigrator;\n","const STORAGE_MIGRATOR_PLUGIN = 'StorageMigratorPlugin';\n\nexport { STORAGE_MIGRATOR_PLUGIN };\n","const STORAGE_MIGRATION_ERROR = (key: string): string =>\n `Failed to retrieve or parse data for ${key} from storage.`;\n\nexport { STORAGE_MIGRATION_ERROR };\n","const DEFAULT_RETRY_QUEUE_OPTIONS = {\n maxRetryDelay: 360000,\n minRetryDelay: 1000,\n backoffFactor: 2,\n maxAttempts: 10,\n maxItems: 100,\n};\n\nconst REQUEST_TIMEOUT_MS = 30 * 1000; // 30 seconds\n\nconst DATA_PLANE_API_VERSION = 'v1';\n\nconst QUEUE_NAME = 'rudder';\n\nconst XHR_QUEUE_PLUGIN = 'XhrQueuePlugin';\n\nexport {\n DEFAULT_RETRY_QUEUE_OPTIONS,\n REQUEST_TIMEOUT_MS,\n DATA_PLANE_API_VERSION,\n QUEUE_NAME,\n XHR_QUEUE_PLUGIN,\n};\n","import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport type { QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { IResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { clone } from 'ramda';\nimport { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp';\nimport { checks, http, url, json, eventsDelivery } from '../shared-chunks/common';\nimport { DATA_PLANE_API_VERSION, DEFAULT_RETRY_QUEUE_OPTIONS, XHR_QUEUE_PLUGIN } from './constants';\nimport type { XHRRetryQueueItemData, XHRQueueItemData, XHRBatchPayload } from './types';\nimport { EVENT_DELIVERY_FAILURE_ERROR_PREFIX } from './logMessages';\n\nconst getBatchDeliveryPayload = (\n events: RudderEvent[],\n currentTime: string,\n logger?: ILogger,\n): Nullable => {\n const batchPayload: XHRBatchPayload = { batch: events, sentAt: currentTime };\n return json.stringifyWithoutCircular(batchPayload, true, undefined, logger);\n};\n\nconst getNormalizedQueueOptions = (queueOpts: QueueOpts): QueueOpts =>\n mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS, queueOpts);\n\nconst getDeliveryUrl = (dataplaneUrl: string, endpoint: string): string => {\n const dpUrl = new URL(dataplaneUrl);\n return new URL(\n url.removeDuplicateSlashes(\n [dpUrl.pathname, '/', DATA_PLANE_API_VERSION, '/', endpoint].join(''),\n ),\n dpUrl,\n ).href;\n};\n\nconst getBatchDeliveryUrl = (dataplaneUrl: string): string => getDeliveryUrl(dataplaneUrl, 'batch');\n\nconst logErrorOnFailure = (\n details: IResponseDetails,\n url: string,\n willBeRetried?: boolean,\n attemptNumber?: number,\n maxRetryAttempts?: number,\n logger?: ILogger,\n) => {\n if (checks.isUndefined(details.error) || checks.isUndefined(logger)) {\n return;\n }\n\n const isRetryableFailure = http.isErrRetryable(details);\n let errMsg = EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN, url);\n const dropMsg = `The event(s) will be dropped.`;\n if (isRetryableFailure) {\n if (willBeRetried) {\n errMsg = `${errMsg} It/they will be retried.`;\n if ((attemptNumber as number) > 0) {\n errMsg = `${errMsg} Retry attempt ${attemptNumber} of ${maxRetryAttempts}.`;\n }\n } else {\n errMsg = `${errMsg} Retries exhausted (${maxRetryAttempts}). ${dropMsg}`;\n }\n } else {\n errMsg = `${errMsg} ${dropMsg}`;\n }\n logger?.error(errMsg);\n};\n\nconst getRequestInfo = (\n itemData: XHRRetryQueueItemData,\n state: ApplicationState,\n logger?: ILogger,\n) => {\n let data;\n let headers;\n let url: string;\n const currentTime = getCurrentTimeFormatted();\n if (Array.isArray(itemData)) {\n const finalEvents = itemData.map((queueItemData: XHRQueueItemData) =>\n eventsDelivery.getFinalEventForDeliveryMutator(queueItemData.event, currentTime),\n );\n data = getBatchDeliveryPayload(finalEvents, currentTime, logger);\n headers = itemData[0] ? clone(itemData[0].headers) : {};\n url = getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value as string);\n } else {\n const { url: eventUrl, event, headers: eventHeaders } = itemData;\n const finalEvent = eventsDelivery.getFinalEventForDeliveryMutator(event, currentTime);\n\n data = eventsDelivery.getDeliveryPayload(finalEvent, logger);\n headers = clone(eventHeaders);\n url = eventUrl;\n }\n return { data, headers, url };\n};\n\nexport {\n getNormalizedQueueOptions,\n getDeliveryUrl,\n logErrorOnFailure,\n getBatchDeliveryUrl,\n getRequestInfo,\n getBatchDeliveryPayload,\n};\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst EVENT_DELIVERY_FAILURE_ERROR_PREFIX = (context: string, url: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to deliver event(s) to ${url}.`;\n\nexport { EVENT_DELIVERY_FAILURE_ERROR_PREFIX };\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp';\nimport { storages, http, timestamp, string, eventsDelivery } from '../shared-chunks/common';\nimport {\n getNormalizedQueueOptions,\n getDeliveryUrl,\n logErrorOnFailure,\n getRequestInfo,\n getBatchDeliveryPayload,\n} from './utilities';\nimport type { DoneCallback, IQueue, QueueItemData } from '../types/plugins';\nimport { RetryQueue } from '../utilities/retryQueue/RetryQueue';\nimport { QUEUE_NAME, REQUEST_TIMEOUT_MS } from './constants';\nimport type { XHRRetryQueueItemData, XHRQueueItemData } from './types';\n\nconst pluginName: PluginName = 'XhrQueue';\n\nconst XhrQueue = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n dataplaneEventsQueue: {\n /**\n * Initialize the queue for delivery\n * @param state Application state\n * @param httpClient http client instance\n * @param storeManager Store Manager instance\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns RetryQueue instance\n */\n init(\n state: ApplicationState,\n httpClient: IHttpClient,\n storeManager: IStoreManager,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): IQueue {\n const writeKey = state.lifecycle.writeKey.value as string;\n httpClient.setAuthHeader(writeKey);\n\n const finalQOpts = getNormalizedQueueOptions(\n state.loadOptions.value.queueOptions as QueueOpts,\n );\n\n const eventsQueue = new RetryQueue(\n // adding write key to the queue name to avoid conflicts\n `${QUEUE_NAME}_${writeKey}`,\n finalQOpts,\n (\n itemData: QueueItemData,\n done: DoneCallback,\n attemptNumber?: number,\n maxRetryAttempts?: number,\n willBeRetried?: boolean,\n ) => {\n const { data, url, headers } = getRequestInfo(\n itemData as XHRRetryQueueItemData,\n state,\n logger,\n );\n\n httpClient.request({\n url,\n options: {\n method: 'POST',\n headers,\n body: data as string,\n sendRawData: true,\n },\n isRawResponse: true,\n timeout: REQUEST_TIMEOUT_MS,\n callback: (result, details) => {\n // null means item will not be requeued\n const queueErrResp = http.isErrRetryable(details) ? details : null;\n\n logErrorOnFailure(\n details,\n url,\n willBeRetried,\n attemptNumber,\n maxRetryAttempts,\n logger,\n );\n\n done(queueErrResp, result);\n },\n });\n },\n storeManager,\n storages.LOCAL_STORAGE,\n logger,\n (itemData: XHRQueueItemData[]): number => {\n const currentTime = getCurrentTimeFormatted();\n const events = itemData.map((queueItemData: XHRQueueItemData) => queueItemData.event);\n // type casting to string as we know that the event has already been validated prior to enqueue\n return (getBatchDeliveryPayload(events, currentTime, logger) as string)?.length;\n },\n );\n\n return eventsQueue;\n },\n\n /**\n * Add event to the queue for delivery\n * @param state Application state\n * @param eventsQueue RetryQueue instance\n * @param event RudderEvent object\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns none\n */\n enqueue(\n state: ApplicationState,\n eventsQueue: IQueue,\n event: RudderEvent,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): void {\n // sentAt is only added here for the validation step\n // It'll be updated to the latest timestamp during actual delivery\n event.sentAt = timestamp.getCurrentTimeFormatted();\n eventsDelivery.validateEventPayloadSize(event, logger);\n\n const dataplaneUrl = state.lifecycle.activeDataplaneUrl.value as string;\n const url = getDeliveryUrl(dataplaneUrl, event.type);\n // Other default headers are added by the HttpClient\n // Auth header is added during initialization\n const headers = {\n // To maintain event ordering while using the HTTP API as per is documentation,\n // make sure to include anonymousId as a header\n AnonymousId: string.toBase64(event.anonymousId),\n };\n\n eventsQueue.addItem({\n url,\n headers,\n event,\n } as XHRRetryQueueItemData);\n },\n },\n});\n\nexport { XhrQueue };\n\nexport default XhrQueue;\n","const DEFAULT_RETRY_QUEUE_OPTIONS = {\n maxRetryDelay: 360000,\n minRetryDelay: 1000,\n backoffFactor: 2,\n maxAttempts: 10,\n maxItems: 100,\n};\n\nconst REQUEST_TIMEOUT_MS = 30 * 1000; // 30 seconds\n\nconst DATA_PLANE_API_VERSION = 'v1';\n\nconst QUEUE_NAME = 'rudder';\n\nconst FETCH_QUEUE_PLUGIN = 'FetchQueuePlugin';\n\nexport {\n DEFAULT_RETRY_QUEUE_OPTIONS,\n REQUEST_TIMEOUT_MS,\n DATA_PLANE_API_VERSION,\n QUEUE_NAME,\n FETCH_QUEUE_PLUGIN,\n};\n","import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport type { QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { IResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { clone } from 'ramda';\nimport { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp';\nimport { checks, http, url, json, eventsDelivery } from '../shared-chunks/common';\nimport {\n DATA_PLANE_API_VERSION,\n DEFAULT_RETRY_QUEUE_OPTIONS,\n FETCH_QUEUE_PLUGIN,\n} from './constants';\nimport type { FetchRetryQueueItemData, FetchQueueItemData, FetchBatchPayload } from './types';\nimport { EVENT_DELIVERY_FAILURE_ERROR_PREFIX } from './logMessages';\n\nconst getBatchDeliveryPayload = (\n events: RudderEvent[],\n currentTime: string,\n logger?: ILogger,\n): Nullable => {\n const batchPayload: FetchBatchPayload = { batch: events, sentAt: currentTime };\n return json.stringifyWithoutCircular(batchPayload, true, undefined, logger);\n};\n\nconst getNormalizedQueueOptions = (queueOpts: QueueOpts): QueueOpts =>\n mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS, queueOpts);\n\nconst getDeliveryUrl = (dataplaneUrl: string, endpoint: string): string => {\n const dpUrl = new URL(dataplaneUrl);\n return new URL(\n url.removeDuplicateSlashes(\n [dpUrl.pathname, '/', DATA_PLANE_API_VERSION, '/', endpoint].join(''),\n ),\n dpUrl,\n ).href;\n};\n\nconst getBatchDeliveryUrl = (dataplaneUrl: string): string => getDeliveryUrl(dataplaneUrl, 'batch');\n\nconst logErrorOnFailure = (\n details: IResponseDetails,\n url: string,\n willBeRetried?: boolean,\n attemptNumber?: number,\n maxRetryAttempts?: number,\n logger?: ILogger,\n) => {\n if (checks.isUndefined(details.error) || checks.isUndefined(logger)) {\n return;\n }\n\n const isRetryableFailure = http.isErrRetryable(details);\n let errMsg = EVENT_DELIVERY_FAILURE_ERROR_PREFIX(FETCH_QUEUE_PLUGIN, url);\n const dropMsg = `The event(s) will be dropped.`;\n if (isRetryableFailure) {\n if (willBeRetried) {\n errMsg = `${errMsg} It/they will be retried.`;\n if ((attemptNumber as number) > 0) {\n errMsg = `${errMsg} Retry attempt ${attemptNumber} of ${maxRetryAttempts}.`;\n }\n } else {\n errMsg = `${errMsg} Retries exhausted (${maxRetryAttempts}). ${dropMsg}`;\n }\n } else {\n errMsg = `${errMsg} ${dropMsg}`;\n }\n logger?.error(errMsg);\n};\n\nconst getRequestInfo = (\n itemData: FetchRetryQueueItemData,\n state: ApplicationState,\n logger?: ILogger,\n) => {\n let data;\n let headers;\n let url: string;\n const currentTime = getCurrentTimeFormatted();\n if (Array.isArray(itemData)) {\n const finalEvents = itemData.map((queueItemData: FetchQueueItemData) =>\n eventsDelivery.getFinalEventForDeliveryMutator(queueItemData.event, currentTime),\n );\n data = getBatchDeliveryPayload(finalEvents, currentTime, logger);\n headers = itemData[0] ? clone(itemData[0].headers) : {};\n url = getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value as string);\n } else {\n const { url: eventUrl, event, headers: eventHeaders } = itemData;\n const finalEvent = eventsDelivery.getFinalEventForDeliveryMutator(event, currentTime);\n\n data = eventsDelivery.getDeliveryPayload(finalEvent, logger);\n headers = clone(eventHeaders);\n url = eventUrl;\n }\n return { data, headers, url };\n};\n\nexport {\n getNormalizedQueueOptions,\n getDeliveryUrl,\n logErrorOnFailure,\n getBatchDeliveryUrl,\n getRequestInfo,\n getBatchDeliveryPayload,\n};\n","import { LOG_CONTEXT_SEPARATOR } from '@rudderstack/analytics-js-common/constants/logMessages';\n\nconst EVENT_DELIVERY_FAILURE_ERROR_PREFIX = (context: string, url: string): string =>\n `${context}${LOG_CONTEXT_SEPARATOR}Failed to deliver event(s) to ${url}.`;\n\nexport { EVENT_DELIVERY_FAILURE_ERROR_PREFIX };\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable no-param-reassign */\nimport type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { QueueOpts } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp';\nimport { storages, http, timestamp, string, eventsDelivery } from '../shared-chunks/common';\nimport {\n getNormalizedQueueOptions,\n getDeliveryUrl,\n logErrorOnFailure,\n getRequestInfo,\n getBatchDeliveryPayload,\n} from './utilities';\nimport type { DoneCallback, IQueue, QueueItemData } from '../types/plugins';\nimport { RetryQueue } from '../utilities/retryQueue/RetryQueue';\nimport { QUEUE_NAME, REQUEST_TIMEOUT_MS } from './constants';\nimport type { FetchRetryQueueItemData, FetchQueueItemData } from './types';\n\nconst pluginName: PluginName = 'FetchQueue';\n\nconst FetchQueue = (): ExtensionPlugin => ({\n name: pluginName,\n deps: [],\n initialize: (state: ApplicationState) => {\n state.plugins.loadedPlugins.value = [...state.plugins.loadedPlugins.value, pluginName];\n },\n dataplaneEventsQueue: {\n /**\n * Initialize the queue for delivery\n * @param state Application state\n * @param httpClient http client instance\n * @param storeManager Store Manager instance\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns RetryQueue instance\n */\n init(\n state: ApplicationState,\n httpClient: IHttpClient,\n storeManager: IStoreManager,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): IQueue {\n const writeKey = state.lifecycle.writeKey.value as string;\n httpClient.setAuthHeader(writeKey);\n\n const finalQOpts = getNormalizedQueueOptions(\n state.loadOptions.value.queueOptions as QueueOpts,\n );\n\n const eventsQueue = new RetryQueue(\n // adding write key to the queue name to avoid conflicts\n `${QUEUE_NAME}_${writeKey}`,\n finalQOpts,\n (\n itemData: QueueItemData,\n done: DoneCallback,\n attemptNumber?: number,\n maxRetryAttempts?: number,\n willBeRetried?: boolean,\n ) => {\n const { data, url, headers } = getRequestInfo(\n itemData as FetchRetryQueueItemData,\n state,\n logger,\n );\n\n httpClient.request({\n url,\n options: {\n method: 'POST',\n headers,\n body: data as string,\n sendRawData: true,\n },\n isRawResponse: true,\n timeout: REQUEST_TIMEOUT_MS,\n callback: (result, details) => {\n // null means item will not be requeued\n const queueErrResp = http.isErrRetryable(details) ? details : null;\n\n logErrorOnFailure(\n details,\n url,\n willBeRetried,\n attemptNumber,\n maxRetryAttempts,\n logger,\n );\n\n done(queueErrResp, result);\n },\n });\n },\n storeManager,\n storages.LOCAL_STORAGE,\n logger,\n (itemData: FetchQueueItemData[]): number => {\n const currentTime = getCurrentTimeFormatted();\n const events = itemData.map((queueItemData: FetchQueueItemData) => queueItemData.event);\n // type casting to string as we know that the event has already been validated prior to enqueue\n return (getBatchDeliveryPayload(events, currentTime, logger) as string)?.length;\n },\n );\n\n return eventsQueue;\n },\n\n /**\n * Add event to the queue for delivery\n * @param state Application state\n * @param eventsQueue RetryQueue instance\n * @param event RudderEvent object\n * @param errorHandler Error handler instance\n * @param logger Logger instance\n * @returns none\n */\n enqueue(\n state: ApplicationState,\n eventsQueue: IQueue,\n event: RudderEvent,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ): void {\n // sentAt is only added here for the validation step\n // It'll be updated to the latest timestamp during actual delivery\n event.sentAt = timestamp.getCurrentTimeFormatted();\n eventsDelivery.validateEventPayloadSize(event, logger);\n\n const dataplaneUrl = state.lifecycle.activeDataplaneUrl.value as string;\n const url = getDeliveryUrl(dataplaneUrl, event.type);\n // Other default headers are added by the HttpClient\n // Auth header is added during initialization\n const headers = {\n // To maintain event ordering while using the HTTP API as per is documentation,\n // make sure to include anonymousId as a header\n AnonymousId: string.toBase64(event.anonymousId),\n };\n\n eventsQueue.addItem({\n url,\n headers,\n event,\n } as FetchRetryQueueItemData);\n },\n },\n});\n\nexport { FetchQueue };\n\nexport default FetchQueue;\n","import type { ExtensionPlugin } from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { PluginMap } from './types';\nimport { getBundledBuildPluginImports } from './bundledBuildPluginImports';\nimport { federatedModulesBuildPluginImports } from './federatedModulesBuildPluginImports';\n\n/**\n * Map of mandatory plugin names and direct imports\n */\nconst getMandatoryPluginsMap = (): PluginMap => ({}) as PluginMap;\n\n/**\n * Map of optional plugin names and direct imports for legacy builds\n */\nconst getOptionalPluginsMap = (): PluginMap => {\n if (!__BUNDLE_ALL_PLUGINS__) {\n return {} as PluginMap;\n }\n\n return getBundledBuildPluginImports();\n};\n\n/**\n * Map of optional plugin names and dynamic imports for modern builds\n */\nconst getRemotePluginsMap = (\n activePluginNames: PluginName[],\n): PluginMap> => {\n if (__BUNDLE_ALL_PLUGINS__) {\n return {} as PluginMap>;\n }\n\n return federatedModulesBuildPluginImports?.(activePluginNames) || {};\n};\n\nconst pluginsInventory: PluginMap = {\n ...getMandatoryPluginsMap(),\n ...getOptionalPluginsMap(),\n};\n\nconst remotePluginsInventory = (\n activePluginNames: PluginName[],\n): PluginMap> => ({\n ...getRemotePluginsMap(activePluginNames),\n});\n\nexport { pluginsInventory, remotePluginsInventory, getMandatoryPluginsMap };\n","import { BeaconQueue } from '@rudderstack/analytics-js-plugins/beaconQueue';\nimport { Bugsnag } from '@rudderstack/analytics-js-plugins/bugsnag';\nimport { CustomConsentManager } from '@rudderstack/analytics-js-plugins/customConsentManager';\nimport { DeviceModeDestinations } from '@rudderstack/analytics-js-plugins/deviceModeDestinations';\nimport { DeviceModeTransformation } from '@rudderstack/analytics-js-plugins/deviceModeTransformation';\nimport { ErrorReporting } from '@rudderstack/analytics-js-plugins/errorReporting';\nimport { ExternalAnonymousId } from '@rudderstack/analytics-js-plugins/externalAnonymousId';\nimport { GoogleLinker } from '@rudderstack/analytics-js-plugins/googleLinker';\nimport { KetchConsentManager } from '@rudderstack/analytics-js-plugins/ketchConsentManager';\nimport { NativeDestinationQueue } from '@rudderstack/analytics-js-plugins/nativeDestinationQueue';\nimport { OneTrustConsentManager } from '@rudderstack/analytics-js-plugins/oneTrustConsentManager';\nimport { StorageEncryption } from '@rudderstack/analytics-js-plugins/storageEncryption';\nimport { StorageEncryptionLegacy } from '@rudderstack/analytics-js-plugins/storageEncryptionLegacy';\nimport { StorageMigrator } from '@rudderstack/analytics-js-plugins/storageMigrator';\nimport { XhrQueue } from '@rudderstack/analytics-js-plugins/xhrQueue';\nimport { FetchQueue } from '@rudderstack/analytics-js-plugins/fetchQueue';\nimport type { PluginMap } from './types';\n\n/**\n * Map plugin names to direct code imports from plugins package\n */\nconst getBundledBuildPluginImports = (): PluginMap => ({\n BeaconQueue,\n Bugsnag,\n CustomConsentManager,\n DeviceModeDestinations,\n DeviceModeTransformation,\n ErrorReporting,\n ExternalAnonymousId,\n GoogleLinker,\n KetchConsentManager,\n NativeDestinationQueue,\n OneTrustConsentManager,\n StorageEncryption,\n StorageEncryptionLegacy,\n StorageMigrator,\n XhrQueue,\n FetchQueue,\n});\n\nexport { getBundledBuildPluginImports };\n","import { batch, effect } from '@preact/signals-core';\nimport type {\n ExtensionPlugin,\n IPluginEngine,\n} from '@rudderstack/analytics-js-common/types/PluginEngine';\nimport { getNonCloudDestinations } from '@rudderstack/analytics-js-common/utilities/destinations';\nimport type {\n IPluginsManager,\n PluginName,\n} from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { PLUGINS_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { isDefined, isFunction } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { generateMisconfiguredPluginsWarning } from '../../constants/logMessages';\nimport { setExposedGlobal } from '../utilities/globals';\nimport { state } from '../../state';\nimport {\n ConsentManagersToPluginNameMap,\n StorageEncryptionVersionsToPluginNameMap,\n DataPlaneEventsTransportToPluginNameMap,\n} from '../configManager/constants';\nimport { pluginNamesList } from './pluginNames';\nimport {\n getMandatoryPluginsMap,\n pluginsInventory,\n remotePluginsInventory,\n} from './pluginsInventory';\nimport type { PluginsGroup } from './types';\n\n// TODO: we may want to add chained plugins that pass their value to the next one\n// TODO: add retry mechanism for getting remote plugins\n// TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state\nclass PluginsManager implements IPluginsManager {\n engine: IPluginEngine;\n errorHandler?: IErrorHandler;\n logger?: ILogger;\n\n constructor(engine: IPluginEngine, errorHandler?: IErrorHandler, logger?: ILogger) {\n this.engine = engine;\n\n this.errorHandler = errorHandler;\n this.logger = logger;\n this.onError = this.onError.bind(this);\n }\n\n /**\n * Orchestrate the plugin loading and registering\n */\n init() {\n state.lifecycle.status.value = 'pluginsLoading';\n // Expose pluginsCDNPath to global object, so it can be used in the promise that determines\n // remote plugin cdn path to support proxied plugin remotes\n if (!__BUNDLE_ALL_PLUGINS__) {\n setExposedGlobal('pluginsCDNPath', state.lifecycle.pluginsCDNPath.value);\n }\n this.setActivePlugins();\n this.registerLocalPlugins();\n this.registerRemotePlugins();\n this.attachEffects();\n }\n\n /**\n * Update state based on plugin loaded status\n */\n // eslint-disable-next-line class-methods-use-this\n attachEffects() {\n effect(() => {\n const isAllPluginsReady =\n state.plugins.activePlugins.value.length === 0 ||\n state.plugins.loadedPlugins.value.length + state.plugins.failedPlugins.value.length ===\n state.plugins.totalPluginsToLoad.value;\n\n if (isAllPluginsReady) {\n batch(() => {\n state.plugins.ready.value = true;\n // TODO: decide what to do if a plugin fails to load for any reason.\n // Should we stop here or should we progress?\n state.lifecycle.status.value = 'pluginsReady';\n });\n }\n });\n }\n\n /**\n * Determine the list of plugins that should be loaded based on sourceConfig & load options\n */\n // eslint-disable-next-line class-methods-use-this\n getPluginsToLoadBasedOnConfig(): PluginName[] {\n // This contains the default plugins if load option has been omitted by user\n let pluginsToLoadFromConfig = state.plugins.pluginsToLoadFromConfig.value as PluginName[];\n\n if (!pluginsToLoadFromConfig) {\n return [];\n }\n\n // TODO: Uncomment below lines after removing deprecated plugin\n // Filter deprecated plugins\n // pluginsToLoadFromConfig = pluginsToLoadFromConfig.filter(pluginName => {\n // if (deprecatedPluginsList.includes(pluginName)) {\n // this.logger?.warn(DEPRECATED_PLUGIN_WARNING(PLUGINS_MANAGER, pluginName));\n // return false;\n // }\n // return true;\n // });\n\n const pluginGroupsToProcess: PluginsGroup[] = [\n {\n configurationStatus: () => isDefined(state.dataPlaneEvents.eventsQueuePluginName.value),\n configurationStatusStr: 'Data plane events delivery is enabled',\n activePluginName: state.dataPlaneEvents.eventsQueuePluginName.value,\n supportedPlugins: Object.values(DataPlaneEventsTransportToPluginNameMap),\n shouldAddMissingPlugins: true,\n },\n {\n configurationStatus: () => state.reporting.isErrorReportingEnabled.value,\n configurationStatusStr: 'Error reporting is enabled',\n supportedPlugins: ['ErrorReporting', 'Bugsnag'] as PluginName[], // TODO: Remove deprecated plugin- Bugsnag\n },\n {\n configurationStatus: () =>\n getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).length > 0,\n configurationStatusStr: 'Device mode destinations are connected to the source',\n supportedPlugins: ['DeviceModeDestinations', 'NativeDestinationQueue'] as PluginName[],\n },\n {\n configurationStatus: () =>\n getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).some(\n destination => destination.shouldApplyDeviceModeTransformation,\n ),\n configurationStatusStr:\n 'Device mode transformations are enabled for at least one destination',\n supportedPlugins: ['DeviceModeTransformation'] as PluginName[],\n },\n {\n configurationStatus: () => isDefined(state.consents.activeConsentManagerPluginName.value),\n configurationStatusStr: 'Consent management is enabled',\n activePluginName: state.consents.activeConsentManagerPluginName.value,\n supportedPlugins: Object.values(ConsentManagersToPluginNameMap),\n },\n {\n configurationStatus: () => isDefined(state.storage.encryptionPluginName.value),\n configurationStatusStr: 'Storage encryption is enabled',\n activePluginName: state.storage.encryptionPluginName.value,\n supportedPlugins: Object.values(StorageEncryptionVersionsToPluginNameMap),\n },\n {\n configurationStatus: () => state.storage.migrate.value,\n configurationStatusStr: 'Storage migration is enabled',\n supportedPlugins: ['StorageMigrator'],\n },\n ];\n\n const addMissingPlugins = false;\n pluginGroupsToProcess.forEach(group => {\n if (group.configurationStatus()) {\n pluginsToLoadFromConfig = pluginsToLoadFromConfig.filter(\n group.activePluginName\n ? pluginName =>\n !(\n pluginName !== group.activePluginName &&\n group.supportedPlugins.includes(pluginName)\n )\n : pluginName => isDefined(pluginName), // pass through\n );\n\n this.addMissingPlugins(group, addMissingPlugins, pluginsToLoadFromConfig);\n } else {\n pluginsToLoadFromConfig = pluginsToLoadFromConfig.filter(\n group.basePlugins !== undefined\n ? pluginName =>\n !(\n (group.basePlugins as PluginName[]).includes(pluginName) ||\n group.supportedPlugins.includes(pluginName)\n )\n : pluginName => !group.supportedPlugins.includes(pluginName),\n );\n }\n });\n\n return [...(Object.keys(getMandatoryPluginsMap()) as PluginName[]), ...pluginsToLoadFromConfig];\n }\n\n private addMissingPlugins(\n group: PluginsGroup,\n addMissingPlugins: boolean,\n pluginsToLoadFromConfig: PluginName[],\n ) {\n const shouldAddMissingPlugins = group.shouldAddMissingPlugins || addMissingPlugins;\n let pluginsToConfigure;\n if (group.activePluginName) {\n pluginsToConfigure = [...(group.basePlugins || []), group.activePluginName] as PluginName[];\n } else {\n pluginsToConfigure = [...group.supportedPlugins];\n }\n\n const missingPlugins = pluginsToConfigure.filter(\n pluginName => !pluginsToLoadFromConfig.includes(pluginName),\n );\n if (missingPlugins.length > 0) {\n if (shouldAddMissingPlugins) {\n pluginsToLoadFromConfig.push(...missingPlugins);\n }\n\n this.logger?.warn(\n generateMisconfiguredPluginsWarning(\n PLUGINS_MANAGER,\n group.configurationStatusStr,\n missingPlugins,\n shouldAddMissingPlugins,\n ),\n );\n }\n }\n\n /**\n * Determine the list of plugins that should be activated\n */\n setActivePlugins() {\n const pluginsToLoad = this.getPluginsToLoadBasedOnConfig();\n // Merging available mandatory and optional plugin name list\n const availablePlugins = [...Object.keys(pluginsInventory), ...pluginNamesList];\n const activePlugins: PluginName[] = [];\n const failedPlugins: string[] = [];\n\n pluginsToLoad.forEach(pluginName => {\n if (availablePlugins.includes(pluginName)) {\n activePlugins.push(pluginName);\n } else {\n failedPlugins.push(pluginName);\n }\n });\n\n if (failedPlugins.length > 0) {\n this.onError(\n new Error(\n `Ignoring loading of unknown plugins: ${failedPlugins.join(\n ',',\n )}. Mandatory plugins: ${Object.keys(getMandatoryPluginsMap()).join(\n ',',\n )}. Load option plugins: ${state.plugins.pluginsToLoadFromConfig.value.join(',')}`,\n ),\n );\n }\n\n batch(() => {\n state.plugins.totalPluginsToLoad.value = pluginsToLoad.length;\n state.plugins.activePlugins.value = activePlugins;\n state.plugins.failedPlugins.value = failedPlugins;\n });\n }\n\n /**\n * Register plugins that are direct imports to PluginEngine\n */\n registerLocalPlugins() {\n Object.values(pluginsInventory).forEach(localPlugin => {\n if (\n isFunction(localPlugin) &&\n state.plugins.activePlugins.value.includes(localPlugin().name)\n ) {\n this.register([localPlugin()]);\n }\n });\n }\n\n /**\n * Register plugins that are dynamic imports to PluginEngine\n */\n registerRemotePlugins() {\n const remotePluginsList = remotePluginsInventory(\n state.plugins.activePlugins.value as PluginName[],\n );\n\n Promise.all(\n Object.keys(remotePluginsList).map(async remotePluginKey => {\n await remotePluginsList[remotePluginKey as PluginName]()\n .then((remotePluginModule: any) => this.register([remotePluginModule.default()]))\n .catch(err => {\n // TODO: add retry here if dynamic import fails\n state.plugins.failedPlugins.value = [\n ...state.plugins.failedPlugins.value,\n remotePluginKey,\n ];\n this.onError(err, remotePluginKey);\n });\n }),\n ).catch(err => {\n this.onError(err);\n });\n }\n\n /**\n * Extension point invoke that allows multiple plugins to be registered to it with error handling\n */\n invokeMultiple(extPoint?: string, ...args: any[]): Nullable[] {\n try {\n return this.engine.invokeMultiple(extPoint, ...args);\n } catch (e) {\n this.onError(e, extPoint);\n return [];\n }\n }\n\n /**\n * Extension point invoke that allows a single plugin to be registered to it with error handling\n */\n invokeSingle(extPoint?: string, ...args: any[]): Nullable {\n try {\n return this.engine.invokeSingle(extPoint, ...args);\n } catch (e) {\n this.onError(e, extPoint);\n return null;\n }\n }\n\n /**\n * Plugin engine register with error handling\n */\n register(plugins: ExtensionPlugin[]) {\n plugins.forEach(plugin => {\n try {\n this.engine.register(plugin, state);\n } catch (e) {\n state.plugins.failedPlugins.value = [...state.plugins.failedPlugins.value, plugin.name];\n this.onError(e);\n }\n });\n }\n\n // TODO: Implement reset API instead\n unregisterLocalPlugins() {\n Object.values(pluginsInventory).forEach(localPlugin => {\n try {\n this.engine.unregister(localPlugin().name);\n } catch (e) {\n this.onError(e);\n }\n });\n }\n\n /**\n * Handle errors\n */\n onError(error: unknown, customMessage?: string): void {\n if (this.errorHandler) {\n this.errorHandler.onError(error, PLUGINS_MANAGER, customMessage);\n } else {\n throw error;\n }\n }\n}\n\nexport { PluginsManager };\n","import type { IHttpClientError } from \"@rudderstack/analytics-js-common/types/HttpClient\";\n\nclass HttpClientError extends Error implements IHttpClientError {\n public status?: number;\n public statusText?: string;\n public responseBody?: string | null;\n\n constructor(message: string, status?: number, statusText?: string, responseBody?: string | null) {\n super(message);\n this.name = 'HttpClientError';\n this.status = status;\n this.statusText = statusText;\n this.responseBody = responseBody;\n }\n}\n\nexport { HttpClientError };\n","import { FAILED_REQUEST_ERR_MSG_PREFIX } from \"@rudderstack/analytics-js-common/constants/errors\";\nimport type { IXHRRequestOptions } from \"@rudderstack/analytics-js-common/types/HttpClient\";\nimport { clone } from \"ramda\";\nimport { DELIVERY_ERROR, REQUEST_ERROR, XHR_SEND_ERROR } from \"../../../constants/logMessages\";\nimport { HttpClientError } from \"../utils\";\n\nconst makeXHRRequest = (\n url: string | URL,\n options: IXHRRequestOptions): Promise =>\n new Promise((resolve, reject) => { \n const xhr = new XMLHttpRequest();\n const xhrReject = (e?: ProgressEvent) => {\n reject(\n new HttpClientError(\n DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, xhr.status, xhr.statusText, url, e),\n xhr.status,\n xhr.statusText,\n xhr.responseText,\n ));\n };\n const xhrError = (e?: ProgressEvent) => {\n reject(\n new HttpClientError(\n REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, url, options.timeout as number, e),\n xhr.status,\n xhr.statusText,\n xhr.responseText,\n ));\n };\n\n xhr.ontimeout = xhrError;\n xhr.onerror = xhrError;\n \n xhr.onload = () => {\n if (xhr.status >= 200 && xhr.status < 400) {\n resolve(\n new Response(xhr.responseText, {\n status: xhr.status,\n statusText: xhr.statusText,\n }));\n } else {\n xhrReject();\n }\n };\n \n xhr.open(options.method, url);\n if (options.withCredentials === true) {\n xhr.withCredentials = true;\n }\n // The timeout property may be set only in the time interval between a call to the open method\n // and the first call to the send method in legacy browsers\n xhr.timeout = options.timeout as number;\n \n if (options.headers) {\n Object.entries(options.headers).forEach(([headerName, headerValue]) => {\n xhr.setRequestHeader(headerName, headerValue);\n });\n }\n \n try {\n xhr.send(options.body);\n } catch (err: any) {\n // clone the error object and add the status, statusText, and responseBody properties\n const clonedErr: HttpClientError = clone(err);\n clonedErr.message = `${XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, url)}: ${err.message}`;\n clonedErr.status = xhr.status;\n clonedErr.statusText = xhr.statusText;\n clonedErr.responseBody = xhr.responseText;\n\n reject(clonedErr);\n }\n });\n\nexport { makeXHRRequest };\n","import type { IFetchRequestOptions } from \"@rudderstack/analytics-js-common/types/HttpClient\";\nimport { FAILED_REQUEST_ERR_MSG_PREFIX } from \"@rudderstack/analytics-js-common/constants/errors\";\nimport { clone } from \"ramda\";\nimport { DELIVERY_ERROR, REQUEST_ERROR } from \"../../../constants/logMessages\";\nimport { HttpClientError } from \"../utils\";\n\nconst makeFetchRequest = (\n url: string | URL,\n options: IFetchRequestOptions): Promise =>\n {\n const controller = new AbortController();\n const { signal } = controller;\n const fetchOptions: RequestInit = { ...options, signal };\n\n const fetchPromise = (globalThis as typeof window).fetch(url, fetchOptions)\n .then(response => {\n if (!response.ok) {\n return response.text().then(body => {\n throw new HttpClientError(\n DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, response.status, response.statusText, url),\n response.status,\n response.statusText,\n body\n );\n });\n }\n return response;\n })\n .catch(err => {\n if (err.name === 'HttpClientError') {\n throw err;\n }\n\n const clonedErr = clone(err);\n clonedErr.message = `${REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, url, options.timeout as number)}: ${err.message}`;\n\n throw clonedErr;\n });\n\n // Implement the timeout logic\n if (options.timeout) {\n const timeoutId = setTimeout(() => controller.abort(), options.timeout);\n return fetchPromise.finally(() => clearTimeout(timeoutId));\n } \n return fetchPromise;\n }\n\nexport { makeFetchRequest };\n","import type { IBeaconRequestOptions } from \"@rudderstack/analytics-js-common/types/HttpClient\";\nimport { HttpClientError } from \"../utils\";\n\nconst makeBeaconRequest = (\n url: string | URL,\n options: IBeaconRequestOptions): Promise => {\n const success = navigator.sendBeacon(url, options.body);\n if (!success) {\n return Promise.reject(new HttpClientError(\n \"Beacon request failed\",\n ));\n }\n\n return Promise.resolve(new Response(null, { status: 204 }));\n };\n\nexport { makeBeaconRequest };\n","import { isFunction, isNull } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type {\n IAsyncRequestConfig,\n IFetchRequestOptions,\n IHttpClient,\n IHttpClientError,\n IRequestOptions,\n IXHRRequestOptions,\n} from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { toBase64 } from '@rudderstack/analytics-js-common/utilities/string';\nimport { HTTP_CLIENT } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport type { TransportType } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport { clone } from 'ramda';\nimport { DEFAULT_REQ_TIMEOUT_MS } from '../../constants/timeouts';\nimport { PAYLOAD_PREP_ERROR } from '../../constants/logMessages';\nimport { defaultErrorHandler } from '../ErrorHandler';\nimport { defaultLogger } from '../Logger';\nimport { HttpClientError } from './utils';\nimport { makeXHRRequest } from './xhr';\nimport { makeFetchRequest } from './fetch';\nimport { makeBeaconRequest } from './beacon';\n\nconst DEFAULT_REQUEST_OPTIONS: Partial = {\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json;charset=UTF-8',\n },\n timeout: DEFAULT_REQ_TIMEOUT_MS,\n method: 'GET',\n};\n\n// TODO: should we add any debug level loggers?\n\n/**\n * Service to handle data communication with APIs\n */\nclass HttpClient implements IHttpClient {\n errorHandler?: IErrorHandler;\n logger?: ILogger;\n basicAuthHeader?: string;\n transportFn: (url: string | URL, options: any) => Promise;\n\n constructor(transportType: TransportType, errorHandler?: IErrorHandler, logger?: ILogger) {\n switch (transportType) {\n case 'xhr':\n this.transportFn = makeXHRRequest;\n break;\n case 'beacon':\n this.transportFn = makeBeaconRequest;\n break;\n case 'fetch':\n default:\n this.transportFn = makeFetchRequest;\n break;\n }\n this.errorHandler = errorHandler;\n this.logger = logger;\n this.onError = this.onError.bind(this);\n }\n\n /**\n * Implement requests in a non-blocking way\n */\n request(config: IAsyncRequestConfig) {\n const { callback, url, options, isRawResponse } = config;\n const isFireAndForget = !isFunction(callback);\n\n const finalOptions = mergeDeepRight(\n DEFAULT_REQUEST_OPTIONS,\n options || {},\n ) as IRequestOptions;\n \n if (finalOptions.body && !finalOptions.sendRawData) {\n const payload = stringifyWithoutCircular(finalOptions.body, false, [], this.logger);\n // return and don't process further if the payload could not be stringified\n if (isNull(payload)) {\n const err = new HttpClientError(PAYLOAD_PREP_ERROR);\n this.onError(err);\n if (!isFireAndForget) {\n callback(err.responseBody, {\n error: err,\n url,\n options: finalOptions,\n });\n }\n return;\n }\n\n finalOptions.body = payload;\n }\n\n if ((finalOptions as IXHRRequestOptions | IFetchRequestOptions).headers) {\n (finalOptions as IXHRRequestOptions | IFetchRequestOptions).headers = mergeDeepRight({\n Authorization: this.basicAuthHeader,\n }, (finalOptions as IXHRRequestOptions | IFetchRequestOptions).headers ?? {});\n }\n\n this.transportFn(url, finalOptions).then((response: Response) => {\n if (!isFireAndForget) {\n const finalDataPromise = isRawResponse ? response.text() : response.json();\n finalDataPromise.then((data) => {\n callback(data, {\n response,\n url,\n options: finalOptions,\n });\n }).catch((err: Error) => {\n const finalError = clone(err);\n finalError.message = `Failed to parse response data: ${err.message}`;\n\n this.onError(finalError);\n\n callback(undefined, {\n error: finalError,\n url,\n options: finalOptions,\n });\n });\n }\n })\n .catch((error: IHttpClientError) => {\n this.onError(error);\n if (!isFireAndForget) {\n callback(error.responseBody, {\n error,\n url,\n options: finalOptions,\n });\n }\n });\n }\n\n getAsyncData(config: IAsyncRequestConfig) {\n this.request(config);\n }\n\n /**\n * Handle errors\n */\n onError(error: unknown) {\n if (this.errorHandler) {\n this.errorHandler?.onError(error, HTTP_CLIENT);\n } else {\n throw error;\n }\n }\n\n /**\n * Set basic authentication header\n */\n setAuthHeader(value: string, noBtoa = false) {\n const authVal = noBtoa ? value : toBase64(`${value}:`);\n this.basicAuthHeader = `Basic ${authVal}`;\n }\n\n /**\n * Clear basic authentication header\n */\n resetAuthHeader() {\n this.basicAuthHeader = undefined;\n }\n}\n\nconst defaultHttpClient = new HttpClient('fetch', defaultErrorHandler, defaultLogger);\n\nexport { HttpClient, defaultHttpClient };\n","import type { UserSessionKey } from '@rudderstack/analytics-js-common/types/UserSessionStorage';\n\nconst STORAGE_TEST_COOKIE = 'test_rudder_cookie';\nconst STORAGE_TEST_LOCAL_STORAGE = 'test_rudder_ls';\nconst STORAGE_TEST_SESSION_STORAGE = 'test_rudder_ss';\nconst STORAGE_TEST_TOP_LEVEL_DOMAIN = '__tld__';\nconst STOREJS_IS_INCOGNITO = '_Is_Incognit';\n\nconst CLIENT_DATA_STORE_NAME = 'clientData';\n\nconst CLIENT_DATA_STORE_COOKIE = 'clientDataInCookie';\nconst CLIENT_DATA_STORE_LS = 'clientDataInLocalStorage';\nconst CLIENT_DATA_STORE_MEMORY = 'clientDataInMemory';\nconst CLIENT_DATA_STORE_SESSION = 'clientDataInSessionStorage';\n\nconst USER_SESSION_KEYS: UserSessionKey[] = [\n 'userId',\n 'userTraits',\n 'anonymousId',\n 'groupId',\n 'groupTraits',\n 'initialReferrer',\n 'initialReferringDomain',\n 'sessionInfo',\n 'authToken',\n];\n\nexport {\n STORAGE_TEST_COOKIE,\n STORAGE_TEST_LOCAL_STORAGE,\n STORAGE_TEST_SESSION_STORAGE,\n STORAGE_TEST_TOP_LEVEL_DOMAIN,\n STOREJS_IS_INCOGNITO,\n CLIENT_DATA_STORE_NAME,\n CLIENT_DATA_STORE_COOKIE,\n CLIENT_DATA_STORE_LS,\n CLIENT_DATA_STORE_MEMORY,\n CLIENT_DATA_STORE_SESSION,\n USER_SESSION_KEYS,\n};\n","import {\n COOKIE_STORAGE,\n LOCAL_STORAGE,\n MEMORY_STORAGE,\n SESSION_STORAGE,\n} from '@rudderstack/analytics-js-common/constants/storages';\nimport type {\n ICookieStorageOptions,\n IInMemoryStorageOptions,\n ILocalStorageOptions,\n ISessionStorageOptions,\n} from '@rudderstack/analytics-js-common/types/Store';\nimport {\n CLIENT_DATA_STORE_COOKIE,\n CLIENT_DATA_STORE_LS,\n CLIENT_DATA_STORE_MEMORY,\n CLIENT_DATA_STORE_SESSION,\n} from '../../constants/storage';\n\nexport type StoreManagerOptions = {\n cookieStorageOptions?: Partial;\n localStorageOptions?: Partial;\n inMemoryStorageOptions?: Partial;\n sessionStorageOptions?: Partial;\n};\n\nexport const storageClientDataStoreNameMap: Record = {\n [COOKIE_STORAGE]: CLIENT_DATA_STORE_COOKIE,\n [LOCAL_STORAGE]: CLIENT_DATA_STORE_LS,\n [MEMORY_STORAGE]: CLIENT_DATA_STORE_MEMORY,\n [SESSION_STORAGE]: CLIENT_DATA_STORE_SESSION,\n};\n","import {\n isUndefined,\n isNull,\n isNullOrUndefined,\n isFunction,\n} from '@rudderstack/analytics-js-common/utilities/checks';\n\nconst isBrowser = (): boolean => !isUndefined(globalThis) && !isUndefined(globalThis.document);\n\nconst isNode = (): boolean =>\n !isUndefined(process) && !isNull(process.versions) && !isNull(process.versions.node);\n\nconst hasCrypto = (): boolean =>\n !isNullOrUndefined(globalThis.crypto) && isFunction(globalThis.crypto.getRandomValues);\n\n// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData\nconst hasUAClientHints = (): boolean => !isNullOrUndefined(globalThis.navigator.userAgentData);\n\nconst hasBeacon = (): boolean =>\n !isNullOrUndefined(globalThis.navigator.sendBeacon) &&\n isFunction(globalThis.navigator.sendBeacon);\n\nconst isIE11 = (): boolean => Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\\./));\n\nexport { isBrowser, isNode, hasCrypto, hasUAClientHints, hasBeacon, isIE11 };\n","import { isFunction } from '@rudderstack/analytics-js-common/utilities/checks';\n\nconst isDatasetAvailable = (): boolean => {\n const testElement = globalThis.document.createElement('div');\n testElement.setAttribute('data-a-b', 'c');\n return testElement.dataset ? testElement.dataset.aB === 'c' : false;\n};\n\nconst legacyJSEngineRequiredPolyfills: Record boolean> = {\n // Ideally, we should separate the checks for URL and URLSearchParams but\n // the polyfill service serves them under the same feature name, \"URL\".\n URL: () => !isFunction(globalThis.URL) || !isFunction(globalThis.URLSearchParams),\n Promise: () => !isFunction(globalThis.Promise),\n 'Number.isNaN': () => !isFunction(globalThis.Number.isNaN),\n 'Number.isInteger': () => !isFunction(globalThis.Number.isInteger),\n 'Array.from': () => !isFunction(globalThis.Array.from),\n 'Array.prototype.find': () => !isFunction(globalThis.Array.prototype.find),\n 'Array.prototype.includes': () => !isFunction(globalThis.Array.prototype.includes),\n 'String.prototype.endsWith': () => !isFunction(globalThis.String.prototype.endsWith),\n 'String.prototype.startsWith': () => !isFunction(globalThis.String.prototype.startsWith),\n 'String.prototype.includes': () => !isFunction(globalThis.String.prototype.includes),\n 'String.prototype.replaceAll': () => !isFunction(globalThis.String.prototype.replaceAll),\n 'String.fromCodePoint': () => !isFunction(globalThis.String.fromCodePoint),\n 'Object.entries': () => !isFunction(globalThis.Object.entries),\n 'Object.values': () => !isFunction(globalThis.Object.values),\n 'Object.assign': () => !isFunction(globalThis.Object.assign),\n 'Object.fromEntries': () => !isFunction(globalThis.Object.fromEntries),\n 'Element.prototype.dataset': () => !isDatasetAvailable(),\n // Ideally, we should separate the checks for TextEncoder and TextDecoder but\n // the polyfill service serves them under the same feature name, \"TextEncoder\".\n TextEncoder: () => !isFunction(globalThis.TextEncoder) || !isFunction(globalThis.TextDecoder),\n requestAnimationFrame: () =>\n !isFunction(globalThis.requestAnimationFrame) || !isFunction(globalThis.cancelAnimationFrame),\n CustomEvent: () => !isFunction(globalThis.CustomEvent),\n 'navigator.sendBeacon': () => !isFunction(globalThis.navigator.sendBeacon),\n // Note, the polyfill service serves both ArrayBuffer and Uint8Array under the same feature name, \"ArrayBuffer\".\n ArrayBuffer: () => !isFunction(globalThis.Uint8Array),\n Set: () => !isFunction(globalThis.Set),\n atob: () => !isFunction(globalThis.atob),\n};\n\nconst isLegacyJSEngine = (): boolean => {\n const requiredCapabilitiesList = Object.keys(legacyJSEngineRequiredPolyfills);\n let needsPolyfill = false;\n\n /* eslint-disable-next-line unicorn/no-for-loop */\n for (let i = 0; i < requiredCapabilitiesList.length; i++) {\n const isCapabilityMissing =\n legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i] as string];\n\n if (isFunction(isCapabilityMissing) && isCapabilityMissing()) {\n needsPolyfill = true;\n break;\n }\n }\n\n return needsPolyfill;\n};\n\nexport { isDatasetAvailable, legacyJSEngineRequiredPolyfills, isLegacyJSEngine };\n","import type { ScreenInfo } from '@rudderstack/analytics-js-common/types/EventContext';\n\nconst getScreenDetails = (): ScreenInfo => {\n let screenDetails: ScreenInfo = {\n density: 0,\n width: 0,\n height: 0,\n innerWidth: 0,\n innerHeight: 0,\n };\n\n screenDetails = {\n width: globalThis.screen.width,\n height: globalThis.screen.height,\n density: globalThis.devicePixelRatio,\n innerWidth: globalThis.innerWidth,\n innerHeight: globalThis.innerHeight,\n };\n\n return screenDetails;\n};\n\nexport { getScreenDetails };\n","import { CAPABILITIES_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport type { IStorage } from '@rudderstack/analytics-js-common/types/Store';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport {\n COOKIE_STORAGE,\n LOCAL_STORAGE,\n MEMORY_STORAGE,\n SESSION_STORAGE,\n} from '@rudderstack/analytics-js-common/constants/storages';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport {\n STORAGE_TEST_COOKIE,\n STORAGE_TEST_LOCAL_STORAGE,\n STORAGE_TEST_SESSION_STORAGE,\n} from '../../../constants/storage';\nimport { STORAGE_UNAVAILABILITY_ERROR_PREFIX } from '../../../constants/logMessages';\n\nconst isStorageQuotaExceeded = (e: DOMException | any): boolean => {\n const matchingNames = ['QuotaExceededError', 'NS_ERROR_DOM_QUOTA_REACHED']; // [everything except Firefox, Firefox]\n const matchingCodes = [22, 1014]; // [everything except Firefox, Firefox]\n const isQuotaExceededError = matchingNames.includes(e.name) || matchingCodes.includes(e.code);\n\n return e instanceof DOMException && isQuotaExceededError;\n};\n\n// TODO: also check for SecurityErrors\n// https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions\nconst isStorageAvailable = (\n type: StorageType = LOCAL_STORAGE,\n storageInstance?: IStorage,\n logger?: ILogger,\n) => {\n let storage;\n let testData;\n\n try {\n switch (type) {\n case MEMORY_STORAGE:\n return true;\n case COOKIE_STORAGE:\n storage = storageInstance;\n testData = STORAGE_TEST_COOKIE;\n break;\n case LOCAL_STORAGE:\n storage = storageInstance ?? globalThis.localStorage;\n testData = STORAGE_TEST_LOCAL_STORAGE; // was STORAGE_TEST_LOCAL_STORAGE in ours and generateUUID() in segment retry one\n break;\n case SESSION_STORAGE:\n storage = storageInstance ?? globalThis.sessionStorage;\n testData = STORAGE_TEST_SESSION_STORAGE;\n break;\n default:\n return false;\n }\n\n if (!storage) {\n return false;\n }\n\n storage.setItem(testData, 'true');\n if (storage.getItem(testData)) {\n storage.removeItem(testData);\n return true;\n }\n return false;\n } catch (err) {\n const msgPrefix = STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER, type);\n let reason = 'unavailable';\n if (isStorageQuotaExceeded(err)) {\n reason = 'full';\n }\n logger?.warn(`${msgPrefix}${reason}.`, err);\n return false;\n }\n};\n\nexport { isStorageQuotaExceeded, isStorageAvailable };\n","import { cookie } from '@rudderstack/analytics-js-cookies/component-cookie';\nimport { STORAGE_TEST_TOP_LEVEL_DOMAIN } from '../../../constants/storage';\n\nconst legacyGetHostname = (href: string): string => {\n const l = document.createElement('a');\n l.href = href;\n return l.hostname;\n};\n\n/**\n * Levels returns all levels of the given url\n *\n * The method returns an empty array when the hostname is an ip.\n */\nconst levelsFunc = (url: string): string[] => {\n // This is called before the polyfills load thus new URL cannot be used\n const host =\n typeof globalThis.URL !== 'function' ? legacyGetHostname(url) : new URL(url).hostname;\n const parts = host?.split('.') ?? [];\n const last = parts[parts.length - 1];\n const levels: string[] = [];\n\n // Ip address.\n if (parts.length === 4 && last && last === parseInt(last, 10).toString()) {\n return levels;\n }\n\n // Localhost.\n if (parts.length <= 1) {\n // Fix to support localhost\n if (parts[0] && parts[0].indexOf('localhost') !== -1) {\n return ['localhost'];\n }\n return levels;\n }\n\n // Create levels.\n for (let i = parts.length - 2; i >= 0; i -= 1) {\n levels.push(parts.slice(i).join('.'));\n }\n\n return levels;\n};\n\n/**\n * Get the top domain.\n *\n * The function constructs the levels of domain and attempts to set a global\n * cookie on each one when it succeeds it returns the top level domain.\n *\n * The method returns an empty string when the hostname is an ip.\n */\nconst domain = (url: string): string => {\n const levels = levelsFunc(url);\n\n // Lookup the real top level one.\n // eslint-disable-next-line unicorn/no-for-loop\n for (let i = 0; i < levels.length; i += 1) {\n const domain = levels[i] as string;\n const cname = STORAGE_TEST_TOP_LEVEL_DOMAIN;\n const opts = {\n domain: `${domain.indexOf('localhost') !== -1 ? '' : '.'}${domain}`,\n };\n\n // Set cookie on domain\n cookie(cname, 1, opts);\n\n // If successful\n if (cookie(cname)) {\n // Remove cookie from domain\n cookie(cname, null, opts);\n return domain;\n }\n }\n\n return '';\n};\n\n/*\n * Exports.\n */\n\nexport { domain };\n","import type {\n ICookieStorageOptions,\n IInMemoryStorageOptions,\n ILocalStorageOptions,\n ISessionStorageOptions,\n} from '@rudderstack/analytics-js-common/types/Store';\nimport { DEFAULT_COOKIE_MAX_AGE_MS } from '../../../constants/timeouts';\nimport { domain } from '../top-domain';\n\nconst getDefaultCookieOptions = (): ICookieStorageOptions => {\n const topDomain = `.${domain(globalThis.location.href)}`;\n\n return {\n maxage: DEFAULT_COOKIE_MAX_AGE_MS,\n path: '/',\n domain: !topDomain || topDomain === '.' ? undefined : topDomain,\n samesite: 'Lax',\n enabled: true,\n };\n};\n\nconst getDefaultLocalStorageOptions = (): ILocalStorageOptions => ({\n enabled: true,\n});\n\nconst getDefaultSessionStorageOptions = (): ISessionStorageOptions => ({\n enabled: true,\n});\n\nconst getDefaultInMemoryStorageOptions = (): IInMemoryStorageOptions => ({\n enabled: true,\n});\n\nexport {\n getDefaultCookieOptions,\n getDefaultLocalStorageOptions,\n getDefaultInMemoryStorageOptions,\n getDefaultSessionStorageOptions,\n};\n","import { isUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { ICookieStorageOptions, IStorage } from '@rudderstack/analytics-js-common/types/Store';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { COOKIE_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport { cookie } from '@rudderstack/analytics-js-cookies/component-cookie';\nimport { isStorageAvailable } from '../../../components/capabilitiesManager/detection';\nimport { getDefaultCookieOptions } from './defaultOptions';\n\n/**\n * A storage utility to persist values in cookies via Storage interface\n */\nclass CookieStorage implements IStorage {\n static globalSingleton: Nullable = null;\n logger?: ILogger;\n options?: ICookieStorageOptions;\n isSupportAvailable = true;\n isEnabled = true;\n length = 0;\n\n constructor(options: Partial = {}, logger?: ILogger) {\n if (CookieStorage.globalSingleton) {\n // eslint-disable-next-line no-constructor-return\n return CookieStorage.globalSingleton;\n }\n\n this.options = getDefaultCookieOptions();\n this.logger = logger;\n this.configure(options);\n\n CookieStorage.globalSingleton = this;\n }\n\n configure(options: Partial): ICookieStorageOptions {\n this.options = mergeDeepRight(this.options ?? {}, options);\n if (options.sameDomainCookiesOnly) {\n delete this.options.domain;\n }\n this.isSupportAvailable = isStorageAvailable(COOKIE_STORAGE, this, this.logger);\n this.isEnabled = Boolean(this.options.enabled && this.isSupportAvailable);\n return this.options;\n }\n\n setItem(key: string, value: Nullable): boolean {\n cookie(key, value, this.options, this.logger);\n this.length = Object.keys(cookie()).length;\n return true;\n }\n\n // eslint-disable-next-line class-methods-use-this\n getItem(key: string): Nullable {\n const value = cookie(key);\n return isUndefined(value) ? null : value;\n }\n\n removeItem(key: string): boolean {\n const result = this.setItem(key, null);\n this.length = Object.keys(cookie()).length;\n return result;\n }\n\n // eslint-disable-next-line class-methods-use-this\n clear() {\n // Not implemented\n // getting a list of all cookie storage keys and remove all values\n // sounds risky to do as it will take on all top domain cookies\n // better to explicitly clear specific ones if needed\n }\n\n key(index: number): Nullable {\n const curKeys = this.keys();\n return curKeys[index] ?? null;\n }\n\n // eslint-disable-next-line class-methods-use-this\n keys(): string[] {\n return Object.keys(cookie());\n }\n}\n\nexport { CookieStorage };\n","import type {\n IInMemoryStorageOptions,\n IStorage,\n} from '@rudderstack/analytics-js-common/types/Store';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { defaultLogger } from '../../Logger';\nimport { getDefaultInMemoryStorageOptions } from './defaultOptions';\n\n/**\n * A storage utility to retain values in memory via Storage interface\n */\nclass InMemoryStorage implements IStorage {\n logger?: ILogger;\n options: IInMemoryStorageOptions;\n isEnabled = true;\n length = 0;\n data: Record = {};\n\n constructor(options?: IInMemoryStorageOptions, logger?: ILogger) {\n this.options = getDefaultInMemoryStorageOptions();\n this.logger = logger;\n this.configure(options ?? {});\n }\n\n configure(options: Partial): IInMemoryStorageOptions {\n this.options = mergeDeepRight(this.options, options);\n this.isEnabled = Boolean(this.options.enabled);\n return this.options;\n }\n\n setItem(key: string, value: any): any {\n this.data[key] = value;\n this.length = Object.keys(this.data).length;\n return value;\n }\n\n getItem(key: string): any {\n if (key in this.data) {\n return this.data[key];\n }\n return null;\n }\n\n removeItem(key: string) {\n if (key in this.data) {\n delete this.data[key];\n }\n this.length = Object.keys(this.data).length;\n return null;\n }\n\n clear() {\n this.data = {};\n this.length = 0;\n }\n\n key(index: number): Nullable {\n const curKeys = this.keys();\n return curKeys[index] ?? null;\n }\n\n keys(): string[] {\n return Object.keys(this.data);\n }\n}\n\nconst defaultInMemoryStorage = new InMemoryStorage({}, defaultLogger);\n\nexport { InMemoryStorage, defaultInMemoryStorage };\n","/**!\n * storejs v2.1.0\n * Local storage localstorage package provides a simple API\n * \n * Copyright (c) 2024 kenny wang \n * https://jaywcjlove.github.io/store.js/\n * \n * Licensed under the MIT license.\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.store = factory());\n})(this, (function () { 'use strict';\n\n function isJSON(obj) {\n obj = JSON.stringify(obj);\n if (!/^\\{[\\s\\S]*\\}$/.test(obj)) {\n return false;\n }\n return true;\n }\n function stringify(val) {\n return val === undefined || typeof val === \"function\" ? val + '' : JSON.stringify(val);\n }\n function deserialize(value) {\n if (typeof value !== 'string') {\n return undefined;\n }\n try {\n return JSON.parse(value);\n } catch (e) {\n return value;\n }\n }\n function isFunction(value) {\n return {}.toString.call(value) === \"[object Function]\";\n }\n function isArray(value) {\n return Object.prototype.toString.call(value) === \"[object Array]\";\n }\n // https://github.com/jaywcjlove/store.js/pull/8\n // Error: QuotaExceededError\n function dealIncognito(storage) {\n var _KEY = '_Is_Incognit',\n _VALUE = 'yes';\n try {\n // NOTE: set default storage when not passed in\n if (!storage) {\n storage = window.localStorage;\n }\n storage.setItem(_KEY, _VALUE);\n storage.removeItem(_KEY);\n } catch (e) {\n var inMemoryStorage = {};\n inMemoryStorage._data = {};\n inMemoryStorage.setItem = function (id, val) {\n return inMemoryStorage._data[id] = String(val);\n };\n inMemoryStorage.getItem = function (id) {\n return inMemoryStorage._data.hasOwnProperty(id) ? inMemoryStorage._data[id] : undefined;\n };\n inMemoryStorage.removeItem = function (id) {\n return delete inMemoryStorage._data[id];\n };\n inMemoryStorage.clear = function () {\n return inMemoryStorage._data = {};\n };\n storage = inMemoryStorage;\n } finally {\n if (storage.getItem(_KEY) === _VALUE) storage.removeItem(_KEY);\n }\n return storage;\n }\n\n // deal QuotaExceededError if user use incognito mode in browser\n var storage = dealIncognito();\n function Store() {\n if (!(this instanceof Store)) {\n return new Store();\n }\n }\n Store.prototype = {\n set: function set(key, val) {\n if (key && !isJSON(key)) {\n storage.setItem(key, stringify(val));\n } else if (isJSON(key)) {\n for (var a in key) this.set(a, key[a]);\n }\n return this;\n },\n get: function get(key) {\n // Return all entries if no key\n if (key === undefined) {\n var ret = {};\n this.forEach(function (key, val) {\n return ret[key] = val;\n });\n return ret;\n }\n if (key.charAt(0) === '?') {\n return this.has(key.substr(1));\n }\n var args = arguments;\n if (args.length > 1) {\n var dt = {};\n for (var i = 0, len = args.length; i < len; i++) {\n var value = deserialize(storage.getItem(args[i]));\n if (this.has(args[i])) {\n dt[args[i]] = value;\n }\n }\n return dt;\n }\n return deserialize(storage.getItem(key));\n },\n clear: function clear() {\n storage.clear();\n return this;\n },\n remove: function remove(key) {\n var val = this.get(key);\n storage.removeItem(key);\n return val;\n },\n has: function has(key) {\n return {}.hasOwnProperty.call(this.get(), key);\n },\n keys: function keys() {\n var d = [];\n this.forEach(function (k) {\n d.push(k);\n });\n return d;\n },\n forEach: function forEach(callback) {\n for (var i = 0, len = storage.length; i < len; i++) {\n var key = storage.key(i);\n callback(key, this.get(key));\n }\n return this;\n },\n search: function search(str) {\n var arr = this.keys(),\n dt = {};\n for (var i = 0, len = arr.length; i < len; i++) {\n if (arr[i].indexOf(str) > -1) dt[arr[i]] = this.get(arr[i]);\n }\n return dt;\n },\n len: function len() {\n return storage.length;\n }\n };\n var _Store = null;\n function store(key, data) {\n var argm = arguments;\n var dt = null;\n if (!_Store) _Store = Store();\n if (argm.length === 0) return _Store.get();\n if (argm.length === 1) {\n if (typeof key === \"string\") return _Store.get(key);\n if (isJSON(key)) return _Store.set(key);\n }\n if (argm.length === 2 && typeof key === \"string\") {\n if (!data) return _Store.remove(key);\n if (data && typeof data === \"string\") return _Store.set(key, data);\n if (data && isFunction(data)) {\n dt = null;\n dt = data(key, _Store.get(key));\n store.set(key, dt);\n }\n }\n if (argm.length === 2 && isArray(key) && isFunction(data)) {\n for (var i = 0, len = key.length; i < len; i++) {\n dt = data(key[i], _Store.get(key[i]));\n store.set(key[i], dt);\n }\n }\n return store;\n }\n for (var a in Store.prototype) store[a] = Store.prototype[a];\n\n return store;\n\n}));\n","import store from 'storejs';\nimport type { ILocalStorageOptions, IStorage } from '@rudderstack/analytics-js-common/types/Store';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport { isUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { LOCAL_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { isStorageAvailable } from '../../../components/capabilitiesManager/detection';\nimport { defaultLogger } from '../../Logger';\nimport { getDefaultLocalStorageOptions } from './defaultOptions';\n\n// TODO: can we remove the storejs dependency to save bundle size?\n// check if the get, set overloads and search methods are used at all\n// if we do, ensure we provide types to support overloads as per storejs docs\n// https://www.npmjs.com/package/storejs\n/**\n * A storage utility to persist values in localstorage via Storage interface\n */\nclass LocalStorage implements IStorage {\n logger?: ILogger;\n options: ILocalStorageOptions;\n isSupportAvailable = true;\n isEnabled = true;\n length = 0;\n\n constructor(options: ILocalStorageOptions = {}, logger?: ILogger) {\n this.options = getDefaultLocalStorageOptions();\n this.logger = logger;\n this.configure(options);\n }\n\n configure(options: Partial): ILocalStorageOptions {\n this.options = mergeDeepRight(this.options, options);\n this.isSupportAvailable = isStorageAvailable(LOCAL_STORAGE, this, this.logger);\n this.isEnabled = Boolean(this.options.enabled && this.isSupportAvailable);\n return this.options;\n }\n\n setItem(key: string, value: any) {\n store.set(key, value);\n this.length = store.len();\n }\n\n // eslint-disable-next-line class-methods-use-this\n getItem(key: string): any {\n const value = store.get(key);\n return isUndefined(value) ? null : value;\n }\n\n removeItem(key: string) {\n store.remove(key);\n this.length = store.len();\n }\n\n clear() {\n store.clear();\n this.length = 0;\n }\n\n key(index: number): Nullable {\n const curKeys = this.keys();\n return curKeys[index] ?? null;\n }\n\n // eslint-disable-next-line class-methods-use-this\n keys(): string[] {\n return store.keys();\n }\n}\n\nconst defaultLocalStorage = new LocalStorage({}, defaultLogger);\n\nexport { LocalStorage, defaultLocalStorage };\n","import type {\n ISessionStorageOptions,\n IStorage,\n} from '@rudderstack/analytics-js-common/types/Store';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport { isUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { SESSION_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { isStorageAvailable } from '../../../components/capabilitiesManager/detection';\nimport { defaultLogger } from '../../Logger';\nimport { getDefaultSessionStorageOptions } from './defaultOptions';\n\n/**\n * A storage utility to persist values in SessionStorage via Storage interface\n */\nclass SessionStorage implements IStorage {\n logger?: ILogger;\n options: ISessionStorageOptions;\n isSupportAvailable = true;\n isEnabled = true;\n length = 0;\n store = globalThis.sessionStorage;\n\n constructor(options: ISessionStorageOptions = {}, logger?: ILogger) {\n this.options = getDefaultSessionStorageOptions();\n this.logger = logger;\n this.configure(options);\n }\n\n configure(options: Partial): ISessionStorageOptions {\n this.options = mergeDeepRight(this.options, options);\n this.isSupportAvailable = isStorageAvailable(SESSION_STORAGE, this, this.logger);\n this.isEnabled = Boolean(this.options.enabled && this.isSupportAvailable);\n return this.options;\n }\n\n setItem(key: string, value: any) {\n this.store.setItem(key, value);\n this.length = this.store.length;\n }\n\n getItem(key: string): any {\n const value = this.store.getItem(key);\n return isUndefined(value) ? null : value;\n }\n\n removeItem(key: string) {\n this.store.removeItem(key);\n this.length = this.store.length;\n }\n\n clear() {\n this.store.clear();\n this.length = 0;\n }\n\n key(index: number): Nullable {\n return this.store.key(index);\n }\n\n keys(): string[] {\n const keys: string[] = [];\n for (let i = 0; i < this.store.length; i += 1) {\n const key = this.store.key(i);\n if (key !== null) {\n keys.push(key);\n }\n }\n return keys;\n }\n}\n\nconst defaultSessionStorage = new SessionStorage({}, defaultLogger);\n\nexport { SessionStorage, defaultSessionStorage };\n","import type {\n ICookieStorageOptions,\n IInMemoryStorageOptions,\n ILocalStorageOptions,\n ISessionStorageOptions,\n IStorage,\n} from '@rudderstack/analytics-js-common/types/Store';\nimport {\n COOKIE_STORAGE,\n LOCAL_STORAGE,\n MEMORY_STORAGE,\n SESSION_STORAGE,\n} from '@rudderstack/analytics-js-common/constants/storages';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport { state } from '../../../state';\nimport { defaultLogger } from '../../Logger';\nimport { CookieStorage } from './CookieStorage';\nimport { defaultInMemoryStorage } from './InMemoryStorage';\nimport { defaultLocalStorage } from './LocalStorage';\nimport { defaultSessionStorage } from './sessionStorage';\n\n/**\n * A utility to retrieve the storage singleton instance by type\n */\nconst getStorageEngine = (type?: StorageType): IStorage => {\n switch (type) {\n case LOCAL_STORAGE:\n return defaultLocalStorage;\n case SESSION_STORAGE:\n return defaultSessionStorage;\n case MEMORY_STORAGE:\n return defaultInMemoryStorage;\n case COOKIE_STORAGE:\n return new CookieStorage({}, defaultLogger);\n default:\n return defaultInMemoryStorage;\n }\n};\n\n/**\n * Configure cookie storage singleton\n */\nconst configureCookieStorageEngine = (options: Partial) => {\n const cookieStorageOptions = new CookieStorage({}, defaultLogger).configure(options);\n state.storage.cookie.value = {\n maxage: cookieStorageOptions.maxage,\n path: cookieStorageOptions.path,\n domain: cookieStorageOptions.domain,\n samesite: cookieStorageOptions.samesite,\n expires: cookieStorageOptions.expires,\n secure: cookieStorageOptions.secure,\n };\n};\n\n/**\n * Configure local storage singleton\n */\nconst configureLocalStorageEngine = (options: Partial) => {\n defaultLocalStorage.configure(options);\n};\n\n/**\n * Configure in memory storage singleton\n */\nconst configureInMemoryStorageEngine = (options: Partial) => {\n defaultInMemoryStorage.configure(options);\n};\n\n/**\n * Configure session storage singleton\n */\nconst configureSessionStorageEngine = (options: Partial) => {\n defaultSessionStorage.configure(options);\n};\n\n/**\n * Configure all storage singleton instances\n */\nconst configureStorageEngines = (\n cookieStorageOptions: Partial = {},\n localStorageOptions: Partial = {},\n inMemoryStorageOptions: Partial = {},\n sessionStorageOptions: Partial = {},\n) => {\n configureCookieStorageEngine(cookieStorageOptions);\n configureLocalStorageEngine(localStorageOptions);\n configureInMemoryStorageEngine(inMemoryStorageOptions);\n configureSessionStorageEngine(sessionStorageOptions);\n};\n\nexport {\n getStorageEngine,\n configureCookieStorageEngine,\n configureLocalStorageEngine,\n configureInMemoryStorageEngine,\n configureSessionStorageEngine,\n configureStorageEngines,\n};\n","import { trim } from '@rudderstack/analytics-js-common/utilities/string';\nimport { isNullOrUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport type { IStorage, IStore, IStoreConfig } from '@rudderstack/analytics-js-common/types/Store';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IPluginsManager } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { LOCAL_STORAGE, MEMORY_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport { getMutatedError } from '@rudderstack/analytics-js-common/utilities/errors';\nimport { defaultLogger } from '../Logger';\nimport { defaultErrorHandler } from '../ErrorHandler';\nimport { isStorageQuotaExceeded } from '../../components/capabilitiesManager/detection';\nimport {\n STORAGE_QUOTA_EXCEEDED_WARNING,\n STORE_DATA_FETCH_ERROR,\n STORE_DATA_SAVE_ERROR,\n} from '../../constants/logMessages';\nimport { getStorageEngine } from './storages/storageEngine';\n\n/**\n * Store Implementation with dedicated storage\n */\nclass Store implements IStore {\n id: string;\n name: string;\n isEncrypted: boolean;\n validKeys: Record;\n engine: IStorage;\n originalEngine: IStorage;\n noKeyValidation?: boolean;\n noCompoundKey?: boolean;\n errorHandler?: IErrorHandler;\n hasErrorHandler = false;\n logger?: ILogger;\n pluginsManager?: IPluginsManager;\n\n constructor(config: IStoreConfig, engine?: IStorage, pluginsManager?: IPluginsManager) {\n this.id = config.id;\n this.name = config.name;\n this.isEncrypted = config.isEncrypted ?? false;\n this.validKeys = config.validKeys ?? {};\n this.engine = engine ?? getStorageEngine(LOCAL_STORAGE);\n this.noKeyValidation = Object.keys(this.validKeys).length === 0;\n this.noCompoundKey = config.noCompoundKey;\n this.originalEngine = this.engine;\n this.errorHandler = config.errorHandler ?? defaultErrorHandler;\n this.hasErrorHandler = Boolean(this.errorHandler);\n this.logger = config.logger ?? defaultLogger;\n this.pluginsManager = pluginsManager;\n }\n\n /**\n * Ensure the key is valid and with correct format\n */\n createValidKey(key: string): string | undefined {\n const { name, id, validKeys, noKeyValidation, noCompoundKey } = this;\n\n if (noKeyValidation) {\n return noCompoundKey ? key : [name, id, key].join('.');\n }\n\n // validate and return undefined if invalid key\n let compoundKey;\n Object.values(validKeys).forEach(validKeyName => {\n if (validKeyName === key) {\n compoundKey = noCompoundKey ? key : [name, id, key].join('.');\n }\n });\n\n return compoundKey;\n }\n\n /**\n * Switch to inMemoryEngine, bringing any existing data with.\n */\n swapQueueStoreToInMemoryEngine() {\n const { name, id, validKeys, noCompoundKey } = this;\n const inMemoryStorage = getStorageEngine(MEMORY_STORAGE);\n\n // grab existing data, but only for this page's queue instance, not all\n // better to keep other queues in localstorage to be flushed later\n // than to pull them into memory and remove them from durable storage\n Object.keys(validKeys).forEach(key => {\n const value = this.get(validKeys[key] as string);\n const validKey = noCompoundKey ? key : [name, id, key].join('.');\n\n inMemoryStorage.setItem(validKey, value);\n // TODO: are we sure we want to drop clientData\n // if cookies are not available and localstorage is full?\n this.remove(key);\n });\n\n this.engine = inMemoryStorage;\n }\n\n /**\n * Set value by key.\n */\n set(key: string, value: any) {\n const validKey = this.createValidKey(key);\n\n if (!validKey) {\n return;\n }\n\n try {\n // storejs that is used in localstorage engine already stringifies json\n this.engine.setItem(\n validKey,\n this.encrypt(stringifyWithoutCircular(value, false, [], this.logger)),\n );\n } catch (err) {\n if (isStorageQuotaExceeded(err)) {\n this.logger?.warn(STORAGE_QUOTA_EXCEEDED_WARNING(`Store ${this.id}`));\n // switch to inMemory engine\n this.swapQueueStoreToInMemoryEngine();\n // and save it there\n this.set(key, value);\n } else {\n this.onError(getMutatedError(err, STORE_DATA_SAVE_ERROR(key)));\n }\n }\n }\n\n /**\n * Get by Key.\n */\n get(key: string): Nullable {\n const validKey = this.createValidKey(key);\n\n try {\n if (!validKey) {\n return null;\n }\n\n const str = this.decrypt(this.engine.getItem(validKey));\n\n if (isNullOrUndefined(str)) {\n return null;\n }\n\n // storejs that is used in localstorage engine already deserializes json strings but swallows errors\n return JSON.parse(str as string);\n } catch (err) {\n this.onError(new Error(`${STORE_DATA_FETCH_ERROR(key)}: ${(err as Error).message}`));\n return null;\n }\n }\n\n /**\n * Remove by Key.\n */\n remove(key: string) {\n const validKey = this.createValidKey(key);\n\n if (validKey) {\n this.engine.removeItem(validKey);\n }\n }\n\n /**\n * Get original engine\n */\n getOriginalEngine(): IStorage {\n return this.originalEngine;\n }\n\n /**\n * Decrypt values\n */\n decrypt(value?: Nullable): Nullable {\n if (isNullOrUndefined(value)) {\n return null;\n }\n\n return this.crypto(value as string, 'decrypt');\n }\n\n /**\n * Encrypt value\n */\n encrypt(value: Nullable): string {\n return this.crypto(value, 'encrypt');\n }\n\n /**\n * Extension point to use with encryption plugins\n */\n crypto(value: Nullable, mode: 'encrypt' | 'decrypt'): string {\n const noEncryption =\n !this.isEncrypted || !value || typeof value !== 'string' || trim(value) === '';\n\n if (noEncryption) {\n return value;\n }\n\n const extensionPointName = `storage.${mode}`;\n const formattedValue = this.pluginsManager\n ? this.pluginsManager.invokeSingle(extensionPointName, value)\n : value;\n\n return typeof formattedValue === 'undefined' ? value : (formattedValue ?? '');\n }\n\n /**\n * Handle errors\n */\n onError(error: unknown) {\n if (this.hasErrorHandler) {\n this.errorHandler?.onError(error, `Store ${this.id}`);\n } else {\n throw error;\n }\n }\n}\n\nexport { Store };\n","import type {\n IStoreConfig,\n IStoreManager,\n StoreId,\n} from '@rudderstack/analytics-js-common/types/Store';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IPluginsManager } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { STORE_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport {\n COOKIE_STORAGE,\n LOCAL_STORAGE,\n MEMORY_STORAGE,\n NO_STORAGE,\n SESSION_STORAGE,\n} from '@rudderstack/analytics-js-common/constants/storages';\nimport {\n mergeDeepRight,\n removeUndefinedValues,\n} from '@rudderstack/analytics-js-common/utilities/object';\nimport {\n DEFAULT_STORAGE_TYPE,\n type StorageType,\n} from '@rudderstack/analytics-js-common/types/Storage';\nimport type { UserSessionKey } from '@rudderstack/analytics-js-common/types/UserSessionStorage';\nimport { batch } from '@preact/signals-core';\nimport { isDefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { COOKIE_KEYS } from '@rudderstack/analytics-js-cookies/constants/cookies';\nimport { USER_SESSION_KEYS } from '../../constants/storage';\nimport { STORAGE_UNAVAILABLE_WARNING } from '../../constants/logMessages';\nimport { type StoreManagerOptions, storageClientDataStoreNameMap } from './types';\nimport { state } from '../../state';\nimport { configureStorageEngines, getStorageEngine } from './storages/storageEngine';\nimport { Store } from './Store';\nimport { getStorageTypeFromPreConsentIfApplicable } from './utils';\n\n/**\n * A service to manage stores & available storage client configurations\n */\nclass StoreManager implements IStoreManager {\n stores: Record = {};\n isInitialized = false;\n errorHandler?: IErrorHandler;\n logger?: ILogger;\n pluginsManager?: IPluginsManager;\n hasErrorHandler = false;\n\n constructor(pluginsManager?: IPluginsManager, errorHandler?: IErrorHandler, logger?: ILogger) {\n this.errorHandler = errorHandler;\n this.logger = logger;\n this.hasErrorHandler = Boolean(this.errorHandler);\n this.pluginsManager = pluginsManager;\n this.onError = this.onError.bind(this);\n }\n\n /**\n * Configure available storage client instances\n */\n init() {\n if (this.isInitialized) {\n return;\n }\n\n const loadOptions = state.loadOptions.value;\n const config: StoreManagerOptions = {\n cookieStorageOptions: {\n samesite: loadOptions.sameSiteCookie,\n secure: loadOptions.secureCookie,\n domain: loadOptions.setCookieDomain,\n sameDomainCookiesOnly: loadOptions.sameDomainCookiesOnly,\n enabled: true,\n },\n localStorageOptions: { enabled: true },\n inMemoryStorageOptions: { enabled: true },\n sessionStorageOptions: { enabled: true },\n };\n\n configureStorageEngines(\n removeUndefinedValues(\n mergeDeepRight(config.cookieStorageOptions ?? {}, state.storage.cookie?.value ?? {}),\n ),\n removeUndefinedValues(config.localStorageOptions),\n removeUndefinedValues(config.inMemoryStorageOptions),\n removeUndefinedValues(config.sessionStorageOptions),\n );\n\n this.initClientDataStores();\n this.isInitialized = true;\n }\n\n /**\n * Create store to persist data used by the SDK like session, used details etc\n */\n initClientDataStores() {\n this.initializeStorageState();\n\n // TODO: fill in extra config values and bring them in from StoreManagerOptions if needed\n // TODO: should we pass the keys for all in order to validate or leave free as v1.1?\n\n // Initializing all the enabled store because previous user data might be in different storage\n // that needs auto migration\n const storageTypes = [MEMORY_STORAGE, LOCAL_STORAGE, COOKIE_STORAGE, SESSION_STORAGE];\n\n storageTypes.forEach(storageType => {\n if (getStorageEngine(storageType)?.isEnabled) {\n this.setStore({\n id: storageClientDataStoreNameMap[storageType] as string,\n name: storageClientDataStoreNameMap[storageType] as string,\n isEncrypted: true,\n noCompoundKey: true,\n type: storageType,\n });\n }\n });\n }\n\n initializeStorageState() {\n let globalStorageType = state.storage.type.value;\n let entriesOptions = state.loadOptions.value.storage?.entries;\n\n // Use the storage options from post consent if anything is defined\n const postConsentStorageOpts = state.consents.postConsent.value.storage;\n if (isDefined(postConsentStorageOpts?.type) || isDefined(postConsentStorageOpts?.entries)) {\n globalStorageType = postConsentStorageOpts?.type;\n entriesOptions = postConsentStorageOpts?.entries;\n }\n\n let trulyAnonymousTracking = true;\n let storageEntries = {};\n USER_SESSION_KEYS.forEach(sessionKey => {\n const key = sessionKey;\n const storageKey = sessionKey;\n const configuredStorageType = entriesOptions?.[key]?.type;\n\n const preConsentStorageType = getStorageTypeFromPreConsentIfApplicable(state, sessionKey);\n\n // Storage type precedence order: pre-consent strategy > entry type > global type > default\n const storageType =\n preConsentStorageType ?? configuredStorageType ?? globalStorageType ?? DEFAULT_STORAGE_TYPE;\n\n const finalStorageType = this.getResolvedStorageTypeForEntry(storageType, sessionKey);\n\n if (finalStorageType !== NO_STORAGE) {\n trulyAnonymousTracking = false;\n }\n\n storageEntries = {\n ...storageEntries,\n [sessionKey]: {\n type: finalStorageType,\n key: COOKIE_KEYS[storageKey],\n },\n };\n });\n\n batch(() => {\n state.storage.type.value = globalStorageType;\n state.storage.entries.value = storageEntries;\n state.storage.trulyAnonymousTracking.value = trulyAnonymousTracking;\n });\n }\n\n private getResolvedStorageTypeForEntry(storageType: StorageType, sessionKey: UserSessionKey) {\n let finalStorageType = storageType;\n switch (storageType) {\n case LOCAL_STORAGE:\n if (!getStorageEngine(LOCAL_STORAGE)?.isEnabled) {\n finalStorageType = MEMORY_STORAGE;\n }\n break;\n case SESSION_STORAGE:\n if (!getStorageEngine(SESSION_STORAGE)?.isEnabled) {\n finalStorageType = MEMORY_STORAGE;\n }\n break;\n case MEMORY_STORAGE:\n case NO_STORAGE:\n break;\n case COOKIE_STORAGE:\n default:\n // First try setting the storage to cookie else to local storage\n if (getStorageEngine(COOKIE_STORAGE)?.isEnabled) {\n finalStorageType = COOKIE_STORAGE;\n } else if (getStorageEngine(LOCAL_STORAGE)?.isEnabled) {\n finalStorageType = LOCAL_STORAGE;\n } else if (getStorageEngine(SESSION_STORAGE)?.isEnabled) {\n finalStorageType = SESSION_STORAGE;\n } else {\n finalStorageType = MEMORY_STORAGE;\n }\n break;\n }\n\n if (finalStorageType !== storageType) {\n this.logger?.warn(\n STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER, sessionKey, storageType, finalStorageType),\n );\n }\n\n return finalStorageType;\n }\n\n /**\n * Create a new store\n */\n setStore(storeConfig: IStoreConfig): Store {\n const storageEngine = getStorageEngine(storeConfig.type);\n this.stores[storeConfig.id] = new Store(storeConfig, storageEngine, this.pluginsManager);\n return this.stores[storeConfig.id] as Store;\n }\n\n /**\n * Retrieve a store\n */\n getStore(id: StoreId): Store | undefined {\n return this.stores[id];\n }\n\n /**\n * Handle errors\n */\n onError(error: unknown) {\n if (this.hasErrorHandler) {\n this.errorHandler?.onError(error, STORE_MANAGER);\n } else {\n throw error;\n }\n }\n}\n\nexport { StoreManager };\n","import { NO_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport type { UserSessionKey } from '@rudderstack/analytics-js-common/types/UserSessionStorage';\n\nconst getStorageTypeFromPreConsentIfApplicable = (\n state: ApplicationState,\n sessionKey: UserSessionKey,\n) => {\n let overriddenStorageType: StorageType | undefined;\n if (state.consents.preConsent.value.enabled) {\n switch (state.consents.preConsent.value.storage?.strategy) {\n case 'none':\n overriddenStorageType = NO_STORAGE;\n break;\n case 'session':\n if (sessionKey !== 'sessionInfo') {\n overriddenStorageType = NO_STORAGE;\n }\n break;\n case 'anonymousId':\n if (sessionKey !== 'anonymousId') {\n overriddenStorageType = NO_STORAGE;\n }\n break;\n default:\n break;\n }\n }\n return overriddenStorageType;\n};\n\nexport { getStorageTypeFromPreConsentIfApplicable };\n","import { isObjectLiteralAndNotNull } from '@rudderstack/analytics-js-common/utilities/object';\nimport { isNullOrUndefined, isString } from '@rudderstack/analytics-js-common/utilities/checks';\nimport {\n SUPPORTED_STORAGE_TYPES,\n type StorageType,\n} from '@rudderstack/analytics-js-common/types/Storage';\nimport { isValidURL } from '@rudderstack/analytics-js-common/utilities/url';\nimport {\n WRITE_KEY_VALIDATION_ERROR,\n DATA_PLANE_URL_VALIDATION_ERROR,\n} from '../../../constants/logMessages';\n\nconst validateWriteKey = (writeKey?: string) => {\n if (!isString(writeKey) || (writeKey as string).trim().length === 0) {\n throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));\n }\n};\n\nconst validateDataPlaneUrl = (dataPlaneUrl?: string) => {\n if (!isValidURL(dataPlaneUrl)) {\n throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));\n }\n};\n\nconst validateLoadArgs = (writeKey?: string, dataPlaneUrl?: string) => {\n validateWriteKey(writeKey);\n validateDataPlaneUrl(dataPlaneUrl);\n};\n\nconst isValidSourceConfig = (res: any): boolean =>\n isObjectLiteralAndNotNull(res) &&\n isObjectLiteralAndNotNull(res.source) &&\n !isNullOrUndefined(res.source.id) &&\n isObjectLiteralAndNotNull(res.source.config) &&\n Array.isArray(res.source.destinations);\n\nconst isValidStorageType = (storageType?: StorageType): boolean =>\n typeof storageType === 'string' && SUPPORTED_STORAGE_TYPES.includes(storageType);\n\nconst getTopDomain = (url: string) => {\n // Create a URL object\n const urlObj = new URL(url);\n\n // Extract the host and protocol\n const { host, protocol } = urlObj;\n\n // Split the host into parts\n const parts: string[] = host.split('.');\n let topDomain;\n // Handle different cases, especially for co.uk or similar TLDs\n if (parts.length > 2) {\n // Join the last two parts for the top-level domain\n topDomain = `${parts[parts.length - 2]}.${parts[parts.length - 1]}`;\n } else {\n // If only two parts or less, return as it is\n topDomain = host;\n }\n return { topDomain, protocol };\n};\n\nconst getTopDomainUrl = (url: string) => {\n const { topDomain, protocol } = getTopDomain(url);\n return `${protocol}//${topDomain}`;\n};\n\nconst getDataServiceUrl = (endpoint: string, useExactDomain: boolean) => {\n const url = useExactDomain ? window.location.origin : getTopDomainUrl(window.location.href);\n const formattedEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;\n return `${url}/${formattedEndpoint}`;\n};\n\nconst isWebpageTopLevelDomain = (providedDomain: string): boolean => {\n const { topDomain } = getTopDomain(window.location.href);\n return topDomain === providedDomain;\n};\n\nexport {\n validateLoadArgs,\n isValidSourceConfig,\n isValidStorageType,\n validateWriteKey,\n validateDataPlaneUrl,\n getTopDomainUrl,\n getDataServiceUrl,\n isWebpageTopLevelDomain,\n};\n","import type { UTMParameters } from '@rudderstack/analytics-js-common/types/EventContext';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\n\n/**\n * Removes trailing slash from url\n * @param url\n * @returns url\n */\nconst removeTrailingSlashes = (url: Nullable | undefined): Nullable | undefined =>\n url?.endsWith('/') ? removeTrailingSlashes(url.substring(0, url.length - 1)) : url;\n\nconst getDomain = (url: string): Nullable => {\n try {\n const urlObj = new URL(url);\n return urlObj.host;\n } catch (error) {\n return null;\n }\n};\n\n/**\n * Get the referring domain from the referrer URL\n * @param referrer Page referrer\n * @returns Page referring domain\n */\nconst getReferringDomain = (referrer: string): string => getDomain(referrer) ?? '';\n\n/**\n * Extracts UTM parameters from the URL\n * @param url Page URL\n * @returns UTM parameters\n */\nconst extractUTMParameters = (url: string): UTMParameters => {\n const result: UTMParameters = {};\n try {\n const urlObj = new URL(url);\n const UTM_PREFIX = 'utm_';\n urlObj.searchParams.forEach((value, sParam) => {\n if (sParam.startsWith(UTM_PREFIX)) {\n let utmParam = sParam.substring(UTM_PREFIX.length);\n // Not sure why we're doing this\n if (utmParam === 'campaign') {\n utmParam = 'name';\n }\n result[utmParam] = value;\n }\n });\n } catch (error) {\n // Do nothing\n }\n return result;\n};\n\n/**\n * To get the URL until the hash\n * @param url The input URL\n * @returns URL until the hash\n */\nconst getUrlWithoutHash = (url: string): string => {\n let urlWithoutHash = url;\n try {\n const urlObj = new URL(url);\n urlWithoutHash = urlObj.origin + urlObj.pathname + urlObj.search;\n } catch (error) {\n // Do nothing\n }\n return urlWithoutHash;\n};\n\nexport {\n removeTrailingSlashes,\n getReferringDomain,\n extractUTMParameters,\n getUrlWithoutHash,\n getDomain,\n};\n","import type { DeliveryType, StorageStrategy } from '../types/LoadOptions';\n\nconst DEFAULT_PRE_CONSENT_STORAGE_STRATEGY: StorageStrategy = 'none';\nconst DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE: DeliveryType = 'immediate';\n\nexport { DEFAULT_PRE_CONSENT_STORAGE_STRATEGY, DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE };\n","import { CONFIG_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport type {\n ConsentManagementOptions,\n ConsentManagementProvider,\n Consents,\n CookieConsentOptions,\n} from '@rudderstack/analytics-js-common/types/Consent';\nimport type { ConsentOptions } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport {\n isNonEmptyObject,\n isObjectLiteralAndNotNull,\n mergeDeepRight,\n} from '@rudderstack/analytics-js-common/utilities/object';\nimport { clone } from 'ramda';\nimport { DEFAULT_INTEGRATIONS_CONFIG } from '@rudderstack/analytics-js-common/constants/integrationsConfig';\nimport { isDefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { state } from '../../state';\nimport { UNSUPPORTED_CONSENT_MANAGER_ERROR } from '../../constants/logMessages';\nimport { ConsentManagersToPluginNameMap } from '../configManager/constants';\n\n/**\n * A function to get the name of the consent manager with enabled true set in the load options\n * @param cookieConsentOptions Input provided as load option\n * @returns string|undefined\n *\n * Example input: {\n * oneTrust:{\n * enabled: true\n * }\n * }\n *\n * Output: 'oneTrust'\n */\nconst getUserSelectedConsentManager = (\n cookieConsentOptions?: CookieConsentOptions,\n): string | undefined => {\n if (!isNonEmptyObject(cookieConsentOptions)) {\n return undefined;\n }\n\n const validCookieConsentOptions = cookieConsentOptions as CookieConsentOptions;\n return Object.keys(validCookieConsentOptions).find(\n e =>\n e && validCookieConsentOptions[e] && (validCookieConsentOptions[e] as any).enabled === true,\n );\n};\n\n/**\n * Validates and normalizes the consent options provided by the user\n * @param options Consent options provided by the user\n * @returns Validated and normalized consent options\n */\nconst getValidPostConsentOptions = (options?: ConsentOptions) => {\n const validOptions: ConsentOptions = {\n sendPageEvent: false,\n trackConsent: false,\n discardPreConsentEvents: false,\n };\n if (isObjectLiteralAndNotNull(options)) {\n const clonedOptions = clone(options);\n\n validOptions.storage = clonedOptions.storage;\n if (isDefined(clonedOptions.integrations)) {\n validOptions.integrations = isObjectLiteralAndNotNull(clonedOptions.integrations)\n ? clonedOptions.integrations\n : DEFAULT_INTEGRATIONS_CONFIG;\n }\n validOptions.discardPreConsentEvents = clonedOptions.discardPreConsentEvents === true;\n validOptions.sendPageEvent = clonedOptions.sendPageEvent === true;\n validOptions.trackConsent = clonedOptions.trackConsent === true;\n if (isNonEmptyObject(clonedOptions.consentManagement)) {\n // Override enabled value with the current state value\n validOptions.consentManagement = mergeDeepRight(clonedOptions.consentManagement, {\n enabled: state.consents.enabled.value,\n });\n }\n }\n return validOptions;\n};\n\n/**\n * Validates if the input is a valid consents data\n * @param value Input consents data\n * @returns true if the input is a valid consents data else false\n */\nconst isValidConsentsData = (value: Consents | undefined): value is Consents =>\n isNonEmptyObject(value) || Array.isArray(value);\n\n/**\n * Retrieves the corresponding provider and plugin name of the selected consent manager from the supported consent managers\n * @param consentManagementOpts consent management options\n * @param logger logger instance\n * @returns Corresponding provider and plugin name of the selected consent manager from the supported consent managers\n */\nconst getConsentManagerInfo = (\n consentManagementOpts: ConsentManagementOptions,\n logger?: ILogger,\n) => {\n let { provider }: { provider?: ConsentManagementProvider } = consentManagementOpts;\n const consentManagerPluginName = provider ? ConsentManagersToPluginNameMap[provider] : undefined;\n if (provider && !consentManagerPluginName) {\n logger?.error(\n UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER, provider, ConsentManagersToPluginNameMap),\n );\n\n // Reset the provider value\n provider = undefined;\n }\n return { provider, consentManagerPluginName };\n};\n\n/**\n * Validates and converts the consent management options into a normalized format\n * @param consentManagementOpts Consent management options provided by the user\n * @param logger logger instance\n * @returns An object containing the consent manager plugin name, initialized, enabled and consents data\n */\nconst getConsentManagementData = (\n consentManagementOpts: ConsentManagementOptions | undefined,\n logger?: ILogger,\n) => {\n let consentManagerPluginName: PluginName | undefined;\n let allowedConsentIds: Consents = [];\n let deniedConsentIds: Consents = [];\n let initialized = false;\n let provider: ConsentManagementProvider | undefined;\n\n let enabled = consentManagementOpts?.enabled === true;\n if (isNonEmptyObject(consentManagementOpts) && enabled) {\n // Get the corresponding plugin name of the selected consent manager from the supported consent managers\n ({ provider, consentManagerPluginName } = getConsentManagerInfo(consentManagementOpts, logger));\n\n if (isValidConsentsData(consentManagementOpts.allowedConsentIds)) {\n allowedConsentIds = consentManagementOpts.allowedConsentIds;\n initialized = true;\n }\n\n if (isValidConsentsData(consentManagementOpts.deniedConsentIds)) {\n deniedConsentIds = consentManagementOpts.deniedConsentIds;\n initialized = true;\n }\n }\n\n const consentsData = {\n allowedConsentIds,\n deniedConsentIds,\n };\n\n // Enable consent management only if consent manager is supported\n enabled = enabled && Boolean(consentManagerPluginName);\n\n return {\n provider,\n consentManagerPluginName,\n initialized,\n enabled,\n consentsData,\n };\n};\n\nexport { getUserSelectedConsentManager, getValidPostConsentOptions, getConsentManagementData };\n","import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { CONFIG_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { batch } from '@preact/signals-core';\nimport { isDefined, isUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { isSDKRunningInChromeExtension } from '@rudderstack/analytics-js-common/utilities/detect';\nimport { DEFAULT_STORAGE_TYPE } from '@rudderstack/analytics-js-common/types/Storage';\nimport type {\n DeliveryType,\n StorageStrategy,\n} from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport {\n DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE,\n DEFAULT_PRE_CONSENT_STORAGE_STRATEGY,\n} from '@rudderstack/analytics-js-common/constants/consent';\nimport { isObjectLiteralAndNotNull } from '@rudderstack/analytics-js-common/utilities/object';\nimport type {\n ConsentManagementMetadata,\n ConsentResolutionStrategy,\n} from '@rudderstack/analytics-js-common/types/Consent';\nimport { clone } from 'ramda';\nimport type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { isValidURL, removeDuplicateSlashes } from '@rudderstack/analytics-js-common/utilities/url';\nimport { removeLeadingPeriod } from '@rudderstack/analytics-js-common/utilities/string';\nimport { MODULE_TYPE, APP_VERSION } from '../../../constants/app';\nimport { BUILD_TYPE, DEFAULT_CONFIG_BE_URL } from '../../../constants/urls';\nimport { state } from '../../../state';\nimport {\n INVALID_CONFIG_URL_WARNING,\n STORAGE_DATA_MIGRATION_OVERRIDE_WARNING,\n STORAGE_TYPE_VALIDATION_WARNING,\n UNSUPPORTED_BEACON_API_WARNING,\n UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE,\n UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY,\n UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING,\n SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING,\n} from '../../../constants/logMessages';\nimport {\n isErrorReportingEnabled,\n isMetricsReportingEnabled,\n} from '../../utilities/statsCollection';\nimport { getDomain, removeTrailingSlashes } from '../../utilities/url';\nimport type { SourceConfigResponse } from '../types';\nimport {\n DEFAULT_DATA_SERVICE_ENDPOINT,\n DEFAULT_STORAGE_ENCRYPTION_VERSION,\n StorageEncryptionVersionsToPluginNameMap,\n} from '../constants';\nimport { getDataServiceUrl, isValidStorageType, isWebpageTopLevelDomain } from './validate';\nimport { getConsentManagementData } from '../../utilities/consent';\n\n/**\n * Determines the SDK URL\n * @returns sdkURL\n */\nconst getSDKUrl = (): string | undefined => {\n const scripts = document.getElementsByTagName('script');\n const sdkFileNameRegex = /(?:^|\\/)rsa(\\.min)?\\.js$/;\n\n // eslint-disable-next-line no-restricted-syntax\n for (const script of scripts) {\n const src = script.getAttribute('src');\n if (src && sdkFileNameRegex.test(src)) {\n return src;\n }\n }\n\n return undefined;\n};\n\n/**\n * Updates the reporting state variables from the source config data\n * @param res Source config\n * @param logger Logger instance\n */\nconst updateReportingState = (res: SourceConfigResponse): void => {\n state.reporting.isErrorReportingEnabled.value =\n isErrorReportingEnabled(res.source.config) && !isSDKRunningInChromeExtension();\n state.reporting.isMetricsReportingEnabled.value = isMetricsReportingEnabled(res.source.config);\n};\n\nconst updateStorageStateFromLoadOptions = (logger?: ILogger): void => {\n const {\n useServerSideCookies,\n dataServiceEndpoint,\n storage: storageOptsFromLoad,\n setCookieDomain,\n sameDomainCookiesOnly,\n } = state.loadOptions.value;\n let storageType = storageOptsFromLoad?.type;\n if (isDefined(storageType) && !isValidStorageType(storageType)) {\n logger?.warn(\n STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER, storageType, DEFAULT_STORAGE_TYPE),\n );\n storageType = DEFAULT_STORAGE_TYPE;\n }\n\n let storageEncryptionVersion = storageOptsFromLoad?.encryption?.version;\n const encryptionPluginName =\n storageEncryptionVersion && StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];\n\n if (!isUndefined(storageEncryptionVersion) && isUndefined(encryptionPluginName)) {\n // set the default encryption plugin\n logger?.warn(\n UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(\n CONFIG_MANAGER,\n storageEncryptionVersion,\n StorageEncryptionVersionsToPluginNameMap,\n DEFAULT_STORAGE_ENCRYPTION_VERSION,\n ),\n );\n storageEncryptionVersion = DEFAULT_STORAGE_ENCRYPTION_VERSION;\n } else if (isUndefined(storageEncryptionVersion)) {\n storageEncryptionVersion = DEFAULT_STORAGE_ENCRYPTION_VERSION;\n }\n\n // Allow migration only if the configured encryption version is the default encryption version\n const configuredMigrationValue = storageOptsFromLoad?.migrate;\n const finalMigrationVal =\n (configuredMigrationValue as boolean) &&\n storageEncryptionVersion === DEFAULT_STORAGE_ENCRYPTION_VERSION;\n\n if (configuredMigrationValue === true && finalMigrationVal !== configuredMigrationValue) {\n logger?.warn(\n STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(\n CONFIG_MANAGER,\n storageEncryptionVersion,\n DEFAULT_STORAGE_ENCRYPTION_VERSION,\n ),\n );\n }\n\n batch(() => {\n state.storage.type.value = storageType;\n let cookieOptions = storageOptsFromLoad?.cookie ?? {};\n\n if (useServerSideCookies) {\n state.serverCookies.isEnabledServerSideCookies.value = useServerSideCookies;\n const providedCookieDomain = cookieOptions.domain ?? setCookieDomain;\n /**\n * Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:\n * 1. If the cookie domain is provided and it is not a top-level domain, then use the exact domain\n * 2. If the sameDomainCookiesOnly flag is set to true, then use the exact domain\n */\n const useExactDomain =\n (isDefined(providedCookieDomain) &&\n !isWebpageTopLevelDomain(removeLeadingPeriod(providedCookieDomain as string))) ||\n sameDomainCookiesOnly;\n\n const dataServiceUrl = getDataServiceUrl(\n dataServiceEndpoint ?? DEFAULT_DATA_SERVICE_ENDPOINT,\n useExactDomain ?? false,\n );\n\n if (isValidURL(dataServiceUrl)) {\n state.serverCookies.dataServiceUrl.value = removeTrailingSlashes(dataServiceUrl) as string;\n\n const curHost = getDomain(window.location.href);\n const dataServiceHost = getDomain(dataServiceUrl);\n\n // If the current host is different from the data service host, then it is a cross-site request\n // For server-side cookies to work, we need to set the SameSite=None and Secure attributes\n // One round of cookie options manipulation is taking place here\n // Based on these(setCookieDomain/storage.cookie or sameDomainCookiesOnly) two load-options, final cookie options are set in the storage module\n // TODO: Refactor the cookie options manipulation logic in one place\n if (curHost !== dataServiceHost) {\n cookieOptions = {\n ...cookieOptions,\n samesite: 'None',\n secure: true,\n };\n }\n /**\n * If the sameDomainCookiesOnly flag is not set and the cookie domain is provided(not top level domain),\n * and the data service host is different from the provided cookie domain, then we disable server-side cookies\n * ex: provided cookie domain: 'random.com', data service host: 'sub.example.com'\n */\n if (\n !sameDomainCookiesOnly &&\n useExactDomain &&\n dataServiceHost !== removeLeadingPeriod(providedCookieDomain as string)\n ) {\n state.serverCookies.isEnabledServerSideCookies.value = false;\n logger?.warn(\n SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(\n CONFIG_MANAGER,\n providedCookieDomain,\n dataServiceHost as string,\n ),\n );\n }\n } else {\n state.serverCookies.isEnabledServerSideCookies.value = false;\n }\n }\n\n state.storage.cookie.value = cookieOptions;\n\n state.storage.encryptionPluginName.value =\n StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion as string];\n\n state.storage.migrate.value = finalMigrationVal;\n });\n};\n\nconst updateConsentsStateFromLoadOptions = (logger?: ILogger): void => {\n const { provider, consentManagerPluginName, initialized, enabled, consentsData } =\n getConsentManagementData(state.loadOptions.value.consentManagement, logger);\n\n // Pre-consent\n const preConsentOpts = state.loadOptions.value.preConsent;\n\n let storageStrategy: StorageStrategy =\n preConsentOpts?.storage?.strategy ?? DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;\n const StorageStrategies = ['none', 'session', 'anonymousId'];\n if (isDefined(storageStrategy) && !StorageStrategies.includes(storageStrategy)) {\n storageStrategy = DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;\n\n logger?.warn(\n UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(\n CONFIG_MANAGER,\n preConsentOpts?.storage?.strategy,\n DEFAULT_PRE_CONSENT_STORAGE_STRATEGY,\n ),\n );\n }\n\n let eventsDeliveryType: DeliveryType =\n preConsentOpts?.events?.delivery ?? DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;\n const deliveryTypes = ['immediate', 'buffer'];\n if (isDefined(eventsDeliveryType) && !deliveryTypes.includes(eventsDeliveryType)) {\n eventsDeliveryType = DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;\n\n logger?.warn(\n UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(\n CONFIG_MANAGER,\n preConsentOpts?.events?.delivery,\n DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE,\n ),\n );\n }\n\n batch(() => {\n state.consents.activeConsentManagerPluginName.value = consentManagerPluginName;\n state.consents.initialized.value = initialized;\n state.consents.enabled.value = enabled;\n state.consents.data.value = consentsData;\n state.consents.provider.value = provider;\n\n state.consents.preConsent.value = {\n // Only enable pre-consent if it is explicitly enabled and\n // if it is not already initialized and\n // if consent management is enabled\n enabled:\n state.loadOptions.value.preConsent?.enabled === true &&\n initialized === false &&\n enabled === true,\n storage: {\n strategy: storageStrategy,\n },\n events: {\n delivery: eventsDeliveryType,\n },\n };\n });\n};\n\n/**\n * Determines the consent management state variables from the source config data\n * @param resp Source config response\n * @param logger Logger instance\n */\nconst updateConsentsState = (resp: SourceConfigResponse): void => {\n let resolutionStrategy: ConsentResolutionStrategy | undefined =\n state.consents.resolutionStrategy.value;\n\n let cmpMetadata: ConsentManagementMetadata | undefined;\n if (isObjectLiteralAndNotNull(resp.consentManagementMetadata)) {\n if (state.consents.provider.value) {\n resolutionStrategy =\n resp.consentManagementMetadata.providers.find(\n p => p.provider === state.consents.provider.value,\n )?.resolutionStrategy ?? state.consents.resolutionStrategy.value;\n }\n\n cmpMetadata = resp.consentManagementMetadata;\n }\n\n // If the provider is custom, then the resolution strategy is not applicable\n if (state.consents.provider.value === 'custom') {\n resolutionStrategy = undefined;\n }\n\n batch(() => {\n state.consents.metadata.value = clone(cmpMetadata);\n state.consents.resolutionStrategy.value = resolutionStrategy;\n });\n};\n\nconst updateDataPlaneEventsStateFromLoadOptions = (logger?: ILogger) => {\n if (state.dataPlaneEvents.deliveryEnabled.value) {\n const defaultEventsQueuePluginName: PluginName = 'FetchQueue';\n let eventsQueuePluginName: PluginName = defaultEventsQueuePluginName;\n\n if (state.loadOptions.value.useBeacon) {\n if (state.capabilities.isBeaconAvailable.value) {\n eventsQueuePluginName = 'BeaconQueue';\n } else {\n eventsQueuePluginName = defaultEventsQueuePluginName;\n\n logger?.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));\n }\n }\n\n batch(() => {\n state.dataPlaneEvents.eventsQueuePluginName.value = eventsQueuePluginName;\n });\n }\n};\n\nconst getSourceConfigURL = (\n configUrl: string | undefined,\n writeKey: string,\n lockIntegrationsVersion: boolean,\n lockPluginsVersion: boolean,\n logger?: ILogger,\n): string => {\n const defSearchParams = new URLSearchParams({\n p: MODULE_TYPE,\n v: APP_VERSION,\n build: BUILD_TYPE,\n writeKey,\n lockIntegrationsVersion: lockIntegrationsVersion.toString(),\n lockPluginsVersion: lockPluginsVersion.toString(),\n });\n\n let origin = DEFAULT_CONFIG_BE_URL;\n let searchParams = defSearchParams;\n let pathname = '/sourceConfig/';\n let hash = '';\n if (isValidURL(configUrl)) {\n const configUrlInstance = new URL(configUrl);\n if (!(removeTrailingSlashes(configUrlInstance.pathname) as string).endsWith('/sourceConfig')) {\n configUrlInstance.pathname = `${\n removeTrailingSlashes(configUrlInstance.pathname) as string\n }/sourceConfig/`;\n }\n configUrlInstance.pathname = removeDuplicateSlashes(configUrlInstance.pathname);\n\n defSearchParams.forEach((value, key) => {\n if (configUrlInstance.searchParams.get(key) === null) {\n configUrlInstance.searchParams.set(key, value);\n }\n });\n\n origin = configUrlInstance.origin;\n pathname = configUrlInstance.pathname;\n searchParams = configUrlInstance.searchParams;\n hash = configUrlInstance.hash;\n } else {\n logger?.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER, configUrl));\n }\n\n return `${origin}${pathname}?${searchParams}${hash}`;\n};\n\nexport {\n getSDKUrl,\n updateReportingState,\n updateStorageStateFromLoadOptions,\n updateConsentsStateFromLoadOptions,\n updateConsentsState,\n updateDataPlaneEventsStateFromLoadOptions,\n getSourceConfigURL,\n};\n","import type { SourceConfig } from '@rudderstack/analytics-js-common/types/Source';\n\nconst isErrorReportingEnabled = (sourceConfig?: SourceConfig): boolean =>\n sourceConfig?.statsCollection?.errors?.enabled === true;\n\nconst isMetricsReportingEnabled = (sourceConfig?: SourceConfig): boolean =>\n sourceConfig?.statsCollection?.metrics?.enabled === true;\n\nexport { isErrorReportingEnabled, isMetricsReportingEnabled };\n","/**\n * Determines if the SDK is running inside a chrome extension\n * @returns boolean\n */\nconst isSDKRunningInChromeExtension = (): boolean =>\n !!((window as any).chrome && (window as any).chrome.runtime && (window as any).chrome.runtime.id);\n\nexport { isSDKRunningInChromeExtension };\n","import { CDN_INT_DIR, CDN_PLUGINS_DIR } from '@rudderstack/analytics-js-common/constants/urls';\nimport { isValidURL } from '@rudderstack/analytics-js-common/utilities/url';\nimport {\n BUILD_TYPE,\n CDN_ARCH_VERSION_DIR,\n DEST_SDK_BASE_URL,\n PLUGINS_BASE_URL,\n} from '../../../constants/urls';\nimport { COMPONENT_BASE_URL_ERROR } from '../../../constants/logMessages';\nimport { removeTrailingSlashes } from '../../utilities/url';\nimport { getSDKUrl } from './commonUtil';\n\nconst getSDKComponentBaseURL = (\n componentType: string,\n pathSuffix: string,\n baseURL: string,\n currentVersion: string,\n lockVersion: boolean,\n customURL?: string,\n) => {\n let sdkComponentURL = '';\n\n if (customURL) {\n if (!isValidURL(customURL)) {\n throw new Error(COMPONENT_BASE_URL_ERROR(componentType));\n }\n\n return removeTrailingSlashes(customURL) as string;\n }\n\n const sdkURL = getSDKUrl();\n sdkComponentURL = sdkURL ? sdkURL.split('/').slice(0, -1).concat(pathSuffix).join('/') : baseURL;\n\n if (lockVersion) {\n sdkComponentURL = sdkComponentURL.replace(\n `/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${pathSuffix}`,\n `/${currentVersion}/${BUILD_TYPE}/${pathSuffix}`,\n );\n }\n\n return sdkComponentURL;\n};\n\n/**\n * A function that determines integration SDK loading path\n * @param currentVersion\n * @param lockIntegrationsVersion\n * @param customIntegrationsCDNPath\n * @returns\n */\nconst getIntegrationsCDNPath = (\n currentVersion: string,\n lockIntegrationsVersion: boolean,\n customIntegrationsCDNPath?: string,\n): string =>\n getSDKComponentBaseURL(\n 'integrations',\n CDN_INT_DIR,\n DEST_SDK_BASE_URL,\n currentVersion,\n lockIntegrationsVersion,\n customIntegrationsCDNPath,\n );\n\n/**\n * A function that determines plugins SDK loading path\n * @param currentVersion Current SDK version\n * @param lockPluginsVersion Flag to lock the plugins version\n * @param customPluginsCDNPath URL to load the plugins from\n * @returns Final plugins CDN path\n */\nconst getPluginsCDNPath = (\n currentVersion: string,\n lockPluginsVersion: boolean,\n customPluginsCDNPath?: string,\n): string =>\n getSDKComponentBaseURL(\n 'plugins',\n CDN_PLUGINS_DIR,\n PLUGINS_BASE_URL,\n currentVersion,\n lockPluginsVersion,\n customPluginsCDNPath,\n );\n\nexport { getIntegrationsCDNPath, getPluginsCDNPath };\n","/* eslint-disable class-methods-use-this */\nimport type {\n IHttpClient,\n IResponseDetails,\n} from '@rudderstack/analytics-js-common/types/HttpClient';\nimport { batch, effect } from '@preact/signals-core';\nimport { isFunction, isString } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { CONFIG_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { isValidSourceConfig, validateLoadArgs } from './util/validate';\nimport {\n SOURCE_CONFIG_FETCH_ERROR,\n SOURCE_CONFIG_OPTION_ERROR,\n SOURCE_CONFIG_RESOLUTION_ERROR,\n SOURCE_DISABLED_ERROR,\n} from '../../constants/logMessages';\nimport { filterEnabledDestination } from '../utilities/destinations';\nimport { removeTrailingSlashes } from '../utilities/url';\nimport { APP_VERSION } from '../../constants/app';\nimport { state } from '../../state';\nimport { getIntegrationsCDNPath, getPluginsCDNPath } from './util/cdnPaths';\nimport type { IConfigManager, SourceConfigResponse } from './types';\nimport {\n getSourceConfigURL,\n updateConsentsState,\n updateConsentsStateFromLoadOptions,\n updateDataPlaneEventsStateFromLoadOptions,\n updateReportingState,\n updateStorageStateFromLoadOptions,\n} from './util/commonUtil';\nimport { METRICS_SERVICE_ENDPOINT } from './constants';\n\nclass ConfigManager implements IConfigManager {\n httpClient: IHttpClient;\n errorHandler?: IErrorHandler;\n logger?: ILogger;\n hasErrorHandler = false;\n\n constructor(httpClient: IHttpClient, errorHandler?: IErrorHandler, logger?: ILogger) {\n this.errorHandler = errorHandler;\n this.logger = logger;\n this.httpClient = httpClient;\n this.hasErrorHandler = Boolean(this.errorHandler);\n\n this.onError = this.onError.bind(this);\n this.processConfig = this.processConfig.bind(this);\n }\n\n attachEffects() {\n effect(() => {\n this.logger?.setMinLogLevel(state.lifecycle.logLevel.value);\n });\n }\n\n /**\n * A function to validate, construct and store loadOption, lifecycle, source and destination\n * config related information in global state\n */\n init() {\n this.attachEffects();\n\n validateLoadArgs(state.lifecycle.writeKey.value, state.lifecycle.dataPlaneUrl.value);\n\n const {\n logLevel,\n configUrl,\n lockIntegrationsVersion,\n lockPluginsVersion,\n destSDKBaseURL,\n pluginsSDKBaseURL,\n } = state.loadOptions.value;\n\n state.lifecycle.activeDataplaneUrl.value = removeTrailingSlashes(\n state.lifecycle.dataPlaneUrl.value,\n ) as string;\n\n // determine the path to fetch integration SDK from\n const intgCdnUrl = getIntegrationsCDNPath(\n APP_VERSION,\n lockIntegrationsVersion as boolean,\n destSDKBaseURL,\n );\n // determine the path to fetch remote plugins from\n const pluginsCDNPath = getPluginsCDNPath(\n APP_VERSION,\n lockPluginsVersion as boolean,\n pluginsSDKBaseURL,\n );\n\n updateStorageStateFromLoadOptions(this.logger);\n updateConsentsStateFromLoadOptions(this.logger);\n updateDataPlaneEventsStateFromLoadOptions(this.logger);\n\n // set application lifecycle state in global state\n batch(() => {\n state.lifecycle.integrationsCDNPath.value = intgCdnUrl;\n state.lifecycle.pluginsCDNPath.value = pluginsCDNPath;\n\n if (logLevel) {\n state.lifecycle.logLevel.value = logLevel;\n }\n\n state.lifecycle.sourceConfigUrl.value = getSourceConfigURL(\n configUrl,\n state.lifecycle.writeKey.value as string,\n lockIntegrationsVersion as boolean,\n lockPluginsVersion as boolean,\n this.logger,\n );\n state.metrics.metricsServiceUrl.value = `${state.lifecycle.activeDataplaneUrl.value}/${METRICS_SERVICE_ENDPOINT}`;\n });\n\n this.getConfig();\n }\n\n /**\n * Handle errors\n */\n onError(error: unknown, customMessage?: string, shouldAlwaysThrow?: boolean) {\n if (this.hasErrorHandler) {\n this.errorHandler?.onError(error, CONFIG_MANAGER, customMessage, shouldAlwaysThrow);\n } else {\n throw error;\n }\n }\n\n /**\n * A callback function that is executed once we fetch the source config response.\n * Use to construct and store information that are dependent on the sourceConfig.\n */\n processConfig(response?: SourceConfigResponse | string | null, details?: IResponseDetails) {\n // TODO: add retry logic with backoff based on details\n // We can use isErrRetryable utility method\n if (!response) {\n this.onError(SOURCE_CONFIG_FETCH_ERROR(details?.error));\n return;\n }\n\n let res: SourceConfigResponse;\n try {\n if (isString(response)) {\n res = JSON.parse(response);\n } else {\n res = response;\n }\n } catch (err) {\n this.onError(err, SOURCE_CONFIG_RESOLUTION_ERROR, true);\n return;\n }\n\n if (!isValidSourceConfig(res)) {\n this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR), undefined, true);\n return;\n }\n\n // Log error and abort if source is disabled\n if (res.source.enabled === false) {\n this.logger?.error(SOURCE_DISABLED_ERROR);\n return;\n }\n\n // set the values in state for reporting slice\n updateReportingState(res);\n\n const nativeDestinations: Destination[] =\n res.source.destinations.length > 0 ? filterEnabledDestination(res.source.destinations) : [];\n\n // set in the state --> source, destination, lifecycle, reporting\n batch(() => {\n // set source related information in state\n state.source.value = {\n config: res.source.config,\n id: res.source.id,\n workspaceId: res.source.workspaceId,\n };\n\n // set device mode destination related information in state\n state.nativeDestinations.configuredDestinations.value = nativeDestinations;\n\n // set the desired optional plugins\n state.plugins.pluginsToLoadFromConfig.value = state.loadOptions.value.plugins ?? [];\n\n updateConsentsState(res);\n\n // set application lifecycle state\n state.lifecycle.status.value = 'configured';\n });\n }\n\n /**\n * A function to fetch source config either from /sourceConfig endpoint\n * or from getSourceConfig load option\n * @returns\n */\n getConfig() {\n const sourceConfigFunc = state.loadOptions.value.getSourceConfig;\n if (sourceConfigFunc) {\n if (!isFunction(sourceConfigFunc)) {\n throw new Error(SOURCE_CONFIG_OPTION_ERROR);\n }\n // Fetch source config from the function\n const res = sourceConfigFunc();\n\n if (res instanceof Promise) {\n res\n .then(pRes => this.processConfig(pRes as SourceConfigResponse))\n .catch(err => {\n this.onError(err, 'SourceConfig');\n });\n } else {\n this.processConfig(res as SourceConfigResponse);\n }\n } else {\n // Fetch source configuration from the configured URL\n this.httpClient.request({\n url: state.lifecycle.sourceConfigUrl.value as string,\n options: {\n method: 'GET',\n },\n callback: this.processConfig,\n });\n }\n }\n}\n\nexport { ConfigManager };\n","import type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport type { ConfigResponseDestinationItem } from '../configManager/types';\n\n/**\n * A function to filter enabled destinations and map to required properties only\n * @param destinations\n *\n * @returns Destination[]\n */\nconst filterEnabledDestination = (destinations: ConfigResponseDestinationItem[]): Destination[] => {\n const nativeDestinations: Destination[] = [];\n destinations.forEach((destination: ConfigResponseDestinationItem) => {\n if (destination.enabled && !destination.deleted) {\n nativeDestinations.push({\n id: destination.id,\n displayName: destination.destinationDefinition.displayName,\n config: destination.config,\n shouldApplyDeviceModeTransformation:\n destination.shouldApplyDeviceModeTransformation || false,\n propagateEventsUntransformedOnError:\n destination.propagateEventsUntransformedOnError || false,\n userFriendlyId: `${destination.destinationDefinition.displayName.replaceAll(' ', '-')}___${\n destination.id\n }`,\n });\n }\n });\n return nativeDestinations;\n};\n\nexport { filterEnabledDestination };\n","import { isUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport { getReferringDomain, getUrlWithoutHash } from './url';\n\n/**\n * Get the referrer URL\n * @returns The referrer URL\n */\nconst getReferrer = (): string => document?.referrer || '$direct';\n\n/**\n * To get the canonical URL of the page\n * @returns canonical URL\n */\nconst getCanonicalUrl = (): string => {\n const tags = document.getElementsByTagName('link');\n let canonicalUrl = '';\n\n for (let i = 0; tags[i]; i += 1) {\n const tag = tags[i] as HTMLLinkElement;\n if (tag.getAttribute('rel') === 'canonical' && !canonicalUrl) {\n canonicalUrl = tag.getAttribute('href') ?? '';\n break;\n }\n }\n\n return canonicalUrl;\n};\n\nconst getUserAgent = (): Nullable => {\n if (isUndefined(globalThis.navigator)) {\n return null;\n }\n\n let { userAgent } = globalThis.navigator;\n const { brave } = globalThis.navigator as any;\n\n // For supporting Brave browser detection,\n // add \"Brave/\" to the user agent with the version value from the Chrome component\n if (brave && Object.getPrototypeOf(brave).isBrave) {\n // Example:\n // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36\n const matchedArr = userAgent.match(/(chrome)\\/([\\w.]+)/i);\n\n if (matchedArr) {\n userAgent = `${userAgent} Brave/${matchedArr[2]}`;\n }\n }\n\n return userAgent;\n};\n\nconst getLanguage = (): Nullable => {\n if (isUndefined(globalThis.navigator)) {\n return null;\n }\n\n return globalThis.navigator.language ?? (globalThis.navigator as any).browserLanguage;\n};\n\n/**\n * Default page properties\n * @returns Default page properties\n */\nconst getDefaultPageProperties = (): Record => {\n const canonicalUrl = getCanonicalUrl();\n let path = globalThis.location.pathname;\n const { href: tabUrl } = globalThis.location;\n let pageUrl = tabUrl;\n const { search } = globalThis.location;\n\n // If valid canonical URL is provided use this as page URL.\n if (canonicalUrl) {\n try {\n const urlObj = new URL(canonicalUrl);\n // If existing, query params of canonical URL will be used instead of the location.search ones\n if (urlObj.search === '') {\n pageUrl = canonicalUrl + search;\n } else {\n pageUrl = canonicalUrl;\n }\n\n path = urlObj.pathname;\n } catch (err) {\n // Do nothing\n }\n }\n\n const url = getUrlWithoutHash(pageUrl);\n const { title } = document;\n const referrer = getReferrer();\n return {\n path,\n referrer,\n referring_domain: getReferringDomain(referrer),\n search,\n title,\n url,\n tab_url: tabUrl,\n };\n};\n\nexport { getCanonicalUrl, getReferrer, getUserAgent, getLanguage, getDefaultPageProperties };\n","import { legacyJSEngineRequiredPolyfills } from '../detection/dom';\n\n// eslint-disable-next-line no-constant-condition\nconst POLYFILL_URL = '__RS_POLYFILLIO_SDK_URL__'\n ? `__RS_POLYFILLIO_SDK_URL__?version=3.111.0&features=${Object.keys(\n legacyJSEngineRequiredPolyfills,\n ).join('%2C')}`\n : '';\n\nconst POLYFILL_LOAD_TIMEOUT = 10 * 1000; // 10 seconds\n\nconst POLYFILL_SCRIPT_ID = 'rudderstackPolyfill';\n\nexport { POLYFILL_URL, POLYFILL_LOAD_TIMEOUT, POLYFILL_SCRIPT_ID };\n","import type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types';\nimport { ExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader';\nimport { batch, effect } from '@preact/signals-core';\nimport {\n COOKIE_STORAGE,\n LOCAL_STORAGE,\n SESSION_STORAGE,\n} from '@rudderstack/analytics-js-common/constants/storages';\nimport { CAPABILITIES_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { getTimezone } from '@rudderstack/analytics-js-common/utilities/timezone';\nimport { isValidURL } from '@rudderstack/analytics-js-common/utilities/url';\nimport { isDefinedAndNotNull } from '@rudderstack/analytics-js-common/utilities/checks';\nimport {\n INVALID_POLYFILL_URL_WARNING,\n POLYFILL_SCRIPT_LOAD_ERROR,\n} from '../../constants/logMessages';\nimport { getLanguage, getUserAgent } from '../utilities/page';\nimport { getStorageEngine } from '../../services/StoreManager/storages';\nimport { state } from '../../state';\nimport { getUserAgentClientHint } from './detection/clientHint';\nimport type { ICapabilitiesManager } from './types';\nimport { POLYFILL_LOAD_TIMEOUT, POLYFILL_SCRIPT_ID, POLYFILL_URL } from './polyfill';\nimport {\n getScreenDetails,\n hasBeacon,\n hasCrypto,\n hasUAClientHints,\n isIE11,\n isLegacyJSEngine,\n isStorageAvailable,\n} from './detection';\nimport { detectAdBlockers } from './detection/adBlockers';\nimport { debounce } from '../utilities/globals';\n\n// TODO: replace direct calls to detection methods with state values when possible\nclass CapabilitiesManager implements ICapabilitiesManager {\n logger?: ILogger;\n errorHandler?: IErrorHandler;\n externalSrcLoader: IExternalSrcLoader;\n\n constructor(errorHandler?: IErrorHandler, logger?: ILogger) {\n this.logger = logger;\n this.errorHandler = errorHandler;\n this.externalSrcLoader = new ExternalSrcLoader(this.errorHandler, this.logger);\n this.onError = this.onError.bind(this);\n this.onReady = this.onReady.bind(this);\n }\n\n init() {\n try {\n this.prepareBrowserCapabilities();\n this.attachWindowListeners();\n } catch (err) {\n this.onError(err);\n }\n }\n\n /**\n * Detect supported capabilities and set values in state\n */\n // eslint-disable-next-line class-methods-use-this\n detectBrowserCapabilities() {\n batch(() => {\n // Storage related details\n state.capabilities.storage.isCookieStorageAvailable.value = isStorageAvailable(\n COOKIE_STORAGE,\n getStorageEngine(COOKIE_STORAGE),\n this.logger,\n );\n state.capabilities.storage.isLocalStorageAvailable.value = isStorageAvailable(\n LOCAL_STORAGE,\n undefined,\n this.logger,\n );\n state.capabilities.storage.isSessionStorageAvailable.value = isStorageAvailable(\n SESSION_STORAGE,\n undefined,\n this.logger,\n );\n\n // Browser feature detection details\n state.capabilities.isBeaconAvailable.value = hasBeacon();\n state.capabilities.isUaCHAvailable.value = hasUAClientHints();\n state.capabilities.isCryptoAvailable.value = hasCrypto();\n state.capabilities.isIE11.value = isIE11();\n state.capabilities.isOnline.value = globalThis.navigator.onLine;\n\n // Get page context details\n state.context.userAgent.value = getUserAgent();\n state.context.locale.value = getLanguage();\n state.context.screen.value = getScreenDetails();\n state.context.timezone.value = getTimezone();\n\n if (hasUAClientHints()) {\n getUserAgentClientHint((uach?: UADataValues) => {\n state.context['ua-ch'].value = uach;\n }, state.loadOptions.value.uaChTrackLevel);\n }\n });\n\n // Ad blocker detection\n effect(() => {\n if (\n state.loadOptions.value.sendAdblockPage === true &&\n state.lifecycle.sourceConfigUrl.value !== undefined\n ) {\n detectAdBlockers(this.errorHandler, this.logger);\n }\n });\n }\n\n /**\n * Detect if polyfills are required and then load script from polyfill URL\n */\n prepareBrowserCapabilities() {\n state.capabilities.isLegacyDOM.value = isLegacyJSEngine();\n const customPolyfillUrl = state.loadOptions.value.polyfillURL;\n let polyfillUrl = POLYFILL_URL;\n if (isDefinedAndNotNull(customPolyfillUrl)) {\n if (isValidURL(customPolyfillUrl)) {\n polyfillUrl = customPolyfillUrl;\n } else {\n this.logger?.warn(INVALID_POLYFILL_URL_WARNING(CAPABILITIES_MANAGER, customPolyfillUrl));\n }\n }\n\n const shouldLoadPolyfill =\n state.loadOptions.value.polyfillIfRequired &&\n state.capabilities.isLegacyDOM.value &&\n isValidURL(polyfillUrl);\n\n if (shouldLoadPolyfill) {\n const isDefaultPolyfillService = polyfillUrl !== state.loadOptions.value.polyfillURL;\n if (isDefaultPolyfillService) {\n // write key specific callback\n // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible\n const polyfillCallbackName = `RS_polyfillCallback_${state.lifecycle.writeKey.value}`;\n\n const polyfillCallback = (): void => {\n this.onReady();\n\n // Remove the entry from window so we don't leave room for calling it again\n delete (globalThis as any)[polyfillCallbackName];\n };\n\n (globalThis as any)[polyfillCallbackName] = polyfillCallback;\n\n polyfillUrl = `${polyfillUrl}&callback=${polyfillCallbackName}`;\n }\n\n this.externalSrcLoader.loadJSFile({\n url: polyfillUrl,\n id: POLYFILL_SCRIPT_ID,\n async: true,\n timeout: POLYFILL_LOAD_TIMEOUT,\n callback: (scriptId?: string) => {\n if (!scriptId) {\n this.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID, polyfillUrl)));\n } else if (!isDefaultPolyfillService) {\n this.onReady();\n }\n },\n });\n } else {\n this.onReady();\n }\n }\n\n /**\n * Attach listeners to window to observe event that update capabilities state values\n */\n attachWindowListeners() {\n globalThis.addEventListener('offline', () => {\n state.capabilities.isOnline.value = false;\n });\n\n globalThis.addEventListener('online', () => {\n state.capabilities.isOnline.value = true;\n });\n\n globalThis.addEventListener(\n 'resize',\n debounce(() => {\n state.context.screen.value = getScreenDetails();\n }, this),\n );\n }\n\n /**\n * Set the lifecycle status to next phase\n */\n // eslint-disable-next-line class-methods-use-this\n onReady() {\n this.detectBrowserCapabilities();\n state.lifecycle.status.value = 'browserCapabilitiesReady';\n }\n\n /**\n * Handles error\n * @param error The error object\n */\n onError(error: unknown): void {\n if (this.errorHandler) {\n this.errorHandler.onError(error, CAPABILITIES_MANAGER);\n } else {\n throw error;\n }\n }\n}\n\nexport { CapabilitiesManager };\n","/**\n * To get the timezone of the user\n *\n * @returns string\n */\nconst getTimezone = (): string => {\n const timezone = new Date().toString().match(/([A-Z]+[+-]\\d+)/);\n return timezone && timezone[1] ? timezone[1] : 'NA';\n};\n\nexport { getTimezone };\n","const getUserAgentClientHint = (callback: (uaCH?: UADataValues) => void, level = 'none') => {\n if (level === 'none') {\n callback(undefined);\n }\n if (level === 'default') {\n callback(navigator.userAgentData);\n }\n if (level === 'full') {\n navigator.userAgentData\n ?.getHighEntropyValues([\n 'architecture',\n 'bitness',\n 'brands',\n 'mobile',\n 'model',\n 'platform',\n 'platformVersion',\n 'uaFullVersion',\n 'fullVersionList',\n 'wow64',\n ])\n .then((ua: any) => {\n callback(ua);\n })\n .catch(() => {\n callback();\n });\n }\n};\n\nexport { getUserAgentClientHint };\n","import type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport { HttpClient } from '../../../services/HttpClient/HttpClient';\nimport { state } from '../../../state';\n\nconst detectAdBlockers = (errorHandler?: IErrorHandler, logger?: ILogger): void => {\n // Apparently, '?view=ad' is a query param that is blocked by majority of adblockers\n\n // Use source config URL here as it is very unlikely to be blocked by adblockers\n // Only the extra query param should make it vulnerable to adblockers\n // This will work even if the users proxies it.\n // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)\n const baseUrl = new URL(state.lifecycle.sourceConfigUrl.value as string);\n const url = `${baseUrl.origin}${baseUrl.pathname}?view=ad`;\n\n const httpClient = new HttpClient('fetch', errorHandler, logger);\n httpClient.setAuthHeader(state.lifecycle.writeKey.value as string);\n\n httpClient.request({\n url,\n options: {\n // We actually don't need the response from the request, so we are using HEAD\n method: 'HEAD'\n },\n isRawResponse: true,\n callback: (result, details) => {\n // not ad blocked if the request is successful or it is not internally redirected on the client side\n // Often adblockers instead of blocking the request, they redirect it to an internal URL\n state.capabilities.isAdBlocked.value =\n details?.error !== undefined || details.response?.redirected === true;\n },\n });\n};\n\nexport { detectAdBlockers };\n","const CHANNEL = 'web';\n\n// These are the top-level elements in the standard RudderStack event spec\nconst TOP_LEVEL_ELEMENTS = ['integrations', 'anonymousId', 'originalTimestamp'];\n\n// Reserved elements in the context of standard RudderStack event spec\n// Typically, these elements are not allowed to be overridden by the user\nconst CONTEXT_RESERVED_ELEMENTS = ['library', 'consentManagement', 'userAgent', 'ua-ch', 'screen'];\n\n// Reserved elements in the standard RudderStack event spec\nconst RESERVED_ELEMENTS = [\n 'id',\n 'anonymous_id',\n 'user_id',\n 'sent_at',\n 'timestamp',\n 'received_at',\n 'original_timestamp',\n 'event',\n 'event_text',\n 'channel',\n 'context_ip',\n 'context_request_ip',\n 'context_passed_ip',\n 'group_id',\n 'previous_id',\n];\n\nexport { CHANNEL, TOP_LEVEL_ELEMENTS, CONTEXT_RESERVED_ELEMENTS, RESERVED_ELEMENTS };\n","/**\n * A function to check given value is a number or not\n * @param num input value\n * @returns boolean\n */\nconst isNumber = (num: any): boolean => typeof num === 'number' && !Number.isNaN(num);\n\n/**\n * A function to check given number has minimum length or not\n * @param minimumLength minimum length\n * @param num input number\n * @returns boolean\n */\nconst hasMinLength = (minimumLength: number, num: number) => num.toString().length >= minimumLength;\n\n/**\n * A function to check given value is a positive integer or not\n * @param num input value\n * @returns boolean\n */\nconst isPositiveInteger = (num: any) => isNumber(num) && num >= 0 && Number.isInteger(num);\n\nexport { isNumber, hasMinLength, isPositiveInteger };\n","import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { SessionInfo } from '@rudderstack/analytics-js-common/types/Session';\nimport { USER_SESSION_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport {\n COOKIE_STORAGE,\n LOCAL_STORAGE,\n MEMORY_STORAGE,\n SESSION_STORAGE,\n} from '@rudderstack/analytics-js-common/constants/storages';\nimport { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId';\nimport { DEFAULT_SESSION_TIMEOUT_MS } from '../../constants/timeouts';\nimport { INVALID_SESSION_ID_WARNING } from '../../constants/logMessages';\nimport { hasMinLength, isPositiveInteger } from '../utilities/number';\n\nconst MIN_SESSION_ID_LENGTH = 10;\n\n/**\n * A function to validate current session and return true/false depending on that\n * @returns boolean\n */\nconst hasSessionExpired = (expiresAt?: number): boolean => {\n const timestamp = Date.now();\n return Boolean(!expiresAt || timestamp > expiresAt);\n};\n\n/**\n * A function to generate session id\n * @returns number\n */\nconst generateSessionId = (): number => Date.now();\n\n/**\n * Function to validate user provided sessionId\n * @param {number} sessionId\n * @param logger logger\n * @returns\n */\nconst isManualSessionIdValid = (sessionId?: number, logger?: ILogger): boolean => {\n if (\n !sessionId ||\n !isPositiveInteger(sessionId) ||\n !hasMinLength(MIN_SESSION_ID_LENGTH, sessionId)\n ) {\n logger?.warn(\n INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER, sessionId, MIN_SESSION_ID_LENGTH),\n );\n return false;\n }\n return true;\n};\n\n/**\n * A function to generate new auto tracking session\n * @param sessionTimeout current timestamp\n * @returns SessionInfo\n */\nconst generateAutoTrackingSession = (sessionTimeout?: number): SessionInfo => {\n const timestamp = Date.now();\n const timeout: number = sessionTimeout || DEFAULT_SESSION_TIMEOUT_MS;\n return {\n id: timestamp, // set the current timestamp\n expiresAt: timestamp + timeout, // set the expiry time of the session\n timeout,\n sessionStart: undefined,\n autoTrack: true,\n };\n};\n\n/**\n * A function to generate new manual tracking session\n * @param id Provided sessionId\n * @param logger Logger module\n * @returns SessionInfo\n */\nconst generateManualTrackingSession = (id?: number, logger?: ILogger): SessionInfo => {\n const sessionId: number = isManualSessionIdValid(id, logger)\n ? (id as number)\n : generateSessionId();\n return {\n id: sessionId,\n sessionStart: undefined,\n manualTrack: true,\n };\n};\n\nconst isStorageTypeValidForStoringData = (storageType: StorageType): boolean =>\n Boolean(\n storageType === COOKIE_STORAGE ||\n storageType === LOCAL_STORAGE ||\n storageType === SESSION_STORAGE ||\n storageType === MEMORY_STORAGE,\n );\n\n/**\n * Generate a new anonymousId\n * @returns string anonymousID\n */\nconst generateAnonymousId = (): string => generateUUID();\n\nexport {\n hasSessionExpired,\n generateSessionId,\n generateAutoTrackingSession,\n generateManualTrackingSession,\n MIN_SESSION_ID_LENGTH,\n isStorageTypeValidForStoringData,\n generateAnonymousId,\n};\n","import { clone } from 'ramda';\nimport { isString, isUndefined } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ApiOptions } from '@rudderstack/analytics-js-common/types/EventApi';\nimport type { RudderContext, RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IntegrationOpts } from '@rudderstack/analytics-js-common/types/Integration';\nimport {\n isObjectLiteralAndNotNull,\n mergeDeepRight,\n} from '@rudderstack/analytics-js-common/utilities/object';\nimport { EVENT_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId';\nimport { getCurrentTimeFormatted } from '@rudderstack/analytics-js-common/utilities/timestamp';\nimport { NO_STORAGE } from '@rudderstack/analytics-js-common/constants/storages';\nimport { DEFAULT_INTEGRATIONS_CONFIG } from '@rudderstack/analytics-js-common/constants/integrationsConfig';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport { state } from '../../state';\nimport {\n INVALID_CONTEXT_OBJECT_WARNING,\n RESERVED_KEYWORD_WARNING,\n} from '../../constants/logMessages';\nimport {\n CHANNEL,\n CONTEXT_RESERVED_ELEMENTS,\n RESERVED_ELEMENTS,\n TOP_LEVEL_ELEMENTS,\n} from './constants';\nimport { getDefaultPageProperties } from '../utilities/page';\nimport { extractUTMParameters } from '../utilities/url';\nimport { generateAnonymousId, isStorageTypeValidForStoringData } from '../userSessionManager/utils';\n\n/**\n * To get the page properties for context object\n * @param pageProps Page properties\n * @returns page properties object for context\n */\nconst getContextPageProperties = (pageProps?: ApiObject): ApiObject => {\n // Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist\n const curPageProps = getDefaultPageProperties();\n\n const ctxPageProps: ApiObject = {};\n Object.keys(curPageProps).forEach((key: string) => {\n ctxPageProps[key] = pageProps?.[key] || curPageProps[key];\n });\n\n ctxPageProps.initial_referrer =\n pageProps?.initial_referrer || state.session.initialReferrer.value;\n\n ctxPageProps.initial_referring_domain =\n pageProps?.initial_referring_domain || state.session.initialReferringDomain.value;\n return ctxPageProps;\n};\n\n/**\n * Add any missing default page properties using values from options and defaults\n * @param properties Input page properties\n * @param options API options\n */\nconst getUpdatedPageProperties = (\n properties: ApiObject,\n options?: Nullable,\n): ApiObject => {\n const optionsPageProps = ((options as ApiOptions)?.page as ApiObject) || {};\n const pageProps = properties;\n\n // Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist\n const curPageProps = getDefaultPageProperties();\n\n Object.keys(curPageProps).forEach((key: string) => {\n if (isUndefined(pageProps[key])) {\n pageProps[key] = optionsPageProps[key] || curPageProps[key];\n }\n });\n\n if (isUndefined(pageProps.initial_referrer)) {\n pageProps.initial_referrer =\n optionsPageProps.initial_referrer || state.session.initialReferrer.value;\n }\n\n if (isUndefined(pageProps.initial_referring_domain)) {\n pageProps.initial_referring_domain =\n optionsPageProps.initial_referring_domain || state.session.initialReferringDomain.value;\n }\n\n return pageProps;\n};\n\n/**\n * Utility to check for reserved keys in the input object\n * @param obj Generic object\n * @param parentKeyPath Object's parent key path\n * @param logger Logger instance\n */\nconst checkForReservedElementsInObject = (\n obj: Nullable | RudderContext | undefined,\n parentKeyPath: string,\n logger?: ILogger,\n): void => {\n if (isObjectLiteralAndNotNull(obj)) {\n Object.keys(obj as object).forEach(property => {\n if (\n RESERVED_ELEMENTS.includes(property) ||\n RESERVED_ELEMENTS.includes(property.toLowerCase())\n ) {\n logger?.warn(\n RESERVED_KEYWORD_WARNING(EVENT_MANAGER, property, parentKeyPath, RESERVED_ELEMENTS),\n );\n }\n });\n }\n};\n\n/**\n * Checks for reserved keys in traits, properties, and contextual traits\n * @param rudderEvent Generated rudder event\n * @param logger Logger instance\n */\nconst checkForReservedElements = (rudderEvent: RudderEvent, logger?: ILogger): void => {\n // properties, traits, contextualTraits are either undefined or object\n const { properties, traits, context } = rudderEvent;\n const { traits: contextualTraits } = context;\n\n checkForReservedElementsInObject(properties, 'properties', logger);\n checkForReservedElementsInObject(traits, 'traits', logger);\n checkForReservedElementsInObject(contextualTraits, 'context.traits', logger);\n};\n\n/**\n * Overrides the top-level event properties with data from API options\n * @param rudderEvent Generated rudder event\n * @param options API options\n */\nconst updateTopLevelEventElements = (rudderEvent: RudderEvent, options: ApiOptions): void => {\n if (options.anonymousId && isString(options.anonymousId)) {\n // eslint-disable-next-line no-param-reassign\n rudderEvent.anonymousId = options.anonymousId;\n }\n\n if (isObjectLiteralAndNotNull(options.integrations)) {\n // eslint-disable-next-line no-param-reassign\n rudderEvent.integrations = options.integrations;\n }\n\n if (options.originalTimestamp && isString(options.originalTimestamp)) {\n // eslint-disable-next-line no-param-reassign\n rudderEvent.originalTimestamp = options.originalTimestamp;\n }\n};\n\n/**\n * To merge the contextual information in API options with existing data\n * @param rudderContext Generated rudder event\n * @param options API options\n * @param logger Logger instance\n */\nconst getMergedContext = (\n rudderContext: RudderContext,\n options: ApiOptions,\n logger?: ILogger,\n): RudderContext => {\n let context = rudderContext;\n Object.keys(options).forEach(key => {\n if (!TOP_LEVEL_ELEMENTS.includes(key) && !CONTEXT_RESERVED_ELEMENTS.includes(key)) {\n if (key !== 'context') {\n context = mergeDeepRight(context, {\n [key]: options[key],\n });\n } else if (!isUndefined(options[key]) && isObjectLiteralAndNotNull(options[key])) {\n const tempContext: Record = {};\n Object.keys(options[key] as Record).forEach(e => {\n if (!CONTEXT_RESERVED_ELEMENTS.includes(e)) {\n tempContext[e] = (options[key] as Record)[e];\n }\n });\n context = mergeDeepRight(context, {\n ...tempContext,\n });\n } else {\n logger?.warn(INVALID_CONTEXT_OBJECT_WARNING(EVENT_MANAGER));\n }\n }\n });\n return context;\n};\n\n/**\n * A function to determine whether SDK should use the integration option provided in load call\n * @returns boolean\n */\nconst shouldUseGlobalIntegrationsConfigInEvents = () =>\n state.loadOptions.value.useGlobalIntegrationsConfigInEvents &&\n (isObjectLiteralAndNotNull(state.consents.postConsent.value?.integrations) ||\n isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value));\n\n/**\n * Updates rudder event object with data from the API options\n * @param rudderEvent Generated rudder event\n * @param options API options\n */\nconst processOptions = (rudderEvent: RudderEvent, options?: Nullable): void => {\n // Only allow object type for options\n if (isObjectLiteralAndNotNull(options)) {\n updateTopLevelEventElements(rudderEvent, options as ApiOptions);\n // eslint-disable-next-line no-param-reassign\n rudderEvent.context = getMergedContext(rudderEvent.context, options as ApiOptions);\n }\n};\n\n/**\n * Returns the final integrations config for the event based on the global config and event's config\n * @param integrationsConfig Event's integrations config\n * @returns Final integrations config\n */\nconst getEventIntegrationsConfig = (integrationsConfig: IntegrationOpts) => {\n let finalIntgConfig: IntegrationOpts;\n if (shouldUseGlobalIntegrationsConfigInEvents()) {\n finalIntgConfig = clone(\n state.consents.postConsent.value?.integrations ??\n state.nativeDestinations.loadOnlyIntegrations.value,\n );\n } else if (isObjectLiteralAndNotNull(integrationsConfig)) {\n finalIntgConfig = integrationsConfig;\n } else {\n finalIntgConfig = DEFAULT_INTEGRATIONS_CONFIG;\n }\n return finalIntgConfig;\n};\n\n/**\n * Enrich the base event object with data from state and the API options\n * @param rudderEvent RudderEvent object\n * @param options API options\n * @param pageProps Page properties\n * @param logger logger\n * @returns Enriched RudderEvent object\n */\nconst getEnrichedEvent = (\n rudderEvent: Partial,\n options?: Nullable,\n pageProps?: ApiObject,\n logger?: ILogger,\n): RudderEvent => {\n const commonEventData = {\n channel: CHANNEL,\n context: {\n traits: clone(state.session.userTraits.value),\n sessionId: state.session.sessionInfo.value.id || undefined,\n sessionStart: state.session.sessionInfo.value.sessionStart || undefined,\n // Add 'consentManagement' only if consent management is enabled\n ...(state.consents.enabled.value && {\n consentManagement: {\n deniedConsentIds: clone(state.consents.data.value.deniedConsentIds),\n allowedConsentIds: clone(state.consents.data.value.allowedConsentIds),\n provider: state.consents.provider.value,\n resolutionStrategy: state.consents.resolutionStrategy.value,\n },\n }),\n 'ua-ch': state.context['ua-ch'].value,\n app: state.context.app.value,\n library: state.context.library.value,\n userAgent: state.context.userAgent.value,\n os: state.context.os.value,\n locale: state.context.locale.value,\n screen: state.context.screen.value,\n campaign: extractUTMParameters(globalThis.location.href),\n page: getContextPageProperties(pageProps),\n timezone: state.context.timezone.value,\n },\n originalTimestamp: getCurrentTimeFormatted(),\n integrations: DEFAULT_INTEGRATIONS_CONFIG,\n messageId: generateUUID(),\n userId: rudderEvent.userId || state.session.userId.value,\n } as Partial;\n\n if (\n !isStorageTypeValidForStoringData(state.storage.entries.value.anonymousId?.type as StorageType)\n ) {\n // Generate new anonymous id for each request\n commonEventData.anonymousId = generateAnonymousId();\n } else {\n // Type casting to string as the user session manager will take care of initializing the value\n commonEventData.anonymousId = state.session.anonymousId.value as string;\n }\n\n // set truly anonymous tracking flag\n if (state.storage.trulyAnonymousTracking.value) {\n (commonEventData.context as RudderContext).trulyAnonymousTracking = true;\n }\n\n if (rudderEvent.type === 'identify') {\n (commonEventData.context as RudderContext).traits =\n state.storage.entries.value.userTraits?.type !== NO_STORAGE\n ? clone(state.session.userTraits.value)\n : (rudderEvent.context as RudderContext).traits;\n }\n\n if (rudderEvent.type === 'group') {\n if (rudderEvent.groupId || state.session.groupId.value) {\n commonEventData.groupId = rudderEvent.groupId || state.session.groupId.value;\n }\n\n if (rudderEvent.traits || state.session.groupTraits.value) {\n commonEventData.traits =\n state.storage.entries.value.groupTraits?.type !== NO_STORAGE\n ? clone(state.session.groupTraits.value)\n : rudderEvent.traits;\n }\n }\n\n const processedEvent = mergeDeepRight(rudderEvent, commonEventData) as RudderEvent;\n // Set the default values for the event properties\n // matching with v1.1 payload\n if (processedEvent.event === undefined) {\n processedEvent.event = null;\n }\n\n if (processedEvent.properties === undefined) {\n processedEvent.properties = null;\n }\n\n processOptions(processedEvent, options);\n checkForReservedElements(processedEvent, logger);\n\n // Update the integrations config for the event\n processedEvent.integrations = getEventIntegrationsConfig(processedEvent.integrations);\n\n return processedEvent;\n};\n\nexport {\n getUpdatedPageProperties,\n getEnrichedEvent,\n checkForReservedElements,\n checkForReservedElementsInObject,\n updateTopLevelEventElements,\n getContextPageProperties,\n getMergedContext,\n processOptions,\n};\n","import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport type { APIEvent, ApiOptions } from '@rudderstack/analytics-js-common/types/EventApi';\nimport type { RudderContext, RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport { getEnrichedEvent, getUpdatedPageProperties } from './utilities';\n\nclass RudderEventFactory {\n logger?: ILogger;\n\n constructor(logger?: ILogger) {\n this.logger = logger;\n }\n\n /**\n * Generate a 'page' event based on the user-input fields\n * @param category Page's category\n * @param name Page name\n * @param properties Page properties\n * @param options API options\n */\n generatePageEvent(\n category?: string,\n name?: string,\n properties?: Nullable,\n options?: Nullable,\n ): RudderEvent {\n let props = properties ?? {};\n props = getUpdatedPageProperties(props, options);\n\n const pageEvent: Partial = {\n properties: props,\n name,\n category,\n type: 'page',\n };\n\n return getEnrichedEvent(pageEvent, options, props, this.logger);\n }\n\n /**\n * Generate a 'track' event based on the user-input fields\n * @param event The event name\n * @param properties Event properties\n * @param options API options\n */\n generateTrackEvent(\n event: string,\n properties?: Nullable,\n options?: Nullable,\n ): RudderEvent {\n const trackEvent: Partial = {\n properties,\n event,\n type: 'track',\n };\n\n return getEnrichedEvent(trackEvent, options, undefined, this.logger);\n }\n\n /**\n * Generate an 'identify' event based on the user-input fields\n * @param userId New user ID\n * @param traits new traits\n * @param options API options\n */\n generateIdentifyEvent(\n userId?: Nullable,\n traits?: Nullable,\n options?: Nullable,\n ): RudderEvent {\n const identifyEvent: Partial = {\n userId,\n type: 'identify',\n context: {\n traits,\n } as RudderContext,\n };\n\n return getEnrichedEvent(identifyEvent, options, undefined, this.logger);\n }\n\n /**\n * Generate an 'alias' event based on the user-input fields\n * @param to New user ID\n * @param from Old user ID\n * @param options API options\n */\n generateAliasEvent(to: string, from?: string, options?: Nullable): RudderEvent {\n const aliasEvent: Partial = {\n previousId: from,\n type: 'alias',\n };\n\n const enrichedEvent = getEnrichedEvent(aliasEvent, options, undefined, this.logger);\n // override the User ID from the API inputs\n enrichedEvent.userId = to ?? enrichedEvent.userId;\n return enrichedEvent;\n }\n\n /**\n * Generate a 'group' event based on the user-input fields\n * @param groupId New group ID\n * @param traits new group traits\n * @param options API options\n */\n generateGroupEvent(\n groupId?: Nullable,\n traits?: Nullable,\n options?: Nullable,\n ): RudderEvent {\n const groupEvent: Partial = {\n type: 'group',\n };\n\n if (groupId) {\n groupEvent.groupId = groupId;\n }\n\n if (traits) {\n groupEvent.traits = traits;\n }\n\n return getEnrichedEvent(groupEvent, options, undefined, this.logger);\n }\n\n /**\n * Generates a new RudderEvent object based on the user-input fields\n * @param event API event parameters object\n * @returns A RudderEvent object\n */\n create(event: APIEvent): RudderEvent | undefined {\n let eventObj: RudderEvent | undefined;\n switch (event.type) {\n case 'page':\n eventObj = this.generatePageEvent(\n event.category,\n event.name,\n event.properties,\n event.options,\n );\n break;\n case 'track':\n eventObj = this.generateTrackEvent(event.name as string, event.properties, event.options);\n break;\n case 'identify':\n eventObj = this.generateIdentifyEvent(event.userId, event.traits, event.options);\n break;\n case 'alias':\n eventObj = this.generateAliasEvent(event.to as string, event.from, event.options);\n break;\n case 'group':\n eventObj = this.generateGroupEvent(event.groupId, event.traits, event.options);\n break;\n default:\n // Do nothing\n break;\n }\n return eventObj;\n }\n}\n\nexport { RudderEventFactory };\n","import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { APIEvent } from '@rudderstack/analytics-js-common/types/EventApi';\nimport { EVENT_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { EVENT_OBJECT_GENERATION_ERROR } from '../../constants/logMessages';\nimport type { IEventManager } from './types';\nimport { RudderEventFactory } from './RudderEventFactory';\nimport type { IEventRepository } from '../eventRepository/types';\nimport type { IUserSessionManager } from '../userSessionManager/types';\n\n/**\n * A service to generate valid event payloads and queue them for processing\n */\nclass EventManager implements IEventManager {\n eventRepository: IEventRepository;\n userSessionManager: IUserSessionManager;\n errorHandler?: IErrorHandler;\n logger?: ILogger;\n eventFactory: RudderEventFactory;\n\n /**\n *\n * @param eventRepository Event repository instance\n * @param userSessionManager UserSession Manager instance\n * @param errorHandler Error handler object\n * @param logger Logger object\n */\n constructor(\n eventRepository: IEventRepository,\n userSessionManager: IUserSessionManager,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ) {\n this.eventRepository = eventRepository;\n this.userSessionManager = userSessionManager;\n this.errorHandler = errorHandler;\n this.logger = logger;\n this.eventFactory = new RudderEventFactory(this.logger);\n this.onError = this.onError.bind(this);\n }\n\n /**\n * Initializes the event manager\n */\n init() {\n this.eventRepository.init();\n }\n\n resume() {\n this.eventRepository.resume();\n }\n\n /**\n * Consumes a new incoming event\n * @param event Incoming event data\n */\n addEvent(event: APIEvent) {\n this.userSessionManager.refreshSession();\n const rudderEvent = this.eventFactory.create(event);\n if (rudderEvent) {\n this.eventRepository.enqueue(rudderEvent, event.callback);\n } else {\n this.onError(new Error(EVENT_OBJECT_GENERATION_ERROR));\n }\n }\n\n /**\n * Handles error\n * @param error The error object\n */\n onError(error: unknown, customMessage?: string, shouldAlwaysThrow?: boolean): void {\n if (this.errorHandler) {\n this.errorHandler.onError(error, EVENT_MANAGER, customMessage, shouldAlwaysThrow);\n } else {\n throw error;\n }\n }\n}\n\nexport { EventManager };\n","/* eslint-disable class-methods-use-this */\nimport { batch, effect } from '@preact/signals-core';\nimport {\n isNonEmptyObject,\n mergeDeepRight,\n} from '@rudderstack/analytics-js-common/utilities/object';\nimport {\n isDefinedAndNotNull,\n isDefinedNotNullAndNotEmptyString,\n isNullOrUndefined,\n isString,\n} from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { IPluginsManager } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { IStore, IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { SessionInfo } from '@rudderstack/analytics-js-common/types/Session';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport type { AnonymousIdOptions } from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport { USER_SESSION_MANAGER } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport type { StorageType } from '@rudderstack/analytics-js-common/types/Storage';\nimport {\n COOKIE_STORAGE,\n LOCAL_STORAGE,\n SESSION_STORAGE,\n} from '@rudderstack/analytics-js-common/constants/storages';\nimport type { UserSessionKey } from '@rudderstack/analytics-js-common/types/UserSessionStorage';\nimport type { StorageEntries } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport type {\n AsyncRequestCallback,\n IHttpClient,\n} from '@rudderstack/analytics-js-common/types/HttpClient';\nimport { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json';\nimport { COOKIE_KEYS } from '@rudderstack/analytics-js-cookies/constants/cookies';\nimport {\n CLIENT_DATA_STORE_COOKIE,\n CLIENT_DATA_STORE_LS,\n CLIENT_DATA_STORE_SESSION,\n USER_SESSION_KEYS,\n} from '../../constants/storage';\nimport { storageClientDataStoreNameMap } from '../../services/StoreManager/types';\nimport { DEFAULT_SESSION_TIMEOUT_MS, MIN_SESSION_TIMEOUT_MS } from '../../constants/timeouts';\nimport { defaultSessionConfiguration } from '../../state/slices/session';\nimport { state } from '../../state';\nimport { getStorageEngine } from '../../services/StoreManager/storages';\nimport {\n DATA_SERVER_REQUEST_FAIL_ERROR,\n FAILED_SETTING_COOKIE_FROM_SERVER_ERROR,\n FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR,\n TIMEOUT_NOT_NUMBER_WARNING,\n TIMEOUT_NOT_RECOMMENDED_WARNING,\n TIMEOUT_ZERO_WARNING,\n} from '../../constants/logMessages';\nimport {\n generateAnonymousId,\n generateAutoTrackingSession,\n generateManualTrackingSession,\n hasSessionExpired,\n isStorageTypeValidForStoringData,\n} from './utils';\nimport { getReferringDomain } from '../utilities/url';\nimport { getReferrer } from '../utilities/page';\nimport { DEFAULT_USER_SESSION_VALUES, SERVER_SIDE_COOKIES_DEBOUNCE_TIME } from './constants';\nimport type {\n CallbackFunction,\n CookieData,\n EncryptedCookieData,\n IUserSessionManager,\n UserSessionStorageKeysType,\n} from './types';\nimport { isPositiveInteger } from '../utilities/number';\n\nclass UserSessionManager implements IUserSessionManager {\n storeManager?: IStoreManager;\n pluginsManager?: IPluginsManager;\n errorHandler?: IErrorHandler;\n httpClient?: IHttpClient;\n logger?: ILogger;\n serverSideCookieDebounceFuncs: Record;\n\n constructor(\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n pluginsManager?: IPluginsManager,\n storeManager?: IStoreManager,\n httpClient?: IHttpClient,\n ) {\n this.storeManager = storeManager;\n this.pluginsManager = pluginsManager;\n this.logger = logger;\n this.errorHandler = errorHandler;\n this.httpClient = httpClient;\n this.onError = this.onError.bind(this);\n this.serverSideCookieDebounceFuncs = {} as Record;\n }\n\n /**\n * Initialize User session with values from storage\n */\n init() {\n this.syncStorageDataToState();\n\n // Register the effect to sync with storage\n this.registerEffects();\n }\n\n syncStorageDataToState() {\n this.migrateStorageIfNeeded();\n this.migrateDataFromPreviousStorage();\n\n // get the values from storage and set it again\n this.setUserId(this.getUserId());\n this.setUserTraits(this.getUserTraits());\n this.setGroupId(this.getGroupId());\n this.setGroupTraits(this.getGroupTraits());\n const { externalAnonymousIdCookieName, anonymousIdOptions } = state.loadOptions.value;\n let externalAnonymousId;\n if (\n isDefinedAndNotNull(externalAnonymousIdCookieName) &&\n typeof externalAnonymousIdCookieName === 'string'\n ) {\n externalAnonymousId = this.getExternalAnonymousIdByCookieName(externalAnonymousIdCookieName);\n }\n this.setAnonymousId(externalAnonymousId ?? this.getAnonymousId(anonymousIdOptions));\n this.setAuthToken(this.getAuthToken());\n this.setInitialReferrerInfo();\n this.configureSessionTracking();\n }\n\n configureSessionTracking() {\n let sessionInfo = this.getSessionInfo();\n if (this.isPersistenceEnabledForStorageEntry('sessionInfo')) {\n const configuredSessionTrackingInfo = this.getConfiguredSessionTrackingInfo();\n const initialSessionInfo = sessionInfo ?? defaultSessionConfiguration;\n sessionInfo = {\n ...initialSessionInfo,\n ...configuredSessionTrackingInfo,\n autoTrack:\n configuredSessionTrackingInfo.autoTrack && initialSessionInfo.manualTrack !== true,\n };\n }\n\n state.session.sessionInfo.value = this.isPersistenceEnabledForStorageEntry('sessionInfo')\n ? (sessionInfo as SessionInfo)\n : DEFAULT_USER_SESSION_VALUES.sessionInfo;\n\n // If auto session tracking is enabled start the session tracking\n if (state.session.sessionInfo.value.autoTrack) {\n this.startOrRenewAutoTracking(state.session.sessionInfo.value);\n }\n }\n\n setInitialReferrerInfo() {\n const persistedInitialReferrer = this.getInitialReferrer();\n const persistedInitialReferringDomain = this.getInitialReferringDomain();\n\n if (persistedInitialReferrer && persistedInitialReferringDomain) {\n this.setInitialReferrer(persistedInitialReferrer);\n this.setInitialReferringDomain(persistedInitialReferringDomain);\n } else {\n const initialReferrer = persistedInitialReferrer || getReferrer();\n this.setInitialReferrer(initialReferrer);\n this.setInitialReferringDomain(getReferringDomain(initialReferrer));\n }\n }\n\n isPersistenceEnabledForStorageEntry(entryName: UserSessionKey): boolean {\n return isStorageTypeValidForStoringData(\n state.storage.entries.value[entryName]?.type as StorageType,\n );\n }\n\n migrateDataFromPreviousStorage() {\n const entries = state.storage.entries.value as StorageEntries;\n const storageTypesForMigration = [COOKIE_STORAGE, LOCAL_STORAGE, SESSION_STORAGE];\n Object.keys(entries).forEach(entry => {\n const key = entry as UserSessionStorageKeysType;\n const currentStorage = entries[key]?.type as StorageType;\n const curStore = this.storeManager?.getStore(\n storageClientDataStoreNameMap[currentStorage] as string,\n );\n if (curStore) {\n storageTypesForMigration.forEach(storage => {\n const store = this.storeManager?.getStore(\n storageClientDataStoreNameMap[storage] as string,\n );\n if (store && storage !== currentStorage) {\n const value = store.get(COOKIE_KEYS[key]);\n if (isDefinedNotNullAndNotEmptyString(value)) {\n curStore.set(COOKIE_KEYS[key], value);\n }\n\n store.remove(COOKIE_KEYS[key]);\n }\n });\n }\n });\n }\n\n migrateStorageIfNeeded() {\n if (!state.storage.migrate.value) {\n return;\n }\n\n const persistentStoreNames = [\n CLIENT_DATA_STORE_COOKIE,\n CLIENT_DATA_STORE_LS,\n CLIENT_DATA_STORE_SESSION,\n ];\n\n const stores: IStore[] = [];\n persistentStoreNames.forEach(storeName => {\n const store = this.storeManager?.getStore(storeName);\n if (store) {\n stores.push(store);\n }\n });\n\n Object.keys(COOKIE_KEYS).forEach(storageKey => {\n const storageEntry = COOKIE_KEYS[storageKey as UserSessionStorageKeysType];\n stores.forEach(store => {\n const migratedVal = this.pluginsManager?.invokeSingle(\n 'storage.migrate',\n storageEntry,\n store.engine,\n this.errorHandler,\n this.logger,\n );\n\n // Skip setting the value if it is null or undefined\n // as those values indicate there is no need for migration or\n // migration failed\n if (!isNullOrUndefined(migratedVal)) {\n store.set(storageEntry, migratedVal);\n }\n });\n });\n }\n\n getConfiguredSessionTrackingInfo(): SessionInfo {\n let autoTrack = state.loadOptions.value.sessions?.autoTrack !== false;\n\n // Do not validate any further if autoTrack is disabled\n if (!autoTrack) {\n return {\n autoTrack,\n };\n }\n\n let timeout: number;\n const configuredSessionTimeout = state.loadOptions.value.sessions?.timeout;\n if (!isPositiveInteger(configuredSessionTimeout)) {\n this.logger?.warn(\n TIMEOUT_NOT_NUMBER_WARNING(\n USER_SESSION_MANAGER,\n configuredSessionTimeout,\n DEFAULT_SESSION_TIMEOUT_MS,\n ),\n );\n timeout = DEFAULT_SESSION_TIMEOUT_MS;\n } else {\n timeout = configuredSessionTimeout as number;\n }\n\n if (timeout === 0) {\n this.logger?.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));\n autoTrack = false;\n }\n // In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning\n // and will proceed with it\n if (timeout > 0 && timeout < MIN_SESSION_TIMEOUT_MS) {\n this.logger?.warn(\n TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER, timeout, MIN_SESSION_TIMEOUT_MS),\n );\n }\n return { timeout, autoTrack };\n }\n\n /**\n * Handles error\n * @param error The error object\n */\n onError(error: unknown, customMessage?: string): void {\n if (this.errorHandler) {\n this.errorHandler.onError(error, USER_SESSION_MANAGER, customMessage);\n } else {\n throw error;\n }\n }\n\n /**\n * A function to encrypt the cookie value and return the encrypted data\n * @param cookiesData\n * @param store\n * @returns\n */\n getEncryptedCookieData(cookiesData: CookieData[], store?: IStore): EncryptedCookieData[] {\n const encryptedCookieData: EncryptedCookieData[] = [];\n cookiesData.forEach(cData => {\n const encryptedValue = store?.encrypt(\n stringifyWithoutCircular(cData.value, false, [], this.logger),\n );\n if (isDefinedAndNotNull(encryptedValue)) {\n encryptedCookieData.push({\n name: cData.name,\n value: encryptedValue,\n });\n }\n });\n return encryptedCookieData;\n }\n\n /**\n * A function that makes request to data service to set the cookie\n * @param encryptedCookieData\n * @param callback\n */\n makeRequestToSetCookie(\n encryptedCookieData: EncryptedCookieData[],\n callback: AsyncRequestCallback,\n ) {\n this.httpClient?.request({\n url: state.serverCookies.dataServiceUrl.value as string,\n options: {\n method: 'POST',\n body: stringifyWithoutCircular({\n reqType: 'setCookies',\n workspaceId: state.source.value?.workspaceId,\n data: {\n options: {\n maxAge: state.storage.cookie.value?.maxage,\n path: state.storage.cookie.value?.path,\n domain: state.storage.cookie.value?.domain,\n sameSite: state.storage.cookie.value?.samesite,\n secure: state.storage.cookie.value?.secure,\n expires: state.storage.cookie.value?.expires,\n },\n cookies: encryptedCookieData,\n },\n }) as string,\n sendRawData: true,\n withCredentials: true,\n },\n isRawResponse: true,\n callback,\n });\n }\n\n /**\n * A function to make an external request to set the cookie from server side\n * @param key cookie name\n * @param value encrypted cookie value\n */\n setServerSideCookies(cookiesData: CookieData[], cb?: CallbackFunction, store?: IStore): void {\n try {\n // encrypt cookies values\n const encryptedCookieData = this.getEncryptedCookieData(cookiesData, store);\n if (encryptedCookieData.length > 0) {\n // make request to data service to set the cookie from server side\n this.makeRequestToSetCookie(encryptedCookieData, (res, details) => {\n if (details?.response?.status === 200) {\n cookiesData.forEach(cData => {\n const cookieValue = store?.get(cData.name);\n const before = stringifyWithoutCircular(cData.value, false, []);\n const after = stringifyWithoutCircular(cookieValue, false, []);\n if (after !== before) {\n this.logger?.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name));\n if (cb) {\n cb(cData.name, cData.value);\n }\n }\n });\n } else {\n this.logger?.error(DATA_SERVER_REQUEST_FAIL_ERROR(details?.response?.status));\n cookiesData.forEach(each => {\n if (cb) {\n cb(each.name, each.value);\n }\n });\n }\n });\n }\n } catch (e) {\n this.onError(e, FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);\n cookiesData.forEach(each => {\n if (cb) {\n cb(each.name, each.value);\n }\n });\n }\n }\n\n /**\n * A function to sync values in storage\n * @param sessionKey\n * @param value\n */\n syncValueToStorage(\n sessionKey: UserSessionKey,\n value: Nullable | Nullable | undefined,\n ) {\n const entries = state.storage.entries.value;\n const storageType = entries[sessionKey]?.type as StorageType;\n if (isStorageTypeValidForStoringData(storageType)) {\n const curStore = this.storeManager?.getStore(\n storageClientDataStoreNameMap[storageType] as string,\n );\n const key = entries[sessionKey]?.key as string;\n if (value && (isString(value) || isNonEmptyObject(value))) {\n // if useServerSideCookies load option is set to true\n // set the cookie from server side\n if (\n state.serverCookies.isEnabledServerSideCookies.value &&\n storageType === COOKIE_STORAGE\n ) {\n if (this.serverSideCookieDebounceFuncs[sessionKey]) {\n (globalThis as typeof window).clearTimeout(\n this.serverSideCookieDebounceFuncs[sessionKey],\n );\n }\n\n this.serverSideCookieDebounceFuncs[sessionKey] = (globalThis as typeof window).setTimeout(\n () => {\n this.setServerSideCookies(\n [{ name: key, value }],\n (cookieName, cookieValue) => {\n curStore?.set(cookieName, cookieValue);\n },\n curStore,\n );\n },\n SERVER_SIDE_COOKIES_DEBOUNCE_TIME,\n );\n } else {\n curStore?.set(key, value);\n }\n } else {\n curStore?.remove(key);\n }\n }\n }\n\n /**\n * Function to update storage whenever state value changes\n */\n registerEffects() {\n // This will work as long as the user session entry key names are same as the state keys\n USER_SESSION_KEYS.forEach(sessionKey => {\n effect(() => {\n this.syncValueToStorage(sessionKey, state.session[sessionKey].value);\n });\n });\n }\n\n /**\n * Sets anonymous id in the following precedence:\n *\n * 1. anonymousId: Id directly provided to the function.\n * 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)\n * using parseLinker util.\n * 3. generateUUID: A new unique id is generated and assigned.\n */\n setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string) {\n let finalAnonymousId: string | undefined | null = anonymousId;\n if (this.isPersistenceEnabledForStorageEntry('anonymousId')) {\n if (!finalAnonymousId && rudderAmpLinkerParam) {\n const linkerPluginsResult = this.pluginsManager?.invokeSingle(\n 'userSession.anonymousIdGoogleLinker',\n rudderAmpLinkerParam,\n );\n finalAnonymousId = linkerPluginsResult;\n }\n finalAnonymousId = finalAnonymousId || generateAnonymousId();\n } else {\n finalAnonymousId = DEFAULT_USER_SESSION_VALUES.anonymousId;\n }\n\n state.session.anonymousId.value = finalAnonymousId;\n }\n\n /**\n * Fetches anonymousId\n * @param options option to fetch it from external source\n * @returns anonymousId\n */\n getAnonymousId(options?: AnonymousIdOptions): string {\n const storage: StorageType = state.storage.entries.value.anonymousId?.type as StorageType;\n // fetch the anonymousId from storage\n if (isStorageTypeValidForStoringData(storage)) {\n let persistedAnonymousId = this.getEntryValue('anonymousId');\n if (!persistedAnonymousId && options) {\n // fetch anonymousId from external source\n const autoCapturedAnonymousId = this.pluginsManager?.invokeSingle(\n 'storage.getAnonymousId',\n getStorageEngine,\n options,\n );\n persistedAnonymousId = autoCapturedAnonymousId;\n }\n state.session.anonymousId.value = persistedAnonymousId || generateAnonymousId();\n }\n return state.session.anonymousId.value as string;\n }\n\n getEntryValue(sessionKey: UserSessionKey) {\n const entries = state.storage.entries.value;\n const storageType = entries[sessionKey]?.type as StorageType;\n if (isStorageTypeValidForStoringData(storageType)) {\n const store = this.storeManager?.getStore(\n storageClientDataStoreNameMap[storageType] as string,\n );\n const storageKey = entries[sessionKey]?.key as string;\n return store?.get(storageKey) ?? null;\n }\n return null;\n }\n\n getExternalAnonymousIdByCookieName(key: string) {\n const storageEngine = getStorageEngine(COOKIE_STORAGE);\n if (storageEngine?.isEnabled) {\n return storageEngine.getItem(key) ?? null;\n }\n return null;\n }\n\n /**\n * Fetches User Id\n * @returns\n */\n getUserId(): Nullable {\n return this.getEntryValue('userId');\n }\n\n /**\n * Fetches User Traits\n * @returns\n */\n getUserTraits(): Nullable {\n return this.getEntryValue('userTraits');\n }\n\n /**\n * Fetches Group Id\n * @returns\n */\n getGroupId(): Nullable {\n return this.getEntryValue('groupId');\n }\n\n /**\n * Fetches Group Traits\n * @returns\n */\n getGroupTraits(): Nullable {\n return this.getEntryValue('groupTraits');\n }\n\n /**\n * Fetches Initial Referrer\n * @returns\n */\n getInitialReferrer(): Nullable {\n return this.getEntryValue('initialReferrer');\n }\n\n /**\n * Fetches Initial Referring domain\n * @returns\n */\n getInitialReferringDomain(): Nullable {\n return this.getEntryValue('initialReferringDomain');\n }\n\n /**\n * Fetches session tracking information from storage\n * @returns\n */\n getSessionInfo(): Nullable {\n return this.getEntryValue('sessionInfo');\n }\n\n /**\n * Fetches auth token from storage\n * @returns\n */\n getAuthToken(): Nullable {\n return this.getEntryValue('authToken');\n }\n\n /**\n * If session is active it returns the sessionId\n * @returns\n */\n getSessionId(): Nullable {\n const sessionInfo = this.getSessionInfo() ?? DEFAULT_USER_SESSION_VALUES.sessionInfo;\n if (\n (sessionInfo.autoTrack && !hasSessionExpired(sessionInfo.expiresAt)) ||\n sessionInfo.manualTrack\n ) {\n return sessionInfo.id ?? null;\n }\n return null;\n }\n\n /**\n * A function to keep the session information up to date in the state\n * before using it for building event payloads.\n */\n refreshSession(): void {\n let sessionInfo = this.getSessionInfo() ?? DEFAULT_USER_SESSION_VALUES.sessionInfo;\n if (sessionInfo.autoTrack || sessionInfo.manualTrack) {\n if (sessionInfo.autoTrack) {\n this.startOrRenewAutoTracking(sessionInfo);\n sessionInfo = state.session.sessionInfo.value;\n }\n\n // Note that if sessionStart is false, then it's an active session.\n // So, we needn't update the session info.\n //\n // For other scenarios,\n // 1. If sessionStart is undefined, then it's a new session.\n // Mark it as sessionStart.\n // 2. If sessionStart is true, then need to flip it for the future events.\n if (sessionInfo.sessionStart === undefined) {\n sessionInfo = {\n ...sessionInfo,\n sessionStart: true,\n };\n } else if (sessionInfo.sessionStart) {\n sessionInfo = {\n ...sessionInfo,\n sessionStart: false,\n };\n }\n }\n\n // Always write to state (in-turn to storage) to keep the session info up to date.\n state.session.sessionInfo.value = sessionInfo;\n\n if (state.lifecycle.status.value !== 'readyExecuted') {\n // Force update the storage as the 'effect' blocks are not getting triggered\n // when processing preload buffered requests\n this.syncValueToStorage('sessionInfo', sessionInfo);\n }\n }\n\n /**\n * Reset state values\n * @param resetAnonymousId\n * @param noNewSessionStart\n * @returns\n */\n reset(resetAnonymousId?: boolean, noNewSessionStart?: boolean) {\n const { session } = state;\n const { manualTrack, autoTrack } = session.sessionInfo.value;\n\n batch(() => {\n session.userId.value = DEFAULT_USER_SESSION_VALUES.userId;\n session.userTraits.value = DEFAULT_USER_SESSION_VALUES.userTraits;\n session.groupId.value = DEFAULT_USER_SESSION_VALUES.groupId;\n session.groupTraits.value = DEFAULT_USER_SESSION_VALUES.groupTraits;\n session.authToken.value = DEFAULT_USER_SESSION_VALUES.authToken;\n\n if (resetAnonymousId) {\n // This will generate a new anonymous ID\n this.setAnonymousId();\n }\n\n if (noNewSessionStart) {\n return;\n }\n\n if (autoTrack) {\n session.sessionInfo.value = DEFAULT_USER_SESSION_VALUES.sessionInfo;\n this.startOrRenewAutoTracking(session.sessionInfo.value);\n } else if (manualTrack) {\n this.startManualTrackingInternal();\n }\n });\n }\n\n /**\n * Set user Id\n * @param userId\n */\n setUserId(userId?: Nullable) {\n state.session.userId.value =\n this.isPersistenceEnabledForStorageEntry('userId') && userId\n ? userId\n : DEFAULT_USER_SESSION_VALUES.userId;\n }\n\n /**\n * Set user traits\n * @param traits\n */\n setUserTraits(traits?: Nullable) {\n state.session.userTraits.value =\n this.isPersistenceEnabledForStorageEntry('userTraits') && traits\n ? mergeDeepRight(\n state.session.userTraits.value ?? DEFAULT_USER_SESSION_VALUES.userTraits,\n traits,\n )\n : DEFAULT_USER_SESSION_VALUES.userTraits;\n }\n\n /**\n * Set group Id\n * @param groupId\n */\n setGroupId(groupId?: Nullable) {\n state.session.groupId.value =\n this.isPersistenceEnabledForStorageEntry('groupId') && groupId\n ? groupId\n : DEFAULT_USER_SESSION_VALUES.groupId;\n }\n\n /**\n * Set group traits\n * @param traits\n */\n setGroupTraits(traits?: Nullable) {\n state.session.groupTraits.value =\n this.isPersistenceEnabledForStorageEntry('groupTraits') && traits\n ? mergeDeepRight(\n state.session.groupTraits.value ?? DEFAULT_USER_SESSION_VALUES.groupTraits,\n traits,\n )\n : DEFAULT_USER_SESSION_VALUES.groupTraits;\n }\n\n /**\n * Set initial referrer\n * @param referrer\n */\n setInitialReferrer(referrer?: string) {\n state.session.initialReferrer.value =\n this.isPersistenceEnabledForStorageEntry('initialReferrer') && referrer\n ? referrer\n : DEFAULT_USER_SESSION_VALUES.initialReferrer;\n }\n\n /**\n * Set initial referring domain\n * @param {String} referringDomain\n */\n setInitialReferringDomain(referringDomain?: string) {\n state.session.initialReferringDomain.value =\n this.isPersistenceEnabledForStorageEntry('initialReferringDomain') && referringDomain\n ? referringDomain\n : DEFAULT_USER_SESSION_VALUES.initialReferringDomain;\n }\n\n /**\n * A function to check for existing session details and depending on that create a new session\n */\n startOrRenewAutoTracking(sessionInfo: SessionInfo) {\n if (hasSessionExpired(sessionInfo.expiresAt)) {\n state.session.sessionInfo.value = generateAutoTrackingSession(sessionInfo.timeout);\n } else {\n const timestamp = Date.now();\n const timeout = sessionInfo.timeout as number;\n state.session.sessionInfo.value = mergeDeepRight(sessionInfo, {\n expiresAt: timestamp + timeout, // set the expiry time of the session\n });\n }\n }\n\n /**\n * A function method to start a manual session\n * @param {number} id session identifier\n * @returns\n */\n start(id?: number) {\n state.session.sessionInfo.value = generateManualTrackingSession(id, this.logger);\n }\n\n /**\n * An internal function to start manual session\n */\n startManualTrackingInternal() {\n this.start(Date.now());\n }\n\n /**\n * A public method to end an ongoing session.\n */\n end() {\n state.session.sessionInfo.value = DEFAULT_USER_SESSION_VALUES.sessionInfo;\n }\n\n /**\n * Set auth token\n * @param userId\n */\n setAuthToken(token: Nullable) {\n state.session.authToken.value =\n this.isPersistenceEnabledForStorageEntry('authToken') && token\n ? token\n : DEFAULT_USER_SESSION_VALUES.authToken;\n }\n}\n\nexport { UserSessionManager };\n","import type { PluginName } from '@rudderstack/analytics-js-common/types/PluginsManager';\n\n/**\n * Plugins to be loaded in the plugins loadOption is not defined\n */\nconst defaultOptionalPluginsList: PluginName[] = [\n 'BeaconQueue',\n 'Bugsnag',\n 'CustomConsentManager',\n 'DeviceModeDestinations',\n 'DeviceModeTransformation',\n 'ErrorReporting',\n 'ExternalAnonymousId',\n 'GoogleLinker',\n 'KetchConsentManager',\n 'NativeDestinationQueue',\n 'OneTrustConsentManager',\n 'StorageEncryption',\n 'StorageEncryptionLegacy',\n 'StorageMigrator',\n 'XhrQueue',\n 'FetchQueue',\n];\n\nexport { defaultOptionalPluginsList };\n","const DATA_PLANE_QUEUE_EXT_POINT_PREFIX = 'dataplaneEventsQueue';\nconst DESTINATIONS_QUEUE_EXT_POINT_PREFIX = 'destinationsEventsQueue';\nconst DMT_EXT_POINT_PREFIX = 'transformEvent';\n\nexport {\n DATA_PLANE_QUEUE_EXT_POINT_PREFIX,\n DESTINATIONS_QUEUE_EXT_POINT_PREFIX,\n DMT_EXT_POINT_PREFIX,\n};\n","import type { IntegrationOpts } from '@rudderstack/analytics-js-common/types/Integration';\nimport { clone } from 'ramda';\nimport { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object';\nimport type { ApplicationState } from '@rudderstack/analytics-js-common/types/ApplicationState';\nimport { DEFAULT_INTEGRATIONS_CONFIG } from '@rudderstack/analytics-js-common/constants/integrationsConfig';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\n\n/**\n * Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config\n * @param eventIntgConfig User supplied integrations config at event level\n * @param destinationsIntgConfig Cumulative integrations config from all destinations\n * @returns Filtered user supplied integrations config\n */\nconst getOverriddenIntegrationOptions = (\n eventIntgConfig: IntegrationOpts,\n destinationsIntgConfig: IntegrationOpts,\n): IntegrationOpts =>\n Object.keys(eventIntgConfig)\n .filter(intgName => eventIntgConfig[intgName] !== true || !destinationsIntgConfig[intgName])\n .reduce((obj: IntegrationOpts, key: string) => {\n const retVal = clone(obj);\n retVal[key] = eventIntgConfig[key];\n return retVal;\n }, {});\n\n/**\n * Returns the event object with final integrations config\n * @param event RudderEvent object\n * @param state Application state\n * @returns Mutated event with final integrations config\n */\nconst getFinalEvent = (event: RudderEvent, state: ApplicationState) => {\n const finalEvent = clone(event);\n // Merge the destination specific integrations config with the event's integrations config\n // In general, the preference is given to the event's integrations config\n const eventIntgConfig = event.integrations ?? DEFAULT_INTEGRATIONS_CONFIG;\n const destinationsIntgConfig = state.nativeDestinations.integrationsConfig.value;\n const overriddenIntgOpts = getOverriddenIntegrationOptions(\n eventIntgConfig,\n destinationsIntgConfig,\n );\n\n finalEvent.integrations = mergeDeepRight(destinationsIntgConfig, overriddenIntgOpts);\n return finalEvent;\n};\n\nconst shouldBufferEventsForPreConsent = (state: ApplicationState): boolean =>\n state.consents.preConsent.value.enabled &&\n state.consents.preConsent.value.events?.delivery === 'buffer' &&\n (state.consents.preConsent.value.storage?.strategy === 'session' ||\n state.consents.preConsent.value.storage?.strategy === 'none');\n\nexport { getOverriddenIntegrationOptions, getFinalEvent, shouldBufferEventsForPreConsent };\n","import { clone } from 'ramda';\nimport { effect } from '@preact/signals-core';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { IPluginsManager } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { RudderEvent } from '@rudderstack/analytics-js-common/types/Event';\nimport type { ApiCallback } from '@rudderstack/analytics-js-common/types/EventApi';\nimport { isHybridModeDestination } from '@rudderstack/analytics-js-common/utilities/destinations';\nimport { EVENT_REPOSITORY } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport type { Destination } from '@rudderstack/analytics-js-common/types/Destination';\nimport {\n API_CALLBACK_INVOKE_ERROR,\n DATAPLANE_PLUGIN_ENQUEUE_ERROR,\n DATAPLANE_PLUGIN_INITIALIZE_ERROR,\n DMT_PLUGIN_INITIALIZE_ERROR,\n NATIVE_DEST_PLUGIN_ENQUEUE_ERROR,\n NATIVE_DEST_PLUGIN_INITIALIZE_ERROR,\n} from '../../constants/logMessages';\nimport { HttpClient } from '../../services/HttpClient';\nimport { state } from '../../state';\nimport type { IEventRepository } from './types';\nimport {\n DATA_PLANE_QUEUE_EXT_POINT_PREFIX,\n DESTINATIONS_QUEUE_EXT_POINT_PREFIX,\n DMT_EXT_POINT_PREFIX,\n} from './constants';\nimport { getFinalEvent, shouldBufferEventsForPreConsent } from './utils';\n\n/**\n * Event repository class responsible for queuing events for further processing and delivery\n */\nclass EventRepository implements IEventRepository {\n errorHandler?: IErrorHandler;\n logger?: ILogger;\n pluginsManager: IPluginsManager;\n httpClient: IHttpClient;\n storeManager: IStoreManager;\n dataplaneEventsQueue: any;\n destinationsEventsQueue: any;\n dmtEventsQueue: any;\n\n /**\n *\n * @param pluginsManager Plugins manager instance\n * @param storeManager Store Manager instance\n * @param errorHandler Error handler object\n * @param logger Logger object\n */\n constructor(\n pluginsManager: IPluginsManager,\n storeManager: IStoreManager,\n errorHandler?: IErrorHandler,\n logger?: ILogger,\n ) {\n this.pluginsManager = pluginsManager;\n this.errorHandler = errorHandler;\n this.logger = logger;\n this.httpClient = new HttpClient('fetch', errorHandler, logger);\n this.storeManager = storeManager;\n this.onError = this.onError.bind(this);\n }\n\n /**\n * Initializes the event repository\n */\n init(): void {\n try {\n this.dataplaneEventsQueue = this.pluginsManager.invokeSingle(\n `${DATA_PLANE_QUEUE_EXT_POINT_PREFIX}.init`,\n state,\n this.httpClient,\n this.storeManager,\n this.errorHandler,\n this.logger,\n );\n } catch (e) {\n this.onError(e, DATAPLANE_PLUGIN_INITIALIZE_ERROR);\n }\n\n try {\n this.dmtEventsQueue = this.pluginsManager.invokeSingle(\n `${DMT_EXT_POINT_PREFIX}.init`,\n state,\n this.pluginsManager,\n this.httpClient,\n this.storeManager,\n this.errorHandler,\n this.logger,\n );\n } catch (e) {\n this.onError(e, DMT_PLUGIN_INITIALIZE_ERROR);\n }\n\n try {\n this.destinationsEventsQueue = this.pluginsManager.invokeSingle(\n `${DESTINATIONS_QUEUE_EXT_POINT_PREFIX}.init`,\n state,\n this.pluginsManager,\n this.storeManager,\n this.dmtEventsQueue,\n this.errorHandler,\n this.logger,\n );\n } catch (e) {\n this.onError(e, NATIVE_DEST_PLUGIN_INITIALIZE_ERROR);\n }\n\n // Start the queue once the client destinations are ready\n effect(() => {\n if (state.nativeDestinations.clientDestinationsReady.value === true) {\n this.destinationsEventsQueue?.start();\n this.dmtEventsQueue?.start();\n }\n });\n\n const bufferEventsBeforeConsent = shouldBufferEventsForPreConsent(state);\n\n // Start the queue processing only when the destinations are ready or hybrid mode destinations exist\n // However, events will be enqueued for now.\n // At the time of processing the events, the integrations config data from destinations\n // is merged into the event object\n let timeoutId: number;\n effect(() => {\n const shouldBufferDpEvents =\n state.loadOptions.value.bufferDataPlaneEventsUntilReady === true &&\n state.nativeDestinations.clientDestinationsReady.value === false;\n\n const hybridDestExist = state.nativeDestinations.activeDestinations.value.some(\n (dest: Destination) => isHybridModeDestination(dest),\n );\n\n if (\n (hybridDestExist === false || shouldBufferDpEvents === false) &&\n !bufferEventsBeforeConsent &&\n this.dataplaneEventsQueue?.scheduleTimeoutActive !== true\n ) {\n (globalThis as typeof window).clearTimeout(timeoutId);\n this.dataplaneEventsQueue?.start();\n }\n });\n\n // Force start the data plane events queue processing after a timeout\n if (state.loadOptions.value.bufferDataPlaneEventsUntilReady === true) {\n timeoutId = (globalThis as typeof window).setTimeout(() => {\n if (this.dataplaneEventsQueue?.scheduleTimeoutActive !== true) {\n this.dataplaneEventsQueue?.start();\n }\n }, state.loadOptions.value.dataPlaneEventsBufferTimeout);\n }\n }\n\n resume() {\n if (this.dataplaneEventsQueue?.scheduleTimeoutActive !== true) {\n if (state.consents.postConsent.value.discardPreConsentEvents) {\n this.dataplaneEventsQueue?.clear();\n this.destinationsEventsQueue?.clear();\n }\n\n this.dataplaneEventsQueue?.start();\n }\n }\n\n /**\n * Enqueues the event for processing\n * @param event RudderEvent object\n * @param callback API callback function\n */\n enqueue(event: RudderEvent, callback?: ApiCallback): void {\n let dpQEvent;\n try {\n dpQEvent = getFinalEvent(event, state);\n this.pluginsManager.invokeSingle(\n `${DATA_PLANE_QUEUE_EXT_POINT_PREFIX}.enqueue`,\n state,\n this.dataplaneEventsQueue,\n dpQEvent,\n this.errorHandler,\n this.logger,\n );\n } catch (e) {\n this.onError(e, DATAPLANE_PLUGIN_ENQUEUE_ERROR);\n }\n\n try {\n const dQEvent = clone(event);\n this.pluginsManager.invokeSingle(\n `${DESTINATIONS_QUEUE_EXT_POINT_PREFIX}.enqueue`,\n state,\n this.destinationsEventsQueue,\n dQEvent,\n this.errorHandler,\n this.logger,\n );\n } catch (e) {\n this.onError(e, NATIVE_DEST_PLUGIN_ENQUEUE_ERROR);\n }\n\n // Invoke the callback if it exists\n try {\n // Using the event sent to the data plane queue here\n // to ensure the mutated (if any) event is sent to the callback\n callback?.(dpQEvent);\n } catch (error) {\n this.onError(error, API_CALLBACK_INVOKE_ERROR);\n }\n }\n\n /**\n * Handles error\n * @param error The error object\n * @param customMessage a message\n * @param shouldAlwaysThrow if it should throw or use logger\n */\n onError(error: unknown, customMessage?: string, shouldAlwaysThrow?: boolean): void {\n if (this.errorHandler) {\n this.errorHandler.onError(error, EVENT_REPOSITORY, customMessage, shouldAlwaysThrow);\n } else {\n throw error;\n }\n }\n}\n\nexport { EventRepository };\n","const dispatchSDKEvent = (event: string): void => {\n const customEvent = new CustomEvent(event, {\n detail: { analyticsInstance: (globalThis as typeof window).rudderanalytics },\n bubbles: true,\n cancelable: true,\n composed: true,\n });\n\n (globalThis as typeof window).document.dispatchEvent(customEvent);\n};\n\nexport { dispatchSDKEvent };\n","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { ExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader';\nimport { batch, effect } from '@preact/signals-core';\nimport { isFunction, isNull } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { IHttpClient } from '@rudderstack/analytics-js-common/types/HttpClient';\nimport { clone } from 'ramda';\nimport type { ILogger } from '@rudderstack/analytics-js-common/types/Logger';\nimport type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler';\nimport type { IExternalSrcLoader } from '@rudderstack/analytics-js-common/services/ExternalSrcLoader/types';\nimport type { IStoreManager } from '@rudderstack/analytics-js-common/types/Store';\nimport type { IPluginsManager } from '@rudderstack/analytics-js-common/types/PluginsManager';\nimport { getMutatedError } from '@rudderstack/analytics-js-common/utilities/errors';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport type {\n AnonymousIdOptions,\n ConsentOptions,\n LoadOptions,\n} from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { ApiCallback } from '@rudderstack/analytics-js-common/types/EventApi';\nimport { isObjectAndNotNull } from '@rudderstack/analytics-js-common/utilities/object';\nimport {\n ANALYTICS_CORE,\n READY_API,\n} from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport {\n pageArgumentsToCallOptions,\n type AliasCallOptions,\n type GroupCallOptions,\n type IdentifyCallOptions,\n type PageCallOptions,\n type TrackCallOptions,\n trackArgumentsToCallOptions,\n} from '@rudderstack/analytics-js-common/utilities/eventMethodOverloads';\nimport { BufferQueue } from '@rudderstack/analytics-js-common/services/BufferQueue/BufferQueue';\nimport { defaultLogger } from '../../services/Logger';\nimport { defaultErrorHandler } from '../../services/ErrorHandler';\nimport { defaultPluginEngine } from '../../services/PluginEngine';\nimport { PluginsManager } from '../pluginsManager';\nimport { defaultHttpClient } from '../../services/HttpClient';\nimport { type Store, StoreManager } from '../../services/StoreManager';\nimport { state } from '../../state';\nimport { ConfigManager } from '../configManager/ConfigManager';\nimport type { ICapabilitiesManager } from '../capabilitiesManager/types';\nimport { CapabilitiesManager } from '../capabilitiesManager';\nimport type { IEventManager } from '../eventManager/types';\nimport { EventManager } from '../eventManager';\nimport { UserSessionManager } from '../userSessionManager/UserSessionManager';\nimport type { IUserSessionManager } from '../userSessionManager/types';\nimport type { IConfigManager } from '../configManager/types';\nimport { setExposedGlobal } from '../utilities/globals';\nimport { normalizeLoadOptions } from '../utilities/loadOptions';\nimport { consumePreloadBufferedEvent, retrievePreloadBufferEvents } from '../preloadBuffer';\nimport type { PreloadedEventCall } from '../preloadBuffer/types';\nimport { EventRepository } from '../eventRepository';\nimport type { IEventRepository } from '../eventRepository/types';\nimport {\n ADBLOCK_PAGE_CATEGORY,\n ADBLOCK_PAGE_NAME,\n ADBLOCK_PAGE_PATH,\n CONSENT_TRACK_EVENT_NAME,\n} from '../../constants/app';\nimport { READY_API_CALLBACK_ERROR, READY_CALLBACK_INVOKE_ERROR } from '../../constants/logMessages';\nimport type { IAnalytics } from './IAnalytics';\nimport { getConsentManagementData, getValidPostConsentOptions } from '../utilities/consent';\nimport { dispatchSDKEvent } from './utilities';\n\n/*\n * Analytics class with lifecycle based on state ad user triggered events\n */\nclass Analytics implements IAnalytics {\n preloadBuffer: BufferQueue;\n initialized: boolean;\n logger: ILogger;\n errorHandler: IErrorHandler;\n httpClient: IHttpClient;\n externalSrcLoader: IExternalSrcLoader;\n capabilitiesManager: ICapabilitiesManager;\n pluginsManager?: IPluginsManager;\n storeManager?: IStoreManager;\n configManager?: IConfigManager;\n eventRepository?: IEventRepository;\n eventManager?: IEventManager;\n userSessionManager?: IUserSessionManager;\n clientDataStore?: Store;\n\n /**\n * Initialize services and components or use default ones if singletons\n */\n constructor() {\n this.preloadBuffer = new BufferQueue();\n this.initialized = false;\n this.errorHandler = defaultErrorHandler;\n this.logger = defaultLogger;\n this.externalSrcLoader = new ExternalSrcLoader(this.errorHandler, this.logger);\n this.capabilitiesManager = new CapabilitiesManager(this.errorHandler, this.logger);\n this.httpClient = defaultHttpClient;\n }\n\n /**\n * Start application lifecycle if not already started\n */\n load(\n writeKey: string,\n dataPlaneUrl?: string | Partial,\n loadOptions: Partial = {},\n ) {\n if (state.lifecycle.status.value) {\n return;\n }\n\n let clonedDataPlaneUrl = clone(dataPlaneUrl);\n let clonedLoadOptions = clone(loadOptions);\n\n // dataPlaneUrl is not provided\n if (isObjectAndNotNull(dataPlaneUrl)) {\n clonedLoadOptions = dataPlaneUrl;\n clonedDataPlaneUrl = undefined;\n }\n\n // Set initial state values\n batch(() => {\n state.lifecycle.writeKey.value = writeKey;\n state.lifecycle.dataPlaneUrl.value = clonedDataPlaneUrl as string | undefined;\n state.loadOptions.value = normalizeLoadOptions(state.loadOptions.value, clonedLoadOptions);\n state.lifecycle.status.value = 'mounted';\n });\n\n // set log level as early as possible\n if (state.loadOptions.value.logLevel) {\n this.logger?.setMinLogLevel(state.loadOptions.value.logLevel);\n }\n\n // Expose state to global objects\n setExposedGlobal('state', state, writeKey);\n\n // Configure initial config of any services or components here\n\n // State application lifecycle\n this.startLifecycle();\n }\n\n // Start lifecycle methods\n /**\n * Orchestrate the lifecycle of the application phases/status\n */\n startLifecycle() {\n effect(() => {\n try {\n switch (state.lifecycle.status.value) {\n case 'mounted':\n this.onMounted();\n break;\n case 'browserCapabilitiesReady':\n this.onBrowserCapabilitiesReady();\n break;\n case 'configured':\n this.onConfigured();\n break;\n case 'pluginsLoading':\n break;\n case 'pluginsReady':\n this.onPluginsReady();\n break;\n case 'initialized':\n this.onInitialized();\n break;\n case 'loaded':\n this.onLoaded();\n break;\n case 'destinationsLoading':\n break;\n case 'destinationsReady':\n this.onDestinationsReady();\n break;\n case 'ready':\n this.onReady();\n break;\n case 'readyExecuted':\n default:\n break;\n }\n } catch (err) {\n const issue = 'Failed to load the SDK';\n this.errorHandler.onError(getMutatedError(err, issue), ANALYTICS_CORE);\n }\n });\n }\n\n onBrowserCapabilitiesReady() {\n // initialize the preloaded events enqueuing\n retrievePreloadBufferEvents(this);\n this.prepareInternalServices();\n this.loadConfig();\n }\n\n onLoaded() {\n this.processBufferedEvents();\n // Short-circuit the life cycle and move to the ready state if pre-consent behavior is enabled\n if (state.consents.preConsent.value.enabled === true) {\n state.lifecycle.status.value = 'ready';\n } else {\n this.loadDestinations();\n }\n }\n\n /**\n * Load browser polyfill if required\n */\n onMounted() {\n this.capabilitiesManager.init();\n }\n\n /**\n * Enqueue in SDK preload buffer events, used from preloadBuffer component\n */\n enqueuePreloadBufferEvents(bufferedEvents: PreloadedEventCall[]) {\n if (Array.isArray(bufferedEvents)) {\n bufferedEvents.forEach(bufferedEvent => this.preloadBuffer.enqueue(clone(bufferedEvent)));\n }\n }\n\n /**\n * Process the buffer preloaded events by passing their arguments to the respective facade methods\n */\n processDataInPreloadBuffer() {\n while (this.preloadBuffer.size() > 0) {\n const eventToProcess = this.preloadBuffer.dequeue();\n\n if (eventToProcess) {\n consumePreloadBufferedEvent([...eventToProcess], this);\n }\n }\n }\n\n prepareInternalServices() {\n this.pluginsManager = new PluginsManager(defaultPluginEngine, this.errorHandler, this.logger);\n this.storeManager = new StoreManager(this.pluginsManager, this.errorHandler, this.logger);\n this.configManager = new ConfigManager(this.httpClient, this.errorHandler, this.logger);\n this.userSessionManager = new UserSessionManager(\n this.errorHandler,\n this.logger,\n this.pluginsManager,\n this.storeManager,\n this.httpClient,\n );\n this.eventRepository = new EventRepository(\n this.pluginsManager,\n this.storeManager,\n this.errorHandler,\n this.logger,\n );\n this.eventManager = new EventManager(\n this.eventRepository,\n this.userSessionManager,\n this.errorHandler,\n this.logger,\n );\n }\n\n /**\n * Load configuration\n */\n loadConfig() {\n if (state.lifecycle.writeKey.value) {\n this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);\n }\n\n this.configManager?.init();\n }\n\n /**\n * Initialize the storage and event queue\n */\n onPluginsReady() {\n this.errorHandler.init(this.httpClient, this.externalSrcLoader);\n // Initialize storage\n this.storeManager?.init();\n this.userSessionManager?.init();\n\n // Initialize the appropriate consent manager plugin\n if (state.consents.enabled.value && !state.consents.initialized.value) {\n this.pluginsManager?.invokeSingle(`consentManager.init`, state, this.logger);\n\n if (state.consents.preConsent.value.enabled === false) {\n this.pluginsManager?.invokeSingle(\n `consentManager.updateConsentsInfo`,\n state,\n this.storeManager,\n this.logger,\n );\n }\n }\n\n // Initialize event manager\n this.eventManager?.init();\n\n // Mark the SDK as initialized\n state.lifecycle.status.value = 'initialized';\n }\n\n /**\n * Load plugins\n */\n onConfigured() {\n this.pluginsManager?.init();\n // TODO: are we going to enable custom plugins to be passed as load options?\n // registerCustomPlugins(state.loadOptions.value.customPlugins);\n }\n\n /**\n * Trigger onLoaded callback if any is provided in config & emit initialised event\n */\n onInitialized() {\n // Process any preloaded events\n this.processDataInPreloadBuffer();\n\n // TODO: we need to avoid passing the window object to the callback function\n // as this will prevent us from supporting multiple SDK instances in the same page\n // Execute onLoaded callback if provided in load options\n if (isFunction(state.loadOptions.value.onLoaded)) {\n state.loadOptions.value.onLoaded((globalThis as typeof window).rudderanalytics);\n }\n\n // Set lifecycle state\n batch(() => {\n state.lifecycle.loaded.value = true;\n state.lifecycle.status.value = 'loaded';\n });\n\n this.initialized = true;\n\n // Emit an event to use as substitute to the onLoaded callback\n dispatchSDKEvent('RSA_Initialised');\n }\n\n /**\n * Emit ready event\n */\n // eslint-disable-next-line class-methods-use-this\n onReady() {\n state.lifecycle.status.value = 'readyExecuted';\n state.eventBuffer.readyCallbacksArray.value.forEach((callback: ApiCallback) => {\n try {\n callback();\n } catch (err) {\n this.errorHandler.onError(err, ANALYTICS_CORE, READY_CALLBACK_INVOKE_ERROR);\n }\n });\n\n // Emit an event to use as substitute to the ready callback\n dispatchSDKEvent('RSA_Ready');\n }\n\n /**\n * Consume preloaded events buffer\n */\n processBufferedEvents() {\n // This logic has been intentionally implemented without a simple\n // for-loop as the individual events that are processed may\n // add more events to the buffer (this is needed for the consent API)\n let bufferedEvents = state.eventBuffer.toBeProcessedArray.value;\n while (bufferedEvents.length > 0) {\n const bufferedEvent = bufferedEvents.shift();\n state.eventBuffer.toBeProcessedArray.value = bufferedEvents;\n\n if (bufferedEvent) {\n const methodName = bufferedEvent[0];\n if (isFunction((this as any)[methodName])) {\n // Send additional arg 'true' to indicate that this is a buffered invocation\n (this as any)[methodName](...bufferedEvent.slice(1), true);\n }\n }\n\n bufferedEvents = state.eventBuffer.toBeProcessedArray.value;\n }\n }\n\n /**\n * Load device mode destinations\n */\n loadDestinations() {\n if (state.nativeDestinations.clientDestinationsReady.value) {\n return;\n }\n\n // Set in state the desired activeDestinations to inject in DOM\n this.pluginsManager?.invokeSingle(\n 'nativeDestinations.setActiveDestinations',\n state,\n this.pluginsManager,\n this.errorHandler,\n this.logger,\n );\n\n const totalDestinationsToLoad = state.nativeDestinations.activeDestinations.value.length;\n if (totalDestinationsToLoad === 0) {\n state.lifecycle.status.value = 'destinationsReady';\n return;\n }\n\n // Start loading native integration scripts and create instances\n state.lifecycle.status.value = 'destinationsLoading';\n this.pluginsManager?.invokeSingle(\n 'nativeDestinations.load',\n state,\n this.externalSrcLoader,\n this.errorHandler,\n this.logger,\n );\n\n // Progress to next lifecycle phase if all native destinations are initialized or failed\n effect(() => {\n const areAllDestinationsReady =\n totalDestinationsToLoad === 0 ||\n state.nativeDestinations.initializedDestinations.value.length +\n state.nativeDestinations.failedDestinations.value.length ===\n totalDestinationsToLoad;\n\n if (areAllDestinationsReady) {\n batch(() => {\n state.lifecycle.status.value = 'destinationsReady';\n state.nativeDestinations.clientDestinationsReady.value = true;\n });\n }\n });\n }\n\n /**\n * Move to the ready state\n */\n // eslint-disable-next-line class-methods-use-this\n onDestinationsReady() {\n // May be do any destination specific actions here\n\n // Mark the ready status if not already done\n if (state.lifecycle.status.value !== 'ready') {\n state.lifecycle.status.value = 'ready';\n }\n }\n // End lifecycle methods\n\n // Start consumer exposed methods\n ready(callback: ApiCallback, isBufferedInvocation = false) {\n const type = 'ready';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, callback],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);\n\n if (!isFunction(callback)) {\n this.logger.error(READY_API_CALLBACK_ERROR(READY_API));\n return;\n }\n\n /**\n * If destinations are loaded or no integration is available for loading\n * execute the callback immediately else push the callbacks to a queue that\n * will be executed after loading completes\n */\n if (state.lifecycle.status.value === 'readyExecuted') {\n try {\n callback();\n } catch (err) {\n this.errorHandler.onError(err, ANALYTICS_CORE, READY_CALLBACK_INVOKE_ERROR);\n }\n } else {\n state.eventBuffer.readyCallbacksArray.value = [\n ...state.eventBuffer.readyCallbacksArray.value,\n callback,\n ];\n }\n }\n\n page(payload: PageCallOptions, isBufferedInvocation = false) {\n const type = 'page';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, payload],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} event`);\n state.metrics.triggered.value += 1;\n\n this.eventManager?.addEvent({\n type: 'page',\n category: payload.category,\n name: payload.name,\n properties: payload.properties,\n options: payload.options,\n callback: payload.callback,\n });\n\n // TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.\n\n // Send automatic ad blocked page event if ad-blockers are detected on the page\n // Check page category to avoid infinite loop\n if (\n state.capabilities.isAdBlocked.value === true &&\n payload.category !== ADBLOCK_PAGE_CATEGORY\n ) {\n this.page(\n pageArgumentsToCallOptions(\n ADBLOCK_PAGE_CATEGORY,\n ADBLOCK_PAGE_NAME,\n {\n // 'title' is intentionally omitted as it does not make sense\n // in v3 implementation\n path: ADBLOCK_PAGE_PATH,\n },\n state.loadOptions.value.sendAdblockPageOptions,\n ),\n );\n }\n }\n\n track(payload: TrackCallOptions, isBufferedInvocation = false) {\n const type = 'track';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, payload],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} event`);\n state.metrics.triggered.value += 1;\n\n this.eventManager?.addEvent({\n type,\n name: payload.name || undefined,\n properties: payload.properties,\n options: payload.options,\n callback: payload.callback,\n });\n }\n\n identify(payload: IdentifyCallOptions, isBufferedInvocation = false) {\n const type = 'identify';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, payload],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} event`);\n state.metrics.triggered.value += 1;\n\n const shouldResetSession = Boolean(\n payload.userId && state.session.userId.value && payload.userId !== state.session.userId.value,\n );\n\n if (shouldResetSession) {\n this.reset();\n }\n\n // `null` value indicates that previous user ID needs to be retained\n if (!isNull(payload.userId)) {\n this.userSessionManager?.setUserId(payload.userId);\n }\n this.userSessionManager?.setUserTraits(payload.traits);\n\n this.eventManager?.addEvent({\n type,\n userId: payload.userId,\n traits: payload.traits,\n options: payload.options,\n callback: payload.callback,\n });\n }\n\n alias(payload: AliasCallOptions, isBufferedInvocation = false) {\n const type = 'alias';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, payload],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} event`);\n state.metrics.triggered.value += 1;\n\n const previousId =\n payload.from ??\n this.userSessionManager?.getUserId() ??\n this.userSessionManager?.getAnonymousId();\n\n this.eventManager?.addEvent({\n type,\n to: payload.to,\n from: previousId,\n options: payload.options,\n callback: payload.callback,\n });\n }\n\n group(payload: GroupCallOptions, isBufferedInvocation = false) {\n const type = 'group';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, payload],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} event`);\n state.metrics.triggered.value += 1;\n\n // `null` value indicates that previous group ID needs to be retained\n if (!isNull(payload.groupId)) {\n this.userSessionManager?.setGroupId(payload.groupId);\n }\n\n this.userSessionManager?.setGroupTraits(payload.traits);\n\n this.eventManager?.addEvent({\n type,\n groupId: payload.groupId,\n traits: payload.traits,\n options: payload.options,\n callback: payload.callback,\n });\n }\n\n reset(resetAnonymousId?: boolean, isBufferedInvocation = false) {\n const type = 'reset';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, resetAnonymousId],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(\n `New ${type} invocation, resetAnonymousId: ${resetAnonymousId}`,\n );\n this.userSessionManager?.reset(resetAnonymousId);\n }\n\n getAnonymousId(options?: AnonymousIdOptions): string | undefined {\n return this.userSessionManager?.getAnonymousId(options);\n }\n\n setAnonymousId(\n anonymousId?: string,\n rudderAmpLinkerParam?: string,\n isBufferedInvocation = false,\n ): void {\n const type = 'setAnonymousId';\n // Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, anonymousId, rudderAmpLinkerParam],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);\n this.userSessionManager?.setAnonymousId(anonymousId, rudderAmpLinkerParam);\n }\n\n // eslint-disable-next-line class-methods-use-this\n getUserId(): Nullable | undefined {\n return state.session.userId.value;\n }\n\n // eslint-disable-next-line class-methods-use-this\n getUserTraits(): Nullable | undefined {\n return state.session.userTraits.value;\n }\n\n // eslint-disable-next-line class-methods-use-this\n getGroupId(): Nullable | undefined {\n return state.session.groupId.value;\n }\n\n // eslint-disable-next-line class-methods-use-this\n getGroupTraits(): Nullable | undefined {\n return state.session.groupTraits.value;\n }\n\n startSession(sessionId?: number, isBufferedInvocation = false): void {\n const type = 'startSession';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, sessionId],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);\n this.userSessionManager?.start(sessionId);\n }\n\n endSession(isBufferedInvocation = false): void {\n const type = 'endSession';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New ${type} invocation`);\n this.userSessionManager?.end();\n }\n\n // eslint-disable-next-line class-methods-use-this\n getSessionId(): Nullable {\n const sessionId = this.userSessionManager?.getSessionId();\n return sessionId ?? null;\n }\n\n consent(options?: ConsentOptions, isBufferedInvocation = false) {\n const type = 'consent';\n\n if (!state.lifecycle.loaded.value) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n [type, options],\n ];\n return;\n }\n\n this.errorHandler.leaveBreadcrumb(`New consent invocation`);\n\n batch(() => {\n state.consents.preConsent.value = { ...state.consents.preConsent.value, enabled: false };\n state.consents.postConsent.value = getValidPostConsentOptions(options);\n\n const { initialized, consentsData } = getConsentManagementData(\n state.consents.postConsent.value.consentManagement,\n this.logger,\n );\n\n state.consents.initialized.value = initialized || state.consents.initialized.value;\n state.consents.data.value = consentsData;\n });\n\n // Update consents data in state\n if (state.consents.enabled.value && !state.consents.initialized.value) {\n this.pluginsManager?.invokeSingle(\n `consentManager.updateConsentsInfo`,\n state,\n this.storeManager,\n this.logger,\n );\n }\n\n // Re-init store manager\n this.storeManager?.initializeStorageState();\n\n // Re-init user session manager\n this.userSessionManager?.syncStorageDataToState();\n\n // Resume event manager to process the events to destinations\n this.eventManager?.resume();\n\n this.loadDestinations();\n\n this.sendTrackingEvents(isBufferedInvocation);\n }\n\n sendTrackingEvents(isBufferedInvocation: boolean) {\n // If isBufferedInvocation is true, then the tracking events will be added to the end of the\n // events buffer array so that any other preload events (mainly from query string API) will be processed first.\n if (state.consents.postConsent.value.trackConsent) {\n const trackOptions = trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME);\n if (isBufferedInvocation) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n ['track', trackOptions],\n ];\n } else {\n this.track(trackOptions);\n }\n }\n\n if (state.consents.postConsent.value.sendPageEvent) {\n const pageOptions = pageArgumentsToCallOptions();\n if (isBufferedInvocation) {\n state.eventBuffer.toBeProcessedArray.value = [\n ...state.eventBuffer.toBeProcessedArray.value,\n ['page', pageOptions],\n ];\n } else {\n this.page(pageOptions);\n }\n }\n }\n\n setAuthToken(token: string): void {\n this.userSessionManager?.setAuthToken(token);\n }\n // End consumer exposed methods\n}\n\nexport { Analytics };\n","import { clone } from 'ramda';\nimport {\n isObjectLiteralAndNotNull,\n mergeDeepRight,\n removeUndefinedAndNullValues,\n} from '@rudderstack/analytics-js-common/utilities/object';\nimport type {\n LoadOptions,\n UaChTrackLevel,\n} from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { StorageOpts, CookieSameSite } from '@rudderstack/analytics-js-common/types/Storage';\nimport { isDefined, isString } from '@rudderstack/analytics-js-common/utilities/checks';\nimport { defaultOptionalPluginsList } from '../pluginsManager/defaultPluginsList';\nimport { isNumber } from './number';\n\nconst normalizeLoadOptions = (\n loadOptionsFromState: LoadOptions,\n loadOptions: Partial,\n): LoadOptions => {\n // TODO: Maybe add warnings for invalid values\n const normalizedLoadOpts = clone(loadOptions);\n\n if (!isString(normalizedLoadOpts.setCookieDomain)) {\n delete normalizedLoadOpts.setCookieDomain;\n }\n\n const cookieSameSiteValues = ['Strict', 'Lax', 'None'];\n if (!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie as CookieSameSite)) {\n delete normalizedLoadOpts.sameSiteCookie;\n }\n\n normalizedLoadOpts.secureCookie = normalizedLoadOpts.secureCookie === true;\n\n const uaChTrackLevels = ['none', 'default', 'full'];\n if (!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel as UaChTrackLevel)) {\n delete normalizedLoadOpts.uaChTrackLevel;\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)) {\n delete normalizedLoadOpts.integrations;\n }\n\n normalizedLoadOpts.plugins = normalizedLoadOpts.plugins ?? defaultOptionalPluginsList;\n\n normalizedLoadOpts.useGlobalIntegrationsConfigInEvents =\n normalizedLoadOpts.useGlobalIntegrationsConfigInEvents === true;\n\n normalizedLoadOpts.bufferDataPlaneEventsUntilReady =\n normalizedLoadOpts.bufferDataPlaneEventsUntilReady === true;\n\n normalizedLoadOpts.sendAdblockPage = normalizedLoadOpts.sendAdblockPage === true;\n\n normalizedLoadOpts.useServerSideCookies = normalizedLoadOpts.useServerSideCookies === true;\n\n if (\n normalizedLoadOpts.dataServiceEndpoint &&\n typeof normalizedLoadOpts.dataServiceEndpoint !== 'string'\n ) {\n delete normalizedLoadOpts.dataServiceEndpoint;\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)) {\n delete normalizedLoadOpts.sendAdblockPageOptions;\n }\n\n if (!isDefined(normalizedLoadOpts.loadIntegration)) {\n delete normalizedLoadOpts.loadIntegration;\n } else {\n normalizedLoadOpts.loadIntegration = normalizedLoadOpts.loadIntegration === true;\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)) {\n delete normalizedLoadOpts.storage;\n } else {\n normalizedLoadOpts.storage = removeUndefinedAndNullValues(normalizedLoadOpts.storage);\n (normalizedLoadOpts.storage as StorageOpts).migrate =\n normalizedLoadOpts.storage?.migrate === true;\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)) {\n delete normalizedLoadOpts.beaconQueueOptions;\n } else {\n normalizedLoadOpts.beaconQueueOptions = removeUndefinedAndNullValues(\n normalizedLoadOpts.beaconQueueOptions,\n );\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)) {\n delete normalizedLoadOpts.destinationsQueueOptions;\n } else {\n normalizedLoadOpts.destinationsQueueOptions = removeUndefinedAndNullValues(\n normalizedLoadOpts.destinationsQueueOptions,\n );\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)) {\n delete normalizedLoadOpts.queueOptions;\n } else {\n normalizedLoadOpts.queueOptions = removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);\n }\n\n normalizedLoadOpts.lockIntegrationsVersion = normalizedLoadOpts.lockIntegrationsVersion === true;\n\n normalizedLoadOpts.lockPluginsVersion = normalizedLoadOpts.lockPluginsVersion === true;\n\n if (!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)) {\n delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.storage?.cookie)) {\n delete normalizedLoadOpts.storage?.cookie;\n } else {\n (normalizedLoadOpts.storage as StorageOpts).cookie = removeUndefinedAndNullValues(\n normalizedLoadOpts.storage?.cookie,\n );\n }\n\n if (!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)) {\n delete normalizedLoadOpts.preConsent;\n } else {\n normalizedLoadOpts.preConsent = removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);\n }\n\n const mergedLoadOptions: LoadOptions = mergeDeepRight(loadOptionsFromState, normalizedLoadOpts);\n\n return mergedLoadOptions;\n};\n\nexport { normalizeLoadOptions };\n","/* eslint-disable unicorn/prefer-export-from */\nimport { clone } from 'ramda';\nimport {\n aliasArgumentsToCallOptions,\n groupArgumentsToCallOptions,\n identifyArgumentsToCallOptions,\n pageArgumentsToCallOptions,\n trackArgumentsToCallOptions,\n} from '@rudderstack/analytics-js-common/utilities/eventMethodOverloads';\nimport type { IRudderAnalytics } from '@rudderstack/analytics-js-common/types/IRudderAnalytics';\nimport type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';\nimport type {\n AnonymousIdOptions,\n ConsentOptions,\n LoadOptions,\n} from '@rudderstack/analytics-js-common/types/LoadOptions';\nimport type { ApiCallback, ApiOptions } from '@rudderstack/analytics-js-common/types/EventApi';\nimport type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';\nimport { RS_APP } from '@rudderstack/analytics-js-common/constants/loggerContexts';\nimport { isString } from '@rudderstack/analytics-js-common/utilities/checks';\nimport type { IdentifyTraits } from '@rudderstack/analytics-js-common/types/traits';\nimport { GLOBAL_PRELOAD_BUFFER } from '../constants/app';\nimport {\n getPreloadedLoadEvent,\n promotePreloadedConsentEventsToTop,\n} from '../components/preloadBuffer';\nimport type { PreloadedEventCall } from '../components/preloadBuffer/types';\nimport { setExposedGlobal } from '../components/utilities/globals';\nimport type { IAnalytics } from '../components/core/IAnalytics';\nimport { Analytics } from '../components/core/Analytics';\nimport { defaultLogger } from '../services/Logger/Logger';\nimport { EMPTY_GROUP_CALL_ERROR, WRITE_KEY_NOT_A_STRING_ERROR } from '../constants/logMessages';\nimport { defaultErrorHandler } from '../services/ErrorHandler';\n\n// TODO: add analytics restart/reset mechanism\n\n/*\n * RudderAnalytics facade singleton that is exposed as global object and will:\n * expose overloaded methods\n * handle multiple Analytics instances\n * consume SDK preload event buffer\n */\nclass RudderAnalytics implements IRudderAnalytics {\n static globalSingleton: Nullable = null;\n analyticsInstances: Record = {};\n defaultAnalyticsKey = '';\n logger = defaultLogger;\n\n // Singleton with constructor bind methods\n constructor() {\n if (RudderAnalytics.globalSingleton) {\n // START-NO-SONAR-SCAN\n // eslint-disable-next-line no-constructor-return\n return RudderAnalytics.globalSingleton;\n // END-NO-SONAR-SCAN\n }\n defaultErrorHandler.attachErrorListeners();\n\n this.setDefaultInstanceKey = this.setDefaultInstanceKey.bind(this);\n this.getAnalyticsInstance = this.getAnalyticsInstance.bind(this);\n this.load = this.load.bind(this);\n this.ready = this.ready.bind(this);\n this.triggerBufferedLoadEvent = this.triggerBufferedLoadEvent.bind(this);\n this.page = this.page.bind(this);\n this.track = this.track.bind(this);\n this.identify = this.identify.bind(this);\n this.alias = this.alias.bind(this);\n this.group = this.group.bind(this);\n this.reset = this.reset.bind(this);\n this.getAnonymousId = this.getAnonymousId.bind(this);\n this.setAnonymousId = this.setAnonymousId.bind(this);\n this.getUserId = this.getUserId.bind(this);\n this.getUserTraits = this.getUserTraits.bind(this);\n this.getGroupId = this.getGroupId.bind(this);\n this.getGroupTraits = this.getGroupTraits.bind(this);\n this.startSession = this.startSession.bind(this);\n this.endSession = this.endSession.bind(this);\n this.getSessionId = this.getSessionId.bind(this);\n this.setAuthToken = this.setAuthToken.bind(this);\n this.consent = this.consent.bind(this);\n\n RudderAnalytics.globalSingleton = this;\n\n // start loading if a load event was buffered or wait for explicit load call\n this.triggerBufferedLoadEvent();\n\n // Assign to global \"rudderanalytics\" object after processing the preload buffer (if any exists)\n // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly\n (globalThis as typeof window).rudderanalytics = this;\n }\n\n /**\n * Set instance to use if no specific writeKey is provided in methods\n * automatically for the first created instance\n * TODO: to support multiple analytics instances in the near future\n */\n setDefaultInstanceKey(writeKey: string) {\n if (writeKey) {\n this.defaultAnalyticsKey = writeKey;\n }\n }\n\n /**\n * Retrieve an existing analytics instance\n */\n getAnalyticsInstance(writeKey?: string): IAnalytics {\n const instanceId = writeKey ?? this.defaultAnalyticsKey;\n\n const analyticsInstanceExists = Boolean(this.analyticsInstances[instanceId]);\n\n if (!analyticsInstanceExists) {\n this.analyticsInstances[instanceId] = new Analytics();\n }\n\n return this.analyticsInstances[instanceId] as IAnalytics;\n }\n\n /**\n * Create new analytics instance and trigger application lifecycle start\n */\n load(writeKey: string, dataPlaneUrl: string, loadOptions?: Partial) {\n if (!isString(writeKey)) {\n this.logger.error(WRITE_KEY_NOT_A_STRING_ERROR(RS_APP, writeKey));\n return;\n }\n\n if (this.analyticsInstances[writeKey]) {\n return;\n }\n\n this.setDefaultInstanceKey(writeKey);\n this.analyticsInstances[writeKey] = new Analytics();\n this.getAnalyticsInstance(writeKey).load(writeKey, dataPlaneUrl, loadOptions);\n }\n\n /**\n * Trigger load event in buffer queue if exists and stores the\n * remaining preloaded events array in global object\n */\n triggerBufferedLoadEvent() {\n const preloadedEventsArray = Array.isArray((globalThis as typeof window).rudderanalytics)\n ? ((globalThis as typeof window).rudderanalytics as unknown as PreloadedEventCall[])\n : ([] as PreloadedEventCall[]);\n\n // The array will be mutated in the below method\n promotePreloadedConsentEventsToTop(preloadedEventsArray);\n\n // Get any load method call that is buffered if any\n // BTW, load method is also removed from the array\n // So, the Analytics object can directly consume the remaining events\n const loadEvent: PreloadedEventCall = getPreloadedLoadEvent(preloadedEventsArray);\n\n // Set the final preloaded events array in global object\n setExposedGlobal(GLOBAL_PRELOAD_BUFFER, clone(preloadedEventsArray));\n\n // Process load method if present in the buffered requests\n if (loadEvent.length > 0) {\n // Remove the event name from the Buffered Event array and keep only arguments\n loadEvent.shift();\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this.load.apply(null, loadEvent);\n }\n }\n\n /**\n * Get ready callback arguments and forward to ready call\n */\n ready(callback: ApiCallback) {\n this.getAnalyticsInstance().ready(callback);\n }\n\n /**\n * Process page arguments and forward to page call\n */\n // These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics\n page(\n category: string,\n name: string,\n properties?: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n page(\n category: string,\n name: string,\n properties?: Nullable,\n callback?: ApiCallback,\n ): void;\n page(category: string, name: string, callback?: ApiCallback): void;\n page(\n name: string,\n properties?: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n page(name: string, properties?: Nullable, callback?: ApiCallback): void;\n page(name: string, callback?: ApiCallback): void;\n page(\n properties: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n page(properties: Nullable, callback?: ApiCallback): void;\n page(callback?: ApiCallback): void;\n page(\n category?: string | Nullable | ApiCallback,\n name?: string | Nullable | Nullable | ApiCallback,\n properties?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) {\n this.getAnalyticsInstance().page(\n pageArgumentsToCallOptions(category, name, properties, options, callback),\n );\n }\n\n /**\n * Process track arguments and forward to page call\n */\n // These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics\n track(\n event: string,\n properties?: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n track(event: string, properties?: Nullable, callback?: ApiCallback): void;\n track(event: string, callback?: ApiCallback): void;\n track(\n event: string,\n properties?: Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) {\n this.getAnalyticsInstance().track(\n trackArgumentsToCallOptions(event, properties, options, callback),\n );\n }\n\n /**\n * Process identify arguments and forward to page call\n */\n // These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics\n identify(\n userId: string,\n traits?: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n identify(userId: string, traits?: Nullable, callback?: ApiCallback): void;\n identify(userId: string, callback?: ApiCallback): void;\n identify(\n traits: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n identify(traits: Nullable, callback?: ApiCallback): void;\n identify(\n userId: string | number | Nullable,\n traits?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) {\n this.getAnalyticsInstance().identify(\n identifyArgumentsToCallOptions(userId, traits, options, callback),\n );\n }\n\n /**\n * Process alias arguments and forward to page call\n */\n // These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics\n alias(to: string, from?: string, options?: Nullable, callback?: ApiCallback): void;\n alias(to: string, from?: string, callback?: ApiCallback): void;\n alias(to: string, options?: Nullable, callback?: ApiCallback): void;\n alias(to: string, callback?: ApiCallback): void;\n alias(\n to: string,\n from?: string | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) {\n this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to, from, options, callback));\n }\n\n /**\n * Process group arguments and forward to page call\n */\n // These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics\n group(\n groupId: string,\n traits?: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n group(groupId: string, traits?: Nullable, callback?: ApiCallback): void;\n group(groupId: string, callback?: ApiCallback): void;\n group(\n traits: Nullable,\n options?: Nullable,\n callback?: ApiCallback,\n ): void;\n group(traits: Nullable, callback?: ApiCallback): void;\n group(\n groupId: string | number | Nullable,\n traits?: Nullable | Nullable | ApiCallback,\n options?: Nullable | ApiCallback,\n callback?: ApiCallback,\n ) {\n if (arguments.length === 0) {\n this.logger.error(EMPTY_GROUP_CALL_ERROR(RS_APP));\n return;\n }\n\n this.getAnalyticsInstance().group(\n groupArgumentsToCallOptions(groupId, traits, options, callback),\n );\n }\n\n reset(resetAnonymousId?: boolean) {\n this.getAnalyticsInstance().reset(resetAnonymousId);\n }\n\n getAnonymousId(options?: AnonymousIdOptions) {\n return this.getAnalyticsInstance().getAnonymousId(options);\n }\n\n setAnonymousId(anonymousId?: string, rudderAmpLinkerParam?: string) {\n this.getAnalyticsInstance().setAnonymousId(anonymousId, rudderAmpLinkerParam);\n }\n\n getUserId() {\n return this.getAnalyticsInstance().getUserId();\n }\n\n getUserTraits() {\n return this.getAnalyticsInstance().getUserTraits();\n }\n\n getGroupId() {\n return this.getAnalyticsInstance().getGroupId();\n }\n\n getGroupTraits() {\n return this.getAnalyticsInstance().getGroupTraits();\n }\n\n startSession(sessionId?: number) {\n return this.getAnalyticsInstance().startSession(sessionId);\n }\n\n endSession() {\n return this.getAnalyticsInstance().endSession();\n }\n\n getSessionId() {\n return this.getAnalyticsInstance().getSessionId();\n }\n\n setAuthToken(token: string) {\n return this.getAnalyticsInstance().setAuthToken(token);\n }\n\n consent(options?: ConsentOptions) {\n return this.getAnalyticsInstance().consent(options);\n }\n}\n\nexport { RudderAnalytics };\n","import { RudderAnalytics } from './app/RudderAnalytics';\n\n/*\n * Create new RudderAnalytics facade singleton\n */\nconst {\n setDefaultInstanceKey,\n getAnalyticsInstance,\n load,\n ready,\n page,\n track,\n identify,\n alias,\n group,\n reset,\n getAnonymousId,\n setAnonymousId,\n getUserId,\n getUserTraits,\n getGroupId,\n getGroupTraits,\n startSession,\n endSession,\n getSessionId,\n consent,\n setAuthToken,\n} = new RudderAnalytics();\n\n/*\n * Export as global object the RudderAnalytics facade singleton methods\n */\nexport {\n setDefaultInstanceKey,\n getAnalyticsInstance,\n load,\n ready,\n page,\n track,\n identify,\n alias,\n group,\n reset,\n getAnonymousId,\n setAnonymousId,\n getUserId,\n getUserTraits,\n getGroupId,\n getGroupTraits,\n startSession,\n endSession,\n getSessionId,\n consent,\n setAuthToken,\n};\n"],"names":["_isPlaceholder","a","_typeof","_curry1","fn","f1","arguments","length","apply","this","_curry2","f2","b","_b","_a","_curry3","f3","c","_c","_has","prop","obj","Object","prototype","hasOwnProperty","call","type","val","undefined","toString","slice","_isObject","x","Number","isInteger","n","_nth","offset","list","idx","_isString","charAt","_clone","value","deep","map","_ObjectMap","param","_isPrimitive","pattern","copy","copiedValue","cachedCopy","get","key","set","create","getPrototypeOf","Array","Date","valueOf","RegExp","source","flags","global","ignoreCase","multiline","sticky","unicode","dotAll","hashedKey","hash","bucket","push","join","p","i","element","clone","_path","pathAr","_isInteger","mergeWithKey","l","r","k","result","mergeDeepWithKey","lObj","rObj","lVal","rVal","mergeDeepWith","path","pickBy","test","isFunction","Boolean","constructor","isString","isNull","isUndefined","isNullOrUndefined","isDefined","isDefinedAndNotNull","isTypeOfError","Error","getValueByPath","keyPath","pathParts","split","isObjectAndNotNull","isArray","isObjectLiteralAndNotNull","mergeDeepRightObjectArrays","leftValue","rightValue","mergedArray","forEach","index","mergeDeepRight","leftObject","rightObject","isNonEmptyObject","keys","removeUndefinedValues","removeUndefinedAndNullValues","removeLeadingPeriod","replace","tryStringify","retVal","JSON","stringify","e","toBase64","bytes","TextEncoder","encode","binString","from","String","fromCodePoint","globalThis","btoa","fromBase64","TextDecoder","decode","base64Str","atob","char","charCodeAt","Uint8Array","pageArgumentsToCallOptions","category","name","properties","options","callback","payload","nameForProperties","categoryForProperties","_objectSpread","trackArgumentsToCallOptions","event","identifyArgumentsToCallOptions","userId","traits","aliasArgumentsToCallOptions","to","groupArgumentsToCallOptions","groupId","CAPABILITIES_MANAGER","CONFIG_MANAGER","EVENT_MANAGER","PLUGINS_MANAGER","USER_SESSION_MANAGER","ERROR_HANDLER","PLUGIN_ENGINE","STORE_MANAGER","RS_APP","ANALYTICS_CORE","APP_NAME","APP_VERSION","ADBLOCK_PAGE_CATEGORY","GLOBAL_PRELOAD_BUFFER","QUERY_PARAM_ANONYMOUS_ID_KEY","QUERY_PARAM_USER_ID_KEY","QUERY_PARAM_TRACK_EVENT_NAME_KEY","DEFAULT_SESSION_TIMEOUT_MS","createExposedGlobals","analyticsInstanceId","RudderStackGlobals","setExposedGlobal","keyName","getEventDataFromQueryString","params","dataTypeNamePrefix","data","startsWith","dataKey","substring","retrievePreloadBufferEvents","instance","preloadedEventsArray","getExposedGlobal","argumentsArray","eventArgumentToQueryParamMap","queryObject","URLSearchParams","location","search","unshift","retrieveEventsFromQueryString","enqueuePreloadBufferEvents","consumePreloadBufferedEvent","analyticsInstance","_ref","callOptions","methodName","shift","_toConsumableArray","LOG_CONTEXT_SEPARATOR","SCRIPT_LOAD_ERROR","id","url","concat","getCircularReplacer","excludeNull","excludeKeys","logger","ancestors","includes","pop","warn","context","CIRCULAR_REFERENCE_WARNING","stringifyWithoutCircular","err","getMutatedError","issue","finalError","message","jsFileLoader","timeout","async","extraAttributes","Promise","resolve","reject","document","getElementById","SCRIPT_ALREADY_EXISTS_ERROR","timeoutID","newScriptElement","_scriptElements$","headElements","getElementsByTagName","_headElements$","_headElements$2","insertBefore","firstChild","scriptElements","parentNode","_scriptElements$2","headElement","createElement","appendChild","htmlElement","insertScript","onload","onerror","scriptElement","src","attributeName","setAttribute","createScriptElement","clearTimeout","setTimeout","SCRIPT_LOAD_TIMEOUT_ERROR","ExternalSrcLoader","_createClass","errorHandler","DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS","_classCallCheck","_defineProperty","hasErrorHandler","onError","bind","config","_this","isFireAndForget","then","catch","error","_this$errorHandler","Symbol","for","t","s","h","f","o","v","S","u","d","U","y","g","_","E","brand","subscribe","toJSON","peek","defineProperty","N","BufferQueue","items","item","LOG_LEVEL_MAP","LOG","INFO","DEBUG","WARN","ERROR","NONE","DEFAULT_LOG_LEVEL","Logger","minLogLevel","scope","logProvider","console","_len","_key","outputLog","_len2","_key2","_len3","_key3","_len4","_key4","_len5","_key5","logMethod","_this$logProvider","_this$logProvider2","toLowerCase","formatLogData","scopeVal","logLevel","msg","originalMsg","trim","styledLogArgs","defaultLogger","ErrorType","SUPPORTED_STORAGE_TYPES","DEFAULT_STORAGE_TYPE","SOURCE_CONFIG_RESOLUTION_ERROR","NOTIFY_FAILURE_ERROR","DELIVERY_ERROR","prefix","status","statusText","REQUEST_ERROR","_e$type2","READY_CALLBACK_INVOKE_ERROR","CDN_INT_DIR","CDN_PLUGINS_DIR","URL_PATTERN","BUILD_TYPE","SDK_CDN_BASE_URL","CDN_ARCH_VERSION_DIR","DEST_SDK_BASE_URL","PLUGINS_BASE_URL","DEFAULT_CONFIG_BE_URL","DEFAULT_STORAGE_ENCRYPTION_VERSION","ConsentManagersToPluginNameMap","oneTrust","ketch","custom","StorageEncryptionVersionsToPluginNameMap","DataPlaneEventsTransportToPluginNameMap","DEFAULT_DATA_PLANE_EVENTS_TRANSPORT","loadOptionsState","signal","configUrl","loadIntegration","sessions","autoTrack","sameSiteCookie","polyfillIfRequired","integrations","All","useBeacon","beaconQueueOptions","destinationsQueueOptions","queueOptions","lockIntegrationsVersion","lockPluginsVersion","uaChTrackLevel","plugins","useGlobalIntegrationsConfigInEvents","bufferDataPlaneEventsUntilReady","dataPlaneEventsBufferTimeout","storage","encryption","version","migrate","sendAdblockPageOptions","useServerSideCookies","DEFAULT_USER_SESSION_VALUES","userTraits","anonymousId","groupTraits","initialReferrer","initialReferringDomain","sessionInfo","authToken","defaultSessionConfiguration","sessionState","capabilitiesState","isOnline","isLocalStorageAvailable","isCookieStorageAvailable","isSessionStorageAvailable","isBeaconAvailable","isLegacyDOM","isUaCHAvailable","isCryptoAvailable","isIE11","isAdBlocked","reportingState","isErrorReportingEnabled","isMetricsReportingEnabled","isErrorReportingPluginLoaded","breadcrumbs","sourceConfigState","lifecycleState","activeDataplaneUrl","integrationsCDNPath","pluginsCDNPath","sourceConfigUrl","initialized","loaded","readyCallbacks","writeKey","dataPlaneUrl","consentsState","enabled","activeConsentManagerPluginName","preConsent","postConsent","resolutionStrategy","provider","metadata","metricsState","retries","dropped","sent","queued","triggered","metricsServiceUrl","contextState","app","namespace","installType","library","snippetVersion","RudderSnippetVersion","userAgent","device","network","os","locale","screen","density","width","height","innerWidth","innerHeight","timezone","nativeDestinationsState","configuredDestinations","activeDestinations","loadOnlyIntegrations","failedDestinations","initializedDestinations","clientDestinationsReady","integrationsConfig","eventBufferState","toBeProcessedArray","readyCallbacksArray","pluginsState","ready","loadedPlugins","failedPlugins","pluginsToLoadFromConfig","activePlugins","totalPluginsToLoad","storageState","encryptionPluginName","cookie","entries","trulyAnonymousTracking","serverSideCookiesState","isEnabledServerSideCookies","dataServiceUrl","dataPlaneEventsState","eventsQueuePluginName","deliveryEnabled","state","capabilities","consents","eventBuffer","lifecycle","loadOptions","metrics","nativeDestinations","reporting","session","serverCookies","dataPlaneEvents","PluginEngine","throws","plugin","_this$logger","errorMessage","byName","_this$logger2","pluginName","PLUGIN_ALREADY_EXISTS_ERROR","cache","pos","pluginItem","_pluginItem$deps","deps","Math","min","splice","initialize","_this$logger3","PLUGIN_NOT_FOUND_ERROR","indexOf","_this$logger4","PLUGIN_ENGINE_BUG_ERROR","extPoint","lifeCycleName","filter","_plugin$deps","some","dependency","_this$logger5","notExistDeps","PLUGIN_DEPS_ERROR","hasValueByPath","_this$config$throws","_this2","allowMultiple","args","extensionPointName","noCall","endsWith","extensionPointNameParts","pluginMethodPath","getPlugins","method","_this2$logger","PLUGIN_INVOCATION_ERROR","invoke","defaultPluginEngine","ErrorHandler","pluginEngine","errorBuffer","attachEffect","size","errorToProcess","dequeue","notifyError","errorState","addEventListener","UNHANDLEDEXCEPTION","UNHANDLEDREJECTION","debug","httpClient","externalSrcLoader","errReportingInitVal","invokeSingle","client","errReportingClient","normalizedError","customMessage","shouldAlwaysThrow","errorType","HANDLEDEXCEPTION","ErrorEvent","processError","PromiseRejectionEvent","reason","Event","eventTarget","target","localName","dataset","loader","isnonnativesdk","getNormalizedErrorForUnhandledError","severity","unhandled","severityReason","enqueue","breadcrumb","defaultErrorHandler","isNonCloudDestination","destination","connectionMode","useNativeSDKToSend","useNativeSDK","isHybridModeDestination","getNonCloudDestinations","destinations","pluginNamesList","getCurrentTimeFormatted","toISOString","COOKIE_STORAGE","LOCAL_STORAGE","SESSION_STORAGE","MEMORY_STORAGE","NO_STORAGE","removeDuplicateSlashes","str","isValidURL","URL","BUFFER","HEX","IDX","v4","len","crypto","getRandomValues","tmp","out","generateUUID","uuidSecure","num","random","uuid","isErrRetryable","details","_details$error","isRetryableNWFailure","COOKIE_KEYS","ENCRYPTION_PREFIX_V3","encodeURIComponent","decodeURIComponent","all","pair","pairs","cookieStringValue","pairItem","optionsConfig","cookieString","maxage","expires","domain","toUTCString","samesite","secure","decryptBrowser","QUEUE_UTILITIES","getDeliveryPayload","getDMTDeliveryPayload","dmtRequestPayload","validateEventPayloadSize","payloadStr","payloadSize","sizeLimit","EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING","getFinalEventForDeliveryMutator","currentTime","finalEvent","sentAt","DEFAULT_BEACON_QUEUE_OPTIONS","maxItems","flushQueueInterval","DATA_PLANE_API_VERSION","BEACON_QUEUE_PLUGIN","getBatchDeliveryPayload","events","batch","blobPayload","json","Blob","BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR","QueueStatuses","IN_PROGRESS","QUEUE","RECLAIM_START","RECLAIM_END","ACK","BATCH_QUEUE","ScheduleModes","DEFAULT_CLOCK","ms","clockLateFactor","Schedule","tasks","nextId","clock","task","mode","handle","ASAP","start","now","elapsedTimeoutTime","RESCHEDULE","run","values","DEFAULT_MAX_RETRY_ATTEMPTS","Infinity","DEFAULT_MAX_ITEMS","DEFAULT_MAX_BATCH_SIZE_BYTES","sortByTime","time","RETRY_QUEUE","RetryQueue","queueProcessCb","storeManager","_options$timerScaleFa","storageType","queueBatchItemsSizeCalculatorCb","processQueueCb","batchSizeCalcCb","maxAttempts","configureBatchMode","backoff","minRetryDelay","maxRetryDelay","factor","backoffFactor","jitter","backoffJitter","timerScaleFactor","max","timeouts","ackTimer","round","reclaimTimer","reclaimTimeout","reclaimWait","schedule","processId","store","setStore","validKeys","setDefaultQueueEntries","ack","checkReclaim","processHead","flushBatch","flushBatchOnPageLeave","scheduleTimeoutActive","setStorageEntry","batchingInProgress","_batchOptions$maxSize","_batchOptions$maxItem","_batchOptions$flushIn","batchOptions","maxSize","flushInterval","pageLeft","handleOnLeave","visibilityState","onPageLeave","remove","cancelAll","stop","scheduleFlushBatch","_this$batch","flushBatchTaskId","cancel","batchQueue","getStorageEntry","batchEntry","genQueueItem","queueItem","pushToMainQueue","attemptNumber","pow","rand","deviation","floor","toPrecision","entry","curEntry","handleNewItemForBatch","_ref2","batchItems","batchDispatchInfo","getBatchDispatchInfo","criteriaMet","criteriaExceeded","_ref3","queue","sort","itemData","shouldRetry","getDelay","_this$batch2","_this$batch3","lengthCriteriaMet","lengthCriteriaExceeded","configuredBatchMaxItems","sizeCriteriaMet","sizeCriteriaExceeded","configuredBatchMaxSize","curBatchSize","_ref4","_ref5","_ref7","inProgress","toRun","processItemCallback","el","res","_ref6","requeue","enqueueItem","done","inProgressSize","willBeRetried","nextProcessExecutionTime","reclaimStartVal","reclaimEndVal","_this$getStorageEntry","_other$get","_other$get2","_other$get3","other","our","their","trackMessageIds","addConcatQueue","incrementAttemptNumberBy","concatIterator","_el$id","_el$id2","clearQueueEntries","localStorageBackoff","removeStorageEntry","entryIdx","_this3","attempt","queueEntryKeys","_this3$logger","storageBusyErr","code","RETRY_QUEUE_ENTRY_REMOVE_ERROR","_this4","createReclaimEndTask","reclaim","createReclaimStartTask","ABANDON","storageEngine","getOriginalEngine","storageKeys","keyParts","findOtherQueues","tryReclaim","BeaconQueue","dataplaneEventsQueue","init","_state$loadOptions$va","queueOpts","dataplaneUrl","dpUrl","pathname","href","getDeliveryUrl","finalQOpts","eventsQueue","finalEvents","queueItemData","eventsDelivery","isEnqueuedInBeacon","navigator","sendBeacon","BEACON_QUEUE_SEND_ERROR","BEACON_QUEUE_DELIVERY_ERROR","storages","timestamp","addItem","BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME","GLOBAL_LIBRARY_OBJECT_NAMES","API_KEY","DEV_HOSTS","APP_STATE_EXCLUDE_KEYS","BUGSNAG_PLUGIN","enhanceErrorEventMutator","_getAppStateForMetada","updateMetaData","stateStr","parse","getAppStateForMetadata","_event$stacktrace","errorOrigin","stacktrace","file","isDestinationIntegrationBundle","srcFileName","lastIndexOf","isRudderSDKError","_unused","getGlobalBugsnagLibInstance","loadBugsnagSDK","every","globalKeyName","loadJSFile","initBugsnagClient","promiseResolve","promiseReject","globalLibInstance","_globalLibInstance$_c","_tempInstance$notifie","globalBugsnagLibInstance","_client","_notifier","apiKey","releaseStage","beforeSend","notifier","_state$source$value","host","appVersion","metaData","SDK","autoCaptureSessions","collectUserIp","maxEvents","maxBreadcrumbs","hostname","user","networkBreadcrumbsEnabled","getNewClient","Bugsnag","errorReportingProvider","BUGSNAG_API_KEY_VALIDATION_ERROR","notify","leaveBreadcrumb","CustomConsentManager","consentManager","updateConsentsInfo","isDestinationConsented","destConfig","allowedConsentIds","_cmpConfig$resolution","consentManagement","cmpConfig","find","configuredConsents","consent","matchPredicate","DIR_NAME","NAME","DISPLAY_NAME","ADOBEANALYTICS","_CNameMapping","ActiveCampaign","_destDisplayNamesToFi","destDisplayNamesToFileNamesMap","HubSpotDisplayName","HubSpotDirectoryName","GADisplayName","HotjarDisplayName","HotjarDirectoryName","GoogleAdsDisplayName","GoogleAdsDirectoryName","GoogleTagManagerDisplayName","GoogleTagManagerDirectoryName","BrazeDisplayName","BrazeDirectoryName","IntercomDisplayName","IntercomDirectoryName","KeenDisplayName","KeenDirectoryName","KissmetricsDisplayName","KissmetricsDirectoryName","CustomerIODisplayName","CustomerIODirectoryName","ChartbeatDisplayName","ChartbeatDirectoryName","ComscoreDisplayName","ComscoreDirectoryName","FacebookPixelDisplayName","FacebookPixelDirectoryName","LotameDisplayName","LotameDirectoryName","OptimizelyDisplayName","OptimizelyDirectoryName","BugsnagDisplayName","BugsnagDirectoryName","FullstoryDisplayName","FullstoryDirectoryName","TVSquaredDisplayName","TVSquaredDirectoryName","GA4DisplayName","GA4_V2DisplayName","GA4_V2DirectoryName","MoEngageDisplayName","MoEngageDirectoryName","AmplitudeDisplayName","AmplitudeDirectoryName","PendoDisplayName","PendoDirectoryName","LyticsDisplayName","LyticsDirectoryName","AppcuesDisplayName","AppcuesDirectoryName","PostHogDisplayName","PostHogDirectoryName","KlaviyoDisplayName","KlaviyoDirectoryName","CleverTapDisplayName","CleverTapDirectoryName","BingAdsDisplayName","BingAdsDirectoryName","PinterestTagDisplayName","PinterestTagDirectoryName","AdobeAnalyticsDisplayName","AdobeAnalyticsDirectoryName","LinkedInInsightTagDisplayName","LinkedInInsightTagDirectoryName","RedditPixelDisplayName","RedditPixelDirectoryName","DripDisplayName","DripDirectoryName","HeapDisplayName","HeapDirectoryName","CriteoDisplayName","CriteoDirectoryName","MixpanelDisplayName","MixpanelDirectoryName","QualtricsDisplayName","QualtricsDirectoryName","ProfitWellDisplayName","ProfitWellDirectoryName","SentryDisplayName","SentryDirectoryName","QuantumMetricDisplayName","QuantumMetricDirectoryName","SnapPixelDisplayName","SnapPixelDirectoryName","PostAffiliateProDisplayName","PostAffiliateProDirectoryName","GoogleOptimizeDisplayName","GoogleOptimizeDirectoryName","LaunchDarklyDisplayName","LaunchDarklyDirectoryName","GA360DisplayName","GA360DirectoryName","AdrollDisplayName","AdrollDirectoryName","DCMFloodlightDisplayName","DCMFloodlightDirectoryName","MatomoDisplayName","MatomoDirectoryName","VeroDisplayName","VeroDirectoryName","MouseflowDisplayName","MouseflowDirectoryName","RockerboxDisplayName","RockerboxDirectoryName","ConvertFlowDisplayName","ConvertFlowDirectoryName","SnapEngageDisplayName","SnapEngageDirectoryName","LiveChatDisplayName","LiveChatDirectoryName","ShynetDisplayName","ShynetDirectoryName","WoopraDisplayName","WoopraDirectoryName","RollBarDisplayName","RollBarDirectoryName","QuoraPixelDisplayName","QuoraPixelDirectoryName","JuneDisplayName","JuneDirectoryName","EngageDisplayName","EngageDirectoryName","IterableDisplayName","IterableDirectoryName","YandexMetricaDisplayName","YandexMetricaDirectoryName","RefinerDisplayName","RefinerDirectoryName","QualarooDisplayName","QualarooDirectoryName","PodsightsDisplayName","PodsightsDirectoryName","AxeptioDisplayName","AxeptioDirectoryName","SatismeterDisplayName","SatismeterDirectoryName","MicrosoftClarityDisplayName","MicrosoftClarityDirectoryName","SendinblueDisplayName","SendinblueDirectoryName","OlarkDisplayName","OlarkDirectoryName","LemniskDisplayName","LemniskDirectoryName","TiktokAdsDisplayName","TiktokAdsDirectoryName","ActiveCampaignDisplayName","ActiveCampaignDirectoryName","SprigDisplayName","SprigDirectoryName","SpotifyPixelDisplayName","SpotifyPixelDirectoryName","CommandBarDisplayName","CommandBarDirectoryName","NinetailedDisplayName","NinetailedDirectoryName","DEFAULT_INTEGRATIONS_CONFIG","filterDestinations","intgOpts","_intgOpts$All","allOptVal","dest","isDestEnabled","destIntgConfig","destDisplayName","displayName","checks","isDestIntgConfigTruthy","DEVICE_MODE_DESTINATIONS_PLUGIN","DESTINATION_SDK_LOAD_ERROR","destUserFriendlyId","initializeDestination","destSDKIdentifier","sdkTypeName","initializedDestination","destInstance","_state$consents$postC","_state$consents$postC2","analytics","rudderanalytics","getAnalyticsInstance","page","eventMethodOverloads","track","identify","alias","group","getAnonymousId","getUserId","getUserTraits","getGroupId","getGroupTraits","getSessionId","shouldApplyDeviceModeTransformation","propagateEventsUntransformedOnError","destinationId","createDestinationInstance","handleNumber","checkReady","isLoaded","isReady","requestAnimationFrame","cancelAnimationFrame","userFriendlyId","isDestinationReady","curDestIntgConfig","_dest$instance","getDataForIntegrationsObject","_dest$instance2","getCumulativeIntegrationsConfig","DeviceModeDestinations","setActiveDestinations","pluginsManager","configSupportedDestinations","configDest","consentedDestinations","destinationUtils","_pluginsManager$invok","load","externalScriptOnLoad","sdkName","isDestinationSDKMounted","destSdkURL","DEFAULT_TRANSFORMATION_QUEUE_OPTIONS","DMT_PLUGIN","DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR","action","DMT_REQUEST_FAILED_ERROR","sendTransformedEventToDestinations","destinationIds","ACTION_TO_SEND_UNTRANSFORMED_EVENT","ACTION_TO_DROP_EVENT","eventsToSend","destTransformedResult","transformedBatch","tEvent","DeviceModeTransformation","transformEvent","setAuthHeader","maxRetryAttempts","token","orderNo","request","body","sendRawData","isRawResponse","_details$error$status","_details$response","queueErrResp","response","FAILED_REQUEST_ERR_MSG_PREFIX","ERROR_MESSAGES_TO_BE_FILTERED","createNewBreadcrumb","getErrorDeliveryPayload","message_id","sdk_version","write_key","install_type","errors","StackFrame","FIREFOX_SAFARI_STACK_REGEXP","CHROME_IE_STACK_REGEXP","SAFARI_NATIVE_CODE_REGEXP","exports","_isNumber","isNaN","parseFloat","isFinite","_capitalize","toUpperCase","_getter","booleanProps","numericProps","stringProps","arrayProps","objectProps","props","getArgs","setArgs","TypeError","getEvalOrigin","evalOrigin","setEvalOrigin","fileName","getFileName","lineNumber","getLineNumber","columnNumber","getColumnNumber","functionName","getFunctionName","getIsEval","fromString","argsStartIndex","argsEndIndex","locationString","parts","exec","j","factory","require$$0","parseOpera","stack","match","parseV8OrIE","parseFFOrSafari","extractLocation","urlLike","line","sanitizedLine","locationParts","functionNameRegex","matches","parseOpera9","parseOpera11","parseOpera10","lineRE","lines","argsRaw","tokens","functionCall","hasStack","ensureString","createBugsnagError","errorClass","reduce","accum","frame","inProject","formatStackframe","randomWordArray","normaliseError","maybeError","component","internalFrames","isError","hasNecessaryFields","ErrorFormat","tolerateNonErrors","handledState","errorFramesToSkip","_normaliseError2","_slicedToArray","ErrorStackParser","getStacktrace","ErrorReporting","_state$reporting$brea","errorReporting","isInvokedFromLatestCore","_state$source$value2","_getConfigForPayloadC","getConfigForPayloadCreation","errorPayload","paths","bugsnagPayload","_state$context$locale","_state$context$userAg","_state$source$value$i","payloadVersion","exceptions","clientIp","sdk","getBugsnagErrorEvent","externallyLoadedSessionStorageKeys","segment","ExternalAnonymousId","getStorageEngine","_options$autoCapture","autoCapture","lsEngine","isEnabled","getItem","csEngine","getSegmentAnonymousId","USER_INTERFACE","_navigator","language","_navigator2","decodedData","percentEncodingChar","KEY_VALIDATOR","DELIMITER","getCheckSum","serializedIds","optOffsetMin","fingerprint","getTimezoneOffset","getFingerprint","crc","crcTable","makeCRCTable","crc32","parseLinker","linkerObj","isEven","checksum","parseLinkerParamValue","isCheckSumValid","keyValuePairs","deserialize","GoogleLinker","userSession","anonymousIdGoogleLinker","rudderAmpLinkerParam","parsedAnonymousIdObj","KETCH_CONSENT_MANAGER_PLUGIN","getKetchConsentData","rawConsentCookieData","dataStore","engine","consentCookieData","string","KETCH_CONSENT_COOKIE_PARSE_ERROR","consentPurposes","pEntry","purposeCode","purposeValue","updateConsentStateFromData","ketchConsentData","consentData","deniedConsentIds","getConsentData","KetchConsentManager","getKetchUserConsentedPurposes","_state$consents$data$","getKetchUserDeniedPurposes","_state$consents$data$2","updateKetchConsent","ketchConsent","ketchConsentPurposes","_consentManagement$fi","cmpConsents","purpose","DEFAULT_QUEUE_OPTIONS","NATIVE_DESTINATION_QUEUE_PLUGIN","isValidEventName","eventName","sendEventToDestination","_dest$instance$method","NativeDestinationQueue","destinationsEventsQueue","dmtQueue","rudderEvent","destinationsToSend","destWithTransformationEnabled","clonedRudderEvent","sendEvent","eventType","_dest$config","blacklistedEvents","whitelistedEvents","eventFilteringOption","trimmedEventName","eventObj","isEventDenyListed","enqueueEventToDestination","ONETRUST_CONSENT_MANAGER_PLUGIN","OneTrustConsentManager","OneTrust","OnetrustActiveGroups","oneTrustAllGroupsInfo","GetDomainData","Groups","CustomGroupId","oneTrustCookieCategories","oneTrustCookieCategory","StorageEncryption","encrypt","decrypt","window","self","frames","nBytes","words","Uint32Array","WordArray","rcache","m_w","_m_w","_m_z","mask","_r","Base","assign","_construct","_Base","sigBytes","_callSuper","typedArray","ArrayBuffer","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Float32Array","Float64Array","buffer","byteOffset","byteLength","typedArrayByteLength","_words","_inherits","Hex","wordArray","thisWords","thatWords","thisSigBytes","thatSigBytes","clamp","thatByte","ceil","_superPropGet","hexChars","bite","hexStr","hexStrLength","parseInt","substr","Latin1","latin1Chars","fromCharCode","latin1Str","latin1StrLength","Utf8","escape","utf8Str","unescape","BufferedBlockAlgorithm","_Base2","_minBufferSize","_data","_nDataBytes","m_data","doFlush","processedWords","blockSize","dataWords","dataSigBytes","nBlocksReady","nWordsReady","nBytesReady","_doProcessBlock","Hasher","_BufferedBlockAlgorit","cfg","reset","_doReset","messageUpdate","_append","_process","_doFinalize","SubHasher","finalize","HMAC","_Base3","hasher","_hasher","hasherBlockSize","hasherBlockSizeBytes","oKey","_oKey","iKey","_iKey","oKeyWords","iKeyWords","update","innerHash","Base64","_map","base64Chars","triplet","paddingChar","base64StrLength","reverseMap","_reverseMap","paddingIndex","bitsCombined","parseLoop","T","abs","sin","FF","GG","HH","II","MD5Algo","_Hasher","_hash","M","_M","offset_i","M_offset_i","H","M_offset_0","M_offset_1","M_offset_2","M_offset_3","M_offset_4","M_offset_5","M_offset_6","M_offset_7","M_offset_8","M_offset_9","M_offset_10","M_offset_11","M_offset_12","M_offset_13","M_offset_14","M_offset_15","nBitsTotal","nBitsLeft","nBitsTotalH","nBitsTotalL","H_i","_createHelper","_createHmacHelper","EvpKDFAlgo","keySize","iterations","password","salt","block","derivedKey","derivedKeyWords","ObjectAssign","Cipher","xformMode","_xformMode","dataUpdate","_ENC_XFORM_MODE","_DEC_XFORM_MODE","SubCipher","selectCipherStrategy","PasswordBasedCipher","SerializableCipher","ciphertext","xorBlock","iv","_iv","_prevBlock","ivSize","CBC","_BlockCipherMode","BlockCipherMode","cipher","_cipher","Encryptor","Decryptor","_CBC","_class","encryptBlock","_CBC2","_class2","thisBlock","decryptBlock","Pkcs7","pad","blockSizeBytes","nPaddingBytes","paddingWord","paddingWords","padding","unpad","BlockCipher","_Cipher2","modeCreator","createEncryptor","createDecryptor","_mode","__creator","processBlock","finalProcessedBlocks","CipherParams","cipherParams","_this5","mixIn","formatter","OpenSSLFormatter","openSSLStr","ciphertextWords","_cfg","encryptor","cipherCfg","algorithm","format","_ciphertext","_parse","OpenSSLKdf","execute","_salt","compute","_SerializableCipher","derivedParams","kdf","_SBOX","INV_SBOX","_SUB_MIX_0","_SUB_MIX_1","_SUB_MIX_2","_SUB_MIX_3","INV_SUB_MIX_0","INV_SUB_MIX_1","INV_SUB_MIX_2","INV_SUB_MIX_3","xi","sx","x2","x4","x8","RCON","AESAlgo","_BlockCipher","_nRounds","_keyPriorReset","keyWords","ksRows","_keySchedule","keySchedule","ksRow","_invKeySchedule","invKeySchedule","invKsRow","_doCryptBlock","SUB_MIX_0","SUB_MIX_1","SUB_MIX_2","SUB_MIX_3","SBOX","nRounds","s0","s1","s2","s3","t0","t1","t2","t3","AES","ENCRYPTION_PREFIX_V1","ENCRYPTION_KEY_V1","StorageEncryptionLegacy","StorageMigrator","storedVal","decryptedVal","decryptLegacy","STORAGE_MIGRATION_ERROR","DEFAULT_RETRY_QUEUE_OPTIONS","endpoint","logErrorOnFailure","isRetryableFailure","http","errMsg","EVENT_DELIVERY_FAILURE_ERROR_PREFIX","dropMsg","getRequestInfo","headers","eventUrl","eventHeaders","XhrQueue","_getRequestInfo","_getBatchDeliveryPayl","AnonymousId","FetchQueue","pluginsInventory","PluginsManager","setActivePlugins","registerLocalPlugins","registerRemotePlugins","attachEffects","effect","pluginGroupsToProcess","configurationStatus","configurationStatusStr","activePluginName","supportedPlugins","shouldAddMissingPlugins","addMissingPlugins","basePlugins","missingPlugins","isSinglePlugin","pluginsString","baseWarning","generateMisconfiguredPluginsWarning","pluginsToLoad","getPluginsToLoadBasedOnConfig","availablePlugins","localPlugin","register","remotePluginsList","_regeneratorRuntime","mark","_callee","remotePluginKey","wrap","_context","prev","next","remotePluginModule","default","_x","_this$engine","invokeMultiple","_this$engine2","unregister","HttpClientError","_Error","responseBody","_wrapNativeSuper","makeXHRRequest","xhr","XMLHttpRequest","xhrError","responseText","ontimeout","Response","open","withCredentials","headerName","headerValue","setRequestHeader","send","clonedErr","XHR_SEND_ERROR","makeFetchRequest","controller","AbortController","fetchOptions","fetchPromise","fetch","ok","text","timeoutId","abort","finally","makeBeaconRequest","DEFAULT_REQUEST_OPTIONS","Accept","HttpClient","transportType","transportFn","_headers","finalOptions","Authorization","basicAuthHeader","authVal","defaultHttpClient","CLIENT_DATA_STORE_COOKIE","CLIENT_DATA_STORE_LS","CLIENT_DATA_STORE_SESSION","USER_SESSION_KEYS","storageClientDataStoreNameMap","hasUAClientHints","userAgentData","legacyJSEngineRequiredPolyfills","replaceAll","fromEntries","testElement","aB","CustomEvent","Set","getScreenDetails","devicePixelRatio","isStorageQuotaExceeded","isQuotaExceededError","DOMException","isStorageAvailable","testData","storageInstance","localStorage","sessionStorage","setItem","removeItem","msgPrefix","levelsFunc","_host$split","legacyGetHostname","last","levels","getDefaultCookieOptions","topDomain","cname","opts","CookieStorage","globalSingleton","configure","_this$options","sameDomainCookiesOnly","isSupportAvailable","_curKeys$index","defaultInMemoryStorage","InMemoryStorage","module","isJSON","dealIncognito","_KEY","_VALUE","inMemoryStorage","Store","ret","has","dt","clear","arr","_Store","argm","LocalStorage","defaultLocalStorage","SessionStorage","defaultSessionStorage","configureStorageEngines","localStorageOptions","inMemoryStorageOptions","sessionStorageOptions","cookieStorageOptions","configureCookieStorageEngine","configureInMemoryStorageEngine","configureSessionStorageEngine","_config$isEncrypted","_config$validKeys","_config$errorHandler","_config$logger","isEncrypted","noKeyValidation","noCompoundKey","originalEngine","compoundKey","validKeyName","validKey","createValidKey","swapQueueStoreToInMemoryEngine","STORE_DATA_SAVE_ERROR","STORE_DATA_FETCH_ERROR","noEncryption","formattedValue","StoreManager","_config$cookieStorage","_state$storage$cookie","_state$storage$cookie2","isInitialized","secureCookie","setCookieDomain","initClientDataStores","initializeStorageState","_getStorageEngine","globalStorageType","entriesOptions","postConsentStorageOpts","storageEntries","sessionKey","_entriesOptions","storageKey","configuredStorageType","preConsentStorageType","overriddenStorageType","_state$consents$preCo","strategy","getStorageTypeFromPreConsentIfApplicable","finalStorageType","getResolvedStorageTypeForEntry","_getStorageEngine2","_getStorageEngine3","_getStorageEngine4","_getStorageEngine5","_getStorageEngine6","selectedStorageType","STORAGE_UNAVAILABLE_WARNING","storeConfig","stores","validateLoadArgs","WRITE_KEY_VALIDATION_ERROR","validateWriteKey","DATA_PLANE_URL_VALIDATION_ERROR","validateDataPlaneUrl","getTopDomain","urlObj","protocol","getDataServiceUrl","useExactDomain","origin","_getTopDomain","getTopDomainUrl","formattedEndpoint","removeTrailingSlashes","getDomain","getReferringDomain","referrer","_getDomain","extractUTMParameters","UTM_PREFIX","searchParams","sParam","utmParam","DEFAULT_PRE_CONSENT_STORAGE_STRATEGY","DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE","isValidConsentsData","getConsentManagerInfo","consentManagementOpts","selectedConsentManager","consentManagersToPluginNameMap","consentManagerPluginName","getConsentManagementData","_getConsentManagerInf","consentsData","getSDKUrl","_step","sdkFileNameRegex","_iterator","_createForOfIteratorHelper","getAttribute","updateReportingState","sourceConfig","_sourceConfig$statsCo","statsCollection","chrome","runtime","_sourceConfig$statsCo2","updateStorageStateFromLoadOptions","_storageOptsFromLoad$","dataServiceEndpoint","storageOptsFromLoad","isValidStorageType","defaultStorageType","STORAGE_TYPE_VALIDATION_WARNING","selectedStorageEncryptionVersion","storageEncryptionVersionsToPluginNameMap","defaultVersion","storageEncryptionVersion","configuredMigrationValue","finalMigrationVal","STORAGE_DATA_MIGRATION_OVERRIDE_WARNING","_storageOptsFromLoad$2","providedDomain","cookieOptions","_cookieOptions$domain","providedCookieDomain","curHost","dataServiceHost","currentCookieDomain","SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING","updateConsentsStateFromLoadOptions","_preConsentOpts$stora","_preConsentOpts$stora2","_preConsentOpts$event","_preConsentOpts$event2","_preConsentOpts$stora3","selectedStrategy","defaultStrategy","_getConsentManagement","preConsentOpts","storageStrategy","_preConsentOpts$event3","eventsDeliveryType","delivery","selectedDeliveryType","defaultDeliveryType","UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE","_state$loadOptions$va2","updateDataPlaneEventsStateFromLoadOptions","defaultEventsQueuePluginName","getSourceConfigURL","defSearchParams","build","configUrlInstance","INVALID_CONFIG_URL_WARNING","getSDKComponentBaseURL","componentType","pathSuffix","baseURL","currentVersion","lockVersion","customURL","sdkComponentURL","sdkURL","ConfigManager","processConfig","setMinLogLevel","destSDKBaseURL","pluginsSDKBaseURL","intgCdnUrl","customIntegrationsCDNPath","getIntegrationsCDNPath","customPluginsCDNPath","getPluginsCDNPath","getConfig","isValidSourceConfig","deleted","destinationDefinition","filterEnabledDestination","workspaceId","resp","cmpMetadata","consentManagementMetadata","_resp$consentManageme","_resp$consentManageme2","providers","updateConsentsState","sourceConfigFunc","getSourceConfig","pRes","getReferrer","_document","getDefaultPageProperties","canonicalUrl","tags","tag","_tag$getAttribute","getCanonicalUrl","tabUrl","pageUrl","urlWithoutHash","getUrlWithoutHash","title","referring_domain","tab_url","POLYFILL_URL","POLYFILL_SCRIPT_ID","CapabilitiesManager","onReady","prepareBrowserCapabilities","attachWindowListeners","_globalThis$navigator","onLine","brave","isBrave","matchedArr","getUserAgent","browserLanguage","_navigator$userAgentD","level","getHighEntropyValues","ua","getUserAgentClientHint","uach","baseUrl","sendAdblockPage","redirected","requiredCapabilitiesList","needsPolyfill","isCapabilityMissing","isLegacyJSEngine","customPolyfillUrl","polyfillURL","polyfillUrl","INVALID_POLYFILL_URL_WARNING","isDefaultPolyfillService","polyfillCallbackName","scriptId","POLYFILL_SCRIPT_LOAD_ERROR","func","thisArg","delay","DEBOUNCED_TIMEOUT_MS","debounce","detectBrowserCapabilities","TOP_LEVEL_ELEMENTS","CONTEXT_RESERVED_ELEMENTS","RESERVED_ELEMENTS","isNumber","isPositiveInteger","hasSessionExpired","expiresAt","isManualSessionIdValid","sessionId","minimumLength","minSessionIdLength","INVALID_SESSION_ID_WARNING","generateManualTrackingSession","sessionStart","manualTrack","isStorageTypeValidForStoringData","generateAnonymousId","getContextPageProperties","pageProps","curPageProps","ctxPageProps","initial_referrer","initial_referring_domain","checkForReservedElementsInObject","parentKeyPath","property","reservedElements","RESERVED_KEYWORD_WARNING","processOptions","originalTimestamp","updateTopLevelEventElements","rudderContext","tempContext","getMergedContext","getEventIntegrationsConfig","finalIntgConfig","_state$consents$postC3","getEnrichedEvent","_state$storage$entrie","_state$storage$entrie2","_state$storage$entrie3","commonEventData","channel","campaign","messageId","processedEvent","contextualTraits","checkForReservedElements","RudderEventFactory","optionsPageProps","getUpdatedPageProperties","enrichedEvent","previousId","groupEvent","generatePageEvent","generateTrackEvent","generateIdentifyEvent","generateAliasEvent","generateGroupEvent","EventManager","eventRepository","userSessionManager","eventFactory","resume","refreshSession","UserSessionManager","serverSideCookieDebounceFuncs","syncStorageDataToState","registerEffects","_externalAnonymousId","migrateStorageIfNeeded","migrateDataFromPreviousStorage","setUserId","setUserTraits","setGroupId","setGroupTraits","externalAnonymousId","externalAnonymousIdCookieName","anonymousIdOptions","getExternalAnonymousIdByCookieName","setAnonymousId","setAuthToken","getAuthToken","setInitialReferrerInfo","configureSessionTracking","getSessionInfo","isPersistenceEnabledForStorageEntry","_sessionInfo","configuredSessionTrackingInfo","getConfiguredSessionTrackingInfo","initialSessionInfo","startOrRenewAutoTracking","persistedInitialReferrer","getInitialReferrer","persistedInitialReferringDomain","getInitialReferringDomain","setInitialReferrer","setInitialReferringDomain","entryName","storageTypesForMigration","_entries$key","_this$storeManager","currentStorage","curStore","getStore","_this$storeManager2","isDefinedNotNullAndNotEmptyString","storeName","_this2$storeManager","storageEntry","_this2$pluginsManager","migratedVal","_state$loadOptions$va3","configuredSessionTimeout","defaultValue","TIMEOUT_NOT_NUMBER_WARNING","minTimeout","TIMEOUT_NOT_RECOMMENDED_WARNING","cookiesData","encryptedCookieData","cData","encryptedValue","_this$httpClient","_state$storage$cookie3","_state$storage$cookie4","_state$storage$cookie5","_state$storage$cookie6","reqType","maxAge","sameSite","cookies","cb","getEncryptedCookieData","makeRequestToSetCookie","_this4$logger2","_details$response2","_this4$logger","cookieValue","before","each","_entries$sessionKey","_this$storeManager3","_entries$sessionKey2","setServerSideCookies","cookieName","_this6","syncValueToStorage","finalAnonymousId","_this$pluginsManager","_this$pluginsManager2","persistedAnonymousId","getEntryValue","_entries$sessionKey3","_this$storeManager4","_entries$sessionKey4","_store$get","_storageEngine$getIte","_this$getSessionInfo","_sessionInfo$id","_this$getSessionInfo2","resetAnonymousId","noNewSessionStart","_this7","_session$sessionInfo$","startManualTrackingInternal","_state$session$userTr","_state$session$groupT","referringDomain","sessionTimeout","generateAutoTrackingSession","defaultOptionalPluginsList","DATA_PLANE_QUEUE_EXT_POINT_PREFIX","DESTINATIONS_QUEUE_EXT_POINT_PREFIX","getFinalEvent","_event$integrations","eventIntgConfig","destinationsIntgConfig","overriddenIntgOpts","intgName","getOverriddenIntegrationOptions","EventRepository","dmtEventsQueue","_this$destinationsEve","_this$dmtEventsQueue","bufferEventsBeforeConsent","_state$consents$preCo2","_state$consents$preCo3","shouldBufferEventsForPreConsent","_this$dataplaneEvents","_this$dataplaneEvents2","shouldBufferDpEvents","_this$dataplaneEvents3","_this$dataplaneEvents4","_this$dataplaneEvents5","_this$dataplaneEvents7","_this$dataplaneEvents6","_this$destinationsEve2","discardPreConsentEvents","dpQEvent","dQEvent","dispatchSDKEvent","customEvent","detail","bubbles","cancelable","composed","dispatchEvent","Analytics","preloadBuffer","capabilitiesManager","clonedDataPlaneUrl","clonedLoadOptions","loadOptionsFromState","_normalizedLoadOpts$p","_normalizedLoadOpts$s2","_normalizedLoadOpts$s","_normalizedLoadOpts$s4","_normalizedLoadOpts$s3","normalizedLoadOpts","normalizeLoadOptions","startLifecycle","onMounted","onBrowserCapabilitiesReady","onConfigured","onPluginsReady","onInitialized","onLoaded","onDestinationsReady","prepareInternalServices","loadConfig","processBufferedEvents","loadDestinations","bufferedEvents","bufferedEvent","eventToProcess","configManager","eventManager","_this$configManager","_this$userSessionMana","_this$eventManager","_this$pluginsManager3","processDataInPreloadBuffer","_this$pluginsManager4","_this$pluginsManager5","totalDestinationsToLoad","_this$eventManager2","addEvent","_this$eventManager3","_this$userSessionMana3","_this$eventManager4","_this$userSessionMana2","_payload$from","_this$userSessionMana4","_this$userSessionMana5","_this$eventManager5","_this$userSessionMana7","_this$eventManager6","_this$userSessionMana6","_this$userSessionMana8","_this$userSessionMana9","_this$userSessionMana10","_this$userSessionMana11","_this$userSessionMana12","end","_this$userSessionMana13","_this$userSessionMana14","_this$eventManager7","isBufferedInvocation","_this$pluginsManager6","validOptions","sendPageEvent","trackConsent","clonedOptions","getValidPostConsentOptions","sendTrackingEvents","trackOptions","pageOptions","_this$userSessionMana15","RudderAnalytics","attachErrorListeners","setDefaultInstanceKey","triggerBufferedLoadEvent","startSession","endSession","defaultAnalyticsKey","instanceId","analyticsInstances","WRITE_KEY_NOT_A_STRING_ERROR","consentMethodName","consentEvents","nonConsentEvents","promotePreloadedConsentEventsToTop","loadEvent","getPreloadedLoadEvent","_RudderAnalytics"],"mappings":"qlXAAe,SAASA,EAAeC,GACrC,OAAY,MAALA,GAA0B,WAAbC,EAAOD,KAAoD,IAAlCA,EAAE,2BACjD,UCQwBE,EAAQC,GAC9B,OAAgB,SAAAC,EAAGJ,GACjB,OAAyB,IAArBK,UAAUC,QAAgBP,EAAeC,GACpCI,EAEAD,EAAGI,MAAMC,KAAMH,UAE1B,CACF,CCPe,SAASI,EAAQN,GAC9B,OAAO,SAASO,EAAGV,EAAGW,GACpB,OAAQN,UAAUC,QAChB,KAAM,EACJ,OAAOI,EACT,KAAM,EACJ,OAAOX,EAAeC,GAAKU,EAAKR,GAAQ,SAAUU,GAChD,OAAOT,EAAGH,EAAGY,EACf,IACF,QACE,OAAOb,EAAeC,IAAMD,EAAeY,GAAKD,EAAKX,EAAeC,GAAKE,GAAQ,SAAUW,GACzF,OAAOV,EAAGU,EAAIF,EAChB,IAAKZ,EAAeY,GAAKT,GAAQ,SAAUU,GACzC,OAAOT,EAAGH,EAAGY,EACf,IAAKT,EAAGH,EAAGW,GAEjB,CACF,CChBwB,SAAAG,EAAQX,GAC9B,OAAgB,SAAAY,EAAGf,EAAGW,EAAGK,GACvB,OAAQX,UAAUC,QAChB,KAAM,EACJ,OAAOS,EACT,KAAK,EACH,OAAOhB,EAAeC,GAAKe,EAAKN,GAAQ,SAAUG,EAAIK,GACpD,OAAOd,EAAGH,EAAGY,EAAIK,EACnB,IACF,OACE,OAAOlB,EAAeC,IAAMD,EAAeY,GAAKI,EAAKhB,EAAeC,GAAKS,GAAQ,SAAUI,EAAII,GAC7F,OAAOd,EAAGU,EAAIF,EAAGM,EACnB,IAAKlB,EAAeY,GAAKF,GAAQ,SAAUG,EAAIK,GAC7C,OAAOd,EAAG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+uC,GAAL/uC,MACAwW,GAAKu4B,GAALv4B,MACAvW,GAAc8uC,GAAd9uC,eACAwhC,GAAcsN,GAAdtN,eACAvhC,GAAS6uC,GAAT7uC,UACAC,GAAa4uC,GAAb5uC,cACAC,GAAU2uC,GAAV3uC,WACAC,GAAc0uC,GAAd1uC,eACA8tC,GAAYY,GAAZZ,aACAC,GAAUW,GAAVX,WACA9tC,GAAYyuC,GAAZzuC,aACAxM,GAAOi7C,GAAPj7C,QACA4tC,GAAYqN,GAAZrN","x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,36,71,72,73,194,195,198,221,222,223,224,225,258]} \ No newline at end of file diff --git a/packages/analytics-js/__tests__/browser.test.ts b/packages/analytics-js/__tests__/browser.test.ts index cbbfa6c602..322d2b45eb 100644 --- a/packages/analytics-js/__tests__/browser.test.ts +++ b/packages/analytics-js/__tests__/browser.test.ts @@ -1,7 +1,7 @@ /* eslint-disable global-require */ import { loadingSnippet } from './nativeSdkLoader'; -const pathToSdk = '../dist/cdn/legacy/iife/rsa.min.js'; +const pathToSdk = '../dist/cdn/legacy/iife/rsa.js'; function wait(time: number) { return new Promise(resolve => { @@ -10,22 +10,29 @@ function wait(time: number) { } describe('Test suite for the SDK', () => { - const xhrMock: any = { - open: jest.fn(), - setRequestHeader: jest.fn(), - onload: jest.fn(), - onreadystatechange: jest.fn(), - responseText: JSON.stringify({ - source: { - config: {}, - id: 'id', - destinations: [], - }, + const fetchMock = jest.fn(() => + Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + source: { + config: {}, + id: 'id', + destinations: [], + }, + }), + text: () => + Promise.resolve( + JSON.stringify({ + source: { + config: {}, + id: 'id', + destinations: [], + }, + }), + ), }), - status: 200, - }; - - xhrMock.send = jest.fn(() => xhrMock.onload()); + ); const userId = 'jest-user-id'; const userTraits = { @@ -39,10 +46,17 @@ describe('Test suite for the SDK', () => { 'jest-group-trait-key-2': 'jest-group-trait-value-2', }; - const originalXMLHttpRequest = window.XMLHttpRequest; + const originalFetch = window.fetch; + + let skipBeforeEach = true; beforeEach(async () => { - window.XMLHttpRequest = jest.fn(() => xhrMock); + if (skipBeforeEach) { + return; + } + + // Mocking the fetch function + window.fetch = fetchMock; loadingSnippet(); @@ -57,14 +71,20 @@ describe('Test suite for the SDK', () => { window.rudderanalytics = undefined; - window.XMLHttpRequest = originalXMLHttpRequest; + window.fetch = originalFetch; }); it('should process the buffered API calls when SDK script is loaded', async () => { // Only done for this case to test the - // API calls queuing functionality - jest.resetModules(); + // buffered API calls queuing functionality + skipBeforeEach = false; + + // Mocking the fetch function + window.fetch = fetchMock; + + loadingSnippet(); rudderanalytics.page(); + require(pathToSdk); await wait(500); @@ -72,7 +92,7 @@ describe('Test suite for the SDK', () => { // one source config endpoint call and one implicit page call // Refer to above 'beforeEach' - expect(xhrMock.send).toHaveBeenCalledTimes(2); + expect(fetchMock).toHaveBeenCalledTimes(2); }); it('should make network requests when event APIs are invoked', () => { @@ -83,14 +103,14 @@ describe('Test suite for the SDK', () => { rudderanalytics.alias('new-jest-user', 'jest-user'); // one source config endpoint call and above API requests - expect(xhrMock.send).toHaveBeenCalledTimes(6); + expect(fetchMock).toHaveBeenCalledTimes(6); }); describe('getAnonymousId', () => { it('should return a new UUID when no prior persisted dat is present', () => { const anonId = rudderanalytics.getAnonymousId(); - const uuidRegEx = /^[a-z0-9]{8}-[a-z0-9]{4}-4[a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}$/; + const uuidRegEx = /^[\da-z]{8}-[\da-z]{4}-4[\da-z]{3}-[\da-z]{4}-[\da-z]{12}$/; expect(anonId).toMatch(uuidRegEx); }); @@ -105,7 +125,7 @@ describe('Test suite for the SDK', () => { }); describe('reset', () => { - it('should clear al the persisted data expect for anonymous ID when the flag is not set', () => { + it('should clear all the persisted data expect for anonymous ID when the flag is not set', () => { // Make identify and group API calls to let the SDK persist // user (ID and traits) and group data (ID and traits) rudderanalytics.identify(userId, userTraits); diff --git a/packages/analytics-js/__tests__/components/capabilitiesManager/detection/adBlockers.test.ts b/packages/analytics-js/__tests__/components/capabilitiesManager/detection/adBlockers.test.ts index 75c1a1b462..2b9201f4f0 100644 --- a/packages/analytics-js/__tests__/components/capabilitiesManager/detection/adBlockers.test.ts +++ b/packages/analytics-js/__tests__/components/capabilitiesManager/detection/adBlockers.test.ts @@ -3,7 +3,7 @@ import { detectAdBlockers } from '../../../../src/components/capabilitiesManager import { state, resetState } from '../../../../src/state'; let errObj; -let xhrObj; +let responseObj; jest.mock('../../../../src/services/HttpClient/HttpClient', () => { const originalModule = jest.requireActual('../../../../src/services/HttpClient/HttpClient'); @@ -13,10 +13,10 @@ jest.mock('../../../../src/services/HttpClient/HttpClient', () => { ...originalModule, HttpClient: jest.fn().mockImplementation(() => ({ setAuthHeader: jest.fn(), - getAsyncData: jest.fn().mockImplementation(({ url, callback }) => { + request: jest.fn().mockImplementation(({ url, callback }) => { callback(undefined, { error: errObj, - xhr: xhrObj, + response: responseObj, }); }), })), @@ -32,8 +32,8 @@ describe('detectAdBlockers', () => { state.lifecycle.sourceConfigUrl.value = 'https://example.com/some/path/'; errObj = new Error('Request blocked'); - xhrObj = { - responseURL: 'https://example.com/some/path/?view=ad', + responseObj = { + redirected: false, }; detectAdBlockers(); @@ -48,8 +48,8 @@ describe('detectAdBlockers', () => { state.lifecycle.sourceConfigUrl.value = 'https://example.com/some/path/'; errObj = undefined; - xhrObj = { - responseURL: 'data:text/css;charset=UTF-8;base64,dGVtcA==', + responseObj = { + redirected: true, }; detectAdBlockers(); @@ -64,8 +64,8 @@ describe('detectAdBlockers', () => { state.lifecycle.sourceConfigUrl.value = 'https://example.com/some/path/'; errObj = undefined; - xhrObj = { - responseURL: 'https://example.com/some/path/?view=ad', + responseObj = { + redirected: false, }; detectAdBlockers(); diff --git a/packages/analytics-js/__tests__/components/core/Analytics.test.ts b/packages/analytics-js/__tests__/components/core/Analytics.test.ts index e85709a4d6..5e8611755f 100644 --- a/packages/analytics-js/__tests__/components/core/Analytics.test.ts +++ b/packages/analytics-js/__tests__/components/core/Analytics.test.ts @@ -180,7 +180,7 @@ describe('Core - Analytics', () => { const onReadySpy = jest.spyOn(analytics, 'onReady'); state.lifecycle.status.value = 'ready'; analytics.onDestinationsReady(); - expect(onReadySpy).not.toBeCalled(); + expect(onReadySpy).not.toHaveBeenCalled(); onReadySpy.mockRestore(); }); diff --git a/packages/analytics-js/__tests__/components/eventManager/EventManager.test.ts b/packages/analytics-js/__tests__/components/eventManager/EventManager.test.ts index bd76d974b4..4a96c67581 100644 --- a/packages/analytics-js/__tests__/components/eventManager/EventManager.test.ts +++ b/packages/analytics-js/__tests__/components/eventManager/EventManager.test.ts @@ -26,7 +26,7 @@ describe('EventManager', () => { it('should initialize on init', () => { const eventRepositoryInitSpy = jest.spyOn(eventRepository, 'init'); eventManager.init(); - expect(eventRepositoryInitSpy).toBeCalled(); + expect(eventRepositoryInitSpy).toHaveBeenCalled(); eventRepositoryInitSpy.mockRestore(); }); @@ -43,7 +43,7 @@ describe('EventManager', () => { }, }); - expect(mockErrorHandler.onError).toBeCalledWith( + expect(mockErrorHandler.onError).toHaveBeenCalledWith( new Error('Failed to generate the event object.'), 'EventManager', undefined, @@ -70,7 +70,7 @@ describe('EventManager', () => { it('should resume on resume', () => { const eventRepositoryResumeSpy = jest.spyOn(eventRepository, 'resume'); eventManager.resume(); - expect(eventRepositoryResumeSpy).toBeCalled(); + expect(eventRepositoryResumeSpy).toHaveBeenCalled(); eventRepositoryResumeSpy.mockRestore(); }); diff --git a/packages/analytics-js/__tests__/components/eventRepository/EventRepository.test.ts b/packages/analytics-js/__tests__/components/eventRepository/EventRepository.test.ts index 4a3457b9d9..a527c59305 100644 --- a/packages/analytics-js/__tests__/components/eventRepository/EventRepository.test.ts +++ b/packages/analytics-js/__tests__/components/eventRepository/EventRepository.test.ts @@ -130,7 +130,7 @@ describe('EventRepository', () => { state.nativeDestinations.clientDestinationsReady.value = true; - expect(mockDestinationsEventsQueue.start).toBeCalledTimes(1); + expect(mockDestinationsEventsQueue.start).toHaveBeenCalledTimes(1); }); it('should start the dataplane events queue when no hybrid destinations are present', () => { @@ -157,7 +157,7 @@ describe('EventRepository', () => { eventRepository.init(); - expect(mockDataplaneEventsQueue.start).toBeCalledTimes(1); + expect(mockDataplaneEventsQueue.start).toHaveBeenCalledTimes(1); }); it('should start the dataplane events queue when hybrid destinations are present and bufferDataPlaneEventsUntilReady is false', () => { @@ -169,7 +169,7 @@ describe('EventRepository', () => { eventRepository.init(); - expect(mockDataplaneEventsQueue.start).toBeCalledTimes(1); + expect(mockDataplaneEventsQueue.start).toHaveBeenCalledTimes(1); }); it('should start the dataplane events queue when hybrid destinations are present and bufferDataPlaneEventsUntilReady is true and client destinations are ready after some time', done => { @@ -182,11 +182,11 @@ describe('EventRepository', () => { eventRepository.init(); - expect(mockDataplaneEventsQueue.start).not.toBeCalled(); + expect(mockDataplaneEventsQueue.start).not.toHaveBeenCalled(); setTimeout(() => { state.nativeDestinations.clientDestinationsReady.value = true; - expect(mockDataplaneEventsQueue.start).toBeCalledTimes(1); + expect(mockDataplaneEventsQueue.start).toHaveBeenCalledTimes(1); done(); }, 500); }); @@ -201,10 +201,10 @@ describe('EventRepository', () => { eventRepository.init(); - expect(mockDataplaneEventsQueue.start).not.toBeCalled(); + expect(mockDataplaneEventsQueue.start).not.toHaveBeenCalled(); setTimeout(() => { - expect(mockDataplaneEventsQueue.start).toBeCalledTimes(1); + expect(mockDataplaneEventsQueue.start).toHaveBeenCalledTimes(1); done(); }, state.loadOptions.value.dataPlaneEventsBufferTimeout + 50); }); @@ -250,8 +250,8 @@ describe('EventRepository', () => { const mockEventCallback = jest.fn(); eventRepository.enqueue(testEvent, mockEventCallback); - expect(mockEventCallback).toBeCalledTimes(1); - expect(mockEventCallback).toBeCalledWith({ + expect(mockEventCallback).toHaveBeenCalledTimes(1); + expect(mockEventCallback).toHaveBeenCalledWith({ ...testEvent, integrations: { All: true }, }); @@ -275,8 +275,8 @@ describe('EventRepository', () => { }); eventRepository.enqueue(testEvent, mockEventCallback); - expect(mockErrorHandler.onError).toBeCalledTimes(1); - expect(mockErrorHandler.onError).toBeCalledWith( + expect(mockErrorHandler.onError).toHaveBeenCalledTimes(1); + expect(mockErrorHandler.onError).toHaveBeenCalledWith( new Error('test error'), 'EventRepository', 'API Callback Invocation Failed', @@ -299,7 +299,7 @@ describe('EventRepository', () => { eventRepository.init(); - expect(mockDataplaneEventsQueue.start).not.toBeCalled(); + expect(mockDataplaneEventsQueue.start).not.toHaveBeenCalled(); }); describe('resume', () => { @@ -308,7 +308,7 @@ describe('EventRepository', () => { eventRepository.init(); eventRepository.resume(); - expect(mockDataplaneEventsQueue.start).toBeCalled(); + expect(mockDataplaneEventsQueue.start).toHaveBeenCalled(); }); it('should clear the events queue if discardPreConsentEvents is set to true', () => { @@ -320,8 +320,8 @@ describe('EventRepository', () => { eventRepository.resume(); - expect(mockDataplaneEventsQueue.clear).toBeCalled(); - expect(mockDestinationsEventsQueue.clear).toBeCalled(); + expect(mockDataplaneEventsQueue.clear).toHaveBeenCalled(); + expect(mockDestinationsEventsQueue.clear).toHaveBeenCalled(); }); }); }); diff --git a/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts b/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts index b64f88932b..910b819289 100644 --- a/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts +++ b/packages/analytics-js/__tests__/components/userSessionManager/UserSessionManager.test.ts @@ -1770,16 +1770,16 @@ describe('User session manager', () => { domain: 'example.com', samesite: 'Lax', }; - const getAsyncDataSpy = jest.spyOn(defaultHttpClient, 'getAsyncData'); + const requestSpy = jest.spyOn(defaultHttpClient, 'request'); userSessionManager.makeRequestToSetCookie( [{ name: 'key', value: 'encrypted_sample_cookie_value_1234' }], () => {}, ); - expect(getAsyncDataSpy).toHaveBeenCalledWith({ + expect(requestSpy).toHaveBeenCalledWith({ url: `https://dummy.dataplane.host.com/rsaRequest`, options: { method: 'POST', - data: JSON.stringify({ + body: JSON.stringify({ reqType: 'setCookies', workspaceId: 'sample_workspaceId', data: { diff --git a/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts b/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts index c56a3dfa62..274e075947 100644 --- a/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts +++ b/packages/analytics-js/__tests__/services/HttpClient/HttpClient.test.ts @@ -1,4 +1,5 @@ -import type { XHRResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; +import type { IResponseDetails } from '@rudderstack/analytics-js-common/types/HttpClient'; +import { HttpClientError } from '../../../src/services/HttpClient/utils'; import { HttpClient } from '../../../src/services/HttpClient'; import { defaultErrorHandler } from '../../../src/services/ErrorHandler'; import { defaultLogger } from '../../../src/services/Logger'; @@ -38,7 +39,7 @@ describe('HttpClient', () => { }); beforeEach(() => { - clientInstance = new HttpClient(defaultErrorHandler, defaultLogger); + clientInstance = new HttpClient('fetch', defaultErrorHandler, defaultLogger); }); afterEach(() => { @@ -50,32 +51,32 @@ describe('HttpClient', () => { server.close(); }); - it('should getAsyncData expecting raw response', done => { + it('should request expecting raw response', done => { const callback = (response: any) => { expect(response).toStrictEqual('{"raw": "sample"}'); done(); }; - clientInstance.getAsyncData({ + clientInstance.request({ callback, url: `${dummyDataplaneHost}/rawSample`, isRawResponse: true, }); }); - it('should getAsyncData expecting json response', done => { + it('should request expecting json response', done => { const callback = (response: any) => { - expect(response).toStrictEqual({ json: 'sample' }); + expect(response).toEqual({ raw: 'sample' }); done(); }; - clientInstance.getAsyncData({ + clientInstance.request({ callback, - url: `${dummyDataplaneHost}/jsonSample`, + url: `${dummyDataplaneHost}/rawSample`, }); }); - it('should fire and forget getAsyncData', async () => { - const response = await clientInstance.getAsyncData({ - url: `${dummyDataplaneHost}/jsonSample`, + it('should fire and forget request', async () => { + const response = await clientInstance.request({ + url: `${dummyDataplaneHost}/rawSample`, }); expect(response).toBeUndefined(); }); @@ -90,51 +91,51 @@ describe('HttpClient', () => { expect(clientInstance.basicAuthHeader).toStrictEqual('Basic dummyWriteKey'); }); - it('should set auth header', () => { + it('should reset auth header', () => { clientInstance.setAuthHeader('dummyWriteKey', true); clientInstance.resetAuthHeader(); expect(clientInstance.basicAuthHeader).toBeUndefined(); }); - it('should getAsyncData with auth header expecting json response', done => { + it('should request with auth header expecting json response', done => { const callback = (response: any) => { - expect(response).toStrictEqual({ json: 'sample' }); + expect(response).toEqual({ raw: 'sample' }); done(); }; clientInstance.setAuthHeader('dummyWriteKey'); - clientInstance.getAsyncData({ + clientInstance.request({ callback, - url: `${dummyDataplaneHost}/jsonSample`, + url: `${dummyDataplaneHost}/rawSample`, }); }); - it('should handle 400 range errors in getAsyncData requests', done => { - const callback = (response: any, reject: XHRResponseDetails) => { - const errResult = new Error( - 'The request failed with status: 404, Not Found for URL: https://dummy.dataplane.host.com/404ErrorSample.', + it('should handle 400 range errors in request requests', done => { + const callback = (response: any, details: IResponseDetails) => { + const errResult = new HttpClientError( + 'The request failed with status 404: Not Found (), for URL: https://dummy.dataplane.host.com/404ErrorSample.', ); - expect(reject.error).toEqual(errResult); + expect(details.error).toEqual(errResult); expect(defaultErrorHandler.onError).toHaveBeenCalledTimes(1); expect(defaultErrorHandler.onError).toHaveBeenCalledWith(errResult, 'HttpClient'); done(); }; - clientInstance.getAsyncData({ + clientInstance.request({ callback, url: `${dummyDataplaneHost}/404ErrorSample`, }); }); - it('should handle 500 range errors in getAsyncData requests', done => { - const callback = (response: any, reject: XHRResponseDetails) => { + it('should handle 500 range errors in request requests', done => { + const callback = (response: any, details: IResponseDetails) => { const errResult = new Error( - 'The request failed with status: 500, Internal Server Error for URL: https://dummy.dataplane.host.com/500ErrorSample.', + 'The request failed with status 500: Internal Server Error (), for URL: https://dummy.dataplane.host.com/500ErrorSample.', ); - expect(reject.error).toEqual(errResult); + expect(details.error).toEqual(errResult); expect(defaultErrorHandler.onError).toHaveBeenCalledTimes(1); expect(defaultErrorHandler.onError).toHaveBeenCalledWith(errResult, 'HttpClient'); done(); }; - clientInstance.getAsyncData({ + clientInstance.request({ callback, url: `${dummyDataplaneHost}/500ErrorSample`, }); @@ -152,7 +153,7 @@ describe('HttpClient', () => { ); done(); }; - clientInstance.getAsyncData({ + clientInstance.request({ callback, url: `${dummyDataplaneHost}/brokenJsonSample`, }); @@ -168,7 +169,7 @@ describe('HttpClient', () => { ); done(); }; - clientInstance.getAsyncData({ + clientInstance.request({ callback, url: `${dummyDataplaneHost}/emptyJsonSample`, }); @@ -184,11 +185,11 @@ describe('HttpClient', () => { ); done(); }; - clientInstance.getAsyncData({ + clientInstance.request({ callback, url: `${dummyDataplaneHost}/nonStringifiableDataSample`, options: { - data: { + body: { a: 1, b: BigInt(1), }, diff --git a/packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts b/packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts index a28fffa932..1c1724e7b9 100644 --- a/packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts +++ b/packages/analytics-js/__tests__/services/StoreManager/StoreManager.test.ts @@ -202,7 +202,7 @@ describe('StoreManager', () => { state.loadOptions.value.storage.entries = loadOptionWithEntry; storeManager.initClientDataStores(); expect(state.storage.entries.value).toEqual(entriesWithInMemoryFallback); - expect(logger.warn).toBeCalledTimes(8); + expect(logger.warn).toHaveBeenCalledTimes(8); }); it('should construct the appropriate storage entry state if the pre-consent storage strategy is set to none', () => { diff --git a/packages/analytics-js/package.json b/packages/analytics-js/package.json index 03053e2ca2..fcc68bfdc1 100644 --- a/packages/analytics-js/package.json +++ b/packages/analytics-js/package.json @@ -112,6 +112,7 @@ "build": "npm run build:browser && npm run build:package", "build:modern": "npm run build:browser:modern && npm run build:package:modern", "build:browser": "rollup -c --environment VERSION:$npm_package_version,UGLIFY,PROD_DEBUG,ENV:prod", + "build:browser:dev": "rollup -c --environment PROD_DEBUG", "build:browser:modern": "BROWSERSLIST_ENV=modern npm run build:browser", "build:package": "npm run build:npm && npm run build:npm:bundled && npm run build:npm:content-script", "build:package:modern": "npm run build:npm:modern && npm run build:npm:bundled:modern && npm run build:npm:content-script:modern", @@ -121,9 +122,8 @@ "build:npm:bundled:modern": "BUNDLED_PLUGINS=all npm run build:npm:modern", "build:npm:content-script": "BUNDLED_PLUGINS=all NO_EXTERNAL_HOST=true npm run build:npm", "build:npm:content-script:modern": "BUNDLED_PLUGINS=all NO_EXTERNAL_HOST=true npm run build:npm:modern", - "build:browser:test": "ONLY_IIFE=true npm run build:browser && sed 's/var rudderanalytics/rudderanalytics/g' dist/cdn/legacy/iife/rsa.min.js > __mocks__/cdnSDK.js", - "test": "npm run build:browser:test && nx test --maxWorkers=50%", - "test:ci": "npm run build:browser:test && nx test --configuration=ci --runInBand --maxWorkers=1 --forceExit", + "test": "nx test", + "test:ci": "nx test --configuration=ci", "check:lint": "nx lint", "check:lint:ci": "nx lint --configuration=ci", "check:size:build": "npm run build:browser && npm run build:browser:modern && npm run build:package && npm run build:package:modern", diff --git a/packages/analytics-js/project.json b/packages/analytics-js/project.json index 664c116338..0fefbeb195 100644 --- a/packages/analytics-js/project.json +++ b/packages/analytics-js/project.json @@ -5,13 +5,6 @@ "projectType": "library", "tags": ["type:sdk", "scope:analytics-v3"], "targets": { - "prepare-test-mocks": { - "executor": "nx:run-commands", - "options": { - "command": "sed 's/var rudderanalytics/rudderanalytics/g' packages/analytics-js/dist/cdn/legacy/iife/rsa.min.js > packages/analytics-js/__mocks__/cdnSDK.js" - }, - "dependsOn": ["build:browser"] - }, "test": { "executor": "@nx/jest:jest", "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], @@ -28,7 +21,7 @@ "codeCoverage": true } }, - "dependsOn": ["prepare-test-mocks"] + "dependsOn": ["build:browser:dev"] }, "lint": { "executor": "@nx/eslint:lint", diff --git a/packages/analytics-js/src/components/capabilitiesManager/detection/adBlockers.ts b/packages/analytics-js/src/components/capabilitiesManager/detection/adBlockers.ts index 204140ef4c..76e8ec8a32 100644 --- a/packages/analytics-js/src/components/capabilitiesManager/detection/adBlockers.ts +++ b/packages/analytics-js/src/components/capabilitiesManager/detection/adBlockers.ts @@ -13,24 +13,21 @@ const detectAdBlockers = (errorHandler?: IErrorHandler, logger?: ILogger): void const baseUrl = new URL(state.lifecycle.sourceConfigUrl.value as string); const url = `${baseUrl.origin}${baseUrl.pathname}?view=ad`; - const httpClient = new HttpClient(errorHandler, logger); + const httpClient = new HttpClient('fetch', errorHandler, logger); httpClient.setAuthHeader(state.lifecycle.writeKey.value as string); - httpClient.getAsyncData({ + httpClient.request({ url, options: { // We actually don't need the response from the request, so we are using HEAD method: 'HEAD', - headers: { - 'Content-Type': undefined, - }, }, isRawResponse: true, callback: (result, details) => { // not ad blocked if the request is successful or it is not internally redirected on the client side // Often adblockers instead of blocking the request, they redirect it to an internal URL state.capabilities.isAdBlocked.value = - details?.error !== undefined || details?.xhr?.responseURL !== url; + details?.error !== undefined || details.response?.redirected === true; }, }); }; diff --git a/packages/analytics-js/src/components/configManager/ConfigManager.ts b/packages/analytics-js/src/components/configManager/ConfigManager.ts index 520ed46988..87c8a57b25 100644 --- a/packages/analytics-js/src/components/configManager/ConfigManager.ts +++ b/packages/analytics-js/src/components/configManager/ConfigManager.ts @@ -1,7 +1,7 @@ /* eslint-disable class-methods-use-this */ import type { IHttpClient, - XHRResponseDetails, + IResponseDetails, } from '@rudderstack/analytics-js-common/types/HttpClient'; import { batch, effect } from '@preact/signals-core'; import { isFunction, isString } from '@rudderstack/analytics-js-common/utilities/checks'; @@ -130,8 +130,8 @@ class ConfigManager implements IConfigManager { * A callback function that is executed once we fetch the source config response. * Use to construct and store information that are dependent on the sourceConfig. */ - processConfig(response?: SourceConfigResponse | string, details?: XHRResponseDetails) { - // TODO: add retry logic with backoff based on rejectionDetails.xhr.status + processConfig(response?: SourceConfigResponse | string | null, details?: IResponseDetails) { + // TODO: add retry logic with backoff based on details // We can use isErrRetryable utility method if (!response) { this.onError(SOURCE_CONFIG_FETCH_ERROR(details?.error)); @@ -214,13 +214,10 @@ class ConfigManager implements IConfigManager { } } else { // Fetch source configuration from the configured URL - this.httpClient.getAsyncData({ + this.httpClient.request({ url: state.lifecycle.sourceConfigUrl.value as string, options: { method: 'GET', - headers: { - 'Content-Type': undefined, - }, }, callback: this.processConfig, }); diff --git a/packages/analytics-js/src/components/eventRepository/EventRepository.ts b/packages/analytics-js/src/components/eventRepository/EventRepository.ts index 0964d58aa9..13db8110e7 100644 --- a/packages/analytics-js/src/components/eventRepository/EventRepository.ts +++ b/packages/analytics-js/src/components/eventRepository/EventRepository.ts @@ -57,7 +57,7 @@ class EventRepository implements IEventRepository { this.pluginsManager = pluginsManager; this.errorHandler = errorHandler; this.logger = logger; - this.httpClient = new HttpClient(errorHandler, logger); + this.httpClient = new HttpClient('fetch', errorHandler, logger); this.storeManager = storeManager; this.onError = this.onError.bind(this); } diff --git a/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts b/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts index 61c17d5431..0fd7af1cd2 100644 --- a/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts +++ b/packages/analytics-js/src/components/userSessionManager/UserSessionManager.ts @@ -320,11 +320,11 @@ class UserSessionManager implements IUserSessionManager { encryptedCookieData: EncryptedCookieData[], callback: AsyncRequestCallback, ) { - this.httpClient?.getAsyncData({ + this.httpClient?.request({ url: state.serverCookies.dataServiceUrl.value as string, options: { method: 'POST', - data: stringifyWithoutCircular({ + body: stringifyWithoutCircular({ reqType: 'setCookies', workspaceId: state.source.value?.workspaceId, data: { @@ -359,7 +359,7 @@ class UserSessionManager implements IUserSessionManager { if (encryptedCookieData.length > 0) { // make request to data service to set the cookie from server side this.makeRequestToSetCookie(encryptedCookieData, (res, details) => { - if (details?.xhr?.status === 200) { + if (details?.response?.status === 200) { cookiesData.forEach(cData => { const cookieValue = store?.get(cData.name); const before = stringifyWithoutCircular(cData.value, false, []); @@ -372,7 +372,7 @@ class UserSessionManager implements IUserSessionManager { } }); } else { - this.logger?.error(DATA_SERVER_REQUEST_FAIL_ERROR(details?.xhr?.status)); + this.logger?.error(DATA_SERVER_REQUEST_FAIL_ERROR(details?.response?.status)); cookiesData.forEach(each => { if (cb) { cb(each.name, each.value); diff --git a/packages/analytics-js/src/constants/logMessages.ts b/packages/analytics-js/src/constants/logMessages.ts index 6dfbe1a023..ddbe56309f 100644 --- a/packages/analytics-js/src/constants/logMessages.ts +++ b/packages/analytics-js/src/constants/logMessages.ts @@ -14,7 +14,7 @@ const SOURCE_CONFIG_OPTION_ERROR = `"getSourceConfig" must be a function. Please const DATA_PLANE_URL_ERROR = `Failed to load the SDK as the data plane URL could not be determined. Please check that the data plane URL is set correctly and try again.`; const SOURCE_CONFIG_RESOLUTION_ERROR = `Unable to process/parse source configuration response.`; const SOURCE_DISABLED_ERROR = `The source is disabled. Please enable the source in the dashboard to send events.`; -const XHR_PAYLOAD_PREP_ERROR = `Failed to prepare data for the request.`; +const PAYLOAD_PREP_ERROR = `Failed to prepare data for the request.`; const EVENT_OBJECT_GENERATION_ERROR = `Failed to generate the event object.`; const PLUGIN_EXT_POINT_MISSING_ERROR = `Failed to invoke plugin because the extension point name is missing.`; const PLUGIN_EXT_POINT_INVALID_ERROR = `Failed to invoke plugin because the extension point name is invalid.`; @@ -75,18 +75,21 @@ const DATA_PLANE_URL_VALIDATION_ERROR = (dataPlaneUrl: string | undefined): stri const READY_API_CALLBACK_ERROR = (context: string): string => `${context}${LOG_CONTEXT_SEPARATOR}The callback is not a function.`; -const XHR_DELIVERY_ERROR = ( +const DELIVERY_ERROR = ( prefix: string, status: number, statusText: string, url: string | URL, -): string => `${prefix} with status: ${status}, ${statusText} for URL: ${url}.`; + e?: ProgressEvent | undefined, +): string => `${prefix} with status ${status}: ${statusText} (${e?.type ?? ''}), for URL: ${url}.`; -const XHR_REQUEST_ERROR = ( +const REQUEST_ERROR = ( prefix: string, - e: ProgressEvent | undefined, url: string | URL, -): string => `${prefix} due to timeout or no connection (${e ? e.type : ''}) for URL: ${url}.`; + timeout: number, + e?: ProgressEvent | undefined, +): string => + `${prefix} due to timeout after ${timeout}ms or no connection (${e?.type ?? ''}) for URL: ${url}.`; const XHR_SEND_ERROR = (prefix: string, url: string | URL): string => `${prefix} for URL: ${url}`; @@ -289,10 +292,10 @@ export { WRITE_KEY_VALIDATION_ERROR, DATA_PLANE_URL_VALIDATION_ERROR, READY_API_CALLBACK_ERROR, - XHR_DELIVERY_ERROR, - XHR_REQUEST_ERROR, + DELIVERY_ERROR, + REQUEST_ERROR, XHR_SEND_ERROR, - XHR_PAYLOAD_PREP_ERROR, + PAYLOAD_PREP_ERROR, STORE_DATA_SAVE_ERROR, STORE_DATA_FETCH_ERROR, EVENT_OBJECT_GENERATION_ERROR, diff --git a/packages/analytics-js/src/constants/timeouts.ts b/packages/analytics-js/src/constants/timeouts.ts index f543cebc3f..72c2db3ffe 100644 --- a/packages/analytics-js/src/constants/timeouts.ts +++ b/packages/analytics-js/src/constants/timeouts.ts @@ -1,4 +1,4 @@ -const DEFAULT_XHR_TIMEOUT_MS = 10 * 1000; // 10 seconds +const DEFAULT_REQ_TIMEOUT_MS = 10 * 1000; // 10 seconds const DEFAULT_COOKIE_MAX_AGE_MS = 31536000 * 1000; // 1 year const DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes const MIN_SESSION_TIMEOUT_MS = 10 * 1000; // 10 seconds @@ -6,7 +6,7 @@ const DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS = 10 * 1000; // 10 seconds const DEBOUNCED_TIMEOUT_MS = 250; // 250 milliseconds export { - DEFAULT_XHR_TIMEOUT_MS, + DEFAULT_REQ_TIMEOUT_MS, DEFAULT_COOKIE_MAX_AGE_MS, DEFAULT_SESSION_TIMEOUT_MS, MIN_SESSION_TIMEOUT_MS, diff --git a/packages/analytics-js/src/services/HttpClient/HttpClient.ts b/packages/analytics-js/src/services/HttpClient/HttpClient.ts index f723089871..449b455e76 100644 --- a/packages/analytics-js/src/services/HttpClient/HttpClient.ts +++ b/packages/analytics-js/src/services/HttpClient/HttpClient.ts @@ -1,18 +1,37 @@ -import { isFunction } from '@rudderstack/analytics-js-common/utilities/checks'; +import { isFunction, isNull } from '@rudderstack/analytics-js-common/utilities/checks'; import type { IAsyncRequestConfig, + IFetchRequestOptions, IHttpClient, + IHttpClientError, + IRequestOptions, IXHRRequestOptions, - XHRResponseDetails, } from '@rudderstack/analytics-js-common/types/HttpClient'; import type { IErrorHandler } from '@rudderstack/analytics-js-common/types/ErrorHandler'; import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; import { toBase64 } from '@rudderstack/analytics-js-common/utilities/string'; import { HTTP_CLIENT } from '@rudderstack/analytics-js-common/constants/loggerContexts'; +import type { TransportType } from '@rudderstack/analytics-js-common/types/LoadOptions'; +import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; +import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object'; +import { clone } from 'ramda'; +import { DEFAULT_REQ_TIMEOUT_MS } from '../../constants/timeouts'; +import { PAYLOAD_PREP_ERROR } from '../../constants/logMessages'; import { defaultErrorHandler } from '../ErrorHandler'; import { defaultLogger } from '../Logger'; -import { responseTextToJson } from './xhr/xhrResponseHandler'; -import { createXhrRequestOptions, xhrRequest } from './xhr/xhrRequestHandler'; +import { HttpClientError } from './utils'; +import { makeXHRRequest } from './xhr'; +import { makeFetchRequest } from './fetch'; +import { makeBeaconRequest } from './beacon'; + +const DEFAULT_REQUEST_OPTIONS: Partial = { + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json;charset=UTF-8', + }, + timeout: DEFAULT_REQ_TIMEOUT_MS, + method: 'GET', +}; // TODO: should we add any debug level loggers? @@ -23,8 +42,21 @@ class HttpClient implements IHttpClient { errorHandler?: IErrorHandler; logger?: ILogger; basicAuthHeader?: string; + transportFn: (url: string | URL, options: any) => Promise; - constructor(errorHandler?: IErrorHandler, logger?: ILogger) { + constructor(transportType: TransportType, errorHandler?: IErrorHandler, logger?: ILogger) { + switch (transportType) { + case 'xhr': + this.transportFn = makeXHRRequest; + break; + case 'beacon': + this.transportFn = makeBeaconRequest; + break; + case 'fetch': + default: + this.transportFn = makeFetchRequest; + break; + } this.errorHandler = errorHandler; this.logger = logger; this.onError = this.onError.bind(this); @@ -33,32 +65,82 @@ class HttpClient implements IHttpClient { /** * Implement requests in a non-blocking way */ - getAsyncData(config: IAsyncRequestConfig) { - const { callback, url, options, timeout, isRawResponse } = config; + request(config: IAsyncRequestConfig) { + const { callback, url, options, isRawResponse } = config; const isFireAndForget = !isFunction(callback); - xhrRequest( - url, - createXhrRequestOptions(options as IXHRRequestOptions, this.basicAuthHeader), - timeout, - this.logger, - ) - .then((data: XHRResponseDetails) => { + const finalOptions = mergeDeepRight(DEFAULT_REQUEST_OPTIONS, options || {}) as IRequestOptions; + + if (finalOptions.body && !finalOptions.sendRawData) { + const payload = stringifyWithoutCircular(finalOptions.body, false, [], this.logger); + // return and don't process further if the payload could not be stringified + if (isNull(payload)) { + const err = new HttpClientError(PAYLOAD_PREP_ERROR); + this.onError(err); + if (!isFireAndForget) { + callback(err.responseBody, { + error: err, + url, + options: finalOptions, + }); + } + return; + } + + finalOptions.body = payload; + } + + if ((finalOptions as IXHRRequestOptions | IFetchRequestOptions).headers) { + (finalOptions as IXHRRequestOptions | IFetchRequestOptions).headers = mergeDeepRight( + { + Authorization: this.basicAuthHeader, + }, + (finalOptions as IXHRRequestOptions | IFetchRequestOptions).headers ?? {}, + ); + } + + this.transportFn(url, finalOptions) + .then((response: Response) => { if (!isFireAndForget) { - callback( - isRawResponse ? data.response : responseTextToJson(data.response, this.onError), - data, - ); + const finalDataPromise = isRawResponse ? response.text() : response.json(); + finalDataPromise + .then(data => { + callback(data, { + response, + url, + options: finalOptions, + }); + }) + .catch((err: Error) => { + const finalError = clone(err); + finalError.message = `Failed to parse response data: ${err.message}`; + + this.onError(finalError); + + callback(undefined, { + error: finalError, + url, + options: finalOptions, + }); + }); } }) - .catch((data: XHRResponseDetails) => { - this.onError(data.error ?? data); + .catch((error: IHttpClientError) => { + this.onError(error); if (!isFireAndForget) { - callback(undefined, data); + callback(error.responseBody, { + error, + url, + options: finalOptions, + }); } }); } + getAsyncData(config: IAsyncRequestConfig) { + this.request(config); + } + /** * Handle errors */ @@ -86,6 +168,6 @@ class HttpClient implements IHttpClient { } } -const defaultHttpClient = new HttpClient(defaultErrorHandler, defaultLogger); +const defaultHttpClient = new HttpClient('fetch', defaultErrorHandler, defaultLogger); export { HttpClient, defaultHttpClient }; diff --git a/packages/analytics-js/src/services/HttpClient/beacon/index.ts b/packages/analytics-js/src/services/HttpClient/beacon/index.ts new file mode 100644 index 0000000000..615e7cbeb2 --- /dev/null +++ b/packages/analytics-js/src/services/HttpClient/beacon/index.ts @@ -0,0 +1,16 @@ +import type { IBeaconRequestOptions } from '@rudderstack/analytics-js-common/types/HttpClient'; +import { HttpClientError } from '../utils'; + +const makeBeaconRequest = ( + url: string | URL, + options: IBeaconRequestOptions, +): Promise => { + const success = navigator.sendBeacon(url, options.body); + if (!success) { + return Promise.reject(new HttpClientError('Beacon request failed')); + } + + return Promise.resolve(new Response(null, { status: 204 })); +}; + +export { makeBeaconRequest }; diff --git a/packages/analytics-js/src/services/HttpClient/fetch/index.ts b/packages/analytics-js/src/services/HttpClient/fetch/index.ts new file mode 100644 index 0000000000..ca813d1519 --- /dev/null +++ b/packages/analytics-js/src/services/HttpClient/fetch/index.ts @@ -0,0 +1,51 @@ +import type { IFetchRequestOptions } from '@rudderstack/analytics-js-common/types/HttpClient'; +import { FAILED_REQUEST_ERR_MSG_PREFIX } from '@rudderstack/analytics-js-common/constants/errors'; +import { clone } from 'ramda'; +import { DELIVERY_ERROR, REQUEST_ERROR } from '../../../constants/logMessages'; +import { HttpClientError } from '../utils'; + +const makeFetchRequest = (url: string | URL, options: IFetchRequestOptions): Promise => { + const controller = new AbortController(); + const { signal } = controller; + const fetchOptions: RequestInit = { ...options, signal }; + + const fetchPromise = (globalThis as typeof window) + .fetch(url, fetchOptions) + .then(response => { + if (!response.ok) { + return response.text().then(body => { + throw new HttpClientError( + DELIVERY_ERROR( + FAILED_REQUEST_ERR_MSG_PREFIX, + response.status, + response.statusText, + url, + ), + response.status, + response.statusText, + body, + ); + }); + } + return response; + }) + .catch(err => { + if (err.name === 'HttpClientError') { + throw err; + } + + const clonedErr = clone(err); + clonedErr.message = `${REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, url, options.timeout as number)}: ${err.message}`; + + throw clonedErr; + }); + + // Implement the timeout logic + if (options.timeout) { + const timeoutId = setTimeout(() => controller.abort(), options.timeout); + return fetchPromise.finally(() => clearTimeout(timeoutId)); + } + return fetchPromise; +}; + +export { makeFetchRequest }; diff --git a/packages/analytics-js/src/services/HttpClient/fetch/requestHandler.ts b/packages/analytics-js/src/services/HttpClient/fetch/requestHandler.ts deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/analytics-js/src/services/HttpClient/index.ts b/packages/analytics-js/src/services/HttpClient/index.ts index 12f5da833b..44c188ae42 100644 --- a/packages/analytics-js/src/services/HttpClient/index.ts +++ b/packages/analytics-js/src/services/HttpClient/index.ts @@ -1,7 +1 @@ export { HttpClient, defaultHttpClient } from './HttpClient'; -export { - createXhrRequestOptions, - xhrRequest, - DEFAULT_XHR_REQUEST_OPTIONS, -} from './xhr/xhrRequestHandler'; -export { responseTextToJson } from './xhr/xhrResponseHandler'; diff --git a/packages/analytics-js/src/services/HttpClient/utils.ts b/packages/analytics-js/src/services/HttpClient/utils.ts new file mode 100644 index 0000000000..9525524b3e --- /dev/null +++ b/packages/analytics-js/src/services/HttpClient/utils.ts @@ -0,0 +1,17 @@ +import type { IHttpClientError } from '@rudderstack/analytics-js-common/types/HttpClient'; + +class HttpClientError extends Error implements IHttpClientError { + public status?: number; + public statusText?: string; + public responseBody?: string | null; + + constructor(message: string, status?: number, statusText?: string, responseBody?: string | null) { + super(message); + this.name = 'HttpClientError'; + this.status = status; + this.statusText = statusText; + this.responseBody = responseBody; + } +} + +export { HttpClientError }; diff --git a/packages/analytics-js/src/services/HttpClient/xhr/index.ts b/packages/analytics-js/src/services/HttpClient/xhr/index.ts new file mode 100644 index 0000000000..e2d5ce649c --- /dev/null +++ b/packages/analytics-js/src/services/HttpClient/xhr/index.ts @@ -0,0 +1,75 @@ +import { FAILED_REQUEST_ERR_MSG_PREFIX } from '@rudderstack/analytics-js-common/constants/errors'; +import type { IXHRRequestOptions } from '@rudderstack/analytics-js-common/types/HttpClient'; +import { clone } from 'ramda'; +import { DELIVERY_ERROR, REQUEST_ERROR, XHR_SEND_ERROR } from '../../../constants/logMessages'; +import { HttpClientError } from '../utils'; + +const makeXHRRequest = (url: string | URL, options: IXHRRequestOptions): Promise => + new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + const xhrReject = (e?: ProgressEvent) => { + reject( + new HttpClientError( + DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, xhr.status, xhr.statusText, url, e), + xhr.status, + xhr.statusText, + xhr.responseText, + ), + ); + }; + const xhrError = (e?: ProgressEvent) => { + reject( + new HttpClientError( + REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, url, options.timeout as number, e), + xhr.status, + xhr.statusText, + xhr.responseText, + ), + ); + }; + + xhr.ontimeout = xhrError; + xhr.onerror = xhrError; + + xhr.onload = () => { + if (xhr.status >= 200 && xhr.status < 400) { + resolve( + new Response(xhr.responseText, { + status: xhr.status, + statusText: xhr.statusText, + }), + ); + } else { + xhrReject(); + } + }; + + xhr.open(options.method, url); + if (options.withCredentials === true) { + xhr.withCredentials = true; + } + // The timeout property may be set only in the time interval between a call to the open method + // and the first call to the send method in legacy browsers + xhr.timeout = options.timeout as number; + + if (options.headers) { + Object.entries(options.headers).forEach(([headerName, headerValue]) => { + xhr.setRequestHeader(headerName, headerValue); + }); + } + + try { + xhr.send(options.body); + } catch (err: any) { + // clone the error object and add the status, statusText, and responseBody properties + const clonedErr: HttpClientError = clone(err); + clonedErr.message = `${XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, url)}: ${err.message}`; + clonedErr.status = xhr.status; + clonedErr.statusText = xhr.statusText; + clonedErr.responseBody = xhr.responseText; + + reject(clonedErr); + } + }); + +export { makeXHRRequest }; diff --git a/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts b/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts deleted file mode 100644 index 982df27560..0000000000 --- a/packages/analytics-js/src/services/HttpClient/xhr/xhrRequestHandler.ts +++ /dev/null @@ -1,137 +0,0 @@ -/* eslint-disable prefer-promise-reject-errors */ -import { mergeDeepRight } from '@rudderstack/analytics-js-common/utilities/object'; -import { stringifyWithoutCircular } from '@rudderstack/analytics-js-common/utilities/json'; -import { isNull } from '@rudderstack/analytics-js-common/utilities/checks'; -import type { - IXHRRequestOptions, - XHRResponseDetails, -} from '@rudderstack/analytics-js-common/types/HttpClient'; -import type { ILogger } from '@rudderstack/analytics-js-common/types/Logger'; -import { getMutatedError } from '@rudderstack/analytics-js-common/utilities/errors'; -import { FAILED_REQUEST_ERR_MSG_PREFIX } from '@rudderstack/analytics-js-common/constants/errors'; -import { DEFAULT_XHR_TIMEOUT_MS } from '../../../constants/timeouts'; -import { - XHR_PAYLOAD_PREP_ERROR, - XHR_DELIVERY_ERROR, - XHR_REQUEST_ERROR, - XHR_SEND_ERROR, -} from '../../../constants/logMessages'; - -const DEFAULT_XHR_REQUEST_OPTIONS: Partial = { - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json;charset=UTF-8', - }, - method: 'GET', -}; - -/** - * Utility to create request configuration based on default options - */ -const createXhrRequestOptions = ( - options?: Partial, - basicAuthHeader?: string, -): IXHRRequestOptions => { - const requestOptions: IXHRRequestOptions = mergeDeepRight( - DEFAULT_XHR_REQUEST_OPTIONS, - options || {}, - ); - - if (basicAuthHeader) { - requestOptions.headers = mergeDeepRight(requestOptions.headers ?? {}, { - Authorization: basicAuthHeader, - }); - } - - return requestOptions; -}; - -/** - * Utility implementation of XHR, fetch cannot be used as it requires explicit - * origin allowed values and not wildcard for CORS requests with credentials and - * this is not supported by our sourceConfig API - */ -const xhrRequest = ( - url: string | URL, - options: IXHRRequestOptions, - timeout = DEFAULT_XHR_TIMEOUT_MS, - logger?: ILogger, -): Promise => - new Promise((resolve, reject) => { - let payload; - if (options.sendRawData === true) { - payload = options.data; - } else { - payload = stringifyWithoutCircular(options.data, false, [], logger); - if (isNull(payload)) { - reject({ - error: new Error(XHR_PAYLOAD_PREP_ERROR), - undefined, - options, - }); - // return and don't process further if the payload could not be stringified - return; - } - } - - const xhr = new XMLHttpRequest(); - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const xhrReject = (e?: ProgressEvent) => { - reject({ - error: new Error( - XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, xhr.status, xhr.statusText, url), - ), - xhr, - options, - }); - }; - const xhrError = (e?: ProgressEvent) => { - reject({ - error: new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, e, url)), - xhr, - options, - }); - }; - - xhr.ontimeout = xhrError; - xhr.onerror = xhrError; - - xhr.onload = () => { - if (xhr.status >= 200 && xhr.status < 400) { - resolve({ - response: xhr.responseText, - xhr, - options, - url, - }); - } else { - xhrReject(); - } - }; - - xhr.open(options.method, url); - if (options.withCredentials === true) { - xhr.withCredentials = true; - } - // The timeout property may be set only in the time interval between a call to the open method - // and the first call to the send method in legacy browsers - xhr.timeout = timeout; - - if (options.headers) { - Object.keys(options.headers).forEach(headerName => { - xhr.setRequestHeader(headerName, options.headers?.[headerName] as string); - }); - } - - try { - xhr.send(payload); - } catch (err) { - reject({ - error: getMutatedError(err, XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX, url)), - xhr, - options, - }); - } - }); - -export { createXhrRequestOptions, xhrRequest, DEFAULT_XHR_REQUEST_OPTIONS }; diff --git a/packages/analytics-js/src/services/HttpClient/xhr/xhrResponseHandler.ts b/packages/analytics-js/src/services/HttpClient/xhr/xhrResponseHandler.ts deleted file mode 100644 index 5d3d2cd8d0..0000000000 --- a/packages/analytics-js/src/services/HttpClient/xhr/xhrResponseHandler.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { isFunction } from '@rudderstack/analytics-js-common/utilities/checks'; -import { getMutatedError } from '@rudderstack/analytics-js-common/utilities/errors'; - -/** - * Utility to parse XHR JSON response - */ -const responseTextToJson = ( - responseText?: string, - onError?: (message: Error | unknown) => void, -): T | undefined => { - try { - return JSON.parse(responseText || ''); - } catch (err) { - const error = getMutatedError(err, 'Failed to parse response data'); - if (isFunction(onError)) { - onError(error); - } else { - throw error; - } - } - - return undefined; -}; - -export { responseTextToJson };