@tearleads/client-sdk 0.1.256 → 0.1.257

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 (99) hide show
  1. package/client/documents/index.d.ts +5 -2
  2. package/client/documents/index.js +6 -1
  3. package/client/documents/index.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/data/blobs/attachments/types.d.ts +4 -2
  7. package/data/blobs/attachments/types.js.map +1 -1
  8. package/data/documents/documentContent.d.ts +2 -0
  9. package/data/documents/documentContent.js +7 -0
  10. package/data/documents/documentContent.js.map +1 -1
  11. package/data/documents/shared/manifestBundleReaders.js +1 -1
  12. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  13. package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
  14. package/data/documents/shared/projection/documentCreateSigner.js +49 -0
  15. package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
  16. package/data/documents/shared/projection/index.d.ts +1 -0
  17. package/data/documents/shared/projection/index.js +1 -0
  18. package/data/documents/shared/projection/index.js.map +1 -1
  19. package/data/documents/shared/readers.js +1 -1
  20. package/data/documents/shared/readers.js.map +1 -1
  21. package/data/documents/shared/types.d.ts +1 -0
  22. package/data/documents/shared/types.js.map +1 -1
  23. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  24. package/data/persistence/documents/documentsPersistence.js +4 -1
  25. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  26. package/index.d.ts +3 -3
  27. package/index.js +2 -2
  28. package/index.js.map +1 -1
  29. package/internal/api-client/ApiClient.d.ts +2 -2
  30. package/internal/api-client/apiRequestRuntime.js +12 -8
  31. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  32. package/internal/api-client/binaryResponseOperationTransport.js +2 -2
  33. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  34. package/internal/api-client/client/blobs.d.ts +2 -2
  35. package/internal/api-client/client/blobs.js +21 -9
  36. package/internal/api-client/client/blobs.js.map +1 -1
  37. package/internal/api-client/client/writerProjections.js +2 -1
  38. package/internal/api-client/client/writerProjections.js.map +1 -1
  39. package/internal/api-client/operationResponse.js +3 -3
  40. package/internal/api-client/operationResponse.js.map +1 -1
  41. package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
  42. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  43. package/internal/api-client/sessionRefresh.js +6 -1
  44. package/internal/api-client/sessionRefresh.js.map +1 -1
  45. package/internal/api-client/sessionResponse.js +5 -2
  46. package/internal/api-client/sessionResponse.js.map +1 -1
  47. package/internal/api-client/types.d.ts +2 -0
  48. package/internal/api-client/types.js.map +1 -1
  49. package/package.json +1 -1
  50. package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
  51. package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
  52. package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
  53. package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
  54. package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
  55. package/stores/documents/documentStore/state.js +3 -1
  56. package/stores/documents/documentStore/state.js.map +1 -1
  57. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  58. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  59. package/stores/documents/index.d.ts +1 -0
  60. package/stores/documents/index.js +1 -0
  61. package/stores/documents/index.js.map +1 -1
  62. package/stores/documents/types.d.ts +1 -0
  63. package/stores/documents/types.js.map +1 -1
  64. package/workflows/blobs/upload/index.d.ts +1 -1
  65. package/workflows/blobs/upload/index.js +36 -18
  66. package/workflows/blobs/upload/index.js.map +1 -1
  67. package/workflows/blobs/upload/multipartStageResolution.js +12 -2
  68. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
  69. package/workflows/blobs/upload/multipartUpload.js +10 -2
  70. package/workflows/blobs/upload/multipartUpload.js.map +1 -1
  71. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
  72. package/workflows/container-contents/documentQueries/index.d.ts +1 -1
  73. package/workflows/container-contents/documentQueries/index.js +2 -2
  74. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  75. package/workflows/container-contents/index.d.ts +1 -0
  76. package/workflows/container-contents/index.js +1 -0
  77. package/workflows/container-contents/index.js.map +1 -1
  78. package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
  79. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
  80. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  81. package/workflows/documents/create/createAdoption.js +2 -50
  82. package/workflows/documents/create/createAdoption.js.map +1 -1
  83. package/workflows/documents/create/createResponse.js +12 -1
  84. package/workflows/documents/create/createResponse.js.map +1 -1
  85. package/workflows/documents/create/createSubmission.js +14 -0
  86. package/workflows/documents/create/createSubmission.js.map +1 -0
  87. package/workflows/documents/create/index.d.ts +3 -14
  88. package/workflows/documents/create/index.js +76 -67
  89. package/workflows/documents/create/index.js.map +1 -1
  90. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
  91. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
  92. package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
  93. package/workflows/documents/purge/absentDocumentPurge.js +23 -0
  94. package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
  95. package/workflows/documents/purge/index.d.ts +1 -0
  96. package/workflows/documents/purge/index.js +1 -0
  97. package/workflows/documents/purge/index.js.map +1 -1
  98. package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
  99. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["multipartUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EACL,yCAAyC,EACzC,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AAQ,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAC3C,CAAC;IAAC,MAAM,CAAC;QACP,4EAA4E;QAC5E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACvD,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAC3B,SAA6B,EAC7B,IAAY,EACZ,UAAkB,EAClB,MAAqB;IAErB,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM;QACN,UAAU,EAAE,EAAE;QACd,OAAO,EACL,MAAM,KAAK,GAAG;YACZ,CAAC,CAAC,kBAAkB,UAAU,gEAAgE;YAC9F,CAAC,CAAC,kBAAkB,UAAU,yBAAyB,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,EAAE;KACxG,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { md5 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport {\n authorizeMultipartBlobPartUploadOperation,\n blobWireHeaderKeys,\n operationRequestPath,\n uploadMultipartBlobPartBytesOperation,\n} from \"@tearleads/validators/operation\";\nimport type { UploadMultipartBlobPartResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_MULTIPART_BLOB_PART_BYTES,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { OperationTransport } from \"../../operationTransportFactory\";\nimport type { RequestResultOptions } from \"../../types\";\nimport type { UploadMultipartBlobPartBytesRequest } from \"./get\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\ntype UploadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nfunction invalidPart(transport: OperationTransport, path: string) {\n transport.reportFailure({\n kind: \"shape\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status: null,\n statusText: \"\",\n message: \"Multipart part bytes do not match the declared length or SHA-256\",\n });\n return null;\n}\n\nasync function retryStorageStatus(status: number, attempt: number) {\n if (status === 403) return true;\n const transient = status === 429 || (status >= 500 && status <= 599);\n if (transient && attempt === 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, 250));\n }\n return transient;\n}\n\nfunction contentMd5Base64(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...md5(bytes)));\n}\n\n/**\n * Describe an encrypted part the way a stage initiation lists the parts it\n * will send first: number, exact length, and the Content-MD5 a signed upload\n * URL binds.\n */\nexport function describeMultipartBlobPart(\n partNumber: number,\n encryptedBytes: Uint8Array,\n): MultipartBlobPartDescriptor {\n return {\n byteLength: encryptedBytes.byteLength,\n contentMd5: contentMd5Base64(encryptedBytes),\n partNumber,\n };\n}\n\nasync function preparePart(input: UploadMultipartBlobPartBytesRequest) {\n // File snapshots mutable buffers and preserves ciphertext across Capacitor's\n // native HTTP bridge. Uint8Array is UTF-8 decoded there; a plain Blob becomes\n // JSON. File's base64 bridge path is byte-for-byte, including non-UTF-8 data.\n const file =\n input.encryptedBytes instanceof File\n ? input.encryptedBytes\n : new File([input.encryptedBytes], \"encrypted-blob-part\", {\n type: \"application/octet-stream\",\n });\n if (\n file.size !== input.byteLength ||\n file.size < 1 ||\n file.size > MAX_MULTIPART_BLOB_PART_BYTES\n ) {\n throw new TypeError(\"Invalid multipart part byte length\");\n }\n const bytes = await file.arrayBuffer();\n if (\n bytesToHex(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes))) !==\n input.sha256\n ) {\n throw new TypeError(\"Multipart part SHA-256 does not match its bytes\");\n }\n return { file, contentMd5: contentMd5Base64(new Uint8Array(bytes)) };\n}\n\ninterface PartUploadContext {\n readonly contentMd5: string;\n readonly input: UploadMultipartBlobPartBytesRequest;\n readonly options: RequestResultOptions;\n readonly partNumber: number;\n readonly path: string;\n readonly stageId: string;\n readonly transport: OperationTransport;\n}\n\n// Sign just in time for this part. The returned descriptor must name exactly\n// the part, upload, length, and checksum that were requested.\nasync function authorizePart(\n context: PartUploadContext,\n): Promise<MultipartBlobPartUploadSource | null> {\n const operation = authorizeMultipartBlobPartUploadOperation;\n const { input, partNumber, stageId } = context;\n const result = await context.transport.requestResult(\n operation,\n {\n params: { stageId, partNumber },\n body: {\n byteLength: input.byteLength,\n contentMd5: context.contentMd5,\n uploadId: input.uploadId,\n },\n },\n context.options,\n );\n if (!result.ok) return null;\n const descriptor = result.data;\n if (\n descriptor.stageId !== stageId ||\n descriptor.uploadId !== input.uploadId ||\n descriptor.partNumber !== partNumber ||\n descriptor.byteLength !== input.byteLength ||\n descriptor.contentMd5 !== context.contentMd5\n ) {\n context.transport.reportFailure({\n kind: \"shape\",\n method: operation.method,\n path: context.path,\n status: 200,\n statusText: \"\",\n message: \"Multipart upload descriptor does not match its part\",\n });\n return null;\n }\n return descriptor.source;\n}\n\n// Parts can wait behind other transfers in the shared pool. An issued URL that\n// is about to lapse would only spend this part's retry on a certain 403, so\n// authorize afresh instead; a skewed clock errs toward authorizing.\nconst ISSUED_URL_MIN_REMAINING_MS = 30_000;\n\nfunction isUsableIssuedSource(\n source: MultipartBlobPartUploadSource | undefined,\n): source is MultipartBlobPartUploadSource {\n return (\n source !== undefined &&\n (source.kind === \"api\" ||\n Date.parse(source.expiresAt) - Date.now() > ISSUED_URL_MIN_REMAINING_MS)\n );\n}\n\n// A capability path for memory/custom stores; S3/R2 never proxy parts.\nfunction uploadThroughApi(context: PartUploadContext, file: File) {\n const { input } = context;\n return context.transport.requestBinaryRequest(\n uploadMultipartBlobPartBytesOperation,\n {\n params: { stageId: context.stageId, partNumber: context.partNumber },\n body: input.encryptedBytes,\n headers: {\n [blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),\n [blobWireHeaderKeys.partSha256]: input.sha256,\n [blobWireHeaderKeys.partUploadId]: input.uploadId,\n },\n },\n { ...context.options, encodeBody: () => file },\n );\n}\n\nfunction firstAttemptSource(\n attempt: number,\n source: MultipartBlobPartUploadSource | undefined,\n): MultipartBlobPartUploadSource | null {\n return attempt === 0 && isUsableIssuedSource(source) ? source : null;\n}\n\nexport async function uploadMultipartBlobPartBytes(\n transport: OperationTransport,\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n uploadFetch: UploadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<UploadMultipartBlobPartResponse | null> {\n if (options.signal?.aborted) return null;\n const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {\n stageId,\n partNumber,\n });\n const prepared = await preparePart(input).catch(() =>\n invalidPart(transport, path),\n );\n if (!prepared) return null;\n const { file, contentMd5 } = prepared;\n const context: PartUploadContext = {\n contentMd5,\n input,\n options,\n partNumber,\n path,\n stageId,\n transport,\n };\n let status: number | null = null;\n // The first attempt uses the source the stage initiation issued, if any. A\n // network failure may be an expired URL hidden by R2 CORS, or a lost success\n // response; reauthorize once and send the same immutable bytes to the same\n // part number.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const source =\n firstAttemptSource(attempt, input.source) ??\n (await authorizePart(context));\n if (!source || options.signal?.aborted) return null;\n if (source.kind === \"api\") return uploadThroughApi(context, file);\n const outcome = await putStoragePart(\n context,\n file,\n source.url,\n uploadFetch,\n attempt,\n );\n if (outcome.kind === \"uploaded\") return outcome.response;\n status = outcome.status;\n if (!outcome.retry) break;\n }\n reportStorageFailureUnlessAborted(context, status);\n return null;\n}\n\nfunction reportStorageFailureUnlessAborted(\n context: PartUploadContext,\n status: number | null,\n): void {\n if (context.options.signal?.aborted) return;\n reportStorageFailure(\n context.transport,\n context.path,\n context.partNumber,\n status,\n );\n}\n\ntype StoragePartAttempt =\n | {\n readonly kind: \"uploaded\";\n readonly response: UploadMultipartBlobPartResponse;\n }\n | {\n readonly kind: \"failed\";\n readonly retry: boolean;\n readonly status: number | null;\n };\n\nasync function putStoragePart(\n context: PartUploadContext,\n file: File,\n url: string,\n uploadFetch: UploadFetch,\n attempt: number,\n): Promise<StoragePartAttempt> {\n const { input, partNumber } = context;\n try {\n const response = await uploadFetch(url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": context.contentMd5,\n },\n ...storageFetchOptions(context.options),\n });\n const status = response.status;\n const etag = response.headers.get(\"ETag\")?.trim();\n await response.body?.cancel().catch(() => {});\n if (status === 200 && etag) {\n return {\n kind: \"uploaded\",\n response: {\n stageId: context.stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n },\n };\n }\n const retry = await retryStorageStatus(status, attempt);\n return { kind: \"failed\", retry, status };\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n return { kind: \"failed\", retry: true, status: null };\n }\n}\n\nfunction reportStorageFailure(\n transport: OperationTransport,\n path: string,\n partNumber: number,\n status: number | null,\n) {\n transport.reportFailure({\n kind: \"storage\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status,\n statusText: \"\",\n message:\n status === 200\n ? `Multipart part ${partNumber} storage response is missing ETag; check storage CORS exposure`\n : `Multipart part ${partNumber} storage upload failed${status === null ? \"\" : ` (HTTP ${status})`}`,\n });\n}\n"]}
1
+ {"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["multipartUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EACL,yCAAyC,EACzC,kBAAkB,EAClB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EACL,6BAA6B,GAG9B,MAAM,4BAA4B,CAAC;AAIpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAI5D,SAAS,WAAW,CAAC,SAA6B,EAAE,IAAY;IAC9D,SAAS,CAAC,aAAa,CA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D;aACF,CAAC;QACJ,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACxD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAC3C,CAAC;IAAC,MAAM,CAAC;QACP,4EAA4E;QAC5E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACvD,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAC3B,SAA6B,EAC7B,IAAY,EACZ,UAAkB,EAClB,MAAqB;IAErB,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM;QACN,UAAU,EAAE,EAAE;QACd,OAAO,EACL,MAAM,KAAK,GAAG;YACZ,CAAC,CAAC,kBAAkB,UAAU,gEAAgE;YAC9F,CAAC,CAAC,kBAAkB,UAAU,yBAAyB,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,EAAE;KACxG,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { md5 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport {\n authorizeMultipartBlobPartUploadOperation,\n blobWireHeaderKeys,\n operationRequestPath,\n uploadMultipartBlobPartBytesOperation,\n} from \"@tearleads/validators/operation\";\nimport type { UploadMultipartBlobPartResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_MULTIPART_BLOB_PART_BYTES,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { OperationTransport } from \"../../operationTransportFactory\";\nimport type { RequestResultOptions } from \"../../types\";\nimport type { UploadMultipartBlobPartBytesRequest } from \"./get\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\ntype UploadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nfunction invalidPart(transport: OperationTransport, path: string) {\n transport.reportFailure({\n kind: \"shape\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status: null,\n statusText: \"\",\n message: \"Multipart part bytes do not match the declared length or SHA-256\",\n });\n return null;\n}\n\nasync function retryStorageStatus(status: number, attempt: number) {\n if (status === 403) return true;\n const transient = status === 429 || (status >= 500 && status <= 599);\n if (transient && attempt === 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, 250));\n }\n return transient;\n}\n\nfunction contentMd5Base64(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...md5(bytes)));\n}\n\n/**\n * Describe an encrypted part the way a stage initiation lists the parts it\n * will send first: number, exact length, and the Content-MD5 a signed upload\n * URL binds.\n */\nexport function describeMultipartBlobPart(\n partNumber: number,\n encryptedBytes: Uint8Array,\n): MultipartBlobPartDescriptor {\n return {\n byteLength: encryptedBytes.byteLength,\n contentMd5: contentMd5Base64(encryptedBytes),\n partNumber,\n };\n}\n\nasync function preparePart(input: UploadMultipartBlobPartBytesRequest) {\n // File snapshots mutable buffers and preserves ciphertext across Capacitor's\n // native HTTP bridge. Uint8Array is UTF-8 decoded there; a plain Blob becomes\n // JSON. File's base64 bridge path is byte-for-byte, including non-UTF-8 data.\n const file =\n input.encryptedBytes instanceof File\n ? input.encryptedBytes\n : new File([input.encryptedBytes], \"encrypted-blob-part\", {\n type: \"application/octet-stream\",\n });\n if (\n file.size !== input.byteLength ||\n file.size < 1 ||\n file.size > MAX_MULTIPART_BLOB_PART_BYTES\n ) {\n throw new TypeError(\"Invalid multipart part byte length\");\n }\n const bytes = await file.arrayBuffer();\n if (\n bytesToHex(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes))) !==\n input.sha256\n ) {\n throw new TypeError(\"Multipart part SHA-256 does not match its bytes\");\n }\n return { file, contentMd5: contentMd5Base64(new Uint8Array(bytes)) };\n}\n\ninterface PartUploadContext {\n readonly contentMd5: string;\n readonly input: UploadMultipartBlobPartBytesRequest;\n readonly options: RequestResultOptions;\n readonly partNumber: number;\n readonly path: string;\n readonly stageId: string;\n readonly transport: OperationTransport;\n}\n\n// Sign just in time for this part. The returned descriptor must name exactly\n// the part, upload, length, and checksum that were requested.\nasync function authorizePart(\n context: PartUploadContext,\n): Promise<MultipartBlobPartUploadSource | null> {\n const operation = authorizeMultipartBlobPartUploadOperation;\n const { input, partNumber, stageId } = context;\n const result = await context.transport.requestResult(\n operation,\n {\n params: { stageId, partNumber },\n body: {\n byteLength: input.byteLength,\n contentMd5: context.contentMd5,\n uploadId: input.uploadId,\n },\n },\n context.options,\n );\n if (!result.ok) return null;\n const descriptor = result.data;\n if (\n descriptor.stageId !== stageId ||\n descriptor.uploadId !== input.uploadId ||\n descriptor.partNumber !== partNumber ||\n descriptor.byteLength !== input.byteLength ||\n descriptor.contentMd5 !== context.contentMd5\n ) {\n context.transport.reportFailure({\n kind: \"shape\",\n method: operation.method,\n path: context.path,\n status: 200,\n statusText: \"\",\n message: \"Multipart upload descriptor does not match its part\",\n });\n return null;\n }\n return descriptor.source;\n}\n\n// Parts can wait behind other transfers in the shared pool. An issued URL that\n// is about to lapse would only spend this part's retry on a certain 403, so\n// authorize afresh instead; a skewed clock errs toward authorizing.\nconst ISSUED_URL_MIN_REMAINING_MS = 30_000;\n\nfunction isUsableIssuedSource(\n source: MultipartBlobPartUploadSource | undefined,\n): source is MultipartBlobPartUploadSource {\n return (\n source !== undefined &&\n (source.kind === \"api\" ||\n Date.parse(source.expiresAt) - Date.now() > ISSUED_URL_MIN_REMAINING_MS)\n );\n}\n\n// A capability path for memory/custom stores; S3/R2 never proxy parts.\nfunction uploadThroughApi(context: PartUploadContext, file: File) {\n const { input } = context;\n return context.transport.requestBinaryRequest(\n uploadMultipartBlobPartBytesOperation,\n {\n params: { stageId: context.stageId, partNumber: context.partNumber },\n body: input.encryptedBytes,\n headers: {\n [blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),\n [blobWireHeaderKeys.partSha256]: input.sha256,\n [blobWireHeaderKeys.partUploadId]: input.uploadId,\n },\n },\n { ...context.options, encodeBody: () => file },\n );\n}\n\nfunction firstAttemptSource(\n attempt: number,\n source: MultipartBlobPartUploadSource | undefined,\n): MultipartBlobPartUploadSource | null {\n return attempt === 0 && isUsableIssuedSource(source) ? source : null;\n}\n\nexport async function uploadMultipartBlobPartBytes(\n transport: OperationTransport,\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n uploadFetch: UploadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<UploadMultipartBlobPartResponse | null> {\n const current = () =>\n !options.signal?.aborted && options.stillCurrent?.() !== false;\n if (!current()) return null;\n const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {\n stageId,\n partNumber,\n });\n const prepared = await preparePart(input).catch(() =>\n invalidPart(transport, path),\n );\n if (!prepared) return null;\n const { file, contentMd5 } = prepared;\n const context: PartUploadContext = {\n contentMd5,\n input,\n options,\n partNumber,\n path,\n stageId,\n transport,\n };\n return transferPreparedPart(context, file, uploadFetch, current);\n}\n\nasync function transferPreparedPart(\n context: PartUploadContext,\n file: File,\n uploadFetch: UploadFetch,\n current: () => boolean,\n): Promise<UploadMultipartBlobPartResponse | null> {\n const { input } = context;\n let status: number | null = null;\n // The first attempt uses the source the stage initiation issued, if any. A\n // network failure may be an expired URL hidden by R2 CORS, or a lost success\n // response; reauthorize once and send the same immutable bytes to the same\n // part number.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (!current()) return null;\n const source =\n firstAttemptSource(attempt, input.source) ??\n (await authorizePart(context));\n if (!source || !current()) return null;\n if (source.kind === \"api\") return uploadThroughApi(context, file);\n const outcome = await putStoragePart(\n context,\n file,\n source.url,\n uploadFetch,\n attempt,\n );\n if (!current()) return null;\n if (outcome.kind === \"uploaded\") return outcome.response;\n status = outcome.status;\n if (!outcome.retry) break;\n }\n reportStorageFailureUnlessAborted(context, status);\n return null;\n}\n\nfunction reportStorageFailureUnlessAborted(\n context: PartUploadContext,\n status: number | null,\n): void {\n if (context.options.signal?.aborted) return;\n reportStorageFailure(\n context.transport,\n context.path,\n context.partNumber,\n status,\n );\n}\n\ntype StoragePartAttempt =\n | {\n readonly kind: \"uploaded\";\n readonly response: UploadMultipartBlobPartResponse;\n }\n | {\n readonly kind: \"failed\";\n readonly retry: boolean;\n readonly status: number | null;\n };\n\nasync function putStoragePart(\n context: PartUploadContext,\n file: File,\n url: string,\n uploadFetch: UploadFetch,\n attempt: number,\n): Promise<StoragePartAttempt> {\n const { input, partNumber } = context;\n try {\n const response = await uploadFetch(url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": context.contentMd5,\n },\n ...storageFetchOptions(context.options),\n });\n const status = response.status;\n const etag = response.headers.get(\"ETag\")?.trim();\n await response.body?.cancel().catch(() => {});\n if (status === 200 && etag) {\n return {\n kind: \"uploaded\",\n response: {\n stageId: context.stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n },\n };\n }\n const retry = await retryStorageStatus(status, attempt);\n return { kind: \"failed\", retry, status };\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n return { kind: \"failed\", retry: true, status: null };\n }\n}\n\nfunction reportStorageFailure(\n transport: OperationTransport,\n path: string,\n partNumber: number,\n status: number | null,\n) {\n transport.reportFailure({\n kind: \"storage\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status,\n statusText: \"\",\n message:\n status === 200\n ? `Multipart part ${partNumber} storage response is missing ETag; check storage CORS exposure`\n : `Multipart part ${partNumber} storage upload failed${status === null ? \"\" : ` (HTTP ${status})`}`,\n });\n}\n"]}
@@ -45,6 +45,9 @@ export function renewalUnlessAborted(renewal, signal) {
45
45
  });
46
46
  });
47
47
  }
48
+ function shouldReportRenewalError(options) {
49
+ return options.stillCurrent?.() !== false && (options.reportErrors ?? true);
50
+ }
48
51
  /**
49
52
  * Decides whether a failed request can be replayed after session renewal.
50
53
  * Identity-integrity failures are terminal and must retain their typed error.
@@ -71,10 +74,12 @@ export async function shouldRetryAfterSessionExpired(input) {
71
74
  if (error instanceof KeyingVerificationError) {
72
75
  throw error;
73
76
  }
74
- if (input.options.reportErrors ?? true) {
77
+ if (shouldReportRenewalError(input.options)) {
75
78
  input.reportError(`Session refresh failed: ${errorMessage(error)}`);
76
79
  }
77
80
  }
81
+ if (input.options.stillCurrent?.() === false)
82
+ return false;
78
83
  const refreshedToken = input.getCurrentAuthToken();
79
84
  const renewed = Boolean(refreshed &&
80
85
  refreshedToken &&
@@ -1 +1 @@
1
- {"version":3,"file":"sessionRefresh.js","sourceRoot":"","sources":["sessionRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAgB5B;;;GAGG;AACH,SAAS,iBAAiB,CACxB,KAA0B,EAC1B,SAAiB;IAEjB,MAAM,gBAAgB,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACrD,IAAI,gBAAgB,KAAK,SAAS;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7D,MAAM,OAAO,GACX,gBAAgB,KAAK,IAAI;QACzB,KAAK,CAAC,qBAAqB,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC3D,IAAI,OAAO,EAAE,CAAC;QACZ,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,OAAO,GAAG,KAAK,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAAC;IACvD,IAAI,CAAC,gBAAgB,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAC;IAChD,OAAO,EAAE,OAAO,EAAE,CAAC;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AyB,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,EAC5D,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,UAAU,GAAG,iBAAiB,CAAC,KAAK,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAC7D,IAAI,OAAO,UAAU,KAAK,SAAS;QAAE,OAAO,UAAU,CAAC;IACvD,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC;IACnC,sEAAsE;IACtE,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO;QAAE,OAAO,KAAK,CAAC;IAEhD,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,CAAC;QACH,SAAS,GAAG,MAAM,oBAAoB,CACpC,OAAO,IAAI,KAAK,CAAC,cAAc,EAAE,EACjC,KAAK,CAAC,OAAO,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,IAAI,KAAK,YAAY,uBAAuB,EAAE,CAAC;YAC7C,MAAM,KAAK,CAAC;QACd,CAAC;QACD,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,IAAI,IAAI,EAAE,CAAC;YACvC,KAAK,CAAC,WAAW,CAAC,2BAA2B,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACtE,CAAC;IACH,CAAC;IAED,MAAM,cAAc,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACnD,MAAM,OAAO,GAAG,OAAO,CACrB,SAAS;QACP,cAAc;QACd,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,cAAc,CAAC,CAC/D,CAAC;IACF,IAAI,OAAO;QAAE,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n errorMessage,\n isRefreshableSessionError,\n isReplayableRequestBody,\n} from \"./requestInternals\";\nimport type { RequestBody, RequestResultOptions } from \"./types\";\n\ninterface SessionRefreshInput {\n readonly authToken: string | null;\n readonly body: RequestBody | undefined;\n readonly code: string | null;\n readonly getCurrentAuthToken: () => string | null;\n readonly isKnownSessionRenewal: (from: string, to: string) => boolean;\n readonly options: RequestResultOptions;\n readonly pendingSessionRenewal: (from: string) => Promise<boolean> | null;\n readonly refreshSession: () => boolean | Promise<boolean>;\n readonly reportError: (message: string) => void;\n readonly responseStatus: number;\n}\n\n/**\n * Checks for a renewal that another request already started or finished: a\n * boolean is the final answer, otherwise `pending` (null when none) is awaited.\n */\nfunction concurrentRenewal(\n input: SessionRefreshInput,\n authToken: string,\n): boolean | { readonly pending: Promise<boolean> | null } {\n const currentAuthToken = input.getCurrentAuthToken();\n if (currentAuthToken === authToken) return { pending: null };\n const renewed =\n currentAuthToken !== null &&\n input.isKnownSessionRenewal(authToken, currentAuthToken);\n if (renewed) {\n input.options.onSessionRenewed?.();\n return true;\n }\n const pending = input.pendingSessionRenewal(authToken);\n if (!currentAuthToken || !pending) return false;\n return { pending };\n}\n\n/**\n * Ends a request's wait for a renewal when its signal aborts. Only the wait\n * ends: the renewal is shared with other requests and keeps running, and a\n * rejection it settles with later is still delivered to them.\n */\nexport function renewalUnlessAborted(\n renewal: boolean | Promise<boolean>,\n signal: AbortSignal | undefined,\n): Promise<boolean> {\n if (!signal) return Promise.resolve(renewal);\n // Starting the renewal can abort the signal before a listener exists. The\n // renewal is still consumed, so a later rejection is never unhandled.\n if (signal.aborted) {\n Promise.resolve(renewal).catch(() => undefined);\n return Promise.resolve(false);\n }\n return new Promise<boolean>((resolve, reject) => {\n const abandon = () => resolve(false);\n signal.addEventListener(\"abort\", abandon, { once: true });\n Promise.resolve(renewal).then(\n (renewed) => {\n signal.removeEventListener(\"abort\", abandon);\n resolve(renewed);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", abandon);\n reject(error);\n },\n );\n });\n}\n\n/**\n * Decides whether a failed request can be replayed after session renewal.\n * Identity-integrity failures are terminal and must retain their typed error.\n */\nexport async function shouldRetryAfterSessionExpired(\n input: SessionRefreshInput,\n): Promise<boolean> {\n if (\n input.options.retryOnSessionExpired === false ||\n !input.authToken ||\n !isReplayableRequestBody(input.body) ||\n !isRefreshableSessionError(input.responseStatus, input.code)\n ) {\n return false;\n }\n\n const concurrent = concurrentRenewal(input, input.authToken);\n if (typeof concurrent === \"boolean\") return concurrent;\n const pending = concurrent.pending;\n // An aborted request has no use for a renewal and must not start one.\n if (input.options.signal?.aborted) return false;\n\n let refreshed = false;\n try {\n refreshed = await renewalUnlessAborted(\n pending ?? input.refreshSession(),\n input.options.signal,\n );\n } catch (error: unknown) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n if (input.options.reportErrors ?? true) {\n input.reportError(`Session refresh failed: ${errorMessage(error)}`);\n }\n }\n\n const refreshedToken = input.getCurrentAuthToken();\n const renewed = Boolean(\n refreshed &&\n refreshedToken &&\n input.isKnownSessionRenewal(input.authToken, refreshedToken),\n );\n if (renewed) input.options.onSessionRenewed?.();\n return renewed;\n}\n"]}
1
+ {"version":3,"file":"sessionRefresh.js","sourceRoot":"","sources":["sessionRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAgB5B;;;GAGG;AACH,SAAS,iBAAiB,CACxB,KAA0B,EAC1B,SAAiB;IAEjB,MAAM,gBAAgB,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACrD,IAAI,gBAAgB,KAAK,SAAS;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7D,MAAM,OAAO,GACX,gBAAgB,KAAK,IAAI;QACzB,KAAK,CAAC,qBAAqB,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC3D,IAAI,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AAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACtE,CAAC;IACH,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IAC3D,MAAM,cAAc,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACnD,MAAM,OAAO,GAAG,OAAO,CACrB,SAAS;QACP,cAAc;QACd,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,cAAc,CAAC,CAC/D,CAAC;IACF,IAAI,OAAO;QAAE,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n errorMessage,\n isRefreshableSessionError,\n isReplayableRequestBody,\n} from \"./requestInternals\";\nimport type { RequestBody, RequestResultOptions } from \"./types\";\n\ninterface SessionRefreshInput {\n readonly authToken: string | null;\n readonly body: RequestBody | undefined;\n readonly code: string | null;\n readonly getCurrentAuthToken: () => string | null;\n readonly isKnownSessionRenewal: (from: string, to: string) => boolean;\n readonly options: RequestResultOptions;\n readonly pendingSessionRenewal: (from: string) => Promise<boolean> | null;\n readonly refreshSession: () => boolean | Promise<boolean>;\n readonly reportError: (message: string) => void;\n readonly responseStatus: number;\n}\n\n/**\n * Checks for a renewal that another request already started or finished: a\n * boolean is the final answer, otherwise `pending` (null when none) is awaited.\n */\nfunction concurrentRenewal(\n input: SessionRefreshInput,\n authToken: string,\n): boolean | { readonly pending: Promise<boolean> | null } {\n const currentAuthToken = input.getCurrentAuthToken();\n if (currentAuthToken === authToken) return { pending: null };\n const renewed =\n currentAuthToken !== null &&\n input.isKnownSessionRenewal(authToken, currentAuthToken);\n if (renewed) {\n input.options.onSessionRenewed?.();\n return true;\n }\n const pending = input.pendingSessionRenewal(authToken);\n if (!currentAuthToken || !pending) return false;\n return { pending };\n}\n\n/**\n * Ends a request's wait for a renewal when its signal aborts. Only the wait\n * ends: the renewal is shared with other requests and keeps running, and a\n * rejection it settles with later is still delivered to them.\n */\nexport function renewalUnlessAborted(\n renewal: boolean | Promise<boolean>,\n signal: AbortSignal | undefined,\n): Promise<boolean> {\n if (!signal) return Promise.resolve(renewal);\n // Starting the renewal can abort the signal before a listener exists. The\n // renewal is still consumed, so a later rejection is never unhandled.\n if (signal.aborted) {\n Promise.resolve(renewal).catch(() => undefined);\n return Promise.resolve(false);\n }\n return new Promise<boolean>((resolve, reject) => {\n const abandon = () => resolve(false);\n signal.addEventListener(\"abort\", abandon, { once: true });\n Promise.resolve(renewal).then(\n (renewed) => {\n signal.removeEventListener(\"abort\", abandon);\n resolve(renewed);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", abandon);\n reject(error);\n },\n );\n });\n}\n\nfunction shouldReportRenewalError(options: RequestResultOptions) {\n return options.stillCurrent?.() !== false && (options.reportErrors ?? true);\n}\n\n/**\n * Decides whether a failed request can be replayed after session renewal.\n * Identity-integrity failures are terminal and must retain their typed error.\n */\nexport async function shouldRetryAfterSessionExpired(\n input: SessionRefreshInput,\n): Promise<boolean> {\n if (\n input.options.retryOnSessionExpired === false ||\n !input.authToken ||\n !isReplayableRequestBody(input.body) ||\n !isRefreshableSessionError(input.responseStatus, input.code)\n ) {\n return false;\n }\n\n const concurrent = concurrentRenewal(input, input.authToken);\n if (typeof concurrent === \"boolean\") return concurrent;\n const pending = concurrent.pending;\n // An aborted request has no use for a renewal and must not start one.\n if (input.options.signal?.aborted) return false;\n\n let refreshed = false;\n try {\n refreshed = await renewalUnlessAborted(\n pending ?? input.refreshSession(),\n input.options.signal,\n );\n } catch (error: unknown) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n if (shouldReportRenewalError(input.options)) {\n input.reportError(`Session refresh failed: ${errorMessage(error)}`);\n }\n }\n\n if (input.options.stillCurrent?.() === false) return false;\n const refreshedToken = input.getCurrentAuthToken();\n const renewed = Boolean(\n refreshed &&\n refreshedToken &&\n input.isKnownSessionRenewal(input.authToken, refreshedToken),\n );\n if (renewed) input.options.onSessionRenewed?.();\n return renewed;\n}\n"]}
@@ -1,5 +1,8 @@
1
1
  import { errorMessage } from "./requestInternals.js";
2
2
  import { responseBodyFailure } from "./responseBodyFailure.js";
3
+ export function requestRetired(session, options) {
4
+ return session?.aborted || options?.stillCurrent?.() === false;
5
+ }
3
6
  /** A retired request cannot overwrite the active session's failure cache. */
4
7
  export function retiredRequest(method, path) {
5
8
  return {
@@ -17,12 +20,12 @@ export function retiredRequest(method, path) {
17
20
  export async function readSessionJson(request, response, method, path, options, session) {
18
21
  try {
19
22
  const data = await response.json();
20
- if (session?.aborted)
23
+ if (requestRetired(session, options))
21
24
  return retiredRequest(method, path);
22
25
  return { ok: true, data };
23
26
  }
24
27
  catch (error) {
25
- if (session?.aborted)
28
+ if (requestRetired(session, options))
26
29
  return retiredRequest(method, path);
27
30
  const failure = responseBodyFailure(error, errorMessage(error), options.signal?.aborted === true);
28
31
  return request.reportFailure({
@@ -1 +1 @@
1
- {"version":3,"file":"sessionResponse.js","sourceRoot":"","sources":["sessionResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAS5D,6EAA6E;AAC7E,MAAM,UAAU,cAAc,CAC5B,MAAkB,EAClB,IAAY;IAEZ,OAAO;QACL,IAAI,EAAE,iBAAiB;QACvB,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,iBAAiB;QAC3C,MAAM;QACN,EAAE,EAAE,KAAK;QACT,IAAI;QACJ,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;QAChB,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,EAAE;KACf,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,OAAmC,EACnC,QAAkB,EAClB,MAAkB,EAClB,IAAY,EACZ,OAA6B,EAC7B,OAAgC;IAEhC,IAAI,CAAC;QACH,MAAM,IAAI,GAAY,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5C,IAAI,OAAO,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1D,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,OAAO,EAAE,OAAO;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1D,MAAM,OAAO,GAAG,mBAAmB,CACjC,KAAK,EACL,YAAY,CAAC,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CACjC,CAAC;QACF,OAAO,OAAO,CAAC,aAAa,CAAC;YAC3B,GAAG,OAAO;YACV,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,KAAK,OAAO,CAAC,OAAO,EAAE;YAChD,MAAM;YACN,OAAO;YACP,IAAI;YACJ,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;SAChC,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { errorMessage } from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport type {\n HttpMethod,\n OperationResponseRequestFn,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\n/** A retired request cannot overwrite the active session's failure cache. */\nexport function retiredRequest(\n method: HttpMethod,\n path: string,\n): RequestFailure {\n return {\n code: \"request_aborted\",\n kind: \"cancelled\",\n message: `${method} ${path}: Sign-in ended`,\n method,\n ok: false,\n path,\n report: () => {},\n status: null,\n statusText: \"\",\n };\n}\n\nexport async function readSessionJson(\n request: OperationResponseRequestFn,\n response: Response,\n method: HttpMethod,\n path: string,\n options: RequestResultOptions,\n session: AbortSignal | undefined,\n): Promise<RequestResult<unknown>> {\n try {\n const data: unknown = await response.json();\n if (session?.aborted) return retiredRequest(method, path);\n return { ok: true, data };\n } catch (error) {\n if (session?.aborted) return retiredRequest(method, path);\n const failure = responseBodyFailure(\n error,\n errorMessage(error),\n options.signal?.aborted === true,\n );\n return request.reportFailure({\n ...failure,\n message: `${method} ${path}: ${failure.message}`,\n method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"sessionResponse.js","sourceRoot":"","sources":["sessionResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAS5D,MAAM,UAAU,cAAc,CAC5B,OAAgC,EAChC,OAA8B;IAE9B,OAAO,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,KAAK,CAAC;AACjE,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,cAAc,CAC5B,MAAkB,EAClB,IAAY;IAEZ,OAAO;QACL,IAAI,EAAE,iBAAiB;QACvB,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,iBAAiB;QAC3C,MAAM;QACN,EAAE,EAAE,KAAK;QACT,IAAI;QACJ,MAAM,EAAE,GAAG,EAAE,GAAE,CAAC;QAChB,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,EAAE;KACf,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,OAAmC,EACnC,QAAkB,EAClB,MAAkB,EAClB,IAAY,EACZ,OAA6B,EAC7B,OAAgC;IAEhC,IAAI,CAAC;QACH,MAAM,IAAI,GAAY,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5C,IAAI,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1E,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1E,MAAM,OAAO,GAAG,mBAAmB,CACjC,KAAK,EACL,YAAY,CAAC,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CACjC,CAAC;QACF,OAAO,OAAO,CAAC,aAAa,CAAC;YAC3B,GAAG,OAAO;YACV,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,KAAK,OAAO,CAAC,OAAO,EAAE;YAChD,MAAM;YACN,OAAO;YACP,IAAI;YACJ,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;SAChC,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { errorMessage } from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport type {\n HttpMethod,\n OperationResponseRequestFn,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport function requestRetired(\n session: AbortSignal | undefined,\n options?: RequestResultOptions,\n) {\n return session?.aborted || options?.stillCurrent?.() === false;\n}\n\n/** A retired request cannot overwrite the active session's failure cache. */\nexport function retiredRequest(\n method: HttpMethod,\n path: string,\n): RequestFailure {\n return {\n code: \"request_aborted\",\n kind: \"cancelled\",\n message: `${method} ${path}: Sign-in ended`,\n method,\n ok: false,\n path,\n report: () => {},\n status: null,\n statusText: \"\",\n };\n}\n\nexport async function readSessionJson(\n request: OperationResponseRequestFn,\n response: Response,\n method: HttpMethod,\n path: string,\n options: RequestResultOptions,\n session: AbortSignal | undefined,\n): Promise<RequestResult<unknown>> {\n try {\n const data: unknown = await response.json();\n if (requestRetired(session, options)) return retiredRequest(method, path);\n return { ok: true, data };\n } catch (error) {\n if (requestRetired(session, options)) return retiredRequest(method, path);\n const failure = responseBodyFailure(\n error,\n errorMessage(error),\n options.signal?.aborted === true,\n );\n return request.reportFailure({\n ...failure,\n message: `${method} ${path}: ${failure.message}`,\n method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n }\n}\n"]}
@@ -8,6 +8,8 @@ export type ListDocumentEditAttributionRangesOptions = Omit<DocumentAttributionR
8
8
  cursor?: DocumentAttributionRangesQuery["cursor"] | null;
9
9
  };
10
10
  export interface RequestResultOptions {
11
+ /** Checked at dispatch, on renewal and before handling the response. */
12
+ readonly stillCurrent?: (() => boolean) | undefined;
11
13
  readonly signal?: AbortSignal | undefined;
12
14
  /** Expected target for a declared 402; mismatched response identities fail closed. */
13
15
  readonly expectedPaymentRequiredOrganizationId?: string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { ApiNetworkError } from \"./networkFailure\";\nimport type { WriterProjectionListing } from \"./verifiedManifestCitations\";\n\nexport type HttpMethod = HttpOperationMethod;\nexport type RequestBody = BodyInit;\n\nexport type ListDocumentEditAttributionRangesOptions = Omit<\n DocumentAttributionRangesQuery,\n \"cursor\"\n> & {\n cursor?: DocumentAttributionRangesQuery[\"cursor\"] | null;\n};\n\nexport interface RequestResultOptions {\n readonly signal?: AbortSignal | undefined;\n /** Expected target for a declared 402; mismatched response identities fail closed. */\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly reportErrors?: boolean | undefined;\n /** Called after this request or a concurrent request renews the same session. */\n readonly onSessionRenewed?: (() => void) | undefined;\n readonly retryOnSessionExpired?: boolean | \"renew-only\" | undefined;\n /**\n * Writer-projection reads only: where a listing placed the container, so\n * an unplaced container can cite its listed parent's held bytes. It\n * changes which hashes the read cites, never what the read accepts.\n */\n readonly projectionListing?: WriterProjectionListing | undefined;\n /**\n * Group creates, group policy commits and shares only: the organization\n * read-model cursor the caller holds. The response then carries the\n * read-model delta from it when the commit advanced from that cursor.\n */\n readonly readModelCursor?: string | undefined;\n}\n\nexport type OperationRequestFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<T | null>;\n\nexport type OperationRequestResultFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<RequestResult<T>>;\n\nexport type RequestFailureKind =\n | \"storage\"\n | \"http\"\n | \"network\"\n | \"json\"\n | \"shape\"\n | \"cancelled\"\n | \"outcome-unknown\";\n\nexport interface RequestFailure {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n /** Set when the fetch itself threw: what the client could observe, without secrets. */\n readonly networkError?: ApiNetworkError | undefined;\n readonly ok: false;\n readonly path: string;\n readonly report: () => void;\n readonly status: number | null;\n readonly statusText: string;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /**\n * With `container_descendant_rekeys_required`, the full owed set, parent-first;\n * with `container_descendant_rekeys_inaccessible`, its unwritable subset.\n * A hint, never authority; verify each container before signing for it.\n */\n readonly requiredContainerIds?: readonly string[] | undefined;\n}\n\nexport interface RequestSuccess<T> {\n readonly data: T;\n readonly ok: true;\n}\n\nexport type RequestResult<T> = RequestFailure | RequestSuccess<T>;\n\nexport interface ResponseRequestValidationFailureInput {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions | undefined;\n readonly path: string;\n readonly status: number | null;\n readonly statusText: string;\n}\n\nexport interface OperationResponseRequestFn {\n (\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: HttpOperation,\n ): Promise<RequestResult<Response>>;\n readonly sessionSignal?: () => AbortSignal;\n readonly reportFailure: (\n input: ResponseRequestValidationFailureInput,\n ) => RequestFailure;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { ApiNetworkError } from \"./networkFailure\";\nimport type { WriterProjectionListing } from \"./verifiedManifestCitations\";\n\nexport type HttpMethod = HttpOperationMethod;\nexport type RequestBody = BodyInit;\n\nexport type ListDocumentEditAttributionRangesOptions = Omit<\n DocumentAttributionRangesQuery,\n \"cursor\"\n> & {\n cursor?: DocumentAttributionRangesQuery[\"cursor\"] | null;\n};\n\nexport interface RequestResultOptions {\n /** Checked at dispatch, on renewal and before handling the response. */\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly signal?: AbortSignal | undefined;\n /** Expected target for a declared 402; mismatched response identities fail closed. */\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly reportErrors?: boolean | undefined;\n /** Called after this request or a concurrent request renews the same session. */\n readonly onSessionRenewed?: (() => void) | undefined;\n readonly retryOnSessionExpired?: boolean | \"renew-only\" | undefined;\n /**\n * Writer-projection reads only: where a listing placed the container, so\n * an unplaced container can cite its listed parent's held bytes. It\n * changes which hashes the read cites, never what the read accepts.\n */\n readonly projectionListing?: WriterProjectionListing | undefined;\n /**\n * Group creates, group policy commits and shares only: the organization\n * read-model cursor the caller holds. The response then carries the\n * read-model delta from it when the commit advanced from that cursor.\n */\n readonly readModelCursor?: string | undefined;\n}\n\nexport type OperationRequestFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<T | null>;\n\nexport type OperationRequestResultFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<RequestResult<T>>;\n\nexport type RequestFailureKind =\n | \"storage\"\n | \"http\"\n | \"network\"\n | \"json\"\n | \"shape\"\n | \"cancelled\"\n | \"outcome-unknown\";\n\nexport interface RequestFailure {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n /** Set when the fetch itself threw: what the client could observe, without secrets. */\n readonly networkError?: ApiNetworkError | undefined;\n readonly ok: false;\n readonly path: string;\n readonly report: () => void;\n readonly status: number | null;\n readonly statusText: string;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /**\n * With `container_descendant_rekeys_required`, the full owed set, parent-first;\n * with `container_descendant_rekeys_inaccessible`, its unwritable subset.\n * A hint, never authority; verify each container before signing for it.\n */\n readonly requiredContainerIds?: readonly string[] | undefined;\n}\n\nexport interface RequestSuccess<T> {\n readonly data: T;\n readonly ok: true;\n}\n\nexport type RequestResult<T> = RequestFailure | RequestSuccess<T>;\n\nexport interface ResponseRequestValidationFailureInput {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions | undefined;\n readonly path: string;\n readonly status: number | null;\n readonly statusText: string;\n}\n\nexport interface OperationResponseRequestFn {\n (\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: HttpOperation,\n ): Promise<RequestResult<Response>>;\n readonly sessionSignal?: () => AbortSignal;\n readonly reportFailure: (\n input: ResponseRequestValidationFailureInput,\n ) => RequestFailure;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.256",
3
+ "version": "0.1.257",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -0,0 +1,16 @@
1
+ import { type DocumentAttachment } from "../../../../data/documents/documentContent.js";
2
+ import type { StoredDocumentKind } from "../../../../data/documents/documentKinds.js";
3
+ import type { DiscoveredDocumentInput } from "../../../../data/documents/documentSummary.js";
4
+ import type { DocumentStoreOpenOptions, DocumentsRuntime } from "../../types.js";
5
+ export interface SeededDocumentInput extends Pick<DocumentStoreOpenOptions, "initialRows" | "initialStructuredFields"> {
6
+ readonly initialAttachments?: readonly DocumentAttachment[] | undefined;
7
+ /** Stamped inside the same encrypted update as the validated fixture content. */
8
+ readonly seedTag?: string | undefined;
9
+ readonly onRecoveredStaleTarget?: (() => void) | undefined;
10
+ readonly containerId: string;
11
+ readonly documentId: string;
12
+ readonly initialDocumentKind?: StoredDocumentKind | undefined;
13
+ readonly initialText?: string | undefined;
14
+ }
15
+ /** One online create, without installing a local record or queuing a birth for replay. */
16
+ export declare function createSeededDocument(runtime: DocumentsRuntime, input: SeededDocumentInput, stillCurrent: () => boolean): Promise<DiscoveredDocumentInput | "purged">;
@@ -0,0 +1,119 @@
1
+ import { exportAllUpdates } from "../../../../internal/loro/index.js";
2
+ import { DEFAULT_DOCUMENT_KIND } from "../../../../data/documents/documentConstants.js";
3
+ import { addDocumentAttachments, getDocumentAttachments, sameDocumentAttachments, writeSeedTag, } from "../../../../data/documents/documentContent.js";
4
+ import { initializeStoredDocumentKind, readStoredDocumentState, } from "../../../../data/documents/documentKinds.js";
5
+ import { listDocumentRows } from "../../../../data/documents/documentRowList.js";
6
+ import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
7
+ import { readDocumentLinkSetManifestState } from "../../../../data/documents/shared/readers.js";
8
+ import { createDocumentProjectionUserKeyResolver, RemoteDocumentService, resolveDocumentCreateAuthor, } from "../../../../workflows/documents/index.js";
9
+ import { createVerifiedRemoteDocumentDeletionHandler, hasVerifiedDocumentPurge, pinAbsentDocumentPurge, } from "../../../../workflows/documents/purge/index.js";
10
+ import { createFreshPeerStoredDocument } from "../storedDocument.js";
11
+ import { assertInitialContentFitsKind, writeInitialDocumentContent, } from "./initialContent.js";
12
+ function assertProjectedSeedContent(doc, input, projectors) {
13
+ if (input.initialRows?.length) {
14
+ const rows = listDocumentRows(doc);
15
+ if (input.initialRows.some((row, index) => Object.entries(row).some(([key, value]) => rows[index]?.fields[key] !== value)))
16
+ throw new Error("Invalid initial document row fields.");
17
+ }
18
+ const projected = readStoredDocumentState(doc, projectors);
19
+ const fields = Object.entries(input.initialStructuredFields ?? {});
20
+ if (projected.fieldValidationIssues.length ||
21
+ fields.some(([key, value]) => value !== undefined && projected.structuredFields[key] !== value))
22
+ throw new Error("Invalid initial document fields.");
23
+ }
24
+ async function createSeedUpdate(runtime, input) {
25
+ const doc = await createFreshPeerStoredDocument();
26
+ const initialDocumentKind = input.initialDocumentKind ?? DEFAULT_DOCUMENT_KIND;
27
+ const projectors = runtime.infra.documentProjectors;
28
+ assertInitialContentFitsKind(input, initialDocumentKind);
29
+ if (initialDocumentKind === DEFAULT_DOCUMENT_KIND &&
30
+ input.initialRows?.length)
31
+ throw new Error("A seeded note cannot contain rows.");
32
+ initializeStoredDocumentKind(doc, initialDocumentKind, projectors);
33
+ if (input.initialText)
34
+ doc.getText("text").update(input.initialText);
35
+ writeInitialDocumentContent({ runtime, initialContent: input, initialDocumentKind }, doc);
36
+ const attachments = input.initialAttachments ?? [];
37
+ addDocumentAttachments(doc, attachments);
38
+ if (!sameDocumentAttachments(attachments, getDocumentAttachments(doc)) ||
39
+ attachments.some((item) => !item.slotId.length || !Number.isSafeInteger(item.byteLength)))
40
+ throw new Error("Invalid or duplicate initial attachment metadata.");
41
+ assertProjectedSeedContent(doc, input, projectors);
42
+ if (input.seedTag && doc.opCount() > 0)
43
+ writeSeedTag(doc, input.seedTag);
44
+ const update = createPendingUpdateFields(exportAllUpdates(doc));
45
+ if (!update)
46
+ throw new Error("Seeded creation requires initial content.");
47
+ return update;
48
+ }
49
+ function seededPlacement(containerId, manifest) {
50
+ const state = readDocumentLinkSetManifestState(manifest.state, "Seeded document");
51
+ return {
52
+ documentId: state.documentId,
53
+ containerId,
54
+ linkedContainerIds: [...state.linkedContainerIds],
55
+ accessEpoch: state.epoch,
56
+ accessStateHash: manifest.manifestHash,
57
+ createdAt: new Date().toISOString(),
58
+ };
59
+ }
60
+ /** One online create, without installing a local record or queuing a birth for replay. */
61
+ export async function createSeededDocument(runtime, input, stillCurrent) {
62
+ const author = resolveDocumentCreateAuthor(runtime);
63
+ const keys = runtime.crypto.encapsulationKeyPair;
64
+ if (!author || !keys || !runtime.state.online)
65
+ throw new Error("An online signing identity is required to seed a document.");
66
+ const purged = await hasVerifiedDocumentPurge(runtime.infra.execSql, input.documentId, author.organizationId);
67
+ if (!stillCurrent())
68
+ throw new Error("The account or database scope changed during seeded creation.");
69
+ if (purged)
70
+ return "purged";
71
+ const update = await createSeedUpdate(runtime, input);
72
+ const remote = new RemoteDocumentService({
73
+ api: runtime.apiClient,
74
+ execSql: runtime.infra.execSql,
75
+ encapsulationSecretKey: keys.secretKey,
76
+ isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,
77
+ });
78
+ let failure;
79
+ const verification = {
80
+ resolveProjectionUserKey: createDocumentProjectionUserKeyResolver(runtime),
81
+ warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),
82
+ stillCurrent,
83
+ };
84
+ const created = await remote.createRemoteDocument({
85
+ ...verification,
86
+ onTerminalSubmitFailure: (result) => {
87
+ failure = result;
88
+ },
89
+ author,
90
+ containerId: input.containerId,
91
+ documentId: input.documentId,
92
+ expectedOrganizationId: author.organizationId,
93
+ requireSeededCreate: true,
94
+ onRecoveredStaleTarget: input.onRecoveredStaleTarget,
95
+ seedUpdate: { ...update, id: crypto.randomUUID() },
96
+ });
97
+ if (!stillCurrent())
98
+ throw new Error("The account or database scope changed during seeded creation.");
99
+ if (!created &&
100
+ failure?.status === 409 &&
101
+ failure.message.endsWith("Document was permanently purged")) {
102
+ // A refusal only prompts a read. The signed proof establishes the deletion.
103
+ await createVerifiedRemoteDocumentDeletionHandler({
104
+ ...verification,
105
+ apiClient: runtime.apiClient,
106
+ execSql: runtime.infra.execSql,
107
+ expectedOrganizationId: author.organizationId,
108
+ onVerifiedDeletion: ({ commitPurgeProof, documentId }) => pinAbsentDocumentPurge(runtime.infra.execSql, documentId, commitPurgeProof),
109
+ })({ documentId: input.documentId });
110
+ if (!stillCurrent())
111
+ throw new Error("The account or database scope changed during purge verification.");
112
+ return "purged";
113
+ }
114
+ if (!created)
115
+ throw new Error(failure?.message ??
116
+ "Could not commit the seeded document. Run seed again to resume.");
117
+ return seededPlacement(input.containerId, created.writerProjection.documentManifest);
118
+ }
119
+ //# sourceMappingURL=createSeededDocument.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createSeededDocument.js","sourceRoot":"","sources":["createSeededDocument.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AACrF,OAAO,EACL,sBAAsB,EAEtB,sBAAsB,EACtB,uBAAuB,EACvB,YAAY,GACb,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EACL,4BAA4B,EAC5B,uBAAuB,GACxB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,gBAAgB,EAAE,MAAM,4CAA4C,CAAC;AAE9E,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,gCAAgC,EAAE,MAAM,2CAA2C,CAAC;AAC7F,OA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AAE,OAAO,CAAC,SAAS;YAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;YAC9B,sBAAsB,EAAE,MAAM,CAAC,cAAc;YAC7C,kBAAkB,EAAE,CAAC,EAAE,gBAAgB,EAAE,UAAU,EAAE,EAAE,EAAE,CACvD,sBAAsB,CACpB,OAAO,CAAC,KAAK,CAAC,OAAO,EACrB,UAAU,EACV,gBAAgB,CACjB;SACJ,CAAC,CAAC,EAAE,UAAU,EAAE,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;QACrC,IAAI,CAAC,YAAY,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;QACJ,OAAO,QAAQ,CAAC;IAClB,CAAC;IACD,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,KAAK,CACb,OAAO,EAAE,OAAO;YACd,iEAAiE,CACpE,CAAC;IACJ,OAAO,eAAe,CACpB,KAAK,CAAC,WAAW,EACjB,OAAO,CAAC,gBAAgB,CAAC,gBAAgB,CAC1C,CAAC;AACJ,CAAC","sourcesContent":["import { exportAllUpdates } from \"@tearleads/loro\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../../data/documents/documentConstants\";\nimport {\n addDocumentAttachments,\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n writeSeedTag,\n} from \"../../../../data/documents/documentContent\";\nimport type { StoredDocumentKind } from \"../../../../data/documents/documentKinds\";\nimport {\n initializeStoredDocumentKind,\n readStoredDocumentState,\n} from \"../../../../data/documents/documentKinds\";\nimport { listDocumentRows } from \"../../../../data/documents/documentRowList\";\nimport type { DiscoveredDocumentInput } from \"../../../../data/documents/documentSummary\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { readDocumentLinkSetManifestState } from \"../../../../data/documents/shared/readers\";\nimport {\n createDocumentProjectionUserKeyResolver,\n RemoteDocumentService,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport {\n createVerifiedRemoteDocumentDeletionHandler,\n hasVerifiedDocumentPurge,\n pinAbsentDocumentPurge,\n} from \"../../../../workflows/documents/purge\";\nimport type { DocumentStoreOpenOptions, DocumentsRuntime } from \"../../types\";\nimport { createFreshPeerStoredDocument } from \"../storedDocument\";\nimport {\n assertInitialContentFitsKind,\n writeInitialDocumentContent,\n} from \"./initialContent\";\n\nexport interface SeededDocumentInput\n extends Pick<\n DocumentStoreOpenOptions,\n \"initialRows\" | \"initialStructuredFields\"\n > {\n readonly initialAttachments?: readonly DocumentAttachment[] | undefined;\n /** Stamped inside the same encrypted update as the validated fixture content. */\n readonly seedTag?: string | undefined;\n readonly onRecoveredStaleTarget?: (() => void) | undefined;\n readonly containerId: string;\n readonly documentId: string;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n}\n\nfunction assertProjectedSeedContent(\n doc: Awaited<ReturnType<typeof createFreshPeerStoredDocument>>,\n input: SeededDocumentInput,\n projectors: DocumentsRuntime[\"infra\"][\"documentProjectors\"],\n) {\n if (input.initialRows?.length) {\n const rows = listDocumentRows(doc);\n if (\n input.initialRows.some((row, index) =>\n Object.entries(row).some(\n ([key, value]) => rows[index]?.fields[key] !== value,\n ),\n )\n )\n throw new Error(\"Invalid initial document row fields.\");\n }\n const projected = readStoredDocumentState(doc, projectors);\n const fields = Object.entries(input.initialStructuredFields ?? {});\n if (\n projected.fieldValidationIssues.length ||\n fields.some(\n ([key, value]) =>\n value !== undefined && projected.structuredFields[key] !== value,\n )\n )\n throw new Error(\"Invalid initial document fields.\");\n}\n\nasync function createSeedUpdate(\n runtime: DocumentsRuntime,\n input: SeededDocumentInput,\n) {\n const doc = await createFreshPeerStoredDocument();\n const initialDocumentKind =\n input.initialDocumentKind ?? DEFAULT_DOCUMENT_KIND;\n const projectors = runtime.infra.documentProjectors;\n assertInitialContentFitsKind(input, initialDocumentKind);\n if (\n initialDocumentKind === DEFAULT_DOCUMENT_KIND &&\n input.initialRows?.length\n )\n throw new Error(\"A seeded note cannot contain rows.\");\n initializeStoredDocumentKind(doc, initialDocumentKind, projectors);\n if (input.initialText) doc.getText(\"text\").update(input.initialText);\n writeInitialDocumentContent(\n { runtime, initialContent: input, initialDocumentKind },\n doc,\n );\n const attachments = input.initialAttachments ?? [];\n addDocumentAttachments(doc, attachments);\n if (\n !sameDocumentAttachments(attachments, getDocumentAttachments(doc)) ||\n attachments.some(\n (item) => !item.slotId.length || !Number.isSafeInteger(item.byteLength),\n )\n )\n throw new Error(\"Invalid or duplicate initial attachment metadata.\");\n assertProjectedSeedContent(doc, input, projectors);\n if (input.seedTag && doc.opCount() > 0) writeSeedTag(doc, input.seedTag);\n const update = createPendingUpdateFields(exportAllUpdates(doc));\n if (!update) throw new Error(\"Seeded creation requires initial content.\");\n return update;\n}\n\nfunction seededPlacement(\n containerId: string,\n manifest: AccessManifestBundleWireResponse,\n): DiscoveredDocumentInput {\n const state = readDocumentLinkSetManifestState(\n manifest.state,\n \"Seeded document\",\n );\n return {\n documentId: state.documentId,\n containerId,\n linkedContainerIds: [...state.linkedContainerIds],\n accessEpoch: state.epoch,\n accessStateHash: manifest.manifestHash,\n createdAt: new Date().toISOString(),\n };\n}\n\n/** One online create, without installing a local record or queuing a birth for replay. */\nexport async function createSeededDocument(\n runtime: DocumentsRuntime,\n input: SeededDocumentInput,\n stillCurrent: () => boolean,\n): Promise<DiscoveredDocumentInput | \"purged\"> {\n const author = resolveDocumentCreateAuthor(runtime);\n const keys = runtime.crypto.encapsulationKeyPair;\n if (!author || !keys || !runtime.state.online)\n throw new Error(\n \"An online signing identity is required to seed a document.\",\n );\n const purged = await hasVerifiedDocumentPurge(\n runtime.infra.execSql,\n input.documentId,\n author.organizationId,\n );\n if (!stillCurrent())\n throw new Error(\n \"The account or database scope changed during seeded creation.\",\n );\n if (purged) return \"purged\";\n const update = await createSeedUpdate(runtime, input);\n const remote = new RemoteDocumentService({\n api: runtime.apiClient,\n execSql: runtime.infra.execSql,\n encapsulationSecretKey: keys.secretKey,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n });\n let failure: { message: string; status: number | null } | undefined;\n const verification = {\n resolveProjectionUserKey: createDocumentProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer(),\n stillCurrent,\n };\n const created = await remote.createRemoteDocument({\n ...verification,\n onTerminalSubmitFailure: (result) => {\n failure = result;\n },\n author,\n containerId: input.containerId,\n documentId: input.documentId,\n expectedOrganizationId: author.organizationId,\n requireSeededCreate: true,\n onRecoveredStaleTarget: input.onRecoveredStaleTarget,\n seedUpdate: { ...update, id: crypto.randomUUID() },\n });\n if (!stillCurrent())\n throw new Error(\n \"The account or database scope changed during seeded creation.\",\n );\n if (\n !created &&\n failure?.status === 409 &&\n failure.message.endsWith(\"Document was permanently purged\")\n ) {\n // A refusal only prompts a read. The signed proof establishes the deletion.\n await createVerifiedRemoteDocumentDeletionHandler({\n ...verification,\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n expectedOrganizationId: author.organizationId,\n onVerifiedDeletion: ({ commitPurgeProof, documentId }) =>\n pinAbsentDocumentPurge(\n runtime.infra.execSql,\n documentId,\n commitPurgeProof,\n ),\n })({ documentId: input.documentId });\n if (!stillCurrent())\n throw new Error(\n \"The account or database scope changed during purge verification.\",\n );\n return \"purged\";\n }\n if (!created)\n throw new Error(\n failure?.message ??\n \"Could not commit the seeded document. Run seed again to resume.\",\n );\n return seededPlacement(\n input.containerId,\n created.writerProjection.documentManifest,\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"initialContent.js","sourceRoot":"","sources":["initialContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EACL,cAAc,EACd,mBAAmB,GACpB,MAAM,4CAA4C,CA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AG,EACH,qBAAqB,CAAC,KAAK,CAAC,CAC7B,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,KAAK,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../../data/documents/documentConstants\";\nimport { writeStoredDocumentFields } from \"../../../../data/documents/documentKinds\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n} from \"../../../../data/documents/documentRowList\";\nimport type { DocumentStructuredFieldPatch } from \"../../types\";\nimport { resolveRowAttribution } from \"../rows/rowAttribution\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\n\n// A fresh doc has nothing to delete, and a delete of an absent key would still\n// cost an op, so only the fields that set a value are written.\nfunction definedStructuredFields(\n patch: DocumentStructuredFieldPatch | undefined,\n): Record<string, string> | null {\n const fields: Record<string, string> = {};\n for (const [key, value] of Object.entries(patch ?? {})) {\n if (value !== undefined) fields[key] = value;\n }\n return Object.keys(fields).length > 0 ? fields : null;\n}\n\n/**\n * Rejects initial fields a store could never write, at open rather than in the\n * fire-and-forget initialization: like `setStructuredFields`, fields belong to\n * a structured (non-note) kind.\n */\nexport function assertInitialContentFitsKind(\n initialContent: DocumentStoreState[\"initialContent\"],\n initialDocumentKind: DocumentStoreState[\"initialDocumentKind\"],\n): void {\n if (\n initialDocumentKind === DEFAULT_DOCUMENT_KIND &&\n definedStructuredFields(initialContent?.initialStructuredFields)\n ) {\n throw new Error(\"Initial structured fields need a structured kind\");\n }\n}\n\n/**\n * Writes the fields and rows a created record starts with into its birth doc,\n * beside the initial kind and text, so they share the birth's single update\n * (and through it a seeded create, or the attach a deferred birth waits for).\n * Rows are stamped exactly as `addRow` stamps them. Returns whether anything\n * was written.\n */\nexport function writeInitialDocumentContent(\n state: DocumentStoreState,\n doc: DocumentState,\n): boolean {\n const fields = definedStructuredFields(\n state.initialContent?.initialStructuredFields,\n );\n if (fields) {\n writeStoredDocumentFields(\n doc,\n state.initialDocumentKind,\n fields,\n state.runtime.infra.documentProjectors,\n );\n }\n const rows = state.initialContent?.initialRows ?? [];\n for (const row of rows) {\n addDocumentRow(\n doc,\n createDocumentRowId(),\n row,\n resolveRowAttribution(state),\n );\n }\n return fields !== null || rows.length > 0;\n}\n"]}
1
+ {"version":3,"file":"initialContent.js","sourceRoot":"","sources":["initialContent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,EACL,cAAc,EACd,mBAAmB,GACpB,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAG/D,+EAA+E;AAC/E,+DAA+D;AAC/D,SAAS,uBAAuB,CAC9B,KAA+C;IAE/C,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC;QACvD,IAAI,KAAK,KAAK,SAAS;YAAE,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IAC/C,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;AACxD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,4BAA4B,CAC1C,cAAoD,EACpD,mBAA8D;IAE9D,IACE,mBAAmB,KAAK,qBAAqB;QAC7C,uBAAuB,CAAC,cAAc,EAAE,uBAAuB,CAAC,EAChE,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,kDAAkD,CAAC,CAAC;IACtE,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAGC,EACD,GAAkB;IAElB,MAAM,MAAM,GAAG,uBAAuB,CACpC,KAAK,CAAC,cAAc,EAAE,uBAAuB,CAC9C,CAAC;IACF,IAAI,MAAM,EAAE,CAAC;QACX,yBAAyB,CACvB,GAAG,EACH,KAAK,CAAC,mBAAmB,EACzB,MAAM,EACN,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,kBAAkB,CACvC,CAAC;IACJ,CAAC;IACD,MAAM,IAAI,GAAG,KAAK,CAAC,cAAc,EAAE,WAAW,IAAI,EAAE,CAAC;IACrD,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,cAAc,CACZ,GAAG,EACH,mBAAmB,EAAE,EACrB,GAAG,EACH,qBAAqB,CAAC,KAAK,CAAC,CAC7B,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,KAAK,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../../data/documents/documentConstants\";\nimport { writeStoredDocumentFields } from \"../../../../data/documents/documentKinds\";\nimport {\n addDocumentRow,\n createDocumentRowId,\n} from \"../../../../data/documents/documentRowList\";\nimport type { DocumentStructuredFieldPatch } from \"../../types\";\nimport { resolveRowAttribution } from \"../rows/rowAttribution\";\nimport type { DocumentState, DocumentStoreState } from \"../state\";\n\n// A fresh doc has nothing to delete, and a delete of an absent key would still\n// cost an op, so only the fields that set a value are written.\nfunction definedStructuredFields(\n patch: DocumentStructuredFieldPatch | undefined,\n): Record<string, string> | null {\n const fields: Record<string, string> = {};\n for (const [key, value] of Object.entries(patch ?? {})) {\n if (value !== undefined) fields[key] = value;\n }\n return Object.keys(fields).length > 0 ? fields : null;\n}\n\n/**\n * Rejects initial fields a store could never write, at open rather than in the\n * fire-and-forget initialization: like `setStructuredFields`, fields belong to\n * a structured (non-note) kind.\n */\nexport function assertInitialContentFitsKind(\n initialContent: DocumentStoreState[\"initialContent\"],\n initialDocumentKind: DocumentStoreState[\"initialDocumentKind\"],\n): void {\n if (\n initialDocumentKind === DEFAULT_DOCUMENT_KIND &&\n definedStructuredFields(initialContent?.initialStructuredFields)\n ) {\n throw new Error(\"Initial structured fields need a structured kind\");\n }\n}\n\n/**\n * Writes the fields and rows a created record starts with into its birth doc,\n * beside the initial kind and text, so they share the birth's single update\n * (and through it a seeded create, or the attach a deferred birth waits for).\n * Rows are stamped exactly as `addRow` stamps them. Returns whether anything\n * was written.\n */\nexport function writeInitialDocumentContent(\n state: Pick<\n DocumentStoreState,\n \"initialContent\" | \"initialDocumentKind\" | \"runtime\"\n >,\n doc: DocumentState,\n): boolean {\n const fields = definedStructuredFields(\n state.initialContent?.initialStructuredFields,\n );\n if (fields) {\n writeStoredDocumentFields(\n doc,\n state.initialDocumentKind,\n fields,\n state.runtime.infra.documentProjectors,\n );\n }\n const rows = state.initialContent?.initialRows ?? [];\n for (const row of rows) {\n addDocumentRow(\n doc,\n createDocumentRowId(),\n row,\n resolveRowAttribution(state),\n );\n }\n return fields !== null || rows.length > 0;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"rowAttribution.js","sourceRoot":"","sources":["rowAttribution.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAG9E,mEAAmE;AACnE,gFAAgF;AAChF,0BAA0B;AAC1B,MAAM,UAAU,qBAAqB,CACnC,KAAyB;IAEzB,OAAO;QACL,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAC5B,MAAM,EAAE,2BAA2B,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,YAAY,IAAI,EAAE;KACvE,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentRowAttribution } from \"../../../../data/documents/documentRowList\";\nimport { resolveDocumentCreateAuthor } from \"../../../../workflows/documents\";\nimport type { DocumentStoreState } from \"../state\";\n\n// Stamp each row write with the local signing identity (or \"\" when\n// unauthenticated) and an ISO timestamp, matching the keys the edit-attribution\n// layer resolves against.\nexport function resolveRowAttribution(\n state: DocumentStoreState,\n): DocumentRowAttribution {\n return {\n at: new Date().toISOString(),\n userId: resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? \"\",\n };\n}\n"]}
1
+ {"version":3,"file":"rowAttribution.js","sourceRoot":"","sources":["rowAttribution.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAG9E,mEAAmE;AACnE,gFAAgF;AAChF,0BAA0B;AAC1B,MAAM,UAAU,qBAAqB,CACnC,KAA0C;IAE1C,OAAO;QACL,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAC5B,MAAM,EAAE,2BAA2B,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,YAAY,IAAI,EAAE;KACvE,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentRowAttribution } from \"../../../../data/documents/documentRowList\";\nimport { resolveDocumentCreateAuthor } from \"../../../../workflows/documents\";\nimport type { DocumentStoreState } from \"../state\";\n\n// Stamp each row write with the local signing identity (or \"\" when\n// unauthenticated) and an ISO timestamp, matching the keys the edit-attribution\n// layer resolves against.\nexport function resolveRowAttribution(\n state: Pick<DocumentStoreState, \"runtime\">,\n): DocumentRowAttribution {\n return {\n at: new Date().toISOString(),\n userId: resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? \"\",\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { DEFAULT_DOCUMENT_KIND } from "../../../data/documents/documentConstants.js";
2
- import { getDocumentAttachments, sameDocumentAttachments, } from "../../../data/documents/documentContent.js";
2
+ import { getDocumentAttachments, readSeedTag, sameDocumentAttachments, } from "../../../data/documents/documentContent.js";
3
3
  import { projectStoredDocumentState, readStoredDocumentState, } from "../../../data/documents/documentKinds.js";
4
4
  import { listDocumentRows, sameDocumentRows, } from "../../../data/documents/documentRowList.js";
5
5
  import { canWriteEffectiveAccessLevel, normalizeEffectiveAccessLevel, } from "../../../data/keying/accessLevel.js";
@@ -82,6 +82,7 @@ export function setDocumentSnapshot(state, next) {
82
82
  state.snapshot.currentAuthorId === next.currentAuthorId &&
83
83
  state.snapshot.documentId === next.documentId &&
84
84
  state.snapshot.documentKind === next.documentKind &&
85
+ state.snapshot.seedTag === next.seedTag &&
85
86
  state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&
86
87
  sameValidationIssues(state.snapshot.fieldValidationIssues, next.fieldValidationIssues) &&
87
88
  state.snapshot.ready === next.ready &&
@@ -172,6 +173,7 @@ export function setReadySnapshot(state, currentDoc, syncing, textOverride, struc
172
173
  currentAuthorId: resolveCurrentAuthorId(state),
173
174
  documentId: state.record?.documentId ?? null,
174
175
  documentKind: projectedState.documentKind,
176
+ seedTag: readSeedTag(currentDoc),
175
177
  effectiveAccessLevel: normalizeEffectiveAccessLevel(state.record?.effectiveAccessLevel),
176
178
  fieldValidationIssues: projectedState.fieldValidationIssues,
177
179
  ready: true,
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAOtC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAkK9E,MAAM,uBAAuB,GAAqB;IAChD,WAAW,EAAE,EAAE;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7D,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,KAAyB;IACpE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QAC1B,OAAO;IACT,CAAC;IAED,mBAAmB,CAAC,KAAK,EAAE;QACzB,GAAG,KAAK,CAAC,QAAQ;QACjB,SAAS,EAAE,cAAc,CAAC,KAAK,CAAC;QAChC,QAAQ,EAAE,gBAAgB,CAAC,KAAK,CAAC;QACjC,yEAAyE;QACzE,eAAe,EAAE,sBAAsB,CAAC,KAAK,CAAC;QAC9C,oBAAoB,EAAE,6BAA6B,CACjD,KAAK,CAAC,MAAM,EAAE,oBAAoB,CACnC;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAyB,EACzB,QAAoB;IAEpB,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/sync/syncPagination\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/keying/accessLevel\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/principalPolicyService\";\nimport type {\n DocumentSnapshot,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachments/attachmentSnapshot\";\nimport { sameValidationIssues, shallowEqualRecord } from \"./snapshotEquality\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n /** The request's policy operation; finalizing hydration reuses it. */\n policyOperation: PrincipalPolicyOperation;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n /** Fields and rows a created record starts with; see `initialContent.ts`. */\n initialContent?: Pick<\n DocumentStoreOpenOptions,\n \"initialRows\" | \"initialStructuredFields\"\n >;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Newest queued coalescing write per key; see `localWriteQueue`. */\n localWriteTickets: { issued: number; latestByKey: Map<string, number> };\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n /** Local writes called or chained but unsettled; zero means all in SQLite. */\n queuedWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n startupProbeDeferredAttempt: number | null;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n /**\n * Whether local writes applied ops to `doc` that are not yet durable (e.g.\n * their save failed). Set when a write exports a non-empty delta; cleared once\n * a persist covers `doc` or `doc` is replaced from durable history.\n */\n unsavedLocalEdits: boolean;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteTickets: { issued: 0, latestByKey: new Map() },\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n queuedWrites: 0,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n startupProbeDeferredAttempt: null,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n unsavedLocalEdits: false,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.startupProbeDeferredAttempt = null;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.unsavedLocalEdits = false;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n // Publish runtime identity before a caller captures its write authority.\n currentAuthorId: resolveCurrentAuthorId(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAEL,sBAAsB,EACtB,WAAW,EACX,uBAAuB,GACxB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,0BAA0B,EAC1B,uBAAuB,GAExB,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAEL,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EAGL,uCAAuC,EAOvC,2BAA2B,GAC5B,MAAM,8BAA8B,CAAC;AAOtC,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAkK9E,MAAM,uBAAuB,GAAqB;IAChD,WAAW,EAAE,EAAE;IACf,wBAAwB,EAAE,EAAE;IAC5B,4BAA4B,EAAE,EAAE;IAChC,SAAS,EAAE,KAAK;IAChB,QAAQ,EAAE,IAAI;IACd,eAAe,EAAE,IAAI;IACrB,UAAU,EAAE,IAAI;IAChB,YAAY,EAAE,qBAAqB;IACnC,oBAAoB,EAAE,OAAO;IAC7B,qBAAqB,EAAE,EAAE;IACzB,KAAK,EAAE,KAAK;IACZ,IAAI,EAAE,EAAE;IACR,gBAAgB,EAAE,EAAE;IACpB,IAAI,EAAE,EAAE;IACR,KAAK,EAAE,EAAE;IACT,OAAO,EAAE,KAAK;CACf,CAAC;AAEF,MAAM,UAAU,wBAAwB,CACtC,OAAe,EACf,cAAgC,EAChC,WAAiC,EACjC,OAAwC,EACxC,iBAAgC,EAChC,WAAW,GAAG,EAAE,EAChB,sBAA0C,qBAAqB,EAC/D,yBAAyB,GAAG,IA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C;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAyB,EACzB,QAAoB;IAEpB,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,OAAO,GAAG,EAAE,CAAC,KAAK,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import type { createDocument } from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport {\n type DocumentAttachment,\n getDocumentAttachments,\n readSeedTag,\n sameDocumentAttachments,\n} from \"../../../data/documents/documentContent\";\nimport {\n projectStoredDocumentState,\n readStoredDocumentState,\n type StoredDocumentKind,\n} from \"../../../data/documents/documentKinds\";\nimport {\n type DocumentRow,\n listDocumentRows,\n sameDocumentRows,\n} from \"../../../data/documents/documentRowList\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type { DocumentSyncPullContinuation } from \"../../../data/documents/shared/sync/syncPagination\";\nimport {\n canWriteEffectiveAccessLevel,\n normalizeEffectiveAccessLevel,\n} from \"../../../data/keying/accessLevel\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n type AttachmentRemovalRows,\n type AttachmentStagingRows,\n createDocumentProjectionUserKeyResolver,\n type DocumentProjectionUserKeyResolver,\n type DocumentRecord,\n type DocumentSyncLane,\n type DocumentsPersistence,\n type PendingAttachmentRecord,\n type PendingUpdateInsert,\n resolveDocumentCreateAuthor,\n} from \"../../../workflows/documents\";\nimport type { PrincipalPolicyOperation } from \"../../../workflows/principals/principalPolicyService\";\nimport type {\n DocumentSnapshot,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n getAttachmentStatuses,\n getAttachmentStorageKeys,\n} from \"./attachments/attachmentSnapshot\";\nimport { sameValidationIssues, shallowEqualRecord } from \"./snapshotEquality\";\nexport type DocumentState = Awaited<ReturnType<typeof createDocument>>;\nexport type EncapsulationKeyPair = NonNullable<\n DocumentsRuntime[\"crypto\"][\"encapsulationKeyPair\"]\n>;\nexport type DocumentAttachmentBinding = NonNullable<\n Awaited<ReturnType<DocumentsRuntime[\"apiClient\"][\"listDocumentAttachments\"]>>\n>[number];\nexport type PendingMutationSyncResult = {\n completed: boolean;\n nextRecord: DocumentRecord;\n};\nexport interface PersistedDocumentRecord {\n creationSuperseded?: true;\n historyRestoreState?:\n | Awaited<ReturnType<DocumentsPersistence[\"loadHistoryRestoreState\"]>>\n | undefined;\n pullContinuationSuperseded?: true;\n record: DocumentRecord;\n syncIdentitySuperseded?: true;\n updatedAt?: string | undefined;\n}\nexport interface SaveDocumentRecordOptions {\n acceptedPendingUpdateIds?: readonly string[] | undefined;\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n expectedSyncState?:\n | {\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord;\n }\n | undefined;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: Omit<PendingUpdateInsert, \"localId\"> | undefined;\n pendingBaseVersionOverride?: string | null | undefined;\n preserveSnapshotStructuredFields?: boolean | undefined;\n preserveSnapshotText?: boolean | undefined;\n stillCurrent?: (() => boolean) | undefined;\n}\nexport interface DocumentSyncAttempt {\n consumedPullContinuation: DocumentSyncPullContinuation | null;\n outgoingUpdateCount: number;\n /** The request's policy operation; finalizing hydration reuses it. */\n policyOperation: PrincipalPolicyOperation;\n requestRecord: DocumentRecord;\n synced: SyncRemoteDocumentResult;\n /** `writerProjectionGeneration` when the request left; gates the install. */\n writerProjectionGeneration: number;\n}\nexport interface DocumentStorePersistenceEffects {\n emitPersistedDocument: (\n domainScope: DomainScope,\n persistedDocument: DocumentSummary,\n placementChanged?: boolean | undefined,\n ) => void;\n registerDocumentIdentity: (\n domainScope: DomainScope,\n localId: string,\n documentId: string | null,\n ) => void;\n}\nexport interface DocumentStoreState {\n attachmentBlobIdBySlotId: Record<string, string | null>;\n /** Plaintext digest of the held bytes per slot; see `getAttachmentStatuses`. */\n attachmentContentSha256BySlotId: Record<string, string>;\n attachmentStorageKeyBySlotId: Record<string, string>;\n /** Creation's birth rides the first attach; see `deferredInitialUpdate.ts`. */\n deferInitialUpdate?: boolean;\n doc: DocumentState | null;\n effects: DocumentStorePersistenceEffects;\n initialDocumentId: string | null;\n /** Fields and rows a created record starts with; see `initialContent.ts`. */\n initialContent?: Pick<\n DocumentStoreOpenOptions,\n \"initialRows\" | \"initialStructuredFields\"\n >;\n initialDocumentKind: StoredDocumentKind;\n initialText: string;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n lastEventCount: number;\n /** Newest queued coalescing write per key; see `localWriteQueue`. */\n localWriteTickets: { issued: number; latestByKey: Map<string, number> };\n /** Invalidates queued local-write closures when this store is cleared. */\n localWriteGeneration: number;\n locallyAcceptedUpdateIds: Set<string>;\n localId: string;\n listeners: Set<() => void>;\n pendingAttachments: PendingAttachmentRecord[];\n /**\n * Oplog version through which every op in `doc` is already durably enqueued as\n * a pending update or synced from a remote peer. It advances only after an\n * edit's enqueue+persist succeeds, so a later edit can recover any orphaned\n * delta left by a failed write instead of silently dropping it from sync.\n * `null` only before initialization sets it to the loaded doc's version.\n */\n pendingBaseVersion: string | null;\n /**\n * Local text/structured writes queued on `writeChain` but not yet drained.\n * While positive, sync MUST preserve the optimistic text/fields because `doc`\n * can lag the latest keystroke. Remote merges remain in `doc` and publish when\n * the final write settles.\n */\n pendingLocalWrites: number;\n /** Local writes called or chained but unsettled; zero means all in SQLite. */\n queuedWrites: number;\n persistence: DocumentsPersistence;\n /**\n * Durable continuation for a bounded remote pull, mirrored from the document\n * record so the live lane can advance it without re-reading SQLite.\n */\n pullContinuation: DocumentSyncPullContinuation | null;\n record: DocumentRecord | null;\n /** Served bindings hydration refused for a held copy; see `hydrate.ts`. */\n rejectedServedAttachmentBindings: Set<string>;\n /**\n * Consecutive completed sync passes that re-keyed conflicted pending updates\n * without settling anything. Bounds the rekey-driven self re-arm so a server\n * that keeps conflicting fresh ids cannot drive a network-speed loop; see\n * shouldReArmAfterOutgoingSettlement.\n */\n rekeyOnlyPassCount: number;\n resolveProjectionUserKey: DocumentProjectionUserKeyResolver;\n /** Latest remote-update sequence durably applied by a completed probe. */\n remoteUpdateCompletedSignalSeq: number;\n /** A cancelled remote-only owner blocks late responses until fresh work. */\n remoteSyncBlocked: boolean;\n scheduleStartupRemoteSync: boolean;\n startupProbeDeferredAttempt: number | null;\n remoteUpdatePending: boolean;\n /** Sequence used to keep an older pass from clearing a newer remote event. */\n remoteUpdateSignalSeq: number;\n /**\n * Whether local writes applied ops to `doc` that are not yet durable (e.g.\n * their save failed). Set when a write exports a non-empty delta; cleared once\n * a persist covers `doc` or `doc` is replaced from durable history.\n */\n unsavedLocalEdits: boolean;\n runtime: DocumentsRuntime;\n snapshot: DocumentSnapshot;\n syncLane: DocumentSyncLane | null;\n /** Parked behind another member's ancestor repair; a path hint re-runs. */\n awaitingAncestorRepair: boolean;\n writeChain: Promise<void>;\n writerProjection: DocumentWriterProjectionResponse | null;\n /**\n * Bumped whenever a realtime hint drops `writerProjection`; an operation that\n * fetched or was handed a projection installs it only if this is unchanged\n * since it started, so a pre-hint answer never lands after the hint.\n */\n writerProjectionGeneration: number;\n}\nconst EMPTY_DOCUMENT_SNAPSHOT: DocumentSnapshot = {\n attachments: [],\n attachmentStatusBySlotId: {},\n attachmentStorageKeyBySlotId: {},\n canAttach: false,\n canWrite: true,\n currentAuthorId: null,\n documentId: null,\n documentKind: DEFAULT_DOCUMENT_KIND,\n effectiveAccessLevel: \"admin\",\n fieldValidationIssues: [],\n ready: false,\n rows: [],\n structuredFields: {},\n text: \"\",\n title: \"\",\n syncing: false,\n};\n\nexport function createDocumentStoreState(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n effects: DocumentStorePersistenceEffects,\n initialDocumentId: string | null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n scheduleStartupRemoteSync = true,\n): DocumentStoreState {\n return {\n attachmentBlobIdBySlotId: {},\n attachmentContentSha256BySlotId: {},\n attachmentStorageKeyBySlotId: {},\n doc: null,\n effects,\n initialDocumentId,\n initialDocumentKind,\n initialText,\n initializePromise: null,\n initialized: false,\n lastEventCount: 0,\n localWriteTickets: { issued: 0, latestByKey: new Map() },\n localWriteGeneration: 0,\n locallyAcceptedUpdateIds: new Set(),\n localId,\n listeners: new Set(),\n pendingAttachments: [],\n pendingBaseVersion: null,\n pendingLocalWrites: 0,\n persistence,\n queuedWrites: 0,\n pullContinuation: null,\n record: null,\n rejectedServedAttachmentBindings: new Set(),\n rekeyOnlyPassCount: 0,\n resolveProjectionUserKey:\n createDocumentProjectionUserKeyResolver(initialRuntime),\n remoteUpdateCompletedSignalSeq: 0,\n remoteSyncBlocked: !scheduleStartupRemoteSync,\n scheduleStartupRemoteSync,\n startupProbeDeferredAttempt: null,\n awaitingAncestorRepair: false,\n remoteUpdatePending: false,\n remoteUpdateSignalSeq: 0,\n unsavedLocalEdits: false,\n runtime: initialRuntime,\n snapshot: { ...EMPTY_DOCUMENT_SNAPSHOT },\n syncLane: null,\n writeChain: Promise.resolve(),\n writerProjection: null,\n writerProjectionGeneration: 0,\n };\n}\n\nfunction emitDocumentStore(state: DocumentStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nexport function setDocumentSnapshot(\n state: DocumentStoreState,\n next: DocumentSnapshot,\n) {\n if (\n sameDocumentAttachments(state.snapshot.attachments, next.attachments) &&\n shallowEqualRecord(\n state.snapshot.attachmentStatusBySlotId,\n next.attachmentStatusBySlotId,\n ) &&\n shallowEqualRecord(\n state.snapshot.attachmentStorageKeyBySlotId,\n next.attachmentStorageKeyBySlotId,\n ) &&\n state.snapshot.canAttach === next.canAttach &&\n state.snapshot.canWrite === next.canWrite &&\n state.snapshot.currentAuthorId === next.currentAuthorId &&\n state.snapshot.documentId === next.documentId &&\n state.snapshot.documentKind === next.documentKind &&\n state.snapshot.seedTag === next.seedTag &&\n state.snapshot.effectiveAccessLevel === next.effectiveAccessLevel &&\n sameValidationIssues(\n state.snapshot.fieldValidationIssues,\n next.fieldValidationIssues,\n ) &&\n state.snapshot.ready === next.ready &&\n sameDocumentRows(state.snapshot.rows, next.rows) &&\n shallowEqualRecord(\n state.snapshot.structuredFields,\n next.structuredFields,\n ) &&\n state.snapshot.text === next.text &&\n state.snapshot.title === next.title &&\n state.snapshot.syncing === next.syncing\n ) {\n return;\n }\n\n state.snapshot = next;\n emitDocumentStore(state);\n}\n\nfunction clearDocumentStoreState(\n state: DocumentStoreState,\n { initialized }: { initialized: boolean },\n) {\n state.deferInitialUpdate = false;\n state.doc = null;\n state.localWriteGeneration += 1;\n state.record = null;\n state.pendingAttachments = [];\n state.pendingBaseVersion = null;\n state.pendingLocalWrites = 0;\n state.pullContinuation = null;\n state.attachmentBlobIdBySlotId = {};\n state.attachmentContentSha256BySlotId = {};\n state.attachmentStorageKeyBySlotId = {};\n state.locallyAcceptedUpdateIds = new Set();\n state.rejectedServedAttachmentBindings = new Set();\n state.remoteUpdateCompletedSignalSeq = 0;\n state.remoteSyncBlocked = !state.scheduleStartupRemoteSync;\n state.startupProbeDeferredAttempt = null;\n state.awaitingAncestorRepair = false;\n state.remoteUpdatePending = false;\n state.remoteUpdateSignalSeq = 0;\n state.unsavedLocalEdits = false;\n state.writerProjection = null;\n state.initialized = initialized;\n state.initializePromise = null;\n state.writeChain = Promise.resolve();\n setDocumentSnapshot(state, { ...EMPTY_DOCUMENT_SNAPSHOT });\n}\n\nexport function resetDocumentStore(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: false });\n}\n\nexport function markDocumentStoreRemoved(state: DocumentStoreState) {\n clearDocumentStoreState(state, { initialized: true });\n}\n\nexport function canAttachFiles(state: DocumentStoreState): boolean {\n return (\n canWriteDocument(state) &&\n state.runtime.infra.dbStatus === \"ready\" &&\n !!state.runtime.crypto.encapsulationKeyPair\n );\n}\n\nexport function canWriteDocument(state: DocumentStoreState): boolean {\n return canWriteEffectiveAccessLevel(state.record?.effectiveAccessLevel);\n}\n\nfunction getSnapshotAttachments(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentAttachment[] {\n return currentDoc ? getDocumentAttachments(currentDoc) : [];\n}\n\nfunction getSnapshotRows(\n state: DocumentStoreState,\n currentDoc: DocumentState | null = state.doc,\n): DocumentRow[] {\n return currentDoc ? listDocumentRows(currentDoc) : [];\n}\n\nfunction resolveCurrentAuthorId(state: DocumentStoreState): string | null {\n return resolveDocumentCreateAuthor(state.runtime)?.signerUserId ?? null;\n}\n\nexport function setReadySnapshot(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n syncing: boolean,\n textOverride?: string,\n structuredFieldsOverride?: DocumentSnapshot[\"structuredFields\"],\n) {\n const attachments = getSnapshotAttachments(state, currentDoc);\n const rows = getSnapshotRows(state, currentDoc);\n const documentState = readStoredDocumentState(\n currentDoc,\n state.runtime.infra.documentProjectors,\n );\n const text = textOverride ?? documentState.text;\n const structuredFields =\n structuredFieldsOverride ?? documentState.structuredFields;\n const projectedState =\n textOverride === undefined && structuredFieldsOverride === undefined\n ? documentState\n : projectStoredDocumentState(\n {\n documentKind: documentState.documentKind,\n structuredFields,\n text,\n rows: rows.map((row) => ({ id: row.id, fields: row.fields })),\n },\n state.runtime.infra.documentProjectors,\n );\n\n setDocumentSnapshot(state, {\n attachments,\n attachmentStatusBySlotId: getAttachmentStatuses({\n attachments,\n contentSha256BySlotId: state.attachmentContentSha256BySlotId,\n pendingSlotIds: new Set(\n state.pendingAttachments.map((attachment) => attachment.slotId),\n ),\n }),\n attachmentStorageKeyBySlotId: getAttachmentStorageKeys(\n state.attachmentStorageKeyBySlotId,\n attachments,\n ),\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n currentAuthorId: resolveCurrentAuthorId(state),\n documentId: state.record?.documentId ?? null,\n documentKind: projectedState.documentKind,\n seedTag: readSeedTag(currentDoc),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n fieldValidationIssues: projectedState.fieldValidationIssues,\n ready: true,\n rows,\n structuredFields: projectedState.structuredFields,\n text,\n title: projectedState.title,\n syncing,\n });\n}\n\nexport function setDocumentSyncing(\n state: DocumentStoreState,\n syncing: boolean,\n) {\n setDocumentSnapshot(state, { ...state.snapshot, syncing });\n}\n\nexport function refreshAttachabilitySnapshot(state: DocumentStoreState) {\n if (!state.snapshot.ready) {\n return;\n }\n\n setDocumentSnapshot(state, {\n ...state.snapshot,\n canAttach: canAttachFiles(state),\n canWrite: canWriteDocument(state),\n // Publish runtime identity before a caller captures its write authority.\n currentAuthorId: resolveCurrentAuthorId(state),\n effectiveAccessLevel: normalizeEffectiveAccessLevel(\n state.record?.effectiveAccessLevel,\n ),\n });\n}\n\nexport function subscribeToDocumentStore(\n state: DocumentStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => void state.listeners.delete(listener);\n}\n"]}