@tearleads/client-sdk 0.1.62 → 0.1.63

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 (653) hide show
  1. package/client/organizations/currentPrincipalMutations.js +5 -5
  2. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  3. package/client/organizations/organizationDataUsage.js +1 -1
  4. package/client/organizations/organizationDataUsage.js.map +1 -1
  5. package/client/organizations/organizationGroupHistory.js +1 -1
  6. package/client/organizations/organizationGroupHistory.js.map +1 -1
  7. package/client/organizations/organizationGroupNameHydration.js +3 -3
  8. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  9. package/client/organizations/organizationHistory.js +2 -2
  10. package/client/organizations/organizationHistory.js.map +1 -1
  11. package/client/organizations/organizationReadModels.js +1 -1
  12. package/client/organizations/organizationReadModels.js.map +1 -1
  13. package/client/organizations/principalContainerMutations.js +1 -1
  14. package/client/organizations/principalContainerMutations.js.map +1 -1
  15. package/client/organizations/principalMutationRecovery.js.map +1 -1
  16. package/client/organizations/principalMutations.js +5 -5
  17. package/client/organizations/principalMutations.js.map +1 -1
  18. package/client/runtime/principalMutationApi.d.ts +1 -1
  19. package/client/runtime/principalMutationApi.js +2 -2
  20. package/client/runtime/principalMutationApi.js.map +1 -1
  21. package/client/runtime/principalMutationDispatch.js +1 -1
  22. package/client/runtime/principalMutationDispatch.js.map +1 -1
  23. package/client/session/index.js +1 -1
  24. package/client/session/index.js.map +1 -1
  25. package/client/session/sessionOrganizationCreation.js +1 -1
  26. package/client/session/sessionOrganizationCreation.js.map +1 -1
  27. package/client/session/sessionPurgeRecovery.js +2 -2
  28. package/client/session/sessionPurgeRecovery.js.map +1 -1
  29. package/package.json +1 -1
  30. package/stores/documents/documentStore/attachmentHydrationCommit.js +1 -1
  31. package/stores/documents/documentStore/attachmentHydrationCommit.js.map +1 -1
  32. package/stores/documents/documentStore/attachmentUploadAttempt.js +1 -1
  33. package/stores/documents/documentStore/syncRemoteSignals.js +1 -1
  34. package/stores/documents/documentStore/syncRemoteSignals.js.map +1 -1
  35. package/stores/documents/documentStore/syncShared.js +1 -1
  36. package/stores/documents/documentStore/syncShared.js.map +1 -1
  37. package/workflows/blobs/detach.js +1 -1
  38. package/workflows/blobs/detach.js.map +1 -1
  39. package/workflows/blobs/{blobChunkDecryption.js → hydration/blobChunkDecryption.js} +3 -3
  40. package/workflows/blobs/hydration/blobChunkDecryption.js.map +1 -0
  41. package/workflows/blobs/{decrypt.d.ts → hydration/decrypt.d.ts} +2 -2
  42. package/workflows/blobs/{decrypt.js → hydration/decrypt.js} +14 -14
  43. package/workflows/blobs/hydration/decrypt.js.map +1 -0
  44. package/workflows/blobs/{hydrate.d.ts → hydration/hydrate.d.ts} +7 -7
  45. package/workflows/blobs/{hydrate.js → hydration/hydrate.js} +5 -5
  46. package/workflows/blobs/hydration/hydrate.js.map +1 -0
  47. package/workflows/blobs/{hydrationResults.js → hydration/hydrationResults.js} +2 -2
  48. package/workflows/blobs/hydration/hydrationResults.js.map +1 -0
  49. package/workflows/blobs/index.d.ts +3 -3
  50. package/workflows/blobs/index.js +3 -3
  51. package/workflows/blobs/index.js.map +1 -1
  52. package/workflows/blobs/{automaticMultipartUpload.js → upload/automaticMultipartUpload.js} +1 -1
  53. package/workflows/blobs/upload/automaticMultipartUpload.js.map +1 -0
  54. package/workflows/blobs/{upload.d.ts → upload/index.d.ts} +2 -2
  55. package/workflows/blobs/{upload.js → upload/index.js} +14 -14
  56. package/workflows/blobs/upload/index.js.map +1 -0
  57. package/workflows/blobs/{multipartFirstParts.js → upload/multipartFirstParts.js} +4 -4
  58. package/workflows/blobs/upload/multipartFirstParts.js.map +1 -0
  59. package/workflows/blobs/{multipartStageFailures.js → upload/multipartStageFailures.js} +1 -1
  60. package/workflows/blobs/upload/multipartStageFailures.js.map +1 -0
  61. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -0
  62. package/workflows/blobs/{multipartUpload.js → upload/multipartUpload.js} +3 -3
  63. package/workflows/blobs/upload/multipartUpload.js.map +1 -0
  64. package/workflows/blobs/{attachmentBindingVerification.js → verification/attachmentBindingVerification.js} +3 -3
  65. package/workflows/blobs/verification/attachmentBindingVerification.js.map +1 -0
  66. package/workflows/blobs/{attachmentDecryptor.js → verification/attachmentDecryptor.js} +3 -3
  67. package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -0
  68. package/workflows/blobs/{attachmentKeyAuthenticator.js → verification/attachmentKeyAuthenticator.js} +5 -5
  69. package/workflows/blobs/verification/attachmentKeyAuthenticator.js.map +1 -0
  70. package/workflows/blobs/{retainedAttachmentVerification.js → verification/retainedAttachmentVerification.js} +5 -5
  71. package/workflows/blobs/verification/retainedAttachmentVerification.js.map +1 -0
  72. package/workflows/blobs/{verifiedWrapScope.js → verification/verifiedWrapScope.js} +2 -2
  73. package/workflows/blobs/verification/verifiedWrapScope.js.map +1 -0
  74. package/workflows/blobs/{writerProjection.js → verification/writerProjection.js} +3 -3
  75. package/workflows/blobs/verification/writerProjection.js.map +1 -0
  76. package/workflows/container-contents/container-state/purgeTree.js.map +1 -1
  77. package/workflows/container-contents/container-state/purgeTreeContainerDeletion.js.map +1 -1
  78. package/workflows/container-contents/container-state/remote.js +1 -1
  79. package/workflows/container-contents/container-state/remote.js.map +1 -1
  80. package/workflows/container-contents/documentLinks/index.d.ts +1 -1
  81. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  82. package/workflows/container-contents/info/containerInfo.d.ts +1 -1
  83. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +1 -1
  84. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  85. package/workflows/container-contents/remoteHydration/destinationRootReload.js +1 -1
  86. package/workflows/container-contents/remoteHydration/destinationRootReload.js.map +1 -1
  87. package/workflows/container-contents/remoteHydration/verifiedDestination.js +1 -1
  88. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
  89. package/workflows/container-contents/tombstones/documentPurge.d.ts +1 -1
  90. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  91. package/workflows/containers/child/currentShareGrantMutation.js +5 -5
  92. package/workflows/containers/child/currentShareGrantMutation.js.map +1 -1
  93. package/workflows/containers/child/currentSharePrincipalPolicy.js +5 -5
  94. package/workflows/containers/child/currentSharePrincipalPolicy.js.map +1 -1
  95. package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
  96. package/workflows/containers/child/runtimeCurrentGroupShare.js.map +1 -1
  97. package/workflows/containers/child/share.d.ts +1 -1
  98. package/workflows/containers/child/share.js +4 -4
  99. package/workflows/containers/child/share.js.map +1 -1
  100. package/workflows/containers/child/sharePrincipalPolicy.d.ts +1 -1
  101. package/workflows/containers/child/sharePrincipalPolicy.js +2 -2
  102. package/workflows/containers/child/sharePrincipalPolicy.js.map +1 -1
  103. package/workflows/documents/{attachmentPersistence.d.ts → attachments/attachmentPersistence.d.ts} +2 -2
  104. package/workflows/documents/attachments/attachmentPersistence.js.map +1 -0
  105. package/workflows/documents/{blobMutationLock.d.ts → attachments/blobMutationLock.d.ts} +1 -1
  106. package/workflows/documents/{blobMutationLock.js → attachments/blobMutationLock.js} +1 -1
  107. package/workflows/documents/attachments/blobMutationLock.js.map +1 -0
  108. package/workflows/documents/attachments/orphanBlobReclaimState.js.map +1 -0
  109. package/workflows/documents/{orphanBlobReclaims.d.ts → attachments/orphanBlobReclaims.d.ts} +2 -2
  110. package/workflows/documents/{orphanBlobReclaims.js → attachments/orphanBlobReclaims.js} +3 -3
  111. package/workflows/documents/attachments/orphanBlobReclaims.js.map +1 -0
  112. package/workflows/documents/authorAccessFailure.js.map +1 -1
  113. package/workflows/documents/{createAdoption.js → create/createAdoption.js} +5 -5
  114. package/workflows/documents/create/createAdoption.js.map +1 -0
  115. package/workflows/documents/{createProjection.d.ts → create/createProjection.d.ts} +1 -1
  116. package/workflows/documents/{createProjectionFetch.d.ts → create/createProjectionFetch.d.ts} +2 -2
  117. package/workflows/documents/create/createProjectionFetch.js.map +1 -0
  118. package/workflows/documents/{createResponse.js → create/createResponse.js} +5 -5
  119. package/workflows/documents/create/createResponse.js.map +1 -0
  120. package/workflows/documents/{documentCreationPersistence.js → create/documentCreationPersistence.js} +2 -2
  121. package/workflows/documents/create/documentCreationPersistence.js.map +1 -0
  122. package/workflows/documents/{create.d.ts → create/index.d.ts} +4 -4
  123. package/workflows/documents/{create.js → create/index.js} +10 -10
  124. package/workflows/documents/create/index.js.map +1 -0
  125. package/workflows/documents/documentMutationCommit.js +1 -1
  126. package/workflows/documents/documentMutationCommit.js.map +1 -1
  127. package/workflows/documents/index.d.ts +17 -17
  128. package/workflows/documents/index.js +14 -14
  129. package/workflows/documents/index.js.map +1 -1
  130. package/workflows/documents/{linkSet.d.ts → linkSet/index.d.ts} +5 -5
  131. package/workflows/documents/{linkSet.js → linkSet/index.js} +12 -12
  132. package/workflows/documents/linkSet/index.js.map +1 -0
  133. package/workflows/documents/{linkSetAuthority.js → linkSet/linkSetAuthority.js} +6 -6
  134. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -0
  135. package/workflows/documents/{linkSetBlobRewraps.js → linkSet/linkSetBlobRewraps.js} +13 -13
  136. package/workflows/documents/linkSet/linkSetBlobRewraps.js.map +1 -0
  137. package/workflows/documents/{linkSetProjectionSeed.js → linkSet/linkSetProjectionSeed.js} +2 -2
  138. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -0
  139. package/workflows/documents/{linkSetRemote.d.ts → linkSet/linkSetRemote.d.ts} +4 -4
  140. package/workflows/documents/{linkSetRemote.js → linkSet/linkSetRemote.js} +6 -6
  141. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -0
  142. package/workflows/documents/{purge.d.ts → purge/index.d.ts} +5 -5
  143. package/workflows/documents/{purge.js → purge/index.js} +9 -9
  144. package/workflows/documents/purge/index.js.map +1 -0
  145. package/workflows/documents/{persistedDocumentRemoval.d.ts → purge/persistedDocumentRemoval.d.ts} +3 -3
  146. package/workflows/documents/{persistedDocumentRemoval.js → purge/persistedDocumentRemoval.js} +4 -4
  147. package/workflows/documents/purge/persistedDocumentRemoval.js.map +1 -0
  148. package/workflows/documents/{subtreePurgeScope.d.ts → purge/subtreePurgeScope.d.ts} +1 -1
  149. package/workflows/documents/{subtreePurgeScope.js → purge/subtreePurgeScope.js} +2 -2
  150. package/workflows/documents/purge/subtreePurgeScope.js.map +1 -0
  151. package/workflows/documents/rotationBaseline.js +1 -1
  152. package/workflows/documents/rotationBaseline.js.map +1 -1
  153. package/workflows/documents/{sync.d.ts → sync/index.d.ts} +1 -1
  154. package/workflows/documents/{sync.js → sync/index.js} +11 -11
  155. package/workflows/documents/sync/index.js.map +1 -0
  156. package/workflows/documents/{initialSync.js → sync/initialSync.js} +5 -5
  157. package/workflows/documents/sync/initialSync.js.map +1 -0
  158. package/workflows/documents/{readOnlyProjectionFailure.js → sync/readOnlyProjectionFailure.js} +5 -5
  159. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -0
  160. package/workflows/documents/{readOnlySync.d.ts → sync/readOnlySync.d.ts} +9 -9
  161. package/workflows/documents/{readOnlySync.js → sync/readOnlySync.js} +11 -11
  162. package/workflows/documents/sync/readOnlySync.js.map +1 -0
  163. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -0
  164. package/workflows/documents/{syncAttemptPlanning.js → sync/syncAttemptPlanning.js} +9 -9
  165. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -0
  166. package/workflows/documents/{syncAttemptState.d.ts → sync/syncAttemptState.d.ts} +5 -5
  167. package/workflows/documents/sync/syncAttemptState.js.map +1 -0
  168. package/workflows/documents/{syncLane.d.ts → sync/syncLane.d.ts} +3 -3
  169. package/workflows/documents/{syncLane.js → sync/syncLane.js} +2 -2
  170. package/workflows/documents/sync/syncLane.js.map +1 -0
  171. package/workflows/documents/{syncResponseResult.js → sync/syncResponseResult.js} +9 -9
  172. package/workflows/documents/sync/syncResponseResult.js.map +1 -0
  173. package/workflows/documents/{syncSubmittedResult.js → sync/syncSubmittedResult.js} +6 -6
  174. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -0
  175. package/workflows/documents/{syncTrace.js → sync/syncTrace.js} +1 -1
  176. package/workflows/documents/{syncFailures.js → syncFailures/index.js} +5 -5
  177. package/workflows/documents/syncFailures/index.js.map +1 -0
  178. package/workflows/documents/{syncAbandon.js → syncFailures/syncAbandon.js} +1 -1
  179. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -0
  180. package/workflows/documents/{syncFailureClassification.d.ts → syncFailures/syncFailureClassification.d.ts} +2 -2
  181. package/workflows/documents/{syncFailureClassification.js → syncFailures/syncFailureClassification.js} +6 -6
  182. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -0
  183. package/workflows/documents/{syncPolicyRepair.js → syncFailures/syncPolicyRepair.js} +3 -3
  184. package/workflows/documents/syncFailures/syncPolicyRepair.js.map +1 -0
  185. package/workflows/documents/syncFailures/syncRepairAbandon.js.map +1 -0
  186. package/workflows/documents/{syncRepairAccess.js → syncFailures/syncRepairAccess.js} +2 -2
  187. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -0
  188. package/workflows/documents/{syncContentKeys.d.ts → syncPlan/syncContentKeys.d.ts} +4 -4
  189. package/workflows/documents/{syncContentKeys.js → syncPlan/syncContentKeys.js} +8 -8
  190. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -0
  191. package/workflows/documents/{syncPlanIdentity.js → syncPlan/syncPlanIdentity.js} +3 -3
  192. package/workflows/documents/syncPlan/syncPlanIdentity.js.map +1 -0
  193. package/workflows/documents/{syncPlanMaterial.js → syncPlan/syncPlanMaterial.js} +9 -9
  194. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -0
  195. package/workflows/documents/syncPlan/syncPlanProjection.js.map +1 -0
  196. package/workflows/documents/{syncPlanRequestBounds.js → syncPlan/syncPlanRequestBounds.js} +1 -1
  197. package/workflows/documents/syncPlan/syncPlanRequestBounds.js.map +1 -0
  198. package/workflows/documents/{syncAutomaticContainerRekeys.js → syncRekeys/syncAutomaticContainerRekeys.js} +10 -10
  199. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -0
  200. package/workflows/documents/{syncContainerRekeyPreparation.js → syncRekeys/syncContainerRekeyPreparation.js} +11 -11
  201. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js.map +1 -0
  202. package/workflows/documents/{syncContainerRekeyProjection.js → syncRekeys/syncContainerRekeyProjection.js} +2 -2
  203. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -0
  204. package/workflows/documents/{syncContainerRekeys.js → syncRekeys/syncContainerRekeys.js} +3 -3
  205. package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -0
  206. package/workflows/documents/{syncRecoveryRekey.d.ts → syncRekeys/syncRecoveryRekey.d.ts} +4 -4
  207. package/workflows/documents/{syncRecoveryRekey.js → syncRekeys/syncRecoveryRekey.js} +4 -4
  208. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -0
  209. package/workflows/documents/{syncRekeyCommit.js → syncRekeys/syncRekeyCommit.js} +1 -1
  210. package/workflows/organizations/{currentGroupMetadataAuthority.js → groupMetadata/currentGroupMetadataAuthority.js} +5 -5
  211. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -0
  212. package/workflows/organizations/{groupMetadataAccess.d.ts → groupMetadata/groupMetadataAccess.d.ts} +5 -5
  213. package/workflows/organizations/{groupMetadataAccess.js → groupMetadata/groupMetadataAccess.js} +6 -6
  214. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -0
  215. package/workflows/organizations/{groupMetadataBinding.js → groupMetadata/groupMetadataBinding.js} +1 -1
  216. package/workflows/organizations/groupMetadata/groupMetadataBinding.js.map +1 -0
  217. package/workflows/organizations/{groupMetadataContainerAuthority.js → groupMetadata/groupMetadataContainerAuthority.js} +6 -6
  218. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -0
  219. package/workflows/organizations/{groupMetadataErrors.js → groupMetadata/groupMetadataErrors.js} +1 -1
  220. package/workflows/organizations/{groupMetadataRootBinding.js → groupMetadata/groupMetadataRootBinding.js} +3 -3
  221. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js.map +1 -0
  222. package/workflows/organizations/{groupMetadataRuntime.js → groupMetadata/groupMetadataRuntime.js} +4 -4
  223. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -0
  224. package/workflows/organizations/{runtimeGroupMetadataAuthority.js → groupMetadata/runtimeGroupMetadataAuthority.js} +2 -2
  225. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -0
  226. package/workflows/organizations/{currentOrganizationGroupNames.js → groupNames/currentOrganizationGroupNames.js} +8 -8
  227. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -0
  228. package/workflows/organizations/{groupMembershipName.d.ts → groupNames/groupMembershipName.d.ts} +3 -3
  229. package/workflows/organizations/{groupMembershipName.js → groupNames/groupMembershipName.js} +2 -2
  230. package/workflows/organizations/groupNames/groupMembershipName.js.map +1 -0
  231. package/workflows/organizations/{groupNameUniqueness.js → groupNames/groupNameUniqueness.js} +11 -11
  232. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -0
  233. package/workflows/organizations/{organizationGroupNamePolicies.js → groupNames/organizationGroupNamePolicies.js} +5 -5
  234. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -0
  235. package/workflows/organizations/{organizationGroupNames.js → groupNames/organizationGroupNames.js} +1 -1
  236. package/workflows/organizations/groupNames/organizationGroupNames.js.map +1 -0
  237. package/workflows/organizations/{commitCurrentGroupPolicyMutation.js → groupPolicy/commitCurrentGroupPolicyMutation.js} +4 -4
  238. package/workflows/organizations/groupPolicy/commitCurrentGroupPolicyMutation.js.map +1 -0
  239. package/workflows/organizations/{currentGroupPolicyMutationContext.js → groupPolicy/currentGroupPolicyMutationContext.js} +7 -7
  240. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -0
  241. package/workflows/organizations/{currentPolicyMutationAcknowledgement.js → groupPolicy/currentPolicyMutationAcknowledgement.js} +3 -3
  242. package/workflows/organizations/groupPolicy/currentPolicyMutationAcknowledgement.js.map +1 -0
  243. package/workflows/organizations/{groupPolicyMutationAcknowledgement.js → groupPolicy/groupPolicyMutationAcknowledgement.js} +4 -4
  244. package/workflows/organizations/groupPolicy/groupPolicyMutationAcknowledgement.js.map +1 -0
  245. package/workflows/organizations/{groupPolicyMutationContext.d.ts → groupPolicy/groupPolicyMutationContext.d.ts} +8 -8
  246. package/workflows/organizations/{groupPolicyMutationContext.js → groupPolicy/groupPolicyMutationContext.js} +5 -5
  247. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -0
  248. package/workflows/organizations/{groupPolicyMutationEvidence.d.ts → groupPolicy/groupPolicyMutationEvidence.d.ts} +4 -4
  249. package/workflows/organizations/{groupPolicyMutationEvidence.js → groupPolicy/groupPolicyMutationEvidence.js} +3 -3
  250. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -0
  251. package/workflows/organizations/{groupPolicyMutationHead.js → groupPolicy/groupPolicyMutationHead.js} +1 -1
  252. package/workflows/organizations/{groupPolicyRequests.js → groupPolicy/groupPolicyRequests.js} +5 -5
  253. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -0
  254. package/workflows/organizations/{groupPolicyVerification.js → groupPolicy/groupPolicyVerification.js} +5 -5
  255. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -0
  256. package/workflows/organizations/{submitGroupPolicyCommit.d.ts → groupPolicy/submitGroupPolicyCommit.d.ts} +3 -3
  257. package/workflows/organizations/{submitGroupPolicyCommit.js → groupPolicy/submitGroupPolicyCommit.js} +1 -1
  258. package/workflows/organizations/groupPolicy/submitGroupPolicyCommit.js.map +1 -0
  259. package/workflows/organizations/{createCurrentOrganizationGroup.js → groups/createCurrentOrganizationGroup.js} +9 -9
  260. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -0
  261. package/workflows/organizations/{deleteCurrentOrganizationGroup.js → groups/deleteCurrentOrganizationGroup.js} +2 -2
  262. package/workflows/organizations/groups/deleteCurrentOrganizationGroup.js.map +1 -0
  263. package/workflows/organizations/{deleteOrganizationGroup.d.ts → groups/deleteOrganizationGroup.d.ts} +6 -6
  264. package/workflows/organizations/{deleteOrganizationGroup.js → groups/deleteOrganizationGroup.js} +6 -6
  265. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -0
  266. package/workflows/organizations/{groupCreation.d.ts → groups/groupCreation.d.ts} +7 -7
  267. package/workflows/organizations/{groupCreation.js → groups/groupCreation.js} +4 -4
  268. package/workflows/organizations/groups/groupCreation.js.map +1 -0
  269. package/workflows/organizations/{organizationGroupDirectory.js → groups/organizationGroupDirectory.js} +10 -10
  270. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -0
  271. package/workflows/organizations/index.d.ts +13 -13
  272. package/workflows/organizations/index.js +12 -12
  273. package/workflows/organizations/index.js.map +1 -1
  274. package/workflows/organizations/policyHistory/groupPolicyHistoryPage.js.map +1 -0
  275. package/workflows/organizations/{loadPolicyHistoryDetails.js → policyHistory/loadPolicyHistoryDetails.js} +5 -5
  276. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -0
  277. package/workflows/organizations/{organizationPolicyHistoryDetails.js → policyHistory/organizationPolicyHistoryDetails.js} +2 -2
  278. package/workflows/organizations/policyHistory/organizationPolicyHistoryDetails.js.map +1 -0
  279. package/workflows/organizations/{organizationPolicyHistoryVerification.js → policyHistory/organizationPolicyHistoryVerification.js} +2 -2
  280. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -0
  281. package/workflows/organizations/{policyHistoryAccessDenial.js → policyHistory/policyHistoryAccessDenial.js} +3 -3
  282. package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js.map +1 -0
  283. package/workflows/organizations/{policyHistoryCache.js → policyHistory/policyHistoryCache.js} +1 -1
  284. package/workflows/organizations/policyHistory/policyHistoryCache.js.map +1 -0
  285. package/workflows/organizations/{policyHistoryReadModel.d.ts → policyHistory/policyHistoryReadModel.d.ts} +1 -1
  286. package/workflows/organizations/{policyHistoryTypes.d.ts → policyHistory/policyHistoryTypes.d.ts} +1 -1
  287. package/workflows/organizations/{acknowledgedDirectoryBindings.js → principalMutations/acknowledgedDirectoryBindings.js} +2 -2
  288. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js.map +1 -0
  289. package/workflows/organizations/{currentGroupMutationReferences.js → principalMutations/currentGroupMutationReferences.js} +2 -2
  290. package/workflows/organizations/principalMutations/currentGroupMutationReferences.js.map +1 -0
  291. package/workflows/organizations/{currentOrganizationMutationAuthority.js → principalMutations/currentOrganizationMutationAuthority.js} +3 -3
  292. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js.map +1 -0
  293. package/workflows/organizations/{currentOrganizationMutationRetention.js → principalMutations/currentOrganizationMutationRetention.js} +4 -4
  294. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -0
  295. package/workflows/organizations/{currentPrincipalMutationLease.js → principalMutations/currentPrincipalMutationLease.js} +6 -6
  296. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +1 -0
  297. package/workflows/organizations/{principalMutationJournalManagement.d.ts → principalMutations/principalMutationJournalManagement.d.ts} +1 -1
  298. package/workflows/organizations/{principalMutationJournalManagement.js → principalMutations/principalMutationJournalManagement.js} +7 -7
  299. package/workflows/organizations/principalMutations/principalMutationJournalManagement.js.map +1 -0
  300. package/workflows/organizations/{principalMutationJournalSession.d.ts → principalMutations/principalMutationJournalSession.d.ts} +4 -4
  301. package/workflows/organizations/{principalMutationJournalSession.js → principalMutations/principalMutationJournalSession.js} +4 -4
  302. package/workflows/organizations/principalMutations/principalMutationJournalSession.js.map +1 -0
  303. package/workflows/organizations/{principalMutationReceipt.js → principalMutations/principalMutationReceipt.js} +3 -3
  304. package/workflows/organizations/principalMutations/principalMutationReceipt.js.map +1 -0
  305. package/workflows/organizations/{principalOperationReceipt.d.ts → principalMutations/principalOperationReceipt.d.ts} +2 -2
  306. package/workflows/organizations/{principalOperationReceipt.js → principalMutations/principalOperationReceipt.js} +3 -3
  307. package/workflows/organizations/principalMutations/principalOperationReceipt.js.map +1 -0
  308. package/workflows/organizations/principalMutations/retainAcknowledgedPrincipalCurrents.d.ts +6 -0
  309. package/workflows/organizations/{retainAcknowledgedPrincipalCurrents.js → principalMutations/retainAcknowledgedPrincipalCurrents.js} +4 -4
  310. package/workflows/organizations/principalMutations/retainAcknowledgedPrincipalCurrents.js.map +1 -0
  311. package/workflows/organizations/{runtimeCurrentGroupMutation.js → principalMutations/runtimeCurrentGroupMutation.js} +5 -5
  312. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -0
  313. package/workflows/organizations/{runtimeCurrentOrganizationMutation.js → principalMutations/runtimeCurrentOrganizationMutation.js} +2 -2
  314. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -0
  315. package/workflows/organizations/{principalPolicy.d.ts → principalPolicy/index.d.ts} +8 -8
  316. package/workflows/organizations/{principalPolicy.js → principalPolicy/index.js} +9 -9
  317. package/workflows/organizations/principalPolicy/index.js.map +1 -0
  318. package/workflows/organizations/{principalPolicyApi.d.ts → principalPolicy/principalPolicyApi.d.ts} +4 -4
  319. package/workflows/organizations/principalPolicy/principalPolicyApi.js.map +1 -0
  320. package/workflows/organizations/{principalPolicyReceiptArtifacts.js → principalPolicy/principalPolicyReceiptArtifacts.js} +2 -2
  321. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -0
  322. package/workflows/organizations/{principalPolicyRecipients.js → principalPolicy/principalPolicyRecipients.js} +2 -2
  323. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +1 -0
  324. package/workflows/organizations/{principalPolicyRequest.d.ts → principalPolicy/principalPolicyRequest.d.ts} +3 -3
  325. package/workflows/organizations/{principalPolicyRequest.js → principalPolicy/principalPolicyRequest.js} +2 -2
  326. package/workflows/organizations/{createOrganization.d.ts → provisioning/createOrganization.d.ts} +7 -7
  327. package/workflows/organizations/{createOrganization.js → provisioning/createOrganization.js} +3 -3
  328. package/workflows/organizations/provisioning/createOrganization.js.map +1 -0
  329. package/workflows/organizations/{organizationProvisioningAttempt.d.ts → provisioning/organizationProvisioningAttempt.d.ts} +3 -3
  330. package/workflows/organizations/{organizationProvisioningAttempt.js → provisioning/organizationProvisioningAttempt.js} +6 -6
  331. package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -0
  332. package/workflows/organizations/{organizationReplacementVerification.js → provisioning/organizationReplacementVerification.js} +2 -2
  333. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -0
  334. package/workflows/organizations/{dataUsageReadModel.d.ts → readModel/dataUsageReadModel.d.ts} +3 -3
  335. package/workflows/organizations/{dataUsageReadModel.js → readModel/dataUsageReadModel.js} +2 -2
  336. package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -0
  337. package/workflows/organizations/{readModel.d.ts → readModel/index.d.ts} +5 -5
  338. package/workflows/organizations/{readModel.js → readModel/index.js} +2 -2
  339. package/workflows/organizations/readModel/index.js.map +1 -0
  340. package/workflows/organizations/{listLocalOrganizations.d.ts → readModel/listLocalOrganizations.d.ts} +1 -1
  341. package/workflows/organizations/{listLocalOrganizations.js → readModel/listLocalOrganizations.js} +8 -8
  342. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -0
  343. package/workflows/organizations/{localReadModelDetails.d.ts → readModel/localReadModelDetails.d.ts} +3 -3
  344. package/workflows/organizations/{localReadModelDetails.js → readModel/localReadModelDetails.js} +6 -6
  345. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -0
  346. package/workflows/organizations/{organizationPresentationAccessState.js → readModel/organizationPresentationAccessState.js} +1 -1
  347. package/workflows/organizations/readModel/organizationPresentationAccessState.js.map +1 -0
  348. package/workflows/organizations/{organizationPresentationFailures.js → readModel/organizationPresentationFailures.js} +1 -1
  349. package/workflows/organizations/{readModelProjection.d.ts → readModel/readModelProjection.d.ts} +5 -5
  350. package/workflows/organizations/{readModelProjection.js → readModel/readModelProjection.js} +6 -6
  351. package/workflows/organizations/readModel/readModelProjection.js.map +1 -0
  352. package/workflows/organizations/{authoredPrincipalPolicyWarmer.js → rematerialization/authoredPrincipalPolicyWarmer.js} +2 -2
  353. package/workflows/organizations/rematerialization/authoredPrincipalPolicyWarmer.js.map +1 -0
  354. package/workflows/organizations/{precedingPrincipalRematerialization.js → rematerialization/precedingPrincipalRematerialization.js} +1 -1
  355. package/workflows/organizations/rematerialization/precedingPrincipalRematerialization.js.map +1 -0
  356. package/workflows/organizations/{principalContainerRematerialization.js → rematerialization/principalContainerRematerialization.js} +13 -13
  357. package/workflows/organizations/rematerialization/principalContainerRematerialization.js.map +1 -0
  358. package/workflows/organizations/{principalContainerRematerializationPlanning.js → rematerialization/principalContainerRematerializationPlanning.js} +2 -2
  359. package/workflows/organizations/rematerialization/principalContainerRematerializationPlanning.js.map +1 -0
  360. package/workflows/organizations/{principalContainerRematerializationTargets.js → rematerialization/principalContainerRematerializationTargets.js} +3 -3
  361. package/workflows/organizations/rematerialization/principalContainerRematerializationTargets.js.map +1 -0
  362. package/workflows/principals/{acknowledgedPrincipalCurrents.d.ts → acknowledgements/acknowledgedPrincipalCurrents.d.ts} +6 -6
  363. package/workflows/principals/{acknowledgedPrincipalCurrents.js → acknowledgements/acknowledgedPrincipalCurrents.js} +7 -7
  364. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -0
  365. package/workflows/principals/{acknowledgedPrincipalPredecessor.d.ts → acknowledgements/acknowledgedPrincipalPredecessor.d.ts} +10 -10
  366. package/workflows/principals/{acknowledgedPrincipalPredecessor.js → acknowledgements/acknowledgedPrincipalPredecessor.js} +9 -9
  367. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -0
  368. package/workflows/principals/{initialPrincipalCurrentPublication.js → acknowledgements/initialPrincipalCurrentPublication.js} +7 -7
  369. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -0
  370. package/workflows/principals/{principalAcknowledgementChecks.d.ts → acknowledgements/principalAcknowledgementChecks.d.ts} +3 -3
  371. package/workflows/principals/{principalCurrentPublicationSeal.js → acknowledgements/principalCurrentPublicationSeal.js} +3 -3
  372. package/workflows/principals/acknowledgements/principalCurrentPublicationSeal.js.map +1 -0
  373. package/workflows/principals/{reconcileAcknowledgedPrincipalCurrent.js → acknowledgements/reconcileAcknowledgedPrincipalCurrent.js} +6 -6
  374. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
  375. package/workflows/principals/{loadRecoveredPrincipalHistoryPage.d.ts → historyRecovery/loadRecoveredPrincipalHistoryPage.d.ts} +1 -1
  376. package/workflows/principals/{loadRecoveredPrincipalHistoryPage.js → historyRecovery/loadRecoveredPrincipalHistoryPage.js} +7 -7
  377. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -0
  378. package/workflows/principals/{principalHistoryRecoveryAuthority.js → historyRecovery/principalHistoryRecoveryAuthority.js} +2 -2
  379. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js.map +1 -0
  380. package/workflows/principals/{principalHistoryRecoveryPrefix.js → historyRecovery/principalHistoryRecoveryPrefix.js} +5 -5
  381. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -0
  382. package/workflows/principals/{principalHistoryRecoveryReferences.js → historyRecovery/principalHistoryRecoveryReferences.js} +4 -4
  383. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -0
  384. package/workflows/principals/{principalHistoryRecoveryStage.js → historyRecovery/principalHistoryRecoveryStage.js} +4 -4
  385. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -0
  386. package/workflows/principals/{principalHistoryRecoveryTypes.d.ts → historyRecovery/principalHistoryRecoveryTypes.d.ts} +5 -5
  387. package/workflows/principals/{principalHistoryRecoveryTypes.js → historyRecovery/principalHistoryRecoveryTypes.js} +1 -1
  388. package/workflows/principals/historyRecovery/principalHistoryRecoveryTypes.js.map +1 -0
  389. package/workflows/principals/{principalHistoryRecoveryVerification.js → historyRecovery/principalHistoryRecoveryVerification.js} +1 -1
  390. package/workflows/principals/{recoverCurrentOrganizationPolicy.js → historyRecovery/recoverCurrentOrganizationPolicy.js} +4 -4
  391. package/workflows/principals/historyRecovery/recoverCurrentOrganizationPolicy.js.map +1 -0
  392. package/workflows/principals/{recoverPrincipalHistoryPage.js → historyRecovery/recoverPrincipalHistoryPage.js} +2 -2
  393. package/workflows/principals/{recoverPrincipalPolicyHistory.js → historyRecovery/recoverPrincipalPolicyHistory.js} +8 -8
  394. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -0
  395. package/workflows/principals/{recoverScopedPrincipalPolicyHistory.d.ts → historyRecovery/recoverScopedPrincipalPolicyHistory.d.ts} +3 -3
  396. package/workflows/principals/{recoverScopedPrincipalPolicyHistory.js → historyRecovery/recoverScopedPrincipalPolicyHistory.js} +7 -7
  397. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js.map +1 -0
  398. package/workflows/principals/index.d.ts +6 -6
  399. package/workflows/principals/index.js +6 -6
  400. package/workflows/principals/index.js.map +1 -1
  401. package/workflows/principals/{policyCache.d.ts → policyCache/index.d.ts} +5 -5
  402. package/workflows/principals/{policyCache.js → policyCache/index.js} +10 -10
  403. package/workflows/principals/policyCache/index.js.map +1 -0
  404. package/workflows/principals/{principalPolicyCacheAdvance.js → policyCache/principalPolicyCacheAdvance.js} +2 -2
  405. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -0
  406. package/workflows/principals/{principalPolicyCacheValidation.js → policyCache/principalPolicyCacheValidation.js} +3 -3
  407. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -0
  408. package/workflows/principals/{principalPolicyOrganizationScope.js → policyCache/principalPolicyOrganizationScope.js} +7 -7
  409. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -0
  410. package/workflows/principals/{publicPrincipalHistoryAuthority.js → publicHistory/publicPrincipalHistoryAuthority.js} +3 -3
  411. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -0
  412. package/workflows/principals/{publicPrincipalHistoryPage.js → publicHistory/publicPrincipalHistoryPage.js} +6 -6
  413. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -0
  414. package/workflows/principals/{publicPrincipalHistoryProgress.js → publicHistory/publicPrincipalHistoryProgress.js} +8 -8
  415. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -0
  416. package/workflows/principals/{publicPrincipalHistoryTypes.d.ts → publicHistory/publicPrincipalHistoryTypes.d.ts} +7 -7
  417. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -0
  418. package/workflows/principals/{publicProjectionDirectory.js → publicHistory/publicProjectionDirectory.js} +2 -2
  419. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -0
  420. package/workflows/principals/{publicProjectionPrincipal.js → publicHistory/publicProjectionPrincipal.js} +4 -4
  421. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -0
  422. package/workflows/principals/{recoverProjectionPolicyHistory.d.ts → publicHistory/recoverProjectionPolicyHistory.d.ts} +2 -2
  423. package/workflows/principals/{recoverProjectionPolicyHistory.js → publicHistory/recoverProjectionPolicyHistory.js} +3 -3
  424. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js.map +1 -0
  425. package/workflows/principals/{recoverPublicPrincipalHistory.js → publicHistory/recoverPublicPrincipalHistory.js} +7 -7
  426. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -0
  427. package/workflows/principals/{selectPublicPrincipalHistory.js → publicHistory/selectPublicPrincipalHistory.js} +5 -5
  428. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -0
  429. package/workflows/principals/{principalCurrentRecoveryBatch.js → recoveryOperation/principalCurrentRecoveryBatch.js} +2 -2
  430. package/workflows/principals/recoveryOperation/principalCurrentRecoveryBatch.js.map +1 -0
  431. package/workflows/principals/{principalRecoveryDirectory.d.ts → recoveryOperation/principalRecoveryDirectory.d.ts} +3 -3
  432. package/workflows/principals/{principalRecoveryDirectory.js → recoveryOperation/principalRecoveryDirectory.js} +9 -9
  433. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -0
  434. package/workflows/principals/recoveryOperation/principalRecoveryDiscoveryPage.js.map +1 -0
  435. package/workflows/principals/{principalRecoveryLocalPreference.js → recoveryOperation/principalRecoveryLocalPreference.js} +4 -4
  436. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js.map +1 -0
  437. package/workflows/principals/{principalRecoveryMemo.d.ts → recoveryOperation/principalRecoveryMemo.d.ts} +2 -2
  438. package/workflows/principals/{principalRecoveryMemo.js → recoveryOperation/principalRecoveryMemo.js} +4 -4
  439. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js.map +1 -0
  440. package/workflows/principals/{principalRecoveryMemoValidity.js → recoveryOperation/principalRecoveryMemoValidity.js} +2 -2
  441. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -0
  442. package/workflows/principals/{principalRecoveryOutage.js → recoveryOperation/principalRecoveryOutage.js} +5 -5
  443. package/workflows/principals/recoveryOperation/principalRecoveryOutage.js.map +1 -0
  444. package/workflows/principals/runtimePolicyRecovery.js +3 -3
  445. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  446. package/workflows/principals/runtimeProjectionPolicyRecovery.js +3 -3
  447. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  448. package/workflows/registration/organizationProvisioningArtifacts.d.ts +1 -1
  449. package/workflows/registration/provisionedPrincipalHistory.js +1 -1
  450. package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
  451. package/workflows/registration/provisionedProfileDocument.js +1 -1
  452. package/workflows/registration/provisionedProfileDocument.js.map +1 -1
  453. package/workflows/registration/provisioningBootstrapBuilders.js +2 -2
  454. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  455. package/workflows/registration/registerIdentity.js +2 -2
  456. package/workflows/registration/registerIdentity.js.map +1 -1
  457. package/workflows/sync/remoteReset.js +1 -1
  458. package/workflows/sync/remoteReset.js.map +1 -1
  459. package/workflows/blobs/attachmentBindingVerification.js.map +0 -1
  460. package/workflows/blobs/attachmentDecryptor.js.map +0 -1
  461. package/workflows/blobs/attachmentKeyAuthenticator.js.map +0 -1
  462. package/workflows/blobs/automaticMultipartUpload.js.map +0 -1
  463. package/workflows/blobs/blobChunkDecryption.js.map +0 -1
  464. package/workflows/blobs/decrypt.js.map +0 -1
  465. package/workflows/blobs/hydrate.js.map +0 -1
  466. package/workflows/blobs/hydrationResults.js.map +0 -1
  467. package/workflows/blobs/multipartFirstParts.js.map +0 -1
  468. package/workflows/blobs/multipartStageFailures.js.map +0 -1
  469. package/workflows/blobs/multipartStageResolution.js.map +0 -1
  470. package/workflows/blobs/multipartUpload.js.map +0 -1
  471. package/workflows/blobs/retainedAttachmentVerification.js.map +0 -1
  472. package/workflows/blobs/upload.js.map +0 -1
  473. package/workflows/blobs/verifiedWrapScope.js.map +0 -1
  474. package/workflows/blobs/writerProjection.js.map +0 -1
  475. package/workflows/documents/attachmentPersistence.js.map +0 -1
  476. package/workflows/documents/blobMutationLock.js.map +0 -1
  477. package/workflows/documents/create.js.map +0 -1
  478. package/workflows/documents/createAdoption.js.map +0 -1
  479. package/workflows/documents/createProjectionFetch.js.map +0 -1
  480. package/workflows/documents/createResponse.js.map +0 -1
  481. package/workflows/documents/documentCreationPersistence.js.map +0 -1
  482. package/workflows/documents/initialSync.js.map +0 -1
  483. package/workflows/documents/linkSet.js.map +0 -1
  484. package/workflows/documents/linkSetAuthority.js.map +0 -1
  485. package/workflows/documents/linkSetBlobRewraps.js.map +0 -1
  486. package/workflows/documents/linkSetProjectionSeed.js.map +0 -1
  487. package/workflows/documents/linkSetRemote.js.map +0 -1
  488. package/workflows/documents/orphanBlobReclaimState.js.map +0 -1
  489. package/workflows/documents/orphanBlobReclaims.js.map +0 -1
  490. package/workflows/documents/persistedDocumentRemoval.js.map +0 -1
  491. package/workflows/documents/purge.js.map +0 -1
  492. package/workflows/documents/readOnlyProjectionFailure.js.map +0 -1
  493. package/workflows/documents/readOnlySync.js.map +0 -1
  494. package/workflows/documents/reportDocumentSyncQuarantine.js.map +0 -1
  495. package/workflows/documents/subtreePurgeScope.js.map +0 -1
  496. package/workflows/documents/sync.js.map +0 -1
  497. package/workflows/documents/syncAbandon.js.map +0 -1
  498. package/workflows/documents/syncAttemptPlanning.js.map +0 -1
  499. package/workflows/documents/syncAttemptState.js.map +0 -1
  500. package/workflows/documents/syncAutomaticContainerRekeys.js.map +0 -1
  501. package/workflows/documents/syncContainerRekeyPreparation.js.map +0 -1
  502. package/workflows/documents/syncContainerRekeyProjection.js.map +0 -1
  503. package/workflows/documents/syncContainerRekeys.js.map +0 -1
  504. package/workflows/documents/syncContentKeys.js.map +0 -1
  505. package/workflows/documents/syncFailureClassification.js.map +0 -1
  506. package/workflows/documents/syncFailures.js.map +0 -1
  507. package/workflows/documents/syncLane.js.map +0 -1
  508. package/workflows/documents/syncPlanIdentity.js.map +0 -1
  509. package/workflows/documents/syncPlanMaterial.js.map +0 -1
  510. package/workflows/documents/syncPlanProjection.js.map +0 -1
  511. package/workflows/documents/syncPlanRequestBounds.js.map +0 -1
  512. package/workflows/documents/syncPolicyRepair.js.map +0 -1
  513. package/workflows/documents/syncRecoveryRekey.js.map +0 -1
  514. package/workflows/documents/syncRepairAbandon.js.map +0 -1
  515. package/workflows/documents/syncRepairAccess.js.map +0 -1
  516. package/workflows/documents/syncResponseResult.js.map +0 -1
  517. package/workflows/documents/syncSubmittedResult.js.map +0 -1
  518. package/workflows/organizations/acknowledgedDirectoryBindings.js.map +0 -1
  519. package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +0 -1
  520. package/workflows/organizations/commitCurrentGroupPolicyMutation.js.map +0 -1
  521. package/workflows/organizations/createCurrentOrganizationGroup.js.map +0 -1
  522. package/workflows/organizations/createOrganization.js.map +0 -1
  523. package/workflows/organizations/currentGroupMetadataAuthority.js.map +0 -1
  524. package/workflows/organizations/currentGroupMutationReferences.js.map +0 -1
  525. package/workflows/organizations/currentGroupPolicyMutationContext.js.map +0 -1
  526. package/workflows/organizations/currentOrganizationGroupNames.js.map +0 -1
  527. package/workflows/organizations/currentOrganizationMutationAuthority.js.map +0 -1
  528. package/workflows/organizations/currentOrganizationMutationRetention.js.map +0 -1
  529. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +0 -1
  530. package/workflows/organizations/currentPrincipalMutationLease.js.map +0 -1
  531. package/workflows/organizations/dataUsageReadModel.js.map +0 -1
  532. package/workflows/organizations/deleteCurrentOrganizationGroup.js.map +0 -1
  533. package/workflows/organizations/deleteOrganizationGroup.js.map +0 -1
  534. package/workflows/organizations/groupCreation.js.map +0 -1
  535. package/workflows/organizations/groupMembershipName.js.map +0 -1
  536. package/workflows/organizations/groupMetadataAccess.js.map +0 -1
  537. package/workflows/organizations/groupMetadataBinding.js.map +0 -1
  538. package/workflows/organizations/groupMetadataContainerAuthority.js.map +0 -1
  539. package/workflows/organizations/groupMetadataRootBinding.js.map +0 -1
  540. package/workflows/organizations/groupMetadataRuntime.js.map +0 -1
  541. package/workflows/organizations/groupNameUniqueness.js.map +0 -1
  542. package/workflows/organizations/groupPolicyHistoryPage.js.map +0 -1
  543. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +0 -1
  544. package/workflows/organizations/groupPolicyMutationContext.js.map +0 -1
  545. package/workflows/organizations/groupPolicyMutationEvidence.js.map +0 -1
  546. package/workflows/organizations/groupPolicyRequests.js.map +0 -1
  547. package/workflows/organizations/groupPolicyVerification.js.map +0 -1
  548. package/workflows/organizations/listLocalOrganizations.js.map +0 -1
  549. package/workflows/organizations/loadPolicyHistoryDetails.js.map +0 -1
  550. package/workflows/organizations/localReadModelDetails.js.map +0 -1
  551. package/workflows/organizations/organizationGroupDirectory.js.map +0 -1
  552. package/workflows/organizations/organizationGroupNamePolicies.js.map +0 -1
  553. package/workflows/organizations/organizationGroupNames.js.map +0 -1
  554. package/workflows/organizations/organizationPolicyHistoryDetails.js.map +0 -1
  555. package/workflows/organizations/organizationPolicyHistoryVerification.js.map +0 -1
  556. package/workflows/organizations/organizationPresentationAccessState.js.map +0 -1
  557. package/workflows/organizations/organizationProvisioningAttempt.js.map +0 -1
  558. package/workflows/organizations/organizationReplacementVerification.js.map +0 -1
  559. package/workflows/organizations/policyHistoryAccessDenial.js.map +0 -1
  560. package/workflows/organizations/policyHistoryCache.js.map +0 -1
  561. package/workflows/organizations/precedingPrincipalRematerialization.js.map +0 -1
  562. package/workflows/organizations/principalContainerRematerialization.js.map +0 -1
  563. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +0 -1
  564. package/workflows/organizations/principalContainerRematerializationTargets.js.map +0 -1
  565. package/workflows/organizations/principalMutationJournalManagement.js.map +0 -1
  566. package/workflows/organizations/principalMutationJournalSession.js.map +0 -1
  567. package/workflows/organizations/principalMutationReceipt.js.map +0 -1
  568. package/workflows/organizations/principalOperationReceipt.js.map +0 -1
  569. package/workflows/organizations/principalPolicy.js.map +0 -1
  570. package/workflows/organizations/principalPolicyApi.js.map +0 -1
  571. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +0 -1
  572. package/workflows/organizations/principalPolicyRecipients.js.map +0 -1
  573. package/workflows/organizations/readModel.js.map +0 -1
  574. package/workflows/organizations/readModelProjection.js.map +0 -1
  575. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +0 -6
  576. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +0 -1
  577. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +0 -1
  578. package/workflows/organizations/runtimeCurrentOrganizationMutation.js.map +0 -1
  579. package/workflows/organizations/runtimeGroupMetadataAuthority.js.map +0 -1
  580. package/workflows/organizations/submitGroupPolicyCommit.js.map +0 -1
  581. package/workflows/principals/acknowledgedPrincipalCurrents.js.map +0 -1
  582. package/workflows/principals/acknowledgedPrincipalPredecessor.js.map +0 -1
  583. package/workflows/principals/initialPrincipalCurrentPublication.js.map +0 -1
  584. package/workflows/principals/loadRecoveredPrincipalHistoryPage.js.map +0 -1
  585. package/workflows/principals/policyCache.js.map +0 -1
  586. package/workflows/principals/principalCurrentPublicationSeal.js.map +0 -1
  587. package/workflows/principals/principalCurrentRecoveryBatch.js.map +0 -1
  588. package/workflows/principals/principalHistoryRecoveryAuthority.js.map +0 -1
  589. package/workflows/principals/principalHistoryRecoveryPrefix.js.map +0 -1
  590. package/workflows/principals/principalHistoryRecoveryReferences.js.map +0 -1
  591. package/workflows/principals/principalHistoryRecoveryStage.js.map +0 -1
  592. package/workflows/principals/principalHistoryRecoveryTypes.js.map +0 -1
  593. package/workflows/principals/principalPolicyCacheAdvance.js.map +0 -1
  594. package/workflows/principals/principalPolicyCacheValidation.js.map +0 -1
  595. package/workflows/principals/principalPolicyOrganizationScope.js.map +0 -1
  596. package/workflows/principals/principalRecoveryDirectory.js.map +0 -1
  597. package/workflows/principals/principalRecoveryDiscoveryPage.js.map +0 -1
  598. package/workflows/principals/principalRecoveryLocalPreference.js.map +0 -1
  599. package/workflows/principals/principalRecoveryMemo.js.map +0 -1
  600. package/workflows/principals/principalRecoveryMemoValidity.js.map +0 -1
  601. package/workflows/principals/principalRecoveryOutage.js.map +0 -1
  602. package/workflows/principals/publicPrincipalHistoryAuthority.js.map +0 -1
  603. package/workflows/principals/publicPrincipalHistoryPage.js.map +0 -1
  604. package/workflows/principals/publicPrincipalHistoryProgress.js.map +0 -1
  605. package/workflows/principals/publicPrincipalHistoryTypes.js.map +0 -1
  606. package/workflows/principals/publicProjectionDirectory.js.map +0 -1
  607. package/workflows/principals/publicProjectionPrincipal.js.map +0 -1
  608. package/workflows/principals/reconcileAcknowledgedPrincipalCurrent.js.map +0 -1
  609. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +0 -1
  610. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +0 -1
  611. package/workflows/principals/recoverProjectionPolicyHistory.js.map +0 -1
  612. package/workflows/principals/recoverPublicPrincipalHistory.js.map +0 -1
  613. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +0 -1
  614. package/workflows/principals/selectPublicPrincipalHistory.js.map +0 -1
  615. /package/workflows/blobs/{readAttachmentTransfer.js → hydration/readAttachmentTransfer.js} +0 -0
  616. /package/workflows/blobs/{readAttachmentTransfer.js.map → hydration/readAttachmentTransfer.js.map} +0 -0
  617. /package/workflows/blobs/{multipartStageResolution.js → upload/multipartStageResolution.js} +0 -0
  618. /package/workflows/documents/{attachmentPersistence.js → attachments/attachmentPersistence.js} +0 -0
  619. /package/workflows/documents/{orphanBlobReclaimState.js → attachments/orphanBlobReclaimState.js} +0 -0
  620. /package/workflows/documents/{createProjection.js → create/createProjection.js} +0 -0
  621. /package/workflows/documents/{createProjection.js.map → create/createProjection.js.map} +0 -0
  622. /package/workflows/documents/{createProjectionFetch.js → create/createProjectionFetch.js} +0 -0
  623. /package/workflows/documents/{reportDocumentSyncQuarantine.js → sync/reportDocumentSyncQuarantine.js} +0 -0
  624. /package/workflows/documents/{syncAttemptState.js → sync/syncAttemptState.js} +0 -0
  625. /package/workflows/documents/{syncTrace.d.ts → sync/syncTrace.d.ts} +0 -0
  626. /package/workflows/documents/{syncTrace.js.map → sync/syncTrace.js.map} +0 -0
  627. /package/workflows/documents/{syncFailureClearance.d.ts → syncFailures/syncFailureClearance.d.ts} +0 -0
  628. /package/workflows/documents/{syncFailureClearance.js → syncFailures/syncFailureClearance.js} +0 -0
  629. /package/workflows/documents/{syncFailureClearance.js.map → syncFailures/syncFailureClearance.js.map} +0 -0
  630. /package/workflows/documents/{syncRepairAbandon.js → syncFailures/syncRepairAbandon.js} +0 -0
  631. /package/workflows/documents/{syncPlanProjection.js → syncPlan/syncPlanProjection.js} +0 -0
  632. /package/workflows/documents/{syncRekeyCommit.js.map → syncRekeys/syncRekeyCommit.js.map} +0 -0
  633. /package/workflows/organizations/{groupMetadataErrors.js.map → groupMetadata/groupMetadataErrors.js.map} +0 -0
  634. /package/workflows/organizations/{groupMutationAuthorization.js → groupPolicy/groupMutationAuthorization.js} +0 -0
  635. /package/workflows/organizations/{groupMutationAuthorization.js.map → groupPolicy/groupMutationAuthorization.js.map} +0 -0
  636. /package/workflows/organizations/{groupPolicyMutationHead.js.map → groupPolicy/groupPolicyMutationHead.js.map} +0 -0
  637. /package/workflows/organizations/{groupPolicyHistoryPage.js → policyHistory/groupPolicyHistoryPage.js} +0 -0
  638. /package/workflows/organizations/{policyHistoryReadModel.js → policyHistory/policyHistoryReadModel.js} +0 -0
  639. /package/workflows/organizations/{policyHistoryReadModel.js.map → policyHistory/policyHistoryReadModel.js.map} +0 -0
  640. /package/workflows/organizations/{policyHistoryTypes.js → policyHistory/policyHistoryTypes.js} +0 -0
  641. /package/workflows/organizations/{policyHistoryTypes.js.map → policyHistory/policyHistoryTypes.js.map} +0 -0
  642. /package/workflows/organizations/{principalPolicyApi.js → principalPolicy/principalPolicyApi.js} +0 -0
  643. /package/workflows/organizations/{principalPolicyRequest.js.map → principalPolicy/principalPolicyRequest.js.map} +0 -0
  644. /package/workflows/organizations/{organizationPresentationFailures.js.map → readModel/organizationPresentationFailures.js.map} +0 -0
  645. /package/workflows/principals/{principalAcknowledgementChecks.js → acknowledgements/principalAcknowledgementChecks.js} +0 -0
  646. /package/workflows/principals/{principalAcknowledgementChecks.js.map → acknowledgements/principalAcknowledgementChecks.js.map} +0 -0
  647. /package/workflows/principals/{principalHistoryRecoveryVerification.js.map → historyRecovery/principalHistoryRecoveryVerification.js.map} +0 -0
  648. /package/workflows/principals/{recoverPrincipalHistoryPage.js.map → historyRecovery/recoverPrincipalHistoryPage.js.map} +0 -0
  649. /package/workflows/principals/{recoverPrincipalPolicyHistory.d.ts → historyRecovery/recoverPrincipalPolicyHistory.d.ts} +0 -0
  650. /package/workflows/principals/{principalPolicyCacheScope.js → policyCache/principalPolicyCacheScope.js} +0 -0
  651. /package/workflows/principals/{principalPolicyCacheScope.js.map → policyCache/principalPolicyCacheScope.js.map} +0 -0
  652. /package/workflows/principals/{publicPrincipalHistoryTypes.js → publicHistory/publicPrincipalHistoryTypes.js} +0 -0
  653. /package/workflows/principals/{principalRecoveryDiscoveryPage.js → recoveryOperation/principalRecoveryDiscoveryPage.js} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAEL,gCAAgC,GACjC,MAAM,+DAA+D,CAAC;AAiBvE,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,wBAAwB,CACjC,cAAc,EACd,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,UAAU;YACb,OAAO,GAAG,CAAC,mCAAmC,CAC5C,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,C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AI,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutationJournalSession\";\nimport type { PrincipalMutationResponse } from \"../../workflows/organizations/principalOperationReceipt\";\n\nimport type { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport type JournaledPrincipalMutationMethods = Pick<\n ApiClient,\n | \"commitOrganizationGroupPolicy\"\n | \"commitOrganizationGroupPolicyResult\"\n | \"createOrganizationGroup\"\n | \"createOrganizationGroupResult\"\n | \"deleteOrganizationGroup\"\n | \"deleteOrganizationGroupResult\"\n | \"putPrincipalPolicy\"\n | \"putPrincipalPolicyResult\"\n>;\n\n/** Dispatch the authenticated operation, with no application planning callback. */\nexport function dispatchAuthoredPrincipalMutation(\n api: ApiClient,\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n options: RequestResultOptions = {},\n): Promise<RequestResult<PrincipalMutationResponse>> {\n switch (mutation.kind) {\n case \"organization\":\n return api.putPrincipalPolicyResult(\n \"organization\",\n organizationId,\n mutation.request,\n options,\n );\n case \"group-create\":\n return api.createOrganizationGroupResult(\n organizationId,\n mutation.request,\n options,\n );\n case \"group-delete\":\n return api.deleteOrganizationGroupResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n case \"compound\":\n return api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n default:\n return unsupportedMutation(mutation);\n }\n}\n\nfunction unsupportedMutation(_mutation: never): never {\n throw new Error(\"Unsupported principal mutation operation\");\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: (\n organizationId: string,\n ) => Omit<PrincipalMutationJournalContext, \"submit\">,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n async function submit<T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<T>> {\n const result = await submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n submit: (saved) =>\n dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n api,\n organizationId,\n saved,\n dispatchOptions,\n ),\n ),\n });\n if (!result.ok) return result;\n // The session already verified this operation before clearing its row.\n // This check narrows the union for each existing public API signature.\n if (!validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n return { ok: true, data: result.data };\n }\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"compound\", groupId, request },\n isCommitOrganizationGroupPolicyResponse,\n options,\n );\n const create: ApiClient[\"createOrganizationGroupResult\"] = (\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-create\", groupId: request.groupId, request },\n isCreateOrganizationGroupResponse,\n options,\n );\n const remove: ApiClient[\"deleteOrganizationGroupResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-delete\", groupId, request },\n isDeleteOrganizationGroupResponse,\n options,\n );\n const put: ApiClient[\"putPrincipalPolicyResult\"] = (\n _type,\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"organization\", groupId: null, request },\n isPrincipalPolicyMutationResponse,\n options,\n );\n return {\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) =>\n nullable(await commit(...args)),\n createOrganizationGroupResult: create,\n createOrganizationGroup: async (...args) => nullable(await create(...args)),\n deleteOrganizationGroupResult: remove,\n deleteOrganizationGroup: async (...args) => nullable(await remove(...args)),\n putPrincipalPolicyResult: put,\n putPrincipalPolicy: async (...args) => nullable(await put(...args)),\n };\n}\n\nfunction nullable<T>(result: RequestResult<T>): T | null {\n return result.ok ? result.data : null;\n}\n"]}
1
+ {"version":3,"file":"principalMutationDispatch.js","sourceRoot":"","sources":["principalMutationDispatch.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAEL,gCAAgC,GACjC,MAAM,kFAAkF,CAAC;AAiB1F,mFAAmF;AACnF,MAAM,UAAU,iCAAiC,CAC/C,GAAc,EACd,cAAsB,EACtB,QAAmC,EACnC,UAAgC,EAAE;IAElC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,wBAAwB,CACjC,cAAc,EACd,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,cAAc;YACjB,OAAO,GAAG,CAAC,6BAA6B,CACtC,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ,KAAK,UAAU;YACb,OAAO,GAAG,CAAC,mCAAmC,CAC5C,cAAc,EACd,QAAQ,CAAC,OAAO,EAChB,QAAQ,CAAC,OAAO,EAChB,OAAO,CACR,CAAC;QACJ;YACE,OAAO,mBAAmB,CAAC,QAAQ,CAAC,CAAC;IACzC,CAAC;AACH,CAAC;AAED,SAAS,mBAAmB,CAAC,SAAgB;IAC3C,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;AAC9D,CAAC;AAED,MAAM,UAAU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IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,OAAO,EAAE,EAC1C,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,MAAM,GAAG,GAA0C,CACjD,KAAK,EACL,cAAc,EACd,OAAO,EACP,OAAO,EACP,EAAE,CACF,MAAM,CACJ,cAAc,EACd,EAAE,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAChD,iCAAiC,EACjC,OAAO,CACR,CAAC;IACJ,OAAO;QACL,mCAAmC,EAAE,MAAM;QAC3C,6BAA6B,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAC/C,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QACjC,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,6BAA6B,EAAE,MAAM;QACrC,uBAAuB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3E,wBAAwB,EAAE,GAAG;QAC7B,kBAAkB,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAI,MAAwB;IAC3C,OAAO,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AACxC,CAAC","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n RequestResultOptions,\n} from \"@tearleads/api-client\";\nimport {\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport {\n type PrincipalMutationJournalContext,\n submitJournaledPrincipalMutation,\n} from \"../../workflows/organizations/principalMutations/principalMutationJournalSession\";\nimport type { PrincipalMutationResponse } from \"../../workflows/organizations/principalMutations/principalOperationReceipt\";\n\nimport type { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport type JournaledPrincipalMutationMethods = Pick<\n ApiClient,\n | \"commitOrganizationGroupPolicy\"\n | \"commitOrganizationGroupPolicyResult\"\n | \"createOrganizationGroup\"\n | \"createOrganizationGroupResult\"\n | \"deleteOrganizationGroup\"\n | \"deleteOrganizationGroupResult\"\n | \"putPrincipalPolicy\"\n | \"putPrincipalPolicyResult\"\n>;\n\n/** Dispatch the authenticated operation, with no application planning callback. */\nexport function dispatchAuthoredPrincipalMutation(\n api: ApiClient,\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n options: RequestResultOptions = {},\n): Promise<RequestResult<PrincipalMutationResponse>> {\n switch (mutation.kind) {\n case \"organization\":\n return api.putPrincipalPolicyResult(\n \"organization\",\n organizationId,\n mutation.request,\n options,\n );\n case \"group-create\":\n return api.createOrganizationGroupResult(\n organizationId,\n mutation.request,\n options,\n );\n case \"group-delete\":\n return api.deleteOrganizationGroupResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n case \"compound\":\n return api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n options,\n );\n default:\n return unsupportedMutation(mutation);\n }\n}\n\nfunction unsupportedMutation(_mutation: never): never {\n throw new Error(\"Unsupported principal mutation operation\");\n}\n\nexport function createJournaledPrincipalMutations(\n api: ApiClient,\n context: (\n organizationId: string,\n ) => Omit<PrincipalMutationJournalContext, \"submit\">,\n dispatch: ReturnType<typeof createPrincipalMutationDispatcher>,\n): JournaledPrincipalMutationMethods {\n async function submit<T extends PrincipalMutationResponse>(\n organizationId: string,\n mutation: AuthoredPrincipalMutation,\n validator: (value: unknown) => value is T,\n options: RequestResultOptions = {},\n ): Promise<RequestResult<T>> {\n const result = await submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n submit: (saved) =>\n dispatch(options, (dispatchOptions) =>\n dispatchAuthoredPrincipalMutation(\n api,\n organizationId,\n saved,\n dispatchOptions,\n ),\n ),\n });\n if (!result.ok) return result;\n // The session already verified this operation before clearing its row.\n // This check narrows the union for each existing public API signature.\n if (!validator(result.data))\n throw new Error(\"Unexpected principal receipt operation\");\n return { ok: true, data: result.data };\n }\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"compound\", groupId, request },\n isCommitOrganizationGroupPolicyResponse,\n options,\n );\n const create: ApiClient[\"createOrganizationGroupResult\"] = (\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-create\", groupId: request.groupId, request },\n isCreateOrganizationGroupResponse,\n options,\n );\n const remove: ApiClient[\"deleteOrganizationGroupResult\"] = (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"group-delete\", groupId, request },\n isDeleteOrganizationGroupResponse,\n options,\n );\n const put: ApiClient[\"putPrincipalPolicyResult\"] = (\n _type,\n organizationId,\n request,\n options,\n ) =>\n submit(\n organizationId,\n { kind: \"organization\", groupId: null, request },\n isPrincipalPolicyMutationResponse,\n options,\n );\n return {\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) =>\n nullable(await commit(...args)),\n createOrganizationGroupResult: create,\n createOrganizationGroup: async (...args) => nullable(await create(...args)),\n deleteOrganizationGroupResult: remove,\n deleteOrganizationGroup: async (...args) => nullable(await remove(...args)),\n putPrincipalPolicyResult: put,\n putPrincipalPolicy: async (...args) => nullable(await put(...args)),\n };\n}\n\nfunction nullable<T>(result: RequestResult<T>): T | null {\n return result.ok ? result.data : null;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { removeNativeSubscriptionRestoreProvisioningAttempt } from "../../workflows/organizations/createOrganization.js";
1
+ import { removeNativeSubscriptionRestoreProvisioningAttempt } from "../../workflows/organizations/provisioning/createOrganization.js";
2
2
  import { bootstrapRootContainer, registerIdentity as registerIdentityWorkflow, } from "../../workflows/registration/index.js";
3
3
  import { createListenerSet } from "../runtime/listenerSet.js";
4
4
  import { emptySessionSnapshot, mergeSessionContext, sessionSnapshotsEqual, } from "./sessionContext.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kDAAkD,EAAE,MAAM,kDAAkD,CAAC;AACtH,OAAO,EACL,sBAAsB,EACtB,gBAAgB,IAAI,wBAAwB,GAC7C,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,oBAAoB,EACpB,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,EACjC,4BAA4B,EAC5B,8BAA8B,GAC/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,wBAAwB,CAAC;AAgBhC,MAAM,UAAU,aAAa,CAAC,YAAiC;IAC7D,OAAO,IAAI,cAAc,CAAC,YAAY,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,cAAc;IAOW;IANZ,uBAAuB,GACtC,IAAI,8BAA8B,EAAE,CAAC;IACtB,SAAS,GA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,CAAC;IAED,iBAAiB,CAAC,cAA6B;QAC7C,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,CAAC,CAAC;IAC9D,CAAC;IAED,cAAc,CAAC,OAAgB;QAC7B,IAAI,IAAI,CAAC,gBAAgB,KAAK,OAAO,EAAE,CAAC;YACtC,OAAO;QACT,CAAC;QACD,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;QAChC,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;IAED,SAAS,CAAC,MAAqB;QAC7B,IAAI,CAAC,WAAW,CACd,mBAAmB,CACjB,IAAI,CAAC,aAAa,EAClB,EAAE,MAAM,EAAE,EACV,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,kBAAkB,CACvD,CACF,CAAC;IACJ,CAAC;IAED,SAAS,GAAG,CAAC,QAAyB,EAAgB,EAAE,CACtD,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAE7B,WAAW,CAAC,IAAqB;QACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC;QACpC,IAAI,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;YAC1C,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACrD,CAAC;QAED,IAAI,qBAAqB,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC;YAC1C,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import { removeNativeSubscriptionRestoreProvisioningAttempt } from \"../../workflows/organizations/createOrganization\";\nimport {\n bootstrapRootContainer,\n registerIdentity as registerIdentityWorkflow,\n} from \"../../workflows/registration\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport { createListenerSet } from \"../runtime/listenerSet\";\nimport {\n emptySessionSnapshot,\n mergeSessionContext,\n sessionSnapshotsEqual,\n} from \"./sessionContext\";\nimport {\n registrationKeyAlreadyBound,\n requireRegistrationIdentityPinner,\n requireUserIdentityAvailable,\n SessionIdentityAcknowledgments,\n} from \"./sessionIdentityTrust\";\nimport { userSessionsFromResponse } from \"./sessionListing\";\nimport { refuseSessionLogin } from \"./sessionLoginRefusal\";\nimport { createSessionOrganization } from \"./sessionOrganizationCreation\";\nimport {\n clearSessionRemoteSyncState,\n recoverPurgedSessionOrganization,\n} from \"./sessionPurgeRecovery\";\nimport {\n acknowledgedSessionRoot,\n commitSessionRootAcknowledgment,\n} from \"./sessionRootAuthority\";\nimport type {\n CreateOrganizationOptions,\n RegisterIdentityOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionDependencies,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./sessionTypes\";\n\nexport function createSession(dependencies: SessionDependencies): Session {\n return new SessionService(dependencies);\n}\n\nclass SessionService implements Session {\n private readonly identityAcknowledgments =\n new SessionIdentityAcknowledgments();\n private readonly listeners = createListenerSet();\n private syncEnabledValue = true;\n private snapshotValue = emptySessionSnapshot();\n\n constructor(private readonly dependencies: SessionDependencies) {}\n\n get authToken(): string | null {\n return this.snapshotValue.authToken;\n }\n\n get containerId(): string | null {\n return this.snapshotValue.containerId;\n }\n\n get defaultOrganizationId(): string | null {\n return this.snapshotValue.defaultOrganizationId;\n }\n\n get isAuthenticated(): boolean {\n return this.snapshotValue.isAuthenticated;\n }\n\n get isRoot(): boolean {\n return this.snapshotValue.isRoot;\n }\n\n get organizationId(): string | null {\n return this.snapshotValue.organizationId;\n }\n\n get snapshot(): SessionSnapshot {\n return this.snapshotValue;\n }\n\n get syncEnabled(): boolean {\n return this.syncEnabledValue;\n }\n\n get userId(): string | null {\n return this.snapshotValue.userId;\n }\n\n get userIdAcknowledged(): boolean {\n return this.identityAcknowledgments.isAcknowledged(\n this.snapshotValue.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n }\n\n async bootstrapLocalRootContainer(): Promise<{\n containerId: string;\n created: boolean;\n }> {\n // Recovery can request local bootstrap after login. Preserve the root\n // acknowledged by that session instead of replacing it with a local id.\n const acknowledgedRoot = acknowledgedSessionRoot(\n this,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n if (this.isAuthenticated && acknowledgedRoot) {\n return { containerId: acknowledgedRoot, created: false };\n }\n const result = await bootstrapRootContainer(\n this.dependencies.database.requireExecSql(\"bootstrapLocalRootContainer\"),\n );\n this.setContainerId(result.containerId);\n if (result.created) {\n this.dependencies.log(\"Root container created\");\n }\n return result;\n }\n\n async listSessions(): Promise<UserSession[]> {\n return userSessionsFromResponse(await this.dependencies.api.listSessions());\n }\n\n async clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult> {\n return clearSessionRemoteSyncState(this.dependencies, this, organizationId);\n }\n\n async destroySession(sessionId: string): Promise<boolean> {\n const response = await this.dependencies.api.destroySession(sessionId);\n return response?.message === \"ok\";\n }\n\n async login(challengeHex?: string | undefined): Promise<boolean> {\n const signingKeyPair =\n this.dependencies.identity.requireSigningKeyPair(\"login\");\n const fingerprint =\n (await this.dependencies.identity.refreshSigningFingerprint()) ?? null;\n\n if (!fingerprint) {\n return false;\n }\n // A refusal below clears the session it is evidence against; a session\n // another login committed meanwhile is not that session and stays.\n const snapshotAtStart = this.snapshotValue;\n const identitySnapshot = this.dependencies.identity.snapshot;\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n return false;\n }\n if (identitySnapshot.signingKeyPair !== signingKeyPair) {\n return false;\n }\n const pinLocalUserIdentity = requireUserIdentityAvailable(\n this.dependencies.onUserIdentityAvailable,\n \"Login\",\n );\n\n this.dependencies.log(\n challengeHex ? \"Authenticating with challenge...\" : \"Authenticating...\",\n );\n const authentication = challengeHex\n ? await this.dependencies.api.authenticateWithChallenge(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n challengeHex,\n )\n : await this.dependencies.api.authenticate(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n );\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) {\n return false;\n }\n\n if (!authentication) {\n this.logout();\n this.dependencies.log(\"Authentication failed\");\n return false;\n }\n\n try {\n this.identityAcknowledgments.assertMatches(\n authentication.userId,\n fingerprint,\n );\n await pinLocalUserIdentity(authentication.userId, {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: fingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n });\n if (this.dependencies.identity.snapshot !== identitySnapshot)\n return false;\n this.identityAcknowledgments.remember(authentication.userId, fingerprint);\n } catch (error) {\n return refuseSessionLogin(error, authentication.userId, {\n clear: () => this.logout(),\n report: this.dependencies.reportSecurityIncident,\n });\n }\n // A changed root for this identity+org is refused before the token is\n // usable. Decision and commit are one synchronous step against the live\n // snapshot (no await in between); the refusal clears the prior session in\n // that same step and then reports its own incident.\n await commitSessionRootAcknowledgment({\n context: {\n authToken: authentication.token,\n defaultOrganizationId: authentication.organizationId,\n isAuthenticated: true,\n isRoot: authentication.isRoot,\n organizationId: authentication.organizationId,\n userId: authentication.userId,\n },\n onRefused: () => {\n if (this.snapshotValue === snapshotAtStart) this.logout();\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: authentication,\n session: this,\n signingFingerprint: fingerprint,\n });\n this.dependencies.log(\"Authentication successful\");\n return true;\n }\n\n logout(): void {\n this.setContext({ authToken: null, isAuthenticated: false, isRoot: false });\n }\n\n async logoutRemote(): Promise<boolean> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n try {\n if (!this.authToken) {\n return true;\n }\n\n const response = await this.dependencies.api.logout();\n return response?.message === \"ok\";\n } finally {\n if (this.dependencies.identity.snapshot === identitySnapshot) {\n this.logout();\n }\n }\n }\n\n async registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null> {\n const containerId = this.containerId;\n if (!containerId) {\n this.dependencies.log(\n \"Registration skipped: container id is unavailable\",\n );\n return null;\n }\n\n const identitySnapshot = this.dependencies.identity.snapshot;\n const signingKeyPair = identitySnapshot.signingKeyPair;\n if (!signingKeyPair) {\n this.dependencies.log(\"Registration skipped: signing key is unavailable\");\n return null;\n }\n\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n this.dependencies.log(\n \"Registration skipped: encapsulation key is unavailable\",\n );\n return null;\n }\n\n const dbClient = this.dependencies.database.client;\n if (!dbClient) {\n this.dependencies.log(\n \"Registration skipped: database client is unavailable\",\n );\n return null;\n }\n const pinLocalUserIdentity = requireRegistrationIdentityPinner({\n identity: this.dependencies.identity,\n identitySnapshot,\n onUserIdentityAvailable: this.dependencies.onUserIdentityAvailable,\n });\n const keyBound = await registrationKeyAlreadyBound(\n this.dependencies,\n identitySnapshot.signingFingerprint,\n );\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (keyBound) return keyBound;\n\n let response: Awaited<ReturnType<typeof registerIdentityWorkflow>>;\n try {\n response = await registerIdentityWorkflow({\n apiClient: this.dependencies.api,\n containerId,\n dbClient,\n documentProjectors: this.dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n this.dependencies.identity.snapshot === identitySnapshot,\n log: this.dependencies.log,\n logError: this.dependencies.logError,\n organizationProfileName: options?.organizationProfileName,\n pinLocalUserIdentity,\n primePrincipalHistory:\n this.dependencies.primeProvisionedPrincipalHistory,\n provisionedSystemContainers:\n this.dependencies.provisionedSystemContainers,\n rosterProfileNickname: options?.rosterProfileNickname,\n signingKeyFingerprint: identitySnapshot.signingFingerprint,\n signingKeyPair,\n });\n } catch (error: unknown) {\n this.dependencies.logError(\"Identity registration failed\", error);\n throw error;\n }\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n this.dependencies.log(\"Registration failed\");\n return null;\n }\n\n // The workflow pinned `response.userId` once the server confirmed it,\n // under the same currency check as above.\n await commitSessionRootAcknowledgment({\n context: {\n containerId: response.rootContainerId,\n defaultOrganizationId: response.organizationId,\n organizationId: response.organizationId,\n userId: response.userId,\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: response,\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n\n return {\n challenge: response.challenge,\n containerId: response.rootContainerId,\n organizationId: response.organizationId,\n userId: response.userId,\n };\n }\n\n async createOrganization(\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n nativeSubscriptionRestore?: boolean,\n ): Promise<SessionCreateOrganizationResult | null> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n const userId = this.userId;\n const response = await createSessionOrganization(this.dependencies, {\n nativeSubscriptionRestore,\n options,\n replacesOrganizationId,\n userId,\n });\n if (\n !response ||\n !userId ||\n this.userId !== userId ||\n this.dependencies.identity.snapshot !== identitySnapshot\n )\n return null;\n await commitSessionRootAcknowledgment({\n reporter: this.dependencies.reportSecurityIncident,\n root: {\n userId,\n organizationId: response.organizationId,\n rootContainerId: response.containerId,\n },\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n return response;\n }\n\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null> {\n return this.createOrganization(options, undefined, true);\n }\n\n async completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean> {\n const userId = this.userId;\n const dbClient = this.dependencies.database.client;\n const identitySnapshot = this.dependencies.identity.snapshot;\n if (!userId || !dbClient) return false;\n return removeNativeSubscriptionRestoreProvisioningAttempt({\n canCommit: () =>\n this.userId === userId &&\n this.dependencies.identity.snapshot === identitySnapshot,\n dbClient,\n organizationId,\n userId,\n });\n }\n\n async recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null> {\n return recoverPurgedSessionOrganization(\n this.dependencies,\n this,\n organizationId,\n options,\n );\n }\n\n setAuthToken(authToken: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, authToken });\n }\n\n setContainerId(containerId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, containerId });\n }\n\n setContext(context: SessionContext): void {\n const wasAcknowledged = this.userIdAcknowledged;\n this.identityAcknowledgments.remember(\n context.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n const previous = this.snapshotValue;\n this.setSnapshot(\n mergeSessionContext(\n previous,\n context,\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n // Acknowledging an already-held userId changes `userIdAcknowledged` without\n // changing the snapshot; persistence subscribers must still observe it.\n if (\n this.snapshotValue === previous &&\n wasAcknowledged !== this.userIdAcknowledged\n ) {\n this.listeners.notify();\n }\n }\n\n setOrganizationId(organizationId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, organizationId });\n }\n\n setSyncEnabled(enabled: boolean): void {\n if (this.syncEnabledValue === enabled) {\n return;\n }\n this.syncEnabledValue = enabled;\n this.listeners.notify();\n }\n\n setUserId(userId: string | null): void {\n this.setSnapshot(\n mergeSessionContext(\n this.snapshotValue,\n { userId },\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n }\n\n subscribe = (listener: SessionListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: SessionSnapshot): void {\n const previous = this.snapshotValue;\n if (previous.authToken !== next.authToken) {\n this.dependencies.api.setAuthToken(next.authToken);\n }\n\n if (sessionSnapshotsEqual(previous, next)) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kDAAkD,EAAE,MAAM,+DAA+D,CAAC;AACnI,OAAO,E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,MAAM,EAAE,EACV,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC,kBAAkB,CACvD,CACF,CAAC;IACJ,CAAC;IAED,SAAS,GAAG,CAAC,QAAyB,EAAgB,EAAE,CACtD,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAE7B,WAAW,CAAC,IAAqB;QACvC,MAAM,QAAQ,GAAG,IAAI,CAAC,aAAa,CAAC;QACpC,IAAI,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,EAAE,CAAC;YAC1C,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACrD,CAAC;QAED,IAAI,qBAAqB,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC;YAC1C,OAAO;QACT,CAAC;QAED,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;IAC1B,CAAC;CACF","sourcesContent":["import { removeNativeSubscriptionRestoreProvisioningAttempt } from \"../../workflows/organizations/provisioning/createOrganization\";\nimport {\n bootstrapRootContainer,\n registerIdentity as registerIdentityWorkflow,\n} from \"../../workflows/registration\";\nimport type { ClearRemoteSyncStateResult } from \"../../workflows/sync\";\nimport { createListenerSet } from \"../runtime/listenerSet\";\nimport {\n emptySessionSnapshot,\n mergeSessionContext,\n sessionSnapshotsEqual,\n} from \"./sessionContext\";\nimport {\n registrationKeyAlreadyBound,\n requireRegistrationIdentityPinner,\n requireUserIdentityAvailable,\n SessionIdentityAcknowledgments,\n} from \"./sessionIdentityTrust\";\nimport { userSessionsFromResponse } from \"./sessionListing\";\nimport { refuseSessionLogin } from \"./sessionLoginRefusal\";\nimport { createSessionOrganization } from \"./sessionOrganizationCreation\";\nimport {\n clearSessionRemoteSyncState,\n recoverPurgedSessionOrganization,\n} from \"./sessionPurgeRecovery\";\nimport {\n acknowledgedSessionRoot,\n commitSessionRootAcknowledgment,\n} from \"./sessionRootAuthority\";\nimport type {\n CreateOrganizationOptions,\n RegisterIdentityOptions,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionDependencies,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n UserSession,\n} from \"./sessionTypes\";\n\nexport function createSession(dependencies: SessionDependencies): Session {\n return new SessionService(dependencies);\n}\n\nclass SessionService implements Session {\n private readonly identityAcknowledgments =\n new SessionIdentityAcknowledgments();\n private readonly listeners = createListenerSet();\n private syncEnabledValue = true;\n private snapshotValue = emptySessionSnapshot();\n\n constructor(private readonly dependencies: SessionDependencies) {}\n\n get authToken(): string | null {\n return this.snapshotValue.authToken;\n }\n\n get containerId(): string | null {\n return this.snapshotValue.containerId;\n }\n\n get defaultOrganizationId(): string | null {\n return this.snapshotValue.defaultOrganizationId;\n }\n\n get isAuthenticated(): boolean {\n return this.snapshotValue.isAuthenticated;\n }\n\n get isRoot(): boolean {\n return this.snapshotValue.isRoot;\n }\n\n get organizationId(): string | null {\n return this.snapshotValue.organizationId;\n }\n\n get snapshot(): SessionSnapshot {\n return this.snapshotValue;\n }\n\n get syncEnabled(): boolean {\n return this.syncEnabledValue;\n }\n\n get userId(): string | null {\n return this.snapshotValue.userId;\n }\n\n get userIdAcknowledged(): boolean {\n return this.identityAcknowledgments.isAcknowledged(\n this.snapshotValue.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n }\n\n async bootstrapLocalRootContainer(): Promise<{\n containerId: string;\n created: boolean;\n }> {\n // Recovery can request local bootstrap after login. Preserve the root\n // acknowledged by that session instead of replacing it with a local id.\n const acknowledgedRoot = acknowledgedSessionRoot(\n this,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n if (this.isAuthenticated && acknowledgedRoot) {\n return { containerId: acknowledgedRoot, created: false };\n }\n const result = await bootstrapRootContainer(\n this.dependencies.database.requireExecSql(\"bootstrapLocalRootContainer\"),\n );\n this.setContainerId(result.containerId);\n if (result.created) {\n this.dependencies.log(\"Root container created\");\n }\n return result;\n }\n\n async listSessions(): Promise<UserSession[]> {\n return userSessionsFromResponse(await this.dependencies.api.listSessions());\n }\n\n async clearRemoteSyncState(\n organizationId: string,\n ): Promise<ClearRemoteSyncStateResult> {\n return clearSessionRemoteSyncState(this.dependencies, this, organizationId);\n }\n\n async destroySession(sessionId: string): Promise<boolean> {\n const response = await this.dependencies.api.destroySession(sessionId);\n return response?.message === \"ok\";\n }\n\n async login(challengeHex?: string | undefined): Promise<boolean> {\n const signingKeyPair =\n this.dependencies.identity.requireSigningKeyPair(\"login\");\n const fingerprint =\n (await this.dependencies.identity.refreshSigningFingerprint()) ?? null;\n\n if (!fingerprint) {\n return false;\n }\n // A refusal below clears the session it is evidence against; a session\n // another login committed meanwhile is not that session and stays.\n const snapshotAtStart = this.snapshotValue;\n const identitySnapshot = this.dependencies.identity.snapshot;\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n return false;\n }\n if (identitySnapshot.signingKeyPair !== signingKeyPair) {\n return false;\n }\n const pinLocalUserIdentity = requireUserIdentityAvailable(\n this.dependencies.onUserIdentityAvailable,\n \"Login\",\n );\n\n this.dependencies.log(\n challengeHex ? \"Authenticating with challenge...\" : \"Authenticating...\",\n );\n const authentication = challengeHex\n ? await this.dependencies.api.authenticateWithChallenge(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n challengeHex,\n )\n : await this.dependencies.api.authenticate(\n fingerprint,\n signingKeyPair.signingPrivateKey,\n );\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) {\n return false;\n }\n\n if (!authentication) {\n this.logout();\n this.dependencies.log(\"Authentication failed\");\n return false;\n }\n\n try {\n this.identityAcknowledgments.assertMatches(\n authentication.userId,\n fingerprint,\n );\n await pinLocalUserIdentity(authentication.userId, {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: fingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n });\n if (this.dependencies.identity.snapshot !== identitySnapshot)\n return false;\n this.identityAcknowledgments.remember(authentication.userId, fingerprint);\n } catch (error) {\n return refuseSessionLogin(error, authentication.userId, {\n clear: () => this.logout(),\n report: this.dependencies.reportSecurityIncident,\n });\n }\n // A changed root for this identity+org is refused before the token is\n // usable. Decision and commit are one synchronous step against the live\n // snapshot (no await in between); the refusal clears the prior session in\n // that same step and then reports its own incident.\n await commitSessionRootAcknowledgment({\n context: {\n authToken: authentication.token,\n defaultOrganizationId: authentication.organizationId,\n isAuthenticated: true,\n isRoot: authentication.isRoot,\n organizationId: authentication.organizationId,\n userId: authentication.userId,\n },\n onRefused: () => {\n if (this.snapshotValue === snapshotAtStart) this.logout();\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: authentication,\n session: this,\n signingFingerprint: fingerprint,\n });\n this.dependencies.log(\"Authentication successful\");\n return true;\n }\n\n logout(): void {\n this.setContext({ authToken: null, isAuthenticated: false, isRoot: false });\n }\n\n async logoutRemote(): Promise<boolean> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n try {\n if (!this.authToken) {\n return true;\n }\n\n const response = await this.dependencies.api.logout();\n return response?.message === \"ok\";\n } finally {\n if (this.dependencies.identity.snapshot === identitySnapshot) {\n this.logout();\n }\n }\n }\n\n async registerIdentity(\n options?: RegisterIdentityOptions,\n ): Promise<SessionRegistrationResult | SessionRegistrationRefusal | null> {\n const containerId = this.containerId;\n if (!containerId) {\n this.dependencies.log(\n \"Registration skipped: container id is unavailable\",\n );\n return null;\n }\n\n const identitySnapshot = this.dependencies.identity.snapshot;\n const signingKeyPair = identitySnapshot.signingKeyPair;\n if (!signingKeyPair) {\n this.dependencies.log(\"Registration skipped: signing key is unavailable\");\n return null;\n }\n\n const encapsulationKeyPair = identitySnapshot.encapsulationKeyPair;\n if (!encapsulationKeyPair) {\n this.dependencies.log(\n \"Registration skipped: encapsulation key is unavailable\",\n );\n return null;\n }\n\n const dbClient = this.dependencies.database.client;\n if (!dbClient) {\n this.dependencies.log(\n \"Registration skipped: database client is unavailable\",\n );\n return null;\n }\n const pinLocalUserIdentity = requireRegistrationIdentityPinner({\n identity: this.dependencies.identity,\n identitySnapshot,\n onUserIdentityAvailable: this.dependencies.onUserIdentityAvailable,\n });\n const keyBound = await registrationKeyAlreadyBound(\n this.dependencies,\n identitySnapshot.signingFingerprint,\n );\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (keyBound) return keyBound;\n\n let response: Awaited<ReturnType<typeof registerIdentityWorkflow>>;\n try {\n response = await registerIdentityWorkflow({\n apiClient: this.dependencies.api,\n containerId,\n dbClient,\n documentProjectors: this.dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n this.dependencies.identity.snapshot === identitySnapshot,\n log: this.dependencies.log,\n logError: this.dependencies.logError,\n organizationProfileName: options?.organizationProfileName,\n pinLocalUserIdentity,\n primePrincipalHistory:\n this.dependencies.primeProvisionedPrincipalHistory,\n provisionedSystemContainers:\n this.dependencies.provisionedSystemContainers,\n rosterProfileNickname: options?.rosterProfileNickname,\n signingKeyFingerprint: identitySnapshot.signingFingerprint,\n signingKeyPair,\n });\n } catch (error: unknown) {\n this.dependencies.logError(\"Identity registration failed\", error);\n throw error;\n }\n\n if (this.dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n this.dependencies.log(\"Registration failed\");\n return null;\n }\n\n // The workflow pinned `response.userId` once the server confirmed it,\n // under the same currency check as above.\n await commitSessionRootAcknowledgment({\n context: {\n containerId: response.rootContainerId,\n defaultOrganizationId: response.organizationId,\n organizationId: response.organizationId,\n userId: response.userId,\n },\n reporter: this.dependencies.reportSecurityIncident,\n root: response,\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n\n return {\n challenge: response.challenge,\n containerId: response.rootContainerId,\n organizationId: response.organizationId,\n userId: response.userId,\n };\n }\n\n async createOrganization(\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n nativeSubscriptionRestore?: boolean,\n ): Promise<SessionCreateOrganizationResult | null> {\n const identitySnapshot = this.dependencies.identity.snapshot;\n const userId = this.userId;\n const response = await createSessionOrganization(this.dependencies, {\n nativeSubscriptionRestore,\n options,\n replacesOrganizationId,\n userId,\n });\n if (\n !response ||\n !userId ||\n this.userId !== userId ||\n this.dependencies.identity.snapshot !== identitySnapshot\n )\n return null;\n await commitSessionRootAcknowledgment({\n reporter: this.dependencies.reportSecurityIncident,\n root: {\n userId,\n organizationId: response.organizationId,\n rootContainerId: response.containerId,\n },\n session: this,\n signingFingerprint: identitySnapshot.signingFingerprint,\n });\n return response;\n }\n\n prepareNativeSubscriptionRestoreOrganization(\n options?: CreateOrganizationOptions,\n ): Promise<SessionCreateOrganizationResult | null> {\n return this.createOrganization(options, undefined, true);\n }\n\n async completeNativeSubscriptionRestoreOrganization(\n organizationId: string,\n ): Promise<boolean> {\n const userId = this.userId;\n const dbClient = this.dependencies.database.client;\n const identitySnapshot = this.dependencies.identity.snapshot;\n if (!userId || !dbClient) return false;\n return removeNativeSubscriptionRestoreProvisioningAttempt({\n canCommit: () =>\n this.userId === userId &&\n this.dependencies.identity.snapshot === identitySnapshot,\n dbClient,\n organizationId,\n userId,\n });\n }\n\n async recoverPurgedOrganization(\n organizationId: string,\n options?: CreateOrganizationOptions,\n ): Promise<SessionRecoverOrganizationResult | null> {\n return recoverPurgedSessionOrganization(\n this.dependencies,\n this,\n organizationId,\n options,\n );\n }\n\n setAuthToken(authToken: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, authToken });\n }\n\n setContainerId(containerId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, containerId });\n }\n\n setContext(context: SessionContext): void {\n const wasAcknowledged = this.userIdAcknowledged;\n this.identityAcknowledgments.remember(\n context.userId,\n this.dependencies.identity.snapshot.signingFingerprint,\n );\n const previous = this.snapshotValue;\n this.setSnapshot(\n mergeSessionContext(\n previous,\n context,\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n // Acknowledging an already-held userId changes `userIdAcknowledged` without\n // changing the snapshot; persistence subscribers must still observe it.\n if (\n this.snapshotValue === previous &&\n wasAcknowledged !== this.userIdAcknowledged\n ) {\n this.listeners.notify();\n }\n }\n\n setOrganizationId(organizationId: string | null): void {\n this.setSnapshot({ ...this.snapshotValue, organizationId });\n }\n\n setSyncEnabled(enabled: boolean): void {\n if (this.syncEnabledValue === enabled) {\n return;\n }\n this.syncEnabledValue = enabled;\n this.listeners.notify();\n }\n\n setUserId(userId: string | null): void {\n this.setSnapshot(\n mergeSessionContext(\n this.snapshotValue,\n { userId },\n this.dependencies.identity.snapshot.signingFingerprint,\n ),\n );\n }\n\n subscribe = (listener: SessionListener): (() => void) =>\n this.listeners.subscribe(listener);\n\n private setSnapshot(next: SessionSnapshot): void {\n const previous = this.snapshotValue;\n if (previous.authToken !== next.authToken) {\n this.dependencies.api.setAuthToken(next.authToken);\n }\n\n if (sessionSnapshotsEqual(previous, next)) {\n return;\n }\n\n this.snapshotValue = next;\n this.listeners.notify();\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { createOrganization as createOrganizationWorkflow } from "../../workflows/organizations/createOrganization.js";
1
+ import { createOrganization as createOrganizationWorkflow } from "../../workflows/organizations/provisioning/createOrganization.js";
2
2
  export async function createSessionOrganization(dependencies, input) {
3
3
  if (!input.userId) {
4
4
  dependencies.log("Create organization skipped: user id is unavailable");
@@ -1 +1 @@
1
- {"version":3,"file":"sessionOrganizationCreation.js","sourceRoot":"","sources":["sessionOrganizationCreation.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,IAAI,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAyBpH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,YAAqD,EACrD,KAKC;IAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;QAClB,YAAY,CAAC,GAAG,CAAC,qDAAqD,CAAC,CAAC;QACxE,OAAO,IAAI,C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8B,EAAE,KAAK,CAAC,CAAC;QAC7D,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,YAAY,CAAC,QAAQ,CAAC,QAAQ,KAAK,gBAAgB;QAAE,OAAO,IAAI,CAAC;IACrE,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,YAAY,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;QACjD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oEAAoE;IACpE,OAAO;QACL,WAAW,EAAE,QAAQ,CAAC,eAAe;QACrC,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createOrganization as createOrganizationWorkflow } from \"../../workflows/organizations/createOrganization\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport type {\n CreateOrganizationOptions,\n SessionCreateOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionOrganizationCreationDependencies {\n readonly api: ApiClient;\n readonly database: Database;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly identity: Identity;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly primeProvisionedPrincipalHistory?:\n | ProvisionedPrincipalHistoryPrimer\n | undefined;\n readonly provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport async function createSessionOrganization(\n dependencies: SessionOrganizationCreationDependencies,\n input: {\n readonly nativeSubscriptionRestore?: boolean | undefined;\n readonly options?: CreateOrganizationOptions | undefined;\n readonly replacesOrganizationId?: string | undefined;\n readonly userId: string | null;\n },\n): Promise<SessionCreateOrganizationResult | null> {\n if (!input.userId) {\n dependencies.log(\"Create organization skipped: user id is unavailable\");\n return null;\n }\n\n const identitySnapshot = dependencies.identity.snapshot;\n const { encapsulationKeyPair, signingKeyPair } = identitySnapshot;\n if (!signingKeyPair || !encapsulationKeyPair) {\n dependencies.log(\n \"Create organization skipped: identity keys are unavailable\",\n );\n return null;\n }\n\n const dbClient = dependencies.database.client;\n if (!dbClient) {\n dependencies.log(\n \"Create organization skipped: database client is unavailable\",\n );\n return null;\n }\n\n let response: Awaited<ReturnType<typeof createOrganizationWorkflow>>;\n try {\n response = await createOrganizationWorkflow({\n apiClient: dependencies.api,\n dbClient,\n documentProjectors: dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n dependencies.identity.snapshot === identitySnapshot,\n log: dependencies.log,\n logError: dependencies.logError,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n organizationProfileName: input.options?.organizationProfileName,\n primePrincipalHistory: dependencies.primeProvisionedPrincipalHistory,\n provisionedSystemContainers: dependencies.provisionedSystemContainers,\n replacesOrganizationId: input.replacesOrganizationId,\n rosterProfileNickname: input.options?.rosterProfileNickname,\n signingKeyPair,\n userId: input.userId,\n });\n } catch (error: unknown) {\n dependencies.logError(\"Organization creation failed\", error);\n throw error;\n }\n\n if (dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n dependencies.log(\"Organization creation failed\");\n return null;\n }\n // Creating an organization does not switch the active organization.\n return {\n containerId: response.rootContainerId,\n organizationId: response.organizationId,\n };\n}\n"]}
1
+ {"version":3,"file":"sessionOrganizationCreation.js","sourceRoot":"","sources":["sessionOrganizationCreation.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,IAAI,0BAA0B,EAAE,MAAM,+DAA+D,CAAC;AAyBjI,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,YAAqD,EACrD,KAKC;IAED,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;QAClB,YAAY,CAAC,GAAG,CAAC,qDAAqD,CAAC,CAA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AC,QAAQ,CAAC,8BAA8B,EAAE,KAAK,CAAC,CAAC;QAC7D,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,YAAY,CAAC,QAAQ,CAAC,QAAQ,KAAK,gBAAgB;QAAE,OAAO,IAAI,CAAC;IACrE,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,YAAY,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;QACjD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oEAAoE;IACpE,OAAO;QACL,WAAW,EAAE,QAAQ,CAAC,eAAe;QACrC,cAAc,EAAE,QAAQ,CAAC,cAAc;KACxC,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createOrganization as createOrganizationWorkflow } from \"../../workflows/organizations/provisioning/createOrganization\";\nimport type { ProvisionedSystemContainerSpec } from \"../../workflows/registration\";\nimport type { ProvisionedPrincipalHistoryPrimer } from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport type {\n CreateOrganizationOptions,\n SessionCreateOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionOrganizationCreationDependencies {\n readonly api: ApiClient;\n readonly database: Database;\n readonly documentProjectors?: DocumentProjectorRegistryInput | undefined;\n readonly identity: Identity;\n readonly log: (message: string) => void;\n readonly logError: (message: string | Error, cause?: unknown) => void;\n readonly primeProvisionedPrincipalHistory?:\n | ProvisionedPrincipalHistoryPrimer\n | undefined;\n readonly provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n}\n\nexport async function createSessionOrganization(\n dependencies: SessionOrganizationCreationDependencies,\n input: {\n readonly nativeSubscriptionRestore?: boolean | undefined;\n readonly options?: CreateOrganizationOptions | undefined;\n readonly replacesOrganizationId?: string | undefined;\n readonly userId: string | null;\n },\n): Promise<SessionCreateOrganizationResult | null> {\n if (!input.userId) {\n dependencies.log(\"Create organization skipped: user id is unavailable\");\n return null;\n }\n\n const identitySnapshot = dependencies.identity.snapshot;\n const { encapsulationKeyPair, signingKeyPair } = identitySnapshot;\n if (!signingKeyPair || !encapsulationKeyPair) {\n dependencies.log(\n \"Create organization skipped: identity keys are unavailable\",\n );\n return null;\n }\n\n const dbClient = dependencies.database.client;\n if (!dbClient) {\n dependencies.log(\n \"Create organization skipped: database client is unavailable\",\n );\n return null;\n }\n\n let response: Awaited<ReturnType<typeof createOrganizationWorkflow>>;\n try {\n response = await createOrganizationWorkflow({\n apiClient: dependencies.api,\n dbClient,\n documentProjectors: dependencies.documentProjectors,\n encapsulationKeyPair,\n isIdentityCurrent: () =>\n dependencies.identity.snapshot === identitySnapshot,\n log: dependencies.log,\n logError: dependencies.logError,\n nativeSubscriptionRestore: input.nativeSubscriptionRestore,\n organizationProfileName: input.options?.organizationProfileName,\n primePrincipalHistory: dependencies.primeProvisionedPrincipalHistory,\n provisionedSystemContainers: dependencies.provisionedSystemContainers,\n replacesOrganizationId: input.replacesOrganizationId,\n rosterProfileNickname: input.options?.rosterProfileNickname,\n signingKeyPair,\n userId: input.userId,\n });\n } catch (error: unknown) {\n dependencies.logError(\"Organization creation failed\", error);\n throw error;\n }\n\n if (dependencies.identity.snapshot !== identitySnapshot) return null;\n if (!response) {\n dependencies.log(\"Organization creation failed\");\n return null;\n }\n // Creating an organization does not switch the active organization.\n return {\n containerId: response.rootContainerId,\n organizationId: response.organizationId,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { resolveOrganizationBillingView } from "../../workflows/organizations/billing.js";
2
- import { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "../../workflows/organizations/organizationProvisioningAttempt.js";
3
- import { verifyOrganizationReplacementResponse } from "../../workflows/organizations/organizationReplacementVerification.js";
2
+ import { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "../../workflows/organizations/provisioning/organizationProvisioningAttempt.js";
3
+ import { verifyOrganizationReplacementResponse } from "../../workflows/organizations/provisioning/organizationReplacementVerification.js";
4
4
  import { clearRemoteSyncState } from "../../workflows/sync/index.js";
5
5
  import { PurgedOrganizationRecoveryBillingRequiredError } from "./sessionRecoveryErrors.js";
6
6
  function requireReplacementCanSync(replacement, billing) {
@@ -1 +1 @@
1
- {"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,qCAAqC,EAAE,MAAM,mEAAmE,CAAC;AAC1H,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,8CAA8C,EAAE,MAAM,yBAAyB,CAAC;AAyBzF,SAAS,yBAAyB,CAChC,WAA4C,EAC5C,OAAiE;IAEjE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,8BAA8B,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;QACjE,MAAM,IAAI,8CAA8C,CACtD,WAAW,CAAC,cAAc,EAC1B,OAAO,CAAC,MAAM,EACd,WAAW,CAAC,WAAW,CACxB,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,YAA8C,EAC9C,OAAoC,EACpC,cAAsB;IAEtB,MAAM,OAAO,GAAG,YAAY,CAAC,QAAQ,CAAC,cAAc,CAAC,sBAAsB,CAAC,CAAC;IAC7E,MAAM,MAAM,GAAG,MAAM,oBAAoB,CAAC,OAAO,EAAE;QACjD,cAAc;KACf,CAAC,CAAC;IACH,YAAY,CAAC,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AE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACL,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,oBAAoB,GACxB,MAAM,YAAY,CAAC,GAAG,CAAC,kBAAkB,CAAC,mBAAmB,CAAC,CAAC;IACjE,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACtC,0BAA0B,CACxB,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,MAAM,EACN,gBAAgB,CAAC,cAAc,CAChC,CAAC;IACF,MAAM,cAAc,GAAG,MAAM,qCAAqC,CAAC;QACjE,SAAS,EAAE,iBAAiB;QAC5B,OAAO;QACP,sBAAsB,EAAE,cAAc;QACtC,MAAM;KACP,CAAC,CAAC;IACH,IAAI,CAAC,cAAc,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,IAAI,CAAC;IACzD,YAAY,CAAC,GAAG,CAAC,2BAA2B,EAAE,CAAC;IAC/C,OAAO,CAAC,UAAU,CAAC;QACjB,WAAW,EAAE,WAAW,CAAC,WAAW;QACpC,qBAAqB,EAAE,WAAW,CAAC,cAAc;QACjD,cAAc,EAAE,WAAW,CAAC,cAAc;KAC3C,CAAC,CAAC;IACH,YAAY,CAAC,GAAG,CACd,iCAAiC,WAAW,CAAC,cAAc,GAAG,CAC/D,CAAC;IACF,OAAO;QACL,GAAG,WAAW;QACd,sBAAsB,EAAE,cAAc;QACtC,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport { resolveOrganizationBillingView } from \"../../workflows/organizations/billing\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"../../workflows/organizations/organizationProvisioningAttempt\";\nimport { verifyOrganizationReplacementResponse } from \"../../workflows/organizations/organizationReplacementVerification\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const execSql = dependencies.database.requireExecSql(\"clearRemoteSyncState\");\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const isRecoveryCurrent = () =>\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = dependencies.database.requireExecSql(\n \"recoverPurgedOrganization\",\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
1
+ {"version":3,"file":"sessionPurgeRecovery.js","sourceRoot":"","sources":["sessionPurgeRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,qCAAqC,EAAE,MAAM,gFAAgF,CAAC;AACvI,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAG5D,OAAO,EAAE,8CAA8C,EAAE,MAAM,yBAAyB,CAAC;AAyBzF,SAAS,yBAAyB,CAChC,WAA4C,EAC5C,OAAiE;IAEjE,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,IAAI,CAAC,8BAA8B,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC;QACjE,MAAM,IAAI,8CAA8C,CACtD,WAAW,CAAC,cAAc,EAC1B,OAAO,CAAC,MAAM,EACd,WAAW,CAAC,WAAW,CACxB,CAAC;IACJ,CAAC;AACH,CAAC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import { resolveOrganizationBillingView } from \"../../workflows/organizations/billing\";\nimport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"../../workflows/organizations/provisioning/organizationProvisioningAttempt\";\nimport { verifyOrganizationReplacementResponse } from \"../../workflows/organizations/provisioning/organizationReplacementVerification\";\nimport { clearRemoteSyncState } from \"../../workflows/sync\";\nimport type { Identity } from \"../identity\";\nimport type { Database } from \"../runtime/database\";\nimport { PurgedOrganizationRecoveryBillingRequiredError } from \"./sessionRecoveryErrors\";\nimport type {\n CreateOrganizationOptions,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionRecoverOrganizationResult,\n} from \"./sessionTypes\";\n\ninterface SessionPurgeRecoveryDependencies {\n api: Pick<ApiClient, \"clearWriterProjectionCaches\">;\n database: Pick<Database, \"requireExecSql\">;\n identity: Pick<Identity, \"snapshot\">;\n log: (message: string) => void;\n}\n\ninterface SessionPurgeRecoveryContext {\n createOrganization: (\n options?: CreateOrganizationOptions,\n replacesOrganizationId?: string,\n ) => Promise<SessionCreateOrganizationResult | null>;\n organizationId: string | null;\n setContext: (context: SessionContext) => void;\n userId: string | null;\n}\n\nfunction requireReplacementCanSync(\n replacement: SessionCreateOrganizationResult,\n billing: Awaited<ReturnType<ApiClient[\"getOrganizationBilling\"]>>,\n): void {\n if (!billing) {\n throw new Error(\"Replacement organization billing could not be loaded\");\n }\n if (!resolveOrganizationBillingView(billing, Date.now()).canSync) {\n throw new PurgedOrganizationRecoveryBillingRequiredError(\n replacement.organizationId,\n billing.status,\n replacement.containerId,\n );\n }\n}\n\nexport async function clearSessionRemoteSyncState(\n dependencies: SessionPurgeRecoveryDependencies,\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n) {\n const execSql = dependencies.database.requireExecSql(\"clearRemoteSyncState\");\n const result = await clearRemoteSyncState(execSql, {\n organizationId,\n });\n dependencies.api.clearWriterProjectionCaches();\n if (session.organizationId === organizationId) {\n session.setContext({ containerId: null, organizationId: null });\n }\n dependencies.log(\"Remote sync state cleared\");\n return result;\n}\n\nfunction verifyFinalizedReplacement(\n finalizedReplacement: Awaited<ReturnType<ApiClient[\"createOrganization\"]>>,\n replacement: SessionCreateOrganizationResult,\n replacesOrganizationId: string,\n userId: string,\n signingKeyPair: Identity[\"snapshot\"][\"signingKeyPair\"],\n): void {\n if (\n !finalizedReplacement ||\n finalizedReplacement.organizationId !== replacement.organizationId ||\n finalizedReplacement.rootContainerId !== replacement.containerId ||\n finalizedReplacement.userId !== userId\n ) {\n throw new Error(\"Organization replacement finalization was inconsistent\");\n }\n if (!signingKeyPair) {\n throw new Error(\n \"Organization replacement requires the current signing identity\",\n );\n }\n verifyOrganizationReplacementResponse({\n replacesOrganizationId,\n response: finalizedReplacement,\n signingPublicKey: signingKeyPair.signingPublicKey,\n userId,\n });\n}\n\nexport async function recoverPurgedSessionOrganization(\n dependencies: SessionPurgeRecoveryDependencies & {\n api: Pick<\n ApiClient,\n | \"clearWriterProjectionCaches\"\n | \"createOrganization\"\n | \"getOrganizationBilling\"\n >;\n },\n session: SessionPurgeRecoveryContext,\n organizationId: string,\n options: CreateOrganizationOptions | undefined,\n): Promise<SessionRecoverOrganizationResult | null> {\n const identitySnapshot = dependencies.identity.snapshot;\n const sessionOrganizationId = session.organizationId;\n const userId = session.userId;\n if (!userId) {\n throw new Error(\"Purged organization recovery requires a current user\");\n }\n const isRecoveryCurrent = () =>\n dependencies.identity.snapshot === identitySnapshot &&\n session.organizationId === sessionOrganizationId &&\n session.userId === userId;\n const billing = await dependencies.api.getOrganizationBilling(organizationId);\n if (billing?.status !== \"purged\") {\n throw new Error(\n `Organization ${organizationId} cannot be recovered before its purge finishes`,\n );\n }\n if (!isRecoveryCurrent()) return null;\n const replacement = await session.createOrganization(options, organizationId);\n if (!replacement) return null;\n if (!isRecoveryCurrent()) return null;\n const replacementBilling = await dependencies.api.getOrganizationBilling(\n replacement.organizationId,\n );\n if (!isRecoveryCurrent()) return null;\n requireReplacementCanSync(replacement, replacementBilling);\n const execSql = dependencies.database.requireExecSql(\n \"recoverPurgedOrganization\",\n );\n const reset = await clearRemoteSyncState(\n execSql,\n {\n organizationId,\n replacement: {\n organizationId: replacement.organizationId,\n rootContainerId: replacement.containerId,\n },\n },\n isRecoveryCurrent,\n );\n if (!isRecoveryCurrent()) return null;\n const finalizationRequest =\n await loadOrganizationReplacementFinalizationRequest({\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!isRecoveryCurrent()) return null;\n const finalizedReplacement =\n await dependencies.api.createOrganization(finalizationRequest);\n if (!isRecoveryCurrent()) return null;\n verifyFinalizedReplacement(\n finalizedReplacement,\n replacement,\n organizationId,\n userId,\n identitySnapshot.signingKeyPair,\n );\n const attemptRemoved = await removeOrganizationProvisioningAttempt({\n canCommit: isRecoveryCurrent,\n execSql,\n replacedOrganizationId: organizationId,\n userId,\n });\n if (!attemptRemoved || !isRecoveryCurrent()) return null;\n dependencies.api.clearWriterProjectionCaches();\n session.setContext({\n containerId: replacement.containerId,\n defaultOrganizationId: replacement.organizationId,\n organizationId: replacement.organizationId,\n });\n dependencies.log(\n `Purged organization replaced (${replacement.organizationId})`,\n );\n return {\n ...replacement,\n replacedOrganizationId: organizationId,\n reset,\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.62",
3
+ "version": "0.1.63",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -1,6 +1,6 @@
1
1
  import { getDocumentAttachments } from "../../../data/documents/documentContent.js";
2
2
  import { runSerializedDocumentBlobMutation, } from "../../../workflows/documents/index.js";
3
- import { saveHydratedDocumentAttachment } from "../../../workflows/documents/attachmentPersistence.js";
3
+ import { saveHydratedDocumentAttachment } from "../../../workflows/documents/attachments/attachmentPersistence.js";
4
4
  import { installLocalAttachmentRecords, removeLocalAttachmentSlot, } from "./attachmentPersistence.js";
5
5
  export async function commitHydratedAttachment(input) {
6
6
  const { state, currentDoc, hydratedBlob, expectedStorageKey, generationIsCurrent, } = input;
@@ -1 +1 @@
1
- {"version":3,"file":"attachmentHydrationCommit.js","sourceRoot":"","sources":["attachmentHydrationCommit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AAEjF,OAAO,EAEL,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,8BAA8B,EAAE,MAAM,oDAAoD,CAAC;AACpG,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AAOjC,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAW9C;IACC,MAAM,EACJ,KAAK,EACL,UAAU,EACV,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,GACpB,GAAG,KAAK,CAAC;IACV,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,MAAM,0BAA0B,GAAG,KAAK,CAAC,MAAM,EAAE,kBAAkB,IAAI,IAAI,CAAC;IAC5E,MAAM,YAAY,GAAG,GAAG,EAAE,CACxB,mBAAmB,EAAE;QACrB,KAAK,CAAC,GAAG,KAAK,UAAU;QACxB,sBAAsB,CAAC,UAAU,CAAC,CAAC,IAAI,CACrC,CAAC,UAAU,EAAE,EAAE,CACb,UAAU,CAAC,MAAM,KAAK,YAAY,CAAC,UAAU,CAAC,MAAM;YACpD,UAAU,CAAC,aAAa,KAAK,YAAY,CAAC,UAAU,CAAC,aAAa,CACrE,CAAC;IACJ,MAAM,iCAAiC,CACrC,OAAO,CAAC,KAAK,CAAC,OAAO,EACrB,YAAY,CAAC,UAAU,EACvB,KAAK,IAAI,EAAE;QACT,IAAI,CAAC,YAAY,EAAE;YAAE,OAAO;QAC5B,MAAM,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,UAAU,CACtC,YAAY,CAAC,UAAU,EAC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CAAC,UAAU,CAAC,MAAM,CAAC;IAC9C,yBAAyB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACzC,6BAA6B,CAC3B,KAAK,EACL,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,EAC3C,UAAU,CACX,CAAC;AACJ,CAAC","sourcesContent":["import { getDocumentAttachments } from \"../../../data/documents/documentContent\";\nimport type { hydrateDocumentAttachmentBlobs } from \"../../../workflows/blobs\";\nimport {\n type LocalAttachmentRecord,\n runSerializedDocumentBlobMutation,\n} from \"../../../workflows/documents\";\nimport { saveHydratedDocumentAttachment } from \"../../../workflows/documents/attachmentPersistence\";\nimport {\n installLocalAttachmentRecords,\n removeLocalAttachmentSlot,\n} from \"./attachmentPersistence\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\n\ntype HydratedBlob = NonNullable<\n Awaited<ReturnType<typeof hydrateDocumentAttachmentBlobs>>\n>[number];\n\nexport async function commitHydratedAttachment(input: {\n state: DocumentStoreState;\n currentDoc: DocumentState;\n hydratedBlob: Pick<\n HydratedBlob,\n \"attachment\" | \"bytes\" | \"contentSha256\" | \"storageKey\"\n > & {\n binding: Pick<HydratedBlob[\"binding\"], \"blobId\">;\n };\n expectedStorageKey: string | null;\n generationIsCurrent: () => boolean;\n}): Promise<void> {\n const {\n state,\n currentDoc,\n hydratedBlob,\n expectedStorageKey,\n generationIsCurrent,\n } = input;\n const runtime = state.runtime;\n const expectedSnapshotEndVersion = state.record?.snapshotEndVersion ?? null;\n const stillCurrent = () =>\n generationIsCurrent() &&\n state.doc === currentDoc &&\n getDocumentAttachments(currentDoc).some(\n (attachment) =>\n attachment.slotId === hydratedBlob.attachment.slotId &&\n attachment.contentSha256 === hydratedBlob.attachment.contentSha256,\n );\n await runSerializedDocumentBlobMutation(\n runtime.infra.execSql,\n hydratedBlob.storageKey,\n async () => {\n if (!stillCurrent()) return;\n await runtime.infra.blobStore.writeBytes(\n hydratedBlob.storageKey,\n hydratedBlob.bytes,\n );\n const attachment: LocalAttachmentRecord = {\n blobId: hydratedBlob.binding.blobId,\n // The held bytes' own size, not the document intent's: a served\n // binding the intent has not recorded yet may differ in length, and\n // preview gating reads the local record.\n byteLength: hydratedBlob.bytes.byteLength,\n contentSha256: hydratedBlob.contentSha256,\n detachedAt: null,\n localId: state.localId,\n mimeType: hydratedBlob.attachment.mimeType,\n slotId: hydratedBlob.attachment.slotId,\n storageKey: hydratedBlob.storageKey,\n };\n const committed = await saveHydratedDocumentAttachment({\n execSql: runtime.infra.execSql,\n persistence: state.persistence,\n attachment,\n expectedStorageKey,\n expectedSnapshotEndVersion,\n stillCurrent,\n });\n if (committed && stillCurrent())\n installLocalAttachmentRecords(state, [attachment], currentDoc);\n else if (!committed && stillCurrent())\n await refreshRefusedAttachmentSlot(input, stillCurrent);\n },\n );\n}\n\nasync function refreshRefusedAttachmentSlot(\n input: Parameters<typeof commitHydratedAttachment>[0],\n stillCurrent: () => boolean,\n): Promise<void> {\n const { state, currentDoc, hydratedBlob } = input;\n const rows = await state.persistence.listLocalAttachments(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!stillCurrent()) return;\n const slotId = hydratedBlob.attachment.slotId;\n removeLocalAttachmentSlot(state, slotId);\n installLocalAttachmentRecords(\n state,\n rows.filter((row) => row.slotId === slotId),\n currentDoc,\n );\n}\n"]}
1
+ {"version":3,"file":"attachmentHydrationCommit.js","sourceRoot":"","sources":["attachmentHydrationCommit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AAEjF,OAAO,EAEL,iCAAiC,GAClC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,8BAA8B,EAAE,MAAM,gEAAgE,CAAC;AAChH,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AAOjC,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAW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CAAC;YACrD,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,UAAU;YACV,kBAAkB;YAClB,0BAA0B;YAC1B,YAAY;SACb,CAAC,CAAC;QACH,IAAI,SAAS,IAAI,YAAY,EAAE;YAC7B,6BAA6B,CAAC,KAAK,EAAE,CAAC,UAAU,CAAC,EAAE,UAAU,CAAC,CAAC;aAC5D,IAAI,CAAC,SAAS,IAAI,YAAY,EAAE;YACnC,MAAM,4BAA4B,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;IAC5D,CAAC,CACF,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,4BAA4B,CACzC,KAAqD,EACrD,YAA2B;IAE3B,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,KAAK,CAAC;IAClD,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,WAAW,CAAC,oBAAoB,CACvD,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC3B,KAAK,CAAC,OAAO,CACd,CAAC;IACF,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,MAAM,MAAM,GAAG,YAAY,CAAC,UAAU,CAAC,MAAM,CAAC;IAC9C,yBAAyB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACzC,6BAA6B,CAC3B,KAAK,EACL,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,EAC3C,UAAU,CACX,CAAC;AACJ,CAAC","sourcesContent":["import { getDocumentAttachments } from \"../../../data/documents/documentContent\";\nimport type { hydrateDocumentAttachmentBlobs } from \"../../../workflows/blobs\";\nimport {\n type LocalAttachmentRecord,\n runSerializedDocumentBlobMutation,\n} from \"../../../workflows/documents\";\nimport { saveHydratedDocumentAttachment } from \"../../../workflows/documents/attachments/attachmentPersistence\";\nimport {\n installLocalAttachmentRecords,\n removeLocalAttachmentSlot,\n} from \"./attachmentPersistence\";\nimport type { DocumentState, DocumentStoreState } from \"./state\";\n\ntype HydratedBlob = NonNullable<\n Awaited<ReturnType<typeof hydrateDocumentAttachmentBlobs>>\n>[number];\n\nexport async function commitHydratedAttachment(input: {\n state: DocumentStoreState;\n currentDoc: DocumentState;\n hydratedBlob: Pick<\n HydratedBlob,\n \"attachment\" | \"bytes\" | \"contentSha256\" | \"storageKey\"\n > & {\n binding: Pick<HydratedBlob[\"binding\"], \"blobId\">;\n };\n expectedStorageKey: string | null;\n generationIsCurrent: () => boolean;\n}): Promise<void> {\n const {\n state,\n currentDoc,\n hydratedBlob,\n expectedStorageKey,\n generationIsCurrent,\n } = input;\n const runtime = state.runtime;\n const expectedSnapshotEndVersion = state.record?.snapshotEndVersion ?? null;\n const stillCurrent = () =>\n generationIsCurrent() &&\n state.doc === currentDoc &&\n getDocumentAttachments(currentDoc).some(\n (attachment) =>\n attachment.slotId === hydratedBlob.attachment.slotId &&\n attachment.contentSha256 === hydratedBlob.attachment.contentSha256,\n );\n await runSerializedDocumentBlobMutation(\n runtime.infra.execSql,\n hydratedBlob.storageKey,\n async () => {\n if (!stillCurrent()) return;\n await runtime.infra.blobStore.writeBytes(\n hydratedBlob.storageKey,\n hydratedBlob.bytes,\n );\n const attachment: LocalAttachmentRecord = {\n blobId: hydratedBlob.binding.blobId,\n // The held bytes' own size, not the document intent's: a served\n // binding the intent has not recorded yet may differ in length, and\n // preview gating reads the local record.\n byteLength: hydratedBlob.bytes.byteLength,\n contentSha256: hydratedBlob.contentSha256,\n detachedAt: null,\n localId: state.localId,\n mimeType: hydratedBlob.attachment.mimeType,\n slotId: hydratedBlob.attachment.slotId,\n storageKey: hydratedBlob.storageKey,\n };\n const committed = await saveHydratedDocumentAttachment({\n execSql: runtime.infra.execSql,\n persistence: state.persistence,\n attachment,\n expectedStorageKey,\n expectedSnapshotEndVersion,\n stillCurrent,\n });\n if (committed && stillCurrent())\n installLocalAttachmentRecords(state, [attachment], currentDoc);\n else if (!committed && stillCurrent())\n await refreshRefusedAttachmentSlot(input, stillCurrent);\n },\n );\n}\n\nasync function refreshRefusedAttachmentSlot(\n input: Parameters<typeof commitHydratedAttachment>[0],\n stillCurrent: () => boolean,\n): Promise<void> {\n const { state, currentDoc, hydratedBlob } = input;\n const rows = await state.persistence.listLocalAttachments(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!stillCurrent()) return;\n const slotId = hydratedBlob.attachment.slotId;\n removeLocalAttachmentSlot(state, slotId);\n installLocalAttachmentRecords(\n state,\n rows.filter((row) => row.slotId === slotId),\n currentDoc,\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { reportAndRethrowKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
2
- import { uploadPreparedDocumentAttachment as uploadDocumentAttachment } from "../../../workflows/blobs/upload.js";
2
+ import { uploadPreparedDocumentAttachment as uploadDocumentAttachment } from "../../../workflows/blobs/upload/index.js";
3
3
  export async function uploadAttachmentWithWriterProjectionRetry(input) {
4
4
  let remoteSyncBlocked = false;
5
5
  let checkedOrganizationId;
@@ -1,5 +1,5 @@
1
1
  import { isContainerProjectionInvalidationHint, isDocumentUpdateCreatedEvent, } from "../../../data/documents/documentSync.js";
2
- import { sequenceUnchanged } from "../../../workflows/documents/syncLane.js";
2
+ import { sequenceUnchanged } from "../../../workflows/documents/sync/syncLane.js";
3
3
  import { resumeAfterAncestorRepairHint } from "./ancestorRepairPark.js";
4
4
  import { allowDocumentStoreRemoteSync, markDocumentStoreRemoteSyncPending, } from "./syncGeneration.js";
5
5
  import { invalidateDocumentWriterProjection } from "./writerProjectionGeneration.js";
@@ -1 +1 @@
1
- {"version":3,"file":"syncRemoteSignals.js","sourceRoot":"","sources":["syncRemoteSignals.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC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C,mBAAmB,GAAG,KAAK,CAAC;IACpC,CAAC;AACH,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,KAAyB,EACzB,YAAwB;IAExB,MAAM,UAAU,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IAC1E,KAAK,CAAC,cAAc,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC;IAEzD,yEAAyE;IACzE,2EAA2E;IAC3E,4EAA4E;IAC5E,uEAAuE;IACvE,2EAA2E;IAC3E,MAAM,qBAAqB,GAAG,UAAU,CAAC,IAAI,CAC3C,qCAAqC,CACtC,CAAC;IACF,IAAI,qBAAqB;QAAE,kCAAkC,CAAC,KAAK,CAAC,CAAC;IAErE,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,UAAU;QAAE,OAAO;IAEtC,4EAA4E;IAC5E,4EAA4E;IAC5E,0EAA0E;IAC1E,IAAI,qBAAqB,IAAI,6BAA6B,CAAC,KAAK,CAAC,EAAE,CAAC;QAClE,YAAY,EAAE,CAAC;IACjB,CAAC;IAED,IAAI,4BAA4B,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC;QACpD,4BAA4B,CAAC,KAAK,CAAC,CAAC;QACpC,oEAAoE;QACpE,uCAAuC;QACvC,kCAAkC,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QACzD,YAAY,EAAE,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["import {\n isContainerProjectionInvalidationHint,\n isDocumentUpdateCreatedEvent,\n} from \"../../../data/documents/documentSync\";\nimport { sequenceUnchanged } from \"../../../workflows/documents/syncLane\";\nimport { resumeAfterAncestorRepairHint } from \"./ancestorRepairPark\";\nimport type { DocumentStoreState } from \"./state\";\nimport {\n allowDocumentStoreRemoteSync,\n markDocumentStoreRemoteSyncPending,\n} from \"./syncGeneration\";\nimport { invalidateDocumentWriterProjection } from \"./writerProjectionGeneration\";\n\nexport function hasRemoteDocumentUpdateEvent(\n state: DocumentStoreState,\n events: ReadonlyArray<unknown>,\n): boolean {\n let remoteUpdateFound = false;\n\n for (const event of events) {\n if (\n !isDocumentUpdateCreatedEvent(event) ||\n event.documentId !== state.record?.documentId\n ) {\n continue;\n }\n\n if (event.updateIds && event.updateIds.length > 0) {\n for (const updateId of event.updateIds) {\n if (!state.locallyAcceptedUpdateIds.has(updateId)) {\n remoteUpdateFound = true;\n continue;\n }\n\n state.locallyAcceptedUpdateIds.delete(updateId);\n }\n continue;\n }\n\n remoteUpdateFound = true;\n }\n\n return remoteUpdateFound;\n}\n\n/** Clear the remote-update signal only when its consumed sequence is unchanged.\n * A moved sequence means a newer remote event arrived mid-pass and must survive\n * for the coalesced re-run to avoid the convergence-stall race.\n */\nexport const canClearRemoteUpdateSignalAfterSync = sequenceUnchanged;\n\nexport function clearConsumedRemoteUpdateSignal(\n state: DocumentStoreState,\n consumedSignalSequence: number,\n): void {\n // A peer event can arrive while the HTTP request is in flight. Clear only\n // the sequence this pass consumed so the newer event survives for a re-run.\n if (\n canClearRemoteUpdateSignalAfterSync(\n state.remoteUpdateSignalSeq,\n consumedSignalSequence,\n )\n ) {\n state.remoteUpdateCompletedSignalSeq = consumedSignalSequence;\n state.remoteUpdatePending = false;\n }\n}\n\nexport function handleDocumentRemoteEvents(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n const nextEvents = state.runtime.state.events.slice(state.lastEventCount);\n state.lastEventCount = state.runtime.state.events.length;\n\n // A container the document's path cites may have moved its manifest; the\n // store cannot tell which containers this document links into, so the held\n // projection goes and the next mutation fetches a fresh one. This runs even\n // before the document has a remote id: a create in flight captured the\n // generation when it started and must not install its pre-hint projection.\n const projectionInvalidated = nextEvents.some(\n isContainerProjectionInvalidationHint,\n );\n if (projectionInvalidated) invalidateDocumentWriterProjection(state);\n\n if (!state.record?.documentId) return;\n\n // Writes parked behind an ancestor another member must re-key: this hint is\n // the only signal that the repair may have landed. It names no ancestor, so\n // any one re-runs the pass, which parks again if the path is still stale.\n if (projectionInvalidated && resumeAfterAncestorRepairHint(state)) {\n scheduleSync();\n }\n\n if (hasRemoteDocumentUpdateEvent(state, nextEvents)) {\n allowDocumentStoreRemoteSync(state);\n // Let an in-flight pass distinguish this new signal from the one it\n // consumed before its network request.\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n scheduleSync();\n }\n}\n"]}
1
+ {"version":3,"file":"syncRemoteSignals.js","sourceRoot":"","sources":["syncRemoteSignals.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAC/E,OAAO,EAAE,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AAErE,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,GACnC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AAElF,MAAM,UAAU,4BAA4B,CAC1C,KAAyB,EACzB,MAA8B;IAE9B,IAAI,iBAAiB,GAAG,KAAK,CAAC;IAE9B,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,IACE,CAAC,4BAA4B,CAAC,KAAK,CAAC;YACpC,KAAK,CAAC,UAAU,KAAK,KAAK,CAAC,MAAM,EAAE,UAAU,EAC7C,CAAC;YACD,SAAS;QACX,CAAC;QAED,IAAI,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAClD,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBACvC,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;oBAClD,iBAAiB,GAAG,IAAI,CAAC;oBACzB,SAAS;gBACX,CAAC;gBAED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UAAU,CAAC,EAAE,CAAC;QACpD,4BAA4B,CAAC,KAAK,CAAC,CAAC;QACpC,oEAAoE;QACpE,uCAAuC;QACvC,kCAAkC,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;QACzD,YAAY,EAAE,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["import {\n isContainerProjectionInvalidationHint,\n isDocumentUpdateCreatedEvent,\n} from \"../../../data/documents/documentSync\";\nimport { sequenceUnchanged } from \"../../../workflows/documents/sync/syncLane\";\nimport { resumeAfterAncestorRepairHint } from \"./ancestorRepairPark\";\nimport type { DocumentStoreState } from \"./state\";\nimport {\n allowDocumentStoreRemoteSync,\n markDocumentStoreRemoteSyncPending,\n} from \"./syncGeneration\";\nimport { invalidateDocumentWriterProjection } from \"./writerProjectionGeneration\";\n\nexport function hasRemoteDocumentUpdateEvent(\n state: DocumentStoreState,\n events: ReadonlyArray<unknown>,\n): boolean {\n let remoteUpdateFound = false;\n\n for (const event of events) {\n if (\n !isDocumentUpdateCreatedEvent(event) ||\n event.documentId !== state.record?.documentId\n ) {\n continue;\n }\n\n if (event.updateIds && event.updateIds.length > 0) {\n for (const updateId of event.updateIds) {\n if (!state.locallyAcceptedUpdateIds.has(updateId)) {\n remoteUpdateFound = true;\n continue;\n }\n\n state.locallyAcceptedUpdateIds.delete(updateId);\n }\n continue;\n }\n\n remoteUpdateFound = true;\n }\n\n return remoteUpdateFound;\n}\n\n/** Clear the remote-update signal only when its consumed sequence is unchanged.\n * A moved sequence means a newer remote event arrived mid-pass and must survive\n * for the coalesced re-run to avoid the convergence-stall race.\n */\nexport const canClearRemoteUpdateSignalAfterSync = sequenceUnchanged;\n\nexport function clearConsumedRemoteUpdateSignal(\n state: DocumentStoreState,\n consumedSignalSequence: number,\n): void {\n // A peer event can arrive while the HTTP request is in flight. Clear only\n // the sequence this pass consumed so the newer event survives for a re-run.\n if (\n canClearRemoteUpdateSignalAfterSync(\n state.remoteUpdateSignalSeq,\n consumedSignalSequence,\n )\n ) {\n state.remoteUpdateCompletedSignalSeq = consumedSignalSequence;\n state.remoteUpdatePending = false;\n }\n}\n\nexport function handleDocumentRemoteEvents(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n const nextEvents = state.runtime.state.events.slice(state.lastEventCount);\n state.lastEventCount = state.runtime.state.events.length;\n\n // A container the document's path cites may have moved its manifest; the\n // store cannot tell which containers this document links into, so the held\n // projection goes and the next mutation fetches a fresh one. This runs even\n // before the document has a remote id: a create in flight captured the\n // generation when it started and must not install its pre-hint projection.\n const projectionInvalidated = nextEvents.some(\n isContainerProjectionInvalidationHint,\n );\n if (projectionInvalidated) invalidateDocumentWriterProjection(state);\n\n if (!state.record?.documentId) return;\n\n // Writes parked behind an ancestor another member must re-key: this hint is\n // the only signal that the repair may have landed. It names no ancestor, so\n // any one re-runs the pass, which parks again if the path is still stale.\n if (projectionInvalidated && resumeAfterAncestorRepairHint(state)) {\n scheduleSync();\n }\n\n if (hasRemoteDocumentUpdateEvent(state, nextEvents)) {\n allowDocumentStoreRemoteSync(state);\n // Let an in-flight pass distinguish this new signal from the one it\n // consumed before its network request.\n markDocumentStoreRemoteSyncPending(state, \"independent\");\n scheduleSync();\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { deriveStableDocumentId } from "../../../data/documents/shared/stableDocumentId.js";
2
2
  import { createRemoteDocument, DOCUMENTS_APP_KIND, describeDocumentRevalidationFailure, describeDocumentSyncSubmitFailure, recordDocumentSyncFailure, resolveDocumentCreateAuthor, runSerializedSqlMutation, } from "../../../workflows/documents/index.js";
3
- import { reportDocumentSyncQuarantine } from "../../../workflows/documents/reportDocumentSyncQuarantine.js";
3
+ import { reportDocumentSyncQuarantine } from "../../../workflows/documents/sync/reportDocumentSyncQuarantine.js";
4
4
  import { createRuntimePrincipalPolicyWarmer } from "../../../workflows/principals/runtimePolicyWarmer.js";
5
5
  import { chainIdentityWrite } from "./identityWriteChain.js";
6
6
  import { persistDocument } from "./persistence.js";
@@ -1 +1 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,uEAAuE;QACvE,yEAAyE;QACzE,0EAA0E;QAC1E,wEAAwE;QACxE,6DAA6D;QAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;QAChD,IAAI,cAAc,IAAI,cAAc,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAC,MAAM,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAC5D,+BAA+B,CAC7B,KAAK,EACL,OAAO,CAAC,gBAAgB,EACxB,0BAA0B,CAC3B,CAAC;QAEF,6EAA6E;QAC7E,4EAA4E;QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,MAAM,YAAY,GAAG,EAAE,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;QACnD,MAAM,cAAc,GAAG;YACrB,gCAAgC,EAAE,IAAI;YACtC,oBAAoB,EAAE,IAAI;SAC3B,CAAC;QACF,MAAM,SAAS,GAAG,MAAM,eAAe,CACrC,KAAK,EACL,UAAU,EACV,YAAY,EACZ,cAAc,EACd,UAAU,CACX,CAAC;QACF,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n recordDocumentSyncFailure,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../workflows/documents/reportDocumentSyncQuarantine\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"./identityWriteChain\";\nimport { persistDocument } from \"./persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"./state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { installDocumentWriterProjection } from \"./writerProjectionGeneration\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await recordDocumentSyncFailure(\n lockedExecSql,\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation?: DocumentStoreSyncGeneration,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n const persistPatch = { ...created.persistedState };\n const persistOptions = {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n };\n const persisted = await persistDocument(\n state,\n currentDoc,\n persistPatch,\n persistOptions,\n generation,\n );\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
1
+ {"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,iDAAiD,CAAC;AACzF,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAGlB,mCAAmC,EACnC,iCAAiC,EAEjC,yBAAyB,EACzB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,4BAA4B,EAAE,MAAM,gEAAgE,CAAC;AAC9G,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAIL,wBAAwB,GACzB,MAAM,SAAS,CAAC;AACjB,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,+BAA+B,EAAE,MAAM,8BAA8B,CAAC;AAE/E;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CAChD,KAAyB,EACzB,UAAwC;IAExC,OAAO,0BAA0B,CAAC;QAChC,eAAe,EAAE,mCAAmC;QACpD,UAAU;QACV,KAAK;QACL,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oCAAoC,CAClD,KAAyB,EACzB,UAAwC;IAExC,OAAO,0BAA0B,CAAC;QAChC,eAAe,EAAE,iCAAiC;QAClD,UAAU;QACV,KAAK;KACN,CAAC,CAAC;AACL,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,6CAA6C,CAC3D,KAAyB,EACzB,UAA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UAAU,CAAC;IACpB,CAAC;IAED,OAAO,kBAAkB,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE;QAC1C,IAAI,CAAC,mBAAmB,EAAE;YAAE,OAAO,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;QAE9D,uEAAuE;QACvE,yEAAyE;QACzE,0EAA0E;QAC1E,wEAAwE;QACxE,6DAA6D;QAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC;QAChD,IAAI,cAAc,IAAI,cAAc,KAAK,OAAO,CAAC,UAAU,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAC,MAAM,CAAC;QACtB,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,qBAAqB,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAC5D,+BAA+B,CAC7B,KAAK,EACL,OAAO,CAAC,gBAAgB,EACxB,0BAA0B,CAC3B,CAAC;QAEF,6EAA6E;QAC7E,4EAA4E;QAC5E,sEAAsE;QACtE,4EAA4E;QAC5E,4EAA4E;QAC5E,2EAA2E;QAC3E,6EAA6E;QAC7E,uEAAuE;QACvE,0EAA0E;QAC1E,MAAM,YAAY,GAAG,EAAE,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;QACnD,MAAM,cAAc,GAAG;YACrB,gCAAgC,EAAE,IAAI;YACtC,oBAAoB,EAAE,IAAI;SAC3B,CAAC;QACF,MAAM,SAAS,GAAG,MAAM,eAAe,CACrC,KAAK,EACL,UAAU,EACV,YAAY,EACZ,cAAc,EACd,UAAU,CACX,CAAC;QACF,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n recordDocumentSyncFailure,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"./identityWriteChain\";\nimport { persistDocument } from \"./persistence\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"./state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { installDocumentWriterProjection } from \"./writerProjectionGeneration\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await recordDocumentSyncFailure(\n lockedExecSql,\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n generation?: DocumentStoreSyncGeneration,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n const persistPatch = { ...created.persistedState };\n const persistOptions = {\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n };\n const persisted = await persistDocument(\n state,\n currentDoc,\n persistPatch,\n persistOptions,\n generation,\n );\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
@@ -4,7 +4,7 @@ import { authorizingContainerPathRefs } from "../../data/documents/shared/projec
4
4
  import { readCanonicalRecord } from "../../data/keying/canonicalJson.js";
5
5
  import { requireProjectionUserKeyResolver } from "../../data/keyingProjectionVerification/index.js";
6
6
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
7
- import { resolveBlobMutationWriterProjection } from "./writerProjection.js";
7
+ import { resolveBlobMutationWriterProjection } from "./verification/writerProjection.js";
8
8
  export async function detachDocumentAttachment({ apiClient, author, bindingId, blobId, documentId, eventId = crypto.randomUUID(), execSql, isRemoteSyncBlocked, resolveProjectionUserKey, signedAt = new Date().toISOString(), slotId, stillCurrent, warmReferencedPrincipalPolicies, writerProjection, }) {
9
9
  const resolved = await resolveBlobMutationWriterProjection({
10
10
  apiClient,
@@ -1 +1 @@
1
- {"version":3,"file":"detach.js","sourceRoot":"","sources":["detach.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAKhG,OAAO,EAAE,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAC3F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;A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AClD,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,oBAAoB,CACnD,MAAM,EACN,SAAS,EACT,OAAO,EACP;QACE,qCAAqC,EAAE,gBAAgB,CAAC,cAAc;KACvE,CACF,CAAC;IACF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IACD,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAElD,kCAAkC,CAAC;QACjC,SAAS;QACT,MAAM;QACN,UAAU;QACV,QAAQ;QACR,MAAM;KACP,CAAC,CAAC;IAEH,OAAO;QACL,OAAO;QACP,QAAQ;QACR,gBAAgB,EAAE,wBAAwB;KAC3C,CAAC;AACJ,CAAC","sourcesContent":["import type { BlobAttachmentDetachRequest } from \"@tearleads/validators/request\";\nimport { signBlobAttachmentDetachEvent } from \"../../data/documents/blob/shared/events\";\nimport { assertBlobAttachmentDetachResponse } from \"../../data/documents/blob/shared/responses\";\nimport type {\n DetachDocumentAttachmentInput,\n DetachDocumentAttachmentResult,\n} from \"../../data/documents/blob/shared/types\";\nimport { authorizingContainerPathRefs } from \"../../data/documents/shared/projection\";\nimport { readCanonicalRecord } from \"../../data/keying/canonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { resolveBlobMutationWriterProjection } from \"./writerProjection\";\n\nexport async function detachDocumentAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n documentId,\n eventId = crypto.randomUUID(),\n execSql,\n isRemoteSyncBlocked,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: DetachDocumentAttachmentInput): Promise<DetachDocumentAttachmentResult | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient,\n documentId,\n errorLabel: \"Blob attachment detach\",\n execSql,\n isRemoteSyncBlocked,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment detach\",\n ),\n writerProjection,\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection: resolvedWriterProjection } =\n resolved;\n\n const pathRefs = authorizingContainerPathRefs(resolvedWriterProjection);\n const { body, event } = await signBlobAttachmentDetachEvent({\n author,\n bindingId,\n blobId,\n documentId,\n eventId,\n manifestIdentity,\n signedAt,\n slotId,\n authorizingContainerPathRefs: pathRefs,\n });\n const request: BlobAttachmentDetachRequest = {\n event: readCanonicalRecord(event, \"Blob attachment detach event\"),\n body: readCanonicalRecord(body, \"Blob attachment detach body\"),\n authorizingContainerPathRefs: pathRefs,\n };\n assertProjectionVerificationCurrent(stillCurrent);\n const response = await apiClient.detachBlobAttachment(\n blobId,\n bindingId,\n request,\n {\n expectedPaymentRequiredOrganizationId: manifestIdentity.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n\n assertBlobAttachmentDetachResponse({\n bindingId,\n blobId,\n documentId,\n response,\n slotId,\n });\n\n return {\n request,\n response,\n writerProjection: resolvedWriterProjection,\n };\n}\n"]}
1
+ {"version":3,"file":"detach.js","sourceRoot":"","sources":["detach.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAKhG,OAAO,EAAE,4BAA4B,EAAE,MAAM,wCAAwC,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iCAAiC,CAAC;AACtE,OAAO,EAAE,gCAAgC,EAAE,MAAM,yCAAyC,CAAC;AAC3F,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAEtF,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,EAC7C,SAAS,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AAgB,CAAC,cAAc;KACvE,CACF,CAAC;IACF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IACD,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAElD,kCAAkC,CAAC;QACjC,SAAS;QACT,MAAM;QACN,UAAU;QACV,QAAQ;QACR,MAAM;KACP,CAAC,CAAC;IAEH,OAAO;QACL,OAAO;QACP,QAAQ;QACR,gBAAgB,EAAE,wBAAwB;KAC3C,CAAC;AACJ,CAAC","sourcesContent":["import type { BlobAttachmentDetachRequest } from \"@tearleads/validators/request\";\nimport { signBlobAttachmentDetachEvent } from \"../../data/documents/blob/shared/events\";\nimport { assertBlobAttachmentDetachResponse } from \"../../data/documents/blob/shared/responses\";\nimport type {\n DetachDocumentAttachmentInput,\n DetachDocumentAttachmentResult,\n} from \"../../data/documents/blob/shared/types\";\nimport { authorizingContainerPathRefs } from \"../../data/documents/shared/projection\";\nimport { readCanonicalRecord } from \"../../data/keying/canonicalJson\";\nimport { requireProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { resolveBlobMutationWriterProjection } from \"./verification/writerProjection\";\n\nexport async function detachDocumentAttachment({\n apiClient,\n author,\n bindingId,\n blobId,\n documentId,\n eventId = crypto.randomUUID(),\n execSql,\n isRemoteSyncBlocked,\n resolveProjectionUserKey,\n signedAt = new Date().toISOString(),\n slotId,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n writerProjection,\n}: DetachDocumentAttachmentInput): Promise<DetachDocumentAttachmentResult | null> {\n const resolved = await resolveBlobMutationWriterProjection({\n apiClient,\n documentId,\n errorLabel: \"Blob attachment detach\",\n execSql,\n isRemoteSyncBlocked,\n stillCurrent,\n warmReferencedPrincipalPolicies,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n resolveProjectionUserKey,\n \"Document attachment detach\",\n ),\n writerProjection,\n });\n if (!resolved) {\n return null;\n }\n const { manifestIdentity, writerProjection: resolvedWriterProjection } =\n resolved;\n\n const pathRefs = authorizingContainerPathRefs(resolvedWriterProjection);\n const { body, event } = await signBlobAttachmentDetachEvent({\n author,\n bindingId,\n blobId,\n documentId,\n eventId,\n manifestIdentity,\n signedAt,\n slotId,\n authorizingContainerPathRefs: pathRefs,\n });\n const request: BlobAttachmentDetachRequest = {\n event: readCanonicalRecord(event, \"Blob attachment detach event\"),\n body: readCanonicalRecord(body, \"Blob attachment detach body\"),\n authorizingContainerPathRefs: pathRefs,\n };\n assertProjectionVerificationCurrent(stillCurrent);\n const response = await apiClient.detachBlobAttachment(\n blobId,\n bindingId,\n request,\n {\n expectedPaymentRequiredOrganizationId: manifestIdentity.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n\n assertBlobAttachmentDetachResponse({\n bindingId,\n blobId,\n documentId,\n response,\n slotId,\n });\n\n return {\n request,\n response,\n writerProjection: resolvedWriterProjection,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { deriveBlobChunkIv } from "../../internal/crypto/index.js";
2
- import { contentRecordAdditionalDataBytes } from "../../data/documents/blob/shared/crypto.js";
3
- import { asWebCryptoBytes } from "../../data/documents/shared/readers.js";
1
+ import { deriveBlobChunkIv } from "../../../internal/crypto/index.js";
2
+ import { contentRecordAdditionalDataBytes } from "../../../data/documents/blob/shared/crypto.js";
3
+ import { asWebCryptoBytes } from "../../../data/documents/shared/readers.js";
4
4
  export async function decryptBlobChunk(input) {
5
5
  const { encrypted, expectedBlobId, organizationId, recordKey, chunk } = input;
6
6
  const plaintext = new Uint8Array(await crypto.subtle.decrypt({
@@ -0,0 +1 @@
1
+ {"version":3,"file":"blobChunkDecryption.js","sourceRoot":"","sources":["blobChunkDecryption.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAEtD,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C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E,CAAC;QAC3C,SAAS,CAAC,GAAG,CACX,MAAM,gBAAgB,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,CAAC,EAC3C,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,SAAS,CACxC,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import { deriveBlobChunkIv } from \"@tearleads/crypto\";\nimport type { BlobBytes } from \"../../../data/blobs/blobContracts\";\nimport { contentRecordAdditionalDataBytes } from \"../../../data/documents/blob/shared/crypto\";\nimport type {\n BlobEncryptedBytesHeader,\n BlobEncryptedBytesRecord,\n BlobEncryptedChunk,\n} from \"../../../data/documents/blob/shared/types\";\nimport { asWebCryptoBytes } from \"../../../data/documents/shared/readers\";\n\ninterface BlobChunkDecryption {\n encrypted: BlobEncryptedBytesHeader;\n expectedBlobId: string;\n organizationId: string;\n recordKey: CryptoKey;\n}\n\nexport async function decryptBlobChunk(\n input: BlobChunkDecryption & {\n chunk: BlobEncryptedChunk;\n },\n): Promise<BlobBytes> {\n const { encrypted, expectedBlobId, organizationId, recordKey, chunk } = input;\n const plaintext = new Uint8Array(\n await crypto.subtle.decrypt(\n {\n name: \"AES-GCM\",\n iv: deriveBlobChunkIv(encrypted.iv, chunk.index),\n additionalData: contentRecordAdditionalDataBytes({\n blobId: expectedBlobId,\n chunkCount: encrypted.chunkCount,\n chunkIndex: chunk.index,\n chunkPlaintextByteLength: chunk.plaintextByteLength,\n chunkSize: encrypted.chunkSize,\n contentKeyEpoch: encrypted.contentKeyEpoch,\n contentRecordId: encrypted.contentRecordId,\n metadataHash: encrypted.metadataHash,\n nonceDomainHash: encrypted.nonceDomainHash,\n organizationId,\n plaintextByteLength: encrypted.byteLength,\n }),\n },\n recordKey,\n asWebCryptoBytes(chunk.ciphertext),\n ),\n );\n if (plaintext.byteLength !== chunk.plaintextByteLength)\n throw new Error(\"Blob decrypted chunk byte length mismatch\");\n return plaintext;\n}\n\nexport async function decryptBlobChunks(\n input: Omit<BlobChunkDecryption, \"encrypted\"> & {\n encrypted: BlobEncryptedBytesRecord;\n },\n): Promise<BlobBytes> {\n const decrypted = new Uint8Array(input.encrypted.byteLength);\n for (const chunk of input.encrypted.chunks) {\n decrypted.set(\n await decryptBlobChunk({ ...input, chunk }),\n chunk.index * input.encrypted.chunkSize,\n );\n }\n return decrypted;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { BlobBytes } from "../../data/blobs/blobContracts.js";
2
- import type { BlobEncryptedBytesHeader, DecryptDocumentAttachmentBlobInput } from "../../data/documents/blob/shared/types.js";
1
+ import type { BlobBytes } from "../../../data/blobs/blobContracts.js";
2
+ import type { BlobEncryptedBytesHeader, DecryptDocumentAttachmentBlobInput } from "../../../data/documents/blob/shared/types.js";
3
3
  export type AttachmentBlobDecryptionInput = Omit<DecryptDocumentAttachmentBlobInput, "encryptedBytes"> & {
4
4
  encrypted: BlobEncryptedBytesHeader;
5
5
  };