@tearleads/client-sdk 0.1.64 → 0.1.65

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 (622) hide show
  1. package/client/organizations/organizationAccessRestoration.js +1 -1
  2. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  4. package/data/documents/blob/shared/projection.js +3 -3
  5. package/data/documents/blob/shared/projection.js.map +1 -1
  6. package/data/documents/shared/{containerKekCurrency.d.ts → containerKek/containerKekCurrency.d.ts} +1 -1
  7. package/data/documents/shared/{containerKekEntryVerification.js → containerKek/containerKekEntryVerification.js} +1 -1
  8. package/data/documents/shared/{containerKekLogFetch.d.ts → containerKek/containerKekLogFetch.d.ts} +1 -1
  9. package/data/documents/shared/{containerKekLogFetch.js → containerKek/containerKekLogFetch.js} +1 -1
  10. package/data/documents/shared/{containerKekPath.js → containerKek/containerKekPath.js} +3 -3
  11. package/data/documents/shared/containerKek/containerKekPath.js.map +1 -0
  12. package/data/documents/shared/{containerKekPathHistory.d.ts → containerKek/containerKekPathHistory.d.ts} +3 -3
  13. package/data/documents/shared/{containerKekPathHistory.js → containerKek/containerKekPathHistory.js} +4 -4
  14. package/data/documents/shared/containerKek/containerKekPathHistory.js.map +1 -0
  15. package/data/documents/shared/{containerKekPathVerification.d.ts → containerKek/containerKekPathVerification.d.ts} +5 -5
  16. package/data/documents/shared/{containerKekPathVerification.js → containerKek/containerKekPathVerification.js} +2 -2
  17. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -0
  18. package/data/documents/shared/{containerKekWrapping.js → containerKek/containerKekWrapping.js} +3 -3
  19. package/data/documents/shared/containerKek/containerKekWrapping.js.map +1 -0
  20. package/data/documents/shared/{keyringLogWalk.d.ts → containerKek/keyringLogWalk.d.ts} +2 -2
  21. package/data/documents/shared/{keyringLogWalk.js → containerKek/keyringLogWalk.js} +1 -1
  22. package/data/documents/shared/{keyringRebuild.d.ts → containerKek/keyringRebuild.d.ts} +3 -3
  23. package/data/documents/shared/{keyringRebuild.js → containerKek/keyringRebuild.js} +3 -3
  24. package/data/documents/shared/containerKek/keyringRebuild.js.map +1 -0
  25. package/data/documents/shared/crypto.js +2 -2
  26. package/data/documents/shared/crypto.js.map +1 -1
  27. package/data/documents/shared/events.js +1 -1
  28. package/data/documents/shared/{projection.d.ts → projection/index.d.ts} +7 -7
  29. package/data/documents/shared/{projection.js → projection/index.js} +9 -9
  30. package/data/documents/shared/projection/index.js.map +1 -0
  31. package/data/documents/shared/{projectionContentKeys.d.ts → projection/projectionContentKeys.d.ts} +6 -6
  32. package/data/documents/shared/{projectionContentKeys.js → projection/projectionContentKeys.js} +9 -9
  33. package/data/documents/shared/projection/projectionContentKeys.js.map +1 -0
  34. package/data/documents/shared/{projectionTargets.d.ts → projection/projectionTargets.d.ts} +4 -4
  35. package/data/documents/shared/{projectionTargets.js → projection/projectionTargets.js} +3 -3
  36. package/data/documents/shared/projection/projectionTargets.js.map +1 -0
  37. package/data/documents/shared/responses.d.ts +1 -1
  38. package/data/documents/shared/responses.js +1 -1
  39. package/data/documents/shared/responses.js.map +1 -1
  40. package/data/documents/shared/{documentSyncUpdateDecryption.js → sync/documentSyncUpdateDecryption.js} +10 -10
  41. package/data/documents/shared/sync/documentSyncUpdateDecryption.js.map +1 -0
  42. package/data/documents/shared/{documentSyncUpdateIsolation.d.ts → sync/documentSyncUpdateIsolation.d.ts} +3 -3
  43. package/data/documents/shared/{documentSyncUpdateIsolation.js → sync/documentSyncUpdateIsolation.js} +1 -1
  44. package/data/documents/shared/sync/documentSyncUpdateIsolation.js.map +1 -0
  45. package/data/documents/shared/{mutationAcknowledgement.js → sync/mutationAcknowledgement.js} +1 -1
  46. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -0
  47. package/data/documents/shared/{pullContinuation.js → sync/pullContinuation.js} +1 -1
  48. package/data/documents/shared/{syncPagination.d.ts → sync/syncPagination.d.ts} +2 -2
  49. package/data/documents/shared/{syncPagination.js → sync/syncPagination.js} +1 -1
  50. package/data/documents/shared/sync/syncPagination.js.map +1 -0
  51. package/data/documents/shared/{syncResponseAuthorization.js → sync/syncResponseAuthorization.js} +3 -3
  52. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -0
  53. package/data/documents/shared/{syncResponses.d.ts → sync/syncResponses.d.ts} +2 -2
  54. package/data/documents/shared/{syncResponses.js → sync/syncResponses.js} +6 -6
  55. package/data/documents/shared/sync/syncResponses.js.map +1 -0
  56. package/data/documents/shared/{syncSubmitFailure.d.ts → sync/syncSubmitFailure.d.ts} +1 -1
  57. package/data/documents/shared/types.d.ts +3 -3
  58. package/data/documents/shared/types.js.map +1 -1
  59. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js +1 -1
  60. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
  61. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
  62. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  63. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  64. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js +1 -1
  65. package/data/keyingProjectionVerification/checkpoints/manifestCheckpointVerification.js.map +1 -1
  66. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +4 -4
  67. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  68. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js +1 -1
  69. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointEnforcement.js.map +1 -1
  70. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js +1 -1
  71. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCheckpoints.js.map +1 -1
  72. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js +1 -1
  73. package/data/keyingProjectionVerification/documentPurge/documentPurgePolicyCurrency.js.map +1 -1
  74. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -3
  75. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  76. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
  77. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  78. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +2 -2
  79. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  80. package/data/persistence/container-contents/containerContentsPersistence.js +3 -3
  81. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  82. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -2
  83. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  84. package/data/persistence/container-contents/containerCreateIntentSettlement.js +1 -1
  85. package/data/persistence/container-contents/containerDeletionPersistence.js +2 -2
  86. package/data/persistence/container-contents/containerDocumentReassignment.js +2 -2
  87. package/data/persistence/container-contents/containerDocumentReassignment.js.map +1 -1
  88. package/data/persistence/container-contents/containerHydrationPersistence.js +3 -3
  89. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  90. package/data/persistence/container-contents/containerIntentPersistence.js +1 -1
  91. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -5
  92. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  93. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +1 -1
  94. package/data/persistence/container-contents/containerMetadataRows.js +3 -3
  95. package/data/persistence/container-contents/containerMetadataRows.js.map +1 -1
  96. package/data/persistence/container-contents/containerMoveAbandonPersistence.js +1 -1
  97. package/data/persistence/container-contents/containerMoveIntentRows.js +1 -1
  98. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +3 -3
  99. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  100. package/data/persistence/container-contents/containerRebindPersistence.js +1 -1
  101. package/data/persistence/container-contents/containerReconcilePersistence.js +2 -2
  102. package/data/persistence/container-contents/containerRecoveryPersistence.js +1 -1
  103. package/data/persistence/container-contents/containerRemovalWork.js +3 -3
  104. package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
  105. package/data/persistence/container-contents/containerStructuralRepair.js +1 -1
  106. package/data/persistence/container-contents/documentLinkRemovalRepair.js +2 -2
  107. package/data/persistence/container-contents/documentLinkRemovalRepair.js.map +1 -1
  108. package/data/persistence/container-contents/documentMoveIntentPersistence.js +2 -2
  109. package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
  110. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +2 -2
  111. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
  112. package/data/persistence/container-contents/documentPurgePlacement.js +1 -1
  113. package/data/persistence/container-contents/dormantContainerMetadata.js +1 -1
  114. package/data/persistence/container-contents/dormantMetadataSweep.js +1 -1
  115. package/data/persistence/container-contents/pendingContainerCreate.js +1 -1
  116. package/data/persistence/container-contents/supersededContainerBindings.js +1 -1
  117. package/data/persistence/containers/containerPersistence.js +1 -1
  118. package/data/persistence/containers/containerSyncWatermarkPersistence.js +1 -1
  119. package/data/persistence/containers/documentContainerProjectionPersistence.js +1 -1
  120. package/data/persistence/containers/documentPlacement.js +1 -1
  121. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  122. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +3 -3
  123. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  124. package/data/persistence/documents/documentDiscoveryReset.js +1 -1
  125. package/data/persistence/documents/documentDiscoveryReset.js.map +1 -1
  126. package/data/persistence/documents/documentsPersistence.js +3 -3
  127. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  128. package/data/persistence/documents/internal/attachmentStagingPersistence.js +1 -1
  129. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  130. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  131. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +2 -2
  132. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  133. package/data/persistence/documents/internal/discardDocument.js +3 -3
  134. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  135. package/data/persistence/documents/internal/documentDeletionPersistence.js +4 -4
  136. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  137. package/data/persistence/documents/internal/documentMutationPersistence.js +5 -5
  138. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  139. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  140. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  141. package/data/persistence/documents/internal/documentRows.js +2 -2
  142. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  143. package/data/persistence/documents/internal/documentSummaryQueries.js +1 -1
  144. package/data/persistence/documents/internal/ensureDocumentsSchema.js +2 -2
  145. package/data/persistence/documents/internal/hydratedAttachmentPersistence.js +1 -1
  146. package/data/persistence/documents/internal/orphanSideRows.js +2 -2
  147. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  148. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  149. package/data/persistence/documents/internal/rowQueryPersistence.js +2 -2
  150. package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
  151. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  152. package/data/persistence/documents/types.d.ts +3 -3
  153. package/data/persistence/documents/types.js.map +1 -1
  154. package/data/persistence/{documentPurgeCheckpointPersistence.d.ts → keyingCheckpoints/documentPurgeCheckpointPersistence.d.ts} +2 -2
  155. package/data/persistence/{documentPurgeCheckpointPersistence.js → keyingCheckpoints/documentPurgeCheckpointPersistence.js} +4 -4
  156. package/data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js.map +1 -0
  157. package/data/persistence/{keyingCheckpointAdvancePersistence.js → keyingCheckpoints/keyingCheckpointAdvancePersistence.js} +9 -9
  158. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -0
  159. package/data/persistence/{keyingCheckpointEvidence.js → keyingCheckpoints/keyingCheckpointEvidence.js} +1 -1
  160. package/data/persistence/{keyingCheckpointPersistence.js → keyingCheckpoints/keyingCheckpointPersistence.js} +5 -5
  161. package/data/persistence/keyingCheckpoints/keyingCheckpointPersistence.js.map +1 -0
  162. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.d.ts → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts} +4 -4
  163. package/data/persistence/{locallyAcknowledgedCheckpointPersistence.js → keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js} +7 -7
  164. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -0
  165. package/data/persistence/{organizationReplacementCheckpointPersistence.js → keyingCheckpoints/organizationReplacementCheckpointPersistence.js} +6 -6
  166. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -0
  167. package/data/persistence/{principalAuthorizationCheckpoints.js → keyingCheckpoints/principalAuthorizationCheckpoints.js} +1 -1
  168. package/data/persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js.map +1 -0
  169. package/data/persistence/organizationFounderPersistence.js +2 -2
  170. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  171. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +3 -3
  172. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  173. package/data/persistence/organizations/organizationDataUsagePersistence.js +2 -2
  174. package/data/persistence/organizations/organizationDataUsagePersistence.js.map +1 -1
  175. package/data/persistence/organizations/organizationGroupNamePersistence.js +2 -2
  176. package/data/persistence/organizations/organizationGroupNamePersistence.js.map +1 -1
  177. package/data/persistence/organizations/organizationPresentationDenialPersistence.js +2 -2
  178. package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
  179. package/data/persistence/organizations/organizationProfileDocumentPointers.js +2 -2
  180. package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +1 -1
  181. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js +1 -1
  182. package/data/persistence/organizations/organizationProvisioningAttemptPersistence.js.map +1 -1
  183. package/data/persistence/organizations/organizationReadModelGrantPersistence.js +1 -1
  184. package/data/persistence/organizations/organizationReadModelGrantPersistence.js.map +1 -1
  185. package/data/persistence/organizations/organizationReadModelMemberLoad.js +1 -1
  186. package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
  187. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js +1 -1
  188. package/data/persistence/organizations/organizationReadModelMembershipPersistence.js.map +1 -1
  189. package/data/persistence/organizations/organizationReadModelPersistence.js +3 -3
  190. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  191. package/data/persistence/organizations/organizationReadModelProjection.js +1 -1
  192. package/data/persistence/organizations/organizationReadModelProjection.js.map +1 -1
  193. package/data/persistence/organizations/organizationReadModelPurge.js +3 -3
  194. package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
  195. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +3 -3
  196. package/data/persistence/principalCurrentAcknowledgementPersistence.js +10 -10
  197. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  198. package/data/persistence/{principalHistoryEvidencePersistence.d.ts → principalHistory/principalHistoryEvidencePersistence.d.ts} +4 -4
  199. package/data/persistence/{principalHistoryEvidencePersistence.js → principalHistory/principalHistoryEvidencePersistence.js} +7 -7
  200. package/data/persistence/principalHistory/principalHistoryEvidencePersistence.js.map +1 -0
  201. package/data/persistence/{principalHistoryIncompleteRetention.js → principalHistory/principalHistoryIncompleteRetention.js} +1 -1
  202. package/data/persistence/principalHistory/principalHistoryIncompleteRetention.js.map +1 -0
  203. package/data/persistence/{principalHistoryNodeRetention.js → principalHistory/principalHistoryNodeRetention.js} +4 -4
  204. package/data/persistence/principalHistory/principalHistoryNodeRetention.js.map +1 -0
  205. package/data/persistence/{principalHistoryPrefixPersistence.d.ts → principalHistory/principalHistoryPrefixPersistence.d.ts} +2 -2
  206. package/data/persistence/{principalHistoryPrefixPersistence.js → principalHistory/principalHistoryPrefixPersistence.js} +6 -6
  207. package/data/persistence/principalHistory/principalHistoryPrefixPersistence.js.map +1 -0
  208. package/data/persistence/{principalHistoryRootOwnership.js → principalHistory/principalHistoryRootOwnership.js} +1 -1
  209. package/data/persistence/principalHistory/principalHistoryRootOwnership.js.map +1 -0
  210. package/data/persistence/{principalHistoryStagePersistence.d.ts → principalHistory/principalHistoryStagePersistence.d.ts} +2 -2
  211. package/data/persistence/{principalHistoryStagePersistence.js → principalHistory/principalHistoryStagePersistence.js} +6 -6
  212. package/data/persistence/principalHistory/principalHistoryStagePersistence.js.map +1 -0
  213. package/data/persistence/{principalHistoryStageRetention.js → principalHistory/principalHistoryStageRetention.js} +2 -2
  214. package/data/persistence/principalHistory/principalHistoryStageRetention.js.map +1 -0
  215. package/data/persistence/{principalHistoryUnpublishedRetention.js → principalHistory/principalHistoryUnpublishedRetention.js} +3 -3
  216. package/data/persistence/principalHistory/principalHistoryUnpublishedRetention.js.map +1 -0
  217. package/data/persistence/{principalGrantRetirementPersistence.d.ts → principalKeys/principalGrantRetirementPersistence.d.ts} +2 -2
  218. package/data/persistence/{principalGrantRetirementPersistence.js → principalKeys/principalGrantRetirementPersistence.js} +2 -2
  219. package/data/persistence/principalKeys/principalGrantRetirementPersistence.js.map +1 -0
  220. package/data/persistence/{principalKeyEnvelopeArchivePersistence.js → principalKeys/principalKeyEnvelopeArchivePersistence.js} +3 -3
  221. package/data/persistence/principalKeys/principalKeyEnvelopeArchivePersistence.js.map +1 -0
  222. package/data/persistence/{principalKeyEnvelopeCandidates.js → principalKeys/principalKeyEnvelopeCandidates.js} +9 -9
  223. package/data/persistence/principalKeys/principalKeyEnvelopeCandidates.js.map +1 -0
  224. package/data/persistence/principalMutationJournalPersistence.d.ts +1 -1
  225. package/data/persistence/principalMutationJournalPersistence.js +1 -1
  226. package/data/persistence/principalMutationJournalPersistence.js.map +1 -1
  227. package/data/persistence/{principalPolicyBundleIntegrity.js → principalPolicy/principalPolicyBundleIntegrity.js} +3 -3
  228. package/data/persistence/principalPolicy/principalPolicyBundleIntegrity.js.map +1 -0
  229. package/data/persistence/{principalPolicyCheckpointSelection.js → principalPolicy/principalPolicyCheckpointSelection.js} +2 -2
  230. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  231. package/data/persistence/{principalPolicyOrganizationPersistence.js → principalPolicy/principalPolicyOrganizationPersistence.js} +2 -2
  232. package/data/persistence/principalPolicy/principalPolicyOrganizationPersistence.js.map +1 -0
  233. package/data/persistence/{principalPolicyPersistence.js → principalPolicy/principalPolicyPersistence.js} +5 -5
  234. package/data/persistence/principalPolicy/principalPolicyPersistence.js.map +1 -0
  235. package/data/persistence/{principalPolicyReferenceCheckpoint.js → principalPolicy/principalPolicyReferenceCheckpoint.js} +3 -3
  236. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -0
  237. package/data/persistence/{principalPolicyReferenceIndexPersistence.js → principalPolicy/principalPolicyReferenceIndexPersistence.js} +4 -4
  238. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -0
  239. package/data/persistence/{principalPolicyReferencePersistence.js → principalPolicy/principalPolicyReferencePersistence.js} +5 -5
  240. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -0
  241. package/data/persistence/{verifiedPrincipalPolicyBundle.js → principalPolicy/verifiedPrincipalPolicyBundle.js} +2 -2
  242. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundle.js.map +1 -0
  243. package/data/persistence/{verifiedPrincipalPolicyCurrent.js → principalPolicy/verifiedPrincipalPolicyCurrent.js} +2 -2
  244. package/data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js.map +1 -0
  245. package/data/persistence/{verifiedPrincipalPolicyRetentionPersistence.js → principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js} +1 -1
  246. package/data/persistence/principalPolicy/verifiedPrincipalPolicyRetentionPersistence.js.map +1 -0
  247. package/data/persistence/securityIncidentPersistence.js +1 -1
  248. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  249. package/data/persistence/trustedUserIdentityPinPersistence.js +1 -1
  250. package/data/persistence/verifiedManifestBundlePersistence.d.ts +1 -1
  251. package/data/persistence/verifiedManifestBundlePersistence.js +4 -4
  252. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  253. package/data/principals/organizationGroupRoles.js +2 -2
  254. package/data/principals/organizationGroupRoles.js.map +1 -1
  255. package/data/principals/principalHistoryPrefixProtection.js.map +1 -1
  256. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  257. package/data/principals/principalPolicyCrypto.js +1 -1
  258. package/data/principals/principalPolicyCrypto.js.map +1 -1
  259. package/data/sqlite/{documentHistoryPersistence.d.ts → documentPersistence/documentHistoryPersistence.d.ts} +1 -1
  260. package/data/sqlite/{documentHistoryPersistence.js → documentPersistence/documentHistoryPersistence.js} +5 -5
  261. package/data/sqlite/documentPersistence/documentHistoryPersistence.js.map +1 -0
  262. package/data/sqlite/{documentOrphanBlobReclaims.js → documentPersistence/documentOrphanBlobReclaims.js} +1 -1
  263. package/data/sqlite/documentPersistence/documentOrphanBlobReclaims.js.map +1 -0
  264. package/data/sqlite/{documentPendingUpdatePersistence.d.ts → documentPersistence/documentPendingUpdatePersistence.d.ts} +2 -2
  265. package/data/sqlite/{documentPendingUpdatePersistence.js → documentPersistence/documentPendingUpdatePersistence.js} +2 -2
  266. package/data/sqlite/documentPersistence/documentPendingUpdatePersistence.js.map +1 -0
  267. package/data/sqlite/{documentPersistenceTypes.d.ts → documentPersistence/documentPersistenceTypes.d.ts} +2 -2
  268. package/data/sqlite/documentPersistence/documentPersistenceTypes.js.map +1 -0
  269. package/data/sqlite/{documentRecordPersistence.d.ts → documentPersistence/documentRecordPersistence.d.ts} +1 -1
  270. package/data/sqlite/{documentRecordPersistence.js → documentPersistence/documentRecordPersistence.js} +4 -4
  271. package/data/sqlite/documentPersistence/documentRecordPersistence.js.map +1 -0
  272. package/data/sqlite/{documentSyncFailurePersistence.d.ts → documentPersistence/documentSyncFailurePersistence.d.ts} +2 -2
  273. package/data/sqlite/{documentSyncFailurePersistence.js → documentPersistence/documentSyncFailurePersistence.js} +3 -3
  274. package/data/sqlite/documentPersistence/documentSyncFailurePersistence.js.map +1 -0
  275. package/data/sqlite/{documentPersistence.d.ts → documentPersistence/index.d.ts} +2 -2
  276. package/data/sqlite/{documentPersistence.js → documentPersistence/index.js} +5 -5
  277. package/data/sqlite/documentPersistence/index.js.map +1 -0
  278. package/data/sqlite/{containerSchema.d.ts → schema/containerSchema.d.ts} +1 -1
  279. package/data/sqlite/{containerSchema.js → schema/containerSchema.js} +1 -1
  280. package/data/sqlite/schema/containerSchema.js.map +1 -0
  281. package/data/sqlite/{schema.d.ts → schema/index.d.ts} +1 -1
  282. package/data/sqlite/{schema.js → schema/index.js} +3 -3
  283. package/data/sqlite/schema/index.js.map +1 -0
  284. package/data/sqlite/{organizationDataUsageSchema.js → schema/organizationDataUsageSchema.js} +1 -1
  285. package/data/sqlite/schema/organizationDataUsageSchema.js.map +1 -0
  286. package/data/sqlite/{organizationProvisioningAttemptSchema.js → schema/organizationProvisioningAttemptSchema.js} +1 -1
  287. package/data/sqlite/schema/organizationProvisioningAttemptSchema.js.map +1 -0
  288. package/data/sqlite/{organizationReadModelTableRegistry.d.ts → schema/organizationReadModelTableRegistry.d.ts} +1 -1
  289. package/data/sqlite/{organizationReadModelTableRegistry.js → schema/organizationReadModelTableRegistry.js} +1 -1
  290. package/data/sqlite/schema/organizationReadModelTableRegistry.js.map +1 -0
  291. package/data/sqlite/{principalHistoryEvidenceSchema.d.ts → schema/principalHistoryEvidenceSchema.d.ts} +1 -1
  292. package/data/sqlite/{principalHistoryEvidenceSchema.js → schema/principalHistoryEvidenceSchema.js} +2 -2
  293. package/data/sqlite/schema/principalHistoryEvidenceSchema.js.map +1 -0
  294. package/data/sqlite/{principalHistoryNodeRetentionSchema.js → schema/principalHistoryNodeRetentionSchema.js} +1 -1
  295. package/data/sqlite/schema/principalHistoryNodeRetentionSchema.js.map +1 -0
  296. package/data/sqlite/{principalHistoryRetentionSchema.js → schema/principalHistoryRetentionSchema.js} +1 -1
  297. package/data/sqlite/{principalHistoryRetentionSchema.js.map → schema/principalHistoryRetentionSchema.js.map} +1 -1
  298. package/data/sqlite/{principalHistoryStageSchema.d.ts → schema/principalHistoryStageSchema.d.ts} +1 -1
  299. package/data/sqlite/{principalHistoryStageSchema.js → schema/principalHistoryStageSchema.js} +2 -2
  300. package/data/sqlite/schema/principalHistoryStageSchema.js.map +1 -0
  301. package/data/sqlite/{principalMutationJournalSchema.d.ts → schema/principalMutationJournalSchema.d.ts} +1 -1
  302. package/data/sqlite/{principalMutationJournalSchema.js → schema/principalMutationJournalSchema.js} +1 -1
  303. package/data/sqlite/{principalMutationJournalSchema.js.map → schema/principalMutationJournalSchema.js.map} +1 -1
  304. package/data/sqlite/{principalPolicySchema.js → schema/principalPolicySchema.js} +1 -1
  305. package/data/sqlite/schema/principalPolicySchema.js.map +1 -0
  306. package/data/sqlite/{securityIncidentSchema.d.ts → schema/securityIncidentSchema.d.ts} +1 -1
  307. package/data/sqlite/{securityIncidentSchema.js → schema/securityIncidentSchema.js} +1 -1
  308. package/data/sqlite/schema/securityIncidentSchema.js.map +1 -0
  309. package/data/sqlite/{verifiedManifestBundleSchema.d.ts → schema/verifiedManifestBundleSchema.d.ts} +1 -1
  310. package/data/sqlite/{verifiedManifestBundleSchema.js → schema/verifiedManifestBundleSchema.js} +1 -1
  311. package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -0
  312. package/data/sqlite/sqlitePersistenceRuntime.d.ts +1 -1
  313. package/data/sqlite/sqlitePersistenceRuntime.js +1 -1
  314. package/package.json +1 -1
  315. package/sqlite/index.d.ts +1 -1
  316. package/sqlite/index.js +1 -1
  317. package/stores/documents/documentStore/history/historyRebuild.js +1 -1
  318. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
  319. package/stores/documents/documentStore/state.js.map +1 -1
  320. package/stores/documents/documentStore/sync/syncFinalize.js +1 -1
  321. package/stores/documents/documentStore/sync/syncFinalize.js.map +1 -1
  322. package/stores/documents/documentStore/sync/syncUpdateImport.js +1 -1
  323. package/stores/documents/documentStore/sync/syncUpdateImport.js.map +1 -1
  324. package/workflows/blobs/detach.js +1 -1
  325. package/workflows/blobs/hydration/decrypt.js +1 -1
  326. package/workflows/blobs/upload/index.js +1 -1
  327. package/workflows/blobs/verification/retainedAttachmentVerification.js +1 -1
  328. package/workflows/blobs/verification/writerProjection.js +1 -1
  329. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  330. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  331. package/workflows/container-contents/container-state/share/index.js +1 -1
  332. package/workflows/container-contents/documentLinks/index.js +1 -1
  333. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +1 -1
  334. package/workflows/container-contents/documentPriming/documentHydrationProbe.js +1 -1
  335. package/workflows/container-contents/documentPriming/index.js +1 -1
  336. package/workflows/container-contents/documentQueries/index.js +1 -1
  337. package/workflows/container-contents/documentQueries/sql.js +1 -1
  338. package/workflows/container-contents/info/blobInfo.js +1 -1
  339. package/workflows/container-contents/info/containerInfo.js +1 -1
  340. package/workflows/container-contents/info/documentInfo.js +1 -1
  341. package/workflows/container-contents/metadata/index.js +1 -1
  342. package/workflows/container-contents/metadata/index.js.map +1 -1
  343. package/workflows/container-contents/metadata/metadataEvents.d.ts +1 -1
  344. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  345. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  346. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  347. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  348. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  349. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  350. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +1 -1
  351. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  352. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  353. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  354. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  355. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  356. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  357. package/workflows/container-contents/pendingWrites/index.js +2 -2
  358. package/workflows/container-contents/pendingWrites/sources.js +1 -1
  359. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js +1 -1
  360. package/workflows/container-contents/remoteHydration/destination/replacementBinding.js.map +1 -1
  361. package/workflows/container-contents/remoteHydration/reattachMetadata.js.map +1 -1
  362. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +2 -2
  363. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  364. package/workflows/containers/child/create/index.js +2 -2
  365. package/workflows/containers/child/create/index.js.map +1 -1
  366. package/workflows/containers/child/move/index.js +1 -1
  367. package/workflows/containers/child/move/moveRotation.js +1 -1
  368. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  369. package/workflows/containers/child/move/moveWraps.js +1 -1
  370. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  371. package/workflows/containers/child/recite.js +2 -2
  372. package/workflows/containers/child/recite.js.map +1 -1
  373. package/workflows/containers/child/rotation/rotationContext.js +3 -3
  374. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  375. package/workflows/containers/child/share/currentSharePrincipalPolicy.js +1 -1
  376. package/workflows/containers/child/share/currentSharePrincipalPolicy.js.map +1 -1
  377. package/workflows/containers/child/share/index.js +1 -1
  378. package/workflows/containers/child/share/index.js.map +1 -1
  379. package/workflows/containers/child/share/shareAncestorRepair.js +2 -2
  380. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  381. package/workflows/containers/child/share/shareMaterialization.js +1 -1
  382. package/workflows/containers/child/share/sharePrincipalPolicy.js +5 -5
  383. package/workflows/containers/child/share/sharePrincipalPolicy.js.map +1 -1
  384. package/workflows/containers/index.d.ts +3 -3
  385. package/workflows/containers/index.js +2 -2
  386. package/workflows/containers/index.js.map +1 -1
  387. package/workflows/containers/writeRefusal.js +1 -1
  388. package/workflows/containers/writeRefusal.js.map +1 -1
  389. package/workflows/documents/create/createAdoption.js +1 -1
  390. package/workflows/documents/create/createResponse.js +2 -2
  391. package/workflows/documents/create/createResponse.js.map +1 -1
  392. package/workflows/documents/create/index.js +1 -1
  393. package/workflows/documents/documentMutationCommit.d.ts +1 -1
  394. package/workflows/documents/documentMutationPreparation.d.ts +1 -1
  395. package/workflows/documents/documentMutationPreparation.js +1 -1
  396. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  397. package/workflows/documents/index.d.ts +5 -5
  398. package/workflows/documents/index.js +5 -5
  399. package/workflows/documents/index.js.map +1 -1
  400. package/workflows/documents/linkSet/index.js +2 -2
  401. package/workflows/documents/linkSet/index.js.map +1 -1
  402. package/workflows/documents/linkSet/linkSetAuthority.js +1 -1
  403. package/workflows/documents/linkSet/linkSetBlobRewraps.js +1 -1
  404. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  405. package/workflows/documents/linkSet/linkSetRemote.js +1 -1
  406. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  407. package/workflows/documents/purge/index.js +1 -1
  408. package/workflows/documents/sync/index.js +2 -2
  409. package/workflows/documents/sync/index.js.map +1 -1
  410. package/workflows/documents/sync/initialSync.js +1 -1
  411. package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
  412. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
  413. package/workflows/documents/sync/readOnlySync.d.ts +3 -3
  414. package/workflows/documents/sync/readOnlySync.js +1 -1
  415. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  416. package/workflows/documents/sync/reportDocumentSyncQuarantine.js.map +1 -1
  417. package/workflows/documents/sync/syncAttemptPlanning.js +2 -2
  418. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  419. package/workflows/documents/sync/syncAttemptState.d.ts +2 -2
  420. package/workflows/documents/sync/syncAttemptState.js.map +1 -1
  421. package/workflows/documents/sync/syncResponseResult.js +2 -2
  422. package/workflows/documents/sync/syncResponseResult.js.map +1 -1
  423. package/workflows/documents/syncFailures/index.js +1 -1
  424. package/workflows/documents/syncFailures/index.js.map +1 -1
  425. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  426. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -1
  427. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  428. package/workflows/documents/syncPlan/syncContentKeys.d.ts +1 -1
  429. package/workflows/documents/syncPlan/syncContentKeys.js +3 -3
  430. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  431. package/workflows/documents/syncPlan/syncPlanMaterial.js +2 -2
  432. package/workflows/documents/syncPlan/syncPlanMaterial.js.map +1 -1
  433. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +2 -2
  434. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  435. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +1 -1
  436. package/workflows/documents/syncRekeys/syncRecoveryRekey.d.ts +1 -1
  437. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +1 -1
  438. package/workflows/organizations/currentOrganizationAuthority.js +2 -2
  439. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  440. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  441. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  442. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +1 -1
  443. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  444. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  445. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  446. package/workflows/organizations/groupNames/groupNameUniqueness.js +3 -3
  447. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  448. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  449. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  450. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  451. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  452. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  453. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  454. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js +1 -1
  455. package/workflows/organizations/groupPolicy/groupPolicyMutationEvidence.js.map +1 -1
  456. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  457. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  458. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  459. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  460. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  461. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  462. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  463. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  464. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +1 -1
  465. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  466. package/workflows/organizations/provisioning/organizationReplacementVerification.js +1 -1
  467. package/workflows/organizations/provisioning/organizationReplacementVerification.js.map +1 -1
  468. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  469. package/workflows/organizations/readModel/localReadModelDetails.js +1 -1
  470. package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
  471. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  472. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  473. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.d.ts +1 -1
  474. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +1 -1
  475. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  476. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  477. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  478. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  479. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  480. package/workflows/principals/externalAdminPolicy.js +2 -2
  481. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  482. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js +2 -2
  483. package/workflows/principals/historyRecovery/loadRecoveredPrincipalHistoryPage.js.map +1 -1
  484. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js +1 -1
  485. package/workflows/principals/historyRecovery/principalHistoryRecoveryPrefix.js.map +1 -1
  486. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  487. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  488. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js +1 -1
  489. package/workflows/principals/historyRecovery/principalHistoryRecoveryStage.js.map +1 -1
  490. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +3 -3
  491. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  492. package/workflows/principals/policyCache/index.js +3 -3
  493. package/workflows/principals/policyCache/index.js.map +1 -1
  494. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  495. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  496. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +3 -3
  497. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  498. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  499. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +2 -2
  500. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  501. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +3 -3
  502. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  503. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.d.ts +2 -2
  504. package/workflows/principals/publicHistory/publicPrincipalHistoryTypes.js.map +1 -1
  505. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  506. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  507. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +1 -1
  508. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  509. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  510. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  511. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  512. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  513. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js +1 -1
  514. package/workflows/principals/recoveryOperation/principalRecoveryMemoValidity.js.map +1 -1
  515. package/workflows/registration/persistRegistrationBootstrap.d.ts +2 -2
  516. package/workflows/registration/persistRegistrationBootstrap.js +2 -2
  517. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  518. package/workflows/registration/provisioningAcknowledgement.js +1 -1
  519. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  520. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  521. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  522. package/workflows/sync/remoteReset.js +7 -7
  523. package/workflows/sync/remoteReset.js.map +1 -1
  524. package/workflows/sync/remoteResetAttachments.js +1 -1
  525. package/workflows/sync/remoteResetCursorScope.js +1 -1
  526. package/workflows/sync/remoteResetPlans.js +1 -1
  527. package/workflows/sync/remoteResetPrincipalScope.js +5 -5
  528. package/workflows/sync/remoteResetPrincipalScope.js.map +1 -1
  529. package/workflows/sync/remoteResetScope.js +1 -1
  530. package/data/documents/shared/containerKekPath.js.map +0 -1
  531. package/data/documents/shared/containerKekPathHistory.js.map +0 -1
  532. package/data/documents/shared/containerKekPathVerification.js.map +0 -1
  533. package/data/documents/shared/containerKekWrapping.js.map +0 -1
  534. package/data/documents/shared/documentSyncUpdateDecryption.js.map +0 -1
  535. package/data/documents/shared/documentSyncUpdateIsolation.js.map +0 -1
  536. package/data/documents/shared/keyringRebuild.js.map +0 -1
  537. package/data/documents/shared/mutationAcknowledgement.js.map +0 -1
  538. package/data/documents/shared/projection.js.map +0 -1
  539. package/data/documents/shared/projectionContentKeys.js.map +0 -1
  540. package/data/documents/shared/projectionTargets.js.map +0 -1
  541. package/data/documents/shared/syncPagination.js.map +0 -1
  542. package/data/documents/shared/syncResponseAuthorization.js.map +0 -1
  543. package/data/documents/shared/syncResponses.js.map +0 -1
  544. package/data/persistence/documentPurgeCheckpointPersistence.js.map +0 -1
  545. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +0 -1
  546. package/data/persistence/keyingCheckpointPersistence.js.map +0 -1
  547. package/data/persistence/locallyAcknowledgedCheckpointPersistence.js.map +0 -1
  548. package/data/persistence/organizationReplacementCheckpointPersistence.js.map +0 -1
  549. package/data/persistence/principalAuthorizationCheckpoints.js.map +0 -1
  550. package/data/persistence/principalGrantRetirementPersistence.js.map +0 -1
  551. package/data/persistence/principalHistoryEvidencePersistence.js.map +0 -1
  552. package/data/persistence/principalHistoryIncompleteRetention.js.map +0 -1
  553. package/data/persistence/principalHistoryNodeRetention.js.map +0 -1
  554. package/data/persistence/principalHistoryPrefixPersistence.js.map +0 -1
  555. package/data/persistence/principalHistoryRootOwnership.js.map +0 -1
  556. package/data/persistence/principalHistoryStagePersistence.js.map +0 -1
  557. package/data/persistence/principalHistoryStageRetention.js.map +0 -1
  558. package/data/persistence/principalHistoryUnpublishedRetention.js.map +0 -1
  559. package/data/persistence/principalKeyEnvelopeArchivePersistence.js.map +0 -1
  560. package/data/persistence/principalKeyEnvelopeCandidates.js.map +0 -1
  561. package/data/persistence/principalPolicyBundleIntegrity.js.map +0 -1
  562. package/data/persistence/principalPolicyCheckpointSelection.js.map +0 -1
  563. package/data/persistence/principalPolicyOrganizationPersistence.js.map +0 -1
  564. package/data/persistence/principalPolicyPersistence.js.map +0 -1
  565. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +0 -1
  566. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +0 -1
  567. package/data/persistence/principalPolicyReferencePersistence.js.map +0 -1
  568. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +0 -1
  569. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +0 -1
  570. package/data/persistence/verifiedPrincipalPolicyRetentionPersistence.js.map +0 -1
  571. package/data/sqlite/containerSchema.js.map +0 -1
  572. package/data/sqlite/documentHistoryPersistence.js.map +0 -1
  573. package/data/sqlite/documentOrphanBlobReclaims.js.map +0 -1
  574. package/data/sqlite/documentPendingUpdatePersistence.js.map +0 -1
  575. package/data/sqlite/documentPersistence.js.map +0 -1
  576. package/data/sqlite/documentPersistenceTypes.js.map +0 -1
  577. package/data/sqlite/documentRecordPersistence.js.map +0 -1
  578. package/data/sqlite/documentSyncFailurePersistence.js.map +0 -1
  579. package/data/sqlite/organizationDataUsageSchema.js.map +0 -1
  580. package/data/sqlite/organizationProvisioningAttemptSchema.js.map +0 -1
  581. package/data/sqlite/organizationReadModelTableRegistry.js.map +0 -1
  582. package/data/sqlite/principalHistoryEvidenceSchema.js.map +0 -1
  583. package/data/sqlite/principalHistoryNodeRetentionSchema.js.map +0 -1
  584. package/data/sqlite/principalHistoryStageSchema.js.map +0 -1
  585. package/data/sqlite/principalPolicySchema.js.map +0 -1
  586. package/data/sqlite/schema.js.map +0 -1
  587. package/data/sqlite/securityIncidentSchema.js.map +0 -1
  588. package/data/sqlite/verifiedManifestBundleSchema.js.map +0 -1
  589. /package/data/documents/shared/{containerKekCurrency.js → containerKek/containerKekCurrency.js} +0 -0
  590. /package/data/documents/shared/{containerKekCurrency.js.map → containerKek/containerKekCurrency.js.map} +0 -0
  591. /package/data/documents/shared/{containerKekEntryVerification.js.map → containerKek/containerKekEntryVerification.js.map} +0 -0
  592. /package/data/documents/shared/{containerKekLogFetch.js.map → containerKek/containerKekLogFetch.js.map} +0 -0
  593. /package/data/documents/shared/{containerKekPath.d.ts → containerKek/containerKekPath.d.ts} +0 -0
  594. /package/data/documents/shared/{keyringLogWalk.js.map → containerKek/keyringLogWalk.js.map} +0 -0
  595. /package/data/documents/shared/{pullContinuation.d.ts → sync/pullContinuation.d.ts} +0 -0
  596. /package/data/documents/shared/{pullContinuation.js.map → sync/pullContinuation.js.map} +0 -0
  597. /package/data/documents/shared/{syncSubmitFailure.js → sync/syncSubmitFailure.js} +0 -0
  598. /package/data/documents/shared/{syncSubmitFailure.js.map → sync/syncSubmitFailure.js.map} +0 -0
  599. /package/data/persistence/{keyingCheckpointEvidence.js.map → keyingCheckpoints/keyingCheckpointEvidence.js.map} +0 -0
  600. /package/data/persistence/{storedPrincipalPolicyBundle.js → principalPolicy/storedPrincipalPolicyBundle.js} +0 -0
  601. /package/data/persistence/{storedPrincipalPolicyBundle.js.map → principalPolicy/storedPrincipalPolicyBundle.js.map} +0 -0
  602. /package/data/sqlite/{documentPersistenceTypes.js → documentPersistence/documentPersistenceTypes.js} +0 -0
  603. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.d.ts → schema/containerDocumentTombstoneHoldSchema.d.ts} +0 -0
  604. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js → schema/containerDocumentTombstoneHoldSchema.js} +0 -0
  605. /package/data/sqlite/{containerDocumentTombstoneHoldSchema.js.map → schema/containerDocumentTombstoneHoldSchema.js.map} +0 -0
  606. /package/data/sqlite/{documentAttachmentSchema.d.ts → schema/documentAttachmentSchema.d.ts} +0 -0
  607. /package/data/sqlite/{documentAttachmentSchema.js → schema/documentAttachmentSchema.js} +0 -0
  608. /package/data/sqlite/{documentAttachmentSchema.js.map → schema/documentAttachmentSchema.js.map} +0 -0
  609. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js → schema/documentDiscoveryEvidenceSchema.js} +0 -0
  610. /package/data/sqlite/{documentDiscoveryEvidenceSchema.js.map → schema/documentDiscoveryEvidenceSchema.js.map} +0 -0
  611. /package/data/sqlite/{documentPlacementIntentSchema.js → schema/documentPlacementIntentSchema.js} +0 -0
  612. /package/data/sqlite/{documentPlacementIntentSchema.js.map → schema/documentPlacementIntentSchema.js.map} +0 -0
  613. /package/data/sqlite/{localIntentSchema.d.ts → schema/localIntentSchema.d.ts} +0 -0
  614. /package/data/sqlite/{localIntentSchema.js → schema/localIntentSchema.js} +0 -0
  615. /package/data/sqlite/{localIntentSchema.js.map → schema/localIntentSchema.js.map} +0 -0
  616. /package/data/sqlite/{organizationFounderSchema.js → schema/organizationFounderSchema.js} +0 -0
  617. /package/data/sqlite/{organizationFounderSchema.js.map → schema/organizationFounderSchema.js.map} +0 -0
  618. /package/data/sqlite/{organizationReadModelSchema.js → schema/organizationReadModelSchema.js} +0 -0
  619. /package/data/sqlite/{organizationReadModelSchema.js.map → schema/organizationReadModelSchema.js.map} +0 -0
  620. /package/data/sqlite/{principalGrantRetirementSchema.js → schema/principalGrantRetirementSchema.js} +0 -0
  621. /package/data/sqlite/{principalGrantRetirementSchema.js.map → schema/principalGrantRetirementSchema.js.map} +0 -0
  622. /package/data/sqlite/{principalPolicySchema.d.ts → schema/principalPolicySchema.d.ts}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,CAAC;IACZ,MAAM,kBAAkB,GACtB,QAAQ,EAAE,YAAY,IAAI,IAAI;QAC9B,QAAQ,CAAC,KAAK,IAAI,IAAI;QACtB,QAAQ,CAAC,SAAS,IAAI,IAAI;QACxB,CAAC,CAAC;YACE,YAAY,EAAE,QAAQ,CAAC,YAAY;YACnC,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,KAAK,EAAE,QAAQ,CAAC,KAAK;YACrB,SAAS,EAAE,QAAQ,CAAC,SAAS;SAC9B;QACH,CAAC,CAAC,SAAS,CAAC;IAChB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACrC,OAAO,8BAA8B,CACnC,QAAQ;QACN,CAAC,CAAC;YACE,YAAY,EAAE,yBAAyB,CAAC,kBAAkB,CAAC;YAC3D,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;YAC/C,IAAI,EAAE,iBAAiB,CAAC,kBAAkB,CAAC;YAC3C,KAAK,EAAE,kBAAkB,CAAC,kBAAkB,CAAC;SAC9C;QACH,CAAC,CAAC,IAAI,EACR,QAAQ,CACT;QACC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC;AACxD,CAAC","sourcesContent":["import { and, eq, lte } from \"drizzle-orm\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport { deriveStoredDocumentTitle } from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport type { DocumentScope } from \"../../../sqlite/documentPersistence\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { DOCUMENTS_APP_KIND } from \"./constants\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n const existingProjection =\n existing?.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
1
+ {"version":3,"file":"document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,EAAE,YAAY,IAAI,IAAI;QAC9B,QAAQ,CAAC,KAAK,IAAI,IAAI;QACtB,QAAQ,CAAC,SAAS,IAAI,IAAI;QACxB,CAAC,CAAC;YACE,YAAY,EAAE,QAAQ,CAAC,YAAY;YACnC,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,KAAK,EAAE,QAAQ,CAAC,KAAK;YACrB,SAAS,EAAE,QAAQ,CAAC,SAAS;SAC9B;QACH,CAAC,CAAC,SAAS,CAAC;IAChB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACrC,OAAO,8BAA8B,CACnC,QAAQ;QACN,CAAC,CAAC;YACE,YAAY,EAAE,yBAAyB,CAAC,kBAAkB,CAAC;YAC3D,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;YAC/C,IAAI,EAAE,iBAAiB,CAAC,kBAAkB,CAAC;YAC3C,KAAK,EAAE,kBAAkB,CAAC,kBAAkB,CAAC;SAC9C;QACH,CAAC,CAAC,IAAI,EACR,QAAQ,CACT;QACC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC;AACxD,CAAC","sourcesContent":["import { and, eq, lte } from \"drizzle-orm\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport { deriveStoredDocumentTitle } from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport type { DocumentScope } from \"../../../sqlite/documentPersistence\";\nimport {\n documentProjection,\n documentProjectionText,\n documents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { DOCUMENTS_APP_KIND } from \"./constants\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n const existingProjection =\n existing?.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { and, asc, count, desc, eq, notInArray, sql, } from "drizzle-orm";
2
2
  import { HIDDEN_DOCUMENT_SUMMARY_KINDS } from "../../../documents/documentSummary.js";
3
- import { documentProjection, documents } from "../../../sqlite/schema.js";
3
+ import { documentProjection, documents } from "../../../sqlite/schema/index.js";
4
4
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { documentSummaryJoin, documentSummarySelection, mapDocumentSummary, } from "./documentProjectionRows.js";
6
6
  const DEFAULT_DOCUMENT_SUMMARY_SORT = {
@@ -1,5 +1,5 @@
1
- import { ensureDocumentProjectionTables, ensureDocumentTables, } from "../../../sqlite/documentPersistence.js";
2
- import { documentContainerProjectionTables, documentPlacementIntentTables, keyingCheckpointTables, } from "../../../sqlite/schema.js";
1
+ import { ensureDocumentProjectionTables, ensureDocumentTables, } from "../../../sqlite/documentPersistence/index.js";
2
+ import { documentContainerProjectionTables, documentPlacementIntentTables, keyingCheckpointTables, } from "../../../sqlite/schema/index.js";
3
3
  import { ensureSqlTables, runOncePerConnection, runSerializedSqlMutation, } from "../../../sqlite/sqlSchema.js";
4
4
  export async function ensureDocumentsSchema(execSql) {
5
5
  await runOncePerConnection(execSql, "ensure:documents", () => runSerializedSqlMutation(execSql, async (lockedExecSql) => {
@@ -1,5 +1,5 @@
1
1
  import { and, eq } from "drizzle-orm";
2
- import { documentAttachmentBlobProjection, documents, } from "../../../sqlite/schema.js";
2
+ import { documentAttachmentBlobProjection, documents, } from "../../../sqlite/schema/index.js";
3
3
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
4
4
  import { queueDocumentAttachmentStorageKeys } from "./orphanSideRows.js";
5
5
  export const saveHydratedAttachment = async (execSql, input) => {
@@ -1,6 +1,6 @@
1
1
  import { and, asc, eq, inArray, isNotNull, lt, notExists, or, } from "drizzle-orm";
2
- import { documentOrphanBlobReclaims } from "../../../sqlite/documentOrphanBlobReclaims.js";
3
- import { documentAttachmentBlobProjection, documentHistoryCheckpoints, documentHistoryUpdates, documentPendingAttachments, documents, } from "../../../sqlite/schema.js";
2
+ import { documentOrphanBlobReclaims } from "../../../sqlite/documentPersistence/documentOrphanBlobReclaims.js";
3
+ import { documentAttachmentBlobProjection, documentHistoryCheckpoints, documentHistoryUpdates, documentPendingAttachments, documents, } from "../../../sqlite/schema/index.js";
4
4
  import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { runSerializedSqlMutation, } from "../../../sqlite/sqlSchema.js";
6
6
  import { DOCUMENTS_APP_KIND } from "./constants.js";
@@ -1 +1 @@
1
- {"version":3,"file":"orphanSideRows.js","sourceRoot":"","sources":["orphanSideRows.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,GAAG,EACH,EAAE,EACF,OAAO,EACP,SAAS,EACT,EAAE,EACF,SAAS,EACT,EAAE,GAEH,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,0BAA0B,EAAE,MAAM,4CAA4C,CAAC;AACxF,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,sBAAsB,EACtB,0BAA0B,EAC1B,SAAS,GACV,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,6EAA6E;AAC7E,4EAA4E;AAC5E,MAAM,gCAAgC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7D,MAAM,gCAAgC,GAAG,EAAE,CAAC;AAQ5C,SAAS,gBAAgB,CAAC,SAA0B;IAClD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,aAAa,CACpB,EAAgC,EAChC,OAAkC,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0B,CAAC;aAChC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;aAC5D,KAAK,CAAC,CAAC,CAAC;QACX,EAAE;aACC,MAAM,CAAC,EAAE,UAAU,EAAE,gCAAgC,CAAC,UAAU,EAAE,CAAC;aACnE,IAAI,CAAC,gCAAgC,CAAC;aACtC,KAAK,CAAC,EAAE,CAAC,gCAAgC,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;aAClE,KAAK,CAAC,CAAC,CAAC;KACZ,CAAC,CAAC;IACH,OAAO,WAAW,CAAC,MAAM,GAAG,CAAC,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAgB,EAChB,UAAkB;IAElB,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,EAAE;SACL,MAAM,CAAC,0BAA0B,CAAC;SAClC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SAC5D,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import {\n and,\n asc,\n eq,\n inArray,\n isNotNull,\n lt,\n notExists,\n or,\n type SQL,\n} from \"drizzle-orm\";\nimport { documentOrphanBlobReclaims } from \"../../../sqlite/documentOrphanBlobReclaims\";\nimport {\n documentAttachmentBlobProjection,\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentPendingAttachments,\n documents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport { DOCUMENTS_APP_KIND } from \"./constants\";\n\n// Crash residue gets a full day to outlive slow devices and wall-clock skew;\n// canonical-row absence is necessary but never sufficient for fresh writes.\nconst DOCUMENT_ORPHAN_SWEEP_MIN_AGE_MS = 24 * 60 * 60 * 1000;\nconst DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE = 32;\n\ntype DocumentSideLocalIdColumn =\n | typeof documentAttachmentBlobProjection.localId\n | typeof documentHistoryCheckpoints.localId\n | typeof documentHistoryUpdates.localId\n | typeof documentPendingAttachments.localId;\n\nfunction requirePredicate(predicate: SQL | undefined): SQL {\n if (!predicate) {\n throw new Error(\"Document orphan cleanup requires a SQL predicate\");\n }\n return predicate;\n}\n\nfunction hasNoDocument(\n tx: ClientSQLiteTransactionScope,\n localId: DocumentSideLocalIdColumn,\n appKind: string | null = DOCUMENTS_APP_KIND,\n): SQL {\n return notExists(\n tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n appKind === null\n ? eq(documents.localId, localId)\n : and(eq(documents.appKind, appKind), eq(documents.localId, localId)),\n ),\n );\n}\n\nexport async function queueDocumentAttachmentBlobReclaims(input: {\n localWhere: SQL;\n pendingWhere: SQL;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { localWhere, pendingWhere, tx } = input;\n const [pendingAttachmentRows, localAttachmentRows] = await Promise.all([\n tx\n .select({ storageKey: documentPendingAttachments.storageKey })\n .from(documentPendingAttachments)\n .where(pendingWhere),\n tx\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(localWhere),\n ]);\n const storageKeys = [\n ...new Set(\n [...pendingAttachmentRows, ...localAttachmentRows].map(\n (row) => row.storageKey,\n ),\n ),\n ];\n await queueDocumentAttachmentStorageKeys(tx, storageKeys);\n}\n\nexport async function queueDocumentAttachmentStorageKeys(\n tx: ClientSQLiteTransactionScope,\n storageKeys: ReadonlyArray<string>,\n): Promise<void> {\n if (storageKeys.length > 0) {\n await tx\n .insert(documentOrphanBlobReclaims)\n .values(storageKeys.map((storageKey) => ({ storageKey })))\n .onConflictDoNothing()\n .run();\n }\n}\n\ninterface AttachmentSweepCandidate {\n localId: string;\n slotId: string;\n storageKey: string;\n}\n\nfunction pendingAttachmentCandidatesWhere(\n candidates: ReadonlyArray<AttachmentSweepCandidate>,\n): SQL {\n return requirePredicate(\n or(\n ...candidates.map((candidate) =>\n and(\n eq(documentPendingAttachments.localId, candidate.localId),\n eq(documentPendingAttachments.slotId, candidate.slotId),\n ),\n ),\n ),\n );\n}\n\nfunction localAttachmentCandidatesWhere(\n candidates: ReadonlyArray<AttachmentSweepCandidate>,\n): SQL {\n return requirePredicate(\n or(\n ...candidates.map((candidate) =>\n and(\n eq(documentAttachmentBlobProjection.localId, candidate.localId),\n eq(documentAttachmentBlobProjection.slotId, candidate.slotId),\n ),\n ),\n ),\n );\n}\n\ninterface HistorySweepCandidates {\n checkpoints: ReadonlyArray<{ localId: string }>;\n updates: ReadonlyArray<{ id: string | null }>;\n}\n\ninterface AttachmentSweepCandidates {\n local: ReadonlyArray<AttachmentSweepCandidate>;\n pending: ReadonlyArray<AttachmentSweepCandidate>;\n}\n\nasync function selectHistorySweepCandidates(\n tx: ClientSQLiteTransactionScope,\n olderThan: string,\n): Promise<HistorySweepCandidates> {\n const checkpoints = await tx\n .select({ localId: documentHistoryCheckpoints.localId })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, DOCUMENTS_APP_KIND),\n lt(documentHistoryCheckpoints.updatedAt, olderThan),\n hasNoDocument(tx, documentHistoryCheckpoints.localId),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n const updates = await tx\n .select({ id: documentHistoryUpdates.id })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, DOCUMENTS_APP_KIND),\n isNotNull(documentHistoryUpdates.id),\n lt(documentHistoryUpdates.createdAt, olderThan),\n hasNoDocument(tx, documentHistoryUpdates.localId),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n return { checkpoints, updates };\n}\n\nasync function selectAttachmentSweepCandidates(\n tx: ClientSQLiteTransactionScope,\n olderThan: string,\n): Promise<AttachmentSweepCandidates> {\n const pending = await tx\n .select({\n localId: documentPendingAttachments.localId,\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n })\n .from(documentPendingAttachments)\n .where(\n and(\n lt(documentPendingAttachments.createdAt, olderThan),\n hasNoDocument(tx, documentPendingAttachments.localId, null),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n const local = await tx\n .select({\n localId: documentAttachmentBlobProjection.localId,\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n })\n .from(documentAttachmentBlobProjection)\n .where(\n and(\n lt(documentAttachmentBlobProjection.updatedAt, olderThan),\n hasNoDocument(tx, documentAttachmentBlobProjection.localId, null),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n return { local, pending };\n}\n\nasync function deleteHistorySweepCandidates(\n tx: ClientSQLiteTransactionScope,\n candidates: HistorySweepCandidates,\n): Promise<void> {\n if (candidates.checkpoints.length > 0) {\n await tx\n .delete(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, DOCUMENTS_APP_KIND),\n inArray(\n documentHistoryCheckpoints.localId,\n candidates.checkpoints.map((row) => row.localId),\n ),\n ),\n )\n .run();\n }\n if (candidates.updates.length > 0) {\n await tx\n .delete(documentHistoryUpdates)\n .where(\n inArray(\n documentHistoryUpdates.id,\n candidates.updates.flatMap((row) =>\n row.id === null ? [] : [row.id],\n ),\n ),\n )\n .run();\n }\n}\n\nasync function deleteAttachmentSweepCandidates(\n tx: ClientSQLiteTransactionScope,\n candidates: AttachmentSweepCandidates,\n): Promise<void> {\n await queueDocumentAttachmentStorageKeys(tx, [\n ...new Set(\n [...candidates.pending, ...candidates.local].map((row) => row.storageKey),\n ),\n ]);\n if (candidates.pending.length > 0) {\n await tx\n .delete(documentPendingAttachments)\n .where(pendingAttachmentCandidatesWhere(candidates.pending))\n .run();\n }\n if (candidates.local.length > 0) {\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(localAttachmentCandidatesWhere(candidates.local))\n .run();\n }\n}\n\nfunction hasFullSweepBatch(\n history: HistorySweepCandidates,\n attachments: AttachmentSweepCandidates,\n): boolean {\n return [\n history.checkpoints,\n history.updates,\n attachments.pending,\n attachments.local,\n ].some((rows) => rows.length === DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n}\n\n/** Remove one bounded batch of aged side writes without a canonical row. */\nexport async function deleteOrphanedDocumentSideRows(\n execSql: ExecSql,\n options: { now?: Date | undefined } = {},\n): Promise<boolean> {\n const olderThan = new Date(\n (options.now?.getTime() ?? Date.now()) - DOCUMENT_ORPHAN_SWEEP_MIN_AGE_MS,\n ).toISOString();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {\n const history = await selectHistorySweepCandidates(tx, olderThan);\n const attachments = await selectAttachmentSweepCandidates(tx, olderThan);\n await deleteHistorySweepCandidates(tx, history);\n await deleteAttachmentSweepCandidates(tx, attachments);\n return hasFullSweepBatch(history, attachments);\n }),\n );\n}\n\nexport async function listDocumentOrphanBlobReclaims(\n execSql: ExecSql,\n limit: number,\n): Promise<ReadonlyArray<string>> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ storageKey: documentOrphanBlobReclaims.storageKey })\n .from(documentOrphanBlobReclaims)\n .orderBy(asc(documentOrphanBlobReclaims.storageKey))\n .limit(limit);\n return rows.map((row) => row.storageKey);\n}\n\nexport async function isDocumentBlobStorageKeyReferenced(\n execSql: ExecSql,\n storageKey: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [pendingRows, localRows] = await Promise.all([\n db\n .select({ storageKey: documentPendingAttachments.storageKey })\n .from(documentPendingAttachments)\n .where(eq(documentPendingAttachments.storageKey, storageKey))\n .limit(1),\n db\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.storageKey, storageKey))\n .limit(1),\n ]);\n return pendingRows.length > 0 || localRows.length > 0;\n}\n\nexport async function acknowledgeDocumentOrphanBlobReclaim(\n execSql: ExecSql,\n storageKey: string,\n): Promise<void> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n await db\n .delete(documentOrphanBlobReclaims)\n .where(eq(documentOrphanBlobReclaims.storageKey, storageKey))\n .run();\n}\n"]}
1
+ {"version":3,"file":"orphanSideRows.js","sourceRoot":"","sources":["orphanSideRows.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,GAAG,EACH,GAAG,EACH,EAAE,EACF,OAAO,EACP,SAAS,EACT,EAAE,EACF,SAAS,EACT,EAAE,GAEH,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,sBAAsB,EACtB,0BAA0B,EAC1B,SAAS,GACV,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,6EAA6E;AAC7E,4EAA4E;AAC5E,MAAM,gCAAgC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7D,MAAM,gCAAgC,GAAG,EAAE,CAAC;AAQ5C,SAAS,gBAAgB,CAAC,SAA0B;IAClD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,aAAa,CACpB,EAAgC,EAChC,OAAkC,EAClC,UAAyB,k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,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;aAC5D,KAAK,CAAC,CAAC,CAAC;QACX,EAAE;aACC,MAAM,CAAC,EAAE,UAAU,EAAE,gCAAgC,CAAC,UAAU,EAAE,CAAC;aACnE,IAAI,CAAC,gCAAgC,CAAC;aACtC,KAAK,CAAC,EAAE,CAAC,gCAAgC,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;aAClE,KAAK,CAAC,CAAC,CAAC;KACZ,CAAC,CAAC;IACH,OAAO,WAAW,CAAC,MAAM,GAAG,CAAC,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAgB,EAChB,UAAkB;IAElB,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,EAAE;SACL,MAAM,CAAC,0BAA0B,CAAC;SAClC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SAC5D,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import {\n and,\n asc,\n eq,\n inArray,\n isNotNull,\n lt,\n notExists,\n or,\n type SQL,\n} from \"drizzle-orm\";\nimport { documentOrphanBlobReclaims } from \"../../../sqlite/documentPersistence/documentOrphanBlobReclaims\";\nimport {\n documentAttachmentBlobProjection,\n documentHistoryCheckpoints,\n documentHistoryUpdates,\n documentPendingAttachments,\n documents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport { DOCUMENTS_APP_KIND } from \"./constants\";\n\n// Crash residue gets a full day to outlive slow devices and wall-clock skew;\n// canonical-row absence is necessary but never sufficient for fresh writes.\nconst DOCUMENT_ORPHAN_SWEEP_MIN_AGE_MS = 24 * 60 * 60 * 1000;\nconst DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE = 32;\n\ntype DocumentSideLocalIdColumn =\n | typeof documentAttachmentBlobProjection.localId\n | typeof documentHistoryCheckpoints.localId\n | typeof documentHistoryUpdates.localId\n | typeof documentPendingAttachments.localId;\n\nfunction requirePredicate(predicate: SQL | undefined): SQL {\n if (!predicate) {\n throw new Error(\"Document orphan cleanup requires a SQL predicate\");\n }\n return predicate;\n}\n\nfunction hasNoDocument(\n tx: ClientSQLiteTransactionScope,\n localId: DocumentSideLocalIdColumn,\n appKind: string | null = DOCUMENTS_APP_KIND,\n): SQL {\n return notExists(\n tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n appKind === null\n ? eq(documents.localId, localId)\n : and(eq(documents.appKind, appKind), eq(documents.localId, localId)),\n ),\n );\n}\n\nexport async function queueDocumentAttachmentBlobReclaims(input: {\n localWhere: SQL;\n pendingWhere: SQL;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { localWhere, pendingWhere, tx } = input;\n const [pendingAttachmentRows, localAttachmentRows] = await Promise.all([\n tx\n .select({ storageKey: documentPendingAttachments.storageKey })\n .from(documentPendingAttachments)\n .where(pendingWhere),\n tx\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(localWhere),\n ]);\n const storageKeys = [\n ...new Set(\n [...pendingAttachmentRows, ...localAttachmentRows].map(\n (row) => row.storageKey,\n ),\n ),\n ];\n await queueDocumentAttachmentStorageKeys(tx, storageKeys);\n}\n\nexport async function queueDocumentAttachmentStorageKeys(\n tx: ClientSQLiteTransactionScope,\n storageKeys: ReadonlyArray<string>,\n): Promise<void> {\n if (storageKeys.length > 0) {\n await tx\n .insert(documentOrphanBlobReclaims)\n .values(storageKeys.map((storageKey) => ({ storageKey })))\n .onConflictDoNothing()\n .run();\n }\n}\n\ninterface AttachmentSweepCandidate {\n localId: string;\n slotId: string;\n storageKey: string;\n}\n\nfunction pendingAttachmentCandidatesWhere(\n candidates: ReadonlyArray<AttachmentSweepCandidate>,\n): SQL {\n return requirePredicate(\n or(\n ...candidates.map((candidate) =>\n and(\n eq(documentPendingAttachments.localId, candidate.localId),\n eq(documentPendingAttachments.slotId, candidate.slotId),\n ),\n ),\n ),\n );\n}\n\nfunction localAttachmentCandidatesWhere(\n candidates: ReadonlyArray<AttachmentSweepCandidate>,\n): SQL {\n return requirePredicate(\n or(\n ...candidates.map((candidate) =>\n and(\n eq(documentAttachmentBlobProjection.localId, candidate.localId),\n eq(documentAttachmentBlobProjection.slotId, candidate.slotId),\n ),\n ),\n ),\n );\n}\n\ninterface HistorySweepCandidates {\n checkpoints: ReadonlyArray<{ localId: string }>;\n updates: ReadonlyArray<{ id: string | null }>;\n}\n\ninterface AttachmentSweepCandidates {\n local: ReadonlyArray<AttachmentSweepCandidate>;\n pending: ReadonlyArray<AttachmentSweepCandidate>;\n}\n\nasync function selectHistorySweepCandidates(\n tx: ClientSQLiteTransactionScope,\n olderThan: string,\n): Promise<HistorySweepCandidates> {\n const checkpoints = await tx\n .select({ localId: documentHistoryCheckpoints.localId })\n .from(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, DOCUMENTS_APP_KIND),\n lt(documentHistoryCheckpoints.updatedAt, olderThan),\n hasNoDocument(tx, documentHistoryCheckpoints.localId),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n const updates = await tx\n .select({ id: documentHistoryUpdates.id })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, DOCUMENTS_APP_KIND),\n isNotNull(documentHistoryUpdates.id),\n lt(documentHistoryUpdates.createdAt, olderThan),\n hasNoDocument(tx, documentHistoryUpdates.localId),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n return { checkpoints, updates };\n}\n\nasync function selectAttachmentSweepCandidates(\n tx: ClientSQLiteTransactionScope,\n olderThan: string,\n): Promise<AttachmentSweepCandidates> {\n const pending = await tx\n .select({\n localId: documentPendingAttachments.localId,\n slotId: documentPendingAttachments.slotId,\n storageKey: documentPendingAttachments.storageKey,\n })\n .from(documentPendingAttachments)\n .where(\n and(\n lt(documentPendingAttachments.createdAt, olderThan),\n hasNoDocument(tx, documentPendingAttachments.localId, null),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n const local = await tx\n .select({\n localId: documentAttachmentBlobProjection.localId,\n slotId: documentAttachmentBlobProjection.slotId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n })\n .from(documentAttachmentBlobProjection)\n .where(\n and(\n lt(documentAttachmentBlobProjection.updatedAt, olderThan),\n hasNoDocument(tx, documentAttachmentBlobProjection.localId, null),\n ),\n )\n .limit(DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n return { local, pending };\n}\n\nasync function deleteHistorySweepCandidates(\n tx: ClientSQLiteTransactionScope,\n candidates: HistorySweepCandidates,\n): Promise<void> {\n if (candidates.checkpoints.length > 0) {\n await tx\n .delete(documentHistoryCheckpoints)\n .where(\n and(\n eq(documentHistoryCheckpoints.appKind, DOCUMENTS_APP_KIND),\n inArray(\n documentHistoryCheckpoints.localId,\n candidates.checkpoints.map((row) => row.localId),\n ),\n ),\n )\n .run();\n }\n if (candidates.updates.length > 0) {\n await tx\n .delete(documentHistoryUpdates)\n .where(\n inArray(\n documentHistoryUpdates.id,\n candidates.updates.flatMap((row) =>\n row.id === null ? [] : [row.id],\n ),\n ),\n )\n .run();\n }\n}\n\nasync function deleteAttachmentSweepCandidates(\n tx: ClientSQLiteTransactionScope,\n candidates: AttachmentSweepCandidates,\n): Promise<void> {\n await queueDocumentAttachmentStorageKeys(tx, [\n ...new Set(\n [...candidates.pending, ...candidates.local].map((row) => row.storageKey),\n ),\n ]);\n if (candidates.pending.length > 0) {\n await tx\n .delete(documentPendingAttachments)\n .where(pendingAttachmentCandidatesWhere(candidates.pending))\n .run();\n }\n if (candidates.local.length > 0) {\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(localAttachmentCandidatesWhere(candidates.local))\n .run();\n }\n}\n\nfunction hasFullSweepBatch(\n history: HistorySweepCandidates,\n attachments: AttachmentSweepCandidates,\n): boolean {\n return [\n history.checkpoints,\n history.updates,\n attachments.pending,\n attachments.local,\n ].some((rows) => rows.length === DOCUMENT_ORPHAN_SWEEP_BATCH_SIZE);\n}\n\n/** Remove one bounded batch of aged side writes without a canonical row. */\nexport async function deleteOrphanedDocumentSideRows(\n execSql: ExecSql,\n options: { now?: Date | undefined } = {},\n): Promise<boolean> {\n const olderThan = new Date(\n (options.now?.getTime() ?? Date.now()) - DOCUMENT_ORPHAN_SWEEP_MIN_AGE_MS,\n ).toISOString();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {\n const history = await selectHistorySweepCandidates(tx, olderThan);\n const attachments = await selectAttachmentSweepCandidates(tx, olderThan);\n await deleteHistorySweepCandidates(tx, history);\n await deleteAttachmentSweepCandidates(tx, attachments);\n return hasFullSweepBatch(history, attachments);\n }),\n );\n}\n\nexport async function listDocumentOrphanBlobReclaims(\n execSql: ExecSql,\n limit: number,\n): Promise<ReadonlyArray<string>> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ storageKey: documentOrphanBlobReclaims.storageKey })\n .from(documentOrphanBlobReclaims)\n .orderBy(asc(documentOrphanBlobReclaims.storageKey))\n .limit(limit);\n return rows.map((row) => row.storageKey);\n}\n\nexport async function isDocumentBlobStorageKeyReferenced(\n execSql: ExecSql,\n storageKey: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const [pendingRows, localRows] = await Promise.all([\n db\n .select({ storageKey: documentPendingAttachments.storageKey })\n .from(documentPendingAttachments)\n .where(eq(documentPendingAttachments.storageKey, storageKey))\n .limit(1),\n db\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.storageKey, storageKey))\n .limit(1),\n ]);\n return pendingRows.length > 0 || localRows.length > 0;\n}\n\nexport async function acknowledgeDocumentOrphanBlobReclaim(\n execSql: ExecSql,\n storageKey: string,\n): Promise<void> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n await db\n .delete(documentOrphanBlobReclaims)\n .where(eq(documentOrphanBlobReclaims.storageKey, storageKey))\n .run();\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { and, eq, isNull } from "drizzle-orm";
2
2
  import { deriveStableDocumentId } from "../../../documents/shared/stableDocumentId.js";
3
- import { documentProjection, documents } from "../../../sqlite/schema.js";
3
+ import { documentProjection, documents } from "../../../sqlite/schema/index.js";
4
4
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
5
5
  import { DOCUMENTS_APP_KIND } from "./constants.js";
6
6
  import { documentSummaryJoin, documentSummarySelection, mapDocumentSummary, } from "./documentProjectionRows.js";
@@ -1,7 +1,7 @@
1
1
  import { desc, eq, notInArray } from "drizzle-orm";
2
2
  import { HIDDEN_DOCUMENT_SUMMARY_KINDS } from "../../../documents/documentSummary.js";
3
- import { findLocalIdByDocumentId, loadDocumentRecord, } from "../../../sqlite/documentPersistence.js";
4
- import { documentProjection, documentProjectionText, documents, } from "../../../sqlite/schema.js";
3
+ import { findLocalIdByDocumentId, loadDocumentRecord, } from "../../../sqlite/documentPersistence/index.js";
4
+ import { documentProjection, documentProjectionText, documents, } from "../../../sqlite/schema/index.js";
5
5
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
6
6
  import { DOCUMENTS_APP_KIND } from "./constants.js";
7
7
  import { documentSummaryJoin, documentSummarySelection, getProjectionContainerId, getProjectionDocumentKind, getProjectionText, getProjectionTitle, mapDocumentSummary, } from "./documentProjectionRows.js";
@@ -1,7 +1,7 @@
1
1
  import { and, eq, isNull } from "drizzle-orm";
2
- import { appendDocumentHistoryUpdates, listDocumentHistoryTailEntries, loadDocumentHistoryRestoreState, readDocumentHistoryTailSize, replaceDocumentHistoryCheckpoint, } from "../../../sqlite/documentHistoryPersistence.js";
3
- import { enqueueDocumentPendingUpdateWithHistory, listDocumentPendingUpdates, rekeyDocumentPendingUpdate, settleDocumentPendingUpdate, unqueueDocumentPendingUpdates, } from "../../../sqlite/documentPersistence.js";
4
- import { documentAttachmentBlobProjection, documentPendingAttachments, } from "../../../sqlite/schema.js";
2
+ import { enqueueDocumentPendingUpdateWithHistory, listDocumentPendingUpdates, rekeyDocumentPendingUpdate, settleDocumentPendingUpdate, unqueueDocumentPendingUpdates, } from "../../../sqlite/documentPersistence/index.js";
3
+ import { appendDocumentHistoryUpdates, listDocumentHistoryTailEntries, loadDocumentHistoryRestoreState, readDocumentHistoryTailSize, replaceDocumentHistoryCheckpoint, } from "../../../sqlite/documentPersistence/documentHistoryPersistence.js";
4
+ import { documentAttachmentBlobProjection, documentPendingAttachments, } from "../../../sqlite/schema/index.js";
5
5
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
6
6
  import { runSerializedSqlMutation } from "../../../sqlite/sqlSchema.js";
7
7
  import { buildPendingAttachmentRow, mapLocalAttachmentRecord, mapPendingAttachmentRecord, } from "./attachmentRows.js";
@@ -1 +1 @@
1
- {"version":3,"file":"syncQueuePersistence.js","sourceRoot":"","sources":["syncQueuePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EACL,4BAA4B,EAC5B,8BAA8B,EAC9B,+BAA+B,EAC/B,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,uCAAuC,EACvC,0BAA0B,EAC1B,0BAA0B,EAC1B,2BAA2B,EAC3B,6BAA6B,GA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ailEntries,\n loadDocumentHistoryRestoreState,\n readDocumentHistoryTailSize,\n replaceDocumentHistoryCheckpoint,\n} from \"../../../sqlite/documentHistoryPersistence\";\nimport {\n enqueueDocumentPendingUpdateWithHistory,\n listDocumentPendingUpdates,\n rekeyDocumentPendingUpdate,\n settleDocumentPendingUpdate,\n unqueueDocumentPendingUpdates,\n} from \"../../../sqlite/documentPersistence\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentsPersistence } from \"../types\";\nimport {\n buildPendingAttachmentRow,\n mapLocalAttachmentRecord,\n mapPendingAttachmentRecord,\n} from \"./attachmentRows\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\ntype DocumentSyncQueuePersistence = Pick<\n DocumentsPersistence,\n | \"listPendingUpdates\"\n | \"rekeyPendingUpdate\"\n | \"listPendingAttachments\"\n | \"listLocalAttachments\"\n | \"appendHistoryUpdates\"\n | \"loadHistoryRestoreState\"\n | \"readHistoryTailSize\"\n | \"listHistoryTailEntries\"\n | \"replaceHistoryCheckpoint\"\n | \"enqueuePendingUpdate\"\n | \"saveLocalAttachment\"\n | \"deleteLocalAttachment\"\n | \"markLocalAttachmentDetached\"\n | \"savePendingAttachment\"\n | \"deletePendingUpdate\"\n | \"deletePendingUpdates\"\n | \"deletePendingAttachment\"\n | \"deletePendingAttachments\"\n>;\n\nexport const documentSyncQueuePersistence: DocumentSyncQueuePersistence = {\n async listPendingUpdates(execSql, localId) {\n return listDocumentPendingUpdates(execSql, getDocumentScope(localId));\n },\n async rekeyPendingUpdate(execSql, id) {\n return rekeyDocumentPendingUpdate(execSql, id);\n },\n async listPendingAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentPendingAttachments.localId,\n slotId: documentPendingAttachments.slotId,\n name: documentPendingAttachments.name,\n mimeType: documentPendingAttachments.mimeType,\n storageKey: documentPendingAttachments.storageKey,\n byteLength: documentPendingAttachments.byteLength,\n contentSha256: documentPendingAttachments.contentSha256,\n uploadBlobId: documentPendingAttachments.uploadBlobId,\n uploadContentKey: documentPendingAttachments.uploadContentKey,\n uploadIv: documentPendingAttachments.uploadIv,\n uploadContentKeyEpoch: documentPendingAttachments.uploadContentKeyEpoch,\n uploadPartSize: documentPendingAttachments.uploadPartSize,\n uploadPlaintextSha256: documentPendingAttachments.uploadPlaintextSha256,\n uploadStageId: documentPendingAttachments.uploadStageId,\n })\n .from(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .orderBy(\n documentPendingAttachments.createdAt,\n documentPendingAttachments.slotId,\n );\n\n return rows.map(mapPendingAttachmentRecord);\n },\n // Detached rows are included on purpose: they are the durable markers the\n // next sync uses to detach the remote binding, so a restart has to restore\n // them alongside the live slots.\n async listLocalAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentAttachmentBlobProjection.localId,\n slotId: documentAttachmentBlobProjection.slotId,\n blobId: documentAttachmentBlobProjection.blobId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n mimeType: documentAttachmentBlobProjection.mimeType,\n byteLength: documentAttachmentBlobProjection.byteLength,\n contentSha256: documentAttachmentBlobProjection.contentSha256,\n detachedAt: documentAttachmentBlobProjection.detachedAt,\n })\n .from(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId));\n\n return rows.map(mapLocalAttachmentRecord);\n },\n async appendHistoryUpdates(execSql, input) {\n await appendDocumentHistoryUpdates(\n execSql,\n getDocumentScope(input.localId),\n input.updates,\n input.origin,\n );\n },\n async loadHistoryRestoreState(execSql, localId) {\n return loadDocumentHistoryRestoreState(execSql, getDocumentScope(localId));\n },\n async readHistoryTailSize(execSql, localId) {\n return readDocumentHistoryTailSize(execSql, getDocumentScope(localId));\n },\n async listHistoryTailEntries(execSql, localId) {\n return listDocumentHistoryTailEntries(execSql, getDocumentScope(localId));\n },\n async replaceHistoryCheckpoint(execSql, input) {\n await replaceDocumentHistoryCheckpoint(\n execSql,\n getDocumentScope(input.localId),\n {\n coveredTailIds: input.coveredTailIds,\n endVersionVector: input.endVersionVector,\n ...(input.force === undefined ? {} : { force: input.force }),\n snapshot: input.snapshot,\n ...(input.stillCurrent === undefined\n ? {}\n : { stillCurrent: input.stillCurrent }),\n },\n );\n },\n async enqueuePendingUpdate(execSql, pendingUpdate, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const pendingUpdateId = await enqueueDocumentPendingUpdateWithHistory(\n lockedExecSql,\n getDocumentScope(pendingUpdate.localId),\n pendingUpdate,\n options,\n );\n return pendingUpdateId !== null;\n });\n },\n async saveLocalAttachment(execSql, attachment) {\n const updatedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = {\n localId: attachment.localId,\n slotId: attachment.slotId,\n blobId: attachment.blobId,\n storageKey: attachment.storageKey,\n mimeType: attachment.mimeType,\n byteLength: attachment.byteLength,\n contentSha256: attachment.contentSha256,\n updatedAt,\n // Written on every save so re-filling a slot clears a stale detach\n // marker instead of inheriting it from the row it replaces.\n detachedAt: attachment.detachedAt,\n };\n await db\n .insert(documentAttachmentBlobProjection)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentAttachmentBlobProjection.localId,\n documentAttachmentBlobProjection.slotId,\n ],\n set: attachmentRow,\n })\n .run();\n });\n },\n async deleteLocalAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n ),\n )\n .run();\n // Another slot may hold the same hydrated copy; the reclaim deletes\n // the bytes only once no row references them.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async markLocalAttachmentDetached(execSql, localId, slotId, storageKey) {\n const detachedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documentAttachmentBlobProjection)\n .set({ detachedAt })\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n isNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n });\n },\n async savePendingAttachment(execSql, attachment) {\n const createdAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = buildPendingAttachmentRow(attachment, createdAt);\n await db\n .insert(documentPendingAttachments)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentPendingAttachments.localId,\n documentPendingAttachments.slotId,\n ],\n set: {\n name: attachmentRow.name,\n mimeType: attachmentRow.mimeType,\n storageKey: attachmentRow.storageKey,\n byteLength: attachmentRow.byteLength,\n contentSha256: attachmentRow.contentSha256,\n uploadBlobId: attachmentRow.uploadBlobId,\n uploadContentKey: attachmentRow.uploadContentKey,\n uploadIv: attachmentRow.uploadIv,\n uploadContentKeyEpoch: attachmentRow.uploadContentKeyEpoch,\n uploadPartSize: attachmentRow.uploadPartSize,\n uploadPlaintextSha256: attachmentRow.uploadPlaintextSha256,\n uploadStageId: attachmentRow.uploadStageId,\n },\n })\n .run();\n });\n },\n async deletePendingUpdate(execSql, id) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await settleDocumentPendingUpdate(lockedExecSql, id);\n });\n },\n async deletePendingUpdates(execSql, localId) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await unqueueDocumentPendingUpdates(\n lockedExecSql,\n getDocumentScope(localId),\n );\n });\n },\n async deletePendingAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentPendingAttachments)\n .where(\n and(\n eq(documentPendingAttachments.localId, localId),\n eq(documentPendingAttachments.slotId, slotId),\n eq(documentPendingAttachments.storageKey, storageKey),\n ),\n )\n .run();\n // A dropped upload may hold the last reference to its staged bytes.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async deletePendingAttachments(execSql, localId) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n const deleted = await db\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .returning({ storageKey: documentPendingAttachments.storageKey });\n await queueDocumentAttachmentStorageKeys(\n db,\n deleted.map(({ storageKey }) => storageKey),\n );\n });\n },\n};\n"]}
1
+ {"version":3,"file":"syncQueuePersistence.js","sourceRoot":"","sources":["syncQueuePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EACL,uCAAuC,EACvC,0BAA0B,EAC1B,0BAA0B,EAC1B,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,4BAA4B,EAC5B,8BAA8B,EAC9B,+BAA+B,EAC/B,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,gEAAgE,CAAC;AACxE,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAErE,OAAO,EACL,yBAAyB,EACzB,wBAAwB,EACxB,0BAA0B,GAC3B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO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AAC,EAC/C,EAAE,CAAC,0BAA0B,CAAC,MAAM,EAAE,MAAM,CAAC,EAC7C,EAAE,CAAC,0BAA0B,CAAC,UAAU,EAAE,UAAU,CAAC,CACtD,CACF;iBACA,GAAG,EAAE,CAAC;YACT,oEAAoE;YACpE,MAAM,kCAAkC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;QAC7D,CAAC,CAAC,CAAC;IACL,CAAC;IACD,KAAK,CAAC,wBAAwB,CAAC,OAAO,EAAE,OAAO;QAC7C,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;YACxE,MAAM,OAAO,GAAG,MAAM,EAAE;iBACrB,MAAM,CAAC,0BAA0B,CAAC;iBAClC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;iBACtD,SAAS,CAAC,EAAE,UAAU,EAAE,0BAA0B,CAAC,UAAU,EAAE,CAAC,CAAC;YACpE,MAAM,kCAAkC,CACtC,EAAE,EACF,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC,CAC5C,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, eq, isNull } from \"drizzle-orm\";\nimport {\n enqueueDocumentPendingUpdateWithHistory,\n listDocumentPendingUpdates,\n rekeyDocumentPendingUpdate,\n settleDocumentPendingUpdate,\n unqueueDocumentPendingUpdates,\n} from \"../../../sqlite/documentPersistence\";\nimport {\n appendDocumentHistoryUpdates,\n listDocumentHistoryTailEntries,\n loadDocumentHistoryRestoreState,\n readDocumentHistoryTailSize,\n replaceDocumentHistoryCheckpoint,\n} from \"../../../sqlite/documentPersistence/documentHistoryPersistence\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentsPersistence } from \"../types\";\nimport {\n buildPendingAttachmentRow,\n mapLocalAttachmentRecord,\n mapPendingAttachmentRecord,\n} from \"./attachmentRows\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\ntype DocumentSyncQueuePersistence = Pick<\n DocumentsPersistence,\n | \"listPendingUpdates\"\n | \"rekeyPendingUpdate\"\n | \"listPendingAttachments\"\n | \"listLocalAttachments\"\n | \"appendHistoryUpdates\"\n | \"loadHistoryRestoreState\"\n | \"readHistoryTailSize\"\n | \"listHistoryTailEntries\"\n | \"replaceHistoryCheckpoint\"\n | \"enqueuePendingUpdate\"\n | \"saveLocalAttachment\"\n | \"deleteLocalAttachment\"\n | \"markLocalAttachmentDetached\"\n | \"savePendingAttachment\"\n | \"deletePendingUpdate\"\n | \"deletePendingUpdates\"\n | \"deletePendingAttachment\"\n | \"deletePendingAttachments\"\n>;\n\nexport const documentSyncQueuePersistence: DocumentSyncQueuePersistence = {\n async listPendingUpdates(execSql, localId) {\n return listDocumentPendingUpdates(execSql, getDocumentScope(localId));\n },\n async rekeyPendingUpdate(execSql, id) {\n return rekeyDocumentPendingUpdate(execSql, id);\n },\n async listPendingAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentPendingAttachments.localId,\n slotId: documentPendingAttachments.slotId,\n name: documentPendingAttachments.name,\n mimeType: documentPendingAttachments.mimeType,\n storageKey: documentPendingAttachments.storageKey,\n byteLength: documentPendingAttachments.byteLength,\n contentSha256: documentPendingAttachments.contentSha256,\n uploadBlobId: documentPendingAttachments.uploadBlobId,\n uploadContentKey: documentPendingAttachments.uploadContentKey,\n uploadIv: documentPendingAttachments.uploadIv,\n uploadContentKeyEpoch: documentPendingAttachments.uploadContentKeyEpoch,\n uploadPartSize: documentPendingAttachments.uploadPartSize,\n uploadPlaintextSha256: documentPendingAttachments.uploadPlaintextSha256,\n uploadStageId: documentPendingAttachments.uploadStageId,\n })\n .from(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .orderBy(\n documentPendingAttachments.createdAt,\n documentPendingAttachments.slotId,\n );\n\n return rows.map(mapPendingAttachmentRecord);\n },\n // Detached rows are included on purpose: they are the durable markers the\n // next sync uses to detach the remote binding, so a restart has to restore\n // them alongside the live slots.\n async listLocalAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentAttachmentBlobProjection.localId,\n slotId: documentAttachmentBlobProjection.slotId,\n blobId: documentAttachmentBlobProjection.blobId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n mimeType: documentAttachmentBlobProjection.mimeType,\n byteLength: documentAttachmentBlobProjection.byteLength,\n contentSha256: documentAttachmentBlobProjection.contentSha256,\n detachedAt: documentAttachmentBlobProjection.detachedAt,\n })\n .from(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId));\n\n return rows.map(mapLocalAttachmentRecord);\n },\n async appendHistoryUpdates(execSql, input) {\n await appendDocumentHistoryUpdates(\n execSql,\n getDocumentScope(input.localId),\n input.updates,\n input.origin,\n );\n },\n async loadHistoryRestoreState(execSql, localId) {\n return loadDocumentHistoryRestoreState(execSql, getDocumentScope(localId));\n },\n async readHistoryTailSize(execSql, localId) {\n return readDocumentHistoryTailSize(execSql, getDocumentScope(localId));\n },\n async listHistoryTailEntries(execSql, localId) {\n return listDocumentHistoryTailEntries(execSql, getDocumentScope(localId));\n },\n async replaceHistoryCheckpoint(execSql, input) {\n await replaceDocumentHistoryCheckpoint(\n execSql,\n getDocumentScope(input.localId),\n {\n coveredTailIds: input.coveredTailIds,\n endVersionVector: input.endVersionVector,\n ...(input.force === undefined ? {} : { force: input.force }),\n snapshot: input.snapshot,\n ...(input.stillCurrent === undefined\n ? {}\n : { stillCurrent: input.stillCurrent }),\n },\n );\n },\n async enqueuePendingUpdate(execSql, pendingUpdate, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const pendingUpdateId = await enqueueDocumentPendingUpdateWithHistory(\n lockedExecSql,\n getDocumentScope(pendingUpdate.localId),\n pendingUpdate,\n options,\n );\n return pendingUpdateId !== null;\n });\n },\n async saveLocalAttachment(execSql, attachment) {\n const updatedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = {\n localId: attachment.localId,\n slotId: attachment.slotId,\n blobId: attachment.blobId,\n storageKey: attachment.storageKey,\n mimeType: attachment.mimeType,\n byteLength: attachment.byteLength,\n contentSha256: attachment.contentSha256,\n updatedAt,\n // Written on every save so re-filling a slot clears a stale detach\n // marker instead of inheriting it from the row it replaces.\n detachedAt: attachment.detachedAt,\n };\n await db\n .insert(documentAttachmentBlobProjection)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentAttachmentBlobProjection.localId,\n documentAttachmentBlobProjection.slotId,\n ],\n set: attachmentRow,\n })\n .run();\n });\n },\n async deleteLocalAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n ),\n )\n .run();\n // Another slot may hold the same hydrated copy; the reclaim deletes\n // the bytes only once no row references them.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async markLocalAttachmentDetached(execSql, localId, slotId, storageKey) {\n const detachedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documentAttachmentBlobProjection)\n .set({ detachedAt })\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n isNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n });\n },\n async savePendingAttachment(execSql, attachment) {\n const createdAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = buildPendingAttachmentRow(attachment, createdAt);\n await db\n .insert(documentPendingAttachments)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentPendingAttachments.localId,\n documentPendingAttachments.slotId,\n ],\n set: {\n name: attachmentRow.name,\n mimeType: attachmentRow.mimeType,\n storageKey: attachmentRow.storageKey,\n byteLength: attachmentRow.byteLength,\n contentSha256: attachmentRow.contentSha256,\n uploadBlobId: attachmentRow.uploadBlobId,\n uploadContentKey: attachmentRow.uploadContentKey,\n uploadIv: attachmentRow.uploadIv,\n uploadContentKeyEpoch: attachmentRow.uploadContentKeyEpoch,\n uploadPartSize: attachmentRow.uploadPartSize,\n uploadPlaintextSha256: attachmentRow.uploadPlaintextSha256,\n uploadStageId: attachmentRow.uploadStageId,\n },\n })\n .run();\n });\n },\n async deletePendingUpdate(execSql, id) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await settleDocumentPendingUpdate(lockedExecSql, id);\n });\n },\n async deletePendingUpdates(execSql, localId) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await unqueueDocumentPendingUpdates(\n lockedExecSql,\n getDocumentScope(localId),\n );\n });\n },\n async deletePendingAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentPendingAttachments)\n .where(\n and(\n eq(documentPendingAttachments.localId, localId),\n eq(documentPendingAttachments.slotId, slotId),\n eq(documentPendingAttachments.storageKey, storageKey),\n ),\n )\n .run();\n // A dropped upload may hold the last reference to its staged bytes.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async deletePendingAttachments(execSql, localId) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n const deleted = await db\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .returning({ storageKey: documentPendingAttachments.storageKey });\n await queueDocumentAttachmentStorageKeys(\n db,\n deleted.map(({ storageKey }) => storageKey),\n );\n });\n },\n};\n"]}
@@ -1,10 +1,10 @@
1
1
  import type { DocumentProjectorRegistryInput, StoredDocumentKind } from "../../documents/documentKinds.js";
2
2
  import type { DiscoveredDocumentInput, DocumentSummary } from "../../documents/documentSummary.js";
3
- import type { DocumentSyncPullContinuation } from "../../documents/shared/pullContinuation.js";
4
- import type { DocumentRecord as BaseDocumentRecord, PendingUpdateFields, PendingUpdateRecord } from "../../sqlite/documentPersistence.js";
3
+ import type { DocumentSyncPullContinuation } from "../../documents/shared/sync/pullContinuation.js";
4
+ import type { DocumentRecord as BaseDocumentRecord, PendingUpdateFields, PendingUpdateRecord } from "../../sqlite/documentPersistence/index.js";
5
5
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
6
6
  import type { DocumentOrphanBlobPersistence } from "./orphanBlobPersistence.js";
7
- export type { PendingUpdateRecord } from "../../sqlite/documentPersistence.js";
7
+ export type { PendingUpdateRecord } from "../../sqlite/documentPersistence/index.js";
8
8
  export interface StoredDocumentRecord extends BaseDocumentRecord {
9
9
  containerId: string | null;
10
10
  documentKind?: StoredDocumentKind;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/pullContinuation\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../../sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { DocumentOrphanBlobPersistence } from \"./orphanBlobPersistence\";\n\nexport type { PendingUpdateRecord } from \"../../sqlite/documentPersistence\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence {\n readonly orphanBlobs: DocumentOrphanBlobPersistence;\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<string | null>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows only while the response's security identity survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;\n /**\n * Delete the canonical row and every side row only when its security identity\n * and container placement still match the captured record. The comparison,\n * deletes, and client\n * projection callback must share one write transaction.\n */\n deleteDocumentIfMatches: (\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n /**\n * Delete orphaned side rows only if the canonical document is still absent.\n * The absence check, row cleanup, and client projection callback must share\n * one write transaction so a concurrent create is preserved.\n */\n deleteDocumentSideRowsIfAbsent: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../../sqlite/documentPersistence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { DocumentOrphanBlobPersistence } from \"./orphanBlobPersistence\";\n\nexport type { PendingUpdateRecord } from \"../../sqlite/documentPersistence\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence {\n readonly orphanBlobs: DocumentOrphanBlobPersistence;\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<string | null>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows only while the response's security identity survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;\n /**\n * Delete the canonical row and every side row only when its security identity\n * and container placement still match the captured record. The comparison,\n * deletes, and client\n * projection callback must share one write transaction.\n */\n deleteDocumentIfMatches: (\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n /**\n * Delete orphaned side rows only if the canonical document is still absent.\n * The absence check, row cleanup, and client projection callback must share\n * one write transaction so a concurrent create is preserved.\n */\n deleteDocumentSideRowsIfAbsent: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { ClientSQLiteTransactionScope } from "../sqlite/sqlitePersistenceRuntime.js";
2
- import { type ExecSql } from "../sqlite/sqlSchema.js";
1
+ import type { ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
2
+ import { type ExecSql } from "../../sqlite/sqlSchema.js";
3
3
  export interface DocumentPurgeCheckpoint {
4
4
  readonly documentId: string;
5
5
  readonly documentManifestHash: string;
@@ -1,8 +1,8 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { eq } from "drizzle-orm";
3
- import { documentPurgeCheckpoints, keyingCheckpointTables, } from "../sqlite/schema.js";
4
- import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
5
- import { ensureSqlTables } from "../sqlite/sqlSchema.js";
3
+ import { documentPurgeCheckpoints, keyingCheckpointTables, } from "../../sqlite/schema/index.js";
4
+ import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
5
+ import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
6
  export async function loadDocumentPurgeCheckpoint(execSql, documentId) {
7
7
  await ensureSqlTables(execSql, keyingCheckpointTables);
8
8
  const [row] = await getClientSQLitePersistenceRuntime(execSql)
@@ -0,0 +1 @@
1
+ {"version":3,"file":"documentPurgeCheckpointPersistence.js","sourceRoot":"","sources":["documentPurgeCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AASvE,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAAgB,EAChB,UAAkB;IAElB,MAAM,eAAe,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;IACvD,MAAM,CAAC,GAAG,CAAC,GAAG,MAAM,iCAAiC,CAAC,OAAO,CAAC;SAC3D,EAAE,CAAC,MAAM,CAAC;QACT,UAAU,EAAE,wBAAwB,CAAC,UAAU;QAC/C,oBAAoB,EAAE,wBAAwB,CAAC,oBAAoB;QACnE,cAAc,EAAE,wBAAwB,CAAC,cAAc;QACvD,cAAc,EAAE,wBAAwB,CAAC,cAAc;KACxD,CAAC;SACD,IAAI,CAAC,wBAAwB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,wBAAwB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;SAC1D,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,GAAG,IAAI,IAAI,CAAC;AACrB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,UAAmC,EACnC,SAAiB;IAEjB,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC;QACN,oBAAoB,EAAE,wBAAwB,CAAC,oBAAoB;QACnE,cAAc,EAAE,wBAAwB,CAAC,cAAc;QACvD,cAAc,EAAE,wBAAwB,CAAC,cAAc;KACxD,CAAC;SACD,IAAI,CAAC,wBAAwB,CAAC;SAC9B,KAAK,CAAC,EAAE,CAAC,wBAAwB,CAAC,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC;SACrE,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,MAAM,EAAE,CAAC;QACX,IACE,MAAM,CAAC,oBAAoB,KAAK,UAAU,CAAC,oBAAoB;YAC/D,MAAM,CAAC,cAAc,KAAK,UAAU,CAAC,cAAc;YACnD,MAAM,CAAC,cAAc,KAAK,UAAU,CAAC,cAAc,EACnD,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,sEAAsE,CACvE,CAAC;QACJ,CAAC;QACD,OAAO;IACT,CAAC;IACD,MAAM,EAAE;SACL,MAAM,CAAC,wBAAwB,CAAC;SAChC,MAAM,CAAC,EAAE,GAAG,UAAU,EAAE,SAAS,EAAE,CAAC;SACpC,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport {\n documentPurgeCheckpoints,\n keyingCheckpointTables,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\n\nexport interface DocumentPurgeCheckpoint {\n readonly documentId: string;\n readonly documentManifestHash: string;\n readonly organizationId: string;\n readonly purgeEventHash: string;\n}\n\nexport async function loadDocumentPurgeCheckpoint(\n execSql: ExecSql,\n documentId: string,\n): Promise<DocumentPurgeCheckpoint | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const [row] = await getClientSQLitePersistenceRuntime(execSql)\n .db.select({\n documentId: documentPurgeCheckpoints.documentId,\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, documentId))\n .limit(1);\n return row ?? null;\n}\n\nexport async function storeDocumentPurgeCheckpointInTransaction(\n tx: ClientSQLiteTransactionScope,\n checkpoint: DocumentPurgeCheckpoint,\n updatedAt: string,\n): Promise<void> {\n const [stored] = await tx\n .select({\n documentManifestHash: documentPurgeCheckpoints.documentManifestHash,\n organizationId: documentPurgeCheckpoints.organizationId,\n purgeEventHash: documentPurgeCheckpoints.purgeEventHash,\n })\n .from(documentPurgeCheckpoints)\n .where(eq(documentPurgeCheckpoints.documentId, checkpoint.documentId))\n .limit(1);\n if (stored) {\n if (\n stored.documentManifestHash !== checkpoint.documentManifestHash ||\n stored.organizationId !== checkpoint.organizationId ||\n stored.purgeEventHash !== checkpoint.purgeEventHash\n ) {\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Document purge checkpoint conflicts with the verified terminal event\",\n );\n }\n return;\n }\n await tx\n .insert(documentPurgeCheckpoints)\n .values({ ...checkpoint, updatedAt })\n .run();\n}\n"]}
@@ -1,16 +1,16 @@
1
- import { KeyingVerificationError, verifyAccessManifestLocalCheckpoint, verifyPrincipalPolicyCheckpoint, } from "../../internal/crypto/index.js";
2
- import { keyingCheckpointTables, principalPolicyTables, } from "../sqlite/schema.js";
3
- import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
4
- import { ensureSqlTables } from "../sqlite/sqlSchema.js";
5
- import { verifiedManifestBundleTables } from "../sqlite/verifiedManifestBundleSchema.js";
1
+ import { KeyingVerificationError, verifyAccessManifestLocalCheckpoint, verifyPrincipalPolicyCheckpoint, } from "../../../internal/crypto/index.js";
2
+ import { keyingCheckpointTables, principalPolicyTables, } from "../../sqlite/schema/index.js";
3
+ import { verifiedManifestBundleTables } from "../../sqlite/schema/verifiedManifestBundleSchema.js";
4
+ import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
5
+ import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
+ import { assertContainerNotRetired } from "../principalKeys/principalGrantRetirementPersistence.js";
7
+ import { assertPrincipalPolicyBundleStoredInTransaction, writePrincipalPolicyBundleInTransaction, } from "../principalPolicy/principalPolicyPersistence.js";
8
+ import { assertBundleMatchesVerifiedPolicy } from "../principalPolicy/verifiedPrincipalPolicyBundle.js";
9
+ import { verifiedManifestBundleRows, writeVerifiedManifestBundlesInTransaction, } from "../verifiedManifestBundlePersistence.js";
6
10
  import { storeDocumentPurgeCheckpointInTransaction, } from "./documentPurgeCheckpointPersistence.js";
7
11
  import { validateAccessManifestCheckpointEvidence } from "./keyingCheckpointEvidence.js";
8
12
  import { accessManifestObjectKey, loadStoredAccessManifestCheckpoint, loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertAccessManifestCheckpointInTransaction, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpointPersistence.js";
9
13
  import { validatePrincipalAuthorizationCheckpoints } from "./principalAuthorizationCheckpoints.js";
10
- import { assertContainerNotRetired } from "./principalGrantRetirementPersistence.js";
11
- import { assertPrincipalPolicyBundleStoredInTransaction, writePrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
12
- import { verifiedManifestBundleRows, writeVerifiedManifestBundlesInTransaction, } from "./verifiedManifestBundlePersistence.js";
13
- import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
14
14
  function validateAccessAdvance(advance, localCheckpoint) {
15
15
  const current = {
16
16
  ...advance.head.checkpoint,
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAKvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAChG,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AACjG,OAAO,EACL,8CAA8C,EAC9C,uCAAuC,GACxC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,iCAAiC,EAAE,MAAM,kDAAkD,CAAC;AACrG,OAAO,EAGL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAClC,mCAAmC,EACnC,kBAAkB,EAClB,2CAA2C,EAC3C,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAmChG,SAAS,qBAAqB,CAC5B,OAAwC,EACxC,eAAgD;IAEhD,MAAM,OAAO,GAAG;QACd,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU;QAC1B,oBAAoB,EAAE,OAAO,CAAC,IAAI,CAAC,QAAQ,CA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E,EAAE,CAAC;YACvC,MAAM,UAAU,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;YACzE,IACE,CAAC,UAAU;gBACX,UAAU,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;gBACrC,UAAU,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,EACzC,CAAC;gBACD,MAAM,IAAI,KAAK,CACb,wDAAwD,CACzD,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,YAAY,EAAE;YAC5D,QAAQ,EAAE,WAAW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../../sqlite/schema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { assertContainerNotRetired } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"../principalPolicy/principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"../principalPolicy/verifiedPrincipalPolicyBundle\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n verifiedManifestBundleRows,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\ninterface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\nasync function validatePolicyAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\nasync function writePolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\n/**\n * Digests the verified bundles and ensures every table the batch touches,\n * all before its transaction begins.\n */\nasync function prepareKeyingCheckpointBatch(\n input: KeyingCheckpointValidationInput,\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleRows = await verifiedManifestBundleRows(\n input.verifiedBundles ?? [],\n );\n await ensureSqlTables(input.execSql, [\n ...(input.policies.length > 0 ||\n (input.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ]);\n return bundleRows;\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const verifiedAt = new Date().toISOString();\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput & {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n },\n): Promise<void> {\n const bundleRows = await prepareKeyingCheckpointBatch(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n\n/**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n const seen = new Set<string>();\n for (const entry of input.entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const persist = async (tx: ClientSQLiteTransactionScope) => {\n const policies = await validatePolicyAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePolicyCheckpoints(\n tx,\n policies,\n input.updatedAt,\n input.organizationId,\n );\n for (const policy of policies.values()) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\n \"Verified principal policy checkpoint was not persisted\",\n );\n }\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(persist, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(persist, { behavior: \"immediate\" });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { KeyingVerificationError, } from "../../internal/crypto/index.js";
1
+ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { accessManifestObjectKey } from "./keyingCheckpointPersistence.js";
3
3
  /** Structural consistency applies even when local currency prevents acceptance. */
4
4
  export function validateAccessManifestCheckpointEvidence(input) {
@@ -1,9 +1,9 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
1
+ import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { and, eq } from "drizzle-orm";
3
- import { accessManifestCheckpoints, keyingCheckpointTables, principalPolicyCheckpoints, } from "../sqlite/schema.js";
4
- import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
5
- import { ensureSqlTables } from "../sqlite/sqlSchema.js";
6
- import { recordPrincipalPolicyOrganizationInTransaction } from "./principalPolicyOrganizationPersistence.js";
3
+ import { accessManifestCheckpoints, keyingCheckpointTables, principalPolicyCheckpoints, } from "../../sqlite/schema/index.js";
4
+ import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
5
+ import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
6
+ import { recordPrincipalPolicyOrganizationInTransaction } from "../principalPolicy/principalPolicyOrganizationPersistence.js";
7
7
  /** One key format per checkpoint identity, shared by every batch validator. */
8
8
  export function accessManifestObjectKey(identity) {
9
9
  return JSON.stringify([