@processfocus/runtime-local 0.1.0-next.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 (470) hide show
  1. package/LICENSE.md +28 -0
  2. package/README.md +290 -0
  3. package/dist/authentication-server.mjs +188 -0
  4. package/dist/chunk-2sb4v2sx.js +70 -0
  5. package/dist/chunk-9weqs8n8.js +56031 -0
  6. package/dist/chunk-mvkr77wp.js +54113 -0
  7. package/dist/chunk-tkn4cnc8.js +453 -0
  8. package/dist/chunk-vpsm84e8.js +85 -0
  9. package/dist/dashboard-source/apps/frontend/app/%5Fpf/app-icons/[...path]/route.ts +63 -0
  10. package/dist/dashboard-source/apps/frontend/app/%5Fpf/health/page.tsx +19 -0
  11. package/dist/dashboard-source/apps/frontend/app/%5Fpf/public-form-branding/[...path]/route.ts +95 -0
  12. package/dist/dashboard-source/apps/frontend/app/(protected)/act-on-behalf/actions.ts +248 -0
  13. package/dist/dashboard-source/apps/frontend/app/(protected)/act-on-behalf/delegations-client.tsx +751 -0
  14. package/dist/dashboard-source/apps/frontend/app/(protected)/act-on-behalf/page.tsx +46 -0
  15. package/dist/dashboard-source/apps/frontend/app/(protected)/client-index.tsx +375 -0
  16. package/dist/dashboard-source/apps/frontend/app/(protected)/client.tsx +14 -0
  17. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/(.)[executionId]/client.tsx +73 -0
  18. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/(.)[executionId]/page.tsx +20 -0
  19. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/(.)[executionId]/process-state/page.tsx +22 -0
  20. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/default.tsx +3 -0
  21. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/[executionId]/page.tsx +11 -0
  22. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/[executionId]/process-state/page.tsx +23 -0
  23. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/abandon-execution-dialog.tsx +137 -0
  24. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/execution-card-menu.tsx +233 -0
  25. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/layout.tsx +19 -0
  26. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/page.tsx +1549 -0
  27. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/process-state-dialog.tsx +91 -0
  28. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/process-state-modal-client.tsx +33 -0
  29. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/process-state-page-client.tsx +31 -0
  30. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/process-state-route-fallback.tsx +18 -0
  31. package/dist/dashboard-source/apps/frontend/app/(protected)/executions/restart-execution-feedback.tsx +40 -0
  32. package/dist/dashboard-source/apps/frontend/app/(protected)/layout.tsx +129 -0
  33. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/@modal/(.)item/[id]/client.tsx +215 -0
  34. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/@modal/(.)item/[id]/page.tsx +23 -0
  35. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/@modal/default.tsx +3 -0
  36. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/[...listPath]/list-page-client.tsx +678 -0
  37. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/[...listPath]/loading.tsx +10 -0
  38. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/[...listPath]/page.tsx +228 -0
  39. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/components/list-create-form.tsx +147 -0
  40. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/components/list-item-edit-form.tsx +246 -0
  41. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/hooks/metric-control-url-state.ts +71 -0
  42. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/hooks/use-list-deleted-callback.ts +22 -0
  43. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/hooks/use-list-item-detail.ts +315 -0
  44. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/item/[id]/client.tsx +259 -0
  45. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/item/[id]/page.tsx +46 -0
  46. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/layout.tsx +14 -0
  47. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/lib/list-detail-title.ts +20 -0
  48. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/lib/list-refresh.ts +26 -0
  49. package/dist/dashboard-source/apps/frontend/app/(protected)/lists/utils.ts +20 -0
  50. package/dist/dashboard-source/apps/frontend/app/(protected)/loading.tsx +5 -0
  51. package/dist/dashboard-source/apps/frontend/app/(protected)/org-chart/org-chart-client.tsx +74 -0
  52. package/dist/dashboard-source/apps/frontend/app/(protected)/org-chart/page.tsx +120 -0
  53. package/dist/dashboard-source/apps/frontend/app/(protected)/page.tsx +13 -0
  54. package/dist/dashboard-source/apps/frontend/app/(protected)/passkeys/actions.ts +188 -0
  55. package/dist/dashboard-source/apps/frontend/app/(protected)/passkeys/page.tsx +33 -0
  56. package/dist/dashboard-source/apps/frontend/app/(protected)/passkeys/passkeys-client.tsx +320 -0
  57. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/@modal/(.)start/[...startStepPath]/client.tsx +152 -0
  58. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/@modal/(.)start/[...startStepPath]/page.tsx +41 -0
  59. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/@modal/default.tsx +3 -0
  60. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/client.tsx +33 -0
  61. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/components/process-form-actions.tsx +105 -0
  62. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/components/process-submit-button.tsx +81 -0
  63. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/components/start-process-form.tsx +282 -0
  64. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/layout.tsx +21 -0
  65. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/lib/mobile-process-catalog.ts +28 -0
  66. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/lib/start-process-actions.ts +13 -0
  67. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/loading.tsx +10 -0
  68. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/page.tsx +5 -0
  69. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/processes-client.tsx +504 -0
  70. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/start/[...startStepPath]/client.tsx +153 -0
  71. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/start/[...startStepPath]/page.tsx +39 -0
  72. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/loading.tsx +20 -0
  73. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/page.tsx +131 -0
  74. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/process-documentation.tsx +209 -0
  75. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/use-workflow-auto-refresh.ts +120 -0
  76. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/workflow-flow.tsx +319 -0
  77. package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/workflow-form-preview-sheet.tsx +98 -0
  78. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/[[...tab]]/loading.tsx +1 -0
  79. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/[[...tab]]/page.tsx +100 -0
  80. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/access-handbook.tsx +110 -0
  81. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/authorization-loading.tsx +25 -0
  82. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/authorization-tabs.tsx +47 -0
  83. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/cedar-authorize.ts +261 -0
  84. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/cedar-helpers.ts +17 -0
  85. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/cedar-source.tsx +34 -0
  86. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/cedar-types.ts +79 -0
  87. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/evaluate-cedar.ts +43 -0
  88. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/explorer.tsx +526 -0
  89. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/layout.tsx +23 -0
  90. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/load-cedar.ts +174 -0
  91. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/load-handbook.ts +390 -0
  92. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/org-data.ts +70 -0
  93. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/[invitationId]/page.tsx +22 -0
  94. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/invitation-detail-client.tsx +594 -0
  95. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/invitation-detail-skeleton.tsx +48 -0
  96. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/new/page.tsx +5 -0
  97. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations-table.tsx +186 -0
  98. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/page.tsx +69 -0
  99. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/providers-table.tsx +48 -0
  100. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/roles-table.tsx +62 -0
  101. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/settings-client.tsx +244 -0
  102. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users/[userId]/client.tsx +329 -0
  103. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users/[userId]/page.tsx +21 -0
  104. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users/[userId]/tokens/page.tsx +39 -0
  105. package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users-table.tsx +82 -0
  106. package/dist/dashboard-source/apps/frontend/app/(protected)/stats/[...statsPath]/error.tsx +34 -0
  107. package/dist/dashboard-source/apps/frontend/app/(protected)/stats/[...statsPath]/not-found.tsx +13 -0
  108. package/dist/dashboard-source/apps/frontend/app/(protected)/stats/[...statsPath]/page.tsx +84 -0
  109. package/dist/dashboard-source/apps/frontend/app/(protected)/stats/[...statsPath]/stats-data-fetcher.tsx +93 -0
  110. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/@modal/(.)complete/[...stepPath]/client.tsx +143 -0
  111. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/@modal/(.)complete/[...stepPath]/page.tsx +50 -0
  112. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/@modal/default.tsx +3 -0
  113. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/complete/[...stepPath]/client.tsx +131 -0
  114. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/complete/[...stepPath]/page.tsx +50 -0
  115. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/components/complete-todo-form.tsx +172 -0
  116. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/components/public-completion-correction-form.tsx +233 -0
  117. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/components/todo-form-actions.tsx +26 -0
  118. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/correct/[...stepPath]/page.tsx +58 -0
  119. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/layout.tsx +14 -0
  120. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/lib/mobile-todo-list.ts +154 -0
  121. package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/page.tsx +1317 -0
  122. package/dist/dashboard-source/apps/frontend/app/api/auth/callback/route.ts +259 -0
  123. package/dist/dashboard-source/apps/frontend/app/api/auth/delegation/route.ts +127 -0
  124. package/dist/dashboard-source/apps/frontend/app/api/auth/login/route.ts +49 -0
  125. package/dist/dashboard-source/apps/frontend/app/api/auth/logout/route.ts +33 -0
  126. package/dist/dashboard-source/apps/frontend/app/api/auth/passkey/auth-options/route.ts +79 -0
  127. package/dist/dashboard-source/apps/frontend/app/api/auth/passkey/auth-verify/route.ts +142 -0
  128. package/dist/dashboard-source/apps/frontend/app/api/auth/passkey/register/route.ts +103 -0
  129. package/dist/dashboard-source/apps/frontend/app/api/auth/passkey/register-verify/route.ts +136 -0
  130. package/dist/dashboard-source/apps/frontend/app/api/auth/passkey/registration-session/route.ts +129 -0
  131. package/dist/dashboard-source/apps/frontend/app/api/auth/passkey/start/route.ts +153 -0
  132. package/dist/dashboard-source/apps/frontend/app/api/auth/refresh/route.ts +122 -0
  133. package/dist/dashboard-source/apps/frontend/app/api/auth/switch-role/route.ts +177 -0
  134. package/dist/dashboard-source/apps/frontend/app/api/dev/import-completed/route.ts +22 -0
  135. package/dist/dashboard-source/apps/frontend/app/api/dev/import-events/route.ts +38 -0
  136. package/dist/dashboard-source/apps/frontend/app/api/embed/lookup/route.ts +266 -0
  137. package/dist/dashboard-source/apps/frontend/app/api/embed/submit/route.ts +118 -0
  138. package/dist/dashboard-source/apps/frontend/app/api/embed/test-host/route.ts +125 -0
  139. package/dist/dashboard-source/apps/frontend/app/api/public/to-dos/calendar-slots/route.ts +44 -0
  140. package/dist/dashboard-source/apps/frontend/app/api/public/to-dos/complete/route.ts +56 -0
  141. package/dist/dashboard-source/apps/frontend/app/api/public/to-dos/lookup/route.ts +61 -0
  142. package/dist/dashboard-source/apps/frontend/app/api/public/to-dos/request-fresh-link/route.ts +41 -0
  143. package/dist/dashboard-source/apps/frontend/app/api/revalidate/route.ts +61 -0
  144. package/dist/dashboard-source/apps/frontend/app/app-shell.tsx +100 -0
  145. package/dist/dashboard-source/apps/frontend/app/cli-auth/route.ts +261 -0
  146. package/dist/dashboard-source/apps/frontend/app/embed/[...startStepPath]/embed-client.tsx +393 -0
  147. package/dist/dashboard-source/apps/frontend/app/embed/[...startStepPath]/loading.tsx +13 -0
  148. package/dist/dashboard-source/apps/frontend/app/embed/[...startStepPath]/page.tsx +51 -0
  149. package/dist/dashboard-source/apps/frontend/app/embed/embedded.css +48 -0
  150. package/dist/dashboard-source/apps/frontend/app/embed/layout.tsx +15 -0
  151. package/dist/dashboard-source/apps/frontend/app/global.css +13 -0
  152. package/dist/dashboard-source/apps/frontend/app/layout.tsx +102 -0
  153. package/dist/dashboard-source/apps/frontend/app/login/layout.tsx +9 -0
  154. package/dist/dashboard-source/apps/frontend/app/login/login-button.tsx +35 -0
  155. package/dist/dashboard-source/apps/frontend/app/login/login-form-content.tsx +117 -0
  156. package/dist/dashboard-source/apps/frontend/app/login/login-form.tsx +30 -0
  157. package/dist/dashboard-source/apps/frontend/app/login/page.tsx +52 -0
  158. package/dist/dashboard-source/apps/frontend/app/login/passkey-button.tsx +226 -0
  159. package/dist/dashboard-source/apps/frontend/app/login/secret-login-form.tsx +91 -0
  160. package/dist/dashboard-source/apps/frontend/app/manifest.ts +7 -0
  161. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/error.tsx +63 -0
  162. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/layout.tsx +34 -0
  163. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/page.tsx +129 -0
  164. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/public-form-branding-card.tsx +42 -0
  165. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/public-form-branding-context.tsx +27 -0
  166. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/public-form-branding-html.tsx +40 -0
  167. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/public-todo-client.tsx +553 -0
  168. package/dist/dashboard-source/apps/frontend/app/public/form/[token]/public-todo-state-content.tsx +27 -0
  169. package/dist/dashboard-source/apps/frontend/app/public.css +33 -0
  170. package/dist/dashboard-source/apps/frontend/app/register/passkey/layout.tsx +49 -0
  171. package/dist/dashboard-source/apps/frontend/app/register/passkey/page.tsx +36 -0
  172. package/dist/dashboard-source/apps/frontend/app/register/passkey/register-passkey-client.tsx +292 -0
  173. package/dist/dashboard-source/apps/frontend/app/theme.css +117 -0
  174. package/dist/dashboard-source/apps/frontend/components/DashboardSection.tsx +693 -0
  175. package/dist/dashboard-source/apps/frontend/components/Header.tsx +481 -0
  176. package/dist/dashboard-source/apps/frontend/components/OrgUnitNode.tsx +41 -0
  177. package/dist/dashboard-source/apps/frontend/components/app-sidebar.tsx +245 -0
  178. package/dist/dashboard-source/apps/frontend/components/auth-provider.tsx +158 -0
  179. package/dist/dashboard-source/apps/frontend/components/collections/collection-table-card.tsx +218 -0
  180. package/dist/dashboard-source/apps/frontend/components/collections/collection-table-header-row.tsx +97 -0
  181. package/dist/dashboard-source/apps/frontend/components/config-provider.tsx +27 -0
  182. package/dist/dashboard-source/apps/frontend/components/copy-button.tsx +40 -0
  183. package/dist/dashboard-source/apps/frontend/components/dashboard-activity.tsx +35 -0
  184. package/dist/dashboard-source/apps/frontend/components/dashboard-skeleton.tsx +17 -0
  185. package/dist/dashboard-source/apps/frontend/components/delegation-expiry.tsx +21 -0
  186. package/dist/dashboard-source/apps/frontend/components/feature-permissions-provider.tsx +28 -0
  187. package/dist/dashboard-source/apps/frontend/components/form-dialog-content.tsx +66 -0
  188. package/dist/dashboard-source/apps/frontend/components/frontend-client-plugin-host.tsx +27 -0
  189. package/dist/dashboard-source/apps/frontend/components/frontend-client-plugin-identify.tsx +33 -0
  190. package/dist/dashboard-source/apps/frontend/components/frontend-client-plugin-provider.tsx +55 -0
  191. package/dist/dashboard-source/apps/frontend/components/journey-timeline.tsx +378 -0
  192. package/dist/dashboard-source/apps/frontend/components/mobile-home-switchboard.tsx +98 -0
  193. package/dist/dashboard-source/apps/frontend/components/mocks-provider.tsx +27 -0
  194. package/dist/dashboard-source/apps/frontend/components/notification-bell.tsx +137 -0
  195. package/dist/dashboard-source/apps/frontend/components/org-settings-provider.tsx +26 -0
  196. package/dist/dashboard-source/apps/frontend/components/process-workflow-link.tsx +36 -0
  197. package/dist/dashboard-source/apps/frontend/components/session-reissue.tsx +48 -0
  198. package/dist/dashboard-source/apps/frontend/components/sidebar-lists.tsx +89 -0
  199. package/dist/dashboard-source/apps/frontend/components/sidebar-stats-views.tsx +65 -0
  200. package/dist/dashboard-source/apps/frontend/components/theme-provider.tsx +132 -0
  201. package/dist/dashboard-source/apps/frontend/components/todo-count-badge.tsx +59 -0
  202. package/dist/dashboard-source/apps/frontend/components/token-refresh-scheduler.tsx +304 -0
  203. package/dist/dashboard-source/apps/frontend/components/ui/checkbox.tsx +31 -0
  204. package/dist/dashboard-source/apps/frontend/components/ui/dialog.tsx +142 -0
  205. package/dist/dashboard-source/apps/frontend/components/ui/dropdown-menu.tsx +256 -0
  206. package/dist/dashboard-source/apps/frontend/components/ui/input.tsx +20 -0
  207. package/dist/dashboard-source/apps/frontend/components/ui/pagination.tsx +59 -0
  208. package/dist/dashboard-source/apps/frontend/components/ui/sheet.tsx +138 -0
  209. package/dist/dashboard-source/apps/frontend/components/ui/sidebar.tsx +741 -0
  210. package/dist/dashboard-source/apps/frontend/components/ui/skeleton.tsx +13 -0
  211. package/dist/dashboard-source/apps/frontend/components/ui/tab-pill.tsx +30 -0
  212. package/dist/dashboard-source/apps/frontend/components/ui/table.tsx +115 -0
  213. package/dist/dashboard-source/apps/frontend/components/ui/tooltip.tsx +60 -0
  214. package/dist/dashboard-source/apps/frontend/components/without-waiting-badge.tsx +24 -0
  215. package/dist/dashboard-source/apps/frontend/components/workflow/step-node.tsx +116 -0
  216. package/dist/dashboard-source/apps/frontend/components/workflow/swimlane-node.tsx +46 -0
  217. package/dist/dashboard-source/apps/frontend/components/workflow/workflow-edge.tsx +172 -0
  218. package/dist/dashboard-source/apps/frontend/hooks/use-draft-process-save.ts +189 -0
  219. package/dist/dashboard-source/apps/frontend/hooks/use-draft-state.ts +79 -0
  220. package/dist/dashboard-source/apps/frontend/hooks/use-form-metadata.ts +74 -0
  221. package/dist/dashboard-source/apps/frontend/hooks/use-mobile.ts +27 -0
  222. package/dist/dashboard-source/apps/frontend/hooks/use-notification-preference.ts +246 -0
  223. package/dist/dashboard-source/apps/frontend/hooks/use-processes-query.ts +56 -0
  224. package/dist/dashboard-source/apps/frontend/hooks/use-weekly-execution-stats.ts +101 -0
  225. package/dist/dashboard-source/apps/frontend/index.d.ts +12 -0
  226. package/dist/dashboard-source/apps/frontend/instrumentation.node.ts +25 -0
  227. package/dist/dashboard-source/apps/frontend/instrumentation.ts +19 -0
  228. package/dist/dashboard-source/apps/frontend/lib/app-icons-metadata.ts +66 -0
  229. package/dist/dashboard-source/apps/frontend/lib/appsync-events/adapter.ts +128 -0
  230. package/dist/dashboard-source/apps/frontend/lib/appsync-events/client.ts +355 -0
  231. package/dist/dashboard-source/apps/frontend/lib/appsync-events/config.ts +18 -0
  232. package/dist/dashboard-source/apps/frontend/lib/appsync-events/reconnect-registry.ts +34 -0
  233. package/dist/dashboard-source/apps/frontend/lib/auth/act-on-behalf-menu.ts +9 -0
  234. package/dist/dashboard-source/apps/frontend/lib/auth/callback-error.ts +26 -0
  235. package/dist/dashboard-source/apps/frontend/lib/auth/client-session.ts +32 -0
  236. package/dist/dashboard-source/apps/frontend/lib/auth/client.ts +46 -0
  237. package/dist/dashboard-source/apps/frontend/lib/auth/config.ts +48 -0
  238. package/dist/dashboard-source/apps/frontend/lib/auth/delegations.ts +62 -0
  239. package/dist/dashboard-source/apps/frontend/lib/auth/issuer.ts +164 -0
  240. package/dist/dashboard-source/apps/frontend/lib/auth/jwt.ts +17 -0
  241. package/dist/dashboard-source/apps/frontend/lib/auth/logout.ts +35 -0
  242. package/dist/dashboard-source/apps/frontend/lib/auth/passkeys-menu.ts +9 -0
  243. package/dist/dashboard-source/apps/frontend/lib/auth/passkeys.ts +117 -0
  244. package/dist/dashboard-source/apps/frontend/lib/auth/providers.ts +52 -0
  245. package/dist/dashboard-source/apps/frontend/lib/auth/realtime-session-token.ts +62 -0
  246. package/dist/dashboard-source/apps/frontend/lib/auth/reauthentication-state.ts +16 -0
  247. package/dist/dashboard-source/apps/frontend/lib/auth/redirect.ts +105 -0
  248. package/dist/dashboard-source/apps/frontend/lib/auth/secret-login-presentation.ts +33 -0
  249. package/dist/dashboard-source/apps/frontend/lib/auth/session-cache-scope.ts +1 -0
  250. package/dist/dashboard-source/apps/frontend/lib/auth/session-role.ts +6 -0
  251. package/dist/dashboard-source/apps/frontend/lib/auth/session.ts +277 -0
  252. package/dist/dashboard-source/apps/frontend/lib/auth/ssr-session.ts +76 -0
  253. package/dist/dashboard-source/apps/frontend/lib/auth/verify-passkey.ts +95 -0
  254. package/dist/dashboard-source/apps/frontend/lib/authorization-tabs.ts +19 -0
  255. package/dist/dashboard-source/apps/frontend/lib/cedar-highlight.ts +116 -0
  256. package/dist/dashboard-source/apps/frontend/lib/client-plugin-error-reporting.ts +28 -0
  257. package/dist/dashboard-source/apps/frontend/lib/collections/collection-provider-factory.tsx +1119 -0
  258. package/dist/dashboard-source/apps/frontend/lib/collections/collection-provider-scope.ts +48 -0
  259. package/dist/dashboard-source/apps/frontend/lib/collections/database-error-ui.tsx +61 -0
  260. package/dist/dashboard-source/apps/frontend/lib/collections/draft-process-execution-collection-provider.tsx +32 -0
  261. package/dist/dashboard-source/apps/frontend/lib/collections/draft-process-execution.ts +161 -0
  262. package/dist/dashboard-source/apps/frontend/lib/collections/execution-collection-provider.tsx +42 -0
  263. package/dist/dashboard-source/apps/frontend/lib/collections/execution.ts +215 -0
  264. package/dist/dashboard-source/apps/frontend/lib/collections/graphql-stream.ts +123 -0
  265. package/dist/dashboard-source/apps/frontend/lib/collections/process-collection-provider.tsx +30 -0
  266. package/dist/dashboard-source/apps/frontend/lib/collections/process.ts +123 -0
  267. package/dist/dashboard-source/apps/frontend/lib/collections/replication-factory.ts +394 -0
  268. package/dist/dashboard-source/apps/frontend/lib/collections/replication-registry.ts +196 -0
  269. package/dist/dashboard-source/apps/frontend/lib/collections/rxdb-database-name.ts +19 -0
  270. package/dist/dashboard-source/apps/frontend/lib/collections/rxdb-lifecycle.ts +368 -0
  271. package/dist/dashboard-source/apps/frontend/lib/collections/rxdb-provider.tsx +577 -0
  272. package/dist/dashboard-source/apps/frontend/lib/collections/todo-collection-provider.tsx +30 -0
  273. package/dist/dashboard-source/apps/frontend/lib/collections/todo.ts +133 -0
  274. package/dist/dashboard-source/apps/frontend/lib/current-provider-user.ts +30 -0
  275. package/dist/dashboard-source/apps/frontend/lib/dev/frontend-port-file.ts +41 -0
  276. package/dist/dashboard-source/apps/frontend/lib/dev/import-completed-events.ts +21 -0
  277. package/dist/dashboard-source/apps/frontend/lib/dev/import-completed-query-invalidation.tsx +62 -0
  278. package/dist/dashboard-source/apps/frontend/lib/dev/import-completed-refresh.ts +40 -0
  279. package/dist/dashboard-source/apps/frontend/lib/effect/error-boundary.tsx +84 -0
  280. package/dist/dashboard-source/apps/frontend/lib/effect/index.ts +31 -0
  281. package/dist/dashboard-source/apps/frontend/lib/effect/params.ts +57 -0
  282. package/dist/dashboard-source/apps/frontend/lib/effect/run-effect.ts +17 -0
  283. package/dist/dashboard-source/apps/frontend/lib/effect/runtime.ts +168 -0
  284. package/dist/dashboard-source/apps/frontend/lib/effect/services/access-token.ts +48 -0
  285. package/dist/dashboard-source/apps/frontend/lib/effect/services/authorization.ts +206 -0
  286. package/dist/dashboard-source/apps/frontend/lib/effect/services/form-validation.ts +36 -0
  287. package/dist/dashboard-source/apps/frontend/lib/effect/services/graphql.ts +94 -0
  288. package/dist/dashboard-source/apps/frontend/lib/effect/services/index.ts +21 -0
  289. package/dist/dashboard-source/apps/frontend/lib/embed-manifest-store.ts +20 -0
  290. package/dist/dashboard-source/apps/frontend/lib/embed-manifest.ts +152 -0
  291. package/dist/dashboard-source/apps/frontend/lib/embed-request-origin.ts +39 -0
  292. package/dist/dashboard-source/apps/frontend/lib/errors/get-display-error-message.ts +22 -0
  293. package/dist/dashboard-source/apps/frontend/lib/execution-menu-actions-registry.ts +26 -0
  294. package/dist/dashboard-source/apps/frontend/lib/feature-permissions.ts +13 -0
  295. package/dist/dashboard-source/apps/frontend/lib/frontend-boot-health.tsx +161 -0
  296. package/dist/dashboard-source/apps/frontend/lib/frontend-client-plugin-registry.ts +45 -0
  297. package/dist/dashboard-source/apps/frontend/lib/frontend-manifest-store.ts +214 -0
  298. package/dist/dashboard-source/apps/frontend/lib/frontend-manifest.ts +74 -0
  299. package/dist/dashboard-source/apps/frontend/lib/frontend-plugin-loaders.ts +191 -0
  300. package/dist/dashboard-source/apps/frontend/lib/generated/gql/fragment-masking.ts +87 -0
  301. package/dist/dashboard-source/apps/frontend/lib/generated/gql/gql.ts +292 -0
  302. package/dist/dashboard-source/apps/frontend/lib/generated/gql/graphql.ts +443 -0
  303. package/dist/dashboard-source/apps/frontend/lib/generated/gql/index.ts +2 -0
  304. package/dist/dashboard-source/apps/frontend/lib/graphql/client-consumer.tsx +23 -0
  305. package/dist/dashboard-source/apps/frontend/lib/graphql/client-error-reporting.ts +268 -0
  306. package/dist/dashboard-source/apps/frontend/lib/graphql/client-provider.tsx +59 -0
  307. package/dist/dashboard-source/apps/frontend/lib/graphql/dashboard-activity.ts +7 -0
  308. package/dist/dashboard-source/apps/frontend/lib/graphql/dependent-lookup-query.ts +78 -0
  309. package/dist/dashboard-source/apps/frontend/lib/graphql/endpoint.ts +26 -0
  310. package/dist/dashboard-source/apps/frontend/lib/graphql/execution-queries.ts +70 -0
  311. package/dist/dashboard-source/apps/frontend/lib/graphql/file-upload-provider.tsx +82 -0
  312. package/dist/dashboard-source/apps/frontend/lib/graphql/graphql-identifiers.ts +10 -0
  313. package/dist/dashboard-source/apps/frontend/lib/graphql/list-queries.ts +327 -0
  314. package/dist/dashboard-source/apps/frontend/lib/graphql/lookup-provider.tsx +81 -0
  315. package/dist/dashboard-source/apps/frontend/lib/graphql/org-chart-operations.ts +63 -0
  316. package/dist/dashboard-source/apps/frontend/lib/graphql/org-chart-queries.ts +67 -0
  317. package/dist/dashboard-source/apps/frontend/lib/graphql/provider-user-queries.ts +65 -0
  318. package/dist/dashboard-source/apps/frontend/lib/graphql/queries.ts +80 -0
  319. package/dist/dashboard-source/apps/frontend/lib/graphql/server-client.ts +15 -0
  320. package/dist/dashboard-source/apps/frontend/lib/graphql/settings-queries.ts +634 -0
  321. package/dist/dashboard-source/apps/frontend/lib/graphql/stats-views-server.ts +16 -0
  322. package/dist/dashboard-source/apps/frontend/lib/graphql/stats-views.ts +33 -0
  323. package/dist/dashboard-source/apps/frontend/lib/graphql/user-queries.ts +138 -0
  324. package/dist/dashboard-source/apps/frontend/lib/graphql/workflow-operations.ts +54 -0
  325. package/dist/dashboard-source/apps/frontend/lib/graphql/workflow-queries.ts +50 -0
  326. package/dist/dashboard-source/apps/frontend/lib/mobile-home-view-model.ts +74 -0
  327. package/dist/dashboard-source/apps/frontend/lib/mobile-shell-policy.ts +124 -0
  328. package/dist/dashboard-source/apps/frontend/lib/mock-data.ts +364 -0
  329. package/dist/dashboard-source/apps/frontend/lib/notifications/notification-preference.ts +251 -0
  330. package/dist/dashboard-source/apps/frontend/lib/notifications/todo-notification-observer.ts +178 -0
  331. package/dist/dashboard-source/apps/frontend/lib/notifications/todo-notifications-runtime.tsx +14 -0
  332. package/dist/dashboard-source/apps/frontend/lib/notifications/use-todo-notifications.tsx +103 -0
  333. package/dist/dashboard-source/apps/frontend/lib/org-chart-data.ts +50 -0
  334. package/dist/dashboard-source/apps/frontend/lib/org-chart-depth-config.ts +71 -0
  335. package/dist/dashboard-source/apps/frontend/lib/org-chart-layout.ts +149 -0
  336. package/dist/dashboard-source/apps/frontend/lib/org-chart-types.ts +17 -0
  337. package/dist/dashboard-source/apps/frontend/lib/org-identity.ts +57 -0
  338. package/dist/dashboard-source/apps/frontend/lib/organisation-plugin-loaders.ts +13 -0
  339. package/dist/dashboard-source/apps/frontend/lib/organisation-plugin-preparation.ts +2 -0
  340. package/dist/dashboard-source/apps/frontend/lib/plugins-client.tsx +99 -0
  341. package/dist/dashboard-source/apps/frontend/lib/plugins.ts +1 -0
  342. package/dist/dashboard-source/apps/frontend/lib/public-todo-form-runtime.ts +9 -0
  343. package/dist/dashboard-source/apps/frontend/lib/public-todo-graphql-errors.ts +45 -0
  344. package/dist/dashboard-source/apps/frontend/lib/public-todo-model.ts +200 -0
  345. package/dist/dashboard-source/apps/frontend/lib/public-todo-server.ts +209 -0
  346. package/dist/dashboard-source/apps/frontend/lib/query-client.ts +41 -0
  347. package/dist/dashboard-source/apps/frontend/lib/restart-execution-action.ts +76 -0
  348. package/dist/dashboard-source/apps/frontend/lib/runtime-config.ts +23 -0
  349. package/dist/dashboard-source/apps/frontend/lib/telemetry/constants.ts +5 -0
  350. package/dist/dashboard-source/apps/frontend/lib/telemetry/otlp-config.ts +16 -0
  351. package/dist/dashboard-source/apps/frontend/lib/telemetry/register-otel.ts +308 -0
  352. package/dist/dashboard-source/apps/frontend/lib/theme.ts +9 -0
  353. package/dist/dashboard-source/apps/frontend/lib/todo-types.ts +64 -0
  354. package/dist/dashboard-source/apps/frontend/lib/todo-utils.ts +144 -0
  355. package/dist/dashboard-source/apps/frontend/lib/types/org-identity.ts +7 -0
  356. package/dist/dashboard-source/apps/frontend/lib/utils.ts +16 -0
  357. package/dist/dashboard-source/apps/frontend/lib/workflow/constants.ts +118 -0
  358. package/dist/dashboard-source/apps/frontend/lib/workflow/edge-routing.ts +195 -0
  359. package/dist/dashboard-source/apps/frontend/lib/workflow/form-preview.ts +8 -0
  360. package/dist/dashboard-source/apps/frontend/lib/workflow/layout.ts +878 -0
  361. package/dist/dashboard-source/apps/frontend/lib/workflow/types.ts +63 -0
  362. package/dist/dashboard-source/apps/frontend/next.config.ts +238 -0
  363. package/dist/dashboard-source/apps/frontend/package.json +71 -0
  364. package/dist/dashboard-source/apps/frontend/postcss.config.mjs +5 -0
  365. package/dist/dashboard-source/apps/frontend/proxy.ts +293 -0
  366. package/dist/dashboard-source/apps/frontend/public/.gitkeep +0 -0
  367. package/dist/dashboard-source/apps/frontend/public/favicon.ico +0 -0
  368. package/dist/dashboard-source/apps/frontend/public/processfocus-embed.js +553 -0
  369. package/dist/dashboard-source/apps/frontend/tsconfig.json +35 -0
  370. package/dist/dashboard-source/modules/auth-local-cedar/src/index.ts +7 -0
  371. package/dist/dashboard-source/modules/auth-local-cedar/src/lib/auth-local-cedar.ts +1397 -0
  372. package/dist/dashboard-source/modules/auth-local-cedar/src/lib/cedar-reload-notifier.ts +18 -0
  373. package/dist/dashboard-source/modules/auth-local-cedar/src/lib/config-base.ts +346 -0
  374. package/dist/dashboard-source/modules/auth-local-cedar/src/lib/policy-watcher.ts +172 -0
  375. package/dist/dashboard-source/modules/auth-policy/src/index.ts +4 -0
  376. package/dist/dashboard-source/modules/auth-policy/src/lib/auth-policy.ts +263 -0
  377. package/dist/dashboard-source/modules/auth-policy/src/lib/current-principal.ts +34 -0
  378. package/dist/dashboard-source/modules/auth-policy/src/lib/errors.ts +47 -0
  379. package/dist/dashboard-source/modules/auth-policy/src/lib/types.ts +595 -0
  380. package/dist/dashboard-source/modules/auth-session/src/index.ts +22 -0
  381. package/dist/dashboard-source/modules/auth-session/src/lib/issuer-url.ts +192 -0
  382. package/dist/dashboard-source/modules/auth-session/src/lib/realtime-recipient.ts +76 -0
  383. package/dist/dashboard-source/modules/auth-session/src/lib/session-cache-scope.ts +24 -0
  384. package/dist/dashboard-source/modules/auth-session/src/lib/subjects.ts +54 -0
  385. package/dist/dashboard-source/modules/auth-session/src/lib/url.ts +2 -0
  386. package/dist/dashboard-source/modules/aws-common/src/index.ts +3 -0
  387. package/dist/dashboard-source/modules/aws-common/src/lib/acm.ts +50 -0
  388. package/dist/dashboard-source/modules/aws-common/src/lib/otlp-config.ts +66 -0
  389. package/dist/dashboard-source/modules/aws-common/src/lib/runtime-ssm.ts +28 -0
  390. package/dist/dashboard-source/modules/effect-json-logger/src/index.ts +1 -0
  391. package/dist/dashboard-source/modules/effect-json-logger/src/lib/effect-json-logger.ts +65 -0
  392. package/dist/dashboard-source/modules/form/src/hooks/use-local-storage.ts +78 -0
  393. package/dist/dashboard-source/modules/form/src/index.ts +20 -0
  394. package/dist/dashboard-source/modules/form/src/lib/ajv-standard-schema.ts +152 -0
  395. package/dist/dashboard-source/modules/form/src/lib/client-components-to-form.tsx +1421 -0
  396. package/dist/dashboard-source/modules/form/src/lib/friendly-validation-message.ts +85 -0
  397. package/dist/dashboard-source/modules/form/src/lib/lookup-context.tsx +58 -0
  398. package/dist/dashboard-source/modules/form/src/lib/plugin-registry.ts +34 -0
  399. package/dist/dashboard-source/modules/form/src/lib/walker.tsx +1554 -0
  400. package/dist/dashboard-source/modules/form-client-representation/src/lib/client-form-definition.ts +440 -0
  401. package/dist/dashboard-source/modules/form-client-representation/src/lib/plugin-registry.ts +13 -0
  402. package/dist/dashboard-source/modules/form-client-representation/src/lib/types.ts +336 -0
  403. package/dist/dashboard-source/modules/form-rule/src/index.ts +21 -0
  404. package/dist/dashboard-source/modules/form-rule/src/lib/evaluator.ts +531 -0
  405. package/dist/dashboard-source/modules/form-rule/src/lib/paths.ts +102 -0
  406. package/dist/dashboard-source/modules/form-rule/src/lib/types.ts +121 -0
  407. package/dist/dashboard-source/modules/form-schema/src/index.ts +8 -0
  408. package/dist/dashboard-source/modules/form-schema/src/lib/annotation-helpers.ts +44 -0
  409. package/dist/dashboard-source/modules/form-schema/src/lib/deferred-value.ts +21 -0
  410. package/dist/dashboard-source/modules/form-schema/src/lib/email.ts +50 -0
  411. package/dist/dashboard-source/modules/form-schema/src/lib/field-count.ts +82 -0
  412. package/dist/dashboard-source/modules/form-schema/src/lib/form-annotations.ts +58 -0
  413. package/dist/dashboard-source/modules/form-schema/src/lib/form-schema.ts +975 -0
  414. package/dist/dashboard-source/modules/form-schema/src/lib/phone.ts +60 -0
  415. package/dist/dashboard-source/modules/form-schema/src/lib/property-signature.ts +45 -0
  416. package/dist/dashboard-source/modules/frontend-endpoints/src/endpoint.ts +137 -0
  417. package/dist/dashboard-source/modules/frontend-endpoints/src/index.ts +11 -0
  418. package/dist/dashboard-source/modules/frontend-endpoints/src/port-files.ts +219 -0
  419. package/dist/dashboard-source/modules/frontend-manifest/src/index.ts +2 -0
  420. package/dist/dashboard-source/modules/frontend-manifest/src/lib/browser-plugin-artifact.ts +201 -0
  421. package/dist/dashboard-source/modules/frontend-manifest/src/lib/frontend-manifest.ts +408 -0
  422. package/dist/dashboard-source/modules/frontend-plugin-host/src/index.ts +29 -0
  423. package/dist/dashboard-source/modules/frontend-plugin-host/src/lib/frontend-plugin-host.ts +288 -0
  424. package/dist/dashboard-source/modules/openauth/src/client.ts +1045 -0
  425. package/dist/dashboard-source/modules/openauth/src/error.ts +140 -0
  426. package/dist/dashboard-source/modules/openauth/src/pkce.ts +40 -0
  427. package/dist/dashboard-source/modules/openauth/src/random.ts +24 -0
  428. package/dist/dashboard-source/modules/openauth/src/subject.ts +132 -0
  429. package/dist/dashboard-source/modules/openauth/src/util.ts +13 -0
  430. package/dist/dashboard-source/modules/request-time/src/index.ts +1 -0
  431. package/dist/dashboard-source/modules/request-time/src/lib/request-time.ts +30 -0
  432. package/dist/dashboard-source/modules/rxdb-collections/generated/draft-process-execution-schema.json +45 -0
  433. package/dist/dashboard-source/modules/rxdb-collections/generated/execution-schema.json +217 -0
  434. package/dist/dashboard-source/modules/rxdb-collections/generated/process-schema.json +77 -0
  435. package/dist/dashboard-source/modules/rxdb-collections/generated/todo-schema.json +94 -0
  436. package/dist/dashboard-source/modules/rxdb-collections/src/index.ts +2 -0
  437. package/dist/dashboard-source/modules/rxdb-collections/src/lib/rxdb-collections.ts +181 -0
  438. package/dist/dashboard-source/modules/rxdb-collections/src/lib/to-rxdb-schema.ts +166 -0
  439. package/dist/dashboard-source/modules/shadcn-components/src/index.ts +60 -0
  440. package/dist/dashboard-source/modules/shadcn-components/src/lib/boolean-field.tsx +73 -0
  441. package/dist/dashboard-source/modules/shadcn-components/src/lib/calendar-slot-field.tsx +808 -0
  442. package/dist/dashboard-source/modules/shadcn-components/src/lib/date-field.tsx +127 -0
  443. package/dist/dashboard-source/modules/shadcn-components/src/lib/field-set.tsx +14 -0
  444. package/dist/dashboard-source/modules/shadcn-components/src/lib/file-field.tsx +321 -0
  445. package/dist/dashboard-source/modules/shadcn-components/src/lib/file-upload-context.tsx +45 -0
  446. package/dist/dashboard-source/modules/shadcn-components/src/lib/form-context.tsx +19 -0
  447. package/dist/dashboard-source/modules/shadcn-components/src/lib/lookup-field.tsx +394 -0
  448. package/dist/dashboard-source/modules/shadcn-components/src/lib/radio-field.tsx +96 -0
  449. package/dist/dashboard-source/modules/shadcn-components/src/lib/select-field.tsx +106 -0
  450. package/dist/dashboard-source/modules/shadcn-components/src/lib/text-field.tsx +245 -0
  451. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/button.tsx +63 -0
  452. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/checkbox.tsx +31 -0
  453. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/command.tsx +101 -0
  454. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/field.tsx +275 -0
  455. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/input.tsx +29 -0
  456. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/label.tsx +23 -0
  457. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/popover.tsx +31 -0
  458. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/separator.tsx +27 -0
  459. package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/textarea.tsx +19 -0
  460. package/dist/dashboard-source/modules/shadcn-components/src/lib/utils/utils.ts +4 -0
  461. package/dist/dashboard-source.json +70 -0
  462. package/dist/graphql-server.mjs +1319 -0
  463. package/dist/job-worker.mjs +989 -0
  464. package/dist/main.mjs +495 -0
  465. package/dist/prepare-dashboard.mjs +35 -0
  466. package/dist/resources/cedar/policies.cedar +315 -0
  467. package/dist/resources/cedar/schema.cedarschema +276 -0
  468. package/dist/resources/graphql-schema/rxdb.graphql +401 -0
  469. package/dist/resources/graphql-schema/system.graphql +1200 -0
  470. package/package.json +98 -0
@@ -0,0 +1,1119 @@
1
+ "use client"
2
+
3
+ import type { Collection } from "@tanstack/db"
4
+ import { createCollection } from "@tanstack/react-db"
5
+ import { rxdbCollectionOptions } from "@tanstack/rxdb-db-collection"
6
+ import {
7
+ type ReactNode,
8
+ createContext,
9
+ useCallback,
10
+ useContext,
11
+ useEffect,
12
+ useState,
13
+ useSyncExternalStore,
14
+ } from "react"
15
+ import type { RxCollection } from "rxdb/plugins/core"
16
+ import type { RxReplicationState } from "rxdb/plugins/replication"
17
+ import type { RxGraphQLReplicationState } from "rxdb/plugins/replication-graphql"
18
+ import { getRealtimeRecipientId } from "../../../../modules/auth-session/src/lib/realtime-recipient.ts"
19
+ import type { PullCheckpoint } from "../generated/gql/graphql.ts"
20
+ import {
21
+ canInitializeCollectionForScope,
22
+ shouldResetCollectionBinding,
23
+ } from "./collection-provider-scope.ts"
24
+ import { DatabaseErrorUI } from "./database-error-ui.tsx"
25
+ import {
26
+ type PullQueryBuilder,
27
+ type PushQueryBuilder,
28
+ type ReplicationConfig,
29
+ type StreamQueryBuilder,
30
+ createReplication,
31
+ } from "./replication-factory.ts"
32
+ import {
33
+ getReplicationExpiry,
34
+ registerReplication,
35
+ unregisterReplication,
36
+ } from "./replication-registry.ts"
37
+ import {
38
+ type ProcessFocusDatabase,
39
+ cleanupRxDb,
40
+ useRxDb,
41
+ } from "./rxdb-provider.tsx"
42
+ import { useAuth } from "@/components/auth-provider"
43
+ import { useRuntimeConfig } from "@/components/config-provider"
44
+ import { getSessionCacheScope } from "@/lib/auth/session-cache-scope"
45
+
46
+ /**
47
+ * Configuration for creating a collection provider
48
+ */
49
+ /**
50
+ * Base type for all RxDB documents - must have id and updatedAt
51
+ */
52
+ interface RxDbDocumentBase {
53
+ id: string
54
+ updatedAt: number
55
+ }
56
+
57
+ const errorMessage = (error: unknown): string =>
58
+ error instanceof Error ? error.message : String(error)
59
+
60
+ const asError = (error: unknown): Error =>
61
+ error instanceof Error ? error : new Error(String(error))
62
+
63
+ const subscribeToHydration = () => () => {}
64
+ const getHydratedSnapshot = () => true
65
+ const getServerSnapshot = () => false
66
+
67
+ interface CollectionProviderConfig<TDoc extends RxDbDocumentBase> {
68
+ /**
69
+ * Name of the collection (used for error messages and identifiers)
70
+ */
71
+ name: string
72
+
73
+ /**
74
+ * Pull query builder for fetching data from server
75
+ */
76
+ pullQueryBuilder: PullQueryBuilder
77
+
78
+ /**
79
+ * Stream query builder for real-time subscriptions (optional - if not provided, uses polling only)
80
+ */
81
+ pullStreamQueryBuilder?: StreamQueryBuilder
82
+
83
+ /**
84
+ * Push query builder for sending data to server (optional for read-only collections)
85
+ */
86
+ pushQueryBuilder?: PushQueryBuilder
87
+
88
+ /**
89
+ * Field name for soft deletes
90
+ */
91
+ deletedField: string
92
+
93
+ /**
94
+ * AppSync Events channel path (e.g., "/rxdb/collection/process")
95
+ */
96
+ appSyncChannel: string
97
+
98
+ /**
99
+ * Key to extract pull result from GraphQL response (e.g., "pullProcess")
100
+ */
101
+ pullResultKey: string
102
+
103
+ /**
104
+ * Key to extract push result from GraphQL response (e.g., "pushProcess")
105
+ */
106
+ pushResultKey?: string
107
+
108
+ /**
109
+ * Function to get the RxDB collection from the database
110
+ */
111
+ getRxCollection: (db: ProcessFocusDatabase) => RxCollection<TDoc>
112
+
113
+ /**
114
+ * Optional hook to create TanStack DB indexes before queries subscribe.
115
+ */
116
+ createIndexes?: (collection: Collection<TDoc, string>) => void
117
+
118
+ /**
119
+ * One-time local reset key for server-derived fields that old checkpoints
120
+ * cannot refresh unless local docs and replication metadata are cleared.
121
+ */
122
+ resetReplicationOnReadyKey?: string
123
+ }
124
+
125
+ type CollectionState<TDoc extends RxDbDocumentBase> =
126
+ | {
127
+ status: "waiting-for-rxdb" | "initializing"
128
+ promise: Promise<Collection<TDoc, string>>
129
+ resolve: (collection: Collection<TDoc, string>) => void
130
+ reject: (error: Error) => void
131
+ }
132
+ | {
133
+ status: "ready"
134
+ collection: Collection<TDoc, string>
135
+ replicationState:
136
+ | RxReplicationState<TDoc, PullCheckpoint>
137
+ | RxGraphQLReplicationState<TDoc, PullCheckpoint>
138
+ promise: Promise<Collection<TDoc, string>>
139
+ }
140
+ | {
141
+ status: "error"
142
+ error: Error
143
+ promise: Promise<Collection<TDoc, string>>
144
+ }
145
+
146
+ type PendingCollectionState<TDoc extends RxDbDocumentBase> = Extract<
147
+ CollectionState<TDoc>,
148
+ { status: "waiting-for-rxdb" | "initializing" }
149
+ >
150
+
151
+ function isPendingCollectionState<TDoc extends RxDbDocumentBase>(
152
+ state: CollectionState<TDoc>,
153
+ ): state is PendingCollectionState<TDoc> {
154
+ return state.status === "waiting-for-rxdb" || state.status === "initializing"
155
+ }
156
+
157
+ export type CollectionStateStatus = CollectionState<RxDbDocumentBase>["status"]
158
+
159
+ /**
160
+ * Runtime configuration needed for replication
161
+ */
162
+ export interface ReplicationRuntimeConfig {
163
+ appSyncEventsHttpEndpoint: string
164
+ graphqlEndpoint: string
165
+ wsEndpoint: string
166
+ /** Effective owner for recreation checks, never the realtime address. */
167
+ userId: string
168
+ }
169
+
170
+ export interface CollectionContextValue<TDoc extends RxDbDocumentBase> {
171
+ db: ProcessFocusDatabase | null
172
+ rxCollection: RxCollection<TDoc> | null
173
+ state: CollectionState<TDoc>
174
+ /** Promise that resolves when the collection is ready - use with React's use() hook */
175
+ collectionPromise: Promise<Collection<TDoc, string>>
176
+ /**
177
+ * Recreate replication from scratch - cancels old replication and creates fresh one.
178
+ * Keeps the RxDB collection and TanStack collection intact.
179
+ * Useful when authentication/authorization context changes (e.g., role switch).
180
+ */
181
+ recreateReplication: (
182
+ runtimeConfig: ReplicationRuntimeConfig,
183
+ ) => Promise<void>
184
+ }
185
+
186
+ const isRxDbAlreadyRemovedError = (error: unknown): boolean => {
187
+ // RxDB replication metaInstance.remove() throws a plain Error("removed")
188
+ // after the replication database is already gone. Collection operations use
189
+ // COL21 for the same closed/removed lifecycle state.
190
+ if (error instanceof Error && error.message === "removed") {
191
+ return true
192
+ }
193
+
194
+ if (typeof error !== "object" || error === null) {
195
+ return false
196
+ }
197
+
198
+ return (error as Record<string, unknown>)["code"] === "COL21"
199
+ }
200
+
201
+ /**
202
+ * Creates a collection provider with all the necessary state management, replication,
203
+ * and Suspense support.
204
+ *
205
+ * @returns An object with Provider component, useCollection hook, and cleanup function
206
+ */
207
+ export function createCollectionProvider<TDoc extends RxDbDocumentBase>(
208
+ config: CollectionProviderConfig<TDoc>,
209
+ ) {
210
+ function createPendingState(
211
+ status: "waiting-for-rxdb" | "initializing",
212
+ ): CollectionState<TDoc> {
213
+ let resolve: (collection: Collection<TDoc, string>) => void = () => {}
214
+ let reject: (error: Error) => void = () => {}
215
+
216
+ const promise = new Promise<Collection<TDoc, string>>((res, rej) => {
217
+ resolve = res
218
+ reject = rej
219
+ })
220
+ // Session teardown can reject before a Suspense consumer has subscribed.
221
+ void promise.catch(() => {})
222
+
223
+ return {
224
+ status,
225
+ promise,
226
+ resolve,
227
+ reject,
228
+ }
229
+ }
230
+
231
+ // ==========================================================================
232
+ // Module-level state
233
+ // ==========================================================================
234
+ // These variables live at module scope (not component state) for two reasons:
235
+ // 1. React 18 Strict Mode double-mounts components—module state persists across
236
+ // unmount/remount so we don't re-initialize or lose WebSocket connections.
237
+ // 2. Replication should stay alive across page navigation within the SPA.
238
+ //
239
+ // This state is reset in three ways:
240
+ // - **Retry (error recovery)**: reloads the page, which reloads the module.
241
+ // - **Logout**: calls cleanup() which manually resets these variables.
242
+ // - **Org switch**: resets the singleton so the next scope gets a fresh collection.
243
+ // - **RxDB remount**: resets when the same org gets a fresh RxDB collection.
244
+ // ==========================================================================
245
+
246
+ // Singleton state - survives component unmount/remount
247
+ let persistentState: CollectionState<TDoc> =
248
+ createPendingState("waiting-for-rxdb")
249
+
250
+ // Prevents duplicate initialization starts (needed for React 18 Strict Mode double-mount)
251
+ let initializationInProgress = false
252
+
253
+ // Generation counter - incremented on cleanup() to invalidate in-progress initializations.
254
+ // Any async init that started before cleanup() will detect the mismatch and abort.
255
+ let cleanupGeneration = 0
256
+
257
+ // Prevents a one-time reset from starting multiple concurrent recreations.
258
+ let resetReplicationInProgress = false
259
+
260
+ // Avoids repeating a completed reset when localStorage markers cannot be
261
+ // written, for example in private browsing or storage-quota failures.
262
+ const completedReplicationResetKeys = new Set<string>()
263
+
264
+ // Module-level reference to rxCollection for use by registered recreate function
265
+ let moduleRxCollection: RxCollection<TDoc> | null = null
266
+ let replicationAuthority: ReturnType<typeof useAuth> | null = null
267
+ let activeReplicationConfig: ReplicationConfig<TDoc> | null = null
268
+
269
+ // Tracks which org scope the singleton state belongs to.
270
+ let activeScopeKey: string | null = null
271
+ let sessionCacheScope = ""
272
+
273
+ // Callbacks to trigger React re-renders when replication is recreated
274
+ const forceUpdateCallbacks = new Set<() => void>()
275
+
276
+ function triggerAllUpdates(): void {
277
+ for (const callback of forceUpdateCallbacks) {
278
+ callback()
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Module-level recreate function registered with the replication registry.
284
+ * Called when role switches - recreates replication for this collection if active.
285
+ */
286
+ async function registeredRecreateReplication(
287
+ runtimeConfig: ReplicationRuntimeConfig,
288
+ ): Promise<void> {
289
+ if (persistentState.status !== "ready" || !moduleRxCollection) {
290
+ console.log(
291
+ `${config.name} not ready for replication recreation, skipping`,
292
+ )
293
+ return
294
+ }
295
+
296
+ await recreateReplication(
297
+ runtimeConfig,
298
+ moduleRxCollection,
299
+ triggerAllUpdates,
300
+ )
301
+ }
302
+
303
+ const Context = createContext<CollectionContextValue<TDoc> | null>(null)
304
+
305
+ /** Check if cleanup() was called since initialization started */
306
+ function isStaleInitialization(startGeneration: number): boolean {
307
+ return startGeneration !== cleanupGeneration
308
+ }
309
+
310
+ /**
311
+ * Get or create a promise that resolves when the collection is ready.
312
+ * This promise can be used with React's use() hook for Suspense integration.
313
+ */
314
+ function getCollectionPromise(): Promise<Collection<TDoc, string>> {
315
+ return persistentState.promise
316
+ }
317
+
318
+ /**
319
+ * Cleanup function for logout - cancels replication and resets singleton state
320
+ */
321
+ async function cleanup(): Promise<void> {
322
+ cleanupGeneration++
323
+ const previousState = persistentState
324
+ // Unregister from the replication registry
325
+ unregisterReplication(config.name)
326
+
327
+ // Invalidate synchronously, before waiting for storage/socket teardown.
328
+ initializationInProgress = false
329
+ resetReplicationInProgress = false
330
+ moduleRxCollection = null
331
+ replicationAuthority = null
332
+ activeReplicationConfig = null
333
+ activeScopeKey = null
334
+ forceUpdateCallbacks.clear()
335
+ persistentState = createPendingState("waiting-for-rxdb")
336
+
337
+ if (previousState.status === "ready") {
338
+ try {
339
+ await Promise.all([
340
+ previousState.replicationState.cancel(),
341
+ previousState.collection.cleanup(),
342
+ ])
343
+ } catch (error) {
344
+ console.error(
345
+ `Failed to cancel ${config.name} replication during cleanup:`,
346
+ errorMessage(error),
347
+ )
348
+ }
349
+ }
350
+ // For pending states, don't reject - just abandon the promise. Components
351
+ // using it unmount during logout, so the orphaned promise is GC'd.
352
+ }
353
+
354
+ function resetForScopeChange(
355
+ nextScopeKey: string,
356
+ nextRxCollection: RxCollection<TDoc> | null,
357
+ ): Promise<void> | null {
358
+ if (
359
+ !shouldResetCollectionBinding({
360
+ activeCollection: moduleRxCollection,
361
+ activeScopeKey,
362
+ nextCollection: nextRxCollection,
363
+ nextScopeKey,
364
+ })
365
+ ) {
366
+ return null
367
+ }
368
+
369
+ unregisterReplication(config.name)
370
+
371
+ const previousState = persistentState
372
+
373
+ initializationInProgress = false
374
+ cleanupGeneration++
375
+ moduleRxCollection = null
376
+ replicationAuthority = null
377
+ activeReplicationConfig = null
378
+ activeScopeKey = null
379
+ persistentState = createPendingState("waiting-for-rxdb")
380
+
381
+ if (previousState.status === "ready") {
382
+ return Promise.all([
383
+ previousState.replicationState.cancel(),
384
+ previousState.collection.cleanup(),
385
+ ])
386
+ .then(() => undefined)
387
+ .catch((error: unknown) => {
388
+ if (isRxDbAlreadyRemovedError(error)) {
389
+ return
390
+ }
391
+
392
+ console.error(
393
+ `Failed to cancel ${config.name} replication during collection reset:`,
394
+ errorMessage(error),
395
+ )
396
+ })
397
+ }
398
+
399
+ return Promise.resolve()
400
+ }
401
+
402
+ /**
403
+ * Recreate replication from scratch.
404
+ * Clears local documents and replication checkpoint, then creates fresh replication.
405
+ * Keeps the RxDB collection schema and TanStack collection intact.
406
+ *
407
+ * @param runtimeConfig - Runtime configuration with endpoints
408
+ * @param rxCollection - The RxDB collection to replicate
409
+ * @param forceUpdate - Optional callback to trigger React re-render
410
+ */
411
+ async function recreateReplication(
412
+ runtimeConfig: ReplicationRuntimeConfig,
413
+ rxCollection: RxCollection<TDoc>,
414
+ forceUpdate?: () => void,
415
+ ): Promise<void> {
416
+ if (persistentState.status !== "ready") {
417
+ console.error(
418
+ `Cannot recreate ${config.name} replication - not in ready state (current: ${persistentState.status})`,
419
+ )
420
+ return
421
+ }
422
+
423
+ const { collection, replicationState: oldReplicationState } =
424
+ persistentState
425
+ const authority = replicationAuthority
426
+ const startGeneration = cleanupGeneration
427
+ if (
428
+ !authority ||
429
+ rxCollection !== moduleRxCollection ||
430
+ runtimeConfig.userId !== authority.session.userId
431
+ ) {
432
+ throw new Error("Replication authority is unavailable or changed")
433
+ }
434
+ const isCurrent = () => !isStaleInitialization(startGeneration)
435
+
436
+ console.log(`Recreating ${config.name} replication...`)
437
+
438
+ try {
439
+ const expiresAt = await getReplicationExpiry(
440
+ getSessionCacheScope(authority.session),
441
+ authority.expiresAt,
442
+ )
443
+ if (!isCurrent()) return
444
+ // 1. Clear replication meta instance (checkpoint data) BEFORE cancelling
445
+ // This removes the checkpoint so the next replication starts fresh
446
+ if (oldReplicationState.metaInstance) {
447
+ console.log(`Clearing ${config.name} replication checkpoint...`)
448
+ try {
449
+ await oldReplicationState.metaInstance.remove()
450
+ console.log(`${config.name} replication checkpoint cleared`)
451
+ } catch (error) {
452
+ if (!isRxDbAlreadyRemovedError(error)) {
453
+ throw error
454
+ }
455
+ console.log(
456
+ `${config.name} replication checkpoint was already removed`,
457
+ )
458
+ }
459
+ }
460
+
461
+ // 2. Cancel old replication (after meta is cleared)
462
+ console.log(`Cancelling old ${config.name} replication...`)
463
+ try {
464
+ await oldReplicationState.cancel()
465
+ } catch (error) {
466
+ if (!isRxDbAlreadyRemovedError(error)) {
467
+ throw error
468
+ }
469
+ console.log(`${config.name} replication was already removed`)
470
+ }
471
+
472
+ // 3. Remove all local documents from the collection
473
+ if (!isCurrent()) return
474
+ // This ensures we don't show stale data from the old role
475
+ console.log(`Removing local ${config.name} documents...`)
476
+ const allDocs = await rxCollection.find().exec()
477
+ if (!isCurrent()) return
478
+ if (allDocs.length > 0) {
479
+ const docIds = allDocs.map((doc) => doc.primary)
480
+ await rxCollection.bulkRemove(docIds)
481
+ console.log(`Removed ${docIds.length} local ${config.name} documents`)
482
+ } else {
483
+ console.log(`No local ${config.name} documents to remove`)
484
+ }
485
+
486
+ // 4. Build replication config
487
+ const recipientId = await getRealtimeRecipientId(
488
+ authority.session,
489
+ expiresAt,
490
+ )
491
+ if (!isCurrent()) return
492
+ const baseConfig = {
493
+ cacheScope: sessionCacheScope,
494
+ collection: rxCollection,
495
+ pullQueryBuilder: config.pullQueryBuilder,
496
+ deletedField: config.deletedField,
497
+ replicationIdentifier: config.name,
498
+ pullResultKey: config.pullResultKey,
499
+ appSyncChannel: config.appSyncChannel,
500
+ graphqlEndpoint: runtimeConfig.graphqlEndpoint,
501
+ wsEndpoint: runtimeConfig.wsEndpoint,
502
+ httpHost: runtimeConfig.appSyncEventsHttpEndpoint,
503
+ recipientId,
504
+ session: authority.session,
505
+ accessTokenExpiresAt: expiresAt,
506
+ isCurrent,
507
+ }
508
+
509
+ const replicationConfig: ReplicationConfig<TDoc> = {
510
+ ...baseConfig,
511
+ ...(config.pullStreamQueryBuilder
512
+ ? { pullStreamQueryBuilder: config.pullStreamQueryBuilder }
513
+ : {}),
514
+ ...(config.pushQueryBuilder && config.pushResultKey
515
+ ? {
516
+ pushQueryBuilder: config.pushQueryBuilder,
517
+ pushResultKey: config.pushResultKey,
518
+ }
519
+ : { pushQueryBuilder: undefined, pushResultKey: undefined }),
520
+ }
521
+
522
+ // 5. Create new replication
523
+ console.log(`Creating new ${config.name} replication...`)
524
+ const newReplicationState = await createReplication(replicationConfig)
525
+ if (!isCurrent()) {
526
+ await newReplicationState.cancel()
527
+ return
528
+ }
529
+ activeReplicationConfig = replicationConfig
530
+ replicationAuthority = { session: authority.session, expiresAt }
531
+
532
+ // 6. Update persistent state (keep same collection and promise)
533
+ persistentState = {
534
+ status: "ready",
535
+ collection,
536
+ replicationState: newReplicationState,
537
+ promise: persistentState.promise,
538
+ }
539
+
540
+ console.log(`${config.name} replication recreated successfully`)
541
+
542
+ // 7. Trigger re-render if callback provided
543
+ if (forceUpdate) {
544
+ forceUpdate()
545
+ }
546
+ } catch (error) {
547
+ console.error(`Failed to recreate ${config.name} replication:`, error)
548
+ // Surface recreation failures to the role-switch coordinator. Keeping
549
+ // the old state after a partial reset can leave stale role-scoped rows
550
+ // visible, so callers need to fall back to a full local DB reset.
551
+ throw error
552
+ }
553
+ }
554
+
555
+ async function refreshCredentials(
556
+ expiresAt: number,
557
+ cacheScope: string,
558
+ ): Promise<void> {
559
+ if (isPendingCollectionState(persistentState)) await persistentState.promise
560
+ if (
561
+ persistentState.status !== "ready" ||
562
+ !activeReplicationConfig ||
563
+ !replicationAuthority
564
+ ) {
565
+ throw new Error("Replication is not ready for credential refresh")
566
+ }
567
+ const previousState = persistentState
568
+ const previousConfig = activeReplicationConfig
569
+ const session = replicationAuthority.session
570
+ if (getSessionCacheScope(session) !== cacheScope)
571
+ throw new Error("Replication authority changed")
572
+ if (!previousConfig.httpHost) {
573
+ // Local streams renew together after the barrier, retaining RxDB state.
574
+ replicationAuthority = { session, expiresAt }
575
+ return
576
+ }
577
+ const generation = ++cleanupGeneration
578
+ const isCurrent = () => !isStaleInitialization(generation)
579
+ // Invalidate old requests before waiting for socket/storage cancellation.
580
+ await previousState.replicationState.cancel()
581
+ const recipientId = await getRealtimeRecipientId(session, expiresAt)
582
+ if (!isCurrent()) throw new Error("Replication authority changed")
583
+ const nextConfig: ReplicationConfig<TDoc> = {
584
+ ...previousConfig,
585
+ recipientId,
586
+ accessTokenExpiresAt: expiresAt,
587
+ isCurrent,
588
+ }
589
+ const replicationState = await createReplication(nextConfig)
590
+ if (!isCurrent()) {
591
+ await replicationState.cancel()
592
+ throw new Error("Replication authority changed")
593
+ }
594
+ replicationAuthority = { session, expiresAt }
595
+ activeReplicationConfig = nextConfig
596
+ persistentState = { ...previousState, replicationState }
597
+ triggerAllUpdates()
598
+ }
599
+
600
+ function Provider({ children }: { children: ReactNode }) {
601
+ const { appSyncEventsHttpEndpoint, graphqlEndpoint, orgId, wsEndpoint } =
602
+ useRuntimeConfig()
603
+ const { state: rxDbState } = useRxDb()
604
+ const { session, expiresAt } = useAuth()
605
+ const cacheScope = getSessionCacheScope(session)
606
+ const scopeKey = JSON.stringify([
607
+ orgId,
608
+ getSessionCacheScope(session),
609
+ "clientId" in session || session.delegation ? session : null,
610
+ ])
611
+
612
+ const db = rxDbState.status === "ready" ? rxDbState.db : null
613
+ const rxCollection = db ? config.getRxCollection(db) : null
614
+ // Effective owner for recreation checks; addresses come from the session.
615
+ const userId = session.userId
616
+ const isHydrated = useSyncExternalStore(
617
+ subscribeToHydration,
618
+ getHydratedSnapshot,
619
+ getServerSnapshot,
620
+ )
621
+
622
+ const clearAndRetry = async () => {
623
+ try {
624
+ await cleanupRxDb()
625
+ } catch (error) {
626
+ console.error("Failed to cleanup before retry:", error)
627
+ }
628
+ window.location.reload() // Never returns—page reloads
629
+ }
630
+
631
+ // Local state to trigger re-renders when singleton changes
632
+ const [, forceUpdate] = useState({})
633
+
634
+ // Register forceUpdate callback for registry-triggered recreation
635
+ useEffect(() => {
636
+ const callback = () => forceUpdate({})
637
+ forceUpdateCallbacks.add(callback)
638
+ return () => {
639
+ forceUpdateCallbacks.delete(callback)
640
+ }
641
+ }, [])
642
+
643
+ useEffect(() => {
644
+ const cancelPreviousReplication = resetForScopeChange(
645
+ scopeKey,
646
+ rxCollection,
647
+ )
648
+
649
+ if (!cancelPreviousReplication) {
650
+ return
651
+ }
652
+
653
+ // Flush the reset singleton state into context immediately so consumers stop
654
+ // reading the previous org's ready collection while the new scope initializes.
655
+ forceUpdate({})
656
+ }, [scopeKey, rxCollection])
657
+
658
+ useEffect(() => {
659
+ let cancelled = false
660
+
661
+ // Early return if RxDB not ready
662
+ if (!db || !rxCollection) {
663
+ return
664
+ }
665
+
666
+ // Atomic check-and-set to prevent race conditions where multiple components
667
+ // could both see status as waiting before either sets initializing
668
+ // Also check initializationInProgress to prevent React 18 Strict Mode double-init
669
+ if (
670
+ !canInitializeCollectionForScope({
671
+ activeScopeKey,
672
+ initializationInProgress,
673
+ nextScopeKey: scopeKey,
674
+ persistentStatus: persistentState.status,
675
+ })
676
+ ) {
677
+ return
678
+ }
679
+
680
+ // Type guard: canInitializeCollectionForScope returning true guarantees
681
+ // we're in "waiting-for-rxdb" state, but TypeScript can't infer this.
682
+ if (persistentState.status !== "waiting-for-rxdb") {
683
+ return
684
+ }
685
+
686
+ // Mark initialization as in progress BEFORE any async work
687
+ initializationInProgress = true
688
+ activeScopeKey = scopeKey
689
+ sessionCacheScope = cacheScope
690
+ replicationAuthority = { session, expiresAt }
691
+ registerReplication(
692
+ config.name,
693
+ registeredRecreateReplication,
694
+ refreshCredentials,
695
+ )
696
+
697
+ // Capture generation to detect if cleanup was called during initialization
698
+ const startGeneration = cleanupGeneration
699
+
700
+ // Preserve the existing promise/resolvers, just change status
701
+ const previousState = persistentState
702
+
703
+ // Mark as initializing immediately after the check to minimize race window
704
+ persistentState = {
705
+ ...previousState,
706
+ status: "initializing",
707
+ }
708
+
709
+ const baseConfig = {
710
+ collection: rxCollection,
711
+ cacheScope: sessionCacheScope,
712
+ pullQueryBuilder: config.pullQueryBuilder,
713
+ deletedField: config.deletedField,
714
+ replicationIdentifier: config.name,
715
+ pullResultKey: config.pullResultKey,
716
+ appSyncChannel: config.appSyncChannel,
717
+ graphqlEndpoint,
718
+ wsEndpoint,
719
+ httpHost: appSyncEventsHttpEndpoint,
720
+ accessTokenExpiresAt: expiresAt,
721
+ session,
722
+ isCurrent: () => !isStaleInitialization(startGeneration),
723
+ }
724
+
725
+ const replicationConfig = {
726
+ ...baseConfig,
727
+ ...(config.pullStreamQueryBuilder
728
+ ? { pullStreamQueryBuilder: config.pullStreamQueryBuilder }
729
+ : {}),
730
+ ...(config.pushQueryBuilder && config.pushResultKey
731
+ ? {
732
+ pushQueryBuilder: config.pushQueryBuilder,
733
+ pushResultKey: config.pushResultKey,
734
+ }
735
+ : { pushQueryBuilder: undefined, pushResultKey: undefined }),
736
+ }
737
+
738
+ const initializeReplication = async () => {
739
+ try {
740
+ const cacheScope = getSessionCacheScope(session)
741
+ let effectiveExpiresAt: number
742
+ let recipientId: string | undefined
743
+ do {
744
+ effectiveExpiresAt = await getReplicationExpiry(
745
+ cacheScope,
746
+ expiresAt,
747
+ )
748
+ recipientId = await getRealtimeRecipientId(
749
+ session,
750
+ effectiveExpiresAt,
751
+ )
752
+ if (isStaleInitialization(startGeneration)) return
753
+ } while (
754
+ getReplicationExpiry(cacheScope, expiresAt) !== effectiveExpiresAt
755
+ )
756
+ if (isStaleInitialization(startGeneration)) return
757
+ replicationAuthority = { session, expiresAt: effectiveExpiresAt }
758
+ const resolvedConfig: ReplicationConfig<TDoc> = {
759
+ ...replicationConfig,
760
+ recipientId,
761
+ accessTokenExpiresAt: effectiveExpiresAt,
762
+ }
763
+ const replicationState = await createReplication(resolvedConfig)
764
+
765
+ // NOTE: We intentionally do NOT cancel the replication even if the React effect
766
+ // was cancelled (e.g., during React 18 Strict Mode double-mount).
767
+ // Cancelling would close the WebSocket connection. Instead, we let the
768
+ // replication stay alive and proceed to update module state to "ready".
769
+ // The second mount will see status != "waiting-for-rxdb" and skip initialization.
770
+
771
+ const collection: Collection<TDoc, string> = createCollection(
772
+ rxdbCollectionOptions({
773
+ rxCollection,
774
+ startSync: true,
775
+ }),
776
+ )
777
+
778
+ if (config.createIndexes) {
779
+ config.createIndexes(collection)
780
+ }
781
+
782
+ // If cleanup/retry was called, cancel replication and bail out.
783
+ // Note: initializationInProgress was already reset by cleanup/retry.
784
+ if (isStaleInitialization(startGeneration)) {
785
+ try {
786
+ await replicationState.cancel()
787
+ await collection.cleanup()
788
+ } catch {
789
+ // Ignore - replication may already be cancelled
790
+ }
791
+ return
792
+ }
793
+
794
+ // NOTE: We proceed even if the React effect's `cancelled` flag is set
795
+ // (e.g., during React 18 Strict Mode double-mount). The replication is
796
+ // already created and we want to keep it alive. The module state will be
797
+ // updated to "ready" so the second mount will reuse it.
798
+ // However, if cleanup() was called (checked above), we DO abort.
799
+
800
+ // Resolve the promise for Suspense integration
801
+ if (isPendingCollectionState(persistentState)) {
802
+ persistentState.resolve(collection)
803
+ } else {
804
+ console.error("Unexpected state during initialization completion")
805
+ }
806
+
807
+ // Store in singleton
808
+ persistentState = {
809
+ status: "ready",
810
+ collection,
811
+ replicationState,
812
+ // Keep the same promise instance that is now resolved
813
+ promise: persistentState.promise,
814
+ }
815
+
816
+ // Store rxCollection at module level for registry access
817
+ moduleRxCollection = rxCollection
818
+ activeReplicationConfig = resolvedConfig
819
+
820
+ // Clear the in-progress flag now that we're done
821
+ initializationInProgress = false
822
+
823
+ // Every mounted Provider shares this singleton state. Notify all of
824
+ // them regardless of which instance started initialization.
825
+ triggerAllUpdates()
826
+ } catch (error) {
827
+ // If cleanup/retry was called, bail out (flag already reset by them)
828
+ if (isStaleInitialization(startGeneration)) {
829
+ return
830
+ }
831
+
832
+ console.error(
833
+ `Failed to initialize ${config.name} replication:`,
834
+ error,
835
+ )
836
+
837
+ const errorObj = asError(error)
838
+
839
+ // Reject the promise for Suspense integration
840
+ if (isPendingCollectionState(persistentState)) {
841
+ persistentState.reject(errorObj)
842
+ } else {
843
+ console.error("Unexpected state during initialization failure")
844
+ }
845
+
846
+ persistentState = {
847
+ status: "error",
848
+ error: errorObj,
849
+ // Keep the same promise instance that is now rejected
850
+ promise: persistentState.promise,
851
+ }
852
+
853
+ // Clear the in-progress flag on error
854
+ initializationInProgress = false
855
+
856
+ // Ensure the app-level recovery surface updates even when another
857
+ // Provider instance won the initialization race.
858
+ triggerAllUpdates()
859
+ }
860
+ }
861
+
862
+ initializeReplication().catch((error) => {
863
+ if (cancelled || isStaleInitialization(startGeneration)) {
864
+ return
865
+ }
866
+
867
+ console.error(
868
+ `Unhandled error in ${config.name} initialization:`,
869
+ error,
870
+ )
871
+ // Fallback error handling in case the async function throws before try block
872
+ const errorObj = asError(error)
873
+
874
+ if (isPendingCollectionState(persistentState)) {
875
+ persistentState.reject(errorObj)
876
+ }
877
+
878
+ persistentState = {
879
+ status: "error",
880
+ error: errorObj,
881
+ promise: persistentState.promise,
882
+ }
883
+
884
+ // Clear the in-progress flag on error
885
+ initializationInProgress = false
886
+
887
+ triggerAllUpdates()
888
+ })
889
+
890
+ // Cleanup function - sets cancelled flag but does NOT cancel replication
891
+ // The replication persists at module level across unmounts to keep WebSocket alive
892
+ return () => {
893
+ cancelled = true
894
+ // We do NOT cancel the replication or reset state here.
895
+ // The async initialization will complete and store the replication in module state.
896
+ // This ensures WebSocket connections persist across React's double-mount (Strict Mode)
897
+ // and across page navigation.
898
+ }
899
+ }, [
900
+ appSyncEventsHttpEndpoint,
901
+ cacheScope,
902
+ db,
903
+ rxCollection,
904
+ graphqlEndpoint,
905
+ scopeKey,
906
+ wsEndpoint,
907
+ session,
908
+ expiresAt,
909
+ ])
910
+
911
+ useEffect(() => {
912
+ if (!config.resetReplicationOnReadyKey || !rxCollection) {
913
+ return
914
+ }
915
+
916
+ let cancelled = false
917
+
918
+ const resetWhenReady = async () => {
919
+ try {
920
+ await getCollectionPromise()
921
+ } catch (error) {
922
+ console.error(
923
+ `Failed to wait for ${config.name} before replication reset:`,
924
+ error,
925
+ )
926
+ return
927
+ }
928
+
929
+ if (
930
+ cancelled ||
931
+ persistentState.status !== "ready" ||
932
+ activeScopeKey !== scopeKey
933
+ ) {
934
+ return
935
+ }
936
+
937
+ const storageKey = [
938
+ "pf",
939
+ orgId,
940
+ scopeKey,
941
+ config.name,
942
+ "replication-reset",
943
+ config.resetReplicationOnReadyKey,
944
+ ].join(":")
945
+
946
+ if (completedReplicationResetKeys.has(storageKey)) {
947
+ return
948
+ }
949
+
950
+ try {
951
+ if (window.localStorage.getItem(storageKey) === "done") {
952
+ completedReplicationResetKeys.add(storageKey)
953
+ return
954
+ }
955
+ } catch (error) {
956
+ console.warn(
957
+ `Unable to read ${config.name} replication reset marker:`,
958
+ errorMessage(error),
959
+ )
960
+ }
961
+
962
+ if (resetReplicationInProgress) {
963
+ return
964
+ }
965
+
966
+ resetReplicationInProgress = true
967
+ recreateReplication(
968
+ {
969
+ appSyncEventsHttpEndpoint,
970
+ graphqlEndpoint,
971
+ userId,
972
+ wsEndpoint,
973
+ },
974
+ rxCollection,
975
+ triggerAllUpdates,
976
+ )
977
+ .then(() => {
978
+ completedReplicationResetKeys.add(storageKey)
979
+ try {
980
+ window.localStorage.setItem(storageKey, "done")
981
+ } catch (error) {
982
+ console.warn(
983
+ `Unable to write ${config.name} replication reset marker:`,
984
+ errorMessage(error),
985
+ )
986
+ }
987
+ })
988
+ .catch((error) => {
989
+ console.error(`Failed to reset ${config.name} replication:`, error)
990
+ })
991
+ .finally(() => {
992
+ resetReplicationInProgress = false
993
+ })
994
+ }
995
+
996
+ resetWhenReady()
997
+
998
+ return () => {
999
+ cancelled = true
1000
+ }
1001
+ }, [
1002
+ appSyncEventsHttpEndpoint,
1003
+ graphqlEndpoint,
1004
+ orgId,
1005
+ rxCollection,
1006
+ scopeKey,
1007
+ userId,
1008
+ wsEndpoint,
1009
+ ])
1010
+
1011
+ // Memoize recreateReplication to avoid new function reference each render
1012
+ // Note: persistentState is module-level so we access it directly in the callback
1013
+ const recreateReplicationCallback = useCallback(
1014
+ async (runtimeConfig: ReplicationRuntimeConfig) => {
1015
+ if (activeScopeKey !== scopeKey) {
1016
+ throw new Error("Replication authority changed")
1017
+ }
1018
+ // Wait for collection to be ready if not yet
1019
+ if (persistentState.status !== "ready") {
1020
+ console.log(
1021
+ `${config.name} not ready (${persistentState.status}), waiting for collection...`,
1022
+ )
1023
+ try {
1024
+ await getCollectionPromise()
1025
+ console.log(`${config.name} collection is now ready`)
1026
+ } catch (error) {
1027
+ console.error(
1028
+ `Failed to wait for ${config.name} collection:`,
1029
+ error,
1030
+ )
1031
+ return
1032
+ }
1033
+ }
1034
+
1035
+ // After awaiting, persistentState should be updated (it's module-level)
1036
+ if (persistentState.status !== "ready") {
1037
+ console.error(
1038
+ `${config.name} still not ready after awaiting - cannot recreate replication`,
1039
+ )
1040
+ return
1041
+ }
1042
+
1043
+ if (!rxCollection) {
1044
+ console.error(
1045
+ `Cannot recreate ${config.name} replication - rxCollection not available`,
1046
+ )
1047
+ return
1048
+ }
1049
+ if (activeScopeKey !== scopeKey) {
1050
+ throw new Error("Replication authority changed")
1051
+ }
1052
+ await recreateReplication(
1053
+ runtimeConfig,
1054
+ rxCollection,
1055
+ triggerAllUpdates,
1056
+ )
1057
+ },
1058
+ [rxCollection, scopeKey],
1059
+ )
1060
+
1061
+ // Scope resets replace the singleton; never retain its previous context value.
1062
+ const contextValue: CollectionContextValue<TDoc> = {
1063
+ db,
1064
+ rxCollection,
1065
+ state: persistentState,
1066
+ collectionPromise: getCollectionPromise(),
1067
+ recreateReplication: recreateReplicationCallback,
1068
+ }
1069
+
1070
+ // Effects cancel old replication after render. Do not publish the previous
1071
+ // authority's already-ready singleton during that intervening render.
1072
+ if (
1073
+ activeScopeKey !== scopeKey ||
1074
+ (persistentState.status === "ready" &&
1075
+ moduleRxCollection !== rxCollection)
1076
+ )
1077
+ return null
1078
+
1079
+ return (
1080
+ <Context.Provider value={contextValue}>
1081
+ {isHydrated ? (
1082
+ persistentState.status === "error" ? (
1083
+ <DatabaseErrorUI
1084
+ error={persistentState.error}
1085
+ onRetry={clearAndRetry}
1086
+ />
1087
+ ) : (
1088
+ children
1089
+ )
1090
+ ) : null}
1091
+ </Context.Provider>
1092
+ )
1093
+ }
1094
+
1095
+ function useCollection() {
1096
+ const context = useContext(Context)
1097
+ if (!context) {
1098
+ throw new Error(
1099
+ `use${config.name}Collection must be used within ${config.name}CollectionProvider`,
1100
+ )
1101
+ }
1102
+ return context
1103
+ }
1104
+
1105
+ /**
1106
+ * Optional variant that returns null if not within provider.
1107
+ * Useful for components that may render outside the provider context.
1108
+ */
1109
+ function useCollectionOptional(): CollectionContextValue<TDoc> | null {
1110
+ return useContext(Context)
1111
+ }
1112
+
1113
+ return {
1114
+ Provider,
1115
+ useCollection,
1116
+ useCollectionOptional,
1117
+ cleanup,
1118
+ }
1119
+ }