localdeck 1.0.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.
- package/CHANGELOG.md +66 -0
- package/LICENSE +49 -0
- package/README.md +153 -0
- package/THIRD_PARTY_NOTICES.md +491 -0
- package/bin/localdeck.js +11 -0
- package/dashboard/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
- package/dashboard/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
- package/dashboard/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
- package/dashboard/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
- package/dashboard/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
- package/dashboard/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
- package/dashboard/assets/ibm-plex-sans-latin-500-normal-6ng42L7E.woff2 +0 -0
- package/dashboard/assets/ibm-plex-sans-latin-500-normal-BgVn5rGT.woff +0 -0
- package/dashboard/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
- package/dashboard/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
- package/dashboard/assets/index-BVj35bds.js +20 -0
- package/dashboard/assets/index-CWTMVR9T.css +1 -0
- package/dashboard/index.html +14 -0
- package/dashboard/localdeck-icon.png +0 -0
- package/dist/index-3npyta7k.js +7684 -0
- package/dist/index.js +1268 -0
- package/dist/mcp-s6gapf6v.js +34146 -0
- package/package.json +57 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1268 @@
|
|
|
1
|
+
import {
|
|
2
|
+
Api,
|
|
3
|
+
DEFAULT_API_PORT,
|
|
4
|
+
HOME_DIR,
|
|
5
|
+
VERSION,
|
|
6
|
+
__require,
|
|
7
|
+
chooseUpstream,
|
|
8
|
+
connectHost,
|
|
9
|
+
dashboardDir,
|
|
10
|
+
ensureDaemon,
|
|
11
|
+
findDaemon,
|
|
12
|
+
findProjectFile,
|
|
13
|
+
getFreePort,
|
|
14
|
+
isPortFree,
|
|
15
|
+
killProcessTree,
|
|
16
|
+
listeningPorts,
|
|
17
|
+
loadProject,
|
|
18
|
+
loadProjectFile,
|
|
19
|
+
processTree,
|
|
20
|
+
serviceKey,
|
|
21
|
+
shellCommand,
|
|
22
|
+
startDaemon,
|
|
23
|
+
startForwarder,
|
|
24
|
+
startupGuidance,
|
|
25
|
+
startupLayers,
|
|
26
|
+
streamLines,
|
|
27
|
+
stripAnsi,
|
|
28
|
+
waitForReadiness,
|
|
29
|
+
wrapper_default
|
|
30
|
+
} from "./index-3npyta7k.js";
|
|
31
|
+
|
|
32
|
+
// src/index.ts
|
|
33
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
34
|
+
import crypto from "node:crypto";
|
|
35
|
+
import { parseArgs } from "node:util";
|
|
36
|
+
|
|
37
|
+
// src/run.ts
|
|
38
|
+
import { spawn } from "node:child_process";
|
|
39
|
+
import fs from "node:fs";
|
|
40
|
+
// src/ui.ts
|
|
41
|
+
var on = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
42
|
+
var wrap = (code) => (s) => on ? `\x1B[${code}m${s}\x1B[0m` : s;
|
|
43
|
+
var c = {
|
|
44
|
+
bold: wrap(1),
|
|
45
|
+
dim: wrap(2),
|
|
46
|
+
red: wrap(31),
|
|
47
|
+
green: wrap(32),
|
|
48
|
+
yellow: wrap(33),
|
|
49
|
+
cyan: wrap(36),
|
|
50
|
+
magenta: wrap(35),
|
|
51
|
+
blue: wrap(34)
|
|
52
|
+
};
|
|
53
|
+
function fail(message) {
|
|
54
|
+
console.error(`${c.red("error")} ${message}`);
|
|
55
|
+
process.exit(1);
|
|
56
|
+
}
|
|
57
|
+
function table(rows, header) {
|
|
58
|
+
const all = [header, ...rows];
|
|
59
|
+
const widths = header.map((_, i) => Math.max(...all.map((r) => stripLen(r[i] ?? ""))));
|
|
60
|
+
const line = (r) => r.map((cell, i) => cell + " ".repeat(widths[i] - stripLen(cell))).join(" ");
|
|
61
|
+
return [c.dim(line(header)), ...rows.map(line)].join(`
|
|
62
|
+
`);
|
|
63
|
+
}
|
|
64
|
+
var stripLen = (s) => s.replace(/\x1b\[[0-9;]*m/g, "").length;
|
|
65
|
+
function ago(ts) {
|
|
66
|
+
const s = Math.max(0, Math.round((Date.now() - ts) / 1000));
|
|
67
|
+
if (s < 60)
|
|
68
|
+
return `${s}s`;
|
|
69
|
+
if (s < 3600)
|
|
70
|
+
return `${Math.round(s / 60)}m`;
|
|
71
|
+
if (s < 86400)
|
|
72
|
+
return `${Math.round(s / 3600)}h`;
|
|
73
|
+
return `${Math.round(s / 86400)}d`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/clean-urls.ts
|
|
77
|
+
async function prepareCleanUrls(port, interactive, request = fetch, log = console.log) {
|
|
78
|
+
if (interactive)
|
|
79
|
+
log("LocalDeck: preparing app links. macOS may ask once to allow localhost port 80; cancelling keeps port-number links.");
|
|
80
|
+
try {
|
|
81
|
+
const response = await request(`http://127.0.0.1:${port}/api/forwarder`, {
|
|
82
|
+
method: "POST",
|
|
83
|
+
headers: { "content-type": "application/json" },
|
|
84
|
+
body: JSON.stringify({ install: interactive, automatic: true }),
|
|
85
|
+
signal: AbortSignal.timeout(135000)
|
|
86
|
+
});
|
|
87
|
+
const status = await response.json();
|
|
88
|
+
if (response.ok && status?.ready === true)
|
|
89
|
+
return true;
|
|
90
|
+
if (interactive)
|
|
91
|
+
log(`LocalDeck: using port-number links. ${status?.error ?? "Forwarding is unavailable."}`);
|
|
92
|
+
} catch {
|
|
93
|
+
if (interactive)
|
|
94
|
+
log("LocalDeck: using port-number links; forwarding setup was unavailable.");
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/run.ts
|
|
100
|
+
var MAX_ATTACH_LOG_SOURCE_BYTES = 8000;
|
|
101
|
+
var TERMINAL_GRACE_AFTER_MS = 500;
|
|
102
|
+
var TERMINAL_FORCE_AFTER_MS = 1000;
|
|
103
|
+
async function startService(opts, overrides = {}) {
|
|
104
|
+
const dependencies = {
|
|
105
|
+
ensureDaemon,
|
|
106
|
+
getFreePort,
|
|
107
|
+
createWebSocket: (url, options) => new wrapper_default(url, options),
|
|
108
|
+
spawn,
|
|
109
|
+
fetch: globalThis.fetch,
|
|
110
|
+
...overrides
|
|
111
|
+
};
|
|
112
|
+
if (!opts.command.length)
|
|
113
|
+
throw new Error(`nothing to run for "${opts.name}"`);
|
|
114
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
115
|
+
try {
|
|
116
|
+
if (!fs.statSync(cwd).isDirectory())
|
|
117
|
+
throw new Error("not a directory");
|
|
118
|
+
} catch {
|
|
119
|
+
throw new Error(`working directory does not exist or is not a directory: ${cwd}`);
|
|
120
|
+
}
|
|
121
|
+
const daemon = await dependencies.ensureDaemon();
|
|
122
|
+
const upstreamPort = opts.upstreamPort ?? await dependencies.getFreePort();
|
|
123
|
+
const paint = opts.color ?? c.cyan;
|
|
124
|
+
const tag = opts.prefix ? paint(`[${opts.name}] `) : "";
|
|
125
|
+
const project = opts.project ?? {
|
|
126
|
+
id: "standalone",
|
|
127
|
+
name: "standalone",
|
|
128
|
+
slug: "standalone"
|
|
129
|
+
};
|
|
130
|
+
const commandEnv = await expandRunEnvironment(opts.env, opts.after ?? [], project.id, daemon.apiPort, dependencies.fetch);
|
|
131
|
+
const ws = dependencies.createWebSocket(`ws://127.0.0.1:${daemon.apiPort}/api/attach`, {
|
|
132
|
+
headers: { authorization: `Bearer ${daemon.controlToken}` }
|
|
133
|
+
});
|
|
134
|
+
const send = (m) => ws.readyState === wrapper_default.OPEN && ws.send(JSON.stringify(m));
|
|
135
|
+
const service = await new Promise((resolve, reject) => {
|
|
136
|
+
ws.once("open", () => {
|
|
137
|
+
send({
|
|
138
|
+
type: "register",
|
|
139
|
+
key: serviceKey(project.id, opts.name.toLowerCase()),
|
|
140
|
+
projectId: project.id,
|
|
141
|
+
projectName: project.name,
|
|
142
|
+
projectSlug: project.slug,
|
|
143
|
+
name: opts.name,
|
|
144
|
+
managedBy: "terminal",
|
|
145
|
+
stablePort: opts.stablePort,
|
|
146
|
+
upstreamPort,
|
|
147
|
+
upstreamSource: opts.upstreamPort === undefined ? "assigned" : "manual",
|
|
148
|
+
cwd,
|
|
149
|
+
command: opts.displayCommand ?? opts.command.join(" ")
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
ws.on("message", (raw) => {
|
|
153
|
+
const msg = JSON.parse(raw.toString());
|
|
154
|
+
if (msg.type === "registered")
|
|
155
|
+
resolve(msg.service);
|
|
156
|
+
else if (msg.type === "error")
|
|
157
|
+
reject(new Error(msg.message));
|
|
158
|
+
});
|
|
159
|
+
ws.once("error", reject);
|
|
160
|
+
});
|
|
161
|
+
const argv = opts.command.map((a) => a.replaceAll("{port}", String(upstreamPort)));
|
|
162
|
+
const database = service.serviceType !== undefined && service.serviceType !== "http";
|
|
163
|
+
const env = {
|
|
164
|
+
...process.env,
|
|
165
|
+
...commandEnv,
|
|
166
|
+
PORT: String(upstreamPort),
|
|
167
|
+
LOCALDECK_PORT: String(service.stablePort),
|
|
168
|
+
LOCALDECK_SERVICE: service.name,
|
|
169
|
+
...database ? {} : { LOCALDECK_URL: `http://localhost:${service.stablePort}` }
|
|
170
|
+
};
|
|
171
|
+
if (database) {
|
|
172
|
+
console.log(`${tag}${c.bold("LocalDeck")} ${c.dim("›")} ${paint(service.name)} ${c.dim("→")} ${c.green(`database localhost:${service.upstreamPort}`)} ${c.dim("(published port · no HTTP proxy)")}`);
|
|
173
|
+
} else {
|
|
174
|
+
const appUrl = opts.cleanUrls ? service.urls[0].replace(/^(http:\/\/[a-z0-9-]+(?:\.[a-z0-9-]+)?\.localhost):\d+(?=\/|$)/i, "$1") : service.urls[0];
|
|
175
|
+
console.log(`${tag}${c.bold("LocalDeck")} ${c.dim("›")} ${paint(service.name)} ${c.dim("→")} ${c.green(appUrl)} ${c.dim(`(also ${service.urls[1]} · dashboard http://localhost:${daemon.apiPort})`)}`);
|
|
176
|
+
}
|
|
177
|
+
const posix = process.platform !== "win32";
|
|
178
|
+
const child = dependencies.spawn(argv[0], argv.slice(1), { cwd, env, stdio: [opts.prefix ? "ignore" : "inherit", "pipe", "pipe"], shell: !posix, detached: posix });
|
|
179
|
+
if (child.pid)
|
|
180
|
+
send({ type: "pid", pid: child.pid });
|
|
181
|
+
const pipe = (stream, name, out) => {
|
|
182
|
+
stream.on("data", (chunk) => {
|
|
183
|
+
if (opts.prefix) {
|
|
184
|
+
const text = stripAnsi(chunk.toString());
|
|
185
|
+
recentOutput = (recentOutput + text).slice(-16000);
|
|
186
|
+
out.write(text.replace(/^(?=.)/gm, tag));
|
|
187
|
+
} else
|
|
188
|
+
out.write(chunk);
|
|
189
|
+
});
|
|
190
|
+
streamLines(stream, (line) => {
|
|
191
|
+
for (const part of splitAttachLogLine(stripAnsi(line)))
|
|
192
|
+
send({ type: "log", stream: name, line: part });
|
|
193
|
+
});
|
|
194
|
+
};
|
|
195
|
+
pipe(child.stdout, "stdout", process.stdout);
|
|
196
|
+
pipe(child.stderr, "stderr", process.stderr);
|
|
197
|
+
let hinted = false;
|
|
198
|
+
let recentOutput = "";
|
|
199
|
+
const hintOnPortClash = (chunk) => {
|
|
200
|
+
if (hinted)
|
|
201
|
+
return;
|
|
202
|
+
const text = chunk.toString();
|
|
203
|
+
if (/EADDRINUSE|address already in use|already in use/i.test(text) && text.includes(String(service.stablePort))) {
|
|
204
|
+
hinted = true;
|
|
205
|
+
console.error(`${tag}${c.yellow(`LocalDeck: your process tried to use port ${service.stablePort}, which LocalDeck is holding as the stable port for "${service.name}".`)}`);
|
|
206
|
+
console.error(`${tag}${c.yellow(` Fix: run without --port (LocalDeck finds the tool's own port automatically), or pick a different stable port, e.g. --port ${service.stablePort + 1000}.`)}`);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
child.stdout.on("data", hintOnPortClash);
|
|
210
|
+
child.stderr.on("data", hintOnPortClash);
|
|
211
|
+
let detectTimer;
|
|
212
|
+
let reported;
|
|
213
|
+
if (!opts.upstreamPort && child.pid) {
|
|
214
|
+
const rootPid = child.pid;
|
|
215
|
+
let idle = 0;
|
|
216
|
+
const tick = async () => {
|
|
217
|
+
if (child.exitCode !== null || child.signalCode)
|
|
218
|
+
return;
|
|
219
|
+
try {
|
|
220
|
+
const listeners = await listeningPorts(await processTree(rootPid));
|
|
221
|
+
const pick = chooseUpstream(listeners, upstreamPort);
|
|
222
|
+
if (pick) {
|
|
223
|
+
const key = `${connectHost(pick)}:${pick.port}`;
|
|
224
|
+
if (key !== reported) {
|
|
225
|
+
reported = key;
|
|
226
|
+
send({ type: "upstream", port: pick.port, host: connectHost(pick) });
|
|
227
|
+
if (pick.port !== upstreamPort)
|
|
228
|
+
console.log(`${tag}${c.dim(`LocalDeck: process is listening on ${key} (ignored $PORT) — ${service.urls[0]} now points there`)}`);
|
|
229
|
+
}
|
|
230
|
+
idle++;
|
|
231
|
+
}
|
|
232
|
+
} catch {}
|
|
233
|
+
detectTimer = setTimeout(tick, reported ? Math.min(2000 + idle * 500, 1e4) : 400);
|
|
234
|
+
};
|
|
235
|
+
detectTimer = setTimeout(tick, 300);
|
|
236
|
+
}
|
|
237
|
+
let stopping = false;
|
|
238
|
+
let cleanupPromise;
|
|
239
|
+
let leaderExit;
|
|
240
|
+
let finished = false;
|
|
241
|
+
let resolveDone;
|
|
242
|
+
const done = new Promise((resolve) => {
|
|
243
|
+
resolveDone = resolve;
|
|
244
|
+
});
|
|
245
|
+
const cleanup = (signal) => cleanupPromise ??= cleanupTerminalTree(child, signal);
|
|
246
|
+
const finishAfterCleanup = async (signal) => {
|
|
247
|
+
if (finished || !leaderExit)
|
|
248
|
+
return;
|
|
249
|
+
if (!await cleanup(signal)) {
|
|
250
|
+
cleanupPromise = undefined;
|
|
251
|
+
stopping = false;
|
|
252
|
+
console.error(`${tag}${c.red(`LocalDeck: process descendants survived cleanup; retry Stop`)}`);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (finished)
|
|
256
|
+
return;
|
|
257
|
+
finished = true;
|
|
258
|
+
if (detectTimer)
|
|
259
|
+
clearTimeout(detectTimer);
|
|
260
|
+
send({ type: "log", stream: "stderr", line: `process exited (${leaderExit.signal ?? `code ${leaderExit.code}`})` });
|
|
261
|
+
setTimeout(() => {
|
|
262
|
+
ws.close();
|
|
263
|
+
resolveDone(leaderExit.code ?? (leaderExit.signal ? 1 : 0));
|
|
264
|
+
}, 50);
|
|
265
|
+
};
|
|
266
|
+
const stop = (signal = "SIGTERM") => {
|
|
267
|
+
if (finished || stopping)
|
|
268
|
+
return;
|
|
269
|
+
stopping = true;
|
|
270
|
+
cleanup(signal).then(() => finishAfterCleanup(signal));
|
|
271
|
+
};
|
|
272
|
+
ws.on("message", (raw) => {
|
|
273
|
+
const msg = JSON.parse(raw.toString());
|
|
274
|
+
if (msg.type === "error") {
|
|
275
|
+
console.error(`${tag}${c.yellow(`LocalDeck: ${msg.message}`)}`);
|
|
276
|
+
reported = undefined;
|
|
277
|
+
} else if (msg.type === "stop") {
|
|
278
|
+
console.log(`${tag}${c.dim("LocalDeck: stop requested from dashboard/CLI")}`);
|
|
279
|
+
stop();
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
ws.on("close", () => {
|
|
283
|
+
if (!stopping)
|
|
284
|
+
console.error(`${tag}${c.yellow("LocalDeck: lost connection to daemon; the stable port is no longer proxied. Process keeps running.")}`);
|
|
285
|
+
});
|
|
286
|
+
child.on("exit", (code, signal) => {
|
|
287
|
+
if (code !== 0 && !hinted) {
|
|
288
|
+
const guidance = startupGuidance(recentOutput);
|
|
289
|
+
if (guidance)
|
|
290
|
+
console.error(`${tag}${c.yellow(["LocalDeck: " + guidance.title, ...guidance.steps].join(`
|
|
291
|
+
`))}`);
|
|
292
|
+
}
|
|
293
|
+
leaderExit = { code, signal };
|
|
294
|
+
stopping = true;
|
|
295
|
+
finishAfterCleanup("SIGTERM");
|
|
296
|
+
});
|
|
297
|
+
child.on("error", (err) => {
|
|
298
|
+
stopping = true;
|
|
299
|
+
finished = true;
|
|
300
|
+
console.error(`${tag}${c.red(`LocalDeck: failed to start "${argv[0]}": ${err.message}`)}`);
|
|
301
|
+
ws.close();
|
|
302
|
+
resolveDone(1);
|
|
303
|
+
});
|
|
304
|
+
const readiness = opts.ready;
|
|
305
|
+
const readyOperation = readiness ? (async () => {
|
|
306
|
+
send({ type: "readiness", status: "checking", message: readiness.type === "tcp" ? "Waiting for the service to listen" : "Running configured readiness check" });
|
|
307
|
+
try {
|
|
308
|
+
const ready = await waitForReadiness({
|
|
309
|
+
name: service.name,
|
|
310
|
+
run: opts.displayCommand ?? opts.command.join(" "),
|
|
311
|
+
tags: [],
|
|
312
|
+
after: opts.after ?? [],
|
|
313
|
+
ready: readiness
|
|
314
|
+
}, async () => {
|
|
315
|
+
const response = await dependencies.fetch(`http://127.0.0.1:${daemon.apiPort}/api/services/${encodeURIComponent(service.key)}`);
|
|
316
|
+
if (response.status === 404)
|
|
317
|
+
return;
|
|
318
|
+
if (!response.ok)
|
|
319
|
+
throw new Error(`readiness status request failed (${response.status})`);
|
|
320
|
+
return response.json();
|
|
321
|
+
}, { cwd, env: commandEnv });
|
|
322
|
+
send({ type: "readiness", status: "ready", message: readiness.type === "tcp" ? "Listening on its upstream port" : "Configured readiness check passed" });
|
|
323
|
+
return ready;
|
|
324
|
+
} catch (error) {
|
|
325
|
+
send({ type: "readiness", status: "failed", message: error instanceof Error ? error.message.slice(0, 500) : "Readiness check failed" });
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
})() : Promise.resolve(service);
|
|
329
|
+
readyOperation.catch(() => {});
|
|
330
|
+
return { name: opts.name, service, child, stop, done, ready: readyOperation };
|
|
331
|
+
}
|
|
332
|
+
async function cleanupTerminalTree(child, signal) {
|
|
333
|
+
await killProcessTree(child, signal);
|
|
334
|
+
if (process.platform === "win32")
|
|
335
|
+
return true;
|
|
336
|
+
const groupId = child.pid;
|
|
337
|
+
if (!groupId || !processGroupIsAlive(groupId))
|
|
338
|
+
return true;
|
|
339
|
+
if (await waitForProcessGroupExitWhileLeaderLives(child, groupId, TERMINAL_GRACE_AFTER_MS))
|
|
340
|
+
return true;
|
|
341
|
+
await killProcessTree(child, "SIGKILL");
|
|
342
|
+
return waitForProcessGroupExit(groupId, TERMINAL_FORCE_AFTER_MS);
|
|
343
|
+
}
|
|
344
|
+
function processGroupIsAlive(groupId) {
|
|
345
|
+
try {
|
|
346
|
+
process.kill(-groupId, 0);
|
|
347
|
+
return true;
|
|
348
|
+
} catch (error) {
|
|
349
|
+
return error.code === "EPERM";
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async function waitForProcessGroupExit(groupId, timeoutMs) {
|
|
353
|
+
const deadline = Date.now() + timeoutMs;
|
|
354
|
+
while (processGroupIsAlive(groupId)) {
|
|
355
|
+
if (Date.now() >= deadline)
|
|
356
|
+
return false;
|
|
357
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(20, timeoutMs)));
|
|
358
|
+
}
|
|
359
|
+
return true;
|
|
360
|
+
}
|
|
361
|
+
async function waitForProcessGroupExitWhileLeaderLives(child, groupId, timeoutMs) {
|
|
362
|
+
const deadline = Date.now() + timeoutMs;
|
|
363
|
+
while (processGroupIsAlive(groupId)) {
|
|
364
|
+
if (child.exitCode !== null || child.signalCode !== null || Date.now() >= deadline)
|
|
365
|
+
return false;
|
|
366
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(20, timeoutMs)));
|
|
367
|
+
}
|
|
368
|
+
return true;
|
|
369
|
+
}
|
|
370
|
+
function splitAttachLogLine(line) {
|
|
371
|
+
if (Buffer.byteLength(line) <= MAX_ATTACH_LOG_SOURCE_BYTES)
|
|
372
|
+
return [line];
|
|
373
|
+
const chunks = [];
|
|
374
|
+
let characters = [];
|
|
375
|
+
let bytes = 0;
|
|
376
|
+
for (const character of line) {
|
|
377
|
+
const characterBytes = Buffer.byteLength(character);
|
|
378
|
+
if (characters.length && bytes + characterBytes > MAX_ATTACH_LOG_SOURCE_BYTES) {
|
|
379
|
+
chunks.push(characters.join(""));
|
|
380
|
+
characters = [];
|
|
381
|
+
bytes = 0;
|
|
382
|
+
}
|
|
383
|
+
characters.push(character);
|
|
384
|
+
bytes += characterBytes;
|
|
385
|
+
}
|
|
386
|
+
if (characters.length)
|
|
387
|
+
chunks.push(characters.join(""));
|
|
388
|
+
return chunks;
|
|
389
|
+
}
|
|
390
|
+
async function expandRunEnvironment(overrides, prerequisites, projectId, apiPort, fetchImpl) {
|
|
391
|
+
if (!overrides)
|
|
392
|
+
return {};
|
|
393
|
+
const allowed = new Set(prerequisites);
|
|
394
|
+
const services = new Map;
|
|
395
|
+
const load = async (rawName) => {
|
|
396
|
+
const name = rawName.toLowerCase();
|
|
397
|
+
if (!allowed.has(name))
|
|
398
|
+
throw new Error(`environment references undeclared prerequisite "${rawName}"`);
|
|
399
|
+
const cached = services.get(name);
|
|
400
|
+
if (cached)
|
|
401
|
+
return cached;
|
|
402
|
+
const response = await fetchImpl(`http://127.0.0.1:${apiPort}/api/services/${encodeURIComponent(serviceKey(projectId, name))}`);
|
|
403
|
+
if (response.status === 404)
|
|
404
|
+
throw new Error(`environment references unresolved prerequisite "${rawName}"`);
|
|
405
|
+
if (!response.ok)
|
|
406
|
+
throw new Error(`could not resolve prerequisite "${rawName}" (${response.status})`);
|
|
407
|
+
const service = await response.json();
|
|
408
|
+
services.set(name, service);
|
|
409
|
+
return service;
|
|
410
|
+
};
|
|
411
|
+
const reference = /\{service:([^}:]+):(port|url)\}/g;
|
|
412
|
+
const expanded = {};
|
|
413
|
+
for (const [name, value] of Object.entries(overrides)) {
|
|
414
|
+
let cursor = 0;
|
|
415
|
+
let output = "";
|
|
416
|
+
for (const match of value.matchAll(reference)) {
|
|
417
|
+
output += value.slice(cursor, match.index);
|
|
418
|
+
const service = await load(match[1]);
|
|
419
|
+
if (match[2] === "port")
|
|
420
|
+
output += String(service.serviceType && service.serviceType !== "http" ? service.upstreamPort : service.stablePort);
|
|
421
|
+
else {
|
|
422
|
+
if (service.serviceType && service.serviceType !== "http")
|
|
423
|
+
throw new Error(`environment variable ${name} cannot use a URL for database prerequisite "${match[1]}"`);
|
|
424
|
+
output += `http://localhost:${service.stablePort}`;
|
|
425
|
+
}
|
|
426
|
+
cursor = match.index + match[0].length;
|
|
427
|
+
}
|
|
428
|
+
expanded[name] = output + value.slice(cursor);
|
|
429
|
+
if (expanded[name].includes("{service:"))
|
|
430
|
+
throw new Error(`environment variable ${name} has an invalid service reference`);
|
|
431
|
+
}
|
|
432
|
+
return expanded;
|
|
433
|
+
}
|
|
434
|
+
async function runForeground(all) {
|
|
435
|
+
const daemon = await ensureDaemon();
|
|
436
|
+
const cleanUrls = await prepareCleanUrls(daemon.apiPort, Boolean(process.stdin.isTTY && process.stdout.isTTY && !process.env.CI));
|
|
437
|
+
const running = [];
|
|
438
|
+
const controller = new AbortController;
|
|
439
|
+
const stopAll = (sig) => {
|
|
440
|
+
controller.abort();
|
|
441
|
+
running.forEach((r) => r.stop(sig));
|
|
442
|
+
};
|
|
443
|
+
for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"])
|
|
444
|
+
process.on(sig, () => stopAll(sig));
|
|
445
|
+
const scheduled = await scheduleForegroundStarts(all, async (options) => {
|
|
446
|
+
const service = await startService({ ...options, cleanUrls });
|
|
447
|
+
running.push(service);
|
|
448
|
+
return service;
|
|
449
|
+
}, { signal: controller.signal });
|
|
450
|
+
for (const failed of scheduled.failed)
|
|
451
|
+
console.error(`${c.red("error")} starting "${failed.name}": ${failed.error.message}`);
|
|
452
|
+
const codes = await Promise.all(running.map((r) => r.done));
|
|
453
|
+
process.exit(codes.find((c2) => c2 !== 0) ?? (scheduled.failed.length ? 1 : 0));
|
|
454
|
+
}
|
|
455
|
+
async function scheduleForegroundStarts(all, launch, control = {}) {
|
|
456
|
+
const byName = new Map(all.map((options) => [options.name.toLowerCase(), options]));
|
|
457
|
+
const ready = new Map;
|
|
458
|
+
const schedule = (options, ancestors = new Set) => {
|
|
459
|
+
const name = options.name.toLowerCase();
|
|
460
|
+
if (ancestors.has(name))
|
|
461
|
+
return Promise.resolve({ error: new Error("project dependency graph contains a cycle") });
|
|
462
|
+
const existing = ready.get(name);
|
|
463
|
+
if (existing)
|
|
464
|
+
return existing;
|
|
465
|
+
let resolve;
|
|
466
|
+
const scheduled = new Promise((done) => {
|
|
467
|
+
resolve = done;
|
|
468
|
+
});
|
|
469
|
+
ready.set(name, scheduled);
|
|
470
|
+
(async () => {
|
|
471
|
+
const dependencies = options.after ?? [];
|
|
472
|
+
const nextAncestors = new Set(ancestors).add(name);
|
|
473
|
+
const prerequisiteResults = await Promise.all(dependencies.map((dependency) => {
|
|
474
|
+
const prerequisite = byName.get(dependency.toLowerCase());
|
|
475
|
+
if (!prerequisite)
|
|
476
|
+
return Promise.resolve({ error: new Error(`${options.name} starts after unknown service ${dependency}`) });
|
|
477
|
+
return schedule(prerequisite, nextAncestors);
|
|
478
|
+
}));
|
|
479
|
+
const failedDependency = prerequisiteResults.find((result) => result.error);
|
|
480
|
+
if (failedDependency)
|
|
481
|
+
return resolve({ error: new Error(`${options.name} was not started because a prerequisite failed: ${failedDependency.error.message}`) });
|
|
482
|
+
if (control.signal?.aborted)
|
|
483
|
+
return resolve({ error: new Error(`${options.name} was not started because startup was cancelled`) });
|
|
484
|
+
let service;
|
|
485
|
+
try {
|
|
486
|
+
service = await launch(options);
|
|
487
|
+
} catch (error) {
|
|
488
|
+
return resolve({ error: toError(error) });
|
|
489
|
+
}
|
|
490
|
+
if (control.signal?.aborted) {
|
|
491
|
+
service.stop("SIGTERM");
|
|
492
|
+
return resolve({ error: new Error(`${options.name} was stopped because startup was cancelled`) });
|
|
493
|
+
}
|
|
494
|
+
if (all.some((candidate) => (candidate.after ?? []).some((dependency) => dependency.toLowerCase() === name))) {
|
|
495
|
+
console.log(`${c.dim(`LocalDeck: waiting for ${service.name} before starting its dependents`)}`);
|
|
496
|
+
}
|
|
497
|
+
try {
|
|
498
|
+
await service.ready;
|
|
499
|
+
} catch (error) {
|
|
500
|
+
service.stop("SIGTERM");
|
|
501
|
+
return resolve({ error: toError(error) });
|
|
502
|
+
}
|
|
503
|
+
if (control.signal?.aborted) {
|
|
504
|
+
service.stop("SIGTERM");
|
|
505
|
+
return resolve({ error: new Error(`${options.name} was stopped because startup was cancelled`) });
|
|
506
|
+
}
|
|
507
|
+
console.log(`${c.green("✓")} ${service.name} ${options.ready?.type === "tcp" ? "is listening" : "passed readiness"}`);
|
|
508
|
+
resolve({ service });
|
|
509
|
+
})().catch((error) => resolve({ error: toError(error) }));
|
|
510
|
+
return scheduled;
|
|
511
|
+
};
|
|
512
|
+
const settled = await Promise.all(all.map((option) => schedule(option)));
|
|
513
|
+
return {
|
|
514
|
+
running: settled.flatMap((result) => result.service ? [result.service] : []),
|
|
515
|
+
failed: all.flatMap((option, index) => settled[index].error ? [{ name: option.name, error: settled[index].error }] : [])
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
function toError(error) {
|
|
519
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// src/project.ts
|
|
523
|
+
import fs2 from "node:fs";
|
|
524
|
+
import path from "node:path";
|
|
525
|
+
function findProjectCommand(project, name) {
|
|
526
|
+
return project.commands.find((command) => command.name === name.toLowerCase());
|
|
527
|
+
}
|
|
528
|
+
function proposeFromPackageJson(dir = process.cwd()) {
|
|
529
|
+
const root = findPackageRoot(dir);
|
|
530
|
+
if (!root)
|
|
531
|
+
return [];
|
|
532
|
+
const manager = detectPackageManager(root);
|
|
533
|
+
const manifests = discoverWorkspaceManifests(root);
|
|
534
|
+
const entries = manifests.flatMap(({ file, cwd }) => {
|
|
535
|
+
const pkg = readJson(file);
|
|
536
|
+
const scripts = pkg?.scripts;
|
|
537
|
+
return scripts && typeof scripts === "object" ? Object.entries(scripts).filter(([, value]) => typeof value === "string").map(([name, run]) => ({ name, run, cwd })) : [];
|
|
538
|
+
});
|
|
539
|
+
const hasWorkspaceScripts = entries.some((e) => e.cwd);
|
|
540
|
+
const usable = entries.filter((e) => !(hasWorkspaceScripts && !e.cwd && /\b(?:turbo|nx|lerna)\b|\b(?:pnpm|npm|yarn|bun)\s+(?:-r|--recursive|workspaces?)/i.test(e.run)));
|
|
541
|
+
const chosen = usable.filter((entry) => usable.some((other) => other.cwd === entry.cwd && /^dev([:_-]|$)/.test(other.name)) ? /^dev([:_-]|$)/.test(entry.name) : /^(start|serve|preview)([:_-]|$)/.test(entry.name));
|
|
542
|
+
const out = [];
|
|
543
|
+
const taken = new Set;
|
|
544
|
+
for (const source of chosen) {
|
|
545
|
+
const script = source.name;
|
|
546
|
+
const [prefix, ...rest] = script.split(/[:_-]/);
|
|
547
|
+
let name = (source.cwd && !rest.length ? path.basename(source.cwd) : rest.join("-") || prefix).replace(/[^a-z0-9_-]/gi, "-").toLowerCase().replace(/^[^a-z0-9]+/, "");
|
|
548
|
+
if (!name)
|
|
549
|
+
name = "service";
|
|
550
|
+
if (taken.has(name))
|
|
551
|
+
name = script.replace(/[^a-z0-9_-]/gi, "-").toLowerCase().replace(/^[^a-z0-9]+/, "");
|
|
552
|
+
name = name.slice(0, 41);
|
|
553
|
+
if (taken.has(name)) {
|
|
554
|
+
let n = 2;
|
|
555
|
+
const base = name.replace(/-+$/, "").slice(0, 37);
|
|
556
|
+
while (taken.has(name))
|
|
557
|
+
name = `${base}-${n++}`.slice(0, 41);
|
|
558
|
+
}
|
|
559
|
+
taken.add(name);
|
|
560
|
+
out.push({
|
|
561
|
+
name,
|
|
562
|
+
run: `${manager} run ${script}`,
|
|
563
|
+
tags: [],
|
|
564
|
+
after: [],
|
|
565
|
+
...source.cwd ? { cwd: source.cwd } : {},
|
|
566
|
+
ready: { type: "tcp", timeoutMs: 60000, intervalMs: 400 }
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
return out;
|
|
570
|
+
}
|
|
571
|
+
function findPackageRoot(from = process.cwd()) {
|
|
572
|
+
let dir = path.resolve(from);
|
|
573
|
+
for (;; ) {
|
|
574
|
+
if (fs2.existsSync(path.join(dir, "package.json")))
|
|
575
|
+
return dir;
|
|
576
|
+
const parent = path.dirname(dir);
|
|
577
|
+
if (parent === dir)
|
|
578
|
+
return;
|
|
579
|
+
dir = parent;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
function detectPackageManager(root) {
|
|
583
|
+
const pkg = readJson(path.join(root, "package.json"));
|
|
584
|
+
if (typeof pkg?.packageManager === "string") {
|
|
585
|
+
const value = pkg.packageManager.split("@")[0];
|
|
586
|
+
if (["npm", "bun", "pnpm", "yarn"].includes(value))
|
|
587
|
+
return value;
|
|
588
|
+
}
|
|
589
|
+
const lockfiles = [["bun.lock", "bun"], ["bun.lockb", "bun"], ["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["package-lock.json", "npm"]];
|
|
590
|
+
return lockfiles.find(([file]) => fs2.existsSync(path.join(root, file)))?.[1] ?? "npm";
|
|
591
|
+
}
|
|
592
|
+
function readJson(file) {
|
|
593
|
+
try {
|
|
594
|
+
const value = JSON.parse(fs2.readFileSync(file, "utf8"));
|
|
595
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
596
|
+
throw new Error("manifest must contain an object");
|
|
597
|
+
return value;
|
|
598
|
+
} catch (error) {
|
|
599
|
+
if (fs2.existsSync(file))
|
|
600
|
+
throw new Error(`${file} is not valid JSON: ${error.message}`);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
function discoverWorkspaceManifests(root) {
|
|
605
|
+
const rootFile = path.join(root, "package.json");
|
|
606
|
+
const pkg = readJson(rootFile);
|
|
607
|
+
const out = [{ file: rootFile }];
|
|
608
|
+
const workspaces = Array.isArray(pkg?.workspaces) ? pkg.workspaces : Array.isArray(pkg?.packages) ? pkg.packages : Array.isArray(pkg?.workspaces?.packages) ? pkg.workspaces.packages : [];
|
|
609
|
+
const patterns = workspaces.filter((pattern) => typeof pattern === "string" && !pattern.includes("..") && !path.isAbsolute(pattern));
|
|
610
|
+
const matchers = patterns.map((pattern) => {
|
|
611
|
+
const clean = pattern.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/$/, "");
|
|
612
|
+
const parts = clean.split("/");
|
|
613
|
+
const regex = parts.map((part, index) => part === "**" ? index === parts.length - 1 ? ".*" : "(?:[^/]+/)*" : part.split("*").map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*") + (index < parts.length - 1 ? "/" : "")).join("");
|
|
614
|
+
return { regex: new RegExp(`^${regex}$`), prefix: clean.split("*")[0], depth: parts.includes("**") ? Infinity : parts.length };
|
|
615
|
+
});
|
|
616
|
+
const walk = (dir, depth) => {
|
|
617
|
+
if (!matchers.some((matcher) => matcher.depth >= depth))
|
|
618
|
+
return;
|
|
619
|
+
for (const entry of fs2.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
620
|
+
if (!entry.isDirectory() || entry.isSymbolicLink() || ["node_modules", ".git", ".superpowers", "dist"].includes(entry.name))
|
|
621
|
+
continue;
|
|
622
|
+
const full = path.join(dir, entry.name);
|
|
623
|
+
const rel = path.relative(root, full).replace(/\\/g, "/");
|
|
624
|
+
if (!matchers.some((matcher) => matcher.prefix.startsWith(`${rel}/`) || rel.startsWith(matcher.prefix) || matcher.prefix === rel))
|
|
625
|
+
continue;
|
|
626
|
+
if (matchers.some((matcher) => matcher.regex.test(rel))) {
|
|
627
|
+
const file = path.join(full, "package.json");
|
|
628
|
+
if (fs2.existsSync(file) && fs2.lstatSync(file).isFile())
|
|
629
|
+
out.push({ file, cwd: rel });
|
|
630
|
+
}
|
|
631
|
+
walk(full, depth + 1);
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
walk(root, 1);
|
|
635
|
+
return out;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// src/index.ts
|
|
639
|
+
import fs4 from "node:fs";
|
|
640
|
+
import path3 from "node:path";
|
|
641
|
+
|
|
642
|
+
// src/setup.ts
|
|
643
|
+
import fs3 from "node:fs";
|
|
644
|
+
import path2 from "node:path";
|
|
645
|
+
import { spawnSync } from "node:child_process";
|
|
646
|
+
async function doctor(dir = process.cwd(), options = {}) {
|
|
647
|
+
const executable = options.executable ?? ((command, args, timeoutMs) => spawnSync(command, args, { encoding: "utf8", timeout: timeoutMs }));
|
|
648
|
+
const checks = [];
|
|
649
|
+
const nodeProbe = executable("node", ["--version"], 2000);
|
|
650
|
+
const nodeVersion = String(nodeProbe.stdout ?? "").trim().replace(/^v/, "");
|
|
651
|
+
const nodeMajor = Number(nodeVersion.split(".")[0]);
|
|
652
|
+
checks.push({ name: "node", ok: nodeProbe.status === 0 && nodeMajor >= 20, message: nodeProbe.status === 0 ? `Node.js ${nodeVersion}` : "Node.js executable is unavailable", fix: nodeProbe.status === 0 && nodeMajor >= 20 ? undefined : "Install Node.js 20 or newer and put it on PATH." });
|
|
653
|
+
const root = findPackageRoot(dir);
|
|
654
|
+
if (!root)
|
|
655
|
+
checks.push({ name: "package-manager", ok: true, message: "No package.json; using explicitly configured commands." });
|
|
656
|
+
else {
|
|
657
|
+
let manager = "npm";
|
|
658
|
+
try {
|
|
659
|
+
manager = detectPackageManager(root);
|
|
660
|
+
} catch (error) {
|
|
661
|
+
checks.push({ name: "package.json", ok: false, message: error.message, fix: "Fix package.json syntax." });
|
|
662
|
+
}
|
|
663
|
+
const available = executable(manager, ["--version"], 2000).status === 0;
|
|
664
|
+
checks.push({ name: "package-manager", ok: available, message: `${manager} ${available ? "is available" : "is not available"}`, fix: available ? undefined : `Install ${manager} or put it on PATH.` });
|
|
665
|
+
let pkg;
|
|
666
|
+
try {
|
|
667
|
+
pkg = JSON.parse(fs3.readFileSync(path2.join(root, "package.json"), "utf8"));
|
|
668
|
+
if (!pkg || typeof pkg !== "object" || Array.isArray(pkg))
|
|
669
|
+
throw new Error("manifest must contain an object");
|
|
670
|
+
} catch (error) {
|
|
671
|
+
checks.push({ name: "package.json", ok: false, message: `${path2.join(root, "package.json")} is not valid JSON: ${error.message}`, fix: "Fix package.json syntax." });
|
|
672
|
+
pkg = {};
|
|
673
|
+
}
|
|
674
|
+
const deps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {}, ...pkg.optionalDependencies ?? {} };
|
|
675
|
+
if (Object.keys(deps).length) {
|
|
676
|
+
const installed = fs3.existsSync(path2.join(root, "node_modules")) || fs3.existsSync(path2.join(root, ".pnp.cjs"));
|
|
677
|
+
checks.push({ name: "dependencies", ok: installed, message: installed ? "node_modules exists" : "dependencies are not installed", fix: installed ? undefined : `Run ${manager} install.` });
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
const projectFile = findProjectFile(dir);
|
|
681
|
+
if (!projectFile)
|
|
682
|
+
checks.push({ name: "config", ok: false, message: "No LocalDeck config found", fix: "Run localdeck init." });
|
|
683
|
+
else {
|
|
684
|
+
try {
|
|
685
|
+
const project = loadProjectFile(projectFile);
|
|
686
|
+
checks.push({ name: "config", ok: true, message: `${path2.basename(projectFile)}: ${project.commands.length} service(s)` });
|
|
687
|
+
const dirs = [...new Set(project.commands.map((c2) => path2.resolve(project.dir, c2.cwd ?? ".")))];
|
|
688
|
+
for (const cwd of dirs) {
|
|
689
|
+
const exists = fs3.existsSync(cwd) && fs3.statSync(cwd).isDirectory();
|
|
690
|
+
checks.push({ name: `working-directory:${path2.relative(project.dir, cwd) || "."}`, ok: exists, message: exists ? "directory exists" : "directory does not exist", fix: exists ? undefined : "Fix the command cwd in your LocalDeck config." });
|
|
691
|
+
}
|
|
692
|
+
for (const cwd of new Set([project.dir, ...dirs])) {
|
|
693
|
+
if (!fs3.existsSync(cwd) || !fs3.statSync(cwd).isDirectory())
|
|
694
|
+
continue;
|
|
695
|
+
const label = path2.relative(project.dir, cwd) || ".";
|
|
696
|
+
const manifest = path2.join(cwd, "package.json");
|
|
697
|
+
if (cwd !== root && fs3.existsSync(manifest)) {
|
|
698
|
+
try {
|
|
699
|
+
const pkg = JSON.parse(fs3.readFileSync(manifest, "utf8"));
|
|
700
|
+
if (Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).length) {
|
|
701
|
+
const installed = [cwd, root ?? project.dir].some((directory) => fs3.existsSync(path2.join(directory, "node_modules")) || fs3.existsSync(path2.join(directory, ".pnp.cjs")));
|
|
702
|
+
checks.push({ name: `dependencies:${label}`, ok: installed, message: installed ? "Dependency installation found" : "Dependencies are not installed", fix: installed ? undefined : "Run the project's package manager install command." });
|
|
703
|
+
}
|
|
704
|
+
} catch {
|
|
705
|
+
checks.push({ name: `package.json:${label}`, ok: false, message: "Invalid package.json", fix: "Fix this workspace's package.json syntax." });
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const envExample = path2.join(cwd, ".env.example");
|
|
709
|
+
if (!fs3.existsSync(envExample))
|
|
710
|
+
continue;
|
|
711
|
+
const required = envNames(fs3.readFileSync(envExample, "utf8"));
|
|
712
|
+
const envFile = path2.join(cwd, ".env");
|
|
713
|
+
const values = envAssignments(fs3.existsSync(envFile) ? fs3.readFileSync(envFile, "utf8") : "");
|
|
714
|
+
const commands = project.commands.filter((command) => path2.resolve(project.dir, command.cwd ?? ".") === cwd);
|
|
715
|
+
const missing = [...required].filter((name) => !process.env[name] && !values.get(name) && (!commands.length || !commands.every((command) => Boolean(command.env?.[name]))));
|
|
716
|
+
checks.push({ name: label === "." ? "environment" : `environment:${label}`, ok: !missing.length, message: missing.length ? `missing variable names: ${missing.join(", ")}` : "required variable names are present", fix: missing.length ? "Set the variables in this folder's .env or the environment." : undefined });
|
|
717
|
+
}
|
|
718
|
+
for (const command of project.commands)
|
|
719
|
+
if (command.run.includes("docker") || command.serviceType === "compose") {
|
|
720
|
+
const docker = executable("docker", ["--version"], 2000).status === 0;
|
|
721
|
+
const daemon = docker && executable("docker", ["info"], 3000).status === 0;
|
|
722
|
+
checks.push({ name: "docker", ok: daemon, message: daemon ? "Docker executable and daemon are available" : docker ? "Docker executable found but daemon is unavailable" : "Docker executable is unavailable", fix: daemon ? undefined : "Start Docker Desktop or the Docker daemon." });
|
|
723
|
+
break;
|
|
724
|
+
}
|
|
725
|
+
const ports = project.commands.map((c2) => c2.port).filter((p) => Number.isInteger(p));
|
|
726
|
+
const duplicates = [...new Set(ports.filter((p, i) => ports.indexOf(p) !== i))];
|
|
727
|
+
checks.push({ name: "stable-ports", ok: !duplicates.length, message: duplicates.length ? `conflicting configured ports: ${duplicates.join(", ")}` : "configured stable ports are unique", fix: duplicates.length ? "Assign each service a different stable port." : undefined });
|
|
728
|
+
const portFree = options.portFree ?? isPortFree;
|
|
729
|
+
for (const port of [...new Set(ports)])
|
|
730
|
+
if (!await portFree(port))
|
|
731
|
+
checks.push({ name: `stable-port:${port}`, ok: false, message: `port ${port} is already in use`, fix: "Choose another stable port or stop the process using it." });
|
|
732
|
+
for (const command of project.commands) {
|
|
733
|
+
const type = command.serviceType;
|
|
734
|
+
const nativeCheck = command.ready.type === "command" && /^(pg_isready|redis-cli)\b/.exec(command.ready.run)?.[1];
|
|
735
|
+
if (nativeCheck) {
|
|
736
|
+
const tool = nativeCheck;
|
|
737
|
+
const available = executable(tool, ["--version"], 2000).status === 0;
|
|
738
|
+
checks.push({ name: tool, ok: available, message: available ? `${tool} is available` : `${tool} is unavailable for configured ${type} checks`, fix: available ? undefined : `Install ${tool} or use a configured container check.` });
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
} catch (error) {
|
|
742
|
+
checks.push({ name: "config", ok: false, message: error.message, fix: "Fix the config JSON and run doctor again." });
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
return { ok: checks.every((check) => check.ok), checks };
|
|
746
|
+
}
|
|
747
|
+
function envNames(text) {
|
|
748
|
+
return new Set(text.split(/\r?\n/).map((line) => line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1]).filter((v) => Boolean(v)));
|
|
749
|
+
}
|
|
750
|
+
function envAssignments(text) {
|
|
751
|
+
return new Map(text.split(/\r?\n/).map((line) => line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/)).filter((m) => Boolean(m)).map((m) => [m[1], m[2].trim().replace(/^(['"])(.*)\1$/, "$2")]));
|
|
752
|
+
}
|
|
753
|
+
// src/index.ts
|
|
754
|
+
var HELP = `${c.bold("localdeck")} ${c.dim(`v${VERSION}`)} — stable ports, shareable links and logs for local dev servers
|
|
755
|
+
|
|
756
|
+
${c.bold("Usage")}
|
|
757
|
+
localdeck run <name> [--port 4000] [--upstream 5173] [--] <command...>
|
|
758
|
+
localdeck <name> run a command from the project's .localdeck file
|
|
759
|
+
localdeck up [tag|name...] run every .localdeck command (or just the tagged/named ones) in one terminal
|
|
760
|
+
localdeck up --profile <name> run a saved profile and its prerequisites
|
|
761
|
+
localdeck init [--dry-run] [--force] preview/create/replace the project configuration
|
|
762
|
+
localdeck init --name web --command 'your command'
|
|
763
|
+
localdeck commands list configured services (alias: cmds)
|
|
764
|
+
localdeck mcp [--project <id>] connect an AI client over stdio
|
|
765
|
+
localdeck doctor [--json] diagnose setup without starting anything
|
|
766
|
+
localdeck forward [--to-port N] forward 127.0.0.1:80 to 127.0.0.1:7777
|
|
767
|
+
localdeck ps list running services and their ports
|
|
768
|
+
localdeck port <name> print a service's stable port (for scripts)
|
|
769
|
+
localdeck logs <name> [-f] [-n 100] show recent output; -f follows live logs
|
|
770
|
+
localdeck requests <name> [-n 50] show recent proxied HTTP requests
|
|
771
|
+
localdeck share <name> [--password xyz | --public] create a public HTTPS tunnel
|
|
772
|
+
localdeck unshare <name> close a service's public tunnel
|
|
773
|
+
localdeck stop <name> stop a service and its child processes
|
|
774
|
+
localdeck open [name] open the dashboard, or a service, in the browser
|
|
775
|
+
localdeck daemon status|start|stop|run
|
|
776
|
+
localdeck --help | --h | -h show help
|
|
777
|
+
localdeck --version | --v | -v show the installed version
|
|
778
|
+
|
|
779
|
+
${c.bold("How it works")}
|
|
780
|
+
LocalDeck holds a stable port for each service (e.g. 4000) and proxies to
|
|
781
|
+
whatever port your process actually opens — it watches the process and
|
|
782
|
+
finds the port itself, so wrangler, vite, next etc. need no configuration.
|
|
783
|
+
($PORT is also set, and {port} in a command is replaced, for tools that
|
|
784
|
+
want to be told.) Other services and browsers only ever use the stable
|
|
785
|
+
port, so nothing silently moves when a port is busy.
|
|
786
|
+
Dashboard: http://localhost:${DEFAULT_API_PORT}
|
|
787
|
+
|
|
788
|
+
${c.bold(".localdeck")} (JSON, at the project root)
|
|
789
|
+
[
|
|
790
|
+
{ "name": "database", "run": "npm run database" },
|
|
791
|
+
{ "name": "api", "run": "npm run api", "after": "database", "ready": "/health" },
|
|
792
|
+
{ "name": "web", "run": "npm run web", "after": "api" }
|
|
793
|
+
]
|
|
794
|
+
"after" is the beginner-friendly startup order. LocalDeck verifies each
|
|
795
|
+
prerequisite is ready before starting its dependents. Omit "ready" to use
|
|
796
|
+
automatic port readiness; HTTP paths and advanced checks are optional.
|
|
797
|
+
`;
|
|
798
|
+
var defaultDependencies = {
|
|
799
|
+
loadProject,
|
|
800
|
+
ensureDaemon,
|
|
801
|
+
createApi: (port) => new Api(port),
|
|
802
|
+
findDaemon,
|
|
803
|
+
createWebSocket: (url) => new wrapper_default(url),
|
|
804
|
+
runForeground,
|
|
805
|
+
log: (message) => console.log(message),
|
|
806
|
+
warn: (message) => console.warn(message)
|
|
807
|
+
};
|
|
808
|
+
async function main(argv, overrides = {}) {
|
|
809
|
+
const dependencies = { ...defaultDependencies, ...overrides };
|
|
810
|
+
const [cmd, ...rest] = argv;
|
|
811
|
+
switch (cmd) {
|
|
812
|
+
case undefined:
|
|
813
|
+
console.log(HELP);
|
|
814
|
+
await printProjectCommands(false, dependencies);
|
|
815
|
+
return;
|
|
816
|
+
case "help":
|
|
817
|
+
case "-h":
|
|
818
|
+
case "--h":
|
|
819
|
+
case "--help":
|
|
820
|
+
console.log(HELP);
|
|
821
|
+
return;
|
|
822
|
+
case "up":
|
|
823
|
+
return cmdUp(rest, dependencies);
|
|
824
|
+
case "init":
|
|
825
|
+
return cmdInit(rest, dependencies);
|
|
826
|
+
case "mcp":
|
|
827
|
+
return (await import("./mcp-s6gapf6v.js")).runMcp(rest);
|
|
828
|
+
case "doctor":
|
|
829
|
+
return cmdDoctor(rest);
|
|
830
|
+
case "forward":
|
|
831
|
+
return cmdForward(rest);
|
|
832
|
+
case "commands":
|
|
833
|
+
case "cmds":
|
|
834
|
+
return printProjectCommands(true, dependencies);
|
|
835
|
+
case "-v":
|
|
836
|
+
case "--v":
|
|
837
|
+
case "--version":
|
|
838
|
+
console.log(VERSION);
|
|
839
|
+
return;
|
|
840
|
+
case "run":
|
|
841
|
+
return cmdRun(rest, dependencies);
|
|
842
|
+
case "ps":
|
|
843
|
+
case "ls":
|
|
844
|
+
case "ports":
|
|
845
|
+
return cmdPs(dependencies);
|
|
846
|
+
case "port":
|
|
847
|
+
return cmdPort(rest[0]);
|
|
848
|
+
case "logs":
|
|
849
|
+
return cmdLogs(rest, dependencies);
|
|
850
|
+
case "requests":
|
|
851
|
+
return cmdRequests(rest);
|
|
852
|
+
case "share":
|
|
853
|
+
return cmdShare(rest);
|
|
854
|
+
case "unshare":
|
|
855
|
+
return cmdUnshare(rest[0]);
|
|
856
|
+
case "stop":
|
|
857
|
+
return cmdStop(rest[0]);
|
|
858
|
+
case "open":
|
|
859
|
+
return cmdOpen(rest[0]);
|
|
860
|
+
case "daemon":
|
|
861
|
+
return cmdDaemon(rest[0]);
|
|
862
|
+
default: {
|
|
863
|
+
const project = tryLoadProject(dependencies);
|
|
864
|
+
const found = project && findProjectCommand(project, cmd);
|
|
865
|
+
if (found) {
|
|
866
|
+
const remembered = await rememberProject(project, dependencies);
|
|
867
|
+
const selected = startupLayers(project.commands, [found.name]).flat();
|
|
868
|
+
return dependencies.runForeground(selected.map((command, index) => toRunOptions(command, project, remembered, {
|
|
869
|
+
prefix: selected.length > 1,
|
|
870
|
+
color: PALETTE[index % PALETTE.length]
|
|
871
|
+
})));
|
|
872
|
+
}
|
|
873
|
+
const hint = project ? ` Commands in ${path3.basename(project.file)}: ${project.commands.map((p) => p.name).join(", ") || "(none)"}` : "";
|
|
874
|
+
fail(`unknown command "${cmd}". Run localdeck --help.${hint}`);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
function tryLoadProject(dependencies) {
|
|
879
|
+
try {
|
|
880
|
+
return dependencies.loadProject();
|
|
881
|
+
} catch (err) {
|
|
882
|
+
fail(err.message);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
function toRunOptions(p, project, remembered, extra = {}) {
|
|
886
|
+
return {
|
|
887
|
+
name: p.name,
|
|
888
|
+
...remembered ? { project: remembered } : {},
|
|
889
|
+
stablePort: p.port,
|
|
890
|
+
upstreamPort: p.upstream,
|
|
891
|
+
command: shellCommand(p.run),
|
|
892
|
+
displayCommand: p.run,
|
|
893
|
+
cwd: p.cwd ? path3.resolve(project.dir, p.cwd) : project.dir,
|
|
894
|
+
after: p.after,
|
|
895
|
+
ready: p.ready,
|
|
896
|
+
...p.env ? { env: p.env } : {},
|
|
897
|
+
...p.serviceType ? { serviceType: p.serviceType } : {},
|
|
898
|
+
...extra
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
async function rememberProject(project, dependencies) {
|
|
902
|
+
try {
|
|
903
|
+
const daemon = await dependencies.ensureDaemon();
|
|
904
|
+
return await dependencies.createApi(daemon.apiPort).rememberProject(project.file, daemon.controlToken);
|
|
905
|
+
} catch (error) {
|
|
906
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
907
|
+
dependencies.warn(`LocalDeck: could not remember this project: ${message}`);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
async function printProjectCommands(failIfNone, dependencies) {
|
|
912
|
+
const project = tryLoadProject(dependencies);
|
|
913
|
+
if (!project) {
|
|
914
|
+
if (failIfNone)
|
|
915
|
+
fail("no .localdeck file found here or in a parent folder. Create one with: localdeck init");
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
await rememberProject(project, dependencies);
|
|
919
|
+
console.log(`${c.bold("Project commands")} ${c.dim(`(${path3.relative(process.cwd(), project.file) || path3.basename(project.file)})`)}`);
|
|
920
|
+
const rows = project.commands.map((p) => [c.cyan(p.name), p.port ? String(p.port) : c.dim("auto"), p.after.join(",") || "", p.tags.join(",") || "", c.dim(p.run)]);
|
|
921
|
+
console.log(table(rows, ["NAME", "PORT", "AFTER", "TAGS", "RUN"]));
|
|
922
|
+
console.log(c.dim(`
|
|
923
|
+
run one: localdeck <name> · run all: localdeck up · by tag: localdeck up <tag>`));
|
|
924
|
+
}
|
|
925
|
+
var PALETTE = [c.cyan, c.magenta, c.green, c.yellow, c.blue];
|
|
926
|
+
async function cmdUp(args, dependencies) {
|
|
927
|
+
const project = tryLoadProject(dependencies);
|
|
928
|
+
if (!project)
|
|
929
|
+
fail("no .localdeck file found here or in a parent folder. Create one with: localdeck init");
|
|
930
|
+
const profileIndex = args.indexOf("--profile");
|
|
931
|
+
let profile;
|
|
932
|
+
if (profileIndex !== -1) {
|
|
933
|
+
profile = args[profileIndex + 1];
|
|
934
|
+
if (!profile)
|
|
935
|
+
fail("--profile needs a profile name");
|
|
936
|
+
args = args.filter((_, i) => i !== profileIndex && i !== profileIndex + 1);
|
|
937
|
+
}
|
|
938
|
+
const profiles = project.profiles;
|
|
939
|
+
if (profile && (!profiles || !Object.prototype.hasOwnProperty.call(profiles, profile)))
|
|
940
|
+
fail(`unknown profile "${profile}". Available profiles: ${Object.keys(profiles ?? {}).join(", ") || "(none)"}`);
|
|
941
|
+
let selected = project.commands;
|
|
942
|
+
if (profile) {
|
|
943
|
+
const names = new Set(profiles[profile]);
|
|
944
|
+
selected = project.commands.filter((command) => names.has(command.name));
|
|
945
|
+
if (!selected.length)
|
|
946
|
+
fail(`profile "${profile}" selects no configured services`);
|
|
947
|
+
}
|
|
948
|
+
if (args.length) {
|
|
949
|
+
const allowed = new Set(selected);
|
|
950
|
+
const matches = project.commands.filter((p) => args.some((a) => findProjectCommand(project, a) === p || p.tags.includes(a)));
|
|
951
|
+
const outside = matches.filter((p) => !allowed.has(p));
|
|
952
|
+
if (profile && outside.length)
|
|
953
|
+
fail(`service outside profile "${profile}": ${outside.map((p) => p.name).join(", ")}`);
|
|
954
|
+
selected = matches.filter((p) => allowed.has(p));
|
|
955
|
+
const unknown = args.filter((a) => !findProjectCommand(project, a) && !project.commands.some((p) => p.tags.includes(a)));
|
|
956
|
+
if (unknown.length)
|
|
957
|
+
fail(`no command or tag named ${unknown.map((u) => `"${u}"`).join(", ")} in ${path3.basename(project.file)}`);
|
|
958
|
+
}
|
|
959
|
+
if (!selected.length)
|
|
960
|
+
fail("nothing to run");
|
|
961
|
+
selected = startupLayers(project.commands, selected.map((command) => command.name)).flat();
|
|
962
|
+
const remembered = await rememberProject(project, dependencies);
|
|
963
|
+
await dependencies.runForeground(selected.map((p, i) => toRunOptions(p, project, remembered, { prefix: selected.length > 1, color: PALETTE[i % PALETTE.length] })));
|
|
964
|
+
}
|
|
965
|
+
async function cmdInit(args, dependencies) {
|
|
966
|
+
const root = findPackageRoot() ?? process.cwd();
|
|
967
|
+
const existing = [".localdeck", ".localdeck.json", "localdeck.json"].map((f) => path3.join(root, f)).find((f) => fs4.existsSync(f));
|
|
968
|
+
const filename = args.find((a) => a === ".localdeck.json" || a === "localdeck.json") ?? (existing ? path3.basename(existing) : ".localdeck");
|
|
969
|
+
const target = path3.join(root, filename);
|
|
970
|
+
if ((existing && existing !== target || fs4.existsSync(target)) && !args.includes("--force") && !args.includes("--dry-run"))
|
|
971
|
+
fail(`${path3.basename(existing ?? target)} already exists here (use --force to overwrite)`);
|
|
972
|
+
const manual = args.indexOf("--command");
|
|
973
|
+
const nameIndex = args.indexOf("--name");
|
|
974
|
+
const manualCommand = manual >= 0 ? args[manual + 1] : undefined;
|
|
975
|
+
const manualName = nameIndex >= 0 ? args[nameIndex + 1] : undefined;
|
|
976
|
+
if (manual >= 0 && (!manualCommand || manualCommand.startsWith("--")))
|
|
977
|
+
fail("--command requires a command value");
|
|
978
|
+
if (nameIndex >= 0 && (!manualName || manualName.startsWith("--")))
|
|
979
|
+
fail("--name requires a service name");
|
|
980
|
+
if (manualCommand !== undefined && !manualCommand.trim())
|
|
981
|
+
fail("--command must not be empty");
|
|
982
|
+
if (manualCommand && !manualName)
|
|
983
|
+
fail("--command requires --name <service>");
|
|
984
|
+
if (manualName && !/^[a-z0-9][a-z0-9_-]{0,40}$/i.test(manualName))
|
|
985
|
+
fail("--name must start with a letter or number and be at most 41 characters");
|
|
986
|
+
const proposed = manualCommand ? [{ name: manualName.toLowerCase(), run: manualCommand, tags: [], cwd: undefined }] : proposeFromPackageJson();
|
|
987
|
+
if (!proposed.length)
|
|
988
|
+
fail("could not infer any runnable scripts. Add --command '<command>' --name <service>, then run localdeck init again");
|
|
989
|
+
const commands = proposed;
|
|
990
|
+
const json = commands.map((p) => ({ name: p.name, run: p.run, ...p.cwd ? { cwd: p.cwd } : {}, ...p.tags.length ? { tag: p.tags.length === 1 ? p.tags[0] : p.tags } : {} }));
|
|
991
|
+
if (args.includes("--dry-run")) {
|
|
992
|
+
console.log(JSON.stringify({ file: target, commands: json }, null, 2));
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
console.log(table(json.map((command) => [command.name, command.run, command.cwd ?? "."]), ["SERVICE", "COMMAND", "FOLDER"]));
|
|
996
|
+
fs4.writeFileSync(target, JSON.stringify({ commands: json }, null, 2) + `
|
|
997
|
+
`);
|
|
998
|
+
console.log(`${c.green("created")} ${filename} ${c.dim(manualCommand ? "from your command" : "from package.json scripts")}`);
|
|
999
|
+
await printProjectCommands(false, dependencies);
|
|
1000
|
+
console.log(c.dim(`
|
|
1001
|
+
Optional per command: "after": "api" to start in dependency order · "port": 5173 to pin the stable port · "tag": "apps" to start a group.`));
|
|
1002
|
+
}
|
|
1003
|
+
async function cmdDoctor(args) {
|
|
1004
|
+
const report = await doctor();
|
|
1005
|
+
if (!report.ok)
|
|
1006
|
+
process.exitCode = 1;
|
|
1007
|
+
if (args.includes("--json")) {
|
|
1008
|
+
console.log(JSON.stringify(report, null, 2));
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
for (const check of report.checks)
|
|
1012
|
+
console.log(`${check.ok ? c.green("ok") : c.red("fail")} ${check.name}: ${check.message}${check.fix ? ` — ${check.fix}` : ""}`);
|
|
1013
|
+
if (!report.ok)
|
|
1014
|
+
console.log(c.yellow("Repair the failed checks and run localdeck doctor again."));
|
|
1015
|
+
}
|
|
1016
|
+
async function cmdForward(args) {
|
|
1017
|
+
const targetPort = parseForwardArgs(args);
|
|
1018
|
+
let forwarder;
|
|
1019
|
+
try {
|
|
1020
|
+
forwarder = await startForwarder({ targetPort });
|
|
1021
|
+
} catch (error) {
|
|
1022
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
1023
|
+
}
|
|
1024
|
+
console.log(`forwarding http://127.0.0.1:${forwarder.port} → 127.0.0.1:${targetPort} (Ctrl-C to stop)`);
|
|
1025
|
+
await new Promise((resolve) => {
|
|
1026
|
+
function stop() {
|
|
1027
|
+
process.removeListener("SIGINT", stop);
|
|
1028
|
+
process.removeListener("SIGTERM", stop);
|
|
1029
|
+
forwarder.close().then(resolve);
|
|
1030
|
+
}
|
|
1031
|
+
process.once("SIGINT", stop);
|
|
1032
|
+
process.once("SIGTERM", stop);
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
function parseForwardArgs(args) {
|
|
1036
|
+
if (!args.length)
|
|
1037
|
+
return 7777;
|
|
1038
|
+
if (args.length !== 2 || args[0] !== "--to-port")
|
|
1039
|
+
fail("usage: localdeck forward [--to-port N]");
|
|
1040
|
+
const targetPort = Number(args[1]);
|
|
1041
|
+
if (!/^\d+$/.test(args[1]) || !Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535)
|
|
1042
|
+
fail("--to-port needs a port number between 1 and 65535");
|
|
1043
|
+
return targetPort;
|
|
1044
|
+
}
|
|
1045
|
+
async function api() {
|
|
1046
|
+
const d = await findDaemon();
|
|
1047
|
+
if (!d)
|
|
1048
|
+
fail(`LocalDeck daemon is not running. Start a service with: localdeck run <name> -- <command>`);
|
|
1049
|
+
return new Api(d.apiPort);
|
|
1050
|
+
}
|
|
1051
|
+
function need(name) {
|
|
1052
|
+
if (!name)
|
|
1053
|
+
fail("missing service name");
|
|
1054
|
+
return name;
|
|
1055
|
+
}
|
|
1056
|
+
async function cmdRun(args, dependencies) {
|
|
1057
|
+
const opts = {};
|
|
1058
|
+
let name;
|
|
1059
|
+
let i = 0;
|
|
1060
|
+
while (i < args.length) {
|
|
1061
|
+
const a = args[i];
|
|
1062
|
+
if (a === "--") {
|
|
1063
|
+
i++;
|
|
1064
|
+
break;
|
|
1065
|
+
}
|
|
1066
|
+
const m = a.match(/^(?:--(port|upstream)|-(p|u))(?:=(.+))?$/);
|
|
1067
|
+
if (m) {
|
|
1068
|
+
const key = m[1] ?? (m[2] === "p" ? "port" : "upstream");
|
|
1069
|
+
const raw = m[3] ?? args[++i];
|
|
1070
|
+
const n = Number(raw);
|
|
1071
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535)
|
|
1072
|
+
fail(`--${key} needs a port number, got "${raw ?? ""}"`);
|
|
1073
|
+
opts[key] = n;
|
|
1074
|
+
i++;
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
if (!name) {
|
|
1078
|
+
name = a;
|
|
1079
|
+
i++;
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
break;
|
|
1083
|
+
}
|
|
1084
|
+
const command = args.slice(i);
|
|
1085
|
+
if (!command.length) {
|
|
1086
|
+
const project = tryLoadProject(dependencies);
|
|
1087
|
+
const found = project && name ? findProjectCommand(project, name) : undefined;
|
|
1088
|
+
if (found) {
|
|
1089
|
+
const remembered = await rememberProject(project, dependencies);
|
|
1090
|
+
const selected = startupLayers(project.commands, [found.name]).flat();
|
|
1091
|
+
return dependencies.runForeground(selected.map((command2, index) => toRunOptions(command2, project, remembered, {
|
|
1092
|
+
prefix: selected.length > 1,
|
|
1093
|
+
color: PALETTE[index % PALETTE.length],
|
|
1094
|
+
...command2.name === found.name ? { stablePort: opts.port ?? found.port, upstreamPort: opts.upstream ?? found.upstream } : {}
|
|
1095
|
+
})));
|
|
1096
|
+
}
|
|
1097
|
+
fail("nothing to run. Usage: localdeck run <name> [--port 4000] <command...>");
|
|
1098
|
+
}
|
|
1099
|
+
await dependencies.runForeground([{ name: need(name), stablePort: opts.port, upstreamPort: opts.upstream, command }]);
|
|
1100
|
+
}
|
|
1101
|
+
function status(s) {
|
|
1102
|
+
if (s.status === "stopped")
|
|
1103
|
+
return c.dim("stopped");
|
|
1104
|
+
if (!s.upstreamReady)
|
|
1105
|
+
return c.yellow("waiting");
|
|
1106
|
+
return c.green("running");
|
|
1107
|
+
}
|
|
1108
|
+
async function cmdPs(dependencies) {
|
|
1109
|
+
const daemon = await dependencies.findDaemon();
|
|
1110
|
+
if (!daemon)
|
|
1111
|
+
fail(`LocalDeck daemon is not running. Start a service with: localdeck run <name> -- <command>`);
|
|
1112
|
+
const list = await dependencies.createApi(daemon.apiPort).services();
|
|
1113
|
+
if (!list.length) {
|
|
1114
|
+
dependencies.log(c.dim("no services. Start one with: localdeck run <name> -- <command>"));
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
const rows = list.map((s) => [
|
|
1118
|
+
c.cyan(s.name),
|
|
1119
|
+
s.projectName,
|
|
1120
|
+
c.dim(s.key),
|
|
1121
|
+
status(s),
|
|
1122
|
+
String(s.stablePort),
|
|
1123
|
+
s.status === "stopped" ? "-" : `${s.upstreamHost === "::1" ? "[::1]:" : ""}${s.upstreamPort}${s.upstreamSource === "detected" ? c.dim(" ⌕") : ""}`,
|
|
1124
|
+
s.pid ? String(s.pid) : "-",
|
|
1125
|
+
`${s.stats.requests} ${s.stats.serverErrors + s.stats.proxyErrors ? c.red(`(${s.stats.serverErrors + s.stats.proxyErrors} err)`) : ""}`.trim(),
|
|
1126
|
+
s.share ? c.magenta(s.share.url) : "-",
|
|
1127
|
+
ago(s.startedAt),
|
|
1128
|
+
c.dim(s.command ?? "")
|
|
1129
|
+
]);
|
|
1130
|
+
dependencies.log(table(rows, ["NAME", "PROJECT", "KEY", "STATUS", "PORT", "UPSTREAM", "PID", "REQUESTS", "SHARE", "UP", "COMMAND"]));
|
|
1131
|
+
}
|
|
1132
|
+
async function cmdPort(name) {
|
|
1133
|
+
const s = await (await api()).service(need(name));
|
|
1134
|
+
console.log(s.stablePort);
|
|
1135
|
+
}
|
|
1136
|
+
function fmtLog(l) {
|
|
1137
|
+
const t = new Date(l.ts).toLocaleTimeString();
|
|
1138
|
+
const line = l.stream === "stderr" ? c.red(l.line) : l.stream === "system" ? c.dim(l.line) : l.line;
|
|
1139
|
+
return `${c.dim(t)} ${line}`;
|
|
1140
|
+
}
|
|
1141
|
+
async function cmdLogs(args, dependencies) {
|
|
1142
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { follow: { type: "boolean", short: "f" }, lines: { type: "string", short: "n", default: "100" } } });
|
|
1143
|
+
const reference = need(positionals[0]);
|
|
1144
|
+
const daemon = await dependencies.findDaemon();
|
|
1145
|
+
if (!daemon)
|
|
1146
|
+
fail(`LocalDeck daemon is not running. Start a service with: localdeck run <name> -- <command>`);
|
|
1147
|
+
const a = dependencies.createApi(daemon.apiPort);
|
|
1148
|
+
const service = await a.service(reference);
|
|
1149
|
+
for (const l of await a.logs(service.key, Number(values.lines)))
|
|
1150
|
+
dependencies.log(fmtLog(l));
|
|
1151
|
+
if (!values.follow)
|
|
1152
|
+
return;
|
|
1153
|
+
const ws = dependencies.createWebSocket(`ws://127.0.0.1:${daemon.apiPort}/api/events`);
|
|
1154
|
+
ws.on("message", (raw) => {
|
|
1155
|
+
const ev = JSON.parse(raw.toString());
|
|
1156
|
+
if (ev.type === "log" && ev.log.service === service.key)
|
|
1157
|
+
dependencies.log(fmtLog(ev.log));
|
|
1158
|
+
});
|
|
1159
|
+
await new Promise((resolve, reject) => {
|
|
1160
|
+
ws.once("close", resolve);
|
|
1161
|
+
ws.once("error", reject);
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
async function cmdRequests(args) {
|
|
1165
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { lines: { type: "string", short: "n", default: "50" } } });
|
|
1166
|
+
const name = need(positionals[0]);
|
|
1167
|
+
const rows = (await (await api()).requests(name, Number(values.lines))).map((r) => [
|
|
1168
|
+
c.dim(new Date(r.ts).toLocaleTimeString()),
|
|
1169
|
+
r.error ? c.red("ERR") : r.status >= 500 ? c.red(String(r.status)) : r.status >= 400 ? c.yellow(String(r.status)) : c.green(String(r.status)),
|
|
1170
|
+
r.method,
|
|
1171
|
+
r.path,
|
|
1172
|
+
`${r.durationMs}ms`,
|
|
1173
|
+
r.via === "share" ? c.magenta("share") : "",
|
|
1174
|
+
r.error ? c.red(r.error) : ""
|
|
1175
|
+
]);
|
|
1176
|
+
console.log(table(rows, ["TIME", "STATUS", "METHOD", "PATH", "TIME", "VIA", ""]));
|
|
1177
|
+
}
|
|
1178
|
+
async function cmdShare(args) {
|
|
1179
|
+
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { password: { type: "string" }, public: { type: "boolean" } } });
|
|
1180
|
+
if (values.public && values.password !== undefined)
|
|
1181
|
+
fail("cannot combine --password and --public");
|
|
1182
|
+
const name = need(positionals[0]);
|
|
1183
|
+
const password = values.public ? undefined : values.password ?? crypto.randomBytes(6).toString("base64url");
|
|
1184
|
+
process.stdout.write(c.dim("starting tunnel… "));
|
|
1185
|
+
const info = await (await api()).share(name, password);
|
|
1186
|
+
console.log(c.green("ok"));
|
|
1187
|
+
console.log(`
|
|
1188
|
+
${c.bold(info.url)}`);
|
|
1189
|
+
console.log(password ? ` password: ${c.bold(password)}` : ` ${c.yellow("public — anyone with the link can open it")}`);
|
|
1190
|
+
console.log(c.dim(`
|
|
1191
|
+
stays up until: localdeck unshare ${name}`));
|
|
1192
|
+
}
|
|
1193
|
+
async function cmdUnshare(name) {
|
|
1194
|
+
const r = await (await api()).unshare(need(name));
|
|
1195
|
+
console.log(r.ok ? `share for ${name} stopped` : c.dim(`${name} was not shared`));
|
|
1196
|
+
}
|
|
1197
|
+
async function cmdStop(name) {
|
|
1198
|
+
const r = await (await api()).stop(need(name));
|
|
1199
|
+
console.log(r.ok ? `stop sent to ${name}` : c.dim(`${name} is not running`));
|
|
1200
|
+
}
|
|
1201
|
+
async function cmdOpen(name) {
|
|
1202
|
+
const d = await ensureDaemon();
|
|
1203
|
+
let url = `http://localhost:${d.apiPort}`;
|
|
1204
|
+
if (name) {
|
|
1205
|
+
const service = await new Api(d.apiPort).service(name);
|
|
1206
|
+
if (!service.urls[0])
|
|
1207
|
+
fail(`${name} is a database endpoint at ${service.upstreamHost}:${service.upstreamPort}; open it with a database client`);
|
|
1208
|
+
url = service.urls[0];
|
|
1209
|
+
}
|
|
1210
|
+
const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
|
|
1211
|
+
spawn2(opener, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).unref();
|
|
1212
|
+
console.log(url);
|
|
1213
|
+
}
|
|
1214
|
+
async function cmdDaemon(sub) {
|
|
1215
|
+
switch (sub) {
|
|
1216
|
+
case "status": {
|
|
1217
|
+
const d = await findDaemon();
|
|
1218
|
+
console.log(d ? `running · pid ${d.pid} · http://localhost:${d.apiPort} · up ${ago(d.startedAt)} · ${HOME_DIR}` : "not running");
|
|
1219
|
+
return;
|
|
1220
|
+
}
|
|
1221
|
+
case "stop": {
|
|
1222
|
+
const d = await findDaemon();
|
|
1223
|
+
if (!d)
|
|
1224
|
+
return console.log("not running");
|
|
1225
|
+
await new Api(d.apiPort).shutdown();
|
|
1226
|
+
console.log("daemon stopped");
|
|
1227
|
+
return;
|
|
1228
|
+
}
|
|
1229
|
+
case "start": {
|
|
1230
|
+
const d = await ensureDaemon();
|
|
1231
|
+
console.log(`running · pid ${d.pid} · http://localhost:${d.apiPort}`);
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
case "run": {
|
|
1235
|
+
const allowedBrowserOrigins = (process.env.LOCALDECK_DEV_ORIGINS ?? "").split(",").map((origin) => origin.trim()).filter(Boolean);
|
|
1236
|
+
const daemon = await startDaemon({
|
|
1237
|
+
dashboardDir: dashboardDir(),
|
|
1238
|
+
...allowedBrowserOrigins.length > 0 ? { allowedBrowserOrigins } : {}
|
|
1239
|
+
});
|
|
1240
|
+
console.log(`[${new Date().toISOString()}] localdeck daemon v${VERSION} on http://127.0.0.1:${daemon.apiPort} (pid ${process.pid})`);
|
|
1241
|
+
const bye = async () => {
|
|
1242
|
+
await daemon.stop();
|
|
1243
|
+
};
|
|
1244
|
+
process.on("SIGINT", bye);
|
|
1245
|
+
process.on("SIGTERM", bye);
|
|
1246
|
+
await daemon.stopped;
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
default:
|
|
1250
|
+
fail("usage: localdeck daemon status|start|stop|run");
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
async function runCli(argv = process.argv.slice(2)) {
|
|
1254
|
+
try {
|
|
1255
|
+
await main(argv);
|
|
1256
|
+
} catch (error) {
|
|
1257
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
var WRAPPER_IMPORT = Symbol.for("localdeck.cli.wrapper-import");
|
|
1261
|
+
if (__require.main == __require.module && Reflect.get(globalThis, WRAPPER_IMPORT) !== true)
|
|
1262
|
+
await runCli();
|
|
1263
|
+
export {
|
|
1264
|
+
toRunOptions,
|
|
1265
|
+
runCli,
|
|
1266
|
+
parseForwardArgs,
|
|
1267
|
+
main
|
|
1268
|
+
};
|