localgate 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,503 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+ import { createServer, type Server } from "node:http";
3
+ import { readFileSync } from "node:fs";
4
+ import { createServer as createSocketServer } from "node:net";
5
+ import { join } from "node:path";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { LocalgateBanner } from "../cli/localgateBanner.ts";
8
+ import { LocalgateProxyClient } from "../client/localgateProxyClient.ts";
9
+ import { LocalgateMachineConfig } from "../config/localgateMachineConfig.ts";
10
+ import { LocalgateProjectConfig, type LocalgateProjectSettings } from "../config/localgateProjectConfig.ts";
11
+ import type { LocalgateRoute } from "../proxy/localgateRegistry.ts";
12
+ import { LocalgateEnvRewrite } from "./localgateEnvRewrite.ts";
13
+ import { LocalgateProcessTree } from "./localgateProcessTree.ts";
14
+
15
+ // Runs inside the editor's debug terminal and owns the dev process, which is the part an editor cannot
16
+ // give away: the terminal keeps the debugger attached, while `localgate restart` swaps the child
17
+ // underneath without touching the terminal, the route or the port.
18
+ export class LocalgateRunner
19
+ {
20
+ private static readonly logLinesKeptConst = 400;
21
+ private static readonly heartbeatMsConst = 10_000;
22
+ private static readonly takeoverTimeoutMsConst = 10_000;
23
+
24
+ private child: ChildProcess | null = null;
25
+ private controlServer: Server | null = null;
26
+ private route: LocalgateRoute | null = null;
27
+ private readonly logs: string[] = [];
28
+ private stopping = false;
29
+ private restarting = false;
30
+ private exitCode = 0;
31
+
32
+ constructor(
33
+ private readonly command: string[],
34
+ private readonly directory: string,
35
+ private readonly force = false
36
+ ) {}
37
+
38
+ // Only leading flags belong to localgate: from the first other word on, everything is the child's
39
+ // command line, where a `--force` of its own must survive untouched.
40
+ static parseOptions(args: string[]): { force: boolean; command: string[] }
41
+ {
42
+ let force = false;
43
+ let index = 0;
44
+
45
+ while (args[index] == "--force")
46
+ {
47
+ force = true;
48
+ index++;
49
+ }
50
+
51
+ return { force, command: args.slice(index) };
52
+ }
53
+
54
+ static debuggerAttached(env: NodeJS.ProcessEnv = process.env): boolean
55
+ {
56
+ const options = env.NODE_OPTIONS ?? "";
57
+ return options.includes("bootloader") || options.includes("js-debug");
58
+ }
59
+
60
+ // A dev server that ignores PORT still has to land on the port the route points at, so the framework's
61
+ // own flag is appended as well when we can see that the script runs Next.
62
+ static withPortFlag(command: string[], scripts: Record<string, string>, port: number): string[]
63
+ {
64
+ const [runner, verb, script] = command;
65
+ if (!runner || verb != "run" || !script) return command;
66
+ if (!["npm", "pnpm", "yarn", "npm.cmd", "pnpm.cmd"].includes(runner)) return command;
67
+
68
+ const body = scripts[script] ?? "";
69
+ if (!body.includes("next")) return command;
70
+
71
+ return [...command, "--", "-p", String(port)];
72
+ }
73
+
74
+ // Shown before the question, and instead of it when there is no terminal to ask in: whoever is about
75
+ // to lose their dev server should be able to recognise it from this alone.
76
+ static describeRunning(route: LocalgateRoute): string
77
+ {
78
+ const lines = [
79
+ "",
80
+ ` localgate ${route.names[0]} is already running`,
81
+ "",
82
+ ` command ${route.command ?? "-"}`,
83
+ ` upstream 127.0.0.1:${route.port}`,
84
+ ` started ${route.startedAt.replace("T", " ").slice(0, 19)}`,
85
+ ` pids runner ${route.runnerPid ?? "-"}, child ${route.childPid ?? "-"}`
86
+ ];
87
+
88
+ if (route.debuggerAttached) lines.push(" debugger attached");
89
+ lines.push("");
90
+
91
+ return `${lines.join("\n")}\n`;
92
+ }
93
+
94
+ static shellCommand(command: string[]): string
95
+ {
96
+ return command.map(part => /[\s"]/.test(part) ? `"${part.replace(/"/g, '\\"')}"` : part).join(" ");
97
+ }
98
+
99
+ static async freePort(): Promise<number>
100
+ {
101
+ return new Promise<number>((resolve, reject) =>
102
+ {
103
+ const server = createSocketServer();
104
+ server.once("error", reject);
105
+ server.listen(0, "127.0.0.1", () =>
106
+ {
107
+ const address = server.address();
108
+ if (!address || typeof address == "string")
109
+ {
110
+ server.close();
111
+ reject(new Error("could not obtain a free port"));
112
+ return;
113
+ }
114
+ const { port } = address;
115
+ server.close(() => resolve(port));
116
+ });
117
+ });
118
+ }
119
+
120
+ async run(): Promise<number>
121
+ {
122
+ if (this.command.length == 0) throw new Error("localgate run needs a command, for example: localgate run npm run dev");
123
+
124
+ const project = LocalgateProjectConfig.load(this.directory);
125
+
126
+ const blocked = await this.clearPredecessor(project);
127
+ if (blocked != 0) return blocked;
128
+
129
+ const machine = LocalgateMachineConfig.load();
130
+ const external = machine && project.mode != "local" ? LocalgateMachineConfig.externalSuffix(machine) : null;
131
+
132
+ const names = [`${project.name}.localhost`];
133
+ if (external) names.push(`${project.name}${external}`);
134
+
135
+ const port = await LocalgateRunner.freePort();
136
+ const controlUrl = await this.startControlServer();
137
+
138
+ await LocalgateProxyClient.ensureRunning();
139
+ const route = await LocalgateProxyClient.register({
140
+ names,
141
+ port,
142
+ kind: "app",
143
+ mode: project.mode,
144
+ cwd: project.packageDirectory,
145
+ command: this.command.join(" "),
146
+ controlUrl,
147
+ runnerPid: process.pid,
148
+ childPid: null,
149
+ debuggerAttached: LocalgateRunner.debuggerAttached()
150
+ });
151
+ this.route = route;
152
+
153
+ process.stdout.write(LocalgateBanner.render(route));
154
+
155
+ this.installSignalHandlers();
156
+ const heartbeat = this.startHeartbeat();
157
+
158
+ const finished = this.spawnChild(port, project.packageDirectory, external);
159
+ await finished;
160
+
161
+ clearInterval(heartbeat);
162
+ await this.cleanup();
163
+ return this.exitCode;
164
+ }
165
+
166
+ // Starting a second dev server for one project used to fail twice over: the registry handed this
167
+ // runner the name and left the old one holding its port unreachable, and the dev server itself then
168
+ // refused because of its own lock. So the collision is settled here, before anything is claimed.
169
+ // Returns 0 to go ahead, or the exit code to leave with.
170
+ private async clearPredecessor(project: LocalgateProjectSettings): Promise<number>
171
+ {
172
+ // By name, because that is what the registry would take away, and by directory, because that is
173
+ // what a dev server's own lock is keyed on.
174
+ const existing = await LocalgateProxyClient.resolve({ name: project.name })
175
+ ?? await LocalgateProxyClient.resolve({ directory: project.packageDirectory });
176
+
177
+ if (!existing) return 0;
178
+
179
+ if (existing.kind == "alias")
180
+ {
181
+ process.stderr.write(`localgate: ${existing.names[0]} is an alias pointing at 127.0.0.1:${existing.port}, `
182
+ + "so this project cannot claim that name.\n"
183
+ + "Remove the alias, or give the project another name in package.json.\n");
184
+ return 1;
185
+ }
186
+
187
+ if (!await LocalgateRunner.runnerAlive(existing))
188
+ {
189
+ await LocalgateRunner.reclaimAbandoned(existing);
190
+ return 0;
191
+ }
192
+
193
+ if (!this.force)
194
+ {
195
+ process.stdout.write(LocalgateRunner.describeRunning(existing));
196
+
197
+ // Asking without a terminal would block until somebody kills this process, so a non-interactive
198
+ // caller gets the facts and a flag instead.
199
+ if (process.stdin.isTTY !== true)
200
+ {
201
+ process.stderr.write("localgate: nothing to ask on, this is not a terminal. "
202
+ + "Re-run with --force to take it over.\n");
203
+ return 1;
204
+ }
205
+
206
+ if (!await LocalgateRunner.askTakeover())
207
+ {
208
+ process.stdout.write(`localgate: left it running. Reach it at http://${existing.names[0]}\n`);
209
+ return 1;
210
+ }
211
+ }
212
+
213
+ await this.stopPredecessor(existing);
214
+ return 0;
215
+ }
216
+
217
+ // A runner that died without cleaning up leaves a row behind, and usually its dev server too: the
218
+ // child outlives it and keeps the port, which is the orphan the framework's own lock then trips over.
219
+ // Nobody owns it any more, so there is nothing to ask about - it just goes.
220
+ // The pids on the row are not usable here: they were recorded by a runner that has since exited, and
221
+ // a pid number gets reused. So the port is the only handle we trust, and killPortHolder kills
222
+ // whoever answers on it right now rather than whoever used to.
223
+ private static async reclaimAbandoned(route: LocalgateRoute): Promise<void>
224
+ {
225
+ if (await LocalgateProcessTree.isPortListening(route.port))
226
+ {
227
+ process.stdout.write(`localgate: ${route.names[0]} was left behind by a runner that is gone, `
228
+ + `clearing 127.0.0.1:${route.port}\n`);
229
+
230
+ if (!await LocalgateProcessTree.killPortHolder(route.port, LocalgateRunner.takeoverTimeoutMsConst))
231
+ process.stderr.write(`localgate: 127.0.0.1:${route.port} is still held - `
232
+ + "stop that process by hand, then run again\n");
233
+ }
234
+
235
+ await LocalgateProxyClient.deregister(route.id).catch(() => {});
236
+ }
237
+
238
+ private static async runnerAlive(route: LocalgateRoute): Promise<boolean>
239
+ {
240
+ if (!route.controlUrl) return false;
241
+
242
+ return fetch(`${route.controlUrl}/ping`, { signal: AbortSignal.timeout(1_000) })
243
+ .then(response => response.ok)
244
+ .catch(() => false);
245
+ }
246
+
247
+ private static async askTakeover(): Promise<boolean>
248
+ {
249
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
250
+ reader.once("SIGINT", () =>
251
+ {
252
+ reader.close();
253
+ process.exit(1);
254
+ });
255
+
256
+ try
257
+ {
258
+ const answer = await reader.question("Stop it and take over? [Y/n] ");
259
+ return !/^n/i.test(answer.trim());
260
+ }
261
+ finally
262
+ {
263
+ reader.close();
264
+ }
265
+ }
266
+
267
+ // The old runner's own stop endpoint is the good path: it kills its child tree, releases the port and
268
+ // deregisters itself, so its terminal ends cleanly. Killing by pid is the fallback for a runner that
269
+ // no longer answers, and the port has to actually come free either way.
270
+ private async stopPredecessor(route: LocalgateRoute): Promise<void>
271
+ {
272
+ process.stdout.write(`localgate: stopping ${route.names[0]} (runner ${route.runnerPid ?? "?"})\n`);
273
+
274
+ const asked = route.controlUrl !== null && await fetch(`${route.controlUrl}/stop`, {
275
+ method: "POST",
276
+ signal: AbortSignal.timeout(2_000)
277
+ }).then(response => response.ok).catch(() => false);
278
+
279
+ if (asked && await LocalgateProcessTree.waitForPortRelease(route.port, LocalgateRunner.takeoverTimeoutMsConst))
280
+ {
281
+ await LocalgateProxyClient.deregister(route.id).catch(() => {});
282
+ return;
283
+ }
284
+
285
+ const pid = route.childPid ?? route.runnerPid;
286
+ if (pid === null)
287
+ throw new Error(`${route.names[0]} did not stop and has no pid to kill - stop it by hand`);
288
+
289
+ await LocalgateProcessTree.killTree(pid, route.port, LocalgateRunner.takeoverTimeoutMsConst);
290
+ await LocalgateProxyClient.deregister(route.id).catch(() => {});
291
+
292
+ if (await LocalgateProcessTree.isPortListening(route.port))
293
+ throw new Error(`${route.names[0]} still holds 127.0.0.1:${route.port} - stop it by hand`);
294
+ }
295
+
296
+ private spawnChild(port: number, packageDirectory: string, external: string | null): Promise<void>
297
+ {
298
+ const scripts = LocalgateRunner.readScripts(packageDirectory);
299
+ const command = LocalgateRunner.withPortFlag(this.command, scripts, port);
300
+
301
+ const env = LocalgateEnvRewrite.apply(process.env, external);
302
+ env.PORT = String(port);
303
+
304
+ // One command string rather than a command plus an args array: `npm run dev` on Windows is a .cmd,
305
+ // which node refuses to spawn without a shell, and passing an args array alongside `shell: true`
306
+ // triggers DEP0190 because the shell concatenates them anyway. Quoting here makes that explicit.
307
+ const child = spawn(LocalgateRunner.shellCommand(command), {
308
+ cwd: this.directory,
309
+ env,
310
+ shell: true,
311
+ stdio: ["inherit", "pipe", "pipe"]
312
+ });
313
+
314
+ this.child = child;
315
+ if (this.route) void LocalgateProxyClient.patch(this.route.id, { childPid: child.pid ?? null }).catch(() => {});
316
+
317
+ child.stdout?.on("data", chunk => this.absorb(chunk as Buffer, process.stdout));
318
+ child.stderr?.on("data", chunk => this.absorb(chunk as Buffer, process.stderr));
319
+
320
+ return new Promise<void>(resolve =>
321
+ {
322
+ child.once("exit", code =>
323
+ {
324
+ this.child = null;
325
+ // A restart kills the child on purpose; only an exit we did not ask for ends the runner.
326
+ if (this.restarting)
327
+ {
328
+ this.restarting = false;
329
+ resolve(this.spawnChild(port, packageDirectory, external));
330
+ return;
331
+ }
332
+
333
+ this.exitCode = code ?? 0;
334
+ resolve();
335
+ });
336
+ });
337
+ }
338
+
339
+ private async restartChild(): Promise<void>
340
+ {
341
+ const child = this.child;
342
+ if (!child?.pid || !this.route) throw new Error("nothing to restart");
343
+
344
+ this.restarting = true;
345
+ await LocalgateProcessTree.killTree(child.pid, this.route.port);
346
+ }
347
+
348
+ private absorb(chunk: Buffer, sink: NodeJS.WriteStream): void
349
+ {
350
+ sink.write(chunk);
351
+
352
+ for (const line of String(chunk).split(/\r?\n/))
353
+ if (line.length > 0) this.logs.push(line);
354
+
355
+ if (this.logs.length > LocalgateRunner.logLinesKeptConst)
356
+ this.logs.splice(0, this.logs.length - LocalgateRunner.logLinesKeptConst);
357
+ }
358
+
359
+ private startControlServer(): Promise<string>
360
+ {
361
+ const server = createServer((request, response) =>
362
+ {
363
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
364
+ const send = (status: number, payload: unknown) =>
365
+ {
366
+ const body = JSON.stringify(payload);
367
+ response.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
368
+ response.end(body);
369
+ };
370
+
371
+ if (url.pathname == "/ping") return send(200, { ok: true, id: this.route?.id ?? null });
372
+
373
+ if (url.pathname == "/logs")
374
+ {
375
+ const lines = Number.parseInt(url.searchParams.get("lines") ?? "80", 10);
376
+ return send(200, { lines: this.logs.slice(-Math.max(1, lines)) });
377
+ }
378
+
379
+ if (url.pathname == "/restart" && request.method == "POST")
380
+ {
381
+ void this.restartChild().then(
382
+ () => send(200, { ok: true }),
383
+ (error: unknown) => send(409, { error: String(error) })
384
+ );
385
+ return;
386
+ }
387
+
388
+ if (url.pathname == "/stop" && request.method == "POST")
389
+ {
390
+ send(200, { ok: true });
391
+ void this.shutdown(0);
392
+ return;
393
+ }
394
+
395
+ return send(404, { error: `unknown ${request.method} ${url.pathname}` });
396
+ });
397
+
398
+ this.controlServer = server;
399
+
400
+ // Loopback only: the restart channel must not be reachable from the LAN.
401
+ return new Promise<string>((resolve, reject) =>
402
+ {
403
+ server.once("error", reject);
404
+ server.listen(0, "127.0.0.1", () =>
405
+ {
406
+ const address = server.address();
407
+ if (!address || typeof address == "string")
408
+ {
409
+ reject(new Error("control server has no port"));
410
+ return;
411
+ }
412
+ resolve(`http://127.0.0.1:${address.port}`);
413
+ });
414
+ });
415
+ }
416
+
417
+ // The proxy holds the route table in memory, so if it dies the route dies with it. Re-registering on a
418
+ // failed ping keeps a running dev server reachable without the developer noticing anything happened.
419
+ private startHeartbeat(): NodeJS.Timeout
420
+ {
421
+ const timer = setInterval(() =>
422
+ {
423
+ void (async () =>
424
+ {
425
+ if (this.stopping || !this.route) return;
426
+ if (await LocalgateProxyClient.ping()) return;
427
+
428
+ try
429
+ {
430
+ await LocalgateProxyClient.ensureRunning();
431
+ this.route = await LocalgateProxyClient.register({
432
+ names: this.route.names,
433
+ port: this.route.port,
434
+ kind: "app",
435
+ mode: this.route.mode,
436
+ cwd: this.route.cwd,
437
+ command: this.route.command,
438
+ controlUrl: this.route.controlUrl,
439
+ runnerPid: process.pid,
440
+ childPid: this.child?.pid ?? null,
441
+ debuggerAttached: this.route.debuggerAttached
442
+ });
443
+ process.stdout.write("localgate: proxy restarted, route re-registered\n");
444
+ }
445
+ catch (error)
446
+ {
447
+ process.stderr.write(`localgate: could not re-register the route: ${String(error)}\n`);
448
+ }
449
+ })();
450
+ }, LocalgateRunner.heartbeatMsConst);
451
+
452
+ timer.unref();
453
+ return timer;
454
+ }
455
+
456
+ private installSignalHandlers(): void
457
+ {
458
+ for (const signal of ["SIGINT", "SIGTERM"] as const)
459
+ process.on(signal, () => void this.shutdown(0));
460
+ }
461
+
462
+ private async shutdown(code: number): Promise<void>
463
+ {
464
+ if (this.stopping) return;
465
+ this.stopping = true;
466
+ this.exitCode = code;
467
+
468
+ const child = this.child;
469
+ if (child?.pid && this.route) await LocalgateProcessTree.killTree(child.pid, this.route.port);
470
+
471
+ await this.cleanup();
472
+ process.exit(code);
473
+ }
474
+
475
+ private async cleanup(): Promise<void>
476
+ {
477
+ if (this.route)
478
+ {
479
+ await LocalgateProxyClient.deregister(this.route.id).catch(() => {});
480
+ this.route = null;
481
+ }
482
+
483
+ if (this.controlServer)
484
+ {
485
+ this.controlServer.closeAllConnections();
486
+ await new Promise<void>(resolve => this.controlServer!.close(() => resolve()));
487
+ this.controlServer = null;
488
+ }
489
+ }
490
+
491
+ private static readScripts(packageDirectory: string): Record<string, string>
492
+ {
493
+ try
494
+ {
495
+ const parsed = JSON.parse(readFileSync(join(packageDirectory, "package.json"), "utf8")) as { scripts?: Record<string, string> };
496
+ return parsed.scripts ?? {};
497
+ }
498
+ catch
499
+ {
500
+ return {};
501
+ }
502
+ }
503
+ }
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "localgate",
3
+ "version": "0.2.0",
4
+ "description": "Stable names for local dev servers: one port 80 multiplexed by Host, plus an API that can restart a dev server owned by your editor. Windows only today.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "author": "ludekvodicka",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ludekvodicka/LocalGate.git"
11
+ },
12
+ "homepage": "https://github.com/ludekvodicka/LocalGate#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/ludekvodicka/LocalGate/issues"
15
+ },
16
+ "keywords": [
17
+ "reverse-proxy",
18
+ "dev-server",
19
+ "localhost",
20
+ "hostname",
21
+ "developer-tools",
22
+ "cli"
23
+ ],
24
+ "engines": {
25
+ "node": ">=24"
26
+ },
27
+ "os": [
28
+ "win32"
29
+ ],
30
+ "packageManager": "pnpm@11.17.0",
31
+ "bin": {
32
+ "localgate": "bin/localgate.mjs"
33
+ },
34
+ "files": [
35
+ "bin",
36
+ "logic",
37
+ "!logic/**/*.test.ts"
38
+ ],
39
+ "scripts": {
40
+ "test": "vitest run --passWithNoTests",
41
+ "test:watch": "vitest",
42
+ "lint": "eslint .",
43
+ "type-check": "tsc --noEmit",
44
+ "verify": "pnpm run type-check && pnpm run lint && pnpm run test"
45
+ },
46
+ "dependencies": {
47
+ "tsx": "4.21.0"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "25.5.0",
51
+ "eslint": "9.22.0",
52
+ "typescript": "5.8.3",
53
+ "typescript-eslint": "8.27.0",
54
+ "vitest": "4.1.9"
55
+ }
56
+ }