@tearleads/client-sdk 0.1.259 → 0.1.261

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 (39) hide show
  1. package/data/blobs/attachments/types.d.ts +3 -1
  2. package/data/blobs/attachments/types.js.map +1 -1
  3. package/data/documents/documentContent.d.ts +1 -0
  4. package/data/documents/documentContent.js +8 -0
  5. package/data/documents/documentContent.js.map +1 -1
  6. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -0
  7. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  8. package/data/persistence/documents/internal/discardDocument.js +6 -1
  9. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  10. package/data/persistence/documents/internal/documentMutationPersistence.js +1 -0
  11. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  12. package/data/persistence/documents/internal/documentRows.js +3 -0
  13. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  14. package/data/persistence/documents/types.d.ts +2 -0
  15. package/data/persistence/documents/types.js.map +1 -1
  16. package/data/sqlite/migrations/localSchemaMigrations.js +9 -0
  17. package/data/sqlite/migrations/localSchemaMigrations.js.map +1 -1
  18. package/data/sqlite/schema/documentProjectionSchema.js +12 -2
  19. package/data/sqlite/schema/documentProjectionSchema.js.map +1 -1
  20. package/package.json +1 -1
  21. package/workflows/blobs/hydration/hydrate.js +3 -1
  22. package/workflows/blobs/hydration/hydrate.js.map +1 -1
  23. package/workflows/container-contents/info/blobInfo.js +38 -124
  24. package/workflows/container-contents/info/blobInfo.js.map +1 -1
  25. package/workflows/container-contents/info/blobInfoReferenceQuery.js +109 -0
  26. package/workflows/container-contents/info/blobInfoReferenceQuery.js.map +1 -0
  27. package/workflows/documents/attachments/attachmentFilenameBackfill.d.ts +2 -0
  28. package/workflows/documents/attachments/attachmentFilenameBackfill.js +65 -0
  29. package/workflows/documents/attachments/attachmentFilenameBackfill.js.map +1 -0
  30. package/workflows/documents/create/documentCreationPersistence.js +6 -8
  31. package/workflows/documents/create/documentCreationPersistence.js.map +1 -1
  32. package/workflows/documents/documentMutationCommit.js +13 -18
  33. package/workflows/documents/documentMutationCommit.js.map +1 -1
  34. package/workflows/documents/historyContent.d.ts +1 -0
  35. package/workflows/documents/historyContent.js +14 -8
  36. package/workflows/documents/historyContent.js.map +1 -1
  37. package/workflows/documents/index.d.ts +1 -0
  38. package/workflows/documents/index.js +1 -0
  39. package/workflows/documents/index.js.map +1 -1
@@ -41,7 +41,9 @@ export interface DocumentAttachmentHydrationApi {
41
41
  evictDocumentWriterProjection?(documentId: string): void;
42
42
  getBlobBytes(blobId: string, options?: RequestResultOptions): Promise<BlobBytesResponse | null>;
43
43
  getDocumentWriterProjection(documentId: string): Promise<DocumentWriterProjectionResponse | null>;
44
- listDocumentAttachments(documentId: string): Promise<ListDocumentAttachmentsResponse | null>;
44
+ listDocumentAttachments(documentId: string, options?: {
45
+ readonly refresh?: boolean;
46
+ }): Promise<ListDocumentAttachmentsResponse | null>;
45
47
  }
46
48
  export type { BlobContentKeyTarget };
47
49
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAqCA,MAAM,CAAC,MAAM,mCAAmC,GAC9C,wCAAwC,CAAC;AAC3C,MAAM,CAAC,MAAM,8BAA8B,GACzC,mCAAmC,CAAC;AACtC,MAAM,CAAC,MAAM,gCAAgC,GAC3C,qCAAqC,CAAC;AACxC,MAAM,CAAC,MAAM,6BAA6B,GACxC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,yCAAyC,CAAC,CAAC;AACtE,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type {\n BlobBytesResponse,\n RequestFailureKind,\n RequestResultOptions,\n UploadMultipartBlobPartBytesRequest,\n} from \"@tearleads/api-client\";\nimport type {\n BlobContentKeyTarget,\n BlobEnvelopeHeaderRecord,\n BlobEnvelopeRecord,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n BlobContentKeyBundleRequest,\n DocumentSyncRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n InitiateMultipartBlobStageResponse,\n ListDocumentAttachmentsResponse,\n MultipartBlobStageStatusResponse,\n UploadMultipartBlobPartResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateAuthor } from \"../../documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { BlobByteSourceInput, BlobBytes } from \"../blobContracts\";\n\nexport const BLOB_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.blob.content-record-key-info\";\nexport const BLOB_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.blob.content-record-aad\";\nexport const BLOB_CONTENT_RECORD_NONCE_DOMAIN =\n \"tearleads.blob.content-record-nonce\";\nexport const BLOB_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.blob.content-record-hkdf-salt\");\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport interface BlobAttachmentRequestOptions {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n}\n\nexport interface BlobAttachmentApi {\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentBindResponse | null>;\n clearWriterProjectionCaches?(): void;\n evictDocumentWriterProjection?(documentId: string): void;\n getRequestFailure?(input: {\n method: \"DELETE\" | \"GET\" | \"POST\" | \"PUT\";\n path: string;\n }): {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly status: number | null;\n } | null;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getMultipartBlobStage(\n stageId: string,\n options?: RequestResultOptions,\n ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n options?: RequestResultOptions,\n ): Promise<InitiateMultipartBlobStageResponse | null>;\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options?: RequestResultOptions,\n ): Promise<UploadMultipartBlobPartResponse | null>;\n}\n\nexport interface BlobAttachmentDetachApi {\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentDetachResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n}\n\nexport interface DocumentAttachmentHydrationApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getBlobBytes(\n blobId: string,\n options?: RequestResultOptions,\n ): Promise<BlobBytesResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n listDocumentAttachments(\n documentId: string,\n ): Promise<ListDocumentAttachmentsResponse | null>;\n}\n\nexport type { BlobContentKeyTarget };\n\n/**\n * Aliases of the crypto parser's own types. The parser is shared with the API,\n * so restating these shapes here would let the two drift apart silently.\n */\nexport type BlobEncryptedBytesRecord = BlobEnvelopeRecord;\n\n/**\n * The envelope as the header establishes it. Streaming readers hold this\n * before any ciphertext is read, so it has no `chunks`: an empty array there\n * would read as an empty object rather than an unread one.\n */\nexport type BlobEncryptedBytesHeader = BlobEnvelopeHeaderRecord;\n\nexport type BlobEncryptedChunk = BlobEnvelopeRecord[\"chunks\"][number];\n\nexport interface BlobSourceSnapshot {\n readonly byteLength: number;\n readonly chunkSha256: readonly string[];\n readonly chunkSize: number;\n readonly sha256: string;\n}\n\nexport interface BlobEncryptionPlan {\n readonly byteLength: number;\n readonly chunkSize: number;\n readonly metadataHash: string;\n readonly partCount: number;\n readonly plaintextByteLength: number;\n readonly plaintextSha256: string;\n readonly sha256: string;\n encryptPart(index: number): Promise<BlobBytes>;\n getPartByteLength(index: number): number;\n}\n\nexport interface DocumentManifestIdentity {\n documentId: string;\n manifestHash: string;\n organizationId: string;\n}\n\nexport interface BlobAttachmentMaterial {\n blobAccessManifestHash: string;\n contentKeyBundle: BlobContentKeyBundleRequest;\n encrypted: BlobEncryptionPlan;\n manifestIdentity: DocumentManifestIdentity;\n targetHash: string;\n targets: BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/**\n * Progress for an in-flight multipart blob upload.\n */\nexport interface MultipartUploadProgress {\n readonly bytesTotal: number;\n readonly bytesUploaded: number;\n readonly partsCompleted: number;\n readonly partsTotal: number;\n}\n\nexport type MultipartUploadProgressListener = (\n progress: MultipartUploadProgress,\n) => void;\n\n/**\n * Fires once a multipart stage has been opened (or resumed), with its id and\n * plaintext chunk size. Callers persist both so a later attempt can reproduce\n * the same encrypted parts and resume instead of orphaning the partial upload.\n */\nexport type MultipartStageResolvedListener = (input: {\n readonly partSize: number;\n readonly stageId: string;\n}) => void | Promise<void>;\n\n/** One upload; the service supplies the API, executor, and secret key. */\nexport interface UploadDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n blobId?: string | undefined;\n bindingId?: string | undefined;\n bytes: BlobByteSourceInput;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId: string;\n /**\n * The document's deferred first update for the bind to commit after its\n * binding. A bind refused with it is sent once more without it, and the\n * caller's queued row then syncs on its own.\n */\n documentSync?: DocumentSyncRequest | undefined;\n eventId?: string | undefined;\n expectedBindingId: string | null;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n // A persisted nonce seed. The plaintext digest derives the envelope IV from\n // it, then each chunk derives a unique IV. Same-source retries reproduce the\n // encrypted parts; changed bytes cannot reuse their AES-GCM nonces.\n nonceSeed?: Uint8Array | undefined;\n multipart?: MultipartBlobUploadOptions | undefined;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface MultipartBlobUploadOptions {\n /** Exactly 5 MiB per plaintext encryption chunk; transport parts include envelope overhead. */\n readonly partSize: number;\n // The id of a previously opened stage to resume. When set, the upload refetches\n // that stage and skips parts the server already has instead of opening a new\n // one; if the stage is gone (expired), it falls back to a fresh stage.\n readonly resumeStageId?: string | undefined;\n readonly uploadConcurrency?: number | undefined;\n}\n\nexport interface UploadDocumentAttachmentResult {\n blobId: string;\n bindingId: string;\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One detach; the service supplies the API and executor. */\nexport interface DetachDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId?: string | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface DetachDocumentAttachmentResult {\n request: BlobAttachmentDetachRequest;\n response: BlobAttachmentDetachResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DecryptDocumentAttachmentBlobInput {\n binding: BlobAttachmentSummary;\n encryptedBytes: BlobBytes;\n expectedDocumentId: string;\n expectedSlotId: string;\n execSql: ExecSql;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n targetSecretKey: Uint8Array;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One decrypt; the service supplies the executor and its secret key. */\nexport type DecryptDocumentAttachmentBlobRequest = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"execSql\" | \"targetSecretKey\"\n>;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AAqCA,MAAM,CAAC,MAAM,mCAAmC,GAC9C,wCAAwC,CAAC;AAC3C,MAAM,CAAC,MAAM,8BAA8B,GACzC,mCAAmC,CAAC;AACtC,MAAM,CAAC,MAAM,gCAAgC,GAC3C,qCAAqC,CAAC;AACxC,MAAM,CAAC,MAAM,6BAA6B,GACxC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,yCAAyC,CAAC,CAAC;AACtE,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type {\n BlobBytesResponse,\n RequestFailureKind,\n RequestResultOptions,\n UploadMultipartBlobPartBytesRequest,\n} from \"@tearleads/api-client\";\nimport type {\n BlobContentKeyTarget,\n BlobEnvelopeHeaderRecord,\n BlobEnvelopeRecord,\n WriteHeader,\n} from \"@tearleads/crypto\";\nimport type {\n BlobAttachmentBindRequest,\n BlobAttachmentDetachRequest,\n BlobContentKeyBundleRequest,\n DocumentSyncRequest,\n InitiateMultipartBlobStageRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n BlobAttachmentBindResponse,\n BlobAttachmentDetachResponse,\n BlobAttachmentSummary,\n DocumentWriterProjectionResponse,\n InitiateMultipartBlobStageResponse,\n ListDocumentAttachmentsResponse,\n MultipartBlobStageStatusResponse,\n UploadMultipartBlobPartResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateAuthor } from \"../../documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../keyingProjectionVerification\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { BlobByteSourceInput, BlobBytes } from \"../blobContracts\";\n\nexport const BLOB_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.blob.content-record-key-info\";\nexport const BLOB_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.blob.content-record-aad\";\nexport const BLOB_CONTENT_RECORD_NONCE_DOMAIN =\n \"tearleads.blob.content-record-nonce\";\nexport const BLOB_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.blob.content-record-hkdf-salt\");\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport interface BlobAttachmentRequestOptions {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n}\n\nexport interface BlobAttachmentApi {\n bindBlobAttachment(\n blobId: string,\n input: BlobAttachmentBindRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentBindResponse | null>;\n clearWriterProjectionCaches?(): void;\n evictDocumentWriterProjection?(documentId: string): void;\n getRequestFailure?(input: {\n method: \"DELETE\" | \"GET\" | \"POST\" | \"PUT\";\n path: string;\n }): {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly status: number | null;\n } | null;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getMultipartBlobStage(\n stageId: string,\n options?: RequestResultOptions,\n ): Promise<MultipartBlobStageStatusResponse | null>;\n initiateMultipartBlobStage(\n input: InitiateMultipartBlobStageRequest,\n options?: RequestResultOptions,\n ): Promise<InitiateMultipartBlobStageResponse | null>;\n uploadMultipartBlobPartBytes(\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n options?: RequestResultOptions,\n ): Promise<UploadMultipartBlobPartResponse | null>;\n}\n\nexport interface BlobAttachmentDetachApi {\n detachBlobAttachment(\n blobId: string,\n bindingId: string,\n input: BlobAttachmentDetachRequest,\n options?: BlobAttachmentRequestOptions,\n ): Promise<BlobAttachmentDetachResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n}\n\nexport interface DocumentAttachmentHydrationApi {\n evictDocumentWriterProjection?(documentId: string): void;\n getBlobBytes(\n blobId: string,\n options?: RequestResultOptions,\n ): Promise<BlobBytesResponse | null>;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n listDocumentAttachments(\n documentId: string,\n options?: { readonly refresh?: boolean },\n ): Promise<ListDocumentAttachmentsResponse | null>;\n}\n\nexport type { BlobContentKeyTarget };\n\n/**\n * Aliases of the crypto parser's own types. The parser is shared with the API,\n * so restating these shapes here would let the two drift apart silently.\n */\nexport type BlobEncryptedBytesRecord = BlobEnvelopeRecord;\n\n/**\n * The envelope as the header establishes it. Streaming readers hold this\n * before any ciphertext is read, so it has no `chunks`: an empty array there\n * would read as an empty object rather than an unread one.\n */\nexport type BlobEncryptedBytesHeader = BlobEnvelopeHeaderRecord;\n\nexport type BlobEncryptedChunk = BlobEnvelopeRecord[\"chunks\"][number];\n\nexport interface BlobSourceSnapshot {\n readonly byteLength: number;\n readonly chunkSha256: readonly string[];\n readonly chunkSize: number;\n readonly sha256: string;\n}\n\nexport interface BlobEncryptionPlan {\n readonly byteLength: number;\n readonly chunkSize: number;\n readonly metadataHash: string;\n readonly partCount: number;\n readonly plaintextByteLength: number;\n readonly plaintextSha256: string;\n readonly sha256: string;\n encryptPart(index: number): Promise<BlobBytes>;\n getPartByteLength(index: number): number;\n}\n\nexport interface DocumentManifestIdentity {\n documentId: string;\n manifestHash: string;\n organizationId: string;\n}\n\nexport interface BlobAttachmentMaterial {\n blobAccessManifestHash: string;\n contentKeyBundle: BlobContentKeyBundleRequest;\n encrypted: BlobEncryptionPlan;\n manifestIdentity: DocumentManifestIdentity;\n targetHash: string;\n targets: BlobContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/**\n * Progress for an in-flight multipart blob upload.\n */\nexport interface MultipartUploadProgress {\n readonly bytesTotal: number;\n readonly bytesUploaded: number;\n readonly partsCompleted: number;\n readonly partsTotal: number;\n}\n\nexport type MultipartUploadProgressListener = (\n progress: MultipartUploadProgress,\n) => void;\n\n/**\n * Fires once a multipart stage has been opened (or resumed), with its id and\n * plaintext chunk size. Callers persist both so a later attempt can reproduce\n * the same encrypted parts and resume instead of orphaning the partial upload.\n */\nexport type MultipartStageResolvedListener = (input: {\n readonly partSize: number;\n readonly stageId: string;\n}) => void | Promise<void>;\n\n/** One upload; the service supplies the API, executor, and secret key. */\nexport interface UploadDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n blobId?: string | undefined;\n bindingId?: string | undefined;\n bytes: BlobByteSourceInput;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId: string;\n /**\n * The document's deferred first update for the bind to commit after its\n * binding. A bind refused with it is sent once more without it, and the\n * caller's queued row then syncs on its own.\n */\n documentSync?: DocumentSyncRequest | undefined;\n eventId?: string | undefined;\n expectedBindingId: string | null;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n // A persisted nonce seed. The plaintext digest derives the envelope IV from\n // it, then each chunk derives a unique IV. Same-source retries reproduce the\n // encrypted parts; changed bytes cannot reuse their AES-GCM nonces.\n nonceSeed?: Uint8Array | undefined;\n multipart?: MultipartBlobUploadOptions | undefined;\n onMultipartProgress?: MultipartUploadProgressListener | undefined;\n onStageResolved?: MultipartStageResolvedListener | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface MultipartBlobUploadOptions {\n /** Exactly 5 MiB per plaintext encryption chunk; transport parts include envelope overhead. */\n readonly partSize: number;\n // The id of a previously opened stage to resume. When set, the upload refetches\n // that stage and skips parts the server already has instead of opening a new\n // one; if the stage is gone (expired), it falls back to a fresh stage.\n readonly resumeStageId?: string | undefined;\n readonly uploadConcurrency?: number | undefined;\n}\n\nexport interface UploadDocumentAttachmentResult {\n blobId: string;\n bindingId: string;\n request: BlobAttachmentBindRequest;\n response: BlobAttachmentBindResponse;\n sha256: string;\n byteLength: number;\n writeHeader: WriteHeader;\n writeHeaderHash: string;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One detach; the service supplies the API and executor. */\nexport interface DetachDocumentAttachmentRequest {\n author: DocumentCreateAuthor;\n bindingId: string;\n blobId: string;\n documentId: string;\n eventId?: string | undefined;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n slotId: string;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection?: DocumentWriterProjectionResponse | undefined;\n}\n\nexport interface DetachDocumentAttachmentResult {\n request: BlobAttachmentDetachRequest;\n response: BlobAttachmentDetachResponse;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DecryptDocumentAttachmentBlobInput {\n binding: BlobAttachmentSummary;\n encryptedBytes: BlobBytes;\n expectedDocumentId: string;\n expectedSlotId: string;\n execSql: ExecSql;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n targetSecretKey: Uint8Array;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\n/** One decrypt; the service supplies the executor and its secret key. */\nexport type DecryptDocumentAttachmentBlobRequest = Omit<\n DecryptDocumentAttachmentBlobInput,\n \"execSql\" | \"targetSecretKey\"\n>;\n"]}
@@ -11,6 +11,7 @@ export declare function readSeedTag(doc: StructuredDocumentShape): string | unde
11
11
  export declare function writeSeedTag(doc: StructuredDocumentShape, tag: string): void;
12
12
  export declare function ensureDocumentAttachmentStructure(doc: StructuredDocumentShape): void;
13
13
  export declare function getDocumentAttachments(doc: StructuredDocumentShape): DocumentAttachment[];
14
+ export declare function serializeDocumentAttachmentNames(doc: StructuredDocumentShape): string;
14
15
  export declare function addDocumentAttachments(doc: StructuredDocumentShape, attachments: ReadonlyArray<DocumentAttachment>): void;
15
16
  export declare function removeDocumentAttachment(doc: StructuredDocumentShape, slotId: string): void;
16
17
  export declare function sameDocumentAttachments(left: ReadonlyArray<DocumentAttachment>, right: ReadonlyArray<DocumentAttachment>): boolean;
@@ -87,6 +87,14 @@ function getStructuredDocumentAttachments(doc) {
87
87
  export function getDocumentAttachments(doc) {
88
88
  return getStructuredDocumentAttachments(doc);
89
89
  }
90
+ // The fixed-length digest keeps a held copy from inheriting the name of
91
+ // different bytes that later occupy its slot.
92
+ export function serializeDocumentAttachmentNames(doc) {
93
+ return JSON.stringify(Object.fromEntries(getDocumentAttachments(doc).map(({ contentSha256, slotId, name }) => [
94
+ `${contentSha256}:${slotId}`,
95
+ { name, search: name.toLowerCase() },
96
+ ])));
97
+ }
90
98
  export function addDocumentAttachments(doc, attachments) {
91
99
  if (attachments.length === 0) {
92
100
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"documentContent.js","sourceRoot":"","sources":["documentContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAkB1C,MAAM,wBAAwB,GAAG,SAAS,CAAC;AAC3C,MAAM,qBAAqB,GAAG,aAAa,CAAC;AAE5C,MAAM,U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L,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;QAC5B,IAAI,CAAC,KAAK,CAAC,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE;YAC/B,MAAM,cAAc,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YACpC,OAAO,CACL,cAAc,KAAK,SAAS;gBAC5B,UAAU,CAAC,MAAM,KAAK,cAAc,CAAC,MAAM;gBAC3C,UAAU,CAAC,aAAa,KAAK,cAAc,CAAC,aAAa;gBACzD,UAAU,CAAC,IAAI,KAAK,cAAc,CAAC,IAAI;gBACvC,UAAU,CAAC,UAAU,KAAK,cAAc,CAAC,UAAU;gBACnD,UAAU,CAAC,QAAQ,KAAK,cAAc,CAAC,QAAQ,CAChD,CAAC;QACJ,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { compareCanonicalStrings } from \"@tearleads/crypto\";\nimport { LoroMap } from \"@tearleads/loro\";\nimport type {\n StructuredDocumentShape as FullStructuredDocumentShape,\n StructuredDocumentMap,\n} from \"./documentKinds\";\n\nexport interface DocumentAttachment {\n contentSha256: string;\n slotId: string;\n name: string;\n byteLength: number;\n mimeType: string | null;\n}\n\n// Attachment helpers only read/write maps, so callers may pass any shape that\n// provides `getMap` (a full structured document included).\ntype StructuredDocumentShape = Pick<FullStructuredDocumentShape, \"getMap\">;\n\nconst DOCUMENT_CONTENT_MAP_KEY = \"content\";\nconst ATTACHMENT_KEY_PREFIX = \"attachment:\";\n\nexport function readSeedTag(doc: StructuredDocumentShape): string | undefined {\n const value = doc.getMap(DOCUMENT_CONTENT_MAP_KEY).get(\"seedTag\");\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport function writeSeedTag(doc: StructuredDocumentShape, tag: string): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY).set(\"seedTag\", tag);\n}\n\nfunction isStructuredAttachmentMap(\n value: unknown,\n): value is StructuredDocumentMap {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"entries\" in value &&\n typeof value.entries === \"function\" &&\n \"get\" in value &&\n typeof value.get === \"function\" &&\n \"set\" in value &&\n typeof value.set === \"function\" &&\n \"delete\" in value &&\n typeof value.delete === \"function\"\n );\n}\n\nfunction parseStructuredAttachment(\n slotId: string,\n value: unknown,\n): (DocumentAttachment & { order: number | null }) | null {\n if (!isStructuredAttachmentMap(value)) {\n return null;\n }\n\n const contentSha256 = value.get(\"contentSha256\");\n const name = value.get(\"name\");\n const byteLength = value.get(\"byteLength\");\n const mimeType = value.get(\"mimeType\");\n const order = value.get(\"order\");\n\n if (\n typeof contentSha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/.test(contentSha256) ||\n typeof name !== \"string\" ||\n name.length === 0 ||\n typeof byteLength !== \"number\" ||\n !Number.isInteger(byteLength) ||\n byteLength < 0 ||\n !(\n mimeType === undefined ||\n mimeType === null ||\n typeof mimeType === \"string\"\n )\n ) {\n return null;\n }\n\n return {\n contentSha256,\n byteLength,\n mimeType: mimeType ?? null,\n name,\n order: typeof order === \"number\" && Number.isFinite(order) ? order : null,\n slotId,\n };\n}\n\nexport function ensureDocumentAttachmentStructure(\n doc: StructuredDocumentShape,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n}\n\nfunction getAttachmentMapKey(slotId: string): string {\n return `${ATTACHMENT_KEY_PREFIX}${slotId}`;\n}\n\nfunction listStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): Array<DocumentAttachment & { order: number | null }> {\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n return documentMap\n .entries()\n .flatMap(([key, value]) => {\n if (!key.startsWith(ATTACHMENT_KEY_PREFIX)) {\n return [];\n }\n\n const attachment = parseStructuredAttachment(\n key.slice(ATTACHMENT_KEY_PREFIX.length),\n value,\n );\n return attachment ? [attachment] : [];\n })\n .sort((left, right) => {\n if (left.order !== right.order) {\n if (left.order === null) {\n return 1;\n }\n\n if (right.order === null) {\n return -1;\n }\n\n return left.order - right.order;\n }\n\n return compareCanonicalStrings(left.slotId, right.slotId);\n });\n}\n\nfunction getStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return listStructuredDocumentAttachments(doc).map(\n ({ order: _order, ...attachment }) => attachment,\n );\n}\n\nexport function getDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return getStructuredDocumentAttachments(doc);\n}\n\nexport function addDocumentAttachments(\n doc: StructuredDocumentShape,\n attachments: ReadonlyArray<DocumentAttachment>,\n): void {\n if (attachments.length === 0) {\n return;\n }\n\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n const existingAttachments = listStructuredDocumentAttachments(doc);\n let nextOrder =\n existingAttachments.reduce((highestOrder, attachment, index) => {\n return Math.max(highestOrder, attachment.order ?? index);\n }, -1) + 1;\n\n for (const attachment of attachments) {\n const attachmentMap = documentMap.getOrCreateContainer(\n getAttachmentMapKey(attachment.slotId),\n new LoroMap(),\n );\n attachmentMap.set(\"contentSha256\", attachment.contentSha256);\n attachmentMap.set(\"name\", attachment.name);\n attachmentMap.set(\"byteLength\", attachment.byteLength);\n if (attachment.mimeType === null) {\n attachmentMap.delete(\"mimeType\");\n } else {\n attachmentMap.set(\"mimeType\", attachment.mimeType);\n }\n if (attachmentMap.get(\"order\") === undefined) {\n attachmentMap.set(\"order\", nextOrder);\n nextOrder += 1;\n }\n }\n}\n\nexport function removeDocumentAttachment(\n doc: StructuredDocumentShape,\n slotId: string,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY).delete(getAttachmentMapKey(slotId));\n}\n\nexport function sameDocumentAttachments(\n left: ReadonlyArray<DocumentAttachment>,\n right: ReadonlyArray<DocumentAttachment>,\n): boolean {\n return (\n left.length === right.length &&\n left.every((attachment, index) => {\n const nextAttachment = right[index];\n return (\n nextAttachment !== undefined &&\n attachment.slotId === nextAttachment.slotId &&\n attachment.contentSha256 === nextAttachment.contentSha256 &&\n attachment.name === nextAttachment.name &&\n attachment.byteLength === nextAttachment.byteLength &&\n attachment.mimeType === nextAttachment.mimeType\n );\n })\n );\n}\n"]}
1
+ {"version":3,"file":"documentContent.js","sourceRoot":"","sources":["documentContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAkB1C,MAAM,wBAAwB,GAAG,SAAS,CAAC;AAC3C,MAAM,qBAAqB,GAAG,aAAa,CAAC;AAE5C,MAAM,UAAU,WAAW,CAAC,GAA4B;IACtD,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAClE,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAA4B,EAAE,GAAW;IACpE,GAAG,CAAC,MAAM,CAAC,wBAAwB,CAAC,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;AAC3D,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAc;IAEd,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,SAAS,IAAI,KAAK;QAClB,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU;QACnC,KAAK,IAAI,KAAK;QACd,OAAO,KAAK,CAAC,GAAG,KAAK,UAAU;QAC/B,KAAK,IAAI,KAAK;QACd,OAAO,KAAK,CAAC,GAAG,KAAK,UAAU;QAC/B,QAAQ,IAAI,KAAK;QACjB,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU,CACnC,CAAC;AACJ,CAAC;AAED,SAAS,yBAAyB,CAChC,MAAc,EACd,KAAc;IAEd,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,M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CanonicalStrings } from \"@tearleads/crypto\";\nimport { LoroMap } from \"@tearleads/loro\";\nimport type {\n StructuredDocumentShape as FullStructuredDocumentShape,\n StructuredDocumentMap,\n} from \"./documentKinds\";\n\nexport interface DocumentAttachment {\n contentSha256: string;\n slotId: string;\n name: string;\n byteLength: number;\n mimeType: string | null;\n}\n\n// Attachment helpers only read/write maps, so callers may pass any shape that\n// provides `getMap` (a full structured document included).\ntype StructuredDocumentShape = Pick<FullStructuredDocumentShape, \"getMap\">;\n\nconst DOCUMENT_CONTENT_MAP_KEY = \"content\";\nconst ATTACHMENT_KEY_PREFIX = \"attachment:\";\n\nexport function readSeedTag(doc: StructuredDocumentShape): string | undefined {\n const value = doc.getMap(DOCUMENT_CONTENT_MAP_KEY).get(\"seedTag\");\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport function writeSeedTag(doc: StructuredDocumentShape, tag: string): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY).set(\"seedTag\", tag);\n}\n\nfunction isStructuredAttachmentMap(\n value: unknown,\n): value is StructuredDocumentMap {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"entries\" in value &&\n typeof value.entries === \"function\" &&\n \"get\" in value &&\n typeof value.get === \"function\" &&\n \"set\" in value &&\n typeof value.set === \"function\" &&\n \"delete\" in value &&\n typeof value.delete === \"function\"\n );\n}\n\nfunction parseStructuredAttachment(\n slotId: string,\n value: unknown,\n): (DocumentAttachment & { order: number | null }) | null {\n if (!isStructuredAttachmentMap(value)) {\n return null;\n }\n\n const contentSha256 = value.get(\"contentSha256\");\n const name = value.get(\"name\");\n const byteLength = value.get(\"byteLength\");\n const mimeType = value.get(\"mimeType\");\n const order = value.get(\"order\");\n\n if (\n typeof contentSha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/.test(contentSha256) ||\n typeof name !== \"string\" ||\n name.length === 0 ||\n typeof byteLength !== \"number\" ||\n !Number.isInteger(byteLength) ||\n byteLength < 0 ||\n !(\n mimeType === undefined ||\n mimeType === null ||\n typeof mimeType === \"string\"\n )\n ) {\n return null;\n }\n\n return {\n contentSha256,\n byteLength,\n mimeType: mimeType ?? null,\n name,\n order: typeof order === \"number\" && Number.isFinite(order) ? order : null,\n slotId,\n };\n}\n\nexport function ensureDocumentAttachmentStructure(\n doc: StructuredDocumentShape,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n}\n\nfunction getAttachmentMapKey(slotId: string): string {\n return `${ATTACHMENT_KEY_PREFIX}${slotId}`;\n}\n\nfunction listStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): Array<DocumentAttachment & { order: number | null }> {\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n return documentMap\n .entries()\n .flatMap(([key, value]) => {\n if (!key.startsWith(ATTACHMENT_KEY_PREFIX)) {\n return [];\n }\n\n const attachment = parseStructuredAttachment(\n key.slice(ATTACHMENT_KEY_PREFIX.length),\n value,\n );\n return attachment ? [attachment] : [];\n })\n .sort((left, right) => {\n if (left.order !== right.order) {\n if (left.order === null) {\n return 1;\n }\n\n if (right.order === null) {\n return -1;\n }\n\n return left.order - right.order;\n }\n\n return compareCanonicalStrings(left.slotId, right.slotId);\n });\n}\n\nfunction getStructuredDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return listStructuredDocumentAttachments(doc).map(\n ({ order: _order, ...attachment }) => attachment,\n );\n}\n\nexport function getDocumentAttachments(\n doc: StructuredDocumentShape,\n): DocumentAttachment[] {\n return getStructuredDocumentAttachments(doc);\n}\n\n// The fixed-length digest keeps a held copy from inheriting the name of\n// different bytes that later occupy its slot.\nexport function serializeDocumentAttachmentNames(\n doc: StructuredDocumentShape,\n): string {\n return JSON.stringify(\n Object.fromEntries(\n getDocumentAttachments(doc).map(({ contentSha256, slotId, name }) => [\n `${contentSha256}:${slotId}`,\n { name, search: name.toLowerCase() },\n ]),\n ),\n );\n}\n\nexport function addDocumentAttachments(\n doc: StructuredDocumentShape,\n attachments: ReadonlyArray<DocumentAttachment>,\n): void {\n if (attachments.length === 0) {\n return;\n }\n\n const documentMap = doc.getMap(DOCUMENT_CONTENT_MAP_KEY);\n const existingAttachments = listStructuredDocumentAttachments(doc);\n let nextOrder =\n existingAttachments.reduce((highestOrder, attachment, index) => {\n return Math.max(highestOrder, attachment.order ?? index);\n }, -1) + 1;\n\n for (const attachment of attachments) {\n const attachmentMap = documentMap.getOrCreateContainer(\n getAttachmentMapKey(attachment.slotId),\n new LoroMap(),\n );\n attachmentMap.set(\"contentSha256\", attachment.contentSha256);\n attachmentMap.set(\"name\", attachment.name);\n attachmentMap.set(\"byteLength\", attachment.byteLength);\n if (attachment.mimeType === null) {\n attachmentMap.delete(\"mimeType\");\n } else {\n attachmentMap.set(\"mimeType\", attachment.mimeType);\n }\n if (attachmentMap.get(\"order\") === undefined) {\n attachmentMap.set(\"order\", nextOrder);\n nextOrder += 1;\n }\n }\n}\n\nexport function removeDocumentAttachment(\n doc: StructuredDocumentShape,\n slotId: string,\n): void {\n doc.getMap(DOCUMENT_CONTENT_MAP_KEY).delete(getAttachmentMapKey(slotId));\n}\n\nexport function sameDocumentAttachments(\n left: ReadonlyArray<DocumentAttachment>,\n right: ReadonlyArray<DocumentAttachment>,\n): boolean {\n return (\n left.length === right.length &&\n left.every((attachment, index) => {\n const nextAttachment = right[index];\n return (\n nextAttachment !== undefined &&\n attachment.slotId === nextAttachment.slotId &&\n attachment.contentSha256 === nextAttachment.contentSha256 &&\n attachment.name === nextAttachment.name &&\n attachment.byteLength === nextAttachment.byteLength &&\n attachment.mimeType === nextAttachment.mimeType\n );\n })\n );\n}\n"]}
@@ -39,6 +39,7 @@ export async function createStoredDocumentWithHistoryCheckpoint(execSql, documen
39
39
  return classifyExistingBirth(document.id, requestedDocumentId, existing.localId);
40
40
  }
41
41
  const created = await createDocumentRowsIfAbsent({
42
+ attachmentNames: options?.attachmentNames,
42
43
  document,
43
44
  tx,
44
45
  updatedAt,
@@ -1 +1 @@
1
- {"version":3,"file":"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BAAiB,CAAC,gBAAgB;YACpD,QAAQ;YACR,SAAS;SACV,CAAC;aACD,kBAAkB,CAAC;YAClB,MAAM,EAAE;gBACN,0BAA0B,CAAC,OAAO;gBAClC,0BAA0B,CAAC,OAAO;aACnC;YACD,GAAG,EAAE;gBACH,QAAQ,EAAE,iBAAiB,CAAC,QAAQ;gBACpC,gBAAgB,EAAE,iBAAiB,CAAC,gBAAgB;gBACpD,QAAQ;gBACR,SAAS;aACV;SACF,CAAC;aACD,GAAG,EAAE,CAAC;QACT,IAAI,OAAO,EAAE,aAAa,EAAE,CAAC;YAC3B,MAAM,mDAAmD,CAAC;gBACxD,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;gBACnC,aAAa,EAAE,OAAO,CAAC,aAAa;gBACpC,KAAK,EAAE,EAAE,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,EAAE;gBAC5D,EAAE;aACH,CAAC,CAAC;QACL,CAAC;QACD,MAAM,oBAAoB,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;QACrD,OAAO,SAAS,CAAC;IACnB,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, desc, eq, or } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { deriveStableDocumentId } from \"../../../documents/shared/stableDocumentId\";\nimport {\n documentHistoryCheckpoints,\n documents,\n} from \"../../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { insertDocumentPendingUpdateWithHistoryInTransaction } from \"../records/documentPendingUpdatePersistence\";\nimport type { DocumentsPersistence } from \"../types\";\nimport {\n createDocumentRowsIfAbsent,\n resolveDocumentSaveTimestamp,\n} from \"./documentRows\";\n\nfunction classifyExistingBirth(\n requestedLocalId: string,\n requestedDocumentId: string,\n existingLocalId: string,\n) {\n if (existingLocalId === requestedLocalId) return null;\n return {\n status: \"remote-alias\" as const,\n documentId: requestedDocumentId,\n localId: existingLocalId,\n };\n}\n\nexport async function createStoredDocumentWithHistoryCheckpoint(\n execSql: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[0],\n document: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[1],\n historyCheckpoint: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[2],\n options: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[3],\n saveClientProjection: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[4],\n): ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]> {\n const requestedDocumentId =\n document.documentId ?? (await deriveStableDocumentId(document.id));\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n if (options?.stillCurrent && !options.stillCurrent()) {\n return null;\n }\n // Check under the same immediate transaction as the birth. A lookup\n // before entering it misses discovery committed while creation waits.\n // Prefer an existing local winner so its normal restore path survives.\n const [existing] = await tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n or(\n eq(documents.localId, document.id),\n eq(documents.documentId, requestedDocumentId),\n ),\n ),\n )\n .orderBy(desc(eq(documents.localId, document.id)))\n .limit(1);\n if (existing) {\n return classifyExistingBirth(\n document.id,\n requestedDocumentId,\n existing.localId,\n );\n }\n const created = await createDocumentRowsIfAbsent({\n document,\n tx,\n updatedAt,\n });\n if (!created) return null;\n const revision = crypto.randomUUID();\n await tx\n .insert(documentHistoryCheckpoints)\n .values({\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n snapshot: historyCheckpoint.snapshot,\n endVersionVector: historyCheckpoint.endVersionVector,\n revision,\n updatedAt,\n })\n .onConflictDoUpdate({\n target: [\n documentHistoryCheckpoints.appKind,\n documentHistoryCheckpoints.localId,\n ],\n set: {\n snapshot: historyCheckpoint.snapshot,\n endVersionVector: historyCheckpoint.endVersionVector,\n revision,\n updatedAt,\n },\n })\n .run();\n if (options?.pendingUpdate) {\n await insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt: new Date().toISOString(),\n pendingUpdate: options.pendingUpdate,\n scope: { appKind: DOCUMENTS_APP_KIND, localId: document.id },\n tx,\n });\n }\n await saveClientProjection(lockedExecSql, updatedAt);\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"createDocumentWithHistoryCheckpoint.js","sourceRoot":"","sources":["createDocumentWithHistoryCheckpoint.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EACL,0BAA0B,EAC1B,SAAS,GACV,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,mDAAmD,EAAE,MAAM,6CAA6C,CAAC;AAElH,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,gBAAgB,CAAC;AAExB,SAAS,qBAAqB,CAC5B,gBAAwB,EACxB,mBAA2B,EAC3B,eAAuB;IAEvB,IAAI,eAAe,KAAK,gBAAgB;QAAE,OAAO,IAAI,CAAC;IACtD,OAAO;QACL,MAAM,EAAE,cAAuB;QAC/B,UA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nB,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { and, desc, eq, or } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { deriveStableDocumentId } from \"../../../documents/shared/stableDocumentId\";\nimport {\n documentHistoryCheckpoints,\n documents,\n} from \"../../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { insertDocumentPendingUpdateWithHistoryInTransaction } from \"../records/documentPendingUpdatePersistence\";\nimport type { DocumentsPersistence } from \"../types\";\nimport {\n createDocumentRowsIfAbsent,\n resolveDocumentSaveTimestamp,\n} from \"./documentRows\";\n\nfunction classifyExistingBirth(\n requestedLocalId: string,\n requestedDocumentId: string,\n existingLocalId: string,\n) {\n if (existingLocalId === requestedLocalId) return null;\n return {\n status: \"remote-alias\" as const,\n documentId: requestedDocumentId,\n localId: existingLocalId,\n };\n}\n\nexport async function createStoredDocumentWithHistoryCheckpoint(\n execSql: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[0],\n document: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[1],\n historyCheckpoint: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[2],\n options: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[3],\n saveClientProjection: Parameters<\n DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]\n >[4],\n): ReturnType<DocumentsPersistence[\"createDocumentWithHistoryCheckpoint\"]> {\n const requestedDocumentId =\n document.documentId ?? (await deriveStableDocumentId(document.id));\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n if (options?.stillCurrent && !options.stillCurrent()) {\n return null;\n }\n // Check under the same immediate transaction as the birth. A lookup\n // before entering it misses discovery committed while creation waits.\n // Prefer an existing local winner so its normal restore path survives.\n const [existing] = await tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n or(\n eq(documents.localId, document.id),\n eq(documents.documentId, requestedDocumentId),\n ),\n ),\n )\n .orderBy(desc(eq(documents.localId, document.id)))\n .limit(1);\n if (existing) {\n return classifyExistingBirth(\n document.id,\n requestedDocumentId,\n existing.localId,\n );\n }\n const created = await createDocumentRowsIfAbsent({\n attachmentNames: options?.attachmentNames,\n document,\n tx,\n updatedAt,\n });\n if (!created) return null;\n const revision = crypto.randomUUID();\n await tx\n .insert(documentHistoryCheckpoints)\n .values({\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n snapshot: historyCheckpoint.snapshot,\n endVersionVector: historyCheckpoint.endVersionVector,\n revision,\n updatedAt,\n })\n .onConflictDoUpdate({\n target: [\n documentHistoryCheckpoints.appKind,\n documentHistoryCheckpoints.localId,\n ],\n set: {\n snapshot: historyCheckpoint.snapshot,\n endVersionVector: historyCheckpoint.endVersionVector,\n revision,\n updatedAt,\n },\n })\n .run();\n if (options?.pendingUpdate) {\n await insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt: new Date().toISOString(),\n pendingUpdate: options.pendingUpdate,\n scope: { appKind: DOCUMENTS_APP_KIND, localId: document.id },\n tx,\n });\n }\n await saveClientProjection(lockedExecSql, updatedAt);\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
@@ -95,7 +95,12 @@ async function saveDiscardShell(input) {
95
95
  document: shellDocument,
96
96
  tx,
97
97
  });
98
- if (!(await saveDocumentRows({ document: shellDocument, tx, updatedAt }))) {
98
+ if (!(await saveDocumentRows({
99
+ attachmentNames: "{}",
100
+ document: shellDocument,
101
+ tx,
102
+ updatedAt,
103
+ }))) {
99
104
  throw new Error("Document recovery generation changed during discard");
100
105
  }
101
106
  }
@@ -1 +1 @@
1
- {"version":3,"file":"discardDocument.js","sourceRoot":"","sources":["discardDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAGL,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAMtD,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,kCAAkC,EAAE,MAAM,kBAAkB,CAAC;AAEtE,SAAS,yBAAyB,CAChC,OAAe,EACf,gBAAsC;IAEtC,OAAO;QACL,EAAE,EAAE,OAAO;QACX,WAAW,EAAE,gBAAgB,CAAC,WAAW;QACzC,eAAe,EAAE,gBAAgB,CAAC,eAAe,IAAI,IAAI;QACzD,WAAW,EAAE,gBAAgB,CAAC,WAAW;QACzC,gBAAgB,EAAE,IAAI;QACtB,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,kBAAkB,EAAE,IAAI;QACxB,sBAAsB,EAAE,IAAI;QAC5B,oBAAoB,EAAE,gBAAgB,CAAC,oBAAoB,IAAI,IAAI;QACnE,aAAa,EAAE,IAAI;QACnB,kBAAkB,EAAE,IAAI;QACxB,gBAAgB,EAAE,IAAI;QACtB,kBAAkB,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CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QACrE,MAAM,eAAe,CAAC,aAAa,EAAE,6BAA6B,CAAC,CAAC;QACpE,OAAO,0BAA0B,CAAC;YAChC,kBAAkB,EAAE,gCAAgC,CAClD,KAAK,CAAC,kBAAkB,CACzB;YACD,kBAAkB;YAClB,OAAO;YACP,aAAa;YACb,WAAW;SACZ,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, isNotNull } from \"drizzle-orm\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../../documents/documentKinds\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type {\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../types\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\nfunction buildDiscardShellDocument(\n localId: string,\n existingDocument: StoredDocumentRecord,\n): StoredDocumentRecord {\n return {\n id: localId,\n accessEpoch: existingDocument.accessEpoch,\n accessStateHash: existingDocument.accessStateHash ?? null,\n containerId: existingDocument.containerId,\n contentKeyBundle: null,\n documentId: existingDocument.documentId,\n documentKekTargets: null,\n documentManifestBundle: null,\n effectiveAccessLevel: existingDocument.effectiveAccessLevel ?? null,\n lastCommitLsn: null,\n pendingBaseVersion: null,\n pullContinuation: null,\n recoveryGeneration: existingDocument.recoveryGeneration ?? 0,\n snapshotEndVersion: \"\",\n text: \"\",\n ...(existingDocument.documentKind === undefined\n ? {}\n : { documentKind: existingDocument.documentKind }),\n ...(existingDocument.title === undefined\n ? {}\n : { title: existingDocument.title }),\n };\n}\n\ninterface DiscardCandidate {\n detachedStorageKeys: string[];\n existingDocument: StoredDocumentRecord;\n pendingAttachments: ReadonlyArray<{ slotId: string; storageKey: string }>;\n}\n\nasync function loadDiscardCandidate(input: {\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n tx: ClientSQLiteTransactionScope;\n}): Promise<DiscardCandidate | null> {\n const { expectedDocumentId, localId, lockedExecSql, persistence, tx } = input;\n const existingDocument = await persistence.loadDocument(\n lockedExecSql,\n localId,\n );\n if (\n !existingDocument?.documentId ||\n existingDocument.documentId !== expectedDocumentId ||\n !existingDocument.containerId\n ) {\n return null;\n }\n const moveIntentRows = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.localId, localId),\n ),\n )\n .limit(1);\n if (moveIntentRows.length > 0) return null;\n\n const pendingAttachments = await persistence.listPendingAttachments(\n lockedExecSql,\n localId,\n );\n const detachedRows = await tx\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n );\n return {\n detachedStorageKeys: detachedRows.map((row) => row.storageKey),\n existingDocument,\n pendingAttachments,\n };\n}\n\n// Staged-upload rows AND detached local-attachment markers both go: a marker\n// for a locally-discarded detach would otherwise keep filtering the slot out\n// after a re-pull restores it, leaving the attachment permanently invisible.\nasync function clearDiscardedDocumentRows(input: {\n candidate: DiscardCandidate;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, localId, lockedExecSql, tx } = input;\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n for (const pendingAttachment of candidate.pendingAttachments) {\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, pendingAttachment.slotId),\n eq(\n documentAttachmentBlobProjection.storageKey,\n pendingAttachment.storageKey,\n ),\n ),\n )\n .run();\n }\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n const records = new DocumentRecordRepository(lockedExecSql);\n await records.deleteDocumentHistory(getDocumentScope(localId));\n await records.clearDocumentSyncFailure(getDocumentScope(localId));\n}\n\nasync function saveDiscardShell(input: {\n candidate: DiscardCandidate;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, documentProjectors, localId, lockedExecSql, tx } = input;\n const shellDocument = buildDiscardShellDocument(\n localId,\n candidate.existingDocument,\n );\n // The document-kind projection derives from discarded content, so clear it\n // inside the transaction and let the next pull rebuild it.\n await documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: shellDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n execSql: lockedExecSql,\n localId,\n });\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: shellDocument,\n tx,\n });\n if (!(await saveDocumentRows({ document: shellDocument, tx, updatedAt }))) {\n throw new Error(\"Document recovery generation changed during discard\");\n }\n}\n\n// Eligibility, teardown, client-projection clearing, and shell replacement\n// share one immediate transaction, so a second connection cannot relink the\n// local id between identity validation and destructive writes.\nasync function discardDocumentRowsToShell(input: {\n documentProjectors: DocumentProjectorRegistry;\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const clientProjectionTables =\n input.documentProjectors.getClientProjectionTables();\n if (clientProjectionTables.length > 0) {\n await ensureSqlTables(input.lockedExecSql, clientProjectionTables);\n }\n return getClientSQLitePersistenceRuntime(input.lockedExecSql).transaction(\n async (tx) => {\n const candidate = await loadDiscardCandidate({ ...input, tx });\n if (!candidate) return { discarded: false };\n await clearDiscardedDocumentRows({\n candidate,\n localId: input.localId,\n lockedExecSql: input.lockedExecSql,\n tx,\n });\n await saveDiscardShell({ ...input, candidate, tx });\n // The deleted rows were these bytes' only pointers from this document,\n // but a hydrated copy is shared by every slot holding the same blob.\n // Queue them for the reference-checked reclaim instead of deleting.\n await queueDocumentAttachmentStorageKeys(tx, [\n ...new Set([\n ...candidate.pendingAttachments.map((row) => row.storageKey),\n ...candidate.detachedStorageKeys,\n ]),\n ]);\n return {\n discarded: true,\n documentKind:\n candidate.existingDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n };\n },\n { behavior: \"immediate\" },\n );\n}\n\n/**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell: drop its queued updates, staged attachment\n * rows (and their settled local-attachment halves, which share the staged\n * storage keys the caller reclaims), detached attachment markers, durable\n * history, recorded sync failure, and document-kind client projection, then\n * overwrite the record with an empty snapshot that keeps its identity,\n * placement, title, and kind. Everything commits in ONE transaction.\n *\n * Refused under the serialized mutation when the document is local-only or\n * unlinked (its rows are the only copy), when its documentId no longer\n * matches the caller's expectation (a stale caller or racing relink must not\n * discard a different identity's edits), or when any move intent references\n * it (the local containerId is then the move's optimistic placement, and\n * reseeding it as server truth would silently commit the move locally while\n * discarding the intent that was meant to perform it).\n */\nexport async function discardStoredDocumentToShell(input: {\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n expectedDocumentId: string;\n localId: string;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const { expectedDocumentId, localId, persistence } = input;\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return discardDocumentRowsToShell({\n documentProjectors: resolveDocumentProjectorRegistry(\n input.documentProjectors,\n ),\n expectedDocumentId,\n localId,\n lockedExecSql,\n persistence,\n });\n });\n}\n"]}
1
+ {"version":3,"file":"discardDocument.js","sourceRoot":"","sources":["discardDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EAGL,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAMtD,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,kCAAkC,EAAE,MAAM,kBAAkB,CAAC;AAEtE,SAAS,yBAAyB,CAChC,OAAe,EACf,gBAAsC;IAEtC,OAAO;QACL,EAAE,EAAE,OAAO;QACX,WAAW,EAAE,gBAAgB,CAAC,WAAW;QACzC,eAAe,EAAE,gBAAgB,CAAC,eAAe,IAAI,IAAI;QACzD,WAAW,EAAE,gBAAgB,CAAC,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B,CAAC,YAAY,IAAI,qBAAqB;SACnE,CAAC;IACJ,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAAC,KASlD;IACC,MAAM,EAAE,kBAAkB,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC3D,OAAO,wBAAwB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QACrE,MAAM,eAAe,CAAC,aAAa,EAAE,6BAA6B,CAAC,CAAC;QACpE,OAAO,0BAA0B,CAAC;YAChC,kBAAkB,EAAE,gCAAgC,CAClD,KAAK,CAAC,kBAAkB,CACzB;YACD,kBAAkB;YAClB,OAAO;YACP,aAAa;YACb,WAAW;SACZ,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, isNotNull } from \"drizzle-orm\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../documents/documentConstants\";\nimport {\n type DocumentProjectorRegistry,\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../../documents/documentKinds\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type {\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n StoredDocumentRecord,\n} from \"../types\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./documentRows\";\nimport { queueDocumentAttachmentStorageKeys } from \"./orphanSideRows\";\n\nfunction buildDiscardShellDocument(\n localId: string,\n existingDocument: StoredDocumentRecord,\n): StoredDocumentRecord {\n return {\n id: localId,\n accessEpoch: existingDocument.accessEpoch,\n accessStateHash: existingDocument.accessStateHash ?? null,\n containerId: existingDocument.containerId,\n contentKeyBundle: null,\n documentId: existingDocument.documentId,\n documentKekTargets: null,\n documentManifestBundle: null,\n effectiveAccessLevel: existingDocument.effectiveAccessLevel ?? null,\n lastCommitLsn: null,\n pendingBaseVersion: null,\n pullContinuation: null,\n recoveryGeneration: existingDocument.recoveryGeneration ?? 0,\n snapshotEndVersion: \"\",\n text: \"\",\n ...(existingDocument.documentKind === undefined\n ? {}\n : { documentKind: existingDocument.documentKind }),\n ...(existingDocument.title === undefined\n ? {}\n : { title: existingDocument.title }),\n };\n}\n\ninterface DiscardCandidate {\n detachedStorageKeys: string[];\n existingDocument: StoredDocumentRecord;\n pendingAttachments: ReadonlyArray<{ slotId: string; storageKey: string }>;\n}\n\nasync function loadDiscardCandidate(input: {\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n tx: ClientSQLiteTransactionScope;\n}): Promise<DiscardCandidate | null> {\n const { expectedDocumentId, localId, lockedExecSql, persistence, tx } = input;\n const existingDocument = await persistence.loadDocument(\n lockedExecSql,\n localId,\n );\n if (\n !existingDocument?.documentId ||\n existingDocument.documentId !== expectedDocumentId ||\n !existingDocument.containerId\n ) {\n return null;\n }\n const moveIntentRows = await tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.localId, localId),\n ),\n )\n .limit(1);\n if (moveIntentRows.length > 0) return null;\n\n const pendingAttachments = await persistence.listPendingAttachments(\n lockedExecSql,\n localId,\n );\n const detachedRows = await tx\n .select({ storageKey: documentAttachmentBlobProjection.storageKey })\n .from(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n );\n return {\n detachedStorageKeys: detachedRows.map((row) => row.storageKey),\n existingDocument,\n pendingAttachments,\n };\n}\n\n// Staged-upload rows AND detached local-attachment markers both go: a marker\n// for a locally-discarded detach would otherwise keep filtering the slot out\n// after a re-pull restores it, leaving the attachment permanently invisible.\nasync function clearDiscardedDocumentRows(input: {\n candidate: DiscardCandidate;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, localId, lockedExecSql, tx } = input;\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n for (const pendingAttachment of candidate.pendingAttachments) {\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n eq(documentAttachmentBlobProjection.slotId, pendingAttachment.slotId),\n eq(\n documentAttachmentBlobProjection.storageKey,\n pendingAttachment.storageKey,\n ),\n ),\n )\n .run();\n }\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(\n and(\n eq(documentAttachmentBlobProjection.localId, localId),\n isNotNull(documentAttachmentBlobProjection.detachedAt),\n ),\n )\n .run();\n const records = new DocumentRecordRepository(lockedExecSql);\n await records.deleteDocumentHistory(getDocumentScope(localId));\n await records.clearDocumentSyncFailure(getDocumentScope(localId));\n}\n\nasync function saveDiscardShell(input: {\n candidate: DiscardCandidate;\n documentProjectors: DocumentProjectorRegistry;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { candidate, documentProjectors, localId, lockedExecSql, tx } = input;\n const shellDocument = buildDiscardShellDocument(\n localId,\n candidate.existingDocument,\n );\n // The document-kind projection derives from discarded content, so clear it\n // inside the transaction and let the next pull rebuild it.\n await documentProjectors.deleteStoredDocumentClientProjection({\n documentKind: shellDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n execSql: lockedExecSql,\n localId,\n });\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: shellDocument,\n tx,\n });\n if (\n !(await saveDocumentRows({\n attachmentNames: \"{}\",\n document: shellDocument,\n tx,\n updatedAt,\n }))\n ) {\n throw new Error(\"Document recovery generation changed during discard\");\n }\n}\n\n// Eligibility, teardown, client-projection clearing, and shell replacement\n// share one immediate transaction, so a second connection cannot relink the\n// local id between identity validation and destructive writes.\nasync function discardDocumentRowsToShell(input: {\n documentProjectors: DocumentProjectorRegistry;\n expectedDocumentId: string;\n localId: string;\n lockedExecSql: ExecSql;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const clientProjectionTables =\n input.documentProjectors.getClientProjectionTables();\n if (clientProjectionTables.length > 0) {\n await ensureSqlTables(input.lockedExecSql, clientProjectionTables);\n }\n return getClientSQLitePersistenceRuntime(input.lockedExecSql).transaction(\n async (tx) => {\n const candidate = await loadDiscardCandidate({ ...input, tx });\n if (!candidate) return { discarded: false };\n await clearDiscardedDocumentRows({\n candidate,\n localId: input.localId,\n lockedExecSql: input.lockedExecSql,\n tx,\n });\n await saveDiscardShell({ ...input, candidate, tx });\n // The deleted rows were these bytes' only pointers from this document,\n // but a hydrated copy is shared by every slot holding the same blob.\n // Queue them for the reference-checked reclaim instead of deleting.\n await queueDocumentAttachmentStorageKeys(tx, [\n ...new Set([\n ...candidate.pendingAttachments.map((row) => row.storageKey),\n ...candidate.detachedStorageKeys,\n ]),\n ]);\n return {\n discarded: true,\n documentKind:\n candidate.existingDocument.documentKind ?? DEFAULT_DOCUMENT_KIND,\n };\n },\n { behavior: \"immediate\" },\n );\n}\n\n/**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell: drop its queued updates, staged attachment\n * rows (and their settled local-attachment halves, which share the staged\n * storage keys the caller reclaims), detached attachment markers, durable\n * history, recorded sync failure, and document-kind client projection, then\n * overwrite the record with an empty snapshot that keeps its identity,\n * placement, title, and kind. Everything commits in ONE transaction.\n *\n * Refused under the serialized mutation when the document is local-only or\n * unlinked (its rows are the only copy), when its documentId no longer\n * matches the caller's expectation (a stale caller or racing relink must not\n * discard a different identity's edits), or when any move intent references\n * it (the local containerId is then the move's optimistic placement, and\n * reseeding it as server truth would silently commit the move locally while\n * discarding the intent that was meant to perform it).\n */\nexport async function discardStoredDocumentToShell(input: {\n documentProjectors: DocumentProjectorRegistryInput;\n execSql: ExecSql;\n expectedDocumentId: string;\n localId: string;\n persistence: Pick<\n DocumentsPersistence,\n \"listPendingAttachments\" | \"loadDocument\"\n >;\n}): Promise<DiscardDocumentToShellResult> {\n const { expectedDocumentId, localId, persistence } = input;\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n await ensureSqlTables(lockedExecSql, documentPlacementIntentTables);\n return discardDocumentRowsToShell({\n documentProjectors: resolveDocumentProjectorRegistry(\n input.documentProjectors,\n ),\n expectedDocumentId,\n localId,\n lockedExecSql,\n persistence,\n });\n });\n}\n"]}
@@ -180,6 +180,7 @@ async function applyStoredDocumentMutation(input) {
180
180
  snapshotEndVersion: currentRecord.snapshotEndVersion,
181
181
  }, mutation.document);
182
182
  if (!(await saveDocumentRows({
183
+ attachmentNames: mutation.attachmentNames,
183
184
  clearSyncFailure: mutation.clearSyncFailure === true,
184
185
  document: mutation.document,
185
186
  tx,
@@ -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,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AO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC/D,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAC1D,KAAK,EAAE,EAAE,EAAE,EAAE;QACX,MAAM,aAAa,GAAG,MAAM,YAAY,CACtC,aAAa,EACb,KAAK,CAAC,cAAc,CAAC,EAAE,CACxB,CAAC;QACF,IACE,aAAa;YACb,8BAA8B,CAAC,aAAa,EAAE,KAAK,CAAC,cAAc,CAAC;YACnE,sBAAsB,CAAC,aAAa,EAAE,KAAK,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 { 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
+ {"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,4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AAc,CAAC;YACnE,sBAAsB,CAAC,aAAa,EAAE,KAAK,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 { 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 attachmentNames: mutation.attachmentNames,\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"]}
@@ -78,6 +78,9 @@ async function saveDocumentProjectionRows(input) {
78
78
  const projectionTextRow = {
79
79
  localId: document.id,
80
80
  text: document.text,
81
+ ...(input.attachmentNames === undefined
82
+ ? {}
83
+ : { attachmentNames: input.attachmentNames }),
81
84
  };
82
85
  await tx
83
86
  .insert(documentProjectionText)
@@ -1 +1 @@
1
- {"version":3,"file":"documentRows.js","sourceRoot":"","sources":["documentRows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAEtE,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,yBAAyB,GAE1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAG7D,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAAC;AAE1F,OAAO,EACL,yB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C9B,QAAQ;QACN,CAAC,CAAC;YACE,UAAU,EACR,QAAQ,CAAC,YAAY,IAAI,IAAI;gBAC7B,QAAQ,CAAC,KAAK,IAAI,IAAI;gBACtB,QAAQ,CAAC,SAAS,IAAI,IAAI;gBACxB,CAAC,CAAC;oBACE,YAAY,EAAE,QAAQ,CAAC,YAAY;oBACnC,IAAI,EAAE,QAAQ,CAAC,IAAI;oBACnB,KAAK,EAAE,QAAQ,CAAC,KAAK;oBACrB,SAAS,EAAE,QAAQ,CAAC,SAAS;iBAC9B;gBACH,CAAC,CAAC,IAAI;YACV,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;SAChD;QACH,CAAC,CAAC,IAAI,EACR,QAAQ,CACT,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CACvC,QAQQ,EACR,QAA8B;IAE9B,MAAM,kBAAkB,GAAG,QAAQ,EAAE,UAAU,IAAI,SAAS,CAAC;IAC7D,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IACrC,OAAO,8BAA8B,CACnC,QAAQ;QACN,CAAC,CAAC;YACE,YAAY,EAAE,yBAAyB,CAAC,kBAAkB,CAAC;YAC3D,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;YAC/C,IAAI,EAAE,iBAAiB,CAAC,kBAAkB,CAAC;YAC3C,KAAK,EAAE,kBAAkB,CAAC,kBAAkB,CAAC;SAC9C;QACH,CAAC,CAAC,IAAI,EACR,QAAQ,CACT;QACC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,sBAAsB,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC;AACxD,CAAC","sourcesContent":["import { and, eq, getTableColumns, lte, type SQL } from \"drizzle-orm\";\nimport type { SQLiteColumn } from \"drizzle-orm/sqlite-core\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport {\n deriveStoredDocumentTitle,\n type StoredDocumentKind,\n} from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteInsertBatchSize } from \"../../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../../sqlite/sqliteUpsert\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentScope } from \"../records\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../records/documentSyncFailurePersistence\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n /** Clears the recorded sync failure in the same guarded upsert. */\n clearSyncFailure?: boolean;\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = {\n ...toDocumentRecordRow({ document, updatedAt }),\n ...(input.clearSyncFailure ? CLEARED_DOCUMENT_SYNC_FAILURE : {}),\n };\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\ntype UpsertRow = Record<string, unknown>;\n\n/** A `set` clause that applies each conflicting row's own proposed values. */\nfunction excludedSet(\n columns: Record<string, SQLiteColumn>,\n row: UpsertRow,\n): Record<string, SQL> {\n const set: Record<string, SQL> = {};\n for (const key of Object.keys(row)) {\n const column = columns[key];\n if (!column) throw new Error(`Unknown upsert column ${key}`);\n set[key] = excludedValue(column);\n }\n return set;\n}\n\nfunction chunks<T>(values: ReadonlyArray<T>, size: number): T[][] {\n const result: T[][] = [];\n for (let offset = 0; offset < values.length; offset += size) {\n result.push(values.slice(offset, offset + size));\n }\n return result;\n}\n\n// A row that omits an optional column leaves it untouched on update, so\n// rows are grouped by their column shape and each shape gets its own set.\nfunction documentRowsByColumnShape(\n entries: ReadonlyArray<{ document: StoredDocumentRecord; updatedAt: string }>,\n): Map<string, ReturnType<typeof toDocumentRecordRow>[]> {\n const shapes = new Map<string, ReturnType<typeof toDocumentRecordRow>[]>();\n for (const entry of entries) {\n const row = toDocumentRecordRow(entry);\n const shape = Object.keys(row).join(\",\");\n shapes.set(shape, [...(shapes.get(shape) ?? []), row]);\n }\n return shapes;\n}\n\n/**\n * `saveDocumentRows` for documents with DISTINCT local ids, as multi-row\n * statements: one fenced documents upsert per chunk and row shape, then the\n * projection and text upserts for the rows the fence let through. Returns\n * those local ids; a row the recovery-generation fence skips returns no row,\n * exactly as the single-row upsert does.\n */\nexport async function saveDocumentRowsBatch(input: {\n entries: ReadonlyArray<{ document: StoredDocumentRecord; updatedAt: string }>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<Set<string>> {\n const { entries, tx } = input;\n const documentColumns: Record<string, SQLiteColumn> =\n getTableColumns(documents);\n const shapes = documentRowsByColumnShape(entries);\n const saved = new Set<string>();\n for (const rows of shapes.values()) {\n const [first] = rows;\n if (!first) continue;\n const set = excludedSet(documentColumns, first);\n for (const chunk of chunks(rows, sqliteInsertBatchSize(documents))) {\n const returned = await tx\n .insert(documents)\n .values(chunk)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set,\n setWhere: lte(\n documents.recoveryGeneration,\n excludedValue(documents.recoveryGeneration),\n ),\n })\n .returning({ localId: documents.localId });\n for (const row of returned) saved.add(row.localId);\n }\n }\n\n const savedEntries = entries.filter((entry) => saved.has(entry.document.id));\n const projectionRows = savedEntries.map(({ document, updatedAt }) => ({\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n }));\n const [firstProjection] = projectionRows;\n if (firstProjection) {\n const set = excludedSet(\n getTableColumns(documentProjection),\n firstProjection,\n );\n for (const chunk of chunks(\n projectionRows,\n sqliteInsertBatchSize(documentProjection),\n )) {\n await tx\n .insert(documentProjection)\n .values(chunk)\n .onConflictDoUpdate({ target: documentProjection.localId, set })\n .run();\n }\n }\n const textRows = savedEntries.map(({ document }) => ({\n localId: document.id,\n text: document.text,\n }));\n const [firstText] = textRows;\n if (firstText) {\n const set = excludedSet(getTableColumns(documentProjectionText), firstText);\n for (const chunk of chunks(\n textRows,\n sqliteInsertBatchSize(documentProjectionText),\n )) {\n await tx\n .insert(documentProjectionText)\n .values(chunk)\n .onConflictDoUpdate({ target: documentProjectionText.localId, set })\n .run();\n }\n }\n return saved;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n return documentSaveTimestampFrom(\n existing\n ? {\n projection:\n existing.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : null,\n snapshotEndVersion: existing.snapshotEndVersion,\n }\n : null,\n document,\n );\n}\n\n/**\n * The save timestamp from rows already read in the saving transaction: the\n * stored time survives only when the content is unchanged.\n */\nexport function documentSaveTimestampFrom(\n existing: {\n projection: {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n } | null;\n snapshotEndVersion: string;\n } | null,\n document: StoredDocumentRecord,\n): string {\n const existingProjection = existing?.projection ?? undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
1
+ {"version":3,"file":"documentRows.js","sourceRoot":"","sources":["documentRows.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAEtE,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,yBAAyB,GAE1B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AACzE,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAG7D,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAAC;AAE1F,OAAO,EACL,yBAAyB,EACzB,iBAAiB,E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zle-orm/sqlite-core\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport {\n deriveStoredDocumentTitle,\n type StoredDocumentKind,\n} from \"../../../documents/documentKinds\";\nimport { serializeDocumentSyncPullContinuation } from \"../../../documents/shared/sync/pullContinuation\";\nimport { normalizeEffectiveAccessLevel } from \"../../../keying/accessLevel\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteInsertBatchSize } from \"../../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../../../sqlite/sqliteUpsert\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport type { DocumentScope } from \"../records\";\nimport { CLEARED_DOCUMENT_SYNC_FAILURE } from \"../records/documentSyncFailurePersistence\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n getProjectionUpdatedAt,\n} from \"./documentProjectionRows\";\n\nexport function getDocumentScope(localId: string): DocumentScope {\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n };\n}\n\nexport async function hasDocumentRow(\n execSql: ExecSql,\n localId: string,\n): Promise<boolean> {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nfunction toDocumentRecordRow(input: {\n document: StoredDocumentRecord;\n updatedAt: string;\n}) {\n const { document, updatedAt } = input;\n return {\n appKind: DOCUMENTS_APP_KIND,\n localId: document.id,\n documentId: document.documentId,\n recoveryGeneration: document.recoveryGeneration ?? 0,\n recoveryDocumentId: document.documentId\n ? null\n : (document.recoveryDocumentId ?? null),\n snapshotEndVersion: document.snapshotEndVersion,\n accessEpoch: document.accessEpoch,\n accessStateHash: document.accessStateHash ?? null,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n document.effectiveAccessLevel,\n ),\n lastCommitLsn: document.lastCommitLsn ?? null,\n documentManifestBundle: document.documentManifestBundle ?? null,\n contentKeyBundle: document.contentKeyBundle ?? null,\n documentKekTargets: document.documentKekTargets ?? null,\n // Only touch the outgoing-delta marker when the caller manages it. Callers\n // that leave it undefined (e.g. discovery upserts, registration bootstrap)\n // must not clobber a marker a device-first deferRemoteSync write persisted.\n ...(document.pendingBaseVersion === undefined\n ? {}\n : { pendingBaseVersion: document.pendingBaseVersion }),\n ...(document.pullContinuation === undefined\n ? {}\n : {\n pullContinuation: serializeDocumentSyncPullContinuation(\n document.pullContinuation,\n ),\n }),\n updatedAt,\n };\n}\n\nasync function saveDocumentProjectionRows(input: {\n attachmentNames?: string | undefined;\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<void> {\n const { document, tx, updatedAt } = input;\n const projectionRow = {\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n };\n await tx\n .insert(documentProjection)\n .values(projectionRow)\n .onConflictDoUpdate({\n target: documentProjection.localId,\n set: projectionRow,\n })\n .run();\n\n const projectionTextRow = {\n localId: document.id,\n text: document.text,\n ...(input.attachmentNames === undefined\n ? {}\n : { attachmentNames: input.attachmentNames }),\n };\n await tx\n .insert(documentProjectionText)\n .values(projectionTextRow)\n .onConflictDoUpdate({\n target: documentProjectionText.localId,\n set: projectionTextRow,\n })\n .run();\n}\n\nexport async function createDocumentRowsIfAbsent(input: {\n attachmentNames?: string | undefined;\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = toDocumentRecordRow({ document, updatedAt });\n const inserted = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoNothing({\n target: [documents.appKind, documents.localId],\n })\n .returning({ localId: documents.localId });\n if (inserted.length === 0) {\n return false;\n }\n\n await saveDocumentProjectionRows(input);\n return true;\n}\n\nexport async function saveDocumentRows(input: {\n attachmentNames?: string | undefined;\n /** Clears the recorded sync failure in the same guarded upsert. */\n clearSyncFailure?: boolean;\n document: StoredDocumentRecord;\n tx: ClientSQLiteTransactionScope;\n updatedAt: string;\n}): Promise<boolean> {\n const { document, tx, updatedAt } = input;\n const documentRow = {\n ...toDocumentRecordRow({ document, updatedAt }),\n ...(input.clearSyncFailure ? CLEARED_DOCUMENT_SYNC_FAILURE : {}),\n };\n // The recovery-generation fence rides on the upsert: a stored row from a\n // newer recovery generation is left untouched and returns no row, so a\n // stale writer skips the projection writes without a separate read.\n const saved = await tx\n .insert(documents)\n .values(documentRow)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set: documentRow,\n setWhere: lte(\n documents.recoveryGeneration,\n documentRow.recoveryGeneration,\n ),\n })\n .returning({ localId: documents.localId });\n if (saved.length === 0) {\n return false;\n }\n await saveDocumentProjectionRows(input);\n return true;\n}\n\ntype UpsertRow = Record<string, unknown>;\n\n/** A `set` clause that applies each conflicting row's own proposed values. */\nfunction excludedSet(\n columns: Record<string, SQLiteColumn>,\n row: UpsertRow,\n): Record<string, SQL> {\n const set: Record<string, SQL> = {};\n for (const key of Object.keys(row)) {\n const column = columns[key];\n if (!column) throw new Error(`Unknown upsert column ${key}`);\n set[key] = excludedValue(column);\n }\n return set;\n}\n\nfunction chunks<T>(values: ReadonlyArray<T>, size: number): T[][] {\n const result: T[][] = [];\n for (let offset = 0; offset < values.length; offset += size) {\n result.push(values.slice(offset, offset + size));\n }\n return result;\n}\n\n// A row that omits an optional column leaves it untouched on update, so\n// rows are grouped by their column shape and each shape gets its own set.\nfunction documentRowsByColumnShape(\n entries: ReadonlyArray<{ document: StoredDocumentRecord; updatedAt: string }>,\n): Map<string, ReturnType<typeof toDocumentRecordRow>[]> {\n const shapes = new Map<string, ReturnType<typeof toDocumentRecordRow>[]>();\n for (const entry of entries) {\n const row = toDocumentRecordRow(entry);\n const shape = Object.keys(row).join(\",\");\n shapes.set(shape, [...(shapes.get(shape) ?? []), row]);\n }\n return shapes;\n}\n\n/**\n * `saveDocumentRows` for documents with DISTINCT local ids, as multi-row\n * statements: one fenced documents upsert per chunk and row shape, then the\n * projection and text upserts for the rows the fence let through. Returns\n * those local ids; a row the recovery-generation fence skips returns no row,\n * exactly as the single-row upsert does.\n */\nexport async function saveDocumentRowsBatch(input: {\n entries: ReadonlyArray<{ document: StoredDocumentRecord; updatedAt: string }>;\n tx: ClientSQLiteTransactionScope;\n}): Promise<Set<string>> {\n const { entries, tx } = input;\n const documentColumns: Record<string, SQLiteColumn> =\n getTableColumns(documents);\n const shapes = documentRowsByColumnShape(entries);\n const saved = new Set<string>();\n for (const rows of shapes.values()) {\n const [first] = rows;\n if (!first) continue;\n const set = excludedSet(documentColumns, first);\n for (const chunk of chunks(rows, sqliteInsertBatchSize(documents))) {\n const returned = await tx\n .insert(documents)\n .values(chunk)\n .onConflictDoUpdate({\n target: [documents.appKind, documents.localId],\n set,\n setWhere: lte(\n documents.recoveryGeneration,\n excludedValue(documents.recoveryGeneration),\n ),\n })\n .returning({ localId: documents.localId });\n for (const row of returned) saved.add(row.localId);\n }\n }\n\n const savedEntries = entries.filter((entry) => saved.has(entry.document.id));\n const projectionRows = savedEntries.map(({ document, updatedAt }) => ({\n localId: document.id,\n documentId: document.documentId,\n containerId: document.containerId,\n documentKind: document.documentKind ?? DEFAULT_DOCUMENT_KIND,\n title: document.title ?? deriveStoredDocumentTitle(document.text),\n updatedAt,\n }));\n const [firstProjection] = projectionRows;\n if (firstProjection) {\n const set = excludedSet(\n getTableColumns(documentProjection),\n firstProjection,\n );\n for (const chunk of chunks(\n projectionRows,\n sqliteInsertBatchSize(documentProjection),\n )) {\n await tx\n .insert(documentProjection)\n .values(chunk)\n .onConflictDoUpdate({ target: documentProjection.localId, set })\n .run();\n }\n }\n const textRows = savedEntries.map(({ document }) => ({\n localId: document.id,\n text: document.text,\n }));\n const [firstText] = textRows;\n if (firstText) {\n const set = excludedSet(getTableColumns(documentProjectionText), firstText);\n for (const chunk of chunks(\n textRows,\n sqliteInsertBatchSize(documentProjectionText),\n )) {\n await tx\n .insert(documentProjectionText)\n .values(chunk)\n .onConflictDoUpdate({ target: documentProjectionText.localId, set })\n .run();\n }\n }\n return saved;\n}\n\nfunction didStoredDocumentContentChange(\n existing: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n > | null,\n next: Pick<\n StoredDocumentRecord,\n \"documentKind\" | \"snapshotEndVersion\" | \"text\" | \"title\"\n >,\n): boolean {\n return (\n existing === null ||\n existing.documentKind !== (next.documentKind ?? DEFAULT_DOCUMENT_KIND) ||\n existing.snapshotEndVersion !== next.snapshotEndVersion ||\n existing.text !== next.text ||\n existing.title !== (next.title ?? deriveStoredDocumentTitle(next.text))\n );\n}\n\nexport async function resolveDocumentSaveTimestamp(input: {\n document: StoredDocumentRecord;\n options?: { updatedAt?: string } | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<string> {\n const { document, options, tx } = input;\n if (options?.updatedAt) {\n return options.updatedAt;\n }\n\n // One read for the stored row and its projection; the projection columns\n // are not nullable, so they are null exactly when the projection is absent.\n const [existing] = await tx\n .select({\n snapshotEndVersion: documents.snapshotEndVersion,\n documentKind: documentProjection.documentKind,\n text: documentProjectionText.text,\n title: documentProjection.title,\n updatedAt: documentProjection.updatedAt,\n })\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.localId, document.id),\n ),\n )\n .limit(1);\n return documentSaveTimestampFrom(\n existing\n ? {\n projection:\n existing.documentKind != null &&\n existing.title != null &&\n existing.updatedAt != null\n ? {\n documentKind: existing.documentKind,\n text: existing.text,\n title: existing.title,\n updatedAt: existing.updatedAt,\n }\n : null,\n snapshotEndVersion: existing.snapshotEndVersion,\n }\n : null,\n document,\n );\n}\n\n/**\n * The save timestamp from rows already read in the saving transaction: the\n * stored time survives only when the content is unchanged.\n */\nexport function documentSaveTimestampFrom(\n existing: {\n projection: {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n } | null;\n snapshotEndVersion: string;\n } | null,\n document: StoredDocumentRecord,\n): string {\n const existingProjection = existing?.projection ?? undefined;\n const now = new Date().toISOString();\n return didStoredDocumentContentChange(\n existing\n ? {\n documentKind: getProjectionDocumentKind(existingProjection),\n snapshotEndVersion: existing.snapshotEndVersion,\n text: getProjectionText(existingProjection),\n title: getProjectionTitle(existingProjection),\n }\n : null,\n document,\n )\n ? now\n : getProjectionUpdatedAt(existingProjection) || now;\n}\n"]}
@@ -127,6 +127,7 @@ export interface DocumentsPersistence extends QueuedPendingUpdateReplacementPort
127
127
  endVersionVector: string;
128
128
  snapshot: string;
129
129
  }, options: {
130
+ attachmentNames?: string;
130
131
  pendingUpdate?: PendingUpdateFields;
131
132
  /** Recheck volatile caller ownership inside the create transaction. */
132
133
  stillCurrent?: (() => boolean) | undefined;
@@ -141,6 +142,7 @@ export interface DocumentsPersistence extends QueuedPendingUpdateReplacementPort
141
142
  */
142
143
  commitDocumentMutation: (execSql: ExecSql, input: {
143
144
  acceptedPendingUpdateIds: readonly string[];
145
+ attachmentNames?: string;
144
146
  attachmentRemoval?: AttachmentRemovalRows | undefined;
145
147
  attachmentStaging?: AttachmentStagingRows | undefined;
146
148
  clearSyncFailure?: boolean | undefined;