@tearleads/client-sdk 0.1.251 → 0.1.253

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 (226) hide show
  1. package/Tearleads.d.ts +0 -2
  2. package/Tearleads.js +17 -28
  3. package/Tearleads.js.map +1 -1
  4. package/client/containerContents/index.d.ts +2 -0
  5. package/client/containerContents/index.js +4 -9
  6. package/client/containerContents/index.js.map +1 -1
  7. package/client/containerContents/storeRuntime.d.ts +17 -0
  8. package/client/containerContents/storeRuntime.js +31 -0
  9. package/client/containerContents/storeRuntime.js.map +1 -0
  10. package/client/deviceFirst/index.d.ts +2 -3
  11. package/client/deviceFirst/index.js +44 -22
  12. package/client/deviceFirst/index.js.map +1 -1
  13. package/client/organizations/organizationReadModelPresentation.js +7 -4
  14. package/client/organizations/organizationReadModelPresentation.js.map +1 -1
  15. package/client/organizations/organizationReadModels.js +6 -5
  16. package/client/organizations/organizationReadModels.js.map +1 -1
  17. package/client/organizations/organizationWorkflowRuntime.js +1 -1
  18. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  19. package/client/runtime/principalMutationApi.d.ts +4 -0
  20. package/client/runtime/principalMutationApi.js +9 -5
  21. package/client/runtime/principalMutationApi.js.map +1 -1
  22. package/client/runtime/runtimeIdentityResolution.js +23 -0
  23. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  24. package/client/runtime/runtimeSubscription.js +68 -0
  25. package/client/runtime/runtimeSubscription.js.map +1 -0
  26. package/client/runtime/workflowRuntime.d.ts +3 -1
  27. package/client/runtime/workflowRuntime.js +31 -81
  28. package/client/runtime/workflowRuntime.js.map +1 -1
  29. package/client/session/authenticationMachine.js +47 -0
  30. package/client/session/authenticationMachine.js.map +1 -0
  31. package/client/session/index.js +75 -93
  32. package/client/session/index.js.map +1 -1
  33. package/client/session/sessionBlobStore.js +39 -0
  34. package/client/session/sessionBlobStore.js.map +1 -0
  35. package/client/session/sessionContext.js +11 -0
  36. package/client/session/sessionContext.js.map +1 -1
  37. package/client/session/sessionIdentityTrust.d.ts +2 -1
  38. package/client/session/sessionIdentityTrust.js +8 -4
  39. package/client/session/sessionIdentityTrust.js.map +1 -1
  40. package/client/session/sessionLifetime.js +87 -0
  41. package/client/session/sessionLifetime.js.map +1 -0
  42. package/client/session/sessionLogin.js +114 -0
  43. package/client/session/sessionLogin.js.map +1 -0
  44. package/client/session/sessionOrganizationCreation.js +3 -2
  45. package/client/session/sessionOrganizationCreation.js.map +1 -1
  46. package/client/session/sessionPurgeRecovery.js +11 -3
  47. package/client/session/sessionPurgeRecovery.js.map +1 -1
  48. package/client/session/sessionTypes.d.ts +6 -2
  49. package/client/session/sessionTypes.js.map +1 -1
  50. package/data/blobs/blobContracts.d.ts +4 -3
  51. package/data/blobs/blobContracts.js.map +1 -1
  52. package/data/blobs/createBlobStore.js +1 -8
  53. package/data/blobs/createBlobStore.js.map +1 -1
  54. package/data/blobs/encryptedBlobStore.js +17 -12
  55. package/data/blobs/encryptedBlobStore.js.map +1 -1
  56. package/data/blobs/memoryBlobStore.js +8 -5
  57. package/data/blobs/memoryBlobStore.js.map +1 -1
  58. package/data/blobs/opfsBlobFile.js +36 -0
  59. package/data/blobs/opfsBlobFile.js.map +1 -0
  60. package/data/blobs/opfsBlobStore.d.ts +1 -1
  61. package/data/blobs/opfsBlobStore.js +91 -21
  62. package/data/blobs/opfsBlobStore.js.map +1 -1
  63. package/data/principals/principalPolicyCoordinator.js +8 -17
  64. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  65. package/data/shared/domainScope.d.ts +2 -0
  66. package/data/shared/domainScope.js +2 -1
  67. package/data/shared/domainScope.js.map +1 -1
  68. package/data/shared/keyedQueue.js +15 -0
  69. package/data/shared/keyedQueue.js.map +1 -0
  70. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  71. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  72. package/data/sqlite/sqlExec.d.ts +6 -0
  73. package/data/sqlite/sqlExec.js +64 -13
  74. package/data/sqlite/sqlExec.js.map +1 -1
  75. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  76. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  77. package/data/sync/syncCoordinator.js +17 -10
  78. package/data/sync/syncCoordinator.js.map +1 -1
  79. package/data/trustedUserIdentity/service.js +2 -1
  80. package/data/trustedUserIdentity/service.js.map +1 -1
  81. package/data/trustedUserIdentity/types.d.ts +1 -1
  82. package/data/trustedUserIdentity/types.js.map +1 -1
  83. package/internal/api-client/ApiClient.d.ts +4 -1
  84. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  85. package/internal/api-client/apiRequestRuntime.js +86 -101
  86. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  87. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  88. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  89. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  90. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  91. package/internal/api-client/client/blobs.d.ts +1 -0
  92. package/internal/api-client/client/blobs.js +12 -3
  93. package/internal/api-client/client/blobs.js.map +1 -1
  94. package/internal/api-client/client/laneListingRequest.js +4 -0
  95. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  96. package/internal/api-client/client/session.d.ts +5 -1
  97. package/internal/api-client/client/session.js +12 -4
  98. package/internal/api-client/client/session.js.map +1 -1
  99. package/internal/api-client/client/writerProjections.js +12 -13
  100. package/internal/api-client/client/writerProjections.js.map +1 -1
  101. package/internal/api-client/operationResponse.d.ts +1 -1
  102. package/internal/api-client/operationResponse.js +10 -23
  103. package/internal/api-client/operationResponse.js.map +1 -1
  104. package/internal/api-client/operationTransport.js +2 -1
  105. package/internal/api-client/operationTransport.js.map +1 -1
  106. package/internal/api-client/principalHistoryRequest.js +25 -20
  107. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  108. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  109. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  110. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  111. package/internal/api-client/principalPolicyPages.js +4 -2
  112. package/internal/api-client/principalPolicyPages.js.map +1 -1
  113. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  114. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  115. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  116. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  117. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  118. package/internal/api-client/routes/blobs/get.js +9 -67
  119. package/internal/api-client/routes/blobs/get.js.map +1 -1
  120. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  121. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  122. package/internal/api-client/sessionRefresh.js +1 -1
  123. package/internal/api-client/sessionRefresh.js.map +1 -1
  124. package/internal/api-client/sessionRenewal.d.ts +31 -0
  125. package/internal/api-client/sessionRenewal.js +91 -6
  126. package/internal/api-client/sessionRenewal.js.map +1 -1
  127. package/internal/api-client/sessionRequestInit.js +22 -0
  128. package/internal/api-client/sessionRequestInit.js.map +1 -0
  129. package/internal/api-client/sessionResponse.js +39 -0
  130. package/internal/api-client/sessionResponse.js.map +1 -0
  131. package/internal/api-client/types.d.ts +1 -0
  132. package/internal/api-client/types.js.map +1 -1
  133. package/internal/api-client/webSocketTickets.d.ts +1 -0
  134. package/internal/api-client/webSocketTickets.js +4 -0
  135. package/internal/api-client/webSocketTickets.js.map +1 -1
  136. package/internal/sqlite-worker/client.d.ts +1 -1
  137. package/internal/sqlite-worker/client.js +6 -1
  138. package/internal/sqlite-worker/client.js.map +1 -1
  139. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  140. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  141. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  142. package/internal/sqlite-worker/types.d.ts +4 -0
  143. package/internal/sqlite-worker/types.js.map +1 -1
  144. package/package.json +1 -1
  145. package/sqlite/worker.js +1 -1
  146. package/stores/container-contents/containerContentsStore.d.ts +3 -9
  147. package/stores/container-contents/containerContentsStore.js +24 -21
  148. package/stores/container-contents/containerContentsStore.js.map +1 -1
  149. package/stores/container-contents/containerState/storeScope.js +6 -0
  150. package/stores/container-contents/containerState/storeScope.js.map +1 -0
  151. package/stores/container-contents/hydration/backgroundHydration.js +2 -1
  152. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  153. package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
  154. package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
  155. package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
  156. package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
  157. package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
  158. package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
  159. package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
  160. package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
  161. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  162. package/stores/container-contents/hydration/startupHydration.js +2 -9
  163. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  164. package/stores/container-contents/hydration/treeResetMachine.js +61 -0
  165. package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
  166. package/stores/container-contents/localRefresh.js +28 -12
  167. package/stores/container-contents/localRefresh.js.map +1 -1
  168. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
  169. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
  170. package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
  171. package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
  172. package/stores/container-contents/state.d.ts +3 -7
  173. package/stores/container-contents/state.js +27 -16
  174. package/stores/container-contents/state.js.map +1 -1
  175. package/stores/container-contents/syncAgent/index.d.ts +7 -2
  176. package/stores/container-contents/syncAgent/index.js +77 -49
  177. package/stores/container-contents/syncAgent/index.js.map +1 -1
  178. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
  179. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  180. package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
  181. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  182. package/stores/local-projection/localProjectionStore.js +24 -15
  183. package/stores/local-projection/localProjectionStore.js.map +1 -1
  184. package/stores/local-projection/registry.js +2 -2
  185. package/stores/local-projection/registry.js.map +1 -1
  186. package/workflows/container-contents/container-state/create/createChild.js +3 -15
  187. package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
  188. package/workflows/container-contents/containerPersistence.d.ts +4 -8
  189. package/workflows/container-contents/containerPersistence.js +22 -12
  190. package/workflows/container-contents/containerPersistence.js.map +1 -1
  191. package/workflows/container-contents/localState.js +3 -0
  192. package/workflows/container-contents/localState.js.map +1 -1
  193. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
  194. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
  195. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
  196. package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
  197. package/workflows/container-contents/remoteHydration/index.js +17 -66
  198. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  199. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
  200. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
  201. package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
  202. package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
  203. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
  204. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  205. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
  206. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  207. package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
  208. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  209. package/workflows/container-contents/runtime.d.ts +3 -0
  210. package/workflows/container-contents/runtime.js.map +1 -1
  211. package/workflows/container-contents/storedContainerState.js +17 -7
  212. package/workflows/container-contents/storedContainerState.js.map +1 -1
  213. package/workflows/container-contents/syncLane.d.ts +1 -0
  214. package/workflows/container-contents/syncLane.js +9 -1
  215. package/workflows/container-contents/syncLane.js.map +1 -1
  216. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  217. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  218. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  219. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  220. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  221. package/workflows/registration/registerIdentity.js +2 -0
  222. package/workflows/registration/registerIdentity.js.map +1 -1
  223. package/workflows/shared/runtimeInput.d.ts +2 -0
  224. package/workflows/shared/runtimeInput.js.map +1 -1
  225. package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
  226. package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { bytesToBase64 } from "../../../../internal/encoding/index.js";
2
2
  import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
3
3
  import { deriveStableUuidV4Shaped } from "../../../../data/keying/stableUuid.js";
4
- import { defaultContainerContentsPersistence } from "../../containerPersistence.js";
4
+ import { resolveAtomicContainerSave } from "../../containerPersistence.js";
5
5
  import { createInitializedContainerMetadataDocument } from "../../metadata/containerMetadataDocument.js";
6
6
  import { loadContainerWriterProjectionForState } from "../projectionCache.js";
7
7
  import { createRemoteContainer } from "../remote.js";
@@ -122,18 +122,6 @@ function createInitialChildContainerDocumentRecord(input) {
122
122
  snapshotEndVersion: "",
123
123
  };
124
124
  }
125
- function resolveAtomicChildContainerSave(persistence) {
126
- const saveContainerWithPendingUpdate = persistence.saveContainerWithPendingUpdate;
127
- if (!saveContainerWithPendingUpdate)
128
- return null;
129
- const inheritedSqlAtomicSave = saveContainerWithPendingUpdate ===
130
- defaultContainerContentsPersistence.saveContainerWithPendingUpdate &&
131
- (persistence.saveContainer !==
132
- defaultContainerContentsPersistence.saveContainer ||
133
- persistence.enqueuePendingUpdate !==
134
- defaultContainerContentsPersistence.enqueuePendingUpdate);
135
- return inheritedSqlAtomicSave ? null : saveContainerWithPendingUpdate;
136
- }
137
125
  function childContainerSaveOptions(input) {
138
126
  const { createIntent, localUpdatedAt, stillCurrent } = input;
139
127
  return createIntent || localUpdatedAt || stillCurrent
@@ -164,7 +152,7 @@ async function persistCreatedChildContainer(input) {
164
152
  ? createPendingUpdateFields(input.initialUpdate)
165
153
  : null;
166
154
  if (pendingUpdate) {
167
- const saveContainerWithPendingUpdate = resolveAtomicChildContainerSave(persistence);
155
+ const saveContainerWithPendingUpdate = resolveAtomicContainerSave(persistence);
168
156
  if (!saveContainerWithPendingUpdate)
169
157
  return null;
170
158
  containerState.container = await saveContainerWithPendingUpdate(runtime.infra.execSql, containerState.container, containerState.record, { ...saveOptions, pendingUpdate });
@@ -196,7 +184,7 @@ export async function createChildContainerState(input) {
196
184
  // Refuse before any remote create when an adapter cannot provide
197
185
  // that atomic operation; a SQLite transaction cannot roll back adapter-owned
198
186
  // side effects.
199
- if (queueRemoteSync && !resolveAtomicChildContainerSave(persistence)) {
187
+ if (queueRemoteSync && !resolveAtomicContainerSave(persistence)) {
200
188
  return null;
201
189
  }
202
190
  const remoteChild = createRemote
@@ -1 +1 @@
1
- {"version":3,"file":"createChild.js","sourceRoot":"","sources":["createChild.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EA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AAI,CAAC;IACT,MAAM,cAAc,GAClB,WAAW,EAAE,cAAc;QAC3B,8CAA8C,CAAC;YAC7C,OAAO;YACP,IAAI;YACJ,UAAU;YACV,GAAG;YACH,aAAa;YACb,WAAW;YACX,WAAW;SACZ,CAAC,CAAC;IACL,MAAM,iBAAiB,GAAG,MAAM,4BAA4B,CAAC;QAC3D,cAAc;QACd,aAAa;QACb,qEAAqE;QACrE,sCAAsC;QACtC,cAAc,EAAE,WAAW,EAAE,eAAe,IAAI,IAAI;QACpD,WAAW;QACX,eAAe,EAAE,eAAe,IAAI,CAAC,WAAW,EAAE,eAAe;QACjE,OAAO;QACP,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,IAAI,iBAAiB,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAE5C,OAAO;QACL,cAAc;QACd,aAAa;QACb,iBAAiB;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { deriveStableUuidV4Shaped } from \"../../../../data/keying/stableUuid\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord as DocumentRecord,\n} from \"../../containerPersistence\";\nimport { defaultContainerContentsPersistence } from \"../../containerPersistence\";\nimport { createInitializedContainerMetadataDocument } from \"../../metadata/containerMetadataDocument\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { createRemoteContainer } from \"../remote\";\nimport type {\n ContainerMetadataDocumentState,\n ContainerWorkflowRuntime,\n CreatedChildContainerState,\n} from \"../types\";\nimport { withRegisteredMetadataSeed } from \"./createIntentSeed\";\nimport { CONTAINER_ALREADY_COMMITTED } from \"./createWithMetadata\";\n\nconst SYSTEM_CONTAINER_ID_NAMESPACE_BYTES = new Uint8Array([\n 0xc5, 0x5e, 0x8f, 0x2e, 0x3d, 0x82, 0x4b, 0x4d, 0x8d, 0xbd, 0x0d, 0xd2, 0xd3,\n 0x60, 0xb3, 0x6d,\n]);\n\n/**\n * Derives a stable, UUID-shaped container id for a built-in system slot.\n *\n * The namespace digest makes each slot idempotent across stale store snapshots.\n * The UUID version and variant bits are normalized to a v4 shape because remote\n * container APIs currently validate container ids with the same v4 UUID contract\n * they use for random user-created containers.\n */\nexport function deriveSystemContainerId(input: {\n parentContainerId: string;\n systemSlot: ContainerSystemSlot;\n}): Promise<string> {\n return deriveStableUuidV4Shaped(\n SYSTEM_CONTAINER_ID_NAMESPACE_BYTES,\n `${input.parentContainerId}\\u0000${input.systemSlot}`,\n );\n}\n\nasync function createChildContainerId(\n parentContainerId: string,\n systemSlot: ContainerSystemSlot | null | undefined,\n): Promise<string> {\n return systemSlot\n ? deriveSystemContainerId({ parentContainerId, systemSlot })\n : crypto.randomUUID();\n}\n\nasync function buildRemoteContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n /** Present when the first metadata update should commit with the create. */\n initialUpdate: Uint8Array | null;\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n parentState: ContainerState;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n trimmedName: string;\n}): Promise<{\n readonly containerState: ContainerState;\n /** The acknowledged create time, when the create committed the seed. */\n readonly seedCommittedAt: string | null;\n} | null> {\n const {\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n trimmedName,\n } = input;\n const parentProjection = await loadContainerWriterProjectionForState({\n containerState: parentState,\n runtime,\n });\n if (!parentProjection) {\n return null;\n }\n\n // The create carries the whole first metadata update, as a replayed create\n // intent does, so no metadata sync follows an accepted seed.\n const seedFields = input.initialUpdate\n ? createPendingUpdateFields(input.initialUpdate)\n : null;\n const metadataSeedUpdate = seedFields\n ? { ...seedFields, id: crypto.randomUUID() }\n : null;\n const created = await withRegisteredMetadataSeed(\n input.locallyAcceptedMetadataUpdateIds,\n metadataSeedUpdate,\n () =>\n createRemoteContainer({\n systemSlot,\n containerId: childId,\n ...(metadataSeedUpdate ? { metadataSeedUpdate } : {}),\n parentContainerId: parentState.container.id,\n parentProjection,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n }),\n );\n\n if (!created || created === CONTAINER_ALREADY_COMMITTED) {\n // A benign manifest-exists conflict means the container is already committed\n // remotely (a lost create response). This eager path cannot rebuild its\n // committed metadata state, so leave the create intent to reconcile it via\n // hydration rather than fabricating a local record from a missing response.\n return null;\n }\n\n return {\n containerState: {\n container: {\n id: created.containerId,\n // The creator owns a newly-created container until the server reconciles.\n effectiveAccessLevel: \"admin\",\n organizationId: created.organizationId,\n parentId: created.parentId,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n name: trimmedName,\n icon,\n createdAt: created.createdAt,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n updatedAt: created.updatedAt,\n },\n doc,\n record: {\n ...initialRecord,\n accessEpoch: 1,\n accessStateHash: created.accessManifestHash,\n // A committed seed stands in for the first metadata sync.\n lastCommitLsn: created.metadataSeed?.commitLsn ?? null,\n ...created.persistedMetadataState,\n },\n },\n seedCommittedAt: created.metadataSeed ? created.updatedAt : null,\n };\n}\n\nfunction buildLocalContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n parentState: ContainerState;\n trimmedName: string;\n}): ContainerState {\n const {\n systemSlot,\n childId,\n doc,\n icon,\n initialRecord,\n parentState,\n trimmedName,\n } = input;\n\n return {\n container: {\n id: childId,\n effectiveAccessLevel: \"admin\",\n organizationId: parentState.container.organizationId,\n parentId: parentState.container.id,\n metadataDocumentId: null,\n systemSlot: systemSlot ?? null,\n name: trimmedName,\n icon,\n },\n doc,\n record: initialRecord,\n };\n}\n\nfunction createInitialChildContainerDocumentRecord(input: {\n childId: string;\n initialUpdate: Uint8Array;\n}): DocumentRecord {\n return {\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n id: input.childId,\n lastCommitLsn: null,\n metadataUpdates: bytesToBase64(input.initialUpdate),\n snapshotEndVersion: \"\",\n };\n}\n\nfunction resolveAtomicChildContainerSave(\n persistence: ContainerContentsPersistence,\n): NonNullable<\n ContainerContentsPersistence[\"saveContainerWithPendingUpdate\"]\n> | null {\n const saveContainerWithPendingUpdate =\n persistence.saveContainerWithPendingUpdate;\n if (!saveContainerWithPendingUpdate) return null;\n const inheritedSqlAtomicSave =\n saveContainerWithPendingUpdate ===\n defaultContainerContentsPersistence.saveContainerWithPendingUpdate &&\n (persistence.saveContainer !==\n defaultContainerContentsPersistence.saveContainer ||\n persistence.enqueuePendingUpdate !==\n defaultContainerContentsPersistence.enqueuePendingUpdate);\n return inheritedSqlAtomicSave ? null : saveContainerWithPendingUpdate;\n}\n\nfunction childContainerSaveOptions(input: {\n createIntent: { parentContainerId: string } | undefined;\n localUpdatedAt: string | null;\n stillCurrent?: (() => boolean) | undefined;\n}) {\n const { createIntent, localUpdatedAt, stillCurrent } = input;\n return createIntent || localUpdatedAt || stillCurrent\n ? {\n ...(createIntent ? { createIntent } : {}),\n ...(localUpdatedAt ? { localUpdatedAt } : {}),\n stillCurrent,\n }\n : undefined;\n}\n\nasync function persistCreatedChildContainer(input: {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n /** Set once the create committed the initial update as its seed. */\n localUpdatedAt: string | null;\n persistence: ContainerContentsPersistence;\n queueRemoteSync: boolean;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean | null> {\n const { containerState, localUpdatedAt, persistence, queueRemoteSync } =\n input;\n const { runtime } = input;\n const createIntent =\n queueRemoteSync &&\n !containerState.record.documentId &&\n containerState.container.parentId\n ? { parentContainerId: containerState.container.parentId }\n : undefined;\n const shouldRequestSync =\n queueRemoteSync &&\n (!containerState.record.documentId ||\n Boolean(containerState.record.contentKeyBundle));\n const saveOptions = childContainerSaveOptions({\n createIntent,\n localUpdatedAt,\n stillCurrent: input.stillCurrent,\n });\n const pendingUpdate = shouldRequestSync\n ? createPendingUpdateFields(input.initialUpdate)\n : null;\n if (pendingUpdate) {\n const saveContainerWithPendingUpdate =\n resolveAtomicChildContainerSave(persistence);\n if (!saveContainerWithPendingUpdate) return null;\n containerState.container = await saveContainerWithPendingUpdate(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n { ...saveOptions, pendingUpdate },\n );\n } else {\n containerState.container = await persistence.saveContainer(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n saveOptions,\n );\n }\n return input.stillCurrent?.() === false ? null : shouldRequestSync;\n}\n\nexport async function createChildContainerState(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n createRemote: boolean;\n icon?: string | null | undefined;\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n name: string;\n parentState: ContainerState;\n persistence: ContainerContentsPersistence;\n queueRemoteSync?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedChildContainerState | null> {\n const {\n createRemote,\n systemSlot,\n name,\n parentState,\n persistence,\n queueRemoteSync = true,\n resolveProjectionUserKey,\n runtime,\n } = input;\n const trimmedName = name.trim();\n if (!trimmedName) {\n return null;\n }\n\n const icon = input.icon?.trim() || null;\n const childId = await createChildContainerId(\n parentState.container.id,\n systemSlot,\n );\n const { doc, initialUpdate } =\n await createInitializedContainerMetadataDocument(childId, {\n icon,\n name: trimmedName,\n });\n const initialRecord = createInitialChildContainerDocumentRecord({\n childId,\n initialUpdate,\n });\n if (input.stillCurrent?.() === false) return null;\n // An initial metadata update and its container identity are one durable unit.\n // Refuse before any remote create when an adapter cannot provide\n // that atomic operation; a SQLite transaction cannot roll back adapter-owned\n // side effects.\n if (queueRemoteSync && !resolveAtomicChildContainerSave(persistence)) {\n return null;\n }\n\n const remoteChild = createRemote\n ? await buildRemoteContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n initialUpdate: queueRemoteSync ? initialUpdate : null,\n locallyAcceptedMetadataUpdateIds:\n input.locallyAcceptedMetadataUpdateIds,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent: input.stillCurrent,\n trimmedName,\n })\n : null;\n const containerState =\n remoteChild?.containerState ??\n buildLocalContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n trimmedName,\n });\n const shouldRequestSync = await persistCreatedChildContainer({\n containerState,\n initialUpdate,\n // A committed seed leaves nothing to queue or sync: nothing local is\n // newer than the acknowledged create.\n localUpdatedAt: remoteChild?.seedCommittedAt ?? null,\n persistence,\n queueRemoteSync: queueRemoteSync && !remoteChild?.seedCommittedAt,\n runtime,\n stillCurrent: input.stillCurrent,\n });\n if (shouldRequestSync === null) return null;\n\n return {\n containerState,\n initialUpdate,\n shouldRequestSync,\n };\n}\n"]}
1
+ {"version":3,"file":"createChild.js","sourceRoot":"","sources":["createChild.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAM9E,OAAO,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAO,EAAE,0CAA0C,EAAE,MAAM,0CAA0C,CAAC;AAEtG,OAAO,EAA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CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport { createPendingUpdateFields } from \"../../../../data/documents/documentSync\";\nimport { deriveStableUuidV4Shaped } from \"../../../../data/keying/stableUuid\";\nimport type { ProjectionUserKeyResolver } from \"../../../../data/keyingProjectionVerification\";\nimport type {\n ContainerContentsPersistence,\n ContainerDocumentRecord as DocumentRecord,\n} from \"../../containerPersistence\";\nimport { resolveAtomicContainerSave } from \"../../containerPersistence\";\nimport { createInitializedContainerMetadataDocument } from \"../../metadata/containerMetadataDocument\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { createRemoteContainer } from \"../remote\";\nimport type {\n ContainerMetadataDocumentState,\n ContainerWorkflowRuntime,\n CreatedChildContainerState,\n} from \"../types\";\nimport { withRegisteredMetadataSeed } from \"./createIntentSeed\";\nimport { CONTAINER_ALREADY_COMMITTED } from \"./createWithMetadata\";\n\nconst SYSTEM_CONTAINER_ID_NAMESPACE_BYTES = new Uint8Array([\n 0xc5, 0x5e, 0x8f, 0x2e, 0x3d, 0x82, 0x4b, 0x4d, 0x8d, 0xbd, 0x0d, 0xd2, 0xd3,\n 0x60, 0xb3, 0x6d,\n]);\n\n/**\n * Derives a stable, UUID-shaped container id for a built-in system slot.\n *\n * The namespace digest makes each slot idempotent across stale store snapshots.\n * The UUID version and variant bits are normalized to a v4 shape because remote\n * container APIs currently validate container ids with the same v4 UUID contract\n * they use for random user-created containers.\n */\nexport function deriveSystemContainerId(input: {\n parentContainerId: string;\n systemSlot: ContainerSystemSlot;\n}): Promise<string> {\n return deriveStableUuidV4Shaped(\n SYSTEM_CONTAINER_ID_NAMESPACE_BYTES,\n `${input.parentContainerId}\\u0000${input.systemSlot}`,\n );\n}\n\nasync function createChildContainerId(\n parentContainerId: string,\n systemSlot: ContainerSystemSlot | null | undefined,\n): Promise<string> {\n return systemSlot\n ? deriveSystemContainerId({ parentContainerId, systemSlot })\n : crypto.randomUUID();\n}\n\nasync function buildRemoteContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n /** Present when the first metadata update should commit with the create. */\n initialUpdate: Uint8Array | null;\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n parentState: ContainerState;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n trimmedName: string;\n}): Promise<{\n readonly containerState: ContainerState;\n /** The acknowledged create time, when the create committed the seed. */\n readonly seedCommittedAt: string | null;\n} | null> {\n const {\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n trimmedName,\n } = input;\n const parentProjection = await loadContainerWriterProjectionForState({\n containerState: parentState,\n runtime,\n });\n if (!parentProjection) {\n return null;\n }\n\n // The create carries the whole first metadata update, as a replayed create\n // intent does, so no metadata sync follows an accepted seed.\n const seedFields = input.initialUpdate\n ? createPendingUpdateFields(input.initialUpdate)\n : null;\n const metadataSeedUpdate = seedFields\n ? { ...seedFields, id: crypto.randomUUID() }\n : null;\n const created = await withRegisteredMetadataSeed(\n input.locallyAcceptedMetadataUpdateIds,\n metadataSeedUpdate,\n () =>\n createRemoteContainer({\n systemSlot,\n containerId: childId,\n ...(metadataSeedUpdate ? { metadataSeedUpdate } : {}),\n parentContainerId: parentState.container.id,\n parentProjection,\n resolveProjectionUserKey,\n runtime,\n stillCurrent,\n }),\n );\n\n if (!created || created === CONTAINER_ALREADY_COMMITTED) {\n // A benign manifest-exists conflict means the container is already committed\n // remotely (a lost create response). This eager path cannot rebuild its\n // committed metadata state, so leave the create intent to reconcile it via\n // hydration rather than fabricating a local record from a missing response.\n return null;\n }\n\n return {\n containerState: {\n container: {\n id: created.containerId,\n // The creator owns a newly-created container until the server reconciles.\n effectiveAccessLevel: \"admin\",\n organizationId: created.organizationId,\n parentId: created.parentId,\n metadataDocumentId: created.metadataDocumentId,\n systemSlot: created.systemSlot,\n name: trimmedName,\n icon,\n createdAt: created.createdAt,\n serverCreatedAt: created.createdAt,\n serverUpdatedAt: created.updatedAt,\n updatedAt: created.updatedAt,\n },\n doc,\n record: {\n ...initialRecord,\n accessEpoch: 1,\n accessStateHash: created.accessManifestHash,\n // A committed seed stands in for the first metadata sync.\n lastCommitLsn: created.metadataSeed?.commitLsn ?? null,\n ...created.persistedMetadataState,\n },\n },\n seedCommittedAt: created.metadataSeed ? created.updatedAt : null,\n };\n}\n\nfunction buildLocalContainerContentsChildContainerState(input: {\n childId: string;\n icon: string | null;\n systemSlot?: ContainerSystemSlot | null | undefined;\n doc: ContainerMetadataDocumentState;\n initialRecord: DocumentRecord;\n parentState: ContainerState;\n trimmedName: string;\n}): ContainerState {\n const {\n systemSlot,\n childId,\n doc,\n icon,\n initialRecord,\n parentState,\n trimmedName,\n } = input;\n\n return {\n container: {\n id: childId,\n effectiveAccessLevel: \"admin\",\n organizationId: parentState.container.organizationId,\n parentId: parentState.container.id,\n metadataDocumentId: null,\n systemSlot: systemSlot ?? null,\n name: trimmedName,\n icon,\n },\n doc,\n record: initialRecord,\n };\n}\n\nfunction createInitialChildContainerDocumentRecord(input: {\n childId: string;\n initialUpdate: Uint8Array;\n}): DocumentRecord {\n return {\n accessEpoch: 1,\n accessStateHash: null,\n contentKeyBundle: null,\n documentId: null,\n documentKekTargets: null,\n documentManifestBundle: null,\n id: input.childId,\n lastCommitLsn: null,\n metadataUpdates: bytesToBase64(input.initialUpdate),\n snapshotEndVersion: \"\",\n };\n}\n\nfunction childContainerSaveOptions(input: {\n createIntent: { parentContainerId: string } | undefined;\n localUpdatedAt: string | null;\n stillCurrent?: (() => boolean) | undefined;\n}) {\n const { createIntent, localUpdatedAt, stillCurrent } = input;\n return createIntent || localUpdatedAt || stillCurrent\n ? {\n ...(createIntent ? { createIntent } : {}),\n ...(localUpdatedAt ? { localUpdatedAt } : {}),\n stillCurrent,\n }\n : undefined;\n}\n\nasync function persistCreatedChildContainer(input: {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n /** Set once the create committed the initial update as its seed. */\n localUpdatedAt: string | null;\n persistence: ContainerContentsPersistence;\n queueRemoteSync: boolean;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean | null> {\n const { containerState, localUpdatedAt, persistence, queueRemoteSync } =\n input;\n const { runtime } = input;\n const createIntent =\n queueRemoteSync &&\n !containerState.record.documentId &&\n containerState.container.parentId\n ? { parentContainerId: containerState.container.parentId }\n : undefined;\n const shouldRequestSync =\n queueRemoteSync &&\n (!containerState.record.documentId ||\n Boolean(containerState.record.contentKeyBundle));\n const saveOptions = childContainerSaveOptions({\n createIntent,\n localUpdatedAt,\n stillCurrent: input.stillCurrent,\n });\n const pendingUpdate = shouldRequestSync\n ? createPendingUpdateFields(input.initialUpdate)\n : null;\n if (pendingUpdate) {\n const saveContainerWithPendingUpdate =\n resolveAtomicContainerSave(persistence);\n if (!saveContainerWithPendingUpdate) return null;\n containerState.container = await saveContainerWithPendingUpdate(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n { ...saveOptions, pendingUpdate },\n );\n } else {\n containerState.container = await persistence.saveContainer(\n runtime.infra.execSql,\n containerState.container,\n containerState.record,\n saveOptions,\n );\n }\n return input.stillCurrent?.() === false ? null : shouldRequestSync;\n}\n\nexport async function createChildContainerState(input: {\n systemSlot?: ContainerSystemSlot | null | undefined;\n createRemote: boolean;\n icon?: string | null | undefined;\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n name: string;\n parentState: ContainerState;\n persistence: ContainerContentsPersistence;\n queueRemoteSync?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<CreatedChildContainerState | null> {\n const {\n createRemote,\n systemSlot,\n name,\n parentState,\n persistence,\n queueRemoteSync = true,\n resolveProjectionUserKey,\n runtime,\n } = input;\n const trimmedName = name.trim();\n if (!trimmedName) {\n return null;\n }\n\n const icon = input.icon?.trim() || null;\n const childId = await createChildContainerId(\n parentState.container.id,\n systemSlot,\n );\n const { doc, initialUpdate } =\n await createInitializedContainerMetadataDocument(childId, {\n icon,\n name: trimmedName,\n });\n const initialRecord = createInitialChildContainerDocumentRecord({\n childId,\n initialUpdate,\n });\n if (input.stillCurrent?.() === false) return null;\n // An initial metadata update and its container identity are one durable unit.\n // Refuse before any remote create when an adapter cannot provide\n // that atomic operation; a SQLite transaction cannot roll back adapter-owned\n // side effects.\n if (queueRemoteSync && !resolveAtomicContainerSave(persistence)) {\n return null;\n }\n\n const remoteChild = createRemote\n ? await buildRemoteContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n initialUpdate: queueRemoteSync ? initialUpdate : null,\n locallyAcceptedMetadataUpdateIds:\n input.locallyAcceptedMetadataUpdateIds,\n parentState,\n resolveProjectionUserKey,\n runtime,\n stillCurrent: input.stillCurrent,\n trimmedName,\n })\n : null;\n const containerState =\n remoteChild?.containerState ??\n buildLocalContainerContentsChildContainerState({\n childId,\n icon,\n systemSlot,\n doc,\n initialRecord,\n parentState,\n trimmedName,\n });\n const shouldRequestSync = await persistCreatedChildContainer({\n containerState,\n initialUpdate,\n // A committed seed leaves nothing to queue or sync: nothing local is\n // newer than the acknowledged create.\n localUpdatedAt: remoteChild?.seedCommittedAt ?? null,\n persistence,\n queueRemoteSync: queueRemoteSync && !remoteChild?.seedCommittedAt,\n runtime,\n stillCurrent: input.stillCurrent,\n });\n if (shouldRequestSync === null) return null;\n\n return {\n containerState,\n initialUpdate,\n shouldRequestSync,\n };\n}\n"]}
@@ -1,16 +1,12 @@
1
- import type { ContainerContentsPersistence } from "../../data/persistence/container-contents/containerContentsPersistence.js";
1
+ import { type ContainerContentsPersistence, sqlContainerContentsPersistence as defaultContainerContentsPersistence } from "../../data/persistence/container-contents/containerContentsPersistence.js";
2
2
  import { type ContainerSyncWatermarkLane } from "../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
3
- import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
4
3
  export type { ContainerContentsPersistence, ContainerCreateIntentRecord, ContainerHydrationTombstone, ContainerMetadataRecord, ContainerMetadataRecord as ContainerDocumentRecord, ContainerMoveIntentRecord, LocalRootDescendantReparentInput, StoredContainerState, } from "../../data/persistence/container-contents/containerContentsPersistence.js";
5
- export { sqlContainerContentsPersistence as defaultContainerContentsPersistence } from "../../data/persistence/container-contents/containerContentsPersistence.js";
6
4
  export type { ContainerMetadataRevalidation } from "../../data/persistence/container-contents/containerMetadataRevalidations.js";
7
5
  export type { ContainerRecord } from "../../data/persistence/container-contents/containerPersistence.js";
8
6
  export { type ContainerSyncWatermarkLane, ContainerSyncWatermarkRepository, } from "../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
9
7
  export type { ExecSql } from "../../data/sqlite/sqlSchema.js";
10
- export declare function enqueuePendingContainerUpdate(execSql: ExecSql, persistence: ContainerContentsPersistence, params: {
11
- containerId: string;
12
- sourceVersionVector?: string | null | undefined;
13
- update: Uint8Array;
14
- }): Promise<string | null>;
8
+ export { defaultContainerContentsPersistence };
15
9
  export declare function createContainerParentSyncLane(parentId: string | null): ContainerSyncWatermarkLane;
16
10
  export declare function createContainerContentsSyncLane(containerId: string): ContainerSyncWatermarkLane;
11
+ export declare function resolveAtomicContainerSave(persistence: ContainerContentsPersistence): NonNullable<ContainerContentsPersistence["saveContainerWithPendingUpdate"]> | null;
12
+ export declare function requireAtomicContainerSave(persistence: ContainerContentsPersistence): (execSql: import("./containerPersistence.js").ExecSql, container: import("./containerPersistence.js").ContainerRecord, record: import("./containerPersistence.js").ContainerMetadataRecord, options: import("../../data/persistence/container-contents/containerContentsPersistenceTypes.js").SaveContainerWithPendingUpdateOptions) => Promise<import("./containerPersistence.js").ContainerRecord>;
@@ -1,21 +1,31 @@
1
- import { createPendingUpdateFields } from "../../data/documents/documentSync.js";
1
+ import { sqlContainerContentsPersistence as defaultContainerContentsPersistence, } from "../../data/persistence/container-contents/containerContentsPersistence.js";
2
2
  import { containerContentsSyncLane, containerParentSyncLane, } from "../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
3
- export { sqlContainerContentsPersistence as defaultContainerContentsPersistence } from "../../data/persistence/container-contents/containerContentsPersistence.js";
4
3
  export { ContainerSyncWatermarkRepository, } from "../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
5
- export async function enqueuePendingContainerUpdate(execSql, persistence, params) {
6
- const pendingUpdateFields = createPendingUpdateFields(params.update, params.sourceVersionVector);
7
- if (!pendingUpdateFields) {
8
- return null;
9
- }
10
- return persistence.enqueuePendingUpdate(execSql, {
11
- containerId: params.containerId,
12
- ...pendingUpdateFields,
13
- });
14
- }
4
+ export { defaultContainerContentsPersistence };
15
5
  export function createContainerParentSyncLane(parentId) {
16
6
  return containerParentSyncLane(parentId);
17
7
  }
18
8
  export function createContainerContentsSyncLane(containerId) {
19
9
  return containerContentsSyncLane(containerId);
20
10
  }
11
+ export function resolveAtomicContainerSave(persistence) {
12
+ const saveContainerWithPendingUpdate = persistence.saveContainerWithPendingUpdate;
13
+ if (!saveContainerWithPendingUpdate)
14
+ return null;
15
+ const inheritedSqlAtomicSave = saveContainerWithPendingUpdate ===
16
+ defaultContainerContentsPersistence.saveContainerWithPendingUpdate &&
17
+ (persistence.saveContainer !==
18
+ defaultContainerContentsPersistence.saveContainer ||
19
+ persistence.enqueuePendingUpdate !==
20
+ defaultContainerContentsPersistence.enqueuePendingUpdate);
21
+ return inheritedSqlAtomicSave
22
+ ? null
23
+ : saveContainerWithPendingUpdate.bind(persistence);
24
+ }
25
+ export function requireAtomicContainerSave(persistence) {
26
+ const save = resolveAtomicContainerSave(persistence);
27
+ if (!save)
28
+ throw new Error("Container persistence must implement saveContainerWithPendingUpdate to repair pending metadata");
29
+ return save;
30
+ }
21
31
  //# sourceMappingURL=containerPersistence.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"containerPersistence.js","sourceRoot":"","sources":["containerPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAE9E,OAAO,EAEL,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,6EAA6E,CAAC;AAarF,OAAO,EAAE,+BAA+B,IAAI,mCAAmC,EAAE,MAAM,wEAAwE,CAAC;AAGhK,OAAO,EAEL,gCAAgC,GACjC,MAAM,6EAA6E,CAAC;AAGrF,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAgB,EAChB,WAAyC,EACzC,MAIC;IAED,MAAM,mBAAmB,GAAG,yBAAyB,CACnD,MAAM,CAAC,MAAM,EACb,MAAM,CAAC,mBAAmB,CAC3B,CAAC;IACF,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,WAAW,CAAC,oBAAoB,CAAC,OAAO,EAAE;QAC/C,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,GAAG,mBAAmB;KACvB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,QAAuB;IAEvB,OAAO,uBAAuB,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC7C,WAAmB;IAEnB,OAAO,yBAAyB,CAAC,WAAW,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport type { ContainerContentsPersistence } from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n type ContainerSyncWatermarkLane,\n containerContentsSyncLane,\n containerParentSyncLane,\n} from \"../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n ContainerMetadataRecord as ContainerDocumentRecord,\n ContainerMoveIntentRecord,\n LocalRootDescendantReparentInput,\n StoredContainerState,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nexport { sqlContainerContentsPersistence as defaultContainerContentsPersistence } from \"../../data/persistence/container-contents/containerContentsPersistence\";\nexport type { ContainerMetadataRevalidation } from \"../../data/persistence/container-contents/containerMetadataRevalidations\";\nexport type { ContainerRecord } from \"../../data/persistence/container-contents/containerPersistence\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n} from \"../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\n\nexport async function enqueuePendingContainerUpdate(\n execSql: ExecSql,\n persistence: ContainerContentsPersistence,\n params: {\n containerId: string;\n sourceVersionVector?: string | null | undefined;\n update: Uint8Array;\n },\n): Promise<string | null> {\n const pendingUpdateFields = createPendingUpdateFields(\n params.update,\n params.sourceVersionVector,\n );\n if (!pendingUpdateFields) {\n return null;\n }\n\n return persistence.enqueuePendingUpdate(execSql, {\n containerId: params.containerId,\n ...pendingUpdateFields,\n });\n}\n\nexport function createContainerParentSyncLane(\n parentId: string | null,\n): ContainerSyncWatermarkLane {\n return containerParentSyncLane(parentId);\n}\n\nexport function createContainerContentsSyncLane(\n containerId: string,\n): ContainerSyncWatermarkLane {\n return containerContentsSyncLane(containerId);\n}\n"]}
1
+ {"version":3,"file":"containerPersistence.js","sourceRoot":"","sources":["containerPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,+BAA+B,IAAI,mCAAmC,GACvE,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAEL,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,6EAA6E,CAAC;AAcrF,OAAO,EAEL,gCAAgC,GACjC,MAAM,6EAA6E,CAAC;AAErF,OAAO,EAAE,mCAAmC,EAAE,CAAC;AAE/C,MAAM,UAAU,6BAA6B,CAC3C,QAAuB;IAEvB,OAAO,uBAAuB,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,+BAA+B,CAC7C,WAAmB;IAEnB,OAAO,yBAAyB,CAAC,WAAW,CAAC,CAAC;AAChD,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,WAAyC;IAIzC,MAAM,8BAA8B,GAClC,WAAW,CAAC,8BAA8B,CAAC;IAC7C,IAAI,CAAC,8BAA8B;QAAE,OAAO,IAAI,CAAC;IACjD,MAAM,sBAAsB,GAC1B,8BAA8B;QAC5B,mCAAmC,CAAC,8BAA8B;QACpE,CAAC,WAAW,CAAC,aAAa;YACxB,mCAAmC,CAAC,aAAa;YACjD,WAAW,CAAC,oBAAoB;gBAC9B,mCAAmC,CAAC,oBAAoB,CAAC,CAAC;IAChE,OAAO,sBAAsB;QAC3B,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,8BAA8B,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,WAAyC;IAEzC,MAAM,IAAI,GAAG,0BAA0B,CAAC,WAAW,CAAC,CAAC;IACrD,IAAI,CAAC,IAAI;QACP,MAAM,IAAI,KAAK,CACb,gGAAgG,CACjG,CAAC;IACJ,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import {\n type ContainerContentsPersistence,\n sqlContainerContentsPersistence as defaultContainerContentsPersistence,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n type ContainerSyncWatermarkLane,\n containerContentsSyncLane,\n containerParentSyncLane,\n} from \"../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\n\nexport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerHydrationTombstone,\n ContainerMetadataRecord,\n ContainerMetadataRecord as ContainerDocumentRecord,\n ContainerMoveIntentRecord,\n LocalRootDescendantReparentInput,\n StoredContainerState,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nexport type { ContainerMetadataRevalidation } from \"../../data/persistence/container-contents/containerMetadataRevalidations\";\nexport type { ContainerRecord } from \"../../data/persistence/container-contents/containerPersistence\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n} from \"../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nexport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nexport { defaultContainerContentsPersistence };\n\nexport function createContainerParentSyncLane(\n parentId: string | null,\n): ContainerSyncWatermarkLane {\n return containerParentSyncLane(parentId);\n}\n\nexport function createContainerContentsSyncLane(\n containerId: string,\n): ContainerSyncWatermarkLane {\n return containerContentsSyncLane(containerId);\n}\n\nexport function resolveAtomicContainerSave(\n persistence: ContainerContentsPersistence,\n): NonNullable<\n ContainerContentsPersistence[\"saveContainerWithPendingUpdate\"]\n> | null {\n const saveContainerWithPendingUpdate =\n persistence.saveContainerWithPendingUpdate;\n if (!saveContainerWithPendingUpdate) return null;\n const inheritedSqlAtomicSave =\n saveContainerWithPendingUpdate ===\n defaultContainerContentsPersistence.saveContainerWithPendingUpdate &&\n (persistence.saveContainer !==\n defaultContainerContentsPersistence.saveContainer ||\n persistence.enqueuePendingUpdate !==\n defaultContainerContentsPersistence.enqueuePendingUpdate);\n return inheritedSqlAtomicSave\n ? null\n : saveContainerWithPendingUpdate.bind(persistence);\n}\n\nexport function requireAtomicContainerSave(\n persistence: ContainerContentsPersistence,\n) {\n const save = resolveAtomicContainerSave(persistence);\n if (!save)\n throw new Error(\n \"Container persistence must implement saveContainerWithPendingUpdate to repair pending metadata\",\n );\n return save;\n}\n"]}
@@ -6,8 +6,11 @@ export async function loadLocalContainerStates(input) {
6
6
  const storedContainers = await persistence.loadContainers(execSql);
7
7
  const containerStates = [];
8
8
  for (const storedContainer of storedContainers) {
9
+ if (input.isCurrent?.() === false)
10
+ break;
9
11
  containerStates.push(await hydrateStoredContainerState({
10
12
  execSql,
13
+ isCurrent: input.isCurrent,
11
14
  persistence,
12
15
  storedContainer,
13
16
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"localState.js","sourceRoot":"","sources":["localState.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAIrE,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAG9C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;IACtC,MAAM,WAAW,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACxC,MAAM,gBAAgB,GAAG,MAAM,WAAW,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;IAEnE,MAAM,eAAe,GAAqB,EAAE,CAAC;IAC7C,KAAK,MAAM,eAAe,IAAI,gBAAgB,EAAE,CAAC;QAC/C,eAAe,CAAC,IAAI,CAClB,MAAM,2BAA2B,CAAC;YAChC,OAAO;YACP,WAAW;YACX,eAAe;SAChB,CAAC,CACH,CAAC;IACJ,CAAC;IAED,OAAO,eAAe,CAAC;AACzB,CAAC","sourcesContent":["import type { ContainerContentsPersistence } from \"./containerPersistence\";\nimport type { ContainerState } from \"./remoteHydration\";\nimport type { ContainerContentsWorkflowSqlRuntime } from \"./runtime\";\nimport { hydrateStoredContainerState } from \"./storedContainerState\";\n\ntype LocalContainerStateRuntime = ContainerContentsWorkflowSqlRuntime;\n\nexport async function loadLocalContainerStates(input: {\n persistence: ContainerContentsPersistence;\n runtime: LocalContainerStateRuntime;\n}): Promise<ReadonlyArray<ContainerState>> {\n const { persistence, runtime } = input;\n const execSql = runtime.infra.execSql;\n await persistence.ensureSchema(execSql);\n const storedContainers = await persistence.loadContainers(execSql);\n\n const containerStates: ContainerState[] = [];\n for (const storedContainer of storedContainers) {\n containerStates.push(\n await hydrateStoredContainerState({\n execSql,\n persistence,\n storedContainer,\n }),\n );\n }\n\n return containerStates;\n}\n"]}
1
+ {"version":3,"file":"localState.js","sourceRoot":"","sources":["localState.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAIrE,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,KAI9C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;IACtC,MAAM,WAAW,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;IACxC,MAAM,gBAAgB,GAAG,MAAM,WAAW,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;IAEnE,MAAM,eAAe,GAAqB,EAAE,CAAC;IAC7C,KAAK,MAAM,eAAe,IAAI,gBAAgB,EAAE,CAAC;QAC/C,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,MAAM;QACzC,eAAe,CAAC,IAAI,CAClB,MAAM,2BAA2B,CAAC;YAChC,OAAO;YACP,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,WAAW;YACX,eAAe;SAChB,CAAC,CACH,CAAC;IACJ,CAAC;IAED,OAAO,eAAe,CAAC;AACzB,CAAC","sourcesContent":["import type { ContainerContentsPersistence } from \"./containerPersistence\";\nimport type { ContainerState } from \"./remoteHydration\";\nimport type { ContainerContentsWorkflowSqlRuntime } from \"./runtime\";\nimport { hydrateStoredContainerState } from \"./storedContainerState\";\n\ntype LocalContainerStateRuntime = ContainerContentsWorkflowSqlRuntime;\n\nexport async function loadLocalContainerStates(input: {\n isCurrent?: (() => boolean) | undefined;\n persistence: ContainerContentsPersistence;\n runtime: LocalContainerStateRuntime;\n}): Promise<ReadonlyArray<ContainerState>> {\n const { persistence, runtime } = input;\n const execSql = runtime.infra.execSql;\n await persistence.ensureSchema(execSql);\n const storedContainers = await persistence.loadContainers(execSql);\n\n const containerStates: ContainerState[] = [];\n for (const storedContainer of storedContainers) {\n if (input.isCurrent?.() === false) break;\n containerStates.push(\n await hydrateStoredContainerState({\n execSql,\n isCurrent: input.isCurrent,\n persistence,\n storedContainer,\n }),\n );\n }\n\n return containerStates;\n}\n"]}
@@ -0,0 +1,12 @@
1
+ import type { ReconnectCrawl, RemoteContainerHydrationHost, RemoteContainerHydrationState } from "./types.js";
2
+ export declare function hydrateRemoteContainers(input: {
3
+ followDiscoveredParentLanes?: boolean | undefined;
4
+ host: RemoteContainerHydrationHost;
5
+ isCurrent?: (() => boolean) | undefined;
6
+ reconnect?: ReconnectCrawl | undefined;
7
+ onFullyHydrated?: (() => Promise<void> | void) | undefined;
8
+ parentIds?: ReadonlyArray<string | null> | undefined;
9
+ resetAllLaneWatermarks?: boolean | undefined;
10
+ resetRootLaneWatermark?: boolean | undefined;
11
+ state: RemoteContainerHydrationState;
12
+ }): Promise<number>;
@@ -0,0 +1,93 @@
1
+ import { createContainerChildIndex } from "./lanes/childIndex.js";
2
+ import { createContainerParentHydrationQueue } from "./lanes/parentLaneQueue.js";
3
+ import { canHydrateRemoteContainers, hydrateContainerParentLanes, } from "./remoteContainers/remoteContainerPageHydration.js";
4
+ import { describeRemoteContainerHydration } from "./remoteHydrationLog.js";
5
+ async function finishRemoteHydration(input) {
6
+ if (input.isCurrent?.() === false) {
7
+ return;
8
+ }
9
+ if (input.changedCount > 0) {
10
+ input.host.updateSnapshot();
11
+ let insertedCount = 0;
12
+ for (const containerId of input.seenContainerIds) {
13
+ if (!input.containerIdsBeforeHydration.has(containerId)) {
14
+ insertedCount++;
15
+ }
16
+ }
17
+ input.state.runtime.util.log(describeRemoteContainerHydration({
18
+ changedCount: input.changedCount,
19
+ insertedCount,
20
+ }));
21
+ }
22
+ if (input.complete &&
23
+ input.isCurrent?.() !== false &&
24
+ input.onFullyHydrated) {
25
+ await input.onFullyHydrated();
26
+ }
27
+ }
28
+ // Distinct correlation IDs prevent an acknowledged crawl joining an older in-flight HTTP listing.
29
+ let reconnectSequence = 0;
30
+ export async function hydrateRemoteContainers(input) {
31
+ const { host, state } = input;
32
+ if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {
33
+ return 0;
34
+ }
35
+ const seenContainerIds = new Set();
36
+ const containerIdsBeforeHydration = new Set(state.containersById.keys());
37
+ const childIdsByParentId = createContainerChildIndex(state.containersById);
38
+ const { lanes, queueParentLane } = createContainerParentHydrationQueue({
39
+ containerIds: state.containersById.keys(),
40
+ parentIds: input.parentIds,
41
+ resetAllLaneWatermarks: input.resetAllLaneWatermarks,
42
+ resetRootLaneWatermark: input.resetRootLaneWatermark,
43
+ });
44
+ // Follow child lanes during an explicit recursive crawl or for containers first
45
+ // discovered in this pass. The latter lets a newly authorized root populate its
46
+ // descendants immediately, while routine ticks keep known subtrees cache-first.
47
+ const queueDiscoveredParentLane = (containerId) => {
48
+ if (input.followDiscoveredParentLanes ||
49
+ (containerId !== null && !containerIdsBeforeHydration.has(containerId))) {
50
+ queueParentLane(containerId);
51
+ }
52
+ };
53
+ let manualError;
54
+ const result = await hydrateContainerParentLanes({
55
+ reconnect: input.reconnect && {
56
+ laneIdPrefix: `r${++reconnectSequence}`,
57
+ recordManualError: (error) => {
58
+ manualError ??= error;
59
+ },
60
+ },
61
+ childIdsByParentId,
62
+ host,
63
+ isCurrent: input.isCurrent,
64
+ lanes,
65
+ queueParentLane: queueDiscoveredParentLane,
66
+ seenContainerIds,
67
+ state,
68
+ });
69
+ const { changedCount } = result;
70
+ await finishRemoteHydration({
71
+ changedCount,
72
+ complete: result.outcome === "complete" &&
73
+ canHydrateRemoteContainers(state) &&
74
+ input.isCurrent?.() !== false,
75
+ containerIdsBeforeHydration,
76
+ host,
77
+ isCurrent: input.isCurrent,
78
+ onFullyHydrated: input.onFullyHydrated,
79
+ seenContainerIds,
80
+ state,
81
+ });
82
+ if (input.reconnect?.isCurrent() && canHydrateRemoteContainers(state)) {
83
+ const manualRejection = input.resetAllLaneWatermarks
84
+ ? manualError
85
+ : undefined;
86
+ input.reconnect.record(result.outcome, manualRejection);
87
+ // A manual refresh sharing this crawl observes the error it would receive on its own.
88
+ if (manualRejection)
89
+ throw manualRejection;
90
+ }
91
+ return changedCount;
92
+ }
93
+ //# sourceMappingURL=hydrateRemoteContainers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydrateRemoteContainers.js","sourceRoot":"","sources":["hydrateRemoteContainers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,mCAAmC,EAAE,MAAM,yBAAyB,CAAC;AAC9E,OAAO,EACL,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAQxE,KAAK,UAAU,qBAAqB,CAAC,KASpC;IACC,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QAClC,OAAO;IACT,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;QAC5B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;YACjD,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;gBACxD,aAAa,EAAE,CAAC;YAClB,CAAC;QACH,CAAC;QACD,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAC1B,gCAAgC,CAAC;YAC/B,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,aAAa;SACd,CAAC,CACH,CAAC;IACJ,CAAC;IACD,IACE,KAAK,CAAC,QAAQ;QACd,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;QAC7B,KAAK,CAAC,eAAe,EACrB,CAAC;QACD,MAAM,KAAK,CAAC,eAAe,E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I,EAAE,iBAAiB,EAAE;YACvC,iBAAiB,EAAE,CAAC,KAAK,EAAE,EAAE;gBAC3B,WAAW,KAAK,KAAK,CAAC;YACxB,CAAC;SACF;QACD,kBAAkB;QAClB,IAAI;QACJ,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,KAAK;QACL,eAAe,EAAE,yBAAyB;QAC1C,gBAAgB;QAChB,KAAK;KACN,CAAC,CAAC;IACH,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,CAAC;IAChC,MAAM,qBAAqB,CAAC;QAC1B,YAAY;QACZ,QAAQ,EACN,MAAM,CAAC,OAAO,KAAK,UAAU;YAC7B,0BAA0B,CAAC,KAAK,CAAC;YACjC,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;QAC/B,2BAA2B;QAC3B,IAAI;QACJ,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB;QAChB,KAAK;KACN,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,IAAI,0BAA0B,CAAC,KAAK,CAAC,EAAE,CAAC;QACtE,MAAM,eAAe,GAAG,KAAK,CAAC,sBAAsB;YAClD,CAAC,CAAC,WAAW;YACb,CAAC,CAAC,SAAS,CAAC;QACd,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QACxD,sFAAsF;QACtF,IAAI,eAAe;YAAE,MAAM,eAAe,CAAC;IAC7C,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import { createContainerChildIndex } from \"./lanes/childIndex\";\nimport { createContainerParentHydrationQueue } from \"./lanes/parentLaneQueue\";\nimport {\n canHydrateRemoteContainers,\n hydrateContainerParentLanes,\n} from \"./remoteContainers/remoteContainerPageHydration\";\nimport { describeRemoteContainerHydration } from \"./remoteHydrationLog\";\nimport type {\n QueueContainerParentLane,\n ReconnectCrawl,\n RemoteContainerHydrationHost,\n RemoteContainerHydrationState,\n} from \"./types\";\n\nasync function finishRemoteHydration(input: {\n changedCount: number;\n complete: boolean;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n seenContainerIds: ReadonlySet<string>;\n containerIdsBeforeHydration: ReadonlySet<string>;\n state: RemoteContainerHydrationState;\n}): Promise<void> {\n if (input.isCurrent?.() === false) {\n return;\n }\n if (input.changedCount > 0) {\n input.host.updateSnapshot();\n let insertedCount = 0;\n for (const containerId of input.seenContainerIds) {\n if (!input.containerIdsBeforeHydration.has(containerId)) {\n insertedCount++;\n }\n }\n input.state.runtime.util.log(\n describeRemoteContainerHydration({\n changedCount: input.changedCount,\n insertedCount,\n }),\n );\n }\n if (\n input.complete &&\n input.isCurrent?.() !== false &&\n input.onFullyHydrated\n ) {\n await input.onFullyHydrated();\n }\n}\n\n// Distinct correlation IDs prevent an acknowledged crawl joining an older in-flight HTTP listing.\nlet reconnectSequence = 0;\n\nexport async function hydrateRemoteContainers(input: {\n followDiscoveredParentLanes?: boolean | undefined;\n host: RemoteContainerHydrationHost;\n isCurrent?: (() => boolean) | undefined;\n reconnect?: ReconnectCrawl | undefined;\n onFullyHydrated?: (() => Promise<void> | void) | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n resetRootLaneWatermark?: boolean | undefined;\n state: RemoteContainerHydrationState;\n}): Promise<number> {\n const { host, state } = input;\n if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {\n return 0;\n }\n\n const seenContainerIds = new Set<string>();\n const containerIdsBeforeHydration = new Set(state.containersById.keys());\n const childIdsByParentId = createContainerChildIndex(state.containersById);\n const { lanes, queueParentLane } = createContainerParentHydrationQueue({\n containerIds: state.containersById.keys(),\n parentIds: input.parentIds,\n resetAllLaneWatermarks: input.resetAllLaneWatermarks,\n resetRootLaneWatermark: input.resetRootLaneWatermark,\n });\n // Follow child lanes during an explicit recursive crawl or for containers first\n // discovered in this pass. The latter lets a newly authorized root populate its\n // descendants immediately, while routine ticks keep known subtrees cache-first.\n const queueDiscoveredParentLane: QueueContainerParentLane = (containerId) => {\n if (\n input.followDiscoveredParentLanes ||\n (containerId !== null && !containerIdsBeforeHydration.has(containerId))\n ) {\n queueParentLane(containerId);\n }\n };\n let manualError: Error | undefined;\n const result = await hydrateContainerParentLanes({\n reconnect: input.reconnect && {\n laneIdPrefix: `r${++reconnectSequence}`,\n recordManualError: (error) => {\n manualError ??= error;\n },\n },\n childIdsByParentId,\n host,\n isCurrent: input.isCurrent,\n lanes,\n queueParentLane: queueDiscoveredParentLane,\n seenContainerIds,\n state,\n });\n const { changedCount } = result;\n await finishRemoteHydration({\n changedCount,\n complete:\n result.outcome === \"complete\" &&\n canHydrateRemoteContainers(state) &&\n input.isCurrent?.() !== false,\n containerIdsBeforeHydration,\n host,\n isCurrent: input.isCurrent,\n onFullyHydrated: input.onFullyHydrated,\n seenContainerIds,\n state,\n });\n if (input.reconnect?.isCurrent() && canHydrateRemoteContainers(state)) {\n const manualRejection = input.resetAllLaneWatermarks\n ? manualError\n : undefined;\n input.reconnect.record(result.outcome, manualRejection);\n // A manual refresh sharing this crawl observes the error it would receive on its own.\n if (manualRejection) throw manualRejection;\n }\n return changedCount;\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { RemoteContainer, RemoteContainerHydrationHost, RemoteContainerHydrationState } from "./types.js";
2
- export type { ContainerState, PersistContainerStateResult, RemoteContainer, RemoteContainerHydrationHost, } from "./types.js";
2
+ export { hydrateRemoteContainers } from "./hydrateRemoteContainers.js";
3
+ export type { ContainerState, HydrationOutcome, PersistContainerStateResult, ReconnectCrawl, RemoteContainer, RemoteContainerHydrationHost, } from "./types.js";
3
4
  export declare class StaleRemoteHydrationError extends Error {
4
5
  }
5
6
  export declare function createGenerationGuardedHydrationHost(input: {
@@ -12,17 +13,8 @@ interface RemoteContainerIngestor {
12
13
  resume: () => Promise<void>;
13
14
  }
14
15
  export declare function createRemoteContainerIngestor(input: {
16
+ ownsScope?: () => boolean;
15
17
  getSerializationBarrier?: (() => Promise<void> | null) | undefined;
16
18
  host: RemoteContainerHydrationHost;
17
19
  state: RemoteContainerHydrationState;
18
20
  }): RemoteContainerIngestor;
19
- export declare function hydrateRemoteContainers(input: {
20
- followDiscoveredParentLanes?: boolean | undefined;
21
- host: RemoteContainerHydrationHost;
22
- isCurrent?: (() => boolean) | undefined;
23
- onFullyHydrated?: (() => Promise<void> | void) | undefined;
24
- parentIds?: ReadonlyArray<string | null> | undefined;
25
- resetAllLaneWatermarks?: boolean | undefined;
26
- resetRootLaneWatermark?: boolean | undefined;
27
- state: RemoteContainerHydrationState;
28
- }): Promise<number>;
@@ -1,10 +1,7 @@
1
- import { finishRemoteHydration } from "./completeHydration.js";
2
- import { createContainerChildIndex } from "./lanes/childIndex.js";
3
- import { createContainerParentHydrationQueue } from "./lanes/parentLaneQueue.js";
4
1
  import { cacheRemoteContainerPrincipalPolicies } from "./principalPolicyCache.js";
5
2
  import { loadPausedContainerFilter } from "./remoteContainers/organizationSyncPauseFilter.js";
6
- import { canHydrateRemoteContainers, hydrateContainerParentLanes, } from "./remoteContainers/remoteContainerPageHydration.js";
7
3
  import { listRemoteContainerIdsWithPendingMetadataUpdates, listRemoteContainerIdsWithPendingStructuralIntents, upsertIsolatedRemoteContainerState, } from "./remoteContainers/remoteContainerState.js";
4
+ export { hydrateRemoteContainers } from "./hydrateRemoteContainers.js";
8
5
  export class StaleRemoteHydrationError extends Error {
9
6
  }
10
7
  export function createGenerationGuardedHydrationHost(input) {
@@ -192,7 +189,18 @@ export function createRemoteContainerIngestor(input) {
192
189
  const pendingRemoteContainersById = new Map();
193
190
  const generationByContainerId = new Map();
194
191
  let ingestRemoteContainersPromise = null;
192
+ const settleStale = (generation) => settleStaleRemoteContainerIngestGeneration({
193
+ generation,
194
+ generationByContainerId,
195
+ queue: pendingRemoteContainersById,
196
+ state,
197
+ });
195
198
  const runNextGeneration = () => {
199
+ if (input.ownsScope?.() === false) {
200
+ pendingRemoteContainersById.clear();
201
+ generationByContainerId.clear();
202
+ return Promise.resolve();
203
+ }
196
204
  if (ingestRemoteContainersPromise) {
197
205
  return ingestRemoteContainersPromise.then(runNextGeneration, runNextGeneration);
198
206
  }
@@ -213,7 +221,8 @@ export function createRemoteContainerIngestor(input) {
213
221
  pendingRemoteContainersById.delete(nextContainerId);
214
222
  return runNextGeneration();
215
223
  }
216
- const isCurrent = () => isRemoteContainerIngestGenerationCurrent(state, generation);
224
+ const isCurrent = () => input.ownsScope?.() !== false &&
225
+ isRemoteContainerIngestGenerationCurrent(state, generation);
217
226
  const guardedHost = createGenerationGuardedHydrationHost({
218
227
  host,
219
228
  isCurrent,
@@ -228,23 +237,12 @@ export function createRemoteContainerIngestor(input) {
228
237
  state,
229
238
  }))
230
239
  .then(() => {
231
- if (!isCurrent()) {
232
- settleStaleRemoteContainerIngestGeneration({
233
- generation,
234
- generationByContainerId,
235
- queue: pendingRemoteContainersById,
236
- state,
237
- });
238
- }
240
+ if (!isCurrent())
241
+ settleStale(generation);
239
242
  })
240
243
  .catch((error) => {
241
244
  if (!isCurrent() || error instanceof StaleRemoteHydrationError) {
242
- settleStaleRemoteContainerIngestGeneration({
243
- generation,
244
- generationByContainerId,
245
- queue: pendingRemoteContainersById,
246
- state,
247
- });
245
+ settleStale(generation);
248
246
  return;
249
247
  }
250
248
  throw error;
@@ -266,51 +264,4 @@ export function createRemoteContainerIngestor(input) {
266
264
  ingestRemoteContainer.resume = runNextGeneration;
267
265
  return ingestRemoteContainer;
268
266
  }
269
- export async function hydrateRemoteContainers(input) {
270
- const { host, state } = input;
271
- if (!canHydrateRemoteContainers(state) || input.isCurrent?.() === false) {
272
- return 0;
273
- }
274
- const seenContainerIds = new Set();
275
- const containerIdsBeforeHydration = new Set(state.containersById.keys());
276
- const childIdsByParentId = createContainerChildIndex(state.containersById);
277
- const { lanes, queueParentLane } = createContainerParentHydrationQueue({
278
- containerIds: state.containersById.keys(),
279
- parentIds: input.parentIds,
280
- resetAllLaneWatermarks: input.resetAllLaneWatermarks,
281
- resetRootLaneWatermark: input.resetRootLaneWatermark,
282
- });
283
- // Follow child lanes during an explicit recursive crawl or for containers first
284
- // discovered in this pass. The latter lets a newly authorized root populate its
285
- // descendants immediately, while routine ticks keep known subtrees cache-first.
286
- const queueDiscoveredParentLane = (containerId) => {
287
- if (input.followDiscoveredParentLanes ||
288
- (containerId !== null && !containerIdsBeforeHydration.has(containerId))) {
289
- queueParentLane(containerId);
290
- }
291
- };
292
- const result = await hydrateContainerParentLanes({
293
- childIdsByParentId,
294
- host,
295
- isCurrent: input.isCurrent,
296
- lanes,
297
- queueParentLane: queueDiscoveredParentLane,
298
- seenContainerIds,
299
- state,
300
- });
301
- const { changedCount } = result;
302
- await finishRemoteHydration({
303
- changedCount,
304
- complete: result.complete &&
305
- canHydrateRemoteContainers(state) &&
306
- input.isCurrent?.() !== false,
307
- containerIdsBeforeHydration,
308
- host,
309
- isCurrent: input.isCurrent,
310
- onFullyHydrated: input.onFullyHydrated,
311
- seenContainerIds,
312
- state,
313
- });
314
- return changedCount;
315
- }
316
267
  //# sourceMappingURL=index.js.map