@powerhousedao/reactor 6.0.0-dev.14 → 6.0.0-dev.141

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