@lines-db/studio 0.16.3 → 0.16.5

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,23 @@
1
1
  # @lines-db/studio
2
2
 
3
+ ## 0.16.5
4
+
5
+ ### Patch Changes
6
+
7
+ - 3833022: Watch the data and schema directories with `zygiella` instead of `fs.watch` for live reload. The Node.js requirement of Studio is now 22.18.0 or later, the same as `lines-db`, which Studio already depends on as a peer.
8
+
9
+ ## 0.16.4
10
+
11
+ ### Patch Changes
12
+
13
+ - aa9725e: `lines-db studio` now lists a table whose JSONL file has no rows, and a table with a primary key can have its first row added in the studio. The studio reads the columns of such a table from the types of its schema file, so the table is listed when the schema declares its input type through `~standard.types` (zod and valibot do; a hand-written Standard Schema has to declare `types`). Without types, the table stays out of the list as before. `DatabaseConfig` has a new `schemaOfEmptyTable` option to give the columns of a table with no rows. `lines-db validate` no longer says a table has "validation errors" when it only skips the foreign keys that point at an empty table; it says the table has no rows to read its columns from.
14
+ - Updated dependencies [8deddc8]
15
+ - Updated dependencies [aa9725e]
16
+ - Updated dependencies [376a141]
17
+ - Updated dependencies [8deddc8]
18
+ - Updated dependencies [8deddc8]
19
+ - lines-db@0.19.0
20
+
3
21
  ## 0.16.3
4
22
 
5
23
  ### Patch Changes
package/README.ja.md CHANGED
@@ -6,7 +6,7 @@ Studioは[lines-db](https://github.com/toiroakr/lines-db)のブラウザ用エ
6
6
 
7
7
  ## 起動する
8
8
 
9
- Node.js 22.12.0以降が必要です。プロジェクトに両方のパッケージをインストールします。
9
+ Node.js 22.18.0以降が必要です。プロジェクトに両方のパッケージをインストールします。
10
10
 
11
11
  ```bash
12
12
  npm install -D lines-db @lines-db/studio
package/README.md CHANGED
@@ -6,7 +6,7 @@ Studio is a browser editor for [lines-db](https://github.com/toiroakr/lines-db).
6
6
 
7
7
  ## Start Studio
8
8
 
9
- Requires Node.js 22.12.0 or later. Install both packages in the project.
9
+ Requires Node.js 22.18.0 or later. Install both packages in the project.
10
10
 
11
11
  ```bash
12
12
  npm install -D lines-db @lines-db/studio
package/dist/index.d.mts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { WriteFilledValues } from "lines-db";
2
- //#region src/server.d.ts
3
2
  interface StudioServerOptions {
4
3
  dataDir: string | string[];
5
4
  schemaDir?: string;
@@ -17,6 +16,5 @@ interface StudioServer {
17
16
  close(): Promise<void>;
18
17
  }
19
18
  export declare function startStudioServer(options: StudioServerOptions): Promise<StudioServer>;
20
- //#endregion
21
19
  export type { StudioServer, StudioServerOptions };
22
20
  //# sourceMappingURL=index.d.mts.map
@@ -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":";UA8BiB;EACf;EACA;;EAEA;;EAEA,oBAAoB;EACpB;EACA;;UAGe;EACf;;EAEA;EACA,SAAS;;wBAwBW,kBAAkB,SAAS,sBAAsB,QAAQ"}
package/dist/index.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { randomBytes, timingSafeEqual } from "node:crypto";
3
- import { watch } from "node:fs";
4
3
  import { readFile, realpath, stat, writeFile } from "node:fs/promises";
5
4
  import { createServer } from "node:http";
6
5
  import { basename, dirname, extname, join, relative, resolve, win32 } from "node:path";
7
6
  import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import { watch } from "zygiella";
8
8
  import { DirectoryScanner, ErrorFormatter, JsonlReader, LinesDB, findSchemaFile, unwrap } from "lines-db";
9
9
  import { hashJsonlContent, replaceFile } from "lines-db/internal";
10
- //#region src/declared-columns.ts
10
+ // src/declared-columns.ts
11
11
  const CORSA_NULL = 8;
12
12
  const CORSA_UNION = 134217728;
13
13
  const CORSA_OPTIONAL = 16777216;
@@ -190,8 +190,60 @@ async function readDeclaredColumns(schemaPath, searchFrom) {
190
190
  return;
191
191
  }
192
192
  }
193
- //#endregion
194
- //#region src/file-rows.ts
193
+ /**
194
+ * The table the columns a schema file declares make, for a table with no rows to infer them from. The types
195
+ * are written as the compiler prints them, so a number cannot be told an integer from a real one and is stored
196
+ * as REAL, which gives an integer back as one.
197
+ */
198
+ function tableSchemaOf(tableName, columns) {
199
+ return {
200
+ name: tableName,
201
+ columns: columns.map((column) => ({
202
+ name: column.name,
203
+ type: sqlTypeOf(column.type),
204
+ notNull: !column.optional && !column.nullable,
205
+ ...isBoolean(column.type) ? { valueType: "boolean" } : {}
206
+ }))
207
+ };
208
+ }
209
+ function kindOf(member) {
210
+ if (member === "string" || /^(".*"|'.*')$/.test(member)) return "text";
211
+ if (member === "number" || /^-?\d+(\.\d+)?$/.test(member)) return "number";
212
+ if (member === "boolean" || member === "true" || member === "false") return "boolean";
213
+ return "other";
214
+ }
215
+ function sqlTypeOf(type) {
216
+ const kinds = new Set(unionMembers(type).map(kindOf));
217
+ if (kinds.size !== 1) return "JSON";
218
+ const [kind] = kinds;
219
+ return kind === "text" ? "TEXT" : kind === "number" ? "REAL" : kind === "boolean" ? "INTEGER" : "JSON";
220
+ }
221
+ function isBoolean(type) {
222
+ return unionMembers(type).every((member) => kindOf(member) === "boolean");
223
+ }
224
+ /** The members of a union as the compiler prints it, split only where ` | ` is outside quotes and brackets */
225
+ function unionMembers(type) {
226
+ const members = [];
227
+ let depth = 0;
228
+ let quote;
229
+ let start = 0;
230
+ for (let index = 0; index < type.length; index++) {
231
+ const char = type[index];
232
+ if (quote) {
233
+ if (char === "\\") index++;
234
+ else if (char === quote) quote = void 0;
235
+ } else if (char === "\"" || char === "'") quote = char;
236
+ else if ("{[(<".includes(char)) depth++;
237
+ else if ("}])>".includes(char)) depth--;
238
+ else if (depth === 0 && type.startsWith(" | ", index)) {
239
+ members.push(type.slice(start, index));
240
+ start = index + 3;
241
+ }
242
+ }
243
+ members.push(type.slice(start));
244
+ return members;
245
+ }
246
+ // src/file-rows.ts
195
247
  /**
196
248
  * The content with the rows at the given indexes - counting the lines that hold a row, as reading
197
249
  * the file does - written over their lines, and every other line left as it was
@@ -207,8 +259,7 @@ function replaceRows(content, replaced) {
207
259
  return row ? `${JSON.stringify(row)}${carriage}` : raw;
208
260
  }).join("\n");
209
261
  }
210
- //#endregion
211
- //#region src/server.ts
262
+ // src/server.ts
212
263
  async function startStudioServer(options) {
213
264
  const dataDirs = [];
214
265
  const seen = /* @__PURE__ */ new Set();
@@ -296,10 +347,15 @@ async function startStudioServer(options) {
296
347
  const notifyChanged = () => {
297
348
  for (const client of eventClients) client.write("event: changed\ndata: {}\n\n");
298
349
  };
350
+ const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
299
351
  let watchTimer;
300
- const watchers = [.../* @__PURE__ */ new Set([...dataDirs, resolve(schemaDir)])].flatMap((dir) => {
352
+ const watchers = (await Promise.all([.../* @__PURE__ */ new Set([...dataDirs, resolve(schemaDir)])].map(async (dir) => {
301
353
  try {
302
- const watcher = watch(dir, () => {
354
+ const watcher = watch(dir, {
355
+ ignoreInitial: true,
356
+ depth: 0
357
+ });
358
+ watcher.on("all", () => {
303
359
  clearTimeout(watchTimer);
304
360
  watchTimer = setTimeout(() => {
305
361
  reloadIfChanged().catch(notifyChanged);
@@ -309,13 +365,18 @@ async function startStudioServer(options) {
309
365
  console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
310
366
  watcher.close();
311
367
  });
368
+ const { missing } = await watcher.ready;
369
+ if (missing.length > 0) {
370
+ console.warn(`Live reload is off for '${dir}': the directory does not exist`);
371
+ await watcher.close();
372
+ return [];
373
+ }
312
374
  return [watcher];
313
375
  } catch (error) {
314
376
  console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
315
377
  return [];
316
378
  }
317
- });
318
- const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
379
+ }))).flat();
319
380
  const server = createServer((req, res) => {
320
381
  handle(req, res).catch((error) => sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }));
321
382
  });
@@ -716,6 +777,7 @@ async function startStudioServer(options) {
716
777
  }
717
778
  };
718
779
  }
780
+ leeway.get(snapshot)?.delete(tableName);
719
781
  return {
720
782
  status: write.kind === "insert" ? 201 : 200,
721
783
  body: { ok: true },
@@ -734,7 +796,7 @@ async function startStudioServer(options) {
734
796
  });
735
797
  });
736
798
  } catch (error) {
737
- watchers.forEach((watcher) => watcher.close());
799
+ await Promise.all(watchers.map((watcher) => watcher.close()));
738
800
  await snapshot.db.close();
739
801
  throw error;
740
802
  }
@@ -743,7 +805,7 @@ async function startStudioServer(options) {
743
805
  url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
744
806
  token,
745
807
  close: async () => {
746
- watchers.forEach((watcher) => watcher.close());
808
+ await Promise.all(watchers.map((watcher) => watcher.close()));
747
809
  clearTimeout(watchTimer);
748
810
  server.closeAllConnections();
749
811
  await new Promise((resolve) => server.close(() => resolve()));
@@ -759,7 +821,11 @@ async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
759
821
  dataDir,
760
822
  schemaDir,
761
823
  writeFilledValues,
762
- writeDataSets: true
824
+ writeDataSets: true,
825
+ schemaOfEmptyTable: async ({ tableName, schemaPath }) => {
826
+ const declared = schemaPath && await readDeclaredColumns(schemaPath, schemaDir ?? dirname(schemaPath));
827
+ return declared ? tableSchemaOf(tableName, declared) : void 0;
828
+ }
763
829
  });
764
830
  const baseDir = [dataDir].flat()[0];
765
831
  const loaded = await db.initialize({ detailedValidate: true });
@@ -1203,7 +1269,6 @@ function parseJson(text, message) {
1203
1269
  function errorMessage(error) {
1204
1270
  return error instanceof Error ? error.message : String(error);
1205
1271
  }
1206
- //#endregion
1207
1272
  export { startStudioServer };
1208
1273
 
1209
1274
  //# sourceMappingURL=index.mjs.map