@anhlp/alp-cli 0.0.0-beta.1 → 0.0.1-beta.10
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/dist/THIRD-PARTY-NOTICES.txt +52 -2
- package/dist/acp/agent.d.ts +11 -3
- package/dist/acp/agent.js +118 -19
- package/dist/acp/main.js +1 -1
- package/dist/acp.js +7898 -2238
- package/dist/alp-dashboard/THIRD-PARTY-NOTICES.txt +3256 -0
- package/dist/alp-dashboard/alp-boundary.json +16 -0
- package/dist/alp-dashboard/apple-touch-icon.png +0 -0
- package/dist/alp-dashboard/assets/TerminalPanel-D8HE9XBX.js +22 -0
- package/dist/alp-dashboard/assets/TerminalPanel-DLuoa74B.css +1 -0
- package/dist/alp-dashboard/assets/highlighter-BnicKQ_d.js +18 -0
- package/dist/alp-dashboard/assets/index-DwqDSiIi.css +1 -0
- package/dist/alp-dashboard/assets/index-YdtH3NBy.js +59 -0
- package/dist/alp-dashboard/favicon-attention.svg +6 -0
- package/dist/alp-dashboard/favicon-running.svg +6 -0
- package/dist/alp-dashboard/favicon.svg +5 -0
- package/dist/alp-dashboard/index.html +20 -0
- package/dist/alp-dashboard.js +10165 -0
- package/dist/alpd.js +39994 -16997
- package/dist/backup.js +2 -2
- package/dist/build-manifest.json +142 -3
- package/dist/cli.js +40 -6
- package/dist/daemon.d.ts +3 -3
- package/dist/daemon.js +16 -7
- package/dist/dashboard-migrate.d.ts +31 -0
- package/dist/dashboard-migrate.js +127 -0
- package/dist/dashboard-service.d.ts +69 -0
- package/dist/dashboard-service.js +141 -0
- package/dist/desktop.d.ts +56 -0
- package/dist/desktop.js +91 -0
- package/dist/interfaces.d.ts +23 -3
- package/dist/interfaces.js +277 -41
- package/dist/library.d.ts +16 -2
- package/dist/library.js +114 -7
- package/dist/paths.d.ts +6 -0
- package/dist/paths.js +4 -1
- package/dist/projects.js +2 -1
- package/dist/roles.d.ts +15 -0
- package/dist/roles.js +16 -0
- package/dist/schedules.d.ts +2 -0
- package/dist/schedules.js +45 -0
- package/dist/self-update.d.ts +151 -0
- package/dist/self-update.js +422 -0
- package/dist/sessions.d.ts +9 -2
- package/dist/sessions.js +67 -13
- package/dist/tasks.js +22 -8
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal.d.ts +13 -0
- package/dist/terminal.js +80 -0
- package/dist/usage.d.ts +1 -1
- package/dist/usage.js +31 -9
- package/package.json +11 -4
- package/src/acp/agent.ts +111 -20
- package/src/backup.js +1 -1
- package/src/cli.js +51 -6
- package/src/daemon.js +18 -9
- package/src/dashboard-migrate.js +152 -0
- package/src/dashboard-service.js +192 -0
- package/src/desktop.js +122 -0
- package/src/interfaces.js +345 -38
- package/src/library.js +108 -9
- package/src/paths.js +9 -1
- package/src/projects.js +3 -1
- package/src/roles.js +26 -0
- package/src/schedules.js +38 -0
- package/src/self-update.js +443 -0
- package/src/sessions.js +60 -16
- package/src/tasks.js +22 -8
- package/src/terminal.js +78 -0
- package/src/usage.js +31 -9
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { lstat, readFile } from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { promisify } from 'node:util';
|
|
8
|
+
import { bootTime, isSameBoot, readLock } from '@anhlp/alp-client/index';
|
|
9
|
+
import { distributionEntry } from './paths.js';
|
|
10
|
+
import { selfEntry } from '@anhlp/alp-core/packaged';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The CLI's side of alp-dashboard (packages/cli/src/dashboard), the service behind `alp dashboard`:
|
|
14
|
+
* where it is, which process owns its lock, and how to stop that process safely. The same proofs
|
|
15
|
+
* apply to what ran under the names from before the rename (t-81b0.5): `integrations/web.lock` and
|
|
16
|
+
* `web.json`, held by alp web of 0.0.1-beta.8 or earlier, or by the Paseo integration from before
|
|
17
|
+
* its own rename.
|
|
18
|
+
*
|
|
19
|
+
* Only a process proven to be the one that took the service's lock is ever signalled, and only
|
|
20
|
+
* with SIGTERM (the CLI's own `--rotate` child aside, which it may time out): the lock and the
|
|
21
|
+
* service's `<name>.json` name the same pid, both files are the user's, the lock is
|
|
22
|
+
* from this boot, the pid answers signal 0 (so it is the user's own process), and that process
|
|
23
|
+
* started no later than the lock was written (so the pid was not reused). Anything else is reported
|
|
24
|
+
* and left alone. A stopped owner releases the lock; one that died holding it leaves it to the next
|
|
25
|
+
* acquire, which reclaims it only on proof of death (the integration lock protocol, t-e148).
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const execFileAsync = promisify(execFile);
|
|
29
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
30
|
+
|
|
31
|
+
/** The alp-dashboard service script beside this CLI; a clear error when this CLI was built without it. */
|
|
32
|
+
export function dashboardScript() {
|
|
33
|
+
const entry = fileURLToPath(distributionEntry('alp-dashboard.js'));
|
|
34
|
+
if (!existsSync(entry)) throw new Error(`alp dashboard is not built: ${entry} is missing. Build the CLI (npm run build in the ALP checkout) or reinstall ALP.`);
|
|
35
|
+
return entry;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What starts alp-dashboard: its script under Node (named through app/current in the ALP bundle). */
|
|
39
|
+
export const dashboardEntry = () => selfEntry(dashboardScript());
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @typedef {{ lock: string, info: string, app: string, what: string }} Service
|
|
43
|
+
* The integration lock's name, the file the service publishes, the `app` it writes there, and what
|
|
44
|
+
* messages call it.
|
|
45
|
+
*/
|
|
46
|
+
/** @type {Service} */
|
|
47
|
+
export const DASHBOARD = Object.freeze({ lock: 'dashboard', info: 'dashboard.json', app: 'alp-dashboard', what: 'alp dashboard' });
|
|
48
|
+
/** alp web as 0.0.1-beta.8 and earlier ran it (and, before that, the Paseo integration). @type {Service} */
|
|
49
|
+
export const LEGACY_WEB = Object.freeze({ lock: 'web', info: 'web.json', app: 'alp-web', what: 'alp web from before its rename to alp dashboard' });
|
|
50
|
+
|
|
51
|
+
const readJson = async file => JSON.parse(await readFile(file, 'utf8'));
|
|
52
|
+
|
|
53
|
+
/** When `pid` started and elapsed seconds from ps, or undefined when ps cannot say. @param {number} pid */
|
|
54
|
+
async function processTimes(pid) {
|
|
55
|
+
try {
|
|
56
|
+
const { stdout } = await execFileAsync('ps', ['-o', 'etime=', '-p', String(pid)], { encoding: 'utf8', timeout: 5_000 });
|
|
57
|
+
// [[dd-]hh:]mm:ss
|
|
58
|
+
const match = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(stdout);
|
|
59
|
+
if (!match) return undefined;
|
|
60
|
+
const [, days = '0', hours = '0', minutes, seconds] = match;
|
|
61
|
+
const elapsed = ((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds);
|
|
62
|
+
return { started: Date.now() - elapsed * 1000, elapsed };
|
|
63
|
+
} catch { return undefined; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The process that owns `service`'s lock, if it is proven safe to stop; else why not. `kind` says
|
|
68
|
+
* whether waiting can help: `transient` (an owner still starting has not published its file yet),
|
|
69
|
+
* `foreign` (proven not to be the integration: another user's, another boot's, or a reused pid) or
|
|
70
|
+
* `unknown` (it cannot be proven either way, for example without ps or on Windows).
|
|
71
|
+
*
|
|
72
|
+
* The reuse proof compares the lock's creation time with the process's start from ps: when
|
|
73
|
+
* `startedUptime` is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
|
|
74
|
+
* For legacy locks, wall-clock `startedAt` is compared.
|
|
75
|
+
* @param {string} home @param {Service} [service]
|
|
76
|
+
* @returns {Promise<{ pid: number, app: unknown } | { reason: string, alive: boolean, kind?: 'transient' | 'foreign' | 'unknown' }>}
|
|
77
|
+
*/
|
|
78
|
+
export async function serviceOwner(home, service = DASHBOARD) {
|
|
79
|
+
const lockFile = path.join(home, 'integrations', `${service.lock}.lock`);
|
|
80
|
+
const infoFile = path.join(home, service.info);
|
|
81
|
+
let lock, lockInfo;
|
|
82
|
+
try { lockInfo = await lstat(lockFile); lock = await readJson(lockFile); } catch { return { reason: `${lockFile} is missing or unreadable`, alive: false }; }
|
|
83
|
+
if (!lockInfo.isFile() || !Number.isSafeInteger(lock?.pid) || lock.pid <= 0 || typeof lock.bootTime !== 'number' || !Number.isFinite(Date.parse(lock.startedAt))) {
|
|
84
|
+
return { reason: `${lockFile} is not a complete integration lock`, alive: false };
|
|
85
|
+
}
|
|
86
|
+
const { pid } = lock;
|
|
87
|
+
try { process.kill(pid, 0); } catch (error) {
|
|
88
|
+
if (error?.code === 'ESRCH') return { reason: `its pid ${pid} has exited`, alive: false };
|
|
89
|
+
if (error?.code === 'EPERM') return { reason: `pid ${pid} belongs to another user`, alive: true, kind: 'foreign' };
|
|
90
|
+
return { reason: `pid ${pid} cannot be signalled (${error?.code ?? error})`, alive: true, kind: 'unknown' };
|
|
91
|
+
}
|
|
92
|
+
const refuse = (/** @type {string} */ reason, /** @type {'transient' | 'foreign' | 'unknown'} */ kind) => ({ reason, alive: true, kind });
|
|
93
|
+
if (process.platform === 'win32') return refuse('alp does not stop it on Windows', 'unknown');
|
|
94
|
+
const uid = process.getuid?.();
|
|
95
|
+
if (lockInfo.uid !== uid) return refuse('its lock is not yours', 'foreign');
|
|
96
|
+
if (!isSameBoot(lock)) return refuse('its lock is from another boot', 'foreign');
|
|
97
|
+
if (pid === process.pid || pid === (await readLock(home).catch(() => undefined))?.pid) return refuse(`pid ${pid} is not an integration`, 'foreign');
|
|
98
|
+
const times = await processTimes(pid);
|
|
99
|
+
if (times === undefined) return refuse(`the start time of pid ${pid} is unknown`, 'unknown');
|
|
100
|
+
// When startedUptime is recorded, monotonic uptime comparison prevents clock step vulnerabilities.
|
|
101
|
+
// Otherwise, fallback to wall-clock startedAt comparison with 2s tolerance for ps resolution.
|
|
102
|
+
const isReused = typeof lock.startedUptime === 'number'
|
|
103
|
+
? (Math.floor(os.uptime()) - times.elapsed) > lock.startedUptime + 2
|
|
104
|
+
: times.started > Date.parse(lock.startedAt) + 2_000;
|
|
105
|
+
if (isReused) return refuse(`pid ${pid} started after the lock was written (a reused pid)`, 'foreign');
|
|
106
|
+
// The lock's owner; its published file must name it too (an owner still starting has not written it yet).
|
|
107
|
+
let info, infoStat;
|
|
108
|
+
try { infoStat = await lstat(infoFile); info = await readJson(infoFile); } catch { return refuse(`${infoFile} is missing or unreadable`, 'transient'); }
|
|
109
|
+
if (info?.pid !== pid) return refuse(`${infoFile} names another process than the lock`, 'transient');
|
|
110
|
+
if (!infoStat.isFile() || infoStat.uid !== uid) return refuse(`${infoFile} is not yours`, 'foreign');
|
|
111
|
+
return { pid, app: info.app };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Sends SIGTERM to a proven owner and waits for it to exit.
|
|
116
|
+
* @param {number} pid @param {string} what @param {number} [timeoutMs]
|
|
117
|
+
*/
|
|
118
|
+
async function terminate(pid, what, timeoutMs = 20_000) {
|
|
119
|
+
try { process.kill(pid, 'SIGTERM'); } catch (error) { if (error?.code === 'ESRCH') return; throw error; }
|
|
120
|
+
const deadline = Date.now() + timeoutMs;
|
|
121
|
+
while (Date.now() < deadline) {
|
|
122
|
+
try { process.kill(pid, 0); } catch (error) { if (error?.code === 'ESRCH') return; }
|
|
123
|
+
await sleep(100);
|
|
124
|
+
}
|
|
125
|
+
throw new Error(`${what} (pid ${pid}) did not stop within ${timeoutMs / 1000} s of SIGTERM; stop it, then run the command again`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const PASEO_BEFORE_RENAME = 'The Paseo integration from before its rename';
|
|
129
|
+
|
|
130
|
+
/** What a proven owner of `service`'s lock is, by the `app` its file names. @param {Service} service @param {unknown} app */
|
|
131
|
+
const ownerName = (service, app) => app === service.app || service === DASHBOARD ? service.what : PASEO_BEFORE_RENAME;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Stops whatever runs as `service` (alp dashboard; for LEGACY_WEB, alp web from before the rename or
|
|
135
|
+
* the Paseo integration from before its own), waiting up to `timeoutMs` for a starting owner to
|
|
136
|
+
* publish what proves it. Resolves with the pid it stopped, or undefined once no live process owns
|
|
137
|
+
* the lock; refuses at once an owner that is foreign or cannot be proven.
|
|
138
|
+
* @param {string} home @param {number} [timeoutMs] @param {Service} [service]
|
|
139
|
+
*/
|
|
140
|
+
export async function stopService(home, timeoutMs = 30_000, service = DASHBOARD) {
|
|
141
|
+
const deadline = Date.now() + timeoutMs;
|
|
142
|
+
for (;;) {
|
|
143
|
+
const owner = await serviceOwner(home, service);
|
|
144
|
+
if ('pid' in owner) { await terminate(owner.pid, ownerName(service, owner.app)); return owner.pid; }
|
|
145
|
+
if (!owner.alive) return undefined;
|
|
146
|
+
// Only an owner still starting can become provable; waiting changes nothing else.
|
|
147
|
+
if (owner.kind !== 'transient' || Date.now() >= deadline) throw new Error(`${refusal(home, service)} (${owner.reason}); stop it, then run the command again`);
|
|
148
|
+
await sleep(200);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The opening of the message for a lock held by a process alp would not stop. @param {string} home @param {Service} [service] */
|
|
153
|
+
export function refusal(home, service = DASHBOARD) {
|
|
154
|
+
const lock = path.join(home, 'integrations', `${service.lock}.lock`);
|
|
155
|
+
return service === DASHBOARD
|
|
156
|
+
? `${lock} is held by a process that alp cannot prove is alp dashboard, so it was left running`
|
|
157
|
+
: `${lock} is held by a process that alp cannot prove is ${service.what} or the Paseo integration from before its rename, so it was left running`;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Probes whether the published dashboard URL is live and answering requests.
|
|
162
|
+
* Accepts only loopback HTTP/HTTPS addresses.
|
|
163
|
+
* @param {string | undefined} url
|
|
164
|
+
* @param {number} [timeoutMs]
|
|
165
|
+
*/
|
|
166
|
+
export async function isDashboardReady(url, timeoutMs = 1_000) {
|
|
167
|
+
if (typeof url !== 'string' || !url) return false;
|
|
168
|
+
try {
|
|
169
|
+
const parsed = new URL(url);
|
|
170
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
|
|
171
|
+
if (!['127.0.0.1', 'localhost', '::1', '[::1]'].includes(parsed.hostname)) return false;
|
|
172
|
+
const res = await fetch(parsed.href, { signal: AbortSignal.timeout(timeoutMs) });
|
|
173
|
+
return typeof res.status === 'number' && res.status > 0;
|
|
174
|
+
} catch {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Whether the published file is genuinely claimed by a live alp-dashboard process.
|
|
181
|
+
* If the process is proven foreign (e.g. a reused PID or from another boot) or
|
|
182
|
+
* the URL does not answer HTTP requests, it is never claimed.
|
|
183
|
+
* @param {any} published
|
|
184
|
+
* @param {number | undefined} lockPid
|
|
185
|
+
* @param {any} held
|
|
186
|
+
* @param {number} [timeoutMs]
|
|
187
|
+
*/
|
|
188
|
+
export async function isServiceClaimed(published, lockPid, held, timeoutMs = 1_000) {
|
|
189
|
+
if (published?.app !== DASHBOARD.app || published.pid !== lockPid) return false;
|
|
190
|
+
if (held?.kind === 'foreign') return false;
|
|
191
|
+
return isDashboardReady(published.url, timeoutMs);
|
|
192
|
+
}
|
package/src/desktop.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { UsageError } from './usage.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* alp desktop (t-81b0.5): opens ALP's desktop app (apps/desktop, an Electron shell for macOS). The
|
|
9
|
+
* app is looked for, in order:
|
|
10
|
+
* 1. ALP.app in /Applications, then in ~/Applications (macOS), opened with `open`. Only a bundle
|
|
11
|
+
* whose CFBundleIdentifier is DESKTOP_BUNDLE_ID counts: another app of that name (an older ALP
|
|
12
|
+
* desktop app, say) is skipped with a one-line message and the lookup goes on;
|
|
13
|
+
* 2. a checkout named by ALP_DESKTOP_CHECKOUT (the repository root, or its apps/desktop), whose
|
|
14
|
+
* app is built (`bun install && bun run build` in apps/desktop), run with its own Electron;
|
|
15
|
+
* 3. neither: how to get it, and exit 1.
|
|
16
|
+
* Nothing secret passes here: the app asks `alp dashboard --print` for its address itself.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The bundle id of the packaged app (apps/desktop/electron-builder.yml, appId). */
|
|
20
|
+
export const DESKTOP_BUNDLE_ID = 'com.anhlp.alp.shell';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The CFBundleIdentifier of the app bundle at `app`, or undefined when it cannot be read. An XML
|
|
24
|
+
* Info.plist (what electron-builder writes) is read directly; any other form through plutil.
|
|
25
|
+
* @param {string} app
|
|
26
|
+
* @returns {Promise<string | undefined>}
|
|
27
|
+
*/
|
|
28
|
+
export async function readBundleId(app) {
|
|
29
|
+
const plist = path.join(app, 'Contents', 'Info.plist');
|
|
30
|
+
const text = await readFile(plist, 'utf8').catch(() => undefined);
|
|
31
|
+
if (text === undefined) return undefined;
|
|
32
|
+
if (text.trimStart().startsWith('<')) {
|
|
33
|
+
const match = /<key>CFBundleIdentifier<\/key>\s*<string>([^<]*)<\/string>/.exec(text);
|
|
34
|
+
return match ? match[1].trim() : undefined;
|
|
35
|
+
}
|
|
36
|
+
return new Promise(resolve => {
|
|
37
|
+
execFile('/usr/bin/plutil', ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', plist], (error, stdout) => resolve(error ? undefined : stdout.trim() || undefined));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param {string} file */
|
|
42
|
+
const isDirectory = file => stat(file).then(info => info.isDirectory(), () => false);
|
|
43
|
+
/** @param {string} file */
|
|
44
|
+
const isFile = file => stat(file).then(info => info.isFile(), () => false);
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The desktop app's directory in a checkout: `dir` itself or `dir/apps/desktop`, whichever holds the
|
|
48
|
+
* package named alp-desktop.
|
|
49
|
+
* @param {string} dir
|
|
50
|
+
*/
|
|
51
|
+
async function desktopPackage(dir) {
|
|
52
|
+
for (const candidate of [path.join(dir, 'apps', 'desktop'), dir]) {
|
|
53
|
+
const manifest = await readFile(path.join(candidate, 'package.json'), 'utf8').then(text => { try { return JSON.parse(text); } catch { return undefined; } }, () => undefined);
|
|
54
|
+
if (manifest?.name === 'alp-desktop') return candidate;
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Where the app is and how to start it. Exported for tests.
|
|
61
|
+
* `onSkip` hears about each ALP.app passed over because its bundle id is not DESKTOP_BUNDLE_ID.
|
|
62
|
+
* @param {{ platform?: NodeJS.Platform, home?: string, env?: NodeJS.ProcessEnv, applications?: string[], onSkip?: (message: string) => void }} [options]
|
|
63
|
+
* @returns {Promise<{ kind: 'app', app: string, command: string, args: string[] }
|
|
64
|
+
* | { kind: 'checkout', dir: string, command: string, args: string[] }
|
|
65
|
+
* | { kind: 'missing', reason?: string }>}
|
|
66
|
+
*/
|
|
67
|
+
export async function resolveDesktop({ platform = process.platform, home = os.homedir(), env = process.env, applications, onSkip = () => {} } = {}) {
|
|
68
|
+
if (platform === 'darwin') {
|
|
69
|
+
for (const directory of applications ?? ['/Applications', path.join(home, 'Applications')]) {
|
|
70
|
+
const app = path.join(directory, 'ALP.app');
|
|
71
|
+
if (!(await isDirectory(app))) continue;
|
|
72
|
+
const id = await readBundleId(app);
|
|
73
|
+
if (id === DESKTOP_BUNDLE_ID) return { kind: 'app', app, command: 'open', args: [app] };
|
|
74
|
+
onSkip(`Skipped ${app}: its bundle id is ${id ? JSON.stringify(id) : 'unreadable'}, not ${DESKTOP_BUNDLE_ID} (ALP's desktop app).`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const checkout = env.ALP_DESKTOP_CHECKOUT;
|
|
78
|
+
if (!checkout) return { kind: 'missing' };
|
|
79
|
+
const dir = await desktopPackage(path.resolve(checkout));
|
|
80
|
+
if (!dir) return { kind: 'missing', reason: `ALP_DESKTOP_CHECKOUT=${checkout} is not an ALP checkout: neither it nor its apps/desktop holds the alp-desktop package.` };
|
|
81
|
+
const electron = path.join(dir, 'node_modules', '.bin', platform === 'win32' ? 'electron.cmd' : 'electron');
|
|
82
|
+
if (!(await isFile(electron)) || !(await isFile(path.join(dir, 'dist', 'main.cjs')))) {
|
|
83
|
+
return { kind: 'missing', reason: `The desktop app in ${dir} is not built: run \`bun install && bun run build\` there, then run alp desktop again.` };
|
|
84
|
+
}
|
|
85
|
+
return { kind: 'checkout', dir, command: electron, args: [dir] };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const INSTRUCTIONS = `ALP's desktop app is not installed.
|
|
89
|
+
- Put ALP.app in /Applications (or ~/Applications), or
|
|
90
|
+
- point ALP_DESKTOP_CHECKOUT at an ALP checkout whose apps/desktop is built:
|
|
91
|
+
cd <checkout>/apps/desktop && bun install && bun run build
|
|
92
|
+
ALP_DESKTOP_CHECKOUT=<checkout> alp desktop
|
|
93
|
+
Meanwhile, \`alp dashboard\` opens ALP in your browser.`;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* @param {string[]} args
|
|
97
|
+
* @param {{ resolve?: typeof resolveDesktop, launch?: (command: string, args: string[], env: NodeJS.ProcessEnv) => Promise<void> }} [deps]
|
|
98
|
+
*/
|
|
99
|
+
export async function desktopCommand(args, { resolve = resolveDesktop, launch = start } = {}) {
|
|
100
|
+
if (args.length) throw new UsageError();
|
|
101
|
+
const found = await resolve({ onSkip: message => console.error(message) });
|
|
102
|
+
if (found.kind === 'missing') {
|
|
103
|
+
if (found.reason) console.error(found.reason);
|
|
104
|
+
console.error(INSTRUCTIONS);
|
|
105
|
+
process.exitCode = 1;
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const env = { ...process.env };
|
|
109
|
+
// An agent's shell (and Electron's own tools) may set it; Electron would then run as plain Node.
|
|
110
|
+
delete env.ELECTRON_RUN_AS_NODE;
|
|
111
|
+
await launch(found.command, found.args, env);
|
|
112
|
+
console.log(found.kind === 'app' ? `Opened ${found.app}.` : `Started the desktop app from ${found.dir}.`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Starts `command` detached, resolving once it spawned. @param {string} command @param {string[]} args @param {NodeJS.ProcessEnv} env */
|
|
116
|
+
function start(command, args, env) {
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true, env });
|
|
119
|
+
child.once('error', reject);
|
|
120
|
+
child.once('spawn', () => { child.unref(); resolve(); });
|
|
121
|
+
});
|
|
122
|
+
}
|