vue-go-tsc 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/vue-go-tsc CHANGED
@@ -1,17 +1,93 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { spawnSync } = require('child_process');
3
+ const { spawn } = require('child_process');
4
+ const fs = require('fs');
4
5
  const { join } = require('path');
5
6
  const os = require('os');
6
7
 
7
8
  const GiB = 1024 ** 3;
8
9
 
9
- // Fraction of total RAM used as the default soft Go heap ceiling. Half of RAM
10
- // leaves ample headroom for the OS, Node, and any concurrent CI jobs on the
11
- // same runner, and is reproducible across runs (unlike instantaneous free RAM).
10
+ // Fraction of the CPU cores a lone tsgo run may use. The Go runtime defaults
11
+ // GOMAXPROCS to every core, and tsgo parses/binds with one goroutine per file,
12
+ // so an unbounded run pins the whole machine at 100% CPU. Half of the cores
13
+ // keeps a lone typecheck fast while leaving the machine responsive.
14
+ const DEFAULT_CPU_FRACTION = 0.5;
15
+
16
+ // Fraction of total RAM used as the soft Go heap ceiling of a lone run. Half
17
+ // of RAM leaves ample headroom for the OS, Node, and other jobs.
12
18
  const DEFAULT_MEM_FRACTION = 0.5;
13
19
 
14
- // Compute a soft Go heap ceiling (in bytes) for tsgo based on total RAM.
20
+ // Fraction of total RAM shared by all concurrent runs. GOMEMLIMIT is
21
+ // per-process: without sharing, N concurrent runs would each claim 50% of RAM,
22
+ // overcommit it, and spend their time in the GC as the machine fills up.
23
+ const SHARED_MEM_FRACTION = 0.75;
24
+
25
+ // Fraction of the currently available RAM a run may claim. The rest is left as
26
+ // headroom for whatever else is running and may still grow.
27
+ const AVAILABLE_MEM_FRACTION = 0.8;
28
+
29
+ // A busy machine never squeezes a run below this fraction of the cores: the
30
+ // idle measurement is a short snapshot, and a momentary spike elsewhere must
31
+ // not cripple a typecheck for its whole duration. The kernel scheduler shares
32
+ // the cores fairly beyond that.
33
+ const MIN_CPU_FRACTION = 0.125;
34
+
35
+ // How long the launcher samples CPU activity before starting tsgo.
36
+ const CPU_SAMPLE_MS = 200;
37
+
38
+ // Never set a heap ceiling below this: a limit under a project's live heap
39
+ // makes the Go GC run continuously instead of making progress.
40
+ const MIN_MEM_LIMIT = 1 * GiB;
41
+
42
+ // Registry entries older than this are treated as stale even if their PID is
43
+ // alive again (PID reuse after a crash that skipped cleanup).
44
+ const STALE_ENTRY_MS = 24 * 60 * 60 * 1000;
45
+
46
+ const REGISTRY_DIR = join(os.tmpdir(), 'vue-go-tsc-instances');
47
+
48
+ // Compute GOMAXPROCS for one of `instances` concurrent runs on a machine with
49
+ // `cpus` cores of which `idleCpus` are currently idle.
50
+ //
51
+ // The run takes the smallest of: half of the cores, its fair share when
52
+ // several runs are active, and the cores other work leaves idle. It is never
53
+ // squeezed below MIN_CPU_FRACTION of the cores (and at least one core).
54
+ // `idleCpus` is optional: when unknown, only the first two bounds apply.
55
+ //
56
+ // Returns null when the core count is unknown (leave Go's default).
57
+ function computeGoMaxProcs(cpus, instances = 1, idleCpus) {
58
+ if (!Number.isFinite(cpus) || cpus <= 0) {
59
+ return null;
60
+ }
61
+ const n = Math.max(1, Math.floor(instances) || 1);
62
+ const cap = Math.max(1, Math.min(Math.floor(cpus * DEFAULT_CPU_FRACTION), Math.floor(cpus / n)));
63
+ if (!Number.isFinite(idleCpus) || idleCpus < 0) {
64
+ return cap;
65
+ }
66
+ const floor = Math.min(cap, Math.max(1, Math.floor(cpus * MIN_CPU_FRACTION)));
67
+ return Math.max(floor, Math.min(cap, Math.floor(idleCpus)));
68
+ }
69
+
70
+ // Number of idle cores between two `os.cpus()` snapshots, scaled to the
71
+ // `cpus` usable by this process. Returns undefined when nothing was measured.
72
+ function measureIdleCpus(before, after, cpus) {
73
+ let idle = 0;
74
+ let total = 0;
75
+ for (let i = 0; i < Math.min(before.length, after.length); i++) {
76
+ const a = before[i].times;
77
+ const b = after[i].times;
78
+ const idleDelta = b.idle - a.idle;
79
+ const totalDelta = b.user + b.nice + b.sys + b.idle + b.irq - (a.user + a.nice + a.sys + a.idle + a.irq);
80
+ idle += Math.max(0, idleDelta);
81
+ total += Math.max(0, totalDelta);
82
+ }
83
+ if (total <= 0) {
84
+ return undefined;
85
+ }
86
+ return (idle / total) * cpus;
87
+ }
88
+
89
+ // Compute a soft Go heap ceiling (in bytes) for one of `instances` concurrent
90
+ // runs based on total RAM.
15
91
  //
16
92
  // tsgo is the typescript-go native binary; its Go runtime defaults to GOGC=100,
17
93
  // which lets the heap roughly double before the GC runs. On a large Nuxt
@@ -22,20 +98,39 @@ const DEFAULT_MEM_FRACTION = 0.5;
22
98
  // instead of a hard kill, and it can be raised via the GOMEMLIMIT env var when
23
99
  // a project's live heap genuinely needs more.
24
100
  //
101
+ // A lone run gets at most half of RAM; concurrent runs split a shared pool so
102
+ // their combined ceilings stay below physical RAM. The run also never claims
103
+ // more than AVAILABLE_MEM_FRACTION of the RAM currently available
104
+ // (`availableBytes`, optional), so memory held by other programs is left
105
+ // alone. The fair-share bound still matters on top of that: other runs that
106
+ // just started have not grown their heap yet.
107
+ //
25
108
  // Returns null when total RAM is unknown/implausible (leave Go's default).
26
- function computeGoMemLimit(totalBytes) {
109
+ function computeGoMemLimit(totalBytes, instances = 1, availableBytes) {
27
110
  if (!Number.isFinite(totalBytes) || totalBytes <= 0) {
28
111
  return null;
29
112
  }
30
- return Math.floor(totalBytes * DEFAULT_MEM_FRACTION);
113
+ const n = Math.max(1, Math.floor(instances) || 1);
114
+ let share = Math.min(totalBytes * DEFAULT_MEM_FRACTION, (totalBytes * SHARED_MEM_FRACTION) / n);
115
+ if (Number.isFinite(availableBytes) && availableBytes >= 0) {
116
+ share = Math.min(share, availableBytes * AVAILABLE_MEM_FRACTION);
117
+ }
118
+ return Math.floor(Math.max(Math.min(MIN_MEM_LIMIT, totalBytes * DEFAULT_MEM_FRACTION), share));
31
119
  }
32
120
 
33
- // Return a copy of `env` with GOMEMLIMIT defaulted from total RAM. An explicit
34
- // GOMEMLIMIT is always respected (never overridden).
35
- function resolveEnv(env, totalBytes) {
121
+ // Return a copy of `env` with GOMAXPROCS and GOMEMLIMIT defaulted from the
122
+ // machine resources, what is currently free, and the number of concurrent
123
+ // runs. Explicit values are always respected (never overridden).
124
+ function resolveEnv(env, { cpus, totalMem, instances = 1, idleCpus, availableMem }) {
36
125
  const out = { ...env };
126
+ if (!out.GOMAXPROCS) {
127
+ const procs = computeGoMaxProcs(cpus, instances, idleCpus);
128
+ if (procs) {
129
+ out.GOMAXPROCS = String(procs);
130
+ }
131
+ }
37
132
  if (!out.GOMEMLIMIT) {
38
- const limit = computeGoMemLimit(totalBytes);
133
+ const limit = computeGoMemLimit(totalMem, instances, availableMem);
39
134
  if (limit) {
40
135
  // A bare integer is interpreted by the Go runtime as a byte count.
41
136
  out.GOMEMLIMIT = String(limit);
@@ -44,20 +139,166 @@ function resolveEnv(env, totalBytes) {
44
139
  return out;
45
140
  }
46
141
 
47
- if (require.main === module) {
142
+ function isProcessAlive(pid) {
143
+ try {
144
+ process.kill(pid, 0);
145
+ return true;
146
+ } catch (err) {
147
+ // EPERM: the process exists but belongs to another user.
148
+ return err.code === 'EPERM';
149
+ }
150
+ }
151
+
152
+ // Register this run in the shared instance registry and return the number of
153
+ // live runs (including this one) plus a function that unregisters it.
154
+ //
155
+ // Each run owns one `<pid>` file in `dir`. Entries whose process is gone (a
156
+ // run killed before it could clean up) are pruned on the way. Registering
157
+ // before counting means two runs starting at the same moment see each other.
158
+ // Any filesystem failure degrades to "alone" rather than blocking the check.
159
+ function registerInstance(dir = REGISTRY_DIR, pid = process.pid, now = Date.now()) {
160
+ const self = join(dir, String(pid));
161
+ try {
162
+ fs.mkdirSync(dir, { recursive: true });
163
+ fs.writeFileSync(self, String(now));
164
+ } catch {
165
+ return { instances: 1, unregister: () => {} };
166
+ }
167
+
168
+ let instances = 1;
169
+ try {
170
+ for (const name of fs.readdirSync(dir)) {
171
+ const other = Number(name);
172
+ if (!Number.isInteger(other) || other <= 0 || other === pid) {
173
+ continue;
174
+ }
175
+ const entry = join(dir, name);
176
+ let startedAt = NaN;
177
+ try {
178
+ startedAt = Number(fs.readFileSync(entry, 'utf8'));
179
+ } catch {
180
+ continue;
181
+ }
182
+ if (isProcessAlive(other) && now - startedAt < STALE_ENTRY_MS) {
183
+ instances++;
184
+ } else {
185
+ try {
186
+ fs.unlinkSync(entry);
187
+ } catch {}
188
+ }
189
+ }
190
+ } catch {}
191
+
192
+ return {
193
+ instances,
194
+ unregister: () => {
195
+ try {
196
+ fs.unlinkSync(self);
197
+ } catch {}
198
+ },
199
+ };
200
+ }
201
+
202
+ // Usable core count: honors CPU affinity (taskset, container cpusets).
203
+ function availableCpus() {
204
+ return typeof os.availableParallelism === 'function' ? os.availableParallelism() : os.cpus().length;
205
+ }
206
+
207
+ // Usable RAM: honors a cgroup memory limit (containers) when it is tighter
208
+ // than physical RAM.
209
+ function totalMemory() {
210
+ const total = os.totalmem();
211
+ const constrained = typeof process.constrainedMemory === 'function' ? process.constrainedMemory() : 0;
212
+ return constrained > 0 && constrained < total ? constrained : total;
213
+ }
214
+
215
+ // RAM currently available to this process (MemAvailable on Linux, bounded by
216
+ // the cgroup limit when there is one).
217
+ function freeMemory() {
218
+ return typeof process.availableMemory === 'function' ? process.availableMemory() : os.freemem();
219
+ }
220
+
221
+ // Idle cores right now, sampled over CPU_SAMPLE_MS.
222
+ function sampleIdleCpus(cpus) {
223
+ const before = os.cpus();
224
+ return new Promise((resolve) => {
225
+ setTimeout(() => resolve(measureIdleCpus(before, os.cpus(), cpus)), CPU_SAMPLE_MS);
226
+ });
227
+ }
228
+
229
+ async function main() {
48
230
  const BINARY_NAME = process.platform === 'win32' ? 'tsgo.exe' : 'tsgo';
49
231
  const BIN_PATH = join(__dirname, BINARY_NAME);
50
232
 
51
- const env = resolveEnv(process.env, os.totalmem());
233
+ const { instances, unregister } = registerInstance();
234
+ process.on('exit', unregister);
235
+
236
+ const cpus = availableCpus();
237
+ // Sampling costs CPU_SAMPLE_MS of startup; skip it when it cannot matter.
238
+ const idleCpus = process.env.GOMAXPROCS ? undefined : await sampleIdleCpus(cpus);
239
+
240
+ const env = resolveEnv(process.env, {
241
+ cpus,
242
+ totalMem: totalMemory(),
243
+ instances,
244
+ idleCpus,
245
+ availableMem: freeMemory(),
246
+ });
52
247
 
53
248
  // Forward all arguments to the binary
54
- const result = spawnSync(BIN_PATH, process.argv.slice(2), {
249
+ const child = spawn(BIN_PATH, process.argv.slice(2), {
55
250
  stdio: 'inherit',
56
251
  shell: false,
57
252
  env,
58
253
  });
59
254
 
60
- process.exit(result.status || 0);
255
+ // Keep the launcher alive until tsgo exits so the registry entry stays
256
+ // accurate; tsgo receives terminal signals directly from the process group,
257
+ // and signals sent to the launcher alone are forwarded.
258
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
259
+ process.on(signal, () => {
260
+ child.kill(signal);
261
+ });
262
+ }
263
+
264
+ child.on('error', (err) => {
265
+ console.error(`vue-go-tsc: failed to start ${BIN_PATH}: ${err.message}`);
266
+ if (['ENOENT', 'EACCES', 'ENOEXEC'].includes(err.code)) {
267
+ // Missing, non-executable or truncated binary (e.g. an interrupted
268
+ // install, or a package manager that skipped the postinstall script).
269
+ console.error(
270
+ `vue-go-tsc: the tsgo binary is missing or broken; reinstall it with:\n` +
271
+ ` node ${join(__dirname, '..', 'install.js')}`
272
+ );
273
+ }
274
+ process.exit(1);
275
+ });
276
+
277
+ child.on('exit', (code, signal) => {
278
+ if (signal) {
279
+ // Report a killed tsgo (e.g. OOM killer) as a failure, not a success.
280
+ const signum = os.constants.signals[signal];
281
+ process.exit(signum ? 128 + signum : 1);
282
+ }
283
+ process.exit(code ?? 1);
284
+ });
285
+ }
286
+
287
+ if (require.main === module) {
288
+ main();
61
289
  }
62
290
 
63
- module.exports = { computeGoMemLimit, resolveEnv, GiB, DEFAULT_MEM_FRACTION };
291
+ module.exports = {
292
+ computeGoMaxProcs,
293
+ computeGoMemLimit,
294
+ measureIdleCpus,
295
+ resolveEnv,
296
+ registerInstance,
297
+ GiB,
298
+ DEFAULT_CPU_FRACTION,
299
+ DEFAULT_MEM_FRACTION,
300
+ SHARED_MEM_FRACTION,
301
+ MIN_MEM_LIMIT,
302
+ AVAILABLE_MEM_FRACTION,
303
+ MIN_CPU_FRACTION,
304
+ };
@@ -1,39 +1,188 @@
1
1
  // Run with: node --test cli/bin/vue-go-tsc.test.js
2
2
  const { test } = require('node:test');
3
3
  const assert = require('node:assert');
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
4
7
 
5
- const { computeGoMemLimit, resolveEnv, GiB, DEFAULT_MEM_FRACTION } = require('./vue-go-tsc');
8
+ const {
9
+ computeGoMaxProcs,
10
+ computeGoMemLimit,
11
+ measureIdleCpus,
12
+ resolveEnv,
13
+ registerInstance,
14
+ GiB,
15
+ DEFAULT_MEM_FRACTION,
16
+ MIN_MEM_LIMIT,
17
+ AVAILABLE_MEM_FRACTION,
18
+ } = require('./vue-go-tsc');
6
19
 
7
- test('computeGoMemLimit defaults to half of total RAM', () => {
20
+ const machine = { cpus: 16, totalMem: 8 * GiB };
21
+
22
+ test('computeGoMaxProcs defaults to half of the cores when alone', () => {
23
+ assert.strictEqual(computeGoMaxProcs(16), 8);
24
+ assert.strictEqual(computeGoMaxProcs(16, 1), 8);
25
+ assert.strictEqual(computeGoMaxProcs(4), 2);
26
+ });
27
+
28
+ test('computeGoMaxProcs shares the cores between concurrent runs', () => {
29
+ assert.strictEqual(computeGoMaxProcs(16, 2), 8);
30
+ assert.strictEqual(computeGoMaxProcs(16, 3), 5);
31
+ assert.strictEqual(computeGoMaxProcs(16, 4), 4);
32
+ assert.strictEqual(computeGoMaxProcs(16, 8), 2);
33
+ });
34
+
35
+ test('computeGoMaxProcs never goes below one core', () => {
36
+ assert.strictEqual(computeGoMaxProcs(1), 1);
37
+ assert.strictEqual(computeGoMaxProcs(2, 5), 1);
38
+ assert.strictEqual(computeGoMaxProcs(16, 100), 1);
39
+ });
40
+
41
+ test('computeGoMaxProcs returns null for unknown core counts', () => {
42
+ assert.strictEqual(computeGoMaxProcs(0), null);
43
+ assert.strictEqual(computeGoMaxProcs(NaN), null);
44
+ });
45
+
46
+ test('computeGoMaxProcs takes only the idle cores when the machine is busy', () => {
47
+ assert.strictEqual(computeGoMaxProcs(16, 1, 16), 8, 'an idle machine still caps at half');
48
+ assert.strictEqual(computeGoMaxProcs(16, 1, 5.7), 5);
49
+ assert.strictEqual(computeGoMaxProcs(16, 2, 12), 8);
50
+ assert.strictEqual(computeGoMaxProcs(16, 3, 12), 5, 'fair share still applies');
51
+ });
52
+
53
+ test('computeGoMaxProcs keeps a minimum share on a saturated machine', () => {
54
+ assert.strictEqual(computeGoMaxProcs(16, 1, 0), 2);
55
+ assert.strictEqual(computeGoMaxProcs(4, 1, 0), 1);
56
+ // The floor never exceeds the fair share.
57
+ assert.strictEqual(computeGoMaxProcs(16, 16, 0), 1);
58
+ });
59
+
60
+ function cpuTimes(idle, busy) {
61
+ return { times: { user: busy, nice: 0, sys: 0, idle, irq: 0 } };
62
+ }
63
+
64
+ test('measureIdleCpus converts the idle time delta into idle cores', () => {
65
+ const before = [cpuTimes(0, 0), cpuTimes(0, 0)];
66
+ // Core 0 fully idle, core 1 fully busy: one of two cores idle.
67
+ const after = [cpuTimes(200, 0), cpuTimes(0, 200)];
68
+ assert.strictEqual(measureIdleCpus(before, after, 2), 1);
69
+ // Scaled to the cores usable by the process (CPU affinity).
70
+ assert.strictEqual(measureIdleCpus(before, after, 8), 4);
71
+ });
72
+
73
+ test('measureIdleCpus returns undefined when nothing was measured', () => {
74
+ const same = [cpuTimes(10, 10)];
75
+ assert.strictEqual(measureIdleCpus(same, same, 1), undefined);
76
+ assert.strictEqual(measureIdleCpus([], [], 4), undefined);
77
+ });
78
+
79
+ test('computeGoMemLimit defaults to half of total RAM when alone', () => {
8
80
  const total = 8 * GiB;
9
81
  const limit = computeGoMemLimit(total);
10
82
  assert.strictEqual(limit, Math.floor(total * DEFAULT_MEM_FRACTION)); // 4GiB
11
83
  assert.ok(limit < total, 'limit must stay below physical RAM');
12
- });
13
-
14
- test('computeGoMemLimit scales with RAM', () => {
15
84
  assert.strictEqual(computeGoMemLimit(16 * GiB), 8 * GiB);
16
85
  assert.strictEqual(computeGoMemLimit(4 * GiB), 2 * GiB);
17
86
  });
18
87
 
88
+ test('computeGoMemLimit keeps concurrent runs below physical RAM combined', () => {
89
+ const total = 16 * GiB;
90
+ for (const n of [2, 3, 4, 6]) {
91
+ const limit = computeGoMemLimit(total, n);
92
+ assert.ok(limit * n < total, `${n} runs must not overcommit RAM`);
93
+ assert.ok(limit <= computeGoMemLimit(total, n - 1), 'more runs never raise the limit');
94
+ }
95
+ });
96
+
97
+ test('computeGoMemLimit never drops below the minimum ceiling', () => {
98
+ assert.strictEqual(computeGoMemLimit(8 * GiB, 100), MIN_MEM_LIMIT);
99
+ // On a tiny machine the floor itself is capped at half of RAM.
100
+ assert.strictEqual(computeGoMemLimit(1 * GiB, 10), Math.floor(0.5 * GiB));
101
+ });
102
+
103
+ test('computeGoMemLimit leaves memory used by other programs alone', () => {
104
+ const total = 16 * GiB;
105
+ assert.strictEqual(computeGoMemLimit(total, 1, 16 * GiB), 8 * GiB, 'a free machine still caps at half');
106
+ assert.strictEqual(computeGoMemLimit(total, 1, 5 * GiB), Math.floor(5 * GiB * AVAILABLE_MEM_FRACTION));
107
+ assert.strictEqual(computeGoMemLimit(total, 1, 0), MIN_MEM_LIMIT, 'never below the minimum ceiling');
108
+ });
109
+
19
110
  test('computeGoMemLimit returns null for unknown/implausible RAM', () => {
20
111
  assert.strictEqual(computeGoMemLimit(0), null);
21
112
  assert.strictEqual(computeGoMemLimit(-1), null);
22
113
  assert.strictEqual(computeGoMemLimit(NaN), null);
23
114
  });
24
115
 
25
- test('resolveEnv defaults GOMEMLIMIT (in bytes) when unset', () => {
26
- const env = resolveEnv({ PATH: '/usr/bin' }, 8 * GiB);
116
+ test('resolveEnv defaults GOMAXPROCS and GOMEMLIMIT (in bytes) when unset', () => {
117
+ const env = resolveEnv({ PATH: '/usr/bin' }, machine);
118
+ assert.strictEqual(env.GOMAXPROCS, '8');
27
119
  assert.strictEqual(env.GOMEMLIMIT, String(4 * GiB));
28
120
  assert.strictEqual(env.PATH, '/usr/bin', 'existing env is preserved');
29
121
  });
30
122
 
31
- test('resolveEnv never overrides an explicit GOMEMLIMIT', () => {
32
- const env = resolveEnv({ GOMEMLIMIT: '6GiB' }, 8 * GiB);
123
+ test('resolveEnv scales down with concurrent runs', () => {
124
+ const env = resolveEnv({}, { ...machine, instances: 4 });
125
+ assert.strictEqual(env.GOMAXPROCS, '4');
126
+ assert.strictEqual(env.GOMEMLIMIT, String(computeGoMemLimit(8 * GiB, 4)));
127
+ });
128
+
129
+ test('resolveEnv adapts to the free CPU and RAM', () => {
130
+ const env = resolveEnv({}, { ...machine, idleCpus: 3.2, availableMem: 2 * GiB });
131
+ assert.strictEqual(env.GOMAXPROCS, '3');
132
+ assert.strictEqual(env.GOMEMLIMIT, String(Math.floor(2 * GiB * AVAILABLE_MEM_FRACTION)));
133
+ });
134
+
135
+ test('resolveEnv never overrides explicit GOMAXPROCS / GOMEMLIMIT', () => {
136
+ const env = resolveEnv({ GOMAXPROCS: '12', GOMEMLIMIT: '6GiB' }, { ...machine, instances: 4 });
137
+ assert.strictEqual(env.GOMAXPROCS, '12');
33
138
  assert.strictEqual(env.GOMEMLIMIT, '6GiB');
34
139
  });
35
140
 
36
- test('resolveEnv leaves GOMEMLIMIT unset when RAM is unknown', () => {
37
- const env = resolveEnv({}, 0);
141
+ test('resolveEnv leaves values unset when resources are unknown', () => {
142
+ const env = resolveEnv({}, { cpus: 0, totalMem: 0 });
143
+ assert.strictEqual('GOMAXPROCS' in env, false);
38
144
  assert.strictEqual('GOMEMLIMIT' in env, false);
39
145
  });
146
+
147
+ function tempRegistry() {
148
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'vue-go-tsc-test-'));
149
+ }
150
+
151
+ test('registerInstance counts itself when alone and cleans up', () => {
152
+ const dir = tempRegistry();
153
+ const { instances, unregister } = registerInstance(dir);
154
+ assert.strictEqual(instances, 1);
155
+ assert.deepStrictEqual(fs.readdirSync(dir), [String(process.pid)]);
156
+ unregister();
157
+ assert.deepStrictEqual(fs.readdirSync(dir), []);
158
+ });
159
+
160
+ test('registerInstance counts other live runs', () => {
161
+ const dir = tempRegistry();
162
+ // The parent process is alive for the duration of the test.
163
+ fs.writeFileSync(path.join(dir, String(process.ppid)), String(Date.now()));
164
+ const { instances, unregister } = registerInstance(dir);
165
+ assert.strictEqual(instances, 2);
166
+ unregister();
167
+ });
168
+
169
+ test('registerInstance prunes dead and stale entries', () => {
170
+ const dir = tempRegistry();
171
+ const now = Date.now();
172
+ // A PID that is not running, and a live PID whose entry is days old.
173
+ fs.writeFileSync(path.join(dir, '2147483646'), String(now));
174
+ fs.writeFileSync(path.join(dir, String(process.ppid)), String(now - 3 * 24 * 60 * 60 * 1000));
175
+ fs.writeFileSync(path.join(dir, 'not-a-pid'), '');
176
+ const { instances, unregister } = registerInstance(dir, process.pid, now);
177
+ assert.strictEqual(instances, 1);
178
+ assert.deepStrictEqual(fs.readdirSync(dir).sort(), ['not-a-pid', String(process.pid)].sort());
179
+ unregister();
180
+ });
181
+
182
+ test('registerInstance degrades to alone when the registry is unusable', () => {
183
+ const file = path.join(tempRegistry(), 'file');
184
+ fs.writeFileSync(file, '');
185
+ const { instances, unregister } = registerInstance(path.join(file, 'sub'));
186
+ assert.strictEqual(instances, 1);
187
+ unregister();
188
+ });
package/install.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- const { existsSync, mkdirSync, chmodSync, copyFileSync } = require('fs');
3
+ const { existsSync, mkdirSync, chmodSync, copyFileSync, renameSync, rmSync, readdirSync, createWriteStream } = require('fs');
4
4
  const { join } = require('path');
5
5
  const os = require('os');
6
+ const http = require('http');
6
7
  const https = require('https');
7
- const { createWriteStream } = require('fs');
8
+ const { spawnSync } = require('child_process');
8
9
 
9
10
  const PACKAGE_VERSION = require('./package.json').version;
10
11
  const BINARY_NAME = process.platform === 'win32' ? 'tsgo.exe' : 'tsgo';
@@ -17,6 +18,8 @@ const BIN_PATH = join(BIN_DIR, BINARY_NAME);
17
18
  const CACHE_ROOT = process.env.VUE_GO_TSC_CACHE_DIR || join(os.homedir(), '.cache', 'vue-go-tsc');
18
19
  const CACHE_DIR = join(CACHE_ROOT, `v${PACKAGE_VERSION}`);
19
20
 
21
+ const MAX_REDIRECTS = 10;
22
+
20
23
  // Platform mapping for GitHub releases
21
24
  const PLATFORM_MAP = {
22
25
  'darwin-x64': 'tsgo-darwin-amd64',
@@ -41,46 +44,151 @@ function getPlatformBinary() {
41
44
  return PLATFORM_MAP[key];
42
45
  }
43
46
 
44
- function download(url, dest) {
47
+ // A file next to `dest` that is unique to this process, so concurrent
48
+ // installs (parallel CI jobs, pnpm workspaces) never write the same file.
49
+ function tempPathFor(dest) {
50
+ return `${dest}.${process.pid}.tmp`;
51
+ }
52
+
53
+ // Temporary files being written by this process, removed if it is killed.
54
+ const pendingTempFiles = new Set();
55
+
56
+ function cleanupPendingTempFiles() {
57
+ for (const tmp of pendingTempFiles) {
58
+ rmSync(tmp, { force: true });
59
+ }
60
+ }
61
+
62
+ // Remove temporary binaries left in `dir` by an install that was killed
63
+ // before it could clean up. Only for directories no other install writes to.
64
+ function removeStaleTempFiles(dir, name) {
65
+ try {
66
+ for (const entry of readdirSync(dir)) {
67
+ if (entry.startsWith(`${name}.`) && entry.endsWith('.tmp')) {
68
+ rmSync(join(dir, entry), { force: true });
69
+ }
70
+ }
71
+ } catch {}
72
+ }
73
+
74
+ // Download `url` to `dest`.
75
+ //
76
+ // The body is streamed into a temporary file and only renamed onto `dest` once
77
+ // it is complete: an interrupted install (Ctrl+C, a sibling postinstall
78
+ // failing, a network cut) must never leave a truncated binary behind, since a
79
+ // present binary is what later installs trust. A body shorter than the
80
+ // announced Content-Length is rejected for the same reason.
81
+ function download(url, dest, redirects = 0) {
45
82
  return new Promise((resolve, reject) => {
46
- const file = createWriteStream(dest);
47
- https.get(url, (response) => {
48
- if (response.statusCode === 302 || response.statusCode === 301) {
49
- // Follow redirect
50
- download(response.headers.location, dest).then(resolve).catch(reject);
83
+ const client = url.startsWith('http:') ? http : https;
84
+ const request = client.get(url, (response) => {
85
+ const { statusCode } = response;
86
+ if ([301, 302, 303, 307, 308].includes(statusCode) && response.headers.location) {
87
+ response.resume();
88
+ if (redirects >= MAX_REDIRECTS) {
89
+ reject(new Error(`Download failed: too many redirects (${url})`));
90
+ return;
91
+ }
92
+ const next = new URL(response.headers.location, url).toString();
93
+ download(next, dest, redirects + 1).then(resolve, reject);
51
94
  return;
52
95
  }
53
96
 
54
- if (response.statusCode !== 200) {
55
- reject(new Error(`Download failed: ${response.statusCode} ${response.statusMessage}`));
97
+ if (statusCode !== 200) {
98
+ response.resume();
99
+ reject(new Error(`Download failed: ${statusCode} ${response.statusMessage}`));
56
100
  return;
57
101
  }
58
102
 
59
- response.pipe(file);
103
+ const expected = Number(response.headers['content-length']);
104
+ const tmp = tempPathFor(dest);
105
+ pendingTempFiles.add(tmp);
106
+ const file = createWriteStream(tmp);
107
+ let received = 0;
108
+ let failed = false;
109
+
110
+ const fail = (err) => {
111
+ if (failed) return;
112
+ failed = true;
113
+ response.destroy();
114
+ file.destroy();
115
+ rmSync(tmp, { force: true });
116
+ pendingTempFiles.delete(tmp);
117
+ reject(err);
118
+ };
119
+
120
+ response.on('data', (chunk) => {
121
+ received += chunk.length;
122
+ });
123
+ response.on('aborted', () => fail(new Error('Download failed: connection closed early')));
124
+ response.on('error', fail);
125
+ file.on('error', fail);
60
126
  file.on('finish', () => {
61
- file.close();
62
- resolve();
127
+ if (failed) return;
128
+ if (Number.isFinite(expected) && expected > 0 && received !== expected) {
129
+ fail(new Error(`Download failed: received ${received} of ${expected} bytes`));
130
+ return;
131
+ }
132
+ file.close((err) => {
133
+ if (err) {
134
+ fail(err);
135
+ return;
136
+ }
137
+ try {
138
+ renameSync(tmp, dest);
139
+ pendingTempFiles.delete(tmp);
140
+ resolve();
141
+ } catch (renameErr) {
142
+ fail(renameErr);
143
+ }
144
+ });
63
145
  });
64
- }).on('error', (err) => {
65
- reject(err);
146
+
147
+ response.pipe(file);
66
148
  });
149
+ request.on('error', reject);
67
150
  });
68
151
  }
69
152
 
70
- function finalizeBinary() {
153
+ // Copy `src` onto `dest` through a temporary file, so a reader never sees a
154
+ // partially written binary (the shared cache is read by concurrent installs).
155
+ function copyAtomic(src, dest) {
156
+ const tmp = tempPathFor(dest);
157
+ try {
158
+ copyFileSync(src, tmp);
159
+ renameSync(tmp, dest);
160
+ } finally {
161
+ rmSync(tmp, { force: true });
162
+ }
163
+ }
164
+
165
+ function makeExecutable(path) {
71
166
  // Make executable (Unix-like systems)
72
167
  if (process.platform !== 'win32') {
73
- chmodSync(BIN_PATH, 0o755);
168
+ chmodSync(path, 0o755);
74
169
  }
75
170
  }
76
171
 
172
+ // A binary is usable when it exists and actually runs: this rejects a
173
+ // truncated or corrupted file (e.g. left by an install from an older version
174
+ // of this script) instead of trusting it forever.
175
+ function isUsableBinary(path) {
176
+ if (!existsSync(path)) {
177
+ return false;
178
+ }
179
+ const result = spawnSync(path, ['--version'], { stdio: 'ignore', timeout: 30000 });
180
+ return !result.error && result.status === 0;
181
+ }
182
+
77
183
  async function install() {
78
184
  try {
79
- // Check if binary already exists (useful for development)
80
- if (existsSync(BIN_PATH)) {
185
+ // Keep a working binary (useful for development and reinstalls).
186
+ if (isUsableBinary(BIN_PATH)) {
81
187
  console.log('✓ vue-go-tsc binary already exists');
82
188
  return;
83
189
  }
190
+ rmSync(BIN_PATH, { force: true });
191
+ removeStaleTempFiles(BIN_DIR, BINARY_NAME);
84
192
 
85
193
  if (!existsSync(BIN_DIR)) {
86
194
  mkdirSync(BIN_DIR, { recursive: true });
@@ -89,14 +197,18 @@ async function install() {
89
197
  const platformBinary = getPlatformBinary();
90
198
  const cachedBinary = join(CACHE_DIR, platformBinary);
91
199
 
92
- // 1) Serve from the shared cache when present (best-effort — a cache miss or
93
- // error just falls through to the download below).
200
+ // 1) Serve from the shared cache when present (best-effort — a cache miss,
201
+ // an error or a corrupted entry just falls through to the download).
94
202
  try {
95
203
  if (existsSync(cachedBinary)) {
96
- copyFileSync(cachedBinary, BIN_PATH);
97
- finalizeBinary();
98
- console.log(`✓ vue-go-tsc restored from cache (${cachedBinary})`);
99
- return;
204
+ copyAtomic(cachedBinary, BIN_PATH);
205
+ makeExecutable(BIN_PATH);
206
+ if (isUsableBinary(BIN_PATH)) {
207
+ console.log(`✓ vue-go-tsc restored from cache (${cachedBinary})`);
208
+ return;
209
+ }
210
+ rmSync(BIN_PATH, { force: true });
211
+ rmSync(cachedBinary, { force: true });
100
212
  }
101
213
  } catch {
102
214
  // ignore — download is the source of truth
@@ -107,14 +219,14 @@ async function install() {
107
219
  console.log('Installing vue-go-tsc...');
108
220
  console.log(`Downloading from: ${downloadUrl}`);
109
221
  await download(downloadUrl, BIN_PATH);
110
- finalizeBinary();
222
+ makeExecutable(BIN_PATH);
111
223
 
112
224
  // 3) Populate the cache for next time (never fail the install on this).
113
225
  try {
114
226
  if (!existsSync(CACHE_DIR)) {
115
227
  mkdirSync(CACHE_DIR, { recursive: true });
116
228
  }
117
- copyFileSync(BIN_PATH, cachedBinary);
229
+ copyAtomic(BIN_PATH, cachedBinary);
118
230
  } catch {
119
231
  // cache is an optimization only
120
232
  }
@@ -131,4 +243,15 @@ async function install() {
131
243
  }
132
244
  }
133
245
 
134
- install();
246
+ if (require.main === module) {
247
+ // An interrupted install must not leave a partial download behind.
248
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
249
+ process.on(signal, () => {
250
+ cleanupPendingTempFiles();
251
+ process.exit(128 + os.constants.signals[signal]);
252
+ });
253
+ }
254
+ install();
255
+ }
256
+
257
+ module.exports = { download, copyAtomic, isUsableBinary };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vue-go-tsc",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Blazingly fast Vue 3 type checker powered by typescript-go — a Go-native alternative to vue-tsc",
5
5
  "keywords": [
6
6
  "vue",