@tearleads/client-sdk 0.1.255 → 0.1.257

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/client/documents/index.d.ts +5 -2
  2. package/client/documents/index.js +6 -1
  3. package/client/documents/index.js.map +1 -1
  4. package/client/index.d.ts +1 -1
  5. package/client/index.js.map +1 -1
  6. package/data/blobs/attachments/types.d.ts +4 -2
  7. package/data/blobs/attachments/types.js.map +1 -1
  8. package/data/documents/documentContent.d.ts +2 -0
  9. package/data/documents/documentContent.js +7 -0
  10. package/data/documents/documentContent.js.map +1 -1
  11. package/data/documents/shared/manifestBundleReaders.js +1 -1
  12. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  13. package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
  14. package/data/documents/shared/projection/documentCreateSigner.js +49 -0
  15. package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
  16. package/data/documents/shared/projection/index.d.ts +1 -0
  17. package/data/documents/shared/projection/index.js +1 -0
  18. package/data/documents/shared/projection/index.js.map +1 -1
  19. package/data/documents/shared/readers.js +1 -1
  20. package/data/documents/shared/readers.js.map +1 -1
  21. package/data/documents/shared/types.d.ts +1 -0
  22. package/data/documents/shared/types.js.map +1 -1
  23. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  24. package/data/persistence/documents/documentsPersistence.js +4 -1
  25. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  26. package/index.d.ts +3 -3
  27. package/index.js +2 -2
  28. package/index.js.map +1 -1
  29. package/internal/api-client/ApiClient.d.ts +2 -2
  30. package/internal/api-client/apiRequestRuntime.js +12 -8
  31. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  32. package/internal/api-client/binaryResponseOperationTransport.js +2 -2
  33. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  34. package/internal/api-client/client/blobs.d.ts +2 -2
  35. package/internal/api-client/client/blobs.js +21 -9
  36. package/internal/api-client/client/blobs.js.map +1 -1
  37. package/internal/api-client/client/writerProjections.js +2 -1
  38. package/internal/api-client/client/writerProjections.js.map +1 -1
  39. package/internal/api-client/operationResponse.js +3 -3
  40. package/internal/api-client/operationResponse.js.map +1 -1
  41. package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
  42. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  43. package/internal/api-client/sessionRefresh.js +6 -1
  44. package/internal/api-client/sessionRefresh.js.map +1 -1
  45. package/internal/api-client/sessionResponse.js +5 -2
  46. package/internal/api-client/sessionResponse.js.map +1 -1
  47. package/internal/api-client/types.d.ts +2 -0
  48. package/internal/api-client/types.js.map +1 -1
  49. package/package.json +1 -1
  50. package/stores/container-contents/hydration/remoteHydrationRequest.js +6 -5
  51. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  52. package/stores/container-contents/hydration/trackContainerHydration.js +35 -0
  53. package/stores/container-contents/hydration/trackContainerHydration.js.map +1 -0
  54. package/stores/container-contents/state.js +7 -2
  55. package/stores/container-contents/state.js.map +1 -1
  56. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +1 -0
  57. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  58. package/stores/container-contents/types.d.ts +2 -0
  59. package/stores/container-contents/types.js.map +1 -1
  60. package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
  61. package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
  62. package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
  63. package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
  64. package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
  65. package/stores/documents/documentStore/state.js +3 -1
  66. package/stores/documents/documentStore/state.js.map +1 -1
  67. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  68. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  69. package/stores/documents/index.d.ts +1 -0
  70. package/stores/documents/index.js +1 -0
  71. package/stores/documents/index.js.map +1 -1
  72. package/stores/documents/types.d.ts +1 -0
  73. package/stores/documents/types.js.map +1 -1
  74. package/workflows/blobs/upload/index.d.ts +1 -1
  75. package/workflows/blobs/upload/index.js +36 -18
  76. package/workflows/blobs/upload/index.js.map +1 -1
  77. package/workflows/blobs/upload/multipartStageResolution.js +12 -2
  78. package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
  79. package/workflows/blobs/upload/multipartUpload.js +10 -2
  80. package/workflows/blobs/upload/multipartUpload.js.map +1 -1
  81. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
  82. package/workflows/container-contents/documentQueries/index.d.ts +1 -1
  83. package/workflows/container-contents/documentQueries/index.js +2 -2
  84. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  85. package/workflows/container-contents/index.d.ts +1 -0
  86. package/workflows/container-contents/index.js +1 -0
  87. package/workflows/container-contents/index.js.map +1 -1
  88. package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
  89. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
  90. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  91. package/workflows/documents/create/createAdoption.js +2 -50
  92. package/workflows/documents/create/createAdoption.js.map +1 -1
  93. package/workflows/documents/create/createResponse.js +12 -1
  94. package/workflows/documents/create/createResponse.js.map +1 -1
  95. package/workflows/documents/create/createSubmission.js +14 -0
  96. package/workflows/documents/create/createSubmission.js.map +1 -0
  97. package/workflows/documents/create/index.d.ts +3 -14
  98. package/workflows/documents/create/index.js +76 -67
  99. package/workflows/documents/create/index.js.map +1 -1
  100. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
  101. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
  102. package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
  103. package/workflows/documents/purge/absentDocumentPurge.js +23 -0
  104. package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
  105. package/workflows/documents/purge/index.d.ts +1 -0
  106. package/workflows/documents/purge/index.js +1 -0
  107. package/workflows/documents/purge/index.js.map +1 -1
  108. package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
  109. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
@@ -0,0 +1,160 @@
1
+ import type { ListContainerDocumentLanesRequest, ListContainerParentLanesRequest } from "../../../internal/validators/request/index.js";
2
+ import type { EffectiveAccessLevel, ReferencedPrincipalStateResponse, SyncWatermark } from "../../../internal/validators/response/index.js";
3
+ import type { DiscoveredDocumentInput, DocumentSummary } from "../../../data/documents/documentSummary.js";
4
+ import type { DiscoveredDocumentCandidate } from "../../../data/persistence/documents/documentDiscoveryEvidencePersistence.js";
5
+ export interface ListedContainerDocument {
6
+ createdAt: string;
7
+ currentAccessEpoch: number;
8
+ currentAccessStateHash: string;
9
+ effectiveAccessLevel?: EffectiveAccessLevel | undefined;
10
+ id: string;
11
+ linkedContainerIds: string[];
12
+ referencedPrincipals: ReferencedPrincipalStateResponse[];
13
+ updatedAt: string;
14
+ }
15
+ export interface ListContainerDocumentsResponse {
16
+ hasMore: boolean;
17
+ items: ListedContainerDocument[];
18
+ nextWatermark: SyncWatermark | null;
19
+ tombstones: ReadonlyArray<{
20
+ containerId: string;
21
+ documentId: string;
22
+ updatedAt: string;
23
+ }>;
24
+ }
25
+ export interface ListedContainer {
26
+ id: string;
27
+ }
28
+ export interface ListContainersResponse {
29
+ hasMore: boolean;
30
+ items: ListedContainer[];
31
+ nextWatermark: SyncWatermark | null;
32
+ }
33
+ export interface ListContainerParentLanesResponse {
34
+ results: ReadonlyArray<{
35
+ laneId: string;
36
+ page: ListContainersResponse;
37
+ }>;
38
+ }
39
+ export type ContainerDocumentLaneResult = {
40
+ readonly laneId: string;
41
+ readonly page: ListContainerDocumentsResponse;
42
+ } | {
43
+ readonly failure: {
44
+ readonly code?: string | undefined;
45
+ };
46
+ readonly laneId: string;
47
+ };
48
+ export interface ContainerDocumentDiscoveryApi {
49
+ readonly listContainerDocumentLanes: (input: ListContainerDocumentLanesRequest, options?: {
50
+ readonly reportErrors?: boolean | undefined;
51
+ }) => Promise<{
52
+ readonly results: ReadonlyArray<ContainerDocumentLaneResult>;
53
+ } | null>;
54
+ readonly listContainerParentLanes: (input: ListContainerParentLanesRequest) => Promise<ListContainerParentLanesResponse | null>;
55
+ }
56
+ /**
57
+ * One page per lane, aligned with the requested lanes: `null` for a lane the
58
+ * server rejected, or `null` overall when the request itself failed.
59
+ */
60
+ export type ContainerDocumentLaneLister = (lanes: ReadonlyArray<{
61
+ readonly containerId: string;
62
+ readonly watermark: SyncWatermark | null;
63
+ }>) => Promise<ReadonlyArray<ListContainerDocumentsResponse | null> | null>;
64
+ export interface DocumentLinkInput {
65
+ accessEpoch?: number | undefined;
66
+ containerIds: ReadonlyArray<string>;
67
+ documentId: string;
68
+ }
69
+ export type ContainerDocumentTombstone = ListContainerDocumentsResponse["tombstones"][number];
70
+ export interface VerifiedContainerDocumentTombstone extends ContainerDocumentTombstone {
71
+ /** The verified head's link-set epoch, not below the local document epoch. */
72
+ readonly accessEpoch: number;
73
+ /** The verified head link set; it omits `containerId`. */
74
+ readonly linkedContainerIds: ReadonlyArray<string>;
75
+ }
76
+ /**
77
+ * What the document's signed head says about a listing tombstone.
78
+ * - `verified`: the verified head link set omits the container; apply.
79
+ * - `refuted`: the verified head still links the container; keep visible and retry.
80
+ * - `unverified`: no verified head is available; hold, hide, retry later.
81
+ * - `deferred`: not attempted this run (the per-run head-load cap); hold
82
+ * without counting an attempt, so the retry backoff does not grow.
83
+ */
84
+ export type ContainerDocumentTombstoneVerdict = {
85
+ readonly kind: "verified";
86
+ readonly tombstone: VerifiedContainerDocumentTombstone;
87
+ } | {
88
+ readonly kind: "refuted";
89
+ /** The verified head link set, which contains the container. */
90
+ readonly linkedContainerIds: ReadonlyArray<string>;
91
+ readonly tombstone: ContainerDocumentTombstone;
92
+ } | {
93
+ readonly kind: "unverified";
94
+ readonly tombstone: ContainerDocumentTombstone;
95
+ } | {
96
+ readonly kind: "deferred";
97
+ readonly tombstone: ContainerDocumentTombstone;
98
+ };
99
+ export interface HeldContainerDocumentTombstoneInput extends ContainerDocumentTombstone {
100
+ /** Held without a verification attempt; the backoff does not advance. */
101
+ readonly deferred?: boolean | undefined;
102
+ /** A verified head still links it; retry the tombstone while keeping it visible. */
103
+ readonly refuted?: boolean | undefined;
104
+ }
105
+ export type ContainerDocumentTombstoneVerifier = (tombstones: ReadonlyArray<ContainerDocumentTombstone>) => Promise<ReadonlyArray<ContainerDocumentTombstoneVerdict>>;
106
+ export type ContainerDocumentPlacement = Pick<ContainerDocumentTombstone, "containerId" | "documentId">;
107
+ export interface ContainerDocumentTombstoneHoldStore {
108
+ holdContainerDocumentTombstones: (tombstones: ReadonlyArray<HeldContainerDocumentTombstoneInput>, stillCurrent: () => Promise<boolean>) => Promise<void>;
109
+ /** Held tombstones on these containers that are due for another attempt. */
110
+ listHeldContainerDocumentTombstones: (containerIds: ReadonlyArray<string>) => Promise<ReadonlyArray<ContainerDocumentTombstone>>;
111
+ /** The subset of placements that exist locally (link row or primary). */
112
+ listKnownContainerDocumentPlacements: (placements: ReadonlyArray<ContainerDocumentPlacement>) => Promise<ReadonlyArray<ContainerDocumentPlacement>>;
113
+ refuteContainerDocumentTombstoneHolds: (placements: ReadonlyArray<ContainerDocumentPlacement>, stillCurrent: () => Promise<boolean>) => Promise<void>;
114
+ }
115
+ export interface DiscoverContainerDocumentsOptions extends ContainerDocumentTombstoneHoldStore {
116
+ applyContainerDocumentTombstones: (tombstones: ReadonlyArray<VerifiedContainerDocumentTombstone>, stillCurrent: () => Promise<boolean>) => Promise<ReadonlyArray<DocumentSummary>>;
117
+ verifyContainerDocumentTombstones: ContainerDocumentTombstoneVerifier;
118
+ /** Allocate durable local order before fetching a listing. */
119
+ beginDocumentDiscovery: () => Promise<number>;
120
+ /** Persist pending candidates and return only signed placements. */
121
+ verifyDiscoveredDocuments: (inputs: ReadonlyArray<DiscoveredDocumentCandidate>, containerIds: ReadonlyArray<string>, generation: number, tombstones?: ReadonlyArray<ContainerDocumentTombstone>, conflictingDocumentIds?: ReadonlySet<string>) => Promise<{
122
+ inputs: ReadonlyArray<DiscoveredDocumentInput>;
123
+ /** False once a remote trust reset cancels this listing pass. */
124
+ isCurrent: () => Promise<boolean>;
125
+ /** Acknowledge only after local apply; true means no pending candidates remain. */
126
+ commit: () => Promise<boolean>;
127
+ }>;
128
+ cacheReferencedPrincipalPolicies?: (references: ReadonlyArray<ReferencedPrincipalStateResponse>) => Promise<void>;
129
+ containerId: string;
130
+ /** Completed unwatermarked listing, published only after local apply succeeds. */
131
+ onFullListing?: ((documentIds: ReadonlyArray<string>) => void) | undefined;
132
+ loadContainerDocumentWatermark: (containerId: string) => Promise<SyncWatermark | null>;
133
+ listContainerDocumentLanes: ContainerDocumentLaneLister;
134
+ /** Recheck stillCurrent under the mutation lock before persisting a listing. */
135
+ replaceDocumentLinksBatch: (inputs: ReadonlyArray<DocumentLinkInput>, stillCurrent: () => Promise<boolean>) => Promise<void>;
136
+ saveContainerDocumentWatermark: (containerId: string, watermark: SyncWatermark, stillCurrent: () => Promise<boolean>) => Promise<void>;
137
+ upsertDiscoveredDocuments: (inputs: ReadonlyArray<DiscoveredDocumentInput>, stillCurrent: () => Promise<boolean>) => Promise<ReadonlyArray<DocumentSummary>>;
138
+ }
139
+ export interface ListedContainerDocuments {
140
+ isFullListing: boolean;
141
+ items: ListedContainerDocument[];
142
+ nextWatermark: SyncWatermark | null;
143
+ tombstones: ContainerDocumentTombstone[];
144
+ }
145
+ /**
146
+ * One lane's listing: complete; `null` when the server refused the lane or a
147
+ * continuation came back without a watermark; or `"unavailable"` when the
148
+ * batched request carrying it failed or timed out, which says nothing about
149
+ * the lane and is worth retrying.
150
+ */
151
+ export type ContainerDocumentLaneListing = ListedContainerDocuments | "unavailable" | null;
152
+ /**
153
+ * Discovery could not list the container because its listing request failed
154
+ * or timed out. Unlike a refused lane, a later attempt may succeed, so the
155
+ * reconciler treats it as a failed reconciliation, not a skipped one.
156
+ */
157
+ export declare class ContainerDocumentListingUnavailableError extends Error {
158
+ readonly containerId: string;
159
+ constructor(containerId: string);
160
+ }
@@ -63,6 +63,6 @@ export interface ContainerDocumentQueries {
63
63
  }): Promise<void>;
64
64
  replaceDocumentLinksBatch(inputs: ReadonlyArray<ContainerDocumentLinkInput>): Promise<void>;
65
65
  saveContainerDocumentWatermark(containerId: string, watermark: SyncWatermark): Promise<void>;
66
- upsertDiscoveredDocuments(inputs: ReadonlyArray<DiscoveredDocumentInput>): Promise<ReadonlyArray<DocumentSummary>>;
66
+ upsertDiscoveredDocuments(inputs: ReadonlyArray<DiscoveredDocumentInput>, assertCurrent?: () => void): Promise<ReadonlyArray<DocumentSummary>>;
67
67
  }
68
68
  export declare function createContainerDocumentQueriesFromRuntime(runtime: ContainerDocumentQueriesRuntime): ContainerDocumentQueries;
@@ -204,8 +204,8 @@ export function createContainerDocumentQueriesFromRuntime(runtime) {
204
204
  async saveContainerDocumentWatermark(containerId, watermark) {
205
205
  await new ContainerSyncWatermarkRepository(execSql).saveWatermark(containerContentsSyncLane(containerId), watermark);
206
206
  },
207
- upsertDiscoveredDocuments(inputs) {
208
- return upsertDiscoveredDocuments(execSql, inputs);
207
+ upsertDiscoveredDocuments(inputs, assertCurrent) {
208
+ return upsertDiscoveredDocuments(execSql, inputs, assertCurrent);
209
209
  },
210
210
  };
211
211
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM,2EAA2E,CAAC;AACnF,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EACL,qCAAqC,EACrC,6CAA6C,GAC9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OAAO,CAAC,CAAC;QACvC,CAAC;QACD,iBAAiB;YACf,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;QACD,qBAAqB,CAAC,KAAK;YACzB,OAAO,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;QACD,yBAAyB,CAAC,MAAM;YAC9B,OAAO,IAAI,qCAAqC,CAC9C,OAAO,CACR,CAAC,yBAAyB,CAAC,MAAM,CAAC,CAAC;QACtC,CAAC;QACD,KAAK,CAAC,8BAA8B,CAAC,WAAW,EAAE,SAAS;YACzD,MAAM,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC,aAAa,CAC/D,yBAAyB,CAAC,WAAW,CAAC,EACtC,SAAS,CACV,CAAC;QACJ,CAAC;QACD,yBAAyB,CAAC,MAAM;YAC9B,OAAO,yBAAyB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACpD,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { SyncWatermark } from \"@tearleads/validators/response\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport {\n RECOVERY_FOLDER_MOVES_SQL,\n RETAINED_CONTAINER_METADATA_SQL,\n} from \"../../../data/persistence/container-contents/containerRecoveryPersistence\";\nimport {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport {\n DocumentContainerProjectionRepository,\n deleteContainerDocumentTombstonePlacementRows,\n} from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { loadLinkedDocumentSummaryRow } from \"../../../data/persistence/container-contents/linkedDocumentSummary\";\nimport {\n applyContainerDocumentTombstones as applyPersistedContainerDocumentTombstones,\n sqlDocumentsPersistence,\n upsertDiscoveredDocuments,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n LOCAL_INTENT_LANES,\n localIntentTables,\n} from \"../../../data/sqlite/schema\";\nimport { type ExecSql, ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport {\n listPendingWrites,\n type PendingWriteQueueItem,\n resetPendingWriteRetryState,\n} from \"../pendingWrites\";\nimport {\n createFolderRecoveryQueries,\n type RecoveryFolder,\n} from \"../recovery/folderRecovery\";\nimport type { ContainerDocumentObjectSyncState } from \"../syncState\";\nimport { hydratedProjectionSql } from \"./hydrationSql\";\nimport {\n getOrphanedDocumentQueryBind,\n getOrphanedDocumentWhereSql,\n} from \"./orphanedDocumentSql\";\nimport {\n listPendingDownloads,\n type PendingDownloadQueueItem,\n} from \"./pendingDownloads\";\nimport {\n mapContainerContentsDocumentSummaryRow,\n mapContainerContentsDocumentSyncStateRow,\n mapContainerItemRow,\n readContainerContentsContainerItemCount,\n} from \"./rows\";\nimport { listContainerDocumentSidebarWindow } from \"./sidebarWindow\";\nimport {\n clampContainerItemWindowValue,\n getContainerContentsContainerItemOrderBy,\n getContainerContentsContainerItemsBaseSql,\n getContainerContentsDocumentPendingStateCtes,\n getContainerItemWindowLimit,\n getOrphanedDocumentExistsSql,\n getOrphanedDocumentItemsBaseSql,\n listContainerContentsSqlIdBatches,\n} from \"./sql\";\nimport type {\n ContainerDocumentLinkInput,\n ContainerDocumentQueriesRuntime,\n ContainerDocumentSidebarWindow,\n ContainerDocumentTombstone,\n ContainerItemSort,\n ContainerItemWindow,\n} from \"./types\";\n\nexport type {\n ContainerDocumentLinkInput,\n ContainerDocumentSidebarRow,\n ContainerDocumentTombstone,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"./types\";\n\ninterface ListContainerItemWindowInput {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n limit: number;\n offset: number;\n sort: ContainerItemSort;\n visibleForeignSystemContainerNames?: ReadonlyArray<string> | undefined;\n visibleSystemSlots?: ReadonlyArray<ContainerSystemSlot> | undefined;\n}\n\nexport interface ContainerDocumentQueries {\n /** Read a hydrated linked document by cross-device identity, never a local id. */\n loadContainerDocumentSummary(input: {\n containerId: string;\n documentId: string;\n }): Promise<DocumentSummary | null>;\n listRecoveryFolderMoveIds(input: {\n currentOrganizationId: string | null;\n }): Promise<string[]>;\n listRecoveryFolders(input: {\n currentOrganizationId: string | null;\n }): Promise<RecoveryFolder[]>;\n discardRecoveryFolder(\n input: Pick<RecoveryFolder, \"containerId\" | \"organizationId\" | \"revision\">,\n ): Promise<boolean>;\n applyContainerDocumentTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n hasOrphanedDocuments(input: {\n currentOrganizationId: string | null;\n }): Promise<boolean>;\n listContainerDocumentSidebarWindow(input: {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n documentKind?: string | undefined;\n limit: number;\n offset: number;\n }): Promise<ContainerDocumentSidebarWindow>;\n listContainerItemWindow(\n input: ListContainerItemWindowInput,\n ): Promise<ContainerItemWindow>;\n loadDocumentSyncState(\n localId: string,\n ): Promise<ContainerDocumentObjectSyncState | null>;\n loadDocumentSummary(\n localId: string,\n options?: { requireHydrated?: boolean },\n ): Promise<DocumentSummary | null>;\n loadOrphanedDocumentSummary(input: {\n requireHydrated?: boolean;\n currentOrganizationId: string | null;\n localId: string;\n }): Promise<DocumentSummary | null>;\n loadContainerDocumentWatermark(\n containerId: string,\n ): Promise<SyncWatermark | null>;\n listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>>;\n listPendingDownloads(): Promise<ReadonlyArray<PendingDownloadQueueItem>>;\n listPendingWrites(): Promise<ReadonlyArray<PendingWriteQueueItem>>;\n retryPendingWriteItem(input: {\n localId: string;\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n }): Promise<void>;\n replaceDocumentLinksBatch(\n inputs: ReadonlyArray<ContainerDocumentLinkInput>,\n ): Promise<void>;\n saveContainerDocumentWatermark(\n containerId: string,\n watermark: SyncWatermark,\n ): Promise<void>;\n upsertDiscoveredDocuments(\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n}\n\nasync function listContainerItemWindow(\n execSql: ExecSql,\n input: ListContainerItemWindowInput,\n): Promise<ContainerItemWindow> {\n await ensureContainerTables(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, localIntentTables);\n\n const limit = getContainerItemWindowLimit(input.limit);\n const offset = clampContainerItemWindowValue(input.offset);\n const visibleSystemSlots = Array.from(\n new Set(input.visibleSystemSlots ?? []),\n );\n const currentOrganizationId = input.currentOrganizationId || null;\n const visibleForeignSystemContainerNames = currentOrganizationId\n ? Array.from(new Set(input.visibleForeignSystemContainerNames ?? []))\n : [];\n const orphaned = input.containerId === null;\n const bind = orphaned\n ? getOrphanedDocumentQueryBind(input.currentOrganizationId)\n : [\n input.containerId,\n ...visibleSystemSlots,\n ...(visibleForeignSystemContainerNames.length > 0\n ? [currentOrganizationId, ...visibleForeignSystemContainerNames]\n : []),\n input.containerId,\n input.containerId,\n ];\n const baseSql = orphaned\n ? getOrphanedDocumentItemsBaseSql()\n : getContainerContentsContainerItemsBaseSql(\n visibleSystemSlots.length,\n visibleForeignSystemContainerNames.length,\n );\n const countRows = await execSql(\n `SELECT COUNT(*) AS total_count FROM (${baseSql})`,\n bind,\n );\n const totalCount = readContainerContentsContainerItemCount(\n countRows[0] ?? {},\n );\n\n if (limit === 0 || offset >= totalCount) {\n return { rows: [], totalCount };\n }\n\n const rows = await execSql(\n `${baseSql} ORDER BY ${getContainerContentsContainerItemOrderBy(input.sort)} LIMIT ? OFFSET ?`,\n [...bind, limit, offset],\n );\n\n return {\n rows: rows.map((row) => mapContainerItemRow(input.containerId, row)),\n totalCount,\n };\n}\n\nasync function hasOrphanedDocuments(\n execSql: ExecSql,\n currentOrganizationId: string | null,\n): Promise<boolean> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n // One statement for all three probes; the folder probes need an\n // organization, as their standalone readers do.\n const folderProbes = currentOrganizationId\n ? `OR EXISTS(${RETAINED_CONTAINER_METADATA_SQL}) OR EXISTS(${RECOVERY_FOLDER_MOVES_SQL})`\n : \"\";\n if (currentOrganizationId)\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const rows = await execSql(\n `SELECT (EXISTS(${getOrphanedDocumentExistsSql()}) ${folderProbes}) AS found`,\n [\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...(currentOrganizationId\n ? [\n currentOrganizationId,\n LOCAL_INTENT_LANES.containerMove,\n currentOrganizationId,\n ]\n : []),\n ],\n );\n return Number(Object.values(rows[0] ?? {})[0] ?? 0) !== 0;\n}\n\nasync function queryContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n scope: { bind: ReadonlyArray<string | null>; whereSql: string },\n): Promise<DocumentSummary | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n SELECT\n d.local_id AS local_id,\n d.document_id AS document_id,\n d.container_id AS container_id,\n d.document_kind AS document_kind,\n d.title AS title,\n d.updated_at AS updated_at,\n stored.access_state_hash AS access_state_hash,\n stored.effective_access_level AS effective_access_level\n FROM document_projection d\n LEFT JOIN documents stored\n ON stored.app_kind = 'documents'\n AND stored.local_id = d.local_id\n WHERE d.local_id = ?\n ${scope.whereSql}\n LIMIT 1\n `,\n [localId, ...scope.bind],\n );\n\n return mapContainerContentsDocumentSummaryRow(rows[0] ?? {});\n}\n\nfunction loadContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: [],\n whereSql: requireHydrated\n ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}`\n : \"\",\n });\n}\n\nfunction loadContainerContentsOrphanedDocumentSummary(\n execSql: ExecSql,\n localId: string,\n currentOrganizationId: string | null,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: getOrphanedDocumentQueryBind(currentOrganizationId),\n whereSql: `${requireHydrated ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}` : \"\"} AND ${getOrphanedDocumentWhereSql(\n {\n documentIdSql: \"d.document_id\",\n projectionAlias: \"d\",\n },\n )}`,\n });\n}\n\nasync function loadContainerContentsDocumentSyncState(\n execSql: ExecSql,\n localId: string,\n): Promise<ContainerDocumentObjectSyncState | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n WITH ${getContainerContentsDocumentPendingStateCtes()}\n SELECT\n d.document_id AS document_id,\n COALESCE(document_updates.pending_update_count, 0) AS pending_update_count,\n COALESCE(document_attachments.pending_attachment_count, 0) AS pending_attachment_count,\n COALESCE(document_attachments.pending_attachment_bytes, 0) AS pending_attachment_bytes,\n NULL AS sync_last_error\n FROM document_projection d\n LEFT JOIN document_pending_update_counts document_updates\n ON document_updates.local_id = d.local_id\n LEFT JOIN document_pending_attachment_counts document_attachments\n ON document_attachments.local_id = d.local_id\n WHERE d.local_id = ?\n LIMIT 1\n `,\n [localId],\n );\n const [row] = rows;\n if (!row) {\n return null;\n }\n\n return mapContainerContentsDocumentSyncStateRow(row);\n}\n\nasync function listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql: ExecSql,\n documentIds: ReadonlyArray<string>,\n): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const documentIdBatch of listContainerContentsSqlIdBatches(\n uniqueDocumentIds,\n )) {\n const batchLinkedContainerIdsByDocumentId =\n await new DocumentContainerProjectionRepository(\n execSql,\n ).listLinkedContainerIdsByDocumentIds(documentIdBatch);\n for (const [\n documentId,\n linkedContainerIds,\n ] of batchLinkedContainerIdsByDocumentId.entries()) {\n linkedContainerIdsByDocumentId.set(\n documentId,\n Array.from(linkedContainerIds),\n );\n }\n }\n\n return linkedContainerIdsByDocumentId;\n}\n\nexport function createContainerDocumentQueriesFromRuntime(\n runtime: ContainerDocumentQueriesRuntime,\n): ContainerDocumentQueries {\n const execSql = runtime.infra.execSql;\n return {\n ...createFolderRecoveryQueries(execSql),\n async loadContainerDocumentSummary(input) {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n return mapContainerContentsDocumentSummaryRow(\n (await loadLinkedDocumentSummaryRow(execSql, input)) ?? {},\n );\n },\n applyContainerDocumentTombstones(tombstones) {\n return applyPersistedContainerDocumentTombstones(\n execSql,\n tombstones,\n deleteContainerDocumentTombstonePlacementRows,\n );\n },\n hasOrphanedDocuments({ currentOrganizationId }) {\n return hasOrphanedDocuments(execSql, currentOrganizationId);\n },\n listContainerDocumentSidebarWindow(input) {\n return listContainerDocumentSidebarWindow(execSql, input);\n },\n listContainerItemWindow(input) {\n return listContainerItemWindow(execSql, input);\n },\n loadDocumentSyncState(localId) {\n return loadContainerContentsDocumentSyncState(execSql, localId);\n },\n loadDocumentSummary(localId, options) {\n return loadContainerContentsDocumentSummary(\n execSql,\n localId,\n options?.requireHydrated ?? false,\n );\n },\n loadOrphanedDocumentSummary({\n currentOrganizationId,\n localId,\n requireHydrated = false,\n }) {\n return loadContainerContentsOrphanedDocumentSummary(\n execSql,\n localId,\n currentOrganizationId,\n requireHydrated,\n );\n },\n loadContainerDocumentWatermark(containerId) {\n return new ContainerSyncWatermarkRepository(execSql).loadWatermark(\n containerContentsSyncLane(containerId),\n );\n },\n listLinkedContainerIdsByDocumentIds(documentIds) {\n return listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql,\n documentIds,\n );\n },\n listPendingDownloads() {\n return listPendingDownloads(execSql);\n },\n listPendingWrites() {\n return listPendingWrites(execSql);\n },\n retryPendingWriteItem(input) {\n return resetPendingWriteRetryState(execSql, input);\n },\n replaceDocumentLinksBatch(inputs) {\n return new DocumentContainerProjectionRepository(\n execSql,\n ).replaceDocumentLinksBatch(inputs);\n },\n async saveContainerDocumentWatermark(containerId, watermark) {\n await new ContainerSyncWatermarkRepository(execSql).saveWatermark(\n containerContentsSyncLane(containerId),\n watermark,\n );\n },\n upsertDiscoveredDocuments(inputs) {\n return upsertDiscoveredDocuments(execSql, inputs);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM,2EAA2E,CAAC;AACnF,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EACL,qCAAqC,EACrC,6CAA6C,GAC9C,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,4BAA4B,EAAE,MAAM,oEAAoE,CAAC;AAClH,OAAO,EACL,gCAAgC,IAAI,yCAAyC,EAC7E,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAgB,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EACL,iBAAiB,EAEjB,2BAA2B,GAC5B,M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C,WAAW,EAAE,SAAS;YACzD,MAAM,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC,aAAa,CAC/D,yBAAyB,CAAC,WAAW,CAAC,EACtC,SAAS,CACV,CAAC;QACJ,CAAC;QACD,yBAAyB,CAAC,MAAM,EAAE,aAAa;YAC7C,OAAO,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC;QACnE,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { SyncWatermark } from \"@tearleads/validators/response\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport {\n RECOVERY_FOLDER_MOVES_SQL,\n RETAINED_CONTAINER_METADATA_SQL,\n} from \"../../../data/persistence/container-contents/containerRecoveryPersistence\";\nimport {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport {\n DocumentContainerProjectionRepository,\n deleteContainerDocumentTombstonePlacementRows,\n} from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { loadLinkedDocumentSummaryRow } from \"../../../data/persistence/container-contents/linkedDocumentSummary\";\nimport {\n applyContainerDocumentTombstones as applyPersistedContainerDocumentTombstones,\n sqlDocumentsPersistence,\n upsertDiscoveredDocuments,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n LOCAL_INTENT_LANES,\n localIntentTables,\n} from \"../../../data/sqlite/schema\";\nimport { type ExecSql, ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport {\n listPendingWrites,\n type PendingWriteQueueItem,\n resetPendingWriteRetryState,\n} from \"../pendingWrites\";\nimport {\n createFolderRecoveryQueries,\n type RecoveryFolder,\n} from \"../recovery/folderRecovery\";\nimport type { ContainerDocumentObjectSyncState } from \"../syncState\";\nimport { hydratedProjectionSql } from \"./hydrationSql\";\nimport {\n getOrphanedDocumentQueryBind,\n getOrphanedDocumentWhereSql,\n} from \"./orphanedDocumentSql\";\nimport {\n listPendingDownloads,\n type PendingDownloadQueueItem,\n} from \"./pendingDownloads\";\nimport {\n mapContainerContentsDocumentSummaryRow,\n mapContainerContentsDocumentSyncStateRow,\n mapContainerItemRow,\n readContainerContentsContainerItemCount,\n} from \"./rows\";\nimport { listContainerDocumentSidebarWindow } from \"./sidebarWindow\";\nimport {\n clampContainerItemWindowValue,\n getContainerContentsContainerItemOrderBy,\n getContainerContentsContainerItemsBaseSql,\n getContainerContentsDocumentPendingStateCtes,\n getContainerItemWindowLimit,\n getOrphanedDocumentExistsSql,\n getOrphanedDocumentItemsBaseSql,\n listContainerContentsSqlIdBatches,\n} from \"./sql\";\nimport type {\n ContainerDocumentLinkInput,\n ContainerDocumentQueriesRuntime,\n ContainerDocumentSidebarWindow,\n ContainerDocumentTombstone,\n ContainerItemSort,\n ContainerItemWindow,\n} from \"./types\";\n\nexport type {\n ContainerDocumentLinkInput,\n ContainerDocumentSidebarRow,\n ContainerDocumentTombstone,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"./types\";\n\ninterface ListContainerItemWindowInput {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n limit: number;\n offset: number;\n sort: ContainerItemSort;\n visibleForeignSystemContainerNames?: ReadonlyArray<string> | undefined;\n visibleSystemSlots?: ReadonlyArray<ContainerSystemSlot> | undefined;\n}\n\nexport interface ContainerDocumentQueries {\n /** Read a hydrated linked document by cross-device identity, never a local id. */\n loadContainerDocumentSummary(input: {\n containerId: string;\n documentId: string;\n }): Promise<DocumentSummary | null>;\n listRecoveryFolderMoveIds(input: {\n currentOrganizationId: string | null;\n }): Promise<string[]>;\n listRecoveryFolders(input: {\n currentOrganizationId: string | null;\n }): Promise<RecoveryFolder[]>;\n discardRecoveryFolder(\n input: Pick<RecoveryFolder, \"containerId\" | \"organizationId\" | \"revision\">,\n ): Promise<boolean>;\n applyContainerDocumentTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n hasOrphanedDocuments(input: {\n currentOrganizationId: string | null;\n }): Promise<boolean>;\n listContainerDocumentSidebarWindow(input: {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n documentKind?: string | undefined;\n limit: number;\n offset: number;\n }): Promise<ContainerDocumentSidebarWindow>;\n listContainerItemWindow(\n input: ListContainerItemWindowInput,\n ): Promise<ContainerItemWindow>;\n loadDocumentSyncState(\n localId: string,\n ): Promise<ContainerDocumentObjectSyncState | null>;\n loadDocumentSummary(\n localId: string,\n options?: { requireHydrated?: boolean },\n ): Promise<DocumentSummary | null>;\n loadOrphanedDocumentSummary(input: {\n requireHydrated?: boolean;\n currentOrganizationId: string | null;\n localId: string;\n }): Promise<DocumentSummary | null>;\n loadContainerDocumentWatermark(\n containerId: string,\n ): Promise<SyncWatermark | null>;\n listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>>;\n listPendingDownloads(): Promise<ReadonlyArray<PendingDownloadQueueItem>>;\n listPendingWrites(): Promise<ReadonlyArray<PendingWriteQueueItem>>;\n retryPendingWriteItem(input: {\n localId: string;\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n }): Promise<void>;\n replaceDocumentLinksBatch(\n inputs: ReadonlyArray<ContainerDocumentLinkInput>,\n ): Promise<void>;\n saveContainerDocumentWatermark(\n containerId: string,\n watermark: SyncWatermark,\n ): Promise<void>;\n upsertDiscoveredDocuments(\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n assertCurrent?: () => void,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n}\n\nasync function listContainerItemWindow(\n execSql: ExecSql,\n input: ListContainerItemWindowInput,\n): Promise<ContainerItemWindow> {\n await ensureContainerTables(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, localIntentTables);\n\n const limit = getContainerItemWindowLimit(input.limit);\n const offset = clampContainerItemWindowValue(input.offset);\n const visibleSystemSlots = Array.from(\n new Set(input.visibleSystemSlots ?? []),\n );\n const currentOrganizationId = input.currentOrganizationId || null;\n const visibleForeignSystemContainerNames = currentOrganizationId\n ? Array.from(new Set(input.visibleForeignSystemContainerNames ?? []))\n : [];\n const orphaned = input.containerId === null;\n const bind = orphaned\n ? getOrphanedDocumentQueryBind(input.currentOrganizationId)\n : [\n input.containerId,\n ...visibleSystemSlots,\n ...(visibleForeignSystemContainerNames.length > 0\n ? [currentOrganizationId, ...visibleForeignSystemContainerNames]\n : []),\n input.containerId,\n input.containerId,\n ];\n const baseSql = orphaned\n ? getOrphanedDocumentItemsBaseSql()\n : getContainerContentsContainerItemsBaseSql(\n visibleSystemSlots.length,\n visibleForeignSystemContainerNames.length,\n );\n const countRows = await execSql(\n `SELECT COUNT(*) AS total_count FROM (${baseSql})`,\n bind,\n );\n const totalCount = readContainerContentsContainerItemCount(\n countRows[0] ?? {},\n );\n\n if (limit === 0 || offset >= totalCount) {\n return { rows: [], totalCount };\n }\n\n const rows = await execSql(\n `${baseSql} ORDER BY ${getContainerContentsContainerItemOrderBy(input.sort)} LIMIT ? OFFSET ?`,\n [...bind, limit, offset],\n );\n\n return {\n rows: rows.map((row) => mapContainerItemRow(input.containerId, row)),\n totalCount,\n };\n}\n\nasync function hasOrphanedDocuments(\n execSql: ExecSql,\n currentOrganizationId: string | null,\n): Promise<boolean> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n // One statement for all three probes; the folder probes need an\n // organization, as their standalone readers do.\n const folderProbes = currentOrganizationId\n ? `OR EXISTS(${RETAINED_CONTAINER_METADATA_SQL}) OR EXISTS(${RECOVERY_FOLDER_MOVES_SQL})`\n : \"\";\n if (currentOrganizationId)\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const rows = await execSql(\n `SELECT (EXISTS(${getOrphanedDocumentExistsSql()}) ${folderProbes}) AS found`,\n [\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...(currentOrganizationId\n ? [\n currentOrganizationId,\n LOCAL_INTENT_LANES.containerMove,\n currentOrganizationId,\n ]\n : []),\n ],\n );\n return Number(Object.values(rows[0] ?? {})[0] ?? 0) !== 0;\n}\n\nasync function queryContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n scope: { bind: ReadonlyArray<string | null>; whereSql: string },\n): Promise<DocumentSummary | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n SELECT\n d.local_id AS local_id,\n d.document_id AS document_id,\n d.container_id AS container_id,\n d.document_kind AS document_kind,\n d.title AS title,\n d.updated_at AS updated_at,\n stored.access_state_hash AS access_state_hash,\n stored.effective_access_level AS effective_access_level\n FROM document_projection d\n LEFT JOIN documents stored\n ON stored.app_kind = 'documents'\n AND stored.local_id = d.local_id\n WHERE d.local_id = ?\n ${scope.whereSql}\n LIMIT 1\n `,\n [localId, ...scope.bind],\n );\n\n return mapContainerContentsDocumentSummaryRow(rows[0] ?? {});\n}\n\nfunction loadContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: [],\n whereSql: requireHydrated\n ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}`\n : \"\",\n });\n}\n\nfunction loadContainerContentsOrphanedDocumentSummary(\n execSql: ExecSql,\n localId: string,\n currentOrganizationId: string | null,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: getOrphanedDocumentQueryBind(currentOrganizationId),\n whereSql: `${requireHydrated ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}` : \"\"} AND ${getOrphanedDocumentWhereSql(\n {\n documentIdSql: \"d.document_id\",\n projectionAlias: \"d\",\n },\n )}`,\n });\n}\n\nasync function loadContainerContentsDocumentSyncState(\n execSql: ExecSql,\n localId: string,\n): Promise<ContainerDocumentObjectSyncState | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n WITH ${getContainerContentsDocumentPendingStateCtes()}\n SELECT\n d.document_id AS document_id,\n COALESCE(document_updates.pending_update_count, 0) AS pending_update_count,\n COALESCE(document_attachments.pending_attachment_count, 0) AS pending_attachment_count,\n COALESCE(document_attachments.pending_attachment_bytes, 0) AS pending_attachment_bytes,\n NULL AS sync_last_error\n FROM document_projection d\n LEFT JOIN document_pending_update_counts document_updates\n ON document_updates.local_id = d.local_id\n LEFT JOIN document_pending_attachment_counts document_attachments\n ON document_attachments.local_id = d.local_id\n WHERE d.local_id = ?\n LIMIT 1\n `,\n [localId],\n );\n const [row] = rows;\n if (!row) {\n return null;\n }\n\n return mapContainerContentsDocumentSyncStateRow(row);\n}\n\nasync function listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql: ExecSql,\n documentIds: ReadonlyArray<string>,\n): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const documentIdBatch of listContainerContentsSqlIdBatches(\n uniqueDocumentIds,\n )) {\n const batchLinkedContainerIdsByDocumentId =\n await new DocumentContainerProjectionRepository(\n execSql,\n ).listLinkedContainerIdsByDocumentIds(documentIdBatch);\n for (const [\n documentId,\n linkedContainerIds,\n ] of batchLinkedContainerIdsByDocumentId.entries()) {\n linkedContainerIdsByDocumentId.set(\n documentId,\n Array.from(linkedContainerIds),\n );\n }\n }\n\n return linkedContainerIdsByDocumentId;\n}\n\nexport function createContainerDocumentQueriesFromRuntime(\n runtime: ContainerDocumentQueriesRuntime,\n): ContainerDocumentQueries {\n const execSql = runtime.infra.execSql;\n return {\n ...createFolderRecoveryQueries(execSql),\n async loadContainerDocumentSummary(input) {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n return mapContainerContentsDocumentSummaryRow(\n (await loadLinkedDocumentSummaryRow(execSql, input)) ?? {},\n );\n },\n applyContainerDocumentTombstones(tombstones) {\n return applyPersistedContainerDocumentTombstones(\n execSql,\n tombstones,\n deleteContainerDocumentTombstonePlacementRows,\n );\n },\n hasOrphanedDocuments({ currentOrganizationId }) {\n return hasOrphanedDocuments(execSql, currentOrganizationId);\n },\n listContainerDocumentSidebarWindow(input) {\n return listContainerDocumentSidebarWindow(execSql, input);\n },\n listContainerItemWindow(input) {\n return listContainerItemWindow(execSql, input);\n },\n loadDocumentSyncState(localId) {\n return loadContainerContentsDocumentSyncState(execSql, localId);\n },\n loadDocumentSummary(localId, options) {\n return loadContainerContentsDocumentSummary(\n execSql,\n localId,\n options?.requireHydrated ?? false,\n );\n },\n loadOrphanedDocumentSummary({\n currentOrganizationId,\n localId,\n requireHydrated = false,\n }) {\n return loadContainerContentsOrphanedDocumentSummary(\n execSql,\n localId,\n currentOrganizationId,\n requireHydrated,\n );\n },\n loadContainerDocumentWatermark(containerId) {\n return new ContainerSyncWatermarkRepository(execSql).loadWatermark(\n containerContentsSyncLane(containerId),\n );\n },\n listLinkedContainerIdsByDocumentIds(documentIds) {\n return listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql,\n documentIds,\n );\n },\n listPendingDownloads() {\n return listPendingDownloads(execSql);\n },\n listPendingWrites() {\n return listPendingWrites(execSql);\n },\n retryPendingWriteItem(input) {\n return resetPendingWriteRetryState(execSql, input);\n },\n replaceDocumentLinksBatch(inputs) {\n return new DocumentContainerProjectionRepository(\n execSql,\n ).replaceDocumentLinksBatch(inputs);\n },\n async saveContainerDocumentWatermark(containerId, watermark) {\n await new ContainerSyncWatermarkRepository(execSql).saveWatermark(\n containerContentsSyncLane(containerId),\n watermark,\n );\n },\n upsertDiscoveredDocuments(inputs, assertCurrent) {\n return upsertDiscoveredDocuments(execSql, inputs, assertCurrent);\n },\n };\n}\n"]}
@@ -20,3 +20,4 @@ export type { ContainerDocumentObjectSyncState, ContainerDocumentObjectSyncStatu
20
20
  export { createContainerDocumentObjectSyncState, syncedContainerDocumentObjectSyncState, } from "./syncState.js";
21
21
  export { type ContainerSystemSlotDefinition, deriveContainerSystemSlot, } from "./systemSlot.js";
22
22
  export { purgeLocalContainerDocument, purgeRemoteContainerDocument, } from "./tombstones/documentPurge.js";
23
+ export { createDocumentHeadLinkSetLoader } from "./tombstones/documentTombstoneEvidence.js";
@@ -16,4 +16,5 @@ export { createContainerContentsDocumentsRuntime, createContainerContentsStoreWo
16
16
  export { createContainerDocumentObjectSyncState, syncedContainerDocumentObjectSyncState, } from "./syncState.js";
17
17
  export { deriveContainerSystemSlot, } from "./systemSlot.js";
18
18
  export { purgeLocalContainerDocument, purgeRemoteContainerDocument, } from "./tombstones/documentPurge.js";
19
+ export { createDocumentHeadLinkSetLoader } from "./tombstones/documentTombstoneEvidence.js";
19
20
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,kFAAkF,CAAC;AACzI,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAE/E,OAAO,EAEL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EASL,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,0BAA0B,EAG1B,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,GAEnB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EASL,YAAY,GACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAQL,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAQL,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,uCAAuC,EACvC,wCAAwC,EACxC,uCAAuC,EACvC,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,0CAA0C,EAC1C,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,GAOlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,wDAAwD,EACxD,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAcL,uCAAuC,EACvC,2CAA2C,EAC3C,uDAAuD,EACvD,sCAAsC,EACtC,kDAAkD,GACnD,MAAM,WAAW,CAAC;AAKnB,OAAO,EACL,sCAAsC,EACtC,sCAAsC,GACvC,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,yBAAyB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC","sourcesContent":["export { DocumentContainerProjectionRepository } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport { deriveSystemContainerId } from \"./container-state/create/createChild\";\nexport type { ContainerContentsOrganizationHost } from \"./container-state/organizationHost\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeSnapshot,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n createContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,kFAAkF,CAAC;AACzI,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAE/E,OAAO,EAEL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EASL,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,0BAA0B,EAG1B,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,GAEnB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EASL,YAAY,GACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAQL,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAQL,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,uCAAuC,EACvC,wCAAwC,EACxC,uCAAuC,EACvC,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,0CAA0C,EAC1C,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,GAOlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,wDAAwD,EACxD,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAcL,uCAAuC,EACvC,2CAA2C,EAC3C,uDAAuD,EACvD,sCAAsC,EACtC,kDAAkD,GACnD,MAAM,WAAW,CAAC;AAKnB,OAAO,EACL,sCAAsC,EACtC,sCAAsC,GACvC,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,yBAAyB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC","sourcesContent":["export { DocumentContainerProjectionRepository } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport { deriveSystemContainerId } from \"./container-state/create/createChild\";\nexport type { ContainerContentsOrganizationHost } from \"./container-state/organizationHost\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeSnapshot,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n createContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n\nexport { createDocumentHeadLinkSetLoader } from \"./tombstones/documentTombstoneEvidence\";\n"]}
@@ -0,0 +1,42 @@
1
+ import { assertDocumentWriterProjectionConsistent } from "../../../data/documents/shared/projection/index.js";
2
+ import type { DocumentPurgeCheckpoint } from "../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js";
3
+ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
4
+ import type { PrincipalPolicyOperation } from "../../principals/principalPolicyService.js";
5
+ import type { ContainerDocumentTombstoneVerifier } from "../documentDiscovery/documentDiscoveryTypes.js";
6
+ import type { ContainerContentsStoreWorkflowRuntime, ContainerContentsWorkflowRuntime } from "../runtime.js";
7
+ export interface VerifiedDocumentHeadLinkSet {
8
+ readonly organizationId: string | null;
9
+ readonly accessEpoch: number;
10
+ /** Present for a signed head; a terminal purge has no live access state. */
11
+ readonly accessStateHash?: string;
12
+ readonly linkedContainerIds: ReadonlyArray<string>;
13
+ }
14
+ /**
15
+ * The document's verified head link set, or `null` when no verified head is
16
+ * available: the projection could not be fetched (the requester may no
17
+ * longer read the document, or it was purged) or failed verification.
18
+ */
19
+ export type DocumentHeadLinkSetLoader = (documentId: string, expectedManifestHash?: string, expectedSignerUserId?: string) => Promise<VerifiedDocumentHeadLinkSet | "not-found" | null>;
20
+ /** The highest access epoch local state records for the document. */
21
+ export type LocalDocumentAccessEpochLoader = (documentId: string) => Promise<number>;
22
+ export interface DocumentHeadLinkSetLoaderDeps {
23
+ readonly assertDocumentWriterProjectionConsistent: typeof assertDocumentWriterProjectionConsistent;
24
+ readonly loadDocumentPurgeCheckpoint: (execSql: ExecSql, documentId: string) => Promise<DocumentPurgeCheckpoint | null>;
25
+ }
26
+ export declare const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;
27
+ /**
28
+ * Head loads per settle. Tombstones beyond it stay unverified and are held
29
+ * for a later, backed-off retry, so a bulk move out of a folder does not cost
30
+ * every device an unbounded burst of fetches before the watermark advances.
31
+ */
32
+ export declare const HEAD_LINK_SET_LOADS_PER_RUN = 32;
33
+ /** `policyOperation` lets one discovery pass share a directory discovery. */
34
+ export declare function createDocumentHeadLinkSetLoader(runtime: ContainerContentsWorkflowRuntime & Pick<ContainerContentsStoreWorkflowRuntime, "liveHydrationStatus">, deps?: DocumentHeadLinkSetLoaderDeps, policyOperation?: PrincipalPolicyOperation): DocumentHeadLinkSetLoader;
35
+ /**
36
+ * Judge listing tombstones against each document's verified head link set,
37
+ * fetched once per document with bounded concurrency and a per-run cap. A
38
+ * head whose epoch is below local document state is no evidence: it may be a
39
+ * lagging replica or a replay, and applying it could delete rows a newer
40
+ * listing or settled move wrote.
41
+ */
42
+ export declare function createContainerDocumentTombstoneVerifier(organizationId: string | undefined, loadDocumentHeadLinkSet: DocumentHeadLinkSetLoader, loadLocalDocumentAccessEpoch: LocalDocumentAccessEpochLoader): ContainerDocumentTombstoneVerifier;
@@ -1,6 +1,7 @@
1
1
  import { DOCUMENT_NOT_FOUND_ERROR_CODE, } from "../../../internal/validators/response/index.js";
2
- import { assertDocumentWriterProjectionConsistent } from "../../../data/documents/shared/projection/index.js";
2
+ import { assertDocumentCreateSigner, assertDocumentWriterProjectionConsistent, } from "../../../data/documents/shared/projection/index.js";
3
3
  import { uniqueSortedStrings } from "../../../data/documents/shared/readers.js";
4
+ import { checkWithHeldBundleRecovery } from "../../../data/keyingProjectionVerification/index.js";
4
5
  import { createProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/userKeyResolver.js";
5
6
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
6
7
  import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
@@ -13,12 +14,13 @@ export const HEAD_LINK_SET_LOAD_CONCURRENCY = 4;
13
14
  * every device an unbounded burst of fetches before the watermark advances.
14
15
  */
15
16
  export const HEAD_LINK_SET_LOADS_PER_RUN = 32;
16
- async function verifiedHeadLinkSet(runtime, deps, documentId, projection, policyOperation) {
17
+ async function verifiedHeadLinkSet(runtime, deps, documentId, projection, policyOperation, stillCurrent) {
17
18
  const verified = {};
18
19
  await deps.assertDocumentWriterProjectionConsistent(projection, {
19
20
  // Only the link set is read; a bundle wrapped to superseded KEK targets
20
21
  // still carries the signed head.
21
22
  allowStaleContentKeyBundle: true,
23
+ stillCurrent,
22
24
  execSql: runtime.infra.execSql,
23
25
  onVerifiedAuthorization: (authorization) => {
24
26
  const head = authorization.documentManifestByHash.get(projection.documentManifest.manifestHash);
@@ -69,41 +71,63 @@ function failedHeadVerdict(runtime, documentId, failure) {
69
71
  runtime.util.log(`Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? "offline"})`);
70
72
  return null;
71
73
  }
74
+ async function fetchDocumentHead(runtime, documentId, expectedManifestHash, assertCurrent, requestGuard) {
75
+ // Tombstones require a fresh head. Listings can reuse a matching cached
76
+ // projection, whose signature and local checkpoint are still verified.
77
+ if (!expectedManifestHash)
78
+ runtime.apiClient.evictDocumentWriterProjection(documentId);
79
+ let result = await runtime.apiClient.getDocumentWriterProjectionResult(documentId, { reportErrors: false, stillCurrent: requestGuard });
80
+ assertCurrent();
81
+ if (expectedManifestHash &&
82
+ result.ok &&
83
+ result.data.documentManifest.manifestHash !== expectedManifestHash) {
84
+ runtime.apiClient.evictDocumentWriterProjection(documentId);
85
+ result = await runtime.apiClient.getDocumentWriterProjectionResult(documentId, { reportErrors: false, stillCurrent: requestGuard });
86
+ }
87
+ assertCurrent();
88
+ return result;
89
+ }
72
90
  /** `policyOperation` lets one discovery pass share a directory discovery. */
73
91
  export function createDocumentHeadLinkSetLoader(runtime, deps = {
74
92
  assertDocumentWriterProjectionConsistent,
75
93
  loadDocumentPurgeCheckpoint: (execSql, documentId) => new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(documentId),
76
94
  }, policyOperation) {
77
- return async (documentId, expectedManifestHash) => {
95
+ const stillCurrent = () => runtime.liveHydrationStatus?.() !== "retired";
96
+ function assertCurrent() {
97
+ if (!stillCurrent())
98
+ throw new Error("Document head lookup scope changed.");
99
+ }
100
+ return async (documentId, expectedManifestHash, expectedSignerUserId) => {
78
101
  try {
79
102
  // A verified purge proof is terminal signed evidence that the document
80
103
  // links nothing any more.
81
- if (await deps.loadDocumentPurgeCheckpoint(runtime.infra.execSql, documentId)) {
104
+ assertCurrent();
105
+ const purge = await deps.loadDocumentPurgeCheckpoint(runtime.infra.execSql, documentId);
106
+ assertCurrent();
107
+ if (purge) {
82
108
  return {
83
109
  organizationId: null,
84
110
  accessEpoch: Number.MAX_SAFE_INTEGER,
85
111
  linkedContainerIds: [],
86
112
  };
87
113
  }
88
- // Tombstones require a fresh head. Listings can reuse a matching cached
89
- // projection, whose signature and local checkpoint are still verified.
90
- if (!expectedManifestHash)
91
- runtime.apiClient.evictDocumentWriterProjection(documentId);
92
- let result = await runtime.apiClient.getDocumentWriterProjectionResult(documentId, { reportErrors: false });
93
- if (expectedManifestHash &&
94
- result.ok &&
95
- result.data.documentManifest.manifestHash !== expectedManifestHash) {
96
- runtime.apiClient.evictDocumentWriterProjection(documentId);
97
- result = await runtime.apiClient.getDocumentWriterProjectionResult(documentId, { reportErrors: false });
98
- }
114
+ const result = await fetchDocumentHead(runtime, documentId, expectedManifestHash, assertCurrent, expectedSignerUserId ? stillCurrent : undefined);
99
115
  if (!result.ok)
100
116
  return failedHeadVerdict(runtime, documentId, result);
101
- return await verifiedHeadLinkSet(runtime, deps, documentId, result.data, policyOperation);
117
+ const projection = result.data;
118
+ if (expectedSignerUserId) {
119
+ await checkWithHeldBundleRecovery({ execSql: runtime.infra.execSql, projection, stillCurrent }, async () => assertDocumentCreateSigner({ documentId, expectedSignerUserId }, projection));
120
+ }
121
+ assertCurrent();
122
+ const head = await verifiedHeadLinkSet(runtime, deps, documentId, result.data, policyOperation, stillCurrent);
123
+ assertCurrent();
124
+ return head;
102
125
  }
103
126
  catch (error) {
104
127
  // Any failure leaves the tombstone unverified (held and retried); a
105
128
  // thrown error here must not fail the whole discovery pass.
106
- await reportUnavailableHead(runtime, documentId, error);
129
+ if (stillCurrent())
130
+ await reportUnavailableHead(runtime, documentId, error);
107
131
  return null;
108
132
  }
109
133
  };
@@ -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,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAE7G,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,yCAAyC,EAAE,MAAM,wCAAwC,CAAC;AAQnG,OAAO,EAAE,+BAA+B,EAAE,MAAM,wCAAwC,CAAC;AAkCzF,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,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CAAC,UAAU,CAAC,CAAC;gBAC9C,IAAI,IAAI,KAAK,IAAI;oBAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACpE,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 { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\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: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\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: runtime.principalPolicies.createWarmer({\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/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\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: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\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) return failedHeadVerdict(runtime, documentId, result);\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 // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\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 return head.accessEpoch < localEpoch ? null : head;\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 evidentialHead(documentId);\n if (head !== null) 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","sour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U,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;QACrD,CAAC,CAAC;QACF,IAAI,IAAI,GAAG,CAAC,CAAC;QACb,MAAM,MAAM,GAAG,KAAK,IAAI,EAAE;YACxB,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,2BAA2B,CAAC,EAAE,CAAC;gBACnE,MAAM,KAAK,GAAG,IAAI,EAAE,CAAC;gBACrB,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;gBAC5B,IAAI,CAAC,KAAK;oBAAE,MAAM;gBAClB,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,GAAG,KAAK,CAAC;gBAClC,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;gBAC9C,IAAI,IAAI,KAAK,IAAI;oBAAE,QAAQ,CAAC,KAAK,CAAC,GAAG,eAAe,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YACpE,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 {\n assertDocumentCreateSigner,\n assertDocumentWriterProjectionConsistent,\n} from \"../../../data/documents/shared/projection\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { checkWithHeldBundleRecovery } from \"../../../data/keyingProjectionVerification\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { DocumentPurgeCheckpoint } from \"../../../data/persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { reportKeyingVerificationErrorInCauseChain } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type {\n ContainerDocumentTombstone,\n ContainerDocumentTombstoneVerdict,\n ContainerDocumentTombstoneVerifier,\n} from \"../documentDiscovery/documentDiscoveryTypes\";\nimport { documentHeadMatchesOrganization } from \"../documentDiscovery/documentHeadScope\";\nimport type {\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n} 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 expectedSignerUserId?: 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: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<DocumentPurgeCheckpoint | null>;\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 stillCurrent: () => boolean,\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 stillCurrent,\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: runtime.principalPolicies.createWarmer({\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/** Only a typed 404 proves absence; any other failure leaves the head unavailable. */\nfunction failedHeadVerdict(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n failure: {\n readonly code?: string | undefined;\n readonly status?: number | null | undefined;\n },\n): \"not-found\" | null {\n if (failure.status === 404 && failure.code === DOCUMENT_NOT_FOUND_ERROR_CODE)\n return \"not-found\";\n runtime.util.log(\n `Container contents: tombstone evidence for document ${documentId} is unavailable (${failure.status ?? \"offline\"})`,\n );\n return null;\n}\n\nasync function fetchDocumentHead(\n runtime: ContainerContentsWorkflowRuntime,\n documentId: string,\n expectedManifestHash: string | undefined,\n assertCurrent: () => void,\n requestGuard: (() => boolean) | undefined,\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, stillCurrent: requestGuard },\n );\n assertCurrent();\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, stillCurrent: requestGuard },\n );\n }\n assertCurrent();\n return result;\n}\n\n/** `policyOperation` lets one discovery pass share a directory discovery. */\nexport function createDocumentHeadLinkSetLoader(\n runtime: ContainerContentsWorkflowRuntime &\n Pick<ContainerContentsStoreWorkflowRuntime, \"liveHydrationStatus\">,\n deps: DocumentHeadLinkSetLoaderDeps = {\n assertDocumentWriterProjectionConsistent,\n loadDocumentPurgeCheckpoint: (execSql, documentId) =>\n new KeyingCheckpointRepository(execSql).loadDocumentPurgeCheckpoint(\n documentId,\n ),\n },\n policyOperation?: PrincipalPolicyOperation,\n): DocumentHeadLinkSetLoader {\n const stillCurrent = () => runtime.liveHydrationStatus?.() !== \"retired\";\n function assertCurrent() {\n if (!stillCurrent()) throw new Error(\"Document head lookup scope changed.\");\n }\n return async (documentId, expectedManifestHash, expectedSignerUserId) => {\n try {\n // A verified purge proof is terminal signed evidence that the document\n // links nothing any more.\n assertCurrent();\n const purge = await deps.loadDocumentPurgeCheckpoint(\n runtime.infra.execSql,\n documentId,\n );\n assertCurrent();\n if (purge) {\n return {\n organizationId: null,\n accessEpoch: Number.MAX_SAFE_INTEGER,\n linkedContainerIds: [],\n };\n }\n const result = await fetchDocumentHead(\n runtime,\n documentId,\n expectedManifestHash,\n assertCurrent,\n expectedSignerUserId ? stillCurrent : undefined,\n );\n if (!result.ok) return failedHeadVerdict(runtime, documentId, result);\n const projection = result.data;\n if (expectedSignerUserId) {\n await checkWithHeldBundleRecovery(\n { execSql: runtime.infra.execSql, projection, stillCurrent },\n async () =>\n assertDocumentCreateSigner(\n { documentId, expectedSignerUserId },\n projection,\n ),\n );\n }\n assertCurrent();\n const head = await verifiedHeadLinkSet(\n runtime,\n deps,\n documentId,\n result.data,\n policyOperation,\n stillCurrent,\n );\n assertCurrent();\n return head;\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 if (stillCurrent())\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 // A missing, foreign, or older-than-local head is no evidence.\n const evidentialHead = async (documentId: string) => {\n const head = await loadDocumentHeadLinkSet(documentId);\n if (head === null || head === \"not-found\") return null;\n if (!documentHeadMatchesOrganization(head, organizationId)) return null;\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 return head.accessEpoch < localEpoch ? null : head;\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 evidentialHead(documentId);\n if (head !== null) 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"]}