@tearleads/client-sdk 0.1.255 → 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 (109) 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/container-contents/hydration/remoteHydrationRequest.js +6 -5
  51. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  52. package/stores/container-contents/hydration/trackContainerHydration.js +35 -0
  53. package/stores/container-contents/hydration/trackContainerHydration.js.map +1 -0
  54. package/stores/container-contents/state.js +7 -2
  55. package/stores/container-contents/state.js.map +1 -1
  56. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +1 -0
  57. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  58. package/stores/container-contents/types.d.ts +2 -0
  59. package/stores/container-contents/types.js.map +1 -1
  60. package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
  61. package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
  62. package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
  63. package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
  64. package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
  65. package/stores/documents/documentStore/state.js +3 -1
  66. package/stores/documents/documentStore/state.js.map +1 -1
  67. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  68. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  69. package/stores/documents/index.d.ts +1 -0
  70. package/stores/documents/index.js +1 -0
  71. package/stores/documents/index.js.map +1 -1
  72. package/stores/documents/types.d.ts +1 -0
  73. package/stores/documents/types.js.map +1 -1
  74. package/workflows/blobs/upload/index.d.ts +1 -1
  75. package/workflows/blobs/upload/index.js +36 -18
  76. package/workflows/blobs/upload/index.js.map +1 -1
  77. package/workflows/blobs/upload/multipartStageResolution.js +12 -2
  78. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
  79. package/workflows/blobs/upload/multipartUpload.js +10 -2
  80. package/workflows/blobs/upload/multipartUpload.js.map +1 -1
  81. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
  82. package/workflows/container-contents/documentQueries/index.d.ts +1 -1
  83. package/workflows/container-contents/documentQueries/index.js +2 -2
  84. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  85. package/workflows/container-contents/index.d.ts +1 -0
  86. package/workflows/container-contents/index.js +1 -0
  87. package/workflows/container-contents/index.js.map +1 -1
  88. package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
  89. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
  90. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  91. package/workflows/documents/create/createAdoption.js +2 -50
  92. package/workflows/documents/create/createAdoption.js.map +1 -1
  93. package/workflows/documents/create/createResponse.js +12 -1
  94. package/workflows/documents/create/createResponse.js.map +1 -1
  95. package/workflows/documents/create/createSubmission.js +14 -0
  96. package/workflows/documents/create/createSubmission.js.map +1 -0
  97. package/workflows/documents/create/index.d.ts +3 -14
  98. package/workflows/documents/create/index.js +76 -67
  99. package/workflows/documents/create/index.js.map +1 -1
  100. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
  101. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
  102. package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
  103. package/workflows/documents/purge/absentDocumentPurge.js +23 -0
  104. package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
  105. package/workflows/documents/purge/index.d.ts +1 -0
  106. package/workflows/documents/purge/index.js +1 -0
  107. package/workflows/documents/purge/index.js.map +1 -1
  108. package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
  109. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"readers.js","sourceRoot":"","sources":["readers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,+BAA+B,EAE/B,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAMrF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,sCAAsC,EACtC,kBAAkB,GACnB,MAAM,yBAAyB,CAAC;AAEjC,SAAS,mBAAmB,CAC1B,KAAc;IAEd,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAc,EAAE,KAAa;IAC3D,MAAM,MAAM,GAAG,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACjD,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACzD,IAAI,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,wBAAwB,CAAC,CAAC;IACpD,CAAC;IACD,IAAI,iBAAiB,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB,CAAC,C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AAc;IACpC,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,MAAM,UAAU,gCAAgC,CAAC,KAKhD;IAMC,OAAO;QACL,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,gBAAgB,EAAE,cAAc,CAAC,KAAK,CAAC,gBAAgB,CAAC;QACxD,kBAAkB,EAAE,cAAc,CAAC,KAAK,CAAC,kBAAkB,CAAC;QAC5D,sBAAsB,EAAE,cAAc,CAAC,KAAK,CAAC,sBAAsB,CAAC;KACrE,CAAC;AACJ,CAAC","sourcesContent":["export {\n readRecordNullableString,\n readRecordPositiveInteger,\n readRecordString,\n} from \"../../shared/recordReaders\";\n\nimport {\n CONTENT_RECORD_ENCRYPTION_SUITE,\n type ContainerKeyWrap,\n compareCanonicalStrings,\n type DocumentContentKeyTarget,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentContentKeyBundleResponse,\n DocumentKekTargetsResponse,\n} from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport {\n readRecordInteger,\n readRecordPositiveInteger,\n readRecordString,\n readRecordValue,\n readStringArray,\n} from \"../../shared/recordReaders\";\n\nexport {\n assertDocumentManifestBundleConsistent,\n serializeCanonical,\n} from \"./manifestBundleReaders\";\n\nfunction isContentObjectKind(\n value: unknown,\n): value is WriteHeader[\"objectKind\"] {\n return value === \"blob\" || value === \"document\";\n}\n\nexport function readWriteHeader(value: unknown, label: string): WriteHeader {\n const record = readCanonicalRecord(value, label);\n const objectKind = readRecordValue(record, \"objectKind\");\n if (!isContentObjectKind(objectKind)) {\n throw new Error(`${label}.objectKind is invalid`);\n }\n if (readRecordInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n const encryptionSuite = readRecordValue(record, \"encryptionSuite\");\n if (encryptionSuite !== CONTENT_RECORD_ENCRYPTION_SUITE) {\n throw new Error(`${label}.encryptionSuite is invalid`);\n }\n\n return {\n version: 1,\n dependencyManifestHashes: readStringArray(\n readRecordValue(record, \"dependencyManifestHashes\"),\n `${label}.dependencyManifestHashes`,\n ),\n organizationId: readRecordString(record, \"organizationId\", label),\n objectKind,\n objectId: readRecordString(record, \"objectId\", label),\n accessManifestHash: readRecordString(record, \"accessManifestHash\", label),\n contentKeyEpoch: readRecordPositiveInteger(\n record,\n \"contentKeyEpoch\",\n label,\n ),\n targetHash: readRecordString(record, \"targetHash\", label),\n encryptionSuite,\n contentRecordId: readRecordString(record, \"contentRecordId\", label),\n nonceDomainHash: readRecordString(record, \"nonceDomainHash\", label),\n metadataHash: readRecordString(record, \"metadataHash\", label),\n ciphertextHash: readRecordString(record, \"ciphertextHash\", label),\n writerUserId: readRecordString(record, \"writerUserId\", label),\n writerDeviceId: readRecordString(record, \"writerDeviceId\", label),\n writerKeyFingerprint: readRecordString(\n record,\n \"writerKeyFingerprint\",\n label,\n ),\n signedAt: readRecordString(record, \"signedAt\", label),\n signature: readRecordString(record, \"signature\", label),\n };\n}\n\nexport function readManifestContainerId(\n bundle: ContainerWriterProjectionResponse[\"path\"][number],\n): string | null {\n const containerId = isPlainRecord(bundle.state)\n ? Reflect.get(bundle.state, \"containerId\")\n : undefined;\n\n return typeof containerId === \"string\" && containerId.length > 0\n ? containerId\n : null;\n}\n\nexport function targetKey(target: DocumentContentKeyTarget): string {\n return [\n target.containerId,\n target.containerManifestHash,\n target.containerKeyEpochId,\n String(target.containerKeyEpoch),\n ].join(\":\");\n}\n\nexport function sortTargets<T>(\n targets: readonly T[],\n keyOf: (target: T) => string,\n): T[] {\n return [...targets].sort((left, right) =>\n compareCanonicalStrings(keyOf(left), keyOf(right)),\n );\n}\n\nexport function sortDocumentTargets<T extends DocumentContentKeyTarget>(\n targets: readonly T[],\n): T[] {\n return sortTargets(targets, targetKey);\n}\n\nexport function describeDocumentTargetKek(\n target: DocumentContentKeyTarget,\n): string {\n return `container ${target.containerId} epoch ${target.containerKeyEpochId}`;\n}\n\nexport function uniqueSortedStrings(values: readonly string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nexport function asWebCryptoBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n const buffer = bytes.buffer;\n if (!(buffer instanceof ArrayBuffer)) {\n throw new Error(\"Document byte material must be ArrayBuffer-backed\");\n }\n return new Uint8Array(buffer, bytes.byteOffset, bytes.byteLength);\n}\n\nexport function assertOnlyRecordKeys(\n record: Record<string, unknown>,\n allowedKeys: ReadonlySet<string>,\n label: string,\n): void {\n const unexpectedKeys = Object.keys(record).filter(\n (key) => !allowedKeys.has(key),\n );\n if (unexpectedKeys.length === 0) return;\n const named = unexpectedKeys\n .slice(0, 3)\n .map((key) => JSON.stringify(key.slice(0, 32)))\n .join(\",\");\n const remaining = unexpectedKeys.length - 3;\n throw new Error(\n `${label} has unexpected keys: ${named}${remaining > 0 ? ` and ${remaining} more` : \"\"}`,\n );\n}\n\nexport function normalizeContainerKeyWrap(value: unknown): ContainerKeyWrap {\n if (!isPlainRecord(value)) {\n throw new Error(\"Container writer projection KEK wrap is invalid\");\n }\n\n const recipientKind = readRecordString(\n value,\n \"recipientKind\",\n \"container KEK wrap\",\n );\n if (\n recipientKind !== \"user\" &&\n recipientKind !== \"group\" &&\n recipientKind !== \"container\"\n ) {\n throw new Error(\n \"Container writer projection KEK wrap recipient is invalid\",\n );\n }\n\n return {\n containerKeyEpochId: readRecordString(\n value,\n \"containerKeyEpochId\",\n \"container KEK wrap\",\n ),\n recipientKind,\n recipientId: readRecordString(value, \"recipientId\", \"container KEK wrap\"),\n recipientKeyEpochId: readRecordString(\n value,\n \"recipientKeyEpochId\",\n \"container KEK wrap\",\n ),\n recipientKeyFingerprint: readRecordString(\n value,\n \"recipientKeyFingerprint\",\n \"container KEK wrap\",\n ),\n kemCipherText: readRecordString(\n value,\n \"kemCipherText\",\n \"container KEK wrap\",\n ),\n wrappedKey: readRecordString(value, \"wrappedKey\", \"container KEK wrap\"),\n wrapManifestHash: readRecordString(\n value,\n \"wrapManifestHash\",\n \"container KEK wrap\",\n ),\n };\n}\n\nexport function assertEqualBytes(\n left: Uint8Array,\n right: Uint8Array,\n message: string,\n): void {\n let mismatch = left.byteLength ^ right.byteLength;\n const length = Math.max(left.byteLength, right.byteLength);\n for (let index = 0; index < length; index += 1) {\n mismatch |= (left[index] ?? 0) ^ (right[index] ?? 0);\n }\n\n if (mismatch !== 0) {\n throw new Error(message);\n }\n}\n\nfunction readDocumentTarget(\n value: Record<string, unknown>,\n label: string,\n): DocumentContentKeyTarget {\n return {\n containerId: readRecordString(value, \"containerId\", label),\n containerManifestHash: readRecordString(\n value,\n \"containerManifestHash\",\n label,\n ),\n containerKeyEpochId: readRecordString(value, \"containerKeyEpochId\", label),\n containerKeyEpoch: readRecordPositiveInteger(\n value,\n \"containerKeyEpoch\",\n label,\n ),\n };\n}\n\nexport function normalizeDocumentKekTargetResponse(\n targets: DocumentKekTargetsResponse,\n): DocumentContentKeyTarget[] {\n return sortDocumentTargets(\n targets.targets.map((target, index) => {\n if (!isPlainRecord(target)) {\n throw new Error(`Document KEK target[${index}] is invalid`);\n }\n return readDocumentTarget(target, `Document KEK target[${index}]`);\n }),\n );\n}\n\nexport function targetEnvelopeReference(\n envelope: DocumentContentKeyBundleResponse[\"targets\"][number],\n): DocumentContentKeyTarget {\n return {\n containerId: envelope.containerId,\n containerManifestHash: envelope.containerManifestHash,\n containerKeyEpochId: envelope.containerKeyEpochId,\n containerKeyEpoch: envelope.containerKeyEpoch,\n };\n}\n\nfunction serializeState(value: unknown): string {\n return JSON.stringify(value);\n}\n\nexport function serializedPersistedDocumentState(input: {\n contentKeyBundle: unknown;\n documentId: string;\n documentKekTargets: unknown;\n documentManifestBundle: unknown;\n}): {\n contentKeyBundle: string;\n documentId: string;\n documentKekTargets: string;\n documentManifestBundle: string;\n} {\n return {\n documentId: input.documentId,\n contentKeyBundle: serializeState(input.contentKeyBundle),\n documentKekTargets: serializeState(input.documentKekTargets),\n documentManifestBundle: serializeState(input.documentManifestBundle),\n };\n}\n"]}
1
+ {"version":3,"file":"readers.js","sourceRoot":"","sources":["readers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,+BAA+B,EAE/B,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAMrF,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,gBAAgB,EAChB,eAAe,EACf,eAAe,GAChB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,sCAAsC,EACtC,gCAAgC,EAChC,kBAAkB,GACnB,MAAM,yBAAyB,CAAC;AAEjC,SAAS,mBAAmB,CAC1B,KAAc;IAEd,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC;AAClD,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAc,EAAE,KAAa;IAC3D,MAAM,MAAM,GAAG,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACjD,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACzD,IAAI,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,wBAAwB,CAAC,CAAC;IACpD,CAAC;IACD,IAAI,iBAAiB,CAAC,MAAM,EAAE,SAAS,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB,CAAC,CAAC;IAChD,CAAC;IACD,MAAM,eAAe,GAAG,eAAe,CAAC,MAAM,EAAE,iBA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AAC;AAED,MAAM,UAAU,gCAAgC,CAAC,KAKhD;IAMC,OAAO;QACL,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,gBAAgB,EAAE,cAAc,CAAC,KAAK,CAAC,gBAAgB,CAAC;QACxD,kBAAkB,EAAE,cAAc,CAAC,KAAK,CAAC,kBAAkB,CAAC;QAC5D,sBAAsB,EAAE,cAAc,CAAC,KAAK,CAAC,sBAAsB,CAAC;KACrE,CAAC;AACJ,CAAC","sourcesContent":["export {\n readRecordNullableString,\n readRecordPositiveInteger,\n readRecordString,\n} from \"../../shared/recordReaders\";\n\nimport {\n CONTENT_RECORD_ENCRYPTION_SUITE,\n type ContainerKeyWrap,\n compareCanonicalStrings,\n type DocumentContentKeyTarget,\n type WriteHeader,\n} from \"@tearleads/crypto\";\nimport { isPlainObject as isPlainRecord } from \"@tearleads/validators/isPlainObject\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentContentKeyBundleResponse,\n DocumentKekTargetsResponse,\n} from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport {\n readRecordInteger,\n readRecordPositiveInteger,\n readRecordString,\n readRecordValue,\n readStringArray,\n} from \"../../shared/recordReaders\";\n\nexport {\n assertDocumentManifestBundleConsistent,\n readDocumentLinkSetManifestState,\n serializeCanonical,\n} from \"./manifestBundleReaders\";\n\nfunction isContentObjectKind(\n value: unknown,\n): value is WriteHeader[\"objectKind\"] {\n return value === \"blob\" || value === \"document\";\n}\n\nexport function readWriteHeader(value: unknown, label: string): WriteHeader {\n const record = readCanonicalRecord(value, label);\n const objectKind = readRecordValue(record, \"objectKind\");\n if (!isContentObjectKind(objectKind)) {\n throw new Error(`${label}.objectKind is invalid`);\n }\n if (readRecordInteger(record, \"version\", label) !== 1) {\n throw new Error(`${label}.version must be 1`);\n }\n const encryptionSuite = readRecordValue(record, \"encryptionSuite\");\n if (encryptionSuite !== CONTENT_RECORD_ENCRYPTION_SUITE) {\n throw new Error(`${label}.encryptionSuite is invalid`);\n }\n\n return {\n version: 1,\n dependencyManifestHashes: readStringArray(\n readRecordValue(record, \"dependencyManifestHashes\"),\n `${label}.dependencyManifestHashes`,\n ),\n organizationId: readRecordString(record, \"organizationId\", label),\n objectKind,\n objectId: readRecordString(record, \"objectId\", label),\n accessManifestHash: readRecordString(record, \"accessManifestHash\", label),\n contentKeyEpoch: readRecordPositiveInteger(\n record,\n \"contentKeyEpoch\",\n label,\n ),\n targetHash: readRecordString(record, \"targetHash\", label),\n encryptionSuite,\n contentRecordId: readRecordString(record, \"contentRecordId\", label),\n nonceDomainHash: readRecordString(record, \"nonceDomainHash\", label),\n metadataHash: readRecordString(record, \"metadataHash\", label),\n ciphertextHash: readRecordString(record, \"ciphertextHash\", label),\n writerUserId: readRecordString(record, \"writerUserId\", label),\n writerDeviceId: readRecordString(record, \"writerDeviceId\", label),\n writerKeyFingerprint: readRecordString(\n record,\n \"writerKeyFingerprint\",\n label,\n ),\n signedAt: readRecordString(record, \"signedAt\", label),\n signature: readRecordString(record, \"signature\", label),\n };\n}\n\nexport function readManifestContainerId(\n bundle: ContainerWriterProjectionResponse[\"path\"][number],\n): string | null {\n const containerId = isPlainRecord(bundle.state)\n ? Reflect.get(bundle.state, \"containerId\")\n : undefined;\n\n return typeof containerId === \"string\" && containerId.length > 0\n ? containerId\n : null;\n}\n\nexport function targetKey(target: DocumentContentKeyTarget): string {\n return [\n target.containerId,\n target.containerManifestHash,\n target.containerKeyEpochId,\n String(target.containerKeyEpoch),\n ].join(\":\");\n}\n\nexport function sortTargets<T>(\n targets: readonly T[],\n keyOf: (target: T) => string,\n): T[] {\n return [...targets].sort((left, right) =>\n compareCanonicalStrings(keyOf(left), keyOf(right)),\n );\n}\n\nexport function sortDocumentTargets<T extends DocumentContentKeyTarget>(\n targets: readonly T[],\n): T[] {\n return sortTargets(targets, targetKey);\n}\n\nexport function describeDocumentTargetKek(\n target: DocumentContentKeyTarget,\n): string {\n return `container ${target.containerId} epoch ${target.containerKeyEpochId}`;\n}\n\nexport function uniqueSortedStrings(values: readonly string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nexport function asWebCryptoBytes(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n const buffer = bytes.buffer;\n if (!(buffer instanceof ArrayBuffer)) {\n throw new Error(\"Document byte material must be ArrayBuffer-backed\");\n }\n return new Uint8Array(buffer, bytes.byteOffset, bytes.byteLength);\n}\n\nexport function assertOnlyRecordKeys(\n record: Record<string, unknown>,\n allowedKeys: ReadonlySet<string>,\n label: string,\n): void {\n const unexpectedKeys = Object.keys(record).filter(\n (key) => !allowedKeys.has(key),\n );\n if (unexpectedKeys.length === 0) return;\n const named = unexpectedKeys\n .slice(0, 3)\n .map((key) => JSON.stringify(key.slice(0, 32)))\n .join(\",\");\n const remaining = unexpectedKeys.length - 3;\n throw new Error(\n `${label} has unexpected keys: ${named}${remaining > 0 ? ` and ${remaining} more` : \"\"}`,\n );\n}\n\nexport function normalizeContainerKeyWrap(value: unknown): ContainerKeyWrap {\n if (!isPlainRecord(value)) {\n throw new Error(\"Container writer projection KEK wrap is invalid\");\n }\n\n const recipientKind = readRecordString(\n value,\n \"recipientKind\",\n \"container KEK wrap\",\n );\n if (\n recipientKind !== \"user\" &&\n recipientKind !== \"group\" &&\n recipientKind !== \"container\"\n ) {\n throw new Error(\n \"Container writer projection KEK wrap recipient is invalid\",\n );\n }\n\n return {\n containerKeyEpochId: readRecordString(\n value,\n \"containerKeyEpochId\",\n \"container KEK wrap\",\n ),\n recipientKind,\n recipientId: readRecordString(value, \"recipientId\", \"container KEK wrap\"),\n recipientKeyEpochId: readRecordString(\n value,\n \"recipientKeyEpochId\",\n \"container KEK wrap\",\n ),\n recipientKeyFingerprint: readRecordString(\n value,\n \"recipientKeyFingerprint\",\n \"container KEK wrap\",\n ),\n kemCipherText: readRecordString(\n value,\n \"kemCipherText\",\n \"container KEK wrap\",\n ),\n wrappedKey: readRecordString(value, \"wrappedKey\", \"container KEK wrap\"),\n wrapManifestHash: readRecordString(\n value,\n \"wrapManifestHash\",\n \"container KEK wrap\",\n ),\n };\n}\n\nexport function assertEqualBytes(\n left: Uint8Array,\n right: Uint8Array,\n message: string,\n): void {\n let mismatch = left.byteLength ^ right.byteLength;\n const length = Math.max(left.byteLength, right.byteLength);\n for (let index = 0; index < length; index += 1) {\n mismatch |= (left[index] ?? 0) ^ (right[index] ?? 0);\n }\n\n if (mismatch !== 0) {\n throw new Error(message);\n }\n}\n\nfunction readDocumentTarget(\n value: Record<string, unknown>,\n label: string,\n): DocumentContentKeyTarget {\n return {\n containerId: readRecordString(value, \"containerId\", label),\n containerManifestHash: readRecordString(\n value,\n \"containerManifestHash\",\n label,\n ),\n containerKeyEpochId: readRecordString(value, \"containerKeyEpochId\", label),\n containerKeyEpoch: readRecordPositiveInteger(\n value,\n \"containerKeyEpoch\",\n label,\n ),\n };\n}\n\nexport function normalizeDocumentKekTargetResponse(\n targets: DocumentKekTargetsResponse,\n): DocumentContentKeyTarget[] {\n return sortDocumentTargets(\n targets.targets.map((target, index) => {\n if (!isPlainRecord(target)) {\n throw new Error(`Document KEK target[${index}] is invalid`);\n }\n return readDocumentTarget(target, `Document KEK target[${index}]`);\n }),\n );\n}\n\nexport function targetEnvelopeReference(\n envelope: DocumentContentKeyBundleResponse[\"targets\"][number],\n): DocumentContentKeyTarget {\n return {\n containerId: envelope.containerId,\n containerManifestHash: envelope.containerManifestHash,\n containerKeyEpochId: envelope.containerKeyEpochId,\n containerKeyEpoch: envelope.containerKeyEpoch,\n };\n}\n\nfunction serializeState(value: unknown): string {\n return JSON.stringify(value);\n}\n\nexport function serializedPersistedDocumentState(input: {\n contentKeyBundle: unknown;\n documentId: string;\n documentKekTargets: unknown;\n documentManifestBundle: unknown;\n}): {\n contentKeyBundle: string;\n documentId: string;\n documentKekTargets: string;\n documentManifestBundle: string;\n} {\n return {\n documentId: input.documentId,\n contentKeyBundle: serializeState(input.contentKeyBundle),\n documentKekTargets: serializeState(input.documentKekTargets),\n documentManifestBundle: serializeState(input.documentManifestBundle),\n };\n}\n"]}
@@ -158,6 +158,7 @@ export interface RelinkRemoteDocumentResult {
158
158
  response: DocumentLinkSetMutationResponse;
159
159
  }
160
160
  export interface DocumentSyncRequestResultOptions {
161
+ readonly stillCurrent?: (() => boolean) | undefined;
161
162
  readonly expectedPaymentRequiredOrganizationId?: string | undefined;
162
163
  readonly reportErrors?: boolean | undefined;
163
164
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA2BA,MAAM,CAAC,MAAM,qCAAqC,GAChD,gCAAgC,CAAC;AACnC,MAAM,CAAC,MAAM,uCAAuC,GAClD,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,sDAAsD,GACjE,2DAA2D,CAAC;AAC9D,MAAM,CAAC,MAAM,kCAAkC,GAC7C,uCAAuC,CAAC;AAC1C,MAAM,CAAC,MAAM,iCAAiC,GAC5C,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,6CAA6C,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,GAAG,CAAC;IACpD,YAAY;IACZ,iBAAiB;IACjB,iBAAiB;IACjB,iBAAiB;IACjB,QAAQ;IACR,IAAI;IACJ,cAAc;IACd,iBAAiB;IACjB,SAAS;CACV,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport type {\n AccessEvent,\n AccessManifest,\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n DocumentLinkSetManifestState,\n DocumentUnlinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerManifestRef,\n DocumentContentKeyTargetEnvelope,\n DocumentCreateRequest,\n DocumentLinkSetMutationRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerMutationAuthor } from \"../../containers/shared/types\";\nimport type { DocumentRecord } from \"../../persistence/documents/records\";\nimport type { DocumentSyncSubmitFailure } from \"./sync/syncSubmitFailure\";\n\nexport const DOCUMENT_ENCRYPTED_LORO_UPDATE_FORMAT =\n \"tearleads.document.loro-update\";\nexport const DOCUMENT_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_PLAINTEXT_HASH_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-plaintext-hash-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.document.content-record-aad\";\nexport const DOCUMENT_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.document.content-record-hkdf-salt\");\nexport const DOCUMENT_ENCRYPTED_UPDATE_KEYS = new Set([\n \"ciphertext\",\n \"contentKeyEpoch\",\n \"contentRecordId\",\n \"encryptionSuite\",\n \"format\",\n \"iv\",\n \"metadataHash\",\n \"nonceDomainHash\",\n \"version\",\n]);\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport type DocumentCreateAuthor = ContainerMutationAuthor;\n\nexport interface BuildDocumentCreatePlanInput {\n author: DocumentCreateAuthor;\n containerProjection: ContainerWriterProjectionResponse;\n contentKeyEpoch?: number;\n documentId?: string;\n eventId?: string;\n signedAt?: string;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n}\n\nexport interface DocumentCreatePlan {\n body: DocumentLinkAccessEventBody;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n request: DocumentCreateRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentCreatePlan {\n contentKey: Uint8Array;\n plan: DocumentCreatePlan;\n}\n\nexport interface DocumentCreateApi {\n // Lets idempotent create inspect an expected already-exists conflict.\n createDocumentResult(\n input: DocumentCreateRequest,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentCreateResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n // Result-returning variant used by the create path so a terminal projection\n // fetch failure (e.g. a 402 billing block or a 403 after access revocation)\n // can be persisted to the write queue instead of collapsing to a silent\n // null.\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n // Needed to adopt an existing remote document on a create conflict: the\n // committed manifest, content-key bundle and KEK targets are refetched here\n // (the create response that carried them was lost).\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n evictContainerWriterProjection(containerId: string): void;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n}\n\nexport interface CreateRemoteDocumentResult {\n contentKey: Uint8Array;\n /** The requested `deferredSeedUpdate`, signed but unsent, for a bind. */\n deferredSeed?: DocumentSyncRequest | undefined;\n documentId: string;\n persistedState: PersistedDocumentCreateState;\n // `plan` and `response` are absent when the result was adopted from an\n // existing remote document on a create conflict: there is no fresh create\n // response, and the local plan does not match the committed manifest (the\n // first attempt used a different content key). Consumers read only\n // documentId/writerProjection/persistedState.\n plan?: DocumentCreatePlan | undefined;\n response?: DocumentCreateResponse | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport type DocumentLinkSetMutationOperation = \"link\" | \"unlink\";\nexport type DocumentLinkSetMutationBody =\n | DocumentLinkAccessEventBody\n | DocumentUnlinkAccessEventBody;\n\nexport interface DocumentLinkSetTargetState {\n readonly currentTargets: readonly DocumentContentKeyTarget[];\n readonly linkedContainerIds: readonly string[];\n readonly target: DocumentContentKeyTarget;\n readonly targets: readonly DocumentContentKeyTarget[];\n}\n\nexport interface BuildDocumentLinkSetMutationPlanInput {\n blobRewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n author: DocumentCreateAuthor;\n contentKeyEpoch: number;\n eventId?: string | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DocumentLinkSetMutationPlan {\n body: DocumentLinkSetMutationBody;\n contentKeyEpoch: number;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentLinkSetMutationPlan {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n plan: DocumentLinkSetMutationPlan;\n}\n\nexport interface DocumentLinkSetEventPlan {\n authorizingContainerPathRefs: ContainerManifestRef[][];\n body: DocumentLinkSetMutationBody;\n event: AccessEvent;\n eventHash: string;\n}\n\n/**\n * What a failed link-set mutation could tell the caller: the HTTP status (or\n * null for network/local failures) and a short message. Threaded up to the\n * move-intent queue so a permission failure reads as one, instead of the\n * generic \"rejected or unavailable\".\n */\nexport type DocumentLinkSetMutationFailure = Pick<\n DocumentSyncSubmitFailure,\n \"code\" | \"message\" | \"status\"\n>;\n\nexport type DocumentLinkSetFailureHandler = (\n failure: DocumentLinkSetMutationFailure,\n) => void;\n\n/**\n * `prove` pulls and verifies the document's full history. `reuse` returns the\n * store's last completed proof while the same local document still sits at\n * that proof's version vector, and proves otherwise; only a caller the server\n * re-checks (an unlink's rotation baseline) may reuse.\n */\nexport type DocumentRotationProofMode = \"prove\" | \"reuse\";\n\ntype DocumentLinkSetMutationResult =\n | { readonly data: DocumentLinkSetMutationResponse; readonly ok: true }\n | (DocumentLinkSetMutationFailure & {\n readonly ok: false;\n /** The host report a `reportErrors: false` request withheld. */\n readonly report?: (() => void) | undefined;\n });\n\nexport interface DocumentLinkSetMutationApi {\n getBlobBytes(blobId: string): Promise<BlobBytesResponse | null>;\n listDocumentAttachments(\n documentId: string,\n options?: { readonly refresh?: boolean },\n ): Promise<ListDocumentAttachmentsResponse | null>;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getDocumentWriterProjectionResult(\n documentId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n linkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n unlinkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n}\n\nexport interface RelinkRemoteDocumentResult {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n documentId: string;\n linkedContainerIds: readonly string[];\n persistedState: PersistedDocumentCreateState;\n plan: DocumentLinkSetMutationPlan;\n response: DocumentLinkSetMutationResponse;\n}\n\nexport interface DocumentSyncRequestResultOptions {\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly reportErrors?: boolean | undefined;\n}\n\nexport type DocumentWriterPublicKeyResolver = (input: {\n writerSigningKeyFingerprint: string;\n writerUserId: string;\n}) => Promise<Uint8Array | null>;\n\nexport type PersistedDocumentCreateState = Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n>;\n\nexport type PersistedDocumentSyncState = PersistedDocumentCreateState;\n\nexport interface UnwrappedContainerKek {\n containerId: string;\n /**\n * Null for keyring-recovered historical keys, which carry key material and\n * the epoch id committing to it but no epoch record to hash.\n *\n * Such a key still satisfies a parent wrap: the epoch-record fingerprint is\n * a selector for choosing among envelopes, not the security boundary, so a\n * null hash falls back to selecting on the epoch id while AEAD authenticates\n * (see `containerKekPath.ts`). That is what lets a descendant pinned to a\n * rotated parent be opened rather than stranded.\n */\n keyEpochHash: string | null;\n keyMaterial: Uint8Array;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA2BA,MAAM,CAAC,MAAM,qCAAqC,GAChD,gCAAgC,CAAC;AACnC,MAAM,CAAC,MAAM,uCAAuC,GAClD,4CAA4C,CAAC;AAC/C,MAAM,CAAC,MAAM,sDAAsD,GACjE,2DAA2D,CAAC;AAC9D,MAAM,CAAC,MAAM,kCAAkC,GAC7C,uCAAuC,CAAC;AAC1C,MAAM,CAAC,MAAM,iCAAiC,GAC5C,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,6CAA6C,CAAC,CAAC;AAC1E,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,GAAG,CAAC;IACpD,YAAY;IACZ,iBAAiB;IACjB,iBAAiB;IACjB,iBAAiB;IACjB,QAAQ;IACR,IAAI;IACJ,cAAc;IACd,iBAAiB;IACjB,SAAS;CACV,CAAC,CAAC;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC","sourcesContent":["import type { BlobBytesResponse } from \"@tearleads/api-client\";\nimport type {\n AccessEvent,\n AccessManifest,\n DocumentContentKeyTarget,\n DocumentLinkAccessEventBody,\n DocumentLinkSetManifestState,\n DocumentUnlinkAccessEventBody,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerManifestRef,\n DocumentContentKeyTargetEnvelope,\n DocumentCreateRequest,\n DocumentLinkSetMutationRequest,\n DocumentSyncRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n DocumentLinkSetMutationResponse,\n DocumentWriterProjectionResponse,\n ListDocumentAttachmentsResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerMutationAuthor } from \"../../containers/shared/types\";\nimport type { DocumentRecord } from \"../../persistence/documents/records\";\nimport type { DocumentSyncSubmitFailure } from \"./sync/syncSubmitFailure\";\n\nexport const DOCUMENT_ENCRYPTED_LORO_UPDATE_FORMAT =\n \"tearleads.document.loro-update\";\nexport const DOCUMENT_CONTENT_RECORD_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_PLAINTEXT_HASH_KEY_INFO_DOMAIN =\n \"tearleads.document.content-record-plaintext-hash-key-info\";\nexport const DOCUMENT_CONTENT_RECORD_AAD_DOMAIN =\n \"tearleads.document.content-record-aad\";\nexport const DOCUMENT_CONTENT_RECORD_HKDF_SALT: Uint8Array<ArrayBuffer> =\n new TextEncoder().encode(\"tearleads.document.content-record-hkdf-salt\");\nexport const DOCUMENT_ENCRYPTED_UPDATE_KEYS = new Set([\n \"ciphertext\",\n \"contentKeyEpoch\",\n \"contentRecordId\",\n \"encryptionSuite\",\n \"format\",\n \"iv\",\n \"metadataHash\",\n \"nonceDomainHash\",\n \"version\",\n]);\nexport const TEXT_ENCODER = new TextEncoder();\n\nexport type DocumentCreateAuthor = ContainerMutationAuthor;\n\nexport interface BuildDocumentCreatePlanInput {\n author: DocumentCreateAuthor;\n containerProjection: ContainerWriterProjectionResponse;\n contentKeyEpoch?: number;\n documentId?: string;\n eventId?: string;\n signedAt?: string;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n}\n\nexport interface DocumentCreatePlan {\n body: DocumentLinkAccessEventBody;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n request: DocumentCreateRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentCreatePlan {\n contentKey: Uint8Array;\n plan: DocumentCreatePlan;\n}\n\nexport interface DocumentCreateApi {\n // Lets idempotent create inspect an expected already-exists conflict.\n createDocumentResult(\n input: DocumentCreateRequest,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentCreateResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n // Result-returning variant used by the create path so a terminal projection\n // fetch failure (e.g. a 402 billing block or a 403 after access revocation)\n // can be persisted to the write queue instead of collapsing to a silent\n // null.\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n // Needed to adopt an existing remote document on a create conflict: the\n // committed manifest, content-key bundle and KEK targets are refetched here\n // (the create response that carried them was lost).\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n evictContainerWriterProjection(containerId: string): void;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n}\n\nexport interface CreateRemoteDocumentResult {\n contentKey: Uint8Array;\n /** The requested `deferredSeedUpdate`, signed but unsent, for a bind. */\n deferredSeed?: DocumentSyncRequest | undefined;\n documentId: string;\n persistedState: PersistedDocumentCreateState;\n // `plan` and `response` are absent when the result was adopted from an\n // existing remote document on a create conflict: there is no fresh create\n // response, and the local plan does not match the committed manifest (the\n // first attempt used a different content key). Consumers read only\n // documentId/writerProjection/persistedState.\n plan?: DocumentCreatePlan | undefined;\n response?: DocumentCreateResponse | undefined;\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport type DocumentLinkSetMutationOperation = \"link\" | \"unlink\";\nexport type DocumentLinkSetMutationBody =\n | DocumentLinkAccessEventBody\n | DocumentUnlinkAccessEventBody;\n\nexport interface DocumentLinkSetTargetState {\n readonly currentTargets: readonly DocumentContentKeyTarget[];\n readonly linkedContainerIds: readonly string[];\n readonly target: DocumentContentKeyTarget;\n readonly targets: readonly DocumentContentKeyTarget[];\n}\n\nexport interface BuildDocumentLinkSetMutationPlanInput {\n blobRewraps: DocumentLinkAccessEventBody[\"blobRewraps\"];\n author: DocumentCreateAuthor;\n contentKeyEpoch: number;\n eventId?: string | undefined;\n operation: DocumentLinkSetMutationOperation;\n signedAt?: string | undefined;\n targetContainerProjection: ContainerWriterProjectionResponse;\n targetEnvelopes: readonly DocumentContentKeyTargetEnvelope[];\n writerProjection: DocumentWriterProjectionResponse;\n}\n\nexport interface DocumentLinkSetMutationPlan {\n body: DocumentLinkSetMutationBody;\n contentKeyEpoch: number;\n documentId: string;\n event: AccessEvent;\n eventHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n operation: DocumentLinkSetMutationOperation;\n request: DocumentLinkSetMutationRequest;\n state: DocumentLinkSetManifestState;\n targetHash: string;\n targets: DocumentContentKeyTarget[];\n}\n\nexport interface MaterializedDocumentLinkSetMutationPlan {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n plan: DocumentLinkSetMutationPlan;\n}\n\nexport interface DocumentLinkSetEventPlan {\n authorizingContainerPathRefs: ContainerManifestRef[][];\n body: DocumentLinkSetMutationBody;\n event: AccessEvent;\n eventHash: string;\n}\n\n/**\n * What a failed link-set mutation could tell the caller: the HTTP status (or\n * null for network/local failures) and a short message. Threaded up to the\n * move-intent queue so a permission failure reads as one, instead of the\n * generic \"rejected or unavailable\".\n */\nexport type DocumentLinkSetMutationFailure = Pick<\n DocumentSyncSubmitFailure,\n \"code\" | \"message\" | \"status\"\n>;\n\nexport type DocumentLinkSetFailureHandler = (\n failure: DocumentLinkSetMutationFailure,\n) => void;\n\n/**\n * `prove` pulls and verifies the document's full history. `reuse` returns the\n * store's last completed proof while the same local document still sits at\n * that proof's version vector, and proves otherwise; only a caller the server\n * re-checks (an unlink's rotation baseline) may reuse.\n */\nexport type DocumentRotationProofMode = \"prove\" | \"reuse\";\n\ntype DocumentLinkSetMutationResult =\n | { readonly data: DocumentLinkSetMutationResponse; readonly ok: true }\n | (DocumentLinkSetMutationFailure & {\n readonly ok: false;\n /** The host report a `reportErrors: false` request withheld. */\n readonly report?: (() => void) | undefined;\n });\n\nexport interface DocumentLinkSetMutationApi {\n getBlobBytes(blobId: string): Promise<BlobBytesResponse | null>;\n listDocumentAttachments(\n documentId: string,\n options?: { readonly refresh?: boolean },\n ): Promise<ListDocumentAttachmentsResponse | null>;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n getContainerWriterProjectionResult(\n containerId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: ContainerWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n getDocumentWriterProjection(\n documentId: string,\n ): Promise<DocumentWriterProjectionResponse | null>;\n getDocumentWriterProjectionResult(\n documentId: string,\n options?: DocumentSyncRequestResultOptions | undefined,\n ): Promise<\n | {\n readonly data: DocumentWriterProjectionResponse;\n readonly ok: true;\n }\n | DocumentSyncSubmitFailure\n >;\n primeDocumentWriterProjection(\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n ): void;\n linkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n unlinkDocumentResult(\n documentId: string,\n input: DocumentLinkSetMutationRequest,\n options?: DocumentSyncRequestResultOptions,\n ): Promise<DocumentLinkSetMutationResult>;\n}\n\nexport interface RelinkRemoteDocumentResult {\n contentKey: Uint8Array;\n contentKeyRotated: boolean;\n documentId: string;\n linkedContainerIds: readonly string[];\n persistedState: PersistedDocumentCreateState;\n plan: DocumentLinkSetMutationPlan;\n response: DocumentLinkSetMutationResponse;\n}\n\nexport interface DocumentSyncRequestResultOptions {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly reportErrors?: boolean | undefined;\n}\n\nexport type DocumentWriterPublicKeyResolver = (input: {\n writerSigningKeyFingerprint: string;\n writerUserId: string;\n}) => Promise<Uint8Array | null>;\n\nexport type PersistedDocumentCreateState = Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n>;\n\nexport type PersistedDocumentSyncState = PersistedDocumentCreateState;\n\nexport interface UnwrappedContainerKek {\n containerId: string;\n /**\n * Null for keyring-recovered historical keys, which carry key material and\n * the epoch id committing to it but no epoch record to hash.\n *\n * Such a key still satisfies a parent wrap: the epoch-record fingerprint is\n * a selector for choosing among envelopes, not the security boundary, so a\n * null hash falls back to selecting on the epoch id while AEAD authenticates\n * (see `containerKekPath.ts`). That is what lets a descendant pinned to a\n * rotated parent be opened rather than stranded.\n */\n keyEpochHash: string | null;\n keyMaterial: Uint8Array;\n}\n"]}
@@ -6,7 +6,7 @@ export { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
6
6
  export type { DocumentPlacementCleanup } from "./documentDeletionPort.js";
7
7
  export type { PendingUpdateRecord, QueuedPendingUpdateRecord } from "./records/index.js";
8
8
  export type { AttachmentRemovalRows, AttachmentStagingRows, ContainerDocumentTombstoneInput, DiscardDocumentToShellResult, DocumentsPersistence, LocalAttachmentRecord, PendingAttachmentRecord, PendingAttachmentUploadIdentity, PendingUpdateInsert, RelinkPersistedDocumentInput, StoredDocumentRecord, } from "./types.js";
9
- export declare function upsertDiscoveredDocuments(execSql: ExecSql, inputs: ReadonlyArray<DiscoveredDocumentInput>): Promise<DocumentSummary[]>;
9
+ export declare function upsertDiscoveredDocuments(execSql: ExecSql, inputs: ReadonlyArray<DiscoveredDocumentInput>, assertCurrent?: () => void): Promise<DocumentSummary[]>;
10
10
  export declare function applyContainerDocumentTombstones(execSql: ExecSql, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>, removePlacementRows: ContainerDocumentTombstonePlacementRemoval): Promise<DocumentSummary[]>;
11
11
  export declare function listDocumentsByContainerIdsOrDocumentIds(execSql: ExecSql, input: {
12
12
  containerIds: ReadonlyArray<string>;
@@ -2,6 +2,7 @@ import { and, desc, eq, inArray, notInArray, or } from "drizzle-orm";
2
2
  import { HIDDEN_DOCUMENT_SUMMARY_KINDS, } from "../../documents/documentSummary.js";
3
3
  import { documentProjection } from "../../sqlite/schema/documentProjectionSchema.js";
4
4
  import { documents } from "../../sqlite/schema/documentRecordSchema.js";
5
+ import { registerClientSQLiteCommitGuard } from "../../sqlite/sqliteCommitGuards.js";
5
6
  import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
6
7
  import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
7
8
  import { applyContainerDocumentTombstonesWithExec, } from "./internal/containerDocumentTombstones.js";
@@ -55,10 +56,12 @@ async function relinkPersistedDocumentWithExec(execSql, input) {
55
56
  .limit(1);
56
57
  return toDocumentSummary(nextDocument, getProjectionUpdatedAt(updatedAtRows[0]));
57
58
  }
58
- export async function upsertDiscoveredDocuments(execSql, inputs) {
59
+ export async function upsertDiscoveredDocuments(execSql, inputs, assertCurrent) {
59
60
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
60
61
  await sqlDocumentsPersistence.ensureSchema(lockedExecSql);
61
62
  return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
63
+ if (assertCurrent)
64
+ registerClientSQLiteCommitGuard(lockedExecSql, assertCurrent);
62
65
  const pendingCreates = await mapPendingCreateLocalIds(lockedExecSql);
63
66
  return upsertDiscoveredDocumentsInTransaction(lockedExecSql, inputs, pendingCreates, tx);
64
67
  }, { behavior: "immediate" });
@@ -1 +1 @@
1
- {"version":3,"file":"documentsPersistence.js","sourceRoot":"","sources":["documentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC/E,OAAO,EAGL,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAC;AAClF,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EACL,wCAAwC,GAEzC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yCAAyC,EAAE,MAAM,gDAAgD,CAAC;AAC3G,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EACL,oBAAoB,EACpB,6BAA6B,EAC7B,oCAAoC,GACrC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yCAAyC,EAAE,MAAM,4CAA4C,CAAC;AACvG,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,GACnC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,wCAAwC,EAAE,MAAM,gDAAgD,CAAC;AAC1G,OAAO,EACL,gBAAgB,EAChB,4BAA4B,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InArray, or, type SQL } from \"drizzle-orm\";\nimport {\n type DiscoveredDocumentInput,\n type DocumentSummary,\n HIDDEN_DOCUMENT_SUMMARY_KINDS,\n} from \"../../documents/documentSummary\";\nimport { documentProjection } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n applyContainerDocumentTombstonesWithExec,\n type ContainerDocumentTombstonePlacementRemoval,\n} from \"./internal/containerDocumentTombstones\";\nimport { createStoredDocumentWithHistoryCheckpoint } from \"./internal/createDocumentWithHistoryCheckpoint\";\nimport { discardStoredDocumentToShell } from \"./internal/discardDocument\";\nimport { upsertDiscoveredDocumentsInTransaction } from \"./internal/discoveredDocumentUpsert\";\nimport {\n deleteStoredDocument,\n deleteStoredDocumentIfMatches,\n deleteStoredDocumentSideRowsIfAbsent,\n} from \"./internal/documentDeletionPersistence\";\nimport { loadStoredDocumentWithHistoryRestoreState } from \"./internal/documentHistoryStatePersistence\";\nimport {\n commitStoredDocumentMutation,\n settleStoredDocumentPendingUpdates,\n} from \"./internal/documentMutationPersistence\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionUpdatedAt,\n mapDocumentSummary,\n toDocumentSummary,\n} from \"./internal/documentProjectionRows\";\nimport { invalidateStoredDocumentPullContinuation } from \"./internal/documentPullContinuationPersistence\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./internal/documentRows\";\nimport {\n resolvePersistedAccessStateHash,\n resolvePersistedDocumentRuntimeState,\n} from \"./internal/documentRuntimeState\";\nimport { loadStoredDocumentStoreState } from \"./internal/documentStoreStatePersistence\";\nimport { listDocumentSummaries } from \"./internal/documentSummaryQueries\";\nimport { ensureDocumentsSchema } from \"./internal/ensureDocumentsSchema\";\nimport { saveHydratedAttachment } from \"./internal/hydratedAttachmentPersistence\";\nimport {\n acknowledgeDocumentOrphanBlobReclaim,\n deleteOrphanedDocumentSideRows,\n isDocumentBlobStorageKeyReferenced,\n listDocumentOrphanBlobReclaims,\n} from \"./internal/orphanSideRows\";\nimport { mapPendingCreateLocalIds } from \"./internal/pendingCreateAdoption\";\nimport { documentRowQueryPersistence } from \"./internal/rowQueryPersistence\";\nimport { documentSyncQueuePersistence } from \"./internal/syncQueuePersistence\";\nimport { settleQueuedDocumentUpdatesInTransaction } from \"./records/documentPendingUpdatePersistence\";\nimport type {\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nexport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nexport type { DocumentPlacementCleanup } from \"./documentDeletionPort\";\nexport type { PendingUpdateRecord, QueuedPendingUpdateRecord } from \"./records\";\nexport type {\n AttachmentRemovalRows,\n AttachmentStagingRows,\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingAttachmentUploadIdentity,\n PendingUpdateInsert,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nasync function relinkPersistedDocumentWithExec(\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n): Promise<DocumentSummary | null> {\n const existingDocument = await sqlDocumentsPersistence.loadDocument(\n execSql,\n input.localId,\n );\n if (!existingDocument) {\n return null;\n }\n\n const nextAccessEpoch = Math.max(\n existingDocument.accessEpoch,\n input.accessEpoch,\n );\n const nextDocument: StoredDocumentRecord = {\n ...existingDocument,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolvePersistedAccessStateHash(existingDocument, {\n accessEpoch: nextAccessEpoch,\n accessStateHash: input.accessStateHash,\n documentId: input.documentId,\n }),\n containerId: input.containerId,\n documentId: input.documentId,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: nextAccessEpoch,\n documentId: input.documentId,\n }),\n };\n\n await sqlDocumentsPersistence.saveDocument(execSql, nextDocument);\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const updatedAtRows = await db\n .select({ updatedAt: documentProjection.updatedAt })\n .from(documentProjection)\n .where(eq(documentProjection.localId, input.localId))\n .limit(1);\n\n return toDocumentSummary(\n nextDocument,\n getProjectionUpdatedAt(updatedAtRows[0]),\n );\n}\n\nexport async function upsertDiscoveredDocuments(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const pendingCreates = await mapPendingCreateLocalIds(lockedExecSql);\n return upsertDiscoveredDocumentsInTransaction(\n lockedExecSql,\n inputs,\n pendingCreates,\n tx,\n );\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function applyContainerDocumentTombstones(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n removePlacementRows: ContainerDocumentTombstonePlacementRemoval,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return applyContainerDocumentTombstonesWithExec(\n lockedExecSql,\n tombstones,\n removePlacementRows,\n );\n });\n}\n\nexport async function listDocumentsByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n): Promise<DocumentSummary[]> {\n const uniqueContainerIds = Array.from(new Set(input.containerIds));\n const uniqueDocumentIds = Array.from(new Set(input.documentIds));\n if (uniqueContainerIds.length === 0 && uniqueDocumentIds.length === 0) {\n return [];\n }\n\n const filters: SQL[] = [];\n if (uniqueContainerIds.length > 0) {\n filters.push(inArray(documentProjection.containerId, uniqueContainerIds));\n }\n\n if (uniqueDocumentIds.length > 0) {\n filters.push(inArray(documentProjection.documentId, uniqueDocumentIds));\n }\n\n const whereCondition = filters.length === 1 ? filters[0] : or(...filters);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n and(\n whereCondition,\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n}\n\nexport const sqlDocumentsPersistence: DocumentsPersistence = {\n orphanBlobs: {\n acknowledge: acknowledgeDocumentOrphanBlobReclaim,\n isReferenced: isDocumentBlobStorageKeyReferenced,\n list: listDocumentOrphanBlobReclaims,\n sweep: deleteOrphanedDocumentSideRows,\n },\n ...documentRowQueryPersistence,\n ...documentSyncQueuePersistence,\n supportsAtomicRecoveryHistoryPruning: true,\n saveHydratedAttachment,\n createDocumentWithHistoryCheckpoint:\n createStoredDocumentWithHistoryCheckpoint,\n commitDocumentMutation: (execSql, input, saveClientProjection) =>\n commitStoredDocumentMutation(\n execSql,\n input,\n saveClientProjection,\n sqlDocumentsPersistence.loadDocument,\n ),\n settleAcceptedPendingUpdates: (execSql, input) =>\n settleStoredDocumentPendingUpdates(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n ),\n ensureSchema: ensureDocumentsSchema,\n listDocumentSummaries,\n listDocumentsByContainerIdsOrDocumentIds,\n invalidatePullContinuation: (execSql, input) =>\n invalidateStoredDocumentPullContinuation(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n sqlDocumentsPersistence.loadHistoryRestoreState,\n ),\n loadDocumentWithHistoryRestoreState: (execSql, localId) =>\n loadStoredDocumentWithHistoryRestoreState(\n execSql,\n localId,\n sqlDocumentsPersistence,\n ),\n loadDocumentStoreState: (execSql, localId) =>\n loadStoredDocumentStoreState(execSql, localId, sqlDocumentsPersistence),\n async saveDocument(execSql, document, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n async saveDocumentAndDeletePendingUpdates(\n execSql,\n document,\n pendingUpdateIds,\n options,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n const saved = await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n if (!saved) return updatedAt;\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getDocumentScope(document.id),\n pendingUpdateIds,\n );\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n deleteDocument: deleteStoredDocument,\n deleteDocumentIfMatches: deleteStoredDocumentIfMatches,\n deleteDocumentSideRowsIfAbsent: deleteStoredDocumentSideRowsIfAbsent,\n async discardDocumentToShell(\n execSql,\n localId,\n expectedDocumentId,\n documentProjectors,\n ): Promise<DiscardDocumentToShellResult> {\n return discardStoredDocumentToShell({\n documentProjectors,\n execSql,\n expectedDocumentId,\n localId,\n persistence: sqlDocumentsPersistence,\n });\n },\n async upsertDiscoveredDocument(execSql, input) {\n const [nextSummary] = await upsertDiscoveredDocuments(execSql, [input]);\n if (!nextSummary) {\n throw new Error(\"Failed to upsert discovered document\");\n }\n\n return nextSummary;\n },\n async relinkPersistedDocument(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n () => relinkPersistedDocumentWithExec(lockedExecSql, input),\n { behavior: \"immediate\" },\n );\n });\n },\n};\n"]}
1
+ {"version":3,"file":"documentsPersistence.js","sourceRoot":"","sources":["documentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC/E,OAAO,EAGL,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAC;AAClF,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,+BAA+B,EAAE,MAAM,iCAAiC,CAAC;AAClF,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EACL,wCAAwC,GAEzC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yCAAyC,EAAE,MAAM,gDAAgD,CAAC;AAC3G,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EACL,oBAAoB,EACpB,6BAA6B,EAC7B,oCAAoC,GACrC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yCAAyC,EAAE,MAAM,4CAA4C,CAAC;AACvG,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,GACnC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,sBAAsB,EACtB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,wCAAwC,EAAE,MAAM,gDAAgD,CAAC;AAC1G,OAAO,EACL,gBAAgB,EAChB,4BAA4B,EAC5B,gBAAgB,GACjB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,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n type DiscoveredDocumentInput,\n type DocumentSummary,\n HIDDEN_DOCUMENT_SUMMARY_KINDS,\n} from \"../../documents/documentSummary\";\nimport { documentProjection } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n applyContainerDocumentTombstonesWithExec,\n type ContainerDocumentTombstonePlacementRemoval,\n} from \"./internal/containerDocumentTombstones\";\nimport { createStoredDocumentWithHistoryCheckpoint } from \"./internal/createDocumentWithHistoryCheckpoint\";\nimport { discardStoredDocumentToShell } from \"./internal/discardDocument\";\nimport { upsertDiscoveredDocumentsInTransaction } from \"./internal/discoveredDocumentUpsert\";\nimport {\n deleteStoredDocument,\n deleteStoredDocumentIfMatches,\n deleteStoredDocumentSideRowsIfAbsent,\n} from \"./internal/documentDeletionPersistence\";\nimport { loadStoredDocumentWithHistoryRestoreState } from \"./internal/documentHistoryStatePersistence\";\nimport {\n commitStoredDocumentMutation,\n settleStoredDocumentPendingUpdates,\n} from \"./internal/documentMutationPersistence\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionUpdatedAt,\n mapDocumentSummary,\n toDocumentSummary,\n} from \"./internal/documentProjectionRows\";\nimport { invalidateStoredDocumentPullContinuation } from \"./internal/documentPullContinuationPersistence\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./internal/documentRows\";\nimport {\n resolvePersistedAccessStateHash,\n resolvePersistedDocumentRuntimeState,\n} from \"./internal/documentRuntimeState\";\nimport { loadStoredDocumentStoreState } from \"./internal/documentStoreStatePersistence\";\nimport { listDocumentSummaries } from \"./internal/documentSummaryQueries\";\nimport { ensureDocumentsSchema } from \"./internal/ensureDocumentsSchema\";\nimport { saveHydratedAttachment } from \"./internal/hydratedAttachmentPersistence\";\nimport {\n acknowledgeDocumentOrphanBlobReclaim,\n deleteOrphanedDocumentSideRows,\n isDocumentBlobStorageKeyReferenced,\n listDocumentOrphanBlobReclaims,\n} from \"./internal/orphanSideRows\";\nimport { mapPendingCreateLocalIds } from \"./internal/pendingCreateAdoption\";\nimport { documentRowQueryPersistence } from \"./internal/rowQueryPersistence\";\nimport { documentSyncQueuePersistence } from \"./internal/syncQueuePersistence\";\nimport { settleQueuedDocumentUpdatesInTransaction } from \"./records/documentPendingUpdatePersistence\";\nimport type {\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nexport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nexport type { DocumentPlacementCleanup } from \"./documentDeletionPort\";\nexport type { PendingUpdateRecord, QueuedPendingUpdateRecord } from \"./records\";\nexport type {\n AttachmentRemovalRows,\n AttachmentStagingRows,\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingAttachmentUploadIdentity,\n PendingUpdateInsert,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nasync function relinkPersistedDocumentWithExec(\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n): Promise<DocumentSummary | null> {\n const existingDocument = await sqlDocumentsPersistence.loadDocument(\n execSql,\n input.localId,\n );\n if (!existingDocument) {\n return null;\n }\n\n const nextAccessEpoch = Math.max(\n existingDocument.accessEpoch,\n input.accessEpoch,\n );\n const nextDocument: StoredDocumentRecord = {\n ...existingDocument,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolvePersistedAccessStateHash(existingDocument, {\n accessEpoch: nextAccessEpoch,\n accessStateHash: input.accessStateHash,\n documentId: input.documentId,\n }),\n containerId: input.containerId,\n documentId: input.documentId,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: nextAccessEpoch,\n documentId: input.documentId,\n }),\n };\n\n await sqlDocumentsPersistence.saveDocument(execSql, nextDocument);\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const updatedAtRows = await db\n .select({ updatedAt: documentProjection.updatedAt })\n .from(documentProjection)\n .where(eq(documentProjection.localId, input.localId))\n .limit(1);\n\n return toDocumentSummary(\n nextDocument,\n getProjectionUpdatedAt(updatedAtRows[0]),\n );\n}\n\nexport async function upsertDiscoveredDocuments(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n assertCurrent?: () => void,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n if (assertCurrent)\n registerClientSQLiteCommitGuard(lockedExecSql, assertCurrent);\n const pendingCreates = await mapPendingCreateLocalIds(lockedExecSql);\n return upsertDiscoveredDocumentsInTransaction(\n lockedExecSql,\n inputs,\n pendingCreates,\n tx,\n );\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function applyContainerDocumentTombstones(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n removePlacementRows: ContainerDocumentTombstonePlacementRemoval,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return applyContainerDocumentTombstonesWithExec(\n lockedExecSql,\n tombstones,\n removePlacementRows,\n );\n });\n}\n\nexport async function listDocumentsByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n): Promise<DocumentSummary[]> {\n const uniqueContainerIds = Array.from(new Set(input.containerIds));\n const uniqueDocumentIds = Array.from(new Set(input.documentIds));\n if (uniqueContainerIds.length === 0 && uniqueDocumentIds.length === 0) {\n return [];\n }\n\n const filters: SQL[] = [];\n if (uniqueContainerIds.length > 0) {\n filters.push(inArray(documentProjection.containerId, uniqueContainerIds));\n }\n\n if (uniqueDocumentIds.length > 0) {\n filters.push(inArray(documentProjection.documentId, uniqueDocumentIds));\n }\n\n const whereCondition = filters.length === 1 ? filters[0] : or(...filters);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n and(\n whereCondition,\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n}\n\nexport const sqlDocumentsPersistence: DocumentsPersistence = {\n orphanBlobs: {\n acknowledge: acknowledgeDocumentOrphanBlobReclaim,\n isReferenced: isDocumentBlobStorageKeyReferenced,\n list: listDocumentOrphanBlobReclaims,\n sweep: deleteOrphanedDocumentSideRows,\n },\n ...documentRowQueryPersistence,\n ...documentSyncQueuePersistence,\n supportsAtomicRecoveryHistoryPruning: true,\n saveHydratedAttachment,\n createDocumentWithHistoryCheckpoint:\n createStoredDocumentWithHistoryCheckpoint,\n commitDocumentMutation: (execSql, input, saveClientProjection) =>\n commitStoredDocumentMutation(\n execSql,\n input,\n saveClientProjection,\n sqlDocumentsPersistence.loadDocument,\n ),\n settleAcceptedPendingUpdates: (execSql, input) =>\n settleStoredDocumentPendingUpdates(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n ),\n ensureSchema: ensureDocumentsSchema,\n listDocumentSummaries,\n listDocumentsByContainerIdsOrDocumentIds,\n invalidatePullContinuation: (execSql, input) =>\n invalidateStoredDocumentPullContinuation(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n sqlDocumentsPersistence.loadHistoryRestoreState,\n ),\n loadDocumentWithHistoryRestoreState: (execSql, localId) =>\n loadStoredDocumentWithHistoryRestoreState(\n execSql,\n localId,\n sqlDocumentsPersistence,\n ),\n loadDocumentStoreState: (execSql, localId) =>\n loadStoredDocumentStoreState(execSql, localId, sqlDocumentsPersistence),\n async saveDocument(execSql, document, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n async saveDocumentAndDeletePendingUpdates(\n execSql,\n document,\n pendingUpdateIds,\n options,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n const saved = await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n if (!saved) return updatedAt;\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getDocumentScope(document.id),\n pendingUpdateIds,\n );\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n deleteDocument: deleteStoredDocument,\n deleteDocumentIfMatches: deleteStoredDocumentIfMatches,\n deleteDocumentSideRowsIfAbsent: deleteStoredDocumentSideRowsIfAbsent,\n async discardDocumentToShell(\n execSql,\n localId,\n expectedDocumentId,\n documentProjectors,\n ): Promise<DiscardDocumentToShellResult> {\n return discardStoredDocumentToShell({\n documentProjectors,\n execSql,\n expectedDocumentId,\n localId,\n persistence: sqlDocumentsPersistence,\n });\n },\n async upsertDiscoveredDocument(execSql, input) {\n const [nextSummary] = await upsertDiscoveredDocuments(execSql, [input]);\n if (!nextSummary) {\n throw new Error(\"Failed to upsert discovered document\");\n }\n\n return nextSummary;\n },\n async relinkPersistedDocument(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n () => relinkPersistedDocumentWithExec(lockedExecSql, input),\n { behavior: \"immediate\" },\n );\n });\n },\n};\n"]}
package/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { type ApiRequestCounts, type ApiRequestEndpointCounts, ApiRequestMetrics, type ApiRequestMetricsSnapshot, } from "./internal/api-client/index.js";
2
2
  export type { AbandonOrganizationPolicyMutationInput, AddOrganizationGroupUserInput, BlobInfo, BlobInfoAttachmentKind, BlobInfoDocumentReference, BlobInfoInput, BlobInfoList, BlobInfoSort, BlobInfoSortDirection, BlobInfoSortKey, BrowserLocalKeyringOptions, ContainerContents, ContainerContentsContextValue, ContainerContentsStore, ContainerContentsStoreOptions, ContainerDocumentLinkInput, ContainerDocumentLinks, ContainerDocumentObjectSyncState, ContainerDocumentObjectSyncStatus, ContainerDocumentQueries, ContainerDocumentSidebarRow, ContainerInfo, ContainerInfoInput, ContainerItemRow, ContainerItemSort, ContainerItemSortDirection, ContainerItemSortKey, ContainerNode, ContainerShareAccessLevel, CreateOrganizationOptions, DatabaseListener, DatabaseOptions, DatabaseSnapshot, DatabaseStatus, DeviceFirst, DeviceFirstContainerContents, DiscardUnreadableOrganizationPolicyMutationInput, DocumentAttachmentStatus, DocumentAttachmentUpload, DocumentAttributionRangesInput, DocumentAttributionRangesPage, DocumentContextValue, DocumentHistory, DocumentHistoryChange, DocumentHistoryRowChange, DocumentHistoryStop, DocumentHistoryTextChange, DocumentHistoryVersion, DocumentHistoryVersionEntry, DocumentHistoryView, DocumentInfo, DocumentInfoInput, DocumentList, DocumentSort, DocumentSortDirection, DocumentSortKey, DocumentStore, DocumentSubscriptionOptions, Documents, DocumentsRuntime, DocumentsWorkflowRuntimeInput, DomainScope, FileSaver, Identity, IdentityGenerationResult, IdentityKeyPackage, IdentityListener, IdentityOptions, IdentitySnapshot, IndexedDbLocalKeyringManifestStoreOptions, IndexedDbWrappingKeyKeystoreOptions, LinkDocumentToContainerInput, ListDocumentsInput, LocalKeyPurpose, LocalKeyring, LocalKeyringManifest, LocalKeyringManifestFormat, LocalKeyringManifestStorage, LocalKeyringManifestStore, LocalKeyringOptions, LocalKeyringPinCode, LocalKeyringScope, LocalKeyringSession, LocalOrganizationSummary, LocalProjectionReconciledDelta, LocalProjectionSnapshot, LocalProjectionView, LocalSecretContext, LocalStorageLocalKeyringManifestStoreOptions, Logger, MergeDocumentSummary, MoveDocumentToContainerInput, NetworkListener, NetworkMode, NetworkStatusSource, NormalizedLocalKeyringScope, OpenContainerDocumentInput, OpenDocumentInput, OpenDocumentOptions, OrganizationBilling, OrganizationBillingHistory, OrganizationBillingHistoryEntry, OrganizationBillingManagementUrl, OrganizationBillingView, OrganizationContainerGrant, OrganizationContainerGrants, OrganizationDataUsage, OrganizationDeviceDataUsage, OrganizationDeviceDocumentUsageCategoryBreakdown, OrganizationDirectory, OrganizationDirectoryAndGroups, OrganizationDirectoryUser, OrganizationGrantRef, OrganizationGroupContainer, OrganizationGroupContainers, OrganizationGroupDetails, OrganizationGroupMember, OrganizationGroupMembers, OrganizationGroupMutationReceipt, OrganizationGroupMutationResult, OrganizationGroupPolicyHistory, OrganizationGroupSummary, OrganizationLeaveRequestResult, OrganizationMembership, OrganizationMemberships, OrganizationPolicyGrantChange, OrganizationPolicyGroupChange,
3
3
  /** Verified organization display page with an optional older-page cursor. */
4
- OrganizationPolicyHistory, OrganizationPolicyHistoryEntry, OrganizationProfile, OrganizationSyncPauseResult, Organizations, OrganizationUserDetail, PendingWriteQueueItem, PendingWriteQueueItemStatus, PendingWriteQueueObjectKind, PendingWriteQueueOperation, PendingWriteQueueOperationKind, PendingWriteQueueOperationStatus, PersistedDocumentListener, PinCodeBrowserLocalKeyringOptions, PinCodeWrappingKeyKeystoreOptions, PurgeDocumentInput, PurgeDocumentResult, ReconciliationService, RemoveOrganizationGroupUserInput, ResolvedUserIdentity, SaveFileRequest, SecurityIncident, SecurityIncidentListener, SecurityIncidentObjectKind, SecurityIncidents, Session, SessionContext, SessionCreateOrganizationResult, SessionListener, SessionRecoverOrganizationResult, SessionRegistrationRefusal, SessionRegistrationResult, SessionSnapshot, SetActiveDocumentContainerInput, SetLinkedContainerIdsForDocument, UnlinkDocumentFromContainerInput, UnwrapLocalSecretInput, UserIdentities, UserSession, WrapLocalSecretInput, WrappedLocalSecretEnvelope, WrappedLocalSecretFormat, WrappingKeyHandle, WrappingKeyKeystore, WrappingKeyMaterialStorage, } from "./client/index.js";
4
+ OrganizationPolicyHistory, OrganizationPolicyHistoryEntry, OrganizationProfile, OrganizationSyncPauseResult, Organizations, OrganizationUserDetail, PendingWriteQueueItem, PendingWriteQueueItemStatus, PendingWriteQueueObjectKind, PendingWriteQueueOperation, PendingWriteQueueOperationKind, PendingWriteQueueOperationStatus, PersistedDocumentListener, PinCodeBrowserLocalKeyringOptions, PinCodeWrappingKeyKeystoreOptions, PurgeDocumentInput, PurgeDocumentResult, ReconciliationService, RemoveOrganizationGroupUserInput, ResolvedUserIdentity, SaveFileRequest, SecurityIncident, SecurityIncidentListener, SecurityIncidentObjectKind, SecurityIncidents, SeededDocumentInput, Session, SessionContext, SessionCreateOrganizationResult, SessionListener, SessionRecoverOrganizationResult, SessionRegistrationRefusal, SessionRegistrationResult, SessionSnapshot, SetActiveDocumentContainerInput, SetLinkedContainerIdsForDocument, UnlinkDocumentFromContainerInput, UnwrapLocalSecretInput, UserIdentities, UserSession, WrapLocalSecretInput, WrappedLocalSecretEnvelope, WrappedLocalSecretFormat, WrappingKeyHandle, WrappingKeyKeystore, WrappingKeyMaterialStorage, } from "./client/index.js";
5
5
  export { type BlobStoreFactory, Blobs, createBrowserLocalKeyring, createBrowserLocalKeyringManifestStore, createBrowserNetworkStatusSource, createContainerContentsStoreWorkflowRuntime, createContainerContentsWorkflowRuntime, createContainerDocumentObjectSyncState, createDocumentsWorkflowRuntime, createDomainScope, createIndexedDbLocalKeyringManifestStore, createIndexedDbWrappingKeyKeystore, createLocalKeyring, createLocalStorageLocalKeyringManifestStore, createMemoryLocalKeyringManifestStore, createMemoryWrappingKeyKeystore, createPinCodeBrowserLocalKeyring, createPinCodeWrappingKeyKeystore, createRevenueCatPurchases, createUnavailableDirectCheckout, createUnavailablePurchases, createWebViewLocalKeyring, Database, DEFAULT_DOCUMENT_ID, type DirectCheckoutAppearance, type DirectCheckoutCapability, type DirectCheckoutConfirmation, type DirectCheckoutSession, DirectCheckoutUnavailableError, decodeLocalKeyringSqliteKey, Events, type EventsListener, type EventsSnapshot, encodeLocalKeyringSqliteKey, enqueueReconciliationForEvents, IDENTITY_KEY_PACKAGE_FORMAT, isPinCodeWrappedLocalSecretEnvelope, LOCAL_KEYRING_MANIFEST_FORMAT, localKeyringScopeKey, Network, normalizeLocalKeyringScope, type PrincipalHistoryKeyProvider, type PrincipalHistoryKeyScope, PurchaseAbortedError, PurchaseAlreadyOwnedError, PurchaseCancelledError, PurchaseIdentityPendingError, PurchaseProviderStalledError, type PurchasesCapability, PurchasesUnavailableError, PurgedOrganizationRecoveryBillingRequiredError, parseLocalKeyringManifest, type RevenueCatBackend, type RevenueCatCustomerInfo, type RevenueCatPackage, type RevenueCatPurchasesConfig, SyncBillingGate, type SyncBillingGateListener, type SyncPurchaseResult, type SyncSubscriptionOption, serializeLocalKeyringManifest, UnverifiedUserIdentityError, WRAPPED_LOCAL_SECRET_FORMAT, } from "./client/index.js";
6
6
  export type { DiscoveredDocumentInput, DocumentAttachment, DocumentClientProjectionDefinition, DocumentClientProjectionDeleteInput, DocumentClientProjectionSaveInput, DocumentFieldValidationIssue, DocumentProjection, DocumentProjectorDefinition, DocumentProjectorInput, DocumentProjectorRegistry, DocumentProjectorRegistryInput, DocumentRestoreContent, DocumentRow, DocumentRowSummary, DocumentSummary, EnvFileVariable, StoredDocumentKind, StoredDocumentState, StructuredDocumentMap, StructuredDocumentShape, StructuredDocumentText, ValidatedDocumentFields, } from "./data/documents/index.js";
7
7
  export { addDocumentAttachments, createDocumentProjectorRegistry, createDocumentSignerDeviceId, DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, defaultDocumentProjectorRegistry, deriveStoredDocumentTitle, ENV_FILE_DOCUMENT_KIND, ENV_FILE_NAME_FIELD, ENV_FILE_VARIABLE_KEY_FIELD, ENV_FILE_VARIABLE_NAME_PATTERN, ENV_FILE_VARIABLE_VALUE_FIELD, ensureDocumentAttachmentStructure, getDocumentAttachments, getDocumentClientProjectionTables, getStoredDocumentTypeLabel, getUntitledDocumentTitle, initializeStoredDocumentKind, isValidEnvFileVariableName, parseEnvFileText, projectStoredDocumentState, readStoredDocumentState, readStringDocumentField, resolveOpIdAttribution, sameDocumentAttachments, summarizeDocumentContributors, writerByPeerId, writeStoredDocumentFields, } from "./data/documents/index.js";
@@ -14,11 +14,11 @@ export type { TearleadsDatabaseOptions, TearleadsOptions, } from "./TearleadsOpt
14
14
  export type { BlobAttachmentCollaborators, BlobAttachmentServiceApi, BlobByteSource, BlobByteSourceInput, BlobBytes, BlobStore, DecryptDocumentAttachmentBlobRequest, DetachDocumentAttachmentRequest, DetachDocumentAttachmentResult, EncryptedBlobStoreCipher, EncryptedBlobStoreKey, EncryptedBlobStoreOptions, HydrateDocumentAttachmentBlobsRequest, HydratedDocumentAttachmentBlob, UploadDocumentAttachmentRequest, UploadDocumentAttachmentResult, WrapEncryptedBlobStoreOptions, } from "./workflows/blobs/index.js";
15
15
  export { BlobAttachmentService, blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, purgeOpfsBlobStore, readBlobByteSource, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
16
16
  export type { ContainerContentsRootAdopter, ContainerContentsRootAdoptionInput, ContainerContentsStoreWorkflowRuntime, ContainerContentsWorkflowRuntime, ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput, ContainerSystemSlotDefinition, PendingDownloadQueueItem, RecoveryFolder, } from "./workflows/container-contents/index.js";
17
- export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsSyncLane, createContainerParentSyncLane, createInitializedContainerMetadataDocument, DocumentContainerProjectionRepository, defaultContainerContentsPersistence, deriveContainerSystemSlot, listBlobInfo, loadContainerInfo, loadDocumentAttributionRanges, loadDocumentInfo, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
17
+ export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsSyncLane, createContainerParentSyncLane, createDocumentHeadLinkSetLoader, createInitializedContainerMetadataDocument, DocumentContainerProjectionRepository, defaultContainerContentsPersistence, deriveContainerSystemSlot, listBlobInfo, loadContainerInfo, loadDocumentAttributionRanges, loadDocumentInfo, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
18
18
  export type { AggregatedContainerKekLog, ContainerMutationAuthor, ContainerMutationCollaborators, ContainerReciteApi, ContainerWriteRefusal, KeyringRebuildResult, MaterializedContainerRekeyPlan, } from "./workflows/containers/index.js";
19
19
  export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerMutationService, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, fetchContainerKekLog, HistoricalWrapUnavailableError, type HistoricalWrapUnavailableReason, isProjectionVerificationCancelledError, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rootContainerWriterProjectionFromCreatePlan, } from "./workflows/containers/index.js";
20
20
  export type { CreateRemoteDocumentRequest, CreateRemoteDocumentResult, DocumentBirthResult, DocumentRecord, DocumentSyncContainerRekeyBuilder, DocumentSyncPullContinuation, DocumentSyncUpdateIsolationError, DocumentsPersistence, DocumentsWorkflowRuntime, IncomingDocumentSyncUpdateValidator, LocalAttachmentRecord, PendingAttachmentRecord, PendingUpdateInsert, PendingUpdateRecord, QueuedPendingUpdateRecord, RemoteDocumentServiceApi, SyncRemoteDocumentRequest, SyncRemoteDocumentResult, } from "./workflows/documents/index.js";
21
- export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, isEmptyDocumentHistoryChange, persistedDocumentCreateStateFromResponse, RemoteDocumentService, readPullContinuation, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
21
+ export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, isEmptyDocumentHistoryChange, persistedDocumentCreateStateFromResponse, RemoteDocumentService, readPullContinuation, resolveDocumentCreateAuthor, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
22
22
  export type { AcknowledgedPrincipalCurrentInput, AcknowledgedPrincipalCurrentRetirement, AuthoredPrincipalMutation, OrganizationDocumentUsageCategory, OrganizationGroupPolicyHistoryEntry, OrganizationNativePurchaseEligibility, OrganizationPrincipalMemberChange, OrganizationPrincipalMemberChangeType, OrganizationPrincipalPolicyHistory, OrganizationPrincipalPolicyHistoryEntry, PrincipalMutationJournalContext, PrincipalMutationJournalScope, PrincipalMutationResponse, ReconcileOrganizationDataUsageInput, } from "./workflows/organizations/index.js";
23
23
  export { abandonJournaledPrincipalMutation, addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, buildOrganizationGroupPolicyHistory, buildOrganizationProfileDocumentPatch, buildRosterProfileDocumentPatch, checkNativePurchaseEligibility, createInitializedRosterProfileDocument, createOrganizationGroup, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, discardUnreadableJournaledPrincipalMutation, GroupMembershipNameMismatchError, GroupShareNameMismatchError, getOrganizationProfileDocumentLocalId, getRosterProfileDocumentLocalId, loadLocalOrganizationDataUsage, loadLocalOrganizationDirectoryAndGroups, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, ORGANIZATION_DOCUMENT_USAGE_CATEGORIES, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_PROFILE_DOCUMENT_KIND, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, PendingPrincipalMutationError, PrincipalMutationOutcomeUnknownError, ROSTER_PROFILE_DOCUMENT_KIND, readJournaledPrincipalMutation, readOrganizationProfileName, reconcileOrganizationDataUsage, reconcileOrganizationDirectoryAndGroups, recoverJournaledPrincipalMutation, removeOrganizationGroupUser, resolveOrganizationBillingView, retainAcknowledgedPrincipalCurrents, revokeOrganizationContainerGrant, shareRemoteContainerWithGroup, startOrganizationTrial, submitJournaledPrincipalMutation, subscribeOrganizationReadModelInvalidation, UnreadablePrincipalMutationError, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./workflows/organizations/index.js";
24
24
  export type { AcknowledgedPrincipalPredecessor, CacheReferencedPrincipalPoliciesOptions, PrincipalHistoryProtectionLease, PrincipalPolicyService, ProjectionPolicyHistoryRecoveryOptions, RecoveredPrincipalPolicyHistory, RecoveredScopedPrincipalPolicyHistory, RecoverPrincipalPolicyHistoryOptions, RecoverScopedPrincipalPolicyHistoryOptions, } from "./workflows/principals/index.js";
package/index.js CHANGED
@@ -8,9 +8,9 @@ export { createContainerContentsStore, createContainerContentsStoreState, create
8
8
  export { createDocumentStore, discardRegisteredDocumentLocalState, getOrCreateDocumentStore, hasPendingLocalDocumentWrites, openDocumentStore, requestDomainDocumentSync, subscribeToPersistedDocuments, } from "./stores/documents/index.js";
9
9
  export { Tearleads } from "./Tearleads.js";
10
10
  export { BlobAttachmentService, blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, purgeOpfsBlobStore, readBlobByteSource, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
11
- export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsSyncLane, createContainerParentSyncLane, createInitializedContainerMetadataDocument, DocumentContainerProjectionRepository, defaultContainerContentsPersistence, deriveContainerSystemSlot, listBlobInfo, loadContainerInfo, loadDocumentAttributionRanges, loadDocumentInfo, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
11
+ export { ContainerSyncWatermarkRepository, createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsSyncLane, createContainerParentSyncLane, createDocumentHeadLinkSetLoader, createInitializedContainerMetadataDocument, DocumentContainerProjectionRepository, defaultContainerContentsPersistence, deriveContainerSystemSlot, listBlobInfo, loadContainerInfo, loadDocumentAttributionRanges, loadDocumentInfo, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
12
12
  export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerMutationService, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, fetchContainerKekLog, HistoricalWrapUnavailableError, isProjectionVerificationCancelledError, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rootContainerWriterProjectionFromCreatePlan, } from "./workflows/containers/index.js";
13
- export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, isEmptyDocumentHistoryChange, persistedDocumentCreateStateFromResponse, RemoteDocumentService, readPullContinuation, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
13
+ export { buildMaterializedDocumentCreatePlan, createDocumentProjectionUserKeyResolver, DOCUMENT_SYNC_TRACE_FRAGMENT, DOCUMENT_SYNC_TRACE_PATTERN, DOCUMENTS_APP_KIND, DocumentRawHistoryUnavailableError, defaultDocumentsPersistence, deletePersistedDocument, deriveStableDocumentId, isDatabaseUnavailableError, isDocumentSyncUpdateIsolationError, isEmptyDocumentHistoryChange, persistedDocumentCreateStateFromResponse, RemoteDocumentService, readPullContinuation, resolveDocumentCreateAuthor, unwrapContainerKekPath, unwrapDocumentContentKeyTarget, validateDocumentSyncUpdateImports, } from "./workflows/documents/index.js";
14
14
  export { abandonJournaledPrincipalMutation, addOrganizationGroupUser, buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, buildOrganizationGroupPolicyHistory, buildOrganizationProfileDocumentPatch, buildRosterProfileDocumentPatch, checkNativePurchaseEligibility, createInitializedRosterProfileDocument, createOrganizationGroup, DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME, deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, discardUnreadableJournaledPrincipalMutation, GroupMembershipNameMismatchError, GroupShareNameMismatchError, getOrganizationProfileDocumentLocalId, getRosterProfileDocumentLocalId, loadLocalOrganizationDataUsage, loadLocalOrganizationDirectoryAndGroups, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, ORGANIZATION_DOCUMENT_USAGE_CATEGORIES, ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_PROFILE_DOCUMENT_KIND, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, PendingPrincipalMutationError, PrincipalMutationOutcomeUnknownError, ROSTER_PROFILE_DOCUMENT_KIND, readJournaledPrincipalMutation, readOrganizationProfileName, reconcileOrganizationDataUsage, reconcileOrganizationDirectoryAndGroups, recoverJournaledPrincipalMutation, removeOrganizationGroupUser, resolveOrganizationBillingView, retainAcknowledgedPrincipalCurrents, revokeOrganizationContainerGrant, shareRemoteContainerWithGroup, startOrganizationTrial, submitJournaledPrincipalMutation, subscribeOrganizationReadModelInvalidation, UnreadablePrincipalMutationError, updateOrganizationProfile, updateOrganizationRosterEntry, } from "./workflows/organizations/index.js";
15
15
  export { cacheReferencedPrincipalPolicies, captureAcknowledgedPrincipalPredecessor, PrincipalPolicyHistoryReadError, recoverPrincipalPolicyHistory, recoverProjectionPolicyHistory, recoverScopedPrincipalPolicyHistory, } from "./workflows/principals/index.js";
16
16
  export { bootstrapRootContainer, buildInitialOrganizationPolicyRequest, createInitialRootMetadataBootstrap, deriveRegistrationOrganizationId, persistRegistrationBootstrap, registerIdentity, } from "./workflows/registration/index.js";
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,yEAAyE;AACzE,gEAAgE;AAChE,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAiL/B,OAAO,EAEL,KAAK,EACL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,2CAA2C,EAC3C,sCAAsC,EACtC,sCAAsC,EACtC,8BAA8B,EAC9B,iBAAiB,EACjB,wCAAwC,EACxC,k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,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: full-bundle identity trust and bounded Members admission.\n// Exact-head authority; canonical writer domains; restart-safe journals.\n// No pin promotion or legacy adapters. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DocumentsWorkflowRuntimeInput,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDeviceDataUsage,\n OrganizationDeviceDocumentUsageCategoryBreakdown,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupMutationResult,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationMemberships,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n createContainerDocumentObjectSyncState,\n createDocumentsWorkflowRuntime,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n UnverifiedUserIdentityError,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRestoreContent,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n EnvFileVariable,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ENV_FILE_DOCUMENT_KIND,\n ENV_FILE_NAME_FIELD,\n ENV_FILE_VARIABLE_KEY_FIELD,\n ENV_FILE_VARIABLE_NAME_PATTERN,\n ENV_FILE_VARIABLE_VALUE_FIELD,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n isValidEnvFileVariableName,\n parseEnvFileText,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeMoveSettlement,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentMutationGuard,\n DocumentMutationOptions,\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n hasPendingLocalDocumentWrites,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport { Tearleads } from \"./Tearleads\";\nexport type {\n TearleadsDatabaseOptions,\n TearleadsOptions,\n} from \"./TearleadsOptions\";\nexport type {\n BlobAttachmentCollaborators,\n BlobAttachmentServiceApi,\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n DecryptDocumentAttachmentBlobRequest,\n DetachDocumentAttachmentRequest,\n DetachDocumentAttachmentResult,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n HydrateDocumentAttachmentBlobsRequest,\n HydratedDocumentAttachmentBlob,\n UploadDocumentAttachmentRequest,\n UploadDocumentAttachmentResult,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n BlobAttachmentService,\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n purgeOpfsBlobStore,\n readBlobByteSource,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n ContainerSyncWatermarkRepository,\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n DocumentContainerProjectionRepository,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n listBlobInfo,\n loadContainerInfo,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerMutationCollaborators,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerMutationService,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n fetchContainerKekLog,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"./workflows/containers\";\nexport type {\n CreateRemoteDocumentRequest,\n CreateRemoteDocumentResult,\n DocumentBirthResult,\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n QueuedPendingUpdateRecord,\n RemoteDocumentServiceApi,\n SyncRemoteDocumentRequest,\n SyncRemoteDocumentResult,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n deriveStableDocumentId,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n isEmptyDocumentHistoryChange,\n persistedDocumentCreateStateFromResponse,\n RemoteDocumentService,\n readPullContinuation,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationDocumentUsageCategory,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n GroupShareNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n shareRemoteContainerWithGroup,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n PrincipalPolicyService,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n deriveRegistrationOrganizationId,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n PendingBlobDeletion,\n PendingBlobDeletionsPage,\n PendingBlobDeletionsQueryInput,\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootPendingBlobDeletionsQueryInput,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n liftRootIdentitySuspension,\n listRootAuditEvents,\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizationRevenuecatEvents,\n listRootOrganizations,\n listRootRevenuecatEventsReport,\n loadRootIdentity,\n loadRootOpsHealthReport,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootAuditApi,\n type RootAuditEvent,\n type RootAuditEventsPage,\n type RootAuditEventsQueryInput,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOpsHealthApi,\n type RootOpsHealthReport,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationRevenuecatEvent,\n type RootOrganizationRevenuecatEventsPage,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRevenuecatApi,\n type RootRevenuecatEvent,\n type RootRevenuecatEventsQueryInput,\n type RootRevenuecatEventsReportPage,\n type RootRevenuecatEventsReportQueryInput,\n type RootSuspensionApi,\n suspendRootIdentity,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,yEAAyE;AACzE,gEAAgE;AAChE,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAkL/B,OAAO,EAEL,KAAK,EACL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,2CAA2C,EAC3C,sCAAsC,EACtC,sCAAsC,EACtC,8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EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: full-bundle identity trust and bounded Members admission.\n// Exact-head authority; canonical writer domains; restart-safe journals.\n// No pin promotion or legacy adapters. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentHistory,\n DocumentHistoryChange,\n DocumentHistoryRowChange,\n DocumentHistoryStop,\n DocumentHistoryTextChange,\n DocumentHistoryVersion,\n DocumentHistoryVersionEntry,\n DocumentHistoryView,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DocumentsWorkflowRuntimeInput,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDeviceDataUsage,\n OrganizationDeviceDocumentUsageCategoryBreakdown,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupMutationResult,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationLeaveRequestResult,\n OrganizationMembership,\n OrganizationMemberships,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n OrganizationSyncPauseResult,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n SeededDocumentInput,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n createContainerDocumentObjectSyncState,\n createDocumentsWorkflowRuntime,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n UnverifiedUserIdentityError,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRestoreContent,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n EnvFileVariable,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ENV_FILE_DOCUMENT_KIND,\n ENV_FILE_NAME_FIELD,\n ENV_FILE_VARIABLE_KEY_FIELD,\n ENV_FILE_VARIABLE_NAME_PATTERN,\n ENV_FILE_VARIABLE_VALUE_FIELD,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n isValidEnvFileVariableName,\n parseEnvFileText,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeMoveSettlement,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentMutationGuard,\n DocumentMutationOptions,\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n hasPendingLocalDocumentWrites,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport { Tearleads } from \"./Tearleads\";\nexport type {\n TearleadsDatabaseOptions,\n TearleadsOptions,\n} from \"./TearleadsOptions\";\nexport type {\n BlobAttachmentCollaborators,\n BlobAttachmentServiceApi,\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n DecryptDocumentAttachmentBlobRequest,\n DetachDocumentAttachmentRequest,\n DetachDocumentAttachmentResult,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n HydrateDocumentAttachmentBlobsRequest,\n HydratedDocumentAttachmentBlob,\n UploadDocumentAttachmentRequest,\n UploadDocumentAttachmentResult,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n BlobAttachmentService,\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n purgeOpfsBlobStore,\n readBlobByteSource,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n ContainerSyncWatermarkRepository,\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n createDocumentHeadLinkSetLoader,\n createInitializedContainerMetadataDocument,\n DocumentContainerProjectionRepository,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n listBlobInfo,\n loadContainerInfo,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerMutationCollaborators,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerMutationService,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n fetchContainerKekLog,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rootContainerWriterProjectionFromCreatePlan,\n} from \"./workflows/containers\";\nexport type {\n CreateRemoteDocumentRequest,\n CreateRemoteDocumentResult,\n DocumentBirthResult,\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n QueuedPendingUpdateRecord,\n RemoteDocumentServiceApi,\n SyncRemoteDocumentRequest,\n SyncRemoteDocumentResult,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n deriveStableDocumentId,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n isEmptyDocumentHistoryChange,\n persistedDocumentCreateStateFromResponse,\n RemoteDocumentService,\n readPullContinuation,\n resolveDocumentCreateAuthor,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationDocumentUsageCategory,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n GroupShareNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_DOCUMENT_USAGE_CATEGORIES,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n shareRemoteContainerWithGroup,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n PrincipalPolicyService,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n deriveRegistrationOrganizationId,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n PendingBlobDeletion,\n PendingBlobDeletionsPage,\n PendingBlobDeletionsQueryInput,\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootPendingBlobDeletionsQueryInput,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n liftRootIdentitySuspension,\n listRootAuditEvents,\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizationRevenuecatEvents,\n listRootOrganizations,\n listRootRevenuecatEventsReport,\n loadRootIdentity,\n loadRootOpsHealthReport,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootAuditApi,\n type RootAuditEvent,\n type RootAuditEventsPage,\n type RootAuditEventsQueryInput,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOpsHealthApi,\n type RootOpsHealthReport,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationRevenuecatEvent,\n type RootOrganizationRevenuecatEventsPage,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRevenuecatApi,\n type RootRevenuecatEvent,\n type RootRevenuecatEventsQueryInput,\n type RootRevenuecatEventsReportPage,\n type RootRevenuecatEventsReportQueryInput,\n type RootSuspensionApi,\n suspendRootIdentity,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
@@ -2824,7 +2824,7 @@ export declare class ApiClient extends ApiClientAreas {
2824
2824
  acceptedOutgoingUpdateIds: string[];
2825
2825
  } | null>;
2826
2826
  syncDocumentResult: (documentId: string, input: import("../validators/request/index.js").DocumentSyncRequest, options?: import("./types.js").RequestResultOptions) => Promise<import("./types.js").RequestResult<import("../validators/response/index.js").DocumentSyncResponse>>;
2827
- initiateMultipartBlobStage: (input: import("../validators/request/index.js").InitiateMultipartBlobStageRequest) => Promise<{
2827
+ initiateMultipartBlobStage: (input: import("../validators/request/index.js").InitiateMultipartBlobStageRequest, options?: import("./types.js").RequestResultOptions) => Promise<{
2828
2828
  organizationId: string;
2829
2829
  byteLength: number;
2830
2830
  expiresAt: string;
@@ -2849,7 +2849,7 @@ export declare class ApiClient extends ApiClientAreas {
2849
2849
  }[];
2850
2850
  uploadId: string;
2851
2851
  } | null>;
2852
- getMultipartBlobStage: (stageId: string) => Promise<{
2852
+ getMultipartBlobStage: (stageId: string, options?: import("./types.js").RequestResultOptions) => Promise<{
2853
2853
  organizationId: string;
2854
2854
  byteLength: number;
2855
2855
  completed: boolean;
@@ -5,7 +5,7 @@ import { bindPrototypeMethods, describeErrorResponse, isSuccessfulResponse, norm
5
5
  import { shouldRetryAfterSessionExpired } from "./sessionRefresh.js";
6
6
  import { SessionRenewalTracker, sessionAuthChallengeBytes, } from "./sessionRenewal.js";
7
7
  import { sessionRequestInit } from "./sessionRequestInit.js";
8
- import { readSessionJson, retiredRequest } from "./sessionResponse.js";
8
+ import { readSessionJson, requestRetired, retiredRequest, } from "./sessionResponse.js";
9
9
  export class ApiRequestRuntime {
10
10
  instrumentation;
11
11
  authToken = null;
@@ -130,7 +130,7 @@ export class ApiRequestRuntime {
130
130
  const response = responseResult.data;
131
131
  const reportErrors = options?.reportErrors ?? true;
132
132
  const decoded = await readSessionJson(this.responseRequest, response, method, path, options ?? {}, session);
133
- if (session.aborted)
133
+ if (requestRetired(session, options))
134
134
  return retiredRequest(method, path);
135
135
  if (!decoded.ok)
136
136
  return decoded;
@@ -157,7 +157,7 @@ export class ApiRequestRuntime {
157
157
  const result = await this.fetchResponseRequest(path, method, body, options, authToken, failureOperation, attempt);
158
158
  if (!result.ok)
159
159
  return result;
160
- if (session.aborted)
160
+ if (requestRetired(session, options))
161
161
  return this.retiredResponse(session, method, path, result.data);
162
162
  const response = result.data;
163
163
  if (isSuccessfulResponse(response, additionalSuccessStatuses)) {
@@ -166,7 +166,7 @@ export class ApiRequestRuntime {
166
166
  }
167
167
  const errorDescription = await describeErrorResponse(response, failureOperation, options.expectedPaymentRequiredOrganizationId);
168
168
  const retired = () => this.retiredResponse(session, method, path, response, errorDescription.code);
169
- if (session.aborted)
169
+ if (requestRetired(session, options))
170
170
  return retired();
171
171
  const failure = {
172
172
  errorDescription,
@@ -192,7 +192,7 @@ export class ApiRequestRuntime {
192
192
  reportError: (message) => this.onError?.(message),
193
193
  responseStatus: response.status,
194
194
  });
195
- if (session.aborted)
195
+ if (requestRetired(session, options))
196
196
  return retired();
197
197
  const retryToken = this.sessionRenewals.currentToken(authToken);
198
198
  if (!shouldRetry || !retryToken)
@@ -225,6 +225,8 @@ export class ApiRequestRuntime {
225
225
  /** 2 is the retry after a session renewal. */
226
226
  attempt = 1) {
227
227
  const session = this.sessionRenewals.signal;
228
+ if (options.stillCurrent?.() === false)
229
+ return retiredRequest(method, path);
228
230
  const reportErrors = options.reportErrors ?? true;
229
231
  const { headers, init } = sessionRequestInit(method, body, options, authToken);
230
232
  let response;
@@ -233,7 +235,7 @@ export class ApiRequestRuntime {
233
235
  response = await measureApiRequest(this.instrumentation, operation, () => fetch(`${this.baseUrl}${path}`, init), options.signal);
234
236
  }
235
237
  catch (error) {
236
- if (session.aborted)
238
+ if (requestRetired(session, options))
237
239
  return retiredRequest(method, path);
238
240
  const { cancelled, networkError } = await settleNetworkFailure({
239
241
  attempt,
@@ -249,7 +251,7 @@ export class ApiRequestRuntime {
249
251
  signal: options.signal,
250
252
  onNetworkFailure: (failure) => this.onNetworkFailure?.(failure),
251
253
  });
252
- if (session.aborted)
254
+ if (requestRetired(session, options))
253
255
  return retiredRequest(method, path);
254
256
  return this.requestFailure({
255
257
  ...(cancelled ? { code: "request_aborted" } : {}),
@@ -264,7 +266,7 @@ export class ApiRequestRuntime {
264
266
  statusText: "",
265
267
  });
266
268
  }
267
- if (session.aborted)
269
+ if (requestRetired(session, options))
268
270
  return this.retiredResponse(session, method, path, response);
269
271
  this.onNetworkSuccess?.();
270
272
  const apiVersion = parseApiVersion(response.headers.get(apiVersionHeaderName));
@@ -301,6 +303,8 @@ export class ApiRequestRuntime {
301
303
  });
302
304
  }
303
305
  reportResponseRequestFailure(input) {
306
+ if (input.options?.stillCurrent?.() === false)
307
+ return retiredRequest(input.method, input.path);
304
308
  if (input.kind === "network") {
305
309
  this.onNetworkError?.();
306
310
  }