utneque 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (431) hide show
  1. package/.editorconfig +10 -0
  2. package/.eslintrc.isomorphic.js +26 -0
  3. package/.eslintrc.js +86 -0
  4. package/.gitattributes +1 -0
  5. package/.github/workflows/ci.yml +33 -0
  6. package/.github/workflows/deploy-browser-cdn-candidate.yml +51 -0
  7. package/.github/workflows/deploy-releases.yml +178 -0
  8. package/.nvmrc +1 -0
  9. package/.prettierrc +7 -0
  10. package/.vscode/extensions.json +3 -0
  11. package/.vscode/launch.json +81 -0
  12. package/.vscode/settings.json +41 -0
  13. package/.yarn/plugins/@yarnpkg/plugin-constraints.cjs +52 -0
  14. package/.yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs +546 -0
  15. package/.yarn/plugins/@yarnpkg/plugin-typescript.cjs +9 -0
  16. package/.yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs +28 -0
  17. package/.yarn/releases/yarn-3.4.1.cjs +873 -0
  18. package/.yarnrc.yml +15 -0
  19. package/jest.config.js +18 -0
  20. package/package.json +59 -0
  21. package/packages/browser/.eslintrc.js +9 -0
  22. package/packages/browser/.lintstagedrc.js +1 -0
  23. package/packages/browser/ARCHITECTURE.md +48 -0
  24. package/packages/browser/LICENSE.MD +45 -0
  25. package/packages/browser/Makefile +64 -0
  26. package/packages/browser/README.md +227 -0
  27. package/packages/browser/e2e-tests/local-server.ts +28 -0
  28. package/packages/browser/e2e-tests/performance/ajs-perf-browser.test.ts +75 -0
  29. package/packages/browser/jest.config.js +15 -0
  30. package/packages/browser/jest.setup.js +10 -0
  31. package/packages/browser/package.json +106 -0
  32. package/packages/browser/qa/README.md +41 -0
  33. package/packages/browser/qa/__fixtures__/snippets.ts +148 -0
  34. package/packages/browser/qa/__tests__/backwards-compatibility.test.ts +180 -0
  35. package/packages/browser/qa/__tests__/destinations.test.ts +101 -0
  36. package/packages/browser/qa/__tests__/smoke.test.ts +170 -0
  37. package/packages/browser/qa/lib/benchmark.ts +36 -0
  38. package/packages/browser/qa/lib/browser.ts +28 -0
  39. package/packages/browser/qa/lib/jest-reporter.js +57 -0
  40. package/packages/browser/qa/lib/runner.ts +142 -0
  41. package/packages/browser/qa/lib/schema.ts +59 -0
  42. package/packages/browser/qa/lib/server.ts +54 -0
  43. package/packages/browser/qa/lib/stats.ts +52 -0
  44. package/packages/browser/scripts/build-prep.sh +7 -0
  45. package/packages/browser/scripts/ci.sh +15 -0
  46. package/packages/browser/scripts/release.js +121 -0
  47. package/packages/browser/scripts/release.sh +9 -0
  48. package/packages/browser/scripts/run.sh +8 -0
  49. package/packages/browser/src/browser/__tests__/analytics-lazy-init.integration.test.ts +51 -0
  50. package/packages/browser/src/browser/__tests__/analytics-pre-init.integration.test.ts +440 -0
  51. package/packages/browser/src/browser/__tests__/anon-id-and-reset.integration.test.ts +73 -0
  52. package/packages/browser/src/browser/__tests__/cdn.test.ts +53 -0
  53. package/packages/browser/src/browser/__tests__/csp-detection.test.ts +140 -0
  54. package/packages/browser/src/browser/__tests__/inspector.integration.test.ts +121 -0
  55. package/packages/browser/src/browser/__tests__/integration.test.ts +1213 -0
  56. package/packages/browser/src/browser/__tests__/integrations.integration.test.ts +260 -0
  57. package/packages/browser/src/browser/__tests__/page-enrichment.integration.test.ts +216 -0
  58. package/packages/browser/src/browser/__tests__/query-string.integration.test.ts +116 -0
  59. package/packages/browser/src/browser/__tests__/standalone-analytics.test.ts +303 -0
  60. package/packages/browser/src/browser/__tests__/standalone-errors.test.ts +136 -0
  61. package/packages/browser/src/browser/__tests__/standalone.test.ts +97 -0
  62. package/packages/browser/src/browser/__tests__/typedef-tests/analytics-browser.ts +150 -0
  63. package/packages/browser/src/browser/__tests__/update-cdn-settings.test.ts +71 -0
  64. package/packages/browser/src/browser/browser-umd.ts +19 -0
  65. package/packages/browser/src/browser/index.ts +486 -0
  66. package/packages/browser/src/browser/standalone-analytics.ts +62 -0
  67. package/packages/browser/src/browser/standalone-interface.ts +11 -0
  68. package/packages/browser/src/browser/standalone.ts +92 -0
  69. package/packages/browser/src/core/__tests__/track-form.test.ts +193 -0
  70. package/packages/browser/src/core/__tests__/track-link.test.ts +252 -0
  71. package/packages/browser/src/core/analytics/__tests__/integration.test.ts +334 -0
  72. package/packages/browser/src/core/analytics/__tests__/test-plugins.ts +94 -0
  73. package/packages/browser/src/core/analytics/index.ts +672 -0
  74. package/packages/browser/src/core/analytics/interfaces.ts +100 -0
  75. package/packages/browser/src/core/arguments-resolver/__tests__/index.test.ts +524 -0
  76. package/packages/browser/src/core/arguments-resolver/index.ts +200 -0
  77. package/packages/browser/src/core/auto-track.ts +152 -0
  78. package/packages/browser/src/core/buffer/__tests__/index.test.ts +455 -0
  79. package/packages/browser/src/core/buffer/index.ts +371 -0
  80. package/packages/browser/src/core/callback/index.ts +1 -0
  81. package/packages/browser/src/core/connection/__tests__/index.test.ts +25 -0
  82. package/packages/browser/src/core/connection/index.ts +13 -0
  83. package/packages/browser/src/core/constants/index.ts +1 -0
  84. package/packages/browser/src/core/context/__tests__/index.test.ts +201 -0
  85. package/packages/browser/src/core/context/index.ts +21 -0
  86. package/packages/browser/src/core/environment/index.ts +7 -0
  87. package/packages/browser/src/core/events/__tests__/index.test.ts +450 -0
  88. package/packages/browser/src/core/events/index.ts +280 -0
  89. package/packages/browser/src/core/events/interfaces.ts +36 -0
  90. package/packages/browser/src/core/inspector/index.ts +14 -0
  91. package/packages/browser/src/core/page/__tests__/index.test.ts +130 -0
  92. package/packages/browser/src/core/page/add-page-context.ts +33 -0
  93. package/packages/browser/src/core/page/get-page-context.ts +140 -0
  94. package/packages/browser/src/core/page/index.ts +2 -0
  95. package/packages/browser/src/core/plugin/index.ts +12 -0
  96. package/packages/browser/src/core/query-string/__tests__/gracefulDecodeURIComponent.test.ts +17 -0
  97. package/packages/browser/src/core/query-string/__tests__/index.test.ts +149 -0
  98. package/packages/browser/src/core/query-string/__tests__/pickPrefix.test.ts +31 -0
  99. package/packages/browser/src/core/query-string/__tests__/useQueryString.test.ts +60 -0
  100. package/packages/browser/src/core/query-string/gracefulDecodeURIComponent.ts +16 -0
  101. package/packages/browser/src/core/query-string/index.ts +64 -0
  102. package/packages/browser/src/core/query-string/pickPrefix.ts +20 -0
  103. package/packages/browser/src/core/queue/__tests__/event-queue.test.ts +82 -0
  104. package/packages/browser/src/core/queue/event-queue.ts +22 -0
  105. package/packages/browser/src/core/session/__tests__/index.test.ts +41 -0
  106. package/packages/browser/src/core/session/index.ts +107 -0
  107. package/packages/browser/src/core/stats/__tests__/index.test.ts +15 -0
  108. package/packages/browser/src/core/stats/__tests__/remote-metrics.test.ts +189 -0
  109. package/packages/browser/src/core/stats/index.ts +15 -0
  110. package/packages/browser/src/core/stats/remote-metrics.ts +144 -0
  111. package/packages/browser/src/core/storage/__tests__/cookieStorage.test.ts +58 -0
  112. package/packages/browser/src/core/storage/__tests__/localStorage.test.ts +70 -0
  113. package/packages/browser/src/core/storage/__tests__/test-helpers.ts +26 -0
  114. package/packages/browser/src/core/storage/__tests__/universalStorage.test.ts +167 -0
  115. package/packages/browser/src/core/storage/cookieStorage.ts +80 -0
  116. package/packages/browser/src/core/storage/index.ts +64 -0
  117. package/packages/browser/src/core/storage/localStorage.ts +45 -0
  118. package/packages/browser/src/core/storage/memoryStorage.ts +22 -0
  119. package/packages/browser/src/core/storage/settings.ts +23 -0
  120. package/packages/browser/src/core/storage/types.ts +49 -0
  121. package/packages/browser/src/core/storage/universalStorage.ts +78 -0
  122. package/packages/browser/src/core/user/__tests__/index.test.ts +922 -0
  123. package/packages/browser/src/core/user/__tests__/migrate.test.ts +101 -0
  124. package/packages/browser/src/core/user/__tests__/session.test.ts +136 -0
  125. package/packages/browser/src/core/user/__tests__/tld.test.ts +36 -0
  126. package/packages/browser/src/core/user/index.ts +399 -0
  127. package/packages/browser/src/core/user/migrate.ts +126 -0
  128. package/packages/browser/src/core/user/tld.ts +65 -0
  129. package/packages/browser/src/core/user/vendor/crypto-es/LICENSE +53 -0
  130. package/packages/browser/src/core/user/vendor/crypto-es/lib/aes.ts +302 -0
  131. package/packages/browser/src/core/user/vendor/crypto-es/lib/cipher-core.ts +922 -0
  132. package/packages/browser/src/core/user/vendor/crypto-es/lib/core.ts +806 -0
  133. package/packages/browser/src/core/user/vendor/crypto-es/lib/enc-base64.ts +110 -0
  134. package/packages/browser/src/core/user/vendor/crypto-es/lib/evpkdf.ts +110 -0
  135. package/packages/browser/src/core/user/vendor/crypto-es/lib/md5.ts +238 -0
  136. package/packages/browser/src/core/user/vendor/readme.md +7 -0
  137. package/packages/browser/src/generated/__tests__/version.test.ts +18 -0
  138. package/packages/browser/src/generated/version.ts +2 -0
  139. package/packages/browser/src/index.ts +13 -0
  140. package/packages/browser/src/lib/__tests__/embedded-write-key.test.ts +15 -0
  141. package/packages/browser/src/lib/__tests__/fetch.test.ts +35 -0
  142. package/packages/browser/src/lib/__tests__/get-process-env.test.ts +5 -0
  143. package/packages/browser/src/lib/__tests__/group-by.test.ts +96 -0
  144. package/packages/browser/src/lib/__tests__/is-plan-event-enabled.test.ts +36 -0
  145. package/packages/browser/src/lib/__tests__/is-thenable.test.ts +39 -0
  146. package/packages/browser/src/lib/__tests__/merged-options.test.ts +123 -0
  147. package/packages/browser/src/lib/__tests__/on-page-change.test.ts +74 -0
  148. package/packages/browser/src/lib/__tests__/parse-cdn.test.ts +88 -0
  149. package/packages/browser/src/lib/__tests__/pick.test.ts +34 -0
  150. package/packages/browser/src/lib/__tests__/pick.typedef.ts +39 -0
  151. package/packages/browser/src/lib/bind-all.ts +19 -0
  152. package/packages/browser/src/lib/browser-polyfill.ts +23 -0
  153. package/packages/browser/src/lib/client-hints/__tests__/index.test.ts +66 -0
  154. package/packages/browser/src/lib/client-hints/index.ts +16 -0
  155. package/packages/browser/src/lib/client-hints/interfaces.ts +42 -0
  156. package/packages/browser/src/lib/create-deferred.ts +16 -0
  157. package/packages/browser/src/lib/csp-detection.ts +8 -0
  158. package/packages/browser/src/lib/embedded-write-key.ts +24 -0
  159. package/packages/browser/src/lib/fetch.ts +10 -0
  160. package/packages/browser/src/lib/get-global.ts +16 -0
  161. package/packages/browser/src/lib/get-process-env.ts +11 -0
  162. package/packages/browser/src/lib/global-analytics-helper.ts +31 -0
  163. package/packages/browser/src/lib/group-by.ts +30 -0
  164. package/packages/browser/src/lib/is-plan-event-enabled.ts +20 -0
  165. package/packages/browser/src/lib/is-thenable.ts +9 -0
  166. package/packages/browser/src/lib/load-script.ts +66 -0
  167. package/packages/browser/src/lib/merged-options.ts +46 -0
  168. package/packages/browser/src/lib/on-page-change.ts +29 -0
  169. package/packages/browser/src/lib/p-while.ts +12 -0
  170. package/packages/browser/src/lib/parse-cdn.ts +56 -0
  171. package/packages/browser/src/lib/pick.ts +28 -0
  172. package/packages/browser/src/lib/priority-queue/__tests__/backoff.test.ts +23 -0
  173. package/packages/browser/src/lib/priority-queue/__tests__/index.test.ts +158 -0
  174. package/packages/browser/src/lib/priority-queue/__tests__/persisted.test.ts +228 -0
  175. package/packages/browser/src/lib/priority-queue/backoff.ts +24 -0
  176. package/packages/browser/src/lib/priority-queue/index.ts +6 -0
  177. package/packages/browser/src/lib/priority-queue/persisted.ts +127 -0
  178. package/packages/browser/src/lib/sleep.ts +4 -0
  179. package/packages/browser/src/lib/to-facade.ts +53 -0
  180. package/packages/browser/src/lib/version-type.ts +10 -0
  181. package/packages/browser/src/node/__tests__/node-integration.test.ts +19 -0
  182. package/packages/browser/src/node/index.ts +36 -0
  183. package/packages/browser/src/node/node.browser.ts +7 -0
  184. package/packages/browser/src/plugins/ajs-destination/__tests__/index.test.ts +834 -0
  185. package/packages/browser/src/plugins/ajs-destination/index.ts +392 -0
  186. package/packages/browser/src/plugins/ajs-destination/loader.ts +129 -0
  187. package/packages/browser/src/plugins/ajs-destination/types.ts +44 -0
  188. package/packages/browser/src/plugins/ajs-destination/utils.ts +32 -0
  189. package/packages/browser/src/plugins/analytics-node/__tests__/index.test.ts +69 -0
  190. package/packages/browser/src/plugins/analytics-node/index.ts +67 -0
  191. package/packages/browser/src/plugins/env-enrichment/__tests__/index.test.ts +421 -0
  192. package/packages/browser/src/plugins/env-enrichment/index.ts +208 -0
  193. package/packages/browser/src/plugins/hightouchio/__tests__/batched-dispatcher.test.ts +299 -0
  194. package/packages/browser/src/plugins/hightouchio/__tests__/index.test.ts +317 -0
  195. package/packages/browser/src/plugins/hightouchio/__tests__/normalize.test.ts +181 -0
  196. package/packages/browser/src/plugins/hightouchio/__tests__/retries.test.ts +82 -0
  197. package/packages/browser/src/plugins/hightouchio/batched-dispatcher.ts +127 -0
  198. package/packages/browser/src/plugins/hightouchio/fetch-dispatcher.ts +27 -0
  199. package/packages/browser/src/plugins/hightouchio/index.ts +147 -0
  200. package/packages/browser/src/plugins/hightouchio/normalize.ts +71 -0
  201. package/packages/browser/src/plugins/hightouchio/schedule-flush.ts +58 -0
  202. package/packages/browser/src/plugins/legacy-video-plugins/__tests__/index.test.ts +48 -0
  203. package/packages/browser/src/plugins/legacy-video-plugins/index.ts +16 -0
  204. package/packages/browser/src/plugins/middleware/__tests__/index.test.ts +268 -0
  205. package/packages/browser/src/plugins/middleware/index.ts +131 -0
  206. package/packages/browser/src/plugins/remote-loader/__tests__/index.test.ts +943 -0
  207. package/packages/browser/src/plugins/remote-loader/index.ts +256 -0
  208. package/packages/browser/src/plugins/remote-middleware/__tests__/index.test.ts +116 -0
  209. package/packages/browser/src/plugins/remote-middleware/index.ts +44 -0
  210. package/packages/browser/src/plugins/routing-middleware/__tests__/index.test.ts +64 -0
  211. package/packages/browser/src/plugins/routing-middleware/index.ts +37 -0
  212. package/packages/browser/src/plugins/schema-filter/__tests__/index.test.ts +520 -0
  213. package/packages/browser/src/plugins/schema-filter/index.ts +90 -0
  214. package/packages/browser/src/plugins/validation/__tests__/index.test.ts +78 -0
  215. package/packages/browser/src/plugins/validation/index.ts +44 -0
  216. package/packages/browser/src/test-helpers/browser-storage.ts +75 -0
  217. package/packages/browser/src/test-helpers/factories.ts +18 -0
  218. package/packages/browser/src/test-helpers/fetch-parse.ts +8 -0
  219. package/packages/browser/src/test-helpers/fixtures/cdn-settings.ts +301 -0
  220. package/packages/browser/src/test-helpers/fixtures/classic-destination.ts +25 -0
  221. package/packages/browser/src/test-helpers/fixtures/client-hints.ts +28 -0
  222. package/packages/browser/src/test-helpers/fixtures/create-fetch-method.ts +30 -0
  223. package/packages/browser/src/test-helpers/fixtures/index.ts +4 -0
  224. package/packages/browser/src/test-helpers/fixtures/page-context.ts +11 -0
  225. package/packages/browser/src/test-helpers/test-writekeys.ts +5 -0
  226. package/packages/browser/src/test-helpers/type-assertions.ts +11 -0
  227. package/packages/browser/src/tester/__fixtures__/hightouch-snippet.ts +64 -0
  228. package/packages/browser/src/tester/__fixtures__/index.html +8 -0
  229. package/packages/browser/src/tester/ajs-perf.ts +30 -0
  230. package/packages/browser/src/tester/ajs-tester.ts +119 -0
  231. package/packages/browser/src/tester/server.js +16 -0
  232. package/packages/browser/tsconfig.build.json +9 -0
  233. package/packages/browser/tsconfig.json +13 -0
  234. package/packages/browser/webpack.config.js +106 -0
  235. package/packages/config/package.json +10 -0
  236. package/packages/config/src/index.js +4 -0
  237. package/packages/config/src/jest/config.js +50 -0
  238. package/packages/config/src/jest/get-module-map.js +34 -0
  239. package/packages/config/src/lint-staged/config.js +4 -0
  240. package/packages/config-webpack/package.json +20 -0
  241. package/packages/config-webpack/webpack.config.common.js +75 -0
  242. package/packages/consent/consent-tools/.eslintrc.js +7 -0
  243. package/packages/consent/consent-tools/.lintstagedrc.js +1 -0
  244. package/packages/consent/consent-tools/LICENSE +45 -0
  245. package/packages/consent/consent-tools/README.md +104 -0
  246. package/packages/consent/consent-tools/jest.config.js +6 -0
  247. package/packages/consent/consent-tools/jest.setup.js +4 -0
  248. package/packages/consent/consent-tools/package.json +48 -0
  249. package/packages/consent/consent-tools/src/domain/__tests__/assertions/integrations-assertions.ts +37 -0
  250. package/packages/consent/consent-tools/src/domain/__tests__/consent-stamping.test.ts +45 -0
  251. package/packages/consent/consent-tools/src/domain/__tests__/create-wrapper.test.ts +816 -0
  252. package/packages/consent/consent-tools/src/domain/__tests__/typedef-tests.ts +21 -0
  253. package/packages/consent/consent-tools/src/domain/consent-changed.ts +51 -0
  254. package/packages/consent/consent-tools/src/domain/consent-stamping.ts +19 -0
  255. package/packages/consent/consent-tools/src/domain/create-wrapper.ts +238 -0
  256. package/packages/consent/consent-tools/src/domain/get-initialized-analytics.ts +25 -0
  257. package/packages/consent/consent-tools/src/domain/load-cancellation.ts +31 -0
  258. package/packages/consent/consent-tools/src/domain/validation/__tests__/options-validators.test.ts +77 -0
  259. package/packages/consent/consent-tools/src/domain/validation/__tests__/validation-error.test.ts +15 -0
  260. package/packages/consent/consent-tools/src/domain/validation/common-validators.ts +19 -0
  261. package/packages/consent/consent-tools/src/domain/validation/index.ts +1 -0
  262. package/packages/consent/consent-tools/src/domain/validation/options-validators.ts +74 -0
  263. package/packages/consent/consent-tools/src/domain/validation/validation-error.ts +11 -0
  264. package/packages/consent/consent-tools/src/index.ts +16 -0
  265. package/packages/consent/consent-tools/src/types/errors.ts +14 -0
  266. package/packages/consent/consent-tools/src/types/index.ts +3 -0
  267. package/packages/consent/consent-tools/src/types/settings.ts +121 -0
  268. package/packages/consent/consent-tools/src/types/wrapper.ts +107 -0
  269. package/packages/consent/consent-tools/src/utils/index.ts +4 -0
  270. package/packages/consent/consent-tools/src/utils/pick.ts +18 -0
  271. package/packages/consent/consent-tools/src/utils/pipe.ts +14 -0
  272. package/packages/consent/consent-tools/src/utils/resolve-when.ts +32 -0
  273. package/packages/consent/consent-tools/src/utils/uniq.ts +4 -0
  274. package/packages/consent/consent-tools/tsconfig.build.json +9 -0
  275. package/packages/consent/consent-tools/tsconfig.json +12 -0
  276. package/packages/consent/consent-wrapper-onetrust/.eslintrc.js +7 -0
  277. package/packages/consent/consent-wrapper-onetrust/.lintstagedrc.js +1 -0
  278. package/packages/consent/consent-wrapper-onetrust/LICENSE +45 -0
  279. package/packages/consent/consent-wrapper-onetrust/README.md +125 -0
  280. package/packages/consent/consent-wrapper-onetrust/img/onetrust-cat-id.jpg +0 -0
  281. package/packages/consent/consent-wrapper-onetrust/img/onetrust-popup.jpg +0 -0
  282. package/packages/consent/consent-wrapper-onetrust/jest.config.js +6 -0
  283. package/packages/consent/consent-wrapper-onetrust/jest.setup.js +4 -0
  284. package/packages/consent/consent-wrapper-onetrust/package.json +60 -0
  285. package/packages/consent/consent-wrapper-onetrust/src/domain/__tests__/wrapper.test.ts +151 -0
  286. package/packages/consent/consent-wrapper-onetrust/src/domain/wrapper.ts +61 -0
  287. package/packages/consent/consent-wrapper-onetrust/src/index.ts +6 -0
  288. package/packages/consent/consent-wrapper-onetrust/src/index.umd.ts +11 -0
  289. package/packages/consent/consent-wrapper-onetrust/src/lib/__tests__/onetrust-api.test.ts +181 -0
  290. package/packages/consent/consent-wrapper-onetrust/src/lib/onetrust-api.ts +155 -0
  291. package/packages/consent/consent-wrapper-onetrust/src/lib/validation/index.ts +1 -0
  292. package/packages/consent/consent-wrapper-onetrust/src/lib/validation/onetrust-api-error.ts +11 -0
  293. package/packages/consent/consent-wrapper-onetrust/src/test-helpers/mocks.ts +23 -0
  294. package/packages/consent/consent-wrapper-onetrust/src/test-helpers/onetrust-globals.d.ts +11 -0
  295. package/packages/consent/consent-wrapper-onetrust/src/test-helpers/utils.ts +3 -0
  296. package/packages/consent/consent-wrapper-onetrust/tsconfig.build.json +9 -0
  297. package/packages/consent/consent-wrapper-onetrust/tsconfig.json +11 -0
  298. package/packages/consent/consent-wrapper-onetrust/webpack.config.js +25 -0
  299. package/packages/core/.eslintrc.js +4 -0
  300. package/packages/core/.lintstagedrc.js +1 -0
  301. package/packages/core/LICENSE.MD +45 -0
  302. package/packages/core/README.md +3 -0
  303. package/packages/core/jest.config.js +5 -0
  304. package/packages/core/jest.setup.js +10 -0
  305. package/packages/core/package.json +40 -0
  306. package/packages/core/src/analytics/__tests__/dispatch.test.ts +95 -0
  307. package/packages/core/src/analytics/dispatch.ts +58 -0
  308. package/packages/core/src/analytics/index.ts +11 -0
  309. package/packages/core/src/callback/__tests__/index.test.ts +85 -0
  310. package/packages/core/src/callback/index.ts +51 -0
  311. package/packages/core/src/context/index.ts +123 -0
  312. package/packages/core/src/emitter/__tests__/emitter.test.ts +74 -0
  313. package/packages/core/src/emitter/index.ts +65 -0
  314. package/packages/core/src/emitter/interface.ts +31 -0
  315. package/packages/core/src/events/__tests__/index.test.ts +394 -0
  316. package/packages/core/src/events/index.ts +280 -0
  317. package/packages/core/src/events/interfaces.ts +475 -0
  318. package/packages/core/src/index.ts +19 -0
  319. package/packages/core/src/logger/__tests__/index.test.ts +66 -0
  320. package/packages/core/src/logger/index.ts +74 -0
  321. package/packages/core/src/plugins/index.ts +43 -0
  322. package/packages/core/src/priority-queue/__tests__/backoff.test.ts +23 -0
  323. package/packages/core/src/priority-queue/__tests__/index.test.ts +158 -0
  324. package/packages/core/src/priority-queue/backoff.ts +24 -0
  325. package/packages/core/src/priority-queue/index.ts +103 -0
  326. package/packages/core/src/queue/__tests__/event-queue.test.ts +678 -0
  327. package/packages/core/src/queue/__tests__/extension-flushing.test.ts +416 -0
  328. package/packages/core/src/queue/delivery.ts +73 -0
  329. package/packages/core/src/queue/event-queue.ts +318 -0
  330. package/packages/core/src/stats/__tests__/index.test.ts +103 -0
  331. package/packages/core/src/stats/index.ts +88 -0
  332. package/packages/core/src/task/__tests__/task-group.test.ts +26 -0
  333. package/packages/core/src/task/task-group.ts +31 -0
  334. package/packages/core/src/user/index.ts +7 -0
  335. package/packages/core/src/utils/__tests__/group-by.test.ts +96 -0
  336. package/packages/core/src/utils/__tests__/is-plain-object.test.ts +27 -0
  337. package/packages/core/src/utils/__tests__/is-thenable.test.ts +39 -0
  338. package/packages/core/src/utils/bind-all.ts +19 -0
  339. package/packages/core/src/utils/get-global.ts +17 -0
  340. package/packages/core/src/utils/group-by.ts +30 -0
  341. package/packages/core/src/utils/has-properties.ts +7 -0
  342. package/packages/core/src/utils/is-plain-object.ts +26 -0
  343. package/packages/core/src/utils/is-thenable.ts +9 -0
  344. package/packages/core/src/utils/p-while.ts +12 -0
  345. package/packages/core/src/utils/pick.ts +8 -0
  346. package/packages/core/src/utils/ts-helpers.ts +13 -0
  347. package/packages/core/src/validation/__tests__/assertions.test.ts +155 -0
  348. package/packages/core/src/validation/assertions.ts +72 -0
  349. package/packages/core/src/validation/errors.ts +8 -0
  350. package/packages/core/src/validation/helpers.ts +23 -0
  351. package/packages/core/test-helpers/index.ts +2 -0
  352. package/packages/core/test-helpers/test-ctx.ts +7 -0
  353. package/packages/core/test-helpers/test-event-queue.ts +7 -0
  354. package/packages/core/tsconfig.build.json +9 -0
  355. package/packages/core/tsconfig.json +11 -0
  356. package/packages/node/.eslintrc.js +7 -0
  357. package/packages/node/.lintstagedrc.js +1 -0
  358. package/packages/node/LICENSE +45 -0
  359. package/packages/node/README.md +138 -0
  360. package/packages/node/jest.config.js +5 -0
  361. package/packages/node/jest.setup.js +4 -0
  362. package/packages/node/package.json +50 -0
  363. package/packages/node/scripts/version.sh +11 -0
  364. package/packages/node/src/__tests__/callback.test.ts +47 -0
  365. package/packages/node/src/__tests__/disable.integration.test.ts +42 -0
  366. package/packages/node/src/__tests__/emitter.integration.test.ts +45 -0
  367. package/packages/node/src/__tests__/graceful-shutdown-integration.test.ts +244 -0
  368. package/packages/node/src/__tests__/http-client.integration.test.ts +69 -0
  369. package/packages/node/src/__tests__/http-integration.test.ts +362 -0
  370. package/packages/node/src/__tests__/integration.test.ts +357 -0
  371. package/packages/node/src/__tests__/plugins.test.ts +16 -0
  372. package/packages/node/src/__tests__/settings.test.ts +9 -0
  373. package/packages/node/src/__tests__/test-helpers/assert-shape/http-request-event.ts +13 -0
  374. package/packages/node/src/__tests__/test-helpers/assert-shape/index.ts +2 -0
  375. package/packages/node/src/__tests__/test-helpers/assert-shape/segment-http-api.ts +43 -0
  376. package/packages/node/src/__tests__/test-helpers/create-test-analytics.ts +42 -0
  377. package/packages/node/src/__tests__/test-helpers/factories.ts +17 -0
  378. package/packages/node/src/__tests__/test-helpers/is-valid-date.ts +6 -0
  379. package/packages/node/src/__tests__/test-helpers/resolve-ctx.ts +19 -0
  380. package/packages/node/src/__tests__/test-helpers/resolve-emitter.ts +11 -0
  381. package/packages/node/src/__tests__/test-helpers/sleep.ts +3 -0
  382. package/packages/node/src/__tests__/test-helpers/test-plugin.ts +16 -0
  383. package/packages/node/src/__tests__/typedef-tests.ts +120 -0
  384. package/packages/node/src/app/analytics-node.ts +299 -0
  385. package/packages/node/src/app/context.ts +11 -0
  386. package/packages/node/src/app/dispatch-emit.ts +42 -0
  387. package/packages/node/src/app/emitter.ts +23 -0
  388. package/packages/node/src/app/event-factory.ts +20 -0
  389. package/packages/node/src/app/event-queue.ts +23 -0
  390. package/packages/node/src/app/settings.ts +49 -0
  391. package/packages/node/src/app/types/index.ts +3 -0
  392. package/packages/node/src/app/types/params.ts +76 -0
  393. package/packages/node/src/app/types/plugin.ts +5 -0
  394. package/packages/node/src/app/types/segment-event.ts +7 -0
  395. package/packages/node/src/generated/version.ts +2 -0
  396. package/packages/node/src/index.ts +26 -0
  397. package/packages/node/src/lib/__tests__/abort.test.ts +54 -0
  398. package/packages/node/src/lib/__tests__/create-url.test.ts +35 -0
  399. package/packages/node/src/lib/__tests__/env.test.ts +52 -0
  400. package/packages/node/src/lib/__tests__/get-message-id.test.ts +21 -0
  401. package/packages/node/src/lib/abort.ts +77 -0
  402. package/packages/node/src/lib/base-64-encode.ts +8 -0
  403. package/packages/node/src/lib/create-url.ts +11 -0
  404. package/packages/node/src/lib/env.ts +45 -0
  405. package/packages/node/src/lib/extract-promise-parts.ts +21 -0
  406. package/packages/node/src/lib/fetch.ts +16 -0
  407. package/packages/node/src/lib/get-message-id.ts +10 -0
  408. package/packages/node/src/lib/http-client.ts +95 -0
  409. package/packages/node/src/lib/uuid.ts +1 -0
  410. package/packages/node/src/plugins/segmentio/__tests__/methods.test.ts +223 -0
  411. package/packages/node/src/plugins/segmentio/__tests__/publisher.test.ts +411 -0
  412. package/packages/node/src/plugins/segmentio/context-batch.ts +71 -0
  413. package/packages/node/src/plugins/segmentio/index.ts +66 -0
  414. package/packages/node/src/plugins/segmentio/publisher.ts +265 -0
  415. package/packages/node/tsconfig.build.json +9 -0
  416. package/packages/node/tsconfig.json +10 -0
  417. package/packages/test-helpers/.eslintrc.js +7 -0
  418. package/packages/test-helpers/.lintstagedrc.js +1 -0
  419. package/packages/test-helpers/jest.config.js +3 -0
  420. package/packages/test-helpers/package.json +26 -0
  421. package/packages/test-helpers/src/analytics/cdn-settings-builder.ts +79 -0
  422. package/packages/test-helpers/src/analytics/index.ts +1 -0
  423. package/packages/test-helpers/src/index.ts +2 -0
  424. package/packages/test-helpers/src/utils/index.ts +1 -0
  425. package/packages/test-helpers/src/utils/sleep.ts +4 -0
  426. package/packages/test-helpers/tsconfig.build.json +9 -0
  427. package/packages/test-helpers/tsconfig.json +11 -0
  428. package/tsconfig.json +21 -0
  429. package/turbo.json +39 -0
  430. package/typings/get-monorepo-packages.d.ts +9 -0
  431. package/typings/spawn.d.ts +10 -0
@@ -0,0 +1,189 @@
1
+ import unfetch from 'unfetch'
2
+ import { RemoteMetrics } from '../remote-metrics'
3
+ import { version } from '../../../generated/version'
4
+
5
+ jest.mock('unfetch', () => {
6
+ return jest.fn()
7
+ })
8
+
9
+ describe('remote metrics', () => {
10
+ test('stores metrics in a queue when sampling', () => {
11
+ const remote = new RemoteMetrics({
12
+ sampleRate: 100,
13
+ })
14
+ remote.increment('analytics_js.banana', ['phone:1'])
15
+
16
+ expect(remote.queue.length).toBe(1)
17
+ const metric = remote.queue[0]
18
+ expect(metric.tags).toEqual({
19
+ library: 'analytics.js',
20
+ library_version: `npm:next-${version}`,
21
+ phone: '1',
22
+ })
23
+
24
+ expect(metric.metric).toBe('analytics_js.banana')
25
+ expect(metric.type).toBe('Counter')
26
+ expect(metric.value).toBe(1)
27
+ })
28
+
29
+ test('does not store when not sampling', () => {
30
+ const remote = new RemoteMetrics({
31
+ sampleRate: 0,
32
+ })
33
+ remote.increment('analytics_js.banana', ['phone:1'])
34
+
35
+ expect(remote.queue).toMatchInlineSnapshot(`Array []`)
36
+ })
37
+
38
+ test('ignores messages after reaching threshold', () => {
39
+ const remote = new RemoteMetrics({
40
+ sampleRate: 100,
41
+ maxQueueSize: 3,
42
+ })
43
+
44
+ remote.increment('analytics_js.banana', ['phone:1'])
45
+ remote.increment('analytics_js.banana', ['phone:1'])
46
+ remote.increment('analytics_js.banana', ['phone:1'])
47
+ remote.increment('analytics_js.banana', ['phone:1'])
48
+
49
+ expect(remote.queue.length).toBe(3)
50
+ })
51
+
52
+ test('force flushes errors', () => {
53
+ const remote = new RemoteMetrics({
54
+ sampleRate: 100,
55
+ })
56
+
57
+ const spy = jest.spyOn(remote, 'flush')
58
+
59
+ remote.increment('analytics_js.banana', ['phone:1'])
60
+ expect(spy).not.toHaveBeenCalled()
61
+
62
+ remote.increment('analytics_js.banana.error', ['phone:1'])
63
+ expect(spy).toHaveBeenCalled()
64
+ })
65
+
66
+ test('sends metrics requests on flush', async () => {
67
+ const spy = jest.mocked(unfetch).mockImplementation()
68
+
69
+ const remote = new RemoteMetrics({
70
+ sampleRate: 100,
71
+ })
72
+
73
+ remote.increment('analytics_js.banana', ['phone:1'])
74
+ await remote.flush()
75
+
76
+ expect(spy).toHaveBeenCalled()
77
+ const [url, request] = spy.mock.calls[0]
78
+
79
+ expect(url).toBe('https://us-east-1.hightouch-events.com/v1/m')
80
+ expect(request).toMatchInlineSnapshot(
81
+ { body: expect.anything() },
82
+ `
83
+ Object {
84
+ "body": Anything,
85
+ "headers": Object {
86
+ "Accept": "application/json",
87
+ "Content-Type": "application/json",
88
+ },
89
+ "method": "POST",
90
+ }
91
+ `
92
+ )
93
+ const body = JSON.parse(request?.body as any)
94
+ expect(body).toMatchInlineSnapshot(
95
+ {
96
+ series: [
97
+ {
98
+ tags: {
99
+ library_version: expect.any(String),
100
+ },
101
+ },
102
+ ],
103
+ },
104
+ `
105
+ Object {
106
+ "series": Array [
107
+ Object {
108
+ "metric": "analytics_js.banana",
109
+ "tags": Object {
110
+ "library": "analytics.js",
111
+ "library_version": Any<String>,
112
+ "phone": "1",
113
+ },
114
+ "type": "Counter",
115
+ "value": 1,
116
+ },
117
+ ],
118
+ }
119
+ `
120
+ )
121
+ })
122
+
123
+ test('clears queue after sending', async () => {
124
+ const remote = new RemoteMetrics({
125
+ sampleRate: 100,
126
+ })
127
+
128
+ remote.increment('analytics_js.banana', ['phone:1'])
129
+ expect(remote.queue.length).toBe(1)
130
+
131
+ await remote.flush()
132
+ expect(remote.queue.length).toBe(0)
133
+ })
134
+
135
+ test('does not crash on errors', async () => {
136
+ const errorSpy = jest.spyOn(console, 'error').mockImplementation()
137
+
138
+ const error = new Error('aaay')
139
+ jest.mocked(unfetch).mockImplementation(() => {
140
+ throw error
141
+ })
142
+
143
+ const remote = new RemoteMetrics({
144
+ sampleRate: 100,
145
+ })
146
+
147
+ remote.increment('analytics_js.banana', ['phone:1'])
148
+ await remote.flush()
149
+
150
+ expect(errorSpy).toHaveBeenCalledWith(
151
+ 'Error sending hightouch performance metrics',
152
+ error
153
+ )
154
+ })
155
+
156
+ test('disables metrics reporting in case of errors', async () => {
157
+ jest.spyOn(console, 'error').mockImplementation()
158
+
159
+ const error = new Error('aaay')
160
+ jest.mocked(unfetch).mockImplementation(() => {
161
+ throw error
162
+ })
163
+
164
+ const remote = new RemoteMetrics({
165
+ sampleRate: 100,
166
+ })
167
+
168
+ remote.increment('analytics_js.banana', ['phone:1'])
169
+ await remote.flush()
170
+
171
+ expect(remote.sampleRate).toBe(0)
172
+ })
173
+
174
+ test('flushs on a schedule', () => {
175
+ jest.useFakeTimers()
176
+
177
+ const remote = new RemoteMetrics({
178
+ sampleRate: 100,
179
+ flushTimer: 100,
180
+ })
181
+
182
+ const flushSpy = jest.spyOn(remote, 'flush')
183
+
184
+ remote.increment('analytics_js.banana', ['phone:1'])
185
+ jest.advanceTimersByTime(500)
186
+
187
+ expect(flushSpy).toHaveBeenCalledTimes(5)
188
+ })
189
+ })
@@ -0,0 +1,15 @@
1
+ import { CoreStats } from '@ht-sdks/events-sdk-js-core'
2
+ import { MetricsOptions, RemoteMetrics } from './remote-metrics'
3
+
4
+ let remoteMetrics: RemoteMetrics | undefined
5
+
6
+ export class Stats extends CoreStats {
7
+ static initRemoteMetrics(options?: MetricsOptions) {
8
+ remoteMetrics = new RemoteMetrics(options)
9
+ }
10
+
11
+ override increment(metric: string, by?: number, tags?: string[]): void {
12
+ super.increment(metric, by, tags)
13
+ remoteMetrics?.increment(metric, tags ?? [])
14
+ }
15
+ }
@@ -0,0 +1,144 @@
1
+ import { fetch } from '../../lib/fetch'
2
+ import { version } from '../../generated/version'
3
+ import { getVersionType } from '../../lib/version-type'
4
+ import { HIGHTOUCH_API_HOST } from '../constants'
5
+
6
+ export interface MetricsOptions {
7
+ host?: string
8
+ sampleRate?: number
9
+ flushTimer?: number
10
+ maxQueueSize?: number
11
+ }
12
+
13
+ /**
14
+ * Type expected by the hightouch metrics API endpoint
15
+ */
16
+ type RemoteMetric = {
17
+ type: 'Counter'
18
+ metric: string
19
+ value: 1
20
+ tags: {
21
+ library: string
22
+ library_version: string
23
+ [key: string]: string
24
+ }
25
+ }
26
+
27
+ const createRemoteMetric = (
28
+ metric: string,
29
+ tags: string[],
30
+ versionType: 'web' | 'npm'
31
+ ): RemoteMetric => {
32
+ const formattedTags = tags.reduce((acc, t) => {
33
+ const [k, v] = t.split(':')
34
+ acc[k] = v
35
+ return acc
36
+ }, {} as Record<string, string>)
37
+
38
+ return {
39
+ type: 'Counter',
40
+ metric,
41
+ value: 1,
42
+ tags: {
43
+ ...formattedTags,
44
+ library: 'analytics.js',
45
+ library_version:
46
+ versionType === 'web' ? `next-${version}` : `npm:next-${version}`,
47
+ },
48
+ }
49
+ }
50
+
51
+ function logError(err: unknown): void {
52
+ console.error('Error sending hightouch performance metrics', err)
53
+ }
54
+
55
+ export class RemoteMetrics {
56
+ private host: string
57
+ private flushTimer: number
58
+ private maxQueueSize: number
59
+
60
+ sampleRate: number
61
+ queue: RemoteMetric[]
62
+
63
+ constructor(options?: MetricsOptions) {
64
+ this.host = options?.host ?? HIGHTOUCH_API_HOST
65
+ this.sampleRate = options?.sampleRate ?? 1
66
+ this.flushTimer = options?.flushTimer ?? 30 * 1000 /* 30s */
67
+ this.maxQueueSize = options?.maxQueueSize ?? 20
68
+
69
+ this.queue = []
70
+
71
+ if (this.sampleRate > 0) {
72
+ let flushing = false
73
+
74
+ const run = (): void => {
75
+ if (flushing) {
76
+ return
77
+ }
78
+
79
+ flushing = true
80
+ this.flush().catch(logError)
81
+
82
+ flushing = false
83
+
84
+ setTimeout(run, this.flushTimer)
85
+ }
86
+ run()
87
+ }
88
+ }
89
+
90
+ increment(metric: string, tags: string[]): void {
91
+ // All metrics are part of an allow list in Tracking API
92
+ if (!metric.includes('analytics_js.')) {
93
+ return
94
+ }
95
+
96
+ // /m doesn't like empty tags
97
+ if (tags.length === 0) {
98
+ return
99
+ }
100
+
101
+ if (Math.random() > this.sampleRate) {
102
+ return
103
+ }
104
+
105
+ if (this.queue.length >= this.maxQueueSize) {
106
+ return
107
+ }
108
+
109
+ const remoteMetric = createRemoteMetric(metric, tags, getVersionType())
110
+ this.queue.push(remoteMetric)
111
+
112
+ if (metric.includes('error')) {
113
+ this.flush().catch(logError)
114
+ }
115
+ }
116
+
117
+ async flush(): Promise<void> {
118
+ if (this.queue.length <= 0) {
119
+ return
120
+ }
121
+
122
+ await this.send().catch((error) => {
123
+ logError(error)
124
+ this.sampleRate = 0
125
+ })
126
+ }
127
+
128
+ private async send(): Promise<Response> {
129
+ const payload = { series: this.queue }
130
+ this.queue = []
131
+
132
+ const headers = {
133
+ Accept: 'application/json',
134
+ 'Content-Type': 'application/json',
135
+ }
136
+ const url = `https://${this.host}/v1/m`
137
+
138
+ return fetch(url, {
139
+ headers,
140
+ body: JSON.stringify(payload),
141
+ method: 'POST',
142
+ })
143
+ }
144
+ }
@@ -0,0 +1,58 @@
1
+ import { CookieStorage } from '../cookieStorage'
2
+ import jar from 'js-cookie'
3
+
4
+ describe('cookieStorage', () => {
5
+ function clearCookies() {
6
+ document.cookie.split(';').forEach(function (c) {
7
+ document.cookie = c
8
+ .replace(/^ +/, '')
9
+ .replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/')
10
+ })
11
+ }
12
+
13
+ afterEach(() => {
14
+ clearCookies()
15
+ })
16
+
17
+ describe('cookie options', () => {
18
+ it('should have default cookie options', () => {
19
+ const cookie = new CookieStorage()
20
+ expect(cookie['options'].domain).toBe(undefined)
21
+ expect(cookie['options'].maxage).toBe(365)
22
+ expect(cookie['options'].path).toBe('/')
23
+ expect(cookie['options'].sameSite).toBe('Lax')
24
+ expect(cookie['options'].secure).toBe(undefined)
25
+ })
26
+
27
+ it('should set options properly', () => {
28
+ const cookie = new CookieStorage({
29
+ domain: 'foo',
30
+ secure: true,
31
+ path: '/test',
32
+ })
33
+ expect(cookie['options'].domain).toBe('foo')
34
+ expect(cookie['options'].secure).toBe(true)
35
+ expect(cookie['options'].path).toBe('/test')
36
+ expect(cookie['options'].secure).toBe(true)
37
+ })
38
+
39
+ it('should pass options when creating cookie', () => {
40
+ const jarSpy = jest.spyOn(jar, 'set')
41
+ const cookie = new CookieStorage({
42
+ domain: 'foo',
43
+ secure: true,
44
+ path: '/test',
45
+ })
46
+
47
+ cookie.set('foo', 'bar')
48
+
49
+ expect(jarSpy).toHaveBeenCalledWith('foo', 'bar', {
50
+ domain: 'foo',
51
+ expires: 365,
52
+ path: '/test',
53
+ sameSite: 'Lax',
54
+ secure: true,
55
+ })
56
+ })
57
+ })
58
+ })
@@ -0,0 +1,70 @@
1
+ import { LocalStorage } from '../localStorage'
2
+
3
+ describe('LocalStorage', function () {
4
+ let store: LocalStorage
5
+
6
+ beforeEach(() => {
7
+ jest.spyOn(console, 'warn').mockImplementation(() => {}) // silence console spam.
8
+ store = new LocalStorage()
9
+ })
10
+
11
+ afterEach(() => {
12
+ localStorage.clear()
13
+ })
14
+
15
+ describe('#get', function () {
16
+ it('should return null if localStorage throws an error (or does not exist)', function () {
17
+ const getItemSpy = jest
18
+ .spyOn(global.Storage.prototype, 'getItem')
19
+ .mockImplementationOnce(() => {
20
+ throw new Error('getItem fail.')
21
+ })
22
+ store.set('foo', 'some value')
23
+ expect(store.get('foo')).toBeNull()
24
+ expect(getItemSpy).toBeCalledTimes(1)
25
+ })
26
+
27
+ it('should not get an empty record', function () {
28
+ expect(store.get('abc')).toBe(null)
29
+ })
30
+
31
+ it('should get an existing record', function () {
32
+ store.set('x', { a: 'b' })
33
+ store.set('a', 'hello world')
34
+ store.set('b', '')
35
+ store.set('c', false)
36
+ store.set('d', null)
37
+ store.set('e', undefined)
38
+
39
+ expect(store.get('x')).toStrictEqual({ a: 'b' })
40
+ expect(store.get('a')).toBe('hello world')
41
+ expect(store.get('b')).toBe('')
42
+ expect(store.get('c')).toBe(false)
43
+ expect(store.get('d')).toBe(null)
44
+ expect(store.get('e')).toBe('undefined')
45
+ })
46
+ })
47
+
48
+ describe('#set', function () {
49
+ it('should be able to set a record', function () {
50
+ store.set('x', { a: 'b' })
51
+ expect(store.get('x')).toStrictEqual({ a: 'b' })
52
+ })
53
+
54
+ it('should catch localStorage quota exceeded errors', () => {
55
+ const val = 'x'.repeat(10 * 1024 * 1024)
56
+ store.set('foo', val)
57
+
58
+ expect(store.get('foo')).toBe(null)
59
+ })
60
+ })
61
+
62
+ describe('#clear', function () {
63
+ it('should be able to remove a record', function () {
64
+ store.set('x', { a: 'b' })
65
+ expect(store.get('x')).toStrictEqual({ a: 'b' })
66
+ store.remove('x')
67
+ expect(store.get('x')).toBe(null)
68
+ })
69
+ })
70
+ })
@@ -0,0 +1,26 @@
1
+ import jar from 'js-cookie'
2
+ const throwDisabledError = () => {
3
+ throw new Error('__sorry brah, this storage is disabled__')
4
+ }
5
+ /**
6
+ * Disables Cookies
7
+ * @returns jest spy
8
+ */
9
+ export function disableCookies(): void {
10
+ jest.spyOn(window.navigator, 'cookieEnabled', 'get').mockReturnValue(false)
11
+ jest.spyOn(jar, 'set').mockImplementation(throwDisabledError)
12
+ jest.spyOn(jar, 'get').mockImplementation(throwDisabledError)
13
+ }
14
+
15
+ /**
16
+ * Disables LocalStorage
17
+ * @returns jest spy
18
+ */
19
+ export function disableLocalStorage(): void {
20
+ jest
21
+ .spyOn(Storage.prototype, 'setItem')
22
+ .mockImplementation(throwDisabledError)
23
+ jest
24
+ .spyOn(Storage.prototype, 'getItem')
25
+ .mockImplementation(throwDisabledError)
26
+ }
@@ -0,0 +1,167 @@
1
+ import jar from 'js-cookie'
2
+ import { CookieStorage } from '../cookieStorage'
3
+ import { LocalStorage } from '../localStorage'
4
+ import { MemoryStorage } from '../memoryStorage'
5
+ import { UniversalStorage } from '../universalStorage'
6
+ import { disableCookies, disableLocalStorage } from './test-helpers'
7
+
8
+ describe('UniversalStorage', function () {
9
+ const defaultTargets = [
10
+ new CookieStorage(),
11
+ new LocalStorage(),
12
+ new MemoryStorage(),
13
+ ]
14
+ const getFromLS = (key: string) => JSON.parse(localStorage.getItem(key) ?? '')
15
+ jest.spyOn(console, 'warn').mockImplementation(() => {
16
+ // avoid accidental noise in console
17
+ throw new Error('console.warn should be mocked!')
18
+ })
19
+
20
+ beforeEach(function () {
21
+ jest.restoreAllMocks()
22
+ clear()
23
+ })
24
+
25
+ function clear(): void {
26
+ document.cookie.split(';').forEach(function (c) {
27
+ document.cookie = c
28
+ .replace(/^ +/, '')
29
+ .replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/')
30
+ })
31
+ localStorage.clear()
32
+ }
33
+
34
+ describe('#get', function () {
35
+ it('picks data from cookies first', function () {
36
+ jar.set('ajs_test_key', '🍪')
37
+ localStorage.setItem('ajs_test_key', '💾')
38
+ const us = new UniversalStorage(defaultTargets)
39
+ expect(us.get('ajs_test_key')).toEqual('🍪')
40
+ })
41
+
42
+ it('picks data from localStorage if there is no cookie target', function () {
43
+ jar.set('ajs_test_key', '🍪')
44
+ localStorage.setItem('ajs_test_key', '💾')
45
+ const us = new UniversalStorage([new LocalStorage(), new MemoryStorage()])
46
+ expect(us.get('ajs_test_key')).toEqual('💾')
47
+ })
48
+
49
+ it('get data from memory', function () {
50
+ jar.set('ajs_test_key', '🍪')
51
+ localStorage.setItem('ajs_test_key', '💾')
52
+ const us = new UniversalStorage([new MemoryStorage()])
53
+ expect(us.get('ajs_test_key')).toBeNull()
54
+ })
55
+
56
+ it('order of default targets matters!', function () {
57
+ jar.set('ajs_test_key', '🍪')
58
+ localStorage.setItem('ajs_test_key', '💾')
59
+ const us = new UniversalStorage([
60
+ new LocalStorage(),
61
+ new CookieStorage(),
62
+ new MemoryStorage(),
63
+ ])
64
+ expect(us.get('ajs_test_key')).toEqual('💾')
65
+ })
66
+
67
+ it('returns null if there are no storage targets', function () {
68
+ jar.set('ajs_test_key', '🍪')
69
+ localStorage.setItem('ajs_test_key', '💾')
70
+ const us = new UniversalStorage([])
71
+ expect(us.get('ajs_test_key')).toBeNull()
72
+ })
73
+ })
74
+
75
+ describe('#set', function () {
76
+ it('sets the data in all storage types', function () {
77
+ const us = new UniversalStorage<{ ajs_test_key: string }>(defaultTargets)
78
+ us.set('ajs_test_key', '💰')
79
+ expect(jar.get('ajs_test_key')).toEqual('💰')
80
+ expect(getFromLS('ajs_test_key')).toEqual('💰')
81
+ })
82
+
83
+ it('skip saving data to localStorage', function () {
84
+ const us = new UniversalStorage([
85
+ new CookieStorage(),
86
+ new MemoryStorage(),
87
+ ])
88
+ us.set('ajs_test_key', '💰')
89
+ expect(jar.get('ajs_test_key')).toEqual('💰')
90
+ expect(localStorage.getItem('ajs_test_key')).toEqual(null)
91
+ })
92
+
93
+ it('skip saving data to cookie', function () {
94
+ const us = new UniversalStorage([new LocalStorage(), new MemoryStorage()])
95
+ us.set('ajs_test_key', '💰')
96
+ expect(jar.get('ajs_test_key')).toEqual(undefined)
97
+ expect(getFromLS('ajs_test_key')).toEqual('💰')
98
+ })
99
+
100
+ it('can save and retrieve from memory when there is no other storage', function () {
101
+ const us = new UniversalStorage([new MemoryStorage()])
102
+ us.set('ajs_test_key', '💰')
103
+ expect(jar.get('ajs_test_key')).toEqual(undefined)
104
+ expect(localStorage.getItem('ajs_test_key')).toEqual(null)
105
+ expect(us.get('ajs_test_key')).toEqual('💰')
106
+ })
107
+
108
+ it('handles cookie errors gracefully', function () {
109
+ const consoleWarnSpy = jest
110
+ .spyOn(console, 'warn')
111
+ .mockImplementation(() => {})
112
+
113
+ disableCookies() // Cookies is going to throw exceptions now
114
+ const us = new UniversalStorage([
115
+ new LocalStorage(),
116
+ new CookieStorage(),
117
+ new MemoryStorage(),
118
+ ])
119
+ us.set('ajs_test_key', '💰')
120
+ expect(getFromLS('ajs_test_key')).toEqual('💰')
121
+ expect(us.get('ajs_test_key')).toEqual('💰')
122
+ expect(consoleWarnSpy.mock.calls.length).toEqual(1)
123
+ expect(consoleWarnSpy.mock.lastCall[0]).toContain(
124
+ "CookieStorage: Can't set key"
125
+ )
126
+ })
127
+
128
+ it('does not write to LS when LS is not available', function () {
129
+ const consoleWarnSpy = jest
130
+ .spyOn(console, 'warn')
131
+ .mockImplementation(() => {})
132
+
133
+ disableLocalStorage() // Localstorage will throw exceptions
134
+ const us = new UniversalStorage([
135
+ new LocalStorage(),
136
+ new CookieStorage(),
137
+ new MemoryStorage(),
138
+ ])
139
+ us.set('ajs_test_key', '💰')
140
+ expect(jar.get('ajs_test_key')).toEqual('💰')
141
+ expect(us.get('ajs_test_key')).toEqual('💰')
142
+ expect(consoleWarnSpy.mock.lastCall[0]).toContain('localStorage')
143
+ })
144
+
145
+ it('handles cookie getter overrides gracefully', function () {
146
+ const consoleWarnSpy = jest
147
+ .spyOn(console, 'warn')
148
+ .mockImplementation(() => {})
149
+
150
+ ;(document as any).__defineGetter__('cookie', function () {
151
+ return ''
152
+ })
153
+ const us = new UniversalStorage([
154
+ new LocalStorage(),
155
+ new CookieStorage(),
156
+ new MemoryStorage(),
157
+ ])
158
+ us.set('ajs_test_key', '💰')
159
+ expect(getFromLS('ajs_test_key')).toEqual('💰')
160
+ expect(us.get('ajs_test_key')).toEqual('💰')
161
+ expect(consoleWarnSpy.mock.lastCall[0]).toContain(
162
+ "CookieStorage: Can't set key"
163
+ )
164
+ expect(consoleWarnSpy.mock.lastCall[0]).toContain('TypeError')
165
+ })
166
+ })
167
+ })