@tearleads/client-sdk 0.1.255 → 0.1.256

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.255",
3
+ "version": "0.1.256",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -241,16 +241,17 @@ function bindManualTreeReset(input) {
241
241
  return { ...input, ownsTreeReset: captureTreeResetOwner(input.state) };
242
242
  }
243
243
  export function requestContainerContentsRemoteHydration(input) {
244
- const { host, scheduleSync, state } = input;
245
244
  input = bindManualTreeReset(input);
246
245
  if (!ownsHydrationRequest(input))
247
246
  return Promise.resolve();
248
247
  queueRequestedParentIds(input);
249
248
  const readinessBarrier = waitForRemoteHydrationReadiness(input);
250
- if (readinessBarrier) {
251
- return readinessBarrier;
252
- }
253
- input = prepareTreeReset(input);
249
+ const request = readinessBarrier ?? startHydration(prepareTreeReset(input));
250
+ input.state.trackHydration?.(request);
251
+ return request;
252
+ }
253
+ function startHydration(input) {
254
+ const { host, scheduleSync, state } = input;
254
255
  const { followDiscoveredParentLanes, parentIds } = consumeQueuedHydrationScope(state, input.followDiscoveredParentLanes);
255
256
  let appliedRemoteContainerChange = false;
256
257
  let retainInterruptedHydration = false;
@@ -1 +1 @@
1
- {"version":3,"file":"remoteHydrationRequest.js","sourceRoot":"","sources":["remoteHydrationRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAGvB,yBAAyB,GAC1B,MAAM,uDAAuD,CAAC;AAE/D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gDAAgD,CAAC;AAC5F,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAEL,2BAA2B,GAC5B,MAAM,iBAAiB,CA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C3C,IAAI,KAAK,CAAC,sBAAsB,KAAK,gBAAgB,EAAE,CAAC;YACtD,KAAK,CAAC,sBAAsB,GAAG,IAAI,CAAC;YACpC,KAAK,CAAC,yBAAyB,GAAG,IAAI,CAAC;YACvC,KAAK,CAAC,mCAAmC,GAAG,IAAI,CAAC;QACnD,CAAC;QAED,IACE,SAAS,EAAE;YACX,CAAC,CAAC,CAAC,KAAK,CAAC,6BAA6B,IAAI,IAAI,CAAC;gBAC7C,CAAC,4BAA4B;oBAC3B,CAAC,CAAC,6BAA6B,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC;gBAC9D,KAAK,CAAC,0BAA0B,CAAC;YACnC,KAAK,CAAC,QAAQ,CAAC,KAAK;YACpB,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe;YAClC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,EAC1B,CAAC;YACD,YAAY,EAAE,CAAC;QACjB,CAAC;QACD,IAAI,qBAAqB,EAAE,CAAC;YAC1B,OAAO,8BAA8B,CAAC,KAAK,CAAC,CAAC;QAC/C,CAAC;QACD,IAAI,0BAA0B,EAAE,CAAC;YAC/B,4BAA4B,CAAC,KAAK,CAAC,CAAC;QACtC,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;IACL,KAAK,CAAC,sBAAsB,GAAG,gBAAgB,CAAC;IAEhD,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import {\n createGenerationGuardedHydrationHost,\n hydrateRemoteContainers,\n type ReconnectCrawl,\n type RemoteContainerHydrationHost,\n StaleRemoteHydrationError,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { RemoteContainerHydrationState } from \"../../../workflows/container-contents/remoteHydration/types\";\nimport { isDatabaseUnavailableError } from \"../../../workflows/container-contents/syncLane\";\nimport { ownsContainerStore } from \"../containerState/storeScope\";\nimport {\n type LocalContainerRefreshState,\n refreshLocalContainerStates,\n} from \"../localRefresh\";\nimport {\n IDLE_RECOVERY_HYDRATION,\n type RecoveryHydrationEvent,\n type RecoveryHydrationState,\n transitionRecoveryHydration,\n} from \"./recoveryHydrationMachine\";\n\nimport {\n captureTreeResetOwner,\n claimTreeReset,\n queueTreeReset,\n} from \"./treeResetMachine\";\n\ntype RemoteHydrationRequestState = RemoteContainerHydrationState &\n LocalContainerRefreshState & {\n containerParentIdsNeedingHydration: Set<string | null>;\n initializePromise: Promise<void> | null;\n lifecycleGeneration: number;\n remoteHydrationGeneration: number | null;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationStructuralGeneration: number | null;\n rootLaneHydrated: boolean;\n snapshot: {\n ready: boolean;\n };\n structuralGeneration: number;\n writeGeneration?: number;\n };\n\ninterface RemoteHydrationRequestInput {\n ownsTreeReset?: () => boolean;\n followDiscoveredParentLanes?: boolean | undefined;\n host: RemoteContainerHydrationHost;\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 recreateOnFullyHydratedAfterReset?:\n | (() => () => Promise<void> | void)\n | undefined;\n recreateOnFullyHydratedAtStart?: boolean | undefined;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSyncAfterHydration?: boolean | undefined;\n scheduleSyncOnHydrationChange?: boolean | undefined;\n scheduleSync: () => void;\n state: RemoteHydrationRequestState;\n}\n\ninterface RecoveryHydrationRequest {\n input: RemoteHydrationRequestInput;\n lifecycleGeneration: number;\n structuralGeneration: number;\n}\n\nfunction isRequestGenerationCurrent(input: {\n lifecycleGeneration: number;\n state: RemoteHydrationRequestState;\n structuralGeneration: number;\n}): boolean {\n return (\n ownsContainerStore(input.state) &&\n input.state.lifecycleGeneration === input.lifecycleGeneration &&\n input.state.structuralGeneration === input.structuralGeneration\n );\n}\n\nconst recoveryHydrationByState = new WeakMap<\n RemoteHydrationRequestState,\n RecoveryHydrationState<RecoveryHydrationRequest>\n>();\n\nfunction dispatchRecoveryHydration(\n state: RemoteHydrationRequestState,\n event: RecoveryHydrationEvent<RecoveryHydrationRequest>,\n): void {\n const next = transitionRecoveryHydration(\n recoveryHydrationByState.get(state) ?? IDLE_RECOVERY_HYDRATION,\n event,\n );\n if (next.status === \"idle\") {\n recoveryHydrationByState.delete(state);\n } else {\n recoveryHydrationByState.set(state, next);\n }\n}\n\nfunction queueRecoveryHydrationRequest(\n input: RemoteHydrationRequestInput,\n): void {\n dispatchRecoveryHydration(input.state, {\n request: {\n input,\n lifecycleGeneration: input.state.lifecycleGeneration,\n structuralGeneration: input.state.structuralGeneration,\n },\n type: \"queued\",\n });\n}\n\nfunction hasRemoteHydrationPrerequisites(\n state: RemoteHydrationRequestState,\n): boolean {\n return (\n (state.runtime.liveHydrationStatus?.() ?? \"ready\") === \"ready\" &&\n state.runtime.infra.dbStatus === \"ready\" &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online\n );\n}\n\nfunction createResetRecoveryInput(\n input: RemoteHydrationRequestInput,\n): RemoteHydrationRequestInput {\n return {\n ...input,\n followDiscoveredParentLanes: true,\n onFullyHydrated: undefined,\n parentIds: undefined,\n recreateOnFullyHydratedAtStart: true,\n };\n}\n\nfunction resumeRetainedRecoveryHydration(\n input: RemoteHydrationRequestInput,\n): Promise<void> {\n if (!ownsHydrationRequest(input)) return Promise.resolve();\n queueRecoveryHydrationRequest(input);\n return hasRemoteHydrationPrerequisites(input.state)\n ? input.resumeRecoveryWork()\n : Promise.resolve();\n}\n\nfunction prepareTreeReset(\n input: RemoteHydrationRequestInput,\n): RemoteHydrationRequestInput {\n const coverReset = claimTreeReset(\n input.state,\n !!input.reconnect || !!input.resetAllLaneWatermarks,\n );\n if (!coverReset) return input;\n const onCovered = input.recreateOnFullyHydratedAtStart\n ? input.recreateOnFullyHydratedAfterReset?.()\n : input.onFullyHydrated;\n return {\n ...input,\n followDiscoveredParentLanes: true,\n resetAllLaneWatermarks: true,\n recreateOnFullyHydratedAtStart: false,\n ownsTreeReset: coverReset.isOwned,\n onFullyHydrated: () => {\n coverReset.cover();\n return onCovered?.();\n },\n };\n}\n\nfunction waitForActiveRemoteHydration(\n input: RemoteHydrationRequestInput,\n): Promise<void> | null {\n const { state } = input;\n const activeHydration = state.remoteHydrationPromise;\n if (!activeHydration) {\n return null;\n }\n const requestLifecycleGeneration = state.lifecycleGeneration;\n const requestStructuralGeneration = state.structuralGeneration;\n const needsCurrentGenerationHydration =\n state.remoteHydrationGeneration !== state.lifecycleGeneration ||\n state.remoteHydrationStructuralGeneration !== state.structuralGeneration;\n // A restoration owns its sweep callback and its sync scheduling policy.\n // Let it list after prior work settles so its durable claim can complete.\n const needsOwnCrawl =\n !!(input.onFullyHydrated || input.recreateOnFullyHydratedAfterReset) &&\n !!input.resetAllLaneWatermarks &&\n !!input.followDiscoveredParentLanes;\n if (\n !needsOwnCrawl &&\n input.resetAllLaneWatermarks &&\n input.followDiscoveredParentLanes\n ) {\n input = { ...input, ownsTreeReset: queueTreeReset(state) };\n }\n const requestQueuedHydration = () => {\n if (\n !isRequestGenerationCurrent({\n lifecycleGeneration: requestLifecycleGeneration,\n state,\n structuralGeneration: requestStructuralGeneration,\n })\n ) {\n return retryRemoteHydrationAfterReset(input);\n }\n // Another request's crawl may have taken over this request's queued\n // lanes. Settle with that crawl rather than at once, so the request never\n // resolves before the listing that covers it.\n return needsOwnCrawl ||\n needsCurrentGenerationHydration ||\n state.containerParentIdsNeedingHydration.size > 0\n ? requestContainerContentsRemoteHydration(input)\n : (state.remoteHydrationPromise ?? undefined);\n };\n return activeHydration.then(\n requestQueuedHydration,\n (error: unknown) => requestQueuedHydration() ?? Promise.reject(error),\n );\n}\n\nfunction waitForActiveInitialization(\n input: RemoteHydrationRequestInput,\n): Promise<void> | null {\n const { state } = input;\n const activeInitialization = state.initializePromise;\n if (!activeInitialization) {\n return null;\n }\n const requestLifecycleGeneration = state.lifecycleGeneration;\n const requestStructuralGeneration = state.structuralGeneration;\n return activeInitialization.then(() => {\n const recoveryInput = isRequestGenerationCurrent({\n lifecycleGeneration: requestLifecycleGeneration,\n state,\n structuralGeneration: requestStructuralGeneration,\n })\n ? input\n : createResetRecoveryInput(input);\n return resumeRetainedRecoveryHydration(recoveryInput);\n });\n}\n\nfunction retryRemoteHydrationAfterReset(\n input: RemoteHydrationRequestInput,\n): Promise<void> {\n // The reconnect state machine owns its retry across a reset.\n if (input.reconnect) {\n // A superseded crawl still owes the manual refresh whose reset it consumed.\n // Complete that request under the live store's own generation guard.\n if (\n !input.ownsTreeReset?.() ||\n input.state.runtime.liveHydrationStatus?.() === \"retired\"\n )\n return Promise.resolve();\n input = { ...input, reconnect: undefined };\n }\n return resumeRetainedRecoveryHydration(createResetRecoveryInput(input));\n}\n\nfunction retainResetRecoveryHydration(\n input: RemoteHydrationRequestInput,\n): void {\n queueRecoveryHydrationRequest(createResetRecoveryInput(input));\n}\n\nexport function resumeContainerContentsRecoveryHydration(\n state: RemoteHydrationRequestState,\n): Promise<void> | null {\n const recovery =\n recoveryHydrationByState.get(state) ?? IDLE_RECOVERY_HYDRATION;\n if (recovery.status === \"idle\") return null;\n // Another caller already took this caller's queued request over.\n if (recovery.status === \"running\") return recovery.run;\n const inputs = recovery.requests.map((request) =>\n isRequestGenerationCurrent({\n lifecycleGeneration: request.lifecycleGeneration,\n state,\n structuralGeneration: request.structuralGeneration,\n })\n ? request.input\n : createResetRecoveryInput(request.input),\n );\n let resolveRun: () => void = () => undefined;\n let rejectRun: (error: unknown) => void = () => undefined;\n const run = new Promise<void>((resolve, reject) => {\n resolveRun = resolve;\n rejectRun = reject;\n });\n // The run is current before its requests start, so a request one of them\n // queues meanwhile waits for the next resume instead of being dropped.\n dispatchRecoveryHydration(state, { run, type: \"started\" });\n const settle = () =>\n dispatchRecoveryHydration(state, { run, type: \"settled\" });\n run.then(settle, settle);\n const fail = (error: unknown) => {\n for (const input of inputs) {\n queueRecoveryHydrationRequest(input);\n }\n rejectRun(error);\n };\n try {\n Promise.all(inputs.map(requestContainerContentsRemoteHydration)).then(\n () => resolveRun(),\n fail,\n );\n } catch (error) {\n fail(error);\n }\n return run;\n}\n\nfunction queueRequestedParentIds(input: RemoteHydrationRequestInput): void {\n if (!input.parentIds) {\n return;\n }\n for (const parentId of input.parentIds) {\n input.state.containerParentIdsNeedingHydration.add(parentId);\n }\n}\n\nfunction waitForRemoteHydrationReadiness(\n input: RemoteHydrationRequestInput,\n): Promise<void> | null {\n const activeHydration = waitForActiveRemoteHydration(input);\n if (activeHydration) {\n return activeHydration;\n }\n const activeInitialization = waitForActiveInitialization(input);\n if (activeInitialization) {\n return activeInitialization;\n }\n if (!hasRemoteHydrationPrerequisites(input.state)) {\n queueRecoveryHydrationRequest(input);\n return Promise.resolve();\n }\n return null;\n}\n\nfunction consumeQueuedHydrationScope(\n state: RemoteHydrationRequestState,\n followDiscoveredParentLanesOption: boolean | undefined,\n): {\n followDiscoveredParentLanes: boolean;\n parentIds: ReadonlyArray<string | null> | undefined;\n} {\n const queuedParentIds = Array.from(state.containerParentIdsNeedingHydration);\n const followDiscoveredParentLanes =\n followDiscoveredParentLanesOption ?? queuedParentIds.length === 0;\n state.containerParentIdsNeedingHydration.clear();\n return {\n followDiscoveredParentLanes,\n parentIds:\n followDiscoveredParentLanes || queuedParentIds.length === 0\n ? undefined\n : queuedParentIds,\n };\n}\n\nfunction ownsHydrationRequest(input: RemoteHydrationRequestInput): boolean {\n return (\n ownsContainerStore(input.state) &&\n input.ownsTreeReset?.() !== false &&\n input.reconnect?.isCurrent() !== false\n );\n}\n\nfunction captureHydrationScope(\n input: RemoteHydrationRequestInput,\n): () => boolean {\n const { state } = input;\n const { lifecycleGeneration, structuralGeneration } = state;\n return () =>\n ownsHydrationRequest(input) &&\n isRequestGenerationCurrent({\n state,\n lifecycleGeneration,\n structuralGeneration,\n });\n}\n\nfunction bindManualTreeReset(\n input: RemoteHydrationRequestInput,\n): RemoteHydrationRequestInput {\n if (\n !input.resetAllLaneWatermarks ||\n input.ownsTreeReset ||\n input.onFullyHydrated ||\n input.recreateOnFullyHydratedAfterReset\n )\n return input;\n return { ...input, ownsTreeReset: captureTreeResetOwner(input.state) };\n}\n\nexport function requestContainerContentsRemoteHydration(\n input: RemoteHydrationRequestInput,\n): Promise<void> {\n const { host, scheduleSync, state } = input;\n input = bindManualTreeReset(input);\n if (!ownsHydrationRequest(input)) return Promise.resolve();\n queueRequestedParentIds(input);\n const readinessBarrier = waitForRemoteHydrationReadiness(input);\n if (readinessBarrier) {\n return readinessBarrier;\n }\n\n input = prepareTreeReset(input);\n const { followDiscoveredParentLanes, parentIds } =\n consumeQueuedHydrationScope(state, input.followDiscoveredParentLanes);\n\n let appliedRemoteContainerChange = false;\n let retainInterruptedHydration = false;\n const { lifecycleGeneration, structuralGeneration } = state;\n const isCurrent = captureHydrationScope(input);\n const onFullyHydrated = input.recreateOnFullyHydratedAtStart\n ? input.recreateOnFullyHydratedAfterReset?.()\n : input.onFullyHydrated;\n const hydrationHost = createGenerationGuardedHydrationHost({\n host,\n isCurrent,\n });\n const rootLaneHydratedBeforeRequest = state.rootLaneHydrated;\n state.remoteHydrationGeneration = lifecycleGeneration;\n state.remoteHydrationStructuralGeneration = structuralGeneration;\n const hydrationPromise = refreshLocalContainerStates({\n host: hydrationHost,\n stillCurrent: input.reconnect?.isCurrent,\n state,\n })\n .then(() => {\n if (!isCurrent()) {\n return 0;\n }\n return hydrateRemoteContainers({\n followDiscoveredParentLanes,\n host: hydrationHost,\n isCurrent,\n onFullyHydrated,\n reconnect: input.reconnect,\n parentIds,\n resetAllLaneWatermarks: input.resetAllLaneWatermarks,\n resetRootLaneWatermark: input.resetRootLaneWatermark,\n state,\n });\n })\n .then((changedCount) => {\n appliedRemoteContainerChange = changedCount > 0;\n if (isCurrent() && !hasRemoteHydrationPrerequisites(state)) {\n retainInterruptedHydration = true;\n }\n })\n .catch((error: unknown) => {\n if (isCurrent() && isDatabaseUnavailableError(error)) {\n retainInterruptedHydration = true;\n return;\n }\n if (!isCurrent() || error instanceof StaleRemoteHydrationError) {\n return;\n }\n\n throw error;\n })\n .finally(() => {\n const shouldRetryAfterReset = !isCurrent();\n if (state.remoteHydrationPromise === hydrationPromise) {\n state.remoteHydrationPromise = null;\n state.remoteHydrationGeneration = null;\n state.remoteHydrationStructuralGeneration = null;\n }\n\n if (\n isCurrent() &&\n (((input.scheduleSyncOnHydrationChange ?? true) &&\n (appliedRemoteContainerChange ||\n (!rootLaneHydratedBeforeRequest && state.rootLaneHydrated))) ||\n input.scheduleSyncAfterHydration) &&\n state.snapshot.ready &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online\n ) {\n scheduleSync();\n }\n if (shouldRetryAfterReset) {\n return retryRemoteHydrationAfterReset(input);\n }\n if (retainInterruptedHydration) {\n retainResetRecoveryHydration(input);\n }\n return undefined;\n });\n state.remoteHydrationPromise = hydrationPromise;\n\n return hydrationPromise;\n}\n"]}
1
+ {"version":3,"file":"remoteHydrationRequest.js","sourceRoot":"","sources":["remoteHydrationRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAGvB,yBAAyB,GAC1B,MAAM,uDAAuD,CAAC;AAE/D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gDAAgD,CAAC;AAC5F,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAEL,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,uBAAuB,EAGvB,2BAA2B,GAC5B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,cAAc,GACf,MAAM,oBAAoB,CAAC;AA6C5B,SAAS,0BAA0B,CAAC,KAInC;IACC,OAAO,CACL,kBAAkB,CAAC,KAAK,CAAC,KAAK,CAAC;QAC/B,KAAK,CAAC,KAAK,CAAC,mBAAmB,KAAK,KAAK,CAAC,mBAAmB;QAC7D,KAAK,CAAC,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AAE;YACX,CAAC,CAAC,CAAC,KAAK,CAAC,6BAA6B,IAAI,IAAI,CAAC;gBAC7C,CAAC,4BAA4B;oBAC3B,CAAC,CAAC,6BAA6B,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC,CAAC;gBAC9D,KAAK,CAAC,0BAA0B,CAAC;YACnC,KAAK,CAAC,QAAQ,CAAC,KAAK;YACpB,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe;YAClC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,EAC1B,CAAC;YACD,YAAY,EAAE,CAAC;QACjB,CAAC;QACD,IAAI,qBAAqB,EAAE,CAAC;YAC1B,OAAO,8BAA8B,CAAC,KAAK,CAAC,CAAC;QAC/C,CAAC;QACD,IAAI,0BAA0B,EAAE,CAAC;YAC/B,4BAA4B,CAAC,KAAK,CAAC,CAAC;QACtC,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;IACL,KAAK,CAAC,sBAAsB,GAAG,gBAAgB,CAAC;IAChD,OAAO,gBAAgB,CAAC;AAC1B,CAAC","sourcesContent":["import {\n createGenerationGuardedHydrationHost,\n hydrateRemoteContainers,\n type ReconnectCrawl,\n type RemoteContainerHydrationHost,\n StaleRemoteHydrationError,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { RemoteContainerHydrationState } from \"../../../workflows/container-contents/remoteHydration/types\";\nimport { isDatabaseUnavailableError } from \"../../../workflows/container-contents/syncLane\";\nimport { ownsContainerStore } from \"../containerState/storeScope\";\nimport {\n type LocalContainerRefreshState,\n refreshLocalContainerStates,\n} from \"../localRefresh\";\nimport {\n IDLE_RECOVERY_HYDRATION,\n type RecoveryHydrationEvent,\n type RecoveryHydrationState,\n transitionRecoveryHydration,\n} from \"./recoveryHydrationMachine\";\n\nimport {\n captureTreeResetOwner,\n claimTreeReset,\n queueTreeReset,\n} from \"./treeResetMachine\";\n\ntype RemoteHydrationRequestState = RemoteContainerHydrationState &\n LocalContainerRefreshState & {\n containerParentIdsNeedingHydration: Set<string | null>;\n initializePromise: Promise<void> | null;\n lifecycleGeneration: number;\n remoteHydrationGeneration: number | null;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationStructuralGeneration: number | null;\n rootLaneHydrated: boolean;\n snapshot: {\n ready: boolean;\n };\n structuralGeneration: number;\n trackHydration?: (request: Promise<unknown>) => void;\n writeGeneration?: number;\n };\n\ninterface RemoteHydrationRequestInput {\n ownsTreeReset?: () => boolean;\n followDiscoveredParentLanes?: boolean | undefined;\n host: RemoteContainerHydrationHost;\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 recreateOnFullyHydratedAfterReset?:\n | (() => () => Promise<void> | void)\n | undefined;\n recreateOnFullyHydratedAtStart?: boolean | undefined;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSyncAfterHydration?: boolean | undefined;\n scheduleSyncOnHydrationChange?: boolean | undefined;\n scheduleSync: () => void;\n state: RemoteHydrationRequestState;\n}\n\ninterface RecoveryHydrationRequest {\n input: RemoteHydrationRequestInput;\n lifecycleGeneration: number;\n structuralGeneration: number;\n}\n\nfunction isRequestGenerationCurrent(input: {\n lifecycleGeneration: number;\n state: RemoteHydrationRequestState;\n structuralGeneration: number;\n}): boolean {\n return (\n ownsContainerStore(input.state) &&\n input.state.lifecycleGeneration === input.lifecycleGeneration &&\n input.state.structuralGeneration === input.structuralGeneration\n );\n}\n\nconst recoveryHydrationByState = new WeakMap<\n RemoteHydrationRequestState,\n RecoveryHydrationState<RecoveryHydrationRequest>\n>();\n\nfunction dispatchRecoveryHydration(\n state: RemoteHydrationRequestState,\n event: RecoveryHydrationEvent<RecoveryHydrationRequest>,\n): void {\n const next = transitionRecoveryHydration(\n recoveryHydrationByState.get(state) ?? IDLE_RECOVERY_HYDRATION,\n event,\n );\n if (next.status === \"idle\") {\n recoveryHydrationByState.delete(state);\n } else {\n recoveryHydrationByState.set(state, next);\n }\n}\n\nfunction queueRecoveryHydrationRequest(\n input: RemoteHydrationRequestInput,\n): void {\n dispatchRecoveryHydration(input.state, {\n request: {\n input,\n lifecycleGeneration: input.state.lifecycleGeneration,\n structuralGeneration: input.state.structuralGeneration,\n },\n type: \"queued\",\n });\n}\n\nfunction hasRemoteHydrationPrerequisites(\n state: RemoteHydrationRequestState,\n): boolean {\n return (\n (state.runtime.liveHydrationStatus?.() ?? \"ready\") === \"ready\" &&\n state.runtime.infra.dbStatus === \"ready\" &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online\n );\n}\n\nfunction createResetRecoveryInput(\n input: RemoteHydrationRequestInput,\n): RemoteHydrationRequestInput {\n return {\n ...input,\n followDiscoveredParentLanes: true,\n onFullyHydrated: undefined,\n parentIds: undefined,\n recreateOnFullyHydratedAtStart: true,\n };\n}\n\nfunction resumeRetainedRecoveryHydration(\n input: RemoteHydrationRequestInput,\n): Promise<void> {\n if (!ownsHydrationRequest(input)) return Promise.resolve();\n queueRecoveryHydrationRequest(input);\n return hasRemoteHydrationPrerequisites(input.state)\n ? input.resumeRecoveryWork()\n : Promise.resolve();\n}\n\nfunction prepareTreeReset(\n input: RemoteHydrationRequestInput,\n): RemoteHydrationRequestInput {\n const coverReset = claimTreeReset(\n input.state,\n !!input.reconnect || !!input.resetAllLaneWatermarks,\n );\n if (!coverReset) return input;\n const onCovered = input.recreateOnFullyHydratedAtStart\n ? input.recreateOnFullyHydratedAfterReset?.()\n : input.onFullyHydrated;\n return {\n ...input,\n followDiscoveredParentLanes: true,\n resetAllLaneWatermarks: true,\n recreateOnFullyHydratedAtStart: false,\n ownsTreeReset: coverReset.isOwned,\n onFullyHydrated: () => {\n coverReset.cover();\n return onCovered?.();\n },\n };\n}\n\nfunction waitForActiveRemoteHydration(\n input: RemoteHydrationRequestInput,\n): Promise<void> | null {\n const { state } = input;\n const activeHydration = state.remoteHydrationPromise;\n if (!activeHydration) {\n return null;\n }\n const requestLifecycleGeneration = state.lifecycleGeneration;\n const requestStructuralGeneration = state.structuralGeneration;\n const needsCurrentGenerationHydration =\n state.remoteHydrationGeneration !== state.lifecycleGeneration ||\n state.remoteHydrationStructuralGeneration !== state.structuralGeneration;\n // A restoration owns its sweep callback and its sync scheduling policy.\n // Let it list after prior work settles so its durable claim can complete.\n const needsOwnCrawl =\n !!(input.onFullyHydrated || input.recreateOnFullyHydratedAfterReset) &&\n !!input.resetAllLaneWatermarks &&\n !!input.followDiscoveredParentLanes;\n if (\n !needsOwnCrawl &&\n input.resetAllLaneWatermarks &&\n input.followDiscoveredParentLanes\n ) {\n input = { ...input, ownsTreeReset: queueTreeReset(state) };\n }\n const requestQueuedHydration = () => {\n if (\n !isRequestGenerationCurrent({\n lifecycleGeneration: requestLifecycleGeneration,\n state,\n structuralGeneration: requestStructuralGeneration,\n })\n ) {\n return retryRemoteHydrationAfterReset(input);\n }\n // Another request's crawl may have taken over this request's queued\n // lanes. Settle with that crawl rather than at once, so the request never\n // resolves before the listing that covers it.\n return needsOwnCrawl ||\n needsCurrentGenerationHydration ||\n state.containerParentIdsNeedingHydration.size > 0\n ? requestContainerContentsRemoteHydration(input)\n : (state.remoteHydrationPromise ?? undefined);\n };\n return activeHydration.then(\n requestQueuedHydration,\n (error: unknown) => requestQueuedHydration() ?? Promise.reject(error),\n );\n}\n\nfunction waitForActiveInitialization(\n input: RemoteHydrationRequestInput,\n): Promise<void> | null {\n const { state } = input;\n const activeInitialization = state.initializePromise;\n if (!activeInitialization) {\n return null;\n }\n const requestLifecycleGeneration = state.lifecycleGeneration;\n const requestStructuralGeneration = state.structuralGeneration;\n return activeInitialization.then(() => {\n const recoveryInput = isRequestGenerationCurrent({\n lifecycleGeneration: requestLifecycleGeneration,\n state,\n structuralGeneration: requestStructuralGeneration,\n })\n ? input\n : createResetRecoveryInput(input);\n return resumeRetainedRecoveryHydration(recoveryInput);\n });\n}\n\nfunction retryRemoteHydrationAfterReset(\n input: RemoteHydrationRequestInput,\n): Promise<void> {\n // The reconnect state machine owns its retry across a reset.\n if (input.reconnect) {\n // A superseded crawl still owes the manual refresh whose reset it consumed.\n // Complete that request under the live store's own generation guard.\n if (\n !input.ownsTreeReset?.() ||\n input.state.runtime.liveHydrationStatus?.() === \"retired\"\n )\n return Promise.resolve();\n input = { ...input, reconnect: undefined };\n }\n return resumeRetainedRecoveryHydration(createResetRecoveryInput(input));\n}\n\nfunction retainResetRecoveryHydration(\n input: RemoteHydrationRequestInput,\n): void {\n queueRecoveryHydrationRequest(createResetRecoveryInput(input));\n}\n\nexport function resumeContainerContentsRecoveryHydration(\n state: RemoteHydrationRequestState,\n): Promise<void> | null {\n const recovery =\n recoveryHydrationByState.get(state) ?? IDLE_RECOVERY_HYDRATION;\n if (recovery.status === \"idle\") return null;\n // Another caller already took this caller's queued request over.\n if (recovery.status === \"running\") return recovery.run;\n const inputs = recovery.requests.map((request) =>\n isRequestGenerationCurrent({\n lifecycleGeneration: request.lifecycleGeneration,\n state,\n structuralGeneration: request.structuralGeneration,\n })\n ? request.input\n : createResetRecoveryInput(request.input),\n );\n let resolveRun: () => void = () => undefined;\n let rejectRun: (error: unknown) => void = () => undefined;\n const run = new Promise<void>((resolve, reject) => {\n resolveRun = resolve;\n rejectRun = reject;\n });\n // The run is current before its requests start, so a request one of them\n // queues meanwhile waits for the next resume instead of being dropped.\n dispatchRecoveryHydration(state, { run, type: \"started\" });\n const settle = () =>\n dispatchRecoveryHydration(state, { run, type: \"settled\" });\n run.then(settle, settle);\n const fail = (error: unknown) => {\n for (const input of inputs) {\n queueRecoveryHydrationRequest(input);\n }\n rejectRun(error);\n };\n try {\n Promise.all(inputs.map(requestContainerContentsRemoteHydration)).then(\n () => resolveRun(),\n fail,\n );\n } catch (error) {\n fail(error);\n }\n return run;\n}\n\nfunction queueRequestedParentIds(input: RemoteHydrationRequestInput): void {\n if (!input.parentIds) {\n return;\n }\n for (const parentId of input.parentIds) {\n input.state.containerParentIdsNeedingHydration.add(parentId);\n }\n}\n\nfunction waitForRemoteHydrationReadiness(\n input: RemoteHydrationRequestInput,\n): Promise<void> | null {\n const activeHydration = waitForActiveRemoteHydration(input);\n if (activeHydration) {\n return activeHydration;\n }\n const activeInitialization = waitForActiveInitialization(input);\n if (activeInitialization) {\n return activeInitialization;\n }\n if (!hasRemoteHydrationPrerequisites(input.state)) {\n queueRecoveryHydrationRequest(input);\n return Promise.resolve();\n }\n return null;\n}\n\nfunction consumeQueuedHydrationScope(\n state: RemoteHydrationRequestState,\n followDiscoveredParentLanesOption: boolean | undefined,\n): {\n followDiscoveredParentLanes: boolean;\n parentIds: ReadonlyArray<string | null> | undefined;\n} {\n const queuedParentIds = Array.from(state.containerParentIdsNeedingHydration);\n const followDiscoveredParentLanes =\n followDiscoveredParentLanesOption ?? queuedParentIds.length === 0;\n state.containerParentIdsNeedingHydration.clear();\n return {\n followDiscoveredParentLanes,\n parentIds:\n followDiscoveredParentLanes || queuedParentIds.length === 0\n ? undefined\n : queuedParentIds,\n };\n}\n\nfunction ownsHydrationRequest(input: RemoteHydrationRequestInput): boolean {\n return (\n ownsContainerStore(input.state) &&\n input.ownsTreeReset?.() !== false &&\n input.reconnect?.isCurrent() !== false\n );\n}\n\nfunction captureHydrationScope(\n input: RemoteHydrationRequestInput,\n): () => boolean {\n const { state } = input;\n const { lifecycleGeneration, structuralGeneration } = state;\n return () =>\n ownsHydrationRequest(input) &&\n isRequestGenerationCurrent({\n state,\n lifecycleGeneration,\n structuralGeneration,\n });\n}\n\nfunction bindManualTreeReset(\n input: RemoteHydrationRequestInput,\n): RemoteHydrationRequestInput {\n if (\n !input.resetAllLaneWatermarks ||\n input.ownsTreeReset ||\n input.onFullyHydrated ||\n input.recreateOnFullyHydratedAfterReset\n )\n return input;\n return { ...input, ownsTreeReset: captureTreeResetOwner(input.state) };\n}\n\nexport function requestContainerContentsRemoteHydration(\n input: RemoteHydrationRequestInput,\n): Promise<void> {\n input = bindManualTreeReset(input);\n if (!ownsHydrationRequest(input)) return Promise.resolve();\n queueRequestedParentIds(input);\n const readinessBarrier = waitForRemoteHydrationReadiness(input);\n const request = readinessBarrier ?? startHydration(prepareTreeReset(input));\n input.state.trackHydration?.(request);\n return request;\n}\n\nfunction startHydration(input: RemoteHydrationRequestInput): Promise<void> {\n const { host, scheduleSync, state } = input;\n const { followDiscoveredParentLanes, parentIds } =\n consumeQueuedHydrationScope(state, input.followDiscoveredParentLanes);\n\n let appliedRemoteContainerChange = false;\n let retainInterruptedHydration = false;\n const { lifecycleGeneration, structuralGeneration } = state;\n const isCurrent = captureHydrationScope(input);\n const onFullyHydrated = input.recreateOnFullyHydratedAtStart\n ? input.recreateOnFullyHydratedAfterReset?.()\n : input.onFullyHydrated;\n const hydrationHost = createGenerationGuardedHydrationHost({\n host,\n isCurrent,\n });\n const rootLaneHydratedBeforeRequest = state.rootLaneHydrated;\n state.remoteHydrationGeneration = lifecycleGeneration;\n state.remoteHydrationStructuralGeneration = structuralGeneration;\n const hydrationPromise = refreshLocalContainerStates({\n host: hydrationHost,\n stillCurrent: input.reconnect?.isCurrent,\n state,\n })\n .then(() => {\n if (!isCurrent()) {\n return 0;\n }\n return hydrateRemoteContainers({\n followDiscoveredParentLanes,\n host: hydrationHost,\n isCurrent,\n onFullyHydrated,\n reconnect: input.reconnect,\n parentIds,\n resetAllLaneWatermarks: input.resetAllLaneWatermarks,\n resetRootLaneWatermark: input.resetRootLaneWatermark,\n state,\n });\n })\n .then((changedCount) => {\n appliedRemoteContainerChange = changedCount > 0;\n if (isCurrent() && !hasRemoteHydrationPrerequisites(state)) {\n retainInterruptedHydration = true;\n }\n })\n .catch((error: unknown) => {\n if (isCurrent() && isDatabaseUnavailableError(error)) {\n retainInterruptedHydration = true;\n return;\n }\n if (!isCurrent() || error instanceof StaleRemoteHydrationError) {\n return;\n }\n\n throw error;\n })\n .finally(() => {\n const shouldRetryAfterReset = !isCurrent();\n if (state.remoteHydrationPromise === hydrationPromise) {\n state.remoteHydrationPromise = null;\n state.remoteHydrationGeneration = null;\n state.remoteHydrationStructuralGeneration = null;\n }\n\n if (\n isCurrent() &&\n (((input.scheduleSyncOnHydrationChange ?? true) &&\n (appliedRemoteContainerChange ||\n (!rootLaneHydratedBeforeRequest && state.rootLaneHydrated))) ||\n input.scheduleSyncAfterHydration) &&\n state.snapshot.ready &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online\n ) {\n scheduleSync();\n }\n if (shouldRetryAfterReset) {\n return retryRemoteHydrationAfterReset(input);\n }\n if (retainInterruptedHydration) {\n retainResetRecoveryHydration(input);\n }\n return undefined;\n });\n state.remoteHydrationPromise = hydrationPromise;\n return hydrationPromise;\n}\n"]}
@@ -0,0 +1,35 @@
1
+ import { ownsContainerStore } from "../containerState/storeScope.js";
2
+ /** Publish background reads separately from the local snapshot used by writers. */
3
+ export function trackContainerHydration(state) {
4
+ let generation = state.lifecycleGeneration;
5
+ let pending = new Set();
6
+ return (request) => {
7
+ if (generation !== state.lifecycleGeneration) {
8
+ generation = state.lifecycleGeneration;
9
+ pending = new Set();
10
+ }
11
+ if (pending.has(request))
12
+ return;
13
+ pending.add(request);
14
+ const requests = pending;
15
+ const owner = generation;
16
+ const finish = () => {
17
+ requests.delete(request);
18
+ if (requests.size > 0 ||
19
+ state.lifecycleGeneration !== owner ||
20
+ !ownsContainerStore(state))
21
+ return;
22
+ const { hydrating: _finished, ...snapshot } = state.snapshot;
23
+ state.snapshot = snapshot;
24
+ for (const notify of state.listeners)
25
+ notify();
26
+ };
27
+ void request.then(finish, finish);
28
+ if (!state.snapshot.hydrating) {
29
+ state.snapshot = { ...state.snapshot, hydrating: true };
30
+ for (const notify of state.listeners)
31
+ notify();
32
+ }
33
+ };
34
+ }
35
+ //# sourceMappingURL=trackContainerHydration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trackContainerHydration.js","sourceRoot":"","sources":["trackContainerHydration.ts"],"names":[],"mappings":"AAAA,OAAO,EAA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I,EAAE,CAAC;YACxD,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,SAAS;gBAAE,MAAM,EAAE,CAAC;QACjD,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { ownsContainerStore } from \"../containerState/storeScope\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\n/** Publish background reads separately from the local snapshot used by writers. */\nexport function trackContainerHydration(state: ContainerContentsStoreState) {\n let generation = state.lifecycleGeneration;\n let pending = new Set<Promise<unknown>>();\n return (request: Promise<unknown>) => {\n if (generation !== state.lifecycleGeneration) {\n generation = state.lifecycleGeneration;\n pending = new Set();\n }\n if (pending.has(request)) return;\n pending.add(request);\n const requests = pending;\n const owner = generation;\n const finish = () => {\n requests.delete(request);\n if (\n requests.size > 0 ||\n state.lifecycleGeneration !== owner ||\n !ownsContainerStore(state)\n )\n return;\n const { hydrating: _finished, ...snapshot } = state.snapshot;\n state.snapshot = snapshot;\n for (const notify of state.listeners) notify();\n };\n void request.then(finish, finish);\n if (!state.snapshot.hydrating) {\n state.snapshot = { ...state.snapshot, hydrating: true };\n for (const notify of state.listeners) notify();\n }\n };\n}\n"]}
@@ -3,6 +3,7 @@ import { didRegainSyncPrerequisites } from "../../workflows/container-contents/s
3
3
  import { ContainerStateMap } from "./containerState/containerStateMap.js";
4
4
  import { observeContainerBackgroundHydration } from "./hydration/backgroundHydration.js";
5
5
  import { ReconnectRefresh } from "./hydration/reconnectRefresh.js";
6
+ import { trackContainerHydration } from "./hydration/trackContainerHydration.js";
6
7
  import { didContainerWriteRuntimeChange } from "./remoteWrites/writeGeneration.js";
7
8
  import { getSnapshotNodes } from "./utils.js";
8
9
  function areSyncStatesEqual(left, right) {
@@ -50,7 +51,7 @@ function didStructuralRuntimeChange(previousRuntime, nextRuntime) {
50
51
  // issue an identical listing while the retired tree is waiting on the API.
51
52
  let storeSequence = 0;
52
53
  export function createContainerContentsStoreState(initialRuntime, persistence, logLabel) {
53
- return {
54
+ const state = {
54
55
  parentLaneRequestPrefix: `s${++storeSequence}`,
55
56
  containerListingFailures: 0,
56
57
  containersById: new ContainerStateMap(),
@@ -91,6 +92,8 @@ export function createContainerContentsStoreState(initialRuntime, persistence, l
91
92
  writeGeneration: 0,
92
93
  writeChain: Promise.resolve(null),
93
94
  };
95
+ state.trackHydration = trackContainerHydration(state);
96
+ return state;
94
97
  }
95
98
  function emitContainerContentsStore(state) {
96
99
  for (const listener of state.listeners) {
@@ -98,7 +101,8 @@ function emitContainerContentsStore(state) {
98
101
  }
99
102
  }
100
103
  function setContainerContentsSnapshot(state, next) {
101
- if (next.ready === state.snapshot.ready &&
104
+ if (next.hydrating === state.snapshot.hydrating &&
105
+ next.ready === state.snapshot.ready &&
102
106
  areSnapshotNodesEqual(next.nodes, state.snapshot.nodes)) {
103
107
  return;
104
108
  }
@@ -107,6 +111,7 @@ function setContainerContentsSnapshot(state, next) {
107
111
  }
108
112
  export function updateContainerContentsSnapshot(state) {
109
113
  setContainerContentsSnapshot(state, {
114
+ ...state.snapshot,
110
115
  nodes: getSnapshotNodes(state.containersById),
111
116
  ready: true,
112
117
  });
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAWhF,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE3C,SAAS,kBAAkB,CACzB,IAAgC,EAChC,KAAiC;IAEjC,OAAO,CACL,IAAI,CAAC,SAAS,KAAK,KAA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,KAAK,CAAC,gBAAgB,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAC/C,KAAK,CAAC,WAAW,GAAG,eAAe,CAAC;IACpC,KAAK,CAAC,oBAAoB,IAAI,CAAC,CAAC;IAChC,KAAK,CAAC,eAAe,IAAI,CAAC,CAAC;IAC3B,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,2BAA2B,CAAC,KAAK,CAAC,CAAC;IACnC,SAAS,CAAC,iBAAiB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport {\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"../../workflows/container-contents/projectionKeys\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport { ContainerStateMap } from \"./containerState/containerStateMap\";\nimport { observeContainerBackgroundHydration } from \"./hydration/backgroundHydration\";\nimport { ReconnectRefresh } from \"./hydration/reconnectRefresh\";\nimport { didContainerWriteRuntimeChange } from \"./remoteWrites/writeGeneration\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n} from \"./syncAgent/syncAgentTypes\";\nimport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreState,\n ContainerNode,\n} from \"./types\";\nimport { getSnapshotNodes } from \"./utils\";\n\nfunction areSyncStatesEqual(\n left: ContainerNode[\"syncState\"],\n right: ContainerNode[\"syncState\"],\n): boolean {\n return (\n left.lastError === right.lastError &&\n left.pendingAttachmentBytes === right.pendingAttachmentBytes &&\n left.pendingAttachmentCount === right.pendingAttachmentCount &&\n left.pendingUpdateCount === right.pendingUpdateCount &&\n left.status === right.status\n );\n}\n\nfunction areSnapshotNodesEqual(\n left: ReadonlyArray<ContainerNode>,\n right: ReadonlyArray<ContainerNode>,\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n return left.every((leftNode, index) => {\n const rightNode = right[index];\n return (\n rightNode !== undefined &&\n leftNode.createdAt === rightNode.createdAt &&\n leftNode.effectiveAccessLevel === rightNode.effectiveAccessLevel &&\n leftNode.id === rightNode.id &&\n leftNode.icon === rightNode.icon &&\n leftNode.kind === rightNode.kind &&\n leftNode.metadataDocumentId === rightNode.metadataDocumentId &&\n leftNode.metadataReady === rightNode.metadataReady &&\n leftNode.name === rightNode.name &&\n leftNode.organizationId === rightNode.organizationId &&\n leftNode.parentId === rightNode.parentId &&\n leftNode.primaryDocumentId === rightNode.primaryDocumentId &&\n areSyncStatesEqual(leftNode.syncState, rightNode.syncState) &&\n leftNode.systemSlot === rightNode.systemSlot &&\n leftNode.updatedAt === rightNode.updatedAt\n );\n });\n}\n\nfunction didStructuralRuntimeChange(\n previousRuntime: ContainerContentsStoreRuntime,\n nextRuntime: ContainerContentsStoreRuntime,\n): boolean {\n // Structural sync also depends on connectivity and event delivery. Local\n // writes use only the identity and storage checks shared below.\n return (\n didContainerWriteRuntimeChange(previousRuntime, nextRuntime) ||\n previousRuntime.state.online !== nextRuntime.state.online ||\n previousRuntime.state.peerScope !== nextRuntime.state.peerScope ||\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration ||\n previousRuntime.util.isRemoteSyncBlocked !==\n nextRuntime.util.isRemoteSyncBlocked\n );\n}\n\n// Request correlation is scoped to the store instance. A reopened tree can\n// issue an identical listing while the retired tree is waiting on the API.\nlet storeSequence = 0;\n\nexport function createContainerContentsStoreState(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence,\n logLabel?: string | undefined,\n): ContainerContentsStoreState {\n return {\n parentLaneRequestPrefix: `s${++storeSequence}`,\n containerListingFailures: 0,\n containersById: new ContainerStateMap(),\n containerParentIdsNeedingHydration: new Set(),\n documentStoresNeedPriming: true,\n initializeGeneration: null,\n initializePromise: null,\n initialized: false,\n localContainerRefreshPromise: null,\n localContainerRefreshGeneration: null,\n localContainerRefreshStructuralGeneration: null,\n localContainersNeedRefresh: false,\n lifecycleGeneration: 0,\n lastEventCount: 0,\n listeners: new Set(),\n locallyAcceptedMetadataUpdateIds: new Set(),\n logLabel,\n metadataDocumentIdsNeedingSync: new Set(),\n metadataSyncSignalSeqById: new Map(),\n owedMetadataReadsRestored: false,\n persistence,\n plannedMetadataDocumentIds: new Set(),\n remoteHydrationPromise: null,\n remoteHydrationGeneration: null,\n remoteHydrationStructuralGeneration: null,\n // A store opened after the socket's interest was acknowledged missed that\n // acknowledgement's re-list, which is how hints lost earlier are recovered.\n reconnectRefresh: new ReconnectRefresh(\n (initialRuntime.state.serverEventsConnectionGeneration ?? 0) > 0,\n ),\n resolveProjectionUserKey:\n createContainerContentsProjectionUserKeyResolver(initialRuntime),\n rootLaneHydrated: false,\n runtime: initialRuntime,\n snapshot: {\n nodes: [],\n ready: false,\n },\n syncLane: null,\n structuralGeneration: 0,\n writeGeneration: 0,\n writeChain: Promise.resolve<ContainerNode | null>(null),\n };\n}\n\nfunction emitContainerContentsStore(state: ContainerContentsStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nfunction setContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n next: ContainerContentsSnapshot,\n) {\n if (\n next.ready === state.snapshot.ready &&\n areSnapshotNodesEqual(next.nodes, state.snapshot.nodes)\n ) {\n return;\n }\n\n state.snapshot = next;\n emitContainerContentsStore(state);\n}\n\nexport function updateContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n) {\n setContainerContentsSnapshot(state, {\n nodes: getSnapshotNodes(state.containersById),\n ready: true,\n });\n}\n\nfunction resetContainerContentsStore(state: ContainerContentsStoreState) {\n state.lifecycleGeneration += 1;\n state.containersById = new ContainerStateMap();\n state.containerParentIdsNeedingHydration = new Set();\n state.documentStoresNeedPriming = true;\n state.initialized = false;\n state.localContainersNeedRefresh = false;\n // Runtime events are snapshots, not a destructive queue. A replacement\n // executor or persistence adapter has not observed any of them, even when\n // their effects were already applied to the previous database. Replay the\n // snapshot after replacement initialization rebuilds metadata identities.\n state.lastEventCount = 0;\n // Accepted-echo suppression state must not survive a reset: after a\n // database loss the tree rehydrates from remote, and a retained id would\n // suppress the next matching remote update signal. Mirrors\n // clearDocumentStoreState in the document store lane.\n state.locallyAcceptedMetadataUpdateIds = new Set();\n state.metadataDocumentIdsNeedingSync = new Set();\n state.metadataSyncSignalSeqById = new Map();\n state.owedMetadataReadsRestored = false;\n state.plannedMetadataDocumentIds = new Set();\n state.rootLaneHydrated = false;\n state.writeChain = Promise.resolve<ContainerNode | null>(null);\n setContainerContentsSnapshot(state, {\n nodes: [],\n ready: false,\n });\n}\n\nexport function subscribeToContainerContentsStore(\n state: ContainerContentsStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nfunction hasContainerContentsLoadState(\n state: ContainerContentsStoreState,\n): boolean {\n return Boolean(\n state.snapshot.ready || state.initialized || state.initializePromise,\n );\n}\n\nexport function updateContainerContentsStoreRuntime(\n state: ContainerContentsStoreState,\n nextRuntime: ContainerContentsStoreRuntime,\n syncAgent: ContainerContentsStoreSyncAgent,\n) {\n const previousRuntime = state.runtime;\n const runtimeReplaced = didStructuralRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (didContainerWriteRuntimeChange(previousRuntime, nextRuntime)) {\n state.writeGeneration += 1;\n }\n const executorReplaced =\n previousRuntime.infra.execSql !== nextRuntime.infra.execSql;\n const serverEventsConnectionChanged =\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration;\n if (runtimeReplaced) {\n state.reconnectRefresh.reset(\"runtimeChanged\");\n state.structuralGeneration += 1;\n state.localContainersNeedRefresh = true;\n }\n const contextChanged =\n previousRuntime.auth.organizationId !== nextRuntime.auth.organizationId ||\n previousRuntime.state.containerId !== nextRuntime.state.containerId;\n if (\n didContainerContentsProjectionKeyRuntimeChange(previousRuntime, nextRuntime)\n ) {\n state.resolveProjectionUserKey =\n createContainerContentsProjectionUserKeyResolver(nextRuntime);\n }\n state.runtime = nextRuntime;\n if (serverEventsConnectionChanged) {\n state.reconnectRefresh.reset(\"acknowledged\");\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (hasContainerContentsLoadState(state)) {\n resetContainerContentsStore(state);\n }\n return;\n }\n\n if (executorReplaced) {\n // The in-memory tree and lane markers belong to the previous executor.\n // Rebuild them from the replacement database before any remote sync can\n // observe or persist the old database's state.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n syncAgent.handleRemoteEvents();\n return;\n }\n\n // The signing fingerprint owns the locally loaded tree. When this scope\n // gains authentication, keep the tree available while reconciling it.\n if (\n state.snapshot.ready &&\n (contextChanged || didRegainSyncPrerequisites(previousRuntime, nextRuntime))\n ) {\n state.localContainersNeedRefresh = true;\n state.documentStoresNeedPriming = true;\n void syncAgent.refreshLocalContainers();\n // The refresh alone does not run the sync lane; schedule it so newly\n // eligible documents (e.g. this organization's orphans) prime now.\n syncAgent.scheduleSync();\n }\n\n syncAgent.ensureInitialized();\n\n syncAgent.handleRemoteEvents();\n\n if (runtimeReplaced) {\n void syncAgent.refreshLocalContainers();\n syncAgent.scheduleSync();\n }\n\n consumePendingContainerContentsReconnectRefresh(state, syncAgent.refresh);\n\n if (\n state.snapshot.ready &&\n didRegainSyncPrerequisites(previousRuntime, nextRuntime)\n ) {\n // A pass blocked by missing prerequisites consumes its lane request before\n // returning early. Re-arm it directly when they return even if hydration\n // finds no remote delta; this also primes unopened document stores.\n syncAgent.scheduleSync();\n syncAgent.scheduleRemoteHydration();\n }\n}\n\nexport function retireContainerStore(\n state: ContainerContentsStoreSyncState,\n): void {\n state.lifecycleGeneration++;\n state.reconnectRefresh.reset(\"disposed\");\n}\n\nexport function consumePendingContainerContentsReconnectRefresh(\n state: ContainerContentsStoreSyncState,\n refresh: ContainerContentsStoreSyncAgent[\"refresh\"],\n): void {\n state.reconnectRefresh.runWhenReady(\n () =>\n state.snapshot.ready &&\n state.initialized &&\n state.runtime.infra.dbStatus === \"ready\" &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online &&\n (state.runtime.liveHydrationStatus?.() ?? \"ready\") === \"ready\" &&\n state.runtime.isAcknowledgementCurrent?.() !== false &&\n !state.syncLane?.isDisposed?.(),\n (options) => {\n const hydration = refresh(options);\n observeContainerBackgroundHydration(state, hydration);\n return hydration;\n },\n );\n}\n\nexport function updateContainerContentsStorePersistence(\n state: ContainerContentsStoreState,\n nextPersistence: ContainerContentsPersistence,\n syncAgent: ContainerContentsStoreSyncAgent,\n): void {\n if (state.persistence === nextPersistence) {\n return;\n }\n state.reconnectRefresh.reset(\"runtimeChanged\");\n state.persistence = nextPersistence;\n state.structuralGeneration += 1;\n state.writeGeneration += 1;\n // Persistence replacement changes the authoritative local data source even\n // when the SQLite executor itself is stable. Clear storage-backed state and\n // let initialization load the replacement before scheduling remote work.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["state.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,6CAA6C,CAAC;AACzF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,8BAA8B,EAAE,MAAM,gCAAgC,CAAC;AAWhF,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE3C,SAAS,kBAAkB,CACzB,IAAgC,EAChC,KAAiC;IAEjC,OAAO,CACL,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;QAClC,IAAI,CAAC,sBAAsB,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C;AAED,MAAM,UAAU,uCAAuC,CACrD,KAAkC,EAClC,eAA6C,EAC7C,SAA0C;IAE1C,IAAI,KAAK,CAAC,WAAW,KAAK,eAAe,EAAE,CAAC;QAC1C,OAAO;IACT,CAAC;IACD,KAAK,CAAC,gBAAgB,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAC/C,KAAK,CAAC,WAAW,GAAG,eAAe,CAAC;IACpC,KAAK,CAAC,oBAAoB,IAAI,CAAC,CAAC;IAChC,KAAK,CAAC,eAAe,IAAI,CAAC,CAAC;IAC3B,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,2BAA2B,CAAC,KAAK,CAAC,CAAC;IACnC,SAAS,CAAC,iBAAiB,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport {\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"../../workflows/container-contents/projectionKeys\";\nimport { didRegainSyncPrerequisites } from \"../../workflows/container-contents/syncLane\";\nimport { ContainerStateMap } from \"./containerState/containerStateMap\";\nimport { observeContainerBackgroundHydration } from \"./hydration/backgroundHydration\";\nimport { ReconnectRefresh } from \"./hydration/reconnectRefresh\";\nimport { trackContainerHydration } from \"./hydration/trackContainerHydration\";\nimport { didContainerWriteRuntimeChange } from \"./remoteWrites/writeGeneration\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n} from \"./syncAgent/syncAgentTypes\";\nimport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreState,\n ContainerNode,\n} from \"./types\";\nimport { getSnapshotNodes } from \"./utils\";\n\nfunction areSyncStatesEqual(\n left: ContainerNode[\"syncState\"],\n right: ContainerNode[\"syncState\"],\n): boolean {\n return (\n left.lastError === right.lastError &&\n left.pendingAttachmentBytes === right.pendingAttachmentBytes &&\n left.pendingAttachmentCount === right.pendingAttachmentCount &&\n left.pendingUpdateCount === right.pendingUpdateCount &&\n left.status === right.status\n );\n}\n\nfunction areSnapshotNodesEqual(\n left: ReadonlyArray<ContainerNode>,\n right: ReadonlyArray<ContainerNode>,\n): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n return left.every((leftNode, index) => {\n const rightNode = right[index];\n return (\n rightNode !== undefined &&\n leftNode.createdAt === rightNode.createdAt &&\n leftNode.effectiveAccessLevel === rightNode.effectiveAccessLevel &&\n leftNode.id === rightNode.id &&\n leftNode.icon === rightNode.icon &&\n leftNode.kind === rightNode.kind &&\n leftNode.metadataDocumentId === rightNode.metadataDocumentId &&\n leftNode.metadataReady === rightNode.metadataReady &&\n leftNode.name === rightNode.name &&\n leftNode.organizationId === rightNode.organizationId &&\n leftNode.parentId === rightNode.parentId &&\n leftNode.primaryDocumentId === rightNode.primaryDocumentId &&\n areSyncStatesEqual(leftNode.syncState, rightNode.syncState) &&\n leftNode.systemSlot === rightNode.systemSlot &&\n leftNode.updatedAt === rightNode.updatedAt\n );\n });\n}\n\nfunction didStructuralRuntimeChange(\n previousRuntime: ContainerContentsStoreRuntime,\n nextRuntime: ContainerContentsStoreRuntime,\n): boolean {\n // Structural sync also depends on connectivity and event delivery. Local\n // writes use only the identity and storage checks shared below.\n return (\n didContainerWriteRuntimeChange(previousRuntime, nextRuntime) ||\n previousRuntime.state.online !== nextRuntime.state.online ||\n previousRuntime.state.peerScope !== nextRuntime.state.peerScope ||\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration ||\n previousRuntime.util.isRemoteSyncBlocked !==\n nextRuntime.util.isRemoteSyncBlocked\n );\n}\n\n// Request correlation is scoped to the store instance. A reopened tree can\n// issue an identical listing while the retired tree is waiting on the API.\nlet storeSequence = 0;\n\nexport function createContainerContentsStoreState(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence,\n logLabel?: string | undefined,\n): ContainerContentsStoreState {\n const state: ContainerContentsStoreState = {\n parentLaneRequestPrefix: `s${++storeSequence}`,\n containerListingFailures: 0,\n containersById: new ContainerStateMap(),\n containerParentIdsNeedingHydration: new Set(),\n documentStoresNeedPriming: true,\n initializeGeneration: null,\n initializePromise: null,\n initialized: false,\n localContainerRefreshPromise: null,\n localContainerRefreshGeneration: null,\n localContainerRefreshStructuralGeneration: null,\n localContainersNeedRefresh: false,\n lifecycleGeneration: 0,\n lastEventCount: 0,\n listeners: new Set(),\n locallyAcceptedMetadataUpdateIds: new Set(),\n logLabel,\n metadataDocumentIdsNeedingSync: new Set(),\n metadataSyncSignalSeqById: new Map(),\n owedMetadataReadsRestored: false,\n persistence,\n plannedMetadataDocumentIds: new Set(),\n remoteHydrationPromise: null,\n remoteHydrationGeneration: null,\n remoteHydrationStructuralGeneration: null,\n // A store opened after the socket's interest was acknowledged missed that\n // acknowledgement's re-list, which is how hints lost earlier are recovered.\n reconnectRefresh: new ReconnectRefresh(\n (initialRuntime.state.serverEventsConnectionGeneration ?? 0) > 0,\n ),\n resolveProjectionUserKey:\n createContainerContentsProjectionUserKeyResolver(initialRuntime),\n rootLaneHydrated: false,\n runtime: initialRuntime,\n snapshot: {\n nodes: [],\n ready: false,\n },\n syncLane: null,\n structuralGeneration: 0,\n writeGeneration: 0,\n writeChain: Promise.resolve<ContainerNode | null>(null),\n };\n state.trackHydration = trackContainerHydration(state);\n return state;\n}\n\nfunction emitContainerContentsStore(state: ContainerContentsStoreState) {\n for (const listener of state.listeners) {\n listener();\n }\n}\n\nfunction setContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n next: ContainerContentsSnapshot,\n) {\n if (\n next.hydrating === state.snapshot.hydrating &&\n next.ready === state.snapshot.ready &&\n areSnapshotNodesEqual(next.nodes, state.snapshot.nodes)\n ) {\n return;\n }\n\n state.snapshot = next;\n emitContainerContentsStore(state);\n}\n\nexport function updateContainerContentsSnapshot(\n state: ContainerContentsStoreState,\n) {\n setContainerContentsSnapshot(state, {\n ...state.snapshot,\n nodes: getSnapshotNodes(state.containersById),\n ready: true,\n });\n}\n\nfunction resetContainerContentsStore(state: ContainerContentsStoreState) {\n state.lifecycleGeneration += 1;\n state.containersById = new ContainerStateMap();\n state.containerParentIdsNeedingHydration = new Set();\n state.documentStoresNeedPriming = true;\n state.initialized = false;\n state.localContainersNeedRefresh = false;\n // Runtime events are snapshots, not a destructive queue. A replacement\n // executor or persistence adapter has not observed any of them, even when\n // their effects were already applied to the previous database. Replay the\n // snapshot after replacement initialization rebuilds metadata identities.\n state.lastEventCount = 0;\n // Accepted-echo suppression state must not survive a reset: after a\n // database loss the tree rehydrates from remote, and a retained id would\n // suppress the next matching remote update signal. Mirrors\n // clearDocumentStoreState in the document store lane.\n state.locallyAcceptedMetadataUpdateIds = new Set();\n state.metadataDocumentIdsNeedingSync = new Set();\n state.metadataSyncSignalSeqById = new Map();\n state.owedMetadataReadsRestored = false;\n state.plannedMetadataDocumentIds = new Set();\n state.rootLaneHydrated = false;\n state.writeChain = Promise.resolve<ContainerNode | null>(null);\n setContainerContentsSnapshot(state, {\n nodes: [],\n ready: false,\n });\n}\n\nexport function subscribeToContainerContentsStore(\n state: ContainerContentsStoreState,\n listener: () => void,\n) {\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n\nfunction hasContainerContentsLoadState(\n state: ContainerContentsStoreState,\n): boolean {\n return Boolean(\n state.snapshot.ready || state.initialized || state.initializePromise,\n );\n}\n\nexport function updateContainerContentsStoreRuntime(\n state: ContainerContentsStoreState,\n nextRuntime: ContainerContentsStoreRuntime,\n syncAgent: ContainerContentsStoreSyncAgent,\n) {\n const previousRuntime = state.runtime;\n const runtimeReplaced = didStructuralRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (didContainerWriteRuntimeChange(previousRuntime, nextRuntime)) {\n state.writeGeneration += 1;\n }\n const executorReplaced =\n previousRuntime.infra.execSql !== nextRuntime.infra.execSql;\n const serverEventsConnectionChanged =\n previousRuntime.state.serverEventsConnectionGeneration !==\n nextRuntime.state.serverEventsConnectionGeneration;\n if (runtimeReplaced) {\n state.reconnectRefresh.reset(\"runtimeChanged\");\n state.structuralGeneration += 1;\n state.localContainersNeedRefresh = true;\n }\n const contextChanged =\n previousRuntime.auth.organizationId !== nextRuntime.auth.organizationId ||\n previousRuntime.state.containerId !== nextRuntime.state.containerId;\n if (\n didContainerContentsProjectionKeyRuntimeChange(previousRuntime, nextRuntime)\n ) {\n state.resolveProjectionUserKey =\n createContainerContentsProjectionUserKeyResolver(nextRuntime);\n }\n state.runtime = nextRuntime;\n if (serverEventsConnectionChanged) {\n state.reconnectRefresh.reset(\"acknowledged\");\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (hasContainerContentsLoadState(state)) {\n resetContainerContentsStore(state);\n }\n return;\n }\n\n if (executorReplaced) {\n // The in-memory tree and lane markers belong to the previous executor.\n // Rebuild them from the replacement database before any remote sync can\n // observe or persist the old database's state.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n syncAgent.handleRemoteEvents();\n return;\n }\n\n // The signing fingerprint owns the locally loaded tree. When this scope\n // gains authentication, keep the tree available while reconciling it.\n if (\n state.snapshot.ready &&\n (contextChanged || didRegainSyncPrerequisites(previousRuntime, nextRuntime))\n ) {\n state.localContainersNeedRefresh = true;\n state.documentStoresNeedPriming = true;\n void syncAgent.refreshLocalContainers();\n // The refresh alone does not run the sync lane; schedule it so newly\n // eligible documents (e.g. this organization's orphans) prime now.\n syncAgent.scheduleSync();\n }\n\n syncAgent.ensureInitialized();\n\n syncAgent.handleRemoteEvents();\n\n if (runtimeReplaced) {\n void syncAgent.refreshLocalContainers();\n syncAgent.scheduleSync();\n }\n\n consumePendingContainerContentsReconnectRefresh(state, syncAgent.refresh);\n\n if (\n state.snapshot.ready &&\n didRegainSyncPrerequisites(previousRuntime, nextRuntime)\n ) {\n // A pass blocked by missing prerequisites consumes its lane request before\n // returning early. Re-arm it directly when they return even if hydration\n // finds no remote delta; this also primes unopened document stores.\n syncAgent.scheduleSync();\n syncAgent.scheduleRemoteHydration();\n }\n}\n\nexport function retireContainerStore(\n state: ContainerContentsStoreSyncState,\n): void {\n state.lifecycleGeneration++;\n state.reconnectRefresh.reset(\"disposed\");\n}\n\nexport function consumePendingContainerContentsReconnectRefresh(\n state: ContainerContentsStoreSyncState,\n refresh: ContainerContentsStoreSyncAgent[\"refresh\"],\n): void {\n state.reconnectRefresh.runWhenReady(\n () =>\n state.snapshot.ready &&\n state.initialized &&\n state.runtime.infra.dbStatus === \"ready\" &&\n state.runtime.auth.isAuthenticated &&\n state.runtime.state.online &&\n (state.runtime.liveHydrationStatus?.() ?? \"ready\") === \"ready\" &&\n state.runtime.isAcknowledgementCurrent?.() !== false &&\n !state.syncLane?.isDisposed?.(),\n (options) => {\n const hydration = refresh(options);\n observeContainerBackgroundHydration(state, hydration);\n return hydration;\n },\n );\n}\n\nexport function updateContainerContentsStorePersistence(\n state: ContainerContentsStoreState,\n nextPersistence: ContainerContentsPersistence,\n syncAgent: ContainerContentsStoreSyncAgent,\n): void {\n if (state.persistence === nextPersistence) {\n return;\n }\n state.reconnectRefresh.reset(\"runtimeChanged\");\n state.persistence = nextPersistence;\n state.structuralGeneration += 1;\n state.writeGeneration += 1;\n // Persistence replacement changes the authoritative local data source even\n // when the SQLite executor itself is stable. Clear storage-backed state and\n // let initialization load the replacement before scheduling remote work.\n resetContainerContentsStore(state);\n syncAgent.ensureInitialized();\n}\n"]}
@@ -29,6 +29,7 @@ export interface ContainerContentsStoreSyncAgent {
29
29
  scheduleSync: () => void;
30
30
  }
31
31
  export interface ContainerContentsStoreSyncState {
32
+ trackHydration?: (request: Promise<unknown>) => void;
32
33
  readonly parentLaneRequestPrefix?: string;
33
34
  /** Container listing requests that failed or timed out in a current crawl. */
34
35
  containerListingFailures: number;
@@ -1 +1 @@
1
- {"version":3,"file":"syncAgentTypes.js","sourceRoot":"","sources":["syncAgentTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerContentsPersistence } from \"../../../workflows/container-contents/containerPersistence\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../../workflows/container-contents/projectionKeys\";\nimport type {\n ContainerState,\n ReconnectCrawl,\n RemoteContainer,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { ContainerContentsStoreWorkflowRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { ContainerContentsSyncLane } from \"../../../workflows/container-contents/syncLane\";\n\nimport type { ReconnectRefresh } from \"../hydration/reconnectRefresh\";\n\nexport type ContainerContentsStoreRuntime =\n ContainerContentsStoreWorkflowRuntime;\n\nexport interface RefreshRootLaneOptions {\n readonly includeActiveRootChildLane?: boolean | undefined;\n // Extra parent lanes to re-list alongside the root lane. Used by the\n // resync_required handler to re-list affected containers' parent lanes so a\n // tombstone only visible there is still applied without the full crawl.\n readonly parentIds?: ReadonlyArray<string | null> | undefined;\n}\n\nexport interface ContainerContentsStoreSyncAgent {\n ensureInitialized: () => void;\n handleRemoteEvents: () => void;\n ingestRemoteContainer: (remoteContainer: RemoteContainer) => Promise<void>;\n primeDocumentsForSharedSubtree: (\n rootContainerId: string,\n isCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n refreshLocalContainers: () => Promise<void>;\n refresh: (options?: {\n reconnect?: ReconnectCrawl | undefined;\n resetAllLaneWatermarks?: boolean;\n }) => Promise<boolean>;\n refreshRootLane: (options?: RefreshRootLaneOptions) => Promise<boolean>;\n requestRemoteHydration: (options?: {\n followDiscoveredParentLanes?: boolean | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n }) => Promise<void>;\n scheduleRemoteHydration: () => void;\n scheduleSync: () => void;\n}\n\nexport interface ContainerContentsStoreSyncState {\n readonly parentLaneRequestPrefix?: string;\n /** Container listing requests that failed or timed out in a current crawl. */\n containerListingFailures: number;\n containersById: Map<string, ContainerState>;\n documentStoresNeedPriming: boolean;\n initializeGeneration: number | null;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n localContainerRefreshPromise: Promise<void> | null;\n localContainerRefreshGeneration: number | null;\n localContainerRefreshStructuralGeneration: number | null;\n localContainersNeedRefresh: boolean;\n /** Invalidates asynchronous hydration work when this store is reset. */\n lifecycleGeneration: number;\n /** Invalidates structural work when its runtime or persistence is replaced. */\n structuralGeneration: number;\n /** Invalidates writes across write-relevant runtime ABA transitions. */\n writeGeneration: number;\n lastEventCount: number;\n /**\n * Update ids this client sent for container metadata documents, registered\n * before the network await of each metadata sync pass. The author's own\n * `document_update_created` echo consumes its ids here instead of arming a\n * redundant forced read-sync; a genuine peer update always carries unknown\n * ids and still forces one. Shared across all metadata docs in the store —\n * update ids are globally unique.\n */\n locallyAcceptedMetadataUpdateIds: Set<string>;\n logLabel?: string | undefined;\n metadataDocumentIdsNeedingSync: Set<string>;\n /**\n * Per-metadata-document enqueue sequence. Bumped for a specific id whenever a\n * remote event re-queues it in {@link metadataDocumentIdsNeedingSync}. A sync\n * pass snapshots the id's sequence before its GET and only clears the id if it\n * is unchanged at pass end, so a mid-pass re-queue of THIS container is not\n * erased. Keyed per id (not a single global counter) so a remote event for an\n * unrelated container does not force a redundant re-sync of this one. See\n * `clearMetadataSyncQueueIfUnchanged`.\n */\n metadataSyncSignalSeqById: Map<string, number>;\n /**\n * Whether this store's first sync pass has requeued the metadata reads a\n * previous run still owed (`container_metadata_revalidations`). Reset with\n * the store, so a replacement database is restored on its own first pass.\n */\n owedMetadataReadsRestored: boolean;\n /**\n * Metadata document ids of folder creates in flight. A remote hint for one\n * queues the folder's first read before the create response installs the id.\n */\n plannedMetadataDocumentIds: Set<string>;\n containerParentIdsNeedingHydration: Set<string | null>;\n persistence: ContainerContentsPersistence;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationGeneration: number | null;\n remoteHydrationStructuralGeneration: number | null;\n reconnectRefresh: ReconnectRefresh;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n /** True after this store has fully applied an authoritative root lane. */\n rootLaneHydrated: boolean;\n runtime: ContainerContentsStoreRuntime;\n snapshot: { ready: boolean };\n syncLane: ContainerContentsSyncLane | null;\n}\n"]}
1
+ {"version":3,"file":"syncAgentTypes.js","sourceRoot":"","sources":["syncAgentTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerContentsPersistence } from \"../../../workflows/container-contents/containerPersistence\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../../workflows/container-contents/projectionKeys\";\nimport type {\n ContainerState,\n ReconnectCrawl,\n RemoteContainer,\n} from \"../../../workflows/container-contents/remoteHydration\";\nimport type { ContainerContentsStoreWorkflowRuntime } from \"../../../workflows/container-contents/runtime\";\nimport type { ContainerContentsSyncLane } from \"../../../workflows/container-contents/syncLane\";\n\nimport type { ReconnectRefresh } from \"../hydration/reconnectRefresh\";\n\nexport type ContainerContentsStoreRuntime =\n ContainerContentsStoreWorkflowRuntime;\n\nexport interface RefreshRootLaneOptions {\n readonly includeActiveRootChildLane?: boolean | undefined;\n // Extra parent lanes to re-list alongside the root lane. Used by the\n // resync_required handler to re-list affected containers' parent lanes so a\n // tombstone only visible there is still applied without the full crawl.\n readonly parentIds?: ReadonlyArray<string | null> | undefined;\n}\n\nexport interface ContainerContentsStoreSyncAgent {\n ensureInitialized: () => void;\n handleRemoteEvents: () => void;\n ingestRemoteContainer: (remoteContainer: RemoteContainer) => Promise<void>;\n primeDocumentsForSharedSubtree: (\n rootContainerId: string,\n isCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n refreshLocalContainers: () => Promise<void>;\n refresh: (options?: {\n reconnect?: ReconnectCrawl | undefined;\n resetAllLaneWatermarks?: boolean;\n }) => Promise<boolean>;\n refreshRootLane: (options?: RefreshRootLaneOptions) => Promise<boolean>;\n requestRemoteHydration: (options?: {\n followDiscoveredParentLanes?: boolean | undefined;\n parentIds?: ReadonlyArray<string | null> | undefined;\n resetAllLaneWatermarks?: boolean | undefined;\n }) => Promise<void>;\n scheduleRemoteHydration: () => void;\n scheduleSync: () => void;\n}\n\nexport interface ContainerContentsStoreSyncState {\n trackHydration?: (request: Promise<unknown>) => void;\n readonly parentLaneRequestPrefix?: string;\n /** Container listing requests that failed or timed out in a current crawl. */\n containerListingFailures: number;\n containersById: Map<string, ContainerState>;\n documentStoresNeedPriming: boolean;\n initializeGeneration: number | null;\n initializePromise: Promise<void> | null;\n initialized: boolean;\n localContainerRefreshPromise: Promise<void> | null;\n localContainerRefreshGeneration: number | null;\n localContainerRefreshStructuralGeneration: number | null;\n localContainersNeedRefresh: boolean;\n /** Invalidates asynchronous hydration work when this store is reset. */\n lifecycleGeneration: number;\n /** Invalidates structural work when its runtime or persistence is replaced. */\n structuralGeneration: number;\n /** Invalidates writes across write-relevant runtime ABA transitions. */\n writeGeneration: number;\n lastEventCount: number;\n /**\n * Update ids this client sent for container metadata documents, registered\n * before the network await of each metadata sync pass. The author's own\n * `document_update_created` echo consumes its ids here instead of arming a\n * redundant forced read-sync; a genuine peer update always carries unknown\n * ids and still forces one. Shared across all metadata docs in the store —\n * update ids are globally unique.\n */\n locallyAcceptedMetadataUpdateIds: Set<string>;\n logLabel?: string | undefined;\n metadataDocumentIdsNeedingSync: Set<string>;\n /**\n * Per-metadata-document enqueue sequence. Bumped for a specific id whenever a\n * remote event re-queues it in {@link metadataDocumentIdsNeedingSync}. A sync\n * pass snapshots the id's sequence before its GET and only clears the id if it\n * is unchanged at pass end, so a mid-pass re-queue of THIS container is not\n * erased. Keyed per id (not a single global counter) so a remote event for an\n * unrelated container does not force a redundant re-sync of this one. See\n * `clearMetadataSyncQueueIfUnchanged`.\n */\n metadataSyncSignalSeqById: Map<string, number>;\n /**\n * Whether this store's first sync pass has requeued the metadata reads a\n * previous run still owed (`container_metadata_revalidations`). Reset with\n * the store, so a replacement database is restored on its own first pass.\n */\n owedMetadataReadsRestored: boolean;\n /**\n * Metadata document ids of folder creates in flight. A remote hint for one\n * queues the folder's first read before the create response installs the id.\n */\n plannedMetadataDocumentIds: Set<string>;\n containerParentIdsNeedingHydration: Set<string | null>;\n persistence: ContainerContentsPersistence;\n remoteHydrationPromise: Promise<void> | null;\n remoteHydrationGeneration: number | null;\n remoteHydrationStructuralGeneration: number | null;\n reconnectRefresh: ReconnectRefresh;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n /** True after this store has fully applied an authoritative root lane. */\n rootLaneHydrated: boolean;\n runtime: ContainerContentsStoreRuntime;\n snapshot: { ready: boolean };\n syncLane: ContainerContentsSyncLane | null;\n}\n"]}
@@ -39,6 +39,8 @@ export interface ContainerNode {
39
39
  }
40
40
  export type ContainerContentsContextValue = ContainerContentsSnapshot & Pick<ContainerContentsStore, "createChild" | "deleteContainer" | "emptyTrash" | "ensureSystemContainer" | "moveContainer" | "purgeContainer" | "refresh" | "refreshRootLane" | "renameContainer" | "requestSync" | "setContainerIcon" | "setContainerPrimaryDocument" | "shareWithGroup" | "shareWithUser">;
41
41
  export interface ContainerContentsSnapshot {
42
+ /** A background folder listing is pending, independently of local readiness. */
43
+ readonly hydrating?: true;
42
44
  nodes: ReadonlyArray<ContainerNode>;
43
45
  ready: boolean;
44
46
  }
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { PurgeOptions } from \"../../workflows/container-contents/container-state/purge/purgeProgress\";\nimport type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport type { ContainerDocumentObjectSyncState } from \"../../workflows/container-contents/syncState\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgent/syncAgentTypes\";\n\n// Reuse the canonical access-level union from the crypto layer (the same source\n// `ContainerShareAccessLevel` chains to) rather than re-spelling the literals,\n// so the two can't drift.\nexport type ContainerContentsShareAccessLevel = ContainerAccessLevel;\n\nexport interface ContainerContentsStoreOptions {\n logLabel?: string | undefined;\n persistence?: ContainerContentsPersistence | undefined;\n}\n\n/** Lets an explicit tree refresh learn that it may have stopped short. */\nexport interface ContainerTreeRefreshObserver {\n /**\n * Called once the refresh settles if any container listing request failed\n * or timed out while it ran, so lanes may have stayed unlisted. A refused\n * or unverifiable item is not reported: retrying cannot fix it.\n */\n readonly onListingUnavailable?: (() => void) | undefined;\n}\n\nexport interface ContainerNode {\n systemSlot?: ContainerSystemSlot | null;\n createdAt?: string | null;\n effectiveAccessLevel?: ContainerAccessLevel | undefined;\n id: string;\n icon?: string | null;\n metadataDocumentId?: string | null;\n /** False while a discovered remote folder has no local metadata content. */\n metadataReady?: boolean;\n /** Canonical document id stored in encrypted metadata; never a device-local id. */\n primaryDocumentId?: string | null;\n organizationId: string;\n name: string;\n parentId: string | null;\n syncState: ContainerDocumentObjectSyncState;\n kind: \"container\";\n updatedAt?: string | null;\n}\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation/refresh methods, spelled as a Pick so the two can't drift.\nexport type ContainerContentsContextValue = ContainerContentsSnapshot &\n Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"purgeContainer\"\n | \"refresh\"\n | \"refreshRootLane\"\n | \"renameContainer\"\n | \"requestSync\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n >;\n\nexport interface ContainerContentsSnapshot {\n nodes: ReadonlyArray<ContainerNode>;\n ready: boolean;\n}\n\nexport type ContainerGroupRewrapPreparation =\n | {\n status: \"not-granted\";\n }\n | {\n isCurrent(\n expectedGroupHead: ReferencedPrincipalHead,\n expectedContainerId: string,\n expectedOrganizationId: string,\n ): Promise<boolean>;\n rewrap(): Promise<boolean>;\n status: \"prepared\";\n };\n\n/**\n * Shared per-scope container tree and mutation store.\n *\n * Ordinary metadata/topology writes (`createChild`, `moveContainer`,\n * `renameContainer`, and `setContainerIcon`) commit to local persistence and\n * update subscribers before their queued remote sync converges. Destructive\n * and access-control operations retain their explicit remote-authority gates.\n */\nexport interface ContainerContentsStore {\n createChild: (\n parentId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n deleteContainer: (containerId: string) => Promise<boolean>;\n ensureSystemContainer: (\n systemSlot: ContainerSystemSlot,\n name: string,\n options?: EnsureSystemContainerOptions | undefined,\n ) => Promise<ContainerNode | null>;\n moveContainer: (\n containerId: string,\n parentId: string,\n ) => Promise<ContainerNode | null>;\n purgeContainer: (\n containerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n emptyTrash: (\n trashContainerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n // `options.requireExistingGrant` gates the preparation check only. The\n // prepared `rewrap` is always grant-preserving: it re-wraps a signed grant\n // and never mints one, so it carries no chosen group name, and it throws\n // (rather than healing through a policy mutation) when the container\n // manifest grants the group but the verified policy has no matching grant.\n prepareGroupRewrap: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options?: { requireExistingGrant?: boolean } | undefined,\n ) => Promise<ContainerGroupRewrapPreparation | null>;\n refresh: (options?: ContainerTreeRefreshObserver) => Promise<boolean>;\n refreshRootLane: (\n options?: RefreshRootLaneOptions & ContainerTreeRefreshObserver,\n ) => Promise<boolean>;\n // Re-read root-lane containers from local SQLite into the snapshot with NO\n // server round-trip. Surfaces a just-persisted container — e.g. the Trash bin\n // that registration/org-creation provisioned server-side and wrote to SQLite\n // via persistRegistrationBootstrap — instantly, instead of waiting for the\n // remote root-lane pull. Idempotent with a later remote pull: the merge is\n // keyed by container id, so the pull reconciles in place rather than duplicating.\n refreshLocalContainers: () => Promise<void>;\n requestSync: () => void;\n renameContainer: (\n containerId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n /** Null clears the preference. Target must be hydrated, linked and synced once. */\n setContainerPrimaryDocument: (\n containerId: string,\n documentId: string | null,\n ) => Promise<ContainerNode | null>;\n setContainerIcon: (\n containerId: string,\n icon: string | null,\n ) => Promise<ContainerNode | null>;\n shareWithGroup: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options: {\n /**\n * The display name the group was chosen by. Required: the share fails\n * closed if the verified group policy commits a different name. Signed\n * names are unique within an organization by construction (enforced at\n * group creation), so the target's own name identifies it.\n */\n expectedGroupName: string;\n },\n ) => Promise<boolean>;\n shareWithUser: (\n containerId: string,\n userId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n ) => Promise<boolean>;\n getCachedContainerWriterProjection: (\n containerId: string,\n ) => ContainerWriterProjectionResponse | null;\n getSnapshot: () => ContainerContentsSnapshot;\n subscribe: (listener: () => void) => () => void;\n updateRuntime: (runtime: ContainerContentsStoreRuntime) => void;\n}\n\nexport interface EnsureSystemContainerOptions {\n icon?: string | null | undefined;\n skipAdvancedManagedRoot?: boolean | undefined;\n // For local-first bootstrap paths where slow remote I/O must not block the\n // caller from creating the deterministic local system container.\n deferRemoteBootstrap?: boolean | undefined;\n // Create the deterministic local system container without queuing the remote\n // create. A later ensureSystemContainer call without this flag promotes the\n // local slot into the sync queue.\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface ContainerContentsStoreState\n extends ContainerContentsStoreSyncState {\n listeners: Set<() => void>;\n snapshot: ContainerContentsSnapshot;\n writeChain: Promise<ContainerNode | null>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { PurgeOptions } from \"../../workflows/container-contents/container-state/purge/purgeProgress\";\nimport type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport type { ContainerDocumentObjectSyncState } from \"../../workflows/container-contents/syncState\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgent/syncAgentTypes\";\n\n// Reuse the canonical access-level union from the crypto layer (the same source\n// `ContainerShareAccessLevel` chains to) rather than re-spelling the literals,\n// so the two can't drift.\nexport type ContainerContentsShareAccessLevel = ContainerAccessLevel;\n\nexport interface ContainerContentsStoreOptions {\n logLabel?: string | undefined;\n persistence?: ContainerContentsPersistence | undefined;\n}\n\n/** Lets an explicit tree refresh learn that it may have stopped short. */\nexport interface ContainerTreeRefreshObserver {\n /**\n * Called once the refresh settles if any container listing request failed\n * or timed out while it ran, so lanes may have stayed unlisted. A refused\n * or unverifiable item is not reported: retrying cannot fix it.\n */\n readonly onListingUnavailable?: (() => void) | undefined;\n}\n\nexport interface ContainerNode {\n systemSlot?: ContainerSystemSlot | null;\n createdAt?: string | null;\n effectiveAccessLevel?: ContainerAccessLevel | undefined;\n id: string;\n icon?: string | null;\n metadataDocumentId?: string | null;\n /** False while a discovered remote folder has no local metadata content. */\n metadataReady?: boolean;\n /** Canonical document id stored in encrypted metadata; never a device-local id. */\n primaryDocumentId?: string | null;\n organizationId: string;\n name: string;\n parentId: string | null;\n syncState: ContainerDocumentObjectSyncState;\n kind: \"container\";\n updatedAt?: string | null;\n}\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation/refresh methods, spelled as a Pick so the two can't drift.\nexport type ContainerContentsContextValue = ContainerContentsSnapshot &\n Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"purgeContainer\"\n | \"refresh\"\n | \"refreshRootLane\"\n | \"renameContainer\"\n | \"requestSync\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n >;\n\nexport interface ContainerContentsSnapshot {\n /** A background folder listing is pending, independently of local readiness. */\n readonly hydrating?: true;\n nodes: ReadonlyArray<ContainerNode>;\n ready: boolean;\n}\n\nexport type ContainerGroupRewrapPreparation =\n | {\n status: \"not-granted\";\n }\n | {\n isCurrent(\n expectedGroupHead: ReferencedPrincipalHead,\n expectedContainerId: string,\n expectedOrganizationId: string,\n ): Promise<boolean>;\n rewrap(): Promise<boolean>;\n status: \"prepared\";\n };\n\n/**\n * Shared per-scope container tree and mutation store.\n *\n * Ordinary metadata/topology writes (`createChild`, `moveContainer`,\n * `renameContainer`, and `setContainerIcon`) commit to local persistence and\n * update subscribers before their queued remote sync converges. Destructive\n * and access-control operations retain their explicit remote-authority gates.\n */\nexport interface ContainerContentsStore {\n createChild: (\n parentId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n deleteContainer: (containerId: string) => Promise<boolean>;\n ensureSystemContainer: (\n systemSlot: ContainerSystemSlot,\n name: string,\n options?: EnsureSystemContainerOptions | undefined,\n ) => Promise<ContainerNode | null>;\n moveContainer: (\n containerId: string,\n parentId: string,\n ) => Promise<ContainerNode | null>;\n purgeContainer: (\n containerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n emptyTrash: (\n trashContainerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n // `options.requireExistingGrant` gates the preparation check only. The\n // prepared `rewrap` is always grant-preserving: it re-wraps a signed grant\n // and never mints one, so it carries no chosen group name, and it throws\n // (rather than healing through a policy mutation) when the container\n // manifest grants the group but the verified policy has no matching grant.\n prepareGroupRewrap: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options?: { requireExistingGrant?: boolean } | undefined,\n ) => Promise<ContainerGroupRewrapPreparation | null>;\n refresh: (options?: ContainerTreeRefreshObserver) => Promise<boolean>;\n refreshRootLane: (\n options?: RefreshRootLaneOptions & ContainerTreeRefreshObserver,\n ) => Promise<boolean>;\n // Re-read root-lane containers from local SQLite into the snapshot with NO\n // server round-trip. Surfaces a just-persisted container — e.g. the Trash bin\n // that registration/org-creation provisioned server-side and wrote to SQLite\n // via persistRegistrationBootstrap — instantly, instead of waiting for the\n // remote root-lane pull. Idempotent with a later remote pull: the merge is\n // keyed by container id, so the pull reconciles in place rather than duplicating.\n refreshLocalContainers: () => Promise<void>;\n requestSync: () => void;\n renameContainer: (\n containerId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n /** Null clears the preference. Target must be hydrated, linked and synced once. */\n setContainerPrimaryDocument: (\n containerId: string,\n documentId: string | null,\n ) => Promise<ContainerNode | null>;\n setContainerIcon: (\n containerId: string,\n icon: string | null,\n ) => Promise<ContainerNode | null>;\n shareWithGroup: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options: {\n /**\n * The display name the group was chosen by. Required: the share fails\n * closed if the verified group policy commits a different name. Signed\n * names are unique within an organization by construction (enforced at\n * group creation), so the target's own name identifies it.\n */\n expectedGroupName: string;\n },\n ) => Promise<boolean>;\n shareWithUser: (\n containerId: string,\n userId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n ) => Promise<boolean>;\n getCachedContainerWriterProjection: (\n containerId: string,\n ) => ContainerWriterProjectionResponse | null;\n getSnapshot: () => ContainerContentsSnapshot;\n subscribe: (listener: () => void) => () => void;\n updateRuntime: (runtime: ContainerContentsStoreRuntime) => void;\n}\n\nexport interface EnsureSystemContainerOptions {\n icon?: string | null | undefined;\n skipAdvancedManagedRoot?: boolean | undefined;\n // For local-first bootstrap paths where slow remote I/O must not block the\n // caller from creating the deterministic local system container.\n deferRemoteBootstrap?: boolean | undefined;\n // Create the deterministic local system container without queuing the remote\n // create. A later ensureSystemContainer call without this flag promotes the\n // local slot into the sync queue.\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface ContainerContentsStoreState\n extends ContainerContentsStoreSyncState {\n listeners: Set<() => void>;\n snapshot: ContainerContentsSnapshot;\n writeChain: Promise<ContainerNode | null>;\n}\n"]}