@tearleads/client-sdk 0.1.115 → 0.1.117

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 (67) hide show
  1. package/client/containerContents/documentDiscovery.js +5 -3
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/data/persistence/container-contents/containerContentsPersistence.js +14 -13
  4. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  5. package/data/persistence/documents/internal/ensureDocumentsSchema.js +10 -12
  6. package/data/persistence/documents/internal/ensureDocumentsSchema.js.map +1 -1
  7. package/data/sqlite/schema/containerSchema.d.ts +1 -0
  8. package/data/sqlite/schema/containerSchema.js +8 -1
  9. package/data/sqlite/schema/containerSchema.js.map +1 -1
  10. package/data/sqlite/schema/documentAttachmentSchema.d.ts +0 -2
  11. package/data/sqlite/schema/documentAttachmentSchema.js +0 -4
  12. package/data/sqlite/schema/documentAttachmentSchema.js.map +1 -1
  13. package/data/sqlite/schema/index.d.ts +2 -0
  14. package/data/sqlite/schema/index.js +10 -1
  15. package/data/sqlite/schema/index.js.map +1 -1
  16. package/data/sqlite/schema/principalPolicySchema.js +0 -1
  17. package/data/sqlite/schema/principalPolicySchema.js.map +1 -1
  18. package/data/sqlite/schema/verifiedManifestBundleSchema.js +4 -2
  19. package/data/sqlite/schema/verifiedManifestBundleSchema.js.map +1 -1
  20. package/data/sqlite/sqlExec.d.ts +12 -0
  21. package/data/sqlite/sqlExec.js +47 -3
  22. package/data/sqlite/sqlExec.js.map +1 -1
  23. package/data/sqlite/sqlTableSchema.js +40 -15
  24. package/data/sqlite/sqlTableSchema.js.map +1 -1
  25. package/data/sqlite/sqlitePersistenceRuntime.js +18 -10
  26. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  27. package/internal/api-client/ApiClient.d.ts +118 -0
  28. package/internal/api-client/ApiClient.js +4 -0
  29. package/internal/api-client/ApiClient.js.map +1 -1
  30. package/internal/api-client/index.d.ts +1 -1
  31. package/internal/api-client/index.js.map +1 -1
  32. package/internal/api-client/principalPolicyPages.d.ts +15 -1
  33. package/internal/api-client/principalPolicyPages.js +48 -2
  34. package/internal/api-client/principalPolicyPages.js.map +1 -1
  35. package/internal/api-client/principalPolicyRequests.d.ts +118 -1
  36. package/internal/api-client/principalPolicyRequests.js +4 -1
  37. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  38. package/internal/validators/operation/principalPolicyPageQuery.d.ts +9 -0
  39. package/internal/validators/operation/principalPolicyPageQuery.js +10 -0
  40. package/internal/validators/operation/principalPolicyPageQuery.js.map +1 -1
  41. package/internal/validators/operation/principals.d.ts +37 -4
  42. package/internal/validators/operation/principals.js +5 -3
  43. package/internal/validators/operation/principals.js.map +1 -1
  44. package/internal/validators/response/index.d.ts +1 -1
  45. package/internal/validators/response/index.js +1 -1
  46. package/internal/validators/response/index.js.map +1 -1
  47. package/internal/validators/response/principalPolicyPage.d.ts +497 -1
  48. package/internal/validators/response/principalPolicyPage.js +18 -0
  49. package/internal/validators/response/principalPolicyPage.js.map +1 -1
  50. package/package.json +1 -1
  51. package/workflows/container-contents/documentLinks/index.d.ts +4 -0
  52. package/workflows/container-contents/documentLinks/index.js +10 -3
  53. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  54. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +7 -2
  55. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  56. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +6 -5
  57. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  58. package/workflows/principals/principalPolicyHistoryReader.d.ts +6 -1
  59. package/workflows/principals/principalPolicyHistoryReader.js +4 -1
  60. package/workflows/principals/principalPolicyHistoryReader.js.map +1 -1
  61. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +108 -59
  62. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  63. package/workflows/principals/runtimePolicyRecovery.js +26 -14
  64. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  65. package/workflows/principals/runtimePolicyWarmer.d.ts +26 -0
  66. package/workflows/principals/runtimePolicyWarmer.js +8 -5
  67. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.115",
3
+ "version": "0.1.117",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -2,6 +2,7 @@ import type { ProjectionUserKeyResolver } from "../../../data/keyingProjectionVe
2
2
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
3
3
  import { type DocumentLinkSetFailureHandler, type RelinkRemoteDocumentResult, relinkRemoteDocument } from "../../documents/index.js";
4
4
  import type { SubtreePurgeRoot } from "../../documents/purge/subtreePurgeScope.js";
5
+ import { type PrincipalPolicyOperation } from "../../principals/runtimePolicyWarmer.js";
5
6
  import type { ContainerContentsWorkflowRuntime } from "../runtime.js";
6
7
  type ContainerDocumentLinkApi = Parameters<typeof relinkRemoteDocument>[0]["apiClient"];
7
8
  type ContainerDocumentLinkOperation = Parameters<typeof relinkRemoteDocument>[0]["operation"];
@@ -30,6 +31,8 @@ export declare function relinkRemoteContainerDocument(input: {
30
31
  noteId: string;
31
32
  onFailure?: DocumentLinkSetFailureHandler | undefined;
32
33
  operation: ContainerDocumentLinkOperation;
34
+ /** A workflow root's token; each leg otherwise discovers on its own. */
35
+ policyOperation?: PrincipalPolicyOperation | undefined;
33
36
  resolveProjectionUserKey: ProjectionUserKeyResolver;
34
37
  rotationSnapshot?: Uint8Array | undefined;
35
38
  runtime: ContainerDocumentLinkRuntime;
@@ -42,6 +45,7 @@ export declare function unlinkRemoteContainerDocument(input: {
42
45
  isCurrent?: (() => boolean) | undefined;
43
46
  noteId: string;
44
47
  onFailure?: DocumentLinkSetFailureHandler | undefined;
48
+ policyOperation?: PrincipalPolicyOperation | undefined;
45
49
  resolveProjectionUserKey: ProjectionUserKeyResolver;
46
50
  rotationSnapshot: Uint8Array;
47
51
  runtime: ContainerDocumentLinkRuntime;
@@ -5,7 +5,7 @@ import { sqlDocumentContainerProjectionPersistence } from "../../../data/persist
5
5
  import { errorMessage } from "../../../data/shared/errorMessage.js";
6
6
  import { isDatabaseUnavailableError } from "../../../data/sync/databaseUnavailable.js";
7
7
  import { relinkRemoteDocument, resolveDocumentCreateAuthor, } from "../../documents/index.js";
8
- import { createRuntimePrincipalPolicyWarmer } from "../../principals/runtimePolicyWarmer.js";
8
+ import { createPrincipalPolicyOperation, createRuntimePrincipalPolicyWarmer, } from "../../principals/runtimePolicyWarmer.js";
9
9
  import { resolveContainerDocumentMoveUnlinkIds } from "../documentMove/documentMoveUnlinkIds.js";
10
10
  // A cold-cache denial must keep its HTTP status: collapsing a 403 to null
11
11
  // would leave an access-denied move routinely retriable instead of parking
@@ -51,7 +51,7 @@ async function containerDocumentAlreadyMovedResult(input) {
51
51
  execSql: input.runtime.infra.execSql,
52
52
  resolveProjectionUserKey: input.resolveProjectionUserKey,
53
53
  stillCurrent: input.isCurrent,
54
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
54
+ warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime, { operation: input.policyOperation }),
55
55
  onVerifiedAuthorization: (authorization) => {
56
56
  verified.head = authorization.documentManifestByHash.get(input.writerProjection.documentManifest.manifestHash);
57
57
  },
@@ -117,7 +117,7 @@ export async function relinkRemoteContainerDocument(input) {
117
117
  stillCurrent: input.isCurrent,
118
118
  targetContainerId,
119
119
  targetSecretKey,
120
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime),
120
+ warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime, { operation: input.policyOperation }),
121
121
  });
122
122
  if (!result) {
123
123
  runtime.util.log(`Container contents: failed to ${operation} note ${noteId} ${operation === "link" ? "to" : "from"} container ${targetContainerId}`);
@@ -160,6 +160,9 @@ export async function moveRemoteContainerDocument(input) {
160
160
  const { documentId, noteId, resolveProjectionUserKey, runtime, targetContainerId, } = input;
161
161
  if (input.isCurrent?.() === false)
162
162
  return null;
163
+ // One move workflow is one policy operation: its link and unlink legs share
164
+ // a directory discovery. Each leg's commit still refuses a stale view.
165
+ const policyOperation = createPrincipalPolicyOperation();
163
166
  const writerProjection = await fetchMoveWriterProjection({
164
167
  documentId,
165
168
  onFailure: input.onFailure,
@@ -184,6 +187,7 @@ export async function moveRemoteContainerDocument(input) {
184
187
  isCurrent: input.isCurrent,
185
188
  noteId,
186
189
  onFailure: input.onFailure,
190
+ policyOperation,
187
191
  resolveProjectionUserKey,
188
192
  runtime,
189
193
  targetContainerId: linkTarget,
@@ -202,6 +206,7 @@ export async function moveRemoteContainerDocument(input) {
202
206
  ...input,
203
207
  latestDocument,
204
208
  latestLinkedContainerIds,
209
+ policyOperation,
205
210
  unlinkContainerIds,
206
211
  });
207
212
  if (!unlinked)
@@ -226,6 +231,7 @@ export async function moveRemoteContainerDocument(input) {
226
231
  isCurrent: input.isCurrent,
227
232
  linkedContainerIds: latestLinkedContainerIds,
228
233
  nextContainerId,
234
+ policyOperation,
229
235
  status,
230
236
  });
231
237
  }
@@ -244,6 +250,7 @@ async function unlinkMovedDocumentSources(input) {
244
250
  isCurrent: input.isCurrent,
245
251
  noteId,
246
252
  onFailure: input.onFailure,
253
+ policyOperation: input.policyOperation,
247
254
  resolveProjectionUserKey: input.resolveProjectionUserKey,
248
255
  rotationSnapshot: input.rotationSnapshot,
249
256
  runtime,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,wCAAwC,EACxC,0CAA0C,GAC3C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,gDAAgD,EAAE,MAAM,0CAA0C,CAA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iB,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;QACzD,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAC/C,MAAM,gBAAgB,GAAG,MAAM,6BAA6B,CAAC;YAC3D,UAAU,EAAE,KAAK,CAAC,UAAU;YAC5B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,MAAM;YACN,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;YACxD,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;YACxC,OAAO;YACP,iBAAiB,EAAE,iBAAiB;SACrC,CAAC,CAAC;QACH,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAC/C,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtB,wBAAwB,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;YACjD,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,4BAA4B,MAAM,kBAAkB,iBAAiB,8BAA8B,iBAAiB,EAAE,CACvH,CAAC;YACF,SAAS;QACX,CAAC;QAED,cAAc,GAAG,gBAAgB,CAAC;QAClC,wBAAwB,GAAG,gBAAgB,CAAC,kBAAkB,CAAC;IACjE,CAAC;IACD,OAAO,EAAE,wBAAwB,EAAE,cAAc,EAAE,wBAAwB,EAAE,CAAC;AAChF,CAAC","sourcesContent":["import type { VerifiedDocumentLinkSetManifest } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { isDatabaseUnavailableError } from \"../../../data/sync/databaseUnavailable\";\nimport {\n type DocumentLinkSetFailureHandler,\n type RelinkRemoteDocumentResult,\n relinkRemoteDocument,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport { resolveContainerDocumentMoveUnlinkIds } from \"../documentMove/documentMoveUnlinkIds\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\ntype ContainerDocumentLinkApi = Parameters<\n typeof relinkRemoteDocument\n>[0][\"apiClient\"];\ntype ContainerDocumentLinkOperation = Parameters<\n typeof relinkRemoteDocument\n>[0][\"operation\"];\ntype RemoteDocumentPersistedState =\n RelinkRemoteDocumentResult[\"persistedState\"];\n\n// A cold-cache denial must keep its HTTP status: collapsing a 403 to null\n// would leave an access-denied move routinely retriable instead of parking\n// it for the access-restored signal (row 7).\nasync function fetchMoveWriterProjection(input: {\n documentId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n runtime: ContainerDocumentLinkRuntime;\n}): Promise<Awaited<\n ReturnType<ContainerDocumentLinkApi[\"getDocumentWriterProjection\"]>\n> | null> {\n const { apiClient } = input.runtime;\n const result = await apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n result.report();\n input.onFailure?.({ message: result.message, status: result.status });\n return null;\n}\n\ninterface ContainerDocumentLinkRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerDocumentLinkApi &\n Pick<\n ContainerContentsWorkflowRuntime[\"apiClient\"],\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >;\n}\n\ntype MoveRemoteContainerDocumentStatus = \"complete\" | \"partial\";\n\ninterface MoveRemoteContainerDocumentResult {\n accessEpoch: number | null;\n accessStateHash: string | null;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n remoteState: RemoteDocumentPersistedState | null;\n status: MoveRemoteContainerDocumentStatus;\n}\n\nexport type { RemoteDocumentPersistedState };\n\nexport async function initializeDocumentLinksSchema(\n execSql: ExecSql,\n): Promise<void> {\n await sqlDocumentContainerProjectionPersistence.ensureSchema(execSql);\n}\n\nexport async function listDocumentLinkedContainerIds(\n execSql: ExecSql,\n documentId: string,\n): Promise<ReadonlyArray<string>> {\n return sqlDocumentContainerProjectionPersistence.listLinkedContainerIds(\n execSql,\n documentId,\n );\n}\n\nexport async function replaceDocumentLinks(\n execSql: ExecSql,\n documentId: string,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(\n execSql,\n documentId,\n containerIds,\n );\n}\n\nfunction resolveActiveDocumentContainerId(\n linkedContainerIds: ReadonlyArray<string>,\n preferredContainerId: string,\n): string | null {\n if (linkedContainerIds.includes(preferredContainerId)) {\n return preferredContainerId;\n }\n\n return linkedContainerIds[0] ?? null;\n}\n\nfunction containerDocumentMoveResult(input: {\n document: RelinkRemoteDocumentResult;\n nextContainerId: string;\n status: MoveRemoteContainerDocumentStatus;\n}): MoveRemoteContainerDocumentResult {\n return {\n accessEpoch: input.document.plan.state.epoch,\n accessStateHash: input.document.response.accessManifest.manifestHash,\n linkedContainerIds: input.document.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: input.document.persistedState,\n status: input.status,\n };\n}\n\nasync function containerDocumentAlreadyMovedResult(input: {\n writerProjection: DocumentWriterProjectionResponse;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n isCurrent?: (() => boolean) | undefined;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n status: MoveRemoteContainerDocumentStatus;\n}): Promise<MoveRemoteContainerDocumentResult> {\n const verified: { head?: VerifiedDocumentLinkSetManifest | undefined } = {};\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.runtime.infra.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.isCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n onVerifiedAuthorization: (authorization) => {\n verified.head = authorization.documentManifestByHash.get(\n input.writerProjection.documentManifest.manifestHash,\n );\n },\n });\n if (!verified.head)\n throw new Error(\"Move replay lacks a verified document head\");\n return {\n accessEpoch: verified.head.state.epoch,\n accessStateHash: verified.head.manifestHash,\n linkedContainerIds: input.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: persistedDocumentCreateStateFromWriterProjection(\n input.writerProjection,\n ),\n status: input.status,\n };\n}\n\n/**\n * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.\n * The caller's string-only log line stays the fallback for a host without\n * `logError`, so this never logs a second copy of the same failure.\n */\nfunction reportDocumentLinkMutationFailure(\n util: ContainerDocumentLinkRuntime[\"util\"],\n error: unknown,\n): void {\n // `ApiClient` returns `RequestFailure` objects instead of throwing, so\n // offline and 403/404/409 already left through the `!result` branch: a status\n // filter here would be dead code. Only a database lost mid-flight stays quiet.\n if (!util.logError || isDatabaseUnavailableError(error)) return;\n try {\n // A host logger that throws or rejects must not replace the null result or\n // skip the failure handler below.\n void Promise.resolve(\n util.logError(\"Container contents: document link mutation failed\", error),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\nexport async function relinkRemoteContainerDocument(input: {\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: ContainerDocumentLinkOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const {\n documentId,\n noteId,\n operation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n const author = resolveDocumentCreateAuthor(runtime);\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n const execSql = runtime.infra.execSql;\n if (input.isCurrent?.() === false) return null;\n if (!author || !targetSecretKey) {\n runtime.util.log(\n \"Container contents: document mutation skipped because the local key context is unavailable\",\n );\n input.onFailure?.({\n message: \"the local key context is unavailable\",\n status: null,\n });\n return null;\n }\n\n try {\n const result = await relinkRemoteDocument({\n beforeSubmit: input.beforeSubmit,\n apiClient: runtime.apiClient,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n execSql,\n onFailure: input.onFailure,\n operation,\n resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n stillCurrent: input.isCurrent,\n targetContainerId,\n targetSecretKey,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!result) {\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}`,\n );\n return null;\n }\n if (input.isCurrent?.() === false) return null;\n\n await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(\n execSql,\n documentId,\n result.linkedContainerIds,\n { stillCurrent: input.isCurrent },\n );\n\n return result;\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: `document.${operation}`,\n },\n );\n const message = errorMessage(error);\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}: ${message}`,\n );\n // After the keying rethrow above, so a verification failure keeps its\n // security incident instead of being reported twice, and before the failure\n // handler, so a throwing caller callback cannot swallow the report.\n reportDocumentLinkMutationFailure(runtime.util, error);\n input.onFailure?.({ message, status: null });\n return null;\n }\n}\n\nasync function linkRemoteContainerDocument(input: {\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"link\",\n });\n}\n\nexport async function unlinkRemoteContainerDocument(input: {\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"unlink\",\n });\n}\n\nexport async function moveRemoteContainerDocument(input: {\n linkOnly?: boolean | undefined;\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n currentContainerId: string;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n replaceLinkedContainers?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<MoveRemoteContainerDocumentResult | null> {\n const {\n documentId,\n noteId,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n if (input.isCurrent?.() === false) return null;\n const writerProjection = await fetchMoveWriterProjection({\n documentId,\n onFailure: input.onFailure,\n runtime,\n });\n if (!writerProjection || input.isCurrent?.() === false) {\n return null;\n }\n if (writerProjection.documentId !== documentId)\n throw new Error(\"Move replay document id mismatch\");\n const initialLinkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n\n let latestLinkedContainerIds: readonly string[] = initialLinkedContainerIds;\n let latestDocument: RelinkRemoteDocumentResult | null = null;\n for (const linkTarget of new Set([\n ...(input.linkOnly ? [] : [targetContainerId]),\n ...(input.additionalLinkContainerIds ?? []),\n ])) {\n if (latestLinkedContainerIds.includes(linkTarget)) continue;\n const linkedDocument = await linkRemoteContainerDocument({\n documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n resolveProjectionUserKey,\n runtime,\n targetContainerId: linkTarget,\n });\n if (!linkedDocument || input.isCurrent?.() === false) {\n return null;\n }\n\n latestDocument = linkedDocument;\n latestLinkedContainerIds = linkedDocument.linkedContainerIds;\n }\n\n const unlinkContainerIds = resolveContainerDocumentMoveUnlinkIds({\n ...input,\n linkedContainerIds: latestLinkedContainerIds,\n });\n\n const unlinked = await unlinkMovedDocumentSources({\n ...input,\n latestDocument,\n latestLinkedContainerIds,\n unlinkContainerIds,\n });\n if (!unlinked) return null;\n latestDocument = unlinked.latestDocument;\n latestLinkedContainerIds = unlinked.latestLinkedContainerIds;\n\n const nextContainerId = resolveActiveDocumentContainerId(\n latestLinkedContainerIds,\n targetContainerId,\n );\n if (!nextContainerId) {\n return null;\n }\n\n const status =\n unlinked.failedUnlinkContainerIds.length > 0 ? \"partial\" : \"complete\";\n return latestDocument\n ? containerDocumentMoveResult({\n document: latestDocument,\n nextContainerId,\n status,\n })\n : containerDocumentAlreadyMovedResult({\n writerProjection,\n resolveProjectionUserKey,\n runtime,\n isCurrent: input.isCurrent,\n linkedContainerIds: latestLinkedContainerIds,\n nextContainerId,\n status,\n });\n}\n\n// The unlink half of a move: every source is attempted even when an earlier\n// one fails, so one dead source cannot strand the others; a failed unlink\n// leaves the move \"partial\" for the queue to retry.\nasync function unlinkMovedDocumentSources(input: {\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n unlinkContainerIds: readonly string[];\n}): Promise<{\n failedUnlinkContainerIds: readonly string[];\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n} | null> {\n const { noteId, runtime, targetContainerId } = input;\n let { latestDocument, latestLinkedContainerIds } = input;\n const failedUnlinkContainerIds: string[] = [];\n for (const unlinkContainerId of input.unlinkContainerIds) {\n if (input.isCurrent?.() === false) return null;\n const unlinkedDocument = await unlinkRemoteContainerDocument({\n documentId: input.documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n runtime,\n targetContainerId: unlinkContainerId,\n });\n if (input.isCurrent?.() === false) return null;\n if (!unlinkedDocument) {\n failedUnlinkContainerIds.push(unlinkContainerId);\n runtime.util.log(\n `Container contents: note ${noteId} was linked to ${targetContainerId} but failed to unlink from ${unlinkContainerId}`,\n );\n continue;\n }\n\n latestDocument = unlinkedDocument;\n latestLinkedContainerIds = unlinkedDocument.linkedContainerIds;\n }\n return { failedUnlinkContainerIds, latestDocument, latestLinkedContainerIds };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,wCAAwC,EACxC,0CAA0C,GAC3C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,gDAAgD,EAAE,MAAM,0CAA0C,CAAC;AAE5G,OAAO,EAA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AM,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACrD,IAAI,EAAE,cAAc,EAAE,wBAAwB,EAAE,GAAG,KAAK,CAAC;IACzD,MAAM,wBAAwB,GAAa,EAAE,CAAC;IAC9C,KAAK,MAAM,iBAAiB,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;QACzD,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAC/C,MAAM,gBAAgB,GAAG,MAAM,6BAA6B,CAAC;YAC3D,UAAU,EAAE,KAAK,CAAC,UAAU;YAC5B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,MAAM;YACN,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;YACxD,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;YACxC,OAAO;YACP,iBAAiB,EAAE,iBAAiB;SACrC,CAAC,CAAC;QACH,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAC/C,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtB,wBAAwB,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;YACjD,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,4BAA4B,MAAM,kBAAkB,iBAAiB,8BAA8B,iBAAiB,EAAE,CACvH,CAAC;YACF,SAAS;QACX,CAAC;QAED,cAAc,GAAG,gBAAgB,CAAC;QAClC,wBAAwB,GAAG,gBAAgB,CAAC,kBAAkB,CAAC;IACjE,CAAC;IACD,OAAO,EAAE,wBAAwB,EAAE,cAAc,EAAE,wBAAwB,EAAE,CAAC;AAChF,CAAC","sourcesContent":["import type { VerifiedDocumentLinkSetManifest } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { isDatabaseUnavailableError } from \"../../../data/sync/databaseUnavailable\";\nimport {\n type DocumentLinkSetFailureHandler,\n type RelinkRemoteDocumentResult,\n relinkRemoteDocument,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\nimport {\n createPrincipalPolicyOperation,\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../principals/runtimePolicyWarmer\";\nimport { resolveContainerDocumentMoveUnlinkIds } from \"../documentMove/documentMoveUnlinkIds\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\ntype ContainerDocumentLinkApi = Parameters<\n typeof relinkRemoteDocument\n>[0][\"apiClient\"];\ntype ContainerDocumentLinkOperation = Parameters<\n typeof relinkRemoteDocument\n>[0][\"operation\"];\ntype RemoteDocumentPersistedState =\n RelinkRemoteDocumentResult[\"persistedState\"];\n\n// A cold-cache denial must keep its HTTP status: collapsing a 403 to null\n// would leave an access-denied move routinely retriable instead of parking\n// it for the access-restored signal (row 7).\nasync function fetchMoveWriterProjection(input: {\n documentId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n runtime: ContainerDocumentLinkRuntime;\n}): Promise<Awaited<\n ReturnType<ContainerDocumentLinkApi[\"getDocumentWriterProjection\"]>\n> | null> {\n const { apiClient } = input.runtime;\n const result = await apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n result.report();\n input.onFailure?.({ message: result.message, status: result.status });\n return null;\n}\n\ninterface ContainerDocumentLinkRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerDocumentLinkApi &\n Pick<\n ContainerContentsWorkflowRuntime[\"apiClient\"],\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >;\n}\n\ntype MoveRemoteContainerDocumentStatus = \"complete\" | \"partial\";\n\ninterface MoveRemoteContainerDocumentResult {\n accessEpoch: number | null;\n accessStateHash: string | null;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n remoteState: RemoteDocumentPersistedState | null;\n status: MoveRemoteContainerDocumentStatus;\n}\n\nexport type { RemoteDocumentPersistedState };\n\nexport async function initializeDocumentLinksSchema(\n execSql: ExecSql,\n): Promise<void> {\n await sqlDocumentContainerProjectionPersistence.ensureSchema(execSql);\n}\n\nexport async function listDocumentLinkedContainerIds(\n execSql: ExecSql,\n documentId: string,\n): Promise<ReadonlyArray<string>> {\n return sqlDocumentContainerProjectionPersistence.listLinkedContainerIds(\n execSql,\n documentId,\n );\n}\n\nexport async function replaceDocumentLinks(\n execSql: ExecSql,\n documentId: string,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(\n execSql,\n documentId,\n containerIds,\n );\n}\n\nfunction resolveActiveDocumentContainerId(\n linkedContainerIds: ReadonlyArray<string>,\n preferredContainerId: string,\n): string | null {\n if (linkedContainerIds.includes(preferredContainerId)) {\n return preferredContainerId;\n }\n\n return linkedContainerIds[0] ?? null;\n}\n\nfunction containerDocumentMoveResult(input: {\n document: RelinkRemoteDocumentResult;\n nextContainerId: string;\n status: MoveRemoteContainerDocumentStatus;\n}): MoveRemoteContainerDocumentResult {\n return {\n accessEpoch: input.document.plan.state.epoch,\n accessStateHash: input.document.response.accessManifest.manifestHash,\n linkedContainerIds: input.document.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: input.document.persistedState,\n status: input.status,\n };\n}\n\nasync function containerDocumentAlreadyMovedResult(input: {\n writerProjection: DocumentWriterProjectionResponse;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n isCurrent?: (() => boolean) | undefined;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n policyOperation: PrincipalPolicyOperation;\n status: MoveRemoteContainerDocumentStatus;\n}): Promise<MoveRemoteContainerDocumentResult> {\n const verified: { head?: VerifiedDocumentLinkSetManifest | undefined } = {};\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.runtime.infra.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.isCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n { operation: input.policyOperation },\n ),\n onVerifiedAuthorization: (authorization) => {\n verified.head = authorization.documentManifestByHash.get(\n input.writerProjection.documentManifest.manifestHash,\n );\n },\n });\n if (!verified.head)\n throw new Error(\"Move replay lacks a verified document head\");\n return {\n accessEpoch: verified.head.state.epoch,\n accessStateHash: verified.head.manifestHash,\n linkedContainerIds: input.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: persistedDocumentCreateStateFromWriterProjection(\n input.writerProjection,\n ),\n status: input.status,\n };\n}\n\n/**\n * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.\n * The caller's string-only log line stays the fallback for a host without\n * `logError`, so this never logs a second copy of the same failure.\n */\nfunction reportDocumentLinkMutationFailure(\n util: ContainerDocumentLinkRuntime[\"util\"],\n error: unknown,\n): void {\n // `ApiClient` returns `RequestFailure` objects instead of throwing, so\n // offline and 403/404/409 already left through the `!result` branch: a status\n // filter here would be dead code. Only a database lost mid-flight stays quiet.\n if (!util.logError || isDatabaseUnavailableError(error)) return;\n try {\n // A host logger that throws or rejects must not replace the null result or\n // skip the failure handler below.\n void Promise.resolve(\n util.logError(\"Container contents: document link mutation failed\", error),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\nexport async function relinkRemoteContainerDocument(input: {\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: ContainerDocumentLinkOperation;\n /** A workflow root's token; each leg otherwise discovers on its own. */\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const {\n documentId,\n noteId,\n operation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n const author = resolveDocumentCreateAuthor(runtime);\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n const execSql = runtime.infra.execSql;\n if (input.isCurrent?.() === false) return null;\n if (!author || !targetSecretKey) {\n runtime.util.log(\n \"Container contents: document mutation skipped because the local key context is unavailable\",\n );\n input.onFailure?.({\n message: \"the local key context is unavailable\",\n status: null,\n });\n return null;\n }\n\n try {\n const result = await relinkRemoteDocument({\n beforeSubmit: input.beforeSubmit,\n apiClient: runtime.apiClient,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n execSql,\n onFailure: input.onFailure,\n operation,\n resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n stillCurrent: input.isCurrent,\n targetContainerId,\n targetSecretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: input.policyOperation },\n ),\n });\n if (!result) {\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}`,\n );\n return null;\n }\n if (input.isCurrent?.() === false) return null;\n\n await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(\n execSql,\n documentId,\n result.linkedContainerIds,\n { stillCurrent: input.isCurrent },\n );\n\n return result;\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: `document.${operation}`,\n },\n );\n const message = errorMessage(error);\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}: ${message}`,\n );\n // After the keying rethrow above, so a verification failure keeps its\n // security incident instead of being reported twice, and before the failure\n // handler, so a throwing caller callback cannot swallow the report.\n reportDocumentLinkMutationFailure(runtime.util, error);\n input.onFailure?.({ message, status: null });\n return null;\n }\n}\n\nasync function linkRemoteContainerDocument(input: {\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"link\",\n });\n}\n\nexport async function unlinkRemoteContainerDocument(input: {\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"unlink\",\n });\n}\n\nexport async function moveRemoteContainerDocument(input: {\n linkOnly?: boolean | undefined;\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n currentContainerId: string;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n replaceLinkedContainers?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<MoveRemoteContainerDocumentResult | null> {\n const {\n documentId,\n noteId,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n if (input.isCurrent?.() === false) return null;\n // One move workflow is one policy operation: its link and unlink legs share\n // a directory discovery. Each leg's commit still refuses a stale view.\n const policyOperation = createPrincipalPolicyOperation();\n const writerProjection = await fetchMoveWriterProjection({\n documentId,\n onFailure: input.onFailure,\n runtime,\n });\n if (!writerProjection || input.isCurrent?.() === false) {\n return null;\n }\n if (writerProjection.documentId !== documentId)\n throw new Error(\"Move replay document id mismatch\");\n const initialLinkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n\n let latestLinkedContainerIds: readonly string[] = initialLinkedContainerIds;\n let latestDocument: RelinkRemoteDocumentResult | null = null;\n for (const linkTarget of new Set([\n ...(input.linkOnly ? [] : [targetContainerId]),\n ...(input.additionalLinkContainerIds ?? []),\n ])) {\n if (latestLinkedContainerIds.includes(linkTarget)) continue;\n const linkedDocument = await linkRemoteContainerDocument({\n documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n policyOperation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId: linkTarget,\n });\n if (!linkedDocument || input.isCurrent?.() === false) {\n return null;\n }\n\n latestDocument = linkedDocument;\n latestLinkedContainerIds = linkedDocument.linkedContainerIds;\n }\n\n const unlinkContainerIds = resolveContainerDocumentMoveUnlinkIds({\n ...input,\n linkedContainerIds: latestLinkedContainerIds,\n });\n\n const unlinked = await unlinkMovedDocumentSources({\n ...input,\n latestDocument,\n latestLinkedContainerIds,\n policyOperation,\n unlinkContainerIds,\n });\n if (!unlinked) return null;\n latestDocument = unlinked.latestDocument;\n latestLinkedContainerIds = unlinked.latestLinkedContainerIds;\n\n const nextContainerId = resolveActiveDocumentContainerId(\n latestLinkedContainerIds,\n targetContainerId,\n );\n if (!nextContainerId) {\n return null;\n }\n\n const status =\n unlinked.failedUnlinkContainerIds.length > 0 ? \"partial\" : \"complete\";\n return latestDocument\n ? containerDocumentMoveResult({\n document: latestDocument,\n nextContainerId,\n status,\n })\n : containerDocumentAlreadyMovedResult({\n writerProjection,\n resolveProjectionUserKey,\n runtime,\n isCurrent: input.isCurrent,\n linkedContainerIds: latestLinkedContainerIds,\n nextContainerId,\n policyOperation,\n status,\n });\n}\n\n// The unlink half of a move: every source is attempted even when an earlier\n// one fails, so one dead source cannot strand the others; a failed unlink\n// leaves the move \"partial\" for the queue to retry.\nasync function unlinkMovedDocumentSources(input: {\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n unlinkContainerIds: readonly string[];\n}): Promise<{\n failedUnlinkContainerIds: readonly string[];\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n} | null> {\n const { noteId, runtime, targetContainerId } = input;\n let { latestDocument, latestLinkedContainerIds } = input;\n const failedUnlinkContainerIds: string[] = [];\n for (const unlinkContainerId of input.unlinkContainerIds) {\n if (input.isCurrent?.() === false) return null;\n const unlinkedDocument = await unlinkRemoteContainerDocument({\n documentId: input.documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n policyOperation: input.policyOperation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n runtime,\n targetContainerId: unlinkContainerId,\n });\n if (input.isCurrent?.() === false) return null;\n if (!unlinkedDocument) {\n failedUnlinkContainerIds.push(unlinkContainerId);\n runtime.util.log(\n `Container contents: note ${noteId} was linked to ${targetContainerId} but failed to unlink from ${unlinkContainerId}`,\n );\n continue;\n }\n\n latestDocument = unlinkedDocument;\n latestLinkedContainerIds = unlinkedDocument.linkedContainerIds;\n }\n return { failedUnlinkContainerIds, latestDocument, latestLinkedContainerIds };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
1
+ import { createPrincipalPolicyOperation, createRuntimePrincipalPolicyWarmer, } from "../../../principals/runtimePolicyWarmer.js";
2
2
  import { prefetchDestinationProjections } from "../destination/destinationPrefetch.js";
3
3
  import { cachedDestinationRole } from "../destination/destinationRoleCache.js";
4
4
  import { markContainerParentLaneFetched } from "../lanes/laneFetchMarkers.js";
@@ -19,7 +19,7 @@ async function applyRemoteContainerPage(input) {
19
19
  let hydratedCount = 0;
20
20
  let pageCompleted = true;
21
21
  await cacheRemoteContainerPrincipalPolicies({
22
- cacheReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(state.runtime),
22
+ cacheReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(state.runtime, { operation: input.policyOperation }),
23
23
  remoteContainers: items,
24
24
  stillCurrent: input.isCurrent,
25
25
  });
@@ -133,6 +133,7 @@ async function applyContainerParentLanePage(input) {
133
133
  isCurrent: input.isCurrent,
134
134
  isPaused,
135
135
  items: remoteContainerItems.filter((item) => !isPaused(item)),
136
+ policyOperation: input.policyOperation,
136
137
  queueParentLane,
137
138
  seenContainerIds,
138
139
  state,
@@ -198,6 +199,7 @@ async function applyContainerParentLaneBatch(input) {
198
199
  fetchedPage,
199
200
  host,
200
201
  isCurrent: input.isCurrent,
202
+ policyOperation: input.policyOperation,
201
203
  queueContinuationLane: (lane) => lanes.push(lane),
202
204
  queueParentLane,
203
205
  seenContainerIds,
@@ -215,6 +217,8 @@ export async function hydrateContainerParentLanes(input) {
215
217
  const { childIdsByParentId, host, lanes, queueParentLane, seenContainerIds, state, } = input;
216
218
  let changedCount = 0;
217
219
  let complete = true;
220
+ // One hydration pass is one policy operation: its pages share a discovery.
221
+ const policyOperation = createPrincipalPolicyOperation();
218
222
  while (lanes.length > 0) {
219
223
  if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {
220
224
  return { changedCount, complete: false, shouldStop: true };
@@ -240,6 +244,7 @@ export async function hydrateContainerParentLanes(input) {
240
244
  host,
241
245
  isCurrent: input.isCurrent,
242
246
  lanes,
247
+ policyOperation,
243
248
  queueParentLane,
244
249
  seenContainerIds,
245
250
  state,
@@ -1 +1 @@
1
- {"version":3,"file":"remoteContainerPageHydration.js","sourceRoot":"","sources":["remoteContainerPageHydration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAC7F,OAAO,EAAE,8BAA8B,EAAE,MAAM,oCAAoC,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,6BAA6B,EAAE,MAAM,0BAA0B,CAAC;AACzE,OAAO,EAAE,qCAAqC,EAAE,MAAM,yBAAyB,CAAC;AAChF,OAAO,EACL,wBAAwB,EACxB,iCAAiC,GAClC,MAAM,yBAAyB,CAAC;AAWjC,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EACL,gDAAgD,EAChD,kDAAkD,EAClD,kCAAkC,GACnC,MAAM,wB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AC;YACvB,SAAS;QACX,CAAC;QAED,MAAM,YAAY,GAAG,MAAM,6BAA6B,CAAC;YACvD,KAAK;YACL,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,KAAK;SACN,CAAC,CAAC;QACH,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;QAC7D,CAAC;QACD,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;YAClC,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;QAC7D,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,6BAA6B,CAAC;YACjD,kBAAkB;YAClB,YAAY;YACZ,IAAI;YACJ,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,KAAK;YACL,eAAe;YACf,gBAAgB;YAChB,KAAK;SACN,CAAC,CAAC;QACH,YAAY,IAAI,MAAM,CAAC,YAAY,CAAC;QACpC,QAAQ,KAAK,MAAM,CAAC,QAAQ,CAAC;QAE7B,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACtB,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;QAC7D,CAAC;IACH,CAAC;IAED,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;AACvD,CAAC","sourcesContent":["import { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport { prefetchDestinationProjections } from \"../destination/destinationPrefetch\";\nimport { cachedDestinationRole } from \"../destination/destinationRoleCache\";\nimport { markContainerParentLaneFetched } from \"../lanes/laneFetchMarkers\";\nimport { fetchContainerParentLaneBatch } from \"../lanes/parentLaneFetch\";\nimport { cacheRemoteContainerPrincipalPolicies } from \"../principalPolicyCache\";\nimport {\n applyContainerTombstones,\n getApplicableRemoteContainerItems,\n} from \"../tombstoneApplication\";\nimport type {\n ContainerChildIndex,\n ContainerParentHydrationLane,\n ExpectedContainerState,\n FetchedContainerParentLanePage,\n ListedRemoteContainerPageItem,\n QueueContainerParentLane,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { containerStateMatchesFingerprint } from \"./containerStateFingerprint\";\nimport { loadPausedContainerFilter } from \"./organizationSyncPauseFilter\";\nimport {\n listRemoteContainerIdsWithPendingMetadataUpdates,\n listRemoteContainerIdsWithPendingStructuralIntents,\n upsertIsolatedRemoteContainerState,\n} from \"./remoteContainerState\";\n\nconst CONTAINER_PARENT_HYDRATION_CONCURRENCY = 4;\n\ninterface HydrationProgress {\n changedCount: number;\n complete: boolean;\n shouldStop: boolean;\n}\n// Re-checked inside the commit: a pause from another device can land after\n// the page was filtered, and its cleanup may already have run.\nfunction currentUnlessPaused(\n input: {\n isCurrent?: (() => boolean) | undefined;\n isPaused: (container: ListedRemoteContainerPageItem) => boolean;\n },\n container: ListedRemoteContainerPageItem,\n): () => boolean {\n return () => input.isCurrent?.() !== false && !input.isPaused(container);\n}\n\nasync function applyRemoteContainerPage(input: {\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: FetchedContainerParentLanePage[\"expectedHydrationTombstones\"];\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n /** Live pause check; a pause arriving mid-page stops the commit. */\n isPaused: (container: ListedRemoteContainerPageItem) => boolean;\n items: ReadonlyArray<ListedRemoteContainerPageItem>;\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<{ changedCount: number; completed: boolean }> {\n const {\n childIdsByParentId,\n expectedContainerStates,\n expectedHydrationTombstones,\n host,\n items,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n let hydratedCount = 0;\n let pageCompleted = true;\n await cacheRemoteContainerPrincipalPolicies({\n cacheReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n state.runtime,\n ),\n remoteContainers: items,\n stillCurrent: input.isCurrent,\n });\n if (input.isCurrent?.() === false) {\n return { changedCount: 0, completed: false };\n }\n const [\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n ] = await Promise.all([\n listRemoteContainerIdsWithPendingMetadataUpdates({\n remoteContainers: items,\n state,\n }),\n listRemoteContainerIdsWithPendingStructuralIntents({\n remoteContainers: items,\n state,\n }),\n ]);\n if (input.isCurrent?.() === false) {\n return { changedCount: 0, completed: false };\n }\n const prefetchedProjections = await prefetchDestinationProjections({\n containerIds: items.flatMap((item) =>\n seenContainerIds.has(item.id) ||\n state.containersById.has(item.id) ||\n expectedHydrationTombstones.get(item.id) ||\n cachedDestinationRole(state.runtime.infra.execSql, item)\n ? []\n : [item.id],\n ),\n isCurrent: input.isCurrent,\n runtime: state.runtime,\n });\n for (const container of items) {\n if (input.isCurrent?.() === false) {\n return { changedCount: hydratedCount, completed: false };\n }\n if (!seenContainerIds.has(container.id)) {\n if (\n !containerStateMatchesFingerprint({\n currentState: state.containersById.get(container.id),\n expectedFingerprint: expectedContainerStates.get(container.id)\n ?.fingerprint,\n })\n ) {\n pageCompleted = false;\n continue;\n }\n const upserted = await upsertIsolatedRemoteContainerState({\n childIdsByParentId,\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n host,\n isCurrent: currentUnlessPaused(input, container),\n expectedHydrationTombstone:\n expectedHydrationTombstones.get(container.id) ?? null,\n prefetchedProjection: prefetchedProjections.get(container.id),\n remoteContainer: container,\n state,\n });\n if (!upserted) {\n pageCompleted = false;\n continue;\n }\n seenContainerIds.add(container.id);\n hydratedCount += 1;\n if (input.isCurrent?.() === false) {\n return { changedCount: hydratedCount, completed: false };\n }\n }\n queueParentLane(container.id);\n }\n\n return { changedCount: hydratedCount, completed: pageCompleted };\n}\n\nexport function canHydrateRemoteContainers(\n state: RemoteContainerHydrationState,\n): boolean {\n return (\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online &&\n state.runtime.infra.dbStatus === \"ready\"\n );\n}\n\nasync function applyContainerParentLanePage(input: {\n childIdsByParentId: ContainerChildIndex;\n fetchedPage: FetchedContainerParentLanePage;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n queueContinuationLane: (lane: ContainerParentHydrationLane) => void;\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<HydrationProgress> {\n const {\n childIdsByParentId,\n fetchedPage,\n host,\n queueContinuationLane,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n const {\n expectedContainerStates,\n expectedHydrationTombstones,\n lane,\n response,\n syncLane,\n } = fetchedPage;\n let changedCount = 0;\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const remoteContainerItems = getApplicableRemoteContainerItems(response);\n const tombstoneResult = await applyContainerTombstones({\n childIdsByParentId,\n expectedContainerStates,\n isCurrent: input.isCurrent,\n remoteContainerItems,\n response,\n state,\n });\n if (!tombstoneResult.current) {\n return { changedCount, complete: false, shouldStop: true };\n }\n changedCount += tombstoneResult.changedCount;\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n if (tombstoneResult.changedCount > 0) {\n // A live tombstone cascade may have orphaned documents (row 3); re-arm\n // document priming so their null-scoped passes run now rather than on\n // the next startup.\n host.requestDocumentPriming?.();\n }\n\n // A paused organization's containers stay off the device. Skipping them\n // here, after tombstones saw the full page, still lets the lane complete\n // and its watermark advance; their children are never queued.\n const isPaused = await loadPausedContainerFilter(state);\n const appliedPage = await applyRemoteContainerPage({\n childIdsByParentId,\n expectedContainerStates,\n expectedHydrationTombstones,\n host,\n isCurrent: input.isCurrent,\n isPaused,\n items: remoteContainerItems.filter((item) => !isPaused(item)),\n queueParentLane,\n seenContainerIds,\n state,\n });\n changedCount += appliedPage.changedCount;\n if (!tombstoneResult.completed || !appliedPage.completed) {\n // Keep this page retryable without discarding independent lanes, including\n // children of roots first discovered here. Otherwise the root becomes known\n // but its children are never fetched by subsequent root-only refreshes.\n return { changedCount, complete: false, shouldStop: false };\n }\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const didMarkFetched = await markContainerParentLaneFetched({\n isCurrent: input.isCurrent,\n response,\n state,\n syncLane,\n });\n if (!didMarkFetched) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n if (!response.hasMore) {\n return { changedCount, complete: true, shouldStop: false };\n }\n if (!response.nextWatermark) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n queueContinuationLane({\n parentId: lane.parentId,\n watermark: response.nextWatermark,\n });\n return { changedCount, complete: true, shouldStop: false };\n}\n\nfunction takeContainerParentLaneBatch(input: {\n lanes: ContainerParentHydrationLane[];\n state: RemoteContainerHydrationState;\n}): ContainerParentHydrationLane[] {\n const { lanes, state } = input;\n const batch: ContainerParentHydrationLane[] = [];\n\n while (\n lanes.length > 0 &&\n batch.length < CONTAINER_PARENT_HYDRATION_CONCURRENCY\n ) {\n const lane = lanes.shift();\n if (\n lane &&\n (lane.parentId === null || state.containersById.has(lane.parentId))\n ) {\n batch.push(lane);\n }\n }\n\n return batch;\n}\n\nasync function applyContainerParentLaneBatch(input: {\n childIdsByParentId: ContainerChildIndex;\n fetchedPages: ReadonlyArray<FetchedContainerParentLanePage>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n lanes: ContainerParentHydrationLane[];\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<HydrationProgress> {\n const {\n childIdsByParentId,\n fetchedPages,\n host,\n lanes,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n let changedCount = 0;\n let complete = true;\n\n for (const fetchedPage of fetchedPages) {\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n if (\n fetchedPage.lane.parentId !== null &&\n !state.containersById.has(fetchedPage.lane.parentId)\n ) {\n continue;\n }\n\n const result = await applyContainerParentLanePage({\n childIdsByParentId,\n fetchedPage,\n host,\n isCurrent: input.isCurrent,\n queueContinuationLane: (lane) => lanes.push(lane),\n queueParentLane,\n seenContainerIds,\n state,\n });\n changedCount += result.changedCount;\n complete &&= result.complete;\n\n if (result.shouldStop) {\n return { changedCount, complete: false, shouldStop: true };\n }\n }\n\n return { changedCount, complete, shouldStop: false };\n}\n\nexport async function hydrateContainerParentLanes(input: {\n childIdsByParentId: ContainerChildIndex;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n lanes: ContainerParentHydrationLane[];\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<HydrationProgress> {\n const {\n childIdsByParentId,\n host,\n lanes,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n let changedCount = 0;\n let complete = true;\n\n while (lanes.length > 0) {\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const batch = takeContainerParentLaneBatch({ lanes, state });\n if (batch.length === 0) {\n continue;\n }\n\n const fetchedPages = await fetchContainerParentLaneBatch({\n batch,\n isCurrent: input.isCurrent,\n state,\n });\n if (!fetchedPages) {\n return { changedCount, complete: false, shouldStop: true };\n }\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const result = await applyContainerParentLaneBatch({\n childIdsByParentId,\n fetchedPages,\n host,\n isCurrent: input.isCurrent,\n lanes,\n queueParentLane,\n seenContainerIds,\n state,\n });\n changedCount += result.changedCount;\n complete &&= result.complete;\n\n if (result.shouldStop) {\n return { changedCount, complete: false, shouldStop: true };\n }\n }\n\n return { changedCount, complete, shouldStop: false };\n}\n"]}
1
+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EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;QAC7D,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,6BAA6B,CAAC;YACjD,kBAAkB;YAClB,YAAY;YACZ,IAAI;YACJ,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,KAAK;YACL,eAAe;YACf,eAAe;YACf,gBAAgB;YAChB,KAAK;SACN,CAAC,CAAC;QACH,YAAY,IAAI,MAAM,CAAC,YAAY,CAAC;QACpC,QAAQ,KAAK,MAAM,CAAC,QAAQ,CAAC;QAE7B,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;YACtB,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;QAC7D,CAAC;IACH,CAAC;IAED,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC;AACvD,CAAC","sourcesContent":["import {\n createPrincipalPolicyOperation,\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../../principals/runtimePolicyWarmer\";\nimport { prefetchDestinationProjections } from \"../destination/destinationPrefetch\";\nimport { cachedDestinationRole } from \"../destination/destinationRoleCache\";\nimport { markContainerParentLaneFetched } from \"../lanes/laneFetchMarkers\";\nimport { fetchContainerParentLaneBatch } from \"../lanes/parentLaneFetch\";\nimport { cacheRemoteContainerPrincipalPolicies } from \"../principalPolicyCache\";\nimport {\n applyContainerTombstones,\n getApplicableRemoteContainerItems,\n} from \"../tombstoneApplication\";\nimport type {\n ContainerChildIndex,\n ContainerParentHydrationLane,\n ExpectedContainerState,\n FetchedContainerParentLanePage,\n ListedRemoteContainerPageItem,\n QueueContainerParentLane,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"../types\";\nimport { containerStateMatchesFingerprint } from \"./containerStateFingerprint\";\nimport { loadPausedContainerFilter } from \"./organizationSyncPauseFilter\";\nimport {\n listRemoteContainerIdsWithPendingMetadataUpdates,\n listRemoteContainerIdsWithPendingStructuralIntents,\n upsertIsolatedRemoteContainerState,\n} from \"./remoteContainerState\";\n\nconst CONTAINER_PARENT_HYDRATION_CONCURRENCY = 4;\n\ninterface HydrationProgress {\n changedCount: number;\n complete: boolean;\n shouldStop: boolean;\n}\n// Re-checked inside the commit: a pause from another device can land after\n// the page was filtered, and its cleanup may already have run.\nfunction currentUnlessPaused(\n input: {\n isCurrent?: (() => boolean) | undefined;\n isPaused: (container: ListedRemoteContainerPageItem) => boolean;\n },\n container: ListedRemoteContainerPageItem,\n): () => boolean {\n return () => input.isCurrent?.() !== false && !input.isPaused(container);\n}\n\nasync function applyRemoteContainerPage(input: {\n childIdsByParentId: ContainerChildIndex;\n expectedContainerStates: ReadonlyMap<string, ExpectedContainerState>;\n expectedHydrationTombstones: FetchedContainerParentLanePage[\"expectedHydrationTombstones\"];\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n /** Live pause check; a pause arriving mid-page stops the commit. */\n isPaused: (container: ListedRemoteContainerPageItem) => boolean;\n items: ReadonlyArray<ListedRemoteContainerPageItem>;\n /** The hydration pass's token: its pages share one directory discovery. */\n policyOperation: PrincipalPolicyOperation;\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<{ changedCount: number; completed: boolean }> {\n const {\n childIdsByParentId,\n expectedContainerStates,\n expectedHydrationTombstones,\n host,\n items,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n let hydratedCount = 0;\n let pageCompleted = true;\n await cacheRemoteContainerPrincipalPolicies({\n cacheReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n state.runtime,\n { operation: input.policyOperation },\n ),\n remoteContainers: items,\n stillCurrent: input.isCurrent,\n });\n if (input.isCurrent?.() === false) {\n return { changedCount: 0, completed: false };\n }\n const [\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n ] = await Promise.all([\n listRemoteContainerIdsWithPendingMetadataUpdates({\n remoteContainers: items,\n state,\n }),\n listRemoteContainerIdsWithPendingStructuralIntents({\n remoteContainers: items,\n state,\n }),\n ]);\n if (input.isCurrent?.() === false) {\n return { changedCount: 0, completed: false };\n }\n const prefetchedProjections = await prefetchDestinationProjections({\n containerIds: items.flatMap((item) =>\n seenContainerIds.has(item.id) ||\n state.containersById.has(item.id) ||\n expectedHydrationTombstones.get(item.id) ||\n cachedDestinationRole(state.runtime.infra.execSql, item)\n ? []\n : [item.id],\n ),\n isCurrent: input.isCurrent,\n runtime: state.runtime,\n });\n for (const container of items) {\n if (input.isCurrent?.() === false) {\n return { changedCount: hydratedCount, completed: false };\n }\n if (!seenContainerIds.has(container.id)) {\n if (\n !containerStateMatchesFingerprint({\n currentState: state.containersById.get(container.id),\n expectedFingerprint: expectedContainerStates.get(container.id)\n ?.fingerprint,\n })\n ) {\n pageCompleted = false;\n continue;\n }\n const upserted = await upsertIsolatedRemoteContainerState({\n childIdsByParentId,\n containerIdsWithPendingMetadataUpdates,\n containerIdsWithPendingStructuralIntents,\n host,\n isCurrent: currentUnlessPaused(input, container),\n expectedHydrationTombstone:\n expectedHydrationTombstones.get(container.id) ?? null,\n prefetchedProjection: prefetchedProjections.get(container.id),\n remoteContainer: container,\n state,\n });\n if (!upserted) {\n pageCompleted = false;\n continue;\n }\n seenContainerIds.add(container.id);\n hydratedCount += 1;\n if (input.isCurrent?.() === false) {\n return { changedCount: hydratedCount, completed: false };\n }\n }\n queueParentLane(container.id);\n }\n\n return { changedCount: hydratedCount, completed: pageCompleted };\n}\n\nexport function canHydrateRemoteContainers(\n state: RemoteContainerHydrationState,\n): boolean {\n return (\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online &&\n state.runtime.infra.dbStatus === \"ready\"\n );\n}\n\nasync function applyContainerParentLanePage(input: {\n childIdsByParentId: ContainerChildIndex;\n fetchedPage: FetchedContainerParentLanePage;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n policyOperation: PrincipalPolicyOperation;\n queueContinuationLane: (lane: ContainerParentHydrationLane) => void;\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<HydrationProgress> {\n const {\n childIdsByParentId,\n fetchedPage,\n host,\n queueContinuationLane,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n const {\n expectedContainerStates,\n expectedHydrationTombstones,\n lane,\n response,\n syncLane,\n } = fetchedPage;\n let changedCount = 0;\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const remoteContainerItems = getApplicableRemoteContainerItems(response);\n const tombstoneResult = await applyContainerTombstones({\n childIdsByParentId,\n expectedContainerStates,\n isCurrent: input.isCurrent,\n remoteContainerItems,\n response,\n state,\n });\n if (!tombstoneResult.current) {\n return { changedCount, complete: false, shouldStop: true };\n }\n changedCount += tombstoneResult.changedCount;\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n if (tombstoneResult.changedCount > 0) {\n // A live tombstone cascade may have orphaned documents (row 3); re-arm\n // document priming so their null-scoped passes run now rather than on\n // the next startup.\n host.requestDocumentPriming?.();\n }\n\n // A paused organization's containers stay off the device. Skipping them\n // here, after tombstones saw the full page, still lets the lane complete\n // and its watermark advance; their children are never queued.\n const isPaused = await loadPausedContainerFilter(state);\n const appliedPage = await applyRemoteContainerPage({\n childIdsByParentId,\n expectedContainerStates,\n expectedHydrationTombstones,\n host,\n isCurrent: input.isCurrent,\n isPaused,\n items: remoteContainerItems.filter((item) => !isPaused(item)),\n policyOperation: input.policyOperation,\n queueParentLane,\n seenContainerIds,\n state,\n });\n changedCount += appliedPage.changedCount;\n if (!tombstoneResult.completed || !appliedPage.completed) {\n // Keep this page retryable without discarding independent lanes, including\n // children of roots first discovered here. Otherwise the root becomes known\n // but its children are never fetched by subsequent root-only refreshes.\n return { changedCount, complete: false, shouldStop: false };\n }\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const didMarkFetched = await markContainerParentLaneFetched({\n isCurrent: input.isCurrent,\n response,\n state,\n syncLane,\n });\n if (!didMarkFetched) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n if (!response.hasMore) {\n return { changedCount, complete: true, shouldStop: false };\n }\n if (!response.nextWatermark) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n queueContinuationLane({\n parentId: lane.parentId,\n watermark: response.nextWatermark,\n });\n return { changedCount, complete: true, shouldStop: false };\n}\n\nfunction takeContainerParentLaneBatch(input: {\n lanes: ContainerParentHydrationLane[];\n state: RemoteContainerHydrationState;\n}): ContainerParentHydrationLane[] {\n const { lanes, state } = input;\n const batch: ContainerParentHydrationLane[] = [];\n\n while (\n lanes.length > 0 &&\n batch.length < CONTAINER_PARENT_HYDRATION_CONCURRENCY\n ) {\n const lane = lanes.shift();\n if (\n lane &&\n (lane.parentId === null || state.containersById.has(lane.parentId))\n ) {\n batch.push(lane);\n }\n }\n\n return batch;\n}\n\nasync function applyContainerParentLaneBatch(input: {\n childIdsByParentId: ContainerChildIndex;\n fetchedPages: ReadonlyArray<FetchedContainerParentLanePage>;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n lanes: ContainerParentHydrationLane[];\n policyOperation: PrincipalPolicyOperation;\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<HydrationProgress> {\n const {\n childIdsByParentId,\n fetchedPages,\n host,\n lanes,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n let changedCount = 0;\n let complete = true;\n\n for (const fetchedPage of fetchedPages) {\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n if (\n fetchedPage.lane.parentId !== null &&\n !state.containersById.has(fetchedPage.lane.parentId)\n ) {\n continue;\n }\n\n const result = await applyContainerParentLanePage({\n childIdsByParentId,\n fetchedPage,\n host,\n isCurrent: input.isCurrent,\n policyOperation: input.policyOperation,\n queueContinuationLane: (lane) => lanes.push(lane),\n queueParentLane,\n seenContainerIds,\n state,\n });\n changedCount += result.changedCount;\n complete &&= result.complete;\n\n if (result.shouldStop) {\n return { changedCount, complete: false, shouldStop: true };\n }\n }\n\n return { changedCount, complete, shouldStop: false };\n}\n\nexport async function hydrateContainerParentLanes(input: {\n childIdsByParentId: ContainerChildIndex;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n lanes: ContainerParentHydrationLane[];\n queueParentLane: QueueContainerParentLane;\n seenContainerIds: Set<string>;\n state: RemoteContainerHydrationState;\n}): Promise<HydrationProgress> {\n const {\n childIdsByParentId,\n host,\n lanes,\n queueParentLane,\n seenContainerIds,\n state,\n } = input;\n let changedCount = 0;\n let complete = true;\n // One hydration pass is one policy operation: its pages share a discovery.\n const policyOperation = createPrincipalPolicyOperation();\n\n while (lanes.length > 0) {\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const batch = takeContainerParentLaneBatch({ lanes, state });\n if (batch.length === 0) {\n continue;\n }\n\n const fetchedPages = await fetchContainerParentLaneBatch({\n batch,\n isCurrent: input.isCurrent,\n state,\n });\n if (!fetchedPages) {\n return { changedCount, complete: false, shouldStop: true };\n }\n if (input.isCurrent?.() === false) {\n return { changedCount, complete: false, shouldStop: true };\n }\n\n const result = await applyContainerParentLaneBatch({\n childIdsByParentId,\n fetchedPages,\n host,\n isCurrent: input.isCurrent,\n lanes,\n policyOperation,\n queueParentLane,\n seenContainerIds,\n state,\n });\n changedCount += result.changedCount;\n complete &&= result.complete;\n\n if (result.shouldStop) {\n return { changedCount, complete: false, shouldStop: true };\n }\n }\n\n return { changedCount, complete, shouldStop: false };\n}\n"]}
@@ -5,7 +5,7 @@ import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjec
5
5
  import { reportKeyingVerificationErrorInCauseChain } from "../../../data/keyingProjectionVerification/error.js";
6
6
  import { createProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/userKeyResolver.js";
7
7
  import { loadDocumentPurgeCheckpoint } from "../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js";
8
- import { createRuntimePrincipalPolicyWarmer } from "../../principals/runtimePolicyWarmer.js";
8
+ import { createRuntimePrincipalPolicyWarmer, } from "../../principals/runtimePolicyWarmer.js";
9
9
  import { documentHeadMatchesOrganization } from "../documentDiscovery/documentHeadScope.js";
10
10
  export const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;
11
11
  /**
@@ -14,7 +14,7 @@ export const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;
14
14
  * every device an unbounded burst of fetches before the watermark advances.
15
15
  */
16
16
  export const HEAD_LINK_SET_LOADS_PER_RUN = 32;
17
- async function verifiedHeadLinkSet(runtime, deps, documentId, projection) {
17
+ async function verifiedHeadLinkSet(runtime, deps, documentId, projection, policyOperation) {
18
18
  const verified = {};
19
19
  await deps.assertDocumentWriterProjectionConsistent(projection, {
20
20
  // Only the link set is read; a bundle wrapped to superseded KEK targets
@@ -33,7 +33,7 @@ async function verifiedHeadLinkSet(runtime, deps, documentId, projection) {
33
33
  }
34
34
  },
35
35
  resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),
36
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime),
36
+ warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime, { operation: policyOperation }),
37
37
  });
38
38
  if (!verified.value) {
39
39
  throw new Error("Tombstone evidence lacks a verified document head");
@@ -61,10 +61,11 @@ async function reportUnavailableHead(runtime, documentId, error) {
61
61
  // A host logger that throws must not fail the discovery pass.
62
62
  }
63
63
  }
64
+ /** `policyOperation` lets one discovery pass share a directory discovery. */
64
65
  export function createDocumentHeadLinkSetLoader(runtime, deps = {
65
66
  assertDocumentWriterProjectionConsistent,
66
67
  loadDocumentPurgeCheckpoint,
67
- }) {
68
+ }, policyOperation) {
68
69
  return async (documentId, expectedManifestHash) => {
69
70
  try {
70
71
  // A verified purge proof is terminal signed evidence that the document
@@ -94,7 +95,7 @@ export function createDocumentHeadLinkSetLoader(runtime, deps = {
94
95
  runtime.util.log(`Container contents: tombstone evidence for document ${documentId} is unavailable (${result.status ?? "offline"})`);
95
96
  return null;
96
97
  }
97
- return await verifiedHeadLinkSet(runtime, deps, documentId, result.data);
98
+ return await verifiedHeadLinkSet(runtime, deps, documentId, result.data, policyOperation);
98
99
  }
99
100
  catch (error) {
100
101
  // Any failure leaves the tombstone unverified (held and retried); a
@@ -1 +1 @@
1
- {"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,yCAAyC,EAAE,MAAM,kDAAkD,CAAC;AAC7G,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAC7G,OAAO,EAAE,2BAA2B,EAAE,MAAM,gFAAgF,CAAC;AAC7H,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAM1F,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AA+BzF,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAChD;;;;GAIG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,CAAC;AAE9C,KAAK,UAAU,mBAAmB,CAChC,OAAyC,EACzC,IAAmC,EACnC,UAAkB,EAClB,UAA4C;IAE5C,MAAM,QAAQ,GAA4C,EAAE,CAAC;IAC7D,MAAM,IAAI,CAAC,wCAAwC,CAAC,UAAU,EAAE;QAC9D,w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AAC,UAAU,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC;gBAClC,MAAM,IAAI,GAAG,MAAM,uBAAuB,CAAC,UAAU,CAAC,CAAC;gBACvD,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,WAAW;oBAAE,SAAS;gBACpD,IAAI,CAAC,+BAA+B,CAAC,IAAI,EAAE,cAAc,CAAC;oBAAE,SAAS;gBACrE,qEAAqE;gBACrE,mEAAmE;gBACnE,MAAM,UAAU,GAAG,MAAM,4BAA4B,CAAC,UAAU,CAAC,CAAC,KAAK,CACrE,GAAG,EAAE,CAAC,MAAM,CAAC,gBAAgB,CAC9B,CAAC;gBACF,IAAI,IAAI,CAAC,WAAW,GAAG,UAAU;oBAAE,SAAS;gBAC5C,QAAQ,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACjD,CAAC;QACH,CAAC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EACnE,MAAM,CACP,CACF,CAAC;QACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport { loadDocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: typeof loadDocumentPurgeCheckpoint;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint,\n },\n): DocumentHeadLinkSetLoader {\n return async (documentId, expectedManifestHash) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n if (\n await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n )\n ) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n }\n if (!result.ok) {\n if (\n result.status === 404 &&\n result.code === DOCUMENT_NOT_FOUND_ERROR_CODE\n )\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${result.status ?? \"offline\"})`,\n );\n return null;\n }\n return await verifiedHeadLinkSet(runtime, deps, documentId, result.data);\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") continue;\n if (!documentHeadMatchesOrganization(head, organizationId)) continue;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n if (head.accessEpoch < localEpoch) continue;\n verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
1
+ {"version":3,"file":"documentTombstoneEvidence.js","sourceRoot":"","sources":["documentTombstoneEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,6BAA6B,GAE9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,O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CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACjD,CAAC;QACH,CAAC,CAAC;QACF,MAAM,OAAO,CAAC,GAAG,CACf,KAAK,CAAC,IAAI,CACR,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EACnE,MAAM,CACP,CACF,CAAC;QACF,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n DOCUMENT_NOT_FOUND_ERROR_CODE,\n type DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/keyingProjectionVerification/error\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport { loadDocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../principals/runtimePolicyWarmer\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport interface VerifiedDocumentHeadLinkSet {\n readonly organizationId: string | null;\n readonly accessEpoch: number;\n /** Present for a signed head; a terminal purge has no live access state. */\n readonly accessStateHash?: string;\n readonly linkedContainerIds: ReadonlyArray<string>;\n}\n\n/**\n * The document's verified head link set, or `null` when no verified head is\n * available: the projection could not be fetched (the requester may no\n * longer read the document, or it was purged) or failed verification.\n */\nexport type DocumentHeadLinkSetLoader = (\n documentId: string,\n expectedManifestHash?: string,\n) => Promise<VerifiedDocumentHeadLinkSet | \"not-found\" | null>;\n\n/** The highest access epoch local state records for the document. */\nexport type LocalDocumentAccessEpochLoader = (\n documentId: string,\n) => Promise<number>;\n\nexport interface DocumentHeadLinkSetLoaderDeps {\n readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;\n readonly loadDocumentPurgeCheckpoint: typeof loadDocumentPurgeCheckpoint;\n}\n\nexport const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;\n/**\n * Head loads per settle. Tombstones beyond it stay unverified and are held\n * for a later, backed-off retry, so a bulk move out of a folder does not cost\n * every device an unbounded burst of fetches before the watermark advances.\n */\nexport const HEAD_LINK_SET_LOADS_PER_RUN = 32;\n\nasync function verifiedHeadLinkSet(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps,\n documentId: string,\n projection: DocumentWriterProjectionResponse,\n policyOperation: PrincipalPolicyOperation | undefined,\n): Promise<VerifiedDocumentHeadLinkSet> {\n const verified: { value?: VerifiedDocumentHeadLinkSet } = {};\n await deps.assertDocumentWriterProjectionConsistent(projection, {\n // Only the link set is read; a bundle wrapped to superseded KEK targets\n // still carries the signed head.\n allowStaleContentKeyBundle: true,\n execSql: runtime.infra.execSql,\n onVerifiedAuthorization: (authorization) => {\n const head = authorization.documentManifestByHash.get(\n projection.documentManifest.manifestHash,\n );\n if (head && head.state.documentId === documentId) {\n verified.value = {\n organizationId: head.state.organizationId,\n accessEpoch: head.state.epoch,\n accessStateHash: head.manifestHash,\n linkedContainerIds: uniqueSortedStrings(\n head.state.linkedContainerIds,\n ),\n };\n }\n },\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: policyOperation },\n ),\n });\n if (!verified.value) {\n throw new Error(\"Tombstone evidence lacks a verified document head\");\n }\n return verified.value;\n}\n\nasync function reportUnavailableHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n error: unknown,\n): Promise<void> {\n const integrityFailure = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: \"document.tombstone-evidence\",\n },\n );\n try {\n if (\n !integrityFailure &&\n error instanceof ProjectionDependencyUnavailableError\n ) {\n // A policy can advance without changing this document's hash. Drop its\n // cached evidence so the held head can recover on the next run.\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is awaiting current policy history`,\n );\n return;\n }\n runtime.util.logError?.(\n \"Container contents: tombstone evidence is unavailable\",\n error,\n );\n } catch {\n // A host logger that throws must not fail the discovery pass.\n }\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint,\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n return async (documentId, expectedManifestHash) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n if (\n await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n )\n ) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n // Tombstones require a fresh head. Listings can reuse a matching cached\n // projection, whose signature and local checkpoint are still verified.\n if (!expectedManifestHash)\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n let result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n if (\n expectedManifestHash &&\n result.ok &&\n result.data.documentManifest.manifestHash !== expectedManifestHash\n ) {\n runtime.apiClient.evictDocumentWriterProjection(documentId);\n result = await runtime.apiClient.getDocumentWriterProjectionResult(\n documentId,\n { reportErrors: false },\n );\n }\n if (!result.ok) {\n if (\n result.status === 404 &&\n result.code === DOCUMENT_NOT_FOUND_ERROR_CODE\n )\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${result.status ?? \"offline\"})`,\n );\n return null;\n }\n return await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n );\n } catch (error) {\n // Any failure leaves the tombstone unverified (held and retried); a\n // thrown error here must not fail the whole discovery pass.\n await reportUnavailableHead(runtime, documentId, error);\n return null;\n }\n };\n}\n\nfunction judgeTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n head: VerifiedDocumentHeadLinkSet | null,\n): ContainerDocumentTombstoneVerdict[] {\n return tombstones.map((tombstone): ContainerDocumentTombstoneVerdict => {\n if (head === null) {\n return { kind: \"unverified\", tombstone };\n }\n if (head.linkedContainerIds.includes(tombstone.containerId)) {\n return {\n kind: \"refuted\",\n linkedContainerIds: head.linkedContainerIds,\n tombstone,\n };\n }\n return {\n kind: \"verified\",\n tombstone: {\n ...tombstone,\n accessEpoch: head.accessEpoch,\n linkedContainerIds: head.linkedContainerIds,\n },\n };\n });\n}\n\n/**\n * Judge listing tombstones against each document's verified head link set,\n * fetched once per document with bounded concurrency and a per-run cap. A\n * head whose epoch is below local document state is no evidence: it may be a\n * lagging replica or a replay, and applying it could delete rows a newer\n * listing or settled move wrote.\n */\nexport function createContainerDocumentTombstoneVerifier(\n organizationId: string | undefined,\n loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader,\n loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader,\n): ContainerDocumentTombstoneVerifier {\n return async (tombstones) => {\n const byDocumentId = new Map<string, ContainerDocumentTombstone[]>();\n for (const tombstone of tombstones) {\n const group = byDocumentId.get(tombstone.documentId) ?? [];\n group.push(tombstone);\n byDocumentId.set(tombstone.documentId, group);\n }\n const groups = [...byDocumentId.entries()];\n const verdicts: ContainerDocumentTombstoneVerdict[][] = groups.map(\n ([, group], index): ContainerDocumentTombstoneVerdict[] =>\n index < HEAD_LINK_SET_LOADS_PER_RUN\n ? judgeTombstones(group, null)\n : group.map((tombstone) => ({ kind: \"deferred\", tombstone })),\n );\n let next = 0;\n const worker = async () => {\n while (next < Math.min(groups.length, HEAD_LINK_SET_LOADS_PER_RUN)) {\n const index = next++;\n const entry = groups[index];\n if (!entry) break;\n const [documentId, group] = entry;\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") continue;\n if (!documentHeadMatchesOrganization(head, organizationId)) continue;\n // A local-state read that fails is treated like an unavailable head:\n // the tombstones stay held rather than failing the discovery pass.\n const localEpoch = await loadLocalDocumentAccessEpoch(documentId).catch(\n () => Number.MAX_SAFE_INTEGER,\n );\n if (head.accessEpoch < localEpoch) continue;\n verdicts[index] = judgeTombstones(group, head);\n }\n };\n await Promise.all(\n Array.from(\n { length: Math.min(HEAD_LINK_SET_LOAD_CONCURRENCY, groups.length) },\n worker,\n ),\n );\n return verdicts.flat();\n };\n}\n"]}
@@ -9,9 +9,14 @@ import type { ApiClient } from "../../internal/api-client/index.js";
9
9
  export interface PrincipalPolicyHistoryReader {
10
10
  readonly getPrincipalPolicyPages: ApiClient["getPrincipalPolicyPages"];
11
11
  readonly getProjectionPolicyHistoryPages: ApiClient["getProjectionPolicyHistoryPages"];
12
+ /**
13
+ * Conditional unpinned discovery. Readers that replay local or already
14
+ * fetched pages omit it, so discovery reads their first page instead.
15
+ */
16
+ readonly getPrincipalPolicyDiscovery?: ApiClient["getPrincipalPolicyDiscovery"] | undefined;
12
17
  }
13
18
  /** Reads one principal's own policy history. */
14
- export type PrincipalPolicyPageReader = Pick<PrincipalPolicyHistoryReader, "getPrincipalPolicyPages">;
19
+ export type PrincipalPolicyPageReader = Pick<PrincipalPolicyHistoryReader, "getPrincipalPolicyPages" | "getPrincipalPolicyDiscovery">;
15
20
  /** Reads an organization's public projection policy history. */
16
21
  export type ProjectionPolicyHistoryReader = Pick<PrincipalPolicyHistoryReader, "getProjectionPolicyHistoryPages">;
17
22
  /** The API client as a page reader, or undefined when this client has none. */
@@ -1,7 +1,10 @@
1
1
  /** The API client as a page reader, or undefined when this client has none. */
2
2
  export function apiPrincipalPolicyPageReader(apiClient) {
3
3
  const getPrincipalPolicyPages = apiClient.getPrincipalPolicyPages?.bind(apiClient);
4
- return getPrincipalPolicyPages ? { getPrincipalPolicyPages } : undefined;
4
+ const getPrincipalPolicyDiscovery = apiClient.getPrincipalPolicyDiscovery?.bind(apiClient);
5
+ return getPrincipalPolicyPages
6
+ ? { getPrincipalPolicyPages, getPrincipalPolicyDiscovery }
7
+ : undefined;
5
8
  }
6
9
  /** The API client as a projection reader, or undefined when it has none. */
7
10
  export function apiProjectionPolicyHistoryReader(apiClient) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyHistoryReader.js","sourceRoot":"","sources":["principalPolicyHistoryReader.ts"],"names":[],"mappings":"AA0BA,+EAA+E;AAC/E,MAAM,UAAU,4BAA4B,CAC1C,SAA6C;IAE7C,MAAM,uBAAuB,GAC3B,SAAS,CAAC,uBAAuB,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACrD,OAAO,uBAAuB,CAAC,CAAC,CAAC,EAAE,uBAAuB,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3E,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,gCAAgC,CAC9C,SAAiD;IAEjD,MAAM,+BAA+B,GACnC,SAAS,CAAC,+BAA+B,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7D,OAAO,+BAA+B;QACpC,CAAC,CAAC,EAAE,+BAA+B,EAAE;QACrC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\n\n/**\n * Where recovery reads signed principal policy history. The API client is the\n * production reader; registration reads a just-provisioned principal from its\n * local bundles, and directory discovery replays a page it already fetched.\n * Every page is untrusted input to the same verifier, whichever reader\n * supplied it.\n */\nexport interface PrincipalPolicyHistoryReader {\n readonly getPrincipalPolicyPages: ApiClient[\"getPrincipalPolicyPages\"];\n readonly getProjectionPolicyHistoryPages: ApiClient[\"getProjectionPolicyHistoryPages\"];\n}\n\n/** Reads one principal's own policy history. */\nexport type PrincipalPolicyPageReader = Pick<\n PrincipalPolicyHistoryReader,\n \"getPrincipalPolicyPages\"\n>;\n\n/** Reads an organization's public projection policy history. */\nexport type ProjectionPolicyHistoryReader = Pick<\n PrincipalPolicyHistoryReader,\n \"getProjectionPolicyHistoryPages\"\n>;\n\n/** The API client as a page reader, or undefined when this client has none. */\nexport function apiPrincipalPolicyPageReader(\n apiClient: Partial<PrincipalPolicyPageReader>,\n): PrincipalPolicyPageReader | undefined {\n const getPrincipalPolicyPages =\n apiClient.getPrincipalPolicyPages?.bind(apiClient);\n return getPrincipalPolicyPages ? { getPrincipalPolicyPages } : undefined;\n}\n\n/** The API client as a projection reader, or undefined when it has none. */\nexport function apiProjectionPolicyHistoryReader(\n apiClient: Partial<ProjectionPolicyHistoryReader>,\n): ProjectionPolicyHistoryReader | undefined {\n const getProjectionPolicyHistoryPages =\n apiClient.getProjectionPolicyHistoryPages?.bind(apiClient);\n return getProjectionPolicyHistoryPages\n ? { getProjectionPolicyHistoryPages }\n : undefined;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyHistoryReader.js","sourceRoot":"","sources":["principalPolicyHistoryReader.ts"],"names":[],"mappings":"AAiCA,+EAA+E;AAC/E,MAAM,UAAU,4BAA4B,CAC1C,SAA6C;IAE7C,MAAM,uBAAuB,GAC3B,SAAS,CAAC,uBAAuB,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACrD,MAAM,2BAA2B,GAC/B,SAAS,CAAC,2BAA2B,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACzD,OAAO,uBAAuB;QAC5B,CAAC,CAAC,EAAE,uBAAuB,EAAE,2BAA2B,EAAE;QAC1D,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,gCAAgC,CAC9C,SAAiD;IAEjD,MAAM,+BAA+B,GACnC,SAAS,CAAC,+BAA+B,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7D,OAAO,+BAA+B;QACpC,CAAC,CAAC,EAAE,+BAA+B,EAAE;QACrC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\n\n/**\n * Where recovery reads signed principal policy history. The API client is the\n * production reader; registration reads a just-provisioned principal from its\n * local bundles, and directory discovery replays a page it already fetched.\n * Every page is untrusted input to the same verifier, whichever reader\n * supplied it.\n */\nexport interface PrincipalPolicyHistoryReader {\n readonly getPrincipalPolicyPages: ApiClient[\"getPrincipalPolicyPages\"];\n readonly getProjectionPolicyHistoryPages: ApiClient[\"getProjectionPolicyHistoryPages\"];\n /**\n * Conditional unpinned discovery. Readers that replay local or already\n * fetched pages omit it, so discovery reads their first page instead.\n */\n readonly getPrincipalPolicyDiscovery?:\n | ApiClient[\"getPrincipalPolicyDiscovery\"]\n | undefined;\n}\n\n/** Reads one principal's own policy history. */\nexport type PrincipalPolicyPageReader = Pick<\n PrincipalPolicyHistoryReader,\n \"getPrincipalPolicyPages\" | \"getPrincipalPolicyDiscovery\"\n>;\n\n/** Reads an organization's public projection policy history. */\nexport type ProjectionPolicyHistoryReader = Pick<\n PrincipalPolicyHistoryReader,\n \"getProjectionPolicyHistoryPages\"\n>;\n\n/** The API client as a page reader, or undefined when this client has none. */\nexport function apiPrincipalPolicyPageReader(\n apiClient: Partial<PrincipalPolicyPageReader>,\n): PrincipalPolicyPageReader | undefined {\n const getPrincipalPolicyPages =\n apiClient.getPrincipalPolicyPages?.bind(apiClient);\n const getPrincipalPolicyDiscovery =\n apiClient.getPrincipalPolicyDiscovery?.bind(apiClient);\n return getPrincipalPolicyPages\n ? { getPrincipalPolicyPages, getPrincipalPolicyDiscovery }\n : undefined;\n}\n\n/** The API client as a projection reader, or undefined when it has none. */\nexport function apiProjectionPolicyHistoryReader(\n apiClient: Partial<ProjectionPolicyHistoryReader>,\n): ProjectionPolicyHistoryReader | undefined {\n const getProjectionPolicyHistoryPages =\n apiClient.getProjectionPolicyHistoryPages?.bind(apiClient);\n return getProjectionPolicyHistoryPages\n ? { getProjectionPolicyHistoryPages }\n : undefined;\n}\n"]}