@tearleads/client-sdk 0.1.256 → 0.1.258

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 (100) 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/sqlite/worker.js +4 -4
  51. package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
  52. package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
  53. package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
  54. package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
  55. package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
  56. package/stores/documents/documentStore/state.js +3 -1
  57. package/stores/documents/documentStore/state.js.map +1 -1
  58. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  59. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  60. package/stores/documents/index.d.ts +1 -0
  61. package/stores/documents/index.js +1 -0
  62. package/stores/documents/index.js.map +1 -1
  63. package/stores/documents/types.d.ts +1 -0
  64. package/stores/documents/types.js.map +1 -1
  65. package/workflows/blobs/upload/index.d.ts +1 -1
  66. package/workflows/blobs/upload/index.js +36 -18
  67. package/workflows/blobs/upload/index.js.map +1 -1
  68. package/workflows/blobs/upload/multipartStageResolution.js +12 -2
  69. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
  70. package/workflows/blobs/upload/multipartUpload.js +10 -2
  71. package/workflows/blobs/upload/multipartUpload.js.map +1 -1
  72. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
  73. package/workflows/container-contents/documentQueries/index.d.ts +1 -1
  74. package/workflows/container-contents/documentQueries/index.js +2 -2
  75. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  76. package/workflows/container-contents/index.d.ts +1 -0
  77. package/workflows/container-contents/index.js +1 -0
  78. package/workflows/container-contents/index.js.map +1 -1
  79. package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
  80. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
  81. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  82. package/workflows/documents/create/createAdoption.js +2 -50
  83. package/workflows/documents/create/createAdoption.js.map +1 -1
  84. package/workflows/documents/create/createResponse.js +12 -1
  85. package/workflows/documents/create/createResponse.js.map +1 -1
  86. package/workflows/documents/create/createSubmission.js +14 -0
  87. package/workflows/documents/create/createSubmission.js.map +1 -0
  88. package/workflows/documents/create/index.d.ts +3 -14
  89. package/workflows/documents/create/index.js +76 -67
  90. package/workflows/documents/create/index.js.map +1 -1
  91. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
  92. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
  93. package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
  94. package/workflows/documents/purge/absentDocumentPurge.js +23 -0
  95. package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
  96. package/workflows/documents/purge/index.d.ts +1 -0
  97. package/workflows/documents/purge/index.js +1 -0
  98. package/workflows/documents/purge/index.js.map +1 -1
  99. package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
  100. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
@@ -5,18 +5,13 @@ import type { PendingUpdateRecord } from "../../../data/persistence/documents/re
5
5
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
6
6
  import type { DocumentCreateTerminalFailureHandler } from "./createProjectionFetch.js";
7
7
  /** What one `RemoteDocumentService.createRemoteDocument` call varies. */
8
- export interface CreateRemoteDocumentRequest {
8
+ interface DocumentCreateOptions {
9
9
  author: DocumentCreateAuthor;
10
+ onRecoveredStaleTarget?: (() => void) | undefined;
10
11
  containerId: string;
11
12
  containerProjection?: ContainerWriterProjectionResponse | undefined;
12
13
  contentKey?: Uint8Array | undefined;
13
14
  contentKeyEpoch?: number | undefined;
14
- /**
15
- * The queued row holding the new document's whole content when its first
16
- * attachment must bind before it: the create does not send it but returns
17
- * it signed as `deferredSeed`, for that bind to carry.
18
- */
19
- deferredSeedUpdate?: PendingUpdateRecord | undefined;
20
15
  documentId?: string | undefined;
21
16
  eventId?: string | undefined;
22
17
  expectedOrganizationId?: string | undefined;
@@ -28,20 +23,26 @@ export interface CreateRemoteDocumentRequest {
28
23
  */
29
24
  onTerminalSubmitFailure?: DocumentCreateTerminalFailureHandler | undefined;
30
25
  resolveProjectionUserKey: ProjectionUserKeyResolver;
31
- /**
32
- * The queued row holding the new document's whole content (see
33
- * `documentCreateSeedCandidate`). The create commits it as its seed, and the
34
- * caller settles the row from the response instead of syncing it.
35
- */
36
- seedUpdate?: PendingUpdateRecord | undefined;
37
26
  signedAt?: string | undefined;
38
27
  stillCurrent?: (() => boolean) | undefined;
39
28
  warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
40
29
  }
30
+ /** Existing ordinary create options, including a queued birth or a deferred attachment birth. */
31
+ export interface CreateRemoteDocumentRequest extends DocumentCreateOptions {
32
+ requireSeededCreate?: false | undefined;
33
+ seedUpdate?: PendingUpdateRecord | undefined;
34
+ deferredSeedUpdate?: PendingUpdateRecord | undefined;
35
+ }
36
+ export type DocumentSubmissionRequest = CreateRemoteDocumentRequest | (DocumentCreateOptions & {
37
+ requireSeededCreate: true;
38
+ seedUpdate: PendingUpdateRecord;
39
+ deferredSeedUpdate?: undefined;
40
+ });
41
41
  /** One create call's request joined with the service's collaborators. */
42
- export interface RemoteDocumentCreateInput extends CreateRemoteDocumentRequest {
42
+ export type RemoteDocumentCreateInput = DocumentSubmissionRequest & {
43
43
  apiClient: DocumentCreateApi;
44
44
  execSql: ExecSql;
45
45
  isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;
46
46
  targetSecretKey: Uint8Array;
47
- }
47
+ };
48
+ export {};
@@ -1 +1 @@
1
- {"version":3,"file":"remoteDocumentCreateRequest.js","sourceRoot":"","sources":["remoteDocumentCreateRequest.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type {\n DocumentCreateApi,\n DocumentCreateAuthor,\n} from \"../../../data/documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DocumentCreateTerminalFailureHandler } from \"./createProjectionFetch\";\n\n/** What one `RemoteDocumentService.createRemoteDocument` call varies. */\nexport interface CreateRemoteDocumentRequest {\n author: DocumentCreateAuthor;\n containerId: string;\n containerProjection?: ContainerWriterProjectionResponse | undefined;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n /**\n * The queued row holding the new document's whole content when its first\n * attachment must bind before it: the create does not send it but returns\n * it signed as `deferredSeed`, for that bind to carry.\n */\n deferredSeedUpdate?: PendingUpdateRecord | undefined;\n documentId?: string | undefined;\n eventId?: string | undefined;\n expectedOrganizationId?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n /**\n * Invoked when the create submission fails terminally (not a benign\n * adopt/stale-target conflict) — e.g. the server denies the write. Callers\n * persist the failure so the write queue can surface it.\n */\n onTerminalSubmitFailure?: DocumentCreateTerminalFailureHandler | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n /**\n * The queued row holding the new document's whole content (see\n * `documentCreateSeedCandidate`). The create commits it as its seed, and the\n * caller settles the row from the response instead of syncing it.\n */\n seedUpdate?: PendingUpdateRecord | undefined;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\n/** One create call's request joined with the service's collaborators. */\nexport interface RemoteDocumentCreateInput extends CreateRemoteDocumentRequest {\n apiClient: DocumentCreateApi;\n execSql: ExecSql;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n targetSecretKey: Uint8Array;\n}\n"]}
1
+ {"version":3,"file":"remoteDocumentCreateRequest.js","sourceRoot":"","sources":["remoteDocumentCreateRequest.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type {\n DocumentCreateApi,\n DocumentCreateAuthor,\n} from \"../../../data/documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DocumentCreateTerminalFailureHandler } from \"./createProjectionFetch\";\n\n/** What one `RemoteDocumentService.createRemoteDocument` call varies. */\ninterface DocumentCreateOptions {\n author: DocumentCreateAuthor;\n onRecoveredStaleTarget?: (() => void) | undefined;\n containerId: string;\n containerProjection?: ContainerWriterProjectionResponse | undefined;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId?: string | undefined;\n eventId?: string | undefined;\n expectedOrganizationId?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n /**\n * Invoked when the create submission fails terminally (not a benign\n * adopt/stale-target conflict) — e.g. the server denies the write. Callers\n * persist the failure so the write queue can surface it.\n */\n onTerminalSubmitFailure?: DocumentCreateTerminalFailureHandler | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\n/** Existing ordinary create options, including a queued birth or a deferred attachment birth. */\nexport interface CreateRemoteDocumentRequest extends DocumentCreateOptions {\n requireSeededCreate?: false | undefined;\n seedUpdate?: PendingUpdateRecord | undefined;\n deferredSeedUpdate?: PendingUpdateRecord | undefined;\n}\n\nexport type DocumentSubmissionRequest =\n | CreateRemoteDocumentRequest\n | (DocumentCreateOptions & {\n requireSeededCreate: true;\n seedUpdate: PendingUpdateRecord;\n deferredSeedUpdate?: undefined;\n });\n\n/** One create call's request joined with the service's collaborators. */\nexport type RemoteDocumentCreateInput = DocumentSubmissionRequest & {\n apiClient: DocumentCreateApi;\n execSql: ExecSql;\n isRemoteSyncBlocked?: ((organizationId: string) => boolean) | undefined;\n targetSecretKey: Uint8Array;\n};\n"]}
@@ -0,0 +1,3 @@
1
+ import { type ExecSql } from "../../../data/sqlite/sqlSchema.js";
2
+ export declare function hasVerifiedDocumentPurge(execSql: ExecSql, documentId: string, organizationId: string): Promise<boolean>;
3
+ export declare function pinAbsentDocumentPurge(execSql: ExecSql, documentId: string, commitPurgeProof: (transaction: ExecSql) => Promise<void>): Promise<void>;
@@ -0,0 +1,23 @@
1
+ import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
2
+ import { getClientSQLitePersistenceRuntime } from "../../../data/sqlite/sqlitePersistenceRuntime.js";
3
+ import { runSerializedSqlMutation, } from "../../../data/sqlite/sqlSchema.js";
4
+ import { defaultDocumentsPersistence } from "../persistence.js";
5
+ export async function hasVerifiedDocumentPurge(execSql, documentId, organizationId) {
6
+ const checkpoint = await new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(documentId);
7
+ if (checkpoint && checkpoint.organizationId !== organizationId)
8
+ throw new Error("Purge checkpoint belongs to another organization.");
9
+ return checkpoint !== null;
10
+ }
11
+ export function pinAbsentDocumentPurge(execSql, documentId, commitPurgeProof) {
12
+ return runSerializedSqlMutation(execSql, async (locked) => {
13
+ await defaultDocumentsPersistence.ensureSchema(locked);
14
+ await getClientSQLitePersistenceRuntime(locked).transaction(async () => {
15
+ if (await defaultDocumentsPersistence.findLocalIdByDocumentId(locked, documentId)) {
16
+ // The document store pins its proof alongside generation-guarded teardown.
17
+ throw new Error("Sync the local document to apply its verified purge.");
18
+ }
19
+ await commitPurgeProof(locked);
20
+ });
21
+ });
22
+ }
23
+ //# sourceMappingURL=absentDocumentPurge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"absentDocumentPurge.js","sourceRoot":"","sources":["absentDocumentPurge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,iCAAiC,EAAE,MAAM,+CAA+C,CAAC;AAClG,OAAO,EAEL,wBAAwB,GACzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,gBAAgB,CAAC;AAE7D,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAgB,EAChB,UAAkB,EAClB,cAAsB;IAEtB,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,OAAO,CACR,CAAC,2BAA2B,CAAC,UAAU,CAAC,CAAC;IAC1C,IAAI,UAAU,IAAI,UAAU,CAAC,cAAc,KAAK,cAAc;QAC5D,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,OAAO,UAAU,KAAK,IAAI,CAAC;AAC7B,CAAC;AAED,MAAM,UAAU,sBAAsB,CACpC,OAAgB,EAChB,UAAkB,EAClB,gBAAyD;IAEzD,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;QACxD,MAAM,2BAA2B,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;QACvD,MAAM,iCAAiC,CAAC,MAAM,CAAC,CAAC,WAAW,CAAC,KAAK,IAAI,EAAE;YACrE,IACE,MAAM,2BAA2B,CAAC,uBAAuB,CACvD,MAAM,EACN,UAAU,CACX,EACD,CAAC;gBACD,2EAA2E;gBAC3E,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;YAC1E,CAAC;YACD,MAAM,gBAAgB,CAAC,MAAM,CAAC,CAAC;QACjC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n runSerializedSqlMutation,\n} from \"../../../data/sqlite/sqlSchema\";\nimport { defaultDocumentsPersistence } from \"../persistence\";\n\nexport async function hasVerifiedDocumentPurge(\n execSql: ExecSql,\n documentId: string,\n organizationId: string,\n) {\n const checkpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadDocumentPurgeCheckpoint(documentId);\n if (checkpoint && checkpoint.organizationId !== organizationId)\n throw new Error(\"Purge checkpoint belongs to another organization.\");\n return checkpoint !== null;\n}\n\nexport function pinAbsentDocumentPurge(\n execSql: ExecSql,\n documentId: string,\n commitPurgeProof: (transaction: ExecSql) => Promise<void>,\n) {\n return runSerializedSqlMutation(execSql, async (locked) => {\n await defaultDocumentsPersistence.ensureSchema(locked);\n await getClientSQLitePersistenceRuntime(locked).transaction(async () => {\n if (\n await defaultDocumentsPersistence.findLocalIdByDocumentId(\n locked,\n documentId,\n )\n ) {\n // The document store pins its proof alongside generation-guarded teardown.\n throw new Error(\"Sync the local document to apply its verified purge.\");\n }\n await commitPurgeProof(locked);\n });\n });\n}\n"]}
@@ -41,3 +41,4 @@ export declare function createVerifiedRemoteDocumentDeletionHandler(input: {
41
41
  readonly documentId: string;
42
42
  }) => Promise<void>;
43
43
  export declare function purgeRemoteDocument(remote: RemoteDocumentCollaborators, purge: PurgeRemoteDocumentRequest): Promise<DocumentPurgeResponse | null>;
44
+ export { hasVerifiedDocumentPurge, pinAbsentDocumentPurge, } from "./absentDocumentPurge.js";
@@ -212,4 +212,5 @@ export async function purgeRemoteDocument(remote, purge) {
212
212
  });
213
213
  return response;
214
214
  }
215
+ export { hasVerifiedDocumentPurge, pinAbsentDocumentPurge, } from "./absentDocumentPurge.js";
215
216
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAE1B,uBAAuB,EACvB,uBAAuB,EACvB,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,6BAA6B,GAI9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,iBAAiB,EACjB,0CAA0C,GAC3C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,sCAAsC,EACtC,uBAAuB,GACxB,MAAM,wCAAwC,CAAC;AAGhD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAKzE,OAAO,EACL,wBAAwB,EACxB,gCAAgC,EAChC,8BAA8B,GAC/B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAMlG,OAAO,EACL,sBAAsB,GAEvB,MAAM,qBAAqB,CAAC;AAkB7B,MAAM,8BAA8B,GAAG,MAAM,CAAC,6BAA6B,CAAC,CAAC;AAE7E,KAAK,UAAU,mCAAmC,CAAC,KAUlD;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,qBAAqB,EAAE,CAAC;QAC3C,MAAM,IAAI,oCAAoC,CAC5C,4DAA4D,CAC7D,CAAC;IACJ,CAAC;IACD,MAAM,YAAY,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,qBAAqB,CAC9D,KAAK,CAAC,UAAU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essEventBody,\n KeyingVerificationError,\n readKeyingCanonicalJson,\n signAccessEvent,\n type UnsignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeRequest } from \"@tearleads/validators/request\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentPurgeProofResponse,\n type DocumentPurgeResponse,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n containerPathRefs,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport {\n assertDocumentManifestBundleConsistent,\n readManifestContainerId,\n} from \"../../../data/documents/shared/readers\";\nimport type { DocumentSyncApi } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type { DocumentCreateAuthor } from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n verifyDocumentWriterProjection,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { openPrincipalPolicyBundleReader } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n DocumentPurgeApi,\n RemoteDocumentCollaborators,\n} from \"../remote/remoteDocumentCollaborators\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"./subtreePurgeScope\";\n\n/** What varies per purge; the collaborators bind the rest. */\nexport interface PurgeRemoteDocumentRequest {\n readonly beforeSubmit?: (() => Promise<boolean>) | undefined;\n readonly author: DocumentCreateAuthor;\n readonly documentId: string;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly onVerifiedPurge: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nconst REMOTE_DOCUMENT_ALREADY_PURGED = Symbol(\"remoteDocumentAlreadyPurged\");\n\nasync function loadAuthenticatedDocumentPurgeProof(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeProofResponse | null> {\n if (!input.apiClient.getDocumentPurgeProof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing a purge-proof endpoint\",\n );\n }\n const initialProof = await input.apiClient.getDocumentPurgeProof(\n input.documentId,\n undefined,\n {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n },\n );\n if (!initialProof) {\n // ApiClient returns null for transport, HTTP and response-shape failures.\n // Even after a deletion hint, absence cannot prove signed-data tampering.\n // Keep local data and defer deletion until an actual proof verifies.\n return null;\n }\n await verifyDocumentPurgeProofBaseline({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof: initialProof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The current API returns complete history to recorded readers. Otherwise\n // its terminal snapshot needs an exact local pin; a floor refetch cannot\n // grant missing observation authority.\n return initialProof;\n}\n\nasync function resolveDocumentPurgeWriterProjection(input: {\n readonly apiClient: DocumentPurgeApi;\n readonly documentId: string;\n}): Promise<\n | DocumentWriterProjectionResponse\n | typeof REMOTE_DOCUMENT_ALREADY_PURGED\n | null\n> {\n const result = await input.apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n if (result.status === 404 && result.code === DOCUMENT_NOT_FOUND_ERROR_CODE) {\n return REMOTE_DOCUMENT_ALREADY_PURGED;\n }\n result.report();\n return null;\n}\n\nexport async function buildDocumentPurgeRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly eventId?: string | undefined;\n readonly signedAt?: string | undefined;\n readonly writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentPurgeRequest> {\n const identity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document purge predecessor\",\n });\n if (identity.documentId !== input.writerProjection.documentId) {\n throw new Error(\"Document purge projection identity mismatch\");\n }\n if (identity.organizationId !== input.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge author organization mismatch\",\n );\n }\n const linkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n if (linkedContainerIds.length !== 1) {\n throw new Error(\"Document purge requires exactly one linked container\");\n }\n const [containerId] = linkedContainerIds;\n const authorizingProjection = documentContainerProjections(\n input.writerProjection,\n ).find((projection) => {\n const leaf = projection.path.at(-1);\n return leaf && readManifestContainerId(leaf) === containerId;\n });\n const containerManifestHash =\n authorizingProjection?.path.at(-1)?.manifestHash;\n if (!authorizingProjection || !containerId || !containerManifestHash) {\n throw new Error(\"Document purge authorization path is unavailable\");\n }\n assertSubtreePurgePath(authorizingProjection.path, input.expectedSubtreeRoot);\n const authorizingContainerManifestHashes = authorizingProjection.path.map(\n (bundle) => bundle.manifestHash,\n );\n const body: DocumentPurgeAccessEventBody = {\n authorizingContainerManifestHashes,\n containerId,\n containerManifestHash,\n documentManifestHash: input.writerProjection.documentManifest.manifestHash,\n eventType: \"document.purge\",\n };\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId ?? crypto.randomUUID(),\n eventType: \"document.purge\",\n objectKind: \"document\",\n objectId: input.writerProjection.documentId,\n organizationId: input.author.organizationId,\n previousManifestHash: input.writerProjection.documentManifest.manifestHash,\n dependencyManifestHashes: authorizingContainerManifestHashes,\n bodyHash: await computeAccessEventBodyHash(\n readKeyingCanonicalJson(body, \"Document purge body\"),\n ),\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt ?? new Date().toISOString(),\n };\n const event = await signAccessEvent(\n unsignedEvent,\n input.author.signerPrivateKey,\n );\n\n return {\n authorizingContainerPathRefs: containerPathRefs(authorizingProjection.path),\n body: readCanonicalRecord(body, \"Document purge body\"),\n event: readCanonicalRecord(event, \"Document purge event\"),\n };\n}\n\nexport function createVerifiedRemoteDocumentDeletionHandler(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly onVerifiedDeletion: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n readonly documentId: string;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): (deleted: { readonly documentId: string }) => Promise<void> {\n return async ({ documentId }) => {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedDeletion({\n commitPurgeProof: verified.commitCheckpoints,\n documentId,\n });\n };\n}\n\nexport async function purgeRemoteDocument(\n remote: RemoteDocumentCollaborators,\n purge: PurgeRemoteDocumentRequest,\n): Promise<DocumentPurgeResponse | null> {\n const input = {\n ...purge,\n apiClient: remote.api,\n execSql: remote.execSql,\n };\n const writerProjection = await resolveDocumentPurgeWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n });\n if (!writerProjection) {\n return null;\n }\n if (writerProjection === REMOTE_DOCUMENT_ALREADY_PURGED) {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId: input.documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Purged remote document is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return { ...proof, reclaimedBlobStorageKeys: [] };\n }\n await verifyDocumentWriterProjection({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const request = await buildDocumentPurgeRequest({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n writerProjection,\n });\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n if (input.stillCurrent?.() === false) return null;\n const response = await input.apiClient.purgeDocument(\n input.documentId,\n request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof: response,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return response;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAE1B,uBAAuB,EACvB,uBAAuB,EACvB,eAAe,GAEhB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,6BAA6B,GAI9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,iBAAiB,EACjB,0CAA0C,GAC3C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,sCAAsC,EACtC,uBAAuB,GACxB,MAAM,wCAAwC,CAAC;AAGhD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAKzE,OAAO,EACL,wBAAwB,EACxB,gCAAgC,EAChC,8BAA8B,GAC/B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OA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kB,EAAE,KAAK,CAAC,UAAU;QACpC,sBAAsB,EAAE,KAAK,CAAC,MAAM,CAAC,cAAc;QACnD,KAAK,EAAE,QAAQ;QACf,cAAc,EAAE,KAAK,CAAC,wBAAwB;QAC9C,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;KACvE,CAAC,CAAC;IACH,MAAM,KAAK,CAAC,eAAe,CAAC;QAC1B,gBAAgB,EAAE,QAAQ,CAAC,iBAAiB;KAC7C,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,OAAO,EACL,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,uBAAuB,CAAC","sourcesContent":["import {\n computeAccessEventBodyHash,\n type DocumentPurgeAccessEventBody,\n KeyingVerificationError,\n readKeyingCanonicalJson,\n signAccessEvent,\n type UnsignedAccessEvent,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeRequest } from \"@tearleads/validators/request\";\nimport {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentPurgeProofResponse,\n type DocumentPurgeResponse,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport {\n containerPathRefs,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport {\n assertDocumentManifestBundleConsistent,\n readManifestContainerId,\n} from \"../../../data/documents/shared/readers\";\nimport type { DocumentSyncApi } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type { DocumentCreateAuthor } from \"../../../data/documents/shared/types\";\nimport { readCanonicalRecord } from \"../../../data/keying/canonicalJson\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n verifyDocumentWriterProjection,\n} from \"../../../data/keyingProjectionVerification\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { openPrincipalPolicyBundleReader } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type {\n DocumentPurgeApi,\n RemoteDocumentCollaborators,\n} from \"../remote/remoteDocumentCollaborators\";\nimport {\n assertSubtreePurgePath,\n type SubtreePurgeRoot,\n} from \"./subtreePurgeScope\";\n\n/** What varies per purge; the collaborators bind the rest. */\nexport interface PurgeRemoteDocumentRequest {\n readonly beforeSubmit?: (() => Promise<boolean>) | undefined;\n readonly author: DocumentCreateAuthor;\n readonly documentId: string;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly onVerifiedPurge: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nconst REMOTE_DOCUMENT_ALREADY_PURGED = Symbol(\"remoteDocumentAlreadyPurged\");\n\nasync function loadAuthenticatedDocumentPurgeProof(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<DocumentPurgeProofResponse | null> {\n if (!input.apiClient.getDocumentPurgeProof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing a purge-proof endpoint\",\n );\n }\n const initialProof = await input.apiClient.getDocumentPurgeProof(\n input.documentId,\n undefined,\n {\n expectedPaymentRequiredOrganizationId: input.expectedOrganizationId,\n },\n );\n if (!initialProof) {\n // ApiClient returns null for transport, HTTP and response-shape failures.\n // Even after a deletion hint, absence cannot prove signed-data tampering.\n // Keep local data and defer deletion until an actual proof verifies.\n return null;\n }\n await verifyDocumentPurgeProofBaseline({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof: initialProof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The current API returns complete history to recorded readers. Otherwise\n // its terminal snapshot needs an exact local pin; a floor refetch cannot\n // grant missing observation authority.\n return initialProof;\n}\n\nasync function resolveDocumentPurgeWriterProjection(input: {\n readonly apiClient: DocumentPurgeApi;\n readonly documentId: string;\n}): Promise<\n | DocumentWriterProjectionResponse\n | typeof REMOTE_DOCUMENT_ALREADY_PURGED\n | null\n> {\n const result = await input.apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n if (result.status === 404 && result.code === DOCUMENT_NOT_FOUND_ERROR_CODE) {\n return REMOTE_DOCUMENT_ALREADY_PURGED;\n }\n result.report();\n return null;\n}\n\nexport async function buildDocumentPurgeRequest(input: {\n readonly author: DocumentCreateAuthor;\n readonly expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n readonly eventId?: string | undefined;\n readonly signedAt?: string | undefined;\n readonly writerProjection: DocumentWriterProjectionResponse;\n}): Promise<DocumentPurgeRequest> {\n const identity = await assertDocumentManifestBundleConsistent({\n bundle: input.writerProjection.documentManifest,\n label: \"Document purge predecessor\",\n });\n if (identity.documentId !== input.writerProjection.documentId) {\n throw new Error(\"Document purge projection identity mismatch\");\n }\n if (identity.organizationId !== input.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge author organization mismatch\",\n );\n }\n const linkedContainerIds = readLinkedContainerIdsFromDocumentManifest(\n input.writerProjection,\n );\n if (linkedContainerIds.length !== 1) {\n throw new Error(\"Document purge requires exactly one linked container\");\n }\n const [containerId] = linkedContainerIds;\n const authorizingProjection = documentContainerProjections(\n input.writerProjection,\n ).find((projection) => {\n const leaf = projection.path.at(-1);\n return leaf && readManifestContainerId(leaf) === containerId;\n });\n const containerManifestHash =\n authorizingProjection?.path.at(-1)?.manifestHash;\n if (!authorizingProjection || !containerId || !containerManifestHash) {\n throw new Error(\"Document purge authorization path is unavailable\");\n }\n assertSubtreePurgePath(authorizingProjection.path, input.expectedSubtreeRoot);\n const authorizingContainerManifestHashes = authorizingProjection.path.map(\n (bundle) => bundle.manifestHash,\n );\n const body: DocumentPurgeAccessEventBody = {\n authorizingContainerManifestHashes,\n containerId,\n containerManifestHash,\n documentManifestHash: input.writerProjection.documentManifest.manifestHash,\n eventType: \"document.purge\",\n };\n const unsignedEvent: UnsignedAccessEvent = {\n version: 1,\n eventId: input.eventId ?? crypto.randomUUID(),\n eventType: \"document.purge\",\n objectKind: \"document\",\n objectId: input.writerProjection.documentId,\n organizationId: input.author.organizationId,\n previousManifestHash: input.writerProjection.documentManifest.manifestHash,\n dependencyManifestHashes: authorizingContainerManifestHashes,\n bodyHash: await computeAccessEventBodyHash(\n readKeyingCanonicalJson(body, \"Document purge body\"),\n ),\n signerUserId: input.author.signerUserId,\n signerDeviceId: input.author.signerDeviceId,\n signerKeyFingerprint: input.author.signerKeyFingerprint,\n signedAt: input.signedAt ?? new Date().toISOString(),\n };\n const event = await signAccessEvent(\n unsignedEvent,\n input.author.signerPrivateKey,\n );\n\n return {\n authorizingContainerPathRefs: containerPathRefs(authorizingProjection.path),\n body: readCanonicalRecord(body, \"Document purge body\"),\n event: readCanonicalRecord(event, \"Document purge event\"),\n };\n}\n\nexport function createVerifiedRemoteDocumentDeletionHandler(input: {\n readonly apiClient: Pick<DocumentSyncApi, \"getDocumentPurgeProof\">;\n readonly execSql: ExecSql;\n readonly expectedOrganizationId: string;\n readonly onVerifiedDeletion: (input: {\n readonly commitPurgeProof: (transactionExecSql: ExecSql) => Promise<void>;\n readonly documentId: string;\n }) => Promise<void> | void;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): (deleted: { readonly documentId: string }) => Promise<void> {\n return async ({ documentId }) => {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Remote document deletion is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: documentId,\n expectedOrganizationId: input.expectedOrganizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedDeletion({\n commitPurgeProof: verified.commitCheckpoints,\n documentId,\n });\n };\n}\n\nexport async function purgeRemoteDocument(\n remote: RemoteDocumentCollaborators,\n purge: PurgeRemoteDocumentRequest,\n): Promise<DocumentPurgeResponse | null> {\n const input = {\n ...purge,\n apiClient: remote.api,\n execSql: remote.execSql,\n };\n const writerProjection = await resolveDocumentPurgeWriterProjection({\n apiClient: input.apiClient,\n documentId: input.documentId,\n });\n if (!writerProjection) {\n return null;\n }\n if (writerProjection === REMOTE_DOCUMENT_ALREADY_PURGED) {\n const proof = await loadAuthenticatedDocumentPurgeProof({\n apiClient: input.apiClient,\n documentId: input.documentId,\n execSql: input.execSql,\n expectedOrganizationId: input.author.organizationId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!proof) {\n throw new ProjectionDependencyUnavailableError(\n \"Purged remote document is missing its signed purge proof\",\n );\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return { ...proof, reclaimedBlobStorageKeys: [] };\n }\n await verifyDocumentWriterProjection({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const request = await buildDocumentPurgeRequest({\n author: input.author,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n writerProjection,\n });\n if (input.beforeSubmit && !(await input.beforeSubmit())) return null;\n if (input.stillCurrent?.() === false) return null;\n const response = await input.apiClient.purgeDocument(\n input.documentId,\n request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n );\n if (!response) {\n return null;\n }\n const verified = await verifyDocumentPurgeProof({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n expectedDocumentId: input.documentId,\n expectedOrganizationId: input.author.organizationId,\n proof: response,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await input.onVerifiedPurge({\n commitPurgeProof: verified.commitCheckpoints,\n });\n return response;\n}\n\nexport {\n hasVerifiedDocumentPurge,\n pinAbsentDocumentPurge,\n} from \"./absentDocumentPurge\";\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { DocumentPurgeResponse } from "../../../internal/validators/response/index.js";
2
2
  import type { SyncRemoteDocumentResult } from "../../../data/documents/shared/sync/documentSyncTypes.js";
3
3
  import type { CreateRemoteDocumentResult, RelinkRemoteDocumentResult } from "../../../data/documents/shared/types.js";
4
- import type { CreateRemoteDocumentRequest } from "../create/remoteDocumentCreateRequest.js";
4
+ import type { DocumentSubmissionRequest } from "../create/remoteDocumentCreateRequest.js";
5
5
  import { type RelinkRemoteDocumentRequest } from "../linkSet/linkSetRemote.js";
6
6
  import { type PurgeRemoteDocumentRequest } from "../purge/index.js";
7
7
  import type { SyncRemoteDocumentRequest } from "../sync/remoteDocumentSyncPass.js";
@@ -18,7 +18,7 @@ export declare class RemoteDocumentService {
18
18
  /** Throws when the service has no encapsulation secret key. */
19
19
  syncRemoteDocument(request: SyncRemoteDocumentRequest): Promise<SyncRemoteDocumentResult | null>;
20
20
  /** Throws when the service has no encapsulation secret key. */
21
- createRemoteDocument(request: CreateRemoteDocumentRequest): Promise<CreateRemoteDocumentResult | null>;
21
+ createRemoteDocument(request: DocumentSubmissionRequest): Promise<CreateRemoteDocumentResult | null>;
22
22
  /** Throws when the service has no encapsulation secret key. */
23
23
  relinkRemoteDocument(request: RelinkRemoteDocumentRequest): Promise<RelinkRemoteDocumentResult | null>;
24
24
  purgeRemoteDocument(request: PurgeRemoteDocumentRequest): Promise<DocumentPurgeResponse | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"remoteDocumentService.js","sourceRoot":"","sources":["remoteDocumentService.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAEjD,OAAO,EAEL,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAmC,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAI7C;;;;;GAKG;AACH,MAAM,OAAO,qBAAqB;IACf,MAAM,CAA8B;IAErD,YAAY,aAA0C;QACpD,IAAI,CAAC,MAAM,GAAG,aAAa,CAAC;IAC9B,CAAC;IAED,+DAA+D;IAC/D,kBAAkB,CAChB,OAAkC;QAElC,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,+DAA+D;IAC/D,oBAAoB,CAClB,OAAoC;QAEpC,OAAO,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;IAED,+DAA+D;IAC/D,oBAAoB,CAClB,OAAoC;QAEpC,OAAO,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;IAED,mBAAmB,CACjB,OAAmC;QAEnC,OAAO,mBAAmB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;CACF","sourcesContent":["import type { DocumentPurgeResponse } from \"@tearleads/validators/response\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type {\n CreateRemoteDocumentResult,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport { createRemoteDocument } from \"../create\";\nimport type { CreateRemoteDocumentRequest } from \"../create/remoteDocumentCreateRequest\";\nimport {\n type RelinkRemoteDocumentRequest,\n relinkRemoteDocument,\n} from \"../linkSet/linkSetRemote\";\nimport { type PurgeRemoteDocumentRequest, purgeRemoteDocument } from \"../purge\";\nimport { syncRemoteDocument } from \"../sync\";\nimport type { SyncRemoteDocumentRequest } from \"../sync/remoteDocumentSyncPass\";\nimport type { RemoteDocumentCollaborators } from \"./remoteDocumentCollaborators\";\n\n/**\n * Document Store & Sync: signed remote document reads and mutations. One\n * instance binds the API client, executor, key material, and remote-sync block\n * of one runtime snapshot; each request carries what varies per call, such as\n * ids, the author, the projection key resolver, and currency checks.\n */\nexport class RemoteDocumentService {\n private readonly remote: RemoteDocumentCollaborators;\n\n constructor(collaborators: RemoteDocumentCollaborators) {\n this.remote = collaborators;\n }\n\n /** Throws when the service has no encapsulation secret key. */\n syncRemoteDocument(\n request: SyncRemoteDocumentRequest,\n ): Promise<SyncRemoteDocumentResult | null> {\n return syncRemoteDocument(this.remote, request);\n }\n\n /** Throws when the service has no encapsulation secret key. */\n createRemoteDocument(\n request: CreateRemoteDocumentRequest,\n ): Promise<CreateRemoteDocumentResult | null> {\n return createRemoteDocument(this.remote, request);\n }\n\n /** Throws when the service has no encapsulation secret key. */\n relinkRemoteDocument(\n request: RelinkRemoteDocumentRequest,\n ): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteDocument(this.remote, request);\n }\n\n purgeRemoteDocument(\n request: PurgeRemoteDocumentRequest,\n ): Promise<DocumentPurgeResponse | null> {\n return purgeRemoteDocument(this.remote, request);\n }\n}\n"]}
1
+ {"version":3,"file":"remoteDocumentService.js","sourceRoot":"","sources":["remoteDocumentService.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAEjD,OAAO,EAEL,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAmC,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAI7C;;;;;GAKG;AACH,MAAM,OAAO,qBAAqB;IACf,MAAM,CAA8B;IAErD,YAAY,aAA0C;QACpD,IAAI,CAAC,MAAM,GAAG,aAAa,CAAC;IAC9B,CAAC;IAED,+DAA+D;IAC/D,kBAAkB,CAChB,OAAkC;QAElC,OAAO,kBAAkB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,+DAA+D;IAC/D,oBAAoB,CAClB,OAAkC;QAElC,OAAO,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;IAED,+DAA+D;IAC/D,oBAAoB,CAClB,OAAoC;QAEpC,OAAO,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;IAED,mBAAmB,CACjB,OAAmC;QAEnC,OAAO,mBAAmB,CAAC,IAAI,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnD,CAAC;CACF","sourcesContent":["import type { DocumentPurgeResponse } from \"@tearleads/validators/response\";\nimport type { SyncRemoteDocumentResult } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport type {\n CreateRemoteDocumentResult,\n RelinkRemoteDocumentResult,\n} from \"../../../data/documents/shared/types\";\nimport { createRemoteDocument } from \"../create\";\nimport type { DocumentSubmissionRequest } from \"../create/remoteDocumentCreateRequest\";\nimport {\n type RelinkRemoteDocumentRequest,\n relinkRemoteDocument,\n} from \"../linkSet/linkSetRemote\";\nimport { type PurgeRemoteDocumentRequest, purgeRemoteDocument } from \"../purge\";\nimport { syncRemoteDocument } from \"../sync\";\nimport type { SyncRemoteDocumentRequest } from \"../sync/remoteDocumentSyncPass\";\nimport type { RemoteDocumentCollaborators } from \"./remoteDocumentCollaborators\";\n\n/**\n * Document Store & Sync: signed remote document reads and mutations. One\n * instance binds the API client, executor, key material, and remote-sync block\n * of one runtime snapshot; each request carries what varies per call, such as\n * ids, the author, the projection key resolver, and currency checks.\n */\nexport class RemoteDocumentService {\n private readonly remote: RemoteDocumentCollaborators;\n\n constructor(collaborators: RemoteDocumentCollaborators) {\n this.remote = collaborators;\n }\n\n /** Throws when the service has no encapsulation secret key. */\n syncRemoteDocument(\n request: SyncRemoteDocumentRequest,\n ): Promise<SyncRemoteDocumentResult | null> {\n return syncRemoteDocument(this.remote, request);\n }\n\n /** Throws when the service has no encapsulation secret key. */\n createRemoteDocument(\n request: DocumentSubmissionRequest,\n ): Promise<CreateRemoteDocumentResult | null> {\n return createRemoteDocument(this.remote, request);\n }\n\n /** Throws when the service has no encapsulation secret key. */\n relinkRemoteDocument(\n request: RelinkRemoteDocumentRequest,\n ): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteDocument(this.remote, request);\n }\n\n purgeRemoteDocument(\n request: PurgeRemoteDocumentRequest,\n ): Promise<DocumentPurgeResponse | null> {\n return purgeRemoteDocument(this.remote, request);\n }\n}\n"]}