@tearleads/client-sdk 0.1.253 → 0.1.254

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 (73) hide show
  1. package/client/containerContents/documentDiscovery.js +0 -2
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +7 -10
  4. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  5. package/data/persistence/container-contents/containerDeletionPersistence.js +5 -1
  6. package/data/persistence/container-contents/containerDeletionPersistence.js.map +1 -1
  7. package/data/persistence/container-contents/containerHydrationPersistence.js +1 -1
  8. package/data/persistence/container-contents/containerHydrationPersistence.js.map +1 -1
  9. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +11 -4
  10. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  11. package/data/persistence/container-contents/containerRemovalMetadata.js +47 -0
  12. package/data/persistence/container-contents/containerRemovalMetadata.js.map +1 -0
  13. package/data/persistence/container-contents/containerRemovalPlacements.js +22 -0
  14. package/data/persistence/container-contents/containerRemovalPlacements.js.map +1 -0
  15. package/data/persistence/container-contents/containerSyncWatermarkPersistence.d.ts +2 -1
  16. package/data/persistence/container-contents/containerSyncWatermarkPersistence.js +10 -2
  17. package/data/persistence/container-contents/containerSyncWatermarkPersistence.js.map +1 -1
  18. package/data/persistence/documents/documentDiscoveryCandidate.d.ts +1 -0
  19. package/data/persistence/documents/documentDiscoveryCandidate.js +3 -1
  20. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  21. package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +1 -1
  22. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +16 -4
  23. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  24. package/data/sqlite/migrations/localSchemaMigrations.js +11 -0
  25. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  26. package/data/sqlite/schema/containerSyncWatermarkSchema.js +6 -3
  27. package/data/sqlite/schema/containerSyncWatermarkSchema.js.map +1 -1
  28. package/data/sqlite/schema/index.d.ts +17 -0
  29. package/internal/api-client/ApiClient.d.ts +1 -0
  30. package/internal/api-client/client/apiClientContext.d.ts +1 -0
  31. package/internal/api-client/client/containerReads.d.ts +1 -0
  32. package/internal/api-client/requestInternals.js +14 -6
  33. package/internal/api-client/requestInternals.js.map +1 -1
  34. package/internal/validators/operation/containerReads.d.ts +29 -2
  35. package/internal/validators/operation/containerReads.js +2 -1
  36. package/internal/validators/operation/containerReads.js.map +1 -1
  37. package/internal/validators/request/containerDocumentLanes.d.ts +7 -0
  38. package/internal/validators/request/containerDocumentLanes.js +6 -0
  39. package/internal/validators/request/containerDocumentLanes.js.map +1 -1
  40. package/internal/validators/response/container.d.ts +8 -0
  41. package/internal/validators/response/container.js +1 -0
  42. package/internal/validators/response/container.js.map +1 -1
  43. package/internal/validators/response/containerParentLanes.d.ts +2 -0
  44. package/package.json +1 -1
  45. package/workflows/container-contents/documentDiscovery/containerDocumentListing.js +52 -4
  46. package/workflows/container-contents/documentDiscovery/containerDocumentListing.js.map +1 -1
  47. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js +4 -2
  48. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -1
  49. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js +17 -12
  50. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
  51. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.js.map +1 -1
  52. package/workflows/container-contents/documentDiscovery/publicationWatermark.js +15 -0
  53. package/workflows/container-contents/documentDiscovery/publicationWatermark.js.map +1 -0
  54. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +4 -4
  55. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -1
  56. package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js +25 -0
  57. package/workflows/container-contents/remoteHydration/lanes/restorationReceipt.js.map +1 -0
  58. package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js +107 -0
  59. package/workflows/container-contents/remoteHydration/lanes/tombstoneAccess.js.map +1 -0
  60. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +29 -27
  61. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  62. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +17 -5
  63. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  64. package/workflows/container-contents/remoteHydration/tombstoneApplication.js +67 -24
  65. package/workflows/container-contents/remoteHydration/tombstoneApplication.js.map +1 -1
  66. package/workflows/container-contents/remoteHydration/types.d.ts +3 -1
  67. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  68. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js +3 -3
  69. package/workflows/container-contents/remoteReset/remoteResetCursorScope.js.map +1 -1
  70. package/workflows/container-contents/syncPause/discoveryGuard.js +6 -2
  71. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  72. package/workflows/container-contents/tombstones/documentTombstoneGate.js +6 -3
  73. package/workflows/container-contents/tombstones/documentTombstoneGate.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"remoteContainerState.js","sourceRoot":"","sources":["remoteContainerState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,sCAAsC,EAAE,MAAM,qDAAqD,CAAC;AAC7G,OAAO,EACL,oBAAoB,EACpB,iCAAiC,GAClC,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,oCAAoC,EAAE,MAAM,+CAA+C,CAAC;AACrG,OAAO,EACL,yBAAyB,EACzB,gCAAgC,GACjC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,mCAAmC,EAAE,MAA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sC;YAC9C,wCAAwC,EACtC,KAAK,CAAC,wCAAwC;YAChD,aAAa;YACb,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC;QACJ,CAAC,CAAC,0BAA0B,CAAC;YACzB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,0BAA0B,EAAE,KAAK,CAAC,0BAA0B,IAAI,IAAI;YACpE,2BAA2B;YAC3B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC;AACT,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport {\n decodeVersionVector,\n encodeVersionVector,\n satisfiesVersionVector,\n} from \"@tearleads/loro\";\nimport { isProjectionVerificationCancelledError } from \"../../../../data/keyingProjectionVerification/types\";\nimport {\n heldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/shared/dependencyUnavailable\";\nimport {\n isKeyingVerificationError,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport { invalidateContainerProjectionCaches } from \"../../container-state/projectionCache\";\nimport type { ContainerHydrationTombstone } from \"../../containerPersistence\";\nimport { installContainerMetadataRecord } from \"../../metadata/metadataPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { PrefetchedDestinationProjection } from \"../destination/destinationPrefetch\";\nimport { verifyRemoteContainerDestination } from \"../destination/verifiedDestination\";\nimport { rebindReHomedContainer } from \"../heldContainerRebind\";\nimport {\n moveIndexedContainerChild,\n removeIndexedContainerChild,\n} from \"../lanes/childIndex\";\nimport {\n reconcileLocalOnlyRootContainers,\n reconcileLocalOnlySystemContainers,\n} from \"../reconciliation\";\nimport type {\n ContainerChildIndex,\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { insertRemoteContainerState } from \"./insertRemoteContainer\";\nimport {\n applyRemoteContainerTimestamps,\n remoteContainerHydrationSaveOptions,\n resolveRemoteContainerHydrationLocalUpdatedAt,\n} from \"./remoteContainerTimestamps\";\n\n// Container ids (restricted to the inbound page) that carry an unsynced local\n// create or move intent. Such a container's parent and local-edit timestamp are\n// owned by its structural-intent lane until that lane reconciles, so inbound\n// hydration must not revert parentId to the server value nor collapse\n// localUpdatedAt — doing so silently undoes a queued move and falsely reads\n// \"synced\". Move intents are read via listUnsyncedMoveIntents so a blocked\n// move — one whose destination parent has not synced yet, the common boot-time\n// case — is protected too. Pending *metadata*\n// updates are handled separately (listRemoteContainerIdsWithPendingMetadataUpdates);\n// structural intents live in the local outbox's container lanes, which that\n// query does not cover.\nexport async function listRemoteContainerIdsWithPendingStructuralIntents(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n if (input.remoteContainers.length === 0) {\n return new Set();\n }\n const remoteContainerIds = new Set(\n input.remoteContainers.map((remoteContainer) => remoteContainer.id),\n );\n\n const execSql = input.state.runtime.infra.execSql;\n const [pendingCreateIntents, unsyncedMoveIntents] = await Promise.all([\n input.state.persistence.listPendingCreateIntents(execSql),\n input.state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n const containerIdsWithPendingStructuralIntents = new Set<string>();\n for (const intent of pendingCreateIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n for (const intent of unsyncedMoveIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n return containerIdsWithPendingStructuralIntents;\n}\n\nexport async function listRemoteContainerIdsWithPendingMetadataUpdates(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n const containerIds = input.remoteContainers.flatMap((remoteContainer) => {\n const previousLocalUpdatedAt = input.state.containersById.get(\n remoteContainer.id,\n )?.container.localUpdatedAt;\n\n return previousLocalUpdatedAt &&\n previousLocalUpdatedAt.localeCompare(remoteContainer.updatedAt) > 0\n ? [remoteContainer.id]\n : [];\n });\n if (containerIds.length === 0) {\n return new Set();\n }\n\n const execSql = input.state.runtime.infra.execSql;\n return new Set(\n await input.state.persistence.listContainerIdsWithPendingUpdates(\n execSql,\n containerIds,\n ),\n );\n}\n\nfunction removeMissingHydratedContainer(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n existingState: ContainerState;\n host: RemoteContainerHydrationHost;\n previousParentId: string | null;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): void {\n const { existingState, remoteContainer, state } = input;\n if (state.containersById.get(remoteContainer.id) !== existingState) {\n return;\n }\n\n state.containersById.delete(remoteContainer.id);\n if (input.childIdsByParentId) {\n removeIndexedContainerChild(\n input.childIdsByParentId,\n remoteContainer.id,\n input.previousParentId,\n );\n input.childIdsByParentId.delete(remoteContainer.id);\n }\n input.host.updateSnapshot();\n}\n\nfunction createUpdatedRemoteContainerState(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): ContainerState {\n return {\n ...existingState,\n container: applyRemoteContainerTimestamps(\n existingState.container,\n remoteContainer,\n ),\n containerWriterProjection: null,\n metadataReferencedPrincipals: remoteContainer.metadataReferencedPrincipals,\n };\n}\n\nfunction installUpdatedRemoteContainerState(\n existingState: ContainerState,\n nextState: ContainerState,\n host: RemoteContainerHydrationHost,\n): void {\n const wasLocalOnly = existingState.container.serverCreatedAt == null;\n existingState.container = nextState.container;\n existingState.containerWriterProjection = nextState.containerWriterProjection;\n existingState.metadataReferencedPrincipals =\n nextState.metadataReferencedPrincipals;\n // The snapshot copied the live generation when it was taken; a hint that\n // landed during the persist leaves the live metadata projection dropped.\n if (projectionGeneration(existingState) === projectionGeneration(nextState))\n existingState.metadataWriterProjection = nextState.metadataWriterProjection;\n installContainerMetadataRecord(existingState, nextState.record);\n // A document pass may have deferred while this root was awaiting proof.\n // The first durable remote acknowledgement makes its pending creates runnable.\n if (wasLocalOnly && existingState.container.serverCreatedAt != null)\n host.requestDocumentPriming?.();\n}\n\n/**\n * A clean metadata document is read only when a hint names it, and a hint sent\n * while this client was offline or not yet subscribed is lost. The listing\n * reports the version vector of every update the server holds for the metadata\n * document; when this client's copy does not cover it, an edit is unread. Owe\n * the read before this hydration advances the lane watermark past the row.\n */\nfunction coversMetadataVersion(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): boolean {\n const listed = remoteContainer.metadataVersionVector;\n try {\n // A document with no stored update is covered by any copy.\n if (decodeVersionVector(listed).toJSON().size === 0) return true;\n return satisfiesVersionVector(\n encodeVersionVector(existingState.doc),\n listed,\n );\n } catch {\n // An unreadable version proves nothing: owe the read, which pulls the\n // truth, and let the rest of the page hydrate.\n return false;\n }\n}\n\nasync function oweMetadataReadIfBehind(\n host: RemoteContainerHydrationHost,\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): Promise<void> {\n if (!coversMetadataVersion(existingState, remoteContainer)) {\n await host.requestMetadataRevalidation?.({\n advertisedVersionVector: remoteContainer.metadataVersionVector,\n documentId: remoteContainer.metadataDocumentId,\n });\n }\n}\n\nasync function updateExistingRemoteContainerState(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n existingState: ContainerState;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<ContainerState | null> {\n const { childIdsByParentId, existingState, host, remoteContainer, state } =\n input;\n const previousParentId = existingState.container.parentId;\n const previousLocalUpdatedAt = existingState.container.localUpdatedAt;\n // A queued, not-yet-synced local move/create owns this container's parent\n // until its intent lane reconciles. Omit the remote parent when the page scan\n // saw one; persistence also rechecks the intent transactionally so a move\n // created after that scan wins. Both paths preserve the durable local clock.\n const hasPendingStructuralIntent =\n input.containerIdsWithPendingStructuralIntents.has(remoteContainer.id);\n const nextParentId = hasPendingStructuralIntent\n ? undefined\n : remoteContainer.parentId;\n const localUpdatedAt = resolveRemoteContainerHydrationLocalUpdatedAt({\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n hasPendingStructuralIntent,\n previousLocalUpdatedAt,\n remoteContainer,\n });\n await oweMetadataReadIfBehind(host, existingState, remoteContainer);\n const nextState = createUpdatedRemoteContainerState(\n existingState,\n remoteContainer,\n );\n const persistenceResult = await host.persistContainerState(\n nextState,\n {\n accessEpoch: remoteContainer.metadataAccessEpoch,\n accessStateHash: remoteContainer.metadataAccessStateHash,\n documentId: remoteContainer.metadataDocumentId,\n effectiveAccessLevel: remoteContainer.effectiveAccessLevel,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n systemSlot: remoteContainer.systemSlot ?? null,\n organizationId: remoteContainer.organizationId,\n ...(nextParentId !== undefined ? { parentId: nextParentId } : {}),\n },\n false,\n remoteContainerHydrationSaveOptions({\n localUpdatedAt,\n remoteContainer,\n }),\n {\n preserveDurableStructureWhenPending: true,\n },\n );\n if (persistenceResult.status === \"missing\") {\n // Hydration persists a detached candidate so an in-flight response cannot\n // mutate mapped state before its guards settle. Retire the exact state this\n // hydration read because store-level reference cleanup cannot see the clone.\n removeMissingHydratedContainer({\n childIdsByParentId,\n existingState,\n host,\n previousParentId,\n remoteContainer,\n state,\n });\n return null;\n }\n if (persistenceResult.status !== \"persisted\") return null;\n const { record: nextRecord } = persistenceResult;\n installContainerMetadataRecord(nextState, nextRecord);\n if (input.isCurrent?.() === false) {\n return existingState;\n }\n nextState.container = {\n ...nextState.container,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n organizationId: remoteContainer.organizationId,\n parentId: nextState.container.parentId,\n };\n\n installUpdatedRemoteContainerState(existingState, nextState, host);\n moveIndexedContainerChild(\n childIdsByParentId,\n remoteContainer.id,\n previousParentId,\n existingState.container.parentId,\n );\n await reconcileLocalOnlyRootContainers({\n childIdsByParentId,\n isCurrent: input.isCurrent,\n remoteRootState: existingState,\n requestDocumentPriming: host.requestDocumentPriming,\n state,\n });\n return existingState;\n}\n\ninterface UpsertRemoteContainerStateInput {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n expectedHydrationTombstone?: ContainerHydrationTombstone | null | undefined;\n isCurrent?: (() => boolean) | undefined;\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}\n\n/** A pull can observe the same manifest change as a missed realtime hint. */\nfunction invalidateListedProjectionCaches(\n input: UpsertRemoteContainerStateInput,\n) {\n const held = input.state.containersById.get(input.remoteContainer.id);\n if (\n held &&\n (held.record.accessStateHash !==\n input.remoteContainer.metadataAccessStateHash ||\n (held.container.effectiveAccessLevel ?? \"read\") !==\n input.remoteContainer.effectiveAccessLevel)\n ) {\n // Eviction admits no remote state. Drop citations before verification can\n // advance local checkpoints past those cached container/document paths.\n invalidateContainerProjectionCaches(input.state, [\n input.remoteContainer.id,\n ]);\n }\n}\n\nexport async function upsertRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n let expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n const heldState = input.state.containersById.get(input.remoteContainer.id);\n const heldBinding = heldState\n ? heldContainerBinding(heldState)\n : await input.state.persistence.loadHeldContainerBinding(\n input.state.runtime.infra.execSql,\n input.remoteContainer.id,\n );\n const listed = input.remoteContainer;\n // A folder re-homed away from the listed organization never returns there,\n // whatever binding (possibly none, after a reset) the device holds now.\n const supersededListing =\n !listingRepeatsHeldOrdinaryBinding(heldBinding, listed) &&\n (await input.state.persistence.isSupersededContainerBinding(\n input.state.runtime.infra.execSql,\n { containerId: listed.id, organizationId: listed.organizationId },\n ));\n if (input.isCurrent?.() === false) return null;\n invalidateListedProjectionCaches(input);\n const verified = await verifyRemoteContainerDestination({\n ...input,\n heldBinding,\n supersededListing,\n refresh: !!input.expectedHydrationTombstone,\n onVerifiedCheckpoint: (checkpoint) => {\n expectedPlacementCheckpoint = checkpoint;\n },\n });\n if (!verified || input.isCurrent?.() === false) return null;\n input = { ...input, remoteContainer: verified };\n const existingState = input.state.containersById.get(\n input.remoteContainer.id,\n );\n const remoteState = await runWithSecurityIncidentReporting(\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: verified.id,\n objectKind: \"container\",\n operation: \"container.binding.persist\",\n organizationId: verified.organizationId,\n },\n async () =>\n (await rebindReHomedContainer({\n existingState,\n heldBinding,\n isCurrent: input.isCurrent,\n state: input.state,\n verified,\n }))\n ? persistVerifiedRemoteContainer({\n ...input,\n existingState,\n expectedPlacementCheckpoint,\n })\n : null,\n );\n if (!remoteState) {\n return null;\n }\n await reconcileLocalOnlySystemContainers({\n childIdsByParentId: input.childIdsByParentId,\n isCurrent: input.isCurrent,\n requestDocumentPriming: input.host.requestDocumentPriming,\n remoteSystemState: remoteState,\n state: input.state,\n });\n return remoteState;\n}\n\n/**\n * Upsert one listed folder, isolating a rejected proof or binding. The refusal\n * was already reported; returning no state leaves the item unapplied without\n * blocking independent folders.\n */\nexport async function upsertIsolatedRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n recordIncompleteItem?: (outcome: \"refused\" | \"retry\") => void,\n recordUnavailable?:\n | ((error: ProjectionDependencyUnavailableError) => void)\n | undefined,\n): Promise<ContainerState | null> {\n try {\n return await upsertRemoteContainerState(input);\n } catch (error) {\n if (isKeyingVerificationError(error)) {\n recordIncompleteItem?.(\"refused\");\n return null;\n }\n if (isProjectionVerificationCancelledError(error)) return null;\n if (\n error instanceof ProjectionDependencyUnavailableError &&\n recordUnavailable\n ) {\n recordUnavailable(error);\n recordIncompleteItem?.(\"retry\");\n return null;\n }\n throw error;\n }\n}\n\nfunction persistVerifiedRemoteContainer(\n input: UpsertRemoteContainerStateInput & {\n existingState: ContainerState | undefined;\n expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n },\n): Promise<ContainerState | null> {\n const { existingState, expectedPlacementCheckpoint } = input;\n return existingState\n ? updateExistingRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents:\n input.containerIdsWithPendingStructuralIntents,\n existingState,\n host: input.host,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n })\n : insertRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n host: input.host,\n expectedHydrationTombstone: input.expectedHydrationTombstone ?? null,\n expectedPlacementCheckpoint,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n });\n}\n"]}
1
+ {"version":3,"file":"remoteContainerState.js","sourceRoot":"","sources":["remoteContainerState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,sCAAsC,EAAE,MAAM,qDAAqD,CAAC;AAC7G,OAAO,EACL,oBAAoB,EACpB,iCAAiC,GAClC,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,oCAAoC,EAAE,MAAM,+CAA+C,CAAC;AACrG,OAAO,EACL,yBAAyB,EACzB,gCAAgC,GACjC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAE5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAA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;YAChC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,8BAA8B,CACrC,KAGC;IAED,MAAM,EAAE,aAAa,EAAE,2BAA2B,EAAE,GAAG,KAAK,CAAC;IAC7D,OAAO,aAAa;QAClB,CAAC,CAAC,kCAAkC,CAAC;YACjC,iBAAiB,EAAE,2BAA2B;YAC9C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,sCAAsC,EACpC,KAAK,CAAC,sCAAsC;YAC9C,wCAAwC,EACtC,KAAK,CAAC,wCAAwC;YAChD,aAAa;YACb,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC;QACJ,CAAC,CAAC,0BAA0B,CAAC;YACzB,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,0BAA0B,EAAE,KAAK,CAAC,0BAA0B,IAAI,IAAI;YACpE,2BAA2B;YAC3B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,KAAK,EAAE,KAAK,CAAC,KAAK;SACnB,CAAC,CAAC;AACT,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport {\n decodeVersionVector,\n encodeVersionVector,\n satisfiesVersionVector,\n} from \"@tearleads/loro\";\nimport { isProjectionVerificationCancelledError } from \"../../../../data/keyingProjectionVerification/types\";\nimport {\n heldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../../data/persistence/container-contents/containerBinding\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/shared/dependencyUnavailable\";\nimport {\n isKeyingVerificationError,\n runWithSecurityIncidentReporting,\n} from \"../../../../data/shared/securityIncidents\";\nimport { invalidateContainerProjectionCaches } from \"../../container-state/projectionCache\";\nimport type { ContainerHydrationTombstone } from \"../../containerPersistence\";\nimport { installContainerMetadataRecord } from \"../../metadata/metadataPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { PrefetchedDestinationProjection } from \"../destination/destinationPrefetch\";\nimport { verifyRemoteContainerDestination } from \"../destination/verifiedDestination\";\nimport { rebindReHomedContainer } from \"../heldContainerRebind\";\nimport {\n moveIndexedContainerChild,\n removeIndexedContainerChild,\n} from \"../lanes/childIndex\";\nimport {\n reconcileLocalOnlyRootContainers,\n reconcileLocalOnlySystemContainers,\n} from \"../reconciliation\";\nimport type {\n ContainerChildIndex,\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { insertRemoteContainerState } from \"./insertRemoteContainer\";\nimport {\n applyRemoteContainerTimestamps,\n remoteContainerHydrationSaveOptions,\n resolveRemoteContainerHydrationLocalUpdatedAt,\n} from \"./remoteContainerTimestamps\";\n\n// Container ids (restricted to the inbound page) that carry an unsynced local\n// create or move intent. Such a container's parent and local-edit timestamp are\n// owned by its structural-intent lane until that lane reconciles, so inbound\n// hydration must not revert parentId to the server value nor collapse\n// localUpdatedAt — doing so silently undoes a queued move and falsely reads\n// \"synced\". Move intents are read via listUnsyncedMoveIntents so a blocked\n// move — one whose destination parent has not synced yet, the common boot-time\n// case — is protected too. Pending *metadata*\n// updates are handled separately (listRemoteContainerIdsWithPendingMetadataUpdates);\n// structural intents live in the local outbox's container lanes, which that\n// query does not cover.\nexport async function listRemoteContainerIdsWithPendingStructuralIntents(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n if (input.remoteContainers.length === 0) {\n return new Set();\n }\n const remoteContainerIds = new Set(\n input.remoteContainers.map((remoteContainer) => remoteContainer.id),\n );\n\n const execSql = input.state.runtime.infra.execSql;\n const [pendingCreateIntents, unsyncedMoveIntents] = await Promise.all([\n input.state.persistence.listPendingCreateIntents(execSql),\n input.state.persistence.listUnsyncedMoveIntents(execSql),\n ]);\n const containerIdsWithPendingStructuralIntents = new Set<string>();\n for (const intent of pendingCreateIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n for (const intent of unsyncedMoveIntents) {\n if (remoteContainerIds.has(intent.containerId)) {\n containerIdsWithPendingStructuralIntents.add(intent.containerId);\n }\n }\n return containerIdsWithPendingStructuralIntents;\n}\n\nexport async function listRemoteContainerIdsWithPendingMetadataUpdates(input: {\n remoteContainers: ReadonlyArray<RemoteContainer>;\n state: RemoteContainerHydrationState;\n}): Promise<Set<string>> {\n const containerIds = input.remoteContainers.flatMap((remoteContainer) => {\n const previousLocalUpdatedAt = input.state.containersById.get(\n remoteContainer.id,\n )?.container.localUpdatedAt;\n\n return previousLocalUpdatedAt &&\n previousLocalUpdatedAt.localeCompare(remoteContainer.updatedAt) > 0\n ? [remoteContainer.id]\n : [];\n });\n if (containerIds.length === 0) {\n return new Set();\n }\n\n const execSql = input.state.runtime.infra.execSql;\n return new Set(\n await input.state.persistence.listContainerIdsWithPendingUpdates(\n execSql,\n containerIds,\n ),\n );\n}\n\nfunction removeMissingHydratedContainer(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n existingState: ContainerState;\n host: RemoteContainerHydrationHost;\n previousParentId: string | null;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): void {\n const { existingState, remoteContainer, state } = input;\n if (state.containersById.get(remoteContainer.id) !== existingState) {\n return;\n }\n\n state.containersById.delete(remoteContainer.id);\n if (input.childIdsByParentId) {\n removeIndexedContainerChild(\n input.childIdsByParentId,\n remoteContainer.id,\n input.previousParentId,\n );\n input.childIdsByParentId.delete(remoteContainer.id);\n }\n input.host.updateSnapshot();\n}\n\nfunction createUpdatedRemoteContainerState(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): ContainerState {\n return {\n ...existingState,\n container: applyRemoteContainerTimestamps(\n existingState.container,\n remoteContainer,\n ),\n containerWriterProjection: null,\n metadataReferencedPrincipals: remoteContainer.metadataReferencedPrincipals,\n };\n}\n\nfunction installUpdatedRemoteContainerState(\n existingState: ContainerState,\n nextState: ContainerState,\n host: RemoteContainerHydrationHost,\n): void {\n const wasLocalOnly = existingState.container.serverCreatedAt == null;\n existingState.container = nextState.container;\n existingState.containerWriterProjection = nextState.containerWriterProjection;\n existingState.metadataReferencedPrincipals =\n nextState.metadataReferencedPrincipals;\n // The snapshot copied the live generation when it was taken; a hint that\n // landed during the persist leaves the live metadata projection dropped.\n if (projectionGeneration(existingState) === projectionGeneration(nextState))\n existingState.metadataWriterProjection = nextState.metadataWriterProjection;\n installContainerMetadataRecord(existingState, nextState.record);\n // A document pass may have deferred while this root was awaiting proof.\n // The first durable remote acknowledgement makes its pending creates runnable.\n if (wasLocalOnly && existingState.container.serverCreatedAt != null)\n host.requestDocumentPriming?.();\n}\n\n/**\n * A clean metadata document is read only when a hint names it, and a hint sent\n * while this client was offline or not yet subscribed is lost. The listing\n * reports the version vector of every update the server holds for the metadata\n * document; when this client's copy does not cover it, an edit is unread. Owe\n * the read before this hydration advances the lane watermark past the row.\n */\nfunction coversMetadataVersion(\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): boolean {\n const listed = remoteContainer.metadataVersionVector;\n try {\n // A document with no stored update is covered by any copy.\n if (decodeVersionVector(listed).toJSON().size === 0) return true;\n return satisfiesVersionVector(\n encodeVersionVector(existingState.doc),\n listed,\n );\n } catch {\n // An unreadable version proves nothing: owe the read, which pulls the\n // truth, and let the rest of the page hydrate.\n return false;\n }\n}\n\nasync function oweMetadataReadIfBehind(\n host: RemoteContainerHydrationHost,\n existingState: ContainerState,\n remoteContainer: RemoteContainer,\n): Promise<void> {\n if (!coversMetadataVersion(existingState, remoteContainer)) {\n await host.requestMetadataRevalidation?.({\n advertisedVersionVector: remoteContainer.metadataVersionVector,\n documentId: remoteContainer.metadataDocumentId,\n });\n }\n}\n\nasync function updateExistingRemoteContainerState(input: {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n verifiedPlacement?: AccessManifestCheckpoint | undefined;\n existingState: ContainerState;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}): Promise<ContainerState | null> {\n const { childIdsByParentId, existingState, host, remoteContainer, state } =\n input;\n const previousParentId = existingState.container.parentId;\n const previousLocalUpdatedAt = existingState.container.localUpdatedAt;\n // A queued, not-yet-synced local move/create owns this container's parent\n // until its intent lane reconciles. Omit the remote parent when the page scan\n // saw one; persistence also rechecks the intent transactionally so a move\n // created after that scan wins. Both paths preserve the durable local clock.\n const hasPendingStructuralIntent =\n input.containerIdsWithPendingStructuralIntents.has(remoteContainer.id);\n const nextParentId = hasPendingStructuralIntent\n ? undefined\n : remoteContainer.parentId;\n const localUpdatedAt = resolveRemoteContainerHydrationLocalUpdatedAt({\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n hasPendingStructuralIntent,\n previousLocalUpdatedAt,\n remoteContainer,\n });\n await oweMetadataReadIfBehind(host, existingState, remoteContainer);\n const nextState = createUpdatedRemoteContainerState(\n existingState,\n remoteContainer,\n );\n const persistenceResult = await host.persistContainerState(\n nextState,\n {\n accessEpoch: remoteContainer.metadataAccessEpoch,\n accessStateHash: remoteContainer.metadataAccessStateHash,\n documentId: remoteContainer.metadataDocumentId,\n effectiveAccessLevel: remoteContainer.effectiveAccessLevel,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n systemSlot: remoteContainer.systemSlot ?? null,\n organizationId: remoteContainer.organizationId,\n ...(nextParentId !== undefined ? { parentId: nextParentId } : {}),\n },\n false,\n {\n ...remoteContainerHydrationSaveOptions({\n localUpdatedAt,\n remoteContainer,\n }),\n verifiedPlacement: input.verifiedPlacement,\n },\n {\n isCurrent: input.isCurrent,\n preserveDurableStructureWhenPending: true,\n },\n );\n if (persistenceResult.status === \"missing\") {\n // Hydration persists a detached candidate so an in-flight response cannot\n // mutate mapped state before its guards settle. Retire the exact state this\n // hydration read because store-level reference cleanup cannot see the clone.\n removeMissingHydratedContainer({\n childIdsByParentId,\n existingState,\n host,\n previousParentId,\n remoteContainer,\n state,\n });\n return null;\n }\n if (persistenceResult.status !== \"persisted\") return null;\n const { record: nextRecord } = persistenceResult;\n installContainerMetadataRecord(nextState, nextRecord);\n if (input.isCurrent?.() === false) {\n return existingState;\n }\n nextState.container = {\n ...nextState.container,\n metadataDocumentId: remoteContainer.metadataDocumentId,\n organizationId: remoteContainer.organizationId,\n parentId: nextState.container.parentId,\n };\n\n installUpdatedRemoteContainerState(existingState, nextState, host);\n moveIndexedContainerChild(\n childIdsByParentId,\n remoteContainer.id,\n previousParentId,\n existingState.container.parentId,\n );\n await reconcileLocalOnlyRootContainers({\n childIdsByParentId,\n isCurrent: input.isCurrent,\n remoteRootState: existingState,\n requestDocumentPriming: host.requestDocumentPriming,\n state,\n });\n return existingState;\n}\n\ninterface UpsertRemoteContainerStateInput {\n childIdsByParentId?: ContainerChildIndex | undefined;\n containerIdsWithPendingMetadataUpdates: ReadonlySet<string>;\n containerIdsWithPendingStructuralIntents: ReadonlySet<string>;\n host: RemoteContainerHydrationHost;\n expectedHydrationTombstone?: ContainerHydrationTombstone | null | undefined;\n isCurrent?: (() => boolean) | undefined;\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n}\n\n/** A pull can observe the same manifest change as a missed realtime hint. */\nfunction invalidateListedProjectionCaches(\n input: UpsertRemoteContainerStateInput,\n) {\n const held = input.state.containersById.get(input.remoteContainer.id);\n if (\n held &&\n (held.record.accessStateHash !==\n input.remoteContainer.metadataAccessStateHash ||\n (held.container.effectiveAccessLevel ?? \"read\") !==\n input.remoteContainer.effectiveAccessLevel)\n ) {\n // Eviction admits no remote state. Drop citations before verification can\n // advance local checkpoints past those cached container/document paths.\n invalidateContainerProjectionCaches(input.state, [\n input.remoteContainer.id,\n ]);\n }\n}\n\nexport async function upsertRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n): Promise<ContainerState | null> {\n let expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n const heldState = input.state.containersById.get(input.remoteContainer.id);\n const heldBinding = heldState\n ? heldContainerBinding(heldState)\n : await input.state.persistence.loadHeldContainerBinding(\n input.state.runtime.infra.execSql,\n input.remoteContainer.id,\n );\n const listed = input.remoteContainer;\n // A folder re-homed away from the listed organization never returns there,\n // whatever binding (possibly none, after a reset) the device holds now.\n const supersededListing =\n !listingRepeatsHeldOrdinaryBinding(heldBinding, listed) &&\n (await input.state.persistence.isSupersededContainerBinding(\n input.state.runtime.infra.execSql,\n { containerId: listed.id, organizationId: listed.organizationId },\n ));\n if (input.isCurrent?.() === false) return null;\n invalidateListedProjectionCaches(input);\n const backwardsClock =\n heldState?.container.serverUpdatedAt != null &&\n heldState.container.serverUpdatedAt > listed.updatedAt;\n const verified = await verifyRemoteContainerDestination({\n ...input,\n heldBinding,\n supersededListing,\n refresh: !!input.expectedHydrationTombstone || backwardsClock,\n onVerifiedCheckpoint: (checkpoint) => {\n expectedPlacementCheckpoint = checkpoint;\n },\n });\n if (!verified || input.isCurrent?.() === false) return null;\n // A signed projection from a lagging replica can still repeat our old pin.\n // Retry until it covers the manifest whose listing would be checkpointed.\n if (\n backwardsClock &&\n expectedPlacementCheckpoint?.manifestHash !== listed.metadataAccessStateHash\n )\n return null;\n input = { ...input, remoteContainer: verified };\n const existingState = input.state.containersById.get(\n input.remoteContainer.id,\n );\n const remoteState = await runWithSecurityIncidentReporting(\n input.state.runtime.util.reportSecurityIncident,\n {\n objectId: verified.id,\n objectKind: \"container\",\n operation: \"container.binding.persist\",\n organizationId: verified.organizationId,\n },\n async () =>\n (await rebindReHomedContainer({\n existingState,\n heldBinding,\n isCurrent: input.isCurrent,\n state: input.state,\n verified,\n }))\n ? persistVerifiedRemoteContainer({\n ...input,\n existingState,\n expectedPlacementCheckpoint,\n })\n : null,\n );\n if (!remoteState) {\n return null;\n }\n await reconcileLocalOnlySystemContainers({\n childIdsByParentId: input.childIdsByParentId,\n isCurrent: input.isCurrent,\n requestDocumentPriming: input.host.requestDocumentPriming,\n remoteSystemState: remoteState,\n state: input.state,\n });\n return remoteState;\n}\n\n/**\n * Upsert one listed folder, isolating a rejected proof or binding. The refusal\n * was already reported; returning no state leaves the item unapplied without\n * blocking independent folders.\n */\nexport async function upsertIsolatedRemoteContainerState(\n input: UpsertRemoteContainerStateInput,\n recordIncompleteItem?: (outcome: \"refused\" | \"retry\") => void,\n recordUnavailable?:\n | ((error: ProjectionDependencyUnavailableError) => void)\n | undefined,\n): Promise<ContainerState | null> {\n try {\n return await upsertRemoteContainerState(input);\n } catch (error) {\n if (isKeyingVerificationError(error)) {\n recordIncompleteItem?.(\"refused\");\n return null;\n }\n if (isProjectionVerificationCancelledError(error)) return null;\n if (\n error instanceof ProjectionDependencyUnavailableError &&\n recordUnavailable\n ) {\n recordUnavailable(error);\n recordIncompleteItem?.(\"retry\");\n return null;\n }\n throw error;\n }\n}\n\nfunction persistVerifiedRemoteContainer(\n input: UpsertRemoteContainerStateInput & {\n existingState: ContainerState | undefined;\n expectedPlacementCheckpoint: AccessManifestCheckpoint | undefined;\n },\n): Promise<ContainerState | null> {\n const { existingState, expectedPlacementCheckpoint } = input;\n return existingState\n ? updateExistingRemoteContainerState({\n verifiedPlacement: expectedPlacementCheckpoint,\n childIdsByParentId: input.childIdsByParentId,\n containerIdsWithPendingMetadataUpdates:\n input.containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents:\n input.containerIdsWithPendingStructuralIntents,\n existingState,\n host: input.host,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n })\n : insertRemoteContainerState({\n childIdsByParentId: input.childIdsByParentId,\n host: input.host,\n expectedHydrationTombstone: input.expectedHydrationTombstone ?? null,\n expectedPlacementCheckpoint,\n isCurrent: input.isCurrent,\n remoteContainer: input.remoteContainer,\n state: input.state,\n });\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  import { isCanonicalSignedAt } from "../../../internal/validators/util/index.js";
2
2
  import { removeIndexedContainerChild } from "./lanes/childIndex.js";
3
+ import { pendingFolderRestorations, recordFolderRestoration, } from "./lanes/restorationReceipt.js";
4
+ import { resolveTombstoneCascade } from "./lanes/tombstoneAccess.js";
3
5
  import { containerStateMatchesFingerprint } from "./remoteContainers/containerStateFingerprint.js";
4
- import { collectRemovedContainers } from "./tombstoneReasons.js";
5
6
  function latestContainerItemsById(items) {
6
7
  const latestItems = new Map();
7
8
  for (const item of items) {
@@ -48,13 +49,15 @@ export function getApplicableRemoteContainerItems(response) {
48
49
  });
49
50
  }
50
51
  async function applyContainerTombstoneCascade(input) {
51
- const { childIdsByParentId, expectedContainerStates, preservedContainerIds, state, tombstone, } = input;
52
- const { fenceOnlyContainerIds, absentDeletedContainerIds, removalByContainerId, removedContainerIds, } = collectRemovedContainers({
53
- childIdsByParentId,
54
- containersById: state.containersById,
55
- preservedContainerIds,
56
- tombstones: [tombstone],
57
- });
52
+ const { childIdsByParentId, expectedContainerStates, state } = input;
53
+ const resolved = await resolveTombstoneCascade(input);
54
+ if (!resolved || input.isCurrent?.() === false)
55
+ return {
56
+ current: input.isCurrent?.() !== false,
57
+ removedCount: 0,
58
+ settled: false,
59
+ };
60
+ const { fenceOnlyContainerIds, absentDeletedContainerIds, removalByContainerId, removedContainerIds, } = resolved.cascade;
58
61
  const affectedContainerIds = new Set([
59
62
  ...removedContainerIds,
60
63
  ...absentDeletedContainerIds,
@@ -77,10 +80,21 @@ async function applyContainerTombstoneCascade(input) {
77
80
  return removal ? [{ containerId, ...removal }] : [];
78
81
  }), {
79
82
  discoveryOnly: true,
80
- expectedContainers: Array.from(affectedContainerIds, (containerId) => ({
81
- containerId,
82
- expectedContainer: expectedContainerStates.get(containerId)?.container ?? null,
83
- })),
83
+ expectedContainers: Array.from(affectedContainerIds, (containerId) => {
84
+ const metadata = state.containersById.get(containerId)?.record;
85
+ return {
86
+ containerId,
87
+ ...(resolved.denied?.has(containerId)
88
+ ? {
89
+ confirmedAccessLoss: {
90
+ placementHash: resolved.denied.get(containerId) ?? null,
91
+ expectedMetadata: metadata ? { ...metadata } : null,
92
+ },
93
+ }
94
+ : {}),
95
+ expectedContainer: expectedContainerStates.get(containerId)?.container ?? null,
96
+ };
97
+ }),
84
98
  stillCurrent: input.isCurrent,
85
99
  });
86
100
  if (deletedContainerIds.length !== affectedContainerIds.size) {
@@ -101,8 +115,36 @@ async function applyContainerTombstoneCascade(input) {
101
115
  settled: true,
102
116
  };
103
117
  }
118
+ function preserveOtherRoots(state, liveContainerIds, tombstoneRootIds, rootId) {
119
+ const preservedContainerIds = new Set([
120
+ ...liveContainerIds,
121
+ ...tombstoneRootIds,
122
+ ...Array.from(state.containersById, ([id, state]) => state.container.metadataDocumentId === null ? id : null).filter((id) => id !== null),
123
+ ]);
124
+ if (state.containersById.get(rootId)?.container.metadataDocumentId !== null) {
125
+ preservedContainerIds.delete(rootId);
126
+ }
127
+ return preservedContainerIds;
128
+ }
104
129
  export async function applyContainerTombstones(input) {
105
- const tombstones = getApplicableContainerTombstones(input.response);
130
+ // A folder can regain access after one of its cached children moved away.
131
+ // Its live listing keeps the folder and reconciles the previously held tree.
132
+ const restored = await pendingFolderRestorations({
133
+ ...input,
134
+ items: input.remoteContainerItems,
135
+ execSql: input.state.runtime.infra.execSql,
136
+ });
137
+ const restoredById = new Map(restored.map((item) => [item.id, item]));
138
+ const tombstones = [
139
+ ...getApplicableContainerTombstones(input.response),
140
+ ...restored.map((item) => ({
141
+ containerId: item.id,
142
+ parentId: item.parentId,
143
+ depth: item.depth,
144
+ updatedAt: item.updatedAt,
145
+ reason: "access_revoked",
146
+ })),
147
+ ];
106
148
  if (tombstones.length === 0 || input.isCurrent?.() === false) {
107
149
  return {
108
150
  changedCount: 0,
@@ -121,25 +163,26 @@ export async function applyContainerTombstones(input) {
121
163
  // Apply each root as its own CAS-protected cascade. Other explicit roots
122
164
  // stay out of this cascade so their own reason wins and one stale root
123
165
  // cannot block independent tombstones or live items on the page.
124
- const preservedContainerIds = new Set([
125
- ...liveContainerIds,
126
- ...tombstoneRootIds,
127
- ...Array.from(input.state.containersById, ([id, state]) => state.container.metadataDocumentId === null ? id : null).filter((id) => id !== null),
128
- ]);
129
- if (input.state.containersById.get(tombstone.containerId)?.container
130
- .metadataDocumentId !== null) {
131
- preservedContainerIds.delete(tombstone.containerId);
132
- }
166
+ const preservedContainerIds = preserveOtherRoots(input.state, liveContainerIds, tombstoneRootIds, tombstone.containerId);
167
+ const live = restoredById.get(tombstone.containerId);
168
+ const stillCurrent = () => input.isCurrent?.() !== false && !(live && input.isPaused?.(live));
133
169
  const result = await applyContainerTombstoneCascade({
170
+ reconcileDescendants: live !== undefined,
171
+ afterParentPage: input.response.nextWatermark
172
+ ? { parentId: input.parentId, watermark: input.response.nextWatermark }
173
+ : undefined,
134
174
  childIdsByParentId: input.childIdsByParentId,
135
175
  expectedContainerStates: input.expectedContainerStates,
136
- isCurrent: input.isCurrent,
176
+ isCurrent: stillCurrent,
137
177
  preservedContainerIds,
138
178
  state: input.state,
139
179
  tombstone,
140
180
  });
141
181
  changedCount += result.removedCount;
142
- completed = completed && result.settled;
182
+ if (live && input.isPaused?.(live) && input.isCurrent?.() !== false)
183
+ continue;
184
+ const recorded = await recordFolderRestoration(input.state.runtime.infra.execSql, live, result.settled, stillCurrent);
185
+ completed = completed && recorded;
143
186
  if (!result.current) {
144
187
  return { changedCount, completed: false, current: false };
145
188
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tombstoneApplication.js","sourceRoot":"","sources":["tombstoneApplication.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAE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,kBAAkB,KAAK,IAAI,EAC9B,CAAC;YACD,qBAAqB,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QACtD,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,8BAA8B,CAAC;YAClD,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;YAC5C,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;YACtD,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,qBAAqB;YACrB,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,SAAS;SACV,CAAC,CAAC;QACH,YAAY,IAAI,MAAM,CAAC,YAAY,CAAC;QACpC,SAAS,GAAG,SAAS,IAAI,MAAM,CAAC,OAAO,CAAC;QACxC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type {\n ContainerSyncTombstone,\n ListContainersResponse,\n} from \"@tearleads/validators/response\";\nimport { isCanonicalSignedAt } from \"@tearleads/validators/util\";\nimport { removeIndexedContainerChild } from \"./lanes/childIndex\";\nimport { containerStateMatchesFingerprint } from \"./remoteContainers/containerStateFingerprint\";\nimport { collectRemovedContainers } from \"./tombstoneReasons\";\nimport type {\n ContainerChildIndex,\n ExpectedContainerState,\n ListedRemoteContainerPageItem,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nfunction latestContainerItemsById(\n items: ReadonlyArray<ListedRemoteContainerPageItem>,\n): Map<string, ListedRemoteContainerPageItem> {\n const latestItems = new Map<string, ListedRemoteContainerPageItem>();\n for (const item of items) {\n const current = latestItems.get(item.id);\n if (!current || current.updatedAt < item.updatedAt) {\n latestItems.set(item.id, item);\n }\n }\n\n return latestItems;\n}\n\nfunction latestContainerTombstonesById(\n tombstones: ReadonlyArray<ContainerSyncTombstone>,\n): Map<string, ContainerSyncTombstone> {\n const latestTombstones = new Map<string, ContainerSyncTombstone>();\n for (const tombstone of tombstones) {\n if (!isCanonicalSignedAt(tombstone.updatedAt))\n throw new Error(\"Container tombstone timestamp is not canonical\");\n const current = latestTombstones.get(tombstone.containerId);\n if (\n !current ||\n current.updatedAt < tombstone.updatedAt ||\n (current.updatedAt === tombstone.updatedAt &&\n current.reason === \"access_revoked\" &&\n tombstone.reason === \"deleted\")\n ) {\n latestTombstones.set(tombstone.containerId, tombstone);\n }\n }\n\n return latestTombstones;\n}\n\nfunction getApplicableContainerTombstones(\n response: ListContainersResponse,\n): ContainerSyncTombstone[] {\n const latestItems = latestContainerItemsById(response.items);\n return Array.from(\n latestContainerTombstonesById(response.tombstones).values(),\n ).filter((tombstone) => {\n const item = latestItems.get(tombstone.containerId);\n return (\n !item ||\n item.updatedAt < tombstone.updatedAt ||\n (item.updatedAt === tombstone.updatedAt && tombstone.reason === \"deleted\")\n );\n });\n}\n\nexport function getApplicableRemoteContainerItems(\n response: ListContainersResponse,\n): ListedRemoteContainerPageItem[] {\n const latestTombstones = latestContainerTombstonesById(response.tombstones);\n return response.items.filter((item) => {\n const tombstone = latestTombstones.get(item.id);\n return (\n !tombstone ||\n tombstone.updatedAt < item.updatedAt ||\n (tombstone.updatedAt === item.updatedAt &&\n tombstone.reason === \"access_revoked\")\n );\n });\n}\n\nasync function applyContainerTombstoneCascade(input: {\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n preservedContainerIds: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n tombstone: ContainerSyncTombstone;\n}): Promise<{ current: boolean; removedCount: number; settled: boolean }> {\n const {\n childIdsByParentId,\n expectedContainerStates,\n preservedContainerIds,\n state,\n tombstone,\n } = input;\n const {\n fenceOnlyContainerIds,\n absentDeletedContainerIds,\n removalByContainerId,\n removedContainerIds,\n } = collectRemovedContainers({\n childIdsByParentId,\n containersById: state.containersById,\n preservedContainerIds,\n tombstones: [tombstone],\n });\n const affectedContainerIds = new Set([\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ]);\n for (const containerId of affectedContainerIds) {\n if (\n !containerStateMatchesFingerprint({\n currentState: state.containersById.get(containerId),\n expectedFingerprint:\n expectedContainerStates.get(containerId)?.fingerprint,\n })\n ) {\n return { current: true, removedCount: 0, settled: false };\n }\n }\n\n const deletedContainerIds = await state.persistence.deleteContainers(\n state.runtime.infra.execSql,\n [\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ].flatMap((containerId) => {\n const removal = removalByContainerId.get(containerId);\n return removal ? [{ containerId, ...removal }] : [];\n }),\n {\n discoveryOnly: true,\n expectedContainers: Array.from(affectedContainerIds, (containerId) => ({\n containerId,\n expectedContainer:\n expectedContainerStates.get(containerId)?.container ?? null,\n })),\n stillCurrent: input.isCurrent,\n },\n );\n if (deletedContainerIds.length !== affectedContainerIds.size) {\n return { current: true, removedCount: 0, settled: false };\n }\n if (input.isCurrent?.() === false) {\n return { current: false, removedCount: 0, settled: false };\n }\n for (const containerId of removedContainerIds) {\n const parentId =\n state.containersById.get(containerId)?.container.parentId ?? null;\n removeIndexedContainerChild(childIdsByParentId, containerId, parentId);\n childIdsByParentId.delete(containerId);\n state.containersById.delete(containerId);\n }\n\n return {\n current: true,\n removedCount: removedContainerIds.length,\n settled: true,\n };\n}\n\nexport async function applyContainerTombstones(input: {\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n remoteContainerItems: ReadonlyArray<ListedRemoteContainerPageItem>;\n response: ListContainersResponse;\n state: RemoteContainerHydrationState;\n}): Promise<{ changedCount: number; completed: boolean; current: boolean }> {\n const tombstones = getApplicableContainerTombstones(input.response);\n if (tombstones.length === 0 || input.isCurrent?.() === false) {\n return {\n changedCount: 0,\n completed: true,\n current: input.isCurrent?.() !== false,\n };\n }\n\n const tombstoneRootIds = new Set(\n tombstones.map((tombstone) => tombstone.containerId),\n );\n const liveContainerIds = input.remoteContainerItems.map((item) => item.id);\n let changedCount = 0;\n let completed = true;\n for (const tombstone of tombstones) {\n if (input.isCurrent?.() === false) {\n return { changedCount, completed: false, current: false };\n }\n // Apply each root as its own CAS-protected cascade. Other explicit roots\n // stay out of this cascade so their own reason wins and one stale root\n // cannot block independent tombstones or live items on the page.\n const preservedContainerIds = new Set([\n ...liveContainerIds,\n ...tombstoneRootIds,\n ...Array.from(input.state.containersById, ([id, state]) =>\n state.container.metadataDocumentId === null ? id : null,\n ).filter((id): id is string => id !== null),\n ]);\n if (\n input.state.containersById.get(tombstone.containerId)?.container\n .metadataDocumentId !== null\n ) {\n preservedContainerIds.delete(tombstone.containerId);\n }\n const result = await applyContainerTombstoneCascade({\n childIdsByParentId: input.childIdsByParentId,\n expectedContainerStates: input.expectedContainerStates,\n isCurrent: input.isCurrent,\n preservedContainerIds,\n state: input.state,\n tombstone,\n });\n changedCount += result.removedCount;\n completed = completed && result.settled;\n if (!result.current) {\n return { changedCount, completed: false, current: false };\n }\n }\n\n return { changedCount, completed, current: true };\n}\n"]}
1
+ {"version":3,"file":"tombstoneApplication.js","sourceRoot":"","sources":["tombstoneApplication.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EACL,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,gCAAgC,EAAE,MAAM,8CAA8C,CAAC;AAQhG,SAAS,wBAAwB,CAC/B,KAAmD;IAEnD,MAAM,WAAW,GAAG,IAAI,GAAG,E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,EAAE,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AACpD,CAAC","sourcesContent":["import type { ListContainerDocumentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSyncTombstone,\n ListContainersResponse,\n} from \"@tearleads/validators/response\";\nimport { isCanonicalSignedAt } from \"@tearleads/validators/util\";\nimport { removeIndexedContainerChild } from \"./lanes/childIndex\";\nimport {\n pendingFolderRestorations,\n recordFolderRestoration,\n} from \"./lanes/restorationReceipt\";\nimport { resolveTombstoneCascade } from \"./lanes/tombstoneAccess\";\nimport { containerStateMatchesFingerprint } from \"./remoteContainers/containerStateFingerprint\";\nimport type {\n ContainerChildIndex,\n ExpectedContainerState,\n ListedRemoteContainerPageItem,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nfunction latestContainerItemsById(\n items: ReadonlyArray<ListedRemoteContainerPageItem>,\n): Map<string, ListedRemoteContainerPageItem> {\n const latestItems = new Map<string, ListedRemoteContainerPageItem>();\n for (const item of items) {\n const current = latestItems.get(item.id);\n if (!current || current.updatedAt < item.updatedAt) {\n latestItems.set(item.id, item);\n }\n }\n\n return latestItems;\n}\n\nfunction latestContainerTombstonesById(\n tombstones: ReadonlyArray<ContainerSyncTombstone>,\n): Map<string, ContainerSyncTombstone> {\n const latestTombstones = new Map<string, ContainerSyncTombstone>();\n for (const tombstone of tombstones) {\n if (!isCanonicalSignedAt(tombstone.updatedAt))\n throw new Error(\"Container tombstone timestamp is not canonical\");\n const current = latestTombstones.get(tombstone.containerId);\n if (\n !current ||\n current.updatedAt < tombstone.updatedAt ||\n (current.updatedAt === tombstone.updatedAt &&\n current.reason === \"access_revoked\" &&\n tombstone.reason === \"deleted\")\n ) {\n latestTombstones.set(tombstone.containerId, tombstone);\n }\n }\n\n return latestTombstones;\n}\n\nfunction getApplicableContainerTombstones(\n response: ListContainersResponse,\n): ContainerSyncTombstone[] {\n const latestItems = latestContainerItemsById(response.items);\n return Array.from(\n latestContainerTombstonesById(response.tombstones).values(),\n ).filter((tombstone) => {\n const item = latestItems.get(tombstone.containerId);\n return (\n !item ||\n item.updatedAt < tombstone.updatedAt ||\n (item.updatedAt === tombstone.updatedAt && tombstone.reason === \"deleted\")\n );\n });\n}\n\nexport function getApplicableRemoteContainerItems(\n response: ListContainersResponse,\n): ListedRemoteContainerPageItem[] {\n const latestTombstones = latestContainerTombstonesById(response.tombstones);\n return response.items.filter((item) => {\n const tombstone = latestTombstones.get(item.id);\n return (\n !tombstone ||\n tombstone.updatedAt < item.updatedAt ||\n (tombstone.updatedAt === item.updatedAt &&\n tombstone.reason === \"access_revoked\")\n );\n });\n}\n\nasync function applyContainerTombstoneCascade(input: {\n reconcileDescendants: boolean;\n afterParentPage: ListContainerDocumentLanesRequest[\"afterParentPage\"];\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n preservedContainerIds: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n tombstone: ContainerSyncTombstone;\n}): Promise<{ current: boolean; removedCount: number; settled: boolean }> {\n const { childIdsByParentId, expectedContainerStates, state } = input;\n const resolved = await resolveTombstoneCascade(input);\n if (!resolved || input.isCurrent?.() === false)\n return {\n current: input.isCurrent?.() !== false,\n removedCount: 0,\n settled: false,\n };\n const {\n fenceOnlyContainerIds,\n absentDeletedContainerIds,\n removalByContainerId,\n removedContainerIds,\n } = resolved.cascade;\n const affectedContainerIds = new Set([\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ]);\n for (const containerId of affectedContainerIds) {\n if (\n !containerStateMatchesFingerprint({\n currentState: state.containersById.get(containerId),\n expectedFingerprint:\n expectedContainerStates.get(containerId)?.fingerprint,\n })\n ) {\n return { current: true, removedCount: 0, settled: false };\n }\n }\n\n const deletedContainerIds = await state.persistence.deleteContainers(\n state.runtime.infra.execSql,\n [\n ...removedContainerIds,\n ...absentDeletedContainerIds,\n ...fenceOnlyContainerIds,\n ].flatMap((containerId) => {\n const removal = removalByContainerId.get(containerId);\n return removal ? [{ containerId, ...removal }] : [];\n }),\n {\n discoveryOnly: true,\n expectedContainers: Array.from(affectedContainerIds, (containerId) => {\n const metadata = state.containersById.get(containerId)?.record;\n return {\n containerId,\n ...(resolved.denied?.has(containerId)\n ? {\n confirmedAccessLoss: {\n placementHash: resolved.denied.get(containerId) ?? null,\n expectedMetadata: metadata ? { ...metadata } : null,\n },\n }\n : {}),\n expectedContainer:\n expectedContainerStates.get(containerId)?.container ?? null,\n };\n }),\n stillCurrent: input.isCurrent,\n },\n );\n if (deletedContainerIds.length !== affectedContainerIds.size) {\n return { current: true, removedCount: 0, settled: false };\n }\n if (input.isCurrent?.() === false) {\n return { current: false, removedCount: 0, settled: false };\n }\n for (const containerId of removedContainerIds) {\n const parentId =\n state.containersById.get(containerId)?.container.parentId ?? null;\n removeIndexedContainerChild(childIdsByParentId, containerId, parentId);\n childIdsByParentId.delete(containerId);\n state.containersById.delete(containerId);\n }\n\n return {\n current: true,\n removedCount: removedContainerIds.length,\n settled: true,\n };\n}\n\nfunction preserveOtherRoots(\n state: RemoteContainerHydrationState,\n liveContainerIds: ReadonlyArray<string>,\n tombstoneRootIds: ReadonlySet<string>,\n rootId: string,\n) {\n const preservedContainerIds = new Set([\n ...liveContainerIds,\n ...tombstoneRootIds,\n ...Array.from(state.containersById, ([id, state]) =>\n state.container.metadataDocumentId === null ? id : null,\n ).filter((id): id is string => id !== null),\n ]);\n if (state.containersById.get(rootId)?.container.metadataDocumentId !== null) {\n preservedContainerIds.delete(rootId);\n }\n return preservedContainerIds;\n}\n\nexport async function applyContainerTombstones(input: {\n parentId: string | null;\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n isCurrent?: (() => boolean) | undefined;\n isPaused?: (item: ListedRemoteContainerPageItem) => boolean;\n remoteContainerItems: ReadonlyArray<ListedRemoteContainerPageItem>;\n response: ListContainersResponse;\n state: RemoteContainerHydrationState;\n}): Promise<{ changedCount: number; completed: boolean; current: boolean }> {\n // A folder can regain access after one of its cached children moved away.\n // Its live listing keeps the folder and reconciles the previously held tree.\n const restored = await pendingFolderRestorations({\n ...input,\n items: input.remoteContainerItems,\n execSql: input.state.runtime.infra.execSql,\n });\n const restoredById = new Map(restored.map((item) => [item.id, item]));\n const tombstones = [\n ...getApplicableContainerTombstones(input.response),\n ...restored.map((item) => ({\n containerId: item.id,\n parentId: item.parentId,\n depth: item.depth,\n updatedAt: item.updatedAt,\n reason: \"access_revoked\" as const,\n })),\n ];\n if (tombstones.length === 0 || input.isCurrent?.() === false) {\n return {\n changedCount: 0,\n completed: true,\n current: input.isCurrent?.() !== false,\n };\n }\n\n const tombstoneRootIds = new Set(\n tombstones.map((tombstone) => tombstone.containerId),\n );\n const liveContainerIds = input.remoteContainerItems.map((item) => item.id);\n let changedCount = 0;\n let completed = true;\n for (const tombstone of tombstones) {\n if (input.isCurrent?.() === false) {\n return { changedCount, completed: false, current: false };\n }\n // Apply each root as its own CAS-protected cascade. Other explicit roots\n // stay out of this cascade so their own reason wins and one stale root\n // cannot block independent tombstones or live items on the page.\n const preservedContainerIds = preserveOtherRoots(\n input.state,\n liveContainerIds,\n tombstoneRootIds,\n tombstone.containerId,\n );\n const live = restoredById.get(tombstone.containerId);\n const stillCurrent = () =>\n input.isCurrent?.() !== false && !(live && input.isPaused?.(live));\n const result = await applyContainerTombstoneCascade({\n reconcileDescendants: live !== undefined,\n afterParentPage: input.response.nextWatermark\n ? { parentId: input.parentId, watermark: input.response.nextWatermark }\n : undefined,\n childIdsByParentId: input.childIdsByParentId,\n expectedContainerStates: input.expectedContainerStates,\n isCurrent: stillCurrent,\n preservedContainerIds,\n state: input.state,\n tombstone,\n });\n changedCount += result.removedCount;\n if (live && input.isPaused?.(live) && input.isCurrent?.() !== false)\n continue;\n const recorded = await recordFolderRestoration(\n input.state.runtime.infra.execSql,\n live,\n result.settled,\n stillCurrent,\n );\n completed = completed && recorded;\n if (!result.current) {\n return { changedCount, completed: false, current: false };\n }\n }\n\n return { changedCount, completed, current: true };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { RequestResult, WriterProjectionListing } from "../../../internal/api-client/index.js";
1
+ import type { ApiClient, RequestResult, WriterProjectionListing } from "../../../internal/api-client/index.js";
2
2
  import type { ContainerReplacementAuthorizationsResponse } from "../../../internal/validators/operation/index.js";
3
3
  import type { ListContainerParentLanesRequest } from "../../../internal/validators/request/index.js";
4
4
  import type { ContainerSummary, ContainerWriterProjectionResponse, DocumentWriterProjectionResponse, ListContainerParentLanesResponse, ListContainersResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
@@ -34,6 +34,7 @@ export interface ContainerState {
34
34
  }
35
35
  interface RemoteContainerHydrationApi extends Partial<PrincipalPolicyHistoryReader>, CurrentPrincipalPolicyReader {
36
36
  getContainerReplacementAuthorizationsResult(containerId: string, replacesOrganizationId: string): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;
37
+ listContainerDocumentLanes: ApiClient["listContainerDocumentLanes"];
37
38
  evictContainerWriterProjection(containerId: string): void;
38
39
  evictWriterProjectionsCiting(containerIds: readonly string[]): void;
39
40
  getContainerWriterProjection(containerId: string, listing?: WriterProjectionListing): Promise<ContainerWriterProjectionResponse | null>;
@@ -59,6 +60,7 @@ export interface RemoteContainerHydrationState {
59
60
  * fell short while it ran.
60
61
  */
61
62
  containerListingFailures?: number | undefined;
63
+ containerParentIdsNeedingHydration?: Set<string | null>;
62
64
  containersById: Map<string, ContainerState>;
63
65
  lifecycleGeneration?: number | undefined;
64
66
  persistence: ContainerContentsPersistence;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n RequestResult,\n WriterProjectionListing,\n} from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { createContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"metadataVersionVector\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint or a pull drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried 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 | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n evictContainerWriterProjection(containerId: string): void;\n evictWriterProjectionsCiting(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"organizations\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport type HydrationOutcome = \"complete\" | \"refused\" | \"retry\";\nexport interface ReconnectPages {\n laneIdPrefix: string;\n recordManualError(error: Error): void;\n}\n\nexport interface ReconnectCrawl {\n isCurrent(): boolean;\n record(outcome: HydrationOutcome, manualRejection?: Error): void;\n}\n\nexport interface RemoteContainerHydrationState {\n readonly parentLaneRequestPrefix?: string;\n /**\n * Container listing requests that failed or timed out, in a current crawl.\n * An explicit refresh compares it across its wait to tell whether a listing\n * fell short while it ran.\n */\n containerListingFailures?: number | undefined;\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n /**\n * Owe a metadata document one remote read, durably, before hydration\n * advances the timestamps and lane watermark that revealed it.\n */\n requestMetadataRevalidation?:\n | ((request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n }) => Promise<void>)\n | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n /** An earlier page is incomplete. Continue discovery without persisting a cursor past it. */\n skipWatermarkWrite?: boolean;\n continuationCursors?: Set<string>;\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ApiClient,\n RequestResult,\n WriterProjectionListing,\n} from \"@tearleads/api-client\";\nimport type { ContainerReplacementAuthorizationsResponse } from \"@tearleads/validators/operation\";\nimport type { ListContainerParentLanesRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerSummary,\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n ListContainerParentLanesResponse,\n ListContainersResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord,\n ContainerHydrationTombstone,\n ContainerRecord,\n createContainerParentSyncLane,\n} from \"../containerPersistence\";\nimport type { ContainerMetadataPatch } from \"../metadata\";\nimport type { createContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ListedRemoteContainerPageItem =\n ListContainersResponse[\"items\"][number];\nexport type ContainerChildIndex = Map<string, Set<string>>;\nexport type QueueContainerParentLane = (parentId: string | null) => void;\nexport type RemoteContainerIngestQueue = Map<string, RemoteContainer>;\nexport type SaveContainerOptions = Parameters<\n ContainerContentsPersistence[\"saveContainer\"]\n>[3];\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createContainerMetadataDocument>\n>;\nexport type RemoteContainer = Pick<\n ContainerSummary,\n | \"createdAt\"\n | \"effectiveAccessLevel\"\n | \"systemSlot\"\n | \"id\"\n | \"metadataAccessEpoch\"\n | \"metadataAccessStateHash\"\n | \"metadataDocumentId\"\n | \"metadataReferencedPrincipals\"\n | \"metadataVersionVector\"\n | \"organizationId\"\n | \"parentId\"\n | \"updatedAt\"\n>;\n\nexport interface ContainerState {\n containerWriterProjection?:\n | ContainerWriterProjectionResponse\n | null\n | undefined;\n /**\n * Bumped whenever a realtime hint or a pull drops this container's cached writer\n * projections (container and metadata document alike); an operation that\n * fetched or carried 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 | undefined;\n metadataReferencedPrincipals?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n container: ContainerRecord;\n doc: ContainerMetadataDocumentState;\n metadataWriterProjection?:\n | DocumentWriterProjectionResponse\n | null\n | undefined;\n /** Durable pull progress mirrored from the metadata document record. */\n pullContinuation?: ContainerDocumentRecord[\"pullContinuation\"] | undefined;\n record: ContainerDocumentRecord;\n}\n\ninterface RemoteContainerHydrationApi\n extends Partial<PrincipalPolicyHistoryReader>,\n CurrentPrincipalPolicyReader {\n getContainerReplacementAuthorizationsResult(\n containerId: string,\n replacesOrganizationId: string,\n ): Promise<RequestResult<ContainerReplacementAuthorizationsResponse>>;\n listContainerDocumentLanes: ApiClient[\"listContainerDocumentLanes\"];\n evictContainerWriterProjection(containerId: string): void;\n evictWriterProjectionsCiting(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n listing?: WriterProjectionListing,\n ): Promise<ContainerWriterProjectionResponse | null>;\n listContainerParentLanes(\n input: ListContainerParentLanesRequest,\n ): Promise<ListContainerParentLanesResponse | null>;\n}\n\ninterface RemoteContainerHydrationRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"adoptRootContainer\"\n | \"crypto\"\n | \"infra\"\n | \"organizations\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: RemoteContainerHydrationApi;\n}\n\nexport type HydrationOutcome = \"complete\" | \"refused\" | \"retry\";\nexport interface ReconnectPages {\n laneIdPrefix: string;\n recordManualError(error: Error): void;\n}\n\nexport interface ReconnectCrawl {\n isCurrent(): boolean;\n record(outcome: HydrationOutcome, manualRejection?: Error): void;\n}\n\nexport interface RemoteContainerHydrationState {\n readonly parentLaneRequestPrefix?: string;\n /**\n * Container listing requests that failed or timed out, in a current crawl.\n * An explicit refresh compares it across its wait to tell whether a listing\n * fell short while it ran.\n */\n containerListingFailures?: number | undefined;\n containerParentIdsNeedingHydration?: Set<string | null>;\n containersById: Map<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n persistence: ContainerContentsPersistence;\n rootLaneHydrated?: boolean | undefined;\n runtime: RemoteContainerHydrationRuntime;\n structuralGeneration?: number | undefined;\n}\n\nexport type PersistContainerStateResult =\n | { status: \"identity-superseded\"; record: ContainerDocumentRecord }\n | { status: \"missing\" }\n | {\n status: \"persisted\";\n record: ContainerDocumentRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | { status: \"stale-generation\" };\n\nexport interface RemoteContainerHydrationHost {\n persistContainerState: (\n containerState: ContainerState,\n patch?: Partial<ContainerMetadataPatch>,\n updateView?: boolean,\n saveOptions?: SaveContainerOptions,\n mutationOptions?: {\n /** Queued metadata rows the server committed, settled in this write. */\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedStateWhenMissing?: ContainerState | undefined;\n isCurrent?: (() => boolean) | undefined;\n createIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"createIntentSettlement\"];\n moveIntentSettlement?: Parameters<\n ContainerContentsPersistence[\"commitMetadataMutation\"]\n >[1][\"moveIntentSettlement\"];\n preserveDurableStructureWhenPending?: boolean | undefined;\n },\n ) => Promise<PersistContainerStateResult>;\n requestDocumentPriming?: (() => void) | undefined;\n /**\n * Owe a metadata document one remote read, durably, before hydration\n * advances the timestamps and lane watermark that revealed it.\n */\n requestMetadataRevalidation?:\n | ((request: {\n readonly advertisedVersionVector: string;\n readonly documentId: string;\n }) => Promise<void>)\n | undefined;\n updateSnapshot: () => void;\n}\n\nexport interface ContainerParentHydrationLane {\n /** An earlier page is incomplete. Continue discovery without persisting a cursor past it. */\n skipWatermarkWrite?: boolean;\n continuationCursors?: Set<string>;\n parentId: string | null;\n watermark?: ListContainersResponse[\"nextWatermark\"];\n}\n\nexport interface ExpectedContainerState {\n container: ContainerRecord;\n fingerprint: string;\n}\n\nexport interface FetchedContainerParentLanePage {\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: ReadonlyMap<string, ContainerHydrationTombstone>;\n lane: ContainerParentHydrationLane;\n response: ListContainersResponse;\n syncLane: ReturnType<typeof createContainerParentSyncLane>;\n}\n"]}
@@ -1,14 +1,14 @@
1
1
  import { and, eq, inArray, or } from "drizzle-orm";
2
2
  import { containerSyncWatermarks } from "../../../data/sqlite/schema/containerSyncWatermarkSchema.js";
3
3
  import { remoteResetBatches } from "../../../data/sqlite/sqliteBindBudget.js";
4
- const CONTAINER_DOCUMENTS_LANE = "container_documents";
4
+ const CONTAINER_ID_LANES = ["container_documents", "container_restoration"];
5
5
  const CONTAINER_PARENT_LANE = "container_parent";
6
6
  // The API root feed lists every accessible organization. Its one cursor must
7
7
  // reset on any organization's purge; child feeds use globally unique IDs.
8
8
  const ROOT_LANE_ID = "root";
9
9
  const PARENT_LANE_PREFIX = "parent:";
10
10
  export function isRemoteResetSyncCursor(input) {
11
- if (input.row.laneKind === CONTAINER_DOCUMENTS_LANE) {
11
+ if (CONTAINER_ID_LANES.includes(input.row.laneKind)) {
12
12
  return input.containerIds.has(input.row.laneId);
13
13
  }
14
14
  if (input.row.laneKind !== CONTAINER_PARENT_LANE)
@@ -29,7 +29,7 @@ export async function clearRemoteResetSyncCursors(input) {
29
29
  const parentLaneIds = containerBatch.map((containerId) => `${PARENT_LANE_PREFIX}${containerId}`);
30
30
  await input.tx
31
31
  .delete(table)
32
- .where(or(and(eq(table.laneKind, CONTAINER_PARENT_LANE), inArray(table.laneId, parentLaneIds)), and(eq(table.laneKind, CONTAINER_DOCUMENTS_LANE), inArray(table.laneId, containerBatch))))
32
+ .where(or(and(eq(table.laneKind, CONTAINER_PARENT_LANE), inArray(table.laneId, parentLaneIds)), and(inArray(table.laneKind, CONTAINER_ID_LANES), inArray(table.laneId, containerBatch))))
33
33
  .run();
34
34
  }
35
35
  }
@@ -1 +1 @@
1
- {"version":3,"file":"remoteResetCursorScope.js","sourceRoot":"","sources":["remoteResetCursorScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EAAE,kBAAkB,EAAE,MAAM,uCAAuC,CAAC;AAG3E,MAAM,wBAAwB,GAAG,qBAAqB,CAAC;AACvD,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;AACjD,6EAA6E;AAC7E,0EAA0E;AAC1E,MAAM,YAAY,GAAG,MAAM,CAAC;AAC5B,MAAM,kBAAkB,GAAG,SAAS,CAAC;AAOrC,MAAM,UAAU,uBAAuB,CAAC,KAGvC;IACC,IAAI,KAAK,CAAC,GAAG,CAAC,QAAQ,KAAK,wBAAwB,EAAE,CAAC;QACpD,OAAO,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;IACD,IAAI,KAAK,CAAC,GAAG,CAAC,QAAQ,KAAK,qBAAqB;QAAE,OAAO,KAAK,CAAC;IAC/D,IAAI,KAAK,CAAC,GAAG,CAAC,MAAM,KAAK,YAAY;QAAE,OAAO,IAAI,CAAC;IACnD,OAAO,CACL,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,kBAAkB,CAAC;QAC/C,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAC1E,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAGjD;IACC,mEAAmE;IACnE,MAAM,KAAK,GAAG,uBAAuB,CAAC;IACtC,MAAM,KAAK,CAAC,EAAE;SACX,MAAM,CAAC,KAAK,CAAC;SACb,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,qBAAqB,CAAC,EACzC,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,YAAY,CAAC,CAC/B,CACF;SACA,GAAG,EAAE,CAAC;IACT,KAAK,MAAM,cAAc,IAAI,kBAAkB,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE,CAAC;QACpE,MAAM,aAAa,GAAG,cAAc,CAAC,GAAG,CACtC,CAAC,WAAW,EAAE,EAAE,CAAC,GAAG,kBAAkB,GAAG,WAAW,EAAE,CACvD,CAAC;QACF,MAAM,KAAK,CAAC,EAAE;aACX,MAAM,CAAC,KAAK,CAAC;aACb,KAAK,CACJ,EAAE,CACA,GAAG,CACD,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,qBAAqB,CAAC,EACzC,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,aAAa,CAAC,CACrC,EACD,GAAG,CACD,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,wBAAwB,CAAC,EAC5C,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,cAAc,CAAC,CACtC,CACF,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { containerSyncWatermarks } from \"../../../data/sqlite/schema/containerSyncWatermarkSchema\";\nimport { remoteResetBatches } from \"../../../data/sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\n\nconst CONTAINER_DOCUMENTS_LANE = \"container_documents\";\nconst CONTAINER_PARENT_LANE = \"container_parent\";\n// The API root feed lists every accessible organization. Its one cursor must\n// reset on any organization's purge; child feeds use globally unique IDs.\nconst ROOT_LANE_ID = \"root\";\nconst PARENT_LANE_PREFIX = \"parent:\";\n\ninterface SyncCursorRow {\n readonly laneId: string;\n readonly laneKind: string;\n}\n\nexport function isRemoteResetSyncCursor(input: {\n containerIds: ReadonlySet<string>;\n row: SyncCursorRow;\n}): boolean {\n if (input.row.laneKind === CONTAINER_DOCUMENTS_LANE) {\n return input.containerIds.has(input.row.laneId);\n }\n if (input.row.laneKind !== CONTAINER_PARENT_LANE) return false;\n if (input.row.laneId === ROOT_LANE_ID) return true;\n return (\n input.row.laneId.startsWith(PARENT_LANE_PREFIX) &&\n input.containerIds.has(input.row.laneId.slice(PARENT_LANE_PREFIX.length))\n );\n}\n\nexport async function clearRemoteResetSyncCursors(input: {\n containerIds: readonly string[];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n // One row per lane holds both the cursor and its freshness marker.\n const table = containerSyncWatermarks;\n await input.tx\n .delete(table)\n .where(\n and(\n eq(table.laneKind, CONTAINER_PARENT_LANE),\n eq(table.laneId, ROOT_LANE_ID),\n ),\n )\n .run();\n for (const containerBatch of remoteResetBatches(input.containerIds)) {\n const parentLaneIds = containerBatch.map(\n (containerId) => `${PARENT_LANE_PREFIX}${containerId}`,\n );\n await input.tx\n .delete(table)\n .where(\n or(\n and(\n eq(table.laneKind, CONTAINER_PARENT_LANE),\n inArray(table.laneId, parentLaneIds),\n ),\n and(\n eq(table.laneKind, CONTAINER_DOCUMENTS_LANE),\n inArray(table.laneId, containerBatch),\n ),\n ),\n )\n .run();\n }\n}\n"]}
1
+ {"version":3,"file":"remoteResetCursorScope.js","sourceRoot":"","sources":["remoteResetCursorScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OA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C/B,CACF;SACA,GAAG,EAAE,CAAC;IACT,KAAK,MAAM,cAAc,IAAI,kBAAkB,CAAC,KAAK,CAAC,YAAY,CAAC,EAAE,CAAC;QACpE,MAAM,aAAa,GAAG,cAAc,CAAC,GAAG,CACtC,CAAC,WAAW,EAAE,EAAE,CAAC,GAAG,kBAAkB,GAAG,WAAW,EAAE,CACvD,CAAC;QACF,MAAM,KAAK,CAAC,EAAE;aACX,MAAM,CAAC,KAAK,CAAC;aACb,KAAK,CACJ,EAAE,CACA,GAAG,CACD,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,qBAAqB,CAAC,EACzC,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,aAAa,CAAC,CACrC,EACD,GAAG,CACD,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,kBAAkB,CAAC,EAC3C,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,cAAc,CAAC,CACtC,CACF,CACF;aACA,GAAG,EAAE,CAAC;IACX,CAAC;AACH,CAAC","sourcesContent":["import { and, eq, inArray, or } from \"drizzle-orm\";\nimport { containerSyncWatermarks } from \"../../../data/sqlite/schema/containerSyncWatermarkSchema\";\nimport { remoteResetBatches } from \"../../../data/sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\n\nconst CONTAINER_ID_LANES = [\"container_documents\", \"container_restoration\"];\nconst CONTAINER_PARENT_LANE = \"container_parent\";\n// The API root feed lists every accessible organization. Its one cursor must\n// reset on any organization's purge; child feeds use globally unique IDs.\nconst ROOT_LANE_ID = \"root\";\nconst PARENT_LANE_PREFIX = \"parent:\";\n\ninterface SyncCursorRow {\n readonly laneId: string;\n readonly laneKind: string;\n}\n\nexport function isRemoteResetSyncCursor(input: {\n containerIds: ReadonlySet<string>;\n row: SyncCursorRow;\n}): boolean {\n if (CONTAINER_ID_LANES.includes(input.row.laneKind)) {\n return input.containerIds.has(input.row.laneId);\n }\n if (input.row.laneKind !== CONTAINER_PARENT_LANE) return false;\n if (input.row.laneId === ROOT_LANE_ID) return true;\n return (\n input.row.laneId.startsWith(PARENT_LANE_PREFIX) &&\n input.containerIds.has(input.row.laneId.slice(PARENT_LANE_PREFIX.length))\n );\n}\n\nexport async function clearRemoteResetSyncCursors(input: {\n containerIds: readonly string[];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n // One row per lane holds both the cursor and its freshness marker.\n const table = containerSyncWatermarks;\n await input.tx\n .delete(table)\n .where(\n and(\n eq(table.laneKind, CONTAINER_PARENT_LANE),\n eq(table.laneId, ROOT_LANE_ID),\n ),\n )\n .run();\n for (const containerBatch of remoteResetBatches(input.containerIds)) {\n const parentLaneIds = containerBatch.map(\n (containerId) => `${PARENT_LANE_PREFIX}${containerId}`,\n );\n await input.tx\n .delete(table)\n .where(\n or(\n and(\n eq(table.laneKind, CONTAINER_PARENT_LANE),\n inArray(table.laneId, parentLaneIds),\n ),\n and(\n inArray(table.laneKind, CONTAINER_ID_LANES),\n inArray(table.laneId, containerBatch),\n ),\n ),\n )\n .run();\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { ContainerSyncWatermarkRepository, containerContentsSyncLane, } from "../../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
2
- import { DocumentContainerProjectionRepository } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
3
- import { upsertDiscoveredDocuments } from "../../../data/persistence/documents/documentsPersistence.js";
2
+ import { DocumentContainerProjectionRepository, deleteContainerDocumentTombstonePlacementRows, } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
3
+ import { ContainerDocumentTombstoneHoldRepository } from "../../../data/persistence/documents/containerDocumentTombstoneHoldRepository.js";
4
+ import { applyContainerDocumentTombstones, upsertDiscoveredDocuments, } from "../../../data/persistence/documents/documentsPersistence.js";
4
5
  import { runSerializedSqlMutation } from "../../../data/sqlite/sqlExec.js";
5
6
  /**
6
7
  * Binds a discovery lane's writes to its generation and its organization
@@ -16,6 +17,9 @@ export function guardDocumentDiscoveryWrites(input) {
16
17
  ? skipped
17
18
  : write(lockedExecSql));
18
19
  return {
20
+ applyContainerDocumentTombstones: (rows, stillCurrent) => whileCurrent([], (locked) => applyContainerDocumentTombstones(locked, rows, deleteContainerDocumentTombstonePlacementRows), stillCurrent),
21
+ holdContainerDocumentTombstones: (rows, stillCurrent) => whileCurrent(undefined, (locked) => new ContainerDocumentTombstoneHoldRepository(locked).holdContainerDocumentTombstones(rows), stillCurrent),
22
+ refuteContainerDocumentTombstoneHolds: (rows, stillCurrent) => whileCurrent(undefined, (locked) => new ContainerDocumentTombstoneHoldRepository(locked).refuteContainerDocumentTombstoneHolds(rows), stillCurrent),
19
23
  replaceDocumentLinksBatch: (inputs, stillCurrent) => whileCurrent(undefined, (lockedExecSql) => new DocumentContainerProjectionRepository(lockedExecSql).replaceDocumentLinksBatch(inputs), stillCurrent),
20
24
  saveContainerDocumentWatermark: (containerId, watermark, stillCurrent) => whileCurrent(undefined, async (lockedExecSql) => {
21
25
  await new ContainerSyncWatermarkRepository(lockedExecSql).saveWatermark(containerContentsSyncLane(containerId), watermark);
@@ -1 +1 @@
1
- {"version":3,"file":"discoveryGuard.js","sourceRoot":"","sources":["discoveryGuard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EAAE,qCAAqC,EAAE,MAAM,qFAAqF,CAAC;AAC5I,OAAO,EAAE,yBAAyB,EAAE,MAAM,0DAA0D,CAAC;AACrG,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAYxE;;;;;;;;GAQG;AACH,MAAM,UAAU,4BAA4B,CAAC,KAI5C;IACC,MAAM,YAAY,GAAG,CACnB,OAAU,EACV,KAA6C,EAC7C,YAAoC,EACxB,EAAE,CACd,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC9D,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,MAAM,YAAY,EAAE,CAAC;QACzC,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CACzB,CAAC;IACJ,OAAO;QACL,yBAAyB,EAAE,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,CAClD,YAAY,CACV,SAAS,EACT,CAAC,aAAa,EAAE,EAAE,CAChB,IAAI,qCAAqC,CACvC,aAAa,CACd,CAAC,yBAAyB,CAAC,MAAM,CAAC,EACrC,YAAY,CACb;QACH,8BAA8B,EAAE,CAAC,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,CACvE,YAAY,CACV,SAAS,EACT,KAAK,EAAE,aAAa,EAAE,EAAE;YACtB,MAAM,IAAI,gCAAgC,CACxC,aAAa,CACd,CAAC,aAAa,CAAC,yBAAyB,CAAC,WAAW,CAAC,EAAE,SAAS,CAAC,CAAC;QACrE,CAAC,EACD,YAAY,CACb;QACH,yBAAyB,EAAE,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,CAClD,YAAY,CACV,EAAE,EACF,CAAC,aAAa,EAAE,EAAE,CAAC,yBAAyB,CAAC,aAAa,EAAE,MAAM,CAAC,EACnE,YAAY,CACb;QACH,KAAK,CAAC,yBAAyB,CAAC,GAAG,IAAI;YACrC,MAAM,YAAY,GAAG,MAAM,KAAK,CAAC,yBAAyB,CAAC,GAAG,IAAI,CAAC,CAAC;YACpE,OAAO;gBACL,GAAG,YAAY;gBACf,SAAS,EAAE,KAAK,IAAI,EAAE,CACpB,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,YAAY,CAAC,SAAS,EAAE,CAAC;aACxD,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { upsertDiscoveredDocuments } from \"../../../data/persistence/documents/documentsPersistence\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DiscoverContainerDocumentsOptions } from \"../documentDiscovery/documentDiscoveryTypes\";\n\ntype PauseGuardedDiscovery = Pick<\n DiscoverContainerDocumentsOptions,\n | \"replaceDocumentLinksBatch\"\n | \"saveContainerDocumentWatermark\"\n | \"upsertDiscoveredDocuments\"\n | \"verifyDiscoveredDocuments\"\n>;\n\n/**\n * Binds a discovery lane's writes to its generation and its organization\n * staying unpaused. Access changes and pauses invalidate in-flight listings,\n * so the apply stops at its next check, and each write already started\n * rechecks under the SQLite mutation lock. A listing that verified before\n * its organization paused therefore saves no watermark: a watermark saved\n * past documents it did not apply would let the listing after a resume skip\n * them.\n */\nexport function guardDocumentDiscoveryWrites(input: {\n readonly execSql: ExecSql;\n readonly isPaused: () => boolean;\n readonly verifyDiscoveredDocuments: DiscoverContainerDocumentsOptions[\"verifyDiscoveredDocuments\"];\n}): PauseGuardedDiscovery {\n const whileCurrent = <T>(\n skipped: T,\n write: (lockedExecSql: ExecSql) => Promise<T>,\n stillCurrent: () => Promise<boolean>,\n ): Promise<T> =>\n runSerializedSqlMutation(input.execSql, async (lockedExecSql) =>\n input.isPaused() || !(await stillCurrent())\n ? skipped\n : write(lockedExecSql),\n );\n return {\n replaceDocumentLinksBatch: (inputs, stillCurrent) =>\n whileCurrent(\n undefined,\n (lockedExecSql) =>\n new DocumentContainerProjectionRepository(\n lockedExecSql,\n ).replaceDocumentLinksBatch(inputs),\n stillCurrent,\n ),\n saveContainerDocumentWatermark: (containerId, watermark, stillCurrent) =>\n whileCurrent(\n undefined,\n async (lockedExecSql) => {\n await new ContainerSyncWatermarkRepository(\n lockedExecSql,\n ).saveWatermark(containerContentsSyncLane(containerId), watermark);\n },\n stillCurrent,\n ),\n upsertDiscoveredDocuments: (inputs, stillCurrent) =>\n whileCurrent(\n [],\n (lockedExecSql) => upsertDiscoveredDocuments(lockedExecSql, inputs),\n stillCurrent,\n ),\n async verifyDiscoveredDocuments(...args) {\n const verification = await input.verifyDiscoveredDocuments(...args);\n return {\n ...verification,\n isCurrent: async () =>\n !input.isPaused() && (await verification.isCurrent()),\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"discoveryGuard.js","sourceRoot":"","sources":["discoveryGuard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EACL,qCAAqC,EACrC,6CAA6C,GAC9C,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,wCAAwC,EAAE,MAAM,8EAA8E,CAAC;AACxI,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,wBAAwB,EAAE,MAAM,8BAA8B,CAAC;AAexE;;;;;;;;GAQG;AACH,MAAM,UAAU,4BAA4B,CAAC,KAI5C;IACC,MAAM,YAAY,GAAG,CACnB,OAAU,EACV,KAA6C,EAC7C,YAAoC,EACxB,EAAE,CACd,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC9D,KAAK,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,MAAM,YAAY,EAAE,CAAC;QACzC,CAAC,CAAC,OAAO;QACT,CAAC,CAAC,KAAK,CAAC,aAAa,CAAC,CACzB,CAAC;IACJ,OAAO;QACL,gCAAgC,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,CACvD,YAAY,CACV,EAAE,EACF,CAAC,MAAM,EAAE,EAAE,CACT,gCAAgC,CAC9B,MAAM,EACN,IAAI,EACJ,6CAA6C,CAC9C,EACH,YAAY,CACb;QACH,+BAA+B,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,EAAE,CACtD,YAAY,CACV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;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport {\n DocumentContainerProjectionRepository,\n deleteContainerDocumentTombstonePlacementRows,\n} from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport {\n applyContainerDocumentTombstones,\n upsertDiscoveredDocuments,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DiscoverContainerDocumentsOptions } from \"../documentDiscovery/documentDiscoveryTypes\";\n\ntype PauseGuardedDiscovery = Pick<\n DiscoverContainerDocumentsOptions,\n | \"applyContainerDocumentTombstones\"\n | \"holdContainerDocumentTombstones\"\n | \"refuteContainerDocumentTombstoneHolds\"\n | \"replaceDocumentLinksBatch\"\n | \"saveContainerDocumentWatermark\"\n | \"upsertDiscoveredDocuments\"\n | \"verifyDiscoveredDocuments\"\n>;\n\n/**\n * Binds a discovery lane's writes to its generation and its organization\n * staying unpaused. Access changes and pauses invalidate in-flight listings,\n * so the apply stops at its next check, and each write already started\n * rechecks under the SQLite mutation lock. A listing that verified before\n * its organization paused therefore saves no watermark: a watermark saved\n * past documents it did not apply would let the listing after a resume skip\n * them.\n */\nexport function guardDocumentDiscoveryWrites(input: {\n readonly execSql: ExecSql;\n readonly isPaused: () => boolean;\n readonly verifyDiscoveredDocuments: DiscoverContainerDocumentsOptions[\"verifyDiscoveredDocuments\"];\n}): PauseGuardedDiscovery {\n const whileCurrent = <T>(\n skipped: T,\n write: (lockedExecSql: ExecSql) => Promise<T>,\n stillCurrent: () => Promise<boolean>,\n ): Promise<T> =>\n runSerializedSqlMutation(input.execSql, async (lockedExecSql) =>\n input.isPaused() || !(await stillCurrent())\n ? skipped\n : write(lockedExecSql),\n );\n return {\n applyContainerDocumentTombstones: (rows, stillCurrent) =>\n whileCurrent(\n [],\n (locked) =>\n applyContainerDocumentTombstones(\n locked,\n rows,\n deleteContainerDocumentTombstonePlacementRows,\n ),\n stillCurrent,\n ),\n holdContainerDocumentTombstones: (rows, stillCurrent) =>\n whileCurrent(\n undefined,\n (locked) =>\n new ContainerDocumentTombstoneHoldRepository(\n locked,\n ).holdContainerDocumentTombstones(rows),\n stillCurrent,\n ),\n refuteContainerDocumentTombstoneHolds: (rows, stillCurrent) =>\n whileCurrent(\n undefined,\n (locked) =>\n new ContainerDocumentTombstoneHoldRepository(\n locked,\n ).refuteContainerDocumentTombstoneHolds(rows),\n stillCurrent,\n ),\n replaceDocumentLinksBatch: (inputs, stillCurrent) =>\n whileCurrent(\n undefined,\n (lockedExecSql) =>\n new DocumentContainerProjectionRepository(\n lockedExecSql,\n ).replaceDocumentLinksBatch(inputs),\n stillCurrent,\n ),\n saveContainerDocumentWatermark: (containerId, watermark, stillCurrent) =>\n whileCurrent(\n undefined,\n async (lockedExecSql) => {\n await new ContainerSyncWatermarkRepository(\n lockedExecSql,\n ).saveWatermark(containerContentsSyncLane(containerId), watermark);\n },\n stillCurrent,\n ),\n upsertDiscoveredDocuments: (inputs, stillCurrent) =>\n whileCurrent(\n [],\n (lockedExecSql) => upsertDiscoveredDocuments(lockedExecSql, inputs),\n stillCurrent,\n ),\n async verifyDiscoveredDocuments(...args) {\n const verification = await input.verifyDiscoveredDocuments(...args);\n return {\n ...verification,\n isCurrent: async () =>\n !input.isPaused() && (await verification.isCurrent()),\n };\n },\n };\n}\n"]}
@@ -47,12 +47,15 @@ function assertVerdictsCoverCandidates(candidates, verdicts) {
47
47
  */
48
48
  export async function settleContainerDocumentTombstones(input) {
49
49
  const { store } = input;
50
+ const isCurrent = input.isCurrent ?? (async () => true);
50
51
  const held = await store.listHeldContainerDocumentTombstones(input.containerIds);
51
52
  const candidates = await mergeTombstoneCandidates(store, input.tombstones, held);
52
53
  if (candidates.length === 0) {
53
54
  return [];
54
55
  }
55
56
  const verdicts = await store.verifyContainerDocumentTombstones(candidates);
57
+ if (!(await isCurrent()))
58
+ return [];
56
59
  assertVerdictsCoverCandidates(candidates, verdicts);
57
60
  const verified = verdicts.flatMap((verdict) => verdict.kind === "verified" ? [verdict.tombstone] : []);
58
61
  const refuted = verdicts.flatMap((verdict) => verdict.kind === "refuted" ? [verdict.tombstone] : []);
@@ -75,12 +78,12 @@ export async function settleContainerDocumentTombstones(input) {
75
78
  }));
76
79
  });
77
80
  const summaries = verified.length > 0
78
- ? await store.applyContainerDocumentTombstones(verified)
81
+ ? await store.applyContainerDocumentTombstones(verified, isCurrent)
79
82
  : [];
80
83
  const retryKeys = new Set(refuted.map(placementKey));
81
84
  const visibleRetries = dedupePlacements(headLinkedPlacements).filter((placement) => !retryKeys.has(placementKey(placement)));
82
85
  if (visibleRetries.length > 0) {
83
- await store.refuteContainerDocumentTombstoneHolds(visibleRetries);
86
+ await store.refuteContainerDocumentTombstoneHolds(visibleRetries, isCurrent);
84
87
  }
85
88
  const retries = [
86
89
  ...unverified,
@@ -88,7 +91,7 @@ export async function settleContainerDocumentTombstones(input) {
88
91
  ...refuted.map((tombstone) => ({ ...tombstone, refuted: true })),
89
92
  ];
90
93
  if (retries.length > 0)
91
- await store.holdContainerDocumentTombstones(retries);
94
+ await store.holdContainerDocumentTombstones(retries, isCurrent);
92
95
  return summaries;
93
96
  }
94
97
  //# sourceMappingURL=documentTombstoneGate.js.map