@lines-db/studio 0.16.6 → 0.16.8
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 +28 -0
- package/README.ja.md +26 -0
- package/README.md +26 -0
- package/dist/index.d.mts +16 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +202 -167
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
- package/ui/assets/index-BOXnVdiV.js +91 -0
- package/ui/assets/index-DqhpJkVr.css +2 -0
- package/ui/index.html +2 -2
- package/ui/assets/index-CM-ZFnfz.js +0 -91
- package/ui/assets/index-DB7uh2ec.css +0 -2
package/dist/index.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { existsSync } from "node:fs";
|
|
|
4
4
|
import { readFile, realpath, stat, writeFile } from "node:fs/promises";
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
6
|
import { basename, dirname, extname, join, relative, resolve, win32 } from "node:path";
|
|
7
|
+
import { Readable, pipeline } from "node:stream";
|
|
7
8
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
9
|
import { watch } from "zygiella";
|
|
9
10
|
import { DirectoryScanner, ErrorFormatter, JsonlReader, LinesDB, findSchemaFile, unwrap } from "lines-db";
|
|
@@ -261,7 +262,7 @@ function replaceRows(content, replaced) {
|
|
|
261
262
|
}).join("\n");
|
|
262
263
|
}
|
|
263
264
|
// src/server.ts
|
|
264
|
-
async function
|
|
265
|
+
async function createStudioHandler(options) {
|
|
265
266
|
const dataDirs = [];
|
|
266
267
|
const seen = /* @__PURE__ */ new Set();
|
|
267
268
|
for (const dir of [options.dataDir].flat()) {
|
|
@@ -274,7 +275,6 @@ async function startStudioServer(options) {
|
|
|
274
275
|
if (dataDirs.length === 0) throw new Error("Studio requires at least one data directory");
|
|
275
276
|
const dataDir = dataDirs[0];
|
|
276
277
|
const schemaDir = options.schemaDir ?? dataDir;
|
|
277
|
-
const host = options.host ?? "127.0.0.1";
|
|
278
278
|
const uiDir = options.uiDir ?? shippedUiDir();
|
|
279
279
|
const token = randomBytes(24).toString("base64url");
|
|
280
280
|
const writeFilledValues = options.writeFilledValues ?? "primaryKey";
|
|
@@ -355,9 +355,10 @@ async function startStudioServer(options) {
|
|
|
355
355
|
}
|
|
356
356
|
return byTable.get(name);
|
|
357
357
|
};
|
|
358
|
+
const encoder = new TextEncoder();
|
|
358
359
|
const eventClients = /* @__PURE__ */ new Set();
|
|
359
360
|
const notifyChanged = () => {
|
|
360
|
-
for (const client of eventClients) client.
|
|
361
|
+
for (const client of eventClients) client.enqueue(encoder.encode("event: changed\ndata: {}\n\n"));
|
|
361
362
|
};
|
|
362
363
|
const reloadIfChanged = () => serialize(reloadIfChangedUnlocked);
|
|
363
364
|
let watchTimer;
|
|
@@ -424,102 +425,103 @@ async function startStudioServer(options) {
|
|
|
424
425
|
watchedDependencies = wanted;
|
|
425
426
|
};
|
|
426
427
|
watchDependencies();
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
`127.0.0.1:${port}`,
|
|
435
|
-
`localhost:${port}`,
|
|
436
|
-
`[::1]:${port}`
|
|
437
|
-
]);
|
|
438
|
-
if (!allowedHosts.has(req.headers.host ?? "")) {
|
|
439
|
-
sendJson(res, 403, { message: "Requests must be addressed to the local studio server" });
|
|
440
|
-
return;
|
|
441
|
-
}
|
|
442
|
-
const url = new URL(req.url ?? "/", "http://localhost");
|
|
443
|
-
if (req.method === "GET" && !url.pathname.startsWith("/api/")) {
|
|
444
|
-
await servePage(res, uiDir, url.pathname, token);
|
|
445
|
-
return;
|
|
446
|
-
}
|
|
447
|
-
if (!sameToken(bearerToken(req) ?? (url.pathname === "/api/events" ? url.searchParams.get("token") : null) ?? "", token)) {
|
|
448
|
-
sendJson(res, 401, { message: "This page holds no token of this run of lines-db studio. Reload it to get one." });
|
|
449
|
-
return;
|
|
428
|
+
let closing = false;
|
|
429
|
+
const fetch = async (request) => {
|
|
430
|
+
if (closing) return jsonResponse(503, { message: "The studio is shutting down" });
|
|
431
|
+
try {
|
|
432
|
+
return await handle(request);
|
|
433
|
+
} catch (error) {
|
|
434
|
+
return jsonResponse(error instanceof BadRequestError ? 400 : 500, { message: errorMessage(error) });
|
|
450
435
|
}
|
|
436
|
+
};
|
|
437
|
+
async function handle(request) {
|
|
438
|
+
const url = new URL(request.url);
|
|
439
|
+
if (request.method === "GET" && !url.pathname.startsWith("/api/")) return servePage(uiDir, url.pathname, {
|
|
440
|
+
token,
|
|
441
|
+
frameAncestors: options.frameAncestors ?? "none",
|
|
442
|
+
requestHeaders: options.requestHeaders
|
|
443
|
+
});
|
|
444
|
+
if (!sameToken(bearerToken(request) ?? (url.pathname === "/api/events" ? url.searchParams.get("token") : null) ?? "", token)) return jsonResponse(401, { message: "This page holds no token of this run of lines-db studio. Reload it to get one." });
|
|
451
445
|
const segments = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
|
452
|
-
if (
|
|
453
|
-
|
|
446
|
+
if (request.method === "GET" && url.pathname === "/api/events") {
|
|
447
|
+
let client;
|
|
448
|
+
const end = () => {
|
|
449
|
+
request.signal.removeEventListener("abort", end);
|
|
450
|
+
if (!eventClients.delete(client)) return;
|
|
451
|
+
try {
|
|
452
|
+
client.close();
|
|
453
|
+
} catch {}
|
|
454
|
+
};
|
|
455
|
+
const stream = new ReadableStream({
|
|
456
|
+
start(controller) {
|
|
457
|
+
client = controller;
|
|
458
|
+
if (request.signal.aborted) {
|
|
459
|
+
controller.close();
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
eventClients.add(controller);
|
|
463
|
+
request.signal.addEventListener("abort", end, { once: true });
|
|
464
|
+
controller.enqueue(encoder.encode(": connected\n\n"));
|
|
465
|
+
},
|
|
466
|
+
cancel: end
|
|
467
|
+
});
|
|
468
|
+
return new Response(stream, { headers: {
|
|
454
469
|
"Content-Type": "text/event-stream",
|
|
455
470
|
"Cache-Control": "no-store"
|
|
456
|
-
});
|
|
457
|
-
res.write(": connected\n\n");
|
|
458
|
-
eventClients.add(res);
|
|
459
|
-
req.on("close", () => eventClients.delete(res));
|
|
460
|
-
return;
|
|
461
|
-
}
|
|
462
|
-
if (req.method === "GET" && url.pathname === "/api/tables") {
|
|
463
|
-
sendJson(res, 200, await serialize(async () => {
|
|
464
|
-
await reloadIfChangedUnlocked();
|
|
465
|
-
const current = snapshot;
|
|
466
|
-
const loadedTables = current.db.getTableNames().filter((name) => !current.invalid.has(name));
|
|
467
|
-
const tables = [];
|
|
468
|
-
for (const name of loadedTables) {
|
|
469
|
-
const columns = await loadedColumnsOf(current, name);
|
|
470
|
-
const primaryKey = columns.find((column) => column.primaryKey)?.name ?? null;
|
|
471
|
-
const rowCount = unwrap(current.db.queryOne(`SELECT COUNT(*) AS n FROM "${name.replaceAll("\"", "\"\"")}"`))?.n ?? 0;
|
|
472
|
-
tables.push({
|
|
473
|
-
name,
|
|
474
|
-
columns,
|
|
475
|
-
primaryKey,
|
|
476
|
-
rowCount,
|
|
477
|
-
invalidRows: 0,
|
|
478
|
-
readOnlyReason: whyReadOnly(current.db, name),
|
|
479
|
-
schemaFile: null,
|
|
480
|
-
references: await referencesFor(current, name)
|
|
481
|
-
});
|
|
482
|
-
}
|
|
483
|
-
for (const [name, { issues }] of current.invalid) {
|
|
484
|
-
const { columns, rowCount } = await invalidColumnsOf(current, name);
|
|
485
|
-
tables.push({
|
|
486
|
-
name,
|
|
487
|
-
columns,
|
|
488
|
-
primaryKey: null,
|
|
489
|
-
rowCount,
|
|
490
|
-
invalidRows: issues.size,
|
|
491
|
-
readOnlyReason: null,
|
|
492
|
-
schemaFile: null,
|
|
493
|
-
references: await referencesFor(current, name)
|
|
494
|
-
});
|
|
495
|
-
}
|
|
496
|
-
for (const table of tables) {
|
|
497
|
-
const schemaPath = await findSchemaFile(schemaDir, table.name);
|
|
498
|
-
table.schemaFile = schemaPath ? basename(schemaPath) : null;
|
|
499
|
-
}
|
|
500
|
-
tables.sort((a, b) => a.name.localeCompare(b.name));
|
|
501
|
-
return {
|
|
502
|
-
dataDir,
|
|
503
|
-
dataDirs,
|
|
504
|
-
schemaDir: resolve(schemaDir),
|
|
505
|
-
tables,
|
|
506
|
-
problems: current.problems
|
|
507
|
-
};
|
|
508
|
-
}));
|
|
509
|
-
return;
|
|
471
|
+
} });
|
|
510
472
|
}
|
|
473
|
+
if (request.method === "GET" && url.pathname === "/api/tables") return jsonResponse(200, await serialize(async () => {
|
|
474
|
+
await reloadIfChangedUnlocked();
|
|
475
|
+
const current = snapshot;
|
|
476
|
+
const loadedTables = current.db.getTableNames().filter((name) => !current.invalid.has(name));
|
|
477
|
+
const tables = [];
|
|
478
|
+
for (const name of loadedTables) {
|
|
479
|
+
const columns = await loadedColumnsOf(current, name);
|
|
480
|
+
const primaryKey = columns.find((column) => column.primaryKey)?.name ?? null;
|
|
481
|
+
const rowCount = unwrap(current.db.queryOne(`SELECT COUNT(*) AS n FROM "${name.replaceAll("\"", "\"\"")}"`))?.n ?? 0;
|
|
482
|
+
tables.push({
|
|
483
|
+
name,
|
|
484
|
+
columns,
|
|
485
|
+
primaryKey,
|
|
486
|
+
rowCount,
|
|
487
|
+
invalidRows: 0,
|
|
488
|
+
readOnlyReason: whyReadOnly(current.db, name),
|
|
489
|
+
schemaFile: null,
|
|
490
|
+
references: await referencesFor(current, name)
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
for (const [name, { issues }] of current.invalid) {
|
|
494
|
+
const { columns, rowCount } = await invalidColumnsOf(current, name);
|
|
495
|
+
tables.push({
|
|
496
|
+
name,
|
|
497
|
+
columns,
|
|
498
|
+
primaryKey: null,
|
|
499
|
+
rowCount,
|
|
500
|
+
invalidRows: issues.size,
|
|
501
|
+
readOnlyReason: null,
|
|
502
|
+
schemaFile: null,
|
|
503
|
+
references: await referencesFor(current, name)
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
for (const table of tables) {
|
|
507
|
+
const schemaPath = await findSchemaFile(schemaDir, table.name);
|
|
508
|
+
table.schemaFile = schemaPath ? basename(schemaPath) : null;
|
|
509
|
+
}
|
|
510
|
+
tables.sort((a, b) => a.name.localeCompare(b.name));
|
|
511
|
+
return {
|
|
512
|
+
dataDir,
|
|
513
|
+
dataDirs,
|
|
514
|
+
schemaDir: resolve(schemaDir),
|
|
515
|
+
tables,
|
|
516
|
+
problems: current.problems
|
|
517
|
+
};
|
|
518
|
+
}));
|
|
511
519
|
const [, , tableName, resource, encodedKey] = segments;
|
|
512
520
|
if (segments[0] === "api" && segments[1] === "tables" && resource === "schema" && segments.length === 4) {
|
|
513
|
-
if (
|
|
514
|
-
sendJson(res, 405, { message: "Method not allowed" });
|
|
515
|
-
return;
|
|
516
|
-
}
|
|
521
|
+
if (request.method !== "GET") return jsonResponse(405, { message: "Method not allowed" });
|
|
517
522
|
await reloadIfChanged();
|
|
518
523
|
const schemaPath = Boolean(snapshot.db.getSchema(tableName)) || snapshot.invalid.has(tableName) ? await findSchemaFile(schemaDir, tableName) : void 0;
|
|
519
|
-
if (!schemaPath) {
|
|
520
|
-
sendJson(res, 404, { message: `Table '${tableName}' has no schema file` });
|
|
521
|
-
return;
|
|
522
|
-
}
|
|
524
|
+
if (!schemaPath) return jsonResponse(404, { message: `Table '${tableName}' has no schema file` });
|
|
523
525
|
const loaded = snapshot.invalid.has(tableName) ? void 0 : snapshot.db.getSchema(tableName);
|
|
524
526
|
const declared = loaded && await readDeclaredColumns(schemaPath, schemaDir);
|
|
525
527
|
const flagsOf = (name) => {
|
|
@@ -529,7 +531,7 @@ async function startStudioServer(options) {
|
|
|
529
531
|
...column?.unique ? { unique: true } : {}
|
|
530
532
|
};
|
|
531
533
|
};
|
|
532
|
-
|
|
534
|
+
return jsonResponse(200, {
|
|
533
535
|
file: basename(schemaPath),
|
|
534
536
|
source: await readFile(schemaPath, "utf-8"),
|
|
535
537
|
definition: loaded ? {
|
|
@@ -547,71 +549,51 @@ async function startStudioServer(options) {
|
|
|
547
549
|
indexes: loaded.indexes ?? []
|
|
548
550
|
} : null
|
|
549
551
|
});
|
|
550
|
-
return;
|
|
551
552
|
}
|
|
552
553
|
const isRows = segments[0] === "api" && segments[1] === "tables" && resource === "rows" && segments.length <= 5;
|
|
553
554
|
const isChanges = segments[0] === "api" && segments[1] === "tables" && (resource === "changes" || resource === "check") && segments.length === 4;
|
|
554
|
-
if (!isRows && !isChanges) {
|
|
555
|
-
|
|
556
|
-
return;
|
|
557
|
-
}
|
|
558
|
-
if (isRows && req.method === "GET" && encodedKey === void 0) {
|
|
555
|
+
if (!isRows && !isChanges) return jsonResponse(404, { message: "Not found" });
|
|
556
|
+
if (isRows && request.method === "GET" && encodedKey === void 0) {
|
|
559
557
|
await reloadIfChanged();
|
|
560
558
|
const invalid = snapshot.invalid.get(tableName);
|
|
561
559
|
if (invalid) {
|
|
562
|
-
if (invalid.rows) {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
});
|
|
569
|
-
return;
|
|
570
|
-
}
|
|
560
|
+
if (invalid.rows) return jsonResponse(200, {
|
|
561
|
+
rows: invalid.rows,
|
|
562
|
+
defaulted: invalid.rows.map(() => []),
|
|
563
|
+
issues: Object.fromEntries(invalid.issues),
|
|
564
|
+
revision: invalid.revision
|
|
565
|
+
});
|
|
571
566
|
const { rows, contentHash } = unwrap(await JsonlReader.readSnapshot(invalid.file));
|
|
572
567
|
const read = unwrap(rows);
|
|
573
|
-
|
|
568
|
+
return jsonResponse(200, {
|
|
574
569
|
rows: read,
|
|
575
570
|
defaulted: read.map(() => []),
|
|
576
571
|
issues: Object.fromEntries(invalid.issues),
|
|
577
572
|
revision: contentHash
|
|
578
573
|
});
|
|
579
|
-
return;
|
|
580
|
-
}
|
|
581
|
-
if (!snapshot.db.getSchema(tableName)) {
|
|
582
|
-
sendJson(res, 404, { message: `Table '${tableName}' does not exist` });
|
|
583
|
-
return;
|
|
584
574
|
}
|
|
575
|
+
if (!snapshot.db.getSchema(tableName)) return jsonResponse(404, { message: `Table '${tableName}' does not exist` });
|
|
585
576
|
const rows = unwrap(await snapshot.db.findWithDefaults(tableName));
|
|
586
|
-
|
|
577
|
+
return jsonResponse(200, {
|
|
587
578
|
rows: rows.map(({ row }) => row),
|
|
588
|
-
defaulted: rows.map(({ defaulted }) => defaulted)
|
|
579
|
+
defaulted: rows.map(({ defaulted }) => defaulted),
|
|
580
|
+
inputs: rows.map(({ input }) => input)
|
|
589
581
|
});
|
|
590
|
-
return;
|
|
591
|
-
}
|
|
592
|
-
const write = isChanges ? req.method === "POST" ? resource === "check" ? { kind: "check" } : { kind: "batch" } : void 0 : writeOperation(req.method, encodedKey);
|
|
593
|
-
if (!write) {
|
|
594
|
-
sendJson(res, 405, { message: "Method not allowed" });
|
|
595
|
-
return;
|
|
596
|
-
}
|
|
597
|
-
const origin = req.headers.origin;
|
|
598
|
-
if (origin !== void 0 && !allowedHosts.has(origin.replace(/^http:\/\//, ""))) {
|
|
599
|
-
sendJson(res, 403, { message: "Writes are accepted from the studio page only" });
|
|
600
|
-
return;
|
|
601
|
-
}
|
|
602
|
-
if (write.kind !== "delete" && !isJsonMediaType(req.headers["content-type"])) {
|
|
603
|
-
sendJson(res, 415, { message: "Writes must be sent as application/json" });
|
|
604
|
-
return;
|
|
605
582
|
}
|
|
583
|
+
const write = isChanges ? request.method === "POST" ? resource === "check" ? { kind: "check" } : { kind: "batch" } : void 0 : writeOperation(request.method, encodedKey);
|
|
584
|
+
if (!write) return jsonResponse(405, { message: "Method not allowed" });
|
|
585
|
+
const origin = request.headers.get("origin");
|
|
586
|
+
if (origin !== null && origin !== url.origin) return jsonResponse(403, { message: "Writes are accepted from the studio page only" });
|
|
587
|
+
if (write.kind !== "delete" && !isJsonMediaType(request.headers.get("content-type") ?? void 0)) return jsonResponse(415, { message: "Writes must be sent as application/json" });
|
|
606
588
|
let batch;
|
|
607
|
-
if (write.kind === "batch" || write.kind === "check") batch = changeBatch(await readJson(
|
|
589
|
+
if (write.kind === "batch" || write.kind === "check") batch = changeBatch(await readJson(request));
|
|
608
590
|
else if (write.kind === "delete") batch = {
|
|
609
591
|
inserts: [],
|
|
610
592
|
updates: [],
|
|
611
593
|
deletes: [write.key]
|
|
612
594
|
};
|
|
613
595
|
else {
|
|
614
|
-
const body = writeBody(await readJson(
|
|
596
|
+
const body = writeBody(await readJson(request));
|
|
615
597
|
batch = write.kind === "insert" ? {
|
|
616
598
|
inserts: [body.row ?? {}],
|
|
617
599
|
insertDataDirs: body.dataDir ? [body.dataDir] : void 0,
|
|
@@ -832,9 +814,42 @@ async function startStudioServer(options) {
|
|
|
832
814
|
changed: true
|
|
833
815
|
};
|
|
834
816
|
});
|
|
835
|
-
|
|
836
|
-
|
|
817
|
+
if (outcome.changed || reloaded) setImmediate(notifyChanged);
|
|
818
|
+
return jsonResponse(outcome.status, outcome.body);
|
|
837
819
|
}
|
|
820
|
+
return {
|
|
821
|
+
token,
|
|
822
|
+
fetch,
|
|
823
|
+
close: async () => {
|
|
824
|
+
closing = true;
|
|
825
|
+
await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
|
|
826
|
+
clearTimeout(watchTimer);
|
|
827
|
+
for (const client of eventClients) client.close();
|
|
828
|
+
eventClients.clear();
|
|
829
|
+
await serialize(() => snapshot.db.close());
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
async function startStudioServer(options) {
|
|
834
|
+
const host = options.host ?? "127.0.0.1";
|
|
835
|
+
const studio = await createStudioHandler(options);
|
|
836
|
+
const server = createServer((req, res) => {
|
|
837
|
+
const { port } = server.address();
|
|
838
|
+
const allowedHosts = /* @__PURE__ */ new Set([
|
|
839
|
+
`${host}:${port}`,
|
|
840
|
+
`127.0.0.1:${port}`,
|
|
841
|
+
`localhost:${port}`,
|
|
842
|
+
`[::1]:${port}`
|
|
843
|
+
]);
|
|
844
|
+
let respond;
|
|
845
|
+
if (!allowedHosts.has(req.headers.host ?? "")) respond = Promise.resolve(jsonResponse(403, { message: "Requests must be addressed to the local studio server" }));
|
|
846
|
+
else try {
|
|
847
|
+
respond = studio.fetch(toRequest(req, res));
|
|
848
|
+
} catch {
|
|
849
|
+
respond = Promise.resolve(jsonResponse(400, { message: "The request cannot be served" }));
|
|
850
|
+
}
|
|
851
|
+
respond.then((response) => sendResponse(res, response)).catch(() => res.destroy());
|
|
852
|
+
});
|
|
838
853
|
try {
|
|
839
854
|
await new Promise((resolve, reject) => {
|
|
840
855
|
server.once("error", reject);
|
|
@@ -844,23 +859,46 @@ async function startStudioServer(options) {
|
|
|
844
859
|
});
|
|
845
860
|
});
|
|
846
861
|
} catch (error) {
|
|
847
|
-
await
|
|
848
|
-
await snapshot.db.close();
|
|
862
|
+
await studio.close();
|
|
849
863
|
throw error;
|
|
850
864
|
}
|
|
851
865
|
const { port } = server.address();
|
|
852
866
|
return {
|
|
853
867
|
url: `http://${host.includes(":") ? `[${host}]` : host}:${port}`,
|
|
854
|
-
token,
|
|
868
|
+
token: studio.token,
|
|
855
869
|
close: async () => {
|
|
856
|
-
await Promise.all([...watchers, dependencyWatcher].map((watcher) => watcher?.close()));
|
|
857
|
-
clearTimeout(watchTimer);
|
|
858
870
|
server.closeAllConnections();
|
|
859
871
|
await new Promise((resolve) => server.close(() => resolve()));
|
|
860
|
-
await
|
|
872
|
+
await studio.close();
|
|
861
873
|
}
|
|
862
874
|
};
|
|
863
875
|
}
|
|
876
|
+
function toRequest(req, res) {
|
|
877
|
+
const aborted = new AbortController();
|
|
878
|
+
res.on("close", () => aborted.abort());
|
|
879
|
+
const headers = new Headers();
|
|
880
|
+
for (const [name, value] of Object.entries(req.headers)) for (const each of [value ?? []].flat()) headers.append(name, each);
|
|
881
|
+
const method = req.method ?? "GET";
|
|
882
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
883
|
+
return new Request(new URL(req.url ?? "/", `http://${req.headers.host}`), {
|
|
884
|
+
method,
|
|
885
|
+
headers,
|
|
886
|
+
signal: aborted.signal,
|
|
887
|
+
...hasBody ? {
|
|
888
|
+
body: Readable.toWeb(req),
|
|
889
|
+
duplex: "half"
|
|
890
|
+
} : {}
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
function sendResponse(res, response) {
|
|
894
|
+
res.writeHead(response.status, Object.fromEntries(response.headers));
|
|
895
|
+
if (!response.body) {
|
|
896
|
+
res.end();
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
res.flushHeaders();
|
|
900
|
+
pipeline(Readable.fromWeb(response.body), res, () => {});
|
|
901
|
+
}
|
|
864
902
|
async function replaceUnchangedFile(file, next, expected) {
|
|
865
903
|
await replaceFile(file, (temporary) => writeFile(temporary, next, "utf8"), expected);
|
|
866
904
|
}
|
|
@@ -1194,39 +1232,36 @@ const CONTENT_TYPES = {
|
|
|
1194
1232
|
function shippedUiDir() {
|
|
1195
1233
|
return fileURLToPath(new URL("../ui", import.meta.url));
|
|
1196
1234
|
}
|
|
1197
|
-
|
|
1198
|
-
|
|
1235
|
+
function escapeAttribute(value) {
|
|
1236
|
+
return value.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
1237
|
+
}
|
|
1238
|
+
async function servePage(uiDir, pathname, page) {
|
|
1199
1239
|
const isPage = pathname === "/" || pathname === "/index.html";
|
|
1200
1240
|
const file = resolve(uiDir, `.${isPage ? "/index.html" : pathname}`);
|
|
1201
|
-
if (relative(uiDir, file).startsWith("..")) {
|
|
1202
|
-
sendJson(res, 404, { message: "Not found" });
|
|
1203
|
-
return;
|
|
1204
|
-
}
|
|
1241
|
+
if (relative(uiDir, file).startsWith("..")) return jsonResponse(404, { message: "Not found" });
|
|
1205
1242
|
const content = await readFile(file).catch((error) => {
|
|
1206
1243
|
if (error.code === "ENOENT" || error.code === "EISDIR") return void 0;
|
|
1207
1244
|
throw error;
|
|
1208
1245
|
});
|
|
1209
1246
|
if (!content) {
|
|
1210
|
-
if (isPage) {
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
}
|
|
1215
|
-
sendJson(res, 404, { message: "Not found" });
|
|
1216
|
-
return;
|
|
1247
|
+
if (isPage) return new Response("The studio page has not been built. Run `pnpm build` in the lines-db repository.", {
|
|
1248
|
+
status: 503,
|
|
1249
|
+
headers: { "Content-Type": "text/plain; charset=utf-8" }
|
|
1250
|
+
});
|
|
1251
|
+
return jsonResponse(404, { message: "Not found" });
|
|
1217
1252
|
}
|
|
1218
1253
|
const nonce = randomBytes(18).toString("base64");
|
|
1219
|
-
const
|
|
1220
|
-
|
|
1254
|
+
const requestHeaders = page.requestHeaders ? `<meta name="studio-request-headers" content="${escapeAttribute(JSON.stringify(page.requestHeaders))}">` : "";
|
|
1255
|
+
const body = isPage ? Buffer.from(content.toString("utf8").replace("</head>", () => `<meta name="csp-nonce" content="${nonce}"><meta name="studio-token" content="${page.token}">${requestHeaders}</head>`)) : content;
|
|
1256
|
+
return new Response(body, { headers: {
|
|
1221
1257
|
"Content-Type": CONTENT_TYPES[extname(file)] ?? "application/octet-stream",
|
|
1222
|
-
"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 '
|
|
1258
|
+
"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 '${page.frameAncestors}'`,
|
|
1223
1259
|
"Cache-Control": isPage ? "no-store" : "public, max-age=31536000, immutable",
|
|
1224
1260
|
"X-Content-Type-Options": "nosniff"
|
|
1225
|
-
});
|
|
1226
|
-
res.end(body);
|
|
1261
|
+
} });
|
|
1227
1262
|
}
|
|
1228
|
-
function bearerToken(
|
|
1229
|
-
return /^Bearer (.+)$/.exec(
|
|
1263
|
+
function bearerToken(request) {
|
|
1264
|
+
return /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1];
|
|
1230
1265
|
}
|
|
1231
1266
|
function sameToken(presented, token) {
|
|
1232
1267
|
const a = Buffer.from(presented);
|
|
@@ -1255,14 +1290,14 @@ function writeOperation(method, encodedKey) {
|
|
|
1255
1290
|
key
|
|
1256
1291
|
};
|
|
1257
1292
|
}
|
|
1258
|
-
function
|
|
1259
|
-
|
|
1260
|
-
|
|
1293
|
+
function jsonResponse(status, body) {
|
|
1294
|
+
return new Response(JSON.stringify(body), {
|
|
1295
|
+
status,
|
|
1296
|
+
headers: { "Content-Type": "application/json; charset=utf-8" }
|
|
1297
|
+
});
|
|
1261
1298
|
}
|
|
1262
|
-
async function readJson(
|
|
1263
|
-
|
|
1264
|
-
for await (const chunk of req) chunks.push(chunk);
|
|
1265
|
-
return parseJson(Buffer.concat(chunks).toString("utf8"), "The request body is not JSON");
|
|
1299
|
+
async function readJson(request) {
|
|
1300
|
+
return parseJson(await request.text(), "The request body is not JSON");
|
|
1266
1301
|
}
|
|
1267
1302
|
function isJsonObject(value) {
|
|
1268
1303
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -1318,6 +1353,6 @@ function parseJson(text, message) {
|
|
|
1318
1353
|
function errorMessage(error) {
|
|
1319
1354
|
return error instanceof Error ? error.message : String(error);
|
|
1320
1355
|
}
|
|
1321
|
-
export { startStudioServer };
|
|
1356
|
+
export { createStudioHandler, startStudioServer };
|
|
1322
1357
|
|
|
1323
1358
|
//# sourceMappingURL=index.mjs.map
|