@tearleads/client-sdk 0.1.217 → 0.1.218

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 (139) hide show
  1. package/client/containerContents/documentDiscovery.js +6 -4
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/containerContents/index.js +3 -4
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +2 -2
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/documents/index.js +2 -2
  8. package/client/documents/index.js.map +1 -1
  9. package/client/organizations/organizationGroupHistory.js +1 -2
  10. package/client/organizations/organizationGroupHistory.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +1 -2
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationHistory.js +2 -4
  14. package/client/organizations/organizationHistory.js.map +1 -1
  15. package/client/organizations/principalContainerMutations.js +1 -2
  16. package/client/organizations/principalContainerMutations.js.map +1 -1
  17. package/client/organizations/principalMutations.js +1 -2
  18. package/client/organizations/principalMutations.js.map +1 -1
  19. package/client/organizations/rosterAdmissionEvidence.js +1 -2
  20. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  21. package/client/runtime/workflowRuntime.d.ts +3 -2
  22. package/client/runtime/workflowRuntime.js +13 -3
  23. package/client/runtime/workflowRuntime.js.map +1 -1
  24. package/index.d.ts +1 -1
  25. package/index.js.map +1 -1
  26. package/package.json +1 -1
  27. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  28. package/stores/documents/documentStore/attachments/attachmentHydration.js +3 -2
  29. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -1
  30. package/stores/documents/documentStore/rotation/index.js +1 -2
  31. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  32. package/stores/documents/documentStore/rotation/rotationSettlement.js +1 -1
  33. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -1
  34. package/stores/documents/documentStore/state.js.map +1 -1
  35. package/stores/documents/documentStore/sync/carriedFirstUpdate.js.map +1 -1
  36. package/stores/documents/documentStore/sync/index.js.map +1 -1
  37. package/stores/documents/documentStore/sync/syncAttachments.js +3 -2
  38. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  39. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -2
  40. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  41. package/stores/documents/documentStore/sync/syncRequest.js +3 -2
  42. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  43. package/stores/documents/documentStore/sync/syncRevalidation.js.map +1 -1
  44. package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -1
  45. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  46. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  47. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  48. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  49. package/workflows/container-contents/container-state/create/createWithMetadata.js +1 -2
  50. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  51. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -2
  52. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  53. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -2
  54. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  55. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -2
  56. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  57. package/workflows/container-contents/container-state/remote.js +3 -4
  58. package/workflows/container-contents/container-state/remote.js.map +1 -1
  59. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  60. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  61. package/workflows/container-contents/container-state/share/index.js +2 -3
  62. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  63. package/workflows/container-contents/container-state/types.js.map +1 -1
  64. package/workflows/container-contents/documentLinks/documentLinksMove.js +4 -2
  65. package/workflows/container-contents/documentLinks/documentLinksMove.js.map +1 -1
  66. package/workflows/container-contents/documentLinks/index.js +3 -2
  67. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  68. package/workflows/container-contents/index.d.ts +1 -1
  69. package/workflows/container-contents/index.js +1 -1
  70. package/workflows/container-contents/index.js.map +1 -1
  71. package/workflows/container-contents/metadata/index.d.ts +1 -1
  72. package/workflows/container-contents/metadata/index.js.map +1 -1
  73. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +3 -3
  74. package/workflows/container-contents/metadata/metadataRemoteSync.js +3 -2
  75. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  76. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -2
  77. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  78. package/workflows/container-contents/remoteHydration/index.js +1 -2
  79. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  80. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +4 -2
  81. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  82. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  83. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  84. package/workflows/container-contents/runtime.d.ts +13 -2
  85. package/workflows/container-contents/runtime.js +33 -21
  86. package/workflows/container-contents/runtime.js.map +1 -1
  87. package/workflows/container-contents/syncLane.d.ts +1 -1
  88. package/workflows/container-contents/syncLane.js.map +1 -1
  89. package/workflows/container-contents/tombstones/documentPurge.d.ts +2 -3
  90. package/workflows/container-contents/tombstones/documentPurge.js +1 -2
  91. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  92. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +3 -2
  93. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  94. package/workflows/documents/index.d.ts +1 -1
  95. package/workflows/documents/index.js +1 -1
  96. package/workflows/documents/index.js.map +1 -1
  97. package/workflows/documents/runtime.d.ts +12 -1
  98. package/workflows/documents/runtime.js +24 -16
  99. package/workflows/documents/runtime.js.map +1 -1
  100. package/workflows/documents/sync/syncLane.d.ts +1 -1
  101. package/workflows/documents/sync/syncLane.js.map +1 -1
  102. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -2
  103. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  104. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +5 -4
  105. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +2 -4
  106. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
  107. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -2
  108. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
  109. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  110. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -2
  111. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +2 -2
  112. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  113. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js +4 -8
  114. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -1
  115. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +2 -3
  116. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  117. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  118. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +2 -2
  119. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  120. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +2 -2
  121. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  122. package/workflows/principals/index.d.ts +1 -0
  123. package/workflows/principals/index.js.map +1 -1
  124. package/workflows/principals/principalPolicyService.d.ts +64 -0
  125. package/workflows/principals/principalPolicyService.js +117 -0
  126. package/workflows/principals/principalPolicyService.js.map +1 -0
  127. package/workflows/principals/runtimePolicyRecovery.d.ts +13 -10
  128. package/workflows/principals/runtimePolicyRecovery.js +9 -17
  129. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  130. package/workflows/principals/runtimeProjectionPolicyRecovery.js +7 -8
  131. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  132. package/data/principals/principalHistoryRuntime.js +0 -12
  133. package/data/principals/principalHistoryRuntime.js.map +0 -1
  134. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +0 -16
  135. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js +0 -39
  136. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +0 -1
  137. package/workflows/principals/runtimePolicyWarmer.d.ts +0 -26
  138. package/workflows/principals/runtimePolicyWarmer.js +0 -48
  139. package/workflows/principals/runtimePolicyWarmer.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"syncLaneIteration.js","sourceRoot":"","sources":["syncLaneIteration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+EAA+E,CAAC;AAClI,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,8BAA8B,GAC/B,MAAM,2EAA2E,CAAC;AACnF,OAAO,EAAE,0BAA0B,EAAE,MAAM,gDAAgD,CAAC;AAK5F,OAAO,EAAE,uCAAuC,EAAE,MAAM,+CAA+C,CAAC;AAExG,OAAO,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,uCAAuC,EAAE,MAAM,8CAA8C,CAAC;AACvG,OAAO,EAAE,2BAA2B,EAAE,MAAM,+CAA+C,CAAC;AAC5F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,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CAAC;KACL,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { syncPendingContainerCreateIntents } from \"../../../workflows/container-contents/container-state/create/createIntentSync\";\nimport { syncPendingContainerMoveIntents } from \"../../../workflows/container-contents/container-state/move/moveIntentSync\";\nimport {\n type DocumentMoveIntentSyncHost,\n syncPendingDocumentMoveIntents,\n} from \"../../../workflows/container-contents/documentMove/documentMoveIntentSync\";\nimport { syncContainerMetadataState } from \"../../../workflows/container-contents/metadata\";\nimport type {\n ContainerState,\n RemoteContainerHydrationHost,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport { createContainerContentsDocumentsRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport { openDocumentStore, requestDomainDocumentSync } from \"../../documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../../documents/documentStore/internalRelink\";\nimport { DocumentRemoteWorkBusyError } from \"../../documents/documentStore/sync/remoteWork\";\nimport { removeMissingSyncedContainerState } from \"../containerState/missingSyncedContainerState\";\nimport { runContainerDocumentWork } from \"../documentWork\";\nimport {\n primeStoreDocuments,\n recoverStoreStaleRoot,\n} from \"../documentWork/documentRecovery\";\nimport { createAcceptedMoveRetry } from \"./acceptedMoveRetry\";\nimport {\n bumpMetadataSyncSeq,\n clearMetadataSyncQueueIfUnchanged,\n readMetadataSyncSeq,\n} from \"./metadataSyncSignal\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\n\ntype ContainerContentsStorePrimeDocumentRuntime = ReturnType<\n typeof createContainerContentsDocumentsRuntime\n>;\ntype SyncContainerMetadata = typeof syncContainerMetadataState;\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nfunction createRemoteSyncBlocker(runtime: ContainerContentsStoreRuntime) {\n return (organizationId: string) =>\n runtime.util.isRemoteSyncBlocked?.(organizationId) ?? false;\n}\n\nfunction captureStructuralSyncGeneration(\n state: ContainerContentsStoreSyncState,\n runtime: ContainerContentsStoreRuntime,\n) {\n const activeContainerId = runtime.state.containerId;\n const activeOrganizationId = runtime.auth.organizationId;\n const lifecycleGeneration = state.lifecycleGeneration;\n const structuralGeneration = state.structuralGeneration;\n const domainScope = runtime.state.domainScope;\n const execSql = runtime.infra.execSql;\n const resolveProjectionUserKey = state.resolveProjectionUserKey;\n const syncLane = state.syncLane;\n return () =>\n state.lifecycleGeneration === lifecycleGeneration &&\n state.structuralGeneration === structuralGeneration &&\n state.runtime.auth.organizationId === activeOrganizationId &&\n state.runtime.state.containerId === activeContainerId &&\n state.runtime.state.domainScope === domainScope &&\n state.runtime.infra.execSql === execSql &&\n state.resolveProjectionUserKey === resolveProjectionUserKey &&\n state.syncLane === syncLane &&\n !syncLane?.isDisposed?.();\n}\n\nfunction createContainerContentsStoreDocumentMoveHost(\n state: ContainerContentsStoreSyncState,\n isCurrent: () => boolean,\n): DocumentMoveIntentSyncHost<ContainerContentsStorePrimeDocumentRuntime> {\n const runtime = state.runtime;\n const domainScope = runtime.state.domainScope;\n return {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: ({ containerId, documentId, localId }) => {\n const store = openDocumentStore(\n domainScope,\n localId,\n createContainerContentsDocumentsRuntime(runtime, containerId),\n documentId,\n );\n return {\n assertCanRotateContentKey: (proof) =>\n store.assertCanRotateContentKey(proof).catch((error: unknown) => {\n if (error instanceof DocumentRemoteWorkBusyError) {\n void error.whenIdle.then(() => {\n if (isCurrent()) requestContainerContentsStoreSync(state);\n });\n }\n throw error;\n }),\n ensureInitialized: () => store.ensureInitialized(),\n relink: ({ commitSideEffect, ...input }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n input,\n commitSideEffect,\n )\n : store.relink(input),\n requestSync: () => store.requestSync(),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n },\n };\n}\n\nfunction syncPendingStoreDocumentMoves(input: {\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: ContainerContentsStoreSyncState;\n}) {\n return syncPendingDocumentMoveIntents({\n host: createContainerContentsStoreDocumentMoveHost(\n input.state,\n input.isCurrent,\n ),\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n state: input.state,\n });\n}\n\nfunction syncPendingStoreContainerMoves(\n input: Omit<\n Parameters<typeof syncPendingContainerMoveIntents>[0],\n \"acceptedMoveRetry\" | \"state\"\n > & { state: ContainerContentsStoreSyncState },\n) {\n return syncPendingContainerMoveIntents({\n ...input,\n acceptedMoveRetry: createAcceptedMoveRetry(input.state),\n });\n}\n\nasync function syncSingleContainerMetadata(input: {\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n state: ContainerContentsStoreSyncState;\n containerState: ContainerState;\n encapsulationKeyPair: NonNullable<\n ContainerContentsStoreRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n >;\n policyOperation: PrincipalPolicyOperation;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}) {\n const { containerState, encapsulationKeyPair, host, isCurrent, state } =\n input;\n const metadataDocumentId = containerState.record.documentId;\n // Snapshot this signal before the GET so a mid-pass event survives clearing.\n const consumedSeqById = new Map<string, number>();\n if (typeof metadataDocumentId === \"string\") {\n consumedSeqById.set(\n metadataDocumentId,\n readMetadataSyncSeq(state.metadataSyncSignalSeqById, metadataDocumentId),\n );\n }\n const synced = await (\n input.syncContainerMetadata ?? syncContainerMetadataState\n )({\n forceReadSync:\n typeof metadataDocumentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(metadataDocumentId),\n locallyAcceptedUpdateIds: state.locallyAcceptedMetadataUpdateIds,\n isCurrent,\n metadataState: containerState,\n onDurableStateNeedsReload: () => {\n const currentDocumentId = state.containersById.get(\n containerState.container.id,\n )?.record.documentId;\n if (typeof currentDocumentId === \"string\") {\n state.metadataDocumentIdsNeedingSync.add(currentDocumentId);\n bumpMetadataSyncSeq(state.metadataSyncSignalSeqById, currentDocumentId);\n }\n requestContainerContentsStoreSync(state);\n },\n persistence: state.persistence,\n policyOperation: input.policyOperation,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n targetSecretKey: encapsulationKeyPair.secretKey,\n });\n if (!isCurrent() || !synced) {\n return;\n }\n if (\"missing\" in synced) {\n removeMissingSyncedContainerState(\n state,\n containerState,\n host.updateSnapshot,\n );\n return;\n }\n\n for (const id of [metadataDocumentId, synced.record.documentId]) {\n if (typeof id === \"string\") {\n clearMetadataSyncQueueIfUnchanged({\n consumedSeqById,\n id,\n needingSync: state.metadataDocumentIdsNeedingSync,\n seqById: state.metadataSyncSignalSeqById,\n });\n }\n }\n // syncContainerMetadataState settles its detached candidate into this live\n // object while preserving any metadata edit that completed or queued during\n // the remote pass. Do not install its returned detached record again here:\n // doing so would overwrite that preserved live edit.\n host.updateSnapshot();\n\n if (synced.shouldRequestFollowupSync) {\n requestContainerContentsStoreSync(state);\n }\n}\n\n/**\n * A folder whose create has not settled can carry a listed identity that\n * adoption has not verified, or has refused. Folder moves, document moves and\n * metadata edits wait for it; child and document creates wait in their own\n * create paths.\n */\nasync function loadPendingCreatePredicate(\n state: ContainerContentsStoreSyncState,\n): Promise<(containerId: string) => boolean> {\n const pending = await state.persistence.listPendingCreateIntents(\n state.runtime.infra.execSql,\n );\n const pendingIds = new Set(pending.map((intent) => intent.containerId));\n return (containerId) => pendingIds.has(containerId);\n}\n\ninterface ContainerContentsStoreSyncIterationInput {\n host: RemoteContainerHydrationHost;\n /** The drain's operation: every metadata sync of this pass shares it. */\n policyOperation: PrincipalPolicyOperation;\n reconcileRestoredAccess: (isCurrent: () => boolean) => Promise<void>;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerContentsStoreSyncState;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}\n\nexport async function runContainerContentsStoreSyncIteration(\n input: ContainerContentsStoreSyncIterationInput,\n) {\n const { host, reconcileRestoredAccess, requestRemoteReconciliation, state } =\n input;\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n runtime.infra.dbStatus !== \"ready\" ||\n !state.snapshot.ready ||\n !runtime.state.online ||\n !runtime.auth.isAuthenticated ||\n !encapsulationKeyPair\n ) {\n return;\n }\n const domainScope = runtime.state.domainScope;\n const isCurrent = captureStructuralSyncGeneration(state, runtime);\n\n await reconcileRestoredAccess(isCurrent);\n if (!isCurrent()) {\n return;\n }\n const isOrganizationBlocked = createRemoteSyncBlocker(runtime);\n\n const createdContainerCount = await syncPendingContainerCreateIntents({\n host,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (createdContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n }\n const isCreatePending = await loadPendingCreatePredicate(state);\n if (!isCurrent()) {\n return;\n }\n\n const movedContainerCount = await syncPendingStoreContainerMoves({\n host,\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (movedContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n\n for (const containerState of Array.from(state.containersById.values())) {\n if (isCreatePending(containerState.container.id)) continue;\n await syncSingleContainerMetadata({\n ...input,\n containerState,\n encapsulationKeyPair,\n isCurrent,\n });\n if (!isCurrent()) {\n return;\n }\n }\n\n // Root adoption notifies session consumers synchronously. Let container\n // metadata converge first so a recovered system container is never exposed\n // under its placeholder name when the active root changes.\n await runContainerDocumentWork({\n isCurrent,\n onContextChanged: () => {\n if (isCurrent()) {\n requestContainerContentsStoreSync(state);\n }\n },\n onDocumentsMoved: () => {\n if (isCurrent()) {\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n },\n primeDocuments: () => primeStoreDocuments(state, isCurrent),\n recoverStaleRoot: () => recoverStoreStaleRoot(state, isCurrent),\n shouldPrimeDocuments: () => state.documentStoresNeedPriming,\n // Document move intents live in the structural phase because they may\n // target containers created locally in the same session, such as Trash.\n // Root recovery rewrites stale endpoints and returns their intents to\n // pending, so replay follows recovery in this same pass.\n syncPendingDocumentMoves: () =>\n syncPendingStoreDocumentMoves({\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n state,\n }),\n });\n}\n"]}
1
+ {"version":3,"file":"syncLaneIteration.js","sourceRoot":"","sources":["syncLaneIteration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iCAAiC,EAAE,MAAM,+EAA+E,CAAC;AAClI,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,8BAA8B,GAC/B,MAAM,2EAA2E,CAAC;AACnF,OAAO,EAAE,0BAA0B,EAAE,MAAM,gDAAgD,CAAC;AAK5F,OAAO,EAAE,uCAAuC,EAAE,MAAM,+CAA+C,CAAC;AAExG,OAAO,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,uCAAuC,EAAE,MAAM,8CAA8C,CAAC;AACvG,OAAO,EAAE,2BAA2B,EAAE,MAAM,+CAA+C,CAAC;AAC5F,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EACL,mBAAmB,EACnB,iCAAiC,EACjC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AI,eAAe,CAAC,cAAc,CAAC,SAAS,CAAC,EAAE,CAAC;YAAE,SAAS;QAC3D,MAAM,2BAA2B,CAAC;YAChC,GAAG,KAAK;YACR,cAAc;YACd,oBAAoB;YACpB,SAAS;SACV,CAAC,CAAC;QACH,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YACjB,OAAO;QACT,CAAC;IACH,CAAC;IAED,wEAAwE;IACxE,2EAA2E;IAC3E,2DAA2D;IAC3D,MAAM,wBAAwB,CAAC;QAC7B,SAAS;QACT,gBAAgB,EAAE,GAAG,EAAE;YACrB,IAAI,SAAS,EAAE,EAAE,CAAC;gBAChB,iCAAiC,CAAC,KAAK,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,gBAAgB,EAAE,GAAG,EAAE;YACrB,IAAI,SAAS,EAAE,EAAE,CAAC;gBAChB,yBAAyB,CAAC,WAAW,CAAC,CAAC;gBACvC,iCAAiC,CAAC,KAAK,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,cAAc,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,KAAK,EAAE,SAAS,CAAC;QAC3D,gBAAgB,EAAE,GAAG,EAAE,CAAC,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC;QAC/D,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,yBAAyB;QAC3D,sEAAsE;QACtE,wEAAwE;QACxE,sEAAsE;QACtE,yDAAyD;QACzD,wBAAwB,EAAE,GAAG,EAAE,CAC7B,6BAA6B,CAAC;YAC5B,eAAe;YACf,SAAS;YACT,mBAAmB,EAAE,qBAAqB;YAC1C,KAAK;SACN,CAAC;KACL,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { syncPendingContainerCreateIntents } from \"../../../workflows/container-contents/container-state/create/createIntentSync\";\nimport { syncPendingContainerMoveIntents } from \"../../../workflows/container-contents/container-state/move/moveIntentSync\";\nimport {\n type DocumentMoveIntentSyncHost,\n syncPendingDocumentMoveIntents,\n} from \"../../../workflows/container-contents/documentMove/documentMoveIntentSync\";\nimport { syncContainerMetadataState } from \"../../../workflows/container-contents/metadata\";\nimport type {\n ContainerState,\n RemoteContainerHydrationHost,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport { createContainerContentsDocumentsRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/principalPolicyService\";\nimport { openDocumentStore, requestDomainDocumentSync } from \"../../documents\";\nimport { relinkDocumentStoreWithCommitSideEffect } from \"../../documents/documentStore/internalRelink\";\nimport { DocumentRemoteWorkBusyError } from \"../../documents/documentStore/sync/remoteWork\";\nimport { removeMissingSyncedContainerState } from \"../containerState/missingSyncedContainerState\";\nimport { runContainerDocumentWork } from \"../documentWork\";\nimport {\n primeStoreDocuments,\n recoverStoreStaleRoot,\n} from \"../documentWork/documentRecovery\";\nimport { createAcceptedMoveRetry } from \"./acceptedMoveRetry\";\nimport {\n bumpMetadataSyncSeq,\n clearMetadataSyncQueueIfUnchanged,\n readMetadataSyncSeq,\n} from \"./metadataSyncSignal\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\n\ntype ContainerContentsStorePrimeDocumentRuntime = ReturnType<\n typeof createContainerContentsDocumentsRuntime\n>;\ntype SyncContainerMetadata = typeof syncContainerMetadataState;\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nfunction createRemoteSyncBlocker(runtime: ContainerContentsStoreRuntime) {\n return (organizationId: string) =>\n runtime.util.isRemoteSyncBlocked?.(organizationId) ?? false;\n}\n\nfunction captureStructuralSyncGeneration(\n state: ContainerContentsStoreSyncState,\n runtime: ContainerContentsStoreRuntime,\n) {\n const activeContainerId = runtime.state.containerId;\n const activeOrganizationId = runtime.auth.organizationId;\n const lifecycleGeneration = state.lifecycleGeneration;\n const structuralGeneration = state.structuralGeneration;\n const domainScope = runtime.state.domainScope;\n const execSql = runtime.infra.execSql;\n const resolveProjectionUserKey = state.resolveProjectionUserKey;\n const syncLane = state.syncLane;\n return () =>\n state.lifecycleGeneration === lifecycleGeneration &&\n state.structuralGeneration === structuralGeneration &&\n state.runtime.auth.organizationId === activeOrganizationId &&\n state.runtime.state.containerId === activeContainerId &&\n state.runtime.state.domainScope === domainScope &&\n state.runtime.infra.execSql === execSql &&\n state.resolveProjectionUserKey === resolveProjectionUserKey &&\n state.syncLane === syncLane &&\n !syncLane?.isDisposed?.();\n}\n\nfunction createContainerContentsStoreDocumentMoveHost(\n state: ContainerContentsStoreSyncState,\n isCurrent: () => boolean,\n): DocumentMoveIntentSyncHost<ContainerContentsStorePrimeDocumentRuntime> {\n const runtime = state.runtime;\n const domainScope = runtime.state.domainScope;\n return {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: ({ containerId, documentId, localId }) => {\n const store = openDocumentStore(\n domainScope,\n localId,\n createContainerContentsDocumentsRuntime(runtime, containerId),\n documentId,\n );\n return {\n assertCanRotateContentKey: (proof) =>\n store.assertCanRotateContentKey(proof).catch((error: unknown) => {\n if (error instanceof DocumentRemoteWorkBusyError) {\n void error.whenIdle.then(() => {\n if (isCurrent()) requestContainerContentsStoreSync(state);\n });\n }\n throw error;\n }),\n ensureInitialized: () => store.ensureInitialized(),\n relink: ({ commitSideEffect, ...input }) =>\n commitSideEffect\n ? relinkDocumentStoreWithCommitSideEffect(\n store,\n input,\n commitSideEffect,\n )\n : store.relink(input),\n requestSync: () => store.requestSync(),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n },\n };\n}\n\nfunction syncPendingStoreDocumentMoves(input: {\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: ContainerContentsStoreSyncState;\n}) {\n return syncPendingDocumentMoveIntents({\n host: createContainerContentsStoreDocumentMoveHost(\n input.state,\n input.isCurrent,\n ),\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n state: input.state,\n });\n}\n\nfunction syncPendingStoreContainerMoves(\n input: Omit<\n Parameters<typeof syncPendingContainerMoveIntents>[0],\n \"acceptedMoveRetry\" | \"state\"\n > & { state: ContainerContentsStoreSyncState },\n) {\n return syncPendingContainerMoveIntents({\n ...input,\n acceptedMoveRetry: createAcceptedMoveRetry(input.state),\n });\n}\n\nasync function syncSingleContainerMetadata(input: {\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n state: ContainerContentsStoreSyncState;\n containerState: ContainerState;\n encapsulationKeyPair: NonNullable<\n ContainerContentsStoreRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n >;\n policyOperation: PrincipalPolicyOperation;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}) {\n const { containerState, encapsulationKeyPair, host, isCurrent, state } =\n input;\n const metadataDocumentId = containerState.record.documentId;\n // Snapshot this signal before the GET so a mid-pass event survives clearing.\n const consumedSeqById = new Map<string, number>();\n if (typeof metadataDocumentId === \"string\") {\n consumedSeqById.set(\n metadataDocumentId,\n readMetadataSyncSeq(state.metadataSyncSignalSeqById, metadataDocumentId),\n );\n }\n const synced = await (\n input.syncContainerMetadata ?? syncContainerMetadataState\n )({\n forceReadSync:\n typeof metadataDocumentId === \"string\" &&\n state.metadataDocumentIdsNeedingSync.has(metadataDocumentId),\n locallyAcceptedUpdateIds: state.locallyAcceptedMetadataUpdateIds,\n isCurrent,\n metadataState: containerState,\n onDurableStateNeedsReload: () => {\n const currentDocumentId = state.containersById.get(\n containerState.container.id,\n )?.record.documentId;\n if (typeof currentDocumentId === \"string\") {\n state.metadataDocumentIdsNeedingSync.add(currentDocumentId);\n bumpMetadataSyncSeq(state.metadataSyncSignalSeqById, currentDocumentId);\n }\n requestContainerContentsStoreSync(state);\n },\n persistence: state.persistence,\n policyOperation: input.policyOperation,\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n runtime: state.runtime,\n targetSecretKey: encapsulationKeyPair.secretKey,\n });\n if (!isCurrent() || !synced) {\n return;\n }\n if (\"missing\" in synced) {\n removeMissingSyncedContainerState(\n state,\n containerState,\n host.updateSnapshot,\n );\n return;\n }\n\n for (const id of [metadataDocumentId, synced.record.documentId]) {\n if (typeof id === \"string\") {\n clearMetadataSyncQueueIfUnchanged({\n consumedSeqById,\n id,\n needingSync: state.metadataDocumentIdsNeedingSync,\n seqById: state.metadataSyncSignalSeqById,\n });\n }\n }\n // syncContainerMetadataState settles its detached candidate into this live\n // object while preserving any metadata edit that completed or queued during\n // the remote pass. Do not install its returned detached record again here:\n // doing so would overwrite that preserved live edit.\n host.updateSnapshot();\n\n if (synced.shouldRequestFollowupSync) {\n requestContainerContentsStoreSync(state);\n }\n}\n\n/**\n * A folder whose create has not settled can carry a listed identity that\n * adoption has not verified, or has refused. Folder moves, document moves and\n * metadata edits wait for it; child and document creates wait in their own\n * create paths.\n */\nasync function loadPendingCreatePredicate(\n state: ContainerContentsStoreSyncState,\n): Promise<(containerId: string) => boolean> {\n const pending = await state.persistence.listPendingCreateIntents(\n state.runtime.infra.execSql,\n );\n const pendingIds = new Set(pending.map((intent) => intent.containerId));\n return (containerId) => pendingIds.has(containerId);\n}\n\ninterface ContainerContentsStoreSyncIterationInput {\n host: RemoteContainerHydrationHost;\n /** The drain's operation: every metadata sync of this pass shares it. */\n policyOperation: PrincipalPolicyOperation;\n reconcileRestoredAccess: (isCurrent: () => boolean) => Promise<void>;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerContentsStoreSyncState;\n syncContainerMetadata?: SyncContainerMetadata | undefined;\n}\n\nexport async function runContainerContentsStoreSyncIteration(\n input: ContainerContentsStoreSyncIterationInput,\n) {\n const { host, reconcileRestoredAccess, requestRemoteReconciliation, state } =\n input;\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n runtime.infra.dbStatus !== \"ready\" ||\n !state.snapshot.ready ||\n !runtime.state.online ||\n !runtime.auth.isAuthenticated ||\n !encapsulationKeyPair\n ) {\n return;\n }\n const domainScope = runtime.state.domainScope;\n const isCurrent = captureStructuralSyncGeneration(state, runtime);\n\n await reconcileRestoredAccess(isCurrent);\n if (!isCurrent()) {\n return;\n }\n const isOrganizationBlocked = createRemoteSyncBlocker(runtime);\n\n const createdContainerCount = await syncPendingContainerCreateIntents({\n host,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (createdContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n }\n const isCreatePending = await loadPendingCreatePredicate(state);\n if (!isCurrent()) {\n return;\n }\n\n const movedContainerCount = await syncPendingStoreContainerMoves({\n host,\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n requestRemoteReconciliation,\n state,\n });\n if (!isCurrent()) {\n return;\n }\n if (movedContainerCount > 0) {\n state.documentStoresNeedPriming = true;\n host.updateSnapshot();\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n\n for (const containerState of Array.from(state.containersById.values())) {\n if (isCreatePending(containerState.container.id)) continue;\n await syncSingleContainerMetadata({\n ...input,\n containerState,\n encapsulationKeyPair,\n isCurrent,\n });\n if (!isCurrent()) {\n return;\n }\n }\n\n // Root adoption notifies session consumers synchronously. Let container\n // metadata converge first so a recovered system container is never exposed\n // under its placeholder name when the active root changes.\n await runContainerDocumentWork({\n isCurrent,\n onContextChanged: () => {\n if (isCurrent()) {\n requestContainerContentsStoreSync(state);\n }\n },\n onDocumentsMoved: () => {\n if (isCurrent()) {\n requestDomainDocumentSync(domainScope);\n requestContainerContentsStoreSync(state);\n }\n },\n primeDocuments: () => primeStoreDocuments(state, isCurrent),\n recoverStaleRoot: () => recoverStoreStaleRoot(state, isCurrent),\n shouldPrimeDocuments: () => state.documentStoresNeedPriming,\n // Document move intents live in the structural phase because they may\n // target containers created locally in the same session, such as Trash.\n // Root recovery rewrites stale endpoints and returns their intents to\n // pending, so replay follows recovery in this same pass.\n syncPendingDocumentMoves: () =>\n syncPendingStoreDocumentMoves({\n isCreatePending,\n isCurrent,\n isRemoteSyncBlocked: isOrganizationBlocked,\n state,\n }),\n });\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  /** Hydrate only bytes matching the current document's authenticated attachment intent. */
2
2
  import { getDocumentAttachments } from "../../../../data/documents/documentContent.js";
3
- import { createRuntimePrincipalPolicyWarmer, } from "../../../../workflows/principals/runtimePolicyWarmer.js";
4
3
  import { runDocumentOrphanMaintenance } from "../orphanMaintenance.js";
5
4
  import { isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent, } from "../sync/syncGeneration.js";
6
5
  import { commitHydratedAttachment } from "./attachmentHydrationCommit.js";
@@ -41,7 +40,9 @@ export async function hydrateAttachmentBlobs(state, currentDoc, currentRecord, p
41
40
  resolveProjectionUserKey: expectedGeneration?.resolveProjectionUserKey ??
42
41
  state.resolveProjectionUserKey,
43
42
  stillCurrent: generationIsCurrent,
44
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime, { operation: policyOperation }),
43
+ warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({
44
+ operation: policyOperation,
45
+ }),
45
46
  });
46
47
  if (!generationIsCurrent())
47
48
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"attachmentHydration.js","sourceRoot":"","sources":["attachmentHydration.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AAEpF,OAAO,EACL,kCAAkC,GAEnC,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAEpE,OAAO,EAEL,oCAAoC,IAAI,uBAAuB,GAChE,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAA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IAEtB,MAAM,OAAO,GAAG,cAAc,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC1C,MAAM,iBAAiB,GACrB,cAAc;QACd,CAAC,OAAO,EAAE,UAAU,KAAK,UAAU;YACnC,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,UAAU;YACrC,CAAC,CAAC,OAAO,CAAC,QAAQ;YAClB,CAAC,CAAC,CAAC,CAAC,CAAC;IACT,OAAO,CACL,CAAC,iBAAiB;QAClB,WAAW,CAAC,KAAK,CACf,CAAC,UAAU,EAAE,EAAE,CACb,KAAK,CAAC,4BAA4B,CAAC,UAAU,CAAC,MAAM,CAAC;YACrD,KAAK,CAAC,+BAA+B,CAAC,UAAU,CAAC,MAAM,CAAC;gBACtD,UAAU,CAAC,aAAa,CAC7B,CACF,CAAC;AACJ,CAAC","sourcesContent":["/** Hydrate only bytes matching the current document's authenticated attachment intent. */\n\nimport { getDocumentAttachments } from \"../../../../data/documents/documentContent\";\nimport type { DocumentRecord } from \"../../../../workflows/documents\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { commitHydratedAttachment } from \"./attachmentHydrationCommit\";\n\n// A remote probe is evidence that bindings may have moved independently of\n// content. Capture its sequence before I/O so a hint arriving during hydration\n// survives for the trailing pass. Missing or changed local bytes always retry.\nconst checkedSignals = new WeakMap<\n DocumentStoreState,\n { documentId: string; document: WeakRef<DocumentState>; sequence: number }\n>();\n\nexport async function hydrateAttachmentBlobs(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord | null,\n policyOperation: PrincipalPolicyOperation,\n expectedGeneration?: DocumentStoreSyncGeneration,\n) {\n const generationIsCurrent = () =>\n !expectedGeneration || isSyncGenerationCurrent(state, expectedGeneration);\n if (!generationIsCurrent()) return;\n\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n !encapsulationKeyPair ||\n !runtime.auth.isAuthenticated ||\n !runtime.state.online ||\n !currentRecord?.documentId\n ) {\n return;\n }\n\n const attachments = getDocumentAttachments(currentDoc);\n if (attachments.length === 0) {\n return;\n }\n\n const signalSequence = state.remoteUpdateSignalSeq;\n if (\n bindingsAlreadyChecked(\n state,\n currentDoc,\n currentRecord.documentId,\n attachments,\n signalSequence,\n )\n )\n return;\n\n const expectedStorageKeys = { ...state.attachmentStorageKeyBySlotId };\n let bindingsChecked = false;\n const hydratedBlobs =\n await runtime.blobAttachments.hydrateDocumentAttachmentBlobs({\n onBindingsChecked: () => {\n bindingsChecked = true;\n },\n attachments,\n documentId: currentRecord.documentId,\n localBlobIdBySlotId: state.attachmentBlobIdBySlotId,\n localStorageKeyBySlotId: state.attachmentStorageKeyBySlotId,\n rejectedServedBindings: state.rejectedServedAttachmentBindings,\n resolveProjectionUserKey:\n expectedGeneration?.resolveProjectionUserKey ??\n state.resolveProjectionUserKey,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: policyOperation },\n ),\n });\n if (!generationIsCurrent()) return;\n if (!hydratedBlobs) {\n return;\n }\n\n for (const hydratedBlob of hydratedBlobs) {\n await commitHydratedAttachment({\n state,\n currentDoc,\n hydratedBlob,\n generationIsCurrent,\n expectedStorageKey:\n expectedStorageKeys[hydratedBlob.attachment.slotId] ?? null,\n });\n }\n if (\n bindingsChecked &&\n generationIsCurrent() &&\n hydratedBlobs.every(\n (blob) =>\n state.attachmentBlobIdBySlotId[blob.attachment.slotId] ===\n blob.binding.blobId,\n )\n ) {\n checkedSignals.set(state, {\n documentId: currentRecord.documentId,\n document: new WeakRef(currentDoc),\n sequence: signalSequence,\n });\n }\n void runDocumentOrphanMaintenance(state);\n}\n\nfunction bindingsAlreadyChecked(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n documentId: string,\n attachments: ReturnType<typeof getDocumentAttachments>,\n signalSequence: number,\n): boolean {\n const checked = checkedSignals.get(state);\n const needsBindingProbe =\n signalSequence >\n (checked?.documentId === documentId &&\n checked.document.deref() === currentDoc\n ? checked.sequence\n : 0);\n return (\n !needsBindingProbe &&\n attachments.every(\n (attachment) =>\n state.attachmentStorageKeyBySlotId[attachment.slotId] &&\n state.attachmentContentSha256BySlotId[attachment.slotId] ===\n attachment.contentSha256,\n )\n );\n}\n"]}
1
+ {"version":3,"file":"attachmentHydration.js","sourceRoot":"","sources":["attachmentHydration.ts"],"names":[],"mappings":"AAAA,0FAA0F;AAE1F,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AAGpF,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAEpE,OAAO,EAEL,oCAAoC,IAAI,uBAAuB,GAChE,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAEvE,2EAA2E;AAC3E,+EAA+E;AAC/E,+EAA+E;AAC/E,MAAM,cAAc,GAAG,IAAI,OAAO,EAG/B,CAAC;AAEJ,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAyB,EACzB,UAAyB,EACzB,aAAoC,EACpC,eAAyC,EACzC,kBAAgD;IAEhD,MAAM,mBAAmB,GAAG,GAAG,EAAE,CAC/B,CAAC,kBAAkB,IAAI,uBAAuB,CAAC,KAAK,EAAE,kBAAkB,CAAC,CAAC;IAC5E,IAAI,CAAC,mBAAmB,EAAE;QAAE,OAAO;IAEnC,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IAC9B,MAAM,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,CAAC;IACjE,IACE,CAAC,oBAAoB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ourcesContent":["/** Hydrate only bytes matching the current document's authenticated attachment intent. */\n\nimport { getDocumentAttachments } from \"../../../../data/documents/documentContent\";\nimport type { DocumentRecord } from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { runDocumentOrphanMaintenance } from \"../orphanMaintenance\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent as isSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { commitHydratedAttachment } from \"./attachmentHydrationCommit\";\n\n// A remote probe is evidence that bindings may have moved independently of\n// content. Capture its sequence before I/O so a hint arriving during hydration\n// survives for the trailing pass. Missing or changed local bytes always retry.\nconst checkedSignals = new WeakMap<\n DocumentStoreState,\n { documentId: string; document: WeakRef<DocumentState>; sequence: number }\n>();\n\nexport async function hydrateAttachmentBlobs(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n currentRecord: DocumentRecord | null,\n policyOperation: PrincipalPolicyOperation,\n expectedGeneration?: DocumentStoreSyncGeneration,\n) {\n const generationIsCurrent = () =>\n !expectedGeneration || isSyncGenerationCurrent(state, expectedGeneration);\n if (!generationIsCurrent()) return;\n\n const runtime = state.runtime;\n const encapsulationKeyPair = runtime.crypto.encapsulationKeyPair;\n if (\n !encapsulationKeyPair ||\n !runtime.auth.isAuthenticated ||\n !runtime.state.online ||\n !currentRecord?.documentId\n ) {\n return;\n }\n\n const attachments = getDocumentAttachments(currentDoc);\n if (attachments.length === 0) {\n return;\n }\n\n const signalSequence = state.remoteUpdateSignalSeq;\n if (\n bindingsAlreadyChecked(\n state,\n currentDoc,\n currentRecord.documentId,\n attachments,\n signalSequence,\n )\n )\n return;\n\n const expectedStorageKeys = { ...state.attachmentStorageKeyBySlotId };\n let bindingsChecked = false;\n const hydratedBlobs =\n await runtime.blobAttachments.hydrateDocumentAttachmentBlobs({\n onBindingsChecked: () => {\n bindingsChecked = true;\n },\n attachments,\n documentId: currentRecord.documentId,\n localBlobIdBySlotId: state.attachmentBlobIdBySlotId,\n localStorageKeyBySlotId: state.attachmentStorageKeyBySlotId,\n rejectedServedBindings: state.rejectedServedAttachmentBindings,\n resolveProjectionUserKey:\n expectedGeneration?.resolveProjectionUserKey ??\n state.resolveProjectionUserKey,\n stillCurrent: generationIsCurrent,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: policyOperation,\n }),\n });\n if (!generationIsCurrent()) return;\n if (!hydratedBlobs) {\n return;\n }\n\n for (const hydratedBlob of hydratedBlobs) {\n await commitHydratedAttachment({\n state,\n currentDoc,\n hydratedBlob,\n generationIsCurrent,\n expectedStorageKey:\n expectedStorageKeys[hydratedBlob.attachment.slotId] ?? null,\n });\n }\n if (\n bindingsChecked &&\n generationIsCurrent() &&\n hydratedBlobs.every(\n (blob) =>\n state.attachmentBlobIdBySlotId[blob.attachment.slotId] ===\n blob.binding.blobId,\n )\n ) {\n checkedSignals.set(state, {\n documentId: currentRecord.documentId,\n document: new WeakRef(currentDoc),\n sequence: signalSequence,\n });\n }\n void runDocumentOrphanMaintenance(state);\n}\n\nfunction bindingsAlreadyChecked(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n documentId: string,\n attachments: ReturnType<typeof getDocumentAttachments>,\n signalSequence: number,\n): boolean {\n const checked = checkedSignals.get(state);\n const needsBindingProbe =\n signalSequence >\n (checked?.documentId === documentId &&\n checked.document.deref() === currentDoc\n ? checked.sequence\n : 0);\n return (\n !needsBindingProbe &&\n attachments.every(\n (attachment) =>\n state.attachmentStorageKeyBySlotId[attachment.slotId] &&\n state.attachmentContentSha256BySlotId[attachment.slotId] ===\n attachment.contentSha256,\n )\n );\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { encodeVersionVector, versionVectorsEqual } from "../../../../internal/loro/index.js";
2
2
  import { createDocumentWriterPublicKeyResolver, readPullContinuation, resolveDocumentCreateAuthor, syncRemoteDocument, validateDocumentSyncUpdateImports, } from "../../../../workflows/documents/index.js";
3
- import { createRuntimePrincipalPolicyWarmer } from "../../../../workflows/principals/runtimePolicyWarmer.js";
4
3
  import { requestDocumentStoreSync } from "../../registry.js";
5
4
  import { installRebuiltDocument } from "../history/historyRebuild.js";
6
5
  import { chainIdentityWrite } from "../identityWriteChain.js";
@@ -99,7 +98,7 @@ async function pullVerifiedRawHistoryForRotation(input) {
99
98
  writerKeyLabel: "writer key",
100
99
  }),
101
100
  targetSecretKey: encapsulationKeyPair.secretKey,
102
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.state.runtime),
101
+ warmReferencedPrincipalPolicies: input.state.runtime.principalPolicies.createWarmer(),
103
102
  writerProjection,
104
103
  });
105
104
  if (!synced) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EACL,qCAAqC,EAGrC,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EAClB,iCAAiC,GAClC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACL,4CAA4C,EAC5C,sCAAsC,EAGtC,oCAAoC,GACrC,MAAM,wBAAwB,CAAC;AAChC,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KAAK,CACb,+DAA+D,CAChE,CAAC;QACJ,CAAC;QACD,MAAM,QAAQ,GACZ,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,4BAA4B,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACjE,IAAI,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAC9B,MAAM,QAAQ,GAAG,MAAM,2BAA2B,CAChD,KAAK,EACL,cAAc,EACd,UAAU,CACX,CAAC;QACF,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;QACrC,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,KAAK,UAAU,2BAA2B,CACxC,KAAyB,EACzB,cAA+C,EAC/C,UAAuC;IAEvC,KAAK,IAAI,OAAO,GAAG,CAAC,GAAI,OAAO,IAAI,CAAC,EAAE,CAAC;QACrC,IAAI,CAAC;YACH,OAAO,MAAM,6BAA6B,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QACpE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,uEAAuE;YACvE,uEAAuE;YACvE,gEAAgE;YAChE,IACE,CAAC,CACC,KAAK,YAAY,kCAAkC;gBACnD,KAAK,YAAY,4BAA4B,CAC9C;gBACD,OAAO,IAAI,CAAC;gBACZ,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC,EACxD,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector, versionVectorsEqual } from \"@tearleads/loro\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRotationProofMode,\n type DocumentSyncPullContinuation,\n readPullContinuation,\n resolveDocumentCreateAuthor,\n syncRemoteDocument,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { installRebuiltDocument } from \"../history/historyRebuild\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { listPendingUpdates } from \"../persistence\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { runDocumentRemoteWork } from \"../sync/remoteWork\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { deleteUpstreamDeletedDocument } from \"../sync/syncRequest\";\nimport { documentIncomingUpdateIsolationFailureHandler } from \"../sync/syncShared\";\nimport { importSyncedDocumentUpdates } from \"../sync/syncUpdateImport\";\nimport {\n currentRecordedRotationProof,\n recordRotationProof,\n} from \"./rotationProofRecord\";\nimport {\n assertExactDocumentHistory,\n importProvenOrdinaryPendingHistory,\n} from \"./rotationProvenance\";\nimport {\n invalidatePullContinuationBeforeRotation,\n RotationPendingUpdatesChangedError,\n settleOrdinaryDocumentUpdatesBeforeRotation,\n} from \"./rotationSettlement\";\n\nfunction ordinaryRawHistoryUpdates<T extends { checkpointKind?: string }>(\n updates: readonly T[],\n): T[] {\n return updates.filter((update) => update.checkpointKind === undefined);\n}\n\nfunction assertRotationRecoveryPrerequisites(state: DocumentStoreState) {\n if (state.persistence.supportsAtomicRecoveryHistoryPruning !== true) {\n throw new Error(\n \"Rotation raw-history recovery requires an adapter with atomic local-history pruning\",\n );\n }\n const author = resolveDocumentCreateAuthor(state.runtime);\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n const documentId = state.record?.documentId;\n if (\n !author ||\n !encapsulationKeyPair ||\n !documentId ||\n !state.runtime.auth.isAuthenticated ||\n !state.runtime.state.online\n ) {\n throw new Error(\n \"Rotation requires verified full-history recovery, but remote sync prerequisites are unavailable\",\n );\n }\n return { author, documentId, encapsulationKeyPair };\n}\n\nfunction assertRotationRecoveryGeneration(input: {\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction rotationIncomingUpdateIsolation(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n return {\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(\n input.state,\n input.generation,\n ),\n validateIncomingUpdates: async (\n result: Pick<\n NonNullable<Awaited<ReturnType<typeof syncRemoteDocument>>>,\n \"decryptedUpdates\" | \"response\"\n >,\n ) => {\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n });\n const decryptedUpdates = ordinaryRawHistoryUpdates(\n result.decryptedUpdates,\n );\n const ordinaryUpdateIds = new Set(\n decryptedUpdates.map((update) => update.id),\n );\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates,\n responseUpdates: result.response.updates.filter((update) =>\n ordinaryUpdateIds.has(update.id),\n ),\n });\n },\n };\n}\n\nasync function pullVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n rebuiltDocument: DocumentState;\n state: DocumentStoreState;\n}) {\n const { author, documentId, encapsulationKeyPair } =\n assertRotationRecoveryPrerequisites(input.state);\n let pullContinuation: DocumentSyncPullContinuation | undefined;\n const seenPullCursors = new Set<string>();\n let planningRecord = input.currentRecord;\n let writerProjection =\n input.state.writerProjection?.documentId === documentId\n ? input.state.writerProjection\n : undefined;\n\n while (true) {\n let abandonReason: string | null = null;\n const synced = await syncRemoteDocument({\n apiClient: input.state.runtime.apiClient,\n author,\n documentId,\n execSql: input.state.runtime.infra.execSql,\n historyMode: \"raw\",\n isRemoteSyncBlocked: input.state.runtime.util.isRemoteSyncBlocked,\n localVersionVector: null,\n minLsn: input.currentRecord.lastCommitLsn ?? undefined,\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n input.state,\n input.generation,\n input.currentRecord,\n documentId,\n commitPurgeProof,\n ),\n // Recorded, never parked: this pass submits no writes, so it plans no\n // ancestor repair and cannot abandon as `inaccessible`.\n onSyncAbandoned: (reason) => {\n abandonReason = reason;\n },\n ...rotationIncomingUpdateIsolation({\n currentDocument: input.rebuiltDocument,\n generation: input.generation,\n state: input.state,\n }),\n onSyncTrace: (line) => input.state.runtime.util.log(`Documents: ${line}`),\n pendingUpdates: [],\n persistedState: planningRecord,\n pullContinuation,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime: input.state.runtime,\n writerKeyLabel: \"writer key\",\n }),\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.state.runtime,\n ),\n writerProjection,\n });\n if (!synced) {\n throw new Error(\n `Rotation raw-history recovery could not complete (${abandonReason ?? \"sync did not finish\"}); key rotation was not started`,\n );\n }\n\n assertRotationRecoveryGeneration(input);\n\n importSyncedDocumentUpdates(\n input.rebuiltDocument,\n ordinaryRawHistoryUpdates(synced.decryptedUpdates),\n );\n if (!synced.hasIncompletePull) return synced;\n\n const nextContinuation = readPullContinuation(synced.response);\n if (!nextContinuation) {\n throw new Error(\n \"Rotation raw-history recovery ended before the retained history was complete\",\n );\n }\n if (seenPullCursors.has(nextContinuation.cursor)) {\n throw new Error(\n \"Rotation raw-history recovery encountered a repeated pull cursor\",\n );\n }\n seenPullCursors.add(nextContinuation.cursor);\n pullContinuation = nextContinuation;\n planningRecord = { ...planningRecord, ...synced.persistedState };\n writerProjection = synced.writerProjection;\n }\n}\n\nasync function collectVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const consumedPullContinuation = input.state.pullContinuation;\n const writerProjectionGeneration = input.state.writerProjectionGeneration;\n const rebuiltDocument = await createStoredDocument(input.state);\n try {\n const synced = await pullVerifiedRawHistoryForRotation({\n ...input,\n rebuiltDocument,\n });\n return {\n consumedPullContinuation,\n currentRecord: input.currentRecord,\n rebuiltDocument,\n synced,\n writerProjectionGeneration,\n };\n } catch (error) {\n rebuiltDocument.free();\n throw error;\n }\n}\n\nclass RotationDocumentChangedError extends Error {}\n\nfunction assertCapturedDocumentCurrent(input: {\n capturedVersion: string;\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n assertRotationRecoveryGeneration(input);\n if (\n !versionVectorsEqual(\n encodeVersionVector(input.currentDocument),\n input.capturedVersion,\n )\n ) {\n throw new RotationDocumentChangedError(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction currentRotationRecoveryRecord(\n state: DocumentStoreState,\n): NonNullable<DocumentStoreState[\"record\"]> {\n if (state.record) return state.record;\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n}\n\nfunction installRotationRecovery(input: {\n capturedVersion: string;\n collection: Awaited<ReturnType<typeof collectVerifiedRawHistoryForRotation>>;\n currentDoc: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const { capturedVersion, collection, currentDoc, generation, state } = input;\n const installation = state.writeChain\n .catch(() => undefined)\n .then(() =>\n chainIdentityWrite(state, async () => {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n assertExactDocumentHistory({\n currentDocument: currentDoc,\n rebuiltDocument: collection.rebuiltDocument,\n });\n return installRebuiltDocument({\n consumedPullContinuation: collection.consumedPullContinuation,\n currentRecord: collection.currentRecord,\n generation,\n rebuiltDoc: collection.rebuiltDocument,\n state,\n synced: collection.synced,\n writerProjectionGeneration: collection.writerProjectionGeneration,\n });\n }),\n );\n // Only the checked local install occupies the write queue. Network recovery\n // uses the remote queue, so an outage cannot hold new edits hostage.\n void chainQueuedWrite(\n state,\n installation.then(\n () => undefined,\n () => undefined,\n ),\n );\n return installation;\n}\n\nasync function recoverFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n): Promise<Uint8Array> {\n assertRotationRecoveryPrerequisites(state);\n await invalidatePullContinuationBeforeRotation(state);\n const currentDoc = state.doc;\n const currentRecord = state.record;\n if (!currentDoc || !currentRecord) {\n throw new Error(\n \"Document must finish loading before its content key can rotate\",\n );\n }\n // The teardown guard for the recovery's terminal-failure handler: captured\n // before the pull so a discard (row 21) racing this preflight invalidates\n // it, and the stale handler cannot resurrect a deleted failure row.\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n laneGeneration,\n );\n if (!generation) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n\n const capturedVersion = encodeVersionVector(currentDoc);\n let settlementRequiresRetry = false;\n\n // A raw recovery starts from an empty scratch document, bypasses untrusted\n // rotation-baseline redirects, drains every retained page in memory, and\n // publishes nothing until all response updates have validated. Checkpoints\n // are authenticated and decrypted but are not reconstruction inputs: the\n // original ordinary update stream is the source of truth in this mode.\n let collection = await collectVerifiedRawHistoryForRotation({\n currentRecord,\n generation,\n state,\n });\n\n try {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const pendingUpdates = await listPendingUpdates(state);\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const verifiedOrdinaryVersion = importProvenOrdinaryPendingHistory({\n currentDocument: currentDoc,\n pendingUpdates,\n rebuiltDocument: collection.rebuiltDocument,\n });\n if (pendingUpdates.some((update) => update.sourceVersionVector == null)) {\n // The first raw pass proves the exact ordinary frontier before any local\n // row can be published. Pull raw history again after settlement so the\n // installed snapshot also includes remote work that raced that submit.\n await settleOrdinaryDocumentUpdatesBeforeRotation(\n state,\n verifiedOrdinaryVersion,\n pendingUpdates,\n generation,\n );\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const definitiveCollection = await collectVerifiedRawHistoryForRotation({\n currentRecord: currentRotationRecoveryRecord(state),\n generation,\n state,\n });\n collection.rebuiltDocument.free();\n collection = definitiveCollection;\n }\n const installed = await installRotationRecovery({\n capturedVersion,\n collection,\n currentDoc,\n generation,\n state,\n });\n settlementRequiresRetry = installed.settlementRequiresRetry;\n if (settlementRequiresRetry) {\n throw new Error(\n \"Rotation raw-history recovery was superseded during its atomic install; retry key rotation\",\n );\n }\n return installed.fullHistorySnapshot;\n } finally {\n if (state.doc !== collection.rebuiltDocument) {\n collection.rebuiltDocument.free();\n }\n if (settlementRequiresRetry) {\n requestDocumentStoreSync(state);\n }\n }\n}\n\n/**\n * Wait for prior local writes and serialize with other remote work. Edits can\n * continue during the pull; the checked install rejects a changed document so\n * a stale recovery cannot replace them. This preflight can then be retried.\n * `reuse` returns the last completed proof while it still covers this exact\n * local document (rotationProofRecord); otherwise it proves like `prove`.\n */\nexport function assertDocumentStoreCanRotateContentKey(\n state: DocumentStoreState,\n proof: DocumentRotationProofMode = \"prove\",\n): Promise<Uint8Array> {\n const laneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n state.doc,\n laneGeneration,\n );\n return runDocumentRemoteWork(state, async () => {\n await state.writeChain.catch(() => undefined);\n if (\n !generation ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document changed before rotation recovery; retry key rotation\",\n );\n }\n const recorded =\n proof === \"reuse\" ? currentRecordedRotationProof(state) : null;\n if (recorded) return recorded;\n const snapshot = await proveFullHistoryForRotation(\n state,\n laneGeneration,\n generation,\n );\n recordRotationProof(state, snapshot);\n return snapshot;\n });\n}\n\nasync function proveFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n generation: DocumentStoreSyncGeneration,\n): Promise<Uint8Array> {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await recoverFullHistoryForRotation(state, laneGeneration);\n } catch (error) {\n // Autosaves and conflict re-keying can invalidate the proven frontier.\n // Repeat the complete proof without blocking new local edits; repeated\n // changes remain bounded and leave the durable queue retryable.\n if (\n !(\n error instanceof RotationPendingUpdatesChangedError ||\n error instanceof RotationDocumentChangedError\n ) ||\n attempt >= 2 ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw error;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC3E,OAAO,EACL,qCAAqC,EAGrC,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EAClB,iCAAiC,GAClC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACL,4CAA4C,EAC5C,sCAAsC,EAGtC,oCAAoC,GACrC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB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CAAC;QACJ,CAAC;QACD,MAAM,QAAQ,GACZ,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,4BAA4B,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACjE,IAAI,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAC9B,MAAM,QAAQ,GAAG,MAAM,2BAA2B,CAChD,KAAK,EACL,cAAc,EACd,UAAU,CACX,CAAC;QACF,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;QACrC,OAAO,QAAQ,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,KAAK,UAAU,2BAA2B,CACxC,KAAyB,EACzB,cAA+C,EAC/C,UAAuC;IAEvC,KAAK,IAAI,OAAO,GAAG,CAAC,GAAI,OAAO,IAAI,CAAC,EAAE,CAAC;QACrC,IAAI,CAAC;YACH,OAAO,MAAM,6BAA6B,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QACpE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,uEAAuE;YACvE,uEAAuE;YACvE,gEAAgE;YAChE,IACE,CAAC,CACC,KAAK,YAAY,kCAAkC;gBACnD,KAAK,YAAY,4BAA4B,CAC9C;gBACD,OAAO,IAAI,CAAC;gBACZ,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC,EACxD,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector, versionVectorsEqual } from \"@tearleads/loro\";\nimport {\n createDocumentWriterPublicKeyResolver,\n type DocumentRotationProofMode,\n type DocumentSyncPullContinuation,\n readPullContinuation,\n resolveDocumentCreateAuthor,\n syncRemoteDocument,\n validateDocumentSyncUpdateImports,\n} from \"../../../../workflows/documents\";\n\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport { installRebuiltDocument } from \"../history/historyRebuild\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { chainQueuedWrite } from \"../localWriteQueue\";\nimport { listPendingUpdates } from \"../persistence\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\nimport { createStoredDocument } from \"../storedDocument\";\nimport { runDocumentRemoteWork } from \"../sync/remoteWork\";\nimport {\n captureDocumentStoreAttachmentSyncGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreSyncGeneration,\n type DocumentStoreSyncLaneGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { deleteUpstreamDeletedDocument } from \"../sync/syncRequest\";\nimport { documentIncomingUpdateIsolationFailureHandler } from \"../sync/syncShared\";\nimport { importSyncedDocumentUpdates } from \"../sync/syncUpdateImport\";\nimport {\n currentRecordedRotationProof,\n recordRotationProof,\n} from \"./rotationProofRecord\";\nimport {\n assertExactDocumentHistory,\n importProvenOrdinaryPendingHistory,\n} from \"./rotationProvenance\";\nimport {\n invalidatePullContinuationBeforeRotation,\n RotationPendingUpdatesChangedError,\n settleOrdinaryDocumentUpdatesBeforeRotation,\n} from \"./rotationSettlement\";\n\nfunction ordinaryRawHistoryUpdates<T extends { checkpointKind?: string }>(\n updates: readonly T[],\n): T[] {\n return updates.filter((update) => update.checkpointKind === undefined);\n}\n\nfunction assertRotationRecoveryPrerequisites(state: DocumentStoreState) {\n if (state.persistence.supportsAtomicRecoveryHistoryPruning !== true) {\n throw new Error(\n \"Rotation raw-history recovery requires an adapter with atomic local-history pruning\",\n );\n }\n const author = resolveDocumentCreateAuthor(state.runtime);\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n const documentId = state.record?.documentId;\n if (\n !author ||\n !encapsulationKeyPair ||\n !documentId ||\n !state.runtime.auth.isAuthenticated ||\n !state.runtime.state.online\n ) {\n throw new Error(\n \"Rotation requires verified full-history recovery, but remote sync prerequisites are unavailable\",\n );\n }\n return { author, documentId, encapsulationKeyPair };\n}\n\nfunction assertRotationRecoveryGeneration(input: {\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction rotationIncomingUpdateIsolation(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n return {\n onIncomingUpdateIsolationFailure:\n documentIncomingUpdateIsolationFailureHandler(\n input.state,\n input.generation,\n ),\n validateIncomingUpdates: async (\n result: Pick<\n NonNullable<Awaited<ReturnType<typeof syncRemoteDocument>>>,\n \"decryptedUpdates\" | \"response\"\n >,\n ) => {\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates: result.decryptedUpdates,\n responseUpdates: result.response.updates,\n });\n const decryptedUpdates = ordinaryRawHistoryUpdates(\n result.decryptedUpdates,\n );\n const ordinaryUpdateIds = new Set(\n decryptedUpdates.map((update) => update.id),\n );\n await validateDocumentSyncUpdateImports({\n currentDocument: input.currentDocument,\n decryptedUpdates,\n responseUpdates: result.response.updates.filter((update) =>\n ordinaryUpdateIds.has(update.id),\n ),\n });\n },\n };\n}\n\nasync function pullVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n rebuiltDocument: DocumentState;\n state: DocumentStoreState;\n}) {\n const { author, documentId, encapsulationKeyPair } =\n assertRotationRecoveryPrerequisites(input.state);\n let pullContinuation: DocumentSyncPullContinuation | undefined;\n const seenPullCursors = new Set<string>();\n let planningRecord = input.currentRecord;\n let writerProjection =\n input.state.writerProjection?.documentId === documentId\n ? input.state.writerProjection\n : undefined;\n\n while (true) {\n let abandonReason: string | null = null;\n const synced = await syncRemoteDocument({\n apiClient: input.state.runtime.apiClient,\n author,\n documentId,\n execSql: input.state.runtime.infra.execSql,\n historyMode: \"raw\",\n isRemoteSyncBlocked: input.state.runtime.util.isRemoteSyncBlocked,\n localVersionVector: null,\n minLsn: input.currentRecord.lastCommitLsn ?? undefined,\n onRemoteDocumentDeleted: ({ commitPurgeProof, documentId }) =>\n deleteUpstreamDeletedDocument(\n input.state,\n input.generation,\n input.currentRecord,\n documentId,\n commitPurgeProof,\n ),\n // Recorded, never parked: this pass submits no writes, so it plans no\n // ancestor repair and cannot abandon as `inaccessible`.\n onSyncAbandoned: (reason) => {\n abandonReason = reason;\n },\n ...rotationIncomingUpdateIsolation({\n currentDocument: input.rebuiltDocument,\n generation: input.generation,\n state: input.state,\n }),\n onSyncTrace: (line) => input.state.runtime.util.log(`Documents: ${line}`),\n pendingUpdates: [],\n persistedState: planningRecord,\n pullContinuation,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n resolveWriterPublicKey: createDocumentWriterPublicKeyResolver({\n logPrefix: \"Documents\",\n runtime: input.state.runtime,\n writerKeyLabel: \"writer key\",\n }),\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies:\n input.state.runtime.principalPolicies.createWarmer(),\n writerProjection,\n });\n if (!synced) {\n throw new Error(\n `Rotation raw-history recovery could not complete (${abandonReason ?? \"sync did not finish\"}); key rotation was not started`,\n );\n }\n\n assertRotationRecoveryGeneration(input);\n\n importSyncedDocumentUpdates(\n input.rebuiltDocument,\n ordinaryRawHistoryUpdates(synced.decryptedUpdates),\n );\n if (!synced.hasIncompletePull) return synced;\n\n const nextContinuation = readPullContinuation(synced.response);\n if (!nextContinuation) {\n throw new Error(\n \"Rotation raw-history recovery ended before the retained history was complete\",\n );\n }\n if (seenPullCursors.has(nextContinuation.cursor)) {\n throw new Error(\n \"Rotation raw-history recovery encountered a repeated pull cursor\",\n );\n }\n seenPullCursors.add(nextContinuation.cursor);\n pullContinuation = nextContinuation;\n planningRecord = { ...planningRecord, ...synced.persistedState };\n writerProjection = synced.writerProjection;\n }\n}\n\nasync function collectVerifiedRawHistoryForRotation(input: {\n currentRecord: NonNullable<DocumentStoreState[\"record\"]>;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const consumedPullContinuation = input.state.pullContinuation;\n const writerProjectionGeneration = input.state.writerProjectionGeneration;\n const rebuiltDocument = await createStoredDocument(input.state);\n try {\n const synced = await pullVerifiedRawHistoryForRotation({\n ...input,\n rebuiltDocument,\n });\n return {\n consumedPullContinuation,\n currentRecord: input.currentRecord,\n rebuiltDocument,\n synced,\n writerProjectionGeneration,\n };\n } catch (error) {\n rebuiltDocument.free();\n throw error;\n }\n}\n\nclass RotationDocumentChangedError extends Error {}\n\nfunction assertCapturedDocumentCurrent(input: {\n capturedVersion: string;\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}): void {\n assertRotationRecoveryGeneration(input);\n if (\n !versionVectorsEqual(\n encodeVersionVector(input.currentDocument),\n input.capturedVersion,\n )\n ) {\n throw new RotationDocumentChangedError(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n}\n\nfunction currentRotationRecoveryRecord(\n state: DocumentStoreState,\n): NonNullable<DocumentStoreState[\"record\"]> {\n if (state.record) return state.record;\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n}\n\nfunction installRotationRecovery(input: {\n capturedVersion: string;\n collection: Awaited<ReturnType<typeof collectVerifiedRawHistoryForRotation>>;\n currentDoc: DocumentState;\n generation: DocumentStoreSyncGeneration;\n state: DocumentStoreState;\n}) {\n const { capturedVersion, collection, currentDoc, generation, state } = input;\n const installation = state.writeChain\n .catch(() => undefined)\n .then(() =>\n chainIdentityWrite(state, async () => {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n assertExactDocumentHistory({\n currentDocument: currentDoc,\n rebuiltDocument: collection.rebuiltDocument,\n });\n return installRebuiltDocument({\n consumedPullContinuation: collection.consumedPullContinuation,\n currentRecord: collection.currentRecord,\n generation,\n rebuiltDoc: collection.rebuiltDocument,\n state,\n synced: collection.synced,\n writerProjectionGeneration: collection.writerProjectionGeneration,\n });\n }),\n );\n // Only the checked local install occupies the write queue. Network recovery\n // uses the remote queue, so an outage cannot hold new edits hostage.\n void chainQueuedWrite(\n state,\n installation.then(\n () => undefined,\n () => undefined,\n ),\n );\n return installation;\n}\n\nasync function recoverFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n): Promise<Uint8Array> {\n assertRotationRecoveryPrerequisites(state);\n await invalidatePullContinuationBeforeRotation(state);\n const currentDoc = state.doc;\n const currentRecord = state.record;\n if (!currentDoc || !currentRecord) {\n throw new Error(\n \"Document must finish loading before its content key can rotate\",\n );\n }\n // The teardown guard for the recovery's terminal-failure handler: captured\n // before the pull so a discard (row 21) racing this preflight invalidates\n // it, and the stale handler cannot resurrect a deleted failure row.\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n currentDoc,\n laneGeneration,\n );\n if (!generation) {\n throw new Error(\n \"Document changed during rotation recovery; retry key rotation\",\n );\n }\n\n const capturedVersion = encodeVersionVector(currentDoc);\n let settlementRequiresRetry = false;\n\n // A raw recovery starts from an empty scratch document, bypasses untrusted\n // rotation-baseline redirects, drains every retained page in memory, and\n // publishes nothing until all response updates have validated. Checkpoints\n // are authenticated and decrypted but are not reconstruction inputs: the\n // original ordinary update stream is the source of truth in this mode.\n let collection = await collectVerifiedRawHistoryForRotation({\n currentRecord,\n generation,\n state,\n });\n\n try {\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const pendingUpdates = await listPendingUpdates(state);\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const verifiedOrdinaryVersion = importProvenOrdinaryPendingHistory({\n currentDocument: currentDoc,\n pendingUpdates,\n rebuiltDocument: collection.rebuiltDocument,\n });\n if (pendingUpdates.some((update) => update.sourceVersionVector == null)) {\n // The first raw pass proves the exact ordinary frontier before any local\n // row can be published. Pull raw history again after settlement so the\n // installed snapshot also includes remote work that raced that submit.\n await settleOrdinaryDocumentUpdatesBeforeRotation(\n state,\n verifiedOrdinaryVersion,\n pendingUpdates,\n generation,\n );\n assertCapturedDocumentCurrent({\n capturedVersion,\n currentDocument: currentDoc,\n generation,\n state,\n });\n const definitiveCollection = await collectVerifiedRawHistoryForRotation({\n currentRecord: currentRotationRecoveryRecord(state),\n generation,\n state,\n });\n collection.rebuiltDocument.free();\n collection = definitiveCollection;\n }\n const installed = await installRotationRecovery({\n capturedVersion,\n collection,\n currentDoc,\n generation,\n state,\n });\n settlementRequiresRetry = installed.settlementRequiresRetry;\n if (settlementRequiresRetry) {\n throw new Error(\n \"Rotation raw-history recovery was superseded during its atomic install; retry key rotation\",\n );\n }\n return installed.fullHistorySnapshot;\n } finally {\n if (state.doc !== collection.rebuiltDocument) {\n collection.rebuiltDocument.free();\n }\n if (settlementRequiresRetry) {\n requestDocumentStoreSync(state);\n }\n }\n}\n\n/**\n * Wait for prior local writes and serialize with other remote work. Edits can\n * continue during the pull; the checked install rejects a changed document so\n * a stale recovery cannot replace them. This preflight can then be retried.\n * `reuse` returns the last completed proof while it still covers this exact\n * local document (rotationProofRecord); otherwise it proves like `prove`.\n */\nexport function assertDocumentStoreCanRotateContentKey(\n state: DocumentStoreState,\n proof: DocumentRotationProofMode = \"prove\",\n): Promise<Uint8Array> {\n const laneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n const generation = captureDocumentStoreAttachmentSyncGeneration(\n state,\n state.doc,\n laneGeneration,\n );\n return runDocumentRemoteWork(state, async () => {\n await state.writeChain.catch(() => undefined);\n if (\n !generation ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document changed before rotation recovery; retry key rotation\",\n );\n }\n const recorded =\n proof === \"reuse\" ? currentRecordedRotationProof(state) : null;\n if (recorded) return recorded;\n const snapshot = await proveFullHistoryForRotation(\n state,\n laneGeneration,\n generation,\n );\n recordRotationProof(state, snapshot);\n return snapshot;\n });\n}\n\nasync function proveFullHistoryForRotation(\n state: DocumentStoreState,\n laneGeneration: DocumentStoreSyncLaneGeneration,\n generation: DocumentStoreSyncGeneration,\n): Promise<Uint8Array> {\n for (let attempt = 0; ; attempt += 1) {\n try {\n return await recoverFullHistoryForRotation(state, laneGeneration);\n } catch (error) {\n // Autosaves and conflict re-keying can invalidate the proven frontier.\n // Repeat the complete proof without blocking new local edits; repeated\n // changes remain bounded and leave the durable queue retryable.\n if (\n !(\n error instanceof RotationPendingUpdatesChangedError ||\n error instanceof RotationDocumentChangedError\n ) ||\n attempt >= 2 ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw error;\n }\n }\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { encodeVersionVector, satisfiesVersionVector } from "../../../../internal/loro/index.js";
2
- import { createPrincipalPolicyOperation } from "../../../../workflows/principals/runtimePolicyWarmer.js";
2
+ import { createPrincipalPolicyOperation } from "../../../../workflows/principals/principalPolicyService.js";
3
3
  import { chainIdentityWrite } from "../identityWriteChain.js";
4
4
  import { listPendingUpdates, persistDocument } from "../persistence.js";
5
5
  import { invalidateDocumentStorePullContinuation } from "../sync/pullContinuationInvalidation.js";
@@ -1 +1 @@
1
- {"version":3,"file":"rotationSettlement.js","sourceRoot":"","sources":["rotationSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AACtG,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAMrE,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAC/F,OAAO,EACL,sCAAsC,EACtC,uCAAuC,EACvC,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kCAAkC,EAElC,oCAAoC,GACrC,MAAM,wBAAwB,CAA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BAAgB,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC,EACzE,CAAC;YACD,OAAO;QACT,CAAC;QAED,MAAM,UAAU,GAAG,GAAG,gBAAgB,KAAK,mBAAmB,CAAC,cAAc,CAAC,EAAE,CAAC;QACjF,IAAI,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;QACJ,CAAC;QACD,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACnC,gBAAgB,GAAG,MAAM,wBAAwB,CAAC;YAChD,UAAU;YACV,cAAc,EAAE,iBAAiB;YACjC,KAAK;YACL,mBAAmB,EAAE,gBAAgB;SACtC,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector, satisfiesVersionVector } from \"@tearleads/loro\";\nimport type { PendingUpdateRecord } from \"../../../../workflows/documents\";\nimport { createPrincipalPolicyOperation } from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { listPendingUpdates, persistDocument } from \"../persistence\";\nimport type {\n DocumentState,\n DocumentStoreState,\n DocumentSyncAttempt,\n} from \"../state\";\nimport { invalidateDocumentStorePullContinuation } from \"../sync/pullContinuationInvalidation\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardUnacceptedPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"../sync/syncAcceptedUpdateIds\";\nimport {\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { prepareDocumentOutgoingCoverage } from \"../sync/syncOutgoingCoverage\";\nimport { requestRemoteDocumentSync } from \"../sync/syncRequest\";\nimport { extendDocumentVersionCoverage } from \"../sync/versionCoverage\";\n\nexport class RotationPendingUpdatesChangedError extends Error {}\n\nfunction ordinaryPendingUpdates(\n pendingUpdates: readonly PendingUpdateRecord[],\n): PendingUpdateRecord[] {\n return pendingUpdates.filter(\n (pendingUpdate) => pendingUpdate.sourceVersionVector == null,\n );\n}\n\nfunction pendingUpdateSetKey(pendingUpdates: readonly PendingUpdateRecord[]) {\n return pendingUpdates\n .map((pendingUpdate) => pendingUpdate.id)\n .sort()\n .join(\"\\n\");\n}\n\nfunction pendingUpdateMatchesProvenRow(\n pendingUpdate: PendingUpdateRecord,\n provenUpdate: PendingUpdateRecord,\n): boolean {\n return (\n pendingUpdate.id === provenUpdate.id &&\n pendingUpdate.updateData === provenUpdate.updateData &&\n pendingUpdate.partialStartVersionVector ===\n provenUpdate.partialStartVersionVector &&\n pendingUpdate.partialEndVersionVector ===\n provenUpdate.partialEndVersionVector &&\n pendingUpdate.sourceVersionVector === provenUpdate.sourceVersionVector\n );\n}\n\nfunction assertOrdinaryRowsWereProven(input: {\n pendingUpdates: readonly PendingUpdateRecord[];\n provenUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n}): void {\n for (const pendingUpdate of ordinaryPendingUpdates(input.pendingUpdates)) {\n const provenUpdate = input.provenUpdatesById.get(pendingUpdate.id);\n if (\n !provenUpdate ||\n !pendingUpdateMatchesProvenRow(pendingUpdate, provenUpdate)\n ) {\n throw new RotationPendingUpdatesChangedError(\n \"Document local updates changed after rotation provenance verification\",\n );\n }\n }\n}\n\nfunction ordinaryPendingUpdatesWithProvenCoverage(input: {\n currentDocument: DocumentState;\n pendingUpdates: PendingUpdateRecord[];\n verifiedBaseVersion: string;\n}): { coverage: string; pendingUpdates: PendingUpdateRecord[] } {\n const ordinaryUpdates = ordinaryPendingUpdates(input.pendingUpdates);\n const documentVersion = encodeVersionVector(input.currentDocument);\n const ordinaryCoverage = extendDocumentVersionCoverage({\n baseVersion: input.verifiedBaseVersion,\n documentVersion,\n spans: ordinaryUpdates,\n });\n if (!satisfiesVersionVector(ordinaryCoverage, documentVersion)) {\n throw new Error(\n \"Document rotation cannot settle uncovered local history because it may be checkpoint-derived\",\n );\n }\n return { coverage: ordinaryCoverage, pendingUpdates: ordinaryUpdates };\n}\n\nexport async function invalidatePullContinuationBeforeRotation(\n state: DocumentStoreState,\n): Promise<void> {\n const continuation = state.pullContinuation;\n if (!continuation) return;\n const currentDoc = state.doc;\n const currentRecord = state.record;\n if (!currentDoc || !currentRecord) {\n throw new Error(\n \"Document changed while its pull continuation was invalidated for key rotation\",\n );\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n throw new Error(\n \"Document changed while its pull continuation was invalidated for key rotation\",\n );\n }\n await invalidateDocumentStorePullContinuation({\n continuation,\n currentRecord,\n generation,\n state,\n });\n if (\n state.pullContinuation !== null ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document pull continuation could not be invalidated before key rotation\",\n );\n }\n}\n\nasync function persistStagedSettlement(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n preparedRecord: NonNullable<DocumentStoreState[\"record\"]>;\n sentUpdateIds: string[];\n state: DocumentStoreState;\n syncAttempt: DocumentSyncAttempt;\n}): Promise<void> {\n const { state, syncAttempt } = input;\n discardUnacceptedPreRegisteredUpdateIds(\n state,\n input.sentUpdateIds,\n syncAttempt.synced.response.acceptedOutgoingUpdateIds,\n );\n const persisted = await persistDocument(\n state,\n input.currentDocument,\n {\n lastCommitLsn:\n syncAttempt.synced.response.commitLsn ??\n input.preparedRecord.lastCommitLsn ??\n null,\n pullContinuation: null,\n },\n {\n acceptedPendingUpdateIds: syncAttempt.synced.settledPendingUpdateIds,\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation,\n record: syncAttempt.requestRecord,\n },\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n input.generation,\n );\n if (\n !persisted ||\n persisted.pullContinuationSuperseded ||\n persisted.syncIdentitySuperseded ||\n !isDocumentStoreSyncGenerationCurrent(state, input.generation)\n ) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n}\n\nfunction settledOrdinaryCoverage(input: {\n currentDocument: DocumentState;\n pendingUpdates: PendingUpdateRecord[];\n settledUpdateIds: readonly string[];\n verifiedBaseVersion: string;\n}): string {\n const settled = new Set(input.settledUpdateIds);\n return extendDocumentVersionCoverage({\n baseVersion: input.verifiedBaseVersion,\n documentVersion: encodeVersionVector(input.currentDocument),\n spans: input.pendingUpdates.filter((update) => settled.has(update.id)),\n });\n}\n\nasync function persistStagedSettlementOnIdentityChain(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n pendingUpdates: PendingUpdateRecord[];\n preparedRecord: NonNullable<DocumentStoreState[\"record\"]>;\n sentUpdateIds: string[];\n state: DocumentStoreState;\n syncAttempt: DocumentSyncAttempt;\n verifiedBaseVersion: string;\n}): Promise<string> {\n return chainIdentityWrite(input.state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n await persistStagedSettlement(input);\n return settledOrdinaryCoverage({\n currentDocument: input.currentDocument,\n pendingUpdates: input.pendingUpdates,\n settledUpdateIds: input.syncAttempt.synced.settledPendingUpdateIds,\n verifiedBaseVersion: input.verifiedBaseVersion,\n });\n });\n}\n\nasync function settleOrdinaryUpdatePass(input: {\n generation: DocumentStoreSyncGeneration;\n pendingUpdates: PendingUpdateRecord[];\n state: DocumentStoreState;\n verifiedBaseVersion: string;\n}): Promise<string> {\n const { state } = input;\n const currentDoc = state.doc;\n const currentRecord = state.record;\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n if (!currentDoc || !currentRecord || !encapsulationKeyPair) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n const generation = input.generation;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n const proven = ordinaryPendingUpdatesWithProvenCoverage({\n currentDocument: currentDoc,\n pendingUpdates: input.pendingUpdates,\n verifiedBaseVersion: input.verifiedBaseVersion,\n });\n const prepared = await prepareDocumentOutgoingCoverage({\n coverageBaseVersion: input.verifiedBaseVersion,\n currentDoc,\n generation,\n pendingUpdates: proven.pendingUpdates,\n state,\n });\n if (!prepared || !isDocumentStoreSyncGenerationCurrent(state, generation)) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n const preparedPendingUpdates = ordinaryPendingUpdates(\n prepared.pendingUpdates,\n );\n if (preparedPendingUpdates.length === 0) return proven.coverage;\n\n const sentUpdateIds: string[] = [];\n return cleanupPreRegisteredUpdateIdsOnFailure(\n state,\n sentUpdateIds,\n async () => {\n const syncAttempt = await requestRemoteDocumentSync({\n allowRecoveryBaseline: false,\n currentDoc,\n currentRecord: prepared.record,\n encapsulationKeyPair,\n generation,\n onOutgoingUpdatesMaterialized: (updateIds) =>\n preRegisterMaterializedDocumentSyncUpdateIds(\n state,\n sentUpdateIds,\n updateIds,\n ),\n pendingUpdates: preparedPendingUpdates,\n // Rotation settlement runs outside a sync drain: its own operation.\n policyOperation: createPrincipalPolicyOperation(),\n queuedUpdateCount: preparedPendingUpdates.length,\n state,\n unavailableWriterLogMessage:\n \"Documents: rotation could not settle local updates because the writer context is unavailable.\",\n });\n if (\n !syncAttempt ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document local updates could not be committed before key rotation\",\n );\n }\n\n return persistStagedSettlementOnIdentityChain({\n currentDocument: currentDoc,\n generation,\n pendingUpdates: preparedPendingUpdates,\n preparedRecord: prepared.record,\n sentUpdateIds,\n state,\n syncAttempt,\n verifiedBaseVersion: input.verifiedBaseVersion,\n });\n },\n );\n}\n\n/**\n * Commit only ordinary local rows before rotation. Server-returned updates are\n * authenticated and decrypted by the workflow but deliberately not imported\n * or persisted; the subsequent raw rebuild owns that all-or-nothing install.\n */\nexport async function settleOrdinaryDocumentUpdatesBeforeRotation(\n state: DocumentStoreState,\n verifiedBaseVersion: string,\n provenPendingUpdates: readonly PendingUpdateRecord[],\n generation: DocumentStoreSyncGeneration,\n): Promise<void> {\n const stalledQueueStates = new Set<string>();\n let verifiedCoverage = verifiedBaseVersion;\n const provenUpdatesById = new Map(\n ordinaryPendingUpdates(provenPendingUpdates).map((update) => [\n update.id,\n update,\n ]),\n );\n\n while (true) {\n const currentDoc = state.doc;\n if (!currentDoc) {\n throw new Error(\"Document rotation requires an initialized document\");\n }\n const allPendingUpdates = await listPendingUpdates(state);\n assertOrdinaryRowsWereProven({\n pendingUpdates: allPendingUpdates,\n provenUpdatesById,\n });\n const pendingUpdates = ordinaryPendingUpdates(allPendingUpdates);\n if (\n pendingUpdates.length === 0 &&\n satisfiesVersionVector(verifiedCoverage, encodeVersionVector(currentDoc))\n ) {\n return;\n }\n\n const queueState = `${verifiedCoverage}\\n${pendingUpdateSetKey(pendingUpdates)}`;\n if (stalledQueueStates.has(queueState)) {\n throw new Error(\n \"Document local updates could not be committed before key rotation\",\n );\n }\n stalledQueueStates.add(queueState);\n verifiedCoverage = await settleOrdinaryUpdatePass({\n generation,\n pendingUpdates: allPendingUpdates,\n state,\n verifiedBaseVersion: verifiedCoverage,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"rotationSettlement.js","sourceRoot":"","sources":["rotationSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EAAE,8BAA8B,EAAE,MAAM,yDAAyD,CAAC;AACzG,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAMrE,OAAO,EAAE,uCAAuC,EAAE,MAAM,sCAAsC,CAAC;AAC/F,OAAO,EACL,sCAAsC,EACtC,uCAAuC,EACvC,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,kCAAkC,EA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,KAAK,CAAC;YAC3B,sBAAsB,CAAC,gBAAgB,EAAE,mBAAmB,CAAC,UAAU,CAAC,CAAC,EACzE,CAAC;YACD,OAAO;QACT,CAAC;QAED,MAAM,UAAU,GAAG,GAAG,gBAAgB,KAAK,mBAAmB,CAAC,cAAc,CAAC,EAAE,CAAC;QACjF,IAAI,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CACb,mEAAmE,CACpE,CAAC;QACJ,CAAC;QACD,kBAAkB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QACnC,gBAAgB,GAAG,MAAM,wBAAwB,CAAC;YAChD,UAAU;YACV,cAAc,EAAE,iBAAiB;YACjC,KAAK;YACL,mBAAmB,EAAE,gBAAgB;SACtC,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { encodeVersionVector, satisfiesVersionVector } from \"@tearleads/loro\";\nimport type { PendingUpdateRecord } from \"../../../../workflows/documents\";\nimport { createPrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { listPendingUpdates, persistDocument } from \"../persistence\";\nimport type {\n DocumentState,\n DocumentStoreState,\n DocumentSyncAttempt,\n} from \"../state\";\nimport { invalidateDocumentStorePullContinuation } from \"../sync/pullContinuationInvalidation\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardUnacceptedPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"../sync/syncAcceptedUpdateIds\";\nimport {\n captureDocumentStoreSyncGeneration,\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"../sync/syncGeneration\";\nimport { prepareDocumentOutgoingCoverage } from \"../sync/syncOutgoingCoverage\";\nimport { requestRemoteDocumentSync } from \"../sync/syncRequest\";\nimport { extendDocumentVersionCoverage } from \"../sync/versionCoverage\";\n\nexport class RotationPendingUpdatesChangedError extends Error {}\n\nfunction ordinaryPendingUpdates(\n pendingUpdates: readonly PendingUpdateRecord[],\n): PendingUpdateRecord[] {\n return pendingUpdates.filter(\n (pendingUpdate) => pendingUpdate.sourceVersionVector == null,\n );\n}\n\nfunction pendingUpdateSetKey(pendingUpdates: readonly PendingUpdateRecord[]) {\n return pendingUpdates\n .map((pendingUpdate) => pendingUpdate.id)\n .sort()\n .join(\"\\n\");\n}\n\nfunction pendingUpdateMatchesProvenRow(\n pendingUpdate: PendingUpdateRecord,\n provenUpdate: PendingUpdateRecord,\n): boolean {\n return (\n pendingUpdate.id === provenUpdate.id &&\n pendingUpdate.updateData === provenUpdate.updateData &&\n pendingUpdate.partialStartVersionVector ===\n provenUpdate.partialStartVersionVector &&\n pendingUpdate.partialEndVersionVector ===\n provenUpdate.partialEndVersionVector &&\n pendingUpdate.sourceVersionVector === provenUpdate.sourceVersionVector\n );\n}\n\nfunction assertOrdinaryRowsWereProven(input: {\n pendingUpdates: readonly PendingUpdateRecord[];\n provenUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n}): void {\n for (const pendingUpdate of ordinaryPendingUpdates(input.pendingUpdates)) {\n const provenUpdate = input.provenUpdatesById.get(pendingUpdate.id);\n if (\n !provenUpdate ||\n !pendingUpdateMatchesProvenRow(pendingUpdate, provenUpdate)\n ) {\n throw new RotationPendingUpdatesChangedError(\n \"Document local updates changed after rotation provenance verification\",\n );\n }\n }\n}\n\nfunction ordinaryPendingUpdatesWithProvenCoverage(input: {\n currentDocument: DocumentState;\n pendingUpdates: PendingUpdateRecord[];\n verifiedBaseVersion: string;\n}): { coverage: string; pendingUpdates: PendingUpdateRecord[] } {\n const ordinaryUpdates = ordinaryPendingUpdates(input.pendingUpdates);\n const documentVersion = encodeVersionVector(input.currentDocument);\n const ordinaryCoverage = extendDocumentVersionCoverage({\n baseVersion: input.verifiedBaseVersion,\n documentVersion,\n spans: ordinaryUpdates,\n });\n if (!satisfiesVersionVector(ordinaryCoverage, documentVersion)) {\n throw new Error(\n \"Document rotation cannot settle uncovered local history because it may be checkpoint-derived\",\n );\n }\n return { coverage: ordinaryCoverage, pendingUpdates: ordinaryUpdates };\n}\n\nexport async function invalidatePullContinuationBeforeRotation(\n state: DocumentStoreState,\n): Promise<void> {\n const continuation = state.pullContinuation;\n if (!continuation) return;\n const currentDoc = state.doc;\n const currentRecord = state.record;\n if (!currentDoc || !currentRecord) {\n throw new Error(\n \"Document changed while its pull continuation was invalidated for key rotation\",\n );\n }\n const generation = captureDocumentStoreSyncGeneration(state, currentDoc);\n if (!generation) {\n throw new Error(\n \"Document changed while its pull continuation was invalidated for key rotation\",\n );\n }\n await invalidateDocumentStorePullContinuation({\n continuation,\n currentRecord,\n generation,\n state,\n });\n if (\n state.pullContinuation !== null ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document pull continuation could not be invalidated before key rotation\",\n );\n }\n}\n\nasync function persistStagedSettlement(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n preparedRecord: NonNullable<DocumentStoreState[\"record\"]>;\n sentUpdateIds: string[];\n state: DocumentStoreState;\n syncAttempt: DocumentSyncAttempt;\n}): Promise<void> {\n const { state, syncAttempt } = input;\n discardUnacceptedPreRegisteredUpdateIds(\n state,\n input.sentUpdateIds,\n syncAttempt.synced.response.acceptedOutgoingUpdateIds,\n );\n const persisted = await persistDocument(\n state,\n input.currentDocument,\n {\n lastCommitLsn:\n syncAttempt.synced.response.commitLsn ??\n input.preparedRecord.lastCommitLsn ??\n null,\n pullContinuation: null,\n },\n {\n acceptedPendingUpdateIds: syncAttempt.synced.settledPendingUpdateIds,\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation,\n record: syncAttempt.requestRecord,\n },\n preserveSnapshotStructuredFields: true,\n preserveSnapshotText: true,\n },\n input.generation,\n );\n if (\n !persisted ||\n persisted.pullContinuationSuperseded ||\n persisted.syncIdentitySuperseded ||\n !isDocumentStoreSyncGenerationCurrent(state, input.generation)\n ) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n}\n\nfunction settledOrdinaryCoverage(input: {\n currentDocument: DocumentState;\n pendingUpdates: PendingUpdateRecord[];\n settledUpdateIds: readonly string[];\n verifiedBaseVersion: string;\n}): string {\n const settled = new Set(input.settledUpdateIds);\n return extendDocumentVersionCoverage({\n baseVersion: input.verifiedBaseVersion,\n documentVersion: encodeVersionVector(input.currentDocument),\n spans: input.pendingUpdates.filter((update) => settled.has(update.id)),\n });\n}\n\nasync function persistStagedSettlementOnIdentityChain(input: {\n currentDocument: DocumentState;\n generation: DocumentStoreSyncGeneration;\n pendingUpdates: PendingUpdateRecord[];\n preparedRecord: NonNullable<DocumentStoreState[\"record\"]>;\n sentUpdateIds: string[];\n state: DocumentStoreState;\n syncAttempt: DocumentSyncAttempt;\n verifiedBaseVersion: string;\n}): Promise<string> {\n return chainIdentityWrite(input.state, async () => {\n if (!isDocumentStoreSyncGenerationCurrent(input.state, input.generation)) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n await persistStagedSettlement(input);\n return settledOrdinaryCoverage({\n currentDocument: input.currentDocument,\n pendingUpdates: input.pendingUpdates,\n settledUpdateIds: input.syncAttempt.synced.settledPendingUpdateIds,\n verifiedBaseVersion: input.verifiedBaseVersion,\n });\n });\n}\n\nasync function settleOrdinaryUpdatePass(input: {\n generation: DocumentStoreSyncGeneration;\n pendingUpdates: PendingUpdateRecord[];\n state: DocumentStoreState;\n verifiedBaseVersion: string;\n}): Promise<string> {\n const { state } = input;\n const currentDoc = state.doc;\n const currentRecord = state.record;\n const encapsulationKeyPair = state.runtime.crypto.encapsulationKeyPair;\n if (!currentDoc || !currentRecord || !encapsulationKeyPair) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n const generation = input.generation;\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n const proven = ordinaryPendingUpdatesWithProvenCoverage({\n currentDocument: currentDoc,\n pendingUpdates: input.pendingUpdates,\n verifiedBaseVersion: input.verifiedBaseVersion,\n });\n const prepared = await prepareDocumentOutgoingCoverage({\n coverageBaseVersion: input.verifiedBaseVersion,\n currentDoc,\n generation,\n pendingUpdates: proven.pendingUpdates,\n state,\n });\n if (!prepared || !isDocumentStoreSyncGenerationCurrent(state, generation)) {\n throw new Error(\n \"Document changed while local updates were settling for key rotation\",\n );\n }\n const preparedPendingUpdates = ordinaryPendingUpdates(\n prepared.pendingUpdates,\n );\n if (preparedPendingUpdates.length === 0) return proven.coverage;\n\n const sentUpdateIds: string[] = [];\n return cleanupPreRegisteredUpdateIdsOnFailure(\n state,\n sentUpdateIds,\n async () => {\n const syncAttempt = await requestRemoteDocumentSync({\n allowRecoveryBaseline: false,\n currentDoc,\n currentRecord: prepared.record,\n encapsulationKeyPair,\n generation,\n onOutgoingUpdatesMaterialized: (updateIds) =>\n preRegisterMaterializedDocumentSyncUpdateIds(\n state,\n sentUpdateIds,\n updateIds,\n ),\n pendingUpdates: preparedPendingUpdates,\n // Rotation settlement runs outside a sync drain: its own operation.\n policyOperation: createPrincipalPolicyOperation(),\n queuedUpdateCount: preparedPendingUpdates.length,\n state,\n unavailableWriterLogMessage:\n \"Documents: rotation could not settle local updates because the writer context is unavailable.\",\n });\n if (\n !syncAttempt ||\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n throw new Error(\n \"Document local updates could not be committed before key rotation\",\n );\n }\n\n return persistStagedSettlementOnIdentityChain({\n currentDocument: currentDoc,\n generation,\n pendingUpdates: preparedPendingUpdates,\n preparedRecord: prepared.record,\n sentUpdateIds,\n state,\n syncAttempt,\n verifiedBaseVersion: input.verifiedBaseVersion,\n });\n },\n );\n}\n\n/**\n * Commit only ordinary local rows before rotation. Server-returned updates are\n * authenticated and decrypted by the workflow but deliberately not imported\n * or persisted; the subsequent raw rebuild owns that all-or-nothing install.\n */\nexport async function settleOrdinaryDocumentUpdatesBeforeRotation(\n state: DocumentStoreState,\n verifiedBaseVersion: string,\n provenPendingUpdates: readonly PendingUpdateRecord[],\n generation: DocumentStoreSyncGeneration,\n): Promise<void> {\n const stalledQueueStates = new Set<string>();\n let verifiedCoverage = verifiedBaseVersion;\n const provenUpdatesById = new Map(\n ordinaryPendingUpdates(provenPendingUpdates).map((update) => [\n update.id,\n update,\n ]),\n );\n\n while (true) {\n const currentDoc = state.doc;\n if (!currentDoc) {\n throw new Error(\"Document rotation requires an initialized document\");\n }\n const allPendingUpdates = await listPendingUpdates(state);\n assertOrdinaryRowsWereProven({\n pendingUpdates: allPendingUpdates,\n provenUpdatesById,\n });\n const pendingUpdates = ordinaryPendingUpdates(allPendingUpdates);\n if (\n pendingUpdates.length === 0 &&\n satisfiesVersionVector(verifiedCoverage, encodeVersionVector(currentDoc))\n ) {\n return;\n }\n\n const queueState = `${verifiedCoverage}\\n${pendingUpdateSetKey(pendingUpdates)}`;\n if (stalledQueueStates.has(queueState)) {\n throw new Error(\n \"Document local updates could not be committed before key rotation\",\n );\n }\n stalledQueueStates.add(queueState);\n verifiedCoverage = await settleOrdinaryUpdatePass({\n generation,\n pendingUpdates: allPendingUpdates,\n state,\n verifiedBaseVersion: verifiedCoverage,\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B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E,cAAc,CAAC,KAAK;QAC3B,OAAO;KACR,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,KAAyB,EACzB,OAAgB;IAEhB,mBAAmB,CAAC,KAAK,EAAE,EAAE,GAAG,KAAK,CAAC,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;AAC7D,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAAyB;IACpE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,mBAAmB,CAAC,KAAK,EAAE;QACzB,GAAG,KAAK,CAAC,QAAQ;QACjB,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC;QAChC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC;QACjC,yEAAyE;QACzE,eAAe,EAAE,sBAAsB,CAAC,KAAK,CAAC;QAC9C,oBAAoB,EAAE,6BAA6B,CACjD,KAAK,CAAC,MAAM,EAAE,oBAAoB,CACnC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAyB,EACzB,QAAoB;IAEpB,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/sync/syncPagination\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/keying/accessLevel\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/runtimePolicyWarmer\";\nimport type {\n DocumentSnapshot,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachments/attachmentSnapshot\";\nimport { sameValidationIssues, shallowEqualRecord } from \"./snapshotEquality\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\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?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n /** The request's policy operation; finalizing hydration reuses it. */\n policyOperation: PrincipalPolicyOperation;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n /** Fields and rows a created record starts with; see `initialContent.ts`. */\n initialContent?: Pick<\n DocumentStoreOpenOptions,\n \"initialRows\" | \"initialStructuredFields\"\n >;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Newest queued coalescing write per key; see `localWriteQueue`. */\n localWriteTickets: { issued: number; latestByKey: Map<string, number> };\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n /** Local writes called or chained but unsettled; zero means all in SQLite. */\n queuedWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n startupProbeDeferredAttempt: number | null;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n /**\n * Whether local writes applied ops to `doc` that are not yet durable (e.g.\n * their save failed). Set when a write exports a non-empty delta; cleared once\n * a persist covers `doc` or `doc` is replaced from durable history.\n */\n unsavedLocalEdits: boolean;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteTickets: { issued: 0, latestByKey: new Map() },\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n queuedWrites: 0,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n startupProbeDeferredAttempt: null,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n unsavedLocalEdits: false,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.startupProbeDeferredAttempt = null;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.unsavedLocalEdits = false;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n // Publish runtime identity before a caller captures its write authority.\n currentAuthorId: resolveCurrentAuthorId(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAOtC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAkK9E,MAAM,uBAAuB,GAAqB;IAChD,WAAW,EAAE,EAAE;IACf,wBAAwB,EAAE,EAAE;IAC5B,4BAA4B,EAAE,EAAE;IAChC,SAAS,EAAE,KAAK;IAChB,QAAQ,EAAE,IAAI;IACd,eAAe,EAAE,IAAI;IACrB,UAAU,EAAE,IAAI;IAChB,YAAY,EAAE,qBAAqB;IACnC,oBAAoB,EAAE,OAAO;IAC7B,qBAAqB,EAAE,EAAE;IACzB,KAAK,EAAE,KAAK;IACZ,IAAI,EAAE,EAAE;IACR,gBAAgB,EAAE,EAAE;IACpB,IAAI,EAAE,EAAE;IACR,KAAK,EA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C;QAC9C,oBAAoB,EAAE,6BAA6B,CACjD,KAAK,CAAC,MAAM,EAAE,oBAAoB,CACnC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAyB,EACzB,QAAoB;IAEpB,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/sync/syncPagination\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/keying/accessLevel\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/principalPolicyService\";\nimport type {\n DocumentSnapshot,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachments/attachmentSnapshot\";\nimport { sameValidationIssues, shallowEqualRecord } from \"./snapshotEquality\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\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?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n /** The request's policy operation; finalizing hydration reuses it. */\n policyOperation: PrincipalPolicyOperation;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n /** Fields and rows a created record starts with; see `initialContent.ts`. */\n initialContent?: Pick<\n DocumentStoreOpenOptions,\n \"initialRows\" | \"initialStructuredFields\"\n >;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Newest queued coalescing write per key; see `localWriteQueue`. */\n localWriteTickets: { issued: number; latestByKey: Map<string, number> };\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n /** Local writes called or chained but unsettled; zero means all in SQLite. */\n queuedWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n startupProbeDeferredAttempt: number | null;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n /**\n * Whether local writes applied ops to `doc` that are not yet durable (e.g.\n * their save failed). Set when a write exports a non-empty delta; cleared once\n * a persist covers `doc` or `doc` is replaced from durable history.\n */\n unsavedLocalEdits: boolean;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteTickets: { issued: 0, latestByKey: new Map() },\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n queuedWrites: 0,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n startupProbeDeferredAttempt: null,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n unsavedLocalEdits: false,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.startupProbeDeferredAttempt = null;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.unsavedLocalEdits = false;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n // Publish runtime identity before a caller captures its write authority.\n currentAuthorId: resolveCurrentAuthorId(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"carriedFirstUpdate.js","sourceRoot":"","sources":["carriedFirstUpdate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAGtD,OAAO,EAEL,2BAA2B,GAE5B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;A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Aa,GAAa,EAAE,CAAC;IACnC,4CAA4C,CAAC,KAAK,EAAE,aAAa,EAAE;QACjE,OAAO,CAAC,MAAM,CAAC,EAAE;KAClB,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,sCAAsC,CACzD,KAAK,EACL,aAAa,EACb,KAAK,CAAC,MAAM,CACb,CAAC;IACF,MAAM,OAAO,GAAG,MAAM,sCAAsC,CAC1D,KAAK,EACL,aAAa,EACb,GAAG,EAAE,CACH,wBAAwB,CAAC;QACvB,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,OAAO;QACP,SAAS,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC;QAClC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,aAAa;QACb,KAAK;KACN,CAAC,CACL,CAAC;IACF,IAAI,CAAC,OAAO;QAAE,6BAA6B,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport type { DocumentSyncRequest } from \"@tearleads/validators/request\";\nimport type { DocumentCreateSeedResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentRecord,\n documentCreateSeedCandidate,\n type PendingUpdateRecord,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { listPendingUpdates } from \"../persistence\";\nimport type {\n DocumentState,\n DocumentStoreState,\n EncapsulationKeyPair,\n} from \"../state\";\nimport { persistBindCarriedSeed } from \"./createdDocumentPersistence\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport { isNewPendingAttachmentSlot } from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { ensureRemoteDocument } from \"./syncShared\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\n/**\n * The document's deferred first update, signed by the create that preceded\n * its attachment's bind: the bind carries it, so its content never reaches\n * the server before the binding it names.\n */\nexport interface CarriedFirstUpdate {\n readonly request: DocumentSyncRequest;\n readonly update: PendingUpdateRecord;\n}\n\n/**\n * The queued row the create may sign for the bind to carry: the document's\n * whole content, held back for exactly one fresh attachment. With more\n * attachments the row names slots a single bind does not commit.\n */\nasync function deferredFirstUpdateCandidate(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n): Promise<PendingUpdateRecord | null> {\n const [pendingAttachment, ...others] = state.pendingAttachments;\n if (\n !pendingAttachment ||\n others.length > 0 ||\n pendingAttachment.upload != null ||\n !isNewPendingAttachmentSlot(state, pendingAttachment)\n ) {\n return null;\n }\n return documentCreateSeedCandidate({\n documentVersion: encodeVersionVector(currentDoc),\n pendingUpdates: await listPendingUpdates(state),\n });\n}\n\n/**\n * Creates the remote document for its attachment's first upload. When the\n * queue holds the deferred first update, the create signs it without sending\n * it and `onCarried` receives it for the bind to carry.\n */\nexport async function ensureRemoteDocumentCarryingFirstUpdate(input: {\n readonly currentDoc: DocumentState;\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly generation: DocumentStoreSyncGeneration;\n readonly nextRecord: DocumentRecord;\n readonly onCarried: (carried: CarriedFirstUpdate) => void;\n readonly policyOperation: PrincipalPolicyOperation;\n readonly state: DocumentStoreState;\n}): Promise<DocumentRecord | null> {\n const update = await deferredFirstUpdateCandidate(\n input.state,\n input.currentDoc,\n );\n return ensureRemoteDocument(\n input.state,\n input.currentDoc,\n input.nextRecord,\n input.encapsulationKeyPair,\n input.policyOperation,\n input.generation,\n undefined,\n update\n ? {\n onSigned: (request) => input.onCarried({ request, update }),\n update,\n }\n : undefined,\n );\n}\n\n/**\n * Settles the carried update when the bind's acknowledgement names it. A bind\n * that dropped it (a refused carry falls back to a plain bind) or failed\n * leaves the row queued, so the pass's document sync ships it alone.\n */\nasync function settleCarriedFirstUpdate(input: {\n readonly attachmentGeneration: DocumentStoreSyncGeneration;\n readonly carried: CarriedFirstUpdate;\n readonly committed: DocumentCreateSeedResponse | undefined;\n readonly remoteDocumentId: string;\n readonly requestRecord: DocumentRecord | null;\n readonly state: DocumentStoreState;\n}): Promise<boolean> {\n const { requestRecord, state } = input;\n if (!requestRecord) return false;\n // A relink during the bind leaves the attachment generation current, but\n // the acknowledgement describes the old document: settle only while the\n // identity and security context the bind ran under are still live, on the\n // identity-write chain so a relink cannot interleave.\n const contextCurrent = () =>\n isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration) &&\n documentSyncContextMatches(\n state.record,\n requestRecord,\n input.remoteDocumentId,\n );\n return chainIdentityWrite(state, async () => {\n if (!state.doc || !contextCurrent()) return false;\n return persistBindCarriedSeed({\n committed: input.committed,\n currentDoc: state.doc,\n generation: input.attachmentGeneration,\n state,\n stillCurrent: contextCurrent,\n update: input.carried.update,\n });\n });\n}\n\n/**\n * Runs the upload whose bind carries `carried`. Its id is registered before\n * the network await, as a sync registers its sent ids, so the update's own\n * echo is classified as self-authored; the registration is dropped unless\n * the row settles.\n */\nexport async function uploadCarryingFirstUpdate<Result>(input: {\n readonly attachmentGeneration: DocumentStoreSyncGeneration;\n readonly carried: CarriedFirstUpdate | undefined;\n readonly committed: (\n result: Result,\n ) => DocumentCreateSeedResponse | undefined;\n readonly remoteDocumentId: string;\n readonly state: DocumentStoreState;\n readonly upload: () => Promise<Result>;\n}): Promise<Result> {\n const { carried, state } = input;\n if (!carried) return input.upload();\n const requestRecord = state.record;\n const registeredIds: string[] = [];\n preRegisterMaterializedDocumentSyncUpdateIds(state, registeredIds, [\n carried.update.id,\n ]);\n const result = await cleanupPreRegisteredUpdateIdsOnFailure(\n state,\n registeredIds,\n input.upload,\n );\n const settled = await cleanupPreRegisteredUpdateIdsOnFailure(\n state,\n registeredIds,\n () =>\n settleCarriedFirstUpdate({\n attachmentGeneration: input.attachmentGeneration,\n carried,\n committed: input.committed(result),\n remoteDocumentId: input.remoteDocumentId,\n requestRecord,\n state,\n }),\n );\n if (!settled) discardPreRegisteredUpdateIds(state, registeredIds);\n return result;\n}\n"]}
1
+ {"version":3,"file":"carriedFirstUpdate.js","sourceRoot":"","sources":["carriedFirstUpdate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAGtD,OAAO,EAEL,2BAA2B,GAE5B,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAMpD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8BAA8B,CAAC;AACtE,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,4CAA4C,GAC7C,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAYhE;;;;GAIG;AACH,KAAK,UAAU,4BAA4B,CACzC,KAAyB,EACzB,UAAyB;IAEzB,MAAM,CAAC,iBAAiB,EAAE,GAAG,MAAM,CAAC,GAAG,KAAK,CAAC,kBAAkB,CAAC;IAChE,IACE,CAAC,iBAAiB;QAClB,MAAM,CAAC,MAAM,GAAG,CAAC;QACjB,iBAAiB,CAAC,MAAM,IAAI,IAAI;QAChC,CAAC,0BAA0B,CAAC,KAAK,EAAE,iBAAiB,CAAC,EACrD,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO,2BAA2B,CAAC;QACjC,eAAe,EAAE,mBAAmB,CAAC,UAAU,CAAC;QAChD,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UAAU,EAAE,KAAK,CAAC,GAAG;YACrB,UAAU,EAAE,KAAK,CAAC,oBAAoB;YACtC,KAAK;YACL,YAAY,EAAE,cAAc;YAC5B,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;SAC7B,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAS,KASvD;IACC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC;IACjC,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;IACpC,MAAM,aAAa,GAAG,KAAK,CAAC,MAAM,CAAC;IACnC,MAAM,aAAa,GAAa,EAAE,CAAC;IACnC,4CAA4C,CAAC,KAAK,EAAE,aAAa,EAAE;QACjE,OAAO,CAAC,MAAM,CAAC,EAAE;KAClB,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,sCAAsC,CACzD,KAAK,EACL,aAAa,EACb,KAAK,CAAC,MAAM,CACb,CAAC;IACF,MAAM,OAAO,GAAG,MAAM,sCAAsC,CAC1D,KAAK,EACL,aAAa,EACb,GAAG,EAAE,CACH,wBAAwB,CAAC;QACvB,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,OAAO;QACP,SAAS,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC;QAClC,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,aAAa;QACb,KAAK;KACN,CAAC,CACL,CAAC;IACF,IAAI,CAAC,OAAO;QAAE,6BAA6B,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC;IAClE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { encodeVersionVector } from \"@tearleads/loro\";\nimport type { DocumentSyncRequest } from \"@tearleads/validators/request\";\nimport type { DocumentCreateSeedResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentRecord,\n documentCreateSeedCandidate,\n type PendingUpdateRecord,\n} from \"../../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../../workflows/principals/principalPolicyService\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport { listPendingUpdates } from \"../persistence\";\nimport type {\n DocumentState,\n DocumentStoreState,\n EncapsulationKeyPair,\n} from \"../state\";\nimport { persistBindCarriedSeed } from \"./createdDocumentPersistence\";\nimport {\n cleanupPreRegisteredUpdateIdsOnFailure,\n discardPreRegisteredUpdateIds,\n preRegisterMaterializedDocumentSyncUpdateIds,\n} from \"./syncAcceptedUpdateIds\";\nimport { isNewPendingAttachmentSlot } from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { ensureRemoteDocument } from \"./syncShared\";\nimport { documentSyncContextMatches } from \"./syncUpdateImport\";\n\n/**\n * The document's deferred first update, signed by the create that preceded\n * its attachment's bind: the bind carries it, so its content never reaches\n * the server before the binding it names.\n */\nexport interface CarriedFirstUpdate {\n readonly request: DocumentSyncRequest;\n readonly update: PendingUpdateRecord;\n}\n\n/**\n * The queued row the create may sign for the bind to carry: the document's\n * whole content, held back for exactly one fresh attachment. With more\n * attachments the row names slots a single bind does not commit.\n */\nasync function deferredFirstUpdateCandidate(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n): Promise<PendingUpdateRecord | null> {\n const [pendingAttachment, ...others] = state.pendingAttachments;\n if (\n !pendingAttachment ||\n others.length > 0 ||\n pendingAttachment.upload != null ||\n !isNewPendingAttachmentSlot(state, pendingAttachment)\n ) {\n return null;\n }\n return documentCreateSeedCandidate({\n documentVersion: encodeVersionVector(currentDoc),\n pendingUpdates: await listPendingUpdates(state),\n });\n}\n\n/**\n * Creates the remote document for its attachment's first upload. When the\n * queue holds the deferred first update, the create signs it without sending\n * it and `onCarried` receives it for the bind to carry.\n */\nexport async function ensureRemoteDocumentCarryingFirstUpdate(input: {\n readonly currentDoc: DocumentState;\n readonly encapsulationKeyPair: EncapsulationKeyPair;\n readonly generation: DocumentStoreSyncGeneration;\n readonly nextRecord: DocumentRecord;\n readonly onCarried: (carried: CarriedFirstUpdate) => void;\n readonly policyOperation: PrincipalPolicyOperation;\n readonly state: DocumentStoreState;\n}): Promise<DocumentRecord | null> {\n const update = await deferredFirstUpdateCandidate(\n input.state,\n input.currentDoc,\n );\n return ensureRemoteDocument(\n input.state,\n input.currentDoc,\n input.nextRecord,\n input.encapsulationKeyPair,\n input.policyOperation,\n input.generation,\n undefined,\n update\n ? {\n onSigned: (request) => input.onCarried({ request, update }),\n update,\n }\n : undefined,\n );\n}\n\n/**\n * Settles the carried update when the bind's acknowledgement names it. A bind\n * that dropped it (a refused carry falls back to a plain bind) or failed\n * leaves the row queued, so the pass's document sync ships it alone.\n */\nasync function settleCarriedFirstUpdate(input: {\n readonly attachmentGeneration: DocumentStoreSyncGeneration;\n readonly carried: CarriedFirstUpdate;\n readonly committed: DocumentCreateSeedResponse | undefined;\n readonly remoteDocumentId: string;\n readonly requestRecord: DocumentRecord | null;\n readonly state: DocumentStoreState;\n}): Promise<boolean> {\n const { requestRecord, state } = input;\n if (!requestRecord) return false;\n // A relink during the bind leaves the attachment generation current, but\n // the acknowledgement describes the old document: settle only while the\n // identity and security context the bind ran under are still live, on the\n // identity-write chain so a relink cannot interleave.\n const contextCurrent = () =>\n isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration) &&\n documentSyncContextMatches(\n state.record,\n requestRecord,\n input.remoteDocumentId,\n );\n return chainIdentityWrite(state, async () => {\n if (!state.doc || !contextCurrent()) return false;\n return persistBindCarriedSeed({\n committed: input.committed,\n currentDoc: state.doc,\n generation: input.attachmentGeneration,\n state,\n stillCurrent: contextCurrent,\n update: input.carried.update,\n });\n });\n}\n\n/**\n * Runs the upload whose bind carries `carried`. Its id is registered before\n * the network await, as a sync registers its sent ids, so the update's own\n * echo is classified as self-authored; the registration is dropped unless\n * the row settles.\n */\nexport async function uploadCarryingFirstUpdate<Result>(input: {\n readonly attachmentGeneration: DocumentStoreSyncGeneration;\n readonly carried: CarriedFirstUpdate | undefined;\n readonly committed: (\n result: Result,\n ) => DocumentCreateSeedResponse | undefined;\n readonly remoteDocumentId: string;\n readonly state: DocumentStoreState;\n readonly upload: () => Promise<Result>;\n}): Promise<Result> {\n const { carried, state } = input;\n if (!carried) return input.upload();\n const requestRecord = state.record;\n const registeredIds: string[] = [];\n preRegisterMaterializedDocumentSyncUpdateIds(state, registeredIds, [\n carried.update.id,\n ]);\n const result = await cleanupPreRegisteredUpdateIdsOnFailure(\n state,\n registeredIds,\n input.upload,\n );\n const settled = await cleanupPreRegisteredUpdateIdsOnFailure(\n state,\n registeredIds,\n () =>\n settleCarriedFirstUpdate({\n attachmentGeneration: input.attachmentGeneration,\n carried,\n committed: input.committed(result),\n remoteDocumentId: input.remoteDocumentId,\n requestRecord,\n state,\n }),\n );\n if (!settled) discardPreRegisteredUpdateIds(state, registeredIds);\n return result;\n}\n"]}