@tearleads/client-sdk 0.1.60 → 0.1.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/Tearleads.d.ts +8 -48
  2. package/Tearleads.js +18 -25
  3. package/Tearleads.js.map +1 -1
  4. package/TearleadsOptions.d.ts +49 -0
  5. package/TearleadsOptions.js +2 -0
  6. package/TearleadsOptions.js.map +1 -0
  7. package/client/containerContents/documentDiscovery.js +5 -5
  8. package/client/containerContents/documentDiscovery.js.map +1 -1
  9. package/client/containerContents/index.d.ts +7 -7
  10. package/client/containerContents/index.js +7 -7
  11. package/client/containerContents/index.js.map +1 -1
  12. package/client/containerContents/types.d.ts +6 -6
  13. package/client/containerContents/types.js.map +1 -1
  14. package/client/deviceFirst/index.js +2 -2
  15. package/client/deviceFirst/index.js.map +1 -1
  16. package/client/root/index.d.ts +1 -1
  17. package/client/root/index.js.map +1 -1
  18. package/client/runtime/workflowRuntime.d.ts +1 -1
  19. package/client/runtime/workflowRuntime.js.map +1 -1
  20. package/index.d.ts +2 -1
  21. package/index.js +1 -1
  22. package/index.js.map +1 -1
  23. package/package.json +1 -1
  24. package/stores/container-contents/containerStatePersistence.js +1 -1
  25. package/stores/container-contents/documentRecovery.js +2 -2
  26. package/stores/container-contents/documentRecovery.js.map +1 -1
  27. package/stores/container-contents/documentWork.js.map +1 -1
  28. package/stores/container-contents/localRefresh.js +2 -2
  29. package/stores/container-contents/localRefresh.js.map +1 -1
  30. package/stores/container-contents/operations.js +2 -2
  31. package/stores/container-contents/operations.js.map +1 -1
  32. package/stores/container-contents/remoteContainerIngestion.js +1 -1
  33. package/stores/container-contents/remoteEventSync.js +1 -1
  34. package/stores/container-contents/remoteHydrationRequest.js +1 -1
  35. package/stores/container-contents/setContainerIconOperation.js +2 -2
  36. package/stores/container-contents/setContainerIconOperation.js.map +1 -1
  37. package/stores/container-contents/shareOperations.js +1 -1
  38. package/stores/container-contents/startupHydration.js +1 -1
  39. package/stores/container-contents/syncAgent.d.ts +2 -2
  40. package/stores/container-contents/syncAgentTypes.d.ts +1 -1
  41. package/stores/container-contents/syncLaneIteration.js +2 -2
  42. package/stores/container-contents/syncLaneIteration.js.map +1 -1
  43. package/stores/container-contents/systemContainerIcon.js +1 -1
  44. package/stores/container-contents/systemContainerIcon.js.map +1 -1
  45. package/workflows/container-contents/{documentAttributionRanges.d.ts → attribution/documentAttributionRanges.d.ts} +1 -1
  46. package/workflows/container-contents/{documentCharacterBlame.js → attribution/documentCharacterBlame.js} +3 -3
  47. package/workflows/container-contents/attribution/documentCharacterBlame.js.map +1 -0
  48. package/workflows/container-contents/{documentFieldBlame.js → attribution/documentFieldBlame.js} +4 -4
  49. package/workflows/container-contents/attribution/documentFieldBlame.js.map +1 -0
  50. package/workflows/container-contents/container-state/createIntentSync.js +1 -1
  51. package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
  52. package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
  53. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  54. package/workflows/container-contents/container-state/purgeTree.js +2 -2
  55. package/workflows/container-contents/container-state/purgeTree.js.map +1 -1
  56. package/workflows/container-contents/container-state/sharePersistence.js +2 -2
  57. package/workflows/container-contents/container-state/sharePersistence.js.map +1 -1
  58. package/workflows/container-contents/{containerDocumentListing.js → documentDiscovery/containerDocumentListing.js} +1 -1
  59. package/workflows/container-contents/{documentDiscoveryApply.js → documentDiscovery/documentDiscoveryApply.js} +3 -3
  60. package/workflows/container-contents/documentDiscovery/documentDiscoveryApply.js.map +1 -0
  61. package/workflows/container-contents/{documentDiscoveryCandidates.js.map → documentDiscovery/documentDiscoveryCandidates.js.map} +1 -1
  62. package/workflows/container-contents/{documentDiscoveryEvidence.js → documentDiscovery/documentDiscoveryEvidence.js} +1 -1
  63. package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -0
  64. package/workflows/container-contents/{documentDiscoveryInputs.js → documentDiscovery/documentDiscoveryInputs.js} +2 -2
  65. package/workflows/container-contents/documentDiscovery/documentDiscoveryInputs.js.map +1 -0
  66. package/workflows/container-contents/documentDiscovery/documentDiscoveryLanes.js.map +1 -0
  67. package/workflows/container-contents/{documentDiscoveryTypes.d.ts → documentDiscovery/documentDiscoveryTypes.d.ts} +4 -4
  68. package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.js.map +1 -0
  69. package/workflows/container-contents/{documentDiscovery.d.ts → documentDiscovery/index.d.ts} +1 -1
  70. package/workflows/container-contents/{documentDiscovery.js → documentDiscovery/index.js} +5 -5
  71. package/workflows/container-contents/documentDiscovery/index.js.map +1 -0
  72. package/workflows/container-contents/{availableDocumentLinkIntent.js → documentLinks/availableDocumentLinkIntent.js} +1 -1
  73. package/workflows/container-contents/documentLinks/availableDocumentLinkIntent.js.map +1 -0
  74. package/workflows/container-contents/{deferredDocumentLinks.js → documentLinks/deferredDocumentLinks.js} +1 -1
  75. package/workflows/container-contents/documentLinks/deferredDocumentLinks.js.map +1 -0
  76. package/workflows/container-contents/{documentLinkIntent.js → documentLinks/documentLinkIntent.js} +4 -4
  77. package/workflows/container-contents/documentLinks/documentLinkIntent.js.map +1 -0
  78. package/workflows/container-contents/documentLinks/documentLocalRelink.js.map +1 -0
  79. package/workflows/container-contents/{documentLinks.d.ts → documentLinks/index.d.ts} +5 -5
  80. package/workflows/container-contents/{documentLinks.js → documentLinks/index.js} +10 -10
  81. package/workflows/container-contents/documentLinks/index.js.map +1 -0
  82. package/workflows/container-contents/documentMove/documentMoveDeniedReplay.js.map +1 -0
  83. package/workflows/container-contents/{documentMoveFailure.js → documentMove/documentMoveFailure.js} +1 -1
  84. package/workflows/container-contents/documentMove/documentMoveFailure.js.map +1 -0
  85. package/workflows/container-contents/{documentMoveIntent.js → documentMove/documentMoveIntent.js} +7 -7
  86. package/workflows/container-contents/documentMove/documentMoveIntent.js.map +1 -0
  87. package/workflows/container-contents/{documentMoveIntentErrors.js → documentMove/documentMoveIntentErrors.js} +1 -1
  88. package/workflows/container-contents/documentMove/documentMoveIntentErrors.js.map +1 -0
  89. package/workflows/container-contents/{documentMoveIntentSettlement.js → documentMove/documentMoveIntentSettlement.js} +4 -4
  90. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -0
  91. package/workflows/container-contents/{documentMoveIntentSync.js → documentMove/documentMoveIntentSync.js} +7 -7
  92. package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -0
  93. package/workflows/container-contents/{documentMoveVanishedRefresh.js → documentMove/documentMoveVanishedRefresh.js} +3 -3
  94. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js.map +1 -0
  95. package/workflows/container-contents/{documentHydrationProbe.js → documentPriming/documentHydrationProbe.js} +4 -4
  96. package/workflows/container-contents/documentPriming/documentHydrationProbe.js.map +1 -0
  97. package/workflows/container-contents/documentPriming/documentRuntimeTargetSync.js.map +1 -0
  98. package/workflows/container-contents/{documentPriming.js → documentPriming/index.js} +5 -5
  99. package/workflows/container-contents/documentPriming/index.js.map +1 -0
  100. package/workflows/container-contents/{documentStructure.d.ts → documentQueries/documentStructure.d.ts} +1 -1
  101. package/workflows/container-contents/{documentStructure.js → documentQueries/documentStructure.js} +4 -4
  102. package/workflows/container-contents/documentQueries/documentStructure.js.map +1 -0
  103. package/workflows/container-contents/{documentStructureTypes.d.ts → documentQueries/documentStructureTypes.d.ts} +4 -4
  104. package/workflows/container-contents/documentQueries/documentStructureTypes.js.map +1 -0
  105. package/workflows/container-contents/{documentSubtreeQueries.js → documentQueries/documentSubtreeQueries.js} +5 -5
  106. package/workflows/container-contents/documentQueries/documentSubtreeQueries.js.map +1 -0
  107. package/workflows/container-contents/{documentQueries.d.ts → documentQueries/index.d.ts} +8 -8
  108. package/workflows/container-contents/{documentQueries.js → documentQueries/index.js} +13 -13
  109. package/workflows/container-contents/documentQueries/index.js.map +1 -0
  110. package/workflows/container-contents/{orphanedDocumentSql.js → documentQueries/orphanedDocumentSql.js} +1 -1
  111. package/workflows/container-contents/documentQueries/orphanedDocumentSql.js.map +1 -0
  112. package/workflows/container-contents/{pendingDownloads.d.ts → documentQueries/pendingDownloads.d.ts} +1 -1
  113. package/workflows/container-contents/{pendingDownloads.js → documentQueries/pendingDownloads.js} +3 -3
  114. package/workflows/container-contents/documentQueries/pendingDownloads.js.map +1 -0
  115. package/workflows/container-contents/documentQueries/sql.js +1 -1
  116. package/workflows/container-contents/documentQueries/sql.js.map +1 -1
  117. package/workflows/container-contents/index.d.ts +13 -13
  118. package/workflows/container-contents/index.js +11 -11
  119. package/workflows/container-contents/index.js.map +1 -1
  120. package/workflows/container-contents/{blobInfo.d.ts → info/blobInfo.d.ts} +1 -1
  121. package/workflows/container-contents/{blobInfo.js → info/blobInfo.js} +4 -4
  122. package/workflows/container-contents/info/blobInfo.js.map +1 -0
  123. package/workflows/container-contents/{blobInfoTypes.d.ts → info/blobInfoTypes.d.ts} +1 -1
  124. package/workflows/container-contents/info/blobInfoTypes.js.map +1 -0
  125. package/workflows/container-contents/{containerInfo.d.ts → info/containerInfo.d.ts} +4 -4
  126. package/workflows/container-contents/{containerInfo.js → info/containerInfo.js} +5 -5
  127. package/workflows/container-contents/info/containerInfo.js.map +1 -0
  128. package/workflows/container-contents/{documentInfo.d.ts → info/documentInfo.d.ts} +3 -3
  129. package/workflows/container-contents/{documentInfo.js → info/documentInfo.js} +11 -11
  130. package/workflows/container-contents/info/documentInfo.js.map +1 -0
  131. package/workflows/container-contents/{documentInfoTypes.d.ts → info/documentInfoTypes.d.ts} +3 -3
  132. package/workflows/container-contents/info/documentInfoTypes.js.map +1 -0
  133. package/workflows/container-contents/{metadata.d.ts → metadata/index.d.ts} +2 -2
  134. package/workflows/container-contents/{metadata.js → metadata/index.js} +5 -5
  135. package/workflows/container-contents/metadata/index.js.map +1 -0
  136. package/workflows/container-contents/{metadataEvents.d.ts → metadata/metadataEvents.d.ts} +1 -1
  137. package/workflows/container-contents/{metadataEvents.js → metadata/metadataEvents.js} +1 -1
  138. package/workflows/container-contents/metadata/metadataEvents.js.map +1 -0
  139. package/workflows/container-contents/{metadataIncomingUpdateIsolation.js → metadata/metadataIncomingUpdateIsolation.js} +5 -5
  140. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -0
  141. package/workflows/container-contents/{metadataMutationPreparation.d.ts → metadata/metadataMutationPreparation.d.ts} +7 -7
  142. package/workflows/container-contents/{metadataMutationPreparation.js → metadata/metadataMutationPreparation.js} +5 -5
  143. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -0
  144. package/workflows/container-contents/{metadataPersistence.d.ts → metadata/metadataPersistence.d.ts} +2 -2
  145. package/workflows/container-contents/{metadataPersistence.js → metadata/metadataPersistence.js} +4 -4
  146. package/workflows/container-contents/metadata/metadataPersistence.js.map +1 -0
  147. package/workflows/container-contents/{metadataPullContinuationInvalidation.js → metadata/metadataPullContinuationInvalidation.js} +4 -4
  148. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -0
  149. package/workflows/container-contents/{metadataReadState.d.ts → metadata/metadataReadState.d.ts} +1 -1
  150. package/workflows/container-contents/metadata/metadataReadState.js.map +1 -0
  151. package/workflows/container-contents/{metadataRecord.js → metadata/metadataRecord.js} +2 -2
  152. package/workflows/container-contents/metadata/metadataRecord.js.map +1 -0
  153. package/workflows/container-contents/{metadataRemoteSync.d.ts → metadata/metadataRemoteSync.d.ts} +5 -5
  154. package/workflows/container-contents/{metadataRemoteSync.js → metadata/metadataRemoteSync.js} +3 -3
  155. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -0
  156. package/workflows/container-contents/{metadataStateInstallation.d.ts → metadata/metadataStateInstallation.d.ts} +1 -1
  157. package/workflows/container-contents/metadata/metadataStateInstallation.js.map +1 -0
  158. package/workflows/container-contents/{metadataStateIsolation.js → metadata/metadataStateIsolation.js} +3 -3
  159. package/workflows/container-contents/metadata/metadataStateIsolation.js.map +1 -0
  160. package/workflows/container-contents/{metadataSyncErrors.js → metadata/metadataSyncErrors.js} +3 -3
  161. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -0
  162. package/workflows/container-contents/{metadataSyncSettlement.d.ts → metadata/metadataSyncSettlement.d.ts} +2 -2
  163. package/workflows/container-contents/{metadataSyncSettlement.js → metadata/metadataSyncSettlement.js} +3 -3
  164. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -0
  165. package/workflows/container-contents/{metadataTypes.d.ts → metadata/metadataTypes.d.ts} +5 -5
  166. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -0
  167. package/workflows/container-contents/pendingWrites/aggregation.js.map +1 -1
  168. package/workflows/container-contents/pendingWrites/deferredTails.js.map +1 -1
  169. package/workflows/container-contents/{pendingWrites.d.ts → pendingWrites/index.d.ts} +1 -1
  170. package/workflows/container-contents/{pendingWrites.js → pendingWrites/index.js} +12 -12
  171. package/workflows/container-contents/pendingWrites/index.js.map +1 -0
  172. package/workflows/container-contents/projectionGeneration.js.map +1 -1
  173. package/workflows/container-contents/projectionKeys.d.ts +1 -1
  174. package/workflows/container-contents/projectionKeys.js.map +1 -1
  175. package/workflows/container-contents/projectionView.js +1 -1
  176. package/workflows/container-contents/projectionView.js.map +1 -1
  177. package/workflows/container-contents/{folderRecovery.d.ts → recovery/folderRecovery.d.ts} +1 -1
  178. package/workflows/container-contents/{folderRecovery.js → recovery/folderRecovery.js} +4 -4
  179. package/workflows/container-contents/recovery/folderRecovery.js.map +1 -0
  180. package/workflows/container-contents/{staleRootRecovery.js → recovery/staleRootRecovery.js} +1 -1
  181. package/workflows/container-contents/recovery/staleRootRecovery.js.map +1 -0
  182. package/workflows/container-contents/remoteHydration/completeHydration.js +1 -1
  183. package/workflows/container-contents/remoteHydration/completeHydration.js.map +1 -1
  184. package/workflows/container-contents/remoteHydration/heldContainerRebind.js +1 -1
  185. package/workflows/container-contents/remoteHydration/heldContainerRebind.js.map +1 -1
  186. package/workflows/container-contents/{remoteHydration.d.ts → remoteHydration/index.d.ts} +2 -2
  187. package/workflows/container-contents/{remoteHydration.js → remoteHydration/index.js} +6 -6
  188. package/workflows/container-contents/remoteHydration/index.js.map +1 -0
  189. package/workflows/container-contents/{remoteContainerPageHydration.js → remoteHydration/remoteContainerPageHydration.js} +8 -8
  190. package/workflows/container-contents/remoteHydration/remoteContainerPageHydration.js.map +1 -0
  191. package/workflows/container-contents/{remoteContainerState.js → remoteHydration/remoteContainerState.js} +11 -11
  192. package/workflows/container-contents/remoteHydration/remoteContainerState.js.map +1 -0
  193. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  194. package/workflows/container-contents/runtime.d.ts +1 -1
  195. package/workflows/container-contents/runtime.js.map +1 -1
  196. package/workflows/container-contents/{documentPurge.d.ts → tombstones/documentPurge.d.ts} +6 -6
  197. package/workflows/container-contents/{documentPurge.js → tombstones/documentPurge.js} +6 -6
  198. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -0
  199. package/workflows/container-contents/{documentTombstoneEvidence.js → tombstones/documentTombstoneEvidence.js} +9 -9
  200. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -0
  201. package/workflows/container-contents/{documentTombstoneGate.js → tombstones/documentTombstoneGate.js} +1 -1
  202. package/workflows/container-contents/tombstones/documentTombstoneGate.js.map +1 -0
  203. package/workflows/documents/projectionKeys.d.ts +1 -1
  204. package/workflows/documents/projectionKeys.js.map +1 -1
  205. package/workflows/documents/reportDocumentSyncQuarantine.js.map +1 -1
  206. package/workflows/documents/runtime.d.ts +1 -1
  207. package/workflows/documents/runtime.js.map +1 -1
  208. package/workflows/{runtimeInput.d.ts → shared/runtimeInput.d.ts} +6 -6
  209. package/workflows/shared/runtimeInput.js.map +1 -0
  210. package/workflows/container-contents/availableDocumentLinkIntent.js.map +0 -1
  211. package/workflows/container-contents/blobInfo.js.map +0 -1
  212. package/workflows/container-contents/blobInfoTypes.js.map +0 -1
  213. package/workflows/container-contents/containerInfo.js.map +0 -1
  214. package/workflows/container-contents/deferredDocumentLinks.js.map +0 -1
  215. package/workflows/container-contents/documentCharacterBlame.js.map +0 -1
  216. package/workflows/container-contents/documentDiscovery.js.map +0 -1
  217. package/workflows/container-contents/documentDiscoveryApply.js.map +0 -1
  218. package/workflows/container-contents/documentDiscoveryEvidence.js.map +0 -1
  219. package/workflows/container-contents/documentDiscoveryInputs.js.map +0 -1
  220. package/workflows/container-contents/documentDiscoveryLanes.js.map +0 -1
  221. package/workflows/container-contents/documentDiscoveryTypes.js.map +0 -1
  222. package/workflows/container-contents/documentFieldBlame.js.map +0 -1
  223. package/workflows/container-contents/documentHydrationProbe.js.map +0 -1
  224. package/workflows/container-contents/documentInfo.js.map +0 -1
  225. package/workflows/container-contents/documentInfoTypes.js.map +0 -1
  226. package/workflows/container-contents/documentLinkIntent.js.map +0 -1
  227. package/workflows/container-contents/documentLinks.js.map +0 -1
  228. package/workflows/container-contents/documentLocalRelink.js.map +0 -1
  229. package/workflows/container-contents/documentMoveDeniedReplay.js.map +0 -1
  230. package/workflows/container-contents/documentMoveFailure.js.map +0 -1
  231. package/workflows/container-contents/documentMoveIntent.js.map +0 -1
  232. package/workflows/container-contents/documentMoveIntentErrors.js.map +0 -1
  233. package/workflows/container-contents/documentMoveIntentSettlement.js.map +0 -1
  234. package/workflows/container-contents/documentMoveIntentSync.js.map +0 -1
  235. package/workflows/container-contents/documentMoveVanishedRefresh.js.map +0 -1
  236. package/workflows/container-contents/documentPriming.js.map +0 -1
  237. package/workflows/container-contents/documentPurge.js.map +0 -1
  238. package/workflows/container-contents/documentQueries.js.map +0 -1
  239. package/workflows/container-contents/documentRuntimeTargetSync.js.map +0 -1
  240. package/workflows/container-contents/documentStructure.js.map +0 -1
  241. package/workflows/container-contents/documentStructureTypes.js.map +0 -1
  242. package/workflows/container-contents/documentSubtreeQueries.js.map +0 -1
  243. package/workflows/container-contents/documentTombstoneEvidence.js.map +0 -1
  244. package/workflows/container-contents/documentTombstoneGate.js.map +0 -1
  245. package/workflows/container-contents/folderRecovery.js.map +0 -1
  246. package/workflows/container-contents/metadata.js.map +0 -1
  247. package/workflows/container-contents/metadataEvents.js.map +0 -1
  248. package/workflows/container-contents/metadataIncomingUpdateIsolation.js.map +0 -1
  249. package/workflows/container-contents/metadataMutationPreparation.js.map +0 -1
  250. package/workflows/container-contents/metadataPersistence.js.map +0 -1
  251. package/workflows/container-contents/metadataPullContinuationInvalidation.js.map +0 -1
  252. package/workflows/container-contents/metadataReadState.js.map +0 -1
  253. package/workflows/container-contents/metadataRecord.js.map +0 -1
  254. package/workflows/container-contents/metadataRemoteSync.js.map +0 -1
  255. package/workflows/container-contents/metadataStateInstallation.js.map +0 -1
  256. package/workflows/container-contents/metadataStateIsolation.js.map +0 -1
  257. package/workflows/container-contents/metadataSyncErrors.js.map +0 -1
  258. package/workflows/container-contents/metadataSyncSettlement.js.map +0 -1
  259. package/workflows/container-contents/metadataTypes.js.map +0 -1
  260. package/workflows/container-contents/orphanedDocumentSql.js.map +0 -1
  261. package/workflows/container-contents/pendingDownloads.js.map +0 -1
  262. package/workflows/container-contents/pendingWrites.js.map +0 -1
  263. package/workflows/container-contents/remoteContainerPageHydration.js.map +0 -1
  264. package/workflows/container-contents/remoteContainerState.js.map +0 -1
  265. package/workflows/container-contents/remoteHydration.js.map +0 -1
  266. package/workflows/container-contents/staleRootRecovery.js.map +0 -1
  267. package/workflows/runtimeInput.js.map +0 -1
  268. /package/workflows/container-contents/{documentAttributionRanges.js → attribution/documentAttributionRanges.js} +0 -0
  269. /package/workflows/container-contents/{documentAttributionRanges.js.map → attribution/documentAttributionRanges.js.map} +0 -0
  270. /package/workflows/container-contents/{containerDocumentListing.js.map → documentDiscovery/containerDocumentListing.js.map} +0 -0
  271. /package/workflows/container-contents/{documentDiscoveryCandidates.js → documentDiscovery/documentDiscoveryCandidates.js} +0 -0
  272. /package/workflows/container-contents/{documentDiscoveryLanes.js → documentDiscovery/documentDiscoveryLanes.js} +0 -0
  273. /package/workflows/container-contents/{documentDiscoveryTypes.js → documentDiscovery/documentDiscoveryTypes.js} +0 -0
  274. /package/workflows/container-contents/{documentHeadScope.js → documentDiscovery/documentHeadScope.js} +0 -0
  275. /package/workflows/container-contents/{documentHeadScope.js.map → documentDiscovery/documentHeadScope.js.map} +0 -0
  276. /package/workflows/container-contents/{documentLocalRelink.js → documentLinks/documentLocalRelink.js} +0 -0
  277. /package/workflows/container-contents/{documentMoveDeniedReplay.js → documentMove/documentMoveDeniedReplay.js} +0 -0
  278. /package/workflows/container-contents/{documentMoveUnlinkIds.js → documentMove/documentMoveUnlinkIds.js} +0 -0
  279. /package/workflows/container-contents/{documentMoveUnlinkIds.js.map → documentMove/documentMoveUnlinkIds.js.map} +0 -0
  280. /package/workflows/container-contents/{documentRuntimeTargetSync.js → documentPriming/documentRuntimeTargetSync.js} +0 -0
  281. /package/workflows/container-contents/{documentStructureTypes.js → documentQueries/documentStructureTypes.js} +0 -0
  282. /package/workflows/container-contents/{blobInfoRows.js → info/blobInfoRows.js} +0 -0
  283. /package/workflows/container-contents/{blobInfoRows.js.map → info/blobInfoRows.js.map} +0 -0
  284. /package/workflows/container-contents/{blobInfoTypes.js → info/blobInfoTypes.js} +0 -0
  285. /package/workflows/container-contents/{documentInfoTypes.js → info/documentInfoTypes.js} +0 -0
  286. /package/workflows/container-contents/{metadataReadState.js → metadata/metadataReadState.js} +0 -0
  287. /package/workflows/container-contents/{metadataStateInstallation.js → metadata/metadataStateInstallation.js} +0 -0
  288. /package/workflows/container-contents/{metadataSyncFollowup.js → metadata/metadataSyncFollowup.js} +0 -0
  289. /package/workflows/container-contents/{metadataSyncFollowup.js.map → metadata/metadataSyncFollowup.js.map} +0 -0
  290. /package/workflows/container-contents/{metadataSyncRegistrations.d.ts → metadata/metadataSyncRegistrations.d.ts} +0 -0
  291. /package/workflows/container-contents/{metadataSyncRegistrations.js → metadata/metadataSyncRegistrations.js} +0 -0
  292. /package/workflows/container-contents/{metadataSyncRegistrations.js.map → metadata/metadataSyncRegistrations.js.map} +0 -0
  293. /package/workflows/container-contents/{metadataTypes.js → metadata/metadataTypes.js} +0 -0
  294. /package/workflows/container-contents/{pendingWritesTypes.d.ts → pendingWrites/pendingWritesTypes.d.ts} +0 -0
  295. /package/workflows/container-contents/{pendingWritesTypes.js → pendingWrites/pendingWritesTypes.js} +0 -0
  296. /package/workflows/container-contents/{pendingWritesTypes.js.map → pendingWrites/pendingWritesTypes.js.map} +0 -0
  297. /package/workflows/container-contents/{remoteHydrationLog.js → remoteHydration/remoteHydrationLog.js} +0 -0
  298. /package/workflows/container-contents/{remoteHydrationLog.js.map → remoteHydration/remoteHydrationLog.js.map} +0 -0
  299. /package/workflows/{runtimeInput.js → shared/runtimeInput.js} +0 -0
@@ -3,12 +3,12 @@ import type { StoredDocumentKind } from "../../data/documents/documentKinds.js";
3
3
  import type { DocumentSummary } from "../../data/documents/documentSummary.js";
4
4
  import type { ContainerContentsStore, ContainerContentsStoreOptions, ContainerContentsStoreRuntime } from "../../stores/container-contents/index.js";
5
5
  import type { DocumentStore } from "../../stores/documents/index.js";
6
- import type { BlobInfoInput, BlobInfoList } from "../../workflows/container-contents/blobInfo.js";
7
- import type { ContainerInfo, ContainerInfoRemoteMode } from "../../workflows/container-contents/containerInfo.js";
8
- import type { DocumentAttributionRangesInput, DocumentAttributionRangesPage } from "../../workflows/container-contents/documentAttributionRanges.js";
9
- import type { DocumentInfo, DocumentInfoRemoteMode } from "../../workflows/container-contents/documentInfo.js";
10
- import type { ContainerDocumentQueries } from "../../workflows/container-contents/documentQueries.js";
11
- import type { SetLinkedContainerIdsForDocument } from "../../workflows/container-contents/documentStructure.js";
6
+ import type { DocumentAttributionRangesInput, DocumentAttributionRangesPage } from "../../workflows/container-contents/attribution/documentAttributionRanges.js";
7
+ import type { ContainerDocumentQueries } from "../../workflows/container-contents/documentQueries/index.js";
8
+ import type { SetLinkedContainerIdsForDocument } from "../../workflows/container-contents/documentQueries/documentStructure.js";
9
+ import type { BlobInfoInput, BlobInfoList } from "../../workflows/container-contents/info/blobInfo.js";
10
+ import type { ContainerInfo, ContainerInfoRemoteMode } from "../../workflows/container-contents/info/containerInfo.js";
11
+ import type { DocumentInfo, DocumentInfoRemoteMode } from "../../workflows/container-contents/info/documentInfo.js";
12
12
  import type { ContainerContentsProjectionUserKeyResolver } from "../../workflows/container-contents/projectionKeys.js";
13
13
  import type { ContainerContentsWorkflowRuntime } from "../../workflows/container-contents/runtime.js";
14
14
  import type { DocumentsWorkflowRuntime } from "../../workflows/documents/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentEditAttributionResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreRuntime,\n} from \"../../stores/container-contents\";\nimport type { DocumentStore } from \"../../stores/documents\";\nimport type {\n BlobInfoInput,\n BlobInfoList,\n} from \"../../workflows/container-contents/blobInfo\";\nimport type {\n ContainerInfo,\n ContainerInfoRemoteMode,\n} from \"../../workflows/container-contents/containerInfo\";\nimport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../../workflows/container-contents/documentAttributionRanges\";\nimport type {\n DocumentInfo,\n DocumentInfoRemoteMode,\n} from \"../../workflows/container-contents/documentInfo\";\nimport type { ContainerDocumentQueries } from \"../../workflows/container-contents/documentQueries\";\nimport type { SetLinkedContainerIdsForDocument } from \"../../workflows/container-contents/documentStructure\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../workflows/container-contents/projectionKeys\";\nimport type { ContainerContentsWorkflowRuntime } from \"../../workflows/container-contents/runtime\";\nimport type { DocumentsWorkflowRuntime } from \"../../workflows/documents\";\n\n/**\n * Selects the container to inspect.\n *\n * Container info combines local SQLite timestamps with optional remote writer\n * projection details. Remote details include direct and inherited grants,\n * organization groups, security-path metadata, and sync watermarks for the\n * parent, child-container, and document lanes.\n *\n * Fields:\n * - `containerId`: Container id to inspect.\n * - `parentId`: Known parent id used when the container has not been synced\n * locally yet. Synced local state wins when available.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface ContainerInfoInput {\n containerId: string;\n parentId?: string | null | undefined;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}\n\n/**\n * Selects the document to inspect.\n *\n * Document info combines local document state, local and pending attachment\n * rows, and optional remote writer projection details.\n *\n * Fields:\n * - `attributionRequestKey`: Optional freshness generation used to coalesce\n * duplicate attribution reads without joining requests across invalidation.\n * - `localId`: Local document id stored in the client database.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface DocumentInfoInput {\n attributionRequestKey?: string | undefined;\n localId: string;\n remoteInfoMode?: DocumentInfoRemoteMode | undefined;\n}\n\nexport type MergeDocumentSummary = (nextDocument: DocumentSummary) => void;\n\nexport interface OpenContainerDocumentInput {\n readonly containerId: string | null;\n /** A file attach follows creation and carries the birth; see the store. */\n readonly deferInitialUpdate?: boolean | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId: string;\n}\n\nexport interface ContainerDocumentLinkInput {\n readonly mergeDocumentSummary: MergeDocumentSummary;\n readonly note: DocumentSummary;\n}\n\nexport interface MoveDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly expandNode: (nodeId: string) => void;\n readonly replaceLinkedContainers?: boolean | undefined;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly sourceContainerId?: string | null | undefined;\n readonly targetContainerId: string;\n}\n\nexport interface LinkDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly targetContainerId: string;\n}\n\nexport interface UnlinkDocumentFromContainerInput\n extends ContainerDocumentLinkInput {\n readonly removedContainerId: string;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n}\n\nexport interface SetActiveDocumentContainerInput\n extends ContainerDocumentLinkInput {\n readonly targetContainerId: string;\n}\n\nexport interface PurgeDocumentInput {\n /** The current local summary of the document to destroy. */\n readonly note: DocumentSummary;\n}\n\nexport interface PurgeDocumentResult {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: ReadonlyArray<string>;\n}\n\nexport interface ContainerDocumentLinks\n extends ContainerContentsWorkflowRuntime {\n documentRuntime(containerId: string | null): DocumentsWorkflowRuntime;\n openDocument(input: OpenContainerDocumentInput): DocumentStore;\n setActiveDocumentContainer(\n input: SetActiveDocumentContainerInput,\n ): Promise<DocumentSummary | null>;\n readonly canMutateDocumentLinks: boolean;\n readonly canMutateUnsyncedDocumentLinks: boolean;\n linkDocumentToContainer(\n input: LinkDocumentToContainerInput,\n ): Promise<DocumentSummary | null>;\n moveDocumentToContainer(\n input: MoveDocumentToContainerInput,\n ): Promise<{ linksChanged: boolean; note: DocumentSummary | null }>;\n /**\n * Permanently destroy a local-only document, or submit and verify a signed\n * terminal purge for a remote document. Remote purge requires exactly one\n * remaining container link and returns null on refusal or verification\n * failure.\n */\n purgeDocument(input: PurgeDocumentInput): Promise<PurgeDocumentResult | null>;\n readonly resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n unlinkDocumentFromContainer(\n input: UnlinkDocumentFromContainerInput,\n ): Promise<DocumentSummary | null>;\n}\n\n/**\n * High-level container-content service for tree state, document lists, document\n * links, discovery, and diagnostics.\n *\n * The facade owns the normal SDK protocol: it supplies the API client,\n * referenced-principal policy cache, local document query helpers, link\n * projection, tombstone handling, and sync watermarks. Consumers that need a\n * custom persistence protocol can call the lower-level workflows directly from\n * `@tearleads/client-sdk`.\n */\nexport interface ContainerContents {\n /**\n * Open the container tree state store for the current SDK runtime.\n *\n * The store is cached per domain scope and created from the current runtime\n * snapshot. Long-lived hosts should call `updateRuntime` after runtime\n * changes, such as from a React effect.\n */\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore;\n\n /**\n * Create local document query helpers for container contents.\n *\n * The facade is bound to the current SDK runtime snapshot, including the\n * active SQLite executor. Recreate it when the SDK runtime version changes.\n */\n documentQueries(): ContainerDocumentQueries;\n\n /**\n * Create the default document-link workflow helper.\n *\n * The returned object includes the current container-contents runtime,\n * the document projection-key resolver, mutation readiness, document store\n * priming, and container document-link mutations. Product stores can pass\n * this bundle around without rebuilding SDK runtime plumbing themselves.\n */\n documentLinks(): ContainerDocumentLinks;\n\n /**\n * Discover remote documents linked to one container.\n *\n * The method pages the remote container-document lane, writes discovered\n * document summaries into local SQLite, replaces the local link projection for\n * each discovered document, applies applicable tombstones, caches referenced\n * principal policies needed by newly visible documents, and advances the\n * container-document watermark after the local apply completes.\n *\n * One call verifies a bounded batch. Pending evidence is durable; a later\n * explicit call or background reconciliation resumes it.\n *\n * Returns the summaries touched by the apply, or `null` when the database or\n * listing is unavailable, a trust reset cancels the pass, or all evidence is\n * pending. Pending evidence may advance the watermark after durable staging.\n *\n * Parameters:\n * - `containerId`: Remote container id whose document lane should be listed.\n */\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null>;\n\n /**\n * Sync the content of a single document that no mini-app has opened.\n *\n * Discovery only records a document's metadata + an empty content shell, and a\n * document's locally authored content is only pushed once its store syncs; both\n * normally happen lazily when a mini-app opens the document. Some documents are\n * never opened yet still need to sync — notably the organization profile\n * document, which lives in an org's Members-granted metadata container and\n * holds the org display name. This opens a transient document store (registered\n * under the container's keys, so it can decrypt) and schedules a remote sync\n * pass. The pass both pushes the store's pending updates and merges + persists\n * any remote body, so the same call lets an owning device publish its profile\n * content and a member device pull it. `documentId` may be omitted; the store\n * then resolves it from the persisted record (the owning device keys the\n * document under a local alias, not its server id).\n */\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void;\n\n /**\n * Load diagnostic information for one local document.\n *\n * Local details are available when SQLite is ready. Remote details are loaded\n * from the document writer projection according to `remoteInfoMode`; the\n * default is `\"if-synced\"`.\n */\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo>;\n\n /**\n * Fetch a synced document's compact edit-attribution segments (peer -> writer\n * intervals) on their own, without the writer-projection/attachment work\n * `loadDocumentInfo` also does. Resolves to `null` on any request failure.\n * Callers must ignore the segments when `truncated` is set — a truncated\n * interval list can drop a peer's segments and mis-resolve it.\n */\n loadDocumentEditAttribution(\n documentId: string,\n ): Promise<DocumentEditAttributionResponse | null>;\n\n /** Load one revision-bound page of detailed per-upload edit attribution. */\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage>;\n\n /**\n * List local blob projections and pending attachment bytes grouped by blob.\n *\n * This is a reverse lookup query: callers can search by server blob id,\n * local storage key, document id/title, attachment slot, or MIME metadata and\n * then traverse matching blobs back to their owning local documents.\n */\n listBlobInfo(input?: BlobInfoInput | undefined): Promise<BlobInfoList>;\n\n /**\n * Load diagnostic information for one container.\n *\n * Local details include synced timestamps. Remote details are loaded from the\n * container writer projection according to `remoteInfoMode`; the default is\n * `\"always\"`. Pass `parentId` when inspecting a container before its local row\n * has been synced.\n */\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo>;\n\n /**\n * Create a workflow runtime for advanced container-content workflows.\n *\n * Prefer the high-level methods on this service for the default SDK protocol.\n * Use this when constructing lower-level stores or custom workflows that need\n * access to the current runtime snapshot.\n */\n workflowRuntime(): ContainerContentsStoreRuntime;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentEditAttributionResponse } from \"@tearleads/validators/response\";\nimport type { StoredDocumentKind } from \"../../data/documents/documentKinds\";\nimport type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreRuntime,\n} from \"../../stores/container-contents\";\nimport type { DocumentStore } from \"../../stores/documents\";\nimport type {\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n} from \"../../workflows/container-contents/attribution/documentAttributionRanges\";\nimport type { ContainerDocumentQueries } from \"../../workflows/container-contents/documentQueries\";\nimport type { SetLinkedContainerIdsForDocument } from \"../../workflows/container-contents/documentQueries/documentStructure\";\nimport type {\n BlobInfoInput,\n BlobInfoList,\n} from \"../../workflows/container-contents/info/blobInfo\";\nimport type {\n ContainerInfo,\n ContainerInfoRemoteMode,\n} from \"../../workflows/container-contents/info/containerInfo\";\nimport type {\n DocumentInfo,\n DocumentInfoRemoteMode,\n} from \"../../workflows/container-contents/info/documentInfo\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../../workflows/container-contents/projectionKeys\";\nimport type { ContainerContentsWorkflowRuntime } from \"../../workflows/container-contents/runtime\";\nimport type { DocumentsWorkflowRuntime } from \"../../workflows/documents\";\n\n/**\n * Selects the container to inspect.\n *\n * Container info combines local SQLite timestamps with optional remote writer\n * projection details. Remote details include direct and inherited grants,\n * organization groups, security-path metadata, and sync watermarks for the\n * parent, child-container, and document lanes.\n *\n * Fields:\n * - `containerId`: Container id to inspect.\n * - `parentId`: Known parent id used when the container has not been synced\n * locally yet. Synced local state wins when available.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface ContainerInfoInput {\n containerId: string;\n parentId?: string | null | undefined;\n remoteInfoMode?: ContainerInfoRemoteMode | undefined;\n}\n\n/**\n * Selects the document to inspect.\n *\n * Document info combines local document state, local and pending attachment\n * rows, and optional remote writer projection details.\n *\n * Fields:\n * - `attributionRequestKey`: Optional freshness generation used to coalesce\n * duplicate attribution reads without joining requests across invalidation.\n * - `localId`: Local document id stored in the client database.\n * - `remoteInfoMode`: Controls whether remote projection details are fetched.\n */\nexport interface DocumentInfoInput {\n attributionRequestKey?: string | undefined;\n localId: string;\n remoteInfoMode?: DocumentInfoRemoteMode | undefined;\n}\n\nexport type MergeDocumentSummary = (nextDocument: DocumentSummary) => void;\n\nexport interface OpenContainerDocumentInput {\n readonly containerId: string | null;\n /** A file attach follows creation and carries the birth; see the store. */\n readonly deferInitialUpdate?: boolean | undefined;\n readonly documentId?: string | null | undefined;\n readonly initialDocumentKind?: StoredDocumentKind | undefined;\n readonly initialText?: string | undefined;\n readonly localId: string;\n}\n\nexport interface ContainerDocumentLinkInput {\n readonly mergeDocumentSummary: MergeDocumentSummary;\n readonly note: DocumentSummary;\n}\n\nexport interface MoveDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly expandNode: (nodeId: string) => void;\n readonly replaceLinkedContainers?: boolean | undefined;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly sourceContainerId?: string | null | undefined;\n readonly targetContainerId: string;\n}\n\nexport interface LinkDocumentToContainerInput\n extends ContainerDocumentLinkInput {\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n readonly targetContainerId: string;\n}\n\nexport interface UnlinkDocumentFromContainerInput\n extends ContainerDocumentLinkInput {\n readonly removedContainerId: string;\n readonly setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n}\n\nexport interface SetActiveDocumentContainerInput\n extends ContainerDocumentLinkInput {\n readonly targetContainerId: string;\n}\n\nexport interface PurgeDocumentInput {\n /** The current local summary of the document to destroy. */\n readonly note: DocumentSummary;\n}\n\nexport interface PurgeDocumentResult {\n readonly documentId: string;\n readonly purgedAt: string;\n readonly reclaimedBlobStorageKeys: ReadonlyArray<string>;\n}\n\nexport interface ContainerDocumentLinks\n extends ContainerContentsWorkflowRuntime {\n documentRuntime(containerId: string | null): DocumentsWorkflowRuntime;\n openDocument(input: OpenContainerDocumentInput): DocumentStore;\n setActiveDocumentContainer(\n input: SetActiveDocumentContainerInput,\n ): Promise<DocumentSummary | null>;\n readonly canMutateDocumentLinks: boolean;\n readonly canMutateUnsyncedDocumentLinks: boolean;\n linkDocumentToContainer(\n input: LinkDocumentToContainerInput,\n ): Promise<DocumentSummary | null>;\n moveDocumentToContainer(\n input: MoveDocumentToContainerInput,\n ): Promise<{ linksChanged: boolean; note: DocumentSummary | null }>;\n /**\n * Permanently destroy a local-only document, or submit and verify a signed\n * terminal purge for a remote document. Remote purge requires exactly one\n * remaining container link and returns null on refusal or verification\n * failure.\n */\n purgeDocument(input: PurgeDocumentInput): Promise<PurgeDocumentResult | null>;\n readonly resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n unlinkDocumentFromContainer(\n input: UnlinkDocumentFromContainerInput,\n ): Promise<DocumentSummary | null>;\n}\n\n/**\n * High-level container-content service for tree state, document lists, document\n * links, discovery, and diagnostics.\n *\n * The facade owns the normal SDK protocol: it supplies the API client,\n * referenced-principal policy cache, local document query helpers, link\n * projection, tombstone handling, and sync watermarks. Consumers that need a\n * custom persistence protocol can call the lower-level workflows directly from\n * `@tearleads/client-sdk`.\n */\nexport interface ContainerContents {\n /**\n * Open the container tree state store for the current SDK runtime.\n *\n * The store is cached per domain scope and created from the current runtime\n * snapshot. Long-lived hosts should call `updateRuntime` after runtime\n * changes, such as from a React effect.\n */\n openTree(\n options?: ContainerContentsStoreOptions | undefined,\n ): ContainerContentsStore;\n\n /**\n * Create local document query helpers for container contents.\n *\n * The facade is bound to the current SDK runtime snapshot, including the\n * active SQLite executor. Recreate it when the SDK runtime version changes.\n */\n documentQueries(): ContainerDocumentQueries;\n\n /**\n * Create the default document-link workflow helper.\n *\n * The returned object includes the current container-contents runtime,\n * the document projection-key resolver, mutation readiness, document store\n * priming, and container document-link mutations. Product stores can pass\n * this bundle around without rebuilding SDK runtime plumbing themselves.\n */\n documentLinks(): ContainerDocumentLinks;\n\n /**\n * Discover remote documents linked to one container.\n *\n * The method pages the remote container-document lane, writes discovered\n * document summaries into local SQLite, replaces the local link projection for\n * each discovered document, applies applicable tombstones, caches referenced\n * principal policies needed by newly visible documents, and advances the\n * container-document watermark after the local apply completes.\n *\n * One call verifies a bounded batch. Pending evidence is durable; a later\n * explicit call or background reconciliation resumes it.\n *\n * Returns the summaries touched by the apply, or `null` when the database or\n * listing is unavailable, a trust reset cancels the pass, or all evidence is\n * pending. Pending evidence may advance the watermark after durable staging.\n *\n * Parameters:\n * - `containerId`: Remote container id whose document lane should be listed.\n */\n discoverContainerDocuments(\n containerId: string,\n ): Promise<ReadonlyArray<DocumentSummary> | null>;\n\n /**\n * Sync the content of a single document that no mini-app has opened.\n *\n * Discovery only records a document's metadata + an empty content shell, and a\n * document's locally authored content is only pushed once its store syncs; both\n * normally happen lazily when a mini-app opens the document. Some documents are\n * never opened yet still need to sync — notably the organization profile\n * document, which lives in an org's Members-granted metadata container and\n * holds the org display name. This opens a transient document store (registered\n * under the container's keys, so it can decrypt) and schedules a remote sync\n * pass. The pass both pushes the store's pending updates and merges + persists\n * any remote body, so the same call lets an owning device publish its profile\n * content and a member device pull it. `documentId` may be omitted; the store\n * then resolves it from the persisted record (the owning device keys the\n * document under a local alias, not its server id).\n */\n pullDocumentContent(input: {\n containerId: string;\n localId: string;\n documentId?: string | null | undefined;\n }): void;\n\n /**\n * Load diagnostic information for one local document.\n *\n * Local details are available when SQLite is ready. Remote details are loaded\n * from the document writer projection according to `remoteInfoMode`; the\n * default is `\"if-synced\"`.\n */\n loadDocumentInfo(input: DocumentInfoInput): Promise<DocumentInfo>;\n\n /**\n * Fetch a synced document's compact edit-attribution segments (peer -> writer\n * intervals) on their own, without the writer-projection/attachment work\n * `loadDocumentInfo` also does. Resolves to `null` on any request failure.\n * Callers must ignore the segments when `truncated` is set — a truncated\n * interval list can drop a peer's segments and mis-resolve it.\n */\n loadDocumentEditAttribution(\n documentId: string,\n ): Promise<DocumentEditAttributionResponse | null>;\n\n /** Load one revision-bound page of detailed per-upload edit attribution. */\n loadDocumentAttributionRanges(\n input: DocumentAttributionRangesInput,\n ): Promise<DocumentAttributionRangesPage>;\n\n /**\n * List local blob projections and pending attachment bytes grouped by blob.\n *\n * This is a reverse lookup query: callers can search by server blob id,\n * local storage key, document id/title, attachment slot, or MIME metadata and\n * then traverse matching blobs back to their owning local documents.\n */\n listBlobInfo(input?: BlobInfoInput | undefined): Promise<BlobInfoList>;\n\n /**\n * Load diagnostic information for one container.\n *\n * Local details include synced timestamps. Remote details are loaded from the\n * container writer projection according to `remoteInfoMode`; the default is\n * `\"always\"`. Pass `parentId` when inspecting a container before its local row\n * has been synced.\n */\n loadContainerInfo(input: ContainerInfoInput): Promise<ContainerInfo>;\n\n /**\n * Create a workflow runtime for advanced container-content workflows.\n *\n * Prefer the high-level methods on this service for the default SDK protocol.\n * Use this when constructing lower-level stores or custom workflows that need\n * access to the current runtime snapshot.\n */\n workflowRuntime(): ContainerContentsStoreRuntime;\n}\n"]}
@@ -4,8 +4,8 @@ import { openDocumentStore } from "../../stores/documents/index.js";
4
4
  import { requestRegisteredDocumentRemoteSync, subscribeToPersistedDocumentDeletions, subscribeToPersistedDocuments, } from "../../stores/documents/registry.js";
5
5
  import { getOrCreateLocalProjectionStore, } from "../../stores/local-projection/index.js";
6
6
  import { connectReconciliationTriggers, createReconciliationService, systemReconciliationClock, } from "../../sync/reconciliation/index.js";
7
- import { listAllContainerDocumentIdsFromApi } from "../../workflows/container-contents/containerDocumentListing.js";
8
- import { probeUndiscoveredRemoteDocumentBatch } from "../../workflows/container-contents/documentHydrationProbe.js";
7
+ import { listAllContainerDocumentIdsFromApi } from "../../workflows/container-contents/documentDiscovery/containerDocumentListing.js";
8
+ import { probeUndiscoveredRemoteDocumentBatch } from "../../workflows/container-contents/documentPriming/documentHydrationProbe.js";
9
9
  import { createContainerContentsDocumentsRuntime, createContainerContentsStoreWorkflowRuntime, } from "../../workflows/container-contents/runtime.js";
10
10
  import { discoverContainerDocumentLanesForRuntime } from "../containerContents/documentDiscovery.js";
11
11
  import { createReconciledDocumentContentPuller } from "./reconciledDocumentContentPull.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,EAC5B,gC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IAEd,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,cAA+B;IAE/B,OAAO,2CAA2C,CAChD,cAAc,CAAC,aAAa,EAAE,EAC9B,cAAc,CAAC,kBAAkB,CAClC,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n disposeDomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../../stores/container-contents\";\nimport { openDocumentStore } from \"../../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../../sync/reconciliation\";\nimport { listAllContainerDocumentIdsFromApi } from \"../../workflows/container-contents/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../../workflows/container-contents/documentHydrationProbe\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../../workflows/container-contents/runtime\";\nimport type { ContainerContents } from \"../containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"../containerContents/documentDiscovery\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\n\nexport type { LocalProjectionView } from \"../../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n for (const [domainScope, entry] of this.entriesByScope) {\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n disposeDomainSyncCoordinator(domainScope);\n }\n this.entriesByScope.clear();\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n service.start();\n\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n return entry;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) =>\n getOrCreateDomainSyncCoordinator(domainScope).registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: async () => {\n await store.getContainerStore().refresh();\n },\n refreshRootTree: async () => {\n await store.getContainerStore().refreshRootLane();\n },\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport function createDeviceFirstWorkflowRuntime(\n runtimeService: InternalRuntime,\n): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n runtimeService.workflowInput(),\n runtimeService.adoptRootContainer,\n );\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,mCAAmC,EACnC,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,mCAAmC,EACnC,qCAAqC,EACrC,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,GAGhC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,EAG3B,yBAAyB,GAC1B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,kCAAkC,EAAE,MAAM,+EAA+E,CAAC;AACnI,OAAO,EAAE,oCAAoC,EAAE,MAAM,2EAA2E,CAAC;AACjI,OAAO,EAEL,uCAAuC,EACvC,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAElG,OAAO,EAAE,qCAAqC,EAAE,MAAM,iCAAiC,CAAC;AAgCxF,MAAM,UAAU,iBAAiB,CAC/B,cAA+B,EAC/B,iBAAoC;IAEpC,OAAO,IAAI,kBAAkB,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;AACnE,CAAC;AASD,SAAS,8BAA8B,CACrC,cAA+B,EAC/B,WAA8C;IAO9C,OAAO;QACL,wBAAwB,EAAE,CAAC,WAAW,EAAE,EAAE;YACxC,MAAM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,EAAE,0BAA0B;YAC5C,qEAAqE;YACrE,wEAAwE;YACxE,QAAQ,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAC3B,wBAAwB,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC;SACnE,CAAC;IACJ,CAAC;CACF;AAED,8EAA8E;AAC9E,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA8C,EAC9C,OAAe,EACf,KAAc;IAEd,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,cAA+B;IAE/B,OAAO,2CAA2C,CAChD,cAAc,CAAC,aAAa,EAAE,EAC9B,cAAc,CAAC,kBAAkB,CAClC,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n disposeDomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../../stores/container-contents\";\nimport { openDocumentStore } from \"../../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../../sync/reconciliation\";\nimport { listAllContainerDocumentIdsFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../../workflows/container-contents/documentPriming/documentHydrationProbe\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n} from \"../../workflows/container-contents/runtime\";\nimport type { ContainerContents } from \"../containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"../containerContents/documentDiscovery\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\n\nexport type { LocalProjectionView } from \"../../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n for (const [domainScope, entry] of this.entriesByScope) {\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n disposeDomainSyncCoordinator(domainScope);\n }\n this.entriesByScope.clear();\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n service.start();\n\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n return entry;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) =>\n getOrCreateDomainSyncCoordinator(domainScope).registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: async () => {\n await store.getContainerStore().refresh();\n },\n refreshRootTree: async () => {\n await store.getContainerStore().refreshRootLane();\n },\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport function createDeviceFirstWorkflowRuntime(\n runtimeService: InternalRuntime,\n): ContainerContentsStoreWorkflowRuntime {\n return createContainerContentsStoreWorkflowRuntime(\n runtimeService.workflowInput(),\n runtimeService.adoptRootContainer,\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { OrganizationDataUsageResponse } from "../../internal/validators/response/index.js";
2
2
  import { type RootDataUsageApi, type RootDataUsageReportPage, type RootIdentitiesApi, type RootIdentitiesPage, type RootIdentitiesQueryInput, type RootIdentityDetail, type RootIdentityOrganization, type RootOrganizationDetail, type RootOrganizationIdentitiesPage, type RootOrganizationPageQueryInput, type RootOrganizationsApi, type RootOrganizationsPage, type RootOrganizationsQueryInput, type RootRequestOutcome } from "../../workflows/root/index.js";
3
- import type { WorkflowRuntimeAuthInput, WorkflowRuntimeCryptoInput } from "../../workflows/runtimeInput.js";
3
+ import type { WorkflowRuntimeAuthInput, WorkflowRuntimeCryptoInput } from "../../workflows/shared/runtimeInput.js";
4
4
  import type { InternalRuntime } from "../runtime/workflowRuntime.js";
5
5
  import type { Session } from "../session/sessionTypes.js";
6
6
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,E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CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oBAAoB,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC7D,0BAA0B,EAAE,CAAC,cAAc,EAAE,KAAK,EAAE,EAAE,CACpD,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CACd,8BAA8B,CAAC,GAAG,EAAE,cAAc,EAAE,KAAK,CAAC,CAC3D;QACH,cAAc,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,kBAAkB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3E,yBAAyB,EAAE,CAAC,MAAM,EAAE,EAAE,CACpC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,6BAA6B,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9D,YAAY,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;KAC1E,CAAC;AACJ,CAAC","sourcesContent":["import type { OrganizationDataUsageResponse } from \"@tearleads/validators/response\";\nimport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootIdentitiesApi,\n type RootIdentitiesPage,\n type RootIdentitiesQueryInput,\n type RootIdentityDetail,\n type RootIdentityOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRequestOutcome,\n} from \"../../workflows/root\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n} from \"../../workflows/runtimeInput\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport type { Session } from \"../session/sessionTypes\";\n\n/**\n * Platform-operator lookups. Every call is refused locally unless the session\n * is authenticated and the server reported it as root at login; the API still\n * enforces root access on its own, so this gate only avoids doomed requests.\n */\ntype RootApi = RootIdentitiesApi & RootOrganizationsApi & RootDataUsageApi;\n\nexport interface Root {\n loadOrganizationDataUsage(\n organizationId: string,\n ): Promise<RootRequestOutcome<OrganizationDataUsageResponse>>;\n listDataUsageReport(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootDataUsageReportPage>>;\n listOrganizations(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationsPage>>;\n loadOrganization(\n organizationId: string,\n ): Promise<RootRequestOutcome<RootOrganizationDetail>>;\n listOrganizationIdentities(\n organizationId: string,\n query?: RootOrganizationPageQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationIdentitiesPage>>;\n /** Whether the current session may use the root surface at all. */\n readonly isAvailable: boolean;\n listIdentities(\n query?: RootIdentitiesQueryInput,\n ): Promise<RootRequestOutcome<RootIdentitiesPage>>;\n listIdentityOrganizations(\n userId: string,\n ): Promise<RootRequestOutcome<RootIdentityOrganization[]>>;\n loadIdentity(userId: string): Promise<RootRequestOutcome<RootIdentityDetail>>;\n}\n\n/**\n * What the facade needs from the runtime: change notifications, the current\n * auth snapshot, the signing identity (which can change or vanish without\n * touching the session), and the api client. Narrower than the full runtime\n * so tests can drive it with a fake.\n */\nexport interface RootRuntime {\n /** The session's current auth token; a new one marks a fresh login. */\n authToken(): string | null;\n subscribe(listener: () => void): () => void;\n workflowInput(): {\n readonly apiClient: RootApi;\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: Pick<WorkflowRuntimeCryptoInput, \"signingFingerprint\">;\n };\n}\n\n/** The SDK's internal runtime, narrowed to what the root facade observes. */\nexport function rootRuntimeOf(\n runtime: Pick<InternalRuntime, \"publicRuntime\" | \"workflowInput\">,\n session: Pick<Session, \"authToken\">,\n): RootRuntime {\n return {\n authToken: () => session.authToken,\n subscribe: (listener) => runtime.publicRuntime.subscribe(listener),\n workflowInput: () => runtime.workflowInput(),\n };\n}\n\nconst NOT_AVAILABLE: RootRequestOutcome<never> = {\n message: \"The current session is not a platform operator.\",\n ok: false,\n status: null,\n};\n\nconst SESSION_CHANGED: RootRequestOutcome<never> = {\n message: \"The session changed while the request was in flight.\",\n ok: false,\n status: null,\n};\n\nexport function createRoot(runtimeService: RootRuntime): Root {\n const principal = () => {\n const runtime = runtimeService.workflowInput();\n return {\n fingerprint: runtime.crypto.signingFingerprint,\n isAuthenticated: runtime.auth.isAuthenticated,\n isRoot: runtime.auth.isRoot === true,\n userId: runtime.auth.userId,\n };\n };\n\n // Root standing belongs to the signing identity that authenticated, not to\n // whichever key pair is loaded now. The fingerprint is bound whenever a\n // login completes, which is observable as a new auth token carrying the\n // server's verdict, or when the session first becomes root. A principal\n // change without a new token (a key swap while the old token lingers)\n // unbinds root until the next login. Every principal change is also\n // counted as it happens, so a round trip such as logout then login, or a\n // switch to another identity and back, is still two changes even though\n // the endpoints match; a token renewal alone changes no principal, so a\n // retried lookup is still returned.\n let observed = principal();\n let observedToken = runtimeService.authToken();\n let boundFingerprint: string | null =\n observed.isAuthenticated && observed.isRoot ? observed.fingerprint : null;\n let lifecycle = 0;\n runtimeService.subscribe(() => {\n const next = principal();\n const token = runtimeService.authToken();\n const freshToken = token !== null && token !== observedToken;\n const wasRoot = observed.isAuthenticated && observed.isRoot;\n const isRootNow = next.isAuthenticated && next.isRoot;\n const changed =\n next.fingerprint !== observed.fingerprint ||\n next.isAuthenticated !== observed.isAuthenticated ||\n next.isRoot !== observed.isRoot ||\n next.userId !== observed.userId;\n if (changed) {\n lifecycle += 1;\n }\n if (!isRootNow) {\n boundFingerprint = null;\n } else if (freshToken || !wasRoot) {\n boundFingerprint = next.fingerprint;\n } else if (changed) {\n boundFingerprint = null;\n }\n observed = next;\n observedToken = token;\n });\n\n const activeApi = (): RootApi | null => {\n const runtime = runtimeService.workflowInput();\n return runtime.auth.isAuthenticated &&\n runtime.auth.isRoot === true &&\n boundFingerprint !== null &&\n runtime.crypto.signingFingerprint === boundFingerprint\n ? runtime.apiClient\n : null;\n };\n\n const guarded = async <Data>(\n request: (api: RootApi) => Promise<RootRequestOutcome<Data>>,\n ): Promise<RootRequestOutcome<Data>> => {\n const api = activeApi();\n if (!api) {\n return NOT_AVAILABLE;\n }\n const startedIn = lifecycle;\n const outcome = await request(api);\n if (activeApi() === null || lifecycle !== startedIn) {\n return SESSION_CHANGED;\n }\n return outcome;\n };\n\n return {\n get isAvailable() {\n return activeApi() !== null;\n },\n loadOrganizationDataUsage: (organizationId) =>\n guarded((api) => loadRootOrganizationDataUsage(api, organizationId)),\n listDataUsageReport: (query) =>\n guarded((api) => listRootDataUsageReport(api, query)),\n listOrganizations: (query) =>\n guarded((api) => listRootOrganizations(api, query)),\n loadOrganization: (organizationId) =>\n guarded((api) => loadRootOrganization(api, organizationId)),\n listOrganizationIdentities: (organizationId, query) =>\n guarded((api) =>\n listRootOrganizationIdentities(api, organizationId, query),\n ),\n listIdentities: (query) => guarded((api) => listRootIdentities(api, query)),\n listIdentityOrganizations: (userId) =>\n guarded((api) => listRootIdentityOrganizations(api, userId)),\n loadIdentity: (userId) => guarded((api) => loadRootIdentity(api, userId)),\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAe9B,MAAM,sBAAsB,CAAC;AA4D9B,6EAA6E;AAC7E,MAAM,UAAU,aAAa,CAC3B,OAAiE,EACjE,OAAmC;IAEnC,OAAO;QACL,SAAS,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,SAAS;QAClC,SAAS,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,CAA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CAC3D;QACH,cAAc,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,kBAAkB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3E,yBAAyB,EAAE,CAAC,MAAM,EAAE,EAAE,CACpC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,6BAA6B,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9D,YAAY,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;KAC1E,CAAC;AACJ,CAAC","sourcesContent":["import type { OrganizationDataUsageResponse } from \"@tearleads/validators/response\";\nimport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootIdentitiesApi,\n type RootIdentitiesPage,\n type RootIdentitiesQueryInput,\n type RootIdentityDetail,\n type RootIdentityOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n type RootRequestOutcome,\n} from \"../../workflows/root\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport type { Session } from \"../session/sessionTypes\";\n\n/**\n * Platform-operator lookups. Every call is refused locally unless the session\n * is authenticated and the server reported it as root at login; the API still\n * enforces root access on its own, so this gate only avoids doomed requests.\n */\ntype RootApi = RootIdentitiesApi & RootOrganizationsApi & RootDataUsageApi;\n\nexport interface Root {\n loadOrganizationDataUsage(\n organizationId: string,\n ): Promise<RootRequestOutcome<OrganizationDataUsageResponse>>;\n listDataUsageReport(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootDataUsageReportPage>>;\n listOrganizations(\n query?: RootOrganizationsQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationsPage>>;\n loadOrganization(\n organizationId: string,\n ): Promise<RootRequestOutcome<RootOrganizationDetail>>;\n listOrganizationIdentities(\n organizationId: string,\n query?: RootOrganizationPageQueryInput,\n ): Promise<RootRequestOutcome<RootOrganizationIdentitiesPage>>;\n /** Whether the current session may use the root surface at all. */\n readonly isAvailable: boolean;\n listIdentities(\n query?: RootIdentitiesQueryInput,\n ): Promise<RootRequestOutcome<RootIdentitiesPage>>;\n listIdentityOrganizations(\n userId: string,\n ): Promise<RootRequestOutcome<RootIdentityOrganization[]>>;\n loadIdentity(userId: string): Promise<RootRequestOutcome<RootIdentityDetail>>;\n}\n\n/**\n * What the facade needs from the runtime: change notifications, the current\n * auth snapshot, the signing identity (which can change or vanish without\n * touching the session), and the api client. Narrower than the full runtime\n * so tests can drive it with a fake.\n */\nexport interface RootRuntime {\n /** The session's current auth token; a new one marks a fresh login. */\n authToken(): string | null;\n subscribe(listener: () => void): () => void;\n workflowInput(): {\n readonly apiClient: RootApi;\n readonly auth: WorkflowRuntimeAuthInput;\n readonly crypto: Pick<WorkflowRuntimeCryptoInput, \"signingFingerprint\">;\n };\n}\n\n/** The SDK's internal runtime, narrowed to what the root facade observes. */\nexport function rootRuntimeOf(\n runtime: Pick<InternalRuntime, \"publicRuntime\" | \"workflowInput\">,\n session: Pick<Session, \"authToken\">,\n): RootRuntime {\n return {\n authToken: () => session.authToken,\n subscribe: (listener) => runtime.publicRuntime.subscribe(listener),\n workflowInput: () => runtime.workflowInput(),\n };\n}\n\nconst NOT_AVAILABLE: RootRequestOutcome<never> = {\n message: \"The current session is not a platform operator.\",\n ok: false,\n status: null,\n};\n\nconst SESSION_CHANGED: RootRequestOutcome<never> = {\n message: \"The session changed while the request was in flight.\",\n ok: false,\n status: null,\n};\n\nexport function createRoot(runtimeService: RootRuntime): Root {\n const principal = () => {\n const runtime = runtimeService.workflowInput();\n return {\n fingerprint: runtime.crypto.signingFingerprint,\n isAuthenticated: runtime.auth.isAuthenticated,\n isRoot: runtime.auth.isRoot === true,\n userId: runtime.auth.userId,\n };\n };\n\n // Root standing belongs to the signing identity that authenticated, not to\n // whichever key pair is loaded now. The fingerprint is bound whenever a\n // login completes, which is observable as a new auth token carrying the\n // server's verdict, or when the session first becomes root. A principal\n // change without a new token (a key swap while the old token lingers)\n // unbinds root until the next login. Every principal change is also\n // counted as it happens, so a round trip such as logout then login, or a\n // switch to another identity and back, is still two changes even though\n // the endpoints match; a token renewal alone changes no principal, so a\n // retried lookup is still returned.\n let observed = principal();\n let observedToken = runtimeService.authToken();\n let boundFingerprint: string | null =\n observed.isAuthenticated && observed.isRoot ? observed.fingerprint : null;\n let lifecycle = 0;\n runtimeService.subscribe(() => {\n const next = principal();\n const token = runtimeService.authToken();\n const freshToken = token !== null && token !== observedToken;\n const wasRoot = observed.isAuthenticated && observed.isRoot;\n const isRootNow = next.isAuthenticated && next.isRoot;\n const changed =\n next.fingerprint !== observed.fingerprint ||\n next.isAuthenticated !== observed.isAuthenticated ||\n next.isRoot !== observed.isRoot ||\n next.userId !== observed.userId;\n if (changed) {\n lifecycle += 1;\n }\n if (!isRootNow) {\n boundFingerprint = null;\n } else if (freshToken || !wasRoot) {\n boundFingerprint = next.fingerprint;\n } else if (changed) {\n boundFingerprint = null;\n }\n observed = next;\n observedToken = token;\n });\n\n const activeApi = (): RootApi | null => {\n const runtime = runtimeService.workflowInput();\n return runtime.auth.isAuthenticated &&\n runtime.auth.isRoot === true &&\n boundFingerprint !== null &&\n runtime.crypto.signingFingerprint === boundFingerprint\n ? runtime.apiClient\n : null;\n };\n\n const guarded = async <Data>(\n request: (api: RootApi) => Promise<RootRequestOutcome<Data>>,\n ): Promise<RootRequestOutcome<Data>> => {\n const api = activeApi();\n if (!api) {\n return NOT_AVAILABLE;\n }\n const startedIn = lifecycle;\n const outcome = await request(api);\n if (activeApi() === null || lifecycle !== startedIn) {\n return SESSION_CHANGED;\n }\n return outcome;\n };\n\n return {\n get isAvailable() {\n return activeApi() !== null;\n },\n loadOrganizationDataUsage: (organizationId) =>\n guarded((api) => loadRootOrganizationDataUsage(api, organizationId)),\n listDataUsageReport: (query) =>\n guarded((api) => listRootDataUsageReport(api, query)),\n listOrganizations: (query) =>\n guarded((api) => listRootOrganizations(api, query)),\n loadOrganization: (organizationId) =>\n guarded((api) => loadRootOrganization(api, organizationId)),\n listOrganizationIdentities: (organizationId, query) =>\n guarded((api) =>\n listRootOrganizationIdentities(api, organizationId, query),\n ),\n listIdentities: (query) => guarded((api) => listRootIdentities(api, query)),\n listIdentityOrganizations: (userId) =>\n guarded((api) => listRootIdentityOrganizations(api, userId)),\n loadIdentity: (userId) => guarded((api) => loadRootIdentity(api, userId)),\n };\n}\n"]}
@@ -6,7 +6,7 @@ import type { SecurityIncidentReporter } from "../../data/shared/securityInciden
6
6
  import { type LocalUserIdentityCandidate, type TrustedUserIdentityResolver, type TrustedUserIdentityService } from "../../data/trustedUserIdentity/index.js";
7
7
  import type { ContainerContentsRootAdopter } from "../../workflows/container-contents/runtime.js";
8
8
  import { type ProvisionedPrincipalHistoryPrimer } from "../../workflows/registration/provisionedPrincipalHistory.js";
9
- import type { WorkflowRuntimeGroups, WorkflowRuntimeUtilInput } from "../../workflows/runtimeInput.js";
9
+ import type { WorkflowRuntimeGroups, WorkflowRuntimeUtilInput } from "../../workflows/shared/runtimeInput.js";
10
10
  import type { Blobs } from "../blobs/index.js";
11
11
  import type { Identity } from "../identity/index.js";
12
12
  import type { Session } from "../session/sessionTypes.js";
@@ -1 +1 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AAIjG,OAAO,EAAgB,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,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents/runtime\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AAIjG,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,EAEhC,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAExC,OAAO,EACL,uCAAuC,GAExC,MAAM,0DAA0D,CAAC;AAWlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAI1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,iCAAiC,GAElC,MAAM,wBAAwB,CAAC;AAChC,OAAO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,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../../workflows/container-contents/runtime\";\nimport {\n createProvisionedPrincipalHistoryPrimer,\n type ProvisionedPrincipalHistoryPrimer,\n} from \"../../workflows/registration/provisionedPrincipalHistory\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n identityLinks: Pick<\n TrustedUserIdentityService,\n \"createLink\" | \"verifyLink\" | \"resolvePinned\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n readonly primeProvisionedPrincipalHistory: ProvisionedPrincipalHistoryPrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nfunction localIdentityCandidate(\n identity: Identity,\n): LocalUserIdentityCandidate | null {\n const { encapsulationKeyPair, signingKeyPair } = identity;\n if (!encapsulationKeyPair || !signingKeyPair) return null;\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedPrincipalHistoryPrimer {\n return createProvisionedPrincipalHistoryPrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null;\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: readyExecSql,\n getLocalIdentity: () => localIdentityCandidate(dependencies.identity),\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n primeProvisionedPrincipalHistory: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
package/index.d.ts CHANGED
@@ -9,7 +9,8 @@ export type { ContainerContentsSnapshot, ContainerContentsStoreRuntime, Containe
9
9
  export { createContainerContentsStore, createContainerContentsStoreState, createContainerContentsStoreSyncAgent, getOrCreateContainerContentsStore, isSystemContainerNode, requestContainerContentsDocumentPriming, subscribeToContainerContentsStore, updateContainerContentsSnapshot, updateContainerContentsStoreRuntime, } from "./stores/container-contents/index.js";
10
10
  export type { DocumentSnapshot, DocumentStoreFacade, DocumentStoreOpenOptions, DocumentStoreRelinkInput, DocumentStructuredFieldPatch, } from "./stores/documents/index.js";
11
11
  export { createDocumentStore, discardRegisteredDocumentLocalState, getOrCreateDocumentStore, openDocumentStore, requestDomainDocumentSync, subscribeToPersistedDocuments, } from "./stores/documents/index.js";
12
- export { type ClientDatabaseOptions, type ClientOptions, Tearleads, } from "./Tearleads.js";
12
+ export { Tearleads } from "./Tearleads.js";
13
+ export type { TearleadsDatabaseOptions, TearleadsOptions, } from "./TearleadsOptions.js";
13
14
  export type { BlobByteSource, BlobByteSourceInput, BlobBytes, BlobStore, EncryptedBlobStoreCipher, EncryptedBlobStoreKey, EncryptedBlobStoreOptions, WrapEncryptedBlobStoreOptions, } from "./workflows/blobs/index.js";
14
15
  export { blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, decryptDocumentAttachmentBlob, hydrateDocumentAttachmentBlobs, purgeOpfsBlobStore, readBlobByteSource, uploadDocumentAttachment, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
15
16
  export type { ContainerContentsRootAdopter, ContainerContentsRootAdoptionInput, ContainerContentsStoreWorkflowRuntime, ContainerContentsWorkflowRuntime, ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput, ContainerSystemSlotDefinition, PendingDownloadQueueItem, RecoveryFolder, } from "./workflows/container-contents/index.js";
package/index.js CHANGED
@@ -6,7 +6,7 @@ export { Blobs, createBrowserLocalKeyring, createBrowserLocalKeyringManifestStor
6
6
  export { addDocumentAttachments, createDocumentProjectorRegistry, createDocumentSignerDeviceId, DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, defaultDocumentProjectorRegistry, deriveStoredDocumentTitle, ensureDocumentAttachmentStructure, getDocumentAttachments, getDocumentClientProjectionTables, getStoredDocumentTypeLabel, getUntitledDocumentTitle, initializeStoredDocumentKind, projectStoredDocumentState, readStoredDocumentState, readStringDocumentField, resolveOpIdAttribution, sameDocumentAttachments, summarizeDocumentContributors, writerByPeerId, writeStoredDocumentFields, } from "./data/documents/index.js";
7
7
  export { createContainerContentsStore, createContainerContentsStoreState, createContainerContentsStoreSyncAgent, getOrCreateContainerContentsStore, isSystemContainerNode, requestContainerContentsDocumentPriming, subscribeToContainerContentsStore, updateContainerContentsSnapshot, updateContainerContentsStoreRuntime, } from "./stores/container-contents/index.js";
8
8
  export { createDocumentStore, discardRegisteredDocumentLocalState, getOrCreateDocumentStore, openDocumentStore, requestDomainDocumentSync, subscribeToPersistedDocuments, } from "./stores/documents/index.js";
9
- export { Tearleads, } from "./Tearleads.js";
9
+ export { Tearleads } from "./Tearleads.js";
10
10
  export { blobByteSourceInputLength, createBlobByteSource, createBlobStore, createEncryptedBlobStore, createLazyEncryptedBlobStore, createMemoryBlobStore, decryptDocumentAttachmentBlob, hydrateDocumentAttachmentBlobs, purgeOpfsBlobStore, readBlobByteSource, uploadDocumentAttachment, wrapEncryptedBlobStore, } from "./workflows/blobs/index.js";
11
11
  export { createContainerContentsDocumentsRuntime, createContainerContentsProjectionUserKeyResolver, createContainerContentsStoreWorkflowRuntime, createContainerContentsSyncLane, createContainerContentsWorkflowRuntime, createContainerParentSyncLane, createInitializedContainerMetadataDocument, defaultContainerContentsPersistence, deriveContainerSystemSlot, initializeDocumentLinksSchema, listBlobInfo, listDocumentLinkedContainerIds, loadContainerInfo, loadContainerSyncWatermark, loadDocumentAttributionRanges, loadDocumentInfo, replaceDocumentLinks, saveContainerSyncWatermark, syncedContainerDocumentObjectSyncState, } from "./workflows/container-contents/index.js";
12
12
  export { buildMaterializedContainerRekeyPlan, buildRootContainerCreatePlan, ContainerAuthorAccessError, ContainerKekRepairInaccessibleError, ContainerKekRepairRequiredError, ContainerKeyringOverrideStaleError, ContainerPathTooDeepError, classifyContainerWriteRefusal, containerWriterProjectionFromRekeyPlan, createRemoteContainer, fetchContainerKekLog, GroupShareNameMismatchError, HistoricalWrapUnavailableError, isProjectionVerificationCancelledError, moveRemoteContainer, rebuildKeyringEntriesFromLog, recoverKeyringEntryFromWraps, rekeyRemoteContainer, revokeRemoteContainer, rootContainerWriterProjectionFromCreatePlan, shareRemoteContainer, shareRemoteContainerWithGroup, } from "./workflows/containers/index.js";
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,2EAA2E;AAC3E,4FAA4F;AAC5F,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAkK/B,OAAO,EAEL,KAAK,EACL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,sCAAsC,EACtC,iBAAiB,EACjB,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,gCAAgC,EAChC,gCAAgC,EAChC,yBAAyB,EACzB,+BAA+B,EAC/B,0BAA0B,EAC1B,yBAAyB,EACzB,QAAQ,EACR,m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,EAClD,2CAA2C,EAC3C,gCAAgC,EAChC,qCAAqC,EACrC,+BAA+B,EAC/B,sBAAsB,EACtB,8BAA8B,EAC9B,uCAAuC,EACvC,uBAAuB,EACvB,8BAA8B,EAC9B,oCAAoC,EACpC,oCAAoC,EACpC,kCAAkC,EAClC,0CAA0C,EAC1C,6BAA6B,EAC7B,oCAAoC,EACpC,4BAA4B,EAC5B,8BAA8B,EAC9B,2BAA2B,EAC3B,8BAA8B,EAC9B,uCAAuC,EACvC,iCAAiC,EACjC,2BAA2B,EAC3B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,EAChC,sBAAsB,EACtB,gCAAgC,EAChC,0CAA0C,EAC1C,gCAAgC,EAChC,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AAWnC,OAAO,EACL,gCAAgC,EAChC,uCAAuC,EACvC,+BAA+B,EAC/B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAOhC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACrC,kCAAkC,EAClC,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAWlC,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAW9B,MAAM,kBAAkB,CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: verified identity links, read-only pins and device-first handles.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n ImportedOrganizationUser,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerDocumentObjectSyncState,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport {\n type ClientDatabaseOptions,\n type ClientOptions,\n Tearleads,\n} from \"./Tearleads\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\n readBlobByteSource,\n uploadDocumentAttachment,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n GroupShareNameMismatchError,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n importOrganizationUser,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,2EAA2E;AAC3E,4FAA4F;AAC5F,OAAO,EAGL,iBAAiB,GAElB,MAAM,uBAAuB,CAAC;AAkK/B,OAAO,EAEL,KAAK,EACL,yBAAyB,EACzB,sCAAsC,EACtC,gCAAgC,EAChC,sCAAsC,EACtC,iBAAiB,EACjB,wCAAwC,EACxC,kCAAkC,EAClC,kBAAkB,EAClB,2CAA2C,EAC3C,qCAAqC,EACrC,+BAA+B,EAC/B,gCAAgC,EAChC,gCAAgC,EAChC,yBAAyB,EACzB,+BAA+B,EAC/B,0BAA0B,EAC1B,yBAAyB,EACzB,QAAQ,EACR,mBAAmB,EAKnB,8BAA8B,EAC9B,2BAA2B,EAC3B,MAAM,EAGN,2BAA2B,EAC3B,8BAA8B,EAC9B,2BAA2B,EAC3B,mCAAmC,EACnC,6BAA6B,EAC7B,oBAAoB,EACpB,OAAO,EACP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AAoC,EACpC,kCAAkC,EAClC,0CAA0C,EAC1C,6BAA6B,EAC7B,oCAAoC,EACpC,4BAA4B,EAC5B,8BAA8B,EAC9B,2BAA2B,EAC3B,8BAA8B,EAC9B,uCAAuC,EACvC,iCAAiC,EACjC,2BAA2B,EAC3B,8BAA8B,EAC9B,mCAAmC,EACnC,gCAAgC,EAChC,sBAAsB,EACtB,gCAAgC,EAChC,0CAA0C,EAC1C,gCAAgC,EAChC,yBAAyB,EACzB,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AAWnC,OAAO,EACL,gCAAgC,EAChC,uCAAuC,EACvC,+BAA+B,EAC/B,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAOhC,OAAO,EACL,sBAAsB,EACtB,qCAAqC,EACrC,kCAAkC,EAClC,4BAA4B,EAC5B,gBAAgB,GACjB,MAAM,0BAA0B,CAAC;AAWlC,OAAO,EACL,uBAAuB,EACvB,kBAAkB,EAClB,6BAA6B,EAC7B,8BAA8B,EAC9B,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,EACpB,6BAA6B,GAW9B,MAAM,kBAAkB,CAAC;AAe1B,OAAO,EACL,oBAAoB,EACpB,gCAAgC,EAChC,gCAAgC,EAChC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,kBAAkB,CAAC","sourcesContent":["// SDK: verified identity links, read-only pins and device-first handles.\n// Authority loaders take exact heads, including cached citations. Obsolete\n// adapters are excluded; authored policy journals survive restart. See workflows/README.md.\nexport {\n type ApiRequestCounts,\n type ApiRequestEndpointCounts,\n ApiRequestMetrics,\n type ApiRequestMetricsSnapshot,\n} from \"@tearleads/api-client\";\nexport type {\n AbandonOrganizationPolicyMutationInput,\n AddOrganizationGroupUserInput,\n BlobInfo,\n BlobInfoAttachmentKind,\n BlobInfoDocumentReference,\n BlobInfoInput,\n BlobInfoList,\n BlobInfoSort,\n BlobInfoSortDirection,\n BlobInfoSortKey,\n BrowserLocalKeyringOptions,\n ContainerContents,\n ContainerContentsContextValue,\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerDocumentLinkInput,\n ContainerDocumentLinks,\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n ContainerDocumentQueries,\n ContainerDocumentSidebarRow,\n ContainerInfo,\n ContainerInfoInput,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n ContainerNode,\n ContainerShareAccessLevel,\n CreateOrganizationOptions,\n DatabaseListener,\n DatabaseOptions,\n DatabaseSnapshot,\n DatabaseStatus,\n DeviceFirst,\n DeviceFirstContainerContents,\n DiscardUnreadableOrganizationPolicyMutationInput,\n DocumentAttachmentStatus,\n DocumentAttachmentUpload,\n DocumentAttributionRangesInput,\n DocumentAttributionRangesPage,\n DocumentContextValue,\n DocumentInfo,\n DocumentInfoInput,\n DocumentList,\n DocumentSort,\n DocumentSortDirection,\n DocumentSortKey,\n DocumentStore,\n DocumentSubscriptionOptions,\n Documents,\n DocumentsRuntime,\n DomainScope,\n FileSaver,\n Identity,\n IdentityGenerationResult,\n IdentityKeyPackage,\n IdentityListener,\n IdentityOptions,\n IdentitySnapshot,\n ImportedOrganizationUser,\n IndexedDbLocalKeyringManifestStoreOptions,\n IndexedDbWrappingKeyKeystoreOptions,\n LinkDocumentToContainerInput,\n ListDocumentsInput,\n LocalKeyPurpose,\n LocalKeyring,\n LocalKeyringManifest,\n LocalKeyringManifestFormat,\n LocalKeyringManifestStorage,\n LocalKeyringManifestStore,\n LocalKeyringOptions,\n LocalKeyringPinCode,\n LocalKeyringScope,\n LocalKeyringSession,\n LocalOrganizationSummary,\n LocalProjectionReconciledDelta,\n LocalProjectionSnapshot,\n LocalProjectionView,\n LocalSecretContext,\n LocalStorageLocalKeyringManifestStoreOptions,\n Logger,\n MergeDocumentSummary,\n MoveDocumentToContainerInput,\n NetworkListener,\n NetworkMode,\n NetworkStatusSource,\n NormalizedLocalKeyringScope,\n OpenContainerDocumentInput,\n OpenDocumentInput,\n OpenDocumentOptions,\n OrganizationBilling,\n OrganizationBillingHistory,\n OrganizationBillingHistoryEntry,\n OrganizationBillingManagementUrl,\n OrganizationBillingView,\n OrganizationContainerGrant,\n OrganizationContainerGrants,\n OrganizationDataUsage,\n OrganizationDirectory,\n OrganizationDirectoryAndGroups,\n OrganizationDirectoryUser,\n OrganizationGrantRef,\n OrganizationGroupContainer,\n OrganizationGroupContainers,\n OrganizationGroupDetails,\n OrganizationGroupMember,\n OrganizationGroupMembers,\n OrganizationGroupMutationReceipt,\n OrganizationGroupPolicyHistory,\n OrganizationGroupSummary,\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n /** Verified organization display page with an optional older-page cursor. */\n OrganizationPolicyHistory,\n OrganizationPolicyHistoryEntry,\n OrganizationProfile,\n Organizations,\n OrganizationUserDetail,\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n // Persistence notifications distinguish placement changes from content saves.\n PersistedDocumentListener,\n PinCodeBrowserLocalKeyringOptions,\n PinCodeWrappingKeyKeystoreOptions,\n PurgeDocumentInput,\n PurgeDocumentResult,\n ReconciliationService,\n RemoveOrganizationGroupUserInput,\n ResolvedUserIdentity,\n SaveFileRequest,\n SecurityIncident,\n SecurityIncidentListener,\n SecurityIncidentObjectKind,\n SecurityIncidents,\n Session,\n SessionContext,\n SessionCreateOrganizationResult,\n SessionListener,\n SessionRecoverOrganizationResult,\n SessionRegistrationRefusal,\n SessionRegistrationResult,\n SessionSnapshot,\n SetActiveDocumentContainerInput,\n SetLinkedContainerIdsForDocument,\n UnlinkDocumentFromContainerInput,\n UnwrapLocalSecretInput,\n UserIdentities,\n UserSession,\n WrapLocalSecretInput,\n WrappedLocalSecretEnvelope,\n WrappedLocalSecretFormat,\n WrappingKeyHandle,\n WrappingKeyKeystore,\n WrappingKeyMaterialStorage,\n} from \"./client\";\nexport {\n type BlobStoreFactory,\n Blobs,\n createBrowserLocalKeyring,\n createBrowserLocalKeyringManifestStore,\n createBrowserNetworkStatusSource,\n createContainerDocumentObjectSyncState,\n createDomainScope,\n createIndexedDbLocalKeyringManifestStore,\n createIndexedDbWrappingKeyKeystore,\n createLocalKeyring,\n createLocalStorageLocalKeyringManifestStore,\n createMemoryLocalKeyringManifestStore,\n createMemoryWrappingKeyKeystore,\n createPinCodeBrowserLocalKeyring,\n createPinCodeWrappingKeyKeystore,\n createRevenueCatPurchases,\n createUnavailableDirectCheckout,\n createUnavailablePurchases,\n createWebViewLocalKeyring,\n Database,\n DEFAULT_DOCUMENT_ID,\n type DirectCheckoutAppearance,\n type DirectCheckoutCapability,\n type DirectCheckoutConfirmation,\n type DirectCheckoutSession,\n DirectCheckoutUnavailableError,\n decodeLocalKeyringSqliteKey,\n Events,\n type EventsListener,\n type EventsSnapshot,\n encodeLocalKeyringSqliteKey,\n enqueueReconciliationForEvents,\n IDENTITY_KEY_PACKAGE_FORMAT,\n isPinCodeWrappedLocalSecretEnvelope,\n LOCAL_KEYRING_MANIFEST_FORMAT,\n localKeyringScopeKey,\n Network,\n normalizeLocalKeyringScope,\n type PrincipalHistoryKeyProvider,\n type PrincipalHistoryKeyScope,\n PurchaseAbortedError,\n PurchaseAlreadyOwnedError,\n PurchaseCancelledError,\n PurchaseIdentityPendingError,\n PurchaseProviderStalledError,\n type PurchasesCapability,\n PurchasesUnavailableError,\n PurgedOrganizationRecoveryBillingRequiredError,\n parseLocalKeyringManifest,\n type RevenueCatBackend,\n type RevenueCatCustomerInfo,\n type RevenueCatPackage,\n type RevenueCatPurchasesConfig,\n SyncBillingGate,\n type SyncBillingGateListener,\n type SyncPurchaseResult,\n type SyncSubscriptionOption,\n serializeLocalKeyringManifest,\n WRAPPED_LOCAL_SECRET_FORMAT,\n} from \"./client\";\nexport type {\n DiscoveredDocumentInput,\n DocumentAttachment,\n DocumentClientProjectionDefinition,\n DocumentClientProjectionDeleteInput,\n DocumentClientProjectionSaveInput,\n DocumentFieldValidationIssue,\n DocumentProjection,\n DocumentProjectorDefinition,\n DocumentProjectorInput,\n DocumentProjectorRegistry,\n DocumentProjectorRegistryInput,\n DocumentRow,\n DocumentRowSummary,\n DocumentSummary,\n StoredDocumentKind,\n StoredDocumentState,\n StructuredDocumentMap,\n StructuredDocumentShape,\n StructuredDocumentText,\n ValidatedDocumentFields,\n} from \"./data/documents\";\nexport {\n addDocumentAttachments,\n createDocumentProjectorRegistry,\n createDocumentSignerDeviceId,\n DEFAULT_DOCUMENT_ACCESS_EPOCH,\n DEFAULT_DOCUMENT_KIND,\n defaultDocumentProjectorRegistry,\n deriveStoredDocumentTitle,\n ensureDocumentAttachmentStructure,\n getDocumentAttachments,\n getDocumentClientProjectionTables,\n getStoredDocumentTypeLabel,\n getUntitledDocumentTitle,\n initializeStoredDocumentKind,\n projectStoredDocumentState,\n readStoredDocumentState,\n readStringDocumentField,\n resolveOpIdAttribution,\n sameDocumentAttachments,\n summarizeDocumentContributors,\n writerByPeerId,\n writeStoredDocumentFields,\n} from \"./data/documents\";\nexport type {\n ContainerContentsSnapshot,\n ContainerContentsStoreRuntime,\n ContainerContentsStoreState,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n ContainerState,\n PurgeOptions,\n PurgeProgress,\n} from \"./stores/container-contents\";\nexport {\n createContainerContentsStore,\n createContainerContentsStoreState,\n createContainerContentsStoreSyncAgent,\n getOrCreateContainerContentsStore,\n isSystemContainerNode,\n requestContainerContentsDocumentPriming,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStoreRuntime,\n} from \"./stores/container-contents\";\nexport type {\n DocumentSnapshot,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentStoreRelinkInput,\n DocumentStructuredFieldPatch,\n} from \"./stores/documents\";\nexport {\n createDocumentStore,\n discardRegisteredDocumentLocalState,\n getOrCreateDocumentStore,\n openDocumentStore,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"./stores/documents\";\nexport { Tearleads } from \"./Tearleads\";\nexport type {\n TearleadsDatabaseOptions,\n TearleadsOptions,\n} from \"./TearleadsOptions\";\nexport type {\n BlobByteSource,\n BlobByteSourceInput,\n BlobBytes,\n BlobStore,\n EncryptedBlobStoreCipher,\n EncryptedBlobStoreKey,\n EncryptedBlobStoreOptions,\n WrapEncryptedBlobStoreOptions,\n} from \"./workflows/blobs\";\nexport {\n blobByteSourceInputLength,\n createBlobByteSource,\n createBlobStore,\n createEncryptedBlobStore,\n createLazyEncryptedBlobStore,\n createMemoryBlobStore,\n decryptDocumentAttachmentBlob,\n hydrateDocumentAttachmentBlobs,\n purgeOpfsBlobStore,\n readBlobByteSource,\n uploadDocumentAttachment,\n wrapEncryptedBlobStore,\n} from \"./workflows/blobs\";\nexport type {\n ContainerContentsRootAdopter,\n ContainerContentsRootAdoptionInput,\n ContainerContentsStoreWorkflowRuntime,\n ContainerContentsWorkflowRuntime,\n // Distinct from the canonical `ContainerDocumentLinkInput` (./client); the\n // documentQueries variant has a different shape, so it keeps a disambiguating\n // alias on the public surface.\n ContainerDocumentLinkInput as ContainerDocumentQueriesLinkInput,\n ContainerSystemSlotDefinition,\n PendingDownloadQueueItem,\n RecoveryFolder,\n} from \"./workflows/container-contents\";\nexport {\n createContainerContentsDocumentsRuntime,\n createContainerContentsProjectionUserKeyResolver,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsSyncLane,\n createContainerContentsWorkflowRuntime,\n createContainerParentSyncLane,\n createInitializedContainerMetadataDocument,\n defaultContainerContentsPersistence,\n deriveContainerSystemSlot,\n initializeDocumentLinksSchema,\n listBlobInfo,\n listDocumentLinkedContainerIds,\n loadContainerInfo,\n loadContainerSyncWatermark,\n loadDocumentAttributionRanges,\n loadDocumentInfo,\n replaceDocumentLinks,\n saveContainerSyncWatermark,\n syncedContainerDocumentObjectSyncState,\n} from \"./workflows/container-contents\";\nexport type {\n AggregatedContainerKekLog,\n ContainerMutationAuthor,\n ContainerReciteApi,\n ContainerWriteRefusal,\n KeyringRebuildResult,\n MaterializedContainerRekeyPlan,\n} from \"./workflows/containers\";\nexport {\n buildMaterializedContainerRekeyPlan,\n buildRootContainerCreatePlan,\n ContainerAuthorAccessError,\n ContainerKekRepairInaccessibleError,\n ContainerKekRepairRequiredError,\n ContainerKeyringOverrideStaleError,\n ContainerPathTooDeepError,\n classifyContainerWriteRefusal,\n containerWriterProjectionFromRekeyPlan,\n createRemoteContainer,\n fetchContainerKekLog,\n GroupShareNameMismatchError,\n HistoricalWrapUnavailableError,\n type HistoricalWrapUnavailableReason,\n isProjectionVerificationCancelledError,\n moveRemoteContainer,\n rebuildKeyringEntriesFromLog,\n recoverKeyringEntryFromWraps,\n rekeyRemoteContainer,\n revokeRemoteContainer,\n rootContainerWriterProjectionFromCreatePlan,\n shareRemoteContainer,\n shareRemoteContainerWithGroup,\n} from \"./workflows/containers\";\nexport type {\n DocumentRecord,\n DocumentSyncContainerRekeyBuilder,\n DocumentSyncPullContinuation,\n DocumentSyncUpdateIsolationError,\n DocumentsPersistence,\n DocumentsWorkflowRuntime,\n DocumentsWorkflowRuntimeInput,\n IncomingDocumentSyncUpdateValidator,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingUpdateInsert,\n PendingUpdateRecord,\n SyncRemoteDocumentInput,\n} from \"./workflows/documents\";\nexport {\n buildMaterializedDocumentCreatePlan,\n createDocumentProjectionUserKeyResolver,\n createDocumentsWorkflowRuntime,\n createRemoteDocument,\n DOCUMENT_SYNC_TRACE_FRAGMENT,\n DOCUMENT_SYNC_TRACE_PATTERN,\n DOCUMENTS_APP_KIND,\n DocumentRawHistoryUnavailableError,\n defaultDocumentsPersistence,\n deletePersistedDocument,\n isDatabaseUnavailableError,\n isDocumentSyncUpdateIsolationError,\n persistedDocumentCreateStateFromResponse,\n readPullContinuation,\n syncRemoteDocument,\n unwrapContainerKekPath,\n unwrapDocumentContentKeyTarget,\n validateDocumentSyncUpdateImports,\n} from \"./workflows/documents\";\n// Nominal identity constructors are available only through the testing subpath\n// for low-level runtime tests.\nexport type {\n AcknowledgedPrincipalCurrentInput,\n AcknowledgedPrincipalCurrentRetirement,\n AuthoredPrincipalMutation,\n OrganizationGroupPolicyHistoryEntry,\n OrganizationNativePurchaseEligibility,\n OrganizationPrincipalMemberChange,\n OrganizationPrincipalMemberChangeType,\n OrganizationPrincipalPolicyHistory,\n OrganizationPrincipalPolicyHistoryEntry,\n PrincipalMutationJournalContext,\n PrincipalMutationJournalScope,\n PrincipalMutationResponse,\n ReconcileOrganizationDataUsageInput,\n} from \"./workflows/organizations\";\nexport {\n abandonJournaledPrincipalMutation,\n addOrganizationGroupUser,\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n buildOrganizationGroupPolicyHistory,\n buildOrganizationProfileDocumentPatch,\n buildRosterProfileDocumentPatch,\n checkNativePurchaseEligibility,\n createInitializedRosterProfileDocument,\n createOrganizationGroup,\n DEFAULT_PERSONAL_ORGANIZATION_PROFILE_NAME,\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n discardUnreadableJournaledPrincipalMutation,\n GroupMembershipNameMismatchError,\n getOrganizationProfileDocumentLocalId,\n getRosterProfileDocumentLocalId,\n importOrganizationUser,\n loadLocalOrganizationDataUsage,\n loadLocalOrganizationDirectoryAndGroups,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n PendingPrincipalMutationError,\n PrincipalMutationOutcomeUnknownError,\n ROSTER_PROFILE_DOCUMENT_KIND,\n readJournaledPrincipalMutation,\n readOrganizationProfileName,\n reconcileOrganizationDataUsage,\n reconcileOrganizationDirectoryAndGroups,\n recoverJournaledPrincipalMutation,\n removeOrganizationGroupUser,\n resolveOrganizationBillingView,\n retainAcknowledgedPrincipalCurrents,\n revokeOrganizationContainerGrant,\n startOrganizationTrial,\n submitJournaledPrincipalMutation,\n subscribeOrganizationReadModelInvalidation,\n UnreadablePrincipalMutationError,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"./workflows/organizations\";\nexport type {\n AcknowledgedPrincipalPredecessor,\n CacheReferencedPrincipalPoliciesOptions,\n PrincipalHistoryProtectionLease,\n ProjectionPolicyHistoryRecoveryOptions,\n RecoveredPrincipalPolicyHistory,\n RecoveredScopedPrincipalPolicyHistory,\n RecoverPrincipalPolicyHistoryOptions,\n RecoverScopedPrincipalPolicyHistoryOptions,\n} from \"./workflows/principals\";\nexport {\n cacheReferencedPrincipalPolicies,\n captureAcknowledgedPrincipalPredecessor,\n PrincipalPolicyHistoryReadError,\n recoverPrincipalPolicyHistory,\n recoverProjectionPolicyHistory,\n recoverScopedPrincipalPolicyHistory,\n} from \"./workflows/principals\";\nexport type {\n InitialRootMetadataBootstrap,\n ProvisionedSystemContainerSpec,\n RegisterIdentityInput,\n RegistrationApi,\n} from \"./workflows/registration\";\nexport {\n bootstrapRootContainer,\n buildInitialOrganizationPolicyRequest,\n createInitialRootMetadataBootstrap,\n persistRegistrationBootstrap,\n registerIdentity,\n} from \"./workflows/registration\";\nexport type {\n RootIdentitiesApi,\n RootIdentitiesPage,\n RootIdentitiesQueryInput,\n RootIdentity,\n RootIdentityDetail,\n RootIdentityOrganization,\n RootIdentitySession,\n RootRequestOutcome,\n} from \"./workflows/root\";\nexport {\n listRootDataUsageReport,\n listRootIdentities,\n listRootIdentityOrganizations,\n listRootOrganizationIdentities,\n listRootOrganizations,\n loadRootIdentity,\n loadRootOrganization,\n loadRootOrganizationDataUsage,\n type RootDataUsageApi,\n type RootDataUsageReportPage,\n type RootOrganization,\n type RootOrganizationDetail,\n type RootOrganizationIdentitiesPage,\n type RootOrganizationIdentity,\n type RootOrganizationPageQueryInput,\n type RootOrganizationsApi,\n type RootOrganizationsPage,\n type RootOrganizationsQueryInput,\n} from \"./workflows/root\";\nexport type {\n ClearRemoteSyncStateResult,\n DomainSyncCoordinator,\n DomainSyncSnapshot,\n RemoteResetInput,\n RemoteResetReplacement,\n SyncIdleOptions,\n SyncLane,\n SyncLaneConfig,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./workflows/sync\";\nexport {\n clearRemoteSyncState,\n getDomainSyncCoordinatorSnapshot,\n getOrCreateDomainSyncCoordinator,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"./workflows/sync\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.60",
3
+ "version": "0.1.62",
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": {
@@ -1,4 +1,4 @@
1
- import { installContainerMetadataRecord, persistContainerMetadataStateFromRuntime, } from "../../workflows/container-contents/metadata.js";
1
+ import { installContainerMetadataRecord, persistContainerMetadataStateFromRuntime, } from "../../workflows/container-contents/metadata/index.js";
2
2
  import { removeMissingContainerState } from "./missingContainerState.js";
3
3
  import { updateContainerContentsSnapshot } from "./state.js";
4
4
  export async function persistContainerState(state, containerState, options = {}) {
@@ -1,6 +1,6 @@
1
- import { primeDocumentsForContainerSubtree, primeDocumentsForLoadedRoots, } from "../../workflows/container-contents/documentPriming.js";
1
+ import { primeDocumentsForContainerSubtree, primeDocumentsForLoadedRoots, } from "../../workflows/container-contents/documentPriming/index.js";
2
+ import { recoverStaleSessionRoot } from "../../workflows/container-contents/recovery/staleRootRecovery.js";
2
3
  import { createContainerContentsDocumentsRuntime, } from "../../workflows/container-contents/runtime.js";
3
- import { recoverStaleSessionRoot } from "../../workflows/container-contents/staleRootRecovery.js";
4
4
  import { isDatabaseUnavailableError } from "../../workflows/container-contents/syncLane.js";
5
5
  import { openDocumentStore } from "../documents/index.js";
6
6
  import { getContainerContentsStoreLogLabel } from "./logLabel.js";