@tearleads/client-sdk 0.1.251 → 0.1.253

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 (226) hide show
  1. package/Tearleads.d.ts +0 -2
  2. package/Tearleads.js +17 -28
  3. package/Tearleads.js.map +1 -1
  4. package/client/containerContents/index.d.ts +2 -0
  5. package/client/containerContents/index.js +4 -9
  6. package/client/containerContents/index.js.map +1 -1
  7. package/client/containerContents/storeRuntime.d.ts +17 -0
  8. package/client/containerContents/storeRuntime.js +31 -0
  9. package/client/containerContents/storeRuntime.js.map +1 -0
  10. package/client/deviceFirst/index.d.ts +2 -3
  11. package/client/deviceFirst/index.js +44 -22
  12. package/client/deviceFirst/index.js.map +1 -1
  13. package/client/organizations/organizationReadModelPresentation.js +7 -4
  14. package/client/organizations/organizationReadModelPresentation.js.map +1 -1
  15. package/client/organizations/organizationReadModels.js +6 -5
  16. package/client/organizations/organizationReadModels.js.map +1 -1
  17. package/client/organizations/organizationWorkflowRuntime.js +1 -1
  18. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  19. package/client/runtime/principalMutationApi.d.ts +4 -0
  20. package/client/runtime/principalMutationApi.js +9 -5
  21. package/client/runtime/principalMutationApi.js.map +1 -1
  22. package/client/runtime/runtimeIdentityResolution.js +23 -0
  23. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  24. package/client/runtime/runtimeSubscription.js +68 -0
  25. package/client/runtime/runtimeSubscription.js.map +1 -0
  26. package/client/runtime/workflowRuntime.d.ts +3 -1
  27. package/client/runtime/workflowRuntime.js +31 -81
  28. package/client/runtime/workflowRuntime.js.map +1 -1
  29. package/client/session/authenticationMachine.js +47 -0
  30. package/client/session/authenticationMachine.js.map +1 -0
  31. package/client/session/index.js +75 -93
  32. package/client/session/index.js.map +1 -1
  33. package/client/session/sessionBlobStore.js +39 -0
  34. package/client/session/sessionBlobStore.js.map +1 -0
  35. package/client/session/sessionContext.js +11 -0
  36. package/client/session/sessionContext.js.map +1 -1
  37. package/client/session/sessionIdentityTrust.d.ts +2 -1
  38. package/client/session/sessionIdentityTrust.js +8 -4
  39. package/client/session/sessionIdentityTrust.js.map +1 -1
  40. package/client/session/sessionLifetime.js +87 -0
  41. package/client/session/sessionLifetime.js.map +1 -0
  42. package/client/session/sessionLogin.js +114 -0
  43. package/client/session/sessionLogin.js.map +1 -0
  44. package/client/session/sessionOrganizationCreation.js +3 -2
  45. package/client/session/sessionOrganizationCreation.js.map +1 -1
  46. package/client/session/sessionPurgeRecovery.js +11 -3
  47. package/client/session/sessionPurgeRecovery.js.map +1 -1
  48. package/client/session/sessionTypes.d.ts +6 -2
  49. package/client/session/sessionTypes.js.map +1 -1
  50. package/data/blobs/blobContracts.d.ts +4 -3
  51. package/data/blobs/blobContracts.js.map +1 -1
  52. package/data/blobs/createBlobStore.js +1 -8
  53. package/data/blobs/createBlobStore.js.map +1 -1
  54. package/data/blobs/encryptedBlobStore.js +17 -12
  55. package/data/blobs/encryptedBlobStore.js.map +1 -1
  56. package/data/blobs/memoryBlobStore.js +8 -5
  57. package/data/blobs/memoryBlobStore.js.map +1 -1
  58. package/data/blobs/opfsBlobFile.js +36 -0
  59. package/data/blobs/opfsBlobFile.js.map +1 -0
  60. package/data/blobs/opfsBlobStore.d.ts +1 -1
  61. package/data/blobs/opfsBlobStore.js +91 -21
  62. package/data/blobs/opfsBlobStore.js.map +1 -1
  63. package/data/principals/principalPolicyCoordinator.js +8 -17
  64. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  65. package/data/shared/domainScope.d.ts +2 -0
  66. package/data/shared/domainScope.js +2 -1
  67. package/data/shared/domainScope.js.map +1 -1
  68. package/data/shared/keyedQueue.js +15 -0
  69. package/data/shared/keyedQueue.js.map +1 -0
  70. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  71. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  72. package/data/sqlite/sqlExec.d.ts +6 -0
  73. package/data/sqlite/sqlExec.js +64 -13
  74. package/data/sqlite/sqlExec.js.map +1 -1
  75. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  76. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  77. package/data/sync/syncCoordinator.js +17 -10
  78. package/data/sync/syncCoordinator.js.map +1 -1
  79. package/data/trustedUserIdentity/service.js +2 -1
  80. package/data/trustedUserIdentity/service.js.map +1 -1
  81. package/data/trustedUserIdentity/types.d.ts +1 -1
  82. package/data/trustedUserIdentity/types.js.map +1 -1
  83. package/internal/api-client/ApiClient.d.ts +4 -1
  84. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  85. package/internal/api-client/apiRequestRuntime.js +86 -101
  86. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  87. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  88. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  89. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  90. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  91. package/internal/api-client/client/blobs.d.ts +1 -0
  92. package/internal/api-client/client/blobs.js +12 -3
  93. package/internal/api-client/client/blobs.js.map +1 -1
  94. package/internal/api-client/client/laneListingRequest.js +4 -0
  95. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  96. package/internal/api-client/client/session.d.ts +5 -1
  97. package/internal/api-client/client/session.js +12 -4
  98. package/internal/api-client/client/session.js.map +1 -1
  99. package/internal/api-client/client/writerProjections.js +12 -13
  100. package/internal/api-client/client/writerProjections.js.map +1 -1
  101. package/internal/api-client/operationResponse.d.ts +1 -1
  102. package/internal/api-client/operationResponse.js +10 -23
  103. package/internal/api-client/operationResponse.js.map +1 -1
  104. package/internal/api-client/operationTransport.js +2 -1
  105. package/internal/api-client/operationTransport.js.map +1 -1
  106. package/internal/api-client/principalHistoryRequest.js +25 -20
  107. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  108. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  109. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  110. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  111. package/internal/api-client/principalPolicyPages.js +4 -2
  112. package/internal/api-client/principalPolicyPages.js.map +1 -1
  113. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  114. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  115. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  116. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  117. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  118. package/internal/api-client/routes/blobs/get.js +9 -67
  119. package/internal/api-client/routes/blobs/get.js.map +1 -1
  120. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  121. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  122. package/internal/api-client/sessionRefresh.js +1 -1
  123. package/internal/api-client/sessionRefresh.js.map +1 -1
  124. package/internal/api-client/sessionRenewal.d.ts +31 -0
  125. package/internal/api-client/sessionRenewal.js +91 -6
  126. package/internal/api-client/sessionRenewal.js.map +1 -1
  127. package/internal/api-client/sessionRequestInit.js +22 -0
  128. package/internal/api-client/sessionRequestInit.js.map +1 -0
  129. package/internal/api-client/sessionResponse.js +39 -0
  130. package/internal/api-client/sessionResponse.js.map +1 -0
  131. package/internal/api-client/types.d.ts +1 -0
  132. package/internal/api-client/types.js.map +1 -1
  133. package/internal/api-client/webSocketTickets.d.ts +1 -0
  134. package/internal/api-client/webSocketTickets.js +4 -0
  135. package/internal/api-client/webSocketTickets.js.map +1 -1
  136. package/internal/sqlite-worker/client.d.ts +1 -1
  137. package/internal/sqlite-worker/client.js +6 -1
  138. package/internal/sqlite-worker/client.js.map +1 -1
  139. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  140. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  141. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  142. package/internal/sqlite-worker/types.d.ts +4 -0
  143. package/internal/sqlite-worker/types.js.map +1 -1
  144. package/package.json +1 -1
  145. package/sqlite/worker.js +1 -1
  146. package/stores/container-contents/containerContentsStore.d.ts +3 -9
  147. package/stores/container-contents/containerContentsStore.js +24 -21
  148. package/stores/container-contents/containerContentsStore.js.map +1 -1
  149. package/stores/container-contents/containerState/storeScope.js +6 -0
  150. package/stores/container-contents/containerState/storeScope.js.map +1 -0
  151. package/stores/container-contents/hydration/backgroundHydration.js +2 -1
  152. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  153. package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
  154. package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
  155. package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
  156. package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
  157. package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
  158. package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
  159. package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
  160. package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
  161. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  162. package/stores/container-contents/hydration/startupHydration.js +2 -9
  163. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  164. package/stores/container-contents/hydration/treeResetMachine.js +61 -0
  165. package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
  166. package/stores/container-contents/localRefresh.js +28 -12
  167. package/stores/container-contents/localRefresh.js.map +1 -1
  168. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
  169. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
  170. package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
  171. package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
  172. package/stores/container-contents/state.d.ts +3 -7
  173. package/stores/container-contents/state.js +27 -16
  174. package/stores/container-contents/state.js.map +1 -1
  175. package/stores/container-contents/syncAgent/index.d.ts +7 -2
  176. package/stores/container-contents/syncAgent/index.js +77 -49
  177. package/stores/container-contents/syncAgent/index.js.map +1 -1
  178. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
  179. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  180. package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
  181. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  182. package/stores/local-projection/localProjectionStore.js +24 -15
  183. package/stores/local-projection/localProjectionStore.js.map +1 -1
  184. package/stores/local-projection/registry.js +2 -2
  185. package/stores/local-projection/registry.js.map +1 -1
  186. package/workflows/container-contents/container-state/create/createChild.js +3 -15
  187. package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
  188. package/workflows/container-contents/containerPersistence.d.ts +4 -8
  189. package/workflows/container-contents/containerPersistence.js +22 -12
  190. package/workflows/container-contents/containerPersistence.js.map +1 -1
  191. package/workflows/container-contents/localState.js +3 -0
  192. package/workflows/container-contents/localState.js.map +1 -1
  193. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
  194. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
  195. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
  196. package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
  197. package/workflows/container-contents/remoteHydration/index.js +17 -66
  198. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  199. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
  200. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
  201. package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
  202. package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
  203. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
  204. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  205. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
  206. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  207. package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
  208. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  209. package/workflows/container-contents/runtime.d.ts +3 -0
  210. package/workflows/container-contents/runtime.js.map +1 -1
  211. package/workflows/container-contents/storedContainerState.js +17 -7
  212. package/workflows/container-contents/storedContainerState.js.map +1 -1
  213. package/workflows/container-contents/syncLane.d.ts +1 -0
  214. package/workflows/container-contents/syncLane.js +9 -1
  215. package/workflows/container-contents/syncLane.js.map +1 -1
  216. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  217. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  218. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  219. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  220. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  221. package/workflows/registration/registerIdentity.js +2 -0
  222. package/workflows/registration/registerIdentity.js.map +1 -1
  223. package/workflows/shared/runtimeInput.d.ts +2 -0
  224. package/workflows/shared/runtimeInput.js.map +1 -1
  225. package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
  226. package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { resolveCanonicalExecSql, } from "../../../data/sqlite/sqlSchema.js";
1
+ import { sqlConnectionIdentity, } from "../../../data/sqlite/sqlExec.js";
2
2
  const mutationQueuesByExecSql = new WeakMap();
3
3
  /**
4
4
  * Serialize byte-store mutations that address the same document blob key.
@@ -7,7 +7,7 @@ const mutationQueuesByExecSql = new WeakMap();
7
7
  * must not acquire this lock from inside `runSerializedSqlMutation`.
8
8
  */
9
9
  export async function runSerializedDocumentBlobMutation(execSql, storageKey, operation) {
10
- const canonicalExecSql = resolveCanonicalExecSql(execSql);
10
+ const canonicalExecSql = sqlConnectionIdentity(execSql);
11
11
  const queues = mutationQueuesByExecSql.get(canonicalExecSql) ?? new Map();
12
12
  mutationQueuesByExecSql.set(canonicalExecSql, queues);
13
13
  const previous = queues.get(storageKey) ?? Promise.resolve();
@@ -1 +1 @@
1
- {"version":3,"file":"blobMutationLock.js","sourceRoot":"","sources":["blobMutationLock.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GACxB,MAAM,gCAAgC,CAAC;AAExC,MAAM,uBAAuB,GAAG,IAAI,OAAO,EAGxC,CAAC;AAEJ;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,OAAgB,EAChB,UAAkB,EAClB,SAA+B;IAE/B,MAAM,gBAAgB,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,uBAAuB,CAAC,GAAG,CAAC,gBAAgB,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC;IAC1E,uBAAuB,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC;IAEtD,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7D,IAAI,cAAc,GAAe,GAAG,EAAE,CAAC,SAAS,CAAC;IACjD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;QAC5C,cAAc,GAAG,OAAO,CAAC;IAC3B,CAAC,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IACxD,MAAM,aAAa,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,aAAa,CAAC,CAAC;IACtC,MAAM,eAAe,CAAC;IAEtB,IAAI,CAAC;QACH,OAAO,MAAM,SAAS,EAAE,CAAC;IAC3B,CAAC;YAAS,CAAC;QACT,cAAc,EAAE,CAAC;QACjB,IAAI,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,aAAa,EAAE,CAAC;YAC7C,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;YAC1B,IAAI,MAAM,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;gBACtB,uBAAuB,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC;YACnD,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {\n type ExecSql,\n resolveCanonicalExecSql,\n} from \"../../../data/sqlite/sqlSchema\";\n\nconst mutationQueuesByExecSql = new WeakMap<\n ExecSql,\n Map<string, Promise<void>>\n>();\n\n/**\n * Serialize byte-store mutations that address the same document blob key.\n *\n * Lock order is blob key, then the connection-wide SQL mutation lock. Callers\n * must not acquire this lock from inside `runSerializedSqlMutation`.\n */\nexport async function runSerializedDocumentBlobMutation<T>(\n execSql: ExecSql,\n storageKey: string,\n operation: () => Promise<T> | T,\n): Promise<T> {\n const canonicalExecSql = resolveCanonicalExecSql(execSql);\n const queues = mutationQueuesByExecSql.get(canonicalExecSql) ?? new Map();\n mutationQueuesByExecSql.set(canonicalExecSql, queues);\n\n const previous = queues.get(storageKey) ?? Promise.resolve();\n let releaseCurrent: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n releaseCurrent = resolve;\n });\n const waitForPrevious = previous.catch(() => undefined);\n const queuedCurrent = waitForPrevious.then(() => current);\n queues.set(storageKey, queuedCurrent);\n await waitForPrevious;\n\n try {\n return await operation();\n } finally {\n releaseCurrent();\n if (queues.get(storageKey) === queuedCurrent) {\n queues.delete(storageKey);\n if (queues.size === 0) {\n mutationQueuesByExecSql.delete(canonicalExecSql);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"blobMutationLock.js","sourceRoot":"","sources":["blobMutationLock.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,qBAAqB,GACtB,MAAM,8BAA8B,CAAC;AAEtC,MAAM,uBAAuB,GAAG,IAAI,OAAO,E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AAC","sourcesContent":["import {\n type ExecSql,\n sqlConnectionIdentity,\n} from \"../../../data/sqlite/sqlExec\";\n\nconst mutationQueuesByExecSql = new WeakMap<\n object,\n Map<string, Promise<void>>\n>();\n\n/**\n * Serialize byte-store mutations that address the same document blob key.\n *\n * Lock order is blob key, then the connection-wide SQL mutation lock. Callers\n * must not acquire this lock from inside `runSerializedSqlMutation`.\n */\nexport async function runSerializedDocumentBlobMutation<T>(\n execSql: ExecSql,\n storageKey: string,\n operation: () => Promise<T> | T,\n): Promise<T> {\n const canonicalExecSql = sqlConnectionIdentity(execSql);\n const queues = mutationQueuesByExecSql.get(canonicalExecSql) ?? new Map();\n mutationQueuesByExecSql.set(canonicalExecSql, queues);\n\n const previous = queues.get(storageKey) ?? Promise.resolve();\n let releaseCurrent: () => void = () => undefined;\n const current = new Promise<void>((resolve) => {\n releaseCurrent = resolve;\n });\n const waitForPrevious = previous.catch(() => undefined);\n const queuedCurrent = waitForPrevious.then(() => current);\n queues.set(storageKey, queuedCurrent);\n await waitForPrevious;\n\n try {\n return await operation();\n } finally {\n releaseCurrent();\n if (queues.get(storageKey) === queuedCurrent) {\n queues.delete(storageKey);\n if (queues.size === 0) {\n mutationQueuesByExecSql.delete(canonicalExecSql);\n }\n }\n }\n}\n"]}
@@ -72,6 +72,8 @@ function isInvalidReadModelCursorFailure(result) {
72
72
  }
73
73
  async function requestReadModelPage(input, state) {
74
74
  const result = await input.apiClient.getOrganizationReadModelResult(input.organizationId, state.requestCursor, { reportErrors: false });
75
+ if (input.stillCurrent?.() === false)
76
+ return { kind: "done", value: undefined };
75
77
  if (result.ok) {
76
78
  return { kind: "response", response: result.data };
77
79
  }
@@ -1 +1 @@
1
- {"version":3,"file":"readModelProjection.js","sourceRoot":"","sources":["readModelProjection.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,mCAAmC,GAEpC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,iCAAiC,EAAE,MAAM,oFAAoF,CAAC;AAKvI,OAA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AAK,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,QAAQ,EAAE,CACd,4DAA4D,CAC7D,CAAC;IACF,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n ORGANIZATION_READ_MODEL_ERROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationReadModelGroupMembers } from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport type {\n ApplyOrganizationReadModelResponseResult,\n OrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\n/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */\ninterface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends ApplyReadModelPageInput {\n readonly apiClient: OrganizationReadModelApi;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection({\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: ApplyOrganizationReadModelResponseResult;\n };\n\nasync function applyResponse(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n return {\n kind: \"applied\",\n result: await repository.applyOrganizationReadModelResponse({\n canCommit: input.stillCurrent,\n currentUserId: input.currentUserId,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await repository.purgeOrganizationReadModelProjection(input.organizationId);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await new OrganizationReadModelRepository(\n input.execSql,\n ).purgeOrganizationReadModelProjection(input.organizationId, {\n onlyRequesterUserId: input.currentUserId,\n });\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (\n !reconciliationIsCurrent(input, state) ||\n input.stillCurrent?.() === false\n )\n return { kind: \"done\", value: null };\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) return preparation;\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelGroupMembers(\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Apply one page as a feed read from `requestedCursor` returns it, with no\n * request, while the projection still holds that cursor. Resolves `undefined`\n * when it is not applied; it is never retried.\n */\nexport async function applyOrganizationReadModelPageAt(\n input: ApplyReadModelPageInput & {\n readonly requestedCursor: string;\n readonly response: OrganizationReadModelResponse;\n },\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n organizationPresentationAccessInput(input),\n \"readModel\",\n );\n const projection = await loadProjection(input);\n if (projection?.cursor !== input.requestedCursor) return undefined;\n const applied = await applyReadModelPage(\n input,\n {\n accessAttempt,\n expectedLocalCursor: projection.cursor,\n preparedDeniedProjection: true,\n projection,\n requestCursor: projection.cursor,\n retriedBindingFailure: true,\n retriedInvalidCursor: true,\n staleRetries: MAX_STALE_RETRIES,\n },\n input.response,\n );\n return applied.kind === \"done\" ? applied.value : undefined;\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
1
+ {"version":3,"file":"readModel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,MAAM,OAAO,GAAG,MAAM,oBAAoB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACzD,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;QACD,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;YAChC,SAAS;QACX,CAAC;QACD,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC5B,OAAO,OAAO,CAAC,KAAK,CAAC;QACvB,CAAC;IACH,CAAC;IAED,KAAK,CAAC,QAAQ,EAAE,CACd,4DAA4D,CAC7D,CAAC;IACF,MAAM,QAAQ,GAAG,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,OAAO,QAAQ,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1D,CAAC","sourcesContent":["import type {\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n ORGANIZATION_READ_MODEL_ERROR_CODES,\n type OrganizationReadModelResponse,\n} from \"@tearleads/validators/response\";\nimport type { OrganizationReadModelGroupMembers } from \"../../../data/persistence/organizations/organizationReadModelMemberLoad\";\nimport { OrganizationReadModelBindingError } from \"../../../data/persistence/organizations/organizationReadModelMembershipPersistence\";\nimport type {\n ApplyOrganizationReadModelResponseResult,\n OrganizationReadModelProjection,\n} from \"../../../data/persistence/organizations/organizationReadModelPersistence\";\nimport { OrganizationReadModelRepository } from \"../../../data/persistence/organizations/organizationReadModelRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { OrganizationDirectoryAndGroups } from \"./index\";\nimport {\n captureOrganizationPresentationAccessAttempt,\n denyOrganizationPresentationAccess,\n isOrganizationPresentationAccessAttemptCurrent,\n isOrganizationPresentationAccessReadable,\n type OrganizationPresentationAccessAttempt,\n type OrganizationPresentationAccessInput,\n restoreOrganizationPresentationAccess,\n runOrganizationPresentationMutation,\n runOrganizationPresentationRead,\n} from \"./organizationPresentationAccessState\";\nimport { isOrganizationPresentationAccessDeniedFailure } from \"./organizationPresentationFailures\";\n\nconst MAX_READ_MODEL_PAGES = 100;\nconst MAX_STALE_RETRIES = 1;\n\ninterface OrganizationReadModelApi {\n getOrganizationReadModelResult(\n organizationId: string,\n cursor?: string,\n options?: RequestResultOptions,\n ): Promise<RequestResult<OrganizationReadModelResponse>>;\n}\n\ninterface OrganizationReadModelProjectionInput {\n readonly currentUserId: string;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n}\n\n/** Applying a page needs no API; `stillCurrent` is rechecked in the write. */\ninterface ApplyReadModelPageInput extends OrganizationReadModelProjectionInput {\n readonly logError?:\n | ((message: string | Error, cause?: unknown) => void)\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ReconcileOrganizationDirectoryAndGroupsInput\n extends ApplyReadModelPageInput {\n readonly apiClient: OrganizationReadModelApi;\n}\n\nfunction toDirectoryAndGroups(\n projection: OrganizationReadModelProjection | null,\n): OrganizationDirectoryAndGroups | null {\n if (!projection?.requester) {\n return null;\n }\n\n return {\n directory: {\n ...projection.directory,\n currentUser: projection.requester,\n },\n // Hydration decides whether a name is unreadable; a stored blank name may\n // only mean the group has not been hydrated yet.\n groups: projection.groups.groups.map((group) => ({\n ...group,\n nameUnreadable: false,\n })),\n memberGroupId: projection.groups.memberGroupId,\n readModelCursor: projection.cursor,\n };\n}\n\nasync function loadProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () => loadRawProjection(input),\n );\n}\n\nfunction loadRawProjection(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationReadModelProjection | null> {\n return new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelProjection(\n input.organizationId,\n input.currentUserId,\n );\n}\n\nfunction organizationPresentationAccessInput(\n input: OrganizationReadModelProjectionInput,\n): OrganizationPresentationAccessInput {\n return {\n execSql: input.execSql,\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n };\n}\n\ninterface ReconciliationState {\n readonly accessAttempt: OrganizationPresentationAccessAttempt;\n expectedLocalCursor: string | null;\n preparedDeniedProjection: boolean;\n projection: OrganizationReadModelProjection | null;\n requestCursor: string | undefined;\n retriedBindingFailure: boolean;\n retriedInvalidCursor: boolean;\n staleRetries: number;\n}\n\ntype ReconciliationStep =\n | { readonly kind: \"continue\" }\n | {\n readonly kind: \"done\";\n readonly value: OrganizationDirectoryAndGroups | null | undefined;\n };\n\ntype PageRequestStep =\n | ReconciliationStep\n | {\n readonly kind: \"response\";\n readonly response: OrganizationReadModelResponse;\n };\n\nfunction localResult(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n outcome: { readonly failed: boolean },\n): ReconciliationStep {\n const accessInput = organizationPresentationAccessInput(input);\n const readable =\n isOrganizationPresentationAccessAttemptCurrent(\n accessInput,\n state.accessAttempt,\n ) && isOrganizationPresentationAccessReadable(accessInput, \"readModel\");\n if (!readable) {\n return { kind: \"done\", value: null };\n }\n // Retained rows are available through the local loader, but are not proof\n // that this pass caught up. Returning them after a failed post-commit read\n // makes mutation callers skip their retry and repaint pre-mutation status.\n if (outcome.failed) {\n return { kind: \"done\", value: undefined };\n }\n return { kind: \"done\", value: toDirectoryAndGroups(state.projection) };\n}\n\nfunction resetRequestCursor(state: ReconciliationState): void {\n state.expectedLocalCursor = state.projection?.cursor ?? null;\n state.requestCursor = state.projection?.cursor ?? undefined;\n}\n\n/** Replays a page that applied stale, up to the retry budget. */\nfunction retryStaleApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): ReconciliationStep {\n if (state.staleRetries >= MAX_STALE_RETRIES) {\n return localResult(input, state, { failed: true });\n }\n state.staleRetries += 1;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n}\n\nfunction isInvalidReadModelCursorFailure(\n result: RequestResult<OrganizationReadModelResponse>,\n): boolean {\n return (\n !result.ok &&\n result.kind === \"http\" &&\n result.status === 400 &&\n result.code === ORGANIZATION_READ_MODEL_ERROR_CODES.cursorInvalid\n );\n}\n\nasync function requestReadModelPage(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n state: ReconciliationState,\n): Promise<PageRequestStep> {\n const result = await input.apiClient.getOrganizationReadModelResult(\n input.organizationId,\n state.requestCursor,\n { reportErrors: false },\n );\n if (input.stillCurrent?.() === false)\n return { kind: \"done\", value: undefined };\n if (result.ok) {\n return { kind: \"response\", response: result.data };\n }\n if (isOrganizationPresentationAccessDeniedFailure(result)) {\n const accessInput = organizationPresentationAccessInput(input);\n denyOrganizationPresentationAccess(accessInput, [\"readModel\", \"usage\"]);\n const repository = new OrganizationReadModelRepository(input.execSql);\n // The durable marker lands before the purge attempt: if the purge fails,\n // an offline restart must still refuse to serve the revoked projection.\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.recordOrganizationPresentationDenials(accessInput, [\n \"readModel\",\n \"usage\",\n ]),\n );\n } catch (error) {\n input.logError?.(\"Failed to record denied organization access\", error);\n }\n try {\n await runOrganizationPresentationMutation(input.execSql, () =>\n repository.purgeOrganizationAccessProjection({\n organizationId: input.organizationId,\n requesterUserId: input.currentUserId,\n }),\n );\n } catch (error) {\n input.logError?.(\"Failed to purge denied organization access\", error);\n }\n return { kind: \"done\", value: null };\n }\n if (\n isInvalidReadModelCursorFailure(result) &&\n state.requestCursor !== undefined &&\n !state.retriedInvalidCursor\n ) {\n state.requestCursor = undefined;\n state.retriedInvalidCursor = true;\n return { kind: \"continue\" };\n }\n\n result.report();\n return localResult(input, state, { failed: true });\n}\n\nfunction responseMatchesRequest(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): boolean {\n if (response.organizationId !== input.organizationId) {\n input.logError?.(\n `Organization read-model response scope does not match ${input.organizationId}`,\n );\n return false;\n }\n if (response.hasMore && response.nextCursor === state.expectedLocalCursor) {\n input.logError?.(\"Organization read-model page did not advance its cursor\");\n return false;\n }\n return true;\n}\n\nfunction reconciliationIsCurrent(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): boolean {\n return isOrganizationPresentationAccessAttemptCurrent(\n organizationPresentationAccessInput(input),\n state.accessAttempt,\n );\n}\n\ntype ApplyResponseStep =\n | ReconciliationStep\n | {\n readonly kind: \"applied\";\n readonly result: ApplyOrganizationReadModelResponseResult;\n };\n\nasync function applyResponse(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ApplyResponseStep> {\n const repository = new OrganizationReadModelRepository(input.execSql);\n try {\n return {\n kind: \"applied\",\n result: await repository.applyOrganizationReadModelResponse({\n canCommit: input.stillCurrent,\n currentUserId: input.currentUserId,\n requestedCursor: state.expectedLocalCursor,\n response,\n }),\n };\n } catch (error) {\n input.logError?.(\"Failed to apply organization read-model response\", error);\n if (\n !(error instanceof OrganizationReadModelBindingError) ||\n state.retriedBindingFailure\n ) {\n return localResult(input, state, { failed: true });\n }\n state.retriedBindingFailure = true;\n await repository.purgeOrganizationReadModelProjection(input.organizationId);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.projection = null;\n resetRequestCursor(state);\n return { kind: \"continue\" };\n }\n}\n\nasync function prepareDeniedProjectionForApply(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n): Promise<ReconciliationStep | null> {\n if (state.preparedDeniedProjection) {\n return null;\n }\n try {\n // The apply that follows replaces the shared rows authoritatively, so\n // only this requester's row is dropped: another local identity sharing\n // the database keeps its access and reads the replacement.\n await new OrganizationReadModelRepository(\n input.execSql,\n ).purgeOrganizationReadModelProjection(input.organizationId, {\n onlyRequesterUserId: input.currentUserId,\n });\n } catch (error) {\n input.logError?.(\"Failed to replace denied organization read model\", error);\n return { kind: \"done\", value: null };\n }\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n state.expectedLocalCursor = null;\n state.preparedDeniedProjection = true;\n state.projection = null;\n return null;\n}\n\n/** The last page settles only if presentation access is still restorable. */\nfunction finalPageStep(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n accessInput: OrganizationPresentationAccessInput,\n): ReconciliationStep {\n return restoreOrganizationPresentationAccess(accessInput, state.accessAttempt)\n ? localResult(input, state, { failed: false })\n : { kind: \"done\", value: null };\n}\n\nasync function applyReadModelPage(\n input: ApplyReadModelPageInput,\n state: ReconciliationState,\n response: OrganizationReadModelResponse,\n): Promise<ReconciliationStep> {\n if (!responseMatchesRequest(input, state, response)) {\n return localResult(input, state, { failed: true });\n }\n\n const accessInput = organizationPresentationAccessInput(input);\n return runOrganizationPresentationMutation(input.execSql, async () => {\n if (\n !reconciliationIsCurrent(input, state) ||\n input.stillCurrent?.() === false\n )\n return { kind: \"done\", value: null };\n const preparation = await prepareDeniedProjectionForApply(input, state);\n if (preparation) return preparation;\n const applied = await applyResponse(input, state, response);\n if (applied.kind !== \"applied\") {\n return applied;\n }\n\n state.projection = await loadRawProjection(input);\n if (!reconciliationIsCurrent(input, state)) {\n return { kind: \"done\", value: null };\n }\n if (applied.result === \"stale\") {\n return retryStaleApply(input, state);\n }\n\n state.expectedLocalCursor = state.projection?.cursor ?? response.nextCursor;\n if (!response.hasMore) {\n return finalPageStep(input, state, accessInput);\n }\n state.requestCursor = response.nextCursor;\n return { kind: \"continue\" };\n });\n}\n\nexport async function loadLocalOrganizationDirectoryAndGroups(\n input: OrganizationReadModelProjectionInput,\n): Promise<OrganizationDirectoryAndGroups | null> {\n return toDirectoryAndGroups(await loadProjection(input));\n}\n\nexport async function loadLocalOrganizationGroupMembers(\n input: OrganizationReadModelProjectionInput & { readonly groupId: string },\n): Promise<OrganizationReadModelGroupMembers | null> {\n return runOrganizationPresentationRead(\n organizationPresentationAccessInput(input),\n \"readModel\",\n () =>\n new OrganizationReadModelRepository(\n input.execSql,\n ).loadOrganizationReadModelGroupMembers(\n input.organizationId,\n input.groupId,\n input.currentUserId,\n ),\n );\n}\n\n/**\n * Apply one page as a feed read from `requestedCursor` returns it, with no\n * request, while the projection still holds that cursor. Resolves `undefined`\n * when it is not applied; it is never retried.\n */\nexport async function applyOrganizationReadModelPageAt(\n input: ApplyReadModelPageInput & {\n readonly requestedCursor: string;\n readonly response: OrganizationReadModelResponse;\n },\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n organizationPresentationAccessInput(input),\n \"readModel\",\n );\n const projection = await loadProjection(input);\n if (projection?.cursor !== input.requestedCursor) return undefined;\n const applied = await applyReadModelPage(\n input,\n {\n accessAttempt,\n expectedLocalCursor: projection.cursor,\n preparedDeniedProjection: true,\n projection,\n requestCursor: projection.cursor,\n retriedBindingFailure: true,\n retriedInvalidCursor: true,\n staleRetries: MAX_STALE_RETRIES,\n },\n input.response,\n );\n return applied.kind === \"done\" ? applied.value : undefined;\n}\n\n/**\n * Resolves the reconciled projection, `null` when the pass completed\n * authoritatively with nothing presentable (including a denial that purged\n * the projection), or `undefined` when the feed failed — even when local\n * rows remain available. A failed pass must not count as caught up.\n */\nexport async function reconcileOrganizationDirectoryAndGroups(\n input: ReconcileOrganizationDirectoryAndGroupsInput,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const accessInput = organizationPresentationAccessInput(input);\n const accessAttempt = captureOrganizationPresentationAccessAttempt(\n accessInput,\n \"readModel\",\n );\n const state: ReconciliationState = {\n accessAttempt,\n expectedLocalCursor: null,\n preparedDeniedProjection: !accessAttempt.startedDenied,\n projection: await loadProjection(input),\n requestCursor: undefined,\n retriedBindingFailure: false,\n retriedInvalidCursor: false,\n staleRetries: 0,\n };\n resetRequestCursor(state);\n\n for (let page = 0; page < MAX_READ_MODEL_PAGES; page += 1) {\n const request = await requestReadModelPage(input, state);\n if (request.kind === \"done\") {\n return request.value;\n }\n if (request.kind === \"continue\") {\n continue;\n }\n const applied = await applyReadModelPage(input, state, request.response);\n if (applied.kind === \"done\") {\n return applied.value;\n }\n }\n\n input.logError?.(\n \"Organization read-model reconciliation exceeded page limit\",\n );\n const retained = localResult(input, state, { failed: true });\n return retained.kind === \"done\" ? retained.value : null;\n}\n"]}
@@ -22,6 +22,8 @@ export async function registerIdentity(input) {
22
22
  signingKeyPair: input.signingKeyPair,
23
23
  userId: newUserId,
24
24
  });
25
+ if (input.isIdentityCurrent?.() === false)
26
+ return null;
25
27
  const response = await input.apiClient.registerUser(newUserId, artifacts.organizationId, input.containerId, input.signingKeyPair.signingPublicKey, input.encapsulationKeyPair.publicKey, artifacts.initialAdminGroup, artifacts.initialMemberGroup, artifacts.initialOrganizationPolicy, artifacts.initialRootContainer, artifacts.rootMetadataDocumentRequest, artifacts.rosterProfileBootstrap.containerRequest, artifacts.rosterProfileBootstrap.profileDocumentRequest, artifacts.organizationMetadataBootstrap.containerRequest, artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest, artifacts.systemContainerBootstraps.map((systemContainer) => systemContainer.containerRequest));
26
28
  if (!response) {
27
29
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"registerIdentity.js","sourceRoot":"","sources":["registerIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAU3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAoE7F,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,KAA4B;IAE5B,KAAK,CAAC,GAAG,EAAE,CAAC,yBAAyB,CAAC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AAC,qBAAqB;QAClD,QAAQ;QACR,aAAa,EAAE,SAAS,CAAC,aAAa;QACtC,oBAAoB,EAAE,SAAS,CAAC,oBAAoB;QACpD,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,sBAAsB,EAAE,SAAS,CAAC,sBAAsB;QACxD,yBAAyB,EAAE,SAAS,CAAC,yBAAyB;KAC/D,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n type EncapsulationKeyPair,\n KeyingVerificationError,\n type SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type {\n ProvisionedDocumentRequest,\n ProvisionedSystemContainerRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { RegistrationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type { LocalUserIdentityCandidate } from \"../../data/trustedUserIdentity\";\nimport { validateUserIdentityKeys } from \"../../data/trustedUserIdentity\";\nimport { buildOrganizationProvisioningArtifacts } from \"./organizationProvisioning\";\nimport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\nexport interface RegistrationApi {\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: ProvisionedDocumentRequest,\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: ProvisionedDocumentRequest | undefined,\n initialOrganizationMetadataContainer: ProvisionedSystemContainerRequest,\n initialOrganizationProfileDocument?: ProvisionedDocumentRequest | undefined,\n initialSystemContainers?: ProvisionedSystemContainerRequest[] | undefined,\n ): Promise<RegistrationResponse | null>;\n}\n\nexport interface RegisterIdentityInput {\n identityTrustDomain: string;\n apiClient: RegistrationApi;\n containerId: string;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n /**\n * Reports whether the identity that started this registration is still\n * current. Forwarded to the bootstrap persist's in-mutex currency check,\n * so an identity replaced while the persist waits for the mutation queue\n * cannot write its bootstrap through a client the replacement owns.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /**\n * Overrides the seeded personal-org profile name; defaults to \"Personal Org\".\n */\n organizationProfileName?: string | undefined;\n pinLocalUserIdentity: (\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ) => Promise<void>;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the personal\n * organization (e.g. a trash bin). See {@link ProvisionedSystemContainerSpec}.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Overrides the seeded self roster-profile nickname; defaults to \"You\". The\n * demo host passes each pane's peer-labeled self name (\"Peer 1 (You)\").\n */\n rosterProfileNickname?: string | undefined;\n signingKeyFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair;\n}\n\nexport async function registerIdentity(\n input: RegisterIdentityInput,\n): Promise<RegistrationResponse | null> {\n input.log?.(\"Registering identity...\");\n await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingKeyFingerprint: input.signingKeyFingerprint,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n },\n });\n\n const newUserId = crypto.randomUUID();\n const artifacts = await buildOrganizationProvisioningArtifacts({\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId: input.containerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: newUserId,\n });\n\n const response = await input.apiClient.registerUser(\n newUserId,\n artifacts.organizationId,\n input.containerId,\n input.signingKeyPair.signingPublicKey,\n input.encapsulationKeyPair.publicKey,\n artifacts.initialAdminGroup,\n artifacts.initialMemberGroup,\n artifacts.initialOrganizationPolicy,\n artifacts.initialRootContainer,\n artifacts.rootMetadataDocumentRequest,\n artifacts.rosterProfileBootstrap.containerRequest,\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n artifacts.organizationMetadataBootstrap.containerRequest,\n artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n );\n if (!response) {\n return null;\n }\n if (response.userId !== newUserId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Registration response user does not match the requested identity\",\n );\n }\n // Pinned only once the server has confirmed this user, and before anything\n // is persisted under it. The trust store binds each signing key to one user,\n // so a pin for an id the server never accepted — a retry after a lost\n // response, or a restored key that is already registered — would later\n // refuse the key's real user at login. Like the persistence below, it is a\n // durable write, so it is skipped once the registering identity has been\n // replaced: the caller discards this result.\n if (input.isIdentityCurrent?.() ?? true) {\n await input.pinLocalUserIdentity(newUserId, {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n }\n\n input.log?.(`Key registered (${response.userId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n commitLsn: response.commitLsn,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n log: input.log,\n logError: input.logError,\n organizationMetadataBootstrap: artifacts.organizationMetadataBootstrap,\n primeProvisionedState: input.primeProvisionedState,\n response,\n rootContainer: artifacts.rootContainer,\n rootMetadataDocument: artifacts.rootMetadataDocument,\n rootMetadataDocumentRequest: artifacts.rootMetadataDocumentRequest,\n rosterProfileBootstrap: artifacts.rosterProfileBootstrap,\n systemContainerBootstraps: artifacts.systemContainerBootstraps,\n });\n\n return response;\n}\n"]}
1
+ {"version":3,"file":"registerIdentity.js","sourceRoot":"","sources":["registerIdentity.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAU3B,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAoE7F,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,KAA4B;IAE5B,KAAK,CAAC,GAAG,EAAE,CAAC,yBAAyB,CAAC,CAAC;IACvC,MAAM,wBAAwB,CAAC;QAC7B,SAAS,EAAE;YACT,sBAAsB,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;YAC5D,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;YAClD,gBAAgB,EAAE,KAAK,CAAC,cAAc,CAAC,gBAAgB;SACxD;KACF,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IACtC,MAAM,SAAS,GAAG,MAAM,sCAAsC,CAAC;QAC7D,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;QAC9C,oB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{\n type EncapsulationKeyPair,\n KeyingVerificationError,\n type SigningKeyPair,\n} from \"@tearleads/crypto\";\nimport type {\n ProvisionedDocumentRequest,\n ProvisionedSystemContainerRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport type { RegistrationResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport type { ExecSqlClientLike } from \"../../data/sqlite/sqlSchema\";\nimport type { LocalUserIdentityCandidate } from \"../../data/trustedUserIdentity\";\nimport { validateUserIdentityKeys } from \"../../data/trustedUserIdentity\";\nimport { buildOrganizationProvisioningArtifacts } from \"./organizationProvisioning\";\nimport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nimport type { ProvisionedStatePrimer } from \"./provisionedStatePrimer\";\nimport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\nexport interface RegistrationApi {\n registerUser(\n userId: string,\n organizationId: string,\n rootContainerId: string,\n signingPublicKey: Uint8Array,\n encapsulationPublicKey: Uint8Array,\n initialAdminGroup: RegistrationRequest[\"initialAdminGroup\"],\n initialMemberGroup: RegistrationRequest[\"initialMemberGroup\"],\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"],\n initialRootContainer: RegistrationRequest[\"initialRootContainer\"],\n initialRootMetadataDocument: ProvisionedDocumentRequest,\n initialRosterProfileContainer: RegistrationRequest[\"initialRosterProfileContainer\"],\n initialRosterProfileDocument: ProvisionedDocumentRequest | undefined,\n initialOrganizationMetadataContainer: ProvisionedSystemContainerRequest,\n initialOrganizationProfileDocument?: ProvisionedDocumentRequest | undefined,\n initialSystemContainers?: ProvisionedSystemContainerRequest[] | undefined,\n ): Promise<RegistrationResponse | null>;\n}\n\nexport interface RegisterIdentityInput {\n identityTrustDomain: string;\n apiClient: RegistrationApi;\n containerId: string;\n dbClient: ExecSqlClientLike;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n /**\n * Reports whether the identity that started this registration is still\n * current. Forwarded to the bootstrap persist's in-mutex currency check,\n * so an identity replaced while the persist waits for the mutation queue\n * cannot write its bootstrap through a client the replacement owns.\n */\n isIdentityCurrent?: (() => boolean) | undefined;\n /** @internal Forwarded to the bootstrap persist; test-only seam. */\n onPersistQueued?: (() => void) | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n log?: ((message: string) => void) | undefined;\n logError?: ((message: string | Error, cause?: unknown) => void) | undefined;\n /**\n * Overrides the seeded personal-org profile name; defaults to \"Personal Org\".\n */\n organizationProfileName?: string | undefined;\n pinLocalUserIdentity: (\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ) => Promise<void>;\n /** Seeds what the committed bootstrap already proves. */\n primeProvisionedState?: ProvisionedStatePrimer | undefined;\n /**\n * App-owned system containers to provision atomically with the personal\n * organization (e.g. a trash bin). See {@link ProvisionedSystemContainerSpec}.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n /**\n * Overrides the seeded self roster-profile nickname; defaults to \"You\". The\n * demo host passes each pane's peer-labeled self name (\"Peer 1 (You)\").\n */\n rosterProfileNickname?: string | undefined;\n signingKeyFingerprint?: string | null | undefined;\n signingKeyPair: SigningKeyPair;\n}\n\nexport async function registerIdentity(\n input: RegisterIdentityInput,\n): Promise<RegistrationResponse | null> {\n input.log?.(\"Registering identity...\");\n await validateUserIdentityKeys({\n candidate: {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingKeyFingerprint: input.signingKeyFingerprint,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n },\n });\n\n const newUserId = crypto.randomUUID();\n const artifacts = await buildOrganizationProvisioningArtifacts({\n identityTrustDomain: input.identityTrustDomain,\n encapsulationKeyPair: input.encapsulationKeyPair,\n organizationProfileName: input.organizationProfileName,\n provisionedSystemContainers: input.provisionedSystemContainers,\n rootContainerId: input.containerId,\n rosterProfileNickname: input.rosterProfileNickname,\n signingKeyPair: input.signingKeyPair,\n userId: newUserId,\n });\n\n if (input.isIdentityCurrent?.() === false) return null;\n const response = await input.apiClient.registerUser(\n newUserId,\n artifacts.organizationId,\n input.containerId,\n input.signingKeyPair.signingPublicKey,\n input.encapsulationKeyPair.publicKey,\n artifacts.initialAdminGroup,\n artifacts.initialMemberGroup,\n artifacts.initialOrganizationPolicy,\n artifacts.initialRootContainer,\n artifacts.rootMetadataDocumentRequest,\n artifacts.rosterProfileBootstrap.containerRequest,\n artifacts.rosterProfileBootstrap.profileDocumentRequest,\n artifacts.organizationMetadataBootstrap.containerRequest,\n artifacts.organizationMetadataBootstrap.organizationProfileDocumentRequest,\n artifacts.systemContainerBootstraps.map(\n (systemContainer) => systemContainer.containerRequest,\n ),\n );\n if (!response) {\n return null;\n }\n if (response.userId !== newUserId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Registration response user does not match the requested identity\",\n );\n }\n // Pinned only once the server has confirmed this user, and before anything\n // is persisted under it. The trust store binds each signing key to one user,\n // so a pin for an id the server never accepted — a retry after a lost\n // response, or a restored key that is already registered — would later\n // refuse the key's real user at login. Like the persistence below, it is a\n // durable write, so it is skipped once the registering identity has been\n // replaced: the caller discards this result.\n if (input.isIdentityCurrent?.() ?? true) {\n await input.pinLocalUserIdentity(newUserId, {\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n }\n\n input.log?.(`Key registered (${response.userId})`);\n await persistOrganizationProvisioningState({\n bootstrap: artifacts.bootstrap,\n canStartDurableMutation: input.isIdentityCurrent,\n commitLsn: response.commitLsn,\n onPersistQueued: input.onPersistQueued,\n containerId: input.containerId,\n dbClient: input.dbClient,\n documentProjectors: input.documentProjectors,\n initialAdminGroup: artifacts.initialAdminGroup,\n initialMemberGroup: artifacts.initialMemberGroup,\n initialOrganizationPolicy: artifacts.initialOrganizationPolicy,\n log: input.log,\n logError: input.logError,\n organizationMetadataBootstrap: artifacts.organizationMetadataBootstrap,\n primeProvisionedState: input.primeProvisionedState,\n response,\n rootContainer: artifacts.rootContainer,\n rootMetadataDocument: artifacts.rootMetadataDocument,\n rootMetadataDocumentRequest: artifacts.rootMetadataDocumentRequest,\n rosterProfileBootstrap: artifacts.rosterProfileBootstrap,\n systemContainerBootstraps: artifacts.systemContainerBootstraps,\n });\n\n return response;\n}\n"]}
@@ -26,6 +26,8 @@ export interface WorkflowRuntimeStateInput {
26
26
  readonly domainScope: DomainScope;
27
27
  readonly events: ReadonlyArray<unknown>;
28
28
  readonly online: boolean;
29
+ /** True while the current socket has acknowledged its container interest. */
30
+ readonly serverEventsConnected?: boolean | undefined;
29
31
  /**
30
32
  * Increments after each acknowledged server-events interest declaration.
31
33
  * Unlike a boolean connection edge, this survives coalesced runtime
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeInput.js","sourceRoot":"","sources":["runtimeInput.ts"],"names":[],"mappings":"","sourcesContent":["import type { EncapsulationKeyPair, SigningKeyPair } from \"@tearleads/crypto\";\nimport type { BlobStore } from \"../../data/blobs/blobContracts\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport type WorkflowRuntimeDatabaseStatus =\n | \"idle\"\n | \"ready\"\n | \"error\"\n | \"terminated\";\n\nexport interface WorkflowRuntimeAuthInput {\n /** Server-backed personal organization; independent of organizationId. */\n readonly defaultOrganizationId?: string | null;\n /** Session root identity, independent of a document/pane target. */\n readonly rootContainerId?: string | null | undefined;\n readonly isAuthenticated: boolean;\n /** Platform-operator flag from the server; the API enforces root access. */\n readonly isRoot?: boolean | undefined;\n readonly organizationId: string | null;\n readonly userId: string | null;\n}\n\nexport interface WorkflowRuntimeCryptoInput {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n readonly signingFingerprint: string | null;\n readonly signingKeyPair: SigningKeyPair | null;\n}\n\nexport interface WorkflowRuntimeStateInput {\n readonly containerId: string | null;\n readonly domainScope: DomainScope;\n readonly events: ReadonlyArray<unknown>;\n readonly online: boolean;\n /**\n * Increments after each acknowledged server-events interest declaration.\n * Unlike a boolean connection edge, this survives coalesced runtime\n * notifications and document stores retained while their host provider is\n * unmounted.\n */\n readonly serverEventsConnectionGeneration?: number | undefined;\n /**\n * The server-events connect attempt whose interest acknowledgement is\n * outstanding. A document opened meanwhile defers its startup probe to the\n * reconnect probe that acknowledgement arms; when the attempt ends without\n * one, the deferred probe runs.\n */\n readonly serverEventsPendingConnectAttempt?: number | undefined;\n /**\n * Per-pane CRDT peer-seed discriminator (e.g. the pane's local identity\n * namespace). Documents in distinct panes must derive distinct Loro peer ids;\n * absent/`null` means single-pane (bare scope). The document runtime factory\n * always populates it; other runtimes and test fixtures may omit it.\n */\n readonly peerScope?: string | null;\n}\n\nexport interface WorkflowRuntimeInfraInput {\n readonly blobStore: BlobStore;\n readonly dbStatus: WorkflowRuntimeDatabaseStatus;\n readonly documentProjectors: DocumentProjectorRegistry;\n readonly execSql: ExecSql;\n}\n\n/**\n * Which half of an organization's sync a caller is about to run: `push` sends\n * local writes, `pull` fetches updates to a document the device already holds.\n */\nexport type RemoteSyncDirection = \"push\" | \"pull\";\n\nexport interface WorkflowRuntimeUtilInput {\n /**\n * Whether the organization's remote sync is held in `direction`, `push`\n * unless given. A billing block holds only pushes; a sync pause the user\n * chose holds both. Held writes stay queued.\n */\n readonly isRemoteSyncBlocked?:\n | ((organizationId: string, direction?: RemoteSyncDirection) => boolean)\n | undefined;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n}\n\nexport interface WorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: WorkflowRuntimeInfraInput;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: WorkflowRuntimeUtilInput;\n}\n"]}
1
+ {"version":3,"file":"runtimeInput.js","sourceRoot":"","sources":["runtimeInput.ts"],"names":[],"mappings":"","sourcesContent":["import type { EncapsulationKeyPair, SigningKeyPair } from \"@tearleads/crypto\";\nimport type { BlobStore } from \"../../data/blobs/blobContracts\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport type WorkflowRuntimeDatabaseStatus =\n | \"idle\"\n | \"ready\"\n | \"error\"\n | \"terminated\";\n\nexport interface WorkflowRuntimeAuthInput {\n /** Server-backed personal organization; independent of organizationId. */\n readonly defaultOrganizationId?: string | null;\n /** Session root identity, independent of a document/pane target. */\n readonly rootContainerId?: string | null | undefined;\n readonly isAuthenticated: boolean;\n /** Platform-operator flag from the server; the API enforces root access. */\n readonly isRoot?: boolean | undefined;\n readonly organizationId: string | null;\n readonly userId: string | null;\n}\n\nexport interface WorkflowRuntimeCryptoInput {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n readonly signingFingerprint: string | null;\n readonly signingKeyPair: SigningKeyPair | null;\n}\n\nexport interface WorkflowRuntimeStateInput {\n readonly containerId: string | null;\n readonly domainScope: DomainScope;\n readonly events: ReadonlyArray<unknown>;\n readonly online: boolean;\n /** True while the current socket has acknowledged its container interest. */\n readonly serverEventsConnected?: boolean | undefined;\n /**\n * Increments after each acknowledged server-events interest declaration.\n * Unlike a boolean connection edge, this survives coalesced runtime\n * notifications and document stores retained while their host provider is\n * unmounted.\n */\n readonly serverEventsConnectionGeneration?: number | undefined;\n /**\n * The server-events connect attempt whose interest acknowledgement is\n * outstanding. A document opened meanwhile defers its startup probe to the\n * reconnect probe that acknowledgement arms; when the attempt ends without\n * one, the deferred probe runs.\n */\n readonly serverEventsPendingConnectAttempt?: number | undefined;\n /**\n * Per-pane CRDT peer-seed discriminator (e.g. the pane's local identity\n * namespace). Documents in distinct panes must derive distinct Loro peer ids;\n * absent/`null` means single-pane (bare scope). The document runtime factory\n * always populates it; other runtimes and test fixtures may omit it.\n */\n readonly peerScope?: string | null;\n}\n\nexport interface WorkflowRuntimeInfraInput {\n readonly blobStore: BlobStore;\n readonly dbStatus: WorkflowRuntimeDatabaseStatus;\n readonly documentProjectors: DocumentProjectorRegistry;\n readonly execSql: ExecSql;\n}\n\n/**\n * Which half of an organization's sync a caller is about to run: `push` sends\n * local writes, `pull` fetches updates to a document the device already holds.\n */\nexport type RemoteSyncDirection = \"push\" | \"pull\";\n\nexport interface WorkflowRuntimeUtilInput {\n /**\n * Whether the organization's remote sync is held in `direction`, `push`\n * unless given. A billing block holds only pushes; a sync pause the user\n * chose holds both. Held writes stay queued.\n */\n readonly isRemoteSyncBlocked?:\n | ((organizationId: string, direction?: RemoteSyncDirection) => boolean)\n | undefined;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n}\n\nexport interface WorkflowRuntimeGroups {\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: WorkflowRuntimeCryptoInput;\n readonly infra: WorkflowRuntimeInfraInput;\n readonly state: WorkflowRuntimeStateInput;\n readonly util: WorkflowRuntimeUtilInput;\n}\n"]}
@@ -1,25 +0,0 @@
1
- import { describeRemoteContainerHydration } from "./remoteHydrationLog.js";
2
- export async function finishRemoteHydration(input) {
3
- if (input.isCurrent?.() === false) {
4
- return;
5
- }
6
- if (input.changedCount > 0) {
7
- input.host.updateSnapshot();
8
- let insertedCount = 0;
9
- for (const containerId of input.seenContainerIds) {
10
- if (!input.containerIdsBeforeHydration.has(containerId)) {
11
- insertedCount++;
12
- }
13
- }
14
- input.state.runtime.util.log(describeRemoteContainerHydration({
15
- changedCount: input.changedCount,
16
- insertedCount,
17
- }));
18
- }
19
- if (input.complete &&
20
- input.isCurrent?.() !== false &&
21
- input.onFullyHydrated) {
22
- await input.onFullyHydrated();
23
- }
24
- }
25
- //# sourceMappingURL=completeHydration.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"completeHydration.js","sourceRoot":"","sources":["completeHydration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAMxE,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAAC,KAS3C;IACC,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QAClC,OAAO;IACT,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;QAC5B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;YACjD,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;gBACxD,aAAa,EAAE,CAAC;YAClB,CAAC;QACH,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAC1B,gCAAgC,CAAC;YAC/B,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,aAAa;SACd,CAAC,CACH,CAAC;IACJ,CAAC;IACD,IACE,KAAK,CAAC,QAAQ;QACd,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;QAC7B,KAAK,CAAC,eAAe,EACrB,CAAC;QACD,MAAM,KAAK,CAAC,eAAe,EAAE,CAAC;IAChC,CAAC;AACH,CAAC","sourcesContent":["import { describeRemoteContainerHydration } from \"./remoteHydrationLog\";\nimport type {\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nexport async function finishRemoteHydration(input: {\n changedCount: number;\n complete: boolean;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n seenContainerIds: ReadonlySet<string>;\n containerIdsBeforeHydration: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n}): Promise<void> {\n if (input.isCurrent?.() === false) {\n return;\n }\n if (input.changedCount > 0) {\n input.host.updateSnapshot();\n let insertedCount = 0;\n for (const containerId of input.seenContainerIds) {\n if (!input.containerIdsBeforeHydration.has(containerId)) {\n insertedCount++;\n }\n }\n input.state.runtime.util.log(\n describeRemoteContainerHydration({\n changedCount: input.changedCount,\n insertedCount,\n }),\n );\n }\n if (\n input.complete &&\n input.isCurrent?.() !== false &&\n input.onFullyHydrated\n ) {\n await input.onFullyHydrated();\n }\n}\n"]}