@tearleads/client-sdk 0.1.211 → 0.1.212

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 (63) hide show
  1. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  2. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  3. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
  4. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  5. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +2 -2
  6. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
  7. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -6
  8. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  9. package/data/persistence/documents/internal/discardDocument.js +4 -4
  10. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  11. package/data/persistence/documents/internal/discoveredDocumentUpsert.js +3 -3
  12. package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
  13. package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -8
  14. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  15. package/data/persistence/documents/internal/documentMutationPersistence.js +4 -3
  16. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  17. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +2 -2
  18. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  19. package/data/persistence/documents/internal/rowQueryPersistence.js +3 -3
  20. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  21. package/data/persistence/documents/internal/syncQueuePersistence.js +12 -13
  22. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  23. package/data/persistence/documents/records/documentHistoryPersistence.d.ts +24 -20
  24. package/data/persistence/documents/records/documentHistoryPersistence.js +59 -90
  25. package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -1
  26. package/data/persistence/documents/records/documentPendingUpdatePersistence.d.ts +10 -25
  27. package/data/persistence/documents/records/documentPendingUpdatePersistence.js +19 -79
  28. package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -1
  29. package/data/persistence/documents/records/documentQueuedUpdateReplacement.d.ts +4 -14
  30. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js +27 -42
  31. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js.map +1 -1
  32. package/data/persistence/documents/records/documentRecordPersistence.d.ts +5 -8
  33. package/data/persistence/documents/records/documentRecordPersistence.js +2 -55
  34. package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -1
  35. package/data/persistence/documents/records/documentRecordRepository.d.ts +133 -0
  36. package/data/persistence/documents/records/documentRecordRepository.js +286 -0
  37. package/data/persistence/documents/records/documentRecordRepository.js.map +1 -0
  38. package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +9 -12
  39. package/data/persistence/documents/records/documentSyncFailurePersistence.js +19 -34
  40. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
  41. package/data/persistence/documents/records/index.d.ts +4 -19
  42. package/data/persistence/documents/records/index.js +5 -29
  43. package/data/persistence/documents/records/index.js.map +1 -1
  44. package/package.json +1 -1
  45. package/stores/documents/documentStore/sync/attachmentUploadFailure.js +2 -2
  46. package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
  47. package/stores/documents/documentStore/sync/syncAttachments.js +2 -2
  48. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  49. package/stores/documents/documentStore/sync/syncShared.js +2 -2
  50. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  51. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  52. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  53. package/workflows/container-contents/pendingWrites/index.js +4 -3
  54. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  55. package/workflows/container-contents/recovery/accessRestoration.js +2 -2
  56. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
  57. package/workflows/documents/index.d.ts +1 -1
  58. package/workflows/documents/index.js +1 -1
  59. package/workflows/documents/index.js.map +1 -1
  60. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +3 -2
  61. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
  62. package/workflows/organizations/readModel/listLocalOrganizations.js +2 -2
  63. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
@@ -6,8 +6,7 @@ import { documents } from "../../../sqlite/schema/documentRecordSchema.js";
6
6
  import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
7
7
  import { ensureSqlTables, runSerializedSqlMutation, } from "../../../sqlite/sqlSchema.js";
8
8
  import { deleteDocumentPlacementIntentsInTransaction, deleteDocumentPlacementRowsByDocumentIds, } from "../../container-contents/documentContainerProjectionPersistence.js";
9
- import { clearDocumentSyncFailure, deleteDocumentRecord, loadDocumentRecord, } from "../records/index.js";
10
- import { deleteDocumentHistory } from "../records/documentHistoryPersistence.js";
9
+ import { DocumentRecordRepository } from "../records/index.js";
11
10
  import { sameCanonicalDocumentSecurityIdentity } from "./documentRecordIdentity.js";
12
11
  import { getDocumentScope } from "./documentRows.js";
13
12
  import { queueDocumentAttachmentBlobReclaims } from "./orphanSideRows.js";
@@ -40,9 +39,10 @@ async function deleteStoredDocumentRows(input) {
40
39
  await deleteDocumentPlacementIntentsInTransaction(tx, existingDocumentId);
41
40
  }
42
41
  const scope = getDocumentScope(localId);
43
- await deleteDocumentHistory(lockedExecSql, scope);
44
- await clearDocumentSyncFailure(lockedExecSql, scope);
45
- await deleteDocumentRecord(lockedExecSql, scope);
42
+ const records = new DocumentRecordRepository(lockedExecSql);
43
+ await records.deleteDocumentHistory(scope);
44
+ await records.clearDocumentSyncFailure(scope);
45
+ await records.deleteDocumentRecord(scope);
46
46
  }
47
47
  async function ensureDocumentDeletionTables(execSql) {
48
48
  // Move intents live in the container-contents schema, which document-only
@@ -61,7 +61,7 @@ export async function deleteStoredDocument(execSql, localId) {
61
61
  await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
62
62
  await ensureDocumentDeletionTables(lockedExecSql);
63
63
  await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
64
- const existingDocument = await loadDocumentRecord(lockedExecSql, {
64
+ const existingDocument = await new DocumentRecordRepository(lockedExecSql).loadDocumentRecord({
65
65
  appKind: DOCUMENTS_APP_KIND,
66
66
  localId,
67
67
  });
@@ -78,7 +78,7 @@ export async function deleteStoredDocumentIfMatches(execSql, expectedRecord, del
78
78
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
79
79
  await ensureDocumentDeletionTables(lockedExecSql);
80
80
  return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
81
- const existingDocument = await loadDocumentRecord(lockedExecSql, {
81
+ const existingDocument = await new DocumentRecordRepository(lockedExecSql).loadDocumentRecord({
82
82
  appKind: DOCUMENTS_APP_KIND,
83
83
  localId: expectedRecord.id,
84
84
  });
@@ -116,7 +116,7 @@ export async function deleteStoredDocumentSideRowsIfAbsent(execSql, localId, exp
116
116
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
117
117
  await ensureDocumentDeletionTables(lockedExecSql);
118
118
  return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
119
- const existingDocument = await loadDocumentRecord(lockedExecSql, {
119
+ const existingDocument = await new DocumentRecordRepository(lockedExecSql).loadDocumentRecord({
120
120
  appKind: DOCUMENTS_APP_KIND,
121
121
  localId,
122
122
  });
@@ -1 +1 @@
1
- {"version":3,"file":"documentDeletionPersistence.js","sourceRoot":"","sources":["documentDeletionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EACL,gCAAgC,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CAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,KAAK,EAAE,EAAE,EAAE,EAAE;YACX,MAAM,gBAAgB,GAAG,MAAM,kBAAkB,CAAC,aAAa,EAAE;gBAC/D,OAAO,EAAE,kBAAkB;gBAC3B,OAAO;aACR,CAAC,CAAC;YACH,IAAI,gBAAgB;gBAAE,OAAO,KAAK,CAAC;YACnC,IACE,kBAAkB;gBAClB,CAAC,MAAM,uBAAuB,CAAC;oBAC7B,UAAU,EAAE,kBAAkB;oBAC9B,OAAO;oBACP,EAAE;iBACH,CAAC,CAAC,EACH,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,MAAM,wBAAwB,CAAC;gBAC7B,kBAAkB,EAAE,kBAAkB;gBACtC,OAAO;gBACP,aAAa;gBACb,EAAE;aACH,CAAC,CAAC;YACH,MAAM,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, ne } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n} from \"../../../sqlite/schema\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport {\n deleteDocumentPlacementIntentsInTransaction,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../container-contents/documentContainerProjectionPersistence\";\nimport {\n clearDocumentSyncFailure,\n deleteDocumentRecord,\n loadDocumentRecord,\n} from \"../records\";\nimport { deleteDocumentHistory } from \"../records/documentHistoryPersistence\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { sameCanonicalDocumentSecurityIdentity } from \"./documentRecordIdentity\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentBlobReclaims } from \"./orphanSideRows\";\n\nasync function deleteStoredDocumentRows(input: {\n existingDocumentId: string | null;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { existingDocumentId, localId, lockedExecSql, tx } = input;\n await queueDocumentAttachmentBlobReclaims({\n localWhere: eq(documentAttachmentBlobProjection.localId, localId),\n pendingWhere: eq(documentPendingAttachments.localId, localId),\n tx,\n });\n await tx\n .delete(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .run();\n await tx\n .delete(documentProjectionText)\n .where(eq(documentProjectionText.localId, localId))\n .run();\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId))\n .run();\n if (existingDocumentId) {\n // Placement rows and their tombstone holds, then queued placement intents.\n await deleteDocumentPlacementRowsByDocumentIds(tx, [existingDocumentId]);\n await deleteDocumentPlacementIntentsInTransaction(tx, existingDocumentId);\n }\n const scope = getDocumentScope(localId);\n await deleteDocumentHistory(lockedExecSql, scope);\n await clearDocumentSyncFailure(lockedExecSql, scope);\n await deleteDocumentRecord(lockedExecSql, scope);\n}\n\nasync function ensureDocumentDeletionTables(execSql: ExecSql): Promise<void> {\n // Move intents live in the container-contents schema, which document-only\n // callers may not have initialized yet.\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n}\n\nasync function hasAnotherDocumentAlias(input: {\n documentId: string;\n localId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const rows = await input.tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.documentId, input.documentId),\n ne(documents.localId, input.localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nexport async function deleteStoredDocument(\n execSql: ExecSql,\n localId: string,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await loadDocumentRecord(lockedExecSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument?.documentId ?? null,\n localId,\n lockedExecSql,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentIfMatches(\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await loadDocumentRecord(lockedExecSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId: expectedRecord.id,\n });\n if (\n !existingDocument ||\n !sameCanonicalDocumentSecurityIdentity(\n existingDocument,\n expectedRecord,\n )\n ) {\n return false;\n }\n const [placement] = await tx\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, expectedRecord.id))\n .limit(1);\n if ((placement?.containerId ?? null) !== expectedRecord.containerId)\n return false;\n if (\n existingDocument.documentId &&\n (await hasAnotherDocumentAlias({\n documentId: existingDocument.documentId,\n localId: expectedRecord.id,\n tx,\n }))\n ) {\n return false;\n }\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument.documentId ?? null,\n localId: expectedRecord.id,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentSideRowsIfAbsent(\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await loadDocumentRecord(lockedExecSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n if (existingDocument) return false;\n if (\n expectedDocumentId &&\n (await hasAnotherDocumentAlias({\n documentId: expectedDocumentId,\n localId,\n tx,\n }))\n ) {\n return false;\n }\n\n await deleteStoredDocumentRows({\n existingDocumentId: expectedDocumentId,\n localId,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
1
+ {"version":3,"file":"documentDeletionPersistence.js","sourceRoot":"","sources":["documentDeletionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,2CAA2C,EAC3C,wCAAwC,GACzC,MAAM,iEAAiE,CAAC;AACzE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAEtD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CAAC,EACH,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,MAAM,wBAAwB,CAAC;gBAC7B,kBAAkB,EAAE,kBAAkB;gBACtC,OAAO;gBACP,aAAa;gBACb,EAAE;aACH,CAAC,CAAC;YACH,MAAM,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, ne } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n} from \"../../../sqlite/schema\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport {\n deleteDocumentPlacementIntentsInTransaction,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../container-contents/documentContainerProjectionPersistence\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { sameCanonicalDocumentSecurityIdentity } from \"./documentRecordIdentity\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentBlobReclaims } from \"./orphanSideRows\";\n\nasync function deleteStoredDocumentRows(input: {\n existingDocumentId: string | null;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { existingDocumentId, localId, lockedExecSql, tx } = input;\n await queueDocumentAttachmentBlobReclaims({\n localWhere: eq(documentAttachmentBlobProjection.localId, localId),\n pendingWhere: eq(documentPendingAttachments.localId, localId),\n tx,\n });\n await tx\n .delete(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .run();\n await tx\n .delete(documentProjectionText)\n .where(eq(documentProjectionText.localId, localId))\n .run();\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId))\n .run();\n if (existingDocumentId) {\n // Placement rows and their tombstone holds, then queued placement intents.\n await deleteDocumentPlacementRowsByDocumentIds(tx, [existingDocumentId]);\n await deleteDocumentPlacementIntentsInTransaction(tx, existingDocumentId);\n }\n const scope = getDocumentScope(localId);\n const records = new DocumentRecordRepository(lockedExecSql);\n await records.deleteDocumentHistory(scope);\n await records.clearDocumentSyncFailure(scope);\n await records.deleteDocumentRecord(scope);\n}\n\nasync function ensureDocumentDeletionTables(execSql: ExecSql): Promise<void> {\n // Move intents live in the container-contents schema, which document-only\n // callers may not have initialized yet.\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n}\n\nasync function hasAnotherDocumentAlias(input: {\n documentId: string;\n localId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const rows = await input.tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.documentId, input.documentId),\n ne(documents.localId, input.localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nexport async function deleteStoredDocument(\n execSql: ExecSql,\n localId: string,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument?.documentId ?? null,\n localId,\n lockedExecSql,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentIfMatches(\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId: expectedRecord.id,\n });\n if (\n !existingDocument ||\n !sameCanonicalDocumentSecurityIdentity(\n existingDocument,\n expectedRecord,\n )\n ) {\n return false;\n }\n const [placement] = await tx\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, expectedRecord.id))\n .limit(1);\n if ((placement?.containerId ?? null) !== expectedRecord.containerId)\n return false;\n if (\n existingDocument.documentId &&\n (await hasAnotherDocumentAlias({\n documentId: existingDocument.documentId,\n localId: expectedRecord.id,\n tx,\n }))\n ) {\n return false;\n }\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument.documentId ?? null,\n localId: expectedRecord.id,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentSideRowsIfAbsent(\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n if (existingDocument) return false;\n if (\n expectedDocumentId &&\n (await hasAnotherDocumentAlias({\n documentId: expectedDocumentId,\n localId,\n tx,\n }))\n ) {\n return false;\n }\n\n await deleteStoredDocumentRows({\n existingDocumentId: expectedDocumentId,\n localId,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
@@ -6,7 +6,7 @@ import { documentSyncPullContinuationsEqual } from "../../../documents/shared/sy
6
6
  import { documentHistoryUpdates } from "../../../sqlite/schema/documentRecordSchema.js";
7
7
  import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
8
8
  import { runSerializedSqlMutation } from "../../../sqlite/sqlSchema.js";
9
- import { appendDocumentHistoryUpdates, replaceDocumentHistoryCheckpoint, } from "../records/documentHistoryPersistence.js";
9
+ import { DocumentRecordRepository } from "../records/index.js";
10
10
  import { insertDocumentPendingUpdateWithHistoryInTransaction, settleQueuedDocumentUpdatesInTransaction, } from "../records/documentPendingUpdatePersistence.js";
11
11
  import { applyStoredAttachmentRemoval, upsertStoredAttachmentStagingRows, } from "./attachmentStagingPersistence.js";
12
12
  import { sameDocumentSecurityIdentity, sameDocumentSettlementIdentity, sameNullableDocumentValue, } from "./documentRecordIdentity.js";
@@ -59,6 +59,7 @@ function assertRecoveryCoversLocalState(coveredLocalState) {
59
59
  }
60
60
  }
61
61
  async function appendMutationHistory(execSql, input, tx) {
62
+ const records = new DocumentRecordRepository(execSql);
62
63
  if (input.historyCheckpoint) {
63
64
  const coveredLocalState = input.historyCheckpoint.pruneCoveredLocalState
64
65
  ? await findCoveredRecoveryLocalState(tx, input.document.id, input.historyCheckpoint.snapshot)
@@ -75,7 +76,7 @@ async function appendMutationHistory(execSql, input, tx) {
75
76
  // A queued rotation baseline the recovery snapshot covers is unqueued
76
77
  // first so the replacement below can delete it with the covered tail.
77
78
  await deleteAcceptedPendingUpdates(tx, input.document.id, coveredLocalState.checkpointIds);
78
- const checkpointReplaced = await replaceDocumentHistoryCheckpoint(execSql, { appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, {
79
+ const checkpointReplaced = await records.replaceDocumentHistoryCheckpoint({ appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, {
79
80
  ...input.historyCheckpoint,
80
81
  coveredTailIds: input.historyCheckpoint.pruneCoveredLocalState
81
82
  ? coveredLocalState.tailIds
@@ -86,7 +87,7 @@ async function appendMutationHistory(execSql, input, tx) {
86
87
  }
87
88
  }
88
89
  if (input.historyUpdates && input.historyUpdates.length > 0) {
89
- await appendDocumentHistoryUpdates(execSql, { appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, input.historyUpdates, input.historyUpdateOrigin ?? "local");
90
+ await records.appendDocumentHistoryUpdates({ appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, input.historyUpdates, input.historyUpdateOrigin ?? "local");
90
91
  }
91
92
  }
92
93
  async function findCoveredRecoveryLocalState(tx, localId, recoverySnapshot) {
@@ -1 +1 @@
1
- {"version":3,"file":"documentMutationPersistence.js","sourceRoot":"","sources":["documentMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,cAAc,EACd,4BAA4B,GAC7B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AACrG,OAAO,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AACrF,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,GACjC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,mDAAmD,EACnD,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,CAAC,cAAc,CAAC,EAC3D,CAAC;YACD,MAAM,4BAA4B,CAChC,EAAE,EACF,KAAK,CAAC,cAAc,CAAC,EAAE,EACvB,KAAK,CAAC,gBAAgB,CACvB,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n createDocument,\n importSnapshot,\n updateMatchesDocumentHistory,\n} from \"@tearleads/loro\";\nimport { and, eq } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { documentSyncPullContinuationsEqual } from \"../../../documents/shared/sync/pullContinuation\";\nimport { documentHistoryUpdates } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport {\n appendDocumentHistoryUpdates,\n replaceDocumentHistoryCheckpoint,\n} from \"../records/documentHistoryPersistence\";\nimport {\n insertDocumentPendingUpdateWithHistoryInTransaction,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../records/documentPendingUpdatePersistence\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n applyStoredAttachmentRemoval,\n upsertStoredAttachmentStagingRows,\n} from \"./attachmentStagingPersistence\";\nimport {\n sameDocumentSecurityIdentity,\n sameDocumentSettlementIdentity,\n sameNullableDocumentValue,\n} from \"./documentRecordIdentity\";\nimport { documentSaveTimestampFrom, saveDocumentRows } from \"./documentRows\";\nimport { loadStoredDocumentState } from \"./rowQueryPersistence\";\n\nfunction sameRecoveryGeneration(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n (current.recoveryGeneration ?? 0) === (expected.recoveryGeneration ?? 0)\n );\n}\n\nfunction sameExpectedDocumentRecord(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n sameDocumentSecurityIdentity(current, expected) &&\n sameRecoveryGeneration(current, expected) &&\n sameNullableDocumentValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n sameNullableDocumentValue(\n current.pendingBaseVersion,\n expected.pendingBaseVersion,\n ) &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired) &&\n (current.documentKind ?? null) === (expected.documentKind ?? null) &&\n current.text === expected.text &&\n (current.title ?? null) === (expected.title ?? null)\n );\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n { appKind: DOCUMENTS_APP_KIND, localId },\n ids,\n );\n}\n\nasync function insertPendingUpdate(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n pendingUpdate: Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"pendingUpdate\"],\n): Promise<void> {\n if (!pendingUpdate) return;\n await insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt: new Date().toISOString(),\n pendingUpdate,\n scope: { appKind: DOCUMENTS_APP_KIND, localId: documentId },\n tx,\n });\n}\n\nasync function settleMutationConflict(input: {\n currentRecord: StoredDocumentRecord | null;\n mutation: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n if (\n input.currentRecord &&\n input.mutation.settleAcceptedPendingOnConflict &&\n sameDocumentSettlementIdentity(\n input.currentRecord,\n input.mutation.expectedRecord,\n ) &&\n sameRecoveryGeneration(input.currentRecord, input.mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n input.tx,\n input.mutation.document.id,\n input.mutation.acceptedPendingUpdateIds,\n );\n }\n}\n\nfunction assertRecoveryCoversLocalState(coveredLocalState: {\n readonly hasOrdinaryPendingUpdates: boolean;\n readonly hasUnprunablePendingUpdates: boolean;\n readonly hasUnverifiedHistoryTail: boolean;\n}): void {\n if (\n coveredLocalState.hasOrdinaryPendingUpdates ||\n coveredLocalState.hasUnprunablePendingUpdates\n ) {\n throw new Error(\n \"Document recovery found unproven pending updates before installation\",\n );\n }\n if (coveredLocalState.hasUnverifiedHistoryTail) {\n throw new Error(\n \"Document recovery found unverified history tail before installation\",\n );\n }\n}\n\nasync function appendMutationHistory(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1],\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n if (input.historyCheckpoint) {\n const coveredLocalState = input.historyCheckpoint.pruneCoveredLocalState\n ? await findCoveredRecoveryLocalState(\n tx,\n input.document.id,\n input.historyCheckpoint.snapshot,\n )\n : {\n checkpointIds: [],\n hasOrdinaryPendingUpdates: false,\n hasUnprunablePendingUpdates: false,\n hasUnverifiedHistoryTail: false,\n tailIds: [],\n };\n if (input.historyCheckpoint.pruneCoveredLocalState) {\n assertRecoveryCoversLocalState(coveredLocalState);\n }\n // A queued rotation baseline the recovery snapshot covers is unqueued\n // first so the replacement below can delete it with the covered tail.\n await deleteAcceptedPendingUpdates(\n tx,\n input.document.id,\n coveredLocalState.checkpointIds,\n );\n const checkpointReplaced = await replaceDocumentHistoryCheckpoint(\n execSql,\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n {\n ...input.historyCheckpoint,\n coveredTailIds: input.historyCheckpoint.pruneCoveredLocalState\n ? coveredLocalState.tailIds\n : input.historyCheckpoint.coveredTailIds,\n },\n );\n if (input.historyCheckpoint.pruneCoveredLocalState && !checkpointReplaced) {\n throw new Error(\n \"Document recovery checkpoint was superseded before installation\",\n );\n }\n }\n if (input.historyUpdates && input.historyUpdates.length > 0) {\n await appendDocumentHistoryUpdates(\n execSql,\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n input.historyUpdates,\n input.historyUpdateOrigin ?? \"local\",\n );\n }\n}\n\nasync function findCoveredRecoveryLocalState(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n recoverySnapshot: string,\n): Promise<{\n checkpointIds: string[];\n hasOrdinaryPendingUpdates: boolean;\n hasUnprunablePendingUpdates: boolean;\n hasUnverifiedHistoryTail: boolean;\n tailIds: string[];\n}> {\n const recoveredDocument = await createDocument(\n `recovery-tail-verification:${localId}`,\n );\n try {\n importSnapshot(recoveredDocument, base64ToBytes(recoverySnapshot));\n const rows = await tx\n .select({\n id: documentHistoryUpdates.id,\n origin: documentHistoryUpdates.origin,\n sourceVersionVector: documentHistoryUpdates.sourceVersionVector,\n updateData: documentHistoryUpdates.updateData,\n updateId: documentHistoryUpdates.updateId,\n })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, DOCUMENTS_APP_KIND),\n eq(documentHistoryUpdates.localId, localId),\n ),\n );\n const pendingUpdates = rows.filter((row) => row.updateId !== null);\n const tail = rows.filter((row) => row.origin !== \"outbox\");\n const checkpointUpdateData = new Set(\n pendingUpdates.flatMap((row) =>\n row.sourceVersionVector === null ? [] : [row.updateData],\n ),\n );\n let hasUnverifiedHistoryTail = false;\n const tailIds = tail.flatMap((row) => {\n if (row.id === null) {\n // An unverifiable row identity cannot participate in the guarded\n // delete, so accepting it would leave a stale recovery redirect.\n hasUnverifiedHistoryTail = true;\n return [];\n }\n if (checkpointUpdateData.has(row.updateData)) return [row.id];\n try {\n if (\n updateMatchesDocumentHistory(\n recoveredDocument,\n base64ToBytes(row.updateData),\n )\n ) {\n return [row.id];\n }\n } catch {\n // Fall through: malformed history is not proven by the rebuild.\n }\n hasUnverifiedHistoryTail = true;\n return [];\n });\n return {\n checkpointIds: pendingUpdates.flatMap((row) =>\n row.updateId !== null && row.sourceVersionVector !== null\n ? [row.updateId]\n : [],\n ),\n hasOrdinaryPendingUpdates: pendingUpdates.some(\n (row) => row.sourceVersionVector === null,\n ),\n hasUnprunablePendingUpdates: pendingUpdates.some(\n (row) => row.id === null,\n ),\n hasUnverifiedHistoryTail,\n tailIds,\n };\n } finally {\n recoveredDocument.free();\n }\n}\n\ntype CommitDocumentMutationInput = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[1];\ntype SaveClientProjection = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[2];\n\nasync function applyStoredDocumentMutation(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { lockedExecSql, mutation, tx } = input;\n const currentState = await loadStoredDocumentState(\n lockedExecSql,\n mutation.document.id,\n );\n const currentRecord = currentState?.record ?? null;\n if (mutation.stillCurrent && !mutation.stillCurrent()) {\n return { committed: false as const, currentRecord };\n }\n if (\n !currentRecord ||\n !sameExpectedDocumentRecord(currentRecord, mutation.expectedRecord)\n ) {\n await settleMutationConflict({ currentRecord, mutation, tx });\n return { committed: false as const, currentRecord };\n }\n\n if (mutation.attachmentRemoval) {\n await applyStoredAttachmentRemoval({\n localId: mutation.document.id,\n removal: mutation.attachmentRemoval,\n tx,\n });\n }\n if (mutation.attachmentStaging) {\n await upsertStoredAttachmentStagingRows({\n createdAt: new Date().toISOString(),\n localId: mutation.document.id,\n staging: mutation.attachmentStaging,\n tx,\n });\n }\n await appendMutationHistory(lockedExecSql, mutation, tx);\n await insertPendingUpdate(tx, mutation.document.id, mutation.pendingUpdate);\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.document.id,\n mutation.acceptedPendingUpdateIds,\n );\n // Nothing above writes the document or projection rows, so the state read\n // at the top of this transaction still decides the save timestamp.\n const updatedAt =\n mutation.updatedAt ||\n documentSaveTimestampFrom(\n {\n projection: currentState?.projection ?? null,\n snapshotEndVersion: currentRecord.snapshotEndVersion,\n },\n mutation.document,\n );\n if (\n !(await saveDocumentRows({\n clearSyncFailure: mutation.clearSyncFailure === true,\n document: mutation.document,\n tx,\n updatedAt,\n }))\n ) {\n throw new Error(\n \"Document recovery generation changed before mutation save\",\n );\n }\n await input.saveClientProjection(lockedExecSql, updatedAt);\n return { committed: true as const, updatedAt };\n}\n\nasync function runStoredDocumentMutationTransaction(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n loadDocument: DocumentsPersistence[\"loadDocument\"];\n}) {\n const outcome = await getClientSQLitePersistenceRuntime(\n input.lockedExecSql,\n ).guardedTransaction(\n (tx) => applyStoredDocumentMutation({ ...input, tx }),\n () => !input.mutation.stillCurrent || input.mutation.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentRecord: await input.loadDocument(\n input.lockedExecSql,\n input.mutation.document.id,\n ),\n };\n}\n\nexport async function commitStoredDocumentMutation(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: CommitDocumentMutationInput,\n saveClientProjection: SaveClientProjection,\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n runStoredDocumentMutationTransaction({\n lockedExecSql,\n loadDocument,\n mutation: input,\n saveClientProjection,\n }),\n );\n}\n\nexport async function settleStoredDocumentPendingUpdates(\n execSql: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[0],\n input: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const currentRecord = await loadDocument(\n lockedExecSql,\n input.expectedRecord.id,\n );\n if (\n currentRecord &&\n sameDocumentSettlementIdentity(currentRecord, input.expectedRecord) &&\n sameRecoveryGeneration(currentRecord, input.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.expectedRecord.id,\n input.pendingUpdateIds,\n );\n }\n return currentRecord;\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"documentMutationPersistence.js","sourceRoot":"","sources":["documentMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,cAAc,EACd,4BAA4B,GAC7B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AACrG,OAAO,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AACrF,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EACL,mDAAmD,EACnD,wCAAwC,GACzC,MAAM,6CAA6C,CAAC;AAErD,OAAO,EACL,4BAA4B,EAC5B,iCAAiC,GAClC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,4BAA4B,EAC5B,8BAA8B,EAC9B,yBAAyB,GAC1B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAEhE,SAAS,sBAAsB,CAC7B,OAA6B,EAC7B,QAA8B;IAE9B,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,\n importSnapshot,\n updateMatchesDocumentHistory,\n} from \"@tearleads/loro\";\nimport { and, eq } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { documentSyncPullContinuationsEqual } from \"../../../documents/shared/sync/pullContinuation\";\nimport { documentHistoryUpdates } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport {\n insertDocumentPendingUpdateWithHistoryInTransaction,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../records/documentPendingUpdatePersistence\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n applyStoredAttachmentRemoval,\n upsertStoredAttachmentStagingRows,\n} from \"./attachmentStagingPersistence\";\nimport {\n sameDocumentSecurityIdentity,\n sameDocumentSettlementIdentity,\n sameNullableDocumentValue,\n} from \"./documentRecordIdentity\";\nimport { documentSaveTimestampFrom, saveDocumentRows } from \"./documentRows\";\nimport { loadStoredDocumentState } from \"./rowQueryPersistence\";\n\nfunction sameRecoveryGeneration(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n (current.recoveryGeneration ?? 0) === (expected.recoveryGeneration ?? 0)\n );\n}\n\nfunction sameExpectedDocumentRecord(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n sameDocumentSecurityIdentity(current, expected) &&\n sameRecoveryGeneration(current, expected) &&\n sameNullableDocumentValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n sameNullableDocumentValue(\n current.pendingBaseVersion,\n expected.pendingBaseVersion,\n ) &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired) &&\n (current.documentKind ?? null) === (expected.documentKind ?? null) &&\n current.text === expected.text &&\n (current.title ?? null) === (expected.title ?? null)\n );\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n { appKind: DOCUMENTS_APP_KIND, localId },\n ids,\n );\n}\n\nasync function insertPendingUpdate(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n pendingUpdate: Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"pendingUpdate\"],\n): Promise<void> {\n if (!pendingUpdate) return;\n await insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt: new Date().toISOString(),\n pendingUpdate,\n scope: { appKind: DOCUMENTS_APP_KIND, localId: documentId },\n tx,\n });\n}\n\nasync function settleMutationConflict(input: {\n currentRecord: StoredDocumentRecord | null;\n mutation: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n if (\n input.currentRecord &&\n input.mutation.settleAcceptedPendingOnConflict &&\n sameDocumentSettlementIdentity(\n input.currentRecord,\n input.mutation.expectedRecord,\n ) &&\n sameRecoveryGeneration(input.currentRecord, input.mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n input.tx,\n input.mutation.document.id,\n input.mutation.acceptedPendingUpdateIds,\n );\n }\n}\n\nfunction assertRecoveryCoversLocalState(coveredLocalState: {\n readonly hasOrdinaryPendingUpdates: boolean;\n readonly hasUnprunablePendingUpdates: boolean;\n readonly hasUnverifiedHistoryTail: boolean;\n}): void {\n if (\n coveredLocalState.hasOrdinaryPendingUpdates ||\n coveredLocalState.hasUnprunablePendingUpdates\n ) {\n throw new Error(\n \"Document recovery found unproven pending updates before installation\",\n );\n }\n if (coveredLocalState.hasUnverifiedHistoryTail) {\n throw new Error(\n \"Document recovery found unverified history tail before installation\",\n );\n }\n}\n\nasync function appendMutationHistory(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1],\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const records = new DocumentRecordRepository(execSql);\n if (input.historyCheckpoint) {\n const coveredLocalState = input.historyCheckpoint.pruneCoveredLocalState\n ? await findCoveredRecoveryLocalState(\n tx,\n input.document.id,\n input.historyCheckpoint.snapshot,\n )\n : {\n checkpointIds: [],\n hasOrdinaryPendingUpdates: false,\n hasUnprunablePendingUpdates: false,\n hasUnverifiedHistoryTail: false,\n tailIds: [],\n };\n if (input.historyCheckpoint.pruneCoveredLocalState) {\n assertRecoveryCoversLocalState(coveredLocalState);\n }\n // A queued rotation baseline the recovery snapshot covers is unqueued\n // first so the replacement below can delete it with the covered tail.\n await deleteAcceptedPendingUpdates(\n tx,\n input.document.id,\n coveredLocalState.checkpointIds,\n );\n const checkpointReplaced = await records.replaceDocumentHistoryCheckpoint(\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n {\n ...input.historyCheckpoint,\n coveredTailIds: input.historyCheckpoint.pruneCoveredLocalState\n ? coveredLocalState.tailIds\n : input.historyCheckpoint.coveredTailIds,\n },\n );\n if (input.historyCheckpoint.pruneCoveredLocalState && !checkpointReplaced) {\n throw new Error(\n \"Document recovery checkpoint was superseded before installation\",\n );\n }\n }\n if (input.historyUpdates && input.historyUpdates.length > 0) {\n await records.appendDocumentHistoryUpdates(\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n input.historyUpdates,\n input.historyUpdateOrigin ?? \"local\",\n );\n }\n}\n\nasync function findCoveredRecoveryLocalState(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n recoverySnapshot: string,\n): Promise<{\n checkpointIds: string[];\n hasOrdinaryPendingUpdates: boolean;\n hasUnprunablePendingUpdates: boolean;\n hasUnverifiedHistoryTail: boolean;\n tailIds: string[];\n}> {\n const recoveredDocument = await createDocument(\n `recovery-tail-verification:${localId}`,\n );\n try {\n importSnapshot(recoveredDocument, base64ToBytes(recoverySnapshot));\n const rows = await tx\n .select({\n id: documentHistoryUpdates.id,\n origin: documentHistoryUpdates.origin,\n sourceVersionVector: documentHistoryUpdates.sourceVersionVector,\n updateData: documentHistoryUpdates.updateData,\n updateId: documentHistoryUpdates.updateId,\n })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, DOCUMENTS_APP_KIND),\n eq(documentHistoryUpdates.localId, localId),\n ),\n );\n const pendingUpdates = rows.filter((row) => row.updateId !== null);\n const tail = rows.filter((row) => row.origin !== \"outbox\");\n const checkpointUpdateData = new Set(\n pendingUpdates.flatMap((row) =>\n row.sourceVersionVector === null ? [] : [row.updateData],\n ),\n );\n let hasUnverifiedHistoryTail = false;\n const tailIds = tail.flatMap((row) => {\n if (row.id === null) {\n // An unverifiable row identity cannot participate in the guarded\n // delete, so accepting it would leave a stale recovery redirect.\n hasUnverifiedHistoryTail = true;\n return [];\n }\n if (checkpointUpdateData.has(row.updateData)) return [row.id];\n try {\n if (\n updateMatchesDocumentHistory(\n recoveredDocument,\n base64ToBytes(row.updateData),\n )\n ) {\n return [row.id];\n }\n } catch {\n // Fall through: malformed history is not proven by the rebuild.\n }\n hasUnverifiedHistoryTail = true;\n return [];\n });\n return {\n checkpointIds: pendingUpdates.flatMap((row) =>\n row.updateId !== null && row.sourceVersionVector !== null\n ? [row.updateId]\n : [],\n ),\n hasOrdinaryPendingUpdates: pendingUpdates.some(\n (row) => row.sourceVersionVector === null,\n ),\n hasUnprunablePendingUpdates: pendingUpdates.some(\n (row) => row.id === null,\n ),\n hasUnverifiedHistoryTail,\n tailIds,\n };\n } finally {\n recoveredDocument.free();\n }\n}\n\ntype CommitDocumentMutationInput = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[1];\ntype SaveClientProjection = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[2];\n\nasync function applyStoredDocumentMutation(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { lockedExecSql, mutation, tx } = input;\n const currentState = await loadStoredDocumentState(\n lockedExecSql,\n mutation.document.id,\n );\n const currentRecord = currentState?.record ?? null;\n if (mutation.stillCurrent && !mutation.stillCurrent()) {\n return { committed: false as const, currentRecord };\n }\n if (\n !currentRecord ||\n !sameExpectedDocumentRecord(currentRecord, mutation.expectedRecord)\n ) {\n await settleMutationConflict({ currentRecord, mutation, tx });\n return { committed: false as const, currentRecord };\n }\n\n if (mutation.attachmentRemoval) {\n await applyStoredAttachmentRemoval({\n localId: mutation.document.id,\n removal: mutation.attachmentRemoval,\n tx,\n });\n }\n if (mutation.attachmentStaging) {\n await upsertStoredAttachmentStagingRows({\n createdAt: new Date().toISOString(),\n localId: mutation.document.id,\n staging: mutation.attachmentStaging,\n tx,\n });\n }\n await appendMutationHistory(lockedExecSql, mutation, tx);\n await insertPendingUpdate(tx, mutation.document.id, mutation.pendingUpdate);\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.document.id,\n mutation.acceptedPendingUpdateIds,\n );\n // Nothing above writes the document or projection rows, so the state read\n // at the top of this transaction still decides the save timestamp.\n const updatedAt =\n mutation.updatedAt ||\n documentSaveTimestampFrom(\n {\n projection: currentState?.projection ?? null,\n snapshotEndVersion: currentRecord.snapshotEndVersion,\n },\n mutation.document,\n );\n if (\n !(await saveDocumentRows({\n clearSyncFailure: mutation.clearSyncFailure === true,\n document: mutation.document,\n tx,\n updatedAt,\n }))\n ) {\n throw new Error(\n \"Document recovery generation changed before mutation save\",\n );\n }\n await input.saveClientProjection(lockedExecSql, updatedAt);\n return { committed: true as const, updatedAt };\n}\n\nasync function runStoredDocumentMutationTransaction(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n loadDocument: DocumentsPersistence[\"loadDocument\"];\n}) {\n const outcome = await getClientSQLitePersistenceRuntime(\n input.lockedExecSql,\n ).guardedTransaction(\n (tx) => applyStoredDocumentMutation({ ...input, tx }),\n () => !input.mutation.stillCurrent || input.mutation.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentRecord: await input.loadDocument(\n input.lockedExecSql,\n input.mutation.document.id,\n ),\n };\n}\n\nexport async function commitStoredDocumentMutation(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: CommitDocumentMutationInput,\n saveClientProjection: SaveClientProjection,\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n runStoredDocumentMutationTransaction({\n lockedExecSql,\n loadDocument,\n mutation: input,\n saveClientProjection,\n }),\n );\n}\n\nexport async function settleStoredDocumentPendingUpdates(\n execSql: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[0],\n input: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const currentRecord = await loadDocument(\n lockedExecSql,\n input.expectedRecord.id,\n );\n if (\n currentRecord &&\n sameDocumentSettlementIdentity(currentRecord, input.expectedRecord) &&\n sameRecoveryGeneration(currentRecord, input.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.expectedRecord.id,\n input.pendingUpdateIds,\n );\n }\n return currentRecord;\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import { DOCUMENTS_APP_KIND } from "../../../documents/documentConstants.js";
2
2
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
3
3
  import { runSerializedSqlMutation } from "../../../sqlite/sqlSchema.js";
4
- import { invalidateDocumentSyncPullContinuation } from "../records/index.js";
4
+ import { DocumentRecordRepository } from "../records/index.js";
5
5
  export async function invalidateStoredDocumentPullContinuation(execSql, input, loadDocument, loadHistoryRestoreState) {
6
6
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async () => {
7
- const invalidated = await invalidateDocumentSyncPullContinuation(lockedExecSql, {
7
+ const invalidated = await new DocumentRecordRepository(lockedExecSql).invalidateDocumentSyncPullContinuation({
8
8
  ...input,
9
9
  appKind: DOCUMENTS_APP_KIND,
10
10
  });
@@ -1 +1 @@
1
- {"version":3,"file":"documentPullContinuationPersistence.js","sourceRoot":"","sources":["documentPullContinuationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAC;AAGpE,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,OAA0E,EAC1E,KAAwE,EACxE,YAAkD,EAClD,uBAAwE;IAExE,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC/D,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAC1D,KAAK,IAAI,EAAE;QACT,MAAM,WAAW,GAAG,MAAM,sCAAsC,CAC9D,aAAa,EACb;YACE,GAAG,KAAK;YACR,OAAO,EAAE,kBAAkB;SAC5B,CACF,CAAC;QACF,IAAI,CAAC,WAAW;YAAE,OAAO,IAAI,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,MAAM,mBAAmB,GAAG,MAAM,uBAAuB,CACvD,aAAa,EACb,KAAK,CAAC,OAAO,CACd,CAAC;QACF,OAAO,EAAE,mBAAmB,EAAE,MAAM,EAAE,CAAC;IACzC,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { invalidateDocumentSyncPullContinuation } from \"../records\";\nimport type { DocumentsPersistence } from \"../types\";\n\nexport async function invalidateStoredDocumentPullContinuation(\n execSql: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[0],\n input: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n loadHistoryRestoreState: DocumentsPersistence[\"loadHistoryRestoreState\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async () => {\n const invalidated = await invalidateDocumentSyncPullContinuation(\n lockedExecSql,\n {\n ...input,\n appKind: DOCUMENTS_APP_KIND,\n },\n );\n if (!invalidated) return null;\n const record = await loadDocument(lockedExecSql, input.localId);\n if (!record) return null;\n const historyRestoreState = await loadHistoryRestoreState(\n lockedExecSql,\n input.localId,\n );\n return { historyRestoreState, record };\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"documentPullContinuationPersistence.js","sourceRoot":"","sources":["documentPullContinuationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAGtD,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,OAA0E,EAC1E,KAAwE,EACxE,YAAkD,EAClD,uBAAwE;IAExE,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC/D,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAC1D,KAAK,IAAI,EAAE;QACT,MAAM,WAAW,GAAG,MAAM,IAAI,wBAAwB,CACpD,aAAa,CACd,CAAC,sCAAsC,CAAC;YACvC,GAAG,KAAK;YACR,OAAO,EAAE,kBAAkB;SAC5B,CAAC,CAAC;QACH,IAAI,CAAC,WAAW;YAAE,OAAO,IAAI,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,MAAM,mBAAmB,GAAG,MAAM,uBAAuB,CACvD,aAAa,EACb,KAAK,CAAC,OAAO,CACd,CAAC;QACF,OAAO,EAAE,mBAAmB,EAAE,MAAM,EAAE,CAAC;IACzC,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { DocumentsPersistence } from \"../types\";\n\nexport async function invalidateStoredDocumentPullContinuation(\n execSql: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[0],\n input: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n loadHistoryRestoreState: DocumentsPersistence[\"loadHistoryRestoreState\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async () => {\n const invalidated = await new DocumentRecordRepository(\n lockedExecSql,\n ).invalidateDocumentSyncPullContinuation({\n ...input,\n appKind: DOCUMENTS_APP_KIND,\n });\n if (!invalidated) return null;\n const record = await loadDocument(lockedExecSql, input.localId);\n if (!record) return null;\n const historyRestoreState = await loadHistoryRestoreState(\n lockedExecSql,\n input.localId,\n );\n return { historyRestoreState, record };\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
@@ -5,7 +5,7 @@ import { documentProjection, documentProjectionText, } from "../../../sqlite/sch
5
5
  import { documents } from "../../../sqlite/schema/documentRecordSchema.js";
6
6
  import { sqliteRowsPerStatement } from "../../../sqlite/sqliteBindBudget.js";
7
7
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
8
- import { documentRecordSelection, findLocalIdByDocumentId, loadDocumentRecord, mapSelectedDocumentRecord, } from "../records/index.js";
8
+ import { DocumentRecordRepository, documentRecordSelection, mapSelectedDocumentRecord, } from "../records/index.js";
9
9
  import { documentSummaryJoin, documentSummarySelection, getProjectionContainerId, getProjectionDocumentKind, getProjectionText, getProjectionTitle, mapDocumentSummary, } from "./documentProjectionRows.js";
10
10
  import { getDocumentScope, hasDocumentRow } from "./documentRows.js";
11
11
  const storedDocumentStateSelection = {
@@ -106,12 +106,12 @@ export const documentRowQueryPersistence = {
106
106
  .map((row) => row.localId)
107
107
  .filter((localId) => localId !== null);
108
108
  },
109
- findLocalIdByDocumentId: (execSql, documentId) => findLocalIdByDocumentId(execSql, DOCUMENTS_APP_KIND, documentId),
109
+ findLocalIdByDocumentId: (execSql, documentId) => new DocumentRecordRepository(execSql).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, documentId),
110
110
  async hasDocument(execSql, localId) {
111
111
  return hasDocumentRow(execSql, localId);
112
112
  },
113
113
  async documentIdentityMatches(execSql, localId, expectedDocumentId, expectedRecoveryGeneration) {
114
- const record = await loadDocumentRecord(execSql, getDocumentScope(localId));
114
+ const record = await new DocumentRecordRepository(execSql).loadDocumentRecord(getDocumentScope(localId));
115
115
  return (record?.documentId === expectedDocumentId &&
116
116
  (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration);
117
117
  },
@@ -1 +1 @@
1
- {"version":3,"file":"rowQueryPersistence.js","sourceRoot":"","sources":["rowQueryPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAY,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAE1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,kBAAkB,EAClB,yBAAyB,GAC1B,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,wBAAwB,EACxB,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAUlE,MAAM,4BAA4B,GAAG;IACnC,GAAG,uBAAuB;IAC1B,qBAAqB,EAAE,kBAAkB,CAAC,WAAW;IACrD,sBAAsB,EAAE,kBAAkB,CAAC,YAAY;I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CAAC,kBAAkB,CAAC;aACxB,KAAK,CAAC,EAAE,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;aAC9C,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,MAAM,aAAa,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;QACxC,IAAI,CAAC,aAAa,EAAE,CAAC;YACnB,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,EAAE,WAAW,EAAE,aAAa,CAAC,WAAW,EAAE,CAAC;IACpD,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, type SQL } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../documents/documentKinds\";\nimport { HIDDEN_DOCUMENT_SUMMARY_KINDS } from \"../../../documents/documentSummary\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n documentRecordSelection,\n findLocalIdByDocumentId,\n loadDocumentRecord,\n mapSelectedDocumentRecord,\n} from \"../records\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionContainerId,\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { getDocumentScope, hasDocumentRow } from \"./documentRows\";\n\n/** The projection columns a stored record was loaded with, if any. */\nexport interface StoredDocumentProjectionState {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n}\n\nconst storedDocumentStateSelection = {\n ...documentRecordSelection,\n projectionContainerId: documentProjection.containerId,\n projectionDocumentKind: documentProjection.documentKind,\n projectionText: documentProjectionText.text,\n projectionTitle: documentProjection.title,\n projectionUpdatedAt: documentProjection.updatedAt,\n};\n\nexport interface StoredDocumentState {\n projection: StoredDocumentProjectionState | null;\n record: StoredDocumentRecord;\n}\n\nfunction storedDocumentStateQuery(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: SQL | undefined,\n) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(storedDocumentStateSelection)\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), localIds));\n}\n\nfunction mapStoredDocumentState(\n row: Awaited<ReturnType<typeof storedDocumentStateQuery>>[number],\n): StoredDocumentState {\n const {\n projectionContainerId,\n projectionDocumentKind,\n projectionText,\n projectionTitle,\n projectionUpdatedAt,\n ...recordRow\n } = row;\n // Projection columns are NOT NULL, so they are null exactly when the\n // projection row is absent.\n const projectionRow =\n projectionDocumentKind !== null &&\n projectionTitle !== null &&\n projectionUpdatedAt !== null\n ? {\n containerId: projectionContainerId,\n documentKind: projectionDocumentKind,\n text: projectionText,\n title: projectionTitle,\n }\n : undefined;\n return {\n projection:\n projectionRow && projectionUpdatedAt !== null\n ? { ...projectionRow, updatedAt: projectionUpdatedAt }\n : null,\n record: {\n ...mapSelectedDocumentRecord(recordRow),\n containerId: getProjectionContainerId(projectionRow),\n documentKind: getProjectionDocumentKind(projectionRow),\n text: getProjectionText(projectionRow),\n title: getProjectionTitle(projectionRow),\n },\n };\n}\n\n/**\n * The canonical record and its projection from ONE joined statement, so the\n * pair comes from one snapshot and a save inside the same transaction can\n * reuse the projection instead of reading it again.\n */\nexport async function loadStoredDocumentState(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localId: string,\n): Promise<StoredDocumentState | null> {\n const [row] = await storedDocumentStateQuery(\n execSql,\n eq(documents.localId, localId),\n ).limit(1);\n return row ? mapStoredDocumentState(row) : null;\n}\n\n/** `loadStoredDocumentState` for many local ids, one joined read per chunk. */\nexport async function loadStoredDocumentStates(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: ReadonlyArray<string>,\n): Promise<Map<string, StoredDocumentState>> {\n const states = new Map<string, StoredDocumentState>();\n const unique = Array.from(new Set(localIds));\n // One bind for the app kind; the rest carry local ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < unique.length; offset += chunkSize) {\n const rows = await storedDocumentStateQuery(\n execSql,\n inArray(documents.localId, unique.slice(offset, offset + chunkSize)),\n );\n for (const row of rows) states.set(row.id, mapStoredDocumentState(row));\n }\n return states;\n}\n\ntype DocumentRowQueryPersistence = Pick<\n DocumentsPersistence,\n | \"listDocuments\"\n | \"findDocumentLocalIdsByContainerId\"\n | \"findLocalIdByDocumentId\"\n | \"hasDocument\"\n | \"documentIdentityMatches\"\n | \"loadDocument\"\n | \"loadDocumentContainer\"\n>;\n\nexport const documentRowQueryPersistence: DocumentRowQueryPersistence = {\n async listDocuments(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n },\n async findDocumentLocalIdsByContainerId(execSql, containerId) {\n // Unlike `listDocumentsByContainerIdsOrDocumentIds`, this deliberately does\n // NOT drop `HIDDEN_DOCUMENT_SUMMARY_KINDS` — it exists to reach the hidden\n // `organization_profile` document by the container it is linked to, which is\n // how a *foreign* org's display name is found on a member who synced the doc\n // under its server documentId rather than the provisioner-only local alias.\n // `documentProjection` is written and deleted in lockstep with the\n // `documents` rows (all DOCUMENTS_APP_KIND), so filtering by containerId\n // alone is sufficient — no join to `documents` is needed to select localId.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documentProjection.localId })\n .from(documentProjection)\n .where(eq(documentProjection.containerId, containerId))\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n return rows\n .map((row) => row.localId)\n .filter((localId): localId is string => localId !== null);\n },\n findLocalIdByDocumentId: (execSql, documentId) =>\n findLocalIdByDocumentId(execSql, DOCUMENTS_APP_KIND, documentId),\n async hasDocument(execSql, localId) {\n return hasDocumentRow(execSql, localId);\n },\n async documentIdentityMatches(\n execSql,\n localId,\n expectedDocumentId,\n expectedRecoveryGeneration,\n ) {\n const record = await loadDocumentRecord(execSql, getDocumentScope(localId));\n return (\n record?.documentId === expectedDocumentId &&\n (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration\n );\n },\n async loadDocument(execSql, localId) {\n return (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n },\n async loadDocumentContainer(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Select the row itself, not just its container, so an existing row with a\n // null container is reported as `{ containerId: null }` while a missing row\n // is reported as `undefined` — the caller relies on that distinction to know\n // whether the projection has authoritative placement to defer to.\n const projectionRows = await db\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .limit(1);\n const projectionRow = projectionRows[0];\n if (!projectionRow) {\n return undefined;\n }\n\n return { containerId: projectionRow.containerId };\n },\n};\n"]}
1
+ {"version":3,"file":"rowQueryPersistence.js","sourceRoot":"","sources":["rowQueryPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAY,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAE1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;A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M,IAAI,wBAAwB,CAC/C,OAAO,CACR,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC;QAChD,OAAO,CACL,MAAM,EAAE,UAAU,KAAK,kBAAkB;YACzC,CAAC,MAAM,CAAC,kBAAkB,IAAI,CAAC,CAAC,KAAK,0BAA0B,CAChE,CAAC;IACJ,CAAC;IACD,KAAK,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO;QACjC,OAAO,CAAC,MAAM,uBAAuB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,MAAM,IAAI,IAAI,CAAC;IAC3E,CAAC;IACD,KAAK,CAAC,qBAAqB,CAAC,OAAO,EAAE,OAAO;QAC1C,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;QAC1D,2EAA2E;QAC3E,4EAA4E;QAC5E,6EAA6E;QAC7E,kEAAkE;QAClE,MAAM,cAAc,GAAG,MAAM,EAAE;aAC5B,MAAM,CAAC,EAAE,WAAW,EAAE,kBAAkB,CAAC,WAAW,EAAE,CAAC;aACvD,IAAI,CAAC,kBAAkB,CAAC;aACxB,KAAK,CAAC,EAAE,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;aAC9C,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,MAAM,aAAa,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;QACxC,IAAI,CAAC,aAAa,EAAE,CAAC;YACnB,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,EAAE,WAAW,EAAE,aAAa,CAAC,WAAW,EAAE,CAAC;IACpD,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, type SQL } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../documents/documentKinds\";\nimport { HIDDEN_DOCUMENT_SUMMARY_KINDS } from \"../../../documents/documentSummary\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n DocumentRecordRepository,\n documentRecordSelection,\n mapSelectedDocumentRecord,\n} from \"../records\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionContainerId,\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { getDocumentScope, hasDocumentRow } from \"./documentRows\";\n\n/** The projection columns a stored record was loaded with, if any. */\nexport interface StoredDocumentProjectionState {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n}\n\nconst storedDocumentStateSelection = {\n ...documentRecordSelection,\n projectionContainerId: documentProjection.containerId,\n projectionDocumentKind: documentProjection.documentKind,\n projectionText: documentProjectionText.text,\n projectionTitle: documentProjection.title,\n projectionUpdatedAt: documentProjection.updatedAt,\n};\n\nexport interface StoredDocumentState {\n projection: StoredDocumentProjectionState | null;\n record: StoredDocumentRecord;\n}\n\nfunction storedDocumentStateQuery(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: SQL | undefined,\n) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(storedDocumentStateSelection)\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), localIds));\n}\n\nfunction mapStoredDocumentState(\n row: Awaited<ReturnType<typeof storedDocumentStateQuery>>[number],\n): StoredDocumentState {\n const {\n projectionContainerId,\n projectionDocumentKind,\n projectionText,\n projectionTitle,\n projectionUpdatedAt,\n ...recordRow\n } = row;\n // Projection columns are NOT NULL, so they are null exactly when the\n // projection row is absent.\n const projectionRow =\n projectionDocumentKind !== null &&\n projectionTitle !== null &&\n projectionUpdatedAt !== null\n ? {\n containerId: projectionContainerId,\n documentKind: projectionDocumentKind,\n text: projectionText,\n title: projectionTitle,\n }\n : undefined;\n return {\n projection:\n projectionRow && projectionUpdatedAt !== null\n ? { ...projectionRow, updatedAt: projectionUpdatedAt }\n : null,\n record: {\n ...mapSelectedDocumentRecord(recordRow),\n containerId: getProjectionContainerId(projectionRow),\n documentKind: getProjectionDocumentKind(projectionRow),\n text: getProjectionText(projectionRow),\n title: getProjectionTitle(projectionRow),\n },\n };\n}\n\n/**\n * The canonical record and its projection from ONE joined statement, so the\n * pair comes from one snapshot and a save inside the same transaction can\n * reuse the projection instead of reading it again.\n */\nexport async function loadStoredDocumentState(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localId: string,\n): Promise<StoredDocumentState | null> {\n const [row] = await storedDocumentStateQuery(\n execSql,\n eq(documents.localId, localId),\n ).limit(1);\n return row ? mapStoredDocumentState(row) : null;\n}\n\n/** `loadStoredDocumentState` for many local ids, one joined read per chunk. */\nexport async function loadStoredDocumentStates(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: ReadonlyArray<string>,\n): Promise<Map<string, StoredDocumentState>> {\n const states = new Map<string, StoredDocumentState>();\n const unique = Array.from(new Set(localIds));\n // One bind for the app kind; the rest carry local ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < unique.length; offset += chunkSize) {\n const rows = await storedDocumentStateQuery(\n execSql,\n inArray(documents.localId, unique.slice(offset, offset + chunkSize)),\n );\n for (const row of rows) states.set(row.id, mapStoredDocumentState(row));\n }\n return states;\n}\n\ntype DocumentRowQueryPersistence = Pick<\n DocumentsPersistence,\n | \"listDocuments\"\n | \"findDocumentLocalIdsByContainerId\"\n | \"findLocalIdByDocumentId\"\n | \"hasDocument\"\n | \"documentIdentityMatches\"\n | \"loadDocument\"\n | \"loadDocumentContainer\"\n>;\n\nexport const documentRowQueryPersistence: DocumentRowQueryPersistence = {\n async listDocuments(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n },\n async findDocumentLocalIdsByContainerId(execSql, containerId) {\n // Unlike `listDocumentsByContainerIdsOrDocumentIds`, this deliberately does\n // NOT drop `HIDDEN_DOCUMENT_SUMMARY_KINDS` — it exists to reach the hidden\n // `organization_profile` document by the container it is linked to, which is\n // how a *foreign* org's display name is found on a member who synced the doc\n // under its server documentId rather than the provisioner-only local alias.\n // `documentProjection` is written and deleted in lockstep with the\n // `documents` rows (all DOCUMENTS_APP_KIND), so filtering by containerId\n // alone is sufficient — no join to `documents` is needed to select localId.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documentProjection.localId })\n .from(documentProjection)\n .where(eq(documentProjection.containerId, containerId))\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n return rows\n .map((row) => row.localId)\n .filter((localId): localId is string => localId !== null);\n },\n findLocalIdByDocumentId: (execSql, documentId) =>\n new DocumentRecordRepository(execSql).findLocalIdByDocumentId(\n DOCUMENTS_APP_KIND,\n documentId,\n ),\n async hasDocument(execSql, localId) {\n return hasDocumentRow(execSql, localId);\n },\n async documentIdentityMatches(\n execSql,\n localId,\n expectedDocumentId,\n expectedRecoveryGeneration,\n ) {\n const record = await new DocumentRecordRepository(\n execSql,\n ).loadDocumentRecord(getDocumentScope(localId));\n return (\n record?.documentId === expectedDocumentId &&\n (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration\n );\n },\n async loadDocument(execSql, localId) {\n return (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n },\n async loadDocumentContainer(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Select the row itself, not just its container, so an existing row with a\n // null container is reported as `{ containerId: null }` while a missing row\n // is reported as `undefined` — the caller relies on that distinction to know\n // whether the projection has authoritative placement to defer to.\n const projectionRows = await db\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .limit(1);\n const projectionRow = projectionRows[0];\n if (!projectionRow) {\n return undefined;\n }\n\n return { containerId: projectionRow.containerId };\n },\n};\n"]}
@@ -2,17 +2,16 @@ import { and, eq, isNull } from "drizzle-orm";
2
2
  import { documentAttachmentBlobProjection, documentPendingAttachments, } from "../../../sqlite/schema/index.js";
3
3
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
4
4
  import { runSerializedSqlMutation } from "../../../sqlite/sqlSchema.js";
5
- import { enqueueDocumentPendingUpdateWithHistory, listDocumentPendingUpdates, rekeyDocumentPendingUpdate, replaceDocumentQueuedUpdates, settleDocumentPendingUpdate, unqueueDocumentPendingUpdates, } from "../records/index.js";
6
- import { appendDocumentHistoryUpdates, listDocumentHistoryTailEntries, loadDocumentHistoryRestoreState, readDocumentHistoryTailSize, replaceDocumentHistoryCheckpoint, } from "../records/documentHistoryPersistence.js";
5
+ import { DocumentRecordRepository } from "../records/index.js";
7
6
  import { buildPendingAttachmentRow, mapLocalAttachmentRecord, mapPendingAttachmentRecord, } from "./attachmentRows.js";
8
7
  import { getDocumentScope } from "./documentRows.js";
9
8
  import { queueDocumentAttachmentStorageKeys } from "./orphanSideRows.js";
10
9
  export const documentSyncQueuePersistence = {
11
10
  async listPendingUpdates(execSql, localId) {
12
- return listDocumentPendingUpdates(execSql, getDocumentScope(localId));
11
+ return new DocumentRecordRepository(execSql).listDocumentPendingUpdates(getDocumentScope(localId));
13
12
  },
14
13
  async rekeyPendingUpdate(execSql, id) {
15
- return rekeyDocumentPendingUpdate(execSql, id);
14
+ return new DocumentRecordRepository(execSql).rekeyDocumentPendingUpdate(id);
16
15
  },
17
16
  async listPendingAttachments(execSql, localId) {
18
17
  const { db } = getClientSQLitePersistenceRuntime(execSql);
@@ -59,19 +58,19 @@ export const documentSyncQueuePersistence = {
59
58
  return rows.map(mapLocalAttachmentRecord);
60
59
  },
61
60
  async appendHistoryUpdates(execSql, input) {
62
- await appendDocumentHistoryUpdates(execSql, getDocumentScope(input.localId), input.updates, input.origin);
61
+ await new DocumentRecordRepository(execSql).appendDocumentHistoryUpdates(getDocumentScope(input.localId), input.updates, input.origin);
63
62
  },
64
63
  async loadHistoryRestoreState(execSql, localId) {
65
- return loadDocumentHistoryRestoreState(execSql, getDocumentScope(localId));
64
+ return new DocumentRecordRepository(execSql).loadDocumentHistoryRestoreState(getDocumentScope(localId));
66
65
  },
67
66
  async readHistoryTailSize(execSql, localId) {
68
- return readDocumentHistoryTailSize(execSql, getDocumentScope(localId));
67
+ return new DocumentRecordRepository(execSql).readDocumentHistoryTailSize(getDocumentScope(localId));
69
68
  },
70
69
  async listHistoryTailEntries(execSql, localId) {
71
- return listDocumentHistoryTailEntries(execSql, getDocumentScope(localId));
70
+ return new DocumentRecordRepository(execSql).listDocumentHistoryTailEntries(getDocumentScope(localId));
72
71
  },
73
72
  async replaceHistoryCheckpoint(execSql, input) {
74
- await replaceDocumentHistoryCheckpoint(execSql, getDocumentScope(input.localId), {
73
+ await new DocumentRecordRepository(execSql).replaceDocumentHistoryCheckpoint(getDocumentScope(input.localId), {
75
74
  coveredTailIds: input.coveredTailIds,
76
75
  endVersionVector: input.endVersionVector,
77
76
  ...(input.force === undefined ? {} : { force: input.force }),
@@ -83,12 +82,12 @@ export const documentSyncQueuePersistence = {
83
82
  },
84
83
  async enqueuePendingUpdate(execSql, pendingUpdate, options) {
85
84
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
86
- const pendingUpdateId = await enqueueDocumentPendingUpdateWithHistory(lockedExecSql, getDocumentScope(pendingUpdate.localId), pendingUpdate, options);
85
+ const pendingUpdateId = await new DocumentRecordRepository(lockedExecSql).enqueueDocumentPendingUpdateWithHistory(getDocumentScope(pendingUpdate.localId), pendingUpdate, options);
87
86
  return pendingUpdateId !== null;
88
87
  });
89
88
  },
90
89
  async replaceQueuedPendingUpdates(execSql, { localId, ...replacement }) {
91
- return runSerializedSqlMutation(execSql, (lockedExecSql) => replaceDocumentQueuedUpdates(lockedExecSql, getDocumentScope(localId), replacement));
90
+ return runSerializedSqlMutation(execSql, (lockedExecSql) => new DocumentRecordRepository(lockedExecSql).replaceDocumentQueuedUpdates(getDocumentScope(localId), replacement));
92
91
  },
93
92
  async saveLocalAttachment(execSql, attachment) {
94
93
  const updatedAt = new Date().toISOString();
@@ -172,12 +171,12 @@ export const documentSyncQueuePersistence = {
172
171
  },
173
172
  async deletePendingUpdate(execSql, id) {
174
173
  await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
175
- await settleDocumentPendingUpdate(lockedExecSql, id);
174
+ await new DocumentRecordRepository(lockedExecSql).settleDocumentPendingUpdate(id);
176
175
  });
177
176
  },
178
177
  async deletePendingUpdates(execSql, localId) {
179
178
  await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
180
- await unqueueDocumentPendingUpdates(lockedExecSql, getDocumentScope(localId));
179
+ await new DocumentRecordRepository(lockedExecSql).unqueueDocumentPendingUpdates(getDocumentScope(localId));
181
180
  });
182
181
  },
183
182
  async deletePendingAttachment(execSql, localId, slotId, storageKey) {
@@ -1 +1 @@
1
- {"version":3,"file":"syncQueuePersistence.js","sourceRoot":"","sources":["syncQueuePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EACL,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,wBAAwB,CAAC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,CAAC,EAAE,CAAC,0BAA0B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;iBACtD,SAAS,CAAC,EAAE,UAAU,EAAE,0BAA0B,CAAC,UAAU,EAAE,CAAC,CAAC;YACpE,MAAM,kCAAkC,CACtC,EAAE,EACF,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC,CAC5C,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, eq, isNull } from \"drizzle-orm\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport {\n enqueueDocumentPendingUpdateWithHistory,\n listDocumentPendingUpdates,\n rekeyDocumentPendingUpdate,\n replaceDocumentQueuedUpdates,\n settleDocumentPendingUpdate,\n unqueueDocumentPendingUpdates,\n} from \"../records\";\nimport {\n appendDocumentHistoryUpdates,\n listDocumentHistoryTailEntries,\n loadDocumentHistoryRestoreState,\n readDocumentHistoryTailSize,\n replaceDocumentHistoryCheckpoint,\n} from \"../records/documentHistoryPersistence\";\nimport type { DocumentsPersistence } from \"../types\";\nimport {\n buildPendingAttachmentRow,\n mapLocalAttachmentRecord,\n mapPendingAttachmentRecord,\n} from \"./attachmentRows\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\ntype DocumentSyncQueuePersistence = Pick<\n DocumentsPersistence,\n | \"listPendingUpdates\"\n | \"rekeyPendingUpdate\"\n | \"listPendingAttachments\"\n | \"listLocalAttachments\"\n | \"appendHistoryUpdates\"\n | \"loadHistoryRestoreState\"\n | \"readHistoryTailSize\"\n | \"listHistoryTailEntries\"\n | \"replaceHistoryCheckpoint\"\n | \"enqueuePendingUpdate\"\n | \"replaceQueuedPendingUpdates\"\n | \"saveLocalAttachment\"\n | \"deleteLocalAttachment\"\n | \"markLocalAttachmentDetached\"\n | \"savePendingAttachment\"\n | \"deletePendingUpdate\"\n | \"deletePendingUpdates\"\n | \"deletePendingAttachment\"\n | \"deletePendingAttachments\"\n>;\n\nexport const documentSyncQueuePersistence: DocumentSyncQueuePersistence = {\n async listPendingUpdates(execSql, localId) {\n return listDocumentPendingUpdates(execSql, getDocumentScope(localId));\n },\n async rekeyPendingUpdate(execSql, id) {\n return rekeyDocumentPendingUpdate(execSql, id);\n },\n async listPendingAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentPendingAttachments.localId,\n slotId: documentPendingAttachments.slotId,\n name: documentPendingAttachments.name,\n mimeType: documentPendingAttachments.mimeType,\n storageKey: documentPendingAttachments.storageKey,\n byteLength: documentPendingAttachments.byteLength,\n contentSha256: documentPendingAttachments.contentSha256,\n uploadBlobId: documentPendingAttachments.uploadBlobId,\n uploadContentKey: documentPendingAttachments.uploadContentKey,\n uploadIv: documentPendingAttachments.uploadIv,\n uploadContentKeyEpoch: documentPendingAttachments.uploadContentKeyEpoch,\n uploadPartSize: documentPendingAttachments.uploadPartSize,\n uploadPlaintextSha256: documentPendingAttachments.uploadPlaintextSha256,\n uploadStageId: documentPendingAttachments.uploadStageId,\n })\n .from(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .orderBy(\n documentPendingAttachments.createdAt,\n documentPendingAttachments.slotId,\n );\n\n return rows.map(mapPendingAttachmentRecord);\n },\n // Detached rows are included on purpose: they are the durable markers the\n // next sync uses to detach the remote binding, so a restart has to restore\n // them alongside the live slots.\n async listLocalAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentAttachmentBlobProjection.localId,\n slotId: documentAttachmentBlobProjection.slotId,\n blobId: documentAttachmentBlobProjection.blobId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n mimeType: documentAttachmentBlobProjection.mimeType,\n byteLength: documentAttachmentBlobProjection.byteLength,\n contentSha256: documentAttachmentBlobProjection.contentSha256,\n detachedAt: documentAttachmentBlobProjection.detachedAt,\n })\n .from(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId));\n\n return rows.map(mapLocalAttachmentRecord);\n },\n async appendHistoryUpdates(execSql, input) {\n await appendDocumentHistoryUpdates(\n execSql,\n getDocumentScope(input.localId),\n input.updates,\n input.origin,\n );\n },\n async loadHistoryRestoreState(execSql, localId) {\n return loadDocumentHistoryRestoreState(execSql, getDocumentScope(localId));\n },\n async readHistoryTailSize(execSql, localId) {\n return readDocumentHistoryTailSize(execSql, getDocumentScope(localId));\n },\n async listHistoryTailEntries(execSql, localId) {\n return listDocumentHistoryTailEntries(execSql, getDocumentScope(localId));\n },\n async replaceHistoryCheckpoint(execSql, input) {\n await replaceDocumentHistoryCheckpoint(\n execSql,\n getDocumentScope(input.localId),\n {\n coveredTailIds: input.coveredTailIds,\n endVersionVector: input.endVersionVector,\n ...(input.force === undefined ? {} : { force: input.force }),\n snapshot: input.snapshot,\n ...(input.stillCurrent === undefined\n ? {}\n : { stillCurrent: input.stillCurrent }),\n },\n );\n },\n async enqueuePendingUpdate(execSql, pendingUpdate, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const pendingUpdateId = await enqueueDocumentPendingUpdateWithHistory(\n lockedExecSql,\n getDocumentScope(pendingUpdate.localId),\n pendingUpdate,\n options,\n );\n return pendingUpdateId !== null;\n });\n },\n async replaceQueuedPendingUpdates(execSql, { localId, ...replacement }) {\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n replaceDocumentQueuedUpdates(\n lockedExecSql,\n getDocumentScope(localId),\n replacement,\n ),\n );\n },\n async saveLocalAttachment(execSql, attachment) {\n const updatedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = {\n localId: attachment.localId,\n slotId: attachment.slotId,\n blobId: attachment.blobId,\n storageKey: attachment.storageKey,\n mimeType: attachment.mimeType,\n byteLength: attachment.byteLength,\n contentSha256: attachment.contentSha256,\n updatedAt,\n // Written on every save so re-filling a slot clears a stale detach\n // marker instead of inheriting it from the row it replaces.\n detachedAt: attachment.detachedAt,\n };\n await db\n .insert(documentAttachmentBlobProjection)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentAttachmentBlobProjection.localId,\n documentAttachmentBlobProjection.slotId,\n ],\n set: attachmentRow,\n })\n .run();\n });\n },\n async deleteLocalAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n ),\n )\n .run();\n // Another slot may hold the same hydrated copy; the reclaim deletes\n // the bytes only once no row references them.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async markLocalAttachmentDetached(execSql, localId, slotId, storageKey) {\n const detachedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documentAttachmentBlobProjection)\n .set({ detachedAt })\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n isNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n });\n },\n async savePendingAttachment(execSql, attachment) {\n const createdAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = buildPendingAttachmentRow(attachment, createdAt);\n await db\n .insert(documentPendingAttachments)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentPendingAttachments.localId,\n documentPendingAttachments.slotId,\n ],\n set: {\n name: attachmentRow.name,\n mimeType: attachmentRow.mimeType,\n storageKey: attachmentRow.storageKey,\n byteLength: attachmentRow.byteLength,\n contentSha256: attachmentRow.contentSha256,\n uploadBlobId: attachmentRow.uploadBlobId,\n uploadContentKey: attachmentRow.uploadContentKey,\n uploadIv: attachmentRow.uploadIv,\n uploadContentKeyEpoch: attachmentRow.uploadContentKeyEpoch,\n uploadPartSize: attachmentRow.uploadPartSize,\n uploadPlaintextSha256: attachmentRow.uploadPlaintextSha256,\n uploadStageId: attachmentRow.uploadStageId,\n },\n })\n .run();\n });\n },\n async deletePendingUpdate(execSql, id) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await settleDocumentPendingUpdate(lockedExecSql, id);\n });\n },\n async deletePendingUpdates(execSql, localId) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await unqueueDocumentPendingUpdates(\n lockedExecSql,\n getDocumentScope(localId),\n );\n });\n },\n async deletePendingAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentPendingAttachments)\n .where(\n and(\n eq(documentPendingAttachments.localId, localId),\n eq(documentPendingAttachments.slotId, slotId),\n eq(documentPendingAttachments.storageKey, storageKey),\n ),\n )\n .run();\n // A dropped upload may hold the last reference to its staged bytes.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async deletePendingAttachments(execSql, localId) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n const deleted = await db\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .returning({ storageKey: documentPendingAttachments.storageKey });\n await queueDocumentAttachmentStorageKeys(\n db,\n deleted.map(({ storageKey }) => storageKey),\n );\n });\n },\n};\n"]}
1
+ {"version":3,"file":"syncQueuePersistence.js","sourceRoot":"","sources":["syncQueuePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,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EAAE,OAAO;QAC7C,MAAM,iCAAiC,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE;YACxE,MAAM,OAAO,GAAG,MAAM,EAAE;iBACrB,MAAM,CAAC,0BAA0B,CAAC;iBAClC,KAAK,CAAC,EAAE,CAAC,0BAA0B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;iBACtD,SAAS,CAAC,EAAE,UAAU,EAAE,0BAA0B,CAAC,UAAU,EAAE,CAAC,CAAC;YACpE,MAAM,kCAAkC,CACtC,EAAE,EACF,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC,CAC5C,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, eq, isNull } from \"drizzle-orm\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n} from \"../../../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { DocumentsPersistence } from \"../types\";\nimport {\n buildPendingAttachmentRow,\n mapLocalAttachmentRecord,\n mapPendingAttachmentRecord,\n} from \"./attachmentRows\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\ntype DocumentSyncQueuePersistence = Pick<\n DocumentsPersistence,\n | \"listPendingUpdates\"\n | \"rekeyPendingUpdate\"\n | \"listPendingAttachments\"\n | \"listLocalAttachments\"\n | \"appendHistoryUpdates\"\n | \"loadHistoryRestoreState\"\n | \"readHistoryTailSize\"\n | \"listHistoryTailEntries\"\n | \"replaceHistoryCheckpoint\"\n | \"enqueuePendingUpdate\"\n | \"replaceQueuedPendingUpdates\"\n | \"saveLocalAttachment\"\n | \"deleteLocalAttachment\"\n | \"markLocalAttachmentDetached\"\n | \"savePendingAttachment\"\n | \"deletePendingUpdate\"\n | \"deletePendingUpdates\"\n | \"deletePendingAttachment\"\n | \"deletePendingAttachments\"\n>;\n\nexport const documentSyncQueuePersistence: DocumentSyncQueuePersistence = {\n async listPendingUpdates(execSql, localId) {\n return new DocumentRecordRepository(execSql).listDocumentPendingUpdates(\n getDocumentScope(localId),\n );\n },\n async rekeyPendingUpdate(execSql, id) {\n return new DocumentRecordRepository(execSql).rekeyDocumentPendingUpdate(id);\n },\n async listPendingAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentPendingAttachments.localId,\n slotId: documentPendingAttachments.slotId,\n name: documentPendingAttachments.name,\n mimeType: documentPendingAttachments.mimeType,\n storageKey: documentPendingAttachments.storageKey,\n byteLength: documentPendingAttachments.byteLength,\n contentSha256: documentPendingAttachments.contentSha256,\n uploadBlobId: documentPendingAttachments.uploadBlobId,\n uploadContentKey: documentPendingAttachments.uploadContentKey,\n uploadIv: documentPendingAttachments.uploadIv,\n uploadContentKeyEpoch: documentPendingAttachments.uploadContentKeyEpoch,\n uploadPartSize: documentPendingAttachments.uploadPartSize,\n uploadPlaintextSha256: documentPendingAttachments.uploadPlaintextSha256,\n uploadStageId: documentPendingAttachments.uploadStageId,\n })\n .from(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .orderBy(\n documentPendingAttachments.createdAt,\n documentPendingAttachments.slotId,\n );\n\n return rows.map(mapPendingAttachmentRecord);\n },\n // Detached rows are included on purpose: they are the durable markers the\n // next sync uses to detach the remote binding, so a restart has to restore\n // them alongside the live slots.\n async listLocalAttachments(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n localId: documentAttachmentBlobProjection.localId,\n slotId: documentAttachmentBlobProjection.slotId,\n blobId: documentAttachmentBlobProjection.blobId,\n storageKey: documentAttachmentBlobProjection.storageKey,\n mimeType: documentAttachmentBlobProjection.mimeType,\n byteLength: documentAttachmentBlobProjection.byteLength,\n contentSha256: documentAttachmentBlobProjection.contentSha256,\n detachedAt: documentAttachmentBlobProjection.detachedAt,\n })\n .from(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId));\n\n return rows.map(mapLocalAttachmentRecord);\n },\n async appendHistoryUpdates(execSql, input) {\n await new DocumentRecordRepository(execSql).appendDocumentHistoryUpdates(\n getDocumentScope(input.localId),\n input.updates,\n input.origin,\n );\n },\n async loadHistoryRestoreState(execSql, localId) {\n return new DocumentRecordRepository(\n execSql,\n ).loadDocumentHistoryRestoreState(getDocumentScope(localId));\n },\n async readHistoryTailSize(execSql, localId) {\n return new DocumentRecordRepository(execSql).readDocumentHistoryTailSize(\n getDocumentScope(localId),\n );\n },\n async listHistoryTailEntries(execSql, localId) {\n return new DocumentRecordRepository(execSql).listDocumentHistoryTailEntries(\n getDocumentScope(localId),\n );\n },\n async replaceHistoryCheckpoint(execSql, input) {\n await new DocumentRecordRepository(\n execSql,\n ).replaceDocumentHistoryCheckpoint(getDocumentScope(input.localId), {\n coveredTailIds: input.coveredTailIds,\n endVersionVector: input.endVersionVector,\n ...(input.force === undefined ? {} : { force: input.force }),\n snapshot: input.snapshot,\n ...(input.stillCurrent === undefined\n ? {}\n : { stillCurrent: input.stillCurrent }),\n });\n },\n async enqueuePendingUpdate(execSql, pendingUpdate, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n const pendingUpdateId = await new DocumentRecordRepository(\n lockedExecSql,\n ).enqueueDocumentPendingUpdateWithHistory(\n getDocumentScope(pendingUpdate.localId),\n pendingUpdate,\n options,\n );\n return pendingUpdateId !== null;\n });\n },\n async replaceQueuedPendingUpdates(execSql, { localId, ...replacement }) {\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n new DocumentRecordRepository(lockedExecSql).replaceDocumentQueuedUpdates(\n getDocumentScope(localId),\n replacement,\n ),\n );\n },\n async saveLocalAttachment(execSql, attachment) {\n const updatedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = {\n localId: attachment.localId,\n slotId: attachment.slotId,\n blobId: attachment.blobId,\n storageKey: attachment.storageKey,\n mimeType: attachment.mimeType,\n byteLength: attachment.byteLength,\n contentSha256: attachment.contentSha256,\n updatedAt,\n // Written on every save so re-filling a slot clears a stale detach\n // marker instead of inheriting it from the row it replaces.\n detachedAt: attachment.detachedAt,\n };\n await db\n .insert(documentAttachmentBlobProjection)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentAttachmentBlobProjection.localId,\n documentAttachmentBlobProjection.slotId,\n ],\n set: attachmentRow,\n })\n .run();\n });\n },\n async deleteLocalAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n ),\n )\n .run();\n // Another slot may hold the same hydrated copy; the reclaim deletes\n // the bytes only once no row references them.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async markLocalAttachmentDetached(execSql, localId, slotId, storageKey) {\n const detachedAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n await db\n .update(documentAttachmentBlobProjection)\n .set({ detachedAt })\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, slotId),\n eq(documentAttachmentBlobProjection.storageKey, storageKey),\n isNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n });\n },\n async savePendingAttachment(execSql, attachment) {\n const createdAt = new Date().toISOString();\n\n await getClientSQLitePersistenceRuntime(execSql).runMutation(async (db) => {\n const attachmentRow = buildPendingAttachmentRow(attachment, createdAt);\n await db\n .insert(documentPendingAttachments)\n .values(attachmentRow)\n .onConflictDoUpdate({\n target: [\n documentPendingAttachments.localId,\n documentPendingAttachments.slotId,\n ],\n set: {\n name: attachmentRow.name,\n mimeType: attachmentRow.mimeType,\n storageKey: attachmentRow.storageKey,\n byteLength: attachmentRow.byteLength,\n contentSha256: attachmentRow.contentSha256,\n uploadBlobId: attachmentRow.uploadBlobId,\n uploadContentKey: attachmentRow.uploadContentKey,\n uploadIv: attachmentRow.uploadIv,\n uploadContentKeyEpoch: attachmentRow.uploadContentKeyEpoch,\n uploadPartSize: attachmentRow.uploadPartSize,\n uploadPlaintextSha256: attachmentRow.uploadPlaintextSha256,\n uploadStageId: attachmentRow.uploadStageId,\n },\n })\n .run();\n });\n },\n async deletePendingUpdate(execSql, id) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).settleDocumentPendingUpdate(id);\n });\n },\n async deletePendingUpdates(execSql, localId) {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await new DocumentRecordRepository(\n lockedExecSql,\n ).unqueueDocumentPendingUpdates(getDocumentScope(localId));\n });\n },\n async deletePendingAttachment(execSql, localId, slotId, storageKey) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n await db\n .delete(documentPendingAttachments)\n .where(\n and(\n eq(documentPendingAttachments.localId, localId),\n eq(documentPendingAttachments.slotId, slotId),\n eq(documentPendingAttachments.storageKey, storageKey),\n ),\n )\n .run();\n // A dropped upload may hold the last reference to its staged bytes.\n await queueDocumentAttachmentStorageKeys(db, [storageKey]);\n });\n },\n async deletePendingAttachments(execSql, localId) {\n await getClientSQLitePersistenceRuntime(execSql).transaction(async (db) => {\n const deleted = await db\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .returning({ storageKey: documentPendingAttachments.storageKey });\n await queueDocumentAttachmentStorageKeys(\n db,\n deleted.map(({ storageKey }) => storageKey),\n );\n });\n },\n};\n"]}