@powerhousedao/reactor 6.0.0-staging.3 → 6.0.0

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 (469) hide show
  1. package/dist/index.d.ts +4667 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +10146 -0
  4. package/dist/index.js.map +1 -0
  5. package/package.json +23 -15
  6. package/dist/src/actions/index.d.ts +0 -24
  7. package/dist/src/actions/index.d.ts.map +0 -1
  8. package/dist/src/actions/index.js +0 -76
  9. package/dist/src/actions/index.js.map +0 -1
  10. package/dist/src/cache/buffer/ring-buffer.d.ts +0 -37
  11. package/dist/src/cache/buffer/ring-buffer.d.ts.map +0 -1
  12. package/dist/src/cache/buffer/ring-buffer.js +0 -69
  13. package/dist/src/cache/buffer/ring-buffer.js.map +0 -1
  14. package/dist/src/cache/collection-membership-cache.d.ts +0 -13
  15. package/dist/src/cache/collection-membership-cache.d.ts.map +0 -1
  16. package/dist/src/cache/collection-membership-cache.js +0 -33
  17. package/dist/src/cache/collection-membership-cache.js.map +0 -1
  18. package/dist/src/cache/document-meta-cache-types.d.ts +0 -114
  19. package/dist/src/cache/document-meta-cache-types.d.ts.map +0 -1
  20. package/dist/src/cache/document-meta-cache-types.js +0 -2
  21. package/dist/src/cache/document-meta-cache-types.js.map +0 -1
  22. package/dist/src/cache/document-meta-cache.d.ts +0 -30
  23. package/dist/src/cache/document-meta-cache.d.ts.map +0 -1
  24. package/dist/src/cache/document-meta-cache.js +0 -129
  25. package/dist/src/cache/document-meta-cache.js.map +0 -1
  26. package/dist/src/cache/index.d.ts +0 -3
  27. package/dist/src/cache/index.d.ts.map +0 -1
  28. package/dist/src/cache/index.js +0 -2
  29. package/dist/src/cache/index.js.map +0 -1
  30. package/dist/src/cache/kysely-operation-index.d.ts +0 -20
  31. package/dist/src/cache/kysely-operation-index.d.ts.map +0 -1
  32. package/dist/src/cache/kysely-operation-index.js +0 -345
  33. package/dist/src/cache/kysely-operation-index.js.map +0 -1
  34. package/dist/src/cache/kysely-write-cache.d.ts +0 -141
  35. package/dist/src/cache/kysely-write-cache.d.ts.map +0 -1
  36. package/dist/src/cache/kysely-write-cache.js +0 -411
  37. package/dist/src/cache/kysely-write-cache.js.map +0 -1
  38. package/dist/src/cache/lru/lru-tracker.d.ts +0 -15
  39. package/dist/src/cache/lru/lru-tracker.d.ts.map +0 -1
  40. package/dist/src/cache/lru/lru-tracker.js +0 -96
  41. package/dist/src/cache/lru/lru-tracker.js.map +0 -1
  42. package/dist/src/cache/operation-index-types.d.ts +0 -64
  43. package/dist/src/cache/operation-index-types.d.ts.map +0 -1
  44. package/dist/src/cache/operation-index-types.js +0 -4
  45. package/dist/src/cache/operation-index-types.js.map +0 -1
  46. package/dist/src/cache/write/interfaces.d.ts +0 -88
  47. package/dist/src/cache/write/interfaces.d.ts.map +0 -1
  48. package/dist/src/cache/write/interfaces.js +0 -2
  49. package/dist/src/cache/write/interfaces.js.map +0 -1
  50. package/dist/src/cache/write-cache-types.d.ts +0 -42
  51. package/dist/src/cache/write-cache-types.d.ts.map +0 -1
  52. package/dist/src/cache/write-cache-types.js +0 -2
  53. package/dist/src/cache/write-cache-types.js.map +0 -1
  54. package/dist/src/client/reactor-client.d.ts +0 -120
  55. package/dist/src/client/reactor-client.d.ts.map +0 -1
  56. package/dist/src/client/reactor-client.js +0 -497
  57. package/dist/src/client/reactor-client.js.map +0 -1
  58. package/dist/src/client/types.d.ts +0 -260
  59. package/dist/src/client/types.d.ts.map +0 -1
  60. package/dist/src/client/types.js +0 -14
  61. package/dist/src/client/types.js.map +0 -1
  62. package/dist/src/core/reactor-builder.d.ts +0 -63
  63. package/dist/src/core/reactor-builder.d.ts.map +0 -1
  64. package/dist/src/core/reactor-builder.js +0 -306
  65. package/dist/src/core/reactor-builder.js.map +0 -1
  66. package/dist/src/core/reactor-client-builder.d.ts +0 -50
  67. package/dist/src/core/reactor-client-builder.d.ts.map +0 -1
  68. package/dist/src/core/reactor-client-builder.js +0 -132
  69. package/dist/src/core/reactor-client-builder.js.map +0 -1
  70. package/dist/src/core/reactor.d.ts +0 -56
  71. package/dist/src/core/reactor.d.ts.map +0 -1
  72. package/dist/src/core/reactor.js +0 -640
  73. package/dist/src/core/reactor.js.map +0 -1
  74. package/dist/src/core/types.d.ts +0 -312
  75. package/dist/src/core/types.d.ts.map +0 -1
  76. package/dist/src/core/types.js +0 -2
  77. package/dist/src/core/types.js.map +0 -1
  78. package/dist/src/core/utils.d.ts +0 -95
  79. package/dist/src/core/utils.d.ts.map +0 -1
  80. package/dist/src/core/utils.js +0 -225
  81. package/dist/src/core/utils.js.map +0 -1
  82. package/dist/src/events/event-bus.d.ts +0 -8
  83. package/dist/src/events/event-bus.d.ts.map +0 -1
  84. package/dist/src/events/event-bus.js +0 -53
  85. package/dist/src/events/event-bus.js.map +0 -1
  86. package/dist/src/events/interfaces.d.ts +0 -27
  87. package/dist/src/events/interfaces.d.ts.map +0 -1
  88. package/dist/src/events/interfaces.js +0 -2
  89. package/dist/src/events/interfaces.js.map +0 -1
  90. package/dist/src/events/types.d.ts +0 -92
  91. package/dist/src/events/types.d.ts.map +0 -1
  92. package/dist/src/events/types.js +0 -30
  93. package/dist/src/events/types.js.map +0 -1
  94. package/dist/src/executor/document-action-handler.d.ts +0 -37
  95. package/dist/src/executor/document-action-handler.d.ts.map +0 -1
  96. package/dist/src/executor/document-action-handler.js +0 -356
  97. package/dist/src/executor/document-action-handler.js.map +0 -1
  98. package/dist/src/executor/interfaces.d.ts +0 -49
  99. package/dist/src/executor/interfaces.d.ts.map +0 -1
  100. package/dist/src/executor/interfaces.js +0 -2
  101. package/dist/src/executor/interfaces.js.map +0 -1
  102. package/dist/src/executor/signature-verifier.d.ts +0 -9
  103. package/dist/src/executor/signature-verifier.d.ts.map +0 -1
  104. package/dist/src/executor/signature-verifier.js +0 -70
  105. package/dist/src/executor/signature-verifier.js.map +0 -1
  106. package/dist/src/executor/simple-job-executor-manager.d.ts +0 -39
  107. package/dist/src/executor/simple-job-executor-manager.d.ts.map +0 -1
  108. package/dist/src/executor/simple-job-executor-manager.js +0 -345
  109. package/dist/src/executor/simple-job-executor-manager.js.map +0 -1
  110. package/dist/src/executor/simple-job-executor.d.ts +0 -40
  111. package/dist/src/executor/simple-job-executor.d.ts.map +0 -1
  112. package/dist/src/executor/simple-job-executor.js +0 -423
  113. package/dist/src/executor/simple-job-executor.js.map +0 -1
  114. package/dist/src/executor/types.d.ts +0 -91
  115. package/dist/src/executor/types.d.ts.map +0 -1
  116. package/dist/src/executor/types.js +0 -11
  117. package/dist/src/executor/types.js.map +0 -1
  118. package/dist/src/executor/util.d.ts +0 -84
  119. package/dist/src/executor/util.d.ts.map +0 -1
  120. package/dist/src/executor/util.js +0 -230
  121. package/dist/src/executor/util.js.map +0 -1
  122. package/dist/src/index.d.ts +0 -54
  123. package/dist/src/index.d.ts.map +0 -1
  124. package/dist/src/index.js +0 -62
  125. package/dist/src/index.js.map +0 -1
  126. package/dist/src/job-tracker/in-memory-job-tracker.d.ts +0 -26
  127. package/dist/src/job-tracker/in-memory-job-tracker.d.ts.map +0 -1
  128. package/dist/src/job-tracker/in-memory-job-tracker.js +0 -114
  129. package/dist/src/job-tracker/in-memory-job-tracker.js.map +0 -1
  130. package/dist/src/job-tracker/index.d.ts +0 -3
  131. package/dist/src/job-tracker/index.d.ts.map +0 -1
  132. package/dist/src/job-tracker/index.js +0 -2
  133. package/dist/src/job-tracker/index.js.map +0 -1
  134. package/dist/src/job-tracker/interfaces.d.ts +0 -41
  135. package/dist/src/job-tracker/interfaces.d.ts.map +0 -1
  136. package/dist/src/job-tracker/interfaces.js +0 -2
  137. package/dist/src/job-tracker/interfaces.js.map +0 -1
  138. package/dist/src/logging/console.d.ts +0 -2
  139. package/dist/src/logging/console.d.ts.map +0 -1
  140. package/dist/src/logging/console.js +0 -2
  141. package/dist/src/logging/console.js.map +0 -1
  142. package/dist/src/logging/types.d.ts +0 -2
  143. package/dist/src/logging/types.d.ts.map +0 -1
  144. package/dist/src/logging/types.js +0 -2
  145. package/dist/src/logging/types.js.map +0 -1
  146. package/dist/src/processors/index.d.ts +0 -3
  147. package/dist/src/processors/index.d.ts.map +0 -1
  148. package/dist/src/processors/index.js +0 -2
  149. package/dist/src/processors/index.js.map +0 -1
  150. package/dist/src/processors/processor-manager.d.ts +0 -38
  151. package/dist/src/processors/processor-manager.d.ts.map +0 -1
  152. package/dist/src/processors/processor-manager.js +0 -165
  153. package/dist/src/processors/processor-manager.js.map +0 -1
  154. package/dist/src/processors/relational/types.d.ts +0 -2
  155. package/dist/src/processors/relational/types.d.ts.map +0 -1
  156. package/dist/src/processors/relational/types.js +0 -2
  157. package/dist/src/processors/relational/types.js.map +0 -1
  158. package/dist/src/processors/relational/utils.d.ts +0 -2
  159. package/dist/src/processors/relational/utils.d.ts.map +0 -1
  160. package/dist/src/processors/relational/utils.js +0 -2
  161. package/dist/src/processors/relational/utils.js.map +0 -1
  162. package/dist/src/processors/utils.d.ts +0 -10
  163. package/dist/src/processors/utils.d.ts.map +0 -1
  164. package/dist/src/processors/utils.js +0 -59
  165. package/dist/src/processors/utils.js.map +0 -1
  166. package/dist/src/queue/interfaces.d.ts +0 -103
  167. package/dist/src/queue/interfaces.d.ts.map +0 -1
  168. package/dist/src/queue/interfaces.js +0 -2
  169. package/dist/src/queue/interfaces.js.map +0 -1
  170. package/dist/src/queue/job-execution-handle.d.ts +0 -28
  171. package/dist/src/queue/job-execution-handle.d.ts.map +0 -1
  172. package/dist/src/queue/job-execution-handle.js +0 -71
  173. package/dist/src/queue/job-execution-handle.js.map +0 -1
  174. package/dist/src/queue/queue.d.ts +0 -110
  175. package/dist/src/queue/queue.d.ts.map +0 -1
  176. package/dist/src/queue/queue.js +0 -493
  177. package/dist/src/queue/queue.js.map +0 -1
  178. package/dist/src/queue/types.d.ts +0 -74
  179. package/dist/src/queue/types.d.ts.map +0 -1
  180. package/dist/src/queue/types.js +0 -19
  181. package/dist/src/queue/types.js.map +0 -1
  182. package/dist/src/read-models/base-read-model.d.ts +0 -60
  183. package/dist/src/read-models/base-read-model.d.ts.map +0 -1
  184. package/dist/src/read-models/base-read-model.js +0 -143
  185. package/dist/src/read-models/base-read-model.js.map +0 -1
  186. package/dist/src/read-models/coordinator.d.ts +0 -39
  187. package/dist/src/read-models/coordinator.d.ts.map +0 -1
  188. package/dist/src/read-models/coordinator.js +0 -72
  189. package/dist/src/read-models/coordinator.js.map +0 -1
  190. package/dist/src/read-models/document-view.d.ts +0 -27
  191. package/dist/src/read-models/document-view.d.ts.map +0 -1
  192. package/dist/src/read-models/document-view.js +0 -457
  193. package/dist/src/read-models/document-view.js.map +0 -1
  194. package/dist/src/read-models/interfaces.d.ts +0 -29
  195. package/dist/src/read-models/interfaces.d.ts.map +0 -1
  196. package/dist/src/read-models/interfaces.js +0 -2
  197. package/dist/src/read-models/interfaces.js.map +0 -1
  198. package/dist/src/read-models/types.d.ts +0 -47
  199. package/dist/src/read-models/types.d.ts.map +0 -1
  200. package/dist/src/read-models/types.js +0 -2
  201. package/dist/src/read-models/types.js.map +0 -1
  202. package/dist/src/registry/document-model-resolver.d.ts +0 -29
  203. package/dist/src/registry/document-model-resolver.d.ts.map +0 -1
  204. package/dist/src/registry/document-model-resolver.js +0 -81
  205. package/dist/src/registry/document-model-resolver.js.map +0 -1
  206. package/dist/src/registry/implementation.d.ts +0 -74
  207. package/dist/src/registry/implementation.d.ts.map +0 -1
  208. package/dist/src/registry/implementation.js +0 -226
  209. package/dist/src/registry/implementation.js.map +0 -1
  210. package/dist/src/registry/index.d.ts +0 -5
  211. package/dist/src/registry/index.d.ts.map +0 -1
  212. package/dist/src/registry/index.js +0 -3
  213. package/dist/src/registry/index.js.map +0 -1
  214. package/dist/src/registry/interfaces.d.ts +0 -108
  215. package/dist/src/registry/interfaces.d.ts.map +0 -1
  216. package/dist/src/registry/interfaces.js +0 -2
  217. package/dist/src/registry/interfaces.js.map +0 -1
  218. package/dist/src/shared/awaiter.d.ts +0 -35
  219. package/dist/src/shared/awaiter.d.ts.map +0 -1
  220. package/dist/src/shared/awaiter.js +0 -123
  221. package/dist/src/shared/awaiter.js.map +0 -1
  222. package/dist/src/shared/collect-all-pages.d.ts +0 -7
  223. package/dist/src/shared/collect-all-pages.d.ts.map +0 -1
  224. package/dist/src/shared/collect-all-pages.js +0 -17
  225. package/dist/src/shared/collect-all-pages.js.map +0 -1
  226. package/dist/src/shared/consistency-tracker.d.ts +0 -48
  227. package/dist/src/shared/consistency-tracker.d.ts.map +0 -1
  228. package/dist/src/shared/consistency-tracker.js +0 -123
  229. package/dist/src/shared/consistency-tracker.js.map +0 -1
  230. package/dist/src/shared/drive-url.d.ts +0 -15
  231. package/dist/src/shared/drive-url.d.ts.map +0 -1
  232. package/dist/src/shared/drive-url.js +0 -17
  233. package/dist/src/shared/drive-url.js.map +0 -1
  234. package/dist/src/shared/errors.d.ts +0 -50
  235. package/dist/src/shared/errors.d.ts.map +0 -1
  236. package/dist/src/shared/errors.js +0 -93
  237. package/dist/src/shared/errors.js.map +0 -1
  238. package/dist/src/shared/factories.d.ts +0 -20
  239. package/dist/src/shared/factories.d.ts.map +0 -1
  240. package/dist/src/shared/factories.js +0 -41
  241. package/dist/src/shared/factories.js.map +0 -1
  242. package/dist/src/shared/types.d.ts +0 -161
  243. package/dist/src/shared/types.d.ts.map +0 -1
  244. package/dist/src/shared/types.js +0 -38
  245. package/dist/src/shared/types.js.map +0 -1
  246. package/dist/src/shared/utils.d.ts +0 -3
  247. package/dist/src/shared/utils.d.ts.map +0 -1
  248. package/dist/src/shared/utils.js +0 -8
  249. package/dist/src/shared/utils.js.map +0 -1
  250. package/dist/src/signer/passthrough-signer.d.ts +0 -12
  251. package/dist/src/signer/passthrough-signer.d.ts.map +0 -1
  252. package/dist/src/signer/passthrough-signer.js +0 -17
  253. package/dist/src/signer/passthrough-signer.js.map +0 -1
  254. package/dist/src/signer/types.d.ts +0 -17
  255. package/dist/src/signer/types.d.ts.map +0 -1
  256. package/dist/src/signer/types.js +0 -2
  257. package/dist/src/signer/types.js.map +0 -1
  258. package/dist/src/storage/index.d.ts +0 -4
  259. package/dist/src/storage/index.d.ts.map +0 -1
  260. package/dist/src/storage/index.js +0 -3
  261. package/dist/src/storage/index.js.map +0 -1
  262. package/dist/src/storage/interfaces.d.ts +0 -553
  263. package/dist/src/storage/interfaces.d.ts.map +0 -1
  264. package/dist/src/storage/interfaces.js +0 -29
  265. package/dist/src/storage/interfaces.js.map +0 -1
  266. package/dist/src/storage/kysely/document-indexer.d.ts +0 -29
  267. package/dist/src/storage/kysely/document-indexer.d.ts.map +0 -1
  268. package/dist/src/storage/kysely/document-indexer.js +0 -421
  269. package/dist/src/storage/kysely/document-indexer.js.map +0 -1
  270. package/dist/src/storage/kysely/keyframe-store.d.ts +0 -15
  271. package/dist/src/storage/kysely/keyframe-store.d.ts.map +0 -1
  272. package/dist/src/storage/kysely/keyframe-store.js +0 -64
  273. package/dist/src/storage/kysely/keyframe-store.js.map +0 -1
  274. package/dist/src/storage/kysely/store.d.ts +0 -17
  275. package/dist/src/storage/kysely/store.d.ts.map +0 -1
  276. package/dist/src/storage/kysely/store.js +0 -264
  277. package/dist/src/storage/kysely/store.js.map +0 -1
  278. package/dist/src/storage/kysely/sync-cursor-storage.d.ts +0 -13
  279. package/dist/src/storage/kysely/sync-cursor-storage.d.ts.map +0 -1
  280. package/dist/src/storage/kysely/sync-cursor-storage.js +0 -97
  281. package/dist/src/storage/kysely/sync-cursor-storage.js.map +0 -1
  282. package/dist/src/storage/kysely/sync-dead-letter-storage.d.ts +0 -17
  283. package/dist/src/storage/kysely/sync-dead-letter-storage.d.ts.map +0 -1
  284. package/dist/src/storage/kysely/sync-dead-letter-storage.js +0 -110
  285. package/dist/src/storage/kysely/sync-dead-letter-storage.js.map +0 -1
  286. package/dist/src/storage/kysely/sync-remote-storage.d.ts +0 -13
  287. package/dist/src/storage/kysely/sync-remote-storage.d.ts.map +0 -1
  288. package/dist/src/storage/kysely/sync-remote-storage.js +0 -133
  289. package/dist/src/storage/kysely/sync-remote-storage.js.map +0 -1
  290. package/dist/src/storage/kysely/types.d.ts +0 -157
  291. package/dist/src/storage/kysely/types.d.ts.map +0 -1
  292. package/dist/src/storage/kysely/types.js +0 -2
  293. package/dist/src/storage/kysely/types.js.map +0 -1
  294. package/dist/src/storage/migrations/001_create_operation_table.d.ts +0 -3
  295. package/dist/src/storage/migrations/001_create_operation_table.d.ts.map +0 -1
  296. package/dist/src/storage/migrations/001_create_operation_table.js +0 -41
  297. package/dist/src/storage/migrations/001_create_operation_table.js.map +0 -1
  298. package/dist/src/storage/migrations/002_create_keyframe_table.d.ts +0 -3
  299. package/dist/src/storage/migrations/002_create_keyframe_table.d.ts.map +0 -1
  300. package/dist/src/storage/migrations/002_create_keyframe_table.js +0 -27
  301. package/dist/src/storage/migrations/002_create_keyframe_table.js.map +0 -1
  302. package/dist/src/storage/migrations/003_create_document_table.d.ts +0 -3
  303. package/dist/src/storage/migrations/003_create_document_table.d.ts.map +0 -1
  304. package/dist/src/storage/migrations/003_create_document_table.js +0 -10
  305. package/dist/src/storage/migrations/003_create_document_table.js.map +0 -1
  306. package/dist/src/storage/migrations/004_create_document_relationship_table.d.ts +0 -3
  307. package/dist/src/storage/migrations/004_create_document_relationship_table.d.ts.map +0 -1
  308. package/dist/src/storage/migrations/004_create_document_relationship_table.js +0 -35
  309. package/dist/src/storage/migrations/004_create_document_relationship_table.js.map +0 -1
  310. package/dist/src/storage/migrations/005_create_indexer_state_table.d.ts +0 -3
  311. package/dist/src/storage/migrations/005_create_indexer_state_table.d.ts.map +0 -1
  312. package/dist/src/storage/migrations/005_create_indexer_state_table.js +0 -10
  313. package/dist/src/storage/migrations/005_create_indexer_state_table.js.map +0 -1
  314. package/dist/src/storage/migrations/006_create_document_snapshot_table.d.ts +0 -3
  315. package/dist/src/storage/migrations/006_create_document_snapshot_table.d.ts.map +0 -1
  316. package/dist/src/storage/migrations/006_create_document_snapshot_table.js +0 -49
  317. package/dist/src/storage/migrations/006_create_document_snapshot_table.js.map +0 -1
  318. package/dist/src/storage/migrations/007_create_slug_mapping_table.d.ts +0 -3
  319. package/dist/src/storage/migrations/007_create_slug_mapping_table.d.ts.map +0 -1
  320. package/dist/src/storage/migrations/007_create_slug_mapping_table.js +0 -24
  321. package/dist/src/storage/migrations/007_create_slug_mapping_table.js.map +0 -1
  322. package/dist/src/storage/migrations/008_create_view_state_table.d.ts +0 -3
  323. package/dist/src/storage/migrations/008_create_view_state_table.d.ts.map +0 -1
  324. package/dist/src/storage/migrations/008_create_view_state_table.js +0 -10
  325. package/dist/src/storage/migrations/008_create_view_state_table.js.map +0 -1
  326. package/dist/src/storage/migrations/009_create_operation_index_tables.d.ts +0 -3
  327. package/dist/src/storage/migrations/009_create_operation_index_tables.d.ts.map +0 -1
  328. package/dist/src/storage/migrations/009_create_operation_index_tables.js +0 -50
  329. package/dist/src/storage/migrations/009_create_operation_index_tables.js.map +0 -1
  330. package/dist/src/storage/migrations/010_create_sync_tables.d.ts +0 -3
  331. package/dist/src/storage/migrations/010_create_sync_tables.d.ts.map +0 -1
  332. package/dist/src/storage/migrations/010_create_sync_tables.js +0 -43
  333. package/dist/src/storage/migrations/010_create_sync_tables.js.map +0 -1
  334. package/dist/src/storage/migrations/011_add_cursor_type_column.d.ts +0 -3
  335. package/dist/src/storage/migrations/011_add_cursor_type_column.d.ts.map +0 -1
  336. package/dist/src/storage/migrations/011_add_cursor_type_column.js +0 -29
  337. package/dist/src/storage/migrations/011_add_cursor_type_column.js.map +0 -1
  338. package/dist/src/storage/migrations/012_add_source_remote_column.d.ts +0 -3
  339. package/dist/src/storage/migrations/012_add_source_remote_column.d.ts.map +0 -1
  340. package/dist/src/storage/migrations/012_add_source_remote_column.js +0 -7
  341. package/dist/src/storage/migrations/012_add_source_remote_column.js.map +0 -1
  342. package/dist/src/storage/migrations/013_create_sync_dead_letters_table.d.ts +0 -3
  343. package/dist/src/storage/migrations/013_create_sync_dead_letters_table.d.ts.map +0 -1
  344. package/dist/src/storage/migrations/013_create_sync_dead_letters_table.js +0 -24
  345. package/dist/src/storage/migrations/013_create_sync_dead_letters_table.js.map +0 -1
  346. package/dist/src/storage/migrations/index.d.ts +0 -3
  347. package/dist/src/storage/migrations/index.d.ts.map +0 -1
  348. package/dist/src/storage/migrations/index.js +0 -3
  349. package/dist/src/storage/migrations/index.js.map +0 -1
  350. package/dist/src/storage/migrations/migrator.d.ts +0 -6
  351. package/dist/src/storage/migrations/migrator.d.ts.map +0 -1
  352. package/dist/src/storage/migrations/migrator.js +0 -84
  353. package/dist/src/storage/migrations/migrator.js.map +0 -1
  354. package/dist/src/storage/migrations/run-migrations.d.ts +0 -2
  355. package/dist/src/storage/migrations/run-migrations.d.ts.map +0 -1
  356. package/dist/src/storage/migrations/run-migrations.js +0 -58
  357. package/dist/src/storage/migrations/run-migrations.js.map +0 -1
  358. package/dist/src/storage/migrations/types.d.ts +0 -9
  359. package/dist/src/storage/migrations/types.d.ts.map +0 -1
  360. package/dist/src/storage/migrations/types.js +0 -2
  361. package/dist/src/storage/migrations/types.js.map +0 -1
  362. package/dist/src/storage/txn.d.ts +0 -15
  363. package/dist/src/storage/txn.d.ts.map +0 -1
  364. package/dist/src/storage/txn.js +0 -42
  365. package/dist/src/storage/txn.js.map +0 -1
  366. package/dist/src/subs/default-error-handler.d.ts +0 -13
  367. package/dist/src/subs/default-error-handler.d.ts.map +0 -1
  368. package/dist/src/subs/default-error-handler.js +0 -27
  369. package/dist/src/subs/default-error-handler.js.map +0 -1
  370. package/dist/src/subs/react-subscription-manager.d.ts +0 -45
  371. package/dist/src/subs/react-subscription-manager.d.ts.map +0 -1
  372. package/dist/src/subs/react-subscription-manager.js +0 -185
  373. package/dist/src/subs/react-subscription-manager.js.map +0 -1
  374. package/dist/src/subs/subscription-notification-read-model.d.ts +0 -18
  375. package/dist/src/subs/subscription-notification-read-model.d.ts.map +0 -1
  376. package/dist/src/subs/subscription-notification-read-model.js +0 -62
  377. package/dist/src/subs/subscription-notification-read-model.js.map +0 -1
  378. package/dist/src/subs/types.d.ts +0 -64
  379. package/dist/src/subs/types.d.ts.map +0 -1
  380. package/dist/src/subs/types.js +0 -2
  381. package/dist/src/subs/types.js.map +0 -1
  382. package/dist/src/sync/batch-aggregator.d.ts +0 -25
  383. package/dist/src/sync/batch-aggregator.d.ts.map +0 -1
  384. package/dist/src/sync/batch-aggregator.js +0 -94
  385. package/dist/src/sync/batch-aggregator.js.map +0 -1
  386. package/dist/src/sync/buffered-mailbox.d.ts +0 -36
  387. package/dist/src/sync/buffered-mailbox.d.ts.map +0 -1
  388. package/dist/src/sync/buffered-mailbox.js +0 -164
  389. package/dist/src/sync/buffered-mailbox.js.map +0 -1
  390. package/dist/src/sync/channels/gql-req-channel.d.ts +0 -125
  391. package/dist/src/sync/channels/gql-req-channel.d.ts.map +0 -1
  392. package/dist/src/sync/channels/gql-req-channel.js +0 -548
  393. package/dist/src/sync/channels/gql-req-channel.js.map +0 -1
  394. package/dist/src/sync/channels/gql-request-channel-factory.d.ts +0 -32
  395. package/dist/src/sync/channels/gql-request-channel-factory.d.ts.map +0 -1
  396. package/dist/src/sync/channels/gql-request-channel-factory.js +0 -105
  397. package/dist/src/sync/channels/gql-request-channel-factory.js.map +0 -1
  398. package/dist/src/sync/channels/gql-res-channel.d.ts +0 -25
  399. package/dist/src/sync/channels/gql-res-channel.d.ts.map +0 -1
  400. package/dist/src/sync/channels/gql-res-channel.js +0 -79
  401. package/dist/src/sync/channels/gql-res-channel.js.map +0 -1
  402. package/dist/src/sync/channels/gql-response-channel-factory.d.ts +0 -13
  403. package/dist/src/sync/channels/gql-response-channel-factory.d.ts.map +0 -1
  404. package/dist/src/sync/channels/gql-response-channel-factory.js +0 -14
  405. package/dist/src/sync/channels/gql-response-channel-factory.js.map +0 -1
  406. package/dist/src/sync/channels/index.d.ts +0 -8
  407. package/dist/src/sync/channels/index.d.ts.map +0 -1
  408. package/dist/src/sync/channels/index.js +0 -8
  409. package/dist/src/sync/channels/index.js.map +0 -1
  410. package/dist/src/sync/channels/interval-poll-timer.d.ts +0 -40
  411. package/dist/src/sync/channels/interval-poll-timer.d.ts.map +0 -1
  412. package/dist/src/sync/channels/interval-poll-timer.js +0 -123
  413. package/dist/src/sync/channels/interval-poll-timer.js.map +0 -1
  414. package/dist/src/sync/channels/poll-timer.d.ts +0 -14
  415. package/dist/src/sync/channels/poll-timer.d.ts.map +0 -1
  416. package/dist/src/sync/channels/poll-timer.js +0 -2
  417. package/dist/src/sync/channels/poll-timer.js.map +0 -1
  418. package/dist/src/sync/channels/utils.d.ts +0 -44
  419. package/dist/src/sync/channels/utils.d.ts.map +0 -1
  420. package/dist/src/sync/channels/utils.js +0 -161
  421. package/dist/src/sync/channels/utils.js.map +0 -1
  422. package/dist/src/sync/errors.d.ts +0 -10
  423. package/dist/src/sync/errors.d.ts.map +0 -1
  424. package/dist/src/sync/errors.js +0 -17
  425. package/dist/src/sync/errors.js.map +0 -1
  426. package/dist/src/sync/index.d.ts +0 -16
  427. package/dist/src/sync/index.d.ts.map +0 -1
  428. package/dist/src/sync/index.js +0 -11
  429. package/dist/src/sync/index.js.map +0 -1
  430. package/dist/src/sync/interfaces.d.ts +0 -193
  431. package/dist/src/sync/interfaces.d.ts.map +0 -1
  432. package/dist/src/sync/interfaces.js +0 -2
  433. package/dist/src/sync/interfaces.js.map +0 -1
  434. package/dist/src/sync/mailbox.d.ts +0 -60
  435. package/dist/src/sync/mailbox.d.ts.map +0 -1
  436. package/dist/src/sync/mailbox.js +0 -142
  437. package/dist/src/sync/mailbox.js.map +0 -1
  438. package/dist/src/sync/sync-awaiter.d.ts +0 -34
  439. package/dist/src/sync/sync-awaiter.d.ts.map +0 -1
  440. package/dist/src/sync/sync-awaiter.js +0 -124
  441. package/dist/src/sync/sync-awaiter.js.map +0 -1
  442. package/dist/src/sync/sync-builder.d.ts +0 -23
  443. package/dist/src/sync/sync-builder.d.ts.map +0 -1
  444. package/dist/src/sync/sync-builder.js +0 -52
  445. package/dist/src/sync/sync-builder.js.map +0 -1
  446. package/dist/src/sync/sync-manager.d.ts +0 -50
  447. package/dist/src/sync/sync-manager.d.ts.map +0 -1
  448. package/dist/src/sync/sync-manager.js +0 -447
  449. package/dist/src/sync/sync-manager.js.map +0 -1
  450. package/dist/src/sync/sync-operation.d.ts +0 -30
  451. package/dist/src/sync/sync-operation.d.ts.map +0 -1
  452. package/dist/src/sync/sync-operation.js +0 -70
  453. package/dist/src/sync/sync-operation.js.map +0 -1
  454. package/dist/src/sync/sync-status-tracker.d.ts +0 -31
  455. package/dist/src/sync/sync-status-tracker.d.ts.map +0 -1
  456. package/dist/src/sync/sync-status-tracker.js +0 -137
  457. package/dist/src/sync/sync-status-tracker.js.map +0 -1
  458. package/dist/src/sync/types.d.ts +0 -137
  459. package/dist/src/sync/types.d.ts.map +0 -1
  460. package/dist/src/sync/types.js +0 -31
  461. package/dist/src/sync/types.js.map +0 -1
  462. package/dist/src/sync/utils.d.ts +0 -71
  463. package/dist/src/sync/utils.d.ts.map +0 -1
  464. package/dist/src/sync/utils.js +0 -283
  465. package/dist/src/sync/utils.js.map +0 -1
  466. package/dist/src/utils/reshuffle.d.ts +0 -47
  467. package/dist/src/utils/reshuffle.d.ts.map +0 -1
  468. package/dist/src/utils/reshuffle.js +0 -91
  469. package/dist/src/utils/reshuffle.js.map +0 -1
@@ -0,0 +1,4667 @@
1
+ import { Action, CreateDocumentActionInput, DocumentModelModule, ISigner, Operation, OperationContext, OperationWithContext, OperationWithContext as OperationWithContext$1, PHDocument, PHDocumentState, SignatureVerificationHandler, UpgradeDocumentActionInput, UpgradeManifest, UpgradeReducer, UpgradeTransition, actions as documentActions } from "@powerhousedao/shared/document-model";
2
+ import { DocumentDriveDocument, DriveInput, FolderNode, Node } from "@powerhousedao/shared/document-drive";
3
+ import { ILogger } from "document-model";
4
+ import * as kysely from "kysely";
5
+ import { Generated, Insertable, Kysely, Transaction } from "kysely";
6
+ import { IProcessor, IProcessorHostModule, IProcessorManager, IProcessorManager as IProcessorManager$1, IRelationalDb, ProcessorApp, ProcessorFactory, ProcessorFactory as ProcessorFactory$1, ProcessorFactoryBuilder, ProcessorFilter, ProcessorRecord, ProcessorStatus, RelationalDbProcessor, TrackedProcessor, TrackedProcessor as TrackedProcessor$1, createRelationalDb } from "@powerhousedao/shared/processors";
7
+
8
+ //#region src/attachments/types.d.ts
9
+ /**
10
+ * Content hash of the attachment data. This is the primary identifier.
11
+ * Format is algorithm-dependent, e.g. SHA-256 hex.
12
+ */
13
+ type AttachmentHash = string;
14
+ /**
15
+ * A reference to an attachment, used in document state and action inputs.
16
+ * Format: `attachment://v<version>:<hash>`
17
+ *
18
+ * The version prefix allows changing the hash algorithm, encoding, or
19
+ * length without leaking implementation details into the ref format.
20
+ * Version 1 is defined as SHA-256 hex.
21
+ *
22
+ * Using the hash as the ref makes attachments content-addressable:
23
+ * any peer that has the bytes for a given hash can serve the attachment.
24
+ */
25
+ type AttachmentRef = `attachment://v${number}:${string}`;
26
+ //#endregion
27
+ //#region src/actions/index.d.ts
28
+ /**
29
+ * Creates a CREATE_DOCUMENT action for document creation.
30
+ */
31
+ declare function createDocumentAction(input: CreateDocumentActionInput): Action;
32
+ /**
33
+ * Creates an UPGRADE_DOCUMENT action to set initial document state.
34
+ */
35
+ declare function upgradeDocumentAction(input: UpgradeDocumentActionInput): Action;
36
+ /**
37
+ * Creates a DELETE_DOCUMENT action for document deletion.
38
+ */
39
+ declare function deleteDocumentAction(documentId: string): Action;
40
+ /**
41
+ * Creates an ADD_RELATIONSHIP action that records a directed edge from
42
+ * `sourceId` to `targetId` with an arbitrary `relationshipType` and optional
43
+ * `metadata`. The edge is opaque to the reactor — consumers (e.g. reactor-drive)
44
+ * define their own type strings such as `"drive/child"` and attach
45
+ * domain-specific metadata.
46
+ */
47
+ declare function addRelationshipAction(sourceId: string, targetId: string, relationshipType: string, metadata?: Record<string, unknown>): Action;
48
+ /**
49
+ * Creates an UPDATE_RELATIONSHIP action to replace a relationship's metadata
50
+ * without losing its createdAt ordering.
51
+ */
52
+ declare function updateRelationshipAction(sourceId: string, targetId: string, relationshipType: string, metadata: Record<string, unknown> | null): Action;
53
+ /**
54
+ * Creates a REMOVE_RELATIONSHIP action to remove a parent-child relationship.
55
+ */
56
+ declare function removeRelationshipAction(sourceId: string, targetId: string, relationshipType?: string): Action;
57
+ //#endregion
58
+ //#region src/queue/types.d.ts
59
+ type JobKind = "mutation" | "load";
60
+ /**
61
+ * State of a job in the queue
62
+ */
63
+ declare enum JobQueueState {
64
+ UNKNOWN = -1,
65
+ PREPROCESSING = 0,
66
+ PENDING = 1,
67
+ READY = 2,
68
+ RUNNING = 3,
69
+ RESOLVED = 4
70
+ }
71
+ /**
72
+ * Interface for a job execution handle
73
+ */
74
+ interface IJobExecutionHandle {
75
+ readonly job: Job;
76
+ readonly state: JobQueueState;
77
+ start(): void;
78
+ complete(): void;
79
+ fail(error: ErrorInfo): void;
80
+ defer(): void;
81
+ }
82
+ /**
83
+ * Represents a job to be executed by the job executor
84
+ */
85
+ type Job = {
86
+ /** Unique identifier for the job */id: string; /** Classification of the job so executors can switch behavior */
87
+ kind: JobKind; /** The document ID this job operates on */
88
+ documentId: string; /** The scope of the operations */
89
+ scope: string; /** The branch of the operations */
90
+ branch: string; /** The actions to be executed (processed sequentially) */
91
+ actions: Action[]; /** Pre-existing operations to import (used for load jobs) */
92
+ operations: Operation[]; /** Timestamp when the job was created */
93
+ createdAt: string; /** The hint for the queue to use for ordering the job */
94
+ queueHint: string[]; /** Number of retry attempts */
95
+ retryCount?: number; /** Maximum number of retries allowed */
96
+ maxRetries?: number; /** Last error if job failed */
97
+ lastError?: ErrorInfo; /** History of all errors from each attempt (ordered) */
98
+ errorHistory: ErrorInfo[]; /** Metadata that flows through the job lifecycle */
99
+ meta: JobMeta;
100
+ };
101
+ /**
102
+ * Event types for the queue system
103
+ */
104
+ declare const QueueEventTypes: {
105
+ readonly JOB_AVAILABLE: 10000;
106
+ };
107
+ /**
108
+ * Event data for job available events
109
+ */
110
+ type JobAvailableEvent = {
111
+ documentId: string;
112
+ scope: string;
113
+ branch: string;
114
+ jobId: string;
115
+ };
116
+ //#endregion
117
+ //#region src/shared/types.d.ts
118
+ /**
119
+ * Information about an error including message and stack trace.
120
+ */
121
+ type ErrorInfo = {
122
+ message: string;
123
+ stack: string;
124
+ };
125
+ /**
126
+ * Describes the status of a shutdown operation.
127
+ */
128
+ type ShutdownStatus = {
129
+ /**
130
+ * True if and only if the system has been shutdown.
131
+ *
132
+ * This value is meant to be polled to determine if the system has been shutdown.
133
+ *
134
+ * In the case of a browser process, the `kill` method should be able to synchronously set this to true.
135
+ *
136
+ * In the case of a server process, a graceful shutdown period should be allowed for the system to finish its work.
137
+ */
138
+ get isShutdown(): boolean;
139
+ /**
140
+ * A promise that resolves when the shutdown process is complete.
141
+ *
142
+ * For server environments, await this promise to ensure all active jobs finish
143
+ * before exiting the process.
144
+ */
145
+ completed: Promise<void>;
146
+ };
147
+ /**
148
+ * Enum that determines deletion propagation.
149
+ */
150
+ declare enum PropagationMode {
151
+ None = "none",
152
+ Cascade = "cascade"
153
+ }
154
+ /**
155
+ * Enum that describes the type of relationship change.
156
+ */
157
+ declare enum RelationshipChangeType {
158
+ Added = "added",
159
+ Removed = "removed"
160
+ }
161
+ /**
162
+ * Batch-specific metadata always present on every job.
163
+ * Single jobs get a unique batchId and batchJobIds of [jobId].
164
+ */
165
+ type BatchMeta = {
166
+ batchId: string;
167
+ batchJobIds: string[];
168
+ };
169
+ /**
170
+ * Metadata that flows through the job lifecycle.
171
+ * Always includes batch fields; callers may add additional properties.
172
+ */
173
+ type JobMeta = BatchMeta & Record<string, unknown>;
174
+ /**
175
+ * Describes the current state of a job.
176
+ */
177
+ type JobInfo = {
178
+ id: string;
179
+ status: JobStatus;
180
+ createdAtUtcIso: string;
181
+ completedAtUtcIso?: string;
182
+ error?: ErrorInfo;
183
+ errorHistory?: ErrorInfo[];
184
+ result?: any;
185
+ /**
186
+ * A token for coordinating reads, only valid once a job reaches COMPLETED.
187
+ */
188
+ consistencyToken: ConsistencyToken;
189
+ /**
190
+ * Metadata that flows through the job lifecycle.
191
+ */
192
+ meta: JobMeta;
193
+ /**
194
+ * The full job object, populated on failure for debugging purposes.
195
+ */
196
+ job?: Job;
197
+ };
198
+ /**
199
+ * Job execution statuses
200
+ */
201
+ declare enum JobStatus {
202
+ /** Job is queued but not yet started */
203
+ PENDING = "PENDING",
204
+ /** Job is currently being executed */
205
+ RUNNING = "RUNNING",
206
+ /** Operations have been written to the operation store (JOB_WRITE_READY event) */
207
+ WRITE_READY = "WRITE_READY",
208
+ /** Read models have finished indexing operations (JOB_READ_READY event) */
209
+ READ_READY = "READ_READY",
210
+ /** Job failed (may be retried) */
211
+ FAILED = "FAILED"
212
+ }
213
+ /**
214
+ * Describe the view of a set of documents. That is, what pieces of the
215
+ * documents are populated.
216
+ */
217
+ type ViewFilter = {
218
+ branch?: string;
219
+ scopes?: string[];
220
+ revision?: number;
221
+ };
222
+ /**
223
+ * Describes filter options for searching documents.
224
+ *
225
+ * Each parameter is treated as an AND condition.
226
+ */
227
+ type SearchFilter = {
228
+ type?: string;
229
+ parentId?: string;
230
+ ids?: string[];
231
+ slugs?: string[];
232
+ };
233
+ /**
234
+ * Describes the options for paging.
235
+ */
236
+ type PagingOptions = {
237
+ cursor: string;
238
+ limit: number;
239
+ };
240
+ /**
241
+ * The paged result.
242
+ */
243
+ type PagedResults<T> = {
244
+ results: T[];
245
+ options: PagingOptions;
246
+ next?: () => Promise<PagedResults<T>>;
247
+ nextCursor?: string;
248
+ totalCount?: number;
249
+ };
250
+ /**
251
+ * A string key in the format `documentId:scope:branch` used to identify a consistency checkpoint.
252
+ */
253
+ type ConsistencyKey = `${string}:${string}:${string}`;
254
+ /**
255
+ * Describes a specific point in a document's operation history.
256
+ */
257
+ type ConsistencyCoordinate = {
258
+ documentId: string;
259
+ scope: string;
260
+ branch: string;
261
+ operationIndex: number;
262
+ };
263
+ /**
264
+ * A token that captures the state of write operations at a point in time.
265
+ * Can be used to ensure read-after-write consistency.
266
+ */
267
+ type ConsistencyToken = {
268
+ version: 1;
269
+ createdAtUtcIso: string;
270
+ coordinates: ConsistencyCoordinate[];
271
+ };
272
+ //#endregion
273
+ //#region src/read-models/interfaces.d.ts
274
+ /**
275
+ * Generic interface for any read model that can index operations.
276
+ * Implementations include IDocumentView, search indices, caches, etc.
277
+ */
278
+ interface IReadModel {
279
+ /**
280
+ * Unique name identifying this read model, used for lookup via getReadModel.
281
+ */
282
+ readonly name: string;
283
+ /**
284
+ * Indexes a list of operations into the read model.
285
+ * This method is called asynchronously when operations are written to the operation store.
286
+ *
287
+ * @param operations - The operations with their context to index
288
+ */
289
+ indexOperations(operations: OperationWithContext$1[]): Promise<void>;
290
+ }
291
+ /**
292
+ * Coordinates read model synchronization with operation writes.
293
+ * Listens to operation events from the event bus and updates all registered read models.
294
+ */
295
+ interface IReadModelCoordinator {
296
+ /**
297
+ * All registered read models (pre-ready and post-ready).
298
+ */
299
+ readonly readModels: IReadModel[];
300
+ /**
301
+ * Start listening for operation events and updating read models.
302
+ */
303
+ start(): void;
304
+ /**
305
+ * Stop listening and clean up subscriptions.
306
+ */
307
+ stop(): void;
308
+ }
309
+ //#endregion
310
+ //#region src/sync/types.d.ts
311
+ declare enum ChannelScheme {
312
+ CONNECT = "connect",
313
+ SWITCHBOARD = "switchboard"
314
+ }
315
+ /**
316
+ * Dynamic JWT token handler for generating authentication tokens per-request.
317
+ * Called with the target URL to enable audience-specific tokens (aud claim).
318
+ * Returns undefined if no authentication is available (e.g., user not logged in).
319
+ */
320
+ type JwtHandler = (url: string) => Promise<string | undefined>;
321
+ /**
322
+ * Controls how a remote drives its polling schedule.
323
+ * - `Auto` (default): the channel runs the configured interval timer in the background.
324
+ * - `Manual`: the channel registers and connects but never ticks on its own.
325
+ * Callers must invoke ISyncManager.triggerPull(name) to fetch.
326
+ */
327
+ declare enum PollBehavior {
328
+ Auto = "auto",
329
+ Manual = "manual"
330
+ }
331
+ type RemoteOptions = {
332
+ /**
333
+ * Stringified UTC timestamp (ms). When set and not `"0"`, outbox operations older
334
+ * than this value are excluded. `"0"` and `undefined` are equivalent and disable
335
+ * the filter, syncing from the beginning of history.
336
+ */
337
+ sinceTimestampUtcMs?: string;
338
+ /**
339
+ * Polling cadence for this remote. Defaults to `PollBehavior.Auto` when omitted.
340
+ */
341
+ pollBehavior?: PollBehavior;
342
+ };
343
+ type RemoteFilter = {
344
+ documentId: string[];
345
+ scope: string[];
346
+ branch: string;
347
+ };
348
+ type RemoteCursor = {
349
+ remoteName: string;
350
+ cursorType: string;
351
+ cursorOrdinal: number;
352
+ lastSyncedAtUtcMs?: number;
353
+ };
354
+ type ChannelMeta = {
355
+ id: string;
356
+ };
357
+ type SyncEnvelopeType = "operations" | "ack";
358
+ type SyncEnvelope = {
359
+ type: SyncEnvelopeType;
360
+ channelMeta: ChannelMeta;
361
+ operations?: OperationWithContext$1[];
362
+ cursor?: RemoteCursor;
363
+ key?: string;
364
+ dependsOn?: string[];
365
+ };
366
+ declare enum SyncOperationStatus {
367
+ Unknown = -1,
368
+ TransportPending = 0,
369
+ ExecutionPending = 1,
370
+ Applied = 2,
371
+ Error = 3
372
+ }
373
+ declare enum ChannelErrorSource {
374
+ None = "none",
375
+ Channel = "channel",
376
+ Inbox = "inbox",
377
+ Outbox = "outbox"
378
+ }
379
+ type SyncOperationErrorType = "SIGNATURE_INVALID" | "HASH_MISMATCH" | "LIBRARY_ERROR" | "MISSING_OPERATIONS" | "EXCESSIVE_SHUFFLE" | "GRACEFUL_ABORT";
380
+ type ChannelHealth = {
381
+ state: "idle" | "running" | "error";
382
+ lastSuccessUtcMs?: number;
383
+ lastFailureUtcMs?: number;
384
+ failureCount: number;
385
+ };
386
+ type ConnectionState = "connecting" | "connected" | "disconnected" | "reconnecting" | "error";
387
+ type ConnectionStateSnapshot = {
388
+ state: ConnectionState;
389
+ failureCount: number;
390
+ lastSuccessUtcMs: number;
391
+ lastFailureUtcMs: number;
392
+ pushBlocked: boolean;
393
+ pushFailureCount: number;
394
+ receivingPages: boolean;
395
+ };
396
+ type ConnectionStateChangedEvent = {
397
+ remoteName: string;
398
+ remoteId: string;
399
+ previous: ConnectionState;
400
+ current: ConnectionState;
401
+ snapshot: ConnectionStateSnapshot;
402
+ };
403
+ type RemoteStatus = {
404
+ push: ChannelHealth;
405
+ pull: ChannelHealth;
406
+ };
407
+ type ChannelConfig = {
408
+ type: string;
409
+ parameters: Record<string, unknown>;
410
+ };
411
+ type RemoteRecord = {
412
+ id: string;
413
+ name: string;
414
+ collectionId: string;
415
+ channelConfig: ChannelConfig;
416
+ filter: RemoteFilter;
417
+ options: RemoteOptions;
418
+ status: RemoteStatus;
419
+ };
420
+ /**
421
+ * Event types for sync lifecycle events.
422
+ * These events track the sync progress of a job's operations to remotes.
423
+ * Uses a separate namespace (20000 range) from ReactorEventTypes (10000 range).
424
+ */
425
+ declare const SyncEventTypes: {
426
+ readonly SYNC_PENDING: 20001;
427
+ readonly SYNC_SUCCEEDED: 20002;
428
+ readonly SYNC_FAILED: 20003;
429
+ readonly DEAD_LETTER_ADDED: 20004;
430
+ readonly CONNECTION_STATE_CHANGED: 20005;
431
+ };
432
+ /**
433
+ * Event emitted when all SyncOperations for a job are queued in outboxes.
434
+ */
435
+ type SyncPendingEvent = {
436
+ jobId: string;
437
+ syncOperationCount: number;
438
+ remoteNames: string[];
439
+ };
440
+ /**
441
+ * Event emitted when all sync operations for a job succeed.
442
+ */
443
+ type SyncSucceededEvent = {
444
+ jobId: string;
445
+ syncOperationCount: number;
446
+ };
447
+ /**
448
+ * Event emitted when at least one sync operation for a job fails.
449
+ */
450
+ type SyncFailedEvent = {
451
+ jobId: string;
452
+ successCount: number;
453
+ failureCount: number;
454
+ errors: Array<{
455
+ remoteName: string;
456
+ documentId: string;
457
+ error: string;
458
+ }>;
459
+ };
460
+ /**
461
+ * Event emitted when a sync operation is moved to dead letter storage.
462
+ */
463
+ type DeadLetterAddedEvent = {
464
+ id: string;
465
+ jobId: string;
466
+ remoteName: string;
467
+ documentId: string;
468
+ errorSource: ChannelErrorSource;
469
+ };
470
+ /**
471
+ * Status of a sync operation result.
472
+ */
473
+ type SyncResultStatus = "succeeded" | "failed";
474
+ /**
475
+ * Error information for a failed sync operation to a specific remote.
476
+ */
477
+ type SyncResultError = {
478
+ remoteName: string;
479
+ documentId: string;
480
+ error: string;
481
+ };
482
+ /**
483
+ * Result of waiting for sync operations to complete for a job.
484
+ * Returned by ISyncManager.waitForSync().
485
+ */
486
+ type SyncResult = {
487
+ jobId: string;
488
+ status: SyncResultStatus;
489
+ syncOperationCount: number;
490
+ successCount: number;
491
+ failureCount: number;
492
+ errors: SyncResultError[];
493
+ };
494
+ //#endregion
495
+ //#region src/storage/interfaces.d.ts
496
+ /**
497
+ * Thrown when an operation with the same identity already exists in the store.
498
+ */
499
+ declare class DuplicateOperationError extends Error {
500
+ constructor(description: string);
501
+ }
502
+ /**
503
+ * Thrown when a concurrent write conflict is detected during an atomic apply.
504
+ */
505
+ declare class OptimisticLockError extends Error {
506
+ constructor(message: string);
507
+ }
508
+ /**
509
+ * Thrown when the caller-provided revision does not match the current
510
+ * stored revision, indicating a stale read.
511
+ */
512
+ declare class RevisionMismatchError extends Error {
513
+ constructor(expected: number, actual: number);
514
+ }
515
+ /**
516
+ * A write transaction passed to {@link IOperationStore.apply}. Accumulates
517
+ * operations that are committed atomically when the callback returns.
518
+ */
519
+ interface AtomicTxn {
520
+ /** Stages one or more operations to be written as part of this transaction. */
521
+ addOperations(...operations: Operation[]): void;
522
+ }
523
+ /**
524
+ * Per-scope revision map for a document, used to reconstruct the header
525
+ * revision field and lastModified timestamp.
526
+ */
527
+ type DocumentRevisions = {
528
+ /** Map of scope to operation index for that scope */revision: Record<string, number>; /** Latest timestamp across revisions */
529
+ latestTimestamp: string;
530
+ };
531
+ /**
532
+ * Append-only store for document operations. Operations are partitioned by
533
+ * (documentId, scope, branch) and ordered by a monotonic revision index.
534
+ */
535
+ interface IOperationStore {
536
+ /**
537
+ * Atomically appends operations for a single document/scope/branch.
538
+ * The provided revision must match the current head; otherwise a
539
+ * {@link RevisionMismatchError} is thrown.
540
+ *
541
+ * @param documentId - The document id
542
+ * @param documentType - The document type identifier
543
+ * @param scope - The operation scope (e.g. "global", "local")
544
+ * @param branch - The branch name
545
+ * @param revision - Expected current revision (optimistic lock)
546
+ * @param fn - Callback that stages operations via {@link AtomicTxn}
547
+ * @param signal - Optional abort signal to cancel the request
548
+ */
549
+ apply(documentId: string, documentType: string, scope: string, branch: string, revision: number, fn: (txn: AtomicTxn) => void | Promise<void>, signal?: AbortSignal): Promise<void>;
550
+ /**
551
+ * Returns operations for a document/scope/branch whose index is greater
552
+ * than the given revision.
553
+ *
554
+ * @param documentId - The document id
555
+ * @param scope - The operation scope
556
+ * @param branch - The branch name
557
+ * @param revision - Return operations after this revision index
558
+ * @param filter - Optional filters (action types, timestamp range)
559
+ * @param paging - Optional paging options for cursor-based pagination
560
+ * @param signal - Optional abort signal to cancel the request
561
+ */
562
+ getSince(documentId: string, scope: string, branch: string, revision: number, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
563
+ /**
564
+ * Returns operations across all documents whose auto-increment store id
565
+ * is greater than the given id. Used by read models and sync to catch up
566
+ * on operations they may have missed.
567
+ *
568
+ * @param id - Return operations with store id greater than this value
569
+ * @param paging - Optional paging options for cursor-based pagination
570
+ * @param signal - Optional abort signal to cancel the request
571
+ */
572
+ getSinceId(id: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext$1>>;
573
+ /**
574
+ * Gets operations that may conflict with incoming operations during a load.
575
+ *
576
+ * @param documentId - The document id
577
+ * @param scope - The scope to query
578
+ * @param branch - The branch name
579
+ * @param minTimestamp - Minimum timestamp (inclusive) as ISO string
580
+ * @param paging - Optional paging options for cursor-based pagination
581
+ * @param signal - Optional abort signal to cancel the request
582
+ * @returns Paged results of operations that may conflict
583
+ */
584
+ getConflicting(documentId: string, scope: string, branch: string, minTimestamp: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
585
+ /**
586
+ * Gets the latest operation index for each scope of a document, along with
587
+ * the latest timestamp across all scopes. This is used to efficiently reconstruct
588
+ * the revision map and lastModified timestamp for document headers.
589
+ *
590
+ * @param documentId - The document id
591
+ * @param branch - The branch name
592
+ * @param signal - Optional abort signal to cancel the request
593
+ * @returns Object containing revision map and latest timestamp
594
+ */
595
+ getRevisions(documentId: string, branch: string, signal?: AbortSignal): Promise<DocumentRevisions>;
596
+ }
597
+ /**
598
+ * Stores periodic document snapshots (keyframes) so that document state
599
+ * can be reconstructed without replaying the full operation history.
600
+ */
601
+ interface IKeyframeStore {
602
+ /**
603
+ * Stores a document snapshot at a specific revision.
604
+ *
605
+ * @param documentId - The document id
606
+ * @param scope - The operation scope
607
+ * @param branch - The branch name
608
+ * @param revision - The operation index this snapshot corresponds to
609
+ * @param document - The full document state to persist
610
+ * @param signal - Optional abort signal to cancel the request
611
+ */
612
+ putKeyframe(documentId: string, scope: string, branch: string, revision: number, document: PHDocument, signal?: AbortSignal): Promise<void>;
613
+ /**
614
+ * Finds the keyframe closest to (but not exceeding) the target revision.
615
+ * Returns undefined if no keyframe exists for this document/scope/branch.
616
+ *
617
+ * @param documentId - The document id
618
+ * @param scope - The operation scope
619
+ * @param branch - The branch name
620
+ * @param targetRevision - The desired revision upper bound
621
+ * @param signal - Optional abort signal to cancel the request
622
+ */
623
+ findNearestKeyframe(documentId: string, scope: string, branch: string, targetRevision: number, signal?: AbortSignal): Promise<{
624
+ revision: number;
625
+ document: PHDocument;
626
+ } | undefined>;
627
+ /**
628
+ * Lists all keyframes for a document, optionally filtered by scope and branch.
629
+ *
630
+ * @param documentId - The document id
631
+ * @param scope - Optional scope filter
632
+ * @param branch - Optional branch filter
633
+ * @param signal - Optional abort signal to cancel the request
634
+ */
635
+ listKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<Array<{
636
+ scope: string;
637
+ branch: string;
638
+ revision: number;
639
+ document: PHDocument;
640
+ }>>;
641
+ /**
642
+ * Deletes keyframes for a document. Optionally scoped to a specific
643
+ * scope and/or branch.
644
+ *
645
+ * @param documentId - The document id
646
+ * @param scope - Optional scope filter; omit to delete across all scopes
647
+ * @param branch - Optional branch filter; omit to delete across all branches
648
+ * @param signal - Optional abort signal to cancel the request
649
+ * @returns The number of keyframes deleted
650
+ */
651
+ deleteKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<number>;
652
+ }
653
+ /**
654
+ * Filters applied when reading document state from {@link IDocumentView}.
655
+ */
656
+ interface ViewFilter$1 {
657
+ /** Branch to read from. Defaults to the main branch when omitted. */
658
+ branch?: string;
659
+ /** Scopes to include. When omitted, all scopes are included. */
660
+ scopes?: string[];
661
+ /** Exclude operations originating from this remote name. */
662
+ excludeSourceRemote?: string;
663
+ }
664
+ /**
665
+ * Filter options for querying operations. When multiple filters are provided,
666
+ * they are combined with AND logic.
667
+ */
668
+ interface OperationFilter {
669
+ /** Filter by action types (OR logic within array) */
670
+ actionTypes?: string[];
671
+ /** Filter operations with timestamp >= this value (ISO string) */
672
+ timestampFrom?: string;
673
+ /** Filter operations with timestamp <= this value (ISO string) */
674
+ timestampTo?: string;
675
+ /** Filter operations with index >= this value */
676
+ sinceRevision?: number;
677
+ }
678
+ /**
679
+ * Materialised read model that maintains document snapshots. Snapshots are
680
+ * updated by indexing operations (which must include `resultingState`) and
681
+ * queried with optional consistency tokens for read-after-write guarantees.
682
+ */
683
+ interface IDocumentView extends IReadModel {
684
+ /**
685
+ * Initializes the view.
686
+ */
687
+ init(): Promise<void>;
688
+ /**
689
+ * Indexes a list of operations.
690
+ *
691
+ * @param items - Operations with context. Context MUST include ephemeral
692
+ * `resultingState` for optimization. IDocumentView never rebuilds
693
+ * documents from operations - it always requires resultingState.
694
+ */
695
+ indexOperations(items: OperationWithContext$1[]): Promise<void>;
696
+ /**
697
+ * Blocks until the view has processed the coordinates referenced by the
698
+ * provided consistency token.
699
+ *
700
+ * @param token - Consistency token derived from the originating job
701
+ * @param timeoutMs - Optional timeout window in milliseconds
702
+ * @param signal - Optional abort signal to cancel the wait
703
+ */
704
+ waitForConsistency(token: ConsistencyToken, timeoutMs?: number, signal?: AbortSignal): Promise<void>;
705
+ /**
706
+ * Returns true if and only if the documents exist.
707
+ *
708
+ * @param documentIds - The list of document ids to check.
709
+ * @param consistencyToken - Optional token for read-after-write consistency
710
+ * @param signal - Optional abort signal to cancel the request
711
+ */
712
+ exists(documentIds: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean[]>;
713
+ /**
714
+ * Returns the document with the given id.
715
+ *
716
+ * @param documentId - The id of the document to get.
717
+ * @param view - Optional filter containing branch and scopes information
718
+ * @param consistencyToken - Optional token for read-after-write consistency
719
+ * @param signal - Optional abort signal to cancel the request
720
+ */
721
+ get<TDocument extends PHDocument>(documentId: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
722
+ /**
723
+ * Returns the documents with the given ids.
724
+ *
725
+ * @param documentIds - The list of document ids to get.
726
+ * @param view - Optional filter containing branch and scopes information
727
+ * @param consistencyToken - Optional token for read-after-write consistency
728
+ * @param signal - Optional abort signal to cancel the request
729
+ */
730
+ getMany<TDocument extends PHDocument>(documentIds: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument[]>;
731
+ /**
732
+ * Returns the document with the given identifier (either id or slug).
733
+ * Throws an error if the identifier matches both an id and a slug that refer to different documents.
734
+ *
735
+ * @param identifier - The id or slug of the document to get.
736
+ * @param view - Optional filter containing branch and scopes information
737
+ * @param consistencyToken - Optional token for read-after-write consistency
738
+ * @param signal - Optional abort signal to cancel the request
739
+ * @throws {Error} If identifier matches both an ID and slug referring to different documents
740
+ */
741
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
742
+ /**
743
+ * Finds documents by their document type.
744
+ *
745
+ * @param type - The document type to search for
746
+ * @param view - Optional filter containing branch and scopes information
747
+ * @param paging - Optional paging options for cursor-based pagination
748
+ * @param consistencyToken - Optional token for read-after-write consistency
749
+ * @param signal - Optional abort signal to cancel the request
750
+ */
751
+ findByType(type: string, view?: ViewFilter$1, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
752
+ /**
753
+ * Resolves a slug to a document ID.
754
+ *
755
+ * @param slug - The slug to resolve
756
+ * @param view - Optional filter containing branch and scopes information
757
+ * @param consistencyToken - Optional token for read-after-write consistency
758
+ * @param signal - Optional abort signal to cancel the request
759
+ * @returns The document ID or undefined if the slug doesn't exist
760
+ */
761
+ resolveSlug(slug: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string | undefined>;
762
+ /**
763
+ * Resolves a list of slugs to document IDs.
764
+ *
765
+ * @param slugs - The list of slugs to resolve.
766
+ * @param view - Optional filter containing branch and scopes information
767
+ * @param consistencyToken - Optional token for read-after-write consistency
768
+ * @param signal - Optional abort signal to cancel the request
769
+ * @returns The list of document IDs
770
+ */
771
+ resolveSlugs(slugs: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
772
+ /**
773
+ * Resolves an identifier (either id or slug) to a document ID.
774
+ * This is a lightweight alternative to getByIdOrSlug that returns just the ID
775
+ * without fetching the full document.
776
+ *
777
+ * @param identifier - The id or slug to resolve
778
+ * @param view - Optional filter containing branch and scopes information
779
+ * @param consistencyToken - Optional token for read-after-write consistency
780
+ * @param signal - Optional abort signal to cancel the request
781
+ * @returns The document ID
782
+ * @throws {Error} If document not found or identifier matches both an ID and slug referring to different documents
783
+ */
784
+ resolveIdOrSlug(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string>;
785
+ }
786
+ /**
787
+ * A directed relationship between two documents in the document graph.
788
+ */
789
+ type DocumentRelationship = {
790
+ sourceId: string;
791
+ targetId: string;
792
+ relationshipType: string;
793
+ metadata?: Record<string, unknown>;
794
+ createdAt: Date;
795
+ updatedAt: Date;
796
+ };
797
+ /**
798
+ * A lightweight directed edge in a {@link IDocumentGraph}.
799
+ */
800
+ type DocumentGraphEdge = {
801
+ from: string;
802
+ to: string;
803
+ type: string;
804
+ };
805
+ /**
806
+ * A subgraph of the document relationship graph, returned by traversal
807
+ * queries such as {@link IDocumentIndexer.findAncestors}.
808
+ */
809
+ interface IDocumentGraph {
810
+ nodes: string[];
811
+ edges: DocumentGraphEdge[];
812
+ }
813
+ /**
814
+ * Read model that maintains a directed graph of document relationships.
815
+ * Relationships are created and removed by indexing operations containing
816
+ * ADD_RELATIONSHIP and REMOVE_RELATIONSHIP actions.
817
+ */
818
+ interface IDocumentIndexer extends IReadModel {
819
+ /**
820
+ * Initializes the indexer and catches up on any missed operations.
821
+ */
822
+ init(): Promise<void>;
823
+ /**
824
+ * Indexes a list of operations to update the relationship graph.
825
+ *
826
+ * @param operations - Operations to index. Will process ADD_RELATIONSHIP and
827
+ * REMOVE_RELATIONSHIP operations.
828
+ */
829
+ indexOperations(operations: OperationWithContext$1[]): Promise<void>;
830
+ /**
831
+ * Blocks until the indexer has processed the coordinates referenced by the
832
+ * provided consistency token.
833
+ *
834
+ * @param token - Consistency token derived from the originating job
835
+ * @param timeoutMs - Optional timeout window in milliseconds
836
+ * @param signal - Optional abort signal to cancel the wait
837
+ */
838
+ waitForConsistency(token: ConsistencyToken, timeoutMs?: number, signal?: AbortSignal): Promise<void>;
839
+ /**
840
+ * Returns outgoing relationships from a document.
841
+ *
842
+ * @param documentId - The source document id
843
+ * @param types - Optional filter by relationship types
844
+ * @param consistencyToken - Optional token for read-after-write consistency
845
+ * @param signal - Optional abort signal to cancel the request
846
+ */
847
+ getOutgoing(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
848
+ /**
849
+ * Returns incoming relationships to a document.
850
+ *
851
+ * @param documentId - The target document id
852
+ * @param types - Optional filter by relationship types
853
+ * @param consistencyToken - Optional token for read-after-write consistency
854
+ * @param signal - Optional abort signal to cancel the request
855
+ */
856
+ getIncoming(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
857
+ /**
858
+ * Checks if a relationship exists between two documents.
859
+ *
860
+ * @param sourceId - The source document id
861
+ * @param targetId - The target document id
862
+ * @param types - Optional filter by relationship types
863
+ * @param consistencyToken - Optional token for read-after-write consistency
864
+ * @param signal - Optional abort signal to cancel the request
865
+ */
866
+ hasRelationship(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean>;
867
+ /**
868
+ * Returns all undirected relationships between two documents.
869
+ *
870
+ * @param a - The ID of the first document
871
+ * @param b - The ID of the second document
872
+ * @param types - Optional filter by relationship types
873
+ * @param consistencyToken - Optional token for read-after-write consistency
874
+ * @param signal - Optional abort signal to cancel the request
875
+ */
876
+ getUndirectedRelationships(a: string, b: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
877
+ /**
878
+ * Returns all directed relationships between two documents.
879
+ *
880
+ * @param sourceId - The source document id
881
+ * @param targetId - The target document id
882
+ * @param types - Optional filter by relationship types
883
+ * @param consistencyToken - Optional token for read-after-write consistency
884
+ * @param signal - Optional abort signal to cancel the request
885
+ */
886
+ getDirectedRelationships(sourceId: string, targetId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
887
+ /**
888
+ * Finds a path from source to target following directed edges.
889
+ *
890
+ * @param sourceId - The source document id
891
+ * @param targetId - The target document id
892
+ * @param types - Optional filter by relationship types
893
+ * @param consistencyToken - Optional token for read-after-write consistency
894
+ * @param signal - Optional abort signal to cancel the request
895
+ * @returns Array of document ids representing the path, or null if no path exists
896
+ */
897
+ findPath(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[] | null>;
898
+ /**
899
+ * Returns all ancestors of a document in the relationship graph.
900
+ *
901
+ * @param documentId - The document id
902
+ * @param types - Optional filter by relationship types
903
+ * @param consistencyToken - Optional token for read-after-write consistency
904
+ * @param signal - Optional abort signal to cancel the request
905
+ */
906
+ findAncestors(documentId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<IDocumentGraph>;
907
+ /**
908
+ * Returns children of the given parents that have no parents outside
909
+ * the given set. Used by cascade delete to find documents that would
910
+ * be orphaned if all the given parents were deleted.
911
+ *
912
+ * @param parentIds - The set of parent document ids (the deletion set)
913
+ * @param types - Optional filter by relationship types
914
+ * @param signal - Optional abort signal to cancel the request
915
+ */
916
+ getOrphanedChildren(parentIds: string[], types?: string[], signal?: AbortSignal): Promise<string[]>;
917
+ /**
918
+ * Returns all relationship types currently in the system.
919
+ *
920
+ * @param consistencyToken - Optional token for read-after-write consistency
921
+ * @param signal - Optional abort signal to cancel the request
922
+ */
923
+ getRelationshipTypes(consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
924
+ }
925
+ /**
926
+ * Persistent storage for sync remote configurations. Each remote represents
927
+ * a connection to an external system that operations can be synced with.
928
+ */
929
+ interface ISyncRemoteStorage {
930
+ /**
931
+ * Lists all remotes.
932
+ *
933
+ * @param signal - Optional abort signal to cancel the request
934
+ * @returns The remotes
935
+ */
936
+ list(signal?: AbortSignal): Promise<RemoteRecord[]>;
937
+ /**
938
+ * Gets a remote by name.
939
+ *
940
+ * @param name - The name of the remote
941
+ * @param signal - Optional abort signal to cancel the request
942
+ * @returns The remote
943
+ */
944
+ get(name: string, signal?: AbortSignal): Promise<RemoteRecord>;
945
+ /**
946
+ * Upserts a remote.
947
+ *
948
+ * @param remote - The remote to upsert
949
+ * @param signal - Optional abort signal to cancel the request
950
+ * @returns The remote
951
+ */
952
+ upsert(remote: RemoteRecord, signal?: AbortSignal): Promise<void>;
953
+ /**
954
+ * Removes a remote by name.
955
+ *
956
+ * @param name - The name of the remote
957
+ * @param signal - Optional abort signal to cancel the request
958
+ * @returns The remote
959
+ */
960
+ remove(name: string, signal?: AbortSignal): Promise<void>;
961
+ }
962
+ /**
963
+ * Persistent storage for sync cursors that track inbox/outbox progress
964
+ * per remote. Cursors allow sync to resume from where it left off.
965
+ */
966
+ interface ISyncCursorStorage {
967
+ /**
968
+ * Lists all cursors for a remote.
969
+ *
970
+ * @param remoteName - The name of the remote
971
+ * @param signal - Optional abort signal to cancel the request
972
+ * @returns The cursors
973
+ */
974
+ list(remoteName: string, signal?: AbortSignal): Promise<RemoteCursor[]>;
975
+ /**
976
+ * Gets a cursor for a remote.
977
+ *
978
+ * @param remoteName - The name of the remote
979
+ * @param cursorType - The type of cursor ("inbox" or "outbox")
980
+ * @param signal - Optional abort signal to cancel the request
981
+ * @returns The cursor
982
+ */
983
+ get(remoteName: string, cursorType: "inbox" | "outbox", signal?: AbortSignal): Promise<RemoteCursor>;
984
+ /**
985
+ * Upserts a cursor.
986
+ *
987
+ * @param cursor - The cursor to upsert
988
+ * @param signal - Optional abort signal to cancel the request
989
+ * @returns The cursor
990
+ */
991
+ upsert(cursor: RemoteCursor, signal?: AbortSignal): Promise<void>;
992
+ /**
993
+ * Removes a cursor for a remote.
994
+ *
995
+ * @param remoteName - The name of the remote
996
+ * @param signal - Optional abort signal to cancel the request
997
+ * @returns The cursor
998
+ */
999
+ remove(remoteName: string, signal?: AbortSignal): Promise<void>;
1000
+ }
1001
+ /**
1002
+ * Serializable snapshot of a permanently failed SyncOperation.
1003
+ */
1004
+ type DeadLetterRecord = {
1005
+ id: string;
1006
+ jobId: string;
1007
+ jobDependencies: string[];
1008
+ remoteName: string;
1009
+ documentId: string;
1010
+ scopes: string[];
1011
+ branch: string;
1012
+ operations: OperationWithContext$1[];
1013
+ errorSource: ChannelErrorSource;
1014
+ errorMessage: string;
1015
+ };
1016
+ /**
1017
+ * Persists dead-lettered sync operations so they survive reactor restarts.
1018
+ */
1019
+ interface ISyncDeadLetterStorage {
1020
+ /**
1021
+ * Lists dead letters for a remote, ordered by ordinal DESC (newest first).
1022
+ *
1023
+ * @param remoteName - The name of the remote
1024
+ * @param paging - Optional paging options (cursor + limit)
1025
+ * @param signal - Optional abort signal to cancel the request
1026
+ * @returns Paged dead letter records
1027
+ */
1028
+ list(remoteName: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DeadLetterRecord>>;
1029
+ /**
1030
+ * Adds a dead letter. Duplicate ids are silently ignored.
1031
+ *
1032
+ * @param deadLetter - The dead letter record to persist
1033
+ * @param signal - Optional abort signal to cancel the request
1034
+ */
1035
+ add(deadLetter: DeadLetterRecord, signal?: AbortSignal): Promise<void>;
1036
+ /**
1037
+ * Removes a single dead letter by id.
1038
+ *
1039
+ * @param id - The dead letter id
1040
+ * @param signal - Optional abort signal to cancel the request
1041
+ */
1042
+ remove(id: string, signal?: AbortSignal): Promise<void>;
1043
+ /**
1044
+ * Removes all dead letters for a remote.
1045
+ *
1046
+ * @param remoteName - The name of the remote
1047
+ * @param signal - Optional abort signal to cancel the request
1048
+ */
1049
+ removeByRemote(remoteName: string, signal?: AbortSignal): Promise<void>;
1050
+ /**
1051
+ * Returns distinct document IDs that have any dead letter record across all remotes.
1052
+ * Used to populate the quarantine set on startup.
1053
+ *
1054
+ * @param signal - Optional abort signal to cancel the request
1055
+ */
1056
+ listQuarantinedDocumentIds(signal?: AbortSignal): Promise<string[]>;
1057
+ }
1058
+ //#endregion
1059
+ //#region src/cache/operation-index-types.d.ts
1060
+ type OperationIndexEntry = Operation & {
1061
+ ordinal?: number;
1062
+ documentId: string;
1063
+ documentType: string;
1064
+ branch: string;
1065
+ scope: string;
1066
+ sourceRemote: string;
1067
+ };
1068
+ interface IOperationIndexTxn {
1069
+ createCollection(collectionId: string): void;
1070
+ addToCollection(collectionId: string, documentId: string): void;
1071
+ removeFromCollection(collectionId: string, documentId: string): void;
1072
+ write(operations: OperationIndexEntry[]): void;
1073
+ }
1074
+ interface IOperationIndex {
1075
+ start(): IOperationIndexTxn;
1076
+ commit(txn: IOperationIndexTxn, signal?: AbortSignal): Promise<number[]>;
1077
+ find(collectionId: string, cursor?: number, view?: ViewFilter$1, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationIndexEntry>>;
1078
+ /**
1079
+ * Get all operations for a specific document, ordered by ordinal.
1080
+ * Used for retroactive sync when a document is added to a collection.
1081
+ */
1082
+ get(documentId: string, view?: ViewFilter$1, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationIndexEntry>>;
1083
+ getSinceOrdinal(ordinal: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext$1>>;
1084
+ getLatestTimestampForCollection(collectionId: string, signal?: AbortSignal): Promise<string | null>;
1085
+ /**
1086
+ * Get all collection memberships for the given document IDs.
1087
+ * Returns a map of documentId to array of collection IDs.
1088
+ */
1089
+ getCollectionsForDocuments(documentIds: string[]): Promise<Record<string, string[]>>;
1090
+ }
1091
+ declare function driveCollectionId(branch: string, driveId: string): string;
1092
+ //#endregion
1093
+ //#region src/cache/write/interfaces.d.ts
1094
+ /**
1095
+ * IWriteCache is a write-side projection that optimizes document state retrieval
1096
+ * for the job executor. This is separate from IDocumentView (read-side projection) which optimizes
1097
+ * queries and searches.
1098
+ */
1099
+ interface IWriteCache {
1100
+ /**
1101
+ * Retrieves or builds the document at the specified revision.
1102
+ * If targetRevision is not provided, retrieves the latest state.
1103
+ *
1104
+ * @param documentId - The document identifier
1105
+ * @param scope - Operation scope
1106
+ * @param branch - Branch name
1107
+ * @param targetRevision - The exact revision to retrieve (optional, defaults to latest)
1108
+ * @param signal - Optional abort signal to cancel the operation
1109
+ * @returns The complete document at the specified revision
1110
+ *
1111
+ * @example
1112
+ * ```typescript
1113
+ * // Get latest document state
1114
+ * const doc = await cache.getState(docId, 'global', 'main');
1115
+ *
1116
+ * // Get document at specific revision
1117
+ * const doc = await cache.getState(docId, 'global', 'main', 42);
1118
+ * ```
1119
+ */
1120
+ getState(documentId: string, scope: string, branch: string, targetRevision?: number, signal?: AbortSignal): Promise<PHDocument>;
1121
+ /**
1122
+ * Stores a document snapshot in the cache at the specified revision.
1123
+ * Implementations may truncate the stored document (e.g. strip operation
1124
+ * history beyond the last entry per scope, clear clipboard) to bound memory
1125
+ * and copy cost. Callers must not assume that the document returned by a
1126
+ * subsequent getState() call will have a complete operations array; the only
1127
+ * guaranteed invariant is that operations[scope].at(-1) holds the latest
1128
+ * operation index for each scope present in the cached document.
1129
+ *
1130
+ * @param documentId - The document identifier
1131
+ * @param scope - Operation scope
1132
+ * @param branch - Branch name
1133
+ * @param revision - The revision this document represents
1134
+ * @param document - The document to cache
1135
+ *
1136
+ * @example
1137
+ * ```typescript
1138
+ * cache.putState(docId, 'global', 'main', 42, document);
1139
+ * ```
1140
+ */
1141
+ putState(documentId: string, scope: string, branch: string, revision: number, document: PHDocument): void;
1142
+ /**
1143
+ * Invalidates (removes) cached entries for a document stream.
1144
+ *
1145
+ * - If only documentId is provided: invalidates all scopes and branches for that document
1146
+ * - If documentId + scope provided: invalidates all branches for that document and scope
1147
+ * - If all parameters provided: invalidates the specific stream
1148
+ *
1149
+ * @param documentId - The document identifier
1150
+ * @param scope - Optional scope to narrow invalidation
1151
+ * @param branch - Optional branch to narrow invalidation
1152
+ * @returns Number of ring buffers evicted
1153
+ *
1154
+ * @example
1155
+ * ```typescript
1156
+ * // Invalidate all streams for a document
1157
+ * cache.invalidate(docId);
1158
+ *
1159
+ * // Invalidate all branches for a specific scope
1160
+ * cache.invalidate(docId, 'global');
1161
+ *
1162
+ * // Invalidate specific stream
1163
+ * cache.invalidate(docId, 'global', 'main');
1164
+ * ```
1165
+ */
1166
+ invalidate(documentId: string, scope?: string, branch?: string): number;
1167
+ /**
1168
+ * Clears all cached data from the in-memory cache.
1169
+ */
1170
+ clear(): void;
1171
+ /**
1172
+ * Performs startup initialization.
1173
+ */
1174
+ startup(): Promise<void>;
1175
+ /**
1176
+ * Performs graceful shutdown.
1177
+ */
1178
+ shutdown(): Promise<void>;
1179
+ }
1180
+ //#endregion
1181
+ //#region src/events/types.d.ts
1182
+ /**
1183
+ * Describes a function to unsubscribe from an event.
1184
+ */
1185
+ type Unsubscribe = () => void;
1186
+ /**
1187
+ * A subscriber is a function that is called when an event is emitted.
1188
+ *
1189
+ * It is passed the event type and the data.
1190
+ * It can return a promise or a value.
1191
+ * If it returns a promise, the event bus will wait for the promise to resolve before calling the next subscriber.
1192
+ * If it throws an error, the event bus will reject with an aggregate error of all errors.
1193
+ *
1194
+ * @param type - The type of event to emit.
1195
+ * @param data - The data to pass to the subscriber.
1196
+ */
1197
+ type Subscriber = (type: number, data: any) => void | Promise<void>;
1198
+ /**
1199
+ * Custom error class that aggregates multiple errors from event subscribers.
1200
+ */
1201
+ declare class EventBusAggregateError extends Error {
1202
+ readonly errors: any[];
1203
+ constructor(errors: unknown[]);
1204
+ }
1205
+ /**
1206
+ * Event types for reactor lifecycle events.
1207
+ */
1208
+ declare const ReactorEventTypes: {
1209
+ readonly JOB_PENDING: 10001;
1210
+ readonly JOB_RUNNING: 10002;
1211
+ readonly JOB_WRITE_READY: 10003;
1212
+ readonly JOB_READ_READY: 10004;
1213
+ readonly JOB_FAILED: 10005;
1214
+ };
1215
+ /**
1216
+ * Event emitted when a job is registered and waiting to be executed.
1217
+ */
1218
+ type JobPendingEvent = {
1219
+ jobId: string;
1220
+ jobMeta: JobMeta;
1221
+ };
1222
+ /**
1223
+ * Event emitted when a job starts executing.
1224
+ */
1225
+ type JobRunningEvent = {
1226
+ jobId: string;
1227
+ jobMeta: JobMeta;
1228
+ };
1229
+ /**
1230
+ * Event emitted when operations are written to IOperationStore.
1231
+ * Contains the operations directly to avoid round-trip queries.
1232
+ */
1233
+ type JobWriteReadyEvent = {
1234
+ jobId: string;
1235
+ operations: OperationWithContext$1[];
1236
+ jobMeta: JobMeta;
1237
+ /**
1238
+ * Maps documentId to the collection IDs it belongs to.
1239
+ * Used by SyncManager to route operations only to remotes
1240
+ * whose collection contains the document.
1241
+ */
1242
+ collectionMemberships?: Record<string, string[]>;
1243
+ };
1244
+ /**
1245
+ * Event emitted after all read models have finished processing operations.
1246
+ * This event fires after JOB_WRITE_READY and guarantees that:
1247
+ * - All read models (DocumentView, DocumentIndexer, etc.) have indexed the operations
1248
+ * - All consistency trackers have been updated with the new operation indices
1249
+ * - Queries without consistency tokens will now see the updated data
1250
+ *
1251
+ * This event is useful for:
1252
+ * - Test synchronization (knowing when read models are ready)
1253
+ * - Observability (measuring read model latency)
1254
+ * - Event-driven workflows (triggering downstream processes)
1255
+ */
1256
+ type JobReadReadyEvent = {
1257
+ jobId: string;
1258
+ operations: OperationWithContext$1[];
1259
+ };
1260
+ /**
1261
+ * Event emitted when a job fails with an unrecoverable error.
1262
+ * This event allows the JobAwaiter and other subscribers to react to job failures
1263
+ * without polling.
1264
+ */
1265
+ type JobFailedEvent$1 = {
1266
+ jobId: string;
1267
+ error: Error;
1268
+ job?: Job;
1269
+ };
1270
+ //#endregion
1271
+ //#region src/events/interfaces.d.ts
1272
+ /**
1273
+ * Describes an object that manages event subscriptions and emissions.
1274
+ */
1275
+ interface IEventBus {
1276
+ /**
1277
+ * Register a new subscriber.
1278
+ * Order is preserved by pushing to the end of the per-type array.
1279
+ *
1280
+ * @param type - The type of event to subscribe to.
1281
+ * @param subscriber - The subscriber function to call when the event is emitted.
1282
+ *
1283
+ * @returns A function to unsubscribe from the event.
1284
+ */
1285
+ subscribe<K>(type: number, subscriber: (type: number, event: K) => void | Promise<void>): Unsubscribe;
1286
+ /**
1287
+ * Emits an event and waits until **all** subscribers finish.
1288
+ * - Every subscriber present at emit-start is called, in registration order.
1289
+ * - Calls are invoked and settled sequentially.
1290
+ * - If subscribers throw/reject, `emit` rejects with an aggregate error of all errors.
1291
+ *
1292
+ * @param type - The type of event to emit.
1293
+ * @param data - The data to pass to the subscribers.
1294
+ */
1295
+ emit(type: number, data: any): Promise<void>;
1296
+ }
1297
+ //#endregion
1298
+ //#region src/shared/awaiter.d.ts
1299
+ interface IJobAwaiter {
1300
+ /**
1301
+ * Waits for a job to complete: turns a job into a promise.
1302
+ *
1303
+ * @param jobId - The job id or job object
1304
+ * @param signal - Optional abort signal to cancel the request
1305
+ * @returns The result of the job
1306
+ */
1307
+ waitForJob(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1308
+ /**
1309
+ * Shuts down the job awaiter. This will synchronously reject all pending jobs.
1310
+ */
1311
+ shutdown(): void;
1312
+ }
1313
+ /**
1314
+ * Event-driven implementation of IJobAwaiter.
1315
+ * Subscribes to operation events to detect job completion without polling.
1316
+ */
1317
+ declare class JobAwaiter implements IJobAwaiter {
1318
+ private eventBus;
1319
+ private getJobStatus;
1320
+ private pendingJobs;
1321
+ private unsubscribers;
1322
+ constructor(eventBus: IEventBus, getJobStatus: (jobId: string, signal?: AbortSignal) => Promise<JobInfo>);
1323
+ private subscribeToEvents;
1324
+ shutdown(): void;
1325
+ waitForJob(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1326
+ private handleWriteReady;
1327
+ private handleReadReady;
1328
+ private handleJobFailed;
1329
+ private checkAndResolveWaiters;
1330
+ }
1331
+ //#endregion
1332
+ //#region src/subs/types.d.ts
1333
+ /**
1334
+ * Error handler for subscription callback errors
1335
+ */
1336
+ interface ISubscriptionErrorHandler {
1337
+ /**
1338
+ * Called when a subscription callback throws an error
1339
+ * @param error - The error that was thrown
1340
+ * @param context - Context about which subscription failed
1341
+ */
1342
+ handleError(error: unknown, context: SubscriptionErrorContext): void;
1343
+ }
1344
+ /**
1345
+ * Context information about a subscription error
1346
+ */
1347
+ interface SubscriptionErrorContext {
1348
+ /** The type of event that was being processed */
1349
+ eventType: "created" | "deleted" | "updated" | "relationshipChanged";
1350
+ /** The subscription ID that failed */
1351
+ subscriptionId: string;
1352
+ /** Optional additional data about the event */
1353
+ eventData?: unknown;
1354
+ }
1355
+ /**
1356
+ * Interface for subscribing to document events in the reactor.
1357
+ */
1358
+ interface IReactorSubscriptionManager {
1359
+ /**
1360
+ * Subscribes to document creation events
1361
+ *
1362
+ * @param callback - Function called when documents are created
1363
+ * @param search - Optional search filter to limit which documents trigger events
1364
+ * @param view - Optional filter containing branch and scopes information
1365
+ * @returns A function that unsubscribes from the events
1366
+ */
1367
+ onDocumentCreated(callback: (result: PagedResults<string>) => void, search?: SearchFilter): () => void;
1368
+ /**
1369
+ * Subscribes to document deletion events
1370
+ *
1371
+ * @param callback - Function called when documents are deleted
1372
+ * @param search - Optional search filter to limit which documents trigger events
1373
+ * @returns A function that unsubscribes from the events
1374
+ */
1375
+ onDocumentDeleted(callback: (documentIds: string[]) => void, search?: SearchFilter): () => void;
1376
+ /**
1377
+ * Subscribes to document state updates
1378
+ *
1379
+ * @param callback - Function called when documents are updated
1380
+ * @param search - Optional search filter to limit which documents trigger events
1381
+ * @param view - Optional filter containing branch and scopes information
1382
+ * @returns A function that unsubscribes from the events
1383
+ */
1384
+ onDocumentStateUpdated(callback: (result: PagedResults<PHDocument>) => void, search?: SearchFilter, view?: ViewFilter): () => void;
1385
+ /**
1386
+ * Subscribes to parent-child relationship change events
1387
+ *
1388
+ * @param callback - Function called when parent-child relationships change
1389
+ * @param search - Optional search filter to limit which documents trigger events
1390
+ * @returns A function that unsubscribes from the events
1391
+ */
1392
+ onRelationshipChanged(callback: (parentId: string, childId: string, changeType: RelationshipChangeType) => void, search?: SearchFilter): () => void;
1393
+ }
1394
+ //#endregion
1395
+ //#region src/client/types.d.ts
1396
+ /**
1397
+ * Describes the types of document changes that can occur.
1398
+ */
1399
+ declare enum DocumentChangeType {
1400
+ Created = "created",
1401
+ Deleted = "deleted",
1402
+ Updated = "updated",
1403
+ ParentAdded = "parent_added",
1404
+ ParentRemoved = "parent_removed",
1405
+ ChildAdded = "child_added",
1406
+ ChildRemoved = "child_removed"
1407
+ }
1408
+ /**
1409
+ * Represents a change event for documents.
1410
+ */
1411
+ type DocumentChangeEvent = {
1412
+ type: DocumentChangeType;
1413
+ documents: PHDocument[];
1414
+ context?: {
1415
+ parentId?: string;
1416
+ childId?: string;
1417
+ };
1418
+ };
1419
+ /**
1420
+ * Options for creating an empty document.
1421
+ */
1422
+ type CreateDocumentOptions = {
1423
+ /** Optional "id" or "slug" of parent document */parentIdentifier?: string; /** Optional version of the document model to use (defaults to latest) */
1424
+ documentModelVersion?: number;
1425
+ };
1426
+ /**
1427
+ * Drive-aware operations grouped under `client.drives`.
1428
+ *
1429
+ * These methods orchestrate the multi-action, multi-document choreography
1430
+ * required to keep a drive's `state.global.nodes` array consistent with the
1431
+ * relationship index and the underlying documents. Use the flat
1432
+ * `IReactorClient` primitives (`get`, `execute`, `find`) for everything that
1433
+ * is not drive-aware.
1434
+ */
1435
+ interface IDriveClient {
1436
+ /**
1437
+ * Creates a new drive document and waits for completion.
1438
+ */
1439
+ create(input: DriveInput, signal?: AbortSignal): Promise<DocumentDriveDocument>;
1440
+ /**
1441
+ * Adds a document to a drive as a single batched operation.
1442
+ *
1443
+ * Issues CREATE_DOCUMENT, UPGRADE_DOCUMENT, ADD_RELATIONSHIP on the new
1444
+ * document and ADD_FILE on the drive in a single dependent batch.
1445
+ */
1446
+ addFile<TDocument extends PHDocument = PHDocument>(driveIdentifier: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
1447
+ /**
1448
+ * Adds a folder node to a drive.
1449
+ */
1450
+ addFolder(driveIdentifier: string, name: string, parentFolder?: string, signal?: AbortSignal): Promise<FolderNode>;
1451
+ /**
1452
+ * Removes a node from a drive. Folder nodes cascade: descendant file
1453
+ * documents are deleted first, then the folder node entry itself.
1454
+ */
1455
+ removeNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<void>;
1456
+ /**
1457
+ * Renames a node. Updates both the underlying document header and the
1458
+ * drive's node entry.
1459
+ */
1460
+ renameNode(driveIdentifier: string, nodeId: string, name: string, signal?: AbortSignal): Promise<Node>;
1461
+ /**
1462
+ * Updates the preferred editor recorded in the document header meta for
1463
+ * a node. Pass `null` to clear it.
1464
+ */
1465
+ setPreferredEditorOnNode(nodeId: string, preferredEditor: string | null, signal?: AbortSignal): Promise<PHDocument>;
1466
+ /**
1467
+ * Moves a node to a different parent folder within the same drive.
1468
+ * Pass `undefined` to move the node to the drive root.
1469
+ */
1470
+ moveNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
1471
+ /**
1472
+ * Copies a node (and its subtree, if it is a folder) within a drive.
1473
+ * Each copied file gets a new id and a duplicated document.
1474
+ */
1475
+ copyNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
1476
+ /**
1477
+ * Returns a single node from the drive's `state.global.nodes` array.
1478
+ */
1479
+ getNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<Node>;
1480
+ /**
1481
+ * Returns nodes in the drive, optionally filtered by parent folder:
1482
+ * - omit `parentFolder` (or pass `undefined`) to list every node in the drive.
1483
+ * - pass `null` to list only root-level nodes.
1484
+ * - pass a folder id to list only the direct children of that folder.
1485
+ *
1486
+ * Returns a paged result so callers can stream through drives with very
1487
+ * large node counts without materialising the whole list in memory.
1488
+ */
1489
+ listNodes(driveIdentifier: string, parentFolder?: string | null, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Node>>;
1490
+ }
1491
+ /**
1492
+ * The ReactorClient interface that wraps lower-level APIs to provide
1493
+ * a simpler interface for document operations.
1494
+ *
1495
+ * Features:
1496
+ * - Wraps Jobs with Promises for easier async handling
1497
+ * - Manages signing of submitted Action objects
1498
+ * - Provides quality-of-life functions for common tasks
1499
+ * - Wraps subscription interface with ViewFilters
1500
+ */
1501
+ interface IReactorClient {
1502
+ /**
1503
+ * Drive-aware operations. See {@link IDriveClient}.
1504
+ */
1505
+ readonly drives: IDriveClient;
1506
+ /**
1507
+ * Retrieves a list of document model modules.
1508
+ *
1509
+ * @param namespace - Optional namespace like "powerhouse" or "sky", defaults to ""
1510
+ * @param paging - Optional pagination options
1511
+ * @param signal - Optional abort signal to cancel the request
1512
+ * @returns List of document model modules
1513
+ */
1514
+ getDocumentModelModules(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
1515
+ /**
1516
+ * Retrieves a specific document model module by document type.
1517
+ *
1518
+ * @param documentType - The document type identifier
1519
+ * @returns The document model module
1520
+ */
1521
+ getDocumentModelModule(documentType: string): Promise<DocumentModelModule<any>>;
1522
+ /**
1523
+ * Retrieves a specific document by identifier (either id or slug).
1524
+ *
1525
+ * @param identifier - Required, this is the document id or slug
1526
+ * @param view - Optional filter containing branch and scopes information
1527
+ * @param signal - Optional abort signal to cancel the request
1528
+ * @returns The up-to-date PHDocument with scopes and list of child document ids
1529
+ */
1530
+ get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<TDocument>;
1531
+ /**
1532
+ * Retrieves operations for a document.
1533
+ *
1534
+ * @param documentIdentifier - Required, this is either a document "id" field or a "slug"
1535
+ * @param view - Optional filter containing branch and scopes information
1536
+ * @param filter - Optional filter for actionTypes, timestamps, and revision
1537
+ * @param paging - Optional pagination options
1538
+ * @param signal - Optional abort signal to cancel the request
1539
+ * @returns Paginated list of operations
1540
+ */
1541
+ getOperations(documentIdentifier: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
1542
+ /**
1543
+ * Retrieves outgoing relationships of a given type from a source document.
1544
+ *
1545
+ * @param sourceIdentifier - Required, this is either a document "id" field or a "slug"
1546
+ * @param relationshipType - The relationship type to filter by
1547
+ * @param view - Optional filter containing branch and scopes information
1548
+ * @param paging - Optional pagination options
1549
+ * @param signal - Optional abort signal to cancel the request
1550
+ * @returns The target documents and paging cursor
1551
+ */
1552
+ getOutgoingRelationships(sourceIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1553
+ /**
1554
+ * Retrieves incoming relationships of a given type to a target document.
1555
+ *
1556
+ * @param targetIdentifier - Required, this is either a document "id" field or a "slug"
1557
+ * @param relationshipType - The relationship type to filter by
1558
+ * @param view - Optional filter containing branch and scopes information
1559
+ * @param paging - Optional pagination options
1560
+ * @param signal - Optional abort signal to cancel the request
1561
+ * @returns The source documents and paging cursor
1562
+ */
1563
+ getIncomingRelationships(targetIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1564
+ /**
1565
+ * Filters documents by criteria and returns a list of them
1566
+ *
1567
+ * @param search - Search filter options (type, parentId, identifiers)
1568
+ * @param view - Optional filter containing branch and scopes information
1569
+ * @param paging - Optional pagination options
1570
+ * @param signal - Optional abort signal to cancel the request
1571
+ * @returns List of documents matching criteria and pagination cursor
1572
+ */
1573
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1574
+ /**
1575
+ * Creates a document and waits for completion
1576
+ *
1577
+ * @param document - Document with optional id, slug, parent, model type, and initial state
1578
+ * @param parentIdentifier - Optional "id" or "slug" of parent document
1579
+ * @param signal - Optional abort signal to cancel the request
1580
+ * @returns The created document
1581
+ */
1582
+ create<TDocument extends PHDocument = PHDocument>(document: PHDocument, parentIdentifier?: string, signal?: AbortSignal): Promise<TDocument>;
1583
+ /**
1584
+ * Creates an empty document and waits for completion
1585
+ *
1586
+ * @param documentModelType - Type of document to create
1587
+ * @param options - Optional creation options (parentIdentifier, documentModelVersion)
1588
+ * @param signal - Optional abort signal to cancel the request
1589
+ */
1590
+ createEmpty<TDocument extends PHDocument>(documentModelType: string, options?: CreateDocumentOptions, signal?: AbortSignal): Promise<TDocument>;
1591
+ /**
1592
+ * Creates an empty document in a drive as a single batched operation.
1593
+ * This is more efficient than createEmpty + addFile as it batches all
1594
+ * actions into dependent jobs and waits for them to complete together.
1595
+ *
1596
+ * @deprecated Use {@link IDriveClient.addFile} via `client.drives.addFile`
1597
+ * instead. This method will be removed in a future release.
1598
+ * @param driveId - The drive document id or slug
1599
+ * @param document - The document to create
1600
+ * @param parentFolder - Optional folder id within the drive
1601
+ * @param signal - Optional abort signal to cancel the request
1602
+ * @returns The created document
1603
+ */
1604
+ createDocumentInDrive<TDocument extends PHDocument>(driveId: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
1605
+ /**
1606
+ * Applies a list of actions to a document and waits for completion
1607
+ *
1608
+ * @param documentIdentifier - Target document id or slug
1609
+ * @param branch - Branch to apply actions to
1610
+ * @param actions - List of actions to apply
1611
+ * @param signal - Optional abort signal to cancel the request
1612
+ * @returns The updated document
1613
+ */
1614
+ execute<TDocument extends PHDocument>(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<TDocument>;
1615
+ /**
1616
+ * Submits a list of actions to a document
1617
+ *
1618
+ * @param documentIdentifier - Target document id or slug
1619
+ * @param branch - Branch to apply actions to
1620
+ * @param actions - List of actions to apply
1621
+ * @param signal - Optional abort signal to cancel the request
1622
+ * @returns The job
1623
+ */
1624
+ executeAsync(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<JobInfo>;
1625
+ /**
1626
+ * Applies multiple mutation jobs in dependency order and waits for all to
1627
+ * complete. Actions on each job are signed by the client signer before
1628
+ * dispatch. Throws on the first failed job; the others may still execute
1629
+ * because dispatch is fire-and-await-all.
1630
+ *
1631
+ * @param request - Batch mutation request with per-job actions and dependsOn keys
1632
+ * @param signal - Optional abort signal to cancel the request
1633
+ * @returns The completed batch result (job ids keyed by plan key)
1634
+ */
1635
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal): Promise<BatchExecutionResult>;
1636
+ /**
1637
+ * Renames a document and waits for completion
1638
+ *
1639
+ * @param documentIdentifier - Target document id or slug
1640
+ * @param name - The new name of the document
1641
+ * @param branch - Optional branch to rename the document, defaults to "main"
1642
+ * @param signal - Optional abort signal to cancel the request
1643
+ * @returns The updated document.
1644
+ */
1645
+ rename(documentIdentifier: string, name: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1646
+ /**
1647
+ * Updates the preferred editor in the document header meta and waits for completion.
1648
+ *
1649
+ * @param documentIdentifier - Target document id or slug
1650
+ * @param preferredEditor - The new preferred editor, or `null` to clear it
1651
+ * @param branch - Optional branch, defaults to "main"
1652
+ * @param signal - Optional abort signal to cancel the request
1653
+ * @returns The updated document.
1654
+ */
1655
+ setPreferredEditor(documentIdentifier: string, preferredEditor: string | null, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1656
+ /**
1657
+ * Adds a relationship between two documents and waits for completion.
1658
+ *
1659
+ * @param sourceIdentifier - Source document id or slug
1660
+ * @param targetIdentifier - Target document id or slug
1661
+ * @param relationshipType - Relationship type identifier
1662
+ * @param branch - Optional branch to add the relationship to, defaults to "main"
1663
+ * @param signal - Optional abort signal to cancel the request
1664
+ * @returns The updated source document
1665
+ */
1666
+ addRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1667
+ /**
1668
+ * Removes a relationship between two documents and waits for completion.
1669
+ *
1670
+ * @param sourceIdentifier - Source document id or slug
1671
+ * @param targetIdentifier - Target document id or slug
1672
+ * @param relationshipType - Relationship type identifier
1673
+ * @param branch - Optional branch to remove the relationship from, defaults to "main"
1674
+ * @param signal - Optional abort signal to cancel the request
1675
+ * @returns The updated source document
1676
+ */
1677
+ removeRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1678
+ /**
1679
+ * Moves a relationship from one source document to another and waits for completion.
1680
+ *
1681
+ * @param sourceParentIdentifier - Source parent document id or slug
1682
+ * @param targetParentIdentifier - Target parent document id or slug
1683
+ * @param targetIdentifier - The target document id or slug
1684
+ * @param relationshipType - Relationship type identifier
1685
+ * @param branch - Optional branch to apply the move to, defaults to "main"
1686
+ * @param signal - Optional abort signal to cancel the request
1687
+ * @returns The updated source and target documents
1688
+ */
1689
+ moveRelationship(sourceParentIdentifier: string, targetParentIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<{
1690
+ source: PHDocument;
1691
+ target: PHDocument;
1692
+ }>;
1693
+ /**
1694
+ * Deletes a document and waits for completion
1695
+ *
1696
+ * @param identifier - Document identifier (id or slug)
1697
+ * @param propagate - Optional mode for handling children, CASCADE deletes child documents
1698
+ * @param signal - Optional abort signal to cancel the request
1699
+ * @returns a promise, resolving on deletion confirmation
1700
+ */
1701
+ deleteDocument(identifier: string, propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1702
+ /**
1703
+ * Deletes documents and waits for completion
1704
+ *
1705
+ * @param identifiers - Document identifiers (ids or slugs)
1706
+ * @param propagate - Optional mode for handling children, CASCADE deletes child documents
1707
+ * @param signal - Optional abort signal to cancel the request
1708
+ * @returns a promise, resolving on deletion confirmation
1709
+ */
1710
+ deleteDocuments(identifiers: string[], propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1711
+ /**
1712
+ * Loads multiple batches of pre-existing operations across documents with dependency management.
1713
+ * Waits for all jobs to complete.
1714
+ *
1715
+ * @param request - Batch load request containing jobs with dependencies
1716
+ * @param signal - Optional abort signal to cancel the request
1717
+ * @returns Map of job keys to completed job information
1718
+ */
1719
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal): Promise<BatchLoadResult>;
1720
+ /**
1721
+ * Retrieves the status of a job
1722
+ *
1723
+ * @param jobId - The job id
1724
+ * @param signal - Optional abort signal to cancel the request
1725
+ * @returns The job status
1726
+ */
1727
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1728
+ /**
1729
+ * Waits for a job to complete
1730
+ *
1731
+ * @param jobId - The job id or job object
1732
+ * @param signal - Optional abort signal to cancel the request
1733
+ * @returns The result of the job
1734
+ */
1735
+ waitForJob(jobId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo>;
1736
+ /**
1737
+ * Subscribes to changes for documents matching specified filters
1738
+ *
1739
+ * @param search - Search filter options (type, parentId, identifiers)
1740
+ * @param callback - Function called when documents change with the change event details
1741
+ * @param view - Optional filter containing branch and scopes information
1742
+ * @returns A function that unsubscribes from the changes
1743
+ */
1744
+ subscribe(search: SearchFilter, callback: (event: DocumentChangeEvent) => void, view?: ViewFilter): () => void;
1745
+ }
1746
+ //#endregion
1747
+ //#region src/client/reactor-client.d.ts
1748
+ /**
1749
+ * ReactorClient implementation that wraps lower-level APIs to provide
1750
+ * a simpler interface for document operations.
1751
+ *
1752
+ * Features:
1753
+ * - Wraps Jobs with Promises for easier async handling
1754
+ * - Manages signing of submitted Action objects
1755
+ * - Provides quality-of-life functions for common tasks
1756
+ * - Wraps subscription interface with ViewFilters
1757
+ */
1758
+ declare class ReactorClient implements IReactorClient {
1759
+ private logger;
1760
+ private reactor;
1761
+ private signer;
1762
+ private subscriptionManager;
1763
+ private jobAwaiter;
1764
+ private documentIndexer;
1765
+ private documentView;
1766
+ readonly drives: IDriveClient;
1767
+ constructor(logger: ILogger, reactor: IReactor, signer: ISigner, subscriptionManager: IReactorSubscriptionManager, jobAwaiter: IJobAwaiter, documentIndexer: IDocumentIndexer, documentView: IDocumentView);
1768
+ /**
1769
+ * Retrieves a list of document model modules.
1770
+ */
1771
+ getDocumentModelModules(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
1772
+ /**
1773
+ * Retrieves a specific document model module by document type.
1774
+ *
1775
+ * @param documentType - The document type identifier
1776
+ * @returns The document model module
1777
+ */
1778
+ getDocumentModelModule(documentType: string): Promise<DocumentModelModule<any>>;
1779
+ /**
1780
+ * Retrieves a specific PHDocument
1781
+ */
1782
+ get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<TDocument>;
1783
+ /**
1784
+ * Retrieves operations for a document
1785
+ */
1786
+ getOperations(documentIdentifier: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
1787
+ private getOperationsWithCompositeCursor;
1788
+ /**
1789
+ * Retrieves outgoing relationships of a given type from a source document.
1790
+ */
1791
+ getOutgoingRelationships(sourceIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1792
+ /**
1793
+ * Retrieves incoming relationships of a given type to a target document.
1794
+ */
1795
+ getIncomingRelationships(targetIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1796
+ /**
1797
+ * Filters documents by criteria and returns a list of them
1798
+ */
1799
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
1800
+ /**
1801
+ * Creates a document and waits for completion
1802
+ */
1803
+ create<TDocument extends PHDocument = PHDocument>(document: PHDocument, parentIdentifier?: string, signal?: AbortSignal): Promise<TDocument>;
1804
+ /**
1805
+ * Creates an empty document and waits for completion
1806
+ */
1807
+ createEmpty<TDocument extends PHDocument>(documentModelType: string, options?: CreateDocumentOptions, signal?: AbortSignal): Promise<TDocument>;
1808
+ /**
1809
+ * Creates an empty document in a drive as a single batched operation.
1810
+ * Delegates to {@link IDriveClient.addFile}.
1811
+ *
1812
+ * @deprecated Use `client.drives.addFile` instead. This method will be
1813
+ * removed in a future release.
1814
+ */
1815
+ createDocumentInDrive<TDocument extends PHDocument>(driveId: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
1816
+ /**
1817
+ * Applies a list of actions to a document and waits for completion
1818
+ */
1819
+ execute<TDocument extends PHDocument>(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<TDocument>;
1820
+ /**
1821
+ * Submits a list of actions to a document
1822
+ */
1823
+ executeAsync(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<JobInfo>;
1824
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal): Promise<BatchExecutionResult>;
1825
+ /**
1826
+ * Renames a document and waits for completion
1827
+ */
1828
+ rename(documentIdentifier: string, name: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1829
+ /**
1830
+ * Updates the preferred editor recorded in the document header meta.
1831
+ * Pass `null` to clear it.
1832
+ */
1833
+ setPreferredEditor(documentIdentifier: string, preferredEditor: string | null, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1834
+ /**
1835
+ * Adds multiple documents as children to another and waits for completion
1836
+ */
1837
+ addRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1838
+ /**
1839
+ * Removes a relationship between two documents and waits for completion.
1840
+ */
1841
+ removeRelationship(sourceIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
1842
+ /**
1843
+ * Moves a relationship from one source document to another and waits for completion.
1844
+ */
1845
+ moveRelationship(sourceParentIdentifier: string, targetParentIdentifier: string, targetIdentifier: string, relationshipType: string, branch?: string, signal?: AbortSignal): Promise<{
1846
+ source: PHDocument;
1847
+ target: PHDocument;
1848
+ }>;
1849
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal): Promise<BatchLoadResult>;
1850
+ /**
1851
+ * Deletes a document and waits for completion
1852
+ */
1853
+ deleteDocument(identifier: string, propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1854
+ /**
1855
+ * Deletes documents and waits for completion
1856
+ */
1857
+ deleteDocuments(identifiers: string[], propagate?: PropagationMode, signal?: AbortSignal): Promise<void>;
1858
+ /**
1859
+ * Retrieves the status of a job
1860
+ */
1861
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
1862
+ /**
1863
+ * Waits for a job to complete
1864
+ */
1865
+ waitForJob(jobId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo>;
1866
+ /**
1867
+ * Subscribes to changes for documents matching specified filters
1868
+ */
1869
+ subscribe(search: SearchFilter, callback: (event: DocumentChangeEvent) => void, view?: ViewFilter): () => void;
1870
+ private removeAllIncomingRelationships;
1871
+ }
1872
+ //#endregion
1873
+ //#region src/executor/types.d.ts
1874
+ /**
1875
+ * Represents the result of a job execution
1876
+ */
1877
+ type JobResult = {
1878
+ /** The job that was executed */job: Job; /** Whether the job executed successfully */
1879
+ success: boolean; /** Error if the job failed */
1880
+ error?: Error; /** The operations generated from the actions (if successful) */
1881
+ operations?: Operation[];
1882
+ /**
1883
+ * Operations with context (includes ephemeral resultingState).
1884
+ * Used for emitting to IDocumentView via event bus.
1885
+ */
1886
+ operationsWithContext?: OperationWithContext$1[]; /** Timestamp when the job execution completed */
1887
+ completedAt?: string; /** Duration of job execution in milliseconds */
1888
+ duration?: number; /** Any additional metadata from the execution */
1889
+ metadata?: Record<string, any>;
1890
+ };
1891
+ /**
1892
+ * Configuration options for the job executor
1893
+ */
1894
+ type JobExecutorConfig = {
1895
+ /** Maximum number of conflicting operations to skip when reshuffling. */maxSkipThreshold?: number; /** Maximum number of concurrent jobs to execute */
1896
+ maxConcurrency?: number; /** Maximum time in milliseconds a job can run before being considered timed out */
1897
+ jobTimeoutMs?: number; /** Base delay in milliseconds for exponential backoff retries */
1898
+ retryBaseDelayMs?: number; /** Maximum delay in milliseconds for exponential backoff retries */
1899
+ retryMaxDelayMs?: number;
1900
+ /** Maximum elapsed milliseconds before yielding to the main thread between actions.
1901
+ * Keeps the UI responsive when processing large batches. */
1902
+ yieldDeadlineMs?: number;
1903
+ };
1904
+ /**
1905
+ * Event types for the job executor
1906
+ */
1907
+ declare const JobExecutorEventTypes: {
1908
+ readonly JOB_STARTED: 20000;
1909
+ readonly JOB_COMPLETED: 20001;
1910
+ readonly JOB_FAILED: 20002;
1911
+ readonly EXECUTOR_STARTED: 20003;
1912
+ readonly EXECUTOR_STOPPED: 20004;
1913
+ };
1914
+ /**
1915
+ * Event data for job execution events
1916
+ */
1917
+ type JobStartedEvent = {
1918
+ job: Job;
1919
+ startedAt: string;
1920
+ };
1921
+ type JobCompletedEvent = {
1922
+ job: Job;
1923
+ result: JobResult;
1924
+ };
1925
+ type JobFailedEvent = {
1926
+ job: Job;
1927
+ error: string;
1928
+ willRetry: boolean;
1929
+ retryCount: number;
1930
+ };
1931
+ type ExecutorStartedEvent = {
1932
+ config: JobExecutorConfig;
1933
+ startedAt: string;
1934
+ };
1935
+ type ExecutorStoppedEvent = {
1936
+ stoppedAt: string;
1937
+ graceful: boolean;
1938
+ };
1939
+ /**
1940
+ * Status information for the job executor manager
1941
+ */
1942
+ type ExecutorManagerStatus = {
1943
+ /** Whether the manager is currently running */isRunning: boolean; /** Number of executor instances managed */
1944
+ numExecutors: number; /** Number of jobs currently being processed */
1945
+ activeJobs: number; /** Total number of jobs processed since start */
1946
+ totalJobsProcessed: number;
1947
+ };
1948
+ //#endregion
1949
+ //#region src/executor/interfaces.d.ts
1950
+ /**
1951
+ * Simple interface for executing a job.
1952
+ * A JobExecutor simply takes a job and executes it - nothing more.
1953
+ */
1954
+ interface IJobExecutor {
1955
+ /**
1956
+ * Execute a single job.
1957
+ * @param job - The job to execute
1958
+ * @returns Promise that resolves to the job result
1959
+ */
1960
+ executeJob(job: Job, signal?: AbortSignal): Promise<JobResult>;
1961
+ }
1962
+ /**
1963
+ * Interface for managing multiple job executors.
1964
+ * Listens for 'jobAvailable' events from the event bus, pulls jobs from the queue,
1965
+ * and coordinates the distribution of jobs across multiple executor instances.
1966
+ */
1967
+ interface IJobExecutorManager {
1968
+ /**
1969
+ * Start the executor manager.
1970
+ * Begins listening for 'jobAvailable' events and dispatching to executors.
1971
+ *
1972
+ * @param numExecutors - Number of executor instances to create
1973
+ * @returns Promise that resolves when the manager is started
1974
+ */
1975
+ start(numExecutors: number): Promise<void>;
1976
+ /**
1977
+ * Stop the executor manager.
1978
+ *
1979
+ * @param graceful - Whether to wait for current jobs to complete
1980
+ * @returns Promise that resolves when the manager is stopped
1981
+ */
1982
+ stop(graceful?: boolean): Promise<void>;
1983
+ /**
1984
+ * Get all managed executor instances.
1985
+ *
1986
+ * @returns Array of executor instances
1987
+ */
1988
+ getExecutors(): IJobExecutor[];
1989
+ /**
1990
+ * Get the current status of the manager.
1991
+ *
1992
+ * @returns The current manager status
1993
+ */
1994
+ getStatus(): ExecutorManagerStatus;
1995
+ }
1996
+ //#endregion
1997
+ //#region src/job-tracker/interfaces.d.ts
1998
+ /**
1999
+ * Interface for tracking job lifecycle status.
2000
+ * Maintains job state throughout execution: PENDING → RUNNING → COMPLETED/FAILED.
2001
+ */
2002
+ interface IJobTracker {
2003
+ /**
2004
+ * Register a new job with PENDING status.
2005
+ *
2006
+ * @param jobInfo - The job information to register
2007
+ */
2008
+ registerJob(jobInfo: JobInfo): void;
2009
+ /**
2010
+ * Update a job's status to RUNNING.
2011
+ *
2012
+ * @param jobId - The job ID to mark as running
2013
+ */
2014
+ markRunning(jobId: string): void;
2015
+ /**
2016
+ * Mark a job as failed.
2017
+ *
2018
+ * @param jobId - The job ID to mark as failed
2019
+ * @param error - Error information including message and stack trace
2020
+ * @param job - Optional full job object for debugging purposes
2021
+ */
2022
+ markFailed(jobId: string, error: ErrorInfo, job?: Job): void;
2023
+ /**
2024
+ * Retrieve the current status of a job.
2025
+ *
2026
+ * @param jobId - The job ID to query
2027
+ * @returns The job information, or null if the job is not found
2028
+ */
2029
+ getJobStatus(jobId: string): JobInfo | null;
2030
+ /**
2031
+ * Shutdown the job tracker and clean up resources.
2032
+ * Unsubscribes from all event bus subscriptions.
2033
+ */
2034
+ shutdown(): void;
2035
+ }
2036
+ //#endregion
2037
+ //#region src/queue/interfaces.d.ts
2038
+ /**
2039
+ * Interface for a job queue that manages write operations.
2040
+ * Internally organizes jobs by documentId, scope, and branch to ensure proper ordering.
2041
+ * Emits events to the event bus when new jobs are available for consumption.
2042
+ */
2043
+ interface IQueue {
2044
+ /**
2045
+ * Add a new job to the queue.
2046
+ * Jobs are automatically organized by documentId, scope, and branch internally.
2047
+ * Emits a 'jobAvailable' event to the event bus when the job is queued.
2048
+ * @param job - The job to add to the queue
2049
+ * @returns Promise that resolves when the job is queued
2050
+ */
2051
+ enqueue(job: Job): Promise<void>;
2052
+ /**
2053
+ * Get the next job to execute for a specific document/scope/branch combination.
2054
+ * @param documentId - The document ID to get jobs for
2055
+ * @param scope - The scope to get jobs for
2056
+ * @param branch - The branch to get jobs for
2057
+ * @param signal - Optional abort signal to cancel the request
2058
+ * @returns Promise that resolves to the next job execution handle or null if no jobs available
2059
+ */
2060
+ dequeue(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
2061
+ /**
2062
+ * Get the next available job from any queue.
2063
+ * @param signal - Optional abort signal to cancel the request
2064
+ * @returns Promise that resolves to the next job execution handle or null if no jobs available
2065
+ */
2066
+ dequeueNext(signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
2067
+ /**
2068
+ * Get the current size of the queue for a specific document/scope/branch.
2069
+ * @param documentId - The document ID
2070
+ * @param scope - The scope
2071
+ * @param branch - The branch
2072
+ * @returns Promise that resolves to the number of jobs in the queue
2073
+ */
2074
+ size(documentId: string, scope: string, branch: string): Promise<number>;
2075
+ /**
2076
+ * Get the total size of all queues.
2077
+ * @returns Promise that resolves to the total number of jobs across all queues
2078
+ */
2079
+ totalSize(): Promise<number>;
2080
+ /**
2081
+ * Remove a specific job from the queue.
2082
+ * @param jobId - The ID of the job to remove
2083
+ * @returns Promise that resolves to true if job was removed, false if not found
2084
+ */
2085
+ remove(jobId: string): Promise<boolean>;
2086
+ /**
2087
+ * Clear all jobs for a specific document/scope/branch combination.
2088
+ * @param documentId - The document ID
2089
+ * @param scope - The scope
2090
+ * @param branch - The branch
2091
+ * @returns Promise that resolves when the queue is cleared
2092
+ */
2093
+ clear(documentId: string, scope: string, branch: string): Promise<void>;
2094
+ /**
2095
+ * Clear all jobs from all queues.
2096
+ * @returns Promise that resolves when all queues are cleared
2097
+ */
2098
+ clearAll(): Promise<void>;
2099
+ /**
2100
+ * Check if there are any jobs in the queue.
2101
+ * @returns Promise that resolves to true if there are jobs, false otherwise
2102
+ */
2103
+ hasJobs(): Promise<boolean>;
2104
+ /**
2105
+ * Mark a job as completed.
2106
+ * @param jobId - The ID of the job to mark as completed
2107
+ * @returns Promise that resolves when the job is marked as completed
2108
+ */
2109
+ completeJob(jobId: string): Promise<void>;
2110
+ /**
2111
+ * Mark a job as failed.
2112
+ * @param jobId - The ID of the job to mark as failed
2113
+ * @param error - Optional error information
2114
+ * @returns Promise that resolves when the job is marked as failed
2115
+ */
2116
+ failJob(jobId: string, error?: ErrorInfo): Promise<void>;
2117
+ /**
2118
+ * Retry a failed job.
2119
+ * @param jobId - The ID of the job to retry
2120
+ * @param error - Optional error information from the failure
2121
+ * @returns Promise that resolves when the job is requeued for retry
2122
+ */
2123
+ retryJob(jobId: string, error?: ErrorInfo): Promise<void>;
2124
+ /**
2125
+ * Returns true if and only if all jobs have been resolved.
2126
+ */
2127
+ get isDrained(): boolean;
2128
+ /**
2129
+ * Blocks the queue from accepting new jobs.
2130
+ * @param onDrained - Optional callback to call when the queue is drained
2131
+ */
2132
+ block(onDrained?: () => void): void;
2133
+ /**
2134
+ * Unblocks the queue from accepting new jobs.
2135
+ */
2136
+ unblock(): void;
2137
+ }
2138
+ //#endregion
2139
+ //#region src/read-models/types.d.ts
2140
+ interface ViewStateTable {
2141
+ readModelId: string;
2142
+ lastOrdinal: number;
2143
+ lastOperationTimestamp: Generated<Date>;
2144
+ }
2145
+ interface DocumentSnapshotTable {
2146
+ id: Generated<string>;
2147
+ documentId: string;
2148
+ slug: string | null;
2149
+ name: string | null;
2150
+ scope: string;
2151
+ branch: string;
2152
+ content: unknown;
2153
+ documentType: string;
2154
+ lastOperationIndex: number;
2155
+ lastOperationHash: string;
2156
+ lastUpdatedAt: Generated<Date>;
2157
+ snapshotVersion: Generated<number>;
2158
+ identifiers: unknown;
2159
+ metadata: unknown;
2160
+ isDeleted: Generated<boolean>;
2161
+ deletedAt: Date | null;
2162
+ }
2163
+ interface SlugMappingTable {
2164
+ slug: string;
2165
+ documentId: string;
2166
+ scope: string;
2167
+ branch: string;
2168
+ createdAt: Generated<Date>;
2169
+ updatedAt: Generated<Date>;
2170
+ }
2171
+ interface ProcessorCursorTable {
2172
+ processorId: string;
2173
+ factoryId: string;
2174
+ driveId: string;
2175
+ processorIndex: number;
2176
+ lastOrdinal: Generated<number>;
2177
+ status: Generated<string>;
2178
+ lastError: string | null;
2179
+ lastErrorTimestamp: Date | null;
2180
+ createdAt: Generated<Date>;
2181
+ updatedAt: Generated<Date>;
2182
+ }
2183
+ interface DocumentViewDatabase {
2184
+ ViewState: ViewStateTable;
2185
+ DocumentSnapshot: DocumentSnapshotTable;
2186
+ SlugMapping: SlugMappingTable;
2187
+ ProcessorCursor: ProcessorCursorTable;
2188
+ }
2189
+ type InsertableDocumentSnapshot = Insertable<DocumentSnapshotTable>;
2190
+ //#endregion
2191
+ //#region src/registry/interfaces.d.ts
2192
+ type RegistrationResult<T> = {
2193
+ status: "success";
2194
+ item: T;
2195
+ } | {
2196
+ status: "error";
2197
+ item: T;
2198
+ error: Error;
2199
+ };
2200
+ /**
2201
+ * Loader that can asynchronously resolve and return a document model module
2202
+ * for a given document type. Used by the queue to gate CREATE_DOCUMENT jobs
2203
+ * until the required model is available in the registry.
2204
+ */
2205
+ interface IDocumentModelLoader {
2206
+ load(documentType: string): Promise<DocumentModelModule<any>>;
2207
+ }
2208
+ /**
2209
+ * Registry for managing document model modules.
2210
+ * Provides centralized access to document models' reducers, utils, and specifications.
2211
+ * Supports version-aware module storage and upgrade manifest management.
2212
+ */
2213
+ interface IDocumentModelRegistry {
2214
+ /**
2215
+ * Register multiple modules at once.
2216
+ * Modules without a version field default to version 1.
2217
+ * Invalid or duplicate modules are skipped without breaking registration of the remaining modules.
2218
+ *
2219
+ * @param modules Document model modules to register
2220
+ * @returns Array of results, one per module, indicating success or failure
2221
+ */
2222
+ registerModules(...modules: DocumentModelModule<any>[]): RegistrationResult<DocumentModelModule<any>>[];
2223
+ /**
2224
+ * Unregister all versions of the specified document types.
2225
+ *
2226
+ * @param documentTypes The document types to unregister
2227
+ * @returns true if all modules were unregistered, false if any were not found
2228
+ */
2229
+ unregisterModules(...documentTypes: string[]): boolean;
2230
+ /**
2231
+ * Get a specific document model module by document type and optional version.
2232
+ * If version is not specified, returns the latest version.
2233
+ *
2234
+ * @param documentType The document type identifier
2235
+ * @param version Optional version number to retrieve
2236
+ * @returns The document model module
2237
+ * @throws ModuleNotFoundError if the document type or version is not registered
2238
+ */
2239
+ getModule(documentType: string, version?: number): DocumentModelModule<any>;
2240
+ /**
2241
+ * Get all registered document model modules.
2242
+ *
2243
+ * @returns Array of all registered modules
2244
+ */
2245
+ getAllModules(): DocumentModelModule<any>[];
2246
+ /**
2247
+ * Clear all registered modules and upgrade manifests.
2248
+ */
2249
+ clear(): void;
2250
+ /**
2251
+ * Get all supported versions for a document type, sorted in ascending order.
2252
+ *
2253
+ * @param documentType The document type identifier
2254
+ * @returns Array of version numbers sorted ascending
2255
+ * @throws ModuleNotFoundError if no modules are registered for the document type
2256
+ */
2257
+ getSupportedVersions(documentType: string): number[];
2258
+ /**
2259
+ * Get the latest (highest) version number for a document type.
2260
+ *
2261
+ * @param documentType The document type identifier
2262
+ * @returns The highest version number registered for this document type
2263
+ * @throws ModuleNotFoundError if no modules are registered for the document type
2264
+ */
2265
+ getLatestVersion(documentType: string): number;
2266
+ /**
2267
+ * Register upgrade manifests that define upgrade paths between versions.
2268
+ * Invalid or duplicate manifests are skipped without breaking registration of the remaining manifests.
2269
+ *
2270
+ * @param manifests Upgrade manifests to register
2271
+ * @returns Array of results, one per manifest, indicating success or failure
2272
+ */
2273
+ registerUpgradeManifests(...manifests: UpgradeManifest<readonly number[]>[]): RegistrationResult<UpgradeManifest<readonly number[]>>[];
2274
+ /**
2275
+ * Unregister upgrade manifests for the specified document types.
2276
+ * @param documentTypes The document types whose upgrade manifests should be unregistered
2277
+ * @returns true if all modules were unregistered, false if any were not found
2278
+ **/
2279
+ unregisterUpgradeManifests(...documentTypes: string[]): boolean;
2280
+ /**
2281
+ * Get the upgrade manifest for a document type.
2282
+ *
2283
+ * @param documentType The document type identifier
2284
+ * @returns The upgrade manifest
2285
+ * @throws ManifestNotFoundError if no manifest is registered for the document type
2286
+ */
2287
+ getUpgradeManifest(documentType: string): UpgradeManifest<readonly number[]>;
2288
+ /**
2289
+ * Compute the upgrade path from one version to another.
2290
+ * Returns the sequence of upgrade transitions needed.
2291
+ *
2292
+ * @param documentType The document type identifier
2293
+ * @param fromVersion The starting version
2294
+ * @param toVersion The target version
2295
+ * @returns Array of upgrade transitions in order
2296
+ * @throws DowngradeNotSupportedError if toVersion is less than fromVersion
2297
+ * @throws ManifestNotFoundError if no upgrade manifest is registered
2298
+ * @throws MissingUpgradeTransitionError if any transition in the path is missing
2299
+ */
2300
+ computeUpgradePath(documentType: string, fromVersion: number, toVersion: number): UpgradeTransition[];
2301
+ /**
2302
+ * Get the upgrade reducer for a single-step version transition.
2303
+ *
2304
+ * @param documentType The document type identifier
2305
+ * @param fromVersion The starting version
2306
+ * @param toVersion The target version (must be fromVersion + 1)
2307
+ * @returns The upgrade reducer function
2308
+ * @throws InvalidUpgradeStepError if toVersion is not fromVersion + 1
2309
+ * @throws ManifestNotFoundError if no upgrade manifest is registered
2310
+ * @throws MissingUpgradeTransitionError if the transition is not found
2311
+ */
2312
+ getUpgradeReducer(documentType: string, fromVersion: number, toVersion: number): UpgradeReducer<any, any>;
2313
+ }
2314
+ //#endregion
2315
+ //#region src/shared/consistency-tracker.d.ts
2316
+ interface IConsistencyTracker {
2317
+ /**
2318
+ * Updates the tracker with new operation indexes.
2319
+ * When multiple coordinates have the same key, keeps the highest operationIndex.
2320
+ * Resolves any pending waiters whose coordinates are now satisfied.
2321
+ */
2322
+ update(coordinates: ConsistencyCoordinate[]): void;
2323
+ /**
2324
+ * Returns the latest operation index for a given key, or undefined if not tracked.
2325
+ */
2326
+ getLatest(key: ConsistencyKey): number | undefined;
2327
+ /**
2328
+ * Returns a promise that resolves when all coordinates are satisfied.
2329
+ * Rejects if the timeout is reached or the signal is aborted.
2330
+ */
2331
+ waitFor(coordinates: ConsistencyCoordinate[], timeoutMs?: number, signal?: AbortSignal): Promise<void>;
2332
+ /**
2333
+ * Returns a serializable snapshot of the current state.
2334
+ */
2335
+ serialize(): Array<[ConsistencyKey, number]>;
2336
+ /**
2337
+ * Restores state from a serialized snapshot.
2338
+ */
2339
+ hydrate(entries: Array<[ConsistencyKey, number]>): void;
2340
+ }
2341
+ /**
2342
+ * Creates a consistency key from documentId, scope, and branch.
2343
+ */
2344
+ declare function makeConsistencyKey(documentId: string, scope: string, branch: string): ConsistencyKey;
2345
+ /**
2346
+ * Tracks operation indexes for documents and provides read-after-write consistency guarantees.
2347
+ * Maintains an in-memory map of the latest operation index for each (documentId, scope, branch) tuple.
2348
+ */
2349
+ declare class ConsistencyTracker implements IConsistencyTracker {
2350
+ private state;
2351
+ private waiters;
2352
+ update(coordinates: ConsistencyCoordinate[]): void;
2353
+ getLatest(key: ConsistencyKey): number | undefined;
2354
+ waitFor(coordinates: ConsistencyCoordinate[], timeoutMs?: number, signal?: AbortSignal): Promise<void>;
2355
+ serialize(): Array<[ConsistencyKey, number]>;
2356
+ hydrate(entries: Array<[ConsistencyKey, number]>): void;
2357
+ private deduplicateCoordinates;
2358
+ private areCoordinatesSatisfied;
2359
+ private checkWaiters;
2360
+ private removeWaiter;
2361
+ }
2362
+ //#endregion
2363
+ //#region src/storage/kysely/types.d.ts
2364
+ interface OperationTable {
2365
+ id: Generated<number>;
2366
+ jobId: string;
2367
+ opId: string;
2368
+ prevOpId: string;
2369
+ writeTimestampUtcMs: Generated<Date>;
2370
+ documentId: string;
2371
+ documentType: string;
2372
+ scope: string;
2373
+ branch: string;
2374
+ timestampUtcMs: Date;
2375
+ index: number;
2376
+ action: unknown;
2377
+ skip: number;
2378
+ error?: string | null;
2379
+ hash: string;
2380
+ }
2381
+ interface KeyframeTable {
2382
+ id: Generated<number>;
2383
+ documentId: string;
2384
+ documentType: string;
2385
+ scope: string;
2386
+ branch: string;
2387
+ revision: number;
2388
+ document: unknown;
2389
+ createdAt: Generated<Date>;
2390
+ }
2391
+ interface DocumentCollectionTable {
2392
+ documentId: string;
2393
+ collectionId: string;
2394
+ joinedOrdinal: bigint;
2395
+ leftOrdinal: bigint | null;
2396
+ }
2397
+ interface OperationIndexOperationTable {
2398
+ ordinal: Generated<number>;
2399
+ opId: string;
2400
+ documentId: string;
2401
+ documentType: string;
2402
+ scope: string;
2403
+ branch: string;
2404
+ timestampUtcMs: string;
2405
+ writeTimestampUtcMs: Generated<Date>;
2406
+ index: number;
2407
+ skip: number;
2408
+ hash: string;
2409
+ action: unknown;
2410
+ sourceRemote: Generated<string>;
2411
+ }
2412
+ interface SyncRemoteTable {
2413
+ name: string;
2414
+ collection_id: string;
2415
+ channel_type: string;
2416
+ channel_id: string;
2417
+ remote_name: string;
2418
+ channel_parameters: unknown;
2419
+ filter_document_ids: unknown;
2420
+ filter_scopes: unknown;
2421
+ filter_branch: string;
2422
+ push_state: string;
2423
+ push_last_success_utc_ms: string | null;
2424
+ push_last_failure_utc_ms: string | null;
2425
+ push_failure_count: number;
2426
+ pull_state: string;
2427
+ pull_last_success_utc_ms: string | null;
2428
+ pull_last_failure_utc_ms: string | null;
2429
+ pull_failure_count: number;
2430
+ created_at: Generated<Date>;
2431
+ updated_at: Generated<Date>;
2432
+ }
2433
+ interface SyncCursorTable {
2434
+ remote_name: string;
2435
+ cursor_type: string;
2436
+ cursor_ordinal: bigint;
2437
+ last_synced_at_utc_ms: string | null;
2438
+ updated_at: Generated<Date>;
2439
+ }
2440
+ /**
2441
+ * Kysely table definition for the `sync_dead_letters` table.
2442
+ */
2443
+ interface SyncDeadLetterTable {
2444
+ ordinal: Generated<number>;
2445
+ id: string;
2446
+ job_id: string;
2447
+ job_dependencies: unknown;
2448
+ remote_name: string;
2449
+ document_id: string;
2450
+ scopes: unknown;
2451
+ branch: string;
2452
+ operations: unknown;
2453
+ error_source: string;
2454
+ error_message: string;
2455
+ created_at: Generated<Date>;
2456
+ }
2457
+ interface Database$1 {
2458
+ Operation: OperationTable;
2459
+ Keyframe: KeyframeTable;
2460
+ document_collections: DocumentCollectionTable;
2461
+ operation_index_operations: OperationIndexOperationTable;
2462
+ sync_remotes: SyncRemoteTable;
2463
+ sync_cursors: SyncCursorTable;
2464
+ sync_dead_letters: SyncDeadLetterTable;
2465
+ }
2466
+ interface DocumentTable {
2467
+ id: string;
2468
+ createdAt: Generated<Date>;
2469
+ updatedAt: Generated<Date>;
2470
+ }
2471
+ interface DocumentRelationshipTable {
2472
+ id: Generated<string>;
2473
+ sourceId: string;
2474
+ targetId: string;
2475
+ relationshipType: string;
2476
+ metadata: unknown;
2477
+ createdAt: Generated<Date>;
2478
+ updatedAt: Generated<Date>;
2479
+ }
2480
+ interface IndexerStateTable {
2481
+ id: Generated<number>;
2482
+ lastOperationId: number;
2483
+ lastOperationTimestamp: Generated<Date>;
2484
+ }
2485
+ interface DocumentIndexerDatabase {
2486
+ Document: DocumentTable;
2487
+ DocumentRelationship: DocumentRelationshipTable;
2488
+ IndexerState: IndexerStateTable;
2489
+ }
2490
+ //#endregion
2491
+ //#region src/sync/errors.d.ts
2492
+ declare class PollingChannelError extends Error {
2493
+ constructor(message: string);
2494
+ }
2495
+ declare class ChannelError extends Error {
2496
+ source: ChannelErrorSource;
2497
+ error: Error;
2498
+ constructor(source: ChannelErrorSource, error: Error);
2499
+ }
2500
+ //#endregion
2501
+ //#region src/sync/sync-operation.d.ts
2502
+ type SyncOperationStatusCallback = (syncOp: SyncOperation, prev: SyncOperationStatus, next: SyncOperationStatus) => void;
2503
+ declare class SyncOperationAggregateError extends Error {
2504
+ errors: Error[];
2505
+ constructor(errors: Error[]);
2506
+ }
2507
+ declare class SyncOperation {
2508
+ readonly id: string;
2509
+ readonly jobId: string;
2510
+ jobDependencies: string[];
2511
+ readonly remoteName: string;
2512
+ readonly documentId: string;
2513
+ readonly scopes: string[];
2514
+ readonly branch: string;
2515
+ readonly operations: OperationWithContext$1[];
2516
+ status: SyncOperationStatus;
2517
+ error?: ChannelError;
2518
+ deliveredCount: number;
2519
+ emittedCount: number;
2520
+ callbacks: SyncOperationStatusCallback[];
2521
+ constructor(id: string, jobId: string, jobDependencies: string[], remoteName: string, documentId: string, scopes: string[], branch: string, operations: OperationWithContext$1[]);
2522
+ on(callback: SyncOperationStatusCallback): void;
2523
+ started(): void;
2524
+ transported(): void;
2525
+ executed(): void;
2526
+ failed(error: ChannelError): void;
2527
+ transition(next: SyncOperationStatus): void;
2528
+ }
2529
+ //#endregion
2530
+ //#region src/sync/mailbox.d.ts
2531
+ type MailboxCallback = (items: SyncOperation[]) => void;
2532
+ /**
2533
+ * The Mailbox interface is not intended to use any persistence. Instead, the
2534
+ * IChannel implementation is responsible for persisting cursors or other data.
2535
+ *
2536
+ * This means that ackOrdinal and latestOrdinal are in memory only.
2537
+ */
2538
+ interface IMailbox {
2539
+ get items(): ReadonlyArray<SyncOperation>;
2540
+ /**
2541
+ * The latest ordinal that has been acknowledged. Because acknowledged items
2542
+ * are removed from the mailbox, this is the last ordinal that has been removed.
2543
+ */
2544
+ get ackOrdinal(): number;
2545
+ /**
2546
+ * The latest ordinal of the items that are or have been added to the mailbox.
2547
+ * This may be greater than the ack ordinal if items have been added but not
2548
+ * yet acknowledged.
2549
+ */
2550
+ get latestOrdinal(): number;
2551
+ init(ackOrdinal: number): void;
2552
+ advanceOrdinal(ordinal: number): void;
2553
+ get(id: string): SyncOperation | undefined;
2554
+ add(...items: SyncOperation[]): void;
2555
+ remove(...items: SyncOperation[]): void;
2556
+ onAdded(callback: MailboxCallback): void;
2557
+ onRemoved(callback: MailboxCallback): void;
2558
+ pause(): void;
2559
+ resume(): void;
2560
+ flush(): void;
2561
+ isPaused(): boolean;
2562
+ }
2563
+ declare class Mailbox implements IMailbox {
2564
+ private itemsMap;
2565
+ private addedCallbacks;
2566
+ private removedCallbacks;
2567
+ private paused;
2568
+ private addedBuffer;
2569
+ private removedBuffer;
2570
+ private _ack;
2571
+ private _latestOrdinal;
2572
+ init(ackOrdinal: number): void;
2573
+ advanceOrdinal(ordinal: number): void;
2574
+ get items(): ReadonlyArray<SyncOperation>;
2575
+ get ackOrdinal(): number;
2576
+ get latestOrdinal(): number;
2577
+ get(id: string): SyncOperation | undefined;
2578
+ add(...items: SyncOperation[]): void;
2579
+ remove(...items: SyncOperation[]): void;
2580
+ onAdded(callback: MailboxCallback): void;
2581
+ onRemoved(callback: MailboxCallback): void;
2582
+ pause(): void;
2583
+ resume(): void;
2584
+ flush(): void;
2585
+ isPaused(): boolean;
2586
+ }
2587
+ //#endregion
2588
+ //#region src/sync/sync-status-tracker.d.ts
2589
+ declare enum SyncStatus {
2590
+ Synced = "SYNCED",
2591
+ Outgoing = "OUTGOING",
2592
+ Incoming = "INCOMING",
2593
+ OutgoingAndIncoming = "OUTGOING_AND_INCOMING",
2594
+ Error = "ERROR"
2595
+ }
2596
+ type SyncStatusChangeCallback = (documentId: string, status: SyncStatus) => void;
2597
+ interface ISyncStatusTracker {
2598
+ getStatus(documentId: string): SyncStatus | undefined;
2599
+ onChange(callback: SyncStatusChangeCallback): () => void;
2600
+ trackRemote(remoteName: string, channel: IChannel): void;
2601
+ untrackRemote(remoteName: string): void;
2602
+ clear(): void;
2603
+ }
2604
+ declare class SyncStatusTracker implements ISyncStatusTracker {
2605
+ private readonly remotes;
2606
+ private readonly seen;
2607
+ private readonly callbacks;
2608
+ getStatus(documentId: string): SyncStatus | undefined;
2609
+ onChange(callback: SyncStatusChangeCallback): () => void;
2610
+ trackRemote(remoteName: string, channel: IChannel): void;
2611
+ untrackRemote(remoteName: string): void;
2612
+ clear(): void;
2613
+ private handleAdded;
2614
+ private handleRemoved;
2615
+ private getOrCreateCounts;
2616
+ private notifyChange;
2617
+ }
2618
+ //#endregion
2619
+ //#region src/sync/interfaces.d.ts
2620
+ /**
2621
+ * Represents a bidirectional synchronization channel between two reactor instances.
2622
+ *
2623
+ * A channel manages three mailboxes:
2624
+ * - inbox: Sync operations received from the remote that need to be applied locally
2625
+ * - outbox: Sync operations to be sent to the remote
2626
+ * - deadLetter: Sync operations that failed and cannot be retried
2627
+ */
2628
+ type ConnectionStateChangeCallback = (snapshot: ConnectionStateSnapshot) => void;
2629
+ interface IChannel {
2630
+ /**
2631
+ * Mailbox containing sync operations received from the remote that need to be applied locally.
2632
+ * Consumers should register callbacks via onAdded to process incoming sync operations.
2633
+ */
2634
+ inbox: IMailbox;
2635
+ /**
2636
+ * Mailbox containing sync operations that need to be sent to the remote.
2637
+ * The channel is responsible for transporting these sync operations and handling ACKs.
2638
+ */
2639
+ outbox: IMailbox;
2640
+ /**
2641
+ * Mailbox containing sync operations that failed and cannot be retried.
2642
+ * These sync operations require manual intervention or should be logged for debugging.
2643
+ */
2644
+ deadLetter: IMailbox;
2645
+ /**
2646
+ * Initializes the channel asynchronously.
2647
+ * For remote channels, this typically involves registering the channel on the remote server.
2648
+ * Must be called after construction before the channel is used.
2649
+ */
2650
+ init(): Promise<void>;
2651
+ /**
2652
+ * Shuts down the channel and prevents further operations.
2653
+ */
2654
+ shutdown(): Promise<void>;
2655
+ /**
2656
+ * Returns the current connection state snapshot.
2657
+ */
2658
+ getConnectionState(): ConnectionStateSnapshot;
2659
+ /**
2660
+ * Registers a callback that fires when the connection state changes.
2661
+ * Returns an unsubscribe function.
2662
+ */
2663
+ onConnectionStateChange(callback: ConnectionStateChangeCallback): () => void;
2664
+ /**
2665
+ * Fires a single pull cycle on demand. For Manual poll-behavior remotes this is the
2666
+ * mechanism for syncing without enabling background polling. Implementations that do
2667
+ * not poll (e.g. push-only response channels) should treat this as a no-op.
2668
+ */
2669
+ triggerPull(): void;
2670
+ }
2671
+ /**
2672
+ * Factory for creating channel instances.
2673
+ *
2674
+ * Different channel implementations (InternalChannel, GqlChannel, etc.) will have
2675
+ * their own factories that implement this interface.
2676
+ */
2677
+ interface IChannelFactory {
2678
+ /**
2679
+ * Creates a new channel instance with the given configuration.
2680
+ *
2681
+ * @param remoteId - Unique identifier for the remote
2682
+ * @param remoteName - Name of the remote
2683
+ * @param config - Channel configuration including type and parameters
2684
+ * @param cursorStorage - Storage for persisting synchronization cursors
2685
+ * @param collectionId - Collection ID to synchronize
2686
+ * @param filter - Filter to apply to operations
2687
+ * @param operationIndex - Operation index for querying timestamps
2688
+ * @param options - Remote-level options (e.g. pollBehavior). May be omitted; implementations should default sensibly.
2689
+ * @returns A new channel instance
2690
+ */
2691
+ instance(remoteId: string, remoteName: string, config: ChannelConfig, cursorStorage: ISyncCursorStorage, collectionId: string, filter: RemoteFilter, operationIndex: IOperationIndex, options?: RemoteOptions): IChannel;
2692
+ }
2693
+ /**
2694
+ * Represents a configured remote with an active channel.
2695
+ *
2696
+ * A remote defines what to synchronize (collectionId, filter) and how to synchronize it (channel).
2697
+ * The remote name is used as a unique identifier across the system.
2698
+ */
2699
+ type Remote = {
2700
+ /**
2701
+ * Unique identifier for this remote.
2702
+ */
2703
+ id: string;
2704
+ /**
2705
+ * Unique name for this remote.
2706
+ */
2707
+ name: string;
2708
+ /**
2709
+ * Collection ID to synchronize.
2710
+ * Typically created via driveCollectionId(branch, documentId) for drive-level sync.
2711
+ */
2712
+ collectionId: string;
2713
+ /**
2714
+ * Filter to apply to operations.
2715
+ * Can filter by documentId, scope, and branch.
2716
+ */
2717
+ filter: RemoteFilter;
2718
+ /**
2719
+ * Additional configuration options for the remote.
2720
+ */
2721
+ options: RemoteOptions;
2722
+ /**
2723
+ * Active channel for bidirectional communication with the remote.
2724
+ */
2725
+ channel: IChannel;
2726
+ };
2727
+ /**
2728
+ * Orchestrates all synchronization activity for a reactor instance.
2729
+ */
2730
+ interface ISyncManager {
2731
+ /**
2732
+ * Starts the synchronization manager.
2733
+ *
2734
+ * This recreates all remotes from storage and prepares channels for synchronization.
2735
+ * Each remote's channel will begin processing its inbox/outbox mailboxes.
2736
+ *
2737
+ * @returns Promise that resolves when the manager is started
2738
+ */
2739
+ startup(): Promise<void>;
2740
+ /**
2741
+ * Shuts down the synchronization manager.
2742
+ *
2743
+ * This stops all channels, flushes pending operations, and releases resources.
2744
+ * The shutdown status indicates whether the system was cleanly shut down.
2745
+ *
2746
+ * @returns Status object with shutdown information
2747
+ */
2748
+ shutdown(): ShutdownStatus;
2749
+ /**
2750
+ * Gets a remote by name.
2751
+ *
2752
+ * @param name - The name of the remote
2753
+ * @returns The remote
2754
+ * @throws Error if the remote does not exist
2755
+ */
2756
+ getByName(name: string): Remote;
2757
+ /**
2758
+ * Gets a remote by ID.
2759
+ *
2760
+ * @param id - The ID of the remote
2761
+ * @returns The remote
2762
+ * @throws Error if the remote does not exist
2763
+ */
2764
+ getById(id: string): Remote;
2765
+ /**
2766
+ * Adds a new remote and starts its channel.
2767
+ *
2768
+ * The remote configuration is persisted to storage and a channel is created
2769
+ * using the appropriate factory. The channel begins processing immediately.
2770
+ *
2771
+ * @param name - Unique name for the remote
2772
+ * @param collectionId - Collection ID to synchronize
2773
+ * @param channelConfig - Configuration for the channel type and parameters
2774
+ * @param filter - Optional filter for operations (defaults to no filtering)
2775
+ * @param options - Optional remote configuration options
2776
+ * @param id - Optional ID for the remote (generated if not provided)
2777
+ * @returns Promise that resolves with the created remote
2778
+ * @throws Error if a remote with this name already exists
2779
+ */
2780
+ add(name: string, collectionId: string, channelConfig: ChannelConfig, filter?: RemoteFilter, options?: RemoteOptions, id?: string): Promise<Remote>;
2781
+ /**
2782
+ * Triggers a one-shot pull for the named remote. Useful for Manual poll-behavior
2783
+ * remotes, where the channel is registered but does not poll on a schedule.
2784
+ *
2785
+ * @param name - The name of the remote
2786
+ * @throws Error if the remote does not exist
2787
+ */
2788
+ triggerPull(name: string): void;
2789
+ /**
2790
+ * Removes a remote and stops its channel.
2791
+ *
2792
+ * The remote configuration is removed from storage and the channel is shut down.
2793
+ * Any pending sync operations in the channel's mailboxes will be processed before shutdown.
2794
+ *
2795
+ * @param name - The name of the remote to remove
2796
+ * @returns Promise that resolves when the remote is removed
2797
+ * @throws Error if the remote does not exist
2798
+ */
2799
+ remove(name: string): Promise<void>;
2800
+ /**
2801
+ * Lists all configured remotes.
2802
+ *
2803
+ * @returns Array of all remotes
2804
+ */
2805
+ list(): Remote[];
2806
+ /**
2807
+ * Waits for sync operations for a job to complete.
2808
+ * Resolves when SYNC_SUCCEEDED is emitted.
2809
+ * Rejects when SYNC_FAILED is emitted.
2810
+ *
2811
+ * @param jobId - The job id to wait for
2812
+ * @param signal - Optional abort signal
2813
+ * @returns The sync result
2814
+ */
2815
+ waitForSync(jobId: string, signal?: AbortSignal): Promise<SyncResult>;
2816
+ /**
2817
+ * Gets the current sync status for a document.
2818
+ *
2819
+ * @param documentId - The document ID to check
2820
+ * @returns The sync status, or undefined if the document has never been tracked
2821
+ */
2822
+ getSyncStatus(documentId: string): SyncStatus | undefined;
2823
+ /**
2824
+ * Registers a callback that fires when a document's sync status changes.
2825
+ *
2826
+ * @param callback - Called with (documentId, newStatus) on each transition
2827
+ * @returns Unsubscribe function
2828
+ */
2829
+ onSyncStatusChange(callback: SyncStatusChangeCallback): () => void;
2830
+ }
2831
+ //#endregion
2832
+ //#region src/core/types.d.ts
2833
+ /**
2834
+ * A single mutation job within a batch request.
2835
+ */
2836
+ type ExecutionJobPlan = {
2837
+ key: string;
2838
+ documentId: string;
2839
+ scope: string;
2840
+ branch: string;
2841
+ actions: Action[];
2842
+ dependsOn: string[];
2843
+ };
2844
+ /**
2845
+ * Request for batch mutation operation.
2846
+ */
2847
+ type BatchExecutionRequest = {
2848
+ jobs: ExecutionJobPlan[];
2849
+ };
2850
+ /**
2851
+ * Result from batch mutation operation.
2852
+ */
2853
+ type BatchExecutionResult = {
2854
+ jobs: Record<string, JobInfo>;
2855
+ };
2856
+ /**
2857
+ * A single load job within a batch request.
2858
+ *
2859
+ * `dependsOn` lists intra-batch plan keys (resolved to UUIDs by `loadBatch`).
2860
+ * `externalDeps` lists pre-resolved job UUIDs from prior batches; these are
2861
+ * appended to the queue hint without going through plan-key resolution.
2862
+ */
2863
+ type LoadJobPlan = {
2864
+ key: string;
2865
+ documentId: string;
2866
+ scope: string;
2867
+ branch: string;
2868
+ operations: Operation[];
2869
+ dependsOn: string[];
2870
+ externalDeps: string[];
2871
+ };
2872
+ /**
2873
+ * Request for batch load operation.
2874
+ */
2875
+ type BatchLoadRequest = {
2876
+ jobs: LoadJobPlan[];
2877
+ };
2878
+ /**
2879
+ * Result from batch load operation.
2880
+ */
2881
+ type BatchLoadResult = {
2882
+ jobs: Record<string, JobInfo>;
2883
+ };
2884
+ /**
2885
+ * The main Reactor interface that serves as a facade for document operations.
2886
+ * This interface provides a unified API for document management, including
2887
+ * creation, retrieval, mutation, and deletion operations.
2888
+ */
2889
+ interface IReactor {
2890
+ /**
2891
+ * Signals that the reactor should shutdown.
2892
+ */
2893
+ kill(): ShutdownStatus;
2894
+ /**
2895
+ * Retrieves a list of document model modules.
2896
+ *
2897
+ * @param namespace - Optional namespace like "powerhouse" or "sky", defaults to ""
2898
+ * @param paging - Optional options for paging data in large queries.
2899
+ * @param signal - Optional abort signal to cancel the request
2900
+ * @returns List of document model modules
2901
+ */
2902
+ getDocumentModels(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
2903
+ /**
2904
+ * Retrieves a specific PHDocument by id
2905
+ *
2906
+ * @param id - Required, this is the document id
2907
+ * @param view - Optional filter containing branch and scopes information
2908
+ * @param consistencyToken - Optional token for read-after-write consistency
2909
+ * @param signal - Optional abort signal to cancel the request
2910
+ * @returns The up-to-date PHDocument
2911
+ */
2912
+ get<TDocument extends PHDocument>(id: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
2913
+ /**
2914
+ * Retrieves a specific PHDocument by slug
2915
+ *
2916
+ * @param slug - Required, this is the document slug
2917
+ * @param view - Optional filter containing branch and scopes information
2918
+ * @param consistencyToken - Optional token for read-after-write consistency
2919
+ * @param signal - Optional abort signal to cancel the request
2920
+ * @returns The up-to-date PHDocument with scopes and list of child document ids
2921
+ */
2922
+ getBySlug<TDocument extends PHDocument>(slug: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
2923
+ /**
2924
+ * Retrieves a specific PHDocument by identifier (either id or slug).
2925
+ * Throws an error if the identifier matches both an id and a slug that refer to different documents.
2926
+ *
2927
+ * @param identifier - Required, this is the document id or slug
2928
+ * @param view - Optional filter containing branch and scopes information
2929
+ * @param consistencyToken - Optional token for read-after-write consistency
2930
+ * @param signal - Optional abort signal to cancel the request
2931
+ * @returns The up-to-date PHDocument with scopes and list of child document ids
2932
+ * @throws {Error} If identifier matches both an ID and slug referring to different documents
2933
+ */
2934
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
2935
+ /**
2936
+ * Retrieves outgoing relationships of a given type from a source document.
2937
+ *
2938
+ * @param sourceId - The source document id
2939
+ * @param relationshipType - The relationship type to filter by
2940
+ * @param consistencyToken - Optional token for read-after-write consistency
2941
+ * @param signal - Optional abort signal to cancel the request
2942
+ * @returns The list of target document ids
2943
+ */
2944
+ getOutgoingRelationships(sourceId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
2945
+ /**
2946
+ * Retrieves incoming relationships of a given type to a target document.
2947
+ *
2948
+ * @param targetId - The target document id
2949
+ * @param relationshipType - The relationship type to filter by
2950
+ * @param consistencyToken - Optional token for read-after-write consistency
2951
+ * @param signal - Optional abort signal to cancel the request
2952
+ * @returns The list of source document ids
2953
+ */
2954
+ getIncomingRelationships(targetId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
2955
+ /**
2956
+ * Retrieves the operations for a document
2957
+ *
2958
+ * @param documentId - The document id
2959
+ * @param view - Optional filter containing branch and scopes information
2960
+ * @param filter - Optional filter for actionTypes, timestamps, and revision
2961
+ * @param paging - Optional pagination options
2962
+ * @param consistencyToken - Optional token for read-after-write consistency
2963
+ * @param signal - Optional abort signal to cancel the request
2964
+ * @returns The list of operations
2965
+ */
2966
+ getOperations(documentId: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<Record<string, PagedResults<Operation>>>;
2967
+ /**
2968
+ * Filters documents by criteria and returns a list of them
2969
+ *
2970
+ * @param search - Search filter options (type, parentId, identifiers)
2971
+ * @param view - Optional filter containing branch and scopes information
2972
+ * @param paging - Optional pagination options
2973
+ * @param consistencyToken - Optional token for read-after-write consistency
2974
+ * @param signal - Optional abort signal to cancel the request
2975
+ * @returns List of documents matching criteria and pagination cursor
2976
+ */
2977
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
2978
+ /**
2979
+ * Creates a document
2980
+ *
2981
+ * @param document - Document with optional id, slug, parent, model type, and initial state
2982
+ * @param signer - Optional signer to sign the actions
2983
+ * @param signal - Optional abort signal to cancel the request
2984
+ * @param meta - Optional metadata that flows through the job lifecycle
2985
+ * @returns The job status
2986
+ */
2987
+ create(document: PHDocument, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
2988
+ /**
2989
+ * Deletes a document
2990
+ *
2991
+ * @param id - Document id
2992
+ * @param signer - Optional signer to sign the actions
2993
+ * @param signal - Optional abort signal to cancel the request
2994
+ * @param meta - Optional metadata that flows through the job lifecycle
2995
+ * @returns The job id and status
2996
+ */
2997
+ deleteDocument(id: string, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
2998
+ /**
2999
+ * Applies a list of actions to a document.
3000
+ *
3001
+ * @param docId - Document id
3002
+ * @param branch - Branch to apply actions to
3003
+ * @param actions - List of actions to apply
3004
+ * @param signal - Optional abort signal to cancel the request
3005
+ * @param meta - Optional metadata that flows through the job lifecycle
3006
+ * @returns The job id and status
3007
+ */
3008
+ execute(docId: string, branch: string, actions: Action[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3009
+ /**
3010
+ * Loads existing operations generated elsewhere into this reactor.
3011
+ *
3012
+ * @param docId - Document id
3013
+ * @param branch - Branch to load operations to
3014
+ * @param operations - List of operations to load
3015
+ * @param signal - Optional abort signal to cancel the request
3016
+ * @param meta - Optional metadata that flows through the job lifecycle
3017
+ * @returns The job id and status
3018
+ */
3019
+ load(docId: string, branch: string, operations: Operation[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3020
+ /**
3021
+ * Applies multiple mutations across documents with dependency management.
3022
+ *
3023
+ * @param request - Batch mutation request containing jobs with dependencies
3024
+ * @param signal - Optional abort signal to cancel the request
3025
+ * @param meta - Optional metadata that flows through the job lifecycle
3026
+ * @returns Map of job keys to job information
3027
+ */
3028
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchExecutionResult>;
3029
+ /**
3030
+ * Loads multiple batches of pre-existing operations across documents with dependency management.
3031
+ *
3032
+ * @param request - Batch load request containing jobs with dependencies
3033
+ * @param signal - Optional abort signal to cancel the request
3034
+ * @param meta - Optional metadata that flows through the job lifecycle
3035
+ * @returns Map of job keys to job information
3036
+ */
3037
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchLoadResult>;
3038
+ /**
3039
+ * Adds a relationship between two documents.
3040
+ *
3041
+ * @param sourceId - Source document id
3042
+ * @param targetId - Target document id
3043
+ * @param relationshipType - Relationship type identifier
3044
+ * @param branch - Branch to add the relationship to, defaults to "main"
3045
+ * @param signer - Optional signer to sign the actions
3046
+ * @param signal - Optional abort signal to cancel the request
3047
+ * @returns The job id and status
3048
+ */
3049
+ addRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
3050
+ /**
3051
+ * Removes a relationship between two documents.
3052
+ *
3053
+ * @param sourceId - Source document id
3054
+ * @param targetId - Target document id
3055
+ * @param relationshipType - Relationship type identifier
3056
+ * @param branch - Branch to remove the relationship from, defaults to "main"
3057
+ * @param signer - Optional signer to sign the actions
3058
+ * @param signal - Optional abort signal to cancel the request
3059
+ * @returns The job id and status
3060
+ */
3061
+ removeRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
3062
+ /**
3063
+ * Retrieves the status of a job
3064
+ *
3065
+ * @param jobId - The job id
3066
+ * @returns The job status
3067
+ */
3068
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
3069
+ }
3070
+ /**
3071
+ * Feature flags for reactor configuration
3072
+ */
3073
+ type ReactorFeatures = {
3074
+ [key: string]: boolean;
3075
+ };
3076
+ /**
3077
+ * Combined database type that includes all schemas
3078
+ */
3079
+ type Database = Database$1 & DocumentViewDatabase & DocumentIndexerDatabase;
3080
+ /**
3081
+ * Container for all sync manager dependencies created during the build process.
3082
+ */
3083
+ interface SyncModule {
3084
+ remoteStorage: ISyncRemoteStorage;
3085
+ cursorStorage: ISyncCursorStorage;
3086
+ deadLetterStorage: ISyncDeadLetterStorage;
3087
+ channelFactory: IChannelFactory;
3088
+ syncManager: ISyncManager;
3089
+ }
3090
+ /**
3091
+ * Container for all reactor dependencies created during the build process.
3092
+ * Provides direct access to internal components for advanced use cases,
3093
+ * testing, or integration scenarios.
3094
+ */
3095
+ interface ReactorModule {
3096
+ eventBus: IEventBus;
3097
+ documentModelRegistry: IDocumentModelRegistry;
3098
+ queue: IQueue;
3099
+ jobTracker: IJobTracker;
3100
+ executorManager: IJobExecutorManager;
3101
+ database: Kysely<Database>;
3102
+ operationStore: IOperationStore;
3103
+ keyframeStore: IKeyframeStore;
3104
+ writeCache: IWriteCache;
3105
+ operationIndex: IOperationIndex;
3106
+ documentView: IDocumentView;
3107
+ documentViewConsistencyTracker: IConsistencyTracker;
3108
+ documentIndexer: IDocumentIndexer;
3109
+ documentIndexerConsistencyTracker: IConsistencyTracker;
3110
+ readModelCoordinator: IReadModelCoordinator;
3111
+ subscriptionManager: IReactorSubscriptionManager;
3112
+ processorManager: IProcessorManager$1;
3113
+ processorManagerConsistencyTracker: IConsistencyTracker;
3114
+ syncModule: SyncModule | undefined;
3115
+ reactor: IReactor;
3116
+ }
3117
+ /**
3118
+ * Container for all reactor client dependencies created during the build process.
3119
+ * Provides direct access to internal components for advanced use cases,
3120
+ * testing, or integration scenarios.
3121
+ */
3122
+ interface ReactorClientModule {
3123
+ client: ReactorClient;
3124
+ reactor: IReactor;
3125
+ eventBus: IEventBus;
3126
+ documentIndexer: IDocumentIndexer;
3127
+ documentView: IDocumentView;
3128
+ signer: ISigner;
3129
+ subscriptionManager: IReactorSubscriptionManager;
3130
+ jobAwaiter: IJobAwaiter;
3131
+ reactorModule: ReactorModule | undefined;
3132
+ }
3133
+ //#endregion
3134
+ //#region src/client/drive-client.d.ts
3135
+ /**
3136
+ * Implementation of {@link IDriveClient}.
3137
+ *
3138
+ * Holds a back-reference to its parent {@link IReactorClient} for read and
3139
+ * single-document write primitives, plus direct access to {@link IReactor}
3140
+ * for batch execution. The back-reference is captured but never invoked
3141
+ * during construction, so the partial-`this` hazard does not apply.
3142
+ */
3143
+ declare class DriveClient implements IDriveClient {
3144
+ private readonly client;
3145
+ private readonly logger;
3146
+ private readonly reactor;
3147
+ private readonly signer;
3148
+ constructor(client: IReactorClient, logger: ILogger, reactor: IReactor, signer: ISigner);
3149
+ create(input: DriveInput, signal?: AbortSignal): Promise<DocumentDriveDocument>;
3150
+ addFile<TDocument extends PHDocument = PHDocument>(driveIdentifier: string, document: PHDocument, parentFolder?: string, signal?: AbortSignal): Promise<TDocument>;
3151
+ addFolder(driveIdentifier: string, name: string, parentFolder?: string, signal?: AbortSignal): Promise<FolderNode>;
3152
+ removeNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<void>;
3153
+ renameNode(driveIdentifier: string, nodeId: string, name: string, signal?: AbortSignal): Promise<Node>;
3154
+ setPreferredEditorOnNode(nodeId: string, preferredEditor: string | null, signal?: AbortSignal): Promise<PHDocument>;
3155
+ moveNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
3156
+ copyNode(driveIdentifier: string, srcNodeId: string, targetParentFolderId: string | undefined, signal?: AbortSignal): Promise<DocumentDriveDocument>;
3157
+ getNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<Node>;
3158
+ listNodes(driveIdentifier: string, parentFolder?: string | null, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Node>>;
3159
+ private removeFileNode;
3160
+ }
3161
+ //#endregion
3162
+ //#region src/cache/write-cache-types.d.ts
3163
+ /**
3164
+ * Configuration options for the write cache
3165
+ */
3166
+ type WriteCacheConfig = {
3167
+ /** Maximum number of document streams to cache (LRU eviction). Default: 1000 */maxDocuments: number; /** Number of snapshots to keep in each document's ring buffer. Default: 10 */
3168
+ ringBufferSize: number; /** Persist a keyframe snapshot every N revisions. Default: 10 */
3169
+ keyframeInterval: number;
3170
+ };
3171
+ /**
3172
+ * Unique identifier for a document stream
3173
+ */
3174
+ type DocumentStreamKey = {
3175
+ /** Document identifier */documentId: string; /** Operation scope */
3176
+ scope: string; /** Branch name */
3177
+ branch: string;
3178
+ };
3179
+ /**
3180
+ * A cached document snapshot at a specific revision
3181
+ */
3182
+ type CachedSnapshot = {
3183
+ /** The revision number of this snapshot */revision: number; /** The document state at this revision */
3184
+ document: PHDocument;
3185
+ };
3186
+ /**
3187
+ * Serialized keyframe snapshot for K/V store persistence
3188
+ */
3189
+ type KeyframeSnapshot = {
3190
+ /** The revision number of this keyframe */revision: number; /** Serialized document state */
3191
+ document: string;
3192
+ };
3193
+ //#endregion
3194
+ //#region src/signer/types.d.ts
3195
+ /**
3196
+ * Configuration for signing and verification.
3197
+ */
3198
+ type SignerConfig = {
3199
+ /**
3200
+ * The signer used to sign actions before submission.
3201
+ */
3202
+ signer: ISigner;
3203
+ /**
3204
+ * Optional handler for verifying signatures on incoming operations.
3205
+ * If not provided, signature verification will be skipped.
3206
+ */
3207
+ verifier?: SignatureVerificationHandler;
3208
+ };
3209
+ //#endregion
3210
+ //#region src/storage/migrations/types.d.ts
3211
+ type MigrationStrategy = "auto" | "manual" | "none";
3212
+ interface MigrationResult {
3213
+ success: boolean;
3214
+ migrationsExecuted: string[];
3215
+ error?: Error;
3216
+ }
3217
+ //#endregion
3218
+ //#region src/sync/sync-builder.d.ts
3219
+ declare class SyncBuilder {
3220
+ private channelFactory?;
3221
+ private remoteStorage?;
3222
+ private cursorStorage?;
3223
+ private deadLetterStorage?;
3224
+ private config;
3225
+ withChannelFactory(factory: IChannelFactory): this;
3226
+ withRemoteStorage(storage: ISyncRemoteStorage): this;
3227
+ withCursorStorage(storage: ISyncCursorStorage): this;
3228
+ withDeadLetterStorage(storage: ISyncDeadLetterStorage): this;
3229
+ withMaxDeadLettersPerRemote(limit: number): this;
3230
+ withMaxInboxBatchSize(limit: number): this;
3231
+ build(reactor: IReactor, logger: ILogger, operationIndex: IOperationIndex, eventBus: IEventBus, db: Kysely<Database$1>, driveContainerTypes: ReadonlySet<string>): ISyncManager;
3232
+ buildModule(reactor: IReactor, logger: ILogger, operationIndex: IOperationIndex, eventBus: IEventBus, db: Kysely<Database$1>, driveContainerTypes: ReadonlySet<string>): SyncModule;
3233
+ }
3234
+ //#endregion
3235
+ //#region src/core/reactor-builder.d.ts
3236
+ /**
3237
+ * Dependencies provided to read-model factories registered via
3238
+ * `withReadModelFactory`. These are constructed inside `buildModule()`, which
3239
+ * is why factory-based registration is needed for read models that depend on
3240
+ * them (`BaseReadModel` subclasses, in particular).
3241
+ */
3242
+ interface ReadModelFactoryDeps {
3243
+ operationIndex: IOperationIndex;
3244
+ writeCache: IWriteCache;
3245
+ processorManagerConsistencyTracker: IConsistencyTracker;
3246
+ }
3247
+ /**
3248
+ * Factory that builds a pre-ready read model from internal reactor
3249
+ * dependencies once they are available. Awaited during `buildModule()`.
3250
+ */
3251
+ type ReadModelFactory = (deps: ReadModelFactoryDeps) => IReadModel | Promise<IReadModel>;
3252
+ declare class ReactorBuilder {
3253
+ private logger?;
3254
+ private documentModels;
3255
+ private upgradeManifests;
3256
+ private features;
3257
+ private readModels;
3258
+ private readModelFactories;
3259
+ private executorManager;
3260
+ private executorConfig;
3261
+ private writeCacheConfig?;
3262
+ private migrationStrategy;
3263
+ private syncBuilder?;
3264
+ private eventBus?;
3265
+ private readModelCoordinator?;
3266
+ private signatureVerifier?;
3267
+ private kyselyInstance?;
3268
+ private signalHandlersEnabled;
3269
+ private queueInstance?;
3270
+ private channelScheme?;
3271
+ private jwtHandler?;
3272
+ private documentModelLoader?;
3273
+ private shutdownHooks;
3274
+ private driveContainerTypes;
3275
+ withLogger(logger: ILogger): this;
3276
+ withDocumentModels(models: DocumentModelModule<any>[]): this;
3277
+ withUpgradeManifests(manifests: UpgradeManifest<readonly number[]>[]): this;
3278
+ withFeatures(features: ReactorFeatures): this;
3279
+ withReadModel(readModel: IReadModel): this;
3280
+ /**
3281
+ * Register a factory that builds a pre-ready read model after the reactor's
3282
+ * internal `operationIndex`, `writeCache`, and processor-manager consistency
3283
+ * tracker are constructed. Use this for read models (e.g. `BaseReadModel`
3284
+ * subclasses) that need those dependencies and therefore cannot be built
3285
+ * before calling `buildModule()`.
3286
+ */
3287
+ withReadModelFactory(factory: ReadModelFactory): this;
3288
+ withReadModelCoordinator(readModelCoordinator: IReadModelCoordinator): this;
3289
+ withExecutor(executor: IJobExecutorManager): this;
3290
+ withExecutorConfig(config: Partial<JobExecutorConfig>): this;
3291
+ withWriteCacheConfig(config: Partial<WriteCacheConfig>): this;
3292
+ withDriveContainerTypes(types: string[]): this;
3293
+ withMigrationStrategy(strategy: MigrationStrategy): this;
3294
+ withSync(syncBuilder: SyncBuilder): this;
3295
+ withEventBus(eventBus: IEventBus): this;
3296
+ withSignatureVerifier(verifier: SignatureVerificationHandler): this;
3297
+ withKysely(kysely: Kysely<Database>): this;
3298
+ withQueue(queue: IQueue): this;
3299
+ withChannelScheme(scheme: ChannelScheme): this;
3300
+ withJwtHandler(handler: JwtHandler): this;
3301
+ withDocumentModelLoader(loader: IDocumentModelLoader): this;
3302
+ withSignalHandlers(): this;
3303
+ /**
3304
+ * Register an async cleanup hook to run during graceful shutdown. Hooks fire
3305
+ * after `reactor.kill()` resolves and before `database.destroy()`, so callers
3306
+ * that depend on the reactor (e.g. an HTTP API layered on top) can drain
3307
+ * cleanly before the underlying kysely instance is torn down. Hook errors are
3308
+ * logged and otherwise ignored — one bad hook cannot strand the rest of the
3309
+ * shutdown chain.
3310
+ */
3311
+ withShutdownHook(hook: () => Promise<void>): this;
3312
+ build(): Promise<IReactor>;
3313
+ buildModule(): Promise<ReactorModule>;
3314
+ private attachSignalHandlers;
3315
+ }
3316
+ //#endregion
3317
+ //#region src/core/reactor-client-builder.d.ts
3318
+ /**
3319
+ * Builder class for constructing ReactorClient instances with proper configuration
3320
+ */
3321
+ declare class ReactorClientBuilder {
3322
+ private logger?;
3323
+ private reactorBuilder?;
3324
+ private reactor?;
3325
+ private eventBus?;
3326
+ private documentIndexer?;
3327
+ private documentView?;
3328
+ private signer?;
3329
+ private signatureVerifier?;
3330
+ private subscriptionManager?;
3331
+ private jobAwaiter?;
3332
+ private documentModelLoader?;
3333
+ /**
3334
+ * Sets the logger for the ReactorClient.
3335
+ * @param logger - The logger to use.
3336
+ * @returns The ReactorClientBuilder instance.
3337
+ */
3338
+ withLogger(logger: ILogger): this;
3339
+ /**
3340
+ * Either this or withReactor must be set.
3341
+ */
3342
+ withReactorBuilder(reactorBuilder: ReactorBuilder): this;
3343
+ /**
3344
+ * Either this or withReactorBuilder must be set.
3345
+ */
3346
+ withReactor(reactor: IReactor, eventBus: IEventBus, documentIndexer: IDocumentIndexer, documentView: IDocumentView): this;
3347
+ /**
3348
+ * Sets the signer configuration for signing and verifying actions.
3349
+ *
3350
+ * @param config - Either an ISigner for signing only, or a SignerConfig for both signing and verification
3351
+ */
3352
+ withSigner(config: ISigner | SignerConfig): this;
3353
+ withSubscriptionManager(subscriptionManager: IReactorSubscriptionManager): this;
3354
+ withJobAwaiter(jobAwaiter: IJobAwaiter): this;
3355
+ withDocumentModelLoader(loader: IDocumentModelLoader): this;
3356
+ build(): Promise<ReactorClient>;
3357
+ buildModule(): Promise<ReactorClientModule>;
3358
+ }
3359
+ //#endregion
3360
+ //#region src/core/drive-container-types.d.ts
3361
+ declare const DEFAULT_DRIVE_CONTAINER_TYPES: ReadonlySet<string>;
3362
+ //#endregion
3363
+ //#region src/core/reactor.d.ts
3364
+ /**
3365
+ * This class implements the IReactor interface and serves as the main entry point
3366
+ * for the new Reactor architecture.
3367
+ */
3368
+ declare class Reactor implements IReactor {
3369
+ private logger;
3370
+ private documentModelRegistry;
3371
+ private shutdownStatus;
3372
+ private setShutdown;
3373
+ private setCompleted;
3374
+ private queue;
3375
+ private jobTracker;
3376
+ private readModelCoordinator;
3377
+ private features;
3378
+ private documentView;
3379
+ private documentIndexer;
3380
+ private operationStore;
3381
+ private eventBus;
3382
+ private executorManager;
3383
+ constructor(logger: ILogger, documentModelRegistry: IDocumentModelRegistry, queue: IQueue, jobTracker: IJobTracker, readModelCoordinator: IReadModelCoordinator, features: ReactorFeatures, documentView: IDocumentView, documentIndexer: IDocumentIndexer, operationStore: IOperationStore, eventBus: IEventBus, executorManager: IJobExecutorManager);
3384
+ kill(): ShutdownStatus;
3385
+ getDocumentModels(namespace?: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentModelModule>>;
3386
+ get<TDocument extends PHDocument>(id: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
3387
+ getBySlug<TDocument extends PHDocument>(slug: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
3388
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
3389
+ getOutgoingRelationships(sourceId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
3390
+ getIncomingRelationships(targetId: string, relationshipType: string, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
3391
+ getOperations(documentId: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<Record<string, PagedResults<Operation>>>;
3392
+ find(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
3393
+ create(document: PHDocument, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3394
+ deleteDocument(id: string, signer?: ISigner, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3395
+ execute(docId: string, branch: string, actions: Action[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3396
+ load(docId: string, branch: string, operations: Operation[], signal?: AbortSignal, meta?: Record<string, unknown>): Promise<JobInfo>;
3397
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchExecutionResult>;
3398
+ loadBatch(request: BatchLoadRequest, signal?: AbortSignal, meta?: Record<string, unknown>): Promise<BatchLoadResult>;
3399
+ addRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
3400
+ removeRelationship(sourceId: string, targetId: string, relationshipType: string, branch?: string, signer?: ISigner, signal?: AbortSignal): Promise<JobInfo>;
3401
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
3402
+ private findByIds;
3403
+ private findBySlugs;
3404
+ private findByParentId;
3405
+ private findByType;
3406
+ private emitJobPending;
3407
+ }
3408
+ //#endregion
3409
+ //#region src/shared/drive-url.d.ts
3410
+ interface ParsedDriveUrl {
3411
+ url: string;
3412
+ driveId: string;
3413
+ graphqlEndpoint: string;
3414
+ }
3415
+ /**
3416
+ * Parse a drive URL to extract drive ID and construct GraphQL endpoint.
3417
+ * Preserves any subpath prefix so the result is correct when the reactor is
3418
+ * served behind a proxy at a non-root path.
3419
+ * e.g., "http://localhost:4001/d/abc123" -> { driveId: "abc123", graphqlEndpoint: "http://localhost:4001/graphql/r" }
3420
+ * e.g., "https://example.com/api/reactor/d/abc123" -> { ..., graphqlEndpoint: "https://example.com/api/reactor/graphql/r" }
3421
+ */
3422
+ declare function parseDriveUrl(url: string): ParsedDriveUrl;
3423
+ /**
3424
+ * Extract drive ID from a drive URL.
3425
+ */
3426
+ declare function driveIdFromUrl(url: string): string;
3427
+ //#endregion
3428
+ //#region src/shared/factories.d.ts
3429
+ /**
3430
+ * Factory method to create a ShutdownStatus that can be updated
3431
+ *
3432
+ * @param initialState - Initial shutdown state (default: false)
3433
+ * @returns A tuple of [ShutdownStatus, setShutdown function, setCompleted function]
3434
+ */
3435
+ declare function createMutableShutdownStatus(initialState?: boolean): [ShutdownStatus, (value: boolean) => void, (completed: Promise<void>) => void];
3436
+ //#endregion
3437
+ //#region src/shared/utils.d.ts
3438
+ type ParsedPaging = {
3439
+ offset: number;
3440
+ limit: number;
3441
+ };
3442
+ /**
3443
+ * Validates PagingOptions and returns a normalized offset and limit.
3444
+ * Throws if the cursor is not empty and not a non-negative integer, or if
3445
+ * limit is less than 1. When `paging` is undefined, returns offset 0 and
3446
+ * the caller-supplied `defaultLimit`.
3447
+ */
3448
+ declare function parsePagingOptions(paging: PagingOptions | undefined, defaultLimit: number): ParsedPaging;
3449
+ //#endregion
3450
+ //#region src/subs/default-error-handler.d.ts
3451
+ /**
3452
+ * Default error handler that re-throws subscription errors.
3453
+ * This ensures that errors are not silently swallowed.
3454
+ */
3455
+ declare class DefaultSubscriptionErrorHandler implements ISubscriptionErrorHandler {
3456
+ handleError(error: unknown, context: SubscriptionErrorContext): void;
3457
+ }
3458
+ //#endregion
3459
+ //#region src/subs/react-subscription-manager.d.ts
3460
+ type DocumentCreatedCallback = (result: PagedResults<string>) => void;
3461
+ type DocumentDeletedCallback = (documentIds: string[]) => void;
3462
+ type DocumentStateUpdatedCallback = (result: PagedResults<PHDocument>) => void;
3463
+ type RelationshipChangedCallback = (parentId: string, childId: string, changeType: RelationshipChangeType) => void;
3464
+ declare class ReactorSubscriptionManager implements IReactorSubscriptionManager {
3465
+ private createdSubscriptions;
3466
+ private deletedSubscriptions;
3467
+ private updatedSubscriptions;
3468
+ private relationshipSubscriptions;
3469
+ private subscriptionCounter;
3470
+ private errorHandler;
3471
+ constructor(errorHandler: ISubscriptionErrorHandler);
3472
+ onDocumentCreated(callback: DocumentCreatedCallback, search?: SearchFilter): () => void;
3473
+ onDocumentDeleted(callback: DocumentDeletedCallback, search?: SearchFilter): () => void;
3474
+ onDocumentStateUpdated(callback: DocumentStateUpdatedCallback, search?: SearchFilter, view?: ViewFilter): () => void;
3475
+ onRelationshipChanged(callback: RelationshipChangedCallback, search?: SearchFilter): () => void;
3476
+ /**
3477
+ * Notify subscribers about created documents
3478
+ */
3479
+ notifyDocumentsCreated(documentIds: string[], documentTypes?: Map<string, string>, parentIds?: Map<string, string | null>): void;
3480
+ /**
3481
+ * Notify subscribers about deleted documents
3482
+ */
3483
+ notifyDocumentsDeleted(documentIds: string[], documentTypes?: Map<string, string>, parentIds?: Map<string, string | null>): void;
3484
+ /**
3485
+ * Notify subscribers about updated documents
3486
+ */
3487
+ notifyDocumentsUpdated(documents: PHDocument[]): void;
3488
+ /**
3489
+ * Notify subscribers about relationship changes
3490
+ */
3491
+ notifyRelationshipChanged(parentId: string, childId: string, changeType: RelationshipChangeType, childType?: string): void;
3492
+ /**
3493
+ * Clear all subscriptions
3494
+ */
3495
+ clearAll(): void;
3496
+ private filterDocumentIds;
3497
+ private filterDocuments;
3498
+ private matchesRelationshipFilter;
3499
+ }
3500
+ //#endregion
3501
+ //#region src/events/event-bus.d.ts
3502
+ declare class EventBus implements IEventBus {
3503
+ readonly eventTypeToSubscribers: Map<number, Subscriber[]>;
3504
+ subscribe<K>(type: number, subscriber: (type: number, event: K) => void | Promise<void>): Unsubscribe;
3505
+ emit(type: number, data: any): Promise<void>;
3506
+ }
3507
+ //#endregion
3508
+ //#region src/registry/document-model-resolver.d.ts
3509
+ interface IDocumentModelResolver {
3510
+ ensureModelLoaded(documentType: string): Promise<void>;
3511
+ }
3512
+ /**
3513
+ * Encapsulates the logic for resolving document model modules on demand.
3514
+ * Shared between the queue (CREATE_DOCUMENT gate) and the executor manager
3515
+ * (post-failure recovery) so that both paths use the same deduplication
3516
+ * and failure-caching state.
3517
+ */
3518
+ declare class DocumentModelResolver implements IDocumentModelResolver {
3519
+ private registry;
3520
+ private loader;
3521
+ private loadingModels;
3522
+ private failedModelTypes;
3523
+ constructor(registry: IDocumentModelRegistry, loader: IDocumentModelLoader);
3524
+ ensureModelLoaded(documentType: string): Promise<void>;
3525
+ }
3526
+ /**
3527
+ * No-op resolver used when no document model loader is configured.
3528
+ * Checks the registry for the model and returns if found; throws if not.
3529
+ * Since there is no loader, missing models cannot be recovered.
3530
+ */
3531
+ declare class NullDocumentModelResolver implements IDocumentModelResolver {
3532
+ private registry?;
3533
+ constructor(registry?: IDocumentModelRegistry | undefined);
3534
+ ensureModelLoaded(documentType: string): Promise<void>;
3535
+ }
3536
+ //#endregion
3537
+ //#region src/queue/queue.d.ts
3538
+ /**
3539
+ * In-memory implementation of the IQueue interface.
3540
+ * Organizes jobs by documentId, scope, and branch to ensure proper ordering.
3541
+ * Ensures serial execution per document by tracking executing jobs.
3542
+ * Implements dependency management through queue hints.
3543
+ */
3544
+ declare class InMemoryQueue implements IQueue {
3545
+ private eventBus;
3546
+ private resolver;
3547
+ private queues;
3548
+ private jobIdToQueueKey;
3549
+ private docIdToJobId;
3550
+ private jobIdToDocId;
3551
+ private completedJobs;
3552
+ private jobIndex;
3553
+ private isBlocked;
3554
+ private onDrainedCallback?;
3555
+ private isPausedFlag;
3556
+ constructor(eventBus: IEventBus, resolver: IDocumentModelResolver);
3557
+ private toErrorInfo;
3558
+ /**
3559
+ * Creates a unique key for a document/scope/branch combination
3560
+ */
3561
+ private createQueueKey;
3562
+ /**
3563
+ * Gets or creates a queue for the given key
3564
+ */
3565
+ private getQueue;
3566
+ /**
3567
+ * Check if a document has any jobs currently executing
3568
+ */
3569
+ private isDocumentExecuting;
3570
+ /**
3571
+ * Mark a job as executing for its document
3572
+ */
3573
+ private markJobExecuting;
3574
+ /**
3575
+ * Mark a job as no longer executing for its document
3576
+ */
3577
+ private markJobComplete;
3578
+ /**
3579
+ * Check if all dependencies for a job have been completed
3580
+ */
3581
+ private areDependenciesMet;
3582
+ /**
3583
+ * Returns the head of the sub-queue if its dependencies are met, or null.
3584
+ *
3585
+ * The dispatcher only ever considers the head — a dep-blocked head holds
3586
+ * the rest of its sub-queue. This preserves per-(documentId, scope, branch)
3587
+ * FIFO regardless of how dependencies are authored, and makes the queue's
3588
+ * documented "serialized per document" invariant hold even when callers
3589
+ * omit queueHint dependencies on jobs that share a sub-queue.
3590
+ */
3591
+ private getNextJobWithMetDependencies;
3592
+ private getCreateDocumentType;
3593
+ enqueue(job: Job): Promise<void>;
3594
+ dequeue(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
3595
+ dequeueNext(signal?: AbortSignal): Promise<IJobExecutionHandle | null>;
3596
+ size(documentId: string, scope: string, branch: string): Promise<number>;
3597
+ totalSize(): Promise<number>;
3598
+ remove(jobId: string): Promise<boolean>;
3599
+ clear(documentId: string, scope: string, branch: string): Promise<void>;
3600
+ clearAll(): Promise<void>;
3601
+ hasJobs(): Promise<boolean>;
3602
+ completeJob(jobId: string): Promise<void>;
3603
+ failJob(jobId: string, error?: ErrorInfo): Promise<void>;
3604
+ deferJob(jobId: string): void;
3605
+ retryJob(jobId: string, error?: ErrorInfo): Promise<void>;
3606
+ /**
3607
+ * Check if the queue is drained and call the callback if it is
3608
+ */
3609
+ private checkDrained;
3610
+ /**
3611
+ * Returns true if and only if all jobs have been resolved.
3612
+ */
3613
+ get isDrained(): boolean;
3614
+ /**
3615
+ * Blocks the queue from accepting new jobs.
3616
+ * @param onDrained - Optional callback to call when the queue is drained
3617
+ */
3618
+ block(onDrained?: () => void): void;
3619
+ /**
3620
+ * Unblocks the queue from accepting new jobs.
3621
+ */
3622
+ unblock(): void;
3623
+ /**
3624
+ * Pauses job dequeuing. Jobs can still be enqueued but dequeueNext() will return null.
3625
+ */
3626
+ pause(): void;
3627
+ /**
3628
+ * Resumes job dequeuing and emits JOB_AVAILABLE events for pending jobs to wake up executors.
3629
+ */
3630
+ resume(): Promise<void>;
3631
+ /**
3632
+ * Returns whether job dequeuing is paused.
3633
+ */
3634
+ get paused(): boolean;
3635
+ /**
3636
+ * Returns all pending jobs across all queues.
3637
+ */
3638
+ getPendingJobs(): Job[];
3639
+ /**
3640
+ * Returns a map of document IDs to sets of executing job IDs.
3641
+ */
3642
+ getExecutingJobIds(): Map<string, Set<string>>;
3643
+ /**
3644
+ * Returns a job by ID from the job index.
3645
+ */
3646
+ getJob(jobId: string): Job | undefined;
3647
+ }
3648
+ //#endregion
3649
+ //#region src/job-tracker/in-memory-job-tracker.d.ts
3650
+ /**
3651
+ * In-memory implementation of IJobTracker.
3652
+ * Maintains job status in a Map for synchronous access.
3653
+ * Subscribes to operation events to update job states.
3654
+ */
3655
+ declare class InMemoryJobTracker implements IJobTracker {
3656
+ private eventBus;
3657
+ private jobs;
3658
+ private unsubscribers;
3659
+ constructor(eventBus: IEventBus);
3660
+ private subscribeToEvents;
3661
+ private handleWriteReady;
3662
+ private handleReadReady;
3663
+ private handleJobFailed;
3664
+ shutdown(): void;
3665
+ registerJob(jobInfo: JobInfo): void;
3666
+ markRunning(jobId: string): void;
3667
+ markFailed(jobId: string, error: ErrorInfo, job?: Job): void;
3668
+ getJobStatus(jobId: string): JobInfo | null;
3669
+ }
3670
+ //#endregion
3671
+ //#region src/executor/simple-job-executor-manager.d.ts
3672
+ type JobExecutorFactory = () => IJobExecutor;
3673
+ /**
3674
+ * Manages multiple job executors and coordinates job distribution.
3675
+ * Listens for job available events and dispatches jobs to executors.
3676
+ */
3677
+ declare class SimpleJobExecutorManager implements IJobExecutorManager {
3678
+ private executorFactory;
3679
+ private eventBus;
3680
+ private queue;
3681
+ private jobTracker;
3682
+ private logger;
3683
+ private resolver;
3684
+ private executors;
3685
+ private isRunning;
3686
+ private activeJobs;
3687
+ private totalJobsProcessed;
3688
+ private unsubscribe?;
3689
+ private deferredJobs;
3690
+ private jobTimeoutMs;
3691
+ constructor(executorFactory: JobExecutorFactory, eventBus: IEventBus, queue: IQueue, jobTracker: IJobTracker, logger: ILogger, resolver: IDocumentModelResolver, jobTimeoutMs?: number);
3692
+ start(numExecutors: number): Promise<void>;
3693
+ stop(graceful?: boolean): Promise<void>;
3694
+ getExecutors(): IJobExecutor[];
3695
+ getStatus(): ExecutorManagerStatus;
3696
+ private processNextJob;
3697
+ private checkForMoreJobs;
3698
+ private processExistingJobs;
3699
+ private toErrorInfo;
3700
+ private hasCreateDocumentAction;
3701
+ private flushDeferredJobs;
3702
+ private formatErrorHistory;
3703
+ }
3704
+ //#endregion
3705
+ //#region src/cache/collection-membership-cache.d.ts
3706
+ interface ICollectionMembershipCache {
3707
+ getCollectionsForDocuments(documentIds: string[]): Promise<Record<string, string[]>>;
3708
+ invalidate(documentId: string): void;
3709
+ }
3710
+ //#endregion
3711
+ //#region src/cache/document-meta-cache-types.d.ts
3712
+ /**
3713
+ * Cached document metadata from the "document" scope.
3714
+ *
3715
+ * This lightweight structure holds essential document information needed by
3716
+ * the job executor without fetching full scope state. It provides an explicit
3717
+ * cross-scope contract for accessing document scope metadata.
3718
+ */
3719
+ type CachedDocumentMeta = {
3720
+ /**
3721
+ * The full PHDocumentState from document.state.document.
3722
+ * Contains version, hash, isDeleted, deletedAtUtcIso, etc.
3723
+ */
3724
+ state: PHDocumentState;
3725
+ /**
3726
+ * The document type (from header), cached for convenience.
3727
+ */
3728
+ documentType: string;
3729
+ /**
3730
+ * The revision of the document scope when this metadata was captured.
3731
+ * Used for cache invalidation and consistency checks.
3732
+ */
3733
+ documentScopeRevision: number;
3734
+ };
3735
+ /**
3736
+ * Interface for the document metadata cache.
3737
+ *
3738
+ * This cache provides an explicit cross-scope contract for accessing document
3739
+ * scope metadata. It solves the problem where job execution in one scope (e.g.,
3740
+ * "global") needs access to document scope state (version, isDeleted, etc.)
3741
+ * which may be stale in scope-specific caches or keyframes.
3742
+ *
3743
+ * The cache supports:
3744
+ * - Latest metadata retrieval with LRU caching
3745
+ * - Historical metadata reconstruction for reshuffling scenarios
3746
+ * - Eager updates after document scope operations
3747
+ */
3748
+ interface IDocumentMetaCache {
3749
+ /**
3750
+ * Retrieves the LATEST document metadata from cache or rebuilds from operations.
3751
+ *
3752
+ * On cache miss, fetches all document scope operations and reconstructs the
3753
+ * current PHDocumentState by applying UPGRADE_DOCUMENT and DELETE_DOCUMENT
3754
+ * operations.
3755
+ *
3756
+ * @param documentId - The document identifier
3757
+ * @param branch - Branch name
3758
+ * @param signal - Optional abort signal to cancel the operation
3759
+ * @returns The cached or rebuilt document metadata
3760
+ * @throws {Error} "Operation aborted" if signal is aborted
3761
+ * @throws {Error} If document not found (no CREATE_DOCUMENT operation)
3762
+ */
3763
+ getDocumentMeta(documentId: string, branch: string, signal?: AbortSignal): Promise<CachedDocumentMeta>;
3764
+ /**
3765
+ * Rebuilds document metadata at a SPECIFIC revision (always rebuilds, no caching).
3766
+ *
3767
+ * Used during reshuffling when operations need to be inserted at a previous
3768
+ * revision and we need the document scope state as of that point in time.
3769
+ *
3770
+ * @param documentId - The document identifier
3771
+ * @param branch - Branch name
3772
+ * @param targetRevision - The document scope revision to reconstruct up to
3773
+ * @param signal - Optional abort signal to cancel the operation
3774
+ * @returns Document metadata as of the target revision
3775
+ * @throws {Error} "Operation aborted" if signal is aborted
3776
+ * @throws {Error} If document not found
3777
+ */
3778
+ rebuildAtRevision(documentId: string, branch: string, targetRevision: number, signal?: AbortSignal): Promise<CachedDocumentMeta>;
3779
+ /**
3780
+ * Eagerly updates cached metadata after document scope operations.
3781
+ *
3782
+ * Called by the job executor after CREATE_DOCUMENT, UPGRADE_DOCUMENT, or
3783
+ * DELETE_DOCUMENT operations to keep the cache current.
3784
+ *
3785
+ * @param documentId - The document identifier
3786
+ * @param branch - Branch name
3787
+ * @param meta - The new metadata to cache
3788
+ */
3789
+ putDocumentMeta(documentId: string, branch: string, meta: CachedDocumentMeta): void;
3790
+ /**
3791
+ * Invalidates cached document metadata.
3792
+ *
3793
+ * Call before reshuffling operations that modify the document scope, or
3794
+ * when document state may have changed externally.
3795
+ *
3796
+ * @param documentId - The document identifier
3797
+ * @param branch - Optional branch to narrow invalidation (if omitted, all branches)
3798
+ * @returns Number of entries invalidated
3799
+ */
3800
+ invalidate(documentId: string, branch?: string): number;
3801
+ /**
3802
+ * Clears all cached document metadata.
3803
+ */
3804
+ clear(): void;
3805
+ /**
3806
+ * Performs startup initialization.
3807
+ */
3808
+ startup(): Promise<void>;
3809
+ /**
3810
+ * Performs graceful shutdown.
3811
+ */
3812
+ shutdown(): Promise<void>;
3813
+ }
3814
+ //#endregion
3815
+ //#region src/cache/buffer/ring-buffer.d.ts
3816
+ /**
3817
+ * RingBuffer is a generic circular buffer implementation that stores a fixed number
3818
+ * of items. When the buffer is full, new items overwrite the oldest items.
3819
+ *
3820
+ * This implementation maintains O(1) time complexity for push operations and provides
3821
+ * items in chronological order (oldest to newest) via getAll().
3822
+ *
3823
+ * @template T - The type of items stored in the buffer
3824
+ */
3825
+ declare class RingBuffer<T> {
3826
+ private buffer;
3827
+ private head;
3828
+ private size;
3829
+ private capacity;
3830
+ constructor(capacity: number);
3831
+ /**
3832
+ * Adds an item to the buffer. If the buffer is full, overwrites the oldest item.
3833
+ *
3834
+ * @param item - The item to add
3835
+ */
3836
+ push(item: T): void;
3837
+ /**
3838
+ * Returns all items in the buffer in chronological order (oldest to newest).
3839
+ *
3840
+ * @returns Array of items in insertion order
3841
+ */
3842
+ getAll(): T[];
3843
+ /**
3844
+ * Clears all items from the buffer.
3845
+ */
3846
+ clear(): void;
3847
+ /**
3848
+ * Gets the current number of items in the buffer.
3849
+ */
3850
+ get length(): number;
3851
+ }
3852
+ //#endregion
3853
+ //#region src/cache/kysely-write-cache.d.ts
3854
+ type DocumentStream = {
3855
+ key: string;
3856
+ ringBuffer: RingBuffer<CachedSnapshot>;
3857
+ };
3858
+ /**
3859
+ * In-memory write cache with keyframe persistence for PHDocuments.
3860
+ *
3861
+ * Caches document snapshots in ring buffers with LRU eviction. On cache miss,
3862
+ * rebuilds documents from nearest keyframe or full operation history.
3863
+ *
3864
+ * **Performance Characteristics:**
3865
+ * - Cache hit: O(1) lookup in ring buffer
3866
+ * - Cold miss: O(n) where n is total operation count, or O(k) where k is operations since keyframe
3867
+ * - Warm miss: O(m) where m is operations since cached revision
3868
+ * - Eviction: O(1) for LRU tracking and removal
3869
+ *
3870
+ * **Thread Safety:**
3871
+ * Not thread-safe. Designed for single-threaded job executor environment.
3872
+ * External synchronization required for concurrent access across multiple executors.
3873
+ *
3874
+ * **Example:**
3875
+ * ```typescript
3876
+ * const cache = new KyselyWriteCache(
3877
+ * keyframeStore,
3878
+ * operationStore,
3879
+ * registry,
3880
+ * { maxDocuments: 1000, ringBufferSize: 10, keyframeInterval: 10 }
3881
+ * );
3882
+ *
3883
+ * await cache.startup();
3884
+ *
3885
+ * // Retrieve or rebuild document
3886
+ * const doc = await cache.getState(docId, docType, scope, branch, revision);
3887
+ *
3888
+ * // Cache result after job execution
3889
+ * cache.putState(docId, docType, scope, branch, newRevision, updatedDoc);
3890
+ *
3891
+ * await cache.shutdown();
3892
+ * ```
3893
+ */
3894
+ declare class KyselyWriteCache implements IWriteCache {
3895
+ private streams;
3896
+ private lruTracker;
3897
+ private keyframeStore;
3898
+ private operationStore;
3899
+ private registry;
3900
+ private config;
3901
+ constructor(keyframeStore: IKeyframeStore, operationStore: IOperationStore, registry: IDocumentModelRegistry, config: WriteCacheConfig);
3902
+ withScopedStores(operationStore: IOperationStore, keyframeStore: IKeyframeStore): KyselyWriteCache;
3903
+ /**
3904
+ * Initializes the write cache.
3905
+ * Currently a no-op as keyframe store lifecycle is managed externally.
3906
+ */
3907
+ startup(): Promise<void>;
3908
+ /**
3909
+ * Shuts down the write cache.
3910
+ * Currently a no-op as keyframe store lifecycle is managed externally.
3911
+ */
3912
+ shutdown(): Promise<void>;
3913
+ /**
3914
+ * Retrieves document state at a specific revision from cache or rebuilds it.
3915
+ *
3916
+ * Cache hit path: Returns cached snapshot if available (O(1))
3917
+ * Warm miss path: Rebuilds from cached base revision + incremental ops
3918
+ * Cold miss path: Rebuilds from keyframe or from scratch using all operations
3919
+ *
3920
+ * @param documentId - The document identifier
3921
+ * @param scope - The operation scope
3922
+ * @param branch - The operation branch
3923
+ * @param targetRevision - The target revision, or undefined for newest
3924
+ * @param signal - Optional abort signal to cancel the operation
3925
+ * @returns The document at the target revision
3926
+ * @throws {Error} "Operation aborted" if signal is aborted
3927
+ * @throws {ModuleNotFoundError} If document type not registered in registry
3928
+ * @throws {Error} "Failed to rebuild document" if operation store fails
3929
+ * @throws {Error} If reducer throws during operation application
3930
+ * @throws {Error} If document serialization fails
3931
+ */
3932
+ getState(documentId: string, scope: string, branch: string, targetRevision?: number, signal?: AbortSignal): Promise<PHDocument>;
3933
+ /**
3934
+ * Stores a document snapshot in the cache at a specific revision.
3935
+ *
3936
+ * The cached document is a shallow copy of the input with its operation history
3937
+ * truncated to the last operation per scope and its clipboard cleared. This keeps
3938
+ * memory use and copy costs constant regardless of operation count. Consumers of
3939
+ * getState() must not rely on the full operation history being present; the only
3940
+ * guaranteed invariant is that operations[scope].at(-1) reflects the latest
3941
+ * operation index for each scope.
3942
+ *
3943
+ * Updates LRU tracker and may evict least recently used stream if at capacity.
3944
+ * Asynchronously persists keyframes at configured intervals (fire-and-forget).
3945
+ *
3946
+ * @param documentId - The document identifier
3947
+ * @param scope - The operation scope
3948
+ * @param branch - The operation branch
3949
+ * @param revision - The revision number
3950
+ * @param document - The document to cache
3951
+ * @throws {Error} If document serialization fails
3952
+ */
3953
+ putState(documentId: string, scope: string, branch: string, revision: number, document: PHDocument): void;
3954
+ /**
3955
+ * Invalidates cached document streams.
3956
+ *
3957
+ * Supports three invalidation scopes:
3958
+ * - Document-level: invalidate(documentId) - removes all streams for document
3959
+ * - Scope-level: invalidate(documentId, scope) - removes all branches for scope
3960
+ * - Stream-level: invalidate(documentId, scope, branch) - removes specific stream
3961
+ *
3962
+ * @param documentId - The document identifier
3963
+ * @param scope - Optional scope to narrow invalidation
3964
+ * @param branch - Optional branch to narrow invalidation (requires scope)
3965
+ * @returns The number of streams evicted
3966
+ */
3967
+ invalidate(documentId: string, scope?: string, branch?: string): number;
3968
+ /**
3969
+ * Clears the entire cache, removing all cached document streams.
3970
+ * Resets LRU tracking state. This operation always succeeds.
3971
+ */
3972
+ clear(): void;
3973
+ /**
3974
+ * Retrieves a specific stream for a document. Exposed on the implementation
3975
+ * for testing, but not on the interface.
3976
+ *
3977
+ * @internal
3978
+ */
3979
+ getStream(documentId: string, scope: string, branch: string): DocumentStream | undefined;
3980
+ private findNearestKeyframe;
3981
+ private coldMissRebuild;
3982
+ private warmMissRebuild;
3983
+ private findNearestOlderSnapshot;
3984
+ private makeStreamKey;
3985
+ private getOrCreateStream;
3986
+ private isKeyframeRevision;
3987
+ }
3988
+ //#endregion
3989
+ //#region src/storage/kysely/store.d.ts
3990
+ declare class KyselyOperationStore implements IOperationStore {
3991
+ private db;
3992
+ private trx?;
3993
+ constructor(db: Kysely<Database$1>);
3994
+ private get queryExecutor();
3995
+ withTransaction(trx: Transaction<Database$1>): KyselyOperationStore;
3996
+ apply(documentId: string, documentType: string, scope: string, branch: string, revision: number, fn: (txn: AtomicTxn) => void | Promise<void>, signal?: AbortSignal): Promise<void>;
3997
+ private executeApply;
3998
+ getSince(documentId: string, scope: string, branch: string, revision: number, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
3999
+ getSinceId(id: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext$1>>;
4000
+ getConflicting(documentId: string, scope: string, branch: string, minTimestamp: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
4001
+ getRevisions(documentId: string, branch: string, signal?: AbortSignal): Promise<DocumentRevisions>;
4002
+ private rowToOperation;
4003
+ private rowToOperationWithContext;
4004
+ }
4005
+ //#endregion
4006
+ //#region src/storage/kysely/keyframe-store.d.ts
4007
+ declare class KyselyKeyframeStore implements IKeyframeStore {
4008
+ private db;
4009
+ private trx?;
4010
+ constructor(db: Kysely<Database$1>);
4011
+ private get queryExecutor();
4012
+ withTransaction(trx: Transaction<Database$1>): KyselyKeyframeStore;
4013
+ putKeyframe(documentId: string, scope: string, branch: string, revision: number, document: PHDocument, signal?: AbortSignal): Promise<void>;
4014
+ findNearestKeyframe(documentId: string, scope: string, branch: string, targetRevision: number, signal?: AbortSignal): Promise<{
4015
+ revision: number;
4016
+ document: PHDocument;
4017
+ } | undefined>;
4018
+ listKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<Array<{
4019
+ scope: string;
4020
+ branch: string;
4021
+ revision: number;
4022
+ document: PHDocument;
4023
+ }>>;
4024
+ deleteKeyframes(documentId: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<number>;
4025
+ }
4026
+ //#endregion
4027
+ //#region src/executor/execution-scope.d.ts
4028
+ interface ExecutionStores {
4029
+ operationStore: IOperationStore;
4030
+ operationIndex: IOperationIndex;
4031
+ writeCache: IWriteCache;
4032
+ documentMetaCache: IDocumentMetaCache;
4033
+ collectionMembershipCache: ICollectionMembershipCache;
4034
+ }
4035
+ interface IExecutionScope {
4036
+ run<T>(fn: (stores: ExecutionStores) => Promise<T>, signal?: AbortSignal): Promise<T>;
4037
+ }
4038
+ //#endregion
4039
+ //#region src/executor/simple-job-executor.d.ts
4040
+ /**
4041
+ * Simple job executor that processes a job by applying actions through document model reducers.
4042
+ */
4043
+ declare class SimpleJobExecutor implements IJobExecutor {
4044
+ private logger;
4045
+ private registry;
4046
+ private operationStore;
4047
+ private eventBus;
4048
+ private writeCache;
4049
+ private operationIndex;
4050
+ private documentMetaCache;
4051
+ private collectionMembershipCache;
4052
+ private driveContainerTypes;
4053
+ private config;
4054
+ private signatureVerifierModule;
4055
+ private documentActionHandler;
4056
+ private executionScope;
4057
+ constructor(logger: ILogger, registry: IDocumentModelRegistry, operationStore: IOperationStore, eventBus: IEventBus, writeCache: IWriteCache, operationIndex: IOperationIndex, documentMetaCache: IDocumentMetaCache, collectionMembershipCache: ICollectionMembershipCache, driveContainerTypes: ReadonlySet<string>, config: JobExecutorConfig, signatureVerifier?: SignatureVerificationHandler, executionScope?: IExecutionScope);
4058
+ /**
4059
+ * Execute a single job by applying all its actions through the appropriate reducers.
4060
+ * Actions are processed sequentially in order.
4061
+ */
4062
+ executeJob(job: Job, signal?: AbortSignal): Promise<JobResult>;
4063
+ private getCollectionMembershipsForOperations;
4064
+ private processActions;
4065
+ private executeRegularAction;
4066
+ private executeLoadJob;
4067
+ private accumulateResultOrReturnError;
4068
+ }
4069
+ //#endregion
4070
+ //#region src/registry/errors.d.ts
4071
+ /**
4072
+ * Error thrown when a document model module is not found in the registry.
4073
+ */
4074
+ declare class ModuleNotFoundError extends Error {
4075
+ readonly documentType: string;
4076
+ readonly requestedVersion: number | undefined;
4077
+ constructor(documentType: string, version?: number);
4078
+ static isError(error: unknown): error is ModuleNotFoundError;
4079
+ }
4080
+ /**
4081
+ * Error thrown when attempting to register a module that already exists.
4082
+ */
4083
+ declare class DuplicateModuleError extends Error {
4084
+ constructor(documentType: string, version?: number);
4085
+ static isError(error: unknown): error is DuplicateModuleError;
4086
+ }
4087
+ /**
4088
+ * Error thrown when a module is invalid or malformed.
4089
+ */
4090
+ declare class InvalidModuleError extends Error {
4091
+ constructor(message: string);
4092
+ }
4093
+ /**
4094
+ * Error thrown when attempting to register an upgrade manifest that already exists.
4095
+ */
4096
+ declare class DuplicateManifestError extends Error {
4097
+ constructor(documentType: string);
4098
+ static isError(error: unknown): error is DuplicateManifestError;
4099
+ }
4100
+ //#endregion
4101
+ //#region src/registry/implementation.d.ts
4102
+ /**
4103
+ * In-memory implementation of the IDocumentModelRegistry interface.
4104
+ * Manages document model modules with version-aware storage and upgrade manifest support.
4105
+ */
4106
+ declare class DocumentModelRegistry implements IDocumentModelRegistry {
4107
+ private modules;
4108
+ private manifests;
4109
+ registerModules(...modules: DocumentModelModule<any>[]): RegistrationResult<DocumentModelModule<any>>[];
4110
+ unregisterModules(...documentTypes: string[]): boolean;
4111
+ getModule(documentType: string, version?: number): DocumentModelModule<any>;
4112
+ getAllModules(): DocumentModelModule<any>[];
4113
+ clear(): void;
4114
+ getSupportedVersions(documentType: string): number[];
4115
+ getLatestVersion(documentType: string): number;
4116
+ registerUpgradeManifests(...manifestsToRegister: UpgradeManifest<readonly number[]>[]): RegistrationResult<UpgradeManifest<readonly number[]>>[];
4117
+ unregisterUpgradeManifests(...documentTypes: string[]): boolean;
4118
+ getUpgradeManifest(documentType: string): UpgradeManifest<readonly number[]>;
4119
+ computeUpgradePath(documentType: string, fromVersion: number, toVersion: number): UpgradeTransition[];
4120
+ getUpgradeReducer(documentType: string, fromVersion: number, toVersion: number): UpgradeReducer<any, any>;
4121
+ }
4122
+ //#endregion
4123
+ //#region src/read-models/base-read-model.d.ts
4124
+ type BaseReadModelConfig = {
4125
+ readModelId: string;
4126
+ rebuildStateOnInit: boolean;
4127
+ };
4128
+ /**
4129
+ * Base class for read models that provides catch-up/rewind functionality.
4130
+ * Handles initialization, state tracking via ViewState table, and consistency tracking.
4131
+ * Subclasses override commitOperations() with their specific domain logic.
4132
+ */
4133
+ declare class BaseReadModel implements IReadModel {
4134
+ protected db: Kysely<DocumentViewDatabase>;
4135
+ protected operationIndex: IOperationIndex;
4136
+ protected writeCache: IWriteCache;
4137
+ protected consistencyTracker: IConsistencyTracker;
4138
+ protected config: BaseReadModelConfig;
4139
+ protected lastOrdinal: number;
4140
+ readonly name: string;
4141
+ constructor(db: Kysely<DocumentViewDatabase>, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker, config: BaseReadModelConfig);
4142
+ /**
4143
+ * Initializes the read model by loading state and catching up on missed operations.
4144
+ */
4145
+ init(): Promise<void>;
4146
+ /**
4147
+ * Template method: runs domain-specific commitOperations, then persists
4148
+ * state and updates consistency tracking.
4149
+ */
4150
+ indexOperations(items: OperationWithContext$1[]): Promise<void>;
4151
+ /**
4152
+ * Waits for the read model to reach the specified consistency level.
4153
+ */
4154
+ waitForConsistency(token: ConsistencyToken, timeoutMs?: number, signal?: AbortSignal): Promise<void>;
4155
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4156
+ /**
4157
+ * Rebuilds document state for each operation using the write cache.
4158
+ */
4159
+ protected rebuildStateForOperations(operations: OperationWithContext$1[]): Promise<OperationWithContext$1[]>;
4160
+ /**
4161
+ * Loads the last processed ordinal from the ViewState table.
4162
+ * Returns undefined if no state exists for this read model.
4163
+ */
4164
+ protected loadState(): Promise<number | undefined>;
4165
+ /**
4166
+ * Initializes the ViewState row for this read model.
4167
+ */
4168
+ protected initializeState(): Promise<void>;
4169
+ /**
4170
+ * Saves the last processed ordinal to the ViewState table.
4171
+ */
4172
+ protected saveState(trx: Transaction<DocumentViewDatabase>, items: OperationWithContext$1[]): Promise<void>;
4173
+ /**
4174
+ * Updates the consistency tracker with the processed operations.
4175
+ */
4176
+ protected updateConsistencyTracker(items: OperationWithContext$1[]): void;
4177
+ }
4178
+ //#endregion
4179
+ //#region src/storage/kysely/document-indexer.d.ts
4180
+ type IndexerDatabase = Database$1 & DocumentIndexerDatabase & DocumentViewDatabase;
4181
+ declare class KyselyDocumentIndexer extends BaseReadModel implements IDocumentIndexer {
4182
+ private _db;
4183
+ constructor(db: Kysely<IndexerDatabase>, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker);
4184
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4185
+ getOutgoing(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4186
+ getIncoming(documentId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4187
+ getOrphanedChildren(parentIds: string[], types?: string[], signal?: AbortSignal): Promise<string[]>;
4188
+ hasRelationship(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean>;
4189
+ getUndirectedRelationships(a: string, b: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4190
+ getDirectedRelationships(sourceId: string, targetId: string, types?: string[], paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
4191
+ findPath(sourceId: string, targetId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[] | null>;
4192
+ findAncestors(documentId: string, types?: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<IDocumentGraph>;
4193
+ getRelationshipTypes(consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
4194
+ private handleAddRelationship;
4195
+ private handleRemoveRelationship;
4196
+ private handleUpdateRelationship;
4197
+ }
4198
+ //#endregion
4199
+ //#region src/read-models/coordinator.d.ts
4200
+ /**
4201
+ * Coordinates read model synchronization by listening to operation write events
4202
+ * and updating all registered read models in parallel.
4203
+ *
4204
+ * This coordinator is responsible for:
4205
+ * - Subscribing to OPERATION_WRITTEN events from the event bus
4206
+ * - Distributing operation updates to all registered read models
4207
+ * - Managing the lifecycle of read model subscriptions
4208
+ *
4209
+ * Read models are updated asynchronously and in parallel to avoid blocking
4210
+ * the write path. Errors in read model updates are propagated through the
4211
+ * event bus but do not affect the write operation success.
4212
+ */
4213
+ declare class ReadModelCoordinator implements IReadModelCoordinator {
4214
+ private eventBus;
4215
+ readonly preReady: IReadModel[];
4216
+ readonly postReady: IReadModel[];
4217
+ private unsubscribe?;
4218
+ private isRunning;
4219
+ readonly readModels: IReadModel[];
4220
+ constructor(eventBus: IEventBus, preReady: IReadModel[], postReady: IReadModel[]);
4221
+ /**
4222
+ * Start listening for operation events and updating read models.
4223
+ * Can be called multiple times safely (subsequent calls are no-ops).
4224
+ */
4225
+ start(): void;
4226
+ /**
4227
+ * Stop listening and clean up subscriptions.
4228
+ * Can be called multiple times safely (subsequent calls are no-ops).
4229
+ */
4230
+ stop(): void;
4231
+ /**
4232
+ * Handle write ready events by updating all read models in parallel.
4233
+ * Errors from individual read models are collected and re-thrown as an aggregate.
4234
+ */
4235
+ private handleWriteReady;
4236
+ }
4237
+ //#endregion
4238
+ //#region src/read-models/document-view.d.ts
4239
+ type Database$2 = Database$1 & DocumentViewDatabase;
4240
+ declare class KyselyDocumentView extends BaseReadModel implements IDocumentView {
4241
+ private operationStore;
4242
+ private _db;
4243
+ constructor(db: Kysely<Database$2>, operationStore: IOperationStore, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker);
4244
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4245
+ exists(documentIds: string[], consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<boolean[]>;
4246
+ get<TDocument extends PHDocument>(documentId: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
4247
+ getMany<TDocument extends PHDocument>(documentIds: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument[]>;
4248
+ getByIdOrSlug<TDocument extends PHDocument>(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<TDocument>;
4249
+ findByType(type: string, view?: ViewFilter$1, paging?: PagingOptions, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
4250
+ resolveSlug(slug: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string | undefined>;
4251
+ resolveSlugs(slugs: string[], view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string[]>;
4252
+ resolveIdOrSlug(identifier: string, view?: ViewFilter$1, consistencyToken?: ConsistencyToken, signal?: AbortSignal): Promise<string>;
4253
+ }
4254
+ //#endregion
4255
+ //#region src/storage/migrations/migrator.d.ts
4256
+ declare const REACTOR_SCHEMA = "reactor";
4257
+ declare function runMigrations(db: Kysely<any>, schema?: string): Promise<MigrationResult>;
4258
+ declare function getMigrationStatus(db: Kysely<any>, schema?: string): Promise<readonly kysely.MigrationInfo[]>;
4259
+ //#endregion
4260
+ //#region src/storage/kysely/sync-cursor-storage.d.ts
4261
+ declare class KyselySyncCursorStorage implements ISyncCursorStorage {
4262
+ private readonly db;
4263
+ constructor(db: Kysely<Database$1>);
4264
+ list(remoteName: string, signal?: AbortSignal): Promise<RemoteCursor[]>;
4265
+ get(remoteName: string, cursorType: "inbox" | "outbox", signal?: AbortSignal): Promise<RemoteCursor>;
4266
+ upsert(cursor: RemoteCursor, signal?: AbortSignal): Promise<void>;
4267
+ remove(remoteName: string, signal?: AbortSignal): Promise<void>;
4268
+ }
4269
+ //#endregion
4270
+ //#region src/storage/kysely/sync-remote-storage.d.ts
4271
+ declare class KyselySyncRemoteStorage implements ISyncRemoteStorage {
4272
+ private readonly db;
4273
+ constructor(db: Kysely<Database$1>);
4274
+ list(signal?: AbortSignal): Promise<RemoteRecord[]>;
4275
+ get(name: string, signal?: AbortSignal): Promise<RemoteRecord>;
4276
+ upsert(remote: RemoteRecord, signal?: AbortSignal): Promise<void>;
4277
+ remove(name: string, signal?: AbortSignal): Promise<void>;
4278
+ }
4279
+ //#endregion
4280
+ //#region src/sync/channels/gql-request-channel-factory.d.ts
4281
+ /**
4282
+ * Factory for creating GqlRequestChannel instances.
4283
+ *
4284
+ * Extracts GraphQL-specific configuration from ChannelConfig.parameters and
4285
+ * instantiates GqlRequestChannel instances for network-based synchronization.
4286
+ *
4287
+ * The optional jwtHandler enables dynamic JWT token generation per-request,
4288
+ * which is useful for short-lived tokens with audience-specific claims.
4289
+ */
4290
+ declare class GqlRequestChannelFactory implements IChannelFactory {
4291
+ private readonly logger;
4292
+ private readonly jwtHandler?;
4293
+ private readonly queue;
4294
+ constructor(logger: ILogger, jwtHandler: JwtHandler | undefined, queue: IQueue);
4295
+ /**
4296
+ * Creates a new GqlRequestChannel instance with the given configuration.
4297
+ * See GqlChannelConfig for the expected parameters.
4298
+ *
4299
+ * @param config - Channel configuration including type and parameters
4300
+ * @param cursorStorage - Storage for persisting synchronization cursors
4301
+ * @param operationIndex - Operation index for querying timestamps
4302
+ * @returns A new GqlRequestChannel instance
4303
+ */
4304
+ instance(remoteId: string, remoteName: string, config: ChannelConfig, cursorStorage: ISyncCursorStorage, collectionId: string, filter: RemoteFilter, operationIndex: IOperationIndex, options?: RemoteOptions): IChannel;
4305
+ }
4306
+ //#endregion
4307
+ //#region src/sync/channels/gql-response-channel-factory.d.ts
4308
+ /**
4309
+ * Factory for creating GqlResponseChannel instances.
4310
+ */
4311
+ declare class GqlResponseChannelFactory implements IChannelFactory {
4312
+ private readonly logger;
4313
+ constructor(logger: ILogger);
4314
+ instance(remoteId: string, remoteName: string, config: ChannelConfig, cursorStorage: ISyncCursorStorage): IChannel;
4315
+ }
4316
+ //#endregion
4317
+ //#region src/sync/channels/poll-timer.d.ts
4318
+ /**
4319
+ * Timer that controls when polling occurs.
4320
+ * GqlChannel registers a delegate; the timer invokes it when appropriate.
4321
+ * The delegate returns a Promise; timer waits for completion before scheduling next tick.
4322
+ */
4323
+ type IPollTimer = {
4324
+ /** Register the delegate to be called on each tick. Returns Promise that timer awaits. */setDelegate: (delegate: () => Promise<void>) => void; /** Start the timer (begins calling delegate periodically) */
4325
+ start: () => void; /** Stop the timer */
4326
+ stop: () => void;
4327
+ /**
4328
+ * Fires the delegate exactly once without changing the running/paused state.
4329
+ * Used by Manual polling mode to pull on demand without resuming the schedule.
4330
+ */
4331
+ triggerNow: () => void;
4332
+ };
4333
+ //#endregion
4334
+ //#region src/sync/channels/gql-req-channel.d.ts
4335
+ /**
4336
+ * Configuration parameters for GqlChannel
4337
+ */
4338
+ type GqlChannelConfig = {
4339
+ /** The GraphQL endpoint URL */url: string; /** Dynamic JWT token handler for generating fresh tokens per-request */
4340
+ jwtHandler?: JwtHandler; /** Custom fetch function for testing (default: global fetch) */
4341
+ fetchFn?: typeof fetch; /** Collection ID to synchronize */
4342
+ collectionId: string; /** Filter to apply to operations */
4343
+ filter: RemoteFilter; /** Base delay in ms for exponential backoff on push retries */
4344
+ retryBaseDelayMs: number; /** Maximum delay in ms for exponential backoff on push retries */
4345
+ retryMaxDelayMs: number;
4346
+ };
4347
+ /**
4348
+ * GraphQL-based synchronization channel for network communication between reactors.
4349
+ */
4350
+ declare class GqlRequestChannel implements IChannel {
4351
+ private readonly logger;
4352
+ readonly inbox: IMailbox;
4353
+ readonly outbox: IMailbox;
4354
+ readonly deadLetter: IMailbox;
4355
+ readonly config: GqlChannelConfig;
4356
+ private readonly bufferedOutbox;
4357
+ private readonly channelId;
4358
+ private readonly remoteName;
4359
+ private readonly cursorStorage;
4360
+ private readonly operationIndex;
4361
+ private readonly pollTimer;
4362
+ private readonly abortController;
4363
+ private isShutdown;
4364
+ private failureCount;
4365
+ private lastSuccessUtcMs?;
4366
+ private lastFailureUtcMs?;
4367
+ private lastPersistedInboxOrdinal;
4368
+ private lastPersistedOutboxOrdinal;
4369
+ private pushFailureCount;
4370
+ private pushRetryTimer;
4371
+ private pushBlocked;
4372
+ private isPushing;
4373
+ private pendingDrain;
4374
+ private receivingPages;
4375
+ private connectionState;
4376
+ private readonly connectionStateCallbacks;
4377
+ constructor(logger: ILogger, channelId: string, remoteName: string, cursorStorage: ISyncCursorStorage, config: GqlChannelConfig, operationIndex: IOperationIndex, pollTimer: IPollTimer);
4378
+ /**
4379
+ * Shuts down the channel and prevents further operations.
4380
+ */
4381
+ shutdown(): Promise<void>;
4382
+ getConnectionState(): ConnectionStateSnapshot;
4383
+ onConnectionStateChange(callback: ConnectionStateChangeCallback): () => void;
4384
+ triggerPull(): void;
4385
+ /**
4386
+ * Initializes the channel by registering it on the remote server and starting polling.
4387
+ */
4388
+ init(): Promise<void>;
4389
+ private transitionConnectionState;
4390
+ /**
4391
+ * Polls the remote for new sync envelopes.
4392
+ */
4393
+ private poll;
4394
+ /**
4395
+ * Handles dead letters reported by the remote server.
4396
+ * Creates local dead letter SyncOperations so the channel quiesces.
4397
+ */
4398
+ private handleRemoteDeadLetters;
4399
+ /**
4400
+ * Handles polling errors with error classification.
4401
+ * Returns true if the error was handled (caller should not rethrow).
4402
+ */
4403
+ private handlePollError;
4404
+ /**
4405
+ * Recovers from a "Channel not found" error by re-registering and restarting polling.
4406
+ * Self-retries with backoff instead of restarting the poll timer on failure.
4407
+ */
4408
+ private recoverFromChannelNotFound;
4409
+ /**
4410
+ * Queries the remote GraphQL endpoint for sync envelopes.
4411
+ */
4412
+ private pollSyncEnvelopes;
4413
+ /**
4414
+ * Registers or updates this channel on the remote server via GraphQL mutation.
4415
+ * Returns the remote's ack ordinal so the client can trim its outbox.
4416
+ */
4417
+ private touchRemoteChannel;
4418
+ /**
4419
+ * Fire-and-forget push with retry on recoverable errors.
4420
+ * On success, clears push blocked state. On recoverable error, blocks
4421
+ * further pushes and schedules a retry. On unrecoverable error, moves
4422
+ * ops to deadLetter.
4423
+ */
4424
+ private attemptPush;
4425
+ /**
4426
+ * Schedules a retry of all current outbox items using exponential backoff.
4427
+ */
4428
+ private schedulePushRetry;
4429
+ /**
4430
+ * Drains pending outbox items that arrived while a push was in-flight.
4431
+ * Server-side action.id dedup handles any overlap with the previous push.
4432
+ */
4433
+ private drainOutbox;
4434
+ /**
4435
+ * Classifies an error as recoverable or unrecoverable based on its type.
4436
+ * Recoverable errors are transient and worth retrying (network, 5xx, parse).
4437
+ * Unrecoverable errors will not self-heal (auth, client errors, GraphQL rejections).
4438
+ */
4439
+ private classifyError;
4440
+ /**
4441
+ * Pushes multiple sync operations to the remote via a single GraphQL mutation.
4442
+ * Creates one SyncEnvelope per SyncOperation with key/dependsOn for batch ordering.
4443
+ */
4444
+ private pushSyncOperations;
4445
+ /**
4446
+ * Gets the authorization header value using jwtHandler.
4447
+ */
4448
+ private getAuthorizationHeader;
4449
+ /**
4450
+ * Executes a GraphQL query or mutation against the remote endpoint.
4451
+ */
4452
+ private executeGraphQL;
4453
+ get poller(): IPollTimer;
4454
+ }
4455
+ //#endregion
4456
+ //#region src/sync/channels/gql-res-channel.d.ts
4457
+ /**
4458
+ * This class is used server-side to accumulate inbox + outbox operations.
4459
+ *
4460
+ * In general, the resolvers are responsible for updating mailboxes.
4461
+ */
4462
+ declare class GqlResponseChannel implements IChannel {
4463
+ private readonly logger;
4464
+ readonly inbox: Mailbox;
4465
+ readonly outbox: Mailbox;
4466
+ readonly deadLetter: Mailbox;
4467
+ private readonly channelId;
4468
+ private readonly remoteName;
4469
+ private readonly cursorStorage;
4470
+ private isShutdown;
4471
+ private lastPersistedInboxOrdinal;
4472
+ private lastPersistedOutboxOrdinal;
4473
+ private connectionState;
4474
+ private readonly connectionStateCallbacks;
4475
+ constructor(logger: ILogger, channelId: string, remoteName: string, cursorStorage: ISyncCursorStorage);
4476
+ shutdown(): Promise<void>;
4477
+ getConnectionState(): ConnectionStateSnapshot;
4478
+ onConnectionStateChange(callback: ConnectionStateChangeCallback): () => void;
4479
+ /** Response channels are push-driven; resolvers populate mailboxes directly. */
4480
+ triggerPull(): void;
4481
+ private transitionConnectionState;
4482
+ init(): Promise<void>;
4483
+ }
4484
+ //#endregion
4485
+ //#region src/sync/channels/interval-poll-timer.d.ts
4486
+ type PollTimerConfig = {
4487
+ intervalMs: number;
4488
+ maxQueueDepth: number;
4489
+ backpressureCheckIntervalMs: number;
4490
+ retryBaseDelayMs: number;
4491
+ retryMaxDelayMs: number;
4492
+ /**
4493
+ * If true, start() puts the timer into a paused state — running but not ticking.
4494
+ * Use resume() to begin scheduling ticks, or triggerNow() to fire a single tick
4495
+ * without leaving the paused state. Defaults to false (auto-tick on start).
4496
+ */
4497
+ startPaused: boolean;
4498
+ };
4499
+ /**
4500
+ * Default poll timer using setTimeout.
4501
+ * Waits for delegate completion before scheduling next tick.
4502
+ * Checks queue depth and defers polling when backpressure is detected.
4503
+ */
4504
+ declare class IntervalPollTimer implements IPollTimer {
4505
+ private delegate;
4506
+ private timer;
4507
+ private running;
4508
+ private paused;
4509
+ private consecutiveFailures;
4510
+ private readonly queue;
4511
+ private readonly config;
4512
+ constructor(queue: IQueue, config?: Partial<PollTimerConfig>);
4513
+ setDelegate(delegate: () => Promise<void>): void;
4514
+ start(): void;
4515
+ stop(): void;
4516
+ private tick;
4517
+ private scheduleNext;
4518
+ private scheduleRetry;
4519
+ private scheduleBackpressureRecheck;
4520
+ pause(): void;
4521
+ resume(): void;
4522
+ triggerNow(): void;
4523
+ isPaused(): boolean;
4524
+ isRunning(): boolean;
4525
+ getIntervalMs(): number;
4526
+ setIntervalMs(ms: number): void;
4527
+ }
4528
+ //#endregion
4529
+ //#region src/sync/channels/utils.d.ts
4530
+ /**
4531
+ * Converts a SyncEnvelope containing operations into multiple SyncOperations.
4532
+ *
4533
+ * This function batches operations by documentId, preserving cross-document ordering.
4534
+ * For operations [a1, a2, a3, b1, b2, a4], it returns:
4535
+ * - SyncOperation 1: [a1, a2, a3] for doc-a
4536
+ * - SyncOperation 2: [b1, b2] for doc-b
4537
+ * - SyncOperation 3: [a4] for doc-a
4538
+ *
4539
+ * This ensures operations are grouped for efficient processing while maintaining
4540
+ * causality across documents.
4541
+ */
4542
+ declare function envelopesToSyncOperations(envelope: SyncEnvelope, remoteName: string): SyncOperation[];
4543
+ //#endregion
4544
+ //#region src/sync/utils.d.ts
4545
+ type OperationBatch = {
4546
+ documentId: string;
4547
+ branch: string;
4548
+ scope: string;
4549
+ operations: OperationWithContext$1[];
4550
+ };
4551
+ /**
4552
+ * Trims a mailbox using the ack ordinal.
4553
+ */
4554
+ declare function trimMailboxFromAckOrdinal(mailbox: IMailbox, ackOrdinal: number): void;
4555
+ /**
4556
+ * Batches consecutive operations by documentId and scope, preserving ordering.
4557
+ *
4558
+ * For operations [a1_doc, a1_global, a2_doc, b1_global], this returns:
4559
+ * - Batch 1: [a1_doc] for doc-a, document scope
4560
+ * - Batch 2: [a1_global] for doc-a, global scope
4561
+ * - Batch 3: [a2_doc] for doc-a, document scope
4562
+ * - Batch 4: [b1_global] for doc-b, global scope
4563
+ *
4564
+ * This ensures operations are grouped for efficient processing while maintaining
4565
+ * causality across documents and scopes.
4566
+ */
4567
+ declare function batchOperationsByDocument(operations: OperationWithContext$1[]): OperationBatch[];
4568
+ /**
4569
+ * Merges SyncOperations that share the same (documentId, scope, branch) into
4570
+ * a single SyncOperation per group. Within each group, operations are sorted
4571
+ * by context.ordinal. The merged SyncOperation keeps the first group member's
4572
+ * jobId; all other jobIds are remapped so external dependencies still resolve.
4573
+ */
4574
+ declare function consolidateSyncOperations(syncOps: SyncOperation[]): SyncOperation[];
4575
+ //#endregion
4576
+ //#region src/admin/types.d.ts
4577
+ type KeyframeValidationIssue = {
4578
+ scope: string;
4579
+ branch: string;
4580
+ revision: number;
4581
+ keyframeHash: string;
4582
+ replayedHash: string;
4583
+ };
4584
+ type SnapshotValidationIssue = {
4585
+ scope: string;
4586
+ branch: string;
4587
+ snapshotHash: string;
4588
+ replayedHash: string;
4589
+ };
4590
+ type ValidationResult = {
4591
+ documentId: string;
4592
+ isConsistent: boolean;
4593
+ keyframeIssues: KeyframeValidationIssue[];
4594
+ snapshotIssues: SnapshotValidationIssue[];
4595
+ };
4596
+ type RebuildResult = {
4597
+ documentId: string;
4598
+ keyframesDeleted: number;
4599
+ scopesInvalidated: number;
4600
+ };
4601
+ interface IDocumentIntegrityService {
4602
+ validateDocument(documentId: string, branch?: string, signal?: AbortSignal): Promise<ValidationResult>;
4603
+ rebuildKeyframes(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4604
+ rebuildSnapshots(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4605
+ }
4606
+ //#endregion
4607
+ //#region src/admin/document-integrity-service.d.ts
4608
+ declare class DocumentIntegrityService implements IDocumentIntegrityService {
4609
+ private readonly keyframeStore;
4610
+ private readonly operationStore;
4611
+ private readonly writeCache;
4612
+ private readonly documentView;
4613
+ private readonly documentModelRegistry;
4614
+ constructor(keyframeStore: IKeyframeStore, operationStore: IOperationStore, writeCache: IWriteCache, documentView: IDocumentView, documentModelRegistry: IDocumentModelRegistry);
4615
+ validateDocument(documentId: string, branch?: string, signal?: AbortSignal): Promise<ValidationResult>;
4616
+ rebuildKeyframes(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4617
+ rebuildSnapshots(documentId: string, branch?: string, signal?: AbortSignal): Promise<RebuildResult>;
4618
+ private discoverScopes;
4619
+ }
4620
+ //#endregion
4621
+ //#region src/processors/processor-manager.d.ts
4622
+ /**
4623
+ * Manages processor lifecycle based on operations.
4624
+ * Extends BaseReadModel to receive operations from ReadModelCoordinator.
4625
+ *
4626
+ * Responsibilities:
4627
+ * 1. Detect drive creation from CREATE_DOCUMENT operations
4628
+ * 2. Create processors for each drive using registered factories
4629
+ * 3. Route operations to matching processors based on filters
4630
+ * 4. Clean up processors when drives are deleted or factories are unregistered
4631
+ * 5. Track per-processor cursors for failure recovery and backfill
4632
+ */
4633
+ declare class ProcessorManager extends BaseReadModel implements IProcessorManager$1 {
4634
+ private factoryRegistry;
4635
+ private processorsByDrive;
4636
+ private factoryToProcessors;
4637
+ private knownDrives;
4638
+ private cursorCache;
4639
+ private logger;
4640
+ private driveContainerTypes;
4641
+ constructor(db: Kysely<DocumentViewDatabase>, operationIndex: IOperationIndex, writeCache: IWriteCache, consistencyTracker: IConsistencyTracker, logger: ILogger, driveContainerTypes: ReadonlySet<string>);
4642
+ init(): Promise<void>;
4643
+ protected commitOperations(items: OperationWithContext$1[]): Promise<void>;
4644
+ registerFactory(identifier: string, factory: ProcessorFactory$1): Promise<void>;
4645
+ unregisterFactory(identifier: string): Promise<void>;
4646
+ get(processorId: string): TrackedProcessor$1 | undefined;
4647
+ getAll(): TrackedProcessor$1[];
4648
+ private allTrackedProcessors;
4649
+ private detectAndRegisterNewDrives;
4650
+ private isDriveCreation;
4651
+ private detectAndCleanupDeletedDrives;
4652
+ private discoverExistingDrives;
4653
+ private isDeletedDocumentADrive;
4654
+ private createProcessorsForDrive;
4655
+ private backfillProcessor;
4656
+ private retryProcessor;
4657
+ private cleanupDriveProcessors;
4658
+ private safeDisconnect;
4659
+ private routeOperationsToProcessors;
4660
+ private loadAllCursors;
4661
+ private safeSaveProcessorCursor;
4662
+ private saveProcessorCursor;
4663
+ private deleteProcessorCursors;
4664
+ }
4665
+ //#endregion
4666
+ export { type AtomicTxn, type AttachmentHash, type AttachmentRef, BaseReadModel, type BatchExecutionRequest, type BatchExecutionResult, type BatchLoadRequest, type BatchLoadResult, type CachedSnapshot, type ChannelConfig, ChannelError, ChannelErrorSource, type ChannelHealth, type ChannelMeta, ChannelScheme, type ConnectionState, type ConnectionStateChangeCallback, type ConnectionStateChangedEvent, type ConnectionStateSnapshot, type ConsistencyCoordinate, type ConsistencyKey, type ConsistencyToken, ConsistencyTracker, DEFAULT_DRIVE_CONTAINER_TYPES, type Database, type DeadLetterAddedEvent, DefaultSubscriptionErrorHandler, type DocumentChangeEvent, DocumentChangeType, type DocumentGraphEdge, type DocumentIndexerDatabase, DocumentIntegrityService, DocumentModelRegistry, DocumentModelResolver, type DocumentRelationship, type DocumentRevisions, type DocumentStreamKey, type DocumentViewDatabase, DriveClient, DuplicateManifestError, DuplicateModuleError, DuplicateOperationError, EventBus, EventBusAggregateError, type ExecutionJobPlan, type ExecutorStartedEvent, type ExecutorStoppedEvent, type GqlChannelConfig, GqlRequestChannel, GqlRequestChannelFactory, GqlResponseChannel, GqlResponseChannelFactory, type IChannel, type IChannelFactory, type IConsistencyTracker, type IDocumentGraph, type IDocumentIndexer, type IDocumentIntegrityService, type IDocumentModelLoader, type IDocumentModelRegistry, type IDocumentModelResolver, type IDocumentView, type IDriveClient, type IEventBus, type IJobAwaiter, type IJobExecutor, type IJobExecutorManager, type IJobTracker, type IKeyframeStore, type IOperationIndex, type IOperationStore, type IPollTimer, type IProcessor, type IProcessorHostModule, type IProcessorManager, type IQueue, type IReactor, type IReactorClient, type IReactorSubscriptionManager, type IReadModel, type IReadModelCoordinator, type IRelationalDb, type ISubscriptionErrorHandler, type ISyncCursorStorage, type ISyncManager, type ISyncRemoteStorage, type ISyncStatusTracker, type IWriteCache, SimpleJobExecutor as InMemoryJobExecutor, SimpleJobExecutor, InMemoryJobTracker, InMemoryQueue, type InsertableDocumentSnapshot, IntervalPollTimer, InvalidModuleError, type Job, type JobAvailableEvent, JobAwaiter, type JobCompletedEvent, type JobExecutorConfig, JobExecutorEventTypes, type JobExecutorFactory, type JobFailedEvent, type JobInfo, type JobPendingEvent, type JobReadReadyEvent, type JobResult, type JobRunningEvent, type JobStartedEvent, JobStatus, type JobWriteReadyEvent, type JwtHandler, type KeyframeSnapshot, type KeyframeValidationIssue, KyselyDocumentIndexer, KyselyDocumentView, KyselyKeyframeStore, KyselyOperationStore, KyselySyncCursorStorage, KyselySyncRemoteStorage, KyselyWriteCache, type LoadJobPlan, Mailbox, ModuleNotFoundError, NullDocumentModelResolver, type OperationBatch, type OperationContext, type OperationFilter, type OperationIndexEntry, type OperationTable, type OperationWithContext, OptimisticLockError, type PagedResults, type PagingOptions, type ParsedDriveUrl, type ParsedPaging, PollBehavior, PollingChannelError, type ProcessorApp, type ProcessorFactory, type ProcessorFactoryBuilder, type ProcessorFilter, ProcessorManager, type ProcessorRecord, type ProcessorStatus, PropagationMode, QueueEventTypes, REACTOR_SCHEMA, Reactor, ReactorBuilder, ReactorClient, ReactorClientBuilder, type ReactorClientModule, ReactorEventTypes, type ReactorFeatures, type JobFailedEvent$1 as ReactorJobFailedEvent, type ReactorModule, ReactorSubscriptionManager, ReadModelCoordinator, type ReadModelFactory, type ReadModelFactoryDeps, type RebuildResult, RelationalDbProcessor, RelationshipChangeType, type Remote, type RemoteCursor, type RemoteFilter, type RemoteOptions, type RemoteRecord, type RemoteStatus, RevisionMismatchError, type SearchFilter, type ShutdownStatus, type SignatureVerificationHandler, type SignerConfig, SimpleJobExecutorManager, type SnapshotValidationIssue, type Database$1 as StorageDatabase, type SubscriptionErrorContext, SyncBuilder, type SyncEnvelope, type SyncEnvelopeType, SyncEventTypes, type SyncFailedEvent, type SyncModule, SyncOperation, SyncOperationAggregateError, type SyncOperationErrorType, SyncOperationStatus, type SyncPendingEvent, SyncStatus, type SyncStatusChangeCallback, SyncStatusTracker, type SyncSucceededEvent, type TrackedProcessor, type Unsubscribe, type ValidationResult, type ViewFilter, type WriteCacheConfig, addRelationshipAction, batchOperationsByDocument, consolidateSyncOperations, createDocumentAction, createMutableShutdownStatus, createRelationalDb, deleteDocumentAction, documentActions, driveCollectionId, driveIdFromUrl, envelopesToSyncOperations, getMigrationStatus, makeConsistencyKey, parseDriveUrl, parsePagingOptions, removeRelationshipAction, runMigrations, trimMailboxFromAckOrdinal, updateRelationshipAction, upgradeDocumentAction };
4667
+ //# sourceMappingURL=index.d.ts.map