@tearleads/client-sdk 0.1.221 → 0.1.223

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 (95) hide show
  1. package/client/session/index.js +1 -2
  2. package/client/session/index.js.map +1 -1
  3. package/client/session/sessionOrganizationCreation.js +1 -1
  4. package/client/session/sessionOrganizationCreation.js.map +1 -1
  5. package/client/session/sessionPurgeRecovery.js +1 -2
  6. package/client/session/sessionPurgeRecovery.js.map +1 -1
  7. package/data/blobs/attachmentContentIdentity.d.ts +3 -0
  8. package/data/{documents → blobs}/attachmentContentIdentity.js +1 -1
  9. package/data/{documents → blobs}/attachmentContentIdentity.js.map +1 -1
  10. package/data/documents/shared/projection/freshProjectionRetry.d.ts +14 -0
  11. package/data/documents/shared/projection/freshProjectionRetry.js +55 -0
  12. package/data/documents/shared/projection/freshProjectionRetry.js.map +1 -0
  13. package/data/documents/shared/projection/index.d.ts +1 -0
  14. package/data/documents/shared/projection/index.js +1 -0
  15. package/data/documents/shared/projection/index.js.map +1 -1
  16. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +1 -1
  17. package/data/persistence/container-contents/containerContentsPersistenceTypes.js +0 -1
  18. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  19. package/data/persistence/container-contents/containerCreateIntentSettlement.js +2 -2
  20. package/data/persistence/container-contents/containerCreateIntentSettlement.js.map +1 -1
  21. package/data/persistence/container-contents/containerIntentPersistence.js +2 -2
  22. package/data/persistence/container-contents/containerIntentPersistence.js.map +1 -1
  23. package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +10 -9
  24. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +14 -3
  25. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  26. package/data/persistence/documents/documentsPersistence.d.ts +2 -1
  27. package/data/persistence/documents/documentsPersistence.js +3 -3
  28. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  29. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  30. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js.map +1 -1
  31. package/data/persistence/documents/internal/containerDocumentTombstones.d.ts +10 -0
  32. package/data/persistence/documents/internal/containerDocumentTombstones.js +3 -14
  33. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  34. package/data/persistence/documents/internal/discoveredDocumentPlacement.js +1 -1
  35. package/data/persistence/documents/internal/discoveredDocumentPlacement.js.map +1 -1
  36. package/data/persistence/documents/internal/discoveredDocumentUpsert.js +1 -1
  37. package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
  38. package/data/persistence/{container-contents → documents}/pendingContainerCreate.js +1 -2
  39. package/data/persistence/documents/pendingContainerCreate.js.map +1 -0
  40. package/data/sqlite/schema/index.d.ts +1 -1
  41. package/data/sqlite/schema/index.js +1 -1
  42. package/data/sqlite/schema/index.js.map +1 -1
  43. package/data/sqlite/schema/localIntentSchema.d.ts +6 -0
  44. package/data/sqlite/schema/localIntentSchema.js +6 -0
  45. package/data/sqlite/schema/localIntentSchema.js.map +1 -1
  46. package/package.json +1 -1
  47. package/stores/documents/documentStore/attachments/attachmentIntents.js +1 -2
  48. package/stores/documents/documentStore/attachments/attachmentIntents.js.map +1 -1
  49. package/workflows/blobs/hydration/hydrate.js +1 -1
  50. package/workflows/blobs/hydration/hydrate.js.map +1 -1
  51. package/workflows/blobs/index.d.ts +1 -0
  52. package/workflows/blobs/index.js +1 -0
  53. package/workflows/blobs/index.js.map +1 -1
  54. package/workflows/blobs/upload/index.js +1 -2
  55. package/workflows/blobs/upload/index.js.map +1 -1
  56. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +1 -1
  57. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
  58. package/workflows/container-contents/documentQueries/index.js +2 -2
  59. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  60. package/workflows/documents/create/index.js +3 -2
  61. package/workflows/documents/create/index.js.map +1 -1
  62. package/workflows/documents/sync/readOnlyProjectionFailure.js +1 -1
  63. package/workflows/documents/sync/readOnlyProjectionFailure.js.map +1 -1
  64. package/workflows/documents/sync/readOnlySync.js +2 -1
  65. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  66. package/workflows/documents/syncFailures/syncFailureClassification.d.ts +0 -14
  67. package/workflows/documents/syncFailures/syncFailureClassification.js +1 -54
  68. package/workflows/documents/syncFailures/syncFailureClassification.js.map +1 -1
  69. package/workflows/organizations/index.d.ts +0 -1
  70. package/workflows/organizations/index.js +0 -1
  71. package/workflows/organizations/index.js.map +1 -1
  72. package/workflows/registration/index.d.ts +3 -0
  73. package/workflows/registration/index.js +3 -0
  74. package/workflows/registration/index.js.map +1 -1
  75. package/workflows/{organizations/provisioning → registration/organizationCreation}/createOrganization.d.ts +2 -2
  76. package/workflows/{organizations/provisioning → registration/organizationCreation}/createOrganization.js +1 -1
  77. package/workflows/registration/organizationCreation/createOrganization.js.map +1 -0
  78. package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationCreationIntent.d.ts +1 -1
  79. package/workflows/registration/organizationCreation/organizationCreationIntent.js.map +1 -0
  80. package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationProvisioningAttempt.d.ts +1 -1
  81. package/workflows/registration/organizationCreation/organizationProvisioningAttempt.js.map +1 -0
  82. package/workflows/registration/organizationCreation/organizationReplacementVerification.d.ts +14 -0
  83. package/data/persistence/container-contents/pendingContainerCreate.js.map +0 -1
  84. package/workflows/organizations/provisioning/createOrganization.js.map +0 -1
  85. package/workflows/organizations/provisioning/organizationCreationIntent.js.map +0 -1
  86. package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +0 -1
  87. /package/data/persistence/{container-contents → documents}/documentPlacement.d.ts +0 -0
  88. /package/data/persistence/{container-contents → documents}/documentPlacement.js +0 -0
  89. /package/data/persistence/{container-contents → documents}/documentPlacement.js.map +0 -0
  90. /package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationCreationIntent.js +0 -0
  91. /package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationCreationState.js +0 -0
  92. /package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationCreationState.js.map +0 -0
  93. /package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationProvisioningAttempt.js +0 -0
  94. /package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationReplacementVerification.js +0 -0
  95. /package/workflows/{organizations/provisioning → registration/organizationCreation}/organizationReplacementVerification.js.map +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"containerCreateIntentSettlement.js","sourceRoot":"","sources":["containerCreateIntentSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAE3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,KAAK,UAAU,uCAAuC,CAAC,KAQtD;IACC,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,EAAE;SAC3B,MAAM,CAAC,YAAY,CAAC;SACpB,GAAG,CAAC;QACH,UAAU,EAAE,QAAQ;QACpB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,6BAA6B,EAAE,KAAK,CAAC,6BAA6B;QAClE,SAAS,EAAE,IAAI;QACf,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC;SACD,KAAK,CACJ,GAAG,CACD,iBAAiB,CAAC,kBAAkB,CAAC,eAAe,CAAC,EACrD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,WAAW,CAAC,EAC7C,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,4BAA4B,CAAC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wBAAwB,EAAE,KAAK,CAAC,wBAAwB;YACxD,8BAA8B,EAAE,gBAAgB;SACjD,CAAC,CAAC;IACL,CAAC;IACD,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;QACnC,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,MAAM,CAAC,aAAa,CAAC,GAAG,MAAM,KAAK,CAAC,EAAE;SACnC,MAAM,CAAC;QACN,EAAE,EAAE,YAAY,CAAC,EAAE;QACnB,iBAAiB,EAAE,YAAY,CAAC,iBAAiB;QACjD,SAAS,EAAE,YAAY,CAAC,SAAS;KAClC,CAAC;SACD,IAAI,CAAC,YAAY,CAAC;SAClB,KAAK,CACJ,GAAG,CACD,iBAAiB,CAAC,kBAAkB,CAAC,eAAe,CAAC,EACrD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,WAAW,CAAC,EAC7C,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,4BAA4B,CAAC,EACzD,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,SAAS,CAAC,CACvC,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,CAAC,aAAa,EAAE,EAAE;QAAE,OAAO,YAAY,CAAC;IAE5C,MAAM,OAAO,GAAG,MAAM,uCAAuC,CAAC;QAC5D,GAAG,KAAK;QACR,gBAAgB,EAAE,aAAa,CAAC,EAAE;QAClC,iBAAiB,EAAE,aAAa,CAAC,SAAS;KAC3C,CAAC,CAAC;IACH,IAAI,CAAC,OAAO;QAAE,OAAO,YAAY,CAAC;IAClC,OAAO,mBAAmB,CAAC;QACzB,GAAG,KAAK;QACR,wBAAwB,EAAE,aAAa,CAAC,iBAAiB;QACzD,8BAA8B,EAAE,gBAAgB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerMoveIntentInput,\n} from \"./containerContentsPersistenceTypes\";\nimport { saveContainerMoveIntent } from \"./containerMoveIntentRows\";\n\nasync function markContainerCreateIntentRevisionSynced(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const updated = await input.tx\n .update(localIntents)\n .set({\n syncStatus: \"synced\",\n remoteContainerId: input.remoteContainerId,\n remoteMetadataDocumentId: input.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: input.remoteMetadataAccessStateHash,\n lastError: null,\n updatedAt: new Date().toISOString(),\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return updated.length > 0;\n}\n\n/**\n * The move an adopted create still owes: to the desired parent, citing where\n * the folder is now. A desired parent equal to the created one means the user\n * never moved it away, so a later remote move by another writer stands.\n */\nfunction owedCreateMove(input: {\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n}): ContainerMoveIntentInput | null {\n const desired = input.desiredParentContainerId;\n if (\n desired === input.supersededMovePreviousParentId ||\n desired === input.createdParentContainerId\n ) {\n return null;\n }\n return {\n parentContainerId: desired,\n previousParentContainerId: input.supersededMovePreviousParentId,\n };\n}\n\n/**\n * A local move of a folder the listing already carried queues its own move\n * intent, which is newer than the create's parent: it keeps its destination,\n * and now cites where the folder sits remotely rather than the parent it was\n * queued from, which never committed. One whose destination is already that\n * parent is done and is dropped.\n */\nasync function rebaseQueuedMove(input: {\n readonly containerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"none\" | \"synced\"> {\n const queued = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n );\n const arrived = await input.tx\n .delete(localIntents)\n .where(\n and(\n queued,\n eq(\n localIntents.targetContainerId,\n input.supersededMovePreviousParentId,\n ),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n if (arrived.length > 0) return \"synced\";\n const rebased = await input.tx\n .update(localIntents)\n .set({ sourceContainerId: input.supersededMovePreviousParentId })\n .where(queued)\n .returning({ containerId: localIntents.subjectId });\n return rebased.length > 0 ? \"converted-to-move\" : \"none\";\n}\n\nasync function queueOwedCreateMove(input: {\n readonly containerId: string;\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"synced\"> {\n const queued = await rebaseQueuedMove(input);\n if (queued !== \"none\") return queued;\n const moveIntent = owedCreateMove(input);\n if (!moveIntent) return \"synced\";\n await saveContainerMoveIntent({\n containerId: input.containerId,\n moveIntent,\n tx: input.tx,\n updatedAt: new Date().toISOString(),\n });\n return \"converted-to-move\";\n}\n\nexport async function settleContainerCreateIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n supersededMovePreviousParentId?: string | undefined;\n createdParentContainerId?: string | undefined;\n desiredParentContainerId?: string | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"superseded\" | \"synced\"> {\n const previousParentId = input.supersededMovePreviousParentId;\n if (await markContainerCreateIntentRevisionSynced(input)) {\n // An adopted create may still owe a move: the user can move the folder\n // after its create committed.\n if (\n previousParentId === undefined ||\n input.desiredParentContainerId === undefined\n ) {\n return \"synced\";\n }\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: input.desiredParentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n }\n if (previousParentId === undefined) {\n return \"superseded\";\n }\n\n const [currentIntent] = await input.tx\n .select({\n id: localIntents.id,\n parentContainerId: localIntents.targetContainerId,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n )\n .limit(1);\n if (!currentIntent?.id) return \"superseded\";\n\n const adopted = await markContainerCreateIntentRevisionSynced({\n ...input,\n expectedIntentId: currentIntent.id,\n expectedUpdatedAt: currentIntent.updatedAt,\n });\n if (!adopted) return \"superseded\";\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: currentIntent.parentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n}\n"]}
1
+ {"version":3,"file":"containerCreateIntentSettlement.js","sourceRoot":"","sources":["containerCreateIntentSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,0BAA0B,GAE3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,KAAK,UAAU,uCAAuC,CAAC,KAQtD;IACC,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,EAAE;SAC3B,MAAM,CAAC,YAAY,CAAC;SACpB,GA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,CAAC;QAC5D,GAAG,KAAK;QACR,gBAAgB,EAAE,aAAa,CAAC,EAAE;QAClC,iBAAiB,EAAE,aAAa,CAAC,SAAS;KAC3C,CAAC,CAAC;IACH,IAAI,CAAC,OAAO;QAAE,OAAO,YAAY,CAAC;IAClC,OAAO,mBAAmB,CAAC;QACzB,GAAG,KAAK;QACR,wBAAwB,EAAE,aAAa,CAAC,iBAAiB;QACzD,8BAA8B,EAAE,gBAAgB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerMoveIntentInput,\n} from \"./containerContentsPersistenceTypes\";\nimport { saveContainerMoveIntent } from \"./containerMoveIntentRows\";\n\nasync function markContainerCreateIntentRevisionSynced(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const updated = await input.tx\n .update(localIntents)\n .set({\n syncStatus: \"synced\",\n remoteContainerId: input.remoteContainerId,\n remoteMetadataDocumentId: input.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: input.remoteMetadataAccessStateHash,\n lastError: null,\n updatedAt: new Date().toISOString(),\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return updated.length > 0;\n}\n\n/**\n * The move an adopted create still owes: to the desired parent, citing where\n * the folder is now. A desired parent equal to the created one means the user\n * never moved it away, so a later remote move by another writer stands.\n */\nfunction owedCreateMove(input: {\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n}): ContainerMoveIntentInput | null {\n const desired = input.desiredParentContainerId;\n if (\n desired === input.supersededMovePreviousParentId ||\n desired === input.createdParentContainerId\n ) {\n return null;\n }\n return {\n parentContainerId: desired,\n previousParentContainerId: input.supersededMovePreviousParentId,\n };\n}\n\n/**\n * A local move of a folder the listing already carried queues its own move\n * intent, which is newer than the create's parent: it keeps its destination,\n * and now cites where the folder sits remotely rather than the parent it was\n * queued from, which never committed. One whose destination is already that\n * parent is done and is dropped.\n */\nasync function rebaseQueuedMove(input: {\n readonly containerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"none\" | \"synced\"> {\n const queued = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n );\n const arrived = await input.tx\n .delete(localIntents)\n .where(\n and(\n queued,\n eq(\n localIntents.targetContainerId,\n input.supersededMovePreviousParentId,\n ),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n if (arrived.length > 0) return \"synced\";\n const rebased = await input.tx\n .update(localIntents)\n .set({ sourceContainerId: input.supersededMovePreviousParentId })\n .where(queued)\n .returning({ containerId: localIntents.subjectId });\n return rebased.length > 0 ? \"converted-to-move\" : \"none\";\n}\n\nasync function queueOwedCreateMove(input: {\n readonly containerId: string;\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"synced\"> {\n const queued = await rebaseQueuedMove(input);\n if (queued !== \"none\") return queued;\n const moveIntent = owedCreateMove(input);\n if (!moveIntent) return \"synced\";\n await saveContainerMoveIntent({\n containerId: input.containerId,\n moveIntent,\n tx: input.tx,\n updatedAt: new Date().toISOString(),\n });\n return \"converted-to-move\";\n}\n\nexport async function settleContainerCreateIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n supersededMovePreviousParentId?: string | undefined;\n createdParentContainerId?: string | undefined;\n desiredParentContainerId?: string | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"superseded\" | \"synced\"> {\n const previousParentId = input.supersededMovePreviousParentId;\n if (await markContainerCreateIntentRevisionSynced(input)) {\n // An adopted create may still owe a move: the user can move the folder\n // after its create committed.\n if (\n previousParentId === undefined ||\n input.desiredParentContainerId === undefined\n ) {\n return \"synced\";\n }\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: input.desiredParentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n }\n if (previousParentId === undefined) {\n return \"superseded\";\n }\n\n const [currentIntent] = await input.tx\n .select({\n id: localIntents.id,\n parentContainerId: localIntents.targetContainerId,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n )\n .limit(1);\n if (!currentIntent?.id) return \"superseded\";\n\n const adopted = await markContainerCreateIntentRevisionSynced({\n ...input,\n expectedIntentId: currentIntent.id,\n expectedUpdatedAt: currentIntent.updatedAt,\n });\n if (!adopted) return \"superseded\";\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: currentIntent.parentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { and, asc, eq, inArray } from "drizzle-orm";
2
- import { inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "../../sqlite/schema/index.js";
2
+ import { CONTAINER_CREATE_INTENT_TYPE, inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "../../sqlite/schema/index.js";
3
3
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
4
- import { CONTAINER_CREATE_INTENT_TYPE, CONTAINER_MOVE_INTENT_TYPE, } from "./containerContentsPersistenceTypes.js";
4
+ import { CONTAINER_MOVE_INTENT_TYPE, } from "./containerContentsPersistenceTypes.js";
5
5
  import { settleContainerCreateIntentRevision } from "./containerCreateIntentSettlement.js";
6
6
  function parseCreateIntentSyncStatus(value) {
7
7
  return value === "synced" ? "synced" : "pending";
@@ -1 +1 @@
1
- {"version":3,"file":"containerIntentPersistence.js","sourceRoot":"","sources":["containerIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAU3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAExF,SAAS,2BAA2B,CAClC,KAAc;IAEd,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACnD,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAc;IAEd,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;AACrD,CAA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AAC,WAAW,CAAC;YAC7C,8DAA8D;YAC9D,qDAAqD;YACrD,OAAO,CAAC,YAAY,CAAC,UAAU,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,EACxD,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,0BAA0B,CAAC,EACvD,GAAG,CAAC,KAAK,CAAC,gBAAgB;gBACxB,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,EAAE,EAAE,KAAK,CAAC,gBAAgB,CAAC,CAAC;gBAC/C,CAAC,CAAC,EAAE,CAAC,EACP,GAAG,CAAC,KAAK,CAAC,iBAAiB;gBACzB,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,iBAAiB,CAAC,CAAC;gBACvD,CAAC,CAAC,EAAE,CAAC,CACR,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC,CAAC;QACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;YACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,YAAY,EAAE;gBAC3D,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC/D,CAAC;IACD,8BAA8B;IAC9B,4BAA4B;CACQ,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerContentsPersistence,\n type ContainerCreateIntentErrorInput,\n type ContainerCreateIntentInput,\n type ContainerCreateIntentRecord,\n type ContainerCreateIntentRevisionInput,\n type ContainerCreateIntentSyncStatus,\n type ContainerMoveIntentRecord,\n type ContainerMoveIntentRevisionInput,\n type ContainerMoveIntentSyncStatus,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\n\nfunction parseCreateIntentSyncStatus(\n value: unknown,\n): ContainerCreateIntentSyncStatus {\n return value === \"synced\" ? \"synced\" : \"pending\";\n}\n\nfunction parseMoveIntentSyncStatus(\n value: unknown,\n): ContainerMoveIntentSyncStatus {\n return value === \"blocked\" ? \"blocked\" : \"pending\";\n}\n\ninterface SelectedContainerCreateIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n syncStatus: string;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedContainerMoveIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n syncStatus: string;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction mapContainerCreateIntentRecord(\n row: SelectedContainerCreateIntentRecord,\n): ContainerCreateIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: parseCreateIntentSyncStatus(row.syncStatus),\n remoteContainerId: row.remoteContainerId,\n remoteMetadataDocumentId: row.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: row.remoteMetadataAccessStateHash,\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction mapContainerMoveIntentRecord(\n row: SelectedContainerMoveIntentRecord,\n): ContainerMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n previousParentContainerId: row.previousParentContainerId,\n intentType: CONTAINER_MOVE_INTENT_TYPE,\n syncStatus: parseMoveIntentSyncStatus(row.syncStatus),\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport async function saveContainerCreateIntent(input: {\n tx: ClientSQLiteTransactionScope;\n containerId: string;\n createIntent: ContainerCreateIntentInput;\n updatedAt: string;\n}) {\n const { containerId, createIntent, tx, updatedAt } = input;\n const id = createIntent.id ?? crypto.randomUUID();\n await tx\n .insert(localIntents)\n .values({\n id,\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: containerId,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n createdAt: updatedAt,\n updatedAt,\n })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: {\n // Timestamps can collide when a create is re-queued in one clock tick,\n // so every enqueue owns a fresh revision token too.\n id,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n updatedAt,\n },\n })\n .run();\n}\n\nexport class ContainerCreateIntentSupersededError extends Error {\n constructor() {\n super(\"Container create intent was superseded before local settlement\");\n }\n}\n\nexport async function deleteContainerMoveIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const deleted = await input.tx\n .delete(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return deleted.length > 0;\n}\n\nasync function recordCreateIntentErrorAttempt(\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n): Promise<void> {\n const {\n containerId,\n expectedIntentId,\n expectedUpdatedAt,\n message,\n stillCurrent,\n } = input;\n if (!message) throw new Error(\"Container create intent error is required\");\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: message,\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, containerId),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.id, expectedIntentId),\n eq(localIntents.updatedAt, expectedUpdatedAt),\n ),\n )\n .run();\n };\n if (stillCurrent) {\n await runtime.guardedTransaction(record, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n}\n\nasync function markMoveIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => {\n return deleteContainerMoveIntentRevision({ ...input, tx });\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result === true;\n}\n\nasync function markCreateIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => settleContainerCreateIntentRevision({ ...input, tx }),\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result !== \"superseded\";\n}\n\ntype ContainerIntentPersistence = Pick<\n ContainerContentsPersistence,\n | \"listPendingCreateIntents\"\n | \"listUnsyncedMoveIntents\"\n | \"recordCreateIntentRevisionError\"\n | \"recordMoveIntentError\"\n | \"markCreateIntentRevisionSynced\"\n | \"markMoveIntentRevisionSynced\"\n>;\n\nexport const containerIntentPersistence = {\n async listPendingCreateIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n syncStatus: localIntents.syncStatus,\n remoteContainerId: localIntents.remoteContainerId,\n remoteMetadataDocumentId: localIntents.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash:\n localIntents.remoteMetadataAccessStateHash,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerCreateIntentRecord(row));\n },\n async listUnsyncedMoveIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // No status filter: markMoveIntentRevisionSynced deletes settled rows,\n // so every surviving row is unsynced. Blocked intents replay too: \"blocked\"\n // names the reason the last attempt could not proceed, not a terminal\n // verdict — the missing container can appear via hydration, after which\n // the move completes — and hydration must still not revert them.\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n previousParentContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerMoveIntentRecord(row));\n },\n recordCreateIntentRevisionError: (execSql, input) =>\n recordCreateIntentErrorAttempt(execSql, input),\n async recordMoveIntentError(execSql, input) {\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: input.blocked ? \"blocked\" : \"pending\",\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n // Blocked rows stay updatable so a retried intent records its\n // fresh outcome and a transient failure unblocks it.\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(record, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n },\n markCreateIntentRevisionSynced,\n markMoveIntentRevisionSynced,\n} satisfies ContainerIntentPersistence;\n"]}
1
+ {"version":3,"file":"containerIntentPersistence.js","sourceRoot":"","sources":["containerIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OA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,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC/D,CAAC;IACD,8BAA8B;IAC9B,4BAA4B;CACQ,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerContentsPersistence,\n type ContainerCreateIntentErrorInput,\n type ContainerCreateIntentInput,\n type ContainerCreateIntentRecord,\n type ContainerCreateIntentRevisionInput,\n type ContainerCreateIntentSyncStatus,\n type ContainerMoveIntentRecord,\n type ContainerMoveIntentRevisionInput,\n type ContainerMoveIntentSyncStatus,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\n\nfunction parseCreateIntentSyncStatus(\n value: unknown,\n): ContainerCreateIntentSyncStatus {\n return value === \"synced\" ? \"synced\" : \"pending\";\n}\n\nfunction parseMoveIntentSyncStatus(\n value: unknown,\n): ContainerMoveIntentSyncStatus {\n return value === \"blocked\" ? \"blocked\" : \"pending\";\n}\n\ninterface SelectedContainerCreateIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n syncStatus: string;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedContainerMoveIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n syncStatus: string;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction mapContainerCreateIntentRecord(\n row: SelectedContainerCreateIntentRecord,\n): ContainerCreateIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: parseCreateIntentSyncStatus(row.syncStatus),\n remoteContainerId: row.remoteContainerId,\n remoteMetadataDocumentId: row.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: row.remoteMetadataAccessStateHash,\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction mapContainerMoveIntentRecord(\n row: SelectedContainerMoveIntentRecord,\n): ContainerMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n previousParentContainerId: row.previousParentContainerId,\n intentType: CONTAINER_MOVE_INTENT_TYPE,\n syncStatus: parseMoveIntentSyncStatus(row.syncStatus),\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport async function saveContainerCreateIntent(input: {\n tx: ClientSQLiteTransactionScope;\n containerId: string;\n createIntent: ContainerCreateIntentInput;\n updatedAt: string;\n}) {\n const { containerId, createIntent, tx, updatedAt } = input;\n const id = createIntent.id ?? crypto.randomUUID();\n await tx\n .insert(localIntents)\n .values({\n id,\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: containerId,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n createdAt: updatedAt,\n updatedAt,\n })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: {\n // Timestamps can collide when a create is re-queued in one clock tick,\n // so every enqueue owns a fresh revision token too.\n id,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n updatedAt,\n },\n })\n .run();\n}\n\nexport class ContainerCreateIntentSupersededError extends Error {\n constructor() {\n super(\"Container create intent was superseded before local settlement\");\n }\n}\n\nexport async function deleteContainerMoveIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const deleted = await input.tx\n .delete(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return deleted.length > 0;\n}\n\nasync function recordCreateIntentErrorAttempt(\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n): Promise<void> {\n const {\n containerId,\n expectedIntentId,\n expectedUpdatedAt,\n message,\n stillCurrent,\n } = input;\n if (!message) throw new Error(\"Container create intent error is required\");\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: message,\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, containerId),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.id, expectedIntentId),\n eq(localIntents.updatedAt, expectedUpdatedAt),\n ),\n )\n .run();\n };\n if (stillCurrent) {\n await runtime.guardedTransaction(record, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n}\n\nasync function markMoveIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => {\n return deleteContainerMoveIntentRevision({ ...input, tx });\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result === true;\n}\n\nasync function markCreateIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => settleContainerCreateIntentRevision({ ...input, tx }),\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result !== \"superseded\";\n}\n\ntype ContainerIntentPersistence = Pick<\n ContainerContentsPersistence,\n | \"listPendingCreateIntents\"\n | \"listUnsyncedMoveIntents\"\n | \"recordCreateIntentRevisionError\"\n | \"recordMoveIntentError\"\n | \"markCreateIntentRevisionSynced\"\n | \"markMoveIntentRevisionSynced\"\n>;\n\nexport const containerIntentPersistence = {\n async listPendingCreateIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n syncStatus: localIntents.syncStatus,\n remoteContainerId: localIntents.remoteContainerId,\n remoteMetadataDocumentId: localIntents.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash:\n localIntents.remoteMetadataAccessStateHash,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerCreateIntentRecord(row));\n },\n async listUnsyncedMoveIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // No status filter: markMoveIntentRevisionSynced deletes settled rows,\n // so every surviving row is unsynced. Blocked intents replay too: \"blocked\"\n // names the reason the last attempt could not proceed, not a terminal\n // verdict — the missing container can appear via hydration, after which\n // the move completes — and hydration must still not revert them.\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n previousParentContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerMoveIntentRecord(row));\n },\n recordCreateIntentRevisionError: (execSql, input) =>\n recordCreateIntentErrorAttempt(execSql, input),\n async recordMoveIntentError(execSql, input) {\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: input.blocked ? \"blocked\" : \"pending\",\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n // Blocked rows stay updatable so a retried intent records its\n // fresh outcome and a transient failure unblocks it.\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(record, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n },\n markCreateIntentRevisionSynced,\n markMoveIntentRevisionSynced,\n} satisfies ContainerIntentPersistence;\n"]}
@@ -1,19 +1,20 @@
1
1
  import { type ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
2
2
  import { type ExecSql } from "../../sqlite/sqlSchema.js";
3
- import { type DocumentPlacementInput, type DocumentPlacementWriteOptions } from "./documentPlacement.js";
3
+ import { type DocumentPlacementInput, type DocumentPlacementWriteOptions } from "../documents/documentPlacement.js";
4
4
  /** Link rows and their tombstone holds leave together on a remote reset. */
5
5
  export declare function deleteDocumentPlacementRowsByContainerIds(tx: ClientSQLiteTransactionScope, containerIds: ReadonlyArray<string>): Promise<void>;
6
6
  export declare function deleteDocumentPlacementRowsByDocumentIds(tx: ClientSQLiteTransactionScope, documentIds: ReadonlyArray<string>): Promise<void>;
7
- /** Removes the listed (document, container) placements, 50 pairs per statement. */
8
- export declare function deleteDocumentPlacementRowsInTransaction(tx: ClientSQLiteTransactionScope, placements: ReadonlyArray<{
9
- readonly containerId: string;
10
- readonly documentId: string;
11
- }>): Promise<void>;
12
7
  /**
13
- * Removes each document's placements outside the containers its head links,
14
- * batching documents so one statement stays inside SQLite's bind budget.
8
+ * Remove the tombstoned placements and, with each head now verified, every
9
+ * remaining local link row the head does not link: those are listing-seeded
10
+ * rows, and leaving one would keep showing the document in a container the
11
+ * signed link set never named. Rows the head links are kept as they are.
12
+ * Runs inside the Document Store tombstone transaction.
15
13
  */
16
- export declare function deleteUnlinkedDocumentPlacementRowsInTransaction(tx: ClientSQLiteTransactionScope, linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>): Promise<void>;
14
+ export declare function deleteContainerDocumentTombstonePlacementRows(tx: ClientSQLiteTransactionScope, tombstones: ReadonlyArray<{
15
+ readonly containerId: string;
16
+ readonly documentId: string;
17
+ }>, verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>): Promise<void>;
17
18
  /** Removes a deleted document's queued placement intents and link targets. */
18
19
  export declare function deleteDocumentPlacementIntentsInTransaction(tx: ClientSQLiteTransactionScope, documentId: string): Promise<void>;
19
20
  /** The caller owns the open document commit and must propagate every failure. */
@@ -7,7 +7,7 @@ import { REMOTE_RESET_SQL_BATCH_SIZE, remoteResetBatches, SQLITE_BOUND_VARIABLE_
7
7
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
8
8
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
9
9
  import { deleteContainerDocumentTombstoneHoldRowsForLinks, deleteContainerDocumentTombstoneHoldsForContainers, deleteContainerDocumentTombstoneHoldsForDocuments, placementPairsMatch, } from "../documents/containerDocumentTombstoneHoldsPersistence.js";
10
- import { filterWritableDocumentPlacements, } from "./documentPlacement.js";
10
+ import { filterWritableDocumentPlacements, } from "../documents/documentPlacement.js";
11
11
  const LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(documentContainerProjection);
12
12
  /** Link rows and their tombstone holds leave together on a remote reset. */
13
13
  export async function deleteDocumentPlacementRowsByContainerIds(tx, containerIds) {
@@ -24,8 +24,19 @@ export async function deleteDocumentPlacementRowsByDocumentIds(tx, documentIds)
24
24
  .run();
25
25
  await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);
26
26
  }
27
+ /**
28
+ * Remove the tombstoned placements and, with each head now verified, every
29
+ * remaining local link row the head does not link: those are listing-seeded
30
+ * rows, and leaving one would keep showing the document in a container the
31
+ * signed link set never named. Rows the head links are kept as they are.
32
+ * Runs inside the Document Store tombstone transaction.
33
+ */
34
+ export async function deleteContainerDocumentTombstonePlacementRows(tx, tombstones, verifiedLinkedContainerIdsByDocumentId) {
35
+ await deleteDocumentPlacementRowsInTransaction(tx, tombstones);
36
+ await deleteUnlinkedDocumentPlacementRowsInTransaction(tx, verifiedLinkedContainerIdsByDocumentId);
37
+ }
27
38
  /** Removes the listed (document, container) placements, 50 pairs per statement. */
28
- export async function deleteDocumentPlacementRowsInTransaction(tx, placements) {
39
+ async function deleteDocumentPlacementRowsInTransaction(tx, placements) {
29
40
  for (const batch of remoteResetBatches(placements)) {
30
41
  await tx
31
42
  .delete(documentContainerProjection)
@@ -37,7 +48,7 @@ export async function deleteDocumentPlacementRowsInTransaction(tx, placements) {
37
48
  * Removes each document's placements outside the containers its head links,
38
49
  * batching documents so one statement stays inside SQLite's bind budget.
39
50
  */
40
- export async function deleteUnlinkedDocumentPlacementRowsInTransaction(tx, linkedContainerIdsByDocumentId) {
51
+ async function deleteUnlinkedDocumentPlacementRowsInTransaction(tx, linkedContainerIdsByDocumentId) {
41
52
  let batch = [];
42
53
  let binds = 0;
43
54
  const flush = async () => {
@@ -1 +1 @@
1
- {"version":3,"file":"documentContainerProjectionPersistence.js","sourceRoot":"","sources":["documentContainerProjectionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC9E,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,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C,UAAU,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QACzE,IAAI,MAAM,CAAC,IAAI,KAAK,CAAC;YAAE,OAAO;QAC9B,MAAM,OAAO,GAAG,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,OAAO,GAAG,CAAC,EAAgC,EAAE,EAAE,CACnD,uBAAuB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QACzD,IAAI,OAAO,EAAE,YAAY,EAAE,CAAC;YAC1B,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;YAChE,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import { and, asc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport {\n REMOTE_RESET_SQL_BATCH_SIZE,\n remoteResetBatches,\n SQLITE_BOUND_VARIABLE_BUDGET,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n deleteContainerDocumentTombstoneHoldRowsForLinks,\n deleteContainerDocumentTombstoneHoldsForContainers,\n deleteContainerDocumentTombstoneHoldsForDocuments,\n placementPairsMatch,\n} from \"../documents/containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DocumentPlacementInput,\n type DocumentPlacementWriteOptions,\n filterWritableDocumentPlacements,\n} from \"./documentPlacement\";\n\nconst LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n documentContainerProjection,\n);\n\n/** Link rows and their tombstone holds leave together on a remote reset. */\nexport async function deleteDocumentPlacementRowsByContainerIds(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n}\n\nexport async function deleteDocumentPlacementRowsByDocumentIds(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, documentIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);\n}\n\n/** Removes the listed (document, container) placements, 50 pairs per statement. */\nexport async function deleteDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n): Promise<void> {\n for (const batch of remoteResetBatches(placements)) {\n await tx\n .delete(documentContainerProjection)\n .where(\n placementPairsMatch(\n batch,\n documentContainerProjection.documentId,\n documentContainerProjection.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * Removes each document's placements outside the containers its head links,\n * batching documents so one statement stays inside SQLite's bind budget.\n */\nexport async function deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>,\n): Promise<void> {\n let batch: SQL[] = [];\n let binds = 0;\n const flush = async () => {\n if (batch.length === 0) return;\n await tx\n .delete(documentContainerProjection)\n .where(or(...batch))\n .run();\n batch = [];\n binds = 0;\n };\n for (const [documentId, linked] of linkedContainerIdsByDocumentId) {\n // The document id plus one bind per linked container.\n const documentBinds = 1 + linked.size;\n if (\n batch.length >= REMOTE_RESET_SQL_BATCH_SIZE ||\n binds + documentBinds > SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await flush();\n }\n batch.push(unlinkedDocumentPlacementRows(documentId, linked));\n binds += documentBinds;\n }\n await flush();\n}\n\n/** A document's placements outside the containers its head links. */\nfunction unlinkedDocumentPlacementRows(\n documentId: string,\n linkedContainerIds: ReadonlySet<string>,\n): SQL {\n const ofDocument = eq(documentContainerProjection.documentId, documentId);\n return linkedContainerIds.size === 0\n ? ofDocument\n : (and(\n ofDocument,\n notInArray(documentContainerProjection.containerId, [\n ...linkedContainerIds,\n ]),\n ) ?? ofDocument);\n}\n\n/** Removes a deleted document's queued placement intents and link targets. */\nexport async function deleteDocumentPlacementIntentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<void> {\n const placementIntent = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntent),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntent).run();\n}\n\nasync function ensureDocumentLinksSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentTables,\n ]);\n}\n\nasync function replaceDocumentLinkRows(\n tx: ClientSQLiteTransactionScope,\n latest: ReadonlyMap<string, DocumentPlacementInput>,\n now: () => Date,\n options?: DocumentPlacementWriteOptions,\n): Promise<void> {\n const writable = await filterWritableDocumentPlacements(\n tx,\n [...latest.values()],\n options,\n );\n if (writable.length === 0) return;\n // A placement the writer re-asserts is no longer tombstoned: a\n // listing that links it again, or a local move that owns it, releases\n // the hold so the document is not hidden until the next retry.\n if (options?.moveIntentId) {\n await deleteContainerDocumentTombstoneHoldsForDocuments(\n tx,\n writable.map((input) => input.documentId),\n );\n } else {\n await deleteContainerDocumentTombstoneHoldRowsForLinks(tx, writable);\n }\n // Each document binds once; finish every deletion before inserting.\n for (\n let index = 0;\n index < writable.length;\n index += SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await tx\n .delete(documentContainerProjection)\n .where(\n inArray(\n documentContainerProjection.documentId,\n writable\n .slice(index, index + SQLITE_BOUND_VARIABLE_BUDGET)\n .map((input) => input.documentId),\n ),\n )\n .run();\n }\n const updatedAt = now().toISOString();\n const rows = writable.flatMap((input) =>\n Array.from(new Set(input.containerIds))\n .sort()\n .map((containerId) => ({\n documentId: input.documentId,\n containerId,\n updatedAt,\n })),\n );\n // A lane page of multi-link documents can carry more link rows than\n // one statement may bind.\n for (let index = 0; index < rows.length; index += LINK_INSERT_BATCH_SIZE) {\n await tx\n .insert(documentContainerProjection)\n .values(rows.slice(index, index + LINK_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\n/** The caller owns the open document commit and must propagate every failure. */\nexport async function replaceDocumentLinksInTransaction(\n transactionExecSql: ExecSql,\n documentId: string,\n containerIds: readonly string[],\n options?: Omit<DocumentPlacementWriteOptions, \"stillCurrent\">,\n): Promise<void> {\n await ensureDocumentLinksSchema(transactionExecSql);\n await replaceDocumentLinkRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n new Map([[documentId, { documentId, containerIds }]]),\n () => new Date(),\n options,\n );\n}\n\n/** The document container projection, bound to one executor and clock. */\nexport class DocumentContainerProjectionRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n async ensureSchema(): Promise<void> {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n }\n\n async listLinkedContainerIds(\n documentId: string,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(eq(documentContainerProjection.documentId, documentId))\n .orderBy(asc(documentContainerProjection.containerId));\n\n return rows.map((row) => row.containerId);\n }\n\n async listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n await this.ensureSchema();\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n documentId: documentContainerProjection.documentId,\n containerId: documentContainerProjection.containerId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, uniqueDocumentIds))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const row of rows) {\n const linkedContainerIds =\n linkedContainerIdsByDocumentId.get(row.documentId) ?? [];\n linkedContainerIds.push(row.containerId);\n linkedContainerIdsByDocumentId.set(row.documentId, linkedContainerIds);\n }\n\n return linkedContainerIdsByDocumentId;\n }\n\n async listDocumentIdsByContainerIds(\n containerIds: ReadonlyArray<string>,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const uniqueContainerIds = Array.from(new Set(containerIds));\n if (uniqueContainerIds.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .selectDistinct({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(\n inArray(documentContainerProjection.containerId, uniqueContainerIds),\n )\n .orderBy(asc(documentContainerProjection.documentId));\n\n return rows.map((row) => row.documentId);\n }\n\n async replaceDocumentLinks(\n documentId: string,\n containerIds: ReadonlyArray<string>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await this.replaceDocumentLinksBatch(\n [{ documentId, containerIds }],\n options,\n );\n }\n\n async replaceDocumentLinksBatch(\n inputs: ReadonlyArray<DocumentPlacementInput>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await ensureDocumentLinksSchema(this.execSql);\n const latest = new Map(inputs.map((input) => [input.documentId, input]));\n if (latest.size === 0) return;\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const replace = (tx: ClientSQLiteTransactionScope) =>\n replaceDocumentLinkRows(tx, latest, this.now, options);\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(replace, options.stillCurrent);\n return;\n }\n await runtime.transaction(replace);\n }\n}\n"]}
1
+ {"version":3,"file":"documentContainerProjectionPersistence.js","sourceRoot":"","sources":["documentContainerProjectionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC9E,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,gDAAgD,EAChD,kDAAkD,EAClD,iDAAiD,EACjD,mBAAmB,GACpB,MAAM,yDAAyD,CAAC;AAEjE,OAAO,EAGL,gCAAgC,GACjC,MAAM,gCAAgC,CAAC;AAExC,MAAM,sBAAsB,GAAG,qBAAqB,CAClD,2BAA2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CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,OAAO,GAAG,CAAC,EAAgC,EAAE,EAAE,CACnD,uBAAuB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QACzD,IAAI,OAAO,EAAE,YAAY,EAAE,CAAC;YAC1B,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC;YAChE,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import { and, asc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport {\n REMOTE_RESET_SQL_BATCH_SIZE,\n remoteResetBatches,\n SQLITE_BOUND_VARIABLE_BUDGET,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n deleteContainerDocumentTombstoneHoldRowsForLinks,\n deleteContainerDocumentTombstoneHoldsForContainers,\n deleteContainerDocumentTombstoneHoldsForDocuments,\n placementPairsMatch,\n} from \"../documents/containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DocumentPlacementInput,\n type DocumentPlacementWriteOptions,\n filterWritableDocumentPlacements,\n} from \"../documents/documentPlacement\";\n\nconst LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n documentContainerProjection,\n);\n\n/** Link rows and their tombstone holds leave together on a remote reset. */\nexport async function deleteDocumentPlacementRowsByContainerIds(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n}\n\nexport async function deleteDocumentPlacementRowsByDocumentIds(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, documentIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);\n}\n\n/**\n * Remove the tombstoned placements and, with each head now verified, every\n * remaining local link row the head does not link: those are listing-seeded\n * rows, and leaving one would keep showing the document in a container the\n * signed link set never named. Rows the head links are kept as they are.\n * Runs inside the Document Store tombstone transaction.\n */\nexport async function deleteContainerDocumentTombstonePlacementRows(\n tx: ClientSQLiteTransactionScope,\n tombstones: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<\n string,\n ReadonlySet<string>\n >,\n): Promise<void> {\n await deleteDocumentPlacementRowsInTransaction(tx, tombstones);\n await deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx,\n verifiedLinkedContainerIdsByDocumentId,\n );\n}\n\n/** Removes the listed (document, container) placements, 50 pairs per statement. */\nasync function deleteDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n): Promise<void> {\n for (const batch of remoteResetBatches(placements)) {\n await tx\n .delete(documentContainerProjection)\n .where(\n placementPairsMatch(\n batch,\n documentContainerProjection.documentId,\n documentContainerProjection.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * Removes each document's placements outside the containers its head links,\n * batching documents so one statement stays inside SQLite's bind budget.\n */\nasync function deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>,\n): Promise<void> {\n let batch: SQL[] = [];\n let binds = 0;\n const flush = async () => {\n if (batch.length === 0) return;\n await tx\n .delete(documentContainerProjection)\n .where(or(...batch))\n .run();\n batch = [];\n binds = 0;\n };\n for (const [documentId, linked] of linkedContainerIdsByDocumentId) {\n // The document id plus one bind per linked container.\n const documentBinds = 1 + linked.size;\n if (\n batch.length >= REMOTE_RESET_SQL_BATCH_SIZE ||\n binds + documentBinds > SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await flush();\n }\n batch.push(unlinkedDocumentPlacementRows(documentId, linked));\n binds += documentBinds;\n }\n await flush();\n}\n\n/** A document's placements outside the containers its head links. */\nfunction unlinkedDocumentPlacementRows(\n documentId: string,\n linkedContainerIds: ReadonlySet<string>,\n): SQL {\n const ofDocument = eq(documentContainerProjection.documentId, documentId);\n return linkedContainerIds.size === 0\n ? ofDocument\n : (and(\n ofDocument,\n notInArray(documentContainerProjection.containerId, [\n ...linkedContainerIds,\n ]),\n ) ?? ofDocument);\n}\n\n/** Removes a deleted document's queued placement intents and link targets. */\nexport async function deleteDocumentPlacementIntentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<void> {\n const placementIntent = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntent),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntent).run();\n}\n\nasync function ensureDocumentLinksSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentTables,\n ]);\n}\n\nasync function replaceDocumentLinkRows(\n tx: ClientSQLiteTransactionScope,\n latest: ReadonlyMap<string, DocumentPlacementInput>,\n now: () => Date,\n options?: DocumentPlacementWriteOptions,\n): Promise<void> {\n const writable = await filterWritableDocumentPlacements(\n tx,\n [...latest.values()],\n options,\n );\n if (writable.length === 0) return;\n // A placement the writer re-asserts is no longer tombstoned: a\n // listing that links it again, or a local move that owns it, releases\n // the hold so the document is not hidden until the next retry.\n if (options?.moveIntentId) {\n await deleteContainerDocumentTombstoneHoldsForDocuments(\n tx,\n writable.map((input) => input.documentId),\n );\n } else {\n await deleteContainerDocumentTombstoneHoldRowsForLinks(tx, writable);\n }\n // Each document binds once; finish every deletion before inserting.\n for (\n let index = 0;\n index < writable.length;\n index += SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await tx\n .delete(documentContainerProjection)\n .where(\n inArray(\n documentContainerProjection.documentId,\n writable\n .slice(index, index + SQLITE_BOUND_VARIABLE_BUDGET)\n .map((input) => input.documentId),\n ),\n )\n .run();\n }\n const updatedAt = now().toISOString();\n const rows = writable.flatMap((input) =>\n Array.from(new Set(input.containerIds))\n .sort()\n .map((containerId) => ({\n documentId: input.documentId,\n containerId,\n updatedAt,\n })),\n );\n // A lane page of multi-link documents can carry more link rows than\n // one statement may bind.\n for (let index = 0; index < rows.length; index += LINK_INSERT_BATCH_SIZE) {\n await tx\n .insert(documentContainerProjection)\n .values(rows.slice(index, index + LINK_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\n/** The caller owns the open document commit and must propagate every failure. */\nexport async function replaceDocumentLinksInTransaction(\n transactionExecSql: ExecSql,\n documentId: string,\n containerIds: readonly string[],\n options?: Omit<DocumentPlacementWriteOptions, \"stillCurrent\">,\n): Promise<void> {\n await ensureDocumentLinksSchema(transactionExecSql);\n await replaceDocumentLinkRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n new Map([[documentId, { documentId, containerIds }]]),\n () => new Date(),\n options,\n );\n}\n\n/** The document container projection, bound to one executor and clock. */\nexport class DocumentContainerProjectionRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n async ensureSchema(): Promise<void> {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n }\n\n async listLinkedContainerIds(\n documentId: string,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(eq(documentContainerProjection.documentId, documentId))\n .orderBy(asc(documentContainerProjection.containerId));\n\n return rows.map((row) => row.containerId);\n }\n\n async listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n await this.ensureSchema();\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n documentId: documentContainerProjection.documentId,\n containerId: documentContainerProjection.containerId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, uniqueDocumentIds))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const row of rows) {\n const linkedContainerIds =\n linkedContainerIdsByDocumentId.get(row.documentId) ?? [];\n linkedContainerIds.push(row.containerId);\n linkedContainerIdsByDocumentId.set(row.documentId, linkedContainerIds);\n }\n\n return linkedContainerIdsByDocumentId;\n }\n\n async listDocumentIdsByContainerIds(\n containerIds: ReadonlyArray<string>,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const uniqueContainerIds = Array.from(new Set(containerIds));\n if (uniqueContainerIds.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .selectDistinct({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(\n inArray(documentContainerProjection.containerId, uniqueContainerIds),\n )\n .orderBy(asc(documentContainerProjection.documentId));\n\n return rows.map((row) => row.documentId);\n }\n\n async replaceDocumentLinks(\n documentId: string,\n containerIds: ReadonlyArray<string>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await this.replaceDocumentLinksBatch(\n [{ documentId, containerIds }],\n options,\n );\n }\n\n async replaceDocumentLinksBatch(\n inputs: ReadonlyArray<DocumentPlacementInput>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await ensureDocumentLinksSchema(this.execSql);\n const latest = new Map(inputs.map((input) => [input.documentId, input]));\n if (latest.size === 0) return;\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const replace = (tx: ClientSQLiteTransactionScope) =>\n replaceDocumentLinkRows(tx, latest, this.now, options);\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(replace, options.stillCurrent);\n return;\n }\n await runtime.transaction(replace);\n }\n}\n"]}
@@ -1,11 +1,12 @@
1
1
  import { type DiscoveredDocumentInput, type DocumentSummary } from "../../documents/documentSummary.js";
2
2
  import { type ExecSql } from "../../sqlite/sqlSchema.js";
3
+ import { type ContainerDocumentTombstonePlacementRemoval } from "./internal/containerDocumentTombstones.js";
3
4
  import type { ContainerDocumentTombstoneInput, DocumentsPersistence } from "./types.js";
4
5
  export { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
5
6
  export type { PendingUpdateRecord, QueuedPendingUpdateRecord } from "./records/index.js";
6
7
  export type { AttachmentRemovalRows, AttachmentStagingRows, ContainerDocumentTombstoneInput, DiscardDocumentToShellResult, DocumentsPersistence, LocalAttachmentRecord, PendingAttachmentRecord, PendingAttachmentUploadIdentity, PendingUpdateInsert, RelinkPersistedDocumentInput, StoredDocumentRecord, } from "./types.js";
7
8
  export declare function upsertDiscoveredDocuments(execSql: ExecSql, inputs: ReadonlyArray<DiscoveredDocumentInput>): Promise<DocumentSummary[]>;
8
- export declare function applyContainerDocumentTombstones(execSql: ExecSql, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>): Promise<DocumentSummary[]>;
9
+ export declare function applyContainerDocumentTombstones(execSql: ExecSql, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>, removePlacementRows: ContainerDocumentTombstonePlacementRemoval): Promise<DocumentSummary[]>;
9
10
  export declare function listDocumentsByContainerIdsOrDocumentIds(execSql: ExecSql, input: {
10
11
  containerIds: ReadonlyArray<string>;
11
12
  documentIds: ReadonlyArray<string>;
@@ -4,7 +4,7 @@ import { documentProjection } from "../../sqlite/schema/documentProjectionSchema
4
4
  import { documents } from "../../sqlite/schema/documentRecordSchema.js";
5
5
  import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
6
6
  import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
7
- import { applyContainerDocumentTombstonesWithExec } from "./internal/containerDocumentTombstones.js";
7
+ import { applyContainerDocumentTombstonesWithExec, } from "./internal/containerDocumentTombstones.js";
8
8
  import { createStoredDocumentWithHistoryCheckpoint } from "./internal/createDocumentWithHistoryCheckpoint.js";
9
9
  import { discardStoredDocumentToShell } from "./internal/discardDocument.js";
10
10
  import { upsertDiscoveredDocumentsInTransaction } from "./internal/discoveredDocumentUpsert.js";
@@ -64,10 +64,10 @@ export async function upsertDiscoveredDocuments(execSql, inputs) {
64
64
  }, { behavior: "immediate" });
65
65
  });
66
66
  }
67
- export async function applyContainerDocumentTombstones(execSql, tombstones) {
67
+ export async function applyContainerDocumentTombstones(execSql, tombstones, removePlacementRows) {
68
68
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
69
69
  await sqlDocumentsPersistence.ensureSchema(lockedExecSql);
70
- return applyContainerDocumentTombstonesWithExec(lockedExecSql, tombstones);
70
+ return applyContainerDocumentTombstonesWithExec(lockedExecSql, tombstones, removePlacementRows);
71
71
  });
72
72
  }
73
73
  export async function listDocumentsByContainerIdsOrDocumentIds(execSql, input) {
@@ -1 +1 @@
1
- {"version":3,"file":"documentsPersistence.js","sourceRoot":"","sources":["documentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC/E,OAAO,EAGL,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAC;AAClF,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAClG,OAAO,EAAE,yCAAyC,EAAE,MAAM,gDAAgD,CAAC;AAC3G,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EACL,oBAAoB,EACpB,6BAA6B,EAC7B,oCAAoC,GACrC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yCAAyC,EAAE,MAAM,4CAA4C,CAAC;AACvG,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,GACnC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,wCAAwC,EAAE,MAAM,gDAAgD,CAAC;AAC1G,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,GACrC,MAAM,iCAAiC,CA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AC;YACF,OAAO,SAAS,CAAC;QACnB,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;IACJ,CAAC;IACD,cAAc,EAAE,oBAAoB;IACpC,uBAAuB,EAAE,6BAA6B;IACtD,8BAA8B,EAAE,oCAAoC;IACpE,KAAK,CAAC,sBAAsB,CAC1B,OAAO,EACP,OAAO,EACP,kBAAkB,EAClB,kBAAkB;QAElB,OAAO,4BAA4B,CAAC;YAClC,kBAAkB;YAClB,OAAO;YACP,kBAAkB;YAClB,OAAO;YACP,WAAW,EAAE,uBAAuB;SACrC,CAAC,CAAC;IACL,CAAC;IACD,KAAK,CAAC,wBAAwB,CAAC,OAAO,EAAE,KAAK;QAC3C,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,yBAAyB,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QACxE,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC1D,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,KAAK,CAAC,uBAAuB,CAAC,OAAO,EAAE,KAAK;QAC1C,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC/D,MAAM,uBAAuB,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;YAC1D,OAAO,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,GAAG,EAAE,CAAC,+BAA+B,CAAC,aAAa,EAAE,KAAK,CAAC,EAC3D,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n type DiscoveredDocumentInput,\n type DocumentSummary,\n HIDDEN_DOCUMENT_SUMMARY_KINDS,\n} from \"../../documents/documentSummary\";\nimport { documentProjection } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { applyContainerDocumentTombstonesWithExec } from \"./internal/containerDocumentTombstones\";\nimport { createStoredDocumentWithHistoryCheckpoint } from \"./internal/createDocumentWithHistoryCheckpoint\";\nimport { discardStoredDocumentToShell } from \"./internal/discardDocument\";\nimport { upsertDiscoveredDocumentsInTransaction } from \"./internal/discoveredDocumentUpsert\";\nimport {\n deleteStoredDocument,\n deleteStoredDocumentIfMatches,\n deleteStoredDocumentSideRowsIfAbsent,\n} from \"./internal/documentDeletionPersistence\";\nimport { loadStoredDocumentWithHistoryRestoreState } from \"./internal/documentHistoryStatePersistence\";\nimport {\n commitStoredDocumentMutation,\n settleStoredDocumentPendingUpdates,\n} from \"./internal/documentMutationPersistence\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionUpdatedAt,\n mapDocumentSummary,\n toDocumentSummary,\n} from \"./internal/documentProjectionRows\";\nimport { invalidateStoredDocumentPullContinuation } from \"./internal/documentPullContinuationPersistence\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./internal/documentRows\";\nimport {\n resolvePersistedAccessStateHash,\n resolvePersistedDocumentRuntimeState,\n} from \"./internal/documentRuntimeState\";\nimport { loadStoredDocumentStoreState } from \"./internal/documentStoreStatePersistence\";\nimport { listDocumentSummaries } from \"./internal/documentSummaryQueries\";\nimport { ensureDocumentsSchema } from \"./internal/ensureDocumentsSchema\";\nimport { saveHydratedAttachment } from \"./internal/hydratedAttachmentPersistence\";\nimport {\n acknowledgeDocumentOrphanBlobReclaim,\n deleteOrphanedDocumentSideRows,\n isDocumentBlobStorageKeyReferenced,\n listDocumentOrphanBlobReclaims,\n} from \"./internal/orphanSideRows\";\nimport { mapPendingCreateLocalIds } from \"./internal/pendingCreateAdoption\";\nimport { documentRowQueryPersistence } from \"./internal/rowQueryPersistence\";\nimport { documentSyncQueuePersistence } from \"./internal/syncQueuePersistence\";\nimport { settleQueuedDocumentUpdatesInTransaction } from \"./records/documentPendingUpdatePersistence\";\nimport type {\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nexport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nexport type { PendingUpdateRecord, QueuedPendingUpdateRecord } from \"./records\";\nexport type {\n AttachmentRemovalRows,\n AttachmentStagingRows,\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingAttachmentUploadIdentity,\n PendingUpdateInsert,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nasync function relinkPersistedDocumentWithExec(\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n): Promise<DocumentSummary | null> {\n const existingDocument = await sqlDocumentsPersistence.loadDocument(\n execSql,\n input.localId,\n );\n if (!existingDocument) {\n return null;\n }\n\n const nextAccessEpoch = Math.max(\n existingDocument.accessEpoch,\n input.accessEpoch,\n );\n const nextDocument: StoredDocumentRecord = {\n ...existingDocument,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolvePersistedAccessStateHash(existingDocument, {\n accessEpoch: nextAccessEpoch,\n accessStateHash: input.accessStateHash,\n documentId: input.documentId,\n }),\n containerId: input.containerId,\n documentId: input.documentId,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: nextAccessEpoch,\n documentId: input.documentId,\n }),\n };\n\n await sqlDocumentsPersistence.saveDocument(execSql, nextDocument);\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const updatedAtRows = await db\n .select({ updatedAt: documentProjection.updatedAt })\n .from(documentProjection)\n .where(eq(documentProjection.localId, input.localId))\n .limit(1);\n\n return toDocumentSummary(\n nextDocument,\n getProjectionUpdatedAt(updatedAtRows[0]),\n );\n}\n\nexport async function upsertDiscoveredDocuments(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const pendingCreates = await mapPendingCreateLocalIds(lockedExecSql);\n return upsertDiscoveredDocumentsInTransaction(\n lockedExecSql,\n inputs,\n pendingCreates,\n tx,\n );\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function applyContainerDocumentTombstones(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return applyContainerDocumentTombstonesWithExec(lockedExecSql, tombstones);\n });\n}\n\nexport async function listDocumentsByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n): Promise<DocumentSummary[]> {\n const uniqueContainerIds = Array.from(new Set(input.containerIds));\n const uniqueDocumentIds = Array.from(new Set(input.documentIds));\n if (uniqueContainerIds.length === 0 && uniqueDocumentIds.length === 0) {\n return [];\n }\n\n const filters: SQL[] = [];\n if (uniqueContainerIds.length > 0) {\n filters.push(inArray(documentProjection.containerId, uniqueContainerIds));\n }\n\n if (uniqueDocumentIds.length > 0) {\n filters.push(inArray(documentProjection.documentId, uniqueDocumentIds));\n }\n\n const whereCondition = filters.length === 1 ? filters[0] : or(...filters);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n and(\n whereCondition,\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n}\n\nexport const sqlDocumentsPersistence: DocumentsPersistence = {\n orphanBlobs: {\n acknowledge: acknowledgeDocumentOrphanBlobReclaim,\n isReferenced: isDocumentBlobStorageKeyReferenced,\n list: listDocumentOrphanBlobReclaims,\n sweep: deleteOrphanedDocumentSideRows,\n },\n ...documentRowQueryPersistence,\n ...documentSyncQueuePersistence,\n supportsAtomicRecoveryHistoryPruning: true,\n saveHydratedAttachment,\n createDocumentWithHistoryCheckpoint:\n createStoredDocumentWithHistoryCheckpoint,\n commitDocumentMutation: (execSql, input, saveClientProjection) =>\n commitStoredDocumentMutation(\n execSql,\n input,\n saveClientProjection,\n sqlDocumentsPersistence.loadDocument,\n ),\n settleAcceptedPendingUpdates: (execSql, input) =>\n settleStoredDocumentPendingUpdates(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n ),\n ensureSchema: ensureDocumentsSchema,\n listDocumentSummaries,\n listDocumentsByContainerIdsOrDocumentIds,\n invalidatePullContinuation: (execSql, input) =>\n invalidateStoredDocumentPullContinuation(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n sqlDocumentsPersistence.loadHistoryRestoreState,\n ),\n loadDocumentWithHistoryRestoreState: (execSql, localId) =>\n loadStoredDocumentWithHistoryRestoreState(\n execSql,\n localId,\n sqlDocumentsPersistence,\n ),\n loadDocumentStoreState: (execSql, localId) =>\n loadStoredDocumentStoreState(execSql, localId, sqlDocumentsPersistence),\n async saveDocument(execSql, document, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n async saveDocumentAndDeletePendingUpdates(\n execSql,\n document,\n pendingUpdateIds,\n options,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n const saved = await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n if (!saved) return updatedAt;\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getDocumentScope(document.id),\n pendingUpdateIds,\n );\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n deleteDocument: deleteStoredDocument,\n deleteDocumentIfMatches: deleteStoredDocumentIfMatches,\n deleteDocumentSideRowsIfAbsent: deleteStoredDocumentSideRowsIfAbsent,\n async discardDocumentToShell(\n execSql,\n localId,\n expectedDocumentId,\n documentProjectors,\n ): Promise<DiscardDocumentToShellResult> {\n return discardStoredDocumentToShell({\n documentProjectors,\n execSql,\n expectedDocumentId,\n localId,\n persistence: sqlDocumentsPersistence,\n });\n },\n async upsertDiscoveredDocument(execSql, input) {\n const [nextSummary] = await upsertDiscoveredDocuments(execSql, [input]);\n if (!nextSummary) {\n throw new Error(\"Failed to upsert discovered document\");\n }\n\n return nextSummary;\n },\n async relinkPersistedDocument(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n () => relinkPersistedDocumentWithExec(lockedExecSql, input),\n { behavior: \"immediate\" },\n );\n });\n },\n};\n"]}
1
+ {"version":3,"file":"documentsPersistence.js","sourceRoot":"","sources":["documentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CA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sBAAsB,CAC1B,OAAO,EACP,OAAO,EACP,kBAAkB,EAClB,kBAAkB;QAElB,OAAO,4BAA4B,CAAC;YAClC,kBAAkB;YAClB,OAAO;YACP,kBAAkB;YAClB,OAAO;YACP,WAAW,EAAE,uBAAuB;SACrC,CAAC,CAAC;IACL,CAAC;IACD,KAAK,CAAC,wBAAwB,CAAC,OAAO,EAAE,KAAK;QAC3C,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,yBAAyB,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QACxE,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC1D,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,KAAK,CAAC,uBAAuB,CAAC,OAAO,EAAE,KAAK;QAC1C,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC/D,MAAM,uBAAuB,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;YAC1D,OAAO,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,GAAG,EAAE,CAAC,+BAA+B,CAAC,aAAa,EAAE,KAAK,CAAC,EAC3D,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n type DiscoveredDocumentInput,\n type DocumentSummary,\n HIDDEN_DOCUMENT_SUMMARY_KINDS,\n} from \"../../documents/documentSummary\";\nimport { documentProjection } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n applyContainerDocumentTombstonesWithExec,\n type ContainerDocumentTombstonePlacementRemoval,\n} from \"./internal/containerDocumentTombstones\";\nimport { createStoredDocumentWithHistoryCheckpoint } from \"./internal/createDocumentWithHistoryCheckpoint\";\nimport { discardStoredDocumentToShell } from \"./internal/discardDocument\";\nimport { upsertDiscoveredDocumentsInTransaction } from \"./internal/discoveredDocumentUpsert\";\nimport {\n deleteStoredDocument,\n deleteStoredDocumentIfMatches,\n deleteStoredDocumentSideRowsIfAbsent,\n} from \"./internal/documentDeletionPersistence\";\nimport { loadStoredDocumentWithHistoryRestoreState } from \"./internal/documentHistoryStatePersistence\";\nimport {\n commitStoredDocumentMutation,\n settleStoredDocumentPendingUpdates,\n} from \"./internal/documentMutationPersistence\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionUpdatedAt,\n mapDocumentSummary,\n toDocumentSummary,\n} from \"./internal/documentProjectionRows\";\nimport { invalidateStoredDocumentPullContinuation } from \"./internal/documentPullContinuationPersistence\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./internal/documentRows\";\nimport {\n resolvePersistedAccessStateHash,\n resolvePersistedDocumentRuntimeState,\n} from \"./internal/documentRuntimeState\";\nimport { loadStoredDocumentStoreState } from \"./internal/documentStoreStatePersistence\";\nimport { listDocumentSummaries } from \"./internal/documentSummaryQueries\";\nimport { ensureDocumentsSchema } from \"./internal/ensureDocumentsSchema\";\nimport { saveHydratedAttachment } from \"./internal/hydratedAttachmentPersistence\";\nimport {\n acknowledgeDocumentOrphanBlobReclaim,\n deleteOrphanedDocumentSideRows,\n isDocumentBlobStorageKeyReferenced,\n listDocumentOrphanBlobReclaims,\n} from \"./internal/orphanSideRows\";\nimport { mapPendingCreateLocalIds } from \"./internal/pendingCreateAdoption\";\nimport { documentRowQueryPersistence } from \"./internal/rowQueryPersistence\";\nimport { documentSyncQueuePersistence } from \"./internal/syncQueuePersistence\";\nimport { settleQueuedDocumentUpdatesInTransaction } from \"./records/documentPendingUpdatePersistence\";\nimport type {\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nexport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nexport type { PendingUpdateRecord, QueuedPendingUpdateRecord } from \"./records\";\nexport type {\n AttachmentRemovalRows,\n AttachmentStagingRows,\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingAttachmentUploadIdentity,\n PendingUpdateInsert,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nasync function relinkPersistedDocumentWithExec(\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n): Promise<DocumentSummary | null> {\n const existingDocument = await sqlDocumentsPersistence.loadDocument(\n execSql,\n input.localId,\n );\n if (!existingDocument) {\n return null;\n }\n\n const nextAccessEpoch = Math.max(\n existingDocument.accessEpoch,\n input.accessEpoch,\n );\n const nextDocument: StoredDocumentRecord = {\n ...existingDocument,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolvePersistedAccessStateHash(existingDocument, {\n accessEpoch: nextAccessEpoch,\n accessStateHash: input.accessStateHash,\n documentId: input.documentId,\n }),\n containerId: input.containerId,\n documentId: input.documentId,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: nextAccessEpoch,\n documentId: input.documentId,\n }),\n };\n\n await sqlDocumentsPersistence.saveDocument(execSql, nextDocument);\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const updatedAtRows = await db\n .select({ updatedAt: documentProjection.updatedAt })\n .from(documentProjection)\n .where(eq(documentProjection.localId, input.localId))\n .limit(1);\n\n return toDocumentSummary(\n nextDocument,\n getProjectionUpdatedAt(updatedAtRows[0]),\n );\n}\n\nexport async function upsertDiscoveredDocuments(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const pendingCreates = await mapPendingCreateLocalIds(lockedExecSql);\n return upsertDiscoveredDocumentsInTransaction(\n lockedExecSql,\n inputs,\n pendingCreates,\n tx,\n );\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function applyContainerDocumentTombstones(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n removePlacementRows: ContainerDocumentTombstonePlacementRemoval,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return applyContainerDocumentTombstonesWithExec(\n lockedExecSql,\n tombstones,\n removePlacementRows,\n );\n });\n}\n\nexport async function listDocumentsByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n): Promise<DocumentSummary[]> {\n const uniqueContainerIds = Array.from(new Set(input.containerIds));\n const uniqueDocumentIds = Array.from(new Set(input.documentIds));\n if (uniqueContainerIds.length === 0 && uniqueDocumentIds.length === 0) {\n return [];\n }\n\n const filters: SQL[] = [];\n if (uniqueContainerIds.length > 0) {\n filters.push(inArray(documentProjection.containerId, uniqueContainerIds));\n }\n\n if (uniqueDocumentIds.length > 0) {\n filters.push(inArray(documentProjection.documentId, uniqueDocumentIds));\n }\n\n const whereCondition = filters.length === 1 ? filters[0] : or(...filters);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n and(\n whereCondition,\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n}\n\nexport const sqlDocumentsPersistence: DocumentsPersistence = {\n orphanBlobs: {\n acknowledge: acknowledgeDocumentOrphanBlobReclaim,\n isReferenced: isDocumentBlobStorageKeyReferenced,\n list: listDocumentOrphanBlobReclaims,\n sweep: deleteOrphanedDocumentSideRows,\n },\n ...documentRowQueryPersistence,\n ...documentSyncQueuePersistence,\n supportsAtomicRecoveryHistoryPruning: true,\n saveHydratedAttachment,\n createDocumentWithHistoryCheckpoint:\n createStoredDocumentWithHistoryCheckpoint,\n commitDocumentMutation: (execSql, input, saveClientProjection) =>\n commitStoredDocumentMutation(\n execSql,\n input,\n saveClientProjection,\n sqlDocumentsPersistence.loadDocument,\n ),\n settleAcceptedPendingUpdates: (execSql, input) =>\n settleStoredDocumentPendingUpdates(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n ),\n ensureSchema: ensureDocumentsSchema,\n listDocumentSummaries,\n listDocumentsByContainerIdsOrDocumentIds,\n invalidatePullContinuation: (execSql, input) =>\n invalidateStoredDocumentPullContinuation(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n sqlDocumentsPersistence.loadHistoryRestoreState,\n ),\n loadDocumentWithHistoryRestoreState: (execSql, localId) =>\n loadStoredDocumentWithHistoryRestoreState(\n execSql,\n localId,\n sqlDocumentsPersistence,\n ),\n loadDocumentStoreState: (execSql, localId) =>\n loadStoredDocumentStoreState(execSql, localId, sqlDocumentsPersistence),\n async saveDocument(execSql, document, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n async saveDocumentAndDeletePendingUpdates(\n execSql,\n document,\n pendingUpdateIds,\n options,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n const saved = await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n if (!saved) return updatedAt;\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getDocumentScope(document.id),\n pendingUpdateIds,\n );\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n deleteDocument: deleteStoredDocument,\n deleteDocumentIfMatches: deleteStoredDocumentIfMatches,\n deleteDocumentSideRowsIfAbsent: deleteStoredDocumentSideRowsIfAbsent,\n async discardDocumentToShell(\n execSql,\n localId,\n expectedDocumentId,\n documentProjectors,\n ): Promise<DiscardDocumentToShellResult> {\n return discardStoredDocumentToShell({\n documentProjectors,\n execSql,\n expectedDocumentId,\n localId,\n persistence: sqlDocumentsPersistence,\n });\n },\n async upsertDiscoveredDocument(execSql, input) {\n const [nextSummary] = await upsertDiscoveredDocuments(execSql, [input]);\n if (!nextSummary) {\n throw new Error(\"Failed to upsert discovered document\");\n }\n\n return nextSummary;\n },\n async relinkPersistedDocument(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n () => relinkPersistedDocumentWithExec(lockedExecSql, input),\n { behavior: \"immediate\" },\n );\n });\n },\n};\n"]}
@@ -2,7 +2,7 @@ import { and, asc, eq, inArray, or, sql } from "drizzle-orm";
2
2
  import { containerDocumentTombstoneHolds } from "../../../sqlite/schema/index.js";
3
3
  import { documentContainerProjection, documentProjection, } from "../../../sqlite/schema/documentProjectionSchema.js";
4
4
  import { remoteResetBatches, sqliteRowsPerStatement, } from "../../../sqlite/sqliteBindBudget.js";
5
- import { filterWritableDocumentPlacements } from "../../container-contents/documentPlacement.js";
5
+ import { filterWritableDocumentPlacements } from "../documentPlacement.js";
6
6
  /** Keep `IN (...)` lists well under SQLite's bound-parameter limit. */
7
7
  const HOLD_SQL_ID_BATCH_SIZE = 400;
8
8
  function batches(values) {
@@ -1 +1 @@
1
- {"version":3,"file":"containerDocumentTombstoneHolds.js","sourceRoot":"","sources":["containerDocumentTombstoneHolds.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAY,GAAG,EAAE,MAAM,aAAa,CAAC;AAEvE,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,GACnB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAkB9F,uEAAuE;AACvE,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAEnC,SAAS,OAAO,CAAI,MAAwB;IAC1C,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IAC3C,MAAM,MAAM,GAAU,EAAE,CAAC;IACzB,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,IAAI,sBAAsB,EAAE,CAAC;QAC3E,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,sBAAsB,CAAC,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,SAAwC;IAExC,OAAO,GAAG,SAAS,CAAC,UAAU,SAAS,SAAS,CAAC,WAAW,EAAE,CAAC;AACjE,CAAC;AACD,MAAM,YAAY,GAAG,6BAA6B,CAAC;AAEnD;;;;GAIG;A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, type SQL, sql } from \"drizzle-orm\";\nimport type { SQLiteColumn } from \"drizzle-orm/sqlite-core\";\nimport { containerDocumentTombstoneHolds } from \"../../../sqlite/schema\";\nimport {\n documentContainerProjection,\n documentProjection,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport {\n remoteResetBatches,\n sqliteRowsPerStatement,\n} from \"../../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { filterWritableDocumentPlacements } from \"../../container-contents/documentPlacement\";\nimport type { ContainerDocumentTombstoneInput } from \"../types\";\n\nexport interface ContainerDocumentPlacementKey {\n readonly containerId: string;\n readonly documentId: string;\n}\n\nexport type HeldContainerDocumentTombstone = Omit<\n ContainerDocumentTombstoneInput,\n \"accessEpoch\" | \"linkedContainerIds\"\n> & {\n /** Held without a verification attempt; the backoff does not advance. */\n readonly deferred?: boolean | undefined;\n /** A verified head still links it; retry the tombstone while keeping it visible. */\n readonly refuted?: boolean | undefined;\n};\n\n/** Keep `IN (...)` lists well under SQLite's bound-parameter limit. */\nconst HOLD_SQL_ID_BATCH_SIZE = 400;\n\nfunction batches<T>(values: ReadonlyArray<T>): T[][] {\n const unique = Array.from(new Set(values));\n const result: T[][] = [];\n for (let index = 0; index < unique.length; index += HOLD_SQL_ID_BATCH_SIZE) {\n result.push(unique.slice(index, index + HOLD_SQL_ID_BATCH_SIZE));\n }\n return result;\n}\n\nexport function containerDocumentPlacementKey(\n placement: ContainerDocumentPlacementKey,\n): string {\n return `${placement.documentId}\\u0000${placement.containerId}`;\n}\nconst placementKey = containerDocumentPlacementKey;\n\n/**\n * Matches the listed (document, container) placements by primary key. An\n * empty list matches nothing: `or()` of no terms is no condition at all, and\n * a delete filtered by it would remove every row.\n */\nexport function placementPairsMatch(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n documentIdColumn: SQLiteColumn,\n containerIdColumn: SQLiteColumn,\n): SQL {\n return (\n or(\n ...placements.map((placement) =>\n and(\n eq(documentIdColumn, placement.documentId),\n eq(containerIdColumn, placement.containerId),\n ),\n ),\n ) ?? sql`0`\n );\n}\n\nfunction uniquePlacements(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): ContainerDocumentPlacementKey[] {\n return Array.from(\n new Map(\n placements.map((placement) => [placementKey(placement), placement]),\n ).values(),\n );\n}\n\nexport async function deleteContainerDocumentTombstoneHoldRows(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<void> {\n for (const batch of remoteResetBatches(uniquePlacements(placements))) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(\n placementPairsMatch(\n batch,\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * A local move takes ownership of a document's placement: the intent, not a\n * server listing, now says where it lives, so every hold that was hiding one\n * of its placements is released with the link rewrite.\n */\nexport async function deleteContainerDocumentTombstoneHoldsForDocuments(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(documentIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.documentId, batch))\n .run();\n }\n}\n\n/** Holds on containers whose link rows are being removed locally. */\nexport async function deleteContainerDocumentTombstoneHoldsForContainers(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(containerIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .run();\n }\n}\n\n/**\n * The placements among `placements` that exist locally: a link row, or a\n * document projection row whose primary container is the named container.\n * A tombstone for any other placement has nothing to remove or hide, so it\n * is not worth fetching and verifying the document head for.\n */\nexport async function listKnownContainerDocumentPlacementsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<ContainerDocumentPlacementKey[]> {\n const known = new Set<string>();\n for (const batch of batches(placements.map((entry) => entry.documentId))) {\n const [linkRows, projectionRows] = await Promise.all([\n tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch)),\n tx\n .select({\n containerId: documentProjection.containerId,\n documentId: documentProjection.documentId,\n })\n .from(documentProjection)\n .where(inArray(documentProjection.documentId, batch)),\n ]);\n for (const row of [...linkRows, ...projectionRows]) {\n if (row.documentId !== null && row.containerId !== null) {\n known.add(\n placementKey({\n containerId: row.containerId,\n documentId: row.documentId,\n }),\n );\n }\n }\n }\n return placements.filter((placement) => known.has(placementKey(placement)));\n}\n\n// Preserve input order when one placement occurs in both attempt modes.\n// A deferred conflict changes only tombstonedAt, never recency or attempts.\nfunction* holdWriteBatches(\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n) {\n const size = sqliteRowsPerStatement(6);\n let batch: HeldContainerDocumentTombstone[] = [];\n for (const tombstone of tombstones) {\n if (\n batch.length &&\n (batch.length === size ||\n Boolean(batch[0]?.deferred) !== Boolean(tombstone.deferred))\n ) {\n yield batch;\n batch = [];\n }\n batch.push(tombstone);\n }\n if (batch.length) yield batch;\n}\n\n/**\n * Hold listing tombstones whose signed evidence is unavailable. A placement a\n * pending move intent owns is never held: the intent, not the listing, decides\n * where the document lives until it settles (`ProtectPendingTombstones`).\n */\nexport async function holdContainerDocumentTombstonesInTransaction(\n tx: ClientSQLiteTransactionScope,\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n now: string,\n): Promise<void> {\n const writable = new Set(\n (\n await filterWritableDocumentPlacements(\n tx,\n tombstones.map((tombstone) => ({\n documentId: tombstone.documentId,\n containerIds: [],\n })),\n )\n ).map((input) => input.documentId),\n );\n const applicable = tombstones.filter((tombstone) =>\n writable.has(tombstone.documentId),\n );\n for (const batch of holdWriteBatches(applicable)) {\n const deferred = Boolean(batch[0]?.deferred);\n await tx\n .insert(containerDocumentTombstoneHolds)\n .values(\n batch.map((tombstone) => ({\n containerId: tombstone.containerId,\n documentId: tombstone.documentId,\n tombstonedAt: tombstone.updatedAt,\n hidden: !tombstone.refuted,\n updatedAt: now,\n attempts: deferred ? 0 : 1,\n })),\n )\n .onConflictDoUpdate({\n target: [\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ],\n set: deferred\n ? { tombstonedAt: sql`excluded.tombstoned_at` }\n : {\n tombstonedAt: sql`excluded.tombstoned_at`,\n updatedAt: sql`excluded.updated_at`,\n hidden: sql`min(${containerDocumentTombstoneHolds.hidden}, excluded.hidden)`,\n attempts: sql`${containerDocumentTombstoneHolds.attempts} + 1`,\n },\n })\n .run();\n }\n}\n\n/** Release the holds on placements a listing has re-asserted as linked. */\nexport async function deleteContainerDocumentTombstoneHoldRowsForLinks(\n tx: ClientSQLiteTransactionScope,\n links: ReadonlyArray<{\n readonly containerIds: ReadonlyArray<string>;\n readonly documentId: string;\n }>,\n): Promise<void> {\n await deleteContainerDocumentTombstoneHoldRows(\n tx,\n links.flatMap((link) =>\n link.containerIds.map((containerId) => ({\n containerId,\n documentId: link.documentId,\n })),\n ),\n );\n}\n\nexport interface ContainerDocumentTombstoneHoldRow\n extends ContainerDocumentPlacementKey {\n readonly attempts: number;\n readonly hidden: boolean;\n readonly tombstonedAt: string;\n readonly updatedAt: string;\n}\n\nconst holdRowSelection = {\n attempts: containerDocumentTombstoneHolds.attempts,\n hidden: containerDocumentTombstoneHolds.hidden,\n containerId: containerDocumentTombstoneHolds.containerId,\n documentId: containerDocumentTombstoneHolds.documentId,\n tombstonedAt: containerDocumentTombstoneHolds.tombstonedAt,\n updatedAt: containerDocumentTombstoneHolds.updatedAt,\n};\n\n/** Every hold on the given containers, including visible refuted retries. */\nexport async function listContainerDocumentTombstoneHoldsInTransaction(\n handle: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(containerIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .orderBy(\n asc(containerDocumentTombstoneHolds.containerId),\n asc(containerDocumentTombstoneHolds.documentId),\n )),\n );\n }\n return holds;\n}\n\n/** Every hidden hold on the given documents, in any container. */\nexport async function listContainerDocumentTombstoneHoldsForDocumentsInTransaction(\n handle: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(documentIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(\n and(\n inArray(containerDocumentTombstoneHolds.documentId, batch),\n eq(containerDocumentTombstoneHolds.hidden, true),\n ),\n )\n .orderBy(\n asc(containerDocumentTombstoneHolds.documentId),\n asc(containerDocumentTombstoneHolds.containerId),\n )),\n );\n }\n return holds;\n}\n\n/**\n * Split the holds on the given containers into those whose placement is gone\n * (the document was purged, reset, or relinked locally: nothing left to hide,\n * so the hold is dropped) and those still hiding a placement.\n */\nexport async function partitionContainerDocumentTombstoneHolds(\n handle: ClientSQLiteTransactionScope,\n holds: ReadonlyArray<ContainerDocumentTombstoneHoldRow>,\n): Promise<{\n live: ContainerDocumentTombstoneHoldRow[];\n orphaned: ContainerDocumentTombstoneHoldRow[];\n}> {\n const known = new Set(\n (\n await listKnownContainerDocumentPlacementsInTransaction(handle, holds)\n ).map(placementKey),\n );\n return {\n live: holds.filter((hold) => known.has(placementKey(hold))),\n orphaned: holds.filter((hold) => !known.has(placementKey(hold))),\n };\n}\n"]}
1
+ {"version":3,"file":"containerDocumentTombstoneHolds.js","sourceRoot":"","sources":["containerDocumentTombstoneHolds.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE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AAC;QACzC,KAAK,CAAC,IAAI,CACR,GAAG,CAAC,MAAM,MAAM;aACb,MAAM,CAAC,gBAAgB,CAAC;aACxB,IAAI,CAAC,+BAA+B,CAAC;aACrC,KAAK,CACJ,GAAG,CACD,OAAO,CAAC,+BAA+B,CAAC,UAAU,EAAE,KAAK,CAAC,EAC1D,EAAE,CAAC,+BAA+B,CAAC,MAAM,EAAE,IAAI,CAAC,CACjD,CACF;aACA,OAAO,CACN,GAAG,CAAC,+BAA+B,CAAC,UAAU,CAAC,EAC/C,GAAG,CAAC,+BAA+B,CAAC,WAAW,CAAC,CACjD,CAAC,CACL,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,MAAoC,EACpC,KAAuD;IAKvD,MAAM,KAAK,GAAG,IAAI,GAAG,CACnB,CACE,MAAM,iDAAiD,CAAC,MAAM,EAAE,KAAK,CAAC,CACvE,CAAC,GAAG,CAAC,YAAY,CAAC,CACpB,CAAC;IACF,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3D,QAAQ,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;KACjE,CAAC;AACJ,CAAC","sourcesContent":["import { and, asc, eq, inArray, or, type SQL, sql } from \"drizzle-orm\";\nimport type { SQLiteColumn } from \"drizzle-orm/sqlite-core\";\nimport { containerDocumentTombstoneHolds } from \"../../../sqlite/schema\";\nimport {\n documentContainerProjection,\n documentProjection,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport {\n remoteResetBatches,\n sqliteRowsPerStatement,\n} from \"../../../sqlite/sqliteBindBudget\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { filterWritableDocumentPlacements } from \"../documentPlacement\";\nimport type { ContainerDocumentTombstoneInput } from \"../types\";\n\nexport interface ContainerDocumentPlacementKey {\n readonly containerId: string;\n readonly documentId: string;\n}\n\nexport type HeldContainerDocumentTombstone = Omit<\n ContainerDocumentTombstoneInput,\n \"accessEpoch\" | \"linkedContainerIds\"\n> & {\n /** Held without a verification attempt; the backoff does not advance. */\n readonly deferred?: boolean | undefined;\n /** A verified head still links it; retry the tombstone while keeping it visible. */\n readonly refuted?: boolean | undefined;\n};\n\n/** Keep `IN (...)` lists well under SQLite's bound-parameter limit. */\nconst HOLD_SQL_ID_BATCH_SIZE = 400;\n\nfunction batches<T>(values: ReadonlyArray<T>): T[][] {\n const unique = Array.from(new Set(values));\n const result: T[][] = [];\n for (let index = 0; index < unique.length; index += HOLD_SQL_ID_BATCH_SIZE) {\n result.push(unique.slice(index, index + HOLD_SQL_ID_BATCH_SIZE));\n }\n return result;\n}\n\nexport function containerDocumentPlacementKey(\n placement: ContainerDocumentPlacementKey,\n): string {\n return `${placement.documentId}\\u0000${placement.containerId}`;\n}\nconst placementKey = containerDocumentPlacementKey;\n\n/**\n * Matches the listed (document, container) placements by primary key. An\n * empty list matches nothing: `or()` of no terms is no condition at all, and\n * a delete filtered by it would remove every row.\n */\nexport function placementPairsMatch(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n documentIdColumn: SQLiteColumn,\n containerIdColumn: SQLiteColumn,\n): SQL {\n return (\n or(\n ...placements.map((placement) =>\n and(\n eq(documentIdColumn, placement.documentId),\n eq(containerIdColumn, placement.containerId),\n ),\n ),\n ) ?? sql`0`\n );\n}\n\nfunction uniquePlacements(\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): ContainerDocumentPlacementKey[] {\n return Array.from(\n new Map(\n placements.map((placement) => [placementKey(placement), placement]),\n ).values(),\n );\n}\n\nexport async function deleteContainerDocumentTombstoneHoldRows(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<void> {\n for (const batch of remoteResetBatches(uniquePlacements(placements))) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(\n placementPairsMatch(\n batch,\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * A local move takes ownership of a document's placement: the intent, not a\n * server listing, now says where it lives, so every hold that was hiding one\n * of its placements is released with the link rewrite.\n */\nexport async function deleteContainerDocumentTombstoneHoldsForDocuments(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(documentIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.documentId, batch))\n .run();\n }\n}\n\n/** Holds on containers whose link rows are being removed locally. */\nexport async function deleteContainerDocumentTombstoneHoldsForContainers(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n for (const batch of batches(containerIds)) {\n await tx\n .delete(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .run();\n }\n}\n\n/**\n * The placements among `placements` that exist locally: a link row, or a\n * document projection row whose primary container is the named container.\n * A tombstone for any other placement has nothing to remove or hide, so it\n * is not worth fetching and verifying the document head for.\n */\nexport async function listKnownContainerDocumentPlacementsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<ContainerDocumentPlacementKey>,\n): Promise<ContainerDocumentPlacementKey[]> {\n const known = new Set<string>();\n for (const batch of batches(placements.map((entry) => entry.documentId))) {\n const [linkRows, projectionRows] = await Promise.all([\n tx\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch)),\n tx\n .select({\n containerId: documentProjection.containerId,\n documentId: documentProjection.documentId,\n })\n .from(documentProjection)\n .where(inArray(documentProjection.documentId, batch)),\n ]);\n for (const row of [...linkRows, ...projectionRows]) {\n if (row.documentId !== null && row.containerId !== null) {\n known.add(\n placementKey({\n containerId: row.containerId,\n documentId: row.documentId,\n }),\n );\n }\n }\n }\n return placements.filter((placement) => known.has(placementKey(placement)));\n}\n\n// Preserve input order when one placement occurs in both attempt modes.\n// A deferred conflict changes only tombstonedAt, never recency or attempts.\nfunction* holdWriteBatches(\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n) {\n const size = sqliteRowsPerStatement(6);\n let batch: HeldContainerDocumentTombstone[] = [];\n for (const tombstone of tombstones) {\n if (\n batch.length &&\n (batch.length === size ||\n Boolean(batch[0]?.deferred) !== Boolean(tombstone.deferred))\n ) {\n yield batch;\n batch = [];\n }\n batch.push(tombstone);\n }\n if (batch.length) yield batch;\n}\n\n/**\n * Hold listing tombstones whose signed evidence is unavailable. A placement a\n * pending move intent owns is never held: the intent, not the listing, decides\n * where the document lives until it settles (`ProtectPendingTombstones`).\n */\nexport async function holdContainerDocumentTombstonesInTransaction(\n tx: ClientSQLiteTransactionScope,\n tombstones: ReadonlyArray<HeldContainerDocumentTombstone>,\n now: string,\n): Promise<void> {\n const writable = new Set(\n (\n await filterWritableDocumentPlacements(\n tx,\n tombstones.map((tombstone) => ({\n documentId: tombstone.documentId,\n containerIds: [],\n })),\n )\n ).map((input) => input.documentId),\n );\n const applicable = tombstones.filter((tombstone) =>\n writable.has(tombstone.documentId),\n );\n for (const batch of holdWriteBatches(applicable)) {\n const deferred = Boolean(batch[0]?.deferred);\n await tx\n .insert(containerDocumentTombstoneHolds)\n .values(\n batch.map((tombstone) => ({\n containerId: tombstone.containerId,\n documentId: tombstone.documentId,\n tombstonedAt: tombstone.updatedAt,\n hidden: !tombstone.refuted,\n updatedAt: now,\n attempts: deferred ? 0 : 1,\n })),\n )\n .onConflictDoUpdate({\n target: [\n containerDocumentTombstoneHolds.documentId,\n containerDocumentTombstoneHolds.containerId,\n ],\n set: deferred\n ? { tombstonedAt: sql`excluded.tombstoned_at` }\n : {\n tombstonedAt: sql`excluded.tombstoned_at`,\n updatedAt: sql`excluded.updated_at`,\n hidden: sql`min(${containerDocumentTombstoneHolds.hidden}, excluded.hidden)`,\n attempts: sql`${containerDocumentTombstoneHolds.attempts} + 1`,\n },\n })\n .run();\n }\n}\n\n/** Release the holds on placements a listing has re-asserted as linked. */\nexport async function deleteContainerDocumentTombstoneHoldRowsForLinks(\n tx: ClientSQLiteTransactionScope,\n links: ReadonlyArray<{\n readonly containerIds: ReadonlyArray<string>;\n readonly documentId: string;\n }>,\n): Promise<void> {\n await deleteContainerDocumentTombstoneHoldRows(\n tx,\n links.flatMap((link) =>\n link.containerIds.map((containerId) => ({\n containerId,\n documentId: link.documentId,\n })),\n ),\n );\n}\n\nexport interface ContainerDocumentTombstoneHoldRow\n extends ContainerDocumentPlacementKey {\n readonly attempts: number;\n readonly hidden: boolean;\n readonly tombstonedAt: string;\n readonly updatedAt: string;\n}\n\nconst holdRowSelection = {\n attempts: containerDocumentTombstoneHolds.attempts,\n hidden: containerDocumentTombstoneHolds.hidden,\n containerId: containerDocumentTombstoneHolds.containerId,\n documentId: containerDocumentTombstoneHolds.documentId,\n tombstonedAt: containerDocumentTombstoneHolds.tombstonedAt,\n updatedAt: containerDocumentTombstoneHolds.updatedAt,\n};\n\n/** Every hold on the given containers, including visible refuted retries. */\nexport async function listContainerDocumentTombstoneHoldsInTransaction(\n handle: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(containerIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(inArray(containerDocumentTombstoneHolds.containerId, batch))\n .orderBy(\n asc(containerDocumentTombstoneHolds.containerId),\n asc(containerDocumentTombstoneHolds.documentId),\n )),\n );\n }\n return holds;\n}\n\n/** Every hidden hold on the given documents, in any container. */\nexport async function listContainerDocumentTombstoneHoldsForDocumentsInTransaction(\n handle: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<ContainerDocumentTombstoneHoldRow[]> {\n const holds: ContainerDocumentTombstoneHoldRow[] = [];\n for (const batch of batches(documentIds)) {\n holds.push(\n ...(await handle\n .select(holdRowSelection)\n .from(containerDocumentTombstoneHolds)\n .where(\n and(\n inArray(containerDocumentTombstoneHolds.documentId, batch),\n eq(containerDocumentTombstoneHolds.hidden, true),\n ),\n )\n .orderBy(\n asc(containerDocumentTombstoneHolds.documentId),\n asc(containerDocumentTombstoneHolds.containerId),\n )),\n );\n }\n return holds;\n}\n\n/**\n * Split the holds on the given containers into those whose placement is gone\n * (the document was purged, reset, or relinked locally: nothing left to hide,\n * so the hold is dropped) and those still hiding a placement.\n */\nexport async function partitionContainerDocumentTombstoneHolds(\n handle: ClientSQLiteTransactionScope,\n holds: ReadonlyArray<ContainerDocumentTombstoneHoldRow>,\n): Promise<{\n live: ContainerDocumentTombstoneHoldRow[];\n orphaned: ContainerDocumentTombstoneHoldRow[];\n}> {\n const known = new Set(\n (\n await listKnownContainerDocumentPlacementsInTransaction(handle, holds)\n ).map(placementKey),\n );\n return {\n live: holds.filter((hold) => known.has(placementKey(hold))),\n orphaned: holds.filter((hold) => !known.has(placementKey(hold))),\n };\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import { type ClientSQLiteTransactionScope } from "../../../sqlite/sqlitePersistenceRuntime.js";
2
+ import type { ExecSql } from "../../../sqlite/sqlSchema.js";
3
+ import type { ContainerDocumentTombstoneInput } from "../types.js";
4
+ /**
5
+ * Container Contents owns the link rows: it removes the tombstoned placement
6
+ * and, with the head now verified, every remaining local link row the head
7
+ * does not link, inside the tombstone transaction.
8
+ */
9
+ export type ContainerDocumentTombstonePlacementRemoval = (tx: ClientSQLiteTransactionScope, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>, verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>) => Promise<void>;
10
+ export declare function applyContainerDocumentTombstonesWithExec(execSql: ExecSql, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>, removePlacementRows: ContainerDocumentTombstonePlacementRemoval): Promise<import("../../../documents/index.js").DocumentSummary[]>;