@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.
- package/client/documents/index.d.ts +5 -2
- package/client/documents/index.js +6 -1
- package/client/documents/index.js.map +1 -1
- package/client/index.d.ts +1 -1
- package/client/index.js.map +1 -1
- package/data/blobs/attachments/types.d.ts +4 -2
- package/data/blobs/attachments/types.js.map +1 -1
- package/data/documents/documentContent.d.ts +2 -0
- package/data/documents/documentContent.js +7 -0
- package/data/documents/documentContent.js.map +1 -1
- package/data/documents/shared/manifestBundleReaders.js +1 -1
- package/data/documents/shared/manifestBundleReaders.js.map +1 -1
- package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
- package/data/documents/shared/projection/documentCreateSigner.js +49 -0
- package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
- package/data/documents/shared/projection/index.d.ts +1 -0
- package/data/documents/shared/projection/index.js +1 -0
- package/data/documents/shared/projection/index.js.map +1 -1
- package/data/documents/shared/readers.js +1 -1
- package/data/documents/shared/readers.js.map +1 -1
- package/data/documents/shared/types.d.ts +1 -0
- package/data/documents/shared/types.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.d.ts +1 -1
- package/data/persistence/documents/documentsPersistence.js +4 -1
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +2 -2
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +2 -2
- package/internal/api-client/apiRequestRuntime.js +12 -8
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/binaryResponseOperationTransport.js +2 -2
- package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
- package/internal/api-client/client/blobs.d.ts +2 -2
- package/internal/api-client/client/blobs.js +21 -9
- package/internal/api-client/client/blobs.js.map +1 -1
- package/internal/api-client/client/writerProjections.js +2 -1
- package/internal/api-client/client/writerProjections.js.map +1 -1
- package/internal/api-client/operationResponse.js +3 -3
- package/internal/api-client/operationResponse.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +6 -1
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionResponse.js +5 -2
- package/internal/api-client/sessionResponse.js.map +1 -1
- package/internal/api-client/types.d.ts +2 -0
- package/internal/api-client/types.js.map +1 -1
- package/package.json +1 -1
- package/sqlite/worker.js +4 -4
- package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
- package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
- package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
- package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
- package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
- package/stores/documents/documentStore/state.js +3 -1
- package/stores/documents/documentStore/state.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +3 -2
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/stores/documents/index.d.ts +1 -0
- package/stores/documents/index.js +1 -0
- package/stores/documents/index.js.map +1 -1
- package/stores/documents/types.d.ts +1 -0
- package/stores/documents/types.js.map +1 -1
- package/workflows/blobs/upload/index.d.ts +1 -1
- package/workflows/blobs/upload/index.js +36 -18
- package/workflows/blobs/upload/index.js.map +1 -1
- package/workflows/blobs/upload/multipartStageResolution.js +12 -2
- package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
- package/workflows/blobs/upload/multipartUpload.js +10 -2
- package/workflows/blobs/upload/multipartUpload.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
- package/workflows/container-contents/documentQueries/index.d.ts +1 -1
- package/workflows/container-contents/documentQueries/index.js +2 -2
- package/workflows/container-contents/documentQueries/index.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -0
- package/workflows/container-contents/index.js +1 -0
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
- package/workflows/documents/create/createAdoption.js +2 -50
- package/workflows/documents/create/createAdoption.js.map +1 -1
- package/workflows/documents/create/createResponse.js +12 -1
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/create/createSubmission.js +14 -0
- package/workflows/documents/create/createSubmission.js.map +1 -0
- package/workflows/documents/create/index.d.ts +3 -14
- package/workflows/documents/create/index.js +76 -67
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
- package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
- package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
- package/workflows/documents/purge/absentDocumentPurge.js +23 -0
- package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
- package/workflows/documents/purge/index.d.ts +1 -0
- package/workflows/documents/purge/index.js +1 -0
- package/workflows/documents/purge/index.js.map +1 -1
- package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
- package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
|
@@ -1,55 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { assertDocumentWriterProjectionConsistent, readLinkedContainerIdsFromDocumentManifest, unwrapDocumentContentKeyFromWriterProjection, } from "../../../data/documents/shared/projection/index.js";
|
|
1
|
+
import { assertDocumentCreateSigner, assertDocumentWriterProjectionConsistent, readLinkedContainerIdsFromDocumentManifest, unwrapDocumentContentKeyFromWriterProjection, } from "../../../data/documents/shared/projection/index.js";
|
|
3
2
|
import { projectionVerificationOptions } from "../../../data/documents/shared/projection/projectionVerificationOptions.js";
|
|
4
3
|
import { persistedDocumentCreateStateFromWriterProjection } from "../../../data/documents/shared/responses.js";
|
|
5
4
|
import { checkWithHeldBundleRecovery } from "../../../data/keyingProjectionVerification/index.js";
|
|
6
|
-
import { readAccessEvent, readAccessManifest, } from "../../../data/keyingProjectionVerification/readers.js";
|
|
7
|
-
/**
|
|
8
|
-
* A retry after a lost create response can only recover the local user's own
|
|
9
|
-
* create: the server serves whatever document holds the stable id we minted,
|
|
10
|
-
* and an honest server only ever committed ours under it. A create event signed
|
|
11
|
-
* by anyone else is a foreign document colliding on that id (a member with
|
|
12
|
-
* write access on the same container, or a dishonest server), which must not be
|
|
13
|
-
* adopted as if it were the pending local write.
|
|
14
|
-
*
|
|
15
|
-
* The create event is located by walking the served head's predecessor chain,
|
|
16
|
-
* not by scanning the history for any parentless manifest: the history is
|
|
17
|
-
* server-supplied, so a dishonest server could splice in a genesis this user
|
|
18
|
-
* signed for a different document. Every manifest on the chain must also name
|
|
19
|
-
* the requested document.
|
|
20
|
-
*/
|
|
21
|
-
function assertCreateEventSignedLocally(input, writerProjection) {
|
|
22
|
-
const label = "Document create conflict";
|
|
23
|
-
const historyByHash = new Map(writerProjection.documentManifestHistory.map((bundle) => [
|
|
24
|
-
bundle.manifestHash,
|
|
25
|
-
bundle,
|
|
26
|
-
]));
|
|
27
|
-
const visited = new Set();
|
|
28
|
-
let bundle = writerProjection.documentManifest;
|
|
29
|
-
for (;;) {
|
|
30
|
-
const manifest = readAccessManifest(bundle.manifest, `${label} manifest`);
|
|
31
|
-
if (manifest.objectKind !== "document" ||
|
|
32
|
-
manifest.objectId !== input.documentId) {
|
|
33
|
-
throw new KeyingVerificationError("object_mismatch", `${label} manifest chain names another document`);
|
|
34
|
-
}
|
|
35
|
-
if (manifest.previousManifestHash === null) {
|
|
36
|
-
const createEvent = readAccessEvent(bundle.event.event, `${label} create event`);
|
|
37
|
-
if (createEvent.signerUserId !== input.expectedSignerUserId) {
|
|
38
|
-
throw new KeyingVerificationError("signer_mismatch", `${label} create event was signed by another user`);
|
|
39
|
-
}
|
|
40
|
-
return;
|
|
41
|
-
}
|
|
42
|
-
if (visited.has(bundle.manifestHash)) {
|
|
43
|
-
throw new KeyingVerificationError("invalid_shape", `${label} manifest history is cyclic`);
|
|
44
|
-
}
|
|
45
|
-
visited.add(bundle.manifestHash);
|
|
46
|
-
const previous = historyByHash.get(manifest.previousManifestHash);
|
|
47
|
-
if (!previous) {
|
|
48
|
-
throw new KeyingVerificationError("invalid_shape", `${label} does not expose its create event`);
|
|
49
|
-
}
|
|
50
|
-
bundle = previous;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
5
|
function assertExpectedAdoptionScope(input, writerProjection) {
|
|
54
6
|
const linkedContainerIds = readLinkedContainerIdsFromDocumentManifest(writerProjection);
|
|
55
7
|
const expectedPath = writerProjection.authorizingContainerPaths.find((projection) => projection.containerId === input.expectedContainerId &&
|
|
@@ -74,7 +26,7 @@ export async function adoptExistingRemoteDocument(input) {
|
|
|
74
26
|
stillCurrent: input.stillCurrent,
|
|
75
27
|
}, async () => {
|
|
76
28
|
assertExpectedAdoptionScope(input, writerProjection);
|
|
77
|
-
|
|
29
|
+
assertDocumentCreateSigner(input, writerProjection);
|
|
78
30
|
});
|
|
79
31
|
const verifiedByHash = new Map();
|
|
80
32
|
const principalPolicyCache = new Map();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,wCAAwC,EACxC,0CAA0C,EAC1C,4CAA4C,GAC7C,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gDAAgD,EAAE,MAAM,0CAA0C,CAAC;AAK5G,OAAO,EAAE,2BAA2B,EAAE,MAAM,4CAA4C,CAAC;AACzF,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,oDAAoD,CAAC;AAc5D;;;;;;;;;;;;;GAaG;AACH,SAAS,8BAA8B,CACr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8B,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;IAC1D,CAAC,CACF,CAAC;IACF,MAAM,cAAc,GAAG,IAAI,GAAG,EAA2C,CAAC;IAC1E,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAmC,CAAC;IACxE,MAAM,OAAO,GAAG,MAAM,wCAAwC,CAC5D,gBAAgB,EAChB;QACE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,oBAAoB;QACpB,cAAc;QACd,GAAG,6BAA6B,CAAC,KAAK,CAAC;KACxC,CACF,CAAC;IACF,IACE,OAAO,CAAC,MAAM,KAAK,CAAC;QACpB,OAAO,CAAC,CAAC,CAAC,EAAE,WAAW,KAAK,KAAK,CAAC,mBAAmB,EACrD,CAAC;QACD,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;IACJ,CAAC;IACD,MAAM,UAAU,GAAG,MAAM,4CAA4C,CAAC;QACpE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,oBAAoB;QACpB,SAAS,EAAE,KAAK,CAAC,eAAe;QAChC,cAAc;QACd,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC;KACxC,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,KAAK,CAAC,SAAS,CAAC,6BAA6B,CAC3C,gBAAgB,CAAC,UAAU,EAC3B,gBAAgB,CACjB,CAAC;IACF,OAAO;QACL,UAAU;QACV,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,cAAc,EACZ,gDAAgD,CAAC,gBAAgB,CAAC;QACpE,gBAAgB;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapDocumentContentKeyFromWriterProjection,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n} from \"../../../data/documents/shared/types\";\nimport { checkWithHeldBundleRecovery } from \"../../../data/keyingProjectionVerification\";\nimport {\n readAccessEvent,\n readAccessManifest,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\ntype RemoteDocumentAdoptionInput = {\n readonly apiClient: DocumentCreateApi;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedContainerId: string;\n readonly expectedOrganizationId: string;\n /** The local user whose pending create the retry is recovering. */\n readonly expectedSignerUserId: string;\n readonly targetSecretKey: Uint8Array;\n} & ProjectionVerificationOptions;\n\n/**\n * A retry after a lost create response can only recover the local user's own\n * create: the server serves whatever document holds the stable id we minted,\n * and an honest server only ever committed ours under it. A create event signed\n * by anyone else is a foreign document colliding on that id (a member with\n * write access on the same container, or a dishonest server), which must not be\n * adopted as if it were the pending local write.\n *\n * The create event is located by walking the served head's predecessor chain,\n * not by scanning the history for any parentless manifest: the history is\n * server-supplied, so a dishonest server could splice in a genesis this user\n * signed for a different document. Every manifest on the chain must also name\n * the requested document.\n */\nfunction assertCreateEventSignedLocally(\n input: RemoteDocumentAdoptionInput,\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const label = \"Document create conflict\";\n const historyByHash = new Map(\n writerProjection.documentManifestHistory.map((bundle) => [\n bundle.manifestHash,\n bundle,\n ]),\n );\n const visited = new Set<string>();\n let bundle = writerProjection.documentManifest;\n for (;;) {\n const manifest = readAccessManifest(bundle.manifest, `${label} manifest`);\n if (\n manifest.objectKind !== \"document\" ||\n manifest.objectId !== input.documentId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${label} manifest chain names another document`,\n );\n }\n if (manifest.previousManifestHash === null) {\n const createEvent = readAccessEvent(\n bundle.event.event,\n `${label} create event`,\n );\n if (createEvent.signerUserId !== input.expectedSignerUserId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${label} create event was signed by another user`,\n );\n }\n return;\n }\n if (visited.has(bundle.manifestHash)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} manifest history is cyclic`,\n );\n }\n visited.add(bundle.manifestHash);\n const previous = historyByHash.get(manifest.previousManifestHash);\n if (!previous) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `${label} does not expose its create event`,\n );\n }\n bundle = previous;\n }\n}\n\nfunction assertExpectedAdoptionScope(\n input: RemoteDocumentAdoptionInput,\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const linkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n const expectedPath = writerProjection.authorizingContainerPaths.find(\n (projection) =>\n projection.containerId === input.expectedContainerId &&\n projection.organizationId === input.expectedOrganizationId,\n );\n if (\n linkedContainerIds.length !== 1 ||\n linkedContainerIds[0] !== input.expectedContainerId ||\n !expectedPath\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n}\n\n/** Recover a committed retry only when it belongs to the intended org scope. */\nexport async function adoptExistingRemoteDocument(\n input: RemoteDocumentAdoptionInput,\n): Promise<CreateRemoteDocumentResult | null> {\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) return null;\n\n // Reject a foreign collision before verification can pin its checkpoints.\n // A refusal drops any held bundles the projection took, so a retry\n // fetches them.\n await checkWithHeldBundleRecovery(\n {\n execSql: input.execSql,\n projection: writerProjection,\n stillCurrent: input.stillCurrent,\n },\n async () => {\n assertExpectedAdoptionScope(input, writerProjection);\n assertCreateEventSignedLocally(input, writerProjection);\n },\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n const targets = await assertDocumentWriterProjectionConsistent(\n writerProjection,\n {\n execSql: input.execSql,\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n },\n );\n if (\n targets.length !== 1 ||\n targets[0]?.containerId !== input.expectedContainerId\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n const contentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (input.stillCurrent?.() === false) return null;\n input.apiClient.primeDocumentWriterProjection(\n writerProjection.documentId,\n writerProjection,\n );\n return {\n contentKey,\n documentId: writerProjection.documentId,\n persistedState:\n persistedDocumentCreateStateFromWriterProjection(writerProjection),\n writerProjection,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"createAdoption.js","sourceRoot":"","sources":["createAdoption.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,0BAA0B,EAC1B,wCAAwC,EACxC,0CAA0C,EAC1C,4CAA4C,GAC7C,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gDAAgD,EAAE,MAAM,0CAA0C,CAAC;AAK5G,OAAO,EAAE,2BAA2B,EAAE,MAAM,4CAA4C,CAAC;AAczF,SAAS,2BAA2B,CAClC,KAAkC,EAClC,gBAAkD;IAElD,MAAM,kBAAkB,GACtB,0CAA0C,CAAC,gBAAgB,CAAC,CAAC;IAC/D,MAAM,YAAY,GAAG,gBAAgB,CAAC,yBAAyB,CAAC,IAAI,CAClE,CAAC,UAAU,EAAE,EAAE,CACb,UAAU,CAAC,WAAW,KAAK,KAAK,CAAC,mBAAmB;QACpD,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,sBAAsB,C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,GAAG,MAAM,4CAA4C,CAAC;QACpE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,oBAAoB;QACpB,SAAS,EAAE,KAAK,CAAC,eAAe;QAChC,cAAc;QACd,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC;KACxC,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAClD,KAAK,CAAC,SAAS,CAAC,6BAA6B,CAC3C,gBAAgB,CAAC,UAAU,EAC3B,gBAAgB,CACjB,CAAC;IACF,OAAO;QACL,UAAU;QACV,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,cAAc,EACZ,gDAAgD,CAAC,gBAAgB,CAAC;QACpE,gBAAgB;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n VerifiedContainerAccessManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentCreateSigner,\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n unwrapDocumentContentKeyFromWriterProjection,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n} from \"../../../data/documents/shared/types\";\nimport { checkWithHeldBundleRecovery } from \"../../../data/keyingProjectionVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\ntype RemoteDocumentAdoptionInput = {\n readonly apiClient: DocumentCreateApi;\n readonly documentId: string;\n readonly execSql: ExecSql;\n readonly expectedContainerId: string;\n readonly expectedOrganizationId: string;\n /** The local user whose pending create the retry is recovering. */\n readonly expectedSignerUserId: string;\n readonly targetSecretKey: Uint8Array;\n} & ProjectionVerificationOptions;\n\nfunction assertExpectedAdoptionScope(\n input: RemoteDocumentAdoptionInput,\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n const linkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n const expectedPath = writerProjection.authorizingContainerPaths.find(\n (projection) =>\n projection.containerId === input.expectedContainerId &&\n projection.organizationId === input.expectedOrganizationId,\n );\n if (\n linkedContainerIds.length !== 1 ||\n linkedContainerIds[0] !== input.expectedContainerId ||\n !expectedPath\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n}\n\n/** Recover a committed retry only when it belongs to the intended org scope. */\nexport async function adoptExistingRemoteDocument(\n input: RemoteDocumentAdoptionInput,\n): Promise<CreateRemoteDocumentResult | null> {\n const writerProjection = await input.apiClient.getDocumentWriterProjection(\n input.documentId,\n );\n if (!writerProjection) return null;\n\n // Reject a foreign collision before verification can pin its checkpoints.\n // A refusal drops any held bundles the projection took, so a retry\n // fetches them.\n await checkWithHeldBundleRecovery(\n {\n execSql: input.execSql,\n projection: writerProjection,\n stillCurrent: input.stillCurrent,\n },\n async () => {\n assertExpectedAdoptionScope(input, writerProjection);\n assertDocumentCreateSigner(input, writerProjection);\n },\n );\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const principalPolicyCache = new Map<string, VerifiedPrincipalPolicy>();\n const targets = await assertDocumentWriterProjectionConsistent(\n writerProjection,\n {\n execSql: input.execSql,\n principalPolicyCache,\n verifiedByHash,\n ...projectionVerificationOptions(input),\n },\n );\n if (\n targets.length !== 1 ||\n targets[0]?.containerId !== input.expectedContainerId\n ) {\n throw new Error(\n \"Document create conflict belongs to another container or organization\",\n );\n }\n const contentKey = await unwrapDocumentContentKeyFromWriterProjection({\n execSql: input.execSql,\n principalPolicyCache,\n secretKey: input.targetSecretKey,\n verifiedByHash,\n writerProjection,\n ...projectionVerificationOptions(input),\n });\n if (input.stillCurrent?.() === false) return null;\n input.apiClient.primeDocumentWriterProjection(\n writerProjection.documentId,\n writerProjection,\n );\n return {\n contentKey,\n documentId: writerProjection.documentId,\n persistedState:\n persistedDocumentCreateStateFromWriterProjection(writerProjection),\n writerProjection,\n };\n}\n"]}
|
|
@@ -5,6 +5,14 @@ import { nullOnProjectionVerificationCancellation } from "../../../data/keyingPr
|
|
|
5
5
|
import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
|
|
6
6
|
import { adoptExistingRemoteDocument } from "./createAdoption.js";
|
|
7
7
|
import { documentWriterProjectionFromCreateResponse } from "./createProjection.js";
|
|
8
|
+
/** A strict importer can only proceed after its exact birth update is acknowledged. */
|
|
9
|
+
export function assertRequiredSeedAcknowledged(request, created) {
|
|
10
|
+
if (!request.requireSeededCreate)
|
|
11
|
+
return;
|
|
12
|
+
const accepted = created?.response?.initialSync?.acceptedOutgoingUpdateIds;
|
|
13
|
+
if (!request.seedUpdate || !accepted?.includes(request.seedUpdate.id))
|
|
14
|
+
throw new Error("The server did not acknowledge the initial document content.");
|
|
15
|
+
}
|
|
8
16
|
/** A matched acknowledgement remains committed if authorization evidence races. */
|
|
9
17
|
export async function acknowledgeRemoteDocumentCreate(input) {
|
|
10
18
|
const { materializedPlan, response } = input;
|
|
@@ -33,13 +41,16 @@ export async function acknowledgeRemoteDocumentCreate(input) {
|
|
|
33
41
|
// A principal pin can advance while POST is in flight. Recover the already
|
|
34
42
|
// committed document from fresh evidence, without submitting another create.
|
|
35
43
|
// The adoption path still verifies its author, scope, chain and key binding.
|
|
36
|
-
|
|
44
|
+
const recovered = await nullOnProjectionVerificationCancellation(() => adoptExistingRemoteDocument({
|
|
37
45
|
...input,
|
|
38
46
|
documentId: response.id,
|
|
39
47
|
expectedContainerId: input.containerProjection.containerId,
|
|
40
48
|
expectedOrganizationId: input.containerProjection.organizationId,
|
|
41
49
|
expectedSignerUserId: input.author.signerUserId,
|
|
42
50
|
}));
|
|
51
|
+
return recovered && response.initialSync
|
|
52
|
+
? { ...recovered, response }
|
|
53
|
+
: recovered;
|
|
43
54
|
}
|
|
44
55
|
input.apiClient.primeDocumentWriterProjection(response.id, writerProjection);
|
|
45
56
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createResponse.js","sourceRoot":"","sources":["createResponse.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AAErG,OAAO,EACL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAQ1G,OAAO,EAAE,wCAAwC,EAAE,MAAM,kDAAkD,CAAC;AAC5G,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,0CAA0C,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"createResponse.js","sourceRoot":"","sources":["createResponse.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AAErG,OAAO,EACL,0BAA0B,EAC1B,yCAAyC,GAC1C,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,2BAA2B,EAAE,MAAM,6DAA6D,CAAC;AAQ1G,OAAO,EAAE,wCAAwC,EAAE,MAAM,kDAAkD,CAAC;AAC5G,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,0CAA0C,EAAE,MAAM,oBAAoB,CAAC;AAGhF,uFAAuF;AACvF,MAAM,UAAU,8BAA8B,CAC5C,OAAkC,EAClC,OAA0C;IAE1C,IAAI,CAAC,OAAO,CAAC,mBAAmB;QAAE,OAAO;IACzC,MAAM,QAAQ,GAAG,OAAO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C1E,2EAA2E;QAC3E,6EAA6E;QAC7E,6EAA6E;QAC7E,MAAM,SAAS,GAAG,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACpE,2BAA2B,CAAC;YAC1B,GAAG,KAAK;YACR,UAAU,EAAE,QAAQ,CAAC,EAAE;YACvB,mBAAmB,EAAE,KAAK,CAAC,mBAAmB,CAAC,WAAW;YAC1D,sBAAsB,EAAE,KAAK,CAAC,mBAAmB,CAAC,cAAc;YAChE,oBAAoB,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;SAChD,CAAC,CACH,CAAC;QACF,OAAO,SAAS,IAAI,QAAQ,CAAC,WAAW;YACtC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,QAAQ,EAAE;YAC5B,CAAC,CAAC,SAAS,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,SAAS,CAAC,6BAA6B,CAAC,QAAQ,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC7E,OAAO;QACL,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,UAAU,EAAE,QAAQ,CAAC,EAAE;QACvB,cAAc;QACd,IAAI,EAAE,gBAAgB,CAAC,IAAI;QAC3B,QAAQ;QACR,gBAAgB;KACjB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport {\n acknowledgedDocumentCreate,\n persistedDocumentStateFromAcknowledgement,\n} from \"../../../data/documents/shared/responses\";\nimport { acknowledgeDocumentMutation } from \"../../../data/documents/shared/sync/mutationAcknowledgement\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../../data/documents/shared/types\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { nullOnProjectionVerificationCancellation } from \"../../../data/keyingProjectionVerification/types\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { adoptExistingRemoteDocument } from \"./createAdoption\";\nimport { documentWriterProjectionFromCreateResponse } from \"./createProjection\";\nimport type { DocumentSubmissionRequest } from \"./remoteDocumentCreateRequest\";\n\n/** A strict importer can only proceed after its exact birth update is acknowledged. */\nexport function assertRequiredSeedAcknowledged(\n request: DocumentSubmissionRequest,\n created: CreateRemoteDocumentResult | null,\n) {\n if (!request.requireSeededCreate) return;\n const accepted = created?.response?.initialSync?.acceptedOutgoingUpdateIds;\n if (!request.seedUpdate || !accepted?.includes(request.seedUpdate.id))\n throw new Error(\n \"The server did not acknowledge the initial document content.\",\n );\n}\n\n/** A matched acknowledgement remains committed if authorization evidence races. */\nexport async function acknowledgeRemoteDocumentCreate(\n input: {\n readonly apiClient: DocumentCreateApi;\n readonly author: DocumentCreateAuthor;\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly execSql: ExecSql;\n readonly materializedPlan: MaterializedDocumentCreatePlan;\n readonly resolveProjectionUserKey: ProjectionUserKeyResolver;\n readonly response: DocumentCreateResponse;\n readonly targetSecretKey: Uint8Array;\n } & ProjectionVerificationOptions,\n): Promise<CreateRemoteDocumentResult | null> {\n const { materializedPlan, response } = input;\n const acknowledged = acknowledgedDocumentCreate(\n materializedPlan.plan,\n response,\n );\n const persistedState =\n persistedDocumentStateFromAcknowledgement(acknowledged);\n await acknowledgeDocumentMutation({\n bundleDigest: response.bundleDigest,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n });\n if (input.stillCurrent?.() === false) return null;\n const writerProjection = documentWriterProjectionFromCreateResponse({\n containerProjection: input.containerProjection,\n response: acknowledged,\n });\n try {\n const targets = await nullOnProjectionVerificationCancellation(() =>\n assertDocumentWriterProjectionConsistent(writerProjection, input),\n );\n if (!targets || input.stillCurrent?.() === false) return null;\n } catch (error) {\n if (!(error instanceof ProjectionDependencyUnavailableError)) throw error;\n // A principal pin can advance while POST is in flight. Recover the already\n // committed document from fresh evidence, without submitting another create.\n // The adoption path still verifies its author, scope, chain and key binding.\n const recovered = await nullOnProjectionVerificationCancellation(() =>\n adoptExistingRemoteDocument({\n ...input,\n documentId: response.id,\n expectedContainerId: input.containerProjection.containerId,\n expectedOrganizationId: input.containerProjection.organizationId,\n expectedSignerUserId: input.author.signerUserId,\n }),\n );\n return recovered && response.initialSync\n ? { ...recovered, response }\n : recovered;\n }\n input.apiClient.primeDocumentWriterProjection(response.id, writerProjection);\n return {\n contentKey: materializedPlan.contentKey,\n documentId: response.id,\n persistedState,\n plan: materializedPlan.plan,\n response,\n writerProjection,\n };\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { DOCUMENT_SYNC_ERROR_CODES, } from "../../../internal/validators/response/index.js";
|
|
2
|
+
export function isStaleDocumentCreateTargetConflict(submission) {
|
|
3
|
+
return (!submission.ok &&
|
|
4
|
+
submission.status === 409 &&
|
|
5
|
+
submission.code === DOCUMENT_SYNC_ERROR_CODES.stateStale);
|
|
6
|
+
}
|
|
7
|
+
export async function submitDocumentCreate(apiClient, request, expectedOrganizationId, stillCurrent) {
|
|
8
|
+
return apiClient.createDocumentResult(request, {
|
|
9
|
+
expectedPaymentRequiredOrganizationId: expectedOrganizationId,
|
|
10
|
+
...(stillCurrent ? { stillCurrent } : {}),
|
|
11
|
+
reportErrors: false,
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=createSubmission.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createSubmission.js","sourceRoot":"","sources":["createSubmission.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AAgBxC,MAAM,UAAU,mCAAmC,CACjD,UAAoC;IAEpC,OAAO,CACL,CAAC,UAAU,CAAC,EAAE;QACd,UAAU,CAAC,MAAM,KAAK,GAAG;QACzB,UAAU,CAAC,IAAI,KAAK,yBAAyB,CAAC,UAAU,CACzD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,SAA4B,EAC5B,OAA8B,EAC9B,sBAA8B,EAC9B,YAAyC;IAEzC,OAAO,SAAS,CAAC,oBAAoB,CAAC,OAAO,EAAE;QAC7C,qCAAqC,EAAE,sBAAsB;QAC7D,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzC,YAAY,EAAE,KAAK;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentCreateRequest } from \"@tearleads/validators/request\";\nimport {\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentCreateResponse,\n} from \"@tearleads/validators/response\";\nimport type { DocumentCreateApi } from \"../../../data/documents/shared/types\";\n\nexport type DocumentCreateSubmission =\n | {\n readonly data: DocumentCreateResponse;\n readonly ok: true;\n }\n | {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report?: (() => void) | undefined;\n readonly status: number | null;\n };\n\nexport function isStaleDocumentCreateTargetConflict(\n submission: DocumentCreateSubmission,\n): boolean {\n return (\n !submission.ok &&\n submission.status === 409 &&\n submission.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\nexport async function submitDocumentCreate(\n apiClient: DocumentCreateApi,\n request: DocumentCreateRequest,\n expectedOrganizationId: string,\n stillCurrent: (() => boolean) | undefined,\n): Promise<DocumentCreateSubmission> {\n return apiClient.createDocumentResult(request, {\n expectedPaymentRequiredOrganizationId: expectedOrganizationId,\n ...(stillCurrent ? { stillCurrent } : {}),\n reportErrors: false,\n });\n}\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
|
|
2
2
|
import type { ProjectionVerificationOptions } from "../../../data/documents/shared/projection/projectionVerificationOptions.js";
|
|
3
3
|
import type { CreateRemoteDocumentResult, DocumentCreateAuthor, MaterializedDocumentCreatePlan } from "../../../data/documents/shared/types.js";
|
|
4
4
|
import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
|
|
5
5
|
import type { RemoteDocumentCollaborators } from "../remote/remoteDocumentCollaborators.js";
|
|
6
|
-
import type {
|
|
6
|
+
import type { DocumentSubmissionRequest } from "./remoteDocumentCreateRequest.js";
|
|
7
7
|
export declare function buildMaterializedDocumentCreatePlan(input: {
|
|
8
8
|
author: DocumentCreateAuthor;
|
|
9
9
|
containerProjection: ContainerWriterProjectionResponse;
|
|
@@ -19,15 +19,4 @@ export declare function buildMaterializedDocumentCreatePlan(input: {
|
|
|
19
19
|
} & ProjectionVerificationOptions): Promise<MaterializedDocumentCreatePlan>;
|
|
20
20
|
export { documentWriterProjectionFromCreateResponse } from "./createProjection.js";
|
|
21
21
|
/** Throws when the collaborators carry no encapsulation secret key. */
|
|
22
|
-
export declare function createRemoteDocument(remote: RemoteDocumentCollaborators, request:
|
|
23
|
-
type DocumentCreateSubmission = {
|
|
24
|
-
readonly data: DocumentCreateResponse;
|
|
25
|
-
readonly ok: true;
|
|
26
|
-
} | {
|
|
27
|
-
readonly code?: string | undefined;
|
|
28
|
-
readonly message: string;
|
|
29
|
-
readonly ok: false;
|
|
30
|
-
readonly report?: (() => void) | undefined;
|
|
31
|
-
readonly status: number | null;
|
|
32
|
-
};
|
|
33
|
-
export declare function isStaleDocumentCreateTargetConflict(submission: DocumentCreateSubmission): boolean;
|
|
22
|
+
export declare function createRemoteDocument(remote: RemoteDocumentCollaborators, request: DocumentSubmissionRequest): Promise<CreateRemoteDocumentResult | null>;
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { DOCUMENT_SYNC_ERROR_CODES, } from "../../../internal/validators/response/index.js";
|
|
2
1
|
import { assertContainerAuthorAccess } from "../../../data/containers/shared/authorAccess.js";
|
|
3
2
|
import { buildDocumentCreatePlan } from "../../../data/documents/shared/events.js";
|
|
4
3
|
import { wrapDocumentContentKeyForCreate } from "../../../data/documents/shared/projection/index.js";
|
|
@@ -12,7 +11,8 @@ import { buildDocumentCreateSeedRequest, documentCreateSeed, documentCreateSeedF
|
|
|
12
11
|
import { isDocumentManifestAlreadyExistsConflict } from "../syncFailures/syncFailureClassification.js";
|
|
13
12
|
import { adoptExistingRemoteDocument } from "./createAdoption.js";
|
|
14
13
|
import { fetchContainerWriterProjectionForCreate } from "./createProjectionFetch.js";
|
|
15
|
-
import { acknowledgeRemoteDocumentCreate } from "./createResponse.js";
|
|
14
|
+
import { acknowledgeRemoteDocumentCreate, assertRequiredSeedAcknowledged, } from "./createResponse.js";
|
|
15
|
+
import { isStaleDocumentCreateTargetConflict, submitDocumentCreate, } from "./createSubmission.js";
|
|
16
16
|
export async function buildMaterializedDocumentCreatePlan(input) {
|
|
17
17
|
const contentKey = input.contentKey ?? crypto.getRandomValues(new Uint8Array(32));
|
|
18
18
|
if (contentKey.byteLength !== 32) {
|
|
@@ -134,6 +134,8 @@ async function buildMaterializedDocumentCreatePlanWithFreshProjection(input) {
|
|
|
134
134
|
async function submitPlannedDocumentCreateRequest(input, createPlan) {
|
|
135
135
|
const request = createPlan.materializedPlan.plan.request;
|
|
136
136
|
const organizationId = createPlan.containerProjection.organizationId;
|
|
137
|
+
const canSubmit = () => input.stillCurrent?.() !== false &&
|
|
138
|
+
!isRemoteDocumentCreatePlanBlocked(input, createPlan);
|
|
137
139
|
const seed = input.seedUpdate
|
|
138
140
|
? await buildDocumentCreateSeedRequest({
|
|
139
141
|
author: input.author,
|
|
@@ -143,18 +145,25 @@ async function submitPlannedDocumentCreateRequest(input, createPlan) {
|
|
|
143
145
|
})
|
|
144
146
|
: null;
|
|
145
147
|
if (seed && documentCreateSeedFits(request, seed)) {
|
|
146
|
-
if (
|
|
148
|
+
if (!canSubmit())
|
|
147
149
|
return null;
|
|
148
|
-
const seeded = await submitDocumentCreate(input.apiClient, { ...request, initialSync: documentCreateSeed(seed) }, organizationId);
|
|
149
|
-
if (
|
|
150
|
+
const seeded = await submitDocumentCreate(input.apiClient, { ...request, initialSync: documentCreateSeed(seed) }, organizationId, canSubmit);
|
|
151
|
+
if (input.requireSeededCreate ||
|
|
152
|
+
seeded.ok ||
|
|
150
153
|
isDocumentManifestAlreadyExistsConflict(seeded) ||
|
|
151
154
|
isStaleDocumentCreateTargetConflict(seeded)) {
|
|
152
155
|
return seeded;
|
|
153
156
|
}
|
|
154
157
|
}
|
|
155
|
-
if (
|
|
158
|
+
if (!canSubmit())
|
|
156
159
|
return null;
|
|
157
|
-
|
|
160
|
+
if (input.requireSeededCreate)
|
|
161
|
+
return {
|
|
162
|
+
ok: false,
|
|
163
|
+
status: null,
|
|
164
|
+
message: "The initial document content must fit in one seeded create.",
|
|
165
|
+
};
|
|
166
|
+
return submitDocumentCreate(input.apiClient, request, organizationId, canSubmit);
|
|
158
167
|
}
|
|
159
168
|
function isRemoteDocumentCreatePlanBlocked(input, createPlan) {
|
|
160
169
|
const organizationId = createPlan.containerProjection.organizationId;
|
|
@@ -192,43 +201,43 @@ async function submitPlannedDocumentCreate(input, resolveProjectionUserKey) {
|
|
|
192
201
|
let submission = await submitPlannedDocumentCreateRequest(input, createPlan);
|
|
193
202
|
if (!submission)
|
|
194
203
|
return null;
|
|
195
|
-
if (isStaleDocumentCreateTargetConflict(submission))
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
}
|
|
199
|
-
input.apiClient.evictContainerWriterProjection(input.containerId);
|
|
200
|
-
const firstPlan = createPlan.materializedPlan;
|
|
201
|
-
const refreshedPlan = await buildMaterializedDocumentCreatePlanWithFreshProjection({
|
|
202
|
-
apiClient: input.apiClient,
|
|
203
|
-
author: input.author,
|
|
204
|
-
containerId: input.containerId,
|
|
205
|
-
contentKey: firstPlan.contentKey,
|
|
206
|
-
contentKeyEpoch: firstPlan.plan.request.contentKeyBundle.contentKeyEpoch,
|
|
207
|
-
documentId: firstPlan.plan.documentId,
|
|
208
|
-
eventId: firstPlan.plan.event.eventId,
|
|
209
|
-
execSql: input.execSql,
|
|
210
|
-
expectedOrganizationId: input.expectedOrganizationId,
|
|
211
|
-
knownContainerKeks: input.knownContainerKeks,
|
|
212
|
-
onTerminalSubmitFailure: input.onTerminalSubmitFailure,
|
|
213
|
-
resolveProjectionUserKey,
|
|
214
|
-
signedAt: firstPlan.plan.event.signedAt,
|
|
215
|
-
targetSecretKey: input.targetSecretKey,
|
|
216
|
-
warmReferencedPrincipalPolicies,
|
|
217
|
-
...verificationOptions,
|
|
218
|
-
});
|
|
219
|
-
if (!refreshedPlan) {
|
|
220
|
-
return null;
|
|
221
|
-
}
|
|
222
|
-
if (isRemoteDocumentCreatePlanBlocked(input, refreshedPlan))
|
|
223
|
-
return null;
|
|
224
|
-
createPlan = refreshedPlan;
|
|
225
|
-
if (input.stillCurrent?.() === false)
|
|
226
|
-
return null;
|
|
227
|
-
submission = await submitPlannedDocumentCreateRequest(input, createPlan);
|
|
228
|
-
if (!submission)
|
|
229
|
-
return null;
|
|
204
|
+
if (!isStaleDocumentCreateTargetConflict(submission))
|
|
205
|
+
return { createPlan, submission };
|
|
206
|
+
if (input.stillCurrent?.() === false) {
|
|
207
|
+
return { createPlan, submission };
|
|
230
208
|
}
|
|
231
|
-
|
|
209
|
+
input.apiClient.evictContainerWriterProjection(input.containerId);
|
|
210
|
+
const firstPlan = createPlan.materializedPlan;
|
|
211
|
+
const refreshedPlan = await buildMaterializedDocumentCreatePlanWithFreshProjection({
|
|
212
|
+
apiClient: input.apiClient,
|
|
213
|
+
author: input.author,
|
|
214
|
+
containerId: input.containerId,
|
|
215
|
+
contentKey: firstPlan.contentKey,
|
|
216
|
+
contentKeyEpoch: firstPlan.plan.request.contentKeyBundle.contentKeyEpoch,
|
|
217
|
+
documentId: firstPlan.plan.documentId,
|
|
218
|
+
eventId: firstPlan.plan.event.eventId,
|
|
219
|
+
execSql: input.execSql,
|
|
220
|
+
expectedOrganizationId: input.expectedOrganizationId,
|
|
221
|
+
knownContainerKeks: input.knownContainerKeks,
|
|
222
|
+
onTerminalSubmitFailure: input.onTerminalSubmitFailure,
|
|
223
|
+
resolveProjectionUserKey,
|
|
224
|
+
signedAt: firstPlan.plan.event.signedAt,
|
|
225
|
+
targetSecretKey: input.targetSecretKey,
|
|
226
|
+
warmReferencedPrincipalPolicies,
|
|
227
|
+
...verificationOptions,
|
|
228
|
+
});
|
|
229
|
+
if (!refreshedPlan) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
if (isRemoteDocumentCreatePlanBlocked(input, refreshedPlan))
|
|
233
|
+
return null;
|
|
234
|
+
createPlan = refreshedPlan;
|
|
235
|
+
if (input.stillCurrent?.() === false)
|
|
236
|
+
return null;
|
|
237
|
+
submission = await submitPlannedDocumentCreateRequest(input, createPlan);
|
|
238
|
+
if (!submission)
|
|
239
|
+
return null;
|
|
240
|
+
return { createPlan, submission, retriedStaleTarget: true };
|
|
232
241
|
}
|
|
233
242
|
/**
|
|
234
243
|
* Signs the deferred first update against the plan the server just accepted,
|
|
@@ -248,6 +257,22 @@ async function withDeferredSeed(created, createPlan, input) {
|
|
|
248
257
|
? { ...created, deferredSeed }
|
|
249
258
|
: created;
|
|
250
259
|
}
|
|
260
|
+
async function settleSubmittedCreate(input, createPlan, resolveProjectionUserKey, response, retriedStaleTarget) {
|
|
261
|
+
const created = await acknowledgeRemoteDocumentCreate({
|
|
262
|
+
...input,
|
|
263
|
+
...createPlan,
|
|
264
|
+
resolveProjectionUserKey,
|
|
265
|
+
response,
|
|
266
|
+
});
|
|
267
|
+
assertRequiredSeedAcknowledged(input, created);
|
|
268
|
+
if (input.stillCurrent?.() === false)
|
|
269
|
+
return null;
|
|
270
|
+
if (created && retriedStaleTarget)
|
|
271
|
+
input.onRecoveredStaleTarget?.();
|
|
272
|
+
return created && input.deferredSeedUpdate
|
|
273
|
+
? withDeferredSeed(created, createPlan, input)
|
|
274
|
+
: created;
|
|
275
|
+
}
|
|
251
276
|
/** Throws when the collaborators carry no encapsulation secret key. */
|
|
252
277
|
export async function createRemoteDocument(remote, request) {
|
|
253
278
|
if (!remote.encapsulationSecretKey) {
|
|
@@ -272,24 +297,17 @@ export async function createRemoteDocument(remote, request) {
|
|
|
272
297
|
const { createPlan, submission } = plannedSubmission;
|
|
273
298
|
if (input.stillCurrent?.() === false)
|
|
274
299
|
return null;
|
|
275
|
-
if (submission.ok)
|
|
276
|
-
|
|
277
|
-
...input,
|
|
278
|
-
...createPlan,
|
|
279
|
-
resolveProjectionUserKey,
|
|
280
|
-
response: submission.data,
|
|
281
|
-
});
|
|
282
|
-
return created && input.deferredSeedUpdate
|
|
283
|
-
? withDeferredSeed(created, createPlan, input)
|
|
284
|
-
: created;
|
|
285
|
-
}
|
|
300
|
+
if (submission.ok)
|
|
301
|
+
return settleSubmittedCreate(input, createPlan, resolveProjectionUserKey, submission.data, plannedSubmission.retriedStaleTarget);
|
|
286
302
|
// A stable documentId means a retry after a lost create response re-submits
|
|
287
303
|
// the same id; the server then reports the manifest already exists. That is
|
|
288
304
|
// not a failure — the first attempt committed. Adopt the existing remote
|
|
289
305
|
// document instead of leaking a duplicate. Requires the stable id we sent, so
|
|
290
306
|
// we can fetch its projection back.
|
|
291
307
|
const stableDocumentId = input.documentId;
|
|
292
|
-
if (stableDocumentId &&
|
|
308
|
+
if (stableDocumentId &&
|
|
309
|
+
!input.requireSeededCreate &&
|
|
310
|
+
isDocumentManifestAlreadyExistsConflict(submission)) {
|
|
293
311
|
if (input.stillCurrent?.() === false)
|
|
294
312
|
return null;
|
|
295
313
|
const adopted = await nullOnProjectionVerificationCancellation(() => adoptExistingRemoteDocument({
|
|
@@ -314,19 +332,10 @@ export async function createRemoteDocument(remote, request) {
|
|
|
314
332
|
// error — the sync engine retries and adopts it on a later tick.
|
|
315
333
|
return null;
|
|
316
334
|
}
|
|
317
|
-
|
|
335
|
+
// Create-only callers handle the refusal directly, including a verified purge.
|
|
336
|
+
if (!input.requireSeededCreate)
|
|
337
|
+
submission.report?.();
|
|
318
338
|
await input.onTerminalSubmitFailure?.(submission);
|
|
319
339
|
return null;
|
|
320
340
|
}
|
|
321
|
-
export function isStaleDocumentCreateTargetConflict(submission) {
|
|
322
|
-
return (!submission.ok &&
|
|
323
|
-
submission.status === 409 &&
|
|
324
|
-
submission.code === DOCUMENT_SYNC_ERROR_CODES.stateStale);
|
|
325
|
-
}
|
|
326
|
-
async function submitDocumentCreate(apiClient, request, expectedOrganizationId) {
|
|
327
|
-
return apiClient.createDocumentResult(request, {
|
|
328
|
-
expectedPaymentRequiredOrganizationId: expectedOrganizationId,
|
|
329
|
-
reportErrors: false,
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
341
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,EAAE,+BAA+B,EAAE,MAAM,2CAA2C,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,gEAAgE,CAAC;AAEhH,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAWxH,OAAO,EACL,iDAAiD,EACjD,wCAAwC,EACxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,wBAAwB,EAAE,MAAM,4DAA4D,CAAC;AACtG,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAE5H,OAAO,EAAE,iCAAiC,EAAE,MAAM,wBAAwB,CAAC;AAE3E,OAAO,EACL,8BAA8B,EAC9B,kBAAkB,EAClB,sBAAs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AU,CAAC,IAAI,KAAK,yBAAyB,CAAC,UAAU,CACzD,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,oBAAoB,CACjC,SAA4B,EAC5B,OAA8B,EAC9B,sBAA8B;IAE9B,OAAO,SAAS,CAAC,oBAAoB,CAAC,OAAO,EAAE;QAC7C,qCAAqC,EAAE,sBAAsB;QAC7D,YAAY,EAAE,KAAK;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentCreateRequest } from \"@tearleads/validators/request\";\nimport {\n type ContainerWriterProjectionResponse,\n DOCUMENT_SYNC_ERROR_CODES,\n type DocumentCreateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertContainerAuthorAccess } from \"../../../data/containers/shared/authorAccess\";\nimport { buildDocumentCreatePlan } from \"../../../data/documents/shared/events\";\nimport { wrapDocumentContentKeyForCreate } from \"../../../data/documents/shared/projection\";\nimport { shouldRetryWithFreshProjection } from \"../../../data/documents/shared/projection/freshProjectionRetry\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../../data/documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n nullOnProjectionVerificationCancellation,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { isContainerCreatePending } from \"../../../data/persistence/documents/pendingContainerCreate\";\nimport { openPrincipalPolicyBundleReader } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport {\n buildDocumentCreateSeedRequest,\n documentCreateSeed,\n documentCreateSeedFits,\n documentSyncFits,\n} from \"../sync/initialSync\";\nimport { isDocumentManifestAlreadyExistsConflict } from \"../syncFailures/syncFailureClassification\";\nimport { adoptExistingRemoteDocument } from \"./createAdoption\";\nimport type { DocumentCreateTerminalFailureHandler } from \"./createProjectionFetch\";\nimport { fetchContainerWriterProjectionForCreate } from \"./createProjectionFetch\";\nimport { acknowledgeRemoteDocumentCreate } from \"./createResponse\";\nimport type {\n CreateRemoteDocumentRequest,\n RemoteDocumentCreateInput,\n} from \"./remoteDocumentCreateRequest\";\n\nexport async function buildMaterializedDocumentCreatePlan(\n input: {\n author: DocumentCreateAuthor;\n containerProjection: ContainerWriterProjectionResponse;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId?: string | undefined;\n eventId?: string | undefined;\n execSql?: ExecSql | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentCreatePlan> {\n const contentKey =\n input.contentKey ?? crypto.getRandomValues(new Uint8Array(32));\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Document content key must be 32 bytes\");\n }\n // Resolved before wrapping: each envelope is sealed to its document and\n // content-key epoch.\n const documentId = input.documentId ?? crypto.randomUUID();\n const contentKeyEpoch = input.contentKeyEpoch ?? 1;\n const targetEnvelopes = await wrapDocumentContentKeyForCreate({\n contentKey,\n contentKeyEpoch,\n documentId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n projection: input.containerProjection,\n secretKey: input.targetSecretKey,\n ...projectionVerificationOptions(input),\n });\n if (input.resolveProjectionUserKey) {\n const principalPolicies =\n await collectContainerWriterProjectionPrincipalPolicies({\n ...projectionVerificationOptions(input),\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n projection: input.containerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n });\n assertContainerAuthorAccess({\n // Document signing derives its organization from the verified target.\n author: {\n ...input.author,\n organizationId: input.containerProjection.organizationId,\n },\n projection: input.containerProjection,\n principalPolicies,\n minimumAccess: \"write\",\n });\n }\n // The explicit local-trust variant builds provisioning artifacts before\n // their new principal policies exist remotely; remote creates cannot use it.\n const plan = await buildDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n contentKeyEpoch,\n documentId,\n ...(input.eventId === undefined ? {} : { eventId: input.eventId }),\n ...(input.signedAt === undefined ? {} : { signedAt: input.signedAt }),\n targetEnvelopes,\n });\n\n return {\n contentKey,\n plan,\n };\n}\n\nexport { documentWriterProjectionFromCreateResponse } from \"./createProjection\";\n\ninterface MaterializedDocumentCreatePlanWithProjection {\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly materializedPlan: MaterializedDocumentCreatePlan;\n}\n\nasync function buildMaterializedDocumentCreatePlanWithFreshProjection(input: {\n apiClient: DocumentCreateApi;\n author: DocumentCreateAuthor;\n containerId: string;\n containerProjection?: ContainerWriterProjectionResponse | undefined;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId?: string | undefined;\n eventId?: string | undefined;\n execSql: ExecSql;\n expectedOrganizationId?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n onTerminalSubmitFailure?: DocumentCreateTerminalFailureHandler | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<MaterializedDocumentCreatePlanWithProjection | null> {\n const buildWithProjection = async (\n containerProjection: ContainerWriterProjectionResponse,\n ) => {\n if (\n containerProjection.containerId !== input.containerId ||\n (input.expectedOrganizationId !== undefined &&\n containerProjection.organizationId !== input.expectedOrganizationId)\n ) {\n throw new Error(\n \"Container writer projection belongs to another container or organization\",\n );\n }\n return {\n containerProjection,\n materializedPlan: await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n };\n };\n\n const containerProjection =\n input.containerProjection ??\n (await fetchContainerWriterProjectionForCreate({\n apiClient: input.apiClient,\n containerId: input.containerId,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n }));\n if (!containerProjection) {\n return null;\n }\n\n try {\n return await buildWithProjection(containerProjection);\n } catch (error) {\n if (\n !shouldRetryWithFreshProjection(error, (message) =>\n message.includes(\"could not be unwrapped\"),\n )\n ) {\n throw error;\n }\n }\n\n // Only this container's projection was stale; evict just it rather than\n // wiping every cached projection.\n input.apiClient.evictContainerWriterProjection(input.containerId);\n const refreshedProjection = await fetchContainerWriterProjectionForCreate({\n apiClient: input.apiClient,\n containerId: input.containerId,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n });\n return refreshedProjection ? buildWithProjection(refreshedProjection) : null;\n}\n\n/**\n * A seed only saves the first sync. A refusal of the seeded create falls back\n * to the plain create once, so the row syncs as before and seeding adds no\n * failure mode. A lost response is adopted, and a stale target is replanned\n * with a fresh seed, exactly as for a plain create. Building the seed awaits\n * its encryption, so each submission rechecks the caller is still current and\n * returns null instead of creating a document whose response would be dropped.\n */\nasync function submitPlannedDocumentCreateRequest(\n input: RemoteDocumentCreateInput,\n createPlan: MaterializedDocumentCreatePlanWithProjection,\n): Promise<DocumentCreateSubmission | null> {\n const request = createPlan.materializedPlan.plan.request;\n const organizationId = createPlan.containerProjection.organizationId;\n const seed = input.seedUpdate\n ? await buildDocumentCreateSeedRequest({\n author: input.author,\n containerProjection: createPlan.containerProjection,\n materializedDocument: createPlan.materializedPlan,\n pendingUpdate: input.seedUpdate,\n })\n : null;\n if (seed && documentCreateSeedFits(request, seed)) {\n if (input.stillCurrent?.() === false) return null;\n const seeded = await submitDocumentCreate(\n input.apiClient,\n { ...request, initialSync: documentCreateSeed(seed) },\n organizationId,\n );\n if (\n seeded.ok ||\n isDocumentManifestAlreadyExistsConflict(seeded) ||\n isStaleDocumentCreateTargetConflict(seeded)\n ) {\n return seeded;\n }\n }\n if (input.stillCurrent?.() === false) return null;\n return submitDocumentCreate(input.apiClient, request, organizationId);\n}\n\nfunction isRemoteDocumentCreatePlanBlocked(\n input: RemoteDocumentCreateInput,\n createPlan: MaterializedDocumentCreatePlanWithProjection,\n): boolean {\n const organizationId = createPlan.containerProjection.organizationId;\n return input.isRemoteSyncBlocked?.(organizationId) ?? false;\n}\n\nasync function submitPlannedDocumentCreate(\n input: RemoteDocumentCreateInput,\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<{\n readonly createPlan: MaterializedDocumentCreatePlanWithProjection;\n readonly submission: DocumentCreateSubmission;\n} | null> {\n const verificationOptions = { stillCurrent: input.stillCurrent };\n const warmReferencedPrincipalPolicies = input.warmReferencedPrincipalPolicies;\n let createPlan = await buildMaterializedDocumentCreatePlanWithFreshProjection(\n {\n apiClient: input.apiClient,\n author: input.author,\n containerId: input.containerId,\n containerProjection: input.containerProjection,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n eventId: input.eventId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n knownContainerKeks: input.knownContainerKeks,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies,\n ...verificationOptions,\n },\n );\n if (!createPlan) {\n return null;\n }\n if (isRemoteDocumentCreatePlanBlocked(input, createPlan)) return null;\n if (input.stillCurrent?.() === false) return null;\n let submission = await submitPlannedDocumentCreateRequest(input, createPlan);\n if (!submission) return null;\n if (isStaleDocumentCreateTargetConflict(submission)) {\n if (input.stillCurrent?.() === false) {\n return { createPlan, submission };\n }\n input.apiClient.evictContainerWriterProjection(input.containerId);\n const firstPlan = createPlan.materializedPlan;\n const refreshedPlan =\n await buildMaterializedDocumentCreatePlanWithFreshProjection({\n apiClient: input.apiClient,\n author: input.author,\n containerId: input.containerId,\n contentKey: firstPlan.contentKey,\n contentKeyEpoch:\n firstPlan.plan.request.contentKeyBundle.contentKeyEpoch,\n documentId: firstPlan.plan.documentId,\n eventId: firstPlan.plan.event.eventId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n knownContainerKeks: input.knownContainerKeks,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n resolveProjectionUserKey,\n signedAt: firstPlan.plan.event.signedAt,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies,\n ...verificationOptions,\n });\n if (!refreshedPlan) {\n return null;\n }\n if (isRemoteDocumentCreatePlanBlocked(input, refreshedPlan)) return null;\n createPlan = refreshedPlan;\n if (input.stillCurrent?.() === false) return null;\n submission = await submitPlannedDocumentCreateRequest(input, createPlan);\n if (!submission) return null;\n }\n return { createPlan, submission };\n}\n\n/**\n * Signs the deferred first update against the plan the server just accepted,\n * without sending it, so the attachment bind that must precede it can carry\n * it. One that would not fit a sync request is left to sync on its own.\n */\nasync function withDeferredSeed(\n created: CreateRemoteDocumentResult,\n createPlan: MaterializedDocumentCreatePlanWithProjection,\n input: RemoteDocumentCreateInput,\n): Promise<CreateRemoteDocumentResult> {\n if (!input.deferredSeedUpdate) return created;\n const deferredSeed = await buildDocumentCreateSeedRequest({\n author: input.author,\n containerProjection: createPlan.containerProjection,\n materializedDocument: createPlan.materializedPlan,\n pendingUpdate: input.deferredSeedUpdate,\n });\n return documentSyncFits(deferredSeed)\n ? { ...created, deferredSeed }\n : created;\n}\n\n/** Throws when the collaborators carry no encapsulation secret key. */\nexport async function createRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: CreateRemoteDocumentRequest,\n): Promise<CreateRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\"Remote document create requires an encapsulation key\");\n }\n const input: RemoteDocumentCreateInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n isRemoteSyncBlocked: remote.isRemoteSyncBlocked,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n // The store retries once the folder's own create settles.\n if (await isContainerCreatePending(input.execSql, input.containerId)) {\n return null;\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document create\",\n );\n const plannedSubmission = await recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n submitPlannedDocumentCreate(input, resolveProjectionUserKey),\n ),\n input.onTerminalSubmitFailure,\n );\n if (!plannedSubmission) {\n return null;\n }\n const { createPlan, submission } = plannedSubmission;\n if (input.stillCurrent?.() === false) return null;\n if (submission.ok) {\n const created = await acknowledgeRemoteDocumentCreate({\n ...input,\n ...createPlan,\n resolveProjectionUserKey,\n response: submission.data,\n });\n return created && input.deferredSeedUpdate\n ? withDeferredSeed(created, createPlan, input)\n : created;\n }\n\n // A stable documentId means a retry after a lost create response re-submits\n // the same id; the server then reports the manifest already exists. That is\n // not a failure — the first attempt committed. Adopt the existing remote\n // document instead of leaking a duplicate. Requires the stable id we sent, so\n // we can fetch its projection back.\n const stableDocumentId = input.documentId;\n if (stableDocumentId && isDocumentManifestAlreadyExistsConflict(submission)) {\n if (input.stillCurrent?.() === false) return null;\n const adopted = await nullOnProjectionVerificationCancellation(() =>\n adoptExistingRemoteDocument({\n apiClient: input.apiClient,\n documentId: stableDocumentId,\n execSql: input.execSql,\n expectedContainerId: input.containerId,\n expectedOrganizationId:\n input.expectedOrganizationId ??\n createPlan.containerProjection.organizationId,\n expectedSignerUserId: input.author.signerUserId,\n resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n );\n if (adopted) {\n return adopted;\n }\n // A conflict is the expected, benign outcome of an idempotent retry after a\n // lost create response. If adoption cannot complete yet (e.g. the writer\n // projection fetch failed transiently), do not surface the conflict as a UI\n // error — the sync engine retries and adopts it on a later tick.\n return null;\n }\n\n submission.report?.();\n await input.onTerminalSubmitFailure?.(submission);\n return null;\n}\n\ntype DocumentCreateSubmission =\n | {\n readonly data: DocumentCreateResponse;\n readonly ok: true;\n }\n | {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report?: (() => void) | undefined;\n readonly status: number | null;\n };\n\nexport function isStaleDocumentCreateTargetConflict(\n submission: DocumentCreateSubmission,\n): boolean {\n return (\n !submission.ok &&\n submission.status === 409 &&\n submission.code === DOCUMENT_SYNC_ERROR_CODES.stateStale\n );\n}\n\nasync function submitDocumentCreate(\n apiClient: DocumentCreateApi,\n request: DocumentCreateRequest,\n expectedOrganizationId: string,\n): Promise<DocumentCreateSubmission> {\n return apiClient.createDocumentResult(request, {\n expectedPaymentRequiredOrganizationId: expectedOrganizationId,\n reportErrors: false,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,EAAE,+BAA+B,EAAE,MAAM,2CAA2C,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,gEAAgE,CA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;IACzE,8EAA8E;IAC9E,oCAAoC;IACpC,MAAM,gBAAgB,GAAG,KAAK,CAAC,UAAU,CAAC;IAC1C,IACE,gBAAgB;QAChB,CAAC,KAAK,CAAC,mBAAmB;QAC1B,uCAAuC,CAAC,UAAU,CAAC,EACnD,CAAC;QACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAClD,MAAM,OAAO,GAAG,MAAM,wCAAwC,CAAC,GAAG,EAAE,CAClE,2BAA2B,CAAC;YAC1B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,UAAU,EAAE,gBAAgB;YAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,mBAAmB,EAAE,KAAK,CAAC,WAAW;YACtC,sBAAsB,EACpB,KAAK,CAAC,sBAAsB;gBAC5B,UAAU,CAAC,mBAAmB,CAAC,cAAc;YAC/C,oBAAoB,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;YAC/C,wBAAwB;YACxB,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;SACvE,CAAC,CACH,CAAC;QACF,IAAI,OAAO,EAAE,CAAC;YACZ,OAAO,OAAO,CAAC;QACjB,CAAC;QACD,4EAA4E;QAC5E,yEAAyE;QACzE,4EAA4E;QAC5E,iEAAiE;QACjE,OAAO,IAAI,CAAC;IACd,CAAC;IAED,+EAA+E;IAC/E,IAAI,CAAC,KAAK,CAAC,mBAAmB;QAAE,UAAU,CAAC,MAAM,EAAE,EAAE,CAAC;IACtD,MAAM,KAAK,CAAC,uBAAuB,EAAE,CAAC,UAAU,CAAC,CAAC;IAClD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n DocumentCreateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertContainerAuthorAccess } from \"../../../data/containers/shared/authorAccess\";\nimport { buildDocumentCreatePlan } from \"../../../data/documents/shared/events\";\nimport { wrapDocumentContentKeyForCreate } from \"../../../data/documents/shared/projection\";\nimport { shouldRetryWithFreshProjection } from \"../../../data/documents/shared/projection/freshProjectionRetry\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type {\n CreateRemoteDocumentResult,\n DocumentCreateApi,\n DocumentCreateAuthor,\n MaterializedDocumentCreatePlan,\n} from \"../../../data/documents/shared/types\";\nimport type {\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification\";\nimport {\n collectContainerWriterProjectionPrincipalPolicies,\n nullOnProjectionVerificationCancellation,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { isContainerCreatePending } from \"../../../data/persistence/documents/pendingContainerCreate\";\nimport { openPrincipalPolicyBundleReader } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { recordDocumentAuthorAccessFailure } from \"../authorAccessFailure\";\nimport type { RemoteDocumentCollaborators } from \"../remote/remoteDocumentCollaborators\";\nimport {\n buildDocumentCreateSeedRequest,\n documentCreateSeed,\n documentCreateSeedFits,\n documentSyncFits,\n} from \"../sync/initialSync\";\nimport { isDocumentManifestAlreadyExistsConflict } from \"../syncFailures/syncFailureClassification\";\nimport { adoptExistingRemoteDocument } from \"./createAdoption\";\nimport type { DocumentCreateTerminalFailureHandler } from \"./createProjectionFetch\";\nimport { fetchContainerWriterProjectionForCreate } from \"./createProjectionFetch\";\nimport {\n acknowledgeRemoteDocumentCreate,\n assertRequiredSeedAcknowledged,\n} from \"./createResponse\";\nimport {\n type DocumentCreateSubmission,\n isStaleDocumentCreateTargetConflict,\n submitDocumentCreate,\n} from \"./createSubmission\";\nimport type {\n DocumentSubmissionRequest,\n RemoteDocumentCreateInput,\n} from \"./remoteDocumentCreateRequest\";\n\nexport async function buildMaterializedDocumentCreatePlan(\n input: {\n author: DocumentCreateAuthor;\n containerProjection: ContainerWriterProjectionResponse;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId?: string | undefined;\n eventId?: string | undefined;\n execSql?: ExecSql | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n } & ProjectionVerificationOptions,\n): Promise<MaterializedDocumentCreatePlan> {\n const contentKey =\n input.contentKey ?? crypto.getRandomValues(new Uint8Array(32));\n if (contentKey.byteLength !== 32) {\n throw new Error(\"Document content key must be 32 bytes\");\n }\n // Resolved before wrapping: each envelope is sealed to its document and\n // content-key epoch.\n const documentId = input.documentId ?? crypto.randomUUID();\n const contentKeyEpoch = input.contentKeyEpoch ?? 1;\n const targetEnvelopes = await wrapDocumentContentKeyForCreate({\n contentKey,\n contentKeyEpoch,\n documentId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n projection: input.containerProjection,\n secretKey: input.targetSecretKey,\n ...projectionVerificationOptions(input),\n });\n if (input.resolveProjectionUserKey) {\n const principalPolicies =\n await collectContainerWriterProjectionPrincipalPolicies({\n ...projectionVerificationOptions(input),\n execSql: input.execSql,\n openPrincipalPolicyBundleReader,\n projection: input.containerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n });\n assertContainerAuthorAccess({\n // Document signing derives its organization from the verified target.\n author: {\n ...input.author,\n organizationId: input.containerProjection.organizationId,\n },\n projection: input.containerProjection,\n principalPolicies,\n minimumAccess: \"write\",\n });\n }\n // The explicit local-trust variant builds provisioning artifacts before\n // their new principal policies exist remotely; remote creates cannot use it.\n const plan = await buildDocumentCreatePlan({\n author: input.author,\n containerProjection: input.containerProjection,\n contentKeyEpoch,\n documentId,\n ...(input.eventId === undefined ? {} : { eventId: input.eventId }),\n ...(input.signedAt === undefined ? {} : { signedAt: input.signedAt }),\n targetEnvelopes,\n });\n\n return {\n contentKey,\n plan,\n };\n}\n\nexport { documentWriterProjectionFromCreateResponse } from \"./createProjection\";\n\ninterface MaterializedDocumentCreatePlanWithProjection {\n readonly containerProjection: ContainerWriterProjectionResponse;\n readonly materializedPlan: MaterializedDocumentCreatePlan;\n}\n\nasync function buildMaterializedDocumentCreatePlanWithFreshProjection(input: {\n apiClient: DocumentCreateApi;\n author: DocumentCreateAuthor;\n containerId: string;\n containerProjection?: ContainerWriterProjectionResponse | undefined;\n contentKey?: Uint8Array | undefined;\n contentKeyEpoch?: number | undefined;\n documentId?: string | undefined;\n eventId?: string | undefined;\n execSql: ExecSql;\n expectedOrganizationId?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n onTerminalSubmitFailure?: DocumentCreateTerminalFailureHandler | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<MaterializedDocumentCreatePlanWithProjection | null> {\n const buildWithProjection = async (\n containerProjection: ContainerWriterProjectionResponse,\n ) => {\n if (\n containerProjection.containerId !== input.containerId ||\n (input.expectedOrganizationId !== undefined &&\n containerProjection.organizationId !== input.expectedOrganizationId)\n ) {\n throw new Error(\n \"Container writer projection belongs to another container or organization\",\n );\n }\n return {\n containerProjection,\n materializedPlan: await buildMaterializedDocumentCreatePlan({\n author: input.author,\n containerProjection,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n };\n };\n\n const containerProjection =\n input.containerProjection ??\n (await fetchContainerWriterProjectionForCreate({\n apiClient: input.apiClient,\n containerId: input.containerId,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n }));\n if (!containerProjection) {\n return null;\n }\n\n try {\n return await buildWithProjection(containerProjection);\n } catch (error) {\n if (\n !shouldRetryWithFreshProjection(error, (message) =>\n message.includes(\"could not be unwrapped\"),\n )\n ) {\n throw error;\n }\n }\n\n // Only this container's projection was stale; evict just it rather than\n // wiping every cached projection.\n input.apiClient.evictContainerWriterProjection(input.containerId);\n const refreshedProjection = await fetchContainerWriterProjectionForCreate({\n apiClient: input.apiClient,\n containerId: input.containerId,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n });\n return refreshedProjection ? buildWithProjection(refreshedProjection) : null;\n}\n\n/**\n * A seed only saves the first sync. A refusal of the seeded create falls back\n * to the plain create once, so the row syncs as before and seeding adds no\n * failure mode. A lost response is adopted, and a stale target is replanned\n * with a fresh seed, exactly as for a plain create. Building the seed awaits\n * its encryption, so each submission rechecks the caller is still current and\n * returns null instead of creating a document whose response would be dropped.\n */\nasync function submitPlannedDocumentCreateRequest(\n input: RemoteDocumentCreateInput,\n createPlan: MaterializedDocumentCreatePlanWithProjection,\n): Promise<DocumentCreateSubmission | null> {\n const request = createPlan.materializedPlan.plan.request;\n const organizationId = createPlan.containerProjection.organizationId;\n const canSubmit = () =>\n input.stillCurrent?.() !== false &&\n !isRemoteDocumentCreatePlanBlocked(input, createPlan);\n const seed = input.seedUpdate\n ? await buildDocumentCreateSeedRequest({\n author: input.author,\n containerProjection: createPlan.containerProjection,\n materializedDocument: createPlan.materializedPlan,\n pendingUpdate: input.seedUpdate,\n })\n : null;\n if (seed && documentCreateSeedFits(request, seed)) {\n if (!canSubmit()) return null;\n const seeded = await submitDocumentCreate(\n input.apiClient,\n { ...request, initialSync: documentCreateSeed(seed) },\n organizationId,\n canSubmit,\n );\n if (\n input.requireSeededCreate ||\n seeded.ok ||\n isDocumentManifestAlreadyExistsConflict(seeded) ||\n isStaleDocumentCreateTargetConflict(seeded)\n ) {\n return seeded;\n }\n }\n if (!canSubmit()) return null;\n if (input.requireSeededCreate)\n return {\n ok: false,\n status: null,\n message: \"The initial document content must fit in one seeded create.\",\n };\n return submitDocumentCreate(\n input.apiClient,\n request,\n organizationId,\n canSubmit,\n );\n}\n\nfunction isRemoteDocumentCreatePlanBlocked(\n input: RemoteDocumentCreateInput,\n createPlan: MaterializedDocumentCreatePlanWithProjection,\n): boolean {\n const organizationId = createPlan.containerProjection.organizationId;\n return input.isRemoteSyncBlocked?.(organizationId) ?? false;\n}\n\nasync function submitPlannedDocumentCreate(\n input: RemoteDocumentCreateInput,\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<{\n readonly createPlan: MaterializedDocumentCreatePlanWithProjection;\n readonly retriedStaleTarget?: boolean;\n readonly submission: DocumentCreateSubmission;\n} | null> {\n const verificationOptions = { stillCurrent: input.stillCurrent };\n const warmReferencedPrincipalPolicies = input.warmReferencedPrincipalPolicies;\n let createPlan = await buildMaterializedDocumentCreatePlanWithFreshProjection(\n {\n apiClient: input.apiClient,\n author: input.author,\n containerId: input.containerId,\n containerProjection: input.containerProjection,\n contentKey: input.contentKey,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n eventId: input.eventId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n knownContainerKeks: input.knownContainerKeks,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies,\n ...verificationOptions,\n },\n );\n if (!createPlan) {\n return null;\n }\n if (isRemoteDocumentCreatePlanBlocked(input, createPlan)) return null;\n if (input.stillCurrent?.() === false) return null;\n let submission = await submitPlannedDocumentCreateRequest(input, createPlan);\n if (!submission) return null;\n if (!isStaleDocumentCreateTargetConflict(submission))\n return { createPlan, submission };\n if (input.stillCurrent?.() === false) {\n return { createPlan, submission };\n }\n input.apiClient.evictContainerWriterProjection(input.containerId);\n const firstPlan = createPlan.materializedPlan;\n const refreshedPlan =\n await buildMaterializedDocumentCreatePlanWithFreshProjection({\n apiClient: input.apiClient,\n author: input.author,\n containerId: input.containerId,\n contentKey: firstPlan.contentKey,\n contentKeyEpoch: firstPlan.plan.request.contentKeyBundle.contentKeyEpoch,\n documentId: firstPlan.plan.documentId,\n eventId: firstPlan.plan.event.eventId,\n execSql: input.execSql,\n expectedOrganizationId: input.expectedOrganizationId,\n knownContainerKeks: input.knownContainerKeks,\n onTerminalSubmitFailure: input.onTerminalSubmitFailure,\n resolveProjectionUserKey,\n signedAt: firstPlan.plan.event.signedAt,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies,\n ...verificationOptions,\n });\n if (!refreshedPlan) {\n return null;\n }\n if (isRemoteDocumentCreatePlanBlocked(input, refreshedPlan)) return null;\n createPlan = refreshedPlan;\n if (input.stillCurrent?.() === false) return null;\n submission = await submitPlannedDocumentCreateRequest(input, createPlan);\n if (!submission) return null;\n return { createPlan, submission, retriedStaleTarget: true };\n}\n\n/**\n * Signs the deferred first update against the plan the server just accepted,\n * without sending it, so the attachment bind that must precede it can carry\n * it. One that would not fit a sync request is left to sync on its own.\n */\nasync function withDeferredSeed(\n created: CreateRemoteDocumentResult,\n createPlan: MaterializedDocumentCreatePlanWithProjection,\n input: RemoteDocumentCreateInput,\n): Promise<CreateRemoteDocumentResult> {\n if (!input.deferredSeedUpdate) return created;\n const deferredSeed = await buildDocumentCreateSeedRequest({\n author: input.author,\n containerProjection: createPlan.containerProjection,\n materializedDocument: createPlan.materializedPlan,\n pendingUpdate: input.deferredSeedUpdate,\n });\n return documentSyncFits(deferredSeed)\n ? { ...created, deferredSeed }\n : created;\n}\n\nasync function settleSubmittedCreate(\n input: RemoteDocumentCreateInput,\n createPlan: MaterializedDocumentCreatePlanWithProjection,\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n response: DocumentCreateResponse,\n retriedStaleTarget: boolean | undefined,\n) {\n const created = await acknowledgeRemoteDocumentCreate({\n ...input,\n ...createPlan,\n resolveProjectionUserKey,\n response,\n });\n assertRequiredSeedAcknowledged(input, created);\n if (input.stillCurrent?.() === false) return null;\n if (created && retriedStaleTarget) input.onRecoveredStaleTarget?.();\n return created && input.deferredSeedUpdate\n ? withDeferredSeed(created, createPlan, input)\n : created;\n}\n\n/** Throws when the collaborators carry no encapsulation secret key. */\nexport async function createRemoteDocument(\n remote: RemoteDocumentCollaborators,\n request: DocumentSubmissionRequest,\n): Promise<CreateRemoteDocumentResult | null> {\n if (!remote.encapsulationSecretKey) {\n throw new Error(\"Remote document create requires an encapsulation key\");\n }\n const input: RemoteDocumentCreateInput = {\n ...request,\n apiClient: remote.api,\n execSql: remote.execSql,\n isRemoteSyncBlocked: remote.isRemoteSyncBlocked,\n targetSecretKey: remote.encapsulationSecretKey,\n };\n // The store retries once the folder's own create settles.\n if (await isContainerCreatePending(input.execSql, input.containerId)) {\n return null;\n }\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote document create\",\n );\n const plannedSubmission = await recordDocumentAuthorAccessFailure(\n () =>\n nullOnProjectionVerificationCancellation(() =>\n submitPlannedDocumentCreate(input, resolveProjectionUserKey),\n ),\n input.onTerminalSubmitFailure,\n );\n if (!plannedSubmission) {\n return null;\n }\n const { createPlan, submission } = plannedSubmission;\n if (input.stillCurrent?.() === false) return null;\n if (submission.ok)\n return settleSubmittedCreate(\n input,\n createPlan,\n resolveProjectionUserKey,\n submission.data,\n plannedSubmission.retriedStaleTarget,\n );\n\n // A stable documentId means a retry after a lost create response re-submits\n // the same id; the server then reports the manifest already exists. That is\n // not a failure — the first attempt committed. Adopt the existing remote\n // document instead of leaking a duplicate. Requires the stable id we sent, so\n // we can fetch its projection back.\n const stableDocumentId = input.documentId;\n if (\n stableDocumentId &&\n !input.requireSeededCreate &&\n isDocumentManifestAlreadyExistsConflict(submission)\n ) {\n if (input.stillCurrent?.() === false) return null;\n const adopted = await nullOnProjectionVerificationCancellation(() =>\n adoptExistingRemoteDocument({\n apiClient: input.apiClient,\n documentId: stableDocumentId,\n execSql: input.execSql,\n expectedContainerId: input.containerId,\n expectedOrganizationId:\n input.expectedOrganizationId ??\n createPlan.containerProjection.organizationId,\n expectedSignerUserId: input.author.signerUserId,\n resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n }),\n );\n if (adopted) {\n return adopted;\n }\n // A conflict is the expected, benign outcome of an idempotent retry after a\n // lost create response. If adoption cannot complete yet (e.g. the writer\n // projection fetch failed transiently), do not surface the conflict as a UI\n // error — the sync engine retries and adopts it on a later tick.\n return null;\n }\n\n // Create-only callers handle the refusal directly, including a verified purge.\n if (!input.requireSeededCreate) submission.report?.();\n await input.onTerminalSubmitFailure?.(submission);\n return null;\n}\n"]}
|