@lunora/sql-store 1.0.0-alpha.214 → 1.0.0-alpha.215

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/index.d.mts +260 -4
  2. package/dist/index.d.ts +260 -4
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/OCC_VERSION_COLUMN-ByC64Jgx.mjs +1 -0
  5. package/dist/packem_shared/{SEARCH_STATE_TABLE-Dw9zY5R8.mjs → SEARCH_STATE_TABLE-noI80gFQ.mjs} +1 -1
  6. package/dist/packem_shared/backfillSqlSearchIndexes-BYfsAIee.mjs +1 -0
  7. package/dist/packem_shared/createSqlCtxDb-Cy7Dvrk9.mjs +7 -0
  8. package/dist/packem_shared/ctx-db-search-B4wC-Jrm.mjs +1 -0
  9. package/dist/packem_shared/ctx-db-search-state-Dt0iNPGb.mjs +1 -0
  10. package/dist/packem_shared/{decodeBigint-prUTsk6p.mjs → decodeBigint-BZku9YxY.mjs} +1 -1
  11. package/dist/packem_shared/decodeGlobalRow-kOyx0SBl.mjs +1 -0
  12. package/dist/packem_shared/exportSqlGlobalRows-BI_ZxPQU.mjs +1 -0
  13. package/dist/packem_shared/facetSqlGlobalColumn-Col-9Hcc.mjs +1 -0
  14. package/dist/packem_shared/{runSqlAggregateMigrations-CTaYuZh9.mjs → runSqlAggregateMigrations-lP0mwd-W.mjs} +1 -1
  15. package/dist/packem_shared/runSqlGlobalTableMigrations-DMC5hXJo.mjs +1 -0
  16. package/dist/packem_shared/sql-exec-BKz380dy.mjs +1 -0
  17. package/dist/packem_shared/{value-codec-CiS1h_97.mjs → value-codec-C52YW-Do.mjs} +1 -1
  18. package/package.json +2 -2
  19. package/dist/packem_shared/backfillSqlSearchIndexes-BW2vP7-P.mjs +0 -1
  20. package/dist/packem_shared/createSqlCtxDb-CwgVezf1.mjs +0 -7
  21. package/dist/packem_shared/ctx-db-search-gBXL6_Ra.mjs +0 -1
  22. package/dist/packem_shared/ctx-db-search-state-BYatr_oi.mjs +0 -1
  23. package/dist/packem_shared/decodeGlobalRow-C0NS-YZn.mjs +0 -1
  24. package/dist/packem_shared/runSqlGlobalTableMigrations-6cXUbFbj.mjs +0 -1
  25. package/dist/packem_shared/sql-exec-DBWZFC7S.mjs +0 -1
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { TableDefinitionLike, ServerDefaultContextLike, DatabaseWriterLike, CrossShardReadArgs, QueryPage, SchedulerLike, SchemaLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
1
+ import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
2
2
  import { SqlRunResult, SqlDialect } from "./dialect.mjs";
3
3
  export type { SqlExec } from "./dialect.mjs";
4
4
  import 'drizzle-orm';
@@ -28,6 +28,98 @@ interface SqlCtxExec {
28
28
  * correct on SQLite, Postgres and MySQL.
29
29
  */
30
30
  declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
31
+ /** One exported row: `doc` is reconstructed from the column tuple. */
32
+ interface ExportRow {
33
+ doc: Record<string, unknown>;
34
+ /**
35
+ * True physical source line, when the caller has it (e.g. a global row
36
+ * pulled out of an interspersed NDJSON import stream by
37
+ * `@lunora/runtime`'s `import-stream.ts`). When present this overrides the
38
+ * position-derived line below — the caller-side positions of a
39
+ * global-only subset don't line up with the original file once
40
+ * non-global rows have been filtered out. Absent for callers with no
41
+ * physical source to attribute (e.g. a fresh `exportSqlGlobalRows` roundtrip
42
+ * in tests), which keeps the positional fallback.
43
+ */
44
+ line?: number;
45
+ table: string;
46
+ }
47
+ interface ImportError {
48
+ code: string;
49
+ line: number;
50
+ message: string;
51
+ table: string;
52
+ }
53
+ interface ImportResult {
54
+ /** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
55
+ conflicts: number;
56
+ errors: ImportError[];
57
+ inserted: Record<string, number>;
58
+ /** Existing rows overwritten under `onConflict: "replace"`. */
59
+ replaced: number;
60
+ }
61
+ /**
62
+ * Return every `.global()` table in the schema, optionally narrowed by an
63
+ * allowlist. Shard-local tables are skipped here — they're handled by the DO
64
+ * helpers — so callers get a clean separation between the two storage planes.
65
+ */
66
+ declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
67
+ interface ExportGlobalArgs {
68
+ batchSize?: number;
69
+ tables?: ReadonlyArray<string>;
70
+ }
71
+ /**
72
+ * Yield rows from every requested `.global()` table in batches.
73
+ *
74
+ * Keyset-paginates on the physical primary key (`id` — every `.global()` table
75
+ * carries it): `WHERE id > ? ORDER BY id LIMIT n`, carrying the last id forward.
76
+ * A plain `LIMIT/OFFSET` scan would be wrong here — no engine guarantees an
77
+ * order for an unordered SELECT and each page is a separate query, so pages
78
+ * could overlap or skip rows (and any concurrent insert/delete would shift
79
+ * offsets and silently drop/duplicate rows in the snapshot). Keyset paging is
80
+ * deterministic under concurrent writes and avoids O(n^2) OFFSET scans.
81
+ *
82
+ * Tables are provisioned first (idempotent `CREATE … IF NOT EXISTS`): `.global()`
83
+ * tables are created lazily on first write, so a fresh deployment — or any table
84
+ * never written — would otherwise abort the stream with a raw `no such table`
85
+ * instead of exporting it as empty.
86
+ */
87
+ declare const exportSqlGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
88
+ interface ImportGlobalArgs {
89
+ /**
90
+ * Check the rows and report their shape errors, writing nothing. The conflict
91
+ * probe and the insert are skipped, so an `_id` already in use and a foreign-key
92
+ * or unique failure are only found by a real import.
93
+ */
94
+ dryRun?: boolean;
95
+ /**
96
+ * Optional direct exec handle to the same database the writer targets.
97
+ * When supplied, the conflict pre-probe issues a single
98
+ * `SELECT 1 FROM <table> WHERE id = ? LIMIT 1` against the row's declared
99
+ * table instead of falling back to an unscoped id probe, which scans every
100
+ * global table looking for the id. Strongly recommended for large schemas
101
+ * — the writer-fallback is O(N tables) per row.
102
+ */
103
+ exec?: SqlCtxExec;
104
+ /**
105
+ * What a row whose `_id` already exists in its table does: `"skip"` (the
106
+ * default) counts it as a conflict and leaves the stored row unchanged;
107
+ * `"replace"` overwrites the stored row with the snapshot's fields, keeping
108
+ * its `_id` and taking the snapshot's `_creationTime`. A dry run probes
109
+ * nothing, so the mode does not change its answer.
110
+ */
111
+ onConflict?: ImportConflictMode;
112
+ rows: ReadonlyArray<ExportRow>;
113
+ startLine?: number;
114
+ }
115
+ /**
116
+ * Import rows into `.global()` tables via the schema-aware writer. The
117
+ * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
118
+ * absent); we pre-probe each row's `_id` so a collision is reported as a
119
+ * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
120
+ * `errors`; the rest land.
121
+ */
122
+ declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
31
123
  interface SqlCtxDbOptions {
32
124
  /**
33
125
  * Resolved request auth handed to `.serverDefault(fn)` column factories so
@@ -190,9 +282,19 @@ declare const readSqlCdcFloor: (exec: SqlCtxExec, dialect: SqlDialect) => Promis
190
282
  /**
191
283
  * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
192
284
  * (clamped to [1, 10000]); plus the cursor to resume from.
285
+ *
286
+ * On Postgres and MySQL the page also stops at the first late-commit hole: an
287
+ * allocated `seq` not yet visible, followed by a row younger than
288
+ * {@link CDC_LATE_COMMIT_WINDOW_MS} (see "Late commits" on
289
+ * {@link readSqlCdcChangedTables}). The cursor is a consumer's only record of
290
+ * what it has seen, so handing out rows past an in-flight append would skip that
291
+ * append for good. Stopping the page instead of just the cursor keeps the
292
+ * cursor the `seq` of the last change returned. A permanent hole (a failed
293
+ * append) holds the page back for one window only.
193
294
  */
194
295
  declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
195
296
  limit?: number;
297
+ now?: number;
196
298
  sinceSeq?: number;
197
299
  }, dialect: SqlDialect) => Promise<{
198
300
  changes: CdcChange[];
@@ -312,6 +414,118 @@ declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, d
312
414
  declare const SEARCH_STATE_TABLE = "__lunora_search_state";
313
415
  /** Create the progress table. Idempotent; runs alongside the companion DDL. */
314
416
  declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
417
+ /** A table plus its current row count. */
418
+ interface GlobalTableInfo {
419
+ name: string;
420
+ rowCount: number;
421
+ }
422
+ /** A window of rows from one table, plus the column list and total size. */
423
+ interface GlobalTablePage {
424
+ columns: string[];
425
+ /**
426
+ * Foreign-key columns (local column → referenced table) for tables that carry
427
+ * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
428
+ * Schema `.global()` tables omit this (their refs come from `describeTables`);
429
+ * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
430
+ * schema diagram can draw their global→global FK edges.
431
+ */
432
+ refs?: Record<string, string>;
433
+ rows: Record<string, unknown>[];
434
+ total: number;
435
+ }
436
+ /**
437
+ * One equality constraint a facet-value click adds to the global browser's view:
438
+ * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
439
+ * displayed column name, validated against the table's columns and mapped to its
440
+ * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
441
+ * value** the facet returned (a SQLite scalar — including a BLOB, which reaches
442
+ * here as bytes because the facet payload is wire-encoded), normalised by
443
+ * {@link sqliteEncode} and bound as a parameter, never interpolated.
444
+ * AND-combined with the other clauses.
445
+ *
446
+ * Only `eq` is compiled on this path. `operator` and `path` exist so that a
447
+ * request asking for anything else is refused by {@link buildEqPredicate} rather
448
+ * than read as an equality: a `has` or `contains` clause matched as `= ?` would
449
+ * return rows the caller did not ask for.
450
+ */
451
+ interface GlobalFilterClause {
452
+ column: string;
453
+ /** Must be absent or `"eq"`; any other operator is refused. */
454
+ operator?: string;
455
+ /** Must be absent or empty; a nested path is refused (D1 columns are physical). */
456
+ path?: string[];
457
+ value: unknown;
458
+ }
459
+ interface ReadGlobalTablePageOptions {
460
+ filters?: GlobalFilterClause[];
461
+ limit?: number;
462
+ offset?: number;
463
+ table: string;
464
+ }
465
+ /**
466
+ * Options for {@link facetSqlGlobalColumn} — the read-only "what values does this
467
+ * column hold?" summary for the global (D1) browser. `column` is the displayed
468
+ * column to group by (validated and mapped to its physical column, never
469
+ * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
470
+ * constraints so the facet reflects the **active view** (the same rows the
471
+ * browser is previewing); `limit` caps the distinct values returned (clamped).
472
+ */
473
+ interface FacetGlobalColumnOptions {
474
+ column: string;
475
+ filters?: GlobalFilterClause[];
476
+ limit?: number;
477
+ table: string;
478
+ }
479
+ /** One distinct value of a faceted global column with its row count over the active view. */
480
+ interface GlobalFacetValue {
481
+ count: number;
482
+ value: unknown;
483
+ }
484
+ /**
485
+ * Payload of a {@link facetSqlGlobalColumn} call: the top-N distinct `values` (each
486
+ * with a `count`) ordered by frequency, plus `truncated` — `true` when more
487
+ * distinct values existed beyond the cap, so the UI can say so rather than imply
488
+ * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
489
+ */
490
+ interface GlobalFacetResult {
491
+ truncated: boolean;
492
+ values: GlobalFacetValue[];
493
+ }
494
+ /**
495
+ * List every browsable D1 table with its row count, ordered by name. Surfaces
496
+ * both the schema's `.global()` tables (provisioned first) and external tables
497
+ * (auth, etc.); internal/companion tables are excluded.
498
+ */
499
+ declare const listSqlGlobalTables: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<GlobalTableInfo[]>;
500
+ /**
501
+ * Read a page of rows from one D1 table. The table is validated against the live
502
+ * browsable-table list before its name is interpolated, so this can't be coerced
503
+ * into reading an internal table or injecting SQL. `limit` is clamped to
504
+ * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
505
+ * matching each `column = value` eq constraint (a facet-value drill-down), bound
506
+ * through {@link buildEqPredicate} so they never inject SQL.
507
+ */
508
+ declare const readSqlGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
509
+ /**
510
+ * Summarise the distinct values of one displayed column over the **active view**
511
+ * (the same eq `filters` the global browser is previewing) — the D1 twin of the
512
+ * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
513
+ * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
514
+ * against the table's displayed columns (typed 404 if unknown), mapped to its
515
+ * physical column, and quoted — never interpolated from caller input. The extra
516
+ * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
517
+ * an external (non-schema) table is never grouped — it collapses to a single
518
+ * redacted `•••` bucket — mirroring the page browser's value redaction so the
519
+ * facet can't leak credentials. The returned `value` is the raw stored scalar, so
520
+ * a click feeds it straight back as an eq filter.
521
+ *
522
+ * The payload is wire-encoded on the way out, like the page read's rows: a BLOB
523
+ * column's stored value is bytes, and `Response.json` flattens those to `{}` —
524
+ * which is not a display glitch but a broken drill-down, since the flattened
525
+ * value is what the click sends back as the filter. `needsWireEncoding` leaves a
526
+ * facet over an ordinary text/numeric column untouched.
527
+ */
528
+ declare const facetSqlGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
315
529
  /** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
316
530
  declare const sqliteEncode: (value: unknown, kind?: string) => unknown;
317
531
  /** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
@@ -397,7 +611,49 @@ declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefi
397
611
  * - everything else (string/number/date/timestamp/id/literal): verbatim.
398
612
  */
399
613
  declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
400
- export { SEARCH_STATE_TABLE,
614
+ export {
615
+ /**
616
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
617
+ * shared by Lunora's `.global()` table backends.
618
+ *
619
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
620
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
621
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
622
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
623
+ * whose `broadcast` hook drives live queries regardless of engine.
624
+ *
625
+ * This package is internal: consumers depend on `@lunora/d1` or
626
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
627
+ */
628
+ type ExportGlobalArgs,
629
+ /**
630
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
631
+ * shared by Lunora's `.global()` table backends.
632
+ *
633
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
634
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
635
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
636
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
637
+ * whose `broadcast` hook drives live queries regardless of engine.
638
+ *
639
+ * This package is internal: consumers depend on `@lunora/d1` or
640
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
641
+ */
642
+ type ExportRow, type FacetGlobalColumnOptions, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type GlobalTableInfo, type GlobalTablePage,
643
+ /**
644
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
645
+ * shared by Lunora's `.global()` table backends.
646
+ *
647
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
648
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
649
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
650
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
651
+ * whose `broadcast` hook drives live queries regardless of engine.
652
+ *
653
+ * This package is internal: consumers depend on `@lunora/d1` or
654
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
655
+ */
656
+ type ImportError,
401
657
  /**
402
658
  * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
403
659
  * shared by Lunora's `.global()` table backends.
@@ -411,7 +667,7 @@ export { SEARCH_STATE_TABLE,
411
667
  * This package is internal: consumers depend on `@lunora/d1` or
412
668
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
413
669
  */
414
- type SqlCtxDbOptions,
670
+ type ImportGlobalArgs,
415
671
  /**
416
672
  * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
417
673
  * shared by Lunora's `.global()` table backends.
@@ -425,4 +681,4 @@ type SqlCtxDbOptions,
425
681
  * This package is internal: consumers depend on `@lunora/d1` or
426
682
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
427
683
  */
428
- type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
684
+ type ImportResult, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TableDefinitionLike, ServerDefaultContextLike, DatabaseWriterLike, CrossShardReadArgs, QueryPage, SchedulerLike, SchemaLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
1
+ import { TableDefinitionLike, ImportConflictMode, SchemaLike, DatabaseWriterLike, ServerDefaultContextLike, CrossShardReadArgs, QueryPage, SchedulerLike, CdcChange, ValidatorLike } from '@lunora/shard-engine';
2
2
  import { SqlRunResult, SqlDialect } from "./dialect.js";
3
3
  export type { SqlExec } from "./dialect.js";
4
4
  import 'drizzle-orm';
@@ -28,6 +28,98 @@ interface SqlCtxExec {
28
28
  * correct on SQLite, Postgres and MySQL.
29
29
  */
30
30
  declare const decodeGlobalRow: (definition: TableDefinitionLike, row: Record<string, unknown>) => Record<string, unknown>;
31
+ /** One exported row: `doc` is reconstructed from the column tuple. */
32
+ interface ExportRow {
33
+ doc: Record<string, unknown>;
34
+ /**
35
+ * True physical source line, when the caller has it (e.g. a global row
36
+ * pulled out of an interspersed NDJSON import stream by
37
+ * `@lunora/runtime`'s `import-stream.ts`). When present this overrides the
38
+ * position-derived line below — the caller-side positions of a
39
+ * global-only subset don't line up with the original file once
40
+ * non-global rows have been filtered out. Absent for callers with no
41
+ * physical source to attribute (e.g. a fresh `exportSqlGlobalRows` roundtrip
42
+ * in tests), which keeps the positional fallback.
43
+ */
44
+ line?: number;
45
+ table: string;
46
+ }
47
+ interface ImportError {
48
+ code: string;
49
+ line: number;
50
+ message: string;
51
+ table: string;
52
+ }
53
+ interface ImportResult {
54
+ /** Skipped rows whose `_id` already exists (the default `onConflict: "skip"`). */
55
+ conflicts: number;
56
+ errors: ImportError[];
57
+ inserted: Record<string, number>;
58
+ /** Existing rows overwritten under `onConflict: "replace"`. */
59
+ replaced: number;
60
+ }
61
+ /**
62
+ * Return every `.global()` table in the schema, optionally narrowed by an
63
+ * allowlist. Shard-local tables are skipped here — they're handled by the DO
64
+ * helpers — so callers get a clean separation between the two storage planes.
65
+ */
66
+ declare const selectGlobalTables: (schema: SchemaLike, requested?: ReadonlyArray<string>) => string[];
67
+ interface ExportGlobalArgs {
68
+ batchSize?: number;
69
+ tables?: ReadonlyArray<string>;
70
+ }
71
+ /**
72
+ * Yield rows from every requested `.global()` table in batches.
73
+ *
74
+ * Keyset-paginates on the physical primary key (`id` — every `.global()` table
75
+ * carries it): `WHERE id > ? ORDER BY id LIMIT n`, carrying the last id forward.
76
+ * A plain `LIMIT/OFFSET` scan would be wrong here — no engine guarantees an
77
+ * order for an unordered SELECT and each page is a separate query, so pages
78
+ * could overlap or skip rows (and any concurrent insert/delete would shift
79
+ * offsets and silently drop/duplicate rows in the snapshot). Keyset paging is
80
+ * deterministic under concurrent writes and avoids O(n^2) OFFSET scans.
81
+ *
82
+ * Tables are provisioned first (idempotent `CREATE … IF NOT EXISTS`): `.global()`
83
+ * tables are created lazily on first write, so a fresh deployment — or any table
84
+ * never written — would otherwise abort the stream with a raw `no such table`
85
+ * instead of exporting it as empty.
86
+ */
87
+ declare const exportSqlGlobalRows: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, args: ExportGlobalArgs) => AsyncGenerator<ExportRow, void, undefined>;
88
+ interface ImportGlobalArgs {
89
+ /**
90
+ * Check the rows and report their shape errors, writing nothing. The conflict
91
+ * probe and the insert are skipped, so an `_id` already in use and a foreign-key
92
+ * or unique failure are only found by a real import.
93
+ */
94
+ dryRun?: boolean;
95
+ /**
96
+ * Optional direct exec handle to the same database the writer targets.
97
+ * When supplied, the conflict pre-probe issues a single
98
+ * `SELECT 1 FROM <table> WHERE id = ? LIMIT 1` against the row's declared
99
+ * table instead of falling back to an unscoped id probe, which scans every
100
+ * global table looking for the id. Strongly recommended for large schemas
101
+ * — the writer-fallback is O(N tables) per row.
102
+ */
103
+ exec?: SqlCtxExec;
104
+ /**
105
+ * What a row whose `_id` already exists in its table does: `"skip"` (the
106
+ * default) counts it as a conflict and leaves the stored row unchanged;
107
+ * `"replace"` overwrites the stored row with the snapshot's fields, keeping
108
+ * its `_id` and taking the snapshot's `_creationTime`. A dry run probes
109
+ * nothing, so the mode does not change its answer.
110
+ */
111
+ onConflict?: ImportConflictMode;
112
+ rows: ReadonlyArray<ExportRow>;
113
+ startLine?: number;
114
+ }
115
+ /**
116
+ * Import rows into `.global()` tables via the schema-aware writer. The
117
+ * writer rejects unknown ids on `insert` (the writer assigns one when `_id` is
118
+ * absent); we pre-probe each row's `_id` so a collision is reported as a
119
+ * conflict instead of bubbled as a UNIQUE error. Schema-failed rows surface in
120
+ * `errors`; the rest land.
121
+ */
122
+ declare const importSqlGlobalRows: (writer: DatabaseWriterLike, schema: SchemaLike, dialect: SqlDialect, args: ImportGlobalArgs) => Promise<ImportResult>;
31
123
  interface SqlCtxDbOptions {
32
124
  /**
33
125
  * Resolved request auth handed to `.serverDefault(fn)` column factories so
@@ -190,9 +282,19 @@ declare const readSqlCdcFloor: (exec: SqlCtxExec, dialect: SqlDialect) => Promis
190
282
  /**
191
283
  * Read changelog entries newer than `sinceSeq` in commit order, up to `limit`
192
284
  * (clamped to [1, 10000]); plus the cursor to resume from.
285
+ *
286
+ * On Postgres and MySQL the page also stops at the first late-commit hole: an
287
+ * allocated `seq` not yet visible, followed by a row younger than
288
+ * {@link CDC_LATE_COMMIT_WINDOW_MS} (see "Late commits" on
289
+ * {@link readSqlCdcChangedTables}). The cursor is a consumer's only record of
290
+ * what it has seen, so handing out rows past an in-flight append would skip that
291
+ * append for good. Stopping the page instead of just the cursor keeps the
292
+ * cursor the `seq` of the last change returned. A permanent hole (a failed
293
+ * append) holds the page back for one window only.
193
294
  */
194
295
  declare const readSqlCdcChanges: (exec: SqlCtxExec, options: {
195
296
  limit?: number;
297
+ now?: number;
196
298
  sinceSeq?: number;
197
299
  }, dialect: SqlDialect) => Promise<{
198
300
  changes: CdcChange[];
@@ -312,6 +414,118 @@ declare const backfillSqlSearchIndexes: (exec: SqlCtxExec, schema: SchemaLike, d
312
414
  declare const SEARCH_STATE_TABLE = "__lunora_search_state";
313
415
  /** Create the progress table. Idempotent; runs alongside the companion DDL. */
314
416
  declare const migrateSearchState: (exec: SqlCtxExec, dialect: SqlDialect) => Promise<void>;
417
+ /** A table plus its current row count. */
418
+ interface GlobalTableInfo {
419
+ name: string;
420
+ rowCount: number;
421
+ }
422
+ /** A window of rows from one table, plus the column list and total size. */
423
+ interface GlobalTablePage {
424
+ columns: string[];
425
+ /**
426
+ * Foreign-key columns (local column → referenced table) for tables that carry
427
+ * real SQL `REFERENCES` constraints — recovered from `PRAGMA foreign_key_list`.
428
+ * Schema `.global()` tables omit this (their refs come from `describeTables`);
429
+ * external tables (e.g. better-auth's `session`/`twoFactor`) expose it so the
430
+ * schema diagram can draw their global→global FK edges.
431
+ */
432
+ refs?: Record<string, string>;
433
+ rows: Record<string, unknown>[];
434
+ total: number;
435
+ }
436
+ /**
437
+ * One equality constraint a facet-value click adds to the global browser's view:
438
+ * `column = value` (or `column IS NULL` when `value` is nullish). `column` is a
439
+ * displayed column name, validated against the table's columns and mapped to its
440
+ * physical column (`_id` → `id`) before it is quoted; `value` is the **raw stored
441
+ * value** the facet returned (a SQLite scalar — including a BLOB, which reaches
442
+ * here as bytes because the facet payload is wire-encoded), normalised by
443
+ * {@link sqliteEncode} and bound as a parameter, never interpolated.
444
+ * AND-combined with the other clauses.
445
+ *
446
+ * Only `eq` is compiled on this path. `operator` and `path` exist so that a
447
+ * request asking for anything else is refused by {@link buildEqPredicate} rather
448
+ * than read as an equality: a `has` or `contains` clause matched as `= ?` would
449
+ * return rows the caller did not ask for.
450
+ */
451
+ interface GlobalFilterClause {
452
+ column: string;
453
+ /** Must be absent or `"eq"`; any other operator is refused. */
454
+ operator?: string;
455
+ /** Must be absent or empty; a nested path is refused (D1 columns are physical). */
456
+ path?: string[];
457
+ value: unknown;
458
+ }
459
+ interface ReadGlobalTablePageOptions {
460
+ filters?: GlobalFilterClause[];
461
+ limit?: number;
462
+ offset?: number;
463
+ table: string;
464
+ }
465
+ /**
466
+ * Options for {@link facetSqlGlobalColumn} — the read-only "what values does this
467
+ * column hold?" summary for the global (D1) browser. `column` is the displayed
468
+ * column to group by (validated and mapped to its physical column, never
469
+ * interpolated); `filters` mirrors {@link ReadGlobalTablePageOptions}'s eq
470
+ * constraints so the facet reflects the **active view** (the same rows the
471
+ * browser is previewing); `limit` caps the distinct values returned (clamped).
472
+ */
473
+ interface FacetGlobalColumnOptions {
474
+ column: string;
475
+ filters?: GlobalFilterClause[];
476
+ limit?: number;
477
+ table: string;
478
+ }
479
+ /** One distinct value of a faceted global column with its row count over the active view. */
480
+ interface GlobalFacetValue {
481
+ count: number;
482
+ value: unknown;
483
+ }
484
+ /**
485
+ * Payload of a {@link facetSqlGlobalColumn} call: the top-N distinct `values` (each
486
+ * with a `count`) ordered by frequency, plus `truncated` — `true` when more
487
+ * distinct values existed beyond the cap, so the UI can say so rather than imply
488
+ * the list is exhaustive. Mirrors the shard browser's `FacetColumnResult`.
489
+ */
490
+ interface GlobalFacetResult {
491
+ truncated: boolean;
492
+ values: GlobalFacetValue[];
493
+ }
494
+ /**
495
+ * List every browsable D1 table with its row count, ordered by name. Surfaces
496
+ * both the schema's `.global()` tables (provisioned first) and external tables
497
+ * (auth, etc.); internal/companion tables are excluded.
498
+ */
499
+ declare const listSqlGlobalTables: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect) => Promise<GlobalTableInfo[]>;
500
+ /**
501
+ * Read a page of rows from one D1 table. The table is validated against the live
502
+ * browsable-table list before its name is interpolated, so this can't be coerced
503
+ * into reading an internal table or injecting SQL. `limit` is clamped to
504
+ * `[1, 500]`; `offset` floors at `0`. `filters` AND-narrows the page to rows
505
+ * matching each `column = value` eq constraint (a facet-value drill-down), bound
506
+ * through {@link buildEqPredicate} so they never inject SQL.
507
+ */
508
+ declare const readSqlGlobalTablePage: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: ReadGlobalTablePageOptions) => Promise<GlobalTablePage>;
509
+ /**
510
+ * Summarise the distinct values of one displayed column over the **active view**
511
+ * (the same eq `filters` the global browser is previewing) — the D1 twin of the
512
+ * shard browser's `facetColumn`. Read-only: a `SELECT col AS value, COUNT(*) AS
513
+ * count … GROUP BY col ORDER BY count DESC LIMIT N+1`, with the column validated
514
+ * against the table's displayed columns (typed 404 if unknown), mapped to its
515
+ * physical column, and quoted — never interpolated from caller input. The extra
516
+ * over-fetched row is dropped and surfaced as `truncated`. A sensitive column on
517
+ * an external (non-schema) table is never grouped — it collapses to a single
518
+ * redacted `•••` bucket — mirroring the page browser's value redaction so the
519
+ * facet can't leak credentials. The returned `value` is the raw stored scalar, so
520
+ * a click feeds it straight back as an eq filter.
521
+ *
522
+ * The payload is wire-encoded on the way out, like the page read's rows: a BLOB
523
+ * column's stored value is bytes, and `Response.json` flattens those to `{}` —
524
+ * which is not a display glitch but a broken drill-down, since the flattened
525
+ * value is what the click sends back as the filter. `needsWireEncoding` leaves a
526
+ * facet over an ordinary text/numeric column untouched.
527
+ */
528
+ declare const facetSqlGlobalColumn: (exec: SqlCtxExec, schema: SchemaLike, dialect: SqlDialect, options: FacetGlobalColumnOptions) => Promise<GlobalFacetResult>;
315
529
  /** Map a JS value onto its SQLite storage form — SQLite has no boolean, so true/false → 1/0. */
316
530
  declare const sqliteEncode: (value: unknown, kind?: string) => unknown;
317
531
  /** Parse `raw` as JSON, returning `raw` unchanged when it is not valid JSON. */
@@ -397,7 +611,49 @@ declare const effectiveColumnKind: (validator: ValidatorLike) => string | undefi
397
611
  * - everything else (string/number/date/timestamp/id/literal): verbatim.
398
612
  */
399
613
  declare const sqliteDecode: (raw: unknown, kind: string | undefined) => unknown;
400
- export { SEARCH_STATE_TABLE,
614
+ export {
615
+ /**
616
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
617
+ * shared by Lunora's `.global()` table backends.
618
+ *
619
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
620
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
621
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
622
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
623
+ * whose `broadcast` hook drives live queries regardless of engine.
624
+ *
625
+ * This package is internal: consumers depend on `@lunora/d1` or
626
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
627
+ */
628
+ type ExportGlobalArgs,
629
+ /**
630
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
631
+ * shared by Lunora's `.global()` table backends.
632
+ *
633
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
634
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
635
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
636
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
637
+ * whose `broadcast` hook drives live queries regardless of engine.
638
+ *
639
+ * This package is internal: consumers depend on `@lunora/d1` or
640
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
641
+ */
642
+ type ExportRow, type FacetGlobalColumnOptions, type GlobalFacetResult, type GlobalFacetValue, type GlobalFilterClause, type GlobalTableInfo, type GlobalTablePage,
643
+ /**
644
+ * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
645
+ * shared by Lunora's `.global()` table backends.
646
+ *
647
+ * One ORM implementation (`createSqlCtxDb`) drives any SQL engine through a
648
+ * `SqlDialect`: SQLite via `@lunora/d1`, and Postgres/MySQL (PlanetScale, Neon,
649
+ * any Hyperdrive-reachable database) via `@lunora/hyperdrive`. Reactivity is
650
+ * unaffected — the writer is injected as `globalDb` into `createShardCtxDb`,
651
+ * whose `broadcast` hook drives live queries regardless of engine.
652
+ *
653
+ * This package is internal: consumers depend on `@lunora/d1` or
654
+ * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
655
+ */
656
+ type ImportError,
401
657
  /**
402
658
  * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
403
659
  * shared by Lunora's `.global()` table backends.
@@ -411,7 +667,7 @@ export { SEARCH_STATE_TABLE,
411
667
  * This package is internal: consumers depend on `@lunora/d1` or
412
668
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
413
669
  */
414
- type SqlCtxDbOptions,
670
+ type ImportGlobalArgs,
415
671
  /**
416
672
  * `@lunora/sql-store` — the internal, dialect-parameterized SQL store core
417
673
  * shared by Lunora's `.global()` table backends.
@@ -425,4 +681,4 @@ type SqlCtxDbOptions,
425
681
  * This package is internal: consumers depend on `@lunora/d1` or
426
682
  * `@lunora/hyperdrive`, which assemble the concrete dialect and wrap the core.
427
683
  */
428
- type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
684
+ type ImportResult, type ReadGlobalTablePageOptions, SEARCH_STATE_TABLE, type SqlCtxDbOptions, type SqlCtxExec, type SqlDialect, type SqlRunResult, type SqlSearchBackfillResult, backfillSqlSearchIndexes, createSqlCtxDb, decodeBigint, decodeGlobalRow, effectiveColumnKind, exportSqlGlobalRows, facetSqlGlobalColumn, importSqlGlobalRows, listSqlGlobalTables, migrateSearchState, readSqlCdcChangedTables, readSqlCdcChanges, readSqlCdcFloor, readSqlGlobalTablePage, runSqlAggregateMigrations, runSqlCdcMigration, runSqlGlobalTableMigrations, runSqlRankMigrations, runSqlSearchMigrations, selectGlobalTables, sqliteDecode, sqliteEncode, sweepSqlCdcRetention, tryJsonParse };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createSqlCtxDb as a,readSqlCdcChangedTables as o,readSqlCdcChanges as t,readSqlCdcFloor as l,runSqlCdcMigration as s,sweepSqlCdcRetention as n}from"./packem_shared/createSqlCtxDb-CwgVezf1.mjs";import{runSqlGlobalTableMigrations as i}from"./packem_shared/runSqlGlobalTableMigrations-6cXUbFbj.mjs";import{runSqlAggregateMigrations as c,runSqlRankMigrations as q}from"./packem_shared/runSqlAggregateMigrations-CTaYuZh9.mjs";import{d as f,r as m}from"./packem_shared/ctx-db-search-gBXL6_Ra.mjs";import{S as x,m as p}from"./packem_shared/ctx-db-search-state-BYatr_oi.mjs";import{d as u,a as h,c as M,s as T,t as A}from"./packem_shared/value-codec-CiS1h_97.mjs";import{z as R}from"./packem_shared/sql-exec-DBWZFC7S.mjs";export{x as SEARCH_STATE_TABLE,f as backfillSqlSearchIndexes,a as createSqlCtxDb,u as decodeBigint,R as decodeGlobalRow,h as effectiveColumnKind,p as migrateSearchState,o as readSqlCdcChangedTables,t as readSqlCdcChanges,l as readSqlCdcFloor,c as runSqlAggregateMigrations,s as runSqlCdcMigration,i as runSqlGlobalTableMigrations,q as runSqlRankMigrations,m as runSqlSearchMigrations,M as sqliteDecode,T as sqliteEncode,n as sweepSqlCdcRetention,A as tryJsonParse};
1
+ import{exportSqlGlobalRows as l,importSqlGlobalRows as o,selectGlobalTables as r}from"./packem_shared/exportSqlGlobalRows-BI_ZxPQU.mjs";import{createSqlCtxDb as s,readSqlCdcChangedTables as S,readSqlCdcChanges as n,readSqlCdcFloor as i,runSqlCdcMigration as d,sweepSqlCdcRetention as q}from"./packem_shared/createSqlCtxDb-Cy7Dvrk9.mjs";import{runSqlGlobalTableMigrations as b}from"./packem_shared/runSqlGlobalTableMigrations-DMC5hXJo.mjs";import{runSqlAggregateMigrations as f,runSqlRankMigrations as g}from"./packem_shared/runSqlAggregateMigrations-lP0mwd-W.mjs";import{b as x,r as C}from"./packem_shared/ctx-db-search-B4wC-Jrm.mjs";import{S as T,m as u}from"./packem_shared/ctx-db-search-state-Dt0iNPGb.mjs";import{facetSqlGlobalColumn as h,listSqlGlobalTables as M,readSqlGlobalTablePage as w}from"./packem_shared/facetSqlGlobalColumn-Col-9Hcc.mjs";import{d as E,e as k,s as B,a as D,t as P}from"./packem_shared/value-codec-C52YW-Do.mjs";import{d as v}from"./packem_shared/sql-exec-BKz380dy.mjs";export{T as SEARCH_STATE_TABLE,x as backfillSqlSearchIndexes,s as createSqlCtxDb,E as decodeBigint,v as decodeGlobalRow,k as effectiveColumnKind,l as exportSqlGlobalRows,h as facetSqlGlobalColumn,o as importSqlGlobalRows,M as listSqlGlobalTables,u as migrateSearchState,S as readSqlCdcChangedTables,n as readSqlCdcChanges,i as readSqlCdcFloor,w as readSqlGlobalTablePage,f as runSqlAggregateMigrations,d as runSqlCdcMigration,b as runSqlGlobalTableMigrations,g as runSqlRankMigrations,C as runSqlSearchMigrations,r as selectGlobalTables,B as sqliteDecode,D as sqliteEncode,q as sweepSqlCdcRetention,P as tryJsonParse};
@@ -0,0 +1 @@
1
+ const o="_version";export{o as OCC_VERSION_COLUMN};
@@ -1 +1 @@
1
- import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-BYatr_oi.mjs";import"./sql-exec-DBWZFC7S.mjs";export{t as SEARCH_STATE_TABLE,S as clearSearchBackfillState,c as migrateSearchState,l as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
1
+ import{S as t,a as S,m as c,r as l,b as i,w as s}from"./ctx-db-search-state-Dt0iNPGb.mjs";import"./sql-exec-BKz380dy.mjs";export{t as SEARCH_STATE_TABLE,S as clearSearchBackfillState,c as migrateSearchState,l as readSearchBackfillState,i as readSearchIndexCoverage,s as writeSearchBackfillState};
@@ -0,0 +1 @@
1
+ import"./ctx-db-search-state-Dt0iNPGb.mjs";import{b as S,c as s,a as i,r as l}from"./ctx-db-search-B4wC-Jrm.mjs";import"./sql-exec-BKz380dy.mjs";export{S as backfillSqlSearchIndexes,s as createSearchSync,i as runSqlSearch,l as runSqlSearchMigrations};