@lines-db/studio 0.16.5 → 0.16.6

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,15 @@
1
1
  # @lines-db/studio
2
2
 
3
+ ## 0.16.6
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
+ - Updated dependencies [4bfd4b7]
11
+ - lines-db@0.19.1
12
+
3
13
  ## 0.16.5
4
14
 
5
15
  ### Patch Changes
package/README.ja.md CHANGED
@@ -69,7 +69,7 @@ npx lines-db studio --data-dir seed/data --data-dir seed/data/cogs --schema-dir
69
69
 
70
70
  ## 他のツールでファイルを変更した場合
71
71
 
72
- Studioはディスク上のファイルを監視します。未保存の編集がなければ変更後のデータを読み直し、編集が残っていれば通知を表示します。
72
+ Studioはディスク上のファイルを監視します。スキーマがimportするテーブル定義などのプロジェクト内ファイルも対象です。未保存の編集がなければ変更後のデータを読み直し、編集が残っていれば通知を表示します。
73
73
 
74
74
  保存前にスキーマの変更を確認し、変更されていれば読み直して検証します。書き込み対象のファイルが変更されていた場合は、何も書き込まずに保存を中止します。ファイル名を表示し、テーブルを読み直します。`CASCADE`や`SET NULL`などの外部キーの操作で変更されるテーブルも対象です。無関係なテーブルのファイルの変更では保存を中止しません。
75
75
 
package/README.md CHANGED
@@ -69,7 +69,7 @@ Updates and deletions go back to each row's source file. In **Add record**, choo
69
69
 
70
70
  ## Changes made outside Studio
71
71
 
72
- Studio watches the files on disk. With no pending edits, it reloads changed data automatically. With pending edits, it shows a notice.
72
+ Studio watches the files on disk, including the project files the schemas import, such as a table definition. With no pending edits, it reloads changed data automatically. With pending edits, it shows a notice.
73
73
 
74
74
  Before saving, Studio reloads changed schemas and validates against them. If a file that the save would write has changed, the save stops, names the file, and reloads the tables without writing. This includes tables affected by foreign key actions such as `CASCADE` or `SET NULL`. Changes to unrelated table files do not stop the save.
75
75
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UA8BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";UA+BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { existsSync } from "node:fs";
3
4
  import { readFile, realpath, stat, writeFile } from "node:fs/promises";
4
5
  import { createServer } from "node:http";
5
6
  import { basename, dirname, extname, join, relative, resolve, win32 } from "node:path";
6
7
  import { fileURLToPath, pathToFileURL } from "node:url";
7
8
  import { watch } from "zygiella";
8
9
  import { DirectoryScanner, ErrorFormatter, JsonlReader, LinesDB, findSchemaFile, unwrap } from "lines-db";
9
- import { hashJsonlContent, replaceFile } from "lines-db/internal";
10
+ import { createSchemaImports, hashJsonlContent, replaceFile } from "lines-db/internal";
10
11
  // src/declared-columns.ts
11
12
  const CORSA_NULL = 8;
12
13
  const CORSA_UNION = 134217728;
@@ -277,7 +278,14 @@ async function startStudioServer(options) {
277
278
  const uiDir = options.uiDir ?? shippedUiDir();
278
279
  const token = randomBytes(24).toString("base64url");
279
280
  const writeFilledValues = options.writeFilledValues ?? "primaryKey";
280
- const load = () => loadSnapshot(dataDirs, options.schemaDir, writeFilledValues);
281
+ let failedDependencies = [];
282
+ const load = async () => {
283
+ const loaded = await loadSnapshot(dataDirs, options.schemaDir, writeFilledValues, (files) => {
284
+ failedDependencies = files;
285
+ });
286
+ failedDependencies = [];
287
+ return loaded;
288
+ };
281
289
  let snapshot = await load();
282
290
  let queue = Promise.resolve();
283
291
  const serialize = (fn) => {
@@ -288,7 +296,11 @@ async function startStudioServer(options) {
288
296
  /** Reload the tables when a JSONL file no longer holds what they were read from; true if it did */
289
297
  const reloadUnlocked = async () => {
290
298
  const previous = snapshot;
291
- snapshot = await load();
299
+ try {
300
+ snapshot = await load();
301
+ } finally {
302
+ watchDependencies();
303
+ }
292
304
  await previous.db.close();
293
305
  };
294
306
  const reloadIfChangedUnlocked = async () => {
@@ -349,18 +361,19 @@ async function startStudioServer(options) {
349
361
  };
350
362
  const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
351
363
  let watchTimer;
364
+ const scheduleReload = () => {
365
+ clearTimeout(watchTimer);
366
+ watchTimer = setTimeout(() => {
367
+ reloadIfChanged().catch(notifyChanged);
368
+ }, 100);
369
+ };
352
370
  const watchers = (await Promise.all([.../* @__PURE__ */ new Set([...dataDirs, resolve(schemaDir)])].map(async (dir) => {
353
371
  try {
354
372
  const watcher = watch(dir, {
355
373
  ignoreInitial: true,
356
374
  depth: 0
357
375
  });
358
- watcher.on("all", () => {
359
- clearTimeout(watchTimer);
360
- watchTimer = setTimeout(() => {
361
- reloadIfChanged().catch(notifyChanged);
362
- }, 100);
363
- });
376
+ watcher.on("all", scheduleReload);
364
377
  watcher.on("error", (error) => {
365
378
  console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
366
379
  watcher.close();
@@ -377,6 +390,40 @@ async function startStudioServer(options) {
377
390
  return [];
378
391
  }
379
392
  }))).flat();
393
+ const existingPathOf = (file) => {
394
+ let path = file;
395
+ while (!existsSync(path) && dirname(path) !== path) path = dirname(path);
396
+ return path;
397
+ };
398
+ let dependencyWatcher;
399
+ let watchedDependencies = [];
400
+ const watchDependencies = () => {
401
+ const wanted = [...new Set([...snapshot.db.listSchemaDependencies(), ...failedDependencies].map(existingPathOf))];
402
+ if (!dependencyWatcher) {
403
+ if (wanted.length === 0) return;
404
+ try {
405
+ const created = watch(wanted, {
406
+ ignoreInitial: true,
407
+ depth: 0
408
+ });
409
+ created.on("all", scheduleReload);
410
+ created.on("error", (error) => {
411
+ console.warn(`Live reload is off for the files the schemas import: ${errorMessage(error)}`);
412
+ created.close();
413
+ if (dependencyWatcher === created) dependencyWatcher = void 0;
414
+ });
415
+ dependencyWatcher = created;
416
+ } catch (error) {
417
+ console.warn(`Live reload is off for the files the schemas import: ${errorMessage(error)}`);
418
+ return;
419
+ }
420
+ } else {
421
+ dependencyWatcher.unwatch(watchedDependencies.filter((file) => !wanted.includes(file)));
422
+ dependencyWatcher.add(wanted.filter((file) => !watchedDependencies.includes(file)));
423
+ }
424
+ watchedDependencies = wanted;
425
+ };
426
+ watchDependencies();
380
427
  const server = createServer((req, res) => {
381
428
  handle(req, res).catch((error) => sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }));
382
429
  });
@@ -697,10 +744,11 @@ async function startStudioServer(options) {
697
744
  const outcome = await serialize(async () => {
698
745
  const changedFiles = unwrap(await snapshot.db.findExternalChanges());
699
746
  if (changedFiles.length > 0) {
747
+ const tableImports = snapshot.db.listSchemaDependencies(tableName);
700
748
  await reloadUnlocked();
701
749
  reloaded = true;
702
750
  if (write.kind === "check") changedFiles.length = 0;
703
- const ownFile = changedFiles.find((file) => dataDirs.some((dir) => resolve(file) === resolve(dir, `${tableName}.jsonl`)) || basename(file).startsWith(`${tableName}.schema.`));
751
+ const ownFile = changedFiles.find((file) => dataDirs.some((dir) => resolve(file) === resolve(dir, `${tableName}.jsonl`)) || basename(file).startsWith(`${tableName}.schema.`) || tableImports.includes(file));
704
752
  if (ownFile) return {
705
753
  status: 409,
706
754
  body: { message: `${relative(dataDir, ownFile) || ownFile} changed on disk, so the tables were reloaded. Check the rows and try again.` },
@@ -796,7 +844,7 @@ async function startStudioServer(options) {
796
844
  });
797
845
  });
798
846
  } catch (error) {
799
- await Promise.all(watchers.map((watcher) => watcher.close()));
847
+ await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
800
848
  await snapshot.db.close();
801
849
  throw error;
802
850
  }
@@ -805,7 +853,7 @@ async function startStudioServer(options) {
805
853
  url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
806
854
  token,
807
855
  close: async () => {
808
- await Promise.all(watchers.map((watcher) => watcher.close()));
856
+ await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
809
857
  clearTimeout(watchTimer);
810
858
  server.closeAllConnections();
811
859
  await new Promise((resolve) => server.close(() => resolve()));
@@ -816,7 +864,7 @@ async function startStudioServer(options) {
816
864
  async function replaceUnchangedFile(file, next, expected) {
817
865
  await replaceFile(file, (temporary) => writeFile(temporary, next, "utf8"), expected);
818
866
  }
819
- async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
867
+ async function loadSnapshot(dataDir, schemaDir, writeFilledValues, onFailure) {
820
868
  const db = LinesDB.create({
821
869
  dataDir,
822
870
  schemaDir,
@@ -830,6 +878,7 @@ async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
830
878
  const baseDir = [dataDir].flat()[0];
831
879
  const loaded = await db.initialize({ detailedValidate: true });
832
880
  if (!loaded.ok) {
881
+ onFailure(db.listSchemaDependencies());
833
882
  await db.close();
834
883
  if (loaded.error.name === "JsonlParseError") {
835
884
  const { file, line, message } = loaded.error;
@@ -907,7 +956,7 @@ async function foreignKeysInFile(dataDir, tableName) {
907
956
  const schemaPath = await findSchemaFile(dataDir, tableName);
908
957
  if (!schemaPath) return [];
909
958
  try {
910
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
959
+ const module = await createSchemaImports().import(schemaPath);
911
960
  return (module.schema ?? module.default)?.foreignKeys ?? module.foreignKeys ?? [];
912
961
  } catch {
913
962
  return [];