lines-db 0.0.0-stage → 0.15.0

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.
@@ -0,0 +1,874 @@
1
+ import { A as WhereCondition, C as TableConfig, D as ValidationError, E as TableValidationResult, O as ValidationErrorDetail, S as Table, T as TableSchema, _ as JsonlConflictError, a as err, b as StandardSchemaIssue, c as ColumnDefinition, d as IndexDefinition, f as InferInput, g as JsonValue, h as JsonObject, i as Result, j as WriteFilledValues, k as ValidationResult, l as DatabaseConfig, m as JsonArray, n as JsonlSnapshot, o as ok, p as InferOutput, s as unwrap, t as JsonlReader, u as ForeignKeyDefinition, v as JsonlParseError, w as TableDefs, x as StandardSchemaResult, y as StandardSchema } from "./jsonl-reader-CoYEJ9pg.mjs";
2
+ //#region src/sqlite-adapter.d.ts
3
+ /**
4
+ * SQLite adapter for Node.js
5
+ */
6
+ /**
7
+ * Common interface for SQLite database
8
+ */
9
+ interface SQLiteDatabase {
10
+ prepare(sql: string): SQLiteStatement;
11
+ exec(sql: string): void;
12
+ close(): void;
13
+ }
14
+ interface SQLiteStatement {
15
+ run(...params: any[]): {
16
+ changes: number;
17
+ lastInsertRowid: number | bigint;
18
+ };
19
+ get(...params: any[]): any;
20
+ all(...params: any[]): any[];
21
+ }
22
+ //#endregion
23
+ //#region src/database.d.ts
24
+ /**
25
+ * Options for {@link LinesDB.update}
26
+ */
27
+ interface UpdateOptions {
28
+ /** Validate each updated row against the table's schema. Defaults to true */
29
+ validate?: boolean;
30
+ /**
31
+ * Fields to leave to the schema: each updated row stores the value its schema fills in for them, and
32
+ * a write-back removes them from the row's line
33
+ */
34
+ resetToDefault?: readonly string[];
35
+ }
36
+ /**
37
+ * Options for {@link LinesDB.sync}
38
+ */
39
+ interface SyncOptions {
40
+ /**
41
+ * Fields written back to the JSONL file.
42
+ * When provided, only these fields are taken from the database and merged into the matching
43
+ * JSONL line; every other field keeps the value the file already had. An empty list takes no
44
+ * field from the database, so existing lines keep every value they hold - rows added to or
45
+ * removed from the database are still reflected.
46
+ * Defaults to `writeBackFields` from the database config, or writing every field of the row.
47
+ */
48
+ fields?: readonly string[];
49
+ /**
50
+ * Which values the validation schema fills in to write into the file.
51
+ * Defaults to `writeFilledValues` from the database config, or `'all'`.
52
+ */
53
+ writeFilledValues?: WriteFilledValues;
54
+ }
55
+ export declare class LinesDB<Tables extends TableDefs> {
56
+ private db;
57
+ private readonly rowMovesTable;
58
+ private config;
59
+ private schemas;
60
+ private validationSchemas;
61
+ private tables;
62
+ private inTransaction;
63
+ private syncQueue;
64
+ /** The order a table's schema declares its fields in, as the rows it computes list them */
65
+ private keyOrders;
66
+ /** The row each rowid was inserted from, per table loaded with detailed validation */
67
+ private rowOriginsByRowid;
68
+ /**
69
+ * The fields set and reset on each row (by rowid) since its table was last written back: a line
70
+ * holds the fields a user wrote, so only what changed since it was written needs remembering
71
+ */
72
+ private fieldChanges;
73
+ /**
74
+ * The tables raw SQL may have changed since they were last written back: which fields it set is
75
+ * unknown, so their rows are written back whole
76
+ */
77
+ private rawSqlTables;
78
+ /** How many changes each table has seen, which tells a write-back whether one came after it read the rows */
79
+ private changeGenerations;
80
+ /**
81
+ * The lines read, by rowid, that hold a field the table has no column for: kept to write that field
82
+ * back, also once the row's primary key changed and its line can no longer be found by it
83
+ */
84
+ private linesWithUnknownFields;
85
+ /** Whether a transaction's callback has returned and its files are being written back */
86
+ private transactionClosing;
87
+ /** Whether a transaction() call is past its guard but has not begun yet */
88
+ private transactionStarting;
89
+ /** Whether the running call came in through the object the running transaction() callback receives */
90
+ private viaTransactionObject;
91
+ /** Identifies the running transaction, so an object kept from an earlier one is not taken for its own */
92
+ private transactionToken;
93
+ /** The tables changed in the running transaction, or 'all' once raw SQL may have changed any */
94
+ private transactionChanges;
95
+ /** Hash of each JSONL file's content as this database last read or wrote it */
96
+ private fileHashes;
97
+ /**
98
+ * Hash of each JSONL file's content as this database last read or wrote it, kept for a table that
99
+ * failed to load too: unlike fileHashes, it only tells whether a file changed and guards no write
100
+ */
101
+ private observedHashes;
102
+ /** The JSONL files the data directories held when the tables were scanned */
103
+ private scannedJsonlFiles;
104
+ /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
105
+ private schemaFileStates;
106
+ private constructor();
107
+ static create<Tables extends TableDefs>(config: DatabaseConfig<Tables>, dbPath?: string): LinesDB<Tables>;
108
+ /**
109
+ * Initialize database by loading all JSONL files or a specific table
110
+ * Uses dependency resolution to ensure foreign key references are loaded in correct order
111
+ * @param options Optional configuration for initialization
112
+ * @param options.tableName Optional table name to initialize. If not provided, initializes all tables
113
+ * @param options.detailedValidate If true, performs detailed validation by inserting rows one by one to catch constraint violations
114
+ * @param options.transform Optional transform function to apply to rows before validation (only applied to the specified tableName)
115
+ * @returns Result wrapping a ValidationResult with validation status, errors, and warnings
116
+ */
117
+ initialize(options?: {
118
+ tableName?: string;
119
+ detailedValidate?: boolean;
120
+ transform?: (row: JsonObject) => JsonObject;
121
+ }): Promise<Result<ValidationResult, Error>>;
122
+ private initializeInternal;
123
+ private loadTables;
124
+ /**
125
+ * Load a table and its dependencies recursively
126
+ */
127
+ private loadTableWithDependencies;
128
+ /**
129
+ * Find the schema file of a table in schemaDir, or next to the table's JSONL file when unset
130
+ */
131
+ private findTableSchemaFile;
132
+ /**
133
+ * Load a single table from JSONL file
134
+ * @returns Object with loaded status and validation errors
135
+ */
136
+ private loadTable;
137
+ /**
138
+ * Create table in SQLite with constraints and indexes
139
+ */
140
+ private createTable;
141
+ /**
142
+ * Quote table name to handle special characters in SQL
143
+ */
144
+ private quoteTableName;
145
+ /**
146
+ * Quote identifier for SQL statements, escaping embedded quotes
147
+ */
148
+ private quoteIdentifier;
149
+ /**
150
+ * Insert data into table using batch insert (multiple rows per SQL)
151
+ * SQLite has a parameter limit (default 999), so we batch rows accordingly
152
+ * Throws exception if any constraint violation occurs
153
+ */
154
+ private insertData;
155
+ /**
156
+ * Insert data into table one row at a time with detailed error reporting
157
+ * This is used for validation to catch constraint violations
158
+ */
159
+ private insertDataWithDetailedValidation;
160
+ /**
161
+ * Analyze constraint error and extract detailed information
162
+ */
163
+ private analyzeConstraintError;
164
+ /**
165
+ * Validate a deferred foreign key constraint after all tables have been loaded.
166
+ * Used for circular dependency FK validation.
167
+ */
168
+ private validateDeferredForeignKey;
169
+ /**
170
+ * Execute a raw SQL query
171
+ */
172
+ query<T = unknown>(sql: string, params?: (string | number | bigint | null | Uint8Array)[]): Result<T[], Error>;
173
+ private queryInternal;
174
+ /**
175
+ * Execute a SQL query that returns a single row
176
+ */
177
+ queryOne<T = unknown>(sql: string, params?: (string | number | bigint | null | Uint8Array)[]): Result<T | null, Error>;
178
+ private queryOneInternal;
179
+ /**
180
+ * Execute a SQL statement (INSERT, UPDATE, DELETE)
181
+ */
182
+ execute(sql: string, params?: (string | number | bigint | null | Uint8Array)[]): Result<{
183
+ changes: number | bigint;
184
+ lastInsertRowid: number | bigint;
185
+ }, Error>;
186
+ /**
187
+ * Run a caller's SQL, and when it changed rows, write back every table whole: which tables and
188
+ * fields raw SQL changed is unknown, and a query() can change rows with RETURNING too
189
+ */
190
+ private trackRawSql;
191
+ private totalChanges;
192
+ private executeInternal;
193
+ /**
194
+ * Find rows by condition (supports OR/AND with arrays and function filters)
195
+ * If where is not provided, returns all rows
196
+ */
197
+ find<K extends keyof Tables & string>(tableName: K, where?: WhereCondition<Tables[K]>): Result<Tables[K][], Error>;
198
+ private findInternal;
199
+ /**
200
+ * Find a single row by condition (supports OR/AND with arrays and function filters)
201
+ */
202
+ findOne<K extends keyof Tables & string>(tableName: K, where: WhereCondition<Tables[K]>): Result<Tables[K] | null, Error>;
203
+ private findOneInternal;
204
+ /**
205
+ * Deserialize JSON columns in a row
206
+ */
207
+ private deserializeRow;
208
+ /**
209
+ * Validate data using StandardSchema and return the transformed value
210
+ * Note: Only synchronous validation is supported
211
+ */
212
+ private validateAndTransform;
213
+ /**
214
+ * Validate data using StandardSchema (without returning transformed value)
215
+ * Note: Only synchronous validation is supported
216
+ */
217
+ private validateData;
218
+ /**
219
+ * Remember the order a computed row lists its fields in - the order the schema declares them, since
220
+ * that is the order a hook or a validation fills a row in. A sync inserts a key the line did not
221
+ * have at the place this order gives it.
222
+ */
223
+ private recordKeyOrder;
224
+ /**
225
+ * Insert a row into a table with validation
226
+ */
227
+ insert<K extends keyof Tables & string>(tableName: K, data: Tables[K], options?: {
228
+ dataDir?: string;
229
+ }): Result<{
230
+ changes: number | bigint;
231
+ lastInsertRowid: number | bigint;
232
+ }, Error>;
233
+ private insertInternal;
234
+ /**
235
+ * Batch insert rows with validation per record.
236
+ */
237
+ batchInsert<K extends keyof Tables & string>(tableName: K, records: Tables[K][]): Result<{
238
+ changes: number | bigint;
239
+ lastInsertRowid: number | bigint;
240
+ }, Error>;
241
+ private batchInsertInternal;
242
+ /**
243
+ * Update rows in a table with validation (supports OR/AND with arrays)
244
+ * Note: Function filters are not supported for update operations
245
+ * Note: By default, validation is enabled. For partial updates, existing data is fetched
246
+ * and merged before validation. Set options.validate = false to disable validation.
247
+ */
248
+ update<K extends keyof Tables & string>(tableName: K, data: Partial<Tables[K]>, where: WhereCondition<Tables[K]>, options?: UpdateOptions): Result<{
249
+ changes: number | bigint;
250
+ lastInsertRowid: number | bigint;
251
+ }, Error>;
252
+ private updateInternal;
253
+ /**
254
+ * Batch update rows with record-specific values and validation.
255
+ * Each record must include the primary key to identify the target row.
256
+ * Validation runs once per merged record unless explicitly disabled.
257
+ */
258
+ batchUpdate<K extends keyof Tables & string>(tableName: K, records: Array<Partial<Tables[K]> & Record<string, unknown>>, options?: {
259
+ validate?: boolean;
260
+ }): Result<{
261
+ changes: number | bigint;
262
+ lastInsertRowid: number | bigint;
263
+ }, Error>;
264
+ private batchUpdateInternal;
265
+ /**
266
+ * Delete rows from a table (supports OR/AND with arrays)
267
+ * Note: Function filters are not supported for delete operations
268
+ */
269
+ delete<K extends keyof Tables & string>(tableName: K, where: WhereCondition<Tables[K]>): Result<{
270
+ changes: number | bigint;
271
+ lastInsertRowid: number | bigint;
272
+ }, Error>;
273
+ private deleteInternal;
274
+ /**
275
+ * Batch delete rows by primary key.
276
+ */
277
+ batchDelete<K extends keyof Tables & string>(tableName: K, records: Array<Partial<Tables[K]> & Record<string, unknown>>): Result<{
278
+ changes: number | bigint;
279
+ lastInsertRowid: number | bigint;
280
+ }, Error>;
281
+ private batchDeleteInternal;
282
+ /**
283
+ * Normalize value for SQLite
284
+ */
285
+ private normalizeValue;
286
+ /**
287
+ * Build WHERE clause from condition (supports OR/AND with arrays and functions)
288
+ */
289
+ private buildWhereClause;
290
+ /**
291
+ * Apply OR condition with function filters by evaluating each row against the condition
292
+ */
293
+ private applyOrConditionWithFilters;
294
+ /**
295
+ * Check if a row matches an OR/AND condition (recursively)
296
+ */
297
+ private matchesOrCondition;
298
+ /**
299
+ * Apply function filters to rows
300
+ */
301
+ private applyFunctionFilters;
302
+ /**
303
+ * Get table schema
304
+ */
305
+ /**
306
+ * Validate a row against a table's schema, also for a table left out on load because rows failed
307
+ * validation, so a fix can be checked before it is written to the file
308
+ */
309
+ validateRow(tableName: string, row: JsonObject): Result<JsonObject, ValidationError>;
310
+ getSchema(tableName: string): TableSchema | undefined;
311
+ /**
312
+ * Get all table names
313
+ */
314
+ getTableNames(): string[];
315
+ /**
316
+ * A database composed from several data directories is read-only: the rows of its tables have no
317
+ * single file to be written back to
318
+ */
319
+ private hasSeveralDataDirs;
320
+ /**
321
+ * Turn query_only back on before running a caller's SQL, since an earlier call may have run
322
+ * `PRAGMA query_only = OFF`
323
+ */
324
+ /**
325
+ * Refuse SQL that would end a transaction() or lift the read-only mode that holds back writes made
326
+ * through the database while it runs. Looked for in each statement as SQLite reads it, so a `;` or a
327
+ * comment cannot hide one
328
+ */
329
+ private refuseUnsafeSql;
330
+ private isReadOnlyDataSet;
331
+ private enforceReadOnlySql;
332
+ /** Writable, and not while a transaction writes back the rows it has already read */
333
+ private assertMutable;
334
+ /**
335
+ * Refuse a change while a transaction starts or writes its files back: one made while it starts would
336
+ * be written back with rows the transaction may roll back, and one made while it closes would be
337
+ * committed without reaching the files. Also refuse one made through the database itself while the
338
+ * callback runs, which would be committed or rolled back with the transaction unnoticed by its caller
339
+ */
340
+ private refuseWhileTransactionSettles;
341
+ /**
342
+ * Run a query() with the database read-only while a transaction starts or writes its files back.
343
+ * Not refused outright as execute() is: a query that only reads changes nothing the files would miss
344
+ */
345
+ private readOnlyWhileTransactionSettles;
346
+ private assertWritable;
347
+ /**
348
+ * Sync a specific table back to its JSONL file
349
+ * Syncs of the same table run one after another: auto-sync is fire-and-forget, and a write-back
350
+ * that reads the file first must never see a file another sync is halfway through writing.
351
+ */
352
+ private syncTable;
353
+ /**
354
+ * Write a table back to its JSONL file
355
+ * Uses backward transformation when available
356
+ */
357
+ private writeTable;
358
+ /**
359
+ * The rows a table is written back as, laid over the lines of its file; fails when the file changed
360
+ * since this database last read or wrote it
361
+ */
362
+ private prepareWriteBack;
363
+ private prepareFileWriteBack;
364
+ /**
365
+ * Every row of a table in rowid order - the order the file was read in - as stored and as its line
366
+ * would hold it, after the backward transformation
367
+ */
368
+ private readStoredRows;
369
+ /**
370
+ * Narrow each row to the fields a user wrote - the ones its line holds, plus those set since and
371
+ * minus those reset to their default - its primary key and the fields named to be written back, so
372
+ * a value the schema fills in stays out of the file
373
+ */
374
+ private keepWrittenFields;
375
+ private rowidsWhere;
376
+ /**
377
+ * Forget the field changes of deleted rows: a deleted row's rowid can be given to a row inserted
378
+ * later, which must not inherit them
379
+ */
380
+ private moveRowMetadata;
381
+ /** Forget the lines kept for rows that are gone, such as rows raw SQL or a foreign-key action deleted */
382
+ private forgetLinesOfGoneRows;
383
+ private forgetFieldChanges;
384
+ private noteChange;
385
+ private noteFieldChanges;
386
+ /**
387
+ * Store the value the schema fills in for each reset field, as validating the row without the field
388
+ * gives it, and remember the field as reset so it leaves the line
389
+ */
390
+ /** The value the schema fills in for each reset field of each target, validating the row without them */
391
+ private computeResets;
392
+ /** Store the values computeResets gave, and remember the fields as reset so they leave the line */
393
+ private applyResets;
394
+ /**
395
+ * Every row of a table with the fields the schema filled in rather than the file: the ones its line
396
+ * does not hold and no write set, which a write-back leaves out of the file
397
+ */
398
+ findWithDefaults<K extends keyof Tables & string>(tableName: K): Promise<Result<Array<{
399
+ row: Tables[K];
400
+ defaulted: string[];
401
+ }>, Error>>;
402
+ private writePrepared;
403
+ /**
404
+ * Write a table back to its file, or leave it to the running transaction, which writes back the
405
+ * tables it changed once its callback is done
406
+ */
407
+ private afterWrite;
408
+ /**
409
+ * The tables whose rows an ON DELETE / ON UPDATE action can change when a table's rows change,
410
+ * following the actions on to the tables they change in turn
411
+ */
412
+ private tablesChangedByForeignKeyActions;
413
+ private tablesChangedInTransaction;
414
+ /**
415
+ * Write several tables back, checking every file before writing any, so a file changed on disk
416
+ * fails the write-back before it has written part of it
417
+ */
418
+ private writeBackTogether;
419
+ private writeFilesTogether;
420
+ /**
421
+ * Put back every written file, going on past one that cannot be put back, and give the error to
422
+ * throw: the one that made the write-back fail, naming the files left holding what was written
423
+ */
424
+ private restoreAll;
425
+ /**
426
+ * Put back the content a file held before {@link writePrepared} wrote over it. The file is expected
427
+ * to hold that content even when putting it back fails, so a file left holding the written rows
428
+ * counts as changed on disk instead of matching the database
429
+ */
430
+ private restorePrepared;
431
+ /**
432
+ * Lay the rows out over the lines the JSONL file already holds.
433
+ *
434
+ * Rows keep the order the file lists them in - the database returns rows in its own order, and
435
+ * an integer primary key is SQLite's rowid, so writing rows back in query order would reshuffle
436
+ * the file. Rows the file never had follow, in database order.
437
+ *
438
+ * With `fields`, only those fields are taken from the row and every other field keeps the value
439
+ * its line already had, so values a validation hook computed and fields the file omitted are
440
+ * never materialized. Fields this table does not have are simply not written, so one list can
441
+ * cover a directory of tables that do not all share it; a sync asked for a single table by name
442
+ * rejects them instead, since there the caller named both the table and the fields.
443
+ */
444
+ private mergeWithExistingLines;
445
+ /**
446
+ * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
447
+ * Returns undefined when the rows cannot be matched and the caller can do without it.
448
+ */
449
+ private matchExistingRows;
450
+ /**
451
+ * Read the rows a JSONL file currently holds, treating a missing file as empty, and refuse to go on
452
+ * when the file is not the one this database last read or wrote: writing over it would drop the
453
+ * changes made to it since
454
+ */
455
+ private readUnchangedRows;
456
+ /**
457
+ * Tell whether the files the tables were loaded from changed since this database last read or
458
+ * wrote them: a JSONL file was edited, added or removed, or a table's schema file was edited, added
459
+ * or removed. When they did, the database holds rows or a schema the files no longer have; create it
460
+ * again and call initialize() to load the current files.
461
+ */
462
+ hasExternalChanges(): Promise<Result<boolean, Error>>;
463
+ /**
464
+ * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
465
+ * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
466
+ */
467
+ findExternalChanges(): Promise<Result<string[], Error>>;
468
+ private findExternalChangesInternal;
469
+ /** The state of the schema file a state names, for a table whose JSONL file is gone */
470
+ private stateOfKnownSchemaFile;
471
+ private schemaFileState;
472
+ /**
473
+ * Sync database changes back to JSONL files
474
+ * Uses backward transformation when available
475
+ * @param tableName Optional table name to sync. If not provided, syncs all loaded tables
476
+ * @param options Optional sync options, e.g. the fields to write back
477
+ */
478
+ sync(tableName?: string, options?: SyncOptions): Promise<Result<void, Error>>;
479
+ private syncInternal;
480
+ /**
481
+ * Execute a function within a transaction
482
+ * Automatically commits on success or rolls back on error.
483
+ *
484
+ * Note: `tx` (the argument `fn` receives) is the same Result-returning API as `this` - a failed
485
+ * `tx.insert()`/`tx.update()`/etc. inside `fn` does not throw and therefore does not roll back the
486
+ * transaction on its own. To abort on such a failure, check the Result and `throw result.error`
487
+ * (or any error) from `fn`; only a thrown error rolls the transaction back.
488
+ */
489
+ transaction<T>(fn: (tx: LinesDB<Tables>) => Promise<T> | T): Promise<Result<T, Error>>;
490
+ /**
491
+ * The object a transaction() callback receives. Calls on it are marked as the transaction's own for as
492
+ * long as they run; a write made through the database itself in the meantime is refused, since writes are
493
+ * synchronous and cannot be queued until the transaction ends
494
+ */
495
+ private scopedToTransaction;
496
+ /**
497
+ * Wait for every queued sync to finish, so a fire-and-forget auto-sync is not dropped
498
+ */
499
+ private waitForPendingSyncs;
500
+ /**
501
+ * Close the database connection
502
+ */
503
+ close(): Promise<Result<void, Error>>;
504
+ /**
505
+ * Get a handle for running SQL on the underlying SQLite database. It wraps the connection rather than
506
+ * being it, also outside a transaction: while a transaction() callback runs, SQL that changes rows is
507
+ * refused unless the handle came from the callback's `tx`, and SQL that would end the transaction is
508
+ * refused for every handle. Outside a transaction it runs SQL unchanged.
509
+ */
510
+ getDb(): SQLiteDatabase;
511
+ }
512
+ //#endregion
513
+ //#region src/jsonl-writer.d.ts
514
+ export declare class JsonlWriter {
515
+ /**
516
+ * Write data to JSONL file
517
+ */
518
+ static write(filePath: string, data: JsonObject[]): Promise<void>;
519
+ /**
520
+ * The content {@link write} writes for the data
521
+ */
522
+ static serialize(data: JsonObject[]): string;
523
+ /**
524
+ * Append data to JSONL file
525
+ */
526
+ static append(filePath: string, data: JsonObject[]): Promise<void>;
527
+ }
528
+ //#endregion
529
+ //#region src/merge-fields.d.ts
530
+ /**
531
+ * Options for {@link mergeFields}
532
+ */
533
+ interface MergeFieldsOptions {
534
+ /**
535
+ * Fields taken from the computed row. Every other field keeps the value the line holds.
536
+ * A field the computed row has no value for is not written, so the line keeps what it has rather
537
+ * than having a null written over it.
538
+ */
539
+ fields: readonly string[];
540
+ /**
541
+ * The order fields are declared in, used to place a field the line did not have.
542
+ * Defaults to the order the computed row lists its own fields in - a row a schema computed lists
543
+ * them the way that schema declares them.
544
+ */
545
+ keyOrder?: Iterable<string>;
546
+ }
547
+ /**
548
+ * Lay the named fields of a computed row over the line a JSONL file already holds.
549
+ *
550
+ * A field the line did not have is inserted where the schema declares it rather than appended, so a
551
+ * filled-in `id` lands at the front of the line the way a hand-written row has it. No key the line
552
+ * already had moves, and a key the schema does not declare stays behind the declared ones.
553
+ *
554
+ * @param line - The row as the JSONL file holds it
555
+ * @param computed - The row a schema computed from it, which the named fields are taken from. Only its
556
+ * own fields count: a field the schema does not produce is left to the line even when a name like
557
+ * `toString` would resolve to something on `Object.prototype`. A field it holds as `undefined` is
558
+ * left to the line as well.
559
+ * @param options - The fields to take, and the order they are declared in
560
+ * @returns A new row: the line, with the named fields written into it
561
+ *
562
+ * @example
563
+ * // line: {"name":"Alice","note":"check"}
564
+ * // computed: {"id":"018f…","name":"Alice","createdAt":"2026-…"}
565
+ * mergeFields(line, computed, { fields: ['id', 'createdAt'] });
566
+ * // {"id":"018f…","name":"Alice","createdAt":"2026-…","note":"check"}
567
+ */
568
+ export declare function mergeFields(line: JsonObject, computed: Record<string, JsonValue | undefined>, options: MergeFieldsOptions): JsonObject;
569
+ //#endregion
570
+ //#region src/fill.d.ts
571
+ /** Computes the values a row gets, from the row as its line holds it */
572
+ type RowFiller = (row: JsonObject) => Record<string, unknown>;
573
+ interface FillFieldsOptions {
574
+ /** A data directory, or one `.jsonl` file in it */
575
+ path: string;
576
+ /** Fields to fill. Defaults to each table's primary key: `primaryKey` in its schema file, or `id` */
577
+ fields?: readonly string[];
578
+ /** Directory the `<Table>.schema.{ts,mts,cts}` files are looked up in. Defaults to the data directory */
579
+ schemaDir?: string;
580
+ /**
581
+ * Builds the function that computes a table's row values from its schema module. Defaults to the
582
+ * value its validation schema (the `schema` or default export) gives a row, after its backward
583
+ * transformation; a row the schema rejects gains nothing. Throwing stops the fill before any file
584
+ * is written.
585
+ */
586
+ loadFiller?: (schemaModule: Record<string, unknown>, context: {
587
+ tableName: string;
588
+ schemaPath: string;
589
+ }) => RowFiller;
590
+ }
591
+ interface FilledFile {
592
+ /** Name of the table, matching the JSONL file name */
593
+ table: string;
594
+ file: string;
595
+ /** The fields written into at least one of its rows */
596
+ fields: string[];
597
+ /** How many rows gained a value */
598
+ count: number;
599
+ }
600
+ interface FillFieldsResult {
601
+ filled: FilledFile[];
602
+ /** Tables without a schema file, so nothing could compute their values */
603
+ tablesWithoutSchema: string[];
604
+ /** The 1-based lines of each file that are not JSON objects, so nothing was filled in there */
605
+ unreadableLines: Array<{
606
+ file: string;
607
+ lines: number[];
608
+ }>;
609
+ /** Fields to fill that no row of any table got a value for */
610
+ unproducedFields: string[];
611
+ }
612
+ /**
613
+ * Fill the named fields into the rows of the JSONL files that have no value for them, with the values
614
+ * each table computes for a row. A value already in the file is never replaced, and a line that gains
615
+ * nothing is left byte for byte; a line that does gain a value is written with its keys in the order
616
+ * the computed row lists them. Every value is computed before any file is written.
617
+ */
618
+ export declare function fillFields(options: FillFieldsOptions): Promise<Result<FillFieldsResult, Error>>;
619
+ //#endregion
620
+ //#region src/schema-loader.d.ts
621
+ export declare class SchemaLoader {
622
+ /**
623
+ * Check if a schema file exists for a table
624
+ */
625
+ static hasSchema(jsonlPath: string, schemaDir?: string): Promise<boolean>;
626
+ /**
627
+ * Load a validation schema file for a table
628
+ * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
629
+ */
630
+ static loadSchema(jsonlPath: string, schemaDir?: string): Promise<StandardSchema>;
631
+ /**
632
+ * Check if an object implements the StandardSchema interface
633
+ */
634
+ private static isStandardSchema;
635
+ }
636
+ //#endregion
637
+ //#region src/directory-scanner.d.ts
638
+ export declare class DirectoryScanner {
639
+ /**
640
+ * Scan directories for JSONL files and create table configurations.
641
+ * A table found in several directories lists its files in the order the directories are given.
642
+ */
643
+ static scanDirectory(dataDir: string | readonly string[]): Promise<Map<string, TableConfig>>;
644
+ }
645
+ //#endregion
646
+ //#region src/schema.d.ts
647
+ /**
648
+ * Schema options for defining constraints and indexes
649
+ * When Input and Output types differ, backward transformation is required
650
+ */
651
+ type SchemaOptions<Input extends Table, Output extends Table> = {
652
+ /**
653
+ * Primary key column
654
+ */
655
+ primaryKey?: string;
656
+ /**
657
+ * Foreign key constraints
658
+ */
659
+ foreignKeys?: ForeignKeyDefinition[];
660
+ /**
661
+ * Indexes to create
662
+ */
663
+ indexes?: IndexDefinition[];
664
+ } & (Output extends Input ? {
665
+ /**
666
+ * Backward transformation from Output to Input (optional when output is substitutable for input)
667
+ */
668
+ backward?: (output: Output) => Input;
669
+ } : {
670
+ /**
671
+ * Backward transformation from Output to Input (REQUIRED when types differ)
672
+ */
673
+ backward: (output: Output) => Input;
674
+ });
675
+ /**
676
+ * BiDirectional Schema interface
677
+ * Extends StandardSchema with optional backward transformation and schema metadata
678
+ */
679
+ interface BiDirectionalSchema<Input extends Table = Table, Output extends Table = Input> extends StandardSchema<Input, Output> {
680
+ /**
681
+ * Backward transformation from Output to Input
682
+ * Required when Input and Output types differ (e.g., with transformations)
683
+ */
684
+ backward?: (output: Output) => Input;
685
+ /**
686
+ * Primary key column
687
+ */
688
+ primaryKey?: string;
689
+ /**
690
+ * Foreign key constraints
691
+ */
692
+ foreignKeys?: ForeignKeyDefinition[];
693
+ /**
694
+ * Indexes to create
695
+ */
696
+ indexes?: IndexDefinition[];
697
+ }
698
+ /**
699
+ * Define a bidirectional schema with optional backward transformation
700
+ *
701
+ * @param schema - Standard Schema for validation
702
+ * @param options - SchemaOptions object. When Input and Output types differ, backward transformation is required
703
+ *
704
+ * @example
705
+ * // No transformation - backward not needed
706
+ * const schema = defineSchema(
707
+ * v.object({ id: v.number(), name: v.string() })
708
+ * );
709
+ *
710
+ * @example
711
+ * // With transformation - backward REQUIRED
712
+ * const schema = defineSchema(
713
+ * v.pipe(v.string(), v.transform(Number)),
714
+ * {
715
+ * backward: (num) => String(num) // backward: number → string (REQUIRED)
716
+ * }
717
+ * );
718
+ *
719
+ * @example
720
+ * // With primary key and foreign key
721
+ * const schema = defineSchema(
722
+ * v.object({ id: v.number(), customerId: v.number() }),
723
+ * {
724
+ * primaryKey: 'id',
725
+ * foreignKeys: [
726
+ * { column: 'customerId', references: { table: 'users', column: 'id' } }
727
+ * ]
728
+ * }
729
+ * );
730
+ */
731
+ export declare function defineSchema<Input extends Table, Output extends Table>(schema: StandardSchema<Input, Output>, ...args: Output extends Input ? [options?: SchemaOptions<Input, Output>] : [options: SchemaOptions<Input, Output>]): BiDirectionalSchema<Input, Output>;
732
+ /**
733
+ * Check if a schema has backward transformation
734
+ */
735
+ export declare function hasBackward<Input extends Table, Output extends Table>(schema: StandardSchema<Input, Output>): schema is BiDirectionalSchema<Input, Output>;
736
+ //#endregion
737
+ //#region src/type-generator.d.ts
738
+ interface TypeGeneratorOptions {
739
+ dataDir: string;
740
+ projectRoot?: string;
741
+ output?: string;
742
+ }
743
+ export declare class TypeGenerator {
744
+ private dataDir;
745
+ private projectRoot;
746
+ private outputFile;
747
+ private dataDirPath;
748
+ constructor(options: TypeGeneratorOptions);
749
+ /**
750
+ * Generate types file from JSONL files and their optional schema files.
751
+ */
752
+ generate(): Promise<string>;
753
+ /**
754
+ * Find all *.jsonl files and check if they have corresponding *.schema.ts files
755
+ */
756
+ private findTables;
757
+ /**
758
+ * Generate type declaration content
759
+ */
760
+ private generateTypeDeclarations;
761
+ private createSchemaIdentifier;
762
+ private formatTableKey;
763
+ }
764
+ //#endregion
765
+ //#region src/jsonl-migration.d.ts
766
+ interface TableValidationOptions {
767
+ dataDir: string;
768
+ tableName: string;
769
+ rows: JsonObject[];
770
+ }
771
+ /**
772
+ * Validate a table by temporarily supplying in-memory rows while reusing the existing LinesDB validation pipeline.
773
+ * If validation fails, throws an error with validation details.
774
+ */
775
+ export declare function ensureTableRowsValid(options: TableValidationOptions): Promise<void>;
776
+ //#endregion
777
+ //#region src/schema-extensions.d.ts
778
+ /**
779
+ * Supported schema file extensions, in priority order.
780
+ * The first match wins when discovering schema files.
781
+ */
782
+ export declare const SCHEMA_EXTENSIONS: readonly [".schema.ts", ".schema.mts", ".schema.cts"];
783
+ type SchemaExtension = (typeof SCHEMA_EXTENSIONS)[number];
784
+ /**
785
+ * Try each supported schema extension and return the full path of the first
786
+ * one that exists on disk. Returns undefined if none is found.
787
+ */
788
+ export declare function findSchemaFile(dir: string, tableName: string): Promise<string | undefined>;
789
+ /**
790
+ * Check if a filename matches any supported schema file pattern.
791
+ */
792
+ export declare function isSchemaFile(fileName: string): boolean;
793
+ /**
794
+ * Extract table name from a schema filename.
795
+ * e.g., "users.schema.ts" -> "users", "users.schema.mts" -> "users"
796
+ */
797
+ export declare function extractTableNameFromSchemaFile(fileName: string): string | null;
798
+ /**
799
+ * Rewrite a TypeScript path to its JavaScript counterpart for ESM imports.
800
+ * ".schema.ts" -> ".schema.js", ".schema.mts" -> ".schema.mjs", ".schema.cts" -> ".schema.cjs"
801
+ */
802
+ export declare function rewriteExtensionForImport(filePath: string): string;
803
+ //#endregion
804
+ //#region src/error-formatter.d.ts
805
+ interface ValidationErrorInfo {
806
+ file: string;
807
+ rowIndex: number;
808
+ issues: ReadonlyArray<StandardSchemaIssue>;
809
+ data?: unknown;
810
+ originalData?: unknown;
811
+ }
812
+ interface ForeignKeyErrorInfo {
813
+ file: string;
814
+ rowIndex: number;
815
+ column: string;
816
+ value: unknown;
817
+ referencedTable: string;
818
+ referencedColumn: string;
819
+ data?: unknown;
820
+ }
821
+ interface ErrorFormatterOptions {
822
+ verbose?: boolean;
823
+ }
824
+ export declare class ErrorFormatter {
825
+ private verbose;
826
+ constructor(options?: ErrorFormatterOptions);
827
+ /**
828
+ * Format validation errors
829
+ */
830
+ formatValidationErrors(errors: ValidationErrorInfo[]): string;
831
+ /**
832
+ * Format foreign key error
833
+ */
834
+ formatForeignKeyError(error: ForeignKeyErrorInfo): string;
835
+ /**
836
+ * Format compact (default) validation errors
837
+ */
838
+ private formatValidationErrorsCompact;
839
+ /**
840
+ * Format verbose validation errors
841
+ */
842
+ private formatValidationErrorsVerbose;
843
+ /**
844
+ * Format compact foreign key error
845
+ */
846
+ private formatForeignKeyErrorCompact;
847
+ /**
848
+ * Format verbose foreign key error
849
+ */
850
+ private formatForeignKeyErrorVerbose;
851
+ /**
852
+ * Get field path from issue
853
+ */
854
+ private getFieldPath;
855
+ /**
856
+ * Format error header with count
857
+ */
858
+ formatErrorHeader(count: number, file?: string): string;
859
+ /**
860
+ * Format migration failure header
861
+ */
862
+ formatMigrationFailureHeader(): string;
863
+ }
864
+ //#endregion
865
+ //#region src/runtime.d.ts
866
+ /**
867
+ * Runtime detection utilities
868
+ */
869
+ type RuntimeEnvironment = 'node' | 'unknown';
870
+ export declare function detectRuntime(): RuntimeEnvironment;
871
+ export declare const RUNTIME: RuntimeEnvironment;
872
+ //#endregion
873
+ export { type BiDirectionalSchema, type ColumnDefinition, type DatabaseConfig, type ErrorFormatterOptions, type FillFieldsOptions, type FillFieldsResult, type FilledFile, type ForeignKeyDefinition, type ForeignKeyErrorInfo, type IndexDefinition, type InferInput, type InferOutput, type JsonArray, type JsonObject, type JsonValue, type JsonlConflictError, type JsonlParseError, JsonlReader, type JsonlSnapshot, type MergeFieldsOptions, type Result, type RowFiller, type RuntimeEnvironment, type SQLiteDatabase, type SQLiteStatement, type SchemaExtension, type SchemaOptions, type StandardSchema, type StandardSchemaIssue, type StandardSchemaResult, type SyncOptions, type Table, type TableConfig, type TableDefs, type TableSchema, type TableValidationOptions, type TableValidationResult, type TypeGeneratorOptions, type UpdateOptions, type ValidationError, type ValidationErrorDetail, type ValidationErrorInfo, type ValidationResult, type WriteFilledValues, err, ok, unwrap };
874
+ //# sourceMappingURL=index.d.mts.map