@tech4good/angular-schematics 21.6.0 → 21.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +266 -1
  3. package/package.json +34 -7
  4. package/src/component/files/__name@dasherize__/__name@dasherize__.component.spec.ts.template +4 -5
  5. package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +1 -1
  6. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +14 -6
  7. package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +12 -6
  8. package/src/entity/files/__name@dasherize__/__name@dasherize__.store.ts.template +18 -10
  9. package/src/entity/index.js +4 -49
  10. package/src/entity/index.js.map +1 -1
  11. package/src/guard/files/__name@dasherize__.guard.spec.ts.template +0 -1
  12. package/src/ng-add/files/.github/workflows/angular-github-ci.yml.template +3 -0
  13. package/src/ng-add/files/.gitignore.template +3 -0
  14. package/src/ng-add/files/analytics/datasets.js.template +206 -0
  15. package/src/ng-add/files/analytics/entity_sources.js.template +58 -0
  16. package/src/ng-add/files/analytics/entity_sources.test.js.template +57 -0
  17. package/src/ng-add/files/analytics/lib/api_query.js.template +87 -0
  18. package/src/ng-add/files/analytics/lib/api_query.test.js.template +84 -0
  19. package/src/ng-add/files/analytics/lib/bigquery_query_compatibility.test.js.template +53 -0
  20. package/src/ng-add/files/analytics/lib/dataset_schema.js.template +53 -0
  21. package/src/ng-add/files/analytics/lib/dataset_schema.test.js.template +34 -0
  22. package/src/ng-add/files/analytics/lib/entity_sync.js.template +397 -0
  23. package/src/ng-add/files/analytics/lib/entity_sync.test.js.template +212 -0
  24. package/src/ng-add/files/analytics/lib/identifier_salt.js.template +57 -0
  25. package/src/ng-add/files/analytics/lib/identifier_salt.test.js.template +36 -0
  26. package/src/ng-add/files/analytics/lib/snapshot_files.js.template +46 -0
  27. package/src/ng-add/files/analytics/lib/snapshot_files.test.js.template +67 -0
  28. package/src/ng-add/files/analytics/lib/sqlite.js.template +92 -0
  29. package/src/ng-add/files/analytics/lib/upload_entities.js.template +81 -0
  30. package/src/ng-add/files/analytics/lib/upload_entities.test.js.template +86 -0
  31. package/src/ng-add/files/analytics/proxy.conf.json.template +7 -0
  32. package/src/ng-add/files/analytics/scripts/refresh_snapshot.js.template +518 -0
  33. package/src/ng-add/files/analytics/scripts/start.js.template +88 -0
  34. package/src/ng-add/files/analytics/server/server.js.template +212 -0
  35. package/src/ng-add/files/angular.json.template +80 -1
  36. package/src/ng-add/files/bigquery/queries/active_time_by_route.sql.template +27 -8
  37. package/src/ng-add/files/bigquery/queries/active_user_windows.sql.template +67 -0
  38. package/src/ng-add/files/bigquery/queries/dashboard_route_visits.sql.template +47 -0
  39. package/src/ng-add/files/bigquery/queries/data_quality.sql.template +323 -0
  40. package/src/ng-add/files/bigquery/queries/onboarding_funnel.sql.template +512 -0
  41. package/src/ng-add/files/bigquery/queries/onboarding_stage_observations.sql.template +134 -0
  42. package/src/ng-add/files/bigquery/queries/weekly_retention_cohorts.sql.template +90 -0
  43. package/src/ng-add/files/bigquery/scripts/export_entities.js.template +120 -0
  44. package/src/ng-add/files/bigquery/scripts/init_views.js.template +57 -0
  45. package/src/ng-add/files/bigquery/scripts/run_query.js.template +141 -0
  46. package/src/ng-add/files/bigquery/views/events_flat.sql.template +27 -12
  47. package/src/ng-add/files/bigquery/views/logs_latest.sql.template +16 -3
  48. package/src/ng-add/files/docs-infra/analytics-guide.md.template +270 -25
  49. package/src/ng-add/files/docs-infra/analytics-workbench-guide.md.template +307 -0
  50. package/src/ng-add/files/docs-infra/authentication-architecture.md.template +54 -24
  51. package/src/ng-add/files/docs-infra/email-infrastructure.md.template +43 -0
  52. package/src/ng-add/files/docs-infra/firestore-index-checker.md.template +87 -0
  53. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +108 -29
  54. package/src/ng-add/files/docs-infra/load-system-architecture.md.template +15 -1
  55. package/src/ng-add/files/docs-infra/querying-strategy.md.template +14 -0
  56. package/src/ng-add/files/docs-infra/stream-system-architecture.md.template +21 -7
  57. package/src/ng-add/files/eslint.config.js.template +22 -3
  58. package/src/ng-add/files/functions/package.json.template +1 -0
  59. package/src/ng-add/files/functions/src/email.ts.template +23 -0
  60. package/src/ng-add/files/jest.config.ts.template +3 -2
  61. package/src/ng-add/files/package.json.template +39 -16
  62. package/src/ng-add/files/projects/analytics/src/app/analytics-api.service.ts.template +130 -0
  63. package/src/ng-add/files/projects/analytics/src/app/app.component.html.template +77 -0
  64. package/src/ng-add/files/projects/analytics/src/app/app.component.scss.template +240 -0
  65. package/src/ng-add/files/projects/analytics/src/app/app.component.ts.template +96 -0
  66. package/src/ng-add/files/projects/analytics/src/app/app.routes.ts.template +11 -0
  67. package/src/ng-add/files/projects/analytics/src/app/dashboard-pages.spec.ts.template +151 -0
  68. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.html.template +39 -0
  69. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.scss.template +1 -0
  70. package/src/ng-add/files/projects/analytics/src/app/data-quality/data-quality-page/data-quality-page.component.ts.template +95 -0
  71. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.html.template +47 -0
  72. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.scss.template +1 -0
  73. package/src/ng-add/files/projects/analytics/src/app/engagement/engagement-page/engagement-page.component.ts.template +120 -0
  74. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.html.template +40 -0
  75. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.scss.template +1 -0
  76. package/src/ng-add/files/projects/analytics/src/app/onboarding/onboarding-page/onboarding-page.component.ts.template +98 -0
  77. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.html.template +35 -0
  78. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.scss.template +1 -0
  79. package/src/ng-add/files/projects/analytics/src/app/overview/overview-page/overview-page.component.ts.template +84 -0
  80. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.html.template +42 -0
  81. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.scss.template +1 -0
  82. package/src/ng-add/files/projects/analytics/src/app/routes/routes-page/routes-page.component.ts.template +110 -0
  83. package/src/ng-add/files/projects/analytics/src/app/shared/analytics-utils.ts.template +43 -0
  84. package/src/ng-add/files/projects/analytics/src/app/shared/chart-theme.ts.template +42 -0
  85. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-layout.scss.template +239 -0
  86. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.html.template +76 -0
  87. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.scss.template +128 -0
  88. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.spec.ts.template +31 -0
  89. package/src/ng-add/files/projects/analytics/src/app/shared/dashboard-table/dashboard-table.component.ts.template +153 -0
  90. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.html.template +16 -0
  91. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.scss.template +63 -0
  92. package/src/ng-add/files/projects/analytics/src/app/shared/funnel-chart/funnel-chart.component.ts.template +52 -0
  93. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.html.template +5 -0
  94. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.scss.template +56 -0
  95. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.spec.ts.template +30 -0
  96. package/src/ng-add/files/projects/analytics/src/app/shared/metric-card/metric-card.component.ts.template +15 -0
  97. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.html.template +9 -0
  98. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.scss.template +43 -0
  99. package/src/ng-add/files/projects/analytics/src/app/shared/quality-chart/quality-chart.component.ts.template +62 -0
  100. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.html.template +9 -0
  101. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.scss.template +33 -0
  102. package/src/ng-add/files/projects/analytics/src/app/shared/route-distribution-chart/route-distribution-chart.component.ts.template +82 -0
  103. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.html.template +15 -0
  104. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.scss.template +45 -0
  105. package/src/ng-add/files/projects/analytics/src/app/shared/route-traffic-chart/route-traffic-chart.component.ts.template +55 -0
  106. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.html.template +18 -0
  107. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.scss.template +45 -0
  108. package/src/ng-add/files/projects/analytics/src/app/shared/status-message/status-message.component.ts.template +15 -0
  109. package/src/ng-add/files/projects/analytics/src/app/vega-chart/vega-chart.component.ts.template +121 -0
  110. package/src/ng-add/files/projects/analytics/src/index.html.template +19 -0
  111. package/src/ng-add/files/projects/analytics/src/main.ts.template +16 -0
  112. package/src/ng-add/files/projects/analytics/src/styles.scss.template +28 -0
  113. package/src/ng-add/files/projects/analytics/tsconfig.app.json.template +13 -0
  114. package/src/ng-add/files/projects/analytics/tsconfig.spec.json.template +15 -0
  115. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +4 -5
  116. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.spec.ts.template +4 -5
  117. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.spec.ts.template +11 -12
  118. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +7 -7
  119. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.spec.ts.template +8 -10
  120. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +3 -2
  121. package/src/ng-add/files/src/app/app.component.html.template +1 -1
  122. package/src/ng-add/files/src/app/app.component.scss.template +1 -1
  123. package/src/ng-add/files/src/app/app.component.spec.ts.template +4 -5
  124. package/src/ng-add/files/src/app/app.component.ts.template +1 -2
  125. package/src/ng-add/files/src/app/app.config.ts.template +21 -15
  126. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +4 -5
  127. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +46 -29
  128. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +27 -18
  129. package/src/ng-add/files/src/app/core/auth/auth.providers.spec.ts.template +112 -0
  130. package/src/ng-add/files/src/app/core/auth/auth.providers.ts.template +48 -0
  131. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +9 -23
  132. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +3 -14
  133. package/src/ng-add/files/src/app/core/firebase/data.providers.prod.ts.template +21 -0
  134. package/src/ng-add/files/src/app/core/firebase/data.providers.ts.template +13 -0
  135. package/src/ng-add/files/src/app/core/local-storage/session.service.spec.ts.template +43 -0
  136. package/src/ng-add/files/src/app/core/local-storage/session.service.ts.template +7 -0
  137. package/src/ng-add/files/src/app/core/store/app-data.spec.ts.template +76 -0
  138. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +19 -67
  139. package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +102 -12
  140. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +32 -237
  141. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +17 -12
  142. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +6 -7
  143. package/src/ng-add/files/src/app/core/store/user/user.store.ts.template +14 -10
  144. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +20 -8
  145. package/src/ng-add/files/src/app/core/store/user-context/user-context.model.ts.template +5 -6
  146. package/src/ng-add/files/src/app/core/store/user-context/user-context.store.ts.template +14 -10
  147. package/src/ng-add/files/src/app/core/store/user-private/user-private.mock.ts.template +20 -7
  148. package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +5 -6
  149. package/src/ng-add/files/src/app/core/store/user-private/user-private.store.ts.template +14 -10
  150. package/src/ng-add/files/src/app/core/testing/app-mocks.ts.template +42 -0
  151. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +2 -1
  152. package/src/ng-add/files/src/app/first-time/consent/consent.component.scss.template +7 -3
  153. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +31 -11
  154. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +16 -1
  155. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +15 -15
  156. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +11 -3
  157. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.html.template +2 -1
  158. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.scss.template +7 -3
  159. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.spec.ts.template +20 -6
  160. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.ts.template +2 -0
  161. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.spec.ts.template +4 -5
  162. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +17 -1
  163. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +15 -0
  164. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +4 -5
  165. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +15 -0
  166. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +2 -0
  167. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +21 -3
  168. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +26 -0
  169. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.spec.ts.template +4 -2
  170. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.ts.template +1 -1
  171. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +2 -2
  172. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +2 -2
  173. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +4 -4
  174. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +2 -2
  175. package/src/ng-add/files/src/app/main/home/home.component.spec.ts.template +4 -5
  176. package/src/ng-add/files/src/app/main/home/home.component.ts.template +1 -1
  177. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +4 -4
  178. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +2 -2
  179. package/src/ng-add/files/tsconfig.spec.json.template +3 -1
  180. package/src/ng-add/index.js +7 -0
  181. package/src/ng-add/index.js.map +1 -1
  182. package/src/shared/entity-registry.d.ts +8 -0
  183. package/src/shared/entity-registry.js +28 -0
  184. package/src/shared/entity-registry.js.map +1 -0
  185. package/.agents/skills/publish-npm/SKILL.md +0 -37
  186. package/.agents/skills/publish-npm/eval.yaml +0 -32
  187. package/.agents/skills/publish-npm/fixtures/package-v21.json.template +0 -8
  188. package/.husky/commit-msg +0 -1
  189. package/.husky/pre-commit +0 -1
  190. package/.t4g/agent-memory.db +0 -0
  191. package/src/component/index_spec.d.ts +0 -1
  192. package/src/component/index_spec.js +0 -68
  193. package/src/component/index_spec.js.map +0 -1
  194. package/src/entity/index_spec.d.ts +0 -1
  195. package/src/entity/index_spec.js +0 -153
  196. package/src/entity/index_spec.js.map +0 -1
  197. package/src/guard/index_spec.d.ts +0 -1
  198. package/src/guard/index_spec.js +0 -64
  199. package/src/guard/index_spec.js.map +0 -1
  200. package/src/ng-add/files/bigquery/scripts/export_entities.py.template +0 -143
  201. package/src/ng-add/files/bigquery/scripts/run_query.py.template +0 -167
  202. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +0 -500
  203. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +0 -73
  204. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.spec.ts.template +0 -59
  205. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.ts.template +0 -147
  206. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +0 -453
  207. package/src/ng-add/files/src/app/core/firebase/firebase.service.spec.ts.template +0 -116
  208. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +0 -639
  209. package/src/ng-add/files/src/app/core/firebase/simulate-load.spec.ts.template +0 -104
  210. package/src/ng-add/files/src/app/core/firebase/simulate-stream.spec.ts.template +0 -127
  211. package/src/ng-add/files/src/app/core/firebase/simulation.mock.ts.template +0 -38
  212. package/src/ng-add/files/src/app/core/firebase/stream-multiplexer.ts.template +0 -445
  213. package/src/ng-add/files/src/app/core/logging/logging.service.spec.ts.template +0 -118
  214. package/src/ng-add/files/src/app/core/logging/logging.service.ts.template +0 -168
  215. package/src/ng-add/files/src/app/core/store/app.model.ts.template +0 -21
  216. package/src/ng-add/files/src/app/core/store/app.store.spec.ts.template +0 -920
  217. package/src/ng-add/files/src/app/core/store/app.store.ts.template +0 -1320
  218. package/src/ng-add/files/src/app/core/store/batch-write.firebase.service.ts.template +0 -58
  219. package/src/ng-add/files/src/app/core/store/batch-write.mock.service.ts.template +0 -105
  220. package/src/ng-add/files/src/app/core/store/batch-write.service.ts.template +0 -126
  221. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +0 -9
  222. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.scss.template +0 -46
  223. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.spec.ts.template +0 -69
  224. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +0 -39
  225. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.spec.ts.template +0 -122
  226. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +0 -88
  227. package/src/ng-add/index_spec.d.ts +0 -1
  228. package/src/ng-add/index_spec.js +0 -108
  229. package/src/ng-add/index_spec.js.map +0 -1
@@ -1,500 +0,0 @@
1
- import { Inject, Injectable, WritableSignal, inject, DestroyRef, computed } from '@angular/core';
2
- import { toObservable } from '@angular/core/rxjs-interop';
3
- import { Subject, Observable, merge, forkJoin, of, from, pipe } from 'rxjs';
4
- import { startWith, pairwise, share, tap, pluck, mergeMap, filter, takeUntil, skipUntil, buffer, skip, switchMap, map, take } from 'rxjs/operators';
5
- import { setEntities, setEntity, removeEntities, SelectEntityId } from '@ngrx/signals/entities';
6
- import { EntityLoadQuery, EntityStreamQuery, entityInQueryResults } from '../store/app.store';
7
- import { QueryParams, QueryOptions, AnyEntity } from '../store/app.model';
8
- import { DocumentChange } from '@angular/fire/firestore';
9
- import { DATABASE_SERVICE, DatabaseService } from './database.service';
10
- import { StreamMultiplexer } from './stream-multiplexer';
11
- import { getLogger } from '../logging/logging.service';
12
-
13
- const queryLogger = getLogger('query');
14
-
15
- const selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;
16
-
17
- export interface CachedConnection {
18
- queryKey: string;
19
- registeredSet: Set<DestroyRef>;
20
- }
21
-
22
-
23
- /**
24
- * CachedListenersService manages database connections and their lifecycles to
25
- * ensure optimal performance, prevent memory leaks, and solve the N+1 query problem.
26
- *
27
- * Responsibilities:
28
- * 1. **Listener Pooling**: Deduplicates active Firestore snapshot listeners. If multiple
29
- * components request a stream for the exact same query, only one actual database
30
- * connection is opened.
31
- * 2. **Reference Counting & Lifecycle Management**: Tracks which components are using
32
- * which stream via their Angular `DestroyRef`. When a component is destroyed, its
33
- * reference is removed.
34
- * 3. **Graceful Teardown**: Implements a 5-second grace period before fully closing a
35
- * database connection after its last reference drops. This prevents UI flicker and
36
- * unnecessary DB reads if the user navigates away and immediately back.
37
- * 4. **Load Time Tracking (One-shot Loads)**: Tracks `lastLoadTime` for general queries
38
- * and precise `entityLoadTime` for optimized batch equality queries. This enables
39
- * incremental (delta-only) fetching, drastically reducing bandwidth by only fetching
40
- * entities modified since the last load.
41
- */
42
- @Injectable({
43
- providedIn: 'root',
44
- })
45
- export class CachedListenersService {
46
- /** Cached connections by loadKey. */
47
- private connectionByQueryKey: Record<string, CachedConnection> = {};
48
-
49
- /** Active multiplexers by collection.field */
50
- private streamMultiplexers = new Map<string, StreamMultiplexer>();
51
-
52
- /** Close connection events. */
53
- private closeConnection$: Subject<string> = new Subject<string>();
54
-
55
-
56
- /** Load state across the app by queryKey. Stores last load time in milliseconds. */
57
- private lastLoadTime: Record<string, number> = {};
58
-
59
- /** Per-entity load times for optimized equality queries. Key: "collection.field:value" */
60
- private entityLoadTime: Record<string, number> = {};
61
-
62
- getEntityLoadTime(collection: string, field: string, value: string): number {
63
- return this.entityLoadTime[`${collection}.${field}:${value}`] || -1;
64
- }
65
-
66
- setEntityLoadTime(collection: string, field: string, value: string, time: number): void {
67
- this.entityLoadTime[`${collection}.${field}:${value}`] = time;
68
- }
69
-
70
- /** Define a unique key for each connection. */
71
- private getQueryKey(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): string {
72
- let queryOptionsString = '';
73
- if (queryOptions) {
74
- if (queryOptions.orderBy) {
75
- queryOptionsString = queryOptionsString.concat(`orderBy${queryOptions.orderBy}`);
76
- }
77
- if (queryOptions.limit) {
78
- queryOptionsString = queryOptionsString.concat(`limit${queryOptions.limit}`);
79
- }
80
- if (queryOptions.startAt) {
81
- queryOptionsString = queryOptionsString.concat(`startAt${queryOptions.startAt}`);
82
- }
83
- if (queryOptions.startAfter) {
84
- queryOptionsString = queryOptionsString.concat(`startAfter${queryOptions.startAfter}`);
85
- }
86
- if (queryOptions.endAt) {
87
- queryOptionsString = queryOptionsString.concat(`endAt${queryOptions.endAt}`);
88
- }
89
- if (queryOptions.endBefore) {
90
- queryOptionsString = queryOptionsString.concat(`endBefore${queryOptions.endBefore}`);
91
- }
92
- }
93
- return `${collection}.${queryParams.sort()}.${queryOptionsString}`;
94
- }
95
-
96
- /**
97
- * Tears down active Firestore listeners before authentication is removed.
98
- * Load-time tracking is also reset so the next account performs fresh queries.
99
- */
100
- teardownAllStreams(): void {
101
- for (const key of Object.keys(this.connectionByQueryKey)) {
102
- const connection = this.connectionByQueryKey[key];
103
- if (connection) {
104
- this.closeConnection$.next(key);
105
- connection.registeredSet.clear();
106
- }
107
- }
108
- this.connectionByQueryKey = {};
109
-
110
- for (const multiplexer of this.streamMultiplexers.values()) {
111
- multiplexer.teardownAll();
112
- }
113
- this.streamMultiplexers.clear();
114
- this.lastLoadTime = {};
115
- this.entityLoadTime = {};
116
- }
117
-
118
- /**
119
- * Clear cached connection states and last load times.
120
- * NOTE: This is intended for resetting state between tests.
121
- */
122
- clearCache(): void {
123
- this.teardownAllStreams();
124
- }
125
-
126
- /** Return whether a stream exists for this query. */
127
- isStreamForQuery(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): boolean {
128
- const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
129
- return !!this.connectionByQueryKey[queryKey];
130
- }
131
-
132
- /** Return whether a specific ID is currently being streamed by a multiplexer. */
133
- isIdStreamed(collection: string, field: string, id: string): boolean {
134
- const multiplexerKey = `${collection}.${field}`;
135
- const multiplexer = this.streamMultiplexers.get(multiplexerKey);
136
- return multiplexer ? multiplexer.isIdActive(id) : false;
137
- }
138
-
139
- /** Get the last load time for a particular query. */
140
- getLastLoadTime(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): number {
141
- // If there are queryOptions, we don't support saving load times
142
- if (queryOptions && Object.keys(queryOptions).length > 0) return -1;
143
-
144
- const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
145
- return this.lastLoadTime[queryKey] || -1;
146
- }
147
-
148
- /** Set the last load time for a particular query. */
149
- setLastLoadTime(collection: string, queryParams: QueryParams, queryOptions: QueryOptions, time: number): void {
150
- // If there are queryOptions, we don't support saving load times
151
- if (queryOptions && Object.keys(queryOptions).length > 0) return;
152
-
153
- const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
154
- this.lastLoadTime[queryKey] = time;
155
- }
156
-
157
- /** Gets a cached connection if one exists. */
158
- private getConnection(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): CachedConnection {
159
- const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
160
- return this.connectionByQueryKey[queryKey];
161
- }
162
-
163
- /**
164
- * Main function called by the outside.
165
- */
166
- public async processStreamQuery<T extends AnyEntity>(
167
- collection: string,
168
- store,
169
- queryParams: QueryParams,
170
- queryOptions: QueryOptions,
171
- injector,
172
- streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],
173
- options?: {
174
- loading?: WritableSignal<boolean>,
175
- },
176
- ): Promise<CachedConnection> {
177
- queryLogger.log(`[CachedListenersService] processStreamQuery called for collection: '${collection}', query:`, JSON.stringify(queryParams));
178
- // console.log("PROCESS QUERY: " + this.getQueryKey(collection, queryParams, queryOptions));
179
-
180
- // Get destroyRef for the component that called processStreamQuery
181
- // (which will be used to determine when to trigger unsubscribe)
182
- const destroyRef = injector.get(DestroyRef);
183
-
184
- // get connection and process the immediate query
185
- let connection = this.getConnection(collection, queryParams, queryOptions);
186
-
187
- if (connection) {
188
- // if the connection already exists, don't need to create a new connection,
189
- // but may need to add the DestroyRef if it doesn't already exist
190
- if (!connection.registeredSet.has(destroyRef)) {
191
- connection.registeredSet.add(destroyRef);
192
- }
193
- } else {
194
- // if the connection does not exist, create it and initialize the
195
- // registeredSet to include destroyRef
196
- // this function also will subscribe and link to the store
197
- connection = this.createConnection<T>(collection, store, queryParams, queryOptions, destroyRef);
198
- this.connectionByQueryKey[connection.queryKey] = connection;
199
- }
200
-
201
- // Unregister from the connection when the component is destroyed
202
- // Disconnects the "virtual" connection. If this was the only DestroyRef,
203
- // then actually unsubscribe
204
- destroyRef.onDestroy(() => {
205
- // Add a 5-second delay so we don't have to reconnect multiple times
206
- // if the next view happens to use the same stream
207
- setTimeout(() => {
208
- // If the destroyRef is not in the set, it means this connection was already
209
- // cleared/cleaned up (e.g., via clearCache() in tests), so we bail out.
210
- if (!connection.registeredSet.has(destroyRef)) {
211
- return;
212
- }
213
-
214
- connection.registeredSet.delete(destroyRef);
215
- if (connection.registeredSet.size === 0) {
216
- // Verify that this connection is still the active connection in the cache map.
217
- // This is essential to prevent stale callbacks (e.g. from a previous test case
218
- // that was cleared via clearCache()) from overwriting a new active connection
219
- // in the cache or triggering premature disconnections.
220
- if (this.connectionByQueryKey[connection.queryKey] === connection) {
221
- this.closeConnection$.next(connection.queryKey);
222
- this.connectionByQueryKey[connection.queryKey] = undefined;
223
- }
224
- }
225
- }, 5000);
226
- });
227
-
228
- // For every new entity on the stream, process the nested streamQueries
229
- if (streamQueries) {
230
- // get the entities we're streaming as a signal. we do it here rather than
231
- // using the firestore stream so that we can always get the latest version
232
- // without needing to multicast the original stream to all future components
233
- // querying for the stream
234
- const streamEntities = computed(() => {
235
- return store.selectEntities(queryParams, queryOptions);
236
- });
237
-
238
- // convert to an observable, convert to the changes, then subscribe
239
- // note: we do not need takeUntil for unsubscribing because toObservable will
240
- // unsubscribe once the injector context (passed in from the component/container) is destroyed
241
- toObservable(streamEntities, { injector }).pipe(
242
- // convert to entityMap to more easily compare
243
- map((entities) => {
244
- const entityMap = {};
245
- for (const entity of entities) {
246
- entityMap[entity.__id] = entity;
247
- }
248
- return entityMap;
249
- }),
250
- // compare current with prior including the first
251
- startWith({}),
252
- pairwise(),
253
- // get the changedEntities
254
- map(([prevEntities, currEntities]) => {
255
- const changedEntities = [];
256
- for (const key in currEntities) {
257
- if (!(key in prevEntities)) {
258
- // the entity was added
259
- changedEntities.push({
260
- type: 'added',
261
- doc: currEntities[key],
262
- });
263
- } else if (currEntities[key]['_deleted']) {
264
- // the entity was removed
265
- changedEntities.push({
266
- type: 'removed',
267
- doc: currEntities[key],
268
- });
269
- } else if (currEntities[key]['_updatedAt'] !== prevEntities[key]['_updatedAt']) {
270
- // the entity was modified
271
- changedEntities.push({
272
- type: 'modified',
273
- doc: currEntities[key],
274
- });
275
- }
276
- }
277
-
278
- return changedEntities;
279
- }),
280
- // We don't need the removed ones for nested streamQueries (but I just
281
- // included it above for debugging purposes so we can see all changes)
282
- map((changes) => changes.filter((c) => c.type !== 'removed')),
283
- filter((changes) => changes.length > 0),
284
- ).subscribe(async (changes) => {
285
- // create a matrix of queries, each row corresponding to a given entity
286
- const queriesByEntity = changes.map((change) => streamQueries(change.doc));
287
-
288
- // transpose the matrix so each row corresponds to all queries for the same query type
289
- const queriesByQueryType = queriesByEntity[0].map((_, colIndex) => queriesByEntity.map((row) => row[colIndex]));
290
-
291
- // Process all query types concurrently
292
- await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
293
- // Seeing if we can optimize by collapsing equality queries into 'in' queries
294
- const optimizedQueries = EntityStreamQuery.optimize(queriesForOneType);
295
-
296
- // Process queries concurrently using Promise.all
297
- await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
298
- const isSimpleChild = (!query.queryOptions || Object.keys(query.queryOptions).length === 0) &&
299
- query.queryParams.length === 1 &&
300
- (query.queryParams[0][1] === '==' || query.queryParams[0][1] === 'in');
301
-
302
- if (isSimpleChild) {
303
- const childField = query.queryParams[0][0];
304
- const childOp = query.queryParams[0][1];
305
- const childVal = query.queryParams[0][2];
306
- const childIds = childOp === 'in' ? childVal : [childVal];
307
- queryLogger.log(`[CachedListenersService] Nested query optimized to simple stream query: ${childField} in [${childIds}]`);
308
- await this.processSimpleStreamQuery(query.collection, childField, childIds, query.store, injector, query.streamQueries, { loading: options?.loading });
309
- } else {
310
- queryLogger.log(`[CachedListenersService] Nested query falling back to standard stream query:`, JSON.stringify(query.queryParams));
311
- await this.processStreamQuery(query.collection, query.store, query.queryParams, query.queryOptions, injector, query.streamQueries, { loading: options?.loading });
312
- }
313
- }));
314
- }));
315
- });
316
- } else {
317
- // We'll turn off the loading indicator the first time there is a query that doesn't have nested queries
318
- // (ideally we'd want to turn if off after each of the streams have gotten their first entities, but I
319
- // don't think we can do that easily and this won't be too off)
320
- options?.loading?.set(false);
321
- }
322
-
323
- return connection;
324
- }
325
-
326
- /**
327
- * Optimized fast-path for simple streaming queries (e.g., `id in [1, 2, 3]`).
328
- * Instead of managing distinct complex RxJS subscription chains for every component, this delegates
329
- * ID registration to a centralized `StreamMultiplexer` (per collection/field).
330
- *
331
- * It also handles nested `streamQueries` (e.g. streaming a post's author) by listening to changes
332
- * to the parent entities, diffing them (`pairwise`), and setting up streams for the new children.
333
- */
334
- public async processSimpleStreamQuery<T extends AnyEntity>(
335
- collection: string,
336
- field: string,
337
- ids: string[],
338
- store: any,
339
- injector: any,
340
- streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],
341
- options?: { loading?: WritableSignal<boolean> },
342
- ): Promise<void> {
343
- queryLogger.log(`[CachedListenersService] processSimpleStreamQuery called for collection: '${collection}', field: '${field}', ids: [${ids}]`);
344
-
345
- if (!ids || ids.length === 0) {
346
- options?.loading?.set(false);
347
- return;
348
- }
349
-
350
- const destroyRef = injector.get(DestroyRef);
351
- const multiplexerKey = `${collection}.${field}`;
352
-
353
- let multiplexer = this.streamMultiplexers.get(multiplexerKey);
354
- if (!multiplexer) {
355
- multiplexer = new StreamMultiplexer(collection, field, this.db, store);
356
- this.streamMultiplexers.set(multiplexerKey, multiplexer);
357
- }
358
- multiplexer.registerIds(ids, destroyRef);
359
-
360
- if (streamQueries) {
361
- // 1. We select the entities from the store.
362
- // Because `app.store.ts` caches identical array references, `filteredSignal` will NOT trigger
363
- // spurious emissions if the underlying data has not actually changed.
364
- const filteredSignal = computed(() => {
365
- return store.selectEntities([[field, 'in', ids]], {});
366
- });
367
-
368
- // 2. We convert the signal to an observable to perform pairwise diffing.
369
- // This is necessary because if a parent entity is added or modified, we need to re-evaluate
370
- // its nested `streamQueries` (e.g., if a post's authorId changes, we must query the new author).
371
- toObservable(filteredSignal, { injector }).pipe(
372
- map((entities) => {
373
- const entityMap = {};
374
- for (const entity of entities) {
375
- entityMap[entity.__id] = entity;
376
- }
377
- return entityMap;
378
- }),
379
- startWith({}),
380
- pairwise(),
381
- map(([prevEntities, currEntities]) => {
382
- // 3. Diff the current entities against the previous entities to determine exactly
383
- // what was added, removed, or modified. We rely on the `_deleted` flag and `_updatedAt`.
384
- const changedEntities = [];
385
- for (const key in currEntities) {
386
- if (!(key in prevEntities)) {
387
- changedEntities.push({ type: 'added', doc: currEntities[key] });
388
- } else if (currEntities[key]['_deleted']) {
389
- changedEntities.push({ type: 'removed', doc: currEntities[key] });
390
- } else if (currEntities[key]['_updatedAt'] !== prevEntities[key]['_updatedAt']) {
391
- changedEntities.push({ type: 'modified', doc: currEntities[key] });
392
- }
393
- }
394
- return changedEntities;
395
- }),
396
- map((changes) => changes.filter((c) => c.type !== 'removed')),
397
- filter((changes) => changes.length > 0),
398
- ).subscribe(async (changes) => {
399
- // 4. For every changed entity, evaluate its nested stream queries.
400
- const queriesByEntity = changes.map((change) => streamQueries(change.doc));
401
- if (queriesByEntity.length === 0 || queriesByEntity[0].length === 0) return;
402
-
403
- // 5. Transpose the matrix so each row corresponds to all queries of the same query type.
404
- // This allows us to group and optimize queries (e.g., combining 5 single equality queries into 1 'in' query).
405
- const queriesByQueryType = queriesByEntity[0].map((_, colIndex) => queriesByEntity.map((row) => row[colIndex]));
406
-
407
- await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
408
- const optimizedQueries = EntityStreamQuery.optimize(queriesForOneType);
409
- await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {
410
- const isSimpleChild = (!query.queryOptions || Object.keys(query.queryOptions).length === 0) &&
411
- query.queryParams.length === 1 &&
412
- (query.queryParams[0][1] === '==' || query.queryParams[0][1] === 'in');
413
-
414
- if (isSimpleChild) {
415
- const childField = query.queryParams[0][0];
416
- const childOp = query.queryParams[0][1];
417
- const childVal = query.queryParams[0][2];
418
- const childIds = childOp === 'in' ? childVal : [childVal];
419
- queryLogger.log(`[CachedListenersService] Nested query optimized to simple stream query: ${childField} in [${childIds}]`);
420
- await this.processSimpleStreamQuery(query.collection, childField, childIds, query.store, injector, query.streamQueries, { loading: options?.loading });
421
- } else {
422
- queryLogger.log(`[CachedListenersService] Nested query falling back to standard stream query:`, JSON.stringify(query.queryParams));
423
- await this.processStreamQuery(query.collection, query.store, query.queryParams, query.queryOptions, injector, query.streamQueries, { loading: options?.loading });
424
- }
425
- }));
426
- }));
427
- });
428
- }
429
-
430
- // We'll turn off the loading indicator right away since we don't have a good way
431
- // to know when all individual streams are initialized yet.
432
- options?.loading?.set(false);
433
- }
434
-
435
- private createConnection<T>(collection: string, store: any, queryParams: QueryParams, queryOptions: QueryOptions, destroyRef: DestroyRef): CachedConnection {
436
- // console.log("CONNECT " + this.getQueryKey(collection, queryParams, queryOptions));
437
-
438
- // ------------ DEFINE OBSERVABLES FOR DISCONNECTING ------------------------------
439
-
440
- const queryKey = this.getQueryKey(collection, queryParams, queryOptions);
441
- const disconnectObs$ = this.closeConnection$.pipe(
442
- filter((qk) => qk === queryKey),
443
- take(1),
444
- // tap(a => { console.log("DISCONNECT: " + queryKey) }),
445
- share(),
446
- );
447
-
448
- // ------------ HANDLE PATCHING TO STORE ------------------------------------------
449
-
450
- // Handle patching to the store
451
- this.db.streamEntitiesChanges(collection, queryParams, queryOptions).pipe(
452
- takeUntil(disconnectObs$),
453
- ).subscribe((fbPayload: Array<{ type: string, docData: AnyEntity }>) => {
454
- // Handle all the added entities
455
- const entitiesToAdd = fbPayload
456
- .filter((dc) => dc.type === 'added' && !dc.docData['_deleted'])
457
- .map((dc) => dc.docData);
458
-
459
- // Handle all the modified entities
460
- const entitiesToModify = fbPayload
461
- .filter((dc) => dc.type === 'modified' && !dc.docData['_deleted'])
462
- .map((dc) => dc.docData);
463
-
464
- // Handle all the removed entities
465
- const entitiesToRemove = fbPayload
466
- .filter((dc) => dc.type === 'modified' && dc.docData['_deleted'])
467
- .map((dc) => dc.docData['__id']);
468
-
469
- // Handle changes of the 'removed' type. In general, firebase 'removed'
470
- // could be due to no longer matching the stream query rather than being
471
- // deleted from the DB. this is why we use soft deletes (set _deleted to true).
472
- // We could still get 'removed' entries if there are manual deletions in the
473
- // database or when firestore is syncing updates after temporarily using
474
- // entities cached to IndexedDB.
475
- const entitiesToModify2 = fbPayload
476
- .filter((dc) => dc.type === 'removed' && !entityInQueryResults(dc.docData, queryParams, queryOptions))
477
- .map((dc) => dc.docData);
478
-
479
- const entitiesToRemove2 = fbPayload
480
- .filter((dc) => dc.type === 'removed' && entityInQueryResults(dc.docData, queryParams, queryOptions))
481
- .map((dc) => dc.docData['__id']);
482
-
483
- // Patch all the changes to the store
484
- store.handleStreamChanges(
485
- entitiesToAdd,
486
- [...entitiesToModify, ...entitiesToModify2],
487
- [...entitiesToRemove, ...entitiesToRemove2],
488
- );
489
- });
490
-
491
- return {
492
- queryKey: this.getQueryKey(collection, queryParams, queryOptions),
493
- registeredSet: new Set<DestroyRef>([destroyRef]),
494
- };
495
- }
496
-
497
- constructor(
498
- @Inject(DATABASE_SERVICE) private db: DatabaseService,
499
- ) { }
500
- }
@@ -1,73 +0,0 @@
1
- import { InjectionToken, Injector } from '@angular/core';
2
- import { QueryParams, QueryOptions, AnyEntity } from '../store/app.model';
3
- import { Observable } from 'rxjs';
4
- import { User } from '@angular/fire/auth';
5
- import { WriteBatchI } from '../store/batch-write.service';
6
-
7
- /** Firebase Authentication state needed by the application. */
8
- export interface AuthSession {
9
- uid: string;
10
- email: string | null;
11
- displayName: string | null;
12
- photoURL: string | null;
13
- isAnonymous: boolean;
14
- emailVerified: boolean;
15
- emailLinkEnabled: boolean;
16
- providerIds: string[];
17
- }
18
-
19
- export interface DatabaseService {
20
- createId(): string;
21
- afUser(): Observable<AuthSession | null>;
22
- signInWithGoogle(): Promise<AuthSession>;
23
- signInAnonymously(): Promise<AuthSession>;
24
- linkGoogle(): Promise<AuthSession>;
25
- sendEmailSignInLink(email: string): Promise<void>;
26
- sendEmailLinkForCurrentAccount(): Promise<void>;
27
- getStoredEmailForEmailLink(): string | null;
28
- completeEmailSignInLink(url: string, email: string): Promise<AuthSession>;
29
- deleteAnonymousAccount(): Promise<void>;
30
- ensureUserProfile(session: AuthSession): Promise<any>;
31
- logout(): any;
32
- streamEntity<T>(collectionName: string, id: string): Observable<T>;
33
- streamEntities<T>(collectionName, queryParams, queryOptions?): Observable<T[]>;
34
- streamEntitiesChanges<T>(
35
- collectionName,
36
- queryParams,
37
- queryOptions?,
38
- ): Observable<
39
- {
40
- type: string;
41
- docData: T;
42
- }[]
43
- >;
44
- getEntity<T>(collectionName: string, id: string): Promise<T>;
45
- getEntities<S>(
46
- collectionName: string,
47
- queryParams: [string, string, any][],
48
- queryOptions?: { [index: string]: any },
49
- ): Promise<S[]>;
50
- count(
51
- collectionName: string,
52
- queryParams: QueryParams,
53
- queryOptions?: QueryOptions,
54
- ): Promise<number>;
55
- aggregate<S extends { [k: string]: number }>(
56
- collectionName: string,
57
- queryParams: QueryParams,
58
- queryOptions: QueryOptions,
59
- aggregateParams: { [K in keyof S]: [string] | [string, string] },
60
- ): Promise<{ [K in keyof S]: number }>;
61
- addEntity(collectionName: string, entity: AnyEntity, batch?: WriteBatchI): Promise<any>;
62
- updateEntity(
63
- collectionName: string,
64
- id: string,
65
- changes: Partial<AnyEntity>,
66
- batch?: WriteBatchI,
67
- ): Promise<any>;
68
- removeEntity(collectionName: string, id: string, batch?: WriteBatchI): Promise<any>;
69
- incrementEntityField(collectionName, id, field, delta): Promise<void>;
70
- }
71
-
72
- // InjectionToken that can be swapped out for
73
- export const DATABASE_SERVICE = new InjectionToken<DatabaseService>('DatabaseService');
@@ -1,59 +0,0 @@
1
- import { TestBed } from '@angular/core/testing';
2
- import { EmailLinkContextService } from './email-link-context.service';
3
-
4
- describe('EmailLinkContextService', () => {
5
- let service: EmailLinkContextService;
6
-
7
- beforeEach(() => {
8
- TestBed.configureTestingModule({});
9
- service = TestBed.inject(EmailLinkContextService);
10
- service.clear();
11
- });
12
-
13
- afterEach(() => service.clear());
14
-
15
- it('restores the pending email when local storage is unavailable on the callback', () => {
16
- service.remember({
17
- email: 'learner@example.com',
18
- flow: 'sign-in',
19
- uid: null,
20
- });
21
-
22
- localStorage.removeItem('app.email-link.email');
23
- localStorage.removeItem('app.email-link.flow');
24
-
25
- expect(service.getEmail()).toBe('learner@example.com');
26
- expect(service.getFlow()).toBe('sign-in');
27
- });
28
-
29
- it('does not clear a newer request when an older send fails', () => {
30
- service.remember({
31
- email: 'new@example.com',
32
- flow: 'sign-in',
33
- uid: null,
34
- });
35
-
36
- service.clearIfMatches({
37
- email: 'old@example.com',
38
- flow: 'sign-in',
39
- uid: null,
40
- });
41
-
42
- expect(service.getEmail()).toBe('new@example.com');
43
- });
44
-
45
- it('clears matching local-storage and cookie context', () => {
46
- const context = {
47
- email: 'learner@example.com',
48
- flow: 'guest-upgrade' as const,
49
- uid: 'guest-123',
50
- };
51
- service.remember(context);
52
-
53
- service.clearIfMatches(context);
54
-
55
- expect(service.getEmail()).toBeNull();
56
- expect(service.getFlow()).toBeNull();
57
- expect(service.getUid()).toBeNull();
58
- });
59
- });