@powerhousedao/reactor 6.0.2-staging.2 → 6.0.2-staging.4

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