@powerhousedao/reactor 6.0.0-dev.105 → 6.0.0-dev.107

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