@coderook/cli 0.47.0 → 0.47.1

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.
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Repository = exports.DEFAULT_LINE = exports.FORMAT_LINE_V2 = exports.FORMAT_LINE = exports.STORE_DIRECTORY = void 0;
7
7
  exports.lineNameProblem = lineNameProblem;
8
+ exports.lockIsStale = lockIsStale;
8
9
  /**
9
10
  * A local history: the `.cbx/` folder at the top of a project.
10
11
  *
@@ -22,9 +23,11 @@ exports.lineNameProblem = lineNameProblem;
22
23
  * or a tree depends on the machine it was made on, so two people who make the
23
24
  * same save from the same files get the same id.
24
25
  */
26
+ const node_fs_1 = require("node:fs");
25
27
  const promises_1 = require("node:fs/promises");
26
28
  const node_os_1 = __importDefault(require("node:os"));
27
29
  const node_path_1 = __importDefault(require("node:path"));
30
+ const durable_js_1 = require("./durable.js");
28
31
  const store_js_1 = require("./store.js");
29
32
  exports.STORE_DIRECTORY = ".cbx";
30
33
  exports.FORMAT_LINE = "cbx-local 1";
@@ -60,7 +63,15 @@ function lineNameProblem(name) {
60
63
  return "names ending .partial are how cbx marks unfinished writes";
61
64
  return null;
62
65
  }
63
- async function writeAtomically(target, contents) {
66
+ /*
67
+ Lines, state and config: synced to disk before and after the rename, so a
68
+ power cut cannot leave a line naming a save that never reached the disk
69
+ (durable.ts). The index is only a cache of what files looked like, so it
70
+ is renamed into place without the syncs, which every status would pay for.
71
+ */
72
+ async function writeAtomically(target, contents, durable = true) {
73
+ if (durable)
74
+ return (0, durable_js_1.writeDurably)(target, contents);
64
75
  const partial = `${target}.partial`;
65
76
  await (0, promises_1.writeFile)(partial, contents);
66
77
  await (0, promises_1.rename)(partial, target);
@@ -96,9 +107,10 @@ class Repository {
96
107
  await (0, promises_1.mkdir)(node_path_1.default.join(directory, "objects"), { recursive: true });
97
108
  await (0, promises_1.mkdir)(node_path_1.default.join(directory, "lines"), { recursive: true });
98
109
  const format = process.env.CBX_LOCAL_FORMAT === "2" ? exports.FORMAT_LINE_V2 : exports.FORMAT_LINE;
99
- await (0, promises_1.writeFile)(node_path_1.default.join(directory, "format"), `${format}\n`);
100
- await (0, promises_1.writeFile)(node_path_1.default.join(directory, "state.json"), JSON.stringify({ line }));
101
- await (0, promises_1.writeFile)(node_path_1.default.join(directory, "config.json"), "{}");
110
+ await (0, durable_js_1.writeDurably)(node_path_1.default.join(directory, "format"), `${format}\n`);
111
+ await (0, durable_js_1.writeDurably)(node_path_1.default.join(directory, "state.json"), JSON.stringify({ line }));
112
+ await (0, durable_js_1.writeDurably)(node_path_1.default.join(directory, "config.json"), "{}");
113
+ await (0, durable_js_1.syncDirectory)(full);
102
114
  return new Repository(full, format);
103
115
  }
104
116
  /** The history `from` is inside, looking upward; null when there is none. */
@@ -150,6 +162,8 @@ class Repository {
150
162
  const problem = lineNameProblem(line);
151
163
  if (problem)
152
164
  throw new Error(`Cannot name a line "${line}": ${problem}.`);
165
+ /* Whatever the line will name is on the disk before the line names it. */
166
+ await this.objects.syncWritten();
153
167
  await writeAtomically(node_path_1.default.join(this.directory, "lines", line), `${id}\n`);
154
168
  }
155
169
  async lineExists(line) {
@@ -370,7 +384,7 @@ class Repository {
370
384
  ]),
371
385
  })
372
386
  : JSON.stringify(Object.fromEntries(index));
373
- await writeAtomically(node_path_1.default.join(this.directory, "index.json"), body);
387
+ await writeAtomically(node_path_1.default.join(this.directory, "index.json"), body, false);
374
388
  }
375
389
  /* ---- the lock ------------------------------------------------------- */
376
390
  /**
@@ -383,13 +397,18 @@ class Repository {
383
397
  async locked(work) {
384
398
  const lock = node_path_1.default.join(this.directory, "lock");
385
399
  let handle;
386
- try {
387
- handle = await (0, promises_1.open)(lock, "wx");
388
- }
389
- catch {
390
- throw new Error(`Another cbx command is using this history. If none is running, delete ${lock} and try again.`);
400
+ for (let attempt = 0;; attempt += 1) {
401
+ try {
402
+ handle = await (0, promises_1.open)(lock, "wx");
403
+ break;
404
+ }
405
+ catch (error) {
406
+ if (error.code !== "EEXIST" || attempt > 0 || !(await clearedStaleLock(lock))) {
407
+ throw new Error(`Another cbx command is using this history. If none is running, delete ${lock} and try again.`);
408
+ }
409
+ }
391
410
  }
392
- await handle.write(`${process.pid}\n`);
411
+ await handle.write(lockRecord());
393
412
  await handle.close();
394
413
  try {
395
414
  return await work();
@@ -401,3 +420,89 @@ class Repository {
401
420
  }
402
421
  }
403
422
  exports.Repository = Repository;
423
+ /** A marker for when process `pid` started, comparable between runs; null when unknown here. */
424
+ function startMarker(pid) {
425
+ if (process.platform === "linux") {
426
+ try {
427
+ const stat = (0, node_fs_1.readFileSync)(`/proc/${pid}/stat`, "utf8");
428
+ /* Field 22, after the parenthesised name, which may hold spaces. */
429
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null;
430
+ }
431
+ catch {
432
+ return null;
433
+ }
434
+ }
435
+ return pid === process.pid ? String(Math.round(performance.timeOrigin)) : null;
436
+ }
437
+ function lockRecord() {
438
+ return `${JSON.stringify({ pid: process.pid, started: startMarker(process.pid), host: node_os_1.default.hostname() })}\n`;
439
+ }
440
+ function readLockHolder(text) {
441
+ const trimmed = text.trim();
442
+ /* Written by a cbx before this one: the id alone. */
443
+ if (/^\d+$/.test(trimmed))
444
+ return { pid: Number(trimmed), started: null, host: null };
445
+ try {
446
+ const parsed = JSON.parse(trimmed);
447
+ if (!Number.isSafeInteger(parsed.pid))
448
+ return null;
449
+ return {
450
+ pid: parsed.pid,
451
+ started: typeof parsed.started === "string" ? parsed.started : null,
452
+ host: typeof parsed.host === "string" ? parsed.host : null,
453
+ };
454
+ }
455
+ catch {
456
+ return null;
457
+ }
458
+ }
459
+ function running(pid) {
460
+ try {
461
+ process.kill(pid, 0);
462
+ return true;
463
+ }
464
+ catch (error) {
465
+ /* EPERM: it exists and belongs to somebody else. */
466
+ return error.code === "EPERM";
467
+ }
468
+ }
469
+ /** Whether the process a lock names is certainly gone. */
470
+ function lockIsStale(text) {
471
+ const holder = readLockHolder(text);
472
+ if (!holder || holder.pid <= 0)
473
+ return false;
474
+ /* Another machine's process (a shared or synced folder) cannot be judged from here. */
475
+ if (holder.host !== node_os_1.default.hostname())
476
+ return false;
477
+ if (!running(holder.pid))
478
+ return true;
479
+ const now = startMarker(holder.pid);
480
+ return holder.started !== null && now !== null && now !== holder.started;
481
+ }
482
+ /**
483
+ * Remove a lock whose holder is certainly gone; true when it was removed.
484
+ * Moved aside rather than deleted, and only if it still says what was judged,
485
+ * so two commands clearing it at once do not remove each other's new lock.
486
+ */
487
+ async function clearedStaleLock(lock) {
488
+ let text;
489
+ try {
490
+ text = await (0, promises_1.readFile)(lock, "utf8");
491
+ }
492
+ catch {
493
+ return true;
494
+ }
495
+ if (!lockIsStale(text))
496
+ return false;
497
+ const aside = `${lock}.stale-${process.pid}-${Date.now()}`;
498
+ try {
499
+ if ((await (0, promises_1.readFile)(lock, "utf8")) !== text)
500
+ return false;
501
+ await (0, promises_1.rename)(lock, aside);
502
+ }
503
+ catch {
504
+ return false;
505
+ }
506
+ await (0, promises_1.rm)(aside, { force: true });
507
+ return true;
508
+ }
@@ -29,6 +29,7 @@ exports.digestOf = digestOf;
29
29
  const node_crypto_1 = require("node:crypto");
30
30
  const promises_1 = require("node:fs/promises");
31
31
  const node_path_1 = __importDefault(require("node:path"));
32
+ const durable_js_1 = require("./durable.js");
32
33
  const cbx_js_1 = require("../core/cbx.js");
33
34
  const delta_js_1 = require("../shared/delta.js");
34
35
  const store_v2_js_1 = require("./store_v2.js");
@@ -122,9 +123,32 @@ class ObjectStore {
122
123
  writingV2 = new Map();
123
124
  pendingV2Bytes = 0;
124
125
  blocks = new Map();
126
+ /* Folders given new loose objects since they were last synced (syncWritten). */
127
+ unsynced = new Set();
128
+ /** Pack indexes that could not be read, and why; skipped, not fatal. */
129
+ damaged = [];
130
+ onDamage;
125
131
  constructor(directory, options = {}) {
126
132
  this.directory = directory;
127
133
  this.v2 = options.v2 === true;
134
+ this.onDamage =
135
+ options.onDamage ??
136
+ ((index, reason) => process.stderr.write(`cbx: skipped a damaged pack index, ${index} (${reason}); the objects it listed read as missing.\n`));
137
+ }
138
+ reportDamage(index, error) {
139
+ if (this.damaged.some((one) => one.index === index))
140
+ return;
141
+ const reason = error instanceof Error ? error.message : String(error);
142
+ this.damaged.push({ index, reason });
143
+ this.onDamage(index, reason);
144
+ }
145
+ /** Sync the folders new loose objects went into, before anything names them. */
146
+ async syncWritten() {
147
+ await this.flush();
148
+ const folders = [...this.unsynced];
149
+ this.unsynced.clear();
150
+ for (const folder of folders)
151
+ await (0, durable_js_1.syncDirectory)(folder);
128
152
  }
129
153
  get packDirectory() {
130
154
  return node_path_1.default.join(this.directory, "packs");
@@ -159,9 +183,30 @@ class ObjectStore {
159
183
  }
160
184
  for (const name of names.filter((one) => one.endsWith(".idx")).sort()) {
161
185
  const pack = node_path_1.default.join(this.packDirectory, name.replace(/\.idx$/, ".pack"));
162
- const index = JSON.parse(await (0, promises_1.readFile)(node_path_1.default.join(this.packDirectory, name), "utf8"));
163
- for (const [digest, [offset, length]] of Object.entries(index)) {
164
- found.set(digest, { pack, offset, length });
186
+ /*
187
+ One damaged index used to stop every command in the history with a
188
+ JSON error. It is skipped and reported instead: the objects it named
189
+ read as missing, which is what they effectively are.
190
+ */
191
+ try {
192
+ const index = JSON.parse(await (0, promises_1.readFile)(node_path_1.default.join(this.packDirectory, name), "utf8"));
193
+ const rows = [];
194
+ for (const [digest, place] of Object.entries(index)) {
195
+ if (!exports.DIGEST.test(digest) ||
196
+ !Array.isArray(place) ||
197
+ !Number.isSafeInteger(place[0]) ||
198
+ !Number.isSafeInteger(place[1]) ||
199
+ place[0] < 0 ||
200
+ place[1] < 0) {
201
+ throw new Error("an entry is not an object's place");
202
+ }
203
+ rows.push([digest, { pack, offset: place[0], length: place[1] }]);
204
+ }
205
+ for (const [digest, place] of rows)
206
+ found.set(digest, place);
207
+ }
208
+ catch (error) {
209
+ this.reportDamage(node_path_1.default.join(this.packDirectory, name), error);
165
210
  }
166
211
  }
167
212
  const v2 = await this.readV2Indexes();
@@ -183,7 +228,12 @@ class ObjectStore {
183
228
  }
184
229
  for (const name of names.filter((one) => one.endsWith(".idx")).sort()) {
185
230
  const pack = node_path_1.default.join(this.v2Directory, name.replace(/\.idx$/, ".pack"));
186
- found.add(new store_v2_js_1.V2IndexFile(pack, await (0, promises_1.readFile)(node_path_1.default.join(this.v2Directory, name))));
231
+ try {
232
+ found.add(new store_v2_js_1.V2IndexFile(pack, await (0, promises_1.readFile)(node_path_1.default.join(this.v2Directory, name))));
233
+ }
234
+ catch (error) {
235
+ this.reportDamage(node_path_1.default.join(this.v2Directory, name), error);
236
+ }
187
237
  }
188
238
  return found;
189
239
  }
@@ -288,7 +338,16 @@ class ObjectStore {
288
338
  this.made.add(folder);
289
339
  }
290
340
  const partial = `${target}.${(0, node_crypto_1.randomBytes)(6).toString("hex")}.partial`;
291
- await (0, promises_1.writeFile)(partial, frame);
341
+ const file = await (0, promises_1.open)(partial, "w");
342
+ try {
343
+ await file.writeFile(frame);
344
+ /* On the disk before it has its real name; the folder is synced by syncWritten. */
345
+ await file.sync();
346
+ }
347
+ finally {
348
+ await file.close();
349
+ }
350
+ this.unsynced.add(folder);
292
351
  try {
293
352
  await (0, promises_1.rename)(partial, target);
294
353
  }
@@ -443,11 +502,10 @@ class ObjectStore {
443
502
  const id = digestOf(body);
444
503
  const pack = node_path_1.default.join(this.v2Directory, `${id}.pack`);
445
504
  const idx = node_path_1.default.join(this.v2Directory, `${id}.idx`);
446
- await (0, promises_1.writeFile)(`${pack}.partial`, body);
447
- await (0, promises_1.rename)(`${pack}.partial`, pack);
505
+ /* The pack is durable before the index that names it exists at all. */
506
+ await (0, durable_js_1.writeDurably)(pack, body);
448
507
  const encoded = (0, store_v2_js_1.encodeIndex)(entries);
449
- await (0, promises_1.writeFile)(`${idx}.partial`, encoded);
450
- await (0, promises_1.rename)(`${idx}.partial`, idx);
508
+ await (0, durable_js_1.writeDurably)(idx, encoded);
451
509
  (await this.v2Index()).add(new store_v2_js_1.V2IndexFile(pack, encoded));
452
510
  }
453
511
  handleFor(pack) {
@@ -466,9 +524,17 @@ class ObjectStore {
466
524
  return record;
467
525
  }
468
526
  /** Rebuild one object from a v2 pack and check it against its name. */
469
- async getV2(digest, entry) {
527
+ async getV2(digest, entry, depth = 0) {
470
528
  let raw;
471
529
  try {
530
+ /*
531
+ A delta stands on at most MAX_CHAIN others when written. Read back, a
532
+ damaged or crafted index could name a chain of any length, or a loop
533
+ (a delta of b, b a delta of a), which recursed until the stack ran
534
+ out. Refused past the limit, with a little room for older writers.
535
+ */
536
+ if (depth > store_v2_js_1.MAX_CHAIN + 4)
537
+ throw new Error("its chain of deltas is longer than any cbx writes");
472
538
  if (entry.kind === store_v2_js_1.KIND_SOLID) {
473
539
  const key = `${entry.pack}:${entry.offset}`;
474
540
  let block = this.blocks.get(key);
@@ -493,12 +559,12 @@ class ObjectStore {
493
559
  }
494
560
  else if (entry.kind === store_v2_js_1.KIND_WHOLE || entry.kind === store_v2_js_1.KIND_WHOLE_ZSTD) {
495
561
  const record = await this.readRecord(entry);
496
- raw = entry.kind === store_v2_js_1.KIND_WHOLE ? record : (0, store_v2_js_1.unzstd)(record);
562
+ raw = entry.kind === store_v2_js_1.KIND_WHOLE ? record : (0, store_v2_js_1.unzstd)(record, entry.raw);
497
563
  }
498
564
  else if (entry.kind === store_v2_js_1.KIND_DELTA || entry.kind === store_v2_js_1.KIND_DELTA_ZSTD) {
499
565
  const record = await this.readRecord(entry);
500
566
  const patch = entry.kind === store_v2_js_1.KIND_DELTA ? record : (0, store_v2_js_1.unzstd)(record);
501
- raw = Buffer.from((0, delta_js_1.applyDeltaPatch)(await this.get(entry.base), patch, LOCAL_DELTA_MAX_BYTES));
567
+ raw = Buffer.from((0, delta_js_1.applyDeltaPatch)(await this.getAt(entry.base, depth + 1), patch, LOCAL_DELTA_MAX_BYTES));
502
568
  }
503
569
  else {
504
570
  throw new Error("it is of a kind this cbx does not read");
@@ -526,16 +592,17 @@ class ObjectStore {
526
592
  const id = digestOf(body);
527
593
  const pack = node_path_1.default.join(this.packDirectory, `${id}.pack`);
528
594
  const idx = node_path_1.default.join(this.packDirectory, `${id}.idx`);
529
- await (0, promises_1.writeFile)(`${pack}.partial`, body);
530
- await (0, promises_1.rename)(`${pack}.partial`, pack);
531
- await (0, promises_1.writeFile)(`${idx}.partial`, JSON.stringify(index));
532
- await (0, promises_1.rename)(`${idx}.partial`, idx);
595
+ await (0, durable_js_1.writeDurably)(pack, body);
596
+ await (0, durable_js_1.writeDurably)(idx, JSON.stringify(index));
533
597
  const known = await this.packs();
534
598
  for (const [digest, [at, length]] of Object.entries(index)) {
535
599
  known.set(digest, { pack, offset: at, length });
536
600
  }
537
601
  }
538
602
  async get(digest) {
603
+ return this.getAt(digest, 0);
604
+ }
605
+ async getAt(digest, depth) {
539
606
  const waiting = this.pending.get(digest) ?? this.writing.get(digest);
540
607
  if (waiting)
541
608
  return (0, cbx_js_1.openChunkFrame)(waiting, digest);
@@ -545,7 +612,7 @@ class ObjectStore {
545
612
  const located = (await this.packs()).get(digest);
546
613
  const inV2 = !located ? this.v2Located.get(digest) : undefined;
547
614
  if (inV2)
548
- return this.getV2(digest, inV2);
615
+ return this.getV2(digest, inV2, depth);
549
616
  if (located) {
550
617
  const handle = await this.handleFor(located.pack);
551
618
  const frame = Buffer.alloc(located.length);
@@ -71,8 +71,13 @@ function compresses(raw) {
71
71
  const sample = raw.length > 131072 ? raw.subarray((raw.length >> 1) - 32768, (raw.length >> 1) + 32768) : raw;
72
72
  return zstdAt(sample, 1).length < sample.length * 0.92;
73
73
  }
74
- function unzstd(stored) {
75
- return (0, node_zlib_1.zstdDecompressSync)(stored);
74
+ /*
75
+ Never more than `limit` bytes out, whatever the record holds: a damaged or
76
+ crafted pack could otherwise inflate a few bytes into all of memory. The
77
+ default covers the largest solid block (LARGE_BLOCK_BYTES) with room.
78
+ */
79
+ function unzstd(stored, limit = 4 * exports.LARGE_BLOCK_BYTES) {
80
+ return (0, node_zlib_1.zstdDecompressSync)(stored, { maxOutputLength: Math.max(1, limit) });
76
81
  }
77
82
  const INDEX_MAGIC = Buffer.from("CBXI", "latin1");
78
83
  const INDEX_VERSION = 2;
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.ENGINE_SCAN_MIN_FILES = exports.ENGINE_MIN_BYTES = exports.ENGINE_MIN_FILES = void 0;
7
7
  exports.enginePath = enginePath;
8
+ exports.packageRoot = packageRoot;
8
9
  exports.engineProblem = engineProblem;
9
10
  exports.worthTheEngine = worthTheEngine;
10
11
  exports.engineStore = engineStore;
@@ -28,7 +29,8 @@ exports.engineQuickStatus = engineQuickStatus;
28
29
  *
29
30
  * Where it is looked for:
30
31
  * CBX_ENGINE=<path> that binary ("off" turns the engine off)
31
- * engine-bin/<platform>-<arch>/cbx-engine[.exe] in this package or a folder above it
32
+ * engine-bin/<platform>-<arch>/cbx-engine[.exe] in this package's own root
33
+ * (the nearest folder above this file holding a package.json), and nowhere else
32
34
  */
33
35
  const node_child_process_1 = require("node:child_process");
34
36
  const node_fs_1 = require("node:fs");
@@ -80,16 +82,44 @@ function enginePath() {
80
82
  if (chosen)
81
83
  return (located = (0, node_fs_1.existsSync)(chosen) ? chosen : null);
82
84
  /* CommonJS here; in an ES module build __dirname is not defined and only CBX_ENGINE applies. */
83
- let directory = typeof __dirname === "string" ? __dirname : null;
84
- const wanted = node_path_1.default.join("engine-bin", `${process.platform}-${process.arch}`, binaryName());
85
- for (let depth = 0; directory && depth < 8; depth += 1) {
86
- const candidate = node_path_1.default.join(directory, wanted);
87
- if ((0, node_fs_1.existsSync)(candidate))
88
- return (located = runnable(candidate) ? candidate : null);
85
+ const root = typeof __dirname === "string" ? packageRoot(__dirname) : null;
86
+ if (!root)
87
+ return (located = null);
88
+ const candidate = node_path_1.default.join(root, "engine-bin", `${process.platform}-${process.arch}`, binaryName());
89
+ return (located = (0, node_fs_1.existsSync)(candidate) && runnable(candidate) ? candidate : null);
90
+ }
91
+ /*
92
+ The folder this package was installed as: the nearest one above `from`
93
+ holding a package.json.
94
+
95
+ The engine used to be looked for in up to eight folders above this file. A
96
+ CLI installed inside a project (npx, node_modules) then found an
97
+ `engine-bin` the project itself carried, and a cloned repository could
98
+ have a program of its own run on every save (audit, 16 November 2026).
99
+ The package's own root is the only place an engine comes from.
100
+ */
101
+ function packageRoot(from) {
102
+ let directory = from;
103
+ for (let depth = 0; depth < 6; depth += 1) {
104
+ if ((0, node_fs_1.existsSync)(node_path_1.default.join(directory, "package.json")))
105
+ return directory;
89
106
  const parent = node_path_1.default.dirname(directory);
90
- directory = parent === directory ? null : parent;
107
+ if (parent === directory)
108
+ return null;
109
+ directory = parent;
91
110
  }
92
- return (located = null);
111
+ return null;
112
+ }
113
+ /*
114
+ How long the engine may go without saying anything before it is stopped
115
+ and the TypeScript path takes over. Silence, not total time: a large store
116
+ reports each file as it finishes, and a walk of a big folder answers in
117
+ seconds, so ten quiet minutes means it is stuck. CBX_ENGINE_TIMEOUT_MS
118
+ changes it.
119
+ */
120
+ function quietLimit() {
121
+ const chosen = Number(process.env.CBX_ENGINE_TIMEOUT_MS);
122
+ return Number.isFinite(chosen) && chosen > 0 ? chosen : 10 * 60 * 1000;
93
123
  }
94
124
  /** Why the engine is not being used, for diagnostics; null when it is available. */
95
125
  function engineProblem() {
@@ -144,12 +174,36 @@ function run(args, input, onLine, signal) {
144
174
  if (signal?.aborted)
145
175
  stop();
146
176
  signal?.addEventListener("abort", stop, { once: true });
147
- child.on("close", () => signal?.removeEventListener("abort", stop));
177
+ /*
178
+ A child that never answered held the save open for ever: nothing timed
179
+ it out. Stopped after a quiet spell; the caller then uses TypeScript.
180
+ */
181
+ let timedOut = false;
182
+ const limit = quietLimit();
183
+ let quiet = setTimeout(() => {
184
+ timedOut = true;
185
+ child.kill();
186
+ }, limit);
187
+ const heard = () => {
188
+ clearTimeout(quiet);
189
+ quiet = setTimeout(() => {
190
+ timedOut = true;
191
+ child.kill();
192
+ }, limit);
193
+ };
194
+ child.on("close", () => {
195
+ clearTimeout(quiet);
196
+ signal?.removeEventListener("abort", stop);
197
+ });
148
198
  const out = [];
149
199
  let err = "";
150
200
  let partial = "";
151
- child.stdout.on("data", (data) => out.push(data));
201
+ child.stdout.on("data", (data) => {
202
+ heard();
203
+ out.push(data);
204
+ });
152
205
  child.stderr.on("data", (data) => {
206
+ heard();
153
207
  const text = partial + data.toString("utf8");
154
208
  const lines = text.split("\n");
155
209
  partial = lines.pop() ?? "";
@@ -161,7 +215,9 @@ function run(args, input, onLine, signal) {
161
215
  }
162
216
  });
163
217
  child.on("error", (error) => resolve({ stdout: "", stderr: String(error), code: -1 }));
164
- child.on("close", (code) => resolve({ stdout: Buffer.concat(out).toString("utf8"), stderr: err + partial, code }));
218
+ child.on("close", (code) => resolve(timedOut
219
+ ? { stdout: "", stderr: `the engine said nothing for ${Math.round(limit / 1000)} s and was stopped`, code: -1 }
220
+ : { stdout: Buffer.concat(out).toString("utf8"), stderr: err + partial, code }));
165
221
  child.stdin.on("error", () => {
166
222
  /* The engine exited before reading; its exit code says why. */
167
223
  });