lines-db 0.19.0 → 0.19.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @toiroakr/lines-db
2
2
 
3
+ ## 0.19.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 4bfd4b7: Read the files a schema file imports anew when one of them changed, so an edit to a project file the schema imports, such as a table definition, is validated against instead of the version first loaded. Once the first read has recorded the imports, a file is evaluated again only when it or a file it imports changed, except after a read that failed, so reading the tables again many times does not grow memory with the number of files. A package from `node_modules`, and a file of another package, such as one linked from a workspace, stay one module. A runtime without synchronous module hooks still reads only the schema file itself again, and CommonJS schemas (`.schema.cts`) keep their first evaluation, as before.
8
+
9
+ `hasExternalChanges()` and `findExternalChanges()` now report an edit to, or the removal of, a project file the schemas imported, so the studio reloads when only a table definition changed. `listSchemaDependencies()` lists the project files a database's schemas imported. With synchronous module hooks, a relative import of a file that was not there when the tables were read is tracked too, so creating the file is reported as a change. Calling `initialize()` again in the same process before an earlier call has finished can leave `hasExternalChanges()` reporting no change for a file edited while the earlier call was reading; the studio reads the tables one reload at a time and is not affected. The studio watches the imported files too, so an open page is told as soon as one of them is edited or created, even when it is outside the watched directories; a file that is not there yet is watched through the directory that would hold it, or the nearest one that exists.
10
+
3
11
  ## 0.19.0
4
12
 
5
13
  ### Minor Changes
package/README.ja.md CHANGED
@@ -473,7 +473,7 @@ if (!result.ok && result.error.name === 'JsonlConflictError') {
473
473
 
474
474
  内容の確認と書き込みの間はファイルをロックしません。その間に別のプロセスが保存した変更は上書きされます。一人でローカルファイルを編集する用途を想定しており、同時に書き込むプロセス間の排他制御は行いません。
475
475
 
476
- `hasExternalChanges()`は、最後に読み書きした後のJSONLファイルやスキーマファイルの変更・追加・削除を確認します。`findExternalChanges()`は該当ファイルの一覧を返します。長時間動くプロセスで、他のツールによる変更を検知して読み直すときに使えます。
476
+ `hasExternalChanges()`は、最後に読み書きした後のJSONLファイルやスキーマファイルの変更・追加・削除と、読み込み時にスキーマがimportしていたプロジェクト内ファイル(テーブル定義など)の変更・削除を確認します。`findExternalChanges()`は該当ファイルの一覧を返し、`listSchemaDependencies()`はスキーマがimportしていたプロジェクト内ファイルの一覧を返します。長時間動くプロセスで、他のツールによる変更を検知して読み直すときに使えます。同期のモジュールフックがあるときは、読み込み時に存在しなかった相対importの先も追跡し、そのファイルが作られると変更として報告します。最初の読み込みでimportが記録されたあとは、読み込みに失敗した場合を除き、そのファイルか、そのファイルがimportしているファイルが変わったときだけ、次の読み込みで評価し直されます。同期のモジュールフックがない実行環境では、スキーマファイル自身だけを読み直します。
477
477
 
478
478
  ```typescript
479
479
  if (unwrap(await db.hasExternalChanges())) {
package/README.md CHANGED
@@ -474,7 +474,7 @@ With `sync()` or automatic sync outside a transaction, database changes remain a
474
474
 
475
475
  Files are not locked between checking their contents and writing. Changes saved by another process during that interval are overwritten. This is intended for one person editing local files; it does not coordinate concurrent writers.
476
476
 
477
- `hasExternalChanges()` detects changes, additions, and deletions of JSONL and schema files since the last read or write. `findExternalChanges()` lists the affected files. Use them to detect edits made by other tools and reload data in a long-running process.
477
+ `hasExternalChanges()` detects changes, additions, and deletions of JSONL and schema files since the last read or write, and changes and deletions of the project files the schemas imported (such as a table definition) when they were read. `findExternalChanges()` lists the affected files, and `listSchemaDependencies()` lists the project files the schemas imported. Use them to detect edits made by other tools and reload data in a long-running process. With synchronous module hooks, a relative import of a file that was not there when the tables were read is tracked too, so creating the file is reported as a change. Once the first read has recorded the imports, a file is evaluated again on the next read only when it or a file it imports changed, except after a read that failed; a runtime without synchronous module hooks reads only the schema file itself again.
478
478
 
479
479
  ```typescript
480
480
  if (unwrap(await db.hasExternalChanges())) {
package/bin/cli.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  #!/usr/bin/env node
2
+ import * as nodeModule from "node:module";
2
3
  import { createRequire, register } from "node:module";
3
4
  import * as l from "loculus";
4
5
  import { _rawValidate, _resolveIssue, _typeIssue, config } from "loculus";
5
6
  import { access, chmod, link, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
6
7
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
7
8
  import { createHash, randomBytes } from "node:crypto";
8
- import { pathToFileURL } from "node:url";
9
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
11
  import { styleText } from "node:util";
10
12
  import { arg, defineCommand, runMain } from "@politty/loculus";
11
13
  import { runInNewContext } from "node:vm";
@@ -438,6 +440,199 @@ async function replaceFile(file, write, expected) {
438
440
  if (!moved) await rm(temporary, { force: true }).catch(() => {});
439
441
  }
440
442
  }
443
+ // src/schema-module.ts
444
+ const VERSION_PARAM = "linesDbV";
445
+ const SHARED = Symbol.for("lines-db:schema-imports:1");
446
+ let counter = 0;
447
+ const shared = globalThis[SHARED] ??= {
448
+ graph: /* @__PURE__ */ new Map(),
449
+ evaluated: /* @__PURE__ */ new Map(),
450
+ evaluatedUrls: /* @__PURE__ */ new Set(),
451
+ versions: /* @__PURE__ */ new Map(),
452
+ hashes: /* @__PURE__ */ new Map(),
453
+ salt: "",
454
+ hooked: false
455
+ };
456
+ shared.evaluated ??= /* @__PURE__ */ new Map();
457
+ shared.evaluatedUrls ??= /* @__PURE__ */ new Set();
458
+ const packageRoots = /* @__PURE__ */ new Map();
459
+ function hashOf(parts) {
460
+ const hash = createHash("sha1");
461
+ for (const part of parts) hash.update(part).update("\0");
462
+ return hash.digest("hex");
463
+ }
464
+ function contentOf(file) {
465
+ try {
466
+ return readFileSync(file);
467
+ } catch {
468
+ return;
469
+ }
470
+ }
471
+ function hashContent(content) {
472
+ return createHash("sha1").update(content).digest("hex");
473
+ }
474
+ /** What a file that is not there holds: not a hash, so that no file can have it */
475
+ const MISSING_HASH = "missing";
476
+ function hashOfFile(file) {
477
+ const content = contentOf(file);
478
+ return content === void 0 ? MISSING_HASH : hashContent(content);
479
+ }
480
+ /**
481
+ * What the file is, with what it imports: a file evaluated again only when it or a file it imports changed,
482
+ * as a URL that names the version is one module for as long as the version stays. An import not recorded
483
+ * yet is not in the version. A file importing itself through others is taken by its own content there, so
484
+ * a version that was cut by a cycle is kept only for the file the count started from, which holds all of it
485
+ */
486
+ function versionOf(file, visiting = /* @__PURE__ */ new Set()) {
487
+ const known = shared.versions.get(file);
488
+ if (known) return {
489
+ version: known,
490
+ whole: true
491
+ };
492
+ const content = hashOfFile(file);
493
+ if (!shared.hashes.has(file)) shared.hashes.set(file, content);
494
+ if (visiting.has(file)) return {
495
+ version: hashOf([shared.salt, content]),
496
+ whole: false
497
+ };
498
+ visiting.add(file);
499
+ let whole = true;
500
+ const versions = [];
501
+ for (const imported of [...shared.graph.get(file) ?? []].sort()) {
502
+ const importedVersion = versionOf(imported, visiting);
503
+ versions.push(importedVersion.version);
504
+ whole &&= importedVersion.whole;
505
+ }
506
+ visiting.delete(file);
507
+ const version = hashOf([
508
+ shared.salt,
509
+ content,
510
+ ...versions
511
+ ]);
512
+ if (whole || visiting.size === 0) shared.versions.set(file, version);
513
+ return {
514
+ version,
515
+ whole
516
+ };
517
+ }
518
+ function packageRootOf(file) {
519
+ const start = dirname(file);
520
+ const cached = packageRoots.get(start);
521
+ if (cached !== void 0) return cached;
522
+ let dir = start;
523
+ let root = "";
524
+ for (;;) {
525
+ if (existsSync(join(dir, "package.json"))) {
526
+ root = dir;
527
+ break;
528
+ }
529
+ const parent = dirname(dir);
530
+ if (parent === dir) break;
531
+ dir = parent;
532
+ }
533
+ packageRoots.set(start, root);
534
+ return root;
535
+ }
536
+ /**
537
+ * A file imported under a URL not seen before is evaluated, and imports again what it imports: what an earlier
538
+ * evaluation of it imported is dropped here, as a file that no longer imports anything resolves nothing to
539
+ * replace it. A URL seen before is a module already evaluated, whose imports stay
540
+ */
541
+ function startEvaluation(file, url) {
542
+ if (shared.evaluatedUrls.has(url)) return;
543
+ shared.evaluatedUrls.add(url);
544
+ shared.graph.set(file, /* @__PURE__ */ new Set());
545
+ shared.evaluated.set(file, url);
546
+ }
547
+ /** Records the import of a file by a file that is read with versions; false for a file that is not one of the project */
548
+ function recordImport(parentURL, imported) {
549
+ if (!new URL(parentURL).searchParams.has(VERSION_PARAM)) return false;
550
+ const parent = fileURLToPath(parentURL);
551
+ if (packageRootOf(imported) !== packageRootOf(parent)) return false;
552
+ let imports = shared.graph.get(parent);
553
+ if (!imports || shared.evaluated.get(parent) !== parentURL) {
554
+ imports = /* @__PURE__ */ new Set();
555
+ shared.graph.set(parent, imports);
556
+ shared.evaluated.set(parent, parentURL);
557
+ }
558
+ imports.add(imported);
559
+ versionOf(imported);
560
+ return true;
561
+ }
562
+ function hookImports() {
563
+ if (shared.hooked) return true;
564
+ if (typeof nodeModule.registerHooks !== "function") return false;
565
+ nodeModule.registerHooks({ resolve(specifier, context, nextResolve) {
566
+ let resolved;
567
+ try {
568
+ resolved = nextResolve(specifier, context);
569
+ } catch (error) {
570
+ if (error.code === "ERR_MODULE_NOT_FOUND" && /^\.\.?\//.test(specifier)) {
571
+ const missing = context.parentURL?.startsWith("file:") ? new URL(specifier, context.parentURL) : void 0;
572
+ if (missing && !missing.href.includes("/node_modules/")) recordImport(context.parentURL, fileURLToPath(missing));
573
+ }
574
+ throw error;
575
+ }
576
+ if (!context.parentURL?.includes(VERSION_PARAM) || !resolved.url.startsWith("file:")) return resolved;
577
+ if (resolved.url.includes("/node_modules/")) return resolved;
578
+ const url = new URL(resolved.url);
579
+ if (url.searchParams.has(VERSION_PARAM)) return resolved;
580
+ const imported = fileURLToPath(url);
581
+ if (!recordImport(context.parentURL, imported)) return resolved;
582
+ url.searchParams.set(VERSION_PARAM, versionOf(imported).version);
583
+ startEvaluation(imported, url.href);
584
+ return {
585
+ ...resolved,
586
+ url: url.href
587
+ };
588
+ } });
589
+ shared.hooked = true;
590
+ return true;
591
+ }
592
+ function realFile(file) {
593
+ try {
594
+ return realpathSync(file);
595
+ } catch {
596
+ return file;
597
+ }
598
+ }
599
+ function importedBy(entries) {
600
+ const files = /* @__PURE__ */ new Set();
601
+ const pending = [...entries].flatMap((entry) => [...shared.graph.get(entry) ?? []]);
602
+ for (let file = pending.pop(); file !== void 0; file = pending.pop()) {
603
+ if (files.has(file)) continue;
604
+ files.add(file);
605
+ pending.push(...shared.graph.get(file) ?? []);
606
+ }
607
+ return [...files].filter((file) => !entries.has(file));
608
+ }
609
+ /**
610
+ * Imports of schema files in which a file imported by several of them, and by the same one again, is
611
+ * evaluated once: the versions are taken at the first import of a file and kept for the ones after it
612
+ */
613
+ function createSchemaImports() {
614
+ const hooks = hookImports();
615
+ shared.versions.clear();
616
+ shared.hashes.clear();
617
+ const modules = /* @__PURE__ */ new Map();
618
+ return {
619
+ import(schemaPath) {
620
+ const file = realFile(schemaPath);
621
+ const known = modules.get(file);
622
+ if (known) return known;
623
+ const url = new URL(pathToFileURL(file).href);
624
+ url.searchParams.set(VERSION_PARAM, hooks ? versionOf(file).version : `${Date.now()}`);
625
+ if (hooks) startEvaluation(file, url.href);
626
+ const loaded = import(url.href);
627
+ loaded.catch(() => {
628
+ shared.salt = `${Date.now()}-${++counter}`;
629
+ });
630
+ modules.set(file, loaded);
631
+ return loaded;
632
+ },
633
+ dependencies: (schemaPath) => new Map(importedBy(new Set(schemaPath ? [realFile(schemaPath)] : modules.keys())).map((file) => [file, shared.hashes.get(file) ?? hashOfFile(file)]))
634
+ };
635
+ }
441
636
  // src/schema-loader.ts
442
637
  var SchemaLoader = class {
443
638
  /**
@@ -450,13 +645,13 @@ var SchemaLoader = class {
450
645
  * Load a validation schema file for a table
451
646
  * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
452
647
  */
453
- static async loadSchema(jsonlPath, schemaDir) {
648
+ static async loadSchema(jsonlPath, schemaDir, imports) {
454
649
  const dir = schemaDir ?? dirname(jsonlPath);
455
650
  const tableName = basename(jsonlPath, ".jsonl");
456
651
  const schemaPath = await findSchemaFile(dir, tableName);
457
652
  if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
458
653
  try {
459
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
654
+ const module = await (imports ?? createSchemaImports()).import(schemaPath);
460
655
  const schema = module.default || module.schema;
461
656
  if (schema && this.isStandardSchema(schema)) return schema;
462
657
  throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
@@ -749,6 +944,8 @@ var LinesDB = class LinesDB {
749
944
  tablesFromGivenColumns = /* @__PURE__ */ new Set();
750
945
  /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
751
946
  schemaFileStates = /* @__PURE__ */ new Map();
947
+ schemaImports;
948
+ schemaDependencyHashes = /* @__PURE__ */ new Map();
752
949
  constructor(config, dbPath) {
753
950
  this.config = config;
754
951
  this.db = createDatabase(dbPath ?? ":memory:");
@@ -804,13 +1001,25 @@ var LinesDB = class LinesDB {
804
1001
  const loadingTables = /* @__PURE__ */ new Set();
805
1002
  const attemptedTables = /* @__PURE__ */ new Set();
806
1003
  const allDeferredForeignKeys = [];
807
- for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
808
- const tableTransform = tableNameToLoad === tableName ? transform : void 0;
809
- const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
810
- allErrors.push(...errors);
811
- allWarnings.push(...warnings);
812
- allDeferredForeignKeys.push(...deferredForeignKeys);
813
- for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
1004
+ const imports = createSchemaImports();
1005
+ this.schemaImports = imports;
1006
+ const schemaPaths = /* @__PURE__ */ new Map();
1007
+ for (const [name, config] of this.tables) {
1008
+ const schemaPath = await this.findTableSchemaFile(name, config);
1009
+ if (schemaPath) schemaPaths.set(name, schemaPath);
1010
+ }
1011
+ try {
1012
+ for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
1013
+ const tableTransform = tableNameToLoad === tableName ? transform : void 0;
1014
+ const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
1015
+ allErrors.push(...errors);
1016
+ allWarnings.push(...warnings);
1017
+ allDeferredForeignKeys.push(...deferredForeignKeys);
1018
+ for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
1019
+ }
1020
+ } finally {
1021
+ this.schemaImports = void 0;
1022
+ this.recordSchemaDependencies(imports, attemptedTables, schemaPaths, tableName === void 0);
814
1023
  }
815
1024
  if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
816
1025
  if (!loadedTables.has(fk.references.table)) continue;
@@ -835,6 +1044,9 @@ var LinesDB = class LinesDB {
835
1044
  tableResults
836
1045
  };
837
1046
  }
1047
+ importSchemaModule(schemaPath) {
1048
+ return (this.schemaImports ?? createSchemaImports()).import(schemaPath);
1049
+ }
838
1050
  /**
839
1051
  * Load a table and its dependencies recursively
840
1052
  */
@@ -857,10 +1069,9 @@ var LinesDB = class LinesDB {
857
1069
  try {
858
1070
  let foreignKeys;
859
1071
  try {
860
- const { pathToFileURL } = await import("node:url");
861
1072
  const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
862
1073
  if (schemaPath) {
863
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
1074
+ const schemaModule = await this.importSchemaModule(schemaPath);
864
1075
  foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
865
1076
  }
866
1077
  } catch {}
@@ -961,11 +1172,10 @@ var LinesDB = class LinesDB {
961
1172
  let validationSchema = config.validationSchema;
962
1173
  const schemaMetadata = {};
963
1174
  const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
964
- if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
1175
+ if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath), this.schemaImports);
965
1176
  if (!config.validationSchema) try {
966
- const { pathToFileURL } = await import("node:url");
967
1177
  if (!schemaPath) throw new Error("Schema file not found");
968
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
1178
+ const schemaModule = await this.importSchemaModule(schemaPath);
969
1179
  const schemaExport = schemaModule.schema || schemaModule.default;
970
1180
  if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
971
1181
  else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
@@ -2505,7 +2715,8 @@ var LinesDB = class LinesDB {
2505
2715
  }
2506
2716
  /**
2507
2717
  * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
2508
- * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
2718
+ * tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each
2719
+ * project file a schema imports edited, added or removed
2509
2720
  */
2510
2721
  async findExternalChanges() {
2511
2722
  try {
@@ -2524,6 +2735,16 @@ var LinesDB = class LinesDB {
2524
2735
  });
2525
2736
  if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
2526
2737
  }
2738
+ const knownHashes = /* @__PURE__ */ new Map();
2739
+ for (const files of this.schemaDependencyHashes.values()) for (const [file, knownHash] of files) knownHashes.set(file, (knownHashes.get(file) ?? /* @__PURE__ */ new Set()).add(knownHash));
2740
+ for (const [file, hashes] of knownHashes) {
2741
+ const content = await readFile(file).catch((error) => {
2742
+ if (error.code === "ENOENT") return void 0;
2743
+ throw error;
2744
+ });
2745
+ const current = content === void 0 ? MISSING_HASH : hashContent(content);
2746
+ if ([...hashes].some((hash) => hash !== current)) changed.add(file);
2747
+ }
2527
2748
  const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
2528
2749
  const scanned = new Set(listJsonlFiles(tables));
2529
2750
  for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
@@ -2546,6 +2767,25 @@ var LinesDB = class LinesDB {
2546
2767
  });
2547
2768
  return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
2548
2769
  }
2770
+ recordSchemaDependencies(imports, tableNames, schemaPaths, replace) {
2771
+ if (replace) {
2772
+ for (const name of this.schemaDependencyHashes.keys()) if (!schemaPaths.has(name)) this.schemaDependencyHashes.delete(name);
2773
+ }
2774
+ for (const name of tableNames) {
2775
+ const schemaPath = schemaPaths.get(name);
2776
+ if (schemaPath) this.schemaDependencyHashes.set(name, imports.dependencies(schemaPath));
2777
+ else this.schemaDependencyHashes.delete(name);
2778
+ }
2779
+ }
2780
+ /**
2781
+ * The project files the schemas import, as paths: not the schema files, and not a package from
2782
+ * node_modules. Those of one table when it is given. An edit to one of them is among
2783
+ * {@link findExternalChanges}
2784
+ */
2785
+ listSchemaDependencies(tableName) {
2786
+ const tables = tableName === void 0 ? [...this.schemaDependencyHashes.values()] : [this.schemaDependencyHashes.get(tableName) ?? /* @__PURE__ */ new Map()];
2787
+ return [...new Set(tables.flatMap((files) => [...files.keys()]))];
2788
+ }
2549
2789
  async schemaFileState(tableName, config) {
2550
2790
  if (config.validationSchema) return "";
2551
2791
  const schemaPath = await this.findTableSchemaFile(tableName, config);
@@ -2864,13 +3104,14 @@ async function fillFieldsInternal(options) {
2864
3104
  const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
2865
3105
  const tablesWithoutSchema = [];
2866
3106
  const tables = [];
3107
+ const imports = createSchemaImports();
2867
3108
  for (const { table, file, target, schemaDir } of sources.values()) {
2868
3109
  const schemaPath = await findSchemaFile(schemaDir, table);
2869
3110
  if (!schemaPath) {
2870
3111
  if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);
2871
3112
  continue;
2872
3113
  }
2873
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
3114
+ const schemaModule = await imports.import(schemaPath);
2874
3115
  tables.push({
2875
3116
  table,
2876
3117
  file,
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
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-aQqE1pe5.mjs";
1
+ import { A as ValidationErrorDetail, C as StandardSchemaResult, D as TableSchema, E as TableDefs, M as WhereCondition, N as WriteFilledValues, O as TableValidationResult, S as StandardSchemaIssue, T as TableConfig, _ as JsonObject, b as JsonlParseError, c as ok, d as DatabaseConfig, f as ForeignKeyDefinition, g as JsonArray, h as InferOutput, i as JsonlSnapshot, j as ValidationResult, k as ValidationError, l as unwrap, m as InferInput, o as Result, p as IndexDefinition, r as JsonlReader, s as err, t as SchemaImports, u as ColumnDefinition, v as JsonValue, w as Table, x as StandardSchema, y as JsonlConflictError } from "./schema-module-Tb40gPyF.mjs";
2
2
  /**
3
3
  * SQLite adapter for Node.js
4
4
  */
@@ -105,6 +105,8 @@ export declare class LinesDB<Tables extends TableDefs> {
105
105
  private tablesFromGivenColumns;
106
106
  /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
107
107
  private schemaFileStates;
108
+ private schemaImports;
109
+ private schemaDependencyHashes;
108
110
  private constructor();
109
111
  static create<Tables extends TableDefs>(config: DatabaseConfig<Tables>, dbPath?: string): LinesDB<Tables>;
110
112
  /**
@@ -123,6 +125,7 @@ export declare class LinesDB<Tables extends TableDefs> {
123
125
  }): Promise<Result<ValidationResult, Error>>;
124
126
  private initializeInternal;
125
127
  private loadTables;
128
+ private importSchemaModule;
126
129
  /**
127
130
  * Load a table and its dependencies recursively
128
131
  */
@@ -484,12 +487,20 @@ export declare class LinesDB<Tables extends TableDefs> {
484
487
  hasExternalChanges(): Promise<Result<boolean, Error>>;
485
488
  /**
486
489
  * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
487
- * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
490
+ * tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each
491
+ * project file a schema imports edited, added or removed
488
492
  */
489
493
  findExternalChanges(): Promise<Result<string[], Error>>;
490
494
  private findExternalChangesInternal;
491
495
  /** The state of the schema file a state names, for a table whose JSONL file is gone */
492
496
  private stateOfKnownSchemaFile;
497
+ private recordSchemaDependencies;
498
+ /**
499
+ * The project files the schemas import, as paths: not the schema files, and not a package from
500
+ * node_modules. Those of one table when it is given. An edit to one of them is among
501
+ * {@link findExternalChanges}
502
+ */
503
+ listSchemaDependencies(tableName?: string): string[];
493
504
  private schemaFileState;
494
505
  /**
495
506
  * Sync database changes back to JSONL files
@@ -641,7 +652,7 @@ export declare class SchemaLoader {
641
652
  * Load a validation schema file for a table
642
653
  * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
643
654
  */
644
- static loadSchema(jsonlPath: string, schemaDir?: string): Promise<StandardSchema>;
655
+ static loadSchema(jsonlPath: string, schemaDir?: string, imports?: SchemaImports): Promise<StandardSchema>;
645
656
  /**
646
657
  * Check if an object implements the StandardSchema interface
647
658
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/sqlite-adapter.ts","../src/database.ts","../src/jsonl-writer.ts","../src/merge-fields.ts","../src/fill.ts","../src/schema-loader.ts","../src/directory-scanner.ts","../src/schema.ts","../src/type-generator.ts","../src/jsonl-migration.ts","../src/schema-extensions.ts","../src/error-formatter.ts","../src/run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;;;;;;;;;;;;;;;;;;;;;wBAoCI,aAAa,cAAc,OAAO,eAAe,OAC/D,QAAQ,eAAe,OAAO,YAC3B,MAAM,eAAe,SAAS,UAAU,cAAc,OAAO,YAAY,SAAS,cAAc,OAAO,WACzG,oBAAoB,OAAO;;;;wBAkCd,YAAY,cAAc,OAAO,eAAe,OAC9D,QAAQ,eAAe,OAAO,UAC7B,UAAU,oBAAoB,OAAO;UCpIvB;EACf;EACA;EACA;;qBAQW;UACH;UACA;UACA;UACA;EAEI,YAAA,SAAS;;;;EAgBf,YAAY;;;;UAwBJ;;;;UA6BN;UA0DA;UAkBA;;UCjKO;EACf;EACA;EACA,MAAM;;;;;;wBAOc,qBAAqB,SAAS,yBAAyB;;;;;qBCThE;KACD,0BAA0B;;;;;wBAehB,eAAe,aAAa,oBAAoB;;;;wBAkCtD,aAAa;;;;;wBAQb,+BAA+B;;;;;wBAa/B,0BAA0B;UC3EzB;EACf;EACA;EACA,QAAQ,cAAc;EACtB;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;;qBAGW;UACH;EAEI,YAAA,UAAS;;;;EAOrB,uBAAuB,QAAQ;;;;EAU/B,sBAAsB,OAAO;;;;UAUrB;;;;UAiBA;;;;UAqCA;;;;UAOA;;;;UAoBA;;;;EAkBR,kBAAkB,eAAe;;;;EAQjC;;;;;KC9JU;wBAEI,iBAAiB;qBASpB,SAAO;UC2BH;EACf;;wBAGoB,kBACpB,eACA,UAAS,uBACR,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/sqlite-adapter.ts","../src/database.ts","../src/jsonl-writer.ts","../src/merge-fields.ts","../src/fill.ts","../src/schema-loader.ts","../src/directory-scanner.ts","../src/schema.ts","../src/type-generator.ts","../src/jsonl-migration.ts","../src/schema-extensions.ts","../src/error-formatter.ts","../src/runtime.ts","../src/dataset-config.ts"],"mappings":";;;;;;;UASiB;EACf,QAAQ,cAAc;EACtB,KAAK;EACL;;UAG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