@powerhousedao/reactor-hypercore 6.2.3-dev.5 → 6.2.3-dev.51
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.
- package/dist/index.d.ts +78 -63
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +117 -26
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { Operation, OperationWithContext } from "@powerhousedao/shared/document-model";
|
|
2
|
+
import "@powerhousedao/shared/document-model/errors";
|
|
3
|
+
import "document-model";
|
|
4
|
+
import "@powerhousedao/shared/document-drive";
|
|
5
|
+
import "@powerhousedao/shared/processors";
|
|
2
6
|
import Hyperbee from "hyperbee";
|
|
3
|
-
|
|
7
|
+
import "node:worker_threads";
|
|
4
8
|
//#region ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.d.ts
|
|
5
9
|
declare global {
|
|
6
10
|
interface AsyncDisposable {}
|
|
@@ -8,41 +12,8 @@ declare global {
|
|
|
8
12
|
readonly asyncDispose: unique symbol;
|
|
9
13
|
}
|
|
10
14
|
}
|
|
11
|
-
/**
|
|
12
|
-
* The main Kysely class.
|
|
13
|
-
*
|
|
14
|
-
* You should create one instance of `Kysely` per database using the {@link Kysely}
|
|
15
|
-
* constructor. Each `Kysely` instance maintains its own connection pool.
|
|
16
|
-
*
|
|
17
|
-
* ### Examples
|
|
18
|
-
*
|
|
19
|
-
* This example assumes your database has a "person" table:
|
|
20
|
-
*
|
|
21
|
-
* ```ts
|
|
22
|
-
* import * as Sqlite from 'better-sqlite3'
|
|
23
|
-
* import { type Generated, Kysely, SqliteDialect } from 'kysely'
|
|
24
|
-
*
|
|
25
|
-
* interface Database {
|
|
26
|
-
* person: {
|
|
27
|
-
* id: Generated<number>
|
|
28
|
-
* first_name: string
|
|
29
|
-
* last_name: string | null
|
|
30
|
-
* }
|
|
31
|
-
* }
|
|
32
|
-
*
|
|
33
|
-
* const db = new Kysely<Database>({
|
|
34
|
-
* dialect: new SqliteDialect({
|
|
35
|
-
* database: new Sqlite(':memory:'),
|
|
36
|
-
* })
|
|
37
|
-
* })
|
|
38
|
-
* ```
|
|
39
|
-
*
|
|
40
|
-
* @typeParam DB - The database interface type. Keys of this type must be table names
|
|
41
|
-
* in the database and values must be interfaces that describe the rows in those
|
|
42
|
-
* tables. See the examples above.
|
|
43
|
-
*/
|
|
44
15
|
//#endregion
|
|
45
|
-
//#region ../reactor/dist/index.d.ts
|
|
16
|
+
//#region ../reactor/dist/index-dDm0fUBT.d.ts
|
|
46
17
|
/**
|
|
47
18
|
* Describes the options for paging.
|
|
48
19
|
*/
|
|
@@ -58,11 +29,7 @@ type PagedResults<T> = {
|
|
|
58
29
|
options: PagingOptions;
|
|
59
30
|
next?: () => Promise<PagedResults<T>>;
|
|
60
31
|
nextCursor?: string;
|
|
61
|
-
totalCount?: number;
|
|
62
32
|
};
|
|
63
|
-
/**
|
|
64
|
-
* A string key in the format `documentId:scope:branch` used to identify a consistency checkpoint.
|
|
65
|
-
*/
|
|
66
33
|
/**
|
|
67
34
|
* One read-set stream and the highest operation index observed on it, or -1
|
|
68
35
|
* if it was observed empty.
|
|
@@ -80,7 +47,6 @@ type AppendConditionStream = {
|
|
|
80
47
|
type AppendCondition = {
|
|
81
48
|
streams: AppendConditionStream[];
|
|
82
49
|
};
|
|
83
|
-
/** Error history keeps messages, not classes, so failures match by prefix. */
|
|
84
50
|
/**
|
|
85
51
|
* A write transaction passed to {@link IOperationStore.apply}. Accumulates
|
|
86
52
|
* operations that are committed atomically when the callback returns.
|
|
@@ -94,7 +60,9 @@ interface AtomicTxn {
|
|
|
94
60
|
* revision field and lastModified timestamp.
|
|
95
61
|
*/
|
|
96
62
|
type DocumentRevisions = {
|
|
97
|
-
/** Map of scope to operation index for that scope */
|
|
63
|
+
/** Map of scope to operation index for that scope */
|
|
64
|
+
revision: Record<string, number>;
|
|
65
|
+
/** The largest operation timestamp in the document, across every scope. */
|
|
98
66
|
latestTimestamp: string;
|
|
99
67
|
};
|
|
100
68
|
/**
|
|
@@ -136,6 +104,16 @@ interface IOperationStore {
|
|
|
136
104
|
* Returns operations for a document/scope/branch whose index is greater
|
|
137
105
|
* than the given revision.
|
|
138
106
|
*
|
|
107
|
+
* `paging.cursor` is opaque to callers: treat it only as the value
|
|
108
|
+
* returned in `nextCursor` from a previous page, never construct or
|
|
109
|
+
* interpret it directly. An implementation must never emit a `nextCursor`
|
|
110
|
+
* equal to the start-of-stream sentinel ("0"), since a caller that walks
|
|
111
|
+
* `nextCursor` to exhaustion would read that as "start over" and loop
|
|
112
|
+
* forever. The reference encoding (used by the Kysely and Hypercore
|
|
113
|
+
* stores) is the index to resume from, i.e. the last returned row's index
|
|
114
|
+
* plus one, so a page that happens to end at index 0 still produces a
|
|
115
|
+
* cursor distinguishable from the start sentinel.
|
|
116
|
+
*
|
|
139
117
|
* @param documentId - The document id
|
|
140
118
|
* @param scope - The operation scope
|
|
141
119
|
* @param branch - The branch name
|
|
@@ -158,6 +136,16 @@ interface IOperationStore {
|
|
|
158
136
|
/**
|
|
159
137
|
* Gets operations that may conflict with incoming operations during a load.
|
|
160
138
|
*
|
|
139
|
+
* `paging.cursor` is opaque to callers: treat it only as the value
|
|
140
|
+
* returned in `nextCursor` from a previous page, never construct or
|
|
141
|
+
* interpret it directly. An implementation must never emit a `nextCursor`
|
|
142
|
+
* equal to the start-of-stream sentinel ("0"), since a caller that walks
|
|
143
|
+
* `nextCursor` to exhaustion would read that as "start over" and loop
|
|
144
|
+
* forever. The reference encoding (used by the Kysely and Hypercore
|
|
145
|
+
* stores) is the index to resume from, i.e. the last returned row's index
|
|
146
|
+
* plus one, so a page that happens to end at index 0 still produces a
|
|
147
|
+
* cursor distinguishable from the start sentinel.
|
|
148
|
+
*
|
|
161
149
|
* @param documentId - The document id
|
|
162
150
|
* @param scope - The scope to query
|
|
163
151
|
* @param branch - The branch name
|
|
@@ -188,11 +176,14 @@ interface IOperationStore {
|
|
|
188
176
|
* timestamp, so a later timestamp can sit behind the last row.
|
|
189
177
|
*/
|
|
190
178
|
getStreamLatestTimestamp(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
179
|
+
/**
|
|
180
|
+
* The subset of `opIds` stored anywhere in one stream, retracted rows
|
|
181
|
+
* included.
|
|
182
|
+
*/
|
|
183
|
+
findOperationIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Set<string>>;
|
|
184
|
+
/** The latest row of each of `opIds` stored in one stream. */
|
|
185
|
+
getOperationsByIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Operation[]>;
|
|
191
186
|
}
|
|
192
|
-
/**
|
|
193
|
-
* Stores periodic document snapshots (keyframes) so that document state
|
|
194
|
-
* can be reconstructed without replaying the full operation history.
|
|
195
|
-
*/
|
|
196
187
|
/**
|
|
197
188
|
* Filter options for querying operations. When multiple filters are provided,
|
|
198
189
|
* they are combined with AND logic.
|
|
@@ -207,12 +198,9 @@ interface OperationFilter {
|
|
|
207
198
|
/** Filter operations with index >= this value */
|
|
208
199
|
sinceRevision?: number;
|
|
209
200
|
}
|
|
210
|
-
/**
|
|
211
|
-
* Which sense of "exists" a caller of {@link IDocumentView.exists} means.
|
|
212
|
-
*/
|
|
213
201
|
//#endregion
|
|
214
202
|
//#region src/hypercore-operation-store.d.ts
|
|
215
|
-
declare class HypercoreOperationStore implements IOperationStore {
|
|
203
|
+
export declare class HypercoreOperationStore implements IOperationStore {
|
|
216
204
|
private bee;
|
|
217
205
|
private applyLock;
|
|
218
206
|
constructor(bee: Hyperbee);
|
|
@@ -220,9 +208,33 @@ declare class HypercoreOperationStore implements IOperationStore {
|
|
|
220
208
|
/** Throws if any read-set stream has grown past its recorded revision. */
|
|
221
209
|
private assertConditionHolds;
|
|
222
210
|
private executeApply;
|
|
211
|
+
/** A purge marker is written to document/main whichever branch it erases. */
|
|
212
|
+
private purgeMarkerAtHead;
|
|
223
213
|
private isCreate;
|
|
214
|
+
/**
|
|
215
|
+
* The paging cursor encodes the index to resume from (one past the last
|
|
216
|
+
* row returned), not the last row's own index; "" or "0" (or anything
|
|
217
|
+
* unparsable) means the start of the stream. This keeps "0" an unambiguous
|
|
218
|
+
* start-of-stream sentinel even when a page ends at index 0, which would
|
|
219
|
+
* otherwise make `nextCursor` equal the start cursor and loop a caller that
|
|
220
|
+
* walks pages forever. Mirrors the encoding in the Kysely store.
|
|
221
|
+
*/
|
|
224
222
|
getSince(documentId: string, scope: string, branch: string, revision: number, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
|
|
223
|
+
/**
|
|
224
|
+
* The paging cursor encodes the ordinal to resume from (one past the last
|
|
225
|
+
* ordinal returned), not the last ordinal itself; "" or "0" (or anything
|
|
226
|
+
* unparsable) means the start of the stream. Unlike the Kysely store's
|
|
227
|
+
* `getSinceId` (whose auto-increment id starts at 1), this store's ordinal
|
|
228
|
+
* counter starts at 0, so 0 is a real, valid ordinal and the same
|
|
229
|
+
* ambiguous-cursor hazard as `getSince`/`getConflicting` applies here too.
|
|
230
|
+
*/
|
|
225
231
|
getSinceId(id: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext>>;
|
|
232
|
+
/**
|
|
233
|
+
* The paging cursor here encodes the index to resume from (one past the
|
|
234
|
+
* last row returned), not the last row's own index, for the same reason as
|
|
235
|
+
* `getSince`: a page ending at index 0 must not produce a cursor that is
|
|
236
|
+
* indistinguishable from the start-of-stream sentinel.
|
|
237
|
+
*/
|
|
226
238
|
getConflicting(documentId: string, scope: string, branch: string, minTimestamp: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
|
|
227
239
|
getRevisions(documentId: string, branch: string, signal?: AbortSignal): Promise<DocumentRevisions>;
|
|
228
240
|
/**
|
|
@@ -231,6 +243,8 @@ declare class HypercoreOperationStore implements IOperationStore {
|
|
|
231
243
|
* later one, so it would under-report and admit a backdated auth write.
|
|
232
244
|
*/
|
|
233
245
|
getStreamLatestTimestamp(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
246
|
+
findOperationIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Set<string>>;
|
|
247
|
+
getOperationsByIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Operation[]>;
|
|
234
248
|
private serializeOperation;
|
|
235
249
|
private toOperation;
|
|
236
250
|
}
|
|
@@ -247,7 +261,7 @@ type HypercoreStoreOptions = {
|
|
|
247
261
|
};
|
|
248
262
|
//#endregion
|
|
249
263
|
//#region src/hypercore-atomic-transaction.d.ts
|
|
250
|
-
declare class HypercoreAtomicTransaction implements AtomicTxn {
|
|
264
|
+
export declare class HypercoreAtomicTransaction implements AtomicTxn {
|
|
251
265
|
private documentId;
|
|
252
266
|
private documentType;
|
|
253
267
|
private scope;
|
|
@@ -259,7 +273,7 @@ declare class HypercoreAtomicTransaction implements AtomicTxn {
|
|
|
259
273
|
}
|
|
260
274
|
//#endregion
|
|
261
275
|
//#region src/storage-manager.d.ts
|
|
262
|
-
declare class StorageManager {
|
|
276
|
+
export declare class StorageManager {
|
|
263
277
|
private store;
|
|
264
278
|
private bee;
|
|
265
279
|
constructor(storagePath: string);
|
|
@@ -269,23 +283,23 @@ declare class StorageManager {
|
|
|
269
283
|
}
|
|
270
284
|
//#endregion
|
|
271
285
|
//#region src/key-encoding.d.ts
|
|
272
|
-
declare const RANGE_UPPER_BOUND: string;
|
|
273
|
-
declare function pad(n: number): string;
|
|
274
|
-
declare function operationKey(documentId: string, scope: string, branch: string, index: number): string;
|
|
275
|
-
declare function operationPrefix(documentId: string, scope: string, branch: string): string;
|
|
276
|
-
declare function ordinalKey(ordinal: number): string;
|
|
277
|
-
declare function ordinalPrefix(): string;
|
|
278
|
-
declare function duplicateKey(opId: string, index: number, skip: number): string;
|
|
279
|
-
declare function headKey(documentId: string, scope: string, branch: string): string;
|
|
280
|
-
declare function headPrefix(documentId: string): string;
|
|
281
|
-
declare const ORDINAL_COUNTER_KEY = "_meta/ordinal";
|
|
286
|
+
export declare const RANGE_UPPER_BOUND: string;
|
|
287
|
+
export declare function pad(n: number): string;
|
|
288
|
+
export declare function operationKey(documentId: string, scope: string, branch: string, index: number): string;
|
|
289
|
+
export declare function operationPrefix(documentId: string, scope: string, branch: string): string;
|
|
290
|
+
export declare function ordinalKey(ordinal: number): string;
|
|
291
|
+
export declare function ordinalPrefix(): string;
|
|
292
|
+
export declare function duplicateKey(opId: string, index: number, skip: number): string;
|
|
293
|
+
export declare function headKey(documentId: string, scope: string, branch: string): string;
|
|
294
|
+
export declare function headPrefix(documentId: string): string;
|
|
295
|
+
export declare const ORDINAL_COUNTER_KEY = "_meta/ordinal";
|
|
282
296
|
type ParsedOperationKey = {
|
|
283
297
|
documentId: string;
|
|
284
298
|
scope: string;
|
|
285
299
|
branch: string;
|
|
286
300
|
index: number;
|
|
287
301
|
};
|
|
288
|
-
declare function parseOperationKey(key: string): ParsedOperationKey;
|
|
302
|
+
export declare function parseOperationKey(key: string): ParsedOperationKey;
|
|
289
303
|
type OrdinalEntry = {
|
|
290
304
|
documentId: string;
|
|
291
305
|
documentType: string;
|
|
@@ -299,5 +313,6 @@ type HeadEntryValue = {
|
|
|
299
313
|
latestTimestampUtcMs: string;
|
|
300
314
|
};
|
|
301
315
|
//#endregion
|
|
302
|
-
export {
|
|
316
|
+
export type { HeadEntryValue, HypercoreStoreOptions, OrdinalEntry, ParsedOperationKey, StoredOperation };
|
|
317
|
+
export {};
|
|
303
318
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["Dialect","SchemaModule","DynamicModule","QueryExecutor","QueryCreator","KyselyPlugin","DatabaseIntrospector","Driver","IsolationLevel","AccessMode","FunctionModule","LogConfig","QueryExecutorProvider","QueryResult","CompiledQuery","QueryId","Compilable","CaseBuilder","Expression","DrainOuterGeneric","ReleaseSavepoint","RollbackToSavepoint","ControlledConnection","_0","global","AsyncDisposable","SymbolConstructor","asyncDispose","sideEffect","Kysely","V","T","R","DB","KyselyConfig","KyselyProps","TransactionBuilder","ControlledTransactionBuilder","ConnectionBuilder","Record","Promise","Symbol","private","constructor","args","schema","dynamic","introspection","case","value","fn","transaction","startTransaction","connection","withPlugin","plugin","withoutPlugins","withSchema","withTables","destroy","isTransaction","getExecutor","executeQuery","query","queryId","Transaction","props","config","driver","executor","dialect","isKyselyProps","obj","plugins","log","ConnectionBuilderProps","execute","db","callback","TransactionBuilderProps","setAccessMode","accessMode","setIsolationLevel","isolationLevel","trx","ControlledTransaction","SN","S","ControlledTransactionProps","Command","isCommitted","isRolledBack","commit","rollback","savepoint","savepointName","rollbackToSavepoint","releaseSavepoint","cb","Action","AuthRequest","AuthSubject","CreateDocumentActionInput","DocumentModelModule","ISigner","Operation","OperationContext","OperationWithContext","OperationWithContext$1","PHAuthState","PHDocument","PHDocumentState","SignatureVerificationHandler","UpgradeDocumentActionInput","UpgradeManifest","UpgradeReducer","UpgradeTransition","actions","documentActions","DocumentDriveDocument","DriveInput","FolderNode","Node","ILogger","kysely","Generated","Insertable","Kysely","Transaction","IProcessor","IProcessorHostModuleBase","IProcessorHostModuleBase$1","IProcessorManager","IProcessorManager$1","IRelationalDb","ProcessorApp","ProcessorFactory","ProcessorFactory$1","ProcessorFactoryBuilder","ProcessorFilter","ProcessorRecord","ProcessorStatus","RelationalDbProcessor","TrackedProcessor","TrackedProcessor$1","createRelationalDb","Pool","AttachmentHash","AttachmentRef","createDocumentAction","input","upgradeDocumentAction","deleteDocumentAction","documentId","addRelationshipAction","Record","sourceId","targetId","relationshipType","metadata","updateRelationshipAction","removeRelationshipAction","JobKind","JobQueueState","UNKNOWN","PREPROCESSING","PENDING","READY","RUNNING","RESOLVED","RetryAccounting","CountAgainstLimit","ExemptFromLimit","IJobExecutionHandle","Job","ErrorInfo$1","job","state","start","complete","fail","error","defer","JobMeta","id","kind","scope","branch","operations","createdAt","queueHint","retryCount","maxRetries","lastError","errorHistory","meta","QueueEventTypes","JOB_AVAILABLE","JobRoutingMeta","JobAvailableEvent","jobId","name","message","stack","ShutdownStatus","Promise","isShutdown","completed","PropagationMode","None","Cascade","RelationshipChangeType","Added","Removed","BatchMeta","batchId","batchJobIds","JobInfo","JobStatus","ConsistencyToken","status","createdAtUtcIso","completedAtUtcIso","result","consistencyToken","WRITE_READY","READ_READY","FAILED","ViewFilter","scopes","revision","subject","SearchFilter","type","parentId","ids","slugs","PagingOptions","cursor","limit","PagedResults","T","results","options","next","nextCursor","totalCount","ConsistencyKey","ConsistencyCoordinate","operationIndex","version","coordinates","IReadModel","indexOperations","IReadModelCoordinator","readModels","stop","drain","getChainDepth","ReadModelRegistrationStage","ILiveReadModelCoordinator","addReadModel","readModel","stage","supportsLiveReadModelRegistration","coordinator","ChannelScheme","CONNECT","SWITCHBOARD","JwtHandler","url","PollBehavior","Auto","Manual","RemoteOptions","sinceTimestampUtcMs","pollBehavior","boundAddress","RemoteFilter","RemoteCursor","remoteName","cursorType","cursorOrdinal","lastSyncedAtUtcMs","ChannelMeta","SyncEnvelopeType","SyncEnvelope","channelMeta","key","dependsOn","SyncOperationStatus","Unknown","TransportPending","ExecutionPending","Applied","Error","ChannelErrorSource","Channel","Inbox","Outbox","SyncOperationErrorType","ChannelHealth","lastSuccessUtcMs","lastFailureUtcMs","failureCount","ConnectionState","ConnectionStateSnapshot","pushBlocked","pushFailureCount","receivingPages","requiresAuth","ConnectionStateChangedEvent","remoteId","previous","current","snapshot","RemoteStatus","push","pull","ChannelConfig","parameters","RemoteRecord","DriveCollectionId","collectionId","channelConfig","filter","SyncEventTypes","SYNC_PENDING","SYNC_SUCCEEDED","SYNC_FAILED","DEAD_LETTER_ADDED","CONNECTION_STATE_CHANGED","SyncPendingEvent","syncOperationCount","remoteNames","SyncSucceededEvent","SyncFailedEvent","Array","successCount","errors","DeadLetterAddedEvent","errorSource","errorType","SyncResultStatus","SyncResultError","SyncResult","DuplicateOperationError","constructor","description","OptimisticLockError","RevisionMismatchError","expected","actual","DocumentAlreadyExistsError","headRevision","isError","AppendConditionStream","AppendCondition","streams","APPEND_CONDITION_FAILED_PREFIX","AppendConditionFailedError","condition","isFailureMessage","AtomicTxn","addOperations","DocumentRevisions","latestTimestamp","IOperationStore","AbortSignal","OperationFilter","apply","documentType","txn","fn","signal","getSince","paging","getSinceId","getConflicting","minTimestamp","getRevisions","getStreamLatestTimestamp","IKeyframeStore","putKeyframe","document","findNearestKeyframe","targetRevision","listKeyframes","deleteKeyframes","ViewFilter$1","excludeSourceRemote","actionTypes","timestampFrom","timestampTo","sinceRevision","DocumentExistence","LiveOnly","IncludingDeleted","IDocumentView","TDocument","init","items","waitForConsistency","token","timeoutMs","exists","documentIds","existence","get","view","getMany","getByIdOrSlug","identifier","findByType","resolveSlug","slug","resolveSlugs","resolveIdOrSlug","DocumentRelationship","Date","updatedAt","DocumentGraphEdge","from","to","IDocumentGraph","nodes","edges","IDocumentIndexer","getOutgoing","types","getIncoming","hasRelationship","getUndirectedRelationships","a","b","getDirectedRelationships","findPath","findAncestors","getOrphanedChildren","parentIds","getRelationshipTypes","ISyncRemoteStorage","list","upsert","remote","remove","ISyncCursorStorage","DeadLetterRecord","jobDependencies","errorMessage","ISyncDeadLetterStorage","add","deadLetter","removeByRemote","listQuarantinedDocumentIds","OperationIndexEntry","ordinal","sourceRemote","IOperationIndexTxn","createCollection","addToCollection","removeFromCollection","recordGroupReferences","groupIds","write","getMembershipInvalidations","IOperationIndex","commit","find","getSinceOrdinal","getLatestTimestampForCollection","getCollectionsForDocuments","getGroupReferencers","groupId","driveId","forDrive","fromKey","toString","equals","other","WriteCacheConfig","maxDocuments","ringBufferSize","keyframeInterval","DocumentStreamKey","SnapshotPosition","Head","Historical","CachedSnapshot","position","KeyframeSnapshot","IWriteCache","getState","putState","putRun","run","invalidate","clear","startup","shutdown","Unsubscribe","Subscriber","data","EventBusAggregateError","ReactorEventTypes","JOB_PENDING","JOB_RUNNING","JOB_WRITE_READY","JOB_READ_READY","JOB_FAILED","READMODEL_BATCH_COMPLETED","READMODEL_INDEXED","MODEL_LOADED","ReadModelStage","ReadModelIndexingStage","ModelLoadedEvent","JobPendingEvent","jobMeta","JobRunningEvent","JobWriteReadyEvent","collectionMemberships","JobReadReadyEvent","JobFailedEvent$1","ReadModelBatchCompletedEvent","batchSize","chainWaitDurationMs","preReadyDurationMs","emitDurationMs","postReadyDurationMs","ReadModelIndexedEvent","readModelName","durationMs","operationCount","success","IEventBus","K","subscribe","event","subscriber","emit","IJobAwaiter","waitForJob","JobAwaiter","eventBus","getJobStatus","pendingJobs","unsubscribers","subscribeToEvents","handleWriteReady","handleReadReady","handleJobFailed","checkAndResolveWaiters","ISubscriptionErrorHandler","SubscriptionErrorContext","handleError","context","eventType","subscriptionId","eventData","IReactorSubscriptionManager","onDocumentCreated","callback","search","onDocumentDeleted","onDocumentStateUpdated","onRelationshipChanged","childId","changeType","StreamQuery","IStreamStateReader","DecisionTarget","DecisionContext","scopeState","actionInput","StreamHistory","Projection","M","Partial","query","model","queryOverHistory","reads","decidingActions","operation","Evaluation","decision","reason","DecisionModel","projections","foldEvaluatedScope","evaluatesScope","decide","request","ctx","BuiltDecisionModel","appendCondition","DocumentChangeType","Created","Deleted","Updated","ParentAdded","ParentRemoved","ChildAdded","ChildRemoved","DocumentChangeEvent","documents","CreateDocumentOptions","parentIdentifier","documentModelVersion","UpgradeDocumentOptions","maxConflictRetries","IDriveClient","create","addFile","driveIdentifier","parentFolder","addFolder","removeNode","nodeId","renameNode","setPreferredEditorOnNode","preferredEditor","moveNode","srcNodeId","targetParentFolderId","copyNode","getNode","listNodes","ActionCandidate","ActionEvaluations","evaluations","allAllowed","anyAllowed","allDenied","anyDenied","IReactorClient","BatchExecutionRequest","BatchExecutionResult","BatchLoadRequest","BatchLoadResult","drives","getDocumentModelModules","namespace","getDocumentModelModule","isDocumentIdTaken","getOperations","documentIdentifier","getOutgoingRelationships","sourceIdentifier","getIncomingRelationships","targetIdentifier","evaluateActions","candidates","createEmpty","documentModelType","getDocumentModelModuleForDocument","upgradeDocument","toVersion","createDocumentInDrive","execute","executeAsync","executeBatch","rename","setPreferredEditor","addRelationship","removeRelationship","moveRelationship","sourceParentIdentifier","targetParentIdentifier","source","target","deleteDocument","propagate","deleteDocuments","identifiers","loadBatch","ICollectionMembershipCache","CachedDocumentMeta","documentScopeRevision","IDocumentMetaCache","getDocumentMeta","rebuildAtRevision","putDocumentMeta","OperationTable","opId","prevOpId","writeTimestampUtcMs","timestampUtcMs","index","action","skip","deniedReason","hash","KeyframeTable","DocumentCollectionTable","joinedOrdinal","leftOrdinal","OperationIndexOperationTable","SyncRemoteTable","collection_id","channel_type","channel_id","remote_name","channel_parameters","filter_document_ids","filter_scopes","filter_branch","push_state","push_last_success_utc_ms","push_last_failure_utc_ms","push_failure_count","pull_state","pull_last_success_utc_ms","pull_last_failure_utc_ms","pull_failure_count","bound_address","created_at","updated_at","SyncCursorTable","cursor_type","cursor_ordinal","last_synced_at_utc_ms","SyncDeadLetterTable","job_id","job_dependencies","document_id","error_source","error_message","error_type","GroupReferenceTable","Database$1","Keyframe","document_collections","operation_index_operations","group_references","sync_remotes","sync_cursors","sync_dead_letters","DocumentTable","DocumentRelationshipTable","IndexerStateTable","lastOperationId","lastOperationTimestamp","DocumentIndexerDatabase","Document","IndexerState","SanitizedArg","ErrorInfo","cause","ModuleRef","packageName","exportName","filePath","FactorySpec","module","initArgs","SignatureVerifierSpec","DocumentModelSpec","ModelManifestEntry","spec","DbConfig","host","port","database","user","password","ssl","applicationName","poolSize","connectionTimeoutMillis","idleTimeoutMillis","WorkerPoolConfig","enabled","numWorkers","workerType","heartbeatMs","workerPgPoolSize","JobWriteReadyPayload","InitMessage","JobExecutorConfig","correlationId","workerId","poolConfig","db","signatureVerifier","models","executorConfig","ExecuteMessage","AbortMessage","targetCorrelationId","ShutdownMessage","graceMs","LoadModelMessage","ParentMessage","ReadyMessage","ResultMessage","JobResult","writeReady","ModelLoadedMessage","ModelLoadFailedMessage","LogMessage","level","args","timestamp","HeartbeatMessage","inFlightCorrelationIds","MetricsMessage","counters","gauges","PoolAcquireSamplesMessage","poolName","durations","size","idle","waiting","WorkerMessage","FileModelSource","PackageModelSource","subpath","DocumentModelSource","RegistrationResult","item","IDocumentModelLoader","load","IDocumentModelRegistry","registerModules","modules","unregisterModules","documentTypes","getModule","getAllModules","getSupportedVersions","getLatestVersion","registerUpgradeManifests","manifests","unregisterUpgradeManifests","getUpgradeManifest","computeUpgradePath","fromVersion","getUpgradeReducer","RingBuffer","buffer","head","capacity","getAll","length","DocumentStream","ringBuffer","KyselyWriteCache","lruTracker","keyframeStore","operationStore","registry","config","withScopedStores","store","persistKeyframe","getStream","coldMissRebuild","applyPendingUpgrades","applyTailPendingUpgrades","applyPendingUpgrade","stampRevisions","operationAt","resolveModuleVersionForOp","warmMissRebuild","findNearestOlderSnapshot","makeStreamKey","getOrCreateStream","isKeyframeRevision","KyselyOperationStore","trx","queryExecutor","withTransaction","resolveUniqueConstraint","executeApply","acquireStreamLocks","insertGuarded","findIdempotentReplay","isCreate","rowToOperation","rowToOperationWithContext","KyselyKeyframeStore","ExecutionStores","writeCache","documentMetaCache","collectionMembershipCache","IExecutionScope","stores","operationsWithContext","completedAt","duration","ReactorFeatureFlags","documentDecisions","authEnforcement","authGroups","authConditions","featureFlags","maxSkipThreshold","maxConcurrency","jobTimeoutMs","deferredJobTtlMs","retryBaseDelayMs","retryMaxDelayMs","yieldDeadlineMs","batchApplies","JobExecutorEventTypes","JOB_STARTED","JOB_COMPLETED","EXECUTOR_STARTED","EXECUTOR_STOPPED","JobStartedEvent","startedAt","JobCompletedEvent","JobFailedEvent","willRetry","ExecutorStartedEvent","ExecutorStoppedEvent","stoppedAt","graceful","ExecutorManagerStatus","isRunning","numExecutors","activeJobs","totalJobsProcessed","DocumentDecisionModel","documentDecisionModel","RegisteredDecisionModel","AdmissionDecision","evaluation","documentVersion","deletedAtUtcIso","AdmissionConditions","carriedDocument","decideAtHead","cache","conditions","selectDecisionModel","flags","ALWAYS_READABLE_SCOPES","ReadonlySet","ReadGateOptions","withholdUninitialized","IReadGate","scopePredicate","readDecisionModel","BareReadGate","SeededStateReader","documentView","seed","assertAbsent","ModelReadGate","servesGroups","logger","servesGroupTo","servesThrough","servesGroup","ownPolicyPredicate","ActionEvaluationConfig","ReactorClient","IReactor","reactor","signer","subscriptionManager","jobAwaiter","documentIndexer","readGate","actionEvaluation","readSubject","readableScopes","gateDocument","getOperationsWithCompositeCursor","buildEvaluationTarget","removeAllIncomingRelationships","WorkerInFlightSnapshot","WorkerExecutionOutcome","IExecutorWorker","abort","loadModel","entry","isIdle","getInFlight","IJobExecutor","executeJob","IJobExecutorManager","getExecutors","getStatus","IJobTracker","registerJob","jobInfo","markRunning","markFailed","IQueue","enqueue","dequeue","dequeueNext","dequeueNextMatching","predicate","totalSize","clearAll","hasJobs","completeJob","failJob","retryJob","accounting","isDrained","block","onDrained","unblock","GroupReevaluationTrigger","queue","unsubscribe","onWriteReady","ViewStateTable","readModelId","lastOrdinal","DocumentSnapshotTable","content","lastOperationIndex","lastOperationHash","lastUpdatedAt","snapshotVersion","isDeleted","deletedAt","SlugMappingTable","ProcessorCursorTable","processorId","factoryId","processorIndex","lastErrorTimestamp","DocumentViewDatabase","ViewState","DocumentSnapshot","SlugMapping","ProcessorCursor","InsertableDocumentSnapshot","IConsistencyTracker","update","getLatest","waitFor","serialize","hydrate","entries","makeConsistencyKey","ConsistencyTracker","waiters","deduplicateCoordinates","areCoordinatesSatisfied","checkWaiters","removeWaiter","PoolStats","PoolInstrumentation","getStats","onAcquire","listener","instrumentPgPool","pool","ForwardingPoolInstrumentation","pushSamples","updateStats","stats","GraphQLRequestErrorCategory","GraphQLRequestError","statusCode","category","codes","RECOVERABLE_GRAPHQL_ERROR_CODES","malformedStoredOperation","isRecoverableGraphQLError","DRIVE_AUTH_ERROR_MESSAGES","forbidden","authenticationRequired","DriveRequestError","isDriveAuthError","PollingChannelError","ChannelError","SyncOperationStatusCallback","SyncOperation","syncOp","prev","SyncOperationAggregateError","deliveredCount","emittedCount","callbacks","on","started","transported","executed","failed","transition","MailboxCallback","IMailbox","ReadonlyArray","ackOrdinal","latestOrdinal","advanceOrdinal","onAdded","onRemoved","pause","resume","flush","isPaused","Mailbox","itemsMap","addedCallbacks","removedCallbacks","paused","addedBuffer","removedBuffer","_ack","_latestOrdinal","SyncStatus","Synced","Outgoing","Incoming","OutgoingAndIncoming","SyncStatusChangeCallback","ISyncStatusTracker","IChannel","onChange","trackRemote","channel","untrackRemote","SyncStatusTracker","remotes","seen","handleAdded","handleRemoved","getOrCreateCounts","notifyChange","ConnectionStateChangeCallback","inbox","outbox","getConnectionState","onConnectionStateChange","triggerPull","notePoll","lastHolderPollUtcMs","IChannelFactory","instance","cursorStorage","RemoteMeta","Remote","ISyncManager","getByName","getById","bindRemote","waitForSync","getSyncStatus","onSyncStatusChange","ExecutionJobPlan","jobs","LoadJobPlan","externalDeps","kill","getDocumentModels","getBySlug","docId","ReactorFeatures","Database","SyncModule","syncManager","InProcessSyncModule","remoteStorage","deadLetterStorage","channelFactory","ReactorModule","documentModelRegistry","syncModule","DegradedComponent","component","InProcessReactorModule","jobTracker","executorManager","documentViewConsistencyTracker","documentIndexerConsistencyTracker","readModelCoordinator","processorManager","processorManagerConsistencyTracker","groupReevaluationTrigger","pools","degradedComponents","ReactorClientModule","client","reactorModule","InProcessReactorClientModule","DriveClient","runJobs","toError","documentExists","removeFileNode","IDocumentModelResolver","ensureModelLoaded","ModelLoadedBroadcastHook","DocumentModelResolver","loader","loadingModels","failedModelTypes","broadcastHook","modelLoadedHook","setBroadcastHook","hook","setModelLoadedHook","loadRegisterAndBroadcast","notifyPeersModelLoaded","NullDocumentModelResolver","WorkerFactory","BuiltInReadModelKind","ChainDepthReport","shardId","depth","ProjectionInitMessage","shardIndex","shardCount","preReadyKinds","postReadyKinds","chainDepthReportIntervalMs","ProjectionWriteReadyMessage","ProjectionDrainMessage","ProjectionShutdownMessage","ProjectionParentMessage","ProjectionReadyMessage","ProjectionInitFailedMessage","ProjectionReadReadyMessage","ProjectionReadModelIndexedMessage","ProjectionBatchCompletedMessage","ProjectionChainDepthMessage","ProjectionPoolAcquireSamplesMessage","ProjectionDrainedMessage","ProjectionLogMessage","ProjectionWorkerMessage","HybridProjectionOptions","onFatal","initTimeoutMs","shutdownGraceMs","drainTimeoutMs","createHybridProjectionCoordinatorFactory","ReadModelCoordinatorFactory","ProjectionTransportEventMap","exit","ProjectionTransportEvent","ProjectionTransportListener","E","payload","IProjectionTransport","postMessage","off","terminate","ProjectionWorkerFactory","ProjectionShardHooks","onReadReady","onShardFatal","ProjectionShardManagerConfig","factory","hostBus","poolInstrumentations","consistencyTrackers","ProjectionShardManager","shards","initPromises","pendingDrains","trackersByReadModelName","hostSubscription","isShuttingDown","emitReadReady","getShardDepths","routeWriteReady","dropWriteReady","handleWorkerMessage","advanceConsistencyTrackers","handlePoolAcquireSamples","failPendingInit","handleReady","handleDrained","releaseDrain","handleLog","handleTransportError","handleTransportExit","relayReadReady","relayReadModelIndexed","relayBatchCompleted","HybridProjectionCoordinatorOptions","manager","preReady","postReady","lookupOnly","HybridProjectionCoordinator","chains","acceptReadReady","runHostChain","indexWithTiming","emitBatchCompleted","emitReadModelIndexed","queueKeyFor","SignerConfig","verifier","MigrationStrategy","MigrationResult","migrationsExecuted","SyncBuilder","withChannelFactory","withRemoteStorage","storage","withCursorStorage","withDeadLetterStorage","withMaxDeadLettersPerRemote","withMaxInboxBatchSize","withMaxHeldOperationsPerRemote","withStaleRemotePollWindowMs","windowMs","build","driveContainerTypes","buildModule","ReadModelFactoryDeps","ReadModelFactory","deps","ReadModelCoordinatorFactoryDeps","ProjectionShardBuilderConfig","subscriptionNotificationReadModel","createProjectionShardManager","registerShutdownHook","WorkerPoolBase","WorkerPoolOptions","ReactorBuilder","documentModelSources","upgradeManifests","features","readModelFactories","writeCacheConfig","migrationStrategy","syncBuilder","readModelCoordinatorFactory","kyselyInstance","signalHandlersEnabled","queueInstance","channelScheme","jwtHandler","documentModelLoader","shutdownHooks","workerPool","resolvedModelManifest","moduleOnlyModelKeys","projectionShardConfig","projectionWorkerFactory","instrumentedPools","withLogger","withDocumentModelSources","sources","withUpgradeManifests","withFeatures","withReadModel","withReadModelFactory","withReadModelCoordinator","withReadModelCoordinatorFactory","withExecutor","executor","withExecutorConfig","withWriteCacheConfig","withDriveContainerTypes","withMigrationStrategy","strategy","withSync","withEventBus","withSignatureVerifier","withKysely","withInstrumentedPool","instrumentation","withQueue","withChannelScheme","scheme","withJwtHandler","handler","withDocumentModelLoader","withSignalHandlers","withShutdownHook","withWorkerPool","withProjectionShards","withProjectionWorkerFactory","getResolvedModelManifest","resolveReactorDbConfig","createDefaultProjectionWorkerFactory","createDefaultWorkerFactory","createPostgresDatabase","attachSignalHandlers","ReactorClientBuilder","reactorBuilder","withReactorBuilder","withReactor","withSigner","withSubscriptionManager","withJobAwaiter","withReadGate","resolveReadGate","resolveActionEvaluation","DEFAULT_DRIVE_CONTAINER_TYPES","Reactor","shutdownStatus","setShutdown","setCompleted","findByIds","findBySlugs","findByParentId","emitJobPending","ParsedDriveUrl","graphqlEndpoint","parseDriveUrl","driveIdFromUrl","AuthEnforcementDisabledError","createMutableShutdownStatus","initialState","value","ParsedPaging","offset","parsePagingOptions","defaultLimit","DefaultSubscriptionErrorHandler","DocumentCreatedCallback","DocumentDeletedCallback","DocumentStateUpdatedCallback","RelationshipChangedCallback","ReactorSubscriptionManager","Map","createdSubscriptions","deletedSubscriptions","updatedSubscriptions","relationshipSubscriptions","subscriptionCounter","errorHandler","notifyDocumentsCreated","notifyDocumentsDeleted","notifyDocumentsUpdated","notifyRelationshipChanged","childType","filterDocumentIds","filterDocuments","matchesRelationshipFilter","EventBus","eventTypeToSubscribers","InMemoryQueue","Set","resolver","queues","jobIdToQueueKey","docIdToJobId","jobIdToDocId","completedJobs","jobIndex","isBlocked","onDrainedCallback","isPausedFlag","toErrorInfo","createQueueKey","getQueue","isDocumentExecuting","markJobExecuting","markJobComplete","areDependenciesMet","getNextJobWithMetDependencies","getCreateDocumentType","deferJob","checkDrained","getPendingJobs","getExecutingJobIds","getJob","InMemoryJobTracker","JobExecutorFactory","SimpleJobExecutorManager","executorFactory","executors","deferredJobs","resultHandler","processNextJob","checkForMoreJobs","processExistingJobs","SimpleJobExecutor","decisionModel","signatureVerifierModule","documentActionHandler","executionScope","executeInScope","evictTouchedStreams","getCollectionMembershipsForOperations","processActions","prepareRegularWrite","commitPreparedWrites","canBatch","executeRegularActionsBatched","conditionsAgree","executeRegularActionsSequentially","executeRegularAction","positionByTimestamp","evaluatePositioned","evaluationOrder","firstNonMonotonicTimestamp","appendedOperations","reevaluateIfCriteriaMet","reevaluateDocument","executeReevaluationJob","executeLoadJob","accumulateResultOrReturnError","createForwardingLogger","msg","post","tags","errorToInfo","err","sanitizeArg","WeakSet","workerEntryPath","ModuleNotFoundError","requestedVersion","DuplicateModuleError","InvalidModuleError","DuplicateManifestError","DocumentModelRegistry","manifestsToRegister","buildDecisionModel","reader","definition","AuthDecisionModel","auth","authDecisionModel","SyncScopeGate","gate","scopePredicateById","OutOfOrderPair","firstOutOfOrderPair","requireStrict","BaseReadModelConfig","rebuildStateOnInit","BaseReadModel","consistencyTracker","commitOperations","rebuildStateForOperations","loadState","initializeState","saveState","updateConsistencyTracker","IndexerDatabase","KyselyDocumentIndexer","_db","handleAddRelationship","handleRemoveRelationship","handleUpdateRelationship","ReadModelCoordinator","emitEmptyReadReady","runChain","Database$2","KyselyDocumentView","servesDeletionBoundary","idsWithStreams","liveIds","DOCUMENT_VIEW_READ_MODEL","DOCUMENT_INDEXER_READ_MODEL","ReactorReadModels","REACTOR_SCHEMA","runMigrations","schema","upTo","getMigrationStatus","MigrationInfo","KyselySyncCursorStorage","KyselySyncRemoteStorage","GqlRequestChannelFactory","GqlResponseChannelFactory","IPollTimer","setDelegate","delegate","triggerNow","GqlChannelConfig","fetch","fetchFn","GqlRequestChannel","bufferedOutbox","channelId","pollTimer","abortController","lastPersistedInboxOrdinal","lastPersistedOutboxOrdinal","pushRetryTimer","isPushing","pendingDrain","peerServesDecisionFields","isRecovering","connectionState","connectionStateCallbacks","transitionConnectionState","poll","handleRemoteDeadLetters","handlePollError","recoverFromChannelNotFound","resumePushAfterRecovery","pollSyncEnvelopes","rejectsDecisionFields","pollQuery","touchRemoteChannel","attemptPush","schedulePushRetry","drainOutbox","classifyError","pushSyncOperations","getAuthorizationHeader","executeGraphQL","poller","GqlResponseChannel","evictedOutboxFloor","appliedOutboxOrdinal","lastPollUtcMs","rememberUnserved","persistOutboxCursor","forgetEvictedBelow","unservedFloor","PollTimerConfig","intervalMs","maxQueueDepth","backpressureCheckIntervalMs","startPaused","IntervalPollTimer","timer","running","consecutiveFailures","tick","scheduleNext","scheduleRetry","scheduleBackpressureRecheck","getIntervalMs","setIntervalMs","ms","envelopesToSyncOperations","envelope","OperationBatch","trimMailboxFromAckOrdinal","mailbox","batchOperationsByDocument","consolidateSyncOperations","syncOps","classifyJobFailure","errorName","syncOperationErrorType","quarantinesDocument","IReactorProcessorHostModuleBase","getReadModel","ReactorHostModuleBaseOptions","Pick","createReactorHostModuleBase","KeyframeValidationIssue","keyframeHash","replayedHash","SnapshotValidationIssue","snapshotHash","StreamOrderIssue","ValidationResult","isConsistent","keyframeIssues","snapshotIssues","streamOrderIssues","RebuildResult","keyframesDeleted","scopesInvalidated","IDocumentIntegrityService","validateDocument","rebuildKeyframes","rebuildSnapshots","DocumentIntegrityService","findStreamOrderIssues","discoverScopes","ProcessorManagerOptions","legacyProcessorIds","ProcessorManager","factoryRegistry","processorsByDrive","factoryToProcessors","knownDrives","cursorCache","registerFactory","unregisterFactory","allTrackedProcessors","detectAndRegisterNewDrives","isDriveCreation","detectAndCleanupDeletedDrives","discoverExistingDrives","isDeletedDocumentADrive","createProcessorsForDrive","backfillProcessor","retryProcessor","cleanupDriveProcessors","safeDisconnect","routeOperationsToProcessors","loadAllCursors","safeSaveProcessorCursor","saveProcessorCursor","deleteProcessorCursors","InMemoryJobExecutor","ReactorJobFailedEvent","StorageDatabase","WorkerErrorInfo"],"sources":["../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.d.ts","../../reactor/dist/index.d.ts","../src/hypercore-operation-store.ts","../src/types.ts","../src/hypercore-atomic-transaction.ts","../src/storage-manager.ts","../src/key-encoding.ts"],"x_google_ignoreList":[0],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.d.ts","../../reactor/dist/index-dDm0fUBT.d.ts","../src/hypercore-operation-store.ts","../src/types.ts","../src/hypercore-atomic-transaction.ts","../src/storage-manager.ts","../src/key-encoding.ts"],"x_google_ignoreList":[0],"mappings":";;;;;;;;QAoBQ;YACM;YAEA;aACG;;;;;;;;KC0NZ;EACH;EACA;;;;;KAKG,aAAa;EAChB,SAAS;EACT,SAAS;EACT,aAAa,QAAQ,aAAa;EAClC;;;;;;KAkhBG;EACH;EACA;EACA;EACA;;;;;;KAMG;EACH,SAAS;;;;;;UAmBD;;EAER,iBAAiB,YAAY;;;;;;KAM1B;;EAEH,UAAU;;EAEV;;;;;;UAMQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8BR,MAAM,oBAAoB,sBAAsB,eAAe,gBAAgB,kBAAkB,KAAK,KAAK,qBAAqB,eAAe,SAAS,aAAa,YAAY,kBAAkB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;EAuB3M,SAAS,oBAAoB,eAAe,gBAAgB,kBAAkB,SAAS,iBAAiB,SAAS,eAAe,SAAS,cAAc,QAAQ,aAAa;;;;;;;;;;EAU5K,WAAW,YAAY,SAAS,eAAe,SAAS,cAAc,QAAQ,aAAa;;;;;;;;;;;;;;;;;;;;;;EAsB3F,eAAe,oBAAoB,eAAe,gBAAgB,sBAAsB,SAAS,eAAe,SAAS,cAAc,QAAQ,aAAa;;;;;;;;;;;EAW5J,aAAa,oBAAoB,gBAAgB,SAAS,cAAc,QAAQ;;;;;;;;;;EAUhF,yBAAyB,oBAAoB,eAAe,gBAAgB,SAAS,cAAc;;;;;EAKnG,iBAAiB,oBAAoB,eAAe,gBAAgB,iBAAiB,SAAS,cAAc,QAAQ;;EAEpH,mBAAmB,oBAAoB,eAAe,gBAAgB,iBAAiB,SAAS,cAAc,QAAQ;;;;;;UA2E9G;;EAER;;EAEA;;EAEA;;EAEA;;;;qBC79BW,mCAAmC;UAG1B;UAFZ;EAER,YAAoB,KAAK;EAEnB,MACJ,oBACA,sBACA,eACA,gBACA,kBACA,KAAK,KAAK,qBAAqB,eAC/B,SAAS,aACT,YAAY,kBACX,QAAQ;;UA8BG;UAoBA;;UAuGA;UAkBN;;;;;;;;;EAYF,SACJ,oBACA,eACA,gBACA,kBACA,SAAS,iBACT,SAAS,eACT,SAAS,cACR,QAAQ,aAAa;;;;;;;;;EAiGlB,WACJ,YACA,SAAS,eACT,SAAS,cACR,QAAQ,aAAa;;;;;;;EA2ElB,eACJ,oBACA,eACA,gBACA,sBACA,SAAS,eACT,SAAS,cACR,QAAQ,aAAa;EAwElB,aACJ,oBACA,gBACA,SAAS,cACR,QAAQ;;;;;;EAuCL,yBACJ,oBACA,eACA,gBACA,SAAS,cACR;EAyBG,iBACJ,oBACA,eACA,gBACA,iBACA,SAAS,cACR,QAAQ;EA6BL,mBACJ,oBACA,eACA,gBACA,iBACA,SAAS,cACR,QAAQ;UA2BH;UAiBA;;;;KC9oBE,kBAAkB;EAC5B;EACA;EACA;EACA;;KAGU;EACV;;;;qBCNW,sCAAsC;UAIvC;UACA;UACA;UACA;UANF;EAER,YACU,oBACA,sBACA,eACA;EAGV,iBAAiB,YAAY;EAY7B,iBAAiB;;;;qBCvBN;UACH;UACA;EAER,YAAY;EAIN,QAAQ;EAUR,SAAS;EAOf,UAAU;;;;qBCxBC;wBAEG,IAAI;wBAIJ,aACd,oBACA,eACA,gBACA;wBAKc,gBACd,oBACA,eACA;wBAKc,WAAW;wBAIX;wBAIA,aACd,cACA,eACA;wBAKc,QACd,oBACA,eACA;wBAKc,WAAW;qBAId;KAED;EACV;EACA;EACA;EACA;;wBAGc,kBAAkB,cAAc;KAUpC;EACV;EACA;EACA;EACA;EACA;EACA,WAAW;;KAGD;EACV;EACA"}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,41 @@
|
|
|
1
|
-
import "@powerhousedao/shared/document-model";
|
|
1
|
+
import { DOCUMENT_SCOPE_ACTION_TYPES, isPurgeMarker } from "@powerhousedao/shared/document-model";
|
|
2
2
|
import Corestore from "corestore";
|
|
3
3
|
import Hyperbee from "hyperbee";
|
|
4
|
-
//#region ../reactor/dist/
|
|
4
|
+
//#region ../reactor/dist/forwarding-logger-B9LLXItm.js
|
|
5
|
+
/**
|
|
6
|
+
* Error thrown when a document is not found (no operations exist for the document ID).
|
|
7
|
+
*/
|
|
8
|
+
var DocumentNotFoundError = class DocumentNotFoundError extends Error {
|
|
9
|
+
documentId;
|
|
10
|
+
/**
|
|
11
|
+
* @param message Overrides the default text. A handler that knows which of
|
|
12
|
+
* several documents an action reads - a relationship's source, say - says so
|
|
13
|
+
* here rather than rewrapping in a bare Error, which would strip the name the
|
|
14
|
+
* executor classifies by.
|
|
15
|
+
*/
|
|
16
|
+
constructor(documentId, message) {
|
|
17
|
+
super(message ?? `Document ${documentId} not found`);
|
|
18
|
+
this.name = "DocumentNotFoundError";
|
|
19
|
+
this.documentId = documentId;
|
|
20
|
+
Error.captureStackTrace(this, DocumentNotFoundError);
|
|
21
|
+
}
|
|
22
|
+
/** Also true for DocumentPurgedError: only the name crosses the queue. */
|
|
23
|
+
static isError(error) {
|
|
24
|
+
return Error.isError(error) && (error.name === "DocumentNotFoundError" || error.name === "DocumentPurgedError");
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/** The document was purged; readers treat it as absent. Terminal. */
|
|
28
|
+
var DocumentPurgedError = class DocumentPurgedError extends DocumentNotFoundError {
|
|
29
|
+
purged = true;
|
|
30
|
+
constructor(documentId, message) {
|
|
31
|
+
super(documentId, message ?? `Document ${documentId} was purged`);
|
|
32
|
+
this.name = "DocumentPurgedError";
|
|
33
|
+
Error.captureStackTrace(this, DocumentPurgedError);
|
|
34
|
+
}
|
|
35
|
+
static isError(error) {
|
|
36
|
+
return Error.isError(error) && error.name === "DocumentPurgedError";
|
|
37
|
+
}
|
|
38
|
+
};
|
|
5
39
|
/**
|
|
6
40
|
* Thrown when an operation with the same identity already exists in the store.
|
|
7
41
|
*/
|
|
@@ -43,6 +77,7 @@ const APPEND_CONDITION_FAILED_PREFIX = "Append condition failed: ";
|
|
|
43
77
|
* conflict, not a fault: the caller retries against the new stream heads.
|
|
44
78
|
*/
|
|
45
79
|
var AppendConditionFailedError = class extends Error {
|
|
80
|
+
condition;
|
|
46
81
|
constructor(condition) {
|
|
47
82
|
const streams = condition.streams.map((s) => `${s.documentId}:${s.scope}:${s.branch}@${s.revision}`).join(", ");
|
|
48
83
|
super(`${APPEND_CONDITION_FAILED_PREFIX}a read-set stream advanced [${streams}]`);
|
|
@@ -57,19 +92,14 @@ var AppendConditionFailedError = class extends Error {
|
|
|
57
92
|
return message.startsWith(APPEND_CONDITION_FAILED_PREFIX);
|
|
58
93
|
}
|
|
59
94
|
};
|
|
60
|
-
|
|
61
|
-
const DOCUMENT_SCOPE_ACTIONS = new Set([
|
|
62
|
-
"CREATE_DOCUMENT",
|
|
63
|
-
"DELETE_DOCUMENT",
|
|
64
|
-
"UPGRADE_DOCUMENT",
|
|
65
|
-
"ADD_RELATIONSHIP",
|
|
66
|
-
"REMOVE_RELATIONSHIP",
|
|
67
|
-
"UPDATE_RELATIONSHIP"
|
|
68
|
-
]);
|
|
69
|
-
new Set([...DOCUMENT_SCOPE_ACTIONS].filter((type) => type !== "CREATE_DOCUMENT"));
|
|
95
|
+
new Set([...DOCUMENT_SCOPE_ACTION_TYPES].filter((type) => type !== "CREATE_DOCUMENT"));
|
|
70
96
|
//#endregion
|
|
71
97
|
//#region src/hypercore-atomic-transaction.ts
|
|
72
98
|
var HypercoreAtomicTransaction = class {
|
|
99
|
+
documentId;
|
|
100
|
+
documentType;
|
|
101
|
+
scope;
|
|
102
|
+
branch;
|
|
73
103
|
operations = [];
|
|
74
104
|
constructor(documentId, documentType, scope, branch) {
|
|
75
105
|
this.documentId = documentId;
|
|
@@ -131,6 +161,7 @@ function parseOperationKey(key) {
|
|
|
131
161
|
//#endregion
|
|
132
162
|
//#region src/hypercore-operation-store.ts
|
|
133
163
|
var HypercoreOperationStore = class {
|
|
164
|
+
bee;
|
|
134
165
|
applyLock = Promise.resolve();
|
|
135
166
|
constructor(bee) {
|
|
136
167
|
this.bee = bee;
|
|
@@ -165,6 +196,11 @@ var HypercoreOperationStore = class {
|
|
|
165
196
|
const atomicTxn = new HypercoreAtomicTransaction(documentId, documentType, scope, branch);
|
|
166
197
|
await fn(atomicTxn);
|
|
167
198
|
const operations = atomicTxn.getOperations();
|
|
199
|
+
const marker = await this.purgeMarkerAtHead(documentId);
|
|
200
|
+
if (marker !== void 0 && operations.length > 0) {
|
|
201
|
+
if (!operations.every((op) => isPurgeMarker(op))) throw new DocumentPurgedError(documentId);
|
|
202
|
+
return [marker];
|
|
203
|
+
}
|
|
168
204
|
if (currentRevision !== revision - 1) {
|
|
169
205
|
if (revision === 0 && this.isCreate(operations)) throw new DocumentAlreadyExistsError(documentId, scope, currentRevision);
|
|
170
206
|
throw new RevisionMismatchError(currentRevision + 1, revision);
|
|
@@ -203,15 +239,32 @@ var HypercoreOperationStore = class {
|
|
|
203
239
|
await batch.flush();
|
|
204
240
|
return operations.map((op) => this.toOperation(op));
|
|
205
241
|
}
|
|
242
|
+
/** A purge marker is written to document/main whichever branch it erases. */
|
|
243
|
+
async purgeMarkerAtHead(documentId) {
|
|
244
|
+
const branch = "main";
|
|
245
|
+
const head = await this.bee.get(headKey(documentId, "document", branch));
|
|
246
|
+
if (!head) return;
|
|
247
|
+
const index = head.value.index;
|
|
248
|
+
const stored = (await this.bee.get(operationKey(documentId, "document", branch, index)))?.value;
|
|
249
|
+
return stored && isPurgeMarker(stored) ? this.toOperation(stored) : void 0;
|
|
250
|
+
}
|
|
206
251
|
isCreate(operations) {
|
|
207
252
|
return operations.some((op) => op.action.type === "CREATE_DOCUMENT");
|
|
208
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* The paging cursor encodes the index to resume from (one past the last
|
|
256
|
+
* row returned), not the last row's own index; "" or "0" (or anything
|
|
257
|
+
* unparsable) means the start of the stream. This keeps "0" an unambiguous
|
|
258
|
+
* start-of-stream sentinel even when a page ends at index 0, which would
|
|
259
|
+
* otherwise make `nextCursor` equal the start cursor and loop a caller that
|
|
260
|
+
* walks pages forever. Mirrors the encoding in the Kysely store.
|
|
261
|
+
*/
|
|
209
262
|
async getSince(documentId, scope, branch, revision, filter, paging, signal) {
|
|
210
263
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
211
264
|
const prefix = operationPrefix(documentId, scope, branch);
|
|
212
265
|
const startIndex = revision + 1;
|
|
213
|
-
const
|
|
214
|
-
const gt = prefix + pad(Math.max(startIndex,
|
|
266
|
+
const parsedCursor = paging?.cursor ? Number.parseInt(paging.cursor, 10) : NaN;
|
|
267
|
+
const gt = prefix + pad(Math.max(startIndex, Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : startIndex) - 1);
|
|
215
268
|
const lt = prefix + RANGE_UPPER_BOUND;
|
|
216
269
|
const limit = paging?.limit ? paging.limit + 1 : void 0;
|
|
217
270
|
const items = [];
|
|
@@ -236,7 +289,7 @@ var HypercoreOperationStore = class {
|
|
|
236
289
|
hasMore = true;
|
|
237
290
|
resultItems = items.slice(0, paging.limit);
|
|
238
291
|
}
|
|
239
|
-
const nextCursor = hasMore && resultItems.length > 0 ? resultItems[resultItems.length - 1].index.toString() : void 0;
|
|
292
|
+
const nextCursor = hasMore && resultItems.length > 0 ? (resultItems[resultItems.length - 1].index + 1).toString() : void 0;
|
|
240
293
|
const cursor = paging?.cursor || "0";
|
|
241
294
|
const resultLimit = paging?.limit || 100;
|
|
242
295
|
return {
|
|
@@ -252,11 +305,20 @@ var HypercoreOperationStore = class {
|
|
|
252
305
|
}, signal) : void 0
|
|
253
306
|
};
|
|
254
307
|
}
|
|
308
|
+
/**
|
|
309
|
+
* The paging cursor encodes the ordinal to resume from (one past the last
|
|
310
|
+
* ordinal returned), not the last ordinal itself; "" or "0" (or anything
|
|
311
|
+
* unparsable) means the start of the stream. Unlike the Kysely store's
|
|
312
|
+
* `getSinceId` (whose auto-increment id starts at 1), this store's ordinal
|
|
313
|
+
* counter starts at 0, so 0 is a real, valid ordinal and the same
|
|
314
|
+
* ambiguous-cursor hazard as `getSince`/`getConflicting` applies here too.
|
|
315
|
+
*/
|
|
255
316
|
async getSinceId(id, paging, signal) {
|
|
256
317
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
257
|
-
const
|
|
258
|
-
const
|
|
259
|
-
const
|
|
318
|
+
const startId = id + 1;
|
|
319
|
+
const parsedCursor = paging?.cursor ? Number.parseInt(paging.cursor, 10) : NaN;
|
|
320
|
+
const effectiveStart = Math.max(startId, Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : startId);
|
|
321
|
+
const gt = ordinalPrefix() + pad(effectiveStart - 1);
|
|
260
322
|
const lt = ordinalPrefix() + RANGE_UPPER_BOUND;
|
|
261
323
|
const limit = paging?.limit ? paging.limit + 1 : void 0;
|
|
262
324
|
const items = [];
|
|
@@ -285,7 +347,7 @@ var HypercoreOperationStore = class {
|
|
|
285
347
|
hasMore = true;
|
|
286
348
|
resultItems = items.slice(0, paging.limit);
|
|
287
349
|
}
|
|
288
|
-
const nextCursor = hasMore && resultItems.length > 0 ? resultItems[resultItems.length - 1].context.ordinal.toString() : void 0;
|
|
350
|
+
const nextCursor = hasMore && resultItems.length > 0 ? (resultItems[resultItems.length - 1].context.ordinal + 1).toString() : void 0;
|
|
289
351
|
const cursor = paging?.cursor || "0";
|
|
290
352
|
const resultLimit = paging?.limit || 100;
|
|
291
353
|
return {
|
|
@@ -301,21 +363,31 @@ var HypercoreOperationStore = class {
|
|
|
301
363
|
}, signal) : void 0
|
|
302
364
|
};
|
|
303
365
|
}
|
|
366
|
+
/**
|
|
367
|
+
* The paging cursor here encodes the index to resume from (one past the
|
|
368
|
+
* last row returned), not the last row's own index, for the same reason as
|
|
369
|
+
* `getSince`: a page ending at index 0 must not produce a cursor that is
|
|
370
|
+
* indistinguishable from the start-of-stream sentinel.
|
|
371
|
+
*/
|
|
304
372
|
async getConflicting(documentId, scope, branch, minTimestamp, paging, signal) {
|
|
305
373
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
306
374
|
const prefix = operationPrefix(documentId, scope, branch);
|
|
307
|
-
const
|
|
308
|
-
const
|
|
375
|
+
const parsedCursor = paging?.cursor ? Number.parseInt(paging.cursor, 10) : NaN;
|
|
376
|
+
const cursorIndex = Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : -1;
|
|
377
|
+
const gte = cursorIndex >= 0 ? prefix + pad(cursorIndex) : prefix;
|
|
309
378
|
const lt = prefix + RANGE_UPPER_BOUND;
|
|
310
379
|
const stream = this.bee.createReadStream({
|
|
311
|
-
|
|
312
|
-
gte: cursorIndex >= 0 ? void 0 : gt,
|
|
380
|
+
gte,
|
|
313
381
|
lt
|
|
314
382
|
});
|
|
383
|
+
const readLimit = paging?.limit ? paging.limit + 1 : void 0;
|
|
315
384
|
const items = [];
|
|
316
385
|
for await (const entry of stream) {
|
|
317
386
|
const stored = entry.value;
|
|
318
|
-
if (stored.timestampUtcMs >= minTimestamp)
|
|
387
|
+
if (stored.timestampUtcMs >= minTimestamp) {
|
|
388
|
+
items.push(this.toOperation(stored));
|
|
389
|
+
if (readLimit !== void 0 && items.length >= readLimit) break;
|
|
390
|
+
}
|
|
319
391
|
}
|
|
320
392
|
let hasMore = false;
|
|
321
393
|
let resultItems = items;
|
|
@@ -323,7 +395,7 @@ var HypercoreOperationStore = class {
|
|
|
323
395
|
hasMore = true;
|
|
324
396
|
resultItems = items.slice(0, paging.limit);
|
|
325
397
|
}
|
|
326
|
-
const nextCursor = hasMore && resultItems.length > 0 ? resultItems[resultItems.length - 1].index.toString() : void 0;
|
|
398
|
+
const nextCursor = hasMore && resultItems.length > 0 ? (resultItems[resultItems.length - 1].index + 1).toString() : void 0;
|
|
327
399
|
const cursor = paging?.cursor || "0";
|
|
328
400
|
const resultLimit = paging?.limit || 100;
|
|
329
401
|
return {
|
|
@@ -373,6 +445,24 @@ var HypercoreOperationStore = class {
|
|
|
373
445
|
for (const operation of stored.results) if (latest === void 0 || operation.timestampUtcMs > latest) latest = operation.timestampUtcMs;
|
|
374
446
|
return latest;
|
|
375
447
|
}
|
|
448
|
+
async findOperationIds(documentId, scope, branch, opIds, signal) {
|
|
449
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
450
|
+
const found = /* @__PURE__ */ new Set();
|
|
451
|
+
if (opIds.length === 0) return found;
|
|
452
|
+
const wanted = new Set(opIds);
|
|
453
|
+
const stored = await this.getSince(documentId, scope, branch, -1, void 0, void 0, signal);
|
|
454
|
+
for (const operation of stored.results) if (wanted.has(operation.id)) found.add(operation.id);
|
|
455
|
+
return found;
|
|
456
|
+
}
|
|
457
|
+
async getOperationsByIds(documentId, scope, branch, opIds, signal) {
|
|
458
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
459
|
+
if (opIds.length === 0) return [];
|
|
460
|
+
const wanted = new Set(opIds);
|
|
461
|
+
const stored = await this.getSince(documentId, scope, branch, -1, void 0, void 0, signal);
|
|
462
|
+
const latest = /* @__PURE__ */ new Map();
|
|
463
|
+
for (const operation of stored.results) if (wanted.has(operation.id)) latest.set(operation.id, operation);
|
|
464
|
+
return [...latest.values()];
|
|
465
|
+
}
|
|
376
466
|
serializeOperation(op) {
|
|
377
467
|
return {
|
|
378
468
|
id: op.id,
|
|
@@ -412,7 +502,8 @@ var StorageManager = class {
|
|
|
412
502
|
}
|
|
413
503
|
async open() {
|
|
414
504
|
await this.store.ready();
|
|
415
|
-
|
|
505
|
+
const core = this.store.get({ name: "operations" });
|
|
506
|
+
this.bee = new Hyperbee(core, {
|
|
416
507
|
keyEncoding: "utf-8",
|
|
417
508
|
valueEncoding: "json"
|
|
418
509
|
});
|