@lines-db/studio 0.0.0-stage → 0.16.2

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/dist/index.mjs ADDED
@@ -0,0 +1,1209 @@
1
+ import { createRequire } from "node:module";
2
+ import { randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { watch } from "node:fs";
4
+ import { readFile, realpath, stat, writeFile } from "node:fs/promises";
5
+ import { createServer } from "node:http";
6
+ import { basename, dirname, extname, join, relative, resolve, win32 } from "node:path";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import { DirectoryScanner, ErrorFormatter, JsonlReader, LinesDB, findSchemaFile, unwrap } from "lines-db";
9
+ import { hashJsonlContent, replaceFile } from "lines-db/internal";
10
+ //#region src/declared-columns.ts
11
+ const CORSA_NULL = 8;
12
+ const CORSA_UNION = 134217728;
13
+ const CORSA_OPTIONAL = 16777216;
14
+ /**
15
+ * Standard Schema holds the types of what it validates in `~standard.types`, which every library that
16
+ * implements it fills in, so the columns are read from the types and not from any one library
17
+ */
18
+ function columnsOf(reader) {
19
+ let type = reader.entryType();
20
+ for (const name of [
21
+ "~standard",
22
+ "types",
23
+ "input"
24
+ ]) {
25
+ const property = type && reader.property(type, name);
26
+ if (!property) return void 0;
27
+ type = reader.nonNullable(reader.typeOf(property));
28
+ }
29
+ const members = type ? reader.members(type) : [];
30
+ const merged = /* @__PURE__ */ new Map();
31
+ for (const member of members) for (const property of reader.properties(member)) {
32
+ const declared = reader.typeOf(property);
33
+ const name = reader.nameOf(property);
34
+ const column = merged.get(name) ?? {
35
+ types: [],
36
+ seen: 0,
37
+ optional: false,
38
+ nullable: false
39
+ };
40
+ const text = reader.text(reader.nonNullable(declared));
41
+ if (!column.types.includes(text)) column.types.push(text);
42
+ column.seen += 1;
43
+ column.optional ||= reader.isOptional(property);
44
+ column.nullable ||= reader.isNullable(declared);
45
+ merged.set(name, column);
46
+ }
47
+ if (merged.size === 0) return void 0;
48
+ return [...merged].map(([name, column]) => ({
49
+ name,
50
+ type: column.types.join(" | "),
51
+ optional: column.optional || column.seen < members.length,
52
+ nullable: column.nullable
53
+ }));
54
+ }
55
+ function readWithCompilerApi(ts, schemaPath) {
56
+ const configPath = ts.findConfigFile(dirname(schemaPath), ts.sys.fileExists);
57
+ const configured = configPath ? ts.parseJsonConfigFileContent(ts.readConfigFile(configPath, ts.sys.readFile).config, ts.sys, dirname(configPath)).options : {};
58
+ const program = ts.createProgram([schemaPath], {
59
+ target: ts.ScriptTarget.ESNext,
60
+ module: ts.ModuleKind.ESNext,
61
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
62
+ ...configured,
63
+ noEmit: true,
64
+ skipLibCheck: true,
65
+ strictNullChecks: true,
66
+ allowImportingTsExtensions: true,
67
+ types: []
68
+ });
69
+ const checker = program.getTypeChecker();
70
+ const file = program.getSourceFile(schemaPath);
71
+ const module = file && checker.getSymbolAtLocation(file);
72
+ const files = program.getSourceFiles().filter((source) => !program.isSourceFileFromExternalLibrary(source) && !program.isSourceFileDefaultLibrary(source)).map((source) => source.fileName);
73
+ if (configPath) files.push(configPath);
74
+ if (!file || !module) return {
75
+ columns: void 0,
76
+ files
77
+ };
78
+ return {
79
+ files,
80
+ columns: columnsOf({
81
+ entryType() {
82
+ const exports = checker.getExportsOfModule(module);
83
+ let entry = exports.find((symbol) => symbol.name === "schema") ?? exports.find((symbol) => symbol.name === "default");
84
+ if (entry && entry.flags & ts.SymbolFlags.Alias) entry = checker.getAliasedSymbol(entry);
85
+ return entry && checker.getTypeOfSymbolAtLocation(entry, file);
86
+ },
87
+ property: (type, name) => type.getProperty(name),
88
+ typeOf: (property) => checker.getTypeOfSymbol(property),
89
+ nonNullable: (type) => checker.getNonNullableType(type),
90
+ members: (type) => type.flags & ts.TypeFlags.Union ? type.types : [type],
91
+ properties: (type) => checker.getPropertiesOfType(type),
92
+ nameOf: (property) => property.name,
93
+ isOptional: (property) => Boolean(property.flags & ts.SymbolFlags.Optional),
94
+ isNullable: (type) => type.flags & ts.TypeFlags.Union ? type.types.some((member) => member.flags & ts.TypeFlags.Null) : Boolean(type.flags & ts.TypeFlags.Null),
95
+ text: (type) => checker.typeToString(type, void 0, ts.TypeFormatFlags.NoTruncation)
96
+ })
97
+ };
98
+ }
99
+ /**
100
+ * Whether a file of a program is one of the project's own, and not a library: those are in node_modules, or
101
+ * have names that are not paths of the disk at all. Either kind of separator, as on Windows.
102
+ */
103
+ function isProjectSource(name) {
104
+ return win32.isAbsolute(name) && !/[\\/]node_modules[\\/]/.test(name);
105
+ }
106
+ function readWithCorsa(api, schemaPath) {
107
+ try {
108
+ const program = api.createProgram([schemaPath], {
109
+ target: 99,
110
+ module: 99,
111
+ moduleResolution: 100,
112
+ strict: true,
113
+ skipLibCheck: true,
114
+ noEmit: true,
115
+ allowImportingTsExtensions: true,
116
+ types: []
117
+ });
118
+ const checker = program.getProject().checker;
119
+ const files = program.getSourceFileNames().filter(isProjectSource);
120
+ const module = checker.getSymbolOfSourceFile(schemaPath);
121
+ if (!module) return {
122
+ columns: void 0,
123
+ files
124
+ };
125
+ return {
126
+ files,
127
+ columns: columnsOf({
128
+ entryType() {
129
+ const exports = checker.getExportsOfModule(module);
130
+ const entry = exports.find((symbol) => symbol.name === "schema") ?? exports.find((symbol) => symbol.name === "default");
131
+ return entry && checker.getTypeOfSymbol(entry);
132
+ },
133
+ property: (type, name) => type.getProperty(name),
134
+ typeOf: (property) => checker.getTypeOfSymbol(property),
135
+ nonNullable: (type) => checker.getNonNullableType(type),
136
+ members: (type) => type.flags & CORSA_UNION ? type.getTypes() ?? [type] : [type],
137
+ properties: (type) => checker.getPropertiesOfType(type),
138
+ nameOf: (property) => property.name,
139
+ isOptional: (property) => Boolean(property.flags & CORSA_OPTIONAL),
140
+ isNullable: (type) => type.flags & CORSA_UNION ? (type.getTypes() ?? []).some((member) => member.flags & CORSA_NULL) : Boolean(type.flags & CORSA_NULL),
141
+ text: (type) => checker.typeToString(type)
142
+ })
143
+ };
144
+ } finally {
145
+ api.close();
146
+ }
147
+ }
148
+ /** The modification time of each file that can be read, which a reading is as fresh as */
149
+ async function stampsOf(files) {
150
+ const stamps = /* @__PURE__ */ new Map();
151
+ for (const file of new Set(files)) try {
152
+ stamps.set(file, (await stat(file)).mtimeMs);
153
+ } catch {}
154
+ return stamps;
155
+ }
156
+ async function isFresh(stamps) {
157
+ for (const [file, mtimeMs] of stamps) try {
158
+ if ((await stat(file)).mtimeMs !== mtimeMs) return false;
159
+ } catch {
160
+ return false;
161
+ }
162
+ return true;
163
+ }
164
+ const cache = /* @__PURE__ */ new Map();
165
+ /**
166
+ * The columns a schema file declares, read from its types with the TypeScript installed from `searchFrom`:
167
+ * the compiler API of typescript 5 and 6, or the Corsa API of typescript 7.1 and later. Undefined when there
168
+ * is none, the schema declares no types or the file cannot be read, so the caller can fall back on the rows.
169
+ */
170
+ async function readDeclaredColumns(schemaPath, searchFrom) {
171
+ try {
172
+ const schemaFile = resolve(schemaPath);
173
+ const from = resolve(searchFrom);
174
+ const key = `${from}\0${schemaFile}`;
175
+ const cached = cache.get(key);
176
+ if (cached && await isFresh(cached.stamps)) return cached.columns;
177
+ const require = createRequire(join(from, "noop.js"));
178
+ const { version } = require("typescript/package.json");
179
+ let reading;
180
+ if (Number.parseInt(version, 10) >= 7) {
181
+ const { API } = await import(pathToFileURL(require.resolve("typescript/sync")).href);
182
+ reading = readWithCorsa(new API({ cwd: dirname(schemaFile) }), schemaFile);
183
+ } else reading = readWithCompilerApi(require("typescript"), schemaFile);
184
+ cache.set(key, {
185
+ columns: reading.columns,
186
+ stamps: await stampsOf([schemaFile, ...reading.files])
187
+ });
188
+ return reading.columns;
189
+ } catch {
190
+ return;
191
+ }
192
+ }
193
+ //#endregion
194
+ //#region src/file-rows.ts
195
+ /**
196
+ * The content with the rows at the given indexes - counting the lines that hold a row, as reading
197
+ * the file does - written over their lines, and every other line left as it was
198
+ */
199
+ function replaceRows(content, replaced) {
200
+ const bom = content.startsWith("") ? "" : "";
201
+ let index = -1;
202
+ return bom + content.slice(bom.length).split("\n").map((raw) => {
203
+ const carriage = raw.endsWith("\r") ? "\r" : "";
204
+ if (raw.trim() === "") return raw;
205
+ index += 1;
206
+ const row = replaced.get(index);
207
+ return row ? `${JSON.stringify(row)}${carriage}` : raw;
208
+ }).join("\n");
209
+ }
210
+ //#endregion
211
+ //#region src/server.ts
212
+ async function startStudioServer(options) {
213
+ const dataDirs = [];
214
+ const seen = /* @__PURE__ */ new Set();
215
+ for (const dir of [options.dataDir].flat()) {
216
+ const resolved = resolve(dir);
217
+ const actual = await realpath(resolved);
218
+ if (seen.has(actual)) continue;
219
+ seen.add(actual);
220
+ dataDirs.push(resolved);
221
+ }
222
+ if (dataDirs.length === 0) throw new Error("Studio requires at least one data directory");
223
+ const dataDir = dataDirs[0];
224
+ const schemaDir = options.schemaDir ?? dataDir;
225
+ const host = options.host ?? "127.0.0.1";
226
+ const uiDir = options.uiDir ?? shippedUiDir();
227
+ const token = randomBytes(24).toString("base64url");
228
+ const writeFilledValues = options.writeFilledValues ?? "primaryKey";
229
+ const load = () => loadSnapshot(dataDirs, options.schemaDir, writeFilledValues);
230
+ let snapshot = await load();
231
+ let queue = Promise.resolve();
232
+ const serialize = (fn) => {
233
+ const result = queue.then(fn);
234
+ queue = result.catch(() => {});
235
+ return result;
236
+ };
237
+ /** Reload the tables when a JSONL file no longer holds what they were read from; true if it did */
238
+ const reloadUnlocked = async () => {
239
+ const previous = snapshot;
240
+ snapshot = await load();
241
+ await previous.db.close();
242
+ };
243
+ const reloadIfChangedUnlocked = async () => {
244
+ if (!unwrap(await snapshot.db.hasExternalChanges())) return false;
245
+ await reloadUnlocked();
246
+ notifyChanged();
247
+ return true;
248
+ };
249
+ const leeway = /* @__PURE__ */ new WeakMap();
250
+ const loadedColumnsOf = async (current, name) => {
251
+ const byTable = leeway.get(current) ?? /* @__PURE__ */ new Map();
252
+ leeway.set(current, byTable);
253
+ if (!byTable.has(name)) {
254
+ const [sample] = unwrap(await current.db.findWithDefaults(name));
255
+ const columns = current.db.getSchema(name)?.columns ?? [];
256
+ byTable.set(name, withLeeway(current.db, name, sample?.row, columns));
257
+ }
258
+ return byTable.get(name);
259
+ };
260
+ const references = /* @__PURE__ */ new WeakMap();
261
+ const referencesFor = async (current, name) => {
262
+ const byTable = references.get(current) ?? /* @__PURE__ */ new Map();
263
+ references.set(current, byTable);
264
+ if (!byTable.has(name)) byTable.set(name, await referencesOf(current.db, schemaDir, name));
265
+ return byTable.get(name);
266
+ };
267
+ const invalidColumns = /* @__PURE__ */ new WeakMap();
268
+ const invalidColumnsOf = async (current, name) => {
269
+ const byTable = invalidColumns.get(current) ?? /* @__PURE__ */ new Map();
270
+ invalidColumns.set(current, byTable);
271
+ if (!byTable.has(name)) {
272
+ const invalid = current.invalid.get(name);
273
+ const { issues } = invalid;
274
+ const rows = invalid.rows ?? unwrap(await JsonlReader.read(invalid.file));
275
+ const unknown = unknownFields(current.db, name, rows, issues);
276
+ const inferred = unwrap(JsonlReader.inferSchema(name, rows)).columns;
277
+ const missing = [...new Set([...issues.values()].flat().map(fieldOf))].filter((field) => field !== void 0 && !inferred.some((column) => column.name === field));
278
+ const columns = withLeeway(current.db, name, rows.find((_, index) => !issues.has(index)) ?? rows[0], [...inferred, ...missing.map((field) => ({
279
+ name: field,
280
+ type: "JSON",
281
+ notNull: false,
282
+ primaryKey: false
283
+ }))]).map((column) => ({
284
+ ...column,
285
+ primaryKey: false,
286
+ ...unknown.has(column.name) ? { unknown: true } : {}
287
+ }));
288
+ byTable.set(name, {
289
+ columns,
290
+ rowCount: rows.length
291
+ });
292
+ }
293
+ return byTable.get(name);
294
+ };
295
+ const eventClients = /* @__PURE__ */ new Set();
296
+ const notifyChanged = () => {
297
+ for (const client of eventClients) client.write("event: changed\ndata: {}\n\n");
298
+ };
299
+ let watchTimer;
300
+ const watchers = [.../* @__PURE__ */ new Set([...dataDirs, resolve(schemaDir)])].flatMap((dir) => {
301
+ try {
302
+ const watcher = watch(dir, () => {
303
+ clearTimeout(watchTimer);
304
+ watchTimer = setTimeout(() => {
305
+ reloadIfChanged().catch(notifyChanged);
306
+ }, 100);
307
+ });
308
+ watcher.on("error", (error) => {
309
+ console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
310
+ watcher.close();
311
+ });
312
+ return [watcher];
313
+ } catch (error) {
314
+ console.warn(`Live reload is off for '${dir}': ${errorMessage(error)}`);
315
+ return [];
316
+ }
317
+ });
318
+ const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
319
+ const server = createServer((req, res) => {
320
+ handle(req, res).catch((error) => sendJson(res, error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) }));
321
+ });
322
+ async function handle(req, res) {
323
+ const { port } = server.address();
324
+ const allowedHosts = /* @__PURE__ */ new Set([
325
+ `${host}:${port}`,
326
+ `127.0.0.1:${port}`,
327
+ `localhost:${port}`,
328
+ `[::1]:${port}`
329
+ ]);
330
+ if (!allowedHosts.has(req.headers.host ?? "")) {
331
+ sendJson(res, 403, { message: "Requests must be addressed to the local studio server" });
332
+ return;
333
+ }
334
+ const url = new URL(req.url ?? "/", "http://localhost");
335
+ if (req.method === "GET" && !url.pathname.startsWith("/api/")) {
336
+ await servePage(res, uiDir, url.pathname, token);
337
+ return;
338
+ }
339
+ if (!sameToken(bearerToken(req) ?? (url.pathname === "/api/events" ? url.searchParams.get("token") : null) ?? "", token)) {
340
+ sendJson(res, 401, { message: "This page holds no token of this run of lines-db studio. Reload it to get one." });
341
+ return;
342
+ }
343
+ const segments = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
344
+ if (req.method === "GET" && url.pathname === "/api/events") {
345
+ res.writeHead(200, {
346
+ "Content-Type": "text/event-stream",
347
+ "Cache-Control": "no-store"
348
+ });
349
+ res.write(": connected\n\n");
350
+ eventClients.add(res);
351
+ req.on("close", () => eventClients.delete(res));
352
+ return;
353
+ }
354
+ if (req.method === "GET" && url.pathname === "/api/tables") {
355
+ sendJson(res, 200, await serialize(async () => {
356
+ await reloadIfChangedUnlocked();
357
+ const current = snapshot;
358
+ const loadedTables = current.db.getTableNames().filter((name) => !current.invalid.has(name));
359
+ const tables = [];
360
+ for (const name of loadedTables) {
361
+ const columns = await loadedColumnsOf(current, name);
362
+ const primaryKey = columns.find((column) => column.primaryKey)?.name ?? null;
363
+ const rowCount = unwrap(current.db.queryOne(`SELECT COUNT(*) AS n FROM "${name.replaceAll("\"", "\"\"")}"`))?.n ?? 0;
364
+ tables.push({
365
+ name,
366
+ columns,
367
+ primaryKey,
368
+ rowCount,
369
+ invalidRows: 0,
370
+ readOnlyReason: whyReadOnly(current.db, name),
371
+ schemaFile: null,
372
+ references: await referencesFor(current, name)
373
+ });
374
+ }
375
+ for (const [name, { issues }] of current.invalid) {
376
+ const { columns, rowCount } = await invalidColumnsOf(current, name);
377
+ tables.push({
378
+ name,
379
+ columns,
380
+ primaryKey: null,
381
+ rowCount,
382
+ invalidRows: issues.size,
383
+ readOnlyReason: null,
384
+ schemaFile: null,
385
+ references: await referencesFor(current, name)
386
+ });
387
+ }
388
+ for (const table of tables) {
389
+ const schemaPath = await findSchemaFile(schemaDir, table.name);
390
+ table.schemaFile = schemaPath ? basename(schemaPath) : null;
391
+ }
392
+ tables.sort((a, b) => a.name.localeCompare(b.name));
393
+ return {
394
+ dataDir,
395
+ dataDirs,
396
+ schemaDir: resolve(schemaDir),
397
+ tables,
398
+ problems: current.problems
399
+ };
400
+ }));
401
+ return;
402
+ }
403
+ const [, , tableName, resource, encodedKey] = segments;
404
+ if (segments[0] === "api" && segments[1] === "tables" && resource === "schema" && segments.length === 4) {
405
+ if (req.method !== "GET") {
406
+ sendJson(res, 405, { message: "Method not allowed" });
407
+ return;
408
+ }
409
+ await reloadIfChanged();
410
+ const schemaPath = Boolean(snapshot.db.getSchema(tableName)) || snapshot.invalid.has(tableName) ? await findSchemaFile(schemaDir, tableName) : void 0;
411
+ if (!schemaPath) {
412
+ sendJson(res, 404, { message: `Table '${tableName}' has no schema file` });
413
+ return;
414
+ }
415
+ const loaded = snapshot.invalid.has(tableName) ? void 0 : snapshot.db.getSchema(tableName);
416
+ const declared = loaded && await readDeclaredColumns(schemaPath, schemaDir);
417
+ const flagsOf = (name) => {
418
+ const column = loaded?.columns.find((candidate) => candidate.name === name);
419
+ return {
420
+ ...column?.primaryKey ? { primaryKey: true } : {},
421
+ ...column?.unique ? { unique: true } : {}
422
+ };
423
+ };
424
+ sendJson(res, 200, {
425
+ file: basename(schemaPath),
426
+ source: await readFile(schemaPath, "utf-8"),
427
+ definition: loaded ? {
428
+ columnsFrom: declared ? "schema" : "rows",
429
+ columns: declared ? declared.map((column) => ({
430
+ ...column,
431
+ ...flagsOf(column.name)
432
+ })) : loaded.columns.map((column) => ({
433
+ name: column.name,
434
+ type: column.valueType ?? column.type,
435
+ ...column.notNull ? { notNull: true } : {},
436
+ ...flagsOf(column.name)
437
+ })),
438
+ foreignKeys: loaded.declaredForeignKeys ?? [],
439
+ indexes: loaded.indexes ?? []
440
+ } : null
441
+ });
442
+ return;
443
+ }
444
+ const isRows = segments[0] === "api" && segments[1] === "tables" && resource === "rows" && segments.length <= 5;
445
+ const isChanges = segments[0] === "api" && segments[1] === "tables" && (resource === "changes" || resource === "check") && segments.length === 4;
446
+ if (!isRows && !isChanges) {
447
+ sendJson(res, 404, { message: "Not found" });
448
+ return;
449
+ }
450
+ if (isRows && req.method === "GET" && encodedKey === void 0) {
451
+ await reloadIfChanged();
452
+ const invalid = snapshot.invalid.get(tableName);
453
+ if (invalid) {
454
+ if (invalid.rows) {
455
+ sendJson(res, 200, {
456
+ rows: invalid.rows,
457
+ defaulted: invalid.rows.map(() => []),
458
+ issues: Object.fromEntries(invalid.issues),
459
+ revision: invalid.revision
460
+ });
461
+ return;
462
+ }
463
+ const { rows, contentHash } = unwrap(await JsonlReader.readSnapshot(invalid.file));
464
+ const read = unwrap(rows);
465
+ sendJson(res, 200, {
466
+ rows: read,
467
+ defaulted: read.map(() => []),
468
+ issues: Object.fromEntries(invalid.issues),
469
+ revision: contentHash
470
+ });
471
+ return;
472
+ }
473
+ if (!snapshot.db.getSchema(tableName)) {
474
+ sendJson(res, 404, { message: `Table '${tableName}' does not exist` });
475
+ return;
476
+ }
477
+ const rows = unwrap(await snapshot.db.findWithDefaults(tableName));
478
+ sendJson(res, 200, {
479
+ rows: rows.map(({ row }) => row),
480
+ defaulted: rows.map(({ defaulted }) => defaulted)
481
+ });
482
+ return;
483
+ }
484
+ const write = isChanges ? req.method === "POST" ? resource === "check" ? { kind: "check" } : { kind: "batch" } : void 0 : writeOperation(req.method, encodedKey);
485
+ if (!write) {
486
+ sendJson(res, 405, { message: "Method not allowed" });
487
+ return;
488
+ }
489
+ const origin = req.headers.origin;
490
+ if (origin !== void 0 && !allowedHosts.has(origin.replace(/^http:\/\//, ""))) {
491
+ sendJson(res, 403, { message: "Writes are accepted from the studio page only" });
492
+ return;
493
+ }
494
+ if (write.kind !== "delete" && !isJsonMediaType(req.headers["content-type"])) {
495
+ sendJson(res, 415, { message: "Writes must be sent as application/json" });
496
+ return;
497
+ }
498
+ let batch;
499
+ if (write.kind === "batch" || write.kind === "check") batch = changeBatch(await readJson(req));
500
+ else if (write.kind === "delete") batch = {
501
+ inserts: [],
502
+ updates: [],
503
+ deletes: [write.key]
504
+ };
505
+ else {
506
+ const body = writeBody(await readJson(req));
507
+ batch = write.kind === "insert" ? {
508
+ inserts: [body.row ?? {}],
509
+ insertDataDirs: body.dataDir ? [body.dataDir] : void 0,
510
+ updates: [],
511
+ deletes: []
512
+ } : {
513
+ inserts: [],
514
+ updates: [{
515
+ key: write.key,
516
+ changes: body.changes ?? {},
517
+ resetToDefault: body.resetToDefault
518
+ }],
519
+ deletes: []
520
+ };
521
+ }
522
+ if (dataDirs.length > 1 && batch.inserts.some((_, index) => {
523
+ const dir = batch.insertDataDirs?.[index];
524
+ return !dir || !dataDirs.includes(resolve(dir));
525
+ })) throw new BadRequestError("Choose a data directory for each inserted row");
526
+ /** Apply the updates to the rows of the file, and write them only once every edited row passes */
527
+ const writeInvalidTable = async (invalid) => {
528
+ const { file } = invalid;
529
+ if (batch.inserts.length > 0 || batch.deletes.length > 0) return {
530
+ status: 409,
531
+ body: { message: "Fix the rows that fail validation before adding or deleting rows of this table" }
532
+ };
533
+ const files = await Promise.all((invalid.files ?? [{ file }]).map(async ({ file }) => ({
534
+ file,
535
+ content: await readFile(file, "utf8")
536
+ })));
537
+ const content = files[0].content;
538
+ const revision = files.length > 1 || invalid.files ? hashJsonlContent(JSON.stringify(files)) : hashJsonlContent(content);
539
+ if (batch.revision !== revision) return {
540
+ status: 409,
541
+ body: { message: files.length > 1 ? "Source files changed since their rows were read; reload the table to see them" : `${relative(dataDir, file)} changed since its rows were read; reload the table to see them` }
542
+ };
543
+ const rows = invalid.rows ?? unwrap(await JsonlReader.read(file));
544
+ const replaced = /* @__PURE__ */ new Map();
545
+ for (const [index, { key, changes, resetToDefault }] of batch.updates.entries()) {
546
+ const base = typeof key === "number" ? replaced.get(key) ?? rows[key] : void 0;
547
+ if (!base) return {
548
+ status: 400,
549
+ body: { message: `No row ${JSON.stringify(key)} in ${relative(dataDir, file)}` }
550
+ };
551
+ const next = {
552
+ ...base,
553
+ ...changes
554
+ };
555
+ for (const field of resetToDefault ?? []) delete next[field];
556
+ const validated = snapshot.db.validateRow(tableName, next);
557
+ if (!validated.ok) {
558
+ const change = {
559
+ kind: "update",
560
+ index,
561
+ key
562
+ };
563
+ const failure = {
564
+ message: validated.error.message,
565
+ issues: perKey(validated.error.issues),
566
+ change
567
+ };
568
+ return write.kind === "check" ? {
569
+ status: 200,
570
+ body: {
571
+ ok: false,
572
+ ...failure
573
+ }
574
+ } : {
575
+ status: 400,
576
+ body: failure
577
+ };
578
+ }
579
+ replaced.set(key, next);
580
+ }
581
+ if (write.kind === "check") return {
582
+ status: 200,
583
+ body: { ok: true }
584
+ };
585
+ const plans = files.map(({ file, content }) => {
586
+ const changes = /* @__PURE__ */ new Map();
587
+ for (const [index, row] of replaced) {
588
+ const source = invalid.sources?.[index] ?? {
589
+ file: invalid.file,
590
+ rowIndex: index
591
+ };
592
+ if (source.file === file) changes.set(source.rowIndex, row);
593
+ }
594
+ return {
595
+ file,
596
+ content,
597
+ next: replaceRows(content, changes),
598
+ changed: changes.size > 0
599
+ };
600
+ }).filter((plan) => plan.changed);
601
+ const written = [];
602
+ try {
603
+ for (const plan of plans) {
604
+ await replaceUnchangedFile(plan.file, plan.next, plan.content);
605
+ written.push(plan);
606
+ }
607
+ } catch (error) {
608
+ const unrestored = [];
609
+ for (const plan of written) await replaceUnchangedFile(plan.file, plan.content, plan.next).catch(() => unrestored.push(plan.file));
610
+ if (unrestored.length) throw new Error(`${errorMessage(error)}; could not restore ${unrestored.join(", ")}`, { cause: error });
611
+ if (error instanceof Error && error.name === "JsonlConflictError") {
612
+ await reloadUnlocked();
613
+ return {
614
+ status: 409,
615
+ body: { message: error.message },
616
+ changed: true
617
+ };
618
+ }
619
+ throw error;
620
+ }
621
+ await reloadUnlocked();
622
+ const stillFailing = [...replaced.keys()].map((index) => ({
623
+ index,
624
+ issues: snapshot.invalid.get(tableName)?.issues.get(index) ?? []
625
+ })).filter(({ issues }) => issues.length > 0);
626
+ return {
627
+ status: 200,
628
+ body: {
629
+ ok: true,
630
+ ...stillFailing.length > 0 ? { stillFailing } : {}
631
+ },
632
+ changed: true
633
+ };
634
+ };
635
+ let reloaded = false;
636
+ const outcome = await serialize(async () => {
637
+ const changedFiles = unwrap(await snapshot.db.findExternalChanges());
638
+ if (changedFiles.length > 0) {
639
+ await reloadUnlocked();
640
+ reloaded = true;
641
+ if (write.kind === "check") changedFiles.length = 0;
642
+ const ownFile = changedFiles.find((file) => dataDirs.some((dir) => resolve(file) === resolve(dir, `${tableName}.jsonl`)) || basename(file).startsWith(`${tableName}.schema.`));
643
+ if (ownFile) return {
644
+ status: 409,
645
+ body: { message: `${relative(dataDir, ownFile) || ownFile} changed on disk, so the tables were reloaded. Check the rows and try again.` },
646
+ changed: true
647
+ };
648
+ }
649
+ const { db } = snapshot;
650
+ const invalid = snapshot.invalid.get(tableName);
651
+ if (invalid) return writeInvalidTable(invalid);
652
+ const schema = db.getSchema(tableName);
653
+ if (!schema) return {
654
+ status: 404,
655
+ body: { message: `Table '${tableName}' does not exist` }
656
+ };
657
+ const primaryKey = schema.columns.find((column) => column.primaryKey)?.name;
658
+ const reason = whyReadOnly(db, tableName);
659
+ if (!primaryKey || reason) return {
660
+ status: 409,
661
+ body: { message: reason }
662
+ };
663
+ const result = await db.transaction((tx) => {
664
+ const check = (written, change) => {
665
+ if (!written.ok) throw Object.assign(written.error, { change });
666
+ };
667
+ batch.deletes.forEach((key, index) => check(tx.delete(tableName, { [primaryKey]: key }), {
668
+ kind: "delete",
669
+ index,
670
+ key
671
+ }));
672
+ batch.updates.forEach(({ key, changes, resetToDefault }, index) => check(tx.update(tableName, changes, { [primaryKey]: key }, { resetToDefault }), {
673
+ kind: "update",
674
+ index,
675
+ key
676
+ }));
677
+ batch.inserts.forEach((row, index) => check(tx.insert(tableName, row, { dataDir: batch.insertDataDirs?.[index] }), {
678
+ kind: "insert",
679
+ index
680
+ }));
681
+ if (write.kind === "check") throw DRY_RUN;
682
+ });
683
+ if (write.kind === "check") {
684
+ if (!result.ok && result.error === DRY_RUN) return {
685
+ status: 200,
686
+ body: { ok: true }
687
+ };
688
+ const failure = result.ok ? {} : result.error;
689
+ return {
690
+ status: 200,
691
+ body: {
692
+ ok: false,
693
+ message: failure.message,
694
+ issues: perKey(failure.issues ?? []),
695
+ ...failure.change ? { change: failure.change } : {}
696
+ }
697
+ };
698
+ }
699
+ if (!result.ok) {
700
+ if (result.error.name === "JsonlConflictError") {
701
+ await reloadUnlocked();
702
+ const { file } = result.error;
703
+ return {
704
+ status: 409,
705
+ body: { message: `${relative(dataDir, file) || file} changed on disk, so the tables were reloaded. Check the rows and try again.` },
706
+ changed: true
707
+ };
708
+ }
709
+ const { issues, change } = result.error;
710
+ return {
711
+ status: 400,
712
+ body: {
713
+ message: result.error.message,
714
+ ...issues ? { issues: perKey(issues) } : {},
715
+ ...change ? { change } : {}
716
+ }
717
+ };
718
+ }
719
+ return {
720
+ status: write.kind === "insert" ? 201 : 200,
721
+ body: { ok: true },
722
+ changed: true
723
+ };
724
+ });
725
+ sendJson(res, outcome.status, outcome.body);
726
+ if (outcome.changed || reloaded) notifyChanged();
727
+ }
728
+ try {
729
+ await new Promise((resolve, reject) => {
730
+ server.once("error", reject);
731
+ server.listen(options.port ?? 4848, host, () => {
732
+ server.off("error", reject);
733
+ resolve();
734
+ });
735
+ });
736
+ } catch (error) {
737
+ watchers.forEach((watcher) => watcher.close());
738
+ await snapshot.db.close();
739
+ throw error;
740
+ }
741
+ const { port } = server.address();
742
+ return {
743
+ url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
744
+ token,
745
+ close: async () => {
746
+ watchers.forEach((watcher) => watcher.close());
747
+ clearTimeout(watchTimer);
748
+ server.closeAllConnections();
749
+ await new Promise((resolve) => server.close(() => resolve()));
750
+ await serialize(() => snapshot.db.close());
751
+ }
752
+ };
753
+ }
754
+ async function replaceUnchangedFile(file, next, expected) {
755
+ await replaceFile(file, (temporary) => writeFile(temporary, next, "utf8"), expected);
756
+ }
757
+ async function loadSnapshot(dataDir, schemaDir, writeFilledValues) {
758
+ const db = LinesDB.create({
759
+ dataDir,
760
+ schemaDir,
761
+ writeFilledValues,
762
+ writeDataSets: true
763
+ });
764
+ const baseDir = [dataDir].flat()[0];
765
+ const loaded = await db.initialize({ detailedValidate: true });
766
+ if (!loaded.ok) {
767
+ await db.close();
768
+ if (loaded.error.name === "JsonlParseError") {
769
+ const { file, line, message } = loaded.error;
770
+ throw new Error(`${relative(baseDir, file) || file}:${line}: ${message}`, { cause: loaded.error });
771
+ }
772
+ throw loaded.error;
773
+ }
774
+ return {
775
+ db,
776
+ problems: describeProblems(baseDir, loaded.value.errors),
777
+ invalid: typeof dataDir !== "string" && dataDir.length > 1 ? await composedInvalidTables(dataDir, loaded.value.errors) : invalidTables(loaded.value.errors)
778
+ };
779
+ }
780
+ /**
781
+ * Each column with whether the schema lets it be null and lets the key be left out. A schema does not
782
+ * list what it takes, so a row is validated with the field set to null and with the key removed, and
783
+ * the column counts as taking it when no issue is about that field; an issue about another field is
784
+ * the row's own and says nothing of this one
785
+ */
786
+ function withLeeway(db, tableName, sample, columns) {
787
+ const probe = prober(db, tableName, sample ?? {});
788
+ return columns.map((column) => {
789
+ const { [column.name]: _removed, ...without } = sample ?? {};
790
+ const value = sample?.[column.name];
791
+ const takes = (row) => {
792
+ const { taken, value: validated, failsAt } = probe(row);
793
+ return taken && !failsAt([column.name]) && (!column.notNull || (validated?.[column.name] ?? null) !== null);
794
+ };
795
+ return {
796
+ ...column,
797
+ nullable: takes({
798
+ ...without,
799
+ [column.name]: null
800
+ }),
801
+ optional: takes(without),
802
+ ...sample && value !== null && typeof value === "object" ? { nested: nestedLeeway(db, tableName, sample, column.name) } : {}
803
+ };
804
+ });
805
+ }
806
+ /**
807
+ * Whether the schema takes a change of the sample row: it does when the change brings no issue the
808
+ * sample did not have. Not only an issue about the field changed counts, as a check across fields
809
+ * reports on another field, or on the row as a whole
810
+ */
811
+ function prober(db, tableName, sample) {
812
+ const issuesOf = (result) => !result ? void 0 : result.ok ? [] : perKey(result.error.issues).map((issue) => JSON.stringify(issue));
813
+ const before = new Set(issuesOf(tryValidate(db, tableName, sample)));
814
+ return (row) => {
815
+ const result = tryValidate(db, tableName, row);
816
+ const taken = issuesOf(result)?.every((issue) => before.has(issue)) ?? false;
817
+ const paths = result && !result.ok ? perKey(result.error.issues).map((issue) => (issue.path ?? []).map(keyOf)) : [];
818
+ const failsAt = (path) => paths.some((at) => path.every((segment, index) => at[index] === String(segment)));
819
+ return {
820
+ taken,
821
+ value: result?.ok ? result.value : void 0,
822
+ failsAt
823
+ };
824
+ };
825
+ }
826
+ /**
827
+ * The foreign keys of a table, as the row form opens the row a key refers to by them. Read from its
828
+ * schema file first: the database leaves out a key to a table whose rows failed on load, and has no
829
+ * schema at all for a table whose own rows failed, though the studio lists those tables and their rows
830
+ */
831
+ async function referencesOf(db, dataDir, tableName) {
832
+ const declared = await foreignKeysInFile(dataDir, tableName);
833
+ return (declared.length > 0 ? declared : db.getSchema(tableName)?.foreignKeys ?? []).map((fk) => ({
834
+ column: fk.column,
835
+ table: fk.references.table,
836
+ referencedColumn: fk.references.column
837
+ }));
838
+ }
839
+ /** The foreign keys a table's schema file exports, as the database reads them on load */
840
+ async function foreignKeysInFile(dataDir, tableName) {
841
+ const schemaPath = await findSchemaFile(dataDir, tableName);
842
+ if (!schemaPath) return [];
843
+ try {
844
+ const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
845
+ return (module.schema ?? module.default)?.foreignKeys ?? module.foreignKeys ?? [];
846
+ } catch {
847
+ return [];
848
+ }
849
+ }
850
+ /**
851
+ * The row validated, or undefined when the schema threw: a schema can assume a value the change took
852
+ * away, such as reading the keys of an object removed, and that says it does not take the change
853
+ */
854
+ function tryValidate(db, tableName, row) {
855
+ try {
856
+ return db.validateRow(tableName, row);
857
+ } catch {
858
+ return;
859
+ }
860
+ }
861
+ /** A key no schema names, added to an object to see whether the schema takes keys it does not name */
862
+ const PROBE_KEY = "__lines_db_studio_probe__";
863
+ /**
864
+ * What the schema takes of each object inside the sample's value of a JSON column, by its path there
865
+ * with list indexes as `*` (`''` for the value itself, `items.*.name` for a key of each item, and
866
+ * `%`, `.` and `*` in a key as `%25`, `%2E` and `%2A`). Found as
867
+ * for a column, from the issues a change brings that the sample did not have: a key added to an object
868
+ * tells whether it takes keys it does not name, and a key removed whether it can be left out. The
869
+ * items of a list are changed together in one check, so what one of them refuses counts as refused for all
870
+ */
871
+ function nestedLeeway(db, tableName, sample, column) {
872
+ const probe = prober(db, tableName, sample);
873
+ const atAll = (paths, change) => ({
874
+ ...sample,
875
+ [column]: paths.reduce((value, path) => changeAt(value, path, change), sample[column])
876
+ });
877
+ const objects = /* @__PURE__ */ new Map();
878
+ const walk = (value, path, pattern) => {
879
+ if (Array.isArray(value)) {
880
+ value.forEach((item, index) => walk(item, [...path, index], [...pattern, "*"]));
881
+ return;
882
+ }
883
+ if (value === null || typeof value !== "object") return;
884
+ const key = pattern.join(".");
885
+ objects.set(key, [...objects.get(key) ?? [], {
886
+ path,
887
+ object: value
888
+ }]);
889
+ for (const [name, item] of Object.entries(value)) walk(item, [...path, name], [...pattern, segmentOf(name)]);
890
+ };
891
+ walk(sample[column], [], []);
892
+ const leeway = {};
893
+ for (const [pattern, found] of objects) {
894
+ const prefix = pattern === "" ? "" : `${pattern}.`;
895
+ const filled = found.filter(({ object }) => Object.keys(object).length > 0);
896
+ if (filled.length > 0) {
897
+ let added = PROBE_KEY;
898
+ while (filled.some(({ object }) => Object.hasOwn(object, added))) added += "_";
899
+ leeway[pattern] = { open: probe(atAll(filled.map(({ path }) => path), (object) => ({
900
+ ...object,
901
+ [added]: Object.values(object)[0]
902
+ }))).taken };
903
+ }
904
+ const keys = new Set(found.flatMap(({ object }) => Object.keys(object)));
905
+ for (const name of keys) {
906
+ const holding = found.filter(({ object }) => Object.hasOwn(object, name)).map(({ path }) => path);
907
+ const { taken, failsAt } = probe(atAll(holding, (object) => {
908
+ const { [name]: _removed, ...rest } = object;
909
+ return rest;
910
+ }));
911
+ const optional = taken && !holding.some((path) => failsAt([
912
+ column,
913
+ ...path,
914
+ name
915
+ ]));
916
+ leeway[`${prefix}${segmentOf(name)}`] = {
917
+ ...leeway[`${prefix}${segmentOf(name)}`],
918
+ optional
919
+ };
920
+ }
921
+ }
922
+ return leeway;
923
+ }
924
+ /** A key as a segment of a pattern, apart from the dots between segments and the `*` of a list index */
925
+ const segmentOf = (key) => key.replace(/[%.*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
926
+ /** The value with the object at the path inside it changed */
927
+ function changeAt(value, path, change) {
928
+ if (path.length === 0) return change(value);
929
+ const [head, ...rest] = path;
930
+ if (Array.isArray(value)) return value.map((item, index) => index === head ? changeAt(item, rest, change) : item);
931
+ const object = value;
932
+ return {
933
+ ...object,
934
+ [head]: changeAt(object[head], rest, change)
935
+ };
936
+ }
937
+ /**
938
+ * The issues with one about several refused keys split per key. Zod reports the keys a strict object
939
+ * refuses in one issue at the path of the object and the keys beside it, which no field would be found
940
+ * by, nor a key inside a JSON value
941
+ */
942
+ function perKey(issues) {
943
+ return issues.flatMap((issue) => {
944
+ const { code, keys } = issue;
945
+ if (code !== "unrecognized_keys" || !Array.isArray(keys)) return [issue];
946
+ if (keys.length === 0 || !keys.every((key) => typeof key === "string")) return [issue];
947
+ return keys.map((key) => ({
948
+ ...issue,
949
+ keys: [key],
950
+ path: [...issue.path ?? [], { key }]
951
+ }));
952
+ });
953
+ }
954
+ /** A segment of an issue's path as the key it names */
955
+ const keyOf = (segment) => typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment);
956
+ /** The field of the row an issue is about, if it is about one */
957
+ function fieldOf(issue) {
958
+ const segment = issue.path?.[0];
959
+ if (segment === void 0) return void 0;
960
+ return typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment);
961
+ }
962
+ /**
963
+ * The fields of a table's rows its schema refuses as keys, which a fix can only remove. A schema does
964
+ * not list its keys, so a field counts when removing it from each row it fails on clears its issues,
965
+ * and no row that passes keeps it: removing a known optional field holding a wrong value clears its
966
+ * issue too, but a passing row then has it
967
+ */
968
+ function unknownFields(db, tableName, rows, issues) {
969
+ const failingOn = /* @__PURE__ */ new Map();
970
+ for (const [index, rowIssues] of issues) for (const issue of rowIssues) {
971
+ const key = fieldOf(issue);
972
+ if (key !== void 0 && Object.hasOwn(rows[index] ?? {}, key)) failingOn.set(key, [...failingOn.get(key) ?? [], index]);
973
+ }
974
+ const kept = /* @__PURE__ */ new Set();
975
+ rows.forEach((row, index) => {
976
+ if (issues.has(index)) return;
977
+ const validated = tryValidate(db, tableName, row);
978
+ if (validated?.ok) for (const key of Object.keys(validated.value)) kept.add(key);
979
+ });
980
+ const unknown = /* @__PURE__ */ new Set();
981
+ for (const [key, indexes] of failingOn) {
982
+ if (kept.has(key)) continue;
983
+ if (indexes.every((index) => {
984
+ const { [key]: _removed, ...rest } = rows[index];
985
+ const result = tryValidate(db, tableName, rest);
986
+ return result !== void 0 && (result.ok || !perKey(result.error.issues).some((issue) => fieldOf(issue) === key));
987
+ })) unknown.add(key);
988
+ }
989
+ return unknown;
990
+ }
991
+ /** The tables whose failing rows all come from one file, which can then be edited line by line */
992
+ function invalidTables(errors) {
993
+ const tables = /* @__PURE__ */ new Map();
994
+ for (const error of errors) {
995
+ const known = tables.get(error.tableName);
996
+ if (known === null) continue;
997
+ if (known && known.file !== error.file) {
998
+ tables.set(error.tableName, null);
999
+ continue;
1000
+ }
1001
+ const table = known ?? {
1002
+ file: error.file,
1003
+ issues: /* @__PURE__ */ new Map()
1004
+ };
1005
+ const foreignKey = error.foreignKeyError;
1006
+ const issues = foreignKey ? [{
1007
+ message: `No ${foreignKey.referencedTable} row has ${foreignKey.referencedColumn} ${JSON.stringify(foreignKey.value)}`,
1008
+ path: [{ key: foreignKey.column }]
1009
+ }] : perKey(error.issues);
1010
+ table.issues.set(error.rowIndex, [...table.issues.get(error.rowIndex) ?? [], ...issues]);
1011
+ tables.set(error.tableName, table);
1012
+ }
1013
+ return new Map([...tables].filter((entry) => entry[1] !== null));
1014
+ }
1015
+ async function composedInvalidTables(dataDirs, errors) {
1016
+ const tables = await DirectoryScanner.scanDirectory(dataDirs);
1017
+ const invalid = /* @__PURE__ */ new Map();
1018
+ for (const name of new Set(errors.map((error) => error.tableName))) {
1019
+ const config = tables.get(name);
1020
+ const rows = [];
1021
+ const adjusted = [];
1022
+ const files = [];
1023
+ const sources = [];
1024
+ for (const file of config.jsonlPaths ?? [config.jsonlPath]) {
1025
+ const offset = rows.length;
1026
+ const read = unwrap(await JsonlReader.read(file));
1027
+ files.push({
1028
+ file,
1029
+ content: await readFile(file, "utf8")
1030
+ });
1031
+ sources.push(...read.map((_, rowIndex) => ({
1032
+ file,
1033
+ rowIndex
1034
+ })));
1035
+ rows.push(...read);
1036
+ adjusted.push(...errors.filter((error) => error.tableName === name && error.file === file).map((error) => ({
1037
+ ...error,
1038
+ file: config.jsonlPath,
1039
+ rowIndex: offset + error.rowIndex
1040
+ })));
1041
+ }
1042
+ const table = invalidTables(adjusted).get(name);
1043
+ invalid.set(name, {
1044
+ ...table,
1045
+ rows,
1046
+ files,
1047
+ sources,
1048
+ revision: hashJsonlContent(JSON.stringify(files))
1049
+ });
1050
+ }
1051
+ return invalid;
1052
+ }
1053
+ function describeProblems(dataDir, errors) {
1054
+ const formatter = new ErrorFormatter();
1055
+ return errors.map((error) => {
1056
+ const file = relative(dataDir, error.file) || error.file;
1057
+ const foreignKey = error.foreignKeyError;
1058
+ return foreignKey ? formatter.formatForeignKeyError({
1059
+ file,
1060
+ rowIndex: error.rowIndex,
1061
+ ...foreignKey
1062
+ }) : formatter.formatValidationErrors([{
1063
+ file,
1064
+ rowIndex: error.rowIndex,
1065
+ issues: error.issues
1066
+ }]);
1067
+ });
1068
+ }
1069
+ const CONTENT_TYPES = {
1070
+ ".html": "text/html; charset=utf-8",
1071
+ ".js": "text/javascript; charset=utf-8",
1072
+ ".css": "text/css; charset=utf-8",
1073
+ ".svg": "image/svg+xml",
1074
+ ".png": "image/png",
1075
+ ".ico": "image/x-icon",
1076
+ ".woff2": "font/woff2",
1077
+ ".json": "application/json; charset=utf-8"
1078
+ };
1079
+ function shippedUiDir() {
1080
+ return fileURLToPath(new URL("../ui", import.meta.url));
1081
+ }
1082
+ /** Serve a file of the built page, the page itself carrying the token */
1083
+ async function servePage(res, uiDir, pathname, token) {
1084
+ const isPage = pathname === "/" || pathname === "/index.html";
1085
+ const file = resolve(uiDir, `.${isPage ? "/index.html" : pathname}`);
1086
+ if (relative(uiDir, file).startsWith("..")) {
1087
+ sendJson(res, 404, { message: "Not found" });
1088
+ return;
1089
+ }
1090
+ const content = await readFile(file).catch((error) => {
1091
+ if (error.code === "ENOENT" || error.code === "EISDIR") return void 0;
1092
+ throw error;
1093
+ });
1094
+ if (!content) {
1095
+ if (isPage) {
1096
+ res.writeHead(503, { "Content-Type": "text/plain; charset=utf-8" });
1097
+ res.end("The studio page has not been built. Run `pnpm build` in the lines-db repository.");
1098
+ return;
1099
+ }
1100
+ sendJson(res, 404, { message: "Not found" });
1101
+ return;
1102
+ }
1103
+ const nonce = randomBytes(18).toString("base64");
1104
+ const body = isPage ? Buffer.from(content.toString("utf8").replace("</head>", `<meta name="csp-nonce" content="${nonce}"><meta name="studio-token" content="${token}"></head>`)) : content;
1105
+ res.writeHead(200, {
1106
+ "Content-Type": CONTENT_TYPES[extname(file)] ?? "application/octet-stream",
1107
+ "Content-Security-Policy": `default-src 'none'; script-src 'self'; style-src 'self' 'nonce-${nonce}'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
1108
+ "Cache-Control": isPage ? "no-store" : "public, max-age=31536000, immutable",
1109
+ "X-Content-Type-Options": "nosniff"
1110
+ });
1111
+ res.end(body);
1112
+ }
1113
+ function bearerToken(req) {
1114
+ return /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1];
1115
+ }
1116
+ function sameToken(presented, token) {
1117
+ const a = Buffer.from(presented);
1118
+ const b = Buffer.from(token);
1119
+ return a.length === b.length && timingSafeEqual(a, b);
1120
+ }
1121
+ const NO_PRIMARY_KEY = "This table has no primary key, so a row cannot be told apart from the others. Add an \"id\" column or declare primaryKey in its schema file to edit it here.";
1122
+ /** Why a table cannot be edited here: a row is found by its primary key, which must tell every row apart */
1123
+ function whyReadOnly(db, tableName) {
1124
+ const primaryKey = db.getSchema(tableName)?.columns.find((column) => column.primaryKey)?.name;
1125
+ if (!primaryKey) return NO_PRIMARY_KEY;
1126
+ const quote = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
1127
+ const missing = unwrap(db.queryOne(`SELECT COUNT(*) AS n FROM ${quote(tableName)} WHERE ${quote(primaryKey)} IS NULL`))?.n ?? 0;
1128
+ return missing > 0 ? `${missing} row(s) have no value for the primary key ${primaryKey}, so they cannot be told apart. Give them one in the JSONL file to edit this table here.` : null;
1129
+ }
1130
+ function writeOperation(method, encodedKey) {
1131
+ if (method === "POST" && encodedKey === void 0) return { kind: "insert" };
1132
+ if (encodedKey === void 0) return void 0;
1133
+ const key = parseJson(encodedKey, "The row key in the address is not JSON");
1134
+ if (method === "PATCH") return {
1135
+ kind: "update",
1136
+ key
1137
+ };
1138
+ if (method === "DELETE") return {
1139
+ kind: "delete",
1140
+ key
1141
+ };
1142
+ }
1143
+ function sendJson(res, status, body) {
1144
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
1145
+ res.end(JSON.stringify(body));
1146
+ }
1147
+ async function readJson(req) {
1148
+ const chunks = [];
1149
+ for await (const chunk of req) chunks.push(chunk);
1150
+ return parseJson(Buffer.concat(chunks).toString("utf8"), "The request body is not JSON");
1151
+ }
1152
+ function isJsonObject(value) {
1153
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1154
+ }
1155
+ function isFieldList(value) {
1156
+ return Array.isArray(value) && value.every((field) => typeof field === "string");
1157
+ }
1158
+ /** `application/json`, with or without parameters such as a charset */
1159
+ function isJsonMediaType(contentType) {
1160
+ return contentType?.split(";")[0].trim().toLowerCase() === "application/json";
1161
+ }
1162
+ function changeBatch(body) {
1163
+ if (!isJsonObject(body)) throw new BadRequestError("The request body must be a JSON object");
1164
+ const { inserts = [], updates = [], deletes = [], insertDataDirs } = body;
1165
+ if (insertDataDirs !== void 0 && (!Array.isArray(insertDataDirs) || !insertDataDirs.every((dir) => typeof dir === "string") || insertDataDirs.length !== (Array.isArray(inserts) ? inserts.length : 0))) throw new BadRequestError("`insertDataDirs` must name a directory for each insert");
1166
+ if (!Array.isArray(inserts) || !inserts.every(isJsonObject)) throw new BadRequestError("`inserts` must be a list of rows");
1167
+ if (!Array.isArray(deletes)) throw new BadRequestError("`deletes` must be a list of primary keys");
1168
+ if (!Array.isArray(updates) || !updates.every((update) => isJsonObject(update) && "key" in update && isJsonObject(update.changes) && (update.resetToDefault === void 0 || isFieldList(update.resetToDefault)))) throw new BadRequestError("`updates` must be a list of { key, changes, resetToDefault? }");
1169
+ if (body.revision !== void 0 && typeof body.revision !== "string") throw new BadRequestError("`revision` must be a string");
1170
+ return {
1171
+ inserts,
1172
+ insertDataDirs,
1173
+ updates,
1174
+ deletes,
1175
+ revision: body.revision
1176
+ };
1177
+ }
1178
+ function writeBody(body) {
1179
+ if (!isJsonObject(body)) throw new BadRequestError("The request body must be a JSON object");
1180
+ const { row, changes, resetToDefault, dataDir } = body;
1181
+ if (dataDir !== void 0 && typeof dataDir !== "string") throw new BadRequestError("`dataDir` must be a string");
1182
+ if (row !== void 0 && !isJsonObject(row)) throw new BadRequestError("`row` must be an object");
1183
+ if (changes !== void 0 && !isJsonObject(changes)) throw new BadRequestError("`changes` must be an object");
1184
+ if (resetToDefault !== void 0 && !isFieldList(resetToDefault)) throw new BadRequestError("`resetToDefault` must be a list of field names");
1185
+ return {
1186
+ row,
1187
+ changes,
1188
+ resetToDefault,
1189
+ dataDir
1190
+ };
1191
+ }
1192
+ /** Thrown at the end of a checked batch, so its transaction rolls back */
1193
+ const DRY_RUN = /* @__PURE__ */ new Error("dry run");
1194
+ /** An error in the request itself, answered with 400 */
1195
+ var BadRequestError = class extends Error {};
1196
+ function parseJson(text, message) {
1197
+ try {
1198
+ return JSON.parse(text);
1199
+ } catch {
1200
+ throw new BadRequestError(message);
1201
+ }
1202
+ }
1203
+ function errorMessage(error) {
1204
+ return error instanceof Error ? error.message : String(error);
1205
+ }
1206
+ //#endregion
1207
+ export { startStudioServer };
1208
+
1209
+ //# sourceMappingURL=index.mjs.map