@verbaly/studio 0.74.0 → 0.76.0

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.
@@ -0,0 +1,846 @@
1
+ import { createServer } from "node:http";
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { join, normalize, relative, resolve } from "node:path";
4
+ import { STATE_FILE, check, clearDrafts, collectOrigins, counted, doctor, effectiveDrafts, extractProject, loadCatalogs, loadDrafts, loadState, markDrafts, mergeTranslations, parseCatalog, readCatalog, readState, recordTranslations, resolveProvider, saveDrafts, shippedCatalogs, status, syncProject, targetLocales, translateCatalogs, validateMessage, validatePair, writeCatalog } from "@verbaly/compiler";
5
+ import { execFile, spawn } from "node:child_process";
6
+ import { promisify } from "node:util";
7
+ import { fileURLToPath } from "node:url";
8
+ import { randomBytes, timingSafeEqual } from "node:crypto";
9
+ //#region src/http.ts
10
+ var HttpError = class extends Error {
11
+ status;
12
+ constructor(status, message) {
13
+ super(message.startsWith("[verbaly]") ? message : `[verbaly] ${message}`);
14
+ this.status = status;
15
+ this.name = "HttpError";
16
+ }
17
+ };
18
+ const badRequest = (message) => new HttpError(400, message);
19
+ function scrub(message, root) {
20
+ return root ? message.split(root).join(".") : message;
21
+ }
22
+ //#endregion
23
+ //#region src/triage.ts
24
+ const DIGITS = /\d[\d.,]*/g;
25
+ const URLS = /https?:\/\/[^\s<)"']+/g;
26
+ const CODE = /<code>([^<]+)<\/code>/g;
27
+ function bag(text, re, normalize) {
28
+ const found = text.match(re) ?? [];
29
+ return (normalize ? found.map(normalize) : found).sort();
30
+ }
31
+ function same(a, b) {
32
+ return a.length === b.length && a.every((v, i) => v === b[i]);
33
+ }
34
+ const trimPunct = (v) => v.replace(/[.,;:!?)\]]+$/, "");
35
+ const bareDigits = (v) => trimPunct(v).replaceAll(/[.,]/g, ".");
36
+ function push(out, key, reason) {
37
+ (out[key] ??= []).push(reason);
38
+ }
39
+ function clip(text, max = 42) {
40
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
41
+ }
42
+ const quote = (text, max) => `"${clip(text, max)}"`;
43
+ function lost(from, to) {
44
+ const rest = [...to];
45
+ const out = [];
46
+ for (const item of from) {
47
+ const at = rest.indexOf(item);
48
+ if (at < 0) out.push(item);
49
+ else rest.splice(at, 1);
50
+ }
51
+ return out;
52
+ }
53
+ function movedText(kind, from, to) {
54
+ const gone = lost(from, to);
55
+ const added = lost(to, from);
56
+ if (gone.length && added.length) return `the source ${kind} ${quote(gone[0])}, this one ${kind} ${quote(added[0])}`;
57
+ if (gone.length) return `the source ${kind} ${quote(gone[0])} and this one does not`;
58
+ return `this one ${kind} ${quote(added[0])} and the source does not`;
59
+ }
60
+ function triage({ source, target, reviewed }) {
61
+ const out = Object.create(null);
62
+ const keys = Object.keys(source);
63
+ const bySource = Object.create(null);
64
+ for (const key of keys) {
65
+ const text = source[key]?.trim();
66
+ if (text) (bySource[text] ??= []).push(key);
67
+ }
68
+ for (const [text, group] of Object.entries(bySource)) {
69
+ if (group.length < 2) continue;
70
+ let split;
71
+ for (const { locale, catalog } of reviewed) {
72
+ const seen = [...new Set(group.map((k) => catalog[k]?.trim() ?? "").filter(Boolean))];
73
+ if (seen.length > 1) {
74
+ split = {
75
+ locale,
76
+ first: seen[0],
77
+ second: seen[1]
78
+ };
79
+ break;
80
+ }
81
+ }
82
+ if (split) for (const key of group) push(out, key, {
83
+ signal: "divergent",
84
+ text: `${split.locale} already says this two ways: ${quote(split.first, 32)} and ${quote(split.second, 32)}`
85
+ });
86
+ const targets = new Set(group.map((key) => target[key]?.trim() ?? "").filter(Boolean));
87
+ if (!split && targets.size > 1) for (const key of group) {
88
+ const mine = target[key]?.trim() ?? "";
89
+ const other = group.find((k) => k !== key && (target[k]?.trim() ?? "") !== mine && target[k]?.trim());
90
+ push(out, key, {
91
+ signal: "collision",
92
+ text: other ? `${other} has the same source text and says ${quote(target[other].trim())}` : `${quote(text)} came back as two different translations`
93
+ });
94
+ }
95
+ }
96
+ for (const key of keys) {
97
+ const src = source[key]?.trim() ?? "";
98
+ const trg = target[key]?.trim() ?? "";
99
+ if (!src || !trg) continue;
100
+ const voters = reviewed.filter(({ catalog }) => {
101
+ const value = catalog[key]?.trim();
102
+ return value !== void 0 && value !== "";
103
+ });
104
+ if (trg === src && voters.length > 0 && voters.every(({ catalog }) => catalog[key]?.trim() !== src)) push(out, key, {
105
+ signal: "echo",
106
+ text: `still the source text, and ${voters.map(({ locale }) => locale).join(" and ")} did translate it`
107
+ });
108
+ const srcDigits = bag(src, DIGITS, bareDigits);
109
+ const trgDigits = bag(trg, DIGITS, bareDigits);
110
+ if (srcDigits.length > 0 && !same(srcDigits, trgDigits)) push(out, key, {
111
+ signal: "digits",
112
+ text: movedText("says", srcDigits, trgDigits)
113
+ });
114
+ const srcUrls = bag(src, URLS, trimPunct);
115
+ const trgUrls = bag(trg, URLS, trimPunct);
116
+ if (!same(srcUrls, trgUrls)) push(out, key, {
117
+ signal: "url",
118
+ text: movedText("links to", srcUrls, trgUrls)
119
+ });
120
+ const srcCode = bag(src, CODE);
121
+ const trgCode = bag(trg, CODE);
122
+ if (!same(srcCode, trgCode)) push(out, key, {
123
+ signal: "code",
124
+ text: movedText("shows the code", srcCode, trgCode)
125
+ });
126
+ }
127
+ return out;
128
+ }
129
+ //#endregion
130
+ //#region src/api.ts
131
+ function readAll(cfg) {
132
+ const catalogs = {};
133
+ const problems = [];
134
+ if (!existsSync(cfg.dir)) {
135
+ const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
136
+ problems.push({
137
+ scope: dir,
138
+ message: "[verbaly] no catalogs here, run npx verbaly init or check --root"
139
+ });
140
+ }
141
+ for (const locale of cfg.locales) try {
142
+ catalogs[locale] = readCatalog(cfg, locale);
143
+ } catch (error) {
144
+ catalogs[locale] = {};
145
+ problems.push({
146
+ scope: locale,
147
+ message: error instanceof Error ? error.message : String(error)
148
+ });
149
+ }
150
+ return {
151
+ catalogs,
152
+ problems
153
+ };
154
+ }
155
+ function relativize(cfg, result) {
156
+ const rel = (file) => relative(cfg.root, file).replaceAll("\\", "/");
157
+ return {
158
+ ...result,
159
+ unknown: result.unknown.map((entry) => ({
160
+ ...entry,
161
+ files: entry.files.map(rel)
162
+ })),
163
+ extra: result.extra.map((entry) => ({
164
+ ...entry,
165
+ files: entry.files.map(rel)
166
+ })),
167
+ collisions: result.collisions.map((entry) => ({
168
+ ...entry,
169
+ sites: entry.sites.map((at) => ({
170
+ ...at,
171
+ file: rel(at.file)
172
+ }))
173
+ })),
174
+ divergent: result.divergent.map((entry) => ({
175
+ ...entry,
176
+ code: {
177
+ ...entry.code,
178
+ file: rel(entry.code.file)
179
+ }
180
+ }))
181
+ };
182
+ }
183
+ async function buildState(cfg) {
184
+ const { catalogs, problems } = readAll(cfg);
185
+ const registry = await extractProject(cfg);
186
+ const { state: sidecar, problem } = readState(cfg);
187
+ if (problem) problems.push({
188
+ scope: STATE_FILE,
189
+ message: problem
190
+ });
191
+ const live = effectiveDrafts(sidecar.drafts, catalogs);
192
+ const source = catalogs[cfg.sourceLocale] ?? {};
193
+ const targets = targetLocales(cfg);
194
+ for (const { file, message } of registry.parseErrors()) problems.push({
195
+ scope: relative(cfg.root, file).replaceAll("\\", "/"),
196
+ message
197
+ });
198
+ const perLocale = {};
199
+ for (const locale of targets) perLocale[locale] = triage({
200
+ source,
201
+ target: catalogs[locale] ?? {},
202
+ reviewed: targets.filter((other) => other !== locale && !(live[other] ?? []).length).map((other) => ({
203
+ locale: other,
204
+ catalog: catalogs[other] ?? {}
205
+ }))
206
+ });
207
+ return {
208
+ root: cfg.root,
209
+ dir: cfg.dir,
210
+ sourceLocale: cfg.sourceLocale,
211
+ locales: cfg.locales,
212
+ scanning: cfg.include.length > 0,
213
+ catalogs,
214
+ origins: await collectOrigins(cfg, registry),
215
+ status: status(cfg, catalogs, registry, live, sidecar.fingerprints),
216
+ check: relativize(cfg, check(cfg, catalogs, registry, sidecar.fingerprints)),
217
+ drafts: live,
218
+ triage: perLocale,
219
+ problems
220
+ };
221
+ }
222
+ function health(cfg) {
223
+ return doctor(cfg);
224
+ }
225
+ async function writeMessage(cfg, locale, key, text) {
226
+ if (locale === cfg.sourceLocale) throw badRequest("the source text lives in your code, Studio never edits it");
227
+ if (!cfg.locales.includes(locale)) throw badRequest(`${locale} is not one of this project's locales`);
228
+ const before = loadState(cfg);
229
+ const catalogs = { [cfg.sourceLocale]: readCatalog(cfg, cfg.sourceLocale) };
230
+ const registry = await extractProject(cfg);
231
+ const source = shippedCatalogs(cfg, catalogs, registry, { newKeys: false })[cfg.sourceLocale];
232
+ if (!Object.hasOwn(source, key)) throw badRequest(`"${key}" is not in the source catalog, so Studio will not create it`);
233
+ const value = text.trim() ? text : "";
234
+ const errors = (value ? [...validateMessage(value, locale), ...validatePair(source[key], value)] : []).filter((issue) => issue.severity === "error");
235
+ if (errors.length) throw badRequest(`${errors.map((issue) => issue.message).join("; ")}`);
236
+ const catalog = {
237
+ ...readCatalog(cfg, locale),
238
+ [key]: value
239
+ };
240
+ writeCatalog(cfg, locale, catalog);
241
+ const clearedDraft = (before.drafts[locale] ?? []).includes(key);
242
+ recordTranslations(cfg, source, [{
243
+ locale,
244
+ entries: [{
245
+ key,
246
+ text: value
247
+ }],
248
+ draft: false
249
+ }]);
250
+ return {
251
+ locale,
252
+ key,
253
+ clearedDraft
254
+ };
255
+ }
256
+ function approve(cfg, locale, keys) {
257
+ if (!cfg.locales.includes(locale)) throw badRequest(`${locale} is not one of this project's locales`);
258
+ const drafts = loadDrafts(cfg);
259
+ const had = drafts[locale] ?? [];
260
+ const cleared = keys ? had.filter((key) => keys.includes(key)) : [...had];
261
+ clearDrafts(drafts, locale, keys);
262
+ saveDrafts(cfg, drafts);
263
+ return {
264
+ locale,
265
+ approved: cleared.length,
266
+ keys: cleared
267
+ };
268
+ }
269
+ function unapprove(cfg, locale, keys) {
270
+ if (!cfg.locales.includes(locale)) throw badRequest(`${locale} is not one of this project's locales`);
271
+ const drafts = loadDrafts(cfg);
272
+ markDrafts(drafts, locale, keys);
273
+ saveDrafts(cfg, drafts);
274
+ return {
275
+ locale,
276
+ approved: keys.length,
277
+ keys
278
+ };
279
+ }
280
+ //#endregion
281
+ //#region src/jobs.ts
282
+ let current = null;
283
+ let counter = 0;
284
+ function running() {
285
+ return current?.state === "running" ? current : null;
286
+ }
287
+ function read(id) {
288
+ if (!current || current.id !== id) throw new HttpError(404, `no job called "${id}"`);
289
+ return current;
290
+ }
291
+ function start(kind, total) {
292
+ if (running()) throw badRequest("a job is already running, wait for it or read its progress");
293
+ counter += 1;
294
+ current = {
295
+ id: `${kind}-${counter}`,
296
+ kind,
297
+ state: "running",
298
+ total,
299
+ done: 0
300
+ };
301
+ return current;
302
+ }
303
+ function advance(id, keys, locale, error) {
304
+ if (current?.id !== id) return;
305
+ current.done = Math.min(current.done + keys, current.total);
306
+ current.locale = locale;
307
+ if (error) current.message = error;
308
+ }
309
+ function finish(id, state, patch = {}) {
310
+ if (current?.id === id) Object.assign(current, patch, { state });
311
+ }
312
+ //#endregion
313
+ //#region src/actions.ts
314
+ async function runExtract(cfg) {
315
+ if (!cfg.include.length) throw badRequest("source scanning is off (include: []), so there is nothing to extract");
316
+ const result = await syncProject(cfg);
317
+ return {
318
+ added: result.added,
319
+ found: result.added[cfg.sourceLocale]?.length ?? 0,
320
+ replaced: result.replaced.length,
321
+ messages: result.messages,
322
+ ...result.stateProblem && { stateProblem: result.stateProblem }
323
+ };
324
+ }
325
+ async function planTranslate(cfg, locales) {
326
+ const provider = await resolveProvider(cfg);
327
+ const catalogs = loadCatalogs(cfg);
328
+ const result = await translateCatalogs(cfg, catalogs, provider, {
329
+ locales,
330
+ dryRun: true
331
+ });
332
+ const total = Object.values(result.pending).reduce((n, keys) => n + keys.length, 0);
333
+ return {
334
+ pending: result.pending,
335
+ total
336
+ };
337
+ }
338
+ async function startTranslate(cfg, locales) {
339
+ loadState(cfg);
340
+ const provider = await resolveProvider(cfg);
341
+ const job = start("translate", (await planTranslate(cfg, locales)).total);
342
+ const id = job.id;
343
+ (async () => {
344
+ try {
345
+ const registry = await extractProject(cfg);
346
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
347
+ const result = await translateCatalogs(cfg, catalogs, provider, {
348
+ locales,
349
+ batchSize: cfg.translate.batchSize,
350
+ concurrency: cfg.translate.concurrency,
351
+ retries: cfg.translate.retries,
352
+ origins: await collectOrigins(cfg, registry),
353
+ onProgress: (p) => advance(id, p.keys, p.locale, p.error)
354
+ });
355
+ const writes = [];
356
+ let written = 0;
357
+ let kept = 0;
358
+ for (const [locale, keys] of Object.entries(result.translated)) {
359
+ const catalog = catalogs[locale] ?? {};
360
+ const landed = mergeTranslations(cfg, locale, catalog, keys);
361
+ writes.push({
362
+ locale,
363
+ draft: true,
364
+ entries: landed.map((key) => ({
365
+ key,
366
+ text: catalog[key]
367
+ }))
368
+ });
369
+ written += landed.length;
370
+ kept += keys.length - landed.length;
371
+ }
372
+ recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
373
+ const failed = result.failed[0];
374
+ finish(id, failed ? "failed" : "done", {
375
+ result,
376
+ written,
377
+ kept,
378
+ message: failed ? `${counted(written, "message")} translated, but ${counted(result.failed.length, "batch", "batches")} did not answer (${failed.error}): run it again for the rest` : void 0
379
+ });
380
+ } catch (error) {
381
+ finish(id, "failed", { message: error instanceof Error ? error.message : String(error) });
382
+ }
383
+ })();
384
+ return job;
385
+ }
386
+ //#endregion
387
+ //#region src/history.ts
388
+ const run = promisify(execFile);
389
+ const FIELD = "";
390
+ const FORMAT = `--format=%H${FIELD}%an${FIELD}%aI${FIELD}%s`;
391
+ function parseFullLog(stdout) {
392
+ const commits = [];
393
+ for (const line of stdout.split("\n")) {
394
+ const [sha, author, date, ...rest] = line.split(FIELD);
395
+ if (!sha || !author || !date || !rest.length) continue;
396
+ commits.push({
397
+ sha,
398
+ author,
399
+ date,
400
+ subject: rest.join(FIELD)
401
+ });
402
+ }
403
+ return commits;
404
+ }
405
+ function parseLog(stdout) {
406
+ return parseFullLog(stdout).map((commit) => ({
407
+ ...commit,
408
+ sha: commit.sha.slice(0, 7)
409
+ }));
410
+ }
411
+ async function catalogHistory(cfg, limit = 5) {
412
+ const dir = relative(cfg.root, cfg.dir).replaceAll("\\", "/") || ".";
413
+ try {
414
+ const { stdout } = await run("git", [
415
+ "log",
416
+ `-n${limit}`,
417
+ FORMAT,
418
+ "--",
419
+ dir
420
+ ], {
421
+ cwd: cfg.root,
422
+ timeout: 3e3,
423
+ windowsHide: true
424
+ });
425
+ return parseLog(stdout);
426
+ } catch {
427
+ return [];
428
+ }
429
+ }
430
+ function attribute(revisions, owners = /* @__PURE__ */ new Map()) {
431
+ for (const { commit, now, before } of revisions) {
432
+ if (!now || !before) continue;
433
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(now), ...Object.keys(before)])) if (!owners.has(key) && now[key] !== before[key]) owners.set(key, commit);
434
+ }
435
+ return owners;
436
+ }
437
+ function mergeOwners(maps) {
438
+ const merged = /* @__PURE__ */ new Map();
439
+ for (const map of maps) for (const [key, commit] of map) {
440
+ const held = merged.get(key);
441
+ if (!held || Date.parse(commit.date) > Date.parse(held.date)) merged.set(key, commit);
442
+ }
443
+ return merged;
444
+ }
445
+ const BLOB = /^[0-9a-f]{40} \w+ (\d+)$/;
446
+ function readBlobs(root, requests, take) {
447
+ return new Promise((resolve) => {
448
+ const child = spawn("git", ["cat-file", "--batch"], {
449
+ cwd: root,
450
+ windowsHide: true
451
+ });
452
+ const stop = setTimeout(() => {
453
+ ok = false;
454
+ child.kill();
455
+ }, 2e4);
456
+ let pending = Buffer.alloc(0);
457
+ let index = 0;
458
+ let ok = true;
459
+ const fail = () => {
460
+ ok = false;
461
+ };
462
+ child.on("error", fail);
463
+ child.stdin.on("error", fail);
464
+ child.stdout.on("data", (chunk) => {
465
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
466
+ for (;;) {
467
+ const end = pending.indexOf(10);
468
+ if (end < 0) break;
469
+ const header = pending.toString("utf8", 0, end);
470
+ const blob = BLOB.exec(header);
471
+ if (!blob) {
472
+ take(index++, null, "");
473
+ pending = pending.subarray(end + 1);
474
+ continue;
475
+ }
476
+ const size = Number(blob[1]);
477
+ if (pending.length < end + size + 2) break;
478
+ take(index++, pending.toString("utf8", end + 1, end + 1 + size), header.slice(0, 40));
479
+ pending = pending.subarray(end + size + 2);
480
+ }
481
+ });
482
+ child.on("close", () => {
483
+ clearTimeout(stop);
484
+ resolve(ok);
485
+ });
486
+ child.stdin.end(requests.join("\n") + "\n");
487
+ });
488
+ }
489
+ const WINDOW = 200;
490
+ async function walkFile(root, file, limit) {
491
+ const { stdout } = await run("git", [
492
+ "log",
493
+ `-n${limit}`,
494
+ FORMAT,
495
+ "--",
496
+ file
497
+ ], {
498
+ cwd: root,
499
+ timeout: 5e3,
500
+ windowsHide: true,
501
+ maxBuffer: 8e6
502
+ });
503
+ const commits = parseFullLog(stdout);
504
+ if (!commits.length) return {
505
+ owners: /* @__PURE__ */ new Map(),
506
+ head: []
507
+ };
508
+ const owners = /* @__PURE__ */ new Map();
509
+ let head = [];
510
+ let waiting;
511
+ let last = null;
512
+ const parse = (body, blob) => {
513
+ if (body === null) return {};
514
+ if (last && last.blob === blob) return last.flat;
515
+ const flat = parseCatalog(body);
516
+ last = {
517
+ blob,
518
+ flat
519
+ };
520
+ return flat;
521
+ };
522
+ if (!await readBlobs(root, commits.flatMap((commit) => [`${commit.sha}:${file}`, `${commit.sha}^:${file}`]), (index, body, blob) => {
523
+ const flat = parse(body, blob);
524
+ if (index % 2 === 0) {
525
+ waiting = flat;
526
+ if (index === 0 && flat) head = Object.keys(flat);
527
+ return;
528
+ }
529
+ const commit = commits[(index - 1) / 2];
530
+ if (commit) attribute([{
531
+ commit,
532
+ now: waiting,
533
+ before: flat
534
+ }], owners);
535
+ waiting = void 0;
536
+ })) throw new Error("[verbaly] git could not read every revision of this catalog");
537
+ return {
538
+ owners,
539
+ head
540
+ };
541
+ }
542
+ async function catalogKeyHistory(cfg, limit = WINDOW) {
543
+ const maps = [];
544
+ const committed = /* @__PURE__ */ new Set();
545
+ let ok = false;
546
+ for (const locale of cfg.locales) {
547
+ const file = relative(cfg.root, join(cfg.dir, `${locale}.json`)).replaceAll("\\", "/");
548
+ try {
549
+ const walked = await walkFile(cfg.root, file, limit);
550
+ maps.push(walked.owners);
551
+ for (const key of walked.head) committed.add(key);
552
+ ok = true;
553
+ } catch {}
554
+ }
555
+ return {
556
+ owners: mergeOwners(maps),
557
+ committed,
558
+ ok
559
+ };
560
+ }
561
+ const walked = /* @__PURE__ */ new Map();
562
+ async function headSha(root) {
563
+ try {
564
+ const { stdout } = await run("git", ["rev-parse", "HEAD"], {
565
+ cwd: root,
566
+ timeout: 3e3,
567
+ windowsHide: true
568
+ });
569
+ return stdout.trim();
570
+ } catch {
571
+ return "";
572
+ }
573
+ }
574
+ async function keyHistory(cfg) {
575
+ const head = await headSha(cfg.root);
576
+ const held = walked.get(cfg.root);
577
+ if (held && held.head === head) return held.history;
578
+ const history = await catalogKeyHistory(cfg);
579
+ walked.set(cfg.root, {
580
+ head,
581
+ history
582
+ });
583
+ return history;
584
+ }
585
+ async function keyCommit(cfg, key) {
586
+ const history = await keyHistory(cfg);
587
+ if (!history.ok) return {
588
+ key,
589
+ commit: null,
590
+ reason: "nogit"
591
+ };
592
+ const commit = history.owners.get(key);
593
+ if (commit) return {
594
+ key,
595
+ commit: {
596
+ ...commit,
597
+ sha: commit.sha.slice(0, 7)
598
+ }
599
+ };
600
+ return {
601
+ key,
602
+ commit: null,
603
+ reason: history.committed.has(key) ? "older" : "uncommitted"
604
+ };
605
+ }
606
+ //#endregion
607
+ //#region src/assets.ts
608
+ const UI = resolve(fileURLToPath(new URL(".", import.meta.url)), "ui");
609
+ const TYPES = {
610
+ ".html": "text/html; charset=utf-8",
611
+ ".js": "text/javascript; charset=utf-8",
612
+ ".css": "text/css; charset=utf-8",
613
+ ".svg": "image/svg+xml",
614
+ ".woff2": "font/woff2",
615
+ ".json": "application/json; charset=utf-8",
616
+ ".ico": "image/x-icon"
617
+ };
618
+ const uiBuilt = () => existsSync(join(UI, "index.html"));
619
+ function readAsset(pathname) {
620
+ const target = resolve(join(UI, normalize(pathname === "/" ? "/index.html" : pathname)));
621
+ if (target !== UI && !target.startsWith(UI + (process.platform === "win32" ? "\\" : "/"))) return;
622
+ if (!existsSync(target) || !statSync(target).isFile()) return void 0;
623
+ const dot = target.lastIndexOf(".");
624
+ return {
625
+ body: readFileSync(target),
626
+ type: TYPES[target.slice(dot).toLowerCase()] ?? "application/octet-stream"
627
+ };
628
+ }
629
+ //#endregion
630
+ //#region src/guard.ts
631
+ function newToken() {
632
+ return randomBytes(9).toString("base64url");
633
+ }
634
+ function hostAllowed(host, port) {
635
+ const names = port === 80 ? ["127.0.0.1", "localhost"] : [];
636
+ return [
637
+ `127.0.0.1:${port}`,
638
+ `localhost:${port}`,
639
+ ...names
640
+ ].includes(host ?? "");
641
+ }
642
+ function originAllowed(origin, port) {
643
+ if (origin === void 0) return true;
644
+ return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`;
645
+ }
646
+ function tokenMatches(given, expected) {
647
+ if (given === null) return false;
648
+ const a = Buffer.from(given);
649
+ const b = Buffer.from(expected);
650
+ return a.length === b.length && timingSafeEqual(a, b);
651
+ }
652
+ const PASS = {
653
+ ok: true,
654
+ status: 200,
655
+ reason: ""
656
+ };
657
+ function guardRequest(headers, url, { port, token }) {
658
+ if (!hostAllowed(headers.host, port)) return {
659
+ ok: false,
660
+ status: 403,
661
+ reason: "[verbaly] unexpected Host header"
662
+ };
663
+ if (!originAllowed(headers.origin, port)) return {
664
+ ok: false,
665
+ status: 403,
666
+ reason: "[verbaly] cross-origin request"
667
+ };
668
+ if (!tokenMatches(url.searchParams.get("t"), token)) return {
669
+ ok: false,
670
+ status: 401,
671
+ reason: "[verbaly] missing or wrong token, open the printed url"
672
+ };
673
+ return PASS;
674
+ }
675
+ //#endregion
676
+ //#region src/server.ts
677
+ const DEFAULT_PORT = 4747;
678
+ const MAX_BODY = 1e6;
679
+ function send(res, status, body) {
680
+ res.writeHead(status, {
681
+ "content-type": "application/json; charset=utf-8",
682
+ "cache-control": "no-store"
683
+ });
684
+ res.end(JSON.stringify(body));
685
+ }
686
+ async function readJson(req) {
687
+ const chunks = [];
688
+ let size = 0;
689
+ for await (const chunk of req) {
690
+ size += chunk.length;
691
+ if (size > MAX_BODY) throw new HttpError(413, "request body too large");
692
+ chunks.push(chunk);
693
+ }
694
+ if (!chunks.length) return {};
695
+ let parsed;
696
+ try {
697
+ parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
698
+ } catch {
699
+ throw badRequest("body is not valid JSON");
700
+ }
701
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw badRequest("body must be a JSON object");
702
+ return parsed;
703
+ }
704
+ function segment(raw, what) {
705
+ let value;
706
+ try {
707
+ value = decodeURIComponent(raw ?? "");
708
+ } catch {
709
+ throw badRequest(`the ${what} in the url is not valid percent-encoding`);
710
+ }
711
+ if (!value) throw badRequest(`the url is missing a ${what}`);
712
+ return value;
713
+ }
714
+ function createStudioApp(cfg, port, token) {
715
+ return async function handle(req, res) {
716
+ try {
717
+ let url;
718
+ try {
719
+ url = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
720
+ } catch {
721
+ throw badRequest("the request target is not a valid url");
722
+ }
723
+ const api = url.pathname.startsWith("/api/");
724
+ const verdict = guardRequest({
725
+ host: req.headers.host,
726
+ origin: req.headers.origin
727
+ }, url, {
728
+ port,
729
+ token
730
+ });
731
+ if (!verdict.ok && (api || verdict.status !== 401)) {
732
+ send(res, verdict.status, { error: verdict.reason });
733
+ return;
734
+ }
735
+ if (!api && req.method === "GET") {
736
+ const asset = readAsset(url.pathname);
737
+ if (asset) {
738
+ res.writeHead(200, {
739
+ "content-type": asset.type,
740
+ "cache-control": "no-store"
741
+ });
742
+ res.end(asset.body);
743
+ return;
744
+ }
745
+ if (url.pathname === "/" && !uiBuilt()) throw new HttpError(500, "the panel is not in this install, so only /api/* answers here");
746
+ }
747
+ if (req.method === "GET" && url.pathname === "/api/state") {
748
+ send(res, 200, await buildState(cfg));
749
+ return;
750
+ }
751
+ if (req.method === "GET" && url.pathname === "/api/history") {
752
+ send(res, 200, { commits: await catalogHistory(cfg) });
753
+ return;
754
+ }
755
+ if (req.method === "GET" && url.pathname.startsWith("/api/commit/")) {
756
+ send(res, 200, await keyCommit(cfg, segment(url.pathname.slice(12), "key")));
757
+ return;
758
+ }
759
+ if (req.method === "GET" && url.pathname === "/api/health") {
760
+ send(res, 200, await health(cfg));
761
+ return;
762
+ }
763
+ if (req.method === "PUT" && url.pathname.startsWith("/api/message/")) {
764
+ const rest = url.pathname.slice(13).split("/");
765
+ const locale = segment(rest[0], "locale");
766
+ const key = segment(rest.slice(1).join("/"), "key");
767
+ const body = await readJson(req);
768
+ if (typeof body.text !== "string") throw badRequest("body needs a \"text\" string");
769
+ send(res, 200, await writeMessage(cfg, locale, key, body.text));
770
+ return;
771
+ }
772
+ if (req.method === "POST" && url.pathname === "/api/approve") {
773
+ const body = await readJson(req);
774
+ if (typeof body.locale !== "string") throw badRequest("body needs a \"locale\" string");
775
+ const keys = Array.isArray(body.keys) ? body.keys.filter((k) => typeof k === "string") : void 0;
776
+ if (body.undo === true) {
777
+ if (!keys?.length) throw badRequest("undoing needs the \"keys\" it should put back");
778
+ send(res, 200, unapprove(cfg, body.locale, keys));
779
+ return;
780
+ }
781
+ send(res, 200, approve(cfg, body.locale, keys));
782
+ return;
783
+ }
784
+ if (req.method === "POST" && url.pathname === "/api/extract") {
785
+ send(res, 200, await runExtract(cfg));
786
+ return;
787
+ }
788
+ if (req.method === "GET" && url.pathname === "/api/translate") {
789
+ const locales = url.searchParams.getAll("locale");
790
+ send(res, 200, await planTranslate(cfg, locales.length ? locales : void 0));
791
+ return;
792
+ }
793
+ if (req.method === "POST" && url.pathname === "/api/translate") {
794
+ const body = await readJson(req);
795
+ const locales = Array.isArray(body.locales) ? body.locales.filter((l) => typeof l === "string") : void 0;
796
+ send(res, 200, await startTranslate(cfg, locales?.length ? locales : void 0));
797
+ return;
798
+ }
799
+ if (req.method === "GET" && url.pathname === "/api/job") {
800
+ send(res, 200, running());
801
+ return;
802
+ }
803
+ if (req.method === "GET" && url.pathname.startsWith("/api/job/")) {
804
+ send(res, 200, read(segment(url.pathname.slice(9), "job id")));
805
+ return;
806
+ }
807
+ send(res, 404, { error: `[verbaly] no route for ${req.method} ${url.pathname}` });
808
+ } catch (error) {
809
+ send(res, error instanceof HttpError ? error.status : 500, { error: scrub(error instanceof Error ? error.message : String(error), cfg.root) });
810
+ }
811
+ };
812
+ }
813
+ function listen(server, port, attemptsLeft) {
814
+ return new Promise((resolve, reject) => {
815
+ const onError = (error) => {
816
+ if (error.code === "EADDRINUSE" && attemptsLeft > 0) {
817
+ server.removeListener("error", onError);
818
+ resolve(listen(server, port + 1, attemptsLeft - 1));
819
+ return;
820
+ }
821
+ reject(error);
822
+ };
823
+ server.once("error", onError);
824
+ server.listen(port, "127.0.0.1", () => {
825
+ server.removeListener("error", onError);
826
+ const bound = server.address();
827
+ resolve(typeof bound === "object" && bound !== null ? bound.port : port);
828
+ });
829
+ });
830
+ }
831
+ async function startStudio(cfg, options = {}) {
832
+ const token = options.token ?? newToken();
833
+ const server = createServer();
834
+ let port = options.port ?? DEFAULT_PORT;
835
+ server.on("request", (req, res) => void createStudioApp(cfg, port, token)(req, res));
836
+ port = await listen(server, port, 20);
837
+ return {
838
+ server,
839
+ port,
840
+ token,
841
+ url: `http://127.0.0.1:${port}/?t=${token}`,
842
+ close: () => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
843
+ };
844
+ }
845
+ //#endregion
846
+ export { startStudio as n, buildState as r, createStudioApp as t };