@korajs/core 0.0.0-canary-20261008174129
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/LICENSE +21 -0
- package/README.md +84 -0
- package/dist/bindings/index.cjs +105 -0
- package/dist/bindings/index.cjs.map +1 -0
- package/dist/bindings/index.d.cts +142 -0
- package/dist/bindings/index.d.ts +142 -0
- package/dist/bindings/index.js +78 -0
- package/dist/bindings/index.js.map +1 -0
- package/dist/build-scope-map-C9zBTJ1R.d.cts +33 -0
- package/dist/build-scope-map-CZaMyZLV.d.ts +33 -0
- package/dist/chunk-QUD3DMSD.js +1297 -0
- package/dist/chunk-QUD3DMSD.js.map +1 -0
- package/dist/events-Da29Dt_3.d.cts +1737 -0
- package/dist/events-Da29Dt_3.d.ts +1737 -0
- package/dist/index.cjs +5775 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1718 -0
- package/dist/index.d.ts +1718 -0
- package/dist/index.js +4404 -0
- package/dist/index.js.map +1 -0
- package/dist/internal.cjs +1367 -0
- package/dist/internal.cjs.map +1 -0
- package/dist/internal.d.cts +289 -0
- package/dist/internal.d.ts +289 -0
- package/dist/internal.js +501 -0
- package/dist/internal.js.map +1 -0
- package/dist/sql-gen-BOeuiyqu.d.cts +622 -0
- package/dist/sql-gen-CXTA6w-w.d.ts +622 -0
- package/package.json +62 -0
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,1718 @@
|
|
|
1
|
+
import { R as RandomSource, B as BlobRef, C as CollectionDefinition, O as OperationInput, A as AtomicOp, a as Operation, H as HLCTimestamp, S as SchemaDefinition, M as MergeTrace, F as FieldBuilder, b as CustomResolver, c as MigrationDefinition, d as FieldDescriptor, e as OperationType, V as VersionVector, f as MigrationStep, g as StateMachineConstraint, T as TransitionMap, h as TransitionValidationResult } from './events-Da29Dt_3.cjs';
|
|
2
|
+
export { i as ArrayAtomicOpSentinel, j as ArrayFieldBuilder, k as AtomicOpSentinel, l as AtomicOpType, m as BackfillOptions, n as CONNECTION_QUALITIES, o as ConnectionQuality, p as Constraint, E as EncryptedEnvelopeField, q as EncryptedOperationEnvelope, r as EnumFieldBuilder, s as FieldInput, t as FieldKind, u as FieldKindToType, v as FieldMap, w as FieldMergeStrategy, x as FieldOutput, y as FieldTypeInfo, I as InferFieldInput, z as InferFieldType, D as InferInsert, G as InferInsertInput, J as InferRecord, K as InferRecordField, L as InferUpdate, N as InferUpdateField, P as InferUpdateInput, Q as JsonFieldBuilder, U as KoraEvent, W as KoraEventByType, X as KoraEventEmitter, Y as KoraEventListener, Z as KoraEventType, _ as MERGE_STRATEGIES, $ as MergeStrategy, a0 as MigrationBuilder, a1 as NumericAtomicOpSentinel, a2 as ObjectFieldBuilder, a3 as ObjectFieldValue, a4 as OnDeleteAction, a5 as RelationDefinition, a6 as RelationType, a7 as RichtextInput, a8 as RollbackBuilder, a9 as ScalarFieldBuilder, aa as ScalarFieldKind, ab as SecretFieldBuilder, ac as SecretMode, ad as SequenceConfig, ae as Simplify, af as StateMachineDefinition, ag as SyncDiagnosticsSnapshot, ah as SyncRuleDefinition, ai as TimeSource, aj as applyAtomicOp, ak as isAtomicOp, al as migrate, am as op, an as resolveAtomicOp, ao as t, ap as toAtomicOp } from './events-Da29Dt_3.cjs';
|
|
3
|
+
import { F as FoldState, a as FoldOptions, b as FoldRecordResult, c as FoldFieldVersions, M as MergeOpResult, O as OperationTransform, d as FoldTrace } from './sql-gen-BOeuiyqu.cjs';
|
|
4
|
+
export { C as CounterFieldState, e as CreateOperationOptions, D as DEFAULT_OPERATION_HASH_VERSION, E as ElementSetFieldState, f as ElementState, g as ExtremumFieldState, h as FOLD_STATE_VERSION, i as FieldLogEntry, j as FieldState, k as FoldFieldKind, l as FoldTraceMode, H as HashableOperation, m as HybridLogicalClock, K as KeyMapFieldState, n as KeyState, o as MAX_LOGICAL, p as OperationHashVersion, R as RegisterFieldState, q as ResolverFieldState, r as RichtextFieldState, s as RichtextSubsumes, t as RichtextUpdateMerger, S as Stamp, u as computeOperationId, v as createOperation, w as generateFullDDL, x as generateSQL, y as isValidOperation, z as verifyOperationId, A as verifyOperationIntegrity } from './sql-gen-BOeuiyqu.cjs';
|
|
5
|
+
import { S as ScopeMap } from './build-scope-map-C9zBTJ1R.cjs';
|
|
6
|
+
export { b as buildScopeMap } from './build-scope-map-C9zBTJ1R.cjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Base error class for all Kora errors.
|
|
10
|
+
* Every error includes a machine-readable code and optional context for debugging.
|
|
11
|
+
*/
|
|
12
|
+
declare class KoraError extends Error {
|
|
13
|
+
readonly code: string;
|
|
14
|
+
readonly context?: Record<string, unknown> | undefined;
|
|
15
|
+
constructor(message: string, code: string, context?: Record<string, unknown> | undefined);
|
|
16
|
+
/**
|
|
17
|
+
* Actionable hint for resolving this error (from registry or error context).
|
|
18
|
+
*/
|
|
19
|
+
get fix(): string | undefined;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Thrown when schema validation fails during defineSchema() or at app initialization.
|
|
23
|
+
*/
|
|
24
|
+
declare class SchemaValidationError extends KoraError {
|
|
25
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Thrown when an operation is invalid or cannot be created.
|
|
29
|
+
*/
|
|
30
|
+
declare class OperationError extends KoraError {
|
|
31
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Thrown by the local write path when an operation would exceed `maxOperationBytes`
|
|
35
|
+
* (RT-86): the server refuses such an operation, so the write is refused before it is
|
|
36
|
+
* accepted, with nothing written.
|
|
37
|
+
*/
|
|
38
|
+
declare class OperationTooLargeError extends KoraError {
|
|
39
|
+
readonly collection: string;
|
|
40
|
+
readonly recordId: string;
|
|
41
|
+
readonly bytes: number;
|
|
42
|
+
readonly maxBytes: number;
|
|
43
|
+
constructor(collection: string, recordId: string, bytes: number, maxBytes: number);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Thrown when a merge conflict cannot be automatically resolved.
|
|
47
|
+
*/
|
|
48
|
+
declare class MergeConflictError extends KoraError {
|
|
49
|
+
readonly operationA: {
|
|
50
|
+
id: string;
|
|
51
|
+
collection: string;
|
|
52
|
+
};
|
|
53
|
+
readonly operationB: {
|
|
54
|
+
id: string;
|
|
55
|
+
collection: string;
|
|
56
|
+
};
|
|
57
|
+
readonly field: string;
|
|
58
|
+
constructor(operationA: {
|
|
59
|
+
id: string;
|
|
60
|
+
collection: string;
|
|
61
|
+
}, operationB: {
|
|
62
|
+
id: string;
|
|
63
|
+
collection: string;
|
|
64
|
+
}, field: string);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Thrown when a sync error occurs.
|
|
68
|
+
*/
|
|
69
|
+
declare class SyncError extends KoraError {
|
|
70
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Thrown when a storage operation fails.
|
|
74
|
+
*/
|
|
75
|
+
declare class StorageError extends KoraError {
|
|
76
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Thrown when collection/query APIs are used before {@link KoraApp.ready} resolves.
|
|
80
|
+
*/
|
|
81
|
+
declare class AppNotReadyError extends KoraError {
|
|
82
|
+
constructor(detail: string);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Thrown when the HLC detects excessive clock drift.
|
|
86
|
+
* Drift > 60s: warning. Drift > 5min: this error is thrown, refusing to generate timestamps.
|
|
87
|
+
*/
|
|
88
|
+
declare class RemoteClockDriftError extends KoraError {
|
|
89
|
+
readonly remoteWallTime: number;
|
|
90
|
+
readonly localReferenceTime: number;
|
|
91
|
+
constructor(remoteWallTime: number, localReferenceTime: number);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Thrown when an HLC timestamp has structurally invalid fields: non-integer or
|
|
95
|
+
* negative wallTime/logical, or a logical counter beyond the serializable cap.
|
|
96
|
+
* Rejected BEFORE any clock state changes, so a malformed remote timestamp can
|
|
97
|
+
* never corrupt a replica's clock or break the lexicographic ordering of the
|
|
98
|
+
* serialized form.
|
|
99
|
+
*/
|
|
100
|
+
declare class InvalidTimestampError extends KoraError {
|
|
101
|
+
readonly wallTime: number;
|
|
102
|
+
readonly logical: number;
|
|
103
|
+
constructor(message: string, wallTime: number, logical: number);
|
|
104
|
+
}
|
|
105
|
+
declare class ClockDriftError extends KoraError {
|
|
106
|
+
readonly currentHlcTime: number;
|
|
107
|
+
readonly physicalTime: number;
|
|
108
|
+
constructor(currentHlcTime: number, physicalTime: number);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Human-readable remediation hints keyed by {@link KoraError} `code`.
|
|
113
|
+
*/
|
|
114
|
+
declare const KORA_ERROR_FIX_SUGGESTIONS: Record<string, string>;
|
|
115
|
+
/**
|
|
116
|
+
* Returns a suggested fix for a Kora error code, if one is known.
|
|
117
|
+
*/
|
|
118
|
+
declare function getKoraErrorFix(code: string): string | undefined;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Tracks the latest operation per collection and within an open transaction
|
|
122
|
+
* to populate {@link Operation.causalDeps} for local mutations.
|
|
123
|
+
*/
|
|
124
|
+
declare class CausalTracker {
|
|
125
|
+
private readonly lastOpIdByCollection;
|
|
126
|
+
private lastTransactionOpId;
|
|
127
|
+
/**
|
|
128
|
+
* Start a new transaction boundary. Clears in-transaction op ids.
|
|
129
|
+
*/
|
|
130
|
+
beginTransaction(): void;
|
|
131
|
+
/**
|
|
132
|
+
* Clear the transaction boundary without recording ops (after rollback).
|
|
133
|
+
*/
|
|
134
|
+
clearTransaction(): void;
|
|
135
|
+
/**
|
|
136
|
+
* Compute causal dependencies for the next operation in a collection.
|
|
137
|
+
* Uses direct parents only: collection head and the previous op in the open transaction.
|
|
138
|
+
*/
|
|
139
|
+
nextCausalDeps(collection: string, inTransaction: boolean): string[];
|
|
140
|
+
/**
|
|
141
|
+
* Record an operation after it has been created and assigned an id.
|
|
142
|
+
*/
|
|
143
|
+
afterOperation(collection: string, operationId: string, inTransaction: boolean): void;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Generates a UUID v7 per RFC 9562.
|
|
148
|
+
* UUID v7 encodes a Unix timestamp in milliseconds in the most significant 48 bits,
|
|
149
|
+
* making UUIDs time-sortable while remaining globally unique.
|
|
150
|
+
*
|
|
151
|
+
* @param timestamp - Unix timestamp in milliseconds (defaults to Date.now())
|
|
152
|
+
* @param randomSource - Injectable random source for deterministic testing
|
|
153
|
+
* @returns A UUID v7 string in standard 8-4-4-4-12 format
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* ```typescript
|
|
157
|
+
* const id = generateUUIDv7()
|
|
158
|
+
* // "018f3a5c-7e00-7123-abcd-1234567890ab"
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
declare function generateUUIDv7(timestamp?: number, randomSource?: RandomSource): string;
|
|
162
|
+
/**
|
|
163
|
+
* Extracts the Unix timestamp in milliseconds from a UUID v7.
|
|
164
|
+
*
|
|
165
|
+
* @param uuid - A UUID v7 string
|
|
166
|
+
* @returns The encoded Unix timestamp in milliseconds
|
|
167
|
+
*/
|
|
168
|
+
declare function extractTimestamp(uuid: string): number;
|
|
169
|
+
/**
|
|
170
|
+
* Validates whether a string is a valid UUID v7.
|
|
171
|
+
* Checks format, version (7), and variant (10xx).
|
|
172
|
+
*
|
|
173
|
+
* @param uuid - String to validate
|
|
174
|
+
* @returns true if the string is a valid UUID v7
|
|
175
|
+
*/
|
|
176
|
+
declare function isValidUUIDv7(uuid: string): boolean;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Compute the hex-encoded SHA-256 content hash of a byte buffer.
|
|
180
|
+
*
|
|
181
|
+
* This is the content address of a blob: identical bytes always hash to the same
|
|
182
|
+
* value, which is what lets the blob store deduplicate content and lets a peer
|
|
183
|
+
* skip transferring bytes it already holds.
|
|
184
|
+
*
|
|
185
|
+
* @param bytes - The binary content to hash
|
|
186
|
+
* @returns The hex-encoded SHA-256 hash
|
|
187
|
+
*/
|
|
188
|
+
declare function hashBlob(bytes: Uint8Array): Promise<string>;
|
|
189
|
+
/** Optional metadata carried alongside a blob reference. */
|
|
190
|
+
interface BlobRefMetadata {
|
|
191
|
+
mimeType?: string;
|
|
192
|
+
filename?: string;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Create a content-addressed {@link BlobRef} for a byte buffer.
|
|
196
|
+
*
|
|
197
|
+
* @param bytes - The binary content
|
|
198
|
+
* @param metadata - Optional MIME type and filename
|
|
199
|
+
* @returns A reference carrying the content hash, size, and metadata
|
|
200
|
+
*/
|
|
201
|
+
declare function createBlobRef(bytes: Uint8Array, metadata?: BlobRefMetadata): Promise<BlobRef>;
|
|
202
|
+
/**
|
|
203
|
+
* Type guard: whether a value is a structurally valid {@link BlobRef}.
|
|
204
|
+
*
|
|
205
|
+
* Validates the shape only (a non-empty hex hash and a non-negative size); it
|
|
206
|
+
* does not verify that the bytes behind the hash exist or match. Integrity
|
|
207
|
+
* verification against the actual bytes happens in the blob store on read.
|
|
208
|
+
*/
|
|
209
|
+
declare function isBlobRef(value: unknown): value is BlobRef;
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Field-level cryptography for `secret` fields.
|
|
213
|
+
*
|
|
214
|
+
* Two protection modes, matching the two ways secrets are used:
|
|
215
|
+
* - `encrypted`: reversible AES-256-GCM (tokens, API keys — decrypt to use).
|
|
216
|
+
* - `hashed`: one-way PBKDF2-SHA-256 with a random salt (passwords — verify only).
|
|
217
|
+
*
|
|
218
|
+
* These primitives use only the standard WebCrypto API so they live in
|
|
219
|
+
* `@korajs/core` with no dependency on `@korajs/auth`; a `secret` field is
|
|
220
|
+
* therefore self-contained. Higher-level key management composes on top.
|
|
221
|
+
*/
|
|
222
|
+
/**
|
|
223
|
+
* Encrypt a secret's plaintext with AES-256-GCM under a key derived from
|
|
224
|
+
* `secretKey`. The returned string bundles the salt, IV, and ciphertext (all hex,
|
|
225
|
+
* dot-separated) so it is self-describing and safe to store and sync.
|
|
226
|
+
*
|
|
227
|
+
* @param plaintext - The secret value to protect
|
|
228
|
+
* @param secretKey - The key material (from a key provider), never stored
|
|
229
|
+
* @returns An opaque `v1.salt.iv.ciphertext` string
|
|
230
|
+
*/
|
|
231
|
+
declare function encryptSecret(plaintext: string, secretKey: string): Promise<string>;
|
|
232
|
+
/**
|
|
233
|
+
* Decrypt a value produced by {@link encryptSecret} with the same key.
|
|
234
|
+
*
|
|
235
|
+
* @param encrypted - The `v1.salt.iv.ciphertext` string
|
|
236
|
+
* @param secretKey - The key material used to encrypt
|
|
237
|
+
* @returns The original plaintext
|
|
238
|
+
* @throws If the format is invalid or the key is wrong (GCM auth failure)
|
|
239
|
+
*/
|
|
240
|
+
declare function decryptSecret(encrypted: string, secretKey: string): Promise<string>;
|
|
241
|
+
/**
|
|
242
|
+
* One-way hash a secret (a password) with PBKDF2-SHA-256 and a random salt.
|
|
243
|
+
* The result bundles the salt and hash so {@link verifySecret} needs nothing
|
|
244
|
+
* else. There is no way to recover the plaintext from the result.
|
|
245
|
+
*
|
|
246
|
+
* @param plaintext - The secret value to hash
|
|
247
|
+
* @returns An opaque `v1.salt.hash` string
|
|
248
|
+
*/
|
|
249
|
+
declare function hashSecret(plaintext: string): Promise<string>;
|
|
250
|
+
/**
|
|
251
|
+
* Verify a plaintext against a value produced by {@link hashSecret}, in constant
|
|
252
|
+
* time with respect to the stored hash.
|
|
253
|
+
*
|
|
254
|
+
* @param plaintext - The candidate secret
|
|
255
|
+
* @param stored - The `v1.salt.hash` string
|
|
256
|
+
* @returns Whether the plaintext matches
|
|
257
|
+
*/
|
|
258
|
+
declare function verifySecret(plaintext: string, stored: string): Promise<boolean>;
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Provider of the key material used to encrypt reversible (`encrypted`) secret
|
|
262
|
+
* fields. Called at write and reveal time so the key can be loaded lazily (for
|
|
263
|
+
* example derived from a user passphrase after unlock). Returns undefined when
|
|
264
|
+
* no key is available.
|
|
265
|
+
*/
|
|
266
|
+
type SecretKeyProvider = () => string | undefined | Promise<string | undefined>;
|
|
267
|
+
/** Thrown when an `encrypted` secret field is written or read without a key. */
|
|
268
|
+
declare class MissingSecretKeyError extends Error {
|
|
269
|
+
readonly field: string;
|
|
270
|
+
constructor(field: string);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Transform the secret fields of a record's write payload into their at-rest
|
|
274
|
+
* form BEFORE the operation is created, so plaintext never enters the operation
|
|
275
|
+
* log, the store, or the sync stream.
|
|
276
|
+
*
|
|
277
|
+
* - `hashed` fields become a one-way salted hash.
|
|
278
|
+
* - `encrypted` fields become ciphertext (requires a key).
|
|
279
|
+
*
|
|
280
|
+
* Non-secret fields, and secret fields not present in `data`, are passed through
|
|
281
|
+
* untouched. Null/undefined secret values are left as-is (nothing to protect).
|
|
282
|
+
*
|
|
283
|
+
* @param data - The validated write payload (plaintext secret values)
|
|
284
|
+
* @param collectionDef - The collection definition (for field kinds/modes)
|
|
285
|
+
* @param keyProvider - Supplies the encryption key for `encrypted` fields
|
|
286
|
+
* @returns A new payload with secret fields replaced by their at-rest form
|
|
287
|
+
*/
|
|
288
|
+
declare function transformSecretFieldsForWrite(data: Record<string, unknown>, collectionDef: CollectionDefinition, keyProvider?: SecretKeyProvider): Promise<Record<string, unknown>>;
|
|
289
|
+
/**
|
|
290
|
+
* Reveal the plaintext of an `encrypted` secret field's stored value. Throws for
|
|
291
|
+
* `hashed` fields, which are one-way and cannot be revealed.
|
|
292
|
+
*
|
|
293
|
+
* @param storedValue - The at-rest value (ciphertext)
|
|
294
|
+
* @param mode - The field's secret mode
|
|
295
|
+
* @param keyProvider - Supplies the decryption key
|
|
296
|
+
* @param field - Field name (for error messages)
|
|
297
|
+
* @returns The decrypted plaintext
|
|
298
|
+
*/
|
|
299
|
+
declare function revealSecret(storedValue: string, mode: 'hashed' | 'encrypted', keyProvider: SecretKeyProvider | undefined, field?: string): Promise<string>;
|
|
300
|
+
/**
|
|
301
|
+
* Verify a plaintext candidate against a `hashed` secret field's stored value.
|
|
302
|
+
*
|
|
303
|
+
* @param candidate - The plaintext to check (for example a login password)
|
|
304
|
+
* @param storedValue - The stored one-way hash
|
|
305
|
+
* @returns Whether the candidate matches
|
|
306
|
+
*/
|
|
307
|
+
declare function verifySecretValue(candidate: string, storedValue: string): Promise<boolean>;
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Outcome of applying a single operation to materialized storage (local or remote).
|
|
311
|
+
*/
|
|
312
|
+
declare const APPLY_RESULTS: readonly ["applied", "duplicate", "skipped", "rejected", "deferred"];
|
|
313
|
+
type ApplyResult = (typeof APPLY_RESULTS)[number];
|
|
314
|
+
/**
|
|
315
|
+
* Structured failure metadata when apply returns `skipped`, `rejected`, or `deferred`.
|
|
316
|
+
*/
|
|
317
|
+
interface ApplyFailureReason {
|
|
318
|
+
code: string;
|
|
319
|
+
message: string;
|
|
320
|
+
retriable: boolean;
|
|
321
|
+
}
|
|
322
|
+
/** Well-known apply failure codes for DevTools and `sync:apply-failed` events. */
|
|
323
|
+
declare const APPLY_FAILURE_CODES: {
|
|
324
|
+
readonly APPLY_FAILED: "APPLY_FAILED";
|
|
325
|
+
readonly APPLY_SKIPPED: "APPLY_SKIPPED";
|
|
326
|
+
readonly APPLY_REJECTED: "APPLY_REJECTED";
|
|
327
|
+
readonly APPLY_DEFERRED: "APPLY_DEFERRED";
|
|
328
|
+
readonly CLOCK_DRIFT: "CLOCK_DRIFT";
|
|
329
|
+
readonly REFERENTIAL_INTEGRITY: "REFERENTIAL_INTEGRITY";
|
|
330
|
+
readonly SCHEMA_MISMATCH: "SCHEMA_MISMATCH";
|
|
331
|
+
};
|
|
332
|
+
/**
|
|
333
|
+
* Returns true when the apply outcome should surface as a failure to the developer.
|
|
334
|
+
*/
|
|
335
|
+
declare function isApplyFailure(result: ApplyResult): boolean;
|
|
336
|
+
/**
|
|
337
|
+
* Default failure metadata when the store does not attach a specific reason.
|
|
338
|
+
*/
|
|
339
|
+
declare function defaultApplyFailureReason(result: Exclude<ApplyResult, 'applied' | 'duplicate'>, overrides?: Partial<ApplyFailureReason>): ApplyFailureReason;
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Thrown when an operation (or a record value) holds a value that has no canonical
|
|
343
|
+
* JSON form: the op log and the wire are JSON, so such a value would be stored and
|
|
344
|
+
* synced as something other than what was written and hashed.
|
|
345
|
+
*/
|
|
346
|
+
declare class NonCanonicalValueError extends KoraError {
|
|
347
|
+
readonly path: string;
|
|
348
|
+
readonly receivedType: string;
|
|
349
|
+
constructor(message: string, path: string, receivedType: string);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* The one canonical form of an operation body (RT-72 family: RT-79, RT-80, RT-83).
|
|
353
|
+
*
|
|
354
|
+
* The op log, the wire (JSON and protobuf, whose data is JSON) and every store hold an
|
|
355
|
+
* operation as JSON. An operation's id is a hash of its body. So the body is put in its
|
|
356
|
+
* canonical form ONCE, when the operation is created (and when a legacy operation is
|
|
357
|
+
* ingested or rebuilt), and the canonical body is what is hashed, stored, sent and
|
|
358
|
+
* folded: the four can never disagree, by construction.
|
|
359
|
+
*
|
|
360
|
+
* | Value | Canonical form |
|
|
361
|
+
* |-----------------------------------------|-------------------------------------------------|
|
|
362
|
+
* | `undefined` member of an insert's data | absent |
|
|
363
|
+
* | `undefined` member of an update's data | `null`: the field is CLEARED (beta.12 meaning) |
|
|
364
|
+
* | `undefined` member of an update's `previousData` | `null` (the field held no value) |
|
|
365
|
+
* | `undefined` member inside an object value | absent (as JSON drops it); a `t.json()` field refuses it at validation |
|
|
366
|
+
* | `undefined` array element | `null` (as JSON writes it) |
|
|
367
|
+
* | `undefined` atomic op | absent |
|
|
368
|
+
* | `-0` | `0` (JSON writes `0`) |
|
|
369
|
+
* | valid `Date` | its ISO 8601 string (`toISOString()`), as JSON |
|
|
370
|
+
* | `Uint8Array` / `ArrayBuffer` | `{ $koraBytes: <base64> }` (the op-log binary form) |
|
|
371
|
+
* | plain object (`Object.prototype` or `null` prototype) | plain object, members canonical |
|
|
372
|
+
* | array (dense) | array, elements canonical |
|
|
373
|
+
* | string, finite number, boolean, `null` | itself |
|
|
374
|
+
* | invalid `Date`, `NaN`, `±Infinity`, `BigInt`, function, symbol, `Map`, `Set`, `WeakMap`, `RegExp`, `Promise`, any other class instance, an object with a `toJSON` method, an own `__proto__` key, a circular reference | refused: {@link NonCanonicalValueError} naming the path and the fix |
|
|
375
|
+
*
|
|
376
|
+
* Canonicalization is idempotent: a canonical body is returned unchanged (same
|
|
377
|
+
* references where nothing changed).
|
|
378
|
+
*
|
|
379
|
+
* @param input - The operation body (as given to `createOperation`, or a stored operation)
|
|
380
|
+
* @returns The body with `data`, `previousData` and `atomicOps` canonical
|
|
381
|
+
* @throws {NonCanonicalValueError} For a value with no canonical form
|
|
382
|
+
*/
|
|
383
|
+
declare function canonicalizeOperationBody<T extends CanonicalizableBody>(input: T): T;
|
|
384
|
+
/** The members of an operation body that {@link canonicalizeOperationBody} reads. */
|
|
385
|
+
interface CanonicalizableBody {
|
|
386
|
+
type: OperationInput['type'];
|
|
387
|
+
collection: string;
|
|
388
|
+
recordId: string;
|
|
389
|
+
data: Record<string, unknown> | null;
|
|
390
|
+
previousData: Record<string, unknown> | null;
|
|
391
|
+
atomicOps?: Record<string, AtomicOp>;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* The canonical form of one value inside an operation body or a record field (see
|
|
395
|
+
* {@link canonicalizeOperationBody} for the table). Exported so schema validation
|
|
396
|
+
* produces exactly the values an operation will carry.
|
|
397
|
+
*
|
|
398
|
+
* @param value - Any value
|
|
399
|
+
* @param path - Where the value is, for the error message (e.g. `notes.extra.when`)
|
|
400
|
+
* @returns The canonical value (the same reference when it already is)
|
|
401
|
+
* @throws {NonCanonicalValueError} For a value with no canonical form
|
|
402
|
+
*/
|
|
403
|
+
declare function canonicalValue(value: unknown, path: string): unknown;
|
|
404
|
+
/**
|
|
405
|
+
* A legacy update in its canonical body when its id PROVES the beta.12 clear (RT-85):
|
|
406
|
+
* the id is the content hash of the body with every `previousData` key absent from
|
|
407
|
+
* `data` restored as `null` (version 1, or version 2 with a lost declaration), and not
|
|
408
|
+
* of the body as it is. Such an id can only come from a writer that hashed the clear,
|
|
409
|
+
* so the restored body is the one its author wrote and applied; a body a schema
|
|
410
|
+
* transform or anything else rewrote never proves it.
|
|
411
|
+
*
|
|
412
|
+
* Used where a legacy body enters a replica without a known provenance: a device's
|
|
413
|
+
* inbound delivery, and the one-time canonicalization of stored logs. The server's
|
|
414
|
+
* ingest of a protocol-1 upload applies the same rule (plus the unverifiable
|
|
415
|
+
* protocol-1 case, for the session's own node).
|
|
416
|
+
*
|
|
417
|
+
* @param op - Any operation
|
|
418
|
+
* @returns The canonical operation, or `op` itself when nothing is proven
|
|
419
|
+
*/
|
|
420
|
+
declare function canonicalizeProvenLegacyClear<T extends Operation>(op: T): Promise<T>;
|
|
421
|
+
/**
|
|
422
|
+
* The canonical body of a legacy (version-1, beta.12) update (RT-71, RT-83): every
|
|
423
|
+
* `previousData` key absent from `data` is a clear, restored as `null`. beta.12 wrote
|
|
424
|
+
* `previousData[key]` for every key it validated, so such a key held `undefined` in
|
|
425
|
+
* `data`: beta.12 hashed it as `null`, applied it as a cleared field, and its JSON log
|
|
426
|
+
* and upload dropped it. `null` and `undefined` hash identically under version 1, so
|
|
427
|
+
* the id is unchanged.
|
|
428
|
+
*
|
|
429
|
+
* Applied ONCE, where a genuine beta.12 body is identified (RT-85), never at fold time:
|
|
430
|
+
* the server's ingest of a protocol-1 upload, a device's own beta.12 log at the
|
|
431
|
+
* upgrade, and any body whose id proves the clear
|
|
432
|
+
* ({@link canonicalizeProvenLegacyClear}). The result is stored, so the server, peers
|
|
433
|
+
* and the upgraded writer fold the same body. A no-op
|
|
434
|
+
* for anything else (a declared version 2, an envelope, an insert or delete, an update
|
|
435
|
+
* whose data covers its previousData). Idempotent.
|
|
436
|
+
*
|
|
437
|
+
* @param op - Any operation
|
|
438
|
+
* @returns The operation with the restored data, or `op` itself
|
|
439
|
+
*/
|
|
440
|
+
declare function canonicalizeLegacyOperation<T extends LegacyBody>(op: T): T;
|
|
441
|
+
/** The members of an operation {@link canonicalizeLegacyOperation} reads. */
|
|
442
|
+
interface LegacyBody {
|
|
443
|
+
type: Operation['type'];
|
|
444
|
+
data: Record<string, unknown> | null;
|
|
445
|
+
previousData: Record<string, unknown> | null;
|
|
446
|
+
hashVersion?: Operation['hashVersion'];
|
|
447
|
+
encrypted?: Operation['encrypted'];
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** One operation's contribution to a record's materialized state. */
|
|
451
|
+
interface ReplayOperation {
|
|
452
|
+
type: string;
|
|
453
|
+
data: Record<string, unknown> | null;
|
|
454
|
+
/**
|
|
455
|
+
* Atomic-op intents carried by this operation, per field. When present, a field
|
|
456
|
+
* is composed (rather than overwritten) if the previous writer on that field was
|
|
457
|
+
* an atomic op of the same type. Absent means every field resolves by
|
|
458
|
+
* last-write-wins.
|
|
459
|
+
*/
|
|
460
|
+
atomicOps?: Record<string, AtomicOp> | null;
|
|
461
|
+
/**
|
|
462
|
+
* For updates: the values the writer saw before its change. Array fields use it
|
|
463
|
+
* as the base of a three-way set merge (see {@link mergeArraySet}). Absent means
|
|
464
|
+
* array fields resolve by last-write-wins.
|
|
465
|
+
*/
|
|
466
|
+
previousData?: Record<string, unknown> | null;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Three-way set merge for array fields, shared by the client merge engine
|
|
470
|
+
* (`addWinsSet`) and the record fold, so client and server agree.
|
|
471
|
+
*
|
|
472
|
+
* result = (local ∩ remote) ∪ (local − base) ∪ (remote − base)
|
|
473
|
+
*
|
|
474
|
+
* A base element is kept only if BOTH sides kept it (a one-sided removal is never
|
|
475
|
+
* undone by the other side's unchanged copy); a non-base element is kept if EITHER
|
|
476
|
+
* side has it. Elements are compared by `JSON.stringify`.
|
|
477
|
+
*
|
|
478
|
+
* Order is role-independent: kept base elements first, in base order, then every
|
|
479
|
+
* other kept element sorted by its serialized form. Swapping `local` and `remote`
|
|
480
|
+
* yields the identical array.
|
|
481
|
+
*
|
|
482
|
+
* Interim (S1): W7 replaces this pairwise rule with a per-element LWW set.
|
|
483
|
+
*
|
|
484
|
+
* @param local - One side's array after its modifications
|
|
485
|
+
* @param remote - The other side's array after its modifications
|
|
486
|
+
* @param base - The common ancestor both sides edited from
|
|
487
|
+
* @returns The merged array
|
|
488
|
+
*/
|
|
489
|
+
declare function mergeArraySet(local: unknown[], remote: unknown[], base: unknown[]): unknown[];
|
|
490
|
+
/**
|
|
491
|
+
* Replay a list of operations (MUST be pre-sorted in HLC total order —
|
|
492
|
+
* wallTime, then logical, then nodeId) to produce the current state of a single
|
|
493
|
+
* record, composing atomic-op intents.
|
|
494
|
+
*
|
|
495
|
+
* Per field, an atomic op composes onto the running value only when the field's
|
|
496
|
+
* previous writer was an atomic op of the SAME type (a same-type atomic chain:
|
|
497
|
+
* concurrent increments sum, maxes take the max, appends accumulate); any other
|
|
498
|
+
* write, including the first atomic write after a plain set, resolves by
|
|
499
|
+
* last-write-wins on the resolved value. Because operations are folded in HLC order,
|
|
500
|
+
* the current op always wins that last-write-wins comparison, so the result is
|
|
501
|
+
* deterministic and identical on every replica that folds the same operation set.
|
|
502
|
+
*
|
|
503
|
+
* Plain array writes that carry `previousData` are merged as a set against that
|
|
504
|
+
* base (see {@link mergeArraySet}) when a concurrent writer changed the field since
|
|
505
|
+
* the base, so the fold and the client merge agree on one-sided removals.
|
|
506
|
+
*
|
|
507
|
+
* This is the single definition of atomic materialization shared by the client
|
|
508
|
+
* (`@korajs/store` apply pipeline) and the server (`@korajs/server` materialization),
|
|
509
|
+
* so both converge to the same value for any number of concurrent atomic writers.
|
|
510
|
+
*
|
|
511
|
+
* Returns the record field data (without `id`) or null if the record was deleted
|
|
512
|
+
* or never inserted.
|
|
513
|
+
*/
|
|
514
|
+
declare function replayOperationsForRecord(ops: ReplayOperation[]): Record<string, unknown> | null;
|
|
515
|
+
/** A {@link ReplayOperation} with the HLC timestamp it was written at. */
|
|
516
|
+
interface VersionedReplayOperation {
|
|
517
|
+
type: string;
|
|
518
|
+
data: Record<string, unknown> | null;
|
|
519
|
+
timestamp: HLCTimestamp;
|
|
520
|
+
}
|
|
521
|
+
/** Per-field versions of a live record, as folded by {@link replayFieldVersionsForRecord}. */
|
|
522
|
+
interface RecordFieldVersions {
|
|
523
|
+
/** Field name -> HLC of the write that produced the field's current value. */
|
|
524
|
+
fields: Record<string, HLCTimestamp>;
|
|
525
|
+
/** The record's first operation (its creation; the server's `_created_at`). */
|
|
526
|
+
created: HLCTimestamp;
|
|
527
|
+
/** The record's newest operation. */
|
|
528
|
+
latest: HLCTimestamp;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Fold the per-field versions of one record, mirroring {@link replayOperationsForRecord}
|
|
532
|
+
* exactly (RT-27): an insert resets the field set and stamps every field it carries,
|
|
533
|
+
* an update stamps the fields it writes (composed atomic and array writes included:
|
|
534
|
+
* the field's version is its last writer's), a delete hides the record until a later
|
|
535
|
+
* write revives it. Operations MUST be pre-sorted in HLC total order.
|
|
536
|
+
*
|
|
537
|
+
* @param ops - The record's operations in HLC order
|
|
538
|
+
* @returns The live record's field versions, or null when it is deleted or absent
|
|
539
|
+
*/
|
|
540
|
+
declare function replayFieldVersionsForRecord(ops: readonly VersionedReplayOperation[]): RecordFieldVersions | null;
|
|
541
|
+
/**
|
|
542
|
+
* Expand operations for a record fold (RT-27). A scope-entry insert carrying
|
|
543
|
+
* per-field versions restates the record's CURRENT values, each produced at its own
|
|
544
|
+
* version; folding it as one insert at a single timestamp would misplace every field
|
|
545
|
+
* relative to the receiver's own writes. It is expanded into an insert at its
|
|
546
|
+
* `timestamp` (the record's creation) followed by one update per newer field version,
|
|
547
|
+
* so a fold in HLC order puts each field exactly where its writer did. Other
|
|
548
|
+
* operations pass through unchanged. The result is sorted in HLC total order (stable,
|
|
549
|
+
* so an expansion keeps insert-before-update on equal timestamps).
|
|
550
|
+
*
|
|
551
|
+
* @param ops - Operations of one record, in any order
|
|
552
|
+
* @returns The operations to fold, in HLC order
|
|
553
|
+
*/
|
|
554
|
+
declare function expandFieldVersionedOperations(ops: readonly Operation[]): Operation[];
|
|
555
|
+
|
|
556
|
+
/** `FoldTrace.field` of a record-level (delete vs write) decision. */
|
|
557
|
+
declare const FOLD_RECORD_TRACE_FIELD = "*";
|
|
558
|
+
/**
|
|
559
|
+
* An empty fold state for one record: no operation merged yet.
|
|
560
|
+
*
|
|
561
|
+
* @param collection - The record's collection
|
|
562
|
+
* @param recordId - The record's id
|
|
563
|
+
*/
|
|
564
|
+
declare function createFoldState(collection: string, recordId: string): FoldState;
|
|
565
|
+
/**
|
|
566
|
+
* Merge one operation into a record's fold state.
|
|
567
|
+
*
|
|
568
|
+
* The merge is a join on a per-field CRDT, so it is commutative, associative and
|
|
569
|
+
* idempotent: any replica that has merged the same set of operations, in any
|
|
570
|
+
* order, any number of times, holds an identical state. Cost is O(fields the
|
|
571
|
+
* operation touches) except for the out-of-order cases documented per kind (a late
|
|
572
|
+
* write into an atomic or resolver chain refolds that field's chain).
|
|
573
|
+
*
|
|
574
|
+
* Record-level semantics:
|
|
575
|
+
* - The record exists once an insert has been merged.
|
|
576
|
+
* - Delete vs write is last-write-wins on the record: the record is live iff its
|
|
577
|
+
* newest insert/update is later (HLC, then op id) than its newest delete. A
|
|
578
|
+
* delete keeps the field states; a later write revives the record with every
|
|
579
|
+
* field's merged value (the same visible result as the pre-W7 replay for an
|
|
580
|
+
* update after a delete).
|
|
581
|
+
* - An insert onto an existing row merges per field; it is not a reset.
|
|
582
|
+
*
|
|
583
|
+
* @param state - The record's current state (not mutated)
|
|
584
|
+
* @param op - The operation (must belong to the same collection and record)
|
|
585
|
+
* @param schema - The schema; resolvers and merge strategies come from it
|
|
586
|
+
* @param options - Exclusion, richtext merger (traces only), trace mode, schema
|
|
587
|
+
* transforms (the operation is merged as `operationSchemaView` reads it for
|
|
588
|
+
* `schema.version`)
|
|
589
|
+
* @returns The new state, the merge traces, and whether anything changed
|
|
590
|
+
*/
|
|
591
|
+
declare function mergeOp(state: FoldState, input: Operation, schema: SchemaDefinition, options?: FoldOptions): MergeOpResult;
|
|
592
|
+
/**
|
|
593
|
+
* Fold a record's operations from scratch: the reference definition of the
|
|
594
|
+
* record's state. Equal to merging the operations one by one with
|
|
595
|
+
* {@link mergeOp} in any order.
|
|
596
|
+
*
|
|
597
|
+
* @param ops - The record's operations, in any order, duplicates allowed
|
|
598
|
+
* @param schema - The schema
|
|
599
|
+
* @param options - `exclude` leaves out ops the server terminally rejected; traces
|
|
600
|
+
* default to `'none'` here (pass `traces` to get them)
|
|
601
|
+
* @returns The state (null if no op remains after exclusion) and the traces
|
|
602
|
+
*/
|
|
603
|
+
declare function foldRecord(ops: readonly Operation[], schema: SchemaDefinition, options?: FoldOptions): FoldRecordResult;
|
|
604
|
+
/**
|
|
605
|
+
* The record's materialized field values (without `id`), or null when it does not
|
|
606
|
+
* exist (no insert merged) or is deleted. Keys are in sorted order.
|
|
607
|
+
*
|
|
608
|
+
* @param state - The record's fold state
|
|
609
|
+
* @param options - `richtext` is required when a richtext field has concurrent updates
|
|
610
|
+
*/
|
|
611
|
+
declare function materialize(state: FoldState, options?: Pick<FoldOptions, 'richtext'>): Record<string, unknown> | null;
|
|
612
|
+
/** True when the record exists and its newest write is later than its newest delete. */
|
|
613
|
+
declare function isFoldStateLive(state: FoldState): boolean;
|
|
614
|
+
/**
|
|
615
|
+
* Join two replicas' states of the same record (state-based CRDT merge):
|
|
616
|
+
* `joinStates(foldRecord(A).state, foldRecord(B).state) = foldRecord(A ∪ B).state`.
|
|
617
|
+
* Commutative, associative and idempotent. Used to merge a restored backup or a
|
|
618
|
+
* peer's snapshot without replaying its operations.
|
|
619
|
+
*
|
|
620
|
+
* @param a - One state
|
|
621
|
+
* @param b - The other state (same collection and record)
|
|
622
|
+
* @param schema - The schema (resolver fields refold through their resolver)
|
|
623
|
+
*/
|
|
624
|
+
declare function joinStates(a: FoldState, b: FoldState, schema: SchemaDefinition): FoldState;
|
|
625
|
+
/**
|
|
626
|
+
* Each field's newest affecting write as a serialized HLC (`HybridLogicalClock.
|
|
627
|
+
* serialize`), regardless of liveness: the `_field_versions` column of a stored row,
|
|
628
|
+
* without a deserialize/serialize round trip. Keys in sorted order.
|
|
629
|
+
*/
|
|
630
|
+
declare function getFoldFieldVersionStrings(state: FoldState): Record<string, string>;
|
|
631
|
+
/**
|
|
632
|
+
* Per-field versions of a live record (the fold's `_field_versions`): each field's
|
|
633
|
+
* newest affecting write, plus the record's creation and newest operation. null
|
|
634
|
+
* when the record is not live.
|
|
635
|
+
*/
|
|
636
|
+
declare function getFoldFieldVersions(state: FoldState): FoldFieldVersions | null;
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* Serialize a record's fold state for storage (the client `_fold_state` column,
|
|
640
|
+
* the server stores' fold-record rows, backups, compaction snapshots).
|
|
641
|
+
*
|
|
642
|
+
* The output is canonical JSON (sorted keys), so two replicas holding the same
|
|
643
|
+
* operations write byte-identical strings. Format, version 2 (version 1, Stage A,
|
|
644
|
+
* keyed array elements by value only and is refused: such a state is re-folded):
|
|
645
|
+
*
|
|
646
|
+
* ```
|
|
647
|
+
* {
|
|
648
|
+
* "v": 2, // format version
|
|
649
|
+
* "c": "todos", "r": "<id>", // collection, record id
|
|
650
|
+
* "cr": Stamp|null, // oldest insert (creation)
|
|
651
|
+
* "w": Stamp|null, // newest insert/update
|
|
652
|
+
* "d": Stamp|null, // newest delete (tombstone register)
|
|
653
|
+
* "u": Stamp|null, // newest operation of any type
|
|
654
|
+
* "f": { "<field>": FieldState }
|
|
655
|
+
* }
|
|
656
|
+
* Stamp = { "t": "<HLC serialized>", "o": "<op id>", "c"?: 1 } // c: authority class
|
|
657
|
+
* FieldState =
|
|
658
|
+
* { "k":"reg", "e":[{ "s":Stamp, "v":value, "a"?:AtomicOp }], "val":value }
|
|
659
|
+
* { "k":"set", "ao":bool, "sh":{ "s":Stamp, "arr":bool, "v"?:value }|null, "clr":Stamp|null,
|
|
660
|
+
* "el":{ "<canonical JSON>#<k>":{ "v":value, "n":k, "a":Stamp|null, "f":{ "s":Stamp, "i":n }|null, "r":Stamp|null } } }
|
|
661
|
+
* { "k":"map", "sh":{ "s":Stamp, "obj":bool, "v"?:value }|null, "clr":Stamp|null,
|
|
662
|
+
* "keys":{ "<key>":{ "s":Stamp, "del":bool, "v"?:value } } }
|
|
663
|
+
* { "k":"ctr", "base":{ "s":Stamp, "v":value }|null, "d":[{ "s":Stamp, "n":number }], "val":value }
|
|
664
|
+
* { "k":"max"|"min", "best":{ "s":Stamp, "v":number }|null, "reg":{ "s":Stamp, "v":value }|null }
|
|
665
|
+
* { "k":"res", "e":[{ "s":Stamp, "v":value, "b"?:value, "z"?:1 }], "val":value, "err"?:string }
|
|
666
|
+
* { "k":"rt", "reset":{ "s":Stamp, "v":value }|null, "u":{ "<base64 Yjs update>":Stamp } }
|
|
667
|
+
* ```
|
|
668
|
+
*
|
|
669
|
+
* Values are JSON-safe (binary as `{ "$koraBytes": base64 }`). The state is
|
|
670
|
+
* self-contained: kinds that need history embed exactly the history they need
|
|
671
|
+
* ('reg' keeps the atomic chain since the newest plain write, 'res' its whole
|
|
672
|
+
* write log, 'ctr' the deltas since its base), so a compactor may treat the state
|
|
673
|
+
* as the record's snapshot and drop operations it covers.
|
|
674
|
+
*
|
|
675
|
+
* @param state - The fold state
|
|
676
|
+
* @returns Canonical JSON
|
|
677
|
+
*/
|
|
678
|
+
declare function serializeFoldState(state: FoldState): string;
|
|
679
|
+
/**
|
|
680
|
+
* Parse a stored fold state. Throws {@link FoldStateError} for an unknown format
|
|
681
|
+
* version or a malformed state; the caller then re-folds the record from its log.
|
|
682
|
+
*
|
|
683
|
+
* @param json - Output of {@link serializeFoldState}
|
|
684
|
+
*/
|
|
685
|
+
declare function deserializeFoldState(json: string): FoldState;
|
|
686
|
+
|
|
687
|
+
/** A materialized row and its versions, the input of {@link createSnapshotState}. */
|
|
688
|
+
interface FoldSnapshotInput {
|
|
689
|
+
collection: string;
|
|
690
|
+
recordId: string;
|
|
691
|
+
/** Field values of the row (record or op-data form; binary is normalized). */
|
|
692
|
+
values: Record<string, unknown>;
|
|
693
|
+
/** Per-field version: the HLC of the newest write of each field. */
|
|
694
|
+
fieldVersions: Record<string, HLCTimestamp>;
|
|
695
|
+
/** HLC of the row's creation. */
|
|
696
|
+
created: HLCTimestamp;
|
|
697
|
+
/** HLC of the newest operation the row reflects (its `_version`). */
|
|
698
|
+
latest: HLCTimestamp;
|
|
699
|
+
/** The row is a domain tombstone. */
|
|
700
|
+
deleted: boolean;
|
|
701
|
+
}
|
|
702
|
+
/** Options of {@link createSnapshotState}. */
|
|
703
|
+
interface FoldSnapshotOptions {
|
|
704
|
+
/**
|
|
705
|
+
* A fold state this replica still holds for the record (its stored
|
|
706
|
+
* `_kora_fold_state`, or the base of a compacted record). Every field whose stored
|
|
707
|
+
* kind still matches the schema is taken from it as-is (exact: element, delta and
|
|
708
|
+
* update stamps included); only the other fields are rebuilt from the row.
|
|
709
|
+
*/
|
|
710
|
+
seed?: FoldState | null;
|
|
711
|
+
/**
|
|
712
|
+
* Legacy authoritative node ids (`FoldOptions.authoritativeNodeIds`). A
|
|
713
|
+
* `merge('server-authoritative')` field whose version was written by an
|
|
714
|
+
* authoritative node (a `kora:server:` node or one of these) is stamped with
|
|
715
|
+
* authority class 1, so a client write it beat cannot overturn it when merged again.
|
|
716
|
+
*/
|
|
717
|
+
authoritativeNodeIds?: ReadonlySet<string>;
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* Build a record's fold state from a materialized row: the base snapshot used when
|
|
721
|
+
* the operations that produced the row are no longer all in the log (a database
|
|
722
|
+
* compacted before W7, or a record that owns quarantined log rows).
|
|
723
|
+
*
|
|
724
|
+
* Exact where the replica still has the data: fields of `options.seed` (a stored
|
|
725
|
+
* fold state) whose kind is unchanged are used verbatim, and the record stamps come
|
|
726
|
+
* from it. Every other field is written at its own version with a sentinel
|
|
727
|
+
* operation id that sorts after any real id, so the snapshot dominates every
|
|
728
|
+
* operation it reflects: re-merging such an operation changes nothing (the record's
|
|
729
|
+
* remaining log is folded on top of it again on every re-fold), while a later
|
|
730
|
+
* operation merges on top as usual. Arrays and objects also clear elements / keys
|
|
731
|
+
* written before the snapshot (so an older add the row no longer shows is not
|
|
732
|
+
* resurrected), richtext hides older updates, counters drop older deltas and
|
|
733
|
+
* custom-resolver fields start a fresh log at the snapshot value. A
|
|
734
|
+
* `merge('server-authoritative')` field whose version is a server node's write
|
|
735
|
+
* keeps its authority class.
|
|
736
|
+
*
|
|
737
|
+
* Approximate for a row-only field (RT-68 residual): a concurrent write OLDER than
|
|
738
|
+
* the field's version that arrives later folds against the snapshot value, not
|
|
739
|
+
* against the original operations (a late counter delta or array add is dropped).
|
|
740
|
+
* It cannot be otherwise without the original operations: the row alone does not
|
|
741
|
+
* say whether an older write is already in its value. The store marks such records
|
|
742
|
+
* approximate, and the server's fold state replaces the snapshot when the record
|
|
743
|
+
* next enters the device's scope.
|
|
744
|
+
*
|
|
745
|
+
* @param input - The row's values and versions
|
|
746
|
+
* @param schema - The schema (selects each field's fold kind)
|
|
747
|
+
* @param options - Seed state and authoritative node ids
|
|
748
|
+
*/
|
|
749
|
+
declare function createSnapshotState(input: FoldSnapshotInput, schema: SchemaDefinition, options?: FoldSnapshotOptions): FoldState;
|
|
750
|
+
/** Result of {@link adaptFoldState}. */
|
|
751
|
+
interface AdaptedFoldState {
|
|
752
|
+
state: FoldState;
|
|
753
|
+
/** Fields rebuilt as snapshots (their stored kind no longer matched the schema). */
|
|
754
|
+
adapted: string[];
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Make a stored fold state mergeable under the current schema after a change of a
|
|
758
|
+
* field's fold kind (RT-63): every field whose stored kind no longer matches the
|
|
759
|
+
* plan is replaced by a snapshot of its materialized value at its newest write (as
|
|
760
|
+
* {@link createSnapshotState} builds from a row), keeping its authority class.
|
|
761
|
+
* Fields whose kind is unchanged are kept exactly. Used for compacted base states,
|
|
762
|
+
* whose operations are no longer in the log to re-fold with the new plan.
|
|
763
|
+
*
|
|
764
|
+
* @param state - A stored fold state (base or record state)
|
|
765
|
+
* @param schema - The current schema
|
|
766
|
+
* @param options - `richtext` merger, to materialize a richtext field with several updates
|
|
767
|
+
*/
|
|
768
|
+
declare function adaptFoldState(state: FoldState, schema: SchemaDefinition, options?: Pick<FoldOptions, 'richtext'>): AdaptedFoldState;
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Fingerprint of how a schema folds records (W7): the fold-state format version
|
|
772
|
+
* plus every collection's {@link collectionFoldPlanFingerprint}. When it changes
|
|
773
|
+
* (a field becomes `merge('counter')`, an array becomes append-only, a resolver is
|
|
774
|
+
* added or edited), stored fold states may hold fields of another kind and must be
|
|
775
|
+
* re-folded. The same definition as the server stores' `fold_plan_fingerprint`.
|
|
776
|
+
*
|
|
777
|
+
* Schema transforms (RT-84) are part of the plan when any is registered: an operation
|
|
778
|
+
* of another schema version folds as its transformed view, so changing a transform or
|
|
779
|
+
* the target version re-folds. Without transforms the fingerprint is unchanged.
|
|
780
|
+
*
|
|
781
|
+
* @param schema - The schema
|
|
782
|
+
* @param transforms - The schema transforms the replica folds with
|
|
783
|
+
*/
|
|
784
|
+
declare function foldPlanFingerprint(schema: SchemaDefinition, transforms?: readonly OperationTransform[]): string;
|
|
785
|
+
/**
|
|
786
|
+
* Per-collection fold plan fingerprints, to find which collections a schema change
|
|
787
|
+
* re-plans (only their records need re-folding).
|
|
788
|
+
*
|
|
789
|
+
* @param schema - The schema
|
|
790
|
+
* @param transforms - The schema transforms the replica folds with (see {@link foldPlanFingerprint})
|
|
791
|
+
* @returns Collection name -> fingerprint (format version included)
|
|
792
|
+
*/
|
|
793
|
+
declare function foldPlanFingerprints(schema: SchemaDefinition, transforms?: readonly OperationTransform[]): Record<string, string>;
|
|
794
|
+
/**
|
|
795
|
+
* The fields of a stored fold state whose kind no longer matches the schema (empty
|
|
796
|
+
* when the state can be merged into as-is).
|
|
797
|
+
*
|
|
798
|
+
* @param state - A stored fold state
|
|
799
|
+
* @param schema - The current schema
|
|
800
|
+
*/
|
|
801
|
+
declare function mismatchedFoldFields(state: FoldState, schema: SchemaDefinition): string[];
|
|
802
|
+
|
|
803
|
+
/**
|
|
804
|
+
* Node-id namespaces Kora reserves for itself.
|
|
805
|
+
*
|
|
806
|
+
* Every id starting with {@link RESERVED_NODE_ID_PREFIX} belongs to Kora: devices
|
|
807
|
+
* never author under one (a client refuses to adopt such an id, and the server
|
|
808
|
+
* refuses it at the handshake). Inside it, {@link SERVER_NODE_ID_PREFIX} names the
|
|
809
|
+
* server's own nodes (`kora:server:<stableId>`): their writes are authoritative for
|
|
810
|
+
* `merge('server-authoritative')` fields on every replica, whatever list of node
|
|
811
|
+
* ids a given handshake advertised. That keeps authority stable across server
|
|
812
|
+
* restarts and instances without any replica having to learn the ids first.
|
|
813
|
+
*/
|
|
814
|
+
declare const RESERVED_NODE_ID_PREFIX = "kora:";
|
|
815
|
+
/** Prefix of every server-authored node id: `kora:server:<stableId>`. */
|
|
816
|
+
declare const SERVER_NODE_ID_PREFIX = "kora:server:";
|
|
817
|
+
/** True when `nodeId` is in Kora's reserved `kora:` namespace. */
|
|
818
|
+
declare function isReservedNodeId(nodeId: string): boolean;
|
|
819
|
+
/** True when `nodeId` names a server node (`kora:server:<stableId>`). */
|
|
820
|
+
declare function isServerNodeId(nodeId: string): boolean;
|
|
821
|
+
/**
|
|
822
|
+
* Whether a node's writes are authoritative for `merge('server-authoritative')`
|
|
823
|
+
* fields: a server node by prefix, or one of `explicit` (legacy, randomly generated
|
|
824
|
+
* server node ids a server keeps advertising in its handshake).
|
|
825
|
+
*
|
|
826
|
+
* @param nodeId - The writing node
|
|
827
|
+
* @param explicit - Additional authoritative node ids (`FoldOptions.authoritativeNodeIds`)
|
|
828
|
+
*/
|
|
829
|
+
declare function isAuthoritativeNodeId(nodeId: string, explicit?: ReadonlySet<string>): boolean;
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* Turn a {@link FoldTrace} into the {@link MergeTrace} DevTools and `merge:*`
|
|
833
|
+
* events consume. `operationA` is the operation that last wrote the field before
|
|
834
|
+
* the merge; the fold state only keeps its id (`trace.priorOperationId`), so the
|
|
835
|
+
* caller looks it up in its operation log. When it is unavailable (compacted, or
|
|
836
|
+
* the field had no prior value) the incoming operation stands in for it, and
|
|
837
|
+
* `inputA` still carries the prior value.
|
|
838
|
+
*
|
|
839
|
+
* @param trace - A trace from `mergeOp`
|
|
840
|
+
* @param operationA - The operation that produced the field's prior value, if known
|
|
841
|
+
*/
|
|
842
|
+
declare function toMergeTrace(trace: FoldTrace, operationA?: Operation | null): MergeTrace;
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* Lossless string encoding for SQL text columns (RT-65), shared by every store that
|
|
846
|
+
* binds JavaScript strings into a database: the server's Postgres and SQLite stores
|
|
847
|
+
* and the client's SQLite stores (better-sqlite3, SQLite WASM on OPFS, and the
|
|
848
|
+
* IndexedDB fallback, which runs SQLite WASM in memory).
|
|
849
|
+
*
|
|
850
|
+
* A JavaScript string is a sequence of UTF-16 code units. SQL text is UTF-8, which
|
|
851
|
+
* cannot hold two kinds of code unit sequence a JS string can:
|
|
852
|
+
*
|
|
853
|
+
* - A lone UTF-16 surrogate: better-sqlite3, SQLite WASM (TextEncoder) and the
|
|
854
|
+
* Postgres driver all encode it as U+FFFD: silent corruption.
|
|
855
|
+
* - U+0000: Postgres TEXT refuses it; SQLite WASM reads a TEXT column up to the first
|
|
856
|
+
* NUL.
|
|
857
|
+
*
|
|
858
|
+
* The codec maps those code units to an escape introduced by U+FFFF, a Unicode
|
|
859
|
+
* noncharacter (valid UTF-8, never assigned):
|
|
860
|
+
*
|
|
861
|
+
* | Input | Stored |
|
|
862
|
+
* |---|---|
|
|
863
|
+
* | U+0000 | U+FFFF `0` |
|
|
864
|
+
* | U+FFFF | U+FFFF `F` |
|
|
865
|
+
* | lone surrogate `\uXXXX` | U+FFFF `s` + 4 lowercase hex digits |
|
|
866
|
+
*
|
|
867
|
+
* Every other string is stored unchanged, so existing rows, equality filters and
|
|
868
|
+
* ordering are unaffected for ordinary text. The map is injective, and
|
|
869
|
+
* `decodeStoredText(encodeStoredText(s)) === s` for every JS string. Equality is
|
|
870
|
+
* preserved: `encode(a) === encode(b)` iff `a === b`, so an equality filter binds the
|
|
871
|
+
* encoded value.
|
|
872
|
+
*
|
|
873
|
+
* Ordering of escaped strings: range filters (`$gt`, `$lt`, ...) and `orderBy` compare
|
|
874
|
+
* the stored (encoded) form, in the database's collation (UTF-8 byte order on SQLite and
|
|
875
|
+
* on Postgres with `C.UTF-8`). A string containing U+0000, U+FFFF or a lone surrogate
|
|
876
|
+
* therefore sorts by its escape, U+FFFF, at the position of the first such code unit:
|
|
877
|
+
* after every other BMP character there, and before supplementary-plane characters.
|
|
878
|
+
* For example `"a\u0000"` sorts after `"ab"` (in JavaScript it sorts before), and a
|
|
879
|
+
* lone surrogate sorts after `"\uFFFE"`. Such strings are rare and equality is exact;
|
|
880
|
+
* do not rely on their relative order in range queries.
|
|
881
|
+
*
|
|
882
|
+
* Columns holding `JSON.stringify` output need no codec: well-formed `JSON.stringify`
|
|
883
|
+
* escapes U+0000 and lone surrogates as `\u` sequences.
|
|
884
|
+
*/
|
|
885
|
+
/** The escape introducer: U+FFFF, a noncharacter. */
|
|
886
|
+
declare const STORED_TEXT_ESCAPE = "\uFFFF";
|
|
887
|
+
/** True when `s` contains a code unit a SQL text column cannot hold as is. */
|
|
888
|
+
declare function needsStoredTextEncoding(s: string): boolean;
|
|
889
|
+
/**
|
|
890
|
+
* Encode a JS string for a SQL TEXT column (or a string inside a JSONB value).
|
|
891
|
+
*
|
|
892
|
+
* @param s - Any JavaScript string
|
|
893
|
+
* @returns `s` itself when it holds no NUL, U+FFFF or lone surrogate; otherwise the escaped form
|
|
894
|
+
*/
|
|
895
|
+
declare function encodeStoredText(s: string): string;
|
|
896
|
+
/**
|
|
897
|
+
* Decode a string written by {@link encodeStoredText}.
|
|
898
|
+
*
|
|
899
|
+
* @param s - A stored string
|
|
900
|
+
* @returns The original JavaScript string. A U+FFFF not followed by a valid tag is kept as is.
|
|
901
|
+
*/
|
|
902
|
+
declare function decodeStoredText(s: string): string;
|
|
903
|
+
/**
|
|
904
|
+
* Apply {@link encodeStoredText} to every string (and object key) inside a JSON value.
|
|
905
|
+
*
|
|
906
|
+
* @param value - A JSON-compatible value
|
|
907
|
+
*/
|
|
908
|
+
declare function encodeStoredJsonValue(value: unknown): unknown;
|
|
909
|
+
/**
|
|
910
|
+
* Apply {@link decodeStoredText} to every string (and object key) inside a JSON value.
|
|
911
|
+
*
|
|
912
|
+
* @param value - A JSON-compatible value
|
|
913
|
+
*/
|
|
914
|
+
declare function decodeStoredJsonValue(value: unknown): unknown;
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Deterministic id for a side-effect operation (a referential cascade, a
|
|
918
|
+
* set-null, a constraint correction) generated while applying `parentOpId`.
|
|
919
|
+
*
|
|
920
|
+
* Every replica that applies the same parent operation and generates the same
|
|
921
|
+
* effect on the same record derives the same id, so the effect is stored once and
|
|
922
|
+
* deduplicates everywhere instead of multiplying (one copy per replica) and racing
|
|
923
|
+
* (W7 step 3). Cascades keep working offline: a client derives the same id the
|
|
924
|
+
* server will.
|
|
925
|
+
*
|
|
926
|
+
* Callers must also make the side-effect's CONTENT deterministic (timestamp and
|
|
927
|
+
* data derived from the parent), because dedup by id keeps whichever copy arrives
|
|
928
|
+
* first. Ids are SHA-256 over canonical JSON of
|
|
929
|
+
* `{ domain, parent, rule, target }`, hex encoded.
|
|
930
|
+
*
|
|
931
|
+
* @param parentOpId - Id of the operation whose application produced the effect
|
|
932
|
+
* @param ruleId - Stable id of the rule (for example `relation:<name>:cascade`)
|
|
933
|
+
* @param targetRecordId - Id of the record the effect writes
|
|
934
|
+
* @returns 64-char hex id
|
|
935
|
+
*/
|
|
936
|
+
declare function deriveSideEffectOpId(parentOpId: string, ruleId: string, targetRecordId: string): Promise<string>;
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* A fold state cannot be used: unknown format version, malformed JSON, a state
|
|
940
|
+
* for a different record, or a field whose stored kind no longer matches the
|
|
941
|
+
* schema. The fix is always the same: re-fold the record from its operation log
|
|
942
|
+
* (`foldRecord`), which is the source of truth.
|
|
943
|
+
*/
|
|
944
|
+
declare class FoldStateError extends KoraError {
|
|
945
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
946
|
+
}
|
|
947
|
+
/**
|
|
948
|
+
* The fold was asked for something its configuration cannot provide, for example
|
|
949
|
+
* materializing a richtext field with several concurrent Yjs updates without a
|
|
950
|
+
* richtext merger.
|
|
951
|
+
*/
|
|
952
|
+
declare class FoldConfigurationError extends KoraError {
|
|
953
|
+
constructor(message: string, context?: Record<string, unknown>);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* Canonical JSON-safe encoding of binary bytes stored inside `op.data` /
|
|
958
|
+
* `op.previousData` (currently richtext field values). A raw Uint8Array
|
|
959
|
+
* JSON-serializes to a numeric-key object and an ArrayBuffer to `{}` (silent
|
|
960
|
+
* data loss), which breaks content-hash stability, persistence round-trips,
|
|
961
|
+
* remote application, and merge. Tagging the bytes as base64 at
|
|
962
|
+
* operation-creation time makes the hashed value, the persisted JSON, the wire
|
|
963
|
+
* payload, and the value the merge engine sees the identical canonical value.
|
|
964
|
+
*
|
|
965
|
+
* This convention lives in `@korajs/core` because `op.data` is a core concept:
|
|
966
|
+
* both `@korajs/store` (persistence, creation) and `@korajs/merge` (CRDT merge)
|
|
967
|
+
* must agree on it, and neither may depend on the other.
|
|
968
|
+
*/
|
|
969
|
+
interface KoraBytesValue {
|
|
970
|
+
$koraBytes: string;
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Type guard for the tagged binary form. Requires exactly the single
|
|
974
|
+
* `$koraBytes` key so arbitrary user objects that happen to contain the key
|
|
975
|
+
* are never silently reinterpreted as bytes.
|
|
976
|
+
*/
|
|
977
|
+
declare function isKoraBytesValue(value: unknown): value is KoraBytesValue;
|
|
978
|
+
/**
|
|
979
|
+
* Detects the numeric-key object shape a raw Uint8Array produced when
|
|
980
|
+
* JSON-serialized before the tagged encoding existed ({"0":1,"1":2,...}).
|
|
981
|
+
*/
|
|
982
|
+
declare function isLegacyNumericByteObject(value: unknown): value is Record<string, number>;
|
|
983
|
+
/**
|
|
984
|
+
* Dependency-free base64 encoder. btoa is unavailable for bytes in Node and
|
|
985
|
+
* Buffer is unavailable in browsers, so a manual implementation is the only
|
|
986
|
+
* deterministic option that works in every runtime Kora targets.
|
|
987
|
+
*/
|
|
988
|
+
declare function bytesToBase64(bytes: Uint8Array): string;
|
|
989
|
+
/**
|
|
990
|
+
* Inverse of {@link bytesToBase64}.
|
|
991
|
+
*/
|
|
992
|
+
declare function base64ToBytes(base64: string): Uint8Array;
|
|
993
|
+
/**
|
|
994
|
+
* Normalize a validated binary-or-string value into the canonical form stored
|
|
995
|
+
* in `op.data`: strings pass through unchanged (backward compatible with every
|
|
996
|
+
* existing operation), binary values become the tagged base64 form.
|
|
997
|
+
*/
|
|
998
|
+
declare function encodeBytesForOpData(value: string | Uint8Array | ArrayBuffer): string | KoraBytesValue;
|
|
999
|
+
/**
|
|
1000
|
+
* Reverse of {@link encodeBytesForOpData}, tolerant of every shape a binary
|
|
1001
|
+
* op-data value has ever taken: canonical strings and tagged bytes, in-memory
|
|
1002
|
+
* Uint8Array/ArrayBuffer (ops that never round-tripped through JSON), and
|
|
1003
|
+
* pre-fix numeric-key objects.
|
|
1004
|
+
*/
|
|
1005
|
+
declare function decodeBytesFromOpData(value: unknown): string | Uint8Array;
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* Input shape for defineSchema() — what the developer writes.
|
|
1009
|
+
*/
|
|
1010
|
+
interface SchemaInput {
|
|
1011
|
+
version: number;
|
|
1012
|
+
collections: Record<string, CollectionInput>;
|
|
1013
|
+
relations?: Record<string, RelationInput>;
|
|
1014
|
+
/** Schema migrations keyed by target version number. */
|
|
1015
|
+
migrations?: Record<number, MigrationDefinition>;
|
|
1016
|
+
/**
|
|
1017
|
+
* Declarative partial-sync rules.
|
|
1018
|
+
*
|
|
1019
|
+
* @example
|
|
1020
|
+
* ```typescript
|
|
1021
|
+
* sync: {
|
|
1022
|
+
* todos: { where: { userId: true, orgId: true } },
|
|
1023
|
+
* projects: { where: { orgId: true } },
|
|
1024
|
+
* }
|
|
1025
|
+
* ```
|
|
1026
|
+
*/
|
|
1027
|
+
sync?: Record<string, SyncRuleInput>;
|
|
1028
|
+
}
|
|
1029
|
+
/**
|
|
1030
|
+
* Developer input for a collection sync rule.
|
|
1031
|
+
*/
|
|
1032
|
+
interface SyncRuleInput {
|
|
1033
|
+
/**
|
|
1034
|
+
* Field filters bound to scope values.
|
|
1035
|
+
* Use `true` to bind a field to a scope value with the same name.
|
|
1036
|
+
* Use a string to bind to a different scope value key.
|
|
1037
|
+
*/
|
|
1038
|
+
where: Record<string, boolean | string>;
|
|
1039
|
+
}
|
|
1040
|
+
interface StateMachineInput {
|
|
1041
|
+
/** The enum field this state machine controls */
|
|
1042
|
+
field: string;
|
|
1043
|
+
/** Map of state to allowed next states */
|
|
1044
|
+
transitions: Record<string, string[]>;
|
|
1045
|
+
/** What to do when an invalid transition is attempted */
|
|
1046
|
+
onInvalidTransition: 'reject' | 'last-valid-state';
|
|
1047
|
+
}
|
|
1048
|
+
interface CollectionInput {
|
|
1049
|
+
fields: Record<string, FieldBuilder>;
|
|
1050
|
+
indexes?: string[];
|
|
1051
|
+
constraints?: ConstraintInput[];
|
|
1052
|
+
resolve?: Record<string, CustomResolver>;
|
|
1053
|
+
/** Scope fields for sync filtering. Only records matching the client's scope values are synced. */
|
|
1054
|
+
scope?: string[];
|
|
1055
|
+
/** State machine definition constraining transitions on an enum field */
|
|
1056
|
+
stateMachine?: StateMachineInput;
|
|
1057
|
+
}
|
|
1058
|
+
interface ConstraintInput {
|
|
1059
|
+
type: 'unique' | 'capacity' | 'referential';
|
|
1060
|
+
fields: string[];
|
|
1061
|
+
where?: Record<string, unknown>;
|
|
1062
|
+
onConflict: 'first-write-wins' | 'last-write-wins' | 'priority-field' | 'server-decides' | 'custom';
|
|
1063
|
+
priorityField?: string;
|
|
1064
|
+
resolve?: (local: unknown, remote: unknown, base: unknown) => unknown;
|
|
1065
|
+
}
|
|
1066
|
+
interface RelationInput {
|
|
1067
|
+
from: string;
|
|
1068
|
+
to: string;
|
|
1069
|
+
type: 'one-to-one' | 'one-to-many' | 'many-to-one' | 'many-to-many';
|
|
1070
|
+
field: string;
|
|
1071
|
+
onDelete: 'cascade' | 'set-null' | 'restrict' | 'no-action';
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Validates and builds a SchemaDefinition from developer input.
|
|
1075
|
+
* This is the primary developer-facing function for defining a schema.
|
|
1076
|
+
*
|
|
1077
|
+
* @param input - The schema definition using type builders
|
|
1078
|
+
* @returns A validated SchemaDefinition ready for use by the framework
|
|
1079
|
+
* @throws {SchemaValidationError} If the schema is invalid
|
|
1080
|
+
*
|
|
1081
|
+
* @example
|
|
1082
|
+
* ```typescript
|
|
1083
|
+
* import { defineSchema, t } from '@korajs/core'
|
|
1084
|
+
*
|
|
1085
|
+
* const schema = defineSchema({
|
|
1086
|
+
* version: 1,
|
|
1087
|
+
* collections: {
|
|
1088
|
+
* todos: {
|
|
1089
|
+
* fields: {
|
|
1090
|
+
* title: t.string(),
|
|
1091
|
+
* completed: t.boolean().default(false),
|
|
1092
|
+
* }
|
|
1093
|
+
* }
|
|
1094
|
+
* }
|
|
1095
|
+
* })
|
|
1096
|
+
* ```
|
|
1097
|
+
*/
|
|
1098
|
+
/**
|
|
1099
|
+
* Schema definition with a phantom type brand preserving the original input shape.
|
|
1100
|
+
* The `__input` property exists only at the type level for inference — no runtime cost.
|
|
1101
|
+
*/
|
|
1102
|
+
type TypedSchemaDefinition<T extends SchemaInput = SchemaInput> = SchemaDefinition & {
|
|
1103
|
+
readonly __input: T;
|
|
1104
|
+
};
|
|
1105
|
+
declare function defineSchema<const T extends SchemaInput>(input: T): TypedSchemaDefinition<T>;
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* Quote a SQL identifier (table or column name) for safe interpolation into
|
|
1109
|
+
* generated SQL.
|
|
1110
|
+
*
|
|
1111
|
+
* Uses standard double-quote quoting, which both SQLite and PostgreSQL honor,
|
|
1112
|
+
* and doubles any embedded double-quote per the SQL standard. Quoting is what
|
|
1113
|
+
* lets a valid JavaScript identifier — camelCase (`formResponses`), PascalCase
|
|
1114
|
+
* (`UserProfiles`), or a word that happens to be a SQL keyword (`order`,
|
|
1115
|
+
* `select`) — round-trip through generated DDL and queries without ever
|
|
1116
|
+
* producing invalid or ambiguous SQL.
|
|
1117
|
+
*
|
|
1118
|
+
* Schema validation (see `validateCollectionName` / `validateFieldName`)
|
|
1119
|
+
* already restricts identifiers to `[A-Za-z][A-Za-z0-9_]*`, so the escape here
|
|
1120
|
+
* never actually fires in practice; it is defense in depth so this helper is
|
|
1121
|
+
* correct for any input rather than only for pre-validated names.
|
|
1122
|
+
*
|
|
1123
|
+
* Consistency is the contract: every path that emits an identifier for a
|
|
1124
|
+
* user-defined collection or field MUST go through this helper, because a
|
|
1125
|
+
* quoted `CREATE TABLE "order"` paired with an unquoted `SELECT ... FROM order`
|
|
1126
|
+
* would reintroduce the exact keyword-collision bug this guards against.
|
|
1127
|
+
*
|
|
1128
|
+
* @param name - The raw identifier (collection name, field/column name).
|
|
1129
|
+
* @returns The identifier wrapped in double quotes, ready to splice into SQL.
|
|
1130
|
+
*
|
|
1131
|
+
* @example
|
|
1132
|
+
* ```typescript
|
|
1133
|
+
* quoteIdent('formResponses') // => '"formResponses"'
|
|
1134
|
+
* quoteIdent('order') // => '"order"'
|
|
1135
|
+
* ```
|
|
1136
|
+
*/
|
|
1137
|
+
declare function quoteIdent(name: string): string;
|
|
1138
|
+
|
|
1139
|
+
/**
|
|
1140
|
+
* Validates a record's data against a collection's field definitions.
|
|
1141
|
+
* Applies defaults, rejects auto fields, and type-checks each value.
|
|
1142
|
+
*
|
|
1143
|
+
* @param collection - The collection name (for error messages)
|
|
1144
|
+
* @param collectionDef - The collection definition from the schema
|
|
1145
|
+
* @param data - The record data to validate
|
|
1146
|
+
* @param operationType - The operation type ('insert', 'update', 'delete')
|
|
1147
|
+
* @returns The validated and normalized data (with defaults applied)
|
|
1148
|
+
* @throws {SchemaValidationError} If validation fails
|
|
1149
|
+
*/
|
|
1150
|
+
declare function validateRecord(collection: string, collectionDef: CollectionDefinition, data: Record<string, unknown>, operationType: OperationType): Record<string, unknown>;
|
|
1151
|
+
/**
|
|
1152
|
+
* The domain check of one resolved field value (value-domain.ts), for values produced
|
|
1153
|
+
* after validation: an atomic op's resolved result (`op.increment(0.5)` on a timestamp,
|
|
1154
|
+
* an increment past the largest finite number).
|
|
1155
|
+
*
|
|
1156
|
+
* @param collection - The collection (for the message)
|
|
1157
|
+
* @param fieldName - The field
|
|
1158
|
+
* @param descriptor - The field's descriptor
|
|
1159
|
+
* @param value - The resolved value
|
|
1160
|
+
* @throws {SchemaValidationError} When the value is outside the field's domain
|
|
1161
|
+
*/
|
|
1162
|
+
declare function assertResolvedFieldValue(collection: string, fieldName: string, descriptor: FieldDescriptor, value: unknown): void;
|
|
1163
|
+
|
|
1164
|
+
/**
|
|
1165
|
+
* One value domain (RT-86, RT-87): every value the local API accepts must be storable and
|
|
1166
|
+
* transmissible, unchanged, by every built-in store (client SQLite and IndexedDB; server
|
|
1167
|
+
* memory, SQLite and Postgres) and every transport (JSON and protobuf). The domain is
|
|
1168
|
+
* defined here once, enforced where values are written (`validateRecord`, after atomic
|
|
1169
|
+
* ops resolve) and re-checked by the server on ingest (`operationValueViolation`), so a
|
|
1170
|
+
* value outside it is refused with a clear error before anything stores it, never by a
|
|
1171
|
+
* database half-way through a sync.
|
|
1172
|
+
*
|
|
1173
|
+
* | Field type | Domain | Client SQLite / IndexedDB | Server SQLite | Server Postgres | Wire (JSON / protobuf) |
|
|
1174
|
+
* |----------------|-----------------------------------------------------------|---------------------------|---------------|--------------------------|------------------------|
|
|
1175
|
+
* | `string` | any string (U+0000 and lone surrogates included) | TEXT / string | TEXT | TEXT, lossless text codec (RT-65) | JSON string (escaped) |
|
|
1176
|
+
* | `enum` | one of the declared values | TEXT / string | TEXT | TEXT | JSON string |
|
|
1177
|
+
* | `secret` | string (stored hashed or encrypted) | TEXT | TEXT | TEXT | JSON string |
|
|
1178
|
+
* | `number` | finite double; `-0` is `0` | REAL / number | REAL | DOUBLE PRECISION | JSON number |
|
|
1179
|
+
* | `boolean` | `true` / `false` | INTEGER 0/1 / boolean | INTEGER | INTEGER | JSON boolean |
|
|
1180
|
+
* | `timestamp` | integer milliseconds in [-8.64e15, 8.64e15] (the `Date` range; a safe integer). Fractions are refused, not rounded | INTEGER / number | INTEGER | BIGINT | JSON number |
|
|
1181
|
+
* | `array` | dense array of the item kind's domain, nesting <= {@link MAX_VALUE_DEPTH} | TEXT (JSON) / array | TEXT (JSON) | JSONB (text codec) | JSON array |
|
|
1182
|
+
* | `object` | plain object; declared keys in their kind's domain | TEXT (JSON) / object | TEXT (JSON) | JSONB | JSON object |
|
|
1183
|
+
* | `json` | any JSON value: finite numbers, no `__proto__` key, nesting <= {@link MAX_VALUE_DEPTH}, not exactly `{ __kora_bytes__ }` (the wire's binary form) | TEXT (JSON) / value | TEXT (JSON) | JSONB | JSON |
|
|
1184
|
+
* | `blob` | a `BlobRef` | TEXT (JSON) | TEXT | TEXT | JSON object |
|
|
1185
|
+
* | `richtext` | Yjs update bytes (`Uint8Array` / `ArrayBuffer`) or a string | BLOB / bytes | BLOB | BYTEA | `{ $koraBytes }` / bytes |
|
|
1186
|
+
* | any operation | serialized size <= `maxOperationBytes` (default {@link DEFAULT_MAX_OPERATION_BYTES}) | | | | |
|
|
1187
|
+
*
|
|
1188
|
+
* Every value additionally has a canonical JSON form (core canonical-body): no `NaN`,
|
|
1189
|
+
* `±Infinity`, `BigInt`, `Map`, `Set`, class instances or cycles.
|
|
1190
|
+
*/
|
|
1191
|
+
/** Smallest `t.timestamp()` value: the earliest instant a JavaScript `Date` can hold. */
|
|
1192
|
+
declare const TIMESTAMP_MIN_MS = -8640000000000000;
|
|
1193
|
+
/** Largest `t.timestamp()` value: the latest instant a JavaScript `Date` can hold. */
|
|
1194
|
+
declare const TIMESTAMP_MAX_MS = 8640000000000000;
|
|
1195
|
+
/**
|
|
1196
|
+
* Deepest nesting of arrays and objects inside one field value. Postgres parses JSONB
|
|
1197
|
+
* recursively with a stack limit, and every replica folds values recursively; 64 levels
|
|
1198
|
+
* is far beyond any real document.
|
|
1199
|
+
*/
|
|
1200
|
+
declare const MAX_VALUE_DEPTH = 64;
|
|
1201
|
+
/** Default largest serialized operation, shared by the local write path and the server. */
|
|
1202
|
+
declare const DEFAULT_MAX_OPERATION_BYTES: number;
|
|
1203
|
+
/**
|
|
1204
|
+
* Why `value` is not a valid `t.timestamp()` value, or null when it is.
|
|
1205
|
+
*
|
|
1206
|
+
* @param value - The value
|
|
1207
|
+
*/
|
|
1208
|
+
declare function timestampDomainViolation(value: unknown): string | null;
|
|
1209
|
+
/**
|
|
1210
|
+
* The path of the first container nested deeper than `maxDepth`, or null.
|
|
1211
|
+
*
|
|
1212
|
+
* @param value - Any value
|
|
1213
|
+
* @param maxDepth - The deepest allowed nesting of arrays and objects
|
|
1214
|
+
*/
|
|
1215
|
+
declare function valueDepthViolation(value: unknown, maxDepth?: number): string | null;
|
|
1216
|
+
/**
|
|
1217
|
+
* The path of the first own `__proto__` key in a value, or null. JSON can carry such a
|
|
1218
|
+
* key, but most JavaScript code (including object spreads into a fresh `{}` with
|
|
1219
|
+
* assignment) turns it into a prototype and loses it, so it is refused everywhere.
|
|
1220
|
+
*
|
|
1221
|
+
* @param value - Any value
|
|
1222
|
+
*/
|
|
1223
|
+
declare function protoKeyViolation(value: unknown): string | null;
|
|
1224
|
+
/**
|
|
1225
|
+
* Why a field value, as an OPERATION carries it (op-data form: richtext as
|
|
1226
|
+
* `{ $koraBytes }` or a string, secrets in their at-rest string form), is outside the
|
|
1227
|
+
* field's domain, or null when it is inside. The server checks every uploaded and
|
|
1228
|
+
* route-written operation's data with it, so every server store and every peer holds
|
|
1229
|
+
* the same values (RT-86, RT-87). `null` is always accepted (a cleared field).
|
|
1230
|
+
*
|
|
1231
|
+
* @param descriptor - The field's descriptor in the schema that reads the operation
|
|
1232
|
+
* @param value - The value from `data`
|
|
1233
|
+
*/
|
|
1234
|
+
declare function operationValueViolation(descriptor: FieldDescriptor, value: unknown): string | null;
|
|
1235
|
+
/**
|
|
1236
|
+
* Why a json or object field value is reserved by the wire, or null: an object whose
|
|
1237
|
+
* only member is `__kora_bytes__`.
|
|
1238
|
+
*
|
|
1239
|
+
* @param value - A field value
|
|
1240
|
+
*/
|
|
1241
|
+
declare function reservedWireShapeViolation(value: unknown): string | null;
|
|
1242
|
+
/**
|
|
1243
|
+
* Serialized size of an operation in bytes (UTF-8 of its JSON), the measure the server
|
|
1244
|
+
* enforces `maxOperationBytes` with and the local write path checks before a write is
|
|
1245
|
+
* accepted (RT-86).
|
|
1246
|
+
*
|
|
1247
|
+
* @param op - The operation
|
|
1248
|
+
*/
|
|
1249
|
+
declare function measureOperationBytes(op: Operation): number;
|
|
1250
|
+
|
|
1251
|
+
/**
|
|
1252
|
+
* Create an empty version vector.
|
|
1253
|
+
*/
|
|
1254
|
+
declare function createVersionVector(): VersionVector;
|
|
1255
|
+
/**
|
|
1256
|
+
* Merge two version vectors by taking the max sequence number for each node.
|
|
1257
|
+
* This is commutative, associative, and idempotent.
|
|
1258
|
+
*/
|
|
1259
|
+
declare function mergeVectors(a: VersionVector, b: VersionVector): VersionVector;
|
|
1260
|
+
/**
|
|
1261
|
+
* Advance a version vector for a specific node to a new sequence number.
|
|
1262
|
+
* Only advances forward — if the current value is higher, no change is made.
|
|
1263
|
+
*/
|
|
1264
|
+
declare function advanceVector(vector: VersionVector, nodeId: string, seq: number): VersionVector;
|
|
1265
|
+
/**
|
|
1266
|
+
* Returns true if vector `a` dominates vector `b` — meaning `a` has seen
|
|
1267
|
+
* everything `b` has seen. Formally: for every nodeId in b, a[nodeId] >= b[nodeId].
|
|
1268
|
+
*/
|
|
1269
|
+
declare function dominates(a: VersionVector, b: VersionVector): boolean;
|
|
1270
|
+
/**
|
|
1271
|
+
* Returns true if two version vectors are exactly equal.
|
|
1272
|
+
*/
|
|
1273
|
+
declare function vectorsEqual(a: VersionVector, b: VersionVector): boolean;
|
|
1274
|
+
/**
|
|
1275
|
+
* Operation log interface for computing deltas.
|
|
1276
|
+
* getRange may be async (for DB-backed implementations) or sync (for in-memory).
|
|
1277
|
+
*/
|
|
1278
|
+
interface OperationLog {
|
|
1279
|
+
getRange(nodeId: string, fromSeq: number, toSeq: number): Operation[] | Promise<Operation[]>;
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Compute the operations that `local` has but `remote` does not.
|
|
1283
|
+
* Returns operations in causal (topological) order.
|
|
1284
|
+
*
|
|
1285
|
+
* @param localVector - The local version vector
|
|
1286
|
+
* @param remoteVector - The remote version vector
|
|
1287
|
+
* @param operationLog - The operation log to fetch operations from
|
|
1288
|
+
* @returns Operations sorted in causal order
|
|
1289
|
+
*/
|
|
1290
|
+
declare function computeDelta(localVector: VersionVector, remoteVector: VersionVector, operationLog: OperationLog): Promise<Operation[]>;
|
|
1291
|
+
/**
|
|
1292
|
+
* Serialize a version vector to a JSON-compatible string.
|
|
1293
|
+
*/
|
|
1294
|
+
declare function serializeVector(vector: VersionVector): string;
|
|
1295
|
+
/**
|
|
1296
|
+
* Deserialize a version vector from its serialized string form.
|
|
1297
|
+
*/
|
|
1298
|
+
declare function deserializeVector(s: string): VersionVector;
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* Returns true when the schema declares partial sync rules at the root level.
|
|
1302
|
+
*/
|
|
1303
|
+
declare function hasSchemaSyncRules(schema: SchemaDefinition): boolean;
|
|
1304
|
+
/**
|
|
1305
|
+
* Resolve field → scope-value-key bindings for a collection.
|
|
1306
|
+
*
|
|
1307
|
+
* Sync rules take precedence over legacy `collection.scope` arrays.
|
|
1308
|
+
* Returns `null` when the collection has no sync filtering configured.
|
|
1309
|
+
*/
|
|
1310
|
+
declare function getCollectionScopeBindings(schema: SchemaDefinition, collectionName: string): Record<string, string> | null;
|
|
1311
|
+
/**
|
|
1312
|
+
* Returns whether a collection participates in sync filtering for this schema.
|
|
1313
|
+
*/
|
|
1314
|
+
declare function isCollectionSyncScoped(schema: SchemaDefinition, collectionName: string): boolean;
|
|
1315
|
+
/**
|
|
1316
|
+
* Collect unique scope value keys referenced by sync rules and legacy scope fields.
|
|
1317
|
+
*/
|
|
1318
|
+
declare function collectSchemaScopeValueKeys(schema: SchemaDefinition): string[];
|
|
1319
|
+
|
|
1320
|
+
/**
|
|
1321
|
+
* Reserved key in a server scope grant that carries VERIFIED claim values
|
|
1322
|
+
* (for example `{ userId: <jwt sub>, orgId: <from your user store> }`).
|
|
1323
|
+
*
|
|
1324
|
+
* An auth provider usually cannot know the sync schema, so instead of listing
|
|
1325
|
+
* every collection it returns `{ $claims: { userId } }` and the sync server binds
|
|
1326
|
+
* each schema-scoped collection from those values when the session starts. A
|
|
1327
|
+
* collection whose scope bindings cannot all be resolved from the claims is
|
|
1328
|
+
* denied (fail closed), never widened to "everything".
|
|
1329
|
+
*
|
|
1330
|
+
* Collection names must start with a letter, so `$claims` can never collide with
|
|
1331
|
+
* a real collection. Any consumer that does not expand it sees a key that matches
|
|
1332
|
+
* no collection, which is also fail-closed.
|
|
1333
|
+
*/
|
|
1334
|
+
declare const SCOPE_CLAIMS_KEY: "$claims";
|
|
1335
|
+
/**
|
|
1336
|
+
* Build a server scope grant from verified claim values, optionally combined
|
|
1337
|
+
* with explicit per-collection grants. Explicit entries win over claim-derived
|
|
1338
|
+
* bindings for the same collection.
|
|
1339
|
+
*
|
|
1340
|
+
* @param claims - Verified scope values, keyed by the scope binding names your
|
|
1341
|
+
* schema uses (`scope: ['userId']` binds the `userId` value)
|
|
1342
|
+
* @param explicit - Optional explicit per-collection predicates
|
|
1343
|
+
* @returns A scope grant suitable for `AuthContext.scopes`
|
|
1344
|
+
*
|
|
1345
|
+
* @example
|
|
1346
|
+
* ```typescript
|
|
1347
|
+
* return { userId: payload.sub, scopes: claimScopes({ userId: payload.sub, orgId }) }
|
|
1348
|
+
* ```
|
|
1349
|
+
*/
|
|
1350
|
+
declare function claimScopes(claims: Record<string, unknown>, explicit?: ScopeMap): ScopeMap;
|
|
1351
|
+
/**
|
|
1352
|
+
* Read the verified claim values carried by a scope grant, if any.
|
|
1353
|
+
*
|
|
1354
|
+
* @param grant - A scope grant (possibly containing {@link SCOPE_CLAIMS_KEY})
|
|
1355
|
+
* @returns The claim values, or null when the grant has none
|
|
1356
|
+
*/
|
|
1357
|
+
declare function getScopeClaims(grant: ScopeMap | undefined): Record<string, unknown> | null;
|
|
1358
|
+
|
|
1359
|
+
/**
|
|
1360
|
+
* Collect every unique scope field name declared across all collections.
|
|
1361
|
+
*
|
|
1362
|
+
* @deprecated Use {@link collectSchemaScopeValueKeys} instead.
|
|
1363
|
+
*/
|
|
1364
|
+
declare function collectSchemaScopeFields(schema: SchemaDefinition): string[];
|
|
1365
|
+
/**
|
|
1366
|
+
* Extract flat scope values from JWT (or auth) claims using schema scope field names.
|
|
1367
|
+
*
|
|
1368
|
+
* Resolution order for each scope field:
|
|
1369
|
+
* 1. Top-level claim with the same name
|
|
1370
|
+
* 2. Nested `claims.scope[field]` object
|
|
1371
|
+
* 3. `userId` falls back to the standard JWT `sub` claim
|
|
1372
|
+
*
|
|
1373
|
+
* @param schema - Schema with per-collection scope declarations
|
|
1374
|
+
* @param claims - Decoded JWT claims (unverified; client-side scope hints only)
|
|
1375
|
+
* @returns Flat key-value map suitable for {@link buildScopeMap}
|
|
1376
|
+
*/
|
|
1377
|
+
declare function extractScopeValuesFromClaims(schema: SchemaDefinition, claims: Record<string, unknown>): Record<string, unknown>;
|
|
1378
|
+
|
|
1379
|
+
/**
|
|
1380
|
+
* Offline-safe sequence formatting.
|
|
1381
|
+
*
|
|
1382
|
+
* Format tokens:
|
|
1383
|
+
* - `{date}` → YYYYMMDD (current date)
|
|
1384
|
+
* - `{node4}` → first 4 characters of nodeId
|
|
1385
|
+
* - `{node8}` → first 8 characters of nodeId
|
|
1386
|
+
* - `{seq}` → zero-padded counter (default 4 digits)
|
|
1387
|
+
* - `{seq:N}` → zero-padded counter with N digits
|
|
1388
|
+
*
|
|
1389
|
+
* @example
|
|
1390
|
+
* ```typescript
|
|
1391
|
+
* formatSequenceValue('INV-{date}-{node4}-{seq}', 42, 'a1b2c3d4e5f6')
|
|
1392
|
+
* // → "INV-20260508-a1b2-0042"
|
|
1393
|
+
*
|
|
1394
|
+
* formatSequenceValue('ORDER-{seq:6}', 7, 'node-id')
|
|
1395
|
+
* // → "ORDER-000007"
|
|
1396
|
+
* ```
|
|
1397
|
+
*/
|
|
1398
|
+
declare function formatSequenceValue(template: string, counter: number, nodeId: string, now?: Date): string;
|
|
1399
|
+
/**
|
|
1400
|
+
* Default format when none is provided: `{name}-{seq:4}`.
|
|
1401
|
+
*/
|
|
1402
|
+
declare function defaultSequenceFormat(name: string): string;
|
|
1403
|
+
|
|
1404
|
+
/**
|
|
1405
|
+
* Apply registered transforms until the operation matches `targetSchemaVersion`.
|
|
1406
|
+
* Returns null when a transform drops the operation or no path exists.
|
|
1407
|
+
*/
|
|
1408
|
+
declare function applyOperationTransforms(operation: Operation, targetSchemaVersion: number, transforms: readonly OperationTransform[]): Operation | null;
|
|
1409
|
+
|
|
1410
|
+
/**
|
|
1411
|
+
* Thrown when a schema transform breaks its contract: it changed an operation's
|
|
1412
|
+
* identity (id, node, type, collection, record or timestamp), or produced a body with
|
|
1413
|
+
* no canonical JSON form.
|
|
1414
|
+
*/
|
|
1415
|
+
declare class OperationTransformError extends KoraError {
|
|
1416
|
+
constructor(message: string, context: Record<string, unknown>);
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* The operation as a schema reads it: its schema view (transforms at fold time).
|
|
1420
|
+
*
|
|
1421
|
+
* Operations are immutable and content-addressed, so a schema transform never rewrites
|
|
1422
|
+
* a stored operation. Every replica (server stores and devices alike) stores and sends
|
|
1423
|
+
* the operation exactly as its author wrote it, and applies the transform chain only
|
|
1424
|
+
* when it judges or folds the operation, through this one function:
|
|
1425
|
+
* - the server authorizes and validates the view, and its stores fold the view;
|
|
1426
|
+
* - a device folds the view; an operation with no view (no transform path, e.g. one
|
|
1427
|
+
* authored under a NEWER schema than the device's) is kept aside and replayed after
|
|
1428
|
+
* the device upgrades.
|
|
1429
|
+
*
|
|
1430
|
+
* Contract, enforced here:
|
|
1431
|
+
* - transforms are PURE and DETERMINISTIC: the same operation and transforms give the
|
|
1432
|
+
* same view on every replica, at every time (no clock, randomness or I/O). Every
|
|
1433
|
+
* replica must register the same transforms for the schema versions its log holds;
|
|
1434
|
+
* the fold plan fingerprint includes them, so changing a transform re-folds;
|
|
1435
|
+
* - a transform rewrites `data`, `previousData`, `atomicOps` and `schemaVersion` only. A
|
|
1436
|
+
* view whose id, node, type, collection, record or timestamp differs is refused
|
|
1437
|
+
* ({@link OperationTransformError});
|
|
1438
|
+
* - the view's body is canonical (core canonical-body), like any written body.
|
|
1439
|
+
*
|
|
1440
|
+
* Returned unchanged: an operation already at `targetSchemaVersion`, any operation
|
|
1441
|
+
* when no transform is registered (it folds as written), and an encryption envelope the
|
|
1442
|
+
* caller cannot read (`encrypted` set: the server folds its cleartext header as is;
|
|
1443
|
+
* devices transform after decryption).
|
|
1444
|
+
*
|
|
1445
|
+
* @param op - The operation as stored
|
|
1446
|
+
* @param targetSchemaVersion - The schema version of the replica judging or folding it
|
|
1447
|
+
* @param transforms - The registered transforms
|
|
1448
|
+
* @returns The view, or null when a transform drops the operation or no path exists
|
|
1449
|
+
* @throws {OperationTransformError} When a transform breaks the contract above
|
|
1450
|
+
*/
|
|
1451
|
+
declare function operationSchemaView(op: Operation, targetSchemaVersion: number, transforms: readonly OperationTransform[] | undefined): Operation | null;
|
|
1452
|
+
/**
|
|
1453
|
+
* Fingerprint of a transform chain for a target schema version: '' when no transform
|
|
1454
|
+
* is registered (operations fold as written, whatever the target), otherwise the
|
|
1455
|
+
* target version and each transform's versions and source text. Part of the fold plan
|
|
1456
|
+
* fingerprint, so a replica re-folds when its views change.
|
|
1457
|
+
*
|
|
1458
|
+
* @param targetSchemaVersion - The replica's schema version
|
|
1459
|
+
* @param transforms - The registered transforms
|
|
1460
|
+
*/
|
|
1461
|
+
declare function operationTransformsFingerprint(targetSchemaVersion: number, transforms: readonly OperationTransform[] | undefined): string;
|
|
1462
|
+
/**
|
|
1463
|
+
* Thrown when stored operations have a schema version the registered transforms cannot
|
|
1464
|
+
* read (RT-103): starting would fold those operations as absent and silently erase them
|
|
1465
|
+
* from every record they belong to.
|
|
1466
|
+
*/
|
|
1467
|
+
declare class OperationTransformCoverageError extends KoraError {
|
|
1468
|
+
readonly versions: readonly number[];
|
|
1469
|
+
readonly targetSchemaVersion: number;
|
|
1470
|
+
constructor(message: string, versions: readonly number[], targetSchemaVersion: number, context?: Record<string, unknown>);
|
|
1471
|
+
}
|
|
1472
|
+
/**
|
|
1473
|
+
* The stored schema versions the transforms have no path from (RT-103). Mirrors the
|
|
1474
|
+
* path {@link operationSchemaView} follows (`fromVersion` to `toVersion`, at most 32
|
|
1475
|
+
* steps). An empty transform list reads everything (operations fold as written).
|
|
1476
|
+
*
|
|
1477
|
+
* @param storedVersions - Distinct schema versions of the stored operations
|
|
1478
|
+
* @param targetSchemaVersion - The replica's schema version
|
|
1479
|
+
* @param transforms - The registered transforms
|
|
1480
|
+
* @returns Each version with no path and the version whose transform is missing, ascending
|
|
1481
|
+
*/
|
|
1482
|
+
declare function missingTransformPaths(storedVersions: Iterable<number>, targetSchemaVersion: number, transforms: readonly OperationTransform[] | undefined): Array<{
|
|
1483
|
+
version: number;
|
|
1484
|
+
missingFrom: number;
|
|
1485
|
+
}>;
|
|
1486
|
+
/**
|
|
1487
|
+
* Refuse to start a replica whose transforms cannot read operations it stores (RT-103).
|
|
1488
|
+
*
|
|
1489
|
+
* @param storedVersions - Distinct schema versions of the stored operations
|
|
1490
|
+
* @param targetSchemaVersion - The replica's schema version
|
|
1491
|
+
* @param transforms - The registered transforms
|
|
1492
|
+
* @param replica - Names the replica in the message ("server store", "local database")
|
|
1493
|
+
* @throws {OperationTransformCoverageError} When a stored version has no path
|
|
1494
|
+
*/
|
|
1495
|
+
declare function assertOperationTransformCoverage(storedVersions: Iterable<number>, targetSchemaVersion: number, transforms: readonly OperationTransform[] | undefined, replica: string): void;
|
|
1496
|
+
|
|
1497
|
+
/**
|
|
1498
|
+
* Convert migration steps to SQL statements.
|
|
1499
|
+
*
|
|
1500
|
+
* Structural steps (addField, removeField, renameField, addIndex, removeIndex)
|
|
1501
|
+
* produce SQL. Backfill steps are skipped (handled at the application layer
|
|
1502
|
+
* by reading rows and applying the transform function).
|
|
1503
|
+
*
|
|
1504
|
+
* @param steps - The migration steps from a MigrationBuilder
|
|
1505
|
+
* @returns Array of SQL statements for structural changes
|
|
1506
|
+
*/
|
|
1507
|
+
declare function migrationStepsToSQL(steps: readonly MigrationStep[]): string[];
|
|
1508
|
+
/**
|
|
1509
|
+
* Generate SQL statements to roll back a migration.
|
|
1510
|
+
*
|
|
1511
|
+
* Uses the migration's explicit rollback steps if available,
|
|
1512
|
+
* otherwise auto-generates inverse steps from the forward steps.
|
|
1513
|
+
*
|
|
1514
|
+
* Backfill steps in the rollback are skipped (handled at the application layer).
|
|
1515
|
+
*
|
|
1516
|
+
* @param migration - The migration definition to generate rollback SQL for
|
|
1517
|
+
* @returns Array of SQL statements that undo the migration's structural changes
|
|
1518
|
+
*
|
|
1519
|
+
* @example
|
|
1520
|
+
* ```typescript
|
|
1521
|
+
* const migration = migrate()
|
|
1522
|
+
* .addField('todos', 'priority', t.enum(['low', 'medium', 'high']).default('medium'))
|
|
1523
|
+
* .addIndex('todos', 'priority')
|
|
1524
|
+
*
|
|
1525
|
+
* const rollbackSQL = rollbackStepsToSQL(migration)
|
|
1526
|
+
* // ['DROP INDEX IF EXISTS "idx_5_todos_priority"',
|
|
1527
|
+
* // 'ALTER TABLE "todos" DROP COLUMN "priority"']
|
|
1528
|
+
* ```
|
|
1529
|
+
*/
|
|
1530
|
+
declare function rollbackStepsToSQL(migration: MigrationDefinition): string[];
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* A migration that includes both forward (up) and backward (down) steps.
|
|
1534
|
+
* Rollback steps are applied in reverse order of the forward steps.
|
|
1535
|
+
*/
|
|
1536
|
+
interface ReversibleMigration {
|
|
1537
|
+
readonly up: readonly MigrationStep[];
|
|
1538
|
+
readonly down: readonly MigrationStep[];
|
|
1539
|
+
readonly fromVersion: number;
|
|
1540
|
+
readonly toVersion: number;
|
|
1541
|
+
}
|
|
1542
|
+
/**
|
|
1543
|
+
* Error thrown when a migration step cannot be automatically rolled back
|
|
1544
|
+
* and no explicit down step has been provided.
|
|
1545
|
+
*/
|
|
1546
|
+
declare class MigrationRollbackError extends KoraError {
|
|
1547
|
+
constructor(step: MigrationStep);
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* Determines whether a migration step can be automatically rolled back
|
|
1551
|
+
* without explicit developer-provided down steps.
|
|
1552
|
+
*
|
|
1553
|
+
* Auto-rollback is possible when the inverse operation is deterministic:
|
|
1554
|
+
* - addField -> removeField (drop the added column)
|
|
1555
|
+
* - addIndex -> removeIndex (drop the added index)
|
|
1556
|
+
* - removeIndex -> addIndex (re-create the index)
|
|
1557
|
+
* - renameField -> renameField (swap from/to names)
|
|
1558
|
+
*
|
|
1559
|
+
* Steps that CANNOT auto-rollback:
|
|
1560
|
+
* - removeField: the field descriptor is lost (need it to re-create the column)
|
|
1561
|
+
* - backfill: data transforms are not reversible
|
|
1562
|
+
*
|
|
1563
|
+
* @param step - The forward migration step to check
|
|
1564
|
+
* @returns true if the step can be auto-rolled back
|
|
1565
|
+
*/
|
|
1566
|
+
declare function canAutoRollback(step: MigrationStep): boolean;
|
|
1567
|
+
/**
|
|
1568
|
+
* Generates rollback steps for a list of forward migration steps.
|
|
1569
|
+
* Steps are reversed in order (last forward step becomes first rollback step).
|
|
1570
|
+
*
|
|
1571
|
+
* For steps that cannot be auto-rolled back, throws a MigrationRollbackError.
|
|
1572
|
+
* Use canAutoRollback() to check before calling, or provide explicit down steps
|
|
1573
|
+
* via the MigrationBuilder .down() API.
|
|
1574
|
+
*
|
|
1575
|
+
* @param forwardSteps - The forward migration steps to generate rollbacks for
|
|
1576
|
+
* @returns Array of rollback steps in reverse execution order
|
|
1577
|
+
* @throws MigrationRollbackError if any step cannot be auto-rolled back
|
|
1578
|
+
*/
|
|
1579
|
+
declare function generateRollbackSteps(forwardSteps: readonly MigrationStep[]): MigrationStep[];
|
|
1580
|
+
/**
|
|
1581
|
+
* Create a ReversibleMigration from forward steps, explicit down steps, and version info.
|
|
1582
|
+
*
|
|
1583
|
+
* If explicit down steps are provided, they are used as-is.
|
|
1584
|
+
* If no explicit down steps are provided, auto-generation is attempted.
|
|
1585
|
+
*
|
|
1586
|
+
* @param upSteps - The forward migration steps
|
|
1587
|
+
* @param downSteps - Optional explicit rollback steps (overrides auto-generation)
|
|
1588
|
+
* @param fromVersion - The schema version before the migration
|
|
1589
|
+
* @param toVersion - The schema version after the migration
|
|
1590
|
+
* @returns A complete ReversibleMigration
|
|
1591
|
+
* @throws MigrationRollbackError if auto-generation fails and no explicit down steps provided
|
|
1592
|
+
*/
|
|
1593
|
+
declare function createReversibleMigration(upSteps: readonly MigrationStep[], downSteps: readonly MigrationStep[] | null, fromVersion: number, toVersion: number): ReversibleMigration;
|
|
1594
|
+
|
|
1595
|
+
/**
|
|
1596
|
+
* Validates whether a transition from one state to another is allowed
|
|
1597
|
+
* by the given state machine constraint.
|
|
1598
|
+
*
|
|
1599
|
+
* @param constraint - The state machine constraint defining allowed transitions
|
|
1600
|
+
* @param fromValue - The current state value (before the transition)
|
|
1601
|
+
* @param toValue - The target state value (after the transition)
|
|
1602
|
+
* @returns A TransitionValidationResult describing whether the transition is valid
|
|
1603
|
+
*
|
|
1604
|
+
* @example
|
|
1605
|
+
* ```typescript
|
|
1606
|
+
* const constraint: StateMachineConstraint = {
|
|
1607
|
+
* field: 'status',
|
|
1608
|
+
* collection: 'orders',
|
|
1609
|
+
* transitions: {
|
|
1610
|
+
* draft: ['submitted', 'cancelled'],
|
|
1611
|
+
* submitted: ['approved'],
|
|
1612
|
+
* approved: [],
|
|
1613
|
+
* },
|
|
1614
|
+
* }
|
|
1615
|
+
*
|
|
1616
|
+
* const result = validateTransition(constraint, 'draft', 'submitted')
|
|
1617
|
+
* // { valid: true, from: 'draft', to: 'submitted', field: 'status',
|
|
1618
|
+
* // collection: 'orders', allowedTargets: ['submitted', 'cancelled'] }
|
|
1619
|
+
* ```
|
|
1620
|
+
*/
|
|
1621
|
+
declare function validateTransition(constraint: StateMachineConstraint, fromValue: unknown, toValue: unknown): TransitionValidationResult;
|
|
1622
|
+
/**
|
|
1623
|
+
* Extracts all state machine constraints from a schema definition.
|
|
1624
|
+
* Scans every collection for enum fields that have transition rules declared
|
|
1625
|
+
* via the `.transitions()` builder method.
|
|
1626
|
+
*
|
|
1627
|
+
* @param schema - The schema definition to extract constraints from
|
|
1628
|
+
* @returns An array of StateMachineConstraint objects, one per enum field with transitions
|
|
1629
|
+
*
|
|
1630
|
+
* @example
|
|
1631
|
+
* ```typescript
|
|
1632
|
+
* const schema = defineSchema({
|
|
1633
|
+
* version: 1,
|
|
1634
|
+
* collections: {
|
|
1635
|
+
* orders: {
|
|
1636
|
+
* fields: {
|
|
1637
|
+
* status: t.enum(['draft', 'submitted']).transitions({
|
|
1638
|
+
* draft: ['submitted'],
|
|
1639
|
+
* submitted: [],
|
|
1640
|
+
* }),
|
|
1641
|
+
* },
|
|
1642
|
+
* },
|
|
1643
|
+
* },
|
|
1644
|
+
* })
|
|
1645
|
+
*
|
|
1646
|
+
* const constraints = buildStateMachineConstraints(schema)
|
|
1647
|
+
* // [{ field: 'status', collection: 'orders', transitions: { draft: ['submitted'], submitted: [] } }]
|
|
1648
|
+
* ```
|
|
1649
|
+
*/
|
|
1650
|
+
declare function buildStateMachineConstraints(schema: SchemaDefinition): StateMachineConstraint[];
|
|
1651
|
+
/**
|
|
1652
|
+
* Finds the state machine constraint for a specific field in a specific collection,
|
|
1653
|
+
* if one exists.
|
|
1654
|
+
*
|
|
1655
|
+
* @param schema - The schema definition to search
|
|
1656
|
+
* @param collection - The collection name
|
|
1657
|
+
* @param field - The field name
|
|
1658
|
+
* @returns The TransitionMap if the field has transitions declared, or null otherwise
|
|
1659
|
+
*/
|
|
1660
|
+
declare function getTransitionMap(schema: SchemaDefinition, collection: string, field: string): TransitionMap | null;
|
|
1661
|
+
|
|
1662
|
+
/**
|
|
1663
|
+
* Output of the proto definition generator.
|
|
1664
|
+
* Contains the .proto file text, a type mapping, and a JSON descriptor
|
|
1665
|
+
* compatible with protobufjs's `Root.fromJSON()`.
|
|
1666
|
+
*/
|
|
1667
|
+
interface ProtoOutput {
|
|
1668
|
+
/** The generated .proto file content as a string */
|
|
1669
|
+
proto: string;
|
|
1670
|
+
/** TypeScript type map: field name -> protobuf type */
|
|
1671
|
+
typeMap: Map<string, string>;
|
|
1672
|
+
/** JSON descriptor for dynamic protobufjs usage (no .proto file needed) */
|
|
1673
|
+
jsonDescriptor: Record<string, unknown>;
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Generates Protocol Buffer definitions from a Kora schema.
|
|
1677
|
+
*
|
|
1678
|
+
* Produces three outputs:
|
|
1679
|
+
* 1. A `.proto` file string conforming to proto3 syntax
|
|
1680
|
+
* 2. A type map linking Kora field paths to protobuf types
|
|
1681
|
+
* 3. A JSON descriptor for runtime protobufjs usage via `Root.fromJSON()`
|
|
1682
|
+
*
|
|
1683
|
+
* The generated definitions include:
|
|
1684
|
+
* - Per-collection record messages with proper type mappings
|
|
1685
|
+
* - Nested enum types for enum fields
|
|
1686
|
+
* - `KoraOperation` wrapper for the sync wire format
|
|
1687
|
+
* - `OperationBatch` for batched sync transfers
|
|
1688
|
+
* - `HandshakeMessage` / `HandshakeResponse` for sync session initiation
|
|
1689
|
+
* - `Acknowledgment` for delivery confirmation
|
|
1690
|
+
*
|
|
1691
|
+
* @param schema - A validated SchemaDefinition from defineSchema()
|
|
1692
|
+
* @returns ProtoOutput with proto text, type map, and JSON descriptor
|
|
1693
|
+
*
|
|
1694
|
+
* @example
|
|
1695
|
+
* ```typescript
|
|
1696
|
+
* import { defineSchema, t, generateProtoDefinitions } from '@korajs/core'
|
|
1697
|
+
*
|
|
1698
|
+
* const schema = defineSchema({
|
|
1699
|
+
* version: 1,
|
|
1700
|
+
* collections: {
|
|
1701
|
+
* todos: {
|
|
1702
|
+
* fields: {
|
|
1703
|
+
* title: t.string(),
|
|
1704
|
+
* completed: t.boolean().default(false),
|
|
1705
|
+
* }
|
|
1706
|
+
* }
|
|
1707
|
+
* }
|
|
1708
|
+
* })
|
|
1709
|
+
*
|
|
1710
|
+
* const { proto, typeMap, jsonDescriptor } = generateProtoDefinitions(schema)
|
|
1711
|
+
* // proto is a valid .proto file string
|
|
1712
|
+
* // typeMap maps "todos.title" -> "string", "todos.completed" -> "bool"
|
|
1713
|
+
* // jsonDescriptor can be loaded with protobuf.Root.fromJSON()
|
|
1714
|
+
* ```
|
|
1715
|
+
*/
|
|
1716
|
+
declare function generateProtoDefinitions(schema: SchemaDefinition): ProtoOutput;
|
|
1717
|
+
|
|
1718
|
+
export { APPLY_FAILURE_CODES, APPLY_RESULTS, type AdaptedFoldState, AppNotReadyError, type ApplyFailureReason, type ApplyResult, AtomicOp, BlobRef, type BlobRefMetadata, type CanonicalizableBody, CausalTracker, ClockDriftError, CollectionDefinition, type CollectionInput, type ConstraintInput, CustomResolver, DEFAULT_MAX_OPERATION_BYTES, FOLD_RECORD_TRACE_FIELD, FieldBuilder, FieldDescriptor, FoldConfigurationError, FoldFieldVersions, FoldOptions, FoldRecordResult, type FoldSnapshotInput, type FoldSnapshotOptions, FoldState, FoldStateError, FoldTrace, HLCTimestamp, InvalidTimestampError, KORA_ERROR_FIX_SUGGESTIONS, type KoraBytesValue, KoraError, type LegacyBody, MAX_VALUE_DEPTH, MergeConflictError, MergeOpResult, MergeTrace, MigrationDefinition, MigrationRollbackError, MigrationStep, MissingSecretKeyError, NonCanonicalValueError, Operation, OperationError, OperationInput, type OperationLog, OperationTooLargeError, OperationTransform, OperationTransformCoverageError, OperationTransformError, OperationType, type ProtoOutput, RESERVED_NODE_ID_PREFIX, RandomSource, type RecordFieldVersions, type RelationInput, RemoteClockDriftError, type ReplayOperation, type ReversibleMigration, SCOPE_CLAIMS_KEY, SERVER_NODE_ID_PREFIX, STORED_TEXT_ESCAPE, SchemaDefinition, type SchemaInput, SchemaValidationError, ScopeMap, type SecretKeyProvider, StateMachineConstraint, type StateMachineInput, StorageError, SyncError, TIMESTAMP_MAX_MS, TIMESTAMP_MIN_MS, TransitionMap, TransitionValidationResult, type TypedSchemaDefinition, VersionVector, type VersionedReplayOperation, adaptFoldState, advanceVector, applyOperationTransforms, assertOperationTransformCoverage, assertResolvedFieldValue, base64ToBytes, buildStateMachineConstraints, bytesToBase64, canAutoRollback, canonicalValue, canonicalizeLegacyOperation, canonicalizeOperationBody, canonicalizeProvenLegacyClear, claimScopes, collectSchemaScopeFields, collectSchemaScopeValueKeys, computeDelta, createBlobRef, createFoldState, createReversibleMigration, createSnapshotState, createVersionVector, decodeBytesFromOpData, decodeStoredJsonValue, decodeStoredText, decryptSecret, defaultApplyFailureReason, defaultSequenceFormat, defineSchema, deriveSideEffectOpId, deserializeFoldState, deserializeVector, dominates, encodeBytesForOpData, encodeStoredJsonValue, encodeStoredText, encryptSecret, expandFieldVersionedOperations, extractScopeValuesFromClaims, extractTimestamp, foldPlanFingerprint, foldPlanFingerprints, foldRecord, formatSequenceValue, generateProtoDefinitions, generateRollbackSteps, generateUUIDv7, getCollectionScopeBindings, getFoldFieldVersionStrings, getFoldFieldVersions, getKoraErrorFix, getScopeClaims, getTransitionMap, hasSchemaSyncRules, hashBlob, hashSecret, isApplyFailure, isAuthoritativeNodeId, isBlobRef, isCollectionSyncScoped, isFoldStateLive, isKoraBytesValue, isLegacyNumericByteObject, isReservedNodeId, isServerNodeId, isValidUUIDv7, joinStates, materialize, measureOperationBytes, mergeArraySet, mergeOp, mergeVectors, migrationStepsToSQL, mismatchedFoldFields, missingTransformPaths, needsStoredTextEncoding, operationSchemaView, operationTransformsFingerprint, operationValueViolation, protoKeyViolation, quoteIdent, replayFieldVersionsForRecord, replayOperationsForRecord, reservedWireShapeViolation, revealSecret, rollbackStepsToSQL, serializeFoldState, serializeVector, timestampDomainViolation, toMergeTrace, transformSecretFieldsForWrite, validateRecord, validateTransition, valueDepthViolation, vectorsEqual, verifySecret, verifySecretValue };
|