Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
3961 lines (3765 loc) · 190 KB
/
Copy pathcli.js
File metadata and controls
3961 lines (3765 loc) · 190 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// tinyjs CLI: scaffold, run, and package tinyjs projects.
//
// tinyjs new <dir> scaffold a new app
// tinyjs dev run the app in the current directory
// tinyjs build build dist/<name> + dist/<Name>.app
// tinyjs update self-update from the latest GitHub release
// tinyjs uninstall remove ~/.tinyjs and the PATH symlink
//
// Runs on txiki.js itself (via the `tinyjs` wrapper script).
import { pinnedKeys, signManifest, verifyManifest } from './runtime/update-signing.js';
const enc = new TextEncoder();
const dec = new TextDecoder();
// txiki has no tjs.platform; OS=Windows_NT is always set by Windows itself,
// and navigator.platform reads "Linux …" from uname on Linux.
const IS_WIN = tjs.env.OS === 'Windows_NT';
const IS_LINUX = !IS_WIN && /linux/i.test(globalThis.navigator?.platform ?? '');
// URL.pathname renders C:\Users\me as /C:/Users/me (percent-encoded) — decode
// and drop the leading slash so the result is a usable Windows path.
function pathFromUrl(u) {
let p = decodeURIComponent(u.pathname);
if (/^\/[A-Za-z]:\//.test(p)) p = p.slice(1);
return p;
}
const TOOL_DIR = pathFromUrl(new URL('.', import.meta.url));
// Invoked as: tjs run cli.js <cmd> [args...]
const [cmd, ...args] = tjs.args.slice(3);
function fail(msg) {
console.log('tinyjs: ' + msg);
tjs.exit(1);
}
async function exists(p) {
try {
await tjs.stat(p);
return true;
} catch {
return false;
}
}
async function copyTree(src, dest) {
await tjs.makeDir(dest, { recursive: true }).catch(() => {});
const iter = await tjs.readDir(src);
for await (const e of iter) {
const s = src + '/' + e.name;
const d = dest + '/' + e.name;
if (e.isDirectory) await copyTree(s, d);
else await tjs.writeFile(d, await tjs.readFile(s));
}
}
// tjs.watch on a folder: cb(rel) per change, rel relative to dir with '/'
// separators, skipped when skip(rel). macOS (FSEvents) and Windows watch the
// whole tree from one call, but Linux's inotify only sees a folder's direct
// entries, so with `perDir` every subfolder gets its own watch, including
// folders made later. Self-contained: the dev entry inlines its source for
// the frontend reload watcher.
async function watchTree(dir, cb, skip = () => false, perDir = false) {
const watchers = new Map();
const add = async (rel) => {
if (watchers.has(rel)) return;
const path = rel ? dir + '/' + rel : dir;
try {
watchers.set(rel, tjs.watch(path, (file) => {
if (!file) return;
const r = (rel ? rel + '/' : '') + String(file).replace(/\\/g, '/');
if (skip(r)) return;
if (perDir) sync(r);
cb(r);
}));
} catch { return; }
if (!perDir) return;
try {
for await (const e of await tjs.readDir(path)) {
const r = (rel ? rel + '/' : '') + e.name;
if (e.isDirectory && !skip(r)) await add(r);
}
} catch {}
};
// A name that changed may be a folder made (watch it and what's inside) or
// removed (drop its watches, so one made again later is watched afresh).
const sync = async (r) => {
let isDir = false;
try { isDir = (await tjs.stat(dir + '/' + r)).isDirectory; } catch {}
if (isDir) return add(r);
for (const [k, w] of watchers) {
if (k === r || k.startsWith(r + '/')) { try { w.close(); } catch {} watchers.delete(k); }
}
};
await add('');
}
// Data the app's own code reads at runtime lives in resources/ and reaches
// it as app.paths().resources: the whole folder, or only the files and
// directories inside it that tinyjs.json "resources" lists (per OS through
// the platform blocks). Files the OS reads (icon, Credits, help book) live
// in assets/ instead. Reject symlinks at every parent and below selected
// directories, even when they point back into the project.
const RESOURCES_DIR = 'resources';
async function validateResources(value) {
if (value !== undefined && !Array.isArray(value)) fail('tinyjs.json "resources" must be an array of paths inside resources/ (got ' + JSON.stringify(value) + ')');
let dirSt = null;
try { dirSt = await tjs.lstat(RESOURCES_DIR); } catch {}
if (dirSt?.isSymbolicLink) fail('resources/: symlinks are not supported');
if (dirSt && !dirSt.isDirectory) fail('resources/ must be a directory');
if (value === undefined) {
// No list: everything in the folder, if there is one.
if (!dirSt) return [];
value = [];
for await (const e of await tjs.readDir(RESOURCES_DIR)) value.push(e.name);
value.sort();
} else if (value.length && !dirSt) {
fail('tinyjs.json "resources" lists paths inside resources/, but the project has no resources/ folder');
}
const paths = [];
for (const raw of value) {
const bad = (why) => fail('tinyjs.json resource ' + JSON.stringify(raw) + ': ' + why);
if (typeof raw !== 'string' || !raw || raw.includes('\0')) bad('expected a non-empty path inside resources/');
const p = raw.replace(/\\/g, '/');
if (p.startsWith('/') || p.includes(':')) bad('absolute, drive and UNC paths are not allowed');
const parts = p.split('/').filter((s) => s && s !== '.');
if (parts.includes('..')) bad('parent traversal is not allowed');
if (IS_WIN && parts.some((s) => /[. ]$/.test(s))) bad('Windows path components cannot end in a dot or space');
if (!parts.length) bad('that is resources/ itself — leave "resources" out to ship the whole folder');
const rel = parts.join('/');
if (!paths.includes(rel)) paths.push(rel);
}
// A selected directory already includes its children. Keep the first
// occurrence of each root, independent of the order of overlapping entries.
const roots = paths.filter((p) => !paths.some((q) => p !== q && p.startsWith(q + '/')));
const root = paths.length ? await tjs.realPath(RESOURCES_DIR) : null;
async function check(rel, selected, recurse) {
const bad = (why) => fail('tinyjs.json resource ' + JSON.stringify(selected) + ' (resources/' + rel + '): ' + why);
let st;
try { st = await tjs.lstat(root + '/' + rel); }
catch { bad('not found or unreadable'); }
if (st.isSymbolicLink) bad('symlinks are not supported');
if (!st.isDirectory && !st.isFile) bad('expected a regular file or directory');
if (recurse && st.isDirectory) {
try {
const iter = await tjs.readDir(root + '/' + rel);
for await (const e of iter) await check(rel + '/' + e.name, selected, true);
} catch (e) { bad('could not read directory: ' + String(e)); }
}
}
// Validate ALL entries before dropping overlaps: e.g. file.txt/child must
// still fail even if file.txt was also explicitly selected.
for (const p of paths) {
const parts = p.split('/');
for (let i = 1; i < parts.length; i++) await check(parts.slice(0, i).join('/'), p, false);
await check(p, p, true);
}
return roots;
}
async function stageResources(paths) {
// Recheck after any frontend build hook, before copying its output.
for (const p of await validateResources(paths)) {
const src = RESOURCES_DIR + '/' + p;
const dest = '.build/resources/' + p;
try {
if ((await tjs.lstat(src)).isDirectory) await copyTree(src, dest);
else {
await tjs.makeDir(dest.replace(/\/[^/]*$/, ''), { recursive: true });
await copyFile(src, dest);
}
} catch (e) { fail('tinyjs.json resource ' + JSON.stringify(p) + ': could not copy: ' + String(e)); }
}
}
// Sidecar programs the app spawns ship from executables/, the same way
// resources/ does: with no list, everything in it, overridden by name from
// executables/<os>/ (macos, windows, linux) and then executables/<os>-<arch>/
// (arm64 / x86_64) for that build. "executables": [...] lists paths inside
// the folder instead (per OS through the platform blocks). A .app puts them
// in Contents/Helpers/, where codesign treats them as nested code and signs
// each one; Windows/Linux put them in executables/ beside the exe. Either
// way they land flat, so app.paths().executables + '/<name>' is the program.
// Only this OS's native binaries (and the libraries they load) ship:
// anything else in a .app's code location breaks its signature. A no-list
// build skips other files at the root with a note (that's where the other
// OSes' binaries live); in an OS folder or a list they fail the build.
const EXECUTABLES_DIR = 'executables';
const EXEC_OS = IS_WIN ? 'windows' : IS_LINUX ? 'linux' : 'macos';
const EXEC_KIND = IS_WIN ? 'Windows (PE: .exe/.dll)' : IS_LINUX ? 'Linux (ELF or #! script)' : 'macOS (Mach-O)';
const EXEC_OS_DIR = /^(macos|windows|linux)(-(arm64|x86_64))?$/;
const JUNK_FILES = ['.DS_Store', 'Thumbs.db', 'desktop.ini'];
let hostArchP = null;
// On Windows the app is built from this very tjs.exe, so its CPU is the
// build's: read the PE header rather than the environment (an x64 tjs.exe
// emulated on ARM64 is building an x64 app).
const hostArch = () => (hostArchP ??= IS_WIN
? peArch(tjs.exePath).catch(() => null)
.then((a) => a ?? (/arm64/i.test(tjs.env.PROCESSOR_ARCHITECTURE ?? '') ? 'arm64' : 'x86_64'))
: capture(['uname', '-m']).then((m) => ({ aarch64: 'arm64', arm64: 'arm64' })[m.trim()] ?? 'x86_64'));
// A Windows PE file's CPU, from the machine field of its COFF header.
async function peArch(path) {
const fh = await tjs.open(path, 'r');
const b = new Uint8Array(4096);
try { await fh.read(b, 0); } finally { await fh.close(); }
const pe = (b[0x3c] | (b[0x3d] << 8) | (b[0x3e] << 16) | (b[0x3f] << 24)) >>> 0;
const m = pe + 6 <= b.length ? b[pe + 4] | (b[pe + 5] << 8) : 0;
return m === 0xaa64 ? 'arm64' : m === 0x8664 ? 'x86_64' : null;
}
function isNativeBinary(b) {
const u32 = (o) => ((b[o] << 24) | (b[o + 1] << 16) | (b[o + 2] << 8) | b[o + 3]) >>> 0;
if (IS_WIN) return b[0] === 0x4d && b[1] === 0x5a; // MZ
if (IS_LINUX) return (b[0] === 0x7f && b[1] === 0x45 && b[2] === 0x4c && b[3] === 0x46) || (b[0] === 0x23 && b[1] === 0x21);
if (b.length < 8) return false;
const m = u32(0);
// Thin Mach-O (either endianness), or a fat header — which Java class files
// share; their "arch count" is the class version (45+), so cap it.
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(m)) return true;
return (m === 0xcafebabe || m === 0xcafebabf) && u32(4) > 0 && u32(4) < 45;
}
async function readsAsNative(path) {
const fh = await tjs.open(path, 'r');
const head = new Uint8Array(8);
let n = 0;
try { n = (await fh.read(head, 0)) ?? 0; } finally { await fh.close(); }
return isNativeBinary(head.subarray(0, n));
}
const notNative = () => `not a ${EXEC_KIND} binary` + (IS_WIN || IS_LINUX ? '' :
' — a script in a .app can\'t carry a code signature; ship it in resources/ and run it with its interpreter');
// Returns { files: [{ name, src }] } for this build (name = where it lands,
// src = its path in the project), or null when nothing ships. target: a
// macOS build's MAC_TARGET (null = this Mac).
async function validateExecutables(list, target = null) {
if (list !== undefined && !Array.isArray(list)) fail('tinyjs.json "executables" must be an array of paths inside executables/ (got ' + JSON.stringify(list) + ')');
let st = null;
try { st = await tjs.lstat(EXECUTABLES_DIR); } catch {}
if (st?.isSymbolicLink) fail('executables/: symlinks are not supported');
if (st && !st.isDirectory) fail('executables/ must be a directory');
if (!st) {
if (list?.length) fail('tinyjs.json "executables" lists paths inside executables/, but the project has no executables/ folder');
return null;
}
const picked = new Map(); // name -> src
const add = async (src, name, strict, where) => {
const fst = await tjs.lstat(src);
if (fst.isSymbolicLink) fail(`${where}: symlinks are not supported`);
if (!fst.isFile) {
if (strict) fail(`${where}: expected a file — executables ship flat; put data the program reads in resources/`);
console.log(`==> note: ${src}/ isn't shipped — executables ship flat (OS folders are named macos, windows, linux, or <os>-arm64 / <os>-x86_64)`);
return;
}
if (!(await readsAsNative(src))) {
if (strict) fail(`${where}: ${notNative()}`);
console.log(`==> note: ${src} isn't a ${EXEC_KIND} binary — not shipped in this build`);
return;
}
if (!IS_WIN && !(fst.mode & 0o111))
console.log(`==> note: ${src} isn't executable — builds mark it, but run chmod +x on it for dev`);
picked.set(name, src);
};
if (list === undefined) {
// Layers, least specific first; a later file replaces an earlier one of
// the same name. Everything in an OS folder is meant for that OS, so a
// wrong file there fails; at the root it's just another OS's.
const arch = target === 'universal' ? null : target ?? await hostArch();
const layers = [EXECUTABLES_DIR, EXECUTABLES_DIR + '/' + EXEC_OS];
if (arch) layers.push(EXECUTABLES_DIR + '/' + EXEC_OS + '-' + arch);
for (const dir of layers) {
const root = dir === EXECUTABLES_DIR;
if (!root) {
let dst = null;
try { dst = await tjs.lstat(dir); } catch {}
if (!dst) continue;
if (dst.isSymbolicLink || !dst.isDirectory) fail(`executables: ${dir}: expected a folder (symlinks are not supported)`);
}
const names = [];
for await (const e of await tjs.readDir(dir)) names.push(e.name);
for (const name of names.sort()) {
if (JUNK_FILES.includes(name) || (root && EXEC_OS_DIR.test(name))) continue;
await add(dir + '/' + name, name, !root, 'executables: ' + dir + '/' + name);
}
}
} else {
// A list: exactly these, each a binary for this OS (a folder means the
// files in it). Same path rules as "resources".
const from = new Map(); // name -> list entry, to report clashes
for (const raw of list) {
const where = 'tinyjs.json executable ' + JSON.stringify(raw);
if (typeof raw !== 'string' || !raw || raw.includes('\0')) fail(where + ': expected a non-empty path inside executables/');
const p = raw.replace(/\\/g, '/');
if (p.startsWith('/') || p.includes(':')) fail(where + ': absolute, drive and UNC paths are not allowed');
const parts = p.split('/').filter((x) => x && x !== '.');
if (parts.includes('..')) fail(where + ': parent traversal is not allowed');
if (!parts.length) fail(where + ': that is executables/ itself — leave "executables" out to ship the whole folder');
for (let i = 1; i <= parts.length; i++) {
let pst = null;
try { pst = await tjs.lstat(EXECUTABLES_DIR + '/' + parts.slice(0, i).join('/')); } catch {}
if (!pst) fail(where + ': not found');
if (pst.isSymbolicLink) fail(where + ': symlinks are not supported');
}
const src = EXECUTABLES_DIR + '/' + parts.join('/');
const srcs = [];
if ((await tjs.lstat(src)).isDirectory) {
const names = [];
for await (const e of await tjs.readDir(src)) if (!JUNK_FILES.includes(e.name)) names.push(e.name);
for (const name of names.sort()) srcs.push(src + '/' + name);
} else srcs.push(src);
for (const s of srcs) {
const name = s.replace(/^.*\//, '');
if (picked.get(name) === s) continue;
if (picked.has(name)) fail(`${where}: two files named ${name} would ship (${picked.get(name)} from ${from.get(name)}) — they land side by side, so names must differ`);
await add(s, name, true, where + (s === src ? '' : ' (' + s + ')'));
from.set(name, JSON.stringify(raw));
}
}
}
const files = [...picked].map(([name, src]) => ({ name, src })).sort((a, b) => (a.name < b.name ? -1 : 1));
return files.length ? { files } : null;
}
// Copy the staged sidecars to dest, keeping them executable.
async function copyExecutables(exe, dest) {
if (!exe) return;
await tjs.makeDir(dest, { recursive: true });
for (const { name } of exe.files) {
await copyFile('.build/executables/' + name, dest + '/' + name);
if (!IS_WIN) await tjs.chmod(dest + '/' + name, 0o755);
}
}
// "executableEntitlements": { "<file name>": ["com.apple…"] } (macOS) — the
// entitlements each sidecar is signed with, replacing any it arrived with.
function executableEntitlements(cfg) {
const v = cfg.executableEntitlements;
if (v === undefined) return {};
const files = (cfg.executablesStaged?.files ?? []).map((f) => f.name);
const bad = (why) => fail('tinyjs.json "executableEntitlements": ' + why);
if (!isPlainObject(v)) bad('expected { "<file name>": ["com.apple.security…", …] }');
for (const [name, list] of Object.entries(v)) {
if (!files.includes(name)) bad(`${JSON.stringify(name)} isn't one of the executables this build ships` +
(files.length ? ' (' + files.join(', ') + ')' : ' (none)'));
if (!Array.isArray(list) || list.some((k) => typeof k !== 'string' || !/^[A-Za-z0-9.-]+$/.test(k)))
bad(`${JSON.stringify(name)}: expected an array of entitlement keys, e.g. ["com.apple.security.cs.allow-jit"]`);
}
return v;
}
// Gather this build's sidecars flat in .build/executables. Dev links them on
// macOS/Linux, so a sidecar rebuilt while dev runs is the one that spawns;
// builds copy and mark them executable.
async function stageExecutables(exe, dev) {
if (!exe) return;
await tjs.makeDir('.build/executables', { recursive: true });
for (const { name, src } of exe.files) {
const dest = '.build/executables/' + name;
if (dev && !IS_WIN) await tjs.symlink(await tjs.realPath(src), dest);
else {
await copyFile(src, dest);
if (!IS_WIN) await tjs.chmod(dest, 0o755);
}
}
}
// Files for the person downloading the app — a README, a licence, install
// notes — ship from extras/, OUTSIDE the app: beside the executable in the
// Windows/Linux folder (so in the publish archive, and refreshed by each
// update), and at the root of the macOS dmg next to the .app. The .app and
// the macOS update zip never carry them — nobody looks inside a bundle they
// dragged to /Applications. Picked like executables/: with no list,
// everything at the top, overridden by name from extras/<os>/;
// "extras": [...] lists paths inside the folder instead. Each lands by its
// own name (a folder whole), next to files the build writes, so a name the
// build uses fails — case-insensitively, as macOS and Windows compare them.
const EXTRAS_DIR = 'extras';
const EXTRAS_OS_DIR = /^(macos|windows|linux)$/;
function extrasTaken(cfg) {
if (!IS_WIN && !IS_LINUX) return [cfg.title + '.app', 'Applications'];
const common = ['resources', 'executables', 'frontend', 'shared', 'bin', 'publish'];
return IS_WIN ? [cfg.name + '.exe', 'launcher.exe', ...common]
: [cfg.name, 'launcher', 'icon.png', ...common];
}
// Returns [{ name, src }] for this OS, [] when nothing ships.
async function validateExtras(cfg) {
const list = cfg.extras;
if (list !== undefined && !Array.isArray(list)) fail('tinyjs.json "extras" must be an array of paths inside extras/ (got ' + JSON.stringify(list) + ')');
let st = null;
try { st = await tjs.lstat(EXTRAS_DIR); } catch {}
if (st?.isSymbolicLink) fail('extras/: symlinks are not supported');
if (st && !st.isDirectory) fail('extras/ must be a directory');
if (!st) {
if (list?.length) fail('tinyjs.json "extras" lists paths inside extras/, but the project has no extras/ folder');
return [];
}
const taken = extrasTaken(cfg).map((n) => n.toLowerCase());
const picked = new Map(); // lower-cased name -> { name, src, where, layer }
const check = async (src, where) => {
let fst;
try { fst = await tjs.lstat(src); } catch { fail(`${where}: not found or unreadable`); }
if (fst.isSymbolicLink) fail(`${where}: symlinks are not supported (${src})`);
if (!fst.isDirectory && !fst.isFile) fail(`${where}: expected a regular file or folder (${src})`);
if (fst.isDirectory) for await (const e of await tjs.readDir(src)) await check(src + '/' + e.name, where);
};
// A later layer replaces an earlier one's file of the same name; within a
// layer (or a list) two of them would land on each other.
const add = async (src, where, layer) => {
const name = src.replace(/^.*\//, '');
const key = name.toLowerCase();
if (picked.get(key)?.src === src) return;
await check(src, where);
if (taken.includes(key)) fail(`${where}: the build already writes a ${name} there — rename it`);
const had = picked.get(key);
if (had && had.layer === layer) fail(`${where}: two extras named ${name} would ship (${had.src}, from ${had.where}) — they land side by side, so names must differ`);
picked.set(key, { name, src, where, layer });
};
if (list === undefined) {
const layers = [EXTRAS_DIR, EXTRAS_DIR + '/' + EXEC_OS];
for (const [layer, dir] of layers.entries()) {
if (layer) {
let dst = null;
try { dst = await tjs.lstat(dir); } catch {}
if (!dst) continue;
if (dst.isSymbolicLink || !dst.isDirectory) fail(`extras: ${dir}: expected a folder (symlinks are not supported)`);
}
const names = [];
for await (const e of await tjs.readDir(dir)) names.push(e.name);
for (const name of names.sort()) {
if (JUNK_FILES.includes(name) || (!layer && EXTRAS_OS_DIR.test(name))) continue;
await add(dir + '/' + name, 'extras: ' + dir + '/' + name, layer);
}
}
} else {
// Same path rules as "resources".
for (const raw of list) {
const where = 'tinyjs.json extra ' + JSON.stringify(raw);
if (typeof raw !== 'string' || !raw || raw.includes('\0')) fail(where + ': expected a non-empty path inside extras/');
const p = raw.replace(/\\/g, '/');
if (p.startsWith('/') || p.includes(':')) fail(where + ': absolute, drive and UNC paths are not allowed');
const parts = p.split('/').filter((x) => x && x !== '.');
if (parts.includes('..')) fail(where + ': parent traversal is not allowed');
if (IS_WIN && parts.some((s) => /[. ]$/.test(s))) fail(where + ': Windows path components cannot end in a dot or space');
if (!parts.length) fail(where + ': that is extras/ itself — leave "extras" out to ship the whole folder');
for (let i = 1; i < parts.length; i++) {
let pst = null;
try { pst = await tjs.lstat(EXTRAS_DIR + '/' + parts.slice(0, i).join('/')); } catch {}
if (!pst) fail(where + ': not found');
if (pst.isSymbolicLink) fail(where + ': symlinks are not supported');
}
await add(EXTRAS_DIR + '/' + parts.join('/'), where, 0);
}
}
return [...picked.values()].map(({ name, src }) => ({ name, src }))
.sort((a, b) => (a.name < b.name ? -1 : 1));
}
// Copy one extra (a folder whole, minus OS junk), keeping exec bits — an
// install.sh in a Linux tarball is meant to run.
async function copyExtra(src, dest) {
const st = await tjs.lstat(src);
if (st.isDirectory) {
await tjs.makeDir(dest, { recursive: true });
for await (const e of await tjs.readDir(src))
if (!JUNK_FILES.includes(e.name)) await copyExtra(src + '/' + e.name, dest + '/' + e.name);
} else {
await copyFile(src, dest);
if (!IS_WIN && (st.mode & 0o111)) await tjs.chmod(dest, 0o755);
}
}
async function shipExtras(cfg, dest, label) {
const files = await validateExtras(cfg);
if (!files.length) return;
for (const { name, src } of files) await copyExtra(src, dest + '/' + name);
if (label) console.log(`==> extras: ${files.map((f) => f.name).join(', ')} → ${label}`);
}
// assets/ holds the files the OS and the build read, each by a known name:
// the icon, the About panel's Credits, the macOS help book. Nothing else in
// it ships, so anything unrecognised is most likely a page or data file put
// in the wrong folder — say so instead of dropping it silently.
const CREDITS_FILES = ['Credits.html', 'Credits.rtf', 'Credits.rtfd'];
// The About panel's credits: assets/Credits.{html,rtf,rtfd}, or a
// Credits.html at the project root (where it went before assets/).
async function findCredits() {
for (const f of CREDITS_FILES) if (await exists('assets/' + f)) return 'assets/' + f;
return (await exists('Credits.html')) ? 'Credits.html' : null;
}
// "helpBook" (in the macos block) names a folder inside assets/.
function helpBookRel(value) {
if (value === undefined) return null;
const rel = typeof value === 'string' ? value.replace(/\\/g, '/').replace(/\/+$/, '') : '';
if (!rel || rel.startsWith('/') || rel.includes(':') || rel.split('/').includes('..'))
fail('tinyjs.json "helpBook" must name a folder inside assets/ (got ' + JSON.stringify(value) + ')');
// It lands in the .app's Resources/, which already holds the app itself
// and its icon and credits.
const folder = rel.replace(/^.*\//, '');
if (/^(app|AppIcon\.icns|Credits\.(html|rtf|rtfd))$/i.test(folder))
fail(`tinyjs.json "helpBook": a help book can't be named ${folder} — rename the folder`);
return rel;
}
async function warnUnusedAssets(cfg) {
const used = new Set(['.DS_Store', 'Thumbs.db', 'desktop.ini', ...CREDITS_FILES]);
if (cfg.icon && /^assets\/[^/]+$/.test(cfg.icon)) used.add(cfg.icon.slice(7));
if (cfg.helpBookAnyOS) used.add(cfg.helpBookAnyOS.split('/')[0]);
let iter;
try { iter = await tjs.readDir('assets'); } catch { return; }
for await (const e of iter) {
if (used.has(e.name)) continue;
// A README or licence here was most likely meant for the download.
if (/^(read[ _-]?me|licen[cs]e|copying|install|changelog)\b/i.test(e.name)) {
console.log(`==> note: assets/${e.name} isn't used by the build — files for the person ` +
'downloading the app (a README, a licence) go in extras/');
continue;
}
console.log(`==> note: assets/${e.name} isn't used by the build — assets/ is for the ` +
'icon, Credits and help book; files for your page go in the frontend, data for your code in resources/');
}
}
// Copy the help book (#47) into the .app's Resources and (re)build its
// search index. Returns the Info.plist values, or null without one: the
// folder, and the name Help Viewer knows it by — the book's own
// CFBundleIdentifier, falling back to its folder name for a book with no
// Info.plist (older ones).
async function stageHelpBook(cfg, resDir) {
const rel = helpBookRel(cfg.helpBook);
if (!rel) return null;
const src = 'assets/' + rel;
let st = null;
try { st = await tjs.lstat(src); } catch {}
if (!st?.isDirectory) fail(`tinyjs.json "helpBook": ${src} is not a folder`);
const folder = rel.replace(/^.*\//, '');
const dest = resDir + '/' + folder;
await run(['cp', '-R', src, dest]);
const info = dest + '/Contents/Info.plist';
const key = async (k) => (await capture(['plutil', '-extract', k, 'raw', '-o', '-', info])).trim();
let name = await key('CFBundleIdentifier');
if (!name) {
name = folder.replace(/\.help$/i, '');
console.log(`==> note: ${src} has no Contents/Info.plist CFBundleIdentifier — naming the help book "${name}"`);
}
// A stale index is the usual reason Help search finds nothing, so build a
// fresh one into the copy for each language, where the book says it lives.
const indexPath = await key('HPDBookIndexPath');
if (indexPath) {
let iter = null;
try { iter = await tjs.readDir(dest + '/Contents/Resources'); } catch {}
for await (const e of iter ?? []) {
if (!e.isDirectory || !e.name.endsWith('.lproj')) continue;
const dir = dest + '/Contents/Resources/' + e.name;
if (!(await tryRun(['hiutil', '-I', 'corespotlight', '-Caf', dir + '/' + indexPath, dir])))
console.log(`==> note: hiutil could not index ${e.name} of the help book — keeping the index it shipped with`);
}
}
console.log(`==> help book ${folder} (${name})`);
return { folder, name };
}
// Portable rm -rf (replaces shelling out, which Windows has no equivalent for).
async function rmTree(p) {
try {
await tjs.remove(p, { recursive: true });
return;
} catch {}
try {
const st = await tjs.stat(p);
if (st.isDirectory) {
const iter = await tjs.readDir(p);
for await (const e of iter) await rmTree(p + '/' + e.name);
}
await tjs.remove(p);
} catch {}
}
// The first file found under dir (depth-first), or null if it holds none —
// for naming what kept a directory from being removed.
async function firstFileIn(dir) {
try {
for await (const e of await tjs.readDir(dir)) {
const p = dir + '/' + e.name;
if (!e.isDirectory) return p;
const f = await firstFileIn(p);
if (f) return f;
}
} catch {}
return null;
}
async function copyFile(src, dest) {
await tjs.writeFile(dest, await tjs.readFile(src));
}
// Run a shell command line: sh -c on POSIX, cmd /c on Windows (also the only
// way to reach npm/npx there — they are .cmd shims CreateProcess won't exec).
const shellArgv = (cmdline) => IS_WIN ? ['cmd', '/c', cmdline] : ['sh', '-c', cmdline];
// npm/npx-style argv: pass through on POSIX, hop through cmd /c on Windows.
const nodeToolArgv = (argv) => IS_WIN ? ['cmd', '/c', ...argv] : argv;
const SKILL_DIRS = ['.claude/skills/tinyjs', '.agents/skills/tinyjs'];
// Give coding agents working in a scaffolded project the tinyjs reference
// skill — in .claude/skills/ (Claude Code) and .agents/skills/ (the
// tool-agnostic location other agents read).
async function writeAgentSkill(dir) {
// The whole skill dir: SKILL.md plus references/ (loaded on demand by the
// agent, so the core stays small while the deep material rides along).
for (const rel of SKILL_DIRS) await copyTree(TOOL_DIR + 'skill', dir + '/' + rel);
}
// Files `tinyjs new` copies into a project from the install: the agent skill
// folders and the ambient types (types/ for the plain template, src/ and
// backend/ for the Vite ones). Only those the project still has: a deleted
// skill folder or types file stays deleted.
//
// Symbolic links are never followed. A cloned project can ship
// .claude/skills/tinyjs -> ~/Documents or types/tiny.d.ts -> ~/.zshrc; syncing
// through those would delete or overwrite the user's own files. An item with
// a link anywhere on its path is reported and left alone (`linked`), and a
// link INSIDE a skill folder is removed as a link, then replaced by a file.
async function linkOnPath(rel, dir = '.') {
const parts = rel.split('/');
for (let i = 1; i <= parts.length; i++) {
let st;
try { st = await tjs.lstat(dir + '/' + parts.slice(0, i).join('/')); } catch { return false; }
if (st.isSymbolicLink) return true;
}
return false;
}
const lexists = (p) => tjs.lstat(p).then(() => true, () => false);
async function projectToolFiles(dir = '.') {
const items = [];
for (const rel of SKILL_DIRS)
if (await lexists(dir + '/' + rel))
items.push({ rel, src: TOOL_DIR + 'skill', isDir: true, linked: await linkOnPath(rel, dir) });
for (const sub of ['types', 'src', 'backend'])
for (const f of ['tiny.d.ts', 'tjs.d.ts']) {
// A Vite project's src/ is the page, which has no tjs: older scaffolds
// left a tjs.d.ts stub there, and txiki's real types would only offer
// the page calls it can't make. Leave it alone rather than upgrade it.
if (sub === 'src' && f === 'tjs.d.ts') continue;
const rel = `${sub}/${f}`;
if (await lexists(dir + '/' + rel))
items.push({ rel, src: TOOL_DIR + 'template/types/' + f, isDir: false, linked: await linkOnPath(rel, dir) });
}
return items;
}
// Every entry under root by relative path: a regular file's bytes, IS_DIR for
// a folder (descended into), NOT_FILE for anything else (link, fifo,
// socket), which is never read or followed, or an Unreadable for a file that
// couldn't be read (on Windows, one held open with no sharing): that file
// fails on its own instead of taking the whole folder with it. Folders are
// listed so that an extra empty one counts as a difference too.
const IS_DIR = Symbol('folder');
const NOT_FILE = Symbol('not a regular file');
class Unreadable { constructor(e) { this.message = e?.message ?? String(e); } }
async function filesUnder(root, rel = '', out = new Map()) {
for await (const e of await tjs.readDir(root + (rel ? '/' + rel : ''))) {
const r = (rel ? rel + '/' : '') + e.name;
if (e.isDirectory) {
out.set(r, IS_DIR);
await filesUnder(root, r, out);
} else if (!e.isFile) {
out.set(r, NOT_FILE);
} else {
out.set(r, await tjs.readFile(root + '/' + r).catch((err) => new Unreadable(err)));
}
}
return out;
}
const sameBytes = (a, b) => {
if (a === NOT_FILE || b === NOT_FILE || a instanceof Unreadable || b instanceof Unreadable) return false;
if (a === IS_DIR || b === IS_DIR) return a === b;
return a.length === b.length && a.every((v, i) => v === b[i]);
};
// True when the project's copy matches the install's, entry for entry. Not
// meaningful for a linked item (callers skip those).
async function toolFileCurrent(item, dir = '.') {
try {
if (!item.isDir) return sameBytes(await tjs.readFile(dir + '/' + item.rel), await tjs.readFile(item.src));
const [mine, theirs] = await Promise.all([filesUnder(dir + '/' + item.rel), filesUnder(item.src)]);
return mine.size === theirs.size &&
[...theirs].every(([r, entry]) => mine.has(r) && sameBytes(mine.get(r), entry));
} catch { return false; }
}
// Bring a project's skill and types up to this tinyjs. Explicit, never run by
// dev or build: someone may have edited these files.
async function cmdUpdateProject() {
if (args.length) fail('usage: tinyjs update-project (no arguments)');
if (!(await exists('tinyjs.json'))) fail('no tinyjs.json here — run this from a tinyjs project');
const items = await projectToolFiles();
// File by file, so every change is named: a skill folder is made to match
// this tinyjs's exactly, and a leftover (a reference since renamed or
// dropped, or a file someone added) is deleted out loud, never silently.
// Each step is caught on its own: a file another program holds open
// (EBUSY on Windows) is named and skipped, and the run carries on.
const changes = [], skipped = [], failed = [];
const step = async (label, path, fn) => {
try {
await fn();
changes.push(label + path);
return true;
} catch (e) {
failed.push(`${path}: ${e?.message ?? e}`);
return false;
}
};
for (const item of items) {
if (item.linked) {
skipped.push(item.rel + (item.isDir ? '/' : ''));
continue;
}
if (!item.isDir) {
if (!(await toolFileCurrent(item)))
await step('updated ', item.rel, () => copyFile(item.src, item.rel));
continue;
}
let mine, theirs;
try {
[mine, theirs] = await Promise.all([filesUnder(item.rel), filesUnder(item.src)]);
} catch (e) {
failed.push(`${item.rel}/: could not read it: ${e?.message ?? e}`);
continue;
}
// The install's own copy must be whole; a broken install is not synced.
const broken = [...theirs].find(([, entry]) => entry instanceof Unreadable);
if (broken) {
failed.push(`${item.src}/${broken[0]} (in tinyjs itself): ${broken[1].message}`);
continue;
}
// Removals first: a link or other non-file is unlinked before anything
// is written at (or under) its name, so no write can go through it.
// Deepest paths first, so a folder's contents go before the folder.
const remove = [...mine]
.filter(([r, entry]) => !theirs.has(r) || !sameBytes(entry, theirs.get(r)) &&
(entry === NOT_FILE || entry === IS_DIR || theirs.get(r) === IS_DIR))
.map(([r]) => r)
.sort((a, b) => b.split('/').length - a.split('/').length);
for (const r of remove) {
const path = item.rel + '/' + r;
const entry = mine.get(r);
if (entry === IS_DIR) {
// Only an emptied folder: txiki's remove() deletes a folder WITH its
// contents even without { recursive }, and a non-empty one here means
// something inside failed to go and has been reported already.
let empty = true;
try { for await (const _ of await tjs.readDir(path)) { empty = false; break; } } catch {}
if (!empty) continue;
if (await step('removed ', path + '/', () => tjs.remove(path))) mine.delete(r);
} else if (await step('removed ', path + (entry === NOT_FILE ? ' (not a regular file)' : ''),
() => tjs.remove(path))) {
mine.delete(r);
}
}
for (const [r, entry] of theirs) {
if (entry === IS_DIR || (mine.has(r) && sameBytes(mine.get(r), entry))) continue;
const dest = item.rel + '/' + r;
await step(mine.has(r) ? 'updated ' : 'added ', dest, async () => {
// A link whose removal failed above must not be written through.
if (await linkOnPath(dest)) throw new Error('a symbolic link that could not be removed is in the way');
await tjs.makeDir(dest.replace(/\/[^/]*$/, ''), { recursive: true }).catch(() => {});
await tjs.writeFile(dest, entry);
});
}
}
if (!items.some((item) => item.isDir)) {
for (const rel of SKILL_DIRS) {
// .claude or .claude/skills may itself be a link, possibly a dangling one.
if (await linkOnPath(rel)) { skipped.push(rel + '/'); continue; }
await step('added ', rel + '/', () => copyTree(TOOL_DIR + 'skill', rel));
}
}
const version = await toolVersion();
for (const s of skipped)
console.log(`skipped ${s}: it is, or is inside, a symbolic link — tinyjs won't write through one`);
if (changes.length) {
console.log(`from tinyjs ${version}:`);
for (const c of changes) console.log(' ' + c);
} else if (!failed.length) {
console.log(`${skipped.length ? 'nothing else to update' : 'already up to date'} with tinyjs ${version}`);
}
if (changes.some((c) => !c.startsWith('added')))
console.log('edits to updated or removed files are gone; git has the old versions.');
if (failed.length) {
console.log(`could not update ${failed.length} item(s):`);
for (const f of failed) console.log(' ' + f);
console.log('check their permissions, close whatever has them open (an editor, Explorer, a terminal');
console.log('inside the folder), and run it again.');
tjs.exit(1);
}
}
async function run(argv, opts = {}) {
const p = tjs.spawn(argv, { stdin: 'inherit', stdout: 'inherit', stderr: 'inherit', ...opts });
const st = await p.wait();
if (st.exit_status !== 0 || st.term_signal) {
fail(`command failed (${argv[0]}): ` + JSON.stringify(st));
}
}
// Like run(), but stdout passes through only until a line matches `stopAt`;
// that line and everything after it are dropped. For create-vite, whose
// closing "Done. Now run: npm install / npm run dev" contradicts the steps
// we print next (issue #43).
async function runUntil(argv, stopAt, opts = {}) {
const p = tjs.spawn(argv, { stdin: 'inherit', stdout: 'pipe', stderr: 'inherit', ...opts });
const reader = p.stdout.getReader();
let pending = '', stopped = false;
for (;;) {
const { value, done } = await reader.read();
if (done) break;
if (stopped) continue; // keep draining so the child never blocks on a full pipe
pending += dec.decode(value, { stream: true });
const lines = pending.split('\n');
pending = lines.pop();
let out = '';
for (const l of lines) {
if (stopAt.test(l)) { stopped = true; break; }
out += l + '\n';
}
if (out) await writeOut(out);
}
if (!stopped && pending && !stopAt.test(pending)) await writeOut(pending);
const st = await p.wait();
if (st.exit_status !== 0 || st.term_signal) {
fail(`command failed (${argv[0]}): ` + JSON.stringify(st));
}
}
// Run a command and capture its stdout.
async function runCapture(argv) {
const p = tjs.spawn(argv, { stdout: 'pipe', stderr: 'ignore' });
const reader = p.stdout.getReader();
let out = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
out += dec.decode(value, { stream: true });
}
const st = await p.wait();
if (st.exit_status !== 0 || st.term_signal) fail(`command failed (${argv[0]})`);
return out;
}
// Like run(), but returns false on failure instead of aborting.
async function tryRun(argv, opts = {}) {
const p = tjs.spawn(argv, { stdin: 'inherit', stdout: 'ignore', stderr: 'ignore', ...opts });
const st = await p.wait();
return st.exit_status === 0 && !st.term_signal;
}
// Capture stdout, tolerating a non-zero exit (returns whatever was printed).
async function capture(argv, opts = {}) {
const p = tjs.spawn(argv, { stdout: 'pipe', stderr: 'ignore', ...opts });
const reader = p.stdout.getReader();
let out = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
out += dec.decode(value, { stream: true });
}
await p.wait();
return out;
}
// --- self-update -------------------------------------------------------------
const REPO = 'tarwin/tinyjsapp';
const UPDATE_CHECK_FILE = TOOL_DIR + '.update-check';
const UPDATE_CHECK_INTERVAL = 24 * 60 * 60 * 1000;
async function toolVersion() {
try {
return dec.decode(await tjs.readFile(TOOL_DIR + 'VERSION')).trim();
} catch {
return 'dev';
}
}
function parseVer(v) {
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(v));
return m ? [+m[1], +m[2], +m[3]] : null;
}
// True when `latest` is a release newer than `current`.
function isNewer(current, latest) {
const a = parseVer(current), b = parseVer(latest);
if (!a || !b) return false;
for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] < b[i];
return false;
}
function withTimeout(promise, ms) {
return new Promise((resolve) => {
const t = setTimeout(() => resolve(null), ms);
promise.then(
(v) => { clearTimeout(t); resolve(v); },
() => { clearTimeout(t); resolve(null); },
);
});
}
// The tag comes off github.com's /releases/latest redirect (→ /releases/tag/
// vX.Y.Z), not the REST API: unauthenticated API calls are capped at 60 an
// hour per IP, which shared CI runners hit constantly (#51).
// TINYJS_UPDATE_URL is a test hook (point it at a listener that drops
// connections); only a tag that parses as a version is ever used.
const LATEST_URL = tjs.env.TINYJS_UPDATE_URL || `https://github.com/${REPO}/releases/latest`;
function tagFromUrl(url) {
const tag = String(url || '').replace(/\/+$/, '').split('/').pop();
return parseVer(tag) ? tag : null;
}
// Rejects after ms instead of resolving null, so the reason can be reported.
function rejectAfter(promise, ms) {
let t;
return Promise.race([
promise,
new Promise((_, reject) => { t = setTimeout(() => reject(new Error(`timed out after ${ms / 1000}s`)), ms); }),
]).finally(() => clearTimeout(t));
}
// Redirects are followed by hand: txiki follows a Location to file:// itself
// and throws outside the promise, killing the CLI. Usually one hop — the tag
// is already in /releases/latest's Location.
async function latestViaFetch(ms) {
let url = LATEST_URL;
for (let hop = 0; hop < 5; hop++) {
const res = await rejectAfter(fetch(url, {
method: 'HEAD', redirect: 'manual', headers: { 'user-agent': 'tinyjs-cli' },
}), ms);
if (res.status >= 300 && res.status < 400) {
const next = new URL(res.headers.get('location') || '', url);
if (next.protocol !== 'https:' && next.protocol !== 'http:') {
throw new Error(`refusing redirect to ${next.protocol}`);
}
url = next.href;
if (tagFromUrl(url)) return tagFromUrl(url);
continue;
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const tag = tagFromUrl(url);
if (!tag) throw new Error(`no version in ${url}`);
return tag;
}
throw new Error('too many redirects');
}
// txiki's fetch drops connections on some networks where curl and browsers
// don't ("closed before established", #67), and the CLI runs on bare tjs —
// bridge.js's fetch repair shim never loads here. curl ships with macOS,
// Linux distros and Windows 10 1803+. --proto keeps every hop http(s); the
// URL sits after -- so it can't parse as a flag.
async function latestViaCurl() {
const p = tjs.spawn(['curl', '-sS', '-I', '-L', '--max-redirs', '5',
'--proto', '=http,https', '--proto-redir', '=http,https',
'--connect-timeout', '10', '--max-time', '15', '-A', 'tinyjs-cli',
'-o', IS_WIN ? 'NUL' : '/dev/null',
'-w', '%{http_code} %{url_effective}', '--', LATEST_URL],
{ stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
const readAll = async (s) => {
const r = s.getReader();
let out = '';
for (;;) {
const { value, done } = await r.read();
if (done) return out;
out += dec.decode(value, { stream: true });
}
};
const [out, err] = await Promise.all([readAll(p.stdout), readAll(p.stderr)]);
const st = await p.wait();
if (st.exit_status !== 0 || st.term_signal) {
throw new Error(err.trim().replace(/^curl: /, '') || `exit ${st.exit_status}`);
}
const [code, url] = out.trim().split(' ');
if (!/^2/.test(code)) throw new Error(`HTTP ${code}`);
const tag = tagFromUrl(url);
if (!tag) throw new Error(`no version in ${url}`);
return tag;
}
// { tag } or { error } — the error names what each attempt hit, so a failed
// update says why instead of only "could not reach GitHub". `quick` (the
// background notice) makes one fetch attempt and nothing else.
async function fetchLatestVersion({ quick = false } = {}) {
const errors = [];